{"size":7119,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":2.0,"content":"\/\/----------------------------------------------------------------------------\n\/\/\n\/\/ TSDuck - The MPEG Transport Stream Toolkit\n\/\/ Copyright (c) 2005-2020, Thierry Lelegard\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/    this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/    notice, this list of conditions and the following disclaimer in the\n\/\/    documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n\/\/ THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/----------------------------------------------------------------------------\n\n#include \"tsStreamEventDescriptor.h\"\n#include \"tsDescriptor.h\"\n#include \"tsTablesDisplay.h\"\n#include \"tsTablesFactory.h\"\n#include \"tsxmlElement.h\"\nTSDUCK_SOURCE;\n\n#define MY_XML_NAME u\"stream_event_descriptor\"\n#define MY_DID ts::DID_STREAM_EVENT\n#define MY_STD ts::STD_MPEG\n\nTS_XML_DESCRIPTOR_FACTORY(ts::StreamEventDescriptor, MY_XML_NAME);\nTS_ID_DESCRIPTOR_FACTORY(ts::StreamEventDescriptor, ts::EDID::Standard(MY_DID));\nTS_FACTORY_REGISTER(ts::StreamEventDescriptor::DisplayDescriptor, ts::EDID::Standard(MY_DID));\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Constructors\n\/\/----------------------------------------------------------------------------\n\nts::StreamEventDescriptor::StreamEventDescriptor(uint16_t id, uint64_t npt) :\n    AbstractDescriptor(MY_DID, MY_XML_NAME, MY_STD, 0),\n    event_id(id),\n    event_NPT(npt),\n    private_data()\n{\n    _is_valid = true;\n}\n\nts::StreamEventDescriptor::StreamEventDescriptor(DuckContext& duck, const Descriptor& desc) :\n    StreamEventDescriptor()\n{\n    deserialize(duck, desc);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Serialization\n\/\/----------------------------------------------------------------------------\n\nvoid ts::StreamEventDescriptor::serialize(DuckContext& duck, Descriptor& desc) const\n{\n    ByteBlockPtr bbp(serializeStart());\n    bbp->appendUInt16(event_id);\n    bbp->appendUInt64(TS_UCONST64(0xFFFFFFFE00000000) | event_NPT);\n    bbp->append(private_data);\n    serializeEnd(desc, bbp);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Deserialization\n\/\/----------------------------------------------------------------------------\n\nvoid ts::StreamEventDescriptor::deserialize(DuckContext& duck, const Descriptor& desc)\n{\n    _is_valid = desc.isValid() && desc.tag() == _tag && desc.payloadSize() >= 10;\n\n    if (_is_valid) {\n        const uint8_t* data = desc.payload();\n        size_t size = desc.payloadSize();\n        event_id = GetUInt16(data);\n        event_NPT = GetUInt64(data + 2) & TS_UCONST64(0x00000001FFFFFFFF);\n        private_data.copy (data + 10, size - 10);\n    }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Check if all bytes in private part are ASCII characters.\n\/\/----------------------------------------------------------------------------\n\nbool ts::StreamEventDescriptor::asciiPrivate() const\n{\n    bool ascii = !private_data.empty();\n    for (size_t i = 0; ascii && i < private_data.size(); ++i) {\n        ascii = private_data[i] >= 0x20 && private_data[i] < 0x80;\n    }\n    return ascii;\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Static method to display a descriptor.\n\/\/----------------------------------------------------------------------------\n\nvoid ts::StreamEventDescriptor::DisplayDescriptor(TablesDisplay& display, DID did, const uint8_t* data, size_t size, int indent, TID tid, PDS pds)\n{\n    std::ostream& strm(display.duck().out());\n\n    if (size >= 10) {\n        const std::string margin(indent, ' ');\n\n        \/\/ Extract common part\n        const uint16_t id = GetUInt16(data);\n        const uint64_t npt = GetUInt64(data + 2) & TS_UCONST64(0x00000001FFFFFFFF);\n        data += 10; size -= 10;\n\n        strm << margin << UString::Format(u\"Event id: 0x%X (%d), NPT: 0x%09X (%d)\", {id, id, npt, npt}) << std::endl;\n\n        \/\/ Private part.\n        if (size > 0) {\n            strm << margin << \"Private data:\" << std::endl\n                 << UString::Dump(data, size, UString::HEXA | UString::ASCII | UString::OFFSET, indent);\n            data += size; size = 0;\n        }\n    }\n\n    display.displayExtraData(data, size, indent);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ XML serialization\n\/\/----------------------------------------------------------------------------\n\nvoid ts::StreamEventDescriptor::buildXML(DuckContext& duck, xml::Element* root) const\n{\n    root->setIntAttribute(u\"event_id\", event_id, true);\n    root->setIntAttribute(u\"event_NPT\", event_NPT, true);\n    if (!private_data.empty()) {\n        if (asciiPrivate()) {\n            root->addElement(u\"private_text\")->addText(UString::FromUTF8(reinterpret_cast<const char*>(private_data.data()), private_data.size()));\n        }\n        else {\n            root->addElement(u\"private_data\")->addHexaText(private_data);\n        }\n    }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ XML deserialization\n\/\/----------------------------------------------------------------------------\n\nvoid ts::StreamEventDescriptor::fromXML(DuckContext& duck, const xml::Element* element)\n{\n    UString text;\n\n    _is_valid =\n        checkXMLName(element) &&\n        element->getIntAttribute<uint16_t>(event_id, u\"event_id\", true, 0, 0x0000, 0xFFFF) &&\n        element->getIntAttribute<uint64_t>(event_NPT, u\"event_NPT\", true, 0, 0, TS_UCONST64(0x00000001FFFFFFFF)) &&\n        element->getHexaTextChild(private_data, u\"private_data\", false, 0, MAX_DESCRIPTOR_SIZE - 10) &&\n        element->getTextChild(text, u\"private_text\", false, false, UString(), 0, MAX_DESCRIPTOR_SIZE - 10);\n\n    if (_is_valid && !text.empty()) {\n        if (private_data.empty()) {\n            private_data.appendUTF8(text);\n        }\n        else {\n            element->report().error(u\"In <%s> at line %d, <private_data> and <private_text> are mutually exclusive\", {element->name(), element->lineNumber()});\n        }\n    }\n}\n","avg_line_length":38.4810810811,"max_line_length":159,"alphanum_fraction":0.5673549656,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1783,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":13.0,"content":"#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <queue>\n#include <string>\n#include <iostream>\n#include <sstream>\n\n#define MAXN 500\n\nusing namespace std;\n\nint visited[ MAXN + 1 ], par[ MAXN + 1 ], flow[ MAXN + 1 ][ MAXN + 1 ], cap[ MAXN + 1 ][ MAXN + 1 ];\n\nbool bfs( int s, int t ) {\n  memset( par, 0, sizeof( par ) );\n  memset( visited, 0, sizeof( visited ) );\n  queue< int > Q;\n  Q.push( s );\n  visited[ s ] = true;\n  par[ s ] = -1;\n  while( !Q.empty() ) {\n    int u = Q.front();\n    Q.pop();\n    for( int i = 0; i < MAXN; i++ ) {\n      if( !visited[ i ] && cap[ u ][ i ] - flow[ u ][ i ] > 0 ) {\n        visited[ i ] = true;\n        par[ i ] = u;\n        Q.push( i );\n      }\n    }\n  }\n  return visited[ t ];\n}\n\nint maxflow( int s, int t ) {\n  int ans = 0;\n  while( bfs( s, t ) ) {\n    int aug = 250;\n    for( int i = t; i != s; i = par[ i ] ) {\n      aug = min( aug, cap[ par[ i ] ][ i ] - flow[ par[ i ] ][ i ] );\n    }\n    ans += aug;\n    for( int i = t; i != s; i = par[ i ] ) {\n      flow[ par[ i ] ][ i ] += aug;\n      flow[ i ][ par[ i ] ] -= aug;\n    }\n  }\n  return ans;\n}\n\nint main( void ) {\n    int N, x, y;\n    scanf(\"%d\\n\", &N );\n    for( int i = 1; i <= N; i++ ) {\n        int y;\n        for( int j = 1; j <= N; j++ ) cap[ i ][ j + 205 ] = 1;\n        cap[ i ][ i + 205 ] = 0;\n        int enterNumber;\n        std::string line;\n        getline(std::cin, line);\n        std::istringstream iss(line);\n        while (iss >> enterNumber)\n        {\n            cap[ i ][ enterNumber + 1 + 205 ] = 0;\n        }\n    }\n    for( int i = 0; i < 205; i++ ) {\n      cap[ 420 ][ i ] = 1;\n      cap[ i + 205 ][ 421 ] = 1;\n    }\n    printf(\"%d\\n\", N - maxflow( 420, 421 ) );\n    memset( flow, 0, sizeof( flow ) );\n    memset( cap, 0, sizeof( cap ) );\n  return 0;\n}\n","avg_line_length":23.1558441558,"max_line_length":100,"alphanum_fraction":0.4391475042,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2606,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":28.0,"content":"\/* TEMPLATE GENERATED TESTCASE FILE\r\nFilename: CWE590_Free_Memory_Not_on_Heap__delete_int_static_41.cpp\r\nLabel Definition File: CWE590_Free_Memory_Not_on_Heap__delete.nonpointer.label.xml\r\nTemplate File: sources-sink-41.tmpl.cpp\r\n*\/\r\n\/*\r\n * @description\r\n * CWE: 590 Free Memory Not on Heap\r\n * BadSource: static Data buffer is declared static on the stack\r\n * GoodSource: Allocate memory on the heap\r\n * Sink:\r\n *    BadSink : Print then free data\r\n * Flow Variant: 41 Data flow: data passed as an argument from one function to another in the same source file\r\n *\r\n * *\/\r\n\r\n#include \"std_testcase.h\"\r\n\r\n#include <wchar.h>\r\n\r\nnamespace CWE590_Free_Memory_Not_on_Heap__delete_int_static_41\r\n{\r\n\r\n#ifndef OMITBAD\r\n\r\nvoid badSink(int * data)\r\n{\r\n    printIntLine(*data);\r\n    \/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack *\/\r\n    delete data;\r\n}\r\n\r\nvoid bad()\r\n{\r\n    int * data;\r\n    data = NULL; \/* Initialize data *\/\r\n    {\r\n        \/* FLAW: data is allocated on the stack and deallocated in the BadSink *\/\r\n        static int dataBuffer;\r\n        dataBuffer = 5;\r\n        data = &dataBuffer;\r\n    }\r\n    badSink(data);\r\n}\r\n\r\n#endif \/* OMITBAD *\/\r\n\r\n#ifndef OMITGOOD\r\n\r\nvoid goodG2BSink(int * data)\r\n{\r\n    printIntLine(*data);\r\n    \/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack *\/\r\n    delete data;\r\n}\r\n\r\n\/* goodG2B uses the GoodSource with the BadSink *\/\r\nstatic void goodG2B()\r\n{\r\n    int * data;\r\n    data = NULL; \/* Initialize data *\/\r\n    {\r\n        \/* FIX: data is allocated on the heap and deallocated in the BadSink *\/\r\n        int * dataBuffer = new int;\r\n        *dataBuffer = 5;\r\n        data = dataBuffer;\r\n    }\r\n    goodG2BSink(data);\r\n}\r\n\r\nvoid good()\r\n{\r\n    goodG2B();\r\n}\r\n\r\n#endif \/* OMITGOOD *\/\r\n\r\n} \/* close namespace *\/\r\n\r\n\/* Below is the main(). It is only used when building this testcase on\r\n   its own for testing or for building a binary to use in testing binary\r\n   analysis tools. It is not used when compiling all the testcases as one\r\n   application, which is how source code analysis tools are tested. *\/\r\n\r\n#ifdef INCLUDEMAIN\r\n\r\nusing namespace CWE590_Free_Memory_Not_on_Heap__delete_int_static_41; \/* so that we can use good and bad easily *\/\r\n\r\nint main(int argc, char * argv[])\r\n{\r\n    \/* seed randomness *\/\r\n    srand( (unsigned)time(NULL) );\r\n#ifndef OMITGOOD\r\n    printLine(\"Calling good()...\");\r\n    good();\r\n    printLine(\"Finished good()\");\r\n#endif \/* OMITGOOD *\/\r\n#ifndef OMITBAD\r\n    printLine(\"Calling bad()...\");\r\n    bad();\r\n    printLine(\"Finished bad()\");\r\n#endif \/* OMITBAD *\/\r\n    return 0;\r\n}\r\n\r\n#endif\r\n","avg_line_length":24.3551401869,"max_line_length":115,"alphanum_fraction":0.6508058327,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3055,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/**\n * @file    arrays_example1.cpp\n * @brief   arrays create example\n * @author  Sarah Keating\n *\n * <!--------------------------------------------------------------------------\n * This file is part of libSBML.  Please visit http:\/\/sbml.org for more\n * information about SBML, and the latest version of libSBML.\n *\n * Copyright (C) 2009-2013 jointly by the following organizations:\n *     1. California Institute of Technology, Pasadena, CA, USA\n *     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK\n *\n * Copyright (C) 2006-2008 by the California Institute of Technology,\n *     Pasadena, CA, USA \n *\n * Copyright (C) 2002-2005 jointly by the following organizations:\n *     1. California Institute of Technology, Pasadena, CA, USA\n *     2. Japan Science and Technology Agency, Japan\n *\n * This library is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation.  A copy of the license agreement is provided\n * in the file named \"LICENSE.txt\" included with this software distribution\n * and also available online as http:\/\/sbml.org\/software\/libsbml\/license.html\n * ------------------------------------------------------------------------ -->\n *\/\n\n#include <sbml\/SBMLTypes.h>\n#include <sbml\/packages\/arrays\/common\/ArraysExtensionTypes.h>\n\n\nusing namespace std;\nLIBSBML_CPP_NAMESPACE_USE\n\nint\nmain (int argc, char* argv[])\n{\n  SBMLNamespaces sbmlns(3,1,\"arrays\",1);\n\n  \/\/ create the document\n\n  SBMLDocument *document = new SBMLDocument(&sbmlns);\n\n  \/\/ set the required attribute to true\n  ArraysSBMLDocumentPlugin * docPlug = \n    static_cast<ArraysSBMLDocumentPlugin*>(document->getPlugin(\"arrays\"));\n  docPlug->setRequired(true);\n\n\n  \/\/ create the Model\n\n  Model* model=document->createModel();\n\n  \/\/ create the parameters\n\n  Parameter * p = model->createParameter();\n  p->setId(\"n\");\n  p->setConstant(true);\n  p->setValue(10);\n\n  \/\/ second parameter\n  p = model->createParameter();\n  p->setId(\"x\");\n  p->setConstant(false);\n\n\n  \/\/ create the Dimensions via the Plugin\n  ArraysSBasePlugin * arraysPlug = \n    static_cast<ArraysSBasePlugin*>(p->getPlugin(\"arrays\"));\n  Dimension * dim = arraysPlug->createDimension();\n  dim->setDim(0);\n  dim->setSize(\"n\");\n\n  \/\/ third parameter\n  p = model->createParameter();\n  p->setId(\"y\");\n  p->setConstant(true);\n  p->setValue(2.3);\n\n\n\n  \/\/ create the initialAssignment\n  InitialAssignment *ia = model->createInitialAssignment();\n  ia->setSymbol(\"x\");\n\n  ASTNode * math = new ASTNode(AST_LINEAR_ALGEBRA_VECTOR_CONSTRUCTOR);\n  \n  ASTNode * ci1 = new ASTNode(AST_NAME);\n  ci1->setName(\"y\");\n  \n  ASTNode * ci2 = new ASTNode(AST_INTEGER);\n  ci2->setValue(2);\n\n  ASTNode * c1 = new ASTNode(AST_FUNCTION_COS);\n  ASTNode * c11 = new ASTNode(AST_INTEGER);\n  c11->setValue(5);\n  c1->addChild(c11);\n\n  math->addChild(ci1);\n  math->addChild(ci2);\n  math->addChild(c1);\n  math->setClass(\"ss\");\n  ia->setMath(math);\n\n  writeSBML(document,\"arrays_example2.xml\");\n \n  delete document;\n\n  return 0;\n}\n","avg_line_length":27.2767857143,"max_line_length":79,"alphanum_fraction":0.6664484452,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4241,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":20.0,"content":"\/*\n\tmpg123clr: MPEG Audio Decoder library Common Language Runtime version.\n\n\tcopyright 2009-2011 by Malcolm Boczek - free software under the terms of the LGPL 2.1\n\tmpg123clr.dll is a derivative work of libmpg123 - all original mpg123 licensing terms apply.\n\n\tAll rights to this work freely assigned to the mpg123 project.\n*\/\n\/*\n\tlibmpg123: MPEG Audio Decoder library\n\n\tcopyright 1995-2011 by the mpg123 project - free software under the terms of the LGPL 2.1\n\tsee COPYING and AUTHORS files in distribution or http:\/\/mpg123.org\n\n*\/\n\/*\n\t1.8.1.0\t04-Aug-09\tInitial release.\n\t1.9.0.0 24-Sep-09\tFunction names harmonized with libmpg123 (mb)\n\t1.9.0.0 01-Oct-09\tTechnical cleanup - subst nullptr for NULL (mb)\n\t1.13.0.0 13-Jan-11\trelease match - added strlen (mb)\n*\/\n\n#include \"StdAfx.h\"\n#include \"string.h\"\n\n\/\/ Constructor for overlaid instance (instanced)\nmpg123clr::mpg123str::mpg123str(void)\n{\n\tinstanced = true;\n\tsb = new ::mpg123_string;\n\tmpg123_init_string();\n\n}\n\n\/\/ Constructor for mpg123_string handle instance (referenced)\nmpg123clr::mpg123str::mpg123str(mpg123_string* sb)\n{\n\tinstanced = false;\n\tthis->sb = sb;\n}\n\nmpg123clr::mpg123str::mpg123str(const char* str)\n{\n\tinstanced = true;\n\tsb = new ::mpg123_string;\n\tmpg123_init_string();\n\n\t::mpg123_set_string(sb, str);\n}\n\n\/\/ Destructor cleans up all resources\nmpg123clr::mpg123str::~mpg123str(void)\n{\n\t\/\/ clean up code to release managed resources\n\t\/\/ ...\n\n\t\/\/ call Finalizer to clean up unmanaged resources\n\tthis->!mpg123str();\n}\n\n\/\/ Finalizer cleans up unmanaged resources\nmpg123clr::mpg123str::!mpg123str(void)\n{\n\tif (instanced && (sb != nullptr)) mpg123_free_string();\n}\n\nint mpg123clr::mpg123str::mpg123_add_string(String ^ s)\n{\n\treturn mpg123_add_substring(s, 0, s->Length);\n}\n\nint mpg123clr::mpg123str::mpg123_add_substring(String ^ s, int from, int count)\n{\n\t\/\/ convert CLR string to CLI string\n\tusing namespace Runtime::InteropServices;\n\tconst char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s->Substring(from, count))).ToPointer();\n\n\t\/\/ add mpg123_string info\n\tint ret = ::mpg123_add_string(sb, chars);\n\n\t\/\/ free temporary memory\n\tMarshal::FreeHGlobal(IntPtr((void*)chars));\n\n\treturn ret;\n}\n\nint mpg123clr::mpg123str::mpg123_copy_string(mpg123str^ to)\n{\n\treturn ::mpg123_copy_string(sb, to->sb);\n}\n\nvoid mpg123clr::mpg123str::mpg123_free_string()\n{\n\t::mpg123_free_string(sb);\n}\n\nint mpg123clr::mpg123str::mpg123_grow_string(int newSize)\n{\n\treturn ::mpg123_grow_string(sb, newSize);\n}\n\nint mpg123clr::mpg123str::mpg123_resize_string(int newSize)\n{\n\treturn ::mpg123_resize_string(sb, newSize);\n}\n\nvoid mpg123clr::mpg123str::mpg123_init_string()\n{\n\t::mpg123_init_string(sb);\n}\n\nint mpg123clr::mpg123str::mpg123_set_string(String ^ s)\n{\n\treturn mpg123_set_substring(s, 0, s->Length);\n}\n\nint mpg123clr::mpg123str::mpg123_set_substring(String ^ s, int from, int count)\n{\n\t\/\/ convert CLR string to CLI string\n\tusing namespace Runtime::InteropServices;\n\tconst char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s->Substring(from, count))).ToPointer();\n\n\t\/\/ set mpg123_string info\n\tint ret = ::mpg123_set_string(sb, chars);\n\n\t\/\/ free temporary memory\n\tMarshal::FreeHGlobal(IntPtr((void*)chars));\n\n\treturn ret;\n}\n\nlong long mpg123clr::mpg123str::mpg123_strlen(bool utf8)\n{\n\t\/\/ TODO: determine use for utf8 vs ansi\n\treturn ::mpg123_strlen(sb, utf8);\n}\n\nint mpg123clr::mpg123str::Fill::get()\n{\n\t\/\/ WARN 4267 - clr limited to 32bit-length-size strings by PtrToStringAnsi\n\treturn (int)sb->fill;\n}\n\nint mpg123clr::mpg123str::Size::get()\n{\n\t\/\/ WARN 4267 - clr limited to 32bit-length-size strings by PtrToStringAnsi\n\treturn (int)sb->size;\n}\n\nString^ mpg123clr::mpg123str::Text::get()\n{\n\tif (sb->fill == 0) return gcnew String(\"\");\n\n\t\/\/ WARN 4267 - clr limited to 32bit-length-size strings by PtrToStringAnsi\n\treturn Marshal::PtrToStringAnsi((IntPtr)sb->p, (int)strnlen(sb->p, sb->fill));\n}\n\nmpg123clr::mpg123str::text_encoding mpg123clr::mpg123str::mpg123_enc_from_id3(unsigned char id3_enc_byte)\n{\n\treturn (mpg123clr::mpg123str::text_encoding) ::mpg123_enc_from_id3(id3_enc_byte);\n}\n\nint mpg123clr::mpg123str::mpg123_store_utf8(text_encoding enc, const unsigned char *source, size_t source_size)\n{\n\treturn ::mpg123_store_utf8(sb, (mpg123_text_encoding)enc, source, source_size);\n}\n","avg_line_length":25.3952095808,"max_line_length":111,"alphanum_fraction":0.7425135581,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":9316,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":8.0,"content":"\/\/\n\/\/  ast.cpp\n\/\/\n\/\/  Created by Edmund Kapusniak on 28\/09\/2019.\n\/\/  Copyright \u00a9 2019 Edmund Kapusniak.\n\/\/\n\/\/  Licensed under the MIT License. See LICENSE file in the project root for\n\/\/  full license information.\n\/\/\n\n#include \"ast.h\"\n#include \"..\/common\/escape_string.h\"\n\nnamespace kf\n{\n\n#ifdef _MSC_VER\n#define INIT( x )\n#else\n#define INIT( x ) [ x ] =\n#endif\n\nconst char* const AST_NODE_NAME[] =\n{\n    INIT( AST_NONE              ) \"NONE\",\n\n    INIT( AST_EXPR_LENGTH       ) \"EXPR_LENGTH\",\n    INIT( AST_EXPR_NEG          ) \"EXPR_NEG\",\n    INIT( AST_EXPR_POS          ) \"EXPR_POS\",\n    INIT( AST_EXPR_BITNOT       ) \"EXPR_BITNOT\",\n    INIT( AST_EXPR_MUL          ) \"EXPR_MUL\",\n    INIT( AST_EXPR_DIV          ) \"EXPR_DIV\",\n    INIT( AST_EXPR_INTDIV       ) \"EXPR_INTDIV\",\n    INIT( AST_EXPR_MOD          ) \"EXPR_MOD\",\n    INIT( AST_EXPR_ADD          ) \"EXPR_ADD\",\n    INIT( AST_EXPR_SUB          ) \"EXPR_SUB\",\n    INIT( AST_EXPR_CONCAT       ) \"EXPR_CONCAT\",\n    INIT( AST_EXPR_LSHIFT       ) \"EXPR_LSHIFT\",\n    INIT( AST_EXPR_RSHIFT       ) \"EXPR_RSHIFT\",\n    INIT( AST_EXPR_ASHIFT       ) \"EXPR_ASHIFT\",\n    INIT( AST_EXPR_BITAND       ) \"EXPR_BITAND\",\n    INIT( AST_EXPR_BITXOR       ) \"EXPR_BITXOR\",\n    INIT( AST_EXPR_BITOR        ) \"EXPR_BITOR\",\n\n    INIT( AST_EXPR_PAREN        ) \"EXPR_PAREN\",\n\n    INIT( AST_EXPR_NULL         ) \"EXPR_NULL\",\n    INIT( AST_EXPR_FALSE        ) \"EXPR_FALSE\",\n    INIT( AST_EXPR_TRUE         ) \"EXPR_TRUE\",\n    INIT( AST_EXPR_NUMBER       ) \"EXPR_NUMBER\",\n    INIT( AST_EXPR_STRING       ) \"EXPR_STRING\",\n\n    INIT( AST_EXPR_COMPARE      ) \"EXPR_COMPARE\",\n    INIT( AST_OP_EQ             ) \"OP_EQ\",\n    INIT( AST_OP_NE             ) \"OP_NE\",\n    INIT( AST_OP_LT             ) \"OP_LT\",\n    INIT( AST_OP_LE             ) \"OP_LE\",\n    INIT( AST_OP_GT             ) \"OP_GT\",\n    INIT( AST_OP_GE             ) \"OP_GE\",\n    INIT( AST_OP_IS             ) \"OP_IS\",\n    INIT( AST_OP_IS_NOT         ) \"OP_IS_NOT\",\n\n    INIT( AST_EXPR_NOT          ) \"EXPR_NOT\",\n    INIT( AST_EXPR_AND          ) \"EXPR_AND\",\n    INIT( AST_EXPR_OR           ) \"EXPR_OR\",\n    INIT( AST_EXPR_IF           ) \"EXPR_IF\",\n    INIT( AST_EXPR_ELIF         ) \"EXPR_ELIF\",\n\n    INIT( AST_EXPR_KEY          ) \"EXPR_KEY\",\n    INIT( AST_EXPR_INDEX        ) \"EXPR_INDEX\",\n    INIT( AST_EXPR_CALL         ) \"EXPR_CALL\",\n    INIT( AST_EXPR_UNPACK       ) \"EXPR_UNPACK\",\n    INIT( AST_EXPR_ARRAY        ) \"EXPR_ARRAY\",\n    INIT( AST_EXPR_TABLE        ) \"EXPR_TABLE\",\n    INIT( AST_TABLE_KEY         ) \"TABLE_KEY\",\n\n    INIT( AST_EXPR_YIELD        ) \"RVAL_YIELD\",\n    INIT( AST_EXPR_YIELD_FOR    ) \"RVAL_YIELD_FOR\",\n\n    INIT( AST_DECL_VAR          ) \"DECL_VAR\",\n    INIT( AST_DECL_DEF          ) \"DECL_DEF\",\n    INIT( AST_RVAL_ASSIGN       ) \"RVAL_ASSIGN\",\n    INIT( AST_RVAL_OP_ASSIGN    ) \"RVAL_OP_ASSIGN\",\n    INIT( AST_NAME_LIST         ) \"NAME_LIST\",\n    INIT( AST_LVAL_LIST         ) \"LVAL_LIST\",\n    INIT( AST_RVAL_LIST         ) \"RVAL_LIST\",\n\n    INIT( AST_FUNCTION          ) \"FUNCTION\",\n    INIT( AST_PARAMETERS        ) \"PARAMETERS\",\n    INIT( AST_VARARG_PARAM      ) \"VARARG_PARAM\",\n\n    INIT( AST_BLOCK             ) \"BLOCK\",\n\n    INIT( AST_STMT_IF           ) \"STMT_IF\",\n    INIT( AST_STMT_ELIF         ) \"STMT_ELIF\",\n    INIT( AST_STMT_FOR_STEP     ) \"STMT_FOR_STEP\",\n    INIT( AST_STMT_FOR_EACH     ) \"STMT_FOR_EACH\",\n    INIT( AST_STMT_WHILE        ) \"STMT_WHILE\",\n    INIT( AST_STMT_REPEAT       ) \"STMT_REPEAT\",\n    INIT( AST_STMT_BREAK        ) \"STMT_BREAK\",\n    INIT( AST_STMT_CONTINUE     ) \"STMT_CONTINUE\",\n    INIT( AST_STMT_RETURN       ) \"STMT_RETURN\",\n    INIT( AST_STMT_THROW        ) \"STMT_THROW\",\n\n    INIT( AST_DEF_FUNCTION      ) \"DEF_FUNCTION\",\n    INIT( AST_DEF_OBJECT        ) \"DEF_OBJECT\",\n    INIT( AST_OBJECT_PROTOTYPE  ) \"OBJECT_PROTOTYPE\",\n    INIT( AST_OBJECT_KEY        ) \"OBJECT_KEY\",\n\n    INIT( AST_NAME              ) \"EXPR_NAME\",\n    INIT( AST_OBJKEY_DECL       ) \"OBJKEY_DECL\",\n    INIT( AST_LOCAL_DECL        ) \"LOCAL_DECL\",\n    INIT( AST_LOCAL_NAME        ) \"LOCAL_NAME\",\n    INIT( AST_SUPER_NAME        ) \"SUPER_NAME\",\n    INIT( AST_OUTENV_NAME       ) \"OUTENV_NAME\",\n    INIT( AST_GLOBAL_NAME       ) \"GLOBAL_NAME\",\n};\n\nast_script::ast_script()\n{\n}\n\nast_script::~ast_script()\n{\n}\n\nast_function* ast_script::new_function( srcloc sloc, ast_function* outer )\n{\n    functions.append( std::make_unique< ast_function >( sloc, this, outer, (unsigned)functions.size() ) );\n    return functions.back().get();\n}\n\nvoid ast_script::debug_print() const\n{\n    for ( const auto& function : functions )\n    {\n        function->debug_print();\n    }\n}\n\nast_function::ast_function( srcloc sloc, ast_script* script, ast_function* outer, unsigned index )\n    :   sloc( sloc )\n    ,   script( script )\n    ,   outer( outer )\n    ,   index( index )\n    ,   parameter_count( 0 )\n    ,   implicit_self( false )\n    ,   is_generator( false )\n    ,   is_top_level( false )\n    ,   is_varargs( false )\n{\n}\n\nast_function::~ast_function()\n{\n}\n\nvoid ast_function::fixup_nodes()\n{\n    \/\/ Calculate next sibling pointers.\n    unsigned last_index = 0;\n    for ( unsigned index = 0; index < nodes.size(); ++index )\n    {\n        if ( index )\n        {\n            \/\/ Link last child node to its parent.\n            nodes[ last_index ].next_index = index;\n\n            \/\/ Remember if last index so we can move backwards in vector.\n            if ( nodes[ last_index ].leaf )\n            {\n                nodes[ index ].prev_leaf = true;\n            }\n        }\n        last_index = index;\n\n        \/\/ Find oldest descendant.\n        unsigned node_index = index;\n        unsigned child_index = nodes[ node_index ].child_index;\n        while ( child_index != node_index )\n        {\n            node_index = child_index;\n            child_index = nodes[ node_index ].child_index;\n        }\n\n        \/\/ Previous node is the node before the oldest descendant.\n        if ( child_index )\n        {\n            unsigned prev_index = child_index - 1;\n            if ( nodes[ child_index ].prev_leaf )\n            {\n                prev_index -= 1;\n            }\n            nodes[ prev_index ].next_index = index;\n        }\n\n        \/\/ Skip leaf data.\n        if ( nodes[ index ].leaf )\n        {\n            ++index;\n        }\n    }\n}\n\nstatic void debug_print_tree( const std::vector< ast_node >& nodes, unsigned index, int indent )\n{\n    const ast_node& n = nodes.at( index );\n\n    printf( \"%*s[%4u]%s\", indent, \"\", n.sloc, AST_NODE_NAME[ n.kind ] );\n    if ( n.leaf == AST_LEAF_STRING )\n    {\n        const ast_leaf_string& l = n.leaf_string();\n        std::string s = escape_string( std::string_view( l.text, l.size ), 45 );\n        printf( \" STRING %s\\n\", s.c_str() );\n    }\n    else if ( n.leaf == AST_LEAF_NUMBER )\n    {\n        const ast_leaf_number& l = n.leaf_number();\n        printf( \" NUMBER %f\\n\", l.n );\n    }\n    else if ( n.leaf == AST_LEAF_FUNCTION )\n    {\n        const ast_leaf_function& l = n.leaf_function();\n        printf( \" FUNCTION %p %s\\n\", l.function, l.function->name.c_str() );\n    }\n    else if ( n.leaf == AST_LEAF_INDEX )\n    {\n        const ast_leaf_index& l = n.leaf_index();\n        if ( l.index != AST_INVALID_INDEX )\n            printf( \" INDEX %u\\n\", l.index );\n        else\n            printf( \" INVALID INDEX\\n\" );\n    }\n    else if ( n.leaf == AST_LEAF_OUTENV )\n    {\n        const ast_leaf_outenv& l = n.leaf_outenv();\n        printf( \" OUTENV %u SLOT %u\\n\", l.outenv_index, l.outenv_slot );\n    }\n    else\n    {\n        printf( \"\\n\" );\n    }\n\n    for ( unsigned c = n.child_index; c < index; c = nodes[ c ].next_index )\n    {\n        debug_print_tree( nodes, c, indent + 2 );\n    }\n}\n\nvoid ast_function::debug_print() const\n{\n    printf( \"FUNCTION %p %s\\n\", this, name.c_str() );\n    if ( outer )\n        printf( \"  OUTER %p %s\\n\", outer, outer->name.c_str() );\n    printf( \"  %u PARAMETERS\\n\", parameter_count );\n    if ( implicit_self )\n        printf( \"  IMPLICIT_SELF\\n\" );\n    if ( is_generator )\n        printf( \"  GENERATOR\\n\" );\n    if ( is_top_level )\n        printf( \"  TOP_LEVEL\\n\" );\n    if ( is_varargs )\n        printf( \"  VARARGS\\n\" );\n\n    printf( \"  OUTENV:\\n\" );\n    for ( size_t i = 0; i < outenvs.size(); ++i )\n    {\n        const ast_outenv& outenv = outenvs[ i ];\n        printf\n        (\n            \"    %zu : %s %u\\n\", i,\n            outenv.outer_outenv ? \"OUTENV\" : \"VARENV\",\n            outenv.outer_index\n        );\n    }\n\n    printf( \"  LOCALS:\\n\" );\n    for ( size_t i = 0; i < locals.size(); ++i )\n    {\n        const ast_local& local = locals[ i ];\n        printf( \"    %zu : %.*s\", i, (int)local.name.size(), local.name.data() );\n        if ( local.varenv_index != AST_INVALID_INDEX )\n            printf( \" VARENV %u[ %u ]\", local.varenv_index, local.varenv_slot );\n        if ( local.kind == LOCAL_PARAM )\n            printf( \" PARAM\" );\n        if ( local.kind == LOCAL_PARAM_SELF )\n            printf( \" PARAM_SELF\" );\n        if ( local.kind == LOCAL_PARAM_VARARG )\n            printf( \" PARAM_VARARG\" );\n        if ( local.kind == LOCAL_FOR_EACH )\n            printf( \" FOR_EACH\" );\n        if ( local.kind == LOCAL_FOR_STEP )\n            printf( \" FOR_STEP\" );\n        if ( local.kind == LOCAL_TEMPORARY )\n            printf( \" TEMPORARY\" );\n        printf( \"\\n\" );\n    }\n\n    debug_print_tree( nodes, nodes.size() - 1, 2 );\n}\n\n}\n\n","avg_line_length":30.6447368421,"max_line_length":106,"alphanum_fraction":0.5517389438,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":75998,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include \"llvm\/ADT\/STLExtras.h\"\n#include \"swift\/SIL\/SILDeclRef.h\"\n#include <ModuleAnalyzerNodes.h>\n#include <algorithm>\n\nusing namespace swift;\nusing namespace ide;\nusing namespace api;\n\nnamespace fs = llvm::sys::fs;\nnamespace path = llvm::sys::path;\n\nnamespace {\nstatic StringRef getAttrName(DeclAttrKind Kind) {\n  switch (Kind) {\n#define DECL_ATTR(NAME, CLASS, ...)                                           \\\n  case DAK_##CLASS:                                                           \\\n      return DeclAttribute::isDeclModifier(DAK_##CLASS) ? #NAME : \"@\"#NAME;\n#include \"swift\/AST\/Attr.def\"\n  case DAK_Count:\n    llvm_unreachable(\"unrecognized attribute kind.\");\n  }\n  llvm_unreachable(\"covered switch\");\n}\n} \/\/ End of anonymous namespace.\n\nstruct swift::ide::api::SDKNodeInitInfo {\n  SDKContext &Ctx;\n  DeclKind DKind;\n  AccessorKind AccKind;\n\n#define KEY_STRING(X, Y) StringRef X;\n#include \"swift\/IDE\/DigesterEnums.def\"\n#define KEY_BOOL(X, Y) bool X = false;\n#include \"swift\/IDE\/DigesterEnums.def\"\n#define KEY_UINT(X, Y) Optional<uint8_t> X;\n#include \"swift\/IDE\/DigesterEnums.def\"\n#define KEY_STRING_ARR(X, Y) std::vector<StringRef> X;\n#include \"swift\/IDE\/DigesterEnums.def\"\n\n  ReferenceOwnership ReferenceOwnership = ReferenceOwnership::Strong;\n  std::vector<DeclAttrKind> DeclAttrs;\n  std::vector<TypeAttrKind> TypeAttrs;\n\n  SDKNodeInitInfo(SDKContext &Ctx) : Ctx(Ctx) {}\n  SDKNodeInitInfo(SDKContext &Ctx, Decl *D);\n  SDKNodeInitInfo(SDKContext &Ctx, ValueDecl *VD);\n  SDKNodeInitInfo(SDKContext &Ctx, OperatorDecl *D);\n  SDKNodeInitInfo(SDKContext &Ctx, ProtocolConformance *Conform);\n  SDKNodeInitInfo(SDKContext &Ctx, Type Ty, TypeInitInfo Info = TypeInitInfo());\n  SDKNode* createSDKNode(SDKNodeKind Kind);\n};\n\nSDKContext::SDKContext(CheckerOptions Opts): Diags(SourceMgr), Opts(Opts) {\n#define ADD(NAME) BreakingAttrs.push_back({DeclAttrKind::DAK_##NAME, \\\n      getAttrName(DeclAttrKind::DAK_##NAME)});\n  \/\/ Add attributes that both break ABI and API.\n  ADD(Final)\n  if (checkingABI()) {\n    \/\/ Add ABI-breaking-specific attributes.\n    ADD(ObjC)\n    ADD(FixedLayout)\n    ADD(Frozen)\n    ADD(Dynamic)\n  }\n#undef ADD\n}\n\nvoid SDKNodeRoot::registerDescendant(SDKNode *D) {\n  \/\/ Operator doesn't have usr\n  if (isa<SDKNodeDeclOperator>(D))\n    return;\n  if (auto DD = dyn_cast<SDKNodeDecl>(D)) {\n    assert(!DD->getUsr().empty());\n    DescendantDeclTable[DD->getUsr()].insert(DD);\n  }\n}\n\nSDKNode::SDKNode(SDKNodeInitInfo Info, SDKNodeKind Kind): Ctx(Info.Ctx),\n  Name(Info.Name), PrintedName(Info.PrintedName), TheKind(unsigned(Kind)) {}\n\nSDKNodeRoot::SDKNodeRoot(SDKNodeInitInfo Info): SDKNode(Info, SDKNodeKind::Root),\n  ToolArgs(Info.ToolArgs),\n  JsonFormatVer(Info.JsonFormatVer.hasValue() ? *Info.JsonFormatVer : DIGESTER_JSON_DEFAULT_VERSION) {}\n\nSDKNodeDecl::SDKNodeDecl(SDKNodeInitInfo Info, SDKNodeKind Kind)\n      : SDKNode(Info, Kind), DKind(Info.DKind), Usr(Info.Usr),\n        Location(Info.Location), ModuleName(Info.ModuleName),\n        DeclAttributes(Info.DeclAttrs), IsImplicit(Info.IsImplicit),\n        IsStatic(Info.IsStatic), IsDeprecated(Info.IsDeprecated),\n        IsProtocolReq(Info.IsProtocolReq),\n        IsOverriding(Info.IsOverriding),\n        IsOpen(Info.IsOpen),\n        IsInternal(Info.IsInternal), IsABIPlaceholder(Info.IsABIPlaceholder),\n        ReferenceOwnership(uint8_t(Info.ReferenceOwnership)),\n        GenericSig(Info.GenericSig), FixedBinaryOrder(Info.FixedBinaryOrder),\n        introVersions({Info.IntromacOS, Info.IntroiOS, Info.IntrotvOS,\n                       Info.IntrowatchOS, Info.Introswift}){}\n\nSDKNodeType::SDKNodeType(SDKNodeInitInfo Info, SDKNodeKind Kind):\n  SDKNode(Info, Kind), TypeAttributes(Info.TypeAttrs),\n  HasDefaultArg(Info.HasDefaultArg),\n  ParamValueOwnership(Info.ParamValueOwnership) {}\n\nSDKNodeTypeNominal::SDKNodeTypeNominal(SDKNodeInitInfo Info):\n  SDKNodeType(Info, SDKNodeKind::TypeNominal), USR(Info.Usr) {}\n\nSDKNodeTypeFunc::SDKNodeTypeFunc(SDKNodeInitInfo Info):\n  SDKNodeType(Info, SDKNodeKind::TypeFunc) {}\n\nSDKNodeTypeAlias::SDKNodeTypeAlias(SDKNodeInitInfo Info):\n  SDKNodeType(Info, SDKNodeKind::TypeAlias) {}\n\nSDKNodeDeclType::SDKNodeDeclType(SDKNodeInitInfo Info):\n  SDKNodeDecl(Info, SDKNodeKind::DeclType), SuperclassUsr(Info.SuperclassUsr),\n  SuperclassNames(Info.SuperclassNames),\n  EnumRawTypeName(Info.EnumRawTypeName), IsExternal(Info.IsExternal) {}\n\nSDKNodeConformance::SDKNodeConformance(SDKNodeInitInfo Info):\n  SDKNode(Info, SDKNodeKind::Conformance),\n  Usr(Info.Usr), IsABIPlaceholder(Info.IsABIPlaceholder) {}\n\nSDKNodeTypeWitness::SDKNodeTypeWitness(SDKNodeInitInfo Info):\n  SDKNode(Info, SDKNodeKind::TypeWitness) {}\n\nSDKNodeDeclOperator::SDKNodeDeclOperator(SDKNodeInitInfo Info):\n  SDKNodeDecl(Info, SDKNodeKind::DeclOperator) {}\n\nSDKNodeDeclTypeAlias::SDKNodeDeclTypeAlias(SDKNodeInitInfo Info):\n  SDKNodeDecl(Info, SDKNodeKind::DeclTypeAlias) {}\n\nSDKNodeDeclVar::SDKNodeDeclVar(SDKNodeInitInfo Info): \n  SDKNodeDecl(Info, SDKNodeKind::DeclVar), IsLet(Info.IsLet),\n  HasStorage(Info.HasStorage) {}\n\nSDKNodeDeclAbstractFunc::SDKNodeDeclAbstractFunc(SDKNodeInitInfo Info,\n  SDKNodeKind Kind): SDKNodeDecl(Info, Kind), IsThrowing(Info.IsThrowing),\n                     ReqNewWitnessTableEntry(Info.ReqNewWitnessTableEntry),\n                     SelfIndex(Info.SelfIndex) {}\n\nSDKNodeDeclFunction::SDKNodeDeclFunction(SDKNodeInitInfo Info):\n  SDKNodeDeclAbstractFunc(Info, SDKNodeKind::DeclFunction),\n  FuncSelfKind(Info.FuncSelfKind) {}\n\nSDKNodeDeclConstructor::SDKNodeDeclConstructor(SDKNodeInitInfo Info):\n  SDKNodeDeclAbstractFunc(Info, SDKNodeKind::DeclConstructor) {}\n\nSDKNodeDeclAccessor::SDKNodeDeclAccessor(SDKNodeInitInfo Info):\n  SDKNodeDeclAbstractFunc(Info, SDKNodeKind::DeclAccessor),\n  AccKind(Info.AccKind) {}\n\nSDKNodeDeclAssociatedType::SDKNodeDeclAssociatedType(SDKNodeInitInfo Info):\n  SDKNodeDecl(Info, SDKNodeKind::DeclAssociatedType) {};\n\nSDKNodeDeclSubscript::SDKNodeDeclSubscript(SDKNodeInitInfo Info):\n  SDKNodeDeclAbstractFunc(Info, SDKNodeKind::DeclSubscript),\n  HasStorage(Info.HasStorage) {}\n\nStringRef SDKNodeDecl::getHeaderName() const {\n  if (Location.empty())\n    return StringRef();\n  return llvm::sys::path::filename(Location.split(\":\").first);\n}\n\nstatic SDKNodeDeclAccessor *getAccessorInternal(ArrayRef<SDKNode*> Accessors,\n                                                AccessorKind Kind) {\n  for (auto *AC: Accessors) {\n    if (cast<SDKNodeDeclAccessor>(AC)->getAccessorKind() == Kind) {\n      return cast<SDKNodeDeclAccessor>(AC);\n    }\n  }\n  return nullptr;\n}\n\nSDKNodeDeclAccessor *SDKNodeDeclVar::getAccessor(AccessorKind Kind) const {\n  return getAccessorInternal(Accessors, Kind);\n}\n\nSDKNodeDeclAccessor *SDKNodeDeclSubscript::getAccessor(AccessorKind Kind) const {\n  return getAccessorInternal(Accessors, Kind);\n}\n\nSDKNodeType *SDKNodeDeclVar::getType() const {\n  return cast<SDKNodeType>(childAt(0));\n}\n\nNodePtr UpdatedNodesMap::findUpdateCounterpart(const SDKNode *Node) const {\n  assert(Node->isAnnotatedAs(NodeAnnotation::Updated) && \"Not update operation.\");\n  auto FoundPair = std::find_if(MapImpl.begin(), MapImpl.end(),\n                      [&](std::pair<NodePtr, NodePtr> Pair) {\n    return Pair.second == Node || Pair.first == Node;\n  });\n  assert(FoundPair != MapImpl.end() && \"Cannot find update counterpart.\");\n  return Node == FoundPair->first ? FoundPair->second : FoundPair->first;\n}\n\n#define NODE_KIND_RANGE(ID, FIRST, LAST)                                      \\\nbool SDKNode##ID::classof(const SDKNode *N) {                                 \\\n  return N->getKind() >= SDKNodeKind::FIRST &&                                \\\n    N->getKind() <= SDKNodeKind::LAST;                                        \\\n}\n#include \"swift\/IDE\/DigesterEnums.def\"\n\nunsigned SDKNode::getChildIndex(const SDKNode* Child) const {\n  auto It = std::find(Children.begin(), Children.end(), Child);\n  assert(It != Children.end() && \"cannot find the child\");\n  return It - Children.begin();\n}\n\nSDKNode* SDKNode::getOnlyChild() const {\n  assert(Children.size() == 1 && \"more that one child.\");\n  return *Children.begin();\n}\n\nSDKNodeRoot *SDKNode::getRootNode() const {\n  for (auto *Root = const_cast<SDKNode*>(this); ; Root = Root->getParent()) {\n    if (auto Result = dyn_cast<SDKNodeRoot>(Root))\n      return Result;\n  }\n  llvm_unreachable(\"Unhandled SDKNodeKind in switch.\");\n}\n\nvoid SDKNode::addChild(SDKNode *Child) {\n  Child->Parent = this;\n  Children.push_back(Child);\n  if (auto *Root = dyn_cast<SDKNodeRoot>(this)) {\n    struct DeclCollector: public SDKNodeVisitor {\n      SDKNodeRoot &Root;\n      DeclCollector(SDKNodeRoot &Root): Root(Root) {}\n      void visit(NodePtr Node) override {\n        Root.registerDescendant(Node);\n      }\n    } Collector(*Root);\n    SDKNode::preorderVisit(Child, Collector);\n  }\n}\n\nNodePtr SDKNode::childAt(unsigned I) const {\n  assert(I < getChildrenCount());\n  return getChildren()[I];\n}\n\nvoid SDKNode::removeChild(NodePtr C) {\n  Children.erase(std::find(Children.begin(), Children.end(), C));\n}\n\nvoid SDKNode::annotate(NodeAnnotation Anno, StringRef Comment) {\n  assert(!Comment.empty());\n  if(isAnnotatedAs(Anno))\n    return;\n  annotate(Anno);\n  AnnotateComments[Anno] = Comment;\n}\n\nvoid SDKNode::removeAnnotate(NodeAnnotation Anno) {\n  assert(isAnnotatedAs(Anno));\n  Annotations.erase(Anno);\n  AnnotateComments.erase(Anno);\n  assert(!isAnnotatedAs(Anno));\n  assert(AnnotateComments.count(Anno) == 0);\n}\n\nStringRef SDKNode::getAnnotateComment(NodeAnnotation Anno) const {\n  return AnnotateComments.find(Anno)->second;\n}\n\nArrayRef<NodeAnnotation> SDKNode::\ngetAnnotations(std::vector<NodeAnnotation> &Scratch) const {\n  for (auto Ann : Annotations)\n    Scratch.push_back(Ann);\n  return llvm::makeArrayRef(Scratch);\n}\n\nbool SDKNode::isAnnotatedAs(NodeAnnotation Anno) const {\n  return Annotations.find(Anno) != Annotations.end();;\n}\n\nvoid SDKNode::preorderVisit(NodePtr Root, SDKNodeVisitor &Visitor) {\n  Visitor.visit(Root);\n  Visitor.Ancestors.push_back(Root);\n  for (auto Child : Root->Children)\n    preorderVisit(Child, Visitor);\n  Visitor.Ancestors.pop_back();\n}\n\nvoid SDKNode::postorderVisit(NodePtr Root, SDKNodeVisitor &Visitor) {\n  Visitor.Ancestors.push_back(Root);\n  for (auto Child : Root->Children)\n    postorderVisit(Child, Visitor);\n  Visitor.Ancestors.pop_back();\n  Visitor.visit(Root);\n}\n\nSDKNodeVectorViewer::VectorIt\nSDKNodeVectorViewer::getNext(VectorIt Start) {\n  for (auto It = Start; It != Collection.end(); ++ It)\n    if (Selector(*It))\n      return It;\n  return Collection.end();\n}\n\nSDKNodeVectorViewer::ViewerIterator&\nSDKNodeVectorViewer::ViewerIterator::operator++() {\n  P = Viewer.getNext(P + 1);\n  return *this;\n}\n\nSDKNodeVectorViewer::ViewerIterator SDKNodeVectorViewer::begin() {\n  return ViewerIterator(*this, getNext(Collection.begin()));\n}\n\nSDKNodeVectorViewer::ViewerIterator SDKNodeVectorViewer::end() {\n  return ViewerIterator(*this, Collection.end());\n}\n\nKnownTypeKind SDKNodeType::getTypeKind() const {\n#define KNOWN_TYPE(NAME) if (getName() == #NAME) return KnownTypeKind::NAME;\n#include \"swift\/IDE\/DigesterEnums.def\"\n  return KnownTypeKind::Unknown;\n}\n\nArrayRef<TypeAttrKind> SDKNodeType::getTypeAttributes() const {\n  return llvm::makeArrayRef(TypeAttributes.data(), TypeAttributes.size());\n}\n\nvoid SDKNodeType::addTypeAttribute(TypeAttrKind AttrKind) {\n  TypeAttributes.push_back(AttrKind);\n}\n\nbool SDKNodeType::hasTypeAttribute(TypeAttrKind DAKind) const {\n  return std::find(TypeAttributes.begin(), TypeAttributes.end(), DAKind) !=\n    TypeAttributes.end();\n}\n\nStringRef SDKNodeType::getParamValueOwnership() const {\n  return ParamValueOwnership.empty() ? \"Default\" : ParamValueOwnership;\n}\n\nStringRef SDKNodeType::getTypeRoleDescription() const {\n  assert(isTopLevelType());\n  auto P = getParent();\n  switch(P->getKind()) {\n  case SDKNodeKind::Root:\n  case SDKNodeKind::TypeNominal:\n  case SDKNodeKind::TypeFunc:\n  case SDKNodeKind::TypeAlias:\n  case SDKNodeKind::DeclType:\n  case SDKNodeKind::DeclOperator:\n  case SDKNodeKind::Conformance:\n    llvm_unreachable(\"Type Parent is wrong\");\n  case SDKNodeKind::DeclFunction:\n  case SDKNodeKind::DeclConstructor:\n  case SDKNodeKind::DeclAccessor:\n  case SDKNodeKind::DeclSubscript:\n    return SDKNodeDeclAbstractFunc::getTypeRoleDescription(Ctx,\n      P->getChildIndex(this));\n  case SDKNodeKind::DeclVar:\n    return \"declared\";\n  case SDKNodeKind::DeclTypeAlias:\n    return \"underlying\";\n  case SDKNodeKind::DeclAssociatedType:\n    return \"default\";\n  case SDKNodeKind::TypeWitness:\n    return \"type witness type\";\n  }\n}\n\nSDKNode *SDKNodeRoot::getInstance(SDKContext &Ctx) {\n  SDKNodeInitInfo Info(Ctx);\n  Info.Name = Ctx.buffer(\"TopLevel\");\n  Info.PrintedName = Ctx.buffer(\"TopLevel\");\n  Info.ToolArgs = Ctx.getOpts().ToolArgs;\n  Info.JsonFormatVer = DIGESTER_JSON_VERSION;\n  return Info.createSDKNode(SDKNodeKind::Root);\n}\n\nStringRef SDKNodeDecl::getScreenInfo() const {\n  auto ModuleName = getModuleName();\n  auto HeaderName = getHeaderName();\n  auto &Ctx = getSDKContext();\n  llvm::SmallString<64> SS;\n  llvm::raw_svector_ostream OS(SS);\n  if (Ctx.getOpts().PrintModule)\n    OS << ModuleName;\n  if (!HeaderName.empty())\n    OS << \"(\" << HeaderName << \")\";\n  if (!OS.str().empty())\n    OS << \": \";\n  bool IsExtension = false;\n  if (auto *TD = dyn_cast<SDKNodeDeclType>(this)) {\n    IsExtension = TD->isExternal();\n  }\n  if (IsExtension)\n    OS << \"Extension\";\n  else\n    OS << getDeclKind();\n  OS << \" \" << getFullyQualifiedName();\n  return Ctx.buffer(OS.str());\n}\n\nvoid SDKNodeDecl::printFullyQualifiedName(llvm::raw_ostream &OS) const {\n  if (auto *ACC = dyn_cast<SDKNodeDeclAccessor>(this)) {\n    ACC->getStorage()->printFullyQualifiedName(OS);\n    OS << \".\" << getPrintedName();\n    return;\n  }\n  std::vector<NodePtr> Parent;\n  for (auto *P = getParent(); isa<SDKNodeDecl>(P); P = P->getParent())\n    Parent.push_back(P);\n  for (auto It = Parent.rbegin(); It != Parent.rend(); ++ It)\n    OS << (*It)->getPrintedName() << \".\";\n  OS << getPrintedName();\n}\n\nStringRef SDKNodeDecl::getFullyQualifiedName() const {\n  llvm::SmallString<32> Buffer;\n  llvm::raw_svector_ostream OS(Buffer);\n  printFullyQualifiedName(OS);\n  return getSDKContext().buffer(OS.str());\n}\n\nbool SDKNodeDecl::isNonOptionalProtocolRequirement() const {\n  return isProtocolRequirement() && !hasDeclAttribute(DAK_Optional);\n}\n\nbool SDKNodeDecl::hasDeclAttribute(DeclAttrKind DAKind) const {\n  return std::find(DeclAttributes.begin(), DeclAttributes.end(), DAKind) !=\n    DeclAttributes.end();\n}\n\nArrayRef<DeclAttrKind> SDKNodeDecl::getDeclAttributes() const {\n  return llvm::makeArrayRef(DeclAttributes.data(), DeclAttributes.size());\n}\n\nbool SDKNodeDecl::hasAttributeChange(const SDKNodeDecl &Another) const {\n  std::set<DeclAttrKind> Left(getDeclAttributes().begin(),\n                              getDeclAttributes().end());\n  std::set<DeclAttrKind> Right(Another.getDeclAttributes().begin(),\n                               Another.getDeclAttributes().end());\n  return Left != Right;\n}\n\nbool SDKNodeType::hasAttributeChange(const SDKNodeType &Another) const {\n  std::set<TypeAttrKind> Left(getTypeAttributes().begin(),\n                              getTypeAttributes().end());\n  std::set<TypeAttrKind> Right(Another.getTypeAttributes().begin(),\n                               Another.getTypeAttributes().end());\n  return Left != Right;\n}\n\nSDKNodeDecl *SDKNodeType::getClosestParentDecl() const {\n  auto *Result = getParent();\n  for (; !isa<SDKNodeDecl>(Result); Result = Result->getParent());\n  return Result->getAs<SDKNodeDecl>();\n}\n\nvoid SDKNodeDeclType::addConformance(SDKNode *Conf) {\n  cast<SDKNodeConformance>(Conf)->TypeDecl = this;\n  Conformances.push_back(Conf);\n}\n\nvoid SDKNodeDeclSubscript::addAccessor(SDKNode *AC) {\n  cast<SDKNodeDeclAccessor>(AC)->Owner = this;\n  Accessors.push_back(AC);\n}\n\nvoid SDKNodeDeclVar::addAccessor(SDKNode *AC) {\n  cast<SDKNodeDeclAccessor>(AC)->Owner = this;\n  Accessors.push_back(AC);\n}\n\nSDKNodeType *SDKNodeTypeWitness::getUnderlyingType() const {\n  return getOnlyChild()->getAs<SDKNodeType>();\n}\n\nStringRef SDKNodeTypeWitness::getWitnessedTypeName() const {\n  return Ctx.buffer((llvm::Twine(getParent()->getAs<SDKNodeConformance>()->\n    getName()) + \".\" + getName()).str());\n}\n\nOptional<SDKNodeDeclType*> SDKNodeDeclType::getSuperclass() const {\n  if (SuperclassUsr.empty())\n    return None;\n  auto Descendants = getRootNode()->getDescendantsByUsr(SuperclassUsr);\n  if (!Descendants.empty()) {\n    return Descendants.front()->getAs<SDKNodeDeclType>();\n  }\n  return None;\n}\n\n\/\/\/ Finding the node through all children, including the inheritted ones,\n\/\/\/ whose printed name matches with the given name.\nOptional<SDKNodeDecl*>\nSDKNodeDeclType::lookupChildByPrintedName(StringRef Name) const {\n  for (auto C : getChildren()) {\n    if (C->getPrintedName() == Name)\n      return C->getAs<SDKNodeDecl>();\n  }\n  \/\/ Finding from the inheritance chain.\n  if (auto Super = getSuperclass()) {\n    return (*Super)->lookupChildByPrintedName(Name);\n  }\n  return None;\n}\n\nSDKNodeType *SDKNodeDeclType::getRawValueType() const {\n  if (isConformingTo(KnownProtocolKind::RawRepresentable)) {\n    if (auto RV = lookupChildByPrintedName(\"rawValue\")) {\n      return (*(*RV)->getChildBegin())->getAs<SDKNodeType>();\n    }\n  }\n  return nullptr;\n}\n\nbool SDKNodeDeclType::isConformingTo(swift::ide::api::KnownProtocolKind Kind) const {\n  switch (Kind) {\n#define KNOWN_PROTOCOL(NAME)                                                \\\n    case KnownProtocolKind::NAME:                                           \\\n      return std::find_if(Conformances.begin(), Conformances.end(),         \\\n        [](SDKNode *Conf) { return Conf->getName() == #NAME; }) !=          \\\n          Conformances.end();\n#include \"swift\/IDE\/DigesterEnums.def\"\n  }\n  llvm_unreachable(\"covered switch\");\n}\n\nStringRef SDKNodeDeclAbstractFunc::getTypeRoleDescription(SDKContext &Ctx,\n                                                      unsigned Index) {\n  if (Index == 0) {\n    return Ctx.buffer(\"return\");\n  } else {\n    llvm::SmallString<4> Buffer;\n    Buffer += \"parameter \";\n    Buffer += std::to_string(Index - 1);\n    return Ctx.buffer(Buffer.str());\n  }\n}\n\n#define NODE_KIND(X, NAME)                                                 \\\n  bool SDKNode##X::classof(const SDKNode *N) {                             \\\n    return N->getKind() == SDKNodeKind::X;                                 \\\n  }\n#include \"swift\/IDE\/DigesterEnums.def\"\n\nstatic Optional<KeyKind> parseKeyKind(StringRef Content) {\n  return llvm::StringSwitch<Optional<KeyKind>>(Content)\n#define KEY(NAME) .Case(#NAME, KeyKind::KK_##NAME)\n#include \"swift\/IDE\/DigesterEnums.def\"\n    .Default(None);\n}\n\nstatic StringRef getKeyContent(SDKContext &Ctx, KeyKind Kind) {\n  switch (Kind) {\n#define KEY(NAME) case KeyKind::KK_##NAME: return Ctx.buffer(#NAME);\n#include \"swift\/IDE\/DigesterEnums.def\"\n  }\n  llvm_unreachable(\"Unhandled KeyKind in switch.\");\n}\n\nSDKNode* SDKNode::constructSDKNode(SDKContext &Ctx,\n                                   llvm::yaml::MappingNode *Node) {\n  static auto GetScalarString = [&](llvm::yaml::Node *N) -> StringRef {\n    auto WithQuote = cast<llvm::yaml::ScalarNode>(N)->getRawValue();\n    return WithQuote.substr(1, WithQuote.size() - 2);\n  };\n\n  static auto getAsInt = [&](llvm::yaml::Node *N) -> int {\n    return std::stoi(cast<llvm::yaml::ScalarNode>(N)->getRawValue());\n  };\n  static auto getAsBool = [&](llvm::yaml::Node *N) -> bool {\n    auto txt = cast<llvm::yaml::ScalarNode>(N)->getRawValue();\n    assert(txt.startswith(\"false\") || txt.startswith(\"true\"));\n    return txt.startswith(\"true\");\n  };\n  SDKNodeKind Kind;\n  SDKNodeInitInfo Info(Ctx);\n  NodeVector Children;\n  NodeVector Conformances;\n  NodeVector Accessors;\n\n  for (auto &Pair : *Node) {\n    auto keyString = GetScalarString(Pair.getKey()); \n    if (auto keyKind = parseKeyKind(keyString)) {\n      switch(*keyKind) {\n      case KeyKind::KK_kind:\n        if (auto parsedKind = parseSDKNodeKind(GetScalarString(Pair.getValue()))) {\n          Kind = *parsedKind;\n        } else {\n          Ctx.diagnose(Pair.getValue(), diag::sdk_node_unrecognized_node_kind,\n                       GetScalarString(Pair.getValue()));\n        }\n        break;\n#define KEY_UINT(X, Y)                                                        \\\n        case KeyKind::KK_##Y: Info.X = getAsInt(Pair.getValue()); break;\n#include \"swift\/IDE\/DigesterEnums.def\"\n#define KEY_STRING(X, Y)                                                      \\\n  case KeyKind::KK_##Y: Info.X = GetScalarString(Pair.getValue()); break;\n#include \"swift\/IDE\/DigesterEnums.def\"\n#define KEY_BOOL(X, Y) case KeyKind::KK_##Y: Info.X = getAsBool(Pair.getValue()); break;\n#include \"swift\/IDE\/DigesterEnums.def\"\n      case KeyKind::KK_children:\n        for (auto &Mapping : *cast<llvm::yaml::SequenceNode>(Pair.getValue())) {\n          Children.push_back(constructSDKNode(Ctx,\n                                        cast<llvm::yaml::MappingNode>(&Mapping)));\n        }\n        break;\n      case KeyKind::KK_conformances:\n        for (auto &Mapping : *cast<llvm::yaml::SequenceNode>(Pair.getValue())) {\n          Conformances.push_back(constructSDKNode(Ctx,\n                                    cast<llvm::yaml::MappingNode>(&Mapping)));\n        }\n        break;\n#define KEY_STRING_ARR(X, Y)                                                  \\\n      case KeyKind::KK_##Y:                                                   \\\n        assert(Info.X.empty());                                               \\\n        for (auto &Name : *cast<llvm::yaml::SequenceNode>(Pair.getValue())) { \\\n          Info.X.push_back(GetScalarString(&Name));                           \\\n        }                                                                     \\\n        break;\n#include \"swift\/IDE\/DigesterEnums.def\"\n      case KeyKind::KK_ownership:\n        Info.ReferenceOwnership =\n            swift::ReferenceOwnership(getAsInt(Pair.getValue()));\n        assert(Info.ReferenceOwnership != swift::ReferenceOwnership::Strong &&\n               \"Strong is implied.\");\n        break;\n\n      case KeyKind::KK_typeAttributes: {\n        auto *Seq = cast<llvm::yaml::SequenceNode>(Pair.getValue());\n        std::transform(Seq->begin(), Seq->end(),\n                       std::back_inserter(Info.TypeAttrs),\n          [&](llvm::yaml::Node &N) {\n            auto Result = llvm::StringSwitch<TypeAttrKind>(GetScalarString(&N))\n  #define TYPE_ATTR(X) .Case(#X, TypeAttrKind::TAK_##X)\n  #include \"swift\/AST\/Attr.def\"\n            .Default(TypeAttrKind::TAK_Count);\n            if (Result == TAK_Count)\n              Ctx.diagnose(&N, diag::sdk_node_unrecognized_type_attr_kind,\n                           GetScalarString(&N));\n            return Result;\n          });\n        break;\n      }\n      case KeyKind::KK_declAttributes: {\n        auto *Seq = cast<llvm::yaml::SequenceNode>(Pair.getValue());\n        std::transform(Seq->begin(), Seq->end(), std::back_inserter(Info.DeclAttrs),\n          [&](llvm::yaml::Node &N) {\n            auto Result = llvm::StringSwitch<DeclAttrKind>(GetScalarString(&N))\n  #define DECL_ATTR(_, NAME, ...) .Case(#NAME, DeclAttrKind::DAK_##NAME)\n  #include \"swift\/AST\/Attr.def\"\n            .Default(DeclAttrKind::DAK_Count);\n            if (Result == DAK_Count)\n              Ctx.diagnose(&N, diag::sdk_node_unrecognized_decl_attr_kind,\n                           GetScalarString(&N));\n            return Result;\n          });\n        break;\n      }\n      case KeyKind::KK_accessors: {\n        for (auto &Mapping : *cast<llvm::yaml::SequenceNode>(Pair.getValue())) {\n          Accessors.push_back(constructSDKNode(Ctx,\n            cast<llvm::yaml::MappingNode>(&Mapping)));\n        }\n        break;\n      }\n      case KeyKind::KK_accessorKind: {\n        AccessorKind unknownKind = (AccessorKind)((uint8_t)(AccessorKind::Last) + 1);\n        Info.AccKind = llvm::StringSwitch<AccessorKind>(\n          GetScalarString(Pair.getValue()))\n#define ACCESSOR(ID)\n#define SINGLETON_ACCESSOR(ID, KEYWORD) .Case(#KEYWORD, AccessorKind::ID)\n#include \"swift\/AST\/AccessorKinds.def\"\n          .Default(unknownKind);\n        if (Info.AccKind == unknownKind) {\n          Ctx.diagnose(Pair.getValue(), diag::sdk_node_unrecognized_accessor_kind,\n                       GetScalarString(Pair.getValue()));\n        }\n        break;\n      }\n      case KeyKind::KK_declKind: {\n        auto dKind = llvm::StringSwitch<Optional<DeclKind>>(\n          GetScalarString(Pair.getValue()))\n  #define DECL(X, PARENT) .Case(#X, DeclKind::X)\n  #include \"swift\/AST\/DeclNodes.def\"\n        .Default(None);\n        if (dKind)\n          Info.DKind = *dKind;\n        else\n          Ctx.diagnose(Pair.getValue(), diag::sdk_node_unrecognized_decl_kind,\n                       GetScalarString(Pair.getValue()));\n        break;\n      }\n      }\n    }\n    else {\n      Ctx.diagnose(Pair.getKey(), diag::sdk_node_unrecognized_key,\n                              keyString);\n      Pair.skip();\n    }\n  };\n  SDKNode *Result = Info.createSDKNode(Kind);\n  for (auto C : Children) {\n    Result->addChild(C);\n  }\n  for (auto *Conf: Conformances) {\n    cast<SDKNodeDeclType>(Result)->addConformance(Conf);\n  }\n   for (auto *Acc: Accessors) {\n     if (auto *SD = dyn_cast<SDKNodeDeclSubscript>(Result)) {\n       SD->addAccessor(Acc);\n     } else if (auto *VD = dyn_cast<SDKNodeDeclVar>(Result)) {\n       VD->addAccessor(Acc);\n     }\n   }\n  return Result;\n}\n\nbool SDKNode::hasSameChildren(const SDKNode &Other) const {\n  if (Children.size() != Other.Children.size())\n    return false;\n  for (unsigned I = 0; I < Children.size(); ++ I) {\n    if (*Children[I] != *Other.Children[I])\n      return false;\n  }\n  return true;\n}\n\nvoid swift::ide::api::nodeSetDifference(ArrayRef<SDKNode*> Left,\n                                        ArrayRef<SDKNode*> Right,\n                                        NodeVector &LeftMinusRight,\n                                        NodeVector &RightMinusLeft) {\n  llvm::SmallPtrSet<NodePtr, 16> LeftToRemove;\n  llvm::SmallPtrSet<NodePtr, 16> RightToRemove;\n  for (auto LC: Left) {\n    for (auto RC: Right) {\n      if (!RightToRemove.count(RC) && *LC == *RC) {\n        LeftToRemove.insert(LC);\n        RightToRemove.insert(RC);\n        break;\n      }\n    }\n  }\n  std::for_each(Left.begin(), Left.end(), [&] (SDKNode *N) {\n    if (!LeftToRemove.count(N))\n      LeftMinusRight.push_back(N);\n  });\n  std::for_each(Right.begin(), Right.end(), [&] (SDKNode *N) {\n    if (!RightToRemove.count(N))\n      RightMinusLeft.push_back(N);\n  });\n}\n\n\nstatic bool hasSameContents(ArrayRef<SDKNode*> Left,\n                            ArrayRef<SDKNode*> Right) {\n  NodeVector LeftMinusRight, RightMinusLeft;\n  nodeSetDifference(Left, Right, LeftMinusRight, RightMinusLeft);\n  return LeftMinusRight.empty() && RightMinusLeft.empty();\n}\n\nstatic bool hasSameParameterFlags(const SDKNodeType *Left, const SDKNodeType *Right) {\n  if (Left->hasDefaultArgument() != Right->hasDefaultArgument())\n    return false;\n  if (Left->getParamValueOwnership() != Right->getParamValueOwnership())\n    return false;\n\n  return true;\n}\n\nstatic bool isSDKNodeEqual(SDKContext &Ctx, const SDKNode &L, const SDKNode &R) {\n  auto *LeftAlias = dyn_cast<SDKNodeTypeAlias>(&L);\n  auto *RightAlias = dyn_cast<SDKNodeTypeAlias>(&R);\n  if (LeftAlias || RightAlias) {\n    auto Left = L.getAs<SDKNodeType>();\n    auto Right = R.getAs<SDKNodeType>();\n\n    \/\/ First compare the parameter attributes.\n    if (!hasSameParameterFlags(Left, Right))\n      return false;\n\n    \/\/ Comparing the underlying types if any of the inputs are alias.\n    Left = LeftAlias ? LeftAlias->getUnderlyingType() : Left;\n    Right = RightAlias ? RightAlias->getUnderlyingType() : Right;\n    return *Left == *Right;\n  }\n\n  if (L.getKind() != R.getKind())\n    return false;\n\n  switch(L.getKind()) {\n    case SDKNodeKind::TypeAlias:\n      llvm_unreachable(\"Should be handled above.\");\n    case SDKNodeKind::TypeNominal:\n    case SDKNodeKind::TypeFunc: {\n      auto Left = L.getAs<SDKNodeType>();\n      auto Right = R.getAs<SDKNodeType>();\n      if (Left->hasAttributeChange(*Right))\n        return false;\n      if (!hasSameParameterFlags(Left, Right))\n        return false;\n      if (Left->getPrintedName() == Right->getPrintedName())\n        return true;\n      if (Ctx.checkingABI()) {\n        \/\/ For abi checking where we don't have sugar types at all, the printed\n        \/\/ name difference is enough to indicate these two types differ.\n        return false;\n      } else {\n        return Left->getName() == Right->getName() &&\n          Left->hasSameChildren(*Right);\n      }\n    }\n\n    case SDKNodeKind::DeclFunction: {\n      auto Left = L.getAs<SDKNodeDeclFunction>();\n      auto Right = R.getAs<SDKNodeDeclFunction>();\n      if (Left->getSelfAccessKind() != Right->getSelfAccessKind())\n        return false;\n      LLVM_FALLTHROUGH;\n    }\n    case SDKNodeKind::DeclConstructor: {\n      auto Left = L.getAs<SDKNodeDeclAbstractFunc>();\n      auto Right = R.getAs<SDKNodeDeclAbstractFunc>();\n      if (Left->isThrowing() ^ Right->isThrowing())\n        return false;\n      if (Left->reqNewWitnessTableEntry() != Right->reqNewWitnessTableEntry())\n        return false;\n      LLVM_FALLTHROUGH;\n    }\n    case SDKNodeKind::DeclAccessor: {\n      if (auto *LA = dyn_cast<SDKNodeDeclAccessor>(&L)) {\n        if (auto *RA = dyn_cast<SDKNodeDeclAccessor>(&R)) {\n          if (LA->getAccessorKind() != RA->getAccessorKind())\n            return false;\n        }\n      }\n      LLVM_FALLTHROUGH;\n    }\n    case SDKNodeKind::DeclVar: {\n      if (auto *LV = dyn_cast<SDKNodeDeclVar>(&L)) {\n        if (auto *RV = dyn_cast<SDKNodeDeclVar>(&R)) {\n          if (Ctx.checkingABI()) {\n            if (LV->hasStorage() != RV->hasStorage())\n              return false;\n          }\n          if (!hasSameContents(LV->getAllAccessors(), RV->getAllAccessors()))\n            return false;\n        }\n      }\n      LLVM_FALLTHROUGH;\n    }\n    case SDKNodeKind::DeclType: {\n      auto *Left = dyn_cast<SDKNodeDeclType>(&L);\n      auto *Right = dyn_cast<SDKNodeDeclType>(&R);\n      if (Left && Right) {\n        if (!hasSameContents(Left->getConformances(), Right->getConformances())) {\n          return false;\n        }\n        if (Left->getSuperClassName() != Right->getSuperClassName()) {\n          return false;\n        }\n        if (Left->getDeclKind() != Right->getDeclKind()) {\n          return false;\n        }\n      }\n      LLVM_FALLTHROUGH;\n    }\n    case SDKNodeKind::DeclAssociatedType:\n    case SDKNodeKind::DeclSubscript: {\n      if (auto *Left = dyn_cast<SDKNodeDeclSubscript>(&L)) {\n        if (auto *Right = dyn_cast<SDKNodeDeclSubscript>(&R)) {\n          if (!hasSameContents(Left->getAllAccessors(), Right->getAllAccessors()))\n            return false;\n        }\n      }\n      LLVM_FALLTHROUGH;\n    }\n    case SDKNodeKind::DeclOperator:\n    case SDKNodeKind::DeclTypeAlias: {\n      auto Left = L.getAs<SDKNodeDecl>();\n      auto Right = R.getAs<SDKNodeDecl>();\n      if (Left->isStatic() ^ Right->isStatic())\n        return false;\n      if (Left->getReferenceOwnership() != Right->getReferenceOwnership())\n        return false;\n      if (Left->hasAttributeChange(*Right))\n        return false;\n      if (Left->getGenericSignature() != Right->getGenericSignature())\n        return false;\n      if (Left->isOpen() != Right->isOpen())\n        return false;\n      if (Left->isInternal() != Right->isInternal())\n        return false;\n      if (Left->hasFixedBinaryOrder() != Right->hasFixedBinaryOrder())\n        return false;\n      if (Left->hasFixedBinaryOrder()) {\n        if (Left->getFixedBinaryOrder() != Right->getFixedBinaryOrder())\n          return false;\n      }\n      LLVM_FALLTHROUGH;\n    }\n    case SDKNodeKind::Conformance:\n    case SDKNodeKind::TypeWitness:\n    case SDKNodeKind::Root: {\n      return L.getPrintedName() == R.getPrintedName() &&\n        L.hasSameChildren(R);\n    }\n  }\n\n  llvm_unreachable(\"Unhandled SDKNodeKind in switch.\");\n}\n\nbool SDKContext::isEqual(const SDKNode &Left, const SDKNode &Right) {\n  return isSDKNodeEqual(*this, Left, Right);\n}\n\nAccessLevel SDKContext::getAccessLevel(const ValueDecl *VD) const {\n  return checkingABI() ? VD->getEffectiveAccess() : VD->getFormalAccess();\n}\n\nbool SDKNode::operator==(const SDKNode &Other) const {\n  return Ctx.isEqual(*this, Other);\n}\n\n\/\/ The pretty printer of a tree of SDKNode\nclass SDKNodeDumpVisitor : public SDKNodeVisitor {\n  void dumpSpace(int Num) {\n    while (Num != 0) {\n      llvm::outs() << \"\\t\";\n      Num --;\n    }\n  }\n  void visit(NodePtr Node) override {\n    dumpSpace(depth());\n    llvm::outs() << \"[\" << Node->getKind() << \"]\" << Node->getName() << \"\\n\";\n  }\npublic:\n  SDKNodeDumpVisitor() {};\n};\n\nstatic StringRef getPrintedName(SDKContext &Ctx, Type Ty,\n                                bool IsImplicitlyUnwrappedOptional = false) {\n  std::string S;\n  llvm::raw_string_ostream OS(S);\n  PrintOptions PO;\n  PO.SkipAttributes = true;\n  if (IsImplicitlyUnwrappedOptional)\n    PO.PrintOptionalAsImplicitlyUnwrapped = true;\n\n  Ty.print(OS, PO);\n  return Ctx.buffer(OS.str());\n}\n\nstatic StringRef getTypeName(SDKContext &Ctx, Type Ty,\n                             bool IsImplicitlyUnwrappedOptional) {\n  if (Ty->getKind() == TypeKind::Paren) {\n    return Ctx.buffer(\"Paren\");\n  }\n  if (Ty->isVoid()) {\n    return Ctx.buffer(\"Void\");\n  }\n  if (auto *NAT = dyn_cast<TypeAliasType>(Ty.getPointer())) {\n    return NAT->getDecl()->getNameStr();\n  }\n  if (Ty->getAnyNominal()) {\n    if (IsImplicitlyUnwrappedOptional) {\n      assert(Ty->getOptionalObjectType());\n      return StringRef(\"ImplicitlyUnwrappedOptional\");\n    }\n    return Ty->getAnyNominal()->getNameStr();\n  }\n#define TYPE(id, parent)                                                      \\\n  if (Ty->getKind() == TypeKind::id) {                                        \\\n    return Ctx.buffer(#id);                                                   \\\n  }\n#include \"swift\/AST\/TypeNodes.def\"\n  llvm_unreachable(\"Unhandled type name.\");\n}\n\nstatic StringRef calculateUsr(SDKContext &Ctx, ValueDecl *VD) {\n  llvm::SmallString<64> SS;\n  llvm::raw_svector_ostream OS(SS);\n  if (!ide::printDeclUSR(VD, OS)) {\n    return Ctx.buffer(SS.str());\n  }\n  return StringRef();\n}\n\nstatic StringRef calculateLocation(SDKContext &SDKCtx, Decl *D) {\n  if (SDKCtx.getOpts().AvoidLocation)\n    return StringRef();\n  auto &Ctx = D->getASTContext();\n  auto &Importer = static_cast<ClangImporter &>(*Ctx.getClangModuleLoader());\n\n  clang::SourceManager &SM = Importer.getClangPreprocessor().getSourceManager();\n  if (ClangNode CN = D->getClangNode()) {\n    clang::SourceLocation Loc = CN.getLocation();\n    Loc = SM.getFileLoc(Loc);\n    if (Loc.isValid())\n      return SDKCtx.buffer(Loc.printToString(SM));\n  }\n\n  return StringRef();\n}\n\nstatic bool isFunctionTypeNoEscape(Type Ty) {\n  if (auto *AFT = Ty->getAs<AnyFunctionType>()) {\n    return AFT->getExtInfo().isNoEscape();\n  }\n  return false;\n}\n\nstatic StringRef getSimpleName(ValueDecl *VD) {\n  if (VD->hasName()) {\n    auto name = VD->getBaseName();\n    switch (name.getKind()) {\n      case DeclBaseName::Kind::Subscript:\n        return \"subscript\";\n      case DeclBaseName::Kind::Constructor:\n        return \"init\";\n      case DeclBaseName::Kind::Destructor:\n        return \"deinit\";\n      case DeclBaseName::Kind::Normal:\n        return llvm::StringSwitch<StringRef>(name.getIdentifier().str())\n        .Case(\"subscript\", \"`subscript`\")\n        .Case(\"init\", \"`init`\")\n        .Case(\"deinit\", \"`deinit`\")\n        .Default(name.getIdentifier().str());\n    }\n  }\n  if (auto *AD = dyn_cast<AccessorDecl>(VD)) {\n    switch(AD->getAccessorKind()) {\n#define ACCESSOR(ID) \\\ncase AccessorKind::ID: return #ID;\n#include \"swift\/AST\/AccessorKinds.def\"\n    }\n  }\n  return \"_\";\n}\n\nstatic StringRef getPrintedName(SDKContext &Ctx, ValueDecl *VD) {\n  if (isa<AbstractFunctionDecl>(VD) || isa<SubscriptDecl>(VD)) {\n    llvm::SmallString<32> Result;\n    Result.append(getSimpleName(VD));\n    Result.append(\"(\");\n    for (auto Arg : VD->getFullName().getArgumentNames()) {\n      Result.append(Arg.empty() ? \"_\" : Arg.str());\n      Result.append(\":\");\n    }\n    Result.append(\")\");\n    return Ctx.buffer(Result.str());\n  }\n  return getSimpleName(VD);\n}\n\nstatic bool isFuncThrowing(ValueDecl *VD) {\n  if (auto AF = dyn_cast<AbstractFunctionDecl>(VD)) {\n    return AF->hasThrows();\n  }\n  return false;\n}\n\nstatic Optional<uint8_t> getSelfIndex(ValueDecl *VD) {\n  if (auto AF = dyn_cast<AbstractFunctionDecl>(VD)) {\n    if (AF->isImportAsInstanceMember())\n      return AF->getSelfIndex();\n  }\n  return None;\n}\n\nstatic ReferenceOwnership getReferenceOwnership(ValueDecl *VD) {\n  if (auto OA = VD->getAttrs().getAttribute<ReferenceOwnershipAttr>()) {\n    return OA->get();\n  }\n  return ReferenceOwnership::Strong;\n}\n\n\/\/ Get a requirement with all types canonicalized.\nRequirement getCanonicalRequirement(Requirement &Req) {\n  auto kind = Req.getKind();\n  if (kind == RequirementKind::Layout) {\n    return Requirement(kind, Req.getFirstType()->getCanonicalType(),\n                       Req.getLayoutConstraint());\n  } else {\n    return Requirement(kind, Req.getFirstType()->getCanonicalType(),\n                       Req.getSecondType()->getCanonicalType());\n  }\n}\n\nstatic\nStringRef printGenericSignature(SDKContext &Ctx, ArrayRef<Requirement> AllReqs) {\n  llvm::SmallString<32> Result;\n  llvm::raw_svector_ostream OS(Result);\n  if (AllReqs.empty())\n    return StringRef();\n  OS << \"<\";\n  bool First = true;\n  PrintOptions Opts = PrintOptions::printInterface();\n  \/\/ We should always print fully qualified type names here\n  Opts.FullyQualifiedTypes = true;\n  for (auto Req: AllReqs) {\n    if (!First) {\n      OS << \", \";\n    } else {\n      First = false;\n    }\n    if (Ctx.checkingABI())\n      getCanonicalRequirement(Req).print(OS, Opts);\n    else\n      Req.print(OS, Opts);\n  }\n  OS << \">\";\n  return Ctx.buffer(OS.str());\n}\n\nstatic StringRef printGenericSignature(SDKContext &Ctx, Decl *D) {\n  llvm::SmallString<32> Result;\n  llvm::raw_svector_ostream OS(Result);\n  if (auto *PD = dyn_cast<ProtocolDecl>(D)) {\n    return printGenericSignature(Ctx, PD->getRequirementSignature());\n  }\n\n  if (auto *GC = D->getAsGenericContext()) {\n    if (auto *Sig = GC->getGenericSignature()) {\n      if (Ctx.checkingABI())\n        Sig->getCanonicalSignature()->print(OS);\n      else\n        Sig->print(OS);\n      return Ctx.buffer(OS.str());\n    }\n  }\n  return StringRef();\n}\n\nstatic\nStringRef printGenericSignature(SDKContext &Ctx, ProtocolConformance *Conf) {\n  return printGenericSignature(Ctx, Conf->getConditionalRequirements());\n}\n\nstatic Optional<uint8_t> getSimilarMemberCount(NominalTypeDecl *NTD,\n                                               ValueDecl *VD,\n                                        llvm::function_ref<bool(Decl*)> Check) {\n  if (!Check(VD))\n    return None;\n  auto Members = NTD->getMembers();\n  auto End = std::find(Members.begin(), Members.end(), VD);\n  assert(End != Members.end());\n  return std::count_if(Members.begin(), End, Check);\n}\n\nOptional<uint8_t> SDKContext::getFixedBinaryOrder(ValueDecl *VD) const {\n  \/\/ We don't need fixed binary order when checking API stability.\n  if (!checkingABI())\n    return None;\n  auto *NTD = dyn_cast_or_null<NominalTypeDecl>(VD->getDeclContext()->\n    getAsDecl());\n\n  if (!NTD || isa<ProtocolDecl>(NTD) || NTD->isResilient())\n    return None;\n\n  \/\/ The relative order of stored properties matters for non-resilient type.\n  auto isStored = [](Decl *M) {\n    if (auto *STD = dyn_cast<AbstractStorageDecl>(M)) {\n      return STD->hasStorage() && !STD->isStatic();\n    }\n    return false;\n  };\n\n  switch (NTD->getKind()) {\n  case DeclKind::Enum: {\n    return getSimilarMemberCount(NTD, VD, [](Decl *M) {\n      return isa<EnumElementDecl>(M);\n    });\n  }\n  case DeclKind::Class:\n  case DeclKind::Struct: {\n    return getSimilarMemberCount(NTD, VD, isStored);\n  }\n  default:\n    llvm_unreachable(\"bad nominal type kind.\");\n  }\n}\n\n\/\/ check for if it has @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)\nstatic bool isABIPlaceHolder(Decl *D) {\n  llvm::SmallSet<PlatformKind, 4> Platforms;\n  for (auto *ATT: D->getAttrs()) {\n    if (auto *AVA = dyn_cast<AvailableAttr>(ATT)) {\n      if (AVA->Platform != PlatformKind::none && AVA->Introduced &&\n          AVA->Introduced->getMajor() == 9999) {\n        Platforms.insert(AVA->Platform);\n      }\n    }\n  }\n  return Platforms.size() == 4;\n}\n\nstatic bool isABIPlaceholderRecursive(Decl *D) {\n  for (auto *CD = D; CD; CD = CD->getDeclContext()->getAsDecl()) {\n    if (isABIPlaceHolder(CD))\n      return true;\n  }\n  return false;\n}\n\nStringRef SDKContext::getPlatformIntroVersion(Decl *D, PlatformKind Kind) {\n  if (!D)\n    return StringRef();\n  for (auto *ATT: D->getAttrs()) {\n    if (auto *AVA = dyn_cast<AvailableAttr>(ATT)) {\n      if (AVA->Platform == Kind && AVA->Introduced) {\n        return buffer(AVA->Introduced->getAsString());\n      }\n    }\n  }\n  return getPlatformIntroVersion(D->getDeclContext()->getAsDecl(), Kind);\n}\n\nStringRef SDKContext::getLanguageIntroVersion(Decl *D) {\n  if (!D)\n    return StringRef();\n  for (auto *ATT: D->getAttrs()) {\n    if (auto *AVA = dyn_cast<AvailableAttr>(ATT)) {\n      if (AVA->isLanguageVersionSpecific() && AVA->Introduced) {\n        return buffer(AVA->Introduced->getAsString());\n      }\n    }\n  }\n  return getLanguageIntroVersion(D->getDeclContext()->getAsDecl());\n}\n\nSDKNodeInitInfo::SDKNodeInitInfo(SDKContext &Ctx, Type Ty, TypeInitInfo Info) :\n    Ctx(Ctx), Name(getTypeName(Ctx, Ty, Info.IsImplicitlyUnwrappedOptional)),\n    PrintedName(getPrintedName(Ctx, Ty, Info.IsImplicitlyUnwrappedOptional)),\n    ParamValueOwnership(Info.ValueOwnership),\n    HasDefaultArg(Info.hasDefaultArgument) {\n  if (isFunctionTypeNoEscape(Ty))\n    TypeAttrs.push_back(TypeAttrKind::TAK_noescape);\n  \/\/ If this is a nominal type, get its Usr.\n  if (auto *ND = Ty->getAnyNominal()) {\n    Usr = calculateUsr(Ctx, ND);\n  }\n}\n\nSDKNodeInitInfo::SDKNodeInitInfo(SDKContext &Ctx, Decl *D):\n      Ctx(Ctx), DKind(D->getKind()),\n      Location(calculateLocation(Ctx, D)),\n      ModuleName(D->getModuleContext()->getName().str()),\n      GenericSig(printGenericSignature(Ctx, D)),\n      IntromacOS(Ctx.getPlatformIntroVersion(D, PlatformKind::OSX)),\n      IntroiOS(Ctx.getPlatformIntroVersion(D, PlatformKind::iOS)),\n      IntrotvOS(Ctx.getPlatformIntroVersion(D, PlatformKind::tvOS)),\n      IntrowatchOS(Ctx.getPlatformIntroVersion(D, PlatformKind::watchOS)),\n      Introswift(Ctx.getLanguageIntroVersion(D)),\n      IsImplicit(D->isImplicit()),\n      IsDeprecated(D->getAttrs().getDeprecated(D->getASTContext())),\n      IsABIPlaceholder(isABIPlaceholderRecursive(D)) {\n\n  \/\/ Force some attributes that are lazily computed.\n  \/\/ FIXME: we should use these AST predicates directly instead of looking at\n  \/\/ the attributes rdar:\/\/50217247.\n  if (auto *VD = dyn_cast<ValueDecl>(D)) {\n    (void) VD->isObjC();\n    (void) VD->isFinal();\n    (void) VD->isDynamic();\n  }\n\n  \/\/ Capture all attributes.\n  auto AllAttrs = D->getAttrs();\n  std::transform(AllAttrs.begin(), AllAttrs.end(), std::back_inserter(DeclAttrs),\n                 [](DeclAttribute *attr) { return attr->getKind(); });\n}\n\nSDKNodeInitInfo::SDKNodeInitInfo(SDKContext &Ctx, OperatorDecl *OD):\n    SDKNodeInitInfo(Ctx, cast<Decl>(OD)) {\n  Name = OD->getName().str();\n  PrintedName = OD->getName().str();\n}\n\n\nSDKNodeInitInfo::SDKNodeInitInfo(SDKContext &Ctx, ProtocolConformance *Conform):\n    SDKNodeInitInfo(Ctx, Conform->getProtocol()) {\n  \/\/ The conformance can be conditional. The generic signature keeps track of\n  \/\/ the requirements.\n  GenericSig = printGenericSignature(Ctx, Conform);\n  \/\/ Whether this conformance is ABI placeholder depends on the decl context\n  \/\/ of this conformance.\n  IsABIPlaceholder = isABIPlaceholderRecursive(Conform->getDeclContext()->\n                                               getAsDecl());\n}\n\nstatic bool isProtocolRequirement(ValueDecl *VD) {\n  if (isa<ProtocolDecl>(VD->getDeclContext()) && VD->isProtocolRequirement())\n    return true;\n  \/\/ If the VD is an accessor of the property declaration that is a protocol\n  \/\/ requirement, we consider this accessor as a protocol requirement too.\n  if (auto *AD = dyn_cast<AccessorDecl>(VD)) {\n    if (auto *ST = AD->getStorage()) {\n      return isProtocolRequirement(ST);\n    }\n  }\n  return false;\n}\n\nstatic bool requireWitnessTableEntry(ValueDecl *VD) {\n  if (auto *FD = dyn_cast<AbstractFunctionDecl>(VD)) {\n    return SILDeclRef::requiresNewWitnessTableEntry(FD);\n  }\n  return false;\n}\n\nSDKNodeInitInfo::SDKNodeInitInfo(SDKContext &Ctx, ValueDecl *VD)\n    : SDKNodeInitInfo(Ctx, cast<Decl>(VD)) {\n  Name = getSimpleName(VD);\n  PrintedName = getPrintedName(Ctx, VD);\n  Usr = calculateUsr(Ctx, VD);\n  IsThrowing = isFuncThrowing(VD);\n  IsStatic = VD->isStatic();\n  IsOverriding = VD->getOverriddenDecl();\n  IsProtocolReq = isProtocolRequirement(VD);\n  IsOpen = Ctx.getAccessLevel(VD) == AccessLevel::Open;\n  IsInternal = Ctx.getAccessLevel(VD) < AccessLevel::Public;\n  SelfIndex = getSelfIndex(VD);\n  FixedBinaryOrder = Ctx.getFixedBinaryOrder(VD);\n  ReferenceOwnership = getReferenceOwnership(VD);\n  ReqNewWitnessTableEntry = IsProtocolReq && requireWitnessTableEntry(VD);\n\n  \/\/ Calculate usr for its super class.\n  if (auto *CD = dyn_cast_or_null<ClassDecl>(VD)) {\n    if (auto *Super = CD->getSuperclassDecl()) {\n      SuperclassUsr = calculateUsr(Ctx, Super);\n      for (auto T = CD->getSuperclass(); T; T = T->getSuperclass()) {\n        SuperclassNames.push_back(getPrintedName(Ctx, T->getCanonicalType()));\n      }\n    }\n  }\n\n  if (auto *FD = dyn_cast<FuncDecl>(VD)) {\n    switch(FD->getSelfAccessKind()) {\n    case SelfAccessKind::Mutating:\n      FuncSelfKind = \"Mutating\";\n      break;\n    case SelfAccessKind::Consuming:\n      \/\/ FIXME: Stay consistent with earlier digests that had underscores here.\n      FuncSelfKind = \"__Consuming\";\n      break;\n    case SelfAccessKind::NonMutating:\n      FuncSelfKind = \"NonMutating\";\n      break;\n    }\n  }\n\n  \/\/ Get enum raw type name if this is an enum.\n  if (auto *ED = dyn_cast<EnumDecl>(VD)) {\n    if (auto RT = ED->getRawType()) {\n      if (auto *D = RT->getNominalOrBoundGenericNominal()) {\n        EnumRawTypeName = D->getName().str();\n      }\n    }\n  }\n  if (auto *VAD = dyn_cast<VarDecl>(VD)) {\n    IsLet = VAD->isLet();\n  }\n  if (auto *VAR = dyn_cast<AbstractStorageDecl>(VD)) {\n    HasStorage = VAR->hasStorage();\n  }\n  if (auto *ACC = dyn_cast<AccessorDecl>(VD)) {\n    AccKind = ACC->getAccessorKind();\n  }\n}\n\nSDKNode *SDKNodeInitInfo::createSDKNode(SDKNodeKind Kind) {\n  switch(Kind) {\n#define NODE_KIND(X, NAME)                                                     \\\ncase SDKNodeKind::X:                                                           \\\n  return static_cast<SDKNode*>(new (Ctx.allocator().Allocate<SDKNode##X>())    \\\n    SDKNode##X(*this));                                                        \\\n  break;\n#include \"swift\/IDE\/DigesterEnums.def\"\n  }\n  llvm_unreachable(\"covered switch\");\n}\n\n\/\/ Recursively construct a node that represents a type, for instance,\n\/\/ representing the return value type of a function decl.\nSDKNode *swift::ide::api::\nSwiftDeclCollector::constructTypeNode(Type T, TypeInitInfo Info) {\n  if (Ctx.checkingABI()) {\n    T = T->getCanonicalType();\n    \/\/ If the type is a opaque result type (some Type) and we're in the ABI mode,\n    \/\/ we should substitute the opaque result type to its underlying type.\n    \/\/ Notice this only works if the opaque result type is from an inlinable\n    \/\/ function where the function body is present in the swift module file, thus\n    \/\/ allowing us to know the concrete type.\n    if (auto OTA = T->getAs<OpaqueTypeArchetypeType>()) {\n      if (auto *D = OTA->getDecl()) {\n        if (auto SubMap = D->getUnderlyingTypeSubstitutions()) {\n          T = Type(D->getUnderlyingInterfaceType()).\n            subst(*SubMap)->getCanonicalType();\n        }\n      }\n    }\n  }\n\n  if (auto NAT = dyn_cast<TypeAliasType>(T.getPointer())) {\n    SDKNode* Root = SDKNodeInitInfo(Ctx, T, Info).createSDKNode(SDKNodeKind::TypeAlias);\n    Root->addChild(constructTypeNode(NAT->getSinglyDesugaredType()));\n    return Root;\n  }\n\n  if (auto Fun = T->getAs<AnyFunctionType>()) {\n    SDKNode* Root = SDKNodeInitInfo(Ctx, T, Info).createSDKNode(SDKNodeKind::TypeFunc);\n\n    \/\/ Still, return type first\n    Root->addChild(constructTypeNode(Fun->getResult()));\n\n    auto Input = AnyFunctionType::composeInput(Fun->getASTContext(),\n                                               Fun->getParams(),\n                                               \/*canonicalVararg=*\/false);\n    Root->addChild(constructTypeNode(Input));\n    return Root;\n  }\n\n  SDKNode* Root = SDKNodeInitInfo(Ctx, T, Info).createSDKNode(SDKNodeKind::TypeNominal);\n\n  \/\/ Keep paren type as a stand-alone level.\n  if (auto *PT = dyn_cast<ParenType>(T.getPointer())) {\n    Root->addChild(constructTypeNode(PT->getSinglyDesugaredType()));\n    return Root;\n  }\n\n  \/\/ Handle the case where Type has sub-types.\n  if (auto BGT = T->getAs<BoundGenericType>()) {\n    for (auto Arg : BGT->getGenericArgs()) {\n      Root->addChild(constructTypeNode(Arg));\n    }\n  } else if (auto Tup = T->getAs<TupleType>()) {\n    for (auto Elt : Tup->getElementTypes())\n      Root->addChild(constructTypeNode(Elt));\n  } else if (auto MTT = T->getAs<AnyMetatypeType>()) {\n    Root->addChild(constructTypeNode(MTT->getInstanceType()));\n  } else if (auto ATT = T->getAs<ArchetypeType>()) {\n    for (auto Pro : ATT->getConformsTo()) {\n      Root->addChild(constructTypeNode(Pro->getDeclaredType()));\n    }\n  }\n  return Root;\n}\n\nstd::vector<SDKNode*> swift::ide::api::\nSwiftDeclCollector::createParameterNodes(ParameterList *PL) {\n  std::vector<SDKNode*> Result;\n  for (auto param: *PL) {\n    TypeInitInfo Info;\n    Info.IsImplicitlyUnwrappedOptional = param->isImplicitlyUnwrappedOptional();\n    Info.hasDefaultArgument = param->getDefaultArgumentKind() !=\n      DefaultArgumentKind::None;\n    switch (param->getValueOwnership()) {\n#define CASE(KIND) case ValueOwnership::KIND: Info.ValueOwnership = #KIND; break;\n    CASE(Owned)\n    CASE(InOut)\n    CASE(Shared)\n    case ValueOwnership::Default: break;\n#undef CASE\n    }\n    Result.push_back(constructTypeNode(param->getInterfaceType(), Info));\n  }\n  return Result;\n}\n\n\/\/ Construct a node for a function decl. The first child of the function decl\n\/\/ is guaranteed to be the return value type of this function.\n\/\/ We sometimes skip the first parameter because it can be metatype of dynamic\n\/\/ this if the function is a member function.\nSDKNode *swift::ide::api::\nSwiftDeclCollector::constructFunctionNode(FuncDecl* FD,\n                                          SDKNodeKind Kind) {\n  auto Func = SDKNodeInitInfo(Ctx, FD).createSDKNode(Kind);\n  TypeInitInfo Info;\n  Info.IsImplicitlyUnwrappedOptional = FD->isImplicitlyUnwrappedOptional();\n  Func->addChild(constructTypeNode(FD->getResultInterfaceType(), Info));\n  for (auto *Node : createParameterNodes(FD->getParameters()))\n    Func->addChild(Node);\n  return Func;\n}\n\nSDKNode* swift::ide::api::\nSwiftDeclCollector::constructInitNode(ConstructorDecl *CD) {\n  auto Func = SDKNodeInitInfo(Ctx, CD).createSDKNode(SDKNodeKind::DeclConstructor);\n  Func->addChild(constructTypeNode(CD->getResultInterfaceType()));\n  for (auto *Node : createParameterNodes(CD->getParameters()))\n    Func->addChild(Node);\n  return Func;\n}\n\nbool swift::ide::api::\nSDKContext::shouldIgnore(Decl *D, const Decl* Parent) const {\n  \/\/ Exclude all clang nodes if we're comparing Swift decls specifically.\n  if (Opts.SwiftOnly && isFromClang(D)) {\n    return true;\n  }\n  if (auto *ACC = dyn_cast<AccessorDecl>(D)) {\n    \/\/ Only include accessors if they are part of var and subscript decl.\n    if (!isa<AbstractStorageDecl>(Parent)) {\n      return true;\n    }\n    \/\/ Only include getter\/setter if we are checking source compatibility.\n    if (!checkingABI()) {\n      switch (ACC->getAccessorKind()) {\n      case AccessorKind::Get:\n      case AccessorKind::Set:\n        break;\n      default:\n        return true;\n      }\n    }\n  }\n  if (checkingABI()) {\n    if (auto *VD = dyn_cast<ValueDecl>(D)) {\n      \/\/ Private vars with fixed binary orders can have ABI-impact, so we should\n      \/\/ whitelist them if we're checking ABI.\n      if (getFixedBinaryOrder(VD).hasValue())\n        return false;\n      \/\/ Typealias should have no impact on ABI.\n      if (isa<TypeAliasDecl>(VD))\n        return true;\n    }\n  } else {\n    if (D->isPrivateStdlibDecl(false))\n      return true;\n    if (AvailableAttr::isUnavailable(D))\n      return true;\n  }\n  if (auto VD = dyn_cast<ValueDecl>(D)) {\n    switch (getAccessLevel(VD)) {\n    case AccessLevel::Internal:\n    case AccessLevel::Private:\n    case AccessLevel::FilePrivate:\n      return true;\n    case AccessLevel::Public:\n    case AccessLevel::Open:\n      break;\n    }\n  }\n\n  if (auto *ClangD = D->getClangDecl()) {\n    if (isa<clang::ObjCIvarDecl>(ClangD))\n      return true;\n    if (isa<clang::FieldDecl>(ClangD))\n      return true;\n    if (ClangD->hasAttr<clang::SwiftPrivateAttr>())\n      return true;\n\n    \/\/ If this decl is a synthesized member from a conformed clang protocol, we\n    \/\/ should ignore this member to reduce redundancy.\n    if (Parent &&\n        !isa<swift::ProtocolDecl>(Parent) &&\n        isa<clang::ObjCProtocolDecl>(ClangD->getDeclContext()))\n      return true;\n  }\n  return false;\n}\n\nSDKNode *swift::ide::api::\nSwiftDeclCollector::constructTypeDeclNode(NominalTypeDecl *NTD) {\n  auto TypeNode = SDKNodeInitInfo(Ctx, NTD).createSDKNode(SDKNodeKind::DeclType);\n  addConformancesToTypeDecl(cast<SDKNodeDeclType>(TypeNode), NTD);\n  addMembersToRoot(TypeNode, NTD);\n  for (auto Ext : NTD->getExtensions()) {\n    HandledExtensions.insert(Ext);\n    addMembersToRoot(TypeNode, Ext);\n  }\n  return TypeNode;\n}\n\n\/\/\/ Create a node for stand-alone extensions. In the sdk dump, we don't have\n\/\/\/ a specific node for extension. Members in extensions are inlined to the\n\/\/\/ extended types. If the extended types are from a different module, we have to\n\/\/\/ synthesize this type node to include those extension members, since these\n\/\/\/ extension members are legit members of the module.\nSDKNode *swift::ide::api::\nSwiftDeclCollector::constructExternalExtensionNode(NominalTypeDecl *NTD,\n                                            ArrayRef<ExtensionDecl*> AllExts) {\n  SDKNodeInitInfo initInfo(Ctx, NTD);\n  initInfo.IsExternal = true;\n  auto *TypeNode = initInfo.createSDKNode(SDKNodeKind::DeclType);\n  addConformancesToTypeDecl(cast<SDKNodeDeclType>(TypeNode), NTD);\n\n  bool anyConformancesAdded = false;\n  \/\/ The members of the extensions are the only members of this synthesized type.\n  for (auto *Ext: AllExts) {\n    HandledExtensions.insert(Ext);\n    addMembersToRoot(TypeNode, Ext);\n\n    \/\/ Keep track if we've declared any conformances in this extension.\n    \/\/ FIXME: This is too conservative. We only _really_ care if this extension\n    \/\/        declares a conformance to any public protocols outside the module\n    \/\/        where the extended type originated. Eventually this should be\n    \/\/        updated to filter extensions that declare conformances to internal\n    \/\/        protocols that either don't inherit from any protocols or only\n    \/\/        inherit from other internal protocols. It should also consider\n    \/\/        conditional conformances with internal requirements that are still\n    \/\/        part of the ABI.\n    if (!Ext->getInherited().empty())\n      anyConformancesAdded = true;\n  }\n\n  \/\/ If none of the extensions added any public members or conformances, don't\n  \/\/ synthesize the type node.\n  if (TypeNode->getChildrenCount() == 0 && !anyConformancesAdded)\n    return nullptr;\n\n  return TypeNode;\n}\n\nSDKNode *swift::ide::api::\nSwiftDeclCollector::constructVarNode(ValueDecl *VD) {\n  auto Var = cast<SDKNodeDeclVar>(SDKNodeInitInfo(Ctx, VD).createSDKNode(SDKNodeKind::DeclVar));\n  TypeInitInfo Info;\n  Info.IsImplicitlyUnwrappedOptional = VD->isImplicitlyUnwrappedOptional();\n  Var->addChild(constructTypeNode(VD->getInterfaceType(), Info));\n  if (auto VAD = dyn_cast<AbstractStorageDecl>(VD)) {\n    for(auto *AC: VAD->getAllAccessors()) {\n      if (!Ctx.shouldIgnore(AC, VAD)) {\n        Var->addAccessor(constructFunctionNode(AC, SDKNodeKind::DeclAccessor));\n      }\n    }\n  }\n  return Var;\n}\n\nSDKNode *swift::ide::api::\nSwiftDeclCollector::constructTypeAliasNode(TypeAliasDecl *TAD) {\n  auto Alias = SDKNodeInitInfo(Ctx, TAD).createSDKNode(SDKNodeKind::DeclTypeAlias);\n  Alias->addChild(constructTypeNode(TAD->getUnderlyingTypeLoc().getType()));\n  return Alias;\n}\n\nSDKNode *swift::ide::api::\nSwiftDeclCollector::constructAssociatedTypeNode(AssociatedTypeDecl *ATD) {\n  auto Asso = SDKNodeInitInfo(Ctx, ATD).\n    createSDKNode(SDKNodeKind::DeclAssociatedType);\n  if (auto DT = ATD->getDefaultDefinitionType()) {\n    Asso->addChild(constructTypeNode(DT));\n  }\n  return Asso;\n}\n\nSDKNode *swift::ide::api::\nSwiftDeclCollector::constructSubscriptDeclNode(SubscriptDecl *SD) {\n  auto *Subs = cast<SDKNodeDeclSubscript>(SDKNodeInitInfo(Ctx, SD).\n    createSDKNode(SDKNodeKind::DeclSubscript));\n  Subs->addChild(constructTypeNode(SD->getElementInterfaceType()));\n  for (auto *Node: createParameterNodes(SD->getIndices())) {\n    Subs->addChild(Node);\n  }\n  for(auto *AC: SD->getAllAccessors()) {\n    if (!Ctx.shouldIgnore(AC, SD)) {\n      Subs->addAccessor(constructFunctionNode(AC, SDKNodeKind::DeclAccessor));\n    }\n  }\n  return Subs;\n}\n\nvoid swift::ide::api::\nSwiftDeclCollector::addMembersToRoot(SDKNode *Root, IterableDeclContext *Context) {\n  for (auto *Member : Context->getMembers()) {\n    if (Ctx.shouldIgnore(Member, Context->getDecl()))\n      continue;\n    if (auto Func = dyn_cast<FuncDecl>(Member)) {\n      Root->addChild(constructFunctionNode(Func, SDKNodeKind::DeclFunction));\n    } else if (auto CD = dyn_cast<ConstructorDecl>(Member)) {\n      Root->addChild(constructInitNode(CD));\n    } else if (auto VD = dyn_cast<VarDecl>(Member)) {\n      Root->addChild(constructVarNode(VD));\n    } else if (auto TAD = dyn_cast<TypeAliasDecl>(Member)) {\n      Root->addChild(constructTypeAliasNode(TAD));\n    } else if (auto EED = dyn_cast<EnumElementDecl>(Member)) {\n      Root->addChild(constructVarNode(EED));\n    } else if (auto NTD = dyn_cast<NominalTypeDecl>(Member)) {\n      Root->addChild(constructTypeDeclNode(NTD));\n    } else if (auto ATD = dyn_cast<AssociatedTypeDecl>(Member)) {\n      Root->addChild(constructAssociatedTypeNode(ATD));\n    } else if (auto SD = dyn_cast<SubscriptDecl>(Member)) {\n      Root->addChild(constructSubscriptDeclNode(SD));\n    } else if (isa<PatternBindingDecl>(Member)) {\n      \/\/ All containing variables should have been handled.\n    } else if (isa<DestructorDecl>(Member)) {\n      \/\/ deinit has no impact.\n    } else if (isa<MissingMemberDecl>(Member)) {\n      \/\/ avoid adding MissingMemberDecl\n    } else {\n      llvm_unreachable(\"unhandled member decl kind.\");\n    }\n  }\n}\n\nSDKNode *swift::ide::api::\nSwiftDeclCollector::constructTypeWitnessNode(AssociatedTypeDecl *Assoc,\n                                             Type Ty) {\n  auto *Witness = SDKNodeInitInfo(Ctx, Assoc).createSDKNode(SDKNodeKind::TypeWitness);\n  Witness->addChild(constructTypeNode(Ty));\n  return Witness;\n}\n\nSDKNode *swift::ide::api::\nSwiftDeclCollector::constructConformanceNode(ProtocolConformance *Conform) {\n  if (Ctx.checkingABI())\n    Conform = Conform->getCanonicalConformance();\n  auto ConfNode = cast<SDKNodeConformance>(SDKNodeInitInfo(Ctx,\n    Conform).createSDKNode(SDKNodeKind::Conformance));\n  Conform->forEachTypeWitness(\n    [&](AssociatedTypeDecl *assoc, Type ty, TypeDecl *typeDecl) -> bool {\n      ConfNode->addChild(constructTypeWitnessNode(assoc, ty));\n      return false;\n    });\n  return ConfNode;\n}\n\nvoid swift::ide::api::\nSwiftDeclCollector::addConformancesToTypeDecl(SDKNodeDeclType *Root,\n                                              NominalTypeDecl *NTD) {\n  \/\/ Avoid adding the same conformance twice.\n  SmallPtrSet<ProtocolConformance*, 4> Seen;\n  for (auto &Conf: NTD->getAllConformances()) {\n    if (!Ctx.shouldIgnore(Conf->getProtocol()) && !Seen.count(Conf))\n      Root->addConformance(constructConformanceNode(Conf));\n    Seen.insert(Conf);\n  }\n}\n\nvoid SwiftDeclCollector::printTopLevelNames() {\n  for (auto &Node : RootNode->getChildren()) {\n    llvm::outs() << Node->getKind() << \": \" << Node->getName() << '\\n';\n  }\n}\n\nvoid SwiftDeclCollector::lookupVisibleDecls(ArrayRef<ModuleDecl *> Modules) {\n  for (auto M: Modules) {\n    llvm::SmallVector<Decl*, 512> Decls;\n    M->getDisplayDecls(Decls);\n    for (auto D : Decls) {\n      if (Ctx.shouldIgnore(D))\n        continue;\n      if (KnownDecls.count(D))\n        continue;\n      KnownDecls.insert(D);\n      if (auto VD = dyn_cast<ValueDecl>(D))\n        foundDecl(VD, DeclVisibilityKind::DynamicLookup,\n                  DynamicLookupInfo::AnyObject);\n      else\n        processDecl(D);\n    }\n  }\n\n  \/\/ Now sort the macros before processing so that we can have deterministic\n  \/\/ output.\n  llvm::array_pod_sort(ClangMacros.begin(), ClangMacros.end(),\n     [](ValueDecl * const *lhs,\n        ValueDecl * const *rhs) -> int {\n       return (*lhs)->getBaseName().userFacingName().compare(\n                (*rhs)->getBaseName().userFacingName());\n     });\n\n  for (auto *VD : ClangMacros)\n    processValueDecl(VD);\n\n  \/\/ Collect extensions to types from other modules and synthesize type nodes\n  \/\/ for them.\n  llvm::MapVector<NominalTypeDecl*, llvm::SmallVector<ExtensionDecl*, 4>> ExtensionMap;\n  for (auto *D: KnownDecls) {\n    if (auto *Ext = dyn_cast<ExtensionDecl>(D)) {\n      if (HandledExtensions.find(Ext) == HandledExtensions.end()) {\n        auto *NTD = Ext->getExtendedNominal();\n        \/\/ Check if the extension is from other modules.\n        if (!llvm::is_contained(Modules, NTD->getModuleContext())) {\n          ExtensionMap[NTD].push_back(Ext);\n        }\n      }\n    }\n  }\n  for (auto Pair: ExtensionMap) {\n    if (auto child = constructExternalExtensionNode(Pair.first, Pair.second))\n      RootNode->addChild(child);\n  }\n}\n\nSDKNode *SwiftDeclCollector::constructOperatorDeclNode(OperatorDecl *OD) {\n  return SDKNodeInitInfo(Ctx, OD).createSDKNode(SDKNodeKind::DeclOperator);\n}\n\nvoid SwiftDeclCollector::processDecl(Decl *D) {\n  assert(!isa<ValueDecl>(D));\n  if (auto *OD = dyn_cast<OperatorDecl>(D)) {\n    RootNode->addChild(constructOperatorDeclNode(OD));\n  }\n}\n\nvoid SwiftDeclCollector::processValueDecl(ValueDecl *VD) {\n  if (auto FD = dyn_cast<FuncDecl>(VD)) {\n    RootNode->addChild(constructFunctionNode(FD, SDKNodeKind::DeclFunction));\n  } else if (auto NTD = dyn_cast<NominalTypeDecl>(VD)) {\n    RootNode->addChild(constructTypeDeclNode(NTD));\n  } else if (auto VAD = dyn_cast<VarDecl>(VD)) {\n    RootNode->addChild(constructVarNode(VAD));\n  } else if (auto TAD = dyn_cast<TypeAliasDecl>(VD)) {\n    RootNode->addChild(constructTypeAliasNode(TAD));\n  } else {\n    llvm_unreachable(\"unhandled value decl\");\n  }\n}\n\nvoid SwiftDeclCollector::foundDecl(ValueDecl *VD, DeclVisibilityKind Reason,\n                                   DynamicLookupInfo) {\n  if (VD->getClangMacro()) {\n    \/\/ Collect macros, we will sort them afterwards.\n    ClangMacros.push_back(VD);\n    return;\n  }\n\n  processValueDecl(VD);\n}\n\nvoid SDKNode::output(json::Output &out, KeyKind Key, bool Value) {\n  if (Value)\n    out.mapRequired(getKeyContent(Ctx, Key).data(), Value);\n}\n\nvoid SDKNode::output(json::Output &out, KeyKind Key, StringRef Value) {\n  if (!Value.empty())\n    out.mapRequired(getKeyContent(Ctx, Key).data(), Value);\n}\n\nvoid SDKNode::jsonize(json::Output &out) {\n  auto Kind = getKind();\n  out.mapRequired(getKeyContent(Ctx, KeyKind::KK_kind).data(), Kind);\n  output(out, KeyKind::KK_name, Name);\n  output(out, KeyKind::KK_printedName, PrintedName);\n  out.mapOptional(getKeyContent(Ctx, KeyKind::KK_children).data(), Children);\n}\n\nvoid SDKNodeRoot::jsonize(json::Output &out) {\n  SDKNode::jsonize(out);\n  out.mapRequired(getKeyContent(Ctx, KeyKind::KK_json_format_version).data(), JsonFormatVer);\n  if (!Ctx.getOpts().AvoidToolArgs)\n    out.mapOptional(getKeyContent(Ctx, KeyKind::KK_tool_arguments).data(), ToolArgs);\n}\n\nvoid SDKNodeConformance::jsonize(json::Output &out) {\n  SDKNode::jsonize(out);\n  output(out, KeyKind::KK_usr, Usr);\n  output(out, KeyKind::KK_isABIPlaceholder, IsABIPlaceholder);\n}\n\nvoid SDKNodeDecl::jsonize(json::Output &out) {\n  SDKNode::jsonize(out);\n  out.mapRequired(getKeyContent(Ctx, KeyKind::KK_declKind).data(), DKind);\n  output(out, KeyKind::KK_usr, Usr);\n  output(out, KeyKind::KK_location, Location);\n  output(out, KeyKind::KK_moduleName, ModuleName);\n  output(out, KeyKind::KK_genericSig, GenericSig);\n  output(out, KeyKind::KK_static, IsStatic);\n  output(out, KeyKind::KK_deprecated,IsDeprecated);\n  output(out, KeyKind::KK_protocolReq, IsProtocolReq);\n  output(out, KeyKind::KK_overriding, IsOverriding);\n  output(out, KeyKind::KK_implicit, IsImplicit);\n  output(out, KeyKind::KK_isOpen, IsOpen);\n  output(out, KeyKind::KK_isInternal, IsInternal);\n  output(out, KeyKind::KK_isABIPlaceholder, IsABIPlaceholder);\n  output(out, KeyKind::KK_intro_Macosx, introVersions.macos);\n  output(out, KeyKind::KK_intro_iOS, introVersions.ios);\n  output(out, KeyKind::KK_intro_tvOS, introVersions.tvos);\n  output(out, KeyKind::KK_intro_watchOS, introVersions.watchos);\n  output(out, KeyKind::KK_intro_swift, introVersions.swift);\n  out.mapOptional(getKeyContent(Ctx, KeyKind::KK_declAttributes).data(), DeclAttributes);\n  out.mapOptional(getKeyContent(Ctx, KeyKind::KK_fixedbinaryorder).data(), FixedBinaryOrder);\n  \/\/ Strong reference is implied, no need for serialization.\n  if (getReferenceOwnership() != ReferenceOwnership::Strong) {\n    uint8_t Raw = uint8_t(getReferenceOwnership());\n    out.mapRequired(getKeyContent(Ctx, KeyKind::KK_ownership).data(), Raw);\n  }\n}\n\nvoid SDKNodeDeclAbstractFunc::jsonize(json::Output &out) {\n  SDKNodeDecl::jsonize(out);\n  output(out, KeyKind::KK_throwing, IsThrowing);\n  output(out, KeyKind::KK_reqNewWitnessTableEntry, ReqNewWitnessTableEntry);\n  out.mapOptional(getKeyContent(Ctx, KeyKind::KK_selfIndex).data(), SelfIndex);\n}\n\nvoid SDKNodeDeclFunction::jsonize(json::Output &out) {\n  SDKNodeDeclAbstractFunc::jsonize(out);\n  output(out, KeyKind::KK_funcSelfKind, FuncSelfKind);\n}\n\nvoid SDKNodeDeclType::jsonize(json::Output &out) {\n  SDKNodeDecl::jsonize(out);\n  output(out, KeyKind::KK_superclassUsr, SuperclassUsr);\n  output(out, KeyKind::KK_enumRawTypeName, EnumRawTypeName);\n  output(out, KeyKind::KK_isExternal, IsExternal);\n  out.mapOptional(getKeyContent(Ctx, KeyKind::KK_superclassNames).data(), SuperclassNames);\n  out.mapOptional(getKeyContent(Ctx, KeyKind::KK_conformances).data(), Conformances);\n}\n\nvoid SDKNodeType::jsonize(json::Output &out) {\n  SDKNode::jsonize(out);\n  out.mapOptional(getKeyContent(Ctx, KeyKind::KK_typeAttributes).data(), TypeAttributes);\n  output(out, KeyKind::KK_hasDefaultArg, HasDefaultArg);\n  output(out, KeyKind::KK_paramValueOwnership, ParamValueOwnership);\n}\n\nvoid SDKNodeTypeNominal::jsonize(json::Output &out) {\n  SDKNodeType::jsonize(out);\n  output(out, KeyKind::KK_usr, USR);\n}\n\nvoid SDKNodeDeclSubscript::jsonize(json::Output &out) {\n  SDKNodeDeclAbstractFunc::jsonize(out);\n  output(out, KeyKind::KK_hasStorage, HasStorage);\n  out.mapOptional(getKeyContent(Ctx, KeyKind::KK_accessors).data(), Accessors);\n}\n\nvoid SDKNodeDeclVar::jsonize(json::Output &out) {\n  SDKNodeDecl::jsonize(out);\n  output(out, KeyKind::KK_isLet, IsLet);\n  output(out, KeyKind::KK_hasStorage, HasStorage);\n  out.mapOptional(getKeyContent(Ctx, KeyKind::KK_accessors).data(), Accessors);\n}\n\nvoid SDKNodeDeclAccessor::jsonize(json::Output &out) {\n  SDKNodeDeclAbstractFunc::jsonize(out);\n  out.mapRequired(getKeyContent(Ctx, KeyKind::KK_accessorKind).data(), AccKind);\n}\n\n\nnamespace swift {\nnamespace json {\n\/\/ In the namespace of swift::json, we define several functions so that the\n\/\/ JSON serializer will know how to interpret and dump types defined in this\n\/\/ file.\ntemplate<>\nstruct ScalarEnumerationTraits<TypeAttrKind> {\n  static void enumeration(Output &out, TypeAttrKind &value) {\n#define TYPE_ATTR(X) out.enumCase(value, #X, TypeAttrKind::TAK_##X);\n#include \"swift\/AST\/Attr.def\"\n  }\n};\n\ntemplate<>\nstruct ScalarEnumerationTraits<DeclAttrKind> {\n  static void enumeration(Output &out, DeclAttrKind &value) {\n#define DECL_ATTR(_, Name, ...) out.enumCase(value, #Name, DeclAttrKind::DAK_##Name);\n#include \"swift\/AST\/Attr.def\"\n  }\n};\n\ntemplate<>\nstruct ScalarEnumerationTraits<DeclKind> {\n  static void enumeration(Output &out, DeclKind &value) {\n#define DECL(X, PARENT) out.enumCase(value, #X, DeclKind::X);\n#include \"swift\/AST\/DeclNodes.def\"\n  }\n};\n\ntemplate<>\nstruct ScalarEnumerationTraits<AccessorKind> {\n  static void enumeration(Output &out, AccessorKind &value) {\n#define ACCESSOR(ID)\n#define SINGLETON_ACCESSOR(ID, KEYWORD) \\\n  out.enumCase(value, #KEYWORD, AccessorKind::ID);\n#include \"swift\/AST\/AccessorKinds.def\"\n  }\n};\n\ntemplate<>\nstruct ObjectTraits<SDKNode *> {\n  static void mapping(Output &out, SDKNode *&value) {\n    value->jsonize(out);\n  }\n};\n\ntemplate<>\nstruct ArrayTraits<ArrayRef<SDKNode*>> {\n  static size_t size(Output &out, ArrayRef<SDKNode *> &seq) {\n    return seq.size();\n  }\n  static SDKNode *&element(Output &, ArrayRef<SDKNode *> &seq,\n                                size_t index) {\n    return const_cast<SDKNode *&>(seq[index]);\n  }\n};\n\ntemplate<>\nstruct ArrayTraits<ArrayRef<TypeAttrKind>> {\n  static size_t size(Output &out, ArrayRef<TypeAttrKind> &seq) {\n    return seq.size();\n  }\n  static TypeAttrKind& element(Output &, ArrayRef<TypeAttrKind> &seq,\n                               size_t index) {\n    return const_cast<TypeAttrKind&>(seq[index]);\n  }\n};\n\ntemplate<>\nstruct ArrayTraits<ArrayRef<DeclAttrKind>> {\n  static size_t size(Output &out, ArrayRef<DeclAttrKind> &seq) {\n    return seq.size();\n  }\n  static DeclAttrKind& element(Output &, ArrayRef<DeclAttrKind> &seq,\n                               size_t index) {\n    return const_cast<DeclAttrKind&>(seq[index]);\n  }\n};\ntemplate<>\nstruct ArrayTraits<ArrayRef<StringRef>> {\n  static size_t size(Output &out, ArrayRef<StringRef> &seq) {\n    return seq.size();\n  }\n  static StringRef& element(Output &, ArrayRef<StringRef> &seq,\n                               size_t index) {\n    return const_cast<StringRef&>(seq[index]);\n  }\n};\n} \/\/ namespace json\n} \/\/ namespace swift\n\nnamespace  {\/\/ Anonymous namespace.\n\/\/ Deserialize an SDKNode tree.\nstd::pair<std::unique_ptr<llvm::MemoryBuffer>, SDKNode*>\nstatic parseJsonEmit(SDKContext &Ctx, StringRef FileName) {\n  namespace yaml = llvm::yaml;\n\n  \/\/ Load the input file.\n  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =\n    vfs::getFileOrSTDIN(*Ctx.getSourceMgr().getFileSystem(), FileName);\n  if (!FileBufOrErr) {\n    llvm_unreachable(\"Failed to read JSON file\");\n  }\n  StringRef Buffer = FileBufOrErr->get()->getBuffer();\n  yaml::Stream Stream(llvm::MemoryBufferRef(Buffer, FileName),\n                      Ctx.getSourceMgr().getLLVMSourceMgr());\n  SDKNode *Result = nullptr;\n  for (auto DI = Stream.begin(); DI != Stream.end(); ++ DI) {\n    assert(DI != Stream.end() && \"Failed to read a document\");\n    yaml::Node *N = DI->getRoot();\n    assert(N && \"Failed to find a root\");\n    Result = SDKNode::constructSDKNode(Ctx, cast<yaml::MappingNode>(N));\n  }\n  return {std::move(FileBufOrErr.get()), Result};\n}\n} \/\/ End of anonymous namespace\n\n\/\/ Construct all roots vector from a given file where a forest was\n\/\/ previously dumped.\nvoid SwiftDeclCollector::deSerialize(StringRef Filename) {\n  auto Pair = parseJsonEmit(Ctx, Filename);\n  OwnedBuffers.push_back(std::move(Pair.first));\n  RootNode = std::move(Pair.second);\n}\n\n\/\/ Serialize the content of all roots to a given file using JSON format.\nvoid SwiftDeclCollector::serialize(StringRef Filename, SDKNode *Root) {\n  std::error_code EC;\n  llvm::raw_fd_ostream fs(Filename, EC, llvm::sys::fs::F_None);\n  json::Output yout(fs);\n  yout << Root;\n}\n\n\/\/ Serialize the content of all roots to a given file using JSON format.\nvoid SwiftDeclCollector::serialize(StringRef Filename) {\n  SwiftDeclCollector::serialize(Filename, RootNode);\n}\n\nSDKNodeRoot *\nswift::ide::api::getEmptySDKNodeRoot(SDKContext &SDKCtx) {\n  SwiftDeclCollector Collector(SDKCtx);\n  return Collector.getSDKRoot();\n}\n\nSDKNodeRoot*\nswift::ide::api::getSDKNodeRoot(SDKContext &SDKCtx,\n                                 const CompilerInvocation &InitInvok,\n                                 const llvm::StringSet<> &ModuleNames) {\n  CheckerOptions Opts = SDKCtx.getOpts();\n  CompilerInvocation Invocation(InitInvok);\n\n  CompilerInstance &CI = SDKCtx.newCompilerInstance();\n  \/\/ Display diagnostics to stderr.\n  PrintingDiagnosticConsumer PrintDiags(llvm::errs());\n  if (llvm::errs().has_colors())\n    PrintDiags.forceColors();\n  CI.addDiagnosticConsumer(&PrintDiags);\n  if (CI.setup(Invocation)) {\n    llvm::errs() << \"Failed to setup the compiler instance\\n\";\n    return nullptr;\n  }\n\n  auto &Ctx = CI.getASTContext();\n\n\n  \/\/ Load standard library so that Clang importer can use it.\n  auto *Stdlib = Ctx.getStdlibModule(\/*loadIfAbsent=*\/true);\n  if (!Stdlib) {\n    llvm::errs() << \"Failed to load Swift stdlib\\n\";\n    return nullptr;\n  }\n\n  std::vector<ModuleDecl *> Modules;\n  for (auto &Entry : ModuleNames) {\n    StringRef Name = Entry.getKey();\n    if (Opts.Verbose)\n      llvm::errs() << \"Loading module: \" << Name << \"...\\n\";\n    auto *M = Ctx.getModuleByName(Name);\n    if (!M || M->failedToLoad() || Ctx.Diags.hadAnyError()) {\n      llvm::errs() << \"Failed to load module: \" << Name << '\\n';\n      if (Opts.AbortOnModuleLoadFailure)\n        return nullptr;\n    } else {\n      Modules.push_back(M);\n    }\n  }\n  if (Opts.Verbose)\n    llvm::errs() << \"Scanning symbols...\\n\";\n\n  SwiftDeclCollector Collector(SDKCtx);\n  Collector.lookupVisibleDecls(Modules);\n  return Collector.getSDKRoot();\n}\n\nvoid swift::ide::api::dumpSDKRoot(SDKNodeRoot *Root, StringRef OutputFile) {\n  assert(Root);\n  auto Opts = Root->getSDKContext().getOpts();\n  if (Opts.Verbose)\n    llvm::errs() << \"Dumping SDK...\\n\";\n  SwiftDeclCollector::serialize(OutputFile, Root);\n  if (Opts.Verbose)\n    llvm::errs() << \"Dumped to \"<< OutputFile << \"\\n\";\n}\n\nint swift::ide::api::dumpSDKContent(const CompilerInvocation &InitInvok,\n                                    const llvm::StringSet<> &ModuleNames,\n                                    StringRef OutputFile, CheckerOptions Opts) {\n  SDKContext SDKCtx(Opts);\n  SDKNodeRoot *Root = getSDKNodeRoot(SDKCtx, InitInvok, ModuleNames);\n  if (!Root)\n    return 1;\n  dumpSDKRoot(Root, OutputFile);\n  return 0;\n}\n\nint swift::ide::api::deserializeSDKDump(StringRef dumpPath, StringRef OutputPath,\n    CheckerOptions Opts) {\n  std::error_code EC;\n  llvm::raw_fd_ostream FS(OutputPath, EC, llvm::sys::fs::F_None);\n  if (!fs::exists(dumpPath)) {\n    llvm::errs() << dumpPath << \" does not exist\\n\";\n    return 1;\n  }\n  PrintingDiagnosticConsumer PDC;\n  SDKContext Ctx(Opts);\n  Ctx.getDiags().addConsumer(PDC);\n\n  SwiftDeclCollector Collector(Ctx);\n  Collector.deSerialize(dumpPath);\n  Collector.serialize(OutputPath);\n  return 0;\n}\n\nint swift::ide::api::findDeclUsr(StringRef dumpPath, CheckerOptions Opts) {\n  std::error_code EC;\n  if (!fs::exists(dumpPath)) {\n    llvm::errs() << dumpPath << \" does not exist\\n\";\n    return 1;\n  }\n  PrintingDiagnosticConsumer PDC;\n  SDKContext Ctx(Opts);\n  Ctx.getDiags().addConsumer(PDC);\n\n  SwiftDeclCollector Collector(Ctx);\n  Collector.deSerialize(dumpPath);\n  struct FinderByLocation: SDKNodeVisitor {\n    StringRef Location;\n    FinderByLocation(StringRef Location): Location(Location) {}\n    void visit(SDKNode* Node) override {\n      if (auto *D = dyn_cast<SDKNodeDecl>(Node)) {\n        if (D->getLocation().find(Location) != StringRef::npos &&\n            !D->getUsr().empty()) {\n          llvm::outs() << D->getFullyQualifiedName() << \": \" << D->getUsr() << \"\\n\";\n        }\n      }\n    }\n  };\n  if (!Opts.LocationFilter.empty()) {\n    FinderByLocation Finder(Opts.LocationFilter);\n    Collector.visitAllRoots(Finder);\n  }\n  return 0;\n}\n","avg_line_length":34.575978162,"max_line_length":103,"alphanum_fraction":0.6673070344,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2311,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"#include \"c4\/format.hpp\"\n\n#ifdef __clang__\n#   pragma clang diagnostic push\n#   pragma clang diagnostic ignored \"-Wformat-nonliteral\"\n#elif defined(__GNUC__)\n#   pragma GCC diagnostic push\n#   pragma GCC diagnostic ignored \"-Wformat-nonliteral\"\n#endif\n\nnamespace c4 {\n\nsize_t sprintf(substr buf, const char *fmt, ...)\n{\n    va_list args;\n    va_start(args, fmt);\n\n    \/* vsnprintf() returns number of characters written if successful or\n     * negative value if an error occurred. If the resulting string gets\n     * truncated due to buf_size limit, returns the total number of\n     * characters (not including the terminating null-byte) which would have\n     * been written, if the limit was not imposed.\n     *\n     * @see http:\/\/en.cppreference.com\/w\/cpp\/io\/c\/vfprintf\n     *\/\n    int inum = ::vsnprintf(buf.str, buf.len, fmt, args);\n\n    \/* if the retval is negative, maybe there's a formatting error so it's\n     * impossible to know the length of the needed string.\n     *\n     * So return a huge value to try to cause a mess to let the client know\n     * early. *\/\n    size_t snum = inum >= 0 ? (size_t)inum : (size_t)-1;\n\n    va_end(args);\n\n    return snum;\n}\n\n\nsize_t to_chars(substr buf, fmt::const_raw_wrapper r)\n{\n    void * vptr = buf.str;\n    size_t space = buf.len;\n    auto ptr = (decltype(buf.str)) std::align(r.alignment, r.len, vptr, space);\n    if(ptr == nullptr)\n    {\n        \/\/ if it was not possible to align, return a conservative estimate\n        \/\/ of the required space\n        return r.alignment + r.len;\n    }\n    C4_CHECK(ptr >= buf.begin() && ptr <= buf.end());\n    size_t sz = static_cast<size_t>(ptr - buf.str) + r.len;\n    if(sz <= buf.len)\n    {\n        memcpy(ptr, r.buf, r.len);\n    }\n    return sz;\n}\n\n\nsize_t from_chars(csubstr buf, fmt::raw_wrapper *r)\n{\n    void * vptr = (void*)buf.str;\n    size_t space = buf.len;\n    auto ptr = (decltype(buf.str)) std::align(r->alignment, r->len, vptr, space);\n    C4_CHECK(ptr != nullptr);\n    C4_CHECK(ptr >= buf.begin() && ptr <= buf.end());\n    \/\/size_t dim = (ptr - buf.str) + r->len;\n    memcpy(r->buf, ptr, r->len);\n    size_t sz = static_cast<size_t>(ptr - buf.str) + r->len;\n    return sz;\n}\n\n\n} \/\/ namespace c4\n\n#ifdef __clang__\n#   pragma clang diagnostic pop\n#elif defined(__GNUC__)\n#   pragma GCC diagnostic pop\n#endif\n","avg_line_length":27.843373494,"max_line_length":81,"alphanum_fraction":0.6391172653,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":48402,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2018-2019 The Gold BCR Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <script\/descriptor.h>\n\n#include <key_io.h>\n#include <pubkey.h>\n#include <script\/script.h>\n#include <script\/standard.h>\n\n#include <span.h>\n#include <util\/bip32.h>\n#include <util\/spanparsing.h>\n#include <util\/system.h>\n#include <util\/strencodings.h>\n#include <util\/vector.h>\n\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Checksum                                                               \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ This section implements a checksum algorithm for descriptors with the\n\/\/ following properties:\n\/\/ * Mistakes in a descriptor string are measured in \"symbol errors\". The higher\n\/\/   the number of symbol errors, the harder it is to detect:\n\/\/   * An error substituting a character from 0123456789()[],'\/*abcdefgh@:$%{} for\n\/\/     another in that set always counts as 1 symbol error.\n\/\/     * Note that hex encoded keys are covered by these characters. Xprvs and\n\/\/       xpubs use other characters too, but already have their own checksum\n\/\/       mechanism.\n\/\/     * Function names like \"multi()\" use other characters, but mistakes in\n\/\/       these would generally result in an unparsable descriptor.\n\/\/   * A case error always counts as 1 symbol error.\n\/\/   * Any other 1 character substitution error counts as 1 or 2 symbol errors.\n\/\/ * Any 1 symbol error is always detected.\n\/\/ * Any 2 or 3 symbol error in a descriptor of up to 49154 characters is always detected.\n\/\/ * Any 4 symbol error in a descriptor of up to 507 characters is always detected.\n\/\/ * Any 5 symbol error in a descriptor of up to 77 characters is always detected.\n\/\/ * Is optimized to minimize the chance a 5 symbol error in a descriptor up to 387 characters is undetected\n\/\/ * Random errors have a chance of 1 in 2**40 of being undetected.\n\/\/\n\/\/ These properties are achieved by expanding every group of 3 (non checksum) characters into\n\/\/ 4 GF(32) symbols, over which a cyclic code is defined.\n\n\/*\n * Interprets c as 8 groups of 5 bits which are the coefficients of a degree 8 polynomial over GF(32),\n * multiplies that polynomial by x, computes its remainder modulo a generator, and adds the constant term val.\n *\n * This generator is G(x) = x^8 + {30}x^7 + {23}x^6 + {15}x^5 + {14}x^4 + {10}x^3 + {6}x^2 + {12}x + {9}.\n * It is chosen to define an cyclic error detecting code which is selected by:\n * - Starting from all BCH codes over GF(32) of degree 8 and below, which by construction guarantee detecting\n *   3 errors in windows up to 19000 symbols.\n * - Taking all those generators, and for degree 7 ones, extend them to degree 8 by adding all degree-1 factors.\n * - Selecting just the set of generators that guarantee detecting 4 errors in a window of length 512.\n * - Selecting one of those with best worst-case behavior for 5 errors in windows of length up to 512.\n *\n * The generator and the constants to implement it can be verified using this Sage code:\n *   B = GF(2) # Binary field\n *   BP.<b> = B[] # Polynomials over the binary field\n *   F_mod = b**5 + b**3 + 1\n *   F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition\n *   FP.<x> = F[] # Polynomials over GF(32)\n *   E_mod = x**3 + x + F.fetch_int(8)\n *   E.<e> = F.extension(E_mod) # Extension field definition\n *   alpha = e**2743 # Choice of an element in extension field\n *   for p in divisors(E.order() - 1): # Verify alpha has order 32767.\n *       assert((alpha**p == 1) == (p % 32767 == 0))\n *   G = lcm([(alpha**i).minpoly() for i in [1056,1057,1058]] + [x + 1])\n *   print(G) # Print out the generator\n *   for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(G mod x^8), packed in hex integers.\n *       v = 0\n *       for coef in reversed((F.fetch_int(i)*(G % x**8)).coefficients(sparse=True)):\n *           v = v*32 + coef.integer_representation()\n *       print(\"0x%x\" % v)\n *\/\nuint64_t PolyMod(uint64_t c, int val)\n{\n    uint8_t c0 = c >> 35;\n    c = ((c & 0x7ffffffff) << 5) ^ val;\n    if (c0 & 1) c ^= 0xf5dee51989;\n    if (c0 & 2) c ^= 0xa9fdca3312;\n    if (c0 & 4) c ^= 0x1bab10e32d;\n    if (c0 & 8) c ^= 0x3706b1677a;\n    if (c0 & 16) c ^= 0x644d626ffd;\n    return c;\n}\n\nstd::string DescriptorChecksum(const Span<const char>& span)\n{\n    \/** A character set designed such that:\n     *  - The most common 'unprotected' descriptor characters (hex, keypaths) are in the first group of 32.\n     *  - Case errors cause an offset that's a multiple of 32.\n     *  - As many alphabetic characters are in the same group (while following the above restrictions).\n     *\n     * If p(x) gives the position of a character c in this character set, every group of 3 characters\n     * (a,b,c) is encoded as the 4 symbols (p(a) & 31, p(b) & 31, p(c) & 31, (p(a) \/ 32) + 3 * (p(b) \/ 32) + 9 * (p(c) \/ 32).\n     * This means that changes that only affect the lower 5 bits of the position, or only the higher 2 bits, will just\n     * affect a single symbol.\n     *\n     * As a result, within-group-of-32 errors count as 1 symbol, as do cross-group errors that don't affect\n     * the position within the groups.\n     *\/\n    static std::string INPUT_CHARSET =\n        \"0123456789()[],'\/*abcdefgh@:$%{}\"\n        \"IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~\"\n        \"ijklmnopqrstuvwxyzABCDEFGH`#\\\"\\\\ \";\n\n    \/** The character set for the checksum itself (same as bech32). *\/\n    static std::string CHECKSUM_CHARSET = \"qpzry9x8gf2tvdw0s3jn54khce6mua7l\";\n\n    uint64_t c = 1;\n    int cls = 0;\n    int clscount = 0;\n    for (auto ch : span) {\n        auto pos = INPUT_CHARSET.find(ch);\n        if (pos == std::string::npos) return \"\";\n        c = PolyMod(c, pos & 31); \/\/ Emit a symbol for the position inside the group, for every character.\n        cls = cls * 3 + (pos >> 5); \/\/ Accumulate the group numbers\n        if (++clscount == 3) {\n            \/\/ Emit an extra symbol representing the group numbers, for every 3 characters.\n            c = PolyMod(c, cls);\n            cls = 0;\n            clscount = 0;\n        }\n    }\n    if (clscount > 0) c = PolyMod(c, cls);\n    for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); \/\/ Shift further to determine the checksum.\n    c ^= 1; \/\/ Prevent appending zeroes from not affecting the checksum.\n\n    std::string ret(8, ' ');\n    for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];\n    return ret;\n}\n\nstd::string AddChecksum(const std::string& str) { return str + \"#\" + DescriptorChecksum(MakeSpan(str)); }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Internal representation                                                \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef std::vector<uint32_t> KeyPath;\n\n\/** Interface for public key objects in descriptors. *\/\nstruct PubkeyProvider\n{\nprotected:\n    \/\/! Index of this key expression in the descriptor\n    \/\/! E.g. If this PubkeyProvider is key1 in multi(2, key1, key2, key3), then m_expr_index = 0\n    uint32_t m_expr_index;\n\npublic:\n    PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}\n\n    virtual ~PubkeyProvider() = default;\n\n    \/** Derive a public key.\n     *  read_cache is the cache to read keys from (if not nullptr)\n     *  write_cache is the cache to write keys to (if not nullptr)\n     *  Caches are not exclusive but this is not tested. Currently we use them exclusively\n     *\/\n    virtual bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) = 0;\n\n    \/** Whether this represent multiple public keys at different positions. *\/\n    virtual bool IsRange() const = 0;\n\n    \/** Get the size of the generated public key(s) in bytes (33 or 65). *\/\n    virtual size_t GetSize() const = 0;\n\n    \/** Get the descriptor string form. *\/\n    virtual std::string ToString() const = 0;\n\n    \/** Get the descriptor string form including private data (if available in arg). *\/\n    virtual bool ToPrivateString(const SigningProvider& arg, std::string& out) const = 0;\n\n    \/** Derive a private key, if private data is available in arg. *\/\n    virtual bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const = 0;\n};\n\nclass OriginPubkeyProvider final : public PubkeyProvider\n{\n    KeyOriginInfo m_origin;\n    std::unique_ptr<PubkeyProvider> m_provider;\n\n    std::string OriginString() const\n    {\n        return HexStr(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint)) + FormatHDKeypath(m_origin.path);\n    }\n\npublic:\n    OriginPubkeyProvider(uint32_t exp_index, KeyOriginInfo info, std::unique_ptr<PubkeyProvider> provider) : PubkeyProvider(exp_index), m_origin(std::move(info)), m_provider(std::move(provider)) {}\n    bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) override\n    {\n        if (!m_provider->GetPubKey(pos, arg, key, info, read_cache, write_cache)) return false;\n        std::copy(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint), info.fingerprint);\n        info.path.insert(info.path.begin(), m_origin.path.begin(), m_origin.path.end());\n        return true;\n    }\n    bool IsRange() const override { return m_provider->IsRange(); }\n    size_t GetSize() const override { return m_provider->GetSize(); }\n    std::string ToString() const override { return \"[\" + OriginString() + \"]\" + m_provider->ToString(); }\n    bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override\n    {\n        std::string sub;\n        if (!m_provider->ToPrivateString(arg, sub)) return false;\n        ret = \"[\" + OriginString() + \"]\" + std::move(sub);\n        return true;\n    }\n    bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override\n    {\n        return m_provider->GetPrivKey(pos, arg, key);\n    }\n};\n\n\/** An object representing a parsed constant public key in a descriptor. *\/\nclass ConstPubkeyProvider final : public PubkeyProvider\n{\n    CPubKey m_pubkey;\n\npublic:\n    ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey) : PubkeyProvider(exp_index), m_pubkey(pubkey) {}\n    bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) override\n    {\n        key = m_pubkey;\n        info.path.clear();\n        CKeyID keyid = m_pubkey.GetID();\n        std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);\n        return true;\n    }\n    bool IsRange() const override { return false; }\n    size_t GetSize() const override { return m_pubkey.size(); }\n    std::string ToString() const override { return HexStr(m_pubkey.begin(), m_pubkey.end()); }\n    bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override\n    {\n        CKey key;\n        if (!arg.GetKey(m_pubkey.GetID(), key)) return false;\n        ret = EncodeSecret(key);\n        return true;\n    }\n    bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override\n    {\n        return arg.GetKey(m_pubkey.GetID(), key);\n    }\n};\n\nenum class DeriveType {\n    NO,\n    UNHARDENED,\n    HARDENED,\n};\n\n\/** An object representing a parsed extended public key in a descriptor. *\/\nclass BIP32PubkeyProvider final : public PubkeyProvider\n{\n    \/\/ Root xpub, path, and final derivation step type being used, if any\n    CExtPubKey m_root_extkey;\n    KeyPath m_path;\n    DeriveType m_derive;\n    \/\/ Cache of the parent of the final derived pubkeys.\n    \/\/ Primarily useful for situations when no read_cache is provided\n    CExtPubKey m_cached_xpub;\n\n    bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const\n    {\n        CKey key;\n        if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;\n        ret.nDepth = m_root_extkey.nDepth;\n        std::copy(m_root_extkey.vchFingerprint, m_root_extkey.vchFingerprint + sizeof(ret.vchFingerprint), ret.vchFingerprint);\n        ret.nChild = m_root_extkey.nChild;\n        ret.chaincode = m_root_extkey.chaincode;\n        ret.key = key;\n        return true;\n    }\n\n    \/\/ Derives the last xprv\n    bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv) const\n    {\n        if (!GetExtKey(arg, xprv)) return false;\n        for (auto entry : m_path) {\n            xprv.Derive(xprv, entry);\n        }\n        return true;\n    }\n\n    bool IsHardened() const\n    {\n        if (m_derive == DeriveType::HARDENED) return true;\n        for (auto entry : m_path) {\n            if (entry >> 31) return true;\n        }\n        return false;\n    }\n\npublic:\n    BIP32PubkeyProvider(uint32_t exp_index, const CExtPubKey& extkey, KeyPath path, DeriveType derive) : PubkeyProvider(exp_index), m_root_extkey(extkey), m_path(std::move(path)), m_derive(derive) {}\n    bool IsRange() const override { return m_derive != DeriveType::NO; }\n    size_t GetSize() const override { return 33; }\n    bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key_out, KeyOriginInfo& final_info_out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) override\n    {\n        \/\/ Info of parent of the to be derived pubkey\n        KeyOriginInfo parent_info;\n        CKeyID keyid = m_root_extkey.pubkey.GetID();\n        std::copy(keyid.begin(), keyid.begin() + sizeof(parent_info.fingerprint), parent_info.fingerprint);\n        parent_info.path = m_path;\n\n        \/\/ Info of the derived key itself which is copied out upon successful completion\n        KeyOriginInfo final_info_out_tmp = parent_info;\n        if (m_derive == DeriveType::UNHARDENED) final_info_out_tmp.path.push_back((uint32_t)pos);\n        if (m_derive == DeriveType::HARDENED) final_info_out_tmp.path.push_back(((uint32_t)pos) | 0x80000000L);\n\n        \/\/ Derive keys or fetch them from cache\n        CExtPubKey final_extkey = m_root_extkey;\n        CExtPubKey parent_extkey = m_root_extkey;\n        bool der = true;\n        if (read_cache) {\n            if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {\n                if (m_derive == DeriveType::HARDENED) return false;\n                \/\/ Try to get the derivation parent\n                if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return false;\n                final_extkey = parent_extkey;\n                if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);\n            }\n        } else if (m_cached_xpub.pubkey.IsValid() && m_derive != DeriveType::HARDENED) {\n            parent_extkey = final_extkey = m_cached_xpub;\n            if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);\n        } else if (IsHardened()) {\n            CExtKey xprv;\n            if (!GetDerivedExtKey(arg, xprv)) return false;\n            parent_extkey = xprv.Neuter();\n            if (m_derive == DeriveType::UNHARDENED) der = xprv.Derive(xprv, pos);\n            if (m_derive == DeriveType::HARDENED) der = xprv.Derive(xprv, pos | 0x80000000UL);\n            final_extkey = xprv.Neuter();\n        } else {\n            for (auto entry : m_path) {\n                der = parent_extkey.Derive(parent_extkey, entry);\n                assert(der);\n            }\n            final_extkey = parent_extkey;\n            if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);\n            assert(m_derive != DeriveType::HARDENED);\n        }\n        assert(der);\n\n        final_info_out = final_info_out_tmp;\n        key_out = final_extkey.pubkey;\n\n        \/\/ We rely on the consumer to check that m_derive isn't HARDENED as above\n        \/\/ But we can't have already cached something in case we read something from the cache\n        \/\/ and parent_extkey isn't actually the parent.\n        if (!m_cached_xpub.pubkey.IsValid()) m_cached_xpub = parent_extkey;\n\n        if (write_cache) {\n            \/\/ Only cache parent if there is any unhardened derivation\n            if (m_derive != DeriveType::HARDENED) {\n                write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);\n            } else if (final_info_out.path.size() > 0) {\n                write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);\n            }\n        }\n\n        return true;\n    }\n    std::string ToString() const override\n    {\n        std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path);\n        if (IsRange()) {\n            ret += \"\/*\";\n            if (m_derive == DeriveType::HARDENED) ret += '\\'';\n        }\n        return ret;\n    }\n    bool ToPrivateString(const SigningProvider& arg, std::string& out) const override\n    {\n        CExtKey key;\n        if (!GetExtKey(arg, key)) return false;\n        out = EncodeExtKey(key) + FormatHDKeypath(m_path);\n        if (IsRange()) {\n            out += \"\/*\";\n            if (m_derive == DeriveType::HARDENED) out += '\\'';\n        }\n        return true;\n    }\n    bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override\n    {\n        CExtKey extkey;\n        if (!GetDerivedExtKey(arg, extkey)) return false;\n        if (m_derive == DeriveType::UNHARDENED) extkey.Derive(extkey, pos);\n        if (m_derive == DeriveType::HARDENED) extkey.Derive(extkey, pos | 0x80000000UL);\n        key = extkey.key;\n        return true;\n    }\n};\n\n\/** Base class for all Descriptor implementations. *\/\nclass DescriptorImpl : public Descriptor\n{\n    \/\/! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for Multisig).\n    const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;\n    \/\/! The string name of the descriptor function.\n    const std::string m_name;\n\nprotected:\n    \/\/! The sub-descriptor argument (nullptr for everything but SH and WSH).\n    \/\/! In doc\/descriptors.m this is referred to as SCRIPT expressions sh(SCRIPT)\n    \/\/! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.\n    const std::unique_ptr<DescriptorImpl> m_subdescriptor_arg;\n\n    \/\/! Return a serialization of anything except pubkey and script arguments, to be prepended to those.\n    virtual std::string ToStringExtra() const { return \"\"; }\n\n    \/** A helper function to construct the scripts for this descriptor.\n     *\n     *  This function is invoked once for every CScript produced by evaluating\n     *  m_subdescriptor_arg, or just once in case m_subdescriptor_arg is nullptr.\n\n     *  @param pubkeys The evaluations of the m_pubkey_args field.\n     *  @param script The evaluation of m_subdescriptor_arg (or nullptr when m_subdescriptor_arg is nullptr).\n     *  @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.\n     *             The script arguments to this function are automatically added, as is the origin info of the provided pubkeys.\n     *  @return A vector with scriptPubKeys for this descriptor.\n     *\/\n    virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, const CScript* script, FlatSigningProvider& out) const = 0;\n\npublic:\n    DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, std::unique_ptr<DescriptorImpl> script, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_arg(std::move(script)) {}\n\n    bool IsSolvable() const override\n    {\n        if (m_subdescriptor_arg) {\n            if (!m_subdescriptor_arg->IsSolvable()) return false;\n        }\n        return true;\n    }\n\n    bool IsRange() const final\n    {\n        for (const auto& pubkey : m_pubkey_args) {\n            if (pubkey->IsRange()) return true;\n        }\n        if (m_subdescriptor_arg) {\n            if (m_subdescriptor_arg->IsRange()) return true;\n        }\n        return false;\n    }\n\n    bool ToStringHelper(const SigningProvider* arg, std::string& out, bool priv) const\n    {\n        std::string extra = ToStringExtra();\n        size_t pos = extra.size() > 0 ? 1 : 0;\n        std::string ret = m_name + \"(\" + extra;\n        for (const auto& pubkey : m_pubkey_args) {\n            if (pos++) ret += \",\";\n            std::string tmp;\n            if (priv) {\n                if (!pubkey->ToPrivateString(*arg, tmp)) return false;\n            } else {\n                tmp = pubkey->ToString();\n            }\n            ret += std::move(tmp);\n        }\n        if (m_subdescriptor_arg) {\n            if (pos++) ret += \",\";\n            std::string tmp;\n            if (!m_subdescriptor_arg->ToStringHelper(arg, tmp, priv)) return false;\n            ret += std::move(tmp);\n        }\n        out = std::move(ret) + \")\";\n        return true;\n    }\n\n    std::string ToString() const final\n    {\n        std::string ret;\n        ToStringHelper(nullptr, ret, false);\n        return AddChecksum(ret);\n    }\n\n    bool ToPrivateString(const SigningProvider& arg, std::string& out) const override final\n    {\n        bool ret = ToStringHelper(&arg, out, true);\n        out = AddChecksum(out);\n        return ret;\n    }\n\n    bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const\n    {\n        std::vector<std::pair<CPubKey, KeyOriginInfo>> entries;\n        entries.reserve(m_pubkey_args.size());\n\n        \/\/ Construct temporary data in `entries` and `subscripts`, to avoid producing output in case of failure.\n        for (const auto& p : m_pubkey_args) {\n            entries.emplace_back();\n            if (!p->GetPubKey(pos, arg, entries.back().first, entries.back().second, read_cache, write_cache)) return false;\n        }\n        std::vector<CScript> subscripts;\n        if (m_subdescriptor_arg) {\n            FlatSigningProvider subprovider;\n            if (!m_subdescriptor_arg->ExpandHelper(pos, arg, read_cache, subscripts, subprovider, write_cache)) return false;\n            out = Merge(out, subprovider);\n        }\n\n        std::vector<CPubKey> pubkeys;\n        pubkeys.reserve(entries.size());\n        for (auto& entry : entries) {\n            pubkeys.push_back(entry.first);\n            out.origins.emplace(entry.first.GetID(), std::make_pair<CPubKey, KeyOriginInfo>(CPubKey(entry.first), std::move(entry.second)));\n        }\n        if (m_subdescriptor_arg) {\n            for (const auto& subscript : subscripts) {\n                out.scripts.emplace(CScriptID(subscript), subscript);\n                std::vector<CScript> addscripts = MakeScripts(pubkeys, &subscript, out);\n                for (auto& addscript : addscripts) {\n                    output_scripts.push_back(std::move(addscript));\n                }\n            }\n        } else {\n            output_scripts = MakeScripts(pubkeys, nullptr, out);\n        }\n        return true;\n    }\n\n    bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final\n    {\n        return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);\n    }\n\n    bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final\n    {\n        return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);\n    }\n\n    void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final\n    {\n        for (const auto& p : m_pubkey_args) {\n            CKey key;\n            if (!p->GetPrivKey(pos, provider, key)) continue;\n            out.keys.emplace(key.GetPubKey().GetID(), key);\n        }\n        if (m_subdescriptor_arg) {\n            FlatSigningProvider subprovider;\n            m_subdescriptor_arg->ExpandPrivate(pos, provider, subprovider);\n            out = Merge(out, subprovider);\n        }\n    }\n\n    Optional<OutputType> GetOutputType() const override { return nullopt; }\n};\n\n\/** A parsed addr(A) descriptor. *\/\nclass AddressDescriptor final : public DescriptorImpl\n{\n    const CTxDestination m_destination;\nprotected:\n    std::string ToStringExtra() const override { return EncodeDestination(m_destination); }\n    std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, const CScript*, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }\npublic:\n    AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, {}, \"addr\"), m_destination(std::move(destination)) {}\n    bool IsSolvable() const final { return false; }\n\n    Optional<OutputType> GetOutputType() const override\n    {\n        switch (m_destination.which()) {\n            case 1 \/* PKHash *\/:\n            case 2 \/* ScriptHash *\/: return OutputType::LEGACY;\n            case 3 \/* WitnessV0ScriptHash *\/:\n            case 4 \/* WitnessV0KeyHash *\/:\n            case 5 \/* WitnessUnknown *\/: return OutputType::BECH32;\n            case 0 \/* CNoDestination *\/:\n            default: return nullopt;\n        }\n    }\n};\n\n\/** A parsed raw(H) descriptor. *\/\nclass RawDescriptor final : public DescriptorImpl\n{\n    const CScript m_script;\nprotected:\n    std::string ToStringExtra() const override { return HexStr(m_script.begin(), m_script.end()); }\n    std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, const CScript*, FlatSigningProvider&) const override { return Vector(m_script); }\npublic:\n    RawDescriptor(CScript script) : DescriptorImpl({}, {}, \"raw\"), m_script(std::move(script)) {}\n    bool IsSolvable() const final { return false; }\n\n    Optional<OutputType> GetOutputType() const override\n    {\n        CTxDestination dest;\n        ExtractDestination(m_script, dest);\n        switch (dest.which()) {\n            case 1 \/* PKHash *\/:\n            case 2 \/* ScriptHash *\/: return OutputType::LEGACY;\n            case 3 \/* WitnessV0ScriptHash *\/:\n            case 4 \/* WitnessV0KeyHash *\/:\n            case 5 \/* WitnessUnknown *\/: return OutputType::BECH32;\n            case 0 \/* CNoDestination *\/:\n            default: return nullopt;\n        }\n    }\n};\n\n\/** A parsed pk(P) descriptor. *\/\nclass PKDescriptor final : public DescriptorImpl\n{\nprotected:\n    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, const CScript*, FlatSigningProvider&) const override { return Vector(GetScriptForRawPubKey(keys[0])); }\npublic:\n    PKDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), {}, \"pk\") {}\n};\n\n\/** A parsed pkh(P) descriptor. *\/\nclass PKHDescriptor final : public DescriptorImpl\n{\nprotected:\n    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, const CScript*, FlatSigningProvider& out) const override\n    {\n        CKeyID id = keys[0].GetID();\n        out.pubkeys.emplace(id, keys[0]);\n        return Vector(GetScriptForDestination(PKHash(id)));\n    }\npublic:\n    PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), {}, \"pkh\") {}\n    Optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }\n};\n\n\/** A parsed wpkh(P) descriptor. *\/\nclass WPKHDescriptor final : public DescriptorImpl\n{\nprotected:\n    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, const CScript*, FlatSigningProvider& out) const override\n    {\n        CKeyID id = keys[0].GetID();\n        out.pubkeys.emplace(id, keys[0]);\n        return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));\n    }\npublic:\n    WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), {}, \"wpkh\") {}\n    Optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }\n};\n\n\/** A parsed combo(P) descriptor. *\/\nclass ComboDescriptor final : public DescriptorImpl\n{\nprotected:\n    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, const CScript*, FlatSigningProvider& out) const override\n    {\n        std::vector<CScript> ret;\n        CKeyID id = keys[0].GetID();\n        out.pubkeys.emplace(id, keys[0]);\n        ret.emplace_back(GetScriptForRawPubKey(keys[0])); \/\/ P2PK\n        ret.emplace_back(GetScriptForDestination(PKHash(id))); \/\/ P2PKH\n        if (keys[0].IsCompressed()) {\n            CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));\n            out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);\n            ret.emplace_back(p2wpkh);\n            ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); \/\/ P2SH-P2WPKH\n        }\n        return ret;\n    }\npublic:\n    ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), {}, \"combo\") {}\n};\n\n\/** A parsed multi(...) or sortedmulti(...) descriptor *\/\nclass MultisigDescriptor final : public DescriptorImpl\n{\n    const int m_threshold;\n    const bool m_sorted;\nprotected:\n    std::string ToStringExtra() const override { return strprintf(\"%i\", m_threshold); }\n    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, const CScript*, FlatSigningProvider&) const override {\n        if (m_sorted) {\n            std::vector<CPubKey> sorted_keys(keys);\n            std::sort(sorted_keys.begin(), sorted_keys.end());\n            return Vector(GetScriptForMultisig(m_threshold, sorted_keys));\n        }\n        return Vector(GetScriptForMultisig(m_threshold, keys));\n    }\npublic:\n    MultisigDescriptor(int threshold, std::vector<std::unique_ptr<PubkeyProvider>> providers, bool sorted = false) : DescriptorImpl(std::move(providers), {}, sorted ? \"sortedmulti\" : \"multi\"), m_threshold(threshold), m_sorted(sorted) {}\n};\n\n\/** A parsed sh(...) descriptor. *\/\nclass SHDescriptor final : public DescriptorImpl\n{\nprotected:\n    std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, const CScript* script, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(ScriptHash(*script))); }\npublic:\n    SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), \"sh\") {}\n\n    Optional<OutputType> GetOutputType() const override\n    {\n        assert(m_subdescriptor_arg);\n        if (m_subdescriptor_arg->GetOutputType() == OutputType::BECH32) return OutputType::P2SH_SEGWIT;\n        return OutputType::LEGACY;\n    }\n};\n\n\/** A parsed wsh(...) descriptor. *\/\nclass WSHDescriptor final : public DescriptorImpl\n{\nprotected:\n    std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, const CScript* script, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(WitnessV0ScriptHash(*script))); }\npublic:\n    WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), \"wsh\") {}\n    Optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Parser                                                                 \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum class ParseScriptContext {\n    TOP,\n    P2SH,\n    P2WSH,\n};\n\n\/** Parse a key path, being passed a split list of elements (the first element is ignored). *\/\nNODISCARD bool ParseKeyPath(const std::vector<Span<const char>>& split, KeyPath& out, std::string& error)\n{\n    for (size_t i = 1; i < split.size(); ++i) {\n        Span<const char> elem = split[i];\n        bool hardened = false;\n        if (elem.size() > 0 && (elem[elem.size() - 1] == '\\'' || elem[elem.size() - 1] == 'h')) {\n            elem = elem.first(elem.size() - 1);\n            hardened = true;\n        }\n        uint32_t p;\n        if (!ParseUInt32(std::string(elem.begin(), elem.end()), &p)) {\n            error = strprintf(\"Key path value '%s' is not a valid uint32\", std::string(elem.begin(), elem.end()));\n            return false;\n        } else if (p > 0x7FFFFFFFUL) {\n            error = strprintf(\"Key path value %u is out of range\", p);\n            return false;\n        }\n        out.push_back(p | (((uint32_t)hardened) << 31));\n    }\n    return true;\n}\n\n\/** Parse a public key that excludes origin information. *\/\nstd::unique_ptr<PubkeyProvider> ParsePubkeyInner(uint32_t key_exp_index, const Span<const char>& sp, bool permit_uncompressed, FlatSigningProvider& out, std::string& error)\n{\n    using namespace spanparsing;\n\n    auto split = Split(sp, '\/');\n    std::string str(split[0].begin(), split[0].end());\n    if (str.size() == 0) {\n        error = \"No key provided\";\n        return nullptr;\n    }\n    if (split.size() == 1) {\n        if (IsHex(str)) {\n            std::vector<unsigned char> data = ParseHex(str);\n            CPubKey pubkey(data);\n            if (pubkey.IsFullyValid()) {\n                if (permit_uncompressed || pubkey.IsCompressed()) {\n                    return MakeUnique<ConstPubkeyProvider>(key_exp_index, pubkey);\n                } else {\n                    error = \"Uncompressed keys are not allowed\";\n                    return nullptr;\n                }\n            }\n            error = strprintf(\"Pubkey '%s' is invalid\", str);\n            return nullptr;\n        }\n        CKey key = DecodeSecret(str);\n        if (key.IsValid()) {\n            if (permit_uncompressed || key.IsCompressed()) {\n                CPubKey pubkey = key.GetPubKey();\n                out.keys.emplace(pubkey.GetID(), key);\n                return MakeUnique<ConstPubkeyProvider>(key_exp_index, pubkey);\n            } else {\n                error = \"Uncompressed keys are not allowed\";\n                return nullptr;\n            }\n        }\n    }\n    CExtKey extkey = DecodeExtKey(str);\n    CExtPubKey extpubkey = DecodeExtPubKey(str);\n    if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {\n        error = strprintf(\"key '%s' is not valid\", str);\n        return nullptr;\n    }\n    KeyPath path;\n    DeriveType type = DeriveType::NO;\n    if (split.back() == MakeSpan(\"*\").first(1)) {\n        split.pop_back();\n        type = DeriveType::UNHARDENED;\n    } else if (split.back() == MakeSpan(\"*'\").first(2) || split.back() == MakeSpan(\"*h\").first(2)) {\n        split.pop_back();\n        type = DeriveType::HARDENED;\n    }\n    if (!ParseKeyPath(split, path, error)) return nullptr;\n    if (extkey.key.IsValid()) {\n        extpubkey = extkey.Neuter();\n        out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);\n    }\n    return MakeUnique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type);\n}\n\n\/** Parse a public key including origin information (if enabled). *\/\nstd::unique_ptr<PubkeyProvider> ParsePubkey(uint32_t key_exp_index, const Span<const char>& sp, bool permit_uncompressed, FlatSigningProvider& out, std::string& error)\n{\n    using namespace spanparsing;\n\n    auto origin_split = Split(sp, ']');\n    if (origin_split.size() > 2) {\n        error = \"Multiple ']' characters found for a single pubkey\";\n        return nullptr;\n    }\n    if (origin_split.size() == 1) return ParsePubkeyInner(key_exp_index, origin_split[0], permit_uncompressed, out, error);\n    if (origin_split[0].size() < 1 || origin_split[0][0] != '[') {\n        error = strprintf(\"Key origin start '[ character expected but not found, got '%c' instead\", origin_split[0][0]);\n        return nullptr;\n    }\n    auto slash_split = Split(origin_split[0].subspan(1), '\/');\n    if (slash_split[0].size() != 8) {\n        error = strprintf(\"Fingerprint is not 4 bytes (%u characters instead of 8 characters)\", slash_split[0].size());\n        return nullptr;\n    }\n    std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());\n    if (!IsHex(fpr_hex)) {\n        error = strprintf(\"Fingerprint '%s' is not hex\", fpr_hex);\n        return nullptr;\n    }\n    auto fpr_bytes = ParseHex(fpr_hex);\n    KeyOriginInfo info;\n    static_assert(sizeof(info.fingerprint) == 4, \"Fingerprint must be 4 bytes\");\n    assert(fpr_bytes.size() == 4);\n    std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);\n    if (!ParseKeyPath(slash_split, info.path, error)) return nullptr;\n    auto provider = ParsePubkeyInner(key_exp_index, origin_split[1], permit_uncompressed, out, error);\n    if (!provider) return nullptr;\n    return MakeUnique<OriginPubkeyProvider>(key_exp_index, std::move(info), std::move(provider));\n}\n\n\/** Parse a script in a particular context. *\/\nstd::unique_ptr<DescriptorImpl> ParseScript(uint32_t key_exp_index, Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)\n{\n    using namespace spanparsing;\n\n    auto expr = Expr(sp);\n    bool sorted_multi = false;\n    if (Func(\"pk\", expr)) {\n        auto pubkey = ParsePubkey(key_exp_index, expr, ctx != ParseScriptContext::P2WSH, out, error);\n        if (!pubkey) return nullptr;\n        return MakeUnique<PKDescriptor>(std::move(pubkey));\n    }\n    if (Func(\"pkh\", expr)) {\n        auto pubkey = ParsePubkey(key_exp_index, expr, ctx != ParseScriptContext::P2WSH, out, error);\n        if (!pubkey) return nullptr;\n        return MakeUnique<PKHDescriptor>(std::move(pubkey));\n    }\n    if (ctx == ParseScriptContext::TOP && Func(\"combo\", expr)) {\n        auto pubkey = ParsePubkey(key_exp_index, expr, true, out, error);\n        if (!pubkey) return nullptr;\n        return MakeUnique<ComboDescriptor>(std::move(pubkey));\n    } else if (ctx != ParseScriptContext::TOP && Func(\"combo\", expr)) {\n        error = \"Cannot have combo in non-top level\";\n        return nullptr;\n    }\n    if ((sorted_multi = Func(\"sortedmulti\", expr)) || Func(\"multi\", expr)) {\n        auto threshold = Expr(expr);\n        uint32_t thres;\n        std::vector<std::unique_ptr<PubkeyProvider>> providers;\n        if (!ParseUInt32(std::string(threshold.begin(), threshold.end()), &thres)) {\n            error = strprintf(\"Multi threshold '%s' is not valid\", std::string(threshold.begin(), threshold.end()));\n            return nullptr;\n        }\n        size_t script_size = 0;\n        while (expr.size()) {\n            if (!Const(\",\", expr)) {\n                error = strprintf(\"Multi: expected ',', got '%c'\", expr[0]);\n                return nullptr;\n            }\n            auto arg = Expr(expr);\n            auto pk = ParsePubkey(key_exp_index, arg, ctx != ParseScriptContext::P2WSH, out, error);\n            if (!pk) return nullptr;\n            script_size += pk->GetSize() + 1;\n            providers.emplace_back(std::move(pk));\n            key_exp_index++;\n        }\n        if (providers.size() < 1 || providers.size() > 16) {\n            error = strprintf(\"Cannot have %u keys in multisig; must have between 1 and 16 keys, inclusive\", providers.size());\n            return nullptr;\n        } else if (thres < 1) {\n            error = strprintf(\"Multisig threshold cannot be %d, must be at least 1\", thres);\n            return nullptr;\n        } else if (thres > providers.size()) {\n            error = strprintf(\"Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified\", thres, providers.size());\n            return nullptr;\n        }\n        if (ctx == ParseScriptContext::TOP) {\n            if (providers.size() > 3) {\n                error = strprintf(\"Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys\", providers.size());\n                return nullptr;\n            }\n        }\n        if (ctx == ParseScriptContext::P2SH) {\n            if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {\n                error = strprintf(\"P2SH script is too large, %d bytes is larger than %d bytes\", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);\n                return nullptr;\n            }\n        }\n        return MakeUnique<MultisigDescriptor>(thres, std::move(providers), sorted_multi);\n    }\n    if (ctx != ParseScriptContext::P2WSH && Func(\"wpkh\", expr)) {\n        auto pubkey = ParsePubkey(key_exp_index, expr, false, out, error);\n        if (!pubkey) return nullptr;\n        return MakeUnique<WPKHDescriptor>(std::move(pubkey));\n    } else if (ctx == ParseScriptContext::P2WSH && Func(\"wpkh\", expr)) {\n        error = \"Cannot have wpkh within wsh\";\n        return nullptr;\n    }\n    if (ctx == ParseScriptContext::TOP && Func(\"sh\", expr)) {\n        auto desc = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);\n        if (!desc || expr.size()) return nullptr;\n        return MakeUnique<SHDescriptor>(std::move(desc));\n    } else if (ctx != ParseScriptContext::TOP && Func(\"sh\", expr)) {\n        error = \"Cannot have sh in non-top level\";\n        return nullptr;\n    }\n    if (ctx != ParseScriptContext::P2WSH && Func(\"wsh\", expr)) {\n        auto desc = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);\n        if (!desc || expr.size()) return nullptr;\n        return MakeUnique<WSHDescriptor>(std::move(desc));\n    } else if (ctx == ParseScriptContext::P2WSH && Func(\"wsh\", expr)) {\n        error = \"Cannot have wsh within wsh\";\n        return nullptr;\n    }\n    if (ctx == ParseScriptContext::TOP && Func(\"addr\", expr)) {\n        CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));\n        if (!IsValidDestination(dest)) {\n            error = \"Address is not valid\";\n            return nullptr;\n        }\n        return MakeUnique<AddressDescriptor>(std::move(dest));\n    }\n    if (ctx == ParseScriptContext::TOP && Func(\"raw\", expr)) {\n        std::string str(expr.begin(), expr.end());\n        if (!IsHex(str)) {\n            error = \"Raw script is not hex\";\n            return nullptr;\n        }\n        auto bytes = ParseHex(str);\n        return MakeUnique<RawDescriptor>(CScript(bytes.begin(), bytes.end()));\n    }\n    if (ctx == ParseScriptContext::P2SH) {\n        error = \"A function is needed within P2SH\";\n        return nullptr;\n    } else if (ctx == ParseScriptContext::P2WSH) {\n        error = \"A function is needed within P2WSH\";\n        return nullptr;\n    }\n    error = strprintf(\"%s is not a valid descriptor function\", std::string(expr.begin(), expr.end()));\n    return nullptr;\n}\n\nstd::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext, const SigningProvider& provider)\n{\n    std::unique_ptr<PubkeyProvider> key_provider = MakeUnique<ConstPubkeyProvider>(0, pubkey);\n    KeyOriginInfo info;\n    if (provider.GetKeyOrigin(pubkey.GetID(), info)) {\n        return MakeUnique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider));\n    }\n    return key_provider;\n}\n\nstd::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)\n{\n    std::vector<std::vector<unsigned char>> data;\n    txnouttype txntype = Solver(script, data);\n\n    if (txntype == TX_PUBKEY) {\n        CPubKey pubkey(data[0].begin(), data[0].end());\n        if (pubkey.IsValid()) {\n            return MakeUnique<PKDescriptor>(InferPubkey(pubkey, ctx, provider));\n        }\n    }\n    if (txntype == TX_PUBKEYHASH) {\n        uint160 hash(data[0]);\n        CKeyID keyid(hash);\n        CPubKey pubkey;\n        if (provider.GetPubKey(keyid, pubkey)) {\n            return MakeUnique<PKHDescriptor>(InferPubkey(pubkey, ctx, provider));\n        }\n    }\n    if (txntype == TX_WITNESS_V0_KEYHASH && ctx != ParseScriptContext::P2WSH) {\n        uint160 hash(data[0]);\n        CKeyID keyid(hash);\n        CPubKey pubkey;\n        if (provider.GetPubKey(keyid, pubkey)) {\n            return MakeUnique<WPKHDescriptor>(InferPubkey(pubkey, ctx, provider));\n        }\n    }\n    if (txntype == TX_MULTISIG) {\n        std::vector<std::unique_ptr<PubkeyProvider>> providers;\n        for (size_t i = 1; i + 1 < data.size(); ++i) {\n            CPubKey pubkey(data[i].begin(), data[i].end());\n            providers.push_back(InferPubkey(pubkey, ctx, provider));\n        }\n        return MakeUnique<MultisigDescriptor>((int)data[0][0], std::move(providers));\n    }\n    if (txntype == TX_SCRIPTHASH && ctx == ParseScriptContext::TOP) {\n        uint160 hash(data[0]);\n        CScriptID scriptid(hash);\n        CScript subscript;\n        if (provider.GetCScript(scriptid, subscript)) {\n            auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);\n            if (sub) return MakeUnique<SHDescriptor>(std::move(sub));\n        }\n    }\n    if (txntype == TX_WITNESS_V0_SCRIPTHASH && ctx != ParseScriptContext::P2WSH) {\n        CScriptID scriptid;\n        CRIPEMD160().Write(data[0].data(), data[0].size()).Finalize(scriptid.begin());\n        CScript subscript;\n        if (provider.GetCScript(scriptid, subscript)) {\n            auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);\n            if (sub) return MakeUnique<WSHDescriptor>(std::move(sub));\n        }\n    }\n\n    CTxDestination dest;\n    if (ExtractDestination(script, dest)) {\n        if (GetScriptForDestination(dest) == script) {\n            return MakeUnique<AddressDescriptor>(std::move(dest));\n        }\n    }\n\n    return MakeUnique<RawDescriptor>(script);\n}\n\n\n} \/\/ namespace\n\n\/** Check a descriptor checksum, and update desc to be the checksum-less part. *\/\nbool CheckChecksum(Span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)\n{\n    using namespace spanparsing;\n\n    auto check_split = Split(sp, '#');\n    if (check_split.size() > 2) {\n        error = \"Multiple '#' symbols\";\n        return false;\n    }\n    if (check_split.size() == 1 && require_checksum){\n        error = \"Missing checksum\";\n        return false;\n    }\n    if (check_split.size() == 2) {\n        if (check_split[1].size() != 8) {\n            error = strprintf(\"Expected 8 character checksum, not %u characters\", check_split[1].size());\n            return false;\n        }\n    }\n    auto checksum = DescriptorChecksum(check_split[0]);\n    if (checksum.empty()) {\n        error = \"Invalid characters in payload\";\n        return false;\n    }\n    if (check_split.size() == 2) {\n        if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {\n            error = strprintf(\"Provided checksum '%s' does not match computed checksum '%s'\", std::string(check_split[1].begin(), check_split[1].end()), checksum);\n            return false;\n        }\n    }\n    if (out_checksum) *out_checksum = std::move(checksum);\n    sp = check_split[0];\n    return true;\n}\n\nstd::unique_ptr<Descriptor> Parse(const std::string& descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)\n{\n    Span<const char> sp(descriptor.data(), descriptor.size());\n    if (!CheckChecksum(sp, require_checksum, error)) return nullptr;\n    auto ret = ParseScript(0, sp, ParseScriptContext::TOP, out, error);\n    if (sp.size() == 0 && ret) return std::unique_ptr<Descriptor>(std::move(ret));\n    return nullptr;\n}\n\nstd::string GetDescriptorChecksum(const std::string& descriptor)\n{\n    std::string ret;\n    std::string error;\n    Span<const char> sp(descriptor.data(), descriptor.size());\n    if (!CheckChecksum(sp, false, error, &ret)) return \"\";\n    return ret;\n}\n\nstd::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)\n{\n    return InferScript(script, ParseScriptContext::TOP, provider);\n}\n\nvoid DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)\n{\n    m_parent_xpubs[key_exp_pos] = xpub;\n}\n\nvoid DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)\n{\n    auto& xpubs = m_derived_xpubs[key_exp_pos];\n    xpubs[der_index] = xpub;\n}\n\nbool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const\n{\n    const auto& it = m_parent_xpubs.find(key_exp_pos);\n    if (it == m_parent_xpubs.end()) return false;\n    xpub = it->second;\n    return true;\n}\n\nbool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const\n{\n    const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);\n    if (key_exp_it == m_derived_xpubs.end()) return false;\n    const auto& der_it = key_exp_it->second.find(der_index);\n    if (der_it == key_exp_it->second.end()) return false;\n    xpub = der_it->second;\n    return true;\n}\n\nconst ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const\n{\n    return m_parent_xpubs;\n}\n\nconst std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const\n{\n    return m_derived_xpubs;\n}\n","avg_line_length":42.4578947368,"max_line_length":236,"alphanum_fraction":0.6338374447,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":717,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\n\nusing namespace std;\n\nint main(int argc, char const *argv[])\n{\n\n    system(\"cls\");\n\nfor (int i = 5; i <= 100; i = i + 5)\n{\n    cout << i << endl;\n\n    for (int j = 1; j <= 5; j++)\n    {\n           cout << j << endl;\n\n           for (int k = 1; k <= 3; k++)\n           {\n              cout << k  << endl;\n\n              if (i == 25){\n                  break;\n              }\n           }\n\n         if( i == 25){\n              break;\n         }\n        \n    }\n    \n    if( i == 25){\n        break;\n    }\n}\n\nint i = 5;\nwhile (i <= 100)\n{\n cout << i << endl;\n i = i + 5;\n\nint j = 0;\nwhile (j <= 5)\n{\n    if (i == 25){\n        break;\n    }\n j++;\n}\n\n\n if(i == 25)\n {\n     break;\n }\n}\n\n\n    return 0;\n}\n","avg_line_length":11.380952381,"max_line_length":39,"alphanum_fraction":0.3179916318,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5721,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include <hxcpp.h>\n\n#ifndef INCLUDED___ASSET__flixel_fonts_nokiafc22_ttf\n#include <__ASSET__flixel_fonts_nokiafc22_ttf.h>\n#endif\n#ifndef INCLUDED_haxe_Resource\n#include <haxe\/Resource.h>\n#endif\n#ifndef INCLUDED_haxe_io_Bytes\n#include <haxe\/io\/Bytes.h>\n#endif\n#ifndef INCLUDED_lime_text_Font\n#include <lime\/text\/Font.h>\n#endif\n\nHX_DEFINE_STACK_FRAME(_hx_pos_b3ea4ee380faf667_307_new,\"__ASSET__flixel_fonts_nokiafc22_ttf\",\"new\",0x22f03f2a,\"__ASSET__flixel_fonts_nokiafc22_ttf.new\",\"lime\/_internal\/macros\/AssetsMacro.hx\",307,0xc651f030)\nHX_LOCAL_STACK_FRAME(_hx_pos_52fc57ab4b28397c_382_boot,\"__ASSET__flixel_fonts_nokiafc22_ttf\",\"boot\",0x67600628,\"__ASSET__flixel_fonts_nokiafc22_ttf.boot\",\"ManifestResources.hx\",382,0xf77aa668)\n\nvoid __ASSET__flixel_fonts_nokiafc22_ttf_obj::__construct(){\n            \tHX_STACKFRAME(&_hx_pos_b3ea4ee380faf667_307_new)\nHXLINE( 308)\t\tsuper::__construct(null());\nHXLINE( 310)\t\tthis->_hx___fromBytes(::haxe::Resource_obj::getBytes(::__ASSET__flixel_fonts_nokiafc22_ttf_obj::resourceName));\n            \t}\n\nDynamic __ASSET__flixel_fonts_nokiafc22_ttf_obj::__CreateEmpty() { return new __ASSET__flixel_fonts_nokiafc22_ttf_obj; }\n\nvoid *__ASSET__flixel_fonts_nokiafc22_ttf_obj::_hx_vtable = 0;\n\nDynamic __ASSET__flixel_fonts_nokiafc22_ttf_obj::__Create(::hx::DynamicArray inArgs)\n{\n\t::hx::ObjectPtr< __ASSET__flixel_fonts_nokiafc22_ttf_obj > _hx_result = new __ASSET__flixel_fonts_nokiafc22_ttf_obj();\n\t_hx_result->__construct();\n\treturn _hx_result;\n}\n\nbool __ASSET__flixel_fonts_nokiafc22_ttf_obj::_hx_isInstanceOf(int inClassId) {\n\tif (inClassId<=(int)0x40cee131) {\n\t\treturn inClassId==(int)0x00000001 || inClassId==(int)0x40cee131;\n\t} else {\n\t\treturn inClassId==(int)0x453c2778;\n\t}\n}\n\n::String __ASSET__flixel_fonts_nokiafc22_ttf_obj::resourceName;\n\n\n::hx::ObjectPtr< __ASSET__flixel_fonts_nokiafc22_ttf_obj > __ASSET__flixel_fonts_nokiafc22_ttf_obj::__new() {\n\t::hx::ObjectPtr< __ASSET__flixel_fonts_nokiafc22_ttf_obj > __this = new __ASSET__flixel_fonts_nokiafc22_ttf_obj();\n\t__this->__construct();\n\treturn __this;\n}\n\n::hx::ObjectPtr< __ASSET__flixel_fonts_nokiafc22_ttf_obj > __ASSET__flixel_fonts_nokiafc22_ttf_obj::__alloc(::hx::Ctx *_hx_ctx) {\n\t__ASSET__flixel_fonts_nokiafc22_ttf_obj *__this = (__ASSET__flixel_fonts_nokiafc22_ttf_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(__ASSET__flixel_fonts_nokiafc22_ttf_obj), true, \"__ASSET__flixel_fonts_nokiafc22_ttf\"));\n\t*(void **)__this = __ASSET__flixel_fonts_nokiafc22_ttf_obj::_hx_vtable;\n\t__this->__construct();\n\treturn __this;\n}\n\n__ASSET__flixel_fonts_nokiafc22_ttf_obj::__ASSET__flixel_fonts_nokiafc22_ttf_obj()\n{\n}\n\nbool __ASSET__flixel_fonts_nokiafc22_ttf_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp)\n{\n\tswitch(inName.length) {\n\tcase 12:\n\t\tif (HX_FIELD_EQ(inName,\"resourceName\") ) { outValue = ( resourceName ); return true; }\n\t}\n\treturn false;\n}\n\nbool __ASSET__flixel_fonts_nokiafc22_ttf_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,::hx::PropertyAccess inCallProp)\n{\n\tswitch(inName.length) {\n\tcase 12:\n\t\tif (HX_FIELD_EQ(inName,\"resourceName\") ) { resourceName=ioValue.Cast< ::String >(); return true; }\n\t}\n\treturn false;\n}\n\n#ifdef HXCPP_SCRIPTABLE\nstatic ::hx::StorageInfo *__ASSET__flixel_fonts_nokiafc22_ttf_obj_sMemberStorageInfo = 0;\nstatic ::hx::StaticInfo __ASSET__flixel_fonts_nokiafc22_ttf_obj_sStaticStorageInfo[] = {\n\t{::hx::fsString,(void *) &__ASSET__flixel_fonts_nokiafc22_ttf_obj::resourceName,HX_(\"resourceName\",39,7a,62,90)},\n\t{ ::hx::fsUnknown, 0, null()}\n};\n#endif\n\nstatic void __ASSET__flixel_fonts_nokiafc22_ttf_obj_sMarkStatics(HX_MARK_PARAMS) {\n\tHX_MARK_MEMBER_NAME(__ASSET__flixel_fonts_nokiafc22_ttf_obj::resourceName,\"resourceName\");\n};\n\n#ifdef HXCPP_VISIT_ALLOCS\nstatic void __ASSET__flixel_fonts_nokiafc22_ttf_obj_sVisitStatics(HX_VISIT_PARAMS) {\n\tHX_VISIT_MEMBER_NAME(__ASSET__flixel_fonts_nokiafc22_ttf_obj::resourceName,\"resourceName\");\n};\n\n#endif\n\n::hx::Class __ASSET__flixel_fonts_nokiafc22_ttf_obj::__mClass;\n\nstatic ::String __ASSET__flixel_fonts_nokiafc22_ttf_obj_sStaticFields[] = {\n\tHX_(\"resourceName\",39,7a,62,90),\n\t::String(null())\n};\n\nvoid __ASSET__flixel_fonts_nokiafc22_ttf_obj::__register()\n{\n\t__ASSET__flixel_fonts_nokiafc22_ttf_obj _hx_dummy;\n\t__ASSET__flixel_fonts_nokiafc22_ttf_obj::_hx_vtable = *(void **)&_hx_dummy;\n\t::hx::Static(__mClass) = new ::hx::Class_obj();\n\t__mClass->mName = HX_(\"__ASSET__flixel_fonts_nokiafc22_ttf\",38,22,8b,84);\n\t__mClass->mSuper = &super::__SGetClass();\n\t__mClass->mConstructEmpty = &__CreateEmpty;\n\t__mClass->mConstructArgs = &__Create;\n\t__mClass->mGetStaticField = &__ASSET__flixel_fonts_nokiafc22_ttf_obj::__GetStatic;\n\t__mClass->mSetStaticField = &__ASSET__flixel_fonts_nokiafc22_ttf_obj::__SetStatic;\n\t__mClass->mMarkFunc = __ASSET__flixel_fonts_nokiafc22_ttf_obj_sMarkStatics;\n\t__mClass->mStatics = ::hx::Class_obj::dupFunctions(__ASSET__flixel_fonts_nokiafc22_ttf_obj_sStaticFields);\n\t__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 \/* sMemberFields *\/);\n\t__mClass->mCanCast = ::hx::TCanCast< __ASSET__flixel_fonts_nokiafc22_ttf_obj >;\n#ifdef HXCPP_VISIT_ALLOCS\n\t__mClass->mVisitFunc = __ASSET__flixel_fonts_nokiafc22_ttf_obj_sVisitStatics;\n#endif\n#ifdef HXCPP_SCRIPTABLE\n\t__mClass->mMemberStorageInfo = __ASSET__flixel_fonts_nokiafc22_ttf_obj_sMemberStorageInfo;\n#endif\n#ifdef HXCPP_SCRIPTABLE\n\t__mClass->mStaticStorageInfo = __ASSET__flixel_fonts_nokiafc22_ttf_obj_sStaticStorageInfo;\n#endif\n\t::hx::_hx_RegisterClass(__mClass->mName, __mClass);\n}\n\nvoid __ASSET__flixel_fonts_nokiafc22_ttf_obj::__boot()\n{\n{\n            \tHX_STACKFRAME(&_hx_pos_52fc57ab4b28397c_382_boot)\nHXDLIN( 382)\t\tresourceName = HX_(\"LIME_font___ASSET__flixel_fonts_nokiafc22_ttf\",32,8e,cf,38);\n            \t}\n}\n\n","avg_line_length":40.006993007,"max_line_length":215,"alphanum_fraction":0.8140185282,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":305,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":21.0,"content":"#include <regex>\n#include <string>\n\nint main() {\n    const std::string str = \"test0159\";\n    std::regex re;\n    re = std::regex(\"^[a-z]+[0-9]+$\",\n                    std::regex_constants::extended\n                        | std::regex_constants::nosubs);\n    return std::regex_search(str, re) ? 0 : -1;\n}\n\n","avg_line_length":23.4615384615,"max_line_length":56,"alphanum_fraction":0.5213114754,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":464,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"#include \"..\/..\/template.hpp\"\n\npi MinAndMaxAmountToBuyAllCandies(vi candies, int k) {\n    sort(candies);\n    int n = candies.size(), mini = 0, maxi = 0;\n    for(int i = 0, j = n - 1; i <= j; i += 1, j -= k) {\n        mini += candies[i];\n    }\n    for(int i = 0, j = n - 1; i <= j; i += k, j -= 1) {\n        maxi += candies[j];\n    }\n    return {mini, maxi};\n}\n\nint main() { TimeMeasure _;\n    cout << MinAndMaxAmountToBuyAllCandies({3,2,1,4}, 2) << '\\n'; \/\/ 3 7\n}\n","avg_line_length":25.7777777778,"max_line_length":72,"alphanum_fraction":0.5,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2846,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":83.0,"content":"\/*********************************************************\\\n *  File: DrawHelpers.cpp                                *\n *\n *  Copyright (C) 2002-2013 The PixelLight Team (http:\/\/www.pixellight.org\/)\n *\n *  This file is part of PixelLight.\n *\n *  Permission is hereby granted, free of charge, to any person obtaining a copy of this software\n *  and associated documentation files (the \"Software\"), to deal in the Software without\n *  restriction, including without limitation the rights to use, copy, modify, merge, publish,\n *  distribute, sublicense, and\/or sell copies of the Software, and to permit persons to whom the\n *  Software is furnished to do so, subject to the following conditions:\n *\n *  The above copyright notice and this permission notice shall be included in all copies or\n *  substantial portions of the Software.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\n *  BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n *  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\\*********************************************************\/\n\n\n\/\/[-------------------------------------------------------]\n\/\/[ Includes                                              ]\n\/\/[-------------------------------------------------------]\n#include \"PLRenderer\/Renderer\/DrawHelpers.h\"\n\n\n\/\/[-------------------------------------------------------]\n\/\/[ Namespace                                             ]\n\/\/[-------------------------------------------------------]\nnamespace PLRenderer {\n\n\n\/\/[-------------------------------------------------------]\n\/\/[ Protected functions                                   ]\n\/\/[-------------------------------------------------------]\n\/**\n*  @brief\n*    Constructor\n*\/\nDrawHelpers::DrawHelpers()\n{\n}\n\n\/**\n*  @brief\n*    Destructor\n*\/\nDrawHelpers::~DrawHelpers()\n{\n}\n\n\n\/\/[-------------------------------------------------------]\n\/\/[ Private functions                                     ]\n\/\/[-------------------------------------------------------]\n\/**\n*  @brief\n*    Copy constructor\n*\/\nDrawHelpers::DrawHelpers(const DrawHelpers &cSource)\n{\n\t\/\/ No implementation because the copy constructor is never used\n}\n\n\/**\n*  @brief\n*    Copy operator\n*\/\nDrawHelpers &DrawHelpers::operator =(const DrawHelpers &cSource)\n{\n\t\/\/ No implementation because the copy operator is never used\n\treturn *this;\n}\n\n\n\/\/[-------------------------------------------------------]\n\/\/[ Namespace                                             ]\n\/\/[-------------------------------------------------------]\n} \/\/ PLRenderer\n","avg_line_length":33.880952381,"max_line_length":97,"alphanum_fraction":0.4820801124,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":226,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.\n\n#include \"TP_2DSideScroller.h\"\n#include \"Modules\/ModuleManager.h\"\n\nIMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, TP_2DSideScroller, \"TP_2DSideScroller\" );\n","avg_line_length":32.2857142857,"max_line_length":96,"alphanum_fraction":0.814159292,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7565,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":3.0,"content":"\/*\n * Copyright (c) 2011. Philipp Wagner <bytefish[at]gmx[dot]de>.\n * Released to public domain under terms of the BSD Simplified license.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and\/or other materials provided with the distribution.\n *   * Neither the name of the organization nor the names of its contributors\n *     may be used to endorse or promote products derived from this software\n *     without specific prior written permission.\n *\n *   See <http:\/\/www.opensource.org\/licenses\/bsd-license>\n *\/\n\n#include \"opencv2\/core.hpp\"\n#include \"opencv2\/contrib.hpp\"\n#include \"opencv2\/highgui.hpp\"\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\nusing namespace cv;\nusing namespace std;\n\nstatic Mat norm_0_255(InputArray _src) {\n    Mat src = _src.getMat();\n    \/\/ Create and return normalized image:\n    Mat dst;\n    switch(src.channels()) {\n    case 1:\n        cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);\n        break;\n    case 3:\n        cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);\n        break;\n    default:\n        src.copyTo(dst);\n        break;\n    }\n    return dst;\n}\n\nstatic void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {\n    std::ifstream file(filename.c_str(), ifstream::in);\n    if (!file) {\n        string error_message = \"No valid input file was given, please check the given filename.\";\n        CV_Error(CV_StsBadArg, error_message);\n    }\n    string line, path, classlabel;\n    while (getline(file, line)) {\n        stringstream liness(line);\n        getline(liness, path, separator);\n        getline(liness, classlabel);\n        if(!path.empty() && !classlabel.empty()) {\n            images.push_back(imread(path, 0));\n            labels.push_back(atoi(classlabel.c_str()));\n        }\n    }\n}\n\nint main(int argc, const char *argv[]) {\n    \/\/ Check for valid command line arguments, print usage\n    \/\/ if no arguments were given.\n    if (argc < 2) {\n        cout << \"usage: \" << argv[0] << \" <csv.ext> <output_folder> \" << endl;\n        exit(1);\n    }\n    string output_folder = \".\";\n    if (argc == 3) {\n        output_folder = string(argv[2]);\n    }\n    \/\/ Get the path to your CSV.\n    string fn_csv = string(argv[1]);\n    \/\/ These vectors hold the images and corresponding labels.\n    vector<Mat> images;\n    vector<int> labels;\n    \/\/ Read in the data. This can fail if no valid\n    \/\/ input filename is given.\n    try {\n        read_csv(fn_csv, images, labels);\n    } catch (cv::Exception& e) {\n        cerr << \"Error opening file \\\"\" << fn_csv << \"\\\". Reason: \" << e.msg << endl;\n        \/\/ nothing more we can do\n        exit(1);\n    }\n    \/\/ Quit if there are not enough images for this demo.\n    if(images.size() <= 1) {\n        string error_message = \"This demo needs at least 2 images to work. Please add more images to your data set!\";\n        CV_Error(CV_StsError, error_message);\n    }\n    \/\/ Get the height from the first image. We'll need this\n    \/\/ later in code to reshape the images to their original\n    \/\/ size:\n    int height = images[0].rows;\n    \/\/ The following lines simply get the last images from\n    \/\/ your dataset and remove it from the vector. This is\n    \/\/ done, so that the training data (which we learn the\n    \/\/ cv::FaceRecognizer on) and the test data we test\n    \/\/ the model with, do not overlap.\n    Mat testSample = images[images.size() - 1];\n    int testLabel = labels[labels.size() - 1];\n    images.pop_back();\n    labels.pop_back();\n    \/\/ The following lines create an Eigenfaces model for\n    \/\/ face recognition and train it with the images and\n    \/\/ labels read from the given CSV file.\n    \/\/ This here is a full PCA, if you just want to keep\n    \/\/ 10 principal components (read Eigenfaces), then call\n    \/\/ the factory method like this:\n    \/\/\n    \/\/      cv::createEigenFaceRecognizer(10);\n    \/\/\n    \/\/ If you want to create a FaceRecognizer with a\n    \/\/ confidence threshold (e.g. 123.0), call it with:\n    \/\/\n    \/\/      cv::createEigenFaceRecognizer(10, 123.0);\n    \/\/\n    \/\/ If you want to use _all_ Eigenfaces and have a threshold,\n    \/\/ then call the method like this:\n    \/\/\n    \/\/      cv::createEigenFaceRecognizer(0, 123.0);\n    \/\/\n    Ptr<FaceRecognizer> model = createEigenFaceRecognizer();\n    model->train(images, labels);\n    \/\/ The following line predicts the label of a given\n    \/\/ test image:\n    int predictedLabel = model->predict(testSample);\n    \/\/\n    \/\/ To get the confidence of a prediction call the model with:\n    \/\/\n    \/\/      int predictedLabel = -1;\n    \/\/      double confidence = 0.0;\n    \/\/      model->predict(testSample, predictedLabel, confidence);\n    \/\/\n    string result_message = format(\"Predicted class = %d \/ Actual class = %d.\", predictedLabel, testLabel);\n    cout << result_message << endl;\n    \/\/ Here is how to get the eigenvalues of this Eigenfaces model:\n    Mat eigenvalues = model->getMat(\"eigenvalues\");\n    \/\/ And we can do the same to display the Eigenvectors (read Eigenfaces):\n    Mat W = model->getMat(\"eigenvectors\");\n    \/\/ Get the sample mean from the training data\n    Mat mean = model->getMat(\"mean\");\n    \/\/ Display or save:\n    if(argc == 2) {\n        imshow(\"mean\", norm_0_255(mean.reshape(1, images[0].rows)));\n    } else {\n        imwrite(format(\"%s\/mean.png\", output_folder.c_str()), norm_0_255(mean.reshape(1, images[0].rows)));\n    }\n    \/\/ Display or save the Eigenfaces:\n    for (int i = 0; i < min(10, W.cols); i++) {\n        string msg = format(\"Eigenvalue #%d = %.5f\", i, eigenvalues.at<double>(i));\n        cout << msg << endl;\n        \/\/ get eigenvector #i\n        Mat ev = W.col(i).clone();\n        \/\/ Reshape to original size & normalize to [0...255] for imshow.\n        Mat grayscale = norm_0_255(ev.reshape(1, height));\n        \/\/ Show the image & apply a Jet colormap for better sensing.\n        Mat cgrayscale;\n        applyColorMap(grayscale, cgrayscale, COLORMAP_JET);\n        \/\/ Display or save:\n        if(argc == 2) {\n            imshow(format(\"eigenface_%d\", i), cgrayscale);\n        } else {\n            imwrite(format(\"%s\/eigenface_%d.png\", output_folder.c_str(), i), norm_0_255(cgrayscale));\n        }\n    }\n\n    \/\/ Display or save the image reconstruction at some predefined steps:\n    for(int num_components = min(W.cols, 10); num_components < min(W.cols, 300); num_components+=15) {\n        \/\/ slice the eigenvectors from the model\n        Mat evs = Mat(W, Range::all(), Range(0, num_components));\n        Mat projection = subspaceProject(evs, mean, images[0].reshape(1,1));\n        Mat reconstruction = subspaceReconstruct(evs, mean, projection);\n        \/\/ Normalize the result:\n        reconstruction = norm_0_255(reconstruction.reshape(1, images[0].rows));\n        \/\/ Display or save:\n        if(argc == 2) {\n            imshow(format(\"eigenface_reconstruction_%d\", num_components), reconstruction);\n        } else {\n            imwrite(format(\"%s\/eigenface_reconstruction_%d.png\", output_folder.c_str(), num_components), reconstruction);\n        }\n    }\n    \/\/ Display if we are not writing to an output folder:\n    if(argc == 2) {\n        waitKey(0);\n    }\n    return 0;\n}\n","avg_line_length":38.9948453608,"max_line_length":121,"alphanum_fraction":0.6329147389,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1159,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":26.0,"content":"#include \"m1UndoRedo.h\"\n#include \"Core\/Application.h\"\n#include \"Modules\/m1Input.h\"\n\n#include \"Tools\/Command.h\"\n\n#include \"Tools\/System\/Logger.h\"\n\nm1UndoRedo::m1UndoRedo() : Module(\"UndoRedo\", true)\n{\n}\n\nvoid m1UndoRedo::AddCommand(Command* command)\n{\n\tif (iterator != commands.size() - 1 && iterator != -1)\n\t{\n\t\tfor (int i = iterator + 1; i < commands.size(); ++i)\n\t\t{\n\t\t\tdelete commands[i];\n\t\t}\n\t\tcommands.erase(commands.begin() + iterator + 1, commands.end());\n\t}\n\n\tcommands.push_back(command);\n\n\titerator = commands.size() - 1;\n}\n\nUpdateStatus m1UndoRedo::Update()\n{\n\tif (App->input->IsKeyPressed(SDL_SCANCODE_LCTRL) && App->input->IsKeyDown(SDL_SCANCODE_Z) && iterator >= 0 &&\n\t\titerator < commands.size())\n\t{\n\t\tcommands[iterator]->Undo();\n\t\titerator += iterator > 0 ? -1 : 1;\n\t}\n\tif (App->input->IsKeyPressed(SDL_SCANCODE_LCTRL) && App->input->IsKeyDown(SDL_SCANCODE_Y) && iterator >= 0 && iterator < commands.size())\n\t{\n\t\tcommands[iterator]->Redo();\n\t\titerator += iterator < commands.size() - 1 ? 1 : -1;\n\t}\n\n\treturn UpdateStatus::UPDATE_CONTINUE;\n}\n\nbool m1UndoRedo::CleanUp()\n{\n\tfor (auto& command : commands)\n\t{\n\t\tdelete command;\n\t}\n\n\treturn true;\n}\n","avg_line_length":21.0727272727,"max_line_length":138,"alphanum_fraction":0.6635030198,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1984,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2.0,"content":"\ufeff\/*\n* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\").\n* You may not use this file except in compliance with the License.\n* A copy of the License is located at\n*\n*  http:\/\/aws.amazon.com\/apache2.0\n*\n* or in the \"license\" file accompanying this file. This file is distributed\n* on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n* express or implied. See the License for the specific language governing\n* permissions and limitations under the License.\n*\/\n\n#include <aws\/email\/model\/ConfigurationSet.h>\n#include <aws\/core\/utils\/xml\/XmlSerializer.h>\n#include <aws\/core\/utils\/StringUtils.h>\n#include <aws\/core\/utils\/memory\/stl\/AWSStringStream.h>\n\n#include <utility>\n\nusing namespace Aws::Utils::Xml;\nusing namespace Aws::Utils;\n\nnamespace Aws\n{\nnamespace SES\n{\nnamespace Model\n{\n\nConfigurationSet::ConfigurationSet() : \n    m_nameHasBeenSet(false)\n{\n}\n\nConfigurationSet::ConfigurationSet(const XmlNode& xmlNode) : \n    m_nameHasBeenSet(false)\n{\n  *this = xmlNode;\n}\n\nConfigurationSet& ConfigurationSet::operator =(const XmlNode& xmlNode)\n{\n  XmlNode resultNode = xmlNode;\n\n  if(!resultNode.IsNull())\n  {\n    XmlNode nameNode = resultNode.FirstChild(\"Name\");\n    if(!nameNode.IsNull())\n    {\n      m_name = StringUtils::Trim(nameNode.GetText().c_str());\n      m_nameHasBeenSet = true;\n    }\n  }\n\n  return *this;\n}\n\nvoid ConfigurationSet::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const\n{\n  if(m_nameHasBeenSet)\n  {\n      oStream << location << index << locationValue << \".Name=\" << StringUtils::URLEncode(m_name.c_str()) << \"&\";\n  }\n\n}\n\nvoid ConfigurationSet::OutputToStream(Aws::OStream& oStream, const char* location) const\n{\n  if(m_nameHasBeenSet)\n  {\n      oStream << location << \".Name=\" << StringUtils::URLEncode(m_name.c_str()) << \"&\";\n  }\n}\n\n} \/\/ namespace Model\n} \/\/ namespace SES\n} \/\/ namespace Aws\n","avg_line_length":24.4938271605,"max_line_length":131,"alphanum_fraction":0.7116935484,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":23230,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/* -----------------------------------------------------------------------\n * GGPO.net (http:\/\/ggpo.net)  -  Copyright 2009 GroundStorm Studios, LLC.\n *\n * Use of this software is governed by the MIT license that can be found\n * in the LICENSE file.\n *\/\n\n#include \"types.h\"\n#include \"udp_proto.h\"\n#include \"bitvector.h\"\n\nstatic const int UDP_HEADER_SIZE = 28;     \/* Size of IP + UDP headers *\/\nstatic const int NUM_SYNC_PACKETS = 5;\nstatic const int SYNC_RETRY_INTERVAL = 2000;\nstatic const int SYNC_FIRST_RETRY_INTERVAL = 500;\nstatic const int RUNNING_RETRY_INTERVAL = 200;\nstatic const int KEEP_ALIVE_INTERVAL    = 200;\nstatic const int QUALITY_REPORT_INTERVAL = 1000;\nstatic const int NETWORK_STATS_INTERVAL  = 1000;\nstatic const int UDP_SHUTDOWN_TIMER = 5000;\nstatic const int MAX_SEQ_DISTANCE = (1 << 15);\n\nUdpProtocol::UdpProtocol() :\n   _local_frame_advantage(0),\n   _remote_frame_advantage(0),\n   _queue(-1),\n   _magic_number(0),\n   _remote_magic_number(0),\n   _packets_sent(0),\n   _bytes_sent(0),\n   _stats_start_time(0),\n   _last_send_time(0),\n   _shutdown_timeout(0),\n   _disconnect_timeout(0),\n   _disconnect_notify_start(0),\n   _disconnect_notify_sent(false),\n   _disconnect_event_sent(false),\n   _connected(false),\n   _next_send_seq(0),\n   _next_recv_seq(0),\n   _udp(NULL)\n{\n   _last_sent_input.init(-1, NULL, 1);\n   _last_received_input.init(-1, NULL, 1);\n   _last_acked_input.init(-1, NULL, 1);\n\n   memset(&_state, 0, sizeof _state);\n   memset(_peer_connect_status, 0, sizeof(_peer_connect_status));\n   for (int i = 0; i < ARRAY_SIZE(_peer_connect_status); i++) {\n      _peer_connect_status[i].last_frame = -1;\n   }\n   memset(&_peer_addr, 0, sizeof _peer_addr);\n   _oo_packet.msg = NULL;\n\n   _send_latency = Platform::GetConfigInt(\"ggpo.network.delay\");\n   _oop_percent = Platform::GetConfigInt(\"ggpo.oop.percent\");\n}\n\nUdpProtocol::~UdpProtocol()\n{\n   ClearSendQueue();\n}\n\nvoid\nUdpProtocol::Init(Udp *udp,\n                  Poll &poll,\n                  int queue,\n                  char *ip,\n                  u_short port,\n                  UdpMsg::connect_status *status)\n{  \n   _udp = udp;\n   _queue = queue;\n   _local_connect_status = status;\n\n   _peer_addr.sin_family = AF_INET;\n   _peer_addr.sin_port = htons(port);\n   inet_pton(AF_INET, ip, &_peer_addr.sin_addr.s_addr);\n\n   do {\n      _magic_number = (uint16)rand();\n   } while (_magic_number == 0);\n   poll.RegisterLoop(this);\n}\n\nvoid\nUdpProtocol::SendInput(GameInput &input)\n{\n   if (_udp) {\n      if (_current_state == Running) {\n         \/*\n          * Check to see if this is a good time to adjust for the rift...\n          *\/\n         _timesync.advance_frame(input, _local_frame_advantage, _remote_frame_advantage);\n\n         \/*\n          * Save this input packet\n          *\n          * XXX: This queue may fill up for spectators who do not ack input packets in a timely\n          * manner.  When this happens, we can either resize the queue (ug) or disconnect them\n          * (better, but still ug).  For the meantime, make this queue really big to decrease\n          * the odds of this happening...\n          *\/\n         _pending_output.push(input);\n      }\n      SendPendingOutput();\n   }  \n}\n\nvoid\nUdpProtocol::SendPendingOutput()\n{\n   UdpMsg *msg = new UdpMsg(UdpMsg::Input);\n   int i, j, offset = 0;\n   uint8 *bits;\n   GameInput last;\n\n   if (_pending_output.size()) {\n      last = _last_acked_input;\n      bits = msg->u.input.bits;\n\n      msg->u.input.start_frame = _pending_output.front().frame;\n      msg->u.input.input_size = (uint8)_pending_output.front().size;\n\n      ASSERT(last.frame == -1 || last.frame + 1 == msg->u.input.start_frame);\n      for (j = 0; j < _pending_output.size(); j++) {\n         GameInput &current = _pending_output.item(j);\n         if (memcmp(current.bits, last.bits, current.size) != 0) {\n            ASSERT((GAMEINPUT_MAX_BYTES * GAMEINPUT_MAX_PLAYERS * 8) < (1 << BITVECTOR_NIBBLE_SIZE));\n            for (i = 0; i < current.size * 8; i++) {\n               ASSERT(i < (1 << BITVECTOR_NIBBLE_SIZE));\n               if (current.value(i) != last.value(i)) {\n                  BitVector_SetBit(msg->u.input.bits, &offset);\n                  (current.value(i) ? BitVector_SetBit : BitVector_ClearBit)(bits, &offset);\n                  BitVector_WriteNibblet(bits, i, &offset);\n               }\n            }\n         }\n         BitVector_ClearBit(msg->u.input.bits, &offset);\n         last = _last_sent_input = current;\n      }\n   } else {\n      msg->u.input.start_frame = 0;\n      msg->u.input.input_size = 0;\n   }\n   msg->u.input.ack_frame = _last_received_input.frame;\n   msg->u.input.num_bits = (uint16)offset;\n\n   msg->u.input.disconnect_requested = _current_state == Disconnected;\n   if (_local_connect_status) {\n      memcpy(msg->u.input.peer_connect_status, _local_connect_status, sizeof(UdpMsg::connect_status) * UDP_MSG_MAX_PLAYERS);\n   } else {\n      memset(msg->u.input.peer_connect_status, 0, sizeof(UdpMsg::connect_status) * UDP_MSG_MAX_PLAYERS);\n   }\n\n   ASSERT(offset < MAX_COMPRESSED_BITS);\n\n   SendMsg(msg);\n}\n\nvoid\nUdpProtocol::SendInputAck()\n{\n   UdpMsg *msg = new UdpMsg(UdpMsg::InputAck);\n   msg->u.input_ack.ack_frame = _last_received_input.frame;\n   SendMsg(msg);\n}\n\nbool\nUdpProtocol::GetEvent(UdpProtocol::Event &e)\n{\n   if (_event_queue.size() == 0) {\n      return false;\n   }\n   e = _event_queue.front();\n   _event_queue.pop();\n   return true;\n}\n\n\nbool\nUdpProtocol::OnLoopPoll(void *cookie)\n{\n   if (!_udp) {\n      return true;\n   }\n\n   unsigned int now = Platform::GetCurrentTimeMS();\n   unsigned int next_interval;\n\n   PumpSendQueue();\n   switch (_current_state) {\n   case Syncing:\n      next_interval = (_state.sync.roundtrips_remaining == NUM_SYNC_PACKETS) ? SYNC_FIRST_RETRY_INTERVAL : SYNC_RETRY_INTERVAL;\n      if (_last_send_time && _last_send_time + next_interval < now) {\n         Log(\"No luck syncing after %d ms... Re-queueing sync packet.\\n\", next_interval);\n         SendSyncRequest();\n      }\n      break;\n\n   case Running:\n      \/\/ xxx: rig all this up with a timer wrapper\n      if (!_state.running.last_input_packet_recv_time || _state.running.last_input_packet_recv_time + RUNNING_RETRY_INTERVAL < now) {\n         Log(\"Haven't exchanged packets in a while (last received:%d  last sent:%d).  Resending.\\n\", _last_received_input.frame, _last_sent_input.frame);\n         SendPendingOutput();\n         _state.running.last_input_packet_recv_time = now;\n      }\n\n      if (!_state.running.last_quality_report_time || _state.running.last_quality_report_time + QUALITY_REPORT_INTERVAL < now) {\n         UdpMsg *msg = new UdpMsg(UdpMsg::QualityReport);\n         msg->u.quality_report.ping = Platform::GetCurrentTimeMS();\n         msg->u.quality_report.frame_advantage = (uint8)_local_frame_advantage;\n         SendMsg(msg);\n         _state.running.last_quality_report_time = now;\n      }\n\n      if (!_state.running.last_network_stats_interval || _state.running.last_network_stats_interval + NETWORK_STATS_INTERVAL < now) {\n         UpdateNetworkStats();\n         _state.running.last_network_stats_interval =  now;\n      }\n\n      if (_last_send_time && _last_send_time + KEEP_ALIVE_INTERVAL < now) {\n         Log(\"Sending keep alive packet\\n\");\n         SendMsg(new UdpMsg(UdpMsg::KeepAlive));\n      }\n\n      if (_disconnect_timeout && _disconnect_notify_start && \n         !_disconnect_notify_sent && (_last_recv_time + _disconnect_notify_start < now)) {\n         Log(\"Endpoint has stopped receiving packets for %d ms.  Sending notification.\\n\", _disconnect_notify_start);\n         Event e(Event::NetworkInterrupted);\n         e.u.network_interrupted.disconnect_timeout = _disconnect_timeout - _disconnect_notify_start;\n         QueueEvent(e);\n         _disconnect_notify_sent = true;\n      }\n\n      if (_disconnect_timeout && (_last_recv_time + _disconnect_timeout < now)) {\n         if (!_disconnect_event_sent) {\n            Log(\"Endpoint has stopped receiving packets for %d ms.  Disconnecting.\\n\", _disconnect_timeout);\n            QueueEvent(Event(Event::Disconnected));\n            _disconnect_event_sent = true;\n         }\n      }\n      break;\n\n   case Disconnected:\n      if (_shutdown_timeout < now) {\n         Log(\"Shutting down udp connection.\\n\");\n         _udp = NULL;\n         _shutdown_timeout = 0;\n      }\n\n   }\n\n\n   return true;\n}\n\nvoid\nUdpProtocol::Disconnect()\n{\n   _current_state = Disconnected;\n   _shutdown_timeout = Platform::GetCurrentTimeMS() + UDP_SHUTDOWN_TIMER;\n}\n\nvoid\nUdpProtocol::SendSyncRequest()\n{\n   _state.sync.random = rand() & 0xFFFF;\n   UdpMsg *msg = new UdpMsg(UdpMsg::SyncRequest);\n   msg->u.sync_request.random_request = _state.sync.random;\n   SendMsg(msg);\n}\n\nvoid\nUdpProtocol::SendMsg(UdpMsg *msg)\n{\n   LogMsg(\"send\", msg);\n\n   _packets_sent++;\n   _last_send_time = Platform::GetCurrentTimeMS();\n   _bytes_sent += msg->PacketSize();\n\n   msg->hdr.magic = _magic_number;\n   msg->hdr.sequence_number = _next_send_seq++;\n\n   _send_queue.push(QueueEntry(Platform::GetCurrentTimeMS(), _peer_addr, msg));\n   PumpSendQueue();\n}\n\nbool\nUdpProtocol::HandlesMsg(sockaddr_in &from,\n                        UdpMsg *msg)\n{\n   if (!_udp) {\n      return false;\n   }\n   return _peer_addr.sin_addr.s_addr == from.sin_addr.s_addr &&\n          _peer_addr.sin_port == from.sin_port;\n}\n\nvoid\nUdpProtocol::OnMsg(UdpMsg *msg, int len)\n{\n   bool handled = false;\n   typedef bool (UdpProtocol::*DispatchFn)(UdpMsg *msg, int len);\n   static const DispatchFn table[] = {\n      &UdpProtocol::OnInvalid,             \/* Invalid *\/\n      &UdpProtocol::OnSyncRequest,         \/* SyncRequest *\/\n      &UdpProtocol::OnSyncReply,           \/* SyncReply *\/\n      &UdpProtocol::OnInput,               \/* Input *\/\n      &UdpProtocol::OnQualityReport,       \/* QualityReport *\/\n      &UdpProtocol::OnQualityReply,        \/* QualityReply *\/\n      &UdpProtocol::OnKeepAlive,           \/* KeepAlive *\/\n      &UdpProtocol::OnInputAck,            \/* InputAck *\/\n   };\n\n   \/\/ filter out messages that don't match what we expect\n   uint16 seq = msg->hdr.sequence_number;\n   if (msg->hdr.type != UdpMsg::SyncRequest &&\n       msg->hdr.type != UdpMsg::SyncReply) {\n      if (msg->hdr.magic != _remote_magic_number) {\n         LogMsg(\"recv rejecting\", msg);\n         return;\n      }\n\n      \/\/ filter out out-of-order packets\n      uint16 skipped = (uint16)((int)seq - (int)_next_recv_seq);\n      \/\/ Log(\"checking sequence number -> next - seq : %d - %d = %d\\n\", seq, _next_recv_seq, skipped);\n      if (skipped > MAX_SEQ_DISTANCE) {\n         Log(\"dropping out of order packet (seq: %d, last seq:%d)\\n\", seq, _next_recv_seq);\n         return;\n      }\n   }\n\n   _next_recv_seq = seq;\n   LogMsg(\"recv\", msg);\n   if (msg->hdr.type >= ARRAY_SIZE(table)) {\n      OnInvalid(msg, len);\n   } else {\n      handled = (this->*(table[msg->hdr.type]))(msg, len);\n   }\n   if (handled) {\n      _last_recv_time = Platform::GetCurrentTimeMS();\n      if (_disconnect_notify_sent && _current_state == Running) {\n         QueueEvent(Event(Event::NetworkResumed));   \n         _disconnect_notify_sent = false;\n      }\n   }\n}\n\nvoid\nUdpProtocol::UpdateNetworkStats(void)\n{\n   int now = Platform::GetCurrentTimeMS();\n\n   if (_stats_start_time == 0) {\n      _stats_start_time = now;\n   }\n\n   int total_bytes_sent = _bytes_sent + (UDP_HEADER_SIZE * _packets_sent);\n   float seconds = (float)((now - _stats_start_time) \/ 1000.0);\n   float Bps = total_bytes_sent \/ seconds;\n   float udp_overhead = (float)(100.0 * (UDP_HEADER_SIZE * _packets_sent) \/ _bytes_sent);\n\n   _kbps_sent = int(Bps \/ 1024);\n\n   Log(\"Network Stats -- Bandwidth: %.2f KBps   Packets Sent: %5d (%.2f pps)   \"\n       \"KB Sent: %.2f    UDP Overhead: %.2f %%.\\n\",\n       _kbps_sent, \n       _packets_sent,\n       (float)_packets_sent * 1000 \/ (now - _stats_start_time),\n       total_bytes_sent \/ 1024.0,\n       udp_overhead);\n}\n\n\nvoid\nUdpProtocol::QueueEvent(const UdpProtocol::Event &evt)\n{\n   LogEvent(\"Queuing event\", evt);\n   _event_queue.push(evt);\n}\n\nvoid\nUdpProtocol::Synchronize()\n{\n   if (_udp) {\n      _current_state = Syncing;\n      _state.sync.roundtrips_remaining = NUM_SYNC_PACKETS;\n      SendSyncRequest();\n   }\n}\n\nbool\nUdpProtocol::GetPeerConnectStatus(int id, int *frame)\n{\n   *frame = _peer_connect_status[id].last_frame;\n   return !_peer_connect_status[id].disconnected;\n}\n\nvoid\nUdpProtocol::Log(const char *fmt, ...)\n{\n   char buf[1024];\n   size_t offset;\n   va_list args;\n\n   sprintf_s(buf, ARRAY_SIZE(buf), \"udpproto%d | \", _queue);\n   offset = strlen(buf);\n   va_start(args, fmt);\n   vsnprintf(buf + offset, ARRAY_SIZE(buf) - offset - 1, fmt, args);\n   buf[ARRAY_SIZE(buf)-1] = '\\0';\n   ::Log(buf);\n   va_end(args);\n}\n\nvoid\nUdpProtocol::LogMsg(const char *prefix, UdpMsg *msg)\n{\n   switch (msg->hdr.type) {\n   case UdpMsg::SyncRequest:\n      Log(\"%s sync-request (%d).\\n\", prefix,\n          msg->u.sync_request.random_request);\n      break;\n   case UdpMsg::SyncReply:\n      Log(\"%s sync-reply (%d).\\n\", prefix,\n          msg->u.sync_reply.random_reply);\n      break;\n   case UdpMsg::QualityReport:\n      Log(\"%s quality report.\\n\", prefix);\n      break;\n   case UdpMsg::QualityReply:\n      Log(\"%s quality reply.\\n\", prefix);\n      break;\n   case UdpMsg::KeepAlive:\n      Log(\"%s keep alive.\\n\", prefix);\n      break;\n   case UdpMsg::Input:\n      Log(\"%s game-compressed-input %d (+ %d bits).\\n\", prefix, msg->u.input.start_frame, msg->u.input.num_bits);\n      break;\n   case UdpMsg::InputAck:\n      Log(\"%s input ack.\\n\", prefix);\n      break;\n   default:\n      ASSERT(FALSE && \"Unknown UdpMsg type.\");\n   }\n}\n\nvoid\nUdpProtocol::LogEvent(const char *prefix, const UdpProtocol::Event &evt)\n{\n   switch (evt.type) {\n   case UdpProtocol::Event::Synchronzied:\n      Log(\"%s (event: Synchronzied).\\n\", prefix);\n      break;\n   }\n}\n\nbool\nUdpProtocol::OnInvalid(UdpMsg *msg, int len)\n{\n   ASSERT(FALSE && \"Invalid msg in UdpProtocol\");\n   return false;\n}\n\nbool\nUdpProtocol::OnSyncRequest(UdpMsg *msg, int len)\n{\n   if (_remote_magic_number != 0 && msg->hdr.magic != _remote_magic_number) {\n      Log(\"Ignoring sync request from unknown endpoint (%d != %d).\\n\", \n           msg->hdr.magic, _remote_magic_number);\n      return false;\n   }\n   UdpMsg *reply = new UdpMsg(UdpMsg::SyncReply);\n   reply->u.sync_reply.random_reply = msg->u.sync_request.random_request;\n   SendMsg(reply);\n   return true;\n}\n\nbool\nUdpProtocol::OnSyncReply(UdpMsg *msg, int len)\n{\n   if (_current_state != Syncing) {\n      Log(\"Ignoring SyncReply while not synching.\\n\");\n      return msg->hdr.magic == _remote_magic_number;\n   }\n\n   if (msg->u.sync_reply.random_reply != _state.sync.random) {\n      Log(\"sync reply %d != %d.  Keep looking...\\n\",\n          msg->u.sync_reply.random_reply, _state.sync.random);\n      return false;\n   }\n\n   if (!_connected) {\n      QueueEvent(Event(Event::Connected));\n      _connected = true;\n   }\n\n   Log(\"Checking sync state (%d round trips remaining).\\n\", _state.sync.roundtrips_remaining);\n   if (--_state.sync.roundtrips_remaining == 0) {\n      Log(\"Synchronized!\\n\");\n      QueueEvent(UdpProtocol::Event(UdpProtocol::Event::Synchronzied));\n      _current_state = Running;\n      _last_received_input.frame = -1;\n      _remote_magic_number = msg->hdr.magic;\n   } else {\n      UdpProtocol::Event evt(UdpProtocol::Event::Synchronizing);\n      evt.u.synchronizing.total = NUM_SYNC_PACKETS;\n      evt.u.synchronizing.count = NUM_SYNC_PACKETS - _state.sync.roundtrips_remaining;\n      QueueEvent(evt);\n      SendSyncRequest();\n   }\n   return true;\n}\n\nbool\nUdpProtocol::OnInput(UdpMsg *msg, int len)\n{\n   \/*\n    * If a disconnect is requested, go ahead and disconnect now.\n    *\/\n   bool disconnect_requested = msg->u.input.disconnect_requested;\n   if (disconnect_requested) {\n      if (_current_state != Disconnected && !_disconnect_event_sent) {\n         Log(\"Disconnecting endpoint on remote request.\\n\");\n         QueueEvent(Event(Event::Disconnected));\n         _disconnect_event_sent = true;\n      }\n   } else {\n      \/*\n       * Update the peer connection status if this peer is still considered to be part\n       * of the network.\n       *\/\n      UdpMsg::connect_status* remote_status = msg->u.input.peer_connect_status;\n      for (int i = 0; i < ARRAY_SIZE(_peer_connect_status); i++) {\n         ASSERT(remote_status[i].last_frame >= _peer_connect_status[i].last_frame);\n         _peer_connect_status[i].disconnected = _peer_connect_status[i].disconnected || remote_status[i].disconnected;\n         _peer_connect_status[i].last_frame = MAX(_peer_connect_status[i].last_frame, remote_status[i].last_frame);\n      }\n   }\n\n   \/*\n    * Decompress the input.\n    *\/\n   int last_received_frame_number = _last_received_input.frame;\n   if (msg->u.input.num_bits) {\n      int offset = 0;\n      uint8 *bits = (uint8 *)msg->u.input.bits;\n      int numBits = msg->u.input.num_bits;\n      int currentFrame = msg->u.input.start_frame;\n\n      _last_received_input.size = msg->u.input.input_size;\n      if (_last_received_input.frame < 0) {\n         _last_received_input.frame = msg->u.input.start_frame - 1;\n      }\n      while (offset < numBits) {\n         \/*\n          * Keep walking through the frames (parsing bits) until we reach\n          * the inputs for the frame right after the one we're on.\n          *\/\n         ASSERT(currentFrame <= (_last_received_input.frame + 1));\n         bool useInputs = currentFrame == _last_received_input.frame + 1;\n\n         while (BitVector_ReadBit(bits, &offset)) {\n            int on = BitVector_ReadBit(bits, &offset);\n            int button = BitVector_ReadNibblet(bits, &offset);\n            if (useInputs) {\n               if (on) {\n                  _last_received_input.set(button);\n               } else {\n                  _last_received_input.clear(button);\n               }\n            }\n         }\n         ASSERT(offset <= numBits);\n\n         \/*\n          * Now if we want to use these inputs, go ahead and send them to\n          * the emulator.\n          *\/\n         if (useInputs) {\n            \/*\n             * Move forward 1 frame in the stream.\n             *\/\n            char desc[1024];\n            ASSERT(currentFrame == _last_received_input.frame + 1);\n            _last_received_input.frame = currentFrame;\n\n            \/*\n             * Send the event to the emualtor\n             *\/\n            UdpProtocol::Event evt(UdpProtocol::Event::Input);\n            evt.u.input.input = _last_received_input;\n\n            _last_received_input.desc(desc, ARRAY_SIZE(desc));\n\n            _state.running.last_input_packet_recv_time = Platform::GetCurrentTimeMS();\n\n            Log(\"Sending frame %d to emu queue %d (%s).\\n\", _last_received_input.frame, _queue, desc);\n            QueueEvent(evt);\n\n         } else {\n            Log(\"Skipping past frame:(%d) current is %d.\\n\", currentFrame, _last_received_input.frame);\n         }\n\n         \/*\n          * Move forward 1 frame in the input stream.\n          *\/\n         currentFrame++;\n      }\n   }\n   ASSERT(_last_received_input.frame >= last_received_frame_number);\n\n   \/*\n    * Get rid of our buffered input\n    *\/\n   while (_pending_output.size() && _pending_output.front().frame < msg->u.input.ack_frame) {\n      Log(\"Throwing away pending output frame %d\\n\", _pending_output.front().frame);\n      _last_acked_input = _pending_output.front();\n      _pending_output.pop();\n   }\n   return true;\n}\n\n\nbool\nUdpProtocol::OnInputAck(UdpMsg *msg, int len)\n{\n   \/*\n    * Get rid of our buffered input\n    *\/\n   while (_pending_output.size() && _pending_output.front().frame < msg->u.input_ack.ack_frame) {\n      Log(\"Throwing away pending output frame %d\\n\", _pending_output.front().frame);\n      _last_acked_input = _pending_output.front();\n      _pending_output.pop();\n   }\n   return true;\n}\n\nbool\nUdpProtocol::OnQualityReport(UdpMsg *msg, int len)\n{\n   \/\/ send a reply so the other side can compute the round trip transmit time.\n   UdpMsg *reply = new UdpMsg(UdpMsg::QualityReply);\n   reply->u.quality_reply.pong = msg->u.quality_report.ping;\n   SendMsg(reply);\n\n   _remote_frame_advantage = msg->u.quality_report.frame_advantage;\n   return true;\n}\n\nbool\nUdpProtocol::OnQualityReply(UdpMsg *msg, int len)\n{\n   _round_trip_time = Platform::GetCurrentTimeMS() - msg->u.quality_reply.pong;\n   return true;\n}\n\nbool\nUdpProtocol::OnKeepAlive(UdpMsg *msg, int len)\n{\n   return true;\n}\n\nvoid\nUdpProtocol::GetNetworkStats(struct GGPONetworkStats *s)\n{\n   s->network.ping = _round_trip_time;\n   s->network.send_queue_len = _pending_output.size();\n   s->network.kbps_sent = _kbps_sent;\n   s->timesync.remote_frames_behind = _remote_frame_advantage;\n   s->timesync.local_frames_behind = _local_frame_advantage;\n}\n\nvoid\nUdpProtocol::SetLocalFrameNumber(int localFrame)\n{\n   \/*\n    * Estimate which frame the other guy is one by looking at the\n    * last frame they gave us plus some delta for the one-way packet\n    * trip time.\n    *\/\n   int remoteFrame = _last_received_input.frame + (_round_trip_time * 60 \/ 1000);\n\n   \/*\n    * Our frame advantage is how many frames *behind* the other guy\n    * we are.  Counter-intuative, I know.  It's an advantage because\n    * it means they'll have to predict more often and our moves will\n    * pop more frequenetly.\n    *\/\n   _local_frame_advantage = remoteFrame - localFrame;\n}\n\nint\nUdpProtocol::RecommendFrameDelay()\n{\n   \/\/ XXX: require idle input should be a configuration parameter\n   return _timesync.recommend_frame_wait_duration(false);\n}\n\n\nvoid\nUdpProtocol::SetDisconnectTimeout(int timeout)\n{\n   _disconnect_timeout = timeout;\n}\n\nvoid\nUdpProtocol::SetDisconnectNotifyStart(int timeout)\n{\n   _disconnect_notify_start = timeout;\n}\n\nvoid\nUdpProtocol::PumpSendQueue()\n{\n   while (!_send_queue.empty()) {\n      QueueEntry &entry = _send_queue.front();\n\n      if (_send_latency) {\n         \/\/ should really come up with a gaussian distributation based on the configured\n         \/\/ value, but this will do for now.\n         int jitter = (_send_latency * 2 \/ 3) + ((rand() % _send_latency) \/ 3);\n         if (Platform::GetCurrentTimeMS() < _send_queue.front().queue_time + jitter) {\n            break;\n         }\n      }\n      if (_oop_percent && !_oo_packet.msg && ((rand() % 100) < _oop_percent)) {\n         int delay = rand() % (_send_latency * 10 + 1000);\n         Log(\"creating rogue oop (seq: %d  delay: %d)\\n\", entry.msg->hdr.sequence_number, delay);\n         _oo_packet.send_time = Platform::GetCurrentTimeMS() + delay;\n         _oo_packet.msg = entry.msg;\n         _oo_packet.dest_addr = entry.dest_addr;\n      } else {\n         ASSERT(entry.dest_addr.sin_addr.s_addr);\n\n         _udp->SendTo((char *)entry.msg, entry.msg->PacketSize(), 0,\n                      (struct sockaddr *)&entry.dest_addr, sizeof entry.dest_addr);\n\n         delete entry.msg;\n      }\n      _send_queue.pop();\n   }\n   if (_oo_packet.msg && _oo_packet.send_time < Platform::GetCurrentTimeMS()) {\n      Log(\"sending rogue oop!\");\n      _udp->SendTo((char *)_oo_packet.msg, _oo_packet.msg->PacketSize(), 0,\n                     (struct sockaddr *)&_oo_packet.dest_addr, sizeof _oo_packet.dest_addr);\n\n      delete _oo_packet.msg;\n      _oo_packet.msg = NULL;\n   }\n}\n\nvoid\nUdpProtocol::ClearSendQueue()\n{\n   while (!_send_queue.empty()) {\n      delete _send_queue.front().msg;\n      _send_queue.pop();\n   }\n}\n","avg_line_length":30.4855643045,"max_line_length":153,"alphanum_fraction":0.6402927249,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2412,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"XMLParser.h\"\n\n#include <string.h>\n\nXMLParser::XMLParser()\n{\n    callback = NULL;\n    reset();\n}\n\nvoid (*XMLParser::getCallback())(void*, bool, char*, char*, char*)\n{\n    return callback;\n}\nvoid XMLParser::setCallback(void (*function)(void*, bool, char*, char*, char*), void* data)\n{\n    context = data;\n    callback = function;\n}\n\nvoid XMLParser::reset()\n{\n    fInAttribute = false;\n    fInValue = false;\n    fTagClosed = false;\n\n    memset(tag, 0, MAX_STRING_LEN);\n    memset(attribute, 0, MAX_STRING_LEN);\n    memset(value, 0, MAX_STRING_LEN);\n    memset(tmp, 0, MAX_STRING_LEN);\n}\n\nvoid XMLParser::addChar(char ch, char* str)\n{\n    if (strlen(str) < MAX_STRING_LEN-1)\n    {\n        str[strlen(str)] = ch;\n    }\n}\n\nvoid XMLParser::parse(char in)\n{\n    if (callback == NULL)\n    {\n        return;\n    }\n\n    switch (in)\n    {\n    case '<': \/\/ Tag starting\n        memset(tmp, 0, strlen(tmp));\n        break;\n\n    case ' ':\n        if (strlen(tag) == 0)\n        {\n            \/\/ Save tag name\n            strcpy(tag, tmp);\n            callback(context, false, tag, (char *)\"\", (char *)\"\");\n        }\n\n        if (fInValue)\n        {\n            addChar(in, tmp);\n        }\n        else\n        {\n            fInAttribute = true;\n            memset(tmp, 0, strlen(tmp));\n        }\n        break;\n\n    case '\/':\n        if (fInValue)\n        {\n            addChar(in, tmp);\n        }\n        else\n        {\n            fTagClosed = true;\n        }\n        break;\n\n    case '>': \/\/ Tag ending\n        if (strlen(tag) == 0)\n        {\n            strcpy(tag, tmp);\n        }\n        callback(context, fTagClosed, tag, (char *)\"\", (char *)\"\");\n        reset();\n        break;\n\n    case '=':\n        if (fInValue)\n        {\n            addChar(in, tmp);\n        }\n        else if (fInAttribute)\n        {\n            strcpy(attribute, tmp);\n            memset(tmp, 0, strlen(tmp));\n            fInAttribute = false;\n        }\n        break;\n\n    case '\"':\n        if (fInValue)\n        {\n            strcpy(value, tmp);\n            memset(tmp, 0, strlen(tmp));\n            fInValue = false;\n\n            \/\/ Process tag, attribute, value\n            callback(context, false, tag, attribute, value);\n        }\n        else\n        {\n            fInValue = true;\n        }\n        break;\n\n    case 10:\n        \/\/ New line, reset\n        reset();\n        break;\n\n    default:\n        addChar(in, tmp);\n    }\n\n}\n\n\n","avg_line_length":18.0,"max_line_length":91,"alphanum_fraction":0.4585406302,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4326,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <graphics\/graphicsprecomp.h>\n\n#include <graphics\/shader\/shadervertexformatgenerator.h>\n\n#include <graphics\/vertexformat.h>\n\n#include <system\/string.h>\n#include <system\/wrapper\/wrapper.h>\n\nnamespace Shipyard\n{;\n\nvoid WriteVertexFormatShaderFile()\n{\n    FileHandler vertexFormatShaderFile;\n    vertexFormatShaderFile.Open(\"shaders\\\\vertexformats\\\\vertexformats.hlsl\", FileHandlerOpenFlag(FileHandlerOpenFlag::FileHandlerOpenFlag_Write | FileHandlerOpenFlag::FileHandlerOpenFlag_Create));\n\n    if (!vertexFormatShaderFile.IsOpen())\n    {\n        return;\n    }\n\n    StringA content;\n    content += \"\/**\\n* AUTO-GENERATED FILE\\n**\/\\n\";\n    content += \"#ifndef SHADER_VERTEX_FORMATS_HLSL\\n\";\n    content += \"#define SHADER_VERTEX_FORMATS_HLSL\\n\\n\";\n\n    content += \"#ifndef VERTEX_FORMAT_TYPE\\n\";\n    content += \"#define VERTEX_FORMAT_TYPE 0\\n\";\n    content += \"#endif \/\/ #ifndef VERTEX_FORMAT_TYPE\\n\\n\";\n\n    content += \"#\";\n\n    for (shipUint16 i = 0; i < shipUint16(VertexFormatType::VertexFormatType_Count); i++)\n    {\n        VertexFormatType vertexFormatType = VertexFormatType(i);\n\n        content += StringFormat(\"if VERTEX_FORMAT_TYPE == %d\\n\\n\", i);\n\n        content += GetShaderVertexInputForVertexFormat(vertexFormatType);\n\n        if (VertexFormatTypeContainsColor(vertexFormatType))\n        {\n            content += \"#define VERTEX_FORMAT_HAS_COLOR\\n\";\n        }\n\n        if (VertexFormatTypeContainsUV(vertexFormatType))\n        {\n            content += \"#define VERTEX_FORMAT_HAS_TEXCOORDS\\n\";\n        }\n\n        if (VertexFormatTypeContainsNormals(vertexFormatType))\n        {\n            content += \"#define VERTEX_FORMAT_HAS_NORMALS\\n\";\n        }\n\n        if (VertexFormatTypeContainsTangents(vertexFormatType))\n        {\n            content += \"#define VERTEX_FORMAT_HAS_TANGENTS\\n\";\n        }\n\n        content += \"\\n\";\n\n        shipBool isLast = (i == shipUint16(VertexFormatType::VertexFormatType_Count) - 1);\n        if (!isLast)\n        {\n            content += \"#el\";\n        }\n    }\n\n    content += \"#else\\n\\n\";\n\n    content += \"struct vs_input\\n\";\n    content += \"{\\n\";\n    content += \"    float4 position : POSITION;\\n\";\n    content += \"};\\n\\n\";\n\n    content += \"#endif\\n\\n\";\n\n    content += \"#endif \/\/ #ifndef SHADER_VERTEX_FORMATS_HLSL\";\n\n    constexpr shipUint32 startingPosition = 0;\n    constexpr shipBool flush = true;\n    vertexFormatShaderFile.WriteChars(startingPosition, content.GetBuffer(), content.Size(), flush);\n}\n\nStringA GetShaderVertexInputForVertexFormat(VertexFormatType vertexFormatType)\n{\n    StringA shaderVertexInput;\n\n    shaderVertexInput += \"struct vs_input\\n\";\n    shaderVertexInput += \"{\\n\";\n\n    VertexFormat* vertexFormat = nullptr;\n    GetVertexFormat(vertexFormatType, vertexFormat);\n    SHIP_ASSERT(vertexFormat != nullptr);\n\n    shipUint32 numInputLayouts = vertexFormat->GetNumInputLayouts();\n    const InputLayout* inputLayouts = vertexFormat->GetInputLayouts();\n\n    for (shipUint32 j = 0; j < numInputLayouts; j++)\n    {\n        const InputLayout& inputLayout = inputLayouts[j];\n\n        BaseFormatType shaderInputBaseFormatType = GetBaseFormatType(inputLayout.m_Format);\n        shipUint32 shaderInputNumComponents = GetFormatNumComponents(inputLayout.m_Format);\n\n        const shipChar* shaderInputBaseFormatTypeName = GetBaseFormatTypeName(shaderInputBaseFormatType);\n\n        const shipChar* shaderInputType = StringFormat(\"%s%d\", shaderInputBaseFormatTypeName, shaderInputNumComponents);\n\n        const shipChar* shaderInputName = GetVertexShaderInputName(inputLayout.m_SemanticName);\n        if (inputLayout.m_SemanticIndex > 0)\n        {\n            shaderInputName = StringFormat(\"%s%d\", shaderInputName, inputLayout.m_SemanticIndex);\n        }\n\n        const shipChar* semanticName = GetVertexSemanticName(inputLayout.m_SemanticName);\n        if (inputLayout.m_SemanticIndex > 0)\n        {\n            semanticName = StringFormat(\"%s%d\", semanticName, inputLayout.m_SemanticIndex);\n        }\n\n        shaderVertexInput += \"    \";\n        shaderVertexInput += shaderInputType;\n        shaderVertexInput += \" \";\n        shaderVertexInput += shaderInputName;\n        shaderVertexInput += \" : \";\n        shaderVertexInput += semanticName;\n        shaderVertexInput += \";\\n\";\n    }\n\n    shaderVertexInput += \"};\\n\\n\";\n\n    return shaderVertexInput;\n}\n\n}","avg_line_length":31.347826087,"max_line_length":197,"alphanum_fraction":0.674988442,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1529,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":8.0,"content":"#include <iris\/iris.h>\n#include <cassert>\n\nusing namespace iris;\n\ntemplate <typename T>\nvoid test_vabs(T(*func)(T)) {\n    T v, result;\n\n    \/\/ All positive\n    for(size_t i = 0; i < T::length; i++) {\n        v.template at<typename T::elementType>(i) = i;\n    }\n    result = func(v);\n    for(size_t i = 0; i < T::length; i++) {\n        assert(result.template at<typename T::elementType>(i) == static_cast<typename T::elementType>(i));\n    }\n\n    \/\/ All negative\n    for(size_t i = 0; i < T::length; i++) {\n        v.template at<typename T::elementType>(i) = -static_cast<typename T::elementType>(i);\n    }\n    result = func(v);\n    for(size_t i = 0; i < T::length; i++) {\n        assert(result.template at<typename T::elementType>(i) == static_cast<typename T::elementType>(i));\n    }\n\n    for(size_t i = 0; i < T::length; i++) {\n        v.template at<typename T::elementType>(i) = std::numeric_limits<typename T::elementType>::min();\n    }\n    result = func(v);\n    for(size_t i = 0; i < T::length; i++) {\n        if(std::numeric_limits<typename T::elementType>::is_signed) {\n            assert(result.template at<typename T::elementType>(i) == std::numeric_limits<typename T::elementType>::min());\n        } else {\n            assert(result.template at<typename T::elementType>(i) == -1);\n        }\n    }\n}\n\nint main() {\n    test_vabs(vabs_s8);\n    test_vabs(vabs_s16);\n    test_vabs(vabs_s32);\n\n    test_vabs(vabs_f32);\n\n    test_vabs(vabsq_s8);\n    test_vabs(vabsq_s16);\n    test_vabs(vabsq_s32);\n\n    test_vabs(vabsq_f32);\n}\n","avg_line_length":28.3148148148,"max_line_length":122,"alphanum_fraction":0.5951602354,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":56666,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/* Generated code for Python source for module 'django.db.models.functions'\n * created by Nuitka version 0.5.28.2\n *\n * This code is in part copyright 2017 Kay Hayen.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"nuitka\/prelude.h\"\n\n#include \"__helpers.h\"\n\n\/* The _module_django$db$models$functions is a Python object pointer of module type. *\/\n\n\/* Note: For full compatibility with CPython, every module variable access\n * needs to go through it except for cases where the module cannot possibly\n * have changed in the mean time.\n *\/\n\nPyObject *module_django$db$models$functions;\nPyDictObject *moduledict_django$db$models$functions;\n\n\/* The module constants used, if any. *\/\nextern PyObject *const_str_plain_ExtractMinute;\nextern PyObject *const_str_plain_Trunc;\nextern PyObject *const_str_plain_environ;\nextern PyObject *const_str_plain_TruncDate;\nextern PyObject *const_tuple_e264d9df221704bac1b8813696d55517_tuple;\nextern PyObject *const_str_plain_ModuleSpec;\nextern PyObject *const_str_plain___spec__;\nextern PyObject *const_str_plain___package__;\nextern PyObject *const_str_plain_ConcatPair;\nstatic PyObject *const_str_digest_fe19ab428a9952bfcba7a98da752b153;\nextern PyObject *const_str_plain___all__;\nextern PyObject *const_int_pos_1;\nextern PyObject *const_str_plain_ExtractYear;\nextern PyObject *const_str_plain_TruncMinute;\nextern PyObject *const_str_plain_Substr;\nextern PyObject *const_str_plain___file__;\nextern PyObject *const_str_plain_Upper;\nextern PyObject *const_str_plain_ExtractSecond;\nextern PyObject *const_tuple_9aafdb4681f02593d1d6ac7779e00e9d_tuple;\nextern PyObject *const_str_plain_Greatest;\nextern PyObject *const_str_plain_Coalesce;\nextern PyObject *const_str_plain_Lower;\nextern PyObject *const_str_plain_path;\nstatic PyObject *const_tuple_ae54af5000b7d151d08db7b05d852532_tuple;\nextern PyObject *const_str_plain_Now;\nextern PyObject *const_str_plain_Extract;\nextern PyObject *const_str_plain_ExtractDay;\nstatic PyObject *const_str_digest_80646b51abf2eb839e622666027e3d26;\nextern PyObject *const_str_plain_TruncYear;\nextern PyObject *const_str_plain_Cast;\nstatic PyObject *const_str_digest_d4825e9eae920f54e180fef58beae80c;\nstatic PyObject *const_tuple_f37e9448a2e04decb7f95c5d37fa2ec4_tuple;\nextern PyObject *const_str_plain_TruncDay;\nextern PyObject *const_str_plain_NUITKA_PACKAGE_django;\nextern PyObject *const_str_plain_TruncHour;\nextern PyObject *const_str_plain_Concat;\nstatic PyObject *const_tuple_a57d7a35df18217b92792bce665af9a6_tuple;\nextern PyObject *const_str_plain_TruncSecond;\nextern PyObject *const_str_plain_TruncMonth;\nstatic PyObject *const_list_6be8e1a18107e0f2e8d82c61e79fe2e7_list;\nextern PyObject *const_str_plain_NUITKA_PACKAGE_django_db_models;\nextern PyObject *const_str_digest_5bfaf90dbd407b4fc29090c8f6415242;\nstatic PyObject *const_str_digest_41a75782b67d10db27aeaed25e51e404;\nextern PyObject *const_str_plain_ExtractWeek;\nextern PyObject *const_str_plain_ExtractHour;\nextern PyObject *const_str_plain___path__;\nextern PyObject *const_tuple_c15243b3ba68498da186d5d65ae367ca_tuple;\nextern PyObject *const_tuple_empty;\nextern PyObject *const_str_plain_get;\nextern PyObject *const_str_plain_base;\nextern PyObject *const_str_plain_NUITKA_PACKAGE_django_db;\nextern PyObject *const_str_plain_ExtractWeekDay;\nextern PyObject *const_str_plain_datetime;\nextern PyObject *const_str_plain_TruncTime;\nstatic PyObject *const_str_digest_8f6c0325827ce7275904d2bbc39c7bde;\nextern PyObject *const_str_plain___loader__;\nextern PyObject *const_str_plain_join;\nextern PyObject *const_str_digest_4e7e693e251a89f57ec4f0dd4f537b0c;\nstatic PyObject *const_str_plain_functions;\nextern PyObject *const_str_plain_dirname;\nextern PyObject *const_str_plain_Length;\nextern PyObject *const_str_plain_ExtractMonth;\nextern PyObject *const_str_plain___doc__;\nextern PyObject *const_str_plain___cached__;\nextern PyObject *const_str_plain_Least;\nstatic PyObject *module_filename_obj;\n\nstatic bool constants_created = false;\n\nstatic void createModuleConstants( void )\n{\n    const_str_digest_fe19ab428a9952bfcba7a98da752b153 = UNSTREAM_STRING( &constant_bin[ 950214 ], 38, 0 );\n    const_tuple_ae54af5000b7d151d08db7b05d852532_tuple = PyTuple_New( 18 );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 0, const_str_plain_Extract ); Py_INCREF( const_str_plain_Extract );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 1, const_str_plain_ExtractDay ); Py_INCREF( const_str_plain_ExtractDay );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 2, const_str_plain_ExtractHour ); Py_INCREF( const_str_plain_ExtractHour );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 3, const_str_plain_ExtractMinute ); Py_INCREF( const_str_plain_ExtractMinute );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 4, const_str_plain_ExtractMonth ); Py_INCREF( const_str_plain_ExtractMonth );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 5, const_str_plain_ExtractSecond ); Py_INCREF( const_str_plain_ExtractSecond );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 6, const_str_plain_ExtractWeek ); Py_INCREF( const_str_plain_ExtractWeek );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 7, const_str_plain_ExtractWeekDay ); Py_INCREF( const_str_plain_ExtractWeekDay );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 8, const_str_plain_ExtractYear ); Py_INCREF( const_str_plain_ExtractYear );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 9, const_str_plain_Trunc ); Py_INCREF( const_str_plain_Trunc );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 10, const_str_plain_TruncDate ); Py_INCREF( const_str_plain_TruncDate );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 11, const_str_plain_TruncDay ); Py_INCREF( const_str_plain_TruncDay );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 12, const_str_plain_TruncHour ); Py_INCREF( const_str_plain_TruncHour );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 13, const_str_plain_TruncMinute ); Py_INCREF( const_str_plain_TruncMinute );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 14, const_str_plain_TruncMonth ); Py_INCREF( const_str_plain_TruncMonth );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 15, const_str_plain_TruncSecond ); Py_INCREF( const_str_plain_TruncSecond );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 16, const_str_plain_TruncTime ); Py_INCREF( const_str_plain_TruncTime );\n    PyTuple_SET_ITEM( const_tuple_ae54af5000b7d151d08db7b05d852532_tuple, 17, const_str_plain_TruncYear ); Py_INCREF( const_str_plain_TruncYear );\n    const_str_digest_80646b51abf2eb839e622666027e3d26 = UNSTREAM_STRING( &constant_bin[ 950252 ], 35, 0 );\n    const_str_digest_d4825e9eae920f54e180fef58beae80c = UNSTREAM_STRING( &constant_bin[ 950224 ], 16, 0 );\n    const_tuple_f37e9448a2e04decb7f95c5d37fa2ec4_tuple = PyTuple_New( 2 );\n    const_str_digest_41a75782b67d10db27aeaed25e51e404 = UNSTREAM_STRING( &constant_bin[ 950287 ], 41, 1 );\n    PyTuple_SET_ITEM( const_tuple_f37e9448a2e04decb7f95c5d37fa2ec4_tuple, 0, const_str_digest_41a75782b67d10db27aeaed25e51e404 ); Py_INCREF( const_str_digest_41a75782b67d10db27aeaed25e51e404 );\n    PyTuple_SET_ITEM( const_tuple_f37e9448a2e04decb7f95c5d37fa2ec4_tuple, 1, const_str_digest_5bfaf90dbd407b4fc29090c8f6415242 ); Py_INCREF( const_str_digest_5bfaf90dbd407b4fc29090c8f6415242 );\n    const_tuple_a57d7a35df18217b92792bce665af9a6_tuple = PyTuple_New( 11 );\n    PyTuple_SET_ITEM( const_tuple_a57d7a35df18217b92792bce665af9a6_tuple, 0, const_str_plain_Cast ); Py_INCREF( const_str_plain_Cast );\n    PyTuple_SET_ITEM( const_tuple_a57d7a35df18217b92792bce665af9a6_tuple, 1, const_str_plain_Coalesce ); Py_INCREF( const_str_plain_Coalesce );\n    PyTuple_SET_ITEM( const_tuple_a57d7a35df18217b92792bce665af9a6_tuple, 2, const_str_plain_Concat ); Py_INCREF( const_str_plain_Concat );\n    PyTuple_SET_ITEM( const_tuple_a57d7a35df18217b92792bce665af9a6_tuple, 3, const_str_plain_ConcatPair ); Py_INCREF( const_str_plain_ConcatPair );\n    PyTuple_SET_ITEM( const_tuple_a57d7a35df18217b92792bce665af9a6_tuple, 4, const_str_plain_Greatest ); Py_INCREF( const_str_plain_Greatest );\n    PyTuple_SET_ITEM( const_tuple_a57d7a35df18217b92792bce665af9a6_tuple, 5, const_str_plain_Least ); Py_INCREF( const_str_plain_Least );\n    PyTuple_SET_ITEM( const_tuple_a57d7a35df18217b92792bce665af9a6_tuple, 6, const_str_plain_Length ); Py_INCREF( const_str_plain_Length );\n    PyTuple_SET_ITEM( const_tuple_a57d7a35df18217b92792bce665af9a6_tuple, 7, const_str_plain_Lower ); Py_INCREF( const_str_plain_Lower );\n    PyTuple_SET_ITEM( const_tuple_a57d7a35df18217b92792bce665af9a6_tuple, 8, const_str_plain_Now ); Py_INCREF( const_str_plain_Now );\n    PyTuple_SET_ITEM( const_tuple_a57d7a35df18217b92792bce665af9a6_tuple, 9, const_str_plain_Substr ); Py_INCREF( const_str_plain_Substr );\n    PyTuple_SET_ITEM( const_tuple_a57d7a35df18217b92792bce665af9a6_tuple, 10, const_str_plain_Upper ); Py_INCREF( const_str_plain_Upper );\n    const_list_6be8e1a18107e0f2e8d82c61e79fe2e7_list = PyMarshal_ReadObjectFromString( (char *)&constant_bin[ 950328 ], 312 );\n    const_str_digest_8f6c0325827ce7275904d2bbc39c7bde = UNSTREAM_STRING( &constant_bin[ 950221 ], 19, 0 );\n    const_str_plain_functions = UNSTREAM_STRING( &constant_bin[ 21991 ], 9, 1 );\n\n    constants_created = true;\n}\n\n#ifndef __NUITKA_NO_ASSERT__\nvoid checkModuleConstants_django$db$models$functions( void )\n{\n    \/\/ The module may not have been used at all.\n    if (constants_created == false) return;\n\n\n}\n#endif\n\n\/\/ The module code objects.\nstatic PyCodeObject *codeobj_61b49fd0c6a37a70ca165f42c98db6a8;\n\nstatic void createModuleCodeObjects(void)\n{\n    module_filename_obj = MAKE_RELATIVE_PATH( const_str_digest_fe19ab428a9952bfcba7a98da752b153 );\n    codeobj_61b49fd0c6a37a70ca165f42c98db6a8 = MAKE_CODEOBJ( module_filename_obj, const_str_digest_80646b51abf2eb839e622666027e3d26, 1, const_tuple_empty, 0, 0, CO_NOFREE );\n}\n\n\/\/ The module function declarations.\n\n\n\/\/ The module function definitions.\n\n\n\n#if PYTHON_VERSION >= 300\nstatic struct PyModuleDef mdef_django$db$models$functions =\n{\n    PyModuleDef_HEAD_INIT,\n    \"django.db.models.functions\",   \/* m_name *\/\n    NULL,                \/* m_doc *\/\n    -1,                  \/* m_size *\/\n    NULL,                \/* m_methods *\/\n    NULL,                \/* m_reload *\/\n    NULL,                \/* m_traverse *\/\n    NULL,                \/* m_clear *\/\n    NULL,                \/* m_free *\/\n  };\n#endif\n\n#if PYTHON_VERSION >= 300\nextern PyObject *metapath_based_loader;\n#endif\n#if PYTHON_VERSION >= 330\nextern PyObject *const_str_plain___loader__;\n#endif\n\nextern void _initCompiledCellType();\nextern void _initCompiledGeneratorType();\nextern void _initCompiledFunctionType();\nextern void _initCompiledMethodType();\nextern void _initCompiledFrameType();\n#if PYTHON_VERSION >= 350\nextern void _initCompiledCoroutineTypes();\n#endif\n#if PYTHON_VERSION >= 360\nextern void _initCompiledAsyncgenTypes();\n#endif\n\n\/\/ The exported interface to CPython. On import of the module, this function\n\/\/ gets called. It has to have an exact function name, in cases it's a shared\n\/\/ library export. This is hidden behind the MOD_INIT_DECL.\n\nMOD_INIT_DECL( django$db$models$functions )\n{\n#if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300\n    static bool _init_done = false;\n\n    \/\/ Modules might be imported repeatedly, which is to be ignored.\n    if ( _init_done )\n    {\n        return MOD_RETURN_VALUE( module_django$db$models$functions );\n    }\n    else\n    {\n        _init_done = true;\n    }\n#endif\n\n#ifdef _NUITKA_MODULE\n    \/\/ In case of a stand alone extension module, need to call initialization\n    \/\/ the init here because that's the first and only time we are going to get\n    \/\/ called here.\n\n    \/\/ Initialize the constant values used.\n    _initBuiltinModule();\n    createGlobalConstants();\n\n    \/* Initialize the compiled types of Nuitka. *\/\n    _initCompiledCellType();\n    _initCompiledGeneratorType();\n    _initCompiledFunctionType();\n    _initCompiledMethodType();\n    _initCompiledFrameType();\n#if PYTHON_VERSION >= 350\n    _initCompiledCoroutineTypes();\n#endif\n#if PYTHON_VERSION >= 360\n    _initCompiledAsyncgenTypes();\n#endif\n\n#if PYTHON_VERSION < 300\n    _initSlotCompare();\n#endif\n#if PYTHON_VERSION >= 270\n    _initSlotIternext();\n#endif\n\n    patchBuiltinModule();\n    patchTypeComparison();\n\n    \/\/ Enable meta path based loader if not already done.\n    setupMetaPathBasedLoader();\n\n#if PYTHON_VERSION >= 300\n    patchInspectModule();\n#endif\n\n#endif\n\n    \/* The constants only used by this module are created now. *\/\n#ifdef _NUITKA_TRACE\n    puts(\"django.db.models.functions: Calling createModuleConstants().\");\n#endif\n    createModuleConstants();\n\n    \/* The code objects used by this module are created now. *\/\n#ifdef _NUITKA_TRACE\n    puts(\"django.db.models.functions: Calling createModuleCodeObjects().\");\n#endif\n    createModuleCodeObjects();\n\n    \/\/ puts( \"in initdjango$db$models$functions\" );\n\n    \/\/ Create the module object first. There are no methods initially, all are\n    \/\/ added dynamically in actual code only.  Also no \"__doc__\" is initially\n    \/\/ set at this time, as it could not contain NUL characters this way, they\n    \/\/ are instead set in early module code.  No \"self\" for modules, we have no\n    \/\/ use for it.\n#if PYTHON_VERSION < 300\n    module_django$db$models$functions = Py_InitModule4(\n        \"django.db.models.functions\",       \/\/ Module Name\n        NULL,                    \/\/ No methods initially, all are added\n                                 \/\/ dynamically in actual module code only.\n        NULL,                    \/\/ No __doc__ is initially set, as it could\n                                 \/\/ not contain NUL this way, added early in\n                                 \/\/ actual code.\n        NULL,                    \/\/ No self for modules, we don't use it.\n        PYTHON_API_VERSION\n    );\n#else\n    module_django$db$models$functions = PyModule_Create( &mdef_django$db$models$functions );\n#endif\n\n    moduledict_django$db$models$functions = MODULE_DICT( module_django$db$models$functions );\n\n    CHECK_OBJECT( module_django$db$models$functions );\n\n\/\/ Seems to work for Python2.7 out of the box, but for Python3, the module\n\/\/ doesn't automatically enter \"sys.modules\", so do it manually.\n#if PYTHON_VERSION >= 300\n    {\n        int r = PyObject_SetItem( PySys_GetObject( (char *)\"modules\" ), const_str_digest_4e7e693e251a89f57ec4f0dd4f537b0c, module_django$db$models$functions );\n\n        assert( r != -1 );\n    }\n#endif\n\n    \/\/ For deep importing of a module we need to have \"__builtins__\", so we set\n    \/\/ it ourselves in the same way than CPython does. Note: This must be done\n    \/\/ before the frame object is allocated, or else it may fail.\n\n    if ( GET_STRING_DICT_VALUE( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain___builtins__ ) == NULL )\n    {\n        PyObject *value = (PyObject *)builtin_module;\n\n        \/\/ Check if main module, not a dict then but the module itself.\n#if !defined(_NUITKA_EXE) || !0\n        value = PyModule_GetDict( value );\n#endif\n\n        UPDATE_STRING_DICT0( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain___builtins__, value );\n    }\n\n#if PYTHON_VERSION >= 330\n    UPDATE_STRING_DICT0( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain___loader__, metapath_based_loader );\n#endif\n\n    \/\/ Temp variables if any\n    PyObject *tmp_import_from_1__module = NULL;\n    PyObject *tmp_import_from_2__module = NULL;\n    PyObject *exception_type = NULL;\n    PyObject *exception_value = NULL;\n    PyTracebackObject *exception_tb = NULL;\n    NUITKA_MAY_BE_UNUSED int exception_lineno = 0;\n    PyObject *exception_keeper_type_1;\n    PyObject *exception_keeper_value_1;\n    PyTracebackObject *exception_keeper_tb_1;\n    NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;\n    PyObject *exception_keeper_type_2;\n    PyObject *exception_keeper_value_2;\n    PyTracebackObject *exception_keeper_tb_2;\n    NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2;\n    PyObject *tmp_args_element_name_1;\n    PyObject *tmp_args_element_name_2;\n    PyObject *tmp_args_element_name_3;\n    PyObject *tmp_args_element_name_4;\n    PyObject *tmp_args_element_name_5;\n    PyObject *tmp_args_element_name_6;\n    PyObject *tmp_args_element_name_7;\n    PyObject *tmp_args_element_name_8;\n    PyObject *tmp_args_element_name_9;\n    PyObject *tmp_assign_source_1;\n    PyObject *tmp_assign_source_2;\n    PyObject *tmp_assign_source_3;\n    PyObject *tmp_assign_source_4;\n    PyObject *tmp_assign_source_5;\n    PyObject *tmp_assign_source_6;\n    PyObject *tmp_assign_source_7;\n    PyObject *tmp_assign_source_8;\n    PyObject *tmp_assign_source_9;\n    PyObject *tmp_assign_source_10;\n    PyObject *tmp_assign_source_11;\n    PyObject *tmp_assign_source_12;\n    PyObject *tmp_assign_source_13;\n    PyObject *tmp_assign_source_14;\n    PyObject *tmp_assign_source_15;\n    PyObject *tmp_assign_source_16;\n    PyObject *tmp_assign_source_17;\n    PyObject *tmp_assign_source_18;\n    PyObject *tmp_assign_source_19;\n    PyObject *tmp_assign_source_20;\n    PyObject *tmp_assign_source_21;\n    PyObject *tmp_assign_source_22;\n    PyObject *tmp_assign_source_23;\n    PyObject *tmp_assign_source_24;\n    PyObject *tmp_assign_source_25;\n    PyObject *tmp_assign_source_26;\n    PyObject *tmp_assign_source_27;\n    PyObject *tmp_assign_source_28;\n    PyObject *tmp_assign_source_29;\n    PyObject *tmp_assign_source_30;\n    PyObject *tmp_assign_source_31;\n    PyObject *tmp_assign_source_32;\n    PyObject *tmp_assign_source_33;\n    PyObject *tmp_assign_source_34;\n    PyObject *tmp_assign_source_35;\n    PyObject *tmp_assign_source_36;\n    PyObject *tmp_assign_source_37;\n    PyObject *tmp_assign_source_38;\n    PyObject *tmp_assign_source_39;\n    PyObject *tmp_called_instance_1;\n    PyObject *tmp_called_instance_2;\n    PyObject *tmp_called_instance_3;\n    PyObject *tmp_called_instance_4;\n    PyObject *tmp_called_name_1;\n    PyObject *tmp_called_name_2;\n    PyObject *tmp_called_name_3;\n    PyObject *tmp_called_name_4;\n    PyObject *tmp_called_name_5;\n    PyObject *tmp_fromlist_name_1;\n    PyObject *tmp_fromlist_name_2;\n    PyObject *tmp_globals_name_1;\n    PyObject *tmp_globals_name_2;\n    PyObject *tmp_import_name_from_1;\n    PyObject *tmp_import_name_from_2;\n    PyObject *tmp_import_name_from_3;\n    PyObject *tmp_import_name_from_4;\n    PyObject *tmp_import_name_from_5;\n    PyObject *tmp_import_name_from_6;\n    PyObject *tmp_import_name_from_7;\n    PyObject *tmp_import_name_from_8;\n    PyObject *tmp_import_name_from_9;\n    PyObject *tmp_import_name_from_10;\n    PyObject *tmp_import_name_from_11;\n    PyObject *tmp_import_name_from_12;\n    PyObject *tmp_import_name_from_13;\n    PyObject *tmp_import_name_from_14;\n    PyObject *tmp_import_name_from_15;\n    PyObject *tmp_import_name_from_16;\n    PyObject *tmp_import_name_from_17;\n    PyObject *tmp_import_name_from_18;\n    PyObject *tmp_import_name_from_19;\n    PyObject *tmp_import_name_from_20;\n    PyObject *tmp_import_name_from_21;\n    PyObject *tmp_import_name_from_22;\n    PyObject *tmp_import_name_from_23;\n    PyObject *tmp_import_name_from_24;\n    PyObject *tmp_import_name_from_25;\n    PyObject *tmp_import_name_from_26;\n    PyObject *tmp_import_name_from_27;\n    PyObject *tmp_import_name_from_28;\n    PyObject *tmp_import_name_from_29;\n    PyObject *tmp_level_name_1;\n    PyObject *tmp_level_name_2;\n    PyObject *tmp_list_element_1;\n    PyObject *tmp_locals_name_1;\n    PyObject *tmp_locals_name_2;\n    PyObject *tmp_name_name_1;\n    PyObject *tmp_name_name_2;\n    PyObject *tmp_source_name_1;\n    PyObject *tmp_source_name_2;\n    PyObject *tmp_source_name_3;\n    PyObject *tmp_source_name_4;\n    struct Nuitka_FrameObject *frame_61b49fd0c6a37a70ca165f42c98db6a8;\n\n    NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;\n\n    \/\/ Module code.\n    tmp_assign_source_1 = Py_None;\n    UPDATE_STRING_DICT0( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 );\n    tmp_assign_source_2 = module_filename_obj;\n    UPDATE_STRING_DICT0( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 );\n    \/\/ Frame without reuse.\n    frame_61b49fd0c6a37a70ca165f42c98db6a8 = MAKE_MODULE_FRAME( codeobj_61b49fd0c6a37a70ca165f42c98db6a8, module_django$db$models$functions );\n\n    \/\/ Push the new frame as the currently active one, and we should be exclusively\n    \/\/ owning it.\n    pushFrameStack( frame_61b49fd0c6a37a70ca165f42c98db6a8 );\n    assert( Py_REFCNT( frame_61b49fd0c6a37a70ca165f42c98db6a8 ) == 2 );\n\n    \/\/ Framed code:\n    tmp_assign_source_3 = PyList_New( 5 );\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *module = PyImport_ImportModule(\"os\");\n        if (likely( module != NULL ))\n        {\n            tmp_source_name_1 = PyObject_GetAttr( module, const_str_plain_path );\n        }\n        else\n        {\n            tmp_source_name_1 = NULL;\n        }\n    }\n\n    if ( tmp_source_name_1 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_dirname );\n    if ( tmp_called_name_1 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    tmp_args_element_name_1 = module_filename_obj;\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *call_args[] = { tmp_args_element_name_1 };\n        tmp_list_element_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args );\n    }\n\n    Py_DECREF( tmp_called_name_1 );\n    if ( tmp_list_element_1 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    PyList_SET_ITEM( tmp_assign_source_3, 0, tmp_list_element_1 );\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *module = PyImport_ImportModule(\"os\");\n        if (likely( module != NULL ))\n        {\n            tmp_source_name_2 = PyObject_GetAttr( module, const_str_plain_path );\n        }\n        else\n        {\n            tmp_source_name_2 = NULL;\n        }\n    }\n\n    if ( tmp_source_name_2 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_join );\n    if ( tmp_called_name_2 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *module = PyImport_ImportModule(\"os\");\n        if (likely( module != NULL ))\n        {\n            tmp_called_instance_1 = PyObject_GetAttr( module, const_str_plain_environ );\n        }\n        else\n        {\n            tmp_called_instance_1 = NULL;\n        }\n    }\n\n    if ( tmp_called_instance_1 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n        Py_DECREF( tmp_called_name_2 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    tmp_args_element_name_2 = CALL_METHOD_WITH_ARGS2( tmp_called_instance_1, const_str_plain_get, &PyTuple_GET_ITEM( const_tuple_c15243b3ba68498da186d5d65ae367ca_tuple, 0 ) );\n\n    if ( tmp_args_element_name_2 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n        Py_DECREF( tmp_called_name_2 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    tmp_args_element_name_3 = const_str_digest_8f6c0325827ce7275904d2bbc39c7bde;\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *call_args[] = { tmp_args_element_name_2, tmp_args_element_name_3 };\n        tmp_list_element_1 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_2, call_args );\n    }\n\n    Py_DECREF( tmp_called_name_2 );\n    Py_DECREF( tmp_args_element_name_2 );\n    if ( tmp_list_element_1 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    PyList_SET_ITEM( tmp_assign_source_3, 1, tmp_list_element_1 );\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *module = PyImport_ImportModule(\"os\");\n        if (likely( module != NULL ))\n        {\n            tmp_source_name_3 = PyObject_GetAttr( module, const_str_plain_path );\n        }\n        else\n        {\n            tmp_source_name_3 = NULL;\n        }\n    }\n\n    if ( tmp_source_name_3 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_join );\n    if ( tmp_called_name_3 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *module = PyImport_ImportModule(\"os\");\n        if (likely( module != NULL ))\n        {\n            tmp_called_instance_2 = PyObject_GetAttr( module, const_str_plain_environ );\n        }\n        else\n        {\n            tmp_called_instance_2 = NULL;\n        }\n    }\n\n    if ( tmp_called_instance_2 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n        Py_DECREF( tmp_called_name_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    tmp_args_element_name_4 = CALL_METHOD_WITH_ARGS2( tmp_called_instance_2, const_str_plain_get, &PyTuple_GET_ITEM( const_tuple_9aafdb4681f02593d1d6ac7779e00e9d_tuple, 0 ) );\n\n    if ( tmp_args_element_name_4 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n        Py_DECREF( tmp_called_name_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    tmp_args_element_name_5 = const_str_digest_d4825e9eae920f54e180fef58beae80c;\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *call_args[] = { tmp_args_element_name_4, tmp_args_element_name_5 };\n        tmp_list_element_1 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_3, call_args );\n    }\n\n    Py_DECREF( tmp_called_name_3 );\n    Py_DECREF( tmp_args_element_name_4 );\n    if ( tmp_list_element_1 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    PyList_SET_ITEM( tmp_assign_source_3, 2, tmp_list_element_1 );\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *module = PyImport_ImportModule(\"os\");\n        if (likely( module != NULL ))\n        {\n            tmp_source_name_4 = PyObject_GetAttr( module, const_str_plain_path );\n        }\n        else\n        {\n            tmp_source_name_4 = NULL;\n        }\n    }\n\n    if ( tmp_source_name_4 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    tmp_called_name_4 = LOOKUP_ATTRIBUTE( tmp_source_name_4, const_str_plain_join );\n    if ( tmp_called_name_4 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *module = PyImport_ImportModule(\"os\");\n        if (likely( module != NULL ))\n        {\n            tmp_called_instance_3 = PyObject_GetAttr( module, const_str_plain_environ );\n        }\n        else\n        {\n            tmp_called_instance_3 = NULL;\n        }\n    }\n\n    if ( tmp_called_instance_3 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n        Py_DECREF( tmp_called_name_4 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    tmp_args_element_name_6 = CALL_METHOD_WITH_ARGS2( tmp_called_instance_3, const_str_plain_get, &PyTuple_GET_ITEM( const_tuple_e264d9df221704bac1b8813696d55517_tuple, 0 ) );\n\n    if ( tmp_args_element_name_6 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n        Py_DECREF( tmp_called_name_4 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    tmp_args_element_name_7 = const_str_plain_functions;\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *call_args[] = { tmp_args_element_name_6, tmp_args_element_name_7 };\n        tmp_list_element_1 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_4, call_args );\n    }\n\n    Py_DECREF( tmp_called_name_4 );\n    Py_DECREF( tmp_args_element_name_6 );\n    if ( tmp_list_element_1 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    PyList_SET_ITEM( tmp_assign_source_3, 3, tmp_list_element_1 );\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *module = PyImport_ImportModule(\"os\");\n        if (likely( module != NULL ))\n        {\n            tmp_called_instance_4 = PyObject_GetAttr( module, const_str_plain_environ );\n        }\n        else\n        {\n            tmp_called_instance_4 = NULL;\n        }\n    }\n\n    if ( tmp_called_instance_4 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    tmp_list_element_1 = CALL_METHOD_WITH_ARGS2( tmp_called_instance_4, const_str_plain_get, &PyTuple_GET_ITEM( const_tuple_f37e9448a2e04decb7f95c5d37fa2ec4_tuple, 0 ) );\n\n    if ( tmp_list_element_1 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n        Py_DECREF( tmp_assign_source_3 );\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    PyList_SET_ITEM( tmp_assign_source_3, 4, tmp_list_element_1 );\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain___path__, tmp_assign_source_3 );\n    tmp_assign_source_4 = metapath_based_loader;\n    UPDATE_STRING_DICT0( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain___loader__, tmp_assign_source_4 );\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *module = PyImport_ImportModule(\"importlib._bootstrap\");\n        if (likely( module != NULL ))\n        {\n            tmp_called_name_5 = PyObject_GetAttr( module, const_str_plain_ModuleSpec );\n        }\n        else\n        {\n            tmp_called_name_5 = NULL;\n        }\n    }\n\n    if ( tmp_called_name_5 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    tmp_args_element_name_8 = const_str_digest_4e7e693e251a89f57ec4f0dd4f537b0c;\n    tmp_args_element_name_9 = metapath_based_loader;\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    {\n        PyObject *call_args[] = { tmp_args_element_name_8, tmp_args_element_name_9 };\n        tmp_assign_source_5 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_5, call_args );\n    }\n\n    if ( tmp_assign_source_5 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain___spec__, tmp_assign_source_5 );\n    tmp_assign_source_6 = Py_None;\n    UPDATE_STRING_DICT0( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_6 );\n    tmp_assign_source_7 = const_str_digest_4e7e693e251a89f57ec4f0dd4f537b0c;\n    UPDATE_STRING_DICT0( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain___package__, tmp_assign_source_7 );\n    tmp_name_name_1 = const_str_plain_base;\n    tmp_globals_name_1 = (PyObject *)moduledict_django$db$models$functions;\n    tmp_locals_name_1 = Py_None;\n    tmp_fromlist_name_1 = const_tuple_a57d7a35df18217b92792bce665af9a6_tuple;\n    tmp_level_name_1 = const_int_pos_1;\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 1;\n    tmp_assign_source_8 = IMPORT_MODULE5( tmp_name_name_1, tmp_globals_name_1, tmp_locals_name_1, tmp_fromlist_name_1, tmp_level_name_1 );\n    if ( tmp_assign_source_8 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto frame_exception_exit_1;\n    }\n    assert( tmp_import_from_1__module == NULL );\n    tmp_import_from_1__module = tmp_assign_source_8;\n\n    \/\/ Tried code:\n    tmp_import_name_from_1 = tmp_import_from_1__module;\n\n    CHECK_OBJECT( tmp_import_name_from_1 );\n    tmp_assign_source_9 = IMPORT_NAME( tmp_import_name_from_1, const_str_plain_Cast );\n    if ( tmp_assign_source_9 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto try_except_handler_1;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_Cast, tmp_assign_source_9 );\n    tmp_import_name_from_2 = tmp_import_from_1__module;\n\n    CHECK_OBJECT( tmp_import_name_from_2 );\n    tmp_assign_source_10 = IMPORT_NAME( tmp_import_name_from_2, const_str_plain_Coalesce );\n    if ( tmp_assign_source_10 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto try_except_handler_1;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_Coalesce, tmp_assign_source_10 );\n    tmp_import_name_from_3 = tmp_import_from_1__module;\n\n    CHECK_OBJECT( tmp_import_name_from_3 );\n    tmp_assign_source_11 = IMPORT_NAME( tmp_import_name_from_3, const_str_plain_Concat );\n    if ( tmp_assign_source_11 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto try_except_handler_1;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_Concat, tmp_assign_source_11 );\n    tmp_import_name_from_4 = tmp_import_from_1__module;\n\n    CHECK_OBJECT( tmp_import_name_from_4 );\n    tmp_assign_source_12 = IMPORT_NAME( tmp_import_name_from_4, const_str_plain_ConcatPair );\n    if ( tmp_assign_source_12 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto try_except_handler_1;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_ConcatPair, tmp_assign_source_12 );\n    tmp_import_name_from_5 = tmp_import_from_1__module;\n\n    CHECK_OBJECT( tmp_import_name_from_5 );\n    tmp_assign_source_13 = IMPORT_NAME( tmp_import_name_from_5, const_str_plain_Greatest );\n    if ( tmp_assign_source_13 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto try_except_handler_1;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_Greatest, tmp_assign_source_13 );\n    tmp_import_name_from_6 = tmp_import_from_1__module;\n\n    CHECK_OBJECT( tmp_import_name_from_6 );\n    tmp_assign_source_14 = IMPORT_NAME( tmp_import_name_from_6, const_str_plain_Least );\n    if ( tmp_assign_source_14 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto try_except_handler_1;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_Least, tmp_assign_source_14 );\n    tmp_import_name_from_7 = tmp_import_from_1__module;\n\n    CHECK_OBJECT( tmp_import_name_from_7 );\n    tmp_assign_source_15 = IMPORT_NAME( tmp_import_name_from_7, const_str_plain_Length );\n    if ( tmp_assign_source_15 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto try_except_handler_1;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_Length, tmp_assign_source_15 );\n    tmp_import_name_from_8 = tmp_import_from_1__module;\n\n    CHECK_OBJECT( tmp_import_name_from_8 );\n    tmp_assign_source_16 = IMPORT_NAME( tmp_import_name_from_8, const_str_plain_Lower );\n    if ( tmp_assign_source_16 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto try_except_handler_1;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_Lower, tmp_assign_source_16 );\n    tmp_import_name_from_9 = tmp_import_from_1__module;\n\n    CHECK_OBJECT( tmp_import_name_from_9 );\n    tmp_assign_source_17 = IMPORT_NAME( tmp_import_name_from_9, const_str_plain_Now );\n    if ( tmp_assign_source_17 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto try_except_handler_1;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_Now, tmp_assign_source_17 );\n    tmp_import_name_from_10 = tmp_import_from_1__module;\n\n    CHECK_OBJECT( tmp_import_name_from_10 );\n    tmp_assign_source_18 = IMPORT_NAME( tmp_import_name_from_10, const_str_plain_Substr );\n    if ( tmp_assign_source_18 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto try_except_handler_1;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_Substr, tmp_assign_source_18 );\n    tmp_import_name_from_11 = tmp_import_from_1__module;\n\n    CHECK_OBJECT( tmp_import_name_from_11 );\n    tmp_assign_source_19 = IMPORT_NAME( tmp_import_name_from_11, const_str_plain_Upper );\n    if ( tmp_assign_source_19 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 1;\n\n        goto try_except_handler_1;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_Upper, tmp_assign_source_19 );\n    goto try_end_1;\n    \/\/ Exception handler code:\n    try_except_handler_1:;\n    exception_keeper_type_1 = exception_type;\n    exception_keeper_value_1 = exception_value;\n    exception_keeper_tb_1 = exception_tb;\n    exception_keeper_lineno_1 = exception_lineno;\n    exception_type = NULL;\n    exception_value = NULL;\n    exception_tb = NULL;\n    exception_lineno = 0;\n\n    Py_XDECREF( tmp_import_from_1__module );\n    tmp_import_from_1__module = NULL;\n\n    \/\/ Re-raise.\n    exception_type = exception_keeper_type_1;\n    exception_value = exception_keeper_value_1;\n    exception_tb = exception_keeper_tb_1;\n    exception_lineno = exception_keeper_lineno_1;\n\n    goto frame_exception_exit_1;\n    \/\/ End of try:\n    try_end_1:;\n    Py_XDECREF( tmp_import_from_1__module );\n    tmp_import_from_1__module = NULL;\n\n    tmp_name_name_2 = const_str_plain_datetime;\n    tmp_globals_name_2 = (PyObject *)moduledict_django$db$models$functions;\n    tmp_locals_name_2 = Py_None;\n    tmp_fromlist_name_2 = const_tuple_ae54af5000b7d151d08db7b05d852532_tuple;\n    tmp_level_name_2 = const_int_pos_1;\n    frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame.f_lineno = 5;\n    tmp_assign_source_20 = IMPORT_MODULE5( tmp_name_name_2, tmp_globals_name_2, tmp_locals_name_2, tmp_fromlist_name_2, tmp_level_name_2 );\n    if ( tmp_assign_source_20 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto frame_exception_exit_1;\n    }\n    assert( tmp_import_from_2__module == NULL );\n    tmp_import_from_2__module = tmp_assign_source_20;\n\n    \/\/ Tried code:\n    tmp_import_name_from_12 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_12 );\n    tmp_assign_source_21 = IMPORT_NAME( tmp_import_name_from_12, const_str_plain_Extract );\n    if ( tmp_assign_source_21 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_Extract, tmp_assign_source_21 );\n    tmp_import_name_from_13 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_13 );\n    tmp_assign_source_22 = IMPORT_NAME( tmp_import_name_from_13, const_str_plain_ExtractDay );\n    if ( tmp_assign_source_22 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_ExtractDay, tmp_assign_source_22 );\n    tmp_import_name_from_14 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_14 );\n    tmp_assign_source_23 = IMPORT_NAME( tmp_import_name_from_14, const_str_plain_ExtractHour );\n    if ( tmp_assign_source_23 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_ExtractHour, tmp_assign_source_23 );\n    tmp_import_name_from_15 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_15 );\n    tmp_assign_source_24 = IMPORT_NAME( tmp_import_name_from_15, const_str_plain_ExtractMinute );\n    if ( tmp_assign_source_24 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_ExtractMinute, tmp_assign_source_24 );\n    tmp_import_name_from_16 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_16 );\n    tmp_assign_source_25 = IMPORT_NAME( tmp_import_name_from_16, const_str_plain_ExtractMonth );\n    if ( tmp_assign_source_25 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_ExtractMonth, tmp_assign_source_25 );\n    tmp_import_name_from_17 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_17 );\n    tmp_assign_source_26 = IMPORT_NAME( tmp_import_name_from_17, const_str_plain_ExtractSecond );\n    if ( tmp_assign_source_26 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_ExtractSecond, tmp_assign_source_26 );\n    tmp_import_name_from_18 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_18 );\n    tmp_assign_source_27 = IMPORT_NAME( tmp_import_name_from_18, const_str_plain_ExtractWeek );\n    if ( tmp_assign_source_27 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_ExtractWeek, tmp_assign_source_27 );\n    tmp_import_name_from_19 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_19 );\n    tmp_assign_source_28 = IMPORT_NAME( tmp_import_name_from_19, const_str_plain_ExtractWeekDay );\n    if ( tmp_assign_source_28 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_ExtractWeekDay, tmp_assign_source_28 );\n    tmp_import_name_from_20 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_20 );\n    tmp_assign_source_29 = IMPORT_NAME( tmp_import_name_from_20, const_str_plain_ExtractYear );\n    if ( tmp_assign_source_29 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_ExtractYear, tmp_assign_source_29 );\n    tmp_import_name_from_21 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_21 );\n    tmp_assign_source_30 = IMPORT_NAME( tmp_import_name_from_21, const_str_plain_Trunc );\n    if ( tmp_assign_source_30 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_Trunc, tmp_assign_source_30 );\n    tmp_import_name_from_22 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_22 );\n    tmp_assign_source_31 = IMPORT_NAME( tmp_import_name_from_22, const_str_plain_TruncDate );\n    if ( tmp_assign_source_31 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_TruncDate, tmp_assign_source_31 );\n    tmp_import_name_from_23 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_23 );\n    tmp_assign_source_32 = IMPORT_NAME( tmp_import_name_from_23, const_str_plain_TruncDay );\n    if ( tmp_assign_source_32 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_TruncDay, tmp_assign_source_32 );\n    tmp_import_name_from_24 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_24 );\n    tmp_assign_source_33 = IMPORT_NAME( tmp_import_name_from_24, const_str_plain_TruncHour );\n    if ( tmp_assign_source_33 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_TruncHour, tmp_assign_source_33 );\n    tmp_import_name_from_25 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_25 );\n    tmp_assign_source_34 = IMPORT_NAME( tmp_import_name_from_25, const_str_plain_TruncMinute );\n    if ( tmp_assign_source_34 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_TruncMinute, tmp_assign_source_34 );\n    tmp_import_name_from_26 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_26 );\n    tmp_assign_source_35 = IMPORT_NAME( tmp_import_name_from_26, const_str_plain_TruncMonth );\n    if ( tmp_assign_source_35 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_TruncMonth, tmp_assign_source_35 );\n    tmp_import_name_from_27 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_27 );\n    tmp_assign_source_36 = IMPORT_NAME( tmp_import_name_from_27, const_str_plain_TruncSecond );\n    if ( tmp_assign_source_36 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_TruncSecond, tmp_assign_source_36 );\n    tmp_import_name_from_28 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_28 );\n    tmp_assign_source_37 = IMPORT_NAME( tmp_import_name_from_28, const_str_plain_TruncTime );\n    if ( tmp_assign_source_37 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_TruncTime, tmp_assign_source_37 );\n    tmp_import_name_from_29 = tmp_import_from_2__module;\n\n    CHECK_OBJECT( tmp_import_name_from_29 );\n    tmp_assign_source_38 = IMPORT_NAME( tmp_import_name_from_29, const_str_plain_TruncYear );\n    if ( tmp_assign_source_38 == NULL )\n    {\n        assert( ERROR_OCCURRED() );\n\n        FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );\n\n\n        exception_lineno = 5;\n\n        goto try_except_handler_2;\n    }\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain_TruncYear, tmp_assign_source_38 );\n    goto try_end_2;\n    \/\/ Exception handler code:\n    try_except_handler_2:;\n    exception_keeper_type_2 = exception_type;\n    exception_keeper_value_2 = exception_value;\n    exception_keeper_tb_2 = exception_tb;\n    exception_keeper_lineno_2 = exception_lineno;\n    exception_type = NULL;\n    exception_value = NULL;\n    exception_tb = NULL;\n    exception_lineno = 0;\n\n    Py_XDECREF( tmp_import_from_2__module );\n    tmp_import_from_2__module = NULL;\n\n    \/\/ Re-raise.\n    exception_type = exception_keeper_type_2;\n    exception_value = exception_keeper_value_2;\n    exception_tb = exception_keeper_tb_2;\n    exception_lineno = exception_keeper_lineno_2;\n\n    goto frame_exception_exit_1;\n    \/\/ End of try:\n    try_end_2:;\n\n    \/\/ Restore frame exception if necessary.\n#if 0\n    RESTORE_FRAME_EXCEPTION( frame_61b49fd0c6a37a70ca165f42c98db6a8 );\n#endif\n    popFrameStack();\n\n    assertFrameObject( frame_61b49fd0c6a37a70ca165f42c98db6a8 );\n\n    goto frame_no_exception_1;\n    frame_exception_exit_1:;\n#if 0\n    RESTORE_FRAME_EXCEPTION( frame_61b49fd0c6a37a70ca165f42c98db6a8 );\n#endif\n\n    if ( exception_tb == NULL )\n    {\n        exception_tb = MAKE_TRACEBACK( frame_61b49fd0c6a37a70ca165f42c98db6a8, exception_lineno );\n    }\n    else if ( exception_tb->tb_frame != &frame_61b49fd0c6a37a70ca165f42c98db6a8->m_frame )\n    {\n        exception_tb = ADD_TRACEBACK( exception_tb, frame_61b49fd0c6a37a70ca165f42c98db6a8, exception_lineno );\n    }\n\n    \/\/ Put the previous frame back on top.\n    popFrameStack();\n\n    \/\/ Return the error.\n    goto module_exception_exit;\n    frame_no_exception_1:;\n    Py_XDECREF( tmp_import_from_2__module );\n    tmp_import_from_2__module = NULL;\n\n    tmp_assign_source_39 = LIST_COPY( const_list_6be8e1a18107e0f2e8d82c61e79fe2e7_list );\n    UPDATE_STRING_DICT1( moduledict_django$db$models$functions, (Nuitka_StringObject *)const_str_plain___all__, tmp_assign_source_39 );\n\n    return MOD_RETURN_VALUE( module_django$db$models$functions );\n    module_exception_exit:\n    RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );\n    return MOD_RETURN_VALUE( NULL );\n}\n","avg_line_length":37.5023163468,"max_line_length":193,"alphanum_fraction":0.7437087495,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1101,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":6.0,"content":"\/* Copyright (C) 2010-2019, The Regents of The University of Michigan.\n All rights reserved.\n\n This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab\n under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an\n MIT-style License that can be found at \"https:\/\/github.com\/h2ssh\/Vulcan\".\n*\/\n\n\n\/**\n* \\file     map_optimizer.cpp\n* \\author   Collin Johnson\n*\n* Definition of create_map_optimizer factory.\n*\/\n\n#include <hssh\/global_topological\/mapping\/map_optimizer.h>\n#include <hssh\/global_topological\/mapping\/lev_mar_optimizer.h>\n#include <iostream>\n#include <cassert>\n\nnamespace vulcan\n{\nnamespace hssh\n{\n\nstd::unique_ptr<MapOptimizer> create_map_optimizer(const std::string& type, const map_optimizer_params_t& params)\n{\n    if(type == LEV_MAR_OPTIMIZER_TYPE)\n    {\n        return std::unique_ptr<MapOptimizer>(new LevMarOptimizer(params.levMarParams));\n    }\n    else\n    {\n        std::cerr<<\"ERROR:Unknown MapOptimizer type: \"<<type<<std::endl;\n        assert(false);\n    }\n\n    return std::unique_ptr<MapOptimizer>();\n}\n\n}\n}\n","avg_line_length":25.0227272727,"max_line_length":113,"alphanum_fraction":0.7284287012,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4150,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/****************************************************************************\n *\n * Copyright (c) 2015 Vijay Venkatraman. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n#include <px4_defines.h>\n#include <px4_posix.h>\n#include <string.h>\n#include <stdbool.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <systemlib\/err.h>\n#include <errno.h>\n#include <semaphore.h>\n\n#include <sys\/stat.h>\n\n#include <drivers\/drv_hrt.h>\n#include <sys\/mman.h>\n#include <sys\/ioctl.h>\n\n#include <parameters\/param.h>\n\n#include <shmem.h>\n#include \"px4muorb.h\"\n\n\/\/#define SHMEM_DEBUG\nvoid update_to_shmem(param_t param, union param_value_u value);\nint update_from_shmem(param_t param, union param_value_u *value);\nvoid update_index_from_shmem(void);\nuint64_t update_from_shmem_prev_time = 0, update_from_shmem_current_time = 0;\nextern unsigned char *adsp_changed_index;\n\nstruct param_wbuf_s {\n\tunion param_value_u val;\n\tparam_t param;\n\tbool unsaved;\n};\n\n\/*update value and param's change bit in shared memory*\/\nvoid update_to_shmem(param_t param, union param_value_u value)\n{\n\tif (px4muorb_param_update_to_shmem(param, (unsigned char *) &value, sizeof(value))) {\n\t\tPX4_ERR(\"krait update param %u failed\", param);\n\t}\n}\n\nvoid update_index_from_shmem(void)\n{\n\tif (!adsp_changed_index) {\n\t\tPX4_ERR(\"%s no param buffer\", __FUNCTION__);\n\t\treturn;\n\t}\n\n\tpx4muorb_param_update_index_from_shmem(adsp_changed_index, PARAM_BUFFER_SIZE);\n}\n\nstatic void update_value_from_shmem(param_t param, union param_value_u *value)\n{\n\tif (px4muorb_param_update_value_from_shmem(param, (unsigned char *) value, sizeof(union param_value_u))) {\n\t\tPX4_ERR(\"%s get param failed\", __FUNCTION__);\n\t}\n}\n\nint update_from_shmem(param_t param, union param_value_u *value)\n{\n\tunsigned int byte_changed, bit_changed;\n\tunsigned int retval = 0;\n\n\tif (!adsp_changed_index) {\n\t\tPX4_ERR(\"%s no param buffer\", __FUNCTION__);\n\t\treturn 0;\n\t}\n\n\tupdate_from_shmem_current_time = hrt_absolute_time();\n\n\tif ((update_from_shmem_current_time - update_from_shmem_prev_time)\n\t    > 1000000) { \/\/update every 1 second\n\t\tupdate_from_shmem_prev_time = update_from_shmem_current_time;\n\t\tupdate_index_from_shmem();\n\t}\n\n\tbyte_changed = param \/ 8;\n\tbit_changed = 1 << param % 8;\n\n\tif (adsp_changed_index[byte_changed] & bit_changed) {\n\t\tupdate_value_from_shmem(param, value);\n\t\tadsp_changed_index[byte_changed] &= ~bit_changed; \/\/clear the bit\n\t\tretval = 1;\n\t}\n\n\t\/\/else {PX4_INFO(\"no change to param %s\", param_name(param));}\n\n\tPX4_DEBUG(\"%s %d bit on adsp index[%d]\",\n\t\t  (retval) ? \"cleared\" : \"unchanged\", bit_changed, byte_changed);\n\n\treturn retval;\n}\n","avg_line_length":32.421875,"max_line_length":107,"alphanum_fraction":0.7277108434,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":78625,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n * MRustC - Rust Compiler\n * - By John Hodge (Mutabah\/thePowersGang)\n *\n * expand\/mod.cpp\n * - Expand pass core code\n *\/\n#include <ast\/ast.hpp>\n#include <ast\/crate.hpp>\n#include <main_bindings.hpp>\n#include <synext.hpp>\n#include <map>\n#include \"..\/macro_rules\/macro_rules.hpp\"\n#include \"..\/parse\/common.hpp\"  \/\/ For reparse from macros\n#include <ast\/expr.hpp>\n#include <hir\/hir.hpp>  \/\/ For macro lookup\n#include \"cfg.hpp\"\n#include \"common.hpp\"\n#include \"..\/resolve\/common.hpp\"\n#include \"proc_macro.hpp\"\n#include \"..\/parse\/ttstream.hpp\"\n\n#define MAX_MACRO_RECURSION 200\n\nDecoratorDef*   g_decorators_list = nullptr;\nMacroDef*   g_macros_list = nullptr;\n::std::map< RcString, ::std::unique_ptr<ExpandDecorator> >  g_decorators;\n::std::map< RcString, ::std::unique_ptr<ExpandProcMacro> >  g_macros;\n\nvoid Expand_Attrs(const ::AST::AttributeList& attrs, AttrStage stage,  ::std::function<void(const ExpandDecorator& d,const ::AST::Attribute& a)> f);\nvoid Expand_Mod(::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::AbsolutePath modpath, ::AST::Module& mod, unsigned int first_item = 0);\nvoid Expand_Expr(::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::ExprNodeP& node);\nvoid Expand_Expr(::AST::Crate& crate, LList<const AST::Module*> modstack, AST::Expr& node);\nvoid Expand_Expr(::AST::Crate& crate, LList<const AST::Module*> modstack, ::std::shared_ptr<AST::ExprNode>& node);\nvoid Expand_Path(::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::Module& mod, ::AST::Path& p);\n\nvoid Register_Synext_Decorator(::std::string name, ::std::unique_ptr<ExpandDecorator> handler) {\n    g_decorators.insert(::std::make_pair( RcString::new_interned(name), mv$(handler) )); \n}\nvoid Register_Synext_Macro(::std::string name, ::std::unique_ptr<ExpandProcMacro> handler) {\n    g_macros.insert(::std::make_pair( RcString::new_interned(name), mv$(handler) ));\n}\nvoid Register_Synext_Decorator_Static(DecoratorDef* def) {\n    def->prev = g_decorators_list;\n    g_decorators_list = def;\n}\nvoid Register_Synext_Macro_Static(MacroDef* def) {\n    def->prev = g_macros_list;\n    g_macros_list = def;\n}\n\nvoid Expand_Init()\n{\n    \/\/ TODO: Initialise all macros here.\n    void Expand_init_assert(); Expand_init_assert();\n    void Expand_init_std_prelude(); Expand_init_std_prelude();\n    void Expand_init_panic(); Expand_init_panic();\n\n    \/\/ Fill macro\/decorator map from init list\n    while(g_decorators_list)\n    {\n        g_decorators.insert(::std::make_pair( RcString::new_interned(g_decorators_list->name), mv$(g_decorators_list->def) ));\n        g_decorators_list = g_decorators_list->prev;\n    }\n    while(g_macros_list)\n    {\n        g_macros.insert(::std::make_pair(RcString::new_interned(g_macros_list->name), mv$(g_macros_list->def)));\n        g_macros_list = g_macros_list->prev;\n    }\n}\n\nvoid ExpandDecorator::unexpected(const Span& sp, const AST::Attribute& mi, const char* loc_str) const\n{\n    WARNING(sp, W0000, \"Unexpected attribute \" << mi.name() << \" on \" << loc_str);\n}\n\n\nExpandProcMacro* Expand_FindProcMacro(const RcString& name)\n{\n    auto it = g_macros.find(name);\n    if(it == g_macros.end())\n        return nullptr;\n    else\n        return it->second.get();\n}\n\nvoid Expand_Attr(const Span& sp, const ::AST::Attribute& a, AttrStage stage,  ::std::function<void(const Span& sp, const ExpandDecorator& d,const ::AST::Attribute& a)> f)\n{\n    bool found = false;\n    for( auto& d : g_decorators ) {\n        if( a.name() == d.first ) {\n            DEBUG(\"#[\" << d.first << \"] \" << (int)d.second->stage() << \"-\" << (int)stage);\n            if( d.second->stage() == stage ) {\n                f(sp, *d.second, a);\n                \/\/ TODO: Early return?\n                \/\/ TODO: Annotate the attribute as having been handled\n            }\n            found = true;\n        }\n    }\n    if( !found ) {\n        \/\/ TODO: Create no-op handlers for a whole heap of attributes\n        \/\/ - There's a LOT\n        \/\/WARNING(sp, W0000, \"Unknown attribute #[\" << a.name() << \"]\");\n    }\n}\nvoid Expand_Attrs(const ::AST::AttributeList& attrs, AttrStage stage,  ::std::function<void(const Span& sp, const ExpandDecorator& d,const ::AST::Attribute& a)> f)\n{\n    for( auto& a : attrs.m_items )\n    {\n        Expand_Attr(a.span(), a, stage, f);\n    }\n}\nvoid Expand_Attrs_CfgAttr(AST::AttributeList& attrs)\n{\n    for(auto it = attrs.m_items.begin(); it != attrs.m_items.end(); )\n    {\n        auto& a = *it;\n        if( a.name() == \"cfg_attr\" ) {\n            if( check_cfg(a.span(), a.items().at(0)) ) {\n                auto inner_attr = mv$(a.items().at(1));\n                a = mv$(inner_attr);\n                ++ it;\n            }\n            else {\n                it = attrs.m_items.erase(it);\n            }\n        }\n        else {\n            ++ it;\n        }\n    }\n}\nvoid Expand_Attrs(const ::AST::AttributeList& attrs, AttrStage stage,  ::AST::Crate& crate, const ::AST::AbsolutePath& path, ::AST::Module& mod, ::AST::Item& item)\n{\n    Expand_Attrs(attrs, stage,  [&](const auto& sp, const auto& d, const auto& a){\n        if(!item.is_None()) {\n            \/\/ TODO: Pass attributes _after_ this attribute\n            d.handle(sp, a, crate, path, mod, slice<const AST::Attribute>(&a, &attrs.m_items.back() - &a + 1), item);\n        }\n        });\n}\nvoid Expand_Attrs(const ::AST::AttributeList& attrs, AttrStage stage,  ::AST::Crate& crate, const ::AST::AbsolutePath& path, ::AST::Trait& trait, ::AST::Item& item)\n{\n    Expand_Attrs(attrs, stage,  [&](const auto& sp, const auto& d, const auto& a){\n        if(!item.is_None()) {\n            \/\/ TODO: Pass attributes _after_ this attribute\n            d.handle(sp, a, crate, path, trait, slice<const AST::Attribute>(&a, &attrs.m_items.back() - &a + 1), item);\n        }\n        });\n}\nvoid Expand_Attrs(const ::AST::AttributeList& attrs, AttrStage stage,  ::AST::Crate& crate, ::AST::Impl& impl, const RcString& name, ::AST::Item& item)\n{\n    Expand_Attrs(attrs, stage,  [&](const auto& sp, const auto& d, const auto& a){\n        if(!item.is_None()) {\n            \/\/ TODO: Pass attributes _after_ this attribute\n            d.handle(sp, a, crate, impl, name, slice<const AST::Attribute>(&a, &attrs.m_items.back() - &a + 1), item);\n        }\n        });\n}\nvoid Expand_Attrs(const ::AST::AttributeList& attrs, AttrStage stage,  ::AST::Crate& crate, ::AST::Module& mod, ::AST::ImplDef& impl)\n{\n    Expand_Attrs(attrs, stage,  [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate, mod, impl); });\n}\n\nMacroRef Expand_LookupMacro(const Span& mi_span, const ::AST::Crate& crate, LList<const AST::Module*> modstack, const AST::Path& path)\n{\n    ASSERT_BUG(mi_span, path.size() > 0, \"Path should have nodes: \" << path);\n\n    if( path.is_trivial() )\n    {\n        const auto& name = path.as_trivial();\n        \/\/ 1. Search compiler-provided proc macros\n        if(auto* pm = Expand_FindProcMacro(name))\n        {\n            DEBUG(\"Found builtin\");\n            return MacroRef(pm);\n        }\n\n        \/\/ Iterate up the module tree, using the first located macro\n        for(const auto* ll = &modstack; ll; ll = ll->m_prev)\n        {\n            const auto& mac_mod = *ll->m_item;\n            DEBUG(\"Searching in \" << mac_mod.path());\n            for( const auto& mr : reverse(mac_mod.macros()) )\n            {\n                if( mr.name == name )\n                {\n                    DEBUG(mac_mod.path() << \"::\" << mr.name << \" - Defined\");\n                    return MacroRef(&*mr.data);\n                }\n            }\n\n            \/\/ Find the last macro of this name (allows later #[macro_use] definitions to override)\n            MacroRef    rv;\n            for( const auto& mri : mac_mod.macro_imports_res() )\n            {\n                \/\/DEBUG(\"- \" << mri.name);\n                if( mri.name == name )\n                {\n                    DEBUG(\"?::\" << mri.name << \" - Imported\");\n\n                    rv = mri.data.clone();\n                }\n            }\n            if( !rv.is_None() )\n            {\n                return rv;\n            }\n        }\n        if( path.m_class.is_Local() )\n        {\n            DEBUG(\"Local path not resolved?\");\n            return MacroRef();\n        }\n    }\n\n    \/\/ HACK: If the crate name is empty, look up builtins\n    if( path.is_absolute() && path.m_class.as_Absolute().crate == \"\" && path.nodes().size() == 1 )\n    {\n        const auto& name = path.nodes()[0].name();\n        if(auto* pm = Expand_FindProcMacro(name))\n        {\n            return MacroRef(pm);\n        }\n    }\n\n    \/\/ Resolve the path, following use statements (if required)\n    \/\/ - Only mr_ptr matters, as proc_mac is about builtins\n    auto rv = Resolve_Lookup_Macro(mi_span, crate, modstack.m_item->path(), path, \/*out_path=*\/nullptr);\n    TU_MATCH_HDRA( (rv), { )\n    TU_ARMA(None, _e)\n        return MacroRef();\n    TU_ARMA(InternalMacro, pm)\n        return pm;\n    TU_ARMA(ProcMacro, pm)\n        return pm;\n    TU_ARMA(MacroRules, p)\n        return p;\n    }\n    return MacroRef();\n}\n\n::std::unique_ptr<TokenStream> Expand_Macro_Inner(\n    const ::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::Module& mod,\n    Span mi_span, const AST::Path& path, const RcString& input_ident, TokenTree& input_tt\n    )\n{\n    if( !path.is_valid() ) {\n        return ::std::unique_ptr<TokenStream>();\n    }\n\n    TRACE_FUNCTION_F(\"Searching for macro \" << path);\n\n    \/\/ Find the macro\n    auto mac = Expand_LookupMacro(mi_span, crate, modstack, path);\n    if( mac.is_MacroRules() )\n    {\n        \/\/ TODO: If `mr_ptr` is tagged with #[rustc_builtin_macro], look for a matching entry in `g_macros`\n    }\n\n    TU_MATCH_HDRA( (mac), {)\n    TU_ARMA(None, e) {\n        ERROR(mi_span, E0000, \"Unknown macro \" << path);\n        }\n    TU_ARMA(ExternalProcMacro, proc_mac) {\n        ::std::vector<RcString> mac_path;\n        mac_path.push_back(proc_mac->path.m_crate_name);\n        mac_path.insert(mac_path.end(), proc_mac->path.m_components.begin(), proc_mac->path.m_components.end());\n        return ProcMacro_Invoke(mi_span, crate, mac_path, input_tt);\n        }\n    TU_ARMA(BuiltinProcMacro, proc_mac) {\n        auto e = input_ident == \"\"\n            ? proc_mac->expand(mi_span, crate, input_tt, mod)\n            : proc_mac->expand_ident(mi_span, crate, input_ident, input_tt, mod)\n            ;\n        return e;\n        }\n    TU_ARMA(MacroRules, mr_ptr) {\n        if( input_ident != \"\" )\n            ERROR(mi_span, E0000, \"macro_rules! macros can't take an ident\");\n\n        DEBUG(\"Invoking macro_rules \" << path << \" \" << mr_ptr);\n        auto e = Macro_InvokeRules(path.is_trivial() ? path.as_trivial().c_str() : FMT(path).c_str(), *mr_ptr, mi_span, mv$(input_tt), crate, mod);\n        input_tt = TokenTree();\n        return e;\n        }\n    }\n    throw \"\";\n}\n::std::unique_ptr<TokenStream> Expand_Macro(\n    const ::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::Module& mod,\n    Span mi_span, const AST::Path& name, const RcString& input_ident, TokenTree& input_tt\n    )\n{\n    auto rv = Expand_Macro_Inner(crate, modstack, mod, mi_span, name, input_ident, input_tt);\n    assert(rv);\n    rv->parse_state().crate = &crate;\n    rv->parse_state().module = &mod;\n    return rv;\n}\n::std::unique_ptr<TokenStream> Expand_Macro(const ::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::Module& mod, ::AST::MacroInvocation& mi)\n{\n    return Expand_Macro(crate, modstack, mod,  mi.span(), mi.path(), mi.input_ident(), mi.input_tt());\n}\n\nvoid Expand_Pattern(::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::Module& mod, ::AST::Pattern& pat, bool is_refutable)\n{\n    TU_MATCH(::AST::Pattern::Data, (pat.data()), (e),\n    (MaybeBind,\n        ),\n    (Macro,\n        const auto span = e.inv->span();\n\n        auto tt = Expand_Macro(crate, modstack, mod,  *e.inv);\n        if( ! tt ) {\n            ERROR(span, E0000, \"Macro in pattern didn't expand to anything\");\n        }\n        auto& lex = *tt;\n        auto newpat = Parse_Pattern(lex);\n        if( LOOK_AHEAD(lex) != TOK_EOF ) {\n            ERROR(span, E0000, \"Trailing tokens in macro expansion\");\n        }\n\n        if( pat.binding().is_valid() ) {\n            if( newpat.binding().is_valid() )\n                ERROR(span, E0000, \"Macro expansion provided a binding, but one already present\");\n            newpat.binding() = mv$(pat.binding());\n        }\n\n        pat = mv$(newpat);\n        Expand_Pattern(crate, modstack, mod, pat, is_refutable);\n        ),\n    (Any,\n        ),\n    (Box,\n        Expand_Pattern(crate, modstack, mod,  *e.sub, is_refutable);\n        ),\n    (Ref,\n        Expand_Pattern(crate, modstack, mod,  *e.sub, is_refutable);\n        ),\n    (Value,\n        \/\/Expand_Expr(crate, modstack, e.start);\n        \/\/Expand_Expr(crate, modstack, e.end);\n        ),\n    (Tuple,\n        for(auto& sp : e.start)\n            Expand_Pattern(crate, modstack, mod, sp, is_refutable);\n        for(auto& sp : e.end)\n            Expand_Pattern(crate, modstack, mod, sp, is_refutable);\n        ),\n    (StructTuple,\n        for(auto& sp : e.tup_pat.start)\n            Expand_Pattern(crate, modstack, mod, sp, is_refutable);\n        for(auto& sp : e.tup_pat.end)\n            Expand_Pattern(crate, modstack, mod, sp, is_refutable);\n        ),\n    (Struct,\n        for(auto& sp : e.sub_patterns)\n            Expand_Pattern(crate, modstack, mod, sp.second, is_refutable);\n        ),\n    (Slice,\n        for(auto& sp : e.sub_pats)\n            Expand_Pattern(crate, modstack, mod, sp, is_refutable);\n        ),\n    (SplitSlice,\n        for(auto& sp : e.leading)\n            Expand_Pattern(crate, modstack, mod, sp, is_refutable);\n        for(auto& sp : e.trailing)\n            Expand_Pattern(crate, modstack, mod, sp, is_refutable);\n        ),\n    (Or,\n        for(auto& sp : e)\n            Expand_Pattern(crate, modstack, mod, sp, is_refutable);\n        )\n    )\n}\n\nvoid Expand_Type(::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::Module& mod, ::TypeRef& ty)\n{\n    TU_MATCH_HDRA( (ty.m_data), {)\n    TU_ARMA(None, e) {\n        }\n    TU_ARMA(Any, e) {\n        }\n    TU_ARMA(Unit, e) {\n        }\n    TU_ARMA(Bang, e) {\n        }\n    TU_ARMA(Macro, e) {\n        auto tt = Expand_Macro(crate, modstack, mod,  *e.inv);\n        if(!tt)\n            ERROR(e.inv->span(), E0000, \"Macro invocation didn't yeild any data\");\n        auto new_ty = Parse_Type(*tt);\n        if( tt->lookahead(0) != TOK_EOF )\n            ERROR(e.inv->span(), E0000, \"Extra tokens after parsed type\");\n        ty = mv$(new_ty);\n\n        Expand_Type(crate, modstack, mod,  ty);\n        }\n    TU_ARMA(Primitive, e) {\n        }\n    TU_ARMA(Function, e) {\n        Type_Function& tf = e.info;\n        Expand_Type(crate, modstack, mod,  *tf.m_rettype);\n        for(auto& st : tf.m_arg_types)\n            Expand_Type(crate, modstack, mod,  st);\n        }\n    TU_ARMA(Tuple, e) {\n        for(auto& st : e.inner_types)\n            Expand_Type(crate, modstack, mod,  st);\n        }\n    TU_ARMA(Borrow, e) {\n        Expand_Type(crate, modstack, mod,  *e.inner);\n        }\n    TU_ARMA(Pointer, e) {\n        Expand_Type(crate, modstack, mod,  *e.inner);\n        }\n    TU_ARMA(Array, e) {\n        Expand_Type(crate, modstack, mod,  *e.inner);\n        if( e.size ) {\n            Expand_Expr(crate, modstack,  e.size);\n        }\n        }\n    TU_ARMA(Generic, e) {\n        }\n    TU_ARMA(Path, e) {\n        Expand_Path(crate, modstack, mod,  *e);\n        }\n    TU_ARMA(TraitObject, e) {\n        for(auto& p : e.traits)\n        {\n            \/\/ TODO: p.hrbs? Not needed until types are in those\n            Expand_Path(crate, modstack, mod,  *p.path);\n        }\n        }\n    TU_ARMA(ErasedType, e) {\n        for(auto& p : e.traits)\n        {\n            \/\/ TODO: p.hrbs?\n            Expand_Path(crate, modstack, mod,  *p.path);\n        }\n        }\n    }\n}\nvoid Expand_PathParams(::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::Module& mod, ::AST::PathParams& params)\n{\n    for(auto& e : params.m_entries)\n    {\n        TU_MATCH_HDRA( (e), {)\n        TU_ARMA(Null, _) {\n            }\n        TU_ARMA(Lifetime, _) {\n            }\n        TU_ARMA(Type, typ) {\n            Expand_Type(crate, modstack, mod, typ);\n            }\n        TU_ARMA(Value, node) {\n            Expand_Expr(crate, modstack, node);\n            }\n        TU_ARMA(AssociatedTyEqual, aty) {\n            Expand_Type(crate, modstack, mod, aty.second);\n            }\n        TU_ARMA(AssociatedTyBound, aty) {\n            Expand_Path(crate, modstack, mod, aty.second);\n            }\n        }\n    }\n}\nvoid Expand_Path(::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::Module& mod, ::AST::Path& p)\n{\n    auto expand_nodes = [&](::std::vector<::AST::PathNode>& nodes) {\n        for(auto& node : nodes)\n        {\n            Expand_PathParams(crate, modstack, mod, node.args());\n        }\n        };\n\n    TU_MATCH_HDRA( (p.m_class), {)\n    TU_ARMA(Invalid, pe) {\n        }\n    TU_ARMA(Local, pe) {\n        }\n    TU_ARMA(Relative, pe) {\n        expand_nodes(pe.nodes);\n        }\n    TU_ARMA(Self, pe) {\n        expand_nodes(pe.nodes);\n        }\n    TU_ARMA(Super, pe) {\n        expand_nodes(pe.nodes);\n        }\n    TU_ARMA(Absolute, pe) {\n        expand_nodes(pe.nodes);\n        }\n    TU_ARMA(UFCS, pe) {\n        Expand_Type(crate, modstack, mod, *pe.type);\n        if( pe.trait ) {\n            Expand_Path(crate, modstack, mod, *pe.trait);\n        }\n        expand_nodes(pe.nodes);\n        }\n    }\n}\n\nstruct CExpandExpr:\n    public ::AST::NodeVisitor\n{\n    ::AST::Crate&    crate;\n    LList<const AST::Module*>   modstack;\n    ::AST::ExprNodeP replacement;\n\n    \/\/ Stack of `try { ... }` blocks (the string is the loop label for the desugaring)\n    ::std::vector<RcString>   m_try_stack;\n    unsigned m_try_index = 0;\n\n    AST::ExprNode_Block*    current_block = nullptr;\n\n    CExpandExpr(::AST::Crate& crate, LList<const AST::Module*> ms):\n        crate(crate),\n        modstack(ms)\n    {\n    }\n\n    ::AST::Module& cur_mod() {\n        return *const_cast< ::AST::Module*>(modstack.m_item);\n    }\n\n    void visit(::AST::ExprNodeP& cnode) {\n        if(cnode.get())\n        {\n            auto attrs = mv$(cnode->attrs());\n            Expand_Attrs_CfgAttr(attrs);\n            Expand_Attrs(attrs, AttrStage::Pre,  [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, this->crate, cnode); });\n            if(cnode.get())\n                cnode->attrs() = mv$(attrs);\n        }\n        if(cnode.get())\n        {\n            cnode->visit(*this);\n            \/\/ If the node was a macro, and it was consumed, reset it\n            if( auto* n_mac = dynamic_cast<AST::ExprNode_Macro*>(cnode.get()) )\n            {\n                if( !n_mac->m_path.is_valid() )\n                    cnode.reset();\n            }\n            if( this->replacement ) {\n                cnode = mv$(this->replacement);\n            }\n        }\n\n        if(cnode.get())\n            Expand_Attrs(cnode->attrs(), AttrStage::Post,  [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, this->crate, cnode); });\n        assert( ! this->replacement );\n    }\n    void visit_nodelete(const ::AST::ExprNode& parent, ::AST::ExprNodeP& cnode) {\n        if( cnode.get() != nullptr )\n        {\n            this->visit(cnode);\n            if(cnode.get() == nullptr)\n                ERROR(parent.span(), E0000, \"#[cfg] not allowed in this position\");\n        }\n        assert( ! this->replacement );\n    }\n    void visit_vector(::std::vector< ::AST::ExprNodeP >& cnodes) {\n        for( auto it = cnodes.begin(); it != cnodes.end(); ) {\n            assert( it->get() );\n            this->visit(*it);\n            if( it->get() == nullptr ) {\n                it = cnodes.erase( it );\n            }\n            else {\n                ++ it;\n            }\n        }\n    }\n\n    ::AST::ExprNodeP visit_macro(::AST::ExprNode_Macro& node, ::std::vector< ::AST::ExprNodeP>* nodes_out)\n    {\n        TRACE_FUNCTION_F(node.m_path << \"!\");\n        if( !node.m_path.is_valid() ) {\n            return ::AST::ExprNodeP();\n        }\n\n        ::AST::ExprNodeP    rv;\n        auto& mod = this->cur_mod();\n        auto ttl = Expand_Macro( crate, modstack, mod,  node.span(),  node.m_path, node.m_ident, node.m_tokens );\n        if( !ttl.get() )\n        {\n            \/\/ No expansion\n        }\n        else\n        {\n            while( ttl->lookahead(0) != TOK_EOF )\n            {\n                SET_MODULE( (*ttl), mod );\n\n                \/\/ Reparse as expression \/ item\n                bool    add_silence_if_end = false;\n                ::std::shared_ptr< AST::Module> tmp_local_mod;\n                auto& local_mod_ptr = (this->current_block ? this->current_block->m_local_mod : tmp_local_mod);\n                DEBUG(\"-- Parsing as expression line\");\n                auto newexpr = Parse_ExprBlockLine_WithItems(*ttl, local_mod_ptr, add_silence_if_end);\n\n                if( tmp_local_mod )\n                    TODO(node.span(), \"Handle edge case where a macro expansion outside of a _Block creates an item\");\n\n                if( newexpr )\n                {\n                    if( nodes_out ) {\n                        nodes_out->push_back( mv$(newexpr) );\n                    }\n                    else {\n                        assert( !rv );\n                        rv = mv$(newexpr);\n                    }\n                }\n                else\n                {\n                    \/\/ Expansion line just added a new item\n                }\n\n                if( ttl->lookahead(0) != TOK_EOF )\n                {\n                    if( !nodes_out ) {\n                        ERROR(node.span(), E0000, \"Unused tokens at the end of macro expansion - \" << ttl->getToken());\n                    }\n                }\n            }\n        }\n\n        if( !nodes_out && !rv )\n        {\n            ERROR(node.span(), E0000, \"Macro didn't expand to anything\");\n        }\n\n        node.m_path = AST::Path();\n        return mv$(rv);\n    }\n\n    void visit(::AST::ExprNode_Macro& node) override\n    {\n        TRACE_FUNCTION_F(\"ExprNode_Macro - name = \" << node.m_path);\n        if( !node.m_path.is_valid() ) {\n            return ;\n        }\n\n        replacement = this->visit_macro(node, nullptr);\n\n        if( this->replacement )\n        {\n            DEBUG(\"--- Visiting new node\");\n            auto n = mv$(this->replacement);\n            this->visit(n);\n            if( n )\n            {\n                assert( !this->replacement );\n                this->replacement = mv$(n);\n            }\n        }\n    }\n\n    void visit(::AST::ExprNode_Block& node) override {\n        unsigned int mod_item_count = 0;\n\n        auto prev_modstack = this->modstack;\n        if( node.m_local_mod ) {\n            this->modstack = LList<const ::AST::Module*>(&prev_modstack, node.m_local_mod.get());\n        }\n\n        \/\/ TODO: macro_rules! invocations within the expression list influence this.\n        \/\/ > Solution: Defer creation of the local module until during expand.\n        if( node.m_local_mod ) {\n            Expand_Mod(crate, modstack, node.m_local_mod->path(), *node.m_local_mod);\n            mod_item_count = node.m_local_mod->m_items.size();\n        }\n\n        auto saved = this->current_block;\n        this->current_block = &node;\n\n        for( auto it = node.m_nodes.begin(); it != node.m_nodes.end(); )\n        {\n            assert( it->get() );\n\n            if( auto* node_mac = dynamic_cast<::AST::ExprNode_Macro*>(it->get()) )\n            {\n                auto attrs = std::move( (*it)->attrs() );\n                Expand_Attrs_CfgAttr( attrs );\n                Expand_Attrs(attrs, AttrStage::Pre,  [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, this->crate, *it); });\n                if( !it->get() ) {\n                    it = node.m_nodes.erase( it );\n                    continue ;\n                }\n                (*it)->attrs() = std::move(attrs);\n\n                assert(it->get() == node_mac);\n\n                ::std::vector< ::AST::ExprNodeP>    new_nodes;\n                this->visit_macro(*node_mac, &new_nodes);\n\n                it = node.m_nodes.erase(it);\n                it = node.m_nodes.insert(it, ::std::make_move_iterator(new_nodes.begin()), ::std::make_move_iterator(new_nodes.end()));\n                \/\/ NOTE: Doesn't advance the iterator above, we want to re-visit the new node\n            }\n            else\n            {\n                this->visit(*it);\n                if( it->get() == nullptr ) {\n                    it = node.m_nodes.erase( it );\n                }\n                else {\n                    ++ it;\n                }\n            }\n        }\n\n        this->current_block = saved;\n\n        \/\/ HACK! Run Expand_Mod twice on local modules.\n        if( node.m_local_mod ) {\n            Expand_Mod(crate, modstack, node.m_local_mod->path(), *node.m_local_mod, mod_item_count);\n        }\n\n        this->modstack = mv$(prev_modstack);\n    }\n    void visit(::AST::ExprNode_Try& node) override {\n        \/\/ Desugar into\n        \/\/ ```\n        \/\/ loop '#tryNNN {\n        \/\/   break '#tryNNN { ... }\n        \/\/ }\n        \/\/ ```\n        \/\/ NOTE: MIR lowering and HIR typecheck need to know to skip these (OR resolve should handle naming all loop blocks)\n        m_try_stack.push_back(RcString::new_interned(FMT(\"#try\" << m_try_index++)));\n        this->visit_nodelete(node, node.m_inner);\n        auto loop_name = mv$(m_try_stack.back());\n        m_try_stack.pop_back();\n\n        auto core_crate = crate.m_ext_cratename_core;\n        AST::ExprNodeP  ok_node;\n        if(TARGETVER_MOST_1_39)\n        {\n            auto path_Ok  = ::AST::Path(core_crate, {::AST::PathNode(\"result\"), ::AST::PathNode(\"Result\"), ::AST::PathNode(\"Ok\")});\n            ok_node = ::AST::ExprNodeP(new ::AST::ExprNode_CallPath( mv$(path_Ok), ::make_vec1(mv$(node.m_inner)) ));\n        }\n        else\n        {\n            auto path_Try = ::AST::Path(core_crate, {::AST::PathNode(\"ops\"), ::AST::PathNode(\"Try\")});\n            auto path_Try_from_output  = ::AST::Path::new_ufcs_trait(::TypeRef(node.span()), path_Try, { ::AST::PathNode(\"from_output\") });\n            ok_node = ::AST::ExprNodeP(new ::AST::ExprNode_CallPath( mv$(path_Try_from_output), ::make_vec1(mv$(node.m_inner)) ));\n        }\n        auto break_node = AST::ExprNodeP(new AST::ExprNode_Flow(AST::ExprNode_Flow::BREAK, loop_name, mv$(ok_node)));\n        this->replacement = AST::ExprNodeP(new AST::ExprNode_Loop(loop_name, mv$(break_node)));\n    }\n    void visit(::AST::ExprNode_Asm& node) override {\n        for(auto& v : node.m_output)\n            this->visit_nodelete(node, v.value);\n        for(auto& v : node.m_input)\n            this->visit_nodelete(node, v.value);\n    }\n    void visit(::AST::ExprNode_Asm2& node) override {\n        for(auto& v : node.m_params)\n        {\n            TU_MATCH_HDRA((v), {)\n            TU_ARMA(Const, e) {\n                this->visit_nodelete(node, e);\n                }\n            TU_ARMA(Sym, e) {\n                Expand_Path(crate, modstack, this->cur_mod(), e);\n                }\n            TU_ARMA(RegSingle, e) {\n                this->visit_nodelete(node, e.val);\n                }\n            TU_ARMA(Reg, e) {\n                this->visit_nodelete(node, e.val_in);\n                this->visit_nodelete(node, e.val_out);\n                }\n            }\n        }\n    }\n    void visit(::AST::ExprNode_Flow& node) override {\n        this->visit_nodelete(node, node.m_value);\n    }\n    void visit(::AST::ExprNode_LetBinding& node) override {\n        Expand_Type(crate, modstack, this->cur_mod(),  node.m_type);\n        Expand_Pattern(crate, modstack, this->cur_mod(),  node.m_pat, false);\n        this->visit_nodelete(node, node.m_value);\n    }\n    void visit(::AST::ExprNode_Assign& node) override {\n        this->visit_nodelete(node, node.m_slot);\n        this->visit_nodelete(node, node.m_value);\n    }\n    void visit(::AST::ExprNode_CallPath& node) override {\n        Expand_Path(crate, modstack, this->cur_mod(),  node.m_path);\n        this->visit_vector(node.m_args);\n    }\n    void visit(::AST::ExprNode_CallMethod& node) override {\n        Expand_PathParams(crate, modstack, this->cur_mod(), node.m_method.args());\n        this->visit_nodelete(node, node.m_val);\n        this->visit_vector(node.m_args);\n    }\n    void visit(::AST::ExprNode_CallObject& node) override {\n        this->visit_nodelete(node, node.m_val);\n        this->visit_vector(node.m_args);\n    }\n    void visit(::AST::ExprNode_Loop& node) override {\n        this->visit_nodelete(node, node.m_cond);\n        this->visit_nodelete(node, node.m_code);\n        Expand_Pattern(crate, modstack, this->cur_mod(),  node.m_pattern, (node.m_type == ::AST::ExprNode_Loop::WHILELET));\n        if(node.m_type == ::AST::ExprNode_Loop::FOR)\n        {\n            auto core_crate = crate.m_ext_cratename_core;\n            auto path_Some = ::AST::Path(core_crate, {::AST::PathNode(\"option\"), ::AST::PathNode(\"Option\"), ::AST::PathNode(\"Some\")});\n            auto path_None = ::AST::Path(core_crate, {::AST::PathNode(\"option\"), ::AST::PathNode(\"Option\"), ::AST::PathNode(\"None\")});\n            auto path_IntoIterator = ::AST::Path(core_crate, {::AST::PathNode(\"iter\"), ::AST::PathNode(\"IntoIterator\")});\n            auto path_Iterator = ::AST::Path(core_crate, {::AST::PathNode(\"iter\"), ::AST::PathNode(\"Iterator\")});\n            \/\/ Desugar into:\n            \/\/ {\n            \/\/     match <_ as ::iter::IntoIterator>::into_iter(`m_cond`) {\n            \/\/     mut it => {\n            \/\/         `m_label`: loop {\n            \/\/             match ::iter::Iterator::next(&mut it) {\n            \/\/             Some(`m_pattern`) => `m_code`,\n            \/\/             None => break `m_label`,\n            \/\/             }\n            \/\/         }\n            \/\/     }\n            \/\/ }\n            ::std::vector< ::AST::ExprNode_Match_Arm>   arms;\n            \/\/ - `Some(pattern ) => code`\n            arms.push_back( ::AST::ExprNode_Match_Arm(\n                ::make_vec1( ::AST::Pattern(::AST::Pattern::TagNamedTuple(), node.span(), path_Some, ::make_vec1( mv$(node.m_pattern) ) ) ),\n                nullptr,\n                mv$(node.m_code)\n                ) );\n            \/\/ - `None => break label`\n            arms.push_back( ::AST::ExprNode_Match_Arm(\n                ::make_vec1( ::AST::Pattern(::AST::Pattern::TagValue(), node.span(), ::AST::Pattern::Value::make_Named(path_None)) ),\n                nullptr,\n                ::AST::ExprNodeP(new ::AST::ExprNode_Flow(::AST::ExprNode_Flow::BREAK, node.m_label, nullptr))\n                ) );\n\n            replacement.reset(new ::AST::ExprNode_Match(\n                ::AST::ExprNodeP(new ::AST::ExprNode_CallPath(\n                    ::AST::Path::new_ufcs_trait( ::TypeRef(node.span()), path_IntoIterator, { ::AST::PathNode(\"into_iter\") } ),\n                    ::make_vec1( mv$(node.m_cond) )\n                    )),\n                ::make_vec1(::AST::ExprNode_Match_Arm(\n                    ::make_vec1( ::AST::Pattern(::AST::Pattern::TagBind(), node.span(), \"it\") ),\n                    nullptr,\n                    ::AST::ExprNodeP(new ::AST::ExprNode_Loop(\n                        node.m_label,\n                        ::AST::ExprNodeP(new ::AST::ExprNode_Match(\n                            ::AST::ExprNodeP(new ::AST::ExprNode_CallPath(\n                                ::AST::Path::new_ufcs_trait( ::TypeRef(node.span()), path_Iterator, { ::AST::PathNode(\"next\") } ),\n                                ::make_vec1( ::AST::ExprNodeP(new ::AST::ExprNode_UniOp(\n                                    ::AST::ExprNode_UniOp::REFMUT,\n                                    ::AST::ExprNodeP(new ::AST::ExprNode_NamedValue( ::AST::Path(\"it\") ))\n                                    )) )\n                                )),\n                            mv$(arms)\n                            ))\n                        )) )\n                    )\n                ) );\n        }\n    }\n    void visit(::AST::ExprNode_Match& node) override {\n        this->visit_nodelete(node, node.m_val);\n        for(auto& arm : node.m_arms)\n        {\n            Expand_Attrs_CfgAttr( arm.m_attrs );\n            Expand_Attrs(arm.m_attrs, AttrStage::Pre ,  [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate,  arm); });\n            if( arm.m_patterns.size() == 0 )\n                continue ;\n            for(auto& pat : arm.m_patterns) {\n                Expand_Pattern(crate, modstack, this->cur_mod(),  pat, true);\n            }\n            this->visit_nodelete(node, arm.m_cond);\n            this->visit_nodelete(node, arm.m_code);\n            Expand_Attrs(arm.m_attrs, AttrStage::Post,  [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate,  arm); });\n        }\n        \/\/ Prune deleted arms\n        for(auto it = node.m_arms.begin(); it != node.m_arms.end(); ) {\n            if( it->m_patterns.size() == 0 )\n                it = node.m_arms.erase(it);\n            else\n                ++ it;\n        }\n    }\n    void visit(::AST::ExprNode_If& node) override {\n        this->visit_nodelete(node, node.m_cond);\n        this->visit_nodelete(node, node.m_true);\n        this->visit_nodelete(node, node.m_false);\n    }\n    void visit(::AST::ExprNode_IfLet& node) override {\n        for(auto& pat : node.m_patterns)\n            Expand_Pattern(crate, modstack, this->cur_mod(),  pat, true);\n        this->visit_nodelete(node, node.m_value);\n        this->visit_nodelete(node, node.m_true);\n        this->visit_nodelete(node, node.m_false);\n    }\n    void visit(::AST::ExprNode_Integer& node) override { }\n    void visit(::AST::ExprNode_Float& node) override { }\n    void visit(::AST::ExprNode_Bool& node) override { }\n    void visit(::AST::ExprNode_String& node) override { }\n    void visit(::AST::ExprNode_ByteString& node) override { }\n    void visit(::AST::ExprNode_Closure& node) override {\n        for(auto& arg : node.m_args) {\n            Expand_Pattern(crate, modstack, this->cur_mod(),  arg.first, false);\n            Expand_Type(crate, modstack, this->cur_mod(),  arg.second);\n        }\n        Expand_Type(crate, modstack, this->cur_mod(),  node.m_return);\n        this->visit_nodelete(node, node.m_code);\n    }\n    void visit(::AST::ExprNode_StructLiteral& node) override {\n        this->visit_nodelete(node, node.m_base_value);\n        for(auto& val : node.m_values)\n        {\n            Expand_Attrs_CfgAttr(val.attrs);\n            Expand_Attrs(val.attrs, AttrStage::Pre ,  [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate,  val); });\n            if( !val.value )\n                continue ;\n            this->visit_nodelete(node, val.value);\n            Expand_Attrs(val.attrs, AttrStage::Post,  [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate,  val); });\n        }\n        for(auto it = node.m_values.begin(); it != node.m_values.end(); )\n        {\n            if( it->value )\n                ++it;\n            else\n                it = node.m_values.erase(it);\n        }\n    }\n    void visit(::AST::ExprNode_Array& node) override {\n        this->visit_nodelete(node, node.m_size);\n        this->visit_vector(node.m_values);\n    }\n    void visit(::AST::ExprNode_Tuple& node) override {\n        this->visit_vector(node.m_values);\n    }\n    void visit(::AST::ExprNode_NamedValue& node) override {\n        Expand_Path(crate, modstack, this->cur_mod(),  node.m_path);\n    }\n    void visit(::AST::ExprNode_Field& node) override {\n        this->visit_nodelete(node, node.m_obj);\n    }\n    void visit(::AST::ExprNode_Index& node) override {\n        this->visit_nodelete(node, node.m_obj);\n        this->visit_nodelete(node, node.m_idx);\n    }\n    void visit(::AST::ExprNode_Deref& node) override {\n        this->visit_nodelete(node, node.m_value);\n    }\n    void visit(::AST::ExprNode_Cast& node) override {\n        this->visit_nodelete(node, node.m_value);\n        Expand_Type(crate, modstack, this->cur_mod(),  node.m_type);\n    }\n    void visit(::AST::ExprNode_TypeAnnotation& node) override {\n        this->visit_nodelete(node, node.m_value);\n        Expand_Type(crate, modstack, this->cur_mod(),  node.m_type);\n    }\n    void visit(::AST::ExprNode_BinOp& node) override {\n        this->visit_nodelete(node, node.m_left);\n        this->visit_nodelete(node, node.m_right);\n\n        switch(node.m_type)\n        {\n        case ::AST::ExprNode_BinOp::RANGE: {\n            \/\/ NOTE: Not language items pre 1.39\n            auto core_crate = crate.m_ext_cratename_core;\n            auto path_Range     = ::AST::Path(core_crate, {::AST::PathNode(\"ops\"), ::AST::PathNode(\"Range\") });\n            auto path_RangeFrom = ::AST::Path(core_crate, {::AST::PathNode(\"ops\"), ::AST::PathNode(\"RangeFrom\") });\n            auto path_RangeTo   = ::AST::Path(core_crate, {::AST::PathNode(\"ops\"), ::AST::PathNode(\"RangeTo\") });\n            auto path_RangeFull = ::AST::Path(core_crate, {::AST::PathNode(\"ops\"), ::AST::PathNode(\"RangeFull\") });\n\n            ::AST::ExprNode_StructLiteral::t_values values;\n            if( node.m_left && node.m_right )\n            {\n                values.push_back({ {}, \"start\", mv$(node.m_left ) });\n                values.push_back({ {}, \"end\"  , mv$(node.m_right) });\n                replacement.reset( new ::AST::ExprNode_StructLiteral(mv$(path_Range), nullptr, mv$(values)) );\n            }\n            else if( node.m_left )\n            {\n                values.push_back({ {}, \"start\", mv$(node.m_left ) });\n                replacement.reset( new ::AST::ExprNode_StructLiteral(mv$(path_RangeFrom), nullptr, mv$(values)) );\n            }\n            else if( node.m_right )\n            {\n                values.push_back({ {}, \"end\"  , mv$(node.m_right) });\n                replacement.reset( new ::AST::ExprNode_StructLiteral(mv$(path_RangeTo), nullptr, mv$(values)) );\n            }\n            else\n            {\n                replacement.reset( new ::AST::ExprNode_StructLiteral(mv$(path_RangeFull), nullptr, mv$(values)) );\n            }\n            replacement->set_span( node.span() );\n            break; }\n        case ::AST::ExprNode_BinOp::RANGE_INC: {\n            \/\/ NOTE: Not language items pre 1.54\n            auto core_crate = crate.m_ext_cratename_core;\n            auto path_None = ::AST::Path(core_crate, { ::AST::PathNode(\"option\"), ::AST::PathNode(\"Option\"), ::AST::PathNode(\"None\") });\n            auto path_RangeInclusive_NonEmpty = ::AST::Path(core_crate, { ::AST::PathNode(\"ops\"), ::AST::PathNode(\"RangeInclusive\") });\n            auto path_RangeToInclusive        = ::AST::Path(core_crate, { ::AST::PathNode(\"ops\"), ::AST::PathNode(\"RangeToInclusive\") });\n\n            if( node.m_left )\n            {\n                ::AST::ExprNode_StructLiteral::t_values values;\n                values.push_back({ {}, \"start\", mv$(node.m_left)  });\n                values.push_back({ {}, \"end\"  , mv$(node.m_right) });\n                if( gTargetVersion >= TargetVersion::Rustc1_29 )\n                    values.push_back({ {}, \"is_empty\", ::AST::ExprNodeP(new ::AST::ExprNode_NamedValue(mv$(path_None))) });\n                replacement.reset( new ::AST::ExprNode_StructLiteral(mv$(path_RangeInclusive_NonEmpty), nullptr, mv$(values)) );\n            }\n            else\n            {\n                ::AST::ExprNode_StructLiteral::t_values values;\n                values.push_back({ {}, \"end\",  mv$(node.m_right) });\n                replacement.reset( new ::AST::ExprNode_StructLiteral(mv$(path_RangeToInclusive), nullptr, mv$(values)) );\n            }\n            replacement->set_span( node.span() );\n            break; }\n        default:\n            break;\n        }\n    }\n    void visit(::AST::ExprNode_UniOp& node) override {\n        this->visit_nodelete(node, node.m_value);\n        \/\/ - Desugar question mark operator before resolve so it can create names\n        if( node.m_type == ::AST::ExprNode_UniOp::QMARK ) {\n            auto core_crate = crate.m_ext_cratename_core;\n            \n            \/\/ TODO: Find a way of creating bindings during HIR lower instead (so lang items are available)\n\n            \/\/auto it = crate.m_lang_items.find(\"try\");\n            \/\/ASSERT_BUG(node.span(), it != crate.m_lang_items.end(), \"Can't find the `try` lang item\");\n            \/\/auto path_Try = it->second;\n            auto path_Try = ::AST::Path(core_crate, {::AST::PathNode(\"ops\"), ::AST::PathNode(\"Try\")});\n            if(TARGETVER_MOST_1_39)\n            {\n                auto path_Ok  = ::AST::Path(core_crate, {::AST::PathNode(\"result\"), ::AST::PathNode(\"Result\"), ::AST::PathNode(\"Ok\")});\n                auto path_Err = ::AST::Path(core_crate, {::AST::PathNode(\"result\"), ::AST::PathNode(\"Result\"), ::AST::PathNode(\"Err\")});\n                auto path_From = ::AST::Path(core_crate, {::AST::PathNode(\"convert\"), ::AST::PathNode(\"From\")});\n                path_From.nodes().back().args().m_entries.push_back( ::TypeRef(node.span()) );\n\n                auto path_Try_into_result = ::AST::Path::new_ufcs_trait(::TypeRef(node.span()), path_Try, { ::AST::PathNode(\"into_result\") });\n                auto path_Try_from_error  = ::AST::Path::new_ufcs_trait(::TypeRef(node.span()), path_Try, { ::AST::PathNode(\"from_error\") });\n\n                \/\/ Desugars into\n                \/\/ ```\n                \/\/ match `Try::into_result(m_value)` {\n                \/\/ Ok(v) => v,\n                \/\/ Err(e) => return Try::from_error(From::from(e)),\n                \/\/ }\n                \/\/ ```\n\n                ::std::vector< ::AST::ExprNode_Match_Arm>   arms;\n                \/\/ `Ok(v) => v,`\n                arms.push_back(::AST::ExprNode_Match_Arm(\n                    ::make_vec1( ::AST::Pattern(::AST::Pattern::TagNamedTuple(), node.span(), path_Ok, ::make_vec1( ::AST::Pattern(::AST::Pattern::TagBind(), node.span(), \"v\") )) ),\n                    nullptr,\n                    ::AST::ExprNodeP( new ::AST::ExprNode_NamedValue( ::AST::Path(\"v\") ) )\n                    ));\n                \/\/ `Err(e) => return Try::from_error(From::from(e)),`\n                arms.push_back(::AST::ExprNode_Match_Arm(\n                    ::make_vec1( ::AST::Pattern(::AST::Pattern::TagNamedTuple(), node.span(), path_Err, ::make_vec1( ::AST::Pattern(::AST::Pattern::TagBind(), node.span(), \"e\") )) ),\n                    nullptr,\n                    ::AST::ExprNodeP(new ::AST::ExprNode_Flow(\n                        (m_try_stack.empty() ? ::AST::ExprNode_Flow::RETURN : ::AST::ExprNode_Flow::BREAK),   \/\/ NOTE: uses `break 'tryblock` instead of return if in a try block.\n                        (m_try_stack.empty() ? RcString(\"\") : m_try_stack.back()),\n                        ::AST::ExprNodeP(new ::AST::ExprNode_CallPath(\n                            ::AST::Path(path_Try_from_error),\n                            ::make_vec1(\n                                ::AST::ExprNodeP(new ::AST::ExprNode_CallPath(\n                                    ::AST::Path::new_ufcs_trait(::TypeRef(node.span()), mv$(path_From), { ::AST::PathNode(\"from\") }),\n                                    ::make_vec1( ::AST::ExprNodeP( new ::AST::ExprNode_NamedValue( ::AST::Path(\"e\") ) ) )\n                                    ))\n                                )\n                            ))\n                        ))\n                    ));\n\n                replacement.reset(new ::AST::ExprNode_Match(\n                    ::AST::ExprNodeP(new AST::ExprNode_CallPath(\n                        mv$(path_Try_into_result),\n                        ::make_vec1( mv$(node.m_value) )\n                        )),\n                    mv$(arms)\n                    ));\n            }\n            else  \/\/ 1.54+ - TryV2\n            {\n                auto path_Try_branch = ::AST::Path::new_ufcs_trait(::TypeRef(node.span()), path_Try, { ::AST::PathNode(\"branch\") });\n                \/\/ Not a lang item\n                auto path_ControlFlow_Continue = ::AST::Path(core_crate, {::AST::PathNode(\"ops\"), ::AST::PathNode(\"ControlFlow\"), ::AST::PathNode(\"Continue\")});\n                auto path_ControlFlow_Break    = ::AST::Path(core_crate, {::AST::PathNode(\"ops\"), ::AST::PathNode(\"ControlFlow\"), ::AST::PathNode(\"Break\"   )});\n                auto path_FromResidual_from_residual = ::AST::Path(core_crate, {::AST::PathNode(\"ops\"), ::AST::PathNode(\"FromResidual\"), ::AST::PathNode(\"from_residual\")});\n\n                ::std::vector< ::AST::ExprNode_Match_Arm>   arms;\n                \/\/ `Continue(v) => v,`\n                arms.push_back(::AST::ExprNode_Match_Arm(\n                    ::make_vec1( ::AST::Pattern(::AST::Pattern::TagNamedTuple(), node.span(), path_ControlFlow_Continue, ::make_vec1( ::AST::Pattern(::AST::Pattern::TagBind(), node.span(), \"v\") )) ),\n                    nullptr,\n                    ::AST::ExprNodeP( new ::AST::ExprNode_NamedValue( ::AST::Path(\"v\") ) )\n                    ));\n                \/\/ `Break(r) => return R::from_residual(r),`\n                arms.push_back(::AST::ExprNode_Match_Arm(\n                    ::make_vec1( ::AST::Pattern(::AST::Pattern::TagNamedTuple(), node.span(), path_ControlFlow_Break, ::make_vec1( ::AST::Pattern(::AST::Pattern::TagBind(), node.span(), \"e\") )) ),\n                    nullptr,\n                    ::AST::ExprNodeP(new ::AST::ExprNode_Flow(\n                        (m_try_stack.empty() ? ::AST::ExprNode_Flow::RETURN : ::AST::ExprNode_Flow::BREAK),   \/\/ NOTE: uses `break 'tryblock` instead of return if in a try block.\n                        (m_try_stack.empty() ? RcString(\"\") : m_try_stack.back()),\n                        ::AST::ExprNodeP(new ::AST::ExprNode_CallPath(\n                            ::AST::Path(path_FromResidual_from_residual),\n                            ::make_vec1(::AST::ExprNodeP( new ::AST::ExprNode_NamedValue( ::AST::Path(\"e\") ) ))\n                            ))\n                        ))\n                    ));\n\n                replacement.reset(new ::AST::ExprNode_Match(\n                    ::AST::ExprNodeP(new AST::ExprNode_CallPath(\n                        mv$(path_Try_branch),\n                        ::make_vec1( mv$(node.m_value) )\n                        )),\n                    mv$(arms)\n                    ));\n            }\n        }\n    }\n};\n\nvoid Expand_Expr(::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::ExprNodeP& node)\n{\n    TRACE_FUNCTION_F(\"unique_ptr\");\n    auto visitor = CExpandExpr(crate, modstack);\n    visitor.visit(node);\n}\nvoid Expand_Expr(::AST::Crate& crate, LList<const AST::Module*> modstack, ::std::shared_ptr<AST::ExprNode>& node)\n{\n    TRACE_FUNCTION_F(\"shared_ptr\");\n    auto visitor = CExpandExpr(crate, modstack);\n    node->visit(visitor);\n    if( visitor.replacement ) {\n        node.reset( visitor.replacement.release() );\n    }\n}\nvoid Expand_Expr(::AST::Crate& crate, LList<const AST::Module*> modstack, AST::Expr& node)\n{\n    TRACE_FUNCTION_F(\"AST::Expr\");\n    auto visitor = CExpandExpr(crate, modstack);\n    node.visit_nodes(visitor);\n    if( visitor.replacement ) {\n        node = AST::Expr( mv$(visitor.replacement) );\n    }\n}\n\nvoid Expand_GenericParams(::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::Module& mod,  ::AST::GenericParams& params)\n{\n    for(auto& param_def : params.m_params)\n    {\n        TU_MATCH_HDRA( (param_def), {)\n        TU_ARMA(None, e) {\n            \/\/ Ignore\n            }\n        TU_ARMA(Lifetime, e) {\n            }\n        TU_ARMA(Type, ty_def) {\n            Expand_Type(crate, modstack, mod,  ty_def.get_default());\n            }\n        TU_ARMA(Value, val_def) {\n            Expand_Type(crate, modstack, mod,  val_def.type());\n            }\n        }\n    }\n    for(auto& bound : params.m_bounds)\n    {\n        TU_MATCHA( (bound), (be),\n        (None,\n            ),\n        (Lifetime,\n            ),\n        (TypeLifetime,\n            Expand_Type(crate, modstack, mod,  be.type);\n            ),\n        (IsTrait,\n            Expand_Type(crate, modstack, mod,  be.type);\n            Expand_Path(crate, modstack, mod,  be.trait);\n            ),\n        (MaybeTrait,\n            Expand_Type(crate, modstack, mod,  be.type);\n            Expand_Path(crate, modstack, mod,  be.trait);\n            ),\n        (NotTrait,\n            Expand_Type(crate, modstack, mod,  be.type);\n            Expand_Path(crate, modstack, mod,  be.trait);\n            ),\n        (Equality,\n            Expand_Type(crate, modstack, mod,  be.type);\n            Expand_Type(crate, modstack, mod,  be.replacement);\n            )\n        )\n    }\n}\n\nvoid Expand_BareExpr(const ::AST::Crate& crate, const AST::Module& mod, ::AST::ExprNodeP& node)\n{\n    Expand_Expr(const_cast< ::AST::Crate&>(crate), LList<const AST::Module*>(nullptr, &mod), node);\n}\n\nvoid Expand_Impl(::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::Path modpath, ::AST::Module& mod, ::AST::Impl& impl)\n{\n    TRACE_FUNCTION_F(impl.def());\n    Expand_Attrs_CfgAttr(impl.def().attrs());\n    Expand_Attrs(impl.def().attrs(), AttrStage::Pre,  crate, mod, impl.def());\n    if( impl.def().type().is_wildcard() ) {\n        DEBUG(\"Deleted\");\n        return ;\n    }\n    Expand_GenericParams(crate, modstack, mod,  impl.def().params());\n\n    Expand_Type(crate, modstack, mod,  impl.def().type());\n    Expand_Path(crate, modstack, mod,  impl.def().trait().ent);\n\n    DEBUG(\"> Items\");\n    for( unsigned int idx = 0; idx < impl.items().size(); idx ++ )\n    {\n        auto& i = impl.items()[idx];\n        DEBUG(\"  - \" << i.name << \" :: \" << i.attrs);\n\n        \/\/ TODO: Make a path from the impl definition? Requires having the impl def resolved to be correct\n        \/\/ - Does it? the namespace is essentially the same. There may be issues with wherever the path is used though\n        \/\/ TODO: UFCS path, or different method\n        AST::AbsolutePath   path(\"\", {\"\", i.name});\n\n        auto attrs = mv$(i.attrs);\n        Expand_Attrs_CfgAttr(attrs);\n        Expand_Attrs(attrs, AttrStage::Pre,  crate, impl, i.name, *i.data);\n\n        TU_MATCH_HDRA( (*i.data), {)\n        default:\n            BUG(Span(), \"Unknown item type in impl block - \" << i.data->tag_str());\n        TU_ARMA(None, e) {\n            }\n        TU_ARMA(MacroInv, e) {\n            if( e.path().is_valid() )\n            {\n                TRACE_FUNCTION_F(\"Macro invoke \" << e.path());\n                \/\/ Move out of the module to avoid invalidation if a new macro invocation is added\n                auto mi_owned = mv$(e);\n\n                auto ttl = Expand_Macro(crate, modstack, mod, mi_owned);\n\n                if( ttl.get() )\n                {\n                    \/\/ Re-parse tt\n                    while( ttl->lookahead(0) != TOK_EOF )\n                    {\n                        Parse_Impl_Item(*ttl, impl);\n                    }\n                    \/\/ - Any new macro invocations ends up at the end of the list and handled\n                }\n                \/\/ Move back in (using the index, as the old pointr may be invalid)\n                impl.items()[idx].data->as_MacroInv() = mv$(mi_owned);\n            }\n            }\n        TU_ARMA(Function, e) {\n            TRACE_FUNCTION_F(\"fn \" << i.name);\n            for(auto& arg : e.args()) {\n                Expand_Pattern(crate, modstack, mod,  arg.first, false);\n                Expand_Type(crate, modstack, mod,  arg.second);\n            }\n            Expand_Type(crate, modstack, mod,  e.rettype());\n            Expand_Expr(crate, modstack, e.code());\n            }\n        TU_ARMA(Static, e) {\n            TRACE_FUNCTION_F(\"static \" << i.name);\n            Expand_Expr(crate, modstack, e.value());\n            Expand_Type(crate, modstack, mod,  e.type());\n            }\n        TU_ARMA(Type, e) {\n            TRACE_FUNCTION_F(\"type \" << i.name);\n            Expand_Type(crate, modstack, mod,  e.type());\n            }\n        }\n\n        \/\/ Run post-expansion decorators and restore attributes\n        {\n            auto& i = impl.items()[idx];\n            Expand_Attrs(attrs, AttrStage::Post,  crate, impl, i.name, *i.data);\n            \/\/ TODO: How would this be populated? It got moved out?\n            if( i.attrs.m_items.size() == 0 )\n                i.attrs = mv$(attrs);\n        }\n    }\n\n    Expand_Attrs(impl.def().attrs(), AttrStage::Post,  crate, mod, impl.def());\n}\nvoid Expand_ImplDef(::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::Path modpath, ::AST::Module& mod, ::AST::ImplDef& impl_def)\n{\n    Expand_Attrs_CfgAttr(impl_def.attrs());\n    Expand_Attrs(impl_def.attrs(), AttrStage::Pre,  crate, mod, impl_def);\n    if( impl_def.type().is_wildcard() ) {\n        DEBUG(\"Deleted\");\n        return ;\n    }\n    Expand_GenericParams(crate, modstack, mod,  impl_def.params());\n\n    Expand_Type(crate, modstack, mod,  impl_def.type());\n    \/\/Expand_Type(crate, modstack, mod,  impl_def.trait());\n\n    Expand_Attrs(impl_def.attrs(), AttrStage::Post,  crate, mod, impl_def);\n}\n\nvoid Expand_Mod(::AST::Crate& crate, LList<const AST::Module*> modstack, ::AST::AbsolutePath modpath, ::AST::Module& mod, unsigned int first_item)\n{\n    TRACE_FUNCTION_F(\"modpath = \" << modpath << \", first_item=\" << first_item);\n\n    \/\/ TODO: Pre-parse all macro_rules invocations into items?\n\n    for( const auto& mi: mod.macro_imports_res() )\n        DEBUG(\"- Imports '\" << mi.name << \"'\");\n    \/\/ Import all macros from parent module.\n    if( first_item == 0 )\n    {\n        for( const auto& mi: mod.macro_imports_res() )\n            DEBUG(\"- Imports '\" << mi.name << \"'\");\n        if( modstack.m_prev )\n        {\n            for(const auto& mac : modstack.m_prev->m_item->m_macro_imports)\n            {\n                mod.m_macro_imports.push_back(mac);\n            }\n        }\n        for( const auto& mi: mod.m_macro_imports )\n            DEBUG(\"- Imports '\" << mi.path << \"'\");\n    }\n\n    \/\/ Insert prelude if: Enabled for this module, present for the crate, and this module is not an anon\n    if( crate.m_prelude_path != AST::Path() )\n    {\n        if( mod.m_insert_prelude && ! mod.is_anon() ) {\n            DEBUG(\"> Adding custom prelude \" << crate.m_prelude_path);\n            mod.add_item(Span(), false, \"\", ::AST::UseItem { Span(), ::make_vec1(::AST::UseItem::Ent { Span(), crate.m_prelude_path, \"\" }) }, {});\n        }\n        else {\n            DEBUG(\"> Not inserting custom prelude (anon or disabled)\");\n        }\n    }\n\n    \/\/ Stack to prevent macro recursion\n    \/\/ - Items are popped if the item address matches\n    std::vector<const AST::Named<AST::Item>*>   macro_recursion_stack;\n\n    DEBUG(\"Items\");\n    for( unsigned int idx = first_item; idx < mod.m_items.size(); idx ++ )\n    {\n        auto& i = *mod.m_items[idx];\n\n        \/\/ If this is the pop point for this entry, then pop\n        \/\/ - Note, can be `nullptr`, but that indicates that the macro invocation was the end\n        while( !macro_recursion_stack.empty() && macro_recursion_stack.back() == &i ) {\n            macro_recursion_stack.pop_back();\n            DEBUG(\"End macro recursion guard\");\n        }\n\n        DEBUG(\"- \" << modpath << \"::\" << i.name << \" (\" << ::AST::Item::tag_to_str(i.data.tag()) << \") :: \" << i.attrs);\n        auto path = modpath + i.name;\n\n        if(const auto* mi = i.data.opt_MacroInv() )\n        {\n            if( mi->path().is_trivial() && mi->path().as_trivial() == \"macro_rules\" ) {\n                i.is_pub = true;\n                DEBUG(\"macro_rules made pub\");\n            }\n        }\n\n        auto attrs = mv$(i.attrs);\n        Expand_Attrs_CfgAttr(attrs);\n        Expand_Attrs(attrs, AttrStage::Pre,  crate, path, mod, i.data);\n\n        \/\/ Do modules without moving the definition (so the module path is always valid)\n        if( i.data.is_Module() )\n        {\n            auto& e = i.data.as_Module();\n            LList<const AST::Module*>   sub_modstack(&modstack, &e);\n            Expand_Mod(crate, sub_modstack, path, e);\n            Expand_Attrs(attrs, AttrStage::Post,  crate, path, mod, i.data);\n            i.attrs = mv$(attrs);\n            continue ;\n        }\n\n        auto dat = mv$(i.data);\n\n        TU_MATCH_HDRA( (dat), {)\n        TU_ARMA(None, e) {\n            \/\/ Skip: nothing\n            }\n        TU_ARMA(MacroInv, e) {\n            \/\/ Move out of the module to avoid invalidation if a new macro invocation is added\n\n            if( macro_recursion_stack.size() > MAX_MACRO_RECURSION ) {\n                ERROR(i.span, E0000, \"Exceeded macro recusion limit of \" << MAX_MACRO_RECURSION);\n            }\n            auto mi_owned = mv$(e);\n\n            TRACE_FUNCTION_F(\"Macro invoke \" << mi_owned.path());\n\n            auto ttl = Expand_Macro(crate, modstack, mod, mi_owned);\n            assert( mi_owned.path().is_valid() );\n\n            if( ttl.get() )\n            {\n                \/\/ Re-parse tt\n                \/\/ TODO: All new items should be placed just after this?\n                assert(ttl.get());\n                DEBUG(\"-- Parsing as mod items\");\n                \/\/ Move the item list out\n                auto old_items = std::move(mod.m_items);\n                \/\/ Parse module items\n                Parse_ModRoot_Items(*ttl, mod);\n                auto new_item_count = mod.m_items.size();\n                \/\/ Then insert the newly created items\n                old_items.insert(old_items.begin() + idx + 1, std::make_move_iterator(mod.m_items.begin()), std::make_move_iterator(mod.m_items.end()));\n                \/\/ and move the (updated) item list back in\n                mod.m_items = std::move(old_items);\n\n                auto next_non_macro_item = idx + 1 + new_item_count;\n                macro_recursion_stack.push_back(next_non_macro_item == mod.m_items.size() ? nullptr : &*mod.m_items[next_non_macro_item]);\n            }\n            dat.as_MacroInv() = mv$(mi_owned);\n            }\n        TU_ARMA(Macro, e) {\n            mod.add_macro(i.is_pub, i.name, mv$(e));\n            }\n        TU_ARMA(Use, e) {\n            \/\/ Determine if the `use` refers to a macro, and import into the current scope\n            for(const auto& ue : e.entries)\n            {\n                \/\/ Get module ref, if it's to a HIR module then grab the macro\n                if(ue.name != \"\")\n                {\n                    DEBUG(\"Use \" << ue.path);\n\n                    auto m = Resolve_Lookup_Macro(ue.sp, crate, mod.path(), ue.path, \/*out_path=*\/nullptr);\n                    TU_MATCH_HDRA( (m), { )\n                    TU_ARMA(None, e) {\n                        \/\/ Not found? Ignore.\n                        }\n                    TU_ARMA(InternalMacro, e) {\n                        \/\/ Ignore builtins, they're always available.\n                        }\n                    TU_ARMA(ProcMacro, pm) {\n                        auto mi = AST::Module::MacroImport{ false, ue.name, pm->path.m_components, nullptr };\n                        mi.path.insert(mi.path.begin(), pm->path.m_crate_name);\n                        mod.m_macro_imports.push_back(mv$(mi));\n\n                        mod.add_macro_import(ue.sp, ue.name, pm);\n                        }\n                    TU_ARMA(MacroRules, mr) {\n                        mod.add_macro_import(ue.sp, ue.name, mr);\n                        }\n                    }\n                }\n            }\n            }\n        TU_ARMA(ExternBlock, e) {\n            \/\/ TODO: Run expand on inner items?\n            \/\/ HACK: Just convert inner items into outer items\n            auto items = mv$( e.items() );\n            for(auto& i2 : items)\n            {\n                mod.m_items.push_back( box$(i2) );\n            }\n            }\n        TU_ARMA(Impl, e) {\n            Expand_Impl(crate, modstack, modpath, mod,  e);\n            if( e.def().type().is_wildcard() ) {\n                dat = AST::Item();\n            }\n            }\n        TU_ARMA(NegImpl, e) {\n            Expand_ImplDef(crate, modstack, modpath, mod,  e);\n            if( e.type().is_wildcard() ) {\n                dat = AST::Item();\n            }\n            }\n        TU_ARMA(Module, e) {\n            throw \"\";\n            }\n        TU_ARMA(Crate, e) {\n            if( e.name != \"\" )\n            {\n                \/\/ Can't recurse into an `extern crate`\n                if(crate.m_extern_crates.count(e.name) == 0)\n                {\n                    e.name = crate.load_extern_crate( i.span, e.name );\n                }\n                \/\/ Crates imported in root are added to the implicit list\n                if( modpath.nodes.empty() )\n                {\n                    AST::g_implicit_crates.insert( std::make_pair(i.name, e.name) );\n                }\n            }\n            else {\n                if( modpath.nodes.empty() )\n                {\n                    AST::g_implicit_crates.insert( std::make_pair(i.name, \"\") );\n                }\n            }\n            }\n\n        TU_ARMA(Struct, e) {\n            Expand_GenericParams(crate, modstack, mod,  e.params());\n            TU_MATCH_HDRA( (e.m_data), {)\n            TU_ARMA(Unit, sd) {\n                }\n            TU_ARMA(Struct, sd) {\n                for(auto it = sd.ents.begin(); it != sd.ents.end(); ) {\n                    auto& si = *it;\n                    Expand_Attrs_CfgAttr(si.m_attrs);\n                    Expand_Attrs(si.m_attrs, AttrStage::Pre, [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate, si); });\n                    Expand_Type(crate, modstack, mod,  si.m_type);\n                    Expand_Attrs(si.m_attrs, AttrStage::Post, [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate, si); });\n\n                    if( si.m_name == \"\" )\n                        it = sd.ents.erase(it);\n                    else\n                        ++it;\n                }\n                }\n            TU_ARMA(Tuple, sd) {\n                for(auto it = sd.ents.begin(); it != sd.ents.end(); ) {\n                    auto& si = *it;\n                    Expand_Attrs_CfgAttr(si.m_attrs);\n                    Expand_Attrs(si.m_attrs, AttrStage::Pre, [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate, si); });\n                    Expand_Type(crate, modstack, mod,  si.m_type);\n                    Expand_Attrs(si.m_attrs, AttrStage::Post, [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate, si); });\n\n                    if( ! si.m_type.is_valid() )\n                        it = sd.ents.erase(it);\n                    else\n                        ++it;\n                }\n                }\n            }\n            }\n        TU_ARMA(Enum, e) {\n            Expand_GenericParams(crate, modstack, mod,  e.params());\n            for(auto& var : e.variants()) {\n                Expand_Attrs_CfgAttr(var.m_attrs);\n                Expand_Attrs(var.m_attrs, AttrStage::Pre,  [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate, var); });\n                TU_MATCH(::AST::EnumVariantData, (var.m_data), (e),\n                (Value,\n                    Expand_Expr(crate, modstack,  e.m_value);\n                    ),\n                (Tuple,\n                    for(auto& ty : e.m_sub_types) {\n                        Expand_Type(crate, modstack, mod,  ty);\n                    }\n                    ),\n                (Struct,\n                    for(auto it = e.m_fields.begin(); it != e.m_fields.end(); ) {\n                        auto& si = *it;\n                        Expand_Attrs_CfgAttr(si.m_attrs);\n                        Expand_Attrs(si.m_attrs, AttrStage::Pre, [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate, si); });\n                        Expand_Type(crate, modstack, mod,  si.m_type);\n                        Expand_Attrs(si.m_attrs, AttrStage::Post, [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate, si); });\n\n                        if( si.m_name == \"\" )\n                            it = e.m_fields.erase(it);\n                        else\n                            ++it;\n                    }\n                    )\n                )\n                Expand_Attrs(var.m_attrs, AttrStage::Post,  [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate, var); });\n            }\n            \/\/ Handle cfg on variants (kinda hacky)\n            for(auto it = e.variants().begin(); it != e.variants().end(); ) {\n                if( it->m_name == \"\" ) {\n                    it = e.variants().erase(it);\n                }\n                else {\n                    ++ it;\n                }\n            }\n            }\n        TU_ARMA(Union, e) {\n            Expand_GenericParams(crate, modstack, mod,  e.m_params);\n            for(auto it = e.m_variants.begin(); it != e.m_variants.end(); )\n            {\n                auto& si = *it;\n                Expand_Attrs_CfgAttr(si.m_attrs);\n                Expand_Attrs(si.m_attrs, AttrStage::Pre, [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate, si); });\n                Expand_Type(crate, modstack, mod,  si.m_type);\n                Expand_Attrs(si.m_attrs, AttrStage::Post, [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate, si); });\n\n                if( si.m_name == \"\" )\n                    it = e.m_variants.erase(it);\n                else\n                    ++it;\n            }\n            }\n        TU_ARMA(Trait, e) {\n            Expand_GenericParams(crate, modstack, mod,  e.params());\n            for(auto& p : e.supertraits())\n                Expand_Path(crate, modstack, mod, *p.ent.path);\n            auto& trait_items = e.items();\n            for(size_t idx = 0; idx < trait_items.size(); idx ++)\n            {\n                auto& ti = trait_items[idx];\n                DEBUG(\" - \" << ti.name << \" \" << ti.data.tag_str());\n                auto attrs = mv$(ti.attrs);\n                auto ti_path = path + ti.name;\n                Expand_Attrs_CfgAttr(attrs);\n                Expand_Attrs(attrs, AttrStage::Pre,  crate, ti_path, e, ti.data);\n\n                TU_MATCH_HDRA( (ti.data), {)\n                default:\n                    BUG(Span(), \"Unknown item type in trait block - \" << ti.data.tag_str());\n                TU_ARMA(None, e) {}\n                TU_ARMA(MacroInv, e) {\n                    if( e.path().is_valid() )\n                    {\n                        TRACE_FUNCTION_F(\"Macro invoke \" << e.path());\n                        \/\/ Move out of the module to avoid invalidation if a new macro invocation is added\n                        auto mi_owned = mv$(e);\n\n                        auto ttl = Expand_Macro(crate, modstack, mod, mi_owned);\n\n                        if( ttl.get() )\n                        {\n                            \/\/ Re-parse tt\n                            size_t insert_pos = idx+1;\n                            while( ttl->lookahead(0) != TOK_EOF )\n                            {\n                                auto i = Parse_Trait_Item(*ttl);\n                                trait_items.insert( trait_items.begin() + insert_pos, mv$(i) );\n                                insert_pos ++;\n                            }\n                            \/\/ - Any new macro invocations ends up at the end of the list and handled\n                        }\n                        \/\/ Move back in (using the index, as the old pointer may be invalid)\n                        trait_items[idx].data.as_MacroInv() = mv$(mi_owned);\n                    }\n                    }\n                TU_ARMA(Function, e) {\n                    Expand_GenericParams(crate, modstack, mod,  e.params());\n                    for(auto& arg : e.args()) {\n                        Expand_Pattern(crate, modstack, mod,  arg.first, false);\n                        Expand_Type(crate, modstack, mod,  arg.second);\n                    }\n                    Expand_Type(crate, modstack, mod,  e.rettype());\n                    Expand_Expr(crate, modstack, e.code());\n                    }\n                TU_ARMA(Static, e) {\n                    Expand_Expr(crate, modstack, e.value());\n                    Expand_Type(crate, modstack, mod,  e.type());\n                    }\n                TU_ARMA(Type, e) {\n                    Expand_Type(crate, modstack, mod,  e.type());\n                    }\n                }\n\n                {\n                    auto& ti = trait_items[idx];\n\n                    Expand_Attrs(attrs, AttrStage::Post,  crate, ti_path, e, ti.data);\n                    if( ti.attrs.m_items.size() == 0 )\n                        ti.attrs = mv$(attrs);\n                }\n            }\n            }\n        TU_ARMA(Type, e) {\n            Expand_Type(crate, modstack, mod,  e.type());\n            }\n\n        TU_ARMA(Function, e) {\n            Expand_GenericParams(crate, modstack, mod,  e.params());\n            for(auto& arg : e.args()) {\n                Expand_Pattern(crate, modstack, mod,  arg.first, false);\n                Expand_Type(crate, modstack, mod,  arg.second);\n            }\n            Expand_Type(crate, modstack, mod,  e.rettype());\n            Expand_Expr(crate, modstack, e.code());\n            }\n        TU_ARMA(Static, e) {\n            Expand_Expr(crate, modstack, e.value());\n            Expand_Type(crate, modstack, mod,  e.type());\n            }\n        TU_ARMA(TraitAlias, e) {\n            for(auto& p : e.traits)\n                Expand_Path(crate, modstack, mod, *p.ent.path);\n            }\n        }\n        Expand_Attrs(attrs, AttrStage::Post,  crate, path, mod, dat);\n\n        {\n\n            auto& i = *mod.m_items[idx];\n            if( i.data.tag() == ::AST::Item::TAGDEAD ) {\n                i.data = mv$(dat);\n            }\n            \/\/ TODO: When would this _not_ be empty?\n            if( i.attrs.m_items.size() == 0 )\n                i.attrs = mv$(attrs);\n        }\n    }\n\n    \/\/ IGNORE m_anon_modules, handled as part of expressions\n\n    \/\/for( const auto& mi: mod.macro_imports_res() )\n    \/\/    DEBUG(\"- Imports '\" << mi.name << \"'\");\n}\nvoid Expand_Mod_IndexAnon(::AST::Crate& crate, ::AST::Module& mod)\n{\n    TRACE_FUNCTION_F(\"mod=\" << mod.path());\n\n    for(auto& i : mod.m_items)\n    {\n        DEBUG(\"- \" << i->data.tag_str() << \" '\" << i->name << \"'\");\n        if(auto* e = i->data.opt_Module())\n        {\n            Expand_Mod_IndexAnon(crate, *e);\n\n            \/\/ TODO: Also ensure that all #[macro_export] macros end up in parent\n        }\n    }\n\n    for( auto& mp : mod.anon_mods() )\n    {\n        if( mp.unique() ) {\n            DEBUG(\"- \" << mp->path() << \" dropped due to node destruction\");\n            mp.reset();\n        }\n        else {\n            Expand_Mod_IndexAnon(crate, *mp);\n        }\n    }\n}\n\n\n\/\/\n\/\/ Expand all `cfg` attributes... mostly to find #[macro_export]\n\/\/\nvoid Expand_Mod_Early(::AST::Crate& crate, ::AST::Module& mod, std::vector<std::unique_ptr<AST::Named<AST::Item>>>& new_root_items)\n{\n    for(auto& i : mod.m_items)\n    {\n        if(const auto* mi = i->data.opt_MacroInv() )\n        {\n            if( mi->path().is_trivial() && mi->path().as_trivial() == \"macro_rules\" ) {\n                i->is_pub = true;\n                DEBUG(\"macro_rules made pub\");\n            }\n        }\n\n        Expand_Attrs_CfgAttr(i->attrs);\n        bool is_macro_export = false;\n        bool cfg_failed = false;\n        for(auto& a : i->attrs.m_items)\n        {\n            if( a.name() == \"cfg\" ) {\n                if( !check_cfg(i->span, a) ) {\n                    cfg_failed = true;\n                }\n            }\n            else if( a.name() == \"macro_export\" ) {\n                is_macro_export = true;\n            }\n            else {\n            }\n        }\n        if( cfg_failed ) {\n            i->data = ::AST::Item::make_None({});\n        }\n        else if( is_macro_export ) {\n            if( i->data.is_MacroInv() && i->data.as_MacroInv().path().is_trivial() && i->data.as_MacroInv().path().as_trivial() == \"macro_rules\" )\n            {\n                const auto& mac_inv = i->data.as_MacroInv();\n                DEBUG(\"macro_rules marked with #[macro_export] moved to the crate root - \" << mac_inv.input_ident());\n                new_root_items.push_back(box$(*i));\n                i->data = AST::Item();\n\n#if 0\n                TTStream    lex(i->span, ParseState(crate.m_edition), mac_inv.input_tt());\n                auto mac = Parse_MacroRules(lex);\n                const auto* mac_ptr = &*mac;\n                crate.m_root_module.add_macro(true, mac_inv.input_ident(), std::move(mac));\n                crate.m_exported_macros[mac_inv.input_ident()] = mac_ptr;\n#else\n#endif\n            }\n            else if( i->data.is_Macro() )\n            {\n                \/\/ TODO: `#[macro_export] macro foo { ... }` DOESN'T move the item to the root\n                \/\/ - Instead, it should add an alias? Or just tag for export\n                i->data.as_Macro()->m_exported = true;\n            }\n            else\n            {\n                ERROR(i->span, E0000, \"#[macro_export] on non-macro_rules - \" << i->data.tag_str());\n            }\n        }\n        else if( i->data.is_Module() ) {\n            Expand_Mod_Early(crate, i->data.as_Module(), new_root_items);\n        }\n        else {\n        }\n    }\n}\n\nvoid Expand(::AST::Crate& crate)\n{\n    for(const auto& e : g_decorators)\n    {\n        DEBUG(\"Decorator: \" << e.first);\n    }\n    for(const auto& e : g_macros)\n    {\n        DEBUG(\"Macro: \" << e.first);\n    }\n\n    auto modstack = LList<const ::AST::Module*>(nullptr, &crate.m_root_module);\n\n\n    \/\/ 1. Crate attributes\n    Expand_Attrs_CfgAttr(crate.m_attrs);\n    Expand_Attrs(crate.m_attrs, AttrStage::Pre,  [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate); });\n\n    std::vector<std::unique_ptr<AST::Named<AST::Item>>> new_root_items;\n    Expand_Mod_Early(crate, crate.m_root_module, new_root_items);\n    crate.m_root_module.m_items.insert( crate.m_root_module.m_items.begin(),\n        std::make_move_iterator(new_root_items.begin()), std::make_move_iterator(new_root_items.end()) );\n\n    \/\/ Insert magic for libstd\/libcore\n    \/\/ NOTE: The actual crates are loaded in \"LoadCrates\" using magic in AST::Crate::load_externs\n    RcString std_crate_shortname;\n    RcString std_crate_name;\n    switch( crate.m_load_std )\n    {\n    case ::AST::Crate::LOAD_STD:\n        std_crate_shortname = \"std\";\n        std_crate_name = crate.m_ext_cratename_std;\n        break;\n    case ::AST::Crate::LOAD_CORE:\n        std_crate_shortname = \"core\";\n        std_crate_name = crate.m_ext_cratename_core;\n        break;\n    case ::AST::Crate::LOAD_NONE:\n        break;\n    }\n    if(std_crate_shortname != \"\")\n    {\n        ASSERT_BUG(Span(), std_crate_name != \"\", \"`\" << std_crate_shortname << \"` not loaded?\");\n        if( crate.m_prelude_path == AST::Path() )\n        {\n            crate.m_prelude_path = AST::Path(std_crate_name, {AST::PathNode(\"prelude\"), AST::PathNode(\"v1\")});\n        }\n        AST::AttributeList  attrs;\n        AST::AttributeName  name;\n        name.elems.push_back(\"macro_use\");\n        attrs.push_back( AST::Attribute(Span(), mv$(name), {}) );\n        crate.m_root_module.m_items.insert(\n            crate.m_root_module.m_items.begin(),\n            box$( AST::Named<AST::Item>(Span(), mv$(attrs), false, std_crate_shortname, AST::Item::make_Crate({std_crate_name}) ) )\n            );\n    }\n\n    \/\/ 2. Module attributes\n    for( auto& a : crate.m_attrs.m_items )\n    {\n        for( auto& d : g_decorators ) {\n            if( a.name() == d.first && d.second->stage() == AttrStage::Pre ) {\n                \/\/d.second->handle(a, crate, ::AST::Path(), crate.m_root_module, crate.m_root_module);\n            }\n        }\n    }\n\n    \/\/ 3. Module tree\n    Expand_Mod(crate, modstack, ::AST::AbsolutePath(), crate.m_root_module);\n\n    \/\/Expand_Attrs(crate.m_attrs, AttrStage::Post,  [&](const auto& sp, const auto& d, const auto& a){ d.handle(sp, a, crate); });\n\n    \/\/ Post-process\n    Expand_Mod_IndexAnon(crate, crate.m_root_module);\n\n    \/\/ Extract exported macros\n\n    {\n        auto& exported_macros = crate.m_exported_macros;\n\n        ::std::vector< ::AST::Module*>    mods;\n        mods.push_back( &crate.m_root_module );\n        do\n        {\n            auto& mod = *mods.back();\n            mods.pop_back();\n\n            for( \/*const*\/ auto& mac : mod.macros() ) {\n                if( mac.data->m_exported ) {\n                    auto res = exported_macros.insert( ::std::make_pair(mac.name,  &*mac.data) );\n                    if( res.second )\n                        DEBUG(\"- Define \" << mac.name << \"!\");\n                }\n                else {\n                    DEBUG(\"- Non-exported \" << mac.name << \"!\");\n                }\n            }\n\n            for(auto& i : mod.m_items) {\n                if( i->data.is_Module() )\n                    mods.push_back( &i->data.as_Module() );\n            }\n        } while( mods.size() > 0 );\n\n        \/\/ - Exported macros imported by the root (is this needed?)\n        for( auto& mac : crate.m_root_module.macro_imports_res() )\n        {\n            if( mac.data.is_MacroRules() && mac.data.as_MacroRules()->m_exported && mac.name != \"\" ) {\n                auto v = ::std::make_pair( mac.name, mac.data.as_MacroRules() );\n                auto it = exported_macros.find(mac.name);\n                if( it == exported_macros.end() )\n                {\n                    auto res = exported_macros.insert( mv$(v) );\n                    DEBUG(\"- Import \" << mac.name << \"! (from \\\"\" << res.first->second->m_source_crate << \"\\\")\");\n                }\n                else if( v.second->m_rules.empty() ) {\n                    \/\/ Skip\n                }\n                else {\n                    DEBUG(\"- Replace \" << mac.name << \"! (from \\\"\" << it->second->m_source_crate << \"\\\") with one from \\\"\" << v.second->m_source_crate << \"\\\"\");\n                    it->second = mv$( v.second );\n                }\n            }\n        }\n        \/\/ - Re-exported macros (ignore proc macros for now?)\n        for( const auto& mac : crate.m_root_module.m_macro_imports )\n        {\n            if( mac.is_pub )\n            {\n                if( !mac.macro_ptr ) {\n                    continue ;\n                }\n                auto v = ::std::make_pair( mac.name, mac.macro_ptr );\n\n                auto it = exported_macros.find(mac.name);\n                if( it == exported_macros.end() )\n                {\n                    auto res = exported_macros.insert( mv$(v) );\n                    DEBUG(\"- Import \" << mac.name << \"! (from \\\"\" << res.first->second->m_source_crate << \"\\\")\");\n                }\n                else if( v.second->m_rules.empty() ) {\n                    \/\/ Skip\n                }\n                else {\n                    DEBUG(\"- Replace \" << mac.name << \"! (from \\\"\" << it->second->m_source_crate << \"\\\") with one from \\\"\" << v.second->m_source_crate << \"\\\"\");\n                    it->second = mv$( v.second );\n                }\n            }\n        }\n    }\n}\n\n\n","avg_line_length":39.9720386375,"max_line_length":199,"alphanum_fraction":0.5164896661,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":18895,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":4.0,"content":"\/\/ Copyright (c) 2012-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"rpc\/server.h\"\n#include \"rpc\/client.h\"\n\n#include \"base58.h\"\n#include \"netbase.h\"\n\n#include \"test\/test_ruxcrypto.h\"\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/assign\/list_of.hpp>\n#include <boost\/test\/unit_test.hpp>\n\n#include <univalue.h>\n\nUniValue CallRPC(std::string args)\n{\n    std::vector<std::string> vArgs;\n    boost::split(vArgs, args, boost::is_any_of(\" \\t\"));\n    std::string strMethod = vArgs[0];\n    vArgs.erase(vArgs.begin());\n    JSONRPCRequest request;\n    request.strMethod = strMethod;\n    request.params = RPCConvertValues(strMethod, vArgs);\n    request.fHelp = false;\n    BOOST_CHECK(tableRPC[strMethod]);\n    rpcfn_type method = tableRPC[strMethod]->actor;\n    try {\n        UniValue result = (*method)(request);\n        return result;\n    }\n    catch (const UniValue& objError) {\n        throw std::runtime_error(find_value(objError, \"message\").get_str());\n    }\n}\n\n\nBOOST_FIXTURE_TEST_SUITE(rpc_tests, TestingSetup)\n\nBOOST_AUTO_TEST_CASE(rpc_rawparams)\n{\n    \/\/ Test raw transaction API argument handling\n    UniValue r;\n\n    BOOST_CHECK_THROW(CallRPC(\"getrawtransaction\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(\"getrawtransaction not_hex\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(\"getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int\"), std::runtime_error);\n\n    BOOST_CHECK_THROW(CallRPC(\"createrawtransaction\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(\"createrawtransaction null null\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(\"createrawtransaction not_array\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] []\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(\"createrawtransaction {} {}\"), std::runtime_error);\n    BOOST_CHECK_NO_THROW(CallRPC(\"createrawtransaction [] {}\"));\n    BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] {} extra\"), std::runtime_error);\n\n    BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction null\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction DEADBEEF\"), std::runtime_error);\n    std::string rawtx = \"0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000\";\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"decoderawtransaction \")+rawtx));\n    BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"size\").get_int(), 193);\n    BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"version\").get_int(), 1);\n    BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"locktime\").get_int(), 0);\n    BOOST_CHECK_THROW(r = CallRPC(std::string(\"decoderawtransaction \")+rawtx+\" extra\"), std::runtime_error);\n\n    BOOST_CHECK_THROW(CallRPC(\"signrawtransaction\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(\"signrawtransaction null\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(\"signrawtransaction ff00\"), std::runtime_error);\n    BOOST_CHECK_NO_THROW(CallRPC(std::string(\"signrawtransaction \")+rawtx));\n    BOOST_CHECK_NO_THROW(CallRPC(std::string(\"signrawtransaction \")+rawtx+\" null null NONE|ANYONECANPAY\"));\n    BOOST_CHECK_NO_THROW(CallRPC(std::string(\"signrawtransaction \")+rawtx+\" [] [] NONE|ANYONECANPAY\"));\n    BOOST_CHECK_THROW(CallRPC(std::string(\"signrawtransaction \")+rawtx+\" null null badenum\"), std::runtime_error);\n\n    \/\/ Only check failure cases for sendrawtransaction, there's no network to send to...\n    BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction null\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction DEADBEEF\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(std::string(\"sendrawtransaction \")+rawtx+\" extra\"), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_togglenetwork)\n{\n    UniValue r;\n\n    r = CallRPC(\"getnetworkinfo\");\n    bool netState = find_value(r.get_obj(), \"networkactive\").get_bool();\n    BOOST_CHECK_EQUAL(netState, true);\n\n    BOOST_CHECK_NO_THROW(CallRPC(\"setnetworkactive false\"));\n    r = CallRPC(\"getnetworkinfo\");\n    int numConnection = find_value(r.get_obj(), \"connections\").get_int();\n    BOOST_CHECK_EQUAL(numConnection, 0);\n\n    netState = find_value(r.get_obj(), \"networkactive\").get_bool();\n    BOOST_CHECK_EQUAL(netState, false);\n\n    BOOST_CHECK_NO_THROW(CallRPC(\"setnetworkactive true\"));\n    r = CallRPC(\"getnetworkinfo\");\n    netState = find_value(r.get_obj(), \"networkactive\").get_bool();\n    BOOST_CHECK_EQUAL(netState, true);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_rawsign)\n{\n    UniValue r;\n    \/\/ input is a 1-of-2 multisig (so is output):\n    std::string prevout =\n      \"[{\\\"txid\\\":\\\"b4cc287e58f87cdae59417329f710f3ecd75a4ee1d2872b7248f50977c8493f3\\\",\"\n      \"\\\"vout\\\":1,\\\"scriptPubKey\\\":\\\"a914b10c9df5f7edf436c697f02f1efdba4cf399615187\\\",\"\n      \"\\\"redeemScript\\\":\\\"512103debedc17b3df2badbcdd86d5feb4562b86fe182e5998abd8bcd4f122c6155b1b21027e940bb73ab8732bfdf7f9216ecefca5b94d6df834e77e108f68e66f126044c052ae\\\"}]\";\n    r = CallRPC(std::string(\"createrawtransaction \")+prevout+\" \"+\n      \"{\\\"7iYoULd4BAqRsRt1UbD5qqna88JvKRU3SL\\\":11}\");\n    std::string notsigned = r.get_str();\n    std::string privkey1 = \"\\\"XEwTRsCX3CiWSQf8YmKMTeb84KyTbibkUv9mDTZHQ5MwuKG2ZzES\\\"\";\n    std::string privkey2 = \"\\\"XDmZ7LjGd94Q81eUBjb2h6uV5Y14s7fmeXWEGYabfBJP8RVpprBu\\\"\";\n    r = CallRPC(std::string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[]\");\n    BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == false);\n    r = CallRPC(std::string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[\"+privkey1+\",\"+privkey2+\"]\");\n    BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == true);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_createraw_op_return)\n{\n    BOOST_CHECK_NO_THROW(CallRPC(\"createrawtransaction [{\\\"txid\\\":\\\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\\\",\\\"vout\\\":0}] {\\\"data\\\":\\\"68656c6c6f776f726c64\\\"}\"));\n\n    \/\/ Allow more than one data transaction output\n    BOOST_CHECK_NO_THROW(CallRPC(\"createrawtransaction [{\\\"txid\\\":\\\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\\\",\\\"vout\\\":0}] {\\\"data\\\":\\\"68656c6c6f776f726c64\\\",\\\"data\\\":\\\"68656c6c6f776f726c64\\\"}\"));\n\n    \/\/ Key not \"data\" (bad address)\n    BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [{\\\"txid\\\":\\\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\\\",\\\"vout\\\":0}] {\\\"somedata\\\":\\\"68656c6c6f776f726c64\\\"}\"), std::runtime_error);\n\n    \/\/ Bad hex encoding of data output\n    BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [{\\\"txid\\\":\\\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\\\",\\\"vout\\\":0}] {\\\"data\\\":\\\"12345\\\"}\"), std::runtime_error);\n    BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [{\\\"txid\\\":\\\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\\\",\\\"vout\\\":0}] {\\\"data\\\":\\\"12345g\\\"}\"), std::runtime_error);\n\n    \/\/ Data 81 bytes long\n    BOOST_CHECK_NO_THROW(CallRPC(\"createrawtransaction [{\\\"txid\\\":\\\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\\\",\\\"vout\\\":0}] {\\\"data\\\":\\\"010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081\\\"}\"));\n}\n\nBOOST_AUTO_TEST_CASE(rpc_format_monetary_values)\n{\n    BOOST_CHECK(ValueFromAmount(0LL).write() == \"0.00000000\");\n    BOOST_CHECK(ValueFromAmount(1LL).write() == \"0.00000001\");\n    BOOST_CHECK(ValueFromAmount(17622195LL).write() == \"0.17622195\");\n    BOOST_CHECK(ValueFromAmount(50000000LL).write() == \"0.50000000\");\n    BOOST_CHECK(ValueFromAmount(89898989LL).write() == \"0.89898989\");\n    BOOST_CHECK(ValueFromAmount(100000000LL).write() == \"1.00000000\");\n    BOOST_CHECK(ValueFromAmount(2099999999999990LL).write() == \"20999999.99999990\");\n    BOOST_CHECK(ValueFromAmount(2099999999999999LL).write() == \"20999999.99999999\");\n\n    BOOST_CHECK_EQUAL(ValueFromAmount(0).write(), \"0.00000000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount((COIN\/10000)*123456789).write(), \"12345.67890000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(-COIN).write(), \"-1.00000000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(-COIN\/10).write(), \"-0.10000000\");\n\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100000000).write(), \"100000000.00000000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10000000).write(), \"10000000.00000000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN*1000000).write(), \"1000000.00000000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100000).write(), \"100000.00000000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10000).write(), \"10000.00000000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN*1000).write(), \"1000.00000000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100).write(), \"100.00000000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10).write(), \"10.00000000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN).write(), \"1.00000000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN\/10).write(), \"0.10000000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN\/100).write(), \"0.01000000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN\/1000).write(), \"0.00100000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN\/10000).write(), \"0.00010000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN\/100000).write(), \"0.00001000\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN\/1000000).write(), \"0.00000100\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN\/10000000).write(), \"0.00000010\");\n    BOOST_CHECK_EQUAL(ValueFromAmount(COIN\/100000000).write(), \"0.00000001\");\n}\n\nstatic UniValue ValueFromString(const std::string &str)\n{\n    UniValue value;\n    BOOST_CHECK(value.setNumStr(str));\n    return value;\n}\n\nBOOST_AUTO_TEST_CASE(rpc_parse_monetary_values)\n{\n    BOOST_CHECK_THROW(AmountFromValue(ValueFromString(\"-0.00000001\")), UniValue);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0\")), 0LL);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.00000000\")), 0LL);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.00000001\")), 1LL);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.17622195\")), 17622195LL);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.5\")), 50000000LL);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.50000000\")), 50000000LL);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.89898989\")), 89898989LL);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"1.00000000\")), 100000000LL);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"20999999.9999999\")), 2099999999999990LL);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"20999999.99999999\")), 2099999999999999LL);\n\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"1e-8\")), COIN\/100000000);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.1e-7\")), COIN\/100000000);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.01e-6\")), COIN\/100000000);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.0000000000000000000000000000000000000000000000000000000000000000000000000001e+68\")), COIN\/100000000);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"10000000000000000000000000000000000000000000000000000000000000000e-64\")), COIN);\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000e64\")), COIN);\n\n    BOOST_CHECK_THROW(AmountFromValue(ValueFromString(\"1e-9\")), UniValue); \/\/should fail\n    BOOST_CHECK_THROW(AmountFromValue(ValueFromString(\"0.000000019\")), UniValue); \/\/should fail\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.00000001000000\")), 1LL); \/\/should pass, cut trailing 0\n    BOOST_CHECK_THROW(AmountFromValue(ValueFromString(\"19e-9\")), UniValue); \/\/should fail\n    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.19e-6\")), 19); \/\/should pass, leading 0 is present\n\n    BOOST_CHECK_THROW(AmountFromValue(ValueFromString(\"92233720368.54775808\")), UniValue); \/\/overflow error\n    BOOST_CHECK_THROW(AmountFromValue(ValueFromString(\"1e+11\")), UniValue); \/\/overflow error\n    BOOST_CHECK_THROW(AmountFromValue(ValueFromString(\"1e11\")), UniValue); \/\/overflow error signless\n    BOOST_CHECK_THROW(AmountFromValue(ValueFromString(\"93e+9\")), UniValue); \/\/overflow error\n}\n\nBOOST_AUTO_TEST_CASE(json_parse_errors)\n{\n    \/\/ Valid\n    BOOST_CHECK_EQUAL(ParseNonRFCJSONValue(\"1.0\").get_real(), 1.0);\n    \/\/ Valid, with leading or trailing whitespace\n    BOOST_CHECK_EQUAL(ParseNonRFCJSONValue(\" 1.0\").get_real(), 1.0);\n    BOOST_CHECK_EQUAL(ParseNonRFCJSONValue(\"1.0 \").get_real(), 1.0);\n\n    BOOST_CHECK_THROW(AmountFromValue(ParseNonRFCJSONValue(\".19e-6\")), std::runtime_error); \/\/should fail, missing leading 0, therefore invalid JSON\n    BOOST_CHECK_EQUAL(AmountFromValue(ParseNonRFCJSONValue(\"0.00000000000000000000000000000000000001e+30 \")), 1);\n    \/\/ Invalid, initial garbage\n    BOOST_CHECK_THROW(ParseNonRFCJSONValue(\"[1.0\"), std::runtime_error);\n    BOOST_CHECK_THROW(ParseNonRFCJSONValue(\"a1.0\"), std::runtime_error);\n    \/\/ Invalid, trailing garbage\n    BOOST_CHECK_THROW(ParseNonRFCJSONValue(\"1.0sds\"), std::runtime_error);\n    BOOST_CHECK_THROW(ParseNonRFCJSONValue(\"1.0]\"), std::runtime_error);\n    \/\/ BTC addresses should fail parsing\n    BOOST_CHECK_THROW(ParseNonRFCJSONValue(\"175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W\"), std::runtime_error);\n    BOOST_CHECK_THROW(ParseNonRFCJSONValue(\"3J98t1WpEZ73CNmQviecrnyiWrnqRhWNL\"), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_ban)\n{\n    BOOST_CHECK_NO_THROW(CallRPC(std::string(\"clearbanned\")));\n\n    UniValue r;\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"setban 127.0.0.0 add\")));\n    BOOST_CHECK_THROW(r = CallRPC(std::string(\"setban 127.0.0.0:8334\")), std::runtime_error); \/\/portnumber for setban not allowed\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"listbanned\")));\n    UniValue ar = r.get_array();\n    UniValue o1 = ar[0].get_obj();\n    UniValue adr = find_value(o1, \"address\");\n    BOOST_CHECK_EQUAL(adr.get_str(), \"127.0.0.0\/32\");\n    BOOST_CHECK_NO_THROW(CallRPC(std::string(\"setban 127.0.0.0 remove\")));\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"listbanned\")));\n    ar = r.get_array();\n    BOOST_CHECK_EQUAL(ar.size(), 0);\n\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"setban 127.0.0.0\/24 add 1607731200 true\")));\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"listbanned\")));\n    ar = r.get_array();\n    o1 = ar[0].get_obj();\n    adr = find_value(o1, \"address\");\n    UniValue banned_until = find_value(o1, \"banned_until\");\n    BOOST_CHECK_EQUAL(adr.get_str(), \"127.0.0.0\/24\");\n    BOOST_CHECK_EQUAL(banned_until.get_int64(), 1607731200); \/\/ absolute time check\n\n    BOOST_CHECK_NO_THROW(CallRPC(std::string(\"clearbanned\")));\n\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"setban 127.0.0.0\/24 add 200\")));\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"listbanned\")));\n    ar = r.get_array();\n    o1 = ar[0].get_obj();\n    adr = find_value(o1, \"address\");\n    banned_until = find_value(o1, \"banned_until\");\n    BOOST_CHECK_EQUAL(adr.get_str(), \"127.0.0.0\/24\");\n    int64_t now = GetTime();\n    BOOST_CHECK(banned_until.get_int64() > now);\n    BOOST_CHECK(banned_until.get_int64()-now <= 200);\n\n    \/\/ must throw an exception because 127.0.0.1 is in already banned suubnet range\n    BOOST_CHECK_THROW(r = CallRPC(std::string(\"setban 127.0.0.1 add\")), std::runtime_error);\n\n    BOOST_CHECK_NO_THROW(CallRPC(std::string(\"setban 127.0.0.0\/24 remove\")));\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"listbanned\")));\n    ar = r.get_array();\n    BOOST_CHECK_EQUAL(ar.size(), 0);\n\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"setban 127.0.0.0\/255.255.0.0 add\")));\n    BOOST_CHECK_THROW(r = CallRPC(std::string(\"setban 127.0.1.1 add\")), std::runtime_error);\n\n    BOOST_CHECK_NO_THROW(CallRPC(std::string(\"clearbanned\")));\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"listbanned\")));\n    ar = r.get_array();\n    BOOST_CHECK_EQUAL(ar.size(), 0);\n\n\n    BOOST_CHECK_THROW(r = CallRPC(std::string(\"setban test add\")), std::runtime_error); \/\/invalid IP\n\n    \/\/IPv6 tests\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"setban FE80:0000:0000:0000:0202:B3FF:FE1E:8329 add\")));\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"listbanned\")));\n    ar = r.get_array();\n    o1 = ar[0].get_obj();\n    adr = find_value(o1, \"address\");\n    BOOST_CHECK_EQUAL(adr.get_str(), \"fe80::202:b3ff:fe1e:8329\/128\");\n\n    BOOST_CHECK_NO_THROW(CallRPC(std::string(\"clearbanned\")));\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"setban 2001:db8::\/ffff:fffc:0:0:0:0:0:0 add\")));\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"listbanned\")));\n    ar = r.get_array();\n    o1 = ar[0].get_obj();\n    adr = find_value(o1, \"address\");\n    BOOST_CHECK_EQUAL(adr.get_str(), \"2001:db8::\/30\");\n\n    BOOST_CHECK_NO_THROW(CallRPC(std::string(\"clearbanned\")));\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"setban 2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63\/128 add\")));\n    BOOST_CHECK_NO_THROW(r = CallRPC(std::string(\"listbanned\")));\n    ar = r.get_array();\n    o1 = ar[0].get_obj();\n    adr = find_value(o1, \"address\");\n    BOOST_CHECK_EQUAL(adr.get_str(), \"2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63\/128\");\n}\n\n#if ENABLE_MINER\nBOOST_AUTO_TEST_CASE(rpc_convert_values_generatetoaddress)\n{\n    UniValue result;\n\n    BOOST_CHECK_NO_THROW(result = RPCConvertValues(\"generatetoaddress\", boost::assign::list_of(\"101\")(\"yhq7ifNCtTKEpY4Yu5XPCcztQco6Fh6JsZ\")));\n    BOOST_CHECK_EQUAL(result[0].get_int(), 101);\n    BOOST_CHECK_EQUAL(result[1].get_str(), \"yhq7ifNCtTKEpY4Yu5XPCcztQco6Fh6JsZ\");\n\n    BOOST_CHECK_NO_THROW(result = RPCConvertValues(\"generatetoaddress\", boost::assign::list_of(\"101\")(\"yTretFTpoi3oQ3maZk5QadGaDWPiKnmDBc\")));\n    BOOST_CHECK_EQUAL(result[0].get_int(), 101);\n    BOOST_CHECK_EQUAL(result[1].get_str(), \"yTretFTpoi3oQ3maZk5QadGaDWPiKnmDBc\");\n\n    BOOST_CHECK_NO_THROW(result = RPCConvertValues(\"generatetoaddress\", boost::assign::list_of(\"1\")(\"yNbNZyCiTYSFtDwEXt7jChV7tZVYX862ua\")(\"9\")));\n    BOOST_CHECK_EQUAL(result[0].get_int(), 1);\n    BOOST_CHECK_EQUAL(result[1].get_str(), \"yNbNZyCiTYSFtDwEXt7jChV7tZVYX862ua\");\n    BOOST_CHECK_EQUAL(result[2].get_int(), 9);\n\n    BOOST_CHECK_NO_THROW(result = RPCConvertValues(\"generatetoaddress\", boost::assign::list_of(\"1\")(\"yTG8jLL3MvteKXgbEcHyaN7JvTPCejQpSh\")(\"9\")));\n    BOOST_CHECK_EQUAL(result[0].get_int(), 1);\n    BOOST_CHECK_EQUAL(result[1].get_str(), \"yTG8jLL3MvteKXgbEcHyaN7JvTPCejQpSh\");\n    BOOST_CHECK_EQUAL(result[2].get_int(), 9);\n}\n#endif \/\/ ENABLE_MINER\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":54.1404011461,"max_line_length":413,"alphanum_fraction":0.7463879333,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4200,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Intel"],"max_stars_count":38.0,"content":"#include \"StdAfx.h\"\n#include \"BSCyclicBlendTransitionGenerator_1.h\"\n\n#include <Common\/Serialize\/hkSerialize.h>\n#include <Common\/Serialize\/Util\/hkSerializeUtil.h>\n#include <Common\/Serialize\/Version\/hkVersionPatchManager.h>\n#include <Common\/Serialize\/Data\/Dict\/hkDataObjectDict.h>\n#include <Common\/Serialize\/Data\/Native\/hkDataObjectNative.h>\n#include <Common\/Serialize\/Data\/Util\/hkDataObjectUtil.h>\n#include <Common\/Base\/Reflection\/Registry\/hkDynamicClassNameRegistry.h>\n#include <Common\/Base\/Reflection\/Registry\/hkVtableClassRegistry.h>\n#include <Common\/Base\/Reflection\/hkClass.h>\n#include <Common\/Base\/Reflection\/hkInternalClassMember.h>\n#include <Common\/Serialize\/Util\/hkSerializationCheckingUtils.h>\n#include <Common\/Serialize\/Util\/hkVersionCheckingUtils.h>\n\n\nstatic const hkInternalClassEnumItem CurrentBlendModeEnumItems[] =\n{\n   {-1, \"MODE_INACTIVE\"},\n   {0, \"MODE_DEFAULT\"},\n   {1, \"MODE_FROZEN\"},\n   {2, \"MODE_BLENDING\"},\n   {3, \"MODE_WAITINGFORBLENDING\"},\n};\n\nstatic const hkInternalClassEnum BSCyclicBlendTransitionGeneratorClass_Enums[] = {\n   {\"CurrentBlendMode\", CurrentBlendModeEnumItems, _countof(CurrentBlendModeEnumItems), HK_NULL, 0 },\n};\nconst hkClassEnum* CurrentBlendModeEnum = reinterpret_cast<const hkClassEnum*>(&BSCyclicBlendTransitionGeneratorClass_Enums[0]);\nextern const hkClassEnum* BlendCurveEnum;\n\nstatic const hkInternalClassMember BSCyclicBlendTransitionGeneratorClass_Members[] =\n{\n   { \"pBlenderGenerator\",&hkbGeneratorClass,HK_NULL,hkClassMember::TYPE_POINTER,hkClassMember::TYPE_STRUCT,0,hkClassMember::ALIGN_16,HK_OFFSET_OF(BSCyclicBlendTransitionGenerator,m_pBlenderGenerator) \/*48*\/,HK_NULL},\n   { \"EventToFreezeBlendValue\",&hkbEventPropertyClass,HK_NULL,hkClassMember::TYPE_STRUCT,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSCyclicBlendTransitionGenerator,m_EventToFreezeBlendValue) \/*52*\/,HK_NULL},\n   { \"EventToCrossBlend\",&hkbEventPropertyClass,HK_NULL,hkClassMember::TYPE_STRUCT,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSCyclicBlendTransitionGenerator,m_EventToCrossBlend) \/*60*\/,HK_NULL},\n   { \"fBlendParameter\",HK_NULL,HK_NULL,hkClassMember::TYPE_REAL,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSCyclicBlendTransitionGenerator,m_fBlendParameter) \/*68*\/,HK_NULL},\n   { \"fTransitionDuration\",HK_NULL,HK_NULL,hkClassMember::TYPE_REAL,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSCyclicBlendTransitionGenerator,m_fTransitionDuration) \/*72*\/,HK_NULL},\n   { \"eBlendCurve\",HK_NULL,BlendCurveEnum,hkClassMember::TYPE_ENUM,hkClassMember::TYPE_INT8,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSCyclicBlendTransitionGenerator,m_eBlendCurve) \/*76*\/,HK_NULL},\n   { \"pTransitionBlenderGenerator\",HK_NULL,HK_NULL,hkClassMember::TYPE_POINTER,hkClassMember::TYPE_VOID,0,hkClassMember::ALIGN_16 | hkClassMember::SERIALIZE_IGNORED,HK_OFFSET_OF(BSCyclicBlendTransitionGenerator,m_pTransitionBlenderGenerator) \/*80*\/,HK_NULL},\n   { \"pTransitionEffect\",HK_NULL,HK_NULL,hkClassMember::TYPE_POINTER,hkClassMember::TYPE_VOID,0,hkClassMember::ALIGN_16 | hkClassMember::SERIALIZE_IGNORED,HK_OFFSET_OF(BSCyclicBlendTransitionGenerator,m_pTransitionEffect) \/*96*\/,HK_NULL},\n   { \"currentMode\",HK_NULL,HK_NULL,hkClassMember::TYPE_ENUM,hkClassMember::TYPE_INT8,0,hkClassMember::SERIALIZE_IGNORED,HK_OFFSET_OF(BSCyclicBlendTransitionGenerator,m_currentMode) \/*100*\/,HK_NULL},\n};\n\n\/\/ Signature:  5119eb06\nextern const hkClass hkbGeneratorClass;\nextern const hkClass BSCyclicBlendTransitionGeneratorClass;\nconst hkClass BSCyclicBlendTransitionGeneratorClass(\n    \"BSCyclicBlendTransitionGenerator\",\n    &hkbGeneratorClass, \/\/ parent\n    sizeof(BSCyclicBlendTransitionGenerator),\n    HK_NULL, 0, \/\/ interfaces\n    reinterpret_cast<const hkClassEnum*>(BSCyclicBlendTransitionGeneratorClass_Enums), HK_COUNT_OF(BSCyclicBlendTransitionGeneratorClass_Enums),\n    reinterpret_cast<const hkClassMember*>(BSCyclicBlendTransitionGeneratorClass_Members), HK_COUNT_OF(BSCyclicBlendTransitionGeneratorClass_Members),\n    HK_NULL, \/\/ defaults\n    HK_NULL, \/\/ attributes\n    0, \/\/ flags\n    1 \/\/ version\n );\nHK_REFLECTION_DEFINE_VIRTUAL(BSCyclicBlendTransitionGenerator, BSCyclicBlendTransitionGenerator);\n\n","avg_line_length":66.6666666667,"max_line_length":258,"alphanum_fraction":0.8307142857,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4492,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":4.0,"content":"\/*\n * Copyright (C) 2007 Tommi Maekitalo\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * As a special exception, you may use this file as part of a free\n * software library without restriction. Specifically, if other files\n * instantiate templates or use macros or inline functions from this\n * file, or you compile this file and link it with other files to\n * produce an executable, this file does not by itself cause the\n * resulting executable to be covered by the GNU General Public\n * License. This exception does not however invalidate any other\n * reasons why the executable file might be covered by the GNU Library\n * General Public License.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n\n#include <cxxtools\/posix\/pipestream.h>\n#include <cxxtools\/systemerror.h>\n#include <algorithm>\n#include <unistd.h>\n#include <cxxtools\/log.h>\n#include <cstring>\n#include <errno.h>\n#include <unistd.h>\n#include <fcntl.h>\n\nlog_define(\"cxxtools.pipestream\")\n\nnamespace cxxtools\n{\nnamespace posix\n{\n  Pipestreambuf::Pipestreambuf(unsigned bufsize_)\n    : bufsize(bufsize_),\n      ibuffer(0),\n      obuffer(0)\n  { }\n\n  Pipestreambuf::~Pipestreambuf()\n  {\n    log_debug(\"Pipestreambuf::~Pipestreambuf()\");\n\n    try\n    {\n      closeReadFd();\n    }\n    catch (const std::exception& e)\n    {\n      log_debug(\"ignore exception in closing read pipe: \" << e.what());\n    }\n\n    try\n    {\n      closeWriteFd();\n    }\n    catch (const std::exception& e)\n    {\n      log_debug(\"ignore exception in closing write pipe: \" << e.what());\n    }\n\n    delete [] ibuffer;\n    delete [] obuffer;\n  }\n\n  std::streambuf::int_type Pipestreambuf::overflow(std::streambuf::int_type ch)\n  {\n    log_debug(\"overflow(\" << ch << ')');\n\n    if (pptr() != pbase())\n    {\n      log_debug(\"write \" << (pptr() - pbase()) << \" bytes to fd \" << getWriteFd());\n      ssize_t ret = ::write(getWriteFd(), pbase(), pptr() - pbase());\n\n      if(ret < 0)\n        throw SystemError(errno, \"write\");\n\n      if (ret == 0)\n        return traits_type::eof();\n      else\n      {\n        log_debug(ret << \" bytes written to fd \" << getWriteFd());\n        if (static_cast<unsigned>(ret) < bufsize)\n          std::memmove(obuffer, obuffer + ret, bufsize - ret);\n        setp(obuffer, obuffer + bufsize);\n        pbump(bufsize - ret);\n      }\n    }\n    else\n    {\n      log_debug(\"initialize outputbuffer\");\n      if (obuffer == 0)\n      {\n        log_debug(\"allocate \" << bufsize << \" bytes output buffer\");\n        obuffer = new char[bufsize];\n      }\n\n      setp(obuffer, obuffer + bufsize);\n    }\n\n    if (ch != traits_type::eof())\n    {\n      *pptr() = traits_type::to_char_type(ch);\n      pbump(1);\n    }\n\n    return 0;\n  }\n\n  std::streambuf::int_type Pipestreambuf::underflow()\n  {\n    log_debug(\"underflow()\");\n\n    if (ibuffer == 0)\n    {\n      log_debug(\"allocate \" << bufsize << \" bytes input buffer\");\n      ibuffer = new char[bufsize];\n    }\n\n    log_debug(\"read from fd \" << getReadFd());\n    int ret = ::read(getReadFd(), ibuffer, bufsize);\n    log_debug(\"read returned \" << ret);\n\n    if(ret < 0)\n      throw SystemError(errno, \"read\");\n\n    if (ret == 0)\n      return traits_type::eof();\n\n    log_debug(ret << \" bytes read\");\n    setg(ibuffer, ibuffer, ibuffer + ret);\n\n    return *gptr();\n  }\n\n  int Pipestreambuf::sync()\n  {\n    log_debug(\"sync()\");\n    if (pptr() != pbase())\n    {\n      char* p = pbase();\n      while (p < pptr())\n      {\n        log_debug(\"write \" << (pptr() - p) << \" bytes to fd \" << getWriteFd());\n        ssize_t ret = ::write(getWriteFd(), p, pptr() - p);\n\n        if(ret < 0)\n          throw SystemError(errno, \"write\");\n\n        if (ret == 0)\n          return traits_type::eof();\n\n        log_debug(ret << \" bytes written to fd \" << getWriteFd());\n        p += ret;\n      }\n      setp(obuffer, obuffer + bufsize);\n    }\n    return 0;\n  }\n\n}\n}\n","avg_line_length":25.816091954,"max_line_length":83,"alphanum_fraction":0.6119768477,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":986,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":170.0,"content":"#include<stdio.h>\n#include<stdlib.h>\n\n#define sd(x) scanf(\"%d\",&x);\n#define sd2(x,y) scanf(\"%d %d\",&x,&y);\n#define sd3(x,y,z) scanf(\"%d %d %d\",&x,&y,&z);\n#define sull(x) scanf(\"%ull\",&x);\n#define print(x) printf(\"%d\\n\",x);\n#define print2(x,y) printf(\"%d %d\\n\",x,y);\n#define print3(x,y,z) printf(\"%d %d %d\\n\",x,y,z);\n#define printull(x) printf(\"%ull\\n\",x);\n#define max(x,y) ((x) > (y))? (x):(y);\n\nint main(){\n\tint m, p, y, n, type, charge, res, p_temp, interest, i, j;\n\tdouble rate;\n\tsd(m);\n\twhile(m--){\n\t\tsd(p);\n\t\tsd(y);\n\t\tsd(n);\n\t\tres = 0;\n\t\tfor(i = 0; i < n; i++){\n\t\t\tscanf(\"%d %lf %d\",&type, &rate, &charge);\t\n\t\t\tp_temp = p, interest = 0;\n\t\t\tif(type == 0){\n\t\t\t\tfor(j = 0; j < y; j++){\n\t\t\t\t\tinterest += (p_temp * rate);\n\t\t\t\t\tp_temp -= charge;\n\t\t\t\t}\n\t\t\t\tres = max(res, p_temp + interest);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tfor(j = 0; j < y; j++){\n\t\t\t\t\tinterest = p_temp * rate;\n\t\t\t\t\tp_temp = p_temp + interest - charge;\n\t\t\t\t}\n\t\t\t\tres = max(res, p_temp);\n\t\t\t}\n\t\t}\n\t\tprintf(\"%d\\n\",res);\n\t}\n\treturn 0;\n}\n","avg_line_length":21.9111111111,"max_line_length":59,"alphanum_fraction":0.5070993915,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7465,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/\/--------------------------------------------------------------------------------------\r\n\/\/ SimpleTriangleUWP.cpp\r\n\/\/\r\n\/\/ Advanced Technology Group (ATG)\r\n\/\/ Copyright (C) Microsoft Corporation. All rights reserved.\r\n\/\/--------------------------------------------------------------------------------------\r\n\r\n#include \"pch.h\"\r\n#include \"SimpleTriangleUWP.h\"\r\n\r\n#include \"ATGColors.h\"\r\n#include \"ReadData.h\"\r\n\r\nextern void ExitSample();\r\n\r\nusing namespace DirectX;\r\n\r\nusing Microsoft::WRL::ComPtr;\r\n\r\nnamespace\r\n{\r\n    struct Vertex\r\n    {\r\n        XMFLOAT4 position;\r\n        XMFLOAT4 color;\r\n    };\r\n}\r\n\r\nSample::Sample()\r\n{\r\n    \/\/ Use gamma-correct rendering.\r\n    m_deviceResources = std::make_unique<DX::DeviceResources>(\r\n        DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,\r\n        DXGI_FORMAT_D24_UNORM_S8_UINT,\r\n        2,\r\n        D3D_FEATURE_LEVEL_9_3,\r\n        DX::DeviceResources::c_AllowTearing\r\n        );\r\n    m_deviceResources->RegisterDeviceNotify(this);\r\n}\r\n\r\n\/\/ Initialize the Direct3D resources required to run.\r\nvoid Sample::Initialize(IUnknown* window, int width, int height, DXGI_MODE_ROTATION rotation)\r\n{\r\n    m_gamePad = std::make_unique<GamePad>();\r\n\r\n    m_keyboard = std::make_unique<Keyboard>();\r\n    m_keyboard->SetWindow(reinterpret_cast<ABI::Windows::UI::Core::ICoreWindow*>(window));\r\n\r\n    m_deviceResources->SetWindow(window, width, height, rotation);\r\n\r\n    m_deviceResources->CreateDeviceResources();  \t\r\n    CreateDeviceDependentResources();\r\n\r\n    m_deviceResources->CreateWindowSizeDependentResources();\r\n    CreateWindowSizeDependentResources();\r\n}\r\n\r\n#pragma region Frame Update\r\n\/\/ Executes basic render loop.\r\nvoid Sample::Tick()\r\n{\r\n    m_timer.Tick([&]()\r\n    {\r\n        Update(m_timer);\r\n    });\r\n\r\n    Render();\r\n}\r\n\r\n\/\/ Updates the world.\r\nvoid Sample::Update(DX::StepTimer const&)\r\n{\r\n    PIXBeginEvent(PIX_COLOR_DEFAULT, L\"Update\");\r\n\r\n    auto pad = m_gamePad->GetState(0);\r\n    if (pad.IsConnected())\r\n    {\r\n        if (pad.IsViewPressed())\r\n        {\r\n            ExitSample();\r\n        }\r\n    }\r\n\r\n    auto kb = m_keyboard->GetState();\r\n    if (kb.Escape)\r\n    {\r\n        ExitSample();\r\n    }\r\n\r\n    PIXEndEvent();\r\n}\r\n#pragma endregion\r\n\r\n#pragma region Frame Render\r\n\/\/ Draws the scene.\r\nvoid Sample::Render()\r\n{\r\n    \/\/ Don't try to render anything before the first Update.\r\n    if (m_timer.GetFrameCount() == 0)\r\n    {\r\n        return;\r\n    }\r\n\r\n    Clear();\r\n\r\n    auto context = m_deviceResources->GetD3DDeviceContext();\r\n    PIXBeginEvent(context, PIX_COLOR_DEFAULT, L\"Render\");\r\n\r\n    \/\/ Set input assembler state.\r\n    context->IASetInputLayout(m_spInputLayout.Get());\r\n\r\n    UINT strides = sizeof(Vertex);\r\n    UINT offsets = 0;\r\n    context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\r\n    context->IASetVertexBuffers(0, 1, m_spVertexBuffer.GetAddressOf(), &strides, &offsets);\r\n\r\n    \/\/ Set shaders.\r\n    context->VSSetShader(m_spVertexShader.Get(), nullptr, 0);\r\n    context->GSSetShader(nullptr, nullptr, 0);\r\n    context->PSSetShader(m_spPixelShader.Get(), nullptr, 0);\r\n\r\n    \/\/ Draw triangle.\r\n    context->Draw(3, 0);\r\n\r\n    PIXEndEvent(context);\r\n\r\n    \/\/ Show the new frame.\r\n    PIXBeginEvent(PIX_COLOR_DEFAULT, L\"Present\");\r\n    m_deviceResources->Present();\r\n    PIXEndEvent();\r\n}\r\n\r\n\/\/ Helper method to clear the back buffers.\r\nvoid Sample::Clear()\r\n{\r\n    auto context = m_deviceResources->GetD3DDeviceContext();\r\n    PIXBeginEvent(context, PIX_COLOR_DEFAULT, L\"Clear\");\r\n\r\n    \/\/ Clear the views.\r\n    auto renderTarget = m_deviceResources->GetRenderTargetView();\r\n    auto depthStencil = m_deviceResources->GetDepthStencilView();\r\n\r\n    \/\/ Use linear clear color for gamma-correct rendering.\r\n    context->ClearRenderTargetView(renderTarget, ATG::ColorsLinear::Background);\r\n\r\n    context->ClearDepthStencilView(depthStencil, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);\r\n\r\n    context->OMSetRenderTargets(1, &renderTarget, depthStencil);\r\n\r\n    \/\/ Set the viewport.\r\n    auto viewport = m_deviceResources->GetScreenViewport();\r\n    context->RSSetViewports(1, &viewport);\r\n\r\n    PIXEndEvent(context);\r\n}\r\n#pragma endregion\r\n\r\n#pragma region Message Handlers\r\n\/\/ Message handlers\r\nvoid Sample::OnActivated()\r\n{\r\n}\r\n\r\nvoid Sample::OnDeactivated()\r\n{\r\n}\r\n\r\nvoid Sample::OnSuspending()\r\n{\r\n    auto context = m_deviceResources->GetD3DDeviceContext();\r\n    context->ClearState();\r\n\r\n    m_deviceResources->Trim();\r\n}\r\n\r\nvoid Sample::OnResuming()\r\n{\r\n    m_timer.ResetElapsedTime();\r\n}\r\n\r\nvoid Sample::OnWindowSizeChanged(int width, int height, DXGI_MODE_ROTATION rotation)\r\n{\r\n    if (!m_deviceResources->WindowSizeChanged(width, height, rotation))\r\n        return;\r\n\r\n    CreateWindowSizeDependentResources();\r\n}\r\n\r\nvoid Sample::ValidateDevice()\r\n{\r\n    m_deviceResources->ValidateDevice();\r\n}\r\n\r\n\/\/ Properties\r\nvoid Sample::GetDefaultSize(int& width, int& height) const\r\n{\r\n    width = 1280;\r\n    height = 720;\r\n}\r\n#pragma endregion\r\n\r\n#pragma region Direct3D Resources\r\n\/\/ These are the resources that depend on the device.\r\nvoid Sample::CreateDeviceDependentResources()\r\n{\r\n    auto device = m_deviceResources->GetD3DDevice();\r\n\r\n    \/\/ Load and create shaders.\r\n    auto vertexShaderBlob = DX::ReadData(L\"VertexShader.cso\");\r\n\r\n    DX::ThrowIfFailed(\r\n        device->CreateVertexShader(vertexShaderBlob.data(), vertexShaderBlob.size(),\r\n            nullptr, m_spVertexShader.ReleaseAndGetAddressOf()));\r\n\r\n    auto pixelShaderBlob = DX::ReadData(L\"PixelShader.cso\");\r\n\r\n    DX::ThrowIfFailed(\r\n        device->CreatePixelShader(pixelShaderBlob.data(), pixelShaderBlob.size(),\r\n            nullptr, m_spPixelShader.ReleaseAndGetAddressOf()));\r\n\r\n    \/\/ Create input layout.\r\n    static const D3D11_INPUT_ELEMENT_DESC s_inputElementDesc[2] =\r\n    {\r\n        { \"SV_Position\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0,  D3D11_INPUT_PER_VERTEX_DATA,  0 },\r\n        { \"COLOR\",       0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA , 0 },\r\n    };\r\n\r\n    DX::ThrowIfFailed(\r\n        device->CreateInputLayout(s_inputElementDesc, _countof(s_inputElementDesc),\r\n            vertexShaderBlob.data(), vertexShaderBlob.size(),\r\n            m_spInputLayout.ReleaseAndGetAddressOf()));\r\n\r\n    \/\/ Create vertex buffer.\r\n    static const Vertex s_vertexData[3] =\r\n    {\r\n        { { 0.0f,   0.5f,  0.5f, 1.0f },{ 1.0f, 0.0f, 0.0f, 1.0f } },  \/\/ Top \/ Red\r\n        { { 0.5f,  -0.5f,  0.5f, 1.0f },{ 0.0f, 1.0f, 0.0f, 1.0f } },  \/\/ Right \/ Green\r\n        { { -0.5f, -0.5f,  0.5f, 1.0f },{ 0.0f, 0.0f, 1.0f, 1.0f } }   \/\/ Left \/ Blue\r\n    };\r\n\r\n    D3D11_SUBRESOURCE_DATA initialData = {};\r\n    initialData.pSysMem = s_vertexData;\r\n\r\n    D3D11_BUFFER_DESC bufferDesc = {};\r\n    bufferDesc.ByteWidth = sizeof(s_vertexData);\r\n    bufferDesc.Usage = D3D11_USAGE_IMMUTABLE;\r\n    bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;\r\n    bufferDesc.StructureByteStride = sizeof(Vertex);\r\n\r\n    DX::ThrowIfFailed(\r\n        device->CreateBuffer(&bufferDesc, &initialData,\r\n            m_spVertexBuffer.ReleaseAndGetAddressOf()));\r\n}\r\n\r\n\/\/ Allocate all memory resources that change on a window SizeChanged event.\r\nvoid Sample::CreateWindowSizeDependentResources()\r\n{\r\n}\r\n\r\nvoid Sample::OnDeviceLost()\r\n{\r\n    m_spInputLayout.Reset();\r\n    m_spVertexBuffer.Reset();\r\n    m_spVertexShader.Reset();\r\n    m_spPixelShader.Reset();\r\n}\r\n\r\nvoid Sample::OnDeviceRestored()\r\n{\r\n    CreateDeviceDependentResources();\r\n\r\n    CreateWindowSizeDependentResources();\r\n}\r\n#pragma endregion\r\n","avg_line_length":27.0471014493,"max_line_length":102,"alphanum_fraction":0.6468854655,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3894,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":64.0,"content":"\/*\n * Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *   * Redistributions of source code must retain the above copyright notice,\n *     this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and\/or other materials provided with the distribution.\n *   * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived from\n *     this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <opencv\/cv.h>\n#include <opencv\/highgui.h>\n#include <opencv\/cxcore.h>\n\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <sys\/time.h>\n#include <sys\/resource.h>\n\n#include <libdpm_ttic\/dpm_ttic.hpp>\n\n#include \"for_use_GPU.h\"\n#include \"load_model.hpp\"\n#include \"detect.hpp\"\n#include \"GPU_init.hpp\"\n\n#include \"common.hpp\"\n\nstruct timeval tv_memcpy_start, tv_memcpy_end;\nfloat time_memcpy;\nstruct timeval tv_kernel_start, tv_kernel_end;\nfloat time_kernel;\n\nint device_num;\n\nvoid dpm_ttic_gpu_init_cuda(const std::string& cubin_path)\n{\n\tdpm_ttic_gpu_init_cuda_with_cubin(cubin_path.c_str());\n}\n\nvoid dpm_ttic_gpu_cleanup_cuda()\n{\n\tdpm_ttic_gpu_clean_cuda();\n\t\/\/free_model(MO);\n}\n\nDPMTTICGPU::DPMTTICGPU(const char *com_csv, const char *root_csv, const char *part_csv)\n{\n\tconstexpr double RATIO = 1;\n\tmodel_ = dpm_ttic_gpu_load_model(RATIO, com_csv, root_csv, part_csv);\n}\n\nDPMTTICGPU::~DPMTTICGPU()\n{\n\tdpm_ttic_gpu_free_model(model_);\n}\n\nstatic FLOAT *init_accumulated_score(IplImage *image, size_t& accumulated_size)\n{\n\tsize_t num = image->height * image->width;\n\taccumulated_size = num * sizeof(FLOAT);\n\n\tFLOAT *scores = (FLOAT *)calloc(num, sizeof(FLOAT));\n\tfor(size_t i = 0; i < num; i++)\n\t\tscores[i] = -100.0;\n\n\treturn scores;\n}\n\nDPMTTICResult DPMTTICGPU::detect_objects(IplImage *image, const DPMTTICParam& param)\n{\n\tmodel_->MI->interval = param.lambda;\n\tmodel_->MI->sbin     = param.num_cells;\n\n\tint detected_objects;\n\tFLOAT *ac_score = init_accumulated_score(image, gpu_size_A_SCORE);\n\tRESULT *objects = dpm_ttic_gpu_car_detection(image, model_, param.threshold,\n\t\t\t\t\t\t     &detected_objects, ac_score,\n\t\t\t\t\t\t     param.overlap);\n\tfree(ac_score);\n\n\tDPMTTICResult result;\n\tresult.num = objects->num;\n\tfor (int i = 0; i < objects->num; ++i) {\n\t\tresult.type.push_back(objects->type[i]);\n\t}\n\n\tfor (int i = 0; i < objects->num; ++i) {\n\t\tint base = i * 4;\n\t\tint *data = &(objects->OR_point[base]);\n\n\t\tresult.corner_points.push_back(data[0]);\n\t\tresult.corner_points.push_back(data[1]);\n\t\tresult.corner_points.push_back(data[2] - data[0]);\n\t\tresult.corner_points.push_back(data[3] - data[1]);\n\t\tresult.score.push_back(objects->score[i]);\n\t}\n\n\tfree(objects->point);\n\tfree(objects->type);\n\tfree(objects->scale);\n\tfree(objects->score);\n\tfree(objects->IM);\n\treturn result;\n}\n","avg_line_length":31.4032258065,"max_line_length":91,"alphanum_fraction":0.7408834104,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2066,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n * @Date: 2021-04-27 08:38:21\n * @Author: Mengsen Wang\n * @LastEditors: Mengsen Wang\n * @LastEditTime: 2021-04-27 09:09:24\n *\/\n\n#include <cassert>\n#include <queue>\n\nstruct TreeNode {\n  int val;\n  TreeNode *left;\n  TreeNode *right;\n  TreeNode() : val(0), left(nullptr), right(nullptr) {}\n  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n  TreeNode(int x, TreeNode *left, TreeNode *right)\n      : val(x), left(left), right(right) {}\n};\n\nint range_sum_bst_dfs(TreeNode *root, int low, int high) {\n  if (root == nullptr) return 0;\n  if (root->val >= low && root->val <= high)\n    return root->val + range_sum_bst_dfs(root->left, low, high) +\n           range_sum_bst_dfs(root->right, low, high);\n  else if (root->val < low)\n    return range_sum_bst_dfs(root->right, low, high);\n  else\n    return range_sum_bst_dfs(root->left, low, high);\n}\n\nint range_sum_bst_bfs(TreeNode *root, int low, int high) {\n  int val = 0;\n  std::queue<TreeNode *> q({root});\n  while (!q.empty()) {\n    TreeNode *node = q.front();\n    q.pop();\n    if (node == nullptr) continue;\n    if (node->val > high) {\n      q.push(node->left);\n    } else if (node->val < low) {\n      q.push(node->right);\n    } else {\n      val += node->val;\n      q.push(node->left);\n      q.push(node->right);\n    }\n  }\n  return val;\n}\n\nint main() {\n  {\n    TreeNode *root = new TreeNode{\n        10,\n        new TreeNode{5, new TreeNode{3, nullptr, nullptr},\n                     new TreeNode{7, nullptr, nullptr}},\n        new TreeNode{15, nullptr, new TreeNode{18, nullptr, nullptr}}};\n    int low = 7, high = 15;\n    assert(range_sum_bst_dfs(root, low, high) == 32);\n  }\n  {\n    TreeNode *root = new TreeNode{\n        10,\n        new TreeNode{\n            5, new TreeNode{3, new TreeNode{3, nullptr, nullptr}, nullptr},\n            new TreeNode{7, new TreeNode{6, nullptr, nullptr}, nullptr}},\n        new TreeNode{15, new TreeNode{13, nullptr, nullptr},\n                     new TreeNode{18, nullptr, nullptr}}};\n    int low = 6, high = 10;\n    assert(range_sum_bst_bfs(root, low, high) == 23);\n  }\n}\n","avg_line_length":27.9189189189,"max_line_length":75,"alphanum_fraction":0.5895450145,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5740,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"test_bitcoin.h\"\n\n#include \"chainparams.h\"\n#include \"consensus\/consensus.h\"\n#include \"consensus\/validation.h\"\n#include \"crypto\/sha256.h\"\n#include \"fs.h\"\n#include \"key.h\"\n#include \"validation.h\"\n#include \"miner.h\"\n#include \"net_processing.h\"\n#include \"pubkey.h\"\n#include \"random.h\"\n#include \"txdb.h\"\n#include \"txmempool.h\"\n#include \"ui_interface.h\"\n#include \"rpc\/server.h\"\n#include \"rpc\/register.h\"\n#include \"script\/sigcache.h\"\n\n#include <memory>\n\nvoid CConnmanTest::AddNode(CNode& node)\n{\n    LOCK(g_connman->cs_vNodes);\n    g_connman->vNodes.push_back(&node);\n}\n\nvoid CConnmanTest::ClearNodes()\n{\n    LOCK(g_connman->cs_vNodes);\n    g_connman->vNodes.clear();\n}\n\nuint256 insecure_rand_seed = GetRandHash();\nFastRandomContext insecure_rand_ctx(insecure_rand_seed);\n\nextern bool fPrintToConsole;\nextern void noui_connect();\n\nBasicTestingSetup::BasicTestingSetup(const std::string& chainName)\n{\n        SHA256AutoDetect();\n        RandomInit();\n        ECC_Start();\n        SetupEnvironment();\n        SetupNetworking();\n        InitSignatureCache();\n        InitScriptExecutionCache();\n        fPrintToDebugLog = false; \/\/ don't want to write to debug.log file\n        fCheckBlockIndex = true;\n        SelectParams(chainName);\n        noui_connect();\n}\n\nBasicTestingSetup::~BasicTestingSetup()\n{\n        ECC_Stop();\n}\n\nTestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(chainName)\n{\n    const CChainParams& chainparams = Params();\n        \/\/ Ideally we'd move all the RPC tests to the functional testing framework\n        \/\/ instead of unit tests, but for now we need these here.\n\n        RegisterAllCoreRPCCommands(tableRPC);\n        ClearDatadirCache();\n        pathTemp = fs::temp_directory_path() \/ strprintf(\"test_zzboltcoin_%lu_%i\", (unsigned long)GetTime(), (int)(InsecureRandRange(100000)));\n        fs::create_directories(pathTemp);\n        gArgs.ForceSetArg(\"-datadir\", pathTemp.string());\n\n        \/\/ Note that because we don't bother running a scheduler thread here,\n        \/\/ callbacks via CValidationInterface are unreliable, but that's OK,\n        \/\/ our unit tests aren't testing multiple parts of the code at once.\n        GetMainSignals().RegisterBackgroundSignalScheduler(scheduler);\n\n        mempool.setSanityCheck(1.0);\n        pblocktree = new CBlockTreeDB(1 << 20, true);\n        pcoinsdbview = new CCoinsViewDB(1 << 23, true);\n        pcoinsTip = new CCoinsViewCache(pcoinsdbview);\n        if (!LoadGenesisBlock(chainparams)) {\n            throw std::runtime_error(\"LoadGenesisBlock failed.\");\n        }\n        {\n            CValidationState state;\n            if (!ActivateBestChain(state, chainparams)) {\n                throw std::runtime_error(\"ActivateBestChain failed.\");\n            }\n        }\n        nScriptCheckThreads = 3;\n        for (int i=0; i < nScriptCheckThreads-1; i++)\n            threadGroup.create_thread(&ThreadScriptCheck);\n        g_connman = std::unique_ptr<CConnman>(new CConnman(0x1337, 0x1337)); \/\/ Deterministic randomness for tests.\n        connman = g_connman.get();\n        peerLogic.reset(new PeerLogicValidation(connman, scheduler));\n}\n\nTestingSetup::~TestingSetup()\n{\n        threadGroup.interrupt_all();\n        threadGroup.join_all();\n        GetMainSignals().FlushBackgroundCallbacks();\n        GetMainSignals().UnregisterBackgroundSignalScheduler();\n        g_connman.reset();\n        peerLogic.reset();\n        UnloadBlockIndex();\n        delete pcoinsTip;\n        delete pcoinsdbview;\n        delete pblocktree;\n        fs::remove_all(pathTemp);\n}\n\nTestChain100Setup::TestChain100Setup() : TestingSetup(CBaseChainParams::REGTEST)\n{\n    \/\/ Generate a 100-block chain:\n    coinbaseKey.MakeNewKey(true);\n    CScript scriptPubKey = CScript() <<  ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;\n    for (int i = 0; i < COINBASE_MATURITY; i++)\n    {\n        std::vector<CMutableTransaction> noTxns;\n        CBlock b = CreateAndProcessBlock(noTxns, scriptPubKey);\n        coinbaseTxns.push_back(*b.vtx[0]);\n    }\n}\n\n\/\/\n\/\/ Create a new block with just given transactions, coinbase paying to\n\/\/ scriptPubKey, and try to add it to the current chain.\n\/\/\nCBlock\nTestChain100Setup::CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns, const CScript& scriptPubKey)\n{\n    const CChainParams& chainparams = Params();\n    std::unique_ptr<CBlockTemplate> pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey);\n    CBlock& block = pblocktemplate->block;\n\n    \/\/ Replace mempool-selected txns with just coinbase plus passed-in txns:\n    block.vtx.resize(1);\n    for (const CMutableTransaction& tx : txns)\n        block.vtx.push_back(MakeTransactionRef(tx));\n    \/\/ IncrementExtraNonce creates a valid coinbase and merkleRoot\n    unsigned int extraNonce = 0;\n    IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);\n\n    while (!CheckProofOfWork(block.GetPoWHash(), block.nBits, chainparams.GetConsensus())) ++block.nNonce;\n\n    std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block);\n    ProcessNewBlock(chainparams, shared_pblock, true, nullptr);\n\n    CBlock result = block;\n    return result;\n}\n\nTestChain100Setup::~TestChain100Setup()\n{\n}\n\n\nCTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CMutableTransaction &tx) {\n    CTransaction txn(tx);\n    return FromTx(txn);\n}\n\nCTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CTransaction &txn) {\n    return CTxMemPoolEntry(MakeTransactionRef(txn), nFee, nTime, nHeight,\n                           spendsCoinbase, sigOpCost, lp);\n}\n","avg_line_length":33.1791907514,"max_line_length":143,"alphanum_fraction":0.6945993031,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2370,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/*\n *  compare_gmi.cpp\n *  compare_gmi \n *\n *  Created by Wan, Yinan, on 07\/22\/11.\n *  \n *\/\n\n#include <QtGlobal>\n\n#include \"compare_gmi.h\"\n#include \"v3d_message.h\" \n#include \"..\/..\/..\/v3d_main\/basic_c_fun\/basic_surf_objs.h\"\n#include \"fcompare.h\"\n#include <unistd.h>\n#include <iostream>\nusing namespace std;\n\n\n\/\/Q_EXPORT_PLUGIN2 ( PluginName, ClassName )\n\/\/The value of PluginName should correspond to the TARGET specified in the plugin's project file.\nQ_EXPORT_PLUGIN2(compare_gmi, Compare_gmiPlugin);\n\n\n\/\/plugin funcs\nconst QString title = \"compare_feature\";\n\nQStringList Compare_gmiPlugin::menulist() const\n{\n    return QStringList();\n\t\/\/<<tr(\"compare_feature\");\n\t\/\/<<tr(\"Help\");\n}\n\nQStringList Compare_gmiPlugin::funclist() const\n{\n\treturn QStringList()\n\t<<tr(\"compare_gmi\")\n\t<<tr(\"help\");\n}\n\n\n\nvoid Compare_gmiPlugin::domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent)\n{\n\t\/*if (menu_name == tr(\"neuron_feature\"))\n\t{\n    \t\tneuron_feature(callback, parent,1 );\n    }\n\telse if (menu_name == tr(\"Help\"))\n\t{\n\t\tv3d_msg(\"(version 0.01) Compute global features for a certain neuron.\");\n\t}*\/\n\treturn;\n}\n\n\nbool Compare_gmiPlugin::dofunc(const QString & func_name, const V3DPluginArgList & input, V3DPluginArgList & output, V3DPluginCallback2 & callback, QWidget * parent)\n{\t\n\tif (func_name==tr(\"help\"))\n\t{\n\t\tcout<<\"\\n(version 0.03) Find certain number of subjects in the input group that are most similar to a query based on geometric moment invariants.\"<<endl;\n\t\tcout<<\"\\n-x <plugin_dll_full_path>\\ta string indicates the full path of a dll (for a plugin) to be launched.\"<<endl;\n\t\tcout<<\"-f <function_name>\\t\\tcompare_gmi\"<<endl;\n\t\tcout<<\"-i <file>\\t\\t\\tastring indicating the linker file that specifies the library of swc files to perform comparison\"<<endl;\n\t\tcout<<\"-o <file>\\t\\t\\tname for output result file\"<<endl;\n\t\tcout<<\"-p <par1 par2>\\t\\t\\tpar1: a number indicates the query id in the input lib.\\tpar2: the number of subjects you want to pick up\"<<endl;\n\t\tcout<<\"\\nUsage: .\/v3d -x plugins\/neuron_comparison\/compare_gmi\/libcompare_gmi.so -f compare_gmi -i mylinker.ano -o result.txt -p 1 10\"<<endl;\n\t\tcout<<endl;\n\t\treturn true;\n\t}\n\t\n\telse if (func_name==tr(\"compare_gmi\"))\n\t{\n\t\tcout<<\"\\n===============Welcome to compare_gmi Function===============\"<<endl;\n\t\tbool result = compare_gmi(input,output); \n\t\treturn result;\n\t}\n\treturn false;\n}\n","avg_line_length":29.2592592593,"max_line_length":165,"alphanum_fraction":0.7033755274,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":124823,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\ufeff\/*\n* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\").\n* You may not use this file except in compliance with the License.\n* A copy of the License is located at\n*\n*  http:\/\/aws.amazon.com\/apache2.0\n*\n* or in the \"license\" file accompanying this file. This file is distributed\n* on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n* express or implied. See the License for the specific language governing\n* permissions and limitations under the License.\n*\/\n\n#include <aws\/core\/utils\/Outcome.h>\n#include <aws\/core\/auth\/AWSAuthSigner.h>\n#include <aws\/core\/client\/CoreErrors.h>\n#include <aws\/core\/client\/RetryStrategy.h>\n#include <aws\/core\/http\/HttpClient.h>\n#include <aws\/core\/http\/HttpResponse.h>\n#include <aws\/core\/http\/HttpClientFactory.h>\n#include <aws\/core\/auth\/AWSCredentialsProviderChain.h>\n#include <aws\/core\/utils\/json\/JsonSerializer.h>\n#include <aws\/core\/utils\/memory\/stl\/AWSStringStream.h>\n#include <aws\/core\/utils\/threading\/Executor.h>\n#include <aws\/core\/utils\/DNS.h>\n#include <aws\/core\/utils\/logging\/LogMacros.h>\n\n#include <aws\/apigatewayv2\/ApiGatewayV2Client.h>\n#include <aws\/apigatewayv2\/ApiGatewayV2Endpoint.h>\n#include <aws\/apigatewayv2\/ApiGatewayV2ErrorMarshaller.h>\n#include <aws\/apigatewayv2\/model\/CreateApiRequest.h>\n#include <aws\/apigatewayv2\/model\/CreateApiMappingRequest.h>\n#include <aws\/apigatewayv2\/model\/CreateAuthorizerRequest.h>\n#include <aws\/apigatewayv2\/model\/CreateDeploymentRequest.h>\n#include <aws\/apigatewayv2\/model\/CreateDomainNameRequest.h>\n#include <aws\/apigatewayv2\/model\/CreateIntegrationRequest.h>\n#include <aws\/apigatewayv2\/model\/CreateIntegrationResponseRequest.h>\n#include <aws\/apigatewayv2\/model\/CreateModelRequest.h>\n#include <aws\/apigatewayv2\/model\/CreateRouteRequest.h>\n#include <aws\/apigatewayv2\/model\/CreateRouteResponseRequest.h>\n#include <aws\/apigatewayv2\/model\/CreateStageRequest.h>\n#include <aws\/apigatewayv2\/model\/DeleteApiRequest.h>\n#include <aws\/apigatewayv2\/model\/DeleteApiMappingRequest.h>\n#include <aws\/apigatewayv2\/model\/DeleteAuthorizerRequest.h>\n#include <aws\/apigatewayv2\/model\/DeleteDeploymentRequest.h>\n#include <aws\/apigatewayv2\/model\/DeleteDomainNameRequest.h>\n#include <aws\/apigatewayv2\/model\/DeleteIntegrationRequest.h>\n#include <aws\/apigatewayv2\/model\/DeleteIntegrationResponseRequest.h>\n#include <aws\/apigatewayv2\/model\/DeleteModelRequest.h>\n#include <aws\/apigatewayv2\/model\/DeleteRouteRequest.h>\n#include <aws\/apigatewayv2\/model\/DeleteRouteResponseRequest.h>\n#include <aws\/apigatewayv2\/model\/DeleteStageRequest.h>\n#include <aws\/apigatewayv2\/model\/GetApiRequest.h>\n#include <aws\/apigatewayv2\/model\/GetApiMappingRequest.h>\n#include <aws\/apigatewayv2\/model\/GetApiMappingsRequest.h>\n#include <aws\/apigatewayv2\/model\/GetApisRequest.h>\n#include <aws\/apigatewayv2\/model\/GetAuthorizerRequest.h>\n#include <aws\/apigatewayv2\/model\/GetAuthorizersRequest.h>\n#include <aws\/apigatewayv2\/model\/GetDeploymentRequest.h>\n#include <aws\/apigatewayv2\/model\/GetDeploymentsRequest.h>\n#include <aws\/apigatewayv2\/model\/GetDomainNameRequest.h>\n#include <aws\/apigatewayv2\/model\/GetDomainNamesRequest.h>\n#include <aws\/apigatewayv2\/model\/GetIntegrationRequest.h>\n#include <aws\/apigatewayv2\/model\/GetIntegrationResponseRequest.h>\n#include <aws\/apigatewayv2\/model\/GetIntegrationResponsesRequest.h>\n#include <aws\/apigatewayv2\/model\/GetIntegrationsRequest.h>\n#include <aws\/apigatewayv2\/model\/GetModelRequest.h>\n#include <aws\/apigatewayv2\/model\/GetModelTemplateRequest.h>\n#include <aws\/apigatewayv2\/model\/GetModelsRequest.h>\n#include <aws\/apigatewayv2\/model\/GetRouteRequest.h>\n#include <aws\/apigatewayv2\/model\/GetRouteResponseRequest.h>\n#include <aws\/apigatewayv2\/model\/GetRouteResponsesRequest.h>\n#include <aws\/apigatewayv2\/model\/GetRoutesRequest.h>\n#include <aws\/apigatewayv2\/model\/GetStageRequest.h>\n#include <aws\/apigatewayv2\/model\/GetStagesRequest.h>\n#include <aws\/apigatewayv2\/model\/UpdateApiRequest.h>\n#include <aws\/apigatewayv2\/model\/UpdateApiMappingRequest.h>\n#include <aws\/apigatewayv2\/model\/UpdateAuthorizerRequest.h>\n#include <aws\/apigatewayv2\/model\/UpdateDeploymentRequest.h>\n#include <aws\/apigatewayv2\/model\/UpdateDomainNameRequest.h>\n#include <aws\/apigatewayv2\/model\/UpdateIntegrationRequest.h>\n#include <aws\/apigatewayv2\/model\/UpdateIntegrationResponseRequest.h>\n#include <aws\/apigatewayv2\/model\/UpdateModelRequest.h>\n#include <aws\/apigatewayv2\/model\/UpdateRouteRequest.h>\n#include <aws\/apigatewayv2\/model\/UpdateRouteResponseRequest.h>\n#include <aws\/apigatewayv2\/model\/UpdateStageRequest.h>\n\nusing namespace Aws;\nusing namespace Aws::Auth;\nusing namespace Aws::Client;\nusing namespace Aws::ApiGatewayV2;\nusing namespace Aws::ApiGatewayV2::Model;\nusing namespace Aws::Http;\nusing namespace Aws::Utils::Json;\n\nstatic const char* SERVICE_NAME = \"apigateway\";\nstatic const char* ALLOCATION_TAG = \"ApiGatewayV2Client\";\n\n\nApiGatewayV2Client::ApiGatewayV2Client(const Client::ClientConfiguration& clientConfiguration) :\n  BASECLASS(clientConfiguration,\n    Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG),\n        SERVICE_NAME, clientConfiguration.region),\n    Aws::MakeShared<ApiGatewayV2ErrorMarshaller>(ALLOCATION_TAG)),\n    m_executor(clientConfiguration.executor)\n{\n  init(clientConfiguration);\n}\n\nApiGatewayV2Client::ApiGatewayV2Client(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) :\n  BASECLASS(clientConfiguration,\n    Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials),\n         SERVICE_NAME, clientConfiguration.region),\n    Aws::MakeShared<ApiGatewayV2ErrorMarshaller>(ALLOCATION_TAG)),\n    m_executor(clientConfiguration.executor)\n{\n  init(clientConfiguration);\n}\n\nApiGatewayV2Client::ApiGatewayV2Client(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider,\n  const Client::ClientConfiguration& clientConfiguration) :\n  BASECLASS(clientConfiguration,\n    Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider,\n         SERVICE_NAME, clientConfiguration.region),\n    Aws::MakeShared<ApiGatewayV2ErrorMarshaller>(ALLOCATION_TAG)),\n    m_executor(clientConfiguration.executor)\n{\n  init(clientConfiguration);\n}\n\nApiGatewayV2Client::~ApiGatewayV2Client()\n{\n}\n\nvoid ApiGatewayV2Client::init(const ClientConfiguration& config)\n{\n  m_configScheme = SchemeMapper::ToString(config.scheme);\n  if (config.endpointOverride.empty())\n  {\n      m_uri = m_configScheme + \":\/\/\" + ApiGatewayV2Endpoint::ForRegion(config.region, config.useDualStack);\n  }\n  else\n  {\n      OverrideEndpoint(config.endpointOverride);\n  }\n}\n\nvoid ApiGatewayV2Client::OverrideEndpoint(const Aws::String& endpoint)\n{\n  if (endpoint.compare(0, 7, \"http:\/\/\") == 0 || endpoint.compare(0, 8, \"https:\/\/\") == 0)\n  {\n      m_uri = endpoint;\n  }\n  else\n  {\n      m_uri = m_configScheme + \":\/\/\" + endpoint;\n  }\n}\nCreateApiOutcome ApiGatewayV2Client::CreateApi(const CreateApiRequest& request) const\n{\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return CreateApiOutcome(CreateApiResult(outcome.GetResult()));\n  }\n  else\n  {\n    return CreateApiOutcome(outcome.GetError());\n  }\n}\n\nCreateApiOutcomeCallable ApiGatewayV2Client::CreateApiCallable(const CreateApiRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< CreateApiOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateApi(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::CreateApiAsync(const CreateApiRequest& request, const CreateApiResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->CreateApiAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::CreateApiAsyncHelper(const CreateApiRequest& request, const CreateApiResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, CreateApi(request), context);\n}\n\nCreateApiMappingOutcome ApiGatewayV2Client::CreateApiMapping(const CreateApiMappingRequest& request) const\n{\n  if (!request.DomainNameHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"CreateApiMapping\", \"Required field: DomainName, is not set\");\n    return CreateApiMappingOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [DomainName]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/domainnames\/\";\n  ss << request.GetDomainName();\n  ss << \"\/apimappings\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return CreateApiMappingOutcome(CreateApiMappingResult(outcome.GetResult()));\n  }\n  else\n  {\n    return CreateApiMappingOutcome(outcome.GetError());\n  }\n}\n\nCreateApiMappingOutcomeCallable ApiGatewayV2Client::CreateApiMappingCallable(const CreateApiMappingRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< CreateApiMappingOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateApiMapping(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::CreateApiMappingAsync(const CreateApiMappingRequest& request, const CreateApiMappingResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->CreateApiMappingAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::CreateApiMappingAsyncHelper(const CreateApiMappingRequest& request, const CreateApiMappingResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, CreateApiMapping(request), context);\n}\n\nCreateAuthorizerOutcome ApiGatewayV2Client::CreateAuthorizer(const CreateAuthorizerRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"CreateAuthorizer\", \"Required field: ApiId, is not set\");\n    return CreateAuthorizerOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/authorizers\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return CreateAuthorizerOutcome(CreateAuthorizerResult(outcome.GetResult()));\n  }\n  else\n  {\n    return CreateAuthorizerOutcome(outcome.GetError());\n  }\n}\n\nCreateAuthorizerOutcomeCallable ApiGatewayV2Client::CreateAuthorizerCallable(const CreateAuthorizerRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< CreateAuthorizerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateAuthorizer(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::CreateAuthorizerAsync(const CreateAuthorizerRequest& request, const CreateAuthorizerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->CreateAuthorizerAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::CreateAuthorizerAsyncHelper(const CreateAuthorizerRequest& request, const CreateAuthorizerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, CreateAuthorizer(request), context);\n}\n\nCreateDeploymentOutcome ApiGatewayV2Client::CreateDeployment(const CreateDeploymentRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"CreateDeployment\", \"Required field: ApiId, is not set\");\n    return CreateDeploymentOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/deployments\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return CreateDeploymentOutcome(CreateDeploymentResult(outcome.GetResult()));\n  }\n  else\n  {\n    return CreateDeploymentOutcome(outcome.GetError());\n  }\n}\n\nCreateDeploymentOutcomeCallable ApiGatewayV2Client::CreateDeploymentCallable(const CreateDeploymentRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< CreateDeploymentOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateDeployment(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::CreateDeploymentAsync(const CreateDeploymentRequest& request, const CreateDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->CreateDeploymentAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::CreateDeploymentAsyncHelper(const CreateDeploymentRequest& request, const CreateDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, CreateDeployment(request), context);\n}\n\nCreateDomainNameOutcome ApiGatewayV2Client::CreateDomainName(const CreateDomainNameRequest& request) const\n{\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/domainnames\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return CreateDomainNameOutcome(CreateDomainNameResult(outcome.GetResult()));\n  }\n  else\n  {\n    return CreateDomainNameOutcome(outcome.GetError());\n  }\n}\n\nCreateDomainNameOutcomeCallable ApiGatewayV2Client::CreateDomainNameCallable(const CreateDomainNameRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< CreateDomainNameOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateDomainName(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::CreateDomainNameAsync(const CreateDomainNameRequest& request, const CreateDomainNameResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->CreateDomainNameAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::CreateDomainNameAsyncHelper(const CreateDomainNameRequest& request, const CreateDomainNameResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, CreateDomainName(request), context);\n}\n\nCreateIntegrationOutcome ApiGatewayV2Client::CreateIntegration(const CreateIntegrationRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"CreateIntegration\", \"Required field: ApiId, is not set\");\n    return CreateIntegrationOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/integrations\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return CreateIntegrationOutcome(CreateIntegrationResult(outcome.GetResult()));\n  }\n  else\n  {\n    return CreateIntegrationOutcome(outcome.GetError());\n  }\n}\n\nCreateIntegrationOutcomeCallable ApiGatewayV2Client::CreateIntegrationCallable(const CreateIntegrationRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< CreateIntegrationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateIntegration(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::CreateIntegrationAsync(const CreateIntegrationRequest& request, const CreateIntegrationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->CreateIntegrationAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::CreateIntegrationAsyncHelper(const CreateIntegrationRequest& request, const CreateIntegrationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, CreateIntegration(request), context);\n}\n\nCreateIntegrationResponseOutcome ApiGatewayV2Client::CreateIntegrationResponse(const CreateIntegrationResponseRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"CreateIntegrationResponse\", \"Required field: ApiId, is not set\");\n    return CreateIntegrationResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.IntegrationIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"CreateIntegrationResponse\", \"Required field: IntegrationId, is not set\");\n    return CreateIntegrationResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [IntegrationId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/integrations\/\";\n  ss << request.GetIntegrationId();\n  ss << \"\/integrationresponses\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return CreateIntegrationResponseOutcome(CreateIntegrationResponseResult(outcome.GetResult()));\n  }\n  else\n  {\n    return CreateIntegrationResponseOutcome(outcome.GetError());\n  }\n}\n\nCreateIntegrationResponseOutcomeCallable ApiGatewayV2Client::CreateIntegrationResponseCallable(const CreateIntegrationResponseRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< CreateIntegrationResponseOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateIntegrationResponse(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::CreateIntegrationResponseAsync(const CreateIntegrationResponseRequest& request, const CreateIntegrationResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->CreateIntegrationResponseAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::CreateIntegrationResponseAsyncHelper(const CreateIntegrationResponseRequest& request, const CreateIntegrationResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, CreateIntegrationResponse(request), context);\n}\n\nCreateModelOutcome ApiGatewayV2Client::CreateModel(const CreateModelRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"CreateModel\", \"Required field: ApiId, is not set\");\n    return CreateModelOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/models\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return CreateModelOutcome(CreateModelResult(outcome.GetResult()));\n  }\n  else\n  {\n    return CreateModelOutcome(outcome.GetError());\n  }\n}\n\nCreateModelOutcomeCallable ApiGatewayV2Client::CreateModelCallable(const CreateModelRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< CreateModelOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateModel(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::CreateModelAsync(const CreateModelRequest& request, const CreateModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->CreateModelAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::CreateModelAsyncHelper(const CreateModelRequest& request, const CreateModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, CreateModel(request), context);\n}\n\nCreateRouteOutcome ApiGatewayV2Client::CreateRoute(const CreateRouteRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"CreateRoute\", \"Required field: ApiId, is not set\");\n    return CreateRouteOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/routes\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return CreateRouteOutcome(CreateRouteResult(outcome.GetResult()));\n  }\n  else\n  {\n    return CreateRouteOutcome(outcome.GetError());\n  }\n}\n\nCreateRouteOutcomeCallable ApiGatewayV2Client::CreateRouteCallable(const CreateRouteRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< CreateRouteOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateRoute(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::CreateRouteAsync(const CreateRouteRequest& request, const CreateRouteResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->CreateRouteAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::CreateRouteAsyncHelper(const CreateRouteRequest& request, const CreateRouteResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, CreateRoute(request), context);\n}\n\nCreateRouteResponseOutcome ApiGatewayV2Client::CreateRouteResponse(const CreateRouteResponseRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"CreateRouteResponse\", \"Required field: ApiId, is not set\");\n    return CreateRouteResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.RouteIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"CreateRouteResponse\", \"Required field: RouteId, is not set\");\n    return CreateRouteResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [RouteId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/routes\/\";\n  ss << request.GetRouteId();\n  ss << \"\/routeresponses\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return CreateRouteResponseOutcome(CreateRouteResponseResult(outcome.GetResult()));\n  }\n  else\n  {\n    return CreateRouteResponseOutcome(outcome.GetError());\n  }\n}\n\nCreateRouteResponseOutcomeCallable ApiGatewayV2Client::CreateRouteResponseCallable(const CreateRouteResponseRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< CreateRouteResponseOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateRouteResponse(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::CreateRouteResponseAsync(const CreateRouteResponseRequest& request, const CreateRouteResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->CreateRouteResponseAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::CreateRouteResponseAsyncHelper(const CreateRouteResponseRequest& request, const CreateRouteResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, CreateRouteResponse(request), context);\n}\n\nCreateStageOutcome ApiGatewayV2Client::CreateStage(const CreateStageRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"CreateStage\", \"Required field: ApiId, is not set\");\n    return CreateStageOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/stages\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return CreateStageOutcome(CreateStageResult(outcome.GetResult()));\n  }\n  else\n  {\n    return CreateStageOutcome(outcome.GetError());\n  }\n}\n\nCreateStageOutcomeCallable ApiGatewayV2Client::CreateStageCallable(const CreateStageRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< CreateStageOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateStage(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::CreateStageAsync(const CreateStageRequest& request, const CreateStageResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->CreateStageAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::CreateStageAsyncHelper(const CreateStageRequest& request, const CreateStageResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, CreateStage(request), context);\n}\n\nDeleteApiOutcome ApiGatewayV2Client::DeleteApi(const DeleteApiRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteApi\", \"Required field: ApiId, is not set\");\n    return DeleteApiOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return DeleteApiOutcome(NoResult());\n  }\n  else\n  {\n    return DeleteApiOutcome(outcome.GetError());\n  }\n}\n\nDeleteApiOutcomeCallable ApiGatewayV2Client::DeleteApiCallable(const DeleteApiRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< DeleteApiOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteApi(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::DeleteApiAsync(const DeleteApiRequest& request, const DeleteApiResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->DeleteApiAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::DeleteApiAsyncHelper(const DeleteApiRequest& request, const DeleteApiResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, DeleteApi(request), context);\n}\n\nDeleteApiMappingOutcome ApiGatewayV2Client::DeleteApiMapping(const DeleteApiMappingRequest& request) const\n{\n  if (!request.ApiMappingIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteApiMapping\", \"Required field: ApiMappingId, is not set\");\n    return DeleteApiMappingOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiMappingId]\", false));\n  }\n  if (!request.DomainNameHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteApiMapping\", \"Required field: DomainName, is not set\");\n    return DeleteApiMappingOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [DomainName]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/domainnames\/\";\n  ss << request.GetDomainName();\n  ss << \"\/apimappings\/\";\n  ss << request.GetApiMappingId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return DeleteApiMappingOutcome(NoResult());\n  }\n  else\n  {\n    return DeleteApiMappingOutcome(outcome.GetError());\n  }\n}\n\nDeleteApiMappingOutcomeCallable ApiGatewayV2Client::DeleteApiMappingCallable(const DeleteApiMappingRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< DeleteApiMappingOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteApiMapping(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::DeleteApiMappingAsync(const DeleteApiMappingRequest& request, const DeleteApiMappingResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->DeleteApiMappingAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::DeleteApiMappingAsyncHelper(const DeleteApiMappingRequest& request, const DeleteApiMappingResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, DeleteApiMapping(request), context);\n}\n\nDeleteAuthorizerOutcome ApiGatewayV2Client::DeleteAuthorizer(const DeleteAuthorizerRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteAuthorizer\", \"Required field: ApiId, is not set\");\n    return DeleteAuthorizerOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.AuthorizerIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteAuthorizer\", \"Required field: AuthorizerId, is not set\");\n    return DeleteAuthorizerOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [AuthorizerId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/authorizers\/\";\n  ss << request.GetAuthorizerId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return DeleteAuthorizerOutcome(NoResult());\n  }\n  else\n  {\n    return DeleteAuthorizerOutcome(outcome.GetError());\n  }\n}\n\nDeleteAuthorizerOutcomeCallable ApiGatewayV2Client::DeleteAuthorizerCallable(const DeleteAuthorizerRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< DeleteAuthorizerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteAuthorizer(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::DeleteAuthorizerAsync(const DeleteAuthorizerRequest& request, const DeleteAuthorizerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->DeleteAuthorizerAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::DeleteAuthorizerAsyncHelper(const DeleteAuthorizerRequest& request, const DeleteAuthorizerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, DeleteAuthorizer(request), context);\n}\n\nDeleteDeploymentOutcome ApiGatewayV2Client::DeleteDeployment(const DeleteDeploymentRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteDeployment\", \"Required field: ApiId, is not set\");\n    return DeleteDeploymentOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.DeploymentIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteDeployment\", \"Required field: DeploymentId, is not set\");\n    return DeleteDeploymentOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [DeploymentId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/deployments\/\";\n  ss << request.GetDeploymentId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return DeleteDeploymentOutcome(NoResult());\n  }\n  else\n  {\n    return DeleteDeploymentOutcome(outcome.GetError());\n  }\n}\n\nDeleteDeploymentOutcomeCallable ApiGatewayV2Client::DeleteDeploymentCallable(const DeleteDeploymentRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< DeleteDeploymentOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteDeployment(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::DeleteDeploymentAsync(const DeleteDeploymentRequest& request, const DeleteDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->DeleteDeploymentAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::DeleteDeploymentAsyncHelper(const DeleteDeploymentRequest& request, const DeleteDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, DeleteDeployment(request), context);\n}\n\nDeleteDomainNameOutcome ApiGatewayV2Client::DeleteDomainName(const DeleteDomainNameRequest& request) const\n{\n  if (!request.DomainNameHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteDomainName\", \"Required field: DomainName, is not set\");\n    return DeleteDomainNameOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [DomainName]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/domainnames\/\";\n  ss << request.GetDomainName();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return DeleteDomainNameOutcome(NoResult());\n  }\n  else\n  {\n    return DeleteDomainNameOutcome(outcome.GetError());\n  }\n}\n\nDeleteDomainNameOutcomeCallable ApiGatewayV2Client::DeleteDomainNameCallable(const DeleteDomainNameRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< DeleteDomainNameOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteDomainName(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::DeleteDomainNameAsync(const DeleteDomainNameRequest& request, const DeleteDomainNameResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->DeleteDomainNameAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::DeleteDomainNameAsyncHelper(const DeleteDomainNameRequest& request, const DeleteDomainNameResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, DeleteDomainName(request), context);\n}\n\nDeleteIntegrationOutcome ApiGatewayV2Client::DeleteIntegration(const DeleteIntegrationRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteIntegration\", \"Required field: ApiId, is not set\");\n    return DeleteIntegrationOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.IntegrationIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteIntegration\", \"Required field: IntegrationId, is not set\");\n    return DeleteIntegrationOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [IntegrationId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/integrations\/\";\n  ss << request.GetIntegrationId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return DeleteIntegrationOutcome(NoResult());\n  }\n  else\n  {\n    return DeleteIntegrationOutcome(outcome.GetError());\n  }\n}\n\nDeleteIntegrationOutcomeCallable ApiGatewayV2Client::DeleteIntegrationCallable(const DeleteIntegrationRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< DeleteIntegrationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteIntegration(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::DeleteIntegrationAsync(const DeleteIntegrationRequest& request, const DeleteIntegrationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->DeleteIntegrationAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::DeleteIntegrationAsyncHelper(const DeleteIntegrationRequest& request, const DeleteIntegrationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, DeleteIntegration(request), context);\n}\n\nDeleteIntegrationResponseOutcome ApiGatewayV2Client::DeleteIntegrationResponse(const DeleteIntegrationResponseRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteIntegrationResponse\", \"Required field: ApiId, is not set\");\n    return DeleteIntegrationResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.IntegrationIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteIntegrationResponse\", \"Required field: IntegrationId, is not set\");\n    return DeleteIntegrationResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [IntegrationId]\", false));\n  }\n  if (!request.IntegrationResponseIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteIntegrationResponse\", \"Required field: IntegrationResponseId, is not set\");\n    return DeleteIntegrationResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [IntegrationResponseId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/integrations\/\";\n  ss << request.GetIntegrationId();\n  ss << \"\/integrationresponses\/\";\n  ss << request.GetIntegrationResponseId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return DeleteIntegrationResponseOutcome(NoResult());\n  }\n  else\n  {\n    return DeleteIntegrationResponseOutcome(outcome.GetError());\n  }\n}\n\nDeleteIntegrationResponseOutcomeCallable ApiGatewayV2Client::DeleteIntegrationResponseCallable(const DeleteIntegrationResponseRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< DeleteIntegrationResponseOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteIntegrationResponse(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::DeleteIntegrationResponseAsync(const DeleteIntegrationResponseRequest& request, const DeleteIntegrationResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->DeleteIntegrationResponseAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::DeleteIntegrationResponseAsyncHelper(const DeleteIntegrationResponseRequest& request, const DeleteIntegrationResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, DeleteIntegrationResponse(request), context);\n}\n\nDeleteModelOutcome ApiGatewayV2Client::DeleteModel(const DeleteModelRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteModel\", \"Required field: ApiId, is not set\");\n    return DeleteModelOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.ModelIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteModel\", \"Required field: ModelId, is not set\");\n    return DeleteModelOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ModelId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/models\/\";\n  ss << request.GetModelId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return DeleteModelOutcome(NoResult());\n  }\n  else\n  {\n    return DeleteModelOutcome(outcome.GetError());\n  }\n}\n\nDeleteModelOutcomeCallable ApiGatewayV2Client::DeleteModelCallable(const DeleteModelRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< DeleteModelOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteModel(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::DeleteModelAsync(const DeleteModelRequest& request, const DeleteModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->DeleteModelAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::DeleteModelAsyncHelper(const DeleteModelRequest& request, const DeleteModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, DeleteModel(request), context);\n}\n\nDeleteRouteOutcome ApiGatewayV2Client::DeleteRoute(const DeleteRouteRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteRoute\", \"Required field: ApiId, is not set\");\n    return DeleteRouteOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.RouteIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteRoute\", \"Required field: RouteId, is not set\");\n    return DeleteRouteOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [RouteId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/routes\/\";\n  ss << request.GetRouteId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return DeleteRouteOutcome(NoResult());\n  }\n  else\n  {\n    return DeleteRouteOutcome(outcome.GetError());\n  }\n}\n\nDeleteRouteOutcomeCallable ApiGatewayV2Client::DeleteRouteCallable(const DeleteRouteRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< DeleteRouteOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteRoute(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::DeleteRouteAsync(const DeleteRouteRequest& request, const DeleteRouteResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->DeleteRouteAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::DeleteRouteAsyncHelper(const DeleteRouteRequest& request, const DeleteRouteResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, DeleteRoute(request), context);\n}\n\nDeleteRouteResponseOutcome ApiGatewayV2Client::DeleteRouteResponse(const DeleteRouteResponseRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteRouteResponse\", \"Required field: ApiId, is not set\");\n    return DeleteRouteResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.RouteIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteRouteResponse\", \"Required field: RouteId, is not set\");\n    return DeleteRouteResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [RouteId]\", false));\n  }\n  if (!request.RouteResponseIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteRouteResponse\", \"Required field: RouteResponseId, is not set\");\n    return DeleteRouteResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [RouteResponseId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/routes\/\";\n  ss << request.GetRouteId();\n  ss << \"\/routeresponses\/\";\n  ss << request.GetRouteResponseId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return DeleteRouteResponseOutcome(NoResult());\n  }\n  else\n  {\n    return DeleteRouteResponseOutcome(outcome.GetError());\n  }\n}\n\nDeleteRouteResponseOutcomeCallable ApiGatewayV2Client::DeleteRouteResponseCallable(const DeleteRouteResponseRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< DeleteRouteResponseOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteRouteResponse(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::DeleteRouteResponseAsync(const DeleteRouteResponseRequest& request, const DeleteRouteResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->DeleteRouteResponseAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::DeleteRouteResponseAsyncHelper(const DeleteRouteResponseRequest& request, const DeleteRouteResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, DeleteRouteResponse(request), context);\n}\n\nDeleteStageOutcome ApiGatewayV2Client::DeleteStage(const DeleteStageRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteStage\", \"Required field: ApiId, is not set\");\n    return DeleteStageOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.StageNameHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"DeleteStage\", \"Required field: StageName, is not set\");\n    return DeleteStageOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [StageName]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/stages\/\";\n  ss << request.GetStageName();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return DeleteStageOutcome(NoResult());\n  }\n  else\n  {\n    return DeleteStageOutcome(outcome.GetError());\n  }\n}\n\nDeleteStageOutcomeCallable ApiGatewayV2Client::DeleteStageCallable(const DeleteStageRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< DeleteStageOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteStage(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::DeleteStageAsync(const DeleteStageRequest& request, const DeleteStageResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->DeleteStageAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::DeleteStageAsyncHelper(const DeleteStageRequest& request, const DeleteStageResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, DeleteStage(request), context);\n}\n\nGetApiOutcome ApiGatewayV2Client::GetApi(const GetApiRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetApi\", \"Required field: ApiId, is not set\");\n    return GetApiOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetApiOutcome(GetApiResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetApiOutcome(outcome.GetError());\n  }\n}\n\nGetApiOutcomeCallable ApiGatewayV2Client::GetApiCallable(const GetApiRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetApiOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetApi(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetApiAsync(const GetApiRequest& request, const GetApiResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetApiAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetApiAsyncHelper(const GetApiRequest& request, const GetApiResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetApi(request), context);\n}\n\nGetApiMappingOutcome ApiGatewayV2Client::GetApiMapping(const GetApiMappingRequest& request) const\n{\n  if (!request.ApiMappingIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetApiMapping\", \"Required field: ApiMappingId, is not set\");\n    return GetApiMappingOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiMappingId]\", false));\n  }\n  if (!request.DomainNameHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetApiMapping\", \"Required field: DomainName, is not set\");\n    return GetApiMappingOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [DomainName]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/domainnames\/\";\n  ss << request.GetDomainName();\n  ss << \"\/apimappings\/\";\n  ss << request.GetApiMappingId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetApiMappingOutcome(GetApiMappingResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetApiMappingOutcome(outcome.GetError());\n  }\n}\n\nGetApiMappingOutcomeCallable ApiGatewayV2Client::GetApiMappingCallable(const GetApiMappingRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetApiMappingOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetApiMapping(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetApiMappingAsync(const GetApiMappingRequest& request, const GetApiMappingResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetApiMappingAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetApiMappingAsyncHelper(const GetApiMappingRequest& request, const GetApiMappingResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetApiMapping(request), context);\n}\n\nGetApiMappingsOutcome ApiGatewayV2Client::GetApiMappings(const GetApiMappingsRequest& request) const\n{\n  if (!request.DomainNameHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetApiMappings\", \"Required field: DomainName, is not set\");\n    return GetApiMappingsOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [DomainName]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/domainnames\/\";\n  ss << request.GetDomainName();\n  ss << \"\/apimappings\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetApiMappingsOutcome(GetApiMappingsResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetApiMappingsOutcome(outcome.GetError());\n  }\n}\n\nGetApiMappingsOutcomeCallable ApiGatewayV2Client::GetApiMappingsCallable(const GetApiMappingsRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetApiMappingsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetApiMappings(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetApiMappingsAsync(const GetApiMappingsRequest& request, const GetApiMappingsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetApiMappingsAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetApiMappingsAsyncHelper(const GetApiMappingsRequest& request, const GetApiMappingsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetApiMappings(request), context);\n}\n\nGetApisOutcome ApiGatewayV2Client::GetApis(const GetApisRequest& request) const\n{\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetApisOutcome(GetApisResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetApisOutcome(outcome.GetError());\n  }\n}\n\nGetApisOutcomeCallable ApiGatewayV2Client::GetApisCallable(const GetApisRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetApisOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetApis(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetApisAsync(const GetApisRequest& request, const GetApisResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetApisAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetApisAsyncHelper(const GetApisRequest& request, const GetApisResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetApis(request), context);\n}\n\nGetAuthorizerOutcome ApiGatewayV2Client::GetAuthorizer(const GetAuthorizerRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetAuthorizer\", \"Required field: ApiId, is not set\");\n    return GetAuthorizerOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.AuthorizerIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetAuthorizer\", \"Required field: AuthorizerId, is not set\");\n    return GetAuthorizerOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [AuthorizerId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/authorizers\/\";\n  ss << request.GetAuthorizerId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetAuthorizerOutcome(GetAuthorizerResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetAuthorizerOutcome(outcome.GetError());\n  }\n}\n\nGetAuthorizerOutcomeCallable ApiGatewayV2Client::GetAuthorizerCallable(const GetAuthorizerRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetAuthorizerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetAuthorizer(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetAuthorizerAsync(const GetAuthorizerRequest& request, const GetAuthorizerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetAuthorizerAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetAuthorizerAsyncHelper(const GetAuthorizerRequest& request, const GetAuthorizerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetAuthorizer(request), context);\n}\n\nGetAuthorizersOutcome ApiGatewayV2Client::GetAuthorizers(const GetAuthorizersRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetAuthorizers\", \"Required field: ApiId, is not set\");\n    return GetAuthorizersOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/authorizers\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetAuthorizersOutcome(GetAuthorizersResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetAuthorizersOutcome(outcome.GetError());\n  }\n}\n\nGetAuthorizersOutcomeCallable ApiGatewayV2Client::GetAuthorizersCallable(const GetAuthorizersRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetAuthorizersOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetAuthorizers(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetAuthorizersAsync(const GetAuthorizersRequest& request, const GetAuthorizersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetAuthorizersAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetAuthorizersAsyncHelper(const GetAuthorizersRequest& request, const GetAuthorizersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetAuthorizers(request), context);\n}\n\nGetDeploymentOutcome ApiGatewayV2Client::GetDeployment(const GetDeploymentRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetDeployment\", \"Required field: ApiId, is not set\");\n    return GetDeploymentOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.DeploymentIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetDeployment\", \"Required field: DeploymentId, is not set\");\n    return GetDeploymentOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [DeploymentId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/deployments\/\";\n  ss << request.GetDeploymentId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetDeploymentOutcome(GetDeploymentResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetDeploymentOutcome(outcome.GetError());\n  }\n}\n\nGetDeploymentOutcomeCallable ApiGatewayV2Client::GetDeploymentCallable(const GetDeploymentRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetDeploymentOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetDeployment(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetDeploymentAsync(const GetDeploymentRequest& request, const GetDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetDeploymentAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetDeploymentAsyncHelper(const GetDeploymentRequest& request, const GetDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetDeployment(request), context);\n}\n\nGetDeploymentsOutcome ApiGatewayV2Client::GetDeployments(const GetDeploymentsRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetDeployments\", \"Required field: ApiId, is not set\");\n    return GetDeploymentsOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/deployments\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetDeploymentsOutcome(GetDeploymentsResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetDeploymentsOutcome(outcome.GetError());\n  }\n}\n\nGetDeploymentsOutcomeCallable ApiGatewayV2Client::GetDeploymentsCallable(const GetDeploymentsRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetDeploymentsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetDeployments(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetDeploymentsAsync(const GetDeploymentsRequest& request, const GetDeploymentsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetDeploymentsAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetDeploymentsAsyncHelper(const GetDeploymentsRequest& request, const GetDeploymentsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetDeployments(request), context);\n}\n\nGetDomainNameOutcome ApiGatewayV2Client::GetDomainName(const GetDomainNameRequest& request) const\n{\n  if (!request.DomainNameHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetDomainName\", \"Required field: DomainName, is not set\");\n    return GetDomainNameOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [DomainName]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/domainnames\/\";\n  ss << request.GetDomainName();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetDomainNameOutcome(GetDomainNameResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetDomainNameOutcome(outcome.GetError());\n  }\n}\n\nGetDomainNameOutcomeCallable ApiGatewayV2Client::GetDomainNameCallable(const GetDomainNameRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetDomainNameOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetDomainName(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetDomainNameAsync(const GetDomainNameRequest& request, const GetDomainNameResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetDomainNameAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetDomainNameAsyncHelper(const GetDomainNameRequest& request, const GetDomainNameResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetDomainName(request), context);\n}\n\nGetDomainNamesOutcome ApiGatewayV2Client::GetDomainNames(const GetDomainNamesRequest& request) const\n{\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/domainnames\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetDomainNamesOutcome(GetDomainNamesResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetDomainNamesOutcome(outcome.GetError());\n  }\n}\n\nGetDomainNamesOutcomeCallable ApiGatewayV2Client::GetDomainNamesCallable(const GetDomainNamesRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetDomainNamesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetDomainNames(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetDomainNamesAsync(const GetDomainNamesRequest& request, const GetDomainNamesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetDomainNamesAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetDomainNamesAsyncHelper(const GetDomainNamesRequest& request, const GetDomainNamesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetDomainNames(request), context);\n}\n\nGetIntegrationOutcome ApiGatewayV2Client::GetIntegration(const GetIntegrationRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetIntegration\", \"Required field: ApiId, is not set\");\n    return GetIntegrationOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.IntegrationIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetIntegration\", \"Required field: IntegrationId, is not set\");\n    return GetIntegrationOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [IntegrationId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/integrations\/\";\n  ss << request.GetIntegrationId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetIntegrationOutcome(GetIntegrationResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetIntegrationOutcome(outcome.GetError());\n  }\n}\n\nGetIntegrationOutcomeCallable ApiGatewayV2Client::GetIntegrationCallable(const GetIntegrationRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetIntegrationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetIntegration(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetIntegrationAsync(const GetIntegrationRequest& request, const GetIntegrationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetIntegrationAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetIntegrationAsyncHelper(const GetIntegrationRequest& request, const GetIntegrationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetIntegration(request), context);\n}\n\nGetIntegrationResponseOutcome ApiGatewayV2Client::GetIntegrationResponse(const GetIntegrationResponseRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetIntegrationResponse\", \"Required field: ApiId, is not set\");\n    return GetIntegrationResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.IntegrationIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetIntegrationResponse\", \"Required field: IntegrationId, is not set\");\n    return GetIntegrationResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [IntegrationId]\", false));\n  }\n  if (!request.IntegrationResponseIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetIntegrationResponse\", \"Required field: IntegrationResponseId, is not set\");\n    return GetIntegrationResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [IntegrationResponseId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/integrations\/\";\n  ss << request.GetIntegrationId();\n  ss << \"\/integrationresponses\/\";\n  ss << request.GetIntegrationResponseId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetIntegrationResponseOutcome(GetIntegrationResponseResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetIntegrationResponseOutcome(outcome.GetError());\n  }\n}\n\nGetIntegrationResponseOutcomeCallable ApiGatewayV2Client::GetIntegrationResponseCallable(const GetIntegrationResponseRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetIntegrationResponseOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetIntegrationResponse(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetIntegrationResponseAsync(const GetIntegrationResponseRequest& request, const GetIntegrationResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetIntegrationResponseAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetIntegrationResponseAsyncHelper(const GetIntegrationResponseRequest& request, const GetIntegrationResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetIntegrationResponse(request), context);\n}\n\nGetIntegrationResponsesOutcome ApiGatewayV2Client::GetIntegrationResponses(const GetIntegrationResponsesRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetIntegrationResponses\", \"Required field: ApiId, is not set\");\n    return GetIntegrationResponsesOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.IntegrationIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetIntegrationResponses\", \"Required field: IntegrationId, is not set\");\n    return GetIntegrationResponsesOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [IntegrationId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/integrations\/\";\n  ss << request.GetIntegrationId();\n  ss << \"\/integrationresponses\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetIntegrationResponsesOutcome(GetIntegrationResponsesResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetIntegrationResponsesOutcome(outcome.GetError());\n  }\n}\n\nGetIntegrationResponsesOutcomeCallable ApiGatewayV2Client::GetIntegrationResponsesCallable(const GetIntegrationResponsesRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetIntegrationResponsesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetIntegrationResponses(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetIntegrationResponsesAsync(const GetIntegrationResponsesRequest& request, const GetIntegrationResponsesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetIntegrationResponsesAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetIntegrationResponsesAsyncHelper(const GetIntegrationResponsesRequest& request, const GetIntegrationResponsesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetIntegrationResponses(request), context);\n}\n\nGetIntegrationsOutcome ApiGatewayV2Client::GetIntegrations(const GetIntegrationsRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetIntegrations\", \"Required field: ApiId, is not set\");\n    return GetIntegrationsOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/integrations\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetIntegrationsOutcome(GetIntegrationsResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetIntegrationsOutcome(outcome.GetError());\n  }\n}\n\nGetIntegrationsOutcomeCallable ApiGatewayV2Client::GetIntegrationsCallable(const GetIntegrationsRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetIntegrationsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetIntegrations(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetIntegrationsAsync(const GetIntegrationsRequest& request, const GetIntegrationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetIntegrationsAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetIntegrationsAsyncHelper(const GetIntegrationsRequest& request, const GetIntegrationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetIntegrations(request), context);\n}\n\nGetModelOutcome ApiGatewayV2Client::GetModel(const GetModelRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetModel\", \"Required field: ApiId, is not set\");\n    return GetModelOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.ModelIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetModel\", \"Required field: ModelId, is not set\");\n    return GetModelOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ModelId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/models\/\";\n  ss << request.GetModelId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetModelOutcome(GetModelResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetModelOutcome(outcome.GetError());\n  }\n}\n\nGetModelOutcomeCallable ApiGatewayV2Client::GetModelCallable(const GetModelRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetModelOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetModel(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetModelAsync(const GetModelRequest& request, const GetModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetModelAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetModelAsyncHelper(const GetModelRequest& request, const GetModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetModel(request), context);\n}\n\nGetModelTemplateOutcome ApiGatewayV2Client::GetModelTemplate(const GetModelTemplateRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetModelTemplate\", \"Required field: ApiId, is not set\");\n    return GetModelTemplateOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.ModelIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetModelTemplate\", \"Required field: ModelId, is not set\");\n    return GetModelTemplateOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ModelId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/models\/\";\n  ss << request.GetModelId();\n  ss << \"\/template\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetModelTemplateOutcome(GetModelTemplateResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetModelTemplateOutcome(outcome.GetError());\n  }\n}\n\nGetModelTemplateOutcomeCallable ApiGatewayV2Client::GetModelTemplateCallable(const GetModelTemplateRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetModelTemplateOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetModelTemplate(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetModelTemplateAsync(const GetModelTemplateRequest& request, const GetModelTemplateResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetModelTemplateAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetModelTemplateAsyncHelper(const GetModelTemplateRequest& request, const GetModelTemplateResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetModelTemplate(request), context);\n}\n\nGetModelsOutcome ApiGatewayV2Client::GetModels(const GetModelsRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetModels\", \"Required field: ApiId, is not set\");\n    return GetModelsOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/models\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetModelsOutcome(GetModelsResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetModelsOutcome(outcome.GetError());\n  }\n}\n\nGetModelsOutcomeCallable ApiGatewayV2Client::GetModelsCallable(const GetModelsRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetModelsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetModels(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetModelsAsync(const GetModelsRequest& request, const GetModelsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetModelsAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetModelsAsyncHelper(const GetModelsRequest& request, const GetModelsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetModels(request), context);\n}\n\nGetRouteOutcome ApiGatewayV2Client::GetRoute(const GetRouteRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetRoute\", \"Required field: ApiId, is not set\");\n    return GetRouteOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.RouteIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetRoute\", \"Required field: RouteId, is not set\");\n    return GetRouteOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [RouteId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/routes\/\";\n  ss << request.GetRouteId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetRouteOutcome(GetRouteResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetRouteOutcome(outcome.GetError());\n  }\n}\n\nGetRouteOutcomeCallable ApiGatewayV2Client::GetRouteCallable(const GetRouteRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetRouteOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetRoute(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetRouteAsync(const GetRouteRequest& request, const GetRouteResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetRouteAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetRouteAsyncHelper(const GetRouteRequest& request, const GetRouteResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetRoute(request), context);\n}\n\nGetRouteResponseOutcome ApiGatewayV2Client::GetRouteResponse(const GetRouteResponseRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetRouteResponse\", \"Required field: ApiId, is not set\");\n    return GetRouteResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.RouteIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetRouteResponse\", \"Required field: RouteId, is not set\");\n    return GetRouteResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [RouteId]\", false));\n  }\n  if (!request.RouteResponseIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetRouteResponse\", \"Required field: RouteResponseId, is not set\");\n    return GetRouteResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [RouteResponseId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/routes\/\";\n  ss << request.GetRouteId();\n  ss << \"\/routeresponses\/\";\n  ss << request.GetRouteResponseId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetRouteResponseOutcome(GetRouteResponseResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetRouteResponseOutcome(outcome.GetError());\n  }\n}\n\nGetRouteResponseOutcomeCallable ApiGatewayV2Client::GetRouteResponseCallable(const GetRouteResponseRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetRouteResponseOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetRouteResponse(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetRouteResponseAsync(const GetRouteResponseRequest& request, const GetRouteResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetRouteResponseAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetRouteResponseAsyncHelper(const GetRouteResponseRequest& request, const GetRouteResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetRouteResponse(request), context);\n}\n\nGetRouteResponsesOutcome ApiGatewayV2Client::GetRouteResponses(const GetRouteResponsesRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetRouteResponses\", \"Required field: ApiId, is not set\");\n    return GetRouteResponsesOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.RouteIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetRouteResponses\", \"Required field: RouteId, is not set\");\n    return GetRouteResponsesOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [RouteId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/routes\/\";\n  ss << request.GetRouteId();\n  ss << \"\/routeresponses\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetRouteResponsesOutcome(GetRouteResponsesResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetRouteResponsesOutcome(outcome.GetError());\n  }\n}\n\nGetRouteResponsesOutcomeCallable ApiGatewayV2Client::GetRouteResponsesCallable(const GetRouteResponsesRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetRouteResponsesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetRouteResponses(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetRouteResponsesAsync(const GetRouteResponsesRequest& request, const GetRouteResponsesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetRouteResponsesAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetRouteResponsesAsyncHelper(const GetRouteResponsesRequest& request, const GetRouteResponsesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetRouteResponses(request), context);\n}\n\nGetRoutesOutcome ApiGatewayV2Client::GetRoutes(const GetRoutesRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetRoutes\", \"Required field: ApiId, is not set\");\n    return GetRoutesOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/routes\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetRoutesOutcome(GetRoutesResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetRoutesOutcome(outcome.GetError());\n  }\n}\n\nGetRoutesOutcomeCallable ApiGatewayV2Client::GetRoutesCallable(const GetRoutesRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetRoutesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetRoutes(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetRoutesAsync(const GetRoutesRequest& request, const GetRoutesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetRoutesAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetRoutesAsyncHelper(const GetRoutesRequest& request, const GetRoutesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetRoutes(request), context);\n}\n\nGetStageOutcome ApiGatewayV2Client::GetStage(const GetStageRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetStage\", \"Required field: ApiId, is not set\");\n    return GetStageOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.StageNameHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetStage\", \"Required field: StageName, is not set\");\n    return GetStageOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [StageName]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/stages\/\";\n  ss << request.GetStageName();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetStageOutcome(GetStageResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetStageOutcome(outcome.GetError());\n  }\n}\n\nGetStageOutcomeCallable ApiGatewayV2Client::GetStageCallable(const GetStageRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetStageOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetStage(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetStageAsync(const GetStageRequest& request, const GetStageResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetStageAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetStageAsyncHelper(const GetStageRequest& request, const GetStageResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetStage(request), context);\n}\n\nGetStagesOutcome ApiGatewayV2Client::GetStages(const GetStagesRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"GetStages\", \"Required field: ApiId, is not set\");\n    return GetStagesOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/stages\";\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return GetStagesOutcome(GetStagesResult(outcome.GetResult()));\n  }\n  else\n  {\n    return GetStagesOutcome(outcome.GetError());\n  }\n}\n\nGetStagesOutcomeCallable ApiGatewayV2Client::GetStagesCallable(const GetStagesRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< GetStagesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetStages(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::GetStagesAsync(const GetStagesRequest& request, const GetStagesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->GetStagesAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::GetStagesAsyncHelper(const GetStagesRequest& request, const GetStagesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, GetStages(request), context);\n}\n\nUpdateApiOutcome ApiGatewayV2Client::UpdateApi(const UpdateApiRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateApi\", \"Required field: ApiId, is not set\");\n    return UpdateApiOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PATCH, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return UpdateApiOutcome(UpdateApiResult(outcome.GetResult()));\n  }\n  else\n  {\n    return UpdateApiOutcome(outcome.GetError());\n  }\n}\n\nUpdateApiOutcomeCallable ApiGatewayV2Client::UpdateApiCallable(const UpdateApiRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< UpdateApiOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateApi(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::UpdateApiAsync(const UpdateApiRequest& request, const UpdateApiResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->UpdateApiAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::UpdateApiAsyncHelper(const UpdateApiRequest& request, const UpdateApiResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, UpdateApi(request), context);\n}\n\nUpdateApiMappingOutcome ApiGatewayV2Client::UpdateApiMapping(const UpdateApiMappingRequest& request) const\n{\n  if (!request.ApiMappingIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateApiMapping\", \"Required field: ApiMappingId, is not set\");\n    return UpdateApiMappingOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiMappingId]\", false));\n  }\n  if (!request.DomainNameHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateApiMapping\", \"Required field: DomainName, is not set\");\n    return UpdateApiMappingOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [DomainName]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/domainnames\/\";\n  ss << request.GetDomainName();\n  ss << \"\/apimappings\/\";\n  ss << request.GetApiMappingId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PATCH, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return UpdateApiMappingOutcome(UpdateApiMappingResult(outcome.GetResult()));\n  }\n  else\n  {\n    return UpdateApiMappingOutcome(outcome.GetError());\n  }\n}\n\nUpdateApiMappingOutcomeCallable ApiGatewayV2Client::UpdateApiMappingCallable(const UpdateApiMappingRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< UpdateApiMappingOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateApiMapping(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::UpdateApiMappingAsync(const UpdateApiMappingRequest& request, const UpdateApiMappingResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->UpdateApiMappingAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::UpdateApiMappingAsyncHelper(const UpdateApiMappingRequest& request, const UpdateApiMappingResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, UpdateApiMapping(request), context);\n}\n\nUpdateAuthorizerOutcome ApiGatewayV2Client::UpdateAuthorizer(const UpdateAuthorizerRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateAuthorizer\", \"Required field: ApiId, is not set\");\n    return UpdateAuthorizerOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.AuthorizerIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateAuthorizer\", \"Required field: AuthorizerId, is not set\");\n    return UpdateAuthorizerOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [AuthorizerId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/authorizers\/\";\n  ss << request.GetAuthorizerId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PATCH, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return UpdateAuthorizerOutcome(UpdateAuthorizerResult(outcome.GetResult()));\n  }\n  else\n  {\n    return UpdateAuthorizerOutcome(outcome.GetError());\n  }\n}\n\nUpdateAuthorizerOutcomeCallable ApiGatewayV2Client::UpdateAuthorizerCallable(const UpdateAuthorizerRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< UpdateAuthorizerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateAuthorizer(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::UpdateAuthorizerAsync(const UpdateAuthorizerRequest& request, const UpdateAuthorizerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->UpdateAuthorizerAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::UpdateAuthorizerAsyncHelper(const UpdateAuthorizerRequest& request, const UpdateAuthorizerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, UpdateAuthorizer(request), context);\n}\n\nUpdateDeploymentOutcome ApiGatewayV2Client::UpdateDeployment(const UpdateDeploymentRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateDeployment\", \"Required field: ApiId, is not set\");\n    return UpdateDeploymentOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.DeploymentIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateDeployment\", \"Required field: DeploymentId, is not set\");\n    return UpdateDeploymentOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [DeploymentId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/deployments\/\";\n  ss << request.GetDeploymentId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PATCH, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return UpdateDeploymentOutcome(UpdateDeploymentResult(outcome.GetResult()));\n  }\n  else\n  {\n    return UpdateDeploymentOutcome(outcome.GetError());\n  }\n}\n\nUpdateDeploymentOutcomeCallable ApiGatewayV2Client::UpdateDeploymentCallable(const UpdateDeploymentRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< UpdateDeploymentOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateDeployment(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::UpdateDeploymentAsync(const UpdateDeploymentRequest& request, const UpdateDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->UpdateDeploymentAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::UpdateDeploymentAsyncHelper(const UpdateDeploymentRequest& request, const UpdateDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, UpdateDeployment(request), context);\n}\n\nUpdateDomainNameOutcome ApiGatewayV2Client::UpdateDomainName(const UpdateDomainNameRequest& request) const\n{\n  if (!request.DomainNameHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateDomainName\", \"Required field: DomainName, is not set\");\n    return UpdateDomainNameOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [DomainName]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/domainnames\/\";\n  ss << request.GetDomainName();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PATCH, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return UpdateDomainNameOutcome(UpdateDomainNameResult(outcome.GetResult()));\n  }\n  else\n  {\n    return UpdateDomainNameOutcome(outcome.GetError());\n  }\n}\n\nUpdateDomainNameOutcomeCallable ApiGatewayV2Client::UpdateDomainNameCallable(const UpdateDomainNameRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< UpdateDomainNameOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateDomainName(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::UpdateDomainNameAsync(const UpdateDomainNameRequest& request, const UpdateDomainNameResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->UpdateDomainNameAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::UpdateDomainNameAsyncHelper(const UpdateDomainNameRequest& request, const UpdateDomainNameResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, UpdateDomainName(request), context);\n}\n\nUpdateIntegrationOutcome ApiGatewayV2Client::UpdateIntegration(const UpdateIntegrationRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateIntegration\", \"Required field: ApiId, is not set\");\n    return UpdateIntegrationOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.IntegrationIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateIntegration\", \"Required field: IntegrationId, is not set\");\n    return UpdateIntegrationOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [IntegrationId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/integrations\/\";\n  ss << request.GetIntegrationId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PATCH, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return UpdateIntegrationOutcome(UpdateIntegrationResult(outcome.GetResult()));\n  }\n  else\n  {\n    return UpdateIntegrationOutcome(outcome.GetError());\n  }\n}\n\nUpdateIntegrationOutcomeCallable ApiGatewayV2Client::UpdateIntegrationCallable(const UpdateIntegrationRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< UpdateIntegrationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateIntegration(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::UpdateIntegrationAsync(const UpdateIntegrationRequest& request, const UpdateIntegrationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->UpdateIntegrationAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::UpdateIntegrationAsyncHelper(const UpdateIntegrationRequest& request, const UpdateIntegrationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, UpdateIntegration(request), context);\n}\n\nUpdateIntegrationResponseOutcome ApiGatewayV2Client::UpdateIntegrationResponse(const UpdateIntegrationResponseRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateIntegrationResponse\", \"Required field: ApiId, is not set\");\n    return UpdateIntegrationResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.IntegrationIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateIntegrationResponse\", \"Required field: IntegrationId, is not set\");\n    return UpdateIntegrationResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [IntegrationId]\", false));\n  }\n  if (!request.IntegrationResponseIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateIntegrationResponse\", \"Required field: IntegrationResponseId, is not set\");\n    return UpdateIntegrationResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [IntegrationResponseId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/integrations\/\";\n  ss << request.GetIntegrationId();\n  ss << \"\/integrationresponses\/\";\n  ss << request.GetIntegrationResponseId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PATCH, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return UpdateIntegrationResponseOutcome(UpdateIntegrationResponseResult(outcome.GetResult()));\n  }\n  else\n  {\n    return UpdateIntegrationResponseOutcome(outcome.GetError());\n  }\n}\n\nUpdateIntegrationResponseOutcomeCallable ApiGatewayV2Client::UpdateIntegrationResponseCallable(const UpdateIntegrationResponseRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< UpdateIntegrationResponseOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateIntegrationResponse(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::UpdateIntegrationResponseAsync(const UpdateIntegrationResponseRequest& request, const UpdateIntegrationResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->UpdateIntegrationResponseAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::UpdateIntegrationResponseAsyncHelper(const UpdateIntegrationResponseRequest& request, const UpdateIntegrationResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, UpdateIntegrationResponse(request), context);\n}\n\nUpdateModelOutcome ApiGatewayV2Client::UpdateModel(const UpdateModelRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateModel\", \"Required field: ApiId, is not set\");\n    return UpdateModelOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.ModelIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateModel\", \"Required field: ModelId, is not set\");\n    return UpdateModelOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ModelId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/models\/\";\n  ss << request.GetModelId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PATCH, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return UpdateModelOutcome(UpdateModelResult(outcome.GetResult()));\n  }\n  else\n  {\n    return UpdateModelOutcome(outcome.GetError());\n  }\n}\n\nUpdateModelOutcomeCallable ApiGatewayV2Client::UpdateModelCallable(const UpdateModelRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< UpdateModelOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateModel(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::UpdateModelAsync(const UpdateModelRequest& request, const UpdateModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->UpdateModelAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::UpdateModelAsyncHelper(const UpdateModelRequest& request, const UpdateModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, UpdateModel(request), context);\n}\n\nUpdateRouteOutcome ApiGatewayV2Client::UpdateRoute(const UpdateRouteRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateRoute\", \"Required field: ApiId, is not set\");\n    return UpdateRouteOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.RouteIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateRoute\", \"Required field: RouteId, is not set\");\n    return UpdateRouteOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [RouteId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/routes\/\";\n  ss << request.GetRouteId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PATCH, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return UpdateRouteOutcome(UpdateRouteResult(outcome.GetResult()));\n  }\n  else\n  {\n    return UpdateRouteOutcome(outcome.GetError());\n  }\n}\n\nUpdateRouteOutcomeCallable ApiGatewayV2Client::UpdateRouteCallable(const UpdateRouteRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< UpdateRouteOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateRoute(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::UpdateRouteAsync(const UpdateRouteRequest& request, const UpdateRouteResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->UpdateRouteAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::UpdateRouteAsyncHelper(const UpdateRouteRequest& request, const UpdateRouteResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, UpdateRoute(request), context);\n}\n\nUpdateRouteResponseOutcome ApiGatewayV2Client::UpdateRouteResponse(const UpdateRouteResponseRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateRouteResponse\", \"Required field: ApiId, is not set\");\n    return UpdateRouteResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.RouteIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateRouteResponse\", \"Required field: RouteId, is not set\");\n    return UpdateRouteResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [RouteId]\", false));\n  }\n  if (!request.RouteResponseIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateRouteResponse\", \"Required field: RouteResponseId, is not set\");\n    return UpdateRouteResponseOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [RouteResponseId]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/routes\/\";\n  ss << request.GetRouteId();\n  ss << \"\/routeresponses\/\";\n  ss << request.GetRouteResponseId();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PATCH, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return UpdateRouteResponseOutcome(UpdateRouteResponseResult(outcome.GetResult()));\n  }\n  else\n  {\n    return UpdateRouteResponseOutcome(outcome.GetError());\n  }\n}\n\nUpdateRouteResponseOutcomeCallable ApiGatewayV2Client::UpdateRouteResponseCallable(const UpdateRouteResponseRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< UpdateRouteResponseOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateRouteResponse(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::UpdateRouteResponseAsync(const UpdateRouteResponseRequest& request, const UpdateRouteResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->UpdateRouteResponseAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::UpdateRouteResponseAsyncHelper(const UpdateRouteResponseRequest& request, const UpdateRouteResponseResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, UpdateRouteResponse(request), context);\n}\n\nUpdateStageOutcome ApiGatewayV2Client::UpdateStage(const UpdateStageRequest& request) const\n{\n  if (!request.ApiIdHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateStage\", \"Required field: ApiId, is not set\");\n    return UpdateStageOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [ApiId]\", false));\n  }\n  if (!request.StageNameHasBeenSet())\n  {\n    AWS_LOGSTREAM_ERROR(\"UpdateStage\", \"Required field: StageName, is not set\");\n    return UpdateStageOutcome(Aws::Client::AWSError<ApiGatewayV2Errors>(ApiGatewayV2Errors::MISSING_PARAMETER, \"MISSING_PARAMETER\", \"Missing required field [StageName]\", false));\n  }\n  Aws::Http::URI uri = m_uri;\n  Aws::StringStream ss;\n  ss << \"\/v2\/apis\/\";\n  ss << request.GetApiId();\n  ss << \"\/stages\/\";\n  ss << request.GetStageName();\n  uri.SetPath(uri.GetPath() + ss.str());\n  JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PATCH, Aws::Auth::SIGV4_SIGNER);\n  if(outcome.IsSuccess())\n  {\n    return UpdateStageOutcome(UpdateStageResult(outcome.GetResult()));\n  }\n  else\n  {\n    return UpdateStageOutcome(outcome.GetError());\n  }\n}\n\nUpdateStageOutcomeCallable ApiGatewayV2Client::UpdateStageCallable(const UpdateStageRequest& request) const\n{\n  auto task = Aws::MakeShared< std::packaged_task< UpdateStageOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateStage(request); } );\n  auto packagedFunction = [task]() { (*task)(); };\n  m_executor->Submit(packagedFunction);\n  return task->get_future();\n}\n\nvoid ApiGatewayV2Client::UpdateStageAsync(const UpdateStageRequest& request, const UpdateStageResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  m_executor->Submit( [this, request, handler, context](){ this->UpdateStageAsyncHelper( request, handler, context ); } );\n}\n\nvoid ApiGatewayV2Client::UpdateStageAsyncHelper(const UpdateStageRequest& request, const UpdateStageResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const\n{\n  handler(this, request, UpdateStage(request), context);\n}\n\n","avg_line_length":45.9245768948,"max_line_length":252,"alphanum_fraction":0.7652836416,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1458,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/add include statements\n#include<iostream>\n#include \"dna.h\"\n\nusing std::cout; \nusing std::cin; \nusing std::string;\n\/\/add function(s) code here\n\n\nstring dna;\n\n\/\/ Content\ndouble get_gc_content(const string& dna)\n{\n    int c_count = 0; \n    int g_count = 0;\n    double sum_count;\n    double gc_content;   \n\n    for (int i = 0; dna[i] != '\\0'; i++)\n    {\n        if (dna[i] == 'c' || dna[i] == 'C')\n        {\n            c_count = c_count + 1;\n        }\n        else if (dna[i] == 'g' || dna[i] == 'G')\n        {\n            g_count = g_count + 1;\n        }\n\n    }\n    sum_count = c_count + g_count;\n    gc_content = sum_count \/ dna.length();\n\n    return gc_content;\n}\n\n\/\/ Reverse\nstring reverse_string(string dna)\n{\n    int copier = dna.length();\n    string new_dna;\n    \n    for(int i = copier-1; i >= 0; i--)\n      new_dna.push_back(dna[i]);\n\n    return new_dna;\n}\n\n\/\/ Compliment\nstring get_dna_complement(string dna)\n{\n    char ch1 = 'A';\n    char ch2 = 'T';\n    char ch3 = 'C';\n    char ch4 = 'G';\n    \n    string dna_copy = dna;\n\n    for (int i = 0; dna_copy[i]; ++i) \n    {\n        if (dna_copy[i] == ch1){\n        dna_copy[i] = ch2;\n        } \n        else if (dna_copy[i] == ch2){\n        dna_copy[i] = ch1;\n        }\n        else if (dna_copy[i] == ch3){\n        dna_copy[i] = ch4;\n        }    \n        else if (dna_copy[i] == ch4){\n        dna_copy[i] = ch3;\n        }\n    }\n\n    string out_put = reverse_string(dna_copy);\n   \n    return out_put;\n}\n","avg_line_length":18.0,"max_line_length":48,"alphanum_fraction":0.5048010974,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11042,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause-LBNL"],"max_stars_count":9.0,"content":"\/*\n * This software, which is provided in confidence, was prepared by employees of\n * Pacific Northwest National Labratory operated by Battelle Memorial Institute.\n * Battelle has certain unperfected rights in the software which should not be\n * copied or otherwise disseminated outside your organization without the\n * express written authorization from Battelle. All rights to the software are\n * reserved by Battelle. Battelle makes no warranty, express or implied, and\n * assumes no liability or responsibility for the use of this software.\n *\/\n\n\/*! \n * \\file input_OM_fixed.cpp\n * \\ingroup Objects\n * \\brief The InputOMFixed class source file.\n * \\author Sonny Kim\n *\/\n\n#include \"util\/base\/include\/definitions.h\"\n#include <xercesc\/dom\/DOMNode.hpp>\n#include <xercesc\/dom\/DOMNodeList.hpp>\n#include \"functions\/include\/input_OM_fixed.h\"\n#include \"functions\/include\/function_utils.h\"\n#include \"util\/base\/include\/xml_helper.h\"\n#include \"containers\/include\/scenario.h\"\n#include \"util\/base\/include\/model_time.h\"\n\nusing namespace std;\nusing namespace xercesc;\n\nextern Scenario* scenario;\n\n\/\/ static initialize.\nconst string InputOMFixed::XML_REPORTING_NAME = \"input-OM-fixed\";\n\n\/*! \\brief Get the XML node name in static form for comparison when parsing XML.\n*\n* This public function accesses the private constant string, XML_NAME. This way\n* the tag is always consistent for both read-in and output and can be easily\n* changed. The \"==\" operator that is used when parsing, required this second\n* function to return static.\n* \\note A function cannot be static and virtual.\n* \\author Josh Lurz, \n* \\return The constant XML_NAME as a static.\n*\/\nconst string& InputOMFixed::getXMLNameStatic() {\n    const static string XML_NAME = \"input-OM-fixed\";\n    return XML_NAME;\n}\n\n\/*! \\brief Get the XML name for reporting to XML file.\n*\n* This public function accesses the private constant string, XML_NAME. This way\n* the tag is always consistent for reporting outputs and can be easily\n* changed.\n* \\author Sonny Kim\n* \\return The constant XML_NAME.\n*\/\nconst string& InputOMFixed::getXMLReportingName() const{\n    return XML_REPORTING_NAME;\n}\n\n\/\/! Constructor\nInputOMFixed::InputOMFixed()\n: mAdjustedCosts( scenario->getModeltime()->getmaxper() ),\n  mAdjustedCoefficients( scenario->getModeltime()->getmaxper() ){\n}\n\n\/\/! Clone the input.\nInputOMFixed* InputOMFixed::clone() const {\n    return new InputOMFixed( *this );\n}\n\nbool InputOMFixed::isSameType( const string& aType ) const {\n    return aType == getXMLNameStatic();\n}\n\nvoid InputOMFixed::copyParam( const IInput* aInput,\n                              const int aPeriod )\n{\n    aInput->copyParamsInto( *this, aPeriod );\n}\n\nvoid InputOMFixed::copyParamsInto( InputOMFixed& aInput,\n                                   const int aPeriod ) const\n{\n    \/\/ Copy the coefficients forward. This is done to adjust for technical\n    \/\/ change which already occurred.\n    assert( aPeriod > 0 );\n    aInput.mAdjustedCoefficients[ aPeriod ] = mAdjustedCoefficients[ aPeriod - 1 ];\n}\n\nvoid InputOMFixed::XMLParse( const xercesc::DOMNode* node ) {\n    \/\/ TODO: Replace this with the restructured XMLParse.\n    \/\/ Make sure we were passed a valid node.\n    assert( node );\n\n    \/\/ get the name attribute.\n    mName = XMLHelper<string>::getAttr( node, \"name\" );\n\n    \/\/ get all child nodes.\n    const DOMNodeList* nodeList = node->getChildNodes();\n\n    \/\/ loop through the child nodes.\n    for( unsigned int i = 0; i < nodeList->getLength(); i++ ){\n        const DOMNode* curr = nodeList->item( i );\n        if( curr->getNodeType() == DOMNode::TEXT_NODE ){\n            continue;\n        }\n\n        const string nodeName = XMLHelper<string>::safeTranscode( curr->getNodeName() );\n        if ( nodeName == \"OM-fixed\" ) {\n            mOMFixed = XMLHelper<double>::getValue( curr );\n        }\n        \/\/ TODO: Create capacity factor for technology and use that instead.\n        else if( nodeName == \"capacity-factor\" ){\n            mCapacityFactor = XMLHelper<double>::getValue( curr );\n        }\n        else if( nodeName == \"tech-change\" ){\n            mTechChange = XMLHelper<double>::getValue( curr );\n        }\n        else {\n            ILogger& mainLog = ILogger::getLogger( \"main_log\" );\n            mainLog.setLevel( ILogger::WARNING );\n            mainLog << \"Unrecognized text string: \" << nodeName << \" found while parsing \"\n                    << getXMLNameStatic() << \".\" << endl;\n        }\n    }\n}\n\nvoid InputOMFixed::toInputXML( ostream& aOut,\n                               Tabs* aTabs ) const\n{\n    XMLWriteOpeningTag( getXMLNameStatic(), aOut, aTabs, mName );\n    XMLWriteElement( mOMFixed, \"OM-fixed\", aOut, aTabs );\n    XMLWriteElement( mCapacityFactor, \"capacity-factor\", aOut, aTabs );\n    XMLWriteElementCheckDefault( mTechChange, \"tech-change\", aOut, aTabs, Value( 0 ) );\n    XMLWriteClosingTag( getXMLNameStatic(), aOut, aTabs );\n}\n\nvoid InputOMFixed::toDebugXML( const int aPeriod,\n                               ostream& aOut,\n                               Tabs* aTabs ) const\n{\n    XMLWriteOpeningTag ( getXMLNameStatic(), aOut, aTabs, mName );\n    XMLWriteElement( mLevelizedOMFixedCost, \"levelized-OM-fixed\", aOut, aTabs );\n    XMLWriteElement( mOMFixed, \"OM-fixed\", aOut, aTabs );\n    XMLWriteElement( mCapacityFactor, \"capacity-factor\", aOut, aTabs );\n    XMLWriteElement( mTechChange, \"tech-change\", aOut, aTabs );\n    XMLWriteElement( mAdjustedCosts[ aPeriod ], \"adjusted-cost\", aOut, aTabs );\n    XMLWriteElement( mAdjustedCoefficients[ aPeriod ], \"adjusted-coef\", aOut, aTabs );\n    XMLWriteClosingTag( getXMLNameStatic(), aOut, aTabs );\n}\n\nvoid InputOMFixed::completeInit( const string& aRegionName,\n                                 const string& aSectorName,\n                                 const string& aSubsectorName,\n                                 const string& aTechName,\n                                 DependencyFinder* aDependencyFinder,\n                                 const IInfo* aTechInfo )\n{   \n    \/\/ completeInit() is called for each technology for each period\n    \/\/ so levelized O&M fixed cost calculation is done here.\n\n    mLevelizedOMFixedCost = calcLevelizedOMFixedCost();\n\n    \/\/ Initialize the adjusted costs in all periods to the base calculate\n    \/\/ levelized OM_fixed cost.\n    \/\/ These costs may be adjusted by the Technology, for instance for capture\n    \/\/ penalties.\n    mAdjustedCosts.assign( mAdjustedCosts.size(), mLevelizedOMFixedCost );\n}\n\n\/** Calculate the levelizd fixed O&M cost.\n *\n * \\param void \n * \\return Levelized fixed O&M cost.\n * \\author Sonny Kim\n *\/\ndouble InputOMFixed::calcLevelizedOMFixedCost( void ) const\n{\n    \/\/ TODO: Use technology's capacity factor.\n    \/\/ TODO: Use Value class for units conversion.\n    double levelizedOMFixedCost = mOMFixed \n\t\/ ( FunctionUtils::HOURS_PER_YEAR() * mCapacityFactor * FunctionUtils::GJ_PER_KWH() );\n\n    return levelizedOMFixedCost; \/\/ 1975$\/GJ\n}\n\nvoid InputOMFixed::initCalc( const string& aRegionName,\n                             const string& aSectorName,\n                             const bool aIsNewInvestmentPeriod,\n                             const bool aIsTrade,\n                             const int aPeriod )\n{\n    \/\/ Initialize the current coefficient to 1 if it has not \n    \/\/ been initialized through copyParam. It may be adjusted\n    \/\/ later when coefficients are copied forward.\n    mAdjustedCoefficients[ aPeriod ] = 1;\n}\n\ndouble InputOMFixed::getPrice( const string& aRegionName,\n                               const int aPeriod ) const\n{\n    assert( mAdjustedCosts[ aPeriod ].isInited() );\n    return mAdjustedCosts[ aPeriod ];\n}\n\nvoid InputOMFixed::setPrice( const string& aRegionName,\n                             const double aPrice,\n                             const int aPeriod ) \n{\n    mAdjustedCosts[ aPeriod ] = aPrice;\n}\n\ndouble InputOMFixed::getPhysicalDemand( const int aPeriod ) const {\n    return 0;\n}\n\nvoid InputOMFixed::setPhysicalDemand( double aPhysicalDemand,\n                                      const string& aRegionName,\n                                      const int aPeriod )\n{\n    \/\/ Does not add to the marketplace.\n}\n\ndouble InputOMFixed::getCO2EmissionsCoefficient( const string& aGHGName,\n                                                 const int aPeriod ) const\n{\n    \/\/ Capital cost inputs cannot have emissions coefficients.\n    return 0;\n}\n\ndouble InputOMFixed::getCoefficient( const int aPeriod ) const {\n    assert( mAdjustedCoefficients[ aPeriod ].isInited() );\n    return mAdjustedCoefficients[ aPeriod ];\n}\n\nvoid InputOMFixed::setCoefficient( const double aCoefficient,\n                                   const int aPeriod )\n{\n    mAdjustedCoefficients[ aPeriod ] = aCoefficient;\n}\n\nvoid InputOMFixed::tabulateFixedQuantity( const string& aRegionName,\n                                          const double aFixedOutput,\n                                          const bool aIsInvestmentPeriod,\n                                          const int aPeriod )\n{\n}\n\nvoid InputOMFixed::scaleCalibrationQuantity( const double aScaleFactor ){\n    \/\/ Capital cost inputs are not calibrated.\n}\n\ndouble InputOMFixed::getCalibrationQuantity( const int aPeriod ) const\n{\n    \/\/ Capital cost inputs are not calibrated.\n    return -1;\n}\n\nbool InputOMFixed::hasTypeFlag( const int aTypeFlag ) const {\n    return ( ( aTypeFlag & ~( IInput::OM_FIXED ) ) == 0 );\n}\n\ndouble InputOMFixed::getIncomeElasticity() const {\n    return 0;\n}\n\ndouble InputOMFixed::getPriceElasticity() const {\n    return 0;\n}\n\ndouble InputOMFixed::getTechChange( const int aPeriod ) const\n{\n    return mTechChange;\n}\n\nvoid InputOMFixed::doInterpolations( const int aYear, const int aPreviousYear,\n                                     const int aNextYear, const IInput* aPreviousInput,\n                                     const IInput* aNextInput )\n{\n    const InputOMFixed* prevOMInput = static_cast<const InputOMFixed*>( aPreviousInput );\n    const InputOMFixed* nextOMInput = static_cast<const InputOMFixed*>( aNextInput );\n    \n    \/*!\n     * \\pre We are given a valid InputOMFixed for the previous input.\n     *\/\n    assert( prevOMInput );\n    \n    \/*!\n     * \\pre We are given a valid InputOMFixed for the next input.\n     *\/\n    assert( nextOMInput );\n    \n    \/\/ tech change is just copied from the next input\n    mTechChange = nextOMInput->mTechChange;\n    \n    \/\/ interpolate the costs\n    mOMFixed = util::linearInterpolateY( aYear, aPreviousYear, aNextYear,\n                                         prevOMInput->mOMFixed, nextOMInput->mOMFixed );\n    mLevelizedOMFixedCost = util::linearInterpolateY( aYear, aPreviousYear, aNextYear,\n                                                      prevOMInput->mLevelizedOMFixedCost,\n                                                      nextOMInput->mLevelizedOMFixedCost );\n    \n    \/\/ interpolate capacity factor\n    mCapacityFactor = util::linearInterpolateY( aYear, aPreviousYear, aNextYear,\n                                                prevOMInput->mCapacityFactor, nextOMInput->mCapacityFactor );\n}\n","avg_line_length":35.7346278317,"max_line_length":109,"alphanum_fraction":0.6472559319,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":19744,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Copyright (c) 2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <vector>\n#include <string>\n#include <script\/sign.h>\n#include <script\/standard.h>\n#include <test\/test_sin.h>\n#include <boost\/test\/unit_test.hpp>\n#include <script\/descriptor.h>\n#include <utilstrencodings.h>\n\nnamespace {\n\nvoid CheckUnparsable(const std::string& prv, const std::string& pub)\n{\n    FlatSigningProvider keys_priv, keys_pub;\n    auto parse_priv = Parse(prv, keys_priv);\n    auto parse_pub = Parse(pub, keys_pub);\n    BOOST_CHECK(!parse_priv);\n    BOOST_CHECK(!parse_pub);\n}\n\nconstexpr int DEFAULT = 0;\nconstexpr int RANGE = 1; \/\/ Expected to be ranged descriptor\nconstexpr int HARDENED = 2; \/\/ Derivation needs access to private keys\nconstexpr int UNSOLVABLE = 4; \/\/ This descriptor is not expected to be solvable\nconstexpr int SIGNABLE = 8; \/\/ We can sign with this descriptor (this is not true when actual BIP32 derivation is used, as that's not integrated in our signing code)\n\nstd::string MaybeUseHInsteadOfApostrophy(std::string ret)\n{\n    if (InsecureRandBool()) {\n        while (true) {\n            auto it = ret.find(\"'\");\n            if (it != std::string::npos) {\n                ret[it] = 'h';\n            } else {\n                break;\n            }\n        }\n    }\n    return ret;\n}\n\nvoid Check(const std::string& prv, const std::string& pub, int flags, const std::vector<std::vector<std::string>>& scripts)\n{\n    FlatSigningProvider keys_priv, keys_pub;\n\n    \/\/ Check that parsing succeeds.\n    auto parse_priv = Parse(MaybeUseHInsteadOfApostrophy(prv), keys_priv);\n    auto parse_pub = Parse(MaybeUseHInsteadOfApostrophy(pub), keys_pub);\n    BOOST_CHECK(parse_priv);\n    BOOST_CHECK(parse_pub);\n\n    \/\/ Check private keys are extracted from the private version but not the public one.\n    BOOST_CHECK(keys_priv.keys.size());\n    BOOST_CHECK(!keys_pub.keys.size());\n\n    \/\/ Check that both versions serialize back to the public version.\n    std::string pub1 = parse_priv->ToString();\n    std::string pub2 = parse_priv->ToString();\n    BOOST_CHECK_EQUAL(pub, pub1);\n    BOOST_CHECK_EQUAL(pub, pub2);\n\n    \/\/ Check that both can be serialized with private key back to the private version, but not without private key.\n    std::string prv1, prv2;\n    BOOST_CHECK(parse_priv->ToPrivateString(keys_priv, prv1));\n    BOOST_CHECK_EQUAL(prv, prv1);\n    BOOST_CHECK(!parse_priv->ToPrivateString(keys_pub, prv1));\n    BOOST_CHECK(parse_pub->ToPrivateString(keys_priv, prv1));\n    BOOST_CHECK_EQUAL(prv, prv1);\n    BOOST_CHECK(!parse_pub->ToPrivateString(keys_pub, prv1));\n\n    \/\/ Check whether IsRange on both returns the expected result\n    BOOST_CHECK_EQUAL(parse_pub->IsRange(), (flags & RANGE) != 0);\n    BOOST_CHECK_EQUAL(parse_priv->IsRange(), (flags & RANGE) != 0);\n\n\n    \/\/ Is not ranged descriptor, only a single result is expected.\n    if (!(flags & RANGE)) assert(scripts.size() == 1);\n\n    size_t max = (flags & RANGE) ? scripts.size() : 3;\n    for (size_t i = 0; i < max; ++i) {\n        const auto& ref = scripts[(flags & RANGE) ? i : 0];\n        for (int t = 0; t < 2; ++t) {\n            FlatSigningProvider key_provider = (flags & HARDENED) ? keys_priv : keys_pub;\n            FlatSigningProvider script_provider;\n            std::vector<CScript> spks;\n            BOOST_CHECK((t ? parse_priv : parse_pub)->Expand(i, key_provider, spks, script_provider));\n            BOOST_CHECK_EQUAL(spks.size(), ref.size());\n            for (size_t n = 0; n < spks.size(); ++n) {\n                BOOST_CHECK_EQUAL(ref[n], HexStr(spks[n].begin(), spks[n].end()));\n                BOOST_CHECK_EQUAL(IsSolvable(Merge(key_provider, script_provider), spks[n]), (flags & UNSOLVABLE) == 0);\n\n                if (flags & SIGNABLE) {\n                    CMutableTransaction spend;\n                    spend.vin.resize(1);\n                    spend.vout.resize(1);\n                    BOOST_CHECK_MESSAGE(SignSignature(Merge(keys_priv, script_provider), spks[n], spend, 0, 1, SIGHASH_ALL), prv);\n                }\n            }\n\n        }\n    }\n}\n\n}\n\nBOOST_FIXTURE_TEST_SUITE(descriptor_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(descriptor_test)\n{\n    \/\/ Basic single-key compressed\n    Check(\"combo(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)\", \"combo(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)\", SIGNABLE, {{\"2103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bdac\",\"76a9149a1c78a507689f6f54b847ad1cef1e614ee23f1e88ac\",\"00149a1c78a507689f6f54b847ad1cef1e614ee23f1e\",\"a91484ab21b1b2fd065d4504ff693d832434b6108d7b87\"}});\n    Check(\"pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)\", \"pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)\", SIGNABLE, {{\"2103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bdac\"}});\n    Check(\"pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)\", \"pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)\", SIGNABLE, {{\"76a9149a1c78a507689f6f54b847ad1cef1e614ee23f1e88ac\"}});\n    Check(\"wpkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)\", \"wpkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)\", SIGNABLE, {{\"00149a1c78a507689f6f54b847ad1cef1e614ee23f1e\"}});\n    Check(\"sh(wpkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))\", \"sh(wpkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))\", SIGNABLE, {{\"a91484ab21b1b2fd065d4504ff693d832434b6108d7b87\"}});\n\n    \/\/ Basic single-key uncompressed\n    Check(\"combo(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)\", \"combo(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)\", SIGNABLE, {{\"4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235ac\",\"76a914b5bd079c4d57cc7fc28ecf8213a6b791625b818388ac\"}});\n    Check(\"pk(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)\", \"pk(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)\", SIGNABLE, {{\"4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235ac\"}});\n    Check(\"pkh(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)\", \"pkh(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)\", SIGNABLE, {{\"76a914b5bd079c4d57cc7fc28ecf8213a6b791625b818388ac\"}});\n    CheckUnparsable(\"wpkh(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)\", \"wpkh(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)\"); \/\/ No uncompressed keys in witness\n    CheckUnparsable(\"wsh(pk(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss))\", \"wsh(pk(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235))\"); \/\/ No uncompressed keys in witness\n    CheckUnparsable(\"sh(wpkh(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss))\", \"sh(wpkh(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235))\"); \/\/ No uncompressed keys in witness\n\n    \/\/ Some unconventional single-key constructions\n    Check(\"sh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))\", \"sh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))\", SIGNABLE, {{\"a9141857af51a5e516552b3086430fd8ce55f7c1a52487\"}});\n    Check(\"sh(pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))\", \"sh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))\", SIGNABLE, {{\"a9141a31ad23bf49c247dd531a623c2ef57da3c400c587\"}});\n    Check(\"wsh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))\", \"wsh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))\", SIGNABLE, {{\"00202e271faa2325c199d25d22e1ead982e45b64eeb4f31e73dbdf41bd4b5fec23fa\"}});\n    Check(\"wsh(pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))\", \"wsh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))\", SIGNABLE, {{\"0020338e023079b91c58571b20e602d7805fb808c22473cbc391a41b1bd3a192e75b\"}});\n    Check(\"sh(wsh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)))\", \"sh(wsh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))\", SIGNABLE, {{\"a91472d0c5a3bfad8c3e7bd5303a72b94240e80b6f1787\"}});\n    Check(\"sh(wsh(pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)))\", \"sh(wsh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))\", SIGNABLE, {{\"a914b61b92e2ca21bac1e72a3ab859a742982bea960a87\"}});\n\n    \/\/ Versions with BIP32 derivations\n    Check(\"combo(xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc)\", \"combo(xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL)\", SIGNABLE, {{\"2102d2b36900396c9282fa14628566582f206a5dd0bcc8d5e892611806cafb0301f0ac\",\"76a91431a507b815593dfc51ffc7245ae7e5aee304246e88ac\",\"001431a507b815593dfc51ffc7245ae7e5aee304246e\",\"a9142aafb926eb247cb18240a7f4c07983ad1f37922687\"}});\n    Check(\"pk(xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L\/0)\", \"pk(xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y\/0)\", DEFAULT, {{\"210379e45b3cf75f9c5f9befd8e9506fb962f6a9d185ac87001ec44a8d3df8d4a9e3ac\"}});\n    Check(\"pkh(xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U\/2147483647'\/0)\", \"pkh(xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB\/2147483647'\/0)\", HARDENED, {{\"76a914ebdc90806a9c4356c1c88e42216611e1cb4c1c1788ac\"}});\n    Check(\"wpkh(xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt\/1\/2\/*)\", \"wpkh(xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH\/1\/2\/*)\", RANGE, {{\"0014326b2249e3a25d5dc60935f044ee835d090ba859\"},{\"0014af0bd98abc2f2cae66e36896a39ffe2d32984fb7\"},{\"00141fa798efd1cbf95cebf912c031b8a4a6e9fb9f27\"}});\n    Check(\"sh(wpkh(xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi\/10\/20\/30\/40\/*'))\", \"sh(wpkh(xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8\/10\/20\/30\/40\/*'))\", RANGE | HARDENED, {{\"a9149a4d9901d6af519b2a23d4a2f51650fcba87ce7b87\"},{\"a914bed59fc0024fae941d6e20a3b44a109ae740129287\"},{\"a9148483aa1116eb9c05c482a72bada4b1db24af654387\"}});\n    Check(\"combo(xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334\/*)\", \"combo(xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV\/*)\", RANGE, {{\"2102df12b7035bdac8e3bab862a3a83d06ea6b17b6753d52edecba9be46f5d09e076ac\",\"76a914f90e3178ca25f2c808dc76624032d352fdbdfaf288ac\",\"0014f90e3178ca25f2c808dc76624032d352fdbdfaf2\",\"a91408f3ea8c68d4a7585bf9e8bda226723f70e445f087\"},{\"21032869a233c9adff9a994e4966e5b821fd5bac066da6c3112488dc52383b4a98ecac\",\"76a914a8409d1b6dfb1ed2a3e8aa5e0ef2ff26b15b75b788ac\",\"0014a8409d1b6dfb1ed2a3e8aa5e0ef2ff26b15b75b7\",\"a91473e39884cb71ae4e5ac9739e9225026c99763e6687\"}});\n    CheckUnparsable(\"pkh(xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U\/2147483648)\", \"pkh(xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB\/2147483648)\"); \/\/ BIP 32 path element overflow\n\n    \/\/ Multisig constructions\n    Check(\"multi(1,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)\", \"multi(1,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)\", SIGNABLE, {{\"512103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea23552ae\"}});\n    Check(\"sh(multi(2,xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L\/0))\", \"sh(multi(2,xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y\/0))\", DEFAULT, {{\"a91445a9a622a8b0a1269944be477640eedc447bbd8487\"}});\n    Check(\"wsh(multi(2,xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U\/2147483647'\/0,xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt\/1\/2\/*,xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi\/10\/20\/30\/40\/*'))\", \"wsh(multi(2,xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB\/2147483647'\/0,xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH\/1\/2\/*,xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8\/10\/20\/30\/40\/*'))\", HARDENED | RANGE, {{\"0020b92623201f3bb7c3771d45b2ad1d0351ea8fbf8cfe0a0e570264e1075fa1948f\"},{\"002036a08bbe4923af41cf4316817c93b8d37e2f635dd25cfff06bd50df6ae7ea203\"},{\"0020a96e7ab4607ca6b261bfe3245ffda9c746b28d3f59e83d34820ec0e2b36c139c\"}});\n    Check(\"sh(wsh(multi(16,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy,KwGNz6YCCQtYvFzMtrC6D3tKTKdBBboMrLTsjr2NYVBwapCkn7Mr,KxogYhiNfwxuswvXV66eFyKcCpm7dZ7TqHVqujHAVUjJxyivxQ9X,L2BUNduTSyZwZjwNHynQTF14mv2uz2NRq5n5sYWTb4FkkmqgEE9f,L1okJGHGn1kFjdXHKxXjwVVtmCMR2JA5QsbKCSpSb7ReQjezKeoD,KxDCNSST75HFPaW5QKpzHtAyaCQC7p9Vo3FYfi2u4dXD1vgMiboK,L5edQjFtnkcf5UWURn6UuuoFrabgDQUHdheKCziwN42aLwS3KizU,KzF8UWFcEC7BYTq8Go1xVimMkDmyNYVmXV5PV7RuDicvAocoPB8i,L3nHUboKG2w4VSJ5jYZ5CBM97oeK6YuKvfZxrefdShECcjEYKMWZ,KyjHo36dWkYhimKmVVmQTq3gERv3pnqA4xFCpvUgbGDJad7eS8WE,KwsfyHKRUTZPQtysN7M3tZ4GXTnuov5XRgjdF2XCG8faAPmFruRF,KzCUbGhN9LJhdeFfL9zQgTJMjqxdBKEekRGZX24hXdgCNCijkkap,KzgpMBwwsDLwkaC5UrmBgCYaBD2WgZ7PBoGYXR8KT7gCA9UTN5a3,KyBXTPy4T7YG4q9tcAM3LkvfRpD1ybHMvcJ2ehaWXaSqeGUxEdkP,KzJDe9iwJRPtKP2F2AoN6zBgzS7uiuAwhWCfGdNeYJ3PC1HNJ8M8,L1xbHrxynrqLKkoYc4qtoQPx6uy5qYXR5ZDYVYBSRmCV5piU3JG9)))\",\"sh(wsh(multi(16,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0,0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600,0362a74e399c39ed5593852a30147f2959b56bb827dfa3e60e464b02ccf87dc5e8,0261345b53de74a4d721ef877c255429961b7e43714171ac06168d7e08c542a8b8,02da72e8b46901a65d4374fe6315538d8f368557dda3a1dcf9ea903f3afe7314c8,0318c82dd0b53fd3a932d16e0ba9e278fcc937c582d5781be626ff16e201f72286,0297ccef1ef99f9d73dec9ad37476ddb232f1238aff877af19e72ba04493361009,02e502cfd5c3f972fe9a3e2a18827820638f96b6f347e54d63deb839011fd5765d,03e687710f0e3ebe81c1037074da939d409c0025f17eb86adb9427d28f0f7ae0e9,02c04d3a5274952acdbc76987f3184b346a483d43be40874624b29e3692c1df5af,02ed06e0f418b5b43a7ec01d1d7d27290fa15f75771cb69b642a51471c29c84acd,036d46073cbb9ffee90473f3da429abc8de7f8751199da44485682a989a4bebb24,02f5d1ff7c9029a80a4e36b9a5497027ef7f3e73384a4a94fbfe7c4e9164eec8bc,02e41deffd1b7cce11cde209a781adcffdabd1b91c0ba0375857a2bfd9302419f3,02d76625f7956a7fc505ab02556c23ee72d832f1bac391bcd2d3abce5710a13d06,0399eb0a5487515802dc14544cf10b3666623762fbed2ec38a3975716e2c29c232)))\", SIGNABLE, {{\"a9147fc63e13dc25e8a95a3cee3d9a714ac3afd96f1e87\"}});\n    CheckUnparsable(\"sh(multi(16,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy,KwGNz6YCCQtYvFzMtrC6D3tKTKdBBboMrLTsjr2NYVBwapCkn7Mr,KxogYhiNfwxuswvXV66eFyKcCpm7dZ7TqHVqujHAVUjJxyivxQ9X,L2BUNduTSyZwZjwNHynQTF14mv2uz2NRq5n5sYWTb4FkkmqgEE9f,L1okJGHGn1kFjdXHKxXjwVVtmCMR2JA5QsbKCSpSb7ReQjezKeoD,KxDCNSST75HFPaW5QKpzHtAyaCQC7p9Vo3FYfi2u4dXD1vgMiboK,L5edQjFtnkcf5UWURn6UuuoFrabgDQUHdheKCziwN42aLwS3KizU,KzF8UWFcEC7BYTq8Go1xVimMkDmyNYVmXV5PV7RuDicvAocoPB8i,L3nHUboKG2w4VSJ5jYZ5CBM97oeK6YuKvfZxrefdShECcjEYKMWZ,KyjHo36dWkYhimKmVVmQTq3gERv3pnqA4xFCpvUgbGDJad7eS8WE,KwsfyHKRUTZPQtysN7M3tZ4GXTnuov5XRgjdF2XCG8faAPmFruRF,KzCUbGhN9LJhdeFfL9zQgTJMjqxdBKEekRGZX24hXdgCNCijkkap,KzgpMBwwsDLwkaC5UrmBgCYaBD2WgZ7PBoGYXR8KT7gCA9UTN5a3,KyBXTPy4T7YG4q9tcAM3LkvfRpD1ybHMvcJ2ehaWXaSqeGUxEdkP,KzJDe9iwJRPtKP2F2AoN6zBgzS7uiuAwhWCfGdNeYJ3PC1HNJ8M8,L1xbHrxynrqLKkoYc4qtoQPx6uy5qYXR5ZDYVYBSRmCV5piU3JG9))\",\"sh(multi(16,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0,0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600,0362a74e399c39ed5593852a30147f2959b56bb827dfa3e60e464b02ccf87dc5e8,0261345b53de74a4d721ef877c255429961b7e43714171ac06168d7e08c542a8b8,02da72e8b46901a65d4374fe6315538d8f368557dda3a1dcf9ea903f3afe7314c8,0318c82dd0b53fd3a932d16e0ba9e278fcc937c582d5781be626ff16e201f72286,0297ccef1ef99f9d73dec9ad37476ddb232f1238aff877af19e72ba04493361009,02e502cfd5c3f972fe9a3e2a18827820638f96b6f347e54d63deb839011fd5765d,03e687710f0e3ebe81c1037074da939d409c0025f17eb86adb9427d28f0f7ae0e9,02c04d3a5274952acdbc76987f3184b346a483d43be40874624b29e3692c1df5af,02ed06e0f418b5b43a7ec01d1d7d27290fa15f75771cb69b642a51471c29c84acd,036d46073cbb9ffee90473f3da429abc8de7f8751199da44485682a989a4bebb24,02f5d1ff7c9029a80a4e36b9a5497027ef7f3e73384a4a94fbfe7c4e9164eec8bc,02e41deffd1b7cce11cde209a781adcffdabd1b91c0ba0375857a2bfd9302419f3,02d76625f7956a7fc505ab02556c23ee72d832f1bac391bcd2d3abce5710a13d06,0399eb0a5487515802dc14544cf10b3666623762fbed2ec38a3975716e2c29c232))\"); \/\/ P2SH does not fit 16 compressed pubkeys in a redeemscript\n\n    \/\/ Check for invalid nesting of structures\n    CheckUnparsable(\"sh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)\", \"sh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)\"); \/\/ P2SH needs a script, not a key\n    CheckUnparsable(\"sh(combo(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))\", \"sh(combo(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))\"); \/\/ Old must be top level\n    CheckUnparsable(\"wsh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)\", \"wsh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)\"); \/\/ P2WSH needs a script, not a key\n    CheckUnparsable(\"wsh(wpkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))\", \"wsh(wpkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))\"); \/\/ Cannot embed witness inside witness\n    CheckUnparsable(\"wsh(sh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)))\", \"wsh(sh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))\"); \/\/ Cannot embed P2SH inside P2WSH\n    CheckUnparsable(\"sh(sh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)))\", \"sh(sh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))\"); \/\/ Cannot embed P2SH inside P2SH\n    CheckUnparsable(\"wsh(wsh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)))\", \"wsh(wsh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))\"); \/\/ Cannot embed P2WSH inside P2WSH\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":120.3902439024,"max_line_length":2037,"alphanum_fraction":0.8554497569,"low_alphanum":false,"long_lines":true,"lexable":true}
{"size":28426,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Copyright (c) 2019 The OPALCOIN developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"qt\/opalcoin\/send.h\"\n#include \"qt\/opalcoin\/forms\/ui_send.h\"\n#include \"qt\/opalcoin\/addnewcontactdialog.h\"\n#include \"qt\/opalcoin\/qtutils.h\"\n#include \"qt\/opalcoin\/sendchangeaddressdialog.h\"\n#include \"qt\/opalcoin\/optionbutton.h\"\n#include \"qt\/opalcoin\/sendconfirmdialog.h\"\n#include \"qt\/opalcoin\/myaddressrow.h\"\n#include \"qt\/opalcoin\/guitransactionsutils.h\"\n#include \"clientmodel.h\"\n#include \"optionsmodel.h\"\n#include \"addresstablemodel.h\"\n#include \"coincontrol.h\"\n#include \"script\/standard.h\"\n#include \"zauop\/deterministicmint.h\"\n#include \"openuridialog.h\"\n#include \"zauopcontroldialog.h\"\n\nSendWidget::SendWidget(OPALCOINGUI* parent) :\n    PWidget(parent),\n    ui(new Ui::send),\n    coinIcon(new QPushButton()),\n    btnContacts(new QPushButton())\n{\n    ui->setupUi(this);\n\n    this->setStyleSheet(parent->styleSheet());\n\n    \/* Containers *\/\n    setCssProperty(ui->left, \"container\");\n    ui->left->setContentsMargins(0,20,0,20);\n    setCssProperty(ui->right, \"container-right\");\n    ui->right->setContentsMargins(20,10,20,20);\n\n    \/* Light Font *\/\n    QFont fontLight;\n    fontLight.setWeight(QFont::Light);\n\n    \/* Title *\/\n    ui->labelTitle->setText(tr(\"Send\"));\n    setCssProperty(ui->labelTitle, \"text-title-screen\");\n    ui->labelTitle->setFont(fontLight);\n\n    \/* Button Group *\/\n    ui->pushLeft->setText(\"AUOP\");\n    setCssProperty(ui->pushLeft, \"btn-check-left\");\n    ui->pushLeft->setChecked(true);\n    ui->pushRight->setText(\"zAUOP\");\n    setCssProperty(ui->pushRight, \"btn-check-right\");\n    ui->pushRight->setVisible(false);\n    ui->pushLeft->setVisible(false);\n\n    \/* Subtitle *\/\n    ui->labelSubtitle1->setText(tr(\"You can transfer public coins (AUOP)\"));\n    setCssProperty(ui->labelSubtitle1, \"text-subtitle\");\n\n    ui->labelSubtitle2->setText(tr(\"Select coin type to spend\"));\n    ui->labelSubtitle2->setVisible(false);\n    setCssProperty(ui->labelSubtitle2, \"text-subtitle\");\n\n    \/* Address *\/\n    ui->labelSubtitleAddress->setText(tr(\"Enter a OPALCOIN address or contact label\"));\n    setCssProperty(ui->labelSubtitleAddress, \"text-title\");\n\n\n    \/* Amount *\/\n    ui->labelSubtitleAmount->setText(tr(\"Amount\"));\n    setCssProperty(ui->labelSubtitleAmount, \"text-title\");\n\n    \/* Buttons *\/\n    ui->pushButtonFee->setText(tr(\"Customize fee\"));\n    setCssBtnSecondary(ui->pushButtonFee);\n\n    ui->pushButtonClear->setText(tr(\"Clear all\"));\n    setCssProperty(ui->pushButtonClear, \"btn-secundary-clear\");\n\n    ui->pushButtonAddRecipient->setText(tr(\"Add recipient\"));\n    setCssProperty(ui->pushButtonAddRecipient, \"btn-secundary-add\");\n\n    setCssBtnPrimary(ui->pushButtonSave);\n    ui->pushButtonReset->setText(tr(\"Reset to default\"));\n    setCssBtnSecondary(ui->pushButtonReset);\n\n    \/\/ Coin control\n    ui->btnCoinControl->setTitleClassAndText(\"btn-title-grey\", \"Coin Control\");\n    ui->btnCoinControl->setSubTitleClassAndText(\"text-subtitle\", \"Select the source of the coins.\");\n\n    \/\/ Change address option\n    ui->btnChangeAddress->setTitleClassAndText(\"btn-title-grey\", \"Change Address\");\n    ui->btnChangeAddress->setSubTitleClassAndText(\"text-subtitle\", \"Customize the change address.\");\n\n    \/\/ Uri\n    ui->btnUri->setTitleClassAndText(\"btn-title-grey\", \"Open URI\");\n    ui->btnUri->setSubTitleClassAndText(\"text-subtitle\", \"Parse a payment request.\");\n\n    connect(ui->pushButtonFee, SIGNAL(clicked()), this, SLOT(onChangeCustomFeeClicked()));\n    connect(ui->btnCoinControl, SIGNAL(clicked()), this, SLOT(onCoinControlClicked()));\n    connect(ui->btnChangeAddress, SIGNAL(clicked()), this, SLOT(onChangeAddressClicked()));\n    connect(ui->btnUri, SIGNAL(clicked()), this, SLOT(onOpenUriClicked()));\n    connect(ui->pushButtonReset, &QPushButton::clicked, [this](){ onResetCustomOptions(true); });\n\n    setCssProperty(ui->coinWidget, \"container-coin-type\");\n    setCssProperty(ui->labelLine, \"container-divider\");\n\n\n    \/\/ Total Send\n    ui->labelTitleTotalSend->setText(tr(\"Total to send\"));\n    setCssProperty(ui->labelTitleTotalSend, \"text-title\");\n\n    ui->labelAmountSend->setText(\"0.00 AUOP\");\n    setCssProperty(ui->labelAmountSend, \"text-body1\");\n\n    \/\/ Total Remaining\n    setCssProperty(ui->labelTitleTotalRemaining, \"text-title\");\n\n    setCssProperty(ui->labelAmountRemaining, \"text-body1\");\n\n    \/\/ Icon Send\n    ui->stackedWidget->addWidget(coinIcon);\n    coinIcon->show();\n    coinIcon->raise();\n\n    setCssProperty(coinIcon, \"coin-icon-auop\");\n\n    QSize BUTTON_SIZE = QSize(24, 24);\n    coinIcon->setMinimumSize(BUTTON_SIZE);\n    coinIcon->setMaximumSize(BUTTON_SIZE);\n\n    int posX = 0;\n    int posY = 20;\n    coinIcon->move(posX, posY);\n\n    \/\/ Entry\n    addEntry();\n\n    \/\/ Connect\n    connect(ui->pushLeft, &QPushButton::clicked, [this](){onAUOPSelected(true);});\n    connect(ui->pushRight,  &QPushButton::clicked, [this](){onAUOPSelected(false);});\n    connect(ui->pushButtonSave, SIGNAL(clicked()), this, SLOT(onSendClicked()));\n    connect(ui->pushButtonAddRecipient, SIGNAL(clicked()), this, SLOT(onAddEntryClicked()));\n    connect(ui->pushButtonClear, SIGNAL(clicked()), this, SLOT(clearAll()));\n}\n\nvoid SendWidget::refreshView(){\n    QString btnText;\n    if(ui->pushLeft->isChecked()){\n        btnText = tr(\"Send AUOP\");\n        ui->pushButtonAddRecipient->setVisible(true);\n    }else{\n        btnText = tr(\"Send zAUOP\");\n        ui->pushButtonAddRecipient->setVisible(false);\n    }\n    ui->pushButtonSave->setText(btnText);\n\n    refreshAmounts();\n}\n\nvoid SendWidget::refreshAmounts() {\n\n    CAmount total = 0;\n    QMutableListIterator<SendMultiRow*> it(entries);\n    while (it.hasNext()) {\n        SendMultiRow* entry = it.next();\n        CAmount amount = entry->getAmountValue();\n        if (amount > 0)\n            total += amount;\n    }\n\n    bool isZauop = ui->pushRight->isChecked();\n    nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit();\n\n    ui->labelAmountSend->setText(GUIUtil::formatBalance(total, nDisplayUnit, isZauop));\n\n    CAmount totalAmount = 0;\n    if (CoinControlDialog::coinControl->HasSelected()){\n        \/\/ Set remaining balance to the sum of the coinControl selected inputs\n        totalAmount = walletModel->getBalance(CoinControlDialog::coinControl) - total;\n        ui->labelTitleTotalRemaining->setText(tr(\"Total remaining from the selected UTXO\"));\n    } else {\n        \/\/ Wallet's balance\n        totalAmount = (isZauop ? walletModel->getZerocoinBalance() : walletModel->getBalance()) - total;\n        ui->labelTitleTotalRemaining->setText(tr(\"Total remaining\"));\n    }\n    ui->labelAmountRemaining->setText(\n            GUIUtil::formatBalance(\n                    totalAmount,\n                    nDisplayUnit,\n                    isZauop\n                    )\n    );\n}\n\nvoid SendWidget::loadClientModel(){\n    if (clientModel) {\n        connect(clientModel, &ClientModel::numBlocksChanged, [this](){\n            if (customFeeDialog) customFeeDialog->updateFee();\n        });\n    }\n}\n\nvoid SendWidget::loadWalletModel() {\n    if (walletModel && walletModel->getOptionsModel()) {\n        \/\/ display unit\n        nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit();\n\n        for(SendMultiRow *entry : entries){\n            if(entry){\n                entry->setWalletModel(walletModel);\n            }\n        }\n\n        \/\/ Refresh view\n        refreshView();\n\n        \/\/ TODO: This only happen when the coin control features are modified in other screen, check before do this if the wallet has another screen modifying it.\n        \/\/ Coin Control\n        \/\/connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool)));\n        \/\/ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures());\n        \/\/coinControlUpdateLabels();\n    }\n}\n\nvoid SendWidget::clearAll(){\n    onResetCustomOptions(false);\n    if(customFeeDialog) customFeeDialog->clear();\n    ui->pushButtonFee->setText(tr(\"Customize Fee\"));\n    if(walletModel) walletModel->setWalletDefaultFee();\n    clearEntries();\n    refreshAmounts();\n}\n\nvoid SendWidget::onResetCustomOptions(bool fRefreshAmounts){\n    CoinControlDialog::coinControl->SetNull();\n    ui->btnChangeAddress->setActive(false);\n    ui->btnCoinControl->setActive(false);\n    if (fRefreshAmounts) {\n        refreshAmounts();\n    }\n}\n\nvoid SendWidget::clearEntries(){\n    int num = entries.length();\n    for (int i = 0; i < num; ++i) {\n        ui->scrollAreaWidgetContents->layout()->takeAt(0)->widget()->deleteLater();\n    }\n    entries.clear();\n\n    addEntry();\n}\n\nvoid SendWidget::addEntry(){\n    if(entries.isEmpty()){\n        createEntry();\n    } else {\n        if (entries.length() == 1) {\n            SendMultiRow *entry = entries.at(0);\n            entry->hideLabels();\n            entry->setNumber(1);\n        }else if(entries.length() == MAX_SEND_POPUP_ENTRIES){\n            inform(tr(\"Maximum amount of outputs reached\"));\n            return;\n        }\n\n        SendMultiRow *sendMultiRow = createEntry();\n        sendMultiRow->setNumber(entries.length());\n        sendMultiRow->hideLabels();\n    }\n}\n\nSendMultiRow* SendWidget::createEntry(){\n    SendMultiRow *sendMultiRow = new SendMultiRow(this);\n    if(this->walletModel) sendMultiRow->setWalletModel(this->walletModel);\n    entries.append(sendMultiRow);\n    ui->scrollAreaWidgetContents->layout()->addWidget(sendMultiRow);\n    connect(sendMultiRow, &SendMultiRow::onContactsClicked, this, &SendWidget::onContactsClicked);\n    connect(sendMultiRow, &SendMultiRow::onMenuClicked, this, &SendWidget::onMenuClicked);\n    connect(sendMultiRow, &SendMultiRow::onValueChanged, this, &SendWidget::onValueChanged);\n    return sendMultiRow;\n}\n\nvoid SendWidget::onAddEntryClicked(){\n    \/\/ Check prev valid entries before add a new one.\n    for (SendMultiRow* entry : entries){\n        if(!entry || !entry->validate()) {\n            inform(tr(\"Invalid entry, previous entries must be valid before add a new one\"));\n            return;\n        }\n    }\n    addEntry();\n}\n\nvoid SendWidget::resizeEvent(QResizeEvent *event){\n    resizeMenu();\n    QWidget::resizeEvent(event);\n}\n\n\nvoid SendWidget::onSendClicked(){\n\n    if (!walletModel || !walletModel->getOptionsModel())\n        return;\n\n    QList<SendCoinsRecipient> recipients;\n\n    for (SendMultiRow* entry : entries){\n        \/\/ TODO: Check UTXO splitter here..\n        \/\/ Validate send..\n        if(entry && entry->validate()) {\n            recipients.append(entry->getValue());\n        }else{\n            inform(tr(\"Invalid entry\"));\n            return;\n        }\n    }\n\n    if (recipients.isEmpty()) {\n        inform(tr(\"No set recipients\"));\n        return;\n    }\n\n    bool sendAUOP = ui->pushLeft->isChecked();\n\n    \/\/ request unlock only if was locked or unlocked for mixing:\n    \/\/ this way we let users unlock by walletpassphrase or by menu\n    \/\/ and make many transactions while unlocking through this dialog\n    \/\/ will call relock\n    if(!GUIUtil::requestUnlock(walletModel, sendAUOP ? AskPassphraseDialog::Context::Send_AUOP : AskPassphraseDialog::Context::Send_zAUOP, true)){\n        \/\/ Unlock wallet was cancelled\n        inform(tr(\"Cannot send, wallet locked\"));\n        return;\n    }\n\n    if((sendAUOP) ? send(recipients) : sendZauop(recipients)) {\n        updateEntryLabels(recipients);\n    }\n}\n\nbool SendWidget::send(QList<SendCoinsRecipient> recipients){\n    \/\/ prepare transaction for getting txFee earlier\n    WalletModelTransaction currentTransaction(recipients);\n    WalletModel::SendCoinsReturn prepareStatus;\n\n    prepareStatus = walletModel->prepareTransaction(currentTransaction, CoinControlDialog::coinControl);\n\n    \/\/ process prepareStatus and on error generate message shown to user\n    GuiTransactionsUtils::ProcessSendCoinsReturn(\n            this,\n            prepareStatus,\n            walletModel,\n            BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(),\n                                         currentTransaction.getTransactionFee()),\n            true\n    );\n\n    if (prepareStatus.status != WalletModel::OK) {\n        inform(tr(\"Cannot create transaction.\"));\n        return false;\n    }\n\n    showHideOp(true);\n    QString warningStr = QString();\n    if (currentTransaction.getTransaction()->fStakeDelegationVoided)\n        warningStr = tr(\"WARNING:\\nTransaction spends a cold-stake delegation, voiding it.\\n\"\n                     \"These coins will no longer be cold-staked.\");\n    TxDetailDialog* dialog = new TxDetailDialog(window, true, warningStr);\n    dialog->setDisplayUnit(walletModel->getOptionsModel()->getDisplayUnit());\n    dialog->setData(walletModel, currentTransaction);\n    dialog->adjustSize();\n    openDialogWithOpaqueBackgroundY(dialog, window, 3, 5);\n\n    if(dialog->isConfirm()){\n        \/\/ now send the prepared transaction\n        WalletModel::SendCoinsReturn sendStatus = dialog->getStatus();\n        \/\/ process sendStatus and on error generate message shown to user\n        GuiTransactionsUtils::ProcessSendCoinsReturn(\n                this,\n                sendStatus,\n                walletModel\n        );\n\n        if (sendStatus.status == WalletModel::OK) {\n            clearAll();\n            inform(tr(\"Transaction sent\"));\n            dialog->deleteLater();\n            return true;\n        }\n    }\n\n    dialog->deleteLater();\n    return false;\n}\n\nbool SendWidget::sendZauop(QList<SendCoinsRecipient> recipients){\n    if (!walletModel || !walletModel->getOptionsModel())\n        return false;\n\n    if(sporkManager.IsSporkActive(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) {\n        emit message(tr(\"Spend Zerocoin\"), tr(\"zAUOP is currently undergoing maintenance.\"), CClientUIInterface::MSG_ERROR);\n        return false;\n    }\n\n    std::list<std::pair<CBitcoinAddress*, CAmount>> outputs;\n    CAmount total = 0;\n    for (SendCoinsRecipient rec : recipients){\n        total += rec.amount;\n        outputs.push_back(std::pair<CBitcoinAddress*, CAmount>(new CBitcoinAddress(rec.address.toStdString()),rec.amount));\n    }\n\n    \/\/ use mints from zAUOP selector if applicable\n    std::vector<CMintMeta> vMintsToFetch;\n    std::vector<CZerocoinMint> vMintsSelected;\n    if (!ZAUOPControlDialog::setSelectedMints.empty()) {\n        vMintsToFetch = ZAUOPControlDialog::GetSelectedMints();\n\n        for (auto& meta : vMintsToFetch) {\n            CZerocoinMint mint;\n            if (!walletModel->getMint(meta.hashSerial, mint)){\n                inform(tr(\"Coin control mint not found\"));\n                return false;\n            }\n            vMintsSelected.emplace_back(mint);\n        }\n    }\n\n    QString sendBody = outputs.size() == 1 ?\n            tr(\"Sending %1 to address %2\\n\")\n            .arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), total, false, BitcoinUnits::separatorAlways))\n            .arg(recipients.first().address)\n            :\n           tr(\"Sending %1 to addresses:\\n%2\")\n           .arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), total, false, BitcoinUnits::separatorAlways))\n           .arg(recipientsToString(recipients));\n\n    bool ret = false;\n    emit message(\n            tr(\"Spend Zerocoin\"),\n            sendBody,\n            CClientUIInterface::MSG_INFORMATION | CClientUIInterface::BTN_MASK | CClientUIInterface::MODAL,\n            &ret);\n\n    if(!ret) return false;\n\n    CZerocoinSpendReceipt receipt;\n\n    std::string changeAddress = \"\";\n    if(!boost::get<CNoDestination>(&CoinControlDialog::coinControl->destChange)){\n        changeAddress = CBitcoinAddress(CoinControlDialog::coinControl->destChange).ToString();\n    }else{\n        changeAddress = walletModel->getAddressTableModel()->getAddressToShow().toStdString();\n    }\n\n    if (walletModel->sendZauop(\n            vMintsSelected,\n            true,\n            true,\n            receipt,\n            outputs,\n            changeAddress\n    )\n            ) {\n        inform(tr(\"zAUOP transaction sent!\"));\n        ZAUOPControlDialog::setSelectedMints.clear();\n        clearAll();\n        return true;\n    } else {\n        QString body;\n        if (receipt.GetStatus() == ZAUOP_SPEND_V1_SEC_LEVEL) {\n            body = tr(\"Version 1 zAUOP require a security level of 100 to successfully spend.\");\n        } else {\n            int nNeededSpends = receipt.GetNeededSpends(); \/\/ Number of spends we would need for this transaction\n            const int nMaxSpends = Params().Zerocoin_MaxSpendsPerTransaction(); \/\/ Maximum possible spends for one zAUOP transaction\n            if (nNeededSpends > nMaxSpends) {\n                body = tr(\"Too much inputs (\") + QString::number(nNeededSpends, 10) +\n                       tr(\") needed.\\nMaximum allowed: \") + QString::number(nMaxSpends, 10);\n                body += tr(\n                        \"\\nEither mint higher denominations (so fewer inputs are needed) or reduce the amount to spend.\");\n            } else {\n                body = QString::fromStdString(receipt.GetStatusMessage());\n            }\n        }\n        emit message(\"zAUOP transaction failed\", body, CClientUIInterface::MSG_ERROR);\n        return false;\n    }\n}\n\nQString SendWidget::recipientsToString(QList<SendCoinsRecipient> recipients){\n    QString s = \"\";\n    for (SendCoinsRecipient rec : recipients){\n        s += rec.address + \" -> \" + BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), rec.amount, false, BitcoinUnits::separatorAlways) + \"\\n\";\n    }\n    return s;\n}\n\nvoid SendWidget::updateEntryLabels(QList<SendCoinsRecipient> recipients){\n    for (SendCoinsRecipient rec : recipients){\n        QString label = rec.label;\n        if(!label.isNull()) {\n            QString labelOld = walletModel->getAddressTableModel()->labelForAddress(rec.address);\n            if(label.compare(labelOld) != 0) {\n                CTxDestination dest = CBitcoinAddress(rec.address.toStdString()).Get();\n                if (!walletModel->updateAddressBookLabels(dest, label.toStdString(),\n                                                          this->walletModel->isMine(dest) ? \"receive\" : \"send\")) {\n                    \/\/ Label update failed\n                    emit message(\"\", tr(\"Address label update failed for address: %1\").arg(rec.address), CClientUIInterface::MSG_ERROR);\n                    return;\n                }\n            }\n        }\n\n    }\n}\n\n\nvoid SendWidget::onChangeAddressClicked(){\n    showHideOp(true);\n    SendChangeAddressDialog* dialog = new SendChangeAddressDialog(window);\n    if(!boost::get<CNoDestination>(&CoinControlDialog::coinControl->destChange)){\n        dialog->setAddress(QString::fromStdString(CBitcoinAddress(CoinControlDialog::coinControl->destChange).ToString()));\n    }\n    if(openDialogWithOpaqueBackgroundY(dialog, window, 3, 5)) {\n        if(dialog->selected) {\n            QString ret;\n            if (dialog->getAddress(walletModel, &ret)) {\n                CoinControlDialog::coinControl->destChange = CBitcoinAddress(ret.toStdString()).Get();\n                ui->btnChangeAddress->setActive(true);\n            }else{\n                inform(tr(\"Invalid change address\"));\n                ui->btnChangeAddress->setActive(false);\n            }\n        }\n    }\n    dialog->deleteLater();\n}\n\nvoid SendWidget::onOpenUriClicked(){\n    showHideOp(true);\n    OpenURIDialog *dlg = new OpenURIDialog(window);\n    if (openDialogWithOpaqueBackgroundY(dlg, window, 3, 5)) {\n\n        SendCoinsRecipient rcp;\n        if (!GUIUtil::parseBitcoinURI(dlg->getURI(), &rcp)) {\n            inform(tr(\"Invalid URI\"));\n            return;\n        }\n        if (!walletModel->validateAddress(rcp.address)) {\n            inform(tr(\"Invalid address in URI\"));\n            return;\n        }\n\n        int listSize = entries.size();\n        if (listSize == 1) {\n            SendMultiRow *entry = entries[0];\n            entry->setAddressAndLabelOrDescription(rcp.address, rcp.message);\n            entry->setAmount(BitcoinUnits::format(nDisplayUnit, rcp.amount, false));\n        } else {\n            \/\/ Use the last one if it's invalid or add a new one\n            SendMultiRow *entry = entries[listSize - 1];\n            if (!entry->validate()) {\n                addEntry();\n                entry = entries[listSize];\n            }\n            entry->setAddressAndLabelOrDescription(rcp.address, rcp.message);\n            entry->setAmount(BitcoinUnits::format(nDisplayUnit, rcp.amount, false));\n        }\n        emit receivedURI(dlg->getURI());\n    }\n    dlg->deleteLater();\n}\n\nvoid SendWidget::onChangeCustomFeeClicked(){\n    showHideOp(true);\n    if (!customFeeDialog) {\n        customFeeDialog = new SendCustomFeeDialog(window);\n        customFeeDialog->setWalletModel(walletModel);\n    }\n    if (openDialogWithOpaqueBackgroundY(customFeeDialog, window, 3, 5)){\n        ui->pushButtonFee->setText(tr(\"Custom Fee %1\").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, customFeeDialog->getFeeRate().GetFeePerK()) + \"\/kB\"));\n        isCustomFeeSelected = true;\n        walletModel->setWalletDefaultFee(customFeeDialog->getFeeRate().GetFeePerK());\n    } else {\n        ui->pushButtonFee->setText(tr(\"Customize Fee\"));\n        isCustomFeeSelected = false;\n        walletModel->setWalletDefaultFee();\n    }\n}\n\nvoid SendWidget::onCoinControlClicked(){\n    if(isAUOP){\n        if (walletModel->getBalance() > 0) {\n            if (!coinControlDialog) {\n                coinControlDialog = new CoinControlDialog();\n                coinControlDialog->setModel(walletModel);\n            } else {\n                coinControlDialog->refreshDialog();\n            }\n            coinControlDialog->exec();\n            ui->btnCoinControl->setActive(CoinControlDialog::coinControl->HasSelected());\n            refreshAmounts();\n        } else {\n            inform(tr(\"You don't have any AUOP to select.\"));\n        }\n    }else{\n        if (walletModel->getZerocoinBalance() > 0) {\n            ZAUOPControlDialog *zAUOPControl = new ZAUOPControlDialog(this);\n            zAUOPControl->setModel(walletModel);\n            zAUOPControl->exec();\n            ui->btnCoinControl->setActive(!ZAUOPControlDialog::setSelectedMints.empty());\n            zAUOPControl->deleteLater();\n        } else {\n            inform(tr(\"You don't have any zAUOP in your balance to select.\"));\n        }\n    }\n}\n\nvoid SendWidget::onValueChanged() {\n    refreshAmounts();\n}\n\nvoid SendWidget::onAUOPSelected(bool _isAUOP){\n    isAUOP = _isAUOP;\n    setCssProperty(coinIcon, _isAUOP ? \"coin-icon-auop\" : \"coin-icon-zauop\");\n    refreshView();\n    updateStyle(coinIcon);\n}\n\nvoid SendWidget::onContactsClicked(SendMultiRow* entry){\n    focusedEntry = entry;\n    if(menu && menu->isVisible()){\n        menu->hide();\n    }\n\n    int contactsSize = walletModel->getAddressTableModel()->sizeSend();\n    if(contactsSize == 0) {\n        inform(tr(\"No contacts available, you can go to the contacts screen and add some there!\"));\n        return;\n    }\n\n    int height = (contactsSize <= 2) ? entry->getEditHeight() * ( 2 * (contactsSize + 1 )) : entry->getEditHeight() * 4;\n    int width = entry->getEditWidth();\n\n    if(!menuContacts){\n        menuContacts = new ContactsDropdown(\n                    width,\n                    height,\n                    this\n        );\n        menuContacts->setWalletModel(walletModel, AddressTableModel::Send);\n        connect(menuContacts, &ContactsDropdown::contactSelected, [this](QString address, QString label){\n            if(focusedEntry){\n                focusedEntry->setLabel(label);\n                focusedEntry->setAddress(address);\n            }\n        });\n\n    }\n\n    if(menuContacts->isVisible()){\n        menuContacts->hide();\n        return;\n    }\n\n    menuContacts->resizeList(width, height);\n    menuContacts->setStyleSheet(this->styleSheet());\n    menuContacts->adjustSize();\n\n    QPoint pos;\n    if (entries.size() > 1){\n        pos = entry->pos();\n        pos.setY((pos.y() + (focusedEntry->getEditHeight() - 12) * 4));\n    } else {\n        pos = focusedEntry->getEditLineRect().bottomLeft();\n        pos.setY((pos.y() + (focusedEntry->getEditHeight() - 12) * 3));\n    }\n    pos.setX(pos.x() + 20);\n    menuContacts->move(pos);\n    menuContacts->show();\n}\n\nvoid SendWidget::onMenuClicked(SendMultiRow* entry){\n    focusedEntry = entry;\n    if(menuContacts && menuContacts->isVisible()){\n        menuContacts->hide();\n    }\n    QPoint pos = entry->pos();\n    pos.setX(pos.x() + (entry->width() - entry->getMenuBtnWidth()));\n    pos.setY(pos.y() + entry->height() + (entry->getMenuBtnWidth()));\n\n    if(!this->menu){\n        this->menu = new TooltipMenu(window, this);\n        this->menu->setCopyBtnVisible(false);\n        this->menu->setEditBtnText(tr(\"Save contact\"));\n        this->menu->setMinimumSize(this->menu->width() + 30,this->menu->height());\n        connect(this->menu, &TooltipMenu::message, this, &AddressesWidget::message);\n        connect(this->menu, SIGNAL(onEditClicked()), this, SLOT(onContactMultiClicked()));\n        connect(this->menu, SIGNAL(onDeleteClicked()), this, SLOT(onDeleteClicked()));\n    }else {\n        this->menu->hide();\n    }\n    menu->move(pos);\n    menu->show();\n}\n\nvoid SendWidget::onContactMultiClicked(){\n    if(focusedEntry) {\n        QString address = focusedEntry->getAddress();\n        if (address.isEmpty()) {\n            inform(tr(\"Address field is empty\"));\n            return;\n        }\n        if (!walletModel->validateAddress(address)) {\n            inform(tr(\"Invalid address\"));\n            return;\n        }\n        CBitcoinAddress auopAdd = CBitcoinAddress(address.toStdString());\n        if (walletModel->isMine(auopAdd)) {\n            inform(tr(\"Cannot store your own address as contact\"));\n            return;\n        }\n\n        showHideOp(true);\n        AddNewContactDialog *dialog = new AddNewContactDialog(window);\n        QString label = walletModel->getAddressTableModel()->labelForAddress(address);\n        if (!label.isNull()){\n            dialog->setTexts(tr(\"Update Contact\"), \"Edit label for the selected address:\\n%1\");\n            dialog->setData(address, label);\n        } else {\n            dialog->setTexts(tr(\"Create New Contact\"), \"Save label for the selected address:\\n%1\");\n            dialog->setData(address, \"\");\n        }\n        openDialogWithOpaqueBackgroundY(dialog, window, 3, 5);\n        if (dialog->res) {\n            if (label == dialog->getLabel()) {\n                return;\n            }\n            if (walletModel->updateAddressBookLabels(auopAdd.Get(), dialog->getLabel().toStdString(), \"send\")) {\n                inform(tr(\"New Contact Stored\"));\n            } else {\n                inform(tr(\"Error Storing Contact\"));\n            }\n        }\n        dialog->deleteLater();\n    }\n\n}\n\nvoid SendWidget::onDeleteClicked(){\n    if (focusedEntry) {\n        focusedEntry->hide();\n        focusedEntry->deleteLater();\n        int entryNumber = focusedEntry->getNumber();\n\n        \/\/ remove selected entry and update row number for the others\n        QMutableListIterator<SendMultiRow*> it(entries);\n        while (it.hasNext()) {\n            SendMultiRow* entry = it.next();\n            if (focusedEntry == entry){\n                it.remove();\n            } else if (focusedEntry && entry->getNumber() > entryNumber){\n                entry->setNumber(entry->getNumber() - 1);\n            }\n        }\n\n        if (entries.size() == 1) {\n            SendMultiRow* sendMultiRow = QMutableListIterator<SendMultiRow*>(entries).next();\n            sendMultiRow->setNumber(entries.length());\n            sendMultiRow->showLabels();\n        }\n\n        focusedEntry = nullptr;\n\n        \/\/ Update total amounts\n        refreshAmounts();\n    }\n}\n\nvoid SendWidget::resizeMenu(){\n    if(menuContacts && menuContacts->isVisible() && focusedEntry){\n        int width = focusedEntry->getEditWidth();\n        menuContacts->resizeList(width, menuContacts->height());\n        menuContacts->resize(width, menuContacts->height());\n        QPoint pos = focusedEntry->getEditLineRect().bottomLeft();\n        pos.setX(pos.x() + 20);\n        pos.setY(pos.y() + ((focusedEntry->getEditHeight() - 12)  * 3));\n        menuContacts->move(pos);\n    }\n}\n\nvoid SendWidget::changeTheme(bool isLightTheme, QString& theme){\n    if (coinControlDialog) coinControlDialog->setStyleSheet(theme);\n}\n\nSendWidget::~SendWidget(){\n    delete ui;\n}\n","avg_line_length":35.576971214,"max_line_length":172,"alphanum_fraction":0.6319918385,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":407,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":127.0,"content":"#define PROBLEM \"https:\/\/yukicoder.me\/problems\/no\/1254\"\n\n#include \"..\/..\/template\/template.cpp\"\n\n#include \"..\/..\/graph\/others\/namori-graph.hpp\"\n\nint main() {\n  int N;\n  cin >> N;\n  NamoriGraph< int > g(N);\n  g.read(N);\n  g.build();\n  vector< int > ans;\n  for(auto &e : g.loop_edges) {\n    ans.emplace_back(e.idx + 1);\n  }\n  sort(begin(ans), end(ans));\n  cout << ans.size() << \"\\n\";\n  cout << ans << \"\\n\";\n}\n","avg_line_length":19.380952381,"max_line_length":55,"alphanum_fraction":0.5724815725,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6196,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["NRL"],"max_stars_count":null,"content":"\/* ============================================================================\n * Copyright (c) 2009-2016 BlueQuartz Software, LLC\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice, this\n * list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * Neither the name of BlueQuartz Software, the US Air Force, nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The code contained herein was partially funded by the followig contracts:\n *    United States Air Force Prime Contract FA8650-07-D-5800\n *    United States Air Force Prime Contract FA8650-10-D-5210\n *    United States Prime Contract Navy N00173-07-C-2068\n *\n * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *\/\n#include \"TupleTableWidget.h\"\n\n#include <QtWidgets\/QTableWidgetItem>\n\n#include \"TupleTableItemDelegate.h\"\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ -----------------------------------------------------------------------------\nTupleTableWidget::TupleTableWidget(QWidget* parent)\n: QWidget(parent)\n{\n  setupUi(this);\n\n  setupGui();\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ -----------------------------------------------------------------------------\nTupleTableWidget::~TupleTableWidget() = default;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ -----------------------------------------------------------------------------\nbool TupleTableWidget::didUseEdit()\n{\n  return m_UserEdited;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ -----------------------------------------------------------------------------\nvoid TupleTableWidget::setupGui()\n{\n  \/\/ Set the item delegate so that we can only enter 'double' values into the table\n  TupleTableItemDelegate* dlg = new TupleTableItemDelegate(tupleTable);\n  tupleTable->setItemDelegate(dlg);\n\n  tupleTable->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ -----------------------------------------------------------------------------\nstd::vector<size_t> TupleTableWidget::getData()\n{\n  int cCount = tupleTable->columnCount();\n  std::vector<size_t> data(cCount, 0);\n\n  for(int col = 0; col < cCount; col++)\n  {\n    QTableWidgetItem* item = tupleTable->item(0, col);\n    if(nullptr == item)\n    {\n      return std::vector<size_t>();\n    }\n    data[col] = item->data(Qt::DisplayRole).toInt();\n  }\n\n  return data;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ -----------------------------------------------------------------------------\nvoid TupleTableWidget::addTupleDimensions(std::vector<size_t> tupleDims)\n{\n  if(!m_UserEdited)\n  {\n    for(int i = 0; i < tupleDims.size(); i++)\n    {\n      addColumn(tupleDims[i]);\n    }\n  }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ -----------------------------------------------------------------------------\nvoid TupleTableWidget::clearTupleDimensions()\n{\n  m_UserEdited = false;\n  while(tupleTable->columnCount() > 0)\n  {\n    tupleTable->removeColumn(0);\n    if(tupleTable->columnCount() == 0)\n    {\n      tupleTable->removeRow(0);\n    }\n  }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ -----------------------------------------------------------------------------\nvoid TupleTableWidget::addColumn(int value)\n{\n  int col = tupleTable->columnCount();\n\n  \/\/ If we are adding the first column, add the first row too.\n  if(col <= 0)\n  {\n    tupleTable->insertRow(0);\n  }\n\n  tupleTable->insertColumn(col);\n\n  QTableWidgetItem* item = new QTableWidgetItem(QString::number(value));\n  tupleTable->setItem(0, col, item);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ -----------------------------------------------------------------------------\nvoid TupleTableWidget::on_addTupleBtn_clicked()\n{\n  addColumn(1);\n  m_UserEdited = true;\n\n  Q_EMIT tupleDimsChanged(getData());\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ -----------------------------------------------------------------------------\nvoid TupleTableWidget::on_deleteTupleBtn_clicked()\n{\n  int currentColumn = tupleTable->currentColumn();\n\n  if(currentColumn >= 0)\n  {\n    tupleTable->removeColumn(tupleTable->currentColumn());\n  }\n\n  if(tupleTable->columnCount() == 0)\n  {\n    tupleTable->removeRow(0);\n    m_UserEdited = false;\n  }\n\n  Q_EMIT tupleDimsChanged(getData());\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ -----------------------------------------------------------------------------\nvoid TupleTableWidget::on_tupleTable_itemChanged(QTableWidgetItem* item)\n{\n  Q_EMIT tupleDimsChanged(getData());\n}\n","avg_line_length":33.311827957,"max_line_length":86,"alphanum_fraction":0.4975790833,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2860,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":null,"content":"\/\/  Copyright (c) 2017 Ajai V George\n\/\/\n\/\/  SPDX-License-Identifier: BSL-1.0\n\/\/  Distributed under the Boost Software License, Version 1.0. (See accompadjacent_finding\n\/\/  file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <hpx\/hpx_main.hpp>\n#include <hpx\/include\/parallel_adjacent_find.hpp>\n#include <hpx\/include\/partitioned_vector_predef.hpp>\n\n#include <hpx\/testing.hpp>\n\n#include <cstddef>\n#include <iostream>\n#include <vector>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#define SIZE 64\n\nstruct pred\n{\n    template <typename T>\n    bool operator()(const T& prev, const T& curr) const\n    {\n        return curr < prev;\n    }\n};\n\ntemplate <typename T>\nvoid initialize(hpx::partitioned_vector<T>& xvalues)\n{\n    T init_array[SIZE] = {1, 2, 3, 4, 5, 1, 2, 3, 1, 5, 2, 3, 4, 2, 3, 2, 1, 2,\n        3, 4, 5, 6, 5, 6, 1, 2, 3, 4, 2, 1, 2, 3, 3, 5, 4, 3, 2, 1, 1, 2, 3, 4,\n        1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 7, 6, 5, 7, 5, 4, 2, 3, 4, 5, 2};\n    for (int i = 0; i < SIZE; i++)\n    {\n        xvalues.set_value(i, init_array[i]);\n    }\n}\n\ntemplate <typename ExPolicy, typename T>\nvoid test_adjacent_find(ExPolicy&& policy, hpx::partitioned_vector<T>& xvalues)\n{\n    auto result =\n        hpx::parallel::adjacent_find(policy, xvalues.begin(), xvalues.end());\n    HPX_TEST_EQ(std::distance(xvalues.begin(), result), 31);\n\n    result = hpx::parallel::adjacent_find(\n        policy, xvalues.begin(), xvalues.end(), pred());\n    HPX_TEST_EQ(std::distance(xvalues.begin(), result), 4);\n}\n\ntemplate <typename ExPolicy, typename T>\nvoid test_adjacent_find_async(\n    ExPolicy&& policy, hpx::partitioned_vector<T>& xvalues)\n{\n    auto result =\n        hpx::parallel::adjacent_find(policy, xvalues.begin(), xvalues.end())\n            .get();\n    HPX_TEST_EQ(std::distance(xvalues.begin(), result), 31);\n\n    result = hpx::parallel::adjacent_find(\n        policy, xvalues.begin(), xvalues.end(), pred())\n                 .get();\n    HPX_TEST_EQ(std::distance(xvalues.begin(), result), 4);\n}\n\ntemplate <typename T>\nvoid adjacent_find_tests(std::vector<hpx::id_type>& localities)\n{\n    hpx::partitioned_vector<T> xvalues(\n        SIZE, T(0), hpx::container_layout(localities));\n    initialize(xvalues);\n\n    test_adjacent_find(hpx::parallel::execution::seq, xvalues);\n    test_adjacent_find(hpx::parallel::execution::par, xvalues);\n    test_adjacent_find_async(\n        hpx::parallel::execution::seq(hpx::parallel::execution::task), xvalues);\n    test_adjacent_find_async(\n        hpx::parallel::execution::par(hpx::parallel::execution::task), xvalues);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main()\n{\n    std::vector<hpx::id_type> localities = hpx::find_all_localities();\n    adjacent_find_tests<double>(localities);\n    return hpx::util::report_errors();\n}\n","avg_line_length":31.7777777778,"max_line_length":90,"alphanum_fraction":0.6164335664,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2274,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-4.0","MIT"],"max_stars_count":14.0,"content":"\/\/ This example creates a secondary thread that implements\n\/\/ the methods of CAnimateCtrl. The procedure of the thread\n\/\/ is MyClipThreadProc and the thread was created with the\n\/\/ code AfxBeginThread( MyClipThreadProc, (LPVOID) pParentWnd).\n\/\/ The example code creates and initializes an animation control,\n\/\/ then proceeds to pump messages from the queue until one the \n\/\/ private messages WM_STOPCLIP, WM_PLAYCLIP, WM_SHOWFIRSTFRAME or \n\/\/ WM_SHOWLASTFRAME is received. The appropriate action is done for\n\/\/ these messages. The thread ends when the WM_STOPCLIP is received.\n\/\/ NOTE: the thread parameter, pParam, is a pointer to a CWnd object\n\/\/ that will be the parent of the animation control. \n\n#define WM_STOPCLIP               WM_USER+1\n#define WM_PLAYCLIP               WM_USER+2\n#define WM_SHOWFIRSTFRAME         WM_USER+3\n#define WM_SHOWLASTFRAME         WM_USER+4\n\nUINT MyClipThreadProc(LPVOID pParam)\n{\n   \/\/ NOTE: pParentWnd is the parent window of the animation control.\n   CWnd* pParentWnd = (CWnd*) pParam;\n   CAnimateCtrl cAnimCtrl;\n\n   \/\/ Create the animation control.\n   if (!cAnimCtrl.Create(WS_CHILD|WS_VISIBLE|ACS_CENTER, \n      CRect(10,10,100,100), pParentWnd, 1))\n   {\n      return false;\n   }\n\n   \/\/ Open the AVI file.\n   if (!cAnimCtrl.Open(_T(\"MyAvi.avi\")))\n   {\n      return false;\n   }\n\n   \/\/ Pump message from the queue until the stop play message is received.\n   MSG msg;\n   while (GetMessage(&msg, NULL, 0, 0) && (msg.message != WM_STOPCLIP))\n   {\n      switch (msg.message)\n      {\n         \/\/ Start playing from the first frame to the last, \n         \/\/ continuously repeating.\n         case WM_PLAYCLIP:\n            if (!cAnimCtrl.Play(0, (UINT)-1, (UINT)-1))\n               return false;\n            break;\n         \n         \/\/ Show the first frame.\n         case WM_SHOWFIRSTFRAME:\n            if (!cAnimCtrl.Seek(0))\n               return false;\n            cAnimCtrl.RedrawWindow();\n            break;\n\n         \/\/ Show the last frame.\n         case WM_SHOWLASTFRAME:\n            if (!cAnimCtrl.Seek((UINT)-1))\n               return false;\n            cAnimCtrl.RedrawWindow();\n            break;\n      }\n\n      TranslateMessage(&msg);\n      DispatchMessage(&msg);\n   }\n\n   cAnimCtrl.Stop();\n   cAnimCtrl.Close();\n\n   return true;\n}","avg_line_length":31.1506849315,"max_line_length":74,"alphanum_fraction":0.6350043975,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4595,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"#include <unistd.h>\n#include <cstdlib>\n#include <string>\n#include <iostream>\n#include <cassert>\n#include <algorithm>\n\n#include \"default_config.h\"\n#include \"execute.h\"\n\n#include <limits>\n\n\/\/ =====================================================================\n\/\/ =====================================================================\n\n\nint main(int argc, char *argv[]) {\n  std::cout << \"Running User Code...\" << std::endl;\n\n  std::string hw_id = \"\";\n  std::string rcsid = \"\";\n  int subnum = -1;\n  std::string time_of_submission = \"\";\n  std::string docker_name = \"\";\n  \/\/If test_case_to_run isn't passed in as a parameter, all testcases are run.\n  int test_case_to_run = -1;\n  \/\/ Check command line arguments\n  if (argc >= 5) {\n    hw_id = argv[1];\n    rcsid = argv[2];\n    subnum = atoi(argv[3]);\n    time_of_submission = argv[4];\n    if (argc >= 6){\n      test_case_to_run = atoi(argv[5]);\n    }\n    if(argc >= 7){\n      docker_name = argv[6];\n      std::cout << \"TESTCASE: \" << test_case_to_run << \"! THE DOCKER NAME THAT WAS PASSED IN: \" << docker_name << std::endl;\n    }\n  }\n  else if (argc != 1) {\n    std::cerr << \"INCORRECT ARGUMENTS TO RUNNER\" << std::endl;\n    return 1;\n  } \n\n  \/\/ LOAD HW CONFIGURATION JSON\n  nlohmann::json config_json = LoadAndProcessConfigJSON(rcsid);\n\n  \/\/ nlohmann::json grading_parameters = config_json.value(\"grading_parameters\",nlohmann::json::object());\n  \/\/ int AUTO_POINTS         = grading_parameters.value(\"AUTO_POINTS\",0);\n  \/\/ int EXTRA_CREDIT_POINTS = grading_parameters.value(\"EXTRA_CREDIT_POINTS\",0);\n  \/\/ int TA_POINTS           = grading_parameters.value(\"TA_POINTS\",0);\n  \/\/ int TOTAL_POINTS        = grading_parameters.value(\"TOTAL_POINTS\",AUTO_POINTS+TA_POINTS);\n\n  \/\/ necessary since the untrusted user does not have a home directory\n  setenv(\"DYNAMORIO_CONFIGDIR\", \".\", 1);\n\n  system(\"find . -type f -exec ls -sh {} +\");\n\n  \/\/ Run each test case and create output files\n  std::vector<std::string> required_capabilities = stringOrArrayOfStrings(config_json, \"required_capabilities\");\n  \n  bool windowed = false;\n  if (std::find(required_capabilities.begin(), required_capabilities.end(), \"windowed\") != required_capabilities.end()){\n    windowed = true;\n  }\n\n  nlohmann::json::iterator tc = config_json.find(\"testcases\");\n  assert (tc != config_json.end());\n\n  if(test_case_to_run != -1){\n    \/\/testcases begin counting at 1 and end at tc->size()\n    assert (test_case_to_run <= tc->size());\n  }else{\n    std::cout << \"Running all testcases in a single run.\" << std::endl;\n  }\n\n  for (unsigned int i = 1; i <= tc->size(); i++) {\n\n    TestCase my_testcase(config_json,i-1,docker_name);\n\n    if (my_testcase.isFileCheck() || my_testcase.isCompilation()){\n      continue;\n    }\n\n    if(test_case_to_run != -1 &&  test_case_to_run != i){\n      continue;\n    }\n\n    std::cout << \"========================================================\" << std::endl;\n    std::cout << \"TEST #\" << i << std::endl;\n\n    std::vector<std::string> commands = my_testcase.getCommands();\n\n    std::vector<nlohmann::json> actions  = mapOrArrayOfMaps((*tc)[i-1],\"actions\");\n    std::vector<nlohmann::json> dispatcher_actions = mapOrArrayOfMaps((*tc)[i-1],\"dispatcher_actions\");\n\n    assert (commands.size() > 0);\n\n    std::cout << \"TITLE \" << my_testcase.getTitle() << std::endl;\n    \n    for (int x = 0; x < commands.size(); x++) {\n      std::cout << \"COMMAND \" << commands[x] << std::endl;\n\n      assert (commands[x] != \"MISSING COMMAND\");\n      assert (commands[x] != \"\");\n      \n      std::string which = \"\";\n      if (commands.size() > 1) {\n        which = \"_\" + std::to_string(x);\n      }\n      \n      \n      std::string logfile = \"execute_logfile.txt\";\n      \/\/ run the command, capturing STDOUT & STDERR\n      int exit_no = execute(commands[x]\n                            +\n                            \" 1>\" + \"STDOUT\" + which + \".txt\" +\n                            \" 2>\" + \"STDERR\" + which + \".txt\",\n                            actions,\n                            dispatcher_actions,\n                            logfile,\n                            my_testcase.get_test_case_limits(),\n                            config_json.value(\"resource_limits\",nlohmann::json()),\n                            config_json,\n                            windowed); \n    }\n    std::cout << \"========================================================\" << std::endl;\n    std::cout << \"FINISHED TEST #\" << i << std::endl;\n  }\n  return 0;\n}\n\n\/\/ =====================================================================\n\/\/ =====================================================================\n","avg_line_length":33.7867647059,"max_line_length":124,"alphanum_fraction":0.533405876,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":379,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"#include<bits\/stdc++.h>\nusing namespace std;\nint main(){\n\tfreopen(\"in.in\" , \"r\" , stdin);\n\tint k ;\n\tstring s;\n\tcin >> k >> s;\n\tlong long sum = 0;\n\tfor(int i = 0 ;i < s.size() ;i ++)\n\t\tsum += (s[i] - '0');\n\tsort(s.begin() , s.end() );\n\tint cnt = 0;\n\tint idx = 0;\n\twhile(sum < k && idx < s.size() ){\n\t\tsum = sum + 9 - (s[idx] - '0');\n\t\tidx ++;\n\t\tcnt ++;\n\t}\n\tcout << cnt << endl;\n}\n","avg_line_length":18.0476190476,"max_line_length":35,"alphanum_fraction":0.4749340369,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":31623,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/Copyright (c) 2015-2020 The PIVX developers\n\/\/Copyright (c) 2020 The emrals developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"guiutil.h\"\n\n#include \"bitcoinaddressvalidator.h\"\n#include \"bitcoinunits.h\"\n#include \"qvalidatedlineedit.h\"\n#include \"walletmodel.h\"\n\n#include \"init.h\"\n#include \"main.h\"\n#include \"primitives\/transaction.h\"\n#include \"protocol.h\"\n#include \"script\/script.h\"\n#include \"script\/standard.h\"\n#include \"util.h\"\n\n#ifdef WIN32\n#ifdef _WIN32_WINNT\n#undef _WIN32_WINNT\n#endif\n#define _WIN32_WINNT 0x0501\n#ifdef _WIN32_IE\n#undef _WIN32_IE\n#endif\n#define _WIN32_IE 0x0501\n#define WIN32_LEAN_AND_MEAN 1\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n#include \"shellapi.h\"\n#include \"shlobj.h\"\n#include \"shlwapi.h\"\n#endif\n\n#include <QAbstractItemView>\n#include <QApplication>\n#include <QClipboard>\n#include <QDateTime>\n#include <QDesktopServices>\n#include <QDesktopWidget>\n#include <QRegExp>\n#include <QRegularExpression>\n#include <QRegularExpressionValidator>\n#include <QFileDialog>\n#include <QFont>\n#include <QLineEdit>\n#include <QSettings>\n#include <QTextDocument> \/\/ for Qt::mightBeRichText\n#include <QThread>\n#include <QUrlQuery>\n#include <QMouseEvent>\n\n\n#if BOOST_FILESYSTEM_VERSION >= 3\nstatic fs::detail::utf8_codecvt_facet utf8;\n#endif\n\n#if defined(Q_OS_MAC)\nextern double NSAppKitVersionNumber;\n#if !defined(NSAppKitVersionNumber10_8)\n#define NSAppKitVersionNumber10_8 1187\n#endif\n#if !defined(NSAppKitVersionNumber10_9)\n#define NSAppKitVersionNumber10_9 1265\n#endif\n#endif\n\n#define URI_SCHEME \"emrals\"\n\n#if defined(Q_OS_MAC)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n\n#include <CoreServices\/CoreServices.h>\n#include <QProcess>\n\nvoid ForceActivation();\n#endif\n\nnamespace GUIUtil\n{\nQString dateTimeStr(const QDateTime& date)\n{\n    return date.date().toString(Qt::SystemLocaleShortDate) + QString(\" \") + date.toString(\"hh:mm\");\n}\n\nQString dateTimeStrWithSeconds(const QDateTime& date)\n{\n    return date.date().toString(Qt::SystemLocaleShortDate) + QString(\" \") + date.toString(\"hh:mm:ss\");\n}\n\nQString dateTimeStr(qint64 nTime)\n{\n    return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));\n}\n\nQFont bitcoinAddressFont()\n{\n    QFont font(\"Monospace\");\n    font.setStyleHint(QFont::Monospace);\n    return font;\n}\n\n\/**\n * Parse a string into a number of base monetary units and\n * return validity.\n * @note Must return 0 if !valid.\n *\/\nCAmount parseValue(const QString& text, int displayUnit, bool* valid_out)\n{\n    CAmount val = 0;\n    bool valid = BitcoinUnits::parse(displayUnit, text, &val);\n    if (valid) {\n        if (val < 0 || val > BitcoinUnits::maxMoney())\n            valid = false;\n    }\n    if (valid_out)\n        *valid_out = valid;\n    return valid ? val : 0;\n}\n\nQString formatBalance(CAmount amount, int nDisplayUnit)\n{\n    return (amount == 0) ? (\"0.00 \" + BitcoinUnits::name(nDisplayUnit)) : BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, amount, false, BitcoinUnits::separatorAlways, true);\n}\n\nvoid setupAddressWidget(QValidatedLineEdit* widget, QWidget* parent)\n{\n    parent->setFocusProxy(widget);\n\n    widget->setFont(bitcoinAddressFont());\n    \/\/ We don't want translators to use own addresses in translations\n    \/\/ and this is the only place, where this address is supplied.\n    widget->setPlaceholderText(QObject::tr(\"Enter Emrals address (e.g. %1)\").arg(\"M6tGR83SQbie1SW72hjcWJvFfip5krte2Z\"));\n    widget->setValidator(new BitcoinAddressEntryValidator(parent));\n    widget->setCheckValidator(new BitcoinAddressCheckValidator(parent));\n}\n\nvoid setupAmountWidget(QLineEdit* widget, QWidget* parent)\n{\n    QRegularExpression rx(\"^(\\\\d{0,8})((\\\\.|,)\\\\d{1,8})?$\");\n    QValidator *validator = new QRegularExpressionValidator(rx, widget);\n    widget->setValidator(validator);\n}\n\nvoid updateWidgetTextAndCursorPosition(QLineEdit* widget, const QString& str)\n{\n    const int cpos = widget->cursorPosition();\n    widget->setText(str);\n    if (cpos > str.size()) return;\n    widget->setCursorPosition(cpos);\n}\n\nbool parseBitcoinURI(const QUrl& uri, SendCoinsRecipient* out)\n{\n    \/\/ return if URI is not valid or is no emrals: URI\n    if (!uri.isValid() || uri.scheme() != QString(URI_SCHEME))\n        return false;\n\n    SendCoinsRecipient rv;\n    rv.address = uri.path();\n    \/\/ Trim any following forward slash which may have been added by the OS\n    if (rv.address.endsWith(\"\/\")) {\n        rv.address.truncate(rv.address.length() - 1);\n    }\n    rv.amount = 0;\n\n    QUrlQuery uriQuery(uri);\n    QList<QPair<QString, QString> > items = uriQuery.queryItems();\n    for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)\n    {\n        bool fShouldReturnFalse = false;\n        if (i->first.startsWith(\"req-\")) {\n            i->first.remove(0, 4);\n            fShouldReturnFalse = true;\n        }\n\n        if (i->first == \"label\") {\n            rv.label = i->second;\n            fShouldReturnFalse = false;\n        }\n        if (i->first == \"message\") {\n            rv.message = i->second;\n            fShouldReturnFalse = false;\n        } else if (i->first == \"amount\") {\n            if (!i->second.isEmpty()) {\n                if (!BitcoinUnits::parse(BitcoinUnits::EMRALS, i->second, &rv.amount)) {\n                    return false;\n                }\n            }\n            fShouldReturnFalse = false;\n        }\n\n        if (fShouldReturnFalse)\n            return false;\n    }\n    if (out) {\n        *out = rv;\n    }\n    return true;\n}\n\nbool parseBitcoinURI(QString uri, SendCoinsRecipient* out)\n{\n    \/\/ Convert emrals:\/\/ to emrals:\n    \/\/\n    \/\/    Cannot handle this later, because emrals:\/\/ will cause Qt to see the part after \/\/ as host,\n    \/\/    which will lower-case it (and thus invalidate the address).\n    if (uri.startsWith(URI_SCHEME \":\/\/\", Qt::CaseInsensitive)) {\n        uri.replace(0, std::strlen(URI_SCHEME) + 3, URI_SCHEME \":\");\n    }\n    QUrl uriInstance(uri);\n    return parseBitcoinURI(uriInstance, out);\n}\n\nQString formatBitcoinURI(const SendCoinsRecipient& info)\n{\n    QString ret = QString(URI_SCHEME \":%1\").arg(info.address);\n    int paramCount = 0;\n\n    if (info.amount) {\n        ret += QString(\"?amount=%1\").arg(BitcoinUnits::format(BitcoinUnits::EMRALS, info.amount, false, BitcoinUnits::separatorNever));\n        paramCount++;\n    }\n\n    if (!info.label.isEmpty()) {\n        QString lbl(QUrl::toPercentEncoding(info.label));\n        ret += QString(\"%1label=%2\").arg(paramCount == 0 ? \"?\" : \"&\").arg(lbl);\n        paramCount++;\n    }\n\n    if (!info.message.isEmpty()) {\n        QString msg(QUrl::toPercentEncoding(info.message));\n        ret += QString(\"%1message=%2\").arg(paramCount == 0 ? \"?\" : \"&\").arg(msg);\n        paramCount++;\n    }\n\n    return ret;\n}\n\nbool isDust(const QString& address, const CAmount& amount)\n{\n    CTxDestination dest = DecodeDestination(address.toStdString());\n    CScript script = GetScriptForDestination(dest);\n    CTxOut txOut(amount, script);\n    return txOut.IsDust(::minRelayTxFee);\n}\n\nQString HtmlEscape(const QString& str, bool fMultiLine)\n{\n    QString escaped = str.toHtmlEscaped();\n    escaped = escaped.replace(\" \", \"&nbsp;\");\n    if (fMultiLine) {\n        escaped = escaped.replace(\"\\n\", \"<br>\\n\");\n    }\n    return escaped;\n}\n\nQString HtmlEscape(const std::string& str, bool fMultiLine)\n{\n    return HtmlEscape(QString::fromStdString(str), fMultiLine);\n}\n\nvoid copyEntryData(QAbstractItemView* view, int column, int role)\n{\n    if (!view || !view->selectionModel())\n        return;\n    QModelIndexList selection = view->selectionModel()->selectedRows(column);\n\n    if (!selection.isEmpty()) {\n        \/\/ Copy first item\n        setClipboard(selection.at(0).data(role).toString());\n    }\n}\n\nQString getEntryData(QAbstractItemView *view, int column, int role)\n{\n    if (!view || !view->selectionModel())\n        return QString();\n    QModelIndexList selection = view->selectionModel()->selectedRows(column);\n\n    if (!selection.isEmpty()) {\n        \/\/ Return first item\n        return (selection.at(0).data(role).toString());\n    }\n    return QString();\n}\n\nQString getSaveFileName(QWidget* parent, const QString& caption, const QString& dir, const QString& filter, QString* selectedSuffixOut)\n{\n    QString selectedFilter;\n    QString myDir;\n    if (dir.isEmpty()) \/\/ Default to user documents location\n    {\n        myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);\n    }\n    else\n    {\n        myDir = dir;\n    }\n    \/* Directly convert path to native OS path separators *\/\n    QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter));\n\n    \/* Extract first suffix from filter pattern \"Description (*.foo)\" or \"Description (*.foo *.bar ...) *\/\n    QRegExp filter_re(\".* \\\\(\\\\*\\\\.(.*)[ \\\\)]\");\n    QString selectedSuffix;\n    if (filter_re.exactMatch(selectedFilter)) {\n        selectedSuffix = filter_re.cap(1);\n    }\n\n    \/* Add suffix if needed *\/\n    QFileInfo info(result);\n    if (!result.isEmpty()) {\n        if (info.suffix().isEmpty() && !selectedSuffix.isEmpty()) {\n            \/* No suffix specified, add selected suffix *\/\n            if (!result.endsWith(\".\"))\n                result.append(\".\");\n            result.append(selectedSuffix);\n        }\n    }\n\n    \/* Return selected suffix if asked to *\/\n    if (selectedSuffixOut) {\n        *selectedSuffixOut = selectedSuffix;\n    }\n    return result;\n}\n\nQString getOpenFileName(QWidget* parent, const QString& caption, const QString& dir, const QString& filter, QString* selectedSuffixOut)\n{\n    QString selectedFilter;\n    QString myDir;\n    if (dir.isEmpty()) \/\/ Default to user documents location\n    {\n        myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);\n    }\n    else\n    {\n        myDir = dir;\n    }\n    \/* Directly convert path to native OS path separators *\/\n    QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter));\n\n    if (selectedSuffixOut) {\n        \/* Extract first suffix from filter pattern \"Description (*.foo)\" or \"Description (*.foo *.bar ...) *\/\n        QRegExp filter_re(\".* \\\\(\\\\*\\\\.(.*)[ \\\\)]\");\n        QString selectedSuffix;\n        if (filter_re.exactMatch(selectedFilter)) {\n            selectedSuffix = filter_re.cap(1);\n        }\n        *selectedSuffixOut = selectedSuffix;\n    }\n    return result;\n}\n\nQt::ConnectionType blockingGUIThreadConnection()\n{\n    if (QThread::currentThread() != qApp->thread()) {\n        return Qt::BlockingQueuedConnection;\n    } else {\n        return Qt::DirectConnection;\n    }\n}\n\nbool checkPoint(const QPoint& p, const QWidget* w)\n{\n    QWidget* atW = QApplication::widgetAt(w->mapToGlobal(p));\n    if (!atW) return false;\n    return atW->topLevelWidget() == w;\n}\n\nbool isObscured(QWidget* w)\n{\n    return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() \/ 2, w->height() \/ 2), w));\n}\n\nvoid bringToFront(QWidget* w)\n{\n#ifdef Q_OS_MAC\n    ForceActivation();\n#endif\n\n    if (w) {\n        \/\/ activateWindow() (sometimes) helps with keyboard focus on Windows\n        if (w->isMinimized()) {\n            w->showNormal();\n        } else {\n            w->show();\n        }\n        w->activateWindow();\n        w->raise();\n    }\n}\n\n\/* Open file with the associated application *\/\nbool openFile(fs::path path, bool isTextFile)\n{\n    bool ret = false;\n    if (fs::exists(path)) {\n        ret = QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(path)));\n#ifdef Q_OS_MAC\n        \/\/ Workaround for macOS-specific behavior; see btc@15409.\n        if (isTextFile && !ret) {\n            ret = QProcess::startDetached(\"\/usr\/bin\/open\", QStringList{\"-t\", boostPathToQString(path)});\n        }\n#endif\n    }\n    return ret;\n}\n\nbool openDebugLogfile()\n{\n    return openFile(GetDataDir() \/ \"debug.log\", true);\n}\n\nbool openConfigfile()\n{\n    return openFile(GetConfigFile(), true);\n}\n\nbool openMNConfigfile()\n{\n    return openFile(GetMasternodeConfigFile(), true);\n}\n\nbool showBackups()\n{\n    return openFile(GetDataDir() \/ \"backups\", false);\n}\n\nvoid SubstituteFonts(const QString& language)\n{\n#if defined(Q_OS_MAC)\n\/\/ Background:\n\/\/ OSX's default font changed in 10.9 and QT is unable to find it with its\n\/\/ usual fallback methods when building against the 10.7 sdk or lower.\n\/\/ The 10.8 SDK added a function to let it find the correct fallback font.\n\/\/ If this fallback is not properly loaded, some characters may fail to\n\/\/ render correctly.\n\/\/\n\/\/ The same thing happened with 10.10. .Helvetica Neue DeskInterface is now default.\n\/\/\n\/\/ Solution: If building with the 10.7 SDK or lower and the user's platform\n\/\/ is 10.9 or higher at runtime, substitute the correct font. This needs to\n\/\/ happen before the QApplication is created.\n#if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8\n    if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8) {\n        if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9)\n            \/* On a 10.9 - 10.9.x system *\/\n            QFont::insertSubstitution(\".Lucida Grande UI\", \"Lucida Grande\");\n        else {\n            \/* 10.10 or later system *\/\n            if (language == \"zh_CN\" || language == \"zh_TW\" || language == \"zh_HK\") \/\/ traditional or simplified Chinese\n                QFont::insertSubstitution(\".Helvetica Neue DeskInterface\", \"Heiti SC\");\n            else if (language == \"ja\") \/\/ Japanesee\n                QFont::insertSubstitution(\".Helvetica Neue DeskInterface\", \"Songti SC\");\n            else\n                QFont::insertSubstitution(\".Helvetica Neue DeskInterface\", \"Lucida Grande\");\n        }\n    }\n#endif\n#endif\n}\n\nToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject* parent) : QObject(parent),\n                                                                                        size_threshold(size_threshold)\n{\n}\n\nbool ToolTipToRichTextFilter::eventFilter(QObject* obj, QEvent* evt)\n{\n    if (evt->type() == QEvent::ToolTipChange) {\n        QWidget* widget = static_cast<QWidget*>(obj);\n        QString tooltip = widget->toolTip();\n        if (tooltip.size() > size_threshold && !tooltip.startsWith(\"<qt\")) {\n            \/\/ Escape the current message as HTML and replace \\n by <br> if it's not rich text\n            if (!Qt::mightBeRichText(tooltip))\n                tooltip = HtmlEscape(tooltip, true);\n            \/\/ Envelop with <qt><\/qt> to make sure Qt detects every tooltip as rich text\n            \/\/ and style='white-space:pre' to preserve line composition\n            tooltip = \"<qt style='white-space:pre'>\" + tooltip + \"<\/qt>\";\n            widget->setToolTip(tooltip);\n            return true;\n        }\n    }\n    return QObject::eventFilter(obj, evt);\n}\n\nvoid TableViewLastColumnResizingFixer::connectViewHeadersSignals()\n{\n    connect(tableView->horizontalHeader(), &QHeaderView::sectionResized, this, &TableViewLastColumnResizingFixer::on_sectionResized);\n    connect(tableView->horizontalHeader(), &QHeaderView::geometriesChanged, this, &TableViewLastColumnResizingFixer::on_geometriesChanged);\n}\n\n\/\/ We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.\nvoid TableViewLastColumnResizingFixer::disconnectViewHeadersSignals()\n{\n    disconnect(tableView->horizontalHeader(), &QHeaderView::sectionResized, this, &TableViewLastColumnResizingFixer::on_sectionResized);\n    disconnect(tableView->horizontalHeader(), &QHeaderView::geometriesChanged, this, &TableViewLastColumnResizingFixer::on_geometriesChanged);\n}\n\n\/\/ Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.\n\/\/ Refactored here for readability.\nvoid TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)\n{\n    tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode);\n}\n\nvoid TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width)\n{\n    tableView->setColumnWidth(nColumnIndex, width);\n    tableView->horizontalHeader()->resizeSection(nColumnIndex, width);\n}\n\nint TableViewLastColumnResizingFixer::getColumnsWidth()\n{\n    int nColumnsWidthSum = 0;\n    for (int i = 0; i < columnCount; i++) {\n        nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i);\n    }\n    return nColumnsWidthSum;\n}\n\nint TableViewLastColumnResizingFixer::getAvailableWidthForColumn(int column)\n{\n    int nResult = lastColumnMinimumWidth;\n    int nTableWidth = tableView->horizontalHeader()->width();\n\n    if (nTableWidth > 0) {\n        int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column);\n        nResult = std::max(nResult, nTableWidth - nOtherColsWidth);\n    }\n\n    return nResult;\n}\n\n\/\/ Make sure we don't make the columns wider than the tables viewport width.\nvoid TableViewLastColumnResizingFixer::adjustTableColumnsWidth()\n{\n    disconnectViewHeadersSignals();\n    resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex));\n    connectViewHeadersSignals();\n\n    int nTableWidth = tableView->horizontalHeader()->width();\n    int nColsWidth = getColumnsWidth();\n    if (nColsWidth > nTableWidth) {\n        resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));\n    }\n}\n\n\/\/ Make column use all the space available, useful during window resizing.\nvoid TableViewLastColumnResizingFixer::stretchColumnWidth(int column)\n{\n    disconnectViewHeadersSignals();\n    resizeColumn(column, getAvailableWidthForColumn(column));\n    connectViewHeadersSignals();\n}\n\n\/\/ When a section is resized this is a slot-proxy for ajustAmountColumnWidth().\nvoid TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize)\n{\n    adjustTableColumnsWidth();\n    int remainingWidth = getAvailableWidthForColumn(logicalIndex);\n    if (newSize > remainingWidth) {\n        resizeColumn(logicalIndex, remainingWidth);\n    }\n}\n\n\/\/ When the tabless geometry is ready, we manually perform the stretch of the \"Message\" column,\n\/\/ as the \"Stretch\" resize mode does not allow for interactive resizing.\nvoid TableViewLastColumnResizingFixer::on_geometriesChanged()\n{\n    if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0) {\n        disconnectViewHeadersSignals();\n        resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));\n        connectViewHeadersSignals();\n    }\n}\n\n\/**\n * Initializes all internal variables and prepares the\n * the resize modes of the last 2 columns of the table and\n *\/\nTableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth) : tableView(table),\n                                                                                                                                          lastColumnMinimumWidth(lastColMinimumWidth),\n                                                                                                                                          allColumnsMinimumWidth(allColsMinimumWidth)\n{\n    columnCount = tableView->horizontalHeader()->count();\n    lastColumnIndex = columnCount - 1;\n    secondToLastColumnIndex = columnCount - 2;\n    tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth);\n    setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive);\n    setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive);\n}\n\n\/**\n * Class constructor.\n * @param[in] seconds   Number of seconds to convert to a DHMS string\n *\/\nDHMSTableWidgetItem::DHMSTableWidgetItem(const int64_t seconds) : QTableWidgetItem(),\n                                                                  value(seconds)\n{\n    this->setText(QString::fromStdString(DurationToDHMS(seconds)));\n}\n\n\/**\n * Comparator overload to ensure that the \"DHMS\"-type durations as used in\n * the \"active-since\" list in the masternode tab are sorted by the elapsed\n * duration (versus the string value being sorted).\n * @param[in] item      Right hand side of the less than operator\n *\/\nbool DHMSTableWidgetItem::operator<(QTableWidgetItem const& item) const\n{\n    DHMSTableWidgetItem const* rhs =\n        dynamic_cast<DHMSTableWidgetItem const*>(&item);\n\n    if (!rhs)\n        return QTableWidgetItem::operator<(item);\n\n    return value < rhs->value;\n}\n\n#ifdef WIN32\nfs::path static StartupShortcutPath()\n{\n    return GetSpecialFolderPath(CSIDL_STARTUP) \/ \"emrals.lnk\";\n}\n\nbool GetStartOnSystemStartup()\n{\n    \/\/ check for emrals.lnk\n    return fs::exists(StartupShortcutPath());\n}\n\nbool SetStartOnSystemStartup(bool fAutoStart)\n{\n    \/\/ If the shortcut exists already, remove it for updating\n    fs::remove(StartupShortcutPath());\n\n    if (fAutoStart) {\n        CoInitialize(NULL);\n\n        \/\/ Get a pointer to the IShellLink interface.\n        IShellLink* psl = NULL;\n        HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,\n            CLSCTX_INPROC_SERVER, IID_IShellLink,\n            reinterpret_cast<void**>(&psl));\n\n        if (SUCCEEDED(hres)) {\n            \/\/ Get the current executable path\n            TCHAR pszExePath[MAX_PATH];\n            GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));\n\n            TCHAR pszArgs[5] = TEXT(\"-min\");\n\n            \/\/ Set the path to the shortcut target\n            psl->SetPath(pszExePath);\n            PathRemoveFileSpec(pszExePath);\n            psl->SetWorkingDirectory(pszExePath);\n            psl->SetShowCmd(SW_SHOWMINNOACTIVE);\n            psl->SetArguments(pszArgs);\n\n            \/\/ Query IShellLink for the IPersistFile interface for\n            \/\/ saving the shortcut in persistent storage.\n            IPersistFile* ppf = NULL;\n            hres = psl->QueryInterface(IID_IPersistFile,\n                reinterpret_cast<void**>(&ppf));\n            if (SUCCEEDED(hres)) {\n                WCHAR pwsz[MAX_PATH];\n                \/\/ Ensure that the string is ANSI.\n                MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);\n                \/\/ Save the link by calling IPersistFile::Save.\n                hres = ppf->Save(pwsz, TRUE);\n                ppf->Release();\n                psl->Release();\n                CoUninitialize();\n                return true;\n            }\n            psl->Release();\n        }\n        CoUninitialize();\n        return false;\n    }\n    return true;\n}\n\n#elif defined(Q_OS_LINUX)\n\n\/\/ Follow the Desktop Application Autostart Spec:\n\/\/  http:\/\/standards.freedesktop.org\/autostart-spec\/autostart-spec-latest.html\n\nfs::path static GetAutostartDir()\n{\n    char* pszConfigHome = getenv(\"XDG_CONFIG_HOME\");\n    if (pszConfigHome) return fs::path(pszConfigHome) \/ \"autostart\";\n    char* pszHome = getenv(\"HOME\");\n    if (pszHome) return fs::path(pszHome) \/ \".config\" \/ \"autostart\";\n    return fs::path();\n}\n\nfs::path static GetAutostartFilePath()\n{\n    return GetAutostartDir() \/ \"emrals.desktop\";\n}\n\nbool GetStartOnSystemStartup()\n{\n    fs::ifstream optionFile(GetAutostartFilePath());\n    if (!optionFile.good())\n        return false;\n    \/\/ Scan through file for \"Hidden=true\":\n    std::string line;\n    while (!optionFile.eof()) {\n        getline(optionFile, line);\n        if (line.find(\"Hidden\") != std::string::npos &&\n            line.find(\"true\") != std::string::npos)\n            return false;\n    }\n    optionFile.close();\n\n    return true;\n}\n\nbool SetStartOnSystemStartup(bool fAutoStart)\n{\n    if (!fAutoStart)\n        fs::remove(GetAutostartFilePath());\n    else {\n        char pszExePath[MAX_PATH + 1];\n        memset(pszExePath, 0, sizeof(pszExePath));\n        if (readlink(\"\/proc\/self\/exe\", pszExePath, sizeof(pszExePath) - 1) == -1)\n            return false;\n\n        fs::create_directories(GetAutostartDir());\n\n        fs::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out | std::ios_base::trunc);\n        if (!optionFile.good())\n            return false;\n        \/\/ Write a emrals.desktop file to the autostart directory:\n        optionFile << \"[Desktop Entry]\\n\";\n        optionFile << \"Type=Application\\n\";\n        optionFile << \"Name=Emrals\\n\";\n        optionFile << \"Exec=\" << pszExePath << \" -min\\n\";\n        optionFile << \"Terminal=false\\n\";\n        optionFile << \"Hidden=false\\n\";\n        optionFile.close();\n    }\n    return true;\n}\n\n\n#elif defined(Q_OS_MAC)\n\/\/ based on: https:\/\/github.com\/Mozketo\/LaunchAtLoginController\/blob\/master\/LaunchAtLoginController.m\n\nLSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl);\nLSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)\n{\n    \/\/ loop through the list of startup items and try to find the emrals app\n    CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL);\n    for (int i = 0; i < CFArrayGetCount(listSnapshot); i++) {\n        LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);\n        UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;\n        CFURLRef currentItemURL = NULL;\n\n#if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100\n    if (&LSSharedFileListItemCopyResolvedURL)\n        currentItemURL = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, NULL);\n#if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100\n    else\n        LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL);\n#endif\n#else\n    LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL);\n#endif\n\n        if (currentItemURL && CFEqual(currentItemURL, findUrl)) {\n            \/\/ found\n            CFRelease(currentItemURL);\n            return item;\n        }\n        if (currentItemURL) {\n            CFRelease(currentItemURL);\n        }\n    }\n    return NULL;\n}\n\nbool GetStartOnSystemStartup()\n{\n    CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());\n    LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);\n    LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);\n    return !!foundItem; \/\/ return boolified object\n}\n\nbool SetStartOnSystemStartup(bool fAutoStart)\n{\n    CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());\n    LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);\n    LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);\n\n    if (fAutoStart && !foundItem) {\n        \/\/ add emrals app to startup item list\n        LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL);\n    } else if (!fAutoStart && foundItem) {\n        \/\/ remove item\n        LSSharedFileListItemRemove(loginItems, foundItem);\n    }\n    return true;\n}\n#pragma GCC diagnostic pop\n#else\n\nbool GetStartOnSystemStartup()\n{\n    return false;\n}\nbool SetStartOnSystemStartup(bool fAutoStart) { return false; }\n\n#endif\n\nvoid saveWindowGeometry(const QString& strSetting, QWidget* parent)\n{\n    QSettings settings;\n    settings.setValue(strSetting + \"Pos\", parent->pos());\n    settings.setValue(strSetting + \"Size\", parent->size());\n}\n\nvoid restoreWindowGeometry(const QString& strSetting, const QSize& defaultSize, QWidget* parent)\n{\n    QSettings settings;\n    QPoint pos = settings.value(strSetting + \"Pos\").toPoint();\n    QSize size = settings.value(strSetting + \"Size\", defaultSize).toSize();\n\n    if (!pos.x() && !pos.y()) {\n        QRect screen = QApplication::desktop()->screenGeometry();\n        pos.setX((screen.width() - size.width()) \/ 2);\n        pos.setY((screen.height() - size.height()) \/ 2);\n    }\n\n    parent->resize(size);\n    parent->move(pos);\n}\n\n\/\/ Check whether a theme is not build-in\nbool isExternal(QString theme)\n{\n    if (theme.isEmpty())\n        return false;\n\n    return (theme.operator!=(\"default\") && theme.operator!=(\"default-dark\"));\n}\n\n\/\/ Open CSS when configured\nQString loadStyleSheet()\n{\n    QString styleSheet;\n    QSettings settings;\n    QString cssName;\n    QString theme = settings.value(\"theme\", \"\").toString();\n\n    if (isExternal(theme)) {\n        \/\/ External CSS\n        settings.setValue(\"fCSSexternal\", true);\n        fs::path pathAddr = GetDataDir() \/ \"themes\/\";\n        cssName = pathAddr.string().c_str() + theme + \"\/css\/theme.css\";\n    } else {\n        \/\/ Build-in CSS\n        settings.setValue(\"fCSSexternal\", false);\n        if (!theme.isEmpty()) {\n            cssName = QString(\":\/css\/\") + theme;\n        } else {\n            cssName = QString(\":\/css\/default\");\n            settings.setValue(\"theme\", \"default\");\n        }\n    }\n\n    QFile qFile(cssName);\n    if (qFile.open(QFile::ReadOnly)) {\n        styleSheet = QLatin1String(qFile.readAll());\n    }\n\n    return styleSheet;\n}\n\nvoid setClipboard(const QString& str)\n{\n    QApplication::clipboard()->setText(str, QClipboard::Clipboard);\n    QApplication::clipboard()->setText(str, QClipboard::Selection);\n}\n\n#if BOOST_FILESYSTEM_VERSION >= 3\nfs::path qstringToBoostPath(const QString& path)\n{\n    return fs::path(path.toStdString(), utf8);\n}\n\nQString boostPathToQString(const fs::path& path)\n{\n    return QString::fromStdString(path.string(utf8));\n}\n#else\n#warning Conversion between boost path and QString can use invalid character encoding with boost_filesystem v2 and older\nfs::path qstringToBoostPath(const QString& path)\n{\n    return fs::path(path.toStdString());\n}\n\nQString boostPathToQString(const fs::path& path)\n{\n    return QString::fromStdString(path.string());\n}\n#endif\n\nQString formatDurationStr(int secs)\n{\n    QStringList strList;\n    int days = secs \/ 86400;\n    int hours = (secs % 86400) \/ 3600;\n    int mins = (secs % 3600) \/ 60;\n    int seconds = secs % 60;\n\n    if (days)\n        strList.append(QString(QObject::tr(\"%1 d\")).arg(days));\n    if (hours)\n        strList.append(QString(QObject::tr(\"%1 h\")).arg(hours));\n    if (mins)\n        strList.append(QString(QObject::tr(\"%1 m\")).arg(mins));\n    if (seconds || (!days && !hours && !mins))\n        strList.append(QString(QObject::tr(\"%1 s\")).arg(seconds));\n\n    return strList.join(\" \");\n}\n\nQString formatServicesStr(quint64 mask)\n{\n    QStringList strList;\n\n    \/\/ Just scan the last 8 bits for now.\n    for (int i = 0; i < 8; i++) {\n        uint64_t check = 1 << i;\n        if (mask & check) {\n            switch (check) {\n            case NODE_NETWORK:\n                strList.append(QObject::tr(\"NETWORK\"));\n                break;\n            case NODE_BLOOM:\n            case NODE_BLOOM_WITHOUT_MN:\n                strList.append(QObject::tr(\"BLOOM\"));\n                break;\n            default:\n                strList.append(QString(\"%1[%2]\").arg(QObject::tr(\"UNKNOWN\")).arg(check));\n            }\n        }\n    }\n\n    if (strList.size())\n        return strList.join(\" & \");\n    else\n        return QObject::tr(\"None\");\n}\n\nQString formatPingTime(double dPingTime)\n{\n    return dPingTime == 0 ? QObject::tr(\"N\/A\") : QString(QObject::tr(\"%1 ms\")).arg(QString::number((int)(dPingTime * 1000), 10));\n}\n\nQString formatTimeOffset(int64_t nTimeOffset)\n{\n  return QString(QObject::tr(\"%1 s\")).arg(QString::number((int)nTimeOffset, 10));\n}\n\n} \/\/ namespace GUIUtil\n","avg_line_length":32.2683673469,"max_line_length":247,"alphanum_fraction":0.6630933182,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":15904,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":7018.0,"content":"\/* Tencent is pleased to support the open source community by making Hippy available.\n * Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <Hippy.h>\n#include <gtest.h>\n\nTEST(HippyTest, flex_direction_column_no_height) {\n  const HPNodeRef root = HPNodeNew();\n  HPNodeStyleSetWidth(root, 100);\n\n  const HPNodeRef root_child0 = HPNodeNew();\n  HPNodeStyleSetHeight(root_child0, 10);\n  HPNodeInsertChild(root, root_child0, 0);\n\n  const HPNodeRef root_child1 = HPNodeNew();\n  HPNodeStyleSetHeight(root_child1, 10);\n  HPNodeInsertChild(root, root_child1, 1);\n\n  const HPNodeRef root_child2 = HPNodeNew();\n  HPNodeStyleSetHeight(root_child2, 10);\n  HPNodeInsertChild(root, root_child2, 2);\n  HPNodeDoLayout(root, VALUE_UNDEFINED, VALUE_UNDEFINED);\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root));\n  ASSERT_FLOAT_EQ(30, HPNodeLayoutGetHeight(root));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child0));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child0));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child0));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child0));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetTop(root_child1));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child1));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child2));\n  ASSERT_FLOAT_EQ(20, HPNodeLayoutGetTop(root_child2));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child2));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child2));\n\n  HPNodeDoLayout(root, VALUE_UNDEFINED, VALUE_UNDEFINED, DirectionRTL);\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root));\n  ASSERT_FLOAT_EQ(30, HPNodeLayoutGetHeight(root));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child0));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child0));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child0));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child0));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetTop(root_child1));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child1));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child2));\n  ASSERT_FLOAT_EQ(20, HPNodeLayoutGetTop(root_child2));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child2));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child2));\n\n  HPNodeFreeRecursive(root);\n}\n\nTEST(HippyTest, flex_direction_row_no_width) {\n  const HPNodeRef root = HPNodeNew();\n  HPNodeStyleSetFlexDirection(root, FLexDirectionRow);\n  HPNodeStyleSetHeight(root, 100);\n\n  const HPNodeRef root_child0 = HPNodeNew();\n  HPNodeStyleSetWidth(root_child0, 10);\n  HPNodeInsertChild(root, root_child0, 0);\n\n  const HPNodeRef root_child1 = HPNodeNew();\n  HPNodeStyleSetWidth(root_child1, 10);\n  HPNodeInsertChild(root, root_child1, 1);\n\n  const HPNodeRef root_child2 = HPNodeNew();\n  HPNodeStyleSetWidth(root_child2, 10);\n  HPNodeInsertChild(root, root_child2, 2);\n  HPNodeDoLayout(root, VALUE_UNDEFINED, VALUE_UNDEFINED);\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root));\n  ASSERT_FLOAT_EQ(30, HPNodeLayoutGetWidth(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child0));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child0));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child0));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child0));\n\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetLeft(root_child1));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child1));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child1));\n\n  ASSERT_FLOAT_EQ(20, HPNodeLayoutGetLeft(root_child2));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child2));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child2));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child2));\n\n  HPNodeDoLayout(root, VALUE_UNDEFINED, VALUE_UNDEFINED, DirectionRTL);\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root));\n  ASSERT_FLOAT_EQ(30, HPNodeLayoutGetWidth(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root));\n\n  ASSERT_FLOAT_EQ(20, HPNodeLayoutGetLeft(root_child0));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child0));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child0));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child0));\n\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetLeft(root_child1));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child1));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child1));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child2));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child2));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child2));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child2));\n\n  HPNodeFreeRecursive(root);\n}\n\nTEST(HippyTest, flex_direction_column) {\n  const HPNodeRef root = HPNodeNew();\n  HPNodeStyleSetWidth(root, 100);\n  HPNodeStyleSetHeight(root, 100);\n\n  const HPNodeRef root_child0 = HPNodeNew();\n  HPNodeStyleSetHeight(root_child0, 10);\n  HPNodeInsertChild(root, root_child0, 0);\n\n  const HPNodeRef root_child1 = HPNodeNew();\n  HPNodeStyleSetHeight(root_child1, 10);\n  HPNodeInsertChild(root, root_child1, 1);\n\n  const HPNodeRef root_child2 = HPNodeNew();\n  HPNodeStyleSetHeight(root_child2, 10);\n  HPNodeInsertChild(root, root_child2, 2);\n  HPNodeDoLayout(root, VALUE_UNDEFINED, VALUE_UNDEFINED);\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child0));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child0));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child0));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child0));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetTop(root_child1));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child1));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child2));\n  ASSERT_FLOAT_EQ(20, HPNodeLayoutGetTop(root_child2));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child2));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child2));\n\n  HPNodeDoLayout(root, VALUE_UNDEFINED, VALUE_UNDEFINED, DirectionRTL);\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child0));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child0));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child0));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child0));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetTop(root_child1));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child1));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child2));\n  ASSERT_FLOAT_EQ(20, HPNodeLayoutGetTop(root_child2));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child2));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child2));\n\n  HPNodeFreeRecursive(root);\n}\n\nTEST(HippyTest, flex_direction_row) {\n  const HPNodeRef root = HPNodeNew();\n  HPNodeStyleSetFlexDirection(root, FLexDirectionRow);\n  HPNodeStyleSetWidth(root, 100);\n  HPNodeStyleSetHeight(root, 100);\n\n  const HPNodeRef root_child0 = HPNodeNew();\n  HPNodeStyleSetWidth(root_child0, 10);\n  HPNodeInsertChild(root, root_child0, 0);\n\n  const HPNodeRef root_child1 = HPNodeNew();\n  HPNodeStyleSetWidth(root_child1, 10);\n  HPNodeInsertChild(root, root_child1, 1);\n\n  const HPNodeRef root_child2 = HPNodeNew();\n  HPNodeStyleSetWidth(root_child2, 10);\n  HPNodeInsertChild(root, root_child2, 2);\n  HPNodeDoLayout(root, VALUE_UNDEFINED, VALUE_UNDEFINED);\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child0));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child0));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child0));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child0));\n\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetLeft(root_child1));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child1));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child1));\n\n  ASSERT_FLOAT_EQ(20, HPNodeLayoutGetLeft(root_child2));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child2));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child2));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child2));\n\n  HPNodeDoLayout(root, VALUE_UNDEFINED, VALUE_UNDEFINED, DirectionRTL);\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root));\n\n  ASSERT_FLOAT_EQ(90, HPNodeLayoutGetLeft(root_child0));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child0));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child0));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child0));\n\n  ASSERT_FLOAT_EQ(80, HPNodeLayoutGetLeft(root_child1));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child1));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child1));\n\n  ASSERT_FLOAT_EQ(70, HPNodeLayoutGetLeft(root_child2));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child2));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child2));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child2));\n\n  HPNodeFreeRecursive(root);\n}\n\nTEST(HippyTest, flex_direction_column_reverse) {\n  const HPNodeRef root = HPNodeNew();\n  HPNodeStyleSetFlexDirection(root, FLexDirectionColumnReverse);\n  HPNodeStyleSetWidth(root, 100);\n  HPNodeStyleSetHeight(root, 100);\n\n  const HPNodeRef root_child0 = HPNodeNew();\n  HPNodeStyleSetHeight(root_child0, 10);\n  HPNodeInsertChild(root, root_child0, 0);\n\n  const HPNodeRef root_child1 = HPNodeNew();\n  HPNodeStyleSetHeight(root_child1, 10);\n  HPNodeInsertChild(root, root_child1, 1);\n\n  const HPNodeRef root_child2 = HPNodeNew();\n  HPNodeStyleSetHeight(root_child2, 10);\n  HPNodeInsertChild(root, root_child2, 2);\n  HPNodeDoLayout(root, VALUE_UNDEFINED, VALUE_UNDEFINED);\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child0));\n  ASSERT_FLOAT_EQ(90, HPNodeLayoutGetTop(root_child0));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child0));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child0));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child1));\n  ASSERT_FLOAT_EQ(80, HPNodeLayoutGetTop(root_child1));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child1));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child2));\n  ASSERT_FLOAT_EQ(70, HPNodeLayoutGetTop(root_child2));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child2));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child2));\n\n  HPNodeDoLayout(root, VALUE_UNDEFINED, VALUE_UNDEFINED, DirectionRTL);\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child0));\n  ASSERT_FLOAT_EQ(90, HPNodeLayoutGetTop(root_child0));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child0));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child0));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child1));\n  ASSERT_FLOAT_EQ(80, HPNodeLayoutGetTop(root_child1));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child1));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child2));\n  ASSERT_FLOAT_EQ(70, HPNodeLayoutGetTop(root_child2));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root_child2));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetHeight(root_child2));\n\n  HPNodeFreeRecursive(root);\n}\n\nTEST(HippyTest, flex_direction_row_reverse) {\n  const HPNodeRef root = HPNodeNew();\n  HPNodeStyleSetFlexDirection(root, FLexDirectionRowReverse);\n  HPNodeStyleSetWidth(root, 100);\n  HPNodeStyleSetHeight(root, 100);\n\n  const HPNodeRef root_child0 = HPNodeNew();\n  HPNodeStyleSetWidth(root_child0, 10);\n  HPNodeInsertChild(root, root_child0, 0);\n\n  const HPNodeRef root_child1 = HPNodeNew();\n  HPNodeStyleSetWidth(root_child1, 10);\n  HPNodeInsertChild(root, root_child1, 1);\n\n  const HPNodeRef root_child2 = HPNodeNew();\n  HPNodeStyleSetWidth(root_child2, 10);\n  HPNodeInsertChild(root, root_child2, 2);\n  HPNodeDoLayout(root, VALUE_UNDEFINED, VALUE_UNDEFINED);\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root));\n\n  ASSERT_FLOAT_EQ(90, HPNodeLayoutGetLeft(root_child0));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child0));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child0));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child0));\n\n  ASSERT_FLOAT_EQ(80, HPNodeLayoutGetLeft(root_child1));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child1));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child1));\n\n  ASSERT_FLOAT_EQ(70, HPNodeLayoutGetLeft(root_child2));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child2));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child2));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child2));\n\n  HPNodeDoLayout(root, VALUE_UNDEFINED, VALUE_UNDEFINED, DirectionRTL);\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetWidth(root));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root));\n\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetLeft(root_child0));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child0));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child0));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child0));\n\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetLeft(root_child1));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child1));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child1));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child1));\n\n  ASSERT_FLOAT_EQ(20, HPNodeLayoutGetLeft(root_child2));\n  ASSERT_FLOAT_EQ(0, HPNodeLayoutGetTop(root_child2));\n  ASSERT_FLOAT_EQ(10, HPNodeLayoutGetWidth(root_child2));\n  ASSERT_FLOAT_EQ(100, HPNodeLayoutGetHeight(root_child2));\n\n  HPNodeFreeRecursive(root);\n}\n","avg_line_length":39.8596491228,"max_line_length":85,"alphanum_fraction":0.8036343058,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11891,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2122.0,"content":"\/\/ Copyright (c) 2018 Microsoft Corporation\n\/\/ Licensed under the MIT license.\n\/\/ Author: Paul Koch <code@koch.ninja>\n\n#include \"precompiled_header_test.hpp\"\n\n#include \"ebm_native.h\"\n#include \"ebm_native_test.hpp\"\n#include \"RandomStreamTest.hpp\"\n\nstatic const TestPriority k_filePriority = TestPriority::SuggestGraphBounds;\n\n\/\/ TODO : re-formulate these tests after we reach agreement on how the graph bounds are suposed to work\n\nTEST_CASE(\"SuggestGraphBounds, 0 cuts, min -inf, max nan\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 0;\n   constexpr FloatEbmType minValue = -std::numeric_limits<FloatEbmType>::infinity();\n   constexpr FloatEbmType lowestCut = -1;\n   constexpr FloatEbmType highestCut = -1;\n   constexpr FloatEbmType maxValue = std::numeric_limits<FloatEbmType>::quiet_NaN();\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(-std::numeric_limits<FloatEbmType>::infinity() == lowGraphBound);\n   CHECK(-std::numeric_limits<FloatEbmType>::infinity() == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 0 cuts, min nan, max inf\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 0;\n   constexpr FloatEbmType minValue = std::numeric_limits<FloatEbmType>::quiet_NaN();\n   constexpr FloatEbmType lowestCut = -1;\n   constexpr FloatEbmType highestCut = -1;\n   constexpr FloatEbmType maxValue = std::numeric_limits<FloatEbmType>::infinity();\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(std::numeric_limits<FloatEbmType>::infinity() == lowGraphBound);\n   CHECK(std::numeric_limits<FloatEbmType>::infinity() == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 0 cuts, min 7, max 99\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 0;\n   constexpr FloatEbmType minValue = 7;\n   constexpr FloatEbmType lowestCut = -1;\n   constexpr FloatEbmType highestCut = -1;\n   constexpr FloatEbmType maxValue = 99;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(7 == lowGraphBound);\n   CHECK(99 == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, all 6\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 1;\n   constexpr FloatEbmType minValue = 6;\n   constexpr FloatEbmType lowestCut = 6;\n   constexpr FloatEbmType highestCut = 6;\n   constexpr FloatEbmType maxValue = 6;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(6 == lowGraphBound);\n   CHECK(6 == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, progression\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 1;\n   constexpr FloatEbmType minValue = 6;\n   constexpr FloatEbmType lowestCut = 7;\n   constexpr FloatEbmType highestCut = 7;\n   constexpr FloatEbmType maxValue = 8;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(6 == lowGraphBound);\n   CHECK(8 == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 1 cuts, mismatched low high\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 1;\n   constexpr FloatEbmType minValue = -1;\n   constexpr FloatEbmType lowestCut = -2;\n   constexpr FloatEbmType highestCut = -2;\n   constexpr FloatEbmType maxValue = 1;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(lowGraphBound < -2);\n   CHECK(1 == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 1 cuts, mismatched low high\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 1;\n   constexpr FloatEbmType minValue = -2;\n   constexpr FloatEbmType lowestCut = 0;\n   constexpr FloatEbmType highestCut = 0;\n   constexpr FloatEbmType maxValue = -1;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(-2 == lowGraphBound);\n   CHECK(0 < highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 1 cuts, out of range high\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 1;\n   constexpr FloatEbmType minValue = 1;\n   constexpr FloatEbmType lowestCut = 0;\n   constexpr FloatEbmType highestCut = 0;\n   constexpr FloatEbmType maxValue = 2;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(lowGraphBound < 0);\n   CHECK(2 == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 1 cuts, min -inf\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 1;\n   constexpr FloatEbmType minValue = -std::numeric_limits<FloatEbmType>::infinity();\n   constexpr FloatEbmType lowestCut = std::numeric_limits<FloatEbmType>::lowest() + FloatEbmType { 1e300 };\n   constexpr FloatEbmType highestCut = std::numeric_limits<FloatEbmType>::lowest() + FloatEbmType { 1e300 };\n   constexpr FloatEbmType maxValue = std::numeric_limits<FloatEbmType>::lowest() + FloatEbmType { 1.5e300 };\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(minValue == lowGraphBound);\n   CHECK(maxValue == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 1 cuts, max +inf\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 1;\n   constexpr FloatEbmType minValue = std::numeric_limits<FloatEbmType>::max() - 1.5e300;\n   constexpr FloatEbmType lowestCut = std::numeric_limits<FloatEbmType>::max() - 1e300;\n   constexpr FloatEbmType highestCut = std::numeric_limits<FloatEbmType>::max() - 1e300;\n   constexpr FloatEbmType maxValue = std::numeric_limits<FloatEbmType>::infinity();\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(minValue == lowGraphBound);\n   CHECK(maxValue == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 1 cuts, overflow diff\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 1;\n   constexpr FloatEbmType minValue = 0;\n   constexpr FloatEbmType lowestCut = std::numeric_limits<FloatEbmType>::lowest() + 1e300;\n   constexpr FloatEbmType highestCut = lowestCut;\n   constexpr FloatEbmType maxValue = std::numeric_limits<FloatEbmType>::max() - 1e300;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(-std::numeric_limits<FloatEbmType>::infinity() == lowGraphBound);\n   CHECK(maxValue == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 1 cuts, min longest\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 1;\n   constexpr FloatEbmType minValue = 98;\n   constexpr FloatEbmType lowestCut = 100;\n   constexpr FloatEbmType highestCut = 100;\n   constexpr FloatEbmType maxValue = 101;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(98 == lowGraphBound);\n   CHECK(101 == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 1 cuts, max longest\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 1;\n   constexpr FloatEbmType minValue = 99;\n   constexpr FloatEbmType lowestCut = 100;\n   constexpr FloatEbmType highestCut = 100;\n   constexpr FloatEbmType maxValue = 102;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(99 == lowGraphBound);\n   CHECK(102 == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 1 cuts, overflow high\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 1;\n   constexpr FloatEbmType minValue = std::numeric_limits<FloatEbmType>::max() - 1e307;\n   constexpr FloatEbmType lowestCut = std::numeric_limits<FloatEbmType>::max() - 1e306;\n   constexpr FloatEbmType highestCut = std::numeric_limits<FloatEbmType>::max() - 1e306;\n   constexpr FloatEbmType maxValue = std::numeric_limits<FloatEbmType>::max() - 1e307;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(minValue == lowGraphBound);\n   CHECK(std::numeric_limits<FloatEbmType>::infinity() == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 1 cuts, overflow low\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 1;\n   constexpr FloatEbmType minValue = std::numeric_limits<FloatEbmType>::lowest() + 1e307;\n   constexpr FloatEbmType lowestCut = std::numeric_limits<FloatEbmType>::lowest() + 1e306;\n   constexpr FloatEbmType highestCut = std::numeric_limits<FloatEbmType>::lowest() + 1e306;\n   constexpr FloatEbmType maxValue = std::numeric_limits<FloatEbmType>::lowest() + 1e307;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(-std::numeric_limits<FloatEbmType>::infinity() == lowGraphBound);\n   CHECK(maxValue == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 2 cuts\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 2;\n   constexpr FloatEbmType minValue = 5;\n   constexpr FloatEbmType lowestCut = 6;\n   constexpr FloatEbmType highestCut = 7;\n   constexpr FloatEbmType maxValue = 8;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(5 == lowGraphBound);\n   CHECK(8 == highGraphBound);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 4 cuts\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 4;\n   constexpr FloatEbmType minValue = 5;\n   constexpr FloatEbmType lowestCut = 6;\n   constexpr FloatEbmType highestCut = 7;\n   constexpr FloatEbmType maxValue = 8;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK_APPROX(lowGraphBound, 5);\n   CHECK_APPROX(highGraphBound, 8);\n}\n\nTEST_CASE(\"SuggestGraphBounds, 2 cuts, overflow diff\") {\n   FloatEbmType lowGraphBound;\n   FloatEbmType highGraphBound;\n\n   constexpr IntEbmType countCuts = 2;\n   constexpr FloatEbmType minValue = -1;\n   constexpr FloatEbmType lowestCut = std::numeric_limits<FloatEbmType>::lowest();\n   constexpr FloatEbmType highestCut = std::numeric_limits<FloatEbmType>::max();\n   constexpr FloatEbmType maxValue = 1;\n\n   SuggestGraphBounds(\n      countCuts,\n      lowestCut,\n      highestCut,\n      minValue,\n      maxValue,\n      &lowGraphBound,\n      &highGraphBound\n   );\n\n   CHECK(-std::numeric_limits<FloatEbmType>::infinity() == lowGraphBound);\n   CHECK(std::numeric_limits<FloatEbmType>::infinity() == highGraphBound);\n}\n\n","avg_line_length":26.6017897092,"max_line_length":108,"alphanum_fraction":0.70423009,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":19351,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":2.0,"content":"\/*\n* (C) 2016 Philipp Weber\n* (C) 2016 Daniel Neus\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \"tests.h\"\n\n#if defined(BOTAN_HAS_ECIES)\n   #include <botan\/ecies.h>\n   #include <botan\/ecdh.h>\n#endif\n\nnamespace Botan_Tests {\n\nnamespace {\n\n#if defined(BOTAN_HAS_ECIES) && defined(BOTAN_HAS_AES) && defined(BOTAN_HAS_MODE_CBC)\n\nusing Flags = Botan::ECIES_Flags;\n\nBotan::PointGFp::Compression_Type get_compression_type(const std::string& format)\n   {\n   if(format == \"uncompressed\")\n      {\n      return Botan::PointGFp::UNCOMPRESSED;\n      }\n   else if(format == \"compressed\")\n      {\n      return Botan::PointGFp::COMPRESSED;\n      }\n   else if(format == \"hybrid\")\n      {\n      return Botan::PointGFp::HYBRID;\n      }\n   throw Botan::Invalid_Argument(\"invalid compression format\");\n   }\n\nFlags ecies_flags(bool cofactor_mode, bool old_cofactor_mode, bool check_mode, bool single_hash_mode)\n   {\n   return (cofactor_mode ? Flags::COFACTOR_MODE : Flags::NONE)\n          | (single_hash_mode ? Flags::SINGLE_HASH_MODE : Flags::NONE)\n          | (old_cofactor_mode ? Flags::OLD_COFACTOR_MODE : Flags::NONE)\n          | (check_mode ? Flags::CHECK_MODE : Flags::NONE);\n   }\n\nvoid check_encrypt_decrypt(Test::Result& result, const Botan::ECDH_PrivateKey& private_key,\n                           const Botan::ECDH_PrivateKey& other_private_key,\n                           const Botan::ECIES_System_Params& ecies_params,\n                           const Botan::InitializationVector& iv, const std::string& label,\n                           const std::vector<uint8_t>& plaintext, const std::vector<uint8_t>& ciphertext)\n   {\n   try\n      {\n      Botan::ECIES_Encryptor ecies_enc(private_key, ecies_params, Test::rng());\n      ecies_enc.set_other_key(other_private_key.public_point());\n      Botan::ECIES_Decryptor ecies_dec(other_private_key, ecies_params, Test::rng());\n      if(!iv.bits_of().empty())\n         {\n         ecies_enc.set_initialization_vector(iv);\n         ecies_dec.set_initialization_vector(iv);\n         }\n      if(!label.empty())\n         {\n         ecies_enc.set_label(label);\n         ecies_dec.set_label(label);\n         }\n\n      const std::vector<uint8_t> encrypted = ecies_enc.encrypt(plaintext, Test::rng());\n      if(!ciphertext.empty())\n         {\n         result.test_eq(\"encrypted data\", encrypted, ciphertext);\n         }\n      const Botan::secure_vector<uint8_t> decrypted = ecies_dec.decrypt(encrypted);\n      result.test_eq(\"decrypted data equals plaintext\", decrypted, plaintext);\n\n      std::vector<uint8_t> invalid_encrypted = encrypted;\n      uint8_t& last_byte = invalid_encrypted[invalid_encrypted.size() - 1];\n      last_byte = ~last_byte;\n      result.test_throws(\"throw on invalid ciphertext\", [&ecies_dec, &invalid_encrypted]\n         {\n         ecies_dec.decrypt(invalid_encrypted);\n         });\n      }\n   catch(Botan::Lookup_Error& e)\n      {\n      result.test_note(std::string(\"Test not executed: \") + e.what());\n      }\n   }\n\nvoid check_encrypt_decrypt(Test::Result& result, const Botan::ECDH_PrivateKey& private_key,\n                           const Botan::ECDH_PrivateKey& other_private_key,\n                           const Botan::ECIES_System_Params& ecies_params, size_t iv_length = 0)\n   {\n   const std::vector<uint8_t> plaintext { 1, 2, 3 };\n   check_encrypt_decrypt(result, private_key, other_private_key, ecies_params, std::vector<uint8_t>(iv_length, 0), \"\",\n                         plaintext, std::vector<uint8_t>());\n   }\n\n#if defined(BOTAN_HAS_KDF1_18033) && defined(BOTAN_HAS_SHA1)\n\nclass ECIES_ISO_Tests final : public Text_Based_Test\n   {\n   public:\n      ECIES_ISO_Tests() : Text_Based_Test(\n            \"pubkey\/ecies-18033.vec\",\n            \"format,p,a,b,mu,nu,gx,gy,hx,hy,x,r,C0,K\") {}\n\n      Test::Result run_one_test(const std::string& \/*header*\/, const VarMap& vars) override\n         {\n         Test::Result result(\"ECIES-ISO\");\n\n         \/\/ get test vectors defined by ISO 18033\n         const Botan::PointGFp::Compression_Type compression_type = get_compression_type(vars.get_req_str(\"format\"));\n         const Botan::BigInt p = vars.get_req_bn(\"p\");\n         const Botan::BigInt a = vars.get_req_bn(\"a\");\n         const Botan::BigInt b = vars.get_req_bn(\"b\");\n         const Botan::BigInt mu = vars.get_req_bn(\"mu\");   \/\/ order\n         const Botan::BigInt nu = vars.get_req_bn(\"nu\");   \/\/ cofactor\n         const Botan::BigInt gx = vars.get_req_bn(\"gx\");   \/\/ base point x\n         const Botan::BigInt gy = vars.get_req_bn(\"gy\");   \/\/ base point y\n         const Botan::BigInt hx = vars.get_req_bn(\"hx\");   \/\/ x of public point of bob\n         const Botan::BigInt hy = vars.get_req_bn(\"hy\");   \/\/ y of public point of bob\n         const Botan::BigInt x = vars.get_req_bn(\"x\");   \/\/ private key of bob\n         const Botan::BigInt r = vars.get_req_bn(\"r\");   \/\/ (ephemeral) private key of alice\n         const std::vector<uint8_t> c0 = vars.get_req_bin(\"C0\");   \/\/ expected encoded (ephemeral) public key\n         const std::vector<uint8_t> k = vars.get_req_bin(\"K\");   \/\/ expected derived secret\n\n         const Botan::EC_Group domain(p, a, b, gx, gy, mu, nu);\n\n         \/\/ keys of bob\n         const Botan::ECDH_PrivateKey other_private_key(Test::rng(), domain, x);\n         const Botan::PointGFp other_public_key_point = domain.point(hx, hy);\n         const Botan::ECDH_PublicKey other_public_key(domain, other_public_key_point);\n\n         \/\/ (ephemeral) keys of alice\n         const Botan::ECDH_PrivateKey eph_private_key(Test::rng(), domain, r);\n         const Botan::PointGFp eph_public_key_point = eph_private_key.public_point();\n         const std::vector<uint8_t> eph_public_key_bin = eph_public_key_point.encode(compression_type);\n         result.test_eq(\"encoded (ephemeral) public key\", eph_public_key_bin, c0);\n\n         \/\/ test secret derivation: ISO 18033 test vectors use KDF1 from ISO 18033\n         \/\/ no cofactor-\/oldcofactor-\/singlehash-\/check-mode and 128 byte secret length\n         Botan::ECIES_KA_Params ka_params(eph_private_key.domain(), \"KDF1-18033(SHA-1)\", 128, compression_type, Flags::NONE);\n         const Botan::ECIES_KA_Operation ka(eph_private_key, ka_params, true, Test::rng());\n         const Botan::SymmetricKey secret_key = ka.derive_secret(eph_public_key_bin, other_public_key_point);\n         result.test_eq(\"derived secret key\", secret_key.bits_of(), k);\n\n         \/\/ test encryption \/ decryption\n\n         for(auto comp_type : { Botan::PointGFp::UNCOMPRESSED, Botan::PointGFp::COMPRESSED, Botan::PointGFp::HYBRID })\n            {\n            for(bool cofactor_mode : { true, false })\n               {\n               for(bool single_hash_mode : { true, false })\n                  {\n                  for(bool old_cofactor_mode : { true, false })\n                     {\n                     for(bool check_mode : { true, false })\n                        {\n                        Flags flags = ecies_flags(cofactor_mode, old_cofactor_mode, check_mode, single_hash_mode);\n\n                        if(size_t(cofactor_mode) + size_t(check_mode) + size_t(old_cofactor_mode) > 1)\n                           {\n                           auto onThrow =  [&]()\n                              {\n                              Botan::ECIES_System_Params(eph_private_key.domain(),\n                                 \"KDF2(SHA-1)\", \"AES-256\/CBC\", 32, \"HMAC(SHA-1)\", 20,\n                                 comp_type, flags);\n                              };\n                           result.test_throws(\"throw on invalid ECIES_Flags\", onThrow);\n                           continue;\n                           }\n\n                        Botan::ECIES_System_Params ecies_params(eph_private_key.domain(), \"KDF2(SHA-1)\", \"AES-256\/CBC\",\n                                                                32, \"HMAC(SHA-1)\", 20, comp_type, flags);\n                        check_encrypt_decrypt(result, eph_private_key, other_private_key, ecies_params, 16);\n                        }\n                     }\n                  }\n               }\n            }\n\n         return result;\n         }\n   };\n\nBOTAN_REGISTER_TEST(\"pubkey\", \"ecies_iso\", ECIES_ISO_Tests);\n\n#endif\n\nclass ECIES_Tests final : public Text_Based_Test\n   {\n   public:\n      ECIES_Tests()\n         : Text_Based_Test(\n              \"pubkey\/ecies.vec\",\n              \"Curve,PrivateKey,OtherPrivateKey,Kdf,Dem,DemKeyLen,Mac,MacKeyLen,Format,\"\n              \"CofactorMode,OldCofactorMode,CheckMode,SingleHashMode,Label,Plaintext,Ciphertext\",\n              \"Iv\") {}\n\n      Test::Result run_one_test(const std::string& \/*header*\/, const VarMap& vars) override\n         {\n         Test::Result result(\"ECIES\");\n\n         const std::string curve = vars.get_req_str(\"Curve\");\n         const Botan::BigInt private_key_value = vars.get_req_bn(\"PrivateKey\");\n         const Botan::BigInt other_private_key_value = vars.get_req_bn(\"OtherPrivateKey\");\n         const std::string kdf = vars.get_req_str(\"Kdf\");\n         const std::string dem = vars.get_req_str(\"Dem\");\n         const size_t dem_key_len = vars.get_req_sz(\"DemKeyLen\");\n         const std::vector<uint8_t> iv = vars.get_opt_bin(\"Iv\");\n         const std::string mac = vars.get_req_str(\"Mac\");\n         const size_t mac_key_len = vars.get_req_sz(\"MacKeyLen\");\n         const Botan::PointGFp::Compression_Type compression_type = get_compression_type(vars.get_req_str(\"Format\"));\n         const bool cofactor_mode = vars.get_req_sz(\"CofactorMode\") != 0;\n         const bool old_cofactor_mode = vars.get_req_sz(\"OldCofactorMode\") != 0;\n         const bool check_mode = vars.get_req_sz(\"CheckMode\") != 0;\n         const bool single_hash_mode = vars.get_req_sz(\"SingleHashMode\") != 0;\n         const std::string label = vars.get_req_str(\"Label\");\n         const std::vector<uint8_t> plaintext = vars.get_req_bin(\"Plaintext\");\n         const std::vector<uint8_t> ciphertext = vars.get_req_bin(\"Ciphertext\");\n\n         const Flags flags = ecies_flags(cofactor_mode, old_cofactor_mode, check_mode, single_hash_mode);\n         const Botan::EC_Group domain(curve);\n         const Botan::ECDH_PrivateKey private_key(Test::rng(), domain, private_key_value);\n         const Botan::ECDH_PrivateKey other_private_key(Test::rng(), domain, other_private_key_value);\n\n         const Botan::ECIES_System_Params ecies_params(private_key.domain(), kdf, dem, dem_key_len, mac, mac_key_len,\n               compression_type, flags);\n         check_encrypt_decrypt(result, private_key, other_private_key, ecies_params, iv, label, plaintext, ciphertext);\n\n         return result;\n         }\n\n   };\n\nBOTAN_REGISTER_TEST(\"pubkey\", \"ecies\", ECIES_Tests);\n\n#if defined(BOTAN_HAS_KDF1_18033) && defined(BOTAN_HAS_HMAC) && defined(BOTAN_HAS_AES) && defined(BOTAN_HAS_SHA2_64)\n\nTest::Result test_other_key_not_set()\n   {\n   Test::Result result(\"ECIES other key not set\");\n\n   const Flags flags = ecies_flags(false, false, false, true);\n   const Botan::EC_Group domain(\"secp521r1\");\n   const Botan::BigInt private_key_value(\"405029866705438137604064977397053031159826489755682166267763407\"\n                                         \"5002761777100287880684822948852132235484464537021197213998300006\"\n                                         \"547176718172344447619746779823\");\n\n   const Botan::ECDH_PrivateKey private_key(Test::rng(), domain, private_key_value);\n   const Botan::ECIES_System_Params ecies_params(private_key.domain(), \"KDF1-18033(SHA-512)\", \"AES-256\/CBC\", 32,\n         \"HMAC(SHA-512)\", 20, Botan::PointGFp::Compression_Type::COMPRESSED,\n         flags);\n\n   Botan::ECIES_Encryptor ecies_enc(private_key, ecies_params, Test::rng());\n\n   result.test_throws(\"encrypt not possible without setting other public key\", [ &ecies_enc ]()\n      {\n      ecies_enc.encrypt(std::vector<uint8_t>(8), Test::rng());\n      });\n\n   return result;\n   }\n\nTest::Result test_kdf_not_found()\n   {\n   Test::Result result(\"ECIES kdf not found\");\n\n   const Flags flags = ecies_flags(false, false, false, true);\n   const Botan::EC_Group domain(\"secp521r1\");\n   const Botan::BigInt private_key_value(\"405029866705438137604064977397053031159826489755682166267763407\"\n                                         \"5002761777100287880684822948852132235484464537021197213998300006\"\n                                         \"547176718172344447619746779823\");\n\n   const Botan::ECDH_PrivateKey private_key(Test::rng(), domain, private_key_value);\n   const Botan::ECIES_System_Params ecies_params(private_key.domain(), \"KDF-XYZ(SHA-512)\", \"AES-256\/CBC\", 32,\n         \"HMAC(SHA-512)\", 20, Botan::PointGFp::Compression_Type::COMPRESSED,\n         flags);\n\n   result.test_throws(\"kdf not found\", [&]()\n      {\n      Botan::ECIES_Encryptor ecies_enc(private_key, ecies_params, Test::rng());\n      ecies_enc.encrypt(std::vector<uint8_t>(8), Test::rng());\n      });\n\n   return result;\n   }\n\nTest::Result test_mac_not_found()\n   {\n   Test::Result result(\"ECIES mac not found\");\n\n   const Flags flags = ecies_flags(false, false, false, true);\n   const Botan::EC_Group domain(\"secp521r1\");\n   const Botan::BigInt private_key_value(\"405029866705438137604064977397053031159826489755682166267763407\"\n                                         \"5002761777100287880684822948852132235484464537021197213998300006\"\n                                         \"547176718172344447619746779823\");\n\n   const Botan::ECDH_PrivateKey private_key(Test::rng(), domain, private_key_value);\n   const Botan::ECIES_System_Params ecies_params(private_key.domain(), \"KDF1-18033(SHA-512)\", \"AES-256\/CBC\", 32,\n         \"XYZMAC(SHA-512)\", 20, Botan::PointGFp::Compression_Type::COMPRESSED,\n         flags);\n\n   result.test_throws(\"mac not found\", [&]()\n      {\n      Botan::ECIES_Encryptor ecies_enc(private_key, ecies_params, Test::rng());\n      ecies_enc.encrypt(std::vector<uint8_t>(8), Test::rng());\n      });\n\n   return result;\n   }\n\nTest::Result test_cipher_not_found()\n   {\n   Test::Result result(\"ECIES cipher not found\");\n\n   const Flags flags = ecies_flags(false, false, false, true);\n   const Botan::EC_Group domain(\"secp521r1\");\n   const Botan::BigInt private_key_value(\"405029866705438137604064977397053031159826489755682166267763407\"\n                                         \"5002761777100287880684822948852132235484464537021197213998300006\"\n                                         \"547176718172344447619746779823\");\n\n   const Botan::ECDH_PrivateKey private_key(Test::rng(), domain, private_key_value);\n   const Botan::ECIES_System_Params ecies_params(private_key.domain(), \"KDF1-18033(SHA-512)\", \"AES-XYZ-256\/CBC\", 32,\n         \"HMAC(SHA-512)\", 20, Botan::PointGFp::Compression_Type::COMPRESSED,\n         flags);\n\n   result.test_throws(\"cipher not found\", [&]()\n      {\n      Botan::ECIES_Encryptor ecies_enc(private_key, ecies_params, Test::rng());\n      ecies_enc.encrypt(std::vector<uint8_t>(8), Test::rng());\n      });\n\n   return result;\n   }\n\nTest::Result test_system_params_short_ctor()\n   {\n   Test::Result result(\"ECIES short system params ctor\");\n\n   const Botan::EC_Group domain(\"secp521r1\");\n   const Botan::BigInt private_key_value(\"405029866705438137604064977397053031159826489755682166267763407\"\n                                         \"5002761777100287880684822948852132235484464537021197213998300006\"\n                                         \"547176718172344447619746779823\");\n\n   const Botan::BigInt other_private_key_value(\"2294226772740614508941417891614236736606752960073669253551166842\"\n         \"5866095315090327914760325168219669828915074071456176066304457448\"\n         \"25404691681749451640151380153\");\n\n   const Botan::ECDH_PrivateKey private_key(Test::rng(), domain, private_key_value);\n   const Botan::ECDH_PrivateKey other_private_key(Test::rng(), domain, other_private_key_value);\n\n   const Botan::ECIES_System_Params ecies_params(private_key.domain(), \"KDF1-18033(SHA-512)\", \"AES-256\/CBC\", 32,\n         \"HMAC(SHA-512)\", 16);\n\n   const Botan::InitializationVector iv(\"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\");\n   const std::string label = \"Test\";\n\n   const std::vector<uint8_t> plaintext = Botan::hex_decode(\"000102030405060708090A0B0C0D0E0F\");\n\n   \/\/ generated with botan\n   const std::vector<uint8_t> ciphertext = Botan::hex_decode(\"0401519EAA0489FF9D51E98E4C22349463E2001CD06F8CE47D81D4007A\"\n                                           \"79ACF98E92C814686477CEA666EFC277DC84E15FC95E38AFF8E16D478A\"\n                                           \"44CD5C5F1517F8B1F300000591317F261C3D04A7207F01EAE3EC70F2360\"\n                                           \"0F82C53CC0B85BE7AC9F6CE79EF2AB416E5934D61BA9D346385D7545C57F\"\n                                           \"77C7EA7C58E18C70CBFB0A24AE1B9943EC5A8D0657522CCDF30BA95674D81\"\n                                           \"B397635D215178CD13BD9504AE957A9888F4128FFC0F0D3F1CEC646AEC8CE\"\n                                           \"3F2463D233B22A7A12B679F4C06501F584D4DEFF6D26592A8D873398BD892\"\n                                           \"B477B3468813C053DA43C4F3D49009F7A12D6EF7\");\n\n   check_encrypt_decrypt(result, private_key, other_private_key, ecies_params, iv, label, plaintext, ciphertext);\n\n   return result;\n   }\n\nTest::Result test_ciphertext_too_short()\n   {\n   Test::Result result(\"ECIES ciphertext too short\");\n\n   const Botan::EC_Group domain(\"secp521r1\");\n   const Botan::BigInt private_key_value(\"405029866705438137604064977397053031159826489755682166267763407\"\n                                         \"5002761777100287880684822948852132235484464537021197213998300006\"\n                                         \"547176718172344447619746779823\");\n\n   const Botan::BigInt other_private_key_value(\"2294226772740614508941417891614236736606752960073669253551166842\"\n         \"5866095315090327914760325168219669828915074071456176066304457448\"\n         \"25404691681749451640151380153\");\n\n   const Botan::ECDH_PrivateKey private_key(Test::rng(), domain, private_key_value);\n   const Botan::ECDH_PrivateKey other_private_key(Test::rng(), domain, other_private_key_value);\n\n   const Botan::ECIES_System_Params ecies_params(private_key.domain(), \"KDF1-18033(SHA-512)\", \"AES-256\/CBC\", 32,\n         \"HMAC(SHA-512)\", 16);\n\n   Botan::ECIES_Decryptor ecies_dec(other_private_key, ecies_params, Test::rng());\n\n   result.test_throws(\"ciphertext too short\", [ &ecies_dec ]()\n      {\n      ecies_dec.decrypt(Botan::hex_decode(\"0401519EAA0489FF9D51E98E4C22349A\"));\n      });\n\n   return result;\n   }\n\nclass ECIES_Unit_Tests final : public Test\n   {\n   public:\n      std::vector<Test::Result> run() override\n         {\n         std::vector<Test::Result> results;\n\n         std::vector<std::function<Test::Result()>> fns =\n            {\n            test_other_key_not_set,\n            test_kdf_not_found,\n            test_mac_not_found,\n            test_cipher_not_found,\n            test_system_params_short_ctor,\n            test_ciphertext_too_short\n            };\n\n         for(size_t i = 0; i != fns.size(); ++i)\n            {\n            try\n               {\n               results.emplace_back(fns[ i ]());\n               }\n            catch(std::exception& e)\n               {\n               results.emplace_back(Test::Result::Failure(\"ECIES unit tests \" + std::to_string(i), e.what()));\n               }\n            }\n\n         return results;\n         }\n   };\n\nBOTAN_REGISTER_TEST(\"pubkey\", \"ecies_unit\", ECIES_Unit_Tests);\n\n#endif\n\n#endif\n\n}\n\n}\n","avg_line_length":43.0022222222,"max_line_length":125,"alphanum_fraction":0.6389850654,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3447,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.\n\n#include \"UnrealEd.h\"\n\n\/\/ FPreviewScene derived helpers for rendering\n#include \"ThumbnailHelpers.h\"\n\n#include \"Particles\/ParticleSystem.h\"\n#include \"EngineModule.h\"\n#include \"RendererInterface.h\"\n#include \"CanvasTypes.h\"\n\nUParticleSystemThumbnailRenderer::UParticleSystemThumbnailRenderer(const FObjectInitializer& ObjectInitializer)\n\t: Super(ObjectInitializer)\n{\n\t\/\/ Structure to hold one-time initialization\n\tstruct FConstructorStatics\n\t{\n\t\tConstructorHelpers::FObjectFinder<UTexture2D> PSysThumbnail_NoImage;\n\t\tConstructorHelpers::FObjectFinder<UTexture2D> PSysThumbnail_OOD;\n\t\tFConstructorStatics()\n\t\t\t: PSysThumbnail_NoImage(TEXT(\"\/Engine\/EditorMaterials\/ParticleSystems\/PSysThumbnail_NoImage\"))\n\t\t\t, PSysThumbnail_OOD(TEXT(\"\/Engine\/EditorMaterials\/ParticleSystems\/PSysThumbnail_OOD\"))\n\t\t{\n\t\t}\n\t};\n\tstatic FConstructorStatics ConstructorStatics;\n\n\tNoImage = ConstructorStatics.PSysThumbnail_NoImage.Object;\n\tOutOfDate = ConstructorStatics.PSysThumbnail_OOD.Object;\n\tThumbnailScene = nullptr;\n}\n\nvoid UParticleSystemThumbnailRenderer::GetThumbnailSize(UObject* Object, float Zoom, uint32& OutWidth, uint32& OutHeight) const\n{\n\t\/\/ Particle system thumbnails will be 1024x1024 at 100%.\n\tUParticleSystem* PSys = Cast<UParticleSystem>(Object);\n\tif (PSys != nullptr)\n\t{\n\t\tif ((PSys->bUseRealtimeThumbnail) ||\n\t\t\t(PSys->ThumbnailImage) || \n\t\t\t(NoImage))\n\t\t{\n\t\t\tOutWidth = FMath::TruncToInt(1024 * Zoom);\n\t\t\tOutHeight = FMath::TruncToInt(1024 * Zoom);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Nothing valid to display\n\t\t\tOutWidth = OutHeight = 0;\n\t\t}\n\t}\n\telse\n\t{\n\t\tOutWidth = OutHeight = 0;\n\t}\n}\n\nvoid UParticleSystemThumbnailRenderer::Draw(UObject* Object, int32 X, int32 Y, uint32 Width, uint32 Height, FRenderTarget* RenderTarget,FCanvas* Canvas)\n{\n\tif (GUnrealEd->GetThumbnailManager())\n\t{\n\t\tUParticleSystem* ParticleSystem = Cast<UParticleSystem>(Object);\n\t\tif (ParticleSystem != nullptr)\n\t\t{\n\t\t\tif ( ParticleSystem->bUseRealtimeThumbnail )\n\t\t\t{\n\t\t\t\tif ( ThumbnailScene == nullptr )\n\t\t\t\t{\n\t\t\t\t\tThumbnailScene = new FParticleSystemThumbnailScene();\n\t\t\t\t}\n\n\t\t\t\tThumbnailScene->SetParticleSystem(ParticleSystem);\n\t\t\t\tFSceneViewFamilyContext ViewFamily( FSceneViewFamily::ConstructionValues( RenderTarget, ThumbnailScene->GetScene(), FEngineShowFlags(ESFIM_Game))\n\t\t\t\t\t.SetWorldTimes(FApp::GetCurrentTime() - GStartTime, FApp::GetDeltaTime(), FApp::GetCurrentTime() - GStartTime));\n\t\t\t\n\t\t\t\tViewFamily.EngineShowFlags.DisableAdvancedFeatures();\n\t\t\t\tViewFamily.EngineShowFlags.MotionBlur = 0;\n\n\t\t\t\tThumbnailScene->GetView(&ViewFamily, X, Y, Width, Height);\n\t\t\t\tGetRendererModule().BeginRenderingViewFamily(Canvas,&ViewFamily);\n\t\t\t\tThumbnailScene->SetParticleSystem(nullptr);\n\t\t\t}\n\t\t\telse if (ParticleSystem->ThumbnailImage)\n\t\t\t{\n\t\t\t\tCanvas->DrawTile(X,Y,Width,Height,0.f,0.f,1.f,1.f,FLinearColor::White,\n\t\t\t\t\tParticleSystem->ThumbnailImage->Resource,false);\n\t\t\t\tif (ParticleSystem->ThumbnailImageOutOfDate == true)\n\t\t\t\t{\n\t\t\t\t\tCanvas->DrawTile(X,Y,Width\/2,Height\/2,0.f,0.f,1.f,1.f,FLinearColor::White,\n\t\t\t\t\t\tOutOfDate->Resource,true);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (NoImage)\n\t\t\t{\n\t\t\t\t\/\/ Use the texture interface to draw\n\t\t\t\tCanvas->DrawTile(X,Y,Width,Height,0.f,0.f,1.f,1.f,FLinearColor::White,\n\t\t\t\t\tNoImage->Resource,false);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid UParticleSystemThumbnailRenderer::BeginDestroy()\n{\n\tif ( ThumbnailScene != nullptr )\n\t{\n\t\tdelete ThumbnailScene;\n\t\tThumbnailScene = nullptr;\n\t}\n\n\tSuper::BeginDestroy();\n}\n","avg_line_length":30.2368421053,"max_line_length":152,"alphanum_fraction":0.7435451117,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3586,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["blessing"],"max_stars_count":1.0,"content":"\/**********************************************************************\n *  Copyright (c) 2008-2016, Alliance for Sustainable Energy.\n *  All rights reserved.\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation; either\n *  version 2.1 of the License, or (at your option) any later version.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n **********************************************************************\/\n\n#include \"..\/ForwardTranslator.hpp\"\n#include \"..\/..\/model\/Model.hpp\"\n#include \"..\/..\/model\/CoilHeatingElectric.hpp\"\n#include \"..\/..\/model\/CoilHeatingElectric_Impl.hpp\"\n#include \"..\/..\/model\/Schedule.hpp\"\n#include \"..\/..\/model\/Schedule_Impl.hpp\"\n#include \"..\/..\/model\/Node.hpp\"\n#include \"..\/..\/model\/Node_Impl.hpp\"\n#include <utilities\/idd\/Coil_Heating_Electric_FieldEnums.hxx>\n#include \"..\/..\/utilities\/idd\/IddEnums.hpp\"\n#include <utilities\/idd\/IddEnums.hxx>\n#include <utilities\/idd\/IddFactory.hxx>\n\nusing namespace openstudio::model;\n\nusing namespace std;\n\nnamespace openstudio {\n\nnamespace energyplus {\n\nboost::optional<IdfObject> ForwardTranslator::translateCoilHeatingElectric( CoilHeatingElectric & modelObject )\n{\n  boost::optional<std::string> s;\n  boost::optional<double> value;\n\n  IdfObject idfObject(IddObjectType::Coil_Heating_Electric);\n\n  m_idfObjects.push_back(idfObject);\n\n  \/\/ Name\n\n  s = modelObject.name();\n  if( s )\n  {\n    idfObject.setName(*s);\n  }\n\n  \/\/ AvailabilityScheduleName\n\n  if( boost::optional<Schedule> schedule = modelObject.availabilitySchedule() )\n  {\n    if( boost::optional<IdfObject> _schedule = translateAndMapModelObject(schedule.get()) )\n    {\n      idfObject.setString(Coil_Heating_ElectricFields::AvailabilityScheduleName,_schedule->name().get());\n    }\n  }\n\n  \/\/ Efficiency\n\n  if( (value = modelObject.efficiency()) )\n  {\n    idfObject.setDouble(Coil_Heating_ElectricFields::Efficiency,value.get());\n  }\n\n  \/\/ Nominal Capacity \n  \n  if( modelObject.isNominalCapacityAutosized() )\n  {\n    idfObject.setString(Coil_Heating_ElectricFields::NominalCapacity,\"Autosize\");\n  }\n  else if( (value = modelObject.nominalCapacity()) )\n  {\n    idfObject.setDouble(Coil_Heating_ElectricFields::NominalCapacity,value.get());\n  }\n\n  \/\/ Air Inlet Node Name\n \n  if( boost::optional<ModelObject> mo = modelObject.inletModelObject() )\n  {\n    if( boost::optional<Node> node = mo->optionalCast<Node>() )\n    {\n      idfObject.setString(Coil_Heating_ElectricFields::AirInletNodeName,node->name().get());\n    }\n  }\n\n  \/\/ Air Outlet Node Name\n \n  if( boost::optional<ModelObject> mo = modelObject.outletModelObject() )\n  {\n    if( boost::optional<Node> node = mo->optionalCast<Node>() )\n    {\n      idfObject.setString(Coil_Heating_ElectricFields::AirOutletNodeName,node->name().get());\n    }\n  }\n\n  \/\/ Temperature Setpoint Node Name \n \n  if( boost::optional<Node> node = modelObject.temperatureSetpointNode() )\n  {\n    idfObject.setString(Coil_Heating_ElectricFields::TemperatureSetpointNodeName,node->name().get());\n  }\n\n  return idfObject;\n}\n\n} \/\/ energyplus\n\n} \/\/ openstudio\n\n","avg_line_length":29.8833333333,"max_line_length":111,"alphanum_fraction":0.6907417736,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":96050,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":8.0,"content":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Copyright (c) 2014 The Potcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"wallet.h\"\n#include \"walletdb.h\"\n#include \"crypter.h\"\n#include \"ui_interface.h\"\n#include \"base58.h\"\n#include \"kernel.h\"\n#include \"coincontrol.h\"\n#include <boost\/algorithm\/string\/replace.hpp>\n\nusing namespace std;\n\n\nbool bSpendZeroConfChange = true;\n\ntypedef vector<unsigned char> valtype;\n\n\/\/ we split the coinstake output in two to avoid concentrating\n\/\/ too many coins in one output. currently almost always split.\nunsigned int nStakeSplitAge = 10 * 24 * 60 * 60;; \/\/ 10 days\nint64 nStakeCombineThreshold = 250 * COIN;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ mapWallet\n\/\/\n\nstruct CompareValueOnly\n{\n    bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,\n                    const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const\n    {\n        return t1.first < t2.first;\n    }\n};\n\nCPubKey CWallet::GenerateNewKey()\n{\n    bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); \/\/ default to compressed public keys if we want 0.6.0 wallets\n\n    RandAddSeedPerfmon();\n    CKey secret;\n    secret.MakeNewKey(fCompressed);\n\n    \/\/ Compressed public keys were introduced in version 0.6.0\n    if (fCompressed)\n        SetMinVersion(FEATURE_COMPRPUBKEY);\n\n    CPubKey pubkey = secret.GetPubKey();\n    if (!AddKeyPubKey(secret, pubkey))\n        throw std::runtime_error(\"CWallet::GenerateNewKey() : AddKey failed\");\n    return pubkey;\n}\n\nbool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)\n{\n    if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))\n        return false;\n    if (!fFileBacked)\n        return true;\n    if (!IsCrypted()) {\n        return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey());\n    }\n    return true;\n}\n\nbool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)\n{\n    if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))\n        return false;\n    if (!fFileBacked)\n        return true;\n    {\n        LOCK(cs_wallet);\n        if (pwalletdbEncryption)\n            return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);\n        else\n            return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);\n    }\n    return false;\n}\n\nbool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)\n{\n    return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);\n}\n\nbool CWallet::AddCScript(const CScript& redeemScript)\n{\n    if (!CCryptoKeyStore::AddCScript(redeemScript))\n        return false;\n    if (!fFileBacked)\n        return true;\n    return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);\n}\n\n\/\/ ppcoin\n\/\/ optional setting to unlock wallet for staking only\n\/\/ serves to disable the trivial sendmoney when OS account compromised\n\/\/ provides no real security\nbool fWalletUnlockStakingOnly = false;\n\nbool CWallet::Unlock(const SecureString& strWalletPassphrase)\n{\n    if (!IsLocked())\n        return false;\n\n    CCrypter crypter;\n    CKeyingMaterial vMasterKey;\n\n    {\n        LOCK(cs_wallet);\n        BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)\n        {\n            if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))\n                return false;\n            if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))\n                return false;\n            if (CCryptoKeyStore::Unlock(vMasterKey))\n                return true;\n        }\n    }\n    return false;\n}\n\nbool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)\n{\n    bool fWasLocked = IsLocked();\n\n    {\n        LOCK(cs_wallet);\n        Lock();\n\n        CCrypter crypter;\n        CKeyingMaterial vMasterKey;\n        BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)\n        {\n            if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))\n                return false;\n            if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))\n                return false;\n            if (CCryptoKeyStore::Unlock(vMasterKey))\n            {\n                int64 nStartTime = GetTimeMillis();\n                crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);\n                pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 \/ ((double)(GetTimeMillis() - nStartTime)));\n\n                nStartTime = GetTimeMillis();\n                crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);\n                pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 \/ ((double)(GetTimeMillis() - nStartTime))) \/ 2;\n\n                if (pMasterKey.second.nDeriveIterations < 25000)\n                    pMasterKey.second.nDeriveIterations = 25000;\n\n                printf(\"Wallet passphrase changed to an nDeriveIterations of %i\\n\", pMasterKey.second.nDeriveIterations);\n\n                if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))\n                    return false;\n                if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))\n                    return false;\n                CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);\n                if (fWasLocked)\n                    Lock();\n                return true;\n            }\n        }\n    }\n\n    return false;\n}\n\nvoid CWallet::SetBestChain(const CBlockLocator& loc)\n{\n    CWalletDB walletdb(strWalletFile);\n    walletdb.WriteBestBlock(loc);\n}\n\n\/\/ This class implements an addrIncoming entry that causes pre-0.4\n\/\/ clients to crash on startup if reading a private-key-encrypted wallet.\nclass CCorruptAddress\n{\npublic:\n    IMPLEMENT_SERIALIZE\n    (\n        if (nType & SER_DISK)\n            READWRITE(nVersion);\n    )\n};\n\nbool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)\n{\n    if (nWalletVersion >= nVersion)\n        return true;\n\n    \/\/ when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way\n    if (fExplicit && nVersion > nWalletMaxVersion)\n            nVersion = FEATURE_LATEST;\n\n    nWalletVersion = nVersion;\n\n    if (nVersion > nWalletMaxVersion)\n        nWalletMaxVersion = nVersion;\n\n    if (fFileBacked)\n    {\n        CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);\n        if (nWalletVersion >= 40000)\n        {\n            \/\/ Versions prior to 0.4.0 did not support the \"minversion\" record.\n            \/\/ Use a CCorruptAddress to make them crash instead.\n            CCorruptAddress corruptAddress;\n            pwalletdb->WriteSetting(\"addrIncoming\", corruptAddress);\n        }\n        if (nWalletVersion > 40000)\n            pwalletdb->WriteMinVersion(nWalletVersion);\n        if (!pwalletdbIn)\n            delete pwalletdb;\n    }\n\n    return true;\n}\n\nbool CWallet::SetMaxVersion(int nVersion)\n{\n    \/\/ cannot downgrade below current version\n    if (nWalletVersion > nVersion)\n        return false;\n\n    nWalletMaxVersion = nVersion;\n\n    return true;\n}\n\nbool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)\n{\n    if (IsCrypted())\n        return false;\n\n    CKeyingMaterial vMasterKey;\n    RandAddSeedPerfmon();\n\n    vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);\n    RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);\n\n    CMasterKey kMasterKey;\n\n    RandAddSeedPerfmon();\n    kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);\n    RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);\n\n    CCrypter crypter;\n    int64 nStartTime = GetTimeMillis();\n    crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);\n    kMasterKey.nDeriveIterations = 2500000 \/ ((double)(GetTimeMillis() - nStartTime));\n\n    nStartTime = GetTimeMillis();\n    crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);\n    kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 \/ ((double)(GetTimeMillis() - nStartTime))) \/ 2;\n\n    if (kMasterKey.nDeriveIterations < 25000)\n        kMasterKey.nDeriveIterations = 25000;\n\n    printf(\"Encrypting Wallet with an nDeriveIterations of %i\\n\", kMasterKey.nDeriveIterations);\n\n    if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))\n        return false;\n    if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))\n        return false;\n\n    {\n        LOCK(cs_wallet);\n        mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;\n        if (fFileBacked)\n        {\n            pwalletdbEncryption = new CWalletDB(strWalletFile);\n            if (!pwalletdbEncryption->TxnBegin())\n                return false;\n            pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);\n        }\n\n        if (!EncryptKeys(vMasterKey))\n        {\n            if (fFileBacked)\n                pwalletdbEncryption->TxnAbort();\n            exit(1); \/\/We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet.\n        }\n\n        \/\/ Encryption was introduced in version 0.4.0\n        SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);\n\n        if (fFileBacked)\n        {\n            if (!pwalletdbEncryption->TxnCommit())\n                exit(1); \/\/We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet.\n\n            delete pwalletdbEncryption;\n            pwalletdbEncryption = NULL;\n        }\n\n        Lock();\n        Unlock(strWalletPassphrase);\n        NewKeyPool();\n        Lock();\n\n        \/\/ Need to completely rewrite the wallet file; if we don't, bdb might keep\n        \/\/ bits of the unencrypted private key in slack space in the database file.\n        CDB::Rewrite(strWalletFile);\n\n    }\n    NotifyStatusChanged(this);\n\n    return true;\n}\n\nint64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)\n{\n    int64 nRet = nOrderPosNext++;\n    if (pwalletdb) {\n        pwalletdb->WriteOrderPosNext(nOrderPosNext);\n    } else {\n        CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);\n    }\n    return nRet;\n}\n\nCWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)\n{\n    CWalletDB walletdb(strWalletFile);\n\n    \/\/ First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.\n    TxItems txOrdered;\n\n    \/\/ Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry\n    \/\/ would make this much faster for applications that do this a lot.\n    for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\n    {\n        CWalletTx* wtx = &((*it).second);\n        txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));\n    }\n    acentries.clear();\n    walletdb.ListAccountCreditDebit(strAccount, acentries);\n    BOOST_FOREACH(CAccountingEntry& entry, acentries)\n    {\n        txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));\n    }\n\n    return txOrdered;\n}\n\nvoid CWallet::WalletUpdateSpent(const CTransaction &tx)\n{\n    \/\/ Anytime a signature is successfully verified, it's proof the outpoint is spent.\n    \/\/ Update the wallet spent flag if it doesn't know due to wallet.dat being\n    \/\/ restored from backup or the user making copies of wallet.dat.\n    {\n        LOCK(cs_wallet);\n        BOOST_FOREACH(const CTxIn& txin, tx.vin)\n        {\n            map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);\n            if (mi != mapWallet.end())\n            {\n                CWalletTx& wtx = (*mi).second;\n                if (txin.prevout.n >= wtx.vout.size())\n                    printf(\"WalletUpdateSpent: bad wtx %s\\n\", wtx.GetHash().ToString().c_str());\n                else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))\n                {\n                    printf(\"WalletUpdateSpent found spent coin %s UNIFY %s\\n\", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());\n                    wtx.MarkSpent(txin.prevout.n);\n                    wtx.WriteToDisk();\n                    NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);\n                }\n            }\n        }\n    }\n}\n\nvoid CWallet::MarkDirty()\n{\n    {\n        LOCK(cs_wallet);\n        BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)\n            item.second.MarkDirty();\n    }\n}\n\nbool CWallet::AddToWallet(const CWalletTx& wtxIn)\n{\n    uint256 hash = wtxIn.GetHash();\n    {\n        LOCK(cs_wallet);\n        \/\/ Inserts only if not already there, returns tx inserted or tx found\n        pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));\n        CWalletTx& wtx = (*ret.first).second;\n        wtx.BindWallet(this);\n        bool fInsertedNew = ret.second;\n        if (fInsertedNew)\n        {\n            wtx.nTimeReceived = GetAdjustedTime();\n            wtx.nOrderPos = IncOrderPosNext();\n\n            wtx.nTimeSmart = wtx.nTimeReceived;\n            if (wtxIn.hashBlock != 0)\n            {\n                if (mapBlockIndex.count(wtxIn.hashBlock))\n                {\n                    unsigned int latestNow = wtx.nTimeReceived;\n                    unsigned int latestEntry = 0;\n                    {\n                        \/\/ Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future\n                        int64 latestTolerated = latestNow + 300;\n                        std::list<CAccountingEntry> acentries;\n                        TxItems txOrdered = OrderedTxItems(acentries);\n                        for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)\n                        {\n                            CWalletTx *const pwtx = (*it).second.first;\n                            if (pwtx == &wtx)\n                                continue;\n                            CAccountingEntry *const pacentry = (*it).second.second;\n                            int64 nSmartTime;\n                            if (pwtx)\n                            {\n                                nSmartTime = pwtx->nTimeSmart;\n                                if (!nSmartTime)\n                                    nSmartTime = pwtx->nTimeReceived;\n                            }\n                            else\n                                nSmartTime = pacentry->nTime;\n                            if (nSmartTime <= latestTolerated)\n                            {\n                                latestEntry = nSmartTime;\n                                if (nSmartTime > latestNow)\n                                    latestNow = nSmartTime;\n                                break;\n                            }\n                        }\n                    }\n\n                    unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;\n                    wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));\n                    \/\/ PoS: for old transactions, set the nTime to block time\n                    if (wtx.nTime == 0)\n                        wtx.nTime = blocktime;\n                }\n                else\n                    printf(\"AddToWallet() : found %s in block %s not in index\\n\",\n                           wtxIn.GetHash().ToString().c_str(),\n                           wtxIn.hashBlock.ToString().c_str());\n            }\n        }\n\n        bool fUpdated = false;\n        if (!fInsertedNew)\n        {\n            \/\/ Merge\n            if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)\n            {\n                wtx.hashBlock = wtxIn.hashBlock;\n                fUpdated = true;\n            }\n            if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))\n            {\n                wtx.vMerkleBranch = wtxIn.vMerkleBranch;\n                wtx.nIndex = wtxIn.nIndex;\n                fUpdated = true;\n            }\n            if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)\n            {\n                wtx.fFromMe = wtxIn.fFromMe;\n                fUpdated = true;\n            }\n            fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);\n        }\n\n        \/\/\/\/ debug print\n        printf(\"AddToWallet %s  %s%s\\n\", wtxIn.GetHash().ToString().c_str(), (fInsertedNew ? \"new\" : \"\"), (fUpdated ? \"update\" : \"\"));\n\n        \/\/ Write to disk\n        if (fInsertedNew || fUpdated)\n            if (!wtx.WriteToDisk())\n                return false;\n#ifndef QT_GUI\n        \/\/ If default receiving address gets used, replace it with a new one\n        if (vchDefaultKey.IsValid()) {\n            CScript scriptDefaultKey;\n            scriptDefaultKey.SetDestination(vchDefaultKey.GetID());\n            BOOST_FOREACH(const CTxOut& txout, wtx.vout)\n            {\n                if (txout.scriptPubKey == scriptDefaultKey)\n                {\n                    CPubKey newDefaultKey;\n                    if (GetKeyFromPool(newDefaultKey, false))\n                    {\n                        SetDefaultKey(newDefaultKey);\n                        SetAddressBookName(vchDefaultKey.GetID(), \"\");\n                    }\n                }\n            }\n        }\n#endif\n        \/\/ since AddToWallet is called directly for self-originating transactions, check for consumption of own coins\n        WalletUpdateSpent(wtx);\n\n        \/\/ Notify UI of new or updated transaction\n        NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);\n\n        \/\/ notify an external script when a wallet transaction comes in or is updated\n        std::string strCmd = GetArg(\"-walletnotify\", \"\");\n\n        if ( !strCmd.empty())\n        {\n            boost::replace_all(strCmd, \"%s\", wtxIn.GetHash().GetHex());\n            boost::thread t(runCommand, strCmd); \/\/ thread runs free\n        }\n\n        \/\/ notify an external script when a coinstake transaction is created\n        strCmd = GetArg(\"-stakenotify\", \"\");\n\n        if ( !strCmd.empty() && wtxIn.IsCoinStake())\n        {\n            boost::replace_all(strCmd, \"%s\", wtxIn.GetHash().GetHex());\n            boost::thread t(runCommand, strCmd); \/\/ thread runs free\n        }\n    }\n    return true;\n}\n\n\/\/ Add a transaction to the wallet, or update it.\n\/\/ pblock is optional, but should be provided if the transaction is known to be in a block.\n\/\/ If fUpdate is true, existing transactions will be updated.\nbool CWallet::AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)\n{\n    {\n        LOCK(cs_wallet);\n        bool fExisted = mapWallet.count(hash);\n        if (fExisted && !fUpdate) return false;\n        if (fExisted || IsMine(tx) || IsFromMe(tx))\n        {\n            CWalletTx wtx(this,tx);\n            \/\/ Get merkle branch if transaction was found in a block\n            if (pblock)\n                wtx.SetMerkleBranch(pblock);\n            return AddToWallet(wtx);\n        }\n        else\n            WalletUpdateSpent(tx);\n    }\n    return false;\n}\n\nbool CWallet::EraseFromWallet(uint256 hash)\n{\n    if (!fFileBacked)\n        return false;\n    {\n        LOCK(cs_wallet);\n        if (mapWallet.erase(hash))\n            CWalletDB(strWalletFile).EraseTx(hash);\n    }\n    return true;\n}\n\n\nbool CWallet::IsMine(const CTxIn &txin) const\n{\n    {\n        LOCK(cs_wallet);\n        map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);\n        if (mi != mapWallet.end())\n        {\n            const CWalletTx& prev = (*mi).second;\n            if (txin.prevout.n < prev.vout.size())\n                if (IsMine(prev.vout[txin.prevout.n]))\n                    return true;\n        }\n    }\n    return false;\n}\n\nint64 CWallet::GetDebit(const CTxIn &txin) const\n{\n    {\n        LOCK(cs_wallet);\n        map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);\n        if (mi != mapWallet.end())\n        {\n            const CWalletTx& prev = (*mi).second;\n            if (txin.prevout.n < prev.vout.size())\n                if (IsMine(prev.vout[txin.prevout.n]))\n                    return prev.vout[txin.prevout.n].nValue;\n        }\n    }\n    return 0;\n}\n\nbool CWallet::IsChange(const CTxOut& txout) const\n{\n    CTxDestination address;\n\n    \/\/ TODO: fix handling of 'change' outputs. The assumption is that any\n    \/\/ payment to a TX_PUBKEYHASH that is mine but isn't in the address book\n    \/\/ is change. That assumption is likely to break when we implement multisignature\n    \/\/ wallets that return change back into a multi-signature-protected address;\n    \/\/ a better way of identifying which outputs are 'the send' and which are\n    \/\/ 'the change' will need to be implemented (maybe extend CWalletTx to remember\n    \/\/ which output, if any, was change).\n    \n    if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))\n    {\n        LOCK(cs_wallet);\n        if (!mapAddressBook.count(address))\n            return true;\n    }\n    return false;\n}\n\nint64 CWalletTx::GetTxTime() const\n{\n    int64 n = nTimeSmart;\n    return n ? n : nTimeReceived;\n}\n\nint CWalletTx::GetRequestCount() const\n{\n    \/\/ Returns -1 if it wasn't being tracked\n    int nRequests = -1;\n    {\n        LOCK(pwallet->cs_wallet);\n        if (IsCoinBase() || IsCoinStake())\n        {\n            \/\/ Generated block\n            if (hashBlock != 0)\n            {\n                map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);\n                if (mi != pwallet->mapRequestCount.end())\n                    nRequests = (*mi).second;\n            }\n        }\n        else\n        {\n            \/\/ Did anyone request this transaction?\n            map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());\n            if (mi != pwallet->mapRequestCount.end())\n            {\n                nRequests = (*mi).second;\n\n                \/\/ How about the block it's in?\n                if (nRequests == 0 && hashBlock != 0)\n                {\n                    map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);\n                    if (mi != pwallet->mapRequestCount.end())\n                        nRequests = (*mi).second;\n                    else\n                        nRequests = 1; \/\/ If it's in someone else's block it must have got out\n                }\n            }\n        }\n    }\n    return nRequests;\n}\n\nvoid CWalletTx::GetAmounts(list<pair<CTxDestination, int64> >& listReceived,\n                           list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const\n{\n    nFee = 0;\n    listReceived.clear();\n    listSent.clear();\n    strSentAccount = strFromAccount;\n\n    \/\/ Compute fee:\n    int64 nDebit = GetDebit();\n    if (nDebit > 0) \/\/ debit>0 means we signed\/sent this transaction\n    {\n        int64 nValueOut = GetValueOut();\n        nFee = nDebit - nValueOut;\n    }\n\n    \/\/ Sent\/received.\n    BOOST_FOREACH(const CTxOut& txout, vout)\n    {\n        \/\/ ppcoin: Skip special stake out\n        if (txout.scriptPubKey.empty())\n            continue;\n\n        bool fIsMine;\n        \/\/ Only need to handle txouts if AT LEAST one of these is true:\n        \/\/   1) they debit from us (sent)\n        \/\/   2) the output is to us (received)\n        if (nDebit > 0)\n        {\n            \/\/ Don't report 'change' txouts\n            if (pwallet->IsChange(txout))\n                continue;\n            fIsMine = pwallet->IsMine(txout);\n        }\n        else if (!(fIsMine = pwallet->IsMine(txout)))\n            continue;\n\n        \/\/ In either case, we need to get the destination address\n        CTxDestination address;\n        if (!ExtractDestination(txout.scriptPubKey, address))\n        {\n            printf(\"CWalletTx::GetAmounts: Unknown transaction type found, txid %s\\n\",\n                   this->GetHash().ToString().c_str());\n            address = CNoDestination();\n        }\n\n        \/\/ If we are debited by the transaction, add the output as a \"sent\" entry\n        if (nDebit > 0)\n            listSent.push_back(make_pair(address, txout.nValue));\n\n        \/\/ If we are receiving the output, add it as a \"received\" entry\n        if (fIsMine)\n            listReceived.push_back(make_pair(address, txout.nValue));\n    }\n\n}\n\nvoid CWalletTx::GetAccountAmounts(const string& strAccount, int64& nReceived,\n                                  int64& nSent, int64& nFee) const\n{\n    nReceived = nSent = nFee = 0;\n\n    int64 allFee;\n    string strSentAccount;\n    list<pair<CTxDestination, int64> > listReceived;\n    list<pair<CTxDestination, int64> > listSent;\n    GetAmounts(listReceived, listSent, allFee, strSentAccount);\n\n    if (strAccount == strSentAccount)\n    {\n        BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)\n            nSent += s.second;\n        nFee = allFee;\n    }\n    {\n        LOCK(pwallet->cs_wallet);\n        BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)\n        {\n            if (pwallet->mapAddressBook.count(r.first))\n            {\n                map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);\n                if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)\n                    nReceived += r.second;\n            }\n            else if (strAccount.empty())\n            {\n                nReceived += r.second;\n            }\n        }\n    }\n}\n\nvoid CWalletTx::AddSupportingTransactions()\n{\n    vtxPrev.clear();\n\n    const int COPY_DEPTH = 3;\n    if (SetMerkleBranch() < COPY_DEPTH)\n    {\n        vector<uint256> vWorkQueue;\n        BOOST_FOREACH(const CTxIn& txin, vin)\n            vWorkQueue.push_back(txin.prevout.hash);\n\n        {\n            LOCK(pwallet->cs_wallet);\n            map<uint256, const CMerkleTx*> mapWalletPrev;\n            set<uint256> setAlreadyDone;\n            for (unsigned int i = 0; i < vWorkQueue.size(); i++)\n            {\n                uint256 hash = vWorkQueue[i];\n                if (setAlreadyDone.count(hash))\n                    continue;\n                setAlreadyDone.insert(hash);\n\n                CMerkleTx tx;\n                map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);\n                if (mi != pwallet->mapWallet.end())\n                {\n                    tx = (*mi).second;\n                    BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)\n                        mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;\n                }\n                else if (mapWalletPrev.count(hash))\n                {\n                    tx = *mapWalletPrev[hash];\n                }\n                else\n                {\n                    continue;\n                }\n\n                int nDepth = tx.SetMerkleBranch();\n                vtxPrev.push_back(tx);\n\n                if (nDepth < COPY_DEPTH)\n                {\n                    BOOST_FOREACH(const CTxIn& txin, tx.vin)\n                        vWorkQueue.push_back(txin.prevout.hash);\n                }\n            }\n        }\n    }\n\n    reverse(vtxPrev.begin(), vtxPrev.end());\n}\n\nbool CWalletTx::WriteToDisk()\n{\n    return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);\n}\n\n\/\/ Scan the block chain (starting in pindexStart) for transactions\n\/\/ from or to us. If fUpdate is true, found transactions that already\n\/\/ exist in the wallet will be updated.\nint CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)\n{\n    int ret = 0;\n\n    CBlockIndex* pindex = pindexStart;\n    {\n        LOCK(cs_wallet);\n        while (pindex)\n        {\n            CBlock block;\n            block.ReadFromDisk(pindex);\n            BOOST_FOREACH(CTransaction& tx, block.vtx)\n            {\n                if (AddToWalletIfInvolvingMe(tx.GetHash(), tx, &block, fUpdate))\n                    ret++;\n            }\n            pindex = pindex->pnext;\n        }\n    }\n    return ret;\n}\n\nvoid CWallet::ReacceptWalletTransactions()\n{\n    bool fRepeat = true;\n    while (fRepeat)\n    {\n        LOCK(cs_wallet);\n        fRepeat = false;\n        bool fMissing = false;\n        BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)\n        {\n            CWalletTx& wtx = item.second;\n            if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))\n                continue;\n\n            CCoins coins;\n            bool fUpdated = false;\n            bool fFound = pcoinsTip->GetCoins(wtx.GetHash(), coins);\n            if (fFound || wtx.GetDepthInMainChain() > 0)\n            {\n                \/\/ Update fSpent if a tx got spent somewhere else by a copy of wallet.dat\n                for (unsigned int i = 0; i < wtx.vout.size(); i++)\n                {\n                    if (wtx.IsSpent(i))\n                        continue;\n                    if ((i >= coins.vout.size() || coins.vout[i].IsNull()) && IsMine(wtx.vout[i]))\n                    {\n                        wtx.MarkSpent(i);\n                        fUpdated = true;\n                        fMissing = true;\n                    }\n                }\n                if (fUpdated)\n                {\n                    printf(\"ReacceptWalletTransactions found spent coin %s UNIFY %s\\n\", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());\n                    wtx.MarkDirty();\n                    wtx.WriteToDisk();\n                }\n            }\n            else\n            {\n                \/\/ Re-accept any txes of ours that aren't already in a block\n                if (!wtx.IsCoinBase() && !wtx.IsCoinStake())\n                    wtx.AcceptWalletTransaction(false);\n            }\n        }\n        if (fMissing)\n        {\n            \/\/ TODO: optimize this to scan just part of the block chain?\n            if (ScanForWalletTransactions(pindexGenesisBlock))\n                fRepeat = true;  \/\/ Found missing transactions: re-do re-accept.\n        }\n    }\n}\n\nvoid CWalletTx::RelayWalletTransaction()\n{\n    BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)\n    {\n        \/\/ Important: versions of bitcoin before 0.8.6 had a bug that inserted\n        \/\/ empty transactions into the vtxPrev, which will cause the node to be\n        \/\/ banned when retransmitted, hence the check for !tx.vin.empty()\n        if (!tx.IsCoinBase() && !tx.IsCoinStake() && !tx.vin.empty())\n            if (tx.GetDepthInMainChain() == 0)\n                RelayTransaction((CTransaction)tx, tx.GetHash());\n    }\n    if (!IsCoinBase() && !IsCoinStake())\n    {\n        if (GetDepthInMainChain() == 0) {\n            uint256 hash = GetHash();\n            printf(\"Relaying wtx %s\\n\", hash.ToString().c_str());\n            RelayTransaction((CTransaction)*this, hash);\n        }\n    }\n}\n\nvoid CWallet::ResendWalletTransactions()\n{\n    \/\/ Do this infrequently and randomly to avoid giving away\n    \/\/ that these are our transactions.\n    static int64 nNextTime;\n    if (GetTime() < nNextTime)\n        return;\n    bool fFirst = (nNextTime == 0);\n    nNextTime = GetTime() + GetRand(30 * 60);\n    if (fFirst)\n        return;\n\n    \/\/ Only do it if there's been a new block since last time\n    static int64 nLastTime;\n    if (nTimeBestReceived < nLastTime)\n        return;\n    nLastTime = GetTime();\n\n    \/\/ Rebroadcast any of our txes that aren't in a block yet\n    printf(\"ResendWalletTransactions()\\n\");\n    {\n        LOCK(cs_wallet);\n        \/\/ Sort them in chronological order\n        multimap<unsigned int, CWalletTx*> mapSorted;\n        BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)\n        {\n            CWalletTx& wtx = item.second;\n            \/\/ Don't rebroadcast until it's had plenty of time that\n            \/\/ it should have gotten in already by now.\n            if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)\n                mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));\n        }\n        BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)\n        {\n            CWalletTx& wtx = *item.second;\n            wtx.RelayWalletTransaction();\n        }\n    }\n}\n\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Actions\n\/\/\nconst std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const\n{\n    CTxDestination address;\n    if (ExtractDestination(scriptPubKey, address)) {\n        map<CTxDestination, string>::const_iterator mi = mapAddressBook.find(address);\n        if (mi != mapAddressBook.end()) {\n            return (*mi).second;\n        }\n    }\n    \/\/ A scriptPubKey that doesn't have an entry in the address book is\n    \/\/ associated with the default account (\"\").\n    const static std::string DEFAULT_ACCOUNT_NAME;\n    return DEFAULT_ACCOUNT_NAME;\n}\n\nint64 CWallet::GetLegacyBalance(int minDepth, const std::string* account) const\n{\n    int64 balance = 0;\n    LOCK(cs_wallet);\n    for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\n    {\n        const CWalletTx& wtx = (*it).second;\n        const int depth = wtx.GetDepthInMainChain();\n        if (depth < 0 || !wtx.IsConfirmed() || wtx.GetBlocksToMaturity() > 0) {\n            continue;\n        }\n\n        \/\/ Loop through tx outputs and add incoming payments. For outgoing txs,\n        \/\/ treat change outputs specially, as part of the amount debited.\n        int64 debit = wtx.GetDebit();\n\tcout << \">>>HOOK: fromAccount = \" << wtx.strFromAccount << endl;\n\tcout << wtx.ToString() << endl;\n        const bool outgoing = debit > 0;\n\tif(outgoing)\n\t{\n\t    const CTxIn& in = *(wtx.vin.begin());\n\t    cout << \">>>HOOK: fromAccount = \" << GetAccountName(in.scriptSig) << endl;\n\t}\n\tfor (vector<CTxOut>::const_iterator it = wtx.vout.begin(); it != wtx.vout.end(); ++it)\n\t{\n\t    const CTxOut& out = (*it);\n\t    CTxDestination address;\n\t    bool extract = ExtractDestination(out.scriptPubKey, address);\n\t    bool isMine = ::IsMine(*this, out.scriptPubKey);\n\t    string accountName = GetAccountName(out.scriptPubKey);\n\t    cout << \">>>HOOK: scriptPubKey = \" << out.scriptPubKey.ToString() << endl;\n\t    cout << \">>>HOOK: accountName = \" << accountName << endl;\n\t    cout << \">>>HOOK: isMine = \" << isMine<< endl;\n\t    cout << \">>>HOOK: outgoing = \" << outgoing << \", extract = \" << extract << endl;\n\t    cout << \">>> HOOK: out.nValue = \" << out.nValue << endl;\n            if (outgoing && IsChange(out)) {\n                debit -= out.nValue;\n\t\tcout << \">>> HOOK: debit = \" << debit << endl;\n            } else if (IsMine(out) && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {\n                balance += out.nValue;\n            } else {\n\t\tcout << \">>>HOOK: EngEng!!!\" << endl;\n\t    }\n        }\n\n        \/\/ For outgoing txs, subtract amount debited.\n        if (outgoing && (!account || *account == wtx.strFromAccount)) {\n            balance -= debit;\n        }\n\tcout << \">>>HOOK: balance = \" << balance << endl;\n    }\n\n    if (account) {\n        balance += CWalletDB(strWalletFile).GetAccountCreditDebit(*account);\n    }\n    cout << \">>>HOOK: legacy_balance = \" << balance << endl;\n    return balance;\n}\n\nint64 CWallet::GetBalance() const\n{\n    int64 nTotal = 0;\n    {\n        LOCK(cs_wallet);\n        for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\n        {\n            const CWalletTx* pcoin = &(*it).second;\n            if (pcoin->IsConfirmed())\n                nTotal += pcoin->GetAvailableCredit();\n        }\n    }\n\n    return nTotal;\n}\n\nint64 CWallet::GetUnconfirmedBalance() const\n{\n    int64 nTotal = 0;\n    {\n        LOCK(cs_wallet);\n        for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\n        {\n            const CWalletTx* pcoin = &(*it).second;\n            if (!pcoin->IsFinal() || !pcoin->IsConfirmed())\n                nTotal += pcoin->GetAvailableCredit();\n        }\n    }\n    return nTotal;\n}\n\nint64 CWallet::GetImmatureBalance() const\n{\n    int64 nTotal = 0;\n    {\n        LOCK(cs_wallet);\n        for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\n        {\n            const CWalletTx* pcoin = &(*it).second;\n            nTotal += pcoin->GetImmatureCredit();\n        }\n    }\n    return nTotal;\n}\n\n\/\/ populate vCoins with vector of spendable COutputs\nvoid CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const\n{\n    vCoins.clear();\n\n    {\n        LOCK(cs_wallet);\n        for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\n        {\n            const CWalletTx* pcoin = &(*it).second;\n\n            if (!pcoin->IsFinal())\n                continue;\n\n            if (fOnlyConfirmed && !pcoin->IsConfirmed())\n                continue;\n\n            if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)\n                continue;\n\n            int nDepth = pcoin->GetDepthInMainChain();\n            if (nDepth < 0)\n                continue;\n\n            for (unsigned int i = 0; i < pcoin->vout.size(); i++) {\n                if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) &&\n                    !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue >= nMinimumInputValue &&\n                    (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) \n                    vCoins.push_back(COutput(pcoin, i, nDepth));\n            }\n        }\n    }\n}\n\nvoid CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const\n{\n    vCoins.clear();\n\n    {\n        LOCK(cs_wallet);\n        for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\n        {\n            const CWalletTx* pcoin = &(*it).second;\n\n            if (!pcoin->IsFinal())\n                continue;\n\n            if(pcoin->GetDepthInMainChain() < nConf)\n                continue;\n\n            for (unsigned int i = 0; i < pcoin->vout.size(); i++)\n                if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) &&\n                    !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue >= nMinimumInputValue)\n                    vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));\n        }\n    }\n}\n\nstatic void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,\n                                  vector<char>& vfBest, int64& nBest, int iterations = 1000)\n{\n    vector<char> vfIncluded;\n\n    vfBest.assign(vValue.size(), true);\n    nBest = nTotalLower;\n\n    seed_insecure_rand();\n\n    for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)\n    {\n        vfIncluded.assign(vValue.size(), false);\n        int64 nTotal = 0;\n        bool fReachedTarget = false;\n        for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)\n        {\n            for (unsigned int i = 0; i < vValue.size(); i++)\n            {\n                \/\/The solver here uses a randomized algorithm,\n                \/\/the randomness serves no real security purpose but is just\n                \/\/needed to prevent degenerate behavior and it is important\n                \/\/that the rng fast. We do not use a constant random sequence,\n                \/\/because there may be some privacy improvement by making\n                \/\/the selection random.\n                if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])\n                {\n                    nTotal += vValue[i].first;\n                    vfIncluded[i] = true;\n                    if (nTotal >= nTargetValue)\n                    {\n                        fReachedTarget = true;\n                        if (nTotal < nBest)\n                        {\n                            nBest = nTotal;\n                            vfBest = vfIncluded;\n                        }\n                        nTotal -= vValue[i].first;\n                        vfIncluded[i] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n\n\/\/ ppcoin: total coins staked (non-spendable until maturity)\nint64 CWallet::GetStake() const\n{\n    int64 nTotal = 0;\n    LOCK(cs_wallet);\n    for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\n    {\n        const CWalletTx* pcoin = &(*it).second;\n        if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)\n            nTotal += CWallet::GetCredit(*pcoin);\n    }\n    return nTotal;\n}\n\nbool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,\n                                 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const\n{\n    setCoinsRet.clear();\n    nValueRet = 0;\n\n    \/\/ List of values less than target\n    pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;\n    coinLowestLarger.first = std::numeric_limits<int64>::max();\n    coinLowestLarger.second.first = NULL;\n    vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;\n    int64 nTotalLower = 0;\n\n    random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);\n\n    BOOST_FOREACH(COutput output, vCoins)\n    {\n        const CWalletTx *pcoin = output.tx;\n\n        if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))\n            continue;\n\n        int i = output.i;\n        int64 n = pcoin->vout[i].nValue;\n\n        pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));\n\n        if (n == nTargetValue)\n        {\n            setCoinsRet.insert(coin.second);\n            nValueRet += coin.first;\n            return true;\n        }\n        else if (n < nTargetValue + CENT)\n        {\n            vValue.push_back(coin);\n            nTotalLower += n;\n        }\n        else if (n < coinLowestLarger.first)\n        {\n            coinLowestLarger = coin;\n        }\n    }\n\n    if (nTotalLower == nTargetValue)\n    {\n        for (unsigned int i = 0; i < vValue.size(); ++i)\n        {\n            setCoinsRet.insert(vValue[i].second);\n            nValueRet += vValue[i].first;\n        }\n        return true;\n    }\n\n    if (nTotalLower < nTargetValue)\n    {\n        if (coinLowestLarger.second.first == NULL)\n            return false;\n        setCoinsRet.insert(coinLowestLarger.second);\n        nValueRet += coinLowestLarger.first;\n        return true;\n    }\n\n    \/\/ Solve subset sum by stochastic approximation\n    sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());\n    vector<char> vfBest;\n    int64 nBest;\n\n    ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);\n    if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)\n        ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);\n\n    \/\/ If we have a bigger coin and (either the stochastic approximation didn't find a good solution,\n    \/\/                                   or the next bigger coin is closer), return the bigger coin\n    if (coinLowestLarger.second.first &&\n        ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))\n    {\n        setCoinsRet.insert(coinLowestLarger.second);\n        nValueRet += coinLowestLarger.first;\n    }\n    else {\n        for (unsigned int i = 0; i < vValue.size(); i++)\n            if (vfBest[i])\n            {\n                setCoinsRet.insert(vValue[i].second);\n                nValueRet += vValue[i].first;\n            }\n\n        \/\/\/\/ debug print\n        printf(\"SelectCoins() best subset: \");\n        for (unsigned int i = 0; i < vValue.size(); i++)\n            if (vfBest[i])\n                printf(\"%s \", FormatMoney(vValue[i].first).c_str());\n        printf(\"total %s\\n\", FormatMoney(nBest).c_str());\n    }\n\n    return true;\n}\n\nbool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const\n{\n    vector<COutput> vCoins;\n    AvailableCoins(vCoins, true, coinControl);\n    \n    \/\/ coin control -> return all selected outputs (we want all selected to go into the transaction for sure)\n    if (coinControl && coinControl->HasSelected())\n    {\n        BOOST_FOREACH(const COutput& out, vCoins)\n        {\n            nValueRet += out.tx->vout[out.i].nValue;\n            setCoinsRet.insert(make_pair(out.tx, out.i));\n        }\n        return (nValueRet >= nTargetValue);\n    }\n\n    return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||\n            SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||\n            (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)));\n}\n\n\/\/ ppcoin: Select some coins without random shuffle or best subset approximation\nbool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const\n{\n    vector<COutput> vCoins;\n    AvailableCoinsMinConf(vCoins, nMinConf);\n\n    setCoinsRet.clear();\n    nValueRet = 0;\n\n    BOOST_FOREACH(COutput output, vCoins)\n    {\n        const CWalletTx *pcoin = output.tx;\n        int i = output.i;\n\n        \/\/ Stop if we've chosen enough inputs\n        if (nValueRet >= nTargetValue)\n            break;\n\n        int64 n = pcoin->vout[i].nValue;\n\n        pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));\n\n        if (n >= nTargetValue)\n        {\n            \/\/ If input value is greater or equal to target then simply insert\n            \/\/    it into the current subset and exit\n            setCoinsRet.insert(coin.second);\n            nValueRet += coin.first;\n            break;\n        }\n        else if (n < nTargetValue + CENT)\n        {\n            setCoinsRet.insert(coin.second);\n            nValueRet += coin.first;\n        }\n    }\n\n    return true;\n}\n\nbool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend,\n                                CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl)\n{\n    int64 nValue = 0;\n    BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)\n    {\n        if (nValue < 0)\n        {\n            strFailReason = _(\"Transaction amounts must be positive\");\n            return false;\n        }\n        nValue += s.second;\n    }\n    if (vecSend.empty() || nValue < 0)\n    {\n        strFailReason = _(\"Transaction amounts must be positive\");\n        return false;\n    }\n\n    \/\/ Transactions in PoW phase should have the old version.\n    if (pindexBest->nHeight < LAST_POW_BLOCK)\n        wtxNew.nVersion = POW_TX_VERSION;\n\n    wtxNew.BindWallet(this);\n\n    {\n        LOCK2(cs_main, cs_wallet);\n        {\n            nFeeRet = nTransactionFee;\n            loop\n            {\n                wtxNew.vin.clear();\n                wtxNew.vout.clear();\n                wtxNew.fFromMe = true;\n\n                int64 nTotalValue = nValue + nFeeRet;\n                double dPriority = 0;\n                \/\/ vouts to the payees\n                BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)\n                {\n                    CTxOut txout(s.second, s.first);\n                    if (txout.IsDust())\n                    {\n                        strFailReason = _(\"Transaction amount too small\");\n                        return false;\n                    }\n                    wtxNew.vout.push_back(txout);\n                }\n\n                \/\/ Choose coins to use\n                set<pair<const CWalletTx*,unsigned int> > setCoins;\n                int64 nValueIn = 0;\n                if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl))\n                {\n                    strFailReason = _(\"Insufficient funds\");\n                    return false;\n                }\n                BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)\n                {\n                    int64 nCredit = pcoin.first->vout[pcoin.second].nValue;\n                    \/\/The priority after the next block (depth+1) is used instead of the current,\n                    \/\/reflecting an assumption the user would accept a bit more delay for\n                    \/\/a chance at a free transaction.\n                    dPriority += (double)nCredit * (pcoin.first->GetDepthInMainChain()+1);\n                }\n\n                int64 nChange = nValueIn - nValue - nFeeRet;\n                \/\/ if sub-cent change is required, the fee must be raised to at least nMinTxFee\n                \/\/ or until nChange becomes zero\n                \/\/ NOTE: this depends on the exact behaviour of GetMinFee\n                if (nFeeRet < CTransaction::nMinTxFee && nChange > 0 && nChange < CENT)\n                {\n                    int64 nMoveToFee = min(nChange, CTransaction::nMinTxFee - nFeeRet);\n                    nChange -= nMoveToFee;\n                    nFeeRet += nMoveToFee;\n                }\n\n                if (nChange > 0)\n                {\n                    \/\/ Fill a vout to ourself\n                    \/\/ TODO: pass in scriptChange instead of reservekey so\n                    \/\/ change transaction isn't always pay-to-bitcoin-address\n                    CScript scriptChange;\n                    \n                    \/\/ coin control: send change to custom address\n                    if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))\n                        scriptChange.SetDestination(coinControl->destChange);\n                        \n                    \/\/ no coin control: send change to newly generated address\n                    else\n                    {\n                        \/\/ Note: We use a new key here to keep it from being obvious which side is the change.\n                        \/\/  The drawback is that by not reusing a previous key, the change may be lost if a\n                        \/\/  backup is restored, if the backup doesn't have the new private key for the change.\n                        \/\/  If we reused the old key, it would be possible to add code to look for and\n                        \/\/  rediscover unknown transactions that were written with keys of ours to recover\n                        \/\/  post-backup change.\n\n                        \/\/ Reserve a new key pair from key pool\n                        CPubKey vchPubKey;\n                        assert(reservekey.GetReservedKey(vchPubKey)); \/\/ should never fail, as we just unlocked\n\n                        scriptChange.SetDestination(vchPubKey.GetID());\n                    }\n\n                    CTxOut newTxOut(nChange, scriptChange);\n\n                    \/\/ Never create dust outputs; if we would, just\n                    \/\/ add the dust to the fee.\n                    if (newTxOut.IsDust())\n                    {\n                        nFeeRet += nChange;\n                        reservekey.ReturnKey();\n                    }\n                    else\n                    {\n                        \/\/ Insert change txn at random position:\n                        vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()+1);\n                        wtxNew.vout.insert(position, newTxOut);\n                    }\n                }\n                else\n                    reservekey.ReturnKey();\n\n                \/\/ Fill vin\n                BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)\n                    wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));\n\n                \/\/ Sign\n                int nIn = 0;\n                BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)\n                    if (!SignSignature(*this, *coin.first, wtxNew, nIn++))\n                    {\n                        strFailReason = _(\"Signing transaction failed\");\n                        return false;\n                    }\n\n                \/\/ Limit size\n                unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);\n                if (nBytes >= MAX_STANDARD_TX_SIZE)\n                {\n                    strFailReason = _(\"Transaction too large\");\n                    return false;\n                }\n                dPriority \/= nBytes;\n\n                \/\/ Check that enough fee is included\n                int64 nPayFee = nTransactionFee * (1 + (int64)nBytes \/ 1000);\n                bool fAllowFree = CTransaction::AllowFree(dPriority);\n                int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);\n                if (nFeeRet < max(nPayFee, nMinFee))\n                {\n                    nFeeRet = max(nPayFee, nMinFee);\n                    continue;\n                }\n\n                \/\/ Fill vtxPrev by copying from previous transactions vtxPrev\n                wtxNew.AddSupportingTransactions();\n                wtxNew.fTimeReceivedIsTxTime = true;\n\n                break;\n            }\n        }\n    }\n    return true;\n}\n\nbool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue,\n                                CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl)\n{\n    vector< pair<CScript, int64> > vecSend;\n    vecSend.push_back(make_pair(scriptPubKey, nValue));\n    return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl);\n}\n\nbool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nAverageWeight, uint64& nTotalWeight)\n{\n    \/\/ Choose coins to use\n    int64 nBalance = GetBalance();\n\n    if (nBalance <= nReserveBalance)\n        return false;\n\n    vector<const CWalletTx*> vwtxPrev;\n\n    set<pair<const CWalletTx*,unsigned int> > setCoins;\n    int64 nValueIn = 0;\n\n    if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), COINBASE_MATURITY + 20, setCoins, nValueIn))\n        return false;\n\n    if (setCoins.empty())\n        return false;\n\n    nAverageWeight = nTotalWeight = 0;\n    uint64 nWeightCount = 0;\n\n    BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)\n    {\n        CTransaction tx;\n        uint256 hashBlock = 0;\n        {\n            LOCK2(cs_main, cs_wallet);\n            if (!GetTransaction(pcoin.first->GetHash(), tx, hashBlock, true))\n                continue;\n            if (!mapBlockIndex.count(hashBlock))\n                continue;\n        }\n\n        \/\/ Deal with transaction timestmap\n        unsigned int nTimeTx = tx.nTime ? tx.nTime : mapBlockIndex[hashBlock]->nTime;\n\n        int64 nTimeWeight = GetCoinAgeWeight((int64)nTimeTx, (int64)GetTime());\n        CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight \/ COIN \/ (24 * 60 * 60);\n\n        \/\/ Weight is greater than zero\n        if (nTimeWeight > 0)\n        {\n            nTotalWeight += bnCoinDayWeight.getuint64();\n            nWeightCount++;\n        }\n    }\n\n    if (nWeightCount > 0)\n        nAverageWeight = nTotalWeight \/ nWeightCount;\n\n    return true;\n}\n\nbool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, int64 nFees, CTransaction& txNew, CKey& key)\n{\n    CBlockIndex* pindexPrev = pindexBest;\n    CBigNum bnTargetPerCoinDay;\n    bnTargetPerCoinDay.SetCompact(nBits);\n\n    txNew.vin.clear();\n    txNew.vout.clear();\n\n    \/\/ Mark coin stake transaction\n    CScript scriptEmpty;\n    scriptEmpty.clear();\n    txNew.vout.push_back(CTxOut(0, scriptEmpty));\n\n    \/\/ Choose coins to use\n    int64 nBalance = GetBalance();\n\n    if (nBalance <= nReserveBalance)\n        return false;\n\n    vector<const CWalletTx*> vwtxPrev;\n\n    set<pair<const CWalletTx*,unsigned int> > setCoins;\n    int64 nValueIn = 0;\n\n    \/\/ Select coins with suitable depth\n    if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, COINBASE_MATURITY + 20, setCoins, nValueIn))\n        return false;\n\n    if (setCoins.empty())\n        return false;\n\n    int64 nCredit = 0;\n    CScript scriptPubKeyKernel;\n    BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)\n    {\n        boost::this_thread::interruption_point();\n\n        CTransaction tx;\n        uint256 hashBlock = 0;\n        {\n            LOCK2(cs_main, cs_wallet);\n            if (!GetTransaction(pcoin.first->GetHash(), tx, hashBlock, true))\n                continue;\n        }\n\n        \/\/ Read block header\n        if (!mapBlockIndex.count(hashBlock))\n            continue;\n\n        CBlock block;\n        {\n            LOCK2(cs_main, cs_wallet);\n            if (!block.ReadFromDisk(mapBlockIndex[hashBlock]))\n                continue;\n        }\n\n        static int nMaxStakeSearchInterval = 60;\n        if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)\n            continue; \/\/ only count coins meeting min age requirement\n\n        bool fKernelFound = false;\n        for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && pindexPrev == pindexBest; n++)\n        {\n            \/\/ Search backward in time from the given txNew timestamp\n            \/\/ Search nSearchInterval seconds back up to nMaxStakeSearchInterval\n            uint256 hashProofOfStake = 0, targetProofOfStake = 0;\n            COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);\n            if (CheckStakeKernelHash(nBits, block, prevoutStake.n, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake, fDebug))\n            {\n                \/\/ Found a kernel\n                if (fDebug && GetBoolArg(\"-printcoinstake\"))\n                    printf(\"CreateCoinStake : kernel found\\n\");\n                vector<valtype> vSolutions;\n                txnouttype whichType;\n                CScript scriptPubKeyOut;\n                scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;\n                if (!Solver(scriptPubKeyKernel, whichType, vSolutions))\n                {\n                    if (fDebug && GetBoolArg(\"-printcoinstake\"))\n                        printf(\"CreateCoinStake : failed to parse kernel\\n\");\n                    break;\n                }\n                if (fDebug && GetBoolArg(\"-printcoinstake\"))\n                    printf(\"CreateCoinStake : parsed kernel type=%d\\n\", whichType);\n                if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)\n                {\n                    if (fDebug && GetBoolArg(\"-printcoinstake\"))\n                        printf(\"CreateCoinStake : no support for kernel type=%d\\n\", whichType);\n                    break;  \/\/ only support pay to public key and pay to address\n                }\n                if (whichType == TX_PUBKEYHASH) \/\/ pay to address type\n                {\n                    \/\/ convert to pay to public key type\n                    if (!keystore.GetKey(uint160(vSolutions[0]), key))\n                    {\n                        if (fDebug && GetBoolArg(\"-printcoinstake\"))\n                            printf(\"CreateCoinStake : failed to get key for kernel type=%d\\n\", whichType);\n                        break;  \/\/ unable to find corresponding public key\n                    }\n                    scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;\n                }\n                if (whichType == TX_PUBKEY)\n                {\n                    valtype& vchPubKey = vSolutions[0];\n                    if (!keystore.GetKey(Hash160(vchPubKey), key))\n                    {\n                        if (fDebug && GetBoolArg(\"-printcoinstake\"))\n                            printf(\"CreateCoinStake : failed to get key for kernel type=%d\\n\", whichType);\n                        break;  \/\/ unable to find corresponding public key\n                    }\n                    if (key.GetPubKey() != vchPubKey)\n                    {\n                        if (fDebug && GetBoolArg(\"-printcoinstake\"))\n                            printf(\"CreateCoinStake : invalid key for kernel type=%d\\n\", whichType);\n                        break; \/\/ keys mismatch\n                    }\n                    scriptPubKeyOut = scriptPubKeyKernel;\n                }\n\n                txNew.nTime -= n;\n                txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));\n                nCredit += pcoin.first->vout[pcoin.second].nValue;\n                vwtxPrev.push_back(pcoin.first);\n                txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));\n\n                if (GetCoinAgeWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeSplitAge && nCredit >= nStakeCombineThreshold)\n                    txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); \/\/split stake\n                if (fDebug && GetBoolArg(\"-printcoinstake\"))\n                    printf(\"CreateCoinStake : added kernel type=%d\\n\", whichType);\n                fKernelFound = true;\n                break;\n            }\n        }\n\n        if (fKernelFound)\n            break; \/\/ if kernel is found stop searching\n    }\n\n    if (nCredit == 0 || nCredit > nBalance - nReserveBalance)\n        return false;\n\n    BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)\n    {\n        \/\/ Attempt to add more inputs\n        \/\/ Only add coins of the same key\/address as kernel\n        if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))\n            && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)\n        {\n            \/\/ Stop adding more inputs if already too many inputs\n            if (txNew.vin.size() >= 100)\n                break;\n            \/\/ Stop adding more inputs if value is already pretty significant\n            if (nCredit >= nStakeCombineThreshold)\n                break;\n            \/\/ Stop adding inputs if reached reserve limit\n            if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)\n                break;\n            \/\/ Do not add additional significant input\n            if (pcoin.first->vout[pcoin.second].nValue >= nStakeCombineThreshold)\n                continue;\n\n            CTransaction tx;\n            uint256 hashBlock = 0;\n            {\n                LOCK2(cs_main, cs_wallet);\n                if (!GetTransaction(pcoin.first->GetHash(), tx, hashBlock, true))\n                    continue;\n                if (!mapBlockIndex.count(hashBlock))\n                    continue;\n            }\n\n            \/\/ Deal with transaction timestmap\n            unsigned int nTimeTx = tx.nTime ? tx.nTime : mapBlockIndex[hashBlock]->nTime;\n\n            \/\/ Do not add input that is still too young\n            if (!GetCoinAgeWeight((int64)nTimeTx, (int64)txNew.nTime))\n                continue;\n\n            txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));\n            nCredit += pcoin.first->vout[pcoin.second].nValue;\n            vwtxPrev.push_back(pcoin.first);\n        }\n    }\n\n    \/\/ Calculate coin age reward\n    {\n        uint64 nCoinAge;\n        if (!txNew.GetCoinAge(nCoinAge))\n            return error(\"CreateCoinStake : failed to calculate coin age\");\n\n        int64 nReward = GetProofOfStakeReward(nCoinAge, nFees);\n        if (nReward <= 0)\n            return false;\n\n        nCredit += nReward;\n    }\n\n    \/\/ Set output amount\n    if (txNew.vout.size() == 3)\n    {\n        txNew.vout[1].nValue = (nCredit \/ 2 \/ CENT) * CENT;\n        txNew.vout[2].nValue = nCredit - txNew.vout[1].nValue;\n    }\n    else\n        txNew.vout[1].nValue = nCredit;\n\n    \/\/ Sign\n    int nIn = 0;\n    BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)\n    {\n        if (!SignSignature(*this, *pcoin, txNew, nIn++))\n            return error(\"CreateCoinStake : failed to sign coinstake\");\n    }\n\n    \/\/ Limit size\n    unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);\n    if (nBytes >= MAX_BLOCK_SIZE_GEN\/5)\n        return error(\"CreateCoinStake : exceeded coinstake size limit\");\n\n    \/\/ Successfully generated coinstake\n    return true;\n}\n\n\n\/\/ Call after CreateTransaction unless you want to abort\nbool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)\n{\n    {\n        LOCK2(cs_main, cs_wallet);\n        printf(\"CommitTransaction:\\n%s\", wtxNew.ToString().c_str());\n        {\n            \/\/ This is only to keep the database open to defeat the auto-flush for the\n            \/\/ duration of this scope.  This is the only place where this optimization\n            \/\/ maybe makes sense; please don't do it anywhere else.\n            CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,\"r\") : NULL;\n\n            \/\/ Take key pair from key pool so it won't be used again\n            reservekey.KeepKey();\n\n            \/\/ Add tx to wallet, because if it has change it's also ours,\n            \/\/ otherwise just for transaction history.\n            AddToWallet(wtxNew);\n\n            \/\/ Mark old coins as spent\n            set<CWalletTx*> setCoins;\n            BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)\n            {\n                CWalletTx &coin = mapWallet[txin.prevout.hash];\n                coin.BindWallet(this);\n                coin.MarkSpent(txin.prevout.n);\n                coin.WriteToDisk();\n                NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);\n            }\n\n            if (fFileBacked)\n                delete pwalletdb;\n        }\n\n        \/\/ Track how many getdata requests our transaction gets\n        mapRequestCount[wtxNew.GetHash()] = 0;\n\n        \/\/ Broadcast\n        if (!wtxNew.AcceptToMemoryPool(true, false))\n        {\n            \/\/ This must not fail. The transaction has already been signed and recorded.\n            printf(\"CommitTransaction() : Error: Transaction not valid\");\n            return false;\n        }\n        wtxNew.RelayWalletTransaction();\n    }\n    return true;\n}\n\n\n\n\nstring CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)\n{\n    CReserveKey reservekey(this);\n    int64 nFeeRequired;\n\n    string strError;\n    if (IsLocked())\n    {\n        strError = _(\"Error: Wallet locked, unable to create transaction!\");\n        printf(\"SendMoney() : %s\", strError.c_str());\n        return strError;\n    }\n    if (fWalletUnlockStakingOnly)\n    {\n        strError = _(\"Error: Wallet unlocked for staking only, unable to create transaction.\");\n        printf(\"SendMoney() : %s\", strError.c_str());\n        return strError;\n    }\n    if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strError))\n    {\n        if (nValue + nFeeRequired > GetBalance())\n            strError = strprintf(_(\"Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!\"), FormatMoney(nFeeRequired).c_str());\n        printf(\"SendMoney() : %s\\n\", strError.c_str());\n        return strError;\n    }\n\n    if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired))\n        return \"ABORTED\";\n\n    if (!CommitTransaction(wtxNew, reservekey))\n        return _(\"Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.\");\n\n    return \"\";\n}\n\n\n\nstring CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)\n{\n    \/\/ Check amount\n    if (nValue <= 0)\n        return _(\"Invalid amount\");\n    if (nValue + nTransactionFee > GetBalance())\n        return _(\"Insufficient funds\");\n\n    \/\/ Parse Bitcoin address\n    CScript scriptPubKey;\n    scriptPubKey.SetDestination(address);\n\n    return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);\n}\n\nDBErrors CWallet::LoadWallet(bool& fFirstRunRet)\n{\n    if (!fFileBacked)\n        return DB_LOAD_OK;\n    fFirstRunRet = false;\n    DBErrors nLoadWalletRet = CWalletDB(strWalletFile,\"cr+\").LoadWallet(this);\n    if (nLoadWalletRet == DB_NEED_REWRITE)\n    {\n        if (CDB::Rewrite(strWalletFile, \"\\x04pool\"))\n        {\n            setKeyPool.clear();\n            \/\/ Note: can't top-up keypool here, because wallet is locked.\n            \/\/ User will be prompted to unlock wallet the next operation\n            \/\/ the requires a new key.\n        }\n    }\n\n    if (nLoadWalletRet != DB_LOAD_OK)\n        return nLoadWalletRet;\n    fFirstRunRet = !vchDefaultKey.IsValid();\n    return DB_LOAD_OK;\n}\n\n\nbool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)\n{\n    std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);\n    mapAddressBook[address] = strName;\n    NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);\n    if (!fFileBacked)\n        return false;\n    return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);\n}\n\nbool CWallet::DelAddressBookName(const CTxDestination& address)\n{\n    mapAddressBook.erase(address);\n    NotifyAddressBookChanged(this, address, \"\", ::IsMine(*this, address), CT_DELETED);\n    if (!fFileBacked)\n        return false;\n    return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());\n}\n\n\nvoid CWallet::PrintWallet(const CBlock& block)\n{\n    {\n        LOCK(cs_wallet);\n        if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))\n        {\n            CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];\n            printf(\"    mine:  %d  %d  %\"PRI64d\"\", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());\n        }\n        else if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))\n        {\n            CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];\n            printf(\"    stake: %d  %d  %\"PRI64d\"\", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());\n        }\n    }\n    printf(\"\\n\");\n}\n\nbool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)\n{\n    {\n        LOCK(cs_wallet);\n        map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);\n        if (mi != mapWallet.end())\n        {\n            wtx = (*mi).second;\n            return true;\n        }\n    }\n    return false;\n}\n\n\/\/ a blatant copy of the same function in main.cpp\nbool CWallet::GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)\n{\n    CBlockIndex *pindexSlow = NULL;\n    {\n        LOCK(cs_main);\n        {\n            LOCK(mempool.cs);\n            if (mempool.exists(hash))\n            {\n                txOut = mempool.lookup(hash);\n                return true;\n            }\n        }\n\n        if (fTxIndex) {\n            CDiskTxPos postx;\n            if (pblocktree->ReadTxIndex(hash, postx)) {\n                CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);\n                CBlockHeader header;\n                try {\n                    file >> header;\n                    fseek(file, postx.nTxOffset, SEEK_CUR);\n                    file >> txOut;\n                } catch (std::exception &e) {\n                    return error(\"%s() : deserialize or I\/O error\", __PRETTY_FUNCTION__);\n                }\n                hashBlock = header.GetHash();\n                if (txOut.GetHash() != hash)\n                    return error(\"%s() : txid mismatch\", __PRETTY_FUNCTION__);\n                return true;\n            }\n        }\n\n        if (fAllowSlow) { \/\/ use coin database to locate block that contains transaction, and scan it\n            int nHeight = -1;\n            {\n                CCoinsViewCache &view = *pcoinsTip;\n                CCoins coins;\n                if (view.GetCoins(hash, coins))\n                    nHeight = coins.nHeight;\n            }\n            if (nHeight > 0)\n                pindexSlow = FindBlockByHeight(nHeight);\n        }\n    }\n\n    if (pindexSlow) {\n        CBlock block;\n        if (block.ReadFromDisk(pindexSlow)) {\n            BOOST_FOREACH(const CTransaction &tx, block.vtx) {\n                if (tx.GetHash() == hash) {\n                    txOut = tx;\n                    hashBlock = pindexSlow->GetBlockHash();\n                    return true;\n                }\n            }\n        }\n    }\n\n    return false;\n}\n\nbool CWallet::SetDefaultKey(const CPubKey &vchPubKey)\n{\n    if (fFileBacked)\n    {\n        if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))\n            return false;\n    }\n    vchDefaultKey = vchPubKey;\n    return true;\n}\n\nbool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)\n{\n    if (!pwallet->fFileBacked)\n        return false;\n    strWalletFileOut = pwallet->strWalletFile;\n    return true;\n}\n\n\/\/\n\/\/ Mark old keypool keys as used,\n\/\/ and generate all new keys\n\/\/\nbool CWallet::NewKeyPool()\n{\n    {\n        LOCK(cs_wallet);\n        CWalletDB walletdb(strWalletFile);\n        BOOST_FOREACH(int64 nIndex, setKeyPool)\n            walletdb.ErasePool(nIndex);\n        setKeyPool.clear();\n\n        if (IsLocked())\n            return false;\n\n        int64 nKeys = max(GetArg(\"-keypool\", 100), (int64)0);\n        for (int i = 0; i < nKeys; i++)\n        {\n            int64 nIndex = i+1;\n            walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));\n            setKeyPool.insert(nIndex);\n        }\n        printf(\"CWallet::NewKeyPool wrote %\"PRI64d\" new keys\\n\", nKeys);\n    }\n    return true;\n}\n\nbool CWallet::TopUpKeyPool()\n{\n    {\n        LOCK(cs_wallet);\n\n        if (IsLocked())\n            return false;\n\n        CWalletDB walletdb(strWalletFile);\n\n        \/\/ Top up key pool\n        unsigned int nTargetSize = max(GetArg(\"-keypool\", 100), 0LL);\n        while (setKeyPool.size() < (nTargetSize + 1))\n        {\n            int64 nEnd = 1;\n            if (!setKeyPool.empty())\n                nEnd = *(--setKeyPool.end()) + 1;\n            if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))\n                throw runtime_error(\"TopUpKeyPool() : writing generated key failed\");\n            setKeyPool.insert(nEnd);\n            printf(\"keypool added key %\"PRI64d\", size=%\"PRIszu\"\\n\", nEnd, setKeyPool.size());\n        }\n    }\n    return true;\n}\n\nvoid CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)\n{\n    nIndex = -1;\n    keypool.vchPubKey = CPubKey();\n    {\n        LOCK(cs_wallet);\n\n        if (!IsLocked())\n            TopUpKeyPool();\n\n        \/\/ Get the oldest key\n        if(setKeyPool.empty())\n            return;\n\n        CWalletDB walletdb(strWalletFile);\n\n        nIndex = *(setKeyPool.begin());\n        setKeyPool.erase(setKeyPool.begin());\n        if (!walletdb.ReadPool(nIndex, keypool))\n            throw runtime_error(\"ReserveKeyFromKeyPool() : read failed\");\n        if (!HaveKey(keypool.vchPubKey.GetID()))\n            throw runtime_error(\"ReserveKeyFromKeyPool() : unknown key in key pool\");\n        assert(keypool.vchPubKey.IsValid());\n        printf(\"keypool reserve %\"PRI64d\"\\n\", nIndex);\n    }\n}\n\nint64 CWallet::AddReserveKey(const CKeyPool& keypool)\n{\n    {\n        LOCK2(cs_main, cs_wallet);\n        CWalletDB walletdb(strWalletFile);\n\n        int64 nIndex = 1 + *(--setKeyPool.end());\n        if (!walletdb.WritePool(nIndex, keypool))\n            throw runtime_error(\"AddReserveKey() : writing added key failed\");\n        setKeyPool.insert(nIndex);\n        return nIndex;\n    }\n    return -1;\n}\n\nvoid CWallet::KeepKey(int64 nIndex)\n{\n    \/\/ Remove from key pool\n    if (fFileBacked)\n    {\n        CWalletDB walletdb(strWalletFile);\n        walletdb.ErasePool(nIndex);\n    }\n    printf(\"keypool keep %\"PRI64d\"\\n\", nIndex);\n}\n\nvoid CWallet::ReturnKey(int64 nIndex)\n{\n    \/\/ Return to key pool\n    {\n        LOCK(cs_wallet);\n        setKeyPool.insert(nIndex);\n    }\n    printf(\"keypool return %\"PRI64d\"\\n\", nIndex);\n}\n\nbool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)\n{\n    int64 nIndex = 0;\n    CKeyPool keypool;\n    {\n        LOCK(cs_wallet);\n        ReserveKeyFromKeyPool(nIndex, keypool);\n        if (nIndex == -1)\n        {\n            if (fAllowReuse && vchDefaultKey.IsValid())\n            {\n                result = vchDefaultKey;\n                return true;\n            }\n            if (IsLocked()) return false;\n            result = GenerateNewKey();\n            return true;\n        }\n        KeepKey(nIndex);\n        result = keypool.vchPubKey;\n    }\n    return true;\n}\n\nint64 CWallet::GetOldestKeyPoolTime()\n{\n    int64 nIndex = 0;\n    CKeyPool keypool;\n    ReserveKeyFromKeyPool(nIndex, keypool);\n    if (nIndex == -1)\n        return GetTime();\n    ReturnKey(nIndex);\n    return keypool.nTime;\n}\n\nstd::map<CTxDestination, int64> CWallet::GetAddressBalances()\n{\n    map<CTxDestination, int64> balances;\n\n    {\n        LOCK(cs_wallet);\n        BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)\n        {\n            CWalletTx *pcoin = &walletEntry.second;\n\n            if (!pcoin->IsFinal() || !pcoin->IsConfirmed())\n                continue;\n\n            if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)\n                continue;\n\n            int nDepth = pcoin->GetDepthInMainChain();\n            if (nDepth < (pcoin->IsFromMe() ? 0 : 1))\n                continue;\n\n            for (unsigned int i = 0; i < pcoin->vout.size(); i++)\n            {\n                CTxDestination addr;\n                if (!IsMine(pcoin->vout[i]))\n                    continue;\n                if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))\n                    continue;\n\n                int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;\n\n                if (!balances.count(addr))\n                    balances[addr] = 0;\n                balances[addr] += n;\n            }\n        }\n    }\n\n    return balances;\n}\n\nset< set<CTxDestination> > CWallet::GetAddressGroupings()\n{\n    set< set<CTxDestination> > groupings;\n    set<CTxDestination> grouping;\n\n    BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)\n    {\n        CWalletTx *pcoin = &walletEntry.second;\n\n        if (pcoin->vin.size() > 0)\n        {\n            bool any_mine = false;\n            \/\/ group all input addresses with each other\n            BOOST_FOREACH(CTxIn txin, pcoin->vin)\n            {\n                CTxDestination address;\n                if(!IsMine(txin)) \/* If this input isn't mine, ignore it *\/\n                    continue;\n                if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))\n                    continue;\n                grouping.insert(address);\n                any_mine = true;\n            }\n\n            \/\/ group change with input addresses\n            if (any_mine)\n            {\n               BOOST_FOREACH(CTxOut txout, pcoin->vout)\n                   if (IsChange(txout))\n                   {\n                       CTxDestination txoutAddr;\n                       if(!ExtractDestination(txout.scriptPubKey, txoutAddr))\n                           continue;\n                       grouping.insert(txoutAddr);\n                   }\n            }\n            if (grouping.size() > 0)\n            {\n                groupings.insert(grouping);\n                grouping.clear();\n            }\n        }\n\n        \/\/ group lone addrs by themselves\n        for (unsigned int i = 0; i < pcoin->vout.size(); i++)\n            if (IsMine(pcoin->vout[i]))\n            {\n                CTxDestination address;\n                if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))\n                    continue;\n                grouping.insert(address);\n                groupings.insert(grouping);\n                grouping.clear();\n            }\n    }\n\n    set< set<CTxDestination>* > uniqueGroupings; \/\/ a set of pointers to groups of addresses\n    map< CTxDestination, set<CTxDestination>* > setmap;  \/\/ map addresses to the unique group containing it\n    BOOST_FOREACH(set<CTxDestination> grouping, groupings)\n    {\n        \/\/ make a set of all the groups hit by this new group\n        set< set<CTxDestination>* > hits;\n        map< CTxDestination, set<CTxDestination>* >::iterator it;\n        BOOST_FOREACH(CTxDestination address, grouping)\n            if ((it = setmap.find(address)) != setmap.end())\n                hits.insert((*it).second);\n\n        \/\/ merge all hit groups into a new single group and delete old groups\n        set<CTxDestination>* merged = new set<CTxDestination>(grouping);\n        BOOST_FOREACH(set<CTxDestination>* hit, hits)\n        {\n            merged->insert(hit->begin(), hit->end());\n            uniqueGroupings.erase(hit);\n            delete hit;\n        }\n        uniqueGroupings.insert(merged);\n\n        \/\/ update setmap\n        BOOST_FOREACH(CTxDestination element, *merged)\n            setmap[element] = merged;\n    }\n\n    set< set<CTxDestination> > ret;\n    BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)\n    {\n        ret.insert(*uniqueGrouping);\n        delete uniqueGrouping;\n    }\n\n    return ret;\n}\n\n\/\/ ppcoin: disable transaction (only for coinstake)\nvoid CWallet::DisableTransaction(const CTransaction &tx)\n{\n    if (!tx.IsCoinStake() || !IsFromMe(tx))\n        return; \/\/ only disconnecting coinstake requires marking input unspent\n\n    LOCK(cs_wallet);\n    BOOST_FOREACH(const CTxIn& txin, tx.vin)\n    {\n        map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);\n        if (mi != mapWallet.end())\n        {\n            CWalletTx& prev = (*mi).second;\n            if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))\n            {\n                prev.MarkUnspent(txin.prevout.n);\n                prev.WriteToDisk();\n            }\n        }\n    }\n}\n\nbool CReserveKey::GetReservedKey(CPubKey& pubkey)\n{\n    if (nIndex == -1)\n    {\n        CKeyPool keypool;\n        pwallet->ReserveKeyFromKeyPool(nIndex, keypool);\n        if (nIndex != -1)\n            vchPubKey = keypool.vchPubKey;\n        else {\n            if (pwallet->vchDefaultKey.IsValid()) {\n                printf(\"CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!\");\n                vchPubKey = pwallet->vchDefaultKey;\n            } else\n                return false;\n        }\n    }\n    assert(vchPubKey.IsValid());\n    pubkey = vchPubKey;\n    return true;\n}\n\nvoid CReserveKey::KeepKey()\n{\n    if (nIndex != -1)\n        pwallet->KeepKey(nIndex);\n    nIndex = -1;\n    vchPubKey = CPubKey();\n}\n\nvoid CReserveKey::ReturnKey()\n{\n    if (nIndex != -1)\n        pwallet->ReturnKey(nIndex);\n    nIndex = -1;\n    vchPubKey = CPubKey();\n}\n\nvoid CWallet::GetAllReserveKeys(set<CKeyID>& setAddress)\n{\n    setAddress.clear();\n\n    CWalletDB walletdb(strWalletFile);\n\n    LOCK2(cs_main, cs_wallet);\n    BOOST_FOREACH(const int64& id, setKeyPool)\n    {\n        CKeyPool keypool;\n        if (!walletdb.ReadPool(id, keypool))\n            throw runtime_error(\"GetAllReserveKeyHashes() : read failed\");\n        assert(keypool.vchPubKey.IsValid());\n        CKeyID keyID = keypool.vchPubKey.GetID();\n        if (!HaveKey(keyID))\n            throw runtime_error(\"GetAllReserveKeyHashes() : unknown key in key pool\");\n        setAddress.insert(keyID);\n    }\n}\n\nvoid CWallet::UpdatedTransaction(const uint256 &hashTx, bool fDeleted)\n{\n    {\n        LOCK(cs_wallet);\n        \/\/ Only notify UI if this transaction is in this wallet\n        map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);\n        if (mi != mapWallet.end())\n            NotifyTransactionChanged(this, hashTx, CT_UPDATED);\n        else if (fDeleted)\n            NotifyTransactionChanged(this, hashTx, CT_DELETED);\n    }\n}\n\nvoid CWallet::LockCoin(COutPoint& output)\n{\n    setLockedCoins.insert(output);\n}\n\nvoid CWallet::UnlockCoin(COutPoint& output)\n{\n    setLockedCoins.erase(output);\n}\n\nvoid CWallet::UnlockAllCoins()\n{\n    setLockedCoins.clear();\n}\n\nbool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const\n{\n    COutPoint outpt(hash, n);\n\n    return (setLockedCoins.count(outpt) > 0);\n}\n\nvoid CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)\n{\n    for (std::set<COutPoint>::iterator it = setLockedCoins.begin();\n         it != setLockedCoins.end(); it++) {\n        COutPoint outpt = (*it);\n        vOutpts.push_back(outpt);\n    }\n}\n\n\/**\n * ihook98 2018-02-08\n*\/\n\/\/ populate vCoins with vector of spendable COutputs by address\nvoid CWallet::AvailableCoinsByAddress(const CTxDestination &fromAddress, vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const\n{\n    vCoins.clear();\n\n    {\n        LOCK(cs_wallet);\n        for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\n        {\n            const CWalletTx* pcoin = &(*it).second;\n\n            if (!pcoin->IsFinal())\n                continue;\n\n            if (fOnlyConfirmed && !pcoin->IsConfirmed())\n                continue;\n\n            if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)\n                continue;\n\n            int nDepth = pcoin->GetDepthInMainChain();\n            if (nDepth < 0)\n                continue;\n\n            for (unsigned int i = 0; i < pcoin->vout.size(); i++) {\n                CTxDestination addr;\n                if(ExtractDestination(pcoin->vout[i].scriptPubKey, addr))\n                {\n                    if(addr == fromAddress)\n                    {\n                        if (!(pcoin->IsSpent(i)) && \n                            IsMine(pcoin->vout[i]) &&\n                            !IsLockedCoin((*it).first, i) && \n                            pcoin->vout[i].nValue >= nMinimumInputValue &&\n                            (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) \n                            vCoins.push_back(COutput(pcoin, i, nDepth));\n                    }\n                }\n            }\n        }\n    }\n}\n\nbool CWallet::SelectCoinsFromAddress(const CTxDestination &fromAddress, int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const\n{\n    vector<COutput> vCoins;\n    AvailableCoinsByAddress(fromAddress, vCoins, true, coinControl);\n    \n    \/\/ coin control -> return all selected outputs (we want all selected to go into the transaction for sure)\n    if (coinControl && coinControl->HasSelected())\n    {\n        BOOST_FOREACH(const COutput& out, vCoins)\n        {\n            nValueRet += out.tx->vout[out.i].nValue;\n            setCoinsRet.insert(make_pair(out.tx, out.i));\n        }\n        return (nValueRet >= nTargetValue);\n    }\n\n    return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||\n            SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||\n            (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)));\n}\n\nbool CWallet::CreateTransaction(const CTxDestination &fromAddress, CScript scriptPubKey, int64 nValue2,\n                                CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl)\n{\n    vector< pair<CScript, int64> > vecSend;\n    vecSend.push_back(make_pair(scriptPubKey, nValue2));\n    int64 nValue = 0;\n    BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)\n    {\n        if (nValue < 0)\n        {\n            strFailReason = _(\"Transaction amounts must be positive\");\n            return false;\n        }\n        nValue += s.second;\n    }\n    if (vecSend.empty() || nValue < 0)\n    {\n        strFailReason = _(\"Transaction amounts must be positive\");\n        return false;\n    }\n\n    \/\/ Transactions in PoW phase should have the old version.\n    if (pindexBest->nHeight < LAST_POW_BLOCK)\n        wtxNew.nVersion = POW_TX_VERSION;\n\n    wtxNew.BindWallet(this);\n\n    {\n        LOCK2(cs_main, cs_wallet);\n        {\n            nFeeRet = nTransactionFee;\n            loop\n            {\n                wtxNew.vin.clear();\n                wtxNew.vout.clear();\n                wtxNew.fFromMe = true;\n\n                int64 nTotalValue = nValue + nFeeRet;\n                double dPriority = 0;\n                \/\/ vouts to the payees\n                BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)\n                {\n                    CTxOut txout(s.second, s.first);\n                    if (txout.IsDust())\n                    {\n                        strFailReason = _(\"Transaction amount too small\");\n                        return false;\n                    }\n                    wtxNew.vout.push_back(txout);\n                }\n\n                \/\/ Choose coins to use\n                set<pair<const CWalletTx*,unsigned int> > setCoins;\n                int64 nValueIn = 0;\n                if (!SelectCoinsFromAddress(fromAddress, nTotalValue, setCoins, nValueIn, coinControl))\n                {\n                    strFailReason = _(\"Insufficient funds\");\n                    return false;\n                }\n                BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)\n                {\n                    int64 nCredit = pcoin.first->vout[pcoin.second].nValue;\n                    \/\/The priority after the next block (depth+1) is used instead of the current,\n                    \/\/reflecting an assumption the user would accept a bit more delay for\n                    \/\/a chance at a free transaction.\n                    dPriority += (double)nCredit * (pcoin.first->GetDepthInMainChain()+1);\n                }\n\n                int64 nChange = nValueIn - nValue - nFeeRet;\n                \/\/ if sub-cent change is required, the fee must be raised to at least nMinTxFee\n                \/\/ or until nChange becomes zero\n                \/\/ NOTE: this depends on the exact behaviour of GetMinFee\n                if (nFeeRet < CTransaction::nMinTxFee && nChange > 0 && nChange < CENT)\n                {\n                    int64 nMoveToFee = min(nChange, CTransaction::nMinTxFee - nFeeRet);\n                    nChange -= nMoveToFee;\n                    nFeeRet += nMoveToFee;\n                }\n\n                if (nChange > 0)\n                {\n                    \/\/ Fill a vout to ourself\n                    \/\/ TODO: pass in scriptChange instead of reservekey so\n                    \/\/ change transaction isn't always pay-to-bitcoin-address\n                    CScript scriptChange;\n                    \n                    scriptChange.SetDestination(fromAddress);\n                    CTxOut newTxOut(nChange, scriptChange);\n\n                    \/\/ Never create dust outputs; if we would, just\n                    \/\/ add the dust to the fee.\n                    if (newTxOut.IsDust())\n                    {\n                        nFeeRet += nChange;\n                        reservekey.ReturnKey();\n                    }\n                    else\n                    {\n                        \/\/ Insert change txn at random position:\n                        vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()+1);\n                        wtxNew.vout.insert(position, newTxOut);\n                    }\n                }\n                else\n                    reservekey.ReturnKey();\n\n                \/\/ Fill vin\n                BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)\n                    wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));\n\n                \/\/ Sign\n                int nIn = 0;\n                BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)\n                    if (!SignSignature(*this, *coin.first, wtxNew, nIn++))\n                    {\n                        strFailReason = _(\"Signing transaction failed\");\n                        return false;\n                    }\n\n                \/\/ Limit size\n                unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);\n                if (nBytes >= MAX_STANDARD_TX_SIZE)\n                {\n                    strFailReason = _(\"Transaction too large\");\n                    return false;\n                }\n                dPriority \/= nBytes;\n\n                \/\/ Check that enough fee is included\n                int64 nPayFee = nTransactionFee * (1 + (int64)nBytes \/ 1000);\n                bool fAllowFree = CTransaction::AllowFree(dPriority);\n                int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);\n                if (nFeeRet < max(nPayFee, nMinFee))\n                {\n                    nFeeRet = max(nPayFee, nMinFee);\n                    continue;\n                }\n\n                \/\/ Fill vtxPrev by copying from previous transactions vtxPrev\n                wtxNew.AddSupportingTransactions();\n                wtxNew.fTimeReceivedIsTxTime = true;\n\n                break;\n            }\n        }\n    }\n    return true;\n}\n\nstring CWallet::SendMoneyFromAddress(const CTxDestination &fromAddress, CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)\n{\n    CReserveKey reservekey(this);\n    int64 nFeeRequired;\n\n    string strError;\n    if (IsLocked())\n    {\n        strError = _(\"Error: Wallet locked, unable to create transaction!\");\n        printf(\"SendMoney() : %s\", strError.c_str());\n        return strError;\n    }\n    if (fWalletUnlockStakingOnly)\n    {\n        strError = _(\"Error: Wallet unlocked for staking only, unable to create transaction.\");\n        printf(\"SendMoney() : %s\", strError.c_str());\n        return strError;\n    }\n    if (!CreateTransaction(fromAddress, scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strError))\n    {\n        if (nValue + nFeeRequired > GetAddressBalance(fromAddress))\n            strError = strprintf(_(\"Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!\"), FormatMoney(nFeeRequired).c_str());\n        printf(\"SendMoney() : %s\\n\", strError.c_str());\n        return strError;\n    }\n\n    if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired))\n        return \"ABORTED\";\n\n    if (!CommitTransaction(wtxNew, reservekey))\n        return _(\"Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.\");\n\n    return \"\";\n}\n\nint64 CWallet::GetAddressBalance(const CTxDestination &address)\n{\n    int64 nBalance = 0;\n    {\n        map<CTxDestination, int64> balances = GetAddressBalances();\n        map<CTxDestination, int64>::iterator mi = balances.find(address);\n        if(mi != balances.end()){\n            nBalance = (*mi).second;\n        }\n    }\n    return nBalance;\n}\n\nstring CWallet::SendMoneyFromAddressToDestination(const CTxDestination &fromAddress, const CTxDestination &toAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)\n{\n    \/\/ Check amount\n    if (nValue <= 0)\n        return _(\"Invalid amount\");\n    if (nValue + nTransactionFee > GetAddressBalance(fromAddress))\n        return _(\"Insufficient funds\");\n\n    \/\/ Parse Bitcoin address\n    CScript scriptPubKey;\n    scriptPubKey.SetDestination(toAddress);\n\n    return SendMoneyFromAddress(fromAddress, scriptPubKey, nValue, wtxNew, fAskFee);\n}","avg_line_length":34.7629388346,"max_line_length":235,"alphanum_fraction":0.5686309214,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1876,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\ufeff\/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0.\n *\/\n\n#include <aws\/docdb\/model\/ModifyDBClusterSnapshotAttributeResult.h>\n#include <aws\/core\/utils\/xml\/XmlSerializer.h>\n#include <aws\/core\/AmazonWebServiceResult.h>\n#include <aws\/core\/utils\/StringUtils.h>\n#include <aws\/core\/utils\/logging\/LogMacros.h>\n\n#include <utility>\n\nusing namespace Aws::DocDB::Model;\nusing namespace Aws::Utils::Xml;\nusing namespace Aws::Utils::Logging;\nusing namespace Aws::Utils;\nusing namespace Aws;\n\nModifyDBClusterSnapshotAttributeResult::ModifyDBClusterSnapshotAttributeResult()\n{\n}\n\nModifyDBClusterSnapshotAttributeResult::ModifyDBClusterSnapshotAttributeResult(const Aws::AmazonWebServiceResult<XmlDocument>& result)\n{\n  *this = result;\n}\n\nModifyDBClusterSnapshotAttributeResult& ModifyDBClusterSnapshotAttributeResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)\n{\n  const XmlDocument& xmlDocument = result.GetPayload();\n  XmlNode rootNode = xmlDocument.GetRootElement();\n  XmlNode resultNode = rootNode;\n  if (!rootNode.IsNull() && (rootNode.GetName() != \"ModifyDBClusterSnapshotAttributeResult\"))\n  {\n    resultNode = rootNode.FirstChild(\"ModifyDBClusterSnapshotAttributeResult\");\n  }\n\n  if(!resultNode.IsNull())\n  {\n    XmlNode dBClusterSnapshotAttributesResultNode = resultNode.FirstChild(\"DBClusterSnapshotAttributesResult\");\n    if(!dBClusterSnapshotAttributesResultNode.IsNull())\n    {\n      m_dBClusterSnapshotAttributesResult = dBClusterSnapshotAttributesResultNode;\n    }\n  }\n\n  if (!rootNode.IsNull()) {\n    XmlNode responseMetadataNode = rootNode.FirstChild(\"ResponseMetadata\");\n    m_responseMetadata = responseMetadataNode;\n    AWS_LOGSTREAM_DEBUG(\"Aws::DocDB::Model::ModifyDBClusterSnapshotAttributeResult\", \"x-amzn-request-id: \" << m_responseMetadata.GetRequestId() );\n  }\n  return *this;\n}\n","avg_line_length":34.1090909091,"max_line_length":146,"alphanum_fraction":0.7830490405,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4162,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":15.0,"content":"\/\/=================================================================================================\n\/*!\n\/\/  \\file src\/mathtest\/smatdmatadd\/UCaUHa.cpp\n\/\/  \\brief Source file for the UCaUHa sparse matrix\/dense matrix addition math test\n\/\/\n\/\/  Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved\n\/\/\n\/\/  This file is part of the Blaze library. You can redistribute it and\/or modify it under\n\/\/  the terms of the New (Revised) BSD License. Redistribution and use in source and binary\n\/\/  forms, with or without modification, are permitted provided that the following conditions\n\/\/  are met:\n\/\/\n\/\/  1. Redistributions of source code must retain the above copyright notice, this list of\n\/\/     conditions and the following disclaimer.\n\/\/  2. Redistributions in binary form must reproduce the above copyright notice, this list\n\/\/     of conditions and the following disclaimer in the documentation and\/or other materials\n\/\/     provided with the distribution.\n\/\/  3. Neither the names of the Blaze development group nor the names of its contributors\n\/\/     may be used to endorse or promote products derived from this software without specific\n\/\/     prior written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n\/\/  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\/\/  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\n\/\/  SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n\/\/  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n\/\/  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/  DAMAGE.\n*\/\n\/\/=================================================================================================\n\n\n\/\/*************************************************************************************************\n\/\/ Includes\n\/\/*************************************************************************************************\n\n#include <cstdlib>\n#include <iostream>\n#include <blaze\/math\/CompressedMatrix.h>\n#include <blaze\/math\/HybridMatrix.h>\n#include <blaze\/math\/UpperMatrix.h>\n#include <blazetest\/mathtest\/Creator.h>\n#include <blazetest\/mathtest\/smatdmatadd\/OperationTest.h>\n#include <blazetest\/system\/MathTest.h>\n\n#ifdef BLAZE_USE_HPX_THREADS\n#  include <hpx\/hpx_main.hpp>\n#endif\n\n\n\/\/=================================================================================================\n\/\/\n\/\/  MAIN FUNCTION\n\/\/\n\/\/=================================================================================================\n\n\/\/*************************************************************************************************\nint main()\n{\n   std::cout << \"   Running 'UCaUHa'...\" << std::endl;\n\n   using blazetest::mathtest::TypeA;\n\n   try\n   {\n      \/\/ Matrix type definitions\n      using UCa = blaze::UpperMatrix< blaze::CompressedMatrix<TypeA> >;\n      using UHa = blaze::UpperMatrix< blaze::HybridMatrix<TypeA,128UL,128UL> >;\n\n      \/\/ Creator type definitions\n      using CUCa = blazetest::Creator<UCa>;\n      using CUHa = blazetest::Creator<UHa>;\n\n      \/\/ Running tests with small matrices\n      for( size_t i=0UL; i<=6UL; ++i ) {\n         for( size_t j=0UL; j<=UCa::maxNonZeros( i ); ++j ) {\n            RUN_SMATDMATADD_OPERATION_TEST( CUCa( i, j ), CUHa( i ) );\n         }\n      }\n\n      \/\/ Running tests with large matrices\n      RUN_SMATDMATADD_OPERATION_TEST( CUCa(  67UL,  7UL ), CUHa(  67UL ) );\n      RUN_SMATDMATADD_OPERATION_TEST( CUCa( 128UL, 16UL ), CUHa( 128UL ) );\n   }\n   catch( std::exception& ex ) {\n      std::cerr << \"\\n\\n ERROR DETECTED during sparse matrix\/dense matrix addition:\\n\"\n                << ex.what() << \"\\n\";\n      return EXIT_FAILURE;\n   }\n\n   return EXIT_SUCCESS;\n}\n\/\/*************************************************************************************************\n","avg_line_length":42.9072164948,"max_line_length":99,"alphanum_fraction":0.5696780394,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1049,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":10.0,"content":"\/\/ ARKSurvivalEvolved (329.9) SDK\n\n#ifdef _MSC_VER\n\t#pragma pack(push, 0x8)\n#endif\n\n#include \"ARKSurvivalEvolved_WoodHarvestComponent_parameters.hpp\"\n\nnamespace sdk\n{\n\/\/---------------------------------------------------------------------------\n\/\/Functions\n\/\/---------------------------------------------------------------------------\n\n\/\/ Function WoodHarvestComponent.WoodHarvestComponent_C.ExecuteUbergraph_WoodHarvestComponent\n\/\/ ()\n\/\/ Parameters:\n\/\/ int                            EntryPoint                     (Parm, ZeroConstructor, IsPlainOldData)\n\nvoid UWoodHarvestComponent_C::ExecuteUbergraph_WoodHarvestComponent(int EntryPoint)\n{\n\tstatic auto fn = UObject::FindObject<UFunction>(\"Function WoodHarvestComponent.WoodHarvestComponent_C.ExecuteUbergraph_WoodHarvestComponent\");\n\n\tUWoodHarvestComponent_C_ExecuteUbergraph_WoodHarvestComponent_Params params;\n\tparams.EntryPoint = EntryPoint;\n\n\tauto flags = fn->FunctionFlags;\n\n\tUObject::ProcessEvent(fn, &params);\n\n\tfn->FunctionFlags = flags;\n}\n\n\n}\n\n#ifdef _MSC_VER\n\t#pragma pack(pop)\n#endif\n","avg_line_length":26.225,"max_line_length":143,"alphanum_fraction":0.6558627264,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3375,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":329.0,"content":"\/*\nCopyright(c) 2002-2019 Anatoliy Kuznetsov(anatoliy_kuznetsov at yahoo.com)\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nFor more information please visit:  http:\/\/bitmagic.io\n*\/\n\n\/** \\example svsample07.cpp\n  Example of how to use bm::str_sparse_vector<> - succinct container for\n  sorted bit-transposed collection of integers\n\n  \\sa bm::sparse_vector\n  \\sa bm::sparse_vector_scanner<>::lower_bound\n*\/\n\n\/*! \\file svsample07.cpp\n    \\brief Example: sparse_vector<> lower bound search\n*\/\n\n#include <iostream>\n#include <vector>\n#include <chrono>\n#include <algorithm>\n#include <random>\n#include <algorithm>\n#include <stdexcept>\n\n#include \"bm.h\"\n#include \"bmsparsevec.h\"\n#include \"bmsparsevec_algo.h\"\n#include \"bmundef.h\" \/* clear the pre-proc defines from BM *\/\n\nusing namespace std;\n\ntypedef bm::sparse_vector<bm::id_t, bm::bvector<> > sparse_vector_u32;\n\n\/\/ generate collection of strings from integers and shuffle it\n\/\/\nstatic\nvoid generate_set(vector<unsigned>& vec)\n{\n    const unsigned max_coll = 50000;\n   \n    vec.resize(0);\n    for (unsigned i = 10; i < max_coll; i += rand() % 3)\n    {\n        vec.emplace_back(i);\n    } \/\/ for i\n    \n    \/\/ shuffle the data set\n    \/\/\n    std::random_device rd;\n    std::mt19937       g(rd());\n    std::shuffle(vec.begin(), vec.end(), g);\n}\n\n\/\/ insertion sort takes data from unsorted vector places it into sparse vector\n\/\/ maintaining correct sorted order (for fast search)\n\/\/\nstatic\nvoid insertion_sort(sparse_vector_u32& sv, const vector<unsigned>& vec)\n{\n    \/\/ scanner object is re-used throught the processing\n    \/\/\n    bm::sparse_vector_scanner<sparse_vector_u32> scanner;\n    sparse_vector_u32::size_type pos;\n\n    for (const unsigned u : vec)\n    {\n        bool found = scanner.bfind(sv, u, pos);\n        (void)found; \/\/ just to silence the unused variable warning\n        \n        sv.insert(pos, u);\n        \n    } \/\/ for u\n}\n\n\nint main(void)\n{\n    try\n    {\n        sparse_vector_u32 sv;\n        vector<unsigned> vec;\n        generate_set(vec);\n        \n        insertion_sort(sv, vec);\n        \n        sv.optimize(); \/\/ mmemory optimization after active editing\n        \n        \/\/ validate the results to match STL sort\n        std::sort(vec.begin(), vec.end());\n        {\n            vector<unsigned>::const_iterator vit = vec.begin();\n            sparse_vector_u32::const_iterator it = sv.begin();\n            sparse_vector_u32::const_iterator it_end = sv.end();\n            for (; it != it_end; ++it, ++vit)\n            {\n                unsigned u = *it;\n                if (*vit != u)\n                {\n                    cerr << \"Mismatch at:\" << u << \"!=\" << *vit << endl;\n                    return 1;\n                }\n            } \/\/ for\n        }\n        cout << \"Sort validation Ok.\" << endl;\n    }\n    catch(std::exception& ex)\n    {\n        std::cerr << ex.what() << std::endl;\n        return 1;\n    }\n\n    return 0;\n}\n","avg_line_length":26.3671875,"max_line_length":78,"alphanum_fraction":0.6251851852,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":55229,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright 2019 David Conran\n\n#include <string>\n#include \"ir_Amcor.h\"\n#include \"ir_Argo.h\"\n#include \"ir_Daikin.h\"\n#include \"ir_Electra.h\"\n#include \"ir_Fujitsu.h\"\n#include \"ir_Goodweather.h\"\n#include \"ir_Gree.h\"\n#include \"ir_Haier.h\"\n#include \"ir_Hitachi.h\"\n#include \"ir_Kelvinator.h\"\n#include \"ir_Midea.h\"\n#include \"ir_Mitsubishi.h\"\n#include \"ir_MitsubishiHeavy.h\"\n#include \"ir_Neoclima.h\"\n#include \"ir_Panasonic.h\"\n#include \"ir_Samsung.h\"\n#include \"ir_Sharp.h\"\n#include \"ir_Tcl.h\"\n#include \"ir_Teco.h\"\n#include \"ir_Toshiba.h\"\n#include \"ir_Trotec.h\"\n#include \"ir_Vestel.h\"\n#include \"ir_Whirlpool.h\"\n#include \"IRac.h\"\n#include \"IRrecv.h\"\n#include \"IRrecv_test.h\"\n#include \"IRremoteESP8266.h\"\n#include \"IRsend.h\"\n#include \"IRsend_test.h\"\n#include \"gtest\/gtest.h\"\n\n\/\/ Tests for IRac class.\n\nTEST(TestIRac, Amcor) {\n  IRAmcorAc ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 5 (AUTO), Fan: 3 (High), Temp: 19C, Max: Off\";\n\n  ac.begin();\n  irac.amcor(&ac,\n             true,                        \/\/ Power\n             stdAc::opmode_t::kAuto,      \/\/ Mode\n             19,                          \/\/ Celsius\n             stdAc::fanspeed_t::kHigh);   \/\/ Fan speed\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(AMCOR, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kAmcorBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Argo) {\n  IRArgoAC ac(0);\n  IRac irac(0);\n\n  ac.begin();\n  irac.argo(&ac,\n            true,                        \/\/ Power\n            stdAc::opmode_t::kHeat,      \/\/ Mode\n            21,                          \/\/ Celsius\n            stdAc::fanspeed_t::kHigh,    \/\/ Fan speed\n            stdAc::swingv_t::kOff,       \/\/ Veritcal swing\n            false,                       \/\/ Turbo\n            -1);                         \/\/ Sleep\n  EXPECT_TRUE(ac.getPower());\n  EXPECT_EQ(kArgoHeat, ac.getMode());\n  EXPECT_EQ(21, ac.getTemp());\n  EXPECT_EQ(kArgoFlapAuto, ac.getFlap());\n  EXPECT_FALSE(ac.getMax());  \/\/ Turbo\n  EXPECT_FALSE(ac.getNight());  \/\/ Sleep\n}\n\nTEST(TestIRac, Coolix) {\n  IRCoolixAC ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 3 (HEAT), Fan: 1 (MAX), Temp: 21C, Zone Follow: Off, \"\n      \"Sensor Temp: Ignored\";\n\n  ac.begin();\n  irac.coolix(&ac,\n              true,                        \/\/ Power\n              stdAc::opmode_t::kHeat,      \/\/ Mode\n              21,                          \/\/ Celsius\n              stdAc::fanspeed_t::kHigh,    \/\/ Fan speed\n              stdAc::swingv_t::kOff,       \/\/ Veritcal swing\n              stdAc::swingh_t::kOff,       \/\/ Horizontal swing\n              false,                       \/\/ Turbo\n              false,                       \/\/ Light\n              false,                       \/\/ Clean\n              -1);                         \/\/ Sleep\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(COOLIX, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kCoolixBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n  \/\/ Confirm we are sending with a repeat of 1. i.e. two messages.\n  EXPECT_EQ(\n      \"f38000d50\"  \/\/ 38kHz Frequency and 50% duty-cycle.\n      \/\/ Start of message #1 (i.e. Repeat '0')\n      \/\/ Header\n      \"m4480s4480\"\n      \/\/ Data\n      \"m560s1680m560s560m560s1680m560s1680m560s560m560s560m560s1680m560s560\"\n      \"m560s560m560s1680m560s560m560s560m560s1680m560s1680m560s560m560s1680\"\n      \"m560s560m560s560m560s1680m560s1680m560s1680m560s1680m560s1680m560s1680\"\n      \"m560s1680m560s1680m560s560m560s560m560s560m560s560m560s560m560s560\"\n      \"m560s560m560s1680m560s1680m560s560m560s1680m560s1680m560s560m560s560\"\n      \"m560s1680m560s560m560s560m560s1680m560s560m560s560m560s1680m560s1680\"\n      \/\/ Footer\n      \"m560s5040\"\n      \/\/ End of message #1 (i.e. Repeat '0')\n      \/\/ Start of message #2 (i.e. Repeat '1')\n      \/\/ Header\n      \"m4480s4480\"\n      \/\/ Data\n      \"m560s1680m560s560m560s1680m560s1680m560s560m560s560m560s1680m560s560\"\n      \"m560s560m560s1680m560s560m560s560m560s1680m560s1680m560s560m560s1680\"\n      \"m560s560m560s560m560s1680m560s1680m560s1680m560s1680m560s1680m560s1680\"\n      \"m560s1680m560s1680m560s560m560s560m560s560m560s560m560s560m560s560\"\n      \"m560s560m560s1680m560s1680m560s560m560s1680m560s1680m560s560m560s560\"\n      \"m560s1680m560s560m560s560m560s1680m560s560m560s560m560s1680m560s1680\"\n      \/\/ Footer\n      \"m560s105040\",\n      \/\/ End of message #2 (i.e. Repeat '1')\n      \/\/ Note: the two messages (#1 & #2) are identical.\n      ac._irsend.outputStr());\n}\n\nTEST(TestIRac, Daikin) {\n  IRDaikinESP ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 3 (COOL), Temp: 19C, Fan: 5 (High), Powerful: Off, \"\n      \"Quiet: Off, Sensor: Off, Mold: On, Comfort: Off, \"\n      \"Swing (Horizontal): Off, Swing (Vertical): Off, \"\n      \"Current Time: 00:00, Current Day: (UNKNOWN), On Time: Off, \"\n      \"Off Time: Off, Weekly Timer: On\";\n\n  ac.begin();\n  irac.daikin(&ac,\n              true,                        \/\/ Power\n              stdAc::opmode_t::kCool,      \/\/ Mode\n              19,                          \/\/ Celsius\n              stdAc::fanspeed_t::kMax,     \/\/ Fan speed\n              stdAc::swingv_t::kOff,       \/\/ Veritcal swing\n              stdAc::swingh_t::kOff,       \/\/ Horizontal swing\n              false,                       \/\/ Quiet\n              false,                       \/\/ Turbo\n              true,                        \/\/ Filter\n              true);                       \/\/ Clean\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(DAIKIN, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kDaikinBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Daikin128) {\n  IRDaikin128 ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power Toggle: On, Mode: 8 (HEAT), Temp: 27C, Fan: 9 (Quiet), \"\n      \"Powerful: Off, Quiet: On, Swing (V): On, Sleep: On, \"\n      \"Econo: Off, Clock: 21:57, On Timer: Off, On Time: 00:00, \"\n      \"Off Timer: Off, Off Time: 00:00, Light Toggle: 8 (Wall)\";\n\n  ac.begin();\n  irac.daikin128(&ac,\n                 true,                        \/\/ Power\n                 stdAc::opmode_t::kHeat,      \/\/ Mode\n                 27,                          \/\/ Celsius\n                 stdAc::fanspeed_t::kMin,     \/\/ Fan speed\n                 stdAc::swingv_t::kAuto,       \/\/ Veritcal swing\n                 true,                        \/\/ Quiet\n                 false,                       \/\/ Turbo\n                 true,                        \/\/ Light\n                 false,                       \/\/ Econo\n                 18 * 60,                     \/\/ Sleep\n                 21 * 60 + 57);               \/\/ Clock\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(DAIKIN128, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kDaikin128Bits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Daikin160) {\n  IRDaikin160 ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 2 (DRY), Temp: 23C, Fan: 1 (Low), \"\n      \"Vent Position (V): 3 (Middle)\";\n\n  ac.begin();\n  irac.daikin160(&ac,\n                 true,                        \/\/ Power\n                 stdAc::opmode_t::kDry,       \/\/ Mode\n                 23,                          \/\/ Celsius\n                 stdAc::fanspeed_t::kMin,     \/\/ Fan speed\n                 stdAc::swingv_t::kMiddle);   \/\/ Veritcal swing\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(DAIKIN160, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kDaikin160Bits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Daikin176) {\n  IRDaikin176 ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 7 (COOL), Temp: 26C, Fan: 1 (Low), Swing (H): 5 (Auto)\";\n\n  ac.begin();\n  irac.daikin176(&ac,\n                 true,                        \/\/ Power\n                 stdAc::opmode_t::kCool,      \/\/ Mode\n                 26,                          \/\/ Celsius\n                 stdAc::fanspeed_t::kLow,     \/\/ Fan speed\n                 stdAc::swingh_t::kAuto);     \/\/ Horizontal swing\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(DAIKIN176, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kDaikin176Bits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Daikin2) {\n  IRDaikin2 ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 3 (COOL), Temp: 19C, Fan: 1 (Low), \"\n      \"Swing (V): 14 (Auto), Swing (H): 0, Clock: 00:00, On Time: Off, \"\n      \"Off Time: Off, Sleep Time: Off, Beep: 1 (Quiet), Light: 1 (Bright), \"\n      \"Mold: On, Clean: Off, Fresh Air: Off, Eye: Off, Eye Auto: Off, \"\n      \"Quiet: Off, Powerful: Off, Purify: On, Econo: Off\";\n\n  ac.begin();\n  irac.daikin2(&ac,\n               true,                        \/\/ Power\n               stdAc::opmode_t::kCool,      \/\/ Mode\n               19,                          \/\/ Celsius\n               stdAc::fanspeed_t::kLow,     \/\/ Fan speed\n               stdAc::swingv_t::kOff,       \/\/ Veritcal swing\n               stdAc::swingh_t::kOff,       \/\/ Horizontal swing\n               false,                       \/\/ Quiet\n               false,                       \/\/ Turbo\n               true,                        \/\/ Light\n               false,                       \/\/ Econo\n               true,                        \/\/ Filter\n               true,                        \/\/ Clean (aka Mold)\n               -1,                          \/\/ Sleep time\n               -1);                         \/\/ Current time\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(DAIKIN2, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kDaikin2Bits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Daikin216) {\n  IRDaikin216 ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 4 (HEAT), Temp: 31C, Fan: 11 (Quiet), \"\n      \"Swing (Horizontal): On, Swing (Vertical): On, Quiet: On, Powerful: Off\";\n\n  ac.begin();\n  irac.daikin216(&ac,\n                 true,                        \/\/ Power\n                 stdAc::opmode_t::kHeat,      \/\/ Mode\n                 31,                          \/\/ Celsius\n                 stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n                 stdAc::swingv_t::kAuto,      \/\/ Veritcal swing\n                 stdAc::swingh_t::kLeft,      \/\/ Horizontal swing\n                 true,                        \/\/ Quiet\n                 false);                      \/\/ Turbo (Powerful)\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(DAIKIN216, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kDaikin216Bits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Electra) {\n  IRElectraAc ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 6 (FAN), Temp: 26C, Fan: 1 (High), \"\n      \"Swing(V): On, Swing(H): On\";\n\n  ac.begin();\n  irac.electra(&ac,\n                 true,                        \/\/ Power\n                 stdAc::opmode_t::kFan,       \/\/ Mode\n                 26,                          \/\/ Celsius\n                 stdAc::fanspeed_t::kHigh,    \/\/ Fan speed\n                 stdAc::swingv_t::kAuto,      \/\/ Veritcal swing\n                 stdAc::swingh_t::kLeft);     \/\/ Horizontal swing\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(ELECTRA_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kElectraAcBits, ac._irsend.capture.bits);\n  ac.setRaw(ac._irsend.capture.state);\n  ASSERT_EQ(expected, ac.toString());\n}\n\nTEST(TestIRac, Fujitsu) {\n  IRFujitsuAC ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  std::string ardb1_expected =\n      \"Model: 2 (ARDB1), Power: On, Mode: 1 (COOL), Temp: 19C, \"\n      \"Fan: 2 (Medium), Command: N\/A\";\n  std::string arrah2e_expected =\n      \"Model: 1 (ARRAH2E), Power: On, Mode: 1 (COOL), Temp: 19C, \"\n      \"Fan: 2 (Medium), Swing: Off, Command: N\/A\";\n\n  ac.begin();\n  irac.fujitsu(&ac,\n               ARDB1,                       \/\/ Model\n               true,                        \/\/ Power\n               stdAc::opmode_t::kCool,      \/\/ Mode\n               19,                          \/\/ Celsius\n               stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n               stdAc::swingv_t::kOff,       \/\/ Veritcal swing\n               stdAc::swingh_t::kOff,       \/\/ Horizontal swing\n               false,                       \/\/ Quiet\n               false,                       \/\/ Turbo (Powerful)\n               false);                      \/\/ Econo\n  ASSERT_EQ(ardb1_expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(FUJITSU_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kFujitsuAcBits - 8, ac._irsend.capture.bits);\n  ASSERT_EQ(ardb1_expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n\n  ac._irsend.reset();\n  irac.fujitsu(&ac,\n               ARRAH2E,                     \/\/ Model\n               true,                        \/\/ Power\n               stdAc::opmode_t::kCool,      \/\/ Mode\n               19,                          \/\/ Celsius\n               stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n               stdAc::swingv_t::kOff,       \/\/ Veritcal swing\n               stdAc::swingh_t::kOff,       \/\/ Horizontal swing\n               false,                       \/\/ Quiet\n               false,                       \/\/ Turbo (Powerful)\n               false);                      \/\/ Econo\n  ASSERT_EQ(arrah2e_expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(FUJITSU_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kFujitsuAcBits, ac._irsend.capture.bits);\n  ASSERT_EQ(arrah2e_expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Goodweather) {\n  IRGoodweatherAc ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 1 (COOL), Temp: 19C, Fan: 2 (Medium), Turbo: Toggle, \"\n      \"Light: Toggle, Sleep: Toggle, Swing: 1 (Slow), Command: 0 (Power)\";\n\n  ac.begin();\n  irac.goodweather(&ac,\n                   true,                        \/\/ Power\n                   stdAc::opmode_t::kCool,      \/\/ Mode\n                   19,                          \/\/ Celsius\n                   stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n                   stdAc::swingv_t::kHigh,      \/\/ Veritcal swing\n                   true,                        \/\/ Turbo\n                   true,                        \/\/ Light\n                   8 * 60 + 0);                 \/\/ Sleep time\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(GOODWEATHER, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kGoodweatherBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Gree) {\n  IRGreeAC ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Model: 1 (YAW1F), Power: On, Mode: 1 (COOL), Temp: 22C, \"\n      \"Fan: 2 (Medium), Turbo: Off, IFeel: Off, WiFi: Off, XFan: On, \"\n      \"Light: On, Sleep: On, Swing Vertical Mode: Manual, \"\n      \"Swing Vertical Pos: 3, Timer: Off\";\n\n  ac.begin();\n  irac.gree(&ac,\n            gree_ac_remote_model_t::YAW1F,  \/\/ Model\n            true,                           \/\/ Power\n            stdAc::opmode_t::kCool,         \/\/ Mode\n            22,                             \/\/ Celsius\n            stdAc::fanspeed_t::kMedium,     \/\/ Fan speed\n            stdAc::swingv_t::kHigh,         \/\/ Veritcal swing\n            false,                          \/\/ Turbo\n            true,                           \/\/ Light\n            true,                           \/\/ Clean (aka Mold\/XFan)\n            8 * 60 + 0);                    \/\/ Sleep time\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(GREE, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kGreeBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Haier) {\n  IRHaierAC ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Command: 1 (On), Mode: 1 (COOL), Temp: 24C, Fan: 2 (Medium), \"\n      \"Swing: 1 (Up), Sleep: On, Health: On, Current Time: 13:45, \"\n      \"On Timer: Off, Off Timer: Off\";\n\n  ac.begin();\n  irac.haier(&ac,\n             true,                        \/\/ Power\n             stdAc::opmode_t::kCool,      \/\/ Mode\n             24,                          \/\/ Celsius\n             stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n             stdAc::swingv_t::kHigh,      \/\/ Veritcal swing\n             true,                        \/\/ Filter\n             8 * 60 + 0,                  \/\/ Sleep time\n             13 * 60 + 45);               \/\/ Clock\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(HAIER_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kHaierACBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\n\nTEST(TestIRac, HaierYrwo2) {\n  IRHaierACYRW02 ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Button: 5 (Power), Mode: 2 (COOL), Temp: 23C, \"\n      \"Fan: 4 (Medium), Turbo: 1 (High), Swing: 1 (Top), Sleep: On, Health: On\";\n\n  ac.begin();\n  irac.haierYrwo2(&ac,\n             true,                        \/\/ Power\n             stdAc::opmode_t::kCool,      \/\/ Mode\n             23,                          \/\/ Celsius\n             stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n             stdAc::swingv_t::kHigh,      \/\/ Veritcal swing\n             true,                        \/\/ Turbo\n             true,                        \/\/ Filter\n             8 * 60 + 0);                 \/\/ Sleep time\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(HAIER_AC_YRW02, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kHaierACYRW02Bits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Hitachi) {\n  IRHitachiAc ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 2 (AUTO), Temp: 22C, Fan: 3 (Medium), \"\n      \"Swing (Vertical): Off, Swing (Horizontal): On\";\n\n  ac.begin();\n  irac.hitachi(&ac,\n               true,                        \/\/ Power\n               stdAc::opmode_t::kAuto,      \/\/ Mode\n               22,                          \/\/ Celsius\n               stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n               stdAc::swingv_t::kOff,       \/\/ Veritcal swing\n               stdAc::swingh_t::kAuto);     \/\/ Horizontal swing\n\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(HITACHI_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kHitachiAcBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Kelvinator) {\n  IRKelvinatorAC ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 1 (COOL), Temp: 19C, Fan: 3 (Medium), Turbo: Off, \"\n      \"Quiet: Off, XFan: On, IonFilter: On, Light: On, \"\n      \"Swing (Horizontal): Off, Swing (Vertical): Off\";\n\n  ac.begin();\n  irac.kelvinator(&ac,\n                  true,                        \/\/ Power\n                  stdAc::opmode_t::kCool,      \/\/ Mode\n                  19,                          \/\/ Celsius\n                  stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n                  stdAc::swingv_t::kOff,       \/\/ Veritcal swing\n                  stdAc::swingh_t::kOff,       \/\/ Horizontal swing\n                  false,                       \/\/ Quiet\n                  false,                       \/\/ Turbo\n                  true,                        \/\/ Light\n                  true,                        \/\/ Filter\n                  true);                       \/\/ Clean\n\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(KELVINATOR, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kKelvinatorBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Midea) {\n  IRMideaAC ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 1 (DRY), Celsius: On, Temp: 27C\/80F, Fan: 2 (Medium), \"\n      \"Sleep: On, Swing(V) Toggle: Off\";\n\n  ac.begin();\n  irac.midea(&ac,\n             true,                        \/\/ Power\n             stdAc::opmode_t::kDry,       \/\/ Mode\n             true,                        \/\/ Celsius\n             27,                          \/\/ Degrees\n             stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n             stdAc::swingv_t::kOff,       \/\/ Swing (V)\n             8 * 60 + 0);                 \/\/ Sleep time\n\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(MIDEA, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kMideaBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Mitsubishi) {\n  IRMitsubishiAC ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 24 (COOL), Temp: 20C, Fan: 2 (Medium), Vane: AUTO, \"\n      \"Wide Vane: 3, Time: 14:30, On timer: 00:00, Off timer: 00:00, Timer: -\";\n\n  ac.begin();\n  irac.mitsubishi(&ac,\n                  true,                        \/\/ Power\n                  stdAc::opmode_t::kCool,      \/\/ Mode\n                  20,                          \/\/ Celsius\n                  stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n                  stdAc::swingv_t::kOff,       \/\/ Veritcal swing\n                  stdAc::swingh_t::kOff,       \/\/ Horizontal swing\n                  false,                       \/\/ Silent\n                  14 * 60 + 35);               \/\/ Clock\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(MITSUBISHI_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kMitsubishiACBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, MitsubishiHeavy88) {\n  IRMitsubishiHeavy88Ac ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 1 (COOL), Temp: 21C, Fan: 3 (Medium), \"\n      \"Swing (V): 16 (Auto), Swing (H): 0 (Off), Turbo: Off, Econo: Off, \"\n      \"3D: Off, Clean: On\";\n\n  ac.begin();\n  irac.mitsubishiHeavy88(&ac,\n                         true,                        \/\/ Power\n                         stdAc::opmode_t::kCool,      \/\/ Mode\n                         21,                          \/\/ Celsius\n                         stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n                         stdAc::swingv_t::kAuto,      \/\/ Veritcal swing\n                         stdAc::swingh_t::kOff,       \/\/ Horizontal swing\n                         false,                       \/\/ Turbo\n                         false,                       \/\/ Econo\n                         true);                       \/\/ Clean\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(MITSUBISHI_HEAVY_88, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kMitsubishiHeavy88Bits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, MitsubishiHeavy152) {\n  IRMitsubishiHeavy152Ac ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 1 (COOL), Temp: 20C, Fan: 6 (Econo), \"\n      \"Swing (V): 6 (Off), Swing (H): 0 (Auto), Silent: On, Turbo: Off, \"\n      \"Econo: On, Night: On, Filter: On, 3D: Off, Clean: Off\";\n\n  ac.begin();\n  irac.mitsubishiHeavy152(&ac,\n                          true,                        \/\/ Power\n                          stdAc::opmode_t::kCool,      \/\/ Mode\n                          20,                          \/\/ Celsius\n                          stdAc::fanspeed_t::kLow,     \/\/ Fan speed\n                          stdAc::swingv_t::kOff,       \/\/ Veritcal swing\n                          stdAc::swingh_t::kAuto,      \/\/ Horizontal swing\n                          true,                        \/\/ Silent\n                          false,                       \/\/ Turbo\n                          true,                        \/\/ Econo\n                          true,                        \/\/ Filter\n                          false,                       \/\/ Clean\n                          8 * 60);                     \/\/ Sleep\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(MITSUBISHI_HEAVY_152, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kMitsubishiHeavy152Bits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Neoclima) {\n  IRNeoclimaAc ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 1 (COOL), Temp: 20C, Fan: 3 (Low), \"\n      \"Swing(V): Off, Swing(H): On, Sleep: On, Turbo: Off, Hold: Off, Ion: On, \"\n      \"Eye: Off, Light: On, Follow: Off, 8C Heat: Off, Fresh: Off, \"\n      \"Button: 0 (Power)\";\n\n  ac.begin();\n  irac.neoclima(&ac,\n                true,                        \/\/ Power\n                stdAc::opmode_t::kCool,      \/\/ Mode\n                20,                          \/\/ Celsius\n                stdAc::fanspeed_t::kLow,     \/\/ Fan speed\n                stdAc::swingv_t::kOff,       \/\/ Veritcal swing\n                stdAc::swingh_t::kAuto,      \/\/ Horizontal swing\n                false,                       \/\/ Turbo\n                true,                        \/\/ Light\n                true,                        \/\/ Filter\n                8 * 60);                     \/\/ Sleep\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(decode_type_t::NEOCLIMA, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kNeoclimaBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Panasonic) {\n  IRPanasonicAc ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected_nke[] =\n      \"Model: 2 (NKE), Power: On, Mode: 4 (HEAT), Temp: 28C, Fan: 2 (Medium), \"\n      \"Swing (Vertical): 15 (AUTO), Swing (Horizontal): 6 (Middle), Quiet: On, \"\n      \"Powerful: Off, Clock: 19:17, On Timer: Off, Off Timer: Off\";\n\n  ac.begin();\n  irac.panasonic(&ac,\n                 kPanasonicNke,               \/\/ Model\n                 true,                        \/\/ Power\n                 stdAc::opmode_t::kHeat,      \/\/ Mode\n                 28,                          \/\/ Celsius\n                 stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n                 stdAc::swingv_t::kAuto,      \/\/ Veritcal swing\n                 stdAc::swingh_t::kLeft,      \/\/ Horizontal swing\n                 true,                        \/\/ Quiet\n                 false,                       \/\/ Turbo\n                 19 * 60 + 17);               \/\/ Clock\n  ASSERT_EQ(expected_nke, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(PANASONIC_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kPanasonicAcBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected_nke, IRAcUtils::resultAcToString(&ac._irsend.capture));\n\n  char expected_dke[] =\n      \"Model: 3 (DKE), Power: On, Mode: 3 (COOL), Temp: 18C, Fan: 4 (High), \"\n      \"Swing (Vertical): 1 (Full Up), Swing (Horizontal): 6 (Middle), \"\n      \"Quiet: Off, Powerful: On, Clock: 19:17, On Timer: Off, Off Timer: Off\";\n  ac._irsend.reset();\n  irac.panasonic(&ac,\n               kPanasonicDke,               \/\/ Model\n               true,                        \/\/ Power\n               stdAc::opmode_t::kCool,      \/\/ Mode\n               18,                          \/\/ Celsius\n               stdAc::fanspeed_t::kMax,     \/\/ Fan speed\n               stdAc::swingv_t::kHigh,      \/\/ Veritcal swing\n               stdAc::swingh_t::kMiddle,    \/\/ Horizontal swing\n               false,                       \/\/ Quiet\n               true,                        \/\/ Turbo\n               19 * 60 + 17);               \/\/ Clock\n  ASSERT_EQ(expected_dke, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(PANASONIC_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kPanasonicAcBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected_dke, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Samsung) {\n  IRSamsungAc ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 0 (AUTO), Temp: 28C, Fan: 6 (Auto), Swing: On, \"\n      \"Beep: On, Clean: On, Quiet: On, Powerful: Off\";\n\n  ac.begin();\n  irac.samsung(&ac,\n               true,                        \/\/ Power\n               stdAc::opmode_t::kAuto,      \/\/ Mode\n               28,                          \/\/ Celsius\n               stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n               stdAc::swingv_t::kAuto,      \/\/ Veritcal swing\n               true,                        \/\/ Quiet\n               false,                       \/\/ Turbo\n               true,                        \/\/ Clean\n               true,                        \/\/ Beep\n               false);                      \/\/ with dopower Off\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(SAMSUNG_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kSamsungAcBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n\n  ac._irsend.reset();\n  irac.samsung(&ac,\n               true,                        \/\/ Power\n               stdAc::opmode_t::kAuto,      \/\/ Mode\n               28,                          \/\/ Celsius\n               stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n               stdAc::swingv_t::kAuto,      \/\/ Veritcal swing\n               true,                        \/\/ Quiet\n               false,                       \/\/ Turbo\n               true,                        \/\/ Clean\n               true,                        \/\/ Beep\n               true);                       \/\/ with dopower On\n  ASSERT_EQ(expected, ac.toString());  \/\/ Class should be in the desired mode.\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(SAMSUNG_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kSamsungAcExtendedBits, ac._irsend.capture.bits);\n  \/\/ However, we expect a plain \"on\" state as it should be sent before the\n  \/\/ desired state.\n  char expected_on[] =\n      \"Power: On, Mode: 1 (COOL), Temp: 24C, Fan: 0 (Auto), Swing: Off, \"\n      \"Beep: Off, Clean: Off, Quiet: Off, Powerful: Off\";\n  ASSERT_EQ(expected_on, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Sharp) {\n  IRSharpAc ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 2 (COOL), Temp: 28C, Fan: 3 (Medium)\";\n\n  ac.begin();\n  irac.sharp(&ac,\n             true,                         \/\/ Power\n             stdAc::opmode_t::kCool,       \/\/ Mode\n             28,                           \/\/ Celsius\n             stdAc::fanspeed_t::kMedium);  \/\/ Fan speed\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(SHARP_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kSharpAcBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Tcl112) {\n  IRTcl112Ac ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 3 (COOL), Temp: 20C, Fan: 3 (Medium), Econo: On, \"\n      \"Health: On, Light: On, Turbo: Off, Swing (H): On, Swing (V): Off\";\n\n  ac.begin();\n  irac.tcl112(&ac,\n              true,                        \/\/ Power\n              stdAc::opmode_t::kCool,      \/\/ Mode\n              20,                          \/\/ Celsius\n              stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n              stdAc::swingv_t::kOff,       \/\/ Veritcal swing\n              stdAc::swingh_t::kAuto,      \/\/ Horizontal swing\n              false,                       \/\/ Turbo\n              true,                        \/\/ Light\n              true,                        \/\/ Econo\n              true);                       \/\/ Filter (aka. Health)\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(TCL112AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kTcl112AcBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Teco) {\n  IRTecoAc ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 0 (AUTO), Temp: 21C, Fan: 2 (Medium), Sleep: On, \"\n      \"Swing: On, Light: On, Humid: Off, Save: Off\";\n\n  ac.begin();\n  irac.teco(&ac,\n            true,                        \/\/ Power\n            stdAc::opmode_t::kAuto,      \/\/ Mode\n            21,                          \/\/ Celsius\n            stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n            stdAc::swingv_t::kAuto,      \/\/ Veritcal swing\n            true,                        \/\/ Light\n            8 * 60 + 30);                \/\/ Sleep\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(TECO, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kTecoBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Toshiba) {\n  IRToshibaAC ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] = \"Power: On, Mode: 2 (DRY), Temp: 29C, Fan: 2 (UNKNOWN)\";\n\n  ac.begin();\n  irac.toshiba(&ac,\n               true,                      \/\/ Power\n               stdAc::opmode_t::kDry,     \/\/ Mode\n               29,                        \/\/ Celsius\n               stdAc::fanspeed_t::kLow);  \/\/ Fan speed\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(TOSHIBA_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kToshibaACBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Trotec) {\n  IRTrotecESP ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 1 (COOL), Temp: 18C, Fan: 3 (High), Sleep: On\";\n\n  ac.begin();\n  irac.trotec(&ac,\n              true,                        \/\/ Power\n              stdAc::opmode_t::kCool,      \/\/ Mode\n              18,                          \/\/ Celsius\n              stdAc::fanspeed_t::kHigh,    \/\/ Fan speed\n              8 * 60 + 17);                \/\/ Sleep\n  EXPECT_TRUE(ac.getPower());\n  EXPECT_EQ(kTrotecCool, ac.getMode());\n  EXPECT_EQ(18, ac.getTemp());\n  EXPECT_EQ(kTrotecFanHigh, ac.getSpeed());\n  EXPECT_TRUE(ac.getSleep());\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(TROTEC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kTrotecBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, Vestel) {\n  IRVestelAc ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Power: On, Mode: 0 (AUTO), Temp: 22C, Fan: 5 (Low), Sleep: On, \"\n      \"Turbo: Off, Ion: On, Swing: On\";\n\n  ac.begin();\n  irac.vestel(&ac,\n              true,                      \/\/ Power\n              stdAc::opmode_t::kAuto,    \/\/ Mode\n              22,                        \/\/ Celsius\n              stdAc::fanspeed_t::kLow,   \/\/ Fan speed\n              stdAc::swingv_t::kHigh,    \/\/ Veritcal swing\n              false,                     \/\/ Turbo\n              true,                      \/\/ Filter\n              8 * 60 + 0);               \/\/ Sleep time\n              \/\/ 13 * 60 + 45);             \/\/ Clock\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(VESTEL_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kVestelAcBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n\n  ac._irsend.reset();\n  char expected_clocks[] =\n      \"Time: 13:45, Timer: Off, On Timer: Off, Off Timer: Off\";\n\n  ac.begin();\n  irac.vestel(&ac,\n              true,                      \/\/ Power\n              stdAc::opmode_t::kAuto,    \/\/ Mode\n              22,                        \/\/ Celsius\n              stdAc::fanspeed_t::kLow,   \/\/ Fan speed\n              stdAc::swingv_t::kHigh,    \/\/ Veritcal swing\n              false,                     \/\/ Turbo\n              true,                      \/\/ Filter\n              8 * 60 + 0,                \/\/ Sleep time\n              13 * 60 + 45,              \/\/ Clock\n              false);                    \/\/ Don't send the normal message.\n                                         \/\/ Just for testing purposes.\n  ASSERT_EQ(expected_clocks, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(VESTEL_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kVestelAcBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected_clocks, IRAcUtils::resultAcToString(&ac._irsend.capture));\n\n  \/\/ Now check it sends both messages during normal operation when the\n  \/\/ clock is set.\n  ac._irsend.reset();\n  ac.begin();\n  irac.vestel(&ac,\n              true,                      \/\/ Power\n              stdAc::opmode_t::kAuto,    \/\/ Mode\n              22,                        \/\/ Celsius\n              stdAc::fanspeed_t::kLow,   \/\/ Fan speed\n              stdAc::swingv_t::kHigh,    \/\/ Veritcal swing\n              false,                     \/\/ Turbo\n              true,                      \/\/ Filter\n              8 * 60 + 0,                \/\/ Sleep time\n              13 * 60 + 45);             \/\/ Clock\n\n  EXPECT_EQ(\n      \"f38000d50\"\n      \"m3110s9066\"\n      \"m520s1535m520s480m520s480m520s480m520s480m520s480m520s480m520s480\"\n      \"m520s480m520s1535m520s480m520s480m520s480m520s480m520s480m520s480\"\n      \"m520s1535m520s1535m520s1535m520s1535m520s480m520s1535m520s480m520s1535\"\n      \"m520s1535m520s1535m520s480m520s480m520s480m520s480m520s480m520s480\"\n      \"m520s480m520s480m520s480m520s480m520s480m520s1535m520s1535m520s480\"\n      \"m520s1535m520s480m520s1535m520s480m520s480m520s480m520s480m520s480\"\n      \"m520s480m520s480m520s1535m520s480m520s1535m520s1535m520s1535m520s1535\"\n      \"m520s100000\"\n      \"m3110s9066\"\n      \"m520s1535m520s480m520s480m520s480m520s480m520s480m520s480m520s480\"\n      \"m520s480m520s1535m520s480m520s480m520s480m520s1535m520s1535m520s480\"\n      \"m520s1535m520s1535m520s1535m520s1535m520s480m520s480m520s480m520s480\"\n      \"m520s480m520s480m520s480m520s480m520s480m520s480m520s480m520s480\"\n      \"m520s480m520s480m520s480m520s480m520s1535m520s480m520s1535m520s1535\"\n      \"m520s480m520s480m520s480m520s480m520s1535m520s480m520s1535m520s1535\"\n      \"m520s480m520s1535m520s480m520s480m520s480m520s480m520s480m520s480\"\n      \"m520s100000\", ac._irsend.outputStr());\n}\n\n\nTEST(TestIRac, Whirlpool) {\n  IRWhirlpoolAc ac(0);\n  IRac irac(0);\n  IRrecv capture(0);\n  char expected[] =\n      \"Model: 1 (DG11J13A), Power toggle: On, Mode: 1 (AUTO), Temp: 21C, \"\n      \"Fan: 3 (Low), Swing: On, Light: On, Clock: 23:58, On Timer: Off, \"\n      \"Off Timer: Off, Sleep: On, Super: Off, Command: 1 (POWER)\";\n\n  ac.begin();\n  irac.whirlpool(&ac,\n                 DG11J13A,\n                 true,                        \/\/ Power\n                 stdAc::opmode_t::kAuto,      \/\/ Mode\n                 21,                          \/\/ Celsius\n                 stdAc::fanspeed_t::kMedium,  \/\/ Fan speed\n                 stdAc::swingv_t::kAuto,      \/\/ Veritcal swing\n                 false,                       \/\/ Turbo\n                 true,                        \/\/ Light\n                 8 * 60 + 30,                 \/\/ Sleep\n                 23 * 60 + 58);               \/\/ Clock\n  ASSERT_EQ(expected, ac.toString());\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(WHIRLPOOL_AC, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kWhirlpoolAcBits, ac._irsend.capture.bits);\n  ASSERT_EQ(expected, IRAcUtils::resultAcToString(&ac._irsend.capture));\n}\n\nTEST(TestIRac, cmpStates) {\n  stdAc::state_t a, b;\n  a.protocol = decode_type_t::COOLIX;\n  a.model = -1;\n  a.power = true;\n  a.celsius = true;\n  a.degrees = 25;\n  a.mode = stdAc::opmode_t::kAuto;\n  a.fanspeed = stdAc::fanspeed_t::kAuto;\n  a.swingh = stdAc::swingh_t::kOff;\n  a.swingv = stdAc::swingv_t::kOff;\n  a.quiet = false;\n  a.turbo = false;\n  a.light = false;\n  a.econo = false;\n  a.beep = false;\n  a.filter = false;\n  a.clean = false;\n  a.quiet = false;\n  a.sleep = -1;\n  a.clock = -1;\n\n  ASSERT_FALSE(IRac::cmpStates(a, a));\n  ASSERT_TRUE(IRac::cmpStates(a, b));\n\n  b = a;\n  ASSERT_FALSE(IRac::cmpStates(a, b));\n\n  \/\/ Check we don't compare the clock.\n  b.clock = 1234;\n  ASSERT_FALSE(IRac::cmpStates(a, b));\n\n  \/\/ Now make them different.\n  b.power = false;\n  ASSERT_TRUE(IRac::cmpStates(a, b));\n}\n\nTEST(TestIRac, handleToggles) {\n  stdAc::state_t desired, prev, result;\n  desired.protocol = decode_type_t::COOLIX;\n  desired.model = -1;\n  desired.power = true;\n  desired.celsius = true;\n  desired.degrees = 25;\n  desired.mode = stdAc::opmode_t::kAuto;\n  desired.fanspeed = stdAc::fanspeed_t::kAuto;\n  desired.swingh = stdAc::swingh_t::kOff;\n  desired.swingv = stdAc::swingv_t::kOff;\n  desired.quiet = false;\n  desired.turbo = false;\n  desired.light = false;\n  desired.econo = false;\n  desired.beep = false;\n  desired.filter = false;\n  desired.clean = false;\n  desired.quiet = false;\n  desired.sleep = -1;\n  desired.clock = -1;\n\n  \/\/ The states should be the same as we gave no previous state.\n  EXPECT_FALSE(IRac::cmpStates(desired, IRac::handleToggles(desired)));\n  \/\/ The states should be the same as we gave no settings that changed.\n  prev = desired;\n  EXPECT_FALSE(IRac::cmpStates(desired, IRac::handleToggles(desired, &prev)));\n  \/\/ Change something that isn't a toggle.\n  desired.degrees = 26;\n  ASSERT_TRUE(IRac::cmpStates(desired, prev));\n  \/\/ Still shouldn't change.\n  EXPECT_FALSE(IRac::cmpStates(desired, IRac::handleToggles(desired, &prev)));\n  prev.turbo = true;  \/\/ This requires a toggle.\n  result = IRac::handleToggles(desired, &prev);\n  EXPECT_TRUE(IRac::cmpStates(desired, result));\n  EXPECT_TRUE(result.turbo);\n  desired.turbo = true;  \/\/ As the desired setting hasn't changed from previous\n                         \/\/ the result should not have turbo set, as it is\n                         \/\/ a toggle setting.\n  result = IRac::handleToggles(desired, &prev);\n  EXPECT_TRUE(IRac::cmpStates(desired, result));\n  EXPECT_FALSE(result.turbo);\n\n  \/\/ Go back to the same states.\n  prev = desired;\n  ASSERT_FALSE(IRac::cmpStates(desired, prev));\n  \/\/ Test swing, as it is more complicated.\n  result = IRac::handleToggles(desired, &prev);\n  EXPECT_EQ(stdAc::swingv_t::kOff, result.swingv);\n  desired.swingv = stdAc::swingv_t::kAuto;\n  result = IRac::handleToggles(desired, &prev);\n  EXPECT_NE(stdAc::swingv_t::kOff, result.swingv);\n\n  prev = desired;  \/\/ Pretend it was sent and time has passed.\n  ASSERT_FALSE(IRac::cmpStates(desired, prev));\n  ASSERT_NE(stdAc::swingv_t::kOff, desired.swingv);\n\n  \/\/ User changes setting but it's still an \"on\" setting, as this device\n  \/\/ only has a binary on\/off for swingv. Nothing should change.\n  desired.swingv = stdAc::swingv_t::kHigh;\n  result = IRac::handleToggles(desired, &prev);\n  ASSERT_EQ(stdAc::swingv_t::kOff, result.swingv);  \/\/ i.e No toggle.\n\n  prev = desired;  \/\/ Pretend it was sent and time has passed.\n  \/\/ User changes setting to off. i.e. It is no longer on, so it should toggle.\n  desired.swingv = stdAc::swingv_t::kOff;\n  result = IRac::handleToggles(desired, &prev);\n  ASSERT_NE(stdAc::swingv_t::kOff, result.swingv);  \/\/ i.e A toggle.\n}\n\nTEST(TestIRac, strToBool) {\n  EXPECT_TRUE(IRac::strToBool(\"ON\"));\n  EXPECT_TRUE(IRac::strToBool(\"1\"));\n  EXPECT_TRUE(IRac::strToBool(\"TRUE\"));\n  EXPECT_TRUE(IRac::strToBool(\"YES\"));\n  EXPECT_FALSE(IRac::strToBool(\"OFF\"));\n  EXPECT_FALSE(IRac::strToBool(\"0\"));\n  EXPECT_FALSE(IRac::strToBool(\"FALSE\"));\n  EXPECT_FALSE(IRac::strToBool(\"NO\"));\n  EXPECT_FALSE(IRac::strToBool(\"FOOBAR\"));\n  EXPECT_TRUE(IRac::strToBool(\"FOOBAR\", true));\n}\n\nTEST(TestIRac, strToOpmode) {\n  EXPECT_EQ(stdAc::opmode_t::kAuto, IRac::strToOpmode(\"AUTO\"));\n  EXPECT_EQ(stdAc::opmode_t::kCool, IRac::strToOpmode(\"COOL\"));\n  EXPECT_EQ(stdAc::opmode_t::kHeat, IRac::strToOpmode(\"HEAT\"));\n  EXPECT_EQ(stdAc::opmode_t::kDry, IRac::strToOpmode(\"DRY\"));\n  EXPECT_EQ(stdAc::opmode_t::kFan, IRac::strToOpmode(\"FAN\"));\n  EXPECT_EQ(stdAc::opmode_t::kFan, IRac::strToOpmode(\"FAN_ONLY\"));\n  EXPECT_EQ(stdAc::opmode_t::kAuto, IRac::strToOpmode(\"FOOBAR\"));\n  EXPECT_EQ(stdAc::opmode_t::kOff, IRac::strToOpmode(\"OFF\"));\n  EXPECT_EQ(stdAc::opmode_t::kOff, IRac::strToOpmode(\"FOOBAR\",\n                                                     stdAc::opmode_t::kOff));\n}\n\nTEST(TestIRac, strToFanspeed) {\n  EXPECT_EQ(stdAc::fanspeed_t::kAuto, IRac::strToFanspeed(\"AUTO\"));\n  EXPECT_EQ(stdAc::fanspeed_t::kMin, IRac::strToFanspeed(\"MIN\"));\n  EXPECT_EQ(stdAc::fanspeed_t::kLow, IRac::strToFanspeed(\"LOW\"));\n  EXPECT_EQ(stdAc::fanspeed_t::kMedium, IRac::strToFanspeed(\"MEDIUM\"));\n  EXPECT_EQ(stdAc::fanspeed_t::kHigh, IRac::strToFanspeed(\"HIGH\"));\n  EXPECT_EQ(stdAc::fanspeed_t::kMax, IRac::strToFanspeed(\"MAX\"));\n  EXPECT_EQ(stdAc::fanspeed_t::kAuto, IRac::strToFanspeed(\"FOOBAR\"));\n  EXPECT_EQ(stdAc::fanspeed_t::kMin,\n            IRac::strToFanspeed(\"FOOBAR\", stdAc::fanspeed_t::kMin));\n}\n\nTEST(TestIRac, strToSwingV) {\n  EXPECT_EQ(stdAc::swingv_t::kAuto, IRac::strToSwingV(\"AUTO\"));\n  EXPECT_EQ(stdAc::swingv_t::kLowest, IRac::strToSwingV(\"LOWEST\"));\n  EXPECT_EQ(stdAc::swingv_t::kLow, IRac::strToSwingV(\"LOW\"));\n  EXPECT_EQ(stdAc::swingv_t::kMiddle, IRac::strToSwingV(\"MIDDLE\"));\n  EXPECT_EQ(stdAc::swingv_t::kHigh, IRac::strToSwingV(\"HIGH\"));\n  EXPECT_EQ(stdAc::swingv_t::kHighest, IRac::strToSwingV(\"HIGHEST\"));\n  EXPECT_EQ(stdAc::swingv_t::kOff, IRac::strToSwingV(\"OFF\"));\n  EXPECT_EQ(stdAc::swingv_t::kOff, IRac::strToSwingV(\"FOOBAR\"));\n  EXPECT_EQ(stdAc::swingv_t::kAuto,\n            IRac::strToSwingV(\"FOOBAR\", stdAc::swingv_t::kAuto));\n}\n\nTEST(TestIRac, strToSwingH) {\n  EXPECT_EQ(stdAc::swingh_t::kAuto, IRac::strToSwingH(\"AUTO\"));\n  EXPECT_EQ(stdAc::swingh_t::kLeftMax, IRac::strToSwingH(\"MAX LEFT\"));\n  EXPECT_EQ(stdAc::swingh_t::kLeft, IRac::strToSwingH(\"LEFT\"));\n  EXPECT_EQ(stdAc::swingh_t::kMiddle, IRac::strToSwingH(\"CENTRE\"));\n  EXPECT_EQ(stdAc::swingh_t::kRight, IRac::strToSwingH(\"RIGHT\"));\n  EXPECT_EQ(stdAc::swingh_t::kRightMax, IRac::strToSwingH(\"RIGHTMAX\"));\n  EXPECT_EQ(stdAc::swingh_t::kOff, IRac::strToSwingH(\"OFF\"));\n  EXPECT_EQ(stdAc::swingh_t::kOff, IRac::strToSwingH(\"FOOBAR\"));\n  EXPECT_EQ(stdAc::swingh_t::kAuto,\n            IRac::strToSwingH(\"FOOBAR\", stdAc::swingh_t::kAuto));\n}\n\nTEST(TestIRac, strToModel) {\n  EXPECT_EQ(panasonic_ac_remote_model_t::kPanasonicLke,\n            IRac::strToModel(\"LKE\"));\n  EXPECT_EQ(panasonic_ac_remote_model_t::kPanasonicLke,\n            IRac::strToModel(\"PANASONICLKE\"));\n  EXPECT_EQ(fujitsu_ac_remote_model_t::ARRAH2E,\n            IRac::strToModel(\"ARRAH2E\"));\n  EXPECT_EQ(whirlpool_ac_remote_model_t::DG11J13A,\n            IRac::strToModel(\"DG11J13A\"));\n  EXPECT_EQ(1, IRac::strToModel(\"1\"));\n  EXPECT_EQ(10, IRac::strToModel(\"10\"));\n  EXPECT_EQ(-1, IRac::strToModel(\"0\"));\n  EXPECT_EQ(-1, IRac::strToModel(\"FOOBAR\"));\n  EXPECT_EQ(0, IRac::strToModel(\"FOOBAR\", 0));\n}\n\nTEST(TestIRac, boolToString) {\n  EXPECT_EQ(\"on\", IRac::boolToString(true));\n  EXPECT_EQ(\"off\", IRac::boolToString(false));\n}\n\nTEST(TestIRac, opmodeToString) {\n  EXPECT_EQ(\"off\", IRac::opmodeToString(stdAc::opmode_t::kOff));\n  EXPECT_EQ(\"auto\", IRac::opmodeToString(stdAc::opmode_t::kAuto));\n  EXPECT_EQ(\"cool\", IRac::opmodeToString(stdAc::opmode_t::kCool));\n  EXPECT_EQ(\"unknown\", IRac::opmodeToString((stdAc::opmode_t)500));\n}\n\nTEST(TestIRac, fanspeedToString) {\n  EXPECT_EQ(\"low\", IRac::fanspeedToString(stdAc::fanspeed_t::kLow));\n  EXPECT_EQ(\"auto\", IRac::fanspeedToString(stdAc::fanspeed_t::kAuto));\n  EXPECT_EQ(\"unknown\", IRac::fanspeedToString((stdAc::fanspeed_t)500));\n}\n\nTEST(TestIRac, swingvToString) {\n  EXPECT_EQ(\"off\", IRac::swingvToString(stdAc::swingv_t::kOff));\n  EXPECT_EQ(\"low\", IRac::swingvToString(stdAc::swingv_t::kLow));\n  EXPECT_EQ(\"auto\", IRac::swingvToString(stdAc::swingv_t::kAuto));\n  EXPECT_EQ(\"unknown\", IRac::swingvToString((stdAc::swingv_t)500));\n}\n\nTEST(TestIRac, swinghToString) {\n  EXPECT_EQ(\"off\", IRac::swinghToString(stdAc::swingh_t::kOff));\n  EXPECT_EQ(\"left\", IRac::swinghToString(stdAc::swingh_t::kLeft));\n  EXPECT_EQ(\"auto\", IRac::swinghToString(stdAc::swingh_t::kAuto));\n  EXPECT_EQ(\"wide\", IRac::swinghToString(stdAc::swingh_t::kWide));\n  EXPECT_EQ(\"unknown\", IRac::swinghToString((stdAc::swingh_t)500));\n}\n\n\/\/ Check that we keep the previous state info if the message is a special\n\/\/ state-less command.\nTEST(TestIRac, CoolixDecodeToState) {\n  stdAc::state_t prev;\n  prev.mode = stdAc::opmode_t::kHeat;\n  prev.power = true;\n  prev.celsius = true;\n  prev.degrees = 20;\n  prev.fanspeed = stdAc::fanspeed_t::kLow;\n\n  IRsendTest irsend(0);\n  IRrecv irrecv(0);\n  irsend.begin();\n  irsend.sendCOOLIX(kCoolixOff);  \/\/ Special state-less \"off\" message.\n  irsend.makeDecodeResult();\n  ASSERT_TRUE(irrecv.decode(&irsend.capture));\n  stdAc::state_t result;\n  ASSERT_TRUE(IRAcUtils::decodeToState(&irsend.capture, &result, &prev));\n  ASSERT_EQ(decode_type_t::COOLIX, result.protocol);\n  ASSERT_FALSE(result.power);\n  ASSERT_EQ(stdAc::opmode_t::kHeat, result.mode);\n  ASSERT_TRUE(result.celsius);\n  ASSERT_EQ(20, result.degrees);\n  ASSERT_EQ(stdAc::fanspeed_t::kLow, result.fanspeed);\n}\n\n\/\/ Check light on\/off functionality in Coolix common a\/c handling.\nTEST(TestIRac, Issue821) {\n  stdAc::state_t prev;\n  stdAc::state_t next;\n  stdAc::state_t result;\n  \/\/ state info from:\n  \/\/ https:\/\/github.com\/crankyoldgit\/IRremoteESP8266\/issues\/821#issuecomment-513708970\n  prev.protocol = decode_type_t::COOLIX;\n  prev.model = -1;\n  prev.power = true;\n  prev.mode = stdAc::opmode_t::kAuto;\n  prev.degrees = 24;\n  prev.celsius = true;\n  prev.fanspeed = stdAc::fanspeed_t::kAuto;\n  prev.swingv = stdAc::swingv_t::kOff;\n  prev.swingh = stdAc::swingh_t::kOff;\n  prev.quiet = false;\n  prev.turbo = false;\n  prev.econo = false;\n  prev.light = false;\n  prev.filter = false;\n  prev.clean = false;\n  prev.beep = false;\n\n  next = prev;\n  next.light = true;\n\n  IRac irac(0);\n  IRrecv capture(0);\n  IRCoolixAC ac(0);\n\n  ac.begin();\n  result = irac.handleToggles(next, &prev);\n  ASSERT_TRUE(result.light);\n  irac.sendAc(next, &prev);\n  ASSERT_TRUE(next.light);\n  irac.coolix(&ac,\n              result.power,     \/\/ Power\n              result.mode,      \/\/ Mode\n              result.degrees,   \/\/ Celsius\n              result.fanspeed,  \/\/ Fan speed\n              result.swingv,       \/\/ Veritcal swing\n              result.swingh,       \/\/ Horizontal swing\n              result.turbo,                       \/\/ Turbo\n              result.light,                       \/\/ Light\n              result.clean,                       \/\/ Clean\n              -1);                         \/\/ Sleep\n  ac._irsend.makeDecodeResult();\n  EXPECT_TRUE(capture.decode(&ac._irsend.capture));\n  ASSERT_EQ(COOLIX, ac._irsend.capture.decode_type);\n  ASSERT_EQ(kCoolixBits, ac._irsend.capture.bits);\n  ASSERT_EQ(\"Power: On, Led: Toggle\",\n            IRAcUtils::resultAcToString(&ac._irsend.capture));\n  EXPECT_EQ(\n      \"f38000d50m\"\n      \"4480s4480\"\n      \"m560s1680m560s560m560s1680m560s1680m560s560m560s1680m560s560m560s1680\"\n      \"m560s560m560s1680m560s560m560s560m560s1680m560s560m560s1680m560s560\"\n      \"m560s1680m560s1680m560s1680m560s1680m560s560m560s1680m560s560m560s1680\"\n      \"m560s560m560s560m560s560m560s560m560s1680m560s560m560s1680m560s560\"\n      \"m560s1680m560s560m560s1680m560s560m560s560m560s1680m560s560m560s1680\"\n      \"m560s560m560s1680m560s560m560s1680m560s1680m560s560m560s1680m560s560\"\n      \"m560s5040\"\n      \"m4480s4480\"\n      \"m560s1680m560s560m560s1680m560s1680m560s560m560s1680m560s560m560s1680\"\n      \"m560s560m560s1680m560s560m560s560m560s1680m560s560m560s1680m560s560\"\n      \"m560s1680m560s1680m560s1680m560s1680m560s560m560s1680m560s560m560s1680\"\n      \"m560s560m560s560m560s560m560s560m560s1680m560s560m560s1680m560s560\"\n      \"m560s1680m560s560m560s1680m560s560m560s560m560s1680m560s560m560s1680\"\n      \"m560s560m560s1680m560s560m560s1680m560s1680m560s560m560s1680m560s560\"\n      \"m560s105040\"\n      \"m4480s4480\"\n      \"m560s1680m560s560m560s1680m560s1680m560s560m560s560m560s1680m560s560\"\n      \"m560s560m560s1680m560s560m560s560m560s1680m560s1680m560s560m560s1680\"\n      \"m560s560m560s560m560s560m560s1680m560s1680m560s1680m560s1680m560s1680\"\n      \"m560s1680m560s1680m560s1680m560s560m560s560m560s560m560s560m560s560\"\n      \"m560s560m560s1680m560s560m560s560m560s1680m560s560m560s560m560s560\"\n      \"m560s1680m560s560m560s1680m560s1680m560s560m560s1680m560s1680m560s1680\"\n      \"m560s5040\"\n      \"m4480s4480\"\n      \"m560s1680m560s560m560s1680m560s1680m560s560m560s560m560s1680m560s560\"\n      \"m560s560m560s1680m560s560m560s560m560s1680m560s1680m560s560m560s1680\"\n      \"m560s560m560s560m560s560m560s1680m560s1680m560s1680m560s1680m560s1680\"\n      \"m560s1680m560s1680m560s1680m560s560m560s560m560s560m560s560m560s560\"\n      \"m560s560m560s1680m560s560m560s560m560s1680m560s560m560s560m560s560\"\n      \"m560s1680m560s560m560s1680m560s1680m560s560m560s1680m560s1680m560s1680\"\n      \"m560s105040\",\n      ac._irsend.outputStr());\n}\n","avg_line_length":40.4608058608,"max_line_length":86,"alphanum_fraction":0.5774864654,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":338,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"src\/countUniqueWords.h\"\n\nint main(int argc, char **argv) {\n    errors(argc);\n    std::ifstream file(argv[1]);\n    std::multiset<std::string> names;\n\n    errorOpenFile(file);\n    parsFile(file, names);\n    errorNameSize(std::distance(names.begin(), names.end()));\n    createFile(argv[1], names);\n    file.close();\n    return 0;\n}","avg_line_length":24.1428571429,"max_line_length":61,"alphanum_fraction":0.6390532544,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7764,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":30.0,"content":"\n\n#include \"toonz\/txshzeraryfxcolumn.h\"\n#include \"toonz\/tcolumnfx.h\"\n#include \"toonz\/toonzscene.h\"\n#include \"toonz\/txshcell.h\"\n#include \"toonz\/txsheet.h\"\n#include \"toonz\/fxdag.h\"\n#include \"toonz\/txshzeraryfxlevel.h\"\n#include \"toonz\/preferences.h\"\n\n#include \"tstream.h\"\n\n\/\/=============================================================================\n\/\/ TXshZeraryFxColumn\n\nTXshZeraryFxColumn::TXshZeraryFxColumn(int frameCount)\n    : m_zeraryColumnFx(new TZeraryColumnFx())\n    , m_zeraryFxLevel(new TXshZeraryFxLevel())\n    , m_iconVisible(false) {\n  m_zeraryColumnFx->addRef();\n  m_zeraryColumnFx->setColumn(this);\n  m_zeraryFxLevel->addRef();\n  m_zeraryFxLevel->setColumn(this);\n  if (frameCount <= 0) return;\n  for (int i = 0; i < frameCount; i++)\n    setCell(i, TXshCell(m_zeraryFxLevel, TFrameId(1)));\n}\n\n\/\/-----------------------------------------------------------------------------\n\nTXshZeraryFxColumn::TXshZeraryFxColumn(const TXshZeraryFxColumn &src)\n    : m_zeraryColumnFx(new TZeraryColumnFx())\n    , m_zeraryFxLevel(new TXshZeraryFxLevel())\n    , m_iconVisible(false) {\n  m_zeraryColumnFx->addRef();\n  m_zeraryColumnFx->setColumn(this);\n  m_zeraryFxLevel->addRef();\n  m_zeraryFxLevel->setColumn(this);\n  m_first = src.m_first;\n  int i;\n  for (i = 0; i < (int)src.m_cells.size(); i++) {\n    if (Preferences::instance()->isImplicitHoldEnabled() &&\n        src.m_cells[i].getFrameId().isEmptyFrame())\n      m_cells.push_back(TXshCell(0, src.m_cells[i].getFrameId()));\n    else\n      m_cells.push_back(TXshCell(m_zeraryFxLevel, src.m_cells[i].getFrameId()));\n  }\n  assert((int)src.m_cells.size() == (int)m_cells.size());\n  TFx *fx = src.getZeraryColumnFx()->getZeraryFx();\n  if (fx) {\n    std::wstring fxName = fx->getName();\n    fx                  = fx->clone(false);\n    fx->setName(fxName);\n    m_zeraryColumnFx->setZeraryFx(fx);\n  }\n}\n\n\/\/-----------------------------------------------------------------------------\n\nTXshZeraryFxColumn::~TXshZeraryFxColumn() {\n  m_zeraryColumnFx->setColumn(0);\n  m_zeraryColumnFx->release();\n  m_zeraryFxLevel->release();\n}\n\n\/\/-----------------------------------------------------------------------------\n\nTXshColumn::ColumnType TXshZeraryFxColumn::getColumnType() const {\n  return eZeraryFxType;\n}\n\n\/\/-----------------------------------------------------------------------------\n\nbool TXshZeraryFxColumn::canSetCell(const TXshCell &cell) const {\n  return cell.isEmpty() || cell.m_level->getZeraryFxLevel() != 0;\n}\n\n\/\/-----------------------------------------------------------------------------\n\nTXshColumn *TXshZeraryFxColumn::clone() const {\n  return new TXshZeraryFxColumn(*this);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nTFx *TXshZeraryFxColumn::getFx() const { return m_zeraryColumnFx; }\n\n\/\/-----------------------------------------------------------------------------\n\nbool TXshZeraryFxColumn::setCell(int row, const TXshCell &cell) {\n  if (cell.isEmpty()) return false;\n  TXshCell newCell = cell;\n  \/\/ Sto settando delle celle in una colonna nuova, devo settare anche\n  \/\/ l'effetto.\n  if (isEmpty() && getZeraryColumnFx()->getZeraryFx() == 0) {\n    newCell                      = TXshCell(m_zeraryFxLevel, cell.getFrameId());\n    TXshZeraryFxLevel *fxLevel   = cell.m_level->getZeraryFxLevel();\n    TXshZeraryFxColumn *fxColumn = fxLevel->getColumn();\n    m_zeraryColumnFx->setZeraryFx(fxColumn->getZeraryColumnFx()->getZeraryFx());\n  }\n\n  return TXshCellColumn::setCell(row, newCell);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nbool TXshZeraryFxColumn::setCells(int row, int rowCount,\n                                  const TXshCell cells[]) {\n  std::vector<TXshCell> newCells;\n  bool isEmptyColumn = isEmpty() && getZeraryColumnFx()->getZeraryFx() == 0;\n  int i;\n  for (i = 0; i < rowCount; i++) {\n    if (isEmptyColumn) {\n      if (Preferences::instance()->isImplicitHoldEnabled() &&\n          cells[i].getFrameId().isEmptyFrame())\n        newCells.push_back(TXshCell(0, cells[i].getFrameId()));\n      else\n        newCells.push_back(TXshCell(m_zeraryFxLevel, cells[i].getFrameId()));\n    } else\n      newCells.push_back(cells[i]);\n  }\n  \/\/ Sto settando delle celle in una colonna nuova, devo settare anche\n  \/\/ l'effetto.\n  if (isEmptyColumn) {\n    i = 0;\n    while (i < rowCount && cells[i].isEmpty()) i++;\n    if (i >= rowCount) return false;\n    TXshZeraryFxLevel *fxLevel =\n        dynamic_cast<TXshZeraryFxLevel *>(cells[i].m_level.getPointer());\n    TXshZeraryFxColumn *fxColumn = fxLevel->getColumn();\n    m_zeraryColumnFx->setZeraryFx(fxColumn->getZeraryColumnFx()->getZeraryFx());\n  }\n  return TXshCellColumn::setCells(row, rowCount, &newCells[0]);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid TXshZeraryFxColumn::loadData(TIStream &is) {\n  TPersist *p = 0;\n  is >> p;\n  if (!p) return;\n\n  TZeraryColumnFx *fx = dynamic_cast<TZeraryColumnFx *>(p);\n  fx->addRef();\n  if (m_zeraryColumnFx) {\n    m_zeraryColumnFx->setColumn(0);\n    m_zeraryColumnFx->release();\n  }\n  m_zeraryColumnFx = fx;\n  m_zeraryColumnFx->setColumn(this);\n\n  int r0, r1;\n  bool touched = false;\n  TXshCell cell(m_zeraryFxLevel, TFrameId(1));\n  std::string tagName;\n  while (is.matchTag(tagName)) {\n    if (tagName == \"status\") {\n      int status;\n      is >> status;\n      setStatusWord(status);\n    } else if (tagName == \"cells\") {\n      while (is.matchTag(tagName)) {\n        if (tagName == \"cell\") {\n          if (!touched) {\n            touched = true;\n            if (getRange(r0, r1)) removeCells(r0, r1 - r0 + 1);\n          }\n          int r, n;\n          is >> r >> n;\n          if (is.getTagAttribute(\"stopframe\") == \"yes\")\n            cell.m_frameId = TFrameId::STOP_FRAME;\n          else\n            cell.m_frameId = 1;\n          for (int i = 0; i < n; i++) setCell(r++, cell);\n        } else\n          throw TException(\"expected <cell>\");\n        is.closeChild();\n      }\n    } else if (loadCellMarks(tagName, is)) {\n      \/\/ do nothing\n    } else\n      throw TException(\"expected <status> or <cells>\");\n    is.closeChild();\n  }\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid TXshZeraryFxColumn::saveData(TOStream &os) {\n  os << m_zeraryColumnFx;\n  os.child(\"status\") << getStatusWord();\n  int r0, r1;\n  if (getRange(r0, r1)) {\n    os.openChild(\"cells\");\n    for (int r = r0; r <= r1; r++) {\n      TXshCell cell = getCell(r, false);\n      if (cell.isEmpty()) continue;\n      int fnum           = cell.m_frameId.getNumber();\n      if (fnum > 1) fnum = 1;  \/\/ Should always be 1 unless it's stopframe\n      int n              = 1;\n\n      if (r < r1) {\n        TXshCell cell2 = getCell(r + 1, false);\n        if (!cell2.isEmpty()) {\n          int fnum2            = cell2.m_frameId.getNumber();\n          if (fnum2 > 1) fnum2 = 1;  \/\/ Should always be 1 unless it's stopframe\n          if (fnum == fnum2) {\n            n++;\n            for (;;) {\n              if (r + n > r1) break;\n              cell2 = getCell(r + n, false);\n              if (cell2.isEmpty()) break;\n              fnum2 = cell2.m_frameId.getNumber();\n              if (fnum2 > 1)\n                fnum2 = 1;  \/\/ Should always be 1 unless it's stopframe\n              if (fnum != fnum2) break;\n              n++;\n            }\n          }\n        }\n      }\n      std::map<std::string, std::string> attr;\n      if (cell.m_frameId.isStopFrame()) attr[\"stopframe\"] = \"yes\";\n      os.openChild(\"cell\", attr);\n      os << r << n;\n      os.closeChild();\n      r += n - 1;\n    }\n    os.closeChild();\n  }\n  \/\/ cell marks\n  saveCellMarks(os);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nPERSIST_IDENTIFIER(TXshZeraryFxColumn, \"zeraryFxColumn\")\n","avg_line_length":32.4853556485,"max_line_length":80,"alphanum_fraction":0.5414734673,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":134,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\n#include \"VMStack.hpp\"\n\nvm_stack_t::vm_stack_t() {}\n\nvm_stack_t::~vm_stack_t()\n{\n\tfor( auto & val : m_vec ) {\n\t\tVAR_DREF( val );\n\t}\n}","avg_line_length":12.1818181818,"max_line_length":28,"alphanum_fraction":0.6194029851,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5490,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":3.0,"content":"\/*\n * Copyright 2016 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef __STDC_FORMAT_MACROS\n#define __STDC_FORMAT_MACROS 1\n#endif\n\n#include <cstdio>\n#include <cinttypes>\n\n#include <string>\n\n#include <glog\/logging.h>\n\n#include <folly\/Format.h>\n#include <folly\/portability\/GFlags.h>\n\n#include <folly\/detail\/FingerprintPolynomial.h>\n\nusing namespace folly;\nusing namespace folly::detail;\n\n\/\/ The defaults were generated by a separate program that requires the\n\/\/ NTL (Number Theory Library) from http:\/\/www.shoup.net\/ntl\/\n\/\/\n\/\/ Briefly: randomly generate a polynomial of degree D, test for\n\/\/ irreducibility, repeat until you find an irreducible polynomial\n\/\/ (roughly 1\/D of all polynomials of degree D are irreducible, so\n\/\/ this will succeed in D\/2 tries on average; D is small (64..128) so\n\/\/ this simple method works well)\n\/\/\n\/\/ DO NOT REPLACE THE POLYNOMIALS USED, EVER, as that would change the value\n\/\/ of every single fingerprint in existence.\nDEFINE_int64(poly64, 0xbf3736b51869e9b7,\n             \"Generate 64-bit tables using this polynomial\");\nDEFINE_int64(poly96_m, 0x51555cb0aa8d39c3,\n             \"Generate 96-bit tables using this polynomial \"\n             \"(most significant 64 bits)\");\nDEFINE_int32(poly96_l, 0xb679ec37,\n             \"Generate 96-bit tables using this polynomial \"\n             \"(least significant 32 bits)\");\nDEFINE_int64(poly128_m, 0xc91bff9b8768b51b,\n             \"Generate 128-bit tables using this polynomial \"\n             \"(most significant 64 bits)\");\nDEFINE_int64(poly128_l, 0x8c5d5853bd77b0d3,\n             \"Generate 128-bit tables using this polynomial \"\n             \"(least significant 64 bits)\");\nDEFINE_string(install_dir, \".\",\n              \"Direectory to place output files in\");\nDEFINE_string(fbcode_dir, \"\", \"fbcode directory (ignored)\");\n\nnamespace {\n\ntemplate <int DEG>\nvoid computeTables(FILE* file, const FingerprintPolynomial<DEG>& poly) {\n  uint64_t table[8][256][FingerprintPolynomial<DEG>::size()];\n  \/\/ table[i][q] is Q(X) * X^(k+8*i) mod P(X),\n  \/\/ where k is the number of bits in the fingerprint (and deg(P)) and\n  \/\/ Q(X) = q7*X^7 + q6*X^6 + ... + q1*X + q0 is a degree-7 polyonomial\n  \/\/ whose coefficients are the bits of q.\n  for (int x = 0; x < 256; x++) {\n    FingerprintPolynomial<DEG> t;\n    t.setHigh8Bits(x);\n    for (int i = 0; i < 8; i++) {\n      t.mulXkmod(8, poly);\n      t.write(&(table[i][x][0]));\n    }\n  }\n\n  \/\/ Write the actual polynomial used; this isn't needed during fast\n  \/\/ fingerprint calculation, but it's useful for reference and unittesting.\n  uint64_t poly_val[FingerprintPolynomial<DEG>::size()];\n  poly.write(poly_val);\n  CHECK_ERR(fprintf(file,\n      \"template <>\\n\"\n      \"const uint64_t FingerprintTable<%d>::poly[%d] = {\",\n      DEG+1, FingerprintPolynomial<DEG>::size()));\n  for (int j = 0; j < FingerprintPolynomial<DEG>::size(); j++) {\n    CHECK_ERR(fprintf(file, \"%s%\" PRIu64 \"LU\", j ? \", \" : \"\", poly_val[j]));\n  }\n  CHECK_ERR(fprintf(file, \"};\\n\\n\"));\n\n  \/\/ Write the tables.\n  CHECK_ERR(fprintf(file,\n      \"template <>\\n\"\n      \"const uint64_t FingerprintTable<%d>::table[8][256][%d] = {\\n\",\n      DEG+1, FingerprintPolynomial<DEG>::size()));\n  for (int i = 0; i < 8; i++) {\n    CHECK_ERR(fprintf(file,\n        \"  \/\/ Table %d\"\n        \"\\n\"\n        \"  {\\n\", i));\n    for (int x = 0; x < 256; x++) {\n      CHECK_ERR(fprintf(file, \"    {\"));\n      for (int j = 0; j < FingerprintPolynomial<DEG>::size(); j++) {\n        CHECK_ERR(fprintf(\n          file, \"%s%\" PRIu64 \"LU\", (j ? \", \" : \"\"), table[i][x][j]));\n      }\n      CHECK_ERR(fprintf(file, \"},\\n\"));\n    }\n    CHECK_ERR(fprintf(file, \"  },\\n\"));\n  }\n  CHECK_ERR(fprintf(file, \"\\n};\\n\\n\"));\n}\n\n}  \/\/ namespace\n\nint main(int argc, char *argv[]) {\n  gflags::ParseCommandLineFlags(&argc, &argv, true);\n  google::InitGoogleLogging(argv[0]);\n\n  std::string name = folly::format(\"{}\/{}\", FLAGS_install_dir,\n                                   \"FingerprintTables.cpp\").str();\n  FILE* file = fopen(name.c_str(), \"w\");\n  PCHECK(file);\n\n  CHECK_ERR(fprintf(file,\n      \"\/**\\n\"\n      \" * Fingerprint tables for 64-, 96-, and 128-bit Rabin fingerprints.\\n\"\n      \" *\\n\"\n      \" * AUTOMATICALLY GENERATED.  DO NOT EDIT.\\n\"\n      \" *\/\\n\"\n      \"\\n\"\n      \"#include <folly\/Fingerprint.h>\\n\"\n      \"\\n\"\n      \"namespace folly {\\n\"\n      \"namespace detail {\\n\"\n      \"\\n\"));\n\n  FingerprintPolynomial<63> poly64((const uint64_t*)&FLAGS_poly64);\n  computeTables(file, poly64);\n\n  uint64_t poly96_val[2];\n  poly96_val[0] = (uint64_t)FLAGS_poly96_m;\n  poly96_val[1] = (uint64_t)FLAGS_poly96_l << 32;\n  FingerprintPolynomial<95> poly96(poly96_val);\n  computeTables(file, poly96);\n\n  uint64_t poly128_val[2];\n  poly128_val[0] = (uint64_t)FLAGS_poly128_m;\n  poly128_val[1] = (uint64_t)FLAGS_poly128_l;\n  FingerprintPolynomial<127> poly128(poly128_val);\n  computeTables(file, poly128);\n\n  CHECK_ERR(fprintf(file,\n      \"}  \/\/ namespace detail\\n\"\n      \"}  \/\/ namespace folly\\n\"));\n  CHECK_ERR(fclose(file));\n\n  return 0;\n}\n","avg_line_length":33.2727272727,"max_line_length":77,"alphanum_fraction":0.6453551913,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":914,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <fstream>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n\n\nvoid DetectingCycles(std::vector<int> const &line)\n{\n    \/\/TODO\n}\n\nint main(int argc, char *argv[])\n{\n    if (argc != 2) {\n        std::cerr << \"usage: .\/detecting_cycles <filename>\" << std::endl;\n        return -1;\n    }\n\n    std::ifstream file(argv[1]); \/\/get filename and open\n    if (file.is_open()) {\n        std::string line;\n\n        while (std::getline(file, line)) { \/\/read line by line\n            std::vector<int> v;\n            std::stringstream ss(line);\n            std::string tmp;\n            \/\/token -> convert -> push back\n            while (std::getline(ss, tmp, ' ')) {\n                v.push_back(atoi(tmp.c_str()));\n            }\n            DetectingCycles(v);\n        }\n    } else {\n        std::cerr << \"could not open file: \" << argv[1] << std::endl;\n        return -1;\n    }\n    return 0;\n}\n","avg_line_length":22.85,"max_line_length":73,"alphanum_fraction":0.5142231947,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2035,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include<iostream>\r\nusing namespace std;\r\n\r\nclass Node\r\n{\r\n\tprivate:\r\n\t\tint val;\r\n\t\tNode *nextNode;\r\n\t\r\n\tpublic:\r\n\t\tvoid setVal(int v)\r\n\t\t{\r\n\t\t\tval = v;\r\n\t\t}\r\n\t\tint getVal()\r\n\t\t{\r\n\t\t\treturn val;\r\n\t\t}\r\n\t\t\r\n\t\tvoid setNextNode(Node *next)\r\n\t\t{\r\n\t\t\tnextNode = next;\r\n\t\t}\r\n\t\tNode* getNextNode()\r\n\t\t{\r\n\t\t\treturn nextNode;\r\n\t\t}\r\n\t\t\r\n};\r\n\r\nclass LList\r\n{\r\n\tprivate:\r\n\t\tNode *head;\r\n\t\tNode *last;\r\n\t\tNode *current;\r\n\t\tint size;\r\n\t\r\n\tpublic:\r\n\t\t\r\n\t\tLList()\r\n\t\t{\r\n\t\t\thead = new Node();\r\n\t\t\tcurrent = head;\r\n\t\t\tlast = head;\r\n\t\t\tsize = 0;\r\n\t\t}\r\n\t\t\r\n\t\tvoid addToEndOfList(int v)\r\n\t\t{\r\n\t\t\t\/\/create a new node object\r\n\t\t\tNode *temp = new Node();\r\n\t\t\ttemp->setVal(v);\r\n\t\t\ttemp->setNextNode(NULL);\r\n\t\t\t\r\n\t\t\t\/\/attach it to the list\r\n\t\t\tlast->setNextNode(temp);\r\n\t\t\tlast = temp;\r\n\t\t\tsize++;\r\n\t\t}\r\n\t\t\r\n\t\tvoid addNodeToCurrent(int v)\r\n\t\t{\r\n\t\t\tNode *tempNode = new Node();\r\n\t\t\ttempNode->setVal(v);\r\n\t\t\t\r\n\t\t\ttempNode->setNextNode(current->getNextNode()); \r\n\t\t\tcurrent->setNextNode(tempNode);\r\n\t\t\tcurrent = tempNode;\r\n\t\t\t\r\n\t\t\tsize++;\r\n\t\t\t\/\/List is empty - remember our head node is a dummy\r\n\t\t\t\/\/if it is inserted somewhere in the middle of list\r\n\t\t\t\/\/current is at the end of the list\r\n\t\t}\r\n\t\t\r\n\t\tvoid printList()\r\n\t\t{\r\n\t\t\tNode *TCurrent = head->getNextNode();\r\n\t\t\tfor(int i=0; i<size; i++)\r\n\t\t\t{\r\n\t\t\t\tcout<<TCurrent->getVal()<<\" \";\r\n\t\t\t\tTCurrent = TCurrent->getNextNode();\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tvoid moveCurrentToLast()\r\n\t\t{\r\n\t\t\tif(size!=0)\r\n\t\t\t{\r\n\t\t\t\twhile(current->getNextNode() != NULL)\r\n\t\t\t\t{\r\n\t\t\t\t\tcurrent = current->getNextNode();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tvoid moveCurrentToFirst()\r\n\t\t{\r\n\t\t\tif(size!=0)\r\n\t\t\t{\r\n\t\t\t\tcurrent = head->getNextNode();\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tvoid moveCurrentToHead()\r\n\t\t{\r\n\t\t\tcurrent = head;\r\n\t\t}\r\n};\r\n\r\nint main()\r\n{\r\n\tLList myList;\r\n\tmyList.addToEndOfList(10);\r\n\tmyList.addToEndOfList(20);\r\n\tmyList.addToEndOfList(30);\r\n\tmyList.addToEndOfList(40);\r\n\tmyList.addToEndOfList(50);\r\n\t\r\n\tmyList.addNodeToCurrent(5);\r\n\tmyList.addNodeToCurrent(8);\r\n\t\r\n\tmyList.moveCurrentToHead();\r\n\tmyList.addNodeToCurrent(4);\r\n\t\r\n\tmyList.printList();\r\n\t\r\n}","avg_line_length":15.7751937984,"max_line_length":55,"alphanum_fraction":0.5626535627,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1352,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n * Copyright 2016 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <thpp\/cuda\/Storage.h>\n\nnamespace thpp {\n\nnamespace detail {\n\nCudaIOBufAllocator::CudaIOBufAllocator(folly::IOBuf&& iob)\n  : iob_(std::move(iob)) { }\n\ncudaError_t CudaIOBufAllocator::malloc(\n    THCState* state, void** ptr, long size) {\n  LOG(FATAL) << \"CudaIOBufAllocator::malloc should never be called\";\n  return cudaSuccess;  \/\/ not reached\n}\n\ncudaError_t CudaIOBufAllocator::realloc(\n    THCState* state, void** ptr, long oldSize, long newSize) {\n  LOG(FATAL) << \"CudaIOBufAllocator::realloc should never be called\";\n  return cudaSuccess;  \/\/ not reached\n}\n\ncudaError_t CudaIOBufAllocator::free(THCState* stat, void* ptr) {\n  CHECK_EQ(ptr, iob_.writableData());\n  delete this;\n  return cudaSuccess;\n}\n\n}  \/\/ namespace detail\n\n}  \/\/ namespaces\n","avg_line_length":28.7659574468,"max_line_length":75,"alphanum_fraction":0.7270710059,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1401,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":305.0,"content":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <locale>\n\n\/\/ template <> class codecvt<char32_t, char8_t, mbstate_t>\n\n\/\/ result out(stateT& state,\n\/\/            const internT* from, const internT* from_end, const internT*& from_next,\n\/\/            externT* to, externT* to_end, externT*& to_next) const;\n\n\/\/ UNSUPPORTED: c++03, c++11, c++14, c++17\n\n\/\/ C++20 codecvt specializations for char8_t are not yet implemented:\n\/\/ UNSUPPORTED: libc++\n\n#include <cassert>\n#include <locale>\n\nint main(int, char**) {\n  using F = std::codecvt<char32_t, char8_t, std::mbstate_t>;\n  const F& f = std::use_facet<F>(std::locale::classic());\n  F::intern_type from[9] = {'s', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't'};\n  F::extern_type to[9] = {0};\n  std::mbstate_t mbs = {};\n  const F::intern_type* from_next = nullptr;\n  F::extern_type* to_next = nullptr;\n  F::result r = f.out(mbs, from, from + 9, from_next, to, to + 9, to_next);\n  assert(r == F::ok);\n  assert(from_next - from == 9);\n  assert(to_next - to == 9);\n  for (unsigned i = 0; i < 9; ++i)\n    assert(to[i] == from[i]);\n  return 0;\n}\n","avg_line_length":34.1707317073,"max_line_length":86,"alphanum_fraction":0.5553176303,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":458,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/**\n * Copyright 2017 Jacques Florence\n * All rights reserved.\n * See License.txt file\n *\n *\/\n\n\n\n#include \"squareMaxTempEstimator.h\"\n\n#include <scheduler\/system.h>\n#include <scheduler\/processor.h>\n\nusing namespace RlScheduler;\n\nSquareMaxTempEstimator::SquareMaxTempEstimator() :\n\tproc(Scheduler::System::getInstance()->getProc())\n{\n}\n\ndouble SquareMaxTempEstimator::getMaximumTemperature()\n{\n\tconst double temp = proc->getTemperature();\n\treturn temp*temp;\n}\n","avg_line_length":16.962962963,"max_line_length":54,"alphanum_fraction":0.7489082969,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":31599,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Naumen","Condor-1.1","MS-PL"],"max_stars_count":1.0,"content":"\/*\n * ***** BEGIN GPL LICENSE BLOCK *****\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.\n * All rights reserved.\n *\n * The Original Code is: all of this file.\n *\n * Contributor(s): none yet.\n *\n * ***** END GPL LICENSE BLOCK *****\n * Camera in the gameengine. Cameras are also used for views.\n *\/\n\n\/** \\file gameengine\/Ketsji\/KX_Camera.cpp\n *  \\ingroup ketsji\n *\/\n\n#include \"KX_Camera.h\"\n\n#include \"GPU_glew.h\"\n#include \"GPU_matrix.h\"\n#include \"GPU_viewport.h\"\n\n#include \"KX_Globals.h\"\n#include \"KX_PyMath.h\"\n#include \"RAS_ICanvas.h\"\n\nKX_Camera::KX_Camera(void *sgReplicationInfo,\n                     SG_Callbacks callbacks,\n                     const RAS_CameraData &camdata,\n                     bool frustum_culling,\n                     bool delete_node)\n    : KX_GameObject(sgReplicationInfo, callbacks),\n      m_camdata(camdata),\n      m_gpuViewport(nullptr),  \/\/ eevee\n      m_dirty(true),\n      m_normalized(false),\n      m_frustum_culling(frustum_culling),\n      m_set_projection_matrix(false),\n      m_delete_node(delete_node),\n      m_lodDistanceFactor(1.0f),\n      m_showDebugCameraFrustum(false)\n{\n  \/\/ setting a name would be nice...\n  m_name = \"cam\";\n  m_projection_matrix.setIdentity();\n  m_modelview_matrix.setIdentity();\n}\n\nKX_Camera::~KX_Camera()\n{\n  RemoveGPUViewport();\n  if (m_delete_node && m_pSGNode) {\n    \/\/ for shadow camera, avoids memleak\n    delete m_pSGNode;\n    m_pSGNode = nullptr;\n  }\n}\n\nGPUViewport *KX_Camera::GetGPUViewport()\n{\n  if (!m_gpuViewport) {\n    m_gpuViewport = GPU_viewport_create();\n  }\n  return m_gpuViewport;\n}\n\nvoid KX_Camera::RemoveGPUViewport()\n{\n  if (m_gpuViewport && m_gpuViewport != GetScene()->GetCurrentGPUViewport()) {\n    GPU_viewport_free(m_gpuViewport);\n    m_gpuViewport = nullptr;\n  }\n}\n\nCValue *KX_Camera::GetReplica()\n{\n  KX_Camera *replica = new KX_Camera(*this);\n\n  \/\/ this will copy properties and so on...\n  replica->ProcessReplica();\n\n  return replica;\n}\n\nvoid KX_Camera::ProcessReplica()\n{\n  KX_GameObject::ProcessReplica();\n  \/\/ replicated camera are always registered in the scene\n  m_delete_node = false;\n}\n\nMT_Transform KX_Camera::GetWorldToCamera() const\n{\n  MT_Transform camtrans;\n  camtrans.invert(MT_Transform(NodeGetWorldPosition(), NodeGetWorldOrientation()));\n\n  return camtrans;\n}\n\nMT_Transform KX_Camera::GetCameraToWorld() const\n{\n  return MT_Transform(NodeGetWorldPosition(), NodeGetWorldOrientation());\n}\n\n\/**\n * Sets the projection matrix that is used by the rasterizer.\n *\/\nvoid KX_Camera::SetProjectionMatrix(const MT_Matrix4x4 &mat)\n{\n  m_projection_matrix = mat;\n  m_dirty = true;\n  m_set_projection_matrix = true;\n}\n\n\/**\n * Sets the modelview matrix that is used by the rasterizer.\n *\/\nvoid KX_Camera::SetModelviewMatrix(const MT_Matrix4x4 &mat)\n{\n  m_modelview_matrix = mat;\n  m_dirty = true;\n}\n\n\/**\n * Gets the projection matrix that is used by the rasterizer.\n *\/\nconst MT_Matrix4x4 &KX_Camera::GetProjectionMatrix() const\n{\n  return m_projection_matrix;\n}\n\n\/**\n * Gets the modelview matrix that is used by the rasterizer.\n *\/\nconst MT_Matrix4x4 &KX_Camera::GetModelviewMatrix() const\n{\n  return m_modelview_matrix;\n}\n\nbool KX_Camera::hasValidProjectionMatrix() const\n{\n  return m_set_projection_matrix;\n}\n\nvoid KX_Camera::InvalidateProjectionMatrix(bool valid)\n{\n  m_set_projection_matrix = valid;\n}\n\n\/**\n * These getters retrieve the clip data and the focal length\n *\/\nfloat KX_Camera::GetLens() const\n{\n  return m_camdata.m_lens;\n}\n\nfloat KX_Camera::GetScale() const\n{\n  return m_camdata.m_scale;\n}\n\n\/**\n * Gets the horizontal size of the sensor - for camera matching.\n *\/\nfloat KX_Camera::GetSensorWidth() const\n{\n  return m_camdata.m_sensor_x;\n}\n\n\/**\n * Gets the vertical size of the sensor - for camera matching.\n *\/\nfloat KX_Camera::GetSensorHeight() const\n{\n  return m_camdata.m_sensor_y;\n}\n\/** Gets the mode FOV is calculating from sensor dimensions *\/\nshort KX_Camera::GetSensorFit() const\n{\n  return m_camdata.m_sensor_fit;\n}\n\n\/**\n * Gets the horizontal shift of the sensor - for camera matching.\n *\/\nfloat KX_Camera::GetShiftHorizontal() const\n{\n  return m_camdata.m_shift_x;\n}\n\n\/**\n * Gets the vertical shift of the sensor - for camera matching.\n *\/\nfloat KX_Camera::GetShiftVertical() const\n{\n  return m_camdata.m_shift_y;\n}\n\nfloat KX_Camera::GetCameraNear() const\n{\n  return m_camdata.m_clipstart;\n}\n\nfloat KX_Camera::GetCameraFar() const\n{\n  return m_camdata.m_clipend;\n}\n\nfloat KX_Camera::GetFocalLength() const\n{\n  return m_camdata.m_focallength;\n}\n\nRAS_CameraData *KX_Camera::GetCameraData()\n{\n  return &m_camdata;\n}\n\nvoid KX_Camera::SetShowCameraFrustum(bool show)\n{\n  m_showDebugCameraFrustum = show;\n}\n\nbool KX_Camera::GetShowCameraFrustum() const\n{\n  return m_showDebugCameraFrustum;\n}\n\nfloat KX_Camera::GetLodDistanceFactor() const\n{\n  return m_lodDistanceFactor;\n}\n\nvoid KX_Camera::SetLodDistanceFactor(float lodfactor)\n{\n  m_lodDistanceFactor = lodfactor;\n}\n\nvoid KX_Camera::ExtractFrustum()\n{\n  if (m_dirty) {\n    m_frustum = SG_Frustum(m_projection_matrix * m_modelview_matrix);\n    m_dirty = false;\n  }\n}\n\nconst SG_Frustum &KX_Camera::GetFrustum()\n{\n  ExtractFrustum();\n  return m_frustum;\n}\n\nbool KX_Camera::GetFrustumCulling() const\n{\n  return m_frustum_culling;\n}\n\nvoid KX_Camera::EnableViewport(bool viewport)\n{\n  InvalidateProjectionMatrix(false);  \/\/ We need to reset projection matrix\n  m_camdata.m_viewport = viewport;\n}\n\nvoid KX_Camera::SetViewport(int left, int bottom, int right, int top)\n{\n  m_camdata.m_viewportleft = left;\n  m_camdata.m_viewportbottom = bottom;\n  m_camdata.m_viewportright = right;\n  m_camdata.m_viewporttop = top;\n}\n\nbool KX_Camera::GetViewport() const\n{\n  return m_camdata.m_viewport;\n}\n\nint KX_Camera::GetViewportLeft() const\n{\n  return m_camdata.m_viewportleft;\n}\n\nint KX_Camera::GetViewportBottom() const\n{\n  return m_camdata.m_viewportbottom;\n}\n\nint KX_Camera::GetViewportRight() const\n{\n  return m_camdata.m_viewportright;\n}\n\nint KX_Camera::GetViewportTop() const\n{\n  return m_camdata.m_viewporttop;\n}\n\n#ifdef WITH_PYTHON\n\/\/----------------------------------------------------------------------------\n\/\/ Python\n\nPyMethodDef KX_Camera::Methods[] = {\n    KX_PYMETHODTABLE(KX_Camera, sphereInsideFrustum),\n    KX_PYMETHODTABLE_O(KX_Camera, boxInsideFrustum),\n    KX_PYMETHODTABLE_O(KX_Camera, pointInsideFrustum),\n    KX_PYMETHODTABLE_NOARGS(KX_Camera, getCameraToWorld),\n    KX_PYMETHODTABLE_NOARGS(KX_Camera, getWorldToCamera),\n    KX_PYMETHODTABLE(KX_Camera, setViewport),\n    KX_PYMETHODTABLE_NOARGS(KX_Camera, setOnTop),\n    KX_PYMETHODTABLE_O(KX_Camera, getScreenPosition),\n    KX_PYMETHODTABLE(KX_Camera, getScreenVect),\n    KX_PYMETHODTABLE(KX_Camera, getScreenRay),\n    {nullptr, nullptr}  \/\/ Sentinel\n};\n\nPyAttributeDef KX_Camera::Attributes[] = {\n\n    KX_PYATTRIBUTE_BOOL_RW(\"frustum_culling\", KX_Camera, m_frustum_culling),\n    KX_PYATTRIBUTE_RW_FUNCTION(\n        \"perspective\", KX_Camera, pyattr_get_perspective, pyattr_set_perspective),\n\n    KX_PYATTRIBUTE_RW_FUNCTION(\"lens\", KX_Camera, pyattr_get_lens, pyattr_set_lens),\n    KX_PYATTRIBUTE_RW_FUNCTION(\"fov\", KX_Camera, pyattr_get_fov, pyattr_set_fov),\n    KX_PYATTRIBUTE_RW_FUNCTION(\n        \"ortho_scale\", KX_Camera, pyattr_get_ortho_scale, pyattr_set_ortho_scale),\n    KX_PYATTRIBUTE_RW_FUNCTION(\"near\", KX_Camera, pyattr_get_near, pyattr_set_near),\n    KX_PYATTRIBUTE_RW_FUNCTION(\"far\", KX_Camera, pyattr_get_far, pyattr_set_far),\n    KX_PYATTRIBUTE_RW_FUNCTION(\"shift_x\", KX_Camera, pyattr_get_shift_x, pyattr_set_shift_x),\n    KX_PYATTRIBUTE_RW_FUNCTION(\"shift_y\", KX_Camera, pyattr_get_shift_y, pyattr_set_shift_y),\n    KX_PYATTRIBUTE_FLOAT_RW(\"lodDistanceFactor\", 0.0f, FLT_MAX, KX_Camera, m_lodDistanceFactor),\n\n    KX_PYATTRIBUTE_RW_FUNCTION(\n        \"useViewport\", KX_Camera, pyattr_get_use_viewport, pyattr_set_use_viewport),\n\n    KX_PYATTRIBUTE_RW_FUNCTION(\"projection_matrix\",\n                               KX_Camera,\n                               pyattr_get_projection_matrix,\n                               pyattr_set_projection_matrix),\n    KX_PYATTRIBUTE_RO_FUNCTION(\"modelview_matrix\", KX_Camera, pyattr_get_modelview_matrix),\n    KX_PYATTRIBUTE_RO_FUNCTION(\"camera_to_world\", KX_Camera, pyattr_get_camera_to_world),\n    KX_PYATTRIBUTE_RO_FUNCTION(\"world_to_camera\", KX_Camera, pyattr_get_world_to_camera),\n\n    \/* Grrr, functions for constants? *\/\n    KX_PYATTRIBUTE_RO_FUNCTION(\"INSIDE\", KX_Camera, pyattr_get_INSIDE),\n    KX_PYATTRIBUTE_RO_FUNCTION(\"OUTSIDE\", KX_Camera, pyattr_get_OUTSIDE),\n    KX_PYATTRIBUTE_RO_FUNCTION(\"INTERSECT\", KX_Camera, pyattr_get_INTERSECT),\n\n    KX_PYATTRIBUTE_NULL  \/\/ Sentinel\n};\n\nPyTypeObject KX_Camera::Type = {PyVarObject_HEAD_INIT(nullptr, 0) \"KX_Camera\",\n                                sizeof(PyObjectPlus_Proxy),\n                                0,\n                                py_base_dealloc,\n                                0,\n                                0,\n                                0,\n                                0,\n                                py_base_repr,\n                                0,\n                                &KX_GameObject::Sequence,\n                                &KX_GameObject::Mapping,\n                                0,\n                                0,\n                                0,\n                                nullptr,\n                                nullptr,\n                                0,\n                                Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,\n                                0,\n                                0,\n                                0,\n                                0,\n                                0,\n                                0,\n                                0,\n                                Methods,\n                                0,\n                                0,\n                                &KX_GameObject::Type,\n                                0,\n                                0,\n                                0,\n                                0,\n                                0,\n                                0,\n                                py_base_new};\n\nKX_PYMETHODDEF_DOC_VARARGS(KX_Camera,\n                           sphereInsideFrustum,\n                           \"sphereInsideFrustum(center, radius) -> Integer\\n\"\n                           \"\\treturns INSIDE, OUTSIDE or INTERSECT if the given sphere is\\n\"\n                           \"\\tinside\/outside\/intersects this camera's viewing frustum.\\n\\n\"\n                           \"\\tcenter = the center of the sphere (in world coordinates.)\\n\"\n                           \"\\tradius = the radius of the sphere\\n\\n\"\n                           \"\\tExample:\\n\"\n                           \"\\timport bge.logic\\n\\n\"\n                           \"\\tco = bge.logic.getCurrentController()\\n\"\n                           \"\\tcam = co.GetOwner()\\n\\n\"\n                           \"\\t# A sphere of radius 4.0 located at [x, y, z] = [1.0, 1.0, 1.0]\\n\"\n                           \"\\tif (cam.sphereInsideFrustum([1.0, 1.0, 1.0], 4) != cam.OUTSIDE):\\n\"\n                           \"\\t\\t# Sphere is inside frustum !\\n\"\n                           \"\\t\\t# Do something useful !\\n\"\n                           \"\\telse:\\n\"\n                           \"\\t\\t# Sphere is outside frustum\\n\")\n{\n  PyObject *pycenter;\n  float radius;\n  if (PyArg_ParseTuple(args, \"Of:sphereInsideFrustum\", &pycenter, &radius)) {\n    MT_Vector3 center;\n    if (PyVecTo(pycenter, center)) {\n      return PyLong_FromLong(GetFrustum().SphereInsideFrustum(center, radius)); \/* new ref *\/\n    }\n  }\n\n  PyErr_SetString(PyExc_TypeError,\n                  \"camera.sphereInsideFrustum(center, radius): KX_Camera, expected arguments: \"\n                  \"(center, radius)\");\n\n  return nullptr;\n}\n\nKX_PYMETHODDEF_DOC_O(\n    KX_Camera,\n    boxInsideFrustum,\n    \"boxInsideFrustum(box) -> Integer\\n\"\n    \"\\treturns INSIDE, OUTSIDE or INTERSECT if the given box is\\n\"\n    \"\\tinside\/outside\/intersects this camera's viewing frustum.\\n\\n\"\n    \"\\tbox = a list of the eight (8) corners of the box (in world coordinates.)\\n\\n\"\n    \"\\tExample:\\n\"\n    \"\\timport bge.logic\\n\\n\"\n    \"\\tco = bge.logic.getCurrentController()\\n\"\n    \"\\tcam = co.GetOwner()\\n\\n\"\n    \"\\tbox = []\\n\"\n    \"\\tbox.append([-1.0, -1.0, -1.0])\\n\"\n    \"\\tbox.append([-1.0, -1.0,  1.0])\\n\"\n    \"\\tbox.append([-1.0,  1.0, -1.0])\\n\"\n    \"\\tbox.append([-1.0,  1.0,  1.0])\\n\"\n    \"\\tbox.append([ 1.0, -1.0, -1.0])\\n\"\n    \"\\tbox.append([ 1.0, -1.0,  1.0])\\n\"\n    \"\\tbox.append([ 1.0,  1.0, -1.0])\\n\"\n    \"\\tbox.append([ 1.0,  1.0,  1.0])\\n\\n\"\n    \"\\tif (cam.boxInsideFrustum(box) != cam.OUTSIDE):\\n\"\n    \"\\t\\t# Box is inside\/intersects frustum !\\n\"\n    \"\\t\\t# Do something useful !\\n\"\n    \"\\telse:\\n\"\n    \"\\t\\t# Box is outside the frustum !\\n\")\n{\n  unsigned int num_points = PySequence_Size(value);\n  if (num_points != 8) {\n    PyErr_Format(PyExc_TypeError,\n                 \"camera.boxInsideFrustum(box): KX_Camera, expected eight (8) points, got %d\",\n                 num_points);\n    return nullptr;\n  }\n\n  std::array<MT_Vector3, 8> box;\n  for (unsigned int p = 0; p < 8; p++) {\n    PyObject *item = PySequence_GetItem(value, p); \/* new ref *\/\n    bool error = !PyVecTo(item, box[p]);\n    Py_DECREF(item);\n    if (error)\n      return nullptr;\n  }\n\n  return PyLong_FromLong(GetFrustum().BoxInsideFrustum(box)); \/* new ref *\/\n}\n\nKX_PYMETHODDEF_DOC_O(KX_Camera,\n                     pointInsideFrustum,\n                     \"pointInsideFrustum(point) -> Bool\\n\"\n                     \"\\treturns 1 if the given point is inside this camera's viewing frustum.\\n\\n\"\n                     \"\\tpoint = The point to test (in world coordinates.)\\n\\n\"\n                     \"\\tExample:\\n\"\n                     \"\\timport bge.logic\\n\\n\"\n                     \"\\tco = bge.logic.getCurrentController()\\n\"\n                     \"\\tcam = co.GetOwner()\\n\\n\"\n                     \"\\t# Test point [0.0, 0.0, 0.0]\"\n                     \"\\tif (cam.pointInsideFrustum([0.0, 0.0, 0.0])):\\n\"\n                     \"\\t\\t# Point is inside frustum !\\n\"\n                     \"\\t\\t# Do something useful !\\n\"\n                     \"\\telse:\\n\"\n                     \"\\t\\t# Box is outside the frustum !\\n\")\n{\n  MT_Vector3 point;\n  if (PyVecTo(value, point)) {\n    return PyLong_FromLong(GetFrustum().PointInsideFrustum(point)); \/* new ref *\/\n  }\n\n  PyErr_SetString(PyExc_TypeError,\n                  \"camera.pointInsideFrustum(point): KX_Camera, expected point argument.\");\n  return nullptr;\n}\n\nKX_PYMETHODDEF_DOC_NOARGS(KX_Camera,\n                          getCameraToWorld,\n                          \"getCameraToWorld() -> Matrix4x4\\n\"\n                          \"\\treturns the camera to world transformation matrix, as a list of four \"\n                          \"lists of four values.\\n\\n\"\n                          \"\\tie: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, \"\n                          \"0.0], [0.0, 0.0, 0.0, 1.0]])\\n\")\n{\n  return PyObjectFrom(MT_Matrix4x4(GetCameraToWorld())); \/* new ref *\/\n}\n\nKX_PYMETHODDEF_DOC_NOARGS(KX_Camera,\n                          getWorldToCamera,\n                          \"getWorldToCamera() -> Matrix4x4\\n\"\n                          \"\\treturns the world to camera transformation matrix, as a list of four \"\n                          \"lists of four values.\\n\\n\"\n                          \"\\tie: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, \"\n                          \"0.0], [0.0, 0.0, 0.0, 1.0]])\\n\")\n{\n  return PyObjectFrom(MT_Matrix4x4(GetWorldToCamera())); \/* new ref *\/\n}\n\nKX_PYMETHODDEF_DOC_VARARGS(KX_Camera,\n                           setViewport,\n                           \"setViewport(left, bottom, right, top)\\n\"\n                           \"Sets this camera's viewport\\n\")\n{\n  int left, bottom, right, top;\n  if (!PyArg_ParseTuple(args, \"iiii:setViewport\", &left, &bottom, &right, &top))\n    return nullptr;\n\n  SetViewport(left, bottom, right, top);\n  Py_RETURN_NONE;\n}\n\nKX_PYMETHODDEF_DOC_NOARGS(KX_Camera,\n                          setOnTop,\n                          \"setOnTop()\\n\"\n                          \"Sets this camera's viewport on top\\n\")\n{\n  GetScene()->SetCameraOnTop(this);\n  Py_RETURN_NONE;\n}\n\nPyObject *KX_Camera::pyattr_get_perspective(PyObjectPlus *self_v,\n                                            const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  return PyBool_FromLong(self->m_camdata.m_perspective);\n}\n\nint KX_Camera::pyattr_set_perspective(PyObjectPlus *self_v,\n                                      const KX_PYATTRIBUTE_DEF *attrdef,\n                                      PyObject *value)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  int param = PyObject_IsTrue(value);\n  if (param == -1) {\n    PyErr_SetString(PyExc_AttributeError,\n                    \"camera.perspective = bool: KX_Camera, expected True\/False or 0\/1\");\n    return PY_SET_ATTR_FAIL;\n  }\n\n  self->m_camdata.m_perspective = param;\n  self->InvalidateProjectionMatrix();\n  return PY_SET_ATTR_SUCCESS;\n}\n\nPyObject *KX_Camera::pyattr_get_lens(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  return PyFloat_FromDouble(self->m_camdata.m_lens);\n}\n\nint KX_Camera::pyattr_set_lens(PyObjectPlus *self_v,\n                               const KX_PYATTRIBUTE_DEF *attrdef,\n                               PyObject *value)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  float param = PyFloat_AsDouble(value);\n  if (param == -1) {\n    PyErr_SetString(PyExc_AttributeError,\n                    \"camera.lens = float: KX_Camera, expected a float greater than zero\");\n    return PY_SET_ATTR_FAIL;\n  }\n\n  self->m_camdata.m_lens = param;\n  self->m_set_projection_matrix = false;\n  return PY_SET_ATTR_SUCCESS;\n}\n\nPyObject *KX_Camera::pyattr_get_fov(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n\n  float lens = self->m_camdata.m_lens;\n  float width = self->m_camdata.m_sensor_x;\n  float fov = 2.0f * atanf(0.5f * width \/ lens);\n\n  return PyFloat_FromDouble(fov * MT_DEGS_PER_RAD);\n}\n\nint KX_Camera::pyattr_set_fov(PyObjectPlus *self_v,\n                              const KX_PYATTRIBUTE_DEF *attrdef,\n                              PyObject *value)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  float fov = PyFloat_AsDouble(value);\n  if (fov <= 0.0f) {\n    PyErr_SetString(PyExc_AttributeError,\n                    \"camera.fov = float: KX_Camera, expected a float greater than zero\");\n    return PY_SET_ATTR_FAIL;\n  }\n\n  fov *= MT_RADS_PER_DEG;\n  float width = self->m_camdata.m_sensor_x;\n  float lens = width \/ (2.0f * tanf(0.5f * fov));\n\n  self->m_camdata.m_lens = lens;\n  self->m_set_projection_matrix = false;\n  return PY_SET_ATTR_SUCCESS;\n}\n\nPyObject *KX_Camera::pyattr_get_ortho_scale(PyObjectPlus *self_v,\n                                            const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  return PyFloat_FromDouble(self->m_camdata.m_scale);\n}\n\nint KX_Camera::pyattr_set_ortho_scale(PyObjectPlus *self_v,\n                                      const KX_PYATTRIBUTE_DEF *attrdef,\n                                      PyObject *value)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  float param = PyFloat_AsDouble(value);\n  if (param == -1) {\n    PyErr_SetString(PyExc_AttributeError,\n                    \"camera.ortho_scale = float: KX_Camera, expected a float greater than zero\");\n    return PY_SET_ATTR_FAIL;\n  }\n\n  self->m_camdata.m_scale = param;\n  self->m_set_projection_matrix = false;\n  return PY_SET_ATTR_SUCCESS;\n}\n\nPyObject *KX_Camera::pyattr_get_near(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  return PyFloat_FromDouble(self->m_camdata.m_clipstart);\n}\n\nint KX_Camera::pyattr_set_near(PyObjectPlus *self_v,\n                               const KX_PYATTRIBUTE_DEF *attrdef,\n                               PyObject *value)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  float param = PyFloat_AsDouble(value);\n  if (param == -1) {\n    PyErr_SetString(PyExc_AttributeError,\n                    \"camera.near = float: KX_Camera, expected a float greater than zero\");\n    return PY_SET_ATTR_FAIL;\n  }\n\n  self->m_camdata.m_clipstart = param;\n  self->m_set_projection_matrix = false;\n  return PY_SET_ATTR_SUCCESS;\n}\n\nPyObject *KX_Camera::pyattr_get_far(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  return PyFloat_FromDouble(self->m_camdata.m_clipend);\n}\n\nint KX_Camera::pyattr_set_far(PyObjectPlus *self_v,\n                              const KX_PYATTRIBUTE_DEF *attrdef,\n                              PyObject *value)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  float param = PyFloat_AsDouble(value);\n  if (param == -1) {\n    PyErr_SetString(PyExc_AttributeError,\n                    \"camera.far = float: KX_Camera, expected a float greater than zero\");\n    return PY_SET_ATTR_FAIL;\n  }\n\n  self->m_camdata.m_clipend = param;\n  self->m_set_projection_matrix = false;\n  return PY_SET_ATTR_SUCCESS;\n}\n\nPyObject *KX_Camera::pyattr_get_shift_x(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  return PyFloat_FromDouble(self->m_camdata.m_shift_x);\n}\n\nint KX_Camera::pyattr_set_shift_x(PyObjectPlus *self_v,\n                                  const KX_PYATTRIBUTE_DEF *attrdef,\n                                  PyObject *value)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  float param = PyFloat_AsDouble(value);\n  if (param == -1) {\n    PyErr_SetString(PyExc_AttributeError,\n                    \"camera.shift_x = float: KX_Camera, expected a float greater than zero\");\n    return PY_SET_ATTR_FAIL;\n  }\n\n  self->m_camdata.m_shift_x = param;\n  self->m_set_projection_matrix = false;\n  return PY_SET_ATTR_SUCCESS;\n}\n\nPyObject *KX_Camera::pyattr_get_shift_y(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  return PyFloat_FromDouble(self->m_camdata.m_shift_y);\n}\n\nint KX_Camera::pyattr_set_shift_y(PyObjectPlus *self_v,\n                                  const KX_PYATTRIBUTE_DEF *attrdef,\n                                  PyObject *value)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  float param = PyFloat_AsDouble(value);\n  if (param == -1) {\n    PyErr_SetString(PyExc_AttributeError,\n                    \"camera.shift_y = float: KX_Camera, expected a float greater than zero\");\n    return PY_SET_ATTR_FAIL;\n  }\n\n  self->m_camdata.m_shift_y = param;\n  self->m_set_projection_matrix = false;\n  return PY_SET_ATTR_SUCCESS;\n}\n\nPyObject *KX_Camera::pyattr_get_use_viewport(PyObjectPlus *self_v,\n                                             const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  return PyBool_FromLong(self->GetViewport());\n}\n\nint KX_Camera::pyattr_set_use_viewport(PyObjectPlus *self_v,\n                                       const KX_PYATTRIBUTE_DEF *attrdef,\n                                       PyObject *value)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  int param = PyObject_IsTrue(value);\n  if (param == -1) {\n    PyErr_SetString(PyExc_AttributeError,\n                    \"camera.useViewport = bool: KX_Camera, expected True or False\");\n    return PY_SET_ATTR_FAIL;\n  }\n  self->EnableViewport((bool)param);\n  return PY_SET_ATTR_SUCCESS;\n}\n\nPyObject *KX_Camera::pyattr_get_projection_matrix(PyObjectPlus *self_v,\n                                                  const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  return PyObjectFrom(self->GetProjectionMatrix());\n}\n\nint KX_Camera::pyattr_set_projection_matrix(PyObjectPlus *self_v,\n                                            const KX_PYATTRIBUTE_DEF *attrdef,\n                                            PyObject *value)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  MT_Matrix4x4 mat;\n  if (!PyMatTo(value, mat))\n    return PY_SET_ATTR_FAIL;\n\n  self->SetProjectionMatrix(mat);\n  return PY_SET_ATTR_SUCCESS;\n}\n\nPyObject *KX_Camera::pyattr_get_modelview_matrix(PyObjectPlus *self_v,\n                                                 const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  return PyObjectFrom(MT_Matrix4x4(self->GetWorldToCamera()));\n}\n\nPyObject *KX_Camera::pyattr_get_camera_to_world(PyObjectPlus *self_v,\n                                                const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  return PyObjectFrom(MT_Matrix4x4(self->GetCameraToWorld()));\n}\n\nPyObject *KX_Camera::pyattr_get_world_to_camera(PyObjectPlus *self_v,\n                                                const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  KX_Camera *self = static_cast<KX_Camera *>(self_v);\n  return PyObjectFrom(MT_Matrix4x4(self->GetWorldToCamera()));\n}\n\nPyObject *KX_Camera::pyattr_get_INSIDE(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  return PyLong_FromLong(INSIDE);\n}\nPyObject *KX_Camera::pyattr_get_OUTSIDE(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  return PyLong_FromLong(OUTSIDE);\n}\nPyObject *KX_Camera::pyattr_get_INTERSECT(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef)\n{\n  return PyLong_FromLong(INTERSECT);\n}\n\nbool ConvertPythonToCamera(KX_Scene *scene,\n                           PyObject *value,\n                           KX_Camera **object,\n                           bool py_none_ok,\n                           const char *error_prefix)\n{\n  if (value == nullptr) {\n    PyErr_Format(PyExc_TypeError, \"%s, python pointer nullptr, should never happen\", error_prefix);\n    *object = nullptr;\n    return false;\n  }\n\n  if (value == Py_None) {\n    *object = nullptr;\n\n    if (py_none_ok) {\n      return true;\n    }\n    else {\n      PyErr_Format(PyExc_TypeError,\n                   \"%s, expected KX_Camera or a KX_Camera name, None is invalid\",\n                   error_prefix);\n      return false;\n    }\n  }\n\n  if (PyUnicode_Check(value)) {\n    std::string value_str = _PyUnicode_AsString(value);\n    *object = scene->GetCameraList()->FindValue(value_str);\n\n    if (*object) {\n      return true;\n    }\n    else {\n      PyErr_Format(PyExc_ValueError,\n                   \"%s, requested name \\\"%s\\\" did not match any KX_Camera in this scene\",\n                   error_prefix,\n                   _PyUnicode_AsString(value));\n      return false;\n    }\n  }\n\n  if (PyObject_TypeCheck(value, &KX_Camera::Type)) {\n    *object = static_cast<KX_Camera *> BGE_PROXY_REF(value);\n\n    \/* sets the error *\/\n    if (*object == nullptr) {\n      PyErr_Format(PyExc_SystemError, \"%s, \" BGE_PROXY_ERROR_MSG, error_prefix);\n      return false;\n    }\n\n    return true;\n  }\n\n  *object = nullptr;\n\n  if (py_none_ok) {\n    PyErr_Format(PyExc_TypeError, \"%s, expect a KX_Camera, a string or None\", error_prefix);\n  }\n  else {\n    PyErr_Format(PyExc_TypeError, \"%s, expect a KX_Camera or a string\", error_prefix);\n  }\n\n  return false;\n}\n\nKX_PYMETHODDEF_DOC_O(KX_Camera, getScreenPosition, \"getScreenPosition()\\n\")\n\n{\n  MT_Vector3 vect;\n  KX_GameObject *obj = nullptr;\n\n  if (!PyVecTo(value, vect)) {\n    PyErr_Clear();\n\n    if (ConvertPythonToGameObject(GetScene()->GetLogicManager(), value, &obj, false, \"\")) {\n      PyErr_Clear();\n      vect = MT_Vector3(obj->NodeGetWorldPosition());\n    }\n    else {\n      PyErr_SetString(PyExc_TypeError,\n                      \"Error in getScreenPosition. Expected a Vector3 or a KX_GameObject or a \"\n                      \"string for a name of a KX_GameObject\");\n      return nullptr;\n    }\n  }\n\n  GLint viewport[4];\n  GLfloat vec[3];\n  GLfloat win[3];\n  GLfloat modelmatrix[4][4];\n  GLfloat projmatrix[4][4];\n\n  MT_Matrix4x4 m_modelmatrix = MT_Matrix4x4(GetWorldToCamera());\n  MT_Matrix4x4 m_projmatrix = this->GetProjectionMatrix();\n\n  vect.getValue(vec);\n  m_modelmatrix.getValue((float *)modelmatrix);\n  m_projmatrix.getValue((float *)projmatrix);\n\n  KX_GetActiveEngine()->GetCanvas()->GetViewportArea().Pack(viewport);\n\n  GPU_matrix_project(vec, modelmatrix, projmatrix, viewport, win);\n\n  vect[0] = (win[0] - viewport[0]) \/ viewport[2];\n  vect[1] = (win[1] - viewport[1]) \/ viewport[3];\n\n  vect[1] = 1.0f - vect[1];  \/\/ to follow Blender window coordinate system (Top-Down)\n\n  PyObject *ret = PyTuple_New(2);\n  if (ret) {\n    PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(vect[0]));\n    PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(vect[1]));\n    return ret;\n  }\n\n  return nullptr;\n}\n\nKX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenVect, \"getScreenVect()\\n\")\n{\n  double x, y;\n  if (!PyArg_ParseTuple(args, \"dd:getScreenVect\", &x, &y))\n    return nullptr;\n\n  y = 1.0 - y;  \/\/ to follow Blender window coordinate system (Top-Down)\n\n  GLint viewport[4];\n  GLfloat vec[3];\n  GLfloat win[3];\n  GLfloat modelmatrix[4][4];\n  GLfloat projmatrix[4][4];\n\n  MT_Matrix4x4 m_modelmatrix = MT_Matrix4x4(GetWorldToCamera());\n  MT_Matrix4x4 m_projmatrix = this->GetProjectionMatrix();\n\n  m_modelmatrix.getValue((float *)modelmatrix);\n  m_projmatrix.getValue((float *)projmatrix);\n\n  KX_GetActiveEngine()->GetCanvas()->GetViewportArea().Pack(viewport);\n\n  vec[0] = x * viewport[2];\n  vec[1] = y * viewport[3];\n\n  vec[0] += viewport[0];\n  vec[1] += viewport[1];\n\n  vec[2] = 0.f;\n\n  GPU_matrix_unproject(vec, modelmatrix, projmatrix, viewport, win);\n\n  MT_Vector3 campos = NodeGetWorldPosition();\n  MT_Vector3 screenpos(win[0], win[1], win[2]);\n  MT_Vector3 vect = campos - screenpos;\n  vect.normalize();\n  return PyObjectFrom(vect);\n}\n\nKX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenRay, \"getScreenRay()\\n\")\n{\n  MT_Vector3 vect;\n  double x, y, dist;\n  char *propName = nullptr;\n\n  if (!PyArg_ParseTuple(args, \"ddd|s:getScreenRay\", &x, &y, &dist, &propName))\n    return nullptr;\n\n  PyObject *argValue = PyTuple_New(2);\n  PyTuple_SET_ITEM(argValue, 0, PyFloat_FromDouble(x));\n  PyTuple_SET_ITEM(argValue, 1, PyFloat_FromDouble(y));\n\n  if (!PyVecTo(PygetScreenVect(argValue), vect)) {\n    Py_DECREF(argValue);\n    PyErr_SetString(PyExc_TypeError,\n                    \"Error in getScreenRay. Invalid 2D coordinate. \"\n                    \"Expected a normalized 2D screen coordinate, \"\n                    \"a distance and an optional property argument\");\n    return nullptr;\n  }\n  Py_DECREF(argValue);\n\n  dist = -dist;\n  vect += NodeGetWorldPosition();\n\n  argValue = (propName ? PyTuple_New(3) : PyTuple_New(2));\n  if (argValue) {\n    PyTuple_SET_ITEM(argValue, 0, PyObjectFrom(vect));\n    PyTuple_SET_ITEM(argValue, 1, PyFloat_FromDouble(dist));\n    if (propName)\n      PyTuple_SET_ITEM(argValue, 2, PyUnicode_FromString(propName));\n\n    PyObject *ret = this->PyrayCastTo(argValue, nullptr);\n    Py_DECREF(argValue);\n    return ret;\n  }\n\n  return nullptr;\n}\n#endif\n","avg_line_length":30.8282926829,"max_line_length":99,"alphanum_fraction":0.6303680496,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10784,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT-0","Apache-2.0","CC-BY-4.0","MIT"],"max_stars_count":3.0,"content":"\/\/ STL includes\n#include <csignal>\n#include <iomanip>\n#include <clocale>\n\n\/\/ QT includes\n#include <QCoreApplication>\n\n\/\/ blackborder includes\n#include <blackborder\/BlackBorderProcessor.h>\n\n\/\/ grabber includes\n#include \"grabber\/V4L2Grabber.h\"\n\n\/\/ flatbuf includes\n#include <flatbufserver\/FlatBufferConnection.h>\n\n\/\/ hyperion-v4l2 includes\n#include \"ScreenshotHandler.h\"\n\n#include \"HyperionConfig.h\"\n#include <commandline\/Parser.h>\n\n\/\/ ssdp discover\n#include <ssdp\/SSDPDiscover.h>\n\nusing namespace commandline;\n\nint main(int argc, char** argv)\n{\n\tLogger *log = Logger::getInstance(\"V4L2GRABBER\");\n\tLogger::setLogLevel(Logger::WARNING);\n\n\tstd::cout\n\t\t<< \"hyperion-v4l2:\" << std::endl\n\t\t<< \"\\tVersion   : \" << HYPERION_VERSION << \" (\" << HYPERION_BUILD_ID << \")\" << std::endl\n\t\t<< \"\\tbuild time: \" << __DATE__ << \" \" << __TIME__ << std::endl;\n\n\tQCoreApplication app(argc, argv);\n\n\t\/\/ force the locale\n\tsetlocale(LC_ALL, \"C\");\n\tQLocale::setDefault(QLocale::c());\n\n\t\/\/ register the image type to use in signals\n\tqRegisterMetaType<Image<ColorRgb>>(\"Image<ColorRgb>\");\n\n\ttry\n\t{\n\t\t\/\/ create the option parser and initialize all parameters\n\t\tParser parser(\"V4L capture application for Hyperion.  Will automatically search a Hyperion server if -a option isn't used. Please note that if you have more than one server running it's more or less random which one will be used.\");\n\n\t\tOption             & argDevice              = parser.add<Option>       ('d', \"device\", \"The device to use, can be \/dev\/video0 [default: %1 (auto detected)]\", \"auto\");\n\t\tSwitchOption<VideoStandard> & argVideoStandard= parser.add<SwitchOption<VideoStandard>>('v', \"video-standard\", \"The used video standard. Valid values are PAL, NTSC, SECAM or no-change. [default: %1]\", \"no-change\");\n\t\tSwitchOption<PixelFormat> & argPixelFormat    = parser.add<SwitchOption<PixelFormat>>  (0x0, \"pixel-format\", \"The use pixel format. Valid values are YUYV, UYVY, RGB32, MJPEG or no-change. [default: %1]\", \"no-change\");\n\t\tIntOption          & argCropWidth           = parser.add<IntOption>    (0x0, \"crop-width\", \"Number of pixels to crop from the left and right sides of the picture before decimation [default: %1]\", \"0\");\n\t\tIntOption          & argCropHeight          = parser.add<IntOption>    (0x0, \"crop-height\", \"Number of pixels to crop from the top and the bottom of the picture before decimation [default: %1]\", \"0\");\n\t\tIntOption          & argCropLeft            = parser.add<IntOption>    (0x0, \"crop-left\", \"Number of pixels to crop from the left of the picture before decimation (overrides --crop-width)\");\n\t\tIntOption          & argCropRight           = parser.add<IntOption>    (0x0, \"crop-right\", \"Number of pixels to crop from the right of the picture before decimation (overrides --crop-width)\");\n\t\tIntOption          & argCropTop             = parser.add<IntOption>    (0x0, \"crop-top\", \"Number of pixels to crop from the top of the picture before decimation (overrides --crop-height)\");\n\t\tIntOption          & argCropBottom          = parser.add<IntOption>    (0x0, \"crop-bottom\", \"Number of pixels to crop from the bottom of the picture before decimation (overrides --crop-height)\");\n\t\tIntOption          & argSizeDecimation      = parser.add<IntOption>    ('s', \"size-decimator\", \"Decimation factor for the output size [default=%1]\", \"6\", 1);\n\t\tBooleanOption      & argScreenshot          = parser.add<BooleanOption>(0x0, \"screenshot\", \"Take a single screenshot, save it to file and quit\");\n\n\t\tBooleanOption      & argSignalDetection     = parser.add<BooleanOption>('s', \"signal-detection-disabled\", \"disable signal detection\");\n\t\tDoubleOption       & argSignalThreshold     = parser.add<DoubleOption> ('t', \"signal-threshold\", \"The signal threshold for detecting the presence of a signal. Value should be between 0.0 and 1.0.\", QString(), 0.0, 1.0);\n\t\tDoubleOption       & argRedSignalThreshold  = parser.add<DoubleOption> (0x0, \"red-threshold\", \"The red signal threshold. Value should be between 0.0 and 1.0. (overrides --signal-threshold)\");\n\t\tDoubleOption       & argGreenSignalThreshold= parser.add<DoubleOption> (0x0, \"green-threshold\", \"The green signal threshold. Value should be between 0.0 and 1.0. (overrides --signal-threshold)\");\n\t\tDoubleOption       & argBlueSignalThreshold = parser.add<DoubleOption> (0x0, \"blue-threshold\", \"The blue signal threshold. Value should be between 0.0 and 1.0. (overrides --signal-threshold)\");\n\n\t\tDoubleOption       & argSignalHorizontalMin = parser.add<DoubleOption> (0x0, \"signal-horizontal-min\", \"area for signal detection - horizontal minimum offset value. Values between 0.0 and 1.0\");\n\t\tDoubleOption       & argSignalVerticalMin   = parser.add<DoubleOption> (0x0, \"signal-vertical-min\"  , \"area for signal detection - vertical minimum offset value. Values between 0.0 and 1.0\");\n\t\tDoubleOption       & argSignalHorizontalMax = parser.add<DoubleOption> (0x0, \"signal-horizontal-max\", \"area for signal detection - horizontal maximum offset value. Values between 0.0 and 1.0\");\n\t\tDoubleOption       & argSignalVerticalMax   = parser.add<DoubleOption> (0x0, \"signal-vertical-max\"  , \"area for signal detection - vertical maximum offset value. Values between 0.0 and 1.0\");\n\n\t\tBooleanOption      & arg3DSBS               = parser.add<BooleanOption>(0x0, \"3DSBS\", \"Interpret the incoming video stream as 3D side-by-side\");\n\t\tBooleanOption      & arg3DTAB               = parser.add<BooleanOption>(0x0, \"3DTAB\", \"Interpret the incoming video stream as 3D top-and-bottom\");\n\t\tOption             & argAddress             = parser.add<Option>       ('a', \"address\", \"Set the address of the hyperion server [default: %1]\", \"127.0.0.1:19400\");\n\t\tIntOption          & argPriority            = parser.add<IntOption>    ('p', \"priority\", \"Use the provided priority channel (suggested 100-199) [default: %1]\", \"150\");\n\t\tBooleanOption      & argSkipReply           = parser.add<BooleanOption>(0x0, \"skip-reply\", \"Do not receive and check reply messages from Hyperion\");\n\t\tBooleanOption      & argHelp                = parser.add<BooleanOption>('h', \"help\", \"Show this help message and exit\");\n\n\t\targVideoStandard.addSwitch(\"pal\", VIDEOSTANDARD_PAL);\n\t\targVideoStandard.addSwitch(\"ntsc\", VIDEOSTANDARD_NTSC);\n\t\targVideoStandard.addSwitch(\"secam\", VIDEOSTANDARD_SECAM);\n\t\targVideoStandard.addSwitch(\"no-change\", VIDEOSTANDARD_NO_CHANGE);\n\n\t\targPixelFormat.addSwitch(\"yuyv\", PIXELFORMAT_YUYV);\n\t\targPixelFormat.addSwitch(\"uyvy\", PIXELFORMAT_UYVY);\n\t\targPixelFormat.addSwitch(\"rgb32\", PIXELFORMAT_RGB32);\n#ifdef HAVE_JPEG\n\t\targPixelFormat.addSwitch(\"mjpeg\", PIXELFORMAT_MJPEG);\n#endif\n\t\targPixelFormat.addSwitch(\"no-change\", PIXELFORMAT_NO_CHANGE);\n\n\t\t\/\/ parse all options\n\t\tparser.process(app);\n\n\t\t\/\/ check if we need to display the usage. exit if we do.\n\t\tif (parser.isSet(argHelp))\n\t\t{\n\t\t\tparser.showHelp(0);\n\t\t}\n\n\t\t\/\/ initialize the grabber\n\t\tV4L2Grabber grabber(\n\t\t\t\t\targDevice.value(parser),\n\t\t\t\t\targVideoStandard.switchValue(parser),\n\t\t\t\t\targPixelFormat.switchValue(parser),\n\t\t\t\t\tstd::max(1, argSizeDecimation.getInt(parser)));\n\n\t\t\/\/ set signal detection\n\t\tgrabber.setSignalDetectionEnable(! parser.isSet(argSignalDetection));\n\t\tgrabber.setSignalThreshold(\n\t\t\t\t\tstd::min(1.0, std::max(0.0, parser.isSet(argRedSignalThreshold)   ? argRedSignalThreshold.getDouble(parser)   : argSignalThreshold.getDouble(parser))),\n\t\t\t\t\tstd::min(1.0, std::max(0.0, parser.isSet(argGreenSignalThreshold) ? argGreenSignalThreshold.getDouble(parser) : argSignalThreshold.getDouble(parser))),\n\t\t\t\t\tstd::min(1.0, std::max(0.0, parser.isSet(argBlueSignalThreshold)  ? argBlueSignalThreshold.getDouble(parser)  : argSignalThreshold.getDouble(parser))),\n\t\t\t\t\t50);\n\n\t\t\/\/ set cropping values\n\t\tgrabber.setCropping(\n\t\t\tparser.isSet(argCropLeft)   ? argCropLeft.getInt(parser)   : argCropWidth.getInt(parser),\n\t\t\tparser.isSet(argCropRight)  ? argCropRight.getInt(parser)  : argCropWidth.getInt(parser),\n\t\t\tparser.isSet(argCropTop)    ? argCropTop.getInt(parser)    : argCropHeight.getInt(parser),\n\t\t\tparser.isSet(argCropBottom) ? argCropBottom.getInt(parser) : argCropHeight.getInt(parser));\n\n\t\tbool signalAreaOptsOk = true;\n\t\tif (parser.isSet(argSignalHorizontalMin) != parser.isSet(argSignalVerticalMin))\n\t\t{\n\t\t\tsignalAreaOptsOk = false;\n\t\t}\n\n\t\tif (parser.isSet(argSignalHorizontalMin) != parser.isSet(argSignalHorizontalMax))\n\t\t{\n\t\t\tsignalAreaOptsOk = false;\n\t\t}\n\n\t\tif (parser.isSet(argSignalHorizontalMin) != parser.isSet(argSignalVerticalMax))\n\t\t{\n\t\t\tsignalAreaOptsOk = false;\n\t\t}\n\n\t\tif (!signalAreaOptsOk)\n\t\t{\n\t\t\tError(log, \"aborting, because --signal-[vertical|horizontal]-[min|max] options must be used together\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tdouble x_frac_min = argSignalHorizontalMin.getDouble(parser);\n\t\tdouble y_frac_min = argSignalVerticalMin.getDouble(parser);\n\t\tdouble x_frac_max = argSignalHorizontalMax.getDouble(parser);\n\t\tdouble y_frac_max = argSignalVerticalMax.getDouble(parser);\n\n\t\tif (x_frac_min<0.0 || y_frac_min<0.0 || x_frac_max<0.0 || y_frac_max<0.0 || x_frac_min>1.0 || y_frac_min>1.0 ||  x_frac_max>1.0 ||  y_frac_max>1.0)\n\t\t{\n\t\t\tError(log, \"aborting, because --signal-[vertical|horizontal]-[min|max] values have to be between 0.0 and 1.0\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (parser.isSet(argSignalHorizontalMin))\n\t\t{\n\t\t\tgrabber.setSignalDetectionOffset( x_frac_min, y_frac_min, x_frac_max, y_frac_max);\n\t\t}\n\n\t\t\/\/ set 3D mode if applicable\n\t\tif (parser.isSet(arg3DSBS))\n\t\t{\n\t\t\tgrabber.setVideoMode(VIDEO_3DSBS);\n\t\t}\n\t\telse if (parser.isSet(arg3DTAB))\n\t\t{\n\t\t\tgrabber.setVideoMode(VIDEO_3DTAB);\n\t\t}\n\n\t\t\/\/ run the grabber\n\t\tif (parser.isSet(argScreenshot))\n\t\t{\n\t\t\tconst QRectF signalDetectionOffset = grabber.getSignalDetectionOffset();\n\n\t\t\tScreenshotHandler handler(\"screenshot.png\", signalDetectionOffset);\n\t\t\tQObject::connect(&grabber, SIGNAL(newFrame(Image<ColorRgb>)), &handler, SLOT(receiveImage(Image<ColorRgb>)));\n\t\t\tgrabber.start();\n\t\t\tQCoreApplication::exec();\n\t\t\tgrabber.stop();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ server searching by ssdp\n\t\t\tQString address = argAddress.value(parser);\n\t\t\tif(argAddress.value(parser) == \"127.0.0.1:19400\")\n\t\t\t{\n\t\t\t\tSSDPDiscover discover;\n\t\t\t\taddress = discover.getFirstService(STY_FLATBUFSERVER);\n\t\t\t\tif(address.isEmpty())\n\t\t\t\t{\n\t\t\t\t\taddress = argAddress.value(parser);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Create the Flatbuf-connection\n\t\t\tFlatBufferConnection flatbuf(\"V4L2 Standalone\", address, argPriority.getInt(parser), parser.isSet(argSkipReply));\n\n\t\t\t\/\/ Connect the screen capturing to flatbuf connection processing\n\t\t\tQObject::connect(&grabber, SIGNAL(newFrame(const Image<ColorRgb> &)), &flatbuf, SLOT(setImage(Image<ColorRgb>)));\n\n\t\t\t\/\/ Start the capturing\n\t\t\tgrabber.start();\n\n\t\t\t\/\/ Start the application\n\t\t\tapp.exec();\n\t\t}\n\t}\n\tcatch (const std::runtime_error & e)\n\t{\n\t\t\/\/ An error occured. Display error and quit\n\t\tError(log, \"%s\", e.what());\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n","avg_line_length":48.5765765766,"max_line_length":234,"alphanum_fraction":0.7038204748,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":167716,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":214.0,"content":"typedef bool (BuiltinTypeIsProc)(Type *t);\n\nBuiltinTypeIsProc *builtin_type_is_procs[BuiltinProc__type_simple_boolean_end - BuiltinProc__type_simple_boolean_begin] = {\n\tnullptr, \/\/ BuiltinProc__type_simple_boolean_begin\n\n\tis_type_boolean,\n\tis_type_integer,\n\tis_type_rune,\n\tis_type_float,\n\tis_type_complex,\n\tis_type_quaternion,\n\tis_type_string,\n\tis_type_typeid,\n\tis_type_any,\n\tis_type_endian_platform,\n\tis_type_endian_little,\n\tis_type_endian_big,\n\tis_type_unsigned,\n\tis_type_numeric,\n\tis_type_ordered,\n\tis_type_ordered_numeric,\n\tis_type_indexable,\n\tis_type_sliceable,\n\tis_type_comparable,\n\tis_type_simple_compare,\n\tis_type_dereferenceable,\n\tis_type_valid_for_keys,\n\tis_type_valid_for_matrix_elems,\n\n\tis_type_named,\n\tis_type_pointer,\n\tis_type_multi_pointer,\n\tis_type_array,\n\tis_type_enumerated_array,\n\tis_type_slice,\n\tis_type_dynamic_array,\n\n\tis_type_map,\n\tis_type_struct,\n\tis_type_union,\n\tis_type_enum,\n\tis_type_proc,\n\tis_type_bit_set,\n\tis_type_simd_vector,\n\tis_type_matrix,\n\n\tis_type_polymorphic_record_specialized,\n\tis_type_polymorphic_record_unspecialized,\n\n\ttype_has_nil,\n};\n\n\nvoid check_or_else_right_type(CheckerContext *c, Ast *expr, String const &name, Type *right_type) {\n\tif (right_type == nullptr) {\n\t\treturn;\n\t}\n\tif (!is_type_boolean(right_type) && !type_has_nil(right_type)) {\n\t\tgbString str = type_to_string(right_type);\n\t\terror(expr, \"'%.*s' expects an \\\"optional ok\\\" like value, or an n-valued expression where the last value is either a boolean or can be compared against 'nil', got %s\", LIT(name), str);\n\t\tgb_string_free(str);\n\t}\n}\n\nvoid check_or_else_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_) {\n\tType *left_type = nullptr;\n\tType *right_type = nullptr;\n\tif (x->type->kind == Type_Tuple) {\n\t\tauto const &vars = x->type->Tuple.variables;\n\t\tauto lhs = slice(vars, 0, vars.count-1);\n\t\tauto rhs = vars[vars.count-1];\n\t\tif (lhs.count == 1) {\n\t\t\tleft_type = lhs[0]->type;\n\t\t} else if (lhs.count != 0) {\n\t\t\tleft_type = alloc_type_tuple();\n\t\t\tleft_type->Tuple.variables = lhs;\n\t\t}\n\n\t\tright_type = rhs->type;\n\t} else {\n\t\tcheck_promote_optional_ok(c, x, &left_type, &right_type);\n\t}\n\n\tif (left_type_)  *left_type_  = left_type;\n\tif (right_type_) *right_type_ = right_type;\n\n\tcheck_or_else_right_type(c, x->expr, name, right_type);\n}\n\n\nvoid check_or_else_expr_no_value_error(CheckerContext *c, String const &name, Operand const &x, Type *type_hint) {\n\t\/\/ TODO(bill): better error message\n\tgbString t = type_to_string(x.type);\n\terror(x.expr, \"'%.*s' does not return a value, value is of type %s\", LIT(name), t);\n\tif (is_type_union(type_deref(x.type))) {\n\t\tType *bsrc = base_type(type_deref(x.type));\n\t\tgbString th = nullptr;\n\t\tif (type_hint != nullptr) {\n\t\t\tGB_ASSERT(bsrc->kind == Type_Union);\n\t\t\tfor_array(i, bsrc->Union.variants) {\n\t\t\t\tType *vt = bsrc->Union.variants[i];\n\t\t\t\tif (are_types_identical(vt, type_hint)) {\n\t\t\t\t\tth = type_to_string(type_hint);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgbString expr_str = expr_to_string(x.expr);\n\t\tif (th != nullptr) {\n\t\t\terror_line(\"\\tSuggestion: was a type assertion such as %s.(%s) or %s.? wanted?\\n\", expr_str, th, expr_str);\n\t\t} else {\n\t\t\terror_line(\"\\tSuggestion: was a type assertion such as %s.(T) or %s.? wanted?\\n\", expr_str, expr_str);\n\t\t}\n\t\tgb_string_free(th);\n\t\tgb_string_free(expr_str);\n\t}\n\tgb_string_free(t);\n}\n\n\nvoid check_or_return_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_) {\n\tType *left_type = nullptr;\n\tType *right_type = nullptr;\n\tif (x->type->kind == Type_Tuple) {\n\t\tauto const &vars = x->type->Tuple.variables;\n\t\tauto lhs = slice(vars, 0, vars.count-1);\n\t\tauto rhs = vars[vars.count-1];\n\t\tif (lhs.count == 1) {\n\t\t\tleft_type = lhs[0]->type;\n\t\t} else if (lhs.count != 0) {\n\t\t\tleft_type = alloc_type_tuple();\n\t\t\tleft_type->Tuple.variables = lhs;\n\t\t}\n\n\t\tright_type = rhs->type;\n\t} else {\n\t\tcheck_promote_optional_ok(c, x, &left_type, &right_type);\n\t}\n\n\tif (left_type_)  *left_type_  = left_type;\n\tif (right_type_) *right_type_ = right_type;\n\n\tcheck_or_else_right_type(c, x->expr, name, right_type);\n}\n\n\nbool does_require_msgSend_stret(Type *return_type) {\n\tif (return_type == nullptr) {\n\t\treturn false;\n\t}\n\tif (build_context.metrics.arch == TargetArch_i386 || build_context.metrics.arch == TargetArch_amd64) {\n\t\ti64 struct_limit = type_size_of(t_uintptr) << 1;\n\t\treturn type_size_of(return_type) > struct_limit;\n\t}\n\tif (build_context.metrics.arch == TargetArch_arm64) {\n\t\treturn false;\n\t}\n\n\t\/\/ if (build_context.metrics.arch == TargetArch_arm32) {\n\t\/\/ \ti64 struct_limit = type_size_of(t_uintptr);\n\t\/\/ \t\/\/ NOTE(bill): This is technically wrong\n\t\/\/ \treturn is_type_struct(return_type) && !is_type_raw_union(return_type) && type_size_of(return_type) > struct_limit;\n\t\/\/ }\n\tGB_PANIC(\"unsupported architecture\");\n\treturn false;\n}\n\nObjcMsgKind get_objc_proc_kind(Type *return_type) {\n\tif (return_type == nullptr) {\n\t\treturn ObjcMsg_normal;\n\t}\n\n\tif (build_context.metrics.arch == TargetArch_i386 || build_context.metrics.arch == TargetArch_amd64) {\n\t\tif (is_type_float(return_type)) {\n\t\t\treturn ObjcMsg_fpret;\n\t\t}\n\t\tif (build_context.metrics.arch == TargetArch_amd64) {\n\t\t\tif (is_type_complex(return_type)) {\n\t\t\t\t\/\/ URL: https:\/\/github.com\/opensource-apple\/objc4\/blob\/cd5e62a5597ea7a31dccef089317abb3a661c154\/runtime\/message.h#L143-L159\n\t\t\t\treturn ObjcMsg_fpret;\n\t\t\t}\n\t\t}\n\t}\n\tif (build_context.metrics.arch != TargetArch_arm64) {\n\t\tif (does_require_msgSend_stret(return_type)) {\n\t\t\treturn ObjcMsg_stret;\n\t\t}\n\t}\n\treturn ObjcMsg_normal;\n}\n\nvoid add_objc_proc_type(CheckerContext *c, Ast *call, Type *return_type, Slice<Type *> param_types) {\n\tObjcMsgKind kind = get_objc_proc_kind(return_type);\n\n\tScope *scope = create_scope(c->info, nullptr);\n\n\t\/\/ NOTE(bill, 2022-02-08): the backend's ABI handling should handle this correctly, I hope\n\tType *params = alloc_type_tuple();\n\t{\n\t\tauto variables = array_make<Entity *>(permanent_allocator(), 0, param_types.count);\n\n\t\tfor_array(i, param_types)  {\n\t\t\tType *type = param_types[i];\n\t\t\tEntity *param = alloc_entity_param(scope, blank_token, type, false, true);\n\t\t\tarray_add(&variables, param);\n\t\t}\n\t\tparams->Tuple.variables = slice_from_array(variables);\n\t}\n\n\tType *results = alloc_type_tuple();\n\tif (return_type) {\n\t\tauto variables = array_make<Entity *>(permanent_allocator(), 1);\n\t\tresults->Tuple.variables = slice_from_array(variables);\n\t\tEntity *param = alloc_entity_param(scope, blank_token, return_type, false, true);\n\t\tresults->Tuple.variables[0] = param;\n\t}\n\n\n\tObjcMsgData data = {};\n\tdata.kind = kind;\n\tdata.proc_type = alloc_type_proc(scope, params, param_types.count, results, results->Tuple.variables.count, false, ProcCC_CDecl);\n\n\tmutex_lock(&c->info->objc_types_mutex);\n\tmap_set(&c->info->objc_msgSend_types, call, data);\n\tmutex_unlock(&c->info->objc_types_mutex);\n\n\ttry_to_add_package_dependency(c, \"runtime\", \"objc_msgSend\");\n\ttry_to_add_package_dependency(c, \"runtime\", \"objc_msgSend_fpret\");\n\ttry_to_add_package_dependency(c, \"runtime\", \"objc_msgSend_fp2ret\");\n\ttry_to_add_package_dependency(c, \"runtime\", \"objc_msgSend_stret\");\n}\n\nbool is_constant_string(CheckerContext *c, String const &builtin_name, Ast *expr, String *name_) {\n\tOperand op = {};\n\tcheck_expr(c, &op, expr);\n\tif (op.mode == Addressing_Constant && op.value.kind == ExactValue_String) {\n\t\tif (name_) *name_ = op.value.value_string;\n\t\treturn true;\n\t}\n\tgbString e = expr_to_string(op.expr);\n\tgbString t = type_to_string(op.type);\n\terror(op.expr, \"'%.*s' expected a constant string value, got %s of type %s\", LIT(builtin_name), e, t);\n\tgb_string_free(t);\n\tgb_string_free(e);\n\treturn false;\n}\n\nbool check_builtin_objc_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint) {\n\tString const &builtin_name = builtin_procs[id].name;\n\n\tif (build_context.metrics.os != TargetOs_darwin) {\n\t\t\/\/ allow on doc generation (e.g. Metal stuff)\n\t\tif (build_context.command_kind != Command_doc && build_context.command_kind != Command_check) {\n\t\t\terror(call, \"'%.*s' only works on darwin\", LIT(builtin_name));\n\t\t}\n\t}\n\n\n\tast_node(ce, CallExpr, call);\n\tswitch (id) {\n\tdefault:\n\t\tGB_PANIC(\"Implement objective built-in procedure: %.*s\", LIT(builtin_name));\n\t\treturn false;\n\n\tcase BuiltinProc_objc_send: {\n\t\tType *return_type = nullptr;\n\n\t\tOperand rt = {};\n\t\tcheck_expr_or_type(c, &rt, ce->args[0]);\n\t\tif (rt.mode == Addressing_Type) {\n\t\t\treturn_type = rt.type;\n\t\t} else if (is_operand_nil(rt)) {\n\t\t\treturn_type = nullptr;\n\t\t} else {\n\t\t\tgbString e = expr_to_string(rt.expr);\n\t\t\terror(rt.expr, \"'%.*s' expected a type or nil to define the return type of the Objective-C call, got %s\", LIT(builtin_name), e);\n\t\t\tgb_string_free(e);\n\t\t\treturn false;\n\t\t}\n\n\t\toperand->type = return_type;\n\t\toperand->mode = return_type ? Addressing_Value : Addressing_NoValue;\n\n\t\tString class_name = {};\n\t\tString sel_name = {};\n\n\t\tType *sel_type = t_objc_SEL;\n\t\tOperand self = {};\n\t\tcheck_expr_or_type(c, &self, ce->args[1]);\n\t\tif (self.mode == Addressing_Type) {\n\t\t\tif (!is_type_objc_object(self.type)) {\n\t\t\t\tgbString t = type_to_string(self.type);\n\t\t\t\terror(self.expr, \"'%.*s' expected a type or value derived from intrinsics.objc_object, got type %s\", LIT(builtin_name), t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!has_type_got_objc_class_attribute(self.type)) {\n\t\t\t\tgbString t = type_to_string(self.type);\n\t\t\t\terror(self.expr, \"'%.*s' expected a named type with the attribute @(obj_class=<string>) , got type %s\", LIT(builtin_name), t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tsel_type = t_objc_Class;\n\t\t} else if (!is_operand_value(self) || !check_is_assignable_to(c, &self, t_objc_id)) {\n\t\t\tgbString e = expr_to_string(self.expr);\n\t\t\tgbString t = type_to_string(self.type);\n\t\t\terror(self.expr, \"'%.*s' expected a type or value derived from intrinsics.objc_object, got '%s' of type %s\", LIT(builtin_name), e, t);\n\t\t\tgb_string_free(t);\n\t\t\tgb_string_free(e);\n\t\t\treturn false;\n\t\t} else if (!is_type_pointer(self.type)) {\n\t\t\tgbString e = expr_to_string(self.expr);\n\t\t\tgbString t = type_to_string(self.type);\n\t\t\terror(self.expr, \"'%.*s' expected a pointer of a value derived from intrinsics.objc_object, got '%s' of type %s\", LIT(builtin_name), e, t);\n\t\t\tgb_string_free(t);\n\t\t\tgb_string_free(e);\n\t\t\treturn false;\n\t\t} else {\n\t\t\tType *type = type_deref(self.type);\n\t\t\tif (!(type->kind == Type_Named &&\n\t\t\t      type->Named.type_name != nullptr &&\n\t\t\t      type->Named.type_name->TypeName.objc_class_name != \"\")) {\n\t\t\t\tgbString t = type_to_string(type);\n\t\t\t\terror(self.expr, \"'%.*s' expected a named type with the attribute @(obj_class=<string>) , got type %s\", LIT(builtin_name), t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\n\t\tif (!is_constant_string(c, builtin_name, ce->args[2], &sel_name)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tisize const arg_offset = 1;\n\t\tauto param_types = slice_make<Type *>(permanent_allocator(), ce->args.count-arg_offset);\n\t\tparam_types[0] = t_objc_id;\n\t\tparam_types[1] = sel_type;\n\n\t\tfor (isize i = 2+arg_offset; i < ce->args.count; i++) {\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[i]);\n\t\t\tparam_types[i-arg_offset] = x.type;\n\t\t}\n\n\t\tadd_objc_proc_type(c, call, return_type, param_types);\n\n\t\treturn true;\n\t} break;\n\n\tcase BuiltinProc_objc_find_selector: \n\tcase BuiltinProc_objc_find_class: \n\tcase BuiltinProc_objc_register_selector: \n\tcase BuiltinProc_objc_register_class: \n\t{\n\t\tString sel_name = {};\n\t\tif (!is_constant_string(c, builtin_name, ce->args[0], &sel_name)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tswitch (id) {\n\t\tcase BuiltinProc_objc_find_selector: \n\t\tcase BuiltinProc_objc_register_selector: \n\t\t\toperand->type = t_objc_SEL;\n\t\t\tbreak;\n\t\tcase BuiltinProc_objc_find_class: \n\t\tcase BuiltinProc_objc_register_class: \n\t\t\toperand->type = t_objc_Class;\n\t\t\tbreak;\n\n\t\t}\n\t\toperand->mode = Addressing_Value;\n\n\t\ttry_to_add_package_dependency(c, \"runtime\", \"objc_lookUpClass\");\n\t\ttry_to_add_package_dependency(c, \"runtime\", \"sel_registerName\");\n\t\ttry_to_add_package_dependency(c, \"runtime\", \"objc_allocateClassPair\");\n\t\treturn true;\n\t} break;\n\t}\n}\n\nbool check_atomic_memory_order_argument(CheckerContext *c, Ast *expr, String const &builtin_name, OdinAtomicMemoryOrder *memory_order_, char const *extra_message = nullptr) {\n\tOperand x = {};\n\tcheck_expr_with_type_hint(c, &x, expr, t_atomic_memory_order);\n\tif (x.mode == Addressing_Invalid) {\n\t\treturn false;\n\t}\n\tif (!are_types_identical(x.type, t_atomic_memory_order) || x.mode != Addressing_Constant)  {\n\t\tgbString str = type_to_string(x.type);\n\t\tif (extra_message) {\n\t\t\terror(x.expr, \"Expected a constant Atomic_Memory_Order value for the %s of '%.*s', got %s\", extra_message, LIT(builtin_name), str);\n\t\t} else {\n\t\t\terror(x.expr, \"Expected a constant Atomic_Memory_Order value for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t}\n\t\tgb_string_free(str);\n\t\treturn false;\n\t}\n\ti64 value = exact_value_to_i64(x.value);\n\tif (value < 0 || value >= OdinAtomicMemoryOrder_COUNT) {\n\t\terror(x.expr, \"Illegal Atomic_Memory_Order value, got %lld\", cast(long long)value);\n\t\treturn false;\n\t}\n\tif (memory_order_) {\n\t\t*memory_order_ = cast(OdinAtomicMemoryOrder)value;\n\t}\n\n\treturn true;\n\n}\n\n\nbool check_builtin_simd_operation(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint) {\n\tast_node(ce, CallExpr, call);\n\n\tString const &builtin_name = builtin_procs[id].name;\n\tswitch (id) {\n\t\/\/ Any numeric\n\tcase BuiltinProc_simd_add:\n\tcase BuiltinProc_simd_sub:\n\tcase BuiltinProc_simd_mul:\n\tcase BuiltinProc_simd_div:\n\tcase BuiltinProc_simd_min:\n\tcase BuiltinProc_simd_max:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]);                        if (x.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr_with_type_hint(c, &y, ce->args[1], x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &y, x.type);                       if (y.mode == Addressing_Invalid) return false;\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_simd_vector(y.type)) {\n\t\t\t\terror(y.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!are_types_identical(x.type, y.type)) {\n\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\tgbString ys = type_to_string(y.type);\n\t\t\t\terror(x.expr, \"'%.*s' expected 2 arguments of the same type, got '%s' vs '%s'\", LIT(builtin_name), xs, ys);\n\t\t\t\tgb_string_free(ys);\n\t\t\t\tgb_string_free(xs);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *elem = base_array_type(x.type);\n\t\t\tif (!is_type_integer(elem) && !is_type_float(elem)) {\n\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"'%.*s' expected a #simd type with an integer or floating point element, got '%s'\", LIT(builtin_name), xs);\n\t\t\t\tgb_string_free(xs);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (id == BuiltinProc_simd_div && is_type_integer(elem)) {\n\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"'%.*s' is not supported for integer elements, got '%s'\", LIT(builtin_name), xs);\n\t\t\t\tgb_string_free(xs);\n\t\t\t\t\/\/ don't return\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = x.type;\n\t\t\treturn true;\n\t\t}\n\n\t\/\/ Integer only\n\tcase BuiltinProc_simd_add_sat:\n\tcase BuiltinProc_simd_sub_sat:\n\tcase BuiltinProc_simd_and:\n\tcase BuiltinProc_simd_or:\n\tcase BuiltinProc_simd_xor:\n\tcase BuiltinProc_simd_and_not:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr_with_type_hint(c, &y, ce->args[1], x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_simd_vector(y.type)) {\n\t\t\t\terror(y.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!are_types_identical(x.type, y.type)) {\n\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\tgbString ys = type_to_string(y.type);\n\t\t\t\terror(x.expr, \"'%.*s' expected 2 arguments of the same type, got '%s' vs '%s'\", LIT(builtin_name), xs, ys);\n\t\t\t\tgb_string_free(ys);\n\t\t\t\tgb_string_free(xs);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *elem = base_array_type(x.type);\n\n\t\t\tswitch (id) {\n\t\t\tcase BuiltinProc_simd_add_sat:\n\t\t\tcase BuiltinProc_simd_sub_sat:\n\t\t\t\tif (!is_type_integer(elem)) {\n\t\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\t\terror(x.expr, \"'%.*s' expected a #simd type with an integer element, got '%s'\", LIT(builtin_name), xs);\n\t\t\t\t\tgb_string_free(xs);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (!is_type_integer(elem) && !is_type_boolean(elem)) {\n\t\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\t\terror(x.expr, \"'%.*s' expected a #simd type with an integer or boolean element, got '%s'\", LIT(builtin_name), xs);\n\t\t\t\t\tgb_string_free(xs);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = x.type;\n\t\t\treturn true;\n\t\t}\n\n\tcase BuiltinProc_simd_shl:        \/\/ Odin-like\n\tcase BuiltinProc_simd_shr:        \/\/ Odin-like\n\tcase BuiltinProc_simd_shl_masked: \/\/ C-like\n\tcase BuiltinProc_simd_shr_masked: \/\/ C-like\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr_with_type_hint(c, &y, ce->args[1], x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_simd_vector(y.type)) {\n\t\t\t\terror(y.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tGB_ASSERT(x.type->kind == Type_SimdVector);\n\t\t\tGB_ASSERT(y.type->kind == Type_SimdVector);\n\t\t\tType *xt = x.type;\n\t\t\tType *yt = y.type;\n\n\t\t\tif (xt->SimdVector.count != yt->SimdVector.count) {\n\t\t\t\terror(x.expr, \"'%.*s' mismatched simd vector lengths, got '%lld' vs '%lld'\",\n\t\t\t\t      LIT(builtin_name),\n\t\t\t\t      cast(long long)xt->SimdVector.count,\n\t\t\t\t      cast(long long)yt->SimdVector.count);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_integer(base_array_type(x.type))) {\n\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"'%.*s' expected a #simd type with an integer element, got '%s'\", LIT(builtin_name), xs);\n\t\t\t\tgb_string_free(xs);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_unsigned(base_array_type(y.type))) {\n\t\t\t\tgbString ys = type_to_string(y.type);\n\t\t\t\terror(y.expr, \"'%.*s' expected a #simd type with an unsigned integer element as the shifting operand, got '%s'\", LIT(builtin_name), ys);\n\t\t\t\tgb_string_free(ys);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = x.type;\n\t\t\treturn true;\n\t\t}\n\n\t\/\/ Unary\n\tcase BuiltinProc_simd_neg:\n\tcase BuiltinProc_simd_abs:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]);\n\t\t\tif (x.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *elem = base_array_type(x.type);\n\t\t\tif (!is_type_integer(elem) && !is_type_float(elem)) {\n\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"'%.*s' expected a #simd type with an integer or floating point element, got '%s'\", LIT(builtin_name), xs);\n\t\t\t\tgb_string_free(xs);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = x.type;\n\t\t\treturn true;\n\t\t}\n\n\t\/\/ Return integer masks\n\tcase BuiltinProc_simd_lanes_eq:\n\tcase BuiltinProc_simd_lanes_ne:\n\tcase BuiltinProc_simd_lanes_lt:\n\tcase BuiltinProc_simd_lanes_le:\n\tcase BuiltinProc_simd_lanes_gt:\n\tcase BuiltinProc_simd_lanes_ge:\n\t\t{\n\t\t\t\/\/ op(#simd[N]T, #simd[N]T) -> #simd[N]V\n\t\t\t\/\/ where `V` is an integer, `size_of(T) == size_of(V)`\n\t\t\t\/\/ `V` will all 0s if false and all 1s if true (e.g. 0x00 and 0xff for false and true, respectively)\n\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr_with_type_hint(c, &y, ce->args[1], x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *elem = base_array_type(x.type);\n\t\t\tswitch (id) {\n\t\t\tcase BuiltinProc_simd_lanes_eq:\n\t\t\tcase BuiltinProc_simd_lanes_ne:\n\t\t\t\tif (!is_type_integer(elem) && !is_type_float(elem) && !is_type_boolean(elem)) {\n\t\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\t\terror(x.expr, \"'%.*s' expected a #simd type with an integer, floating point, or boolean element, got '%s'\", LIT(builtin_name), xs);\n\t\t\t\t\tgb_string_free(xs);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (!is_type_integer(elem) && !is_type_float(elem)) {\n\t\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\t\terror(x.expr, \"'%.*s' expected a #simd type with an integer or floating point element, got '%s'\", LIT(builtin_name), xs);\n\t\t\t\t\tgb_string_free(xs);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\n\t\t\tType *vt = base_type(x.type);\n\t\t\tGB_ASSERT(vt->kind == Type_SimdVector);\n\t\t\ti64 count = vt->SimdVector.count;\n\n\t\t\ti64 sz = type_size_of(elem);\n\t\t\tType *new_elem = nullptr;\n\n\t\t\tswitch (sz) {\n\t\t\tcase 1: new_elem = t_u8;  break;\n\t\t\tcase 2: new_elem = t_u16; break;\n\t\t\tcase 4: new_elem = t_u32; break;\n\t\t\tcase 8: new_elem = t_u64; break;\n\t\t\tcase 16:\n\t\t\t\terror(x.expr, \"'%.*s' not supported 128-bit integer backed simd vector types\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = alloc_type_simd_vector(count, new_elem);\n\t\t\treturn true;\n\t\t}\n\n\tcase BuiltinProc_simd_extract:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *elem = base_array_type(x.type);\n\t\t\ti64 max_count = x.type->SimdVector.count;\n\t\t\ti64 value = -1;\n\t\t\tif (!check_index_value(c, x.type, false, ce->args[1], max_count, &value)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (max_count < 0) {\n\t\t\t\terror(ce->args[1], \"'%.*s' expected a constant integer index, got '%lld'\", LIT(builtin_name), cast(long long)value);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = elem;\n\t\t\treturn true;\n\t\t}\n\t\tbreak;\n\tcase BuiltinProc_simd_replace:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *elem = base_array_type(x.type);\n\t\t\ti64 max_count = x.type->SimdVector.count;\n\t\t\ti64 value = -1;\n\t\t\tif (!check_index_value(c, x.type, false, ce->args[1], max_count, &value)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (max_count < 0) {\n\t\t\t\terror(ce->args[1], \"'%.*s' expected a constant integer index, got '%lld'\", LIT(builtin_name), cast(long long)value);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tOperand y = {};\n\t\t\tcheck_expr_with_type_hint(c, &y, ce->args[2], elem); if (y.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &y, elem); if (y.mode == Addressing_Invalid) return false;\n\t\t\tif (!are_types_identical(y.type, elem)) {\n\t\t\t\tgbString et = type_to_string(elem);\n\t\t\t\tgbString yt = type_to_string(y.type);\n\t\t\t\terror(y.expr, \"'%.*s' expected a type of '%s' to insert, got '%s'\", LIT(builtin_name), et, yt);\n\t\t\t\tgb_string_free(yt);\n\t\t\t\tgb_string_free(et);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = x.type;\n\t\t\treturn true;\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_simd_reduce_add_ordered:\n\tcase BuiltinProc_simd_reduce_mul_ordered:\n\tcase BuiltinProc_simd_reduce_min:\n\tcase BuiltinProc_simd_reduce_max:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *elem = base_array_type(x.type);\n\t\t\tif (!is_type_integer(elem) && !is_type_float(elem)) {\n\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"'%.*s' expected a #simd type with an integer or floating point element, got '%s'\", LIT(builtin_name), xs);\n\t\t\t\tgb_string_free(xs);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = base_array_type(x.type);\n\t\t\treturn true;\n\t\t}\n\n\tcase BuiltinProc_simd_reduce_and:\n\tcase BuiltinProc_simd_reduce_or:\n\tcase BuiltinProc_simd_reduce_xor:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *elem = base_array_type(x.type);\n\t\t\tif (!is_type_integer(elem) && !is_type_boolean(elem)) {\n\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"'%.*s' expected a #simd type with an integer or boolean element, got '%s'\", LIT(builtin_name), xs);\n\t\t\t\tgb_string_free(xs);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = base_array_type(x.type);\n\t\t\treturn true;\n\t\t}\n\n\n\tcase BuiltinProc_simd_shuffle:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr_with_type_hint(c, &y, ce->args[1], x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_simd_vector(y.type)) {\n\t\t\t\terror(y.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!are_types_identical(x.type, y.type)) {\n\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\tgbString ys = type_to_string(y.type);\n\t\t\t\terror(x.expr, \"'%.*s' expected 2 arguments of the same type, got '%s' vs '%s'\", LIT(builtin_name), xs, ys);\n\t\t\t\tgb_string_free(ys);\n\t\t\t\tgb_string_free(xs);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *elem = base_array_type(x.type);\n\n\t\t\ti64 max_count = x.type->SimdVector.count + y.type->SimdVector.count;\n\n\t\t\ti64 arg_count = 0;\n\t\t\tfor_array(i, ce->args) {\n\t\t\t\tif (i < 2) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tAst *arg = ce->args[i];\n\t\t\t\tOperand op = {};\n\t\t\t\tcheck_expr(c, &op, arg);\n\t\t\t\tif (op.mode == Addressing_Invalid) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tType *arg_type = base_type(op.type);\n\t\t\t\tif (!is_type_integer(arg_type) || op.mode != Addressing_Constant) {\n\t\t\t\t\terror(op.expr, \"Indices to '%.*s' must be constant integers\", LIT(builtin_name));\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tif (big_int_is_neg(&op.value.value_integer)) {\n\t\t\t\t\terror(op.expr, \"Negative '%.*s' index\", LIT(builtin_name));\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tBigInt mc = {};\n\t\t\t\tbig_int_from_i64(&mc, max_count);\n\t\t\t\tif (big_int_cmp(&mc, &op.value.value_integer) <= 0) {\n\t\t\t\t\terror(op.expr, \"'%.*s' index exceeds length\", LIT(builtin_name));\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\targ_count++;\n\t\t\t}\n\n\t\t\tif (arg_count > max_count) {\n\t\t\t\terror(call, \"Too many '%.*s' indices, %td > %td\", LIT(builtin_name), arg_count, max_count);\n\t\t\t\treturn false;\n\t\t\t}\n\n\n\t\t\tif (!is_power_of_two(arg_count)) {\n\t\t\t\terror(call, \"'%.*s' must have a power of two index arguments, got %lld\", LIT(builtin_name), cast(long long)arg_count);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = alloc_type_simd_vector(arg_count, elem);\n\t\t\treturn true;\n\t\t}\n\n\tcase BuiltinProc_simd_select:\n\t\t{\n\t\t\tOperand cond = {};\n\t\t\tcheck_expr(c, &cond, ce->args[0]); if (cond.mode == Addressing_Invalid) return false;\n\n\t\t\tif (!is_type_simd_vector(cond.type)) {\n\t\t\t\terror(cond.expr, \"'%.*s' expected a simd vector boolean type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *cond_elem = base_array_type(cond.type);\n\t\t\tif (!is_type_boolean(cond_elem) && !is_type_integer(cond_elem)) {\n\t\t\t\tgbString cond_str = type_to_string(cond.type);\n\t\t\t\terror(cond.expr, \"'%.*s' expected a simd vector boolean or integer type, got '%s'\", LIT(builtin_name), cond_str);\n\t\t\t\tgb_string_free(cond_str);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tcheck_expr(c, &x, ce->args[1]); if (x.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr_with_type_hint(c, &y, ce->args[2], x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_simd_vector(y.type)) {\n\t\t\t\terror(y.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!are_types_identical(x.type, y.type)) {\n\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\tgbString ys = type_to_string(y.type);\n\t\t\t\terror(x.expr, \"'%.*s' expected 2 results of the same type, got '%s' vs '%s'\", LIT(builtin_name), xs, ys);\n\t\t\t\tgb_string_free(ys);\n\t\t\t\tgb_string_free(xs);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (cond.type->SimdVector.count != x.type->SimdVector.count) {\n\t\t\t\terror(x.expr, \"'%.*s' expected condition vector to match the length of the result lengths, got '%lld' vs '%lld'\",\n\t\t\t\t      LIT(builtin_name),\n\t\t\t\t      cast(long long)cond.type->SimdVector.count,\n\t\t\t\t      cast(long long)x.type->SimdVector.count);\n\t\t\t\treturn false;\n\t\t\t}\n\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = x.type;\n\t\t\treturn true;\n\t\t}\n\n\tcase BuiltinProc_simd_ceil:\n\tcase BuiltinProc_simd_floor:\n\tcase BuiltinProc_simd_trunc:\n\tcase BuiltinProc_simd_nearest:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector boolean type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *elem = base_array_type(x.type);\n\t\t\tif (!is_type_float(elem)) {\n\t\t\t\tgbString x_str = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector floating point type, got '%s'\", LIT(builtin_name), x_str);\n\t\t\t\tgb_string_free(x_str);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = x.type;\n\t\t\treturn true;\n\t\t}\n\n\tcase BuiltinProc_simd_lanes_reverse:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\toperand->type = x.type;\n\t\t\toperand->mode = Addressing_Value;\n\t\t\treturn true;\n\t\t}\n\n\tcase BuiltinProc_simd_lanes_rotate_left:\n\tcase BuiltinProc_simd_lanes_rotate_right:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tOperand offset = {};\n\t\t\tcheck_expr(c, &offset, ce->args[1]); if (offset.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &offset, t_i64);\n\t\t\tif (!is_type_integer(offset.type) || offset.mode != Addressing_Constant) {\n\t\t\t\terror(offset.expr, \"'%.*s' expected a constant integer offset\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tcheck_assignment(c, &offset, t_i64, builtin_name);\n\n\t\t\toperand->type = x.type;\n\t\t\toperand->mode = Addressing_Value;\n\t\t\treturn true;\n\t\t}\n\n\tcase BuiltinProc_simd_clamp:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tOperand z = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr_with_type_hint(c, &y, ce->args[1], x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr_with_type_hint(c, &z, ce->args[2], x.type); if (z.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &z, x.type);\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_simd_vector(y.type)) {\n\t\t\t\terror(y.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_simd_vector(z.type)) {\n\t\t\t\terror(z.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!are_types_identical(x.type, y.type)) {\n\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\tgbString ys = type_to_string(y.type);\n\t\t\t\terror(x.expr, \"'%.*s' expected 2 arguments of the same type, got '%s' vs '%s'\", LIT(builtin_name), xs, ys);\n\t\t\t\tgb_string_free(ys);\n\t\t\t\tgb_string_free(xs);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!are_types_identical(x.type, z.type)) {\n\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\tgbString zs = type_to_string(z.type);\n\t\t\t\terror(x.expr, \"'%.*s' expected 2 arguments of the same type, got '%s' vs '%s'\", LIT(builtin_name), xs, zs);\n\t\t\t\tgb_string_free(zs);\n\t\t\t\tgb_string_free(xs);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *elem = base_array_type(x.type);\n\t\t\tif (!is_type_integer(elem) && !is_type_float(elem)) {\n\t\t\t\tgbString xs = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"'%.*s' expected a #simd type with an integer or floating point element, got '%s'\", LIT(builtin_name), xs);\n\t\t\t\tgb_string_free(xs);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = x.type;\n\t\t\treturn true;\n\t\t}\n\n\tcase BuiltinProc_simd_to_bits:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\n\t\t\tif (!is_type_simd_vector(x.type)) {\n\t\t\t\terror(x.expr, \"'%.*s' expected a simd vector type\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *elem = base_array_type(x.type);\n\t\t\ti64 count = get_array_type_count(x.type);\n\t\t\ti64 sz = type_size_of(elem);\n\t\t\tType *bit_elem = nullptr;\n\t\t\tswitch (sz) {\n\t\t\tcase 1: bit_elem = t_u8;  break;\n\t\t\tcase 2: bit_elem = t_u16; break;\n\t\t\tcase 4: bit_elem = t_u32; break;\n\t\t\tcase 8: bit_elem = t_u64; break;\n\t\t\t}\n\t\t\tGB_ASSERT(bit_elem != nullptr);\n\n\t\t\toperand->type = alloc_type_simd_vector(count, bit_elem);\n\t\t\toperand->mode = Addressing_Value;\n\t\t\treturn true;\n\t\t}\n\n\tcase BuiltinProc_simd_x86__MM_SHUFFLE:\n\t\t{\n\t\t\tOperand x[4] = {};\n\t\t\tfor (unsigned i = 0; i < 4; i++) {\n\t\t\t\tcheck_expr(c, x+i, ce->args[i]); if (x[i].mode == Addressing_Invalid) return false;\n\t\t\t}\n\n\t\t\tu32 offsets[4] = {6, 4, 2, 0};\n\t\t\tu32 result = 0;\n\t\t\tfor (unsigned i = 0; i < 4; i++) {\n\t\t\t\tif (!is_type_integer(x[i].type) || x[i].mode != Addressing_Constant) {\n\t\t\t\t\tgbString xs = type_to_string(x[i].type);\n\t\t\t\t\terror(x[i].expr, \"'%.*s' expected a constant integer\", LIT(builtin_name), xs);\n\t\t\t\t\tgb_string_free(xs);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\ti64 val = exact_value_to_i64(x[i].value);\n\t\t\t\tif (val < 0 || val > 3) {\n\t\t\t\t\terror(x[i].expr, \"'%.*s' expected a constant integer in the range 0..<4, got %lld\", LIT(builtin_name), cast(long long)val);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tresult |= cast(u32)(val) << offsets[i];\n\t\t\t}\n\n\t\t\toperand->type = t_untyped_integer;\n\t\t\toperand->mode = Addressing_Constant;\n\t\t\toperand->value = exact_value_i64(result);\n\t\t\treturn true;\n\t\t}\n\tdefault:\n\t\tGB_PANIC(\"Unhandled simd intrinsic: %.*s\", LIT(builtin_name));\n\t}\n\n\treturn false;\n}\n\n\nbool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint) {\n\tast_node(ce, CallExpr, call);\n\tif (ce->inlining != ProcInlining_none) {\n\t\terror(call, \"Inlining operators are not allowed on built-in procedures\");\n\t}\n\n\tBuiltinProc *bp = &builtin_procs[id];\n\t{\n\t\tchar const *err = nullptr;\n\t\tif (ce->args.count < bp->arg_count) {\n\t\t\terr = \"Too few\";\n\t\t} else if (ce->args.count > bp->arg_count && !bp->variadic) {\n\t\t\terr = \"Too many\";\n\t\t}\n\n\t\tif (err != nullptr) {\n\t\t\tgbString expr = expr_to_string(ce->proc);\n\t\t\terror(ce->close, \"%s arguments for '%s', expected %td, got %td\",\n\t\t\t      err, expr,\n\t\t\t      bp->arg_count, ce->args.count);\n\t\t\tgb_string_free(expr);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tswitch (id) {\n\tcase BuiltinProc_size_of:\n\tcase BuiltinProc_align_of:\n\tcase BuiltinProc_offset_of:\n\tcase BuiltinProc_offset_of_by_string:\n\tcase BuiltinProc_type_info_of:\n\tcase BuiltinProc_typeid_of:\n\tcase BuiltinProc_len:\n\tcase BuiltinProc_min:\n\tcase BuiltinProc_max:\n\tcase BuiltinProc_type_is_subtype_of:\n\tcase BuiltinProc_objc_send:\n\tcase BuiltinProc_objc_find_selector: \n\tcase BuiltinProc_objc_find_class: \n\tcase BuiltinProc_objc_register_selector: \n\tcase BuiltinProc_objc_register_class: \n\tcase BuiltinProc_atomic_type_is_lock_free:\n\t\t\/\/ NOTE(bill): The first arg may be a Type, this will be checked case by case\n\t\tbreak;\n\n\tcase BuiltinProc_atomic_thread_fence:\n\tcase BuiltinProc_atomic_signal_fence:\n\t\t\/\/ NOTE(bill): first type will require a type hint\n\t\tbreak;\n\n\tcase BuiltinProc_DIRECTIVE: {\n\t\tast_node(bd, BasicDirective, ce->proc);\n\t\tString name = bd->name.string;\n\t\tif (name == \"defined\") {\n\t\t\tbreak;\n\t\t}\n\t\tif (name == \"config\") {\n\t\t\tbreak;\n\t\t}\n\t\t\/*fallthrough*\/\n\t}\n\tdefault:\n\t\tif (BuiltinProc__type_begin < id && id < BuiltinProc__type_end) {\n\t\t\tcheck_expr_or_type(c, operand, ce->args[0]);\n\t\t} else if (ce->args.count > 0) {\n\t\t\tcheck_multi_expr(c, operand, ce->args[0]);\n\t\t}\n\t\tbreak;\n\t}\n\n\tString const &builtin_name = builtin_procs[id].name;\n\n\n\tif (ce->args.count > 0) {\n\t\tif (ce->args[0]->kind == Ast_FieldValue) {\n\t\t\tif (id != BuiltinProc_soa_zip) {\n\t\t\t\terror(call, \"'field = value' calling is not allowed on built-in procedures\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (BuiltinProc__simd_begin < id && id < BuiltinProc__simd_end) {\n\t\tbool ok = check_builtin_simd_operation(c, operand, call, id, type_hint);\n\t\tif (!ok) {\n\t\t\toperand->type = t_invalid;\n\t\t}\n\t\toperand->mode = Addressing_Value;\n\t\toperand->value = {};\n\t\toperand->expr = call;\n\t\treturn ok;\n\t}\n\n\tswitch (id) {\n\tdefault:\n\t\tGB_PANIC(\"Implement built-in procedure: %.*s\", LIT(builtin_name));\n\t\tbreak;\n\n\tcase BuiltinProc_objc_send:\n\tcase BuiltinProc_objc_find_selector: \n\tcase BuiltinProc_objc_find_class: \n\tcase BuiltinProc_objc_register_selector: \n\tcase BuiltinProc_objc_register_class: \n\t\treturn check_builtin_objc_procedure(c, operand, call, id, type_hint);\n\n\tcase BuiltinProc___entry_point:\n\t\toperand->mode = Addressing_NoValue;\n\t\toperand->type = nullptr;\n\t\tmpmc_enqueue(&c->info->intrinsics_entry_point_usage, call);\n\t\tbreak;\n\n\tcase BuiltinProc_DIRECTIVE: {\n\t\tast_node(bd, BasicDirective, ce->proc);\n\t\tString name = bd->name.string;\n\t\tif (name == \"location\") {\n\t\t\tif (ce->args.count > 1) {\n\t\t\t\terror(ce->args[0], \"'#location' expects either 0 or 1 arguments, got %td\", ce->args.count);\n\t\t\t}\n\t\t\tif (ce->args.count > 0) {\n\t\t\t\tAst *arg = ce->args[0];\n\t\t\t\tEntity *e = nullptr;\n\t\t\t\tOperand o = {};\n\t\t\t\tif (arg->kind == Ast_Ident) {\n\t\t\t\t\te = check_ident(c, &o, arg, nullptr, nullptr, true);\n\t\t\t\t} else if (arg->kind == Ast_SelectorExpr) {\n\t\t\t\t\te = check_selector(c, &o, arg, nullptr);\n\t\t\t\t}\n\t\t\t\tif (e == nullptr) {\n\t\t\t\t\terror(ce->args[0], \"'#location' expected a valid entity name\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toperand->type = t_source_code_location;\n\t\t\toperand->mode = Addressing_Value;\n\t\t} else if (name == \"load\") {\n\t\t\tif (ce->args.count != 1) {\n\t\t\t\tif (ce->args.count == 0) {\n\t\t\t\t\terror(ce->close, \"'#load' expects 1 argument, got 0\");\n\t\t\t\t} else {\n\t\t\t\t\terror(ce->args[0], \"'#load' expects 1 argument, got %td\", ce->args.count);\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tAst *arg = ce->args[0];\n\t\t\tOperand o = {};\n\t\t\tcheck_expr(c, &o, arg);\n\t\t\tif (o.mode != Addressing_Constant) {\n\t\t\t\terror(arg, \"'#load' expected a constant string argument\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!is_type_string(o.type)) {\n\t\t\t\tgbString str = type_to_string(o.type);\n\t\t\t\terror(arg, \"'#load' expected a constant string, got %s\", str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tgbAllocator a = heap_allocator();\n\n\t\t\tGB_ASSERT(o.value.kind == ExactValue_String);\n\t\t\tString base_dir = dir_from_path(get_file_path_string(bd->token.pos.file_id));\n\t\t\tString original_string = o.value.value_string;\n\n\n\t\t\tBlockingMutex *ignore_mutex = nullptr;\n\t\t\tString path = {};\n\t\t\tbool ok = determine_path_from_string(ignore_mutex, call, base_dir, original_string, &path);\n\t\t\tgb_unused(ok);\n\n\t\t\tchar *c_str = alloc_cstring(a, path);\n\t\t\tdefer (gb_free(a, c_str));\n\n\n\t\t\tgbFile f = {};\n\t\t\tgbFileError file_err = gb_file_open(&f, c_str);\n\t\t\tdefer (gb_file_close(&f));\n\n\t\t\tswitch (file_err) {\n\t\t\tdefault:\n\t\t\tcase gbFileError_Invalid:\n\t\t\t\terror(ce->proc, \"Failed to `#load` file: %s; invalid file or cannot be found\", c_str);\n\t\t\t\treturn false;\n\t\t\tcase gbFileError_NotExists:\n\t\t\t\terror(ce->proc, \"Failed to `#load` file: %s; file cannot be found\", c_str);\n\t\t\t\treturn false;\n\t\t\tcase gbFileError_Permission:\n\t\t\t\terror(ce->proc, \"Failed to `#load` file: %s; file permissions problem\", c_str);\n\t\t\t\treturn false;\n\t\t\tcase gbFileError_None:\n\t\t\t\t\/\/ Okay\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tString result = {};\n\t\t\tisize file_size = cast(isize)gb_file_size(&f);\n\t\t\tif (file_size > 0) {\n\t\t\t\tu8 *data = cast(u8 *)gb_alloc(a, file_size+1);\n\t\t\t\tgb_file_read_at(&f, data, file_size, 0);\n\t\t\t\tdata[file_size] = '\\0';\n\t\t\t\tresult.text = data;\n\t\t\t\tresult.len = file_size;\n\t\t\t}\n\n\t\t\toperand->type = t_u8_slice;\n\t\t\toperand->mode = Addressing_Constant;\n\t\t\toperand->value = exact_value_string(result);\n\n\t\t} else if (name == \"load_hash\") {\n\t\t\tif (ce->args.count != 2) {\n\t\t\t\tif (ce->args.count == 0) {\n\t\t\t\t\terror(ce->close, \"'#load_hash' expects 2 argument, got 0\");\n\t\t\t\t} else {\n\t\t\t\t\terror(ce->args[0], \"'#load_hash' expects 2 argument, got %td\", ce->args.count);\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tAst *arg0 = ce->args[0];\n\t\t\tAst *arg1 = ce->args[1];\n\t\t\tOperand o = {};\n\t\t\tcheck_expr(c, &o, arg0);\n\t\t\tif (o.mode != Addressing_Constant) {\n\t\t\t\terror(arg0, \"'#load_hash' expected a constant string argument\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!is_type_string(o.type)) {\n\t\t\t\tgbString str = type_to_string(o.type);\n\t\t\t\terror(arg0, \"'#load_hash' expected a constant string, got %s\", str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tOperand o_hash = {};\n\t\t\tcheck_expr(c, &o_hash, arg1);\n\t\t\tif (o_hash.mode != Addressing_Constant) {\n\t\t\t\terror(arg1, \"'#load_hash' expected a constant string argument\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!is_type_string(o_hash.type)) {\n\t\t\t\tgbString str = type_to_string(o.type);\n\t\t\t\terror(arg1, \"'#load_hash' expected a constant string, got %s\", str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\n\t\t\tgbAllocator a = heap_allocator();\n\n\t\t\tGB_ASSERT(o.value.kind == ExactValue_String);\n\t\t\tGB_ASSERT(o_hash.value.kind == ExactValue_String);\n\t\t\t\n\t\t\tString base_dir = dir_from_path(get_file_path_string(bd->token.pos.file_id));\n\t\t\tString original_string = o.value.value_string;\n\t\t\tString hash_kind = o_hash.value.value_string;\n\t\t\t\n\t\t\tString supported_hashes[] = {\n\t\t\t\tstr_lit(\"adler32\"),\n\t\t\t\tstr_lit(\"crc32\"),\n\t\t\t\tstr_lit(\"crc64\"),\n\t\t\t\tstr_lit(\"fnv32\"),\n\t\t\t\tstr_lit(\"fnv64\"),\n\t\t\t\tstr_lit(\"fnv32a\"),\n\t\t\t\tstr_lit(\"fnv64a\"),\n\t\t\t\tstr_lit(\"murmur32\"),\n\t\t\t\tstr_lit(\"murmur64\"),\n\t\t\t};\n\t\t\t\n\t\t\tbool hash_found = false;\n\t\t\tfor (isize i = 0; i < gb_count_of(supported_hashes); i++) {\n\t\t\t\tif (supported_hashes[i] == hash_kind) {\n\t\t\t\t\thash_found = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!hash_found) {\n\t\t\t\tERROR_BLOCK();\n\t\t\t\terror(ce->proc, \"Invalid hash kind passed to `#load_hash`, got: %.*s\", LIT(hash_kind));\n\t\t\t\terror_line(\"\\tAvailable hash kinds:\\n\");\n\t\t\t\tfor (isize i = 0; i < gb_count_of(supported_hashes); i++) {\n\t\t\t\t\terror_line(\"\\t%.*s\\n\", LIT(supported_hashes[i]));\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\n\t\t\tBlockingMutex *ignore_mutex = nullptr;\n\t\t\tString path = {};\n\t\t\tbool ok = determine_path_from_string(ignore_mutex, call, base_dir, original_string, &path);\n\t\t\tgb_unused(ok);\n\n\t\t\tchar *c_str = alloc_cstring(a, path);\n\t\t\tdefer (gb_free(a, c_str));\n\n\n\t\t\tgbFile f = {};\n\t\t\tgbFileError file_err = gb_file_open(&f, c_str);\n\t\t\tdefer (gb_file_close(&f));\n\n\t\t\tswitch (file_err) {\n\t\t\tdefault:\n\t\t\tcase gbFileError_Invalid:\n\t\t\t\terror(ce->proc, \"Failed to `#load_hash` file: %s; invalid file or cannot be found\", c_str);\n\t\t\t\treturn false;\n\t\t\tcase gbFileError_NotExists:\n\t\t\t\terror(ce->proc, \"Failed to `#load_hash` file: %s; file cannot be found\", c_str);\n\t\t\t\treturn false;\n\t\t\tcase gbFileError_Permission:\n\t\t\t\terror(ce->proc, \"Failed to `#load_hash` file: %s; file permissions problem\", c_str);\n\t\t\t\treturn false;\n\t\t\tcase gbFileError_None:\n\t\t\t\t\/\/ Okay\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ TODO(bill): make these procedures fast :P\n\t\t\t\n\t\t\tu64 hash_value = 0;\n\t\t\tString result = {};\n\t\t\tisize file_size = cast(isize)gb_file_size(&f);\n\t\t\tif (file_size > 0) {\n\t\t\t\tu8 *data = cast(u8 *)gb_alloc(a, file_size);\n\t\t\t\tgb_file_read_at(&f, data, file_size, 0);\n\t\t\t\tif (hash_kind == \"adler32\") {\n\t\t\t\t\thash_value = gb_adler32(data, file_size);\n\t\t\t\t} else if (hash_kind == \"crc32\") {\n\t\t\t\t\thash_value = gb_crc32(data, file_size);\n\t\t\t\t} else if (hash_kind == \"crc64\") {\n\t\t\t\t\thash_value = gb_crc64(data, file_size);\n\t\t\t\t} else if (hash_kind == \"fnv32\") {\n\t\t\t\t\thash_value = gb_fnv32(data, file_size);\n\t\t\t\t} else if (hash_kind == \"fnv64\") {\n\t\t\t\t\thash_value = gb_fnv64(data, file_size);\n\t\t\t\t} else if (hash_kind == \"fnv32a\") {\n\t\t\t\t\thash_value = fnv32a(data, file_size);\n\t\t\t\t} else if (hash_kind == \"fnv64a\") {\n\t\t\t\t\thash_value = fnv64a(data, file_size);\n\t\t\t\t} else if (hash_kind == \"murmur32\") {\n\t\t\t\t\thash_value = gb_murmur32(data, file_size);\n\t\t\t\t} else if (hash_kind == \"murmur64\") {\n\t\t\t\t\thash_value = gb_murmur64(data, file_size);\n\t\t\t\t} else {\n\t\t\t\t\tcompiler_error(\"unhandled hash kind: %.*s\", LIT(hash_kind));\t\n\t\t\t\t}\n\t\t\t\tgb_free(a, data);\n\t\t\t}\n\n\t\t\toperand->type = t_untyped_integer;\n\t\t\toperand->mode = Addressing_Constant;\n\t\t\toperand->value = exact_value_u64(hash_value);\n\n\t\t} else if (name == \"load_or\") {\n\t\t\tif (ce->args.count != 2) {\n\t\t\t\tif (ce->args.count == 0) {\n\t\t\t\t\terror(ce->close, \"'#load_or' expects 2 arguments, got 0\");\n\t\t\t\t} else {\n\t\t\t\t\terror(ce->args[0], \"'#load_or' expects 2 arguments, got %td\", ce->args.count);\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tAst *arg = ce->args[0];\n\t\t\tOperand o = {};\n\t\t\tcheck_expr(c, &o, arg);\n\t\t\tif (o.mode != Addressing_Constant) {\n\t\t\t\terror(arg, \"'#load_or' expected a constant string argument\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!is_type_string(o.type)) {\n\t\t\t\tgbString str = type_to_string(o.type);\n\t\t\t\terror(arg, \"'#load_or' expected a constant string, got %s\", str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tAst *default_arg = ce->args[1];\n\t\t\tOperand default_op = {};\n\t\t\tcheck_expr_with_type_hint(c, &default_op, default_arg, t_u8_slice);\n\t\t\tif (default_op.mode != Addressing_Constant) {\n\t\t\t\terror(arg, \"'#load_or' expected a constant '[]byte' argument\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!are_types_identical(base_type(default_op.type), t_u8_slice)) {\n\t\t\t\tgbString str = type_to_string(default_op.type);\n\t\t\t\terror(arg, \"'#load_or' expected a constant '[]byte', got %s\", str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tgbAllocator a = heap_allocator();\n\n\t\t\tGB_ASSERT(o.value.kind == ExactValue_String);\n\t\t\tString base_dir = dir_from_path(get_file_path_string(bd->token.pos.file_id));\n\t\t\tString original_string = o.value.value_string;\n\n\n\t\t\tBlockingMutex *ignore_mutex = nullptr;\n\t\t\tString path = {};\n\t\t\tbool ok = determine_path_from_string(ignore_mutex, call, base_dir, original_string, &path);\n\t\t\tgb_unused(ok);\n\n\t\t\tchar *c_str = alloc_cstring(a, path);\n\t\t\tdefer (gb_free(a, c_str));\n\n\n\t\t\tgbFile f = {};\n\t\t\tgbFileError file_err = gb_file_open(&f, c_str);\n\t\t\tdefer (gb_file_close(&f));\n\t\t\t\n\t\t\toperand->type = t_u8_slice;\n\t\t\toperand->mode = Addressing_Constant;\n\t\t\tif (file_err == gbFileError_None) {\n\t\t\t\tString result = {};\n\t\t\t\tisize file_size = cast(isize)gb_file_size(&f);\n\t\t\t\tif (file_size > 0) {\n\t\t\t\t\tu8 *data = cast(u8 *)gb_alloc(a, file_size+1);\n\t\t\t\t\tgb_file_read_at(&f, data, file_size, 0);\n\t\t\t\t\tdata[file_size] = '\\0';\n\t\t\t\t\tresult.text = data;\n\t\t\t\t\tresult.len = file_size;\n\t\t\t\t}\n\n\t\t\t\toperand->value = exact_value_string(result);\n\t\t\t} else {\n\t\t\t\toperand->value = default_op.value;\n\t\t\t}\n\n\t\t} else if (name == \"assert\") {\n\t\t\tif (ce->args.count != 1 && ce->args.count != 2) {\n\t\t\t\terror(call, \"'#assert' expects either 1 or 2 arguments, got %td\", ce->args.count);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_boolean(operand->type) || operand->mode != Addressing_Constant) {\n\t\t\t\tgbString str = expr_to_string(ce->args[0]);\n\t\t\t\terror(call, \"'%s' is not a constant boolean\", str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (ce->args.count == 2) {\n\t\t\t\tAst *arg = unparen_expr(ce->args[1]);\n\t\t\t\tif (arg == nullptr || arg->kind != Ast_BasicLit || arg->BasicLit.token.kind != Token_String) {\n\t\t\t\t\tgbString str = expr_to_string(arg);\n\t\t\t\t\terror(call, \"'%s' is not a constant string\", str);\n\t\t\t\t\tgb_string_free(str);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!operand->value.value_bool) {\n\t\t\t\tgbString arg1 = expr_to_string(ce->args[0]);\n\t\t\t\tgbString arg2 = {};\n\n\t\t\t\tif (ce->args.count == 1) {\n\t\t\t\t\terror(call, \"Compile time assertion: %s\", arg1);\n\t\t\t\t} else {\n\t\t\t\t\targ2 = expr_to_string(ce->args[1]);\n\t\t\t\t\terror(call, \"Compile time assertion: %s (%s)\", arg1, arg2);\n\t\t\t\t}\t\t\t\n\t\t\t\t\n\t\t\t\tif (c->proc_name != \"\") {\n\t\t\t\t\tgbString str = type_to_string(c->curr_proc_sig);\n\t\t\t\t\terror_line(\"\\tCalled within '%.*s' :: %s\\n\", LIT(c->proc_name), str);\n\t\t\t\t\tgb_string_free(str);\n\t\t\t\t}\n\n\t\t\t\tgb_string_free(arg1);\n\t\t\t\tif (ce->args.count == 2) {\n\t\t\t\t\tgb_string_free(arg2);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toperand->type = t_untyped_bool;\n\t\t\toperand->mode = Addressing_Constant;\n\t\t} else if (name == \"panic\") {\n\t\t\tif (ce->args.count != 1) {\n\t\t\t\terror(call, \"'#panic' expects 1 argument, got %td\", ce->args.count);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_string(operand->type) && operand->mode != Addressing_Constant) {\n\t\t\t\tgbString str = expr_to_string(ce->args[0]);\n\t\t\t\terror(call, \"'%s' is not a constant string\", str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\terror(call, \"Compile time panic: %.*s\", LIT(operand->value.value_string));\n\t\t\tif (c->proc_name != \"\") {\n\t\t\t\tgbString str = type_to_string(c->curr_proc_sig);\n\t\t\t\terror_line(\"\\tCalled within '%.*s' :: %s\\n\", LIT(c->proc_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t}\n\t\t\toperand->type = t_invalid;\n\t\t\toperand->mode = Addressing_NoValue;\n\t\t} else if (name == \"defined\") {\n\t\t\tif (ce->args.count != 1) {\n\t\t\t\terror(call, \"'#defined' expects 1 argument, got %td\", ce->args.count);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tAst *arg = unparen_expr(ce->args[0]);\n\t\t\tif (arg == nullptr || (arg->kind != Ast_Ident && arg->kind != Ast_SelectorExpr)) {\n\t\t\t\terror(call, \"'#defined' expects an identifier or selector expression, got %.*s\", LIT(ast_strings[arg->kind]));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (c->curr_proc_decl == nullptr) {\n\t\t\t\terror(call, \"'#defined' is only allowed within a procedure, prefer the replacement '#config(NAME, default_value)'\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tbool is_defined = check_identifier_exists(c->scope, arg);\n\t\t\tgb_unused(is_defined);\n\t\t\toperand->type = t_untyped_bool;\n\t\t\toperand->mode = Addressing_Constant;\n\t\t\toperand->value = exact_value_bool(false);\n\n\t\t} else if (name == \"config\") {\n\t\t\tif (ce->args.count != 2) {\n\t\t\t\terror(call, \"'#config' expects 2 argument, got %td\", ce->args.count);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tAst *arg = unparen_expr(ce->args[0]);\n\t\t\tif (arg == nullptr || arg->kind != Ast_Ident) {\n\t\t\t\terror(call, \"'#config' expects an identifier, got %.*s\", LIT(ast_strings[arg->kind]));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tAst *def_arg = unparen_expr(ce->args[1]);\n\n\t\t\tOperand def = {};\n\t\t\tcheck_expr(c, &def, def_arg);\n\t\t\tif (def.mode != Addressing_Constant) {\n\t\t\t\terror(def_arg, \"'#config' default value must be a constant\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tString name = arg->Ident.token.string;\n\n\n\t\t\toperand->type = def.type;\n\t\t\toperand->mode = def.mode;\n\t\t\toperand->value = def.value;\n\n\t\t\tEntity *found = scope_lookup_current(config_pkg->scope, name);\n\t\t\tif (found != nullptr) {\n\t\t\t\tif (found->kind != Entity_Constant) {\n\t\t\t\t\terror(arg, \"'#config' entity '%.*s' found but expected a constant\", LIT(name));\n\t\t\t\t} else {\n\t\t\t\t\toperand->type = found->type;\n\t\t\t\t\toperand->mode = Addressing_Constant;\n\t\t\t\t\toperand->value = found->Constant.value;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\terror(call, \"Unknown directive call: #%.*s\", LIT(name));\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_len:\n\t\tcheck_expr_or_type(c, operand, ce->args[0]);\n\t\tif (operand->mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\t\/* fallthrough *\/\n\n\tcase BuiltinProc_cap:\n\t{\n\t\t\/\/ len :: proc(Type) -> int\n\t\t\/\/ cap :: proc(Type) -> int\n\n\t\tType *op_type = type_deref(operand->type);\n\t\tType *type = t_int;\n\t\tif (type_hint != nullptr) {\n\t\t\tType *bt = type_hint;\n\t\t\t\/\/ bt = base_type(bt);\n\t\t\tif (bt == t_int) {\n\t\t\t\ttype = type_hint;\n\t\t\t} else if (bt == t_uint) {\n\t\t\t\ttype = type_hint;\n\t\t\t}\n\t\t}\n\n\t\tAddressingMode mode = Addressing_Invalid;\n\t\tExactValue value = {};\n\t\tif (is_type_string(op_type) && id == BuiltinProc_len) {\n\t\t\tif (operand->mode == Addressing_Constant) {\n\t\t\t\tmode = Addressing_Constant;\n\t\t\t\tString str = operand->value.value_string;\n\t\t\t\tvalue = exact_value_i64(str.len);\n\t\t\t\ttype = t_untyped_integer;\n\t\t\t} else {\n\t\t\t\tmode = Addressing_Value;\n\t\t\t\tif (is_type_cstring(op_type)) {\n\t\t\t\t\tadd_package_dependency(c, \"runtime\", \"cstring_len\");\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (is_type_array(op_type)) {\n\t\t\tType *at = core_type(op_type);\n\t\t\tmode = Addressing_Constant;\n\t\t\tvalue = exact_value_i64(at->Array.count);\n\t\t\ttype = t_untyped_integer;\n\t\t} else if (is_type_enumerated_array(op_type) && id == BuiltinProc_len) {\n\t\t\tType *at = core_type(op_type);\n\t\t\tmode = Addressing_Constant;\n\t\t\tvalue = exact_value_i64(at->EnumeratedArray.count);\n\t\t\ttype = t_untyped_integer;\n\t\t} else if ((is_type_slice(op_type) || is_type_relative_slice(op_type)) && id == BuiltinProc_len) {\n\t\t\tmode = Addressing_Value;\n\t\t} else if (is_type_dynamic_array(op_type)) {\n\t\t\tmode = Addressing_Value;\n\t\t} else if (is_type_map(op_type)) {\n\t\t\tmode = Addressing_Value;\n\t\t} else if (operand->mode == Addressing_Type && is_type_enum(op_type) && id == BuiltinProc_len) {\n\t\t\tType *bt = base_type(op_type);\n\t\t\tmode  = Addressing_Constant;\n\t\t\tvalue = exact_value_i64(bt->Enum.fields.count);\n\t\t\ttype  = t_untyped_integer;\n\t\t} else if (is_type_struct(op_type)) {\n\t\t\tType *bt = base_type(op_type);\n\t\t\tif (bt->Struct.soa_kind == StructSoa_Fixed) {\n\t\t\t\tmode  = Addressing_Constant;\n\t\t\t\tvalue = exact_value_i64(bt->Struct.soa_count);\n\t\t\t\ttype  = t_untyped_integer;\n\t\t\t} else if ((bt->Struct.soa_kind == StructSoa_Slice && id == BuiltinProc_len) ||\n\t\t\t           bt->Struct.soa_kind == StructSoa_Dynamic) {\n\t\t\t\tmode = Addressing_Value;\n\t\t\t}\n\t\t} else if (is_type_simd_vector(op_type)) {\n\t\t\tType *bt = base_type(op_type);\n\t\t\tmode  = Addressing_Constant;\n\t\t\tvalue = exact_value_i64(bt->SimdVector.count);\n\t\t\ttype  = t_untyped_integer;\n\t\t}\n\t\tif (operand->mode == Addressing_Type && mode != Addressing_Constant) {\n\t\t\tmode = Addressing_Invalid;\n\t\t}\n\n\t\tif (mode == Addressing_Invalid) {\n\t\t\tgbString t = type_to_string(operand->type);\n\t\t\terror(call, \"'%.*s' is not supported for '%s'\", LIT(builtin_name), t);\n\t\t\treturn false;\n\t\t}\n\n\t\toperand->mode  = mode;\n\t\toperand->value = value;\n\t\toperand->type  = type;\n\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_size_of: {\n\t\t\/\/ size_of :: proc(Type or expr) -> untyped int\n\t\tOperand o = {};\n\t\tcheck_expr_or_type(c, &o, ce->args[0]);\n\t\tif (o.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tType *t = o.type;\n\t\tif (t == nullptr || t == t_invalid) {\n\t\t\terror(ce->args[0], \"Invalid argument for 'size_of'\");\n\t\t\treturn false;\n\t\t}\n\t\tt = default_type(t);\n\n\t\toperand->mode = Addressing_Constant;\n\t\toperand->value = exact_value_i64(type_size_of(t));\n\t\toperand->type = t_untyped_integer;\n\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_align_of: {\n\t\t\/\/ align_of :: proc(Type or expr) -> untyped int\n\t\tOperand o = {};\n\t\tcheck_expr_or_type(c, &o, ce->args[0]);\n\t\tif (o.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tType *t = o.type;\n\t\tif (t == nullptr || t == t_invalid) {\n\t\t\terror(ce->args[0], \"Invalid argument for 'align_of'\");\n\t\t\treturn false;\n\t\t}\n\t\tt = default_type(t);\n\n\t\toperand->mode = Addressing_Constant;\n\t\toperand->value = exact_value_i64(type_align_of(t));\n\t\toperand->type = t_untyped_integer;\n\n\t\tbreak;\n\t}\n\n\n\tcase BuiltinProc_offset_of: {\n\t\t\/\/ offset_of :: proc(value.field) -> uintptr\n\t\t\/\/ offset_of :: proc(Type, field) -> uintptr\n\n\t\tType *type = nullptr;\n\t\tAst *field_arg = nullptr;\n\n\t\tif (ce->args.count == 1) {\n\t\t\tAst *arg0 = unparen_expr(ce->args[0]);\n\t\t\tif (arg0->kind != Ast_SelectorExpr) {\n\t\t\t\tgbString x = expr_to_string(arg0);\n\t\t\t\terror(ce->args[0], \"Invalid expression for '%.*s', '%s' is not a selector expression\", LIT(builtin_name), x);\n\t\t\t\tgb_string_free(x);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tast_node(se, SelectorExpr, arg0);\n\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, se->expr);\n\t\t\tif (x.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\ttype = type_deref(x.type);\n\n\t\t\tType *bt = base_type(type);\n\t\t\tif (bt == nullptr || bt == t_invalid) {\n\t\t\t\terror(ce->args[0], \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfield_arg = unparen_expr(se->selector);\n\t\t} else if (ce->args.count == 2) {\n\t\t\ttype = check_type(c, ce->args[0]);\n\t\t\tType *bt = base_type(type);\n\t\t\tif (bt == nullptr || bt == t_invalid) {\n\t\t\t\terror(ce->args[0], \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfield_arg = unparen_expr(ce->args[1]);\n\t\t} else {\n\t\t\terror(ce->args[0], \"Expected either 1 or 2 arguments to '%.*s', in the format of '%.*s(Type, field)', '%.*s(value.field)'\", LIT(builtin_name), LIT(builtin_name), LIT(builtin_name));\n\t\t\treturn false;\n\t\t}\n\t\tGB_ASSERT(type != nullptr);\n\t\t\n\t\tString field_name = {};\n\t\t\n\t\tif (field_arg == nullptr) {\n\t\t\terror(call, \"Expected an identifier for field argument\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (field_arg->kind == Ast_Ident) {\n\t\t\tfield_name = field_arg->Ident.token.string;\n\t\t}\n\t\tif (field_name.len == 0) {\n\t\t\terror(field_arg, \"Expected an identifier for field argument\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\n\t\tif (is_type_array(type)) {\n\t\t\tgbString t = type_to_string(type);\n\t\t\terror(field_arg, \"Invalid a struct type for '%.*s', got '%s'\", LIT(builtin_name), t);\n\t\t\tgb_string_free(t);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tSelection sel = lookup_field(type, field_name, false);\n\t\tif (sel.entity == nullptr) {\n\t\t\tgbString type_str = type_to_string_shorthand(type);\n\t\t\terror(ce->args[0],\n\t\t\t      \"'%s' has no field named '%.*s'\", type_str, LIT(field_name));\n\t\t\tgb_string_free(type_str);\n\n\t\t\tType *bt = base_type(type);\n\t\t\tif (bt->kind == Type_Struct) {\n\t\t\t\tcheck_did_you_mean_type(field_name, bt->Struct.fields);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tif (sel.indirect) {\n\t\t\tgbString type_str = type_to_string_shorthand(type);\n\t\t\terror(ce->args[0],\n\t\t\t      \"Field '%.*s' is embedded via a pointer in '%s'\", LIT(field_name), type_str);\n\t\t\tgb_string_free(type_str);\n\t\t\treturn false;\n\t\t}\n\n\t\toperand->mode = Addressing_Constant;\n\t\toperand->value = exact_value_i64(type_offset_of_from_selection(type, sel));\n\t\toperand->type  = t_uintptr;\n\t\tbreak;\n\t}\n\t\n\tcase BuiltinProc_offset_of_by_string: {\n\t\t\/\/ offset_of_by_string :: proc(Type, string) -> uintptr\n\n\t\tType *type = nullptr;\n\t\tAst *field_arg = nullptr;\n\n\t\tif (ce->args.count == 2) {\n\t\t\ttype = check_type(c, ce->args[0]);\n\t\t\tType *bt = base_type(type);\n\t\t\tif (bt == nullptr || bt == t_invalid) {\n\t\t\t\terror(ce->args[0], \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfield_arg = unparen_expr(ce->args[1]);\n\t\t} else {\n\t\t\terror(ce->args[0], \"Expected either 2 arguments to '%.*s', in the format of '%.*s(Type, field)'\", LIT(builtin_name), LIT(builtin_name));\n\t\t\treturn false;\n\t\t}\n\t\tGB_ASSERT(type != nullptr);\n\t\t\n\t\tString field_name = {};\n\t\t\n\t\tif (field_arg == nullptr) {\n\t\t\terror(call, \"Expected a constant (not-empty) string for field argument\");\n\t\t\treturn false;\n\t\t}\n\n\t\tOperand x = {};\n\t\tcheck_expr(c, &x, field_arg);\n\t\tif (x.mode == Addressing_Constant && x.value.kind == ExactValue_String) {\n\t\t\tfield_name = x.value.value_string;\n\t\t}\n\t\tif (field_name.len == 0) {\n\t\t\terror(field_arg, \"Expected a constant (non-empty) string for field argument\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\n\t\tif (is_type_array(type)) {\n\t\t\tgbString t = type_to_string(type);\n\t\t\terror(field_arg, \"Invalid a struct type for '%.*s', got '%s'\", LIT(builtin_name), t);\n\t\t\tgb_string_free(t);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tSelection sel = lookup_field(type, field_name, false);\n\t\tif (sel.entity == nullptr) {\n\t\t\tgbString type_str = type_to_string_shorthand(type);\n\t\t\terror(ce->args[0],\n\t\t\t      \"'%s' has no field named '%.*s'\", type_str, LIT(field_name));\n\t\t\tgb_string_free(type_str);\n\n\t\t\tType *bt = base_type(type);\n\t\t\tif (bt->kind == Type_Struct) {\n\t\t\t\tcheck_did_you_mean_type(field_name, bt->Struct.fields);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tif (sel.indirect) {\n\t\t\tgbString type_str = type_to_string_shorthand(type);\n\t\t\terror(ce->args[0],\n\t\t\t      \"Field '%.*s' is embedded via a pointer in '%s'\", LIT(field_name), type_str);\n\t\t\tgb_string_free(type_str);\n\t\t\treturn false;\n\t\t}\n\n\t\toperand->mode = Addressing_Constant;\n\t\toperand->value = exact_value_i64(type_offset_of_from_selection(type, sel));\n\t\toperand->type  = t_uintptr;\n\t\tbreak;\n\t}\n\n\n\tcase BuiltinProc_type_of: {\n\t\t\/\/ type_of :: proc(val: Type) -> type(Type)\n\t\tAst *expr = ce->args[0];\n\t\tOperand o = {};\n\t\tcheck_expr_or_type(c, &o, expr);\n\n\t\t\/\/ check_assignment(c, operand, nullptr, str_lit(\"argument of 'type_of'\"));\n\t\tif (o.mode == Addressing_Invalid || o.mode == Addressing_Builtin) {\n\t\t\treturn false;\n\t\t}\n\t\tif (o.type == nullptr || o.type == t_invalid || is_type_asm_proc(o.type)) {\n\t\t\terror(o.expr, \"Invalid argument to 'type_of'\");\n\t\t\treturn false;\n\t\t}\n\t\t\/\/ NOTE(bill): Prevent type cycles for procedure declarations\n\t\tif (c->curr_proc_sig == o.type) {\n\t\t\tgbString s = expr_to_string(o.expr);\n\t\t\terror(o.expr, \"Invalid cyclic type usage from 'type_of', got '%s'\", s);\n\t\t\tgb_string_free(s);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (is_type_polymorphic(o.type)) {\n\t\t\terror(o.expr, \"'type_of' of polymorphic type cannot be determined\");\n\t\t\treturn false;\n\t\t}\n\t\toperand->mode = Addressing_Type;\n\t\toperand->type = o.type;\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_type_info_of: {\n\t\t\/\/ type_info_of :: proc(Type) -> ^Type_Info\n\t\tif (c->scope->flags&ScopeFlag_Global) {\n\t\t\tcompiler_error(\"'type_info_of' Cannot be declared within the runtime package due to how the internals of the compiler works\");\n\t\t}\n\t\tif (build_context.disallow_rtti) {\n\t\t\terror(call, \"'%.*s' has been disallowed\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ NOTE(bill): The type information may not be setup yet\n\t\tinit_core_type_info(c->checker);\n\t\tAst *expr = ce->args[0];\n\t\tOperand o = {};\n\t\tcheck_expr_or_type(c, &o, expr);\n\t\tif (o.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tType *t = o.type;\n\t\tif (t == nullptr || t == t_invalid || is_type_asm_proc(o.type) || is_type_polymorphic(t)) {\n\t\t\tif (is_type_polymorphic(t)) {\n\t\t\t\terror(ce->args[0], \"Invalid argument for '%.*s', unspecialized polymorphic type\", LIT(builtin_name));\n\t\t\t} else {\n\t\t\t\terror(ce->args[0], \"Invalid argument for '%.*s'\", LIT(builtin_name));\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tt = default_type(t);\n\n\t\tadd_type_info_type(c, t);\n\n\t\tif (is_operand_value(o) && is_type_typeid(t)) {\n\t\t\tadd_package_dependency(c, \"runtime\", \"__type_info_of\");\n\t\t} else if (o.mode != Addressing_Type) {\n\t\t\terror(expr, \"Expected a type or typeid for '%.*s'\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t}\n\n\t\toperand->mode = Addressing_Value;\n\t\toperand->type = t_type_info_ptr;\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_typeid_of: {\n\t\t\/\/ typeid_of :: proc(Type) -> typeid\n\t\tif (c->scope->flags&ScopeFlag_Global) {\n\t\t\tcompiler_error(\"'typeid_of' Cannot be declared within the runtime package due to how the internals of the compiler works\");\n\t\t}\n\t\tif (build_context.disallow_rtti) {\n\t\t\terror(call, \"'%.*s' has been disallowed\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ NOTE(bill): The type information may not be setup yet\n\t\tinit_core_type_info(c->checker);\n\t\tAst *expr = ce->args[0];\n\t\tOperand o = {};\n\t\tcheck_expr_or_type(c, &o, expr);\n\t\tif (o.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tType *t = o.type;\n\t\tif (t == nullptr || t == t_invalid || is_type_asm_proc(o.type) || is_type_polymorphic(operand->type)) {\n\t\t\terror(ce->args[0], \"Invalid argument for '%.*s'\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t}\n\t\tt = default_type(t);\n\n\t\tadd_type_info_type(c, t);\n\n\t\tif (o.mode != Addressing_Type) {\n\t\t\terror(expr, \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t}\n\n\t\toperand->mode = Addressing_Value;\n\t\toperand->type = t_typeid;\n\t\toperand->value = exact_value_typeid(t);\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_swizzle: {\n\t\t\/\/ swizzle :: proc(v: [N]T, ..int) -> [M]T\n\t\tType *original_type = operand->type;\n\t\tType *type = base_type(original_type);\n\t\ti64 max_count = 0;\n\t\tType *elem_type = nullptr;\n\n\t\tif (!is_type_array(type) && !is_type_simd_vector(type)) {\n\t\t\tgbString type_str = type_to_string(operand->type);\n\t\t\terror(call,\n\t\t\t      \"'swizzle' is only allowed on an array or #simd vector, got '%s'\",\n\t\t\t      type_str);\n\t\t\tgb_string_free(type_str);\n\t\t\treturn false;\n\t\t}\n\t\tif (type->kind == Type_Array) {\n\t\t\tmax_count = type->Array.count;\n\t\t\telem_type = type->Array.elem;\n\t\t} else if (type->kind == Type_SimdVector) {\n\t\t\tmax_count = type->SimdVector.count;\n\t\t\telem_type = type->SimdVector.elem;\n\t\t}\n\n\t\ti64 arg_count = 0;\n\t\tfor_array(i, ce->args) {\n\t\t\tif (i == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tAst *arg = ce->args[i];\n\t\t\tOperand op = {};\n\t\t\tcheck_expr(c, &op, arg);\n\t\t\tif (op.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *arg_type = base_type(op.type);\n\t\t\tif (!is_type_integer(arg_type) || op.mode != Addressing_Constant) {\n\t\t\t\terror(op.expr, \"Indices to 'swizzle' must be constant integers\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (big_int_is_neg(&op.value.value_integer)) {\n\t\t\t\terror(op.expr, \"Negative 'swizzle' index\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tBigInt mc = {};\n\t\t\tbig_int_from_i64(&mc, max_count);\n\t\t\tif (big_int_cmp(&mc, &op.value.value_integer) <= 0) {\n\t\t\t\terror(op.expr, \"'swizzle' index exceeds length\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\targ_count++;\n\t\t}\n\n\t\tif (arg_count > max_count) {\n\t\t\terror(call, \"Too many 'swizzle' indices, %td > %td\", arg_count, max_count);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (type->kind == Type_Array) {\n\t\t\tif (operand->mode == Addressing_Variable) {\n\t\t\t\toperand->mode = Addressing_SwizzleVariable;\n\t\t\t} else {\n\t\t\t\toperand->mode = Addressing_SwizzleValue;\n\t\t\t}\n\t\t} else {\n\t\t\toperand->mode = Addressing_Value;\n\t\t}\n\n\t\tif (is_type_simd_vector(type) && !is_power_of_two(arg_count)) {\n\t\t\terror(call, \"'swizzle' with a #simd vector must have a power of two arguments, got %lld\", cast(long long)arg_count);\n\t\t\treturn false;\n\t\t}\n\n\t\toperand->type = determine_swizzle_array_type(original_type, type_hint, arg_count);\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_complex: {\n\t\t\/\/ complex :: proc(real, imag: float_type) -> complex_type\n\t\tOperand x = *operand;\n\t\tOperand y = {};\n\n\t\t\/\/ NOTE(bill): Invalid will be the default till fixed\n\t\toperand->type = t_invalid;\n\t\toperand->mode = Addressing_Invalid;\n\n\t\tcheck_expr(c, &y, ce->args[1]);\n\t\tif (y.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconvert_to_typed(c, &x, y.type); if (x.mode == Addressing_Invalid) return false;\n\t\tconvert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;\n\t\tif (x.mode == Addressing_Constant &&\n\t\t    y.mode == Addressing_Constant) {\n\t\t\tx.value = exact_value_to_float(x.value);\n\t\t    \ty.value = exact_value_to_float(y.value);\n\t\t\tif (is_type_numeric(x.type) && x.value.kind == ExactValue_Float) {\n\t\t\t\tx.type = t_untyped_float;\n\t\t\t}\n\t\t\tif (is_type_numeric(y.type) && y.value.kind == ExactValue_Float) {\n\t\t\t\ty.type = t_untyped_float;\n\t\t\t}\n\t\t}\n\n\t\tif (!are_types_identical(x.type, y.type)) {\n\t\t\tgbString tx = type_to_string(x.type);\n\t\t\tgbString ty = type_to_string(y.type);\n\t\t\terror(call, \"Mismatched types to 'complex', '%s' vs '%s'\", tx, ty);\n\t\t\tgb_string_free(ty);\n\t\t\tgb_string_free(tx);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!is_type_float(x.type)) {\n\t\t\tgbString s = type_to_string(x.type);\n\t\t\terror(call, \"Arguments have type '%s', expected a floating point\", s);\n\t\t\tgb_string_free(s);\n\t\t\treturn false;\n\t\t}\n\t\tif (is_type_endian_specific(x.type)) {\n\t\t\tgbString s = type_to_string(x.type);\n\t\t\terror(call, \"Arguments with a specified endian are not allow, expected a normal floating point, got '%s'\", s);\n\t\t\tgb_string_free(s);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (x.mode == Addressing_Constant && y.mode == Addressing_Constant) {\n\t\t\tf64 r = exact_value_to_float(x.value).value_float;\n\t\t\tf64 i = exact_value_to_float(y.value).value_float;\n\t\t\toperand->value = exact_value_complex(r, i);\n\t\t\toperand->mode = Addressing_Constant;\n\t\t} else {\n\t\t\toperand->mode = Addressing_Value;\n\t\t}\n\n\t\tBasicKind kind = core_type(x.type)->Basic.kind;\n\t\tswitch (kind) {\n\t\tcase Basic_f16:          operand->type = t_complex32;       break;\n\t\tcase Basic_f32:          operand->type = t_complex64;       break;\n\t\tcase Basic_f64:          operand->type = t_complex128;      break;\n\t\tcase Basic_UntypedFloat: operand->type = t_untyped_complex; break;\n\t\tdefault: GB_PANIC(\"Invalid type\"); break;\n\t\t}\n\n\t\tif (type_hint != nullptr && check_is_castable_to(c, operand, type_hint)) {\n\t\t\toperand->type = type_hint;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_quaternion: {\n\t\t\/\/ quaternion :: proc(real, imag, jmag, kmag: float_type) -> complex_type\n\t\tOperand x = *operand;\n\t\tOperand y = {};\n\t\tOperand z = {};\n\t\tOperand w = {};\n\n\t\t\/\/ NOTE(bill): Invalid will be the default till fixed\n\t\toperand->type = t_invalid;\n\t\toperand->mode = Addressing_Invalid;\n\n\t\tcheck_expr(c, &y, ce->args[1]);\n\t\tif (y.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tcheck_expr(c, &z, ce->args[2]);\n\t\tif (y.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tcheck_expr(c, &w, ce->args[3]);\n\t\tif (y.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconvert_to_typed(c, &x, y.type); if (x.mode == Addressing_Invalid) return false;\n\t\tconvert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;\n\t\tconvert_to_typed(c, &z, x.type); if (z.mode == Addressing_Invalid) return false;\n\t\tconvert_to_typed(c, &w, x.type); if (w.mode == Addressing_Invalid) return false;\n\t\tif (x.mode == Addressing_Constant &&\n\t\t    y.mode == Addressing_Constant &&\n\t\t    z.mode == Addressing_Constant &&\n\t\t    w.mode == Addressing_Constant) {\n\t\t    \tx.value = exact_value_to_float(x.value);\n\t\t    \ty.value = exact_value_to_float(y.value);\n\t\t    \tz.value = exact_value_to_float(z.value);\n\t\t    \tw.value = exact_value_to_float(w.value);\n\t\t\tif (is_type_numeric(x.type) && x.value.kind == ExactValue_Float) {\n\t\t\t\tx.type = t_untyped_float;\n\t\t\t}\n\t\t\tif (is_type_numeric(y.type) && y.value.kind == ExactValue_Float) {\n\t\t\t\ty.type = t_untyped_float;\n\t\t\t}\n\t\t\tif (is_type_numeric(z.type) && z.value.kind == ExactValue_Float) {\n\t\t\t\tz.type = t_untyped_float;\n\t\t\t}\n\t\t\tif (is_type_numeric(w.type) && w.value.kind == ExactValue_Float) {\n\t\t\t\tw.type = t_untyped_float;\n\t\t\t}\n\t\t}\n\n\t\tif (!(are_types_identical(x.type, y.type) && are_types_identical(x.type, z.type) && are_types_identical(x.type, w.type))) {\n\t\t\tgbString tx = type_to_string(x.type);\n\t\t\tgbString ty = type_to_string(y.type);\n\t\t\tgbString tz = type_to_string(z.type);\n\t\t\tgbString tw = type_to_string(w.type);\n\t\t\terror(call, \"Mismatched types to 'quaternion', '%s' vs '%s' vs '%s' vs '%s'\", tx, ty, tz, tw);\n\t\t\tgb_string_free(tw);\n\t\t\tgb_string_free(tz);\n\t\t\tgb_string_free(ty);\n\t\t\tgb_string_free(tx);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!is_type_float(x.type)) {\n\t\t\tgbString s = type_to_string(x.type);\n\t\t\terror(call, \"Arguments have type '%s', expected a floating point\", s);\n\t\t\tgb_string_free(s);\n\t\t\treturn false;\n\t\t}\n\t\tif (is_type_endian_specific(x.type)) {\n\t\t\tgbString s = type_to_string(x.type);\n\t\t\terror(call, \"Arguments with a specified endian are not allow, expected a normal floating point, got '%s'\", s);\n\t\t\tgb_string_free(s);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (x.mode == Addressing_Constant && y.mode == Addressing_Constant && z.mode == Addressing_Constant && w.mode == Addressing_Constant) {\n\t\t\tf64 r = exact_value_to_float(x.value).value_float;\n\t\t\tf64 i = exact_value_to_float(y.value).value_float;\n\t\t\tf64 j = exact_value_to_float(z.value).value_float;\n\t\t\tf64 k = exact_value_to_float(w.value).value_float;\n\t\t\toperand->value = exact_value_quaternion(r, i, j, k);\n\t\t\toperand->mode = Addressing_Constant;\n\t\t} else {\n\t\t\toperand->mode = Addressing_Value;\n\t\t}\n\n\t\tBasicKind kind = core_type(x.type)->Basic.kind;\n\t\tswitch (kind) {\n\t\tcase Basic_f16:          operand->type = t_quaternion64;       break;\n\t\tcase Basic_f32:          operand->type = t_quaternion128;      break;\n\t\tcase Basic_f64:          operand->type = t_quaternion256;      break;\n\t\tcase Basic_UntypedFloat: operand->type = t_untyped_quaternion; break;\n\t\tdefault: GB_PANIC(\"Invalid type\"); break;\n\t\t}\n\n\t\tif (type_hint != nullptr && check_is_castable_to(c, operand, type_hint)) {\n\t\t\toperand->type = type_hint;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_real:\n\tcase BuiltinProc_imag: {\n\t\t\/\/ real :: proc(x: type) -> float_type\n\t\t\/\/ imag :: proc(x: type) -> float_type\n\n\t\tOperand *x = operand;\n\t\tif (is_type_untyped(x->type)) {\n\t\t\tif (x->mode == Addressing_Constant) {\n\t\t\t\tif (is_type_numeric(x->type)) {\n\t\t\t\t\tx->type = t_untyped_complex;\n\t\t\t\t}\n\t\t\t} else if (is_type_quaternion(x->type)) {\n\t\t\t\tconvert_to_typed(c, x, t_quaternion256);\n\t\t\t\tif (x->mode == Addressing_Invalid) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t} else{\n\t\t\t\tconvert_to_typed(c, x, t_complex128);\n\t\t\t\tif (x->mode == Addressing_Invalid) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!is_type_complex(x->type) && !is_type_quaternion(x->type)) {\n\t\t\tgbString s = type_to_string(x->type);\n\t\t\terror(call, \"Argument has type '%s', expected a complex or quaternion type\", s);\n\t\t\tgb_string_free(s);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (x->mode == Addressing_Constant) {\n\t\t\tswitch (id) {\n\t\t\tcase BuiltinProc_real: x->value = exact_value_real(x->value); break;\n\t\t\tcase BuiltinProc_imag: x->value = exact_value_imag(x->value); break;\n\t\t\t}\n\t\t} else {\n\t\t\tx->mode = Addressing_Value;\n\t\t}\n\n\t\tBasicKind kind = core_type(x->type)->Basic.kind;\n\t\tswitch (kind) {\n\t\tcase Basic_complex32:         x->type = t_f16;           break;\n\t\tcase Basic_complex64:         x->type = t_f32;           break;\n\t\tcase Basic_complex128:        x->type = t_f64;           break;\n\t\tcase Basic_quaternion64:      x->type = t_f16;           break;\n\t\tcase Basic_quaternion128:     x->type = t_f32;           break;\n\t\tcase Basic_quaternion256:     x->type = t_f64;           break;\n\t\tcase Basic_UntypedComplex:    x->type = t_untyped_float; break;\n\t\tcase Basic_UntypedQuaternion: x->type = t_untyped_float; break;\n\t\tdefault: GB_PANIC(\"Invalid type\"); break;\n\t\t}\n\n\t\tif (type_hint != nullptr && check_is_castable_to(c, operand, type_hint)) {\n\t\t\toperand->type = type_hint;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_jmag:\n\tcase BuiltinProc_kmag: {\n\t\t\/\/ jmag :: proc(x: type) -> float_type\n\t\t\/\/ kmag :: proc(x: type) -> float_type\n\n\t\tOperand *x = operand;\n\t\tif (is_type_untyped(x->type)) {\n\t\t\tif (x->mode == Addressing_Constant) {\n\t\t\t\tif (is_type_numeric(x->type)) {\n\t\t\t\t\tx->type = t_untyped_complex;\n\t\t\t\t}\n\t\t\t} else{\n\t\t\t\tconvert_to_typed(c, x, t_quaternion256);\n\t\t\t\tif (x->mode == Addressing_Invalid) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!is_type_quaternion(x->type)) {\n\t\t\tgbString s = type_to_string(x->type);\n\t\t\terror(call, \"Argument has type '%s', expected a quaternion type\", s);\n\t\t\tgb_string_free(s);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (x->mode == Addressing_Constant) {\n\t\t\tswitch (id) {\n\t\t\tcase BuiltinProc_jmag: x->value = exact_value_jmag(x->value); break;\n\t\t\tcase BuiltinProc_kmag: x->value = exact_value_kmag(x->value); break;\n\t\t\t}\n\t\t} else {\n\t\t\tx->mode = Addressing_Value;\n\t\t}\n\n\t\tBasicKind kind = core_type(x->type)->Basic.kind;\n\t\tswitch (kind) {\n\t\tcase Basic_quaternion64:      x->type = t_f16;           break;\n\t\tcase Basic_quaternion128:     x->type = t_f32;           break;\n\t\tcase Basic_quaternion256:     x->type = t_f64;           break;\n\t\tcase Basic_UntypedComplex:    x->type = t_untyped_float; break;\n\t\tcase Basic_UntypedQuaternion: x->type = t_untyped_float; break;\n\t\tdefault: GB_PANIC(\"Invalid type\"); break;\n\t\t}\n\n\t\tif (type_hint != nullptr && check_is_castable_to(c, operand, type_hint)) {\n\t\t\toperand->type = type_hint;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_conj: {\n\t\t\/\/ conj :: proc(x: type) -> type\n\t\tOperand *x = operand;\n\t\tType *t = x->type;\n\t\tType *elem = core_array_type(t);\n\t\t\n\t\tif (is_type_complex(t)) {\n\t\t\tif (x->mode == Addressing_Constant) {\n\t\t\t\tExactValue v = exact_value_to_complex(x->value);\n\t\t\t\tf64 r = v.value_complex->real;\n\t\t\t\tf64 i = -v.value_complex->imag;\n\t\t\t\tx->value = exact_value_complex(r, i);\n\t\t\t\tx->mode = Addressing_Constant;\n\t\t\t} else {\n\t\t\t\tx->mode = Addressing_Value;\n\t\t\t}\n\t\t} else if (is_type_quaternion(t)) {\n\t\t\tif (x->mode == Addressing_Constant) {\n\t\t\t\tExactValue v = exact_value_to_quaternion(x->value);\n\t\t\t\tf64 r = +v.value_quaternion->real;\n\t\t\t\tf64 i = -v.value_quaternion->imag;\n\t\t\t\tf64 j = -v.value_quaternion->jmag;\n\t\t\t\tf64 k = -v.value_quaternion->kmag;\n\t\t\t\tx->value = exact_value_quaternion(r, i, j, k);\n\t\t\t\tx->mode = Addressing_Constant;\n\t\t\t} else {\n\t\t\t\tx->mode = Addressing_Value;\n\t\t\t}\n\t\t} else if (is_type_array_like(t) && (is_type_complex(elem) || is_type_quaternion(elem))) {\n\t\t\tx->mode = Addressing_Value;\n\t\t} else if (is_type_matrix(t) && (is_type_complex(elem) || is_type_quaternion(elem))) {\n\t\t\tx->mode = Addressing_Value;\n\t\t}else {\n\t\t\tgbString s = type_to_string(x->type);\n\t\t\terror(call, \"Expected a complex or quaternion, got '%s'\", s);\n\t\t\tgb_string_free(s);\n\t\t\treturn false;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_expand_to_tuple: {\n\t\tType *type = base_type(operand->type);\n\t\tif (!is_type_struct(type) && !is_type_array(type)) {\n\t\t\tgbString type_str = type_to_string(operand->type);\n\t\t\terror(call, \"Expected a struct or array type, got '%s'\", type_str);\n\t\t\tgb_string_free(type_str);\n\t\t\treturn false;\n\t\t}\n\t\tgbAllocator a = permanent_allocator();\n\n\t\tType *tuple = alloc_type_tuple();\n\n\t\tif (is_type_struct(type)) {\n\t\t\tisize variable_count = type->Struct.fields.count;\n\t\t\tslice_init(&tuple->Tuple.variables, a, variable_count);\n\t\t\t\/\/ TODO(bill): Should I copy each of the entities or is this good enough?\n\t\t\tgb_memmove_array(tuple->Tuple.variables.data, type->Struct.fields.data, variable_count);\n\t\t} else if (is_type_array(type)) {\n\t\t\tisize variable_count = cast(isize)type->Array.count;\n\t\t\tslice_init(&tuple->Tuple.variables, a, variable_count);\n\t\t\tfor (isize i = 0; i < variable_count; i++) {\n\t\t\t\ttuple->Tuple.variables[i] = alloc_entity_array_elem(nullptr, blank_token, type->Array.elem, cast(i32)i);\n\t\t\t}\n\t\t}\n\t\toperand->type = tuple;\n\t\toperand->mode = Addressing_Value;\n\n\t\tif (tuple->Tuple.variables.count == 1) {\n\t\t\toperand->type = tuple->Tuple.variables[0]->type;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_min: {\n\t\t\/\/ min :: proc($T: typeid) -> ordered\n\t\t\/\/ min :: proc(a: ..ordered) -> ordered\n\n\t\tcheck_multi_expr_or_type(c, operand, ce->args[0]);\n\n\t\tType *original_type = operand->type;\n\t\tType *type = base_type(operand->type);\n\t\tif (operand->mode == Addressing_Type && is_type_enumerated_array(type)) {\n\t\t\t\/\/ Okay\n\t\t} else if (!is_type_ordered(type) || !(is_type_numeric(type) || is_type_string(type))) {\n\t\t\tgbString type_str = type_to_string(original_type);\n\t\t\terror(call, \"Expected a ordered numeric type to 'min', got '%s'\", type_str);\n\t\t\tgb_string_free(type_str);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (operand->mode == Addressing_Type) {\n\t\t\tif (ce->args.count != 1) {\n\t\t\t\terror(call, \"If 'min' gets a type, only 1 arguments is allowed, got %td\", ce->args.count);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (is_type_boolean(type)) {\n\t\t\t\toperand->mode  = Addressing_Constant;\n\t\t\t\toperand->type  = original_type;\n\t\t\t\toperand->value = exact_value_bool(false);\n\t\t\t\treturn true;\n\t\t\t} else if (is_type_integer(type)) {\n\t\t\t\toperand->mode  = Addressing_Constant;\n\t\t\t\toperand->type  = original_type;\n\t\t\t\tif (is_type_unsigned(type)) {\n\t\t\t\t\toperand->value = exact_value_u64(0);\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\ti64 sz = 8*type_size_of(type);\n\t\t\t\t\tExactValue a = exact_value_i64(1);\n\t\t\t\t\tExactValue b = exact_value_i64(sz-1);\n\t\t\t\t\tExactValue v = exact_binary_operator_value(Token_Shl, a, b);\n\t\t\t\t\tv = exact_unary_operator_value(Token_Sub, v, cast(i32)sz, false);\n\t\t\t\t\toperand->value = v;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t} else if (is_type_float(type)) {\n\t\t\t\toperand->mode  = Addressing_Constant;\n\t\t\t\toperand->type  = original_type;\n\t\t\t\tswitch (type_size_of(type)) {\n\t\t\t\tcase 2:\n\t\t\t\t\toperand->value = exact_value_float(-65504.0f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\toperand->value = exact_value_float(-3.402823466e+38f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t\toperand->value = exact_value_float(-1.7976931348623158e+308);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tGB_PANIC(\"Unhandled float type\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t} else if (is_type_enum(type)) {\n\t\t\t\toperand->mode  = Addressing_Constant;\n\t\t\t\toperand->type  = original_type;\n\t\t\t\toperand->value = *type->Enum.min_value;\n\t\t\t\treturn true;\n\t\t\t} else if (is_type_enumerated_array(type)) {\n\t\t\t\tType *bt = base_type(type);\n\t\t\t\tGB_ASSERT(bt->kind == Type_EnumeratedArray);\n\t\t\t\toperand->mode  = Addressing_Constant;\n\t\t\t\toperand->type  = bt->EnumeratedArray.index;\n\t\t\t\toperand->value = *bt->EnumeratedArray.min_value;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tgbString type_str = type_to_string(original_type);\n\t\t\terror(call, \"Invalid type for 'min', got %s\", type_str);\n\t\t\tgb_string_free(type_str);\n\t\t\treturn false;\n\t\t}\n\n\n\t\tbool all_constant = operand->mode == Addressing_Constant;\n\n\t\tauto operands = array_make<Operand>(heap_allocator(), 0, ce->args.count);\n\t\tdefer (array_free(&operands));\n\n\t\tarray_add(&operands, *operand);\n\n\t\tfor (isize i = 1; i < ce->args.count; i++) {\n\t\t\tAst *other_arg = ce->args[i];\n\t\t\tOperand b = {};\n\t\t\tcheck_expr(c, &b, other_arg);\n\t\t\tif (b.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_ordered(b.type) || !(is_type_numeric(b.type) || is_type_string(b.type))) {\n\t\t\t\tgbString type_str = type_to_string(b.type);\n\t\t\t\terror(call,\n\t\t\t\t      \"Expected a ordered numeric type to 'min', got '%s'\",\n\t\t\t\t      type_str);\n\t\t\t\tgb_string_free(type_str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tarray_add(&operands, b);\n\n\t\t\tif (all_constant) {\n\t\t\t\tall_constant = b.mode == Addressing_Constant;\n\t\t\t}\n\t\t}\n\n\t\tif (all_constant) {\n\t\t\tExactValue value = operands[0].value;\n\t\t\tType *type = operands[0].type;\n\t\t\tfor (isize i = 1; i < operands.count; i++) {\n\t\t\t\tOperand y = operands[i];\n\t\t\t\tif (compare_exact_values(Token_Lt, value, y.value)) {\n\t\t\t\t\t\/\/ okay\n\t\t\t\t} else {\n\t\t\t\t\tvalue = y.value;\n\t\t\t\t\ttype = y.type;\n\t\t\t\t}\n\t\t\t}\n\t\t\toperand->value = value;\n\t\t\toperand->type = type;\n\t\t} else {\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = original_type;\n\n\t\t\tfor_array(i, operands) {\n\t\t\t\tOperand *a = &operands[i];\n\t\t\t\tfor_array(j, operands) {\n\t\t\t\t\tif (i == j) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tOperand *b = &operands[j];\n\n\t\t\t\t\tconvert_to_typed(c, a, b->type);\n\t\t\t\t\tif (a->mode == Addressing_Invalid) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tconvert_to_typed(c, b, a->type);\n\t\t\t\t\tif (b->mode == Addressing_Invalid) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (isize i = 0; i < operands.count-1; i++) {\n\t\t\t\tOperand *a = &operands[i];\n\t\t\t\tOperand *b = &operands[i+1];\n\n\t\t\t\tif (!are_types_identical(a->type, b->type)) {\n\t\t\t\t\tgbString type_a = type_to_string(a->type);\n\t\t\t\t\tgbString type_b = type_to_string(b->type);\n\t\t\t\t\terror(a->expr,\n\t\t\t\t\t      \"Mismatched types to 'min', '%s' vs '%s'\",\n\t\t\t\t\t      type_a, type_b);\n\t\t\t\t\tgb_string_free(type_b);\n\t\t\t\t\tgb_string_free(type_a);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toperand->type = operands[0].type;\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_max: {\n\t\t\/\/ max :: proc($T: typeid) -> ordered\n\t\t\/\/ max :: proc(a: ..ordered) -> ordered\n\n\t\tcheck_multi_expr_or_type(c, operand, ce->args[0]);\n\n\t\tType *original_type = operand->type;\n\t\tType *type = base_type(operand->type);\n\n\t\tif (operand->mode == Addressing_Type && is_type_enumerated_array(type)) {\n\t\t\t\/\/ Okay\n\t\t} else if (!is_type_ordered(type) || !(is_type_numeric(type) || is_type_string(type))) {\n\t\t\tgbString type_str = type_to_string(original_type);\n\t\t\terror(call, \"Expected a ordered numeric type to 'max', got '%s'\", type_str);\n\t\t\tgb_string_free(type_str);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (operand->mode == Addressing_Type) {\n\t\t\tif (ce->args.count != 1) {\n\t\t\t\terror(call, \"If 'max' gets a type, only 1 arguments is allowed, got %td\", ce->args.count);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (is_type_boolean(type)) {\n\t\t\t\toperand->mode  = Addressing_Constant;\n\t\t\t\toperand->type  = original_type;\n\t\t\t\toperand->value = exact_value_bool(true);\n\t\t\t\treturn true;\n\t\t\t} else if (is_type_integer(type)) {\n\t\t\t\toperand->mode  = Addressing_Constant;\n\t\t\t\toperand->type  = original_type;\n\t\t\t\tif (is_type_unsigned(type)) {\n\t\t\t\t\ti64 sz = 8*type_size_of(type);\n\t\t\t\t\tExactValue a = exact_value_i64(1);\n\t\t\t\t\tExactValue b = exact_value_i64(sz);\n\t\t\t\t\tExactValue v = exact_binary_operator_value(Token_Shl, a, b);\n\t\t\t\t\tv = exact_binary_operator_value(Token_Sub, v, a);\n\t\t\t\t\toperand->value = v;\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\ti64 sz = 8*type_size_of(type);\n\t\t\t\t\tExactValue a = exact_value_i64(1);\n\t\t\t\t\tExactValue b = exact_value_i64(sz-1);\n\t\t\t\t\tExactValue v = exact_binary_operator_value(Token_Shl, a, b);\n\t\t\t\t\tv = exact_binary_operator_value(Token_Sub, v, a);\n\t\t\t\t\toperand->value = v;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t} else if (is_type_float(type)) {\n\t\t\t\toperand->mode  = Addressing_Constant;\n\t\t\t\toperand->type  = original_type;\n\t\t\t\tswitch (type_size_of(type)) {\n\t\t\t\tcase 2:\n\t\t\t\t\toperand->value = exact_value_float(65504.0f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\toperand->value = exact_value_float(3.402823466e+38f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t\toperand->value = exact_value_float(1.7976931348623158e+308);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tGB_PANIC(\"Unhandled float type\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t} else if (is_type_enum(type)) {\n\t\t\t\toperand->mode  = Addressing_Constant;\n\t\t\t\toperand->type  = original_type;\n\t\t\t\toperand->value = *type->Enum.max_value;\n\t\t\t\treturn true;\n\t\t\t} else if (is_type_enumerated_array(type)) {\n\t\t\t\tType *bt = base_type(type);\n\t\t\t\tGB_ASSERT(bt->kind == Type_EnumeratedArray);\n\t\t\t\toperand->mode  = Addressing_Constant;\n\t\t\t\toperand->type  = bt->EnumeratedArray.index;\n\t\t\t\toperand->value = *bt->EnumeratedArray.max_value;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tgbString type_str = type_to_string(original_type);\n\t\t\terror(call, \"Invalid type for 'max', got %s\", type_str);\n\t\t\tgb_string_free(type_str);\n\t\t\treturn false;\n\t\t}\n\n\t\tbool all_constant = operand->mode == Addressing_Constant;\n\n\t\tauto operands = array_make<Operand>(heap_allocator(), 0, ce->args.count);\n\t\tdefer (array_free(&operands));\n\n\t\tarray_add(&operands, *operand);\n\n\n\t\tfor (isize i = 1; i < ce->args.count; i++) {\n\t\t\tAst *arg = ce->args[i];\n\t\t\tOperand b = {};\n\t\t\tcheck_expr(c, &b, arg);\n\t\t\tif (b.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_ordered(b.type) || !(is_type_numeric(b.type) || is_type_string(b.type))) {\n\t\t\t\tgbString type_str = type_to_string(b.type);\n\t\t\t\terror(arg,\n\t\t\t\t      \"Expected a ordered numeric type to 'max', got '%s'\",\n\t\t\t\t      type_str);\n\t\t\t\tgb_string_free(type_str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tarray_add(&operands, b);\n\n\t\t\tif (all_constant) {\n\t\t\t\tall_constant = b.mode == Addressing_Constant;\n\t\t\t}\n\t\t}\n\n\t\tif (all_constant) {\n\t\t\tExactValue value = operands[0].value;\n\t\t\tType *type = operands[0].type;\n\t\t\tfor (isize i = 1; i < operands.count; i++) {\n\t\t\t\tOperand y = operands[i];\n\t\t\t\tif (compare_exact_values(Token_Gt, value, y.value)) {\n\t\t\t\t\t\/\/ okay\n\t\t\t\t} else {\n\t\t\t\t\ttype  = y.type;\n\t\t\t\t\tvalue = y.value;\n\t\t\t\t}\n\t\t\t}\n\t\t\toperand->value = value;\n\t\t\toperand->type = type;\n\t\t} else {\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = original_type;\n\n\t\t\tfor_array(i, operands) {\n\t\t\t\tOperand *a = &operands[i];\n\t\t\t\tfor_array(j, operands) {\n\t\t\t\t\tif (i == j) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tOperand *b = &operands[j];\n\n\t\t\t\t\tconvert_to_typed(c, a, b->type);\n\t\t\t\t\tif (a->mode == Addressing_Invalid) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tconvert_to_typed(c, b, a->type);\n\t\t\t\t\tif (b->mode == Addressing_Invalid) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (isize i = 0; i < operands.count-1; i++) {\n\t\t\t\tOperand *a = &operands[i];\n\t\t\t\tOperand *b = &operands[i+1];\n\n\t\t\t\tif (!are_types_identical(a->type, b->type)) {\n\t\t\t\t\tgbString type_a = type_to_string(a->type);\n\t\t\t\t\tgbString type_b = type_to_string(b->type);\n\t\t\t\t\terror(a->expr,\n\t\t\t\t\t      \"Mismatched types to 'max', '%s' vs '%s'\",\n\t\t\t\t\t      type_a, type_b);\n\t\t\t\t\tgb_string_free(type_b);\n\t\t\t\t\tgb_string_free(type_a);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toperand->type = operands[0].type;\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_abs: {\n\t\t\/\/ abs :: proc(n: numeric) -> numeric\n\t\tif (!(is_type_numeric(operand->type) && !is_type_array(operand->type))) {\n\t\t\tgbString type_str = type_to_string(operand->type);\n\t\t\terror(call, \"Expected a numeric type to 'abs', got '%s'\", type_str);\n\t\t\tgb_string_free(type_str);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (operand->mode == Addressing_Constant) {\n\t\t\tswitch (operand->value.kind) {\n\t\t\tcase ExactValue_Integer:\n\t\t\t\tmp_abs(&operand->value.value_integer, &operand->value.value_integer);\n\t\t\t\tbreak;\n\t\t\tcase ExactValue_Float:\n\t\t\t\toperand->value.value_float = gb_abs(operand->value.value_float);\n\t\t\t\tbreak;\n\t\t\tcase ExactValue_Complex: {\n\t\t\t\tf64 r = operand->value.value_complex->real;\n\t\t\t\tf64 i = operand->value.value_complex->imag;\n\t\t\t\toperand->value = exact_value_float(gb_sqrt(r*r + i*i));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase ExactValue_Quaternion: {\n\t\t\t\tf64 r = operand->value.value_quaternion->real;\n\t\t\t\tf64 i = operand->value.value_quaternion->imag;\n\t\t\t\tf64 j = operand->value.value_quaternion->jmag;\n\t\t\t\tf64 k = operand->value.value_quaternion->kmag;\n\t\t\t\toperand->value = exact_value_float(gb_sqrt(r*r + i*i + j*j + k*k));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tGB_PANIC(\"Invalid numeric constant\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\toperand->mode = Addressing_Value;\n\n\t\t\t{\n\t\t\t\tType *bt = base_type(operand->type);\n\t\t\t\tif (are_types_identical(bt, t_complex64))  add_package_dependency(c, \"runtime\", \"abs_complex64\");\n\t\t\t\tif (are_types_identical(bt, t_complex128)) add_package_dependency(c, \"runtime\", \"abs_complex128\");\n\t\t\t\tif (are_types_identical(bt, t_quaternion128)) add_package_dependency(c, \"runtime\", \"abs_quaternion128\");\n\t\t\t\tif (are_types_identical(bt, t_quaternion256)) add_package_dependency(c, \"runtime\", \"abs_quaternion256\");\n\t\t\t}\n\t\t}\n\n\t\tif (is_type_complex_or_quaternion(operand->type)) {\n\t\t\toperand->type = base_complex_elem_type(operand->type);\n\t\t}\n\t\tGB_ASSERT(!is_type_complex_or_quaternion(operand->type));\n\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_clamp: {\n\t\t\/\/ clamp :: proc(a, min, max: ordered) -> ordered\n\t\tType *type = operand->type;\n\t\tif (!is_type_ordered(type) || !(is_type_numeric(type) || is_type_string(type))) {\n\t\t\tgbString type_str = type_to_string(operand->type);\n\t\t\terror(call, \"Expected a ordered numeric or string type to 'clamp', got '%s'\", type_str);\n\t\t\tgb_string_free(type_str);\n\t\t\treturn false;\n\t\t}\n\n\t\tAst *min_arg = ce->args[1];\n\t\tAst *max_arg = ce->args[2];\n\t\tOperand x = *operand;\n\t\tOperand y = {};\n\t\tOperand z = {};\n\n\t\tcheck_expr(c, &y, min_arg);\n\t\tif (y.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!is_type_ordered(y.type) || !(is_type_numeric(y.type) || is_type_string(y.type))) {\n\t\t\tgbString type_str = type_to_string(y.type);\n\t\t\terror(call, \"Expected a ordered numeric or string type to 'clamp', got '%s'\", type_str);\n\t\t\tgb_string_free(type_str);\n\t\t\treturn false;\n\t\t}\n\n\t\tcheck_expr(c, &z, max_arg);\n\t\tif (z.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!is_type_ordered(z.type) || !(is_type_numeric(z.type) || is_type_string(z.type))) {\n\t\t\tgbString type_str = type_to_string(z.type);\n\t\t\terror(call, \"Expected a ordered numeric or string type to 'clamp', got '%s'\", type_str);\n\t\t\tgb_string_free(type_str);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (x.mode == Addressing_Constant &&\n\t\t    y.mode == Addressing_Constant &&\n\t\t    z.mode == Addressing_Constant) {\n\t\t\tExactValue a = x.value;\n\t\t\tExactValue b = y.value;\n\t\t\tExactValue c = z.value;\n\n\t\t\toperand->mode = Addressing_Constant;\n\t\t\tif (compare_exact_values(Token_Lt, a, b)) {\n\t\t\t\toperand->value = b;\n\t\t\t\toperand->type = y.type;\n\t\t\t} else if (compare_exact_values(Token_Gt, a, c)) {\n\t\t\t\toperand->value = c;\n\t\t\t\toperand->type = z.type;\n\t\t\t} else {\n\t\t\t\toperand->value = a;\n\t\t\t\toperand->type = x.type;\n\t\t\t}\n\t\t} else {\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = type;\n\n\t\t\tOperand *ops[3] = {&x, &y, &z};\n\t\t\tfor (isize i = 0; i < 3; i++) {\n\t\t\t\tOperand *a = ops[i];\n\t\t\t\tfor (isize j = 0; j < 3; j++) {\n\t\t\t\t\tif (i == j) continue;\n\t\t\t\t\tOperand *b = ops[j];\n\t\t\t\t\tconvert_to_typed(c, a, b->type);\n\t\t\t\t\tif (a->mode == Addressing_Invalid) return false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!are_types_identical(x.type, y.type) || !are_types_identical(x.type, z.type)) {\n\t\t\t\tgbString type_x = type_to_string(x.type);\n\t\t\t\tgbString type_y = type_to_string(y.type);\n\t\t\t\tgbString type_z = type_to_string(z.type);\n\t\t\t\terror(call,\n\t\t\t\t      \"Mismatched types to 'clamp', '%s', '%s', '%s'\",\n\t\t\t\t      type_x, type_y, type_z);\n\t\t\t\tgb_string_free(type_z);\n\t\t\t\tgb_string_free(type_y);\n\t\t\t\tgb_string_free(type_x);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->type = ops[0]->type;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_soa_zip: {\n\t\tauto types = array_make<Type *>(temporary_allocator(), 0, ce->args.count);\n\t\tauto names = array_make<String>(temporary_allocator(), 0, ce->args.count);\n\n\t\tbool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);\n\n\t\tbool fail = false;\n\t\tfor_array(i, ce->args) {\n\t\t\tAst *arg = ce->args[i];\n\t\t\tbool mix = false;\n\t\t\tif (first_is_field_value) {\n\t\t\t\tmix = arg->kind != Ast_FieldValue;\n\t\t\t} else {\n\t\t\t\tmix = arg->kind == Ast_FieldValue;\n\t\t\t}\n\t\t\tif (mix) {\n\t\t\t\terror(arg, \"Mixture of 'field = value' and value elements in the procedure call 'soa_zip' is not allowed\");\n\t\t\t\tfail = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tStringSet name_set = {};\n\t\tstring_set_init(&name_set, heap_allocator(), 2*ce->args.count);\n\n\t\tfor_array(i, ce->args) {\n\t\t\tString name = {};\n\t\t\tAst *arg = ce->args[i];\n\t\t\tif (arg->kind == Ast_FieldValue) {\n\t\t\t\tAst *ename = arg->FieldValue.field;\n\t\t\t\tif (!fail && ename->kind != Ast_Ident) {\n\t\t\t\t\terror(ename, \"Expected an identifier for field argument\");\n\t\t\t\t} else if (ename->kind == Ast_Ident) {\n\t\t\t\t\tname = ename->Ident.token.string;\n\t\t\t\t}\n\t\t\t\targ = arg->FieldValue.value;\n\t\t\t}\n\n\t\t\tOperand op = {};\n\t\t\tcheck_expr(c, &op, arg);\n\t\t\tif (op.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *arg_type = base_type(op.type);\n\t\t\tif (!is_type_slice(arg_type)) {\n\t\t\t\tgbString s = type_to_string(op.type);\n\t\t\t\terror(op.expr, \"Indices to 'soa_zip' must be slices, got %s\", s);\n\t\t\t\tgb_string_free(s);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tGB_ASSERT(arg_type->kind == Type_Slice);\n\t\t\tif (name == \"_\") {\n\t\t\t\terror(op.expr, \"Field argument name '%.*s' is not allowed\", LIT(name));\n\t\t\t\tname = {};\n\t\t\t}\n\t\t\tif (name.len == 0) {\n\t\t\t\tgbString field_name = gb_string_make(permanent_allocator(), \"_\");\n\t\t\t\tfield_name = gb_string_append_fmt(field_name, \"%td\", types.count);\n\t\t\t\tname = make_string_c(field_name);\n\t\t\t}\n\n\n\t\t\tif (string_set_exists(&name_set, name)) {\n\t\t\t\terror(op.expr, \"Field argument name '%.*s' already exists\", LIT(name));\n\t\t\t} else {\n\t\t\t\tarray_add(&types, arg_type->Slice.elem);\n\t\t\t\tarray_add(&names, name);\n\n\t\t\t\tstring_set_add(&name_set, name);\n\t\t\t}\n\t\t}\n\n\n\n\n\t\tAst *dummy_node_struct = alloc_ast_node(nullptr, Ast_Invalid);\n\t\tAst *dummy_node_soa = alloc_ast_node(nullptr, Ast_Invalid);\n\t\tScope *s = create_scope(c->info, builtin_pkg->scope);\n\n\t\tauto fields = array_make<Entity *>(permanent_allocator(), 0, types.count);\n\t\tfor_array(i, types) {\n\t\t\tType *type = types[i];\n\t\t\tString name = names[i];\n\t\t\tGB_ASSERT(name != \"\");\n\t\t\tEntity *e = alloc_entity_field(s, make_token_ident(name), type, false, cast(i32)i, EntityState_Resolved);\n\t\t\tarray_add(&fields, e);\n\t\t\tscope_insert(s, e);\n\t\t}\n\n\t\tType *elem = nullptr;\n\t\tif (type_hint != nullptr && is_type_struct(type_hint)) {\n\t\t\tType *soa_type = base_type(type_hint);\n\t\t\tif (soa_type->Struct.soa_kind != StructSoa_Slice) {\n\t\t\t\tgoto soa_zip_end;\n\t\t\t}\n\t\t\tType *soa_elem_type = soa_type->Struct.soa_elem;\n\t\t\tType *et = base_type(soa_elem_type);\n\t\t\tif (et->kind != Type_Struct) {\n\t\t\t\tgoto soa_zip_end;\n\t\t\t}\n\n\t\t\tif (et->Struct.fields.count != fields.count) {\n\t\t\t\tgoto soa_zip_end;\n\t\t\t}\n\t\t\tif (!fail && first_is_field_value) {\n\t\t\t\tfor_array(i, names) {\n\t\t\t\t\tSelection sel = lookup_field(et, names[i], false);\n\t\t\t\t\tif (sel.entity == nullptr) {\n\t\t\t\t\t\tgoto soa_zip_end;\n\t\t\t\t\t}\n\t\t\t\t\tif (sel.index.count != 1) {\n\t\t\t\t\t\tgoto soa_zip_end;\n\t\t\t\t\t}\n\t\t\t\t\tif (!are_types_identical(sel.entity->type, types[i])) {\n\t\t\t\t\t\tgoto soa_zip_end;\n\t\t\t\t\t}\n\t\t\t\t}\n \t\t\t} else {\n \t\t\t\tfor_array(i, et->Struct.fields) {\n \t\t\t\t\tif (!are_types_identical(et->Struct.fields[i]->type, types[i])) {\n \t\t\t\t\t\tgoto soa_zip_end;\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n\n \t\t\telem = soa_elem_type;\n\t\t}\n\n\t\tsoa_zip_end:;\n\n\t\tif (elem == nullptr) {\n\t\t\telem = alloc_type_struct();\n\t\t\telem->Struct.scope = s;\n\t\t\telem->Struct.fields = slice_from_array(fields);\n\t\t\telem->Struct.tags = gb_alloc_array(permanent_allocator(), String, fields.count);\n\t\t\telem->Struct.node = dummy_node_struct;\n\t\t\ttype_set_offsets(elem);\n\t\t}\n\n\t\tType *soa_type = make_soa_struct_slice(c, dummy_node_soa, nullptr, elem);\n\t\ttype_set_offsets(soa_type);\n\n\t\toperand->type = soa_type;\n\t\toperand->mode = Addressing_Value;\n\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_soa_unzip: {\n\t\tOperand x = {};\n\t\tcheck_expr(c, &x, ce->args[0]);\n\t\tif (x.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!is_operand_value(x)) {\n\t\t\terror(call, \"'%.*s' expects an #soa slice\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t}\n\t\tType *t = base_type(x.type);\n\t\tif (!is_type_soa_struct(t) || t->Struct.soa_kind != StructSoa_Slice) {\n\t\t\tgbString s = type_to_string(x.type);\n\t\t\terror(call, \"'%.*s' expects an #soa slice, got %s\", LIT(builtin_name), s);\n\t\t\tgb_string_free(s);\n\t\t\treturn false;\n\t\t}\n\t\tauto types = slice_make<Type *>(permanent_allocator(), t->Struct.fields.count-1);\n\t\tfor_array(i, types) {\n\t\t\tEntity *f = t->Struct.fields[i];\n\t\t\tGB_ASSERT(f->type->kind == Type_Pointer);\n\t\t\ttypes[i] = alloc_type_slice(f->type->Pointer.elem);\n\t\t}\n\n\t\toperand->type = alloc_type_tuple_from_field_types(types.data, types.count, false, false);\n\t\toperand->mode = Addressing_Value;\n\t\tbreak;\n\t}\n\t\n\tcase BuiltinProc_transpose: {\n\t\tOperand x = {};\n\t\tcheck_expr(c, &x, ce->args[0]);\n\t\tif (x.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!is_operand_value(x)) {\n\t\t\terror(call, \"'%.*s' expects a matrix or array\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t}\n\t\tType *t = base_type(x.type);\n\t\tif (!is_type_matrix(t) && !is_type_array(t)) {\n\t\t\tgbString s = type_to_string(x.type);\n\t\t\terror(call, \"'%.*s' expects a matrix or array, got %s\", LIT(builtin_name), s);\n\t\t\tgb_string_free(s);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\toperand->mode = Addressing_Value;\n\t\tif (t->kind == Type_Array) {\n\t\t\ti32 rank = type_math_rank(t);\n\t\t\t\/\/ Do nothing\n\t\t\toperand->type = x.type;\n\t\t\tif (rank > 2) {\n\t\t\t\tgbString s = type_to_string(x.type);\n\t\t\t\terror(call, \"'%.*s' expects a matrix or array with a rank of 2, got %s of rank %d\", LIT(builtin_name), s, rank);\n\t\t\t\tgb_string_free(s);\n\t\t\t\treturn false;\n\t\t\t} else if (rank == 2) {\n\t\t\t\tType *inner = base_type(t->Array.elem);\n\t\t\t\tGB_ASSERT(inner->kind == Type_Array);\n\t\t\t\tType *elem = inner->Array.elem;\n\t\t\t\tType *array_inner = alloc_type_array(elem, t->Array.count);\n\t\t\t\tType *array_outer = alloc_type_array(array_inner, inner->Array.count);\n\t\t\t\toperand->type = array_outer;\n\n\t\t\t\ti64 elements = t->Array.count*inner->Array.count;\n\t\t\t\ti64 size = type_size_of(operand->type);\n\t\t\t\tif (!is_type_valid_for_matrix_elems(elem)) {\n\t\t\t\t\tgbString s = type_to_string(x.type);\n\t\t\t\t\terror(call, \"'%.*s' expects a matrix or array with a base element type of an integer, float, or complex number, got %s\", LIT(builtin_name), s);\n\t\t\t\t\tgb_string_free(s);\n\t\t\t\t} else if (elements > MATRIX_ELEMENT_COUNT_MAX) {\n\t\t\t\t\tgbString s = type_to_string(x.type);\n\t\t\t\t\terror(call, \"'%.*s' expects a matrix or array with a maximum of %d elements, got %s with %lld elements\", LIT(builtin_name), MATRIX_ELEMENT_COUNT_MAX, s, elements);\n\t\t\t\t\tgb_string_free(s);\n\t\t\t\t} else if (elements > MATRIX_ELEMENT_COUNT_MAX) {\n\t\t\t\t\tgbString s = type_to_string(x.type);\n\t\t\t\t\terror(call, \"'%.*s' expects a matrix or array with non-zero elements, got %s\", LIT(builtin_name), MATRIX_ELEMENT_COUNT_MAX, s);\n\t\t\t\t\tgb_string_free(s);\n\t\t\t\t} else if (size > MATRIX_ELEMENT_MAX_SIZE) {\n\t\t\t\t\tgbString s = type_to_string(x.type);\n\t\t\t\t\terror(call, \"Too large of a type for '%.*s', got %s of size %lld, maximum size %d\", LIT(builtin_name), s, cast(long long)size, MATRIX_ELEMENT_MAX_SIZE);\n\t\t\t\t\tgb_string_free(s);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tGB_ASSERT(t->kind == Type_Matrix);\n\t\t\toperand->type = alloc_type_matrix(t->Matrix.elem, t->Matrix.column_count, t->Matrix.row_count);\n\t\t}\n\t\toperand->type = check_matrix_type_hint(operand->type, type_hint);\n\t\tbreak;\n\t}\n\t\n\tcase BuiltinProc_outer_product: {\n\t\tOperand x = {};\n\t\tOperand y = {};\n\t\tcheck_expr(c, &x, ce->args[0]);\n\t\tif (x.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tcheck_expr(c, &y, ce->args[1]);\n\t\tif (y.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!is_operand_value(x) || !is_operand_value(y)) {\n\t\t\terror(call, \"'%.*s' expects only arrays\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (!is_type_array(x.type) && !is_type_array(y.type)) {\n\t\t\tgbString s1 = type_to_string(x.type);\n\t\t\tgbString s2 = type_to_string(y.type);\n\t\t\terror(call, \"'%.*s' expects only arrays, got %s and %s\", LIT(builtin_name), s1, s2);\n\t\t\tgb_string_free(s2);\n\t\t\tgb_string_free(s1);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tType *xt = base_type(x.type);\n\t\tType *yt = base_type(y.type);\n\t\tGB_ASSERT(xt->kind == Type_Array);\n\t\tGB_ASSERT(yt->kind == Type_Array);\n\t\tif (!are_types_identical(xt->Array.elem, yt->Array.elem)) {\n\t\t\tgbString s1 = type_to_string(xt->Array.elem);\n\t\t\tgbString s2 = type_to_string(yt->Array.elem);\n\t\t\terror(call, \"'%.*s' mismatched element types, got %s vs %s\", LIT(builtin_name), s1, s2);\n\t\t\tgb_string_free(s2);\n\t\t\tgb_string_free(s1);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tType *elem = xt->Array.elem;\n\t\t\n\t\tif (!is_type_valid_for_matrix_elems(elem)) {\n\t\t\tgbString s = type_to_string(elem);\n\t\t\terror(call, \"Matrix elements types are limited to integers, floats, and complex, got %s\", s);\n\t\t\tgb_string_free(s);\n\t\t}\n\t\t\n\t\tif (xt->Array.count == 0 || yt->Array.count == 0) {\n\t\t\tgbString s1 = type_to_string(x.type);\n\t\t\tgbString s2 = type_to_string(y.type);\n\t\t\terror(call, \"'%.*s' expects only arrays of non-zero length, got %s and %s\", LIT(builtin_name), s1, s2);\n\t\t\tgb_string_free(s2);\n\t\t\tgb_string_free(s1);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\ti64 max_count = xt->Array.count*yt->Array.count;\n\t\tif (max_count > MATRIX_ELEMENT_COUNT_MAX) {\n\t\t\terror(call, \"Product of the array lengths exceed the maximum matrix element count, got %d, expected a maximum of %d\", cast(int)max_count, MATRIX_ELEMENT_COUNT_MAX);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\toperand->mode = Addressing_Value;\n\t\toperand->type = alloc_type_matrix(elem, xt->Array.count, yt->Array.count);\t\n\t\toperand->type = check_matrix_type_hint(operand->type, type_hint);\n\t\tbreak;\n\t}\n\t\n\tcase BuiltinProc_hadamard_product: {\n\t\tOperand x = {};\n\t\tOperand y = {};\n\t\tcheck_expr(c, &x, ce->args[0]);\n\t\tif (x.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tcheck_expr(c, &y, ce->args[1]);\n\t\tif (y.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!is_operand_value(x) || !is_operand_value(y)) {\n\t\t\terror(call, \"'%.*s' expects a matrix or array types\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t}\n\t\tif (!is_type_matrix(x.type) && !is_type_array(y.type)) {\n\t\t\tgbString s1 = type_to_string(x.type);\n\t\t\tgbString s2 = type_to_string(y.type);\n\t\t\terror(call, \"'%.*s' expects matrix or array values, got %s and %s\", LIT(builtin_name), s1, s2);\n\t\t\tgb_string_free(s2);\n\t\t\tgb_string_free(s1);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (!are_types_identical(x.type, y.type)) {\n\t\t\tgbString s1 = type_to_string(x.type);\n\t\t\tgbString s2 = type_to_string(y.type);\n\t\t\terror(call, \"'%.*s' values of the same type, got %s and %s\", LIT(builtin_name), s1, s2);\n\t\t\tgb_string_free(s2);\n\t\t\tgb_string_free(s1);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tType *elem = core_array_type(x.type);\n\t\tif (!is_type_valid_for_matrix_elems(elem)) {\n\t\t\tgbString s = type_to_string(elem);\n\t\t\terror(call, \"'%.*s' expects elements to be types are limited to integers, floats, and complex, got %s\", LIT(builtin_name), s);\n\t\t\tgb_string_free(s);\n\t\t}\n\t\t\n\t\toperand->mode = Addressing_Value;\n\t\toperand->type = x.type;\n\t\toperand->type = check_matrix_type_hint(operand->type, type_hint);\n\t\tbreak;\n\t}\n\t\n\tcase BuiltinProc_matrix_flatten: {\n\t\tOperand x = {};\n\t\tcheck_expr(c, &x, ce->args[0]);\n\t\tif (x.mode == Addressing_Invalid) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!is_operand_value(x)) {\n\t\t\terror(call, \"'%.*s' expects a matrix or array\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t}\n\t\tType *t = base_type(x.type);\n\t\tif (!is_type_matrix(t) && !is_type_array(t)) {\n\t\t\tgbString s = type_to_string(x.type);\n\t\t\terror(call, \"'%.*s' expects a matrix or array, got %s\", LIT(builtin_name), s);\n\t\t\tgb_string_free(s);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\toperand->mode = Addressing_Value;\n\t\tif (is_type_array(t)) {\n\t\t\t\/\/ Do nothing\n\t\t\toperand->type = x.type;\t\t\t\n\t\t} else {\n\t\t\tGB_ASSERT(t->kind == Type_Matrix);\n\t\t\toperand->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count*t->Matrix.column_count);\n\t\t}\n\t\toperand->type = check_matrix_type_hint(operand->type, type_hint);\n\t\tbreak;\n\t}\n\t\n\tcase BuiltinProc_is_package_imported: {\n\t\tbool value = false;\n\n\t\tif (!is_type_string(operand->type) && (operand->mode != Addressing_Constant)) {\n\t\t\terror(ce->args[0], \"Expected a constant string for '%.*s'\", LIT(builtin_name));\n\t\t} else if (operand->value.kind == ExactValue_String) {\n\t\t\tString pkg_name = operand->value.value_string;\n\t\t\t\/\/ TODO(bill): probably should have this be a `StringMap` eventually\n\t\t\tfor_array(i, c->info->packages.entries) {\n\t\t\t\tAstPackage *pkg = c->info->packages.entries[i].value;\n\t\t\t\tif (pkg->name == pkg_name) {\n\t\t\t\t\tvalue = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\toperand->mode = Addressing_Constant;\n\t\toperand->type = t_untyped_bool;\n\t\toperand->value = exact_value_bool(value);\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_soa_struct: {\n\t\tOperand x = {};\n\t\tOperand y = {};\n\t\tx = *operand;\n\t\tif (!is_type_integer(x.type) || x.mode != Addressing_Constant) {\n\t\t\terror(call, \"Expected a constant integer for 'intrinsics.soa_struct'\");\n\t\t\toperand->mode = Addressing_Type;\n\t\t\toperand->type = t_invalid;\n\t\t\treturn false;\n\t\t}\n\t\tif (big_int_is_neg(&x.value.value_integer)) {\n\t\t\terror(call, \"Negative array element length\");\n\t\t\toperand->mode = Addressing_Type;\n\t\t\toperand->type = t_invalid;\n\t\t\treturn false;\n\t\t}\n\t\ti64 count = big_int_to_i64(&x.value.value_integer);\n\n\t\tcheck_expr_or_type(c, &y, ce->args[1]);\n\t\tif (y.mode != Addressing_Type) {\n\t\t\terror(call, \"Expected a type 'intrinsics.soa_struct'\");\n\t\t\toperand->mode = Addressing_Type;\n\t\t\toperand->type = t_invalid;\n\t\t\treturn false;\n\t\t}\n\t\tType *elem = y.type;\n\t\tType *bt_elem = base_type(elem);\n\t\tif (!is_type_struct(elem) && !is_type_raw_union(elem) && !(is_type_array(elem) && bt_elem->Array.count <= 4)) {\n\t\t\tgbString str = type_to_string(elem);\n\t\t\terror(call, \"Invalid type for 'intrinsics.soa_struct', expected a struct or array of length 4 or below, got '%s'\", str);\n\t\t\tgb_string_free(str);\n\t\t\toperand->mode = Addressing_Type;\n\t\t\toperand->type = t_invalid;\n\t\t\treturn false;\n\t\t}\n\n\t\toperand->mode = Addressing_Type;\n\t\tType *soa_struct = nullptr;\n\t\tScope *scope = nullptr;\n\n\t\tif (is_type_array(elem)) {\n\t\t\tType *old_array = base_type(elem);\n\t\t\tsoa_struct = alloc_type_struct();\n\t\t\tsoa_struct->Struct.fields = slice_make<Entity *>(heap_allocator(), cast(isize)old_array->Array.count);\n\t\t\tsoa_struct->Struct.tags = gb_alloc_array(permanent_allocator(), String, cast(isize)old_array->Array.count);\n\t\t\tsoa_struct->Struct.node = operand->expr;\n\t\t\tsoa_struct->Struct.soa_kind = StructSoa_Fixed;\n\t\t\tsoa_struct->Struct.soa_elem = elem;\n\t\t\tsoa_struct->Struct.soa_count = cast(i32)count;\n\n\t\t\tscope = create_scope(c->info, c->scope);\n\t\t\tsoa_struct->Struct.scope = scope;\n\n\t\t\tString params_xyzw[4] = {\n\t\t\t\tstr_lit(\"x\"),\n\t\t\t\tstr_lit(\"y\"),\n\t\t\t\tstr_lit(\"z\"),\n\t\t\t\tstr_lit(\"w\")\n\t\t\t};\n\n\t\t\tfor (isize i = 0; i < cast(isize)old_array->Array.count; i++) {\n\t\t\t\tType *array_type = alloc_type_array(old_array->Array.elem, count);\n\t\t\t\tToken token = {};\n\t\t\t\ttoken.string = params_xyzw[i];\n\n\t\t\t\tEntity *new_field = alloc_entity_field(scope, token, array_type, false, cast(i32)i);\n\t\t\t\tsoa_struct->Struct.fields[i] = new_field;\n\t\t\t\tadd_entity(c, scope, nullptr, new_field);\n\t\t\t\tadd_entity_use(c, nullptr, new_field);\n\t\t\t}\n\n\t\t} else {\n\t\t\tGB_ASSERT(is_type_struct(elem));\n\n\t\t\tType *old_struct = base_type(elem);\n\t\t\tsoa_struct = alloc_type_struct();\n\t\t\tsoa_struct->Struct.fields = slice_make<Entity *>(heap_allocator(), old_struct->Struct.fields.count);\n\t\t\tsoa_struct->Struct.tags = gb_alloc_array(permanent_allocator(), String, old_struct->Struct.fields.count);\n\t\t\tsoa_struct->Struct.node = operand->expr;\n\t\t\tsoa_struct->Struct.soa_kind = StructSoa_Fixed;\n\t\t\tsoa_struct->Struct.soa_elem = elem;\n\t\t\tif (count > I32_MAX) {\n\t\t\t\tcount = I32_MAX;\n\t\t\t\terror(call, \"Array count too large for an #soa struct, got %lld\", cast(long long)count);\n\t\t\t}\n\t\t\tsoa_struct->Struct.soa_count = cast(i32)count;\n\n\t\t\tscope = create_scope(c->info, old_struct->Struct.scope->parent);\n\t\t\tsoa_struct->Struct.scope = scope;\n\n\t\t\tfor_array(i, old_struct->Struct.fields) {\n\t\t\t\tEntity *old_field = old_struct->Struct.fields[i];\n\t\t\t\tif (old_field->kind == Entity_Variable) {\n\t\t\t\t\tType *array_type = alloc_type_array(old_field->type, count);\n\t\t\t\t\tEntity *new_field = alloc_entity_field(scope, old_field->token, array_type, false, old_field->Variable.field_index);\n\t\t\t\t\tsoa_struct->Struct.fields[i] = new_field;\n\t\t\t\t\tadd_entity(c, scope, nullptr, new_field);\n\t\t\t\t} else {\n\t\t\t\t\tsoa_struct->Struct.fields[i] = old_field;\n\t\t\t\t}\n\n\t\t\t\tsoa_struct->Struct.tags[i] = old_struct->Struct.tags[i];\n\t\t\t}\n\t\t}\n\n\t\tToken token = {};\n\t\ttoken.string = str_lit(\"Base_Type\");\n\t\tEntity *base_type_entity = alloc_entity_type_name(scope, token, elem, EntityState_Resolved);\n\t\tadd_entity(c, scope, nullptr, base_type_entity);\n\n\t\tadd_type_info_type(c, soa_struct);\n\n\t\toperand->type = soa_struct;\n\t\tbreak;\n\t}\n\n\tcase BuiltinProc_alloca:\n\t\t{\n\t\t\tOperand sz = {};\n\t\t\tOperand al = {};\n\n\t\t\tcheck_expr(c, &sz, ce->args[0]);\n\t\t\tif (sz.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tcheck_expr(c, &al, ce->args[1]);\n\t\t\tif (al.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconvert_to_typed(c, &sz, t_int); if (sz.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &al, t_int); if (al.mode == Addressing_Invalid) return false;\n\n\t\t\tif (!is_type_integer(sz.type) || !is_type_integer(al.type)) {\n\t\t\t\terror(operand->expr, \"Both parameters to '%.*s' must integers\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (sz.mode == Addressing_Constant) {\n\t\t\t\ti64 i_sz = exact_value_to_i64(sz.value);\n\t\t\t\tif (i_sz < 0) {\n\t\t\t\t\terror(sz.expr, \"Size parameter to '%.*s' must be non-negative, got %lld\", LIT(builtin_name), cast(long long)i_sz);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (al.mode == Addressing_Constant) {\n\t\t\t\ti64 i_al = exact_value_to_i64(al.value);\n\t\t\t\tif (i_al < 0) {\n\t\t\t\t\terror(al.expr, \"Alignment parameter to '%.*s' must be non-negative, got %lld\", LIT(builtin_name), cast(long long)i_al);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tif (i_al > 1<<29) {\n\t\t\t\t\terror(al.expr, \"Alignment parameter to '%.*s' must not exceed '1<<29', got %lld\", LIT(builtin_name), cast(long long)i_al);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tif (!gb_is_power_of_two(cast(isize)i_al) && i_al != 0) {\n\t\t\t\t\terror(al.expr, \"Alignment parameter to '%.*s' must be a power of 2 or 0, got %lld\", LIT(builtin_name), cast(long long)i_al);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terror(al.expr, \"Alignment parameter to '%.*s' must be constant\", LIT(builtin_name));\n\t\t\t}\n\n\t\t\toperand->type = alloc_type_multi_pointer(t_u8);\n\t\t\toperand->mode = Addressing_Value;\n\t\t\tbreak;\n\t\t}\n\n\n\tcase BuiltinProc_cpu_relax:\n\t\toperand->mode = Addressing_NoValue;\n\t\tbreak;\n\n\tcase BuiltinProc_trap:\n\tcase BuiltinProc_debug_trap:\n\t\toperand->mode = Addressing_NoValue;\n\t\tbreak;\n\n\tcase BuiltinProc_read_cycle_counter:\n\t\toperand->mode = Addressing_Value;\n\t\toperand->type = t_i64;\n\t\tbreak;\n\n\tcase BuiltinProc_count_ones:\n\tcase BuiltinProc_count_zeros:\n\tcase BuiltinProc_count_trailing_zeros:\n\tcase BuiltinProc_count_leading_zeros:\n\tcase BuiltinProc_reverse_bits:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]);\n\t\t\tif (x.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (is_type_simd_vector(x.type)) {\n\t\t\t\tType *elem = base_array_type(x.type);\n\t\t\t\tif (!is_type_integer_like(elem)) {\n\t\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\t\terror(x.expr, \"#simd values passed to '%.*s' must have an element of an integer-like type (integer, boolean, enum, bit_set), got %s\", LIT(builtin_name), xts);\n\t\t\t\t\tgb_string_free(xts);\n\t\t\t\t}\n\t\t\t} else if (!is_type_integer_like(x.type)) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"Values passed to '%.*s' must be an integer-like type (integer, boolean, enum, bit_set), got %s\", LIT(builtin_name), xts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t} else if (x.type == t_llvm_bool) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"Invalid type passed to '%.*s', got %s\", LIT(builtin_name), xts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = default_type(x.type);\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_byte_swap:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]);\n\t\t\tif (x.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!is_type_integer_like(x.type) && !is_type_float(x.type)) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"Values passed to '%.*s' must be an integer-like type (integer, boolean, enum, bit_set) or float, got %s\", LIT(builtin_name), xts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t} else if (x.type == t_llvm_bool) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"Invalid type passed to '%.*s', got %s\", LIT(builtin_name), xts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t}\n\t\t\ti64 sz = type_size_of(x.type);\n\t\t\tif (sz < 2) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"Type passed to '%.*s' must be at least 2 bytes, got %s with size of %lld\", LIT(builtin_name), xts, sz);\n\t\t\t\tgb_string_free(xts);\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = default_type(x.type);\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_overflow_add:\n\tcase BuiltinProc_overflow_sub:\n\tcase BuiltinProc_overflow_mul:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]);\n\t\t\tcheck_expr(c, &y, ce->args[1]);\n\t\t\tif (x.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (y.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconvert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &x, y.type);\n\t\t\tif (is_type_untyped(x.type)) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"Expected a typed integer for '%.*s', got %s\", LIT(builtin_name), xts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_integer(x.type)) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"Expected an integer for '%.*s', got %s\", LIT(builtin_name), xts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *ct = core_type(x.type);\n\t\t\tif (is_type_different_to_arch_endianness(ct)) {\n\t\t\t\tGB_ASSERT(ct->kind == Type_Basic);\n\t\t\t\tif (ct->Basic.flags & (BasicFlag_EndianLittle|BasicFlag_EndianBig)) {\n\t\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\t\terror(x.expr, \"Expected an integer which does not specify the explicit endianness for '%.*s', got %s\", LIT(builtin_name), xts);\n\t\t\t\t\tgb_string_free(xts);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_OptionalOk;\n\t\t\toperand->type = default_type(x.type);\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_sqrt:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]);\n\t\t\tif (x.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tType *elem = core_array_type(x.type);\n\t\t\tif (!is_type_float(x.type) && !(is_type_simd_vector(x.type) && is_type_float(elem))) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"Expected a floating point or #simd vector value for '%.*s', got %s\", LIT(builtin_name), xts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t\treturn false;\n\t\t\t} else if (is_type_different_to_arch_endianness(elem)) {\n\t\t\t\tGB_ASSERT(elem->kind == Type_Basic);\n\t\t\t\tif (elem->Basic.flags & (BasicFlag_EndianLittle|BasicFlag_EndianBig)) {\n\t\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\t\terror(x.expr, \"Expected a float which does not specify the explicit endianness for '%.*s', got %s\", LIT(builtin_name), xts);\n\t\t\t\t\tgb_string_free(xts);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (is_type_float(x.type) && x.mode == Addressing_Constant) {\n\t\t\t\tf64 v = exact_value_to_f64(x.value);\n\n\t\t\t\toperand->mode = Addressing_Constant;\n\t\t\t\toperand->type = x.type;\n\t\t\t\toperand->value = exact_value_float(gb_sqrt(v));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = default_type(x.type);\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_fused_mul_add:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tOperand z = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]); if (x.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr(c, &y, ce->args[1]); if (y.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr(c, &z, ce->args[2]); if (z.mode == Addressing_Invalid) return false;\n\n\t\t\tconvert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &x, y.type); if (x.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &z, x.type); if (z.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &x, z.type); if (x.mode == Addressing_Invalid) return false;\n\t\t\tif (is_type_untyped(x.type)) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"Expected a typed floating point value or #simd vector for '%.*s', got %s\", LIT(builtin_name), xts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tType *elem = core_array_type(x.type);\n\t\t\tif (!is_type_float(x.type) && !(is_type_simd_vector(x.type) && is_type_float(elem))) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"Expected a floating point or #simd vector value for '%.*s', got %s\", LIT(builtin_name), xts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (is_type_different_to_arch_endianness(elem)) {\n\t\t\t\tGB_ASSERT(elem->kind == Type_Basic);\n\t\t\t\tif (elem->Basic.flags & (BasicFlag_EndianLittle|BasicFlag_EndianBig)) {\n\t\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\t\terror(x.expr, \"Expected a float which does not specify the explicit endianness for '%.*s', got %s\", LIT(builtin_name), xts);\n\t\t\t\t\tgb_string_free(xts);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!are_types_identical(x.type, y.type) || !are_types_identical(y.type, z.type)) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\tgbString yts = type_to_string(y.type);\n\t\t\t\tgbString zts = type_to_string(z.type);\n\t\t\t\terror(x.expr, \"Mismatched types for '%.*s', got %s vs %s vs %s\", LIT(builtin_name), xts, yts, zts);\n\t\t\t\tgb_string_free(zts);\n\t\t\t\tgb_string_free(yts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = default_type(x.type);\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_mem_copy:\n\tcase BuiltinProc_mem_copy_non_overlapping:\n\t\t{\n\t\t\toperand->mode = Addressing_NoValue;\n\t\t\toperand->type = t_invalid;\n\n\t\t\tOperand dst = {};\n\t\t\tOperand src = {};\n\t\t\tOperand len = {};\n\t\t\tcheck_expr(c, &dst, ce->args[0]);\n\t\t\tcheck_expr(c, &src, ce->args[1]);\n\t\t\tcheck_expr(c, &len, ce->args[2]);\n\t\t\tif (dst.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (src.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (len.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\n\t\t\tif (!is_type_pointer(dst.type) && !is_type_multi_pointer(dst.type)) {\n\t\t\t\tgbString str = type_to_string(dst.type);\n\t\t\t\terror(dst.expr, \"Expected a pointer value for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_pointer(src.type) && !is_type_multi_pointer(src.type)) {\n\t\t\t\tgbString str = type_to_string(src.type);\n\t\t\t\terror(src.expr, \"Expected a pointer value for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_integer(len.type)) {\n\t\t\t\tgbString str = type_to_string(len.type);\n\t\t\t\terror(len.expr, \"Expected an integer value for the number of bytes for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (len.mode == Addressing_Constant) {\n\t\t\t\ti64 n = exact_value_to_i64(len.value);\n\t\t\t\tif (n < 0) {\n\t\t\t\t\tgbString str = expr_to_string(len.expr);\n\t\t\t\t\terror(len.expr, \"Expected a non-negative integer value for the number of bytes for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\t\tgb_string_free(str);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_mem_zero:\n\tcase BuiltinProc_mem_zero_volatile:\n\t\t{\n\t\t\toperand->mode = Addressing_NoValue;\n\t\t\toperand->type = t_invalid;\n\n\t\t\tOperand ptr = {};\n\t\t\tOperand len = {};\n\t\t\tcheck_expr(c, &ptr, ce->args[0]);\n\t\t\tcheck_expr(c, &len, ce->args[1]);\n\t\t\tif (ptr.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (len.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\n\t\t\tif (!is_type_pointer(ptr.type) && !is_type_multi_pointer(ptr.type)) {\n\t\t\t\tgbString str = type_to_string(ptr.type);\n\t\t\t\terror(ptr.expr, \"Expected a pointer value for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_integer(len.type)) {\n\t\t\t\tgbString str = type_to_string(len.type);\n\t\t\t\terror(len.expr, \"Expected an integer value for the number of bytes for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (len.mode == Addressing_Constant) {\n\t\t\t\ti64 n = exact_value_to_i64(len.value);\n\t\t\t\tif (n < 0) {\n\t\t\t\t\tgbString str = expr_to_string(len.expr);\n\t\t\t\t\terror(len.expr, \"Expected a non-negative integer value for the number of bytes for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\t\tgb_string_free(str);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_ptr_offset:\n\t\t{\n\t\t\tOperand ptr = {};\n\t\t\tOperand offset = {};\n\t\t\tcheck_expr(c, &ptr, ce->args[0]);\n\t\t\tcheck_expr(c, &offset, ce->args[1]);\n\t\t\tif (ptr.mode == Addressing_Invalid) {\n\t\t\t\toperand->mode = Addressing_Invalid;\n\t\t\t\toperand->type = t_invalid;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (offset.mode == Addressing_Invalid) {\n\t\t\t\toperand->mode = Addressing_Invalid;\n\t\t\t\toperand->type = t_invalid;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = ptr.type;\n\n\t\t\tif (!is_type_pointer(ptr.type)  && !is_type_multi_pointer(ptr.type)) {\n\t\t\t\tgbString str = type_to_string(ptr.type);\n\t\t\t\terror(ptr.expr, \"Expected a pointer value for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (are_types_identical(core_type(ptr.type), t_rawptr)) {\n\t\t\t\tgbString str = type_to_string(ptr.type);\n\t\t\t\terror(ptr.expr, \"Expected a dereferenceable pointer value for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_integer(offset.type)) {\n\t\t\t\tgbString str = type_to_string(offset.type);\n\t\t\t\terror(offset.expr, \"Expected an integer value for the offset parameter for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase BuiltinProc_ptr_sub:\n\t\t{\n\t\t\toperand->mode = Addressing_NoValue;\n\t\t\toperand->type = t_invalid;\n\n\t\t\tOperand ptr0 = {};\n\t\t\tOperand ptr1 = {};\n\t\t\tcheck_expr(c, &ptr0, ce->args[0]);\n\t\t\tcheck_expr(c, &ptr1, ce->args[1]);\n\t\t\tif (ptr0.mode == Addressing_Invalid) {\n\t\t\t\toperand->mode = Addressing_Invalid;\n\t\t\t\toperand->type = t_invalid;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (ptr1.mode == Addressing_Invalid) {\n\t\t\t\toperand->mode = Addressing_Invalid;\n\t\t\t\toperand->type = t_invalid;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = t_int;\n\n\t\t\tif (!is_type_pointer(ptr0.type) && !is_type_multi_pointer(ptr0.type)) {\n\t\t\t\tgbString str = type_to_string(ptr0.type);\n\t\t\t\terror(ptr0.expr, \"Expected a pointer value for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (are_types_identical(core_type(ptr0.type), t_rawptr)) {\n\t\t\t\tgbString str = type_to_string(ptr0.type);\n\t\t\t\terror(ptr0.expr, \"Expected a dereferenceable pointer value for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!is_type_pointer(ptr1.type) && !is_type_multi_pointer(ptr1.type)) {\n\t\t\t\tgbString str = type_to_string(ptr1.type);\n\t\t\t\terror(ptr1.expr, \"Expected a pointer value for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (are_types_identical(core_type(ptr1.type), t_rawptr)) {\n\t\t\t\tgbString str = type_to_string(ptr1.type);\n\t\t\t\terror(ptr1.expr, \"Expected a dereferenceable pointer value for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!are_types_identical(ptr0.type, ptr1.type)) {\n\t\t\t\tgbString xts = type_to_string(ptr0.type);\n\t\t\t\tgbString yts = type_to_string(ptr1.type);\n\t\t\t\terror(ptr0.expr, \"Mismatched types for '%.*s', %s vs %s\", LIT(builtin_name), xts, yts);\n\t\t\t\tgb_string_free(yts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t}\n\t\tbreak;\n\n\n\tcase BuiltinProc_atomic_type_is_lock_free:\n\t\t{\n\t\t\tAst *expr = ce->args[0];\n\t\t\tOperand o = {};\n\t\t\tcheck_expr_or_type(c, &o, expr);\n\n\t\t\tif (o.mode == Addressing_Invalid || o.mode == Addressing_Builtin) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (o.type == nullptr || o.type == t_invalid || is_type_asm_proc(o.type)) {\n\t\t\t\terror(o.expr, \"Invalid argument to '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (is_type_polymorphic(o.type)) {\n\t\t\t\terror(o.expr, \"'%.*s' of polymorphic type cannot be determined\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (is_type_untyped(o.type)) {\n\t\t\t\terror(o.expr, \"'%.*s' of untyped type is not allowed\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *t = o.type;\n\t\t\tbool is_lock_free = is_type_lock_free(t);\n\n\t\t\toperand->mode = Addressing_Constant;\n\t\t\toperand->type = t_untyped_bool;\n\t\t\toperand->value = exact_value_bool(is_lock_free);\n\t\t\tbreak;\n\t\t}\n\n\tcase BuiltinProc_atomic_thread_fence:\n\tcase BuiltinProc_atomic_signal_fence:\n\t\t{\n\t\t\tOdinAtomicMemoryOrder memory_order = {};\n\t\t\tif (!check_atomic_memory_order_argument(c, ce->args[0], builtin_name, &memory_order)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tswitch (memory_order) {\n\t\t\tcase OdinAtomicMemoryOrder_acquire:\n\t\t\tcase OdinAtomicMemoryOrder_release:\n\t\t\tcase OdinAtomicMemoryOrder_acq_rel:\n\t\t\tcase OdinAtomicMemoryOrder_seq_cst:\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\terror(ce->args[0], \"Illegal memory ordering for '%.*s', got .%s\", LIT(builtin_name), OdinAtomicMemoryOrder_strings[memory_order]);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_NoValue;\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_volatile_store:\n\tcase BuiltinProc_unaligned_store:\n\tcase BuiltinProc_non_temporal_store:\n\tcase BuiltinProc_atomic_store:\n\t\t{\n\t\t\tType *elem = nullptr;\n\t\t\tif (!is_type_normal_pointer(operand->type, &elem)) {\n\t\t\t\terror(operand->expr, \"Expected a pointer for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tOperand x = {};\n\t\t\tcheck_expr_with_type_hint(c, &x, ce->args[1], elem);\n\t\t\tcheck_assignment(c, &x, elem, builtin_name);\n\n\t\t\toperand->type = nullptr;\n\t\t\toperand->mode = Addressing_NoValue;\n\t\t\tbreak;\n\t\t}\n\n\tcase BuiltinProc_atomic_store_explicit:\n\t\t{\n\t\t\tType *elem = nullptr;\n\t\t\tif (!is_type_normal_pointer(operand->type, &elem)) {\n\t\t\t\terror(operand->expr, \"Expected a pointer for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tOperand x = {};\n\t\t\tcheck_expr_with_type_hint(c, &x, ce->args[1], elem);\n\t\t\tcheck_assignment(c, &x, elem, builtin_name);\n\n\t\t\tOdinAtomicMemoryOrder memory_order = {};\n\t\t\tif (!check_atomic_memory_order_argument(c, ce->args[2], builtin_name, &memory_order)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tswitch (memory_order) {\n\t\t\tcase OdinAtomicMemoryOrder_consume:\n\t\t\tcase OdinAtomicMemoryOrder_acquire:\n\t\t\tcase OdinAtomicMemoryOrder_acq_rel:\n\t\t\t\terror(ce->args[2], \"Illegal memory order .%s for '%.*s'\", OdinAtomicMemoryOrder_strings[memory_order], LIT(builtin_name));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\toperand->type = nullptr;\n\t\t\toperand->mode = Addressing_NoValue;\n\t\t\tbreak;\n\t\t}\n\n\n\tcase BuiltinProc_volatile_load:\n\tcase BuiltinProc_unaligned_load:\n\tcase BuiltinProc_non_temporal_load:\n\tcase BuiltinProc_atomic_load:\n\t\t{\n\t\t\tType *elem = nullptr;\n\t\t\tif (!is_type_normal_pointer(operand->type, &elem)) {\n\t\t\t\terror(operand->expr, \"Expected a pointer for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\toperand->type = elem;\n\t\t\toperand->mode = Addressing_Value;\n\t\t\tbreak;\n\t\t}\n\n\tcase BuiltinProc_atomic_load_explicit:\n\t\t{\n\t\t\tType *elem = nullptr;\n\t\t\tif (!is_type_normal_pointer(operand->type, &elem)) {\n\t\t\t\terror(operand->expr, \"Expected a pointer for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tOdinAtomicMemoryOrder memory_order = {};\n\t\t\tif (!check_atomic_memory_order_argument(c, ce->args[1], builtin_name, &memory_order)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tswitch (memory_order) {\n\t\t\tcase OdinAtomicMemoryOrder_release:\n\t\t\tcase OdinAtomicMemoryOrder_acq_rel:\n\t\t\t\terror(ce->args[1], \"Illegal memory order .%s for '%.*s'\", OdinAtomicMemoryOrder_strings[memory_order], LIT(builtin_name));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\toperand->type = elem;\n\t\t\toperand->mode = Addressing_Value;\n\t\t\tbreak;\n\t\t}\n\n\tcase BuiltinProc_atomic_add:\n\tcase BuiltinProc_atomic_sub:\n\tcase BuiltinProc_atomic_and:\n\tcase BuiltinProc_atomic_nand:\n\tcase BuiltinProc_atomic_or:\n\tcase BuiltinProc_atomic_xor:\n\tcase BuiltinProc_atomic_exchange:\n\t\t{\n\t\t\tType *elem = nullptr;\n\t\t\tif (!is_type_normal_pointer(operand->type, &elem)) {\n\t\t\t\terror(operand->expr, \"Expected a pointer for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tOperand x = {};\n\t\t\tcheck_expr_with_type_hint(c, &x, ce->args[1], elem);\n\t\t\tcheck_assignment(c, &x, elem, builtin_name);\n\n\t\t\tType *t = type_deref(operand->type);\n\t\t\tswitch (id) {\n\t\t\tcase BuiltinProc_atomic_add:\n\t\t\tcase BuiltinProc_atomic_sub:\n\t\t\t\tif (!is_type_numeric(t)) {\n\t\t\t\t\tgbString str = type_to_string(t);\n\t\t\t\t\terror(operand->expr, \"Expected a numeric type for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\t\tgb_string_free(str);\n\t\t\t\t} else if (is_type_different_to_arch_endianness(t)) {\n\t\t\t\t\tgbString str = type_to_string(t);\n\t\t\t\t\terror(operand->expr, \"Expected a numeric type of the same platform endianness for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\t\tgb_string_free(str);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toperand->type = elem;\n\t\t\toperand->mode = Addressing_Value;\n\t\t\tbreak;\n\t\t}\n\n\tcase BuiltinProc_atomic_add_explicit:\n\tcase BuiltinProc_atomic_sub_explicit:\n\tcase BuiltinProc_atomic_and_explicit:\n\tcase BuiltinProc_atomic_nand_explicit:\n\tcase BuiltinProc_atomic_or_explicit:\n\tcase BuiltinProc_atomic_xor_explicit:\n\tcase BuiltinProc_atomic_exchange_explicit:\n\t\t{\n\t\t\tType *elem = nullptr;\n\t\t\tif (!is_type_normal_pointer(operand->type, &elem)) {\n\t\t\t\terror(operand->expr, \"Expected a pointer for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tOperand x = {};\n\t\t\tcheck_expr_with_type_hint(c, &x, ce->args[1], elem);\n\t\t\tcheck_assignment(c, &x, elem, builtin_name);\n\n\n\t\t\tif (!check_atomic_memory_order_argument(c, ce->args[2], builtin_name, nullptr)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tType *t = type_deref(operand->type);\n\t\t\tswitch (id) {\n\t\t\tcase BuiltinProc_atomic_add_explicit:\n\t\t\tcase BuiltinProc_atomic_sub_explicit:\n\t\t\t\tif (!is_type_numeric(t)) {\n\t\t\t\t\tgbString str = type_to_string(t);\n\t\t\t\t\terror(operand->expr, \"Expected a numeric type for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\t\tgb_string_free(str);\n\t\t\t\t} else if (is_type_different_to_arch_endianness(t)) {\n\t\t\t\t\tgbString str = type_to_string(t);\n\t\t\t\t\terror(operand->expr, \"Expected a numeric type of the same platform endianness for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\t\tgb_string_free(str);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\toperand->type = elem;\n\t\t\toperand->mode = Addressing_Value;\n\t\t\tbreak;\n\t\t}\n\n\tcase BuiltinProc_atomic_compare_exchange_strong:\n\tcase BuiltinProc_atomic_compare_exchange_weak:\n\t\t{\n\t\t\tType *elem = nullptr;\n\t\t\tif (!is_type_normal_pointer(operand->type, &elem)) {\n\t\t\t\terror(operand->expr, \"Expected a pointer for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tcheck_expr_with_type_hint(c, &x, ce->args[1], elem);\n\t\t\tcheck_expr_with_type_hint(c, &y, ce->args[2], elem);\n\t\t\tcheck_assignment(c, &x, elem, builtin_name);\n\t\t\tcheck_assignment(c, &y, elem, builtin_name);\n\n\t\t\tType *t = type_deref(operand->type);\n\t\t\tif (!is_type_comparable(t)) {\n\t\t\t\tgbString str = type_to_string(t);\n\t\t\t\terror(operand->expr, \"Expected a comparable type for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_OptionalOk;\n\t\t\toperand->type = elem;\n\t\t\tbreak;\n\t\t}\n\n\tcase BuiltinProc_atomic_compare_exchange_strong_explicit:\n\tcase BuiltinProc_atomic_compare_exchange_weak_explicit:\n\t\t{\n\t\t\tType *elem = nullptr;\n\t\t\tif (!is_type_normal_pointer(operand->type, &elem)) {\n\t\t\t\terror(operand->expr, \"Expected a pointer for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tcheck_expr_with_type_hint(c, &x, ce->args[1], elem);\n\t\t\tcheck_expr_with_type_hint(c, &y, ce->args[2], elem);\n\t\t\tcheck_assignment(c, &x, elem, builtin_name);\n\t\t\tcheck_assignment(c, &y, elem, builtin_name);\n\n\t\t\tOdinAtomicMemoryOrder success_memory_order = {};\n\t\t\tOdinAtomicMemoryOrder failure_memory_order = {};\n\t\t\tif (!check_atomic_memory_order_argument(c, ce->args[3], builtin_name, &success_memory_order, \"success ordering\")) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!check_atomic_memory_order_argument(c, ce->args[4], builtin_name, &failure_memory_order, \"failure ordering\")) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tType *t = type_deref(operand->type);\n\t\t\tif (!is_type_comparable(t)) {\n\t\t\t\tgbString str = type_to_string(t);\n\t\t\t\terror(operand->expr, \"Expected a comparable type for '%.*s', got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t}\n\n\t\t\tbool invalid_combination = false;\n\n\t\t\tswitch (success_memory_order) {\n\t\t\tcase OdinAtomicMemoryOrder_relaxed:\n\t\t\tcase OdinAtomicMemoryOrder_release:\n\t\t\t\tif (failure_memory_order != OdinAtomicMemoryOrder_relaxed) {\n\t\t\t\t\tinvalid_combination = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OdinAtomicMemoryOrder_consume:\n\t\t\t\tswitch (failure_memory_order) {\n\t\t\t\tcase OdinAtomicMemoryOrder_relaxed:\n\t\t\t\tcase OdinAtomicMemoryOrder_consume:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tinvalid_combination = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OdinAtomicMemoryOrder_acquire:\n\t\t\tcase OdinAtomicMemoryOrder_acq_rel:\n\t\t\t\tswitch (failure_memory_order) {\n\t\t\t\tcase OdinAtomicMemoryOrder_relaxed:\n\t\t\t\tcase OdinAtomicMemoryOrder_consume:\n\t\t\t\tcase OdinAtomicMemoryOrder_acquire:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tinvalid_combination = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OdinAtomicMemoryOrder_seq_cst:\n\t\t\t\tswitch (failure_memory_order) {\n\t\t\t\tcase OdinAtomicMemoryOrder_relaxed:\n\t\t\t\tcase OdinAtomicMemoryOrder_consume:\n\t\t\t\tcase OdinAtomicMemoryOrder_acquire:\n\t\t\t\tcase OdinAtomicMemoryOrder_seq_cst:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tinvalid_combination = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tinvalid_combination = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\n\t\t\tif (invalid_combination) {\n\t\t\t\terror(ce->args[3], \"Illegal memory order pairing for '%.*s', success = .%s, failure = .%s\",\n\t\t\t\t\tLIT(builtin_name),\n\t\t\t\t\tOdinAtomicMemoryOrder_strings[success_memory_order],\n\t\t\t\t\tOdinAtomicMemoryOrder_strings[failure_memory_order]\n\t\t\t\t);\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_OptionalOk;\n\t\t\toperand->type = elem;\n\t\t\tbreak;\n\t\t}\n\n\tcase BuiltinProc_fixed_point_mul:\n\tcase BuiltinProc_fixed_point_div:\n\tcase BuiltinProc_fixed_point_mul_sat:\n\tcase BuiltinProc_fixed_point_div_sat:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tOperand z = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]);\n\t\t\tif (x.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tcheck_expr(c, &y, ce->args[1]);\n\t\t\tif (y.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconvert_to_typed(c, &x, y.type);\n\t\t\tif (x.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconvert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tif (x.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!are_types_identical(x.type, y.type)) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\tgbString yts = type_to_string(y.type);\n\t\t\t\terror(x.expr, \"Mismatched types for '%.*s', %s vs %s\", LIT(builtin_name), xts, yts);\n\t\t\t\tgb_string_free(yts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!is_type_integer(x.type) || is_type_untyped(x.type)) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"Expected an integer type for '%.*s', got %s\", LIT(builtin_name), xts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tcheck_expr(c, &z, ce->args[2]);\n\t\t\tif (z.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (z.mode != Addressing_Constant || !is_type_integer(z.type)) {\n\t\t\t\terror(z.expr, \"Expected a constant integer for the scale in '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\ti64 n = exact_value_to_i64(z.value);\n\t\t\tif (n <= 0) {\n\t\t\t\terror(z.expr, \"Scale parameter in '%.*s' must be positive, got %lld\", LIT(builtin_name), n);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\ti64 sz = 8*type_size_of(x.type);\n\t\t\tif (n > sz) {\n\t\t\t\terror(z.expr, \"Scale parameter in '%.*s' is larger than the base integer bit width, got %lld, expected a maximum of %lld\", LIT(builtin_name), n, sz);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->type = x.type;\n\t\t\toperand->mode = Addressing_Value;\n\t\t}\n\t\tbreak;\n\n\n\tcase BuiltinProc_expect:\n\t\t{\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]);\n\t\t\tcheck_expr(c, &y, ce->args[1]);\n\t\t\tif (x.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (y.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconvert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &x, y.type);\n\t\t\tif (!are_types_identical(x.type, y.type)) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\tgbString yts = type_to_string(y.type);\n\t\t\t\terror(x.expr, \"Mismatched types for '%.*s', %s vs %s\", LIT(builtin_name), xts, yts);\n\t\t\t\tgb_string_free(yts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t\t*operand = x; \/\/ minimize error propagation\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tif (!is_type_integer_like(x.type)) {\n\t\t\t\tgbString xts = type_to_string(x.type);\n\t\t\t\terror(x.expr, \"Values passed to '%.*s' must be an integer-like type (integer, boolean, enum, bit_set), got %s\", LIT(builtin_name), xts);\n\t\t\t\tgb_string_free(xts);\n\t\t\t\t*operand = x;\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tif (y.mode != Addressing_Constant) {\n\t\t\t\terror(y.expr, \"Second argument to '%.*s' must be constant as it is the expected value\", LIT(builtin_name));\n\t\t\t}\n\n\t\t\tif (x.mode == Addressing_Constant) {\n\t\t\t\t\/\/ NOTE(bill): just completely ignore this intrinsic entirely\n\t\t\t\t*operand = x;\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = x.type;\n\t\t}\n\t\tbreak;\n\t\t\n\tcase BuiltinProc_prefetch_read_instruction:\n\tcase BuiltinProc_prefetch_read_data:\n\tcase BuiltinProc_prefetch_write_instruction:\n\tcase BuiltinProc_prefetch_write_data:\n\t\t{\n\t\t\toperand->mode = Addressing_NoValue;\n\t\t\toperand->type = nullptr;\n\t\t\t\n\t\t\tOperand x = {};\n\t\t\tOperand y = {};\n\t\t\tcheck_expr(c, &x, ce->args[0]);\n\t\t\tcheck_expr(c, &y, ce->args[1]);\n\t\t\tif (x.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (y.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tcheck_assignment(c, &x, t_rawptr, builtin_name);\n\t\t\tif (x.mode == Addressing_Invalid) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (y.mode != Addressing_Constant && is_type_integer(y.type)) {\n\t\t\t\terror(y.expr, \"Second argument to '%.*s' representing the locality must be an integer in the range 0..=3\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\ti64 locality = exact_value_to_i64(y.value);\n\t\t\tif (!(0 <= locality && locality <= 3)) {\n\t\t\t\terror(y.expr, \"Second argument to '%.*s' representing the locality must be an integer in the range 0..=3\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\tbreak;\n\t\t\n\tcase BuiltinProc_syscall:\n\t\t{\n\t\t\tconvert_to_typed(c, operand, t_uintptr);\n\t\t\tif (!is_type_uintptr(operand->type)) {\n\t\t\t\tgbString t = type_to_string(operand->type);\n\t\t\t\terror(operand->expr, \"Argument 0 must be of type 'uintptr', got %s\", t);\n\t\t\t\tgb_string_free(t);\n\t\t\t}\n\t\t\tfor (isize i = 1; i < ce->args.count; i++) {\n\t\t\t\tOperand x = {};\n\t\t\t\tcheck_expr(c, &x, ce->args[i]);\n\t\t\t\tif (x.mode != Addressing_Invalid) {\n\t\t\t\t\tconvert_to_typed(c, &x, t_uintptr);\t\n\t\t\t\t}\n\t\t\t\tif (!is_type_uintptr(operand->type)) {\n\t\t\t\t\tgbString t = type_to_string(x.type);\n\t\t\t\t\terror(x.expr, \"Argument %td must be of type 'uintptr', got %s\", i, t);\n\t\t\t\t\tgb_string_free(t);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tisize max_arg_count = 32;\n\t\t\t\n\t\t\tswitch (build_context.metrics.os) {\n\t\t\tcase TargetOs_windows:\n\t\t\tcase TargetOs_freestanding:\n\t\t\t\terror(call, \"'%.*s' is not supported on this platform (%.*s)\", LIT(builtin_name), LIT(target_os_names[build_context.metrics.os]));\n\t\t\t\tbreak;\n\t\t\tcase TargetOs_darwin:\n\t\t\tcase TargetOs_linux:\n\t\t\tcase TargetOs_essence:\n\t\t\tcase TargetOs_freebsd:\n\t\t\tcase TargetOs_openbsd:\n\t\t\t\tswitch (build_context.metrics.arch) {\n\t\t\t\tcase TargetArch_i386:\n\t\t\t\tcase TargetArch_amd64:\n\t\t\t\tcase TargetArch_arm64:\n\t\t\t\t\tmax_arg_count = 7;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tif (ce->args.count > max_arg_count) {\n\t\t\t\terror(ast_end_token(call), \"'%.*s' has a maximum of %td arguments on this platform (%.*s), got %td\", LIT(builtin_name), max_arg_count, LIT(target_os_names[build_context.metrics.os]), ce->args.count);\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = t_uintptr;\n\t\t\treturn true;\n\t\t}\n\t\tbreak;\n\n\n\tcase BuiltinProc_type_base_type:\n\t\tif (operand->mode != Addressing_Type) {\n\t\t\terror(operand->expr, \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t} else {\n\t\t\toperand->type = base_type(operand->type);\n\t\t}\n\t\toperand->mode = Addressing_Type;\n\t\tbreak;\n\tcase BuiltinProc_type_core_type:\n\t\tif (operand->mode != Addressing_Type) {\n\t\t\terror(operand->expr, \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t} else {\n\t\t\toperand->type = core_type(operand->type);\n\t\t}\n\t\toperand->mode = Addressing_Type;\n\t\tbreak;\n\tcase BuiltinProc_type_elem_type:\n\t\tif (operand->mode != Addressing_Type) {\n\t\t\terror(operand->expr, \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t} else {\n\t\t\tType *bt = base_type(operand->type);\n\t\t\tswitch (bt->kind) {\n\t\t\tcase Type_Basic:\n\t\t\t\tswitch (bt->Basic.kind) {\n\t\t\t\tcase Basic_complex64:  operand->type = t_f32; break;\n\t\t\t\tcase Basic_complex128: operand->type = t_f64; break;\n\t\t\t\tcase Basic_quaternion128: operand->type = t_f32; break;\n\t\t\t\tcase Basic_quaternion256: operand->type = t_f64; break;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase Type_Pointer:         operand->type = bt->Pointer.elem;         break;\n\t\t\tcase Type_Array:           operand->type = bt->Array.elem;           break;\n\t\t\tcase Type_EnumeratedArray: operand->type = bt->EnumeratedArray.elem; break;\n\t\t\tcase Type_Slice:           operand->type = bt->Slice.elem;           break;\n\t\t\tcase Type_DynamicArray:    operand->type = bt->DynamicArray.elem;    break;\n\t\t\t}\n\t\t}\n\t\toperand->mode = Addressing_Type;\n\t\tbreak;\n\n\n\tcase BuiltinProc_type_is_boolean:\n\tcase BuiltinProc_type_is_integer:\n\tcase BuiltinProc_type_is_rune:\n\tcase BuiltinProc_type_is_float:\n\tcase BuiltinProc_type_is_complex:\n\tcase BuiltinProc_type_is_quaternion:\n\tcase BuiltinProc_type_is_string:\n\tcase BuiltinProc_type_is_typeid:\n\tcase BuiltinProc_type_is_any:\n\tcase BuiltinProc_type_is_endian_platform:\n\tcase BuiltinProc_type_is_endian_little:\n\tcase BuiltinProc_type_is_endian_big:\n\tcase BuiltinProc_type_is_unsigned:\n\tcase BuiltinProc_type_is_numeric:\n\tcase BuiltinProc_type_is_ordered:\n\tcase BuiltinProc_type_is_ordered_numeric:\n\tcase BuiltinProc_type_is_indexable:\n\tcase BuiltinProc_type_is_sliceable:\n\tcase BuiltinProc_type_is_comparable:\n\tcase BuiltinProc_type_is_simple_compare:\n\tcase BuiltinProc_type_is_dereferenceable:\n\tcase BuiltinProc_type_is_valid_map_key:\n\tcase BuiltinProc_type_is_valid_matrix_elements:\n\tcase BuiltinProc_type_is_named:\n\tcase BuiltinProc_type_is_pointer:\n\tcase BuiltinProc_type_is_multi_pointer:\n\tcase BuiltinProc_type_is_array:\n\tcase BuiltinProc_type_is_enumerated_array:\n\tcase BuiltinProc_type_is_slice:\n\tcase BuiltinProc_type_is_dynamic_array:\n\tcase BuiltinProc_type_is_map:\n\tcase BuiltinProc_type_is_struct:\n\tcase BuiltinProc_type_is_union:\n\tcase BuiltinProc_type_is_enum:\n\tcase BuiltinProc_type_is_proc:\n\tcase BuiltinProc_type_is_bit_set:\n\tcase BuiltinProc_type_is_simd_vector:\n\tcase BuiltinProc_type_is_matrix:\n\tcase BuiltinProc_type_is_specialized_polymorphic_record:\n\tcase BuiltinProc_type_is_unspecialized_polymorphic_record:\n\tcase BuiltinProc_type_has_nil:\n\t\tGB_ASSERT(BuiltinProc__type_simple_boolean_begin < id && id < BuiltinProc__type_simple_boolean_end);\n\n\t\toperand->value = exact_value_bool(false);\n\t\tif (operand->mode != Addressing_Type) {\n\t\t\tgbString str = expr_to_string(ce->args[0]);\n\t\t\terror(operand->expr, \"Expected a type for '%.*s', got '%s'\", LIT(builtin_name), str);\n\t\t\tgb_string_free(str);\n\t\t} else {\n\t\t\ti32 i = id - cast(i32)BuiltinProc__type_simple_boolean_begin;\n\t\t\tauto procedure = builtin_type_is_procs[i];\n\t\t\tGB_ASSERT_MSG(procedure != nullptr, \"%.*s\", LIT(builtin_name));\n\t\t\tbool ok = procedure(operand->type);\n\t\t\toperand->value = exact_value_bool(ok);\n\t\t}\n\t\toperand->mode = Addressing_Constant;\n\t\toperand->type = t_untyped_bool;\n\t\tbreak;\n\n\tcase BuiltinProc_type_has_field:\n\t\t{\n\t\t\tOperand op = {};\n\t\t\tType *bt = check_type(c, ce->args[0]);\n\t\t\tType *type = base_type(bt);\n\t\t\tif (type == nullptr || type == t_invalid) {\n\t\t\t\terror(ce->args[0], \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[1]);\n\n\t\t\tif (!is_type_string(x.type) || x.mode != Addressing_Constant || x.value.kind != ExactValue_String) {\n\t\t\t\terror(ce->args[1], \"Expected a const string for field argument\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tString field_name = x.value.value_string;\n\n\t\t\tSelection sel = lookup_field(type, field_name, false);\n\t\t\toperand->mode = Addressing_Constant;\n\t\t\toperand->value = exact_value_bool(sel.index.count != 0);\n\t\t\toperand->type = t_untyped_bool;\n\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase BuiltinProc_type_field_type:\n\t\t{\n\t\t\tOperand op = {};\n\t\t\tType *bt = check_type(c, ce->args[0]);\n\t\t\tType *type = base_type(bt);\n\t\t\tif (type == nullptr || type == t_invalid) {\n\t\t\t\terror(ce->args[0], \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[1]);\n\n\t\t\tif (!is_type_string(x.type) || x.mode != Addressing_Constant || x.value.kind != ExactValue_String) {\n\t\t\t\terror(ce->args[1], \"Expected a const string for field argument\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tString field_name = x.value.value_string;\n\n\t\t\tSelection sel = lookup_field(type, field_name, false);\n\t\t\tif (sel.index.count == 0) {\n\t\t\t\tgbString t = type_to_string(type);\n\t\t\t\terror(ce->args[1], \"'%.*s' is not a field of type %s\", LIT(field_name), t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\toperand->mode = Addressing_Type;\n\t\t\toperand->type = sel.entity->type;\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_type_is_specialization_of:\n\t\t{\n\t\t\tif (operand->mode != Addressing_Type) {\n\t\t\t\terror(operand->expr, \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t\t\toperand->mode = Addressing_Invalid;\n\t\t\t\toperand->type = t_invalid;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *t = operand->type;\n\t\t\tType *s = nullptr;\n\n\t\t\tbool prev_ips = c->in_polymorphic_specialization;\n\t\t\tc->in_polymorphic_specialization = true;\n\t\t\ts = check_type(c, ce->args[1]);\n\t\t\tc->in_polymorphic_specialization = prev_ips;\n\n\t\t\tif (s == t_invalid) {\n\t\t\t\terror(ce->args[1], \"Invalid specialization type for '%.*s'\", LIT(builtin_name));\n\t\t\t\toperand->mode = Addressing_Invalid;\n\t\t\t\toperand->type = t_invalid;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Constant;\n\t\t\toperand->type = t_untyped_bool;\n\t\t\toperand->value = exact_value_bool(check_type_specialization_to(c, s, t, false, false));\n\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_type_is_variant_of:\n\t\t{\n\t\t\tif (operand->mode != Addressing_Type) {\n\t\t\t\terror(operand->expr, \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t\t\toperand->mode = Addressing_Invalid;\n\t\t\t\toperand->type = t_invalid;\n\t\t\t\treturn false;\n\t\t\t}\n\n\n\t\t\tType *u = operand->type;\n\n\t\t\tif (!is_type_union(u)) {\n\t\t\t\terror(operand->expr, \"Expected a union type for '%.*s'\", LIT(builtin_name));\n\t\t\t\toperand->mode = Addressing_Invalid;\n\t\t\t\toperand->type = t_invalid;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tType *v = check_type(c, ce->args[1]);\n\n\t\t\tu = base_type(u);\n\t\t\tGB_ASSERT(u->kind == Type_Union);\n\n\t\t\tbool is_variant = false;\n\n\t\t\tfor_array(i, u->Union.variants) {\n\t\t\t\tType *vt = u->Union.variants[i];\n\t\t\t\tif (are_types_identical(v, vt)) {\n\t\t\t\t\tis_variant = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Constant;\n\t\t\toperand->type = t_untyped_bool;\n\t\t\toperand->value = exact_value_bool(is_variant);\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_type_struct_field_count:\n\t\toperand->value = exact_value_i64(0);\n\t\tif (operand->mode != Addressing_Type) {\n\t\t\terror(operand->expr, \"Expected a struct type for '%.*s'\", LIT(builtin_name));\n\t\t} else if (!is_type_struct(operand->type)) {\n\t\t\terror(operand->expr, \"Expected a struct type for '%.*s'\", LIT(builtin_name));\n\t\t} else {\n\t\t\tType *bt = base_type(operand->type);\n\t\t\toperand->value = exact_value_i64(bt->Struct.fields.count);\n\t\t}\n\t\toperand->mode = Addressing_Constant;\n\t\toperand->type = t_untyped_integer;\n\t\tbreak;\n\n\tcase BuiltinProc_type_proc_parameter_count:\n\t\toperand->value = exact_value_i64(0);\n\t\tif (operand->mode != Addressing_Type) {\n\t\t\terror(operand->expr, \"Expected a procedure type for '%.*s'\", LIT(builtin_name));\n\t\t} else if (!is_type_proc(operand->type)) {\n\t\t\terror(operand->expr, \"Expected a procedure type for '%.*s'\", LIT(builtin_name));\n\t\t} else {\n\t\t\tType *bt = base_type(operand->type);\n\t\t\toperand->value = exact_value_i64(bt->Proc.param_count);\n\t\t}\n\t\toperand->mode = Addressing_Constant;\n\t\toperand->type = t_untyped_integer;\n\t\tbreak;\n\tcase BuiltinProc_type_proc_return_count:\n\t\toperand->value = exact_value_i64(0);\n\t\tif (operand->mode != Addressing_Type) {\n\t\t\terror(operand->expr, \"Expected a procedure type for '%.*s'\", LIT(builtin_name));\n\t\t} else if (!is_type_proc(operand->type)) {\n\t\t\terror(operand->expr, \"Expected a procedure type for '%.*s'\", LIT(builtin_name));\n\t\t} else {\n\t\t\tType *bt = base_type(operand->type);\n\t\t\toperand->value = exact_value_i64(bt->Proc.result_count);\n\t\t}\n\t\toperand->mode = Addressing_Constant;\n\t\toperand->type = t_untyped_integer;\n\t\tbreak;\n\n\tcase BuiltinProc_type_proc_parameter_type:\n\t\tif (operand->mode != Addressing_Type || !is_type_proc(operand->type)) {\n\t\t\terror(operand->expr, \"Expected a procedure type for '%.*s'\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t} else {\n\t\t\tif (is_type_polymorphic(operand->type)) {\n\t\t\t\terror(operand->expr, \"Expected a non-polymorphic procedure type for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tOperand op = {};\n\t\t\tcheck_expr(c, &op, ce->args[1]);\n\t\t\tif (op.mode != Addressing_Constant && !is_type_integer(op.type)) {\n\t\t\t\terror(op.expr, \"Expected a constant integer for the index of procedure parameter value\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\ti64 index = exact_value_to_i64(op.value);\n\t\t\tif (index < 0) {\n\t\t\t\terror(op.expr, \"Expected a non-negative integer for the index of procedure parameter value, got %lld\", cast(long long)index);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tEntity *param = nullptr;\n\t\t\ti64 count = 0;\n\n\t\t\tType *bt = base_type(operand->type);\n\t\t\tif (bt->kind == Type_Proc) {\n\t\t\t\tcount = bt->Proc.param_count;\n\t\t\t\tif (index < count) {\n\t\t\t\t\tparam = bt->Proc.params->Tuple.variables[cast(isize)index];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (index >= count) {\n\t\t\t\terror(op.expr, \"Index of procedure parameter value out of bounds, expected 0..<%lld, got %lld\", cast(long long)count, cast(long long)index);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tGB_ASSERT(param != nullptr);\n\t\t\tswitch (param->kind) {\n\t\t\tcase Entity_Constant:\n\t\t\t\toperand->mode = Addressing_Constant;\n\t\t\t\toperand->type = param->type;\n\t\t\t\toperand->value = param->Constant.value;\n\t\t\t\tbreak;\n\t\t\tcase Entity_TypeName:\n\t\t\tcase Entity_Variable:\n\t\t\t\toperand->mode = Addressing_Type;\n\t\t\t\toperand->type = param->type;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tGB_PANIC(\"Unhandled procedure entity type %d\", param->kind);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t}\n\n\t\tbreak;\n\n\tcase BuiltinProc_type_proc_return_type:\n\t\tif (operand->mode != Addressing_Type || !is_type_proc(operand->type)) {\n\t\t\terror(operand->expr, \"Expected a procedure type for '%.*s'\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t} else {\n\t\t\tif (is_type_polymorphic(operand->type)) {\n\t\t\t\terror(operand->expr, \"Expected a non-polymorphic procedure type for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tOperand op = {};\n\t\t\tcheck_expr(c, &op, ce->args[1]);\n\t\t\tif (op.mode != Addressing_Constant && !is_type_integer(op.type)) {\n\t\t\t\terror(op.expr, \"Expected a constant integer for the index of procedure parameter value\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\ti64 index = exact_value_to_i64(op.value);\n\t\t\tif (index < 0) {\n\t\t\t\terror(op.expr, \"Expected a non-negative integer for the index of procedure parameter value, got %lld\", cast(long long)index);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tEntity *param = nullptr;\n\t\t\ti64 count = 0;\n\n\t\t\tType *bt = base_type(operand->type);\n\t\t\tif (bt->kind == Type_Proc) {\n\t\t\t\tcount = bt->Proc.result_count;\n\t\t\t\tif (index < count) {\n\t\t\t\t\tparam = bt->Proc.results->Tuple.variables[cast(isize)index];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (index >= count) {\n\t\t\t\terror(op.expr, \"Index of procedure parameter value out of bounds, expected 0..<%lld, got %lld\", cast(long long)count, cast(long long)index);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tGB_ASSERT(param != nullptr);\n\t\t\tswitch (param->kind) {\n\t\t\tcase Entity_Constant:\n\t\t\t\toperand->mode = Addressing_Constant;\n\t\t\t\toperand->type = param->type;\n\t\t\t\toperand->value = param->Constant.value;\n\t\t\t\tbreak;\n\t\t\tcase Entity_TypeName:\n\t\t\tcase Entity_Variable:\n\t\t\t\toperand->mode = Addressing_Type;\n\t\t\t\toperand->type = param->type;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tGB_PANIC(\"Unhandled procedure entity type %d\", param->kind);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t}\n\n\t\tbreak;\n\n\tcase BuiltinProc_type_polymorphic_record_parameter_count:\n\t\toperand->value = exact_value_i64(0);\n\t\tif (operand->mode != Addressing_Type) {\n\t\t\terror(operand->expr, \"Expected a record type for '%.*s'\", LIT(builtin_name));\n\t\t} else {\n\t\t\tType *bt = base_type(operand->type);\n\t\t\tif (bt->kind == Type_Struct) {\n\t\t\t\tif (bt->Struct.polymorphic_params != nullptr) {\n\t\t\t\t\toperand->value = exact_value_i64(bt->Struct.polymorphic_params->Tuple.variables.count);\n\t\t\t\t}\n\t\t\t} else if (bt->kind == Type_Union) {\n\t\t\t\tif (bt->Union.polymorphic_params != nullptr) {\n\t\t\t\t\toperand->value = exact_value_i64(bt->Union.polymorphic_params->Tuple.variables.count);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terror(operand->expr, \"Expected a record type for '%.*s'\", LIT(builtin_name));\n\t\t\t}\n\t\t}\n\t\toperand->mode = Addressing_Constant;\n\t\toperand->type = t_untyped_integer;\n\t\tbreak;\n\tcase BuiltinProc_type_polymorphic_record_parameter_value:\n\t\tif (operand->mode != Addressing_Type) {\n\t\t\terror(operand->expr, \"Expected a record type for '%.*s'\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t} else if (!is_type_polymorphic_record_specialized(operand->type)) {\n\t\t\terror(operand->expr, \"Expected a specialized polymorphic record type for '%.*s'\", LIT(builtin_name));\n\t\t\treturn false;\n\t\t} else {\n\t\t\tOperand op = {};\n\t\t\tcheck_expr(c, &op, ce->args[1]);\n\t\t\tif (op.mode != Addressing_Constant && !is_type_integer(op.type)) {\n\t\t\t\terror(op.expr, \"Expected a constant integer for the index of record parameter value\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\ti64 index = exact_value_to_i64(op.value);\n\t\t\tif (index < 0) {\n\t\t\t\terror(op.expr, \"Expected a non-negative integer for the index of record parameter value, got %lld\", cast(long long)index);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tEntity *param = nullptr;\n\t\t\ti64 count = 0;\n\n\t\t\tType *bt = base_type(operand->type);\n\t\t\tif (bt->kind == Type_Struct) {\n\t\t\t\tif (bt->Struct.polymorphic_params != nullptr) {\n\t\t\t\t\tcount = bt->Struct.polymorphic_params->Tuple.variables.count;\n\t\t\t\t\tif (index < count) {\n\t\t\t\t\t\tparam = bt->Struct.polymorphic_params->Tuple.variables[cast(isize)index];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (bt->kind == Type_Union) {\n\t\t\t\tif (bt->Union.polymorphic_params != nullptr) {\n\t\t\t\t\tcount = bt->Union.polymorphic_params->Tuple.variables.count;\n\t\t\t\t\tif (index < count) {\n\t\t\t\t\t\tparam = bt->Union.polymorphic_params->Tuple.variables[cast(isize)index];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terror(operand->expr, \"Expected a specialized polymorphic record type for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (index >= count) {\n\t\t\t\terror(op.expr, \"Index of record parameter value out of bounds, expected 0..<%lld, got %lld\", cast(long long)count, cast(long long)index);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tGB_ASSERT(param != nullptr);\n\t\t\tswitch (param->kind) {\n\t\t\tcase Entity_Constant:\n\t\t\t\toperand->mode = Addressing_Constant;\n\t\t\t\toperand->type = param->type;\n\t\t\t\toperand->value = param->Constant.value;\n\t\t\t\tbreak;\n\t\t\tcase Entity_TypeName:\n\t\t\t\toperand->mode = Addressing_Type;\n\t\t\t\toperand->type = param->type;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tGB_PANIC(\"Unhandled polymorphic record type\");\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t}\n\n\t\tbreak;\n\n\tcase BuiltinProc_type_is_subtype_of:\n\t\t{\n\t\t\tOperand op_src = {};\n\t\t\tOperand op_dst = {};\n\n\t\t\tcheck_expr_or_type(c, &op_src, ce->args[0]);\n\t\t\tif (op_src.mode != Addressing_Type) {\n\t\t\t\tgbString e = expr_to_string(op_src.expr);\n\t\t\t\terror(op_src.expr, \"'%.*s' expects a type, got %s\", LIT(builtin_name), e);\n\t\t\t\tgb_string_free(e);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tcheck_expr_or_type(c, &op_dst, ce->args[1]);\n\t\t\tif (op_dst.mode != Addressing_Type) {\n\t\t\t\tgbString e = expr_to_string(op_dst.expr);\n\t\t\t\terror(op_dst.expr, \"'%.*s' expects a type, got %s\", LIT(builtin_name), e);\n\t\t\t\tgb_string_free(e);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->value = exact_value_bool(is_type_subtype_of(op_src.type, op_dst.type));\n\t\t\toperand->mode = Addressing_Constant;\n\t\t\toperand->type = t_untyped_bool;\n\t\t} break;\n\n\tcase BuiltinProc_type_field_index_of:\n\t\t{\n\t\t\tOperand op = {};\n\t\t\tType *bt = check_type(c, ce->args[0]);\n\t\t\tType *type = base_type(bt);\n\t\t\tif (type == nullptr || type == t_invalid) {\n\t\t\t\terror(ce->args[0], \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tOperand x = {};\n\t\t\tcheck_expr(c, &x, ce->args[1]);\n\n\t\t\tif (!is_type_string(x.type) || x.mode != Addressing_Constant || x.value.kind != ExactValue_String) {\n\t\t\t\terror(ce->args[1], \"Expected a const string for field argument\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tString field_name = x.value.value_string;\n\n\t\t\tSelection sel = lookup_field(type, field_name, false);\n\t\t\tif (sel.entity == nullptr) {\n\t\t\t\tgbString type_str = type_to_string(bt);\n\t\t\t\terror(ce->args[0],\n\t\t\t\t      \"'%s' has no field named '%.*s'\", type_str, LIT(field_name));\n\t\t\t\tgb_string_free(type_str);\n\n\t\t\t\tif (bt->kind == Type_Struct) {\n\t\t\t\t\tcheck_did_you_mean_type(field_name, bt->Struct.fields);\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (sel.indirect) {\n\t\t\t\tgbString type_str = type_to_string(bt);\n\t\t\t\terror(ce->args[0],\n\t\t\t\t      \"Field '%.*s' is embedded via a pointer in '%s'\", LIT(field_name), type_str);\n\t\t\t\tgb_string_free(type_str);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Constant;\n\t\t\toperand->value = exact_value_u64(sel.index[0]);\n\t\t\toperand->type = t_uintptr;\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_type_equal_proc:\n\t\t{\n\t\t\tOperand op = {};\n\t\t\tType *bt = check_type(c, ce->args[0]);\n\t\t\tType *type = base_type(bt);\n\t\t\tif (type == nullptr || type == t_invalid) {\n\t\t\t\terror(ce->args[0], \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_comparable(type)) {\n\t\t\t\tgbString t = type_to_string(type);\n\t\t\t\terror(ce->args[0], \"Expected a comparable type for '%.*s', got %s\", LIT(builtin_name), t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = t_equal_proc;\n\t\t\tbreak;\n\t\t}\n\n\tcase BuiltinProc_type_hasher_proc:\n\t\t{\n\t\t\tOperand op = {};\n\t\t\tType *bt = check_type(c, ce->args[0]);\n\t\t\tType *type = base_type(bt);\n\t\t\tif (type == nullptr || type == t_invalid) {\n\t\t\t\terror(ce->args[0], \"Expected a type for '%.*s'\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!is_type_valid_for_keys(type)) {\n\t\t\t\tgbString t = type_to_string(type);\n\t\t\t\terror(ce->args[0], \"Expected a valid type for map keys for '%.*s', got %s\", LIT(builtin_name), t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tadd_map_key_type_dependencies(c, type);\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = t_hasher_proc;\n\t\t\tbreak;\n\t\t}\n\n\tcase BuiltinProc_constant_utf16_cstring:\n\t\t{\n\t\t\tString value = {};\n\t\t\tif (!is_constant_string(c, builtin_name, ce->args[0], &value)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = alloc_type_multi_pointer(t_u16);\n\t\t\toperand->value = {};\n\t\t\tbreak;\n\t\t}\n\n\n\tcase BuiltinProc_wasm_memory_grow:\n\t\t{\n\t\t\tif (!is_arch_wasm()) {\n\t\t\t\terror(call, \"'%.*s' is only allowed on wasm targets\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tOperand index = {};\n\t\t\tOperand delta = {};\n\t\t\tcheck_expr(c, &index, ce->args[0]); if (index.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr(c, &delta, ce->args[1]); if (delta.mode == Addressing_Invalid) return false;\n\n\t\t\tconvert_to_typed(c, &index, t_uintptr); if (index.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &delta, t_uintptr); if (delta.mode == Addressing_Invalid) return false;\n\n\t\t\tif (!is_operand_value(index) || !check_is_assignable_to(c, &index, t_uintptr)) {\n\t\t\t\tgbString e = expr_to_string(index.expr);\n\t\t\t\tgbString t = type_to_string(index.type);\n\t\t\t\terror(index.expr, \"'%.*s' expected a uintptr for the memory index, got '%s' of type %s\", LIT(builtin_name), e, t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\tgb_string_free(e);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!is_operand_value(delta) || !check_is_assignable_to(c, &delta, t_uintptr)) {\n\t\t\t\tgbString e = expr_to_string(delta.expr);\n\t\t\t\tgbString t = type_to_string(delta.type);\n\t\t\t\terror(delta.expr, \"'%.*s' expected a uintptr for the memory delta, got '%s' of type %s\", LIT(builtin_name), e, t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\tgb_string_free(e);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = t_int;\n\t\t\toperand->value = {};\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase BuiltinProc_wasm_memory_size:\n\t\t{\n\t\t\tif (!is_arch_wasm()) {\n\t\t\t\terror(call, \"'%.*s' is only allowed on wasm targets\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tOperand index = {};\n\t\t\tcheck_expr(c, &index, ce->args[0]); if (index.mode == Addressing_Invalid) return false;\n\n\t\t\tconvert_to_typed(c, &index, t_uintptr); if (index.mode == Addressing_Invalid) return false;\n\n\t\t\tif (!is_operand_value(index) || !check_is_assignable_to(c, &index, t_uintptr)) {\n\t\t\t\tgbString e = expr_to_string(index.expr);\n\t\t\t\tgbString t = type_to_string(index.type);\n\t\t\t\terror(index.expr, \"'%.*s' expected a uintptr for the memory index, got '%s' of type %s\", LIT(builtin_name), e, t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\tgb_string_free(e);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = t_int;\n\t\t\toperand->value = {};\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_wasm_memory_atomic_wait32:\n\t\t{\n\t\t\tif (!is_arch_wasm()) {\n\t\t\t\terror(call, \"'%.*s' is only allowed on wasm targets\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tOperand ptr = {};\n\t\t\tOperand expected = {};\n\t\t\tOperand timeout = {};\n\t\t\tcheck_expr(c, &ptr,      ce->args[0]); if (ptr.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr(c, &expected, ce->args[1]); if (expected.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr(c, &timeout,  ce->args[2]); if (timeout.mode == Addressing_Invalid) return false;\n\n\t\t\tType *t_u32_ptr = alloc_type_pointer(t_u32);\n\t\t\tconvert_to_typed(c, &ptr, t_u32_ptr);  if (ptr.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &expected, t_u32); if (expected.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &timeout, t_i64);  if (timeout.mode == Addressing_Invalid) return false;\n\n\t\t\tif (!is_operand_value(ptr) || !check_is_assignable_to(c, &ptr, t_u32_ptr)) {\n\t\t\t\tgbString e = expr_to_string(ptr.expr);\n\t\t\t\tgbString t = type_to_string(ptr.type);\n\t\t\t\terror(ptr.expr, \"'%.*s' expected ^u32 for the memory pointer, got '%s' of type %s\", LIT(builtin_name), e, t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\tgb_string_free(e);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!is_operand_value(expected) || !check_is_assignable_to(c, &expected, t_u32)) {\n\t\t\t\tgbString e = expr_to_string(expected.expr);\n\t\t\t\tgbString t = type_to_string(expected.type);\n\t\t\t\terror(expected.expr, \"'%.*s' expected u32 for the 'expected' value, got '%s' of type %s\", LIT(builtin_name), e, t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\tgb_string_free(e);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!is_operand_value(timeout) || !check_is_assignable_to(c, &timeout, t_i64)) {\n\t\t\t\tgbString e = expr_to_string(timeout.expr);\n\t\t\t\tgbString t = type_to_string(timeout.type);\n\t\t\t\terror(timeout.expr, \"'%.*s' expected i64 for the timeout, got '%s' of type %s\", LIT(builtin_name), e, t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\tgb_string_free(e);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = t_u32;\n\t\t\toperand->value = {};\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase BuiltinProc_wasm_memory_atomic_notify32:\n\t\t{\n\t\t\tif (!is_arch_wasm()) {\n\t\t\t\terror(call, \"'%.*s' is only allowed on wasm targets\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tOperand ptr = {};\n\t\t\tOperand waiters = {};\n\t\t\tcheck_expr(c, &ptr,     ce->args[0]); if (ptr.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr(c, &waiters, ce->args[1]); if (waiters.mode == Addressing_Invalid) return false;\n\n\t\t\tType *t_u32_ptr = alloc_type_pointer(t_u32);\n\t\t\tconvert_to_typed(c, &ptr, t_u32_ptr); if (ptr.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &waiters, t_u32); if (waiters.mode == Addressing_Invalid) return false;\n\n\t\t\tif (!is_operand_value(ptr) || !check_is_assignable_to(c, &ptr, t_u32_ptr)) {\n\t\t\t\tgbString e = expr_to_string(ptr.expr);\n\t\t\t\tgbString t = type_to_string(ptr.type);\n\t\t\t\terror(ptr.expr, \"'%.*s' expected ^u32 for the memory pointer, got '%s' of type %s\", LIT(builtin_name), e, t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\tgb_string_free(e);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!is_operand_value(waiters) || !check_is_assignable_to(c, &waiters, t_u32)) {\n\t\t\t\tgbString e = expr_to_string(waiters.expr);\n\t\t\t\tgbString t = type_to_string(waiters.type);\n\t\t\t\terror(waiters.expr, \"'%.*s' expected u32 for the 'waiters' value, got '%s' of type %s\", LIT(builtin_name), e, t);\n\t\t\t\tgb_string_free(t);\n\t\t\t\tgb_string_free(e);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->type = t_u32;\n\t\t\toperand->value = {};\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase BuiltinProc_x86_cpuid:\n\t\t{\n\t\t\tif (!is_arch_x86()) {\n\t\t\t\terror(call, \"'%.*s' is only allowed on x86 targets (i386, amd64)\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tOperand ax = {};\n\t\t\tOperand cx = {};\n\n\t\t\tcheck_expr_with_type_hint(c, &ax, ce->args[0], t_u32); if (ax.mode == Addressing_Invalid) return false;\n\t\t\tcheck_expr_with_type_hint(c, &cx, ce->args[1], t_u32); if (cx.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &ax, t_u32); if (ax.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &cx, t_u32); if (cx.mode == Addressing_Invalid) return false;\n\t\t\tif (!are_types_identical(ax.type, t_u32)) {\n\t\t\t\tgbString str = type_to_string(ax.type);\n\t\t\t\terror(ax.expr, \"'%.*s' expected a u32, got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!are_types_identical(cx.type, t_u32)) {\n\t\t\t\tgbString str = type_to_string(cx.type);\n\t\t\t\terror(cx.expr, \"'%.*s' expected a u32, got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tType *types[4] = {t_u32, t_u32, t_u32, t_u32}; \/\/ eax ebc ecx edx\n\t\t\toperand->type = alloc_type_tuple_from_field_types(types, gb_count_of(types), false, false);\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->value = {};\n\t\t\treturn true;\n\t\t}\n\t\tbreak;\n\tcase BuiltinProc_x86_xgetbv:\n\t\t{\n\t\t\tif (!is_arch_x86()) {\n\t\t\t\terror(call, \"'%.*s' is only allowed on x86 targets (i386, amd64)\", LIT(builtin_name));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tOperand cx = {};\n\t\t\tcheck_expr_with_type_hint(c, &cx, ce->args[0], t_u32); if (cx.mode == Addressing_Invalid) return false;\n\t\t\tconvert_to_typed(c, &cx, t_u32); if (cx.mode == Addressing_Invalid) return false;\n\t\t\tif (!are_types_identical(cx.type, t_u32)) {\n\t\t\t\tgbString str = type_to_string(cx.type);\n\t\t\t\terror(cx.expr, \"'%.*s' expected a u32, got %s\", LIT(builtin_name), str);\n\t\t\t\tgb_string_free(str);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tType *types[2] = {t_u32, t_u32};\n\t\t\toperand->type = alloc_type_tuple_from_field_types(types, gb_count_of(types), false, false);\n\t\t\toperand->mode = Addressing_Value;\n\t\t\toperand->value = {};\n\t\t\treturn true;\n\t\t}\n\t\tbreak;\n\n\t}\n\n\treturn true;\n}\n","avg_line_length":31.3781103835,"max_line_length":203,"alphanum_fraction":0.6599728112,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4093,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"#include \"CubeWindow.hpp\"\n\n#include <QOpenGLFunctions>\n#include <QScreen>\n\n#include <array>\n\nnamespace {\n\nfloat positions[] = {\n    -0.5f, -0.5f, 0.5f,  \/\/ 0\n    0.5f,  -0.5f, 0.5f,  \/\/ 1\n    -0.5f, 0.5f,  0.5f,  \/\/ 2\n    0.5f,  0.5f,  0.5f,  \/\/ 3\n    0.5f,  -0.5f, -0.5f, \/\/ 4\n    0.5f,  0.5f,  -0.5f, \/\/ 5\n    -0.5f, -0.5f, -0.5f, \/\/ 6\n    -0.5f, 0.5f,  -0.5f, \/\/ 7\n};\n\nunsigned int indices[] = {\n    0, 1, 2, 3, 3,    \/\/ front\n    1, 1, 4, 3, 5, 5, \/\/ right\n    4, 4, 6, 5, 7, 7, \/\/ back\n    6, 6, 0, 7, 2, 2, \/\/ left\n    6, 6, 4, 0, 1, 1, \/\/ bottom\n    2, 2, 3, 7, 5     \/\/ top\n};\n\n} \/\/ namespace\n\nnamespace fgl {\n\nvoid CubeWindow::init() {\n  program_ = std::make_unique<QOpenGLShaderProgram>(this);\n\n  \/\/ Compiles source as a shader of the specified type and adds it to this\n  \/\/ shader program. Returns true if compilation was successful, false\n  \/\/ otherwise.\n  program_->addShaderFromSourceFile(QOpenGLShader::Vertex, \":\/Shaders\/cube.vs\");\n  program_->addShaderFromSourceFile(QOpenGLShader::Fragment,\n                                    \":\/Shaders\/cube.fs\");\n\n  \/\/ Links together the shaders that were added to this program with addShader()\n  program_->link();\n\n  \/\/ Returns the location of the attribute\n  posAttr_ = program_->attributeLocation(\"posAttr\");\n  Q_ASSERT(posAttr_ != -1);\n\n  matrixUniform_ = program_->uniformLocation(\"matrix\");\n  Q_ASSERT(matrixUniform_ != -1);\n  colorUniform_ = program_->uniformLocation(\"color\");\n  Q_ASSERT(colorUniform_ != -1);\n\n  glGenBuffers(1, &vertex_buffer);\n  glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);\n  glBufferData(GL_ARRAY_BUFFER, 8 * 3 * sizeof(float), positions,\n               GL_STATIC_DRAW);\n\n  glGenBuffers(1, &ibo);\n  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);\n  glBufferData(GL_ELEMENT_ARRAY_BUFFER, 34 * sizeof(unsigned int), indices,\n               GL_STATIC_DRAW);\n\n  glDisable(GL_DEPTH_TEST);\n  glDisable(GL_CULL_FACE);\n}\n\nvoid CubeWindow::render() {\n\n  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n  \/\/ Returns the ratio between physical pixels and device-independent pixels for\n  \/\/ the window.\n  \/\/ This value is dependent on the screen the window\n  \/\/ From QScreen\n  const auto retinaScale = devicePixelRatio();\n\n  \/\/ width, height from QScreen, in pixels\n  glViewport(0, 0, width() * retinaScale, height() * retinaScale);\n\n  \/\/ Binds this shader program to the active QOpenGLContext and makes it the\n  \/\/ current shader program. Any previously bound shader program is released.\n  program_->bind();\n\n  QMatrix4x4 matrix;\n  matrix.perspective(60.0f, 4.0f \/ 3.0f, 0.1f, 100.0f);\n  matrix.translate(0, 0, -2);\n  matrix.rotate(100.0 * frame_ \/ screen()->refreshRate(), rotationAxis);\n\n  \/\/ Sets the uniform variable called name in the current to a 4x4 matrix value.\n  program_->setUniformValue(matrixUniform_, matrix);\n  program_->setUniformValue(colorUniform_, color);\n\n  glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);\n  glVertexAttribPointer(posAttr_, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), 0);\n\n  \/\/ Enable or disable a generic vertex attribute array\n  glEnableVertexAttribArray(posAttr_);\n\n  \/\/ render primitives from array data\n  glDrawElements(GL_TRIANGLE_STRIP, 34, GL_UNSIGNED_INT, nullptr);\n\n  glDisableVertexAttribArray(posAttr_);\n\n  \/\/ Releases the active shader program from the current QOpenGLContext.\n  program_->release();\n\n  ++frame_;\n}\n\nvoid CubeWindow::mousePressEvent(QMouseEvent *e) {\n  \/\/ Save mouse press position\n  mousePressPosition = QVector2D(e->localPos());\n}\n\nvoid CubeWindow::mouseReleaseEvent(QMouseEvent *e) {\n  \/\/ Mouse release position - mouse press position\n  const auto diff = QVector2D(e->localPos()) - mousePressPosition;\n\n  \/\/ Rotation axis is perpendicular to the mouse position difference vector\n  rotationAxis = QVector3D(diff.y(), diff.x(), 0.0).normalized();\n}\n\nvoid CubeWindow::keyPressEvent(QKeyEvent *e) {\n  if (e->key() == Qt::Key_Space) {\n    const auto chosen_color = QColorDialog::getColor();\n    color =\n        QVector4D(chosen_color.red() \/ 255.0f, chosen_color.green() \/ 255.0f,\n                  chosen_color.blue() \/ 255.0f, 0.2f);\n  }\n}\n\n} \/\/ namespace fgl","avg_line_length":30.3185185185,"max_line_length":80,"alphanum_fraction":0.6762765698,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":80742,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/ Copyright 2016 The SwiftShader Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"SamplerCore.hpp\"\n\n#include \"Constants.hpp\"\n#include \"PixelRoutine.hpp\"\n#include \"System\/Debug.hpp\"\n#include \"Vulkan\/VkSampler.hpp\"\n\n#include <limits>\n\nnamespace {\n\nvoid applySwizzle(VkComponentSwizzle swizzle, sw::Float4 &f, const sw::Vector4f &c, bool integer)\n{\n\tswitch(swizzle)\n\t{\n\t\tcase VK_COMPONENT_SWIZZLE_R: f = c.x; break;\n\t\tcase VK_COMPONENT_SWIZZLE_G: f = c.y; break;\n\t\tcase VK_COMPONENT_SWIZZLE_B: f = c.z; break;\n\t\tcase VK_COMPONENT_SWIZZLE_A: f = c.w; break;\n\t\tcase VK_COMPONENT_SWIZZLE_ZERO: f = sw::Float4(0.0f, 0.0f, 0.0f, 0.0f); break;\n\t\tcase VK_COMPONENT_SWIZZLE_ONE:\n\t\t\tif(integer)\n\t\t\t{\n\t\t\t\tf = rr::As<sw::Float4>(sw::Int4(1, 1, 1, 1));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tf = sw::Float4(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault: ASSERT(false);\n\t}\n}\n\n}  \/\/ anonymous namespace\n\nnamespace sw {\n\nSamplerCore::SamplerCore(Pointer<Byte> &constants, const Sampler &state)\n    : constants(constants)\n    , state(state)\n{\n}\n\nVector4f SamplerCore::sampleTexture(Pointer<Byte> &texture, Pointer<Byte> &sampler, Float4 uvw[4], Float4 &q, Float &&lodOrBias, Float4 &dsx, Float4 &dsy, Vector4f &offset, Int4 &sampleId, SamplerFunction function)\n{\n\tVector4f c;\n\n\tFloat4 uuuu = uvw[0];\n\tFloat4 vvvv = uvw[1];\n\tFloat4 wwww = uvw[2];\n\tFloat4 cubeArrayCoord = uvw[3];\n\tFloat4 qqqq = q;\n\n\tFloat lod;\n\tFloat anisotropy;\n\tFloat4 uDelta;\n\tFloat4 vDelta;\n\tFloat4 M;  \/\/ Major axis\n\n\tif(isCube())\n\t{\n\t\tInt4 face = cubeFace(uuuu, vvvv, uvw[0], uvw[1], uvw[2], M);\n\t\twwww = As<Float4>(face);\n\t}\n\n\tif(function == Implicit || function == Bias || function == Grad || function == Query)\n\t{\n\t\tif(state.textureType != VK_IMAGE_VIEW_TYPE_3D)\n\t\t{\n\t\t\tif(!isCube())\n\t\t\t{\n\t\t\t\tcomputeLod(texture, sampler, lod, anisotropy, uDelta, vDelta, uuuu, vvvv, dsx, dsy, function);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcomputeLodCube(texture, sampler, lod, uvw[0], uvw[1], uvw[2], dsx, dsy, M, function);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcomputeLod3D(texture, sampler, lod, uuuu, vvvv, wwww, dsx, dsy, function);\n\t\t}\n\n\t\tFloat bias = *Pointer<Float>(sampler + OFFSET(vk::Sampler, mipLodBias));\n\n\t\tif(function == Bias)\n\t\t{\n\t\t\t\/\/ Add SPIR-V Bias operand to the sampler provided bias and clamp to maxSamplerLodBias limit.\n\t\t\tbias = Min(Max(bias + lodOrBias, -vk::MAX_SAMPLER_LOD_BIAS), vk::MAX_SAMPLER_LOD_BIAS);\n\t\t}\n\n\t\tlod += bias;\n\t}\n\telse if(function == Lod)\n\t{\n\t\t\/\/ Vulkan 1.1: \"The absolute value of mipLodBias must be less than or equal to VkPhysicalDeviceLimits::maxSamplerLodBias\"\n\t\t\/\/ Hence no explicit clamping to maxSamplerLodBias is required in this case.\n\t\tlod = lodOrBias + *Pointer<Float>(sampler + OFFSET(vk::Sampler, mipLodBias));\n\t}\n\telse if(function == Fetch)\n\t{\n\t\t\/\/ TODO: Eliminate int-float-int conversion.\n\t\tlod = Float(As<Int>(lodOrBias));\n\t}\n\telse if(function == Base || function == Gather)\n\t{\n\t\tlod = Float(0);\n\t}\n\telse\n\t\tUNREACHABLE(\"Sampler function %d\", int(function));\n\n\tif(function != Base && function != Fetch && function != Gather)\n\t{\n\t\tif(function == Query)\n\t\t{\n\t\t\tc.y = Float4(lod);  \/\/ Unclamped LOD.\n\t\t}\n\n\t\tlod = Max(lod, *Pointer<Float>(sampler + OFFSET(vk::Sampler, minLod)));\n\t\tlod = Min(lod, *Pointer<Float>(sampler + OFFSET(vk::Sampler, maxLod)));\n\n\t\tif(function == Query)\n\t\t{\n\t\t\tif(state.mipmapFilter == MIPMAP_POINT)\n\t\t\t{\n\t\t\t\tlod = Round(lod);  \/\/ TODO: Preferred formula is ceil(lod + 0.5) - 1\n\t\t\t}\n\n\t\t\tc.x = lod;\n\t\t\t\/\/\tc.y contains unclamped LOD.\n\n\t\t\treturn c;\n\t\t}\n\t}\n\n\tbool force32BitFiltering = state.highPrecisionFiltering && !isYcbcrFormat() && (state.textureFilter != FILTER_POINT);\n\tbool seamlessCube = (state.addressingModeU == ADDRESSING_SEAMLESS);\n\tbool use32BitFiltering = hasFloatTexture() || hasUnnormalizedIntegerTexture() || force32BitFiltering ||\n\t                         seamlessCube || state.unnormalizedCoordinates || state.compareEnable || state.largeTexture ||\n\t                         borderModeActive() || (function == Gather);\n\n\tif(use32BitFiltering)\n\t{\n\t\tc = sampleFloatFilter(texture, uuuu, vvvv, wwww, qqqq, offset, cubeArrayCoord, sampleId, lod, anisotropy, uDelta, vDelta, function);\n\n\t\tif(!hasFloatTexture() && !hasUnnormalizedIntegerTexture() && !state.compareEnable)\n\t\t{\n\t\t\tswitch(state.textureFormat)\n\t\t\t{\n\t\t\t\tcase VK_FORMAT_R5G6B5_UNORM_PACK16:\n\t\t\t\t\tc.x *= Float4(1.0f \/ 0xF800);\n\t\t\t\t\tc.y *= Float4(1.0f \/ 0xFC00);\n\t\t\t\t\tc.z *= Float4(1.0f \/ 0xF800);\n\t\t\t\t\tbreak;\n\t\t\t\tcase VK_FORMAT_B4G4R4A4_UNORM_PACK16:\n\t\t\t\t\tc.x *= Float4(1.0f \/ 0xF000);\n\t\t\t\t\tc.y *= Float4(1.0f \/ 0xF000);\n\t\t\t\t\tc.z *= Float4(1.0f \/ 0xF000);\n\t\t\t\t\tc.w *= Float4(1.0f \/ 0xF000);\n\t\t\t\t\tbreak;\n\t\t\t\tcase VK_FORMAT_A1R5G5B5_UNORM_PACK16:\n\t\t\t\t\tc.x *= Float4(1.0f \/ 0xF800);\n\t\t\t\t\tc.y *= Float4(1.0f \/ 0xF800);\n\t\t\t\t\tc.z *= Float4(1.0f \/ 0xF800);\n\t\t\t\t\tc.w *= Float4(1.0f \/ 0x8000);\n\t\t\t\t\tbreak;\n\t\t\t\tcase VK_FORMAT_R8_SNORM:\n\t\t\t\tcase VK_FORMAT_R8G8_SNORM:\n\t\t\t\tcase VK_FORMAT_R8G8B8A8_SNORM:\n\t\t\t\tcase VK_FORMAT_A8B8G8R8_SNORM_PACK32:\n\t\t\t\t\tc.x *= Float4(1.0f \/ 0x7F00);\n\t\t\t\t\tc.y *= Float4(1.0f \/ 0x7F00);\n\t\t\t\t\tc.z *= Float4(1.0f \/ 0x7F00);\n\t\t\t\t\tc.w *= Float4(1.0f \/ 0x7F00);\n\t\t\t\t\tbreak;\n\t\t\t\tcase VK_FORMAT_R8_UNORM:\n\t\t\t\tcase VK_FORMAT_R8G8_UNORM:\n\t\t\t\tcase VK_FORMAT_R8G8B8A8_UNORM:\n\t\t\t\tcase VK_FORMAT_B8G8R8A8_UNORM:\n\t\t\t\tcase VK_FORMAT_A8B8G8R8_UNORM_PACK32:\n\t\t\t\tcase VK_FORMAT_B8G8R8A8_SRGB:\n\t\t\t\tcase VK_FORMAT_R8G8B8A8_SRGB:\n\t\t\t\tcase VK_FORMAT_R8_SRGB:\n\t\t\t\tcase VK_FORMAT_R8G8_SRGB:\n\t\t\t\t\tc.x *= Float4(1.0f \/ 0xFF00u);\n\t\t\t\t\tc.y *= Float4(1.0f \/ 0xFF00u);\n\t\t\t\t\tc.z *= Float4(1.0f \/ 0xFF00u);\n\t\t\t\t\tc.w *= Float4(1.0f \/ 0xFF00u);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tfor(int component = 0; component < textureComponentCount(); component++)\n\t\t\t\t\t{\n\t\t\t\t\t\tc[component] *= Float4(hasUnsignedTextureComponent(component) ? 1.0f \/ 0xFFFF : 1.0f \/ 0x7FFF);\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse  \/\/ 16-bit filtering.\n\t{\n\t\tVector4s cs = sampleFilter(texture, uuuu, vvvv, wwww, offset, cubeArrayCoord, sampleId, lod, anisotropy, uDelta, vDelta, function);\n\n\t\tswitch(state.textureFormat)\n\t\t{\n\t\t\tcase VK_FORMAT_R5G6B5_UNORM_PACK16:\n\t\t\t\tc.x = Float4(As<UShort4>(cs.x)) * Float4(1.0f \/ 0xF800);\n\t\t\t\tc.y = Float4(As<UShort4>(cs.y)) * Float4(1.0f \/ 0xFC00);\n\t\t\t\tc.z = Float4(As<UShort4>(cs.z)) * Float4(1.0f \/ 0xF800);\n\t\t\t\tbreak;\n\t\t\tcase VK_FORMAT_B4G4R4A4_UNORM_PACK16:\n\t\t\t\tc.x = Float4(As<UShort4>(cs.x)) * Float4(1.0f \/ 0xF000);\n\t\t\t\tc.y = Float4(As<UShort4>(cs.y)) * Float4(1.0f \/ 0xF000);\n\t\t\t\tc.z = Float4(As<UShort4>(cs.z)) * Float4(1.0f \/ 0xF000);\n\t\t\t\tc.w = Float4(As<UShort4>(cs.w)) * Float4(1.0f \/ 0xF000);\n\t\t\t\tbreak;\n\t\t\tcase VK_FORMAT_A1R5G5B5_UNORM_PACK16:\n\t\t\t\tc.x = Float4(As<UShort4>(cs.x)) * Float4(1.0f \/ 0xF800);\n\t\t\t\tc.y = Float4(As<UShort4>(cs.y)) * Float4(1.0f \/ 0xF800);\n\t\t\t\tc.z = Float4(As<UShort4>(cs.z)) * Float4(1.0f \/ 0xF800);\n\t\t\t\tc.w = Float4(As<UShort4>(cs.w)) * Float4(1.0f \/ 0x8000);\n\t\t\t\tbreak;\n\t\t\tcase VK_FORMAT_R8_SNORM:\n\t\t\tcase VK_FORMAT_R8G8_SNORM:\n\t\t\tcase VK_FORMAT_R8G8B8A8_SNORM:\n\t\t\tcase VK_FORMAT_A8B8G8R8_SNORM_PACK32:\n\t\t\t\tc.x = Float4(cs.x) * Float4(1.0f \/ 0x7F00);\n\t\t\t\tc.y = Float4(cs.y) * Float4(1.0f \/ 0x7F00);\n\t\t\t\tc.z = Float4(cs.z) * Float4(1.0f \/ 0x7F00);\n\t\t\t\tc.w = Float4(cs.w) * Float4(1.0f \/ 0x7F00);\n\t\t\t\tbreak;\n\t\t\tcase VK_FORMAT_R8_UNORM:\n\t\t\tcase VK_FORMAT_R8G8_UNORM:\n\t\t\tcase VK_FORMAT_R8G8B8A8_UNORM:\n\t\t\tcase VK_FORMAT_B8G8R8A8_UNORM:\n\t\t\tcase VK_FORMAT_A8B8G8R8_UNORM_PACK32:\n\t\t\tcase VK_FORMAT_B8G8R8A8_SRGB:\n\t\t\tcase VK_FORMAT_R8G8B8A8_SRGB:\n\t\t\tcase VK_FORMAT_R8_SRGB:\n\t\t\tcase VK_FORMAT_R8G8_SRGB:\n\t\t\t\tc.x = Float4(As<UShort4>(cs.x)) * Float4(1.0f \/ 0xFF00u);\n\t\t\t\tc.y = Float4(As<UShort4>(cs.y)) * Float4(1.0f \/ 0xFF00u);\n\t\t\t\tc.z = Float4(As<UShort4>(cs.z)) * Float4(1.0f \/ 0xFF00u);\n\t\t\t\tc.w = Float4(As<UShort4>(cs.w)) * Float4(1.0f \/ 0xFF00u);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tfor(int component = 0; component < textureComponentCount(); component++)\n\t\t\t\t{\n\t\t\t\t\tif(hasUnsignedTextureComponent(component))\n\t\t\t\t\t{\n\t\t\t\t\t\tconvertUnsigned16(c[component], cs[component]);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tconvertSigned15(c[component], cs[component]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t}\n\n\tif(state.textureFilter != FILTER_GATHER)\n\t{\n\t\tif((state.swizzle.r != VK_COMPONENT_SWIZZLE_R) ||\n\t\t   (state.swizzle.g != VK_COMPONENT_SWIZZLE_G) ||\n\t\t   (state.swizzle.b != VK_COMPONENT_SWIZZLE_B) ||\n\t\t   (state.swizzle.a != VK_COMPONENT_SWIZZLE_A))\n\t\t{\n\t\t\tconst Vector4f col(c);\n\t\t\tbool integer = hasUnnormalizedIntegerTexture();\n\t\t\tapplySwizzle(state.swizzle.r, c.x, col, integer);\n\t\t\tapplySwizzle(state.swizzle.g, c.y, col, integer);\n\t\t\tapplySwizzle(state.swizzle.b, c.z, col, integer);\n\t\t\tapplySwizzle(state.swizzle.a, c.w, col, integer);\n\t\t}\n\t}\n\telse  \/\/ Gather\n\t{\n\t\tVkComponentSwizzle swizzle = gatherSwizzle();\n\n\t\t\/\/ R\/G\/B\/A swizzles affect the component collected from each texel earlier.\n\t\t\/\/ Handle the ZERO and ONE cases here because we don't need to know the format.\n\n\t\tif(swizzle == VK_COMPONENT_SWIZZLE_ZERO)\n\t\t{\n\t\t\tc.x = c.y = c.z = c.w = Float4(0);\n\t\t}\n\t\telse if(swizzle == VK_COMPONENT_SWIZZLE_ONE)\n\t\t{\n\t\t\tbool integer = hasUnnormalizedIntegerTexture();\n\t\t\tc.x = c.y = c.z = c.w = integer ? As<Float4>(Int4(1)) : RValue<Float4>(Float4(1.0f));\n\t\t}\n\t}\n\n\treturn c;\n}\n\nShort4 SamplerCore::offsetSample(Short4 &uvw, Pointer<Byte> &mipmap, int halfOffset, bool wrap, int count, Float &lod)\n{\n\tShort4 offset = *Pointer<Short4>(mipmap + halfOffset);\n\n\tif(state.textureFilter == FILTER_MIN_LINEAR_MAG_POINT)\n\t{\n\t\toffset &= Short4(CmpNLE(Float4(lod), Float4(0.0f)));\n\t}\n\telse if(state.textureFilter == FILTER_MIN_POINT_MAG_LINEAR)\n\t{\n\t\toffset &= Short4(CmpLE(Float4(lod), Float4(0.0f)));\n\t}\n\n\tif(wrap)\n\t{\n\t\tswitch(count)\n\t\t{\n\t\t\tcase -1: return uvw - offset;\n\t\t\tcase 0: return uvw;\n\t\t\tcase +1: return uvw + offset;\n\t\t\tcase 2: return uvw + offset + offset;\n\t\t}\n\t}\n\telse  \/\/ Clamp or mirror\n\t{\n\t\tswitch(count)\n\t\t{\n\t\t\tcase -1: return SubSat(As<UShort4>(uvw), As<UShort4>(offset));\n\t\t\tcase 0: return uvw;\n\t\t\tcase +1: return AddSat(As<UShort4>(uvw), As<UShort4>(offset));\n\t\t\tcase 2: return AddSat(AddSat(As<UShort4>(uvw), As<UShort4>(offset)), As<UShort4>(offset));\n\t\t}\n\t}\n\n\treturn uvw;\n}\n\nVector4s SamplerCore::sampleFilter(Pointer<Byte> &texture, Float4 &u, Float4 &v, Float4 &w, Vector4f &offset, const Float4 &cubeArrayCoord, const Int4 &sampleId, Float &lod, Float &anisotropy, Float4 &uDelta, Float4 &vDelta, SamplerFunction function)\n{\n\tVector4s c = sampleAniso(texture, u, v, w, offset, cubeArrayCoord, sampleId, lod, anisotropy, uDelta, vDelta, false, function);\n\n\tif(function == Fetch)\n\t{\n\t\treturn c;\n\t}\n\n\tif(state.mipmapFilter == MIPMAP_LINEAR)\n\t{\n\t\tVector4s cc = sampleAniso(texture, u, v, w, offset, cubeArrayCoord, sampleId, lod, anisotropy, uDelta, vDelta, true, function);\n\n\t\tlod *= Float(1 << 16);\n\n\t\tUShort4 utri = UShort4(Float4(lod));  \/\/ FIXME: Optimize\n\t\tShort4 stri = utri >> 1;              \/\/ FIXME: Optimize\n\n\t\tif(hasUnsignedTextureComponent(0))\n\t\t\tcc.x = MulHigh(As<UShort4>(cc.x), utri);\n\t\telse\n\t\t\tcc.x = MulHigh(cc.x, stri);\n\t\tif(hasUnsignedTextureComponent(1))\n\t\t\tcc.y = MulHigh(As<UShort4>(cc.y), utri);\n\t\telse\n\t\t\tcc.y = MulHigh(cc.y, stri);\n\t\tif(hasUnsignedTextureComponent(2))\n\t\t\tcc.z = MulHigh(As<UShort4>(cc.z), utri);\n\t\telse\n\t\t\tcc.z = MulHigh(cc.z, stri);\n\t\tif(hasUnsignedTextureComponent(3))\n\t\t\tcc.w = MulHigh(As<UShort4>(cc.w), utri);\n\t\telse\n\t\t\tcc.w = MulHigh(cc.w, stri);\n\n\t\tutri = ~utri;\n\t\tstri = Short4(0x7FFF) - stri;\n\n\t\tif(hasUnsignedTextureComponent(0))\n\t\t\tc.x = MulHigh(As<UShort4>(c.x), utri);\n\t\telse\n\t\t\tc.x = MulHigh(c.x, stri);\n\t\tif(hasUnsignedTextureComponent(1))\n\t\t\tc.y = MulHigh(As<UShort4>(c.y), utri);\n\t\telse\n\t\t\tc.y = MulHigh(c.y, stri);\n\t\tif(hasUnsignedTextureComponent(2))\n\t\t\tc.z = MulHigh(As<UShort4>(c.z), utri);\n\t\telse\n\t\t\tc.z = MulHigh(c.z, stri);\n\t\tif(hasUnsignedTextureComponent(3))\n\t\t\tc.w = MulHigh(As<UShort4>(c.w), utri);\n\t\telse\n\t\t\tc.w = MulHigh(c.w, stri);\n\n\t\tc.x += cc.x;\n\t\tc.y += cc.y;\n\t\tc.z += cc.z;\n\t\tc.w += cc.w;\n\n\t\tif(!hasUnsignedTextureComponent(0)) c.x += c.x;\n\t\tif(!hasUnsignedTextureComponent(1)) c.y += c.y;\n\t\tif(!hasUnsignedTextureComponent(2)) c.z += c.z;\n\t\tif(!hasUnsignedTextureComponent(3)) c.w += c.w;\n\t}\n\n\treturn c;\n}\n\nVector4s SamplerCore::sampleAniso(Pointer<Byte> &texture, Float4 &u, Float4 &v, Float4 &w, Vector4f &offset, const Float4 &cubeArrayCoord, const Int4 &sampleId, Float &lod, Float &anisotropy, Float4 &uDelta, Float4 &vDelta, bool secondLOD, SamplerFunction function)\n{\n\tVector4s c;\n\n\tif(state.textureFilter != FILTER_ANISOTROPIC || function == Lod || function == Fetch)\n\t{\n\t\tc = sampleQuad(texture, u, v, w, offset, cubeArrayCoord, sampleId, lod, secondLOD, function);\n\t}\n\telse\n\t{\n\t\tInt a = RoundInt(anisotropy);\n\n\t\tVector4s cSum;\n\n\t\tcSum.x = Short4(0);\n\t\tcSum.y = Short4(0);\n\t\tcSum.z = Short4(0);\n\t\tcSum.w = Short4(0);\n\n\t\tFloat4 A = *Pointer<Float4>(constants + OFFSET(Constants, uvWeight) + 16 * a);\n\t\tFloat4 B = *Pointer<Float4>(constants + OFFSET(Constants, uvStart) + 16 * a);\n\t\tUShort4 cw = *Pointer<UShort4>(constants + OFFSET(Constants, cWeight) + 8 * a);\n\t\tShort4 sw = Short4(cw >> 1);\n\n\t\tFloat4 du = uDelta;\n\t\tFloat4 dv = vDelta;\n\n\t\tFloat4 u0 = u + B * du;\n\t\tFloat4 v0 = v + B * dv;\n\n\t\tdu *= A;\n\t\tdv *= A;\n\n\t\tInt i = 0;\n\n\t\tDo\n\t\t{\n\t\t\tc = sampleQuad(texture, u0, v0, w, offset, cubeArrayCoord, sampleId, lod, secondLOD, function);\n\n\t\t\tu0 += du;\n\t\t\tv0 += dv;\n\n\t\t\tif(hasUnsignedTextureComponent(0))\n\t\t\t\tcSum.x += As<Short4>(MulHigh(As<UShort4>(c.x), cw));\n\t\t\telse\n\t\t\t\tcSum.x += MulHigh(c.x, sw);\n\t\t\tif(hasUnsignedTextureComponent(1))\n\t\t\t\tcSum.y += As<Short4>(MulHigh(As<UShort4>(c.y), cw));\n\t\t\telse\n\t\t\t\tcSum.y += MulHigh(c.y, sw);\n\t\t\tif(hasUnsignedTextureComponent(2))\n\t\t\t\tcSum.z += As<Short4>(MulHigh(As<UShort4>(c.z), cw));\n\t\t\telse\n\t\t\t\tcSum.z += MulHigh(c.z, sw);\n\t\t\tif(hasUnsignedTextureComponent(3))\n\t\t\t\tcSum.w += As<Short4>(MulHigh(As<UShort4>(c.w), cw));\n\t\t\telse\n\t\t\t\tcSum.w += MulHigh(c.w, sw);\n\n\t\t\ti++;\n\t\t}\n\t\tUntil(i >= a);\n\n\t\tif(hasUnsignedTextureComponent(0))\n\t\t\tc.x = cSum.x;\n\t\telse\n\t\t\tc.x = AddSat(cSum.x, cSum.x);\n\t\tif(hasUnsignedTextureComponent(1))\n\t\t\tc.y = cSum.y;\n\t\telse\n\t\t\tc.y = AddSat(cSum.y, cSum.y);\n\t\tif(hasUnsignedTextureComponent(2))\n\t\t\tc.z = cSum.z;\n\t\telse\n\t\t\tc.z = AddSat(cSum.z, cSum.z);\n\t\tif(hasUnsignedTextureComponent(3))\n\t\t\tc.w = cSum.w;\n\t\telse\n\t\t\tc.w = AddSat(cSum.w, cSum.w);\n\t}\n\n\treturn c;\n}\n\nVector4s SamplerCore::sampleQuad(Pointer<Byte> &texture, Float4 &u, Float4 &v, Float4 &w, Vector4f &offset, const Float4 &cubeArrayCoord, const Int4 &sampleId, Float &lod, bool secondLOD, SamplerFunction function)\n{\n\tif(state.textureType != VK_IMAGE_VIEW_TYPE_3D)\n\t{\n\t\treturn sampleQuad2D(texture, u, v, w, offset, cubeArrayCoord, sampleId, lod, secondLOD, function);\n\t}\n\telse\n\t{\n\t\treturn sample3D(texture, u, v, w, offset, cubeArrayCoord, sampleId, lod, secondLOD, function);\n\t}\n}\n\nVector4s SamplerCore::sampleQuad2D(Pointer<Byte> &texture, Float4 &u, Float4 &v, Float4 &w, Vector4f &offset, const Float4 &cubeArrayCoord, const Int4 &sampleId, Float &lod, bool secondLOD, SamplerFunction function)\n{\n\tVector4s c;\n\n\tint componentCount = textureComponentCount();\n\tbool gather = (state.textureFilter == FILTER_GATHER);\n\n\tPointer<Byte> mipmap;\n\tPointer<Byte> buffer;\n\tselectMipmap(texture, mipmap, buffer, lod, secondLOD);\n\n\tbool texelFetch = (function == Fetch);\n\n\tShort4 uuuu = texelFetch ? Short4(As<Int4>(u)) : address(u, state.addressingModeU, mipmap);\n\tShort4 vvvv = texelFetch ? Short4(As<Int4>(v)) : address(v, state.addressingModeV, mipmap);\n\tShort4 wwww = texelFetch ? Short4(As<Int4>(w)) : address(w, state.addressingModeW, mipmap);\n\n\tShort4 cubeArrayId(0);\n\tif(state.textureType == VK_IMAGE_VIEW_TYPE_CUBE_ARRAY)\n\t{\n\t\tcubeArrayId = address(cubeArrayCoord, state.addressingModeY, mipmap);\n\t}\n\n\tif(state.textureFilter == FILTER_POINT || texelFetch)\n\t{\n\t\tc = sampleTexel(uuuu, vvvv, wwww, offset, mipmap, cubeArrayId, sampleId, buffer, function);\n\t}\n\telse\n\t{\n\t\tShort4 uuuu0 = offsetSample(uuuu, mipmap, OFFSET(Mipmap, uHalf), state.addressingModeU == ADDRESSING_WRAP, -1, lod);\n\t\tShort4 vvvv0 = offsetSample(vvvv, mipmap, OFFSET(Mipmap, vHalf), state.addressingModeV == ADDRESSING_WRAP, -1, lod);\n\t\tShort4 uuuu1 = offsetSample(uuuu, mipmap, OFFSET(Mipmap, uHalf), state.addressingModeU == ADDRESSING_WRAP, +1, lod);\n\t\tShort4 vvvv1 = offsetSample(vvvv, mipmap, OFFSET(Mipmap, vHalf), state.addressingModeV == ADDRESSING_WRAP, +1, lod);\n\n\t\tVector4s c00 = sampleTexel(uuuu0, vvvv0, wwww, offset, mipmap, cubeArrayId, sampleId, buffer, function);\n\t\tVector4s c10 = sampleTexel(uuuu1, vvvv0, wwww, offset, mipmap, cubeArrayId, sampleId, buffer, function);\n\t\tVector4s c01 = sampleTexel(uuuu0, vvvv1, wwww, offset, mipmap, cubeArrayId, sampleId, buffer, function);\n\t\tVector4s c11 = sampleTexel(uuuu1, vvvv1, wwww, offset, mipmap, cubeArrayId, sampleId, buffer, function);\n\n\t\tif(!gather)  \/\/ Blend\n\t\t{\n\t\t\t\/\/ Fractions\n\t\t\tUShort4 f0u = As<UShort4>(uuuu0) * UShort4(*Pointer<Int4>(mipmap + OFFSET(Mipmap, width)));\n\t\t\tUShort4 f0v = As<UShort4>(vvvv0) * UShort4(*Pointer<Int4>(mipmap + OFFSET(Mipmap, height)));\n\n\t\t\tUShort4 f1u = ~f0u;\n\t\t\tUShort4 f1v = ~f0v;\n\n\t\t\tUShort4 f0u0v = MulHigh(f0u, f0v);\n\t\t\tUShort4 f1u0v = MulHigh(f1u, f0v);\n\t\t\tUShort4 f0u1v = MulHigh(f0u, f1v);\n\t\t\tUShort4 f1u1v = MulHigh(f1u, f1v);\n\n\t\t\t\/\/ Signed fractions\n\t\t\tShort4 f1u1vs;\n\t\t\tShort4 f0u1vs;\n\t\t\tShort4 f1u0vs;\n\t\t\tShort4 f0u0vs;\n\n\t\t\tif(!hasUnsignedTextureComponent(0) || !hasUnsignedTextureComponent(1) || !hasUnsignedTextureComponent(2) || !hasUnsignedTextureComponent(3))\n\t\t\t{\n\t\t\t\tf1u1vs = f1u1v >> 1;\n\t\t\t\tf0u1vs = f0u1v >> 1;\n\t\t\t\tf1u0vs = f1u0v >> 1;\n\t\t\t\tf0u0vs = f0u0v >> 1;\n\t\t\t}\n\n\t\t\t\/\/ Bilinear interpolation\n\t\t\tif(componentCount >= 1)\n\t\t\t{\n\t\t\t\tif(has16bitTextureComponents() && hasUnsignedTextureComponent(0))\n\t\t\t\t{\n\t\t\t\t\tc00.x = As<UShort4>(c00.x) - MulHigh(As<UShort4>(c00.x), f0u) + MulHigh(As<UShort4>(c10.x), f0u);\n\t\t\t\t\tc01.x = As<UShort4>(c01.x) - MulHigh(As<UShort4>(c01.x), f0u) + MulHigh(As<UShort4>(c11.x), f0u);\n\t\t\t\t\tc.x = As<UShort4>(c00.x) - MulHigh(As<UShort4>(c00.x), f0v) + MulHigh(As<UShort4>(c01.x), f0v);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(hasUnsignedTextureComponent(0))\n\t\t\t\t\t{\n\t\t\t\t\t\tc00.x = MulHigh(As<UShort4>(c00.x), f1u1v);\n\t\t\t\t\t\tc10.x = MulHigh(As<UShort4>(c10.x), f0u1v);\n\t\t\t\t\t\tc01.x = MulHigh(As<UShort4>(c01.x), f1u0v);\n\t\t\t\t\t\tc11.x = MulHigh(As<UShort4>(c11.x), f0u0v);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tc00.x = MulHigh(c00.x, f1u1vs);\n\t\t\t\t\t\tc10.x = MulHigh(c10.x, f0u1vs);\n\t\t\t\t\t\tc01.x = MulHigh(c01.x, f1u0vs);\n\t\t\t\t\t\tc11.x = MulHigh(c11.x, f0u0vs);\n\t\t\t\t\t}\n\n\t\t\t\t\tc.x = (c00.x + c10.x) + (c01.x + c11.x);\n\t\t\t\t\tif(!hasUnsignedTextureComponent(0)) c.x = AddSat(c.x, c.x);  \/\/ Correct for signed fractions\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(componentCount >= 2)\n\t\t\t{\n\t\t\t\tif(has16bitTextureComponents() && hasUnsignedTextureComponent(1))\n\t\t\t\t{\n\t\t\t\t\tc00.y = As<UShort4>(c00.y) - MulHigh(As<UShort4>(c00.y), f0u) + MulHigh(As<UShort4>(c10.y), f0u);\n\t\t\t\t\tc01.y = As<UShort4>(c01.y) - MulHigh(As<UShort4>(c01.y), f0u) + MulHigh(As<UShort4>(c11.y), f0u);\n\t\t\t\t\tc.y = As<UShort4>(c00.y) - MulHigh(As<UShort4>(c00.y), f0v) + MulHigh(As<UShort4>(c01.y), f0v);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(hasUnsignedTextureComponent(1))\n\t\t\t\t\t{\n\t\t\t\t\t\tc00.y = MulHigh(As<UShort4>(c00.y), f1u1v);\n\t\t\t\t\t\tc10.y = MulHigh(As<UShort4>(c10.y), f0u1v);\n\t\t\t\t\t\tc01.y = MulHigh(As<UShort4>(c01.y), f1u0v);\n\t\t\t\t\t\tc11.y = MulHigh(As<UShort4>(c11.y), f0u0v);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tc00.y = MulHigh(c00.y, f1u1vs);\n\t\t\t\t\t\tc10.y = MulHigh(c10.y, f0u1vs);\n\t\t\t\t\t\tc01.y = MulHigh(c01.y, f1u0vs);\n\t\t\t\t\t\tc11.y = MulHigh(c11.y, f0u0vs);\n\t\t\t\t\t}\n\n\t\t\t\t\tc.y = (c00.y + c10.y) + (c01.y + c11.y);\n\t\t\t\t\tif(!hasUnsignedTextureComponent(1)) c.y = AddSat(c.y, c.y);  \/\/ Correct for signed fractions\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(componentCount >= 3)\n\t\t\t{\n\t\t\t\tif(has16bitTextureComponents() && hasUnsignedTextureComponent(2))\n\t\t\t\t{\n\t\t\t\t\tc00.z = As<UShort4>(c00.z) - MulHigh(As<UShort4>(c00.z), f0u) + MulHigh(As<UShort4>(c10.z), f0u);\n\t\t\t\t\tc01.z = As<UShort4>(c01.z) - MulHigh(As<UShort4>(c01.z), f0u) + MulHigh(As<UShort4>(c11.z), f0u);\n\t\t\t\t\tc.z = As<UShort4>(c00.z) - MulHigh(As<UShort4>(c00.z), f0v) + MulHigh(As<UShort4>(c01.z), f0v);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(hasUnsignedTextureComponent(2))\n\t\t\t\t\t{\n\t\t\t\t\t\tc00.z = MulHigh(As<UShort4>(c00.z), f1u1v);\n\t\t\t\t\t\tc10.z = MulHigh(As<UShort4>(c10.z), f0u1v);\n\t\t\t\t\t\tc01.z = MulHigh(As<UShort4>(c01.z), f1u0v);\n\t\t\t\t\t\tc11.z = MulHigh(As<UShort4>(c11.z), f0u0v);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tc00.z = MulHigh(c00.z, f1u1vs);\n\t\t\t\t\t\tc10.z = MulHigh(c10.z, f0u1vs);\n\t\t\t\t\t\tc01.z = MulHigh(c01.z, f1u0vs);\n\t\t\t\t\t\tc11.z = MulHigh(c11.z, f0u0vs);\n\t\t\t\t\t}\n\n\t\t\t\t\tc.z = (c00.z + c10.z) + (c01.z + c11.z);\n\t\t\t\t\tif(!hasUnsignedTextureComponent(2)) c.z = AddSat(c.z, c.z);  \/\/ Correct for signed fractions\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(componentCount >= 4)\n\t\t\t{\n\t\t\t\tif(has16bitTextureComponents() && hasUnsignedTextureComponent(3))\n\t\t\t\t{\n\t\t\t\t\tc00.w = As<UShort4>(c00.w) - MulHigh(As<UShort4>(c00.w), f0u) + MulHigh(As<UShort4>(c10.w), f0u);\n\t\t\t\t\tc01.w = As<UShort4>(c01.w) - MulHigh(As<UShort4>(c01.w), f0u) + MulHigh(As<UShort4>(c11.w), f0u);\n\t\t\t\t\tc.w = As<UShort4>(c00.w) - MulHigh(As<UShort4>(c00.w), f0v) + MulHigh(As<UShort4>(c01.w), f0v);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(hasUnsignedTextureComponent(3))\n\t\t\t\t\t{\n\t\t\t\t\t\tc00.w = MulHigh(As<UShort4>(c00.w), f1u1v);\n\t\t\t\t\t\tc10.w = MulHigh(As<UShort4>(c10.w), f0u1v);\n\t\t\t\t\t\tc01.w = MulHigh(As<UShort4>(c01.w), f1u0v);\n\t\t\t\t\t\tc11.w = MulHigh(As<UShort4>(c11.w), f0u0v);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tc00.w = MulHigh(c00.w, f1u1vs);\n\t\t\t\t\t\tc10.w = MulHigh(c10.w, f0u1vs);\n\t\t\t\t\t\tc01.w = MulHigh(c01.w, f1u0vs);\n\t\t\t\t\t\tc11.w = MulHigh(c11.w, f0u0vs);\n\t\t\t\t\t}\n\n\t\t\t\t\tc.w = (c00.w + c10.w) + (c01.w + c11.w);\n\t\t\t\t\tif(!hasUnsignedTextureComponent(3)) c.w = AddSat(c.w, c.w);  \/\/ Correct for signed fractions\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse  \/\/ Gather\n\t\t{\n\t\t\tVkComponentSwizzle swizzle = gatherSwizzle();\n\t\t\tswitch(swizzle)\n\t\t\t{\n\t\t\t\tcase VK_COMPONENT_SWIZZLE_ZERO:\n\t\t\t\tcase VK_COMPONENT_SWIZZLE_ONE:\n\t\t\t\t\t\/\/ Handled at the final component swizzle.\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tc.x = c01[swizzle - VK_COMPONENT_SWIZZLE_R];\n\t\t\t\t\tc.y = c11[swizzle - VK_COMPONENT_SWIZZLE_R];\n\t\t\t\t\tc.z = c10[swizzle - VK_COMPONENT_SWIZZLE_R];\n\t\t\t\t\tc.w = c00[swizzle - VK_COMPONENT_SWIZZLE_R];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn c;\n}\n\nVector4s SamplerCore::sample3D(Pointer<Byte> &texture, Float4 &u_, Float4 &v_, Float4 &w_, Vector4f &offset, const Float4 &cubeArrayCoord, const Int4 &sampleId, Float &lod, bool secondLOD, SamplerFunction function)\n{\n\tVector4s c_;\n\n\tint componentCount = textureComponentCount();\n\n\tPointer<Byte> mipmap;\n\tPointer<Byte> buffer;\n\tselectMipmap(texture, mipmap, buffer, lod, secondLOD);\n\n\tbool texelFetch = (function == Fetch);\n\n\tShort4 uuuu = texelFetch ? Short4(As<Int4>(u_)) : address(u_, state.addressingModeU, mipmap);\n\tShort4 vvvv = texelFetch ? Short4(As<Int4>(v_)) : address(v_, state.addressingModeV, mipmap);\n\tShort4 wwww = texelFetch ? Short4(As<Int4>(w_)) : address(w_, state.addressingModeW, mipmap);\n\n\tShort4 cubeArrayId(0);\n\tif(state.textureType == VK_IMAGE_VIEW_TYPE_CUBE_ARRAY)\n\t{\n\t\tcubeArrayId = address(cubeArrayCoord, state.addressingModeY, mipmap);\n\t}\n\n\tif(state.textureFilter == FILTER_POINT || texelFetch)\n\t{\n\t\tc_ = sampleTexel(uuuu, vvvv, wwww, offset, mipmap, cubeArrayId, sampleId, buffer, function);\n\t}\n\telse\n\t{\n\t\tVector4s c[2][2][2];\n\n\t\tShort4 u[2][2][2];\n\t\tShort4 v[2][2][2];\n\t\tShort4 s[2][2][2];\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tfor(int j = 0; j < 2; j++)\n\t\t\t{\n\t\t\t\tfor(int k = 0; k < 2; k++)\n\t\t\t\t{\n\t\t\t\t\tu[i][j][k] = offsetSample(uuuu, mipmap, OFFSET(Mipmap, uHalf), state.addressingModeU == ADDRESSING_WRAP, i * 2 - 1, lod);\n\t\t\t\t\tv[i][j][k] = offsetSample(vvvv, mipmap, OFFSET(Mipmap, vHalf), state.addressingModeV == ADDRESSING_WRAP, j * 2 - 1, lod);\n\t\t\t\t\ts[i][j][k] = offsetSample(wwww, mipmap, OFFSET(Mipmap, wHalf), state.addressingModeW == ADDRESSING_WRAP, k * 2 - 1, lod);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Fractions\n\t\tUShort4 f0u = As<UShort4>(u[0][0][0]) * UShort4(*Pointer<Int4>(mipmap + OFFSET(Mipmap, width)));\n\t\tUShort4 f0v = As<UShort4>(v[0][0][0]) * UShort4(*Pointer<Int4>(mipmap + OFFSET(Mipmap, height)));\n\t\tUShort4 f0s = As<UShort4>(s[0][0][0]) * UShort4(*Pointer<Int4>(mipmap + OFFSET(Mipmap, depth)));\n\n\t\tUShort4 f1u = ~f0u;\n\t\tUShort4 f1v = ~f0v;\n\t\tUShort4 f1s = ~f0s;\n\n\t\tUShort4 f[2][2][2];\n\t\tShort4 fs[2][2][2];\n\n\t\tf[1][1][1] = MulHigh(f1u, f1v);\n\t\tf[0][1][1] = MulHigh(f0u, f1v);\n\t\tf[1][0][1] = MulHigh(f1u, f0v);\n\t\tf[0][0][1] = MulHigh(f0u, f0v);\n\t\tf[1][1][0] = MulHigh(f1u, f1v);\n\t\tf[0][1][0] = MulHigh(f0u, f1v);\n\t\tf[1][0][0] = MulHigh(f1u, f0v);\n\t\tf[0][0][0] = MulHigh(f0u, f0v);\n\n\t\tf[1][1][1] = MulHigh(f[1][1][1], f1s);\n\t\tf[0][1][1] = MulHigh(f[0][1][1], f1s);\n\t\tf[1][0][1] = MulHigh(f[1][0][1], f1s);\n\t\tf[0][0][1] = MulHigh(f[0][0][1], f1s);\n\t\tf[1][1][0] = MulHigh(f[1][1][0], f0s);\n\t\tf[0][1][0] = MulHigh(f[0][1][0], f0s);\n\t\tf[1][0][0] = MulHigh(f[1][0][0], f0s);\n\t\tf[0][0][0] = MulHigh(f[0][0][0], f0s);\n\n\t\t\/\/ Signed fractions\n\t\tif(!hasUnsignedTextureComponent(0) || !hasUnsignedTextureComponent(1) || !hasUnsignedTextureComponent(2) || !hasUnsignedTextureComponent(3))\n\t\t{\n\t\t\tfs[0][0][0] = f[0][0][0] >> 1;\n\t\t\tfs[0][0][1] = f[0][0][1] >> 1;\n\t\t\tfs[0][1][0] = f[0][1][0] >> 1;\n\t\t\tfs[0][1][1] = f[0][1][1] >> 1;\n\t\t\tfs[1][0][0] = f[1][0][0] >> 1;\n\t\t\tfs[1][0][1] = f[1][0][1] >> 1;\n\t\t\tfs[1][1][0] = f[1][1][0] >> 1;\n\t\t\tfs[1][1][1] = f[1][1][1] >> 1;\n\t\t}\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tfor(int j = 0; j < 2; j++)\n\t\t\t{\n\t\t\t\tfor(int k = 0; k < 2; k++)\n\t\t\t\t{\n\t\t\t\t\tc[i][j][k] = sampleTexel(u[i][j][k], v[i][j][k], s[i][j][k], offset, mipmap, cubeArrayId, sampleId, buffer, function);\n\n\t\t\t\t\tif(componentCount >= 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(hasUnsignedTextureComponent(0))\n\t\t\t\t\t\t\tc[i][j][k].x = MulHigh(As<UShort4>(c[i][j][k].x), f[1 - i][1 - j][1 - k]);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tc[i][j][k].x = MulHigh(c[i][j][k].x, fs[1 - i][1 - j][1 - k]);\n\t\t\t\t\t}\n\t\t\t\t\tif(componentCount >= 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(hasUnsignedTextureComponent(1))\n\t\t\t\t\t\t\tc[i][j][k].y = MulHigh(As<UShort4>(c[i][j][k].y), f[1 - i][1 - j][1 - k]);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tc[i][j][k].y = MulHigh(c[i][j][k].y, fs[1 - i][1 - j][1 - k]);\n\t\t\t\t\t}\n\t\t\t\t\tif(componentCount >= 3)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(hasUnsignedTextureComponent(2))\n\t\t\t\t\t\t\tc[i][j][k].z = MulHigh(As<UShort4>(c[i][j][k].z), f[1 - i][1 - j][1 - k]);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tc[i][j][k].z = MulHigh(c[i][j][k].z, fs[1 - i][1 - j][1 - k]);\n\t\t\t\t\t}\n\t\t\t\t\tif(componentCount >= 4)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(hasUnsignedTextureComponent(3))\n\t\t\t\t\t\t\tc[i][j][k].w = MulHigh(As<UShort4>(c[i][j][k].w), f[1 - i][1 - j][1 - k]);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tc[i][j][k].w = MulHigh(c[i][j][k].w, fs[1 - i][1 - j][1 - k]);\n\t\t\t\t\t}\n\n\t\t\t\t\tif(i != 0 || j != 0 || k != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(componentCount >= 1) c[0][0][0].x += c[i][j][k].x;\n\t\t\t\t\t\tif(componentCount >= 2) c[0][0][0].y += c[i][j][k].y;\n\t\t\t\t\t\tif(componentCount >= 3) c[0][0][0].z += c[i][j][k].z;\n\t\t\t\t\t\tif(componentCount >= 4) c[0][0][0].w += c[i][j][k].w;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(componentCount >= 1) c_.x = c[0][0][0].x;\n\t\tif(componentCount >= 2) c_.y = c[0][0][0].y;\n\t\tif(componentCount >= 3) c_.z = c[0][0][0].z;\n\t\tif(componentCount >= 4) c_.w = c[0][0][0].w;\n\n\t\t\/\/ Correct for signed fractions\n\t\tif(componentCount >= 1)\n\t\t\tif(!hasUnsignedTextureComponent(0)) c_.x = AddSat(c_.x, c_.x);\n\t\tif(componentCount >= 2)\n\t\t\tif(!hasUnsignedTextureComponent(1)) c_.y = AddSat(c_.y, c_.y);\n\t\tif(componentCount >= 3)\n\t\t\tif(!hasUnsignedTextureComponent(2)) c_.z = AddSat(c_.z, c_.z);\n\t\tif(componentCount >= 4)\n\t\t\tif(!hasUnsignedTextureComponent(3)) c_.w = AddSat(c_.w, c_.w);\n\t}\n\n\treturn c_;\n}\n\nVector4f SamplerCore::sampleFloatFilter(Pointer<Byte> &texture, Float4 &u, Float4 &v, Float4 &w, Float4 &q, Vector4f &offset, const Float4 &cubeArrayCoord, const Int4 &sampleId, Float &lod, Float &anisotropy, Float4 &uDelta, Float4 &vDelta, SamplerFunction function)\n{\n\tVector4f c = sampleFloatAniso(texture, u, v, w, q, offset, cubeArrayCoord, sampleId, lod, anisotropy, uDelta, vDelta, false, function);\n\n\tif(function == Fetch)\n\t{\n\t\treturn c;\n\t}\n\n\tif(state.mipmapFilter == MIPMAP_LINEAR)\n\t{\n\t\tVector4f cc = sampleFloatAniso(texture, u, v, w, q, offset, cubeArrayCoord, sampleId, lod, anisotropy, uDelta, vDelta, true, function);\n\n\t\tFloat4 lod4 = Float4(Frac(lod));\n\n\t\tc.x = (cc.x - c.x) * lod4 + c.x;\n\t\tc.y = (cc.y - c.y) * lod4 + c.y;\n\t\tc.z = (cc.z - c.z) * lod4 + c.z;\n\t\tc.w = (cc.w - c.w) * lod4 + c.w;\n\t}\n\n\treturn c;\n}\n\nVector4f SamplerCore::sampleFloatAniso(Pointer<Byte> &texture, Float4 &u, Float4 &v, Float4 &w, Float4 &q, Vector4f &offset, const Float4 &cubeArrayCoord, const Int4 &sampleId, Float &lod, Float &anisotropy, Float4 &uDelta, Float4 &vDelta, bool secondLOD, SamplerFunction function)\n{\n\tVector4f c;\n\n\tif(state.textureFilter != FILTER_ANISOTROPIC || function == Lod || function == Fetch)\n\t{\n\t\tc = sampleFloat(texture, u, v, w, q, offset, cubeArrayCoord, sampleId, lod, secondLOD, function);\n\t}\n\telse\n\t{\n\t\tInt a = RoundInt(anisotropy);\n\n\t\tVector4f cSum;\n\n\t\tcSum.x = Float4(0.0f);\n\t\tcSum.y = Float4(0.0f);\n\t\tcSum.z = Float4(0.0f);\n\t\tcSum.w = Float4(0.0f);\n\n\t\tFloat4 A = *Pointer<Float4>(constants + OFFSET(Constants, uvWeight) + 16 * a);\n\t\tFloat4 B = *Pointer<Float4>(constants + OFFSET(Constants, uvStart) + 16 * a);\n\n\t\tFloat4 du = uDelta;\n\t\tFloat4 dv = vDelta;\n\n\t\tFloat4 u0 = u + B * du;\n\t\tFloat4 v0 = v + B * dv;\n\n\t\tdu *= A;\n\t\tdv *= A;\n\n\t\tInt i = 0;\n\n\t\tDo\n\t\t{\n\t\t\tc = sampleFloat(texture, u0, v0, w, q, offset, cubeArrayCoord, sampleId, lod, secondLOD, function);\n\n\t\t\tu0 += du;\n\t\t\tv0 += dv;\n\n\t\t\tcSum.x += c.x * A;\n\t\t\tcSum.y += c.y * A;\n\t\t\tcSum.z += c.z * A;\n\t\t\tcSum.w += c.w * A;\n\n\t\t\ti++;\n\t\t}\n\t\tUntil(i >= a);\n\n\t\tc.x = cSum.x;\n\t\tc.y = cSum.y;\n\t\tc.z = cSum.z;\n\t\tc.w = cSum.w;\n\t}\n\n\treturn c;\n}\n\nVector4f SamplerCore::sampleFloat(Pointer<Byte> &texture, Float4 &u, Float4 &v, Float4 &w, Float4 &q, Vector4f &offset, const Float4 &cubeArrayCoord, const Int4 &sampleId, Float &lod, bool secondLOD, SamplerFunction function)\n{\n\tif(state.textureType != VK_IMAGE_VIEW_TYPE_3D)\n\t{\n\t\treturn sampleFloat2D(texture, u, v, w, q, offset, cubeArrayCoord, sampleId, lod, secondLOD, function);\n\t}\n\telse\n\t{\n\t\treturn sampleFloat3D(texture, u, v, w, offset, cubeArrayCoord, sampleId, lod, secondLOD, function);\n\t}\n}\n\nVector4f SamplerCore::sampleFloat2D(Pointer<Byte> &texture, Float4 &u, Float4 &v, Float4 &w, Float4 &q, Vector4f &offset, const Float4 &cubeArrayCoord, const Int4 &sampleId, Float &lod, bool secondLOD, SamplerFunction function)\n{\n\tVector4f c;\n\n\tint componentCount = textureComponentCount();\n\tbool gather = (state.textureFilter == FILTER_GATHER);\n\n\tPointer<Byte> mipmap;\n\tPointer<Byte> buffer;\n\tselectMipmap(texture, mipmap, buffer, lod, secondLOD);\n\n\tInt4 x0, x1, y0, y1, z0;\n\tFloat4 fu, fv, fw;\n\tInt4 filter = computeFilterOffset(lod);\n\taddress(u, x0, x1, fu, mipmap, offset.x, filter, OFFSET(Mipmap, width), state.addressingModeU, function);\n\taddress(v, y0, y1, fv, mipmap, offset.y, filter, OFFSET(Mipmap, height), state.addressingModeV, function);\n\taddress(w, z0, z0, fw, mipmap, offset.z, filter, OFFSET(Mipmap, depth), state.addressingModeW, function);\n\n\tInt4 cubeArrayId(0);\n\tif(state.textureType == VK_IMAGE_VIEW_TYPE_CUBE_ARRAY)\n\t{\n\t\taddress(cubeArrayCoord, cubeArrayId, cubeArrayId, fw, mipmap, offset.w, filter, OFFSET(Mipmap, depth), state.addressingModeY, function);\n\t}\n\n\tInt4 pitchP = *Pointer<Int4>(mipmap + OFFSET(Mipmap, pitchP), 16);\n\ty0 *= pitchP;\n\tif(state.addressingModeW != ADDRESSING_UNUSED)\n\t{\n\t\tz0 *= *Pointer<Int4>(mipmap + OFFSET(Mipmap, sliceP), 16);\n\t}\n\n\tif(state.textureFilter == FILTER_POINT || (function == Fetch))\n\t{\n\t\tc = sampleTexel(x0, y0, z0, q, mipmap, cubeArrayId, sampleId, buffer, function);\n\t}\n\telse\n\t{\n\t\ty1 *= pitchP;\n\n\t\tVector4f c00 = sampleTexel(x0, y0, z0, q, mipmap, cubeArrayId, sampleId, buffer, function);\n\t\tVector4f c10 = sampleTexel(x1, y0, z0, q, mipmap, cubeArrayId, sampleId, buffer, function);\n\t\tVector4f c01 = sampleTexel(x0, y1, z0, q, mipmap, cubeArrayId, sampleId, buffer, function);\n\t\tVector4f c11 = sampleTexel(x1, y1, z0, q, mipmap, cubeArrayId, sampleId, buffer, function);\n\n\t\tif(!gather)  \/\/ Blend\n\t\t{\n\t\t\tif(componentCount >= 1) c00.x = c00.x + fu * (c10.x - c00.x);\n\t\t\tif(componentCount >= 2) c00.y = c00.y + fu * (c10.y - c00.y);\n\t\t\tif(componentCount >= 3) c00.z = c00.z + fu * (c10.z - c00.z);\n\t\t\tif(componentCount >= 4) c00.w = c00.w + fu * (c10.w - c00.w);\n\n\t\t\tif(componentCount >= 1) c01.x = c01.x + fu * (c11.x - c01.x);\n\t\t\tif(componentCount >= 2) c01.y = c01.y + fu * (c11.y - c01.y);\n\t\t\tif(componentCount >= 3) c01.z = c01.z + fu * (c11.z - c01.z);\n\t\t\tif(componentCount >= 4) c01.w = c01.w + fu * (c11.w - c01.w);\n\n\t\t\tif(componentCount >= 1) c.x = c00.x + fv * (c01.x - c00.x);\n\t\t\tif(componentCount >= 2) c.y = c00.y + fv * (c01.y - c00.y);\n\t\t\tif(componentCount >= 3) c.z = c00.z + fv * (c01.z - c00.z);\n\t\t\tif(componentCount >= 4) c.w = c00.w + fv * (c01.w - c00.w);\n\t\t}\n\t\telse  \/\/ Gather\n\t\t{\n\t\t\tVkComponentSwizzle swizzle = gatherSwizzle();\n\t\t\tswitch(swizzle)\n\t\t\t{\n\t\t\t\tcase VK_COMPONENT_SWIZZLE_ZERO:\n\t\t\t\tcase VK_COMPONENT_SWIZZLE_ONE:\n\t\t\t\t\t\/\/ Handled at the final component swizzle.\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tc.x = c01[swizzle - VK_COMPONENT_SWIZZLE_R];\n\t\t\t\t\tc.y = c11[swizzle - VK_COMPONENT_SWIZZLE_R];\n\t\t\t\t\tc.z = c10[swizzle - VK_COMPONENT_SWIZZLE_R];\n\t\t\t\t\tc.w = c00[swizzle - VK_COMPONENT_SWIZZLE_R];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn c;\n}\n\nVector4f SamplerCore::sampleFloat3D(Pointer<Byte> &texture, Float4 &u, Float4 &v, Float4 &w, Vector4f &offset, const Float4 &cubeArrayCoord, const Int4 &sampleId, Float &lod, bool secondLOD, SamplerFunction function)\n{\n\tVector4f c;\n\n\tint componentCount = textureComponentCount();\n\n\tPointer<Byte> mipmap;\n\tPointer<Byte> buffer;\n\tselectMipmap(texture, mipmap, buffer, lod, secondLOD);\n\n\tInt4 x0, x1, y0, y1, z0, z1;\n\tFloat4 fu, fv, fw;\n\tInt4 filter = computeFilterOffset(lod);\n\taddress(u, x0, x1, fu, mipmap, offset.x, filter, OFFSET(Mipmap, width), state.addressingModeU, function);\n\taddress(v, y0, y1, fv, mipmap, offset.y, filter, OFFSET(Mipmap, height), state.addressingModeV, function);\n\taddress(w, z0, z1, fw, mipmap, offset.z, filter, OFFSET(Mipmap, depth), state.addressingModeW, function);\n\n\tInt4 cubeArrayId(0);\n\tif(state.textureType == VK_IMAGE_VIEW_TYPE_CUBE_ARRAY)\n\t{\n\t\taddress(cubeArrayCoord, cubeArrayId, cubeArrayId, fw, mipmap, offset.w, filter, OFFSET(Mipmap, depth), state.addressingModeY, function);\n\t}\n\n\tInt4 pitchP = *Pointer<Int4>(mipmap + OFFSET(Mipmap, pitchP), 16);\n\tInt4 sliceP = *Pointer<Int4>(mipmap + OFFSET(Mipmap, sliceP), 16);\n\ty0 *= pitchP;\n\tz0 *= sliceP;\n\n\tif(state.textureFilter == FILTER_POINT || (function == Fetch))\n\t{\n\t\tc = sampleTexel(x0, y0, z0, w, mipmap, cubeArrayId, sampleId, buffer, function);\n\t}\n\telse\n\t{\n\t\ty1 *= pitchP;\n\t\tz1 *= sliceP;\n\n\t\tVector4f c000 = sampleTexel(x0, y0, z0, w, mipmap, cubeArrayId, sampleId, buffer, function);\n\t\tVector4f c100 = sampleTexel(x1, y0, z0, w, mipmap, cubeArrayId, sampleId, buffer, function);\n\t\tVector4f c010 = sampleTexel(x0, y1, z0, w, mipmap, cubeArrayId, sampleId, buffer, function);\n\t\tVector4f c110 = sampleTexel(x1, y1, z0, w, mipmap, cubeArrayId, sampleId, buffer, function);\n\t\tVector4f c001 = sampleTexel(x0, y0, z1, w, mipmap, cubeArrayId, sampleId, buffer, function);\n\t\tVector4f c101 = sampleTexel(x1, y0, z1, w, mipmap, cubeArrayId, sampleId, buffer, function);\n\t\tVector4f c011 = sampleTexel(x0, y1, z1, w, mipmap, cubeArrayId, sampleId, buffer, function);\n\t\tVector4f c111 = sampleTexel(x1, y1, z1, w, mipmap, cubeArrayId, sampleId, buffer, function);\n\n\t\t\/\/ Blend first slice\n\t\tif(componentCount >= 1) c000.x = c000.x + fu * (c100.x - c000.x);\n\t\tif(componentCount >= 2) c000.y = c000.y + fu * (c100.y - c000.y);\n\t\tif(componentCount >= 3) c000.z = c000.z + fu * (c100.z - c000.z);\n\t\tif(componentCount >= 4) c000.w = c000.w + fu * (c100.w - c000.w);\n\n\t\tif(componentCount >= 1) c010.x = c010.x + fu * (c110.x - c010.x);\n\t\tif(componentCount >= 2) c010.y = c010.y + fu * (c110.y - c010.y);\n\t\tif(componentCount >= 3) c010.z = c010.z + fu * (c110.z - c010.z);\n\t\tif(componentCount >= 4) c010.w = c010.w + fu * (c110.w - c010.w);\n\n\t\tif(componentCount >= 1) c000.x = c000.x + fv * (c010.x - c000.x);\n\t\tif(componentCount >= 2) c000.y = c000.y + fv * (c010.y - c000.y);\n\t\tif(componentCount >= 3) c000.z = c000.z + fv * (c010.z - c000.z);\n\t\tif(componentCount >= 4) c000.w = c000.w + fv * (c010.w - c000.w);\n\n\t\t\/\/ Blend second slice\n\t\tif(componentCount >= 1) c001.x = c001.x + fu * (c101.x - c001.x);\n\t\tif(componentCount >= 2) c001.y = c001.y + fu * (c101.y - c001.y);\n\t\tif(componentCount >= 3) c001.z = c001.z + fu * (c101.z - c001.z);\n\t\tif(componentCount >= 4) c001.w = c001.w + fu * (c101.w - c001.w);\n\n\t\tif(componentCount >= 1) c011.x = c011.x + fu * (c111.x - c011.x);\n\t\tif(componentCount >= 2) c011.y = c011.y + fu * (c111.y - c011.y);\n\t\tif(componentCount >= 3) c011.z = c011.z + fu * (c111.z - c011.z);\n\t\tif(componentCount >= 4) c011.w = c011.w + fu * (c111.w - c011.w);\n\n\t\tif(componentCount >= 1) c001.x = c001.x + fv * (c011.x - c001.x);\n\t\tif(componentCount >= 2) c001.y = c001.y + fv * (c011.y - c001.y);\n\t\tif(componentCount >= 3) c001.z = c001.z + fv * (c011.z - c001.z);\n\t\tif(componentCount >= 4) c001.w = c001.w + fv * (c011.w - c001.w);\n\n\t\t\/\/ Blend slices\n\t\tif(componentCount >= 1) c.x = c000.x + fw * (c001.x - c000.x);\n\t\tif(componentCount >= 2) c.y = c000.y + fw * (c001.y - c000.y);\n\t\tif(componentCount >= 3) c.z = c000.z + fw * (c001.z - c000.z);\n\t\tif(componentCount >= 4) c.w = c000.w + fw * (c001.w - c000.w);\n\t}\n\n\treturn c;\n}\n\nFloat SamplerCore::log2sqrt(Float lod)\n{\n\t\/\/ log2(sqrt(lod))                               \/\/ Equals 0.25 * log2(lod^2).\n\tlod *= lod;                                     \/\/ Squaring doubles the exponent and produces an extra bit of precision.\n\tlod = Float(As<Int>(lod)) - Float(0x3F800000);  \/\/ Interpret as integer and subtract the exponent bias.\n\tlod *= As<Float>(Int(0x33000000));              \/\/ Scale by 0.25 * 2^-23 (mantissa length).\n\n\treturn lod;\n}\n\nFloat SamplerCore::log2(Float lod)\n{\n\tlod *= lod;                                     \/\/ Squaring doubles the exponent and produces an extra bit of precision.\n\tlod = Float(As<Int>(lod)) - Float(0x3F800000);  \/\/ Interpret as integer and subtract the exponent bias.\n\tlod *= As<Float>(Int(0x33800000));              \/\/ Scale by 0.5 * 2^-23 (mantissa length).\n\n\treturn lod;\n}\n\nvoid SamplerCore::computeLod(Pointer<Byte> &texture, Pointer<Byte> &sampler, Float &lod, Float &anisotropy, Float4 &uDelta, Float4 &vDelta, Float4 &uuuu, Float4 &vvvv, Float4 &dsx, Float4 &dsy, SamplerFunction function)\n{\n\tFloat4 duvdxy;\n\n\tif(function != Grad)  \/\/ Implicit\n\t{\n\t\tduvdxy = Float4(uuuu.yz, vvvv.yz) - Float4(uuuu.xx, vvvv.xx);\n\t}\n\telse\n\t{\n\t\tFloat4 dudxy = Float4(dsx.xx, dsy.xx);\n\t\tFloat4 dvdxy = Float4(dsx.yy, dsy.yy);\n\n\t\tduvdxy = Float4(dudxy.xz, dvdxy.xz);\n\t}\n\n\t\/\/ Scale by texture dimensions.\n\tFloat4 dUVdxy = duvdxy * *Pointer<Float4>(texture + OFFSET(Texture, widthWidthHeightHeight));\n\n\tFloat4 dUV2dxy = dUVdxy * dUVdxy;\n\tFloat4 dUV2 = dUV2dxy.xy + dUV2dxy.zw;\n\n\tlod = Max(Float(dUV2.x), Float(dUV2.y));  \/\/ Square length of major axis\n\n\tif(state.textureFilter == FILTER_ANISOTROPIC)\n\t{\n\t\tFloat det = Abs(Float(dUVdxy.x) * Float(dUVdxy.w) - Float(dUVdxy.y) * Float(dUVdxy.z));\n\n\t\tFloat4 dudx = duvdxy.xxxx;\n\t\tFloat4 dudy = duvdxy.yyyy;\n\t\tFloat4 dvdx = duvdxy.zzzz;\n\t\tFloat4 dvdy = duvdxy.wwww;\n\n\t\tInt4 mask = As<Int4>(CmpNLT(dUV2.x, dUV2.y));\n\t\tuDelta = As<Float4>((As<Int4>(dudx) & mask) | ((As<Int4>(dudy) & ~mask)));\n\t\tvDelta = As<Float4>((As<Int4>(dvdx) & mask) | ((As<Int4>(dvdy) & ~mask)));\n\n\t\tanisotropy = lod * Rcp_pp(det);\n\t\tanisotropy = Min(anisotropy, *Pointer<Float>(sampler + OFFSET(vk::Sampler, maxAnisotropy)));\n\n\t\tlod *= Rcp_pp(anisotropy * anisotropy);\n\t}\n\n\tlod = log2sqrt(lod);  \/\/ log2(sqrt(lod))\n}\n\nvoid SamplerCore::computeLodCube(Pointer<Byte> &texture, Pointer<Byte> &sampler, Float &lod, Float4 &u, Float4 &v, Float4 &w, Float4 &dsx, Float4 &dsy, Float4 &M, SamplerFunction function)\n{\n\tFloat4 dudxy, dvdxy, dsdxy;\n\n\tif(function != Grad)  \/\/ Implicit\n\t{\n\t\tFloat4 U = u * M;\n\t\tFloat4 V = v * M;\n\t\tFloat4 W = w * M;\n\n\t\tdudxy = Abs(U - U.xxxx);\n\t\tdvdxy = Abs(V - V.xxxx);\n\t\tdsdxy = Abs(W - W.xxxx);\n\t}\n\telse\n\t{\n\t\tdudxy = Float4(dsx.xx, dsy.xx);\n\t\tdvdxy = Float4(dsx.yy, dsy.yy);\n\t\tdsdxy = Float4(dsx.zz, dsy.zz);\n\n\t\tdudxy = Abs(dudxy * Float4(M.x));\n\t\tdvdxy = Abs(dvdxy * Float4(M.x));\n\t\tdsdxy = Abs(dsdxy * Float4(M.x));\n\t}\n\n\t\/\/ Compute the largest Manhattan distance in two dimensions.\n\t\/\/ This takes the footprint across adjacent faces into account.\n\tFloat4 duvdxy = dudxy + dvdxy;\n\tFloat4 dusdxy = dudxy + dsdxy;\n\tFloat4 dvsdxy = dvdxy + dsdxy;\n\n\tdudxy = Max(Max(duvdxy, dusdxy), dvsdxy);\n\n\tlod = Max(Float(dudxy.y), Float(dudxy.z));  \/\/ FIXME: Max(dudxy.y, dudxy.z);\n\n\t\/\/ Scale by texture dimension.\n\tlod *= *Pointer<Float>(texture + OFFSET(Texture, width));\n\n\tlod = log2(lod);\n}\n\nvoid SamplerCore::computeLod3D(Pointer<Byte> &texture, Pointer<Byte> &sampler, Float &lod, Float4 &uuuu, Float4 &vvvv, Float4 &wwww, Float4 &dsx, Float4 &dsy, SamplerFunction function)\n{\n\tFloat4 dudxy, dvdxy, dsdxy;\n\n\tif(function != Grad)  \/\/ Implicit\n\t{\n\t\tdudxy = uuuu - uuuu.xxxx;\n\t\tdvdxy = vvvv - vvvv.xxxx;\n\t\tdsdxy = wwww - wwww.xxxx;\n\t}\n\telse\n\t{\n\t\tdudxy = Float4(dsx.xx, dsy.xx);\n\t\tdvdxy = Float4(dsx.yy, dsy.yy);\n\t\tdsdxy = Float4(dsx.zz, dsy.zz);\n\t}\n\n\t\/\/ Scale by texture dimensions.\n\tdudxy *= *Pointer<Float4>(texture + OFFSET(Texture, width));\n\tdvdxy *= *Pointer<Float4>(texture + OFFSET(Texture, height));\n\tdsdxy *= *Pointer<Float4>(texture + OFFSET(Texture, depth));\n\n\tdudxy *= dudxy;\n\tdvdxy *= dvdxy;\n\tdsdxy *= dsdxy;\n\n\tdudxy += dvdxy;\n\tdudxy += dsdxy;\n\n\tlod = Max(Float(dudxy.y), Float(dudxy.z));  \/\/ FIXME: Max(dudxy.y, dudxy.z);\n\n\tlod = log2sqrt(lod);  \/\/ log2(sqrt(lod))\n}\n\nInt4 SamplerCore::cubeFace(Float4 &U, Float4 &V, Float4 &x, Float4 &y, Float4 &z, Float4 &M)\n{\n\t\/\/ TODO: Comply with Vulkan recommendation:\n\t\/\/ Vulkan 1.1: \"The rules should have as the first rule that rz wins over ry and rx, and the second rule that ry wins over rx.\"\n\n\tInt4 xn = CmpLT(x, Float4(0.0f));  \/\/ x < 0\n\tInt4 yn = CmpLT(y, Float4(0.0f));  \/\/ y < 0\n\tInt4 zn = CmpLT(z, Float4(0.0f));  \/\/ z < 0\n\n\tFloat4 absX = Abs(x);\n\tFloat4 absY = Abs(y);\n\tFloat4 absZ = Abs(z);\n\n\tInt4 xy = CmpNLE(absX, absY);  \/\/ abs(x) > abs(y)\n\tInt4 yz = CmpNLE(absY, absZ);  \/\/ abs(y) > abs(z)\n\tInt4 zx = CmpNLE(absZ, absX);  \/\/ abs(z) > abs(x)\n\tInt4 xMajor = xy & ~zx;        \/\/ abs(x) > abs(y) && abs(x) > abs(z)\n\tInt4 yMajor = yz & ~xy;        \/\/ abs(y) > abs(z) && abs(y) > abs(x)\n\tInt4 zMajor = zx & ~yz;        \/\/ abs(z) > abs(x) && abs(z) > abs(y)\n\n\t\/\/ FACE_POSITIVE_X = 000b\n\t\/\/ FACE_NEGATIVE_X = 001b\n\t\/\/ FACE_POSITIVE_Y = 010b\n\t\/\/ FACE_NEGATIVE_Y = 011b\n\t\/\/ FACE_POSITIVE_Z = 100b\n\t\/\/ FACE_NEGATIVE_Z = 101b\n\n\tInt yAxis = SignMask(yMajor);\n\tInt zAxis = SignMask(zMajor);\n\n\tInt4 n = ((xn & xMajor) | (yn & yMajor) | (zn & zMajor)) & Int4(0x80000000);\n\tInt negative = SignMask(n);\n\n\tInt faces = *Pointer<Int>(constants + OFFSET(Constants, transposeBit0) + negative * 4);\n\tfaces |= *Pointer<Int>(constants + OFFSET(Constants, transposeBit1) + yAxis * 4);\n\tfaces |= *Pointer<Int>(constants + OFFSET(Constants, transposeBit2) + zAxis * 4);\n\n\tInt4 face;\n\tface.x = faces & 0x7;\n\tface.y = (faces >> 4) & 0x7;\n\tface.z = (faces >> 8) & 0x7;\n\tface.w = (faces >> 12) & 0x7;\n\n\tM = Max(Max(absX, absY), Max(absZ, Float4(std::numeric_limits<float>::min())));\n\n\t\/\/ U = xMajor ? (neg ^ -z) : ((zMajor & neg) ^ x)\n\tU = As<Float4>((xMajor & (n ^ As<Int4>(-z))) | (~xMajor & ((zMajor & n) ^ As<Int4>(x))));\n\n\t\/\/ V = !yMajor ? -y : (n ^ z)\n\tV = As<Float4>((~yMajor & As<Int4>(-y)) | (yMajor & (n ^ As<Int4>(z))));\n\n\tM = reciprocal(M) * Float4(0.5f);\n\tU = U * M + Float4(0.5f);\n\tV = V * M + Float4(0.5f);\n\n\treturn face;\n}\n\nShort4 SamplerCore::applyOffset(Short4 &uvw, Float4 &offset, const Int4 &whd, AddressingMode mode)\n{\n\tInt4 tmp = Int4(As<UShort4>(uvw));\n\ttmp = tmp + As<Int4>(offset);\n\n\tswitch(mode)\n\t{\n\t\tcase AddressingMode::ADDRESSING_WRAP:\n\t\t\ttmp = (tmp + whd * Int4(-MIN_TEXEL_OFFSET)) % whd;\n\t\t\tbreak;\n\t\tcase AddressingMode::ADDRESSING_CLAMP:\n\t\tcase AddressingMode::ADDRESSING_MIRROR:\n\t\tcase AddressingMode::ADDRESSING_MIRRORONCE:\n\t\tcase AddressingMode::ADDRESSING_BORDER:  \/\/ FIXME: Implement and test ADDRESSING_MIRROR, ADDRESSING_MIRRORONCE, ADDRESSING_BORDER\n\t\t\ttmp = Min(Max(tmp, Int4(0)), whd - Int4(1));\n\t\t\tbreak;\n\t\tcase ADDRESSING_TEXELFETCH:\n\t\t\tbreak;\n\t\tcase AddressingMode::ADDRESSING_SEAMLESS:\n\t\t\tASSERT(false);  \/\/ Cube sampling doesn't support offset.\n\t\tdefault:\n\t\t\tASSERT(false);\n\t}\n\n\treturn As<Short4>(UShort4(tmp));\n}\n\nvoid SamplerCore::computeIndices(UInt index[4], Short4 uuuu, Short4 vvvv, Short4 wwww, Vector4f &offset, const Pointer<Byte> &mipmap, const Short4 &cubeArrayId, const Int4 &sampleId, SamplerFunction function)\n{\n\tbool texelFetch = (function == Fetch);\n\tbool hasOffset = (function.offset != 0);\n\n\tif(!texelFetch)\n\t{\n\t\tuuuu = MulHigh(As<UShort4>(uuuu), UShort4(*Pointer<Int4>(mipmap + OFFSET(Mipmap, width))));\n\t\tvvvv = MulHigh(As<UShort4>(vvvv), UShort4(*Pointer<Int4>(mipmap + OFFSET(Mipmap, height))));\n\t}\n\n\tif(hasOffset)\n\t{\n\t\tuuuu = applyOffset(uuuu, offset.x, *Pointer<Int4>(mipmap + OFFSET(Mipmap, width)),\n\t\t                   texelFetch ? ADDRESSING_TEXELFETCH : state.addressingModeU);\n\t\tvvvv = applyOffset(vvvv, offset.y, *Pointer<Int4>(mipmap + OFFSET(Mipmap, height)),\n\t\t                   texelFetch ? ADDRESSING_TEXELFETCH : state.addressingModeV);\n\t}\n\n\tShort4 uuu2 = uuuu;\n\tuuuu = As<Short4>(UnpackLow(uuuu, vvvv));\n\tuuu2 = As<Short4>(UnpackHigh(uuu2, vvvv));\n\tuuuu = As<Short4>(MulAdd(uuuu, *Pointer<Short4>(mipmap + OFFSET(Mipmap, onePitchP))));\n\tuuu2 = As<Short4>(MulAdd(uuu2, *Pointer<Short4>(mipmap + OFFSET(Mipmap, onePitchP))));\n\n\tif(hasThirdCoordinate())\n\t{\n\t\tif(state.textureType == VK_IMAGE_VIEW_TYPE_3D)\n\t\t{\n\t\t\tif(!texelFetch)\n\t\t\t{\n\t\t\t\twwww = MulHigh(As<UShort4>(wwww), UShort4(*Pointer<Int4>(mipmap + OFFSET(Mipmap, depth))));\n\t\t\t}\n\n\t\t\tif(hasOffset)\n\t\t\t{\n\t\t\t\twwww = applyOffset(wwww, offset.z, *Pointer<Int4>(mipmap + OFFSET(Mipmap, depth)),\n\t\t\t\t                   texelFetch ? ADDRESSING_TEXELFETCH : state.addressingModeW);\n\t\t\t}\n\t\t}\n\n\t\tUInt4 uv(As<UInt2>(uuuu), As<UInt2>(uuu2));\n\t\tuv += As<UInt4>(Int4(As<UShort4>(wwww))) * *Pointer<UInt4>(mipmap + OFFSET(Mipmap, sliceP));\n\n\t\tindex[0] = Extract(As<Int4>(uv), 0);\n\t\tindex[1] = Extract(As<Int4>(uv), 1);\n\t\tindex[2] = Extract(As<Int4>(uv), 2);\n\t\tindex[3] = Extract(As<Int4>(uv), 3);\n\t}\n\telse\n\t{\n\t\tindex[0] = Extract(As<Int2>(uuuu), 0);\n\t\tindex[1] = Extract(As<Int2>(uuuu), 1);\n\t\tindex[2] = Extract(As<Int2>(uuu2), 0);\n\t\tindex[3] = Extract(As<Int2>(uuu2), 1);\n\t}\n\n\tif(texelFetch)\n\t{\n\t\tInt size = *Pointer<Int>(mipmap + OFFSET(Mipmap, sliceP));\n\t\tif(hasThirdCoordinate())\n\t\t{\n\t\t\tsize *= *Pointer<Int>(mipmap + OFFSET(Mipmap, depth));\n\t\t}\n\t\tUInt min = 0;\n\t\tUInt max = size - 1;\n\n\t\tfor(int i = 0; i < 4; i++)\n\t\t{\n\t\t\tindex[i] = Min(Max(index[i], min), max);\n\t\t}\n\t}\n\n\tif(function.sample)\n\t{\n\t\tUInt4 sampleOffset = Min(As<UInt4>(sampleId), *Pointer<UInt4>(mipmap + OFFSET(Mipmap, sampleMax), 16)) *\n\t\t                     *Pointer<UInt4>(mipmap + OFFSET(Mipmap, samplePitchP), 16);\n\t\tfor(int i = 0; i < 4; i++)\n\t\t{\n\t\t\tindex[i] += Extract(sampleOffset, i);\n\t\t}\n\t}\n\n\tif(state.textureType == VK_IMAGE_VIEW_TYPE_CUBE_ARRAY)\n\t{\n\t\tUInt4 cubeLayerOffset = As<UInt4>(cubeArrayId) * *Pointer<UInt4>(mipmap + OFFSET(Mipmap, sliceP)) * UInt4(6);\n\t\tfor(int i = 0; i < 4; i++)\n\t\t{\n\t\t\tindex[i] += Extract(cubeLayerOffset, i);\n\t\t}\n\t}\n}\n\nvoid SamplerCore::computeIndices(UInt index[4], Int4 uuuu, Int4 vvvv, Int4 wwww, Int4 valid, const Pointer<Byte> &mipmap, const Int4 &cubeArrayId, const Int4 &sampleId, SamplerFunction function)\n{\n\tUInt4 indices = uuuu + vvvv;\n\n\tif(state.addressingModeW != ADDRESSING_UNUSED)\n\t{\n\t\tindices += As<UInt4>(wwww);\n\t}\n\n\tif(borderModeActive())\n\t{\n\t\t\/\/ Texels out of range are still sampled before being replaced\n\t\t\/\/ with the border color, so sample them at linear index 0.\n\t\tindices &= As<UInt4>(valid);\n\t}\n\n\tif(function.sample)\n\t{\n\t\tindices += Min(As<UInt4>(sampleId), *Pointer<UInt4>(mipmap + OFFSET(Mipmap, sampleMax), 16)) *\n\t\t           *Pointer<UInt4>(mipmap + OFFSET(Mipmap, samplePitchP), 16);\n\t}\n\n\tif(state.textureType == VK_IMAGE_VIEW_TYPE_CUBE_ARRAY)\n\t{\n\t\tindices += As<UInt4>(cubeArrayId) * *Pointer<UInt4>(mipmap + OFFSET(Mipmap, sliceP)) * UInt4(6);\n\t}\n\n\tfor(int i = 0; i < 4; i++)\n\t{\n\t\tindex[i] = Extract(As<Int4>(indices), i);\n\t}\n}\n\nVector4s SamplerCore::sampleTexel(UInt index[4], Pointer<Byte> buffer)\n{\n\tVector4s c;\n\n\tif(has16bitTextureFormat())\n\t{\n\t\tc.x = Insert(c.x, Pointer<Short>(buffer)[index[0]], 0);\n\t\tc.x = Insert(c.x, Pointer<Short>(buffer)[index[1]], 1);\n\t\tc.x = Insert(c.x, Pointer<Short>(buffer)[index[2]], 2);\n\t\tc.x = Insert(c.x, Pointer<Short>(buffer)[index[3]], 3);\n\n\t\tswitch(state.textureFormat)\n\t\t{\n\t\t\tcase VK_FORMAT_R5G6B5_UNORM_PACK16:\n\t\t\t\tc.z = (c.x & Short4(0x001Fu)) << 11;\n\t\t\t\tc.y = (c.x & Short4(0x07E0u)) << 5;\n\t\t\t\tc.x = (c.x & Short4(0xF800u));\n\t\t\t\tbreak;\n\t\t\tcase VK_FORMAT_B4G4R4A4_UNORM_PACK16:\n\t\t\t\tc.w = (c.x << 12) & Short4(0xF000u);\n\t\t\t\tc.z = (c.x) & Short4(0xF000u);\n\t\t\t\tc.y = (c.x << 4) & Short4(0xF000u);\n\t\t\t\tc.x = (c.x << 8) & Short4(0xF000u);\n\t\t\t\tbreak;\n\t\t\tcase VK_FORMAT_A1R5G5B5_UNORM_PACK16:\n\t\t\t\tc.w = (c.x) & Short4(0x8000u);\n\t\t\t\tc.z = (c.x << 11) & Short4(0xF800u);\n\t\t\t\tc.y = (c.x << 6) & Short4(0xF800u);\n\t\t\t\tc.x = (c.x << 1) & Short4(0xF800u);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tASSERT(false);\n\t\t}\n\t}\n\telse if(has8bitTextureComponents())\n\t{\n\t\tswitch(textureComponentCount())\n\t\t{\n\t\t\tcase 4:\n\t\t\t{\n\t\t\t\tByte4 c0 = Pointer<Byte4>(buffer)[index[0]];\n\t\t\t\tByte4 c1 = Pointer<Byte4>(buffer)[index[1]];\n\t\t\t\tByte4 c2 = Pointer<Byte4>(buffer)[index[2]];\n\t\t\t\tByte4 c3 = Pointer<Byte4>(buffer)[index[3]];\n\t\t\t\tc.x = Unpack(c0, c1);\n\t\t\t\tc.y = Unpack(c2, c3);\n\n\t\t\t\tswitch(state.textureFormat)\n\t\t\t\t{\n\t\t\t\t\tcase VK_FORMAT_B8G8R8A8_UNORM:\n\t\t\t\t\tcase VK_FORMAT_B8G8R8A8_SRGB:\n\t\t\t\t\t\tc.z = As<Short4>(UnpackLow(c.x, c.y));\n\t\t\t\t\t\tc.x = As<Short4>(UnpackHigh(c.x, c.y));\n\t\t\t\t\t\tc.y = c.z;\n\t\t\t\t\t\tc.w = c.x;\n\t\t\t\t\t\tc.z = UnpackLow(As<Byte8>(Short4(0)), As<Byte8>(c.z));\n\t\t\t\t\t\tc.y = UnpackHigh(As<Byte8>(Short4(0)), As<Byte8>(c.y));\n\t\t\t\t\t\tc.x = UnpackLow(As<Byte8>(Short4(0)), As<Byte8>(c.x));\n\t\t\t\t\t\tc.w = UnpackHigh(As<Byte8>(Short4(0)), As<Byte8>(c.w));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase VK_FORMAT_R8G8B8A8_UNORM:\n\t\t\t\t\tcase VK_FORMAT_R8G8B8A8_SINT:\n\t\t\t\t\tcase VK_FORMAT_R8G8B8A8_SNORM:\n\t\t\t\t\tcase VK_FORMAT_R8G8B8A8_SRGB:\n\t\t\t\t\t\tc.z = As<Short4>(UnpackHigh(c.x, c.y));\n\t\t\t\t\t\tc.x = As<Short4>(UnpackLow(c.x, c.y));\n\t\t\t\t\t\tc.y = c.x;\n\t\t\t\t\t\tc.w = c.z;\n\t\t\t\t\t\tc.x = UnpackLow(As<Byte8>(Short4(0)), As<Byte8>(c.x));\n\t\t\t\t\t\tc.y = UnpackHigh(As<Byte8>(Short4(0)), As<Byte8>(c.y));\n\t\t\t\t\t\tc.z = UnpackLow(As<Byte8>(Short4(0)), As<Byte8>(c.z));\n\t\t\t\t\t\tc.w = UnpackHigh(As<Byte8>(Short4(0)), As<Byte8>(c.w));\n\t\t\t\t\t\t\/\/ Propagate sign bit\n\t\t\t\t\t\tif(state.textureFormat == VK_FORMAT_R8G8B8A8_SINT)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tc.x >>= 8;\n\t\t\t\t\t\t\tc.y >>= 8;\n\t\t\t\t\t\t\tc.z >>= 8;\n\t\t\t\t\t\t\tc.w >>= 8;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase VK_FORMAT_R8G8B8A8_UINT:\n\t\t\t\t\t\tc.z = As<Short4>(UnpackHigh(c.x, c.y));\n\t\t\t\t\t\tc.x = As<Short4>(UnpackLow(c.x, c.y));\n\t\t\t\t\t\tc.y = c.x;\n\t\t\t\t\t\tc.w = c.z;\n\t\t\t\t\t\tc.x = UnpackLow(As<Byte8>(c.x), As<Byte8>(Short4(0)));\n\t\t\t\t\t\tc.y = UnpackHigh(As<Byte8>(c.y), As<Byte8>(Short4(0)));\n\t\t\t\t\t\tc.z = UnpackLow(As<Byte8>(c.z), As<Byte8>(Short4(0)));\n\t\t\t\t\t\tc.w = UnpackHigh(As<Byte8>(c.w), As<Byte8>(Short4(0)));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tASSERT(false);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tc.x = Insert(c.x, Pointer<Short>(buffer)[index[0]], 0);\n\t\t\t\tc.x = Insert(c.x, Pointer<Short>(buffer)[index[1]], 1);\n\t\t\t\tc.x = Insert(c.x, Pointer<Short>(buffer)[index[2]], 2);\n\t\t\t\tc.x = Insert(c.x, Pointer<Short>(buffer)[index[3]], 3);\n\n\t\t\t\tswitch(state.textureFormat)\n\t\t\t\t{\n\t\t\t\t\tcase VK_FORMAT_R8G8_UNORM:\n\t\t\t\t\tcase VK_FORMAT_R8G8_SNORM:\n\t\t\t\t\tcase VK_FORMAT_R8G8_SRGB:\n\t\t\t\t\t\tc.y = (c.x & Short4(0xFF00u));\n\t\t\t\t\t\tc.x = (c.x << 8);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase VK_FORMAT_R8G8_SINT:\n\t\t\t\t\t\tc.y = c.x >> 8;\n\t\t\t\t\t\tc.x = (c.x << 8) >> 8;  \/\/ Propagate sign bit\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase VK_FORMAT_R8G8_UINT:\n\t\t\t\t\t\tc.y = As<Short4>(As<UShort4>(c.x) >> 8);\n\t\t\t\t\t\tc.x &= Short4(0x00FFu);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tASSERT(false);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t{\n\t\t\t\tInt c0 = Int(*Pointer<Byte>(buffer + index[0]));\n\t\t\t\tInt c1 = Int(*Pointer<Byte>(buffer + index[1]));\n\t\t\t\tInt c2 = Int(*Pointer<Byte>(buffer + index[2]));\n\t\t\t\tInt c3 = Int(*Pointer<Byte>(buffer + index[3]));\n\t\t\t\tc0 = c0 | (c1 << 8) | (c2 << 16) | (c3 << 24);\n\n\t\t\t\tswitch(state.textureFormat)\n\t\t\t\t{\n\t\t\t\t\tcase VK_FORMAT_R8_SINT:\n\t\t\t\t\tcase VK_FORMAT_R8_UINT:\n\t\t\t\t\tcase VK_FORMAT_S8_UINT:\n\t\t\t\t\t{\n\t\t\t\t\t\tInt zero(0);\n\t\t\t\t\t\tc.x = Unpack(As<Byte4>(c0), As<Byte4>(zero));\n\t\t\t\t\t\t\/\/ Propagate sign bit\n\t\t\t\t\t\tif(state.textureFormat == VK_FORMAT_R8_SINT)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tc.x = (c.x << 8) >> 8;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase VK_FORMAT_R8_SNORM:\n\t\t\t\t\tcase VK_FORMAT_R8_UNORM:\n\t\t\t\t\tcase VK_FORMAT_R8_SRGB:\n\t\t\t\t\t\t\/\/ TODO: avoid populating the low bits at all.\n\t\t\t\t\t\tc.x = Unpack(As<Byte4>(c0));\n\t\t\t\t\t\tc.x &= Short4(0xFF00u);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tc.x = Unpack(As<Byte4>(c0));\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tASSERT(false);\n\t\t}\n\t}\n\telse if(has16bitTextureComponents())\n\t{\n\t\tswitch(textureComponentCount())\n\t\t{\n\t\t\tcase 4:\n\t\t\t\tc.x = Pointer<Short4>(buffer)[index[0]];\n\t\t\t\tc.y = Pointer<Short4>(buffer)[index[1]];\n\t\t\t\tc.z = Pointer<Short4>(buffer)[index[2]];\n\t\t\t\tc.w = Pointer<Short4>(buffer)[index[3]];\n\t\t\t\ttranspose4x4(c.x, c.y, c.z, c.w);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tc.x = Pointer<Short4>(buffer)[index[0]];\n\t\t\t\tc.y = Pointer<Short4>(buffer)[index[1]];\n\t\t\t\tc.z = Pointer<Short4>(buffer)[index[2]];\n\t\t\t\tc.w = Pointer<Short4>(buffer)[index[3]];\n\t\t\t\ttranspose4x3(c.x, c.y, c.z, c.w);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tc.x = *Pointer<Short4>(buffer + 4 * index[0]);\n\t\t\t\tc.x = As<Short4>(UnpackLow(c.x, *Pointer<Short4>(buffer + 4 * index[1])));\n\t\t\t\tc.z = *Pointer<Short4>(buffer + 4 * index[2]);\n\t\t\t\tc.z = As<Short4>(UnpackLow(c.z, *Pointer<Short4>(buffer + 4 * index[3])));\n\t\t\t\tc.y = c.x;\n\t\t\t\tc.x = UnpackLow(As<Int2>(c.x), As<Int2>(c.z));\n\t\t\t\tc.y = UnpackHigh(As<Int2>(c.y), As<Int2>(c.z));\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tc.x = Insert(c.x, Pointer<Short>(buffer)[index[0]], 0);\n\t\t\t\tc.x = Insert(c.x, Pointer<Short>(buffer)[index[1]], 1);\n\t\t\t\tc.x = Insert(c.x, Pointer<Short>(buffer)[index[2]], 2);\n\t\t\t\tc.x = Insert(c.x, Pointer<Short>(buffer)[index[3]], 3);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tASSERT(false);\n\t\t}\n\t}\n\telse if(state.textureFormat == VK_FORMAT_A2B10G10R10_UNORM_PACK32)\n\t{\n\t\tInt4 cc;\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[0]], 0);\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[1]], 1);\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[2]], 2);\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[3]], 3);\n\n\t\tc = a2b10g10r10Unpack(cc);\n\t}\n\telse if(state.textureFormat == VK_FORMAT_A2R10G10B10_UNORM_PACK32)\n\t{\n\t\tInt4 cc;\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[0]], 0);\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[1]], 1);\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[2]], 2);\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[3]], 3);\n\n\t\tc = a2r10g10b10Unpack(cc);\n\t}\n\telse if(state.textureFormat == VK_FORMAT_A2B10G10R10_UINT_PACK32)\n\t{\n\t\tInt4 cc;\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[0]], 0);\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[1]], 1);\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[2]], 2);\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[3]], 3);\n\n\t\tc.x = Short4((cc & Int4(0x3FF)));\n\t\tc.y = Short4(((cc >> 10) & Int4(0x3FF)));\n\t\tc.z = Short4(((cc >> 20) & Int4(0x3FF)));\n\t\tc.w = Short4(((cc >> 30) & Int4(0x3)));\n\t}\n\telse if(state.textureFormat == VK_FORMAT_A2R10G10B10_UINT_PACK32)\n\t{\n\t\tInt4 cc;\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[0]], 0);\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[1]], 1);\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[2]], 2);\n\t\tcc = Insert(cc, Pointer<Int>(buffer)[index[3]], 3);\n\n\t\tc.z = Short4((cc & Int4(0x3FF)));\n\t\tc.y = Short4(((cc >> 10) & Int4(0x3FF)));\n\t\tc.x = Short4(((cc >> 20) & Int4(0x3FF)));\n\t\tc.w = Short4(((cc >> 30) & Int4(0x3)));\n\t}\n\telse\n\t\tASSERT(false);\n\n\tif(state.textureFormat.isSRGBformat())\n\t{\n\t\tfor(int i = 0; i < textureComponentCount(); i++)\n\t\t{\n\t\t\tif(isRGBComponent(i))\n\t\t\t{\n\t\t\t\t\/\/ The current table-based sRGB conversion requires 0xFF00 to represent 1.0.\n\t\t\t\tASSERT(state.textureFormat.has8bitTextureComponents());\n\n\t\t\t\tsRGBtoLinearFF00(c[i]);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn c;\n}\n\nVector4s SamplerCore::sampleTexel(Short4 &uuuu, Short4 &vvvv, Short4 &wwww, Vector4f &offset, Pointer<Byte> &mipmap, const Short4 &cubeArrayId, const Int4 &sampleId, Pointer<Byte> buffer, SamplerFunction function)\n{\n\tVector4s c;\n\n\tUInt index[4];\n\tcomputeIndices(index, uuuu, vvvv, wwww, offset, mipmap, cubeArrayId, sampleId, function);\n\n\tif(isYcbcrFormat())\n\t{\n\t\t\/\/ Pointers to the planes of YCbCr images are stored in consecutive mipmap levels.\n\t\tPointer<Byte> bufferY = buffer;                                                                         \/\/ *Pointer<Pointer<Byte>>(mipmap + 0 * sizeof(Mipmap) + OFFSET(Mipmap, buffer));\n\t\tPointer<Byte> bufferU = *Pointer<Pointer<Byte>>(mipmap + 1 * sizeof(Mipmap) + OFFSET(Mipmap, buffer));  \/\/ U\/V for 2-plane interleaved formats.\n\t\tPointer<Byte> bufferV = *Pointer<Pointer<Byte>>(mipmap + 2 * sizeof(Mipmap) + OFFSET(Mipmap, buffer));\n\n\t\t\/\/ Luminance\n\t\tInt c0 = Int(bufferY[index[0]]);\n\t\tInt c1 = Int(bufferY[index[1]]);\n\t\tInt c2 = Int(bufferY[index[2]]);\n\t\tInt c3 = Int(bufferY[index[3]]);\n\t\tc0 = c0 | (c1 << 8) | (c2 << 16) | (c3 << 24);\n\t\tUShort4 Y = As<UShort4>(Unpack(As<Byte4>(c0)));\n\n\t\tUShort4 Cb, Cr;\n\n\t\t\/\/ Chroma\n\t\t{\n\t\t\tcomputeIndices(index, uuuu, vvvv, wwww, offset, mipmap + sizeof(Mipmap), cubeArrayId, sampleId, function);\n\t\t\tUShort4 U, V;\n\n\t\t\tif(state.textureFormat == VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM)\n\t\t\t{\n\t\t\t\tc0 = Int(bufferU[index[0]]);\n\t\t\t\tc1 = Int(bufferU[index[1]]);\n\t\t\t\tc2 = Int(bufferU[index[2]]);\n\t\t\t\tc3 = Int(bufferU[index[3]]);\n\t\t\t\tc0 = c0 | (c1 << 8) | (c2 << 16) | (c3 << 24);\n\t\t\t\tU = As<UShort4>(Unpack(As<Byte4>(c0)));\n\n\t\t\t\tc0 = Int(bufferV[index[0]]);\n\t\t\t\tc1 = Int(bufferV[index[1]]);\n\t\t\t\tc2 = Int(bufferV[index[2]]);\n\t\t\t\tc3 = Int(bufferV[index[3]]);\n\t\t\t\tc0 = c0 | (c1 << 8) | (c2 << 16) | (c3 << 24);\n\t\t\t\tV = As<UShort4>(Unpack(As<Byte4>(c0)));\n\t\t\t}\n\t\t\telse if(state.textureFormat == VK_FORMAT_G8_B8R8_2PLANE_420_UNORM)\n\t\t\t{\n\t\t\t\tShort4 UV;\n\t\t\t\tUV = Insert(UV, Pointer<Short>(bufferU)[index[0]], 0);  \/\/ TODO: Insert(UShort4, UShort)\n\t\t\t\tUV = Insert(UV, Pointer<Short>(bufferU)[index[1]], 1);\n\t\t\t\tUV = Insert(UV, Pointer<Short>(bufferU)[index[2]], 2);\n\t\t\t\tUV = Insert(UV, Pointer<Short>(bufferU)[index[3]], 3);\n\t\t\t\tU = (UV & Short4(0x00FFu)) | (UV << 8);\n\t\t\t\tV = (UV & Short4(0xFF00u)) | As<Short4>(As<UShort4>(UV) >> 8);\n\t\t\t}\n\t\t\telse\n\t\t\t\tUNSUPPORTED(\"state.textureFormat %d\", (int)state.textureFormat);\n\n\t\t\tif(!state.swappedChroma)\n\t\t\t{\n\t\t\t\tCb = U;\n\t\t\t\tCr = V;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCb = V;\n\t\t\t\tCr = U;\n\t\t\t}\n\t\t}\n\n\t\tif(state.ycbcrModel == VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY)\n\t\t{\n\t\t\t\/\/ YCbCr formats are treated as signed 15-bit.\n\t\t\tc.x = Cr >> 1;\n\t\t\tc.y = Y >> 1;\n\t\t\tc.z = Cb >> 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Scaling and bias for studio-swing range: Y = [16 .. 235], U\/V = [16 .. 240]\n\t\t\t\/\/ Scale down by 0x0101 to normalize the 8.8 samples, and up by 0x7FFF for signed 15-bit output.\n\t\t\tfloat yOffset = static_cast<float>(state.studioSwing ? 16 * 0x0101 : 0);\n\t\t\tfloat uvOffset = static_cast<float>(128 * 0x0101);\n\t\t\tfloat yFactor = static_cast<float>(0x7FFF) \/ static_cast<float>(state.studioSwing ? 219 * 0x0101 : 255 * 0x0101);\n\t\t\tfloat uvFactor = static_cast<float>(0x7FFF) \/ static_cast<float>(state.studioSwing ? 224 * 0x0101 : 255 * 0x0101);\n\n\t\t\tFloat4 y = (Float4(Y) - Float4(yOffset)) * Float4(yFactor);\n\t\t\tFloat4 u = (Float4(Cb) - Float4(uvOffset)) * Float4(uvFactor);\n\t\t\tFloat4 v = (Float4(Cr) - Float4(uvOffset)) * Float4(uvFactor);\n\n\t\t\tif(state.ycbcrModel == VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY)\n\t\t\t{\n\t\t\t\tc.x = Short4(v);\n\t\t\t\tc.y = Short4(y);\n\t\t\t\tc.z = Short4(u);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ Generic YCbCr to RGB transformation:\n\t\t\t\t\/\/ R = Y                               +           2 * (1 - Kr) * Cr\n\t\t\t\t\/\/ G = Y - 2 * Kb * (1 - Kb) \/ Kg * Cb - 2 * Kr * (1 - Kr) \/ Kg * Cr\n\t\t\t\t\/\/ B = Y +           2 * (1 - Kb) * Cb\n\n\t\t\t\tfloat Kb = 0.114f;\n\t\t\t\tfloat Kr = 0.299f;\n\n\t\t\t\tswitch(state.ycbcrModel)\n\t\t\t\t{\n\t\t\t\t\tcase VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709:\n\t\t\t\t\t\tKb = 0.0722f;\n\t\t\t\t\t\tKr = 0.2126f;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601:\n\t\t\t\t\t\tKb = 0.114f;\n\t\t\t\t\t\tKr = 0.299f;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020:\n\t\t\t\t\t\tKb = 0.0593f;\n\t\t\t\t\t\tKr = 0.2627f;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tUNSUPPORTED(\"ycbcrModel %d\", int(state.ycbcrModel));\n\t\t\t\t}\n\n\t\t\t\tconst float Kg = 1.0f - Kr - Kb;\n\n\t\t\t\tconst float Rr = 2 * (1 - Kr);\n\t\t\t\tconst float Gb = -2 * Kb * (1 - Kb) \/ Kg;\n\t\t\t\tconst float Gr = -2 * Kr * (1 - Kr) \/ Kg;\n\t\t\t\tconst float Bb = 2 * (1 - Kb);\n\n\t\t\t\tFloat4 r = y + Float4(Rr) * v;\n\t\t\t\tFloat4 g = y + Float4(Gb) * u + Float4(Gr) * v;\n\t\t\t\tFloat4 b = y + Float4(Bb) * u;\n\n\t\t\t\tc.x = Short4(r);\n\t\t\t\tc.y = Short4(g);\n\t\t\t\tc.z = Short4(b);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn sampleTexel(index, buffer);\n\t}\n\n\treturn c;\n}\n\nVector4f SamplerCore::sampleTexel(Int4 &uuuu, Int4 &vvvv, Int4 &wwww, Float4 &z, Pointer<Byte> &mipmap, const Int4 &cubeArrayId, const Int4 &sampleId, Pointer<Byte> buffer, SamplerFunction function)\n{\n\tInt4 valid;\n\n\tif(borderModeActive())\n\t{\n\t\t\/\/ Valid texels have positive coordinates.\n\t\tInt4 negative = Int4(0);\n\t\tif(state.addressingModeU == ADDRESSING_BORDER) negative |= uuuu;\n\t\tif(state.addressingModeV == ADDRESSING_BORDER) negative |= vvvv;\n\t\tif(state.addressingModeW == ADDRESSING_BORDER) negative |= wwww;\n\t\tvalid = CmpNLT(negative, Int4(0));\n\t}\n\n\tUInt index[4];\n\tUInt4 t0, t1, t2, t3;\n\tcomputeIndices(index, uuuu, vvvv, wwww, valid, mipmap, cubeArrayId, sampleId, function);\n\n\tVector4f c;\n\n\tif(hasFloatTexture() || has32bitIntegerTextureComponents())\n\t{\n\t\tswitch(state.textureFormat)\n\t\t{\n\t\t\tcase VK_FORMAT_R16_SFLOAT:\n\t\t\t\tt0 = Int4(*Pointer<UShort4>(buffer + index[0] * 2));\n\t\t\t\tt1 = Int4(*Pointer<UShort4>(buffer + index[1] * 2));\n\t\t\t\tt2 = Int4(*Pointer<UShort4>(buffer + index[2] * 2));\n\t\t\t\tt3 = Int4(*Pointer<UShort4>(buffer + index[3] * 2));\n\n\t\t\t\tc.x.x = Extract(As<Float4>(halfToFloatBits(t0)), 0);\n\t\t\t\tc.x.y = Extract(As<Float4>(halfToFloatBits(t1)), 0);\n\t\t\t\tc.x.z = Extract(As<Float4>(halfToFloatBits(t2)), 0);\n\t\t\t\tc.x.w = Extract(As<Float4>(halfToFloatBits(t3)), 0);\n\t\t\t\tbreak;\n\t\t\tcase VK_FORMAT_R16G16_SFLOAT:\n\t\t\t\tt0 = Int4(*Pointer<UShort4>(buffer + index[0] * 4));\n\t\t\t\tt1 = Int4(*Pointer<UShort4>(buffer + index[1] * 4));\n\t\t\t\tt2 = Int4(*Pointer<UShort4>(buffer + index[2] * 4));\n\t\t\t\tt3 = Int4(*Pointer<UShort4>(buffer + index[3] * 4));\n\n\t\t\t\t\/\/ FIXME: shuffles\n\t\t\t\tc.x = As<Float4>(halfToFloatBits(t0));\n\t\t\t\tc.y = As<Float4>(halfToFloatBits(t1));\n\t\t\t\tc.z = As<Float4>(halfToFloatBits(t2));\n\t\t\t\tc.w = As<Float4>(halfToFloatBits(t3));\n\t\t\t\ttranspose4x4(c.x, c.y, c.z, c.w);\n\t\t\t\tbreak;\n\t\t\tcase VK_FORMAT_R16G16B16A16_SFLOAT:\n\t\t\t\tt0 = Int4(*Pointer<UShort4>(buffer + index[0] * 8));\n\t\t\t\tt1 = Int4(*Pointer<UShort4>(buffer + index[1] * 8));\n\t\t\t\tt2 = Int4(*Pointer<UShort4>(buffer + index[2] * 8));\n\t\t\t\tt3 = Int4(*Pointer<UShort4>(buffer + index[3] * 8));\n\n\t\t\t\tc.x = As<Float4>(halfToFloatBits(t0));\n\t\t\t\tc.y = As<Float4>(halfToFloatBits(t1));\n\t\t\t\tc.z = As<Float4>(halfToFloatBits(t2));\n\t\t\t\tc.w = As<Float4>(halfToFloatBits(t3));\n\t\t\t\ttranspose4x4(c.x, c.y, c.z, c.w);\n\t\t\t\tbreak;\n\t\t\tcase VK_FORMAT_R32_SFLOAT:\n\t\t\tcase VK_FORMAT_R32_SINT:\n\t\t\tcase VK_FORMAT_R32_UINT:\n\t\t\tcase VK_FORMAT_D32_SFLOAT:\n\t\t\t\t\/\/ FIXME: Optimal shuffling?\n\t\t\t\tc.x.x = *Pointer<Float>(buffer + index[0] * 4);\n\t\t\t\tc.x.y = *Pointer<Float>(buffer + index[1] * 4);\n\t\t\t\tc.x.z = *Pointer<Float>(buffer + index[2] * 4);\n\t\t\t\tc.x.w = *Pointer<Float>(buffer + index[3] * 4);\n\t\t\t\tbreak;\n\t\t\tcase VK_FORMAT_R32G32_SFLOAT:\n\t\t\tcase VK_FORMAT_R32G32_SINT:\n\t\t\tcase VK_FORMAT_R32G32_UINT:\n\t\t\t\t\/\/ FIXME: Optimal shuffling?\n\t\t\t\tc.x.xy = *Pointer<Float4>(buffer + index[0] * 8);\n\t\t\t\tc.x.zw = *Pointer<Float4>(buffer + index[1] * 8 - 8);\n\t\t\t\tc.z.xy = *Pointer<Float4>(buffer + index[2] * 8);\n\t\t\t\tc.z.zw = *Pointer<Float4>(buffer + index[3] * 8 - 8);\n\t\t\t\tc.y = c.x;\n\t\t\t\tc.x = Float4(c.x.xz, c.z.xz);\n\t\t\t\tc.y = Float4(c.y.yw, c.z.yw);\n\t\t\t\tbreak;\n\t\t\tcase VK_FORMAT_R32G32B32_SFLOAT:\n\t\t\tcase VK_FORMAT_R32G32B32_SINT:\n\t\t\tcase VK_FORMAT_R32G32B32_UINT:\n\t\t\t\tc.x = *Pointer<Float4>(buffer + index[0] * 16, 16);\n\t\t\t\tc.y = *Pointer<Float4>(buffer + index[1] * 16, 16);\n\t\t\t\tc.z = *Pointer<Float4>(buffer + index[2] * 16, 16);\n\t\t\t\tc.w = *Pointer<Float4>(buffer + index[3] * 16, 16);\n\t\t\t\ttranspose4x3(c.x, c.y, c.z, c.w);\n\t\t\t\tbreak;\n\t\t\tcase VK_FORMAT_R32G32B32A32_SFLOAT:\n\t\t\tcase VK_FORMAT_R32G32B32A32_SINT:\n\t\t\tcase VK_FORMAT_R32G32B32A32_UINT:\n\t\t\t\tc.x = *Pointer<Float4>(buffer + index[0] * 16, 16);\n\t\t\t\tc.y = *Pointer<Float4>(buffer + index[1] * 16, 16);\n\t\t\t\tc.z = *Pointer<Float4>(buffer + index[2] * 16, 16);\n\t\t\t\tc.w = *Pointer<Float4>(buffer + index[3] * 16, 16);\n\t\t\t\ttranspose4x4(c.x, c.y, c.z, c.w);\n\t\t\t\tbreak;\n\t\t\tcase VK_FORMAT_E5B9G9R9_UFLOAT_PACK32:\n\t\t\t{\n\t\t\t\tFloat4 t;  \/\/ TODO: add Insert(UInt4, RValue<UInt>)\n\t\t\t\tt.x = *Pointer<Float>(buffer + index[0] * 4);\n\t\t\t\tt.y = *Pointer<Float>(buffer + index[1] * 4);\n\t\t\t\tt.z = *Pointer<Float>(buffer + index[2] * 4);\n\t\t\t\tt.w = *Pointer<Float>(buffer + index[3] * 4);\n\t\t\t\tt0 = As<UInt4>(t);\n\t\t\t\tc.w = Float4(UInt4(1) << ((t0 >> 27) & UInt4(0x1F))) * Float4(1.0f \/ (1 << 24));\n\t\t\t\tc.x = Float4(t0 & UInt4(0x1FF)) * c.w;\n\t\t\t\tc.y = Float4((t0 >> 9) & UInt4(0x1FF)) * c.w;\n\t\t\t\tc.z = Float4((t0 >> 18) & UInt4(0x1FF)) * c.w;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase VK_FORMAT_B10G11R11_UFLOAT_PACK32:\n\t\t\t{\n\t\t\t\tFloat4 t;  \/\/ TODO: add Insert(UInt4, RValue<UInt>)\n\t\t\t\tt.x = *Pointer<Float>(buffer + index[0] * 4);\n\t\t\t\tt.y = *Pointer<Float>(buffer + index[1] * 4);\n\t\t\t\tt.z = *Pointer<Float>(buffer + index[2] * 4);\n\t\t\t\tt.w = *Pointer<Float>(buffer + index[3] * 4);\n\t\t\t\tt0 = As<UInt4>(t);\n\t\t\t\tc.x = As<Float4>(halfToFloatBits((t0 << 4) & UInt4(0x7FF0)));\n\t\t\t\tc.y = As<Float4>(halfToFloatBits((t0 >> 7) & UInt4(0x7FF0)));\n\t\t\t\tc.z = As<Float4>(halfToFloatBits((t0 >> 17) & UInt4(0x7FE0)));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tUNSUPPORTED(\"Format %d\", VkFormat(state.textureFormat));\n\t\t}\n\t}\n\telse\n\t{\n\t\tASSERT(!isYcbcrFormat());\n\n\t\tVector4s cs = sampleTexel(index, buffer);\n\n\t\tbool isInteger = state.textureFormat.isUnnormalizedInteger();\n\t\tint componentCount = textureComponentCount();\n\t\tfor(int n = 0; n < componentCount; n++)\n\t\t{\n\t\t\tif(hasUnsignedTextureComponent(n))\n\t\t\t{\n\t\t\t\tif(isInteger)\n\t\t\t\t{\n\t\t\t\t\tc[n] = As<Float4>(Int4(As<UShort4>(cs[n])));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tc[n] = Float4(As<UShort4>(cs[n]));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(isInteger)\n\t\t\t\t{\n\t\t\t\t\tc[n] = As<Float4>(Int4(cs[n]));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tc[n] = Float4(cs[n]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif(state.compareEnable)\n\t{\n\t\tFloat4 ref = z;\n\n\t\tif(!hasFloatTexture())\n\t\t{\n\t\t\t\/\/ D16_UNORM: clamp reference, normalize texel value\n\t\t\tref = Min(Max(ref, Float4(0.0f)), Float4(1.0f));\n\t\t\tc.x = c.x * Float4(1.0f \/ 0xFFFF);\n\t\t}\n\n\t\tInt4 boolean;\n\n\t\tswitch(state.compareOp)\n\t\t{\n\t\t\tcase VK_COMPARE_OP_LESS_OR_EQUAL: boolean = CmpLE(ref, c.x); break;\n\t\t\tcase VK_COMPARE_OP_GREATER_OR_EQUAL: boolean = CmpNLT(ref, c.x); break;\n\t\t\tcase VK_COMPARE_OP_LESS: boolean = CmpLT(ref, c.x); break;\n\t\t\tcase VK_COMPARE_OP_GREATER: boolean = CmpNLE(ref, c.x); break;\n\t\t\tcase VK_COMPARE_OP_EQUAL: boolean = CmpEQ(ref, c.x); break;\n\t\t\tcase VK_COMPARE_OP_NOT_EQUAL: boolean = CmpNEQ(ref, c.x); break;\n\t\t\tcase VK_COMPARE_OP_ALWAYS: boolean = Int4(-1); break;\n\t\t\tcase VK_COMPARE_OP_NEVER: boolean = Int4(0); break;\n\t\t\tdefault: ASSERT(false);\n\t\t}\n\n\t\tc.x = As<Float4>(boolean & As<Int4>(Float4(1.0f)));\n\t\tc.y = Float4(0.0f);\n\t\tc.z = Float4(0.0f);\n\t\tc.w = Float4(1.0f);\n\t}\n\n\tif(borderModeActive())\n\t{\n\t\tc = replaceBorderTexel(c, valid);\n\t}\n\n\treturn c;\n}\n\nVector4f SamplerCore::replaceBorderTexel(const Vector4f &c, Int4 valid)\n{\n\tInt4 borderRGB;\n\tInt4 borderA;\n\n\tbool scaled = !hasFloatTexture() && !hasUnnormalizedIntegerTexture() && !state.compareEnable;\n\tbool sign = !hasUnsignedTextureComponent(0);\n\tInt4 float_one = scaled ? As<Int4>(Float4(static_cast<float>(sign ? 0x7FFF : 0xFFFF))) : As<Int4>(Float4(1.0f));\n\n\tswitch(state.border)\n\t{\n\t\tcase VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK:\n\t\tcase VK_BORDER_COLOR_INT_TRANSPARENT_BLACK:\n\t\t\tborderRGB = Int4(0);\n\t\t\tborderA = Int4(0);\n\t\t\tbreak;\n\t\tcase VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK:\n\t\t\tborderRGB = Int4(0);\n\t\t\tborderA = float_one;\n\t\t\tbreak;\n\t\tcase VK_BORDER_COLOR_INT_OPAQUE_BLACK:\n\t\t\tborderRGB = Int4(0);\n\t\t\tborderA = Int4(1);\n\t\t\tbreak;\n\t\tcase VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE:\n\t\t\tborderRGB = float_one;\n\t\t\tborderA = float_one;\n\t\t\tbreak;\n\t\tcase VK_BORDER_COLOR_INT_OPAQUE_WHITE:\n\t\t\tborderRGB = Int4(1);\n\t\t\tborderA = Int4(1);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tUNSUPPORTED(\"sint\/uint\/sfloat border: %u\", state.border);\n\t}\n\n\tVector4f out;\n\tout.x = As<Float4>((valid & As<Int4>(c.x)) | (~valid & borderRGB));\n\tout.y = As<Float4>((valid & As<Int4>(c.y)) | (~valid & borderRGB));\n\tout.z = As<Float4>((valid & As<Int4>(c.z)) | (~valid & borderRGB));\n\tout.w = As<Float4>((valid & As<Int4>(c.w)) | (~valid & borderA));\n\n\treturn out;\n}\n\nvoid SamplerCore::selectMipmap(const Pointer<Byte> &texture, Pointer<Byte> &mipmap, Pointer<Byte> &buffer, const Float &lod, bool secondLOD)\n{\n\tPointer<Byte> mipmap0 = texture + OFFSET(Texture, mipmap[0]);\n\n\tif(state.mipmapFilter == MIPMAP_NONE)\n\t{\n\t\tmipmap = mipmap0;\n\t}\n\telse\n\t{\n\t\tInt ilod;\n\n\t\tif(state.mipmapFilter == MIPMAP_POINT)\n\t\t{\n\t\t\t\/\/ TODO: Preferred formula is ceil(lod + 0.5) - 1\n\t\t\tilod = RoundInt(lod);\n\t\t}\n\t\telse  \/\/ MIPMAP_LINEAR\n\t\t{\n\t\t\tilod = Int(lod);\n\t\t}\n\n\t\tmipmap = mipmap0 + ilod * sizeof(Mipmap) + secondLOD * sizeof(Mipmap);\n\t}\n\n\tbuffer = *Pointer<Pointer<Byte>>(mipmap + OFFSET(Mipmap, buffer));\n}\n\nInt4 SamplerCore::computeFilterOffset(Float &lod)\n{\n\tif(state.textureFilter == FILTER_POINT)\n\t{\n\t\treturn Int4(0);\n\t}\n\telse if(state.textureFilter == FILTER_MIN_LINEAR_MAG_POINT)\n\t{\n\t\treturn CmpNLE(Float4(lod), Float4(0.0f));\n\t}\n\telse if(state.textureFilter == FILTER_MIN_POINT_MAG_LINEAR)\n\t{\n\t\treturn CmpLE(Float4(lod), Float4(0.0f));\n\t}\n\n\treturn Int4(~0);\n}\n\nShort4 SamplerCore::address(const Float4 &uw, AddressingMode addressingMode, Pointer<Byte> &mipmap)\n{\n\tif(addressingMode == ADDRESSING_UNUSED)\n\t{\n\t\treturn Short4();\n\t}\n\telse if(addressingMode == ADDRESSING_LAYER)\n\t{\n\t\tInt4 dim = *Pointer<Int4>(mipmap + OFFSET(Mipmap, depth));\n\t\t\/\/ For cube maps, the layer argument is per cube, each of which has 6 layers\n\t\tif(state.textureType == VK_IMAGE_VIEW_TYPE_CUBE_ARRAY)\n\t\t{\n\t\t\tdim = dim \/ Int4(6);\n\t\t}\n\n\t\treturn Short4(Min(Max(RoundInt(uw), Int4(0)), dim - Int4(1)));\n\t}\n\telse if(addressingMode == ADDRESSING_CLAMP || addressingMode == ADDRESSING_BORDER)\n\t{\n\t\tFloat4 clamp = Min(Max(uw, Float4(0.0f)), Float4(65535.0f \/ 65536.0f));\n\n\t\treturn Short4(Int4(clamp * Float4(1 << 16)));\n\t}\n\telse if(addressingMode == ADDRESSING_MIRROR)\n\t{\n\t\tInt4 convert = Int4(uw * Float4(1 << 16));\n\t\tInt4 mirror = (convert << 15) >> 31;\n\n\t\tconvert ^= mirror;\n\n\t\treturn Short4(convert);\n\t}\n\telse if(addressingMode == ADDRESSING_MIRRORONCE)\n\t{\n\t\t\/\/ Absolute value\n\t\tInt4 convert = Int4(Abs(uw * Float4(1 << 16)));\n\n\t\t\/\/ Clamp\n\t\tconvert -= Int4(0x00008000, 0x00008000, 0x00008000, 0x00008000);\n\t\tconvert = As<Int4>(PackSigned(convert, convert));\n\n\t\treturn As<Short4>(Int2(convert)) + Short4(0x8000u);\n\t}\n\telse  \/\/ Wrap\n\t{\n\t\treturn Short4(Int4(uw * Float4(1 << 16)));\n\t}\n}\n\n\/\/ TODO: Eliminate when the gather + mirror addressing case is handled by mirroring the footprint.\nstatic Int4 mirror(Int4 n)\n{\n\tauto positive = CmpNLT(n, Int4(0));\n\treturn (positive & n) | (~positive & (-(Int4(1) + n)));\n}\n\nstatic Int4 mod(Int4 n, Int4 d)\n{\n\tauto x = n % d;\n\tauto positive = CmpNLT(x, Int4(0));\n\treturn (positive & x) | (~positive & (x + d));\n}\n\nvoid SamplerCore::address(const Float4 &uvw, Int4 &xyz0, Int4 &xyz1, Float4 &f, Pointer<Byte> &mipmap, Float4 &texOffset, Int4 &filter, int whd, AddressingMode addressingMode, SamplerFunction function)\n{\n\tif(addressingMode == ADDRESSING_UNUSED)\n\t{\n\t\treturn;\n\t}\n\n\tInt4 dim = *Pointer<Int4>(mipmap + whd, 16);\n\tInt4 maxXYZ = dim - Int4(1);\n\n\tif(function == Fetch)\n\t{\n\t\txyz0 = Min(Max(((function.offset != 0) && (addressingMode != ADDRESSING_LAYER)) ? As<Int4>(uvw) + As<Int4>(texOffset) : As<Int4>(uvw), Int4(0)), maxXYZ);\n\t}\n\telse if(addressingMode == ADDRESSING_LAYER)  \/\/ Note: Offset does not apply to array layers\n\t{\n\t\t\/\/ For cube maps, the layer argument is per cube, each of which has 6 layers\n\t\tif(state.textureType == VK_IMAGE_VIEW_TYPE_CUBE_ARRAY)\n\t\t{\n\t\t\tdim = dim \/ Int4(6);\n\t\t}\n\n\t\txyz0 = Min(Max(RoundInt(uvw), Int4(0)), dim - Int4(1));\n\t}\n\telse if(addressingMode == ADDRESSING_CUBEFACE)\n\t{\n\t\txyz0 = As<Int4>(uvw);\n\t}\n\telse\n\t{\n\t\tconst int halfBits = 0x3EFFFFFF;  \/\/ Value just under 0.5f\n\t\tconst int oneBits = 0x3F7FFFFF;   \/\/ Value just under 1.0f\n\t\tconst int twoBits = 0x3FFFFFFF;   \/\/ Value just under 2.0f\n\n\t\tbool pointFilter = state.textureFilter == FILTER_POINT ||\n\t\t                   state.textureFilter == FILTER_MIN_POINT_MAG_LINEAR ||\n\t\t                   state.textureFilter == FILTER_MIN_LINEAR_MAG_POINT;\n\n\t\tFloat4 coord = uvw;\n\n\t\tif(state.unnormalizedCoordinates)\n\t\t{\n\t\t\tswitch(addressingMode)\n\t\t\t{\n\t\t\t\tcase ADDRESSING_CLAMP:\n\t\t\t\t\tcoord = Min(Max(coord, Float4(0.0f)), Float4(dim) * As<Float4>(Int4(oneBits)));\n\t\t\t\t\tbreak;\n\t\t\t\tcase ADDRESSING_BORDER:\n\t\t\t\t\t\/\/ Don't map to a valid range here.\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t\/\/ If unnormalizedCoordinates is VK_TRUE, addressModeU and addressModeV must each be\n\t\t\t\t\t\/\/ either VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE or VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER\n\t\t\t\t\tUNREACHABLE(\"addressingMode %d\", int(addressingMode));\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse if(state.textureFilter == FILTER_GATHER && addressingMode == ADDRESSING_MIRROR)\n\t\t{\n\t\t\t\/\/ Gather requires the 'footprint' of the texels from which a component is taken, to also mirror around.\n\t\t\t\/\/ Therefore we can't just compute one texel's location and find the other ones at +1 offsets from it.\n\t\t\t\/\/ Here we handle that case separately by doing the mirroring per texel coordinate.\n\t\t\t\/\/ TODO: Mirror the footprint by adjusting the sign of the 0.5f and 1 offsets.\n\n\t\t\tcoord = coord * Float4(dim);\n\t\t\tcoord -= Float4(0.5f);\n\t\t\tFloat4 floor = Floor(coord);\n\t\t\txyz0 = Int4(floor);\n\n\t\t\tif(function.offset != 0)\n\t\t\t{\n\t\t\t\txyz0 += As<Int4>(texOffset);\n\t\t\t}\n\n\t\t\txyz1 = xyz0 + Int4(1);\n\n\t\t\txyz0 = (maxXYZ)-mirror(mod(xyz0, Int4(2) * dim) - dim);\n\t\t\txyz1 = (maxXYZ)-mirror(mod(xyz1, Int4(2) * dim) - dim);\n\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(function.offset == 0)\n\t\t\t{\n\t\t\t\tswitch(addressingMode)\n\t\t\t\t{\n\t\t\t\t\tcase ADDRESSING_CLAMP:\n\t\t\t\t\tcase ADDRESSING_SEAMLESS:\n\t\t\t\t\t\t\/\/ Linear filtering of cube doesn't require clamping because the coordinates\n\t\t\t\t\t\t\/\/ are already in [0, 1] range and numerical imprecision is tolerated.\n\t\t\t\t\t\tif(addressingMode != ADDRESSING_SEAMLESS || pointFilter)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tFloat4 one = As<Float4>(Int4(oneBits));\n\t\t\t\t\t\t\tcoord = Min(Max(coord, Float4(0.0f)), one);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase ADDRESSING_MIRROR:\n\t\t\t\t\t{\n\t\t\t\t\t\tFloat4 half = As<Float4>(Int4(halfBits));\n\t\t\t\t\t\tFloat4 one = As<Float4>(Int4(oneBits));\n\t\t\t\t\t\tFloat4 two = As<Float4>(Int4(twoBits));\n\t\t\t\t\t\tcoord = one - Abs(two * Frac(coord * half) - one);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase ADDRESSING_MIRRORONCE:\n\t\t\t\t\t{\n\t\t\t\t\t\tFloat4 half = As<Float4>(Int4(halfBits));\n\t\t\t\t\t\tFloat4 one = As<Float4>(Int4(oneBits));\n\t\t\t\t\t\tFloat4 two = As<Float4>(Int4(twoBits));\n\t\t\t\t\t\tcoord = one - Abs(two * Frac(Min(Max(coord, -one), two) * half) - one);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase ADDRESSING_BORDER:\n\t\t\t\t\t\t\/\/ Don't map to a valid range here.\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:  \/\/ Wrap\n\t\t\t\t\t\tcoord = Frac(coord);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcoord = coord * Float4(dim);\n\t\t}\n\n\t\tif(state.textureFilter == FILTER_POINT)\n\t\t{\n\t\t\tif(addressingMode == ADDRESSING_BORDER || function.offset != 0)\n\t\t\t{\n\t\t\t\txyz0 = Int4(Floor(coord));\n\t\t\t}\n\t\t\telse  \/\/ Can't have negative coordinates, so floor() is redundant when casting to int.\n\t\t\t{\n\t\t\t\txyz0 = Int4(coord);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(state.textureFilter == FILTER_MIN_POINT_MAG_LINEAR ||\n\t\t\t   state.textureFilter == FILTER_MIN_LINEAR_MAG_POINT)\n\t\t\t{\n\t\t\t\tcoord -= As<Float4>(As<Int4>(Float4(0.5f)) & filter);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcoord -= Float4(0.5f);\n\t\t\t}\n\n\t\t\tFloat4 floor = Floor(coord);\n\t\t\txyz0 = Int4(floor);\n\t\t\tf = coord - floor;\n\t\t}\n\n\t\tif(function.offset != 0)\n\t\t{\n\t\t\txyz0 += As<Int4>(texOffset);\n\t\t}\n\n\t\tif(addressingMode == ADDRESSING_SEAMLESS)  \/\/ Adjust for border.\n\t\t{\n\t\t\txyz0 += Int4(1);\n\t\t}\n\n\t\txyz1 = xyz0 - filter;  \/\/ Increment\n\n\t\tif(addressingMode == ADDRESSING_BORDER)\n\t\t{\n\t\t\t\/\/ Replace the coordinates with -1 if they're out of range.\n\t\t\tInt4 border0 = CmpLT(xyz0, Int4(0)) | CmpNLT(xyz0, dim);\n\t\t\tInt4 border1 = CmpLT(xyz1, Int4(0)) | CmpNLT(xyz1, dim);\n\t\t\txyz0 |= border0;\n\t\t\txyz1 |= border1;\n\t\t}\n\t\telse if(function.offset != 0)\n\t\t{\n\t\t\tswitch(addressingMode)\n\t\t\t{\n\t\t\t\tcase ADDRESSING_SEAMLESS:\n\t\t\t\t\tUNREACHABLE(\"addressingMode %d\", int(addressingMode));  \/\/ Cube sampling doesn't support offset.\n\t\t\t\tcase ADDRESSING_MIRROR:\n\t\t\t\tcase ADDRESSING_MIRRORONCE:\n\t\t\t\t\t\/\/ TODO: Implement ADDRESSING_MIRROR and ADDRESSING_MIRRORONCE.\n\t\t\t\t\t\/\/ Fall through to Clamp.\n\t\t\t\tcase ADDRESSING_CLAMP:\n\t\t\t\t\txyz0 = Min(Max(xyz0, Int4(0)), maxXYZ);\n\t\t\t\t\txyz1 = Min(Max(xyz1, Int4(0)), maxXYZ);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:  \/\/ Wrap\n\t\t\t\t\txyz0 = mod(xyz0, dim);\n\t\t\t\t\txyz1 = mod(xyz1, dim);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse if(state.textureFilter != FILTER_POINT)\n\t\t{\n\t\t\tswitch(addressingMode)\n\t\t\t{\n\t\t\t\tcase ADDRESSING_SEAMLESS:\n\t\t\t\t\tbreak;\n\t\t\t\tcase ADDRESSING_MIRROR:\n\t\t\t\tcase ADDRESSING_MIRRORONCE:\n\t\t\t\tcase ADDRESSING_CLAMP:\n\t\t\t\t\txyz0 = Max(xyz0, Int4(0));\n\t\t\t\t\txyz1 = Min(xyz1, maxXYZ);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:  \/\/ Wrap\n\t\t\t\t{\n\t\t\t\t\tInt4 under = CmpLT(xyz0, Int4(0));\n\t\t\t\t\txyz0 = (under & maxXYZ) | (~under & xyz0);  \/\/ xyz < 0 ? dim - 1 : xyz   \/\/ TODO: IfThenElse()\n\n\t\t\t\t\tInt4 nover = CmpLT(xyz1, dim);\n\t\t\t\t\txyz1 = nover & xyz1;  \/\/ xyz >= dim ? 0 : xyz\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid SamplerCore::convertSigned15(Float4 &cf, Short4 &cs)\n{\n\tcf = Float4(cs) * Float4(1.0f \/ 0x7FFF);\n}\n\nvoid SamplerCore::convertUnsigned16(Float4 &cf, Short4 &cs)\n{\n\tcf = Float4(As<UShort4>(cs)) * Float4(1.0f \/ 0xFFFF);\n}\n\nvoid SamplerCore::sRGBtoLinearFF00(Short4 &c)\n{\n\tc = As<UShort4>(c) >> 8;\n\n\tPointer<Byte> LUT = Pointer<Byte>(constants + OFFSET(Constants, sRGBtoLinearFF_FF00));\n\n\tc = Insert(c, *Pointer<Short>(LUT + 2 * Int(Extract(c, 0))), 0);\n\tc = Insert(c, *Pointer<Short>(LUT + 2 * Int(Extract(c, 1))), 1);\n\tc = Insert(c, *Pointer<Short>(LUT + 2 * Int(Extract(c, 2))), 2);\n\tc = Insert(c, *Pointer<Short>(LUT + 2 * Int(Extract(c, 3))), 3);\n}\n\nbool SamplerCore::hasFloatTexture() const\n{\n\treturn state.textureFormat.isFloatFormat();\n}\n\nbool SamplerCore::hasUnnormalizedIntegerTexture() const\n{\n\treturn state.textureFormat.isUnnormalizedInteger();\n}\n\nbool SamplerCore::hasUnsignedTextureComponent(int component) const\n{\n\treturn state.textureFormat.isUnsignedComponent(component);\n}\n\nint SamplerCore::textureComponentCount() const\n{\n\treturn state.textureFormat.componentCount();\n}\n\nbool SamplerCore::hasThirdCoordinate() const\n{\n\treturn (state.textureType == VK_IMAGE_VIEW_TYPE_3D) ||\n\t       (state.textureType == VK_IMAGE_VIEW_TYPE_2D_ARRAY) ||\n\t       (state.textureType == VK_IMAGE_VIEW_TYPE_1D_ARRAY);  \/\/ Treated as 2D texture with second coordinate 0. TODO(b\/134669567)\n}\n\nbool SamplerCore::has16bitTextureFormat() const\n{\n\treturn state.textureFormat.has16bitTextureFormat();\n}\n\nbool SamplerCore::has8bitTextureComponents() const\n{\n\treturn state.textureFormat.has8bitTextureComponents();\n}\n\nbool SamplerCore::has16bitTextureComponents() const\n{\n\treturn state.textureFormat.has16bitTextureComponents();\n}\n\nbool SamplerCore::has32bitIntegerTextureComponents() const\n{\n\treturn state.textureFormat.has32bitIntegerTextureComponents();\n}\n\nbool SamplerCore::isYcbcrFormat() const\n{\n\treturn state.textureFormat.isYcbcrFormat();\n}\n\nbool SamplerCore::isRGBComponent(int component) const\n{\n\treturn state.textureFormat.isRGBComponent(component);\n}\n\nbool SamplerCore::borderModeActive() const\n{\n\treturn state.addressingModeU == ADDRESSING_BORDER ||\n\t       state.addressingModeV == ADDRESSING_BORDER ||\n\t       state.addressingModeW == ADDRESSING_BORDER;\n}\n\nbool SamplerCore::isCube() const\n{\n\treturn state.textureType == VK_IMAGE_VIEW_TYPE_CUBE ||\n\t       state.textureType == VK_IMAGE_VIEW_TYPE_CUBE_ARRAY;\n}\n\nVkComponentSwizzle SamplerCore::gatherSwizzle() const\n{\n\tswitch(state.gatherComponent)\n\t{\n\t\tcase 0: return state.swizzle.r;\n\t\tcase 1: return state.swizzle.g;\n\t\tcase 2: return state.swizzle.b;\n\t\tcase 3: return state.swizzle.a;\n\t\tdefault:\n\t\t\tUNREACHABLE(\"Invalid component\");\n\t\t\treturn VK_COMPONENT_SWIZZLE_R;\n\t}\n}\n\n}  \/\/ namespace sw\n","avg_line_length":31.1144508671,"max_line_length":281,"alphanum_fraction":0.6313814372,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":638,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"gtest\/gtest.h\"\n\n#include \"..\/pbsqlite\/pbsqlite.h\"\n#include \"person.pb.h\"\n\nusing namespace aa;\n\nTEST(bpsqlite, Base) {\n    Person person;\n    person.set_name(\"Jonh\");\n    Person person2;\n    person2.set_id(2);\n    person2.set_name(\"David\");\n    pbsqlite::Database db(\"example.db\", SQLite::OPEN_CREATE | SQLite::OPEN_READWRITE);\n    db.CreateTableIfNotExists(person, \"id\");\n    db.ReplaceInto(person);\n    db.ReplaceInto(person2);\n\n    std::vector<Person> rs = db.Select<Person>(\"WHERE id>=0\");\n\n    EXPECT_TRUE(rs.size() >= 2);\n    EXPECT_EQ(rs[0].id(), 0);\n    EXPECT_EQ(rs[1].id(), 2);\n    EXPECT_EQ(rs[1].name(), \"David\");\n}\n\n","avg_line_length":23.6296296296,"max_line_length":86,"alphanum_fraction":0.6426332288,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3636,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":17.0,"content":"\/\/\r\n\/\/ GCCHELP.CPP\r\n\/\/ GCC helper functions\r\n\/\/\r\n\/\/ Copyright Microsoft 1998-\r\n\/\/\r\n\r\n\r\n\/\/ PRECOMP\r\n#include \"precomp.h\"\r\n#include \"gcchelp.h\"\r\n\r\nvoid\tT126_GCCAllocateHandleConfirm(ULONG drawingHandle, ULONG handle_range)\r\n{\r\n\tg_WaitingForGCCHandles = FALSE;\r\n\tTRACE_MSG((\"T126_GCCAllocateHandleConfirm drawing handle = %d, range = %d\", drawingHandle, handle_range));\r\n\r\n\tTRACE_MSG((\"GCC Tank 0 has %d GCC handles \", g_GCCPreallocHandles[0].GccHandleCount));\r\n\tTRACE_MSG((\"GCC Tank 1 has %d GCC handles \", g_GCCPreallocHandles[1].GccHandleCount));\r\n\r\n\tULONG gccHandle;\r\n\tif(g_GCCPreallocHandles[g_iGCCHandleIndex].GccHandleCount == 0)\r\n\t{\r\n\t\tTRACE_MSG((\"Using GCC Tank %d \", g_iGCCHandleIndex));\r\n\r\n\t\tg_GCCPreallocHandles[g_iGCCHandleIndex].InitialGCCHandle = drawingHandle;\r\n\t\tg_GCCPreallocHandles[g_iGCCHandleIndex].GccHandleCount = handle_range;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tUINT index = g_iGCCHandleIndex ? 0 : 1;\r\n\t\tTRACE_MSG((\"T126_GCCAllocateHandleConfirm: Using GCC Tank %d that contains %d handles\",\r\n\t\t\t\t\t\t\tindex, g_GCCPreallocHandles[index].GccHandleCount ));\r\n\t\tTRACE_MSG((\"Filling up GCC Tank %d \", index));\r\n\t\tg_GCCPreallocHandles[index].InitialGCCHandle = drawingHandle;\r\n\t\tg_GCCPreallocHandles[index].GccHandleCount = handle_range;\r\n\t}\r\n\r\n\tif(handle_range <= 2)\r\n\t{\r\n\t\tgccHandle = g_GCCPreallocHandles[g_iGCCHandleIndex].InitialGCCHandle + g_GCCPreallocHandles[g_iGCCHandleIndex].GccHandleCount - handle_range;\r\n\t\tg_GCCPreallocHandles[g_iGCCHandleIndex].GccHandleCount = g_GCCPreallocHandles[g_iGCCHandleIndex].GccHandleCount - handle_range;\r\n\r\n\t\t\/\/\r\n\t\t\/\/ Remove the drawing object from the list of objects to send\r\n\t\t\/\/\r\n\t\tT126Obj * pT126Obj = (T126Obj*)g_pListOfObjectsThatRequestedHandles->RemoveTail();\r\n\r\n\t\tif(!pT126Obj)\r\n\t\t{\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tpT126Obj->GotGCCHandle(gccHandle);\r\n\r\n\t}\r\n\telse\r\n\t{\r\n\t\t\r\n\t\tif(handle_range != PREALLOC_GCC_HANDLES)\r\n\t\t{\r\n\r\n\t\t\t\/\/\r\n\t\t\t\/\/ Resend all objects\r\n\t\t\t\/\/\r\n\t\t\tWBPOSITION pos;\r\n\t\t\tWBPOSITION posObj;\r\n\t\t\tWorkspaceObj* pWorkspace;\r\n\t\t\tULONG\tworkspaceHandle;\r\n\t\t\tT126Obj* pObj;\r\n\r\n\t\t\tpos = g_pListOfWorkspaces->GetHeadPosition();\r\n\r\n\t\t\twhile(pos)\r\n\t\t\t{\r\n\t\t\t\tgccHandle = g_GCCPreallocHandles[g_iGCCHandleIndex].InitialGCCHandle + g_GCCPreallocHandles[g_iGCCHandleIndex].GccHandleCount - 2;\r\n\t\t\t\t\r\n\t\t\t\tif(g_GCCPreallocHandles[g_iGCCHandleIndex].GccHandleCount == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/\r\n\t\t\t\t\t\/\/ Time to switch to the other tank\r\n\t\t\t\t\t\/\/\r\n\t\t\t\t\tg_iGCCHandleIndex =  g_iGCCHandleIndex ? 0 : 1;\r\n\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tASSERT(g_GCCPreallocHandles[g_iGCCHandleIndex].GccHandleCount);\r\n\t\t\t\tg_GCCPreallocHandles[g_iGCCHandleIndex].GccHandleCount -=2;\r\n\t\t\t\t\r\n\t\t\t\tworkspaceHandle = gccHandle;\r\n\t\t\t\tpWorkspace = (WorkspaceObj*)g_pListOfWorkspaces->GetNext(pos);\r\n\t\t\t\tpWorkspace->SetThisObjectHandle(workspaceHandle);\r\n\t\t\t\tpWorkspace->SetWorkspaceHandle(workspaceHandle);\r\n\t\t\t\tpWorkspace->SetOwnerID(g_MyMemberID);\r\n\t\t\t\tpWorkspace->SetViewHandle(workspaceHandle + 1);\r\n\r\n\t\t\t\tposObj = pWorkspace->GetHeadPosition();\r\n\t\t\t\twhile(posObj)\r\n\t\t\t\t{\r\n\t\t\t\t\tpObj = pWorkspace->GetNextObject(posObj);\r\n\t\t\t\t\tif(pObj)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tgccHandle = g_GCCPreallocHandles[g_iGCCHandleIndex].InitialGCCHandle + g_GCCPreallocHandles[g_iGCCHandleIndex].GccHandleCount - 1;\r\n\t\t\t\t\t\tASSERT(g_GCCPreallocHandles[g_iGCCHandleIndex].GccHandleCount);\r\n\t\t\t\t\t\tg_GCCPreallocHandles[g_iGCCHandleIndex].GccHandleCount--;\r\n\t\t\t\t\t\tpObj->SetThisObjectHandle(gccHandle);\r\n\t\t\t\t\t\tpObj->SetWorkspaceHandle(workspaceHandle);\r\n\t\t\t\t\t\tpObj->SetOwnerID(g_MyMemberID);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t\/\/\r\n\t\/\/ Check if we have enough handles or shoul switch\r\n\t\/\/\r\n\tTimeToGetGCCHandles(PREALLOC_GCC_HANDLES);\r\n\tSetFakeGCCHandle(drawingHandle + 1);\r\n}\r\n\r\n","avg_line_length":29.5609756098,"max_line_length":144,"alphanum_fraction":0.7123212321,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8195,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":4.0,"content":"\/\/ $Id: tree4.cpp 5188 2012-08-30 00:31:31Z dub $\n\n\/*\n Copyright (c) 2007-2012, Trustees of The Leland Stanford Junior University\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n Redistributions of source code must retain the above copyright notice, this \n list of conditions and the following disclaimer.\n Redistributions in binary form must reproduce the above copyright notice, this\n list of conditions and the following disclaimer in the documentation and\/or\n other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Tree4: Network with 64 Terminal Nodes arranged in a tree topology\n\/\/        with 4 routers at the root of the tree\n\/\/ \n\/\/  Level 0 :  4  8 x 8 Routers   (8 Descending Links per Router)\n\/\/  Level 1 :  8  8 x 8 Routers   (4 Descending Links per Router)\n\/\/  Level 2 : 16  6 x 6 Routers   (4 Descending Links per Router)\n\/\/  Level 3 : 64  Terminal Nodes\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ RCS Information:\n\/\/  $Author: jbalfour $\n\/\/  $Date: 2007\/06\/26 22:49:23 $\n\/\/  $Id: tree4.cpp 5188 2012-08-30 00:31:31Z dub $\n\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"booksim.hpp\"\n#include <vector>\n#include <sstream>\n#include <cmath>\n\n#include \"tree4.hpp\"\n#include \"misc_utils.hpp\"\n\nTree4::Tree4( const Configuration& config, const string & name )\n: BSNetwork ( config, name )\n{\n  _ComputeSize( config );\n  _Alloc( );\n  _BuildNet( config );\n}\n\nvoid Tree4::_ComputeSize( const Configuration& config )\n{\n  int h;\n\n  _k = config.GetInt( \"k\" );\n  assert(_k == 4);\n  _n = config.GetInt( \"n\" );\n  assert(_n == 3);\n  \n  gK = _k; gN = _n;\n  \n  _nodes = powi( _k, _n );\n  \n  _size = 0;\n  for ( h = 0; h < _n; ++h ) \n    _size += (4 >> h) * powi( _k, h );\n\n  _channels = 2                  \/\/ Two Channels per Connection\n    * ( 2 * powi( _k, 1) )       \/\/ Number of Middle Routers\n    * ( 2 * _k );                \/\/ Connectivity of Middle Routers\n}\n\nvoid Tree4::RegisterRoutingFunctions(){\n\n}\n\nvoid Tree4::_BuildNet( const Configuration& config )\n{\n\n  \/\/\n  \/\/ Allocate Routers\n  \/\/\n  ostringstream name;\n  int h, pos, nPos, degree, id;\n\n  for ( h = 0; h < _n; h++ ) {\n    nPos = (4 >> h) * powi( _k, h );\n    for ( pos = 0; pos < nPos; ++pos) {\n      if ( h < _n-1 ) \n\tdegree = 8;\n      else\n\tdegree = 6;\n      \n      name.str(\"\");\n      name << \"router_\" << h << \"_\" << pos;\n      id = h * powi( _k, _n-1 ) + pos;\n      Router * r = Router::NewRouter( config, this, name.str( ),\n\t\t\t\t      id, degree, degree );\n      _Router( h, pos ) = r;\n      _timed_modules.push_back(r);\n    }\n  }\n\n  \/\/\n  \/\/ Connect Channels to Routers\n  \/\/\n  int pp, pc;\n  \/\/\n  \/\/ Connection Rule: Output Ports 0:3 Move DOWN Network\n  \/\/                  Output Ports 4:7 Move UP Network\n  \/\/\n  \n  \/\/ Injection & Ejection Channels\n  nPos = powi( _k, _n - 1 );\n  for ( pos = 0 ; pos < nPos ; ++pos ) {\n    for ( int port = 0 ; port < _k ; ++port ) {\n      \n      _Router( _n-1, pos)->AddInputChannel( _inject[_k*pos+port],\n\t\t\t\t\t    _inject_cred[_k*pos+port]);\n      \n\n      _inject[_k*pos+port]->SetLatency( 1 );\n      _inject_cred[_k*pos+port]->SetLatency( 1 );\n\n      _Router( _n-1, pos)->AddOutputChannel( _eject[_k*pos+port],\n\t\t\t\t\t     _eject_cred[_k*pos+port]);\n\n      _eject[_k*pos+port]->SetLatency( 1 );\n      _eject_cred[_k*pos+port]->SetLatency( 1 );\n\n    }\n  }\n\n  \/\/ Connections between h = 1 and h = 2 Levels\n  int c = 0;\n  nPos = 2 * powi( _k, 1 );\n  for ( pos = 0; pos < nPos; ++pos ) {\n    for ( int port = 0; port < _k; ++port ) {\n\n      pp = pos;\n      pc = _k * ( pos \/ 2 ) + port;\n      \n      \/\/ cout << \"connecting (1,\"<<pp<<\") <-> (2,\"<<pc<<\")\"<<endl;\n\n      _Router( 1, pp)->AddOutputChannel( _chan[c], _chan_cred[c] );\n      _Router( 2, pc)->AddInputChannel(  _chan[c], _chan_cred[c] );\n\n      \/\/_chan[c]->SetLatency( L );\n      \/\/_chan_cred[c]->SetLatency( L );\n\n      _chan[c]->SetLatency( 1 );\n      _chan_cred[c]->SetLatency( 1 );\n\n      c++;\n\n      _Router(1, pp)->AddInputChannel( _chan[c], _chan_cred[c] );\n      _Router(2, pc)->AddOutputChannel( _chan[c], _chan_cred[c] );\n      \n      \/\/_chan[c]->SetLatency( L );\n      \/\/_chan_cred[c]->SetLatency( L );\n      _chan[c]->SetLatency( 1 );\n      _chan_cred[c]->SetLatency( 1 );\n\n      c++;\n    }\n  }\n\n  \/\/ Connections between h = 0 and h = 1 Levels\n  nPos = 4 * powi( _k, 0 );\n  for ( pos  = 0; pos < nPos; ++pos ) {\n    for ( int port = 0; port < 2 * _k; ++port ) {\n      pp = pos;\n      pc = port;\n\n      \/\/ cout << \"connecting (0,\"<<pp<<\") <-> (1,\"<<pc<<\")\"<<endl;\n\n      _Router(0, pp)->AddOutputChannel( _chan[c], _chan_cred[c] );\n      _Router(1, pc)->AddInputChannel( _chan[c], _chan_cred[c] );\n\n      \/\/      _chan[c]->SetLatency( L );\n      \/\/_chan_cred[c]->SetLatency( L );\n      _chan[c]->SetLatency( 1 );\n      _chan_cred[c]->SetLatency( 1 );\n\n      c++;\n\n      _Router(0, pp)->AddInputChannel( _chan[c], _chan_cred[c] );\n      _Router(1, pc)->AddOutputChannel( _chan[c], _chan_cred[c] );\n\n      \/\/  _chan[c]->SetLatency( L );\n      \/\/ _chan_cred[c]->SetLatency( L );\n      _chan[c]->SetLatency( 1 );\n      _chan_cred[c]->SetLatency( 1 );\n      c++;\n    }\n  }\n\n  \/\/ cout << \"Used \" << c << \" of \" << _channels << \" channels\" << endl;\n\n}\n  \nRouter*& Tree4::_Router( int height, int pos )\n{\n  assert( height < _n );\n  assert( pos < (4 >> height) * powi( _k, height) );\n\n  int i = 0;\n  for ( int h = 0; h < height; ++h )\n    i += (4 >> h) * powi( _k, h );\n  return _routers[i+pos];\n\n}\n  \nint Tree4::_WireLatency( int height1, int pos1, int height2, int pos2 )\n{\n  int heightChild, heightParent, posChild, posParent;\n\n  int L;\n\n  if (height1 < height2) {\n    heightChild  = height2;\n    posChild     = pos2;\n    heightParent = height1;\n    posParent    = pos1;\n  } else {\n    heightChild  = height1;\n    posChild     = pos1;\n    heightParent = height2;\n    posParent    = pos2;\n  }\n\n  int _length_d2_d1   = 2 ;\n  int _length_d1_d0_0 = 2 ;\n  int _length_d1_d0_1 = 2 ;\n  int _length_d1_d0_2 = 6 ;\n  int _length_d1_d0_3 = 6 ;\n\n  assert( heightChild == heightParent+1 );\n\n  \/\/ We must decrement the delays by one to account for how the \n  \/\/  simulator interprets the specified delay (with 0 indicating one\n  \/\/  cycle of delay).\n\n  if ( heightChild == 2 ) \n    L = _length_d2_d1;\n  else {\n       if ( posChild == 0 || posChild == 6 )\n      switch ( posParent ) {\n      case 0: L =_length_d1_d0_0; break;\n      case 1: L =_length_d1_d0_1; break;\n      case 2: L =_length_d1_d0_2; break;\n      case 3: L =_length_d1_d0_3; break;\n      }\n    if ( posChild == 1 || posChild == 7 )\n      switch ( posParent ) {\n      case 0: L =_length_d1_d0_3; break;\n      case 1: L =_length_d1_d0_2; break;\n      case 2: L =_length_d1_d0_1; break;\n      case 3: L =_length_d1_d0_0; break;\n      }\n    if ( posChild == 2 || posChild == 4 )\n      switch ( posParent ) {\n      case 0: L = _length_d1_d0_0; break;\n      case 1: L = _length_d1_d0_1; break;\n      case 2: L = _length_d1_d0_2; break;\n      case 3: L = _length_d1_d0_3; break;\n      }\n    if ( posChild == 3|| posChild == 5 )\n      switch ( posParent ) {\n      case 0: L =_length_d1_d0_3; break;\n      case 1: L =_length_d1_d0_2; break;\n      case 2: L =_length_d1_d0_1; break;\n      case 3: L =_length_d1_d0_0; break;\n      }\n  }\n  return L;\n}\n","avg_line_length":28.2586206897,"max_line_length":80,"alphanum_fraction":0.5779133618,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":32544,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Naumen","Condor-1.1","MS-PL"],"max_stars_count":2.0,"content":"\/*\n * Copyright 2011-2013 Blender Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <Python.h>\n\n#include \"blender\/CCL_api.h\"\n\n#include \"blender\/blender_device.h\"\n#include \"blender\/blender_sync.h\"\n#include \"blender\/blender_session.h\"\n\n#include \"render\/denoising.h\"\n#include \"render\/merge.h\"\n\n#include \"util\/util_debug.h\"\n#include \"util\/util_foreach.h\"\n#include \"util\/util_logging.h\"\n#include \"util\/util_md5.h\"\n#include \"util\/util_opengl.h\"\n#include \"util\/util_path.h\"\n#include \"util\/util_string.h\"\n#include \"util\/util_types.h\"\n\n#ifdef WITH_OSL\n#  include \"render\/osl.h\"\n\n#  include <OSL\/oslquery.h>\n#  include <OSL\/oslconfig.h>\n#endif\n\n#ifdef WITH_OPENCL\n#  include \"device\/device_intern.h\"\n#endif\n\nCCL_NAMESPACE_BEGIN\n\nnamespace {\n\n\/* Flag describing whether debug flags were synchronized from scene. *\/\nbool debug_flags_set = false;\n\nvoid *pylong_as_voidptr_typesafe(PyObject *object)\n{\n  if (object == Py_None)\n    return NULL;\n  return PyLong_AsVoidPtr(object);\n}\n\n\/* Synchronize debug flags from a given Blender scene.\n * Return truth when device list needs invalidation.\n *\/\nbool debug_flags_sync_from_scene(BL::Scene b_scene)\n{\n  DebugFlagsRef flags = DebugFlags();\n  PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, \"cycles\");\n  \/* Backup some settings for comparison. *\/\n  DebugFlags::OpenCL::DeviceType opencl_device_type = flags.opencl.device_type;\n  \/* Synchronize shared flags. *\/\n  flags.viewport_static_bvh = get_enum(cscene, \"debug_bvh_type\");\n  \/* Synchronize CPU flags. *\/\n  flags.cpu.avx2 = get_boolean(cscene, \"debug_use_cpu_avx2\");\n  flags.cpu.avx = get_boolean(cscene, \"debug_use_cpu_avx\");\n  flags.cpu.sse41 = get_boolean(cscene, \"debug_use_cpu_sse41\");\n  flags.cpu.sse3 = get_boolean(cscene, \"debug_use_cpu_sse3\");\n  flags.cpu.sse2 = get_boolean(cscene, \"debug_use_cpu_sse2\");\n  flags.cpu.bvh_layout = (BVHLayout)get_enum(cscene, \"debug_bvh_layout\");\n  flags.cpu.split_kernel = get_boolean(cscene, \"debug_use_cpu_split_kernel\");\n  \/* Synchronize CUDA flags. *\/\n  flags.cuda.adaptive_compile = get_boolean(cscene, \"debug_use_cuda_adaptive_compile\");\n  flags.cuda.split_kernel = get_boolean(cscene, \"debug_use_cuda_split_kernel\");\n  \/* Synchronize OpenCL device type. *\/\n  switch (get_enum(cscene, \"debug_opencl_device_type\")) {\n    case 0:\n      flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_NONE;\n      break;\n    case 1:\n      flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_ALL;\n      break;\n    case 2:\n      flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_DEFAULT;\n      break;\n    case 3:\n      flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_CPU;\n      break;\n    case 4:\n      flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_GPU;\n      break;\n    case 5:\n      flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_ACCELERATOR;\n      break;\n  }\n  \/* Synchronize other OpenCL flags. *\/\n  flags.opencl.debug = get_boolean(cscene, \"debug_use_opencl_debug\");\n  flags.opencl.mem_limit = ((size_t)get_int(cscene, \"debug_opencl_mem_limit\")) * 1024 * 1024;\n  return flags.opencl.device_type != opencl_device_type;\n}\n\n\/* Reset debug flags to default values.\n * Return truth when device list needs invalidation.\n *\/\nbool debug_flags_reset()\n{\n  DebugFlagsRef flags = DebugFlags();\n  \/* Backup some settings for comparison. *\/\n  DebugFlags::OpenCL::DeviceType opencl_device_type = flags.opencl.device_type;\n  flags.reset();\n  return flags.opencl.device_type != opencl_device_type;\n}\n\n} \/* namespace *\/\n\nvoid python_thread_state_save(void **python_thread_state)\n{\n  *python_thread_state = (void *)PyEval_SaveThread();\n}\n\nvoid python_thread_state_restore(void **python_thread_state)\n{\n  PyEval_RestoreThread((PyThreadState *)*python_thread_state);\n  *python_thread_state = NULL;\n}\n\nstatic const char *PyC_UnicodeAsByte(PyObject *py_str, PyObject **coerce)\n{\n  const char *result = _PyUnicode_AsString(py_str);\n  if (result) {\n    \/* 99% of the time this is enough but we better support non unicode\n     * chars since blender doesnt limit this.\n     *\/\n    return result;\n  }\n  else {\n    PyErr_Clear();\n    if (PyBytes_Check(py_str)) {\n      return PyBytes_AS_STRING(py_str);\n    }\n    else if ((*coerce = PyUnicode_EncodeFSDefault(py_str))) {\n      return PyBytes_AS_STRING(*coerce);\n    }\n    else {\n      \/* Clear the error, so Cycles can be at leadt used without\n       * GPU and OSL support,\n       *\/\n      PyErr_Clear();\n      return \"\";\n    }\n  }\n}\n\nstatic PyObject *init_func(PyObject * \/*self*\/, PyObject *args)\n{\n  PyObject *path, *user_path;\n  int headless;\n\n  if (!PyArg_ParseTuple(args, \"OOi\", &path, &user_path, &headless)) {\n    return NULL;\n  }\n\n  PyObject *path_coerce = NULL, *user_path_coerce = NULL;\n  path_init(PyC_UnicodeAsByte(path, &path_coerce),\n            PyC_UnicodeAsByte(user_path, &user_path_coerce));\n  Py_XDECREF(path_coerce);\n  Py_XDECREF(user_path_coerce);\n\n  BlenderSession::headless = headless;\n\n  VLOG(2) << \"Debug flags initialized to:\\n\" << DebugFlags();\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *exit_func(PyObject * \/*self*\/, PyObject * \/*args*\/)\n{\n  ShaderManager::free_memory();\n  TaskScheduler::free_memory();\n  Device::free_memory();\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *create_func(PyObject * \/*self*\/, PyObject *args)\n{\n  PyObject *pyengine, *pypreferences, *pydata, *pyregion, *pyv3d, *pyrv3d;\n  int preview_osl;\n\n  if (!PyArg_ParseTuple(args,\n                        \"OOOOOOi\",\n                        &pyengine,\n                        &pypreferences,\n                        &pydata,\n                        &pyregion,\n                        &pyv3d,\n                        &pyrv3d,\n                        &preview_osl)) {\n    return NULL;\n  }\n\n  \/* RNA *\/\n  PointerRNA engineptr;\n  RNA_pointer_create(NULL, &RNA_RenderEngine, (void *)PyLong_AsVoidPtr(pyengine), &engineptr);\n  BL::RenderEngine engine(engineptr);\n\n  PointerRNA preferencesptr;\n  RNA_pointer_create(\n      NULL, &RNA_Preferences, (void *)PyLong_AsVoidPtr(pypreferences), &preferencesptr);\n  BL::Preferences preferences(preferencesptr);\n\n  PointerRNA dataptr;\n  RNA_main_pointer_create((Main *)PyLong_AsVoidPtr(pydata), &dataptr);\n  BL::BlendData data(dataptr);\n\n  PointerRNA regionptr;\n  RNA_pointer_create(NULL, &RNA_Region, pylong_as_voidptr_typesafe(pyregion), &regionptr);\n  BL::Region region(regionptr);\n\n  PointerRNA v3dptr;\n  RNA_pointer_create(NULL, &RNA_SpaceView3D, pylong_as_voidptr_typesafe(pyv3d), &v3dptr);\n  BL::SpaceView3D v3d(v3dptr);\n\n  PointerRNA rv3dptr;\n  RNA_pointer_create(NULL, &RNA_RegionView3D, pylong_as_voidptr_typesafe(pyrv3d), &rv3dptr);\n  BL::RegionView3D rv3d(rv3dptr);\n\n  \/* create session *\/\n  BlenderSession *session;\n\n  if (rv3d) {\n    \/* interactive viewport session *\/\n    int width = region.width();\n    int height = region.height();\n\n    session = new BlenderSession(engine, preferences, data, v3d, rv3d, width, height);\n  }\n  else {\n    \/* offline session or preview render *\/\n    session = new BlenderSession(engine, preferences, data, preview_osl);\n  }\n\n  return PyLong_FromVoidPtr(session);\n}\n\nstatic PyObject *free_func(PyObject * \/*self*\/, PyObject *value)\n{\n  delete (BlenderSession *)PyLong_AsVoidPtr(value);\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *render_func(PyObject * \/*self*\/, PyObject *args)\n{\n  PyObject *pysession, *pydepsgraph;\n\n  if (!PyArg_ParseTuple(args, \"OO\", &pysession, &pydepsgraph))\n    return NULL;\n\n  BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession);\n\n  PointerRNA depsgraphptr;\n  RNA_pointer_create(NULL, &RNA_Depsgraph, (ID *)PyLong_AsVoidPtr(pydepsgraph), &depsgraphptr);\n  BL::Depsgraph b_depsgraph(depsgraphptr);\n\n  python_thread_state_save(&session->python_thread_state);\n\n  session->render(b_depsgraph);\n\n  python_thread_state_restore(&session->python_thread_state);\n\n  Py_RETURN_NONE;\n}\n\n\/* pixel_array and result passed as pointers *\/\nstatic PyObject *bake_func(PyObject * \/*self*\/, PyObject *args)\n{\n  PyObject *pysession, *pydepsgraph, *pyobject;\n  PyObject *pypixel_array, *pyresult;\n  const char *pass_type;\n  int num_pixels, depth, object_id, pass_filter;\n\n  if (!PyArg_ParseTuple(args,\n                        \"OOOsiiOiiO\",\n                        &pysession,\n                        &pydepsgraph,\n                        &pyobject,\n                        &pass_type,\n                        &pass_filter,\n                        &object_id,\n                        &pypixel_array,\n                        &num_pixels,\n                        &depth,\n                        &pyresult))\n    return NULL;\n\n  BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession);\n\n  PointerRNA depsgraphptr;\n  RNA_pointer_create(NULL, &RNA_Depsgraph, PyLong_AsVoidPtr(pydepsgraph), &depsgraphptr);\n  BL::Depsgraph b_depsgraph(depsgraphptr);\n\n  PointerRNA objectptr;\n  RNA_id_pointer_create((ID *)PyLong_AsVoidPtr(pyobject), &objectptr);\n  BL::Object b_object(objectptr);\n\n  void *b_result = PyLong_AsVoidPtr(pyresult);\n\n  PointerRNA bakepixelptr;\n  RNA_pointer_create(NULL, &RNA_BakePixel, PyLong_AsVoidPtr(pypixel_array), &bakepixelptr);\n  BL::BakePixel b_bake_pixel(bakepixelptr);\n\n  python_thread_state_save(&session->python_thread_state);\n\n  session->bake(b_depsgraph,\n                b_object,\n                pass_type,\n                pass_filter,\n                object_id,\n                b_bake_pixel,\n                (size_t)num_pixels,\n                depth,\n                (float *)b_result);\n\n  python_thread_state_restore(&session->python_thread_state);\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *draw_func(PyObject * \/*self*\/, PyObject *args)\n{\n  PyObject *pysession, *pygraph, *pyv3d, *pyrv3d;\n\n  if (!PyArg_ParseTuple(args, \"OOOO\", &pysession, &pygraph, &pyv3d, &pyrv3d))\n    return NULL;\n\n  BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession);\n\n  if (PyLong_AsVoidPtr(pyrv3d)) {\n    \/* 3d view drawing *\/\n    int viewport[4];\n    glGetIntegerv(GL_VIEWPORT, viewport);\n\n    session->draw(viewport[2], viewport[3]);\n  }\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *reset_func(PyObject * \/*self*\/, PyObject *args)\n{\n  PyObject *pysession, *pydata, *pydepsgraph;\n\n  if (!PyArg_ParseTuple(args, \"OOO\", &pysession, &pydata, &pydepsgraph))\n    return NULL;\n\n  BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession);\n\n  PointerRNA dataptr;\n  RNA_main_pointer_create((Main *)PyLong_AsVoidPtr(pydata), &dataptr);\n  BL::BlendData b_data(dataptr);\n\n  PointerRNA depsgraphptr;\n  RNA_pointer_create(NULL, &RNA_Depsgraph, PyLong_AsVoidPtr(pydepsgraph), &depsgraphptr);\n  BL::Depsgraph b_depsgraph(depsgraphptr);\n\n  python_thread_state_save(&session->python_thread_state);\n\n  session->reset_session(b_data, b_depsgraph);\n\n  python_thread_state_restore(&session->python_thread_state);\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *sync_func(PyObject * \/*self*\/, PyObject *args)\n{\n  PyObject *pysession, *pydepsgraph;\n\n  if (!PyArg_ParseTuple(args, \"OO\", &pysession, &pydepsgraph))\n    return NULL;\n\n  BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession);\n\n  PointerRNA depsgraphptr;\n  RNA_pointer_create(NULL, &RNA_Depsgraph, PyLong_AsVoidPtr(pydepsgraph), &depsgraphptr);\n  BL::Depsgraph b_depsgraph(depsgraphptr);\n\n  python_thread_state_save(&session->python_thread_state);\n\n  session->synchronize(b_depsgraph);\n\n  python_thread_state_restore(&session->python_thread_state);\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *available_devices_func(PyObject * \/*self*\/, PyObject *args)\n{\n  const char *type_name;\n  if (!PyArg_ParseTuple(args, \"s\", &type_name)) {\n    return NULL;\n  }\n\n  DeviceType type = Device::type_from_string(type_name);\n  uint mask = (type == DEVICE_NONE) ? DEVICE_MASK_ALL : DEVICE_MASK(type);\n  mask |= DEVICE_MASK_CPU;\n\n  vector<DeviceInfo> devices = Device::available_devices(mask);\n  PyObject *ret = PyTuple_New(devices.size());\n\n  for (size_t i = 0; i < devices.size(); i++) {\n    DeviceInfo &device = devices[i];\n    string type_name = Device::string_from_type(device.type);\n    PyObject *device_tuple = PyTuple_New(3);\n    PyTuple_SET_ITEM(device_tuple, 0, PyUnicode_FromString(device.description.c_str()));\n    PyTuple_SET_ITEM(device_tuple, 1, PyUnicode_FromString(type_name.c_str()));\n    PyTuple_SET_ITEM(device_tuple, 2, PyUnicode_FromString(device.id.c_str()));\n    PyTuple_SET_ITEM(ret, i, device_tuple);\n  }\n\n  return ret;\n}\n\n#ifdef WITH_OSL\n\nstatic PyObject *osl_update_node_func(PyObject * \/*self*\/, PyObject *args)\n{\n  PyObject *pydata, *pynodegroup, *pynode;\n  const char *filepath = NULL;\n\n  if (!PyArg_ParseTuple(args, \"OOOs\", &pydata, &pynodegroup, &pynode, &filepath))\n    return NULL;\n\n  \/* RNA *\/\n  PointerRNA dataptr;\n  RNA_main_pointer_create((Main *)PyLong_AsVoidPtr(pydata), &dataptr);\n  BL::BlendData b_data(dataptr);\n\n  PointerRNA nodeptr;\n  RNA_pointer_create((ID *)PyLong_AsVoidPtr(pynodegroup),\n                     &RNA_ShaderNodeScript,\n                     (void *)PyLong_AsVoidPtr(pynode),\n                     &nodeptr);\n  BL::ShaderNodeScript b_node(nodeptr);\n\n  \/* update bytecode hash *\/\n  string bytecode = b_node.bytecode();\n\n  if (!bytecode.empty()) {\n    MD5Hash md5;\n    md5.append((const uint8_t *)bytecode.c_str(), bytecode.size());\n    b_node.bytecode_hash(md5.get_hex().c_str());\n  }\n  else\n    b_node.bytecode_hash(\"\");\n\n  \/* query from file path *\/\n  OSL::OSLQuery query;\n\n  if (!OSLShaderManager::osl_query(query, filepath))\n    Py_RETURN_FALSE;\n\n  \/* add new sockets from parameters *\/\n  set<void *> used_sockets;\n\n  for (int i = 0; i < query.nparams(); i++) {\n    const OSL::OSLQuery::Parameter *param = query.getparam(i);\n\n    \/* skip unsupported types *\/\n    if (param->varlenarray || param->isstruct || param->type.arraylen > 1)\n      continue;\n\n    \/* determine socket type *\/\n    string socket_type;\n    BL::NodeSocket::type_enum data_type = BL::NodeSocket::type_VALUE;\n    float4 default_float4 = make_float4(0.0f, 0.0f, 0.0f, 1.0f);\n    float default_float = 0.0f;\n    int default_int = 0;\n    string default_string = \"\";\n\n    if (param->isclosure) {\n      socket_type = \"NodeSocketShader\";\n      data_type = BL::NodeSocket::type_SHADER;\n    }\n    else if (param->type.vecsemantics == TypeDesc::COLOR) {\n      socket_type = \"NodeSocketColor\";\n      data_type = BL::NodeSocket::type_RGBA;\n\n      if (param->validdefault) {\n        default_float4[0] = param->fdefault[0];\n        default_float4[1] = param->fdefault[1];\n        default_float4[2] = param->fdefault[2];\n      }\n    }\n    else if (param->type.vecsemantics == TypeDesc::POINT ||\n             param->type.vecsemantics == TypeDesc::VECTOR ||\n             param->type.vecsemantics == TypeDesc::NORMAL) {\n      socket_type = \"NodeSocketVector\";\n      data_type = BL::NodeSocket::type_VECTOR;\n\n      if (param->validdefault) {\n        default_float4[0] = param->fdefault[0];\n        default_float4[1] = param->fdefault[1];\n        default_float4[2] = param->fdefault[2];\n      }\n    }\n    else if (param->type.aggregate == TypeDesc::SCALAR) {\n      if (param->type.basetype == TypeDesc::INT) {\n        socket_type = \"NodeSocketInt\";\n        data_type = BL::NodeSocket::type_INT;\n        if (param->validdefault)\n          default_int = param->idefault[0];\n      }\n      else if (param->type.basetype == TypeDesc::FLOAT) {\n        socket_type = \"NodeSocketFloat\";\n        data_type = BL::NodeSocket::type_VALUE;\n        if (param->validdefault)\n          default_float = param->fdefault[0];\n      }\n      else if (param->type.basetype == TypeDesc::STRING) {\n        socket_type = \"NodeSocketString\";\n        data_type = BL::NodeSocket::type_STRING;\n        if (param->validdefault)\n          default_string = param->sdefault[0].string();\n      }\n      else\n        continue;\n    }\n    else\n      continue;\n\n    \/* find socket socket *\/\n    BL::NodeSocket b_sock(PointerRNA_NULL);\n    if (param->isoutput) {\n      b_sock = b_node.outputs[param->name.string()];\n      \/* remove if type no longer matches *\/\n      if (b_sock && b_sock.bl_idname() != socket_type) {\n        b_node.outputs.remove(b_data, b_sock);\n        b_sock = BL::NodeSocket(PointerRNA_NULL);\n      }\n    }\n    else {\n      b_sock = b_node.inputs[param->name.string()];\n      \/* remove if type no longer matches *\/\n      if (b_sock && b_sock.bl_idname() != socket_type) {\n        b_node.inputs.remove(b_data, b_sock);\n        b_sock = BL::NodeSocket(PointerRNA_NULL);\n      }\n    }\n\n    if (!b_sock) {\n      \/* create new socket *\/\n      if (param->isoutput)\n        b_sock = b_node.outputs.create(\n            b_data, socket_type.c_str(), param->name.c_str(), param->name.c_str());\n      else\n        b_sock = b_node.inputs.create(\n            b_data, socket_type.c_str(), param->name.c_str(), param->name.c_str());\n\n      \/* set default value *\/\n      if (data_type == BL::NodeSocket::type_VALUE) {\n        set_float(b_sock.ptr, \"default_value\", default_float);\n      }\n      else if (data_type == BL::NodeSocket::type_INT) {\n        set_int(b_sock.ptr, \"default_value\", default_int);\n      }\n      else if (data_type == BL::NodeSocket::type_RGBA) {\n        set_float4(b_sock.ptr, \"default_value\", default_float4);\n      }\n      else if (data_type == BL::NodeSocket::type_VECTOR) {\n        set_float3(b_sock.ptr, \"default_value\", float4_to_float3(default_float4));\n      }\n      else if (data_type == BL::NodeSocket::type_STRING) {\n        set_string(b_sock.ptr, \"default_value\", default_string);\n      }\n    }\n\n    used_sockets.insert(b_sock.ptr.data);\n  }\n\n  \/* remove unused parameters *\/\n  bool removed;\n\n  do {\n    BL::Node::inputs_iterator b_input;\n    BL::Node::outputs_iterator b_output;\n\n    removed = false;\n\n    for (b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {\n      if (used_sockets.find(b_input->ptr.data) == used_sockets.end()) {\n        b_node.inputs.remove(b_data, *b_input);\n        removed = true;\n        break;\n      }\n    }\n\n    for (b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {\n      if (used_sockets.find(b_output->ptr.data) == used_sockets.end()) {\n        b_node.outputs.remove(b_data, *b_output);\n        removed = true;\n        break;\n      }\n    }\n  } while (removed);\n\n  Py_RETURN_TRUE;\n}\n\nstatic PyObject *osl_compile_func(PyObject * \/*self*\/, PyObject *args)\n{\n  const char *inputfile = NULL, *outputfile = NULL;\n\n  if (!PyArg_ParseTuple(args, \"ss\", &inputfile, &outputfile))\n    return NULL;\n\n  \/* return *\/\n  if (!OSLShaderManager::osl_compile(inputfile, outputfile))\n    Py_RETURN_FALSE;\n\n  Py_RETURN_TRUE;\n}\n#endif\n\nstatic PyObject *system_info_func(PyObject * \/*self*\/, PyObject * \/*value*\/)\n{\n  string system_info = Device::device_capabilities();\n  return PyUnicode_FromString(system_info.c_str());\n}\n\n#ifdef WITH_OPENCL\nstatic PyObject *opencl_disable_func(PyObject * \/*self*\/, PyObject * \/*value*\/)\n{\n  VLOG(2) << \"Disabling OpenCL platform.\";\n  DebugFlags().opencl.device_type = DebugFlags::OpenCL::DEVICE_NONE;\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *opencl_compile_func(PyObject * \/*self*\/, PyObject *args)\n{\n  PyObject *sequence = PySequence_Fast(args, \"Arguments must be a sequence\");\n  if (sequence == NULL) {\n    Py_RETURN_FALSE;\n  }\n\n  vector<string> parameters;\n  for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(sequence); i++) {\n    PyObject *item = PySequence_Fast_GET_ITEM(sequence, i);\n    PyObject *item_as_string = PyObject_Str(item);\n    const char *parameter_string = PyUnicode_AsUTF8(item_as_string);\n    parameters.push_back(parameter_string);\n    Py_DECREF(item_as_string);\n  }\n  Py_DECREF(sequence);\n\n  if (device_opencl_compile_kernel(parameters)) {\n    Py_RETURN_TRUE;\n  }\n  else {\n    Py_RETURN_FALSE;\n  }\n}\n#endif\n\nstatic bool image_parse_filepaths(PyObject *pyfilepaths, vector<string> &filepaths)\n{\n  if (PyUnicode_Check(pyfilepaths)) {\n    const char *filepath = PyUnicode_AsUTF8(pyfilepaths);\n    filepaths.push_back(filepath);\n    return true;\n  }\n\n  PyObject *sequence = PySequence_Fast(pyfilepaths,\n                                       \"File paths must be a string or sequence of strings\");\n  if (sequence == NULL) {\n    return false;\n  }\n\n  for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(sequence); i++) {\n    PyObject *item = PySequence_Fast_GET_ITEM(sequence, i);\n    const char *filepath = PyUnicode_AsUTF8(item);\n    if (filepath == NULL) {\n      PyErr_SetString(PyExc_ValueError, \"File paths must be a string or sequence of strings.\");\n      Py_DECREF(sequence);\n      return false;\n    }\n    filepaths.push_back(filepath);\n  }\n  Py_DECREF(sequence);\n\n  return true;\n}\n\nstatic PyObject *denoise_func(PyObject * \/*self*\/, PyObject *args, PyObject *keywords)\n{\n  static const char *keyword_list[] = {\n      \"preferences\", \"scene\", \"view_layer\", \"input\", \"output\", \"tile_size\", \"samples\", NULL};\n  PyObject *pypreferences, *pyscene, *pyviewlayer;\n  PyObject *pyinput, *pyoutput = NULL;\n  int tile_size = 0, samples = 0;\n\n  if (!PyArg_ParseTupleAndKeywords(args,\n                                   keywords,\n                                   \"OOOO|Oii\",\n                                   (char **)keyword_list,\n                                   &pypreferences,\n                                   &pyscene,\n                                   &pyviewlayer,\n                                   &pyinput,\n                                   &pyoutput,\n                                   &tile_size,\n                                   &samples)) {\n    return NULL;\n  }\n\n  \/* Get device specification from preferences and scene. *\/\n  PointerRNA preferencesptr;\n  RNA_pointer_create(\n      NULL, &RNA_Preferences, (void *)PyLong_AsVoidPtr(pypreferences), &preferencesptr);\n  BL::Preferences b_preferences(preferencesptr);\n\n  PointerRNA sceneptr;\n  RNA_id_pointer_create((ID *)PyLong_AsVoidPtr(pyscene), &sceneptr);\n  BL::Scene b_scene(sceneptr);\n\n  DeviceInfo device = blender_device_info(b_preferences, b_scene, true);\n\n  \/* Get denoising parameters from view layer. *\/\n  PointerRNA viewlayerptr;\n  RNA_pointer_create((ID *)PyLong_AsVoidPtr(pyscene),\n                     &RNA_ViewLayer,\n                     PyLong_AsVoidPtr(pyviewlayer),\n                     &viewlayerptr);\n  PointerRNA cviewlayer = RNA_pointer_get(&viewlayerptr, \"cycles\");\n\n  DenoiseParams params;\n  params.radius = get_int(cviewlayer, \"denoising_radius\");\n  params.strength = get_float(cviewlayer, \"denoising_strength\");\n  params.feature_strength = get_float(cviewlayer, \"denoising_feature_strength\");\n  params.relative_pca = get_boolean(cviewlayer, \"denoising_relative_pca\");\n  params.neighbor_frames = get_int(cviewlayer, \"denoising_neighbor_frames\");\n\n  \/* Parse file paths list. *\/\n  vector<string> input, output;\n\n  if (!image_parse_filepaths(pyinput, input)) {\n    return NULL;\n  }\n\n  if (pyoutput) {\n    if (!image_parse_filepaths(pyoutput, output)) {\n      return NULL;\n    }\n  }\n  else {\n    output = input;\n  }\n\n  if (input.empty()) {\n    PyErr_SetString(PyExc_ValueError, \"No input file paths specified.\");\n    return NULL;\n  }\n  if (input.size() != output.size()) {\n    PyErr_SetString(PyExc_ValueError, \"Number of input and output file paths does not match.\");\n    return NULL;\n  }\n\n  \/* Create denoiser. *\/\n  Denoiser denoiser(device);\n  denoiser.params = params;\n  denoiser.input = input;\n  denoiser.output = output;\n\n  if (tile_size > 0) {\n    denoiser.tile_size = make_int2(tile_size, tile_size);\n  }\n  if (samples > 0) {\n    denoiser.samples_override = samples;\n  }\n\n  \/* Run denoiser. *\/\n  if (!denoiser.run()) {\n    PyErr_SetString(PyExc_ValueError, denoiser.error.c_str());\n    return NULL;\n  }\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *merge_func(PyObject * \/*self*\/, PyObject *args, PyObject *keywords)\n{\n  static const char *keyword_list[] = {\"input\", \"output\", NULL};\n  PyObject *pyinput, *pyoutput = NULL;\n\n  if (!PyArg_ParseTupleAndKeywords(\n          args, keywords, \"OO\", (char **)keyword_list, &pyinput, &pyoutput)) {\n    return NULL;\n  }\n\n  \/* Parse input list. *\/\n  vector<string> input;\n  if (!image_parse_filepaths(pyinput, input)) {\n    return NULL;\n  }\n\n  \/* Parse output string. *\/\n  if (!PyUnicode_Check(pyoutput)) {\n    PyErr_SetString(PyExc_ValueError, \"Output must be a string.\");\n    return NULL;\n  }\n  string output = PyUnicode_AsUTF8(pyoutput);\n\n  \/* Merge. *\/\n  ImageMerger merger;\n  merger.input = input;\n  merger.output = output;\n\n  if (!merger.run()) {\n    PyErr_SetString(PyExc_ValueError, merger.error.c_str());\n    return NULL;\n  }\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *debug_flags_update_func(PyObject * \/*self*\/, PyObject *args)\n{\n  PyObject *pyscene;\n  if (!PyArg_ParseTuple(args, \"O\", &pyscene)) {\n    return NULL;\n  }\n\n  PointerRNA sceneptr;\n  RNA_id_pointer_create((ID *)PyLong_AsVoidPtr(pyscene), &sceneptr);\n  BL::Scene b_scene(sceneptr);\n\n  if (debug_flags_sync_from_scene(b_scene)) {\n    VLOG(2) << \"Tagging device list for update.\";\n    Device::tag_update();\n  }\n\n  VLOG(2) << \"Debug flags set to:\\n\" << DebugFlags();\n\n  debug_flags_set = true;\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *debug_flags_reset_func(PyObject * \/*self*\/, PyObject * \/*args*\/)\n{\n  if (debug_flags_reset()) {\n    VLOG(2) << \"Tagging device list for update.\";\n    Device::tag_update();\n  }\n  if (debug_flags_set) {\n    VLOG(2) << \"Debug flags reset to:\\n\" << DebugFlags();\n    debug_flags_set = false;\n  }\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *set_resumable_chunk_func(PyObject * \/*self*\/, PyObject *args)\n{\n  int num_resumable_chunks, current_resumable_chunk;\n  if (!PyArg_ParseTuple(args, \"ii\", &num_resumable_chunks, &current_resumable_chunk)) {\n    Py_RETURN_NONE;\n  }\n\n  if (num_resumable_chunks <= 0) {\n    fprintf(stderr, \"Cycles: Bad value for number of resumable chunks.\\n\");\n    abort();\n    Py_RETURN_NONE;\n  }\n  if (current_resumable_chunk < 1 || current_resumable_chunk > num_resumable_chunks) {\n    fprintf(stderr, \"Cycles: Bad value for current resumable chunk number.\\n\");\n    abort();\n    Py_RETURN_NONE;\n  }\n\n  VLOG(1) << \"Initialized resumable render: \"\n          << \"num_resumable_chunks=\" << num_resumable_chunks << \", \"\n          << \"current_resumable_chunk=\" << current_resumable_chunk;\n  BlenderSession::num_resumable_chunks = num_resumable_chunks;\n  BlenderSession::current_resumable_chunk = current_resumable_chunk;\n\n  printf(\"Cycles: Will render chunk %d of %d\\n\", current_resumable_chunk, num_resumable_chunks);\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *set_resumable_chunk_range_func(PyObject * \/*self*\/, PyObject *args)\n{\n  int num_chunks, start_chunk, end_chunk;\n  if (!PyArg_ParseTuple(args, \"iii\", &num_chunks, &start_chunk, &end_chunk)) {\n    Py_RETURN_NONE;\n  }\n\n  if (num_chunks <= 0) {\n    fprintf(stderr, \"Cycles: Bad value for number of resumable chunks.\\n\");\n    abort();\n    Py_RETURN_NONE;\n  }\n  if (start_chunk < 1 || start_chunk > num_chunks) {\n    fprintf(stderr, \"Cycles: Bad value for start chunk number.\\n\");\n    abort();\n    Py_RETURN_NONE;\n  }\n  if (end_chunk < 1 || end_chunk > num_chunks) {\n    fprintf(stderr, \"Cycles: Bad value for start chunk number.\\n\");\n    abort();\n    Py_RETURN_NONE;\n  }\n  if (start_chunk > end_chunk) {\n    fprintf(stderr, \"Cycles: End chunk should be higher than start one.\\n\");\n    abort();\n    Py_RETURN_NONE;\n  }\n\n  VLOG(1) << \"Initialized resumable render: \"\n          << \"num_resumable_chunks=\" << num_chunks << \", \"\n          << \"start_resumable_chunk=\" << start_chunk << \"end_resumable_chunk=\" << end_chunk;\n  BlenderSession::num_resumable_chunks = num_chunks;\n  BlenderSession::start_resumable_chunk = start_chunk;\n  BlenderSession::end_resumable_chunk = end_chunk;\n\n  printf(\"Cycles: Will render chunks %d to %d of %d\\n\", start_chunk, end_chunk, num_chunks);\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *clear_resumable_chunk_func(PyObject * \/*self*\/, PyObject * \/*value*\/)\n{\n  VLOG(1) << \"Clear resumable render\";\n  BlenderSession::num_resumable_chunks = 0;\n  BlenderSession::current_resumable_chunk = 0;\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *enable_print_stats_func(PyObject * \/*self*\/, PyObject * \/*args*\/)\n{\n  BlenderSession::print_render_stats = true;\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *get_device_types_func(PyObject * \/*self*\/, PyObject * \/*args*\/)\n{\n  vector<DeviceType> device_types = Device::available_types();\n  bool has_cuda = false, has_opencl = false;\n  foreach (DeviceType device_type, device_types) {\n    has_cuda |= (device_type == DEVICE_CUDA);\n    has_opencl |= (device_type == DEVICE_OPENCL);\n  }\n  PyObject *list = PyTuple_New(2);\n  PyTuple_SET_ITEM(list, 0, PyBool_FromLong(has_cuda));\n  PyTuple_SET_ITEM(list, 1, PyBool_FromLong(has_opencl));\n  return list;\n}\n\nstatic PyMethodDef methods[] = {\n    {\"init\", init_func, METH_VARARGS, \"\"},\n    {\"exit\", exit_func, METH_VARARGS, \"\"},\n    {\"create\", create_func, METH_VARARGS, \"\"},\n    {\"free\", free_func, METH_O, \"\"},\n    {\"render\", render_func, METH_VARARGS, \"\"},\n    {\"bake\", bake_func, METH_VARARGS, \"\"},\n    {\"draw\", draw_func, METH_VARARGS, \"\"},\n    {\"sync\", sync_func, METH_VARARGS, \"\"},\n    {\"reset\", reset_func, METH_VARARGS, \"\"},\n#ifdef WITH_OSL\n    {\"osl_update_node\", osl_update_node_func, METH_VARARGS, \"\"},\n    {\"osl_compile\", osl_compile_func, METH_VARARGS, \"\"},\n#endif\n    {\"available_devices\", available_devices_func, METH_VARARGS, \"\"},\n    {\"system_info\", system_info_func, METH_NOARGS, \"\"},\n#ifdef WITH_OPENCL\n    {\"opencl_disable\", opencl_disable_func, METH_NOARGS, \"\"},\n    {\"opencl_compile\", opencl_compile_func, METH_VARARGS, \"\"},\n#endif\n\n    \/* Standalone denoising *\/\n    {\"denoise\", (PyCFunction)denoise_func, METH_VARARGS | METH_KEYWORDS, \"\"},\n    {\"merge\", (PyCFunction)merge_func, METH_VARARGS | METH_KEYWORDS, \"\"},\n\n    \/* Debugging routines *\/\n    {\"debug_flags_update\", debug_flags_update_func, METH_VARARGS, \"\"},\n    {\"debug_flags_reset\", debug_flags_reset_func, METH_NOARGS, \"\"},\n\n    \/* Statistics. *\/\n    {\"enable_print_stats\", enable_print_stats_func, METH_NOARGS, \"\"},\n\n    \/* Resumable render *\/\n    {\"set_resumable_chunk\", set_resumable_chunk_func, METH_VARARGS, \"\"},\n    {\"set_resumable_chunk_range\", set_resumable_chunk_range_func, METH_VARARGS, \"\"},\n    {\"clear_resumable_chunk\", clear_resumable_chunk_func, METH_NOARGS, \"\"},\n\n    \/* Compute Device selection *\/\n    {\"get_device_types\", get_device_types_func, METH_VARARGS, \"\"},\n\n    {NULL, NULL, 0, NULL},\n};\n\nstatic struct PyModuleDef module = {\n    PyModuleDef_HEAD_INIT,\n    \"_cycles\",\n    \"Blender cycles render integration\",\n    -1,\n    methods,\n    NULL,\n    NULL,\n    NULL,\n    NULL,\n};\n\nCCL_NAMESPACE_END\n\nvoid *CCL_python_module_init()\n{\n  PyObject *mod = PyModule_Create(&ccl::module);\n\n#ifdef WITH_OSL\n  \/* TODO(sergey): This gives us library we've been linking against.\n   *               In theory with dynamic OSL library it might not be\n   *               accurate, but there's nothing in OSL API which we\n   *               might use to get version in runtime.\n   *\/\n  int curversion = OSL_LIBRARY_VERSION_CODE;\n  PyModule_AddObject(mod, \"with_osl\", Py_True);\n  Py_INCREF(Py_True);\n  PyModule_AddObject(\n      mod,\n      \"osl_version\",\n      Py_BuildValue(\"(iii)\", curversion \/ 10000, (curversion \/ 100) % 100, curversion % 100));\n  PyModule_AddObject(\n      mod,\n      \"osl_version_string\",\n      PyUnicode_FromFormat(\n          \"%2d, %2d, %2d\", curversion \/ 10000, (curversion \/ 100) % 100, curversion % 100));\n#else\n  PyModule_AddObject(mod, \"with_osl\", Py_False);\n  Py_INCREF(Py_False);\n  PyModule_AddStringConstant(mod, \"osl_version\", \"unknown\");\n  PyModule_AddStringConstant(mod, \"osl_version_string\", \"unknown\");\n#endif\n\n#ifdef WITH_CYCLES_DEBUG\n  PyModule_AddObject(mod, \"with_cycles_debug\", Py_True);\n  Py_INCREF(Py_True);\n#else\n  PyModule_AddObject(mod, \"with_cycles_debug\", Py_False);\n  Py_INCREF(Py_False);\n#endif\n\n#ifdef WITH_NETWORK\n  PyModule_AddObject(mod, \"with_network\", Py_True);\n  Py_INCREF(Py_True);\n#else  \/* WITH_NETWORK *\/\n  PyModule_AddObject(mod, \"with_network\", Py_False);\n  Py_INCREF(Py_False);\n#endif \/* WITH_NETWORK *\/\n\n#ifdef WITH_EMBREE\n  PyModule_AddObject(mod, \"with_embree\", Py_True);\n  Py_INCREF(Py_True);\n#else  \/* WITH_EMBREE *\/\n  PyModule_AddObject(mod, \"with_embree\", Py_False);\n  Py_INCREF(Py_False);\n#endif \/* WITH_EMBREE *\/\n\n  return (void *)mod;\n}\n","avg_line_length":30.1054579093,"max_line_length":96,"alphanum_fraction":0.6732731072,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1089,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":12278.0,"content":"\/\/ Copyright 2002 The Trustees of Indiana University.\n\n\/\/ Use, modification and distribution is subject to the Boost Software \n\/\/ License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n\/\/  Boost.MultiArray Library\n\/\/  Authors: Ronald Garcia\n\/\/           Jeremy Siek\n\/\/           Andrew Lumsdaine\n\/\/  See http:\/\/www.boost.org\/libs\/multi_array for documentation.\n\n\/\/ \n\/\/ fail_ref_cparen.cpp\n\/\/   Testing const operator() constness. \n\/\/\n\n#include <boost\/multi_array.hpp>\n\n#include <boost\/core\/lightweight_test.hpp>\n\n#include <boost\/array.hpp>\n\nint\nmain()\n{\n  const int ndims=3;\n  typedef boost::multi_array_ref<int,ndims> array_ref;\n\n  boost::array<array_ref::size_type,ndims> sma_dims = {{2,3,4}};\n\n  int data[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,\n                 14,15,16,17,18,19,20,21,22,23};\n\n  array_ref sma(data,sma_dims);\n\n  const array_ref& csma = sma;\n  boost::array<array_ref::index,ndims> indices = {{0,0,0}};\n\n  \/\/ FAIL! cannot assign to a const multi_array_ref\n  csma(indices) = 5;\n\n  return boost::report_errors();\n}\n","avg_line_length":24.2,"max_line_length":74,"alphanum_fraction":0.681359045,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4093,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ THIS CODE AND INFORMATION IS PROVIDED \"AS IS\" WITHOUT WARRANTY OF\r\n\/\/ ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO\r\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\/OR FITNESS FOR A\r\n\/\/ PARTICULAR PURPOSE.\r\n\/\/\r\n\/\/ Copyright (c) Microsoft Corporation. All rights reserved.\r\n\r\n#include \"pch.h\"\r\n#include \"Texture.h\"\r\n#include \"..\\Assets.h\"\r\n#include \"ErrorPopUpScreen.h\"\r\n#include \"..\\Common\\InputState.h\"\r\n#include \"ScreenManager.h\"\r\n\r\nusing namespace DirectX;\r\n\r\nnamespace\r\n{\r\n   const XMVECTORF32 BackgroundColor = Colors::DarkSlateGray;\r\n}\r\n\r\nnamespace GameSaveSample {\r\n\r\n   ErrorPopUpScreen::ErrorPopUpScreen( ScreenManager& screenManager, const std::string& message ) : \r\n      GameScreen( screenManager ),\r\n      m_errorMessage( message )\r\n   {\r\n      m_exitWhenHidden = false;\r\n      m_isPopup = true;\r\n   }\r\n\r\n   ErrorPopUpScreen::~ErrorPopUpScreen( void )\r\n   {\r\n      UnloadContent();\r\n   }\r\n\r\n   void ErrorPopUpScreen::LoadContent( ATG::AssetLoadResources& loadRes )\r\n   {\r\n      m_backgroundTexture = ATG::GetTextureAsset( loadRes, AssetDescriptor::Blank );\r\n   }\r\n\r\n   void ErrorPopUpScreen::UnloadContent()\r\n   {\r\n      m_backgroundTexture.Unload();\r\n   }\r\n\r\n   void ErrorPopUpScreen::HandleInput( const DirectX::InputState& inputState )\r\n   {\r\n      if ( inputState.IsMenuSelect( -1, nullptr ) )\r\n         ExitScreen();\r\n   }\r\n\r\n   void ErrorPopUpScreen::Draw( ID3D12GraphicsCommandList* commandList, float \/*totalTime*\/, float \/*elapsedTime*\/ )\r\n   {\r\n      auto& screenManager = Manager();\r\n      auto spriteBatch = screenManager.GetSpriteBatch();\r\n      auto spriteFont = screenManager.GetSpriteFont();\r\n      auto blendStates = screenManager.GetCommonStates();\r\n      auto viewportBounds = screenManager.GetScreenBounds();\r\n      float viewportWidth = float( viewportBounds.right );\r\n      float viewportHeight = float( viewportBounds.bottom );\r\n      auto scaleMatrix = ATG::GetScaleMatrixForWindow( screenManager.GetWindowBounds() );\r\n\r\n      \/\/ calculate position and size of error message\r\n      XMFLOAT2 errorMsgPosition = XMFLOAT2( 0, viewportHeight \/ 2.0f );\r\n      XMVECTORF32 errorMsgColor = Colors::Yellow;\r\n      XMFLOAT2 origin = XMFLOAT2( 0, spriteFont->GetLineSpacing() \/ 2.0f );\r\n      XMVECTOR size = spriteFont->MeasureString( m_errorMessage.c_str() );\r\n      errorMsgPosition.x = viewportWidth \/ 2.0f - XMVectorGetX( size ) \/ 2.0f;\r\n\r\n      \/\/ create a rectangle representing the screen dimensions of the error message background rectangle\r\n      long rectangleWidth = long( std::min( std::max( XMVectorGetX( size ) + 100.0f, 600.0f ), viewportWidth ) );\r\n      long rectangleHeight = long( spriteFont->GetLineSpacing() * 6.0f );\r\n      long rectangleLeft = long( viewportWidth \/ 2.0f ) - ( rectangleWidth \/ 2 );\r\n      long rectangleTop = long( errorMsgPosition.y + spriteFont->GetLineSpacing() ) - ( rectangleHeight \/ 2 );\r\n      RECT backgroundRectangle = { rectangleLeft, rectangleTop, rectangleLeft + rectangleWidth, rectangleTop + rectangleHeight };\r\n\r\n      ID3D12DescriptorHeap* pHeap = Manager().GetDescriptorHeap()->Heap();\r\n      commandList->SetDescriptorHeaps(1, &pHeap);\r\n\r\n      spriteBatch->Begin( commandList, DirectX::SpriteSortMode_Deferred, scaleMatrix );\r\n\r\n      \/\/ draw a background color for the rectangle\r\n      spriteBatch->Draw( m_backgroundTexture.GetGpuHandle(), m_backgroundTexture->GetTextureSize(), backgroundRectangle, BackgroundColor );\r\n\r\n      \/\/ draw error message in the middle of the screen\r\n      spriteFont->DrawString( spriteBatch.get(), m_errorMessage.c_str(), errorMsgPosition, errorMsgColor, 0, origin );\r\n\r\n      \/\/ draw continuation prompt\r\n      const char* continuePrompt = u8\"Press (A) to Continue\";\r\n\r\n      errorMsgPosition.y += spriteFont->GetLineSpacing();\r\n      size = spriteFont->MeasureString( continuePrompt );\r\n      errorMsgPosition.x = viewportWidth \/ 2.0f - XMVectorGetX( size ) \/ 2.0f;\r\n      spriteFont->DrawString( spriteBatch.get(), continuePrompt, errorMsgPosition, Colors::Yellow, 0, origin );\r\n\r\n      spriteBatch->End();\r\n   }\r\n} \/\/ namespace GameSaveSample\r\n","avg_line_length":40.93,"max_line_length":140,"alphanum_fraction":0.6924016614,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13490,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2.0,"content":"#include <Interpreters\/InterpreterShowCreateAccessEntityQuery.h>\n#include <Interpreters\/Context.h>\n#include <Parsers\/ASTCreateUserQuery.h>\n#include <Parsers\/ASTCreateRoleQuery.h>\n#include <Parsers\/ASTCreateQuotaQuery.h>\n#include <Parsers\/ASTCreateRowPolicyQuery.h>\n#include <Parsers\/ASTCreateSettingsProfileQuery.h>\n#include <Parsers\/ASTShowCreateAccessEntityQuery.h>\n#include <Parsers\/ASTUserNameWithHost.h>\n#include <Parsers\/ASTRolesOrUsersSet.h>\n#include <Parsers\/ASTSettingsProfileElement.h>\n#include <Parsers\/ASTRowPolicyName.h>\n#include <Parsers\/ExpressionListParsers.h>\n#include <Parsers\/formatAST.h>\n#include <Parsers\/parseQuery.h>\n#include <Access\/AccessControlManager.h>\n#include <Access\/EnabledQuota.h>\n#include <Access\/QuotaUsage.h>\n#include <Access\/User.h>\n#include <Access\/Role.h>\n#include <Access\/SettingsProfile.h>\n#include <Columns\/ColumnString.h>\n#include <DataStreams\/OneBlockInputStream.h>\n#include <DataTypes\/DataTypeString.h>\n#include <Common\/StringUtils\/StringUtils.h>\n#include <Core\/Defines.h>\n#include <common\/range.h>\n#include <boost\/range\/algorithm\/sort.hpp>\n\n\nnamespace DB\n{\nnamespace ErrorCodes\n{\n    extern const int NOT_IMPLEMENTED;\n}\n\n\nnamespace\n{\n    ASTPtr getCreateQueryImpl(\n        const User & user,\n        const AccessControlManager * manager \/* not used if attach_mode == true *\/,\n        bool attach_mode)\n    {\n        auto query = std::make_shared<ASTCreateUserQuery>();\n        query->names = std::make_shared<ASTUserNamesWithHost>();\n        query->names->push_back(user.getName());\n        query->attach = attach_mode;\n\n        if (user.allowed_client_hosts != AllowedClientHosts::AnyHostTag{})\n            query->hosts = user.allowed_client_hosts;\n\n        if (user.default_roles != RolesOrUsersSet::AllTag{})\n        {\n            if (attach_mode)\n                query->default_roles = user.default_roles.toAST();\n            else\n                query->default_roles = user.default_roles.toASTWithNames(*manager);\n        }\n\n        if (user.authentication.getType() != Authentication::NO_PASSWORD)\n        {\n            query->authentication = user.authentication;\n            query->show_password = attach_mode; \/\/\/ We don't show password unless it's an ATTACH statement.\n        }\n\n        if (!user.settings.empty())\n        {\n            if (attach_mode)\n                query->settings = user.settings.toAST();\n            else\n                query->settings = user.settings.toASTWithNames(*manager);\n        }\n\n        if (user.grantees != RolesOrUsersSet::AllTag{})\n        {\n            if (attach_mode)\n                query->grantees = user.grantees.toAST();\n            else\n                query->grantees = user.grantees.toASTWithNames(*manager);\n            query->grantees->use_keyword_any = true;\n        }\n\n        if (!user.default_database.empty())\n        {\n            auto ast = std::make_shared<ASTDatabaseOrNone>();\n            ast->database_name = user.default_database;\n            query->default_database = ast;\n        }\n\n        return query;\n    }\n\n\n    ASTPtr getCreateQueryImpl(const Role & role, const AccessControlManager * manager, bool attach_mode)\n    {\n        auto query = std::make_shared<ASTCreateRoleQuery>();\n        query->names.emplace_back(role.getName());\n        query->attach = attach_mode;\n\n        if (!role.settings.empty())\n        {\n            if (attach_mode)\n                query->settings = role.settings.toAST();\n            else\n                query->settings = role.settings.toASTWithNames(*manager);\n        }\n\n        return query;\n    }\n\n\n    ASTPtr getCreateQueryImpl(const SettingsProfile & profile, const AccessControlManager * manager, bool attach_mode)\n    {\n        auto query = std::make_shared<ASTCreateSettingsProfileQuery>();\n        query->names.emplace_back(profile.getName());\n        query->attach = attach_mode;\n\n        if (!profile.elements.empty())\n        {\n            if (attach_mode)\n                query->settings = profile.elements.toAST();\n            else\n                query->settings = profile.elements.toASTWithNames(*manager);\n            if (query->settings)\n                query->settings->setUseInheritKeyword(true);\n        }\n\n        if (!profile.to_roles.empty())\n        {\n            if (attach_mode)\n                query->to_roles = profile.to_roles.toAST();\n            else\n                query->to_roles = profile.to_roles.toASTWithNames(*manager);\n        }\n\n        return query;\n    }\n\n\n    ASTPtr getCreateQueryImpl(\n        const Quota & quota,\n        const AccessControlManager * manager \/* not used if attach_mode == true *\/,\n        bool attach_mode)\n    {\n        auto query = std::make_shared<ASTCreateQuotaQuery>();\n        query->names.emplace_back(quota.getName());\n        query->attach = attach_mode;\n\n        if (quota.key_type != Quota::KeyType::NONE)\n            query->key_type = quota.key_type;\n\n        query->all_limits.reserve(quota.all_limits.size());\n\n        for (const auto & limits : quota.all_limits)\n        {\n            ASTCreateQuotaQuery::Limits create_query_limits;\n            create_query_limits.duration = limits.duration;\n            create_query_limits.randomize_interval = limits.randomize_interval;\n            for (auto resource_type : collections::range(Quota::MAX_RESOURCE_TYPE))\n                create_query_limits.max[resource_type] = limits.max[resource_type];\n            query->all_limits.push_back(create_query_limits);\n        }\n\n        if (!quota.to_roles.empty())\n        {\n            if (attach_mode)\n                query->roles = quota.to_roles.toAST();\n            else\n                query->roles = quota.to_roles.toASTWithNames(*manager);\n        }\n\n        return query;\n    }\n\n\n    ASTPtr getCreateQueryImpl(\n        const RowPolicy & policy,\n        const AccessControlManager * manager \/* not used if attach_mode == true *\/,\n        bool attach_mode)\n    {\n        auto query = std::make_shared<ASTCreateRowPolicyQuery>();\n        query->names = std::make_shared<ASTRowPolicyNames>();\n        query->names->name_parts.emplace_back(policy.getNameParts());\n        query->attach = attach_mode;\n\n        if (policy.isRestrictive())\n            query->is_restrictive = policy.isRestrictive();\n\n        for (auto type : collections::range(RowPolicy::MAX_CONDITION_TYPE))\n        {\n            const auto & condition = policy.conditions[static_cast<size_t>(type)];\n            if (!condition.empty())\n            {\n                ParserExpression parser;\n                ASTPtr expr = parseQuery(parser, condition, 0, DBMS_DEFAULT_MAX_PARSER_DEPTH);\n                query->conditions.emplace_back(type, std::move(expr));\n            }\n        }\n\n        if (!policy.to_roles.empty())\n        {\n            if (attach_mode)\n                query->roles = policy.to_roles.toAST();\n            else\n                query->roles = policy.to_roles.toASTWithNames(*manager);\n        }\n\n        return query;\n    }\n\n    ASTPtr getCreateQueryImpl(\n        const IAccessEntity & entity,\n        const AccessControlManager * manager \/* not used if attach_mode == true *\/,\n        bool attach_mode)\n    {\n        if (const User * user = typeid_cast<const User *>(&entity))\n            return getCreateQueryImpl(*user, manager, attach_mode);\n        if (const Role * role = typeid_cast<const Role *>(&entity))\n            return getCreateQueryImpl(*role, manager, attach_mode);\n        if (const RowPolicy * policy = typeid_cast<const RowPolicy *>(&entity))\n            return getCreateQueryImpl(*policy, manager, attach_mode);\n        if (const Quota * quota = typeid_cast<const Quota *>(&entity))\n            return getCreateQueryImpl(*quota, manager, attach_mode);\n        if (const SettingsProfile * profile = typeid_cast<const SettingsProfile *>(&entity))\n            return getCreateQueryImpl(*profile, manager, attach_mode);\n        throw Exception(entity.outputTypeAndName() + \": type is not supported by SHOW CREATE query\", ErrorCodes::NOT_IMPLEMENTED);\n    }\n\n    using EntityType = IAccessEntity::Type;\n}\n\n\nInterpreterShowCreateAccessEntityQuery::InterpreterShowCreateAccessEntityQuery(const ASTPtr & query_ptr_, ContextPtr context_)\n    : WithContext(context_), query_ptr(query_ptr_)\n{\n}\n\n\nBlockIO InterpreterShowCreateAccessEntityQuery::execute()\n{\n    BlockIO res;\n    res.in = executeImpl();\n    return res;\n}\n\n\nBlockInputStreamPtr InterpreterShowCreateAccessEntityQuery::executeImpl()\n{\n    \/\/\/ Build a create queries.\n    ASTs create_queries = getCreateQueries();\n\n    \/\/\/ Build the result column.\n    MutableColumnPtr column = ColumnString::create();\n    WriteBufferFromOwnString create_query_buf;\n    for (const auto & create_query : create_queries)\n    {\n        formatAST(*create_query, create_query_buf, false, true);\n        column->insert(create_query_buf.str());\n        create_query_buf.restart();\n    }\n\n    \/\/\/ Prepare description of the result column.\n    WriteBufferFromOwnString desc_buf;\n    const auto & show_query = query_ptr->as<const ASTShowCreateAccessEntityQuery &>();\n    formatAST(show_query, desc_buf, false, true);\n    String desc = desc_buf.str();\n    String prefix = \"SHOW \";\n    if (startsWith(desc, prefix))\n        desc = desc.substr(prefix.length()); \/\/\/ `desc` always starts with \"SHOW \", so we can trim this prefix.\n\n    return std::make_shared<OneBlockInputStream>(Block{{std::move(column), std::make_shared<DataTypeString>(), desc}});\n}\n\n\nstd::vector<AccessEntityPtr> InterpreterShowCreateAccessEntityQuery::getEntities() const\n{\n    auto & show_query = query_ptr->as<ASTShowCreateAccessEntityQuery &>();\n    const auto & access_control = getContext()->getAccessControlManager();\n    getContext()->checkAccess(getRequiredAccess());\n    show_query.replaceEmptyDatabase(getContext()->getCurrentDatabase());\n    std::vector<AccessEntityPtr> entities;\n\n    if (show_query.all)\n    {\n        auto ids = access_control.findAll(show_query.type);\n        for (const auto & id : ids)\n        {\n            if (auto entity = access_control.tryRead(id))\n                entities.push_back(entity);\n        }\n    }\n    else if (show_query.current_user)\n    {\n        if (auto user = getContext()->getUser())\n            entities.push_back(user);\n    }\n    else if (show_query.current_quota)\n    {\n        auto usage = getContext()->getQuotaUsage();\n        if (usage)\n            entities.push_back(access_control.read<Quota>(usage->quota_id));\n    }\n    else if (show_query.type == EntityType::ROW_POLICY)\n    {\n        auto ids = access_control.findAll<RowPolicy>();\n        if (show_query.row_policy_names)\n        {\n            for (const String & name : show_query.row_policy_names->toStrings())\n                entities.push_back(access_control.read<RowPolicy>(name));\n        }\n        else\n        {\n            for (const auto & id : ids)\n            {\n                auto policy = access_control.tryRead<RowPolicy>(id);\n                if (!policy)\n                    continue;\n                if (!show_query.short_name.empty() && (policy->getShortName() != show_query.short_name))\n                    continue;\n                if (show_query.database_and_table_name)\n                {\n                    const String & database = show_query.database_and_table_name->first;\n                    const String & table_name = show_query.database_and_table_name->second;\n                    if (!database.empty() && (policy->getDatabase() != database))\n                        continue;\n                    if (!table_name.empty() && (policy->getTableName() != table_name))\n                        continue;\n                }\n                entities.push_back(policy);\n            }\n        }\n    }\n    else\n    {\n        for (const String & name : show_query.names)\n            entities.push_back(access_control.read(access_control.getID(show_query.type, name)));\n    }\n\n    boost::range::sort(entities, IAccessEntity::LessByName{});\n    return entities;\n}\n\n\nASTs InterpreterShowCreateAccessEntityQuery::getCreateQueries() const\n{\n    auto entities = getEntities();\n\n    ASTs list;\n    const auto & access_control = getContext()->getAccessControlManager();\n    for (const auto & entity : entities)\n        list.push_back(getCreateQuery(*entity, access_control));\n\n    return list;\n}\n\n\nASTPtr InterpreterShowCreateAccessEntityQuery::getCreateQuery(const IAccessEntity & entity, const AccessControlManager & access_control)\n{\n    return getCreateQueryImpl(entity, &access_control, false);\n}\n\n\nASTPtr InterpreterShowCreateAccessEntityQuery::getAttachQuery(const IAccessEntity & entity)\n{\n    return getCreateQueryImpl(entity, nullptr, true);\n}\n\n\nAccessRightsElements InterpreterShowCreateAccessEntityQuery::getRequiredAccess() const\n{\n    const auto & show_query = query_ptr->as<const ASTShowCreateAccessEntityQuery &>();\n    AccessRightsElements res;\n    switch (show_query.type)\n    {\n        case EntityType::USER: res.emplace_back(AccessType::SHOW_USERS); return res;\n        case EntityType::ROLE: res.emplace_back(AccessType::SHOW_ROLES); return res;\n        case EntityType::SETTINGS_PROFILE: res.emplace_back(AccessType::SHOW_SETTINGS_PROFILES); return res;\n        case EntityType::ROW_POLICY: res.emplace_back(AccessType::SHOW_ROW_POLICIES); return res;\n        case EntityType::QUOTA: res.emplace_back(AccessType::SHOW_QUOTAS); return res;\n        case EntityType::MAX: break;\n    }\n    throw Exception(toString(show_query.type) + \": type is not supported by SHOW CREATE query\", ErrorCodes::NOT_IMPLEMENTED);\n}\n}\n","avg_line_length":34.857881137,"max_line_length":136,"alphanum_fraction":0.6407709414,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1730,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <unistd.h>\n#include <cctype>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n\n#include \"process.h\"\n#include \"linux_parser.h\"\n\nusing std::string;\nusing std::to_string;\nusing std::vector;\n\n\/\/TODO: Process constructor\nProcess::Process(int pid) {\n  pid_ = pid;\n  cpuUtil_ = Process::CpuUtilization(pid);\n  upTime_ = LinuxParser::UpTime(pid);\n}\n\n\/\/ TODO: Return this process's ID\nint Process::Pid() const { return pid_; }\n\n\/\/ TODO: Return this process's CPU utilization\nfloat Process::CpuUtilization() {\n  return cpuUtil_;\n}\n\nfloat Process::CpuUtilization(int pid) {\n  long procJiffies = LinuxParser::ActiveJiffies(pid);\n  long total = LinuxParser::ActiveJiffies() + LinuxParser::IdleJiffies();\n  float cpuUtil = float(procJiffies)\/float(total);\n  return cpuUtil;\n}\n\n\/\/ TODO: Return the command that generated this process\nstring Process::Command() { return LinuxParser::Command(pid_); }\n\n\/\/ TODO: Return this process's memory utilization\nstring Process::Ram() { \n  string ramString = LinuxParser::Ram(pid_);\n  long ramKB;\n  try {\n    ramKB = std::stol(ramString);\n  } catch(const std::invalid_argument) {\n    ramKB = 0;\n  }\n  long ramMB = ramKB\/1024;\n  return std::to_string(ramMB);\n}\n\n\/\/ TODO: Return the user (name) that generated this process\nstring Process::User() { \n  return LinuxParser::User(pid_);\n}\n\n\/\/ TODO: Return the age of this process (in seconds)\nlong int Process::UpTime() {\n  return upTime_;  \n}\n\n\/\/ TODO: Overload the \"less than\" comparison operator for Process objects\n\/\/ REMOVE: [[maybe_unused]] once you define the function\nbool Process::operator<(Process const& a) const { \n  return cpuUtil_ < a.cpuUtil_; \n  \/\/return upTime_ < a.upTime_;\n}","avg_line_length":24.7142857143,"max_line_length":73,"alphanum_fraction":0.7121387283,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2917,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Copyright (c) 2017 The NextON developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"uritests.h\"\n\n#include \"guiutil.h\"\n#include \"walletmodel.h\"\n\n#include <QUrl>\n\nvoid URITests::uriTests()\n{\n    SendCoinsRecipient rv;\n    QUrl uri;\n    uri.setUrl(QString(\"nxton:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?req-dontexist=\"));\n    QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));\n\n    uri.setUrl(QString(\"nxton:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?dontexist=\"));\n    QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));\n    QVERIFY(rv.address == QString(\"D72dLgywmL73JyTwQBfuU29CADz9yCJ99v\"));\n    QVERIFY(rv.label == QString());\n    QVERIFY(rv.amount == 0);\n\n    uri.setUrl(QString(\"nxton:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?label=Some Example Address\"));\n    QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));\n    QVERIFY(rv.address == QString(\"D72dLgywmL73JyTwQBfuU29CADz9yCJ99v\"));\n    QVERIFY(rv.label == QString(\"Some Example Address\"));\n    QVERIFY(rv.amount == 0);\n\n    uri.setUrl(QString(\"nxton:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=0.001\"));\n    QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));\n    QVERIFY(rv.address == QString(\"D72dLgywmL73JyTwQBfuU29CADz9yCJ99v\"));\n    QVERIFY(rv.label == QString());\n    QVERIFY(rv.amount == 100000);\n\n    uri.setUrl(QString(\"nxton:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=1.001\"));\n    QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));\n    QVERIFY(rv.address == QString(\"D72dLgywmL73JyTwQBfuU29CADz9yCJ99v\"));\n    QVERIFY(rv.label == QString());\n    QVERIFY(rv.amount == 100100000);\n\n    uri.setUrl(QString(\"nxton:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=100&label=Some Example\"));\n    QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));\n    QVERIFY(rv.address == QString(\"D72dLgywmL73JyTwQBfuU29CADz9yCJ99v\"));\n    QVERIFY(rv.amount == 10000000000LL);\n    QVERIFY(rv.label == QString(\"Some Example\"));\n\n    uri.setUrl(QString(\"nxton:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?message=Some Example Address\"));\n    QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));\n    QVERIFY(rv.address == QString(\"D72dLgywmL73JyTwQBfuU29CADz9yCJ99v\"));\n    QVERIFY(rv.label == QString());\n\n    QVERIFY(GUIUtil::parseBitcoinURI(\"nxton:\/\/D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?message=Some Example Address\", &rv));\n    QVERIFY(rv.address == QString(\"D72dLgywmL73JyTwQBfuU29CADz9yCJ99v\"));\n    QVERIFY(rv.label == QString());\n\n    uri.setUrl(QString(\"nxton:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?req-message=Some Example Address\"));\n    QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));\n\n    uri.setUrl(QString(\"nxton:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=1,000&label=Some Example\"));\n    QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));\n\n    uri.setUrl(QString(\"nxton:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=1,000.0&label=Some Example\"));\n    QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));\n}\n","avg_line_length":42.8970588235,"max_line_length":118,"alphanum_fraction":0.7363729859,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":14771,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":4.0,"content":"\/*\r\n  ==============================================================================\r\n\r\n  This is an automatically generated GUI class created by the Introjucer!\r\n\r\n  Be careful when adding custom code to these files, as only the code within\r\n  the \"\/\/[xyz]\" and \"\/\/[\/xyz]\" sections will be retained when the file is loaded\r\n  and re-saved.\r\n\r\n  Created with Introjucer version: 3.1.0\r\n\r\n  ------------------------------------------------------------------------------\r\n\r\n  The Introjucer is part of the JUCE library - \"Jules' Utility Class Extensions\"\r\n  Copyright 2004-13 by Raw Material Software Ltd.\r\n\r\n  ==============================================================================\r\n*\/\r\n\r\n\/\/[Headers] You can add your own extra header files here...\r\n\/\/[\/Headers]\r\n\r\n#include \"PluginEditor.h\"\r\n\r\n\r\n\/\/[MiscUserDefs] You can add your own user definitions and misc code here...\r\n\/\/[\/MiscUserDefs]\r\n\r\n\/\/==============================================================================\r\nPanoramaAudioProcessorEditor::PanoramaAudioProcessorEditor (PanoramaAudioProcessor& ownerFilter)\r\n    : AudioProcessorEditor(ownerFilter)\r\n{\r\n    addAndMakeVisible (panSld = new Slider (\"Pan\"));\r\n    panSld->setRange (-100, 100, 1);\r\n    panSld->setSliderStyle (Slider::RotaryHorizontalVerticalDrag);\r\n    panSld->setTextBoxStyle (Slider::TextBoxBelow, false, 40, 20);\r\n    panSld->setColour (Slider::backgroundColourId, Colour (0x00ffffff));\r\n    panSld->setColour (Slider::thumbColourId, Colours::white);\r\n    panSld->setColour (Slider::trackColourId, Colour (0x00ffffff));\r\n    panSld->setColour (Slider::rotarySliderFillColourId, Colour (0x00c8c8c8));\r\n    panSld->addListener (this);\r\n\r\n    addAndMakeVisible (Title = new Label (\"Title\",\r\n                                          TRANS(\"Panorama\")));\r\n    Title->setFont (Font (\"Lucida Console\", 36.60f, Font::plain));\r\n    Title->setJustificationType (Justification::centred);\r\n    Title->setEditable (false, false, false);\r\n    Title->setColour (Label::textColourId, Colours::white);\r\n    Title->setColour (TextEditor::textColourId, Colours::black);\r\n    Title->setColour (TextEditor::backgroundColourId, Colour (0x00000000));\r\n\r\n    addAndMakeVisible (algorithmSelect = new ComboBox (\"Algorithm\"));\r\n    algorithmSelect->setEditableText (false);\r\n    algorithmSelect->setJustificationType (Justification::centredLeft);\r\n    algorithmSelect->setTextWhenNothingSelected (String::empty);\r\n    algorithmSelect->setTextWhenNoChoicesAvailable (TRANS(\"(no choices)\"));\r\n    algorithmSelect->addItem (TRANS(\"Linear Crossfade\"), 1);\r\n    algorithmSelect->addItem (TRANS(\"Equal Power\"), 2);\r\n    algorithmSelect->addItem (TRANS(\"Speaker-to-Speaker\"), 3);\r\n    algorithmSelect->addListener (this);\r\n\r\n    addAndMakeVisible (panLawSld = new Slider (\"Pan Law\"));\r\n    panLawSld->setRange (0, 10, 0.1);\r\n    panLawSld->setSliderStyle (Slider::LinearHorizontal);\r\n    panLawSld->setTextBoxStyle (Slider::TextBoxRight, false, 40, 20);\r\n    panLawSld->setColour (Slider::thumbColourId, Colour (0xff909090));\r\n    panLawSld->addListener (this);\r\n\r\n    addAndMakeVisible (panLawEnabledBtn = new ToggleButton (\"Pan Law Enabled\"));\r\n    panLawEnabledBtn->addListener (this);\r\n    panLawEnabledBtn->setToggleState (true, dontSendNotification);\r\n    panLawEnabledBtn->setColour (ToggleButton::textColourId, Colours::white);\r\n\r\n    addAndMakeVisible (bypassBtn = new ToggleButton (\"Bypass\"));\r\n    bypassBtn->addListener (this);\r\n    bypassBtn->setColour (ToggleButton::textColourId, Colours::white);\r\n\r\n    addAndMakeVisible (label = new Label (\"new label\",\r\n                                          TRANS(\"Pan Law\\n\")));\r\n    label->setFont (Font (24.10f, Font::plain));\r\n    label->setJustificationType (Justification::centredLeft);\r\n    label->setEditable (false, false, false);\r\n    label->setColour (Label::textColourId, Colours::white);\r\n    label->setColour (TextEditor::textColourId, Colours::black);\r\n    label->setColour (TextEditor::backgroundColourId, Colour (0x00000000));\r\n\r\n    addAndMakeVisible (label2 = new Label (\"new label\",\r\n                                           TRANS(\"Algorithm\\n\")));\r\n    label2->setFont (Font (24.00f, Font::plain));\r\n    label2->setJustificationType (Justification::centred);\r\n    label2->setEditable (false, false, false);\r\n    label2->setColour (Label::textColourId, Colours::white);\r\n    label2->setColour (TextEditor::textColourId, Colours::black);\r\n    label2->setColour (TextEditor::backgroundColourId, Colour (0x00000000));\r\n\r\n    addAndMakeVisible (label3 = new Label (\"new label\",\r\n                                           TRANS(\"dB\")));\r\n    label3->setFont (Font (15.00f, Font::plain));\r\n    label3->setJustificationType (Justification::centredLeft);\r\n    label3->setEditable (false, false, false);\r\n    label3->setColour (Label::textColourId, Colours::white);\r\n    label3->setColour (TextEditor::textColourId, Colours::black);\r\n    label3->setColour (TextEditor::backgroundColourId, Colour (0x00000000));\r\n\r\n\r\n    \/\/[UserPreSize]\r\n    \/\/[\/UserPreSize]\r\n\r\n    setSize (296, 424);\r\n\r\n\r\n    \/\/[Constructor] You can add your own custom stuff here..\r\n    startTimer(30);\r\n\r\n    \/\/Set double-click return values\r\n    panSld->setDoubleClickReturnValue(true, 0);\r\n\r\n\r\n    \/\/Force a parameter reset upon re-opening.\r\n    ownerFilter.requestUIUpdate();\r\n    timerCallback();\r\n    \/\/[\/Constructor]\r\n}\r\n\r\nPanoramaAudioProcessorEditor::~PanoramaAudioProcessorEditor()\r\n{\r\n    \/\/[Destructor_pre]. You can add your own custom destruction code here..\r\n    \/\/[\/Destructor_pre]\r\n\r\n    panSld = nullptr;\r\n    Title = nullptr;\r\n    algorithmSelect = nullptr;\r\n    panLawSld = nullptr;\r\n    panLawEnabledBtn = nullptr;\r\n    bypassBtn = nullptr;\r\n    label = nullptr;\r\n    label2 = nullptr;\r\n    label3 = nullptr;\r\n\r\n\r\n    \/\/[Destructor]. You can add your own custom destruction code here..\r\n    \/\/[\/Destructor]\r\n}\r\n\r\n\/\/==============================================================================\r\nvoid PanoramaAudioProcessorEditor::paint (Graphics& g)\r\n{\r\n    \/\/[UserPrePaint] Add your own custom painting code here..\r\n    \/\/[\/UserPrePaint]\r\n\r\n    g.fillAll (Colour (0xff6900cb));\r\n\r\n    \/\/[UserPaint] Add your own custom painting code here..\r\n    \/\/[\/UserPaint]\r\n}\r\n\r\nvoid PanoramaAudioProcessorEditor::resized()\r\n{\r\n    \/\/[UserPreResize] Add your own custom resize code here..\r\n    \/\/[\/UserPreResize]\r\n\r\n    panSld->setBounds (40, 80, 208, 136);\r\n    Title->setBounds (40, 16, 216, 48);\r\n    algorithmSelect->setBounds (40, 264, 208, 24);\r\n    panLawSld->setBounds (40, 320, 184, 24);\r\n    panLawEnabledBtn->setBounds (40, 352, 150, 24);\r\n    bypassBtn->setBounds (40, 376, 150, 24);\r\n    label->setBounds (40, 296, 96, 24);\r\n    label2->setBounds (40, 232, 112, 24);\r\n    label3->setBounds (224, 320, 31, 24);\r\n    \/\/[UserResized] Add your own custom resize handling here..\r\n    \/\/[\/UserResized]\r\n}\r\n\r\nvoid PanoramaAudioProcessorEditor::sliderValueChanged (Slider* sliderThatWasMoved)\r\n{\r\n    \/\/[UsersliderValueChanged_Pre]\r\n    PanoramaAudioProcessor* ourProcessor = getProcessor();\r\n    \/\/[\/UsersliderValueChanged_Pre]\r\n\r\n    if (sliderThatWasMoved == panSld)\r\n    {\r\n        \/\/[UserSliderCode_panSld] -- add your slider handling code here..\r\n        ourProcessor->setParameter(PanoramaAudioProcessor::pan, (float) panSld->getValue());\r\n        \/\/[\/UserSliderCode_panSld]\r\n    }\r\n    else if (sliderThatWasMoved == panLawSld)\r\n    {\r\n        \/\/[UserSliderCode_panLawSld] -- add your slider handling code here..\r\n        ourProcessor->setParameter(PanoramaAudioProcessor::panLaw, (float) panLawSld->getValue());\r\n        \/\/[\/UserSliderCode_panLawSld]\r\n    }\r\n\r\n    \/\/[UsersliderValueChanged_Post]\r\n    \/\/[\/UsersliderValueChanged_Post]\r\n}\r\n\r\nvoid PanoramaAudioProcessorEditor::comboBoxChanged (ComboBox* comboBoxThatHasChanged)\r\n{\r\n    \/\/[UsercomboBoxChanged_Pre]\r\n    PanoramaAudioProcessor* ourProcessor = getProcessor();\r\n    \/\/[\/UsercomboBoxChanged_Pre]\r\n\r\n    if (comboBoxThatHasChanged == algorithmSelect)\r\n    {\r\n        \/\/[UserComboBoxCode_algorithmSelect] -- add your combo box handling code here..\r\n        ourProcessor->setParameter(PanoramaAudioProcessor::algorithm, (float) algorithmSelect->getSelectedItemIndex());\r\n        \/\/[\/UserComboBoxCode_algorithmSelect]\r\n    }\r\n\r\n    \/\/[UsercomboBoxChanged_Post]\r\n    \/\/[\/UsercomboBoxChanged_Post]\r\n}\r\n\r\nvoid PanoramaAudioProcessorEditor::buttonClicked (Button* buttonThatWasClicked)\r\n{\r\n    \/\/[UserbuttonClicked_Pre]\r\n    PanoramaAudioProcessor* ourProcessor = getProcessor();\r\n    \/\/[\/UserbuttonClicked_Pre]\r\n\r\n    if (buttonThatWasClicked == panLawEnabledBtn)\r\n    {\r\n        \/\/[UserButtonCode_panLawEnabledBtn] -- add your button handler code here..\r\n        ourProcessor->setParameter(PanoramaAudioProcessor::panLawEnabled, (float) panLawEnabledBtn->getToggleState());\r\n        \/\/[\/UserButtonCode_panLawEnabledBtn]\r\n    }\r\n    else if (buttonThatWasClicked == bypassBtn)\r\n    {\r\n        \/\/[UserButtonCode_bypassBtn] -- add your button handler code here..\r\n        ourProcessor->setParameter(PanoramaAudioProcessor::masterBypass, (float) bypassBtn->getToggleState());\r\n        \/\/[\/UserButtonCode_bypassBtn]\r\n    }\r\n\r\n    \/\/[UserbuttonClicked_Post]\r\n    \/\/[\/UserbuttonClicked_Post]\r\n}\r\n\r\n\r\n\r\n\/\/[MiscUserCode] You can add your own definitions of your custom methods or any other code here...\r\nvoid PanoramaAudioProcessorEditor::timerCallback() {\r\n    PanoramaAudioProcessor* ourProcessor = getProcessor();\r\n\r\n    \/\/Perform necessary UI updates\r\n    if(ourProcessor->needsUIUpdate()) {\r\n        \/\/Update panSld's state\r\n        panSld->setValue(ourProcessor->getParameter(PanoramaAudioProcessor::pan), dontSendNotification);\r\n\r\n        \/\/Update panLawSld's state\r\n        panLawSld->setValue(ourProcessor->getParameter(PanoramaAudioProcessor::panLaw), dontSendNotification);\r\n\r\n        \/\/Update panLawEnabledBtn's state\r\n        panLawEnabledBtn->setToggleState(1.0f == ourProcessor->getParameter(PanoramaAudioProcessor::panLawEnabled), dontSendNotification);\r\n\r\n        \/\/Update bypassBtn's state\r\n        bypassBtn->setToggleState(1.0f == ourProcessor->getParameter(PanoramaAudioProcessor::masterBypass), dontSendNotification);\r\n\r\n        \/\/update algorithmSelect's state\r\n        algorithmSelect->setSelectedItemIndex((int) ourProcessor->getParameter(PanoramaAudioProcessor::algorithm), dontSendNotification);\r\n\r\n        \/\/We're done; clear the UI update flag\r\n        ourProcessor->clearUIUpdateFlag();\r\n    }\r\n}\r\n\/\/[\/MiscUserCode]\r\n\r\n\r\n\/\/==============================================================================\r\n#if 0\r\n\/*  -- Introjucer information section --\r\n\r\n    This is where the Introjucer stores the metadata that describe this GUI layout, so\r\n    make changes in here at your peril!\r\n\r\nBEGIN_JUCER_METADATA\r\n\r\n<JUCER_COMPONENT documentType=\"Component\" className=\"PanoramaAudioProcessorEditor\"\r\n                 componentName=\"\" parentClasses=\"public AudioProcessorEditor, public Timer\"\r\n                 constructorParams=\"PanoramaAudioProcessor&amp; ownerFilter\" variableInitialisers=\"AudioProcessorEditor(ownerFilter)\"\r\n                 snapPixels=\"8\" snapActive=\"1\" snapShown=\"1\" overlayOpacity=\"0.330\"\r\n                 fixedSize=\"0\" initialWidth=\"296\" initialHeight=\"424\">\r\n  <BACKGROUND backgroundColour=\"ff6900cb\">\r\n    <RECT pos=\"-8 -8 296 424\" fill=\"solid: e2ccd6\" hasStroke=\"0\"\/>\r\n  <\/BACKGROUND>\r\n  <SLIDER name=\"Pan\" id=\"4078155c81af598b\" memberName=\"panSld\" virtualName=\"\"\r\n          explicitFocusOrder=\"0\" pos=\"40 80 208 136\" bkgcol=\"ffffff\" thumbcol=\"ffffffff\"\r\n          trackcol=\"ffffff\" rotarysliderfill=\"c8c8c8\" min=\"-100\" max=\"100\"\r\n          int=\"1\" style=\"RotaryHorizontalVerticalDrag\" textBoxPos=\"TextBoxBelow\"\r\n          textBoxEditable=\"1\" textBoxWidth=\"40\" textBoxHeight=\"20\" skewFactor=\"1\"\/>\r\n  <LABEL name=\"Title\" id=\"e590c60e54b0ea8c\" memberName=\"Title\" virtualName=\"\"\r\n         explicitFocusOrder=\"0\" pos=\"40 16 216 48\" textCol=\"ffffffff\"\r\n         edTextCol=\"ff000000\" edBkgCol=\"0\" labelText=\"Panorama\" editableSingleClick=\"0\"\r\n         editableDoubleClick=\"0\" focusDiscardsChanges=\"0\" fontname=\"Lucida Console\"\r\n         fontsize=\"36.600000000000001\" bold=\"0\" italic=\"0\" justification=\"36\"\/>\r\n  <COMBOBOX name=\"Algorithm\" id=\"f09b7b27668d5441\" memberName=\"algorithmSelect\"\r\n            virtualName=\"\" explicitFocusOrder=\"0\" pos=\"40 264 208 24\" editable=\"0\"\r\n            layout=\"33\" items=\"Linear Crossfade&#10;Equal Power&#10;Speaker-to-Speaker\"\r\n            textWhenNonSelected=\"\" textWhenNoItems=\"(no choices)\"\/>\r\n  <SLIDER name=\"Pan Law\" id=\"1c663294ce72c0ec\" memberName=\"panLawSld\" virtualName=\"\"\r\n          explicitFocusOrder=\"0\" pos=\"40 320 184 24\" thumbcol=\"ff909090\"\r\n          min=\"0\" max=\"10\" int=\"0.10000000000000001\" style=\"LinearHorizontal\"\r\n          textBoxPos=\"TextBoxRight\" textBoxEditable=\"1\" textBoxWidth=\"40\"\r\n          textBoxHeight=\"20\" skewFactor=\"1\"\/>\r\n  <TOGGLEBUTTON name=\"Pan Law Enabled\" id=\"f1a36e1844919f1d\" memberName=\"panLawEnabledBtn\"\r\n                virtualName=\"\" explicitFocusOrder=\"0\" pos=\"40 352 150 24\" txtcol=\"ffffffff\"\r\n                buttonText=\"Pan Law Enabled\" connectedEdges=\"0\" needsCallback=\"1\"\r\n                radioGroupId=\"0\" state=\"1\"\/>\r\n  <TOGGLEBUTTON name=\"Bypass\" id=\"d9ca914f9b3df8eb\" memberName=\"bypassBtn\" virtualName=\"\"\r\n                explicitFocusOrder=\"0\" pos=\"40 376 150 24\" txtcol=\"ffffffff\"\r\n                buttonText=\"Bypass\" connectedEdges=\"0\" needsCallback=\"1\" radioGroupId=\"0\"\r\n                state=\"0\"\/>\r\n  <LABEL name=\"new label\" id=\"99d93ba3be76a485\" memberName=\"label\" virtualName=\"\"\r\n         explicitFocusOrder=\"0\" pos=\"40 296 96 24\" textCol=\"ffffffff\"\r\n         edTextCol=\"ff000000\" edBkgCol=\"0\" labelText=\"Pan Law&#10;\" editableSingleClick=\"0\"\r\n         editableDoubleClick=\"0\" focusDiscardsChanges=\"0\" fontname=\"Default font\"\r\n         fontsize=\"24.100000000000001\" bold=\"0\" italic=\"0\" justification=\"33\"\/>\r\n  <LABEL name=\"new label\" id=\"8b07e0827979f5b8\" memberName=\"label2\" virtualName=\"\"\r\n         explicitFocusOrder=\"0\" pos=\"40 232 112 24\" textCol=\"ffffffff\"\r\n         edTextCol=\"ff000000\" edBkgCol=\"0\" labelText=\"Algorithm&#10;\"\r\n         editableSingleClick=\"0\" editableDoubleClick=\"0\" focusDiscardsChanges=\"0\"\r\n         fontname=\"Default font\" fontsize=\"24\" bold=\"0\" italic=\"0\" justification=\"36\"\/>\r\n  <LABEL name=\"new label\" id=\"85ca32ba7f1f6679\" memberName=\"label3\" virtualName=\"\"\r\n         explicitFocusOrder=\"0\" pos=\"224 320 31 24\" textCol=\"ffffffff\"\r\n         edTextCol=\"ff000000\" edBkgCol=\"0\" labelText=\"dB\" editableSingleClick=\"0\"\r\n         editableDoubleClick=\"0\" focusDiscardsChanges=\"0\" fontname=\"Default font\"\r\n         fontsize=\"15\" bold=\"0\" italic=\"0\" justification=\"33\"\/>\r\n<\/JUCER_COMPONENT>\r\n\r\nEND_JUCER_METADATA\r\n*\/\r\n#endif\r\n\r\n\r\n\/\/[EndFile] You can add extra defines here...\r\n\/\/[\/EndFile]\r\n","avg_line_length":43.9613095238,"max_line_length":139,"alphanum_fraction":0.6589262745,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":153,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <stdio.h>\n\nint main() {\n\tint *p = new int[1000000000];\n\tp[0] = 1;\n\tp[1000] = 2;\n\tp[1000000] = 3;\n\tp[1000000000-1] = 4;\n\tgetchar();\n\treturn 0;\n}\n","avg_line_length":12.75,"max_line_length":30,"alphanum_fraction":0.5555555556,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4455,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":293.0,"content":"\/*\nCopyright 2020-2021 <Pierre Constantineau>\n\n3-Clause BSD License\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. 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.\n\n3. 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.\n\nTHIS 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 \nA 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 \nLIMITED 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 \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n#include \"HID.h\"\n\n\nuint16_t hid_GetMediaUsageCode(uint16_t keycode)\n{\n  uint16_t usagecode = 0;\n\n  switch (keycode)\n  {\n    case KC_SYSTEM_POWER: usagecode = HID_USAGE_CONSUMER_POWER; break;\n    case KC_SYSTEM_RESET: usagecode = HID_USAGE_CONSUMER_RESET; break;\n    case KC_SYSTEM_SLEEP: usagecode = HID_USAGE_CONSUMER_SLEEP; break;\n    case KC_DISPLAY_BRIGHTI: usagecode = HID_USAGE_CONSUMER_BRIGHTNESS_INCREMENT; break;\n    case KC_DISPLAY_BRIGHTD: usagecode = HID_USAGE_CONSUMER_BRIGHTNESS_DECREMENT; break;\n    case KC_RADIO_CONTROL: usagecode = HID_USAGE_CONSUMER_WIRELESS_RADIO_CONTROLS; break;\n    case KC_RADIO_BUTTONS: usagecode = HID_USAGE_CONSUMER_WIRELESS_RADIO_BUTTONS; break;\n    case KC_RADIO_LED: usagecode = HID_USAGE_CONSUMER_WIRELESS_RADIO_LED; break;\n    case KC_RADIO_SWITCH: usagecode = HID_USAGE_CONSUMER_WIRELESS_RADIO_SLIDER_SWITCH; break;\n    case KC_MEDIA_PLAY_PAUSE: usagecode = HID_USAGE_CONSUMER_PLAY_PAUSE; break;\n    case KC_MEDIA_NEXT_TRACK: usagecode = HID_USAGE_CONSUMER_SCAN_NEXT; break;\n    case KC_MEDIA_PREV_TRACK: usagecode = HID_USAGE_CONSUMER_SCAN_PREVIOUS; break;\n    case KC_MEDIA_STOP: usagecode = HID_USAGE_CONSUMER_STOP; break;\n    case KC_AUDIO_VOL: usagecode = HID_USAGE_CONSUMER_VOLUME; break;\n    case KC_AUDIO_MUTE: usagecode = HID_USAGE_CONSUMER_MUTE; break;\n    case KC_AUDIO_BASS: usagecode = HID_USAGE_CONSUMER_BASS; break;\n    case KC_AUDIO_TREBLE: usagecode = HID_USAGE_CONSUMER_TREBLE; break;\n    case KC_AUDIO_BASS_BOOST: usagecode = HID_USAGE_CONSUMER_BASS_BOOST; break;\n    case KC_AUDIO_VOL_UP: usagecode = HID_USAGE_CONSUMER_VOLUME_INCREMENT; break;\n    case KC_AUDIO_VOL_DOWN: usagecode = HID_USAGE_CONSUMER_VOLUME_DECREMENT; break;\n    case KC_AUDIO_BASS_UP: usagecode = HID_USAGE_CONSUMER_BASS_INCREMENT; break;\n    case KC_AUDIO_BASS_DOWN: usagecode = HID_USAGE_CONSUMER_BASS_DECREMENT; break;\n    case KC_AUDIO_TREBLE_UP: usagecode = HID_USAGE_CONSUMER_TREBLE_INCREMENT; break;\n    case KC_AUDIO_TREBLE_DOWN: usagecode = HID_USAGE_CONSUMER_TREBLE_DECREMENT; break;\n    case KC_MSEL: usagecode = HID_USAGE_CONSUMER_AL_CONSUMER_CONTROL_CONFIGURATION; break;\n    case KC_WWW: usagecode = HID_USAGE_CONSUMER_AL_EMAIL_READER; break;\n    case KC_CALCULATOR: usagecode = HID_USAGE_CONSUMER_AL_CALCULATOR; break;\n    case KC_MYCM: usagecode = HID_USAGE_CONSUMER_AL_LOCAL_BROWSER; break;\n\n    case KC_WWW_SEARCH: usagecode = HID_USAGE_CONSUMER_AC_SEARCH; break;\n    case KC_WWW_HOME: usagecode = HID_USAGE_CONSUMER_AC_HOME; break;\n    case KC_WWW_BACK: usagecode = HID_USAGE_CONSUMER_AC_BACK; break;\n    case KC_WWW_FORWARD: usagecode = HID_USAGE_CONSUMER_AC_FORWARD; break;\n    case KC_WWW_STOP: usagecode = HID_USAGE_CONSUMER_AC_STOP; break;\n    case KC_WWW_REFRESH: usagecode = HID_USAGE_CONSUMER_AC_REFRESH; break;\n    case KC_WWW_FAVORITES: usagecode = HID_USAGE_CONSUMER_AC_BOOKMARKS; break;\n    case KC_AC_PAN: usagecode = HID_USAGE_CONSUMER_AC_PAN; break;\n  }\n  return usagecode;\n  }","avg_line_length":65.5147058824,"max_line_length":208,"alphanum_fraction":0.8132435466,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4998,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\ufeff\/\/\n\/\/ Created by cc on 18-12-17.\n\/\/\n\n#include \"ListItemView.h\"\n#include <QHBoxLayout>\n#include <QPainter>\n#include <QFile>\n#include <QEvent>\n#include <QtWidgets\/QListView>\n#include \"AddressBookPanel.h\"\n#include \"..\/UICom\/qimage\/qimage.h\"\n#include \"..\/UICom\/StyleDefine.h\"\n#include \"..\/Platform\/AppSetting.h\"\n\n#define HEAD_WIDTH 22\n\n\/**\/\nusing namespace QTalk;\nListItemDelegate::ListItemDelegate(QObject *parent )\n    : QStyledItemDelegate(parent)\n{\n\n}\n\nListItemDelegate::~ListItemDelegate() {\n\n}\n\nQSize ListItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const {\n    return {option.widget->width(), 40};\n}\n\nvoid ListItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {\n    QStyledItemDelegate::paint(painter, option, index);\n\n    painter->save();\n    painter->setRenderHint(QPainter::TextAntialiasing);\n    QRect rect = option.rect;\n    if (option.state & QStyle::State_Selected)\n        painter->fillRect(rect, StyleDefine::instance().getNavSelectColor());\n    else\n        painter->fillRect(rect, StyleDefine::instance().getNavNormalColor());\n    QString strText = index.data(EM_DATA_TYPE_TEXT).toString();\n    painter->setPen(StyleDefine::instance().getAdrNameFontColor());\n    QTalk::setPainterFont(painter, AppSetting::instance().getFontLevel());\n    painter->drawText(QRect(rect.x() + 65, rect.y(), rect.width() - 65, rect.height()), Qt::AlignVCenter, strText);\n    QString headPath = index.data(EM_DATA_TYPE_ICON).toString();\n    painter->setRenderHints(QPainter::Antialiasing, true);\n    if(!QFile(headPath).isOpen())\n    {\n        int dpi = QTalk::qimage::instance().dpi();\n        QPixmap pixmap = QTalk::qimage::instance().loadPixmap(headPath, true, true, HEAD_WIDTH * dpi, HEAD_WIDTH * dpi);\n        QPainterPath path;\n        QRect headRect(rect.x() + 30, rect.y() + 8, HEAD_WIDTH, HEAD_WIDTH);\n        path.addEllipse(headRect);\n        painter->setClipPath(path);\n        painter->drawPixmap(headRect, pixmap);\n    }\n    painter->restore();\n}\n\nbool ListItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option,\n                                   const QModelIndex &index) {\n\n    if(event->type() == QEvent::MouseButtonPress)\n    {\n        QString id = model->data(index, EM_DATA_TYPE_ID).toString();\n        QUInt32 type = model->data(index, EM_DATA_TYPE_TYPE).toUInt();\n        emit itemClicked(id, type);\n    }\n    return QStyledItemDelegate::editorEvent(event, model, option, index);\n}\n\n\/**\/\nListItemView::ListItemView(AddressBookPanel* _panel, QWidget *parent)\n    :QFrame(parent)\n    , _pLstView(nullptr)\n    , _pModel(nullptr)\n    , _pDelegate(nullptr)\n    , _mainPanel(_panel)\n{\n    setObjectName(\"ListItemView\");\n\n    _pLstView = new QListView(this);\n    _pLstView->setObjectName(\"ListItemViewListView\");\n    _pModel = new QStandardItemModel(this);\n    _pDelegate = new ListItemDelegate(this);\n\n    _pLstView->setEditTriggers(QAbstractItemView::NoEditTriggers);\n    _pLstView->setFrameShape(QFrame::NoFrame);\n    \/\/_pLstView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n    _pLstView->setModel(_pModel);\n    _pLstView->setItemDelegate(_pDelegate);\n    _pLstView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n    _pLstView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);\n    _pLstView->setResizeMode(QListView::Adjust);\n\n    auto* layout = new QHBoxLayout(this);\n    layout->setMargin(0);\n    layout->setSpacing(0);\n    layout->addWidget(_pLstView);\n\n    connect(_pDelegate, &ListItemDelegate::itemClicked, _mainPanel, &AddressBookPanel::onListItemClicked);\n   \/\/ connect(this, &ListItemView::addItemSignal, this, &ListItemView::addItem);\n  \/\/  connect(this, &ListItemView::removeItemSignal, this, &ListItemView::removeItem);\n\n}\n\nListItemView::~ListItemView()\n= default;\n\nvoid ListItemView::addItem(const QString &id, const QUInt8& type, const QString &icon, const QString& name)\n{\n    if(!_items.contains(id))\n    {\n        auto item = new QStandardItem;\n        item->setData(id, EM_DATA_TYPE_ID);\n        item->setData(icon, EM_DATA_TYPE_ICON);\n        item->setData(name, EM_DATA_TYPE_TEXT);\n        item->setData(type, EM_DATA_TYPE_TYPE);\n\n        _pModel->appendRow(item);\n\n        QMutexLocker locker(&_mutex);\n        _items[id] = item;\n\n        _pLstView->update();\n    }\n}\n\nvoid ListItemView::removeItem(const QString &id)\n{\n    if(_items.contains(id))\n    {\n        \/\/QMutexLocker locker(&_mutex);\n        QStandardItem *item = _items[id];\n        _pModel->removeRow(item->row());\n        _items.remove(id);\n        _pLstView->update();\n    }\n}\n\nvoid ListItemView::resetHeight(int parentH, int FixedH)\n{\n    int itemH = _items.size() * 40;\n    int maxH = parentH - FixedH;\n    if(itemH > maxH)\n        this->setFixedHeight(maxH);\n    else\n        this->setFixedHeight(itemH);\n}\n\nvoid ListItemView::clearSelection()\n{\n    if(_pLstView)\n    {\n        _pLstView->clearSelection();\n    }\n}\n","avg_line_length":31.0434782609,"max_line_length":120,"alphanum_fraction":0.6868747499,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":788,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <bits\/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int, int> P;\ntypedef long long ll;\n#define rep(i, n) for(int i=0;i<n;i++)\n#define rep2(i, m, n) for(int i=m;i<n;i++)\n#define rrep(i, n, m) for(int i=n;i>=m;i--)\nusing Graph = vector<vector<int>>;\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\nconst ll MOD = 1000000007;\n#ifdef __DEBUG\n\n#include \"cpp-pyprint\/pyprint.h\"\n\n#endif\n\nvoid Main() {\n    ll A, K;\n    cin >> A >> K;\n    ll ans = 0;\n    ll tmp =pow(10, 12);\n    if (K == 0) {\n        cout <<  2 * tmp - A << endl;\n        return;\n    }\n    while (A < 2 * tmp) {\n        A += 1 + K*A;\n        ans ++;\n    }\n    cout << ans << endl;\n\n\n}\n\nint main() {\n    cin.tie(0);\n    ios::sync_with_stdio(false);\n    cout << fixed << setprecision(15);\n    Main();\n}\n","avg_line_length":17.9090909091,"max_line_length":43,"alphanum_fraction":0.5139593909,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":360,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/\u3010P3742\u3011umi\u7684\u51fd\u6570 - \u6d1b\u8c37 - 0 \n#include <string>\n#include <iostream> \n#include <algorithm>\n\nint main() {\n\tint l;\n\tstd::cin >> l;\n\tstd::string x, y, z;\n\tstd::cin >> x >> y;\n\tbool ok = true;\n\tfor (register unsigned i = 0; i < x.size(); ++i) {\n\t\tif (y[i] > x[i]) ok = false;\n\t}\n\tif (ok)\t {\n\t\tstd::cout << y << std::endl;\n\t}\n\telse {\n\t\tstd::cout << -1 << std::endl;\n\t}\n}","avg_line_length":17.1428571429,"max_line_length":51,"alphanum_fraction":0.5138888889,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":20486,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n * Copyright 2019 - 2020  Simone Campanoni\n *\n * 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:\n\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\n * 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. \n * 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.\n *\/\n#include \"Mem2RegNonAlloca.hpp\"\n\nusing namespace llvm;\nusing namespace llvm::noelle;\n\nMem2RegNonAlloca::Mem2RegNonAlloca (LoopDependenceInfo const &LDI, Noelle &noelle)\n  : LDI{LDI}, invariants{*LDI.getInvariantManager()}, noelle{noelle} {\n}\n\nbool Mem2RegNonAlloca::promoteMemoryToRegister () {\n\n  auto loopStructure = LDI.getLoopStructure();\n  if (noelle.getVerbosity() >= Verbosity::Maximal) {\n    auto terminator = loopStructure->getHeader()->getTerminator();\n    if (!terminator) return false;\n    terminator->print(errs() << \"Mem2Reg: Checking loop: \"); errs() << \"\\n\";\n  }\n\n  \/*\n   * Ensure the function does not return from within the loop\n   *\/\n  for (auto B : loopStructure->getBasicBlocks()) {\n    auto terminator = B->getTerminator();\n    if (!terminator) {\n      return false;\n    }\n    if (isa<ReturnInst>(terminator)) {\n      return false;\n    }\n    if (isa<InvokeInst>(terminator)){\n      return false;\n    }\n  }\n\n  auto singleMemoryLocationsBySCC = findSCCsWithSingleMemoryLocations();\n  for (auto memoryAndSCCPair : singleMemoryLocationsBySCC) {\n    auto memoryInst = memoryAndSCCPair.first;\n    auto memorySCC = memoryAndSCCPair.second;\n\n    if (noelle.getVerbosity() >= Verbosity::Maximal) {\n      memoryInst->print(errs() << \"Mem2Reg:  Loop invariant memory location: \"); errs() << \"\\n\";\n      memorySCC->printMinimal(errs() << \"Mem2Reg:  SCC:\\n\"); errs() << \"\\n\";\n    }\n\n    \/\/ if (hoistMemoryInstructionsRelyingOnExistingRegisterValues(memorySCC, memoryInst)) {\n    \/\/   modified = true;\n    \/\/   continue;\n    \/\/ }\n\n    bool promoted = promoteMemoryToRegisterForSCC(memorySCC, memoryInst);\n    if (noelle.getVerbosity() >= Verbosity::Maximal) {\n      memoryInst->print(errs() << \"Mem2Reg:  Loop invariant memory location loads\/stores promoted: \" << promoted << \" \");\n      errs() << \"\\n\";\n    }\n    if (promoted) return true;\n  }\n\n  return false;\n}\n\nstd::unordered_map<Value *, SCC *> Mem2RegNonAlloca::findSCCsWithSingleMemoryLocations (void) {\n\n  \/*\n   * Identify SCC containing only loads\/stores on a single memory location\n   * along with any computation that does NOT alias the loads\/stores\n   *\/\n  auto loopStructure = LDI.getLoopStructure();\n  auto sccManager = LDI.getSCCManager();\n  auto sccdag = sccManager->getSCCDAG();\n  std::unordered_map<Value *, SCC *> singleMemoryLocationsBySCC{};\n  for (auto sccNode : sccdag->getNodes()) {\n    auto scc = sccNode->getT();\n    auto sccInfo = sccManager->getSCCAttrs(scc);\n\n    \/\/ scc->printMinimal(errs() << \"SCC: \\n\"); errs() << \"\\n\";\n    \/\/ for (auto edge : scc->getEdges()) {\n    \/\/   auto value = edge->getOutgoingT();\n    \/\/   \/\/ if (isa<GetElementPtrInst>(value) || isa<StoreInst>(value) || isa<LoadInst>(value)) {\n    \/\/   \/\/   edge->print(errs() << \"Edge:\\n\"); errs() << \"\\n\";\n    \/\/   \/\/ }\n    \/\/ }\n\n    bool isSingleMemoryLocation = false;\n    Value *memoryLocation = nullptr;\n    for (auto nodePair : scc->internalNodePairs()) {\n      auto value = nodePair.first;\n\n      \/*\n       * TODO: Expand understanding of instructions that won't interfere\n       *\/\n      if (isa<BinaryOperator>(value)\n        || isa<CmpInst>(value)\n        || isa<BranchInst>(value)\n        || isa<SelectInst>(value)\n        || isa<CastInst>(value)\n        || isa<PHINode>(value)) continue;\n\n      Value *loadOrStoreLocation = nullptr;\n      if (auto load = dyn_cast<LoadInst>(value)) {\n        loadOrStoreLocation = load->getPointerOperand();\n      } else if (auto store = dyn_cast<StoreInst>(value)) {\n        loadOrStoreLocation = store->getPointerOperand();\n      }\n\n      if (loadOrStoreLocation) {\n        if (!memoryLocation || loadOrStoreLocation == memoryLocation) {\n          isSingleMemoryLocation = true;\n          memoryLocation = loadOrStoreLocation;\n          continue;\n        }\n      }\n\n      isSingleMemoryLocation = false;\n      break;\n    }\n\n    \/*\n     * Memory location access must be the same across the loads\/stores, and loop invariant\n     *\/\n    if (!isSingleMemoryLocation) continue;\n\n    \/*\n     * Ensure no memory aliases with any SCC externals\n     *\/\n    bool hasExternalMemoryDependence = false;\n    for (auto nodePair : scc->internalNodePairs()) {\n      auto node = nodePair.second;\n\n      for (auto edge : node->getAllConnectedEdges()) {\n        auto producer = edge->getOutgoingT();\n        auto consumer = edge->getIncomingT();\n        if (scc->isInternal(consumer) && scc->isInternal(producer)) continue;\n        if (!edge->isMemoryDependence()) continue;\n\n        hasExternalMemoryDependence = true;\n        break;\n      }\n\n      if (hasExternalMemoryDependence) break;\n    }\n    if (hasExternalMemoryDependence) continue;\n\n    if (noelle.getVerbosity() >= Verbosity::Maximal) {\n      memoryLocation->print(errs() << \"Mem2Reg:  Possible loop invariant memory location: \"); errs() << \"\\n\";\n    }\n\n    if (auto memoryInst = dyn_cast<Instruction>(memoryLocation)) {\n      if (loopStructure->isIncluded(memoryInst)\n        && !invariants.isLoopInvariant(memoryInst)) continue;\n    }\n\n    singleMemoryLocationsBySCC.insert(std::make_pair(memoryLocation, scc));\n  }\n\n  return singleMemoryLocationsBySCC;\n}\n\nbool Mem2RegNonAlloca::promoteMemoryToRegisterForSCC (SCC *scc, Value *memoryLocation) {\n\n  auto orderedMemoryInstsByBlock = collectOrderedMemoryInstsByBlock(scc);\n\n  \/*\n   * Traverse loop blocks, creating PHIs to track the latest value to-be-stored\n   * and replacing uses of the loads with the latest value at that point\n   *\/\n  std::queue<BasicBlock *> queue;\n  std::unordered_set<BasicBlock *> visited;\n  std::unordered_map<BasicBlock *, Value *> lastRegisterValueByBlock;\n\n  \/*\n   * Initialize traversal\n   *\/\n  auto loopStructure = LDI.getLoopStructure();\n  auto loopHeader = loopStructure->getHeader();\n  auto loopPreHeader = loopStructure->getPreHeader();\n  queue.push(loopHeader);\n  visited.insert(loopHeader);\n\n  \/*\n   * Register load in pre-header\n   *\/\n  IRBuilder<> preHeaderBuilder(loopPreHeader->getTerminator());\n  auto initialLoad = preHeaderBuilder.CreateLoad(memoryLocation);\n  lastRegisterValueByBlock.insert(std::make_pair(loopPreHeader, initialLoad));\n\n  \/*\n   * This list will track placeholder PHIs at all entries where predecessors weren't visited first\n   * Their incoming values will be determined after the end of the entire traversal\n   * Also track every phi for pruning afterwards\n   *\/ \n  std::unordered_set<PHINode *> placeholderPHIs{};\n  std::unordered_set<PHINode *> allPHIs{};\n\n  if (noelle.getVerbosity() >= Verbosity::Maximal) {\n    errs() << \"Mem2Reg: Iterating basic blocks to determine last stored values\\n\";\n  }\n\n  while (!queue.empty()) {\n    auto B = queue.front();\n    queue.pop();\n\n    \/*\n     * If this block as well as 1+ predecessors do not have a last register value,\n     * add a placeholder PHI. It's incoming values will be determined after the traversal\n     *\/\n    if (lastRegisterValueByBlock.find(B) == lastRegisterValueByBlock.end()) {\n\n      bool pushOffExecutionUntilPredecessorsAreTraversed = false;\n      for (auto predBlock : predecessors(B)) {\n        if (lastRegisterValueByBlock.find(predBlock) != lastRegisterValueByBlock.end()) continue;\n\n        if (noelle.getVerbosity() >= Verbosity::Maximal) {\n          B->printAsOperand(errs() << \"Mem2Reg: placeholder PHI required: \"); errs() << \"\\n\";\n        }\n\n        IRBuilder<> builder(B->getFirstNonPHIOrDbgOrLifetime());\n        int32_t numPreds = pred_size(B);\n        auto phi = builder.CreatePHI(initialLoad->getType(), numPreds);\n        lastRegisterValueByBlock.insert(std::make_pair(B, phi));\n        placeholderPHIs.insert(phi);\n        allPHIs.insert(phi);\n\n        break;\n      }\n    }\n\n    if (noelle.getVerbosity() >= Verbosity::Maximal) {\n      B->printAsOperand(errs() << \"Mem2Reg:  checking for last value entering block: \"); errs() << \"\\n\";\n    }\n\n    \/*\n     * Fetch the current register value that would be in the memory location\n     * If the last register value for the block is ALREADY set, it will be the loop\/sub-loop entry\n     * \n     * For all other blocks, their already-traversed predecessors will have last register values\n     * If there is more than 1 predecessor, create a PHI to collect those predecessor's last values\n     *\/\n    Value *lastValue = nullptr;\n    if (lastRegisterValueByBlock.find(B) != lastRegisterValueByBlock.end()) {\n      lastValue = lastRegisterValueByBlock.at(B);\n    } else {\n\n      auto singlePredBlock = B->getSinglePredecessor();\n      if (singlePredBlock) {\n        assertAndDumpLogsOnFailure(\n          [&]() -> bool { return lastRegisterValueByBlock.find(singlePredBlock) != lastRegisterValueByBlock.end(); },\n          \"Mem2Reg: can't identify last value of the single predecessor to the block\");\n        lastValue = lastRegisterValueByBlock.at(singlePredBlock);\n      } else {\n\n        IRBuilder<> builder(B->getFirstNonPHIOrDbgOrLifetime());\n        auto numPreds = pred_size(B);\n        auto phi = builder.CreatePHI(initialLoad->getType(), numPreds);\n        allPHIs.insert(phi);\n        lastValue = phi;\n\n        for (auto predBlock : predecessors(B)) {\n          assertAndDumpLogsOnFailure(\n            [&]() -> bool { return lastRegisterValueByBlock.find(predBlock) != lastRegisterValueByBlock.end(); },\n            \"Mem2Reg: can't identify last value of one of the predecessors to the block\");\n          auto predV = lastRegisterValueByBlock.at(predBlock);\n          phi->addIncoming(predV, predBlock);\n        }\n      }\n\n      lastRegisterValueByBlock.insert_or_assign(B, lastValue);\n    }\n\n    if (noelle.getVerbosity() >= Verbosity::Maximal) {\n      B->printAsOperand(errs() << \"Mem2Reg:  Last value entering block: \"); errs() << \"\\t\";\n      lastValue->print(errs()); errs() << \"\\n\";\n    }\n\n    \/*\n     * Traverse to successors of current block that are within the loop\n     *\/\n    for (auto succBlock : successors(B)) {\n      if (!loopStructure->isIncluded(succBlock)) continue;\n      if (visited.find(succBlock) != visited.end()) continue;\n      queue.push(succBlock);\n      visited.insert(succBlock);\n    }\n\n    \/*\n     * For each load in the block, replace it with the current register value\n     * For each store in the block, update the current register value\n     *\/\n    if (orderedMemoryInstsByBlock.find(B) == orderedMemoryInstsByBlock.end()) continue;\n    for (auto memInst : orderedMemoryInstsByBlock.at(B)) {\n      if (auto loadInst = dyn_cast<LoadInst>(memInst)) {\n\n        \/*\n         * NOTE: We cannot replace users as we traverse the users list, so we cache users of the load\n         *\/\n        std::unordered_set<User *> usersOfLoad{loadInst->user_begin(), loadInst->user_end()};\n        for (auto user : usersOfLoad) {\n          user->replaceUsesOfWith(loadInst, lastValue);\n        }\n\n      } else if (auto storeInst = dyn_cast<StoreInst>(memInst)) {\n        lastValue = storeInst->getValueOperand();\n\n        if (noelle.getVerbosity() >= Verbosity::Maximal) {\n          lastValue->print(errs() << \"Mem2Reg:  Value updated: \"); errs() << \"\\n\";\n        }\n\n      } else assert(false && \"Mem2Reg: corrupt internal memory instruction map data structure\");\n    }\n    lastRegisterValueByBlock.insert_or_assign(B, lastValue);\n\n  }\n\n  \/*\n   * For each placeholder, wire up the PHI with the last register values from all predecessors\n   *\/ \n  for (auto phi : placeholderPHIs) {\n    auto phiBlock = phi->getParent();\n    for (auto predBlock : predecessors(phiBlock)) {\n      assertAndDumpLogsOnFailure(\n        [&]() -> bool { return lastRegisterValueByBlock.find(predBlock) != lastRegisterValueByBlock.end(); },\n        \"Mem2Reg: can't identify last value of predecessor to placeholder PHI block\");\n      auto prevValue = lastRegisterValueByBlock.at(predBlock);\n\n      \/*\n       * To prevent a PHI from referencing itself, add an intermediate in the predecessor block\n       * that references the PHI, and then use that intermediate\n       * \n       * TODO: Determine if we need to handle the case where the block is its own predecessor differently\n       *\/\n      if (prevValue == phi) {\n        auto numPreds = pred_size(predBlock);\n        IRBuilder<> builder(predBlock->getFirstNonPHIOrDbgOrLifetime());\n        auto intermediatePHI = builder.CreatePHI(phi->getType(), numPreds);\n        for (auto latchPredBlock : predecessors(predBlock)) {\n          intermediatePHI->addIncoming(phi, latchPredBlock);\n        }\n        prevValue = intermediatePHI;\n        \n        allPHIs.insert(intermediatePHI);\n        lastRegisterValueByBlock.insert_or_assign(predBlock, intermediatePHI);\n      }\n\n      phi->addIncoming(prevValue, predBlock);\n    }\n  }\n\n  \/*\n   * Store the last register value for the memory location at each loop exit\n   * This may require creating a PHI at the loop exit\n   *\/\n  for (auto exitBlock : loopStructure->getLoopExitBasicBlocks()) {\n    IRBuilder<> exitBuilder(exitBlock->getFirstNonPHIOrDbgOrLifetime());\n\n    Value *lastValue = nullptr;\n    auto singlePredBlock = exitBlock->getSinglePredecessor();\n    if (singlePredBlock) {\n      assertAndDumpLogsOnFailure(\n        [&]() -> bool { return lastRegisterValueByBlock.find(singlePredBlock) != lastRegisterValueByBlock.end(); },\n        \"Mem2Reg: can't identify last value of predecessor to loop exit block\");\n      lastValue = lastRegisterValueByBlock.at(singlePredBlock);\n    } else {\n\n      auto numPreds = pred_size(exitBlock);\n      auto exitPHI = exitBuilder.CreatePHI(initialLoad->getType(), numPreds);\n      for (auto exitPredBlock : predecessors(exitBlock)) {\n        assertAndDumpLogsOnFailure(\n          [&]() -> bool { return lastRegisterValueByBlock.find(exitPredBlock) != lastRegisterValueByBlock.end(); },\n          \"Mem2Reg: can't identify last value of predecessor to loop exit block\");\n        auto exitPredValue = lastRegisterValueByBlock.at(exitPredBlock);\n        exitPHI->addIncoming(exitPredValue, exitPredBlock);\n      }\n      lastValue = exitPHI;\n    }\n\n    exitBuilder.CreateStore(lastValue, memoryLocation);\n  }\n\n  \/*\n   * Delete stores and loads\n   *\/\n  for (auto blockAndInsts : orderedMemoryInstsByBlock) {\n    auto insts = blockAndInsts.second;\n    for (auto I : insts) {\n\n      if (noelle.getVerbosity() >= Verbosity::Maximal) {\n        I->print(errs() << \"Mem2Reg:  Removing\\n\"); errs() << \"\\n\";\n      }\n\n      assert(I->user_empty() && \"Mem2Reg: Removing instruction but failed to replace all its uses\");\n      I->eraseFromParent();\n    }\n  }\n\n  \/*\n   * Primary goal: prevent any extra PHI loop carried dependencies that already exist from being re-stated\n   *\/\n  removeRedundantPHIs(allPHIs, lastRegisterValueByBlock);\n\n  return true;\n}\n\nbool Mem2RegNonAlloca::hoistMemoryInstructionsRelyingOnExistingRegisterValues (SCC *scc, Value *memoryLocation) {\n\n  auto orderedMemoryInstsByBlock = collectOrderedMemoryInstsByBlock(scc);\n\n  auto loopStructure = LDI.getLoopStructure();\n  auto loopHeader = loopStructure->getHeader();\n\n  \/\/ Build a list of basic blocks that collect 2+ unique stored values (store merging blocks)\n  std::unordered_map<BasicBlock *, StoreInst *> blockToLastStoreMap;\n  std::queue<BasicBlock *> blocksToTraverse;\n  std::unordered_set<BasicBlock *> blocksMergingStores;\n\n  for (auto memoryInstsByBlock : orderedMemoryInstsByBlock) {\n    auto block = memoryInstsByBlock.first;\n    auto memoryInsts = memoryInstsByBlock.second;\n\n    StoreInst *lastStore = nullptr;\n    for (auto instIter = memoryInsts.rbegin(); instIter != memoryInsts.rend(); --instIter) {\n      auto inst = *instIter;\n      if (auto store = dyn_cast<StoreInst>(inst)) {\n        lastStore = store;\n        break;\n      }\n    }\n\n    if (!lastStore) continue;\n    blockToLastStoreMap.insert(std::make_pair(block, lastStore));\n    blocksToTraverse.push(block);\n  }\n\n  while (!blocksToTraverse.empty()) {\n    auto block = blocksToTraverse.front();\n    blocksToTraverse.pop();\n\n    for (auto succBlock : successors(block)) {\n      if (pred_size(succBlock) > 1) {\n        blocksMergingStores.insert(succBlock);\n        continue;\n      }\n\n      \/*\n       * This check is needed, even if the only way a block points to itself in our traversal\n       * is if our traversal started in that block\n       *\/\n      if (succBlock == block) continue;\n      blocksToTraverse.push(succBlock);\n    }\n  }\n\n  \/\/ Locate candidate SCCs that have single header PHIs and consume stored values\n  \/\/ TODO:\n\n  \/\/ Filter candidates:\n  \/\/ The header PHI's pre-header incoming value must be the initial value at the memory location\n  \/\/ PHIs must exist at all store merging blocks and propagate all last-stored values\n  \/\/ Only and all last-stored values and store merging PHIs must propagate to the header\n\n  return false;\n}\n\nvoid Mem2RegNonAlloca::removeRedundantPHIs (\n  std::unordered_set<PHINode *> phis,\n  std::unordered_map<BasicBlock *, Value *> lastRegisterValueByBlock\n) {\n\n  \/*\n   * For each PHI, determine if all incoming values are the same.\n   * If so, replace this PHI's uses with that incoming value\n   *\/\n  \/\/ TODO:\n\n}\n\nstd::unordered_map<BasicBlock *, std::vector<Instruction *>> Mem2RegNonAlloca::collectOrderedMemoryInstsByBlock (SCC *scc) {\n\n  if (noelle.getVerbosity() >= Verbosity::Maximal) {\n    errs() << \"Mem2Reg:  Collecting and ordering memory loads\/stores by basic block\\n\";\n  }\n\n  \/*\n   * Index memory values by their basic block\n   *\/\n  std::unordered_map<BasicBlock *, std::unordered_set<Instruction *>> memoryInstsByBlock;\n  for (auto nodePair : scc->internalNodePairs()) {\n    auto value = nodePair.first;\n    Instruction *memoryInst = nullptr;\n    if (isa<LoadInst>(value) || isa<StoreInst>(value)) {\n      memoryInst = cast<Instruction>(value);\n    }\n    if (!memoryInst) continue;\n\n    auto B = memoryInst->getParent();\n    if (memoryInstsByBlock.find(B) == memoryInstsByBlock.end()) {\n      std::unordered_set<Instruction *> memoryInsts = { memoryInst };\n      memoryInstsByBlock.insert(std::make_pair(B, memoryInsts));\n    } else {\n      auto &memoryInsts = memoryInstsByBlock.at(B);\n      memoryInsts.insert(memoryInst);\n    }\n  }\n\n  \/*\n   * Sort memory values in execution order for each basic block\n   *\/\n  std::unordered_map<BasicBlock *, std::vector<Instruction *>> orderedMemoryInstsByBlock;\n  for (auto blockAndInstsPair : memoryInstsByBlock) {\n    auto B = blockAndInstsPair.first;\n    auto memoryInsts = blockAndInstsPair.second;\n    std::vector<Instruction *> orderedInstsInit{};\n    auto result = orderedMemoryInstsByBlock.insert(std::make_pair(B, orderedInstsInit));\n    auto &orderedInsts = (*result.first).second;\n\n    for (auto &I : *B) {\n      if (memoryInsts.find(&I) == memoryInsts.end()) continue;\n      orderedInsts.push_back(&I);\n    }\n  }\n\n  return orderedMemoryInstsByBlock;\n}\n\nvoid Mem2RegNonAlloca::assertAndDumpLogsOnFailure (std::function<bool(void)> assertion, std::string errorString) {\n  if (!assertion()) {\n    errs() << errorString << \"\\n\";\n    if (noelle.getVerbosity() >= Verbosity::Maximal) {\n      dumpLogs();\n    }\n    abort();\n  }\n}\n\nvoid Mem2RegNonAlloca::dumpLogs (void) {\n  auto loop = LDI.getLoopStructure();\n  auto basicBlocks = loop->getBasicBlocks();\n\n  \/*\n   * Identify loop\n   *\/\n  std::string loopId{std::to_string(loop->getID())};\n\n  \/\/ DGPrinter::writeGraph<SCCDAG, SCC>(\"mem2reg-sccdag-loop-\" + loopId + \".dot\", sccManager->getSCCDAG());\n  \/\/ std::set<BasicBlock *> basicBlocksSet(basicBlocks.begin(), basicBlocks.end());\n  \/\/ DGPrinter::writeGraph<SubCFGs, BasicBlock>(\"mem2reg-current-loop-\" + loopId + \".dot\", new SubCFGs(basicBlocksSet));\n}\n","avg_line_length":36.845323741,"max_line_length":435,"alphanum_fraction":0.676461974,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8307,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":22.0,"content":"\/\/ Copyright (c) 2017-2018 The PIVX developers\n\/\/ Copyright (c) 2018 The XIM developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"accumulators.h\"\n#include \"chain.h\"\n#include \"primitives\/deterministicmint.h\"\n#include \"main.h\"\n#include \"stakeinput.h\"\n#include \"wallet.h\"\n\nCZXimBlockStake::CZXimBlockStake(const libzerocoin::CoinSpend& spend)\n{\n    this->nChecksum = spend.getAccumulatorChecksum();\n    this->denom = spend.getDenomination();\n    uint256 nSerial = spend.getCoinSerialNumber().getuint256();\n    this->hashSerial = Hash(nSerial.begin(), nSerial.end());\n    this->pindexFrom = nullptr;\n    fMint = false;\n}\n\nint CZXimBlockStake::GetChecksumHeightFromMint()\n{\n    int nHeightChecksum = chainActive.Height() - Params().Zerocoin_RequiredStakeDepth();\n\n    \/\/Need to return the first occurance of this checksum in order for the validation process to identify a specific\n    \/\/block height\n    uint32_t nChecksum = 0;\n    nChecksum = ParseChecksum(chainActive[nHeightChecksum]->nAccumulatorCheckpoint, denom);\n    return GetChecksumHeight(nChecksum, denom);\n}\n\nint CZXimBlockStake::GetChecksumHeightFromSpend()\n{\n    return GetChecksumHeight(nChecksum, denom);\n}\n\nuint32_t CZXimBlockStake::GetChecksum()\n{\n    return nChecksum;\n}\n\n\/\/ The zXIM block index is the first appearance of the accumulator checksum that was used in the spend\n\/\/ note that this also means when staking that this checksum should be from a block that is beyond 60 minutes old and\n\/\/ 100 blocks deep.\nCBlockIndex* CZXimBlockStake::GetIndexFrom()\n{\n    if (pindexFrom)\n        return pindexFrom;\n\n    int nHeightChecksum = 0;\n\n    if (fMint)\n        nHeightChecksum = GetChecksumHeightFromMint();\n    else\n        nHeightChecksum = GetChecksumHeightFromSpend();\n\n    if (nHeightChecksum < Params().Zerocoin_StartHeight() || nHeightChecksum > chainActive.Height()) {\n        pindexFrom = nullptr;\n    } else {\n        \/\/note that this will be a nullptr if the height DNE\n        pindexFrom = chainActive[nHeightChecksum];\n    }\n\n    return pindexFrom;\n}\n\nCAmount CZXimBlockStake::GetValue()\n{\n    return denom * COIN;\n}\n\n\/\/Use the first accumulator checkpoint that occurs 60 minutes after the block being staked from\nbool CZXimBlockStake::GetModifier(uint64_t& nStakeModifier)\n{\n    CBlockIndex* pindex = GetIndexFrom();\n    if (!pindex)\n        return false;\n\n    int64_t nTimeBlockFrom = pindex->GetBlockTime();\n    while (true) {\n        if (pindex->GetBlockTime() - nTimeBlockFrom > 60*60) {\n            nStakeModifier = pindex->nAccumulatorCheckpoint.Get64();\n            return true;\n        }\n\n        if (pindex->nHeight + 1 <= chainActive.Height())\n            pindex = chainActive.Next(pindex);\n        else\n            return false;\n    }\n}\n\nCDataStream CZXimBlockStake::GetUniqueness()\n{\n    \/\/The unique identifier for a zXIM is a hash of the serial\n    CDataStream ss(SER_GETHASH, 0);\n    ss << hashSerial;\n    return ss;\n}\n\nbool CZXimBlockStake::CreateTxIn(CWallet* pwallet, CTxIn& txIn, uint256 hashTxOut)\n{\n    CBlockIndex* pindexCheckpoint = GetIndexFrom();\n    if (!pindexCheckpoint)\n        return error(\"%s: failed to find checkpoint block index\", __func__);\n\n    CZerocoinMint mint;\n    if (!pwallet->GetMintFromStakeHash(hashSerial, mint))\n        return error(\"%s: failed to fetch mint associated with serial hash %s\", __func__, hashSerial.GetHex());\n\n    if (libzerocoin::ExtractVersionFromSerial(mint.GetSerialNumber()) < 2)\n        return error(\"%s: serial extract is less than v2\", __func__);\n\n    int nSecurityLevel = 100;\n    CZerocoinSpendReceipt receipt;\n    if (!pwallet->MintToTxIn(mint, nSecurityLevel, hashTxOut, txIn, receipt, libzerocoin::SpendType::STAKE, GetIndexFrom()))\n        return error(\"%s\\n\", receipt.GetStatusMessage());\n\n    return true;\n}\n\nbool CZXimBlockStake::CreateTxOuts(CWallet* pwallet, vector<CTxOut>& vout, CAmount nTotal)\n{\n    \/\/Create an output returning the zXIM that was staked\n    CTxOut outReward;\n    libzerocoin::CoinDenomination denomStaked = libzerocoin::AmountToZerocoinDenomination(this->GetValue());\n    CDeterministicMint dMint;\n    if (!pwallet->CreateZXIMOutPut(denomStaked, outReward, dMint))\n        return error(\"%s: failed to create zXIM output\", __func__);\n    vout.emplace_back(outReward);\n\n    \/\/Add new staked denom to our wallet\n    if (!pwallet->DatabaseMint(dMint))\n        return error(\"%s: failed to database the staked zXIM\", __func__);\n\n    for (unsigned int i = 0; i < 3; i++) {\n        CTxOut out;\n        CDeterministicMint dMintReward;\n        if (!pwallet->CreateZXIMOutPut(libzerocoin::CoinDenomination::ZQ_ONE, out, dMintReward))\n            return error(\"%s: failed to create zXIM output\", __func__);\n        vout.emplace_back(out);\n\n        if (!pwallet->DatabaseMint(dMintReward))\n            return error(\"%s: failed to database mint reward\", __func__);\n    }\n\n    return true;\n}\n\nbool CZXimBlockStake::GetTxFrom(CTransaction& tx)\n{\n    return false;\n}\n\nbool CZXimBlockStake::MarkSpent(CWallet *pwallet, const uint256& txid)\n{\n    CzXIMTracker* zpivTracker = pwallet->zpivTracker.get();\n    CMintMeta meta;\n    if (!zpivTracker->GetMetaFromStakeHash(hashSerial, meta))\n        return error(\"%s: tracker does not have serialhash\", __func__);\n\n    zpivTracker->SetPubcoinUsed(meta.hashPubcoin, txid);\n    return true;\n}\n\n\/\/!XIM Stake\nbool CXimBlockStake::SetInput(CTransaction txPrev, unsigned int n)\n{\n    this->txFrom = txPrev;\n    this->nPosition = n;\n    return true;\n}\n\nbool CXimBlockStake::GetTxFrom(CTransaction& tx)\n{\n    tx = txFrom;\n    return true;\n}\n\nbool CXimBlockStake::CreateTxIn(CWallet* pwallet, CTxIn& txIn, uint256 hashTxOut)\n{\n    txIn = CTxIn(txFrom.GetHash(), nPosition);\n    return true;\n}\n\nCAmount CXimBlockStake::GetValue()\n{\n    return txFrom.vout[nPosition].nValue;\n}\n\nbool CXimBlockStake::CreateTxOuts(CWallet* pwallet, vector<CTxOut>& vout, CAmount nTotal)\n{\n    vector<valtype> vSolutions;\n    txnouttype whichType;\n    CScript scriptPubKeyKernel = txFrom.vout[nPosition].scriptPubKey;\n    if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) {\n        LogPrintf(\"CreateCoinStake : failed to parse kernel\\n\");\n        return false;\n    }\n\n    if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)\n        return false; \/\/ only support pay to public key and pay to address\n\n    CScript scriptPubKey;\n    if (whichType == TX_PUBKEYHASH) \/\/ pay to address type\n    {\n        \/\/convert to pay to public key type\n        CKey key;\n        CKeyID keyID = CKeyID(uint160(vSolutions[0]));\n        if (!pwallet->GetKey(keyID, key))\n            return false;\n\n        scriptPubKey << key.GetPubKey() << OP_CHECKSIG;\n    } else\n        scriptPubKey = scriptPubKeyKernel;\n\n    vout.emplace_back(CTxOut(0, scriptPubKey));\n\n    \/\/ Calculate if we need to split the output\n    if (nTotal \/ 2 > (CAmount)(pwallet->nStakeSplitThreshold * COIN))\n        vout.emplace_back(CTxOut(0, scriptPubKey));\n\n    return true;\n}\n\nbool CXimBlockStake::GetModifier(uint64_t& nStakeModifier)\n{\n    int nStakeModifierHeight = 0;\n    int64_t nStakeModifierTime = 0;\n    GetIndexFrom();\n    if (!pindexFrom)\n        return error(\"%s: failed to get index from\", __func__);\n\n    if (!GetKernelStakeModifier(pindexFrom->GetBlockHash(), nStakeModifier, nStakeModifierHeight, nStakeModifierTime, false))\n        return error(\"CheckStakeKernelHash(): failed to get kernel stake modifier \\n\");\n\n    return true;\n}\n\nCDataStream CXimBlockStake::GetUniqueness()\n{\n    \/\/The unique identifier for a XIM stake is the outpoint\n    CDataStream ss(SER_NETWORK, 0);\n    ss << nPosition << txFrom.GetHash();\n    return ss;\n}\n\n\/\/The block that the UTXO was added to the chain\nCBlockIndex* CXimBlockStake::GetIndexFrom()\n{\n    uint256 hashBlock = 0;\n    CTransaction tx;\n    if (GetTransaction(txFrom.GetHash(), tx, hashBlock, true)) {\n        \/\/ If the index is in the chain, then set it as the \"index from\"\n        if (mapBlockIndex.count(hashBlock)) {\n            CBlockIndex* pindex = mapBlockIndex.at(hashBlock);\n            if (chainActive.Contains(pindex))\n                pindexFrom = pindex;\n        }\n    } else {\n        LogPrintf(\"%s : failed to find tx %s\\n\", __func__, txFrom.GetHash().GetHex());\n    }\n\n    return pindexFrom;\n}","avg_line_length":31.1123595506,"max_line_length":125,"alphanum_fraction":0.6915854099,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5284,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n\n#include <Funambol\/spds\/SyncItemStatus.h>\n#include <Funambol\/base\/globalsdef.h>\n\nUSE_NAMESPACE\n\n\/*\n * Default constructor\n *\/\nSyncItemStatus::SyncItemStatus() {\n\tkey = NULL;\n}\n\n\/*\n * Constructs a new SyncItemStatus identified by the given key. The key must\n * not be longer than DIM_KEY_SYNC_ITEM_STATUS (see SPDS Constants).\n *\n * @param key - the key\n *\/\nSyncItemStatus::SyncItemStatus(char* itemStatusKey){\n\n    key = new char[strlen(itemStatusKey)+1];\n    strcpy(key, itemStatusKey);\n\n    data    = 0;\n    cmdID   = 0;\n    msgRef  = 0;\n    cmdRef  = 0;\n\n    cmd = NULL;\n\n}\n\nSyncItemStatus::~SyncItemStatus() {\n\tif (key) {\n\t\tdelete [] key;\n\t}\n\n\tif (cmd) {\n\t\tdelete [] cmd;\n\t}\n\n}\n\n\/*\n * Returns the SyncItemStatus's key. If key is NULL, the internal buffer is\n * returned; if key is not NULL, the value is copied in the caller\n * allocated buffer and the given buffer pointer is returned.\n *\n * @param key - buffer where the key will be stored\n *\/\nconst char* SyncItemStatus::getKey() {\n    return key;\n}\n\n\/*\n * Changes the SyncItemStatus key. The key must not be longer than DIM_KEY_SYNC_ITEM_STATUS\n * (see SPDS Constants).\n *\n * @param key - the key\n *\/\nvoid SyncItemStatus::setKey(const char*itemStatusKey) {\n\tif (key) {\n\t\tdelete [] key;\n\t}\n\tkey = new char[strlen(itemStatusKey)+1];\n    strcpy(key, itemStatusKey);\n}\n\n \/*\n * Returns the SyncItemStatus's command name. If cmd is NULL, the internal buffer is\n * returned; if cmd is not NULL, the value is copied in the caller\n * allocated buffer and the given buffer pointer is returned.\n *\n * @param itemStatusCmd - buffer where the itemStatusCmd will be stored\n *\/\nconst char* SyncItemStatus::getCmd() {\n    return cmd;\n}\n\n\n\/*\n * Changes the SyncItemStatus cmd. The cmd must not be longer than DIM_COMMAND_SYNC_ITEM_STATUS\n * (see SPDS Constants).\n *\n * @param itemStatusCmd - the itemStatusCmd\n *\/\nvoid SyncItemStatus::setCmd(const char*itemStatusCmd) {\n    if (cmd) {\n\t\tdelete [] cmd;\n\t}\n\tcmd = new char[strlen(itemStatusCmd)+1];\n    strcpy(cmd, itemStatusCmd);\n\n}\n\n\n\/*\n * Sets the SyncItemStatus data. The passed data are copied into an\n * internal variable.\n *\/\nvoid SyncItemStatus::setData(int itemStatusData) {\n    data = itemStatusData;\n}\n\n\/*\n * Returns the SyncItemStatus data variable.\n *\/\nint SyncItemStatus::getData() {\n    return data;\n}\n\n\n\/*\n * Sets the SyncItemStatus command ID. The passed data are copied into an\n * internal variable.\n *\/\nvoid SyncItemStatus::setCmdID(int itemStatusCmdID) {\n    cmdID = itemStatusCmdID;\n}\n\n\/*\n * Returns the SyncItemStatus command ID variable.\n *\/\nint SyncItemStatus::getCmdID() {\n    return cmdID;\n}\n\n\/*\n * Sets the SyncItemStatus message referring. The passed data are copied into an\n * internal variable.\n *\/\nvoid SyncItemStatus::setMsgRef(int itemStatusMsgRef) {\n    msgRef = itemStatusMsgRef;\n}\n\n\/*\n * Returns the SyncItemStatus message referring variable.\n *\/\nint SyncItemStatus::getMsgRef() {\n    return msgRef;\n}\n\n\/*\n * Sets the SyncItemStatus command referring. The passed data are copied into an\n * internal variable.\n *\/\nvoid SyncItemStatus::setCmdRef(int itemStatusCmdRef) {\n    cmdRef = itemStatusCmdRef;\n}\n\n\/*\n * Returns the SyncItemStatus command referring variable.\n *\/\nint SyncItemStatus::getCmdRef() {\n    return cmdRef;\n}\n\nArrayElement* SyncItemStatus::clone() {\n\tSyncItemStatus* ret = new SyncItemStatus(key);\n\n\tret->setCmd(cmd);\n\tret->setData(data);\n\tret->setCmdRef(cmdRef);\n\tret->setMsgRef(msgRef);\n\tret->setCmdID(cmdID);\n\n\treturn ret;\n}\n","avg_line_length":25.7756097561,"max_line_length":95,"alphanum_fraction":0.7199091597,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":18624,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include <map>\n#include <vespa\/config-attributes.h>\n#include <vespa\/config-imported-fields.h>\n#include <vespa\/config-indexschema.h>\n#include <vespa\/config-rank-profiles.h>\n#include <vespa\/config-summary.h>\n#include <vespa\/config-summarymap.h>\n#include <vespa\/config-bucketspaces.h>\n#include <vespa\/document\/config\/documenttypes_config_fwd.h>\n#include <vespa\/document\/repo\/documenttyperepo.h>\n#include <vespa\/fileacquirer\/config-filedistributorrpc.h>\n#include <vespa\/searchcore\/proton\/common\/alloc_config.h>\n#include <vespa\/searchcore\/proton\/server\/bootstrapconfig.h>\n#include <vespa\/searchcore\/proton\/server\/documentdbconfigmanager.h>\n#include <vespa\/searchcore\/proton\/server\/document_db_config_owner.h>\n#include <vespa\/searchcore\/proton\/server\/proton_config_snapshot.h>\n#include <vespa\/searchcore\/proton\/server\/proton_configurer.h>\n#include <vespa\/searchcore\/proton\/server\/i_proton_configurer_owner.h>\n#include <vespa\/searchcore\/proton\/server\/i_proton_disk_layout.h>\n#include <vespa\/searchcore\/proton\/server\/threading_service_config.h>\n#include <vespa\/searchsummary\/config\/config-juniperrc.h>\n#include <vespa\/searchcommon\/common\/schemaconfigurer.h>\n#include <vespa\/vespalib\/util\/size_literals.h>\n#include <vespa\/vespalib\/util\/threadstackexecutor.h>\n#include <vespa\/vespalib\/test\/insertion_operators.h>\n#include <vespa\/config\/subscription\/configuri.h>\n#include <vespa\/vespalib\/gtest\/gtest.h>\n\nusing namespace config;\nusing namespace proton;\nusing namespace vespa::config::search::core;\nusing namespace vespa::config::search::summary;\nusing namespace vespa::config::search;\nusing namespace cloud::config::filedistribution;\nusing vespa::config::content::core::BucketspacesConfig;\nusing vespa::config::content::core::BucketspacesConfigBuilder;\n\nusing InitializeThreads = std::shared_ptr<vespalib::ThreadStackExecutorBase>;\nusing config::ConfigUri;\nusing document::DocumentTypeRepo;\nusing search::TuneFileDocumentDB;\nusing std::map;\nusing search::index::Schema;\nusing search::index::SchemaBuilder;\nusing proton::matching::RankingConstants;\nusing proton::matching::RankingExpressions;\nusing proton::matching::OnnxModels;\n\nstruct DBConfigFixture {\n    using UP = std::unique_ptr<DBConfigFixture>;\n    AttributesConfigBuilder _attributesBuilder;\n    RankProfilesConfigBuilder _rankProfilesBuilder;\n    IndexschemaConfigBuilder _indexschemaBuilder;\n    SummaryConfigBuilder _summaryBuilder;\n    SummarymapConfigBuilder _summarymapBuilder;\n    JuniperrcConfigBuilder _juniperrcBuilder;\n    ImportedFieldsConfigBuilder _importedFieldsBuilder;\n\n    Schema::SP buildSchema()\n    {\n        Schema::SP schema(std::make_shared<Schema>());\n        SchemaBuilder::build(_attributesBuilder, *schema);\n        SchemaBuilder::build(_summaryBuilder, *schema);\n        SchemaBuilder::build(_indexschemaBuilder, *schema);\n        return schema;\n    }\n\n    RankingConstants::SP buildRankingConstants()\n    {\n        return std::make_shared<RankingConstants>();\n    }\n\n    RankingExpressions::SP buildRankingExpressions()\n    {\n        return std::make_shared<RankingExpressions>();\n    }\n\n    OnnxModels::SP buildOnnxModels()\n    {\n        return std::make_shared<OnnxModels>();\n    }\n\n    DocumentDBConfig::SP getConfig(int64_t generation,\n                                   std::shared_ptr<DocumenttypesConfig> documentTypes,\n                                   std::shared_ptr<const DocumentTypeRepo> repo,\n                                   const vespalib::string &configId,\n                                   const vespalib::string &docTypeName)\n    {\n        return std::make_shared<DocumentDBConfig>\n            (generation,\n             std::make_shared<RankProfilesConfig>(_rankProfilesBuilder),\n             buildRankingConstants(),\n             buildRankingExpressions(),\n             buildOnnxModels(),\n             std::make_shared<IndexschemaConfig>(_indexschemaBuilder),\n             std::make_shared<AttributesConfig>(_attributesBuilder),\n             std::make_shared<SummaryConfig>(_summaryBuilder),\n             std::make_shared<SummarymapConfig>(_summarymapBuilder),\n             std::make_shared<JuniperrcConfig>(_juniperrcBuilder),\n             documentTypes,\n             repo,\n             std::make_shared<ImportedFieldsConfig>(_importedFieldsBuilder),\n             std::make_shared<TuneFileDocumentDB>(),\n             buildSchema(),\n             std::make_shared<DocumentDBMaintenanceConfig>(),\n             search::LogDocumentStore::Config(),\n             ThreadingServiceConfig::make(),\n             AllocConfig::makeDefault(),\n             configId,\n             docTypeName);\n    }\n};\n\nstruct ConfigFixture {\n    const std::string _configId;\n    ProtonConfigBuilder _protonBuilder;\n    DocumenttypesConfigBuilder _documenttypesBuilder;\n    FiledistributorrpcConfigBuilder _filedistBuilder;\n    BucketspacesConfigBuilder _bucketspacesBuilder;\n    map<std::string, DBConfigFixture::UP> _dbConfig;\n    int _idcounter;\n    int64_t _generation;\n    std::shared_ptr<ProtonConfigSnapshot> _cachedConfigSnapshot;\n\n    ConfigFixture(const std::string & id)\n        : _configId(id),\n          _protonBuilder(),\n          _documenttypesBuilder(),\n          _filedistBuilder(),\n          _bucketspacesBuilder(),\n          _dbConfig(),\n          _idcounter(-1),\n          _generation(1),\n          _cachedConfigSnapshot()\n    {\n        addDocType(\"_alwaysthere_\", \"default\");\n    }\n\n    ~ConfigFixture() { }\n\n    DBConfigFixture *addDocType(const std::string & name, const std::string& bucket_space) {\n        DocumenttypesConfigBuilder::Documenttype dt;\n        dt.bodystruct = -1270491200;\n        dt.headerstruct = 306916075;\n        dt.id = _idcounter--;\n        dt.name = name;\n        dt.version = 0;\n        _documenttypesBuilder.documenttype.push_back(dt);\n\n        ProtonConfigBuilder::Documentdb db;\n        db.inputdoctypename = name;\n        db.configid = _configId + \"\/\" + name;\n        _protonBuilder.documentdb.push_back(db);\n\n        BucketspacesConfigBuilder::Documenttype bsdt;\n        bsdt.name = name;\n        bsdt.bucketspace = bucket_space;\n        _bucketspacesBuilder.documenttype.push_back(bsdt);\n\n        DBConfigFixture::UP fixture = std::make_unique<DBConfigFixture>();\n        return _dbConfig.emplace(std::make_pair(name, std::move(fixture))).first->second.get();\n    }\n\n    void removeDocType(const std::string & name)\n    {\n        for (auto it(_documenttypesBuilder.documenttype.begin()),\n                 mt(_documenttypesBuilder.documenttype.end());\n             it != mt;\n             it++) {\n            if ((*it).name.compare(name) == 0) {\n                _documenttypesBuilder.documenttype.erase(it);\n                break;\n            }\n        }\n\n        for (auto it(_protonBuilder.documentdb.begin()),\n                 mt(_protonBuilder.documentdb.end());\n             it != mt;\n             it++) {\n            if ((*it).inputdoctypename.compare(name) == 0) {\n                _protonBuilder.documentdb.erase(it);\n                break;\n            }\n        }\n        _dbConfig.erase(name);\n        for (auto it(_bucketspacesBuilder.documenttype.begin()), mt(_bucketspacesBuilder.documenttype.end()); it != mt; ++it) {\n            if (it->name == name) {\n                _bucketspacesBuilder.documenttype.erase(it);\n                break;\n            }\n        }\n    }\n\n    BootstrapConfig::SP getBootstrapConfig(int64_t generation) const {\n        return BootstrapConfig::SP(new BootstrapConfig(generation,\n                                                       BootstrapConfig::DocumenttypesConfigSP(new DocumenttypesConfig(_documenttypesBuilder)),\n                                                       std::shared_ptr<const DocumentTypeRepo>(new DocumentTypeRepo(_documenttypesBuilder)),\n                                                       BootstrapConfig::ProtonConfigSP(new ProtonConfig(_protonBuilder)),\n                                                       std::make_shared<FiledistributorrpcConfig>(),\n                                                       std::make_shared<BucketspacesConfig>(_bucketspacesBuilder),\n                                                       std::make_shared<TuneFileDocumentDB>(), HwInfo()));\n    }\n\n    std::shared_ptr<ProtonConfigSnapshot> getConfigSnapshot()\n    {\n        if (_cachedConfigSnapshot) {\n            return _cachedConfigSnapshot;\n        }\n        int64_t generation = ++_generation;\n        auto bootstrap = getBootstrapConfig(generation);\n        std::map<DocTypeName, DocumentDBConfig::SP> dbconfigs;\n        auto doctypes = bootstrap->getDocumenttypesConfigSP();\n        auto repo = bootstrap->getDocumentTypeRepoSP();\n        for (auto &db : _dbConfig) {\n            DocTypeName name(db.first);\n            dbconfigs.insert(std::make_pair(name,\n                                            db.second->getConfig(generation,\n                                                                 doctypes,\n                                                                 repo,\n                                                                 _configId + \"\/\" + db.first,\n                                                                 db.first)));\n        }\n        _cachedConfigSnapshot = std::make_shared<ProtonConfigSnapshot>(bootstrap, dbconfigs);\n        return _cachedConfigSnapshot;\n    }\n    void newConfig() { _cachedConfigSnapshot.reset(); }\n\n};\n\nstruct MyProtonConfigurerOwner;\n\nstruct MyDocumentDBConfigOwner : public DocumentDBConfigOwner\n{\n    vespalib::string _name;\n    document::BucketSpace _bucket_space;\n    MyProtonConfigurerOwner &_owner;\n    MyDocumentDBConfigOwner(const vespalib::string &name,\n                            document::BucketSpace bucket_space,\n                            MyProtonConfigurerOwner &owner)\n        : DocumentDBConfigOwner(),\n          _name(name),\n          _bucket_space(bucket_space),\n          _owner(owner)\n    {\n    }\n    ~MyDocumentDBConfigOwner() { }\n\n    void reconfigure(const DocumentDBConfig::SP & config) override;\n    document::BucketSpace getBucketSpace() const override { return _bucket_space; }\n};\n\nstruct MyLog\n{\n    std::vector<vespalib::string> _log;\n\n    MyLog()\n        : _log()\n    {\n    }\n\n    void appendLog(vespalib::string logEntry)\n    {\n        _log.emplace_back(logEntry);\n    }\n};\n\nstruct MyProtonConfigurerOwner : public IProtonConfigurerOwner,\n                                 public MyLog\n{\n    vespalib::ThreadStackExecutor _executor;\n    std::map<DocTypeName, std::shared_ptr<MyDocumentDBConfigOwner>> _dbs;\n\n    MyProtonConfigurerOwner()\n        : IProtonConfigurerOwner(),\n          MyLog(),\n          _executor(1, 128_Ki),\n          _dbs()\n    {\n    }\n    ~MyProtonConfigurerOwner() { }\n\n    std::shared_ptr<DocumentDBConfigOwner> addDocumentDB(const DocTypeName &docTypeName,\n                                                                 document::BucketSpace bucketSpace,\n                                                                 const vespalib::string &configId,\n                                                                 const std::shared_ptr<BootstrapConfig> &bootstrapConfig,\n                                                                 const std::shared_ptr<DocumentDBConfig> &documentDBConfig,\n                                                                 InitializeThreads initializeThreads) override\n    {\n        (void) bucketSpace;\n        (void) configId;\n        (void) bootstrapConfig;\n        (void) initializeThreads;\n        EXPECT_TRUE(_dbs.find(docTypeName) == _dbs.end());\n        auto db = std::make_shared<MyDocumentDBConfigOwner>(docTypeName.getName(), bucketSpace, *this);\n        _dbs.insert(std::make_pair(docTypeName, db));\n        std::ostringstream os;\n        os << \"add db \" << docTypeName.getName() << \" \" << documentDBConfig->getGeneration();\n        _log.push_back(os.str());\n        return db;\n    }\n    void removeDocumentDB(const DocTypeName &docTypeName) override {\n        ASSERT_FALSE(_dbs.find(docTypeName) == _dbs.end());\n        _dbs.erase(docTypeName);\n        std::ostringstream os;\n        os << \"remove db \" << docTypeName.getName();\n        _log.push_back(os.str());\n    }\n    void applyConfig(const std::shared_ptr<BootstrapConfig> &bootstrapConfig) override {\n        std::ostringstream os;\n        os << \"apply config \" << bootstrapConfig->getGeneration();\n        _log.push_back(os.str());\n        \n    }\n    void reconfigureDocumentDB(const vespalib::string &name, const DocumentDBConfig::SP &config)\n    {\n        std::ostringstream os;\n        os << \"reconf db \" << name << \" \" << config->getGeneration();\n        _log.push_back(os.str());\n    }\n    void sync() { _executor.sync(); }\n};\n\nvoid\nMyDocumentDBConfigOwner::reconfigure(const DocumentDBConfig::SP & config)\n{\n    _owner.reconfigureDocumentDB(_name, config);\n}\n\nstruct MyProtonDiskLayout : public IProtonDiskLayout\n{\n    MyLog &_log;\n\n    MyProtonDiskLayout(MyLog &myLog)\n        : _log(myLog)\n    {\n    }\n    void remove(const DocTypeName &docTypeName) override {\n        std::ostringstream os;\n        os << \"remove dbdir \" << docTypeName.getName();\n        _log.appendLog(os.str());\n    }\n    void initAndPruneUnused(const std::set<DocTypeName> &docTypeNames) override {\n        std::ostringstream os;\n        os << \"initial dbs \";\n        bool first = true;\n        for (const auto &docTypeName : docTypeNames) {\n            if (!first) {\n                os << \",\";\n            }\n            first = false;\n            os << docTypeName.getName();\n        }\n        _log.appendLog(os.str());\n    }\n};\n\nclass ProtonConfigurerTest : public ::testing::Test\n{\n    MyProtonConfigurerOwner _owner;\n    ConfigFixture _config;\n    std::unique_ptr<IProtonDiskLayout> _diskLayout;\n    ProtonConfigurer _configurer;\n\nprotected:\n    ProtonConfigurerTest()\n        : _owner(),\n          _config(\"test\"),\n          _diskLayout(),\n          _configurer(_owner._executor, _owner, _diskLayout)\n    {\n        _diskLayout = std::make_unique<MyProtonDiskLayout>(_owner);\n    }\n    ~ProtonConfigurerTest() override;\n\n    void assertLog(const std::vector<vespalib::string> &expLog) {\n        EXPECT_EQ(expLog, _owner._log);\n    }\n    void sync() { _owner.sync(); }\n    void addDocType(const vespalib::string &name, const std::string& bucket_space = \"default\") { _config.addDocType(name, bucket_space); }\n    void removeDocType(const vespalib::string &name) { _config.removeDocType(name); }\n    void applyConfig() {\n        _configurer.reconfigure(_config.getConfigSnapshot());\n        sync();\n    }\n\n    void applyInitialConfig() {\n        applyConfig(); \/\/ sets initial pending config\n        _configurer.applyInitialConfig(InitializeThreads());\n    }\n    void reconfigure() {\n        _config.newConfig();\n        applyConfig();\n    }\n\n    void allowReconfig() {\n        _configurer.setAllowReconfig(true);\n        sync();\n    }\n    void disableReconfig() {\n        _configurer.setAllowReconfig(false);\n    }\n};\n\nProtonConfigurerTest::~ProtonConfigurerTest() = default;\n\nTEST_F(ProtonConfigurerTest, require_that_nothing_is_applied_before_initial_config)\n{\n    applyConfig();\n    assertLog({});\n}\n\nTEST_F(ProtonConfigurerTest, require_that_initial_config_is_applied)\n{\n    applyInitialConfig();\n    assertLog({\"initial dbs _alwaysthere_\", \"apply config 2\", \"add db _alwaysthere_ 2\"});\n}\n\nTEST_F(ProtonConfigurerTest, require_that_new_config_is_blocked)\n{\n    applyInitialConfig();\n    reconfigure();\n    assertLog({\"initial dbs _alwaysthere_\", \"apply config 2\", \"add db _alwaysthere_ 2\"});\n}\n\nTEST_F(ProtonConfigurerTest, require_that_new_config_can_be_unblocked)\n{\n    applyInitialConfig();\n    reconfigure();\n    allowReconfig();\n    assertLog({\"initial dbs _alwaysthere_\", \"apply config 2\", \"add db _alwaysthere_ 2\", \"apply config 3\", \"reconf db _alwaysthere_ 3\"});\n}\n\nTEST_F(ProtonConfigurerTest, require_that_initial_config_is_not_reapplied_due_to_config_unblock)\n{\n    applyInitialConfig();\n    allowReconfig();\n    assertLog({\"initial dbs _alwaysthere_\", \"apply config 2\", \"add db _alwaysthere_ 2\"});\n}\n\nTEST_F(ProtonConfigurerTest, require_that_we_can_add_document_db)\n{\n    applyInitialConfig();\n    allowReconfig();\n    addDocType(\"foobar\");\n    reconfigure();\n    assertLog({\"initial dbs _alwaysthere_\", \"apply config 2\", \"add db _alwaysthere_ 2\", \"apply config 3\",\"reconf db _alwaysthere_ 3\", \"add db foobar 3\"});\n}\n\nTEST_F(ProtonConfigurerTest, require_that_we_can_remove_document_db)\n{\n    addDocType(\"foobar\");\n    applyInitialConfig();\n    allowReconfig();\n    removeDocType(\"foobar\");\n    reconfigure();\n    assertLog({\"initial dbs _alwaysthere_,foobar\", \"apply config 2\", \"add db _alwaysthere_ 2\", \"add db foobar 2\", \"apply config 3\",\"reconf db _alwaysthere_ 3\", \"remove db foobar\", \"remove dbdir foobar\"});\n}\n\nTEST_F(ProtonConfigurerTest, require_that_document_db_adds_and_reconfigs_are_intermingled)\n{\n    addDocType(\"foobar\");\n    applyInitialConfig();\n    allowReconfig();\n    addDocType(\"abar\");\n    removeDocType(\"foobar\");\n    addDocType(\"foobar\");\n    addDocType(\"zbar\");\n    reconfigure();\n    assertLog({\"initial dbs _alwaysthere_,foobar\", \"apply config 2\", \"add db _alwaysthere_ 2\", \"add db foobar 2\", \"apply config 3\",\"reconf db _alwaysthere_ 3\", \"add db abar 3\", \"reconf db foobar 3\", \"add db zbar 3\"});\n}\n\nTEST_F(ProtonConfigurerTest, require_that_document_db_removes_are_applied_at_end)\n{\n    addDocType(\"abar\");\n    addDocType(\"foobar\");\n    applyInitialConfig();\n    allowReconfig();\n    removeDocType(\"abar\");\n    reconfigure();\n    assertLog({\"initial dbs _alwaysthere_,abar,foobar\", \"apply config 2\", \"add db _alwaysthere_ 2\", \"add db abar 2\", \"add db foobar 2\", \"apply config 3\",\"reconf db _alwaysthere_ 3\", \"reconf db foobar 3\", \"remove db abar\", \"remove dbdir abar\"});\n}\n\nTEST_F(ProtonConfigurerTest, require_that_new_configs_can_be_blocked_again)\n{\n    applyInitialConfig();\n    reconfigure();\n    allowReconfig();\n    disableReconfig();\n    reconfigure();\n    assertLog({\"initial dbs _alwaysthere_\", \"apply config 2\", \"add db _alwaysthere_ 2\", \"apply config 3\", \"reconf db _alwaysthere_ 3\"});\n}\n\nTEST_F(ProtonConfigurerTest, require_that_bucket_space_for_document_type_change_exits)\n{\n    ::testing::FLAGS_gtest_death_test_style = \"threadsafe\";\n    addDocType(\"globaldoc\", \"default\");\n    applyInitialConfig();\n    removeDocType(\"globaldoc\");\n    addDocType(\"globaldoc\", \"global\");\n    allowReconfig();\n    EXPECT_EXIT(reconfigure(), ::testing::ExitedWithCode(1), \"Bucket space for document type globaldoc changed from default to global\");\n}\n\n\nGTEST_MAIN_RUN_ALL_TESTS()\n","avg_line_length":36.6614173228,"max_line_length":244,"alphanum_fraction":0.6444909794,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3087,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":6.0,"content":"\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2018-2021 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <inviwo\/tensorvisbase\/processors\/invariantspacetodataframe.h>\n\nnamespace inviwo {\n\n\/\/ The Class Identifier has to be globally unique. Use a reverse DNS naming scheme\nconst ProcessorInfo InvariantSpaceToDataFrame::processorInfo_{\n    \"org.inviwo.InvariantSpaceToDataFrame\",  \/\/ Class identifier\n    \"Invariant Space To Data Frame\",         \/\/ Display name\n    \"Tensor\",                                \/\/ Category\n    CodeState::Experimental,                 \/\/ Code state\n    Tags::CPU,                               \/\/ Tags\n};\nconst ProcessorInfo InvariantSpaceToDataFrame::getProcessorInfo() const { return processorInfo_; }\n\nInvariantSpaceToDataFrame::InvariantSpaceToDataFrame()\n    : Processor(), inport_(\"inport\"), outport_(\"outport\") {\n\n    addPort(inport_);\n    addPort(outport_);\n}\n\nvoid InvariantSpaceToDataFrame::process() {\n    const auto& invariantSpace = *inport_.getData();\n\n    auto dataFrame = std::make_shared<DataFrame>();\n\n    size_t i{0};\n    for (const auto axis : invariantSpace) {\n        auto buffer = std::make_shared<Buffer<glm::f32>>();\n\n        buffer->setSize(axis->size());\n\n        const auto data = axis->data();\n\n        for (size_t j{0}; j < axis->size(); ++j) {\n            buffer->getEditableRepresentation<BufferRAM>()->setFromDouble(j, data[j]);\n        }\n\n        dataFrame->addColumnFromBuffer(invariantSpace.getIdentifier(i), buffer);\n\n        i++;\n    }\n\n    dataFrame->updateIndexBuffer();\n\n    outport_.setData(dataFrame);\n}\n\n}  \/\/ namespace inviwo\n","avg_line_length":39.0759493671,"max_line_length":98,"alphanum_fraction":0.6712018141,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":762,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ link to the problem: https:\/\/leetcode.com\/problems\/zigzag-conversion\/\n#include <iostream>\n#include <string>\n\nclass Solution {\n public:\n  std::string convert(std::string s, int numRows) {\n    if (numRows == 1) return s;\n    std::string answer;\n    for (int i = 0; i < s.size(); i += 2 * (numRows - 1)) {\n      answer += s[i];\n    }\n\n    for (int i = 1; i < numRows - 1; i++) {\n      for (int j = 0; j < s.size(); j += 2 * (numRows - 1)) {\n        if (j + i < s.size()) answer += s[j + i];\n        if (j + 2 * (numRows - 1) - i < s.size()) answer += s[j + 2 * (numRows - 1) - i];\n      }\n    }\n\n    for (int i = 0; i < s.size(); i += 2 * (numRows - 1)) {\n      if (i + numRows - 1 < s.size())\n      answer += s[i + numRows - 1];\n    }\n    return answer;\n  }\n};\n","avg_line_length":27.2142857143,"max_line_length":89,"alphanum_fraction":0.4816272966,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":35335,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Condor-1.1"],"max_stars_count":null,"content":"\/*\n *\tPROGRAM:\tJRD Remote Interface\/Server\n *\tMODULE:\t\twnet.cpp\n *\tDESCRIPTION:\tWindows Net Communications module.\n *\n * The contents of this file are subject to the Interbase Public\n * License Version 1.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy\n * of the License at http:\/\/www.Inprise.com\/IPL.html\n *\n * Software distributed under the License is distributed on an\n * \"AS IS\" basis, WITHOUT WARRANTY OF ANY KIND, either express\n * or implied. See the License for the specific language governing\n * rights and limitations under the License.\n *\n * The Original Code was created by Inprise Corporation\n * and its predecessors. Portions created by Inprise Corporation are\n * Copyright (C) Inprise Corporation.\n *\n * All Rights Reserved.\n * Contributor(s): ______________________________________.\n *\/\n\n#ifdef DEBUG\n\/\/ define WNET_trace to 0 (zero) for no packet debugging\n#define WNET_trace\n#endif\n\n#include \"firebird.h\"\n#include <stdio.h>\n#include <string.h>\n#include \"..\/remote\/remote.h\"\n#include \"ibase.h\"\n\n#include \"..\/utilities\/install\/install_nt.h\"\n\n#include \"..\/remote\/proto_proto.h\"\n#include \"..\/remote\/remot_proto.h\"\n#include \"..\/remote\/os\/win32\/wnet_proto.h\"\n#include \"..\/yvalve\/gds_proto.h\"\n#include \"..\/common\/isc_proto.h\"\n#include \"..\/common\/isc_f_proto.h\"\n#include \"..\/common\/config\/config.h\"\n#include \"..\/common\/utils_proto.h\"\n#include \"..\/common\/classes\/ClumpletWriter.h\"\n#include \"..\/common\/classes\/init.h\"\n\n#include <stdarg.h>\n\nusing namespace Firebird;\n\nconst int MAX_DATA\t\t= 2048;\nconst int BUFFER_SIZE\t= MAX_DATA;\n\nconst char* PIPE_PREFIX\t\t\t= \"pipe\"; \/\/ win32-specific\nconst char* SERVER_PIPE_SUFFIX\t= \"server\";\nconst char* EVENT_PIPE_SUFFIX\t= \"event\";\nAtomicCounter event_counter;\n\nstatic GlobalPtr<PortsCleanup> wnet_ports;\nstatic GlobalPtr<Mutex> init_mutex;\nstatic volatile bool wnet_initialized = false;\nstatic volatile bool wnet_shutdown = false;\n\nstatic bool\t\taccept_connection(rem_port*, const P_CNCT*);\nstatic rem_port*\t\talloc_port(rem_port*);\nstatic rem_port*\t\taux_connect(rem_port*, PACKET*);\nstatic rem_port*\t\taux_request(rem_port*, PACKET*);\nstatic bool\t\tconnect_client(rem_port*);\nstatic void\t\tdisconnect(rem_port*);\n#ifdef NOT_USED_OR_REPLACED\nstatic void\t\texit_handler(void*);\n#endif\nstatic void\t\tforce_close(rem_port*);\nstatic rem_str*\t\tmake_pipe_name(const RefPtr<const Config>&, const TEXT*, const TEXT*, const TEXT*);\nstatic rem_port*\treceive(rem_port*, PACKET*);\nstatic int\t\tsend_full(rem_port*, PACKET*);\nstatic int\t\tsend_partial(rem_port*, PACKET*);\nstatic RemoteXdr*\t\txdrwnet_create(rem_port*, UCHAR *, USHORT, xdr_op);\nstatic bool_t\txdrwnet_endofrecord(RemoteXdr*);\/\/, int);\nstatic bool\t\twnet_error(rem_port*, const TEXT*, ISC_STATUS, int);\nstatic void\t\twnet_gen_error(rem_port*, const Arg::StatusVector& v);\nstatic bool_t\twnet_read(RemoteXdr*);\nstatic bool_t\twnet_write(RemoteXdr*); \/\/, int);\n#ifdef DEBUG\nstatic void\t\tpacket_print(const TEXT*, const UCHAR*, const int);\n#endif\nstatic bool\t\tpacket_receive(rem_port*, UCHAR*, SSHORT, SSHORT*);\nstatic bool\t\tpacket_send(rem_port*, const SCHAR*, SSHORT);\nstatic void\t\twnet_make_file_name(TEXT*, DWORD);\n\nstatic int\t\tcleanup_ports(const int, const int, void*);\n\nstruct WnetXdr : public RemoteXdr\n{\n\tvirtual bool_t x_getbytes(SCHAR *, unsigned);\t\t\/\/ get some bytes from \"\n\tvirtual bool_t x_putbytes(const SCHAR*, unsigned);\t\/\/ put some bytes to \"\n};\n\n\nrem_port* WNET_analyze(ClntAuthBlock* cBlock,\n\t\t\t\t\t   const PathName& file_name,\n\t\t\t\t\t   const TEXT* node_name,\n\t\t\t\t\t   bool uv_flag,\n\t\t\t\t\t   RefPtr<const Config>* config,\n\t\t\t\t\t   const Firebird::PathName* ref_db_name)\n{\n\/**************************************\n *\n *\tW N E T _ a n a l y z e\n *\n **************************************\n *\n * Functional description\n *\tDetermine whether the file name has a \"\\\\nodename\".\n *\tIf so, establish an external connection to the node.\n *\n *\tIf a connection is established, return a port block, otherwise\n *\treturn NULL.\n *\n **************************************\/\n\n\t\/\/ We need to establish a connection to a remote server.  Allocate the necessary\n\t\/\/ blocks and get ready to go.\n\n\tRdb* rdb = FB_NEW Rdb;\n\tPACKET* packet = &rdb->rdb_packet;\n\n\t\/\/ Pick up some user identification information\n\tstring buffer;\n\tClumpletWriter user_id(ClumpletReader::UnTagged, 64000);\n\tif (cBlock)\n\t{\n\t\tcBlock->extractDataFromPluginTo(user_id);\n\t}\n\n\tISC_get_user(&buffer, 0, 0);\n\tbuffer.lower();\n\tISC_systemToUtf8(buffer);\n\tuser_id.insertString(CNCT_user, buffer);\n\n\tISC_get_host(buffer);\n\tbuffer.lower();\n\tISC_systemToUtf8(buffer);\n\tuser_id.insertString(CNCT_host, buffer);\n\n\tif (uv_flag) {\n\t\tuser_id.insertTag(CNCT_user_verification);\n\t}\n\n\t\/\/ Establish connection to server\n\n\tP_CNCT* const cnct = &packet->p_cnct;\n\tpacket->p_operation = op_connect;\n\tcnct->p_cnct_operation = 0;\n\tcnct->p_cnct_cversion = CONNECT_VERSION3;\n\tcnct->p_cnct_client = ARCHITECTURE;\n\n\tconst PathName& cnct_file(ref_db_name ? (*ref_db_name) : file_name);\n\tcnct->p_cnct_file.cstr_length = (ULONG) cnct_file.length();\n\tcnct->p_cnct_file.cstr_address = reinterpret_cast<const UCHAR*>(cnct_file.c_str());\n\n\t\/\/ If we want user verification, we can't speak anything less than version 7\n\n\tcnct->p_cnct_user_id.cstr_length = (ULONG) user_id.getBufferLength();\n\tcnct->p_cnct_user_id.cstr_address = user_id.getBuffer();\n\n\tstatic const p_cnct::p_cnct_repeat protocols_to_try[] =\n\t{\n\t\tREMOTE_PROTOCOL(PROTOCOL_VERSION10, ptype_batch_send, 1),\n\t\tREMOTE_PROTOCOL(PROTOCOL_VERSION11, ptype_batch_send, 2),\n\t\tREMOTE_PROTOCOL(PROTOCOL_VERSION12, ptype_batch_send, 3),\n\t\tREMOTE_PROTOCOL(PROTOCOL_VERSION13, ptype_batch_send, 4),\n\t\tREMOTE_PROTOCOL(PROTOCOL_VERSION14, ptype_batch_send, 5),\n\t\tREMOTE_PROTOCOL(PROTOCOL_VERSION15, ptype_batch_send, 6),\n\t\tREMOTE_PROTOCOL(PROTOCOL_VERSION16, ptype_batch_send, 7)\n\t};\n\tfb_assert(FB_NELEM(protocols_to_try) <= FB_NELEM(cnct->p_cnct_versions));\n\tcnct->p_cnct_count = FB_NELEM(protocols_to_try);\n\n\tfor (size_t i = 0; i < cnct->p_cnct_count; i++) {\n\t\tcnct->p_cnct_versions[i] = protocols_to_try[i];\n\t}\n\n\t\/\/ If we can't talk to a server, punt. Let somebody else generate an error.\n\n\trem_port* port = NULL;\n\ttry\n\t{\n\t\tport = WNET_connect(node_name, packet, 0, config);\n\t}\n\tcatch (const Exception&)\n\t{\n\t\tdelete rdb;\n\t\tthrow;\n\t}\n\n\t\/\/ Get response packet from server.\n\n\trdb->rdb_port = port;\n\tport->port_context = rdb;\n\tport->receive(packet);\n\n\tP_ACPT* accept = NULL;\n\tswitch (packet->p_operation)\n\t{\n\tcase op_accept_data:\n\tcase op_cond_accept:\n\t\taccept = &packet->p_acpd;\n\t\tif (cBlock)\n\t\t{\n\t\t\tcBlock->storeDataForPlugin(packet->p_acpd.p_acpt_data.cstr_length,\n\t\t\t\t\t\t\t\t\t   packet->p_acpd.p_acpt_data.cstr_address);\n\t\t\tcBlock->authComplete = packet->p_acpd.p_acpt_authenticated;\n\t\t\tport->addServerKeys(&packet->p_acpd.p_acpt_keys);\n\t\t\tcBlock->resetClnt(&packet->p_acpd.p_acpt_keys);\n\t\t}\n\t\tbreak;\n\n\tcase op_accept:\n\t\tif (cBlock)\n\t\t{\n\t\t\tcBlock->resetClnt();\n\t\t}\n\t\taccept = &packet->p_acpt;\n\t\tbreak;\n\n\tcase op_response:\n\t\ttry\n\t\t{\n\t\t\tFirebird::LocalStatus warning;\t\t\/\/ Ignore connect warnings for a while\n\t\t\tREMOTE_check_response(&warning, rdb, packet);\n\t\t}\n\t\tcatch (const Firebird::Exception&)\n\t\t{\n\t\t\tdisconnect(port);\n\t\t\tdelete rdb;\n\t\t\tthrow;\n\t\t}\n\t\t\/\/ fall through - response is not a required accept\n\n\tdefault:\n\t\tdisconnect(port);\n\t\tdelete rdb;\n\t\tArg::Gds(isc_connect_reject).raise();\n\t\tbreak;\n\t}\n\n\tfb_assert(accept);\n\tfb_assert(port);\n\tport->port_protocol = accept->p_acpt_version;\n\n\t\/\/ once we've decided on a protocol, concatenate the version\n\t\/\/ string to reflect it...\n\n\tstring temp;\n\ttemp.printf(\"%s\/P%d\", port->port_version->str_data,\n\t\t\t\t\t\t  port->port_protocol & FB_PROTOCOL_MASK);\n\tdelete port->port_version;\n\tport->port_version = REMOTE_make_string(temp.c_str());\n\n\tif (accept->p_acpt_architecture == ARCHITECTURE)\n\t\tport->port_flags |= PORT_symmetric;\n\n\tif (accept->p_acpt_type != ptype_out_of_band)\n\t\tport->port_flags |= PORT_no_oob;\n\n\treturn port;\n}\n\n\nrem_port* WNET_connect(const TEXT* name, PACKET* packet, USHORT flag, Firebird::RefPtr<const Config>* config)\n{\n\/**************************************\n *\n *\tW N E T _ c o n n e c t\n *\n **************************************\n *\n * Functional description\n *\tEstablish half of a communication link.  If a connect packet is given,\n *\tthe connection is on behalf of a remote interface.  Otherwise the\n *\tconnect is for a server process.\n *\n **************************************\/\n\trem_port* const port = alloc_port(0);\n\tif (config)\n\t{\n\t\tport->port_config = *config;\n\t}\n\n\tdelete port->port_connection;\n\tport->port_connection = make_pipe_name(port->getPortConfig(), name, SERVER_PIPE_SUFFIX, 0);\n\n\t\/\/ If we're a host, just make the connection\n\n\tif (packet)\n\t{\n\t\twhile (true)\n\t\t{\n\t\t\tport->port_pipe = CreateFile(port->port_connection->str_data,\n\t\t\t\t\t\t\t\t\t\t GENERIC_WRITE | GENERIC_READ,\n\t\t\t\t\t\t\t\t\t\t 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);\n\t\t\tif (port->port_pipe != INVALID_HANDLE_VALUE) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tconst ISC_STATUS status = GetLastError();\n\t\t\tif (status != ERROR_PIPE_BUSY)\n\t\t\t{\n\t\t\t\twnet_error(port, \"CreateFile\", isc_net_connect_err, status);\n\t\t\t\tdisconnect(port);\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tWaitNamedPipe(port->port_connection->str_data, 3000L);\n\t\t}\n\t\tsend_full(port, packet);\n\t\treturn port;\n\t}\n\n\t\/\/ We're a server, so wait for a host to show up\n\n\twnet_ports->registerPort(port);\n\twhile (!wnet_shutdown)\n\t{\n\t\tport->port_pipe =\n\t\t\tCreateNamedPipe(port->port_connection->str_data,\n\t\t\t\t\t\t\tPIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,\n\t\t\t\t\t\t\tPIPE_WAIT | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,\n\t\t\t\t\t\t\tPIPE_UNLIMITED_INSTANCES,\n\t\t\t\t\t\t\tMAX_DATA,\n\t\t\t\t\t\t\tMAX_DATA,\n\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\tISC_get_security_desc());\n\t\tif (port->port_pipe == INVALID_HANDLE_VALUE)\n\t\t{\n\t\t\tconst DWORD dwError = GetLastError();\n\t\t\tif (dwError == ERROR_CALL_NOT_IMPLEMENTED)\n\t\t\t{\n\t\t\t\tdisconnect(port);\n\t\t\t\twnet_shutdown = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\twnet_error(port, \"CreateNamedPipe\", isc_net_connect_listen_err, dwError);\n\t\t\tdisconnect(port);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (!connect_client(port))\n\t\t\tbreak;\n\n\t\tif (flag & (SRVR_debug | SRVR_multi_client))\n\t\t{\n\t\t\tport->port_server_flags |= SRVR_server;\n\t\t\tport->port_flags |= PORT_server;\n\t\t\tif (flag & SRVR_multi_client)\n\t\t\t{\n\t\t\t\tport->port_server_flags |= SRVR_multi_client;\n\t\t\t}\n\n\t\t\treturn port;\n\t\t}\n\n\t\tTEXT name[MAXPATHLEN];\n\t\tGetModuleFileName(NULL, name, sizeof(name));\n\n\t\tstring cmdLine;\n\t\tcmdLine.printf(\"%s -w -h %\" HANDLEFORMAT\"@%\" ULONGFORMAT, name, port->port_pipe, GetCurrentProcessId());\n\n\t\tSTARTUPINFO start_crud;\n\t\tPROCESS_INFORMATION pi;\n\t\tstart_crud.cb = sizeof(STARTUPINFO);\n\t\tstart_crud.lpReserved = NULL;\n\t\tstart_crud.lpReserved2 = NULL;\n\t\tstart_crud.cbReserved2 = 0;\n\t\tstart_crud.lpDesktop = NULL;\n\t\tstart_crud.lpTitle = NULL;\n\t\tstart_crud.dwFlags = STARTF_FORCEOFFFEEDBACK;\n\n\t\tif (CreateProcess(NULL, cmdLine.begin(), NULL, NULL, FALSE,\n\t\t\t\t\t\t  (flag & SRVR_high_priority ?\n\t\t\t\t\t\t\t HIGH_PRIORITY_CLASS | DETACHED_PROCESS :\n\t\t\t\t\t\t\t NORMAL_PRIORITY_CLASS | DETACHED_PROCESS),\n\t\t\t\t\t\t  NULL, NULL, &start_crud, &pi))\n\t\t{\n\t\t\t\/\/ hvlad: child process will close our handle of client pipe\n\t\t\tCloseHandle(pi.hThread);\n\t\t\tCloseHandle(pi.hProcess);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgds__log(\"WNET\/wnet_error: fork\/CreateProcess errno = %d\", GetLastError());\n\t\t\tCloseHandle(port->port_pipe);\n\t\t}\n\n\t\tif (wnet_shutdown)\n\t\t\tdisconnect(port);\n\t}\n\n\tif (wnet_shutdown)\n\t{\n\t\tArg::Gds temp(isc_net_server_shutdown);\n\t\ttemp << Arg::Str(\"WNET\");\n\t\ttemp.raise();\n\t}\n\n\treturn NULL;\n}\n\n\nrem_port* WNET_reconnect(HANDLE handle)\n{\n\/**************************************\n *\n *\tW N E T _ r e c o n n e c t\n *\n **************************************\n *\n * Functional description\n *\tA communications link has been established by another\n *\tprocess.  We have inherited the handle.  Set up\n *\ta port block.\n *\n **************************************\/\n\trem_port* const port = alloc_port(0);\n\n\tdelete port->port_connection;\n\tport->port_connection = make_pipe_name(port->getPortConfig(), NULL, SERVER_PIPE_SUFFIX, 0);\n\n\tport->port_pipe = handle;\n\tport->port_server_flags |= SRVR_server;\n\tport->port_flags |= PORT_server;\n\n\treturn port;\n}\n\n\nstatic bool accept_connection( rem_port* port, const P_CNCT* cnct)\n{\n\/**************************************\n *\n *\ta c c e p t _ c o n n e c t i o n\n *\n **************************************\n *\n * Functional description\n *\tAccept an incoming request for connection.  This is purely a lower\n *\tlevel handshaking function, and does not constitute the server\n *\tresponse for protocol selection.\n *\n **************************************\/\n\t\/\/ Default account to \"guest\" (in theory all packets contain a name)\n\n\tstring user_name(\"guest\"), host_name;\n\n\t\/\/ Pick up account and host name, if given\n\n\tClumpletReader id(ClumpletReader::UnTagged,\n\t\t\t\t\t  cnct->p_cnct_user_id.cstr_address,\n\t\t\t\t\t  cnct->p_cnct_user_id.cstr_length);\n\n\tfor (id.rewind(); !id.isEof(); id.moveNext())\n\t{\n\t\tswitch (id.getClumpTag())\n\t\t{\n\t\tcase CNCT_user:\n\t\t\tid.getString(user_name);\n\t\t\tbreak;\n\n\t\tcase CNCT_host:\n\t\t\tid.getString(host_name);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tport->port_login = port->port_user_name = user_name;\n\tport->port_peer_name = host_name;\n\tport->port_protocol_id = \"WNET\";\n\n\treturn true;\n}\n\n\nstatic rem_port* alloc_port( rem_port* parent)\n{\n\/**************************************\n *\n *\ta l l o c _ p o r t\n *\n **************************************\n *\n * Functional description\n *\tAllocate a port block, link it in to parent (if there is a parent),\n *\tand initialize input and output XDR streams.\n *\n **************************************\/\n\n\tif (!wnet_initialized)\n\t{\n\t\tMutexLockGuard guard(init_mutex, FB_FUNCTION);\n\t\tif (!wnet_initialized)\n\t\t{\n\t\t\twnet_initialized = true;\n\t\t\tfb_shutdown_callback(0, cleanup_ports, fb_shut_postproviders, 0);\n\t\t}\n\t}\n\n\trem_port* port = FB_NEW rem_port(rem_port::PIPE, BUFFER_SIZE * 2);\n\n\tTEXT buffer[BUFFER_TINY];\n\tISC_get_host(buffer, sizeof(buffer));\n\tport->port_host = REMOTE_make_string(buffer);\n\tport->port_connection = REMOTE_make_string(buffer);\n\tsprintf(buffer, \"WNet (%s)\", port->port_host->str_data);\n\tport->port_version = REMOTE_make_string(buffer);\n\n\tport->port_accept = accept_connection;\n\tport->port_disconnect = disconnect;\n\tport->port_force_close = force_close;\n\tport->port_receive_packet = receive;\n\tport->port_send_packet = send_full;\n\tport->port_send_partial = send_partial;\n\tport->port_connect = aux_connect;\n\tport->port_request = aux_request;\n\tport->port_buff_size = BUFFER_SIZE;\n\n\tport->port_event = CreateEvent(NULL, TRUE, TRUE, NULL);\n\n\tport->port_send = xdrwnet_create(port, &port->port_buffer[BUFFER_SIZE], BUFFER_SIZE, XDR_ENCODE);\n\n\tport->port_receive = xdrwnet_create(port, port->port_buffer, 0, XDR_DECODE);\n\n\tif (parent)\n\t{\n\t\tdelete port->port_connection;\n\t\tport->port_connection = nullptr;\n\t\tport->port_connection = REMOTE_make_string(parent->port_connection->str_data);\n\n\t\tport->linkParent(parent);\n\t}\n\n\treturn port;\n}\n\n\nstatic rem_port* aux_connect( rem_port* port, PACKET* packet)\n{\n\/**************************************\n *\n *\ta u x _ c o n n e c t\n *\n **************************************\n *\n * Functional description\n *\tTry to establish an alternative connection.  Somebody has already\n *\tdone a successfull connect request (\"packet\" contains the response).\n *\n **************************************\/\n\t\/\/ If this is a server, we're got an auxiliary connection.  Accept it\n\n\tif (port->port_server_flags)\n\t{\n\t\tif (!connect_client(port))\n\t\t\treturn NULL;\n\n\t\tport->port_flags |= PORT_async;\n\t\treturn port;\n\t}\n\n\t\/\/ The server will be sending its process id in the packet to\n\t\/\/ create a unique pipe name.\n\n\tP_RESP* response = &packet->p_resp;\n\n\tTEXT str_pid[32];\n\tconst TEXT* p = 0;\n\tif (response->p_resp_data.cstr_length)\n\t{\n\t\t\/\/ Avoid B.O.\n\t\tconst size_t len = MIN(response->p_resp_data.cstr_length, sizeof(str_pid) - 1);\n\t\tmemcpy(str_pid, response->p_resp_data.cstr_address, len);\n\t\tstr_pid[len] = 0;\n\t\tp = str_pid;\n\t}\n\n\trem_port* const new_port = alloc_port(port->port_parent);\n\tport->port_async = new_port;\n\tnew_port->port_flags = port->port_flags & PORT_no_oob;\n\tnew_port->port_flags |= PORT_async;\n\tnew_port->port_connection = make_pipe_name(port->getPortConfig(),\n\t\tport->port_connection->str_data, EVENT_PIPE_SUFFIX, p);\n\n\twhile (true)\n\t{\n\t\tnew_port->port_pipe =\n\t\t\tCreateFile(new_port->port_connection->str_data, GENERIC_READ, 0,\n\t\t\t\t\t   NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);\n\t\tif (new_port->port_pipe != INVALID_HANDLE_VALUE)\n\t\t\tbreak;\n\t\tconst ISC_STATUS status = GetLastError();\n\t\tif (status != ERROR_PIPE_BUSY)\n\t\t{\n\t\t\twnet_error(new_port, \"CreateFile\", isc_net_event_connect_err, status);\n\t\t\treturn NULL;\n\t\t}\n\t\tWaitNamedPipe(new_port->port_connection->str_data, 3000L);\n\t}\n\n\treturn new_port;\n}\n\n\nstatic rem_port* aux_request( rem_port* vport, PACKET* packet)\n{\n\/**************************************\n *\n *\ta u x _ r e q u e s t\n *\n **************************************\n *\n * Functional description\n *\tA remote interface has requested the server prepare an auxiliary\n *\tconnection; the server calls aux_request to set up the connection.\n *\tSend the servers process id on the packet.  If at a later time\n *\ta multi client server is used, there may be a need to\n *\tgenerate a unique id based on connection.\n *\n **************************************\/\n\n\tconst DWORD server_pid = (vport->port_server_flags & SRVR_multi_client) ?\n\t\t++event_counter : GetCurrentProcessId();\n\trem_port* const new_port = alloc_port(vport->port_parent);\n\tnew_port->port_server_flags = vport->port_server_flags;\n\tnew_port->port_flags = (vport->port_flags & PORT_no_oob) | PORT_connecting;\n\tvport->port_async = new_port;\n\n\tTEXT str_pid[32];\n\twnet_make_file_name(str_pid, server_pid);\n\tnew_port->port_connection = make_pipe_name(vport->getPortConfig(),\n\t\tvport->port_connection->str_data, EVENT_PIPE_SUFFIX, str_pid);\n\n\tnew_port->port_pipe =\n\t\tCreateNamedPipe(new_port->port_connection->str_data,\n\t\t\t\t\t\tPIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,\n\t\t\t\t\t\tPIPE_WAIT | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,\n\t\t\t\t\t\tPIPE_UNLIMITED_INSTANCES,\n\t\t\t\t\t\tMAX_DATA,\n\t\t\t\t\t\tMAX_DATA,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tISC_get_security_desc());\n\n\tif (new_port->port_pipe == INVALID_HANDLE_VALUE)\n\t{\n\t\twnet_error(new_port, \"CreateNamedPipe\", isc_net_event_listen_err, ERRNO);\n\t\tdisconnect(new_port);\n\t\treturn NULL;\n\t}\n\n\tP_RESP* response = &packet->p_resp;\n\tresponse->p_resp_data.cstr_length = (ULONG) strlen(str_pid);\n\tmemcpy(response->p_resp_data.cstr_address, str_pid, response->p_resp_data.cstr_length);\n\n\treturn new_port;\n}\n\n\nstatic bool connect_client(rem_port *port)\n{\n\/**************************************\n *\n *\tc o n n e c t _ c l i e n t\n *\n **************************************\n *\n * Functional description\n *\tWait for new client connected.\n *\n **************************************\/\n\n\tOVERLAPPED ovrl = {0};\n\tovrl.hEvent = port->port_event;\n\tif (!ConnectNamedPipe(port->port_pipe, &ovrl))\n\t{\n\t\tDWORD err = GetLastError();\n\t\tswitch (err)\n\t\t{\n\t\tcase ERROR_PIPE_CONNECTED:\n\t\t\tbreak;\n\n\t\tcase ERROR_IO_PENDING:\n\t\t\tif (WaitForSingleObject(port->port_event, INFINITE) == WAIT_OBJECT_0)\n\t\t\t{\n\t\t\t\tif (!wnet_shutdown)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t\terr = GetLastError(); \/\/ fall thru\n\n\t\tdefault:\n\t\t\tif (!wnet_shutdown) {\n\t\t\t\twnet_error(port, \"ConnectNamedPipe\", isc_net_connect_err, err);\n\t\t\t}\n\t\t\tdisconnect(port);\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n\nstatic void disconnect(rem_port* port)\n{\n\/**************************************\n *\n *\td i s c o n n e c t\n *\n **************************************\n *\n * Functional description\n *\tBreak a remote connection.\n *\n **************************************\/\n\n\tif (port->port_state == rem_port::DISCONNECTED)\n\t\treturn;\n\n\tport->port_state = rem_port::DISCONNECTED;\n\n\tif (port->port_async)\n\t{\n\t\tdisconnect(port->port_async);\n\t\tport->port_async = NULL;\n\t}\n\tport->port_context = NULL;\n\n\t\/\/ If this is a sub-port, unlink it from its parent\n\tport->unlinkParent();\n\tport->port_flags &= ~PORT_connecting;\n\n\tif (port->port_server_flags & SRVR_server)\n\t{\n\t\tFlushFileBuffers(port->port_pipe);\n\t\tDisconnectNamedPipe(port->port_pipe);\n\t}\n\tif (port->port_event != INVALID_HANDLE_VALUE)\n\t{\n\t\tCloseHandle(port->port_event);\n\t\tport->port_event = INVALID_HANDLE_VALUE;\n\t}\n\tif (port->port_pipe != INVALID_HANDLE_VALUE)\n\t{\n\t\tCloseHandle(port->port_pipe);\n\t\tport->port_pipe = INVALID_HANDLE_VALUE;\n\t}\n\n\twnet_ports->unRegisterPort(port);\n\n\tif (port->port_thread_guard && port->port_events_thread && !port->port_events_threadId.isCurrent())\n\t\tport->port_thread_guard->setWait(port->port_events_thread);\n\telse\n\t\tport->releasePort();\n}\n\n\nstatic void force_close(rem_port* port)\n{\n\/**************************************\n *\n *\tf o r c e _ c l o s e\n *\n **************************************\n *\n * Functional description\n *\tForcibly close remote connection.\n *\n **************************************\/\n\n\tif (port->port_event != INVALID_HANDLE_VALUE)\n\t{\n\t\tport->port_state = rem_port::BROKEN;\n\n\t\tconst HANDLE handle = port->port_pipe;\n\t\tport->port_pipe = INVALID_HANDLE_VALUE;\n\t\tSetEvent(port->port_event);\n\t\tCloseHandle(handle);\n\t}\n}\n\n\n#ifdef NOT_USED_OR_REPLACED\nstatic void exit_handler(void* main_port)\n{\n\/**************************************\n *\n *\te x i t _ h a n d l e r\n *\n **************************************\n *\n * Functional description\n *\tShutdown all active connections\n *\tto allow restart.\n *\n **************************************\/\n\tfor (rem_port* vport = static_cast<rem_port*>(main_port); vport; vport = vport->port_next)\n\t\tCloseHandle(vport->port_pipe);\n}\n#endif\n\n\nstatic rem_str* make_pipe_name(const RefPtr<const Config>& config, const TEXT* connect_name,\n\tconst TEXT* suffix_name, const TEXT* str_pid)\n{\n\/**************************************\n *\n *\tm a k e _ p i p e _ n a m e\n *\n **************************************\n *\n * Functional description\n *\tConstruct a name for the pipe connection.\n *\tFigure out whether we need a remote node name,\n *\tand construct the pipe name accordingly.\n *\tIf a server pid != 0, append it to pipe name  as <>\/<pid>\n *\n **************************************\/\n\tstring buffer(\"\\\\\\\\\");\n\n\tconst TEXT* p = connect_name;\n\n\tif (!p || *p++ != '\\\\' || *p++ != '\\\\')\n\t\tp = \".\";\n\n\twhile (*p && *p != '\\\\' && *p != '@')\n\t\tbuffer += *p++;\n\n\tconst TEXT* protocol = NULL;\n\tswitch (*p)\n\t{\n\tcase 0:\n\t\tprotocol = config->getRemoteServiceName();\n\t\tbreak;\n\tcase '@':\n\t\tprotocol = p + 1;\n\t\tbreak;\n\tdefault:\n\t\twhile (*p)\n\t\t{\n\t\t\tif (*p++ == '\\\\')\n\t\t\t\tprotocol = p;\n\t\t}\n\t}\n\n\tbuffer += '\\\\';\n\tbuffer += PIPE_PREFIX;\n\tbuffer += '\\\\';\n\tconst char *pipe_name = config->getRemotePipeName();\n\tbuffer += pipe_name;\n\tbuffer += '\\\\';\n\tbuffer += suffix_name;\n\tbuffer += '\\\\';\n\tbuffer += protocol;\n\n\tif (str_pid)\n\t{\n\t\tbuffer += '\\\\';\n\t\tbuffer += str_pid;\n\t}\n\n\treturn REMOTE_make_string(buffer.c_str());\n}\n\n\nstatic rem_port* receive( rem_port* main_port, PACKET* packet)\n{\n\/**************************************\n *\n *\tr e c e i v e\n *\n **************************************\n *\n * Functional description\n *\tReceive a message from a port or clients of a port.  If the process\n *\tis a server and a connection request comes in, generate a new port\n *\tblock for the client.\n *\n **************************************\/\n\n\tif (!xdr_protocol(main_port->port_receive, packet))\n\t\tpacket->p_operation = op_exit;\n\n\treturn main_port;\n}\n\n\nstatic int send_full( rem_port* port, PACKET* packet)\n{\n\/**************************************\n *\n *\ts e n d _ f u l l\n *\n **************************************\n *\n * Functional description\n *\tSend a packet across a port to another process.\n *\n **************************************\/\n\n\tif (!xdr_protocol(port->port_send, packet))\n\t\treturn FALSE;\n\n\treturn xdrwnet_endofrecord(port->port_send); \/\/, TRUE);\n}\n\n\nstatic int send_partial( rem_port* port, PACKET* packet)\n{\n\/**************************************\n *\n *\ts e n d _ p a r t i a l\n *\n **************************************\n *\n * Functional description\n *\tSend a packet across a port to another process.\n *\n **************************************\/\n\n\treturn xdr_protocol(port->port_send, packet);\n}\n\n\nstatic RemoteXdr* xdrwnet_create(rem_port* port, UCHAR* buffer, USHORT length, xdr_op x_op)\n{\n\/**************************************\n *\n *\tx d r w n e t _ c r e a t e\n *\n **************************************\n *\n * Functional description\n *\tInitialize an XDR stream for Apollo mailboxes.\n *\n **************************************\/\n\n\tRemoteXdr* xdrs = FB_NEW WnetXdr;\n\n\txdrs->x_public = port;\n\txdrs->create(reinterpret_cast<SCHAR*>(buffer), length, x_op);\n\n\treturn xdrs;\n}\n\n\nstatic bool_t xdrwnet_endofrecord( RemoteXdr* xdrs) \/\/, bool_t flushnow)\n{\n\/**************************************\n *\n *\tx d r w n e t _ e n d o f r e c o r d\n *\n **************************************\n *\n * Functional description\n *\tWrite out the rest of a record.\n *\n **************************************\/\n\n\treturn wnet_write(xdrs); \/\/, flushnow);\n}\n\n\nstatic bool wnet_error(rem_port* port,\n\t\t\t\t\t  const TEXT* function, ISC_STATUS operation, int status)\n{\n\/**************************************\n *\n *\tw n e t _ e r r o r\n *\n **************************************\n *\n * Functional description\n *\tAn I\/O error has occurred.  If a status vector is present,\n *\tgenerate an error return.  In any case, return NULL, which\n *\tis used to indicate and error.\n *\n **************************************\/\n\tif (status)\n\t{\n\t\tif (port->port_state == rem_port::PENDING)\n\t\t{\n\t\t\tgds__log(\"WNET\/wnet_error: %s errno = %d\", function, status);\n\t\t}\n\n\t\twnet_gen_error(port, Arg::Gds(operation) << SYS_ERR(status));\n\t}\n\telse\n\t{\n\t\twnet_gen_error(port, Arg::Gds(operation));\n\t}\n\n\treturn false;\n}\n\n\nstatic void wnet_gen_error (rem_port* port, const Arg::StatusVector& v)\n{\n\/**************************************\n *\n *\tw n e t _ g e n _ e r r o r\n *\n **************************************\n *\n * Functional description\n *\tAn error has occurred.  Mark the port as broken.\n *\tFormat the status vector if there is one and\n *\tsave the status vector strings in a permanent place.\n *\n **************************************\/\n\tport->port_state = rem_port::BROKEN;\n\n\tTEXT node_name[MAXPATHLEN];\n\tif (port->port_connection)\n\t{\n\t\tfb_utils::copy_terminate(node_name, port->port_connection->str_data + 2, sizeof(node_name));\n\t\tTEXT* const p = strchr(node_name, '\\\\');\n\t\tif (p != NULL)\n\t\t\t*p = '\\0';\n\t}\n\telse\n\t{\n\t\tstrcpy(node_name, \"(unknown)\");\n\t}\n\n\tArg::Gds error(isc_network_error);\n\terror << Arg::Str(node_name) << v;\n\terror.raise();\n}\n\n\nbool_t WnetXdr::x_getbytes(SCHAR* buff, unsigned bytecount)\n{\n\/**************************************\n *\n *\tw n e t _ g e t b y t e s\n *\n **************************************\n *\n * Functional description\n *\tGet a bunch of bytes from a memory stream if it fits.\n *\n **************************************\/\n\t\/\/ Use memcpy to optimize bulk transfers.\n\n\twhile (bytecount > (SLONG) sizeof(ISC_QUAD))\n\t{\n\t\tif (x_handy >= bytecount)\n\t\t{\n\t\t\tmemcpy(buff, x_private, bytecount);\n\t\t\tx_private += bytecount;\n\t\t\tx_handy -= bytecount;\n\t\t\treturn TRUE;\n\t\t}\n\t\tif (x_handy > 0)\n\t\t{\n\t\t\tmemcpy(buff, x_private, x_handy);\n\t\t\tx_private += x_handy;\n\t\t\tbuff += x_handy;\n\t\t\tbytecount -= x_handy;\n\t\t\tx_handy = 0;\n\t\t}\n\t\tif (!wnet_read(this))\n\t\t\treturn FALSE;\n\t}\n\n\t\/\/ Scalar values and bulk transfer remainder fall thru\n\t\/\/ to be moved byte-by-byte to avoid memcpy setup costs.\n\n\tif (!bytecount)\n\t\treturn TRUE;\n\n\tif (x_handy >= bytecount)\n\t{\n\t\tx_handy -= bytecount;\n\t\tdo {\n\t\t\t*buff++ = *x_private++;\n\t\t} while (--bytecount);\n\t\treturn TRUE;\n\t}\n\n\twhile (bytecount--)\n\t{\n\t\tif (x_handy == 0 && !wnet_read(this))\n\t\t\treturn FALSE;\n\t\t*buff++ = *x_private++;\n\t\t--x_handy;\n\t}\n\n\treturn TRUE;\n}\n\n\nbool_t WnetXdr::x_putbytes(const SCHAR* buff, unsigned count)\n{\n\/**************************************\n *\n *\tw n e t _ p u t b y t e s\n *\n **************************************\n *\n * Functional description\n *\tPut a bunch of bytes to a memory stream if it fits.\n *\n **************************************\/\n\tSLONG bytecount = count;\n\n\t\/\/ Use memcpy to optimize bulk transfers.\n\n\twhile (bytecount > (SLONG) sizeof(ISC_QUAD))\n\t{\n\t\tif (x_handy >= bytecount)\n\t\t{\n\t\t\tmemcpy(x_private, buff, bytecount);\n\t\t\tx_private += bytecount;\n\t\t\tx_handy -= bytecount;\n\t\t\treturn TRUE;\n\t\t}\n\t\tif (x_handy > 0)\n\t\t{\n\t\t\tmemcpy(x_private, buff, x_handy);\n\t\t\tx_private += x_handy;\n\t\t\tbuff += x_handy;\n\t\t\tbytecount -= x_handy;\n\t\t\tx_handy = 0;\n\t\t}\n\t\tif (!wnet_write(this \/*, 0*\/))\n\t\t\treturn FALSE;\n\t}\n\n\t\/\/ Scalar values and bulk transfer remainder fall thru\n\t\/\/ to be moved byte-by-byte to avoid memcpy setup costs.\n\n\tif (!bytecount)\n\t\treturn TRUE;\n\n\tif (x_handy >= bytecount)\n\t{\n\t\tx_handy -= bytecount;\n\t\tdo {\n\t\t\t*x_private++ = *buff++;\n\t\t} while (--bytecount);\n\t\treturn TRUE;\n\t}\n\n\twhile (bytecount--)\n\t{\n\t\tif (x_handy == 0 && !wnet_write(this \/*, 0*\/))\n\t\t\treturn FALSE;\n\t\t--x_handy;\n\t\t*x_private++ = *buff++;\n\t}\n\n\treturn TRUE;\n}\n\n\nstatic bool_t wnet_read( RemoteXdr* xdrs)\n{\n\/**************************************\n *\n *\tw n e t _ r e a d\n *\n **************************************\n *\n * Functional description\n *\tRead a buffer full of data.  If we receive a bad packet,\n *\tsend the moral equivalent of a NAK and retry.  ACK all\n *\tpartial packets.  Don't ACK the last packet -- the next\n *\tmessage sent will handle this.\n *\n **************************************\/\n\trem_port* port = xdrs->x_public;\n\tSCHAR* p = xdrs->x_base;\n\tconst SCHAR* const end = p + BUFFER_SIZE;\n\n\t\/\/ If buffer is not completely empty, slide down what what's left\n\n\tif (xdrs->x_handy > 0)\n\t{\n\t\tmemmove(p, xdrs->x_private, xdrs->x_handy);\n\t\tp += xdrs->x_handy;\n\t}\n\n\twhile (true)\n\t{\n\t\tSSHORT length = end - p;\n\t\tif (!packet_receive(port, reinterpret_cast<UCHAR*>(p), length, &length))\n\t\t{\n\t\t\treturn FALSE;\n\t\t}\n\t\tif (length >= 0)\n\t\t{\n\t\t\tp += length;\n\t\t\tbreak;\n\t\t}\n\t\tp -= length;\n\t\tif (!packet_send(port, 0, 0))\n\t\t\treturn FALSE;\n\t}\n\n\txdrs->x_handy = p - xdrs->x_base;\n\txdrs->x_private = xdrs->x_base;\n\n\treturn TRUE;\n}\n\n\nstatic bool_t wnet_write( RemoteXdr* xdrs \/*, bool_t end_flag*\/)\n{\n\/**************************************\n *\n *\tw n e t _ w r i t e\n *\n **************************************\n *\n * Functional description\n *\tWrite a buffer fulll of data.\n *  Obsolete: If the end_flag isn't set, indicate\n *\tthat the buffer is a fragment, and reset the XDR for another buffer\n *\tload.\n *\n **************************************\/\n\t\/\/ Encode the data portion of the packet\n\n\trem_port* vport = xdrs->x_public;\n\tconst SCHAR* p = xdrs->x_base;\n\tSSHORT length = xdrs->x_private - p;\n\n\t\/\/ Send data in manageable hunks.  If a packet is partial, indicate\n\t\/\/ that with a negative length.  A positive length marks the end.\n\n\twhile (length)\n\t{\n\t\tconst SSHORT l = MIN(length, MAX_DATA);\n\t\tlength -= l;\n\t\tif (!packet_send(vport, p, (SSHORT) (length ? -l : l)))\n\t\t\treturn FALSE;\n\t\tp += l;\n\t}\n\n\txdrs->x_private = xdrs->x_base;\n\txdrs->x_handy = BUFFER_SIZE;\n\n\treturn TRUE;\n}\n\n\n#ifdef DEBUG\nstatic void packet_print(const TEXT* string, const UCHAR* packet, const int length)\n{\n\/**************************************\n *\n *\tp a c k e t _ p r i n t\n *\n **************************************\n *\n * Functional description\n *\tPrint a summary of packet.\n *\n **************************************\/\n\tint sum = 0;\n\tint l = length;\n\n\tif (l)\n\t{\n\t\tdo {\n\t\t\tsum += *packet++;\n\t\t} while (--l);\n\t}\n\n\tprintf(\"%s\\t: length = %d, checksum = %d\\n\", string, length, sum);\n}\n#endif\n\n\nstatic bool packet_receive(rem_port* port, UCHAR* buffer, SSHORT buffer_length, SSHORT* length)\n{\n\/**************************************\n *\n *\tp a c k e t _ r e c e i v e\n *\n **************************************\n *\n * Functional description\n *\tReceive a packet and pass on it's goodness.  If it's good,\n *\treturn true and the reported length of the packet, and update\n *\tthe receive sequence number.  If it's bad, return false.  If it's\n *\ta duplicate message, just ignore it.\n *\n **************************************\/\n\tDWORD n = 0;\n\tOVERLAPPED ovrl = {0};\n\tovrl.hEvent = port->port_event;\n\n\tBOOL status = ReadFile(port->port_pipe, buffer, buffer_length, &n, &ovrl);\n\tDWORD dwError = GetLastError();\n\n\tif (!status && dwError == ERROR_IO_PENDING)\n\t{\n\t\tstatus = GetOverlappedResult(port->port_pipe, &ovrl, &n, TRUE);\n\t\tdwError = GetLastError();\n\t}\n\tif (!status && dwError != ERROR_BROKEN_PIPE) {\n\t\treturn wnet_error(port, \"ReadFile\", isc_net_read_err, dwError);\n\t}\n\n\tif (!n)\n\t{\n\t\tif (port->port_flags & (PORT_detached | PORT_disconnect))\n\t\t\treturn false;\n\n\t\treturn wnet_error(port, \"ReadFile end-of-file\", isc_net_read_err, dwError);\n\t}\n\n\t\/\/ decrypt\n\tif (port->port_crypt_plugin)\n\t{\n\t\tLocalStatus ls;\n\t\tCheckStatusWrapper st(&ls);\n\n\t\tport->port_crypt_plugin->decrypt(&st, n, buffer, buffer);\n\t\tif (st.getState() & IStatus::STATE_ERRORS)\n\t\t{\n\t\t\tstatus_exception::raise(&st);\n\t\t}\n\t}\n\n#if defined(DEBUG) && defined(WNET_trace)\n\tpacket_print(\"receive\", buffer, n);\n#endif\n\n\tport->port_rcv_packets++;\n\tport->port_rcv_bytes += n;\n\n\t*length = (SSHORT) n;\n\n\treturn true;\n}\n\n\nstatic bool packet_send( rem_port* port, const SCHAR* buffer, SSHORT buffer_length)\n{\n\/**************************************\n *\n *\tp a c k e t _ s e n d\n *\n **************************************\n *\n * Functional description\n *\tSend some data on it's way.\n *\n **************************************\/\n\tconst SCHAR* data = buffer;\n\tconst DWORD length = buffer_length;\n\n\t\/\/ encrypt\n\tHalfStaticArray<char, BUFFER_TINY> b;\n\tif (port->port_crypt_plugin && port->port_crypt_complete)\n\t{\n\t\tLocalStatus ls;\n\t\tCheckStatusWrapper st(&ls);\n\n\t\tchar* d = b.getBuffer(buffer_length);\n\t\tport->port_crypt_plugin->encrypt(&st, buffer_length, data, d);\n\t\tif (st.getState() & IStatus::STATE_ERRORS)\n\t\t{\n\t\t\tstatus_exception::raise(&st);\n\t\t}\n\n\t\tdata = d;\n\t}\n\n\tOVERLAPPED ovrl = {0};\n\tovrl.hEvent = port->port_event;\n\n\tDWORD n;\n\tBOOL status = WriteFile(port->port_pipe, data, length, &n, &ovrl);\n\tDWORD dwError = GetLastError();\n\n\tif (!status && dwError == ERROR_IO_PENDING)\n\t{\n\t\tstatus = GetOverlappedResult(port->port_pipe, &ovrl, &n, TRUE);\n\t\tdwError = GetLastError();\n\t}\n\tif (!status && dwError != ERROR_NO_DATA)\n\t\treturn wnet_error(port, \"WriteFile\", isc_net_write_err, dwError);\n\tif (n != length)\n\t{\n\t\tif (port->port_flags & (PORT_detached | PORT_disconnect))\n\t\t\treturn false;\n\n\t\treturn wnet_error(port, \"WriteFile truncated\", isc_net_write_err, dwError);\n\t}\n\n#if defined(DEBUG) && defined(WNET_trace)\n\tpacket_print(\"send\", reinterpret_cast<const UCHAR*>(buffer), buffer_length);\n#endif\n\n\tport->port_snd_packets++;\n\tport->port_snd_bytes += buffer_length;\n\n\treturn true;\n}\n\n\nstatic void wnet_make_file_name( TEXT* name, DWORD number)\n{\n\/**************************************\n *\n *      w n e t _ m a k e _ f i l e _ n a m e\n *\n **************************************\n *\n * Functional description\n *      Create a file name out of a number making sure\n *\tthe Windows <8>.<3> limitations are handled.\n *\n **************************************\/\n\tTEXT temp[32];\n\n\tsprintf(temp, \"%lu\", number);\n\n\tsize_t length = strlen(temp);\n\tif (length < 8)\n\t{\n\t\tstrcpy(name, temp);\n\t\treturn;\n\t}\n\n\tTEXT* p = name;\n\tconst TEXT* q = temp;\n\n\twhile (length)\n\t{\n\t\tsize_t len = (length > 8) ? 8 : length;\n\t\tlength -= len;\n\t\tdo {\n\t\t\t*p++ = *q++;\n\t\t} while (--len != 0);\n\n\t\tif (length)\n\t\t\t*p++ = '\\\\';\n\t}\n\t*p++ = 0;\n}\n\nstatic int cleanup_ports(const int, const int, void*)\n{\n\/**************************************\n *\n *\tc l e a n u p _ p o r t s\n *\n **************************************\n *\n * Functional description\n *\tShutdown all active connections\n *\tto allow correct shutdown.\n *\n **************************************\/\n\twnet_shutdown = true;\n\n\twnet_ports->closePorts();\n\treturn 0;\n}\n","avg_line_length":23.939701897,"max_line_length":109,"alphanum_fraction":0.6259799066,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":190091,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\ufeff#include \"il2cpp-config.h\"\n\n#ifndef _MSC_VER\n# include <alloca.h>\n#else\n# include <malloc.h>\n#endif\n\n#include <cstring>\n#include <string.h>\n#include <stdio.h>\n#include <cmath>\n#include <limits>\n#include <assert.h>\n#include <stdint.h>\n\n#include \"class-internals.h\"\n#include \"codegen\/il2cpp-codegen.h\"\n#include \"object-internals.h\"\n\n\/\/ System.Runtime.Remoting.Contexts.IDynamicProperty\nstruct IDynamicProperty_t603529997;\n\/\/ System.Runtime.Remoting.Contexts.IDynamicMessageSink\nstruct IDynamicMessageSink_t3056162262;\n\/\/ System.Collections.ArrayList\nstruct ArrayList_t4252133567;\n\/\/ System.Runtime.Remoting.ServerIdentity\nstruct ServerIdentity_t1656058977;\n\/\/ System.Security.Principal.IPrincipal\nstruct IPrincipal_t783141777;\n\/\/ System.Type\nstruct Type_t;\n\/\/ System.Collections.Hashtable\nstruct Hashtable_t909839986;\n\/\/ System.Runtime.Remoting.Messaging.CallContextRemotingData\nstruct CallContextRemotingData_t2648008188;\n\/\/ System.Runtime.Remoting.Messaging.CallContextSecurityData\nstruct CallContextSecurityData_t4091024823;\n\/\/ System.String\nstruct String_t;\n\/\/ System.Runtime.Remoting.Messaging.IMessageSink\nstruct IMessageSink_t2189618969;\n\/\/ System.Threading.Timer\nstruct Timer_t791717973;\n\/\/ System.Runtime.Remoting.Activation.IActivator\nstruct IActivator_t1538980900;\n\/\/ System.Reflection.MethodInfo\nstruct MethodInfo_t;\n\/\/ System.Runtime.Remoting.Contexts.SynchronizationAttribute\nstruct SynchronizationAttribute_t3073724998;\n\/\/ System.Runtime.Remoting.Contexts.CrossContextChannel\nstruct CrossContextChannel_t2302426108;\n\/\/ System.Collections.IList\nstruct IList_t3321498491;\n\/\/ System.Runtime.Remoting.Messaging.ObjRefSurrogate\nstruct ObjRefSurrogate_t3912784830;\n\/\/ System.Runtime.Remoting.Messaging.RemotingSurrogate\nstruct RemotingSurrogate_t3248446683;\n\/\/ System.Runtime.Serialization.ISurrogateSelector\nstruct ISurrogateSelector_t1912587528;\n\/\/ System.Runtime.Remoting.Messaging.MessageDictionary\nstruct MessageDictionary_t4157710479;\n\/\/ System.Collections.IDictionaryEnumerator\nstruct IDictionaryEnumerator_t259680273;\n\/\/ System.Reflection.MethodBase\nstruct MethodBase_t904190842;\n\/\/ System.Exception\nstruct Exception_t1927440687;\n\/\/ System.Type[]\nstruct TypeU5BU5D_t1664964607;\n\/\/ System.Runtime.Remoting.Messaging.ArgInfo\nstruct ArgInfo_t688271106;\n\/\/ System.Object[]\nstruct ObjectU5BU5D_t3614634134;\n\/\/ System.Runtime.Remoting.Messaging.IMethodCallMessage\nstruct IMethodCallMessage_t645865707;\n\/\/ System.Runtime.Remoting.Messaging.LogicalCallContext\nstruct LogicalCallContext_t725724420;\n\/\/ System.Runtime.Remoting.Identity\nstruct Identity_t3647548000;\n\/\/ System.Collections.IDictionary\nstruct IDictionary_t596158605;\n\/\/ System.Runtime.Remoting.Messaging.IMethodMessage\nstruct IMethodMessage_t1899389025;\n\/\/ System.String[]\nstruct StringU5BU5D_t1642385972;\n\/\/ System.Runtime.Remoting.Contexts.Context\nstruct Context_t502196753;\n\/\/ System.MarshalByRefObject\nstruct MarshalByRefObject_t1285298191;\n\/\/ System.Runtime.Remoting.Proxies.RealProxy\nstruct RealProxy_t298428346;\n\/\/ System.Runtime.Remoting.Messaging.MethodReturnDictionary\nstruct MethodReturnDictionary_t981009581;\n\/\/ System.Void\nstruct Void_t1841601450;\n\/\/ System.Int32[]\nstruct Int32U5BU5D_t3030399641;\n\/\/ System.Char[]\nstruct CharU5BU5D_t1328083999;\n\/\/ System.DelegateData\nstruct DelegateData_t1572802995;\n\/\/ System.Threading.WaitHandle\nstruct WaitHandle_t677569169;\n\/\/ System.Threading.ExecutionContext\nstruct ExecutionContext_t1392266323;\n\/\/ System.Runtime.Remoting.Messaging.MonoMethodMessage\nstruct MonoMethodMessage_t771543475;\n\/\/ System.Runtime.Remoting.Messaging.IMessageCtrl\nstruct IMessageCtrl_t2081697019;\n\/\/ System.Runtime.Remoting.Messaging.IMessage\nstruct IMessage_t3044378324;\n\/\/ System.Threading.WaitCallback\nstruct WaitCallback_t2798937288;\n\/\/ System.Threading.ContextCallback\nstruct ContextCallback_t2287130692;\n\/\/ System.Collections.Generic.List`1<System.Runtime.Remoting.Contexts.IContextProperty>\nstruct List_1_t3951334827;\n\/\/ System.LocalDataStoreHolder\nstruct LocalDataStoreHolder_t2240136856;\n\/\/ System.LocalDataStoreMgr\nstruct LocalDataStoreMgr_t1152954092;\n\/\/ System.Runtime.Remoting.Contexts.DynamicPropertyCollection\nstruct DynamicPropertyCollection_t2282532998;\n\/\/ System.Runtime.Remoting.Contexts.ContextCallbackObject\nstruct ContextCallbackObject_t3978189709;\n\/\/ System.Threading.Mutex\nstruct Mutex_t297030111;\n\/\/ System.Threading.Thread\nstruct Thread_t241561612;\n\/\/ System.Reflection.MonoMethod\nstruct MonoMethod_t;\n\/\/ System.Byte[]\nstruct ByteU5BU5D_t3397334013;\n\/\/ System.Runtime.Remoting.Messaging.AsyncResult\nstruct AsyncResult_t2232356043;\n\/\/ System.Runtime.Remoting.Messaging.MCMDictionary\nstruct MCMDictionary_t159052147;\n\/\/ System.Collections.Queue\nstruct Queue_t1288490777;\n\/\/ System.Runtime.Remoting.Lifetime.Lease\/RenewalDelegate\nstruct RenewalDelegate_t194360041;\n\/\/ System.Delegate[]\nstruct DelegateU5BU5D_t1606206610;\n\/\/ System.Runtime.Remoting.Lifetime.LeaseManager\nstruct LeaseManager_t1025868639;\n\/\/ System.Runtime.Remoting.Messaging.Header[]\nstruct HeaderU5BU5D_t2408360458;\n\/\/ System.IAsyncResult\nstruct IAsyncResult_t1999651008;\n\/\/ System.AsyncCallback\nstruct AsyncCallback_t163412349;\n\/\/ System.Runtime.Remoting.Lifetime.ILease\nstruct ILease_t3205633421;\n\nstruct WaitHandle_t677569169_marshaled_pinvoke;\nstruct MonoMethodMessage_t771543475_marshaled_pinvoke;\nstruct WaitHandle_t677569169_marshaled_com;\nstruct MonoMethodMessage_t771543475_marshaled_com;\nstruct Exception_t1927440687_marshaled_pinvoke;\nstruct AsyncResult_t2232356043_marshaled_pinvoke;\nstruct Exception_t1927440687_marshaled_com;\nstruct AsyncResult_t2232356043_marshaled_com;\n\n\n\n#ifndef RUNTIMEOBJECT_H\n#define RUNTIMEOBJECT_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Object\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ RUNTIMEOBJECT_H\n#ifndef DYNAMICPROPERTYREG_T1839195831_H\n#define DYNAMICPROPERTYREG_T1839195831_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Contexts.DynamicPropertyCollection\/DynamicPropertyReg\nstruct  DynamicPropertyReg_t1839195831  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Runtime.Remoting.Contexts.IDynamicProperty System.Runtime.Remoting.Contexts.DynamicPropertyCollection\/DynamicPropertyReg::Property\n\tRuntimeObject* ___Property_0;\n\t\/\/ System.Runtime.Remoting.Contexts.IDynamicMessageSink System.Runtime.Remoting.Contexts.DynamicPropertyCollection\/DynamicPropertyReg::Sink\n\tRuntimeObject* ___Sink_1;\n\npublic:\n\tinline static int32_t get_offset_of_Property_0() { return static_cast<int32_t>(offsetof(DynamicPropertyReg_t1839195831, ___Property_0)); }\n\tinline RuntimeObject* get_Property_0() const { return ___Property_0; }\n\tinline RuntimeObject** get_address_of_Property_0() { return &___Property_0; }\n\tinline void set_Property_0(RuntimeObject* value)\n\t{\n\t\t___Property_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Property_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_Sink_1() { return static_cast<int32_t>(offsetof(DynamicPropertyReg_t1839195831, ___Sink_1)); }\n\tinline RuntimeObject* get_Sink_1() const { return ___Sink_1; }\n\tinline RuntimeObject** get_address_of_Sink_1() { return &___Sink_1; }\n\tinline void set_Sink_1(RuntimeObject* value)\n\t{\n\t\t___Sink_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Sink_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DYNAMICPROPERTYREG_T1839195831_H\n#ifndef DYNAMICPROPERTYCOLLECTION_T2282532998_H\n#define DYNAMICPROPERTYCOLLECTION_T2282532998_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Contexts.DynamicPropertyCollection\nstruct  DynamicPropertyCollection_t2282532998  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Collections.ArrayList System.Runtime.Remoting.Contexts.DynamicPropertyCollection::_properties\n\tArrayList_t4252133567 * ____properties_0;\n\npublic:\n\tinline static int32_t get_offset_of__properties_0() { return static_cast<int32_t>(offsetof(DynamicPropertyCollection_t2282532998, ____properties_0)); }\n\tinline ArrayList_t4252133567 * get__properties_0() const { return ____properties_0; }\n\tinline ArrayList_t4252133567 ** get_address_of__properties_0() { return &____properties_0; }\n\tinline void set__properties_0(ArrayList_t4252133567 * value)\n\t{\n\t\t____properties_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____properties_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DYNAMICPROPERTYCOLLECTION_T2282532998_H\n#ifndef VALUETYPE_T3507792607_H\n#define VALUETYPE_T3507792607_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ValueType\nstruct  ValueType_t3507792607  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.ValueType\nstruct ValueType_t3507792607_marshaled_pinvoke\n{\n};\n\/\/ Native definition for COM marshalling of System.ValueType\nstruct ValueType_t3507792607_marshaled_com\n{\n};\n#endif \/\/ VALUETYPE_T3507792607_H\n#ifndef ATTRIBUTE_T542643598_H\n#define ATTRIBUTE_T542643598_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Attribute\nstruct  Attribute_t542643598  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ ATTRIBUTE_T542643598_H\n#ifndef CROSSCONTEXTCHANNEL_T2302426108_H\n#define CROSSCONTEXTCHANNEL_T2302426108_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Contexts.CrossContextChannel\nstruct  CrossContextChannel_t2302426108  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CROSSCONTEXTCHANNEL_T2302426108_H\n#ifndef MARSHALBYREFOBJECT_T1285298191_H\n#define MARSHALBYREFOBJECT_T1285298191_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.MarshalByRefObject\nstruct  MarshalByRefObject_t1285298191  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Runtime.Remoting.ServerIdentity System.MarshalByRefObject::_identity\n\tServerIdentity_t1656058977 * ____identity_0;\n\npublic:\n\tinline static int32_t get_offset_of__identity_0() { return static_cast<int32_t>(offsetof(MarshalByRefObject_t1285298191, ____identity_0)); }\n\tinline ServerIdentity_t1656058977 * get__identity_0() const { return ____identity_0; }\n\tinline ServerIdentity_t1656058977 ** get_address_of__identity_0() { return &____identity_0; }\n\tinline void set__identity_0(ServerIdentity_t1656058977 * value)\n\t{\n\t\t____identity_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____identity_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.MarshalByRefObject\nstruct MarshalByRefObject_t1285298191_marshaled_pinvoke\n{\n\tServerIdentity_t1656058977 * ____identity_0;\n};\n\/\/ Native definition for COM marshalling of System.MarshalByRefObject\nstruct MarshalByRefObject_t1285298191_marshaled_com\n{\n\tServerIdentity_t1656058977 * ____identity_0;\n};\n#endif \/\/ MARSHALBYREFOBJECT_T1285298191_H\n#ifndef CALLCONTEXTSECURITYDATA_T4091024823_H\n#define CALLCONTEXTSECURITYDATA_T4091024823_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.CallContextSecurityData\nstruct  CallContextSecurityData_t4091024823  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Security.Principal.IPrincipal System.Runtime.Remoting.Messaging.CallContextSecurityData::_principal\n\tRuntimeObject* ____principal_0;\n\npublic:\n\tinline static int32_t get_offset_of__principal_0() { return static_cast<int32_t>(offsetof(CallContextSecurityData_t4091024823, ____principal_0)); }\n\tinline RuntimeObject* get__principal_0() const { return ____principal_0; }\n\tinline RuntimeObject** get_address_of__principal_0() { return &____principal_0; }\n\tinline void set__principal_0(RuntimeObject* value)\n\t{\n\t\t____principal_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____principal_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CALLCONTEXTSECURITYDATA_T4091024823_H\n#ifndef LOGICALCALLCONTEXT_T725724420_H\n#define LOGICALCALLCONTEXT_T725724420_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.LogicalCallContext\nstruct  LogicalCallContext_t725724420  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Collections.Hashtable System.Runtime.Remoting.Messaging.LogicalCallContext::m_Datastore\n\tHashtable_t909839986 * ___m_Datastore_1;\n\t\/\/ System.Runtime.Remoting.Messaging.CallContextRemotingData System.Runtime.Remoting.Messaging.LogicalCallContext::m_RemotingData\n\tCallContextRemotingData_t2648008188 * ___m_RemotingData_2;\n\t\/\/ System.Runtime.Remoting.Messaging.CallContextSecurityData System.Runtime.Remoting.Messaging.LogicalCallContext::m_SecurityData\n\tCallContextSecurityData_t4091024823 * ___m_SecurityData_3;\n\t\/\/ System.Object System.Runtime.Remoting.Messaging.LogicalCallContext::m_HostContext\n\tRuntimeObject * ___m_HostContext_4;\n\t\/\/ System.Boolean System.Runtime.Remoting.Messaging.LogicalCallContext::m_IsCorrelationMgr\n\tbool ___m_IsCorrelationMgr_5;\n\npublic:\n\tinline static int32_t get_offset_of_m_Datastore_1() { return static_cast<int32_t>(offsetof(LogicalCallContext_t725724420, ___m_Datastore_1)); }\n\tinline Hashtable_t909839986 * get_m_Datastore_1() const { return ___m_Datastore_1; }\n\tinline Hashtable_t909839986 ** get_address_of_m_Datastore_1() { return &___m_Datastore_1; }\n\tinline void set_m_Datastore_1(Hashtable_t909839986 * value)\n\t{\n\t\t___m_Datastore_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_Datastore_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_m_RemotingData_2() { return static_cast<int32_t>(offsetof(LogicalCallContext_t725724420, ___m_RemotingData_2)); }\n\tinline CallContextRemotingData_t2648008188 * get_m_RemotingData_2() const { return ___m_RemotingData_2; }\n\tinline CallContextRemotingData_t2648008188 ** get_address_of_m_RemotingData_2() { return &___m_RemotingData_2; }\n\tinline void set_m_RemotingData_2(CallContextRemotingData_t2648008188 * value)\n\t{\n\t\t___m_RemotingData_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_RemotingData_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_m_SecurityData_3() { return static_cast<int32_t>(offsetof(LogicalCallContext_t725724420, ___m_SecurityData_3)); }\n\tinline CallContextSecurityData_t4091024823 * get_m_SecurityData_3() const { return ___m_SecurityData_3; }\n\tinline CallContextSecurityData_t4091024823 ** get_address_of_m_SecurityData_3() { return &___m_SecurityData_3; }\n\tinline void set_m_SecurityData_3(CallContextSecurityData_t4091024823 * value)\n\t{\n\t\t___m_SecurityData_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_SecurityData_3), value);\n\t}\n\n\tinline static int32_t get_offset_of_m_HostContext_4() { return static_cast<int32_t>(offsetof(LogicalCallContext_t725724420, ___m_HostContext_4)); }\n\tinline RuntimeObject * get_m_HostContext_4() const { return ___m_HostContext_4; }\n\tinline RuntimeObject ** get_address_of_m_HostContext_4() { return &___m_HostContext_4; }\n\tinline void set_m_HostContext_4(RuntimeObject * value)\n\t{\n\t\t___m_HostContext_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_HostContext_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_m_IsCorrelationMgr_5() { return static_cast<int32_t>(offsetof(LogicalCallContext_t725724420, ___m_IsCorrelationMgr_5)); }\n\tinline bool get_m_IsCorrelationMgr_5() const { return ___m_IsCorrelationMgr_5; }\n\tinline bool* get_address_of_m_IsCorrelationMgr_5() { return &___m_IsCorrelationMgr_5; }\n\tinline void set_m_IsCorrelationMgr_5(bool value)\n\t{\n\t\t___m_IsCorrelationMgr_5 = value;\n\t}\n};\n\nstruct LogicalCallContext_t725724420_StaticFields\n{\npublic:\n\t\/\/ System.Type System.Runtime.Remoting.Messaging.LogicalCallContext::s_callContextType\n\tType_t * ___s_callContextType_0;\n\npublic:\n\tinline static int32_t get_offset_of_s_callContextType_0() { return static_cast<int32_t>(offsetof(LogicalCallContext_t725724420_StaticFields, ___s_callContextType_0)); }\n\tinline Type_t * get_s_callContextType_0() const { return ___s_callContextType_0; }\n\tinline Type_t ** get_address_of_s_callContextType_0() { return &___s_callContextType_0; }\n\tinline void set_s_callContextType_0(Type_t * value)\n\t{\n\t\t___s_callContextType_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___s_callContextType_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ LOGICALCALLCONTEXT_T725724420_H\n#ifndef CALLCONTEXTREMOTINGDATA_T2648008188_H\n#define CALLCONTEXTREMOTINGDATA_T2648008188_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.CallContextRemotingData\nstruct  CallContextRemotingData_t2648008188  : public RuntimeObject\n{\npublic:\n\t\/\/ System.String System.Runtime.Remoting.Messaging.CallContextRemotingData::_logicalCallID\n\tString_t* ____logicalCallID_0;\n\npublic:\n\tinline static int32_t get_offset_of__logicalCallID_0() { return static_cast<int32_t>(offsetof(CallContextRemotingData_t2648008188, ____logicalCallID_0)); }\n\tinline String_t* get__logicalCallID_0() const { return ____logicalCallID_0; }\n\tinline String_t** get_address_of__logicalCallID_0() { return &____logicalCallID_0; }\n\tinline void set__logicalCallID_0(String_t* value)\n\t{\n\t\t____logicalCallID_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____logicalCallID_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CALLCONTEXTREMOTINGDATA_T2648008188_H\n#ifndef LEASESINK_T3007073869_H\n#define LEASESINK_T3007073869_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Lifetime.LeaseSink\nstruct  LeaseSink_t3007073869  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Runtime.Remoting.Messaging.IMessageSink System.Runtime.Remoting.Lifetime.LeaseSink::_nextSink\n\tRuntimeObject* ____nextSink_0;\n\npublic:\n\tinline static int32_t get_offset_of__nextSink_0() { return static_cast<int32_t>(offsetof(LeaseSink_t3007073869, ____nextSink_0)); }\n\tinline RuntimeObject* get__nextSink_0() const { return ____nextSink_0; }\n\tinline RuntimeObject** get_address_of__nextSink_0() { return &____nextSink_0; }\n\tinline void set__nextSink_0(RuntimeObject* value)\n\t{\n\t\t____nextSink_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____nextSink_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ LEASESINK_T3007073869_H\n#ifndef LEASEMANAGER_T1025868639_H\n#define LEASEMANAGER_T1025868639_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Lifetime.LeaseManager\nstruct  LeaseManager_t1025868639  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Collections.ArrayList System.Runtime.Remoting.Lifetime.LeaseManager::_objects\n\tArrayList_t4252133567 * ____objects_0;\n\t\/\/ System.Threading.Timer System.Runtime.Remoting.Lifetime.LeaseManager::_timer\n\tTimer_t791717973 * ____timer_1;\n\npublic:\n\tinline static int32_t get_offset_of__objects_0() { return static_cast<int32_t>(offsetof(LeaseManager_t1025868639, ____objects_0)); }\n\tinline ArrayList_t4252133567 * get__objects_0() const { return ____objects_0; }\n\tinline ArrayList_t4252133567 ** get_address_of__objects_0() { return &____objects_0; }\n\tinline void set__objects_0(ArrayList_t4252133567 * value)\n\t{\n\t\t____objects_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____objects_0), value);\n\t}\n\n\tinline static int32_t get_offset_of__timer_1() { return static_cast<int32_t>(offsetof(LeaseManager_t1025868639, ____timer_1)); }\n\tinline Timer_t791717973 * get__timer_1() const { return ____timer_1; }\n\tinline Timer_t791717973 ** get_address_of__timer_1() { return &____timer_1; }\n\tinline void set__timer_1(Timer_t791717973 * value)\n\t{\n\t\t____timer_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____timer_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ LEASEMANAGER_T1025868639_H\n#ifndef ACTIVATIONSERVICES_T1532663650_H\n#define ACTIVATIONSERVICES_T1532663650_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Activation.ActivationServices\nstruct  ActivationServices_t1532663650  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\nstruct ActivationServices_t1532663650_StaticFields\n{\npublic:\n\t\/\/ System.Runtime.Remoting.Activation.IActivator System.Runtime.Remoting.Activation.ActivationServices::_constructionActivator\n\tRuntimeObject* ____constructionActivator_0;\n\npublic:\n\tinline static int32_t get_offset_of__constructionActivator_0() { return static_cast<int32_t>(offsetof(ActivationServices_t1532663650_StaticFields, ____constructionActivator_0)); }\n\tinline RuntimeObject* get__constructionActivator_0() const { return ____constructionActivator_0; }\n\tinline RuntimeObject** get_address_of__constructionActivator_0() { return &____constructionActivator_0; }\n\tinline void set__constructionActivator_0(RuntimeObject* value)\n\t{\n\t\t____constructionActivator_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____constructionActivator_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ ACTIVATIONSERVICES_T1532663650_H\n#ifndef CROSSAPPDOMAINSINK_T2368859578_H\n#define CROSSAPPDOMAINSINK_T2368859578_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Channels.CrossAppDomainSink\nstruct  CrossAppDomainSink_t2368859578  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Int32 System.Runtime.Remoting.Channels.CrossAppDomainSink::_domainID\n\tint32_t ____domainID_2;\n\npublic:\n\tinline static int32_t get_offset_of__domainID_2() { return static_cast<int32_t>(offsetof(CrossAppDomainSink_t2368859578, ____domainID_2)); }\n\tinline int32_t get__domainID_2() const { return ____domainID_2; }\n\tinline int32_t* get_address_of__domainID_2() { return &____domainID_2; }\n\tinline void set__domainID_2(int32_t value)\n\t{\n\t\t____domainID_2 = value;\n\t}\n};\n\nstruct CrossAppDomainSink_t2368859578_StaticFields\n{\npublic:\n\t\/\/ System.Collections.Hashtable System.Runtime.Remoting.Channels.CrossAppDomainSink::s_sinks\n\tHashtable_t909839986 * ___s_sinks_0;\n\t\/\/ System.Reflection.MethodInfo System.Runtime.Remoting.Channels.CrossAppDomainSink::processMessageMethod\n\tMethodInfo_t * ___processMessageMethod_1;\n\npublic:\n\tinline static int32_t get_offset_of_s_sinks_0() { return static_cast<int32_t>(offsetof(CrossAppDomainSink_t2368859578_StaticFields, ___s_sinks_0)); }\n\tinline Hashtable_t909839986 * get_s_sinks_0() const { return ___s_sinks_0; }\n\tinline Hashtable_t909839986 ** get_address_of_s_sinks_0() { return &___s_sinks_0; }\n\tinline void set_s_sinks_0(Hashtable_t909839986 * value)\n\t{\n\t\t___s_sinks_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___s_sinks_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_processMessageMethod_1() { return static_cast<int32_t>(offsetof(CrossAppDomainSink_t2368859578_StaticFields, ___processMessageMethod_1)); }\n\tinline MethodInfo_t * get_processMessageMethod_1() const { return ___processMessageMethod_1; }\n\tinline MethodInfo_t ** get_address_of_processMessageMethod_1() { return &___processMessageMethod_1; }\n\tinline void set_processMessageMethod_1(MethodInfo_t * value)\n\t{\n\t\t___processMessageMethod_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___processMessageMethod_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CROSSAPPDOMAINSINK_T2368859578_H\n#ifndef APPDOMAINLEVELACTIVATOR_T834876328_H\n#define APPDOMAINLEVELACTIVATOR_T834876328_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Activation.AppDomainLevelActivator\nstruct  AppDomainLevelActivator_t834876328  : public RuntimeObject\n{\npublic:\n\t\/\/ System.String System.Runtime.Remoting.Activation.AppDomainLevelActivator::_activationUrl\n\tString_t* ____activationUrl_0;\n\t\/\/ System.Runtime.Remoting.Activation.IActivator System.Runtime.Remoting.Activation.AppDomainLevelActivator::_next\n\tRuntimeObject* ____next_1;\n\npublic:\n\tinline static int32_t get_offset_of__activationUrl_0() { return static_cast<int32_t>(offsetof(AppDomainLevelActivator_t834876328, ____activationUrl_0)); }\n\tinline String_t* get__activationUrl_0() const { return ____activationUrl_0; }\n\tinline String_t** get_address_of__activationUrl_0() { return &____activationUrl_0; }\n\tinline void set__activationUrl_0(String_t* value)\n\t{\n\t\t____activationUrl_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____activationUrl_0), value);\n\t}\n\n\tinline static int32_t get_offset_of__next_1() { return static_cast<int32_t>(offsetof(AppDomainLevelActivator_t834876328, ____next_1)); }\n\tinline RuntimeObject* get__next_1() const { return ____next_1; }\n\tinline RuntimeObject** get_address_of__next_1() { return &____next_1; }\n\tinline void set__next_1(RuntimeObject* value)\n\t{\n\t\t____next_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____next_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ APPDOMAINLEVELACTIVATOR_T834876328_H\n#ifndef CONTEXTLEVELACTIVATOR_T1784331636_H\n#define CONTEXTLEVELACTIVATOR_T1784331636_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Activation.ContextLevelActivator\nstruct  ContextLevelActivator_t1784331636  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Runtime.Remoting.Activation.IActivator System.Runtime.Remoting.Activation.ContextLevelActivator::m_NextActivator\n\tRuntimeObject* ___m_NextActivator_0;\n\npublic:\n\tinline static int32_t get_offset_of_m_NextActivator_0() { return static_cast<int32_t>(offsetof(ContextLevelActivator_t1784331636, ___m_NextActivator_0)); }\n\tinline RuntimeObject* get_m_NextActivator_0() const { return ___m_NextActivator_0; }\n\tinline RuntimeObject** get_address_of_m_NextActivator_0() { return &___m_NextActivator_0; }\n\tinline void set_m_NextActivator_0(RuntimeObject* value)\n\t{\n\t\t___m_NextActivator_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_NextActivator_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CONTEXTLEVELACTIVATOR_T1784331636_H\n#ifndef CONSTRUCTIONLEVELACTIVATOR_T2284932402_H\n#define CONSTRUCTIONLEVELACTIVATOR_T2284932402_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Activation.ConstructionLevelActivator\nstruct  ConstructionLevelActivator_t2284932402  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CONSTRUCTIONLEVELACTIVATOR_T2284932402_H\n#ifndef CROSSAPPDOMAINCHANNEL_T2471623380_H\n#define CROSSAPPDOMAINCHANNEL_T2471623380_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Channels.CrossAppDomainChannel\nstruct  CrossAppDomainChannel_t2471623380  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\nstruct CrossAppDomainChannel_t2471623380_StaticFields\n{\npublic:\n\t\/\/ System.Object System.Runtime.Remoting.Channels.CrossAppDomainChannel::s_lock\n\tRuntimeObject * ___s_lock_0;\n\npublic:\n\tinline static int32_t get_offset_of_s_lock_0() { return static_cast<int32_t>(offsetof(CrossAppDomainChannel_t2471623380_StaticFields, ___s_lock_0)); }\n\tinline RuntimeObject * get_s_lock_0() const { return ___s_lock_0; }\n\tinline RuntimeObject ** get_address_of_s_lock_0() { return &___s_lock_0; }\n\tinline void set_s_lock_0(RuntimeObject * value)\n\t{\n\t\t___s_lock_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___s_lock_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CROSSAPPDOMAINCHANNEL_T2471623380_H\n#ifndef SYNCHRONIZEDSERVERCONTEXTSINK_T462987365_H\n#define SYNCHRONIZEDSERVERCONTEXTSINK_T462987365_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Contexts.SynchronizedServerContextSink\nstruct  SynchronizedServerContextSink_t462987365  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Runtime.Remoting.Messaging.IMessageSink System.Runtime.Remoting.Contexts.SynchronizedServerContextSink::_next\n\tRuntimeObject* ____next_0;\n\t\/\/ System.Runtime.Remoting.Contexts.SynchronizationAttribute System.Runtime.Remoting.Contexts.SynchronizedServerContextSink::_att\n\tSynchronizationAttribute_t3073724998 * ____att_1;\n\npublic:\n\tinline static int32_t get_offset_of__next_0() { return static_cast<int32_t>(offsetof(SynchronizedServerContextSink_t462987365, ____next_0)); }\n\tinline RuntimeObject* get__next_0() const { return ____next_0; }\n\tinline RuntimeObject** get_address_of__next_0() { return &____next_0; }\n\tinline void set__next_0(RuntimeObject* value)\n\t{\n\t\t____next_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____next_0), value);\n\t}\n\n\tinline static int32_t get_offset_of__att_1() { return static_cast<int32_t>(offsetof(SynchronizedServerContextSink_t462987365, ____att_1)); }\n\tinline SynchronizationAttribute_t3073724998 * get__att_1() const { return ____att_1; }\n\tinline SynchronizationAttribute_t3073724998 ** get_address_of__att_1() { return &____att_1; }\n\tinline void set__att_1(SynchronizationAttribute_t3073724998 * value)\n\t{\n\t\t____att_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____att_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SYNCHRONIZEDSERVERCONTEXTSINK_T462987365_H\n#ifndef SYNCHRONIZEDCLIENTCONTEXTSINK_T3779986825_H\n#define SYNCHRONIZEDCLIENTCONTEXTSINK_T3779986825_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Contexts.SynchronizedClientContextSink\nstruct  SynchronizedClientContextSink_t3779986825  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Runtime.Remoting.Messaging.IMessageSink System.Runtime.Remoting.Contexts.SynchronizedClientContextSink::_next\n\tRuntimeObject* ____next_0;\n\t\/\/ System.Runtime.Remoting.Contexts.SynchronizationAttribute System.Runtime.Remoting.Contexts.SynchronizedClientContextSink::_att\n\tSynchronizationAttribute_t3073724998 * ____att_1;\n\npublic:\n\tinline static int32_t get_offset_of__next_0() { return static_cast<int32_t>(offsetof(SynchronizedClientContextSink_t3779986825, ____next_0)); }\n\tinline RuntimeObject* get__next_0() const { return ____next_0; }\n\tinline RuntimeObject** get_address_of__next_0() { return &____next_0; }\n\tinline void set__next_0(RuntimeObject* value)\n\t{\n\t\t____next_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____next_0), value);\n\t}\n\n\tinline static int32_t get_offset_of__att_1() { return static_cast<int32_t>(offsetof(SynchronizedClientContextSink_t3779986825, ____att_1)); }\n\tinline SynchronizationAttribute_t3073724998 * get__att_1() const { return ____att_1; }\n\tinline SynchronizationAttribute_t3073724998 ** get_address_of__att_1() { return &____att_1; }\n\tinline void set__att_1(SynchronizationAttribute_t3073724998 * value)\n\t{\n\t\t____att_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____att_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SYNCHRONIZEDCLIENTCONTEXTSINK_T3779986825_H\n#ifndef CHANNELSERVICES_T2007814595_H\n#define CHANNELSERVICES_T2007814595_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Channels.ChannelServices\nstruct  ChannelServices_t2007814595  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\nstruct ChannelServices_t2007814595_StaticFields\n{\npublic:\n\t\/\/ System.Collections.ArrayList System.Runtime.Remoting.Channels.ChannelServices::registeredChannels\n\tArrayList_t4252133567 * ___registeredChannels_0;\n\t\/\/ System.Collections.ArrayList System.Runtime.Remoting.Channels.ChannelServices::delayedClientChannels\n\tArrayList_t4252133567 * ___delayedClientChannels_1;\n\t\/\/ System.Runtime.Remoting.Contexts.CrossContextChannel System.Runtime.Remoting.Channels.ChannelServices::_crossContextSink\n\tCrossContextChannel_t2302426108 * ____crossContextSink_2;\n\t\/\/ System.String System.Runtime.Remoting.Channels.ChannelServices::CrossContextUrl\n\tString_t* ___CrossContextUrl_3;\n\t\/\/ System.Collections.IList System.Runtime.Remoting.Channels.ChannelServices::oldStartModeTypes\n\tRuntimeObject* ___oldStartModeTypes_4;\n\npublic:\n\tinline static int32_t get_offset_of_registeredChannels_0() { return static_cast<int32_t>(offsetof(ChannelServices_t2007814595_StaticFields, ___registeredChannels_0)); }\n\tinline ArrayList_t4252133567 * get_registeredChannels_0() const { return ___registeredChannels_0; }\n\tinline ArrayList_t4252133567 ** get_address_of_registeredChannels_0() { return &___registeredChannels_0; }\n\tinline void set_registeredChannels_0(ArrayList_t4252133567 * value)\n\t{\n\t\t___registeredChannels_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___registeredChannels_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_delayedClientChannels_1() { return static_cast<int32_t>(offsetof(ChannelServices_t2007814595_StaticFields, ___delayedClientChannels_1)); }\n\tinline ArrayList_t4252133567 * get_delayedClientChannels_1() const { return ___delayedClientChannels_1; }\n\tinline ArrayList_t4252133567 ** get_address_of_delayedClientChannels_1() { return &___delayedClientChannels_1; }\n\tinline void set_delayedClientChannels_1(ArrayList_t4252133567 * value)\n\t{\n\t\t___delayedClientChannels_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___delayedClientChannels_1), value);\n\t}\n\n\tinline static int32_t get_offset_of__crossContextSink_2() { return static_cast<int32_t>(offsetof(ChannelServices_t2007814595_StaticFields, ____crossContextSink_2)); }\n\tinline CrossContextChannel_t2302426108 * get__crossContextSink_2() const { return ____crossContextSink_2; }\n\tinline CrossContextChannel_t2302426108 ** get_address_of__crossContextSink_2() { return &____crossContextSink_2; }\n\tinline void set__crossContextSink_2(CrossContextChannel_t2302426108 * value)\n\t{\n\t\t____crossContextSink_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____crossContextSink_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_CrossContextUrl_3() { return static_cast<int32_t>(offsetof(ChannelServices_t2007814595_StaticFields, ___CrossContextUrl_3)); }\n\tinline String_t* get_CrossContextUrl_3() const { return ___CrossContextUrl_3; }\n\tinline String_t** get_address_of_CrossContextUrl_3() { return &___CrossContextUrl_3; }\n\tinline void set_CrossContextUrl_3(String_t* value)\n\t{\n\t\t___CrossContextUrl_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___CrossContextUrl_3), value);\n\t}\n\n\tinline static int32_t get_offset_of_oldStartModeTypes_4() { return static_cast<int32_t>(offsetof(ChannelServices_t2007814595_StaticFields, ___oldStartModeTypes_4)); }\n\tinline RuntimeObject* get_oldStartModeTypes_4() const { return ___oldStartModeTypes_4; }\n\tinline RuntimeObject** get_address_of_oldStartModeTypes_4() { return &___oldStartModeTypes_4; }\n\tinline void set_oldStartModeTypes_4(RuntimeObject* value)\n\t{\n\t\t___oldStartModeTypes_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___oldStartModeTypes_4), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CHANNELSERVICES_T2007814595_H\n#ifndef CROSSAPPDOMAINDATA_T816071813_H\n#define CROSSAPPDOMAINDATA_T816071813_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Channels.CrossAppDomainData\nstruct  CrossAppDomainData_t816071813  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Object System.Runtime.Remoting.Channels.CrossAppDomainData::_ContextID\n\tRuntimeObject * ____ContextID_0;\n\t\/\/ System.Int32 System.Runtime.Remoting.Channels.CrossAppDomainData::_DomainID\n\tint32_t ____DomainID_1;\n\t\/\/ System.String System.Runtime.Remoting.Channels.CrossAppDomainData::_processGuid\n\tString_t* ____processGuid_2;\n\npublic:\n\tinline static int32_t get_offset_of__ContextID_0() { return static_cast<int32_t>(offsetof(CrossAppDomainData_t816071813, ____ContextID_0)); }\n\tinline RuntimeObject * get__ContextID_0() const { return ____ContextID_0; }\n\tinline RuntimeObject ** get_address_of__ContextID_0() { return &____ContextID_0; }\n\tinline void set__ContextID_0(RuntimeObject * value)\n\t{\n\t\t____ContextID_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____ContextID_0), value);\n\t}\n\n\tinline static int32_t get_offset_of__DomainID_1() { return static_cast<int32_t>(offsetof(CrossAppDomainData_t816071813, ____DomainID_1)); }\n\tinline int32_t get__DomainID_1() const { return ____DomainID_1; }\n\tinline int32_t* get_address_of__DomainID_1() { return &____DomainID_1; }\n\tinline void set__DomainID_1(int32_t value)\n\t{\n\t\t____DomainID_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of__processGuid_2() { return static_cast<int32_t>(offsetof(CrossAppDomainData_t816071813, ____processGuid_2)); }\n\tinline String_t* get__processGuid_2() const { return ____processGuid_2; }\n\tinline String_t** get_address_of__processGuid_2() { return &____processGuid_2; }\n\tinline void set__processGuid_2(String_t* value)\n\t{\n\t\t____processGuid_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____processGuid_2), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CROSSAPPDOMAINDATA_T816071813_H\n#ifndef SINKPROVIDERDATA_T2645445792_H\n#define SINKPROVIDERDATA_T2645445792_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Channels.SinkProviderData\nstruct  SinkProviderData_t2645445792  : public RuntimeObject\n{\npublic:\n\t\/\/ System.String System.Runtime.Remoting.Channels.SinkProviderData::sinkName\n\tString_t* ___sinkName_0;\n\t\/\/ System.Collections.ArrayList System.Runtime.Remoting.Channels.SinkProviderData::children\n\tArrayList_t4252133567 * ___children_1;\n\t\/\/ System.Collections.Hashtable System.Runtime.Remoting.Channels.SinkProviderData::properties\n\tHashtable_t909839986 * ___properties_2;\n\npublic:\n\tinline static int32_t get_offset_of_sinkName_0() { return static_cast<int32_t>(offsetof(SinkProviderData_t2645445792, ___sinkName_0)); }\n\tinline String_t* get_sinkName_0() const { return ___sinkName_0; }\n\tinline String_t** get_address_of_sinkName_0() { return &___sinkName_0; }\n\tinline void set_sinkName_0(String_t* value)\n\t{\n\t\t___sinkName_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___sinkName_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_children_1() { return static_cast<int32_t>(offsetof(SinkProviderData_t2645445792, ___children_1)); }\n\tinline ArrayList_t4252133567 * get_children_1() const { return ___children_1; }\n\tinline ArrayList_t4252133567 ** get_address_of_children_1() { return &___children_1; }\n\tinline void set_children_1(ArrayList_t4252133567 * value)\n\t{\n\t\t___children_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___children_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_properties_2() { return static_cast<int32_t>(offsetof(SinkProviderData_t2645445792, ___properties_2)); }\n\tinline Hashtable_t909839986 * get_properties_2() const { return ___properties_2; }\n\tinline Hashtable_t909839986 ** get_address_of_properties_2() { return &___properties_2; }\n\tinline void set_properties_2(Hashtable_t909839986 * value)\n\t{\n\t\t___properties_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___properties_2), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SINKPROVIDERDATA_T2645445792_H\n#ifndef ILLOGICALCALLCONTEXT_T206449943_H\n#define ILLOGICALCALLCONTEXT_T206449943_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.IllogicalCallContext\nstruct  IllogicalCallContext_t206449943  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Collections.Hashtable System.Runtime.Remoting.Messaging.IllogicalCallContext::m_Datastore\n\tHashtable_t909839986 * ___m_Datastore_0;\n\t\/\/ System.Object System.Runtime.Remoting.Messaging.IllogicalCallContext::m_HostContext\n\tRuntimeObject * ___m_HostContext_1;\n\npublic:\n\tinline static int32_t get_offset_of_m_Datastore_0() { return static_cast<int32_t>(offsetof(IllogicalCallContext_t206449943, ___m_Datastore_0)); }\n\tinline Hashtable_t909839986 * get_m_Datastore_0() const { return ___m_Datastore_0; }\n\tinline Hashtable_t909839986 ** get_address_of_m_Datastore_0() { return &___m_Datastore_0; }\n\tinline void set_m_Datastore_0(Hashtable_t909839986 * value)\n\t{\n\t\t___m_Datastore_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_Datastore_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_m_HostContext_1() { return static_cast<int32_t>(offsetof(IllogicalCallContext_t206449943, ___m_HostContext_1)); }\n\tinline RuntimeObject * get_m_HostContext_1() const { return ___m_HostContext_1; }\n\tinline RuntimeObject ** get_address_of_m_HostContext_1() { return &___m_HostContext_1; }\n\tinline void set_m_HostContext_1(RuntimeObject * value)\n\t{\n\t\t___m_HostContext_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_HostContext_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ ILLOGICALCALLCONTEXT_T206449943_H\n#ifndef REMOTINGSURROGATESELECTOR_T2821375126_H\n#define REMOTINGSURROGATESELECTOR_T2821375126_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.RemotingSurrogateSelector\nstruct  RemotingSurrogateSelector_t2821375126  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Runtime.Serialization.ISurrogateSelector System.Runtime.Remoting.Messaging.RemotingSurrogateSelector::_next\n\tRuntimeObject* ____next_3;\n\npublic:\n\tinline static int32_t get_offset_of__next_3() { return static_cast<int32_t>(offsetof(RemotingSurrogateSelector_t2821375126, ____next_3)); }\n\tinline RuntimeObject* get__next_3() const { return ____next_3; }\n\tinline RuntimeObject** get_address_of__next_3() { return &____next_3; }\n\tinline void set__next_3(RuntimeObject* value)\n\t{\n\t\t____next_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____next_3), value);\n\t}\n};\n\nstruct RemotingSurrogateSelector_t2821375126_StaticFields\n{\npublic:\n\t\/\/ System.Type System.Runtime.Remoting.Messaging.RemotingSurrogateSelector::s_cachedTypeObjRef\n\tType_t * ___s_cachedTypeObjRef_0;\n\t\/\/ System.Runtime.Remoting.Messaging.ObjRefSurrogate System.Runtime.Remoting.Messaging.RemotingSurrogateSelector::_objRefSurrogate\n\tObjRefSurrogate_t3912784830 * ____objRefSurrogate_1;\n\t\/\/ System.Runtime.Remoting.Messaging.RemotingSurrogate System.Runtime.Remoting.Messaging.RemotingSurrogateSelector::_objRemotingSurrogate\n\tRemotingSurrogate_t3248446683 * ____objRemotingSurrogate_2;\n\npublic:\n\tinline static int32_t get_offset_of_s_cachedTypeObjRef_0() { return static_cast<int32_t>(offsetof(RemotingSurrogateSelector_t2821375126_StaticFields, ___s_cachedTypeObjRef_0)); }\n\tinline Type_t * get_s_cachedTypeObjRef_0() const { return ___s_cachedTypeObjRef_0; }\n\tinline Type_t ** get_address_of_s_cachedTypeObjRef_0() { return &___s_cachedTypeObjRef_0; }\n\tinline void set_s_cachedTypeObjRef_0(Type_t * value)\n\t{\n\t\t___s_cachedTypeObjRef_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___s_cachedTypeObjRef_0), value);\n\t}\n\n\tinline static int32_t get_offset_of__objRefSurrogate_1() { return static_cast<int32_t>(offsetof(RemotingSurrogateSelector_t2821375126_StaticFields, ____objRefSurrogate_1)); }\n\tinline ObjRefSurrogate_t3912784830 * get__objRefSurrogate_1() const { return ____objRefSurrogate_1; }\n\tinline ObjRefSurrogate_t3912784830 ** get_address_of__objRefSurrogate_1() { return &____objRefSurrogate_1; }\n\tinline void set__objRefSurrogate_1(ObjRefSurrogate_t3912784830 * value)\n\t{\n\t\t____objRefSurrogate_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____objRefSurrogate_1), value);\n\t}\n\n\tinline static int32_t get_offset_of__objRemotingSurrogate_2() { return static_cast<int32_t>(offsetof(RemotingSurrogateSelector_t2821375126_StaticFields, ____objRemotingSurrogate_2)); }\n\tinline RemotingSurrogate_t3248446683 * get__objRemotingSurrogate_2() const { return ____objRemotingSurrogate_2; }\n\tinline RemotingSurrogate_t3248446683 ** get_address_of__objRemotingSurrogate_2() { return &____objRemotingSurrogate_2; }\n\tinline void set__objRemotingSurrogate_2(RemotingSurrogate_t3248446683 * value)\n\t{\n\t\t____objRemotingSurrogate_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____objRemotingSurrogate_2), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ REMOTINGSURROGATESELECTOR_T2821375126_H\n#ifndef ENVOYTERMINATORSINK_T3043186997_H\n#define ENVOYTERMINATORSINK_T3043186997_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.EnvoyTerminatorSink\nstruct  EnvoyTerminatorSink_t3043186997  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\nstruct EnvoyTerminatorSink_t3043186997_StaticFields\n{\npublic:\n\t\/\/ System.Runtime.Remoting.Messaging.EnvoyTerminatorSink System.Runtime.Remoting.Messaging.EnvoyTerminatorSink::Instance\n\tEnvoyTerminatorSink_t3043186997 * ___Instance_0;\n\npublic:\n\tinline static int32_t get_offset_of_Instance_0() { return static_cast<int32_t>(offsetof(EnvoyTerminatorSink_t3043186997_StaticFields, ___Instance_0)); }\n\tinline EnvoyTerminatorSink_t3043186997 * get_Instance_0() const { return ___Instance_0; }\n\tinline EnvoyTerminatorSink_t3043186997 ** get_address_of_Instance_0() { return &___Instance_0; }\n\tinline void set_Instance_0(EnvoyTerminatorSink_t3043186997 * value)\n\t{\n\t\t___Instance_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Instance_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ ENVOYTERMINATORSINK_T3043186997_H\n#ifndef DICTIONARYENUMERATOR_T4235333696_H\n#define DICTIONARYENUMERATOR_T4235333696_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.MessageDictionary\/DictionaryEnumerator\nstruct  DictionaryEnumerator_t4235333696  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Runtime.Remoting.Messaging.MessageDictionary System.Runtime.Remoting.Messaging.MessageDictionary\/DictionaryEnumerator::_methodDictionary\n\tMessageDictionary_t4157710479 * ____methodDictionary_0;\n\t\/\/ System.Collections.IDictionaryEnumerator System.Runtime.Remoting.Messaging.MessageDictionary\/DictionaryEnumerator::_hashtableEnum\n\tRuntimeObject* ____hashtableEnum_1;\n\t\/\/ System.Int32 System.Runtime.Remoting.Messaging.MessageDictionary\/DictionaryEnumerator::_posMethod\n\tint32_t ____posMethod_2;\n\npublic:\n\tinline static int32_t get_offset_of__methodDictionary_0() { return static_cast<int32_t>(offsetof(DictionaryEnumerator_t4235333696, ____methodDictionary_0)); }\n\tinline MessageDictionary_t4157710479 * get__methodDictionary_0() const { return ____methodDictionary_0; }\n\tinline MessageDictionary_t4157710479 ** get_address_of__methodDictionary_0() { return &____methodDictionary_0; }\n\tinline void set__methodDictionary_0(MessageDictionary_t4157710479 * value)\n\t{\n\t\t____methodDictionary_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____methodDictionary_0), value);\n\t}\n\n\tinline static int32_t get_offset_of__hashtableEnum_1() { return static_cast<int32_t>(offsetof(DictionaryEnumerator_t4235333696, ____hashtableEnum_1)); }\n\tinline RuntimeObject* get__hashtableEnum_1() const { return ____hashtableEnum_1; }\n\tinline RuntimeObject** get_address_of__hashtableEnum_1() { return &____hashtableEnum_1; }\n\tinline void set__hashtableEnum_1(RuntimeObject* value)\n\t{\n\t\t____hashtableEnum_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____hashtableEnum_1), value);\n\t}\n\n\tinline static int32_t get_offset_of__posMethod_2() { return static_cast<int32_t>(offsetof(DictionaryEnumerator_t4235333696, ____posMethod_2)); }\n\tinline int32_t get__posMethod_2() const { return ____posMethod_2; }\n\tinline int32_t* get_address_of__posMethod_2() { return &____posMethod_2; }\n\tinline void set__posMethod_2(int32_t value)\n\t{\n\t\t____posMethod_2 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DICTIONARYENUMERATOR_T4235333696_H\n#ifndef REMOTINGSURROGATE_T3248446683_H\n#define REMOTINGSURROGATE_T3248446683_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.RemotingSurrogate\nstruct  RemotingSurrogate_t3248446683  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ REMOTINGSURROGATE_T3248446683_H\n#ifndef METHODRESPONSE_T1456661140_H\n#define METHODRESPONSE_T1456661140_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.MethodResponse\nstruct  MethodResponse_t1456661140  : public RuntimeObject\n{\npublic:\n\t\/\/ System.String System.Runtime.Remoting.Messaging.MethodResponse::_methodName\n\tString_t* ____methodName_0;\n\t\/\/ System.String System.Runtime.Remoting.Messaging.MethodResponse::_uri\n\tString_t* ____uri_1;\n\t\/\/ System.String System.Runtime.Remoting.Messaging.MethodResponse::_typeName\n\tString_t* ____typeName_2;\n\t\/\/ System.Reflection.MethodBase System.Runtime.Remoting.Messaging.MethodResponse::_methodBase\n\tMethodBase_t904190842 * ____methodBase_3;\n\t\/\/ System.Object System.Runtime.Remoting.Messaging.MethodResponse::_returnValue\n\tRuntimeObject * ____returnValue_4;\n\t\/\/ System.Exception System.Runtime.Remoting.Messaging.MethodResponse::_exception\n\tException_t1927440687 * ____exception_5;\n\t\/\/ System.Type[] System.Runtime.Remoting.Messaging.MethodResponse::_methodSignature\n\tTypeU5BU5D_t1664964607* ____methodSignature_6;\n\t\/\/ System.Runtime.Remoting.Messaging.ArgInfo System.Runtime.Remoting.Messaging.MethodResponse::_inArgInfo\n\tArgInfo_t688271106 * ____inArgInfo_7;\n\t\/\/ System.Object[] System.Runtime.Remoting.Messaging.MethodResponse::_args\n\tObjectU5BU5D_t3614634134* ____args_8;\n\t\/\/ System.Object[] System.Runtime.Remoting.Messaging.MethodResponse::_outArgs\n\tObjectU5BU5D_t3614634134* ____outArgs_9;\n\t\/\/ System.Runtime.Remoting.Messaging.IMethodCallMessage System.Runtime.Remoting.Messaging.MethodResponse::_callMsg\n\tRuntimeObject* ____callMsg_10;\n\t\/\/ System.Runtime.Remoting.Messaging.LogicalCallContext System.Runtime.Remoting.Messaging.MethodResponse::_callContext\n\tLogicalCallContext_t725724420 * ____callContext_11;\n\t\/\/ System.Runtime.Remoting.Identity System.Runtime.Remoting.Messaging.MethodResponse::_targetIdentity\n\tIdentity_t3647548000 * ____targetIdentity_12;\n\t\/\/ System.Collections.IDictionary System.Runtime.Remoting.Messaging.MethodResponse::ExternalProperties\n\tRuntimeObject* ___ExternalProperties_13;\n\t\/\/ System.Collections.IDictionary System.Runtime.Remoting.Messaging.MethodResponse::InternalProperties\n\tRuntimeObject* ___InternalProperties_14;\n\npublic:\n\tinline static int32_t get_offset_of__methodName_0() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ____methodName_0)); }\n\tinline String_t* get__methodName_0() const { return ____methodName_0; }\n\tinline String_t** get_address_of__methodName_0() { return &____methodName_0; }\n\tinline void set__methodName_0(String_t* value)\n\t{\n\t\t____methodName_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____methodName_0), value);\n\t}\n\n\tinline static int32_t get_offset_of__uri_1() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ____uri_1)); }\n\tinline String_t* get__uri_1() const { return ____uri_1; }\n\tinline String_t** get_address_of__uri_1() { return &____uri_1; }\n\tinline void set__uri_1(String_t* value)\n\t{\n\t\t____uri_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____uri_1), value);\n\t}\n\n\tinline static int32_t get_offset_of__typeName_2() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ____typeName_2)); }\n\tinline String_t* get__typeName_2() const { return ____typeName_2; }\n\tinline String_t** get_address_of__typeName_2() { return &____typeName_2; }\n\tinline void set__typeName_2(String_t* value)\n\t{\n\t\t____typeName_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____typeName_2), value);\n\t}\n\n\tinline static int32_t get_offset_of__methodBase_3() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ____methodBase_3)); }\n\tinline MethodBase_t904190842 * get__methodBase_3() const { return ____methodBase_3; }\n\tinline MethodBase_t904190842 ** get_address_of__methodBase_3() { return &____methodBase_3; }\n\tinline void set__methodBase_3(MethodBase_t904190842 * value)\n\t{\n\t\t____methodBase_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____methodBase_3), value);\n\t}\n\n\tinline static int32_t get_offset_of__returnValue_4() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ____returnValue_4)); }\n\tinline RuntimeObject * get__returnValue_4() const { return ____returnValue_4; }\n\tinline RuntimeObject ** get_address_of__returnValue_4() { return &____returnValue_4; }\n\tinline void set__returnValue_4(RuntimeObject * value)\n\t{\n\t\t____returnValue_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____returnValue_4), value);\n\t}\n\n\tinline static int32_t get_offset_of__exception_5() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ____exception_5)); }\n\tinline Exception_t1927440687 * get__exception_5() const { return ____exception_5; }\n\tinline Exception_t1927440687 ** get_address_of__exception_5() { return &____exception_5; }\n\tinline void set__exception_5(Exception_t1927440687 * value)\n\t{\n\t\t____exception_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____exception_5), value);\n\t}\n\n\tinline static int32_t get_offset_of__methodSignature_6() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ____methodSignature_6)); }\n\tinline TypeU5BU5D_t1664964607* get__methodSignature_6() const { return ____methodSignature_6; }\n\tinline TypeU5BU5D_t1664964607** get_address_of__methodSignature_6() { return &____methodSignature_6; }\n\tinline void set__methodSignature_6(TypeU5BU5D_t1664964607* value)\n\t{\n\t\t____methodSignature_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____methodSignature_6), value);\n\t}\n\n\tinline static int32_t get_offset_of__inArgInfo_7() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ____inArgInfo_7)); }\n\tinline ArgInfo_t688271106 * get__inArgInfo_7() const { return ____inArgInfo_7; }\n\tinline ArgInfo_t688271106 ** get_address_of__inArgInfo_7() { return &____inArgInfo_7; }\n\tinline void set__inArgInfo_7(ArgInfo_t688271106 * value)\n\t{\n\t\t____inArgInfo_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____inArgInfo_7), value);\n\t}\n\n\tinline static int32_t get_offset_of__args_8() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ____args_8)); }\n\tinline ObjectU5BU5D_t3614634134* get__args_8() const { return ____args_8; }\n\tinline ObjectU5BU5D_t3614634134** get_address_of__args_8() { return &____args_8; }\n\tinline void set__args_8(ObjectU5BU5D_t3614634134* value)\n\t{\n\t\t____args_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____args_8), value);\n\t}\n\n\tinline static int32_t get_offset_of__outArgs_9() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ____outArgs_9)); }\n\tinline ObjectU5BU5D_t3614634134* get__outArgs_9() const { return ____outArgs_9; }\n\tinline ObjectU5BU5D_t3614634134** get_address_of__outArgs_9() { return &____outArgs_9; }\n\tinline void set__outArgs_9(ObjectU5BU5D_t3614634134* value)\n\t{\n\t\t____outArgs_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____outArgs_9), value);\n\t}\n\n\tinline static int32_t get_offset_of__callMsg_10() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ____callMsg_10)); }\n\tinline RuntimeObject* get__callMsg_10() const { return ____callMsg_10; }\n\tinline RuntimeObject** get_address_of__callMsg_10() { return &____callMsg_10; }\n\tinline void set__callMsg_10(RuntimeObject* value)\n\t{\n\t\t____callMsg_10 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____callMsg_10), value);\n\t}\n\n\tinline static int32_t get_offset_of__callContext_11() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ____callContext_11)); }\n\tinline LogicalCallContext_t725724420 * get__callContext_11() const { return ____callContext_11; }\n\tinline LogicalCallContext_t725724420 ** get_address_of__callContext_11() { return &____callContext_11; }\n\tinline void set__callContext_11(LogicalCallContext_t725724420 * value)\n\t{\n\t\t____callContext_11 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____callContext_11), value);\n\t}\n\n\tinline static int32_t get_offset_of__targetIdentity_12() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ____targetIdentity_12)); }\n\tinline Identity_t3647548000 * get__targetIdentity_12() const { return ____targetIdentity_12; }\n\tinline Identity_t3647548000 ** get_address_of__targetIdentity_12() { return &____targetIdentity_12; }\n\tinline void set__targetIdentity_12(Identity_t3647548000 * value)\n\t{\n\t\t____targetIdentity_12 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____targetIdentity_12), value);\n\t}\n\n\tinline static int32_t get_offset_of_ExternalProperties_13() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ___ExternalProperties_13)); }\n\tinline RuntimeObject* get_ExternalProperties_13() const { return ___ExternalProperties_13; }\n\tinline RuntimeObject** get_address_of_ExternalProperties_13() { return &___ExternalProperties_13; }\n\tinline void set_ExternalProperties_13(RuntimeObject* value)\n\t{\n\t\t___ExternalProperties_13 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___ExternalProperties_13), value);\n\t}\n\n\tinline static int32_t get_offset_of_InternalProperties_14() { return static_cast<int32_t>(offsetof(MethodResponse_t1456661140, ___InternalProperties_14)); }\n\tinline RuntimeObject* get_InternalProperties_14() const { return ___InternalProperties_14; }\n\tinline RuntimeObject** get_address_of_InternalProperties_14() { return &___InternalProperties_14; }\n\tinline void set_InternalProperties_14(RuntimeObject* value)\n\t{\n\t\t___InternalProperties_14 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___InternalProperties_14), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ METHODRESPONSE_T1456661140_H\n#ifndef MESSAGEDICTIONARY_T4157710479_H\n#define MESSAGEDICTIONARY_T4157710479_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.MessageDictionary\nstruct  MessageDictionary_t4157710479  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Collections.IDictionary System.Runtime.Remoting.Messaging.MessageDictionary::_internalProperties\n\tRuntimeObject* ____internalProperties_0;\n\t\/\/ System.Runtime.Remoting.Messaging.IMethodMessage System.Runtime.Remoting.Messaging.MessageDictionary::_message\n\tRuntimeObject* ____message_1;\n\t\/\/ System.String[] System.Runtime.Remoting.Messaging.MessageDictionary::_methodKeys\n\tStringU5BU5D_t1642385972* ____methodKeys_2;\n\t\/\/ System.Boolean System.Runtime.Remoting.Messaging.MessageDictionary::_ownProperties\n\tbool ____ownProperties_3;\n\npublic:\n\tinline static int32_t get_offset_of__internalProperties_0() { return static_cast<int32_t>(offsetof(MessageDictionary_t4157710479, ____internalProperties_0)); }\n\tinline RuntimeObject* get__internalProperties_0() const { return ____internalProperties_0; }\n\tinline RuntimeObject** get_address_of__internalProperties_0() { return &____internalProperties_0; }\n\tinline void set__internalProperties_0(RuntimeObject* value)\n\t{\n\t\t____internalProperties_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____internalProperties_0), value);\n\t}\n\n\tinline static int32_t get_offset_of__message_1() { return static_cast<int32_t>(offsetof(MessageDictionary_t4157710479, ____message_1)); }\n\tinline RuntimeObject* get__message_1() const { return ____message_1; }\n\tinline RuntimeObject** get_address_of__message_1() { return &____message_1; }\n\tinline void set__message_1(RuntimeObject* value)\n\t{\n\t\t____message_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____message_1), value);\n\t}\n\n\tinline static int32_t get_offset_of__methodKeys_2() { return static_cast<int32_t>(offsetof(MessageDictionary_t4157710479, ____methodKeys_2)); }\n\tinline StringU5BU5D_t1642385972* get__methodKeys_2() const { return ____methodKeys_2; }\n\tinline StringU5BU5D_t1642385972** get_address_of__methodKeys_2() { return &____methodKeys_2; }\n\tinline void set__methodKeys_2(StringU5BU5D_t1642385972* value)\n\t{\n\t\t____methodKeys_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____methodKeys_2), value);\n\t}\n\n\tinline static int32_t get_offset_of__ownProperties_3() { return static_cast<int32_t>(offsetof(MessageDictionary_t4157710479, ____ownProperties_3)); }\n\tinline bool get__ownProperties_3() const { return ____ownProperties_3; }\n\tinline bool* get_address_of__ownProperties_3() { return &____ownProperties_3; }\n\tinline void set__ownProperties_3(bool value)\n\t{\n\t\t____ownProperties_3 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ MESSAGEDICTIONARY_T4157710479_H\n#ifndef HEADER_T2756440555_H\n#define HEADER_T2756440555_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.Header\nstruct  Header_t2756440555  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ HEADER_T2756440555_H\n#ifndef METHODCALL_T2461541281_H\n#define METHODCALL_T2461541281_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.MethodCall\nstruct  MethodCall_t2461541281  : public RuntimeObject\n{\npublic:\n\t\/\/ System.String System.Runtime.Remoting.Messaging.MethodCall::_uri\n\tString_t* ____uri_0;\n\t\/\/ System.String System.Runtime.Remoting.Messaging.MethodCall::_typeName\n\tString_t* ____typeName_1;\n\t\/\/ System.String System.Runtime.Remoting.Messaging.MethodCall::_methodName\n\tString_t* ____methodName_2;\n\t\/\/ System.Object[] System.Runtime.Remoting.Messaging.MethodCall::_args\n\tObjectU5BU5D_t3614634134* ____args_3;\n\t\/\/ System.Type[] System.Runtime.Remoting.Messaging.MethodCall::_methodSignature\n\tTypeU5BU5D_t1664964607* ____methodSignature_4;\n\t\/\/ System.Reflection.MethodBase System.Runtime.Remoting.Messaging.MethodCall::_methodBase\n\tMethodBase_t904190842 * ____methodBase_5;\n\t\/\/ System.Runtime.Remoting.Messaging.LogicalCallContext System.Runtime.Remoting.Messaging.MethodCall::_callContext\n\tLogicalCallContext_t725724420 * ____callContext_6;\n\t\/\/ System.Runtime.Remoting.Identity System.Runtime.Remoting.Messaging.MethodCall::_targetIdentity\n\tIdentity_t3647548000 * ____targetIdentity_7;\n\t\/\/ System.Type[] System.Runtime.Remoting.Messaging.MethodCall::_genericArguments\n\tTypeU5BU5D_t1664964607* ____genericArguments_8;\n\t\/\/ System.Collections.IDictionary System.Runtime.Remoting.Messaging.MethodCall::ExternalProperties\n\tRuntimeObject* ___ExternalProperties_9;\n\t\/\/ System.Collections.IDictionary System.Runtime.Remoting.Messaging.MethodCall::InternalProperties\n\tRuntimeObject* ___InternalProperties_10;\n\npublic:\n\tinline static int32_t get_offset_of__uri_0() { return static_cast<int32_t>(offsetof(MethodCall_t2461541281, ____uri_0)); }\n\tinline String_t* get__uri_0() const { return ____uri_0; }\n\tinline String_t** get_address_of__uri_0() { return &____uri_0; }\n\tinline void set__uri_0(String_t* value)\n\t{\n\t\t____uri_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____uri_0), value);\n\t}\n\n\tinline static int32_t get_offset_of__typeName_1() { return static_cast<int32_t>(offsetof(MethodCall_t2461541281, ____typeName_1)); }\n\tinline String_t* get__typeName_1() const { return ____typeName_1; }\n\tinline String_t** get_address_of__typeName_1() { return &____typeName_1; }\n\tinline void set__typeName_1(String_t* value)\n\t{\n\t\t____typeName_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____typeName_1), value);\n\t}\n\n\tinline static int32_t get_offset_of__methodName_2() { return static_cast<int32_t>(offsetof(MethodCall_t2461541281, ____methodName_2)); }\n\tinline String_t* get__methodName_2() const { return ____methodName_2; }\n\tinline String_t** get_address_of__methodName_2() { return &____methodName_2; }\n\tinline void set__methodName_2(String_t* value)\n\t{\n\t\t____methodName_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____methodName_2), value);\n\t}\n\n\tinline static int32_t get_offset_of__args_3() { return static_cast<int32_t>(offsetof(MethodCall_t2461541281, ____args_3)); }\n\tinline ObjectU5BU5D_t3614634134* get__args_3() const { return ____args_3; }\n\tinline ObjectU5BU5D_t3614634134** get_address_of__args_3() { return &____args_3; }\n\tinline void set__args_3(ObjectU5BU5D_t3614634134* value)\n\t{\n\t\t____args_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____args_3), value);\n\t}\n\n\tinline static int32_t get_offset_of__methodSignature_4() { return static_cast<int32_t>(offsetof(MethodCall_t2461541281, ____methodSignature_4)); }\n\tinline TypeU5BU5D_t1664964607* get__methodSignature_4() const { return ____methodSignature_4; }\n\tinline TypeU5BU5D_t1664964607** get_address_of__methodSignature_4() { return &____methodSignature_4; }\n\tinline void set__methodSignature_4(TypeU5BU5D_t1664964607* value)\n\t{\n\t\t____methodSignature_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____methodSignature_4), value);\n\t}\n\n\tinline static int32_t get_offset_of__methodBase_5() { return static_cast<int32_t>(offsetof(MethodCall_t2461541281, ____methodBase_5)); }\n\tinline MethodBase_t904190842 * get__methodBase_5() const { return ____methodBase_5; }\n\tinline MethodBase_t904190842 ** get_address_of__methodBase_5() { return &____methodBase_5; }\n\tinline void set__methodBase_5(MethodBase_t904190842 * value)\n\t{\n\t\t____methodBase_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____methodBase_5), value);\n\t}\n\n\tinline static int32_t get_offset_of__callContext_6() { return static_cast<int32_t>(offsetof(MethodCall_t2461541281, ____callContext_6)); }\n\tinline LogicalCallContext_t725724420 * get__callContext_6() const { return ____callContext_6; }\n\tinline LogicalCallContext_t725724420 ** get_address_of__callContext_6() { return &____callContext_6; }\n\tinline void set__callContext_6(LogicalCallContext_t725724420 * value)\n\t{\n\t\t____callContext_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____callContext_6), value);\n\t}\n\n\tinline static int32_t get_offset_of__targetIdentity_7() { return static_cast<int32_t>(offsetof(MethodCall_t2461541281, ____targetIdentity_7)); }\n\tinline Identity_t3647548000 * get__targetIdentity_7() const { return ____targetIdentity_7; }\n\tinline Identity_t3647548000 ** get_address_of__targetIdentity_7() { return &____targetIdentity_7; }\n\tinline void set__targetIdentity_7(Identity_t3647548000 * value)\n\t{\n\t\t____targetIdentity_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____targetIdentity_7), value);\n\t}\n\n\tinline static int32_t get_offset_of__genericArguments_8() { return static_cast<int32_t>(offsetof(MethodCall_t2461541281, ____genericArguments_8)); }\n\tinline TypeU5BU5D_t1664964607* get__genericArguments_8() const { return ____genericArguments_8; }\n\tinline TypeU5BU5D_t1664964607** get_address_of__genericArguments_8() { return &____genericArguments_8; }\n\tinline void set__genericArguments_8(TypeU5BU5D_t1664964607* value)\n\t{\n\t\t____genericArguments_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____genericArguments_8), value);\n\t}\n\n\tinline static int32_t get_offset_of_ExternalProperties_9() { return static_cast<int32_t>(offsetof(MethodCall_t2461541281, ___ExternalProperties_9)); }\n\tinline RuntimeObject* get_ExternalProperties_9() const { return ___ExternalProperties_9; }\n\tinline RuntimeObject** get_address_of_ExternalProperties_9() { return &___ExternalProperties_9; }\n\tinline void set_ExternalProperties_9(RuntimeObject* value)\n\t{\n\t\t___ExternalProperties_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___ExternalProperties_9), value);\n\t}\n\n\tinline static int32_t get_offset_of_InternalProperties_10() { return static_cast<int32_t>(offsetof(MethodCall_t2461541281, ___InternalProperties_10)); }\n\tinline RuntimeObject* get_InternalProperties_10() const { return ___InternalProperties_10; }\n\tinline RuntimeObject** get_address_of_InternalProperties_10() { return &___InternalProperties_10; }\n\tinline void set_InternalProperties_10(RuntimeObject* value)\n\t{\n\t\t___InternalProperties_10 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___InternalProperties_10), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ METHODCALL_T2461541281_H\n#ifndef CLIENTCONTEXTTERMINATORSINK_T3236389774_H\n#define CLIENTCONTEXTTERMINATORSINK_T3236389774_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.ClientContextTerminatorSink\nstruct  ClientContextTerminatorSink_t3236389774  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Runtime.Remoting.Contexts.Context System.Runtime.Remoting.Messaging.ClientContextTerminatorSink::_context\n\tContext_t502196753 * ____context_0;\n\npublic:\n\tinline static int32_t get_offset_of__context_0() { return static_cast<int32_t>(offsetof(ClientContextTerminatorSink_t3236389774, ____context_0)); }\n\tinline Context_t502196753 * get__context_0() const { return ____context_0; }\n\tinline Context_t502196753 ** get_address_of__context_0() { return &____context_0; }\n\tinline void set__context_0(Context_t502196753 * value)\n\t{\n\t\t____context_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____context_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CLIENTCONTEXTTERMINATORSINK_T3236389774_H\n#ifndef STACKBUILDERSINK_T1613771438_H\n#define STACKBUILDERSINK_T1613771438_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.StackBuilderSink\nstruct  StackBuilderSink_t1613771438  : public RuntimeObject\n{\npublic:\n\t\/\/ System.MarshalByRefObject System.Runtime.Remoting.Messaging.StackBuilderSink::_target\n\tMarshalByRefObject_t1285298191 * ____target_0;\n\t\/\/ System.Runtime.Remoting.Proxies.RealProxy System.Runtime.Remoting.Messaging.StackBuilderSink::_rp\n\tRealProxy_t298428346 * ____rp_1;\n\npublic:\n\tinline static int32_t get_offset_of__target_0() { return static_cast<int32_t>(offsetof(StackBuilderSink_t1613771438, ____target_0)); }\n\tinline MarshalByRefObject_t1285298191 * get__target_0() const { return ____target_0; }\n\tinline MarshalByRefObject_t1285298191 ** get_address_of__target_0() { return &____target_0; }\n\tinline void set__target_0(MarshalByRefObject_t1285298191 * value)\n\t{\n\t\t____target_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____target_0), value);\n\t}\n\n\tinline static int32_t get_offset_of__rp_1() { return static_cast<int32_t>(offsetof(StackBuilderSink_t1613771438, ____rp_1)); }\n\tinline RealProxy_t298428346 * get__rp_1() const { return ____rp_1; }\n\tinline RealProxy_t298428346 ** get_address_of__rp_1() { return &____rp_1; }\n\tinline void set__rp_1(RealProxy_t298428346 * value)\n\t{\n\t\t____rp_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____rp_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ STACKBUILDERSINK_T1613771438_H\n#ifndef SERVEROBJECTTERMINATORSINK_T4261369100_H\n#define SERVEROBJECTTERMINATORSINK_T4261369100_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.ServerObjectTerminatorSink\nstruct  ServerObjectTerminatorSink_t4261369100  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Runtime.Remoting.Messaging.IMessageSink System.Runtime.Remoting.Messaging.ServerObjectTerminatorSink::_nextSink\n\tRuntimeObject* ____nextSink_0;\n\npublic:\n\tinline static int32_t get_offset_of__nextSink_0() { return static_cast<int32_t>(offsetof(ServerObjectTerminatorSink_t4261369100, ____nextSink_0)); }\n\tinline RuntimeObject* get__nextSink_0() const { return ____nextSink_0; }\n\tinline RuntimeObject** get_address_of__nextSink_0() { return &____nextSink_0; }\n\tinline void set__nextSink_0(RuntimeObject* value)\n\t{\n\t\t____nextSink_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____nextSink_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SERVEROBJECTTERMINATORSINK_T4261369100_H\n#ifndef OBJREFSURROGATE_T3912784830_H\n#define OBJREFSURROGATE_T3912784830_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.ObjRefSurrogate\nstruct  ObjRefSurrogate_t3912784830  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ OBJREFSURROGATE_T3912784830_H\n#ifndef SERVERCONTEXTTERMINATORSINK_T1054294306_H\n#define SERVERCONTEXTTERMINATORSINK_T1054294306_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.ServerContextTerminatorSink\nstruct  ServerContextTerminatorSink_t1054294306  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SERVERCONTEXTTERMINATORSINK_T1054294306_H\n#ifndef RETURNMESSAGE_T3411975905_H\n#define RETURNMESSAGE_T3411975905_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.ReturnMessage\nstruct  ReturnMessage_t3411975905  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Object[] System.Runtime.Remoting.Messaging.ReturnMessage::_outArgs\n\tObjectU5BU5D_t3614634134* ____outArgs_0;\n\t\/\/ System.Object[] System.Runtime.Remoting.Messaging.ReturnMessage::_args\n\tObjectU5BU5D_t3614634134* ____args_1;\n\t\/\/ System.Runtime.Remoting.Messaging.LogicalCallContext System.Runtime.Remoting.Messaging.ReturnMessage::_callCtx\n\tLogicalCallContext_t725724420 * ____callCtx_2;\n\t\/\/ System.Object System.Runtime.Remoting.Messaging.ReturnMessage::_returnValue\n\tRuntimeObject * ____returnValue_3;\n\t\/\/ System.String System.Runtime.Remoting.Messaging.ReturnMessage::_uri\n\tString_t* ____uri_4;\n\t\/\/ System.Exception System.Runtime.Remoting.Messaging.ReturnMessage::_exception\n\tException_t1927440687 * ____exception_5;\n\t\/\/ System.Reflection.MethodBase System.Runtime.Remoting.Messaging.ReturnMessage::_methodBase\n\tMethodBase_t904190842 * ____methodBase_6;\n\t\/\/ System.String System.Runtime.Remoting.Messaging.ReturnMessage::_methodName\n\tString_t* ____methodName_7;\n\t\/\/ System.Type[] System.Runtime.Remoting.Messaging.ReturnMessage::_methodSignature\n\tTypeU5BU5D_t1664964607* ____methodSignature_8;\n\t\/\/ System.String System.Runtime.Remoting.Messaging.ReturnMessage::_typeName\n\tString_t* ____typeName_9;\n\t\/\/ System.Runtime.Remoting.Messaging.MethodReturnDictionary System.Runtime.Remoting.Messaging.ReturnMessage::_properties\n\tMethodReturnDictionary_t981009581 * ____properties_10;\n\t\/\/ System.Runtime.Remoting.Identity System.Runtime.Remoting.Messaging.ReturnMessage::_targetIdentity\n\tIdentity_t3647548000 * ____targetIdentity_11;\n\t\/\/ System.Runtime.Remoting.Messaging.ArgInfo System.Runtime.Remoting.Messaging.ReturnMessage::_inArgInfo\n\tArgInfo_t688271106 * ____inArgInfo_12;\n\npublic:\n\tinline static int32_t get_offset_of__outArgs_0() { return static_cast<int32_t>(offsetof(ReturnMessage_t3411975905, ____outArgs_0)); }\n\tinline ObjectU5BU5D_t3614634134* get__outArgs_0() const { return ____outArgs_0; }\n\tinline ObjectU5BU5D_t3614634134** get_address_of__outArgs_0() { return &____outArgs_0; }\n\tinline void set__outArgs_0(ObjectU5BU5D_t3614634134* value)\n\t{\n\t\t____outArgs_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____outArgs_0), value);\n\t}\n\n\tinline static int32_t get_offset_of__args_1() { return static_cast<int32_t>(offsetof(ReturnMessage_t3411975905, ____args_1)); }\n\tinline ObjectU5BU5D_t3614634134* get__args_1() const { return ____args_1; }\n\tinline ObjectU5BU5D_t3614634134** get_address_of__args_1() { return &____args_1; }\n\tinline void set__args_1(ObjectU5BU5D_t3614634134* value)\n\t{\n\t\t____args_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____args_1), value);\n\t}\n\n\tinline static int32_t get_offset_of__callCtx_2() { return static_cast<int32_t>(offsetof(ReturnMessage_t3411975905, ____callCtx_2)); }\n\tinline LogicalCallContext_t725724420 * get__callCtx_2() const { return ____callCtx_2; }\n\tinline LogicalCallContext_t725724420 ** get_address_of__callCtx_2() { return &____callCtx_2; }\n\tinline void set__callCtx_2(LogicalCallContext_t725724420 * value)\n\t{\n\t\t____callCtx_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____callCtx_2), value);\n\t}\n\n\tinline static int32_t get_offset_of__returnValue_3() { return static_cast<int32_t>(offsetof(ReturnMessage_t3411975905, ____returnValue_3)); }\n\tinline RuntimeObject * get__returnValue_3() const { return ____returnValue_3; }\n\tinline RuntimeObject ** get_address_of__returnValue_3() { return &____returnValue_3; }\n\tinline void set__returnValue_3(RuntimeObject * value)\n\t{\n\t\t____returnValue_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____returnValue_3), value);\n\t}\n\n\tinline static int32_t get_offset_of__uri_4() { return static_cast<int32_t>(offsetof(ReturnMessage_t3411975905, ____uri_4)); }\n\tinline String_t* get__uri_4() const { return ____uri_4; }\n\tinline String_t** get_address_of__uri_4() { return &____uri_4; }\n\tinline void set__uri_4(String_t* value)\n\t{\n\t\t____uri_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____uri_4), value);\n\t}\n\n\tinline static int32_t get_offset_of__exception_5() { return static_cast<int32_t>(offsetof(ReturnMessage_t3411975905, ____exception_5)); }\n\tinline Exception_t1927440687 * get__exception_5() const { return ____exception_5; }\n\tinline Exception_t1927440687 ** get_address_of__exception_5() { return &____exception_5; }\n\tinline void set__exception_5(Exception_t1927440687 * value)\n\t{\n\t\t____exception_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____exception_5), value);\n\t}\n\n\tinline static int32_t get_offset_of__methodBase_6() { return static_cast<int32_t>(offsetof(ReturnMessage_t3411975905, ____methodBase_6)); }\n\tinline MethodBase_t904190842 * get__methodBase_6() const { return ____methodBase_6; }\n\tinline MethodBase_t904190842 ** get_address_of__methodBase_6() { return &____methodBase_6; }\n\tinline void set__methodBase_6(MethodBase_t904190842 * value)\n\t{\n\t\t____methodBase_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____methodBase_6), value);\n\t}\n\n\tinline static int32_t get_offset_of__methodName_7() { return static_cast<int32_t>(offsetof(ReturnMessage_t3411975905, ____methodName_7)); }\n\tinline String_t* get__methodName_7() const { return ____methodName_7; }\n\tinline String_t** get_address_of__methodName_7() { return &____methodName_7; }\n\tinline void set__methodName_7(String_t* value)\n\t{\n\t\t____methodName_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____methodName_7), value);\n\t}\n\n\tinline static int32_t get_offset_of__methodSignature_8() { return static_cast<int32_t>(offsetof(ReturnMessage_t3411975905, ____methodSignature_8)); }\n\tinline TypeU5BU5D_t1664964607* get__methodSignature_8() const { return ____methodSignature_8; }\n\tinline TypeU5BU5D_t1664964607** get_address_of__methodSignature_8() { return &____methodSignature_8; }\n\tinline void set__methodSignature_8(TypeU5BU5D_t1664964607* value)\n\t{\n\t\t____methodSignature_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____methodSignature_8), value);\n\t}\n\n\tinline static int32_t get_offset_of__typeName_9() { return static_cast<int32_t>(offsetof(ReturnMessage_t3411975905, ____typeName_9)); }\n\tinline String_t* get__typeName_9() const { return ____typeName_9; }\n\tinline String_t** get_address_of__typeName_9() { return &____typeName_9; }\n\tinline void set__typeName_9(String_t* value)\n\t{\n\t\t____typeName_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____typeName_9), value);\n\t}\n\n\tinline static int32_t get_offset_of__properties_10() { return static_cast<int32_t>(offsetof(ReturnMessage_t3411975905, ____properties_10)); }\n\tinline MethodReturnDictionary_t981009581 * get__properties_10() const { return ____properties_10; }\n\tinline MethodReturnDictionary_t981009581 ** get_address_of__properties_10() { return &____properties_10; }\n\tinline void set__properties_10(MethodReturnDictionary_t981009581 * value)\n\t{\n\t\t____properties_10 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____properties_10), value);\n\t}\n\n\tinline static int32_t get_offset_of__targetIdentity_11() { return static_cast<int32_t>(offsetof(ReturnMessage_t3411975905, ____targetIdentity_11)); }\n\tinline Identity_t3647548000 * get__targetIdentity_11() const { return ____targetIdentity_11; }\n\tinline Identity_t3647548000 ** get_address_of__targetIdentity_11() { return &____targetIdentity_11; }\n\tinline void set__targetIdentity_11(Identity_t3647548000 * value)\n\t{\n\t\t____targetIdentity_11 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____targetIdentity_11), value);\n\t}\n\n\tinline static int32_t get_offset_of__inArgInfo_12() { return static_cast<int32_t>(offsetof(ReturnMessage_t3411975905, ____inArgInfo_12)); }\n\tinline ArgInfo_t688271106 * get__inArgInfo_12() const { return ____inArgInfo_12; }\n\tinline ArgInfo_t688271106 ** get_address_of__inArgInfo_12() { return &____inArgInfo_12; }\n\tinline void set__inArgInfo_12(ArgInfo_t688271106 * value)\n\t{\n\t\t____inArgInfo_12 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____inArgInfo_12), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ RETURNMESSAGE_T3411975905_H\n#ifndef MCMDICTIONARY_T159052147_H\n#define MCMDICTIONARY_T159052147_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.MCMDictionary\nstruct  MCMDictionary_t159052147  : public MessageDictionary_t4157710479\n{\npublic:\n\npublic:\n};\n\nstruct MCMDictionary_t159052147_StaticFields\n{\npublic:\n\t\/\/ System.String[] System.Runtime.Remoting.Messaging.MCMDictionary::InternalKeys\n\tStringU5BU5D_t1642385972* ___InternalKeys_4;\n\npublic:\n\tinline static int32_t get_offset_of_InternalKeys_4() { return static_cast<int32_t>(offsetof(MCMDictionary_t159052147_StaticFields, ___InternalKeys_4)); }\n\tinline StringU5BU5D_t1642385972* get_InternalKeys_4() const { return ___InternalKeys_4; }\n\tinline StringU5BU5D_t1642385972** get_address_of_InternalKeys_4() { return &___InternalKeys_4; }\n\tinline void set_InternalKeys_4(StringU5BU5D_t1642385972* value)\n\t{\n\t\t___InternalKeys_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___InternalKeys_4), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ MCMDICTIONARY_T159052147_H\n#ifndef CONSTRUCTIONCALLDICTIONARY_T2993650247_H\n#define CONSTRUCTIONCALLDICTIONARY_T2993650247_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.ConstructionCallDictionary\nstruct  ConstructionCallDictionary_t2993650247  : public MessageDictionary_t4157710479\n{\npublic:\n\npublic:\n};\n\nstruct ConstructionCallDictionary_t2993650247_StaticFields\n{\npublic:\n\t\/\/ System.String[] System.Runtime.Remoting.Messaging.ConstructionCallDictionary::InternalKeys\n\tStringU5BU5D_t1642385972* ___InternalKeys_4;\n\npublic:\n\tinline static int32_t get_offset_of_InternalKeys_4() { return static_cast<int32_t>(offsetof(ConstructionCallDictionary_t2993650247_StaticFields, ___InternalKeys_4)); }\n\tinline StringU5BU5D_t1642385972* get_InternalKeys_4() const { return ___InternalKeys_4; }\n\tinline StringU5BU5D_t1642385972** get_address_of_InternalKeys_4() { return &___InternalKeys_4; }\n\tinline void set_InternalKeys_4(StringU5BU5D_t1642385972* value)\n\t{\n\t\t___InternalKeys_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___InternalKeys_4), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CONSTRUCTIONCALLDICTIONARY_T2993650247_H\n#ifndef REMOTEACTIVATOR_T213750447_H\n#define REMOTEACTIVATOR_T213750447_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Activation.RemoteActivator\nstruct  RemoteActivator_t213750447  : public MarshalByRefObject_t1285298191\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ REMOTEACTIVATOR_T213750447_H\n#ifndef CONSTRUCTIONCALL_T1254994451_H\n#define CONSTRUCTIONCALL_T1254994451_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.ConstructionCall\nstruct  ConstructionCall_t1254994451  : public MethodCall_t2461541281\n{\npublic:\n\t\/\/ System.Runtime.Remoting.Activation.IActivator System.Runtime.Remoting.Messaging.ConstructionCall::_activator\n\tRuntimeObject* ____activator_11;\n\t\/\/ System.Object[] System.Runtime.Remoting.Messaging.ConstructionCall::_activationAttributes\n\tObjectU5BU5D_t3614634134* ____activationAttributes_12;\n\t\/\/ System.Collections.IList System.Runtime.Remoting.Messaging.ConstructionCall::_contextProperties\n\tRuntimeObject* ____contextProperties_13;\n\t\/\/ System.Type System.Runtime.Remoting.Messaging.ConstructionCall::_activationType\n\tType_t * ____activationType_14;\n\t\/\/ System.String System.Runtime.Remoting.Messaging.ConstructionCall::_activationTypeName\n\tString_t* ____activationTypeName_15;\n\t\/\/ System.Boolean System.Runtime.Remoting.Messaging.ConstructionCall::_isContextOk\n\tbool ____isContextOk_16;\n\npublic:\n\tinline static int32_t get_offset_of__activator_11() { return static_cast<int32_t>(offsetof(ConstructionCall_t1254994451, ____activator_11)); }\n\tinline RuntimeObject* get__activator_11() const { return ____activator_11; }\n\tinline RuntimeObject** get_address_of__activator_11() { return &____activator_11; }\n\tinline void set__activator_11(RuntimeObject* value)\n\t{\n\t\t____activator_11 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____activator_11), value);\n\t}\n\n\tinline static int32_t get_offset_of__activationAttributes_12() { return static_cast<int32_t>(offsetof(ConstructionCall_t1254994451, ____activationAttributes_12)); }\n\tinline ObjectU5BU5D_t3614634134* get__activationAttributes_12() const { return ____activationAttributes_12; }\n\tinline ObjectU5BU5D_t3614634134** get_address_of__activationAttributes_12() { return &____activationAttributes_12; }\n\tinline void set__activationAttributes_12(ObjectU5BU5D_t3614634134* value)\n\t{\n\t\t____activationAttributes_12 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____activationAttributes_12), value);\n\t}\n\n\tinline static int32_t get_offset_of__contextProperties_13() { return static_cast<int32_t>(offsetof(ConstructionCall_t1254994451, ____contextProperties_13)); }\n\tinline RuntimeObject* get__contextProperties_13() const { return ____contextProperties_13; }\n\tinline RuntimeObject** get_address_of__contextProperties_13() { return &____contextProperties_13; }\n\tinline void set__contextProperties_13(RuntimeObject* value)\n\t{\n\t\t____contextProperties_13 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____contextProperties_13), value);\n\t}\n\n\tinline static int32_t get_offset_of__activationType_14() { return static_cast<int32_t>(offsetof(ConstructionCall_t1254994451, ____activationType_14)); }\n\tinline Type_t * get__activationType_14() const { return ____activationType_14; }\n\tinline Type_t ** get_address_of__activationType_14() { return &____activationType_14; }\n\tinline void set__activationType_14(Type_t * value)\n\t{\n\t\t____activationType_14 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____activationType_14), value);\n\t}\n\n\tinline static int32_t get_offset_of__activationTypeName_15() { return static_cast<int32_t>(offsetof(ConstructionCall_t1254994451, ____activationTypeName_15)); }\n\tinline String_t* get__activationTypeName_15() const { return ____activationTypeName_15; }\n\tinline String_t** get_address_of__activationTypeName_15() { return &____activationTypeName_15; }\n\tinline void set__activationTypeName_15(String_t* value)\n\t{\n\t\t____activationTypeName_15 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____activationTypeName_15), value);\n\t}\n\n\tinline static int32_t get_offset_of__isContextOk_16() { return static_cast<int32_t>(offsetof(ConstructionCall_t1254994451, ____isContextOk_16)); }\n\tinline bool get__isContextOk_16() const { return ____isContextOk_16; }\n\tinline bool* get_address_of__isContextOk_16() { return &____isContextOk_16; }\n\tinline void set__isContextOk_16(bool value)\n\t{\n\t\t____isContextOk_16 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CONSTRUCTIONCALL_T1254994451_H\n#ifndef INTPTR_T_H\n#define INTPTR_T_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.IntPtr\nstruct  IntPtr_t \n{\npublic:\n\t\/\/ System.Void* System.IntPtr::m_value\n\tvoid* ___m_value_0;\n\npublic:\n\tinline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); }\n\tinline void* get_m_value_0() const { return ___m_value_0; }\n\tinline void** get_address_of_m_value_0() { return &___m_value_0; }\n\tinline void set_m_value_0(void* value)\n\t{\n\t\t___m_value_0 = value;\n\t}\n};\n\nstruct IntPtr_t_StaticFields\n{\npublic:\n\t\/\/ System.IntPtr System.IntPtr::Zero\n\tintptr_t ___Zero_1;\n\npublic:\n\tinline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); }\n\tinline intptr_t get_Zero_1() const { return ___Zero_1; }\n\tinline intptr_t* get_address_of_Zero_1() { return &___Zero_1; }\n\tinline void set_Zero_1(intptr_t value)\n\t{\n\t\t___Zero_1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTPTR_T_H\n#ifndef DATETIME_T693205669_H\n#define DATETIME_T693205669_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.DateTime\nstruct  DateTime_t693205669 \n{\npublic:\n\t\/\/ System.UInt64 System.DateTime::dateData\n\tuint64_t ___dateData_4;\n\npublic:\n\tinline static int32_t get_offset_of_dateData_4() { return static_cast<int32_t>(offsetof(DateTime_t693205669, ___dateData_4)); }\n\tinline uint64_t get_dateData_4() const { return ___dateData_4; }\n\tinline uint64_t* get_address_of_dateData_4() { return &___dateData_4; }\n\tinline void set_dateData_4(uint64_t value)\n\t{\n\t\t___dateData_4 = value;\n\t}\n};\n\nstruct DateTime_t693205669_StaticFields\n{\npublic:\n\t\/\/ System.Int32[] System.DateTime::DaysToMonth365\n\tInt32U5BU5D_t3030399641* ___DaysToMonth365_0;\n\t\/\/ System.Int32[] System.DateTime::DaysToMonth366\n\tInt32U5BU5D_t3030399641* ___DaysToMonth366_1;\n\t\/\/ System.DateTime System.DateTime::MinValue\n\tDateTime_t693205669  ___MinValue_2;\n\t\/\/ System.DateTime System.DateTime::MaxValue\n\tDateTime_t693205669  ___MaxValue_3;\n\npublic:\n\tinline static int32_t get_offset_of_DaysToMonth365_0() { return static_cast<int32_t>(offsetof(DateTime_t693205669_StaticFields, ___DaysToMonth365_0)); }\n\tinline Int32U5BU5D_t3030399641* get_DaysToMonth365_0() const { return ___DaysToMonth365_0; }\n\tinline Int32U5BU5D_t3030399641** get_address_of_DaysToMonth365_0() { return &___DaysToMonth365_0; }\n\tinline void set_DaysToMonth365_0(Int32U5BU5D_t3030399641* value)\n\t{\n\t\t___DaysToMonth365_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___DaysToMonth365_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_DaysToMonth366_1() { return static_cast<int32_t>(offsetof(DateTime_t693205669_StaticFields, ___DaysToMonth366_1)); }\n\tinline Int32U5BU5D_t3030399641* get_DaysToMonth366_1() const { return ___DaysToMonth366_1; }\n\tinline Int32U5BU5D_t3030399641** get_address_of_DaysToMonth366_1() { return &___DaysToMonth366_1; }\n\tinline void set_DaysToMonth366_1(Int32U5BU5D_t3030399641* value)\n\t{\n\t\t___DaysToMonth366_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___DaysToMonth366_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_MinValue_2() { return static_cast<int32_t>(offsetof(DateTime_t693205669_StaticFields, ___MinValue_2)); }\n\tinline DateTime_t693205669  get_MinValue_2() const { return ___MinValue_2; }\n\tinline DateTime_t693205669 * get_address_of_MinValue_2() { return &___MinValue_2; }\n\tinline void set_MinValue_2(DateTime_t693205669  value)\n\t{\n\t\t___MinValue_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_MaxValue_3() { return static_cast<int32_t>(offsetof(DateTime_t693205669_StaticFields, ___MaxValue_3)); }\n\tinline DateTime_t693205669  get_MaxValue_3() const { return ___MaxValue_3; }\n\tinline DateTime_t693205669 * get_address_of_MaxValue_3() { return &___MaxValue_3; }\n\tinline void set_MaxValue_3(DateTime_t693205669  value)\n\t{\n\t\t___MaxValue_3 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DATETIME_T693205669_H\n#ifndef ONEWAYATTRIBUTE_T2539461443_H\n#define ONEWAYATTRIBUTE_T2539461443_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.OneWayAttribute\nstruct  OneWayAttribute_t2539461443  : public Attribute_t542643598\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ ONEWAYATTRIBUTE_T2539461443_H\n#ifndef UINTPTR_T_H\n#define UINTPTR_T_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.UIntPtr\nstruct  UIntPtr_t \n{\npublic:\n\t\/\/ System.Void* System.UIntPtr::_pointer\n\tvoid* ____pointer_1;\n\npublic:\n\tinline static int32_t get_offset_of__pointer_1() { return static_cast<int32_t>(offsetof(UIntPtr_t, ____pointer_1)); }\n\tinline void* get__pointer_1() const { return ____pointer_1; }\n\tinline void** get_address_of__pointer_1() { return &____pointer_1; }\n\tinline void set__pointer_1(void* value)\n\t{\n\t\t____pointer_1 = value;\n\t}\n};\n\nstruct UIntPtr_t_StaticFields\n{\npublic:\n\t\/\/ System.UIntPtr System.UIntPtr::Zero\n\tuintptr_t ___Zero_0;\n\npublic:\n\tinline static int32_t get_offset_of_Zero_0() { return static_cast<int32_t>(offsetof(UIntPtr_t_StaticFields, ___Zero_0)); }\n\tinline uintptr_t get_Zero_0() const { return ___Zero_0; }\n\tinline uintptr_t* get_address_of_Zero_0() { return &___Zero_0; }\n\tinline void set_Zero_0(uintptr_t value)\n\t{\n\t\t___Zero_0 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ UINTPTR_T_H\n#ifndef READER_T1568751674_H\n#define READER_T1568751674_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.LogicalCallContext\/Reader\nstruct  Reader_t1568751674 \n{\npublic:\n\t\/\/ System.Runtime.Remoting.Messaging.LogicalCallContext System.Runtime.Remoting.Messaging.LogicalCallContext\/Reader::m_ctx\n\tLogicalCallContext_t725724420 * ___m_ctx_0;\n\npublic:\n\tinline static int32_t get_offset_of_m_ctx_0() { return static_cast<int32_t>(offsetof(Reader_t1568751674, ___m_ctx_0)); }\n\tinline LogicalCallContext_t725724420 * get_m_ctx_0() const { return ___m_ctx_0; }\n\tinline LogicalCallContext_t725724420 ** get_address_of_m_ctx_0() { return &___m_ctx_0; }\n\tinline void set_m_ctx_0(LogicalCallContext_t725724420 * value)\n\t{\n\t\t___m_ctx_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_ctx_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.Runtime.Remoting.Messaging.LogicalCallContext\/Reader\nstruct Reader_t1568751674_marshaled_pinvoke\n{\n\tLogicalCallContext_t725724420 * ___m_ctx_0;\n};\n\/\/ Native definition for COM marshalling of System.Runtime.Remoting.Messaging.LogicalCallContext\/Reader\nstruct Reader_t1568751674_marshaled_com\n{\n\tLogicalCallContext_t725724420 * ___m_ctx_0;\n};\n#endif \/\/ READER_T1568751674_H\n#ifndef CONTEXTBOUNDOBJECT_T4264702438_H\n#define CONTEXTBOUNDOBJECT_T4264702438_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ContextBoundObject\nstruct  ContextBoundObject_t4264702438  : public MarshalByRefObject_t1285298191\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CONTEXTBOUNDOBJECT_T4264702438_H\n#ifndef VOID_T1841601450_H\n#define VOID_T1841601450_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Void\nstruct  Void_t1841601450 \n{\npublic:\n\tunion\n\t{\n\t\tstruct\n\t\t{\n\t\t};\n\t\tuint8_t Void_t1841601450__padding[1];\n\t};\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ VOID_T1841601450_H\n#ifndef METHODRETURNDICTIONARY_T981009581_H\n#define METHODRETURNDICTIONARY_T981009581_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.MethodReturnDictionary\nstruct  MethodReturnDictionary_t981009581  : public MessageDictionary_t4157710479\n{\npublic:\n\npublic:\n};\n\nstruct MethodReturnDictionary_t981009581_StaticFields\n{\npublic:\n\t\/\/ System.String[] System.Runtime.Remoting.Messaging.MethodReturnDictionary::InternalReturnKeys\n\tStringU5BU5D_t1642385972* ___InternalReturnKeys_4;\n\t\/\/ System.String[] System.Runtime.Remoting.Messaging.MethodReturnDictionary::InternalExceptionKeys\n\tStringU5BU5D_t1642385972* ___InternalExceptionKeys_5;\n\npublic:\n\tinline static int32_t get_offset_of_InternalReturnKeys_4() { return static_cast<int32_t>(offsetof(MethodReturnDictionary_t981009581_StaticFields, ___InternalReturnKeys_4)); }\n\tinline StringU5BU5D_t1642385972* get_InternalReturnKeys_4() const { return ___InternalReturnKeys_4; }\n\tinline StringU5BU5D_t1642385972** get_address_of_InternalReturnKeys_4() { return &___InternalReturnKeys_4; }\n\tinline void set_InternalReturnKeys_4(StringU5BU5D_t1642385972* value)\n\t{\n\t\t___InternalReturnKeys_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___InternalReturnKeys_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_InternalExceptionKeys_5() { return static_cast<int32_t>(offsetof(MethodReturnDictionary_t981009581_StaticFields, ___InternalExceptionKeys_5)); }\n\tinline StringU5BU5D_t1642385972* get_InternalExceptionKeys_5() const { return ___InternalExceptionKeys_5; }\n\tinline StringU5BU5D_t1642385972** get_address_of_InternalExceptionKeys_5() { return &___InternalExceptionKeys_5; }\n\tinline void set_InternalExceptionKeys_5(StringU5BU5D_t1642385972* value)\n\t{\n\t\t___InternalExceptionKeys_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___InternalExceptionKeys_5), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ METHODRETURNDICTIONARY_T981009581_H\n#ifndef ENUM_T2459695545_H\n#define ENUM_T2459695545_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Enum\nstruct  Enum_t2459695545  : public ValueType_t3507792607\n{\npublic:\n\npublic:\n};\n\nstruct Enum_t2459695545_StaticFields\n{\npublic:\n\t\/\/ System.Char[] System.Enum::enumSeperatorCharArray\n\tCharU5BU5D_t1328083999* ___enumSeperatorCharArray_0;\n\npublic:\n\tinline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t2459695545_StaticFields, ___enumSeperatorCharArray_0)); }\n\tinline CharU5BU5D_t1328083999* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; }\n\tinline CharU5BU5D_t1328083999** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; }\n\tinline void set_enumSeperatorCharArray_0(CharU5BU5D_t1328083999* value)\n\t{\n\t\t___enumSeperatorCharArray_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___enumSeperatorCharArray_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.Enum\nstruct Enum_t2459695545_marshaled_pinvoke\n{\n};\n\/\/ Native definition for COM marshalling of System.Enum\nstruct Enum_t2459695545_marshaled_com\n{\n};\n#endif \/\/ ENUM_T2459695545_H\n#ifndef BOOLEAN_T3825574718_H\n#define BOOLEAN_T3825574718_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Boolean\nstruct  Boolean_t3825574718 \n{\npublic:\n\t\/\/ System.Boolean System.Boolean::m_value\n\tbool ___m_value_0;\n\npublic:\n\tinline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_t3825574718, ___m_value_0)); }\n\tinline bool get_m_value_0() const { return ___m_value_0; }\n\tinline bool* get_address_of_m_value_0() { return &___m_value_0; }\n\tinline void set_m_value_0(bool value)\n\t{\n\t\t___m_value_0 = value;\n\t}\n};\n\nstruct Boolean_t3825574718_StaticFields\n{\npublic:\n\t\/\/ System.String System.Boolean::TrueString\n\tString_t* ___TrueString_5;\n\t\/\/ System.String System.Boolean::FalseString\n\tString_t* ___FalseString_6;\n\npublic:\n\tinline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_t3825574718_StaticFields, ___TrueString_5)); }\n\tinline String_t* get_TrueString_5() const { return ___TrueString_5; }\n\tinline String_t** get_address_of_TrueString_5() { return &___TrueString_5; }\n\tinline void set_TrueString_5(String_t* value)\n\t{\n\t\t___TrueString_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___TrueString_5), value);\n\t}\n\n\tinline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_t3825574718_StaticFields, ___FalseString_6)); }\n\tinline String_t* get_FalseString_6() const { return ___FalseString_6; }\n\tinline String_t** get_address_of_FalseString_6() { return &___FalseString_6; }\n\tinline void set_FalseString_6(String_t* value)\n\t{\n\t\t___FalseString_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___FalseString_6), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ BOOLEAN_T3825574718_H\n#ifndef CONTEXTATTRIBUTE_T197102333_H\n#define CONTEXTATTRIBUTE_T197102333_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Contexts.ContextAttribute\nstruct  ContextAttribute_t197102333  : public Attribute_t542643598\n{\npublic:\n\t\/\/ System.String System.Runtime.Remoting.Contexts.ContextAttribute::AttributeName\n\tString_t* ___AttributeName_0;\n\npublic:\n\tinline static int32_t get_offset_of_AttributeName_0() { return static_cast<int32_t>(offsetof(ContextAttribute_t197102333, ___AttributeName_0)); }\n\tinline String_t* get_AttributeName_0() const { return ___AttributeName_0; }\n\tinline String_t** get_address_of_AttributeName_0() { return &___AttributeName_0; }\n\tinline void set_AttributeName_0(String_t* value)\n\t{\n\t\t___AttributeName_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___AttributeName_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CONTEXTATTRIBUTE_T197102333_H\n#ifndef DELEGATE_T3022476291_H\n#define DELEGATE_T3022476291_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Delegate\nstruct  Delegate_t3022476291  : public RuntimeObject\n{\npublic:\n\t\/\/ System.IntPtr System.Delegate::method_ptr\n\tIl2CppMethodPointer ___method_ptr_0;\n\t\/\/ System.IntPtr System.Delegate::invoke_impl\n\tintptr_t ___invoke_impl_1;\n\t\/\/ System.Object System.Delegate::m_target\n\tRuntimeObject * ___m_target_2;\n\t\/\/ System.IntPtr System.Delegate::method\n\tintptr_t ___method_3;\n\t\/\/ System.IntPtr System.Delegate::delegate_trampoline\n\tintptr_t ___delegate_trampoline_4;\n\t\/\/ System.IntPtr System.Delegate::extra_arg\n\tintptr_t ___extra_arg_5;\n\t\/\/ System.IntPtr System.Delegate::method_code\n\tintptr_t ___method_code_6;\n\t\/\/ System.Reflection.MethodInfo System.Delegate::method_info\n\tMethodInfo_t * ___method_info_7;\n\t\/\/ System.Reflection.MethodInfo System.Delegate::original_method_info\n\tMethodInfo_t * ___original_method_info_8;\n\t\/\/ System.DelegateData System.Delegate::data\n\tDelegateData_t1572802995 * ___data_9;\n\t\/\/ System.Boolean System.Delegate::method_is_virtual\n\tbool ___method_is_virtual_10;\n\npublic:\n\tinline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_ptr_0)); }\n\tinline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; }\n\tinline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; }\n\tinline void set_method_ptr_0(Il2CppMethodPointer value)\n\t{\n\t\t___method_ptr_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___invoke_impl_1)); }\n\tinline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; }\n\tinline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; }\n\tinline void set_invoke_impl_1(intptr_t value)\n\t{\n\t\t___invoke_impl_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___m_target_2)); }\n\tinline RuntimeObject * get_m_target_2() const { return ___m_target_2; }\n\tinline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; }\n\tinline void set_m_target_2(RuntimeObject * value)\n\t{\n\t\t___m_target_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_target_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_3)); }\n\tinline intptr_t get_method_3() const { return ___method_3; }\n\tinline intptr_t* get_address_of_method_3() { return &___method_3; }\n\tinline void set_method_3(intptr_t value)\n\t{\n\t\t___method_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___delegate_trampoline_4)); }\n\tinline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; }\n\tinline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; }\n\tinline void set_delegate_trampoline_4(intptr_t value)\n\t{\n\t\t___delegate_trampoline_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_extra_arg_5() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___extra_arg_5)); }\n\tinline intptr_t get_extra_arg_5() const { return ___extra_arg_5; }\n\tinline intptr_t* get_address_of_extra_arg_5() { return &___extra_arg_5; }\n\tinline void set_extra_arg_5(intptr_t value)\n\t{\n\t\t___extra_arg_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of_method_code_6() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_code_6)); }\n\tinline intptr_t get_method_code_6() const { return ___method_code_6; }\n\tinline intptr_t* get_address_of_method_code_6() { return &___method_code_6; }\n\tinline void set_method_code_6(intptr_t value)\n\t{\n\t\t___method_code_6 = value;\n\t}\n\n\tinline static int32_t get_offset_of_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_info_7)); }\n\tinline MethodInfo_t * get_method_info_7() const { return ___method_info_7; }\n\tinline MethodInfo_t ** get_address_of_method_info_7() { return &___method_info_7; }\n\tinline void set_method_info_7(MethodInfo_t * value)\n\t{\n\t\t___method_info_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___method_info_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_original_method_info_8() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___original_method_info_8)); }\n\tinline MethodInfo_t * get_original_method_info_8() const { return ___original_method_info_8; }\n\tinline MethodInfo_t ** get_address_of_original_method_info_8() { return &___original_method_info_8; }\n\tinline void set_original_method_info_8(MethodInfo_t * value)\n\t{\n\t\t___original_method_info_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___original_method_info_8), value);\n\t}\n\n\tinline static int32_t get_offset_of_data_9() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___data_9)); }\n\tinline DelegateData_t1572802995 * get_data_9() const { return ___data_9; }\n\tinline DelegateData_t1572802995 ** get_address_of_data_9() { return &___data_9; }\n\tinline void set_data_9(DelegateData_t1572802995 * value)\n\t{\n\t\t___data_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___data_9), value);\n\t}\n\n\tinline static int32_t get_offset_of_method_is_virtual_10() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_is_virtual_10)); }\n\tinline bool get_method_is_virtual_10() const { return ___method_is_virtual_10; }\n\tinline bool* get_address_of_method_is_virtual_10() { return &___method_is_virtual_10; }\n\tinline void set_method_is_virtual_10(bool value)\n\t{\n\t\t___method_is_virtual_10 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.Delegate\nstruct Delegate_t3022476291_marshaled_pinvoke\n{\n\tintptr_t ___method_ptr_0;\n\tintptr_t ___invoke_impl_1;\n\tIl2CppIUnknown* ___m_target_2;\n\tintptr_t ___method_3;\n\tintptr_t ___delegate_trampoline_4;\n\tintptr_t ___extra_arg_5;\n\tintptr_t ___method_code_6;\n\tMethodInfo_t * ___method_info_7;\n\tMethodInfo_t * ___original_method_info_8;\n\tDelegateData_t1572802995 * ___data_9;\n\tint32_t ___method_is_virtual_10;\n};\n\/\/ Native definition for COM marshalling of System.Delegate\nstruct Delegate_t3022476291_marshaled_com\n{\n\tintptr_t ___method_ptr_0;\n\tintptr_t ___invoke_impl_1;\n\tIl2CppIUnknown* ___m_target_2;\n\tintptr_t ___method_3;\n\tintptr_t ___delegate_trampoline_4;\n\tintptr_t ___extra_arg_5;\n\tintptr_t ___method_code_6;\n\tMethodInfo_t * ___method_info_7;\n\tMethodInfo_t * ___original_method_info_8;\n\tDelegateData_t1572802995 * ___data_9;\n\tint32_t ___method_is_virtual_10;\n};\n#endif \/\/ DELEGATE_T3022476291_H\n#ifndef TIMESPAN_T3430258949_H\n#define TIMESPAN_T3430258949_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.TimeSpan\nstruct  TimeSpan_t3430258949 \n{\npublic:\n\t\/\/ System.Int64 System.TimeSpan::_ticks\n\tint64_t ____ticks_3;\n\npublic:\n\tinline static int32_t get_offset_of__ticks_3() { return static_cast<int32_t>(offsetof(TimeSpan_t3430258949, ____ticks_3)); }\n\tinline int64_t get__ticks_3() const { return ____ticks_3; }\n\tinline int64_t* get_address_of__ticks_3() { return &____ticks_3; }\n\tinline void set__ticks_3(int64_t value)\n\t{\n\t\t____ticks_3 = value;\n\t}\n};\n\nstruct TimeSpan_t3430258949_StaticFields\n{\npublic:\n\t\/\/ System.TimeSpan System.TimeSpan::Zero\n\tTimeSpan_t3430258949  ___Zero_0;\n\t\/\/ System.TimeSpan System.TimeSpan::MaxValue\n\tTimeSpan_t3430258949  ___MaxValue_1;\n\t\/\/ System.TimeSpan System.TimeSpan::MinValue\n\tTimeSpan_t3430258949  ___MinValue_2;\n\t\/\/ System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.TimeSpan::_legacyConfigChecked\n\tbool ____legacyConfigChecked_4;\n\t\/\/ System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.TimeSpan::_legacyMode\n\tbool ____legacyMode_5;\n\npublic:\n\tinline static int32_t get_offset_of_Zero_0() { return static_cast<int32_t>(offsetof(TimeSpan_t3430258949_StaticFields, ___Zero_0)); }\n\tinline TimeSpan_t3430258949  get_Zero_0() const { return ___Zero_0; }\n\tinline TimeSpan_t3430258949 * get_address_of_Zero_0() { return &___Zero_0; }\n\tinline void set_Zero_0(TimeSpan_t3430258949  value)\n\t{\n\t\t___Zero_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_MaxValue_1() { return static_cast<int32_t>(offsetof(TimeSpan_t3430258949_StaticFields, ___MaxValue_1)); }\n\tinline TimeSpan_t3430258949  get_MaxValue_1() const { return ___MaxValue_1; }\n\tinline TimeSpan_t3430258949 * get_address_of_MaxValue_1() { return &___MaxValue_1; }\n\tinline void set_MaxValue_1(TimeSpan_t3430258949  value)\n\t{\n\t\t___MaxValue_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_MinValue_2() { return static_cast<int32_t>(offsetof(TimeSpan_t3430258949_StaticFields, ___MinValue_2)); }\n\tinline TimeSpan_t3430258949  get_MinValue_2() const { return ___MinValue_2; }\n\tinline TimeSpan_t3430258949 * get_address_of_MinValue_2() { return &___MinValue_2; }\n\tinline void set_MinValue_2(TimeSpan_t3430258949  value)\n\t{\n\t\t___MinValue_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of__legacyConfigChecked_4() { return static_cast<int32_t>(offsetof(TimeSpan_t3430258949_StaticFields, ____legacyConfigChecked_4)); }\n\tinline bool get__legacyConfigChecked_4() const { return ____legacyConfigChecked_4; }\n\tinline bool* get_address_of__legacyConfigChecked_4() { return &____legacyConfigChecked_4; }\n\tinline void set__legacyConfigChecked_4(bool value)\n\t{\n\t\t____legacyConfigChecked_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of__legacyMode_5() { return static_cast<int32_t>(offsetof(TimeSpan_t3430258949_StaticFields, ____legacyMode_5)); }\n\tinline bool get__legacyMode_5() const { return ____legacyMode_5; }\n\tinline bool* get_address_of__legacyMode_5() { return &____legacyMode_5; }\n\tinline void set__legacyMode_5(bool value)\n\t{\n\t\t____legacyMode_5 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ TIMESPAN_T3430258949_H\n#ifndef ASYNCRESULT_T2232356043_H\n#define ASYNCRESULT_T2232356043_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.AsyncResult\nstruct  AsyncResult_t2232356043  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Object System.Runtime.Remoting.Messaging.AsyncResult::async_state\n\tRuntimeObject * ___async_state_0;\n\t\/\/ System.Threading.WaitHandle System.Runtime.Remoting.Messaging.AsyncResult::handle\n\tWaitHandle_t677569169 * ___handle_1;\n\t\/\/ System.Object System.Runtime.Remoting.Messaging.AsyncResult::async_delegate\n\tRuntimeObject * ___async_delegate_2;\n\t\/\/ System.IntPtr System.Runtime.Remoting.Messaging.AsyncResult::data\n\tintptr_t ___data_3;\n\t\/\/ System.Object System.Runtime.Remoting.Messaging.AsyncResult::object_data\n\tRuntimeObject * ___object_data_4;\n\t\/\/ System.Boolean System.Runtime.Remoting.Messaging.AsyncResult::sync_completed\n\tbool ___sync_completed_5;\n\t\/\/ System.Boolean System.Runtime.Remoting.Messaging.AsyncResult::completed\n\tbool ___completed_6;\n\t\/\/ System.Boolean System.Runtime.Remoting.Messaging.AsyncResult::endinvoke_called\n\tbool ___endinvoke_called_7;\n\t\/\/ System.Object System.Runtime.Remoting.Messaging.AsyncResult::async_callback\n\tRuntimeObject * ___async_callback_8;\n\t\/\/ System.Threading.ExecutionContext System.Runtime.Remoting.Messaging.AsyncResult::current\n\tExecutionContext_t1392266323 * ___current_9;\n\t\/\/ System.Threading.ExecutionContext System.Runtime.Remoting.Messaging.AsyncResult::original\n\tExecutionContext_t1392266323 * ___original_10;\n\t\/\/ System.Int64 System.Runtime.Remoting.Messaging.AsyncResult::add_time\n\tint64_t ___add_time_11;\n\t\/\/ System.Runtime.Remoting.Messaging.MonoMethodMessage System.Runtime.Remoting.Messaging.AsyncResult::call_message\n\tMonoMethodMessage_t771543475 * ___call_message_12;\n\t\/\/ System.Runtime.Remoting.Messaging.IMessageCtrl System.Runtime.Remoting.Messaging.AsyncResult::message_ctrl\n\tRuntimeObject* ___message_ctrl_13;\n\t\/\/ System.Runtime.Remoting.Messaging.IMessage System.Runtime.Remoting.Messaging.AsyncResult::reply_message\n\tRuntimeObject* ___reply_message_14;\n\t\/\/ System.Threading.WaitCallback System.Runtime.Remoting.Messaging.AsyncResult::orig_cb\n\tWaitCallback_t2798937288 * ___orig_cb_15;\n\npublic:\n\tinline static int32_t get_offset_of_async_state_0() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___async_state_0)); }\n\tinline RuntimeObject * get_async_state_0() const { return ___async_state_0; }\n\tinline RuntimeObject ** get_address_of_async_state_0() { return &___async_state_0; }\n\tinline void set_async_state_0(RuntimeObject * value)\n\t{\n\t\t___async_state_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___async_state_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_handle_1() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___handle_1)); }\n\tinline WaitHandle_t677569169 * get_handle_1() const { return ___handle_1; }\n\tinline WaitHandle_t677569169 ** get_address_of_handle_1() { return &___handle_1; }\n\tinline void set_handle_1(WaitHandle_t677569169 * value)\n\t{\n\t\t___handle_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___handle_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_async_delegate_2() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___async_delegate_2)); }\n\tinline RuntimeObject * get_async_delegate_2() const { return ___async_delegate_2; }\n\tinline RuntimeObject ** get_address_of_async_delegate_2() { return &___async_delegate_2; }\n\tinline void set_async_delegate_2(RuntimeObject * value)\n\t{\n\t\t___async_delegate_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___async_delegate_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_data_3() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___data_3)); }\n\tinline intptr_t get_data_3() const { return ___data_3; }\n\tinline intptr_t* get_address_of_data_3() { return &___data_3; }\n\tinline void set_data_3(intptr_t value)\n\t{\n\t\t___data_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_object_data_4() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___object_data_4)); }\n\tinline RuntimeObject * get_object_data_4() const { return ___object_data_4; }\n\tinline RuntimeObject ** get_address_of_object_data_4() { return &___object_data_4; }\n\tinline void set_object_data_4(RuntimeObject * value)\n\t{\n\t\t___object_data_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___object_data_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_sync_completed_5() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___sync_completed_5)); }\n\tinline bool get_sync_completed_5() const { return ___sync_completed_5; }\n\tinline bool* get_address_of_sync_completed_5() { return &___sync_completed_5; }\n\tinline void set_sync_completed_5(bool value)\n\t{\n\t\t___sync_completed_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of_completed_6() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___completed_6)); }\n\tinline bool get_completed_6() const { return ___completed_6; }\n\tinline bool* get_address_of_completed_6() { return &___completed_6; }\n\tinline void set_completed_6(bool value)\n\t{\n\t\t___completed_6 = value;\n\t}\n\n\tinline static int32_t get_offset_of_endinvoke_called_7() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___endinvoke_called_7)); }\n\tinline bool get_endinvoke_called_7() const { return ___endinvoke_called_7; }\n\tinline bool* get_address_of_endinvoke_called_7() { return &___endinvoke_called_7; }\n\tinline void set_endinvoke_called_7(bool value)\n\t{\n\t\t___endinvoke_called_7 = value;\n\t}\n\n\tinline static int32_t get_offset_of_async_callback_8() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___async_callback_8)); }\n\tinline RuntimeObject * get_async_callback_8() const { return ___async_callback_8; }\n\tinline RuntimeObject ** get_address_of_async_callback_8() { return &___async_callback_8; }\n\tinline void set_async_callback_8(RuntimeObject * value)\n\t{\n\t\t___async_callback_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___async_callback_8), value);\n\t}\n\n\tinline static int32_t get_offset_of_current_9() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___current_9)); }\n\tinline ExecutionContext_t1392266323 * get_current_9() const { return ___current_9; }\n\tinline ExecutionContext_t1392266323 ** get_address_of_current_9() { return &___current_9; }\n\tinline void set_current_9(ExecutionContext_t1392266323 * value)\n\t{\n\t\t___current_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___current_9), value);\n\t}\n\n\tinline static int32_t get_offset_of_original_10() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___original_10)); }\n\tinline ExecutionContext_t1392266323 * get_original_10() const { return ___original_10; }\n\tinline ExecutionContext_t1392266323 ** get_address_of_original_10() { return &___original_10; }\n\tinline void set_original_10(ExecutionContext_t1392266323 * value)\n\t{\n\t\t___original_10 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___original_10), value);\n\t}\n\n\tinline static int32_t get_offset_of_add_time_11() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___add_time_11)); }\n\tinline int64_t get_add_time_11() const { return ___add_time_11; }\n\tinline int64_t* get_address_of_add_time_11() { return &___add_time_11; }\n\tinline void set_add_time_11(int64_t value)\n\t{\n\t\t___add_time_11 = value;\n\t}\n\n\tinline static int32_t get_offset_of_call_message_12() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___call_message_12)); }\n\tinline MonoMethodMessage_t771543475 * get_call_message_12() const { return ___call_message_12; }\n\tinline MonoMethodMessage_t771543475 ** get_address_of_call_message_12() { return &___call_message_12; }\n\tinline void set_call_message_12(MonoMethodMessage_t771543475 * value)\n\t{\n\t\t___call_message_12 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___call_message_12), value);\n\t}\n\n\tinline static int32_t get_offset_of_message_ctrl_13() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___message_ctrl_13)); }\n\tinline RuntimeObject* get_message_ctrl_13() const { return ___message_ctrl_13; }\n\tinline RuntimeObject** get_address_of_message_ctrl_13() { return &___message_ctrl_13; }\n\tinline void set_message_ctrl_13(RuntimeObject* value)\n\t{\n\t\t___message_ctrl_13 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___message_ctrl_13), value);\n\t}\n\n\tinline static int32_t get_offset_of_reply_message_14() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___reply_message_14)); }\n\tinline RuntimeObject* get_reply_message_14() const { return ___reply_message_14; }\n\tinline RuntimeObject** get_address_of_reply_message_14() { return &___reply_message_14; }\n\tinline void set_reply_message_14(RuntimeObject* value)\n\t{\n\t\t___reply_message_14 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___reply_message_14), value);\n\t}\n\n\tinline static int32_t get_offset_of_orig_cb_15() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043, ___orig_cb_15)); }\n\tinline WaitCallback_t2798937288 * get_orig_cb_15() const { return ___orig_cb_15; }\n\tinline WaitCallback_t2798937288 ** get_address_of_orig_cb_15() { return &___orig_cb_15; }\n\tinline void set_orig_cb_15(WaitCallback_t2798937288 * value)\n\t{\n\t\t___orig_cb_15 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___orig_cb_15), value);\n\t}\n};\n\nstruct AsyncResult_t2232356043_StaticFields\n{\npublic:\n\t\/\/ System.Threading.ContextCallback System.Runtime.Remoting.Messaging.AsyncResult::ccb\n\tContextCallback_t2287130692 * ___ccb_16;\n\npublic:\n\tinline static int32_t get_offset_of_ccb_16() { return static_cast<int32_t>(offsetof(AsyncResult_t2232356043_StaticFields, ___ccb_16)); }\n\tinline ContextCallback_t2287130692 * get_ccb_16() const { return ___ccb_16; }\n\tinline ContextCallback_t2287130692 ** get_address_of_ccb_16() { return &___ccb_16; }\n\tinline void set_ccb_16(ContextCallback_t2287130692 * value)\n\t{\n\t\t___ccb_16 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___ccb_16), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.Runtime.Remoting.Messaging.AsyncResult\nstruct AsyncResult_t2232356043_marshaled_pinvoke\n{\n\tIl2CppIUnknown* ___async_state_0;\n\tWaitHandle_t677569169_marshaled_pinvoke* ___handle_1;\n\tIl2CppIUnknown* ___async_delegate_2;\n\tintptr_t ___data_3;\n\tIl2CppIUnknown* ___object_data_4;\n\tint32_t ___sync_completed_5;\n\tint32_t ___completed_6;\n\tint32_t ___endinvoke_called_7;\n\tIl2CppIUnknown* ___async_callback_8;\n\tExecutionContext_t1392266323 * ___current_9;\n\tExecutionContext_t1392266323 * ___original_10;\n\tint64_t ___add_time_11;\n\tMonoMethodMessage_t771543475_marshaled_pinvoke* ___call_message_12;\n\tRuntimeObject* ___message_ctrl_13;\n\tRuntimeObject* ___reply_message_14;\n\tIl2CppMethodPointer ___orig_cb_15;\n};\n\/\/ Native definition for COM marshalling of System.Runtime.Remoting.Messaging.AsyncResult\nstruct AsyncResult_t2232356043_marshaled_com\n{\n\tIl2CppIUnknown* ___async_state_0;\n\tWaitHandle_t677569169_marshaled_com* ___handle_1;\n\tIl2CppIUnknown* ___async_delegate_2;\n\tintptr_t ___data_3;\n\tIl2CppIUnknown* ___object_data_4;\n\tint32_t ___sync_completed_5;\n\tint32_t ___completed_6;\n\tint32_t ___endinvoke_called_7;\n\tIl2CppIUnknown* ___async_callback_8;\n\tExecutionContext_t1392266323 * ___current_9;\n\tExecutionContext_t1392266323 * ___original_10;\n\tint64_t ___add_time_11;\n\tMonoMethodMessage_t771543475_marshaled_com* ___call_message_12;\n\tRuntimeObject* ___message_ctrl_13;\n\tRuntimeObject* ___reply_message_14;\n\tIl2CppMethodPointer ___orig_cb_15;\n};\n#endif \/\/ ASYNCRESULT_T2232356043_H\n#ifndef CONTEXTCALLBACKOBJECT_T3978189709_H\n#define CONTEXTCALLBACKOBJECT_T3978189709_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Contexts.ContextCallbackObject\nstruct  ContextCallbackObject_t3978189709  : public ContextBoundObject_t4264702438\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CONTEXTCALLBACKOBJECT_T3978189709_H\n#ifndef CONTEXT_T502196753_H\n#define CONTEXT_T502196753_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Contexts.Context\nstruct  Context_t502196753  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Int32 System.Runtime.Remoting.Contexts.Context::domain_id\n\tint32_t ___domain_id_0;\n\t\/\/ System.Int32 System.Runtime.Remoting.Contexts.Context::context_id\n\tint32_t ___context_id_1;\n\t\/\/ System.UIntPtr System.Runtime.Remoting.Contexts.Context::static_data\n\tuintptr_t ___static_data_2;\n\t\/\/ System.UIntPtr System.Runtime.Remoting.Contexts.Context::data\n\tuintptr_t ___data_3;\n\t\/\/ System.Runtime.Remoting.Messaging.IMessageSink System.Runtime.Remoting.Contexts.Context::server_context_sink_chain\n\tRuntimeObject* ___server_context_sink_chain_6;\n\t\/\/ System.Runtime.Remoting.Messaging.IMessageSink System.Runtime.Remoting.Contexts.Context::client_context_sink_chain\n\tRuntimeObject* ___client_context_sink_chain_7;\n\t\/\/ System.Collections.Generic.List`1<System.Runtime.Remoting.Contexts.IContextProperty> System.Runtime.Remoting.Contexts.Context::context_properties\n\tList_1_t3951334827 * ___context_properties_8;\n\t\/\/ System.LocalDataStoreHolder modreq(System.Runtime.CompilerServices.IsVolatile) System.Runtime.Remoting.Contexts.Context::_localDataStore\n\tLocalDataStoreHolder_t2240136856 * ____localDataStore_10;\n\t\/\/ System.Runtime.Remoting.Contexts.DynamicPropertyCollection System.Runtime.Remoting.Contexts.Context::context_dynamic_properties\n\tDynamicPropertyCollection_t2282532998 * ___context_dynamic_properties_13;\n\t\/\/ System.Runtime.Remoting.Contexts.ContextCallbackObject System.Runtime.Remoting.Contexts.Context::callback_object\n\tContextCallbackObject_t3978189709 * ___callback_object_14;\n\npublic:\n\tinline static int32_t get_offset_of_domain_id_0() { return static_cast<int32_t>(offsetof(Context_t502196753, ___domain_id_0)); }\n\tinline int32_t get_domain_id_0() const { return ___domain_id_0; }\n\tinline int32_t* get_address_of_domain_id_0() { return &___domain_id_0; }\n\tinline void set_domain_id_0(int32_t value)\n\t{\n\t\t___domain_id_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_context_id_1() { return static_cast<int32_t>(offsetof(Context_t502196753, ___context_id_1)); }\n\tinline int32_t get_context_id_1() const { return ___context_id_1; }\n\tinline int32_t* get_address_of_context_id_1() { return &___context_id_1; }\n\tinline void set_context_id_1(int32_t value)\n\t{\n\t\t___context_id_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_static_data_2() { return static_cast<int32_t>(offsetof(Context_t502196753, ___static_data_2)); }\n\tinline uintptr_t get_static_data_2() const { return ___static_data_2; }\n\tinline uintptr_t* get_address_of_static_data_2() { return &___static_data_2; }\n\tinline void set_static_data_2(uintptr_t value)\n\t{\n\t\t___static_data_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_data_3() { return static_cast<int32_t>(offsetof(Context_t502196753, ___data_3)); }\n\tinline uintptr_t get_data_3() const { return ___data_3; }\n\tinline uintptr_t* get_address_of_data_3() { return &___data_3; }\n\tinline void set_data_3(uintptr_t value)\n\t{\n\t\t___data_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_server_context_sink_chain_6() { return static_cast<int32_t>(offsetof(Context_t502196753, ___server_context_sink_chain_6)); }\n\tinline RuntimeObject* get_server_context_sink_chain_6() const { return ___server_context_sink_chain_6; }\n\tinline RuntimeObject** get_address_of_server_context_sink_chain_6() { return &___server_context_sink_chain_6; }\n\tinline void set_server_context_sink_chain_6(RuntimeObject* value)\n\t{\n\t\t___server_context_sink_chain_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___server_context_sink_chain_6), value);\n\t}\n\n\tinline static int32_t get_offset_of_client_context_sink_chain_7() { return static_cast<int32_t>(offsetof(Context_t502196753, ___client_context_sink_chain_7)); }\n\tinline RuntimeObject* get_client_context_sink_chain_7() const { return ___client_context_sink_chain_7; }\n\tinline RuntimeObject** get_address_of_client_context_sink_chain_7() { return &___client_context_sink_chain_7; }\n\tinline void set_client_context_sink_chain_7(RuntimeObject* value)\n\t{\n\t\t___client_context_sink_chain_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___client_context_sink_chain_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_context_properties_8() { return static_cast<int32_t>(offsetof(Context_t502196753, ___context_properties_8)); }\n\tinline List_1_t3951334827 * get_context_properties_8() const { return ___context_properties_8; }\n\tinline List_1_t3951334827 ** get_address_of_context_properties_8() { return &___context_properties_8; }\n\tinline void set_context_properties_8(List_1_t3951334827 * value)\n\t{\n\t\t___context_properties_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___context_properties_8), value);\n\t}\n\n\tinline static int32_t get_offset_of__localDataStore_10() { return static_cast<int32_t>(offsetof(Context_t502196753, ____localDataStore_10)); }\n\tinline LocalDataStoreHolder_t2240136856 * get__localDataStore_10() const { return ____localDataStore_10; }\n\tinline LocalDataStoreHolder_t2240136856 ** get_address_of__localDataStore_10() { return &____localDataStore_10; }\n\tinline void set__localDataStore_10(LocalDataStoreHolder_t2240136856 * value)\n\t{\n\t\t____localDataStore_10 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____localDataStore_10), value);\n\t}\n\n\tinline static int32_t get_offset_of_context_dynamic_properties_13() { return static_cast<int32_t>(offsetof(Context_t502196753, ___context_dynamic_properties_13)); }\n\tinline DynamicPropertyCollection_t2282532998 * get_context_dynamic_properties_13() const { return ___context_dynamic_properties_13; }\n\tinline DynamicPropertyCollection_t2282532998 ** get_address_of_context_dynamic_properties_13() { return &___context_dynamic_properties_13; }\n\tinline void set_context_dynamic_properties_13(DynamicPropertyCollection_t2282532998 * value)\n\t{\n\t\t___context_dynamic_properties_13 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___context_dynamic_properties_13), value);\n\t}\n\n\tinline static int32_t get_offset_of_callback_object_14() { return static_cast<int32_t>(offsetof(Context_t502196753, ___callback_object_14)); }\n\tinline ContextCallbackObject_t3978189709 * get_callback_object_14() const { return ___callback_object_14; }\n\tinline ContextCallbackObject_t3978189709 ** get_address_of_callback_object_14() { return &___callback_object_14; }\n\tinline void set_callback_object_14(ContextCallbackObject_t3978189709 * value)\n\t{\n\t\t___callback_object_14 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___callback_object_14), value);\n\t}\n};\n\nstruct Context_t502196753_StaticFields\n{\npublic:\n\t\/\/ System.Object[] System.Runtime.Remoting.Contexts.Context::local_slots\n\tObjectU5BU5D_t3614634134* ___local_slots_4;\n\t\/\/ System.Runtime.Remoting.Messaging.IMessageSink System.Runtime.Remoting.Contexts.Context::default_server_context_sink\n\tRuntimeObject* ___default_server_context_sink_5;\n\t\/\/ System.Int32 System.Runtime.Remoting.Contexts.Context::global_count\n\tint32_t ___global_count_9;\n\t\/\/ System.LocalDataStoreMgr System.Runtime.Remoting.Contexts.Context::_localDataStoreMgr\n\tLocalDataStoreMgr_t1152954092 * ____localDataStoreMgr_11;\n\t\/\/ System.Runtime.Remoting.Contexts.DynamicPropertyCollection System.Runtime.Remoting.Contexts.Context::global_dynamic_properties\n\tDynamicPropertyCollection_t2282532998 * ___global_dynamic_properties_12;\n\npublic:\n\tinline static int32_t get_offset_of_local_slots_4() { return static_cast<int32_t>(offsetof(Context_t502196753_StaticFields, ___local_slots_4)); }\n\tinline ObjectU5BU5D_t3614634134* get_local_slots_4() const { return ___local_slots_4; }\n\tinline ObjectU5BU5D_t3614634134** get_address_of_local_slots_4() { return &___local_slots_4; }\n\tinline void set_local_slots_4(ObjectU5BU5D_t3614634134* value)\n\t{\n\t\t___local_slots_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___local_slots_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_default_server_context_sink_5() { return static_cast<int32_t>(offsetof(Context_t502196753_StaticFields, ___default_server_context_sink_5)); }\n\tinline RuntimeObject* get_default_server_context_sink_5() const { return ___default_server_context_sink_5; }\n\tinline RuntimeObject** get_address_of_default_server_context_sink_5() { return &___default_server_context_sink_5; }\n\tinline void set_default_server_context_sink_5(RuntimeObject* value)\n\t{\n\t\t___default_server_context_sink_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___default_server_context_sink_5), value);\n\t}\n\n\tinline static int32_t get_offset_of_global_count_9() { return static_cast<int32_t>(offsetof(Context_t502196753_StaticFields, ___global_count_9)); }\n\tinline int32_t get_global_count_9() const { return ___global_count_9; }\n\tinline int32_t* get_address_of_global_count_9() { return &___global_count_9; }\n\tinline void set_global_count_9(int32_t value)\n\t{\n\t\t___global_count_9 = value;\n\t}\n\n\tinline static int32_t get_offset_of__localDataStoreMgr_11() { return static_cast<int32_t>(offsetof(Context_t502196753_StaticFields, ____localDataStoreMgr_11)); }\n\tinline LocalDataStoreMgr_t1152954092 * get__localDataStoreMgr_11() const { return ____localDataStoreMgr_11; }\n\tinline LocalDataStoreMgr_t1152954092 ** get_address_of__localDataStoreMgr_11() { return &____localDataStoreMgr_11; }\n\tinline void set__localDataStoreMgr_11(LocalDataStoreMgr_t1152954092 * value)\n\t{\n\t\t____localDataStoreMgr_11 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____localDataStoreMgr_11), value);\n\t}\n\n\tinline static int32_t get_offset_of_global_dynamic_properties_12() { return static_cast<int32_t>(offsetof(Context_t502196753_StaticFields, ___global_dynamic_properties_12)); }\n\tinline DynamicPropertyCollection_t2282532998 * get_global_dynamic_properties_12() const { return ___global_dynamic_properties_12; }\n\tinline DynamicPropertyCollection_t2282532998 ** get_address_of_global_dynamic_properties_12() { return &___global_dynamic_properties_12; }\n\tinline void set_global_dynamic_properties_12(DynamicPropertyCollection_t2282532998 * value)\n\t{\n\t\t___global_dynamic_properties_12 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___global_dynamic_properties_12), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.Runtime.Remoting.Contexts.Context\nstruct Context_t502196753_marshaled_pinvoke\n{\n\tint32_t ___domain_id_0;\n\tint32_t ___context_id_1;\n\tuintptr_t ___static_data_2;\n\tuintptr_t ___data_3;\n\tRuntimeObject* ___server_context_sink_chain_6;\n\tRuntimeObject* ___client_context_sink_chain_7;\n\tList_1_t3951334827 * ___context_properties_8;\n\tLocalDataStoreHolder_t2240136856 * ____localDataStore_10;\n\tDynamicPropertyCollection_t2282532998 * ___context_dynamic_properties_13;\n\tContextCallbackObject_t3978189709 * ___callback_object_14;\n};\n\/\/ Native definition for COM marshalling of System.Runtime.Remoting.Contexts.Context\nstruct Context_t502196753_marshaled_com\n{\n\tint32_t ___domain_id_0;\n\tint32_t ___context_id_1;\n\tuintptr_t ___static_data_2;\n\tuintptr_t ___data_3;\n\tRuntimeObject* ___server_context_sink_chain_6;\n\tRuntimeObject* ___client_context_sink_chain_7;\n\tList_1_t3951334827 * ___context_properties_8;\n\tLocalDataStoreHolder_t2240136856 * ____localDataStore_10;\n\tDynamicPropertyCollection_t2282532998 * ___context_dynamic_properties_13;\n\tContextCallbackObject_t3978189709 * ___callback_object_14;\n};\n#endif \/\/ CONTEXT_T502196753_H\n#ifndef LEASESTATE_T83447469_H\n#define LEASESTATE_T83447469_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Lifetime.LeaseState\nstruct  LeaseState_t83447469 \n{\npublic:\n\t\/\/ System.Int32 System.Runtime.Remoting.Lifetime.LeaseState::value__\n\tint32_t ___value___2;\n\npublic:\n\tinline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(LeaseState_t83447469, ___value___2)); }\n\tinline int32_t get_value___2() const { return ___value___2; }\n\tinline int32_t* get_address_of_value___2() { return &___value___2; }\n\tinline void set_value___2(int32_t value)\n\t{\n\t\t___value___2 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ LEASESTATE_T83447469_H\n#ifndef CALLTYPE_T2486906258_H\n#define CALLTYPE_T2486906258_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.CallType\nstruct  CallType_t2486906258 \n{\npublic:\n\t\/\/ System.Int32 System.Runtime.Remoting.Messaging.CallType::value__\n\tint32_t ___value___2;\n\npublic:\n\tinline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(CallType_t2486906258, ___value___2)); }\n\tinline int32_t get_value___2() const { return ___value___2; }\n\tinline int32_t* get_address_of_value___2() { return &___value___2; }\n\tinline void set_value___2(int32_t value)\n\t{\n\t\t___value___2 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CALLTYPE_T2486906258_H\n#ifndef URLATTRIBUTE_T1544437301_H\n#define URLATTRIBUTE_T1544437301_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Activation.UrlAttribute\nstruct  UrlAttribute_t1544437301  : public ContextAttribute_t197102333\n{\npublic:\n\t\/\/ System.String System.Runtime.Remoting.Activation.UrlAttribute::url\n\tString_t* ___url_1;\n\npublic:\n\tinline static int32_t get_offset_of_url_1() { return static_cast<int32_t>(offsetof(UrlAttribute_t1544437301, ___url_1)); }\n\tinline String_t* get_url_1() const { return ___url_1; }\n\tinline String_t** get_address_of_url_1() { return &___url_1; }\n\tinline void set_url_1(String_t* value)\n\t{\n\t\t___url_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___url_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ URLATTRIBUTE_T1544437301_H\n#ifndef SYNCHRONIZATIONATTRIBUTE_T3073724998_H\n#define SYNCHRONIZATIONATTRIBUTE_T3073724998_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Contexts.SynchronizationAttribute\nstruct  SynchronizationAttribute_t3073724998  : public ContextAttribute_t197102333\n{\npublic:\n\t\/\/ System.Boolean System.Runtime.Remoting.Contexts.SynchronizationAttribute::_bReEntrant\n\tbool ____bReEntrant_1;\n\t\/\/ System.Int32 System.Runtime.Remoting.Contexts.SynchronizationAttribute::_flavor\n\tint32_t ____flavor_2;\n\t\/\/ System.Int32 System.Runtime.Remoting.Contexts.SynchronizationAttribute::_lockCount\n\tint32_t ____lockCount_3;\n\t\/\/ System.Threading.Mutex System.Runtime.Remoting.Contexts.SynchronizationAttribute::_mutex\n\tMutex_t297030111 * ____mutex_4;\n\t\/\/ System.Threading.Thread System.Runtime.Remoting.Contexts.SynchronizationAttribute::_ownerThread\n\tThread_t241561612 * ____ownerThread_5;\n\npublic:\n\tinline static int32_t get_offset_of__bReEntrant_1() { return static_cast<int32_t>(offsetof(SynchronizationAttribute_t3073724998, ____bReEntrant_1)); }\n\tinline bool get__bReEntrant_1() const { return ____bReEntrant_1; }\n\tinline bool* get_address_of__bReEntrant_1() { return &____bReEntrant_1; }\n\tinline void set__bReEntrant_1(bool value)\n\t{\n\t\t____bReEntrant_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of__flavor_2() { return static_cast<int32_t>(offsetof(SynchronizationAttribute_t3073724998, ____flavor_2)); }\n\tinline int32_t get__flavor_2() const { return ____flavor_2; }\n\tinline int32_t* get_address_of__flavor_2() { return &____flavor_2; }\n\tinline void set__flavor_2(int32_t value)\n\t{\n\t\t____flavor_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of__lockCount_3() { return static_cast<int32_t>(offsetof(SynchronizationAttribute_t3073724998, ____lockCount_3)); }\n\tinline int32_t get__lockCount_3() const { return ____lockCount_3; }\n\tinline int32_t* get_address_of__lockCount_3() { return &____lockCount_3; }\n\tinline void set__lockCount_3(int32_t value)\n\t{\n\t\t____lockCount_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of__mutex_4() { return static_cast<int32_t>(offsetof(SynchronizationAttribute_t3073724998, ____mutex_4)); }\n\tinline Mutex_t297030111 * get__mutex_4() const { return ____mutex_4; }\n\tinline Mutex_t297030111 ** get_address_of__mutex_4() { return &____mutex_4; }\n\tinline void set__mutex_4(Mutex_t297030111 * value)\n\t{\n\t\t____mutex_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____mutex_4), value);\n\t}\n\n\tinline static int32_t get_offset_of__ownerThread_5() { return static_cast<int32_t>(offsetof(SynchronizationAttribute_t3073724998, ____ownerThread_5)); }\n\tinline Thread_t241561612 * get__ownerThread_5() const { return ____ownerThread_5; }\n\tinline Thread_t241561612 ** get_address_of__ownerThread_5() { return &____ownerThread_5; }\n\tinline void set__ownerThread_5(Thread_t241561612 * value)\n\t{\n\t\t____ownerThread_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____ownerThread_5), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SYNCHRONIZATIONATTRIBUTE_T3073724998_H\n#ifndef MONOMETHODMESSAGE_T771543475_H\n#define MONOMETHODMESSAGE_T771543475_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.MonoMethodMessage\nstruct  MonoMethodMessage_t771543475  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Reflection.MonoMethod System.Runtime.Remoting.Messaging.MonoMethodMessage::method\n\tMonoMethod_t * ___method_0;\n\t\/\/ System.Object[] System.Runtime.Remoting.Messaging.MonoMethodMessage::args\n\tObjectU5BU5D_t3614634134* ___args_1;\n\t\/\/ System.String[] System.Runtime.Remoting.Messaging.MonoMethodMessage::names\n\tStringU5BU5D_t1642385972* ___names_2;\n\t\/\/ System.Byte[] System.Runtime.Remoting.Messaging.MonoMethodMessage::arg_types\n\tByteU5BU5D_t3397334013* ___arg_types_3;\n\t\/\/ System.Runtime.Remoting.Messaging.LogicalCallContext System.Runtime.Remoting.Messaging.MonoMethodMessage::ctx\n\tLogicalCallContext_t725724420 * ___ctx_4;\n\t\/\/ System.Object System.Runtime.Remoting.Messaging.MonoMethodMessage::rval\n\tRuntimeObject * ___rval_5;\n\t\/\/ System.Exception System.Runtime.Remoting.Messaging.MonoMethodMessage::exc\n\tException_t1927440687 * ___exc_6;\n\t\/\/ System.Runtime.Remoting.Messaging.AsyncResult System.Runtime.Remoting.Messaging.MonoMethodMessage::asyncResult\n\tAsyncResult_t2232356043 * ___asyncResult_7;\n\t\/\/ System.Runtime.Remoting.Messaging.CallType System.Runtime.Remoting.Messaging.MonoMethodMessage::call_type\n\tint32_t ___call_type_8;\n\t\/\/ System.String System.Runtime.Remoting.Messaging.MonoMethodMessage::uri\n\tString_t* ___uri_9;\n\t\/\/ System.Runtime.Remoting.Messaging.MCMDictionary System.Runtime.Remoting.Messaging.MonoMethodMessage::properties\n\tMCMDictionary_t159052147 * ___properties_10;\n\t\/\/ System.Type[] System.Runtime.Remoting.Messaging.MonoMethodMessage::methodSignature\n\tTypeU5BU5D_t1664964607* ___methodSignature_11;\n\t\/\/ System.Runtime.Remoting.Identity System.Runtime.Remoting.Messaging.MonoMethodMessage::identity\n\tIdentity_t3647548000 * ___identity_12;\n\npublic:\n\tinline static int32_t get_offset_of_method_0() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475, ___method_0)); }\n\tinline MonoMethod_t * get_method_0() const { return ___method_0; }\n\tinline MonoMethod_t ** get_address_of_method_0() { return &___method_0; }\n\tinline void set_method_0(MonoMethod_t * value)\n\t{\n\t\t___method_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___method_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_args_1() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475, ___args_1)); }\n\tinline ObjectU5BU5D_t3614634134* get_args_1() const { return ___args_1; }\n\tinline ObjectU5BU5D_t3614634134** get_address_of_args_1() { return &___args_1; }\n\tinline void set_args_1(ObjectU5BU5D_t3614634134* value)\n\t{\n\t\t___args_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___args_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_names_2() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475, ___names_2)); }\n\tinline StringU5BU5D_t1642385972* get_names_2() const { return ___names_2; }\n\tinline StringU5BU5D_t1642385972** get_address_of_names_2() { return &___names_2; }\n\tinline void set_names_2(StringU5BU5D_t1642385972* value)\n\t{\n\t\t___names_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___names_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_arg_types_3() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475, ___arg_types_3)); }\n\tinline ByteU5BU5D_t3397334013* get_arg_types_3() const { return ___arg_types_3; }\n\tinline ByteU5BU5D_t3397334013** get_address_of_arg_types_3() { return &___arg_types_3; }\n\tinline void set_arg_types_3(ByteU5BU5D_t3397334013* value)\n\t{\n\t\t___arg_types_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___arg_types_3), value);\n\t}\n\n\tinline static int32_t get_offset_of_ctx_4() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475, ___ctx_4)); }\n\tinline LogicalCallContext_t725724420 * get_ctx_4() const { return ___ctx_4; }\n\tinline LogicalCallContext_t725724420 ** get_address_of_ctx_4() { return &___ctx_4; }\n\tinline void set_ctx_4(LogicalCallContext_t725724420 * value)\n\t{\n\t\t___ctx_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___ctx_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_rval_5() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475, ___rval_5)); }\n\tinline RuntimeObject * get_rval_5() const { return ___rval_5; }\n\tinline RuntimeObject ** get_address_of_rval_5() { return &___rval_5; }\n\tinline void set_rval_5(RuntimeObject * value)\n\t{\n\t\t___rval_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___rval_5), value);\n\t}\n\n\tinline static int32_t get_offset_of_exc_6() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475, ___exc_6)); }\n\tinline Exception_t1927440687 * get_exc_6() const { return ___exc_6; }\n\tinline Exception_t1927440687 ** get_address_of_exc_6() { return &___exc_6; }\n\tinline void set_exc_6(Exception_t1927440687 * value)\n\t{\n\t\t___exc_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___exc_6), value);\n\t}\n\n\tinline static int32_t get_offset_of_asyncResult_7() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475, ___asyncResult_7)); }\n\tinline AsyncResult_t2232356043 * get_asyncResult_7() const { return ___asyncResult_7; }\n\tinline AsyncResult_t2232356043 ** get_address_of_asyncResult_7() { return &___asyncResult_7; }\n\tinline void set_asyncResult_7(AsyncResult_t2232356043 * value)\n\t{\n\t\t___asyncResult_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___asyncResult_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_call_type_8() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475, ___call_type_8)); }\n\tinline int32_t get_call_type_8() const { return ___call_type_8; }\n\tinline int32_t* get_address_of_call_type_8() { return &___call_type_8; }\n\tinline void set_call_type_8(int32_t value)\n\t{\n\t\t___call_type_8 = value;\n\t}\n\n\tinline static int32_t get_offset_of_uri_9() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475, ___uri_9)); }\n\tinline String_t* get_uri_9() const { return ___uri_9; }\n\tinline String_t** get_address_of_uri_9() { return &___uri_9; }\n\tinline void set_uri_9(String_t* value)\n\t{\n\t\t___uri_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___uri_9), value);\n\t}\n\n\tinline static int32_t get_offset_of_properties_10() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475, ___properties_10)); }\n\tinline MCMDictionary_t159052147 * get_properties_10() const { return ___properties_10; }\n\tinline MCMDictionary_t159052147 ** get_address_of_properties_10() { return &___properties_10; }\n\tinline void set_properties_10(MCMDictionary_t159052147 * value)\n\t{\n\t\t___properties_10 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___properties_10), value);\n\t}\n\n\tinline static int32_t get_offset_of_methodSignature_11() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475, ___methodSignature_11)); }\n\tinline TypeU5BU5D_t1664964607* get_methodSignature_11() const { return ___methodSignature_11; }\n\tinline TypeU5BU5D_t1664964607** get_address_of_methodSignature_11() { return &___methodSignature_11; }\n\tinline void set_methodSignature_11(TypeU5BU5D_t1664964607* value)\n\t{\n\t\t___methodSignature_11 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___methodSignature_11), value);\n\t}\n\n\tinline static int32_t get_offset_of_identity_12() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475, ___identity_12)); }\n\tinline Identity_t3647548000 * get_identity_12() const { return ___identity_12; }\n\tinline Identity_t3647548000 ** get_address_of_identity_12() { return &___identity_12; }\n\tinline void set_identity_12(Identity_t3647548000 * value)\n\t{\n\t\t___identity_12 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___identity_12), value);\n\t}\n};\n\nstruct MonoMethodMessage_t771543475_StaticFields\n{\npublic:\n\t\/\/ System.String System.Runtime.Remoting.Messaging.MonoMethodMessage::CallContextKey\n\tString_t* ___CallContextKey_13;\n\t\/\/ System.String System.Runtime.Remoting.Messaging.MonoMethodMessage::UriKey\n\tString_t* ___UriKey_14;\n\npublic:\n\tinline static int32_t get_offset_of_CallContextKey_13() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475_StaticFields, ___CallContextKey_13)); }\n\tinline String_t* get_CallContextKey_13() const { return ___CallContextKey_13; }\n\tinline String_t** get_address_of_CallContextKey_13() { return &___CallContextKey_13; }\n\tinline void set_CallContextKey_13(String_t* value)\n\t{\n\t\t___CallContextKey_13 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___CallContextKey_13), value);\n\t}\n\n\tinline static int32_t get_offset_of_UriKey_14() { return static_cast<int32_t>(offsetof(MonoMethodMessage_t771543475_StaticFields, ___UriKey_14)); }\n\tinline String_t* get_UriKey_14() const { return ___UriKey_14; }\n\tinline String_t** get_address_of_UriKey_14() { return &___UriKey_14; }\n\tinline void set_UriKey_14(String_t* value)\n\t{\n\t\t___UriKey_14 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___UriKey_14), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.Runtime.Remoting.Messaging.MonoMethodMessage\nstruct MonoMethodMessage_t771543475_marshaled_pinvoke\n{\n\tMonoMethod_t * ___method_0;\n\tObjectU5BU5D_t3614634134* ___args_1;\n\tchar** ___names_2;\n\tuint8_t* ___arg_types_3;\n\tLogicalCallContext_t725724420 * ___ctx_4;\n\tIl2CppIUnknown* ___rval_5;\n\tException_t1927440687_marshaled_pinvoke* ___exc_6;\n\tAsyncResult_t2232356043_marshaled_pinvoke* ___asyncResult_7;\n\tint32_t ___call_type_8;\n\tchar* ___uri_9;\n\tMCMDictionary_t159052147 * ___properties_10;\n\tTypeU5BU5D_t1664964607* ___methodSignature_11;\n\tIdentity_t3647548000 * ___identity_12;\n};\n\/\/ Native definition for COM marshalling of System.Runtime.Remoting.Messaging.MonoMethodMessage\nstruct MonoMethodMessage_t771543475_marshaled_com\n{\n\tMonoMethod_t * ___method_0;\n\tObjectU5BU5D_t3614634134* ___args_1;\n\tIl2CppChar** ___names_2;\n\tuint8_t* ___arg_types_3;\n\tLogicalCallContext_t725724420 * ___ctx_4;\n\tIl2CppIUnknown* ___rval_5;\n\tException_t1927440687_marshaled_com* ___exc_6;\n\tAsyncResult_t2232356043_marshaled_com* ___asyncResult_7;\n\tint32_t ___call_type_8;\n\tIl2CppChar* ___uri_9;\n\tMCMDictionary_t159052147 * ___properties_10;\n\tTypeU5BU5D_t1664964607* ___methodSignature_11;\n\tIdentity_t3647548000 * ___identity_12;\n};\n#endif \/\/ MONOMETHODMESSAGE_T771543475_H\n#ifndef LEASE_T3663008028_H\n#define LEASE_T3663008028_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Lifetime.Lease\nstruct  Lease_t3663008028  : public MarshalByRefObject_t1285298191\n{\npublic:\n\t\/\/ System.DateTime System.Runtime.Remoting.Lifetime.Lease::_leaseExpireTime\n\tDateTime_t693205669  ____leaseExpireTime_1;\n\t\/\/ System.Runtime.Remoting.Lifetime.LeaseState System.Runtime.Remoting.Lifetime.Lease::_currentState\n\tint32_t ____currentState_2;\n\t\/\/ System.TimeSpan System.Runtime.Remoting.Lifetime.Lease::_initialLeaseTime\n\tTimeSpan_t3430258949  ____initialLeaseTime_3;\n\t\/\/ System.TimeSpan System.Runtime.Remoting.Lifetime.Lease::_renewOnCallTime\n\tTimeSpan_t3430258949  ____renewOnCallTime_4;\n\t\/\/ System.TimeSpan System.Runtime.Remoting.Lifetime.Lease::_sponsorshipTimeout\n\tTimeSpan_t3430258949  ____sponsorshipTimeout_5;\n\t\/\/ System.Collections.ArrayList System.Runtime.Remoting.Lifetime.Lease::_sponsors\n\tArrayList_t4252133567 * ____sponsors_6;\n\t\/\/ System.Collections.Queue System.Runtime.Remoting.Lifetime.Lease::_renewingSponsors\n\tQueue_t1288490777 * ____renewingSponsors_7;\n\t\/\/ System.Runtime.Remoting.Lifetime.Lease\/RenewalDelegate System.Runtime.Remoting.Lifetime.Lease::_renewalDelegate\n\tRenewalDelegate_t194360041 * ____renewalDelegate_8;\n\npublic:\n\tinline static int32_t get_offset_of__leaseExpireTime_1() { return static_cast<int32_t>(offsetof(Lease_t3663008028, ____leaseExpireTime_1)); }\n\tinline DateTime_t693205669  get__leaseExpireTime_1() const { return ____leaseExpireTime_1; }\n\tinline DateTime_t693205669 * get_address_of__leaseExpireTime_1() { return &____leaseExpireTime_1; }\n\tinline void set__leaseExpireTime_1(DateTime_t693205669  value)\n\t{\n\t\t____leaseExpireTime_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of__currentState_2() { return static_cast<int32_t>(offsetof(Lease_t3663008028, ____currentState_2)); }\n\tinline int32_t get__currentState_2() const { return ____currentState_2; }\n\tinline int32_t* get_address_of__currentState_2() { return &____currentState_2; }\n\tinline void set__currentState_2(int32_t value)\n\t{\n\t\t____currentState_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of__initialLeaseTime_3() { return static_cast<int32_t>(offsetof(Lease_t3663008028, ____initialLeaseTime_3)); }\n\tinline TimeSpan_t3430258949  get__initialLeaseTime_3() const { return ____initialLeaseTime_3; }\n\tinline TimeSpan_t3430258949 * get_address_of__initialLeaseTime_3() { return &____initialLeaseTime_3; }\n\tinline void set__initialLeaseTime_3(TimeSpan_t3430258949  value)\n\t{\n\t\t____initialLeaseTime_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of__renewOnCallTime_4() { return static_cast<int32_t>(offsetof(Lease_t3663008028, ____renewOnCallTime_4)); }\n\tinline TimeSpan_t3430258949  get__renewOnCallTime_4() const { return ____renewOnCallTime_4; }\n\tinline TimeSpan_t3430258949 * get_address_of__renewOnCallTime_4() { return &____renewOnCallTime_4; }\n\tinline void set__renewOnCallTime_4(TimeSpan_t3430258949  value)\n\t{\n\t\t____renewOnCallTime_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of__sponsorshipTimeout_5() { return static_cast<int32_t>(offsetof(Lease_t3663008028, ____sponsorshipTimeout_5)); }\n\tinline TimeSpan_t3430258949  get__sponsorshipTimeout_5() const { return ____sponsorshipTimeout_5; }\n\tinline TimeSpan_t3430258949 * get_address_of__sponsorshipTimeout_5() { return &____sponsorshipTimeout_5; }\n\tinline void set__sponsorshipTimeout_5(TimeSpan_t3430258949  value)\n\t{\n\t\t____sponsorshipTimeout_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of__sponsors_6() { return static_cast<int32_t>(offsetof(Lease_t3663008028, ____sponsors_6)); }\n\tinline ArrayList_t4252133567 * get__sponsors_6() const { return ____sponsors_6; }\n\tinline ArrayList_t4252133567 ** get_address_of__sponsors_6() { return &____sponsors_6; }\n\tinline void set__sponsors_6(ArrayList_t4252133567 * value)\n\t{\n\t\t____sponsors_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____sponsors_6), value);\n\t}\n\n\tinline static int32_t get_offset_of__renewingSponsors_7() { return static_cast<int32_t>(offsetof(Lease_t3663008028, ____renewingSponsors_7)); }\n\tinline Queue_t1288490777 * get__renewingSponsors_7() const { return ____renewingSponsors_7; }\n\tinline Queue_t1288490777 ** get_address_of__renewingSponsors_7() { return &____renewingSponsors_7; }\n\tinline void set__renewingSponsors_7(Queue_t1288490777 * value)\n\t{\n\t\t____renewingSponsors_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____renewingSponsors_7), value);\n\t}\n\n\tinline static int32_t get_offset_of__renewalDelegate_8() { return static_cast<int32_t>(offsetof(Lease_t3663008028, ____renewalDelegate_8)); }\n\tinline RenewalDelegate_t194360041 * get__renewalDelegate_8() const { return ____renewalDelegate_8; }\n\tinline RenewalDelegate_t194360041 ** get_address_of__renewalDelegate_8() { return &____renewalDelegate_8; }\n\tinline void set__renewalDelegate_8(RenewalDelegate_t194360041 * value)\n\t{\n\t\t____renewalDelegate_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____renewalDelegate_8), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ LEASE_T3663008028_H\n#ifndef MULTICASTDELEGATE_T3201952435_H\n#define MULTICASTDELEGATE_T3201952435_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.MulticastDelegate\nstruct  MulticastDelegate_t3201952435  : public Delegate_t3022476291\n{\npublic:\n\t\/\/ System.Delegate[] System.MulticastDelegate::delegates\n\tDelegateU5BU5D_t1606206610* ___delegates_11;\n\npublic:\n\tinline static int32_t get_offset_of_delegates_11() { return static_cast<int32_t>(offsetof(MulticastDelegate_t3201952435, ___delegates_11)); }\n\tinline DelegateU5BU5D_t1606206610* get_delegates_11() const { return ___delegates_11; }\n\tinline DelegateU5BU5D_t1606206610** get_address_of_delegates_11() { return &___delegates_11; }\n\tinline void set_delegates_11(DelegateU5BU5D_t1606206610* value)\n\t{\n\t\t___delegates_11 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___delegates_11), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.MulticastDelegate\nstruct MulticastDelegate_t3201952435_marshaled_pinvoke : public Delegate_t3022476291_marshaled_pinvoke\n{\n\tDelegateU5BU5D_t1606206610* ___delegates_11;\n};\n\/\/ Native definition for COM marshalling of System.MulticastDelegate\nstruct MulticastDelegate_t3201952435_marshaled_com : public Delegate_t3022476291_marshaled_com\n{\n\tDelegateU5BU5D_t1606206610* ___delegates_11;\n};\n#endif \/\/ MULTICASTDELEGATE_T3201952435_H\n#ifndef LIFETIMESERVICES_T2939669377_H\n#define LIFETIMESERVICES_T2939669377_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Lifetime.LifetimeServices\nstruct  LifetimeServices_t2939669377  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\nstruct LifetimeServices_t2939669377_StaticFields\n{\npublic:\n\t\/\/ System.TimeSpan System.Runtime.Remoting.Lifetime.LifetimeServices::_leaseManagerPollTime\n\tTimeSpan_t3430258949  ____leaseManagerPollTime_0;\n\t\/\/ System.TimeSpan System.Runtime.Remoting.Lifetime.LifetimeServices::_leaseTime\n\tTimeSpan_t3430258949  ____leaseTime_1;\n\t\/\/ System.TimeSpan System.Runtime.Remoting.Lifetime.LifetimeServices::_renewOnCallTime\n\tTimeSpan_t3430258949  ____renewOnCallTime_2;\n\t\/\/ System.TimeSpan System.Runtime.Remoting.Lifetime.LifetimeServices::_sponsorshipTimeout\n\tTimeSpan_t3430258949  ____sponsorshipTimeout_3;\n\t\/\/ System.Runtime.Remoting.Lifetime.LeaseManager System.Runtime.Remoting.Lifetime.LifetimeServices::_leaseManager\n\tLeaseManager_t1025868639 * ____leaseManager_4;\n\npublic:\n\tinline static int32_t get_offset_of__leaseManagerPollTime_0() { return static_cast<int32_t>(offsetof(LifetimeServices_t2939669377_StaticFields, ____leaseManagerPollTime_0)); }\n\tinline TimeSpan_t3430258949  get__leaseManagerPollTime_0() const { return ____leaseManagerPollTime_0; }\n\tinline TimeSpan_t3430258949 * get_address_of__leaseManagerPollTime_0() { return &____leaseManagerPollTime_0; }\n\tinline void set__leaseManagerPollTime_0(TimeSpan_t3430258949  value)\n\t{\n\t\t____leaseManagerPollTime_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of__leaseTime_1() { return static_cast<int32_t>(offsetof(LifetimeServices_t2939669377_StaticFields, ____leaseTime_1)); }\n\tinline TimeSpan_t3430258949  get__leaseTime_1() const { return ____leaseTime_1; }\n\tinline TimeSpan_t3430258949 * get_address_of__leaseTime_1() { return &____leaseTime_1; }\n\tinline void set__leaseTime_1(TimeSpan_t3430258949  value)\n\t{\n\t\t____leaseTime_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of__renewOnCallTime_2() { return static_cast<int32_t>(offsetof(LifetimeServices_t2939669377_StaticFields, ____renewOnCallTime_2)); }\n\tinline TimeSpan_t3430258949  get__renewOnCallTime_2() const { return ____renewOnCallTime_2; }\n\tinline TimeSpan_t3430258949 * get_address_of__renewOnCallTime_2() { return &____renewOnCallTime_2; }\n\tinline void set__renewOnCallTime_2(TimeSpan_t3430258949  value)\n\t{\n\t\t____renewOnCallTime_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of__sponsorshipTimeout_3() { return static_cast<int32_t>(offsetof(LifetimeServices_t2939669377_StaticFields, ____sponsorshipTimeout_3)); }\n\tinline TimeSpan_t3430258949  get__sponsorshipTimeout_3() const { return ____sponsorshipTimeout_3; }\n\tinline TimeSpan_t3430258949 * get_address_of__sponsorshipTimeout_3() { return &____sponsorshipTimeout_3; }\n\tinline void set__sponsorshipTimeout_3(TimeSpan_t3430258949  value)\n\t{\n\t\t____sponsorshipTimeout_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of__leaseManager_4() { return static_cast<int32_t>(offsetof(LifetimeServices_t2939669377_StaticFields, ____leaseManager_4)); }\n\tinline LeaseManager_t1025868639 * get__leaseManager_4() const { return ____leaseManager_4; }\n\tinline LeaseManager_t1025868639 ** get_address_of__leaseManager_4() { return &____leaseManager_4; }\n\tinline void set__leaseManager_4(LeaseManager_t1025868639 * value)\n\t{\n\t\t____leaseManager_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____leaseManager_4), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ LIFETIMESERVICES_T2939669377_H\n#ifndef HEADERHANDLER_T324204131_H\n#define HEADERHANDLER_T324204131_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Messaging.HeaderHandler\nstruct  HeaderHandler_t324204131  : public MulticastDelegate_t3201952435\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ HEADERHANDLER_T324204131_H\n#ifndef RENEWALDELEGATE_T194360041_H\n#define RENEWALDELEGATE_T194360041_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Lifetime.Lease\/RenewalDelegate\nstruct  RenewalDelegate_t194360041  : public MulticastDelegate_t3201952435\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ RENEWALDELEGATE_T194360041_H\n#ifndef CROSSCONTEXTDELEGATE_T754146990_H\n#define CROSSCONTEXTDELEGATE_T754146990_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.Remoting.Contexts.CrossContextDelegate\nstruct  CrossContextDelegate_t754146990  : public MulticastDelegate_t3201952435\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CROSSCONTEXTDELEGATE_T754146990_H\n\n\n\n\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize900 = { sizeof (AsyncResult_t2232356043), -1, sizeof(AsyncResult_t2232356043_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable900[17] = \n{\n\tAsyncResult_t2232356043::get_offset_of_async_state_0(),\n\tAsyncResult_t2232356043::get_offset_of_handle_1(),\n\tAsyncResult_t2232356043::get_offset_of_async_delegate_2(),\n\tAsyncResult_t2232356043::get_offset_of_data_3(),\n\tAsyncResult_t2232356043::get_offset_of_object_data_4(),\n\tAsyncResult_t2232356043::get_offset_of_sync_completed_5(),\n\tAsyncResult_t2232356043::get_offset_of_completed_6(),\n\tAsyncResult_t2232356043::get_offset_of_endinvoke_called_7(),\n\tAsyncResult_t2232356043::get_offset_of_async_callback_8(),\n\tAsyncResult_t2232356043::get_offset_of_current_9(),\n\tAsyncResult_t2232356043::get_offset_of_original_10(),\n\tAsyncResult_t2232356043::get_offset_of_add_time_11(),\n\tAsyncResult_t2232356043::get_offset_of_call_message_12(),\n\tAsyncResult_t2232356043::get_offset_of_message_ctrl_13(),\n\tAsyncResult_t2232356043::get_offset_of_reply_message_14(),\n\tAsyncResult_t2232356043::get_offset_of_orig_cb_15(),\n\tAsyncResult_t2232356043_StaticFields::get_offset_of_ccb_16(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize901 = { sizeof (ClientContextTerminatorSink_t3236389774), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable901[1] = \n{\n\tClientContextTerminatorSink_t3236389774::get_offset_of__context_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize902 = { sizeof (ConstructionCall_t1254994451), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable902[6] = \n{\n\tConstructionCall_t1254994451::get_offset_of__activator_11(),\n\tConstructionCall_t1254994451::get_offset_of__activationAttributes_12(),\n\tConstructionCall_t1254994451::get_offset_of__contextProperties_13(),\n\tConstructionCall_t1254994451::get_offset_of__activationType_14(),\n\tConstructionCall_t1254994451::get_offset_of__activationTypeName_15(),\n\tConstructionCall_t1254994451::get_offset_of__isContextOk_16(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize903 = { sizeof (ConstructionCallDictionary_t2993650247), -1, sizeof(ConstructionCallDictionary_t2993650247_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable903[1] = \n{\n\tConstructionCallDictionary_t2993650247_StaticFields::get_offset_of_InternalKeys_4(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize904 = { sizeof (EnvoyTerminatorSink_t3043186997), -1, sizeof(EnvoyTerminatorSink_t3043186997_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable904[1] = \n{\n\tEnvoyTerminatorSink_t3043186997_StaticFields::get_offset_of_Instance_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize905 = { sizeof (Header_t2756440555), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize906 = { sizeof (HeaderHandler_t324204131), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize907 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize908 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize909 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize910 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize911 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize912 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize913 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize914 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize915 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize916 = { sizeof (MethodCall_t2461541281), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable916[11] = \n{\n\tMethodCall_t2461541281::get_offset_of__uri_0(),\n\tMethodCall_t2461541281::get_offset_of__typeName_1(),\n\tMethodCall_t2461541281::get_offset_of__methodName_2(),\n\tMethodCall_t2461541281::get_offset_of__args_3(),\n\tMethodCall_t2461541281::get_offset_of__methodSignature_4(),\n\tMethodCall_t2461541281::get_offset_of__methodBase_5(),\n\tMethodCall_t2461541281::get_offset_of__callContext_6(),\n\tMethodCall_t2461541281::get_offset_of__targetIdentity_7(),\n\tMethodCall_t2461541281::get_offset_of__genericArguments_8(),\n\tMethodCall_t2461541281::get_offset_of_ExternalProperties_9(),\n\tMethodCall_t2461541281::get_offset_of_InternalProperties_10(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize917 = { sizeof (MethodResponse_t1456661140), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable917[15] = \n{\n\tMethodResponse_t1456661140::get_offset_of__methodName_0(),\n\tMethodResponse_t1456661140::get_offset_of__uri_1(),\n\tMethodResponse_t1456661140::get_offset_of__typeName_2(),\n\tMethodResponse_t1456661140::get_offset_of__methodBase_3(),\n\tMethodResponse_t1456661140::get_offset_of__returnValue_4(),\n\tMethodResponse_t1456661140::get_offset_of__exception_5(),\n\tMethodResponse_t1456661140::get_offset_of__methodSignature_6(),\n\tMethodResponse_t1456661140::get_offset_of__inArgInfo_7(),\n\tMethodResponse_t1456661140::get_offset_of__args_8(),\n\tMethodResponse_t1456661140::get_offset_of__outArgs_9(),\n\tMethodResponse_t1456661140::get_offset_of__callMsg_10(),\n\tMethodResponse_t1456661140::get_offset_of__callContext_11(),\n\tMethodResponse_t1456661140::get_offset_of__targetIdentity_12(),\n\tMethodResponse_t1456661140::get_offset_of_ExternalProperties_13(),\n\tMethodResponse_t1456661140::get_offset_of_InternalProperties_14(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize918 = { sizeof (MCMDictionary_t159052147), -1, sizeof(MCMDictionary_t159052147_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable918[1] = \n{\n\tMCMDictionary_t159052147_StaticFields::get_offset_of_InternalKeys_4(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize919 = { sizeof (MessageDictionary_t4157710479), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable919[4] = \n{\n\tMessageDictionary_t4157710479::get_offset_of__internalProperties_0(),\n\tMessageDictionary_t4157710479::get_offset_of__message_1(),\n\tMessageDictionary_t4157710479::get_offset_of__methodKeys_2(),\n\tMessageDictionary_t4157710479::get_offset_of__ownProperties_3(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize920 = { sizeof (DictionaryEnumerator_t4235333696), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable920[3] = \n{\n\tDictionaryEnumerator_t4235333696::get_offset_of__methodDictionary_0(),\n\tDictionaryEnumerator_t4235333696::get_offset_of__hashtableEnum_1(),\n\tDictionaryEnumerator_t4235333696::get_offset_of__posMethod_2(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize921 = { sizeof (MethodReturnDictionary_t981009581), -1, sizeof(MethodReturnDictionary_t981009581_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable921[2] = \n{\n\tMethodReturnDictionary_t981009581_StaticFields::get_offset_of_InternalReturnKeys_4(),\n\tMethodReturnDictionary_t981009581_StaticFields::get_offset_of_InternalExceptionKeys_5(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize922 = { sizeof (MonoMethodMessage_t771543475), -1, sizeof(MonoMethodMessage_t771543475_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable922[15] = \n{\n\tMonoMethodMessage_t771543475::get_offset_of_method_0(),\n\tMonoMethodMessage_t771543475::get_offset_of_args_1(),\n\tMonoMethodMessage_t771543475::get_offset_of_names_2(),\n\tMonoMethodMessage_t771543475::get_offset_of_arg_types_3(),\n\tMonoMethodMessage_t771543475::get_offset_of_ctx_4(),\n\tMonoMethodMessage_t771543475::get_offset_of_rval_5(),\n\tMonoMethodMessage_t771543475::get_offset_of_exc_6(),\n\tMonoMethodMessage_t771543475::get_offset_of_asyncResult_7(),\n\tMonoMethodMessage_t771543475::get_offset_of_call_type_8(),\n\tMonoMethodMessage_t771543475::get_offset_of_uri_9(),\n\tMonoMethodMessage_t771543475::get_offset_of_properties_10(),\n\tMonoMethodMessage_t771543475::get_offset_of_methodSignature_11(),\n\tMonoMethodMessage_t771543475::get_offset_of_identity_12(),\n\tMonoMethodMessage_t771543475_StaticFields::get_offset_of_CallContextKey_13(),\n\tMonoMethodMessage_t771543475_StaticFields::get_offset_of_UriKey_14(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize923 = { sizeof (CallType_t2486906258)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable923[5] = \n{\n\tCallType_t2486906258::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize924 = { sizeof (OneWayAttribute_t2539461443), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize925 = { sizeof (RemotingSurrogateSelector_t2821375126), -1, sizeof(RemotingSurrogateSelector_t2821375126_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable925[4] = \n{\n\tRemotingSurrogateSelector_t2821375126_StaticFields::get_offset_of_s_cachedTypeObjRef_0(),\n\tRemotingSurrogateSelector_t2821375126_StaticFields::get_offset_of__objRefSurrogate_1(),\n\tRemotingSurrogateSelector_t2821375126_StaticFields::get_offset_of__objRemotingSurrogate_2(),\n\tRemotingSurrogateSelector_t2821375126::get_offset_of__next_3(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize926 = { sizeof (RemotingSurrogate_t3248446683), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize927 = { sizeof (ObjRefSurrogate_t3912784830), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize928 = { sizeof (ReturnMessage_t3411975905), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable928[13] = \n{\n\tReturnMessage_t3411975905::get_offset_of__outArgs_0(),\n\tReturnMessage_t3411975905::get_offset_of__args_1(),\n\tReturnMessage_t3411975905::get_offset_of__callCtx_2(),\n\tReturnMessage_t3411975905::get_offset_of__returnValue_3(),\n\tReturnMessage_t3411975905::get_offset_of__uri_4(),\n\tReturnMessage_t3411975905::get_offset_of__exception_5(),\n\tReturnMessage_t3411975905::get_offset_of__methodBase_6(),\n\tReturnMessage_t3411975905::get_offset_of__methodName_7(),\n\tReturnMessage_t3411975905::get_offset_of__methodSignature_8(),\n\tReturnMessage_t3411975905::get_offset_of__typeName_9(),\n\tReturnMessage_t3411975905::get_offset_of__properties_10(),\n\tReturnMessage_t3411975905::get_offset_of__targetIdentity_11(),\n\tReturnMessage_t3411975905::get_offset_of__inArgInfo_12(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize929 = { sizeof (ServerContextTerminatorSink_t1054294306), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize930 = { sizeof (ServerObjectTerminatorSink_t4261369100), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable930[1] = \n{\n\tServerObjectTerminatorSink_t4261369100::get_offset_of__nextSink_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize931 = { sizeof (StackBuilderSink_t1613771438), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable931[2] = \n{\n\tStackBuilderSink_t1613771438::get_offset_of__target_0(),\n\tStackBuilderSink_t1613771438::get_offset_of__rp_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize932 = { sizeof (IllogicalCallContext_t206449943), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable932[2] = \n{\n\tIllogicalCallContext_t206449943::get_offset_of_m_Datastore_0(),\n\tIllogicalCallContext_t206449943::get_offset_of_m_HostContext_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize933 = { sizeof (LogicalCallContext_t725724420), -1, sizeof(LogicalCallContext_t725724420_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable933[6] = \n{\n\tLogicalCallContext_t725724420_StaticFields::get_offset_of_s_callContextType_0(),\n\tLogicalCallContext_t725724420::get_offset_of_m_Datastore_1(),\n\tLogicalCallContext_t725724420::get_offset_of_m_RemotingData_2(),\n\tLogicalCallContext_t725724420::get_offset_of_m_SecurityData_3(),\n\tLogicalCallContext_t725724420::get_offset_of_m_HostContext_4(),\n\tLogicalCallContext_t725724420::get_offset_of_m_IsCorrelationMgr_5(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize934 = { sizeof (Reader_t1568751674)+ sizeof (RuntimeObject), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable934[1] = \n{\n\tReader_t1568751674::get_offset_of_m_ctx_0() + static_cast<int32_t>(sizeof(RuntimeObject)),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize935 = { sizeof (CallContextSecurityData_t4091024823), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable935[1] = \n{\n\tCallContextSecurityData_t4091024823::get_offset_of__principal_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize936 = { sizeof (CallContextRemotingData_t2648008188), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable936[1] = \n{\n\tCallContextRemotingData_t2648008188::get_offset_of__logicalCallID_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize937 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize938 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize939 = { sizeof (Lease_t3663008028), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable939[8] = \n{\n\tLease_t3663008028::get_offset_of__leaseExpireTime_1(),\n\tLease_t3663008028::get_offset_of__currentState_2(),\n\tLease_t3663008028::get_offset_of__initialLeaseTime_3(),\n\tLease_t3663008028::get_offset_of__renewOnCallTime_4(),\n\tLease_t3663008028::get_offset_of__sponsorshipTimeout_5(),\n\tLease_t3663008028::get_offset_of__sponsors_6(),\n\tLease_t3663008028::get_offset_of__renewingSponsors_7(),\n\tLease_t3663008028::get_offset_of__renewalDelegate_8(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize940 = { sizeof (RenewalDelegate_t194360041), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize941 = { sizeof (LeaseManager_t1025868639), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable941[2] = \n{\n\tLeaseManager_t1025868639::get_offset_of__objects_0(),\n\tLeaseManager_t1025868639::get_offset_of__timer_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize942 = { sizeof (LeaseSink_t3007073869), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable942[1] = \n{\n\tLeaseSink_t3007073869::get_offset_of__nextSink_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize943 = { sizeof (LeaseState_t83447469)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable943[6] = \n{\n\tLeaseState_t83447469::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize944 = { sizeof (LifetimeServices_t2939669377), -1, sizeof(LifetimeServices_t2939669377_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable944[5] = \n{\n\tLifetimeServices_t2939669377_StaticFields::get_offset_of__leaseManagerPollTime_0(),\n\tLifetimeServices_t2939669377_StaticFields::get_offset_of__leaseTime_1(),\n\tLifetimeServices_t2939669377_StaticFields::get_offset_of__renewOnCallTime_2(),\n\tLifetimeServices_t2939669377_StaticFields::get_offset_of__sponsorshipTimeout_3(),\n\tLifetimeServices_t2939669377_StaticFields::get_offset_of__leaseManager_4(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize945 = { sizeof (Context_t502196753), -1, sizeof(Context_t502196753_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable945[15] = \n{\n\tContext_t502196753::get_offset_of_domain_id_0(),\n\tContext_t502196753::get_offset_of_context_id_1(),\n\tContext_t502196753::get_offset_of_static_data_2(),\n\tContext_t502196753::get_offset_of_data_3(),\n\tContext_t502196753_StaticFields::get_offset_of_local_slots_4(),\n\tContext_t502196753_StaticFields::get_offset_of_default_server_context_sink_5(),\n\tContext_t502196753::get_offset_of_server_context_sink_chain_6(),\n\tContext_t502196753::get_offset_of_client_context_sink_chain_7(),\n\tContext_t502196753::get_offset_of_context_properties_8(),\n\tContext_t502196753_StaticFields::get_offset_of_global_count_9(),\n\tContext_t502196753::get_offset_of__localDataStore_10(),\n\tContext_t502196753_StaticFields::get_offset_of__localDataStoreMgr_11(),\n\tContext_t502196753_StaticFields::get_offset_of_global_dynamic_properties_12(),\n\tContext_t502196753::get_offset_of_context_dynamic_properties_13(),\n\tContext_t502196753::get_offset_of_callback_object_14(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize946 = { sizeof (DynamicPropertyCollection_t2282532998), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable946[1] = \n{\n\tDynamicPropertyCollection_t2282532998::get_offset_of__properties_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize947 = { sizeof (DynamicPropertyReg_t1839195831), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable947[2] = \n{\n\tDynamicPropertyReg_t1839195831::get_offset_of_Property_0(),\n\tDynamicPropertyReg_t1839195831::get_offset_of_Sink_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize948 = { sizeof (ContextCallbackObject_t3978189709), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize949 = { sizeof (ContextAttribute_t197102333), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable949[1] = \n{\n\tContextAttribute_t197102333::get_offset_of_AttributeName_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize950 = { sizeof (CrossContextChannel_t2302426108), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize951 = { sizeof (CrossContextDelegate_t754146990), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize952 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize953 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize954 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize955 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize956 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize957 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize958 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize959 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize960 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize961 = { sizeof (SynchronizationAttribute_t3073724998), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable961[5] = \n{\n\tSynchronizationAttribute_t3073724998::get_offset_of__bReEntrant_1(),\n\tSynchronizationAttribute_t3073724998::get_offset_of__flavor_2(),\n\tSynchronizationAttribute_t3073724998::get_offset_of__lockCount_3(),\n\tSynchronizationAttribute_t3073724998::get_offset_of__mutex_4(),\n\tSynchronizationAttribute_t3073724998::get_offset_of__ownerThread_5(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize962 = { sizeof (SynchronizedClientContextSink_t3779986825), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable962[2] = \n{\n\tSynchronizedClientContextSink_t3779986825::get_offset_of__next_0(),\n\tSynchronizedClientContextSink_t3779986825::get_offset_of__att_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize963 = { sizeof (SynchronizedServerContextSink_t462987365), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable963[2] = \n{\n\tSynchronizedServerContextSink_t462987365::get_offset_of__next_0(),\n\tSynchronizedServerContextSink_t462987365::get_offset_of__att_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize964 = { sizeof (ChannelServices_t2007814595), -1, sizeof(ChannelServices_t2007814595_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable964[5] = \n{\n\tChannelServices_t2007814595_StaticFields::get_offset_of_registeredChannels_0(),\n\tChannelServices_t2007814595_StaticFields::get_offset_of_delayedClientChannels_1(),\n\tChannelServices_t2007814595_StaticFields::get_offset_of__crossContextSink_2(),\n\tChannelServices_t2007814595_StaticFields::get_offset_of_CrossContextUrl_3(),\n\tChannelServices_t2007814595_StaticFields::get_offset_of_oldStartModeTypes_4(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize965 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize966 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize967 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize968 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize969 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize970 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize971 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize972 = { sizeof (SinkProviderData_t2645445792), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable972[3] = \n{\n\tSinkProviderData_t2645445792::get_offset_of_sinkName_0(),\n\tSinkProviderData_t2645445792::get_offset_of_children_1(),\n\tSinkProviderData_t2645445792::get_offset_of_properties_2(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize973 = { sizeof (CrossAppDomainData_t816071813), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable973[3] = \n{\n\tCrossAppDomainData_t816071813::get_offset_of__ContextID_0(),\n\tCrossAppDomainData_t816071813::get_offset_of__DomainID_1(),\n\tCrossAppDomainData_t816071813::get_offset_of__processGuid_2(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize974 = { sizeof (CrossAppDomainChannel_t2471623380), -1, sizeof(CrossAppDomainChannel_t2471623380_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable974[1] = \n{\n\tCrossAppDomainChannel_t2471623380_StaticFields::get_offset_of_s_lock_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize975 = { sizeof (CrossAppDomainSink_t2368859578), -1, sizeof(CrossAppDomainSink_t2368859578_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable975[3] = \n{\n\tCrossAppDomainSink_t2368859578_StaticFields::get_offset_of_s_sinks_0(),\n\tCrossAppDomainSink_t2368859578_StaticFields::get_offset_of_processMessageMethod_1(),\n\tCrossAppDomainSink_t2368859578::get_offset_of__domainID_2(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize976 = { sizeof (ActivationServices_t1532663650), -1, sizeof(ActivationServices_t1532663650_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable976[1] = \n{\n\tActivationServices_t1532663650_StaticFields::get_offset_of__constructionActivator_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize977 = { sizeof (AppDomainLevelActivator_t834876328), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable977[2] = \n{\n\tAppDomainLevelActivator_t834876328::get_offset_of__activationUrl_0(),\n\tAppDomainLevelActivator_t834876328::get_offset_of__next_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize978 = { sizeof (ConstructionLevelActivator_t2284932402), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize979 = { sizeof (ContextLevelActivator_t1784331636), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable979[1] = \n{\n\tContextLevelActivator_t1784331636::get_offset_of_m_NextActivator_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize980 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize981 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize982 = { sizeof (RemoteActivator_t213750447), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize983 = { sizeof (UrlAttribute_t1544437301), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable983[1] = \n{\n\tUrlAttribute_t1544437301::get_offset_of_url_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize984 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize985 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize986 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize987 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize988 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize989 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize990 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize991 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize992 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize993 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize994 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize995 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize996 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize997 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize998 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize999 = { 0, -1, 0, 0 };\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n","avg_line_length":42.7940117064,"max_line_length":185,"alphanum_fraction":0.8286347065,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4290,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0","MIT"],"max_stars_count":2.0,"content":"#include\"stdafx.h\"\r\n\r\nCLC7JohnConfSection::CLC7JohnConfSection(QString name)\r\n{\r\n\tm_name=name;\r\n}\r\n\r\nQString CLC7JohnConfSection::getName()\r\n{\r\n\treturn m_name;\r\n}\r\n\r\nQMap<QString,QString> CLC7JohnConfSection::getValues()\r\n{\r\n\treturn m_values;\r\n}\r\n\r\nQVector<QString> CLC7JohnConfSection::getLines()\r\n{\r\n\treturn m_lines;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\nCLC7JohnConf::CLC7JohnConf()\r\n{\r\n\tm_valid=true;\r\n\r\n\tQDir lc7jtrdir(g_pLinkage->GetPluginsDirectory());\r\n\tlc7jtrdir.cd(\"lc7jtr{9846c8cf-1db1-467e-83c2-c5655aa81936}\");\r\n\t\r\n\tif(!parse(lc7jtrdir.filePath(\"john.conf\"),lc7jtrdir.absolutePath()))\r\n\t{\r\n\t\tm_valid=false;\r\n\t}\r\n\/\/\tif(!parse(lc7jtrdir.filePath(\"lc7.conf\"),lc7jtrdir.absolutePath()))\r\n\/\/\t{\r\n\/\/\t\tm_valid=false;\r\n\/\/\t}\r\n}\r\n\r\nCLC7JohnConf::~CLC7JohnConf()\r\n{\r\n\tforeach(CLC7JohnConfSection *section,m_section_map)\r\n\t{\r\n\t\tdelete section;\r\n\t}\r\n}\r\n\r\nbool CLC7JohnConf::isValid()\r\n{\r\n\treturn m_valid;\r\n}\r\n\r\nQMap<QString,CLC7JohnConfSection *> CLC7JohnConf::getSectionMap()\r\n{\r\n\treturn m_section_map;\r\n}\r\n\r\nbool CLC7JohnConf::parse(QString filename, QString $john_value)\r\n{\r\n\tQList<QTextStream *> instack;\r\n\r\n\tfilename.replace(\"$JOHN\", $john_value);\r\n\r\n\tQFile *file=new QFile(filename);\r\n\tif(!file->open(QIODevice::ReadOnly))\r\n\t{\r\n\t\tdelete file;\r\n\t\treturn false;\r\n\t}\r\n\tinstack.push_back(new QTextStream(file->readAll()));\r\n\tdelete file;\r\n\r\n\tQString line;\r\n\tCLC7JohnConfSection *cursection=NULL;\r\n\tbool cur_is_kv;\r\n\twhile(instack.size()>0)\r\n\t{\r\n\t\tQTextStream *pts=instack.back();\r\n\t\tinstack.pop_back();\r\n\t\t\r\n\t\twhile(!pts->atEnd())\r\n\t\t{\r\n\t\t\tline=pts->readLine();\r\n\t\t\tif(line.startsWith(\"#\"))\r\n\t\t\t{\r\n\t\t\t\t\/\/ Comment\r\n\t\t\t}\r\n\t\t\telse if(line.startsWith(\".include\"))\r\n\t\t\t{\r\n\t\t\t\tQString incpath=line.mid(8).trimmed();\r\n\t\t\t\tif(incpath.startsWith(\"[\"))\r\n\t\t\t\t{\r\n\t\t\t\t\tQRegExp re(\"\\\\[(.*)\\\\]\");\r\n\t\t\t\t\tint pos=re.indexIn(line);\r\n\t\t\t\t\tif(pos!=-1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tQString section_name=re.cap(1);\r\n\t\t\t\t\t\t\/\/ Look up section and append\r\n\t\t\t\t\t\tif(m_section_map.contains(section_name))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tCLC7JohnConfSection *incsection=m_section_map[section_name];\r\n\t\t\t\t\t\t\tint beforesize=cursection->m_lines.size();\r\n\t\t\t\t\t\t\tint tocopy=incsection->m_lines.size();\r\n\t\t\t\t\t\t\tcursection->m_lines.resize(beforesize+tocopy);\r\n\t\t\t\t\t\t\tqCopy(incsection->m_lines.begin(),incsection->m_lines.end(),cursection->m_lines.begin()+beforesize);\r\n\t\t\t\t\t\t\tcursection->m_values.unite(incsection->m_values);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif(incpath.startsWith(\"<\") && incpath.endsWith(\">\") && incpath.size()>=2)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tincpath=$john_value+\"\/\"+incpath.mid(1,incpath.size()-2);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if(incpath.startsWith(\"\\\"\") && incpath.endsWith(\"\\\"\") && incpath.size()>=2)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tincpath=incpath.mid(1,incpath.size()-2).replace(\"$JOHN\", $john_value);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\/\/ Load new file\r\n\t\t\t\t\tQFile *incfile=new QFile(incpath);\r\n\t\t\t\t\tif(!incfile->open(QIODevice::ReadOnly))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdelete incfile;\r\n\t\t\r\n\t\t\t\t\t\tif(!incpath.endsWith(\"\/john.local.conf\"))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tQ_FOREACH(QTextStream *t,instack) delete t;\r\n\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tQTextStream *incts=new QTextStream(incfile->readAll());\r\n\t\t\t\t\t\tdelete incfile;\r\n\t\t\t\t\t\tinstack.push_back(pts);\r\n\t\t\t\t\t\tpts=incts;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if(line.startsWith(\"[\"))\r\n\t\t\t{\r\n\t\t\t\t\/\/ New Section\r\n\t\t\t\tQRegExp re(\"\\\\[(.*)\\\\]\");\r\n\t\t\t\tint pos=re.indexIn(line);\r\n\t\t\t\tif(pos!=-1)\r\n\t\t\t\t{\r\n\t\t\t\t\tQString section_name=re.cap(1);\r\n\t\t\t\t\tcur_is_kv=!section_name.startsWith(\"List.\");\r\n\t\t\t\t\r\n\t\t\t\t\tQMap<QString,CLC7JohnConfSection *>::iterator iter=m_section_map.find(section_name);\r\n\t\t\t\t\tif(iter==m_section_map.end())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcursection=new CLC7JohnConfSection(section_name);\r\n\t\t\t\t\t\tm_section_map.insert(section_name,cursection);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcursection=*iter;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if(cursection)\r\n\t\t\t{\r\n\t\t\t\tif(cur_is_kv)\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Key\/Value\r\n\t\t\t\t\tint pos=line.indexOf('=');\r\n\t\t\t\t\tif(pos!=-1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tQString key;\r\n\t\t\t\t\t\tQString value;\r\n\t\t\t\t\t\tkey=line.left(pos).trimmed();\r\n\t\t\t\t\t\tvalue=line.mid(pos+1).trimmed();\r\n\t\t\t\t\t\tcursection->m_values.insert(key,value);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Just lines\r\n\t\t\t\t\tcursection->m_lines.append(line);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tdelete pts;\r\n\t}\r\n\treturn true;\r\n}\r\n","avg_line_length":22.2279792746,"max_line_length":108,"alphanum_fraction":0.5857808858,"low_alphanum":false,"long_lines":false,"lexable":false}
{"size":4341,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2761.0,"content":"\/*++\n\n    Copyright (c) Microsoft Corporation.\n    Licensed under the MIT License.\n\nAbstract:\n\n    MsQuic Path Unittest\n\n--*\/\n\n#include \"precomp.h\"\n#ifdef QUIC_CLOG\n#include \"PathTest.cpp.clog.h\"\n#endif\n\nstruct PathTestContext {\n    CxPlatEvent HandshakeCompleteEvent;\n    CxPlatEvent ShutdownEvent;\n    MsQuicConnection* Connection {nullptr};\n    CxPlatEvent PeerAddrChangedEvent;\n\n    static QUIC_STATUS ConnCallback(_In_ MsQuicConnection* Conn, _In_opt_ void* Context, _Inout_ QUIC_CONNECTION_EVENT* Event) {\n        PathTestContext* Ctx = static_cast<PathTestContext*>(Context);\n        Ctx->Connection = Conn;\n        if (Event->Type == QUIC_CONNECTION_EVENT_SHUTDOWN_COMPLETE) {\n            Ctx->Connection = nullptr;\n            Ctx->PeerAddrChangedEvent.Set();\n            Ctx->ShutdownEvent.Set();\n            Ctx->HandshakeCompleteEvent.Set();\n        } else if (Event->Type == QUIC_CONNECTION_EVENT_CONNECTED) {\n            Ctx->HandshakeCompleteEvent.Set();\n        } else if (Event->Type == QUIC_CONNECTION_EVENT_PEER_ADDRESS_CHANGED) {\n            MsQuicSettings Settings;\n            Conn->GetSettings(&Settings);\n            Settings.IsSetFlags = 0;\n            Settings.SetPeerBidiStreamCount(Settings.PeerBidiStreamCount + 1);\n            Conn->SetSettings(Settings);\n            Ctx->PeerAddrChangedEvent.Set();\n        }\n        return QUIC_STATUS_SUCCESS;\n    }\n};\n\nstatic\nQUIC_STATUS\nQUIC_API\nClientCallback(\n    _In_ MsQuicConnection* \/* Connection *\/,\n    _In_opt_ void* Context,\n    _Inout_ QUIC_CONNECTION_EVENT* Event\n    ) noexcept\n{\n    if (Event->Type == QUIC_CONNECTION_EVENT_PEER_STREAM_STARTED) {\n        MsQuic->StreamClose(Event->PEER_STREAM_STARTED.Stream);\n    } else if (Event->Type == QUIC_CONNECTION_EVENT_STREAMS_AVAILABLE) {\n        CxPlatEvent* StreamCountEvent = static_cast<CxPlatEvent*>(Context);\n        StreamCountEvent->Set();\n    }\n    return QUIC_STATUS_SUCCESS;\n}\n\nvoid\nQuicTestLocalPathChanges(\n    _In_ int Family\n    )\n{\n    PathTestContext Context;\n    CxPlatEvent PeerStreamsChanged;\n    MsQuicRegistration Registration{true};\n    TEST_QUIC_SUCCEEDED(Registration.GetInitStatus());\n\n    MsQuicSettings Settings;\n    Settings.SetMinimumMtu(1280).SetMaximumMtu(1280);\n\n    MsQuicConfiguration ServerConfiguration(Registration, \"MsQuicTest\", Settings, ServerSelfSignedCredConfig);\n    TEST_QUIC_SUCCEEDED(ServerConfiguration.GetInitStatus());\n\n    MsQuicConfiguration ClientConfiguration(Registration, \"MsQuicTest\", Settings, MsQuicCredentialConfig{});\n    TEST_QUIC_SUCCEEDED(ClientConfiguration.GetInitStatus());\n\n    MsQuicAutoAcceptListener Listener(Registration, ServerConfiguration, PathTestContext::ConnCallback, &Context);\n    TEST_QUIC_SUCCEEDED(Listener.GetInitStatus());\n    QUIC_ADDRESS_FAMILY QuicAddrFamily = (Family == 4) ? QUIC_ADDRESS_FAMILY_INET : QUIC_ADDRESS_FAMILY_INET6;\n    QuicAddr ServerLocalAddr(QuicAddrFamily);\n    TEST_QUIC_SUCCEEDED(Listener.Start(\"MsQuicTest\", &ServerLocalAddr.SockAddr));\n    TEST_QUIC_SUCCEEDED(Listener.GetLocalAddr(ServerLocalAddr));\n\n    MsQuicConnection Connection(Registration, CleanUpManual, ClientCallback, &PeerStreamsChanged);\n    TEST_QUIC_SUCCEEDED(Connection.GetInitStatus());\n\n    TEST_QUIC_SUCCEEDED(Connection.StartLocalhost(ClientConfiguration, ServerLocalAddr));\n    TEST_TRUE(Connection.HandshakeCompleteEvent.WaitTimeout(TestWaitTimeout));\n    TEST_NOT_EQUAL(nullptr, Context.Connection);\n    TEST_TRUE(Context.Connection->HandshakeCompleteEvent.WaitTimeout(TestWaitTimeout));\n\n    QuicAddr OrigLocalAddr;\n    TEST_QUIC_SUCCEEDED(Connection.GetLocalAddr(OrigLocalAddr));\n    ReplaceAddressHelper AddrHelper(OrigLocalAddr.SockAddr, OrigLocalAddr.SockAddr);\n\n    for (int i = 0; i < 50; i++) {\n        QuicAddrSetPort(&AddrHelper.New, QuicAddrGetPort(&AddrHelper.New) + 1);\n        Connection.SetSettings(MsQuicSettings{}.SetKeepAlive(25));\n\n        TEST_TRUE(Context.PeerAddrChangedEvent.WaitTimeout(1500));\n        Context.PeerAddrChangedEvent.Reset();\n        QuicAddr ServerRemoteAddr;\n        TEST_QUIC_SUCCEEDED(Context.Connection->GetRemoteAddr(ServerRemoteAddr));\n        TEST_TRUE(QuicAddrCompare(&AddrHelper.New, &ServerRemoteAddr.SockAddr));\n        Connection.SetSettings(MsQuicSettings{}.SetKeepAlive(0));\n        TEST_TRUE(PeerStreamsChanged.WaitTimeout(1500));\n        PeerStreamsChanged.Reset();\n    }\n}\n","avg_line_length":37.747826087,"max_line_length":128,"alphanum_fraction":0.737157337,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5616,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":null,"content":"\/\/\n\/\/  engine.cpp\n\/\/  audio_engine\n\/\/\n\/\/  Created by Dmitrii Torkhov <dmitriitorkhov@gmail.com> on 15.08.2021.\n\/\/  Copyright \u00a9 2021 Dmitrii Torkhov. All rights reserved.\n\/\/\n\n#define MINIAUDIO_IMPLEMENTATION\n\n#include <miniaudio.h>\n\n#include \"audio\/decoder.h\"\n#include \"audio\/device.h\"\n\n#include \"audio\/engine.h\"\n\noo::audio::engine::engine() {\n    run_service_thread();\n}\n\nvoid oo::audio::engine::preload(const std::string &path) {\n    queue_command(engine::command::preload, path);\n}\n\nvoid oo::audio::engine::release(const std::string &path) {\n    queue_command(engine::command::release, path);\n}\n\nvoid oo::audio::engine::play(const std::string &path) {\n    queue_command(engine::command::play, path);\n}\n\nvoid oo::audio::engine::stop(const std::string &path) {\n    queue_command(engine::command::stop, path);\n}\n\nvoid oo::audio::engine::reset(const std::string &path) {\n    queue_command(engine::command::reset, path);\n}\n\nvoid oo::audio::engine::set_volume(float value) {\n    queue_command(engine::command::volume, value);\n}\n\noo::audio::engine::~engine() {\n    {\n        std::lock_guard<std::mutex> lock(m_mutex);\n\n        m_is_done = true;\n        m_condition.notify_all();\n    }\n\n    m_service_thread->join();\n}\n\nvoid oo::audio::engine::queue_command(oo::audio::engine::command command, const std::any &param) {\n    m_queue.push({command, param});\n    m_condition.notify_one();\n}\n\nvoid oo::audio::engine::run_service_thread() {\n    m_service_thread = std::make_unique<std::thread>([&]() {\n        oo::audio::device device{[this](float *output, uint32_t frame_count, uint32_t channel_count) {\n            return device_callback(output, frame_count, channel_count);\n        }};\n\n        std::pair<engine::command, std::any> command;\n        while (true) {\n            if (m_queue.pop(command)) {\n                process_command(device, command.first, command.second);\n            } else {\n                std::unique_lock<std::mutex> lock(m_mutex);\n                if (m_is_done) {\n                    break;\n                } else {\n                    using namespace std::chrono_literals;\n                    m_condition.wait_for(lock, 100ms);\n                }\n            }\n        }\n    });\n}\n\nuint64_t oo::audio::engine::device_callback(float *output, uint32_t frame_count, uint32_t channel_count) {\n    m_callback_buf.resize(frame_count * channel_count);\n    ma_uint64 total_read = 0;\n\n    for (const auto &decoder: m_playing) {\n        const auto read = decoder->read(output, m_callback_buf.data(), frame_count, channel_count);\n\n        total_read = std::max(total_read, read);\n\n        if (read < frame_count) {\n            const auto &path = decoder->get_path();\n\n            stop(path);\n            reset(path);\n        }\n    }\n\n    if (total_read == 0) {\n        stop();\n    }\n\n    return total_read;\n}\n\nvoid oo::audio::engine::process_command(oo::audio::device &device, engine::command command, const std::any &param) {\n    switch (command) {\n        case command::preload:\n            preload(device, std::any_cast<std::string>(param));\n            break;\n        case command::release:\n            release(device, std::any_cast<std::string>(param));\n            break;\n        case command::play:\n            play(device, std::any_cast<std::string>(param));\n            break;\n        case command::stop:\n            stop(device, std::any_cast<std::string>(param));\n            break;\n        case command::reset:\n            reset(device, std::any_cast<std::string>(param));\n            break;\n        case command::volume:\n            set_volume(device, std::any_cast<float>(param));\n            break;\n    }\n}\n\nvoid oo::audio::engine::preload(oo::audio::device &device, const std::string &path) {\n    const auto decoder = std::make_shared<oo::audio::decoder>(path);\n\n    if (!decoder->init()) {\n        return;\n    }\n\n    if (!device.is_inited()) {\n        if (!device.init(decoder->get_output_format(),\n                         decoder->get_output_channels(),\n                         decoder->get_output_sample_rate())) {\n            return;\n        }\n    }\n\n    m_decoders.emplace(path, decoder);\n}\n\nvoid oo::audio::engine::release(oo::audio::device &device, const std::string &path) {\n    auto decoder_it = m_decoders.find(path);\n    if (decoder_it == m_decoders.end()) {\n        return;\n    }\n\n    m_playing.erase(decoder_it->second);\n    m_decoders.erase(decoder_it);\n}\n\nvoid oo::audio::engine::play(oo::audio::device &device, const std::string &path) {\n    if (m_decoders.find(path) == m_decoders.end()) {\n        preload(device, path);\n    }\n\n    if (!device.is_inited()) {\n        return;\n    }\n\n    \/\/\n\n    auto decoder_it = m_decoders.find(path);\n    if (decoder_it == m_decoders.end()) {\n        return;\n    }\n\n    m_playing.insert(decoder_it->second);\n\n    \/\/\n\n    if (!device.is_started()) {\n        if (!device.start()) {\n            return;\n        }\n    }\n}\n\nvoid oo::audio::engine::stop(oo::audio::device &device, const std::string &path) {\n    if (path.empty()) {\n        if (!device.is_stopped()) {\n            device.stop();\n        }\n    } else {\n        auto decoder_it = m_decoders.find(path);\n        if (decoder_it == m_decoders.end()) {\n            return;\n        }\n\n        m_playing.erase(decoder_it->second);\n    }\n}\n\nvoid oo::audio::engine::reset(oo::audio::device &device, const std::string &path) {\n    auto decoder_it = m_decoders.find(path);\n    if (decoder_it == m_decoders.end()) {\n        return;\n    }\n\n    decoder_it->second->seek(0);\n}\n\nvoid oo::audio::engine::set_volume(oo::audio::device &device, float value) { \/\/ NOLINT\n    device.set_volume(value);\n}\n","avg_line_length":26.2429906542,"max_line_length":116,"alphanum_fraction":0.5902777778,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":71296,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n * Copyright (C) 2004, 2008, 2009, 2010 Apple Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/editing\/FrameSelection.h\"\n\n#include \"bindings\/core\/v8\/ExceptionState.h\"\n#include \"core\/HTMLNames.h\"\n#include \"core\/InputTypeNames.h\"\n#include \"core\/css\/StylePropertySet.h\"\n#include \"core\/dom\/AXObjectCache.h\"\n#include \"core\/dom\/CharacterData.h\"\n#include \"core\/dom\/Document.h\"\n#include \"core\/dom\/Element.h\"\n#include \"core\/dom\/ElementTraversal.h\"\n#include \"core\/dom\/NodeTraversal.h\"\n#include \"core\/dom\/Text.h\"\n#include \"core\/editing\/Editor.h\"\n#include \"core\/editing\/InputMethodController.h\"\n#include \"core\/editing\/RenderedPosition.h\"\n#include \"core\/editing\/SpellChecker.h\"\n#include \"core\/editing\/TextIterator.h\"\n#include \"core\/editing\/TypingCommand.h\"\n#include \"core\/editing\/VisibleUnits.h\"\n#include \"core\/editing\/htmlediting.h\"\n#include \"core\/events\/Event.h\"\n#include \"core\/frame\/LocalDOMWindow.h\"\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/html\/HTMLBodyElement.h\"\n#include \"core\/html\/HTMLFormElement.h\"\n#include \"core\/html\/HTMLFrameElementBase.h\"\n#include \"core\/html\/HTMLInputElement.h\"\n#include \"core\/html\/HTMLSelectElement.h\"\n#include \"core\/page\/EditorClient.h\"\n#include \"core\/page\/EventHandler.h\"\n#include \"core\/page\/FocusController.h\"\n#include \"core\/page\/FrameTree.h\"\n#include \"core\/frame\/FrameView.h\"\n#include \"core\/page\/Page.h\"\n#include \"core\/frame\/Settings.h\"\n#include \"core\/page\/SpatialNavigation.h\"\n#include \"core\/rendering\/HitTestRequest.h\"\n#include \"core\/rendering\/HitTestResult.h\"\n#include \"core\/rendering\/InlineTextBox.h\"\n#include \"core\/rendering\/RenderLayer.h\"\n#include \"core\/rendering\/RenderPart.h\"\n#include \"core\/rendering\/RenderText.h\"\n#include \"core\/rendering\/RenderTheme.h\"\n#include \"core\/rendering\/RenderView.h\"\n#include \"platform\/SecureTextInput.h\"\n#include \"platform\/geometry\/FloatQuad.h\"\n#include \"platform\/graphics\/GraphicsContext.h\"\n#include \"platform\/text\/UnicodeUtilities.h\"\n#include \"wtf\/text\/CString.h\"\n#include <stdio.h>\n\n#define EDIT_DEBUG 0\n\nnamespace blink {\n\nusing namespace HTMLNames;\n\nstatic inline LayoutUnit NoXPosForVerticalArrowNavigation()\n{\n    return LayoutUnit::min();\n}\n\nstatic inline bool shouldAlwaysUseDirectionalSelection(LocalFrame* frame)\n{\n    return !frame || frame->editor().behavior().shouldConsiderSelectionAsDirectional();\n}\n\nFrameSelection::FrameSelection(LocalFrame* frame)\n    : m_frame(frame)\n    , m_xPosForVerticalArrowNavigation(NoXPosForVerticalArrowNavigation())\n    , m_observingVisibleSelection(false)\n    , m_granularity(CharacterGranularity)\n    , m_caretBlinkTimer(this, &FrameSelection::caretBlinkTimerFired)\n    , m_caretRectDirty(true)\n    , m_shouldPaintCaret(true)\n    , m_isCaretBlinkingSuspended(false)\n    , m_focused(frame && frame->page() && frame->page()->focusController().focusedFrame() == frame)\n    , m_shouldShowBlockCursor(false)\n{\n    if (shouldAlwaysUseDirectionalSelection(m_frame))\n        m_selection.setIsDirectional(true);\n}\n\nFrameSelection::~FrameSelection()\n{\n#if !ENABLE(OILPAN)\n    \/\/ Oilpan: No need to clear out VisibleSelection observer;\n    \/\/ it is finalized as a part object of FrameSelection.\n    stopObservingVisibleSelectionChangeIfNecessary();\n#endif\n}\n\nElement* FrameSelection::rootEditableElementOrDocumentElement() const\n{\n    Element* selectionRoot = m_selection.rootEditableElement();\n    return selectionRoot ? selectionRoot : m_frame->document()->documentElement();\n}\n\nContainerNode* FrameSelection::rootEditableElementOrTreeScopeRootNode() const\n{\n    Element* selectionRoot = m_selection.rootEditableElement();\n    if (selectionRoot)\n        return selectionRoot;\n\n    Node* node = m_selection.base().containerNode();\n    return node ? &node->treeScope().rootNode() : 0;\n}\n\nvoid FrameSelection::moveTo(const VisiblePosition &pos, EUserTriggered userTriggered, CursorAlignOnScroll align)\n{\n    SetSelectionOptions options = CloseTyping | ClearTypingStyle | userTriggered;\n    setSelection(VisibleSelection(pos.deepEquivalent(), pos.deepEquivalent(), pos.affinity(), m_selection.isDirectional()), options, align);\n}\n\nvoid FrameSelection::moveTo(const VisiblePosition &base, const VisiblePosition &extent, EUserTriggered userTriggered)\n{\n    const bool selectionHasDirection = true;\n    SetSelectionOptions options = CloseTyping | ClearTypingStyle | userTriggered;\n    setSelection(VisibleSelection(base.deepEquivalent(), extent.deepEquivalent(), base.affinity(), selectionHasDirection), options);\n}\n\nvoid FrameSelection::moveTo(const Position &pos, EAffinity affinity, EUserTriggered userTriggered)\n{\n    SetSelectionOptions options = CloseTyping | ClearTypingStyle | userTriggered;\n    setSelection(VisibleSelection(pos, affinity, m_selection.isDirectional()), options);\n}\n\nstatic void adjustEndpointsAtBidiBoundary(VisiblePosition& visibleBase, VisiblePosition& visibleExtent)\n{\n    RenderedPosition base(visibleBase);\n    RenderedPosition extent(visibleExtent);\n\n    if (base.isNull() || extent.isNull() || base.isEquivalent(extent))\n        return;\n\n    if (base.atLeftBoundaryOfBidiRun()) {\n        if (!extent.atRightBoundaryOfBidiRun(base.bidiLevelOnRight())\n            && base.isEquivalent(extent.leftBoundaryOfBidiRun(base.bidiLevelOnRight()))) {\n            visibleBase = VisiblePosition(base.positionAtLeftBoundaryOfBiDiRun());\n            return;\n        }\n        return;\n    }\n\n    if (base.atRightBoundaryOfBidiRun()) {\n        if (!extent.atLeftBoundaryOfBidiRun(base.bidiLevelOnLeft())\n            && base.isEquivalent(extent.rightBoundaryOfBidiRun(base.bidiLevelOnLeft()))) {\n            visibleBase = VisiblePosition(base.positionAtRightBoundaryOfBiDiRun());\n            return;\n        }\n        return;\n    }\n\n    if (extent.atLeftBoundaryOfBidiRun() && extent.isEquivalent(base.leftBoundaryOfBidiRun(extent.bidiLevelOnRight()))) {\n        visibleExtent = VisiblePosition(extent.positionAtLeftBoundaryOfBiDiRun());\n        return;\n    }\n\n    if (extent.atRightBoundaryOfBidiRun() && extent.isEquivalent(base.rightBoundaryOfBidiRun(extent.bidiLevelOnLeft()))) {\n        visibleExtent = VisiblePosition(extent.positionAtRightBoundaryOfBiDiRun());\n        return;\n    }\n}\n\nvoid FrameSelection::setNonDirectionalSelectionIfNeeded(const VisibleSelection& passedNewSelection, TextGranularity granularity,\n    EndPointsAdjustmentMode endpointsAdjustmentMode)\n{\n    VisibleSelection newSelection = passedNewSelection;\n    bool isDirectional = shouldAlwaysUseDirectionalSelection(m_frame) || newSelection.isDirectional();\n\n    VisiblePosition base = m_originalBase.isNotNull() ? m_originalBase : newSelection.visibleBase();\n    VisiblePosition newBase = base;\n    VisiblePosition extent = newSelection.visibleExtent();\n    VisiblePosition newExtent = extent;\n    if (endpointsAdjustmentMode == AdjustEndpointsAtBidiBoundary)\n        adjustEndpointsAtBidiBoundary(newBase, newExtent);\n\n    if (newBase != base || newExtent != extent) {\n        m_originalBase = base;\n        newSelection.setBase(newBase);\n        newSelection.setExtent(newExtent);\n    } else if (m_originalBase.isNotNull()) {\n        if (m_selection.base() == newSelection.base())\n            newSelection.setBase(m_originalBase);\n        m_originalBase.clear();\n    }\n\n    newSelection.setIsDirectional(isDirectional); \/\/ Adjusting base and extent will make newSelection always directional\n    if (m_selection == newSelection)\n        return;\n\n    setSelection(newSelection, granularity);\n}\n\nvoid FrameSelection::setSelection(const VisibleSelection& newSelection, SetSelectionOptions options, CursorAlignOnScroll align, TextGranularity granularity)\n{\n    bool closeTyping = options & CloseTyping;\n    bool shouldClearTypingStyle = options & ClearTypingStyle;\n    EUserTriggered userTriggered = selectionOptionsToUserTriggered(options);\n\n    VisibleSelection s = validateSelection(newSelection);\n    if (shouldAlwaysUseDirectionalSelection(m_frame))\n        s.setIsDirectional(true);\n\n    if (!m_frame) {\n        m_selection = s;\n        return;\n    }\n\n    \/\/ <http:\/\/bugs.webkit.org\/show_bug.cgi?id=23464>: Infinite recursion at FrameSelection::setSelection\n    \/\/ if document->frame() == m_frame we can get into an infinite loop\n    if (s.base().anchorNode()) {\n        Document& document = *s.base().document();\n        if (document.frame() && document.frame() != m_frame && document != m_frame->document()) {\n            RefPtrWillBeRawPtr<LocalFrame> guard(document.frame());\n            document.frame()->selection().setSelection(s, options, align, granularity);\n            \/\/ It's possible that during the above set selection, this FrameSelection has been modified by\n            \/\/ selectFrameElementInParentIfFullySelected, but that the selection is no longer valid since\n            \/\/ the frame is about to be destroyed. If this is the case, clear our selection.\n            if (!guard->host() && !m_selection.isNonOrphanedCaretOrRange())\n                clear();\n            return;\n        }\n    }\n\n    m_granularity = granularity;\n\n    if (closeTyping)\n        TypingCommand::closeTyping(m_frame);\n\n    if (shouldClearTypingStyle)\n        clearTypingStyle();\n\n    if (m_selection == s) {\n        \/\/ Even if selection was not changed, selection offsets may have been changed.\n        m_frame->inputMethodController().cancelCompositionIfSelectionIsInvalid();\n        notifyRendererOfSelectionChange(userTriggered);\n        return;\n    }\n\n    VisibleSelection oldSelection = m_selection;\n\n    m_selection = s;\n    setCaretRectNeedsUpdate();\n\n    if (!s.isNone() && !(options & DoNotSetFocus))\n        setFocusedNodeIfNeeded();\n\n    if (!(options & DoNotUpdateAppearance)) {\n        \/\/ Hits in compositing\/overflow\/do-not-paint-outline-into-composited-scrolling-contents.html\n        DisableCompositingQueryAsserts disabler;\n        updateAppearance(ResetCaretBlink);\n    }\n\n    \/\/ Always clear the x position used for vertical arrow navigation.\n    \/\/ It will be restored by the vertical arrow navigation code if necessary.\n    m_xPosForVerticalArrowNavigation = NoXPosForVerticalArrowNavigation();\n    selectFrameElementInParentIfFullySelected();\n    notifyRendererOfSelectionChange(userTriggered);\n    m_frame->editor().respondToChangedSelection(oldSelection, options);\n    if (userTriggered == UserTriggered) {\n        ScrollAlignment alignment;\n\n        if (m_frame->editor().behavior().shouldCenterAlignWhenSelectionIsRevealed())\n            alignment = (align == AlignCursorOnScrollAlways) ? ScrollAlignment::alignCenterAlways : ScrollAlignment::alignCenterIfNeeded;\n        else\n            alignment = (align == AlignCursorOnScrollAlways) ? ScrollAlignment::alignTopAlways : ScrollAlignment::alignToEdgeIfNeeded;\n\n        revealSelection(alignment, RevealExtent);\n    }\n\n    notifyAccessibilityForSelectionChange();\n    notifyCompositorForSelectionChange();\n    notifyEventHandlerForSelectionChange();\n    m_frame->localDOMWindow()->enqueueDocumentEvent(Event::create(EventTypeNames::selectionchange));\n}\n\nstatic bool removingNodeRemovesPosition(Node& node, const Position& position)\n{\n    if (!position.anchorNode())\n        return false;\n\n    if (position.anchorNode() == node)\n        return true;\n\n    if (!node.isElementNode())\n        return false;\n\n    Element& element = toElement(node);\n    return element.containsIncludingShadowDOM(position.anchorNode());\n}\n\nvoid FrameSelection::nodeWillBeRemoved(Node& node)\n{\n    \/\/ There can't be a selection inside a fragment, so if a fragment's node is being removed,\n    \/\/ the selection in the document that created the fragment needs no adjustment.\n    if (isNone() || !node.inActiveDocument())\n        return;\n\n    respondToNodeModification(node, removingNodeRemovesPosition(node, m_selection.base()), removingNodeRemovesPosition(node, m_selection.extent()),\n        removingNodeRemovesPosition(node, m_selection.start()), removingNodeRemovesPosition(node, m_selection.end()));\n}\n\nvoid FrameSelection::respondToNodeModification(Node& node, bool baseRemoved, bool extentRemoved, bool startRemoved, bool endRemoved)\n{\n    ASSERT(node.document().isActive());\n\n    bool clearRenderTreeSelection = false;\n    bool clearDOMTreeSelection = false;\n\n    if (startRemoved || endRemoved) {\n        Position start = m_selection.start();\n        Position end = m_selection.end();\n        if (startRemoved)\n            updatePositionForNodeRemoval(start, node);\n        if (endRemoved)\n            updatePositionForNodeRemoval(end, node);\n\n        if (start.isNotNull() && end.isNotNull()) {\n            if (m_selection.isBaseFirst())\n                m_selection.setWithoutValidation(start, end);\n            else\n                m_selection.setWithoutValidation(end, start);\n        } else\n            clearDOMTreeSelection = true;\n\n        clearRenderTreeSelection = true;\n    } else if (baseRemoved || extentRemoved) {\n        \/\/ The base and\/or extent are about to be removed, but the start and end aren't.\n        \/\/ Change the base and extent to the start and end, but don't re-validate the\n        \/\/ selection, since doing so could move the start and end into the node\n        \/\/ that is about to be removed.\n        if (m_selection.isBaseFirst())\n            m_selection.setWithoutValidation(m_selection.start(), m_selection.end());\n        else\n            m_selection.setWithoutValidation(m_selection.end(), m_selection.start());\n    } else if (m_selection.intersectsNode(&node)) {\n        \/\/ If we did nothing here, when this node's renderer was destroyed, the rect that it\n        \/\/ occupied would be invalidated, but, selection gaps that change as a result of\n        \/\/ the removal wouldn't be invalidated.\n        \/\/ FIXME: Don't do so much unnecessary invalidation.\n        clearRenderTreeSelection = true;\n    }\n\n    if (clearRenderTreeSelection)\n        m_selection.start().document()->renderView()->clearSelection();\n\n    if (clearDOMTreeSelection)\n        setSelection(VisibleSelection(), DoNotSetFocus);\n}\n\nstatic Position updatePositionAfterAdoptingTextReplacement(const Position& position, CharacterData* node, unsigned offset, unsigned oldLength, unsigned newLength)\n{\n    if (!position.anchorNode() || position.anchorNode() != node || position.anchorType() != Position::PositionIsOffsetInAnchor)\n        return position;\n\n    \/\/ See: http:\/\/www.w3.org\/TR\/DOM-Level-2-Traversal-Range\/ranges.html#Level-2-Range-Mutation\n    ASSERT(position.offsetInContainerNode() >= 0);\n    unsigned positionOffset = static_cast<unsigned>(position.offsetInContainerNode());\n    \/\/ Replacing text can be viewed as a deletion followed by insertion.\n    if (positionOffset >= offset && positionOffset <= offset + oldLength)\n        positionOffset = offset;\n\n    \/\/ Adjust the offset if the position is after the end of the deleted contents\n    \/\/ (positionOffset > offset + oldLength) to avoid having a stale offset.\n    if (positionOffset > offset + oldLength)\n        positionOffset = positionOffset - oldLength + newLength;\n\n    ASSERT_WITH_SECURITY_IMPLICATION(positionOffset <= node->length());\n    \/\/ CharacterNode in VisibleSelection must be Text node, because Comment\n    \/\/ and ProcessingInstruction node aren't visible.\n    return Position(toText(node), positionOffset);\n}\n\nvoid FrameSelection::didUpdateCharacterData(CharacterData* node, unsigned offset, unsigned oldLength, unsigned newLength)\n{\n    \/\/ The fragment check is a performance optimization. See http:\/\/trac.webkit.org\/changeset\/30062.\n    if (isNone() || !node || !node->inDocument())\n        return;\n\n    Position base = updatePositionAfterAdoptingTextReplacement(m_selection.base(), node, offset, oldLength, newLength);\n    Position extent = updatePositionAfterAdoptingTextReplacement(m_selection.extent(), node, offset, oldLength, newLength);\n    Position start = updatePositionAfterAdoptingTextReplacement(m_selection.start(), node, offset, oldLength, newLength);\n    Position end = updatePositionAfterAdoptingTextReplacement(m_selection.end(), node, offset, oldLength, newLength);\n    updateSelectionIfNeeded(base, extent, start, end);\n}\n\nstatic Position updatePostionAfterAdoptingTextNodesMerged(const Position& position, const Text& oldNode, unsigned offset)\n{\n    if (!position.anchorNode() || position.anchorType() != Position::PositionIsOffsetInAnchor)\n        return position;\n\n    ASSERT(position.offsetInContainerNode() >= 0);\n    unsigned positionOffset = static_cast<unsigned>(position.offsetInContainerNode());\n\n    if (position.anchorNode() == &oldNode)\n        return Position(toText(oldNode.previousSibling()), positionOffset + offset);\n\n    if (position.anchorNode() == oldNode.parentNode() && positionOffset == offset)\n        return Position(toText(oldNode.previousSibling()), offset);\n\n    return position;\n}\n\nvoid FrameSelection::didMergeTextNodes(const Text& oldNode, unsigned offset)\n{\n    if (isNone() || !oldNode.inDocument())\n        return;\n    Position base = updatePostionAfterAdoptingTextNodesMerged(m_selection.base(), oldNode, offset);\n    Position extent = updatePostionAfterAdoptingTextNodesMerged(m_selection.extent(), oldNode, offset);\n    Position start = updatePostionAfterAdoptingTextNodesMerged(m_selection.start(), oldNode, offset);\n    Position end = updatePostionAfterAdoptingTextNodesMerged(m_selection.end(), oldNode, offset);\n    updateSelectionIfNeeded(base, extent, start, end);\n}\n\nstatic Position updatePostionAfterAdoptingTextNodeSplit(const Position& position, const Text& oldNode)\n{\n    if (!position.anchorNode() || position.anchorNode() != &oldNode || position.anchorType() != Position::PositionIsOffsetInAnchor)\n        return position;\n    \/\/ See: http:\/\/www.w3.org\/TR\/DOM-Level-2-Traversal-Range\/ranges.html#Level-2-Range-Mutation\n    ASSERT(position.offsetInContainerNode() >= 0);\n    unsigned positionOffset = static_cast<unsigned>(position.offsetInContainerNode());\n    unsigned oldLength = oldNode.length();\n    if (positionOffset <= oldLength)\n        return position;\n    return Position(toText(oldNode.nextSibling()), positionOffset - oldLength);\n}\n\nvoid FrameSelection::didSplitTextNode(const Text& oldNode)\n{\n    if (isNone() || !oldNode.inDocument())\n        return;\n    Position base = updatePostionAfterAdoptingTextNodeSplit(m_selection.base(), oldNode);\n    Position extent = updatePostionAfterAdoptingTextNodeSplit(m_selection.extent(), oldNode);\n    Position start = updatePostionAfterAdoptingTextNodeSplit(m_selection.start(), oldNode);\n    Position end = updatePostionAfterAdoptingTextNodeSplit(m_selection.end(), oldNode);\n    updateSelectionIfNeeded(base, extent, start, end);\n}\n\nvoid FrameSelection::updateSelectionIfNeeded(const Position& base, const Position& extent, const Position& start, const Position& end)\n{\n    if (base == m_selection.base() && extent == m_selection.extent() && start == m_selection.start() && end == m_selection.end())\n        return;\n    VisibleSelection newSelection;\n    if (m_selection.isBaseFirst())\n        newSelection.setWithoutValidation(start, end);\n    else\n        newSelection.setWithoutValidation(end, start);\n    setSelection(newSelection, DoNotSetFocus);\n}\n\nTextDirection FrameSelection::directionOfEnclosingBlock()\n{\n    return blink::directionOfEnclosingBlock(m_selection.extent());\n}\n\nTextDirection FrameSelection::directionOfSelection()\n{\n    InlineBox* startBox = nullptr;\n    InlineBox* endBox = nullptr;\n    int unusedOffset;\n    \/\/ Cache the VisiblePositions because visibleStart() and visibleEnd()\n    \/\/ can cause layout, which has the potential to invalidate lineboxes.\n    VisiblePosition startPosition = m_selection.visibleStart();\n    VisiblePosition endPosition = m_selection.visibleEnd();\n    if (startPosition.isNotNull())\n        startPosition.getInlineBoxAndOffset(startBox, unusedOffset);\n    if (endPosition.isNotNull())\n        endPosition.getInlineBoxAndOffset(endBox, unusedOffset);\n    if (startBox && endBox && startBox->direction() == endBox->direction())\n        return startBox->direction();\n\n    return directionOfEnclosingBlock();\n}\n\nvoid FrameSelection::didChangeFocus()\n{\n    \/\/ Hits in virtual\/gpu\/compositedscrolling\/scrollbars\/scrollbar-miss-mousemove-disabled.html\n    DisableCompositingQueryAsserts disabler;\n    updateAppearance();\n}\n\nvoid FrameSelection::willBeModified(EAlteration alter, SelectionDirection direction)\n{\n    if (alter != AlterationExtend)\n        return;\n\n    Position start = m_selection.start();\n    Position end = m_selection.end();\n\n    bool baseIsStart = true;\n\n    if (m_selection.isDirectional()) {\n        \/\/ Make base and extent match start and end so we extend the user-visible selection.\n        \/\/ This only matters for cases where base and extend point to different positions than\n        \/\/ start and end (e.g. after a double-click to select a word).\n        if (m_selection.isBaseFirst())\n            baseIsStart = true;\n        else\n            baseIsStart = false;\n    } else {\n        switch (direction) {\n        case DirectionRight:\n            if (directionOfSelection() == LTR)\n                baseIsStart = true;\n            else\n                baseIsStart = false;\n            break;\n        case DirectionForward:\n            baseIsStart = true;\n            break;\n        case DirectionLeft:\n            if (directionOfSelection() == LTR)\n                baseIsStart = false;\n            else\n                baseIsStart = true;\n            break;\n        case DirectionBackward:\n            baseIsStart = false;\n            break;\n        }\n    }\n    if (baseIsStart) {\n        m_selection.setBase(start);\n        m_selection.setExtent(end);\n    } else {\n        m_selection.setBase(end);\n        m_selection.setExtent(start);\n    }\n}\n\nVisiblePosition FrameSelection::positionForPlatform(bool isGetStart) const\n{\n    Settings* settings = m_frame ? m_frame->settings() : 0;\n    if (settings && settings->editingBehaviorType() == EditingMacBehavior)\n        return isGetStart ? m_selection.visibleStart() : m_selection.visibleEnd();\n    \/\/ Linux and Windows always extend selections from the extent endpoint.\n    \/\/ FIXME: VisibleSelection should be fixed to ensure as an invariant that\n    \/\/ base\/extent always point to the same nodes as start\/end, but which points\n    \/\/ to which depends on the value of isBaseFirst. Then this can be changed\n    \/\/ to just return m_sel.extent().\n    return m_selection.isBaseFirst() ? m_selection.visibleEnd() : m_selection.visibleStart();\n}\n\nVisiblePosition FrameSelection::startForPlatform() const\n{\n    return positionForPlatform(true);\n}\n\nVisiblePosition FrameSelection::endForPlatform() const\n{\n    return positionForPlatform(false);\n}\n\nVisiblePosition FrameSelection::nextWordPositionForPlatform(const VisiblePosition &originalPosition)\n{\n    VisiblePosition positionAfterCurrentWord = nextWordPosition(originalPosition);\n\n    if (m_frame && m_frame->editor().behavior().shouldSkipSpaceWhenMovingRight()) {\n        \/\/ In order to skip spaces when moving right, we advance one\n        \/\/ word further and then move one word back. Given the\n        \/\/ semantics of previousWordPosition() this will put us at the\n        \/\/ beginning of the word following.\n        VisiblePosition positionAfterSpacingAndFollowingWord = nextWordPosition(positionAfterCurrentWord);\n        if (positionAfterSpacingAndFollowingWord.isNotNull() && positionAfterSpacingAndFollowingWord != positionAfterCurrentWord)\n            positionAfterCurrentWord = previousWordPosition(positionAfterSpacingAndFollowingWord);\n\n        bool movingBackwardsMovedPositionToStartOfCurrentWord = positionAfterCurrentWord == previousWordPosition(nextWordPosition(originalPosition));\n        if (movingBackwardsMovedPositionToStartOfCurrentWord)\n            positionAfterCurrentWord = positionAfterSpacingAndFollowingWord;\n    }\n    return positionAfterCurrentWord;\n}\n\nstatic void adjustPositionForUserSelectAll(VisiblePosition& pos, bool isForward)\n{\n    if (Node* rootUserSelectAll = Position::rootUserSelectAllForNode(pos.deepEquivalent().anchorNode()))\n        pos = VisiblePosition(isForward ? positionAfterNode(rootUserSelectAll).downstream(CanCrossEditingBoundary) : positionBeforeNode(rootUserSelectAll).upstream(CanCrossEditingBoundary));\n}\n\nVisiblePosition FrameSelection::modifyExtendingRight(TextGranularity granularity)\n{\n    VisiblePosition pos(m_selection.extent(), m_selection.affinity());\n\n    \/\/ The difference between modifyExtendingRight and modifyExtendingForward is:\n    \/\/ modifyExtendingForward always extends forward logically.\n    \/\/ modifyExtendingRight behaves the same as modifyExtendingForward except for extending character or word,\n    \/\/ it extends forward logically if the enclosing block is LTR direction,\n    \/\/ but it extends backward logically if the enclosing block is RTL direction.\n    switch (granularity) {\n    case CharacterGranularity:\n        if (directionOfEnclosingBlock() == LTR)\n            pos = pos.next(CanSkipOverEditingBoundary);\n        else\n            pos = pos.previous(CanSkipOverEditingBoundary);\n        break;\n    case WordGranularity:\n        if (directionOfEnclosingBlock() == LTR)\n            pos = nextWordPositionForPlatform(pos);\n        else\n            pos = previousWordPosition(pos);\n        break;\n    case LineBoundary:\n        if (directionOfEnclosingBlock() == LTR)\n            pos = modifyExtendingForward(granularity);\n        else\n            pos = modifyExtendingBackward(granularity);\n        break;\n    case SentenceGranularity:\n    case LineGranularity:\n    case ParagraphGranularity:\n    case SentenceBoundary:\n    case ParagraphBoundary:\n    case DocumentBoundary:\n        \/\/ FIXME: implement all of the above?\n        pos = modifyExtendingForward(granularity);\n        break;\n    }\n    adjustPositionForUserSelectAll(pos, directionOfEnclosingBlock() == LTR);\n    return pos;\n}\n\nVisiblePosition FrameSelection::modifyExtendingForward(TextGranularity granularity)\n{\n    VisiblePosition pos(m_selection.extent(), m_selection.affinity());\n    switch (granularity) {\n    case CharacterGranularity:\n        pos = pos.next(CanSkipOverEditingBoundary);\n        break;\n    case WordGranularity:\n        pos = nextWordPositionForPlatform(pos);\n        break;\n    case SentenceGranularity:\n        pos = nextSentencePosition(pos);\n        break;\n    case LineGranularity:\n        pos = nextLinePosition(pos, lineDirectionPointForBlockDirectionNavigation(EXTENT));\n        break;\n    case ParagraphGranularity:\n        pos = nextParagraphPosition(pos, lineDirectionPointForBlockDirectionNavigation(EXTENT));\n        break;\n    case SentenceBoundary:\n        pos = endOfSentence(endForPlatform());\n        break;\n    case LineBoundary:\n        pos = logicalEndOfLine(endForPlatform());\n        break;\n    case ParagraphBoundary:\n        pos = endOfParagraph(endForPlatform());\n        break;\n    case DocumentBoundary:\n        pos = endForPlatform();\n        if (isEditablePosition(pos.deepEquivalent()))\n            pos = endOfEditableContent(pos);\n        else\n            pos = endOfDocument(pos);\n        break;\n    }\n    adjustPositionForUserSelectAll(pos, directionOfEnclosingBlock() == LTR);\n    return pos;\n}\n\nVisiblePosition FrameSelection::modifyMovingRight(TextGranularity granularity)\n{\n    VisiblePosition pos;\n    switch (granularity) {\n    case CharacterGranularity:\n        if (isRange()) {\n            if (directionOfSelection() == LTR)\n                pos = VisiblePosition(m_selection.end(), m_selection.affinity());\n            else\n                pos = VisiblePosition(m_selection.start(), m_selection.affinity());\n        } else\n            pos = VisiblePosition(m_selection.extent(), m_selection.affinity()).right(true);\n        break;\n    case WordGranularity: {\n        bool skipsSpaceWhenMovingRight = m_frame && m_frame->editor().behavior().shouldSkipSpaceWhenMovingRight();\n        pos = rightWordPosition(VisiblePosition(m_selection.extent(), m_selection.affinity()), skipsSpaceWhenMovingRight);\n        break;\n    }\n    case SentenceGranularity:\n    case LineGranularity:\n    case ParagraphGranularity:\n    case SentenceBoundary:\n    case ParagraphBoundary:\n    case DocumentBoundary:\n        \/\/ FIXME: Implement all of the above.\n        pos = modifyMovingForward(granularity);\n        break;\n    case LineBoundary:\n        pos = rightBoundaryOfLine(startForPlatform(), directionOfEnclosingBlock());\n        break;\n    }\n    return pos;\n}\n\nVisiblePosition FrameSelection::modifyMovingForward(TextGranularity granularity)\n{\n    VisiblePosition pos;\n    \/\/ FIXME: Stay in editable content for the less common granularities.\n    switch (granularity) {\n    case CharacterGranularity:\n        if (isRange())\n            pos = VisiblePosition(m_selection.end(), m_selection.affinity());\n        else\n            pos = VisiblePosition(m_selection.extent(), m_selection.affinity()).next(CanSkipOverEditingBoundary);\n        break;\n    case WordGranularity:\n        pos = nextWordPositionForPlatform(VisiblePosition(m_selection.extent(), m_selection.affinity()));\n        break;\n    case SentenceGranularity:\n        pos = nextSentencePosition(VisiblePosition(m_selection.extent(), m_selection.affinity()));\n        break;\n    case LineGranularity: {\n        \/\/ down-arrowing from a range selection that ends at the start of a line needs\n        \/\/ to leave the selection at that line start (no need to call nextLinePosition!)\n        pos = endForPlatform();\n        if (!isRange() || !isStartOfLine(pos))\n            pos = nextLinePosition(pos, lineDirectionPointForBlockDirectionNavigation(START));\n        break;\n    }\n    case ParagraphGranularity:\n        pos = nextParagraphPosition(endForPlatform(), lineDirectionPointForBlockDirectionNavigation(START));\n        break;\n    case SentenceBoundary:\n        pos = endOfSentence(endForPlatform());\n        break;\n    case LineBoundary:\n        pos = logicalEndOfLine(endForPlatform());\n        break;\n    case ParagraphBoundary:\n        pos = endOfParagraph(endForPlatform());\n        break;\n    case DocumentBoundary:\n        pos = endForPlatform();\n        if (isEditablePosition(pos.deepEquivalent()))\n            pos = endOfEditableContent(pos);\n        else\n            pos = endOfDocument(pos);\n        break;\n    }\n    return pos;\n}\n\nVisiblePosition FrameSelection::modifyExtendingLeft(TextGranularity granularity)\n{\n    VisiblePosition pos(m_selection.extent(), m_selection.affinity());\n\n    \/\/ The difference between modifyExtendingLeft and modifyExtendingBackward is:\n    \/\/ modifyExtendingBackward always extends backward logically.\n    \/\/ modifyExtendingLeft behaves the same as modifyExtendingBackward except for extending character or word,\n    \/\/ it extends backward logically if the enclosing block is LTR direction,\n    \/\/ but it extends forward logically if the enclosing block is RTL direction.\n    switch (granularity) {\n    case CharacterGranularity:\n        if (directionOfEnclosingBlock() == LTR)\n            pos = pos.previous(CanSkipOverEditingBoundary);\n        else\n            pos = pos.next(CanSkipOverEditingBoundary);\n        break;\n    case WordGranularity:\n        if (directionOfEnclosingBlock() == LTR)\n            pos = previousWordPosition(pos);\n        else\n            pos = nextWordPositionForPlatform(pos);\n        break;\n    case LineBoundary:\n        if (directionOfEnclosingBlock() == LTR)\n            pos = modifyExtendingBackward(granularity);\n        else\n            pos = modifyExtendingForward(granularity);\n        break;\n    case SentenceGranularity:\n    case LineGranularity:\n    case ParagraphGranularity:\n    case SentenceBoundary:\n    case ParagraphBoundary:\n    case DocumentBoundary:\n        pos = modifyExtendingBackward(granularity);\n        break;\n    }\n    adjustPositionForUserSelectAll(pos, !(directionOfEnclosingBlock() == LTR));\n    return pos;\n}\n\nVisiblePosition FrameSelection::modifyExtendingBackward(TextGranularity granularity)\n{\n    VisiblePosition pos(m_selection.extent(), m_selection.affinity());\n\n    \/\/ Extending a selection backward by word or character from just after a table selects\n    \/\/ the table.  This \"makes sense\" from the user perspective, esp. when deleting.\n    \/\/ It was done here instead of in VisiblePosition because we want VPs to iterate\n    \/\/ over everything.\n    switch (granularity) {\n    case CharacterGranularity:\n        pos = pos.previous(CanSkipOverEditingBoundary);\n        break;\n    case WordGranularity:\n        pos = previousWordPosition(pos);\n        break;\n    case SentenceGranularity:\n        pos = previousSentencePosition(pos);\n        break;\n    case LineGranularity:\n        pos = previousLinePosition(pos, lineDirectionPointForBlockDirectionNavigation(EXTENT));\n        break;\n    case ParagraphGranularity:\n        pos = previousParagraphPosition(pos, lineDirectionPointForBlockDirectionNavigation(EXTENT));\n        break;\n    case SentenceBoundary:\n        pos = startOfSentence(startForPlatform());\n        break;\n    case LineBoundary:\n        pos = logicalStartOfLine(startForPlatform());\n        break;\n    case ParagraphBoundary:\n        pos = startOfParagraph(startForPlatform());\n        break;\n    case DocumentBoundary:\n        pos = startForPlatform();\n        if (isEditablePosition(pos.deepEquivalent()))\n            pos = startOfEditableContent(pos);\n        else\n            pos = startOfDocument(pos);\n        break;\n    }\n    adjustPositionForUserSelectAll(pos, !(directionOfEnclosingBlock() == LTR));\n    return pos;\n}\n\nVisiblePosition FrameSelection::modifyMovingLeft(TextGranularity granularity)\n{\n    VisiblePosition pos;\n    switch (granularity) {\n    case CharacterGranularity:\n        if (isRange())\n            if (directionOfSelection() == LTR)\n                pos = VisiblePosition(m_selection.start(), m_selection.affinity());\n            else\n                pos = VisiblePosition(m_selection.end(), m_selection.affinity());\n        else\n            pos = VisiblePosition(m_selection.extent(), m_selection.affinity()).left(true);\n        break;\n    case WordGranularity: {\n        bool skipsSpaceWhenMovingRight = m_frame && m_frame->editor().behavior().shouldSkipSpaceWhenMovingRight();\n        pos = leftWordPosition(VisiblePosition(m_selection.extent(), m_selection.affinity()), skipsSpaceWhenMovingRight);\n        break;\n    }\n    case SentenceGranularity:\n    case LineGranularity:\n    case ParagraphGranularity:\n    case SentenceBoundary:\n    case ParagraphBoundary:\n    case DocumentBoundary:\n        \/\/ FIXME: Implement all of the above.\n        pos = modifyMovingBackward(granularity);\n        break;\n    case LineBoundary:\n        pos = leftBoundaryOfLine(startForPlatform(), directionOfEnclosingBlock());\n        break;\n    }\n    return pos;\n}\n\nVisiblePosition FrameSelection::modifyMovingBackward(TextGranularity granularity)\n{\n    VisiblePosition pos;\n    switch (granularity) {\n    case CharacterGranularity:\n        if (isRange())\n            pos = VisiblePosition(m_selection.start(), m_selection.affinity());\n        else\n            pos = VisiblePosition(m_selection.extent(), m_selection.affinity()).previous(CanSkipOverEditingBoundary);\n        break;\n    case WordGranularity:\n        pos = previousWordPosition(VisiblePosition(m_selection.extent(), m_selection.affinity()));\n        break;\n    case SentenceGranularity:\n        pos = previousSentencePosition(VisiblePosition(m_selection.extent(), m_selection.affinity()));\n        break;\n    case LineGranularity:\n        pos = previousLinePosition(startForPlatform(), lineDirectionPointForBlockDirectionNavigation(START));\n        break;\n    case ParagraphGranularity:\n        pos = previousParagraphPosition(startForPlatform(), lineDirectionPointForBlockDirectionNavigation(START));\n        break;\n    case SentenceBoundary:\n        pos = startOfSentence(startForPlatform());\n        break;\n    case LineBoundary:\n        pos = logicalStartOfLine(startForPlatform());\n        break;\n    case ParagraphBoundary:\n        pos = startOfParagraph(startForPlatform());\n        break;\n    case DocumentBoundary:\n        pos = startForPlatform();\n        if (isEditablePosition(pos.deepEquivalent()))\n            pos = startOfEditableContent(pos);\n        else\n            pos = startOfDocument(pos);\n        break;\n    }\n    return pos;\n}\n\nstatic bool isBoundary(TextGranularity granularity)\n{\n    return granularity == LineBoundary || granularity == ParagraphBoundary || granularity == DocumentBoundary;\n}\n\nbool FrameSelection::modify(EAlteration alter, SelectionDirection direction, TextGranularity granularity, EUserTriggered userTriggered)\n{\n    if (userTriggered == UserTriggered) {\n        OwnPtrWillBeRawPtr<FrameSelection> trialFrameSelection = FrameSelection::create();\n        trialFrameSelection->setSelection(m_selection);\n        trialFrameSelection->modify(alter, direction, granularity, NotUserTriggered);\n\n        if (trialFrameSelection->selection().isRange() && m_selection.isCaret() && !dispatchSelectStart())\n            return false;\n    }\n\n    willBeModified(alter, direction);\n\n    bool wasRange = m_selection.isRange();\n    VisiblePosition originalStartPosition = m_selection.visibleStart();\n    VisiblePosition position;\n    switch (direction) {\n    case DirectionRight:\n        if (alter == AlterationMove)\n            position = modifyMovingRight(granularity);\n        else\n            position = modifyExtendingRight(granularity);\n        break;\n    case DirectionForward:\n        if (alter == AlterationExtend)\n            position = modifyExtendingForward(granularity);\n        else\n            position = modifyMovingForward(granularity);\n        break;\n    case DirectionLeft:\n        if (alter == AlterationMove)\n            position = modifyMovingLeft(granularity);\n        else\n            position = modifyExtendingLeft(granularity);\n        break;\n    case DirectionBackward:\n        if (alter == AlterationExtend)\n            position = modifyExtendingBackward(granularity);\n        else\n            position = modifyMovingBackward(granularity);\n        break;\n    }\n\n    if (position.isNull())\n        return false;\n\n    if (isSpatialNavigationEnabled(m_frame))\n        if (!wasRange && alter == AlterationMove && position == originalStartPosition)\n            return false;\n\n    \/\/ Some of the above operations set an xPosForVerticalArrowNavigation.\n    \/\/ Setting a selection will clear it, so save it to possibly restore later.\n    \/\/ Note: the START position type is arbitrary because it is unused, it would be\n    \/\/ the requested position type if there were no xPosForVerticalArrowNavigation set.\n    LayoutUnit x = lineDirectionPointForBlockDirectionNavigation(START);\n    m_selection.setIsDirectional(shouldAlwaysUseDirectionalSelection(m_frame) || alter == AlterationExtend);\n\n    switch (alter) {\n    case AlterationMove:\n        moveTo(position, userTriggered);\n        break;\n    case AlterationExtend:\n\n        if (!m_selection.isCaret()\n            && (granularity == WordGranularity || granularity == ParagraphGranularity || granularity == LineGranularity)\n            && m_frame && !m_frame->editor().behavior().shouldExtendSelectionByWordOrLineAcrossCaret()) {\n            \/\/ Don't let the selection go across the base position directly. Needed to match mac\n            \/\/ behavior when, for instance, word-selecting backwards starting with the caret in\n            \/\/ the middle of a word and then word-selecting forward, leaving the caret in the\n            \/\/ same place where it was, instead of directly selecting to the end of the word.\n            VisibleSelection newSelection = m_selection;\n            newSelection.setExtent(position);\n            if (m_selection.isBaseFirst() != newSelection.isBaseFirst())\n                position = m_selection.visibleBase();\n        }\n\n        \/\/ Standard Mac behavior when extending to a boundary is grow the selection rather than leaving the\n        \/\/ base in place and moving the extent. Matches NSTextView.\n        if (!m_frame || !m_frame->editor().behavior().shouldAlwaysGrowSelectionWhenExtendingToBoundary() || m_selection.isCaret() || !isBoundary(granularity))\n            setExtent(position, userTriggered);\n        else {\n            TextDirection textDirection = directionOfEnclosingBlock();\n            if (direction == DirectionForward || (textDirection == LTR && direction == DirectionRight) || (textDirection == RTL && direction == DirectionLeft))\n                setEnd(position, userTriggered);\n            else\n                setStart(position, userTriggered);\n        }\n        break;\n    }\n\n    if (granularity == LineGranularity || granularity == ParagraphGranularity)\n        m_xPosForVerticalArrowNavigation = x;\n\n    if (userTriggered == UserTriggered)\n        m_granularity = CharacterGranularity;\n\n    setCaretRectNeedsUpdate();\n\n    return true;\n}\n\n\/\/ FIXME: Maybe baseline would be better?\nstatic bool absoluteCaretY(const VisiblePosition &c, int &y)\n{\n    IntRect rect = c.absoluteCaretBounds();\n    if (rect.isEmpty())\n        return false;\n    y = rect.y() + rect.height() \/ 2;\n    return true;\n}\n\nbool FrameSelection::modify(EAlteration alter, unsigned verticalDistance, VerticalDirection direction, EUserTriggered userTriggered, CursorAlignOnScroll align)\n{\n    if (!verticalDistance)\n        return false;\n\n    if (userTriggered == UserTriggered) {\n        OwnPtrWillBeRawPtr<FrameSelection> trialFrameSelection = FrameSelection::create();\n        trialFrameSelection->setSelection(m_selection);\n        trialFrameSelection->modify(alter, verticalDistance, direction, NotUserTriggered);\n    }\n\n    willBeModified(alter, direction == DirectionUp ? DirectionBackward : DirectionForward);\n\n    VisiblePosition pos;\n    LayoutUnit xPos = 0;\n    switch (alter) {\n    case AlterationMove:\n        pos = VisiblePosition(direction == DirectionUp ? m_selection.start() : m_selection.end(), m_selection.affinity());\n        xPos = lineDirectionPointForBlockDirectionNavigation(direction == DirectionUp ? START : END);\n        m_selection.setAffinity(direction == DirectionUp ? UPSTREAM : DOWNSTREAM);\n        break;\n    case AlterationExtend:\n        pos = VisiblePosition(m_selection.extent(), m_selection.affinity());\n        xPos = lineDirectionPointForBlockDirectionNavigation(EXTENT);\n        m_selection.setAffinity(DOWNSTREAM);\n        break;\n    }\n\n    int startY;\n    if (!absoluteCaretY(pos, startY))\n        return false;\n    if (direction == DirectionUp)\n        startY = -startY;\n    int lastY = startY;\n\n    VisiblePosition result;\n    VisiblePosition next;\n    for (VisiblePosition p = pos; ; p = next) {\n        if (direction == DirectionUp)\n            next = previousLinePosition(p, xPos);\n        else\n            next = nextLinePosition(p, xPos);\n\n        if (next.isNull() || next == p)\n            break;\n        int nextY;\n        if (!absoluteCaretY(next, nextY))\n            break;\n        if (direction == DirectionUp)\n            nextY = -nextY;\n        if (nextY - startY > static_cast<int>(verticalDistance))\n            break;\n        if (nextY >= lastY) {\n            lastY = nextY;\n            result = next;\n        }\n    }\n\n    if (result.isNull())\n        return false;\n\n    switch (alter) {\n    case AlterationMove:\n        moveTo(result, userTriggered, align);\n        break;\n    case AlterationExtend:\n        setExtent(result, userTriggered);\n        break;\n    }\n\n    if (userTriggered == UserTriggered)\n        m_granularity = CharacterGranularity;\n\n    m_selection.setIsDirectional(shouldAlwaysUseDirectionalSelection(m_frame) || alter == AlterationExtend);\n\n    return true;\n}\n\nLayoutUnit FrameSelection::lineDirectionPointForBlockDirectionNavigation(EPositionType type)\n{\n    LayoutUnit x = 0;\n\n    if (isNone())\n        return x;\n\n    Position pos;\n    switch (type) {\n    case START:\n        pos = m_selection.start();\n        break;\n    case END:\n        pos = m_selection.end();\n        break;\n    case BASE:\n        pos = m_selection.base();\n        break;\n    case EXTENT:\n        pos = m_selection.extent();\n        break;\n    }\n\n    LocalFrame* frame = pos.document()->frame();\n    if (!frame)\n        return x;\n\n    if (m_xPosForVerticalArrowNavigation == NoXPosForVerticalArrowNavigation()) {\n        VisiblePosition visiblePosition(pos, m_selection.affinity());\n        \/\/ VisiblePosition creation can fail here if a node containing the selection becomes visibility:hidden\n        \/\/ after the selection is created and before this function is called.\n        x = visiblePosition.isNotNull() ? visiblePosition.lineDirectionPointForBlockDirectionNavigation() : 0;\n        m_xPosForVerticalArrowNavigation = x;\n    } else\n        x = m_xPosForVerticalArrowNavigation;\n\n    return x;\n}\n\nvoid FrameSelection::clear()\n{\n    m_granularity = CharacterGranularity;\n    setSelection(VisibleSelection());\n}\n\nvoid FrameSelection::prepareForDestruction()\n{\n    m_granularity = CharacterGranularity;\n\n    m_caretBlinkTimer.stop();\n\n    RenderView* view = m_frame->contentRenderer();\n    if (view)\n        view->clearSelection();\n\n    setSelection(VisibleSelection(), CloseTyping | ClearTypingStyle | DoNotUpdateAppearance);\n    m_previousCaretNode.clear();\n}\n\nvoid FrameSelection::setStart(const VisiblePosition &pos, EUserTriggered trigger)\n{\n    if (m_selection.isBaseFirst())\n        setBase(pos, trigger);\n    else\n        setExtent(pos, trigger);\n}\n\nvoid FrameSelection::setEnd(const VisiblePosition &pos, EUserTriggered trigger)\n{\n    if (m_selection.isBaseFirst())\n        setExtent(pos, trigger);\n    else\n        setBase(pos, trigger);\n}\n\nvoid FrameSelection::setBase(const VisiblePosition &pos, EUserTriggered userTriggered)\n{\n    const bool selectionHasDirection = true;\n    setSelection(VisibleSelection(pos.deepEquivalent(), m_selection.extent(), pos.affinity(), selectionHasDirection), CloseTyping | ClearTypingStyle | userTriggered);\n}\n\nvoid FrameSelection::setExtent(const VisiblePosition &pos, EUserTriggered userTriggered)\n{\n    const bool selectionHasDirection = true;\n    setSelection(VisibleSelection(m_selection.base(), pos.deepEquivalent(), pos.affinity(), selectionHasDirection), CloseTyping | ClearTypingStyle | userTriggered);\n}\n\nRenderBlock* FrameSelection::caretRenderer() const\n{\n    return CaretBase::caretRenderer(m_selection.start().deprecatedNode());\n}\n\nstatic bool isNonOrphanedCaret(const VisibleSelection& selection)\n{\n    return selection.isCaret() && !selection.start().isOrphan() && !selection.end().isOrphan();\n}\n\nstatic bool isTextFormControl(const VisibleSelection& selection)\n{\n    return enclosingTextFormControl(selection.start());\n}\n\nIntRect FrameSelection::absoluteCaretBounds()\n{\n    ASSERT(m_frame->document()->lifecycle().state() != DocumentLifecycle::InPaintInvalidation);\n    m_frame->document()->updateLayoutIgnorePendingStylesheets();\n    if (!isNonOrphanedCaret(m_selection)) {\n        clearCaretRect();\n    } else {\n        if (isTextFormControl(m_selection))\n            updateCaretRect(m_frame->document(), PositionWithAffinity(m_selection.start().isCandidate() ? m_selection.start() : Position(), m_selection.affinity()));\n        else\n            updateCaretRect(m_frame->document(), VisiblePosition(m_selection.start(), m_selection.affinity()));\n    }\n    return absoluteBoundsForLocalRect(m_selection.start().deprecatedNode(), localCaretRectWithoutUpdate());\n}\n\nstatic LayoutRect localCaretRect(const VisibleSelection& m_selection, const PositionWithAffinity& caretPosition, RenderObject*& renderer)\n{\n    renderer = nullptr;\n    if (!isNonOrphanedCaret(m_selection))\n        return LayoutRect();\n\n    return localCaretRectOfPosition(caretPosition, renderer);\n}\n\nvoid FrameSelection::invalidateCaretRect()\n{\n    if (!m_caretRectDirty)\n        return;\n    m_caretRectDirty = false;\n\n    RenderObject* renderer = nullptr;\n    LayoutRect newRect = localCaretRect(m_selection, PositionWithAffinity(m_selection.start(), m_selection.affinity()), renderer);\n    Node* newNode = renderer ? renderer->node() : nullptr;\n\n    if (!m_caretBlinkTimer.isActive() && newNode == m_previousCaretNode && newRect == m_previousCaretRect)\n        return;\n\n    RenderView* view = m_frame->document()->renderView();\n    if (m_previousCaretNode && (shouldRepaintCaret(*m_previousCaretNode) || shouldRepaintCaret(view)))\n        invalidateLocalCaretRect(m_previousCaretNode.get(), m_previousCaretRect);\n    if (newNode && (shouldRepaintCaret(*newNode) || shouldRepaintCaret(view)))\n        invalidateLocalCaretRect(newNode, newRect);\n\n    m_previousCaretNode = newNode;\n    m_previousCaretRect = newRect;\n}\n\nvoid FrameSelection::paintCaret(GraphicsContext* context, const LayoutPoint& paintOffset, const LayoutRect& clipRect)\n{\n    if (m_selection.isCaret() && m_shouldPaintCaret) {\n        updateCaretRect(m_frame->document(), PositionWithAffinity(m_selection.start(), m_selection.affinity()));\n        CaretBase::paintCaret(m_selection.start().deprecatedNode(), context, paintOffset, clipRect);\n    }\n}\n\nbool FrameSelection::contains(const LayoutPoint& point)\n{\n    Document* document = m_frame->document();\n\n    \/\/ Treat a collapsed selection like no selection.\n    if (!isRange())\n        return false;\n    if (!document->renderView())\n        return false;\n\n    HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);\n    HitTestResult result(point);\n    document->renderView()->hitTest(request, result);\n    Node* innerNode = result.innerNode();\n    if (!innerNode || !innerNode->renderer())\n        return false;\n\n    VisiblePosition visiblePos(innerNode->renderer()->positionForPoint(result.localPoint()));\n    if (visiblePos.isNull())\n        return false;\n\n    if (m_selection.visibleStart().isNull() || m_selection.visibleEnd().isNull())\n        return false;\n\n    Position start(m_selection.visibleStart().deepEquivalent());\n    Position end(m_selection.visibleEnd().deepEquivalent());\n    Position p(visiblePos.deepEquivalent());\n\n    return comparePositions(start, p) <= 0 && comparePositions(p, end) <= 0;\n}\n\n\/\/ Workaround for the fact that it's hard to delete a frame.\n\/\/ Call this after doing user-triggered selections to make it easy to delete the frame you entirely selected.\n\/\/ Can't do this implicitly as part of every setSelection call because in some contexts it might not be good\n\/\/ for the focus to move to another frame. So instead we call it from places where we are selecting with the\n\/\/ mouse or the keyboard after setting the selection.\nvoid FrameSelection::selectFrameElementInParentIfFullySelected()\n{\n    \/\/ Find the parent frame; if there is none, then we have nothing to do.\n    Frame* parent = m_frame->tree().parent();\n    if (!parent)\n        return;\n    Page* page = m_frame->page();\n    if (!page)\n        return;\n\n    \/\/ Check if the selection contains the entire frame contents; if not, then there is nothing to do.\n    if (!isRange())\n        return;\n    if (!isStartOfDocument(selection().visibleStart()))\n        return;\n    if (!isEndOfDocument(selection().visibleEnd()))\n        return;\n\n    \/\/ FIXME: This is not yet implemented for cross-process frame relationships.\n    if (!parent->isLocalFrame())\n        return;\n\n    \/\/ Get to the <iframe> or <frame> (or even <object>) element in the parent frame.\n    \/\/ FIXME: Doesn't work for OOPI.\n    HTMLFrameOwnerElement* ownerElement = m_frame->deprecatedLocalOwner();\n    if (!ownerElement)\n        return;\n    ContainerNode* ownerElementParent = ownerElement->parentNode();\n    if (!ownerElementParent)\n        return;\n\n    \/\/ This method's purpose is it to make it easier to select iframes (in order to delete them).  Don't do anything if the iframe isn't deletable.\n    if (!ownerElementParent->hasEditableStyle())\n        return;\n\n    \/\/ Create compute positions before and after the element.\n    unsigned ownerElementNodeIndex = ownerElement->nodeIndex();\n    VisiblePosition beforeOwnerElement(VisiblePosition(Position(ownerElementParent, ownerElementNodeIndex, Position::PositionIsOffsetInAnchor)));\n    VisiblePosition afterOwnerElement(VisiblePosition(Position(ownerElementParent, ownerElementNodeIndex + 1, Position::PositionIsOffsetInAnchor), VP_UPSTREAM_IF_POSSIBLE));\n\n    \/\/ Focus on the parent frame, and then select from before this element to after.\n    VisibleSelection newSelection(beforeOwnerElement, afterOwnerElement);\n    page->focusController().setFocusedFrame(parent);\n    toLocalFrame(parent)->selection().setSelection(newSelection);\n}\n\nvoid FrameSelection::selectAll()\n{\n    Document* document = m_frame->document();\n\n    if (isHTMLSelectElement(document->focusedElement())) {\n        HTMLSelectElement* selectElement = toHTMLSelectElement(document->focusedElement());\n        if (selectElement->canSelectAll()) {\n            selectElement->selectAll();\n            return;\n        }\n    }\n\n    RefPtrWillBeRawPtr<Node> root = nullptr;\n    Node* selectStartTarget = nullptr;\n    if (isContentEditable()) {\n        root = highestEditableRoot(m_selection.start());\n        if (Node* shadowRoot = m_selection.nonBoundaryShadowTreeRootNode())\n            selectStartTarget = shadowRoot->shadowHost();\n        else\n            selectStartTarget = root.get();\n    } else {\n        root = m_selection.nonBoundaryShadowTreeRootNode();\n        if (root)\n            selectStartTarget = root->shadowHost();\n        else {\n            root = document->documentElement();\n            selectStartTarget = document->body();\n        }\n    }\n    if (!root)\n        return;\n\n    if (selectStartTarget && !selectStartTarget->dispatchEvent(Event::createCancelableBubble(EventTypeNames::selectstart)))\n        return;\n\n    VisibleSelection newSelection(VisibleSelection::selectionFromContentsOfNode(root.get()));\n    setSelection(newSelection);\n    selectFrameElementInParentIfFullySelected();\n    notifyRendererOfSelectionChange(UserTriggered);\n}\n\nbool FrameSelection::setSelectedRange(Range* range, EAffinity affinity, DirectoinalOption directional, SetSelectionOptions options)\n{\n    if (!range || !range->startContainer() || !range->endContainer())\n        return false;\n    ASSERT(range->startContainer()->document() == range->endContainer()->document());\n\n    \/\/ Non-collapsed ranges are not allowed to start at the end of a line that is wrapped,\n    \/\/ they start at the beginning of the next line instead\n    m_logicalRange = nullptr;\n    stopObservingVisibleSelectionChangeIfNecessary();\n\n    VisibleSelection newSelection(range, affinity, directional == Directional);\n    setSelection(newSelection, options);\n\n    m_logicalRange = range->cloneRange();\n    startObservingVisibleSelectionChange();\n\n    return true;\n}\n\nPassRefPtrWillBeRawPtr<Range> FrameSelection::firstRange() const\n{\n    if (m_logicalRange)\n        return m_logicalRange->cloneRange();\n    return m_selection.firstRange();\n}\n\nbool FrameSelection::isInPasswordField() const\n{\n    HTMLTextFormControlElement* textControl = enclosingTextFormControl(start());\n    return isHTMLInputElement(textControl) && toHTMLInputElement(textControl)->type() == InputTypeNames::password;\n}\n\nvoid FrameSelection::notifyAccessibilityForSelectionChange()\n{\n    if (m_selection.start().isNotNull() && m_selection.end().isNotNull()) {\n        if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())\n            cache->selectionChanged(m_selection.start().containerNode());\n    }\n}\n\nvoid FrameSelection::notifyCompositorForSelectionChange()\n{\n    if (!RuntimeEnabledFeatures::compositedSelectionUpdateEnabled())\n        return;\n\n    scheduleVisualUpdate();\n}\n\nvoid FrameSelection::notifyEventHandlerForSelectionChange()\n{\n    m_frame->eventHandler().notifySelectionChanged();\n}\n\nvoid FrameSelection::focusedOrActiveStateChanged()\n{\n    bool activeAndFocused = isFocusedAndActive();\n\n    RefPtrWillBeRawPtr<Document> document = m_frame->document();\n    document->updateRenderTreeIfNeeded();\n\n    \/\/ Because RenderObject::selectionBackgroundColor() and\n    \/\/ RenderObject::selectionForegroundColor() check if the frame is active,\n    \/\/ we have to update places those colors were painted.\n    if (RenderView* view = document->renderView())\n        view->invalidatePaintForSelection();\n\n    \/\/ Caret appears in the active frame.\n    if (activeAndFocused)\n        setSelectionFromNone();\n    else\n        m_frame->spellChecker().spellCheckAfterBlur();\n    setCaretVisibility(activeAndFocused ? Visible : Hidden);\n\n    \/\/ Update for caps lock state\n    m_frame->eventHandler().capsLockStateMayHaveChanged();\n\n    \/\/ We may have lost active status even though the focusElement hasn't changed\n    \/\/ give the element a chance to recalc style if its affected by focus.\n    if (Element* element = document->focusedElement())\n        element->focusStateChanged();\n\n    \/\/ Secure keyboard entry is set by the active frame.\n    if (document->useSecureKeyboardEntryWhenActive())\n        setUseSecureKeyboardEntry(activeAndFocused);\n}\n\nvoid FrameSelection::pageActivationChanged()\n{\n    focusedOrActiveStateChanged();\n}\n\nvoid FrameSelection::updateSecureKeyboardEntryIfActive()\n{\n    if (m_frame->document() && isFocusedAndActive())\n        setUseSecureKeyboardEntry(m_frame->document()->useSecureKeyboardEntryWhenActive());\n}\n\nvoid FrameSelection::setUseSecureKeyboardEntry(bool enable)\n{\n    if (enable)\n        enableSecureTextInput();\n    else\n        disableSecureTextInput();\n}\n\nvoid FrameSelection::setFocused(bool flag)\n{\n    if (m_focused == flag)\n        return;\n    m_focused = flag;\n\n    focusedOrActiveStateChanged();\n}\n\nbool FrameSelection::isFocusedAndActive() const\n{\n    return m_focused && m_frame->page() && m_frame->page()->focusController().isActive();\n}\n\ninline static bool shouldStopBlinkingDueToTypingCommand(LocalFrame* frame)\n{\n    return frame->editor().lastEditCommand() && frame->editor().lastEditCommand()->shouldStopCaretBlinking();\n}\n\nvoid FrameSelection::updateAppearance(ResetCaretBlinkOption option)\n{\n    \/\/ Paint a block cursor instead of a caret in overtype mode unless the caret is at the end of a line (in this case\n    \/\/ the FrameSelection will paint a blinking caret as usual).\n    bool paintBlockCursor = m_shouldShowBlockCursor && m_selection.isCaret() && !isLogicalEndOfLine(m_selection.visibleEnd());\n\n    bool shouldBlink = !paintBlockCursor && shouldBlinkCaret();\n\n    bool willNeedCaretRectUpdate = false;\n\n    \/\/ If the caret moved, stop the blink timer so we can restart with a\n    \/\/ black caret in the new location.\n    if (option == ResetCaretBlink || !shouldBlink || shouldStopBlinkingDueToTypingCommand(m_frame)) {\n        m_caretBlinkTimer.stop();\n\n        m_shouldPaintCaret = false;\n        willNeedCaretRectUpdate = true;\n    }\n\n    \/\/ Start blinking with a black caret. Be sure not to restart if we're\n    \/\/ already blinking in the right location.\n    if (shouldBlink && !m_caretBlinkTimer.isActive()) {\n        if (double blinkInterval = RenderTheme::theme().caretBlinkInterval())\n            m_caretBlinkTimer.startRepeating(blinkInterval, FROM_HERE);\n\n        m_shouldPaintCaret = true;\n        willNeedCaretRectUpdate = true;\n    }\n\n    if (willNeedCaretRectUpdate)\n        setCaretRectNeedsUpdate();\n\n    RenderView* view = m_frame->contentRenderer();\n    if (view)\n        view->setSelection(*this);\n}\n\nvoid FrameSelection::setCaretVisibility(CaretVisibility visibility)\n{\n    if (caretVisibility() == visibility)\n        return;\n\n    CaretBase::setCaretVisibility(visibility);\n\n    updateAppearance();\n}\n\nbool FrameSelection::shouldBlinkCaret() const\n{\n    if (!caretIsVisible() || !isCaret())\n        return false;\n\n    if (m_frame->settings() && m_frame->settings()->caretBrowsingEnabled())\n        return false;\n\n    Element* root = rootEditableElement();\n    if (!root)\n        return false;\n\n    Element* focusedElement = root->document().focusedElement();\n    if (!focusedElement)\n        return false;\n\n    return focusedElement->containsIncludingShadowDOM(m_selection.start().anchorNode());\n}\n\nvoid FrameSelection::caretBlinkTimerFired(Timer<FrameSelection>*)\n{\n    ASSERT(caretIsVisible());\n    ASSERT(isCaret());\n    if (isCaretBlinkingSuspended() && m_shouldPaintCaret)\n        return;\n    m_shouldPaintCaret = !m_shouldPaintCaret;\n    setCaretRectNeedsUpdate();\n}\n\nvoid FrameSelection::notifyRendererOfSelectionChange(EUserTriggered userTriggered)\n{\n    if (HTMLTextFormControlElement* textControl = enclosingTextFormControl(start()))\n        textControl->selectionChanged(userTriggered == UserTriggered);\n}\n\n\/\/ Helper function that tells whether a particular node is an element that has an entire\n\/\/ LocalFrame and FrameView, a <frame>, <iframe>, or <object>.\nstatic bool isFrameElement(const Node* n)\n{\n    if (!n)\n        return false;\n    RenderObject* renderer = n->renderer();\n    if (!renderer || !renderer->isRenderPart())\n        return false;\n    Widget* widget = toRenderPart(renderer)->widget();\n    return widget && widget->isFrameView();\n}\n\nvoid FrameSelection::setFocusedNodeIfNeeded()\n{\n    if (isNone() || !isFocused())\n        return;\n\n    bool caretBrowsing = m_frame->settings() && m_frame->settings()->caretBrowsingEnabled();\n    if (caretBrowsing) {\n        if (Element* anchor = enclosingAnchorElement(base())) {\n            m_frame->page()->focusController().setFocusedElement(anchor, m_frame);\n            return;\n        }\n    }\n\n    if (Element* target = rootEditableElement()) {\n        \/\/ Walk up the DOM tree to search for a node to focus.\n        while (target) {\n            \/\/ We don't want to set focus on a subframe when selecting in a parent frame,\n            \/\/ so add the !isFrameElement check here. There's probably a better way to make this\n            \/\/ work in the long term, but this is the safest fix at this time.\n            if (target->isMouseFocusable() && !isFrameElement(target)) {\n                m_frame->page()->focusController().setFocusedElement(target, m_frame);\n                return;\n            }\n            target = target->parentOrShadowHostElement();\n        }\n        m_frame->document()->setFocusedElement(nullptr);\n    }\n\n    if (caretBrowsing)\n        m_frame->page()->focusController().setFocusedElement(0, m_frame);\n}\n\nstatic String extractSelectedText(const FrameSelection& selection, TextIteratorBehavior behavior)\n{\n    \/\/ We remove '\\0' characters because they are not visibly rendered to the user.\n    return plainText(selection.toNormalizedRange().get(), behavior).replace(0, \"\");\n}\n\nString FrameSelection::selectedText() const\n{\n    return extractSelectedText(*this, TextIteratorDefaultBehavior);\n}\n\nString FrameSelection::selectedTextForClipboard() const\n{\n    if (m_frame->settings() && m_frame->settings()->selectionIncludesAltImageText())\n        return extractSelectedText(*this, TextIteratorEmitsImageAltText);\n    return selectedText();\n}\n\nLayoutRect FrameSelection::bounds() const\n{\n    FrameView* view = m_frame->view();\n    if (!view)\n        return LayoutRect();\n\n    return intersection(unclippedBounds(), view->visibleContentRect());\n}\n\nLayoutRect FrameSelection::unclippedBounds() const\n{\n    m_frame->document()->updateRenderTreeIfNeeded();\n\n    FrameView* view = m_frame->view();\n    RenderView* renderView = m_frame->contentRenderer();\n\n    if (!view || !renderView)\n        return LayoutRect();\n\n    return renderView->selectionBounds();\n}\n\nstatic inline HTMLFormElement* associatedFormElement(HTMLElement& element)\n{\n    if (isHTMLFormElement(element))\n        return &toHTMLFormElement(element);\n    return element.formOwner();\n}\n\n\/\/ Scans logically forward from \"start\", including any child frames.\nstatic HTMLFormElement* scanForForm(Node* start)\n{\n    if (!start)\n        return 0;\n\n    for (HTMLElement& element : Traversal<HTMLElement>::startsAt(start->isHTMLElement() ? toHTMLElement(start) : Traversal<HTMLElement>::next(*start))) {\n        if (HTMLFormElement* form = associatedFormElement(element))\n            return form;\n\n        if (isHTMLFrameElementBase(element)) {\n            Node* childDocument = toHTMLFrameElementBase(element).contentDocument();\n            if (HTMLFormElement* frameResult = scanForForm(childDocument))\n                return frameResult;\n        }\n    }\n    return 0;\n}\n\n\/\/ We look for either the form containing the current focus, or for one immediately after it\nHTMLFormElement* FrameSelection::currentForm() const\n{\n    \/\/ Start looking either at the active (first responder) node, or where the selection is.\n    Node* start = m_frame->document()->focusedElement();\n    if (!start)\n        start = this->start().deprecatedNode();\n    if (!start)\n        return 0;\n\n    \/\/ Try walking up the node tree to find a form element.\n    for (HTMLElement* element = Traversal<HTMLElement>::firstAncestorOrSelf(*start); element; element = Traversal<HTMLElement>::firstAncestor(*element)) {\n        if (HTMLFormElement* form = associatedFormElement(*element))\n            return form;\n    }\n\n    \/\/ Try walking forward in the node tree to find a form element.\n    return scanForForm(start);\n}\n\nvoid FrameSelection::revealSelection(const ScrollAlignment& alignment, RevealExtentOption revealExtentOption)\n{\n    LayoutRect rect;\n\n    switch (selectionType()) {\n    case NoSelection:\n        return;\n    case CaretSelection:\n        rect = absoluteCaretBounds();\n        break;\n    case RangeSelection:\n        rect = revealExtentOption == RevealExtent ? VisiblePosition(extent()).absoluteCaretBounds() : enclosingIntRect(unclippedBounds());\n        break;\n    }\n\n    Position start = this->start();\n    ASSERT(start.deprecatedNode());\n    if (start.deprecatedNode() && start.deprecatedNode()->renderer()) {\n        \/\/ FIXME: This code only handles scrolling the startContainer's layer, but\n        \/\/ the selection rect could intersect more than just that.\n        \/\/ See <rdar:\/\/problem\/4799899>.\n        if (start.deprecatedNode()->renderer()->scrollRectToVisible(rect, alignment, alignment))\n            updateAppearance();\n    }\n}\n\nvoid FrameSelection::setSelectionFromNone()\n{\n    \/\/ Put a caret inside the body if the entire frame is editable (either the\n    \/\/ entire WebView is editable or designMode is on for this document).\n\n    Document* document = m_frame->document();\n    bool caretBrowsing = m_frame->settings() && m_frame->settings()->caretBrowsingEnabled();\n    if (!isNone() || !(document->hasEditableStyle() || caretBrowsing))\n        return;\n\n    Element* documentElement = document->documentElement();\n    if (!documentElement)\n        return;\n    if (HTMLBodyElement* body = Traversal<HTMLBodyElement>::firstChild(*documentElement))\n        setSelection(VisibleSelection(firstPositionInOrBeforeNode(body), DOWNSTREAM));\n}\n\nbool FrameSelection::dispatchSelectStart()\n{\n    Node* selectStartTarget = m_selection.extent().containerNode();\n    if (!selectStartTarget)\n        return true;\n\n    return selectStartTarget->dispatchEvent(Event::createCancelableBubble(EventTypeNames::selectstart));\n}\n\nvoid FrameSelection::setShouldShowBlockCursor(bool shouldShowBlockCursor)\n{\n    m_shouldShowBlockCursor = shouldShowBlockCursor;\n\n    m_frame->document()->updateLayoutIgnorePendingStylesheets();\n\n    updateAppearance();\n}\n\nvoid FrameSelection::didChangeVisibleSelection()\n{\n    ASSERT(m_observingVisibleSelection);\n    \/\/ Invalidate the logical range when the underlying VisibleSelection has changed.\n    m_logicalRange = nullptr;\n    m_selection.clearChangeObserver();\n    m_observingVisibleSelection = false;\n}\n\nVisibleSelection FrameSelection::validateSelection(const VisibleSelection& selection)\n{\n    if (!m_frame || selection.isNone())\n        return selection;\n\n    Position base = selection.base();\n    Position extent = selection.extent();\n    bool isBaseValid = base.document() == m_frame->document();\n    bool isExtentValid = extent.document() == m_frame->document();\n\n    if (isBaseValid && isExtentValid)\n        return selection;\n\n    VisibleSelection newSelection;\n    if (isBaseValid) {\n        newSelection.setWithoutValidation(base, base);\n    } else if (isExtentValid) {\n        newSelection.setWithoutValidation(extent, extent);\n    }\n    return newSelection;\n}\n\nvoid FrameSelection::startObservingVisibleSelectionChange()\n{\n    ASSERT(!m_observingVisibleSelection);\n    m_selection.setChangeObserver(*this);\n    m_observingVisibleSelection = true;\n}\n\nvoid FrameSelection::stopObservingVisibleSelectionChangeIfNecessary()\n{\n    if (m_observingVisibleSelection) {\n        m_selection.clearChangeObserver();\n        m_observingVisibleSelection = false;\n    }\n}\n\n#ifndef NDEBUG\n\nvoid FrameSelection::formatForDebugger(char* buffer, unsigned length) const\n{\n    m_selection.formatForDebugger(buffer, length);\n}\n\nvoid FrameSelection::showTreeForThis() const\n{\n    m_selection.showTreeForThis();\n}\n\n#endif\n\nvoid FrameSelection::trace(Visitor* visitor)\n{\n    visitor->trace(m_frame);\n    visitor->trace(m_selection);\n    visitor->trace(m_originalBase);\n    visitor->trace(m_logicalRange);\n    visitor->trace(m_previousCaretNode);\n    visitor->trace(m_typingStyle);\n    VisibleSelection::ChangeObserver::trace(visitor);\n}\n\nvoid FrameSelection::setCaretRectNeedsUpdate()\n{\n    m_caretRectDirty = true;\n\n    scheduleVisualUpdate();\n}\n\nvoid FrameSelection::scheduleVisualUpdate() const\n{\n    if (!m_frame)\n        return;\n    if (Page* page = m_frame->page())\n        page->animator().scheduleVisualUpdate();\n}\n\nbool FrameSelection::selectWordAroundPosition(const VisiblePosition& position)\n{\n    static const EWordSide wordSideList[2] = { RightWordIfOnBoundary, LeftWordIfOnBoundary };\n    for (EWordSide wordSide : wordSideList) {\n        VisiblePosition start = startOfWord(position, wordSide);\n        VisiblePosition end = endOfWord(position, wordSide);\n        String text = plainText(start.deepEquivalent(), end.deepEquivalent());\n        if (!text.isEmpty() && !isSeparator(text.characterStartingAt(0))) {\n            setSelection(VisibleSelection(start, end), WordGranularity);\n            return true;\n        }\n    }\n\n    return false;\n}\n\n}\n\n#ifndef NDEBUG\n\nvoid showTree(const blink::FrameSelection& sel)\n{\n    sel.showTreeForThis();\n}\n\nvoid showTree(const blink::FrameSelection* sel)\n{\n    if (sel)\n        sel->showTreeForThis();\n}\n\n#endif\n","avg_line_length":37.0368831169,"max_line_length":190,"alphanum_fraction":0.7067717684,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1106,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\n#include \"graphtype.h\"\n#include \"graphtype.cpp\"\n\nusing namespace std;\n\nint main()\n{\n    GraphType<char> G1;\n    G1.AddVertex('A');\n    G1.AddVertex('B');\n    G1.AddVertex('C');\n    G1.AddVertex('D');\n    G1.AddVertex('E');\n    G1.AddVertex('F');\n    G1.AddVertex('G');\n    G1.AddVertex('H');\n\n    G1.AddEdge('A','B',1);\n    G1.AddEdge('B','A',1);\n    G1.AddEdge('A','C',1);\n    G1.AddEdge('A','D',1);\n    G1.AddEdge('D','A',1);\n    G1.AddEdge('D','E',1);\n    G1.AddEdge('D','G',1);\n    G1.AddEdge('G','F',1);\n    G1.AddEdge('F','H',1);\n    G1.AddEdge('H','E',1);\n\n    cout<<\"OutDegree of vertex D :\"<<G1.OutDegree('D')<<endl;\n    if(G1.FoundEdge('A','D'))\n        cout<<\"There is an edge between A and D\"<<endl;\n    else\n        cout<<\"There is no edge between A and D\"<<endl;\n\n    if(G1.FoundEdge('B','D'))\n        cout<<\"There is an edge between B and D\"<<endl;\n    else\n        cout<<\"There is no edge between B and D\"<<endl;\n\n    G1.DepthFirstSearch('B','E');\n    G1.DepthFirstSearch('E','B');\n    G1.BreadthFirstSearch('B','E');\n    G1.BreadthFirstSearch('E','B');\n    return 0;\n}\n","avg_line_length":23.5319148936,"max_line_length":61,"alphanum_fraction":0.5470162749,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":60831,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/\/ Copyright (c) Microsoft Corporation.\r\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\r\n\r\n#define _HAS_DEPRECATED_ADAPTOR_TYPEDEFS     1\r\n#define _HAS_DEPRECATED_ALLOCATOR_MEMBERS    1\r\n#define _HAS_DEPRECATED_NEGATORS             1\r\n#define _HAS_DEPRECATED_RAW_STORAGE_ITERATOR 1\r\n#define _HAS_DEPRECATED_TEMPORARY_BUFFER     1\r\n#define _SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING\r\n#define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING\r\n#define _SILENCE_CXX17_NEGATORS_DEPRECATION_WARNING\r\n#define _SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING\r\n#define _SILENCE_CXX17_RAW_STORAGE_ITERATOR_DEPRECATION_WARNING\r\n#define _SILENCE_CXX17_STRSTREAM_DEPRECATION_WARNING\r\n#define _SILENCE_CXX17_TEMPORARY_BUFFER_DEPRECATION_WARNING\r\n#define _SILENCE_CXX20_ATOMIC_INIT_DEPRECATION_WARNING\r\n#define _SILENCE_CXX20_CODECVT_FACETS_DEPRECATION_WARNING\r\n#define _SILENCE_CXX20_OLD_SHARED_PTR_ATOMIC_SUPPORT_DEPRECATION_WARNING\r\n#define _SILENCE_CXX20_REL_OPS_DEPRECATION_WARNING\r\n#define _SILENCE_CXX20_U8PATH_DEPRECATION_WARNING\r\n#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING\r\n#define _SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING\r\n#define _USE_NAMED_IDL_NAMESPACE 1\r\n\r\n#include <algorithm>\r\n\/\/#include <any> \/\/ All templates instantiated in P0220R1_any\r\n#include <array>\r\n#include <cassert>\r\n#include <ccomplex>\r\n#include <cctype>\r\n#include <cerrno>\r\n#include <cfenv>\r\n#include <cfloat>\r\n#include <chrono>\r\n#include <cinttypes>\r\n#include <ciso646>\r\n#include <climits>\r\n#include <clocale>\r\n#include <cmath>\r\n#include <codecvt>\r\n#include <csetjmp>\r\n#include <csignal>\r\n#include <cstdalign>\r\n#include <cstdarg>\r\n#include <cstdbool>\r\n#include <cstddef>\r\n#include <cstdint>\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <cstring>\r\n#include <ctgmath>\r\n#include <ctime>\r\n#include <cuchar>\r\n#include <cwchar>\r\n#include <cwctype>\r\n#include <deque>\r\n#include <exception>\r\n#include <filesystem>\r\n#include <forward_list>\r\n#include <fstream>\r\n#include <functional>\r\n#include <initializer_list>\r\n#include <iomanip>\r\n#include <ios>\r\n#include <iosfwd>\r\n#include <iostream>\r\n#include <iso646.h>\r\n#include <istream>\r\n#include <iterator>\r\n#include <limits>\r\n#include <list>\r\n#include <locale>\r\n#include <memory>\r\n#include <new>\r\n#include <numeric>\r\n\/\/#include <optional> \/\/ All templates instantiated in P0220R1_optional\r\n#include <ostream>\r\n#include <random>\r\n#include <ratio>\r\n#include <regex>\r\n#include <scoped_allocator>\r\n#include <sstream>\r\n#include <stdexcept>\r\n#include <streambuf>\r\n#include <string>\r\n#include <strstream>\r\n#include <system_error>\r\n#include <tuple>\r\n#include <typeindex>\r\n#include <typeinfo>\r\n#include <utility>\r\n\/\/#include <variant> \/\/ All templates instantiated in P0088R3_variant\r\n#include <vector>\r\n\r\n\/\/ Headers not allowed with \/clr:pure\r\n#ifndef _M_CEE_PURE\r\n#include <atomic>\r\n#endif \/\/ _M_CEE_PURE\r\n\r\n\/\/ Headers not allowed to be used with \/clr\r\n#ifndef _M_CEE\r\n#include <condition_variable>\r\n#include <future>\r\n#include <mutex>\r\n#include <shared_mutex>\r\n#include <thread>\r\n#endif \/\/ _M_CEE\r\n\r\n#include <experimental\/filesystem>\r\n\r\n#include <instantiate_containers_iterators_common.hpp>\r\n\r\n\r\nusing namespace std;\r\n\r\n#define STATIC_ASSERT(...) static_assert(__VA_ARGS__, #__VA_ARGS__)\r\n\r\nint main() {} \/\/ COMPILE-ONLY\r\n\r\n#ifndef _M_CEE_PURE\r\n\r\n#if _HAS_CXX20\r\nSTATIC_ASSERT(memory_order_relaxed == memory_order::relaxed);\r\nSTATIC_ASSERT(memory_order_consume == memory_order::consume);\r\nSTATIC_ASSERT(memory_order_acquire == memory_order::acquire);\r\nSTATIC_ASSERT(memory_order_release == memory_order::release);\r\nSTATIC_ASSERT(memory_order_acq_rel == memory_order::acq_rel);\r\nSTATIC_ASSERT(memory_order_seq_cst == memory_order::seq_cst);\r\n\r\n\/\/ LWG-3268\r\nSTATIC_ASSERT(memory_order::memory_order_relaxed == memory_order::relaxed);\r\nSTATIC_ASSERT(memory_order::memory_order_consume == memory_order::consume);\r\nSTATIC_ASSERT(memory_order::memory_order_acquire == memory_order::acquire);\r\nSTATIC_ASSERT(memory_order::memory_order_release == memory_order::release);\r\nSTATIC_ASSERT(memory_order::memory_order_acq_rel == memory_order::acq_rel);\r\nSTATIC_ASSERT(memory_order::memory_order_seq_cst == memory_order::seq_cst);\r\n#endif \/\/ _HAS_CXX20\r\n\r\ntemplate <typename AtomicType>\r\nvoid atomic_read_test_impl(AtomicType& value) {\r\n    (void) atomic_is_lock_free(&value);\r\n    (void) atomic_load(&value);\r\n    (void) atomic_load_explicit(&value, memory_order_seq_cst);\r\n}\r\n\r\ntemplate <typename AtomicType, typename ValueType>\r\nvoid atomic_has_arithmetic_ops_test_impl(AtomicType& value, ValueType element, true_type) {\r\n    atomic_fetch_add(&value, element);\r\n    atomic_fetch_add_explicit(&value, element, memory_order_seq_cst);\r\n    atomic_fetch_sub(&value, element);\r\n    atomic_fetch_sub_explicit(&value, element, memory_order_seq_cst);\r\n    atomic_fetch_and(&value, element);\r\n    atomic_fetch_and_explicit(&value, element, memory_order_seq_cst);\r\n    atomic_fetch_or(&value, element);\r\n    atomic_fetch_or_explicit(&value, element, memory_order_seq_cst);\r\n    atomic_fetch_xor(&value, element);\r\n    atomic_fetch_xor_explicit(&value, element, memory_order_seq_cst);\r\n}\r\n\r\ntemplate <typename AtomicType, typename ValueType>\r\nvoid atomic_has_arithmetic_ops_test_impl(AtomicType&, ValueType, false_type) {}\r\n\r\ntemplate <typename AtomicType, typename ValueType>\r\nvoid atomic_write_test_impl(AtomicType& value, ValueType element) {\r\n    ValueType* ptr_element = &element;\r\n\r\n    atomic_init(&value, element);\r\n    atomic_store(&value, element);\r\n    atomic_store_explicit(&value, element, memory_order_seq_cst);\r\n    atomic_exchange(&value, element);\r\n    atomic_exchange_explicit(&value, element, memory_order_seq_cst);\r\n    atomic_compare_exchange_weak(&value, ptr_element, element);\r\n    atomic_compare_exchange_weak_explicit(&value, ptr_element, element, memory_order_seq_cst, memory_order_seq_cst);\r\n    atomic_compare_exchange_strong(&value, ptr_element, element);\r\n    atomic_compare_exchange_strong_explicit(&value, ptr_element, element, memory_order_seq_cst, memory_order_seq_cst);\r\n\r\n    atomic_has_arithmetic_ops_test_impl(value, element, negation<is_same<ValueType, bool>>());\r\n}\r\n\r\ntemplate <typename T>\r\nvoid atomic_test_impl(T element) {\r\n    atomic<T> value{element};\r\n    volatile atomic<T> v_value{element};\r\n    const atomic<T> c_value{element};\r\n    const volatile atomic<T> cv_value{element};\r\n\r\n    atomic_read_test_impl(value);\r\n    atomic_read_test_impl(v_value);\r\n    atomic_read_test_impl(c_value);\r\n    atomic_read_test_impl(cv_value);\r\n\r\n    atomic_write_test_impl(value, element);\r\n    atomic_write_test_impl(v_value, element);\r\n}\r\n\r\ntemplate <typename T>\r\nvoid atomic_test_impl() {\r\n    T element{};\r\n    atomic_test_impl(element);\r\n}\r\n\r\nvoid atomic_test() {\r\n    int a = 0;\r\n    kill_dependency(a);\r\n\r\n    uint8_t one_byte = 0;\r\n    STATIC_ASSERT(sizeof(one_byte) == 1);\r\n\r\n    uint16_t two_bytes = 1;\r\n    STATIC_ASSERT(sizeof(two_bytes) == 2);\r\n\r\n    uint32_t four_bytes = 2;\r\n    STATIC_ASSERT(sizeof(four_bytes) == 4);\r\n\r\n    uint64_t eight_bytes = 3;\r\n    STATIC_ASSERT(sizeof(eight_bytes) == 8);\r\n\r\n    atomic_test_impl(one_byte);\r\n    atomic_test_impl(two_bytes);\r\n    atomic_test_impl(four_bytes);\r\n    atomic_test_impl(eight_bytes);\r\n\r\n    atomic_test_impl<bool>();\r\n    atomic_test_impl<char>();\r\n    atomic_test_impl<signed char>();\r\n    atomic_test_impl<unsigned char>();\r\n#ifdef __cpp_char8_t\r\n    atomic_test_impl<char8_t>();\r\n#endif \/\/ __cpp_char8_t\r\n    atomic_test_impl<char16_t>();\r\n    atomic_test_impl<char32_t>();\r\n    atomic_test_impl<wchar_t>();\r\n    atomic_test_impl<short>();\r\n    atomic_test_impl<unsigned short>();\r\n    atomic_test_impl<int>();\r\n    atomic_test_impl<unsigned int>();\r\n    atomic_test_impl<long>();\r\n    atomic_test_impl<unsigned long>();\r\n    atomic_test_impl<long long>();\r\n    atomic_test_impl<unsigned long long>();\r\n}\r\n#endif \/\/ _M_CEE_PURE\r\n\r\nvoid chrono_test() {\r\n    using namespace chrono;\r\n    treat_as_floating_point<float> a{};\r\n    duration_values<float> b{};\r\n    duration<float> c{};\r\n    (void) duration_cast<duration<float, ratio<2>>>(c);\r\n    duration<double> d(1.0f);\r\n    duration<double> e(c);\r\n\r\n    time_point<system_clock> time_pt = system_clock::now();\r\n\r\n    INSTANTIATE(common_type_t<duration<float>, duration<double>>);\r\n    INSTANTIATE(common_type_t<time_point<system_clock>, time_point<system_clock>>);\r\n\r\n    (void) a;\r\n    (void) b;\r\n    (void) d;\r\n    (void) e;\r\n\r\n    duration<float> dur1{};\r\n    duration<double, ratio<2>> dur2{};\r\n\r\n    (void) (dur1 + dur2);\r\n    (void) (dur1 - dur2);\r\n    (void) (1.f * dur2);\r\n    (void) (dur1 * 2.0);\r\n    (void) (dur1 \/ 2.0);\r\n    (void) (dur1 \/ dur2);\r\n\r\n    duration<int> dur3{};\r\n    duration<int, ratio<2>> dur4{};\r\n\r\n    (void) (dur3 % 2);\r\n    (void) (dur3 % dur4);\r\n\r\n    comparable_test(dur1, dur2);\r\n\r\n    (void) floor<duration<int>>(dur1);\r\n    (void) ceil<duration<int>>(dur1);\r\n\r\n    (void) round<duration<int>>(dur1); \/\/ float -> int\r\n    (void) round<duration<int>>(dur3); \/\/ int -> int\r\n\r\n    (void) abs(dur1);\r\n\r\n    (void) (time_pt + dur1);\r\n    (void) (dur1 + time_pt);\r\n    (void) (time_pt - dur1);\r\n    (void) (time_pt - time_pt);\r\n    comparable_test(time_pt);\r\n\r\n    (void) (time_point_cast<duration<float>>(time_pt));\r\n\r\n    (void) (floor<duration<float>>(time_pt));\r\n    (void) (ceil<duration<float>>(time_pt));\r\n}\r\n\r\n#ifndef _M_CEE\r\ntemplate <typename ConditionVariable>\r\nvoid condition_variable_test_impl() {\r\n    ConditionVariable cv{};\r\n    unique_lock<mutex> lock;\r\n\r\n    auto pr0  = []() { return true; };\r\n    auto soon = chrono::system_clock::now() + chrono::minutes(2);\r\n\r\n    cv.wait(lock);\r\n    cv.wait(lock, pr0);\r\n    (void) cv.wait_for(lock, chrono::seconds(1));\r\n    (void) cv.wait_for(lock, chrono::seconds(1), pr0);\r\n    (void) cv.wait_until(lock, soon);\r\n    (void) cv.wait_until(lock, soon, pr0);\r\n}\r\n\r\nvoid condition_variable_test() {\r\n    condition_variable_test_impl<condition_variable_any>();\r\n}\r\n#endif \/\/ _M_CEE\r\n\r\nvoid check_nested_exception_impl(const exception& ex) { \/\/ unroll nested exceptions\r\n    try {\r\n        rethrow_if_nested(ex);\r\n    } catch (const exception& e) {\r\n        check_nested_exception_impl(e);\r\n    } catch (...) {\r\n    }\r\n}\r\n\r\ntemplate <typename ThrowingFunction>\r\nvoid exception_test_impl(const ThrowingFunction& tf) {\r\n    try {\r\n        try {\r\n            tf();\r\n        } catch (...) {\r\n            throw_with_nested(\"BOOMx2\");\r\n        }\r\n    } catch (const exception& e) {\r\n        check_nested_exception_impl(e);\r\n    }\r\n}\r\n\r\nvoid exception_test() {\r\n    exception e{};\r\n    exception_ptr e_ptr = make_exception_ptr(e);\r\n\r\n    exception_test_impl([]() { throw 23; }); \/\/ can't nest\r\n    exception_test_impl([]() { throw runtime_error(\"BOOM\"); }); \/\/ can nest\r\n}\r\n\r\ntemplate <typename CharType>\r\nvoid filesystem_test_impl(const CharType* c_str) {\r\n    using namespace experimental::filesystem;\r\n\r\n    basic_string<CharType> str = c_str;\r\n\r\n    path p0(str.begin(), str.end());\r\n    path p1(c_str);\r\n    path p2(str);\r\n\r\n    locale default_locale{};\r\n    path p3(str.begin(), str.end(), default_locale);\r\n    path p4(c_str, default_locale);\r\n    path p5(str, default_locale);\r\n\r\n    p0 = c_str;\r\n    p1 = str;\r\n    p2.assign(str.begin(), str.end());\r\n    p3.assign(c_str);\r\n    p4.assign(str);\r\n    p5 \/= c_str;\r\n    p0 \/= str;\r\n    p0.append(str.begin(), str.end());\r\n    p0.append(c_str);\r\n    p0 += *c_str;\r\n    p0 += str;\r\n    p0 += c_str;\r\n    p0.concat(str.begin(), str.end());\r\n    p0.concat(str.begin());\r\n    p0.concat(c_str);\r\n    p0.concat(*c_str);\r\n    p0.concat(str);\r\n\r\n    (void) p0.string<CharType>(str.get_allocator());\r\n    (void) p0.generic_string<CharType>(str.get_allocator());\r\n\r\n    stringstream ss{};\r\n\r\n    ss << p0;\r\n    ss >> p0;\r\n\r\n    auto u8str = p0.u8string();\r\n    (void) u8path(u8str.begin(), u8str.end());\r\n    (void) u8path(u8str.c_str());\r\n}\r\n\r\nvoid filesystem_test() {\r\n    filesystem_test_impl(\"narrow\");\r\n    filesystem_test_impl(L\"wide\");\r\n#ifndef _M_CEE_PURE\r\n#ifdef __cpp_char8_t\r\n    filesystem_test_impl(u8\"utf8\");\r\n#endif \/\/ __cpp_char8_t\r\n    filesystem_test_impl(u\"utf16\");\r\n    filesystem_test_impl(U\"utf32\");\r\n#endif \/\/ _M_CEE_PURE\r\n}\r\n\r\ntemplate <typename CharType>\r\nvoid fstream_test_impl() {\r\n    basic_filebuf<CharType, char_traits<CharType>> fb;\r\n    basic_ifstream<CharType, char_traits<CharType>> ifs;\r\n    basic_ofstream<CharType, char_traits<CharType>> ofs;\r\n    basic_fstream<CharType, char_traits<CharType>> fs;\r\n\r\n    swap_test(fb);\r\n    swap_test(ifs);\r\n    swap_test(ofs);\r\n    swap_test(fs);\r\n}\r\n\r\nvoid fstream_test() {\r\n    fstream_test_impl<char>();\r\n    fstream_test_impl<wchar_t>();\r\n}\r\n\r\ntemplate <typename ReturnType, typename Function>\r\nvoid function_test_impl(Function func) {\r\n    function<ReturnType()> f0;\r\n    function<ReturnType()> f1 = nullptr;\r\n    function<ReturnType()> f2 = f0;\r\n    function<ReturnType()> f3 = move(f0);\r\n    function<ReturnType()> f4 = func;\r\n    const auto& cf            = f0;\r\n    f0                        = f1;\r\n    f0                        = move(f1);\r\n    f0                        = nullptr;\r\n    f0                        = func;\r\n    f0                        = ref(func);\r\n    swap_test(f0);\r\n    (void) !cf;\r\n    (void) cf();\r\n    (void) cf.target_type();\r\n    (void) f0.template target<ReturnType (*)()>();\r\n    (void) cf.template target<ReturnType (*)()>();\r\n    equality_test(f0, nullptr);\r\n    equality_test(nullptr, f0);\r\n\r\n#if _HAS_FUNCTION_ALLOCATOR_SUPPORT\r\n    function<ReturnType()> f5(allocator_arg, allocator<double>{});\r\n    function<ReturnType()> f6(allocator_arg, allocator<double>{}, nullptr);\r\n    function<ReturnType()> f7(allocator_arg, allocator<double>{}, f5);\r\n    function<ReturnType()> f8(allocator_arg, allocator<double>{}, move(f5));\r\n    function<ReturnType()> f9(allocator_arg, allocator<double>{}, func);\r\n    TRAIT_V(uses_allocator, function<ReturnType()>, allocator<double>);\r\n#endif \/\/ _HAS_FUNCTION_ALLOCATOR_SUPPORT\r\n}\r\n\r\nvoid functional_test() {\r\n    using namespace placeholders;\r\n\r\n    \/\/ different return types to trigger <type_traits>::_Invoke_ret\r\n    function_test_impl<void>([]() {});\r\n    function_test_impl<int>([]() { return 4; });\r\n    function_test_impl<vector<int>>([]() { return vector<int>{}; });\r\n\r\n    auto ph                  = _1;\r\n    const auto cph           = _2;\r\n    volatile auto vph        = _3;\r\n    const volatile auto cvph = _4;\r\n\r\n    TRAIT_V(is_placeholder, decltype(ph));\r\n    TRAIT_V(is_placeholder, decltype(cph));\r\n    TRAIT_V(is_placeholder, decltype(vph));\r\n    TRAIT_V(is_placeholder, decltype(cvph));\r\n\r\n    TRAIT_V(is_placeholder, int);\r\n    TRAIT_V(is_placeholder, const int);\r\n    TRAIT_V(is_placeholder, volatile int);\r\n    TRAIT_V(is_placeholder, const volatile int);\r\n\r\n    \/\/ implicit return type\r\n    auto be                  = bind([](int, int) {}, _1, 2);\r\n    const auto cbe           = be;\r\n    volatile auto vbe        = be;\r\n    const volatile auto cvbe = be;\r\n\r\n    auto not_be                  = []() {};\r\n    const auto not_cbe           = not_be;\r\n    volatile auto not_vbe        = not_be;\r\n    const volatile auto not_cvbe = not_be;\r\n\r\n    TRAIT_V(is_bind_expression, decltype(be));\r\n    TRAIT_V(is_bind_expression, decltype(cbe));\r\n    TRAIT_V(is_bind_expression, decltype(vbe));\r\n    TRAIT_V(is_bind_expression, decltype(cvbe));\r\n\r\n    TRAIT_V(is_bind_expression, decltype(not_be));\r\n    TRAIT_V(is_bind_expression, decltype(not_cbe));\r\n    TRAIT_V(is_bind_expression, decltype(not_vbe));\r\n    TRAIT_V(is_bind_expression, decltype(not_cvbe));\r\n\r\n    be(1);\r\n    cbe(2);\r\n    \/\/ volatile binder calls not supported\r\n\r\n    \/\/ with explicit return type\r\n    auto be_ret                  = bind<void>([](int, int) {}, _1, 2);\r\n    const auto cbe_ret           = be;\r\n    volatile auto vbe_ret        = be;\r\n    const volatile auto cvbe_ret = be;\r\n\r\n    TRAIT_V(is_bind_expression, decltype(be_ret));\r\n    TRAIT_V(is_bind_expression, decltype(cbe_ret));\r\n    TRAIT_V(is_bind_expression, decltype(vbe_ret));\r\n    TRAIT_V(is_bind_expression, decltype(cvbe_ret));\r\n\r\n    be_ret(3);\r\n    cbe_ret(4);\r\n    \/\/ volatile binder calls not supported\r\n}\r\n\r\n#ifndef _M_CEE\r\ntemplate <typename Future>\r\nvoid future_test_impl(Future& f) {\r\n    using namespace chrono;\r\n\r\n    (void) f.wait_for(seconds(3));\r\n    (void) f.wait_until(system_clock::now());\r\n}\r\n\r\nvoid future_test() {\r\n    auto bp = future_errc::broken_promise;\r\n    (void) bp;\r\n    bool iece = is_error_code_enum_v<decltype(bp)>;\r\n    (void) iece;\r\n\r\n    future<int> f{};\r\n    future<int&> fr{};\r\n    future<void> fv{};\r\n\r\n    shared_future<int> sf{};\r\n    shared_future<int&> sfr{};\r\n    shared_future<void> sfv{};\r\n\r\n    future_test_impl(f);\r\n    future_test_impl(fr);\r\n    future_test_impl(fv);\r\n    future_test_impl(sf);\r\n    future_test_impl(sfr);\r\n    future_test_impl(sfv);\r\n\r\n    promise<int> p(allocator_arg, allocator<double>{});\r\n    promise<int&> pr(allocator_arg, allocator<double>{});\r\n    promise<void> pv(allocator_arg, allocator<double>{});\r\n\r\n    swap_test(p);\r\n    swap_test(pr);\r\n    swap_test(pv);\r\n\r\n    packaged_task<void()> pt([]() {});\r\n\r\n#if _HAS_FUNCTION_ALLOCATOR_SUPPORT\r\n    packaged_task<void()> pta(allocator_arg, allocator<double>{}, []() {});\r\n#endif \/\/ _HAS_FUNCTION_ALLOCATOR_SUPPORT\r\n\r\n    swap_test(pt);\r\n\r\n    (void) async([]() {});\r\n    (void) async(launch::async, []() {});\r\n\r\n    TRAIT_V(uses_allocator, promise<int>, allocator<double>);\r\n\r\n#if _HAS_FUNCTION_ALLOCATOR_SUPPORT\r\n    TRAIT_V(uses_allocator, packaged_task<void()>, allocator<double>);\r\n#endif \/\/ _HAS_FUNCTION_ALLOCATOR_SUPPORT\r\n}\r\n#endif \/\/ _M_CEE\r\n\r\ntemplate <typename IoManipIn, typename IoManipOut>\r\nvoid iomanip_test_impl(IoManipIn in, IoManipOut out) {\r\n    stringstream ss{};\r\n    ss << in;\r\n    ss >> out;\r\n}\r\n\r\ntemplate <typename IoManip>\r\nvoid iomanip_test_impl(IoManip iom) {\r\n    iomanip_test_impl(iom, iom);\r\n}\r\n\r\nvoid iomanip_test() {\r\n    auto sf           = setfill('*');\r\n    long double money = 123.45;\r\n    time_t t          = time(nullptr);\r\n    tm time{};\r\n    localtime_s(&time, &t);\r\n    string str = \"string with \\\" quotes \";\r\n\r\n    iomanip_test_impl(sf);\r\n    iomanip_test_impl(put_money(money), get_money(money));\r\n    iomanip_test_impl(put_time(&time, \"%c %Z\"), get_time(&time, \"%c %Z\"));\r\n    iomanip_test_impl(quoted(str.c_str()), quoted(str));\r\n    iomanip_test_impl(quoted(str));\r\n    iomanip_test_impl(resetiosflags(ios_base::basefield));\r\n    iomanip_test_impl(setiosflags(ios_base::basefield));\r\n    iomanip_test_impl(setbase(2));\r\n    iomanip_test_impl(setprecision(10));\r\n    iomanip_test_impl(setw(10));\r\n}\r\n\r\nvoid ios_test() {\r\n    stringstream ss{};\r\n    basic_ios<char, char_traits<char>> b_ios(ss.rdbuf());\r\n}\r\n\r\nvoid iosfwd_test() {\r\n    streampos sp; \/\/ fpos<char_traits<char>::state_type>\r\n    wstreampos wsp; \/\/ fpos<char_traits<wchar_t>::state_type>\r\n\r\n    INSTANTIATE(char_traits<char>);\r\n    INSTANTIATE(char_traits<wchar_t>);\r\n#ifdef __cpp_char8_t\r\n    INSTANTIATE(char_traits<char8_t>);\r\n#endif \/\/ __cpp_char8_t\r\n    INSTANTIATE(char_traits<char16_t>);\r\n    INSTANTIATE(char_traits<char32_t>);\r\n    INSTANTIATE(char_traits<unsigned short>);\r\n    \/\/ Other templates in iosfwd are forward decls.\r\n    \/\/ Will instantiate in the test for the header where they are defined.\r\n}\r\n\r\ntemplate <typename Container>\r\nvoid nonmember_reverse_iterator_functions_test() {\r\n    Container c{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\r\n\r\n    (void) rbegin(c);\r\n    (void) crbegin(c);\r\n    (void) rend(c);\r\n    (void) crend(c);\r\n}\r\n\r\ntemplate <typename Container>\r\nvoid nonmember_iterator_functions_test() {\r\n    Container c{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\r\n\r\n    (void) begin(c);\r\n    (void) cbegin(c);\r\n    (void) end(c);\r\n    (void) cend(c);\r\n}\r\n\r\nvoid msvc_array_iterators_test() {\r\n    using namespace stdext;\r\n    int arr[] = {1, 2, 3, 4};\r\n\r\n    auto unchecked = make_unchecked_array_iterator(arr);\r\n    auto checked   = make_checked_array_iterator(arr, size(arr));\r\n\r\n    random_access_iterator_test(unchecked);\r\n    random_access_iterator_test(checked);\r\n\r\n    swap_test(unchecked);\r\n    swap_test(checked);\r\n    comparable_test(unchecked);\r\n    comparable_test(checked);\r\n}\r\n\r\nvoid iterators_test() {\r\n    fwd_iterators_test<forward_list<int>>();\r\n    fwd_iterators_test<list<int>>();\r\n    fwd_iterators_test<vector<int>>();\r\n\r\n    bidi_iterators_test<list<int>>();\r\n    bidi_iterators_test<vector<int>>();\r\n\r\n    nonmember_iterator_functions_test<int[]>();\r\n    nonmember_iterator_functions_test<initializer_list<int>>();\r\n    nonmember_iterator_functions_test<forward_list<int>>();\r\n    nonmember_iterator_functions_test<list<int>>();\r\n    nonmember_iterator_functions_test<vector<int>>();\r\n\r\n    nonmember_reverse_iterator_functions_test<int[]>();\r\n    nonmember_reverse_iterator_functions_test<initializer_list<int>>();\r\n    nonmember_reverse_iterator_functions_test<list<int>>();\r\n    nonmember_reverse_iterator_functions_test<vector<int>>();\r\n\r\n    msvc_array_iterators_test();\r\n\r\n    int arr[]                = {1};\r\n    initializer_list<int> il = {2};\r\n    forward_list<int> flist{3};\r\n    list<int> lst{4};\r\n    vector<int> vec{5};\r\n\r\n    (void) size(arr);\r\n    (void) data(arr);\r\n    (void) empty(arr);\r\n\r\n    (void) size(il);\r\n    (void) data(il);\r\n    (void) empty(il);\r\n\r\n    (void) empty(flist);\r\n\r\n    (void) size(lst);\r\n    (void) empty(lst);\r\n\r\n    (void) size(vec);\r\n    (void) data(vec);\r\n    (void) empty(vec);\r\n\r\n#if _HAS_CXX20\r\n    (void) ssize(arr);\r\n    (void) ssize(il);\r\n    (void) ssize(lst);\r\n    (void) ssize(vec);\r\n#endif \/\/ _HAS_CXX20\r\n\r\n    deque<int> value{1, 2, 3};\r\n    auto it  = inserter(value, begin(value));\r\n    auto fit = front_inserter(value);\r\n    auto bit = back_inserter(value);\r\n\r\n    swap_test(it);\r\n    swap_test(fit);\r\n    swap_test(bit);\r\n\r\n    stringstream ss(\"1 2 3 4 5\");\r\n    istream_iterator<int> isi(ss);\r\n    ostream_iterator<int> osi(ss, \" \");\r\n    istreambuf_iterator<char> isbi(ss);\r\n    ostreambuf_iterator<char> osbi(ss);\r\n\r\n    equality_test(isi);\r\n    equality_test(isbi);\r\n    swap_test(isi);\r\n    swap_test(isbi);\r\n    swap_test(osi);\r\n    swap_test(osbi);\r\n}\r\n\r\nvoid istream_test() {\r\n    stringstream ss{};\r\n    istream is(ss.rdbuf());\r\n\r\n    wstringstream wss{};\r\n    wistream wis(wss.rdbuf());\r\n\r\n    unsigned short us{};\r\n    wis >> us;\r\n\r\n    iostream ios(ss.rdbuf());\r\n    wiostream wios(wss.rdbuf());\r\n\r\n    \/\/ \/analyze doesn't like these being nullptr\r\n    char c_str[]           = \"1\";\r\n    signed char sc_str[]   = \"2\";\r\n    unsigned char uc_str[] = \"3\";\r\n\r\n    is >> c_str;\r\n    is >> *c_str;\r\n    is >> sc_str;\r\n    is >> *sc_str;\r\n    is >> uc_str;\r\n    is >> *uc_str;\r\n    move(is) >> c_str;\r\n    is >> ws; \/\/ io manipulator, not variable\r\n}\r\n\r\ntemplate <typename T>\r\nvoid numeric_limits_test_impl() {\r\n    INSTANTIATE(numeric_limits<T>);\r\n    INSTANTIATE(numeric_limits<const T>);\r\n    INSTANTIATE(numeric_limits<volatile T>);\r\n    INSTANTIATE(numeric_limits<const volatile T>);\r\n}\r\n\r\nvoid limits_test() {\r\n    numeric_limits_test_impl<bool>();\r\n    numeric_limits_test_impl<char>();\r\n    numeric_limits_test_impl<signed char>();\r\n    numeric_limits_test_impl<unsigned char>();\r\n#ifdef __cpp_char8_t\r\n    numeric_limits_test_impl<char8_t>();\r\n#endif \/\/ __cpp_char8_t\r\n    numeric_limits_test_impl<char16_t>();\r\n    numeric_limits_test_impl<char32_t>();\r\n    numeric_limits_test_impl<wchar_t>();\r\n    numeric_limits_test_impl<short>();\r\n    numeric_limits_test_impl<int>();\r\n    numeric_limits_test_impl<long>();\r\n    numeric_limits_test_impl<long long>();\r\n    numeric_limits_test_impl<unsigned short>();\r\n    numeric_limits_test_impl<unsigned int>();\r\n    numeric_limits_test_impl<unsigned long>();\r\n    numeric_limits_test_impl<unsigned long long>();\r\n    numeric_limits_test_impl<float>();\r\n    numeric_limits_test_impl<double>();\r\n    numeric_limits_test_impl<long double>();\r\n\r\n    numeric_limits_test_impl<string>();\r\n}\r\n\r\nvoid locale_test() {\r\n    char c{};\r\n    locale loc{};\r\n    \/\/ need all collates to instantiate xlocinfo _Lstrcoll and _Lstrxfrm\r\n    auto cc   = has_facet<collate<char>>(loc);\r\n    auto cw   = has_facet<collate<wchar_t>>(loc);\r\n    auto cbnc = has_facet<collate_byname<char>>(loc);\r\n    auto cbnw = has_facet<collate_byname<wchar_t>>(loc);\r\n    auto ctc  = has_facet<ctype<char>>(loc);\r\n    isalnum(c, loc);\r\n    isalpha(c, loc);\r\n    isblank(c, loc);\r\n    iscntrl(c, loc);\r\n    isdigit(c, loc);\r\n    isgraph(c, loc);\r\n    islower(c, loc);\r\n    isprint(c, loc);\r\n    ispunct(c, loc);\r\n    isspace(c, loc);\r\n    isupper(c, loc);\r\n    isxdigit(c, loc);\r\n    tolower(c, loc);\r\n    toupper(c, loc);\r\n\r\n    (void) cc;\r\n    (void) cw;\r\n    (void) cbnc;\r\n    (void) cbnw;\r\n    (void) ctc;\r\n}\r\n\r\ntemplate <typename OwnerLess, typename SmartPtr1, typename SmartPtr2>\r\nvoid owner_less_test_impl(OwnerLess ol, SmartPtr1 ptr1, SmartPtr2 ptr2) {\r\n    (void) ol(ptr1, ptr2);\r\n    (void) ol(ptr2, ptr1);\r\n}\r\n\r\ntemplate <typename OwnerLess, typename SmartPtr>\r\nvoid owner_less_test_impl(OwnerLess ol, SmartPtr ptr) {\r\n    \/\/ also tests _Ptr_base::owner_before\r\n    owner_less_test_impl(ol, ptr, ptr);\r\n}\r\n\r\nvoid shared_ptr_test_impl() {\r\n    shared_ptr<int> sptr0(new int());\r\n    shared_ptr<int> sptr1(new int(), default_delete<int>{});\r\n    shared_ptr<int> sptr2(nullptr, default_delete<int>{});\r\n    shared_ptr<int> sptr3(nullptr, default_delete<int>{}, allocator<int>{});\r\n    shared_ptr<int> sptr4(new int(), default_delete<int>{}, allocator<int>{});\r\n    shared_ptr<int> sptr5(sptr0, nullptr);\r\n    shared_ptr<void> sptr6(sptr1);\r\n    shared_ptr<int> sptr7(weak_ptr<int>{sptr2});\r\n#if _HAS_AUTO_PTR_ETC\r\n    shared_ptr<int> sptr8(auto_ptr<int>{});\r\n    sptr8 = auto_ptr<int>{};\r\n#endif \/\/ _HAS_AUTO_PTR_ETC\r\n    shared_ptr<void> sptr9(move(sptr3));\r\n    shared_ptr<int> sptr10(unique_ptr<int>{});\r\n\r\n    sptr4 = unique_ptr<int>{};\r\n    sptr6 = move(sptr5);\r\n    sptr9 = sptr7;\r\n\r\n    sptr10.reset(new int());\r\n    sptr0.reset(new int(), default_delete<int>{});\r\n    sptr0.reset(new int(), default_delete<int>{}, allocator<int>{});\r\n\r\n    comparable_test(sptr0, sptr6);\r\n    comparable_test(sptr0, nullptr);\r\n    comparable_test(nullptr, sptr0);\r\n    cout << sptr0;\r\n    swap_test(sptr0);\r\n\r\n    auto sptr11 = make_shared<int>(5);\r\n    auto sptr12 = allocate_shared<int>(allocator<int>{}, 6);\r\n\r\n    struct Cat {\r\n        virtual ~Cat() {}\r\n    };\r\n\r\n    struct Kitten : Cat {};\r\n\r\n    (void) static_pointer_cast<void>(sptr0);\r\n    (void) const_pointer_cast<const int>(sptr0);\r\n    (void) dynamic_pointer_cast<Kitten>(make_shared<Cat>());\r\n\r\n    (void) get_deleter<default_delete<int>>(sptr0);\r\n    hash_test(sptr0);\r\n\r\n    (void) atomic_is_lock_free(&sptr0);\r\n    (void) atomic_load(&sptr0);\r\n    (void) atomic_load_explicit(&sptr0, memory_order_seq_cst);\r\n    atomic_store(&sptr0, sptr0);\r\n    atomic_store_explicit(&sptr0, sptr0, memory_order_seq_cst);\r\n    atomic_exchange(&sptr0, sptr0);\r\n    atomic_exchange_explicit(&sptr0, sptr0, memory_order_seq_cst);\r\n    atomic_compare_exchange_weak(&sptr0, &sptr0, sptr0);\r\n    atomic_compare_exchange_weak_explicit(&sptr0, &sptr0, sptr0, memory_order_seq_cst, memory_order_seq_cst);\r\n    atomic_compare_exchange_strong(&sptr0, &sptr0, sptr0);\r\n    atomic_compare_exchange_strong_explicit(&sptr0, &sptr0, sptr0, memory_order_seq_cst, memory_order_seq_cst);\r\n}\r\n\r\nvoid weak_ptr_test_impl() {\r\n    weak_ptr<int> wptr0(make_shared<int>(5));\r\n    weak_ptr<void> wptr1(wptr0);\r\n    weak_ptr<void> wptr2(move(wptr0));\r\n\r\n    wptr1 = wptr0;\r\n    wptr2 = move(wptr0);\r\n    wptr0 = make_shared<int>(5);\r\n    swap_test(wptr0);\r\n}\r\n\r\nvoid unique_ptr_test_impl() {\r\n    default_delete<int> int_deleter{};\r\n    unique_ptr<int> uptr0{};\r\n    unique_ptr<int, default_delete<int>&> uptr1(new int(), int_deleter);\r\n    unique_ptr<int> uptr2(new int(), move(int_deleter));\r\n    unique_ptr<int> uptr3{move(uptr1)};\r\n#if _HAS_AUTO_PTR_ETC\r\n    unique_ptr<int> uptr4{auto_ptr<int>{}};\r\n    (void) uptr4;\r\n#endif \/\/ _HAS_AUTO_PTR_ETC\r\n\r\n    uptr3 = move(uptr1);\r\n\r\n    default_delete<int[]> int_arr_deleter{};\r\n    unique_ptr<int[]> uptr5{};\r\n    unique_ptr<int[]> uptr6{new int[5]};\r\n    unique_ptr<int[], default_delete<int[]>&> uptr7(new int[5], int_arr_deleter);\r\n    unique_ptr<int[]> uptr8{move(uptr7)};\r\n    uptr8 = move(uptr7);\r\n    uptr6.reset(new int[5]);\r\n\r\n    auto uptr9  = make_unique<int>(5);\r\n    auto uptr10 = make_unique<int[]>(5);\r\n\r\n    swap_test(uptr9);\r\n    comparable_test(uptr2, uptr5);\r\n    comparable_test(uptr1, nullptr);\r\n    comparable_test(nullptr, uptr10);\r\n    hash_test(uptr0);\r\n}\r\n\r\nvoid memory_test() {\r\n    shared_ptr_test_impl();\r\n    weak_ptr_test_impl();\r\n    unique_ptr_test_impl();\r\n\r\n    struct my_shared_from_this : enable_shared_from_this<my_shared_from_this> {\r\n        my_shared_from_this() {}\r\n    };\r\n    my_shared_from_this msft{};\r\n    default_delete<void> dd0{default_delete<int>{}};\r\n    default_delete<int[]> dd1{default_delete<int[]>{}};\r\n    dd1(new int[5]);\r\n\r\n    int* int_ptr{};\r\n    undeclare_reachable(int_ptr);\r\n\r\n    auto sptr = make_shared<int>(5);\r\n    auto wptr = weak_ptr<int>(sptr);\r\n    owner_less_test_impl(owner_less<shared_ptr<int>>{}, sptr);\r\n    owner_less_test_impl(owner_less<weak_ptr<int>>{}, weak_ptr<int>(sptr));\r\n    owner_less_test_impl(owner_less<void>{}, sptr, wptr);\r\n}\r\n\r\n#ifndef _M_CEE\r\ntemplate <typename Mutex>\r\nvoid timed_mutex_test_impl() {\r\n    Mutex mtx{};\r\n    (void) mtx.try_lock_for(chrono::seconds(1));\r\n    (void) mtx.try_lock_until(chrono::system_clock::now());\r\n}\r\n\r\nvoid mutex_test() {\r\n    mutex mtx{};\r\n    recursive_mutex rmtx{};\r\n    recursive_timed_mutex rtmtx{};\r\n\r\n    (void) try_lock(mtx, rmtx);\r\n    (void) try_lock(mtx, rmtx, rtmtx);\r\n    lock(mtx, rmtx);\r\n    lock(mtx, rmtx, rtmtx);\r\n    \/\/ lock_guard and scoped_lock instantiated in P0156R2_scoped_lock\r\n    unique_lock<recursive_timed_mutex> ul_mtx1{rtmtx, chrono::seconds(1)};\r\n    unique_lock<recursive_timed_mutex> ul_mtx2{rtmtx, chrono::system_clock::now()};\r\n\r\n    timed_mutex_test_impl<unique_lock<recursive_timed_mutex>>();\r\n    swap_test(ul_mtx2);\r\n    once_flag of{};\r\n    call_once(of, []() {});\r\n    condition_variable_test_impl<condition_variable>();\r\n\r\n    timed_mutex_test_impl<timed_mutex>();\r\n    timed_mutex_test_impl<recursive_timed_mutex>();\r\n}\r\n#endif \/\/ _M_CEE\r\n\r\nvoid ostream_test() {\r\n    stringstream ss{};\r\n    ostream os{ss.rdbuf()};\r\n\r\n    wstringstream wss{};\r\n    wostream wos{wss.rdbuf()};\r\n\r\n    unsigned short us{};\r\n    wos << us;\r\n\r\n    \/\/ \/analyze doesn't like these being nullptr\r\n    char c_str[]     = \"1\";\r\n    wchar_t wc_str[] = L\"2\";\r\n\r\n    wos << c_str;\r\n    wos << *c_str;\r\n    os << c_str;\r\n    os << *c_str;\r\n    wos << wc_str;\r\n    wos << *wc_str;\r\n\r\n    signed char sc_str[]   = \"3\";\r\n    unsigned char uc_str[] = \"4\";\r\n\r\n    os << sc_str;\r\n    os << *sc_str;\r\n    os << uc_str;\r\n    os << *uc_str;\r\n\r\n    string str{};\r\n    os << str;\r\n    os << endl;\r\n    os << ends;\r\n    os << flush;\r\n    os << error_code{};\r\n}\r\n\r\ntemplate <typename Distribution>\r\nvoid distribution_test_impl(Distribution& d) {\r\n    random_device rd{};\r\n    mt19937 gen(rd());\r\n    (void) d(gen);\r\n    (void) d(gen, d.param());\r\n    equality_test(d);\r\n    cin >> d;\r\n    cout << d;\r\n}\r\n\r\ntemplate <typename Engine, typename SeedArg>\r\nvoid common_engine_test_impl(SeedArg& sa) {\r\n    Engine eng(sa);\r\n    eng.seed(sa);\r\n    equality_test(eng);\r\n    cin >> eng;\r\n    cout << eng;\r\n}\r\n\r\ntemplate <typename Engine>\r\nvoid engine_test_impl() {\r\n    seed_seq ss({1, 2, 3, 4, 5});\r\n    common_engine_test_impl<Engine>(ss);\r\n}\r\n\r\ntemplate <typename Engine>\r\nvoid tr1_engine_test_impl() {\r\n    random_device rd{};\r\n    mt19937 gen(rd());\r\n    common_engine_test_impl<Engine>(gen);\r\n}\r\n\r\nvoid random_test() {\r\n    seed_seq ss0({1, 2, 3, 4, 5, 6});\r\n    vector<uint32_t> v{1, 2, 3, 4};\r\n    seed_seq ss1(v.begin(), v.end());\r\n    ss0.generate(v.begin(), v.end());\r\n    ss1.param(ostream_iterator<unsigned int>(cout, \" \"));\r\n\r\n    random_device rd{};\r\n    mt19937 gen(rd());\r\n    (void) generate_canonical<double, 10>(gen);\r\n\r\n    engine_test_impl<minstd_rand0>(); \/\/ linear congruential engine\r\n    engine_test_impl<mt19937>(); \/\/ mersenne twister engine\r\n    engine_test_impl<ranlux24_base>(); \/\/ subtract_with_carry_engine\r\n    engine_test_impl<ranlux24>(); \/\/ discard block engine\r\n    engine_test_impl<knuth_b>(); \/\/ shuffle_order_engine\r\n    engine_test_impl<independent_bits_engine<minstd_rand0, 2, uint32_t>>();\r\n    engine_test_impl<mt19937_64>();\r\n    engine_test_impl<ranlux48_base>();\r\n    engine_test_impl<ranlux48>();\r\n\r\n    linear_congruential<uint_fast32_t, 16807, 0, 2147483647> minstd_rand_eng(gen);\r\n    minstd_rand_eng.seed(gen);\r\n\r\n    tr1_engine_test_impl<linear_congruential<uint_fast32_t, 16807, 0, 2147483647>>();\r\n\r\n#if _HAS_TR1_NAMESPACE\r\n    tr1_engine_test_impl<ranlux3>();\r\n    tr1_engine_test_impl<ranlux4>();\r\n    tr1_engine_test_impl<ranlux3_01>();\r\n    tr1_engine_test_impl<ranlux4_01>();\r\n    tr1_engine_test_impl<ranlux64_base_01>();\r\n    tr1_engine_test_impl<ranlux_base_01>();\r\n#endif \/\/ _HAS_TR1_NAMESPACE\r\n\r\n    uniform_int_distribution<> uni_int_d{};\r\n    bernoulli_distribution bern_d{};\r\n    geometric_distribution<> geo_d{};\r\n    poisson_distribution<> pois_d{};\r\n    binomial_distribution<> binom_d{};\r\n    uniform_real_distribution<> uni_real_d{};\r\n    exponential_distribution<> expon_d{};\r\n    normal_distribution<> norm_d{};\r\n    gamma_distribution<> gamma_d{};\r\n    weibull_distribution<> weib_d{};\r\n    extreme_value_distribution<> ext_v_d{};\r\n    lognormal_distribution<> log_norm_d{};\r\n    chi_squared_distribution<> chi_sq_d{};\r\n    cauchy_distribution<> cauchy_d{};\r\n    fisher_f_distribution<> fish_f_d{};\r\n    student_t_distribution<> stud_t_d{};\r\n    negative_binomial_distribution<> neg_bi_d{};\r\n    discrete_distribution<> disc_d1(v.begin(), v.end());\r\n    auto sq_func = [](double val) { return val * val; };\r\n    discrete_distribution<> disc_d2(5, 3.5, 7.5, sq_func);\r\n    piecewise_constant_distribution<> piece_const_d1(v.begin(), v.end(), v.begin());\r\n    piecewise_constant_distribution<> piece_const_d2{{1.0, 2.0, 3.0, 4.0, 5.0}, sq_func};\r\n    piecewise_constant_distribution<> piece_const_d3(4, 0.0, 10.0, sq_func);\r\n    piecewise_linear_distribution<> piece_line_d1(v.begin(), v.end(), v.begin());\r\n    piecewise_linear_distribution<> piece_line_d2({1.0, 2.0, 3.0, 4.0}, sq_func);\r\n    piecewise_linear_distribution<> piece_line_d3(4, 0.0, 10.0, sq_func);\r\n\r\n    distribution_test_impl(uni_int_d);\r\n    distribution_test_impl(bern_d);\r\n    distribution_test_impl(geo_d);\r\n    distribution_test_impl(pois_d);\r\n    distribution_test_impl(binom_d);\r\n    distribution_test_impl(uni_real_d);\r\n    distribution_test_impl(expon_d);\r\n    distribution_test_impl(norm_d);\r\n    distribution_test_impl(gamma_d);\r\n    distribution_test_impl(weib_d);\r\n    distribution_test_impl(ext_v_d);\r\n    distribution_test_impl(log_norm_d);\r\n    distribution_test_impl(chi_sq_d);\r\n    distribution_test_impl(cauchy_d);\r\n    distribution_test_impl(fish_f_d);\r\n    distribution_test_impl(stud_t_d);\r\n    distribution_test_impl(neg_bi_d);\r\n    distribution_test_impl(disc_d1);\r\n    distribution_test_impl(disc_d2);\r\n    distribution_test_impl(piece_const_d1);\r\n    distribution_test_impl(piece_const_d2);\r\n    distribution_test_impl(piece_const_d3);\r\n    distribution_test_impl(piece_line_d1);\r\n    distribution_test_impl(piece_line_d2);\r\n    distribution_test_impl(piece_line_d3);\r\n\r\n    (void) uni_int_d(gen, uni_int_d(gen));\r\n}\r\n\r\nvoid ratio_test() {\r\n    using half       = ratio<1, 2>;\r\n    using one        = ratio_add<half, half>;\r\n    using half_again = ratio_subtract<one, half>;\r\n    using quarter    = ratio_multiply<half, half>;\r\n    using two        = ratio_divide<one, half>;\r\n\r\n    TRAIT_V(ratio_equal, half, half);\r\n    TRAIT_V(ratio_not_equal, half_again, quarter);\r\n    TRAIT_V(ratio_less, half, two);\r\n    TRAIT_V(ratio_less_equal, half, half_again);\r\n    TRAIT_V(ratio_greater, one, half);\r\n    TRAIT_V(ratio_greater_equal, half, half_again);\r\n}\r\n\r\ntemplate <typename CharType>\r\nvoid regex_traits_test_impl() {\r\n    CharType buffer[10]{};\r\n    regex_traits<CharType> rt{};\r\n\r\n    rt.transform(begin(buffer), end(buffer));\r\n    rt.transform_primary(begin(buffer), end(buffer));\r\n    rt.lookup_classname(begin(buffer), end(buffer));\r\n    rt.lookup_collatename(begin(buffer), end(buffer));\r\n}\r\n\r\ntemplate <typename SubMatchType>\r\nvoid sub_match_test_impl() {\r\n    SubMatchType sm{};\r\n    using char_type = typename SubMatchType::value_type;\r\n\r\n    char_type value{};\r\n    basic_string<char_type> str{};\r\n\r\n    comparable_test(sm);\r\n    comparable_test(sm, &value);\r\n    comparable_test(&value, sm);\r\n    comparable_test(sm, value);\r\n    comparable_test(value, sm);\r\n    comparable_test(sm, str);\r\n    comparable_test(str, sm);\r\n\r\n    basic_stringstream<char_type> ss{};\r\n    ss << sm;\r\n}\r\n\r\ntemplate <typename MatchResultsType>\r\nvoid match_results_test_impl() {\r\n    MatchResultsType mr{};\r\n    using char_type = typename MatchResultsType::char_type;\r\n    basic_stringstream<char_type> ss{};\r\n    ostream_iterator<int, char_type> out_it(ss);\r\n    basic_string<char_type> str{};\r\n\r\n    char_type out_buffer[5]{};\r\n\r\n    mr.format(out_it, str.data(), str.data() + str.size());\r\n    mr.format(out_it, str);\r\n    mr.format(out_buffer, str.data(), str.data() + str.size());\r\n    mr.format(out_buffer, str);\r\n    str = mr.format(str);\r\n\r\n    equality_test(mr);\r\n    swap_test(mr);\r\n}\r\n\r\ntemplate <typename BasicRegexType>\r\nvoid basic_regex_test_impl() {\r\n    using char_type = typename BasicRegexType::value_type;\r\n    basic_string<char_type> str{};\r\n\r\n    BasicRegexType br1(str);\r\n    BasicRegexType br2(begin(str), end(str), regex_constants::ECMAScript);\r\n    BasicRegexType br3(begin(str), end(str));\r\n\r\n    br1 = str;\r\n    br2.assign(str);\r\n    br3.assign(begin(str), end(str));\r\n\r\n    swap_test(br1);\r\n\r\n    (void) regex_match(begin(str), end(str), br1);\r\n    (void) regex_match(str.c_str(), br1);\r\n\r\n    match_results<const char_type*> mrc{};\r\n    regex_match(str.c_str(), mrc, br1);\r\n\r\n    match_results<typename basic_string<char_type>::const_iterator> mrs{};\r\n    regex_match(str, mrs, br1);\r\n    (void) regex_match(str, br1);\r\n\r\n    regex_search(cbegin(str), cend(str), mrs, br1);\r\n    (void) regex_search(cbegin(str), cend(str), br1);\r\n    (void) regex_search(str.c_str(), br1);\r\n    regex_search(str.c_str(), mrc, br1);\r\n    regex_search(str, mrs, br1);\r\n    (void) regex_search(str, br1);\r\n\r\n    basic_stringstream<char_type> ss{};\r\n    ostream_iterator<int, char_type> out_it(ss);\r\n    char_type out_buffer[5] = {0};\r\n\r\n    regex_replace(out_it, cbegin(str), cend(str), br1, str);\r\n    regex_replace(out_buffer, cbegin(str), cend(str), br1, str);\r\n    regex_replace(out_it, begin(str), end(str), br1, str.c_str());\r\n    (void) regex_replace(str, br1, str);\r\n    (void) regex_replace(str, br1, str.c_str());\r\n    (void) regex_replace(str.c_str(), br1, str);\r\n    (void) regex_replace(str.c_str(), br1, str.c_str());\r\n}\r\n\r\ntemplate <typename RegexTokenIterator>\r\nvoid regex_token_iterator_test_impl() {\r\n    using it_type      = typename RegexTokenIterator::value_type::iterator;\r\n    int submatches[10] = {0};\r\n    it_type start{}, finish{};\r\n    typename RegexTokenIterator::regex_type rgx{};\r\n    RegexTokenIterator rti0(start, finish, rgx, submatches);\r\n}\r\n\r\nvoid regex_test() {\r\n    regex_traits_test_impl<char>();\r\n    regex_traits_test_impl<wchar_t>();\r\n\r\n    sub_match_test_impl<csub_match>();\r\n    sub_match_test_impl<wcsub_match>();\r\n    sub_match_test_impl<ssub_match>();\r\n    sub_match_test_impl<wssub_match>();\r\n\r\n    match_results_test_impl<cmatch>();\r\n    match_results_test_impl<wcmatch>();\r\n    match_results_test_impl<smatch>();\r\n    match_results_test_impl<wsmatch>();\r\n\r\n    basic_regex_test_impl<regex>();\r\n    basic_regex_test_impl<wregex>();\r\n\r\n    cregex_iterator cri{};\r\n    wcregex_iterator wcri{};\r\n    sregex_iterator sri{};\r\n    wsregex_iterator wsri{};\r\n\r\n    regex_token_iterator_test_impl<cregex_token_iterator>();\r\n    regex_token_iterator_test_impl<wcregex_token_iterator>();\r\n    regex_token_iterator_test_impl<sregex_token_iterator>();\r\n    regex_token_iterator_test_impl<wsregex_token_iterator>();\r\n}\r\n\r\n\/\/ need custom minimal allocator to use for scoped_allocator_test to reach all template paths\r\ntemplate <typename T>\r\nstruct custom_allocator {\r\n    using value_type = T;\r\n\r\n    custom_allocator() {}\r\n\r\n    template <class U>\r\n    custom_allocator(const custom_allocator<U>&) {}\r\n\r\n    T* allocate(size_t) {\r\n        return nullptr;\r\n    }\r\n\r\n    void deallocate(T*, size_t) {}\r\n};\r\n\r\ntemplate <typename T, typename U>\r\nbool operator==(const custom_allocator<T>&, const custom_allocator<U>&) {\r\n    return true;\r\n}\r\n\r\ntemplate <typename T, typename U>\r\nbool operator!=(const custom_allocator<T>& a, const custom_allocator<U>& b) {\r\n    return !(a == b);\r\n}\r\n\r\nvoid scoped_allocator_test() {\r\n    using my_vector_saa = scoped_allocator_adaptor<allocator<vector<int>>, allocator<int>>;\r\n    using my_double_saa = scoped_allocator_adaptor<allocator<vector<double>>, allocator<int>>;\r\n\r\n    INSTANTIATE(my_vector_saa::rebind<allocator<double>>);\r\n\r\n    allocator<vector<int>> vec_alloc{};\r\n    allocator<int> int_alloc{};\r\n\r\n    my_vector_saa saa1(move(vec_alloc), move(int_alloc));\r\n    my_double_saa saa2(saa1);\r\n    my_vector_saa saa3(move(saa2));\r\n    saa2 = move(saa1);\r\n    saa3 = saa2;\r\n\r\n    scoped_allocator_adaptor<custom_allocator<int>>\r\n        custom_saa{}; \/\/ needed to hit .construct paths with nonconvertible allocator\r\n\r\n    vector<int> val{};\r\n    vector<int>* ptr = &val;\r\n    custom_saa.construct(ptr, static_cast<size_t>(1), 2);\r\n\r\n    saa1.construct(ptr, static_cast<size_t>(1), 2);\r\n\r\n    tuple<int, int> tuple_val{};\r\n    tuple<int, int>* tuple_ptr = &tuple_val; \/\/ tuple needed to hit .construct paths with allocator_arg_t\r\n    saa1.construct(tuple_ptr, make_pair(1, 2));\r\n\r\n    using my_pair = pair<vector<int>, vector<int>>;\r\n    auto pair_ptr = static_cast<my_pair*>(malloc(sizeof(my_pair)));\r\n\r\n    custom_saa.construct(\r\n        pair_ptr, piecewise_construct, make_tuple(static_cast<size_t>(1), 2), make_tuple(static_cast<size_t>(1), 2));\r\n    saa1.construct(\r\n        pair_ptr, piecewise_construct, make_tuple(static_cast<size_t>(1), 2), make_tuple(static_cast<size_t>(1), 2));\r\n\r\n    using tuple_pair = pair<tuple<int, int>, tuple<int, int>>;\r\n    auto tp_ptr      = static_cast<tuple_pair*>(malloc(sizeof(tuple_pair)));\r\n    saa1.construct(tp_ptr, piecewise_construct, make_tuple(make_pair(1, 2)), make_tuple(make_pair(1, 2)));\r\n\r\n    saa1.construct(pair_ptr);\r\n    vector<int> vec{};\r\n    saa1.construct(pair_ptr, move(vec), move(vec));\r\n\r\n    my_pair vec_pair{};\r\n    saa1.construct(pair_ptr, vec_pair);\r\n    saa1.construct(pair_ptr, move(vec_pair));\r\n\r\n    equality_test(saa1); \/\/ same outer, same inner\r\n    equality_test(saa1, saa2); \/\/ different outer, same inner\r\n\r\n    scoped_allocator_adaptor<allocator<vector<double>>, allocator<double>> saa4;\r\n    equality_test(saa1, saa4); \/\/ different outer, different inner\r\n\r\n    scoped_allocator_adaptor<allocator<vector<int>>, allocator<double>> saa5{};\r\n    equality_test(saa1, saa5); \/\/ same outer, different inner\r\n\r\n    scoped_allocator_adaptor<allocator<vector<double>>> saa6; \/\/ different outer, missing inner\r\n    equality_test(saa1, saa6);\r\n\r\n    scoped_allocator_adaptor<allocator<vector<int>>> saa7; \/\/ same outer, missing inner\r\n    equality_test(saa1, saa7);\r\n}\r\n\r\n#ifndef _M_CEE\r\nvoid shared_mutex_test() {\r\n    using namespace chrono;\r\n\r\n    timed_mutex_test_impl<shared_timed_mutex>();\r\n\r\n    shared_timed_mutex stm{};\r\n    (void) stm.try_lock_shared_for(seconds(1));\r\n    (void) stm.try_lock_shared_until(system_clock::now());\r\n\r\n    shared_lock<shared_timed_mutex> sl1(stm, seconds(1));\r\n    shared_lock<shared_timed_mutex> sl2(stm, system_clock::now());\r\n\r\n    (void) sl1.try_lock_for(seconds(1));\r\n    (void) sl2.try_lock_until(system_clock::now());\r\n    swap_test(sl1);\r\n}\r\n#endif \/\/ _M_CEE\r\n\r\ntemplate <typename T>\r\nvoid sstream_test_impl() {\r\n    T val{};\r\n    swap_test(val);\r\n}\r\n\r\nvoid sstream_test() {\r\n    sstream_test_impl<stringbuf>();\r\n    sstream_test_impl<wstringbuf>();\r\n    sstream_test_impl<istringstream>();\r\n    sstream_test_impl<wistringstream>();\r\n    sstream_test_impl<ostringstream>();\r\n    sstream_test_impl<wostringstream>();\r\n    sstream_test_impl<stringstream>();\r\n    sstream_test_impl<wstringstream>();\r\n}\r\n\r\nvoid streambuf_test() {\r\n    stringstream ss{};\r\n    basic_streambuf<char>& bsbc = *ss.rdbuf();\r\n    (void) bsbc;\r\n\r\n    wstringstream wss{};\r\n    basic_streambuf<wchar_t>& bsbwc = *wss.rdbuf();\r\n    (void) bsbwc;\r\n\r\n    \/\/ istreambuf_iterator and ostreambuf_iterator covered in iterators test\r\n}\r\n\r\n#ifndef _M_CEE\r\nvoid thread_test() {\r\n    using namespace chrono;\r\n\r\n    thread thr([](int, int) {}, 1, 2);\r\n\r\n    this_thread::sleep_for(seconds(1));\r\n    this_thread::sleep_until(system_clock::now());\r\n\r\n    thread::id thr_id{};\r\n\r\n    cout << thr_id;\r\n    hash_test(thr_id);\r\n}\r\n#endif \/\/ _M_CEE\r\n\r\nvoid tuple_test() {\r\n    allocator<double> my_alloc{};\r\n    custom_allocator<double> custom_alloc{}; \/\/ to hit _Tuple_val non-convertible allocator\r\n\r\n    tuple<> empty_tuple1(allocator_arg, allocator<double>());\r\n    tuple<> empty_tuple2(allocator_arg, allocator<double>(), empty_tuple1);\r\n    (void) empty_tuple2;\r\n\r\n    tuple<int, int> tup1{};\r\n    tuple<const int&, const int&> tup2(tup1);\r\n    tuple<const int&, const int&> tup3(allocator_arg, my_alloc, tup1);\r\n    tuple<const char*, const char*> tup4(\"Hello\", \"World\");\r\n    tuple<const char*, const char*> tup5(allocator_arg, my_alloc, \"Hello\", \"World\");\r\n    tuple<string, string> tup6(\"Hello\", \"World\");\r\n    tuple<string, string> tup7(allocator_arg, my_alloc, \"Hello\", \"World\");\r\n\r\n    tup6 = tup4;\r\n    tup7 = move(tup5);\r\n\r\n    tuple<int, int> tup8(allocator_arg, my_alloc);\r\n    tuple<int, int> tup9(allocator_arg, my_alloc, tup8);\r\n    auto int_pair = make_pair(1, 2);\r\n    tuple<int, int> tup10(int_pair);\r\n    tuple<int, int> tup11(allocator_arg, my_alloc, int_pair);\r\n\r\n    tup10 = int_pair;\r\n\r\n    tuple<int, int> tup12(allocator_arg, my_alloc, move(tup9));\r\n    tuple<int, int> tup13(move(int_pair));\r\n    tuple<int, int> tup14(allocator_arg, my_alloc, move(int_pair));\r\n\r\n    tup11 = move(int_pair);\r\n\r\n    comparable_test(tup12);\r\n    swap_test(tup13);\r\n\r\n    \/\/ Extras to ensure hitting _Tuple_val specializations.\r\n    tuple<int> tup15(allocator_arg, custom_alloc, 1); \/\/ construct with non-convertible allocator.\r\n    tuple<tuple<int, int>> tup16(allocator_arg, my_alloc, tup14); \/\/ construct with leading allocator.\r\n    tuple<string> tup17(allocator_arg, my_alloc, \"MyStr\"); \/\/ construct with trailing allocator.\r\n\r\n    (void) get<0>(tup15);\r\n    (void) get<0>(move(tup16));\r\n\r\n    const tuple<string> tup17_c = tup17;\r\n    (void) get<0>(tup17_c);\r\n    (void) get<0>(move(tup17_c));\r\n\r\n    (void) get<int>(tup15);\r\n    (void) get<tuple<int, int>>(move(tup16));\r\n    (void) get<string>(tup17_c);\r\n    (void) get<string>(move(tup17_c));\r\n\r\n    (void) get<volatile int>(tuple<volatile int>{});\r\n    (void) get<const volatile int>(tuple<const volatile int>{});\r\n\r\n    int a = 1, b = 2;\r\n    tie(a, b) = make_tuple(a, b);\r\n    (void) forward_as_tuple(string{}, string{});\r\n\r\n    (void) tuple_cat(tup15, tup16);\r\n\r\n#if _HAS_CXX17\r\n    apply(plus<>{}, tup1);\r\n    (void) make_from_tuple<long>(tuple<int>(1729));\r\n#endif \/\/ _HAS_CXX17\r\n\r\n    pair<string, string> pair1(\r\n        piecewise_construct, make_tuple(\"Hello\", static_cast<size_t>(6)), make_tuple(\"World\", static_cast<size_t>(6)));\r\n\r\n    TRAIT_V(uses_allocator, tuple<int>, allocator<double>);\r\n}\r\n\r\nstruct utility_test_helper {};\r\n\r\nbool operator==(const utility_test_helper&, const utility_test_helper&) {\r\n    return true;\r\n}\r\n\r\nbool operator<(const utility_test_helper&, const utility_test_helper&) {\r\n    return false;\r\n}\r\n\r\nvoid utility_test() {\r\n    struct my_class1 {};\r\n    my_class1 mc1{};\r\n    swap_test(mc1);\r\n\r\n    \/\/ iter_swap covered in algorithms_test\r\n\r\n    int arr1[5] = {0};\r\n    int arr2[5] = {0};\r\n    swap(arr1, arr2);\r\n\r\n    pair<int, int> p1 = make_pair(1, 2);\r\n    pair<const int&, const int&> p2(p1);\r\n    p1 = p2;\r\n\r\n    \/\/ pair piecewise construct from tuple covered in tuple_test\r\n\r\n    pair<string, string> p3(\"Hello\", \"World\");\r\n    pair<const char*, const char*> p4(\"Hello\", \"World\");\r\n    pair<string, string> p5(move(p4));\r\n    p5 = move(p4);\r\n\r\n    swap_test(p3);\r\n    comparable_test(p1);\r\n\r\n    {\r\n        utility_test_helper uth{};\r\n        using namespace rel_ops;\r\n        USE_VALUE(uth != uth);\r\n        USE_VALUE(uth > uth);\r\n        USE_VALUE(uth <= uth);\r\n        USE_VALUE(uth >= uth);\r\n    }\r\n\r\n    TRAIT_V(tuple_size, array<int, 5>);\r\n    TRAIT_V(tuple_size, pair<int, double>);\r\n    TRAIT_V(tuple_size, tuple<int, int, int>);\r\n    TRAIT_V(tuple_size, const tuple<int, int, int>);\r\n    TRAIT_V(tuple_size, volatile tuple<int, int, int>);\r\n    TRAIT_V(tuple_size, const volatile tuple<int, int, int>);\r\n\r\n    INSTANTIATE(tuple_element_t<1, array<int, 5>>);\r\n    INSTANTIATE(tuple_element_t<0, pair<int, double>>);\r\n    INSTANTIATE(tuple_element_t<1, pair<int, double>>);\r\n    INSTANTIATE(tuple_element_t<2, tuple<int, int, int>>);\r\n    INSTANTIATE(tuple_element_t<2, const tuple<int, int, int>>);\r\n    INSTANTIATE(tuple_element_t<2, volatile tuple<int, int, int>>);\r\n    INSTANTIATE(tuple_element_t<2, const volatile tuple<int, int, int>>);\r\n\r\n    auto p6       = make_pair(1, string(\"test\"));\r\n    const auto p7 = as_const(p6);\r\n\r\n    (void) get<0>(p6);\r\n    (void) get<int>(p6);\r\n    (void) get<string>(p6);\r\n\r\n    (void) get<0>(p7);\r\n    (void) get<int>(p7);\r\n    (void) get<string>(p7);\r\n\r\n    (void) get<0>(move(p6));\r\n    (void) get<int>(move(p6));\r\n    (void) get<string>(move(p6));\r\n\r\n    (void) get<0>(move(p7));\r\n    (void) get<int>(move(p7));\r\n    (void) get<string>(move(p7));\r\n\r\n    exchange(p3, move(p5));\r\n}\r\n\r\nvoid typeindex_test() {\r\n    type_index ti(typeid(int));\r\n    hash_test(ti);\r\n}\r\n\r\ntemplate <typename FunctorArg, typename Arg>\r\nvoid functors_test_impl(Arg val) {\r\n    \/\/ Following from <xstddef>:\r\n    (void) plus<FunctorArg>()(val, val);\r\n    (void) minus<FunctorArg>()(val, val);\r\n    (void) multiplies<FunctorArg>()(val, val);\r\n    (void) equal_to<FunctorArg>()(val, val);\r\n    (void) less<FunctorArg>()(val, val);\r\n\r\n    (void) divides<FunctorArg>()(val, val);\r\n    (void) modulus<FunctorArg>()(val, val);\r\n    (void) negate<FunctorArg>()(val);\r\n    (void) not_equal_to<FunctorArg>()(val, val);\r\n    (void) greater<FunctorArg>()(val, val);\r\n    (void) greater_equal<FunctorArg>()(val, val);\r\n    (void) less_equal<FunctorArg>()(val, val);\r\n    (void) logical_and<FunctorArg>()(val, val);\r\n    (void) logical_or<FunctorArg>()(val, val);\r\n    (void) logical_not<FunctorArg>()(val);\r\n    (void) bit_and<FunctorArg>()(val, val);\r\n    (void) bit_or<FunctorArg>()(val, val);\r\n    (void) bit_xor<FunctorArg>()(val, val);\r\n    (void) bit_not<FunctorArg>()(val);\r\n}\r\n\r\nint real_unary_function(int) {\r\n    return 1;\r\n}\r\n\r\nint real_binary_function(int, int) {\r\n    return 1;\r\n}\r\n\r\nvoid xfunctional_test() {\r\n    functors_test_impl<int>(5);\r\n    functors_test_impl<void>(5);\r\n    (void) not1(negate<int>())(5); \/\/ not1 requires T::second_argument_type\r\n    (void) not2(less_equal<int>())(5, 5); \/\/ not2 requires T::second_argument_type\r\n\r\n#if _HAS_AUTO_PTR_ETC\r\n    auto b1 = bind1st(plus<int>(), 1);\r\n    auto b2 = bind2nd(plus<int>(), 2);\r\n\r\n    (void) b1;\r\n    (void) b2;\r\n\r\n    auto ptuf = ptr_fun(real_unary_function);\r\n    auto ptbf = ptr_fun(real_binary_function);\r\n\r\n    (void) ptuf;\r\n    (void) ptbf;\r\n\r\n    struct A {\r\n        int fn() {\r\n            return 1;\r\n        }\r\n        int fn1(int) {\r\n            return 2;\r\n        }\r\n        int cfn() const {\r\n            return 3;\r\n        }\r\n        int cfn1(int) const {\r\n            return 4;\r\n        }\r\n    };\r\n\r\n    auto mft   = mem_fun(&A::fn);\r\n    auto mft1  = mem_fun(&A::fn1);\r\n    auto cmft  = mem_fun(&A::cfn);\r\n    auto cmft1 = mem_fun(&A::cfn1);\r\n\r\n    auto mfrt   = mem_fun_ref(&A::fn);\r\n    auto mfrt1  = mem_fun_ref(&A::fn1);\r\n    auto cmfrt  = mem_fun_ref(&A::cfn);\r\n    auto cmfrt1 = mem_fun_ref(&A::cfn1);\r\n\r\n    (void) mft;\r\n    (void) mft1;\r\n    (void) cmft;\r\n    (void) cmft1;\r\n\r\n    (void) mfrt;\r\n    (void) mfrt1;\r\n    (void) cmfrt;\r\n    (void) cmfrt1;\r\n#endif \/\/ _HAS_AUTO_PTR_ETC\r\n}\r\n\r\ntemplate <typename CharType>\r\nvoid facet_unicode_and_native_wchart_test_impl() {\r\n    locale loc{};\r\n\r\n    \/\/ <codecvt>\r\n    codecvt_utf8<CharType> cvt_utf8{};\r\n    codecvt_utf16<CharType> cvt_utf16{};\r\n    codecvt_utf8_utf16<CharType> cvt_utf8_utf16{};\r\n}\r\n\r\ntemplate <typename CharType>\r\nvoid facet_all_test_impl() {\r\n    locale loc{};\r\n    auto ccvt    = has_facet<codecvt<CharType, char, mbstate_t>>(loc);\r\n    auto ccvt_bn = has_facet<codecvt_byname<CharType, char, mbstate_t>>(loc);\r\n    auto ct      = has_facet<ctype<CharType>>(loc);\r\n    auto ct_bn   = has_facet<ctype_byname<CharType>>(loc);\r\n\r\n    \/\/ <xlocmon>\r\n    auto mp        = has_facet<moneypunct<CharType, false>>(loc);\r\n    auto mpbn      = has_facet<moneypunct_byname<CharType, false>>(loc);\r\n    auto mp_intl   = has_facet<moneypunct<CharType, true>>(loc);\r\n    auto mpbn_intl = has_facet<moneypunct_byname<CharType, true>>(loc);\r\n    auto mg        = has_facet<money_get<CharType>>(loc);\r\n    auto mput      = has_facet<money_put<CharType>>(loc);\r\n\r\n    \/\/ <xlocnum>\r\n    auto np   = has_facet<numpunct<CharType>>(loc);\r\n    auto npbn = has_facet<numpunct_byname<CharType>>(loc);\r\n    auto ng   = has_facet<num_get<CharType>>(loc);\r\n    auto nput = has_facet<num_put<CharType>>(loc);\r\n\r\n    \/\/ <xloctime>\r\n    auto tg   = has_facet<time_get<CharType>>(loc);\r\n    auto tgbn = has_facet<time_get_byname<CharType>>(loc);\r\n    auto tp   = has_facet<time_put<CharType>>(loc);\r\n    auto tpbn = has_facet<time_put_byname<CharType>>(loc);\r\n\r\n    \/\/ <xlocmes>\r\n    auto locmes   = has_facet<messages<CharType>>(loc);\r\n    auto locmesbn = has_facet<messages_byname<CharType>>(loc);\r\n\r\n    facet_unicode_and_native_wchart_test_impl<CharType>();\r\n\r\n    (void) ccvt;\r\n    (void) ccvt_bn;\r\n    (void) ct;\r\n    (void) ct_bn;\r\n    (void) mp;\r\n    (void) mpbn;\r\n    (void) mp_intl;\r\n    (void) mpbn_intl;\r\n    (void) mg;\r\n    (void) mput;\r\n    (void) np;\r\n    (void) npbn;\r\n    (void) ng;\r\n    (void) nput;\r\n    (void) tg;\r\n    (void) tgbn;\r\n    (void) tp;\r\n    (void) tpbn;\r\n    (void) locmes;\r\n    (void) locmesbn;\r\n}\r\n\r\nvoid xlocale_test() {\r\n    locale loc1{};\r\n\r\n    loc1(string{\"Hello\"}, string{\"World\"});\r\n    loc1.combine<numpunct<char>>(loc1);\r\n    locale loc2(loc1, new codecvt_utf8<wchar_t>);\r\n    use_facet<moneypunct<char, true>>(loc2);\r\n\r\n    \/\/ This test also covers <codecvt>\r\n    facet_all_test_impl<char>();\r\n    facet_all_test_impl<wchar_t>();\r\n    facet_unicode_and_native_wchart_test_impl<char16_t>();\r\n    facet_unicode_and_native_wchart_test_impl<char32_t>();\r\n#ifndef _NATIVE_WCHAR_T_DEFINED\r\n    facet_all_test_impl<unsigned short>();\r\n#endif \/\/ _NATIVE_WCHAR_T_DEFINED\r\n}\r\n\r\nvoid xlocbuf_test() {\r\n    wbuffer_convert<codecvt_utf8<wchar_t>> wb_cvt{};\r\n    wstring_convert<codecvt_utf8<wchar_t>> ws_cvt{};\r\n}\r\n\r\nvoid xmemory_test() {\r\n    int* buff = get_temporary_buffer<int>(4).first;\r\n    raw_storage_iterator<int*, int> rsi(buff);\r\n    return_temporary_buffer(buff);\r\n    (void) rsi;\r\n\r\n    \/\/ uninitialized_* in algorithms_test\r\n\r\n#if _HAS_AUTO_PTR_ETC\r\n    struct Base {};\r\n    struct Derived : Base {};\r\n\r\n    auto_ptr<Derived> ap1{};\r\n    auto auto_ptr_source = []() { return auto_ptr<Derived>{}; };\r\n    auto_ptr<Base> ap2(auto_ptr_source()); \/\/ converts to auto_ptr_ref\r\n\r\n    USE_VALUE(static_cast<auto_ptr<Base>>(ap1));\r\n\r\n    auto_ptr<Base> ap3(ap1);\r\n    ap3 = ap1;\r\n#endif \/\/ _HAS_AUTO_PTR_ETC\r\n}\r\n\r\nvoid xmemory0_test() {\r\n    INSTANTIATE(pointer_traits<unique_ptr<int>>);\r\n\r\n    struct Base {};\r\n\r\n    struct Derived : Base {};\r\n\r\n    INSTANTIATE(pointer_traits<unique_ptr<Base>>::rebind<Derived>);\r\n    INSTANTIATE(pointer_traits<int*>);\r\n    INSTANTIATE(pointer_traits<Base*>::rebind<Derived*>);\r\n\r\n    INSTANTIATE(allocator_traits<allocator<int>>);\r\n    INSTANTIATE(allocator_traits<allocator<int>>::rebind_alloc<double>);\r\n    INSTANTIATE(allocator_traits<allocator<int>>::rebind_traits<double>);\r\n\r\n    allocator<int> ai{};\r\n    custom_allocator<int> cai{};\r\n    int* ptr{};\r\n\r\n    allocator_traits<custom_allocator<int>>::construct(cai, ptr, 5);\r\n    allocator_traits<custom_allocator<int>>::destroy(cai, ptr);\r\n\r\n    allocator_traits<allocator<int>>::construct(ai, ptr, 5);\r\n    allocator_traits<allocator<int>>::destroy(ai, ptr);\r\n\r\n    INSTANTIATE(allocator<int>::rebind<double>);\r\n\r\n    allocator<double> ad(ai);\r\n    ai = ad;\r\n\r\n    allocator<int> ai2(ad);\r\n\r\n    ai2.construct(ptr, 1);\r\n    ai2.destroy(ptr);\r\n\r\n    INSTANTIATE(allocator<double>::rebind<int>);\r\n\r\n    ad = ai2;\r\n    equality_test(ad, ai);\r\n}\r\n\r\nvoid xstddef_test() {\r\n#if _HAS_AUTO_PTR_ETC\r\n    INSTANTIATE(unary_function<int, int>);\r\n    INSTANTIATE(binary_function<int, int, int>);\r\n#endif \/\/ _HAS_AUTO_PTR_ETC\r\n\r\n    \/\/ plus<>, minus<>, multiplies<>, equal_to<>, less<> tested in xfunctional_test\r\n\r\n    hash_test<bool>();\r\n    hash_test<char>();\r\n    hash_test<signed char>();\r\n    hash_test<unsigned char>();\r\n#ifdef __cpp_char8_t\r\n    hash_test<char8_t>();\r\n#endif \/\/ __cpp_char8_t\r\n    hash_test<char16_t>();\r\n    hash_test<char32_t>();\r\n    hash_test<wchar_t>();\r\n    hash_test<short>();\r\n    hash_test<unsigned short>();\r\n    hash_test<int>();\r\n    hash_test<unsigned int>();\r\n    hash_test<long>();\r\n    hash_test<unsigned long>();\r\n    hash_test<long long>();\r\n    hash_test<unsigned long long>();\r\n    hash_test<float>();\r\n    hash_test<double>();\r\n    hash_test<long double>();\r\n    hash_test<void*>();\r\n    \/\/ is_function covered in traits_test\r\n\r\n    int value{};\r\n    (void) addressof(value);\r\n    (void) addressof(real_unary_function);\r\n}\r\n\r\ntemplate <typename T1>\r\nvoid xtgmath_integral_test_impl() {\r\n    T1 arg1{1};\r\n    int int_value{};\r\n    long long_value{};\r\n    long double ld_value{};\r\n\r\n    (void) acos(arg1);\r\n    (void) asin(arg1);\r\n    (void) atan(arg1);\r\n    (void) ceil(arg1);\r\n    (void) cos(arg1);\r\n    (void) cosh(arg1);\r\n    (void) exp(arg1);\r\n    (void) fabs(arg1);\r\n    (void) floor(arg1);\r\n    (void) frexp(arg1, &int_value);\r\n    (void) ldexp(arg1, int_value);\r\n    (void) log(arg1);\r\n    (void) log10(arg1);\r\n    (void) sin(arg1);\r\n    (void) sinh(arg1);\r\n    (void) sqrt(arg1);\r\n    (void) tan(arg1);\r\n    (void) tanh(arg1);\r\n    (void) acosh(arg1);\r\n    (void) asinh(arg1);\r\n    (void) atanh(arg1);\r\n    (void) cbrt(arg1);\r\n    (void) erf(arg1);\r\n    (void) erfc(arg1);\r\n    (void) expm1(arg1);\r\n    (void) exp2(arg1);\r\n    (void) ilogb(arg1);\r\n    (void) lgamma(arg1);\r\n    (void) llrint(arg1);\r\n    (void) llround(arg1);\r\n    (void) log1p(arg1);\r\n    (void) log2(arg1);\r\n    (void) logb(arg1);\r\n    (void) lrint(arg1);\r\n    (void) lround(arg1);\r\n    (void) nearbyint(arg1);\r\n    (void) nexttoward(arg1, ld_value);\r\n    (void) rint(arg1);\r\n    (void) round(arg1);\r\n    (void) scalbln(arg1, long_value);\r\n    (void) scalbn(arg1, int_value);\r\n    (void) tgamma(arg1);\r\n    (void) trunc(arg1);\r\n}\r\n\r\ntemplate <typename T1, typename T2, typename T3>\r\nvoid xtgmath_arithmetic_test_impl() {\r\n    T1 arg1{1};\r\n    T2 arg2{2};\r\n\r\n    int int_value{};\r\n\r\n    USE_VALUE(atan2(arg1, arg2));\r\n    USE_VALUE(fmod(arg1, arg2));\r\n    T3 arg3{3};\r\n    USE_VALUE(fma(arg1, arg2, arg3));\r\n    USE_VALUE(remquo(arg1, arg2, &int_value));\r\n    USE_VALUE(copysign(arg1, arg2));\r\n    USE_VALUE(fdim(arg1, arg2));\r\n    USE_VALUE(fmax(arg1, arg2));\r\n    USE_VALUE(fmin(arg1, arg2));\r\n    USE_VALUE(hypot(arg1, arg2));\r\n    USE_VALUE(nextafter(arg1, arg2));\r\n    USE_VALUE(remainder(arg1, arg2));\r\n}\r\n\r\nvoid xtgmath_test() {\r\n    xtgmath_integral_test_impl<int>();\r\n    xtgmath_arithmetic_test_impl<int, int, int>();\r\n    xtgmath_arithmetic_test_impl<int, int, float>();\r\n    xtgmath_arithmetic_test_impl<int, float, float>();\r\n    xtgmath_arithmetic_test_impl<float, float, float>();\r\n    xtgmath_arithmetic_test_impl<int, float, double>();\r\n    xtgmath_arithmetic_test_impl<int, double, double>();\r\n    xtgmath_arithmetic_test_impl<double, double, double>();\r\n    xtgmath_arithmetic_test_impl<float, float, double>();\r\n    xtgmath_arithmetic_test_impl<float, double, double>();\r\n}\r\n\r\nvoid xtr1common_test() {\r\n    INSTANTIATE(integral_constant<int, 5>);\r\n    INSTANTIATE(bool_constant<true>);\r\n    INSTANTIATE(enable_if<true>);\r\n    INSTANTIATE(enable_if<false>);\r\n    INSTANTIATE(conditional_t<true, int, double>);\r\n    INSTANTIATE(conditional_t<false, int, double>);\r\n    \/\/ rest of traits in this header tested in type_traits_test:\r\n    \/\/ is_same, remove_const, remove_volatile, remove_cv,\r\n    \/\/ is_integral, is_floating_point, is_arithmetic,\r\n    \/\/ remove_reference\r\n}\r\n","avg_line_length":30.3245264207,"max_line_length":120,"alphanum_fraction":0.6570005425,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2461,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"..\/..\/include\/textEdit.h\"\n\n\nTextEdit::TextEdit():\n\tinsideArea(false),\n\tcurrentState(false),\n\tpreviousTime(0),\n    clickCounter(0)\n\n{\n\tmyLabel = new Label();\n\tmyButton = new Button();\n}\nTextEdit::~TextEdit() {\n\n}\n\nbool TextEdit::CheckArea(int posX, int posY) {\n\n\treturn myButton->CheckArea(posX, posY);\n}\n\nvoid TextEdit::ShoutDown() {\n\tmyLabel->ShoutDown();\n\tmyButton->ShoutDown();\n}\n\n\nbool TextEdit::onMouseButton(int button, int action) {\n\n\t\/\/myLabel->onMouseButton(button, action);\n\t\n\tcurrentState = myButton->onMouseButton(button, action);\n\n\n\tif (clickCounter == 1 && action == 1) {\n\t\t\n\t\tclickCounter++;\n\t}\n\n\tif (currentState == true && clickCounter == 0) {\n\t\tclickCounter++;\n\t}\n\n\tif (clickCounter == 2) {\n\t\tmyButton->ChangeColor(0.8, 0.9, 0.8, 1.0);\n\t\tclickCounter = 0;\n\t}\n\n\treturn currentState;\n}\n\nvoid TextEdit::CheckKey(int key, int action) {\n\n\n\t\/\/if (textToDisplay.length() > 0) {\n\t\/\/\tif (textToDisplay.back() == '\/') {\n\t\/\/\t\ttextToDisplay.pop_back();\n\t\/\/\t}\n\t\/\/}\n\n\tif (action && clickCounter) {\n\n\t\tswitch (key) {\n\t\tcase 294:\/\/Enter\n\t\t\t\tmyButton->ChangeColor(0.8, 0.9, 0.8, 1.0);\n\t\t\t\tclickCounter++;\n\t\t\tbreak;\n\n\t\tcase 295:\/\/Backspace\n\t\t\tif (currentText.length() > 0) {\n\t\t\t\tcurrentText.pop_back();\n\t\t\t}\n\t\t\tbreak;\n\t\t\t\t\n\t\tdefault:\n\t\t\tcurrentText += (char)key;\n\t\t\tbreak;\n\n\t\t}\n\t\tmyLabel->ChangeText(currentText);\n\t\ttextToDisplay = currentText;\n\t}\t\n}\n\nstd::string TextEdit::getCurrentText() {\n\treturn currentText;\n}\n\nvoid TextEdit::setCurrentText(std::string text) {\n\tcurrentText = text;\n\ttextToDisplay = currentText;\t\n}\n\nvoid TextEdit::UpdateSize(int winW, int winH) {\n\tmyLabel->UpdateSize(winW, winH);\n\tmyButton->UpdateSize(winW, winH);\n}\n\nvoid TextEdit::Init(int winW, int winH, float posX, float posY, int width, int hight, const char * bitmap, std::string textToDraw) {\n\n\ttextToDisplay = textToDraw;\n\tcurrentText = textToDraw;\n\tmyLabel->Init(winW, winH, posX, posY, hight, textToDraw);\n\tmyButton->Init(winW, winH, posX, posY, width, hight, bitmap);\n}\n\n\nvoid TextEdit::Render(double currentTime) {\n\n\tmyButton->Render(currentTime);\n\t\n\tif (clickCounter == 1) {\n\t\tif (int(currentTime) != previousTime) {\n\n\t\t\tif (textToDisplay.length() > 0) {\n\t\t\t\tif (textToDisplay.back() == '\/') {\n\t\t\t\t\ttextToDisplay.pop_back();\n\t\t\t\t} else {\n\t\t\t\t\ttextToDisplay += '\/';\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (textToDisplay.length() == 0) {\n\t\t\t\t\ttextToDisplay += '\/';\n\t\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\n\tmyLabel->ChangeText(textToDisplay);\n\tmyLabel->Render(currentTime);\n\n\tpreviousTime = int(currentTime);\n}","avg_line_length":18.3656716418,"max_line_length":132,"alphanum_fraction":0.648923202,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":873,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <KOMO\/komo-ext.h>\n\n\/\/===========================================================================\n\nvoid TEST(KomoSequence){\n  \n  rai::Configuration K(\"model.g\");\n  K.optimizeTree(false);\n  makeConvexHulls(K.frames);\n\n  KOMO_ext komo;\n  komo.setModel(K);\n  komo.setPathOpt(2., 20, 10.);\n\n  komo.setSquaredQAccVelHoming();\n\n  komo.setGrasp(1., \"humanR\", \"Long1\");\n  komo.setPlace(1.8, \"humanR\", \"Long1\", \"tableL\");\n  komo.setSlowAround(1., .1, 1e3);\n\n  komo.setGrasp(1., \"humanL\", \"Long2\");\n  komo.setPlace(1.8, \"humanL\", \"Long2\", \"tableR\");\n\n  komo.reset();\n  komo.run();\n\n  Graph result = komo.getReport(true);\n\n  for(uint i=0;i<2;i++) if(!komo.displayTrajectory(.1, true)) break;\n}\n\n\/\/===========================================================================\n\nint main(int argc,char** argv){\n  rai::initCmdLine(argc,argv);\n\n  testKomoSequence();\n\n  return 0;\n}\n\n","avg_line_length":20.7857142857,"max_line_length":77,"alphanum_fraction":0.5280641466,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":637,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2338.0,"content":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ REQUIRES: modules-build\n\n\/\/ WARNING: This test was generated by 'generate_private_header_tests.py'\n\/\/ and should not be edited manually.\n\n\/\/ expected-error@*:* {{use of private header from outside its module: '__algorithm\/merge.h'}}\n#include <__algorithm\/merge.h>\n","avg_line_length":39.8125,"max_line_length":94,"alphanum_fraction":0.5557299843,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1625,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <bits\/stdc++.h>\n#define ENDL '\\n'\n#define deb(u) cout << #u \" : \" << (u) << ENDL;\n#define deba(alias, u) cout << alias << \": \" << (u) << ENDL;\n#define debp(u, v) cout << u << \" : \" << v << ENDL;\n#define pb push_back\n#define F first\n#define S second\n#define lli long long\n#define pii pair<int, int>\n#define pll pair<lli, lli>\n#define ALL(a) (a).begin(), (a).end()\n#define ALLR(a) (a).rbegin(), (a).rend()\n#define FOR(i, a, n) for (int i = (a); i < (n); ++i)\n#define FORN(i, a, n) for (int i = (a - 1); i >= n; --i)\n#define IO                          \\\n  ios_base::sync_with_stdio(false); \\\n  cin.tie(0);                       \\\n  cout.tie(0)\nusing namespace std;\n\nint main()\n{\n  IO;\n  int n, m;\n  cin >> n >> m;\n  vector<vector<int>> g(n + 1);\n  vector<int> nodes(n + 1);\n  vector<pii> v(n + 1, {0, 0});\n  FOR(i, 0, m)\n  {\n    int from, to;\n    cin >> from >> to;\n    g[from].pb(to);\n    g[to].pb(from);\n  }\n  FOR(i, 1, n + 1)\n  {\n    int aux;\n    cin >> aux;\n    v[i] = {aux, i};\n  }\n\n  bool ok = true;\n\n  FOR(i, 1, n + 1)\n  {\n    \/\/ deb(i);\n    int val = v[i].F;\n    vector<bool> vb(val, false);\n    for (auto u : g[i])\n    {\n      if (v[u].F > val)\n        continue;\n      if (v[u].F == val)\n      {\n        ok = false;\n        break;\n      }\n      vb[v[u].F] = true;\n    }\n    bool flag = true;\n    FOR(j, 1, val)\n    {\n      if (!vb[j])\n      {\n        flag = false;\n        break;\n      }\n    }\n    if (!flag)\n    {\n      ok = false;\n      break;\n    }\n  }\n\n  sort(ALL(v));\n\n  if (ok)\n  {\n    FOR(i, 1, n + 1)\n    {\n      cout << v[i].S << \" \";\n    }\n  }\n  else\n  {\n    cout << \"-1\" << ENDL;\n  }\n\n  return 0;\n}","avg_line_length":17.4731182796,"max_line_length":60,"alphanum_fraction":0.4289230769,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":217,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Fill out your copyright notice in the Description page of Project Settings.\n\n#include \"TFG_Test.h\"\n#include \"Modules\/ModuleManager.h\"\n\nIMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, TFG_Test, \"TFG_Test\" );\n","avg_line_length":31.0,"max_line_length":78,"alphanum_fraction":0.801843318,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8387,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2014-2017, The Monero Project\n\/\/ \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without modification, are\n\/\/ permitted provided that the following conditions are met:\n\/\/ \n\/\/ 1. Redistributions of source code must retain the above copyright notice, this list of\n\/\/    conditions and the following disclaimer.\n\/\/ \n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice, this list\n\/\/    of conditions and the following disclaimer in the documentation and\/or other\n\/\/    materials provided with the distribution.\n\/\/ \n\/\/ 3. Neither the name of the copyright holder nor the names of its contributors may be\n\/\/    used to endorse or promote products derived from this software without specific\n\/\/    prior written permission.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n\/\/ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n\/\/ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n\/\/ THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n\/\/ STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n\/\/ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/ \n\/\/ Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers\n\n#include \"chaingen.h\"\n#include \"chaingen_tests_list.h\"\n\n#include \"integer_overflow.h\"\n\nusing namespace epee;\nusing namespace cryptonote;\n\nnamespace\n{\n  void split_miner_tx_outs(transaction& miner_tx, uint64_t amount_1)\n  {\n    uint64_t total_amount = get_outs_money_amount(miner_tx);\n    uint64_t amount_2 = total_amount - amount_1;\n    txout_target_v target = miner_tx.vout[0].target;\n\n    miner_tx.vout.clear();\n\n    tx_out out1;\n    out1.amount = amount_1;\n    out1.target = target;\n    miner_tx.vout.push_back(out1);\n\n    tx_out out2;\n    out2.amount = amount_2;\n    out2.target = target;\n    miner_tx.vout.push_back(out2);\n  }\n\n  void append_tx_source_entry(std::vector<cryptonote::tx_source_entry>& sources, const transaction& tx, size_t out_idx)\n  {\n    cryptonote::tx_source_entry se;\n    se.amount = tx.vout[out_idx].amount;\n    se.push_output(0, boost::get<cryptonote::txout_to_key>(tx.vout[out_idx].target).key, se.amount);\n    se.real_output = 0;\n    se.rct = false;\n    se.real_out_tx_key = get_tx_pub_key_from_extra(tx);\n    se.real_output_in_tx_index = out_idx;\n\n    sources.push_back(se);\n  }\n}\n\n\/\/======================================================================================================================\n\ngen_uint_overflow_base::gen_uint_overflow_base()\n  : m_last_valid_block_event_idx(static_cast<size_t>(-1))\n{\n  REGISTER_CALLBACK_METHOD(gen_uint_overflow_1, mark_last_valid_block);\n}\n\nbool gen_uint_overflow_base::check_tx_verification_context(const cryptonote::tx_verification_context& tvc, bool tx_added, size_t event_idx, const cryptonote::transaction& \/*tx*\/)\n{\n  return m_last_valid_block_event_idx < event_idx ? !tx_added && tvc.m_verifivation_failed : tx_added && !tvc.m_verifivation_failed;\n}\n\nbool gen_uint_overflow_base::check_block_verification_context(const cryptonote::block_verification_context& bvc, size_t event_idx, const cryptonote::block& \/*block*\/)\n{\n  return m_last_valid_block_event_idx < event_idx ? bvc.m_verifivation_failed | bvc.m_marked_as_orphaned : !bvc.m_verifivation_failed;\n}\n\nbool gen_uint_overflow_base::mark_last_valid_block(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry>& events)\n{\n  m_last_valid_block_event_idx = ev_index - 1;\n  return true;\n}\n\n\/\/======================================================================================================================\n\nbool gen_uint_overflow_1::generate(std::vector<test_event_entry>& events) const\n{\n  uint64_t ts_start = 1338224400;\n\n  GENERATE_ACCOUNT(miner_account);\n  MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start);\n  DO_CALLBACK(events, \"mark_last_valid_block\");\n  MAKE_ACCOUNT(events, bob_account);\n  MAKE_ACCOUNT(events, alice_account);\n\n  \/\/ Problem 1. Miner tx output overflow\n  MAKE_MINER_TX_MANUALLY(miner_tx_0, blk_0);\n  split_miner_tx_outs(miner_tx_0, MONEY_SUPPLY);\n  block blk_1;\n  if (!generator.construct_block_manually(blk_1, blk_0, miner_account, test_generator::bf_miner_tx, 0, 0, 0, crypto::hash(), 0, miner_tx_0))\n    return false;\n  events.push_back(blk_1);\n\n  \/\/ Problem 1. Miner tx outputs overflow\n  MAKE_MINER_TX_MANUALLY(miner_tx_1, blk_1);\n  split_miner_tx_outs(miner_tx_1, MONEY_SUPPLY);\n  block blk_2;\n  if (!generator.construct_block_manually(blk_2, blk_1, miner_account, test_generator::bf_miner_tx, 0, 0, 0, crypto::hash(), 0, miner_tx_1))\n    return false;\n  events.push_back(blk_2);\n\n  REWIND_BLOCKS(events, blk_2r, blk_2, miner_account);\n  MAKE_TX_LIST_START(events, txs_0, miner_account, bob_account, MONEY_SUPPLY, blk_2);\n  MAKE_TX_LIST(events, txs_0, miner_account, bob_account, MONEY_SUPPLY, blk_2);\n  MAKE_NEXT_BLOCK_TX_LIST(events, blk_3, blk_2r, miner_account, txs_0);\n  REWIND_BLOCKS(events, blk_3r, blk_3, miner_account);\n\n  \/\/ Problem 2. total_fee overflow, block_reward overflow\n  std::list<cryptonote::transaction> txs_1;\n  \/\/ Create txs with huge fee\n  txs_1.push_back(construct_tx_with_fee(events, blk_3, bob_account, alice_account, MK_COINS(1), MONEY_SUPPLY - MK_COINS(1)));\n  txs_1.push_back(construct_tx_with_fee(events, blk_3, bob_account, alice_account, MK_COINS(1), MONEY_SUPPLY - MK_COINS(1)));\n  MAKE_NEXT_BLOCK_TX_LIST(events, blk_4, blk_3r, miner_account, txs_1);\n\n  return true;\n}\n\n\/\/======================================================================================================================\n\nbool gen_uint_overflow_2::generate(std::vector<test_event_entry>& events) const\n{\n  uint64_t ts_start = 1338224400;\n\n  GENERATE_ACCOUNT(miner_account);\n  MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start);\n  MAKE_ACCOUNT(events, bob_account);\n  MAKE_ACCOUNT(events, alice_account);\n  REWIND_BLOCKS(events, blk_0r, blk_0, miner_account);\n  DO_CALLBACK(events, \"mark_last_valid_block\");\n\n  \/\/ Problem 1. Regular tx outputs overflow\n  std::vector<cryptonote::tx_source_entry> sources;\n  for (size_t i = 0; i < blk_0.miner_tx.vout.size(); ++i)\n  {\n    if (TESTS_DEFAULT_FEE < blk_0.miner_tx.vout[i].amount)\n    {\n      append_tx_source_entry(sources, blk_0.miner_tx, i);\n      break;\n    }\n  }\n  if (sources.empty())\n  {\n    return false;\n  }\n\n  std::vector<cryptonote::tx_destination_entry> destinations;\n  const account_public_address& bob_addr = bob_account.get_keys().m_account_address;\n  destinations.push_back(tx_destination_entry(MONEY_SUPPLY, bob_addr, false));\n  destinations.push_back(tx_destination_entry(MONEY_SUPPLY - 1, bob_addr, false));\n  \/\/ sources.front().amount = destinations[0].amount + destinations[2].amount + destinations[3].amount + TESTS_DEFAULT_FEE\n  destinations.push_back(tx_destination_entry(sources.front().amount - MONEY_SUPPLY - MONEY_SUPPLY + 1 - TESTS_DEFAULT_FEE, bob_addr, false));\n\n  cryptonote::transaction tx_1;\n  if (!construct_tx(miner_account.get_keys(), sources, destinations, std::vector<uint8_t>(), tx_1, 0))\n    return false;\n  events.push_back(tx_1);\n\n  MAKE_NEXT_BLOCK_TX1(events, blk_1, blk_0r, miner_account, tx_1);\n  REWIND_BLOCKS(events, blk_1r, blk_1, miner_account);\n\n  \/\/ Problem 2. Regular tx inputs overflow\n  sources.clear();\n  for (size_t i = 0; i < tx_1.vout.size(); ++i)\n  {\n    auto& tx_1_out = tx_1.vout[i];\n    if (tx_1_out.amount < MONEY_SUPPLY - 1)\n      continue;\n\n    append_tx_source_entry(sources, tx_1, i);\n  }\n\n  destinations.clear();\n  cryptonote::tx_destination_entry de;\n  de.addr = alice_account.get_keys().m_account_address;\n  de.amount = MONEY_SUPPLY - TESTS_DEFAULT_FEE;\n  destinations.push_back(de);\n  destinations.push_back(de);\n\n  cryptonote::transaction tx_2;\n  if (!construct_tx(bob_account.get_keys(), sources, destinations, std::vector<uint8_t>(), tx_2, 0))\n    return false;\n  events.push_back(tx_2);\n\n  MAKE_NEXT_BLOCK_TX1(events, blk_2, blk_1r, miner_account, tx_2);\n\n  return true;\n}\n","avg_line_length":39.5613207547,"max_line_length":178,"alphanum_fraction":0.7262429951,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1026,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/Author: WindCry1\n\/\/Mail: lanceyu120@gmail.com\n\/\/Website: https:\/\/windcry1.com\n#include<cstring>\n#include<cmath>\n#include<cstdio>\n#include<cctype>\n#include<cstdlib>\n#include<ctime>\n#include<vector>\n#include<iostream>\n#include<string>\n#include<queue>\n#include<set>\n#include<map>\n#include<algorithm>\n#include<complex>\n#include<stack>\n#include<bitset>\n#include<iomanip>\n#define ll long long\nusing namespace std;\nconst double clf=1e-8;\nconst int MMAX=0x7fffffff;\nconst int INF=0xfffffff;\nconst int mod=1e9+7;\nint w[10010];\ndouble v[10010],dp[10010];\nint main()\n{\n \t\/\/ios::sync_with_stdio(false);\n\t\/\/cin.tie(0);\n    \/\/cout.tie(0);\n\t\/\/freopen(\"C:\\\\Users\\\\LENOVO\\\\Desktop\\\\in.txt\",\"r\",stdin);\n\t\/\/freopen(\"C:\\\\Users\\\\LENOVO\\\\Desktop\\\\out.txt\",\"w\",stdout);\n\tint n,m;\n\twhile(scanf(\"%d%d\",&n,&m)&&(n||m))\n\t{\n\t\tfor(int i=1;i<=m;i++)\n\t\t\tcin>>w[i]>>v[i];\n\t\tfor(int i=0;i<=n;i++)\n\t\t\tdp[i]=1;\n\t\tfor(int i=1;i<=m;i++)\n\t\t\tfor(int j=n;j>=w[i];j--)\n\t\t\t\tdp[j]=min(dp[j],dp[j-w[i]]*(1-v[i]));\n\t\tprintf(\"%.1f%%\\n\",100*(1-dp[n]));\n\t}\n \treturn 0;\n}\n\n","avg_line_length":20.1176470588,"max_line_length":61,"alphanum_fraction":0.6354775828,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6776,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/**\n * @file lda_scvb.cpp\n * @author Chase Geigle\n *\/\n\n#include \"meta\/topics\/lda_scvb.h\"\n#include \"meta\/index\/postings_data.h\"\n#include \"meta\/util\/progress.h\"\n#include <random>\n\nnamespace meta\n{\nnamespace topics\n{\n\nlda_scvb::lda_scvb(const learn::dataset& docs, std::size_t num_topics,\n                   double alpha, double beta, uint64_t minibatch_size)\n    : lda_model{docs, num_topics},\n      docs_view_{docs_},\n      alpha_{alpha},\n      beta_{beta},\n      minibatch_size_{\n          std::min(minibatch_size, static_cast<uint64_t>(docs_.size()))}\n{\n    \/\/ nothing\n}\n\nvoid lda_scvb::run(uint64_t num_iters, double)\n{\n    initialize();\n    for (uint64_t iter = 0; iter < num_iters; ++iter)\n    {\n        docs_view_.shuffle();\n        perform_iteration(iter + 1);\n    }\n}\n\nvoid lda_scvb::initialize()\n{\n    \/\/ TODO: Don't actually iterate through whole dataset here\n    doc_topic_count_.resize(docs_.size());\n    topic_term_count_.resize(num_topics_);\n    for (auto& v : topic_term_count_)\n        v.resize(docs_.total_features());\n    topic_count_.resize(num_topics_);\n    doc_sizes_.resize(docs_.size());\n\n    std::mt19937 rng{std::random_device{}()};\n    printing::progress progress{\" > Initialization: \", docs_.size()};\n    for (const auto& doc : docs_)\n    {\n        progress(doc.id);\n\n        doc_sizes_[doc.id] = doc_size(doc);\n        doc_topic_count_[doc.id].resize(num_topics_);\n\n        for (const auto& freq : doc.weights)\n        {\n            double sum = 0;\n            std::vector<double> gamma(num_topics_);\n            for (topic_id k{0}; k < num_topics_; ++k)\n            {\n                auto random = rng();\n                gamma[k] = random;\n                sum += random;\n            }\n            for (topic_id k{0}; k < num_topics_; ++k)\n            {\n                gamma[k] = gamma[k] * freq.second \/ sum;\n                topic_term_count_[k][freq.first] += gamma[k];\n                doc_topic_count_[doc.id][k] += gamma[k];\n                topic_count_[k] += gamma[k];\n            }\n        }\n    }\n}\n\nvoid lda_scvb::perform_iteration(uint64_t iter)\n{\n    printing::progress progress{\"Minibatch \" + std::to_string(iter) + \": \",\n                                minibatch_size_};\n\n    std::vector<std::unordered_map<term_id, double>> batch_topic_term_count_(\n        num_topics_);\n    std::vector<double> batch_topic_count_(num_topics_, 0.0);\n    std::vector<double> gamma(num_topics_);\n\n    uint64_t j = 0;\n    for (const auto& doc : docs_view_)\n    {\n        if (j++ >= minibatch_size_)\n            break;\n\n        progress(j);\n\n        \/\/ burn-in phase\n        double t = 0;\n        for (const auto& freq : doc.weights)\n        {\n            double sum = 0;\n            for (topic_id k{0}; k < num_topics_; ++k)\n            {\n                gamma[k] = (topic_term_count_[k][freq.first] + beta_)\n                           \/ (topic_count_[k] + docs_.total_features() * beta_)\n                           * (doc_topic_count_[doc.id][k] + alpha_);\n                sum += gamma[k];\n            }\n            for (topic_id k{0}; k < num_topics_; ++k)\n            {\n                gamma[k] \/= sum;\n                auto lr = 1.0 \/ std::pow(10 + t, 0.9);\n                auto weight = std::pow(1 - lr, freq.second);\n                doc_topic_count_[doc.id][k]\n                    = weight * doc_topic_count_[doc.id][k]\n                      + (1 - weight) * doc_sizes_.at(doc.id) * gamma[k];\n            }\n            t += freq.second;\n        }\n\n        \/\/ normal phase\n        for (const auto& freq : doc.weights)\n        {\n            double sum = 0;\n            for (topic_id k{0}; k < num_topics_; ++k)\n            {\n                gamma[k] = (topic_term_count_[k][freq.first] + beta_)\n                           \/ (topic_count_[k] + docs_.total_features() * beta_)\n                           * (doc_topic_count_[doc.id][k] + alpha_);\n                sum += gamma[k];\n            }\n            for (topic_id k{0}; k < num_topics_; ++k)\n            {\n                \/\/ renormalize gamma\n                gamma[k] \/= sum;\n\n                \/\/ compute the learning schedule\n                auto lr = 1.0 \/ std::pow(10 + t, 0.9);\n                auto weight = std::pow(1 - lr, freq.second);\n\n                doc_topic_count_[doc.id][k]\n                    = weight * doc_topic_count_[doc.id][k]\n                      + (1 - weight) * doc_sizes_.at(doc.id) * gamma[k];\n\n                batch_topic_term_count_[k][freq.first]\n                    += docs_.size() * gamma[k];\n\n                batch_topic_count_[k] += docs_.size() * gamma[k];\n            }\n            t += freq.second;\n        }\n    }\n    progress.end();\n\n    \/\/ compute the learning schedule\n    auto lr = 10.0 \/ std::pow(1000 + iter * minibatch_size_, 0.9);\n\n    \/\/ TODO: better weight decay here? We can represent the vectors as the\n    \/\/ product of a scalar and a vector to efficiently scale by (1 - lr)\n    \/\/ when the batch count is 0, and we can cancel the factor out in the\n    \/\/ addition when it is nonzero. Not sure if this will help, but I think\n    \/\/ it may...\n    for (topic_id k{0}; k < num_topics_; ++k)\n    {\n        for (term_id i{0}; i < docs_.total_features(); ++i)\n        {\n            topic_term_count_[k][i]\n                = (1 - lr) * topic_term_count_[k][i]\n                  + lr * (batch_topic_term_count_[k][i] \/ minibatch_size_);\n        }\n        topic_count_[k] = (1 - lr) * topic_count_[k]\n                          + lr * (batch_topic_count_[k] \/ minibatch_size_);\n    }\n}\n\ndouble lda_scvb::compute_term_topic_probability(term_id term,\n                                                topic_id topic) const\n{\n    return (topic_term_count_.at(topic).at(term) + beta_)\n           \/ (topic_count_.at(topic) + docs_.total_features() * beta_);\n}\n\ndouble lda_scvb::compute_doc_topic_probability(learn::instance_id doc,\n                                               topic_id topic) const\n{\n    return (doc_topic_count_.at(doc).at(topic) + alpha_)\n           \/ (doc_sizes_.at(doc) + num_topics_ * alpha_);\n}\n\nstats::multinomial<topic_id> lda_scvb::topic_distribution(doc_id doc) const\n{\n    \/\/ TODO: Replace the count vectors with a multinomial rather than creating\n    \/\/ it here\n    stats::multinomial<topic_id> result;\n    for (topic_id tid{0}; tid < num_topics_; ++tid)\n    {\n        result.increment(tid, doc_topic_count_.at(doc).at(tid) + alpha_);\n    }\n\n    return result;\n}\n\nstats::multinomial<term_id> lda_scvb::term_distribution(topic_id k) const\n{\n    \/\/ TODO: Replace the count vectors with a multinomial rather than creating\n    \/\/ it here\n    stats::multinomial<term_id> result;\n    for (term_id w{0}; w < docs_.total_features(); ++w)\n    {\n        result.increment(w, topic_term_count_.at(k).at(w) + beta_);\n    }\n\n    return result;\n}\n}\n}\n","avg_line_length":31.3703703704,"max_line_length":79,"alphanum_fraction":0.5379279811,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3420,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"hashTable.h\"\n\n\nHash::Hash() {\n    int i;\n    for (i = 0; i < hashGroups; i++) {\n        hashTable[i] = new item;\n        hashTable[i]->key = \"\";\n        hashTable[i]->value = 0;\n        hashTable[i]->next = NULL;\n    }\n}\n\nvoid Hash::addItem(string key, int value) {\n    int index = hashFunction(key);\n    \/\/if empty\n    if (hashTable[index]->key.compare(\"\") == 0) {\n        hashTable[index]->key = key;\n        hashTable[index]->value = value;\n        cout << \"NEW KEY: \" << key << \" VALUE: \" << value << \" added\" << endl;\n    \n    } else {\n        item* ptr = hashTable[index];\n        item* n = new item;\n        n->key = key;\n        n->value = value;\n        n->next = NULL;\n\n        \/\/if first\n        if (ptr->key.compare(key) == 0) {\n            cout << \"WARNING: key \" << key << \" already exists, updating value to \" << value << endl;\n            ptr->value = n->value;\n\n        \/\/look through the rest of the list\n        } else {\n            bool found = false;\n\n            while (ptr->next != NULL) {\n                cout << \"Key being checked: \"  << ptr->key << endl;\n                if (ptr->key.compare(key) == 0) {\n                    ptr->value = value;\n                    found = true;\n                    break;\n                } else {\n                    ptr = ptr->next;\n                }\n            }\n\n            if (!found) {\n                \n                ptr->next = n;\n                cout << \"NEW KEY: \" << key << \" VALUE: \" << value << \"added\" << endl;\n            }\n        }\n    }\n}\n\n\nint Hash::hashFunction(string key) {\n    int hash = 0;\n    int i;\n    int length = key.length();\n    for (i = 0; i < length; i++) {\n        hash = hash + (int)key[i];\n    }\n    return hash % hashGroups;\n}\n\nint Hash::numberItemsInIndex(int index) {\n    int count = 0;\n    if (hashTable[index]->key.compare(\"\") == 0) {\n        return count;\n    } else {\n        count++;\n        item* ptr = hashTable[index];\n        while (ptr->next != NULL) {\n            count++;\n            ptr = ptr->next;\n        }\n    }\n    return count;\n}\n\nvoid Hash::printHashTable() {\n    int numberItems;\n    int i;\n    for (i = 0; i < hashGroups; i++) {\n        numberItems = numberItemsInIndex(i);\n        cout << \"------------\" << endl;\n        cout << \"INDEX: \" << i << endl;\n        cout << \"#ITEMS = \" << numberItems << endl;\n        if (numberItems > 0) {\n            printItemsInIndex(i);\n        }\n    }\n}\n\nvoid Hash::printItemsInIndex(int index) {\n    cout << \"---ITEMS---\" << endl;\n    item*ptr = hashTable[index];\n    while (ptr != NULL) {\n        cout << \"KEY: \" << ptr->key << \" -  VALUE: \" << ptr->value << endl;\n        ptr = ptr->next;\n    }\n}\n\n\/\/returns the value associated with the key\nint Hash::find(string key) {\n    int index = hashFunction(key);\n    bool found = false;\n\n    item* ptr = hashTable[index];\n    while (ptr != NULL) {\n        if (ptr->key.compare(key) == 0) {\n            found = true;\n            break;\n        } else {\n            ptr = ptr->next;\n        }\n    }\n    if (!found) {\n        cout << \"No value associated to key: \" << key << \" found\" << endl;\n        return -1;\n    } else {\n        return ptr->value;\n    }\n}\n\n\n\nint main() {\n    Hash h;\n    h.addItem(\"Alex\", 0);\n    h.addItem(\"Alex\", 1);\n    h.addItem(\"Jones\", 101);\n    h.addItem(\"Stan\", 500);\n    h.printHashTable();\n    cout << h.find(\"Alex\") << endl;\n    cout << h.find(\"James\") << endl;\n    return 0;\n}","avg_line_length":24.2553191489,"max_line_length":101,"alphanum_fraction":0.4502923977,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4329,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":null,"content":"\/\/=================================================================================================\n\/*!\n\/\/  \\file src\/mathtest\/dmatdmatmult\/HDbMDb.cpp\n\/\/  \\brief Source file for the HDbMDb dense matrix\/dense matrix multiplication math test\n\/\/\n\/\/  Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved\n\/\/\n\/\/  This file is part of the Blaze library. You can redistribute it and\/or modify it under\n\/\/  the terms of the New (Revised) BSD License. Redistribution and use in source and binary\n\/\/  forms, with or without modification, are permitted provided that the following conditions\n\/\/  are met:\n\/\/\n\/\/  1. Redistributions of source code must retain the above copyright notice, this list of\n\/\/     conditions and the following disclaimer.\n\/\/  2. Redistributions in binary form must reproduce the above copyright notice, this list\n\/\/     of conditions and the following disclaimer in the documentation and\/or other materials\n\/\/     provided with the distribution.\n\/\/  3. Neither the names of the Blaze development group nor the names of its contributors\n\/\/     may be used to endorse or promote products derived from this software without specific\n\/\/     prior written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n\/\/  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\/\/  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\n\/\/  SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n\/\/  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n\/\/  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/  DAMAGE.\n*\/\n\/\/=================================================================================================\n\n\n\/\/*************************************************************************************************\n\/\/ Includes\n\/\/*************************************************************************************************\n\n#include <cstdlib>\n#include <iostream>\n#include <blaze\/math\/DynamicMatrix.h>\n#include <blaze\/math\/HermitianMatrix.h>\n#include <blazetest\/mathtest\/Creator.h>\n#include <blazetest\/mathtest\/dmatdmatmult\/OperationTest.h>\n#include <blazetest\/system\/MathTest.h>\n\n\n\/\/=================================================================================================\n\/\/\n\/\/  MAIN FUNCTION\n\/\/\n\/\/=================================================================================================\n\n\/\/*************************************************************************************************\nint main()\n{\n   std::cout << \"   Running 'HDbMDb'...\" << std::endl;\n\n   using blazetest::mathtest::NumericB;\n\n   try\n   {\n      \/\/ Matrix type definitions\n      using HDb = blaze::HermitianMatrix< blaze::DynamicMatrix<NumericB> >;\n      using MDb = blaze::DynamicMatrix<NumericB>;\n\n      \/\/ Creator type definitions\n      using CHDb = blazetest::Creator<HDb>;\n      using CMDb = blazetest::Creator<MDb>;\n\n      \/\/ Running tests with small matrices\n      for( size_t i=0UL; i<=6UL; ++i ) {\n         for( size_t j=0UL; j<=6UL; ++j ) {\n            RUN_DMATDMATMULT_OPERATION_TEST( CHDb( i ), CMDb( i, j ) );\n         }\n      }\n\n      \/\/ Running tests with large matrices\n      RUN_DMATDMATMULT_OPERATION_TEST( CHDb( 15UL ), CMDb( 15UL, 37UL ) );\n      RUN_DMATDMATMULT_OPERATION_TEST( CHDb( 37UL ), CMDb( 37UL, 37UL ) );\n      RUN_DMATDMATMULT_OPERATION_TEST( CHDb( 63UL ), CMDb( 63UL, 37UL ) );\n      RUN_DMATDMATMULT_OPERATION_TEST( CHDb( 16UL ), CMDb( 16UL, 32UL ) );\n      RUN_DMATDMATMULT_OPERATION_TEST( CHDb( 32UL ), CMDb( 32UL, 32UL ) );\n      RUN_DMATDMATMULT_OPERATION_TEST( CHDb( 64UL ), CMDb( 64UL, 32UL ) );\n   }\n   catch( std::exception& ex ) {\n      std::cerr << \"\\n\\n ERROR DETECTED during dense matrix\/dense matrix multiplication:\\n\"\n                << ex.what() << \"\\n\";\n      return EXIT_FAILURE;\n   }\n\n   return EXIT_SUCCESS;\n}\n\/\/*************************************************************************************************\n","avg_line_length":45.09375,"max_line_length":99,"alphanum_fraction":0.5733425733,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":403,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":6.0,"content":"#include <iostream>\n#include \"Grammar.h\"\n#include \"Graph.h\"\n#include \"Matrix.h\"\n#include \"m4ri_matrix.h\"\n\nint main(int argc, char *argv[]) {\n    Grammar grammar = Grammar(argv[1]);\n    Graph graph = Graph(argv[2]);\n    auto times = grammar.intersection_with_graph<M4riMatrix>(graph);\n    std::cout << times.first << ' ' << times.second << std::endl;\n    grammar.print_results(argv[3]);\n\n    return 0;\n}\n","avg_line_length":25.1875,"max_line_length":68,"alphanum_fraction":0.6575682382,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5175,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>                    \/\/ std::cout\n#include <fstream>                     \/\/ std::ifstream, std::ofstream\n#include <filesystem>                  \/\/ std::filesystem\n#include <string>                      \/\/ std::string\n#include <sstream>                     \/\/ std::stringstream\n#include <tuple>                       \/\/ std::tuple\n#include <vector>                      \/\/ std::vector\n#include <utility>                     \/\/ std::pair\n#include <iomanip>                     \/\/ std::setprecision\n\/\/ For External Library\n#include <torch\/torch.h>               \/\/ torch\n#include <opencv2\/opencv.hpp>          \/\/ cv::Mat\n#include <boost\/program_options.hpp>   \/\/ boost::program_options\n\/\/ For Original Header\n#include \"networks.hpp\"                \/\/ YOLOv2\n#include \"detector.hpp\"                \/\/ YOLODetector\n#include \"transforms.hpp\"              \/\/ transforms_Compose\n#include \"datasets.hpp\"                \/\/ datasets::ImageFolderPairWithPaths\n#include \"dataloader.hpp\"              \/\/ DataLoader::ImageFolderPairWithPaths\n#include \"visualizer.hpp\"              \/\/ visualizer\n\n\/\/ Define Namespace\nnamespace fs = std::filesystem;\nnamespace po = boost::program_options;\n\n\n\/\/ --------------------\n\/\/ Detection Function\n\/\/ --------------------\nvoid detect(po::variables_map &vm, torch::Device &device, YOLOv2 &model, std::vector<transforms_Compose> &transformI, std::vector<transforms_Compose> &transformD, const std::vector<std::string> class_names, const std::vector<std::tuple<float, float>> anchors){\n\n    constexpr std::pair<float, float> output_range = {0.0, 1.0};  \/\/ range of the value in output images\n\n    \/\/ (0) Initialization and Declaration\n    size_t BB_n;\n    float prob;\n    std::string path, result_dir, fname;\n    std::string dataroot;\n    std::string class_name;\n    std::stringstream ss;\n    std::ofstream ofs;\n    std::tuple<torch::Tensor, torch::Tensor, std::vector<std::string>, std::vector<std::string>> data;\n    torch::Tensor imageI, imageD, output;\n    torch::Tensor ids, coords, probs;\n    std::tuple<torch::Tensor, torch::Tensor, torch::Tensor> detect_result;\n    cv::Mat imageO;\n    datasets::ImageFolderPairWithPaths dataset;\n    DataLoader::ImageFolderPairWithPaths dataloader;\n\n    \/\/ (1) Get Detection Dataset\n    dataroot = \"datasets\/\" + vm[\"dataset\"].as<std::string>() + '\/' + vm[\"detect_dir\"].as<std::string>();\n    dataset = datasets::ImageFolderPairWithPaths(dataroot, dataroot, transformI, transformD);\n    dataloader = DataLoader::ImageFolderPairWithPaths(dataset, \/*batch_size_=*\/1, \/*shuffle_=*\/false, \/*num_workers_=*\/0);\n    std::cout << \"total detect images : \" << dataset.size() << std::endl << std::endl;\n\n    \/\/ (2) Get Model\n    path = \"checkpoints\/\" + vm[\"dataset\"].as<std::string>() + \"\/models\/epoch_\" + vm[\"detect_load_epoch\"].as<std::string>() + \".pth\";\n    torch::load(model, path, device);\n\n    \/\/ (3) Set Detector\n    auto detector = YOLODetector(anchors, (long int)vm[\"class_num\"].as<size_t>(), vm[\"prob_thresh\"].as<float>(), vm[\"nms_thresh\"].as<float>());\n    std::vector<std::tuple<unsigned char, unsigned char, unsigned char>> label_palette = detector.get_label_palette();\n\n    \/\/ (4) Tensor Forward\n    torch::NoGradGuard no_grad;\n    model->eval();\n    result_dir = vm[\"detect_result_dir\"].as<std::string>();  fs::create_directories(result_dir);\n    ofs.open(result_dir + \"\/detect.txt\", std::ios::out);\n    while (dataloader(data)){\n        \n        \/\/ (4.1) Get data\n        imageI = std::get<0>(data).to(device);  \/\/ {1,C,H,W} (image for input)\n        imageD = std::get<1>(data);  \/\/ {1,3,H_D,W_D} (image for detection)\n\n        \/\/ (4.2) Inference and Detection\n        output = model->forward(imageI);  \/\/ {1,C,H,W} ===> {1,G,G,FF}\n        detect_result = detector(output[0]);  \/\/ output[0]{G,G,FF} ===> detect_result{ (ids{BB_n}, coords{BB_n,4}, probs{BB_n}) }\n        ids = std::get<0>(detect_result);  \/\/ ids{BB_n}\n        coords = std::get<1>(detect_result);  \/\/ coords{BB_n,4}\n        probs = std::get<2>(detect_result);  \/\/ probs{BB_n}\n        imageO = visualizer::draw_detections_des(imageD[0].detach(), {ids, coords}, probs, class_names, label_palette, \/*range=*\/output_range);\n\n        \/\/ (4.3) Save image\n        fname = result_dir + '\/' + std::get<2>(data).at(0);  \/\/ {1,C,H,W} ===> {1,G,G,FF}\n        cv::imwrite(fname, imageO);\n\n        \/\/ (4.4) Write detection result\n        BB_n = ids.size(0);\n        std::cout << '<' << std::get<2>(data).at(0) << \"> \" << BB_n << \" { \" << std::flush;\n        ofs << '<' << std::get<2>(data).at(0) << \"> \" << BB_n << \" { \" << std::flush;\n        for (size_t i = 0; i < BB_n; i++){\n            class_name = class_names.at(ids[i].item<long int>());\n            prob = probs[i].item<float>() * 100.0;\n            ss.str(\"\"); ss.clear(std::stringstream::goodbit);\n            ss << std::fixed << std::setprecision(1) << prob;\n            std::cout << class_name << \":\" << ss.str() << \"% \" << std::flush;\n            ofs << class_name << \":\" << ss.str() << \"% \" << std::flush;\n        }\n        std::cout << \"}\" << std::endl;\n        ofs << \"}\" << std::endl;\n\n    }\n\n    \/\/ Post Processing\n    ofs.close();\n\n    \/\/ End Processing\n    return;\n\n}\n","avg_line_length":46.6216216216,"max_line_length":260,"alphanum_fraction":0.5800966184,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1452,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"Game.h\"\n\n#include <cstdlib>\n\n#include <SDL.h>\n#include <SDL_image.h>\n#include <sigc++\/sigc++.h>\n\n#include \"Sdl.h\"\n#include \"SdlError.h\"\n#include \"Logger.h\"\n#include \"Image.h\"\n#include \"MainWindow.h\"\n#include \"Intro.h\"\n\nnamespace RescueHim {\n    using namespace Geom;\n    using namespace Sdl;\n\n    MainWindow& Game::getMainWindow() {\n        return *mainWindow.get();\n    }\n\n    void Game::initialize() {\n        try {\n            SDL::instance().initialize(SDL_INIT_VIDEO);\n        } catch (SdlError const& error) {\n            AppLog<Severity::Error>::log(\"Error while initializing SDL: \", error.what());\n            std::exit(1);\n        }\n\n        try {\n            SDL_image::instance().initialize(IMG_INIT_PNG);\n        } catch (SdlError const& error) {\n            AppLog<Severity::Error>::log(\"Error while initializing SDL_image: \", error.what());\n            std::exit(1);\n        }\n\n        mainWindow = std::static_pointer_cast<MainWindow>(SDL::instance().createWindow<MainWindow>());\n\n        currentState = std::make_unique<Intro>(*this);\n\n        updateConnection = SDL::instance().updateSignal().connect(sigc::mem_fun(*this, &Game::update));\n        renderConnection = SDL::instance().renderSignal().connect(sigc::mem_fun(*this, &Game::render));\n\n        SDL::instance().run();\n    }\n\n    void Game::update() {\n        this->currentState->update();\n    }\n\n    void Game::render() {\n        this->currentState->render();\n    }\n}\n","avg_line_length":25.4736842105,"max_line_length":103,"alphanum_fraction":0.5991735537,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1408,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["ECL-2.0","Apache-2.0"],"max_stars_count":337.0,"content":"\/**\n* packetcapture API generated from packetcapture.yang\n*\n* NOTE: This file is auto generated by polycube-codegen\n* https:\/\/github.com\/polycube-network\/polycube-codegen\n*\/\n\n\n\/* Do not edit this file manually *\/\n\n#include \"JsonObjectBase.h\"\n\nnamespace polycube {\nnamespace service {\nnamespace model {\n\nJsonObjectBase::JsonObjectBase(const nlohmann::json &base) : base_(base) {}\n\nbool JsonObjectBase::iequals(const std::string &a, const std::string &b) {\n  if(a.size() != b.size())\n    return false;\n  for (unsigned int i = 0; i < a.size(); i++){\n    if(tolower(a[i]) != tolower(b[i]))\n      return false;\n  }\n  return true;\n}\n\nstd::string JsonObjectBase::toJson(const std::string& value) {\n  return value;\n}\n\nstd::string JsonObjectBase::toJson(const std::time_t& value) {\n  char buf[sizeof \"2011-10-08T07:07:09Z\"];\n  strftime(buf, sizeof buf, \"%FT%TZ\", gmtime(&value));\n  return buf;\n}\n\nint32_t JsonObjectBase::toJson(int32_t value) {\n  return value;\n}\n\nint64_t JsonObjectBase::toJson(int64_t value) {\n  return value;\n}\n\ndouble JsonObjectBase::toJson(double value) {\n  return value;\n}\n\nbool JsonObjectBase::toJson(bool value) {\n  return value;\n}\n\nnlohmann::json JsonObjectBase::toJson(const JsonObjectBase &content) {\n  return content.toJson();\n}\n\nconst nlohmann::json &JsonObjectBase::getBase() const {\n  return base_;\n}\n\nvoid JsonObjectBase::setBase(const nlohmann::json &base) {\n  base_ = base;\n}\n\n}\n}\n}\n","avg_line_length":20.1142857143,"max_line_length":75,"alphanum_fraction":0.7002840909,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":762,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Copyright (c) 2015 fjz13. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n#include \"MedusaCorePreCompiled.h\"\n\/\/SIREN_BODY_INCLUDE_BEGIN\n#include \"ServerUsageItem.h\"\n\/\/SIREN_BODY_INCLUDE_END\n\nMEDUSA_BEGIN;\n\nServerUsageItem::ServerUsageItem()\n{\n\/\/SIREN_BODY_CONSTRUCT_BEGIN\n\tmUsage = (ServerUsageType)0;\n\tmServerId = 0;\n\/\/SIREN_BODY_CONSTRUCT_END\n}\n\nServerUsageItem::~ServerUsageItem()\n{\n\/\/SIREN_BODY_DESTRUCT_BEGIN\n\/\/SIREN_BODY_DESTRUCT_END\n}\n\n\/\/SIREN_BODY_METADATA_BEGIN\nSIREN_METADATA(ServerUsageItem, 15);\nSIREN_PROPERTY_METADATA(0, ServerUsageItem, Usage, 5, (ServerUsageType)0);\nSIREN_PROPERTY_METADATA(1, ServerUsageItem, ServerId, 8, 0);\n\/\/SIREN_BODY_METADATA_END\n\nMEDUSA_END;","avg_line_length":24.5806451613,"max_line_length":74,"alphanum_fraction":0.8031496063,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":49094,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/===--- TypeCheckGeneric.cpp - Generics ----------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements support for generics.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"TypeChecker.h\"\n#include \"GenericTypeResolver.h\"\n#include \"swift\/AST\/GenericEnvironment.h\"\n#include \"swift\/AST\/GenericSignatureBuilder.h\"\n#include \"swift\/AST\/ProtocolConformance.h\"\n#include \"swift\/AST\/ParameterList.h\"\n#include \"swift\/AST\/Types.h\"\n#include \"swift\/Basic\/Defer.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n\nusing namespace swift;\n\n\/\/\/\n\/\/\/ GenericTypeResolver implementations\n\/\/\/\n\nType DependentGenericTypeResolver::mapTypeIntoContext(Type type) {\n  return type;\n}\n\nType DependentGenericTypeResolver::resolveDependentMemberType(\n                                     Type baseTy,\n                                     DeclContext *DC,\n                                     SourceRange baseRange,\n                                     ComponentIdentTypeRepr *ref) {\n  return DependentMemberType::get(baseTy, ref->getIdentifier());\n}\n\nbool DependentGenericTypeResolver::areSameType(Type type1, Type type2) {\n  if (!type1->hasTypeParameter() && !type2->hasTypeParameter())\n    return type1->isEqual(type2);\n\n  \/\/ Conservative answer: they could be the same.\n  return true;\n}\n\nvoid DependentGenericTypeResolver::recordParamType(ParamDecl *decl, Type type) {\n  \/\/ Do nothing\n}\n\nType GenericTypeToArchetypeResolver::mapTypeIntoContext(Type type) {\n  return GenericEnvironment::mapTypeIntoContext(GenericEnv, type);\n}\n\nType GenericTypeToArchetypeResolver::resolveDependentMemberType(\n                                  Type baseTy,\n                                  DeclContext *DC,\n                                  SourceRange baseRange,\n                                  ComponentIdentTypeRepr *ref) {\n  llvm_unreachable(\"Dependent type after archetype substitution\");\n}\n\nbool GenericTypeToArchetypeResolver::areSameType(Type type1, Type type2) {\n  return type1->isEqual(type2);\n}\n\nvoid GenericTypeToArchetypeResolver::recordParamType(ParamDecl *decl, Type type) {\n  decl->setType(type);\n\n  \/\/ When type checking a closure or subscript index, this is the only\n  \/\/ resolver that runs, so make sure we also set the interface type,\n  \/\/ if one was not already set.\n  \/\/\n  \/\/ When type checking functions, the CompleteGenericTypeResolver sets\n  \/\/ the interface type.\n  if (!decl->hasInterfaceType())\n    decl->setInterfaceType(GenericEnvironment::mapTypeOutOfContext(\n        GenericEnv, type));\n}\n\nType ProtocolRequirementTypeResolver::mapTypeIntoContext(Type type) {\n  return type;\n}\n\nType ProtocolRequirementTypeResolver::resolveDependentMemberType(\n    Type baseTy, DeclContext *DC, SourceRange baseRange,\n    ComponentIdentTypeRepr *ref) {\n  return DependentMemberType::get(baseTy, ref->getIdentifier());\n}\n\nbool ProtocolRequirementTypeResolver::areSameType(Type type1, Type type2) {\n  if (type1->isEqual(type2))\n    return true;\n\n  \/\/ If both refer to associated types with the same name, they'll implicitly\n  \/\/ be considered equivalent.\n  auto depMem1 = type1->getAs<DependentMemberType>();\n  if (!depMem1) return false;\n\n  auto depMem2 = type2->getAs<DependentMemberType>();\n  if (!depMem2) return false;\n\n  if (depMem1->getName() != depMem2->getName()) return false;\n\n  return areSameType(depMem1->getBase(), depMem2->getBase());\n}\n\nvoid ProtocolRequirementTypeResolver::recordParamType(ParamDecl *decl,\n                                                      Type type) {\n  llvm_unreachable(\n      \"recording a param type of a protocol requirement doesn't make sense\");\n}\n\nCompleteGenericTypeResolver::CompleteGenericTypeResolver(\n                                              TypeChecker &tc,\n                                              GenericSignature *genericSig)\n  : tc(tc), genericSig(genericSig),\n    builder(*tc.Context.getOrCreateGenericSignatureBuilder(\n                               genericSig->getCanonicalSignature()))\n{\n}\n\nType CompleteGenericTypeResolver::mapTypeIntoContext(Type type) {\n  return type;\n}\n\nType CompleteGenericTypeResolver::resolveDependentMemberType(\n                                    Type baseTy,\n                                    DeclContext *DC,\n                                    SourceRange baseRange,\n                                    ComponentIdentTypeRepr *ref) {\n  auto baseEquivClass =\n    builder.resolveEquivalenceClass(\n                                baseTy,\n                                ArchetypeResolutionKind::CompleteWellFormed);\n  assert(baseEquivClass && \"Unknown base type?\");\n\n  \/\/ Look for a nested type with the given name.\n  if (auto nestedType =\n          baseEquivClass->lookupNestedType(builder, ref->getIdentifier())) {\n    \/\/ Record the type we found.\n    ref->setValue(nestedType, nullptr);\n  } else {\n    \/\/ Resolve the base to a potential archetype.\n    \/\/ Perform typo correction.\n    LookupResult corrections;\n    tc.performTypoCorrection(DC, DeclRefKind::Ordinary,\n                             MetatypeType::get(baseTy),\n                             ref->getIdentifier(), ref->getIdLoc(),\n                             NameLookupFlags::ProtocolMembers,\n                             corrections, &builder);\n\n    \/\/ Filter out non-types.\n    corrections.filter([](const LookupResultEntry &result) {\n      return isa<TypeDecl>(result.getValueDecl());\n    });\n\n    \/\/ Check whether we have a single type result.\n    auto singleType = corrections.getSingleTypeResult();\n\n    \/\/ If we don't have a single result, complain and fail.\n    if (!singleType) {\n      Identifier name = ref->getIdentifier();\n      SourceLoc nameLoc = ref->getIdLoc();\n      tc.diagnose(nameLoc, diag::invalid_member_type, name, baseTy)\n        .highlight(baseRange);\n      for (const auto &suggestion : corrections)\n        tc.noteTypoCorrection(name, DeclNameLoc(nameLoc),\n                              suggestion.getValueDecl());\n\n      return ErrorType::get(tc.Context);\n    }\n\n    \/\/ We have a single type result. Suggest it.\n    tc.diagnose(ref->getIdLoc(), diag::invalid_member_type_suggest,\n                baseTy, ref->getIdentifier(),\n                singleType->getBaseName().getIdentifier())\n      .fixItReplace(ref->getIdLoc(),\n                    singleType->getBaseName().userFacingName());\n\n    \/\/ Correct to the single type result.\n    ref->overwriteIdentifier(singleType->getBaseName().getIdentifier());\n    ref->setValue(singleType, nullptr);\n  }\n\n  \/\/ If the nested type has been resolved to an associated type, use it.\n  if (auto assocType = dyn_cast<AssociatedTypeDecl>(ref->getBoundDecl())) {\n    return DependentMemberType::get(baseTy, assocType);\n  }\n\n  \/\/ Otherwise, the nested type comes from a concrete type. Substitute the\n  \/\/ base type into it.\n  auto concrete = ref->getBoundDecl();\n  tc.validateDeclForNameLookup(concrete);\n  if (!concrete->hasInterfaceType())\n    return ErrorType::get(tc.Context);\n  if (baseTy->isTypeParameter()) {\n    if (auto proto =\n          concrete->getDeclContext()\n            ->getAsProtocolOrProtocolExtensionContext()) {\n      tc.validateDecl(proto);\n      auto subMap = SubstitutionMap::getProtocolSubstitutions(\n                      proto, baseTy, ProtocolConformanceRef(proto));\n      return concrete->getDeclaredInterfaceType().subst(subMap);\n    }\n\n    if (auto superclass = baseEquivClass->superclass) {\n      return superclass->getTypeOfMember(\n                                       DC->getParentModule(), concrete,\n                                       concrete->getDeclaredInterfaceType());\n    }\n\n    llvm_unreachable(\"shouldn't have a concrete decl here\");\n  }\n\n  return tc.substMemberTypeWithBase(DC->getParentModule(), concrete, baseTy);\n}\n\nbool CompleteGenericTypeResolver::areSameType(Type type1, Type type2) {\n  return genericSig->getCanonicalTypeInContext(type1)\n           == genericSig->getCanonicalTypeInContext(type2);\n}\n\nvoid\nCompleteGenericTypeResolver::recordParamType(ParamDecl *decl, Type type) {\n  decl->setInterfaceType(type);\n}\n\n\/\/\/\n\/\/\/ Common code for generic functions, generic types\n\/\/\/\n\n\/\/\/ Check the generic parameters in the given generic parameter list (and its\n\/\/\/ parent generic parameter lists) according to the given resolver.\nvoid TypeChecker::checkGenericParamList(GenericSignatureBuilder *builder,\n                                        GenericParamList *genericParams,\n                                        GenericSignature *parentSig,\n                                        GenericTypeResolver *resolver) {\n  \/\/ If there is a parent context, add the generic parameters and requirements\n  \/\/ from that context.\n  if (builder)\n    builder->addGenericSignature(parentSig);\n\n  \/\/ If there aren't any generic parameters at this level, we're done.\n  if (!genericParams)\n    return;\n\n  assert(genericParams->size() > 0 &&\n         \"Parsed an empty generic parameter list?\");\n\n  \/\/ Determine where and how to perform name lookup for the generic\n  \/\/ parameter lists and where clause.\n  TypeResolutionOptions options;\n  DeclContext *lookupDC = genericParams->begin()[0]->getDeclContext();\n  if (!lookupDC->isModuleScopeContext()) {\n    assert((isa<GenericTypeDecl>(lookupDC) ||\n            isa<ExtensionDecl>(lookupDC) ||\n            isa<AbstractFunctionDecl>(lookupDC) ||\n            isa<SubscriptDecl>(lookupDC)) &&\n           \"not a proper generic parameter context?\");\n    options = TR_GenericSignature;\n  }    \n\n  \/\/ First, add the generic parameters to the generic signature builder.\n  \/\/ Do this before checking the inheritance clause, since it may\n  \/\/ itself be dependent on one of these parameters.\n  if (builder) {\n    for (auto param : *genericParams)\n      builder->addGenericParameter(param);\n  }\n\n  \/\/ Now, check the inheritance clauses of each parameter.\n  for (auto param : *genericParams) {\n    checkInheritanceClause(param, resolver);\n\n    if (builder)\n      builder->addGenericParameterRequirements(param);\n  }\n\n  \/\/ Add the requirements clause to the builder, validating the types in\n  \/\/ the requirements clause along the way.\n  validateRequirements(genericParams->getWhereLoc(),\n                       genericParams->getRequirements(), lookupDC,\n                       options, resolver, builder);\n}\n\nbool TypeChecker::validateRequirement(SourceLoc whereLoc, RequirementRepr &req,\n                                      DeclContext *lookupDC,\n                                      TypeResolutionOptions options,\n                                      GenericTypeResolver *resolver) {\n  if (req.isInvalid())\n    return true;\n\n  switch (req.getKind()) {\n  case RequirementReprKind::TypeConstraint: {\n    \/\/ Validate the types.\n    if (validateType(req.getSubjectLoc(), lookupDC, options, resolver)) {\n      req.setInvalid();\n    }\n\n    if (validateType(req.getConstraintLoc(), lookupDC, options, resolver)) {\n      req.setInvalid();\n    }\n\n    return req.isInvalid();\n  }\n\n  case RequirementReprKind::LayoutConstraint: {\n    \/\/ Validate the types.\n    if (validateType(req.getSubjectLoc(), lookupDC, options, resolver)) {\n      req.setInvalid();\n    }\n\n    if (req.getLayoutConstraintLoc().isNull()) {\n      req.setInvalid();\n    }\n    return req.isInvalid();\n  }\n\n  case RequirementReprKind::SameType: {\n    if (validateType(req.getFirstTypeLoc(), lookupDC, options, resolver)) {\n      req.setInvalid();\n    }\n\n    if (validateType(req.getSecondTypeLoc(), lookupDC, options, resolver)) {\n      req.setInvalid();\n    }\n\n    return req.isInvalid();\n  }\n  }\n\n  llvm_unreachable(\"Unhandled RequirementKind in switch.\");\n}\n\nvoid TypeChecker::validateRequirements(\n                                 SourceLoc whereLoc,\n                                 MutableArrayRef<RequirementRepr> requirements,\n                                 DeclContext *dc,\n                                 TypeResolutionOptions options,\n                                 GenericTypeResolver *resolver,\n                                 GenericSignatureBuilder *builder) {\n  for (auto &req : requirements) {\n    if (validateRequirement(whereLoc, req, dc, options, resolver))\n      continue;\n\n    if (builder &&\n        isErrorResult(builder->addRequirement(&req, dc->getParentModule())))\n      req.setInvalid();\n  }\n}\n\nvoid\nTypeChecker::prepareGenericParamList(GenericParamList *gp,\n                                     DeclContext *dc) {\n  AccessLevel access;\n  if (auto *fd = dyn_cast<FuncDecl>(dc))\n    access = fd->getFormalAccess();\n  else if (auto *nominal = dyn_cast<NominalTypeDecl>(dc))\n    access = nominal->getFormalAccess();\n  else\n    access = AccessLevel::Internal;\n  access = std::max(access, AccessLevel::Internal);\n\n  unsigned depth = gp->getDepth();\n  for (auto paramDecl : *gp) {\n    paramDecl->setDepth(depth);\n    if (!paramDecl->hasAccess())\n      paramDecl->setAccess(access);\n  }\n}\n\n\/\/\/ Add the generic parameter types from the given list to the vector.\nstatic void addGenericParamTypes(GenericParamList *gpList,\n                                 SmallVectorImpl<GenericTypeParamType *> &params) {\n  if (!gpList) return;\n\n  for (auto gpDecl : *gpList) {\n    params.push_back(\n            gpDecl->getDeclaredInterfaceType()->castTo<GenericTypeParamType>());\n  }\n}\n\nstatic void revertDependentTypeLoc(TypeLoc &tl) {\n  \/\/ If there's no type representation, there's nothing to revert.\n  if (!tl.getTypeRepr())\n    return;\n\n  \/\/ Don't revert an error type; we've already complained.\n  if (tl.wasValidated() && tl.isError())\n    return;\n\n  \/\/ Make sure we validate the type again.\n  tl.setType(Type(), \/*validated=*\/false);\n}\n\n\/\/\/ Revert the dependent types within the given generic parameter list.\nvoid TypeChecker::revertGenericParamList(GenericParamList *genericParams) {\n  \/\/ Revert the inherited clause of the generic parameter list.\n  for (auto param : *genericParams) {\n    param->setCheckedInheritanceClause(false);\n    for (auto &inherited : param->getInherited())\n      revertDependentTypeLoc(inherited);\n  }\n\n  \/\/ Revert the requirements of the generic parameter list.\n  revertGenericRequirements(genericParams->getRequirements());\n}\n\nvoid TypeChecker::revertGenericRequirements(\n                                MutableArrayRef<RequirementRepr> requirements) {\n  for (auto &req : requirements) {\n    if (req.isInvalid())\n      continue;\n\n    switch (req.getKind()) {\n    case RequirementReprKind::TypeConstraint:\n      revertDependentTypeLoc(req.getConstraintLoc());\n      LLVM_FALLTHROUGH;\n\n    case RequirementReprKind::LayoutConstraint:\n      revertDependentTypeLoc(req.getSubjectLoc());\n      break;\n\n    case RequirementReprKind::SameType:\n      revertDependentTypeLoc(req.getFirstTypeLoc());\n      revertDependentTypeLoc(req.getSecondTypeLoc());\n      break;\n    }\n  }\n}\n\n\/\/\/\n\/\/\/ Generic functions\n\/\/\/\n\n\/\/\/ Check the signature of a generic function.\nstatic bool checkGenericFuncSignature(TypeChecker &tc,\n                                      GenericSignatureBuilder *builder,\n                                      AbstractFunctionDecl *func,\n                                      GenericTypeResolver &resolver) {\n  bool badType = false;\n\n  \/\/ Check the generic parameter list.\n  auto genericParams = func->getGenericParams();\n\n  tc.checkGenericParamList(\n                         builder, genericParams,\n                         func->getDeclContext()->getGenericSignatureOfContext(),\n                         &resolver);\n\n  \/\/ Check the parameter patterns.\n  for (auto params : func->getParameterLists()) {\n    \/\/ Check the pattern.\n    if (tc.typeCheckParameterList(params, func, TypeResolutionOptions(),\n                                  resolver))\n      badType = true;\n\n    \/\/ Infer requirements from the pattern.\n    if (builder) {\n      builder->inferRequirements(*func->getParentModule(), params,\n                                 genericParams);\n    }\n  }\n\n  \/\/ If there is a declared result type, check that as well.\n  if (auto fn = dyn_cast<FuncDecl>(func)) {\n    if (!fn->getBodyResultTypeLoc().isNull()) {\n      \/\/ Check the result type of the function.\n      TypeResolutionOptions options = TR_AllowIUO;\n      if (fn->hasDynamicSelf())\n        options |= TR_DynamicSelfResult;\n\n      if (tc.validateType(fn->getBodyResultTypeLoc(), fn, options, &resolver)) {\n        badType = true;\n      }\n\n      \/\/ Infer requirements from it.\n      if (builder && genericParams &&\n          fn->getBodyResultTypeLoc().getTypeRepr()) {\n        auto source =\n          GenericSignatureBuilder::FloatingRequirementSource::forInferred(\n              fn->getBodyResultTypeLoc().getTypeRepr());\n        builder->inferRequirements(*func->getParentModule(),\n                                   fn->getBodyResultTypeLoc(),\n                                   source);\n      }\n    }\n\n    \/\/ If this is a materializeForSet, infer requirements from the\n    \/\/ storage type instead, since it's not part of the accessor's\n    \/\/ type signature.\n    if (fn->getAccessorKind() == AccessorKind::IsMaterializeForSet) {\n      if (builder) {\n        auto *storage = fn->getAccessorStorageDecl();\n        if (auto *subscriptDecl = dyn_cast<SubscriptDecl>(storage)) {\n          auto source =\n            GenericSignatureBuilder::FloatingRequirementSource::forInferred(\n                subscriptDecl->getElementTypeLoc().getTypeRepr());\n\n          TypeLoc type(nullptr, subscriptDecl->getElementInterfaceType());\n          assert(type.getType());\n          builder->inferRequirements(*func->getParentModule(),\n                                     type, source);\n        }\n      }\n    }\n  }\n\n  return badType;\n}\n\nvoid TypeChecker::revertGenericFuncSignature(AbstractFunctionDecl *func) {\n  \/\/ Revert the result type.\n  if (auto fn = dyn_cast<FuncDecl>(func))\n    if (!fn->getBodyResultTypeLoc().isNull())\n      revertDependentTypeLoc(fn->getBodyResultTypeLoc());\n\n  \/\/ Revert the body parameter types.\n  for (auto paramList : func->getParameterLists()) {\n    for (auto &param : *paramList) {\n      revertDependentTypeLoc(param->getTypeLoc());\n    }\n  }\n}\n\n\/\/\/ Determine whether the given type is \\c Self, an associated type of \\c Self,\n\/\/\/ or a concrete type.\nstatic bool isSelfDerivedOrConcrete(Type protoSelf, Type type) {\n  \/\/ Check for a concrete type.\n  if (!type->hasTypeParameter())\n    return true;\n\n  if (type->isTypeParameter() &&\n      type->getRootGenericParam()->isEqual(protoSelf))\n    return true;\n\n  return false;\n}\n\n\/\/ For a generic requirement in a protocol, make sure that the requirement\n\/\/ set didn't add any requirements to Self or its associated types.\nstatic bool checkProtocolSelfRequirements(GenericSignature *sig,\n                                          ValueDecl *decl,\n                                          TypeChecker &TC) {\n  \/\/ For a generic requirement in a protocol, make sure that the requirement\n  \/\/ set didn't add any requirements to Self or its associated types.\n  if (auto *proto = dyn_cast<ProtocolDecl>(decl->getDeclContext())) {\n    auto protoSelf = proto->getSelfInterfaceType();\n    for (auto req : sig->getRequirements()) {\n      \/\/ If one of the types in the requirement is dependent on a non-Self\n      \/\/ type parameter, this requirement is okay.\n      if (!isSelfDerivedOrConcrete(protoSelf, req.getFirstType()) ||\n          !isSelfDerivedOrConcrete(protoSelf, req.getSecondType()))\n        continue;\n\n      \/\/ The conformance of 'Self' to the protocol is okay.\n      if (req.getKind() == RequirementKind::Conformance &&\n          req.getSecondType()->getAs<ProtocolType>()->getDecl() == proto &&\n          req.getFirstType()->is<GenericTypeParamType>())\n        continue;\n\n      TC.diagnose(decl,\n                  TC.Context.LangOpts.EffectiveLanguageVersion[0] >= 4\n                    ? diag::requirement_restricts_self\n                    : diag::requirement_restricts_self_swift3,\n                  decl->getDescriptiveKind(), decl->getFullName(),\n                  req.getFirstType().getString(),\n                  static_cast<unsigned>(req.getKind()),\n                  req.getSecondType().getString());\n\n      if (TC.Context.LangOpts.EffectiveLanguageVersion[0] >= 4)\n        return true;\n    }\n  }\n\n  return false;\n}\n\n\/\/\/ All generic parameters of a generic function must be referenced in the\n\/\/\/ declaration's type, otherwise we have no way to infer them.\nstatic void checkReferencedGenericParams(GenericContext *dc,\n                                         GenericSignature *sig,\n                                         TypeChecker &TC) {\n  auto *genericParams = dc->getGenericParams();\n  if (!genericParams)\n    return;\n\n  auto *decl = cast<ValueDecl>(dc->getInnermostDeclarationDeclContext());\n\n  \/\/ A helper class to collect referenced generic type parameters\n  \/\/ and dependent member types.\n  class ReferencedGenericTypeWalker : public TypeWalker {\n    SmallPtrSet<CanType, 4> ReferencedGenericParams;\n\n  public:\n    ReferencedGenericTypeWalker() {}\n    Action walkToTypePre(Type ty) override {\n      \/\/ Find generic parameters or dependent member types.\n      \/\/ Once such a type is found, don't recurse into its children.\n      if (!ty->hasTypeParameter())\n        return Action::SkipChildren;\n      if (ty->isTypeParameter()) {\n        ReferencedGenericParams.insert(ty->getCanonicalType());\n        return Action::SkipChildren;\n      }\n      return Action::Continue;\n    }\n\n    SmallPtrSet<CanType, 4> &getReferencedGenericParams() {\n      return ReferencedGenericParams;\n    }\n  };\n\n  \/\/ Collect all generic params referenced in parameter types and\n  \/\/ return type.\n  ReferencedGenericTypeWalker paramsAndResultWalker;\n  auto *funcTy = decl->getInterfaceType()->castTo<GenericFunctionType>();\n  funcTy->getInput().walk(paramsAndResultWalker);\n  funcTy->getResult().walk(paramsAndResultWalker);\n\n  \/\/ Set of generic params referenced in parameter types,\n  \/\/ return type or requirements.\n  auto &referencedGenericParams =\n      paramsAndResultWalker.getReferencedGenericParams();\n\n  \/\/ Check if at least one of the generic params in the requirement refers\n  \/\/ to an already referenced generic parameter. If this is the case,\n  \/\/ then the other type is also considered as referenced, because\n  \/\/ it is used to put requirements on the first type.\n  auto reqTypesVisitor = [&referencedGenericParams](Requirement req) -> bool {\n    Type first;\n    Type second;\n\n    switch (req.getKind()) {\n    case RequirementKind::Superclass:\n    case RequirementKind::SameType:\n      second = req.getSecondType();\n      LLVM_FALLTHROUGH;\n\n    case RequirementKind::Conformance:\n    case RequirementKind::Layout:\n      first = req.getFirstType();\n      break;\n    }\n\n    \/\/ Collect generic parameter types referenced by types used in a requirement.\n    ReferencedGenericTypeWalker walker;\n    if (first && first->hasTypeParameter())\n      first.walk(walker);\n    if (second && second->hasTypeParameter())\n      second.walk(walker);\n    auto &genericParamsUsedByRequirementTypes =\n        walker.getReferencedGenericParams();\n\n    \/\/ If at least one of the collected generic types or a root generic\n    \/\/ parameter of dependent member types is known to be referenced by\n    \/\/ parameter types, return types or other types known to be \"referenced\",\n    \/\/ then all the types used in the requirement are considered to be\n    \/\/ referenced, because they are used to defined something that is known\n    \/\/ to be referenced.\n    bool foundNewReferencedGenericParam = false;\n    if (std::any_of(genericParamsUsedByRequirementTypes.begin(),\n                    genericParamsUsedByRequirementTypes.end(),\n                    [&referencedGenericParams](CanType t) {\n                      assert(t->isTypeParameter());\n                      return referencedGenericParams.find(\n                                 t->getRootGenericParam()\n                                     ->getCanonicalType()) !=\n                             referencedGenericParams.end();\n                    })) {\n      std::for_each(genericParamsUsedByRequirementTypes.begin(),\n                    genericParamsUsedByRequirementTypes.end(),\n                    [&referencedGenericParams,\n                     &foundNewReferencedGenericParam](CanType t) {\n                      \/\/ Add only generic type parameters, but ignore any\n                      \/\/ dependent member types, because requirement\n                      \/\/ on a dependent member type does not provide enough\n                      \/\/ information to infer the base generic type\n                      \/\/ parameter.\n                      if (!t->is<GenericTypeParamType>())\n                        return;\n                      if (referencedGenericParams.insert(t).second)\n                        foundNewReferencedGenericParam = true;\n                    });\n    }\n    return foundNewReferencedGenericParam;\n  };\n\n  ArrayRef<Requirement> requirements;\n\n  auto FindReferencedGenericParamsInRequirements = [&requirements, sig, &reqTypesVisitor] {\n    requirements = sig->getRequirements();\n    \/\/ Try to find new referenced generic parameter types in requirements until\n    \/\/ we reach a fix point. We need to iterate until a fix point, because we\n    \/\/ may have e.g. chains of same-type requirements like:\n    \/\/ not-yet-referenced-T1 == not-yet-referenced-T2.DepType2,\n    \/\/ not-yet-referenced-T2 == not-yet-referenced-T3.DepType3,\n    \/\/ not-yet-referenced-T3 == referenced-T4.DepType4.\n    \/\/ When we process the first of these requirements, we don't know yet that\n    \/\/ T2\n    \/\/ will be referenced, because T3 will be referenced,\n    \/\/ because T3 == T4.DepType4.\n    while (true) {\n      bool foundNewReferencedGenericParam = false;\n      for (auto req : requirements) {\n        if (reqTypesVisitor(req))\n          foundNewReferencedGenericParam = true;\n      }\n      if (!foundNewReferencedGenericParam)\n        break;\n    }\n  };\n\n  \/\/ Find the depth of the function's own generic parameters.\n  unsigned fnGenericParamsDepth = genericParams->getDepth();\n\n  \/\/ Check that every generic parameter type from the signature is\n  \/\/ among referencedGenericParams.\n  for (auto *genParam : sig->getGenericParams()) {\n    auto *paramDecl = genParam->getDecl();\n    if (paramDecl->getDepth() != fnGenericParamsDepth)\n      continue;\n    if (!referencedGenericParams.count(genParam->getCanonicalType())) {\n      \/\/ Lazily search for generic params that are indirectly used in the\n      \/\/ function signature. Do it only if there is a generic parameter\n      \/\/ that is not known to be referenced yet.\n      if (requirements.empty()) {\n        FindReferencedGenericParamsInRequirements();\n        \/\/ Nothing to do if this generic parameter is considered to be\n        \/\/ referenced after analyzing the requirements from the generic\n        \/\/ signature.\n        if (referencedGenericParams.count(genParam->getCanonicalType()))\n          continue;\n      }\n      \/\/ Produce an error that this generic parameter cannot be bound.\n      TC.diagnose(paramDecl->getLoc(), diag::unreferenced_generic_parameter,\n                  paramDecl->getNameStr());\n      decl->setInterfaceType(ErrorType::get(TC.Context));\n      decl->setInvalid();\n    }\n  }\n}\n\nGenericSignature *\nTypeChecker::validateGenericFuncSignature(AbstractFunctionDecl *func) {\n  bool invalid = false;\n\n  GenericSignature *sig;\n  if (auto gp = func->getGenericParams()) {\n    prepareGenericParamList(gp, func);\n\n    \/\/ Create the generic signature builder.\n    GenericSignatureBuilder builder(Context);\n\n    \/\/ Type check the function declaration, treating all generic type\n    \/\/ parameters as dependent, unresolved.\n    DependentGenericTypeResolver dependentResolver;\n    if (checkGenericFuncSignature(*this, &builder, func, dependentResolver))\n      invalid = true;\n\n    \/\/ The generic function signature is complete and well-formed. Determine\n    \/\/ the type of the generic function.\n    sig = std::move(builder).computeGenericSignature(func->getLoc());\n\n    \/\/ The generic signature builder now has all of the requirements, although\n    \/\/ there might still be errors that have not yet been diagnosed. Revert the\n    \/\/ generic function signature and type-check it again, completely.\n    revertGenericFuncSignature(func);\n    if (gp)\n      revertGenericParamList(gp);\n\n    \/\/ Debugging of the generic signature.\n    if (Context.LangOpts.DebugGenericSignatures) {\n      func->dumpRef(llvm::errs());\n      llvm::errs() << \"\\n\";\n      llvm::errs() << \"Generic signature: \";\n      sig->print(llvm::errs());\n      llvm::errs() << \"\\n\";\n      llvm::errs() << \"Canonical generic signature: \";\n      sig->getCanonicalSignature()->print(llvm::errs());\n      llvm::errs() << \"\\n\";\n    }\n  } else {\n    \/\/ Inherit the signature of our environment.\n    sig = func->getDeclContext()->getGenericSignatureOfContext();\n  }\n\n  CompleteGenericTypeResolver completeResolver(*this, sig);\n  if (checkGenericFuncSignature(*this, nullptr, func, completeResolver))\n    invalid = true;\n\n  if (!invalid)\n    invalid = checkProtocolSelfRequirements(sig, func, *this);\n\n  if (invalid) {\n    func->setInterfaceType(ErrorType::get(Context));\n    func->setInvalid();\n    \/\/ null doesn't mean error here: callers still expect the signature.\n    return sig;\n  }\n\n  configureInterfaceType(func, sig);\n  return sig;\n}\n\nvoid TypeChecker::configureInterfaceType(AbstractFunctionDecl *func,\n                                         GenericSignature *sig) {\n  Type funcTy;\n  Type initFuncTy = Type();\n\n  if (auto fn = dyn_cast<FuncDecl>(func)) {\n    funcTy = fn->getBodyResultTypeLoc().getType();\n    if (!funcTy)\n      funcTy = TupleType::getEmpty(Context);\n\n  } else if (auto ctor = dyn_cast<ConstructorDecl>(func)) {\n    auto *dc = ctor->getDeclContext();\n\n    funcTy = dc->getSelfInterfaceType();\n    if (!funcTy)\n      funcTy = ErrorType::get(Context);\n\n    \/\/ Adjust result type for failability.\n    if (ctor->getFailability() != OTK_None)\n      funcTy = OptionalType::get(ctor->getFailability(), funcTy);\n\n    initFuncTy = funcTy;\n  } else {\n    assert(isa<DestructorDecl>(func));\n    funcTy = TupleType::getEmpty(Context);\n  }\n\n  auto paramLists = func->getParameterLists();\n  SmallVector<ParameterList*, 4> storedParamLists;\n\n  \/\/ FIXME: Destructors don't have the '()' pattern in their signature, so\n  \/\/ paste it here.\n  if (isa<DestructorDecl>(func)) {\n    assert(paramLists.size() == 1 && \"Only the self paramlist\");\n    storedParamLists.push_back(paramLists[0]);\n    storedParamLists.push_back(ParameterList::createEmpty(Context));\n    paramLists = storedParamLists;\n  }\n\n  bool hasSelf = func->getDeclContext()->isTypeContext();\n  for (unsigned i = 0, e = paramLists.size(); i != e; ++i) {\n    SmallVector<AnyFunctionType::Param, 4> argTy;\n    SmallVector<AnyFunctionType::Param, 4> initArgTy;\n    \n    if (i == e-1 && hasSelf) {      \n      \/\/ Substitute in our own 'self' parameter.\n      \n      argTy.push_back(computeSelfParam(func));\n      if (initFuncTy) {\n        initArgTy.push_back(computeSelfParam(func, \/*isInitializingCtor=*\/true));\n      }\n    } else {\n      AnyFunctionType::decomposeInput(paramLists[e - i - 1]->getInterfaceType(Context), argTy);\n\n      if (initFuncTy)\n        initArgTy = argTy;\n    }\n\n    \/\/ 'throws' only applies to the innermost function.\n    AnyFunctionType::ExtInfo info;\n    if (i == 0) {\n      info = info.withThrows(func->hasThrows());\n      \/\/ Defer bodies must not escape.\n      if (auto fd = dyn_cast<FuncDecl>(func))\n        info = info.withNoEscape(fd->isDeferBody());\n    }\n    \n    assert(std::all_of(argTy.begin(), argTy.end(), [](const AnyFunctionType::Param &aty){\n      return !aty.getType()->hasArchetype();\n    }));\n    assert(!funcTy->hasArchetype());\n    if (initFuncTy)\n      assert(!initFuncTy->hasArchetype());\n\n    if (sig && i == e-1) {\n      funcTy = GenericFunctionType::get(sig, argTy, funcTy, info);\n      if (initFuncTy)\n        initFuncTy = GenericFunctionType::get(sig, initArgTy, initFuncTy, info);\n    } else {\n      funcTy = FunctionType::get(argTy, funcTy, info);\n      if (initFuncTy)\n        initFuncTy = FunctionType::get(initArgTy, initFuncTy, info);\n    }\n  }\n\n  \/\/ Record the interface type.\n  func->setInterfaceType(funcTy);\n  if (initFuncTy)\n    cast<ConstructorDecl>(func)->setInitializerInterfaceType(initFuncTy);\n\n  \/\/ We get bogus errors here with generic subscript materializeForSet.\n  if (!isa<FuncDecl>(func) ||\n      cast<FuncDecl>(func)->getAccessorKind() !=\n        AccessorKind::IsMaterializeForSet)\n    checkReferencedGenericParams(func, sig, *this);\n}\n\n\/\/\/\n\/\/\/ Generic subscripts\n\/\/\/\n\/\/\/ FIXME: A lot of this code is duplicated from the generic functions\n\/\/\/ path above. We could consolidate more of this.\n\/\/\/\n\n\/\/\/ Check the signature of a generic subscript.\nstatic bool checkGenericSubscriptSignature(TypeChecker &tc,\n                                           GenericSignatureBuilder *builder,\n                                           SubscriptDecl *subscript,\n                                           GenericTypeResolver &resolver) {\n  bool badType = false;\n\n  \/\/ Check the generic parameter list.\n  auto genericParams = subscript->getGenericParams();\n\n  auto *dc = subscript->getDeclContext();\n\n  tc.checkGenericParamList(\n                    builder, genericParams,\n                    dc->getGenericSignatureOfContext(),\n                    &resolver);\n\n  \/\/ Check the element type.\n  badType |= tc.validateType(subscript->getElementTypeLoc(), subscript,\n                             TR_AllowIUO, &resolver);\n\n  \/\/ Infer requirements from it.\n  if (genericParams && builder) {\n    auto source =\n      GenericSignatureBuilder::FloatingRequirementSource::forInferred(\n          subscript->getElementTypeLoc().getTypeRepr());\n\n    builder->inferRequirements(*subscript->getParentModule(),\n                               subscript->getElementTypeLoc(),\n                               source);\n  }\n\n  \/\/ Check the indices.\n  auto params = subscript->getIndices();\n\n  TypeResolutionOptions options;\n  options |= TR_SubscriptParameters;\n\n  badType |= tc.typeCheckParameterList(params, subscript,\n                                       options,\n                                       resolver);\n\n  \/\/ Infer requirements from the pattern.\n  if (builder) {\n    builder->inferRequirements(*subscript->getParentModule(), params,\n                               genericParams);\n  }\n\n  return badType;\n}\n\nvoid TypeChecker::revertGenericSubscriptSignature(SubscriptDecl *subscript) {\n  \/\/ Revert the element type.\n  if (!subscript->getElementTypeLoc().isNull())\n    revertDependentTypeLoc(subscript->getElementTypeLoc());\n\n  \/\/ Revert the indices.\n  for (auto &param : *subscript->getIndices())\n    revertDependentTypeLoc(param->getTypeLoc());\n}\n\nGenericSignature *\nTypeChecker::validateGenericSubscriptSignature(SubscriptDecl *subscript) {\n  bool invalid = false;\n\n  GenericSignature *sig;\n  if (auto *gp = subscript->getGenericParams()) {\n    prepareGenericParamList(gp, subscript);\n\n    \/\/ Create the generic signature builder.\n    GenericSignatureBuilder builder(Context);\n\n    \/\/ Type check the function declaration, treating all generic type\n    \/\/ parameters as dependent, unresolved.\n    DependentGenericTypeResolver dependentResolver;\n    if (checkGenericSubscriptSignature(*this, &builder, subscript,\n                                       dependentResolver))\n      invalid = true;\n\n    \/\/ The generic subscript signature is complete and well-formed. Determine\n    \/\/ the type of the generic subscript.\n    sig =\n      std::move(builder).computeGenericSignature(subscript->getLoc());\n\n    \/\/ The generic signature builder now has all of the requirements, although\n    \/\/ there might still be errors that have not yet been diagnosed. Revert the\n    \/\/ generic function signature and type-check it again, completely.\n    revertGenericSubscriptSignature(subscript);\n    revertGenericParamList(gp);\n\n    \/\/ Debugging of generic signature generation.\n    if (Context.LangOpts.DebugGenericSignatures) {\n      subscript->dumpRef(llvm::errs());\n      llvm::errs() << \"\\n\";\n      llvm::errs() << \"Generic signature: \";\n      sig->print(llvm::errs());\n      llvm::errs() << \"\\n\";\n      llvm::errs() << \"Canonical generic signature: \";\n      sig->getCanonicalSignature()->print(llvm::errs());\n      llvm::errs() << \"\\n\";\n    }\n  } else {\n    \/\/ Inherit the signature of our environment.\n    sig = subscript->getDeclContext()->getGenericSignatureOfContext();\n  }\n\n  CompleteGenericTypeResolver completeResolver(*this, sig);\n  if (checkGenericSubscriptSignature(*this, nullptr, subscript, completeResolver))\n    invalid = true;\n\n  if (!invalid)\n    invalid = checkProtocolSelfRequirements(sig, subscript, *this);\n\n  if (invalid) {\n    subscript->setInterfaceType(ErrorType::get(Context));\n    subscript->setInvalid();\n    \/\/ null doesn't mean error here: callers still expect the signature.\n    return sig;\n  }\n\n  configureInterfaceType(subscript, sig);\n  return sig;\n}\n\nvoid TypeChecker::configureInterfaceType(SubscriptDecl *subscript,\n                                         GenericSignature *sig) {\n  auto elementTy = subscript->getElementTypeLoc().getType();\n  auto indicesTy = subscript->getIndices()->getInterfaceType(Context);\n  Type funcTy;\n\n  if (sig)\n    funcTy = GenericFunctionType::get(sig, indicesTy, elementTy,\n                                      AnyFunctionType::ExtInfo());\n  else\n    funcTy = FunctionType::get(indicesTy, elementTy);\n\n  \/\/ Record the interface type.\n  subscript->setInterfaceType(funcTy);\n\n  checkReferencedGenericParams(subscript, sig, *this);\n}\n\n\/\/\/\n\/\/\/ Generic types\n\/\/\/\n\n\/\/\/ Visit the given generic parameter lists from the outermost to the innermost,\n\/\/\/ calling the visitor function for each list.\nstatic void visitOuterToInner(\n                      GenericParamList *genericParams,\n                      llvm::function_ref<void(GenericParamList *)> visitor) {\n  if (auto outerGenericParams = genericParams->getOuterParameters())\n    visitOuterToInner(outerGenericParams, visitor);\n\n  visitor(genericParams);\n}\n\n\/\/\/ Retrieve the generic parameter depth of the extended type.\nstatic unsigned getExtendedTypeGenericDepth(ExtensionDecl *ext) {\n  auto nominal = ext->getAsNominalTypeOrNominalTypeExtensionContext();\n  if (!nominal) return static_cast<unsigned>(-1);\n\n  auto sig = nominal->getGenericSignatureOfContext();\n  if (!sig) return static_cast<unsigned>(-1);\n\n  return sig->getGenericParams().back()->getDepth();\n}\n\nGenericEnvironment *TypeChecker::checkGenericEnvironment(\n                      GenericParamList *genericParams,\n                      DeclContext *dc,\n                      GenericSignature *parentSig,\n                      bool allowConcreteGenericParams,\n                      ExtensionDecl *ext,\n                      llvm::function_ref<void(GenericSignatureBuilder &)>\n                        inferRequirements) {\n  assert(genericParams && \"Missing generic parameters?\");\n  bool recursivelyVisitGenericParams =\n    genericParams->getOuterParameters() && !parentSig;\n\n  GenericSignature *sig;\n  if (!ext || ext->getTrailingWhereClause() ||\n      getExtendedTypeGenericDepth(ext) != genericParams->getDepth()) {\n    \/\/ Collect the generic parameters.\n    SmallVector<GenericTypeParamType *, 4> allGenericParams;\n    if (recursivelyVisitGenericParams) {\n      visitOuterToInner(genericParams,\n                        [&](GenericParamList *gpList) {\n        addGenericParamTypes(gpList, allGenericParams);\n      });\n    } else {\n      if (parentSig) {\n        allGenericParams.append(parentSig->getGenericParams().begin(),\n                                parentSig->getGenericParams().end());\n      }\n\n      addGenericParamTypes(genericParams, allGenericParams);\n    }\n\n    \/\/ Create the generic signature builder.\n    GenericSignatureBuilder builder(Context);\n\n    \/\/ Type check the generic parameters, treating all generic type\n    \/\/ parameters as dependent, unresolved.\n    DependentGenericTypeResolver dependentResolver;\n    if (recursivelyVisitGenericParams) {\n      visitOuterToInner(genericParams,\n                        [&](GenericParamList *gpList) {\n        checkGenericParamList(&builder, gpList, nullptr, &dependentResolver);\n      });\n    } else {\n      checkGenericParamList(&builder, genericParams, parentSig,\n                            &dependentResolver);\n    }\n\n    \/\/\/ Perform any necessary requirement inference.\n    inferRequirements(builder);\n\n    \/\/ Record the generic type parameter types and the requirements.\n    sig = std::move(builder).computeGenericSignature(\n                                         genericParams->getSourceRange().Start,\n                                         allowConcreteGenericParams);\n\n    \/\/ The generic signature builder now has all of the requirements, although\n    \/\/ there might still be errors that have not yet been diagnosed. Revert the\n    \/\/ signature and type-check it again, completely.\n    if (recursivelyVisitGenericParams) {\n      visitOuterToInner(genericParams,\n                        [&](GenericParamList *gpList) {\n        revertGenericParamList(gpList);\n      });\n    } else {\n      revertGenericParamList(genericParams);\n    }\n\n    \/\/ Debugging of the generic signature builder and generic signature\n    \/\/ generation.\n    if (Context.LangOpts.DebugGenericSignatures) {\n      dc->printContext(llvm::errs());\n      llvm::errs() << \"\\n\";\n      llvm::errs() << \"Generic signature: \";\n      sig->print(llvm::errs());\n      llvm::errs() << \"\\n\";\n      llvm::errs() << \"Canonical generic signature: \";\n      sig->getCanonicalSignature()->print(llvm::errs());\n      llvm::errs() << \"\\n\";\n    }\n  } else {\n    \/\/ Re-use the signature of the type being extended.\n    sig = ext->getAsNominalTypeOrNominalTypeExtensionContext()\n            ->getGenericSignatureOfContext();\n  }\n\n  CompleteGenericTypeResolver completeResolver(*this, sig);\n  if (recursivelyVisitGenericParams) {\n    visitOuterToInner(genericParams,\n                      [&](GenericParamList *gpList) {\n      checkGenericParamList(nullptr, gpList, nullptr, &completeResolver);\n    });\n  } else {\n    checkGenericParamList(nullptr, genericParams, parentSig,\n                          &completeResolver);\n  }\n\n  \/\/ Form the generic environment.\n  return sig->createGenericEnvironment();\n}\n\nvoid TypeChecker::validateGenericTypeSignature(GenericTypeDecl *typeDecl) {\n  assert(!typeDecl->getGenericEnvironment());\n\n  auto *gp = typeDecl->getGenericParams();\n  auto *dc = typeDecl->getDeclContext();\n\n  if (!gp) {\n    auto *parentEnv = dc->getGenericEnvironmentOfContext();\n    typeDecl->setGenericEnvironment(parentEnv);\n    return;\n  }\n\n  gp->setOuterParameters(dc->getGenericParamsOfContext());\n\n  prepareGenericParamList(gp, typeDecl);\n\n  \/\/ For a protocol, compute the requirement signature first. It will be used\n  \/\/ by clients of the protocol.\n  if (auto proto = dyn_cast<ProtocolDecl>(typeDecl)) {\n    if (!proto->isRequirementSignatureComputed())\n      proto->computeRequirementSignature();\n  }\n\n  auto *env = checkGenericEnvironment(gp, dc,\n                                      dc->getGenericSignatureOfContext(),\n                                      \/*allowConcreteGenericParams=*\/false,\n                                      \/*ext=*\/nullptr);\n  typeDecl->setGenericEnvironment(env);\n}\n\n\/\/\/\n\/\/\/ Checking bound generic type arguments\n\/\/\/\n\nRequirementCheckResult TypeChecker::checkGenericArguments(\n    DeclContext *dc, SourceLoc loc, SourceLoc noteLoc, Type owner,\n    GenericSignature *genericSig, TypeSubstitutionFn substitutions,\n    LookupConformanceFn conformances,\n    UnsatisfiedDependency *unsatisfiedDependency,\n    ConformanceCheckOptions conformanceOptions,\n    GenericRequirementsCheckListener *listener,\n    SubstOptions options) {\n  bool valid = true;\n\n  struct RequirementSet {\n    ArrayRef<Requirement> Requirements;\n    SmallVector<ParentConditionalConformance, 4> Parents;\n  };\n\n  SmallVector<RequirementSet, 8> pendingReqs;\n  pendingReqs.push_back({genericSig->getRequirements(), {}});\n\n  while (!pendingReqs.empty()) {\n    auto current = pendingReqs.pop_back_val();\n\n    for (const auto &rawReq : current.Requirements) {\n      auto req = rawReq;\n      if (current.Parents.empty()) {\n        auto substed = rawReq.subst(substitutions, conformances, options);\n        if (!substed) {\n          \/\/ Another requirement will fail later; just continue.\n          valid = false;\n          continue;\n        }\n\n        req = *substed;\n      }\n\n      auto kind = req.getKind();\n      Type rawFirstType = rawReq.getFirstType();\n      Type firstType = req.getFirstType();\n      Type rawSecondType, secondType;\n      if (kind != RequirementKind::Layout) {\n        rawSecondType = rawReq.getSecondType();\n        secondType = req.getSecondType();\n      }\n\n      bool requirementFailure = false;\n      if (listener && !listener->shouldCheck(kind, firstType, secondType))\n        continue;\n\n      Diag<Type, Type, Type> diagnostic;\n      Diag<Type, Type, StringRef> diagnosticNote;\n\n      switch (kind) {\n      case RequirementKind::Conformance: {\n        \/\/ Protocol conformance requirements.\n        auto proto = secondType->castTo<ProtocolType>();\n        \/\/ FIXME: This should track whether this should result in a private\n        \/\/ or non-private dependency.\n        \/\/ FIXME: Do we really need \"used\" at this point?\n        \/\/ FIXME: Poor location information. How much better can we do here?\n        \/\/ FIXME: This call should support listener to be able to properly\n        \/\/        diagnose problems with conformances.\n        auto result =\n            conformsToProtocol(firstType, proto->getDecl(), dc,\n                               conformanceOptions, loc, unsatisfiedDependency);\n\n        \/\/ Unsatisfied dependency case.\n        auto status = result.getStatus();\n        switch (status) {\n        case RequirementCheckResult::Failure:\n          \/\/ A failure at the top level is diagnosed elsewhere.\n          if (current.Parents.empty())\n            return status;\n\n          diagnostic = diag::type_does_not_conform_owner;\n          diagnosticNote = diag::type_does_not_inherit_or_conform_requirement;\n          requirementFailure = true;\n          break;\n        case RequirementCheckResult::UnsatisfiedDependency:\n        case RequirementCheckResult::SubstitutionFailure:\n          \/\/ pass it on up.\n          return status;\n        case RequirementCheckResult::Success: {\n          auto conformance = result.getConformance();\n          \/\/ Report the conformance.\n          if (listener && valid && current.Parents.empty()) {\n            listener->satisfiedConformance(rawFirstType, firstType,\n                                           conformance);\n          }\n\n          auto conditionalReqs = conformance.getConditionalRequirements();\n          if (!conditionalReqs.empty()) {\n            auto history = current.Parents;\n            history.push_back({firstType, proto});\n            pendingReqs.push_back({conditionalReqs, std::move(history)});\n          }\n          continue;\n        }\n        }\n\n        \/\/ Failure needs to emit a diagnostic.\n        break;\n      }\n\n      case RequirementKind::Layout: {\n        \/\/ TODO: Statically check if a the first type\n        \/\/ conforms to the layout constraint, once we\n        \/\/ support such static checks.\n        continue;\n      }\n\n      case RequirementKind::Superclass:\n        \/\/ Superclass requirements.\n        if (!isSubclassOf(firstType, secondType, dc)) {\n          diagnostic = diag::type_does_not_inherit;\n          diagnosticNote = diag::type_does_not_inherit_or_conform_requirement;\n          requirementFailure = true;\n        }\n        break;\n\n      case RequirementKind::SameType:\n        if (!firstType->isEqual(secondType)) {\n          diagnostic = diag::types_not_equal;\n          diagnosticNote = diag::types_not_equal_requirement;\n          requirementFailure = true;\n        }\n        break;\n      }\n\n      if (!requirementFailure)\n        continue;\n\n      if (listener &&\n          listener->diagnoseUnsatisfiedRequirement(rawReq, firstType,\n                                                   secondType, current.Parents))\n        return RequirementCheckResult::Failure;\n\n      if (loc.isValid()) {\n        \/\/ FIXME: Poor source-location information.\n        diagnose(loc, diagnostic, owner, firstType, secondType);\n        diagnose(noteLoc, diagnosticNote, rawFirstType, rawSecondType,\n                 genericSig->gatherGenericParamBindingsText(\n                     {rawFirstType, rawSecondType}, substitutions));\n\n        ParentConditionalConformance::diagnoseConformanceStack(Diags, noteLoc,\n                                                               current.Parents);\n      }\n\n      return RequirementCheckResult::Failure;\n    }\n  }\n\n  if (valid)\n    return RequirementCheckResult::Success;\n  return RequirementCheckResult::SubstitutionFailure;\n}\n","avg_line_length":35.7827988338,"max_line_length":95,"alphanum_fraction":0.6442335112,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":49314,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2014 The Bitcoin Core developers\n\/\/ Copyright (c) 2017 The PIVX developers\n\/\/ Copyright (c) 2018-2019 The VALIDEUM developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"data\/script_invalid.json.h\"\n#include \"data\/script_valid.json.h\"\n\n#include \"core_io.h\"\n#include \"key.h\"\n#include \"keystore.h\"\n#include \"main.h\"\n#include \"script\/script.h\"\n#include \"script\/script_error.h\"\n#include \"script\/sign.h\"\n#include \"util.h\"\n\n#if defined(HAVE_CONSENSUS_LIB)\n#include \"script\/bitcoinconsensus.h\"\n#endif\n\n#include <fstream>\n#include <stdint.h>\n#include <string>\n#include <vector>\n\n#include <boost\/algorithm\/string\/classification.hpp>\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/algorithm\/string\/replace.hpp>\n#include <boost\/algorithm\/string\/split.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/test\/unit_test.hpp>\n\n#include <univalue.h>\n\nusing namespace std;\nusing namespace boost::algorithm;\n\n\/\/ Uncomment if you want to output updated JSON tests.\n\/\/ #define UPDATE_JSON_TESTS\n\nstatic const unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC;\n\nunsigned int ParseScriptFlags(string strFlags);\nstring FormatScriptFlags(unsigned int flags);\n\nUniValue\nread_json(const std::string& jsondata)\n{\n    UniValue v;\n\n    if (!v.read(jsondata) || !v.isArray())\n    {\n        BOOST_ERROR(\"Parse error.\");\n        return UniValue(UniValue::VARR);\n    }\n    return v.get_array();\n}\n\nBOOST_AUTO_TEST_SUITE(script_tests)\n\nCMutableTransaction BuildCreditingTransaction(const CScript& scriptPubKey)\n{\n    CMutableTransaction txCredit;\n    txCredit.nVersion = 1;\n    txCredit.nLockTime = 0;\n    txCredit.vin.resize(1);\n    txCredit.vout.resize(1);\n    txCredit.vin[0].prevout.SetNull();\n    txCredit.vin[0].scriptSig = CScript() << CScriptNum(0) << CScriptNum(0);\n    txCredit.vin[0].nSequence = std::numeric_limits<unsigned int>::max();\n    txCredit.vout[0].scriptPubKey = scriptPubKey;\n    txCredit.vout[0].nValue = 0;\n\n    return txCredit;\n}\n\nCMutableTransaction BuildSpendingTransaction(const CScript& scriptSig, const CMutableTransaction& txCredit)\n{\n    CMutableTransaction txSpend;\n    txSpend.nVersion = 1;\n    txSpend.nLockTime = 0;\n    txSpend.vin.resize(1);\n    txSpend.vout.resize(1);\n    txSpend.vin[0].prevout.hash = txCredit.GetHash();\n    txSpend.vin[0].prevout.n = 0;\n    txSpend.vin[0].scriptSig = scriptSig;\n    txSpend.vin[0].nSequence = std::numeric_limits<unsigned int>::max();\n    txSpend.vout[0].scriptPubKey = CScript();\n    txSpend.vout[0].nValue = 0;\n\n    return txSpend;\n}\n\nvoid DoTest(const CScript& scriptPubKey, const CScript& scriptSig, int flags, bool expect, const std::string& message)\n{\n    ScriptError err;\n    CMutableTransaction tx = BuildSpendingTransaction(scriptSig, BuildCreditingTransaction(scriptPubKey));\n    CMutableTransaction tx2 = tx;\n    BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, flags, MutableTransactionSignatureChecker(&tx, 0), &err) == expect, message);\n    BOOST_CHECK_MESSAGE(expect == (err == SCRIPT_ERR_OK), std::string(ScriptErrorString(err)) + \": \" + message);\n#if defined(HAVE_CONSENSUS_LIB)\n    CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n    stream << tx2;\n    BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script(begin_ptr(scriptPubKey), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), 0, flags, NULL) == expect,message);\n#endif\n}\n\nvoid static NegateSignatureS(std::vector<unsigned char>& vchSig) {\n    \/\/ Parse the signature.\n    std::vector<unsigned char> r, s;\n    r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]);\n    s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]);\n    unsigned char hashtype = vchSig.back();\n\n    \/\/ Really ugly to implement mod-n negation here, but it would be feature creep to expose such functionality from libsecp256k1.\n    static const unsigned char order[33] = {\n        0x00,\n        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,\n        0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,\n        0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41\n    };\n    while (s.size() < 33) {\n        s.insert(s.begin(), 0x00);\n    }\n    int carry = 0;\n    for (int p = 32; p >= 1; p--) {\n        int n = (int)order[p] - s[p] - carry;\n        s[p] = (n + 256) & 0xFF;\n        carry = (n < 0);\n    }\n    assert(carry == 0);\n    if (s.size() > 1 && s[0] == 0 && s[1] < 0x80) {\n        s.erase(s.begin());\n    }\n\n    \/\/ Reconstruct the signature.\n    vchSig.clear();\n    vchSig.push_back(0x30);\n    vchSig.push_back(4 + r.size() + s.size());\n    vchSig.push_back(0x02);\n    vchSig.push_back(r.size());\n    vchSig.insert(vchSig.end(), r.begin(), r.end());\n    vchSig.push_back(0x02);\n    vchSig.push_back(s.size());\n    vchSig.insert(vchSig.end(), s.begin(), s.end());\n    vchSig.push_back(hashtype);\n}\n\nnamespace\n{\nconst unsigned char vchKey0[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};\nconst unsigned char vchKey1[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0};\nconst unsigned char vchKey2[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0};\n\nstruct KeyData\n{\n    CKey key0, key0C, key1, key1C, key2, key2C;\n    CPubKey pubkey0, pubkey0C, pubkey0H;\n    CPubKey pubkey1, pubkey1C;\n    CPubKey pubkey2, pubkey2C;\n\n    KeyData()\n    {\n\n        key0.Set(vchKey0, vchKey0 + 32, false);\n        key0C.Set(vchKey0, vchKey0 + 32, true);\n        pubkey0 = key0.GetPubKey();\n        pubkey0H = key0.GetPubKey();\n        pubkey0C = key0C.GetPubKey();\n        *const_cast<unsigned char*>(&pubkey0H[0]) = 0x06 | (pubkey0H[64] & 1);\n\n        key1.Set(vchKey1, vchKey1 + 32, false);\n        key1C.Set(vchKey1, vchKey1 + 32, true);\n        pubkey1 = key1.GetPubKey();\n        pubkey1C = key1C.GetPubKey();\n\n        key2.Set(vchKey2, vchKey2 + 32, false);\n        key2C.Set(vchKey2, vchKey2 + 32, true);\n        pubkey2 = key2.GetPubKey();\n        pubkey2C = key2C.GetPubKey();\n    }\n};\n\n\nclass TestBuilder\n{\nprivate:\n    CScript scriptPubKey;\n    CTransaction creditTx;\n    CMutableTransaction spendTx;\n    bool havePush;\n    std::vector<unsigned char> push;\n    std::string comment;\n    int flags;\n\n    void DoPush()\n    {\n        if (havePush) {\n            spendTx.vin[0].scriptSig << push;\n            havePush = false;\n        }\n    }\n\n    void DoPush(const std::vector<unsigned char>& data)\n    {\n         DoPush();\n         push = data;\n         havePush = true;\n    }\n\npublic:\n    TestBuilder(const CScript& redeemScript, const std::string& comment_, int flags_, bool P2SH = false) : scriptPubKey(redeemScript), havePush(false), comment(comment_), flags(flags_)\n    {\n        if (P2SH) {\n            creditTx = BuildCreditingTransaction(CScript() << OP_HASH160 << ToByteVector(CScriptID(redeemScript)) << OP_EQUAL);\n        } else {\n            creditTx = BuildCreditingTransaction(redeemScript);\n        }\n        spendTx = BuildSpendingTransaction(CScript(), creditTx);\n    }\n\n    TestBuilder& Add(const CScript& script)\n    {\n        DoPush();\n        spendTx.vin[0].scriptSig += script;\n        return *this;\n    }\n\n    TestBuilder& Num(int num)\n    {\n        DoPush();\n        spendTx.vin[0].scriptSig << num;\n        return *this;\n    }\n\n    TestBuilder& Push(const std::string& hex)\n    {\n        DoPush(ParseHex(hex));\n        return *this;\n    }\n\n    TestBuilder& PushSig(const CKey& key, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32)\n    {\n        uint256 hash = SignatureHash(scriptPubKey, spendTx, 0, nHashType);\n        std::vector<unsigned char> vchSig, r, s;\n        uint32_t iter = 0;\n        do {\n            key.Sign(hash, vchSig, iter++);\n            if ((lenS == 33) != (vchSig[5 + vchSig[3]] == 33)) {\n                NegateSignatureS(vchSig);\n            }\n            r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]);\n            s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]);\n        } while (lenR != r.size() || lenS != s.size());\n        vchSig.push_back(static_cast<unsigned char>(nHashType));\n        DoPush(vchSig);\n        return *this;\n    }\n\n    TestBuilder& Push(const CPubKey& pubkey)\n    {\n        DoPush(std::vector<unsigned char>(pubkey.begin(), pubkey.end()));\n        return *this;\n    }\n\n    TestBuilder& PushRedeem()\n    {\n        DoPush(static_cast<std::vector<unsigned char> >(scriptPubKey));\n        return *this;\n    }\n\n    TestBuilder& EditPush(unsigned int pos, const std::string& hexin, const std::string& hexout)\n    {\n        assert(havePush);\n        std::vector<unsigned char> datain = ParseHex(hexin);\n        std::vector<unsigned char> dataout = ParseHex(hexout);\n        assert(pos + datain.size() <= push.size());\n        BOOST_CHECK_MESSAGE(std::vector<unsigned char>(push.begin() + pos, push.begin() + pos + datain.size()) == datain, comment);\n        push.erase(push.begin() + pos, push.begin() + pos + datain.size());\n        push.insert(push.begin() + pos, dataout.begin(), dataout.end());\n        return *this;\n    }\n\n    TestBuilder& DamagePush(unsigned int pos)\n    {\n        assert(havePush);\n        assert(pos < push.size());\n        push[pos] ^= 1;\n        return *this;\n    }\n\n    TestBuilder& Test(bool expect)\n    {\n        TestBuilder copy = *this; \/\/ Make a copy so we can rollback the push.\n        DoPush();\n        DoTest(creditTx.vout[0].scriptPubKey, spendTx.vin[0].scriptSig, flags, expect, comment);\n        *this = copy;\n        return *this;\n    }\n\n    UniValue GetJSON()\n    {\n        DoPush();\n        UniValue array(UniValue::VARR);\n        array.push_back(FormatScript(spendTx.vin[0].scriptSig));\n        array.push_back(FormatScript(creditTx.vout[0].scriptPubKey));\n        array.push_back(FormatScriptFlags(flags));\n        array.push_back(comment);\n        return array;\n    }\n\n    std::string GetComment()\n    {\n        return comment;\n    }\n\n    const CScript& GetScriptPubKey()\n    {\n        return creditTx.vout[0].scriptPubKey;\n    }\n};\n}\n\nBOOST_AUTO_TEST_CASE(script_build)\n{\n    const KeyData keys;\n\n    std::vector<TestBuilder> good;\n    std::vector<TestBuilder> bad;\n\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,\n                               \"P2PK\", 0\n                              ).PushSig(keys.key0));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,\n                              \"P2PK, bad sig\", 0\n                             ).PushSig(keys.key0).DamagePush(10));\n\n    good.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,\n                               \"P2PKH\", 0\n                              ).PushSig(keys.key1).Push(keys.pubkey1C));\n    bad.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey2C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,\n                              \"P2PKH, bad pubkey\", 0\n                             ).PushSig(keys.key2).Push(keys.pubkey2C).DamagePush(5));\n\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,\n                               \"P2PK anyonecanpay\", 0\n                              ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,\n                              \"P2PK anyonecanpay marked with normal hashtype\", 0\n                             ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY).EditPush(70, \"81\", \"01\"));\n\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,\n                               \"P2SH(P2PK)\", SCRIPT_VERIFY_P2SH, true\n                              ).PushSig(keys.key0).PushRedeem());\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,\n                              \"P2SH(P2PK), bad redeemscript\", SCRIPT_VERIFY_P2SH, true\n                             ).PushSig(keys.key0).PushRedeem().DamagePush(10));\n\n    good.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,\n                               \"P2SH(P2PKH), bad sig but no VERIFY_P2SH\", 0, true\n                              ).PushSig(keys.key0).DamagePush(10).PushRedeem());\n    bad.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,\n                              \"P2SH(P2PKH), bad sig\", SCRIPT_VERIFY_P2SH, true\n                             ).PushSig(keys.key0).DamagePush(10).PushRedeem());\n\n    good.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,\n                               \"3-of-3\", 0\n                              ).Num(0).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));\n    bad.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,\n                              \"3-of-3, 2 sigs\", 0\n                             ).Num(0).PushSig(keys.key0).PushSig(keys.key1).Num(0));\n\n    good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,\n                               \"P2SH(2-of-3)\", SCRIPT_VERIFY_P2SH, true\n                              ).Num(0).PushSig(keys.key1).PushSig(keys.key2).PushRedeem());\n    bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,\n                              \"P2SH(2-of-3), 1 sig\", SCRIPT_VERIFY_P2SH, true\n                             ).Num(0).PushSig(keys.key1).Num(0).PushRedeem());\n\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,\n                               \"P2PK with too much R padding but no DERSIG\", 0\n                              ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, \"43021F\", \"44022000\"));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,\n                              \"P2PK with too much R padding\", SCRIPT_VERIFY_DERSIG\n                             ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, \"43021F\", \"44022000\"));\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,\n                               \"P2PK with too much S padding but no DERSIG\", 0\n                              ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, \"44\", \"45\").EditPush(37, \"20\", \"2100\"));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,\n                              \"P2PK with too much S padding\", SCRIPT_VERIFY_DERSIG\n                             ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, \"44\", \"45\").EditPush(37, \"20\", \"2100\"));\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,\n                               \"P2PK with too little R padding but no DERSIG\", 0\n                              ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\"));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,\n                              \"P2PK with too little R padding\", SCRIPT_VERIFY_DERSIG\n                             ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\"));\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,\n                               \"P2PK NOT with bad sig with too much R padding but no DERSIG\", 0\n                              ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, \"43021F\", \"44022000\").DamagePush(10));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,\n                              \"P2PK NOT with bad sig with too much R padding\", SCRIPT_VERIFY_DERSIG\n                             ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, \"43021F\", \"44022000\").DamagePush(10));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,\n                              \"P2PK NOT with too much R padding but no DERSIG\", 0\n                             ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, \"43021F\", \"44022000\"));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,\n                              \"P2PK NOT with too much R padding\", SCRIPT_VERIFY_DERSIG\n                             ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, \"43021F\", \"44022000\"));\n\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,\n                               \"BIP66 example 1, without DERSIG\", 0\n                              ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\"));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,\n                              \"BIP66 example 1, with DERSIG\", SCRIPT_VERIFY_DERSIG\n                             ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\"));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,\n                              \"BIP66 example 2, without DERSIG\", 0\n                             ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\"));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,\n                              \"BIP66 example 2, with DERSIG\", SCRIPT_VERIFY_DERSIG\n                             ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\"));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,\n                              \"BIP66 example 3, without DERSIG\", 0\n                             ).Num(0));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,\n                              \"BIP66 example 3, with DERSIG\", SCRIPT_VERIFY_DERSIG\n                             ).Num(0));\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,\n                               \"BIP66 example 4, without DERSIG\", 0\n                              ).Num(0));\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,\n                               \"BIP66 example 4, with DERSIG\", SCRIPT_VERIFY_DERSIG\n                              ).Num(0));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,\n                              \"BIP66 example 5, without DERSIG\", 0\n                             ).Num(1));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,\n                              \"BIP66 example 5, with DERSIG\", SCRIPT_VERIFY_DERSIG\n                             ).Num(1));\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,\n                               \"BIP66 example 6, without DERSIG\", 0\n                              ).Num(1));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,\n                              \"BIP66 example 6, with DERSIG\", SCRIPT_VERIFY_DERSIG\n                             ).Num(1));\n    good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,\n                               \"BIP66 example 7, without DERSIG\", 0\n                              ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\").PushSig(keys.key2));\n    bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,\n                              \"BIP66 example 7, with DERSIG\", SCRIPT_VERIFY_DERSIG\n                             ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\").PushSig(keys.key2));\n    bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,\n                              \"BIP66 example 8, without DERSIG\", 0\n                             ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\").PushSig(keys.key2));\n    bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,\n                              \"BIP66 example 8, with DERSIG\", SCRIPT_VERIFY_DERSIG\n                             ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\").PushSig(keys.key2));\n    bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,\n                              \"BIP66 example 9, without DERSIG\", 0\n                             ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\"));\n    bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,\n                              \"BIP66 example 9, with DERSIG\", SCRIPT_VERIFY_DERSIG\n                             ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\"));\n    good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,\n                               \"BIP66 example 10, without DERSIG\", 0\n                              ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\"));\n    bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,\n                              \"BIP66 example 10, with DERSIG\", SCRIPT_VERIFY_DERSIG\n                             ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\"));\n    bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,\n                              \"BIP66 example 11, without DERSIG\", 0\n                             ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\").Num(0));\n    bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,\n                              \"BIP66 example 11, with DERSIG\", SCRIPT_VERIFY_DERSIG\n                             ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\").Num(0));\n    good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,\n                               \"BIP66 example 12, without DERSIG\", 0\n                              ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\").Num(0));\n    good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,\n                               \"BIP66 example 12, with DERSIG\", SCRIPT_VERIFY_DERSIG\n                              ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, \"45022100\", \"440220\").Num(0));\n\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,\n                               \"P2PK with high S but no LOW_S\", 0\n                              ).PushSig(keys.key2, SIGHASH_ALL, 32, 33));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,\n                              \"P2PK with high S\", SCRIPT_VERIFY_LOW_S\n                             ).PushSig(keys.key2, SIGHASH_ALL, 32, 33));\n\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,\n                               \"P2PK with hybrid pubkey but no STRICTENC\", 0\n                              ).PushSig(keys.key0, SIGHASH_ALL));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,\n                              \"P2PK with hybrid pubkey\", SCRIPT_VERIFY_STRICTENC\n                             ).PushSig(keys.key0, SIGHASH_ALL));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,\n                              \"P2PK NOT with hybrid pubkey but no STRICTENC\", 0\n                             ).PushSig(keys.key0, SIGHASH_ALL));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,\n                              \"P2PK NOT with hybrid pubkey\", SCRIPT_VERIFY_STRICTENC\n                             ).PushSig(keys.key0, SIGHASH_ALL));\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,\n                               \"P2PK NOT with invalid hybrid pubkey but no STRICTENC\", 0\n                              ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,\n                              \"P2PK NOT with invalid hybrid pubkey\", SCRIPT_VERIFY_STRICTENC\n                             ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10));\n    good.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,\n                               \"1-of-2 with the second 1 hybrid pubkey and no STRICTENC\", 0\n                              ).Num(0).PushSig(keys.key1, SIGHASH_ALL));\n    good.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,\n                               \"1-of-2 with the second 1 hybrid pubkey\", SCRIPT_VERIFY_STRICTENC\n                              ).Num(0).PushSig(keys.key1, SIGHASH_ALL));\n    bad.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0H) << OP_2 << OP_CHECKMULTISIG,\n                              \"1-of-2 with the first 1 hybrid pubkey\", SCRIPT_VERIFY_STRICTENC\n                             ).Num(0).PushSig(keys.key1, SIGHASH_ALL));\n\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,\n                               \"P2PK with undefined hashtype but no STRICTENC\", 0\n                              ).PushSig(keys.key1, 5));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,\n                              \"P2PK with undefined hashtype\", SCRIPT_VERIFY_STRICTENC\n                             ).PushSig(keys.key1, 5));\n    good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,\n                               \"P2PK NOT with invalid sig and undefined hashtype but no STRICTENC\", 0\n                              ).PushSig(keys.key1, 5).DamagePush(10));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,\n                              \"P2PK NOT with invalid sig and undefined hashtype\", SCRIPT_VERIFY_STRICTENC\n                             ).PushSig(keys.key1, 5).DamagePush(10));\n\n    good.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,\n                               \"3-of-3 with nonzero dummy but no NULLDUMMY\", 0\n                              ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));\n    bad.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,\n                              \"3-of-3 with nonzero dummy\", SCRIPT_VERIFY_NULLDUMMY\n                             ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));\n    good.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,\n                               \"3-of-3 NOT with invalid sig and nonzero dummy but no NULLDUMMY\", 0\n                              ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10));\n    bad.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,\n                              \"3-of-3 NOT with invalid sig with nonzero dummy\", SCRIPT_VERIFY_NULLDUMMY\n                             ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10));\n\n    good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,\n                               \"2-of-2 with two identical keys and sigs pushed using OP_DUP but no SIGPUSHONLY\", 0\n                              ).Num(0).PushSig(keys.key1).Add(CScript() << OP_DUP));\n    bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,\n                              \"2-of-2 with two identical keys and sigs pushed using OP_DUP\", SCRIPT_VERIFY_SIGPUSHONLY\n                             ).Num(0).PushSig(keys.key1).Add(CScript() << OP_DUP));\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,\n                              \"P2SH(P2PK) with non-push scriptSig but no SIGPUSHONLY\", 0\n                             ).PushSig(keys.key2).PushRedeem());\n    bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,\n                              \"P2SH(P2PK) with non-push scriptSig\", SCRIPT_VERIFY_SIGPUSHONLY\n                             ).PushSig(keys.key2).PushRedeem());\n    good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,\n                               \"2-of-2 with two identical keys and sigs pushed\", SCRIPT_VERIFY_SIGPUSHONLY\n                              ).Num(0).PushSig(keys.key1).PushSig(keys.key1));\n\n\n    std::set<std::string> tests_good;\n    std::set<std::string> tests_bad;\n\n    {\n        UniValue json_good = read_json(std::string(json_tests::script_valid, json_tests::script_valid + sizeof(json_tests::script_valid)));\n        UniValue json_bad = read_json(std::string(json_tests::script_invalid, json_tests::script_invalid + sizeof(json_tests::script_invalid)));\n\n        for (unsigned int idx = 0; idx < json_good.size(); idx++) {\n            const UniValue& tv = json_good[idx];\n            tests_good.insert(tv.get_array().write());\n        }\n        for (unsigned int idx = 0; idx < json_bad.size(); idx++) {\n            const UniValue& tv = json_bad[idx];\n            tests_bad.insert(tv.get_array().write());\n        }\n    }\n\n    std::string strGood;\n    std::string strBad;\n\n    BOOST_FOREACH(TestBuilder& test, good) {\n        test.Test(true);\n        std::string str = test.GetJSON().write();\n#ifndef UPDATE_JSON_TESTS\n        if (tests_good.count(str) == 0) {\n            BOOST_CHECK_MESSAGE(false, \"Missing auto script_valid test: \" + test.GetComment());\n        }\n#endif\n        strGood += str + \",\\n\";\n    }\n    BOOST_FOREACH(TestBuilder& test, bad) {\n        test.Test(false);\n        std::string str = test.GetJSON().write();\n#ifndef UPDATE_JSON_TESTS\n        if (tests_bad.count(str) == 0) {\n            BOOST_CHECK_MESSAGE(false, \"Missing auto script_invalid test: \" + test.GetComment());\n        }\n#endif\n        strBad += str + \",\\n\";\n    }\n\n#ifdef UPDATE_JSON_TESTS\n    FILE* valid = fopen(\"script_valid.json.gen\", \"w\");\n    fputs(strGood.c_str(), valid);\n    fclose(valid);\n    FILE* invalid = fopen(\"script_invalid.json.gen\", \"w\");\n    fputs(strBad.c_str(), invalid);\n    fclose(invalid);\n#endif\n}\n\nBOOST_AUTO_TEST_CASE(script_valid)\n{\n    \/\/ Read tests from test\/data\/script_valid.json\n    \/\/ Format is an array of arrays\n    \/\/ Inner arrays are [ \"scriptSig\", \"scriptPubKey\", \"flags\" ]\n    \/\/ ... where scriptSig and scriptPubKey are stringified\n    \/\/ scripts.\n    UniValue tests = read_json(std::string(json_tests::script_valid, json_tests::script_valid + sizeof(json_tests::script_valid)));\n\n    for (unsigned int idx = 0; idx < tests.size(); idx++) {\n        UniValue test = tests[idx];\n        string strTest = test.write();\n        if (test.size() < 3) \/\/ Allow size > 3; extra stuff ignored (useful for comments)\n        {\n            if (test.size() != 1) {\n                BOOST_ERROR(\"Bad test: \" << strTest);\n            }\n            continue;\n        }\n        string scriptSigString = test[0].get_str();\n        CScript scriptSig = ParseScript(scriptSigString);\n        string scriptPubKeyString = test[1].get_str();\n        CScript scriptPubKey = ParseScript(scriptPubKeyString);\n        unsigned int scriptflags = ParseScriptFlags(test[2].get_str());\n\n        DoTest(scriptPubKey, scriptSig, scriptflags, true, strTest);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(script_invalid)\n{\n    \/\/ Scripts that should evaluate as invalid\n    UniValue tests = read_json(std::string(json_tests::script_invalid, json_tests::script_invalid + sizeof(json_tests::script_invalid)));\n\n    for (unsigned int idx = 0; idx < tests.size(); idx++) {\n        UniValue test = tests[idx];\n        string strTest = test.write();\n        if (test.size() < 3) \/\/ Allow size > 3; extra stuff ignored (useful for comments)\n        {\n            if (test.size() != 1) {\n                BOOST_ERROR(\"Bad test: \" << strTest);\n            }\n            continue;\n        }\n        string scriptSigString = test[0].get_str();\n        CScript scriptSig = ParseScript(scriptSigString);\n        string scriptPubKeyString = test[1].get_str();\n        CScript scriptPubKey = ParseScript(scriptPubKeyString);\n        unsigned int scriptflags = ParseScriptFlags(test[2].get_str());\n\n        DoTest(scriptPubKey, scriptSig, scriptflags, false, strTest);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(script_PushData)\n{\n    \/\/ Check that PUSHDATA1, PUSHDATA2, and PUSHDATA4 create the same value on\n    \/\/ the stack as the 1-75 opcodes do.\n    static const unsigned char direct[] = { 1, 0x5a };\n    static const unsigned char pushdata1[] = { OP_PUSHDATA1, 1, 0x5a };\n    static const unsigned char pushdata2[] = { OP_PUSHDATA2, 1, 0, 0x5a };\n    static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a };\n\n    ScriptError err;\n    vector<vector<unsigned char> > directStack;\n    BOOST_CHECK(EvalScript(directStack, CScript(&direct[0], &direct[sizeof(direct)]), true, BaseSignatureChecker(), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));\n\n    vector<vector<unsigned char> > pushdata1Stack;\n    BOOST_CHECK(EvalScript(pushdata1Stack, CScript(&pushdata1[0], &pushdata1[sizeof(pushdata1)]), true, BaseSignatureChecker(), &err));\n    BOOST_CHECK(pushdata1Stack == directStack);\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));\n\n    vector<vector<unsigned char> > pushdata2Stack;\n    BOOST_CHECK(EvalScript(pushdata2Stack, CScript(&pushdata2[0], &pushdata2[sizeof(pushdata2)]), true, BaseSignatureChecker(), &err));\n    BOOST_CHECK(pushdata2Stack == directStack);\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));\n\n    vector<vector<unsigned char> > pushdata4Stack;\n    BOOST_CHECK(EvalScript(pushdata4Stack, CScript(&pushdata4[0], &pushdata4[sizeof(pushdata4)]), true, BaseSignatureChecker(), &err));\n    BOOST_CHECK(pushdata4Stack == directStack);\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));\n}\n\nCScript\nsign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transaction)\n{\n    uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL);\n\n    CScript result;\n    \/\/\n    \/\/ NOTE: CHECKMULTISIG has an unfortunate bug; it requires\n    \/\/ one extra item on the stack, before the signatures.\n    \/\/ Putting OP_0 on the stack is the workaround;\n    \/\/ fixing the bug would mean splitting the block chain (old\n    \/\/ clients would not accept new CHECKMULTISIG transactions,\n    \/\/ and vice-versa)\n    \/\/\n    result << OP_0;\n    BOOST_FOREACH(const CKey &key, keys)\n    {\n        vector<unsigned char> vchSig;\n        BOOST_CHECK(key.Sign(hash, vchSig));\n        vchSig.push_back((unsigned char)SIGHASH_ALL);\n        result << vchSig;\n    }\n    return result;\n}\nCScript\nsign_multisig(CScript scriptPubKey, const CKey &key, CTransaction transaction)\n{\n    std::vector<CKey> keys;\n    keys.push_back(key);\n    return sign_multisig(scriptPubKey, keys, transaction);\n}\n\nBOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12)\n{\n    ScriptError err;\n    CKey key1, key2, key3;\n    key1.MakeNewKey(true);\n    key2.MakeNewKey(false);\n    key3.MakeNewKey(true);\n\n    CScript scriptPubKey12;\n    scriptPubKey12 << OP_1 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << OP_2 << OP_CHECKMULTISIG;\n\n    CMutableTransaction txFrom12 = BuildCreditingTransaction(scriptPubKey12);\n    CMutableTransaction txTo12 = BuildSpendingTransaction(CScript(), txFrom12);\n\n    CScript goodsig1 = sign_multisig(scriptPubKey12, key1, txTo12);\n    BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));\n    txTo12.vout[0].nValue = 2;\n    BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));\n\n    CScript goodsig2 = sign_multisig(scriptPubKey12, key2, txTo12);\n    BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));\n\n    CScript badsig1 = sign_multisig(scriptPubKey12, key3, txTo12);\n    BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));\n}\n\nBOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23)\n{\n    ScriptError err;\n    CKey key1, key2, key3, key4;\n    key1.MakeNewKey(true);\n    key2.MakeNewKey(false);\n    key3.MakeNewKey(true);\n    key4.MakeNewKey(false);\n\n    CScript scriptPubKey23;\n    scriptPubKey23 << OP_2 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << ToByteVector(key3.GetPubKey()) << OP_3 << OP_CHECKMULTISIG;\n\n    CMutableTransaction txFrom23 = BuildCreditingTransaction(scriptPubKey23);\n    CMutableTransaction txTo23 = BuildSpendingTransaction(CScript(), txFrom23);\n\n    std::vector<CKey> keys;\n    keys.push_back(key1); keys.push_back(key2);\n    CScript goodsig1 = sign_multisig(scriptPubKey23, keys, txTo23);\n    BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));\n\n    keys.clear();\n    keys.push_back(key1); keys.push_back(key3);\n    CScript goodsig2 = sign_multisig(scriptPubKey23, keys, txTo23);\n    BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));\n\n    keys.clear();\n    keys.push_back(key2); keys.push_back(key3);\n    CScript goodsig3 = sign_multisig(scriptPubKey23, keys, txTo23);\n    BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));\n\n    keys.clear();\n    keys.push_back(key2); keys.push_back(key2); \/\/ Can't re-use sig\n    CScript badsig1 = sign_multisig(scriptPubKey23, keys, txTo23);\n    BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));\n\n    keys.clear();\n    keys.push_back(key2); keys.push_back(key1); \/\/ sigs must be in correct order\n    CScript badsig2 = sign_multisig(scriptPubKey23, keys, txTo23);\n    BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));\n\n    keys.clear();\n    keys.push_back(key3); keys.push_back(key2); \/\/ sigs must be in correct order\n    CScript badsig3 = sign_multisig(scriptPubKey23, keys, txTo23);\n    BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));\n\n    keys.clear();\n    keys.push_back(key4); keys.push_back(key2); \/\/ sigs must match pubkeys\n    CScript badsig4 = sign_multisig(scriptPubKey23, keys, txTo23);\n    BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));\n\n    keys.clear();\n    keys.push_back(key1); keys.push_back(key4); \/\/ sigs must match pubkeys\n    CScript badsig5 = sign_multisig(scriptPubKey23, keys, txTo23);\n    BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));\n\n    keys.clear(); \/\/ Must have signatures\n    CScript badsig6 = sign_multisig(scriptPubKey23, keys, txTo23);\n    BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));\n    BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err));\n}    \n\nBOOST_AUTO_TEST_CASE(script_combineSigs)\n{\n    \/\/ Test the CombineSignatures function\n    CBasicKeyStore keystore;\n    vector<CKey> keys;\n    vector<CPubKey> pubkeys;\n    for (int i = 0; i < 3; i++)\n    {\n        CKey key;\n        key.MakeNewKey(i%2 == 1);\n        keys.push_back(key);\n        pubkeys.push_back(key.GetPubKey());\n        keystore.AddKey(key);\n    }\n\n    CMutableTransaction txFrom = BuildCreditingTransaction(GetScriptForDestination(keys[0].GetPubKey().GetID()));\n    CMutableTransaction txTo = BuildSpendingTransaction(CScript(), txFrom);\n    CScript& scriptPubKey = txFrom.vout[0].scriptPubKey;\n    CScript& scriptSig = txTo.vin[0].scriptSig;\n\n    CScript empty;\n    CScript combined = CombineSignatures(scriptPubKey, txTo, 0, empty, empty);\n    BOOST_CHECK(combined.empty());\n\n    \/\/ Single signature case:\n    SignSignature(keystore, txFrom, txTo, 0); \/\/ changes scriptSig\n    combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty);\n    BOOST_CHECK(combined == scriptSig);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig);\n    BOOST_CHECK(combined == scriptSig);\n    CScript scriptSigCopy = scriptSig;\n    \/\/ Signing again will give a different, valid signature:\n    SignSignature(keystore, txFrom, txTo, 0);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig);\n    BOOST_CHECK(combined == scriptSigCopy || combined == scriptSig);\n\n    \/\/ P2SH, single-signature case:\n    CScript pkSingle; pkSingle << ToByteVector(keys[0].GetPubKey()) << OP_CHECKSIG;\n    keystore.AddCScript(pkSingle);\n    scriptPubKey = GetScriptForDestination(CScriptID(pkSingle));\n    SignSignature(keystore, txFrom, txTo, 0);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty);\n    BOOST_CHECK(combined == scriptSig);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig);\n    BOOST_CHECK(combined == scriptSig);\n    scriptSigCopy = scriptSig;\n    SignSignature(keystore, txFrom, txTo, 0);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig);\n    BOOST_CHECK(combined == scriptSigCopy || combined == scriptSig);\n    \/\/ dummy scriptSigCopy with placeholder, should always choose non-placeholder:\n    scriptSigCopy = CScript() << OP_0 << static_cast<vector<unsigned char> >(pkSingle);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig);\n    BOOST_CHECK(combined == scriptSig);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, scriptSigCopy);\n    BOOST_CHECK(combined == scriptSig);\n\n    \/\/ Hardest case:  Multisig 2-of-3\n    scriptPubKey = GetScriptForMultisig(2, pubkeys);\n    keystore.AddCScript(scriptPubKey);\n    SignSignature(keystore, txFrom, txTo, 0);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty);\n    BOOST_CHECK(combined == scriptSig);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig);\n    BOOST_CHECK(combined == scriptSig);\n\n    \/\/ A couple of partially-signed versions:\n    vector<unsigned char> sig1;\n    uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL);\n    BOOST_CHECK(keys[0].Sign(hash1, sig1));\n    sig1.push_back(SIGHASH_ALL);\n    vector<unsigned char> sig2;\n    uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE);\n    BOOST_CHECK(keys[1].Sign(hash2, sig2));\n    sig2.push_back(SIGHASH_NONE);\n    vector<unsigned char> sig3;\n    uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE);\n    BOOST_CHECK(keys[2].Sign(hash3, sig3));\n    sig3.push_back(SIGHASH_SINGLE);\n\n    \/\/ Not fussy about order (or even existence) of placeholders or signatures:\n    CScript partial1a = CScript() << OP_0 << sig1 << OP_0;\n    CScript partial1b = CScript() << OP_0 << OP_0 << sig1;\n    CScript partial2a = CScript() << OP_0 << sig2;\n    CScript partial2b = CScript() << sig2 << OP_0;\n    CScript partial3a = CScript() << sig3;\n    CScript partial3b = CScript() << OP_0 << OP_0 << sig3;\n    CScript partial3c = CScript() << OP_0 << sig3 << OP_0;\n    CScript complete12 = CScript() << OP_0 << sig1 << sig2;\n    CScript complete13 = CScript() << OP_0 << sig1 << sig3;\n    CScript complete23 = CScript() << OP_0 << sig2 << sig3;\n\n    combined = CombineSignatures(scriptPubKey, txTo, 0, partial1a, partial1b);\n    BOOST_CHECK(combined == partial1a);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, partial1a, partial2a);\n    BOOST_CHECK(combined == complete12);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, partial2a, partial1a);\n    BOOST_CHECK(combined == complete12);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, partial1b, partial2b);\n    BOOST_CHECK(combined == complete12);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial1b);\n    BOOST_CHECK(combined == complete13);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, partial2a, partial3a);\n    BOOST_CHECK(combined == complete23);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial2b);\n    BOOST_CHECK(combined == complete23);\n    combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial3a);\n    BOOST_CHECK(combined == partial3c);\n}\n\nBOOST_AUTO_TEST_CASE(script_standard_push)\n{\n    ScriptError err;\n    for (int i=0; i<67000; i++) {\n        CScript script;\n        script << i;\n        BOOST_CHECK_MESSAGE(script.IsPushOnly(), \"Number \" << i << \" is not pure push.\");\n        BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), \"Number \" << i << \" push is not minimal data.\");\n        BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));\n    }\n\n    for (unsigned int i=0; i<=MAX_SCRIPT_ELEMENT_SIZE; i++) {\n        std::vector<unsigned char> data(i, '\\111');\n        CScript script;\n        script << data;\n        BOOST_CHECK_MESSAGE(script.IsPushOnly(), \"Length \" << i << \" is not pure push.\");\n        BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), \"Length \" << i << \" push is not minimal data.\");\n        BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(script_IsPushOnly_on_invalid_scripts)\n{\n    \/\/ IsPushOnly returns false when given a script containing only pushes that\n    \/\/ are invalid due to truncation. IsPushOnly() is consensus critical\n    \/\/ because P2SH evaluation uses it, although this specific behavior should\n    \/\/ not be consensus critical as the P2SH evaluation would fail first due to\n    \/\/ the invalid push. Still, it doesn't hurt to test it explicitly.\n    static const unsigned char direct[] = { 1 };\n    BOOST_CHECK(!CScript(direct, direct+sizeof(direct)).IsPushOnly());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":50.5784615385,"max_line_length":185,"alphanum_fraction":0.6357626637,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":83174,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/ Copyright (c) 2015-2017 The PIVX developers \n\/\/ Copyright (c) 2018 The Worx developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\/\/\n#include \"Darksend.h\"\n#include \"coincontrol.h\"\n#include \"init.h\"\n#include \"main.h\"\n#include \"masternodeman.h\"\n#include \"script\/sign.h\"\n#include \"Instantx.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n#include \"chainparams.h\"\n#include <boost\/algorithm\/string\/replace.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/filesystem\/fstream.hpp>\n#include <boost\/lexical_cast.hpp>\n\n#include <algorithm>\n#include <boost\/assign\/list_of.hpp>\n#include <openssl\/rand.h>\n\nusing namespace std;\nusing namespace boost;\n\n\/\/ The main object for accessing Darksend\nCDarksendPool DarKsendPool;\n\/\/ A helper object for signing messages from Masternodes\nCDarKsendSigner DarKsendSigner;\n\/\/ The current Darksends in progress on the network\nstd::vector<CDarksendQueue> vecDarksendQueue;\n\/\/ Keep track of the used Masternodes\nstd::vector<CTxIn> vecMasternodesUsed;\n\/\/ Keep track of the scanning errors I've seen\nmap<uint256, CDarksendBroadcastTx> mapDarksendBroadcastTxes;\n\/\/ Keep track of the active Masternode\nCActiveMasternode activeMasternode;\n\n\/* *** BEGIN DARKSEND MAGIC - WORX **********\n    Copyright (c) 2014-2015, Dash Developers\n        eduffield - evan@dashpay.io\n        udjinm6   - udjinm6@dashpay.io\n*\/\n\nvoid CDarksendPool::ProcessMessageDarksend(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)\n{\n    if (fLiteMode) return; \/\/disable all Darksend\/Masternode related functionality\n    if (!masternodeSync.IsBlockchainSynced()) return;\n\n    if (strCommand == \"dsa\") { \/\/Darksend Accept Into Pool\n\n        int errorID;\n\n        if (pfrom->nVersion < ActiveProtocol()) {\n            errorID = ERR_VERSION;\n            LogPrintf(\"dsa -- incompatible version! \\n\");\n            pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n\n            return;\n        }\n\n        if (!fMasterNode) {\n            errorID = ERR_NOT_A_MN;\n            LogPrintf(\"dsa -- not a Masternode! \\n\");\n            pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n\n            return;\n        }\n\n        int nDenom;\n        CTransaction txCollateral;\n        vRecv >> nDenom >> txCollateral;\n\n        CMasternode* pmn = mnodeman.Find(activeMasternode.vin);\n        if (pmn == NULL) {\n            errorID = ERR_MN_LIST;\n            pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n            return;\n        }\n\n        if (sessionUsers == 0) {\n            if (pmn->nLastDsq != 0 &&\n                pmn->nLastDsq + mnodeman.CountEnabled(ActiveProtocol()) \/ 5 > mnodeman.nDsqCount) {\n                LogPrintf(\"dsa -- last dsq too recent, must wait. %s \\n\", pfrom->addr.ToString());\n                errorID = ERR_RECENT;\n                pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n                return;\n            }\n        }\n\n        if (!IsCompatibleWithSession(nDenom, txCollateral, errorID)) {\n            LogPrintf(\"dsa -- not compatible with existing transactions! \\n\");\n            pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n            return;\n        } else {\n            LogPrintf(\"dsa -- is compatible, please submit! \\n\");\n            pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_ACCEPTED, errorID);\n            return;\n        }\n\n    } else if (strCommand == \"dsq\") { \/\/Darksend Queue\n        TRY_LOCK(cs_Darksend, lockRecv);\n        if (!lockRecv) return;\n\n        if (pfrom->nVersion < ActiveProtocol()) {\n            return;\n        }\n\n        CDarksendQueue dsq;\n        vRecv >> dsq;\n\n        CService addr;\n        if (!dsq.GetAddress(addr)) return;\n        if (!dsq.CheckSignature()) return;\n\n        if (dsq.IsExpired()) return;\n\n        CMasternode* pmn = mnodeman.Find(dsq.vin);\n        if (pmn == NULL) return;\n\n        \/\/ if the queue is ready, submit if we can\n        if (dsq.ready) {\n            if (!pSubmittedToMasternode) return;\n            if ((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)addr) {\n                LogPrintf(\"dsq - message doesn't match current Masternode - %s != %s\\n\", pSubmittedToMasternode->addr.ToString(), addr.ToString());\n                return;\n            }\n\n            if (state == POOL_STATUS_QUEUE) {\n                LogPrint(\"Darksend\", \"Darksend queue is ready - %s\\n\", addr.ToString());\n                PrepareDarksendDenominate();\n            }\n        } else {\n            BOOST_FOREACH (CDarksendQueue q, vecDarksendQueue) {\n                if (q.vin == dsq.vin) return;\n            }\n\n            LogPrint(\"Darksend\", \"dsq last %d last2 %d count %d\\n\", pmn->nLastDsq, pmn->nLastDsq + mnodeman.size() \/ 5, mnodeman.nDsqCount);\n            \/\/don't allow a few nodes to dominate the queuing process\n            if (pmn->nLastDsq != 0 &&\n                pmn->nLastDsq + mnodeman.CountEnabled(ActiveProtocol()) \/ 5 > mnodeman.nDsqCount) {\n                LogPrint(\"Darksend\", \"dsq -- Masternode sending too many dsq messages. %s \\n\", pmn->addr.ToString());\n                return;\n            }\n            mnodeman.nDsqCount++;\n            pmn->nLastDsq = mnodeman.nDsqCount;\n            pmn->allowFreeTx = true;\n\n            LogPrint(\"Darksend\", \"dsq - new Darksend queue object - %s\\n\", addr.ToString());\n            vecDarksendQueue.push_back(dsq);\n            dsq.Relay();\n            dsq.time = GetTime();\n        }\n\n    } else if (strCommand == \"dsi\") { \/\/DarKsend vIn\n        int errorID;\n\n        if (pfrom->nVersion < ActiveProtocol()) {\n            LogPrintf(\"dsi -- incompatible version! \\n\");\n            errorID = ERR_VERSION;\n            pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n\n            return;\n        }\n\n        if (!fMasterNode) {\n            LogPrintf(\"dsi -- not a Masternode! \\n\");\n            errorID = ERR_NOT_A_MN;\n            pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n\n            return;\n        }\n\n        std::vector<CTxIn> in;\n        int64_t nAmount;\n        CTransaction txCollateral;\n        std::vector<CTxOut> out;\n        vRecv >> in >> nAmount >> txCollateral >> out;\n\n        \/\/do we have enough users in the current session?\n        if (!IsSessionReady()) {\n            LogPrintf(\"dsi -- session not complete! \\n\");\n            errorID = ERR_SESSION;\n            pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n            return;\n        }\n\n        \/\/do we have the same denominations as the current session?\n        if (!IsCompatibleWithEntries(out)) {\n            LogPrintf(\"dsi -- not compatible with existing transactions! \\n\");\n            errorID = ERR_EXISTING_TX;\n            pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n            return;\n        }\n\n        \/\/check it like a transaction\n        {\n            int64_t nValueIn = 0;\n            int64_t nValueOut = 0;\n            bool missingTx = false;\n\n            CValidationState state;\n            CMutableTransaction tx;\n\n            BOOST_FOREACH (const CTxOut o, out) {\n                nValueOut += o.nValue;\n                tx.vout.push_back(o);\n\n                if (o.scriptPubKey.size() != 25) {\n                    LogPrintf(\"dsi - non-standard pubkey detected! %s\\n\", o.scriptPubKey.ToString());\n                    errorID = ERR_NON_STANDARD_PUBKEY;\n                    pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n                    return;\n                }\n                if (!o.scriptPubKey.IsNormalPaymentScript()) {\n                    LogPrintf(\"dsi - invalid script! %s\\n\", o.scriptPubKey.ToString());\n                    errorID = ERR_INVALID_SCRIPT;\n                    pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n                    return;\n                }\n            }\n\n            BOOST_FOREACH (const CTxIn i, in) {\n                tx.vin.push_back(i);\n\n                LogPrint(\"Darksend\", \"dsi -- tx in %s\\n\", i.ToString());\n\n                CTransaction tx2;\n                uint256 hash;\n                if (GetTransaction(i.prevout.hash, tx2, hash, true)) {\n                    if (tx2.vout.size() > i.prevout.n) {\n                        nValueIn += tx2.vout[i.prevout.n].nValue;\n                    }\n                } else {\n                    missingTx = true;\n                }\n            }\n\n            if (nValueIn > DARKSEND_POOL_MAX) {\n                LogPrintf(\"dsi -- more than Darksend pool max! %s\\n\", tx.ToString());\n                errorID = ERR_MAXIMUM;\n                pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n                return;\n            }\n\n            if (!missingTx) {\n                if (nValueIn - nValueOut > nValueIn * .01) {\n                    LogPrintf(\"dsi -- fees are too high! %s\\n\", tx.ToString());\n                    errorID = ERR_FEES;\n                    pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n                    return;\n                }\n            } else {\n                LogPrintf(\"dsi -- missing input tx! %s\\n\", tx.ToString());\n                errorID = ERR_MISSING_TX;\n                pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n                return;\n            }\n\n            {\n                LOCK(cs_main);\n                if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL, false, true)) {\n                    LogPrintf(\"dsi -- transaction not valid! \\n\");\n                    errorID = ERR_INVALID_TX;\n                    pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n                    return;\n                }\n            }\n        }\n\n        if (AddEntry(in, nAmount, txCollateral, out, errorID)) {\n            pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_ACCEPTED, errorID);\n            Check();\n\n            RelayStatus(sessionID, GetState(), GetEntriesCount(), MASTERNODE_RESET);\n        } else {\n            pfrom->PushMessage(\"dssu\", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID);\n        }\n\n    } else if (strCommand == \"dssu\") { \/\/Darksend status update\n        if (pfrom->nVersion < ActiveProtocol()) {\n            return;\n        }\n\n        if (!pSubmittedToMasternode) return;\n        if ((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)pfrom->addr) {\n            \/\/LogPrintf(\"dssu - message doesn't match current Masternode - %s != %s\\n\", pSubmittedToMasternode->addr.ToString(), pfrom->addr.ToString());\n            return;\n        }\n\n        int sessionIDMessage;\n        int state;\n        int entriesCount;\n        int accepted;\n        int errorID;\n        vRecv >> sessionIDMessage >> state >> entriesCount >> accepted >> errorID;\n\n        LogPrint(\"Darksend\", \"dssu - state: %i entriesCount: %i accepted: %i error: %s \\n\", state, entriesCount, accepted, GetMessageByID(errorID));\n\n        if ((accepted != 1 && accepted != 0) && sessionID != sessionIDMessage) {\n            LogPrintf(\"dssu - message doesn't match current Darksend session %d %d\\n\", sessionID, sessionIDMessage);\n            return;\n        }\n\n        StatusUpdate(state, entriesCount, accepted, errorID, sessionIDMessage);\n\n    } else if (strCommand == \"dss\") { \/\/Darksend Sign Final Tx\n\n        if (pfrom->nVersion < ActiveProtocol()) {\n            return;\n        }\n\n        vector<CTxIn> sigs;\n        vRecv >> sigs;\n\n        bool success = false;\n        int count = 0;\n\n        BOOST_FOREACH (const CTxIn item, sigs) {\n            if (AddScriptSig(item)) success = true;\n            LogPrint(\"Darksend\", \" -- sigs count %d %d\\n\", (int)sigs.size(), count);\n            count++;\n        }\n\n        if (success) {\n            DarKsendPool.Check();\n            RelayStatus(DarKsendPool.sessionID, DarKsendPool.GetState(), DarKsendPool.GetEntriesCount(), MASTERNODE_RESET);\n        }\n    } else if (strCommand == \"dsf\") { \/\/Darksend Final tx\n        if (pfrom->nVersion < ActiveProtocol()) {\n            return;\n        }\n\n        if (!pSubmittedToMasternode) return;\n        if ((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)pfrom->addr) {\n            \/\/LogPrintf(\"dsc - message doesn't match current Masternode - %s != %s\\n\", pSubmittedToMasternode->addr.ToString(), pfrom->addr.ToString());\n            return;\n        }\n\n        int sessionIDMessage;\n        CTransaction txNew;\n        vRecv >> sessionIDMessage >> txNew;\n\n        if (sessionID != sessionIDMessage) {\n            LogPrint(\"Darksend\", \"dsf - message doesn't match current Darksend session %d %d\\n\", sessionID, sessionIDMessage);\n            return;\n        }\n\n        \/\/check to see if input is spent already? (and probably not confirmed)\n        SignFinalTransaction(txNew, pfrom);\n\n    } else if (strCommand == \"dsc\") { \/\/Darksend Complete\n\n        if (pfrom->nVersion < ActiveProtocol()) {\n            return;\n        }\n\n        if (!pSubmittedToMasternode) return;\n        if ((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)pfrom->addr) {\n            \/\/LogPrintf(\"dsc - message doesn't match current Masternode - %s != %s\\n\", pSubmittedToMasternode->addr.ToString(), pfrom->addr.ToString());\n            return;\n        }\n\n        int sessionIDMessage;\n        bool error;\n        int errorID;\n        vRecv >> sessionIDMessage >> error >> errorID;\n\n        if (sessionID != sessionIDMessage) {\n            LogPrint(\"Darksend\", \"dsc - message doesn't match current Darksend session %d %d\\n\", DarKsendPool.sessionID, sessionIDMessage);\n            return;\n        }\n\n        DarKsendPool.CompletedTransaction(error, errorID);\n    }\n}\n\nint randomizeList(int i) { return std::rand() % i; }\n\nvoid CDarksendPool::Reset()\n{\n    cachedLastSuccess = 0;\n    lastNewBlock = 0;\n    txCollateral = CMutableTransaction();\n    vecMasternodesUsed.clear();\n    UnlockCoins();\n    SetNull();\n}\n\nvoid CDarksendPool::SetNull()\n{\n    \/\/ MN side\n    sessionUsers = 0;\n    vecSessionCollateral.clear();\n\n    \/\/ Client side\n    entriesCount = 0;\n    lastEntryAccepted = 0;\n    countEntriesAccepted = 0;\n    sessionFoundMasternode = false;\n\n    \/\/ Both sides\n    state = POOL_STATUS_IDLE;\n    sessionID = 0;\n    sessionDenom = 0;\n    entries.clear();\n    finalTransaction.vin.clear();\n    finalTransaction.vout.clear();\n    lastTimeChanged = GetTimeMillis();\n\n    \/\/ -- seed random number generator (used for ordering output lists)\n    unsigned int seed = 0;\n    RAND_bytes((unsigned char*)&seed, sizeof(seed));\n    std::srand(seed);\n}\n\nbool CDarksendPool::SetCollateralAddress(std::string strAddress)\n{\n    CBitcoinAddress address;\n    if (!address.SetString(strAddress)) {\n        LogPrintf(\"CDarksendPool::SetCollateralAddress - Invalid Darksend collateral address\\n\");\n        return false;\n    }\n    collateralPubKey = GetScriptForDestination(address.Get());\n    return true;\n}\n\n\/\/\n\/\/ Unlock coins after Darksend fails or succeeds\n\/\/\nvoid CDarksendPool::UnlockCoins()\n{\n    while (true) {\n        TRY_LOCK(pwalletMain->cs_wallet, lockWallet);\n        if (!lockWallet) {\n            MilliSleep(50);\n            continue;\n        }\n        BOOST_FOREACH (CTxIn v, lockedCoins)\n            pwalletMain->UnlockCoin(v.prevout);\n        break;\n    }\n\n    lockedCoins.clear();\n}\n\nstd::string CDarksendPool::GetStatus()\n{\n    static int showingDarKsendMessage = 0;\n    showingDarKsendMessage += 10;\n    std::string suffix = \"\";\n\n    if (chainActive.Tip()->nHeight - cachedLastSuccess < minBlockSpacing || !masternodeSync.IsBlockchainSynced()) {\n        return strAutoDenomResult;\n    }\n    switch (state) {\n    case POOL_STATUS_IDLE:\n        return _(\"Darksend is idle.\");\n    case POOL_STATUS_ACCEPTING_ENTRIES:\n        if (entriesCount == 0) {\n            showingDarKsendMessage = 0;\n            return strAutoDenomResult;\n        } else if (lastEntryAccepted == 1) {\n            if (showingDarKsendMessage % 10 > 8) {\n                lastEntryAccepted = 0;\n                showingDarKsendMessage = 0;\n            }\n            return _(\"Darksend request complete:\") + \" \" + _(\"Your transaction was accepted into the pool!\");\n        } else {\n            std::string suffix = \"\";\n            if (showingDarKsendMessage % 70 <= 40)\n                return strprintf(_(\"Submitted following entries to masternode: %u \/ %d\"), entriesCount, GetMaxPoolTransactions());\n            else if (showingDarKsendMessage % 70 <= 50)\n                suffix = \".\";\n            else if (showingDarKsendMessage % 70 <= 60)\n                suffix = \"..\";\n            else if (showingDarKsendMessage % 70 <= 70)\n                suffix = \"...\";\n            return strprintf(_(\"Submitted to masternode, waiting for more entries ( %u \/ %d ) %s\"), entriesCount, GetMaxPoolTransactions(), suffix);\n        }\n    case POOL_STATUS_SIGNING:\n        if (showingDarKsendMessage % 70 <= 40)\n            return _(\"Found enough users, signing ...\");\n        else if (showingDarKsendMessage % 70 <= 50)\n            suffix = \".\";\n        else if (showingDarKsendMessage % 70 <= 60)\n            suffix = \"..\";\n        else if (showingDarKsendMessage % 70 <= 70)\n            suffix = \"...\";\n        return strprintf(_(\"Found enough users, signing ( waiting %s )\"), suffix);\n    case POOL_STATUS_TRANSMISSION:\n        return _(\"Transmitting final transaction.\");\n    case POOL_STATUS_FINALIZE_TRANSACTION:\n        return _(\"Finalizing transaction.\");\n    case POOL_STATUS_ERROR:\n        return _(\"Darksend request incomplete:\") + \" \" + lastMessage + \" \" + _(\"Will retry...\");\n    case POOL_STATUS_SUCCESS:\n        return _(\"Darksend request complete:\") + \" \" + lastMessage;\n    case POOL_STATUS_QUEUE:\n        if (showingDarKsendMessage % 70 <= 30)\n            suffix = \".\";\n        else if (showingDarKsendMessage % 70 <= 50)\n            suffix = \"..\";\n        else if (showingDarKsendMessage % 70 <= 70)\n            suffix = \"...\";\n        return strprintf(_(\"Submitted to masternode, waiting in queue %s\"), suffix);\n        ;\n    default:\n        return strprintf(_(\"Unknown state: id = %u\"), state);\n    }\n}\n\n\/\/\n\/\/ Check the Darksend progress and send client updates if a Masternode\n\/\/\nvoid CDarksendPool::Check()\n{\n    if (fMasterNode) LogPrint(\"Darksend\", \"CDarksendPool::Check() - entries count %lu\\n\", entries.size());\n    \/\/printf(\"CDarksendPool::Check() %d - %d - %d\\n\", state, anonTx.CountEntries(), GetTimeMillis()-lastTimeChanged);\n\n    if (fMasterNode) {\n        LogPrint(\"Darksend\", \"CDarksendPool::Check() - entries count %lu\\n\", entries.size());\n\n        \/\/ If entries is full, then move on to the next phase\n        if (state == POOL_STATUS_ACCEPTING_ENTRIES && (int)entries.size() >= GetMaxPoolTransactions()) {\n            LogPrint(\"Darksend\", \"CDarksendPool::Check() -- TRYING TRANSACTION \\n\");\n            UpdateState(POOL_STATUS_FINALIZE_TRANSACTION);\n        }\n    }\n\n    \/\/ create the finalized transaction for distribution to the clients\n    if (state == POOL_STATUS_FINALIZE_TRANSACTION) {\n        LogPrint(\"Darksend\", \"CDarksendPool::Check() -- FINALIZE TRANSACTIONS\\n\");\n        UpdateState(POOL_STATUS_SIGNING);\n\n        if (fMasterNode) {\n            CMutableTransaction txNew;\n\n            \/\/ make our new transaction\n            for (unsigned int i = 0; i < entries.size(); i++) {\n                BOOST_FOREACH (const CTxOut& v, entries[i].vout)\n                    txNew.vout.push_back(v);\n\n                BOOST_FOREACH (const CTxDSIn& s, entries[i].sev)\n                    txNew.vin.push_back(s);\n            }\n\n            \/\/ shuffle the outputs for improved anonymity\n            std::random_shuffle(txNew.vin.begin(), txNew.vin.end(), randomizeList);\n            std::random_shuffle(txNew.vout.begin(), txNew.vout.end(), randomizeList);\n\n\n            LogPrint(\"Darksend\", \"Transaction 1: %s\\n\", txNew.ToString());\n            finalTransaction = txNew;\n\n            \/\/ request signatures from clients\n            RelayFinalTransaction(sessionID, finalTransaction);\n        }\n    }\n\n    \/\/ If we have all of the signatures, try to compile the transaction\n    if (fMasterNode && state == POOL_STATUS_SIGNING && SignaturesComplete()) {\n        LogPrint(\"Darksend\", \"CDarksendPool::Check() -- SIGNING\\n\");\n        UpdateState(POOL_STATUS_TRANSMISSION);\n\n        CheckFinalTransaction();\n    }\n\n    \/\/ reset if we're here for 10 seconds\n    if ((state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) && GetTimeMillis() - lastTimeChanged >= 10000) {\n        LogPrint(\"Darksend\", \"CDarksendPool::Check() -- timeout, RESETTING\\n\");\n        UnlockCoins();\n        SetNull();\n        if (fMasterNode) RelayStatus(sessionID, GetState(), GetEntriesCount(), MASTERNODE_RESET);\n    }\n}\n\nvoid CDarksendPool::CheckFinalTransaction()\n{\n    if (!fMasterNode) return; \/\/ check and relay final tx only on masternode\n\n    CWalletTx txNew = CWalletTx(pwalletMain, finalTransaction);\n\n    LOCK2(cs_main, pwalletMain->cs_wallet);\n    {\n        LogPrint(\"Darksend\", \"Transaction 2: %s\\n\", txNew.ToString());\n\n        \/\/ See if the transaction is valid\n        if (!txNew.AcceptToMemoryPool(false, true, true)) {\n            LogPrintf(\"CDarksendPool::Check() - CommitTransaction : Error: Transaction not valid\\n\");\n            SetNull();\n\n            \/\/ not much we can do in this case\n            UpdateState(POOL_STATUS_ACCEPTING_ENTRIES);\n            RelayCompletedTransaction(sessionID, true, ERR_INVALID_TX);\n            return;\n        }\n\n        LogPrintf(\"CDarksendPool::Check() -- IS MASTER -- TRANSMITTING DARKSEND\\n\");\n\n        \/\/ sign a message\n\n        int64_t sigTime = GetAdjustedTime();\n        std::string strMessage = txNew.GetHash().ToString() + boost::lexical_cast<std::string>(sigTime);\n        std::string strError = \"\";\n        std::vector<unsigned char> vchSig;\n        CKey key2;\n        CPubKey pubkey2;\n\n        if (!DarKsendSigner.SetKey(strMasterNodePrivKey, strError, key2, pubkey2)) {\n            LogPrintf(\"CDarksendPool::Check() - ERROR: Invalid Masternodeprivkey: '%s'\\n\", strError);\n            return;\n        }\n\n        if (!DarKsendSigner.SignMessage(strMessage, strError, vchSig, key2)) {\n            LogPrintf(\"CDarksendPool::Check() - Sign message failed\\n\");\n            return;\n        }\n\n        if (!DarKsendSigner.VerifyMessage(pubkey2, vchSig, strMessage, strError)) {\n            LogPrintf(\"CDarksendPool::Check() - Verify message failed\\n\");\n            return;\n        }\n\n        if (!mapDarksendBroadcastTxes.count(txNew.GetHash())) {\n            CDarksendBroadcastTx dstx;\n            dstx.tx = txNew;\n            dstx.vin = activeMasternode.vin;\n            dstx.vchSig = vchSig;\n            dstx.sigTime = sigTime;\n\n            mapDarksendBroadcastTxes.insert(make_pair(txNew.GetHash(), dstx));\n        }\n\n        CInv inv(MSG_DSTX, txNew.GetHash());\n        RelayInv(inv);\n\n        \/\/ Tell the clients it was successful\n        RelayCompletedTransaction(sessionID, false, MSG_SUCCESS);\n\n        \/\/ Randomly charge clients\n        ChargeRandomFees();\n\n        \/\/ Reset\n        LogPrint(\"Darksend\", \"CDarksendPool::Check() -- COMPLETED -- RESETTING\\n\");\n        SetNull();\n        RelayStatus(sessionID, GetState(), GetEntriesCount(), MASTERNODE_RESET);\n    }\n}\n\n\/\/\n\/\/ Charge clients a fee if they're abusive\n\/\/\n\/\/ Why bother? Darksend uses collateral to ensure abuse to the process is kept to a minimum.\n\/\/ The submission and signing stages in Darksend are completely separate. In the cases where\n\/\/ a client submits a transaction then refused to sign, there must be a cost. Otherwise they\n\/\/ would be able to do this over and over again and bring the mixing to a hault.\n\/\/\n\/\/ How does this work? Messages to Masternodes come in via \"dsi\", these require a valid collateral\n\/\/ transaction for the client to be able to enter the pool. This transaction is kept by the Masternode\n\/\/ until the transaction is either complete or fails.\n\/\/\nvoid CDarksendPool::ChargeFees()\n{\n    if (!fMasterNode) return;\n\n    \/\/we don't need to charge collateral for every offence.\n    int offences = 0;\n    int r = rand() % 100;\n    if (r > 33) return;\n\n    if (state == POOL_STATUS_ACCEPTING_ENTRIES) {\n        BOOST_FOREACH (const CTransaction& txCollateral, vecSessionCollateral) {\n            bool found = false;\n            BOOST_FOREACH (const CDarKsendEntry& v, entries) {\n                if (v.collateral == txCollateral) {\n                    found = true;\n                }\n            }\n\n            \/\/ This queue entry didn't send us the promised transaction\n            if (!found) {\n                LogPrintf(\"CDarksendPool::ChargeFees -- found uncooperative node (didn't send transaction). Found offence.\\n\");\n                offences++;\n            }\n        }\n    }\n\n    if (state == POOL_STATUS_SIGNING) {\n        \/\/ who didn't sign?\n        BOOST_FOREACH (const CDarKsendEntry v, entries) {\n            BOOST_FOREACH (const CTxDSIn s, v.sev) {\n                if (!s.fHasSig) {\n                    LogPrintf(\"CDarksendPool::ChargeFees -- found uncooperative node (didn't sign). Found offence\\n\");\n                    offences++;\n                }\n            }\n        }\n    }\n\n    r = rand() % 100;\n    int target = 0;\n\n    \/\/mostly offending?\n    if (offences >= Params().PoolMaxTransactions() - 1 && r > 33) return;\n\n    \/\/everyone is an offender? That's not right\n    if (offences >= Params().PoolMaxTransactions()) return;\n\n    \/\/charge one of the offenders randomly\n    if (offences > 1) target = 50;\n\n    \/\/pick random client to charge\n    r = rand() % 100;\n\n    if (state == POOL_STATUS_ACCEPTING_ENTRIES) {\n        BOOST_FOREACH (const CTransaction& txCollateral, vecSessionCollateral) {\n            bool found = false;\n            BOOST_FOREACH (const CDarKsendEntry& v, entries) {\n                if (v.collateral == txCollateral) {\n                    found = true;\n                }\n            }\n\n            \/\/ This queue entry didn't send us the promised transaction\n            if (!found && r > target) {\n                LogPrintf(\"CDarksendPool::ChargeFees -- found uncooperative node (didn't send transaction). charging fees.\\n\");\n\n                CWalletTx wtxCollateral = CWalletTx(pwalletMain, txCollateral);\n\n                \/\/ Broadcast\n                if (!wtxCollateral.AcceptToMemoryPool(true)) {\n                    \/\/ This must not fail. The transaction has already been signed and recorded.\n                    LogPrintf(\"CDarksendPool::ChargeFees() : Error: Transaction not valid\");\n                }\n                wtxCollateral.RelayWalletTransaction();\n                return;\n            }\n        }\n    }\n\n    if (state == POOL_STATUS_SIGNING) {\n        \/\/ who didn't sign?\n        BOOST_FOREACH (const CDarKsendEntry v, entries) {\n            BOOST_FOREACH (const CTxDSIn s, v.sev) {\n                if (!s.fHasSig && r > target) {\n                    LogPrintf(\"CDarksendPool::ChargeFees -- found uncooperative node (didn't sign). charging fees.\\n\");\n\n                    CWalletTx wtxCollateral = CWalletTx(pwalletMain, v.collateral);\n\n                    \/\/ Broadcast\n                    if (!wtxCollateral.AcceptToMemoryPool(false)) {\n                        \/\/ This must not fail. The transaction has already been signed and recorded.\n                        LogPrintf(\"CDarksendPool::ChargeFees() : Error: Transaction not valid\");\n                    }\n                    wtxCollateral.RelayWalletTransaction();\n                    return;\n                }\n            }\n        }\n    }\n}\n\n\/\/ charge the collateral randomly\n\/\/  - Darksend is completely free, to pay miners we randomly pay the collateral of users.\nvoid CDarksendPool::ChargeRandomFees()\n{\n    if (fMasterNode) {\n        int i = 0;\n\n        BOOST_FOREACH (const CTransaction& txCollateral, vecSessionCollateral) {\n            int r = rand() % 100;\n\n            \/*\n                Collateral Fee Charges:\n\n                Being that Darksend has \"no fees\" we need to have some kind of cost associated\n                with using it to stop abuse. Otherwise it could serve as an attack vector and\n                allow endless transaction that would bloat WORX and make it unusable. To\n                stop these kinds of attacks 1 in 10 successful transactions are charged. This\n                adds up to a cost of 0.001 WORX per transaction on average.\n            *\/\n            if (r <= 10) {\n                LogPrintf(\"CDarksendPool::ChargeRandomFees -- charging random fees. %u\\n\", i);\n\n                CWalletTx wtxCollateral = CWalletTx(pwalletMain, txCollateral);\n\n                \/\/ Broadcast\n                if (!wtxCollateral.AcceptToMemoryPool(true)) {\n                    \/\/ This must not fail. The transaction has already been signed and recorded.\n                    LogPrintf(\"CDarksendPool::ChargeRandomFees() : Error: Transaction not valid\");\n                }\n                wtxCollateral.RelayWalletTransaction();\n            }\n        }\n    }\n}\n\n\/\/\n\/\/ Check for various timeouts (queue objects, Darksend, etc)\n\/\/\nvoid CDarksendPool::CheckTimeout()\n{\n    if (!fEnableDarksend && !fMasterNode) return;\n\n    \/\/ catching hanging sessions\n    if (!fMasterNode) {\n        switch (state) {\n        case POOL_STATUS_TRANSMISSION:\n            LogPrint(\"Darksend\", \"CDarksendPool::CheckTimeout() -- Session complete -- Running Check()\\n\");\n            Check();\n            break;\n        case POOL_STATUS_ERROR:\n            LogPrint(\"Darksend\", \"CDarksendPool::CheckTimeout() -- Pool error -- Running Check()\\n\");\n            Check();\n            break;\n        case POOL_STATUS_SUCCESS:\n            LogPrint(\"Darksend\", \"CDarksendPool::CheckTimeout() -- Pool success -- Running Check()\\n\");\n            Check();\n            break;\n        }\n    }\n\n    \/\/ check Darksend queue objects for timeouts\n    int c = 0;\n    vector<CDarksendQueue>::iterator it = vecDarksendQueue.begin();\n    while (it != vecDarksendQueue.end()) {\n        if ((*it).IsExpired()) {\n            LogPrint(\"Darksend\", \"CDarksendPool::CheckTimeout() : Removing expired queue entry - %d\\n\", c);\n            it = vecDarksendQueue.erase(it);\n        } else\n            ++it;\n        c++;\n    }\n\n    int addLagTime = 0;\n    if (!fMasterNode) addLagTime = 10000; \/\/if we're the client, give the server a few extra seconds before resetting.\n\n    if (state == POOL_STATUS_ACCEPTING_ENTRIES || state == POOL_STATUS_QUEUE) {\n        c = 0;\n\n        \/\/ check for a timeout and reset if needed\n        vector<CDarKsendEntry>::iterator it2 = entries.begin();\n        while (it2 != entries.end()) {\n            if ((*it2).IsExpired()) {\n                LogPrint(\"Darksend\", \"CDarksendPool::CheckTimeout() : Removing expired entry - %d\\n\", c);\n                it2 = entries.erase(it2);\n                if (entries.size() == 0) {\n                    UnlockCoins();\n                    SetNull();\n                }\n                if (fMasterNode) {\n                    RelayStatus(sessionID, GetState(), GetEntriesCount(), MASTERNODE_RESET);\n                }\n            } else\n                ++it2;\n            c++;\n        }\n\n        if (GetTimeMillis() - lastTimeChanged >= (DARKSEND_QUEUE_TIMEOUT * 1000) + addLagTime) {\n            UnlockCoins();\n            SetNull();\n        }\n    } else if (GetTimeMillis() - lastTimeChanged >= (DARKSEND_QUEUE_TIMEOUT * 1000) + addLagTime) {\n        LogPrint(\"Darksend\", \"CDarksendPool::CheckTimeout() -- Session timed out (%ds) -- resetting\\n\", DARKSEND_QUEUE_TIMEOUT);\n        UnlockCoins();\n        SetNull();\n\n        UpdateState(POOL_STATUS_ERROR);\n        lastMessage = _(\"Session timed out.\");\n    }\n\n    if (state == POOL_STATUS_SIGNING && GetTimeMillis() - lastTimeChanged >= (DARKSEND_SIGNING_TIMEOUT * 1000) + addLagTime) {\n        LogPrint(\"Darksend\", \"CDarksendPool::CheckTimeout() -- Session timed out (%ds) -- restting\\n\", DARKSEND_SIGNING_TIMEOUT);\n        ChargeFees();\n        UnlockCoins();\n        SetNull();\n\n        UpdateState(POOL_STATUS_ERROR);\n        lastMessage = _(\"Signing timed out.\");\n    }\n}\n\n\/\/\n\/\/ Check for complete queue\n\/\/\nvoid CDarksendPool::CheckForCompleteQueue()\n{\n    if (!fEnableDarksend && !fMasterNode) return;\n\n    \/* Check to see if we're ready for submissions from clients *\/\n    \/\/\n    \/\/ After receiving multiple dsa messages, the queue will switch to \"accepting entries\"\n    \/\/ which is the active state right before merging the transaction\n    \/\/\n    if (state == POOL_STATUS_QUEUE && sessionUsers == GetMaxPoolTransactions()) {\n        UpdateState(POOL_STATUS_ACCEPTING_ENTRIES);\n\n        CDarksendQueue dsq;\n        dsq.nDenom = sessionDenom;\n        dsq.vin = activeMasternode.vin;\n        dsq.time = GetTime();\n        dsq.ready = true;\n        dsq.Sign();\n        dsq.Relay();\n    }\n}\n\n\/\/ check to see if the signature is valid\nbool CDarksendPool::SignatureValid(const CScript& newSig, const CTxIn& newVin)\n{\n    CMutableTransaction txNew;\n    txNew.vin.clear();\n    txNew.vout.clear();\n\n    int found = -1;\n    CScript sigPubKey = CScript();\n    unsigned int i = 0;\n\n    BOOST_FOREACH (CDarKsendEntry& e, entries) {\n        BOOST_FOREACH (const CTxOut& out, e.vout)\n            txNew.vout.push_back(out);\n\n        BOOST_FOREACH (const CTxDSIn& s, e.sev) {\n            txNew.vin.push_back(s);\n\n            if (s == newVin) {\n                found = i;\n                sigPubKey = s.prevPubKey;\n            }\n            i++;\n        }\n    }\n\n    if (found >= 0) { \/\/might have to do this one input at a time?\n        int n = found;\n        txNew.vin[n].scriptSig = newSig;\n        LogPrint(\"Darksend\", \"CDarksendPool::SignatureValid() - Sign with sig %s\\n\", newSig.ToString().substr(0, 24));\n        if (!VerifyScript(txNew.vin[n].scriptSig, sigPubKey, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, MutableTransactionSignatureChecker(&txNew, n))) {\n            LogPrint(\"Darksend\", \"CDarksendPool::SignatureValid() - Signing - Error signing input %u\\n\", n);\n            return false;\n        }\n    }\n\n    LogPrint(\"Darksend\", \"CDarksendPool::SignatureValid() - Signing - Successfully validated input\\n\");\n    return true;\n}\n\n\/\/ check to make sure the collateral provided by the client is valid\nbool CDarksendPool::IsCollateralValid(const CTransaction& txCollateral)\n{\n    if (txCollateral.vout.size() < 1) return false;\n    if (txCollateral.nLockTime != 0) return false;\n\n    int64_t nValueIn = 0;\n    int64_t nValueOut = 0;\n    bool missingTx = false;\n\n    BOOST_FOREACH (const CTxOut o, txCollateral.vout) {\n        nValueOut += o.nValue;\n\n        if (!o.scriptPubKey.IsNormalPaymentScript()) {\n            LogPrintf(\"CDarksendPool::IsCollateralValid - Invalid Script %s\\n\", txCollateral.ToString());\n            return false;\n        }\n    }\n\n    BOOST_FOREACH (const CTxIn i, txCollateral.vin) {\n        CTransaction tx2;\n        uint256 hash;\n        if (GetTransaction(i.prevout.hash, tx2, hash, true)) {\n            if (tx2.vout.size() > i.prevout.n) {\n                nValueIn += tx2.vout[i.prevout.n].nValue;\n            }\n        } else {\n            missingTx = true;\n        }\n    }\n\n    if (missingTx) {\n        LogPrint(\"Darksend\", \"CDarksendPool::IsCollateralValid - Unknown inputs in collateral transaction - %s\\n\", txCollateral.ToString());\n        return false;\n    }\n\n    \/\/collateral transactions are required to pay out DARKSEND_COLLATERAL as a fee to the miners\n    if (nValueIn - nValueOut < DARKSEND_COLLATERAL) {\n        LogPrint(\"Darksend\", \"CDarksendPool::IsCollateralValid - did not include enough fees in transaction %d\\n%s\\n\", nValueOut - nValueIn, txCollateral.ToString());\n        return false;\n    }\n\n    LogPrint(\"Darksend\", \"CDarksendPool::IsCollateralValid %s\\n\", txCollateral.ToString());\n\n    {\n        LOCK(cs_main);\n        CValidationState state;\n        if (!AcceptableInputs(mempool, state, txCollateral, true, NULL)) {\n            if (fDebug) LogPrintf(\"CDarksendPool::IsCollateralValid - didn't pass IsAcceptable\\n\");\n            return false;\n        }\n    }\n\n    return true;\n}\n\n\n\/\/\n\/\/ Add a clients transaction to the pool\n\/\/\nbool CDarksendPool::AddEntry(const std::vector<CTxIn>& newInput, const int64_t& nAmount, const CTransaction& txCollateral, const std::vector<CTxOut>& newOutput, int& errorID)\n{\n    if (!fMasterNode) return false;\n\n    BOOST_FOREACH (CTxIn in, newInput) {\n        if (in.prevout.IsNull() || nAmount < 0) {\n            LogPrint(\"Darksend\", \"CDarksendPool::AddEntry - input not valid!\\n\");\n            errorID = ERR_INVALID_INPUT;\n            sessionUsers--;\n            return false;\n        }\n    }\n\n    if (!IsCollateralValid(txCollateral)) {\n        LogPrint(\"Darksend\", \"CDarksendPool::AddEntry - collateral not valid!\\n\");\n        errorID = ERR_INVALID_COLLATERAL;\n        sessionUsers--;\n        return false;\n    }\n\n    if ((int)entries.size() >= GetMaxPoolTransactions()) {\n        LogPrint(\"Darksend\", \"CDarksendPool::AddEntry - entries is full!\\n\");\n        errorID = ERR_ENTRIES_FULL;\n        sessionUsers--;\n        return false;\n    }\n\n    BOOST_FOREACH (CTxIn in, newInput) {\n        LogPrint(\"Darksend\", \"looking for vin -- %s\\n\", in.ToString());\n        BOOST_FOREACH (const CDarKsendEntry& v, entries) {\n            BOOST_FOREACH (const CTxDSIn& s, v.sev) {\n                if ((CTxIn)s == in) {\n                    LogPrint(\"Darksend\", \"CDarksendPool::AddEntry - found in vin\\n\");\n                    errorID = ERR_ALREADY_HAVE;\n                    sessionUsers--;\n                    return false;\n                }\n            }\n        }\n    }\n\n    CDarKsendEntry v;\n    v.Add(newInput, nAmount, txCollateral, newOutput);\n    entries.push_back(v);\n\n    LogPrint(\"Darksend\", \"CDarksendPool::AddEntry -- adding %s\\n\", newInput[0].ToString());\n    errorID = MSG_ENTRIES_ADDED;\n\n    return true;\n}\n\nbool CDarksendPool::AddScriptSig(const CTxIn& newVin)\n{\n    LogPrint(\"Darksend\", \"CDarksendPool::AddScriptSig -- new sig  %s\\n\", newVin.scriptSig.ToString().substr(0, 24));\n\n\n    BOOST_FOREACH (const CDarKsendEntry& v, entries) {\n        BOOST_FOREACH (const CTxDSIn& s, v.sev) {\n            if (s.scriptSig == newVin.scriptSig) {\n                LogPrint(\"Darksend\", \"CDarksendPool::AddScriptSig - already exists\\n\");\n                return false;\n            }\n        }\n    }\n\n    if (!SignatureValid(newVin.scriptSig, newVin)) {\n        LogPrint(\"Darksend\", \"CDarksendPool::AddScriptSig - Invalid Sig\\n\");\n        return false;\n    }\n\n    LogPrint(\"Darksend\", \"CDarksendPool::AddScriptSig -- sig %s\\n\", newVin.ToString());\n\n    BOOST_FOREACH (CTxIn& vin, finalTransaction.vin) {\n        if (newVin.prevout == vin.prevout && vin.nSequence == newVin.nSequence) {\n            vin.scriptSig = newVin.scriptSig;\n            vin.prevPubKey = newVin.prevPubKey;\n            LogPrint(\"Darksend\", \"CDarKsendPool::AddScriptSig -- adding to finalTransaction  %s\\n\", newVin.scriptSig.ToString().substr(0, 24));\n        }\n    }\n    for (unsigned int i = 0; i < entries.size(); i++) {\n        if (entries[i].AddSig(newVin)) {\n            LogPrint(\"Darksend\", \"CDarKsendPool::AddScriptSig -- adding  %s\\n\", newVin.scriptSig.ToString().substr(0, 24));\n            return true;\n        }\n    }\n\n    LogPrintf(\"CDarksendPool::AddScriptSig -- Couldn't set sig!\\n\");\n    return false;\n}\n\n\/\/ Check to make sure everything is signed\nbool CDarksendPool::SignaturesComplete()\n{\n    BOOST_FOREACH (const CDarKsendEntry& v, entries) {\n        BOOST_FOREACH (const CTxDSIn& s, v.sev) {\n            if (!s.fHasSig) return false;\n        }\n    }\n    return true;\n}\n\n\/\/\n\/\/ Execute a Darksend denomination via a Masternode.\n\/\/ This is only ran from clients\n\/\/\nvoid CDarksendPool::SendDarksendDenominate(std::vector<CTxIn>& vin, std::vector<CTxOut>& vout, int64_t amount)\n{\n    if (fMasterNode) {\n        LogPrintf(\"CDarksendPool::SendDarksendDenominate() - Darksend from a Masternode is not supported currently.\\n\");\n        return;\n    }\n\n    if (txCollateral == CMutableTransaction()) {\n        LogPrintf(\"CDarksendPool:SendDarksendDenominate() - Darksend collateral not set\");\n        return;\n    }\n\n    \/\/ lock the funds we're going to use\n    BOOST_FOREACH (CTxIn in, txCollateral.vin)\n        lockedCoins.push_back(in);\n\n    BOOST_FOREACH (CTxIn in, vin)\n        lockedCoins.push_back(in);\n\n    \/\/BOOST_FOREACH(CTxOut o, vout)\n    \/\/    LogPrintf(\" vout - %s\\n\", o.ToString());\n\n\n    \/\/ we should already be connected to a Masternode\n    if (!sessionFoundMasternode) {\n        LogPrintf(\"CDarksendPool::SendDarksendDenominate() - No Masternode has been selected yet.\\n\");\n        UnlockCoins();\n        SetNull();\n        return;\n    }\n\n    if (!CheckDiskSpace()) {\n        UnlockCoins();\n        SetNull();\n        fEnableDarksend = false;\n        LogPrintf(\"CDarksendPool::SendDarksendDenominate() - Not enough disk space, disabling Darksend.\\n\");\n        return;\n    }\n\n    UpdateState(POOL_STATUS_ACCEPTING_ENTRIES);\n\n    LogPrintf(\"CDarksendPool::SendDarksendDenominate() - Added transaction to pool.\\n\");\n\n    ClearLastMessage();\n\n    \/\/check it against the memory pool to make sure it's valid\n    {\n        int64_t nValueOut = 0;\n\n        CValidationState state;\n        CMutableTransaction tx;\n\n        BOOST_FOREACH (const CTxOut& o, vout) {\n            nValueOut += o.nValue;\n            tx.vout.push_back(o);\n        }\n\n        BOOST_FOREACH (const CTxIn& i, vin) {\n            tx.vin.push_back(i);\n\n            LogPrint(\"Darksend\", \"dsi -- tx in %s\\n\", i.ToString());\n        }\n\n        LogPrintf(\"Submitting tx %s\\n\", tx.ToString());\n\n        while (true) {\n            TRY_LOCK(cs_main, lockMain);\n            if (!lockMain) {\n                MilliSleep(50);\n                continue;\n            }\n            if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL, false, true)) {\n                LogPrintf(\"dsi -- transaction not valid! %s \\n\", tx.ToString());\n                UnlockCoins();\n                SetNull();\n                return;\n            }\n            break;\n        }\n    }\n\n    \/\/ store our entry for later use\n    CDarKsendEntry e;\n    e.Add(vin, amount, txCollateral, vout);\n    entries.push_back(e);\n\n    RelayIn(entries[0].sev, entries[0].amount, txCollateral, entries[0].vout);\n    Check();\n}\n\n\/\/ Incoming message from Masternode updating the progress of Darksend\n\/\/    newAccepted:  -1 mean's it'n not a \"transaction accepted\/not accepted\" message, just a standard update\n\/\/                  0 means transaction was not accepted\n\/\/                  1 means transaction was accepted\n\nbool CDarksendPool::StatusUpdate(int newState, int newEntriesCount, int newAccepted, int& errorID, int newSessionID)\n{\n    if (fMasterNode) return false;\n    if (state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) return false;\n\n    UpdateState(newState);\n    entriesCount = newEntriesCount;\n\n    if (errorID != MSG_NOERR) strAutoDenomResult = _(\"Masternode:\") + \" \" + GetMessageByID(errorID);\n\n    if (newAccepted != -1) {\n        lastEntryAccepted = newAccepted;\n        countEntriesAccepted += newAccepted;\n        if (newAccepted == 0) {\n            UpdateState(POOL_STATUS_ERROR);\n            lastMessage = GetMessageByID(errorID);\n        }\n\n        if (newAccepted == 1 && newSessionID != 0) {\n            sessionID = newSessionID;\n            LogPrintf(\"CDarksendPool::StatusUpdate - set sessionID to %d\\n\", sessionID);\n            sessionFoundMasternode = true;\n        }\n    }\n\n    if (newState == POOL_STATUS_ACCEPTING_ENTRIES) {\n        if (newAccepted == 1) {\n            LogPrintf(\"CDarksendPool::StatusUpdate - entry accepted! \\n\");\n            sessionFoundMasternode = true;\n            \/\/wait for other users. Masternode will report when ready\n            UpdateState(POOL_STATUS_QUEUE);\n        } else if (newAccepted == 0 && sessionID == 0 && !sessionFoundMasternode) {\n            LogPrintf(\"CDarksendPool::StatusUpdate - entry not accepted by Masternode \\n\");\n            UnlockCoins();\n            UpdateState(POOL_STATUS_ACCEPTING_ENTRIES);\n            DoAutomaticDenominating(); \/\/try another Masternode\n        }\n        if (sessionFoundMasternode) return true;\n    }\n\n    return true;\n}\n\n\/\/\n\/\/ After we receive the finalized transaction from the Masternode, we must\n\/\/ check it to make sure it's what we want, then sign it if we agree.\n\/\/ If we refuse to sign, it's possible we'll be charged collateral\n\/\/\nbool CDarksendPool::SignFinalTransaction(CTransaction& finalTransactionNew, CNode* node)\n{\n    if (fMasterNode) return false;\n\n    finalTransaction = finalTransactionNew;\n    LogPrintf(\"CDarksendPool::SignFinalTransaction %s\", finalTransaction.ToString());\n\n    vector<CTxIn> sigs;\n\n    \/\/make sure my inputs\/outputs are present, otherwise refuse to sign\n    BOOST_FOREACH (const CDarKsendEntry e, entries) {\n        BOOST_FOREACH (const CTxDSIn s, e.sev) {\n            \/* Sign my transaction and all outputs *\/\n            int mine = -1;\n            CScript prevPubKey = CScript();\n            CTxIn vin = CTxIn();\n\n            for (unsigned int i = 0; i < finalTransaction.vin.size(); i++) {\n                if (finalTransaction.vin[i] == s) {\n                    mine = i;\n                    prevPubKey = s.prevPubKey;\n                    vin = s;\n                }\n            }\n\n            if (mine >= 0) { \/\/might have to do this one input at a time?\n                int foundOutputs = 0;\n                CAmount nValue1 = 0;\n                CAmount nValue2 = 0;\n\n                for (unsigned int i = 0; i < finalTransaction.vout.size(); i++) {\n                    BOOST_FOREACH (const CTxOut& o, e.vout) {\n                        if (finalTransaction.vout[i] == o) {\n                            foundOutputs++;\n                            nValue1 += finalTransaction.vout[i].nValue;\n                        }\n                    }\n                }\n\n                BOOST_FOREACH (const CTxOut o, e.vout)\n                    nValue2 += o.nValue;\n\n                int targetOuputs = e.vout.size();\n                if (foundOutputs < targetOuputs || nValue1 != nValue2) {\n                    \/\/ in this case, something went wrong and we'll refuse to sign. It's possible we'll be charged collateral. But that's\n                    \/\/ better then signing if the transaction doesn't look like what we wanted.\n                    LogPrintf(\"CDarksendPool::Sign - My entries are not correct! Refusing to sign. %d entries %d target. \\n\", foundOutputs, targetOuputs);\n                    UnlockCoins();\n                    SetNull();\n\n                    return false;\n                }\n\n                const CKeyStore& keystore = *pwalletMain;\n\n                LogPrint(\"Darksend\", \"CDarksendPool::Sign - Signing my input %i\\n\", mine);\n                if (!SignSignature(keystore, prevPubKey, finalTransaction, mine, int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))) { \/\/ changes scriptSig\n                    LogPrint(\"Darksend\", \"CDarksendPool::Sign - Unable to sign my own transaction! \\n\");\n                    \/\/ not sure what to do here, it will timeout...?\n                }\n\n                sigs.push_back(finalTransaction.vin[mine]);\n                LogPrint(\"Darksend\", \" -- dss %d %d %s\\n\", mine, (int)sigs.size(), finalTransaction.vin[mine].scriptSig.ToString());\n            }\n        }\n\n        LogPrint(\"Darksend\", \"CDarksendPool::Sign - txNew:\\n%s\", finalTransaction.ToString());\n    }\n\n    \/\/ push all of our signatures to the Masternode\n    if (sigs.size() > 0 && node != NULL)\n        node->PushMessage(\"dss\", sigs);\n\n\n    return true;\n}\n\nvoid CDarksendPool::NewBlock()\n{\n    LogPrint(\"Darksend\", \"CDarksendPool::NewBlock \\n\");\n\n    \/\/we we're processing lots of blocks, we'll just leave\n    if (GetTime() - lastNewBlock < 10) return;\n    lastNewBlock = GetTime();\n\n    DarKsendPool.CheckTimeout();\n}\n\n\/\/ Darksend transaction was completed (failed or successful)\nvoid CDarksendPool::CompletedTransaction(bool error, int errorID)\n{\n    if (fMasterNode) return;\n\n    if (error) {\n        LogPrintf(\"CompletedTransaction -- error \\n\");\n        UpdateState(POOL_STATUS_ERROR);\n\n        Check();\n        UnlockCoins();\n        SetNull();\n    } else {\n        LogPrintf(\"CompletedTransaction -- success \\n\");\n        UpdateState(POOL_STATUS_SUCCESS);\n\n        UnlockCoins();\n        SetNull();\n\n        \/\/ To avoid race conditions, we'll only let DS run once per block\n        cachedLastSuccess = chainActive.Tip()->nHeight;\n    }\n    lastMessage = GetMessageByID(errorID);\n}\n\nvoid CDarksendPool::ClearLastMessage()\n{\n    lastMessage = \"\";\n}\n\n\/\/\n\/\/ Passively run Darksend in the background to anonymize funds based on the given configuration.\n\/\/\n\/\/ This does NOT run by default for daemons, only for QT.\n\/\/\nbool CDarksendPool::DoAutomaticDenominating(bool fDryRun)\n{\n    if (!fEnableDarksend) return false;\n    if (fMasterNode) return false;\n    if (state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) return false;\n    if (GetEntriesCount() > 0) {\n        strAutoDenomResult = _(\"Mixing in progress...\");\n        return false;\n    }\n\n    TRY_LOCK(cs_Darksend, lockDS);\n    if (!lockDS) {\n        strAutoDenomResult = _(\"Lock is already in place.\");\n        return false;\n    }\n\n    if (!masternodeSync.IsBlockchainSynced()) {\n        strAutoDenomResult = _(\"Can't mix while sync in progress.\");\n        return false;\n    }\n\n    if (!fDryRun && pwalletMain->IsLocked()) {\n        strAutoDenomResult = _(\"Wallet is locked.\");\n        return false;\n    }\n\n    if (chainActive.Tip()->nHeight - cachedLastSuccess < minBlockSpacing) {\n        LogPrintf(\"CDarksendPool::DoAutomaticDenominating - Last successful Darksend action was too recent\\n\");\n        strAutoDenomResult = _(\"Last successful Darksend action was too recent.\");\n        return false;\n    }\n\n    if (mnodeman.size() == 0) {\n        LogPrint(\"Darksend\", \"CDarksendPool::DoAutomaticDenominating - No Masternodes detected\\n\");\n        strAutoDenomResult = _(\"No Masternodes detected.\");\n        return false;\n    }\n\n    \/\/ ** find the coins we'll use\n    std::vector<CTxIn> vCoins;\n    CAmount nValueMin = CENT;\n    CAmount nValueIn = 0;\n\n    CAmount nOnlyDenominatedBalance;\n    CAmount nBalanceNeedsDenominated;\n\n    \/\/ should not be less than fees in DARKSEND_COLLATERAL + few (lets say 5) smallest denoms\n    CAmount nLowestDenom = DARKSEND_COLLATERAL + DarKsendDenominations[DarKsendDenominations.size() - 1] * 5;\n\n    \/\/ if there are no OBF collateral inputs yet\n    if (!pwalletMain->HasCollateralInputs())\n        \/\/ should have some additional amount for them\n        nLowestDenom += DARKSEND_COLLATERAL * 4;\n\n    CAmount nBalanceNeedsAnonymized = nAnonymizeWORXAmount * COIN - pwalletMain->GetAnonymizedBalance();\n\n    \/\/ if balanceNeedsAnonymized is more than pool max, take the pool max\n    if (nBalanceNeedsAnonymized > DARKSEND_POOL_MAX) nBalanceNeedsAnonymized = DARKSEND_POOL_MAX;\n\n    \/\/ if balanceNeedsAnonymized is more than non-anonymized, take non-anonymized\n    CAmount nAnonymizableBalance = pwalletMain->GetAnonymizableBalance();\n    if (nBalanceNeedsAnonymized > nAnonymizableBalance) nBalanceNeedsAnonymized = nAnonymizableBalance;\n\n    if (nBalanceNeedsAnonymized < nLowestDenom) {\n        LogPrintf(\"DoAutomaticDenominating : No funds detected in need of denominating \\n\");\n        strAutoDenomResult = _(\"No funds detected in need of denominating.\");\n        return false;\n    }\n\n    LogPrint(\"Darksend\", \"DoAutomaticDenominating : nLowestDenom=%d, nBalanceNeedsAnonymized=%d\\n\", nLowestDenom, nBalanceNeedsAnonymized);\n\n    \/\/ select coins that should be given to the pool\n    if (!pwalletMain->SelectCoinsDark(nValueMin, nBalanceNeedsAnonymized, vCoins, nValueIn, 0, nDarksendRounds)) {\n        nValueIn = 0;\n        vCoins.clear();\n\n        if (pwalletMain->SelectCoinsDark(nValueMin, 9999999 * COIN, vCoins, nValueIn, -2, 0)) {\n            nOnlyDenominatedBalance = pwalletMain->GetDenominatedBalance(true) + pwalletMain->GetDenominatedBalance() - pwalletMain->GetAnonymizedBalance();\n            nBalanceNeedsDenominated = nBalanceNeedsAnonymized - nOnlyDenominatedBalance;\n\n            if (nBalanceNeedsDenominated > nValueIn) nBalanceNeedsDenominated = nValueIn;\n\n            if (nBalanceNeedsDenominated < nLowestDenom) return false; \/\/ most likely we just waiting for denoms to confirm\n            if (!fDryRun) return CreateDenominated(nBalanceNeedsDenominated);\n\n            return true;\n        } else {\n            LogPrintf(\"DoAutomaticDenominating : Can't denominate - no compatible inputs left\\n\");\n            strAutoDenomResult = _(\"Can't denominate: no compatible inputs left.\");\n            return false;\n        }\n    }\n\n    if (fDryRun) return true;\n\n    nOnlyDenominatedBalance = pwalletMain->GetDenominatedBalance(true) + pwalletMain->GetDenominatedBalance() - pwalletMain->GetAnonymizedBalance();\n    nBalanceNeedsDenominated = nBalanceNeedsAnonymized - nOnlyDenominatedBalance;\n\n    \/\/check if we have should create more denominated inputs\n    if (nBalanceNeedsDenominated > nOnlyDenominatedBalance) return CreateDenominated(nBalanceNeedsDenominated);\n\n    \/\/check if we have the collateral sized inputs\n    if (!pwalletMain->HasCollateralInputs()) return !pwalletMain->HasCollateralInputs(false) && MakeCollateralAmounts();\n\n    std::vector<CTxOut> vOut;\n\n    \/\/ initial phase, find a Masternode\n    if (!sessionFoundMasternode) {\n        \/\/ Clean if there is anything left from previous session\n        UnlockCoins();\n        SetNull();\n\n        int nUseQueue = rand() % 100;\n        UpdateState(POOL_STATUS_ACCEPTING_ENTRIES);\n\n        if (pwalletMain->GetDenominatedBalance(true) > 0) { \/\/get denominated unconfirmed inputs\n            LogPrintf(\"DoAutomaticDenominating -- Found unconfirmed denominated outputs, will wait till they confirm to continue.\\n\");\n            strAutoDenomResult = _(\"Found unconfirmed denominated outputs, will wait till they confirm to continue.\");\n            return false;\n        }\n\n        \/\/check our collateral nad create new if needed\n        std::string strReason;\n        CValidationState state;\n        if (txCollateral == CMutableTransaction()) {\n            if (!pwalletMain->CreateCollateralTransaction(txCollateral, strReason)) {\n                LogPrintf(\"% -- create collateral error:%s\\n\", __func__, strReason);\n                return false;\n            }\n        } else {\n            if (!IsCollateralValid(txCollateral)) {\n                LogPrintf(\"%s -- invalid collateral, recreating...\\n\", __func__);\n                if (!pwalletMain->CreateCollateralTransaction(txCollateral, strReason)) {\n                    LogPrintf(\"%s -- create collateral error: %s\\n\", __func__, strReason);\n                    return false;\n                }\n            }\n        }\n\n        \/\/if we've used 90% of the Masternode list then drop all the oldest first\n        int nThreshold = (int)(mnodeman.CountEnabled(ActiveProtocol()) * 0.9);\n        LogPrint(\"Darksend\", \"Checking vecMasternodesUsed size %d threshold %d\\n\", (int)vecMasternodesUsed.size(), nThreshold);\n        while ((int)vecMasternodesUsed.size() > nThreshold) {\n            vecMasternodesUsed.erase(vecMasternodesUsed.begin());\n            LogPrint(\"Darksend\", \"  vecMasternodesUsed size %d threshold %d\\n\", (int)vecMasternodesUsed.size(), nThreshold);\n        }\n\n        \/\/don't use the queues all of the time for mixing\n        if (nUseQueue > 33) {\n            \/\/ Look through the queues and see if anything matches\n            BOOST_FOREACH (CDarksendQueue& dsq, vecDarksendQueue) {\n                CService addr;\n                if (dsq.time == 0) continue;\n\n                if (!dsq.GetAddress(addr)) continue;\n                if (dsq.IsExpired()) continue;\n\n                int protocolVersion;\n                if (!dsq.GetProtocolVersion(protocolVersion)) continue;\n                if (protocolVersion < ActiveProtocol()) continue;\n\n                \/\/non-denom's are incompatible\n                if ((dsq.nDenom & (1 << 4))) continue;\n\n                bool fUsed = false;\n                \/\/don't reuse Masternodes\n                BOOST_FOREACH (CTxIn usedVin, vecMasternodesUsed) {\n                    if (dsq.vin == usedVin) {\n                        fUsed = true;\n                        break;\n                    }\n                }\n                if (fUsed) continue;\n\n                std::vector<CTxIn> vTempCoins;\n                std::vector<COutput> vTempCoins2;\n                \/\/ Try to match their denominations if possible\n                if (!pwalletMain->SelectCoinsByDenominations(dsq.nDenom, nValueMin, nBalanceNeedsAnonymized, vTempCoins, vTempCoins2, nValueIn, 0, nDarksendRounds)) {\n                    LogPrintf(\"DoAutomaticDenominating --- Couldn't match denominations %d\\n\", dsq.nDenom);\n                    continue;\n                }\n\n                CMasternode* pmn = mnodeman.Find(dsq.vin);\n                if (pmn == NULL) {\n                    LogPrintf(\"DoAutomaticDenominating --- dsq vin %s is not in masternode list!\", dsq.vin.ToString());\n                    continue;\n                }\n\n                LogPrintf(\"DoAutomaticDenominating --- attempt to connect to masternode from queue %s\\n\", pmn->addr.ToString());\n                lastTimeChanged = GetTimeMillis();\n\n                \/\/ connect to Masternode and submit the queue request\n                CNode* pnode = ConnectNode((CAddress)addr, NULL, true);\n                if (pnode != NULL) {\n                    pSubmittedToMasternode = pmn;\n                    vecMasternodesUsed.push_back(dsq.vin);\n                    sessionDenom = dsq.nDenom;\n\n                    pnode->PushMessage(\"dsa\", sessionDenom, txCollateral);\n                    LogPrintf(\"DoAutomaticDenominating --- connected (from queue), sending dsa for %d - %s\\n\", sessionDenom, pnode->addr.ToString());\n                    strAutoDenomResult = _(\"Mixing in progress...\");\n                    dsq.time = 0; \/\/remove node\n                    return true;\n                } else {\n                    LogPrintf(\"DoAutomaticDenominating --- error connecting \\n\");\n                    strAutoDenomResult = _(\"Error connecting to Masternode.\");\n                    dsq.time = 0; \/\/remove node\n                    continue;\n                }\n            }\n        }\n\n        \/\/ do not initiate queue if we are a liquidity proveder to avoid useless inter-mixing\n        if (nLiquidityProvider) return false;\n\n        int i = 0;\n\n        \/\/ otherwise, try one randomly\n        while (i < 10) {\n            CMasternode* pmn = mnodeman.FindRandomNotInVec(vecMasternodesUsed, ActiveProtocol());\n            if (pmn == NULL) {\n                LogPrintf(\"DoAutomaticDenominating --- Can't find random masternode!\\n\");\n                strAutoDenomResult = _(\"Can't find random Masternode.\");\n                return false;\n            }\n\n            if (pmn->nLastDsq != 0 &&\n                pmn->nLastDsq + mnodeman.CountEnabled(ActiveProtocol()) \/ 5 > mnodeman.nDsqCount) {\n                i++;\n                continue;\n            }\n\n            lastTimeChanged = GetTimeMillis();\n            LogPrintf(\"DoAutomaticDenominating --- attempt %d connection to Masternode %s\\n\", i, pmn->addr.ToString());\n            CNode* pnode = ConnectNode((CAddress)pmn->addr, NULL, true);\n            if (pnode != NULL) {\n                pSubmittedToMasternode = pmn;\n                vecMasternodesUsed.push_back(pmn->vin);\n\n                std::vector<CAmount> vecAmounts;\n                pwalletMain->ConvertList(vCoins, vecAmounts);\n                \/\/ try to get a single random denom out of vecAmounts\n                while (sessionDenom == 0)\n                    sessionDenom = GetDenominationsByAmounts(vecAmounts);\n\n                pnode->PushMessage(\"dsa\", sessionDenom, txCollateral);\n                LogPrintf(\"DoAutomaticDenominating --- connected, sending dsa for %d\\n\", sessionDenom);\n                strAutoDenomResult = _(\"Mixing in progress...\");\n                return true;\n            } else {\n                vecMasternodesUsed.push_back(pmn->vin); \/\/ postpone MN we wasn't able to connect to\n                i++;\n                continue;\n            }\n        }\n\n        strAutoDenomResult = _(\"No compatible Masternode found.\");\n        return false;\n    }\n\n    strAutoDenomResult = _(\"Mixing in progress...\");\n    return false;\n}\n\n\nbool CDarksendPool::PrepareDarksendDenominate()\n{\n    std::string strError = \"\";\n    \/\/ Submit transaction to the pool if we get here\n    \/\/ Try to use only inputs with the same number of rounds starting from lowest number of rounds possible\n    for (int i = 0; i < nDarksendRounds; i++) {\n        strError = pwalletMain->PrepareDarksendDenominate(i, i + 1);\n        LogPrintf(\"DoAutomaticDenominating : Running Darksend denominate for %d rounds. Return '%s'\\n\", i, strError);\n        if (strError == \"\") return true;\n    }\n\n    \/\/ We failed? That's strange but let's just make final attempt and try to mix everything\n    strError = pwalletMain->PrepareDarksendDenominate(0, nDarksendRounds);\n    LogPrintf(\"DoAutomaticDenominating : Running Darksend denominate for all rounds. Return '%s'\\n\", strError);\n    if (strError == \"\") return true;\n\n    \/\/ Should never actually get here but just in case\n    strAutoDenomResult = strError;\n    LogPrintf(\"DoAutomaticDenominating : Error running denominate, %s\\n\", strError);\n    return false;\n}\n\nbool CDarksendPool::SendRandomPaymentToSelf()\n{\n    int64_t nBalance = pwalletMain->GetBalance();\n    int64_t nPayment = (nBalance * 0.35) + (rand() % nBalance);\n\n    if (nPayment > nBalance) nPayment = nBalance - (0.1 * COIN);\n\n    \/\/ make our change address\n    CReserveKey reservekey(pwalletMain);\n\n    CScript scriptChange;\n    CPubKey vchPubKey;\n    assert(reservekey.GetReservedKey(vchPubKey)); \/\/ should never fail, as we just unlocked\n    scriptChange = GetScriptForDestination(vchPubKey.GetID());\n\n    CWalletTx wtx;\n    int64_t nFeeRet = 0;\n    std::string strFail = \"\";\n    vector<pair<CScript, int64_t> > vecSend;\n\n    \/\/ ****** Add fees ************ \/\n    vecSend.push_back(make_pair(scriptChange, nPayment));\n\n    CCoinControl* coinControl = NULL;\n    bool success = pwalletMain->CreateTransaction(vecSend, wtx, reservekey, nFeeRet, strFail, coinControl, ONLY_DENOMINATED);\n    if (!success) {\n        LogPrintf(\"SendRandomPaymentToSelf: Error - %s\\n\", strFail);\n        return false;\n    }\n\n    pwalletMain->CommitTransaction(wtx, reservekey);\n\n    LogPrintf(\"SendRandomPaymentToSelf Success: tx %s\\n\", wtx.GetHash().GetHex());\n\n    return true;\n}\n\n\/\/ Split up large inputs or create fee sized inputs\nbool CDarksendPool::MakeCollateralAmounts()\n{\n    CWalletTx wtx;\n    int64_t nFeeRet = 0;\n    std::string strFail = \"\";\n    vector<pair<CScript, int64_t> > vecSend;\n    CCoinControl coinControl;\n    coinControl.fAllowOtherInputs = false;\n    coinControl.fAllowWatchOnly = false;\n    \/\/ make our collateral address\n    CReserveKey reservekeyCollateral(pwalletMain);\n    \/\/ make our change address\n    CReserveKey reservekeyChange(pwalletMain);\n\n    CScript scriptCollateral;\n    CPubKey vchPubKey;\n    assert(reservekeyCollateral.GetReservedKey(vchPubKey)); \/\/ should never fail, as we just unlocked\n    scriptCollateral = GetScriptForDestination(vchPubKey.GetID());\n\n    vecSend.push_back(make_pair(scriptCollateral, DARKSEND_COLLATERAL * 4));\n\n    \/\/ try to use non-denominated and not mn-like funds\n    bool success = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange,\n        nFeeRet, strFail, &coinControl, ONLY_NONDENOMINATED_NOT10000IFMN);\n    if (!success) {\n        \/\/ if we failed (most likeky not enough funds), try to use all coins instead -\n        \/\/ MN-like funds should not be touched in any case and we can't mix denominated without collaterals anyway\n        CCoinControl* coinControlNull = NULL;\n        LogPrintf(\"MakeCollateralAmounts: ONLY_NONDENOMINATED_NOT10000IFMN Error - %s\\n\", strFail);\n        success = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange,\n            nFeeRet, strFail, coinControlNull, ONLY_NOT10000IFMN);\n        if (!success) {\n            LogPrintf(\"MakeCollateralAmounts: ONLY_NOT10000IFMN Error - %s\\n\", strFail);\n            reservekeyCollateral.ReturnKey();\n            return false;\n        }\n    }\n\n    reservekeyCollateral.KeepKey();\n\n    LogPrintf(\"MakeCollateralAmounts: tx %s\\n\", wtx.GetHash().GetHex());\n\n    \/\/ use the same cachedLastSuccess as for DS mixinx to prevent race\n    if (!pwalletMain->CommitTransaction(wtx, reservekeyChange)) {\n        LogPrintf(\"MakeCollateralAmounts: CommitTransaction failed!\\n\");\n        return false;\n    }\n\n    cachedLastSuccess = chainActive.Tip()->nHeight;\n\n    return true;\n}\n\n\/\/ Create denominations\nbool CDarksendPool::CreateDenominated(int64_t nTotalValue)\n{\n    CWalletTx wtx;\n    int64_t nFeeRet = 0;\n    std::string strFail = \"\";\n    vector<pair<CScript, int64_t> > vecSend;\n    int64_t nValueLeft = nTotalValue;\n\n    \/\/ make our collateral address\n    CReserveKey reservekeyCollateral(pwalletMain);\n    \/\/ make our change address\n    CReserveKey reservekeyChange(pwalletMain);\n    \/\/ make our denom addresses\n    CReserveKey reservekeyDenom(pwalletMain);\n\n    CScript scriptCollateral;\n    CPubKey vchPubKey;\n    assert(reservekeyCollateral.GetReservedKey(vchPubKey)); \/\/ should never fail, as we just unlocked\n    scriptCollateral = GetScriptForDestination(vchPubKey.GetID());\n\n    \/\/ ****** Add collateral outputs ************ \/\n    if (!pwalletMain->HasCollateralInputs()) {\n        vecSend.push_back(make_pair(scriptCollateral, DARKSEND_COLLATERAL * 4));\n        nValueLeft -= DARKSEND_COLLATERAL * 4;\n    }\n\n    \/\/ ****** Add denoms ************ \/\n    BOOST_REVERSE_FOREACH (int64_t v, DarKsendDenominations) {\n        int nOutputs = 0;\n\n        \/\/ add each output up to 10 times until it can't be added again\n        while (nValueLeft - v >= DARKSEND_COLLATERAL && nOutputs <= 10) {\n            CScript scriptDenom;\n            CPubKey vchPubKey;\n            \/\/use a unique change address\n            assert(reservekeyDenom.GetReservedKey(vchPubKey)); \/\/ should never fail, as we just unlocked\n            scriptDenom = GetScriptForDestination(vchPubKey.GetID());\n            \/\/ TODO: do not keep reservekeyDenom here\n            reservekeyDenom.KeepKey();\n\n            vecSend.push_back(make_pair(scriptDenom, v));\n\n            \/\/increment outputs and subtract denomination amount\n            nOutputs++;\n            nValueLeft -= v;\n            LogPrintf(\"CreateDenominated1 %d\\n\", nValueLeft);\n        }\n\n        if (nValueLeft == 0) break;\n    }\n    LogPrintf(\"CreateDenominated2 %d\\n\", nValueLeft);\n\n    \/\/ if we have anything left over, it will be automatically send back as change - there is no need to send it manually\n\n    CCoinControl* coinControl = NULL;\n    bool success = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange,\n        nFeeRet, strFail, coinControl, ONLY_NONDENOMINATED_NOT10000IFMN);\n    if (!success) {\n        LogPrintf(\"CreateDenominated: Error - %s\\n\", strFail);\n        \/\/ TODO: return reservekeyDenom here\n        reservekeyCollateral.ReturnKey();\n        return false;\n    }\n\n    \/\/ TODO: keep reservekeyDenom here\n    reservekeyCollateral.KeepKey();\n\n    \/\/ use the same cachedLastSuccess as for DS mixinx to prevent race\n    if (pwalletMain->CommitTransaction(wtx, reservekeyChange))\n        cachedLastSuccess = chainActive.Tip()->nHeight;\n    else\n        LogPrintf(\"CreateDenominated: CommitTransaction failed!\\n\");\n\n    LogPrintf(\"CreateDenominated: tx %s\\n\", wtx.GetHash().GetHex());\n\n    return true;\n}\n\nbool CDarksendPool::IsCompatibleWithEntries(std::vector<CTxOut>& vout)\n{\n    if (GetDenominations(vout) == 0) return false;\n\n    BOOST_FOREACH (const CDarKsendEntry v, entries) {\n        LogPrintf(\" IsCompatibleWithEntries %d %d\\n\", GetDenominations(vout), GetDenominations(v.vout));\n        \/*\n        BOOST_FOREACH(CTxOut o1, vout)\n            LogPrintf(\" vout 1 - %s\\n\", o1.ToString());\n\n        BOOST_FOREACH(CTxOut o2, v.vout)\n            LogPrintf(\" vout 2 - %s\\n\", o2.ToString());\n*\/\n        if (GetDenominations(vout) != GetDenominations(v.vout)) return false;\n    }\n\n    return true;\n}\n\nbool CDarksendPool::IsCompatibleWithSession(int64_t nDenom, CTransaction txCollateral, int& errorID)\n{\n    if (nDenom == 0) return false;\n\n    LogPrintf(\"CDarksendPool::IsCompatibleWithSession - sessionDenom %d sessionUsers %d\\n\", sessionDenom, sessionUsers);\n\n    if (!unitTest && !IsCollateralValid(txCollateral)) {\n        LogPrint(\"Darksend\", \"CDarksendPool::IsCompatibleWithSession - collateral not valid!\\n\");\n        errorID = ERR_INVALID_COLLATERAL;\n        return false;\n    }\n\n    if (sessionUsers < 0) sessionUsers = 0;\n\n    if (sessionUsers == 0) {\n        sessionID = 1 + (rand() % 999999);\n        sessionDenom = nDenom;\n        sessionUsers++;\n        lastTimeChanged = GetTimeMillis();\n\n        if (!unitTest) {\n            \/\/broadcast that I'm accepting entries, only if it's the first entry through\n            CDarksendQueue dsq;\n            dsq.nDenom = nDenom;\n            dsq.vin = activeMasternode.vin;\n            dsq.time = GetTime();\n            dsq.Sign();\n            dsq.Relay();\n        }\n\n        UpdateState(POOL_STATUS_QUEUE);\n        vecSessionCollateral.push_back(txCollateral);\n        return true;\n    }\n\n    if ((state != POOL_STATUS_ACCEPTING_ENTRIES && state != POOL_STATUS_QUEUE) || sessionUsers >= GetMaxPoolTransactions()) {\n        if ((state != POOL_STATUS_ACCEPTING_ENTRIES && state != POOL_STATUS_QUEUE)) errorID = ERR_MODE;\n        if (sessionUsers >= GetMaxPoolTransactions()) errorID = ERR_QUEUE_FULL;\n        LogPrintf(\"CDarksendPool::IsCompatibleWithSession - incompatible mode, return false %d %d\\n\", state != POOL_STATUS_ACCEPTING_ENTRIES, sessionUsers >= GetMaxPoolTransactions());\n        return false;\n    }\n\n    if (nDenom != sessionDenom) {\n        errorID = ERR_DENOM;\n        return false;\n    }\n\n    LogPrintf(\"CDarKsendPool::IsCompatibleWithSession - compatible\\n\");\n\n    sessionUsers++;\n    lastTimeChanged = GetTimeMillis();\n    vecSessionCollateral.push_back(txCollateral);\n\n    return true;\n}\n\n\/\/create a nice string to show the denominations\nvoid CDarksendPool::GetDenominationsToString(int nDenom, std::string& strDenom)\n{\n    \/\/ Function returns as follows:\n    \/\/\n    \/\/ bit 0 - 100WORX+1 ( bit on if present )\n    \/\/ bit 1 - 10WORX+1\n    \/\/ bit 2 - 1WORX+1\n    \/\/ bit 3 - .1WORX+1\n    \/\/ bit 3 - non-denom\n\n\n    strDenom = \"\";\n\n    if (nDenom & (1 << 0)) {\n        if (strDenom.size() > 0) strDenom += \"+\";\n        strDenom += \"100\";\n    }\n\n    if (nDenom & (1 << 1)) {\n        if (strDenom.size() > 0) strDenom += \"+\";\n        strDenom += \"10\";\n    }\n\n    if (nDenom & (1 << 2)) {\n        if (strDenom.size() > 0) strDenom += \"+\";\n        strDenom += \"1\";\n    }\n\n    if (nDenom & (1 << 3)) {\n        if (strDenom.size() > 0) strDenom += \"+\";\n        strDenom += \"0.1\";\n    }\n}\n\nint CDarksendPool::GetDenominations(const std::vector<CTxDSOut>& vout)\n{\n    std::vector<CTxOut> vout2;\n\n    BOOST_FOREACH (CTxDSOut out, vout)\n        vout2.push_back(out);\n\n    return GetDenominations(vout2);\n}\n\n\/\/ return a bitshifted integer representing the denominations in this list\nint CDarksendPool::GetDenominations(const std::vector<CTxOut>& vout, bool fSingleRandomDenom)\n{\n    std::vector<pair<int64_t, int> > denomUsed;\n\n    \/\/ make a list of denominations, with zero uses\n    BOOST_FOREACH (int64_t d, DarKsendDenominations)\n        denomUsed.push_back(make_pair(d, 0));\n\n    \/\/ look for denominations and update uses to 1\n    BOOST_FOREACH (CTxOut out, vout) {\n        bool found = false;\n        BOOST_FOREACH (PAIRTYPE(int64_t, int) & s, denomUsed) {\n            if (out.nValue == s.first) {\n                s.second = 1;\n                found = true;\n            }\n        }\n        if (!found) return 0;\n    }\n\n    int denom = 0;\n    int c = 0;\n    \/\/ if the denomination is used, shift the bit on.\n    \/\/ then move to the next\n    BOOST_FOREACH (PAIRTYPE(int64_t, int) & s, denomUsed) {\n        int bit = (fSingleRandomDenom ? rand() % 2 : 1) * s.second;\n        denom |= bit << c++;\n        if (fSingleRandomDenom && bit) break; \/\/ use just one random denomination\n    }\n\n    \/\/ Function returns as follows:\n    \/\/\n    \/\/ bit 0 - 100WORX+1 ( bit on if present )\n    \/\/ bit 1 - 10WORX+1\n    \/\/ bit 2 - 1WORX+1\n    \/\/ bit 3 - .1WORX+1\n\n    return denom;\n}\n\n\nint CDarksendPool::GetDenominationsByAmounts(std::vector<int64_t>& vecAmount)\n{\n    CScript e = CScript();\n    std::vector<CTxOut> vout1;\n\n    \/\/ Make outputs by looping through denominations, from small to large\n    BOOST_REVERSE_FOREACH (int64_t v, vecAmount) {\n        CTxOut o(v, e);\n        vout1.push_back(o);\n    }\n\n    return GetDenominations(vout1, true);\n}\n\nint CDarksendPool::GetDenominationsByAmount(int64_t nAmount, int nDenomTarget)\n{\n    CScript e = CScript();\n    int64_t nValueLeft = nAmount;\n\n    std::vector<CTxOut> vout1;\n\n    \/\/ Make outputs by looping through denominations, from small to large\n    BOOST_REVERSE_FOREACH (int64_t v, DarKsendDenominations) {\n        if (nDenomTarget != 0) {\n            bool fAccepted = false;\n            if ((nDenomTarget & (1 << 0)) && v == ((100 * COIN) + 100000)) {\n                fAccepted = true;\n            } else if ((nDenomTarget & (1 << 1)) && v == ((10 * COIN) + 10000)) {\n                fAccepted = true;\n            } else if ((nDenomTarget & (1 << 2)) && v == ((1 * COIN) + 1000)) {\n                fAccepted = true;\n            } else if ((nDenomTarget & (1 << 3)) && v == ((.1 * COIN) + 100)) {\n                fAccepted = true;\n            }\n            if (!fAccepted) continue;\n        }\n\n        int nOutputs = 0;\n\n        \/\/ add each output up to 10 times until it can't be added again\n        while (nValueLeft - v >= 0 && nOutputs <= 10) {\n            CTxOut o(v, e);\n            vout1.push_back(o);\n            nValueLeft -= v;\n            nOutputs++;\n        }\n        LogPrintf(\"GetDenominationsByAmount --- %d nOutputs %d\\n\", v, nOutputs);\n    }\n\n    return GetDenominations(vout1);\n}\n\nstd::string CDarksendPool::GetMessageByID(int messageID)\n{\n    switch (messageID) {\n    case ERR_ALREADY_HAVE:\n        return _(\"Already have that input.\");\n    case ERR_DENOM:\n        return _(\"No matching denominations found for mixing.\");\n    case ERR_ENTRIES_FULL:\n        return _(\"Entries are full.\");\n    case ERR_EXISTING_TX:\n        return _(\"Not compatible with existing transactions.\");\n    case ERR_FEES:\n        return _(\"Transaction fees are too high.\");\n    case ERR_INVALID_COLLATERAL:\n        return _(\"Collateral not valid.\");\n    case ERR_INVALID_INPUT:\n        return _(\"Input is not valid.\");\n    case ERR_INVALID_SCRIPT:\n        return _(\"Invalid script detected.\");\n    case ERR_INVALID_TX:\n        return _(\"Transaction not valid.\");\n    case ERR_MAXIMUM:\n        return _(\"Value more than Darksend pool maximum allows.\");\n    case ERR_MN_LIST:\n        return _(\"Not in the Masternode list.\");\n    case ERR_MODE:\n        return _(\"Incompatible mode.\");\n    case ERR_NON_STANDARD_PUBKEY:\n        return _(\"Non-standard public key detected.\");\n    case ERR_NOT_A_MN:\n        return _(\"This is not a Masternode.\");\n    case ERR_QUEUE_FULL:\n        return _(\"Masternode queue is full.\");\n    case ERR_RECENT:\n        return _(\"Last Darksend was too recent.\");\n    case ERR_SESSION:\n        return _(\"Session not complete!\");\n    case ERR_MISSING_TX:\n        return _(\"Missing input transaction information.\");\n    case ERR_VERSION:\n        return _(\"Incompatible version.\");\n    case MSG_SUCCESS:\n        return _(\"Transaction created successfully.\");\n    case MSG_ENTRIES_ADDED:\n        return _(\"Your entries added successfully.\");\n    case MSG_NOERR:\n    default:\n        return \"\";\n    }\n}\n\nbool CDarKsendSigner::IsVinAssociatedWithPubkey(CTxIn& vin, CPubKey& pubkey)\n{\n   CScript payee2;\n    payee2 = GetScriptForDestination(pubkey.GetID());\n\n    CTransaction txVin;\n    uint256 hash;\n    int nHeight = chainActive.Height();\n\n    if (GetTransaction(vin.prevout.hash, txVin, hash, true)) {\n        BOOST_FOREACH (CTxOut out, txVin.vout) {\n          if (nHeight >= Params().NewMasternodeCollateral_StartBlock()) {\n            if (out.nValue == Params().NewMasternode_Collateral() * COIN) {\n              if (out.scriptPubKey == payee2) return true;\n            }\n          } else {\n            if (out.nValue == Params().OriginalMasternode_Collateral() * COIN) {\n              if (out.scriptPubKey == payee2) return true;\n            }\n          }\n        }\n    }\n\nreturn false;\n}\n\nbool CDarKsendSigner::SetKey(std::string strSecret, std::string& errorMessage, CKey& key, CPubKey& pubkey)\n{\n    CBitcoinSecret vchSecret;\n    bool fGood = vchSecret.SetString(strSecret);\n\n    if (!fGood) {\n        errorMessage = _(\"Invalid private key.\");\n        return false;\n    }\n\n    key = vchSecret.GetKey();\n    pubkey = key.GetPubKey();\n\n    return true;\n}\n\nbool CDarKsendSigner::GetKeysFromSecret(std::string strSecret, CKey& keyRet, CPubKey& pubkeyRet)\n{\n    CBitcoinSecret vchSecret;\n\n    if (!vchSecret.SetString(strSecret)) return false;\n\n    keyRet = vchSecret.GetKey();\n    pubkeyRet = keyRet.GetPubKey();\n\n    return true;\n}\n\nbool CDarKsendSigner::SignMessage(std::string strMessage, std::string& errorMessage, vector<unsigned char>& vchSig, CKey key)\n{\n    CHashWriter ss(SER_GETHASH, 0);\n    ss << strMessageMagic;\n    ss << strMessage;\n\n    if (!key.SignCompact(ss.GetHash(), vchSig)) {\n        errorMessage = _(\"Signing failed.\");\n        return false;\n    }\n\n    return true;\n}\n\nbool CDarKsendSigner::VerifyMessage(CPubKey pubkey, vector<unsigned char>& vchSig, std::string strMessage, std::string& errorMessage)\n{\n    CHashWriter ss(SER_GETHASH, 0);\n    ss << strMessageMagic;\n    ss << strMessage;\n\n    CPubKey pubkey2;\n    if (!pubkey2.RecoverCompact(ss.GetHash(), vchSig)) {\n        errorMessage = _(\"Error recovering public key.\");\n        return false;\n    }\n\n    if (fDebug && pubkey2.GetID() != pubkey.GetID())\n        LogPrintf(\"CDarKsendSigner::VerifyMessage -- keys don't match: %s %s\\n\", pubkey2.GetID().ToString(), pubkey.GetID().ToString());\n\n    return (pubkey2.GetID() == pubkey.GetID());\n}\n\nbool CDarksendQueue::Sign()\n{\n    if (!fMasterNode) return false;\n\n    std::string strMessage = vin.ToString() + boost::lexical_cast<std::string>(nDenom) + boost::lexical_cast<std::string>(time) + boost::lexical_cast<std::string>(ready);\n\n    CKey key2;\n    CPubKey pubkey2;\n    std::string errorMessage = \"\";\n\n    if (!DarKsendSigner.SetKey(strMasterNodePrivKey, errorMessage, key2, pubkey2)) {\n        LogPrintf(\"CDarksendQueue():Relay - ERROR: Invalid Masternodeprivkey: '%s'\\n\", errorMessage);\n        return false;\n    }\n\n    if (!DarKsendSigner.SignMessage(strMessage, errorMessage, vchSig, key2)) {\n        LogPrintf(\"CDarksendQueue():Relay - Sign message failed\");\n        return false;\n    }\n\n    if (!DarKsendSigner.VerifyMessage(pubkey2, vchSig, strMessage, errorMessage)) {\n        LogPrintf(\"CDarksendQueue():Relay - Verify message failed\");\n        return false;\n    }\n\n    return true;\n}\n\nbool CDarksendQueue::Relay()\n{\n    LOCK(cs_vNodes);\n    BOOST_FOREACH (CNode* pnode, vNodes) {\n        \/\/ always relay to everyone\n        pnode->PushMessage(\"dsq\", (*this));\n    }\n\n    return true;\n}\n\nbool CDarksendQueue::CheckSignature()\n{\n    CMasternode* pmn = mnodeman.Find(vin);\n\n    if (pmn != NULL) {\n        std::string strMessage = vin.ToString() + boost::lexical_cast<std::string>(nDenom) + boost::lexical_cast<std::string>(time) + boost::lexical_cast<std::string>(ready);\n\n        std::string errorMessage = \"\";\n        if (!DarKsendSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) {\n            return error(\"CDarksendQueue::CheckSignature() - Got bad Masternode address signature %s \\n\", vin.ToString().c_str());\n        }\n\n        return true;\n    }\n\n    return false;\n}\n\n\nvoid CDarksendPool::RelayFinalTransaction(const int sessionID, const CTransaction& txNew)\n{\n    LOCK(cs_vNodes);\n    BOOST_FOREACH (CNode* pnode, vNodes) {\n        pnode->PushMessage(\"dsf\", sessionID, txNew);\n    }\n}\n\nvoid CDarksendPool::RelayIn(const std::vector<CTxDSIn>& vin, const int64_t& nAmount, const CTransaction& txCollateral, const std::vector<CTxDSOut>& vout)\n{\n    if (!pSubmittedToMasternode) return;\n\n    std::vector<CTxIn> vin2;\n    std::vector<CTxOut> vout2;\n\n    BOOST_FOREACH (CTxDSIn in, vin)\n        vin2.push_back(in);\n\n    BOOST_FOREACH (CTxDSOut out, vout)\n        vout2.push_back(out);\n\n    CNode* pnode = FindNode(pSubmittedToMasternode->addr);\n    if (pnode != NULL) {\n        LogPrintf(\"RelayIn - found master, relaying message - %s \\n\", pnode->addr.ToString());\n        pnode->PushMessage(\"dsi\", vin2, nAmount, txCollateral, vout2);\n    }\n}\n\nvoid CDarksendPool::RelayStatus(const int sessionID, const int newState, const int newEntriesCount, const int newAccepted, const int errorID)\n{\n    LOCK(cs_vNodes);\n    BOOST_FOREACH (CNode* pnode, vNodes)\n        pnode->PushMessage(\"dssu\", sessionID, newState, newEntriesCount, newAccepted, errorID);\n}\n\nvoid CDarksendPool::RelayCompletedTransaction(const int sessionID, const bool error, const int errorID)\n{\n    LOCK(cs_vNodes);\n    BOOST_FOREACH (CNode* pnode, vNodes)\n        pnode->PushMessage(\"dsc\", sessionID, error, errorID);\n}\n\n\/\/TODO: Rename\/move to core\nvoid ThreadCheckDarKsendPool()\n{\n    if (fLiteMode) return; \/\/disable all Darksend\/Masternode related functionality\n\n    \/\/ Make this thread recognisable as the wallet flushing thread\n    RenameThread(\"worx-Darksend\");\n\n    unsigned int c = 0;\n\n    while (true) {\n        MilliSleep(1000);\n        \/\/LogPrintf(\"ThreadCheckDarKsendPool::check timeout\\n\");\n\n        \/\/ try to sync from all available nodes, one step at a time\n        masternodeSync.Process();\n\n        if (masternodeSync.IsBlockchainSynced()) {\n            c++;\n\n            \/\/ check if we should activate or ping every few minutes,\n            \/\/ start right after sync is considered to be done\n            if (c % MASTERNODE_PING_SECONDS == 1) activeMasternode.ManageStatus();\n\n            if (c % 60 == 0) {\n                mnodeman.CheckAndRemove();\n                mnodeman.ProcessMasternodeConnections();\n                masternodePayments.CleanPaymentList();\n                CleanTransactionLocksList();\n            }\n\n            \/\/if(c % MASTERNODES_DUMP_SECONDS == 0) DumpMasternodes();\n\n            DarKsendPool.CheckTimeout();\n            DarKsendPool.CheckForCompleteQueue();\n\n            if (DarKsendPool.GetState() == POOL_STATUS_IDLE && c % 15 == 0) {\n                DarKsendPool.DoAutomaticDenominating();\n            }\n        }\n    }\n}\n","avg_line_length":35.6510930133,"max_line_length":184,"alphanum_fraction":0.6082670065,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":17997,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1706.0,"content":"\/*\n * MRustC - Mutabah's Rust Compiler\n * - By John Hodge (Mutabah\/thePowersGang)\n *\n * ast\/expr.cpp\n * - AST Expression nodes\n *\/\n#include \"expr.hpp\"\n#include \"ast.hpp\"\n#include <cctype>\n\nnamespace AST {\n\nExprNodeP::~ExprNodeP()\n{\n    if(m_ptr)\n        delete m_ptr;\n    m_ptr = nullptr;\n}\nExprNodeP::ExprNodeP(std::unique_ptr<ExprNode> node)\n    : m_ptr(node.release())\n{\n}\n\nExpr::Expr(ExprNodeP node):\n    m_node(node.release())\n{\n}\nExpr::Expr(ExprNode* node):\n    m_node(node)\n{\n}\nExpr::Expr():\n    m_node(nullptr)\n{\n}\nvoid Expr::visit_nodes(NodeVisitor& v)\n{\n    if( m_node )\n    {\n        m_node->visit(v);\n    }\n}\nvoid Expr::visit_nodes(NodeVisitor& v) const\n{\n    if( m_node )\n    {\n        assert(v.is_const());\n        \/\/const_cast<const ExprNode*>(m_node.get())->visit(v);\n        m_node->visit(v);\n    }\n}\n\nExpr Expr::clone() const\n{\n    if( m_node ) {\n        return Expr( m_node->clone() );\n    }\n    else {\n        return Expr();\n    }\n}\n\n::std::ostream& operator<<(::std::ostream& os, const Expr& pat)\n{\n    if( pat.m_node.get() )\n        return os << *pat.m_node;\n    else\n        return os << \"\/* null *\/\";\n}\n\n::std::ostream& operator<<(::std::ostream& os, const ExprNode& node)\n{\n    assert( static_cast<const void*>(&node) != nullptr );\n    node.print(os);\n    return os;\n}\nExprNode::~ExprNode() {\n}\n\n#define NODE(class, _print, _clone)\\\n    void class::visit(NodeVisitor& nv) { nv.visit(*this); } \\\n    void class::print(::std::ostream& os) const _print \\\n    ExprNodeP class::clone() const _clone\n#define OPT_CLONE(node) (node.get() ? node->clone() : ::AST::ExprNodeP())\n\nnamespace {\n    static inline ExprNodeP mk_exprnodep(const Span& pos, AST::ExprNode* en) {\n        en->set_span(pos);\n        return ExprNodeP(en);\n    }\n    #define NEWNODE(type, ...)  mk_exprnodep(span(), new type(__VA_ARGS__))\n}\n\nNODE(ExprNode_Block, {\n    os << \"{\";\n    for(const auto& n : m_nodes)\n        os << *n << \";\";\n    os << \"}\";\n},{\n    ::std::vector<ExprNodeP>    nodes;\n    for(const auto& n : m_nodes)\n        nodes.push_back( n->clone() );\n    return NEWNODE(ExprNode_Block, m_is_unsafe, m_yields_final_value, mv$(nodes), m_local_mod);\n})\n\nNODE(ExprNode_Try, {\n    os << \"try \" << *m_inner;\n},{\n    return NEWNODE(ExprNode_Try, m_inner->clone());\n})\n\nNODE(ExprNode_Macro, {\n    os << m_path << \"!\";\n    if( m_ident.size() > 0 )\n    {\n        os << \" \" << m_ident << \" \";\n    }\n    os << \"(\" << \" \/*TODO*\/ \" << \")\";\n},{\n    return NEWNODE(ExprNode_Macro, AST::Path(m_path), m_ident, m_tokens.clone());\n})\n\nNODE(ExprNode_Asm, {\n    os << \"llvm_asm!( \\\"\" << m_text << \"\\\"\";\n    os << \" :\";\n    for(const auto& v : m_output)\n        os << \" \\\"\" << v.name << \"\\\" (\" << *v.value << \"),\";\n    os << \" :\";\n    for(const auto& v : m_input)\n        os << \" \\\"\" << v.name << \"\\\" (\" << *v.value << \"),\";\n    os << \" :\";\n    for(const auto& v : m_clobbers)\n        os << \" \\\"\" << v << \"\\\",\";\n    os << \" :\";\n    for(const auto& v : m_flags)\n        os << \" \\\"\" << v << \"\\\",\";\n    os << \" )\";\n},{\n    ::std::vector<ExprNode_Asm::ValRef> outputs;\n    for(const auto& v : m_output)\n        outputs.push_back( ExprNode_Asm::ValRef { v.name, v.value->clone() });\n    ::std::vector<ExprNode_Asm::ValRef> inputs;\n    for(const auto& v : m_input)\n        inputs.push_back( ExprNode_Asm::ValRef { v.name, v.value->clone() });\n    return NEWNODE(ExprNode_Asm, m_text, mv$(outputs), mv$(inputs), m_clobbers, m_flags);\n})\n}\n\nnamespace {\n    void print_fmt_string(std::ostream& os, const std::string& s) {\n        static const char* hex = \"0123456789ABCDEF\";\n        for(auto c : s) {\n            if( c == '{' )\n                os << \"{{\";\n            else if( c == '\\\\' )\n                os << \"\\\\\\\\\";\n            else if( c == '\"' )\n                os << \"\\\\\\\"\";\n            else if( std::isprint(c) )\n                os << c;\n            else\n                os << \"\\\\x\" << hex[c >> 4] << hex[c & 15];\n        }\n    }\n}\nvoid AsmCommon::Line::fmt(std::ostream& os) const {\n    os << \"\\\"\";\n    for(const auto& f : this->frags)\n    {\n        print_fmt_string(os, f.before);\n        os << \"{\" << f.index;\n        if(f.modifier)\n            os << \":\" << f.modifier;\n        os << \"}\";\n    }\n    print_fmt_string(os, this->trailing);\n    os << \"\\\"\";\n}\n\nnamespace AST {\nNODE(ExprNode_Asm2, {\n    os << \"asm!( \";\n    for(const auto& l : m_lines)\n    {\n        l.fmt(os);\n        os << \", \";\n    }\n    for(const auto& p : m_params)\n    {\n        TU_MATCH_HDRA( (p), {)\n        TU_ARMA(Const, e) {\n            os << \"const \" << *e;\n            }\n        TU_ARMA(Sym, e) {\n            os << \"sym \" << e;\n            }\n        TU_ARMA(RegSingle, e) {\n            os << \"reg(\" << e.dir << \" \" << e.spec << \") \" << *e.val;\n            }\n        TU_ARMA(Reg, e) {\n            os << \"reg(\" << e.dir << \" \" << e.spec << \") \";\n            if( e.val_in ) os << *e.val_in; else os << \"_\";\n            os << \" => \";\n            if( e.val_out ) os << *e.val_out; else os << \"_\";\n            }\n        }\n        os << \", \";\n    }\n    os << \" )\";\n},{\n    std::vector<Param>  params;\n\n    for(const auto& p : m_params)\n    {\n        TU_MATCH_HDRA( (p), { )\n        TU_ARMA(Const, e) {\n            params.push_back(Param::make_Const(e->clone()));\n            }\n        TU_ARMA(Sym, e) {\n            params.push_back(Param::make_Sym(e));\n            }\n        TU_ARMA(RegSingle, e) {\n            params.push_back(Param::make_RegSingle({ e.dir, e.spec.clone(), e.val->clone() }));\n            }\n        TU_ARMA(Reg, e) {\n            params.push_back(Param::make_Reg({ e.dir, e.spec.clone(), e.val_in ? e.val_in->clone() : nullptr, e.val_out ? e.val_out->clone() : nullptr }));\n            }\n        }\n    }\n\n    return NEWNODE(ExprNode_Asm2, m_options, m_lines, std::move(params));\n})\n\nNODE(ExprNode_Flow, {\n    switch(m_type)\n    {\n    case RETURN:    os << \"return\"; break;\n    case YIELD:     os << \"yield\"; break;\n    case BREAK:     os << \"break\"; break;\n    case CONTINUE:  os << \"continue\"; break;\n    }\n    if(m_value)\n        os << \" \" << *m_value;\n},{\n    return NEWNODE(ExprNode_Flow, m_type, m_target, m_value ? m_value->clone() : nullptr);\n})\n\n\nNODE(ExprNode_LetBinding, {\n    os << \"let \" << m_pat << \": \" << m_type;\n    if(m_value)\n        os << \" = \" << *m_value;\n},{\n    return NEWNODE(ExprNode_LetBinding, m_pat.clone(), m_type.clone(), OPT_CLONE(m_value));\n})\n\nNODE(ExprNode_Assign, {\n    os << *m_slot << \" = \" << *m_value;\n},{\n    return NEWNODE(ExprNode_Assign, m_op, m_slot->clone(), m_value->clone());\n})\n\nNODE(ExprNode_CallPath, {\n    os << m_path << \"(\";\n    for(const auto& a : m_args) {\n        os << *a << \",\";\n    }\n    os << \")\";\n},{\n    ::std::vector<ExprNodeP>    args;\n    for(const auto& a : m_args) {\n        args.push_back( a->clone() );\n    }\n    return NEWNODE(ExprNode_CallPath, AST::Path(m_path), mv$(args));\n})\n\nNODE(ExprNode_CallMethod, {\n    os << \"(\" << *m_val << \").\" << m_method << \"(\";\n    for(const auto& a : m_args) {\n        os << *a << \",\";\n    }\n    os << \")\";\n},{\n    ::std::vector<ExprNodeP>    args;\n    for(const auto& a : m_args) {\n        args.push_back( a->clone() );\n    }\n    return NEWNODE(ExprNode_CallMethod, m_val->clone(), m_method, mv$(args));\n})\n\nNODE(ExprNode_CallObject, {\n    os << \"(\" << *m_val << \")(\";\n    for(const auto& a : m_args) {\n        os << *a << \",\";\n    }\n    os << \")\";\n},{\n    ::std::vector<ExprNodeP>    args;\n    for(const auto& a : m_args) {\n        args.push_back( a->clone() );\n    }\n    return NEWNODE(ExprNode_CallObject, m_val->clone(), mv$(args));\n})\n\nNODE(ExprNode_Loop, {\n    os << \"LOOP [\" << m_label << \"] \" << m_pattern;\n    if(m_cond)\n        os << \" in\/= \" << *m_cond;\n    os << \" \" << *m_code;\n},{\n    return NEWNODE(ExprNode_Loop, m_label, m_type, m_pattern.clone(), OPT_CLONE(m_cond), m_code->clone());\n})\n\nNODE(ExprNode_Match, {\n    os << \"match (\"<<*m_val<<\") {\";\n    for(const auto& arm : m_arms)\n    {\n        for( const auto& pat : arm.m_patterns )\n            os << \" \" << pat;\n        if( arm.m_cond )\n            os << \" if \" << *arm.m_cond;\n\n        os << \" => \" << *arm.m_code << \",\";\n    }\n    os << \"}\";\n},{\n    ::std::vector< ExprNode_Match_Arm>  arms;\n    for(const auto& arm : m_arms) {\n        ::std::vector< AST::Pattern>    patterns;\n        for( const auto& pat : arm.m_patterns ) {\n            patterns.push_back( pat.clone() );\n        }\n        arms.push_back( ExprNode_Match_Arm( mv$(patterns), OPT_CLONE(arm.m_cond), arm.m_code->clone() ) );\n        arms.back().m_attrs = arm.m_attrs.clone();\n    }\n    return NEWNODE(ExprNode_Match, m_val->clone(), mv$(arms));\n})\n\nNODE(ExprNode_If, {\n    os << \"if \" << *m_cond << \" { \" << *m_true << \" }\";\n    if(m_false)\n        os << \" else { \" << *m_false << \" }\";\n},{\n    return NEWNODE(ExprNode_If, m_cond->clone(), m_true->clone(), OPT_CLONE(m_false));\n})\nNODE(ExprNode_IfLet, {\n    os << \"if let \";\n    for(const auto& pat : m_patterns)\n    {\n        if(&pat != &m_patterns.front())\n            os << \" | \";\n        os << pat;\n    }\n    os << \" = (\" << *m_value << \") { \" << *m_true << \" }\";\n    if(m_false) os << \" else { \" << *m_false << \" }\";\n},{\n    decltype(m_patterns)    new_pats;\n    for(const auto& pat : m_patterns)\n        new_pats.push_back(pat.clone());\n    return NEWNODE(ExprNode_IfLet, mv$(new_pats), m_value->clone(), m_true->clone(), OPT_CLONE(m_false));\n})\n\nNODE(ExprNode_Integer, {\n    if( m_datatype == CORETYPE_CHAR )\n        os << \"'\\\\u{\" << ::std::hex << m_value << ::std::dec << \"}'\";\n    else\n    {\n        os << m_value;\n        if( m_datatype == CORETYPE_ANY )\n            ;\n        else\n            os << \"_\" << coretype_name(m_datatype);\n    }\n},{\n    return NEWNODE(ExprNode_Integer, m_value, m_datatype);\n})\nNODE(ExprNode_Float, {\n    os << m_value << \"_\" << m_datatype;\n},{\n    return NEWNODE(ExprNode_Float, m_value, m_datatype);\n})\nNODE(ExprNode_Bool, {\n    os << m_value;\n},{\n    return NEWNODE(ExprNode_Bool, m_value);\n})\nNODE(ExprNode_String, {\n    os << \"\\\"\" << m_value << \"\\\"\";\n},{\n    return NEWNODE(ExprNode_String, m_value);\n})\nNODE(ExprNode_ByteString, {\n    os << \"b\\\"\" << m_value << \"\\\"\";\n},{\n    return NEWNODE(ExprNode_ByteString, m_value);\n})\n\nNODE(ExprNode_Closure, {\n    if( m_is_pinned )\n        os << \"static \";\n    if( m_is_move )\n        os << \"move \";\n    os << \"|\";\n    for(const auto& a : m_args)\n    {\n        os << a.first << \": \" << a.second << \",\";\n    }\n    os << \"|\";\n    os << \"->\" << m_return;\n    os << \" \" << *m_code;\n},{\n    ExprNode_Closure::args_t    args;\n    for(const auto& a : m_args) {\n        args.push_back( ::std::make_pair(a.first.clone(), a.second.clone()) );\n    }\n    return NEWNODE(ExprNode_Closure, mv$(args), m_return.clone(), m_code->clone(), m_is_move, m_is_pinned);\n});\n\nNODE(ExprNode_StructLiteral, {\n    os << m_path << \" { \";\n    for(const auto& v : m_values)\n    {\n        os << v.name << \": \" << *v.value << \", \";\n    }\n    if(m_base_value)\n    {\n        os << \"..\" << *m_base_value;\n    }\n    os << \"}\";\n},{\n    ExprNode_StructLiteral::t_values    vals;\n\n    for(const auto& v : m_values) {\n        vals.push_back({ v.attrs.clone(), v.name, v.value->clone() });\n    }\n\n    return NEWNODE(ExprNode_StructLiteral, AST::Path(m_path), OPT_CLONE(m_base_value), mv$(vals) );\n})\n\nNODE(ExprNode_Array, {\n    os << \"[\";\n    if( m_size.get() )\n        os << *m_values[0] << \"; \" << *m_size;\n    else\n        for(const auto& a : m_values)\n            os << *a << \",\";\n    os << \"]\";\n},{\n    if( m_size.get() )\n    {\n        return NEWNODE(ExprNode_Array, m_values[0]->clone(), m_size->clone());\n    }\n    else\n    {\n        ::std::vector<ExprNodeP>    nodes;\n        for(const auto& n : m_values)\n            nodes.push_back( n->clone() );\n        return NEWNODE(ExprNode_Array, mv$(nodes));\n    }\n})\n\nNODE(ExprNode_Tuple, {\n    os << \"(\";\n    for(const auto& a : m_values) {\n        os << *a << \",\";\n    }\n    os << \")\";\n},{\n    ::std::vector<ExprNodeP>    nodes;\n    for(const auto& n : m_values)\n        nodes.push_back( n->clone() );\n    return NEWNODE(ExprNode_Tuple, mv$(nodes));\n})\n\nNODE(ExprNode_NamedValue, {\n    m_path.print_pretty(os, false);\n    \/\/os << m_path;\n},{\n    return NEWNODE(ExprNode_NamedValue, AST::Path(m_path));\n})\n\nNODE(ExprNode_Field, {\n    os << \"(\" << *m_obj << \").\" << m_name;\n},{\n    return NEWNODE(ExprNode_Field, m_obj->clone(), m_name);\n})\n\nNODE(ExprNode_Index, {\n    os << \"(\" << *m_obj << \")[\" << *m_idx << \"]\";\n},{\n    return NEWNODE(ExprNode_Index, m_obj->clone(), m_idx->clone());\n})\n\nNODE(ExprNode_Deref, {\n    os << \"*(\" << *m_value << \")\";\n},{\n    return NEWNODE(ExprNode_Deref, m_value->clone());\n});\n\nNODE(ExprNode_Cast, {\n    os << \"(\" << *m_value << \" as \" << m_type << \")\";\n},{\n    return NEWNODE(ExprNode_Cast, m_value->clone(), m_type.clone());\n})\nNODE(ExprNode_TypeAnnotation, {\n    os << \"(\" << *m_value << \": \" << m_type << \")\";\n},{\n    return NEWNODE(ExprNode_TypeAnnotation, m_value->clone(), m_type.clone());\n})\n\nNODE(ExprNode_BinOp, {\n    if( m_type == RANGE_INC ) {\n        os << \"(\";\n        if( m_left ) {\n            os << *m_left << \" \";\n        }\n        os << \"... \" << *m_right;\n        os << \")\";\n        return ;\n    }\n    if( m_type == RANGE ) {\n        os << \"(\";\n        if( m_left ) {\n            os << *m_left;\n        }\n        os << \"..\";\n        if( m_right ) {\n            os << \" \" << *m_right;\n        }\n        os << \")\";\n        return ;\n    }\n    os << \"(\" << *m_left << \" \";\n    switch(m_type)\n    {\n    case CMPEQU:    os << \"==\"; break;\n    case CMPNEQU:   os << \"!=\"; break;\n    case CMPLT:     os << \"<\";  break;\n    case CMPLTE:    os << \"<=\"; break;\n    case CMPGT:     os << \">\";  break;\n    case CMPGTE:    os << \">=\"; break;\n    case BOOLAND:   os << \"&&\"; break;\n    case BOOLOR:    os << \"||\"; break;\n    case BITAND:    os << \"&\"; break;\n    case BITOR:     os << \"|\"; break;\n    case BITXOR:    os << \"^\"; break;\n    case SHR:    os << \">>\"; break;\n    case SHL:    os << \"<<\"; break;\n    case MULTIPLY: os << \"*\"; break;\n    case DIVIDE:   os << \"\/\"; break;\n    case MODULO:   os << \"%\"; break;\n    case ADD:   os << \"+\"; break;\n    case SUB:   os << \"-\"; break;\n    case RANGE:   os << \"..\"; break;\n    case RANGE_INC:   os << \"...\"; break;\n    case PLACE_IN:  os << \"<-\"; break;\n    }\n    os << \" \" << *m_right << \")\";\n},{\n    return NEWNODE(ExprNode_BinOp, m_type, OPT_CLONE(m_left), OPT_CLONE(m_right));\n})\n\nNODE(ExprNode_UniOp, {\n    switch(m_type)\n    {\n    case NEGATE: os << \"(-\"; break;\n    case INVERT: os << \"(!\"; break;\n    case BOX: os << \"(box \"; break;\n    case REF: os << \"(&\"; break;\n    case REFMUT: os << \"(&mut \"; break;\n    case RawBorrow: os << \"(&raw const \"; break;\n    case RawBorrowMut: os << \"(&raw mut \"; break;\n    case QMARK: os << \"(\" << *m_value << \"?)\"; return;\n    }\n    os << *m_value << \")\";\n},{\n    return NEWNODE(ExprNode_UniOp, m_type, m_value->clone());\n})\n\n\n#define NV(type, actions)\\\n    void NodeVisitorDef::visit(type& node) { \/*DEBUG(\"DEF - \"#type);*\/ actions }\n\/\/  void NodeVisitorDef::visit(const type& node) { DEBUG(\"DEF - \"#type\" (const)\"); actions }\n\nNV(ExprNode_Block, {\n    \/\/INDENT();\n    for( auto& child : node.m_nodes )\n        visit(child);\n    \/\/UNINDENT();\n})\nNV(ExprNode_Try, {\n    visit(node.m_inner);\n})\nNV(ExprNode_Macro,\n{\n    BUG(node.span(), \"Hit unexpanded macro in expression - \" << node);\n})\nNV(ExprNode_Asm,\n{\n    for(auto& v : node.m_output)\n        visit(v.value);\n    for(auto& v : node.m_input)\n        visit(v.value);\n})\nNV(ExprNode_Asm2,\n{\n    for(auto& v : node.m_params)\n    {\n        TU_MATCH_HDRA((v), {)\n        TU_ARMA(Const, e) {\n            visit(e);\n            }\n        TU_ARMA(Sym, e) {\n            \/\/visit(e);\n            }\n        TU_ARMA(RegSingle, e) {\n            visit(e.val);\n            }\n        TU_ARMA(Reg, e) {\n            visit(e.val_in);\n            visit(e.val_out);\n            }\n        }\n    }\n})\nNV(ExprNode_Flow,\n{\n    visit(node.m_value);\n})\nNV(ExprNode_LetBinding,\n{\n    \/\/ TODO: Handle recurse into Let pattern?\n    visit(node.m_value);\n})\nNV(ExprNode_Assign,\n{\n    INDENT();\n    visit(node.m_slot);\n    visit(node.m_value);\n    UNINDENT();\n})\nNV(ExprNode_CallPath,\n{\n    INDENT();\n    for( auto& arg : node.m_args )\n        visit(arg);\n    UNINDENT();\n})\nNV(ExprNode_CallMethod,\n{\n    INDENT();\n    visit(node.m_val);\n    for( auto& arg : node.m_args )\n        visit(arg);\n    UNINDENT();\n})\nNV(ExprNode_CallObject,\n{\n    INDENT();\n    visit(node.m_val);\n    for( auto& arg : node.m_args )\n        visit(arg);\n    UNINDENT();\n})\nNV(ExprNode_Loop,\n{\n    INDENT();\n    visit(node.m_cond);\n    visit(node.m_code);\n    UNINDENT();\n})\nNV(ExprNode_Match,\n{\n    INDENT();\n    visit(node.m_val);\n    for( auto& arm : node.m_arms )\n    {\n        visit(arm.m_cond);\n        visit(arm.m_code);\n    }\n    UNINDENT();\n})\nNV(ExprNode_If,\n{\n    INDENT();\n    visit(node.m_cond);\n    visit(node.m_true);\n    visit(node.m_false);\n    UNINDENT();\n})\nNV(ExprNode_IfLet,\n{\n    INDENT();\n    visit(node.m_value);\n    visit(node.m_true);\n    visit(node.m_false);\n    UNINDENT();\n})\n\nNV(ExprNode_Integer, {(void)node;})\nNV(ExprNode_Float, {(void)node;})\nNV(ExprNode_Bool, {(void)node;})\nNV(ExprNode_String, {(void)node;})\nNV(ExprNode_ByteString, {(void)node;})\n\nNV(ExprNode_Closure,\n{\n    visit(node.m_code);\n});\nNV(ExprNode_StructLiteral,\n{\n    visit(node.m_base_value);\n    for( auto& val : node.m_values )\n        visit(val.value);\n})\nNV(ExprNode_Array,\n{\n    visit(node.m_size);\n    for( auto& val : node.m_values )\n        visit(val);\n})\nNV(ExprNode_Tuple,\n{\n    for( auto& val : node.m_values )\n        visit(val);\n})\nNV(ExprNode_NamedValue,\n{\n    (void)node;\n    \/\/ LEAF\n})\n\nNV(ExprNode_Field,\n{\n    visit(node.m_obj);\n})\nNV(ExprNode_Index,\n{\n    visit(node.m_obj);\n    visit(node.m_idx);\n})\nNV(ExprNode_Deref,\n{\n    visit(node.m_value);\n})\nNV(ExprNode_Cast,\n{\n    visit(node.m_value);\n})\nNV(ExprNode_TypeAnnotation,\n{\n    visit(node.m_value);\n})\nNV(ExprNode_BinOp,\n{\n    visit(node.m_left);\n    visit(node.m_right);\n})\nNV(ExprNode_UniOp,\n{\n    visit(node.m_value);\n})\n#undef NV\n\n\n};\n\n","avg_line_length":23.4031209363,"max_line_length":155,"alphanum_fraction":0.512252042,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1805,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause-Clear"],"max_stars_count":null,"content":"\/\/ Author: Ivan Sovic\n\n#include <cstdlib>\n#include <iostream>\n#include <stdexcept>\n\n#include <pbcopper\/cli2\/CLI.h>\n\n#include <pacbio\/Version.h>\n\n#include <pacbio\/overlaphifi\/OverlapHifiSettings.h>\n#include \"dbfilter\/DBFilterSettings.h\"\n#include \"dbfilter\/DBFilterWorkflow.h\"\n#include \"overlaphifi\/OverlapHifiWorkflow.h\"\n#include \"seeddb\/SeedDBSettings.h\"\n#include \"seeddb\/SeedDBWorkflow.h\"\n#include \"seqdb\/SeqDBSettings.h\"\n#include \"seqdb\/SeqDBWorkflow.h\"\n#include \"seqfetch\/SeqFetchSettings.h\"\n#include \"seqfetch\/SeqFetchWorkflow.h\"\n\nPacBio::CLI_v2::MultiToolInterface CreateMultiInterface()\n{\n    PacBio::CLI_v2::MultiToolInterface mi{\"pancake\", \"PacBio HiFi overlapper.\",\n                                          PacBio::Pancake::PancakeFormattedVersion()};\n\n    \/\/ clang-format off\n    mi.AddTools(\n    {\n        {\"seqdb\",\n            PacBio::Pancake::SeqDBSettings::CreateCLI(),\n           &PacBio::Pancake::SeqDBWorkflow::Runner},\n        {\"seeddb\",\n            PacBio::Pancake::SeedDB::SeedDBSettings::CreateCLI(),\n           &PacBio::Pancake::SeedDB::SeedDBWorkflow::Runner},\n        {\"ovl-hifi\",\n            PacBio::Pancake::OverlapHifiSettings::CreateCLI(),\n           &PacBio::Pancake::OverlapHifiWorkflow::Runner},\n        {\"dbfilter\",\n            PacBio::Pancake::DBFilterSettings::CreateCLI(),\n           &PacBio::Pancake::DBFilterWorkflow::Runner},\n        {\"seqfetch\",\n            PacBio::Pancake::SeqFetchSettings::CreateCLI(),\n           &PacBio::Pancake::SeqFetchWorkflow::Runner},\n    });\n\n    \/\/ clang-format on\n    return mi;\n}\n\nint main(int argc, char* argv[])\n{\n    try {\n        return PacBio::CLI_v2::Run(argc, argv, CreateMultiInterface());\n    } catch (const std::exception& e) {\n        std::cerr << \"Pancake ERROR: \" << e.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n}","avg_line_length":30.593220339,"max_line_length":86,"alphanum_fraction":0.6421052632,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":913,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/\/ test040b.cpp - multiple translation units, part 2\n\n#include <rntcsv.h>\n#include \"unittest.h\"\n\nint help_func()\n{\n  int rv = 0;\n\n  std::string csv =\n    \"-,A,B,C\\n\"\n    \"1,3,9,81\\n\"\n    \"2,4,16,256\\n\"\n  ;\n\n  std::string path = unittest::TempPath();\n  unittest::WriteFile(path, csv);\n\n  try\n  {\n    rntcsv::document doc(path, rntcsv::label_parameters(0, 0));\n    unittest::ExpectEqual(int, doc.cell<int>(0, 0), 3);\n    unittest::ExpectEqual(int, doc.cell<int>(1, 0), 9);\n    unittest::ExpectEqual(int, doc.cell<int>(2, 0), 81);\n\n    unittest::ExpectEqual(std::string, doc.cell<std::string>(\"A\", \"2\"), \"4\");\n    unittest::ExpectEqual(std::string, doc.cell<std::string>(\"B\", \"2\"), \"16\");\n    unittest::ExpectEqual(std::string, doc.cell<std::string>(\"C\", \"2\"), \"256\");\n  }\n  catch (const std::exception& ex)\n  {\n    std::cout << ex.what() << std::endl;\n    rv = 1;\n  }\n\n  unittest::DeleteFile(path);\n\n  return rv;\n}\n","avg_line_length":22.825,"max_line_length":79,"alphanum_fraction":0.5980284775,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":23032,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/****************************************************************************\nCopyright (c) 2013      Zynga Inc.\nCopyright (c) 2013-2016 Chukong Technologies Inc.\nCopyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.\n \nhttp:\/\/www.cocos2d-x.org\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n****************************************************************************\/\n\n#include \"2d\/CCFontFreeType.h\"\n#include FT_BBOX_H\n#include \"edtaa3func.h\"\n#include \"2d\/CCFontAtlas.h\"\n#include \"base\/CCDirector.h\"\n#include \"base\/ccUTF8.h\"\n#include \"platform\/CCFileUtils.h\"\n#include \"platform\/CCFileStream.h\"\n\nNS_CC_BEGIN\n\n\nFT_Library FontFreeType::_FTlibrary;\nbool       FontFreeType::_FTInitialized = false;\nbool       FontFreeType::_streamParsingEnabled = false;\nconst int  FontFreeType::DistanceMapSpread = 3;\n\nconst char* FontFreeType::_glyphASCII = \"\\\"!#$%&'()*+,-.\/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u00a1\u00a2\u00a3\u00a4\u00a5\u00a6\u00a7\u00a8\u00a9\u00aa\u00ab\u00ac\u00ad\u00ae\u00af\u00b0\u00b1\u00b2\u00b3\u00b4\u00b5\u00b6\u00b7\u00b8\u00b9\u00ba\u00bb\u00bc\u00bd\u00be\u00bf\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00c6\u00c7\u00c8\u00c9\u00ca\u00cb\u00cc\u00cd\u00ce\u00cf\u00d0\u00d1\u00d2\u00d3\u00d4\u00d5\u00d6\u00d7\u00d8\u00d9\u00da\u00db\u00dc\u00dd\u00de\u00df\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u00e7\u00e8\u00e9\u00ea\u00eb\u00ec\u00ed\u00ee\u00ef\u00f0\u00f1\u00f2\u00f3\u00f4\u00f5\u00f6\u00f7\u00f8\u00f9\u00fa\u00fb\u00fc\u00fd\u00fe \";\nconst char* FontFreeType::_glyphNEHE = \"!\\\"#$%&'()*+,-.\/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ \";\n\ntypedef struct _DataRef\n{\n    Data data;\n    unsigned int referenceCount;\n}DataRef;\n\nstatic std::unordered_map<std::string, DataRef> s_cacheFontData;\n\n\/\/ ------ freetype2 stream parsing support ---\nstatic unsigned long ft_stream_read_callback(FT_Stream stream, unsigned long offset, unsigned char* buf, unsigned long size) {\n    auto fd = (FileStream*)stream->descriptor.pointer;\n    if (!fd) return 1;\n    if (!size && offset >= stream->size) return 1;\n\n    if (stream->pos != offset)\n        fd->seek(offset, SEEK_SET);\n\n    if (buf)\n        return fd->read(buf, size);\n\n    return 0;\n}\n\nstatic void ft_stream_close_callback(FT_Stream stream) {\n    auto fd = (FileStream*)stream->descriptor.pointer;\n    if (fd) delete fd;\n    stream->size = 0;\n    stream->descriptor.pointer = nullptr;\n}\n\nFontFreeType * FontFreeType::create(const std::string &fontName, float fontSize, GlyphCollection glyphs, const char *customGlyphs,bool distanceFieldEnabled \/* = false *\/,float outline \/* = 0 *\/)\n{\n    FontFreeType *tempFont =  new (std::nothrow) FontFreeType(distanceFieldEnabled,outline);\n\n    if (!tempFont)\n        return nullptr;\n    \n    tempFont->setGlyphCollection(glyphs, customGlyphs);\n    \n    if (!tempFont->createFontObject(fontName, fontSize))\n    {\n        delete tempFont;\n        return nullptr;\n    }\n    tempFont->autorelease();\n    return tempFont;\n}\n\nbool FontFreeType::initFreeType()\n{\n    if (_FTInitialized == false)\n    {\n        \/\/ begin freetype\n        if (FT_Init_FreeType( &_FTlibrary ))\n            return false;\n        \n        _FTInitialized = true;\n    }\n    \n    return  _FTInitialized;\n}\n\nvoid FontFreeType::shutdownFreeType()\n{\n    if (_FTInitialized == true)\n    {\n        FT_Done_FreeType(_FTlibrary);\n        s_cacheFontData.clear();\n        _FTInitialized = false;\n    }\n}\n\nFT_Library FontFreeType::getFTLibrary()\n{\n    initFreeType();\n    return _FTlibrary;\n}\n\nFontFreeType::FontFreeType(bool distanceFieldEnabled \/* = false *\/, float outline \/* = 0 *\/)\n: _fontRef(nullptr)\n, _stroker(nullptr)\n, _encoding(FT_ENCODING_UNICODE)\n, _distanceFieldEnabled(distanceFieldEnabled)\n, _outlineSize(0.0f)\n, _lineHeight(0)\n, _fontAtlas(nullptr)\n, _usedGlyphs(GlyphCollection::ASCII)\n{\n    if (outline > 0.0f)\n    {\n        _outlineSize = outline * CC_CONTENT_SCALE_FACTOR();\n        FT_Stroker_New(FontFreeType::getFTLibrary(), &_stroker);\n        FT_Stroker_Set(_stroker,\n            (int)(_outlineSize * 64),\n            FT_STROKER_LINECAP_ROUND,\n            FT_STROKER_LINEJOIN_ROUND,\n            0);\n    }\n}\n\nbool FontFreeType::createFontObject(const std::string &fontName, float fontSize)\n{\n    FT_Face face;\n    \/\/ save font name locally\n    _fontName = fontName;\n\n    if (!_streamParsingEnabled) {\n        auto it = s_cacheFontData.find(fontName);\n        if (it != s_cacheFontData.end())\n        {\n            (*it).second.referenceCount += 1;\n        }\n        else\n        {\n            s_cacheFontData[fontName].referenceCount = 1;\n            s_cacheFontData[fontName].data = FileUtils::getInstance()->getDataFromFile(fontName);\n\n            if (s_cacheFontData[fontName].data.isNull())\n            {\n                return false;\n            }\n        }\n\n        if (FT_New_Memory_Face(getFTLibrary(), s_cacheFontData[fontName].data.getBytes(), s_cacheFontData[fontName].data.getSize(), 0, &face))\n            return false;\n    }\n    else {\n        auto fullPath = FileUtils::getInstance()->fullPathForFilename(fontName);\n        if (fullPath.empty()) return false;\n\n        FileStream fs;\n        if (!fs.open(fullPath, FileStream::Mode::READ))\n            return false;\n\n        std::unique_ptr<FT_StreamRec> fts(new FT_StreamRec());\n        fts->read = ft_stream_read_callback;\n        fts->close = ft_stream_close_callback;\n        fts->size = fs.seek(0, SEEK_END);\n        fs.seek(0, SEEK_SET);\n\n        fts->descriptor.pointer = new FileStream(std::move(fs));\n\n        FT_Open_Args args = { 0 };\n        args.flags = FT_OPEN_STREAM;\n        args.stream = fts.get();;\n\n        if (FT_Open_Face(getFTLibrary(), &args, 0, &face))\n            return false;\n\n        _fontStream = std::move(fts);\n    }\n\n    if (FT_Select_Charmap(face, FT_ENCODING_UNICODE))\n    {\n        int foundIndex = -1;\n        for (int charmapIndex = 0; charmapIndex < face->num_charmaps; charmapIndex++)\n        {\n            if (face->charmaps[charmapIndex]->encoding != FT_ENCODING_NONE)\n            {\n                foundIndex = charmapIndex;\n                break;\n            }\n        }\n\n        if (foundIndex == -1)\n        {\n            return false;\n        }\n\n        _encoding = face->charmaps[foundIndex]->encoding;\n        if (FT_Select_Charmap(face, _encoding))\n        {\n            return false;\n        }\n    }\n\n    \/\/ set the requested font size\n    int dpi = 72;\n    int fontSizePoints = (int)(64.f * fontSize * CC_CONTENT_SCALE_FACTOR());\n    if (FT_Set_Char_Size(face, fontSizePoints, fontSizePoints, dpi, dpi))\n        return false;\n    \n    \/\/ store the face globally\n    _fontRef = face;\n    _lineHeight = static_cast<int>((_fontRef->size->metrics.ascender - _fontRef->size->metrics.descender) >> 6);\n    \n    \/\/ done and good\n    return true;\n}\n\nFontFreeType::~FontFreeType()\n{\n    if (_FTInitialized)\n    {\n        if (_stroker)\n        {\n            FT_Stroker_Done(_stroker);\n        }\n        if (_fontRef)\n        {\n            FT_Done_Face(_fontRef);\n        }\n    }\n\n    auto iter = s_cacheFontData.find(_fontName);\n    if (iter != s_cacheFontData.end())\n    {\n        iter->second.referenceCount -= 1;\n        if (iter->second.referenceCount == 0)\n        {\n            s_cacheFontData.erase(iter);\n        }\n    }\n}\n\nFontAtlas * FontFreeType::createFontAtlas()\n{\n    if (_fontAtlas == nullptr)\n    {\n        _fontAtlas = new (std::nothrow) FontAtlas(*this);\n        if (_fontAtlas && _usedGlyphs != GlyphCollection::DYNAMIC)\n        {\n            std::u32string utf32;\n            if (StringUtils::UTF8ToUTF32(getGlyphCollection(), utf32))\n            {\n                _fontAtlas->prepareLetterDefinitions(utf32);\n            }\n        }\n\/\/        this->autorelease();\n    }\n    \n    return _fontAtlas;\n}\n\nint * FontFreeType::getHorizontalKerningForTextUTF32(const std::u32string& text, int &outNumLetters) const\n{\n    if (!_fontRef)\n        return nullptr;\n    \n    outNumLetters = static_cast<int>(text.length());\n\n    if (!outNumLetters)\n        return nullptr;\n    \n    int *sizes = new (std::nothrow) int[outNumLetters];\n    if (!sizes)\n        return nullptr;\n    memset(sizes,0,outNumLetters * sizeof(int));\n\n    bool hasKerning = FT_HAS_KERNING( _fontRef ) != 0;\n    if (hasKerning)\n    {\n        for (int c = 1; c < outNumLetters; ++c)\n        {\n            sizes[c] = getHorizontalKerningForChars(text[c-1], text[c]);\n        }\n    }\n    \n    return sizes;\n}\n\nint  FontFreeType::getHorizontalKerningForChars(uint64_t firstChar, uint64_t secondChar) const\n{\n    \/\/ get the ID to the char we need\n    int glyphIndex1 = FT_Get_Char_Index(_fontRef, static_cast<FT_ULong>(firstChar));\n    \n    if (!glyphIndex1)\n        return 0;\n    \n    \/\/ get the ID to the char we need\n    int glyphIndex2 = FT_Get_Char_Index(_fontRef, static_cast<FT_ULong>(secondChar));\n    \n    if (!glyphIndex2)\n        return 0;\n    \n    FT_Vector kerning;\n    \n    if (FT_Get_Kerning( _fontRef, glyphIndex1, glyphIndex2,  FT_KERNING_DEFAULT,  &kerning))\n        return 0;\n    \n    return (static_cast<int>(kerning.x >> 6));\n}\n\nint FontFreeType::getFontAscender() const\n{\n    return (static_cast<int>(_fontRef->size->metrics.ascender >> 6));\n}\n\nconst char* FontFreeType::getFontFamily() const\n{\n    if (!_fontRef)\n        return nullptr;\n\n    return _fontRef->family_name;\n}\n\nunsigned char* FontFreeType::getGlyphBitmap(uint64_t theChar, long &outWidth, long &outHeight, Rect &outRect,int &xAdvance)\n{\n    bool invalidChar = true;\n    unsigned char* ret = nullptr;\n\n    do\n    {\n        if (_fontRef == nullptr)\n            break;\n\n        \/\/ @remark: glyph_index=0 means \n        auto glyph_index = FT_Get_Char_Index(_fontRef, static_cast<FT_ULong>(theChar));\n        if (FT_Load_Glyph(_fontRef, glyph_index, _distanceFieldEnabled ? \n            (FT_LOAD_RENDER | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT) : \n            (FT_LOAD_RENDER | FT_LOAD_NO_AUTOHINT)))\n            break;\n\n#if defined(_DEBUG)\n        if (glyph_index == 0) {\n            std::u32string charUTF32(1, theChar);\n            std::string charUTF8;\n            cocos2d::StringUtils::UTF32ToUTF8(charUTF32, charUTF8);\n\n            if (charUTF8 == \"\\n\") charUTF8 = \"\\\\n\";\n            cocos2d::log(\"The font face: %s doesn't contains char: <%s>\", _fontRef->charmap->face->family_name, charUTF8.c_str());\n        }\n#endif\n\n        auto& metrics = _fontRef->glyph->metrics;\n        outRect.origin.x = static_cast<float>(metrics.horiBearingX >> 6);\n        outRect.origin.y = static_cast<float>(-(metrics.horiBearingY >> 6));\n        outRect.size.width = static_cast<float>((metrics.width >> 6));\n        outRect.size.height = static_cast<float>((metrics.height >> 6));\n\n        xAdvance = (static_cast<int>(_fontRef->glyph->metrics.horiAdvance >> 6));\n\n        outWidth  = _fontRef->glyph->bitmap.width;\n        outHeight = _fontRef->glyph->bitmap.rows;\n        ret = _fontRef->glyph->bitmap.buffer;\n\n        if (_outlineSize > 0 && outWidth > 0 && outHeight > 0)\n        {\n            auto copyBitmap = new (std::nothrow) unsigned char[outWidth * outHeight];\n            memcpy(copyBitmap,ret,outWidth * outHeight * sizeof(unsigned char));\n\n            FT_BBox bbox;\n            auto outlineBitmap = getGlyphBitmapWithOutline(theChar,bbox);\n            if(outlineBitmap == nullptr)\n            {\n                ret = nullptr;\n                delete [] copyBitmap;\n                break;\n            }\n\n            int glyphMinX = (int)outRect.origin.x;\n            int glyphMaxX = (int)(outRect.origin.x + outWidth);\n            int glyphMinY = (int)(-outHeight - outRect.origin.y);\n            int glyphMaxY = (int)-outRect.origin.y;\n\n            auto outlineMinX = bbox.xMin >> 6;\n            auto outlineMaxX = bbox.xMax >> 6;\n            auto outlineMinY = bbox.yMin >> 6;\n            auto outlineMaxY = bbox.yMax >> 6;\n            auto outlineWidth = outlineMaxX - outlineMinX;\n            auto outlineHeight = outlineMaxY - outlineMinY;\n\n            auto blendImageMinX = MIN(outlineMinX, glyphMinX);\n            auto blendImageMaxY = MAX(outlineMaxY, glyphMaxY);\n            auto blendWidth = MAX(outlineMaxX, glyphMaxX) - blendImageMinX;\n            auto blendHeight = blendImageMaxY - MIN(outlineMinY, glyphMinY);\n\n            outRect.origin.x = (float)blendImageMinX;\n            outRect.origin.y = -blendImageMaxY + _outlineSize;\n\n            unsigned char *blendImage = nullptr;\n            if (blendWidth > 0 && blendHeight > 0)\n            {\n                FT_Pos index, index2;\n                auto imageSize = blendWidth * blendHeight * 2;\n                blendImage = new (std::nothrow) unsigned char[imageSize];\n                memset(blendImage, 0, imageSize);\n\n                auto px = outlineMinX - blendImageMinX;\n                auto py = blendImageMaxY - outlineMaxY;\n                for (int x = 0; x < outlineWidth; ++x)\n                {\n                    for (int y = 0; y < outlineHeight; ++y)\n                    {\n                        index = px + x + ((py + y) * blendWidth);\n                        index2 = x + (y * outlineWidth);\n                        blendImage[2 * index] = outlineBitmap[index2];\n                    }\n                }\n\n                px = glyphMinX - blendImageMinX;\n                py = blendImageMaxY - glyphMaxY;\n                for (int x = 0; x < outWidth; ++x)\n                {\n                    for (int y = 0; y < outHeight; ++y)\n                    {\n                        index = px + x + ((y + py) * blendWidth);\n                        index2 = x + (y * outWidth);\n                        blendImage[2 * index + 1] = copyBitmap[index2];\n                    }\n                }\n            }\n\n            outRect.size.width  = (float)blendWidth;\n            outRect.size.height = (float)blendHeight;\n            outWidth  = blendWidth;\n            outHeight = blendHeight;\n\n            delete [] outlineBitmap;\n            delete [] copyBitmap;\n            ret = blendImage;\n        }\n\n        invalidChar = false;\n    } while (0);\n\n    if (invalidChar)\n    {\n        outRect.size.width  = 0;\n        outRect.size.height = 0;\n        xAdvance = 0;\n\n        return nullptr;\n    }\n    else\n    {\n       return ret;\n    }\n}\n\nunsigned char * FontFreeType::getGlyphBitmapWithOutline(uint64_t theChar, FT_BBox &bbox)\n{   \n    unsigned char* ret = nullptr;\n    if (FT_Load_Char(_fontRef, static_cast<FT_ULong>(theChar), FT_LOAD_NO_BITMAP) == 0)\n    {\n        if (_fontRef->glyph->format == FT_GLYPH_FORMAT_OUTLINE)\n        {\n            FT_Glyph glyph;\n            if (FT_Get_Glyph(_fontRef->glyph, &glyph) == 0)\n            {\n                FT_Glyph_StrokeBorder(&glyph, _stroker, 0, 1);\n                if (glyph->format == FT_GLYPH_FORMAT_OUTLINE)\n                {\n                    FT_Outline *outline = &reinterpret_cast<FT_OutlineGlyph>(glyph)->outline;\n                    FT_Glyph_Get_CBox(glyph,FT_GLYPH_BBOX_GRIDFIT,&bbox);\n                    long width = (bbox.xMax - bbox.xMin)>>6;\n                    long rows = (bbox.yMax - bbox.yMin)>>6;\n\n                    FT_Bitmap bmp;\n                    bmp.buffer = new (std::nothrow) unsigned char[width * rows];\n                    memset(bmp.buffer, 0, width * rows);\n                    bmp.width = (int)width;\n                    bmp.rows = (int)rows;\n                    bmp.pitch = (int)width;\n                    bmp.pixel_mode = FT_PIXEL_MODE_GRAY;\n                    bmp.num_grays = 256;\n\n                    FT_Raster_Params params;\n                    memset(&params, 0, sizeof (params));\n                    params.source = outline;\n                    params.target = &bmp;\n                    params.flags = FT_RASTER_FLAG_AA;\n                    FT_Outline_Translate(outline,-bbox.xMin,-bbox.yMin);\n                    FT_Outline_Render(_FTlibrary, outline, &params);\n\n                    ret = bmp.buffer;\n                }\n                FT_Done_Glyph(glyph);\n            }\n        }\n    }\n\n    return ret;\n}\n\nunsigned char * makeDistanceMap( unsigned char *img, long width, long height)\n{\n    long pixelAmount = (width + 2 * FontFreeType::DistanceMapSpread) * (height + 2 * FontFreeType::DistanceMapSpread);\n\n    short * xdist = (short *)  malloc( pixelAmount * sizeof(short) );\n    short * ydist = (short *)  malloc( pixelAmount * sizeof(short) );\n    double * gx   = (double *) calloc( pixelAmount, sizeof(double) );\n    double * gy      = (double *) calloc( pixelAmount, sizeof(double) );\n    double * data    = (double *) calloc( pixelAmount, sizeof(double) );\n    double * outside = (double *) calloc( pixelAmount, sizeof(double) );\n    double * inside  = (double *) calloc( pixelAmount, sizeof(double) );\n    long i,j;\n\n    \/\/ Convert img into double (data) rescale image levels between 0 and 1\n    long outWidth = width + 2 * FontFreeType::DistanceMapSpread;\n    for (i = 0; i < width; ++i)\n    {\n        for (j = 0; j < height; ++j)\n        {\n            data[j * outWidth + FontFreeType::DistanceMapSpread + i] = img[j * width + i] \/ 255.0;\n        }\n    }\n\n    width += 2 * FontFreeType::DistanceMapSpread;\n    height += 2 * FontFreeType::DistanceMapSpread;\n\n    \/\/ Transform background (outside contour, in areas of 0's)   \n    computegradient( data, (int)width, (int)height, gx, gy);\n    edtaa3(data, gx, gy, (int)width, (int)height, xdist, ydist, outside);\n    for( i=0; i< pixelAmount; i++)\n        if( outside[i] < 0.0 )\n            outside[i] = 0.0;\n\n    \/\/ Transform foreground (inside contour, in areas of 1's)   \n    for( i=0; i< pixelAmount; i++)\n        data[i] = 1 - data[i];\n    computegradient( data, (int)width, (int)height, gx, gy);\n    edtaa3(data, gx, gy, (int)width, (int)height, xdist, ydist, inside);\n    for( i=0; i< pixelAmount; i++)\n        if( inside[i] < 0.0 )\n            inside[i] = 0.0;\n\n    \/\/ The bipolar distance field is now outside-inside\n    double dist;\n    \/* Single channel 8-bit output (bad precision and range, but simple) *\/    \n    unsigned char *out = (unsigned char *) malloc( pixelAmount * sizeof(unsigned char) );\n    for( i=0; i < pixelAmount; i++)\n    {\n        dist = outside[i] - inside[i];\n        dist = 128.0 - dist*16;\n        if( dist < 0 ) dist = 0;\n        if( dist > 255 ) dist = 255;\n        out[i] = (unsigned char) dist;\n    }\n    \/* Dual channel 16-bit output (more complicated, but good precision and range) *\/\n    \/*unsigned char *out = (unsigned char *) malloc( pixelAmount * 3 * sizeof(unsigned char) ); \n    for( i=0; i< pixelAmount; i++)\n    {\n        dist = outside[i] - inside[i];\n        dist = 128.0 - dist*16;\n        if( dist < 0.0 ) dist = 0.0;\n        if( dist >= 256.0 ) dist = 255.999;\n        \/\/ R channel is a copy of the original grayscale image\n        out[3*i] = img[i];\n        \/\/ G channel is fraction\n        out[3*i + 1] = (unsigned char) ( 256 - (dist - floor(dist)* 256.0 ));\n        \/\/ B channel is truncated integer part\n        out[3*i + 2] = (unsigned char)dist; \n    }*\/\n    \n    free( xdist );\n    free( ydist );\n    free( gx );\n    free( gy );\n    free( data );\n    free( outside );\n    free( inside );\n\n    return out;\n}\n\nvoid FontFreeType::renderCharAt(unsigned char *dest,int posX, int posY, unsigned char* bitmap,long bitmapWidth,long bitmapHeight)\n{\n    int iX = posX;\n    int iY = posY;\n\n    if (_distanceFieldEnabled)\n    {\n        auto distanceMap = makeDistanceMap(bitmap,bitmapWidth,bitmapHeight);\n\n        bitmapWidth += 2 * DistanceMapSpread;\n        bitmapHeight += 2 * DistanceMapSpread;\n\n        for (long y = 0; y < bitmapHeight; ++y)\n        {\n            long bitmap_y = y * bitmapWidth;\n\n            for (long x = 0; x < bitmapWidth; ++x)\n            {    \n                \/* Dual channel 16-bit output (more complicated, but good precision and range) *\/\n                \/*int index = (iX + ( iY * destSize )) * 3;                \n                int index2 = (bitmap_y + x)*3;\n                dest[index] = out[index2];\n                dest[index + 1] = out[index2 + 1];\n                dest[index + 2] = out[index2 + 2];*\/\n\n                \/\/Single channel 8-bit output \n                dest[iX + ( iY * FontAtlas::CacheTextureWidth )] = distanceMap[bitmap_y + x];\n\n                iX += 1;\n            }\n\n            iX  = posX;\n            iY += 1;\n        }\n        free(distanceMap);\n    }\n    else if(_outlineSize > 0)\n    {\n        unsigned char tempChar;\n        for (long y = 0; y < bitmapHeight; ++y)\n        {\n            long bitmap_y = y * bitmapWidth;\n\n            for (int x = 0; x < bitmapWidth; ++x)\n            {\n                tempChar = bitmap[(bitmap_y + x) * 2];\n                dest[(iX + ( iY * FontAtlas::CacheTextureWidth ) ) * 2] = tempChar;\n                tempChar = bitmap[(bitmap_y + x) * 2 + 1];\n                dest[(iX + ( iY * FontAtlas::CacheTextureWidth ) ) * 2 + 1] = tempChar;\n\n                iX += 1;\n            }\n\n            iX  = posX;\n            iY += 1;\n        }\n        delete [] bitmap;\n    }\n    else\n    {\n        for (long y = 0; y < bitmapHeight; ++y)\n        {\n            long bitmap_y = y * bitmapWidth;\n\n            for (int x = 0; x < bitmapWidth; ++x)\n            {\n                unsigned char cTemp = bitmap[bitmap_y + x];\n\n                \/\/ the final pixel\n                dest[(iX + ( iY * FontAtlas::CacheTextureWidth ) )] = cTemp;\n\n                iX += 1;\n            }\n\n            iX  = posX;\n            iY += 1;\n        }\n    } \n}\n\nvoid FontFreeType::setGlyphCollection(GlyphCollection glyphs, const char* customGlyphs \/* = nullptr *\/)\n{\n    _usedGlyphs = glyphs;\n    if (glyphs == GlyphCollection::CUSTOM)\n    {\n        _customGlyphs = customGlyphs;\n    }\n}\n\nconst char* FontFreeType::getGlyphCollection() const\n{\n    const char* glyphCollection = nullptr;\n    switch (_usedGlyphs)\n    {\n    case cocos2d::GlyphCollection::DYNAMIC:\n        break;\n    case cocos2d::GlyphCollection::NEHE:\n        glyphCollection = _glyphNEHE;\n        break;\n    case cocos2d::GlyphCollection::ASCII:\n        glyphCollection = _glyphASCII;\n        break;\n    case cocos2d::GlyphCollection::CUSTOM:\n        glyphCollection = _customGlyphs.c_str();\n        break;\n    default:\n        break;\n    }\n\n    return glyphCollection;\n}\n\nvoid FontFreeType::releaseFont(const std::string &fontName)\n{\n    auto item = s_cacheFontData.begin();\n    while (s_cacheFontData.end() != item)\n    {\n        if (item->first.find(fontName) != std::string::npos)\n            item = s_cacheFontData.erase(item);\n        else\n            item++;\n    }\n}\n\nNS_CC_END\n","avg_line_length":31.6373626374,"max_line_length":234,"alphanum_fraction":0.5745918722,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2162,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Copyright (c) 2016-2019 The OHONETWORK developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"chain.h\"\n\n\n\/**\n * CChain implementation\n *\/\nvoid CChain::SetTip(CBlockIndex* pindex)\n{\n    if (pindex == NULL) {\n        vChain.clear();\n        return;\n    }\n    vChain.resize(pindex->nHeight + 1);\n    while (pindex && vChain[pindex->nHeight] != pindex) {\n        vChain[pindex->nHeight] = pindex;\n        pindex = pindex->pprev;\n    }\n}\n\nCBlockLocator CChain::GetLocator(const CBlockIndex* pindex) const\n{\n    int nStep = 1;\n    std::vector<uint256> vHave;\n    vHave.reserve(32);\n\n    if (!pindex)\n        pindex = Tip();\n    while (pindex) {\n        vHave.push_back(pindex->GetBlockHash());\n        \/\/ Stop when we have added the genesis block.\n        if (pindex->nHeight == 0)\n            break;\n        \/\/ Exponentially larger steps back, plus the genesis block.\n        int nHeight = std::max(pindex->nHeight - nStep, 0);\n        if (Contains(pindex)) {\n            \/\/ Use O(1) CChain index if possible.\n            pindex = (*this)[nHeight];\n        } else {\n            \/\/ Otherwise, use O(log n) skiplist.\n            pindex = pindex->GetAncestor(nHeight);\n        }\n        if (vHave.size() > 10)\n            nStep *= 2;\n    }\n\n    return CBlockLocator(vHave);\n}\n\nconst CBlockIndex* CChain::FindFork(const CBlockIndex* pindex) const\n{\n    if (pindex->nHeight > Height())\n        pindex = pindex->GetAncestor(Height());\n    while (pindex && !Contains(pindex))\n        pindex = pindex->pprev;\n    return pindex;\n}\n\nuint256 CBlockIndex::GetBlockTrust() const\n{\n    uint256 bnTarget;\n    bnTarget.SetCompact(nBits);\n    if (bnTarget <= 0)\n        return 0;\n\n    if (IsProofOfStake()) {\n        \/\/ Return trust score as usual\n        return (uint256(1) << 256) \/ (bnTarget + 1);\n    } else {\n        \/\/ Calculate work amount for block\n        uint256 bnPoWTrust = ((~uint256(0) >> 20) \/ (bnTarget + 1));\n        return bnPoWTrust > 1 ? bnPoWTrust : 1;\n    }\n}","avg_line_length":27.3670886076,"max_line_length":70,"alphanum_fraction":0.5971322849,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":56645,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0","MIT"],"max_stars_count":null,"content":"#include \"SystemData.h\"\n\n#include \"SystemConf.h\"\n#include \"utils\/FileSystemUtil.h\"\n#include \"utils\/ThreadPool.h\"\n#include \"CollectionSystemManager.h\"\n#include \"FileFilterIndex.h\"\n#include \"FileSorts.h\"\n#include \"Gamelist.h\"\n#include \"Log.h\"\n#include \"platform.h\"\n#include \"Settings.h\"\n#include \"ThemeData.h\"\n#include \"views\/UIModeController.h\"\n#include <fstream>\n#include \"Window.h\"\n#include \"LocaleES.h\"\n#include \"utils\/StringUtil.h\"\n#include \"views\/ViewController.h\"\n#include \"ThreadedHasher.h\"\n#include <unordered_set>\n#include <algorithm>\n#include \"SaveStateRepository.h\"\n\n#if WIN32\n#include \"Win32ApiSystem.h\"\n#endif\n\nusing namespace Utils;\n\nstd::vector<SystemData*> SystemData::sSystemVector;\nstd::vector<CustomFeature> SystemData::mGlobalFeatures;\n\nSystemData::SystemData(const SystemMetadata& meta, SystemEnvironmentData* envData, std::vector<EmulatorData>* pEmulators, bool CollectionSystem, bool groupedSystem, bool withTheme, bool loadThemeOnlyIfElements) : \/\/ batocera\n\tmMetadata(meta), mEnvData(envData), mIsCollectionSystem(CollectionSystem), mIsGameSystem(true)\n{\n\tmSaveRepository = nullptr;\n\tmIsCheevosSupported = -1;\n\tmIsGroupSystem = groupedSystem;\n\tmGameListHash = 0;\n\tmGameCountInfo = nullptr;\n\tmSortId = Settings::getInstance()->getInt(getName() + \".sort\");\n\tmGridSizeOverride = Vector2f(0, 0);\n\n\tmFilterIndex = nullptr;\n\n\tif (pEmulators != nullptr)\n\t\tmEmulators = *pEmulators; \/\/ batocera\n\n\t\/\/ if it's an actual system, initialize it, if not, just create the data structure\n\tif (!CollectionSystem && !mIsGroupSystem)\n\t{\n\t\tmRootFolder = new FolderData(mEnvData->mStartPath, this);\n\t\tmRootFolder->getMetadata().set(MetaDataId::Name, mMetadata.fullName);\n\n\t\tstd::unordered_map<std::string, FileData*> fileMap;\n\t\tfileMap[mEnvData->mStartPath] = mRootFolder;\n\n\t\tif (!Settings::getInstance()->getBool(\"ParseGamelistOnly\"))\n\t\t{\n\t\t\tpopulateFolder(mRootFolder, fileMap);\n\t\t\tif (mRootFolder->getChildren().size() == 0)\n\t\t\t\treturn;\n\t\t}\n\n\t\tif(!Settings::getInstance()->getBool(\"IgnoreGamelist\")) \/\/ && !hasPlatformId(PlatformIds::IMAGEVIEWER))\n\t\t\tparseGamelist(this, fileMap);\n\t}\n\telse\n\t{\n\t\t\/\/ virtual systems are updated afterwards, we're just creating the data structure\n\t\tmRootFolder = new FolderData(\"\" + mMetadata.name, this);\n\t}\n\n\tmRootFolder->getMetadata().resetChangedFlag();\n\n\tif (withTheme && (!loadThemeOnlyIfElements || mRootFolder->mChildren.size() > 0))\n\t{\n\t\tloadTheme();\n\n\t\tauto defaultView = Settings::getInstance()->getString(getName() + \".defaultView\");\n\t\tauto gridSizeOverride = Vector2f::parseString(Settings::getInstance()->getString(getName() + \".gridSize\"));\n\t\tsetSystemViewMode(defaultView, gridSizeOverride, false);\n\n\t\tsetIsGameSystemStatus();\n\t}\n}\n\nSystemData::~SystemData()\n{\n\tdelete mRootFolder;\n\n\tif (mSaveRepository != nullptr)\n\t\tdelete mSaveRepository;\n\n\tif (mGameCountInfo != nullptr)\n\t\tdelete mGameCountInfo;\n\n\tif (mFilterIndex != nullptr)\n\t\tdelete mFilterIndex;\n}\n\nvoid SystemData::setIsGameSystemStatus()\n{\n\t\/\/ we exclude non-game systems from specific operations (i.e. the \"RetroPie\" system, at least)\n\t\/\/ if\/when there are more in the future, maybe this can be a more complex method, with a proper list\n\t\/\/ but for now a simple string comparison is more performant\n\tmIsGameSystem = (mMetadata.name != \"retropie\");\n}\n\nvoid SystemData::populateFolder(FolderData* folder, std::unordered_map<std::string, FileData*>& fileMap)\n{\n\tconst std::string& folderPath = folder->getPath();\n\n\tif(!Utils::FileSystem::isDirectory(folderPath))\n\t\treturn;\n\t\/*\n\t\/\/ [Obsolete] make sure that this isn't a symlink to a thing we already have\n\t\/\/ Deactivated because it's slow & useless : users should to be carefull not to make recursive simlinks\n\tif (Utils::FileSystem::isSymlink(folderPath))\n\t{\n\t\t\/\/if this symlink resolves to somewhere that's at the beginning of our path, it's gonna recurse\n\t\tif(folderPath.find(Utils::FileSystem::getCanonicalPath(folderPath)) == 0)\n\t\t{\n\t\t\tLOG(LogWarning) << \"Skipping infinitely recursive symlink \\\"\" << folderPath << \"\\\"\";\n\t\t\treturn;\n\t\t}\n\t}\n\t*\/\n\tstd::string filePath;\n\tstd::string extension;\n\tbool isGame;\n\tbool showHidden = Settings::getInstance()->getBool(\"ShowHiddenFiles\");\n\n\tauto shv = Settings::getInstance()->getString(getName() + \".ShowHiddenFiles\");\n\tif (shv == \"1\") showHidden = true;\n\telse if (shv == \"0\") showHidden = false;\n\n\tUtils::FileSystem::fileList dirContent = Utils::FileSystem::getDirectoryFiles(folderPath);\n\tfor (auto fileInfo : dirContent)\n\t{\n\t\tfilePath = fileInfo.path;\n\n\t\t\/\/ skip hidden files and folders\n\t\tif(!showHidden && fileInfo.hidden)\n\t\t\tcontinue;\n\n\t\t\/\/this is a little complicated because we allow a list of extensions to be defined (delimited with a space)\n\t\t\/\/we first get the extension of the file itself:\n\t\textension = Utils::String::toLower(Utils::FileSystem::getExtension(filePath));\n\n\t\t\/\/fyi, folders *can* also match the extension and be added as games - this is mostly just to support higan\n\t\t\/\/see issue #75: https:\/\/github.com\/Aloshi\/EmulationStation\/issues\/75\n\n\t\tisGame = false;\n\t\tif(mEnvData->isValidExtension(extension))\n\t\t{\n\t\t\tFileData* newGame = new FileData(GAME, filePath, this);\n\n\t\t\t\/\/ preventing new arcade assets to be added\n\t\t\tif(!newGame->isArcadeAsset())\n\t\t\t{\n\t\t\t\tfolder->addChild(newGame);\n\t\t\t\tfileMap[filePath] = newGame;\n\t\t\t\tisGame = true;\n\t\t\t}\n\t\t}\n\n\t\t\/\/add directories that also do not match an extension as folders\n\t\tif(!isGame && fileInfo.directory)\n\t\t{\n\t\t\tstd::string fn = Utils::String::toLower(Utils::FileSystem::getFileName(filePath));\n\n\t\t\t\/\/ Don't loose time looking in downloaded_images, downloaded_videos & media folders\n\t\t\tif (fn == \"media\" || fn == \"medias\" || fn == \"images\" || fn == \"manuals\" || fn == \"videos\" || fn == \"assets\" || Utils::String::startsWith(fn, \"downloaded_\") || Utils::String::startsWith(fn, \".\"))\n\t\t\t\tcontinue;\n\n\t\t\t\/\/ Hardcoded optimisation : WiiU has so many files in content & meta directories\n\t\t\tif (mMetadata.name == \"wiiu\" && (fn == \"content\" || fn == \"meta\"))\n\t\t\t\tcontinue;\n\n\t\t\tFolderData* newFolder = new FolderData(filePath, this);\n\t\t\tpopulateFolder(newFolder, fileMap);\n\n\t\t\t\/\/ignore folders that do not contain games\n\t\t\tif(newFolder->getChildren().size() == 0)\n\t\t\t\tdelete newFolder;\n\t\t\telse\n\t\t\t{\n\t\t\t\tconst std::string& key = newFolder->getPath();\n\t\t\t\tif (fileMap.find(key) == fileMap.end())\n\t\t\t\t{\n\t\t\t\t\tfolder->addChild(newFolder);\n\t\t\t\t\tfileMap[key] = newFolder;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nFileFilterIndex* SystemData::getIndex(bool createIndex)\n{\n\tif (mFilterIndex == nullptr && createIndex)\n\t{\n\t\tmFilterIndex = new FileFilterIndex();\n\t\tindexAllGameFilters(mRootFolder);\n\t\tmFilterIndex->setUIModeFilters();\n\t}\n\n\treturn mFilterIndex;\n}\n\nvoid SystemData::deleteIndex()\n{\n\tif (mFilterIndex != nullptr)\n\t{\n\t\tdelete mFilterIndex;\n\t\tmFilterIndex = nullptr;\n\t}\n}\n\nvoid SystemData::indexAllGameFilters(const FolderData* folder)\n{\n\tconst std::vector<FileData*>& children = folder->getChildren();\n\n\tfor(auto it = children.cbegin(); it != children.cend(); ++it)\n\t{\n\t\tswitch((*it)->getType())\n\t\t{\n\t\t\tcase GAME:   { mFilterIndex->addToIndex(*it); } break;\n\t\t\tcase FOLDER: { indexAllGameFilters((FolderData*)*it); } break;\n\t\t}\n\t}\n}\n\nstd::vector<std::string> readList(const std::string& str, const char* delims = \" \\t\\r\\n,\")\n{\n\tstd::vector<std::string> ret;\n\n\tsize_t prevOff = str.find_first_not_of(delims, 0);\n\tsize_t off = str.find_first_of(delims, prevOff);\n\twhile(off != std::string::npos || prevOff != std::string::npos)\n\t{\n\t\tret.push_back(str.substr(prevOff, off - prevOff));\n\n\t\tprevOff = str.find_first_not_of(delims, off);\n\t\toff = str.find_first_of(delims, prevOff);\n\t}\n\n\treturn ret;\n}\n\nvoid SystemData::createGroupedSystems()\n{\n\tstd::map<std::string, std::vector<SystemData*>> map;\n\n\tfor (auto sys : sSystemVector)\n\t{\n\t\tif (sys->isCollection() || sys->getSystemEnvData()->mGroup.empty())\n\t\t\tcontinue;\n\n\t\tif (Settings::getInstance()->getBool(sys->getSystemEnvData()->mGroup + \".ungroup\"))\n\t\t\tcontinue;\n\n\t\tif (sys->getName() == sys->getSystemEnvData()->mGroup)\n\t\t{\n\t\t\tsys->getSystemEnvData()->mGroup = \"\";\n\t\t\tcontinue;\n\t\t}\n\n\t\tmap[sys->getSystemEnvData()->mGroup].push_back(sys);\n\t}\n\n\tfor (auto item : map)\n\t{\n\t\tSystemData* system = nullptr;\n\t\tbool existingSystem = false;\n\n\t\tfor (auto sys : sSystemVector)\n\t\t{\n\t\t\tif (sys->getName() == item.first)\n\t\t\t{\n\t\t\t\texistingSystem = true;\n\t\t\t\tsystem = sys;\n\t\t\t\tsystem->mIsGroupSystem = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (system == nullptr)\n\t\t{\n\t\t\tSystemEnvironmentData* envData = new SystemEnvironmentData;\n\t\t\tenvData->mStartPath = \"\";\n\t\t\tenvData->mLaunchCommand = \"\";\n\n\t\t\tSystemMetadata md;\n\t\t\tmd.name = item.first;\n\t\t\tmd.fullName = item.first;\n\t\t\tmd.themeFolder = item.first;\n\n\t\t\t\/\/ Check if the system is described in es_systems but empty, to import metadatas )\n\t\t\tauto sourceSystem = SystemData::loadSystem(item.first, false);\n\t\t\tif (sourceSystem != nullptr)\n\t\t\t{\n\t\t\t\tmd.fullName = sourceSystem->getSystemMetadata().fullName;\n\t\t\t\tmd.themeFolder = sourceSystem->getSystemMetadata().themeFolder;\n\t\t\t\tmd.manufacturer = sourceSystem->getSystemMetadata().manufacturer;\n\t\t\t\tmd.releaseYear = sourceSystem->getSystemMetadata().releaseYear;\n\t\t\t\tmd.hardwareType = sourceSystem->getSystemMetadata().hardwareType;\n\n\t\t\t\tdelete sourceSystem;\n\t\t\t}\n\t\t\telse if (item.second.size() > 0)\n\t\t\t{\n\n\t\t\t\tSystemData* syss = *item.second.cbegin();\n\t\t\t\tmd.manufacturer = syss->getSystemMetadata().manufacturer;\n\t\t\t\tmd.releaseYear = syss->getSystemMetadata().releaseYear;\n\t\t\t\tmd.hardwareType = \"system\";\n\t\t\t}\n\n\t\t\tsystem = new SystemData(md, envData, nullptr, false, true);\n\t\t\tsystem->mIsGroupSystem = true;\n\t\t\tsystem->mIsGameSystem = false;\n\t\t}\n\n\t\tFolderData* root = system->getRootFolder();\n\n\t\tfor (auto childSystem : item.second)\n\t\t{\n\t\t\tauto children = childSystem->getRootFolder()->getChildren();\n\t\t\tif (children.size() > 0)\n\t\t\t{\n\t\t\t\tauto folder = new FolderData(childSystem->getRootFolder()->getPath(), childSystem, false);\n\t\t\t\tfolder->setMetadata(childSystem->getRootFolder()->getMetadata());\n\t\t\t\troot->addChild(folder);\n\n\t\t\t\tif (folder->getMetadata(MetaDataId::Image).empty())\n\t\t\t\t{\n\t\t\t\t\tauto theme = childSystem->getTheme();\n\t\t\t\t\tif (theme)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst ThemeData::ThemeElement* logoElem = theme->getElement(\"system\", \"logo\", \"image\");\n\t\t\t\t\t\tif (logoElem && logoElem->has(\"path\"))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::string path = logoElem->get<std::string>(\"path\");\n\t\t\t\t\t\t\tfolder->setMetadata(MetaDataId::Image, path);\n\t\t\t\t\t\t\tfolder->setMetadata(MetaDataId::Thumbnail, path);\n\t\t\t\t\t\t\tfolder->enableVirtualFolderDisplay(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (auto child : children)\n\t\t\t\t\tfolder->addChild(child, false);\n\n\t\t\t\tfolder->getMetadata().resetChangedFlag();\n\t\t\t}\n\t\t}\n\n\t\tif (root->getChildren().size() > 0 && !existingSystem)\n\t\t{\n\t\t\tsystem->loadTheme();\n\t\t\tsSystemVector.push_back(system);\n\t\t}\n\n\t\troot->getMetadata().resetChangedFlag();\n\t}\n}\n\ninline EmulatorFeatures::Features operator|(EmulatorFeatures::Features a, EmulatorFeatures::Features b)\n{\n\treturn static_cast<EmulatorFeatures::Features>(static_cast<int>(a) | static_cast<int>(b));\n}\n\ninline EmulatorFeatures::Features operator&(EmulatorFeatures::Features a, EmulatorFeatures::Features b)\n{\n\treturn static_cast<EmulatorFeatures::Features>(static_cast<int>(a) & static_cast<int>(b));\n}\n\nEmulatorFeatures::Features EmulatorFeatures::parseFeatures(const std::string features)\n{\n\tEmulatorFeatures::Features ret = EmulatorFeatures::Features::none;\n\n\tfor (auto name : Utils::String::split(features, ','))\n\t{\n\t\tstd::string trim = Utils::String::trim(name);\n\n\t\tif (trim == \"ratio\") ret = ret | EmulatorFeatures::Features::ratio;\n\t\tif (trim == \"rewind\") ret = ret | EmulatorFeatures::Features::rewind;\n\t\tif (trim == \"smooth\") ret = ret | EmulatorFeatures::Features::smooth;\n\t\tif (trim == \"shaders\") ret = ret | EmulatorFeatures::Features::shaders;\n\t\tif (trim == \"pixel_perfect\") ret = ret | EmulatorFeatures::Features::pixel_perfect;\n\t\tif (trim == \"decoration\") ret = ret | EmulatorFeatures::Features::decoration;\n\t\tif (trim == \"latency_reduction\") ret = ret | EmulatorFeatures::Features::latency_reduction;\n\t\tif (trim == \"game_translation\") ret = ret | EmulatorFeatures::Features::game_translation;\n\t\tif (trim == \"autosave\") ret = ret | EmulatorFeatures::Features::autosave;\n\t\tif (trim == \"netplay\") ret = ret | EmulatorFeatures::Features::netplay;\n\t\tif (trim == \"fullboot\") ret = ret | EmulatorFeatures::Features::fullboot;\n\t\tif (trim == \"emulated_wiimotes\") ret = ret | EmulatorFeatures::Features::emulated_wiimotes;\n\t\tif (trim == \"screen_layout\") ret = ret | EmulatorFeatures::Features::screen_layout;\n\t\tif (trim == \"internal_resolution\") ret = ret | EmulatorFeatures::Features::internal_resolution;\n\t\tif (trim == \"videomode\") ret = ret | EmulatorFeatures::Features::videomode;\n\t\tif (trim == \"colorization\") ret = ret | EmulatorFeatures::Features::colorization;\n\t\tif (trim == \"padtokeyboard\") ret = ret | EmulatorFeatures::Features::padTokeyboard;\n\t\tif (trim == \"joystick2pad\") ret = ret | EmulatorFeatures::Features::padTokeyboard;\n\t\tif (trim == \"cheevos\") ret = ret | EmulatorFeatures::Features::cheevos;\n\t\tif (trim == \"autocontrollers\") ret = ret | EmulatorFeatures::Features::autocontrollers;\n#ifdef _ENABLEEMUELEC\n\t\tif (trim == \"vertical\") ret = ret | EmulatorFeatures::Features::vertical;\n#endif\n\t}\n\n\treturn ret;\n}\n\nbool SystemData::es_features_loaded = false;\n\nstd::vector<CustomFeature>  SystemData::loadCustomFeatures(pugi::xml_node node)\n{\n\tstd::vector<CustomFeature> ret;\n\n\tpugi::xml_node customFeatures = node.child(\"features\");\n\tif (customFeatures == nullptr)\n\t\tcustomFeatures = node;\n\n\tfor (pugi::xml_node featureNode = customFeatures.child(\"feature\"); featureNode; featureNode = featureNode.next_sibling(\"feature\"))\n\t{\n\t\tif (!featureNode.attribute(\"name\"))\n\t\t\tcontinue;\n\n\t\tCustomFeature feat;\n\t\tfeat.name = featureNode.attribute(\"name\").value();\n\n\t\tif (featureNode.attribute(\"description\"))\n\t\t\tfeat.description = featureNode.attribute(\"description\").value();\n\n\t\tif (featureNode.attribute(\"value\"))\n\t\t\tfeat.value = featureNode.attribute(\"value\").value();\n\t\telse\n\t\t\tfeat.value = Utils::String::replace(feat.name, \" \", \"_\");\n\n\t\tfor (pugi::xml_node value = featureNode.child(\"choice\"); value; value = value.next_sibling(\"choice\"))\n\t\t{\n\t\t\tif (!value.attribute(\"name\"))\n\t\t\t\tcontinue;\n\n\t\t\tCustomFeatureChoice cv;\n\t\t\tcv.name = value.attribute(\"name\").value();\n\n\t\t\tif (value.attribute(\"value\"))\n\t\t\t\tcv.value = value.attribute(\"value\").value();\n\t\t\telse\n\t\t\t\tcv.value = Utils::String::replace(cv.name, \" \", \"_\");\n\n\t\t\tfeat.choices.push_back(cv);\n\t\t}\n\n\t\tif (feat.choices.size() > 0)\n\t\t\tret.push_back(feat);\n\t}\n\n\treturn ret;\n}\n\nbool SystemData::loadFeatures()\n{\n\tstd::string path = Utils::FileSystem::getEsConfigPath() + \"\/es_features.cfg\";\n\tif (!Utils::FileSystem::exists(path))\n\t\tpath = Utils::FileSystem::getSharedConfigPath() + \"\/es_features.cfg\";\n\n\tif (!Utils::FileSystem::exists(path))\n\t\treturn false;\n\n\tpugi::xml_document doc;\n\tpugi::xml_parse_result res = doc.load_file(path.c_str());\n\n\tif (!res)\n\t{\n\t\tLOG(LogError) << \"Could not parse es_features.cfg file!\";\n\t\tLOG(LogError) << res.description();\n\t\treturn false;\n\t}\n\n\t\/\/actually read the file\n\tpugi::xml_node systemList = doc.child(\"features\");\n\tif (!systemList)\n\t{\n\t\tLOG(LogError) << \"es_features.cfg is missing the <features> tag!\";\n\t\treturn false;\n\t}\n\n\n\tpugi::xml_node globalFeatures = systemList.child(\"globalFeatures\");\n\tif (globalFeatures)\n\t\tmGlobalFeatures = loadCustomFeatures(globalFeatures);\n\telse\n\t\tmGlobalFeatures.clear();\n\n\tes_features_loaded = true;\n\n\tfor (auto sys : SystemData::sSystemVector)\n\t{\n\t\tfor (auto& emul : sys->mEmulators)\n\t\t{\n\t\t\temul.features = EmulatorFeatures::Features::none;\n\t\t\tfor (auto& core : emul.cores)\n\t\t\t\tcore.features = EmulatorFeatures::Features::none;\n\t\t}\n\t}\n\n\tfor (pugi::xml_node emulator = systemList.child(\"emulator\"); emulator; emulator = emulator.next_sibling(\"emulator\"))\n\t{\n\t\tif (!emulator.attribute(\"name\"))\n\t\t\tcontinue;\n\n\t\tstd::string emulatorNames = emulator.attribute(\"name\").value();\n\t\tfor (auto tmpName : Utils::String::split(emulatorNames, ','))\n\t\t{\n\t\t\tstd::string emulatorName = Utils::String::trim(tmpName);\n\n\t\t\tEmulatorFeatures::Features emulatorFeatures = EmulatorFeatures::Features::none;\n\n\t\t\tauto customEmulatorFeatures = loadCustomFeatures(emulator);\n\n\t\t\tif (emulator.attribute(\"features\") || customEmulatorFeatures.size() > 0)\n\t\t\t{\n\t\t\t\tif (emulator.attribute(\"features\"))\n\t\t\t\t\temulatorFeatures = EmulatorFeatures::parseFeatures(emulator.attribute(\"features\").value());\n\n\t\t\t\tfor (auto sys : SystemData::sSystemVector)\n\t\t\t\t{\n\t\t\t\t\tfor (auto& emul : sys->mEmulators)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (emul.name == emulatorName || (emulatorName == \"libretro\" && Utils::String::startsWith(emul.name, \"lr-\")))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\temul.features = emul.features | emulatorFeatures;\n\t\t\t\t\t\t\tfor(auto feat : customEmulatorFeatures)\n\t\t\t\t\t\t\t\temul.customFeatures.push_back(feat);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpugi::xml_node coresNode = emulator.child(\"cores\");\n\t\t\tif (coresNode == nullptr)\n\t\t\t\tcoresNode = emulator;\n\n\t\t\tfor (pugi::xml_node coreNode = coresNode.child(\"core\"); coreNode; coreNode = coreNode.next_sibling(\"core\"))\n\t\t\t{\n\t\t\t\tif (!coreNode.attribute(\"name\") || !coreNode.attribute(\"features\"))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tstd::string coreNames = coreNode.attribute(\"name\").value();\n\t\t\t\tfor (auto tmpCoreName : Utils::String::split(coreNames, ','))\n\t\t\t\t{\n\t\t\t\t\tstd::string coreName = Utils::String::trim(tmpCoreName);\n\n\t\t\t\t\tEmulatorFeatures::Features coreFeatures = EmulatorFeatures::parseFeatures(coreNode.attribute(\"features\").value());\n\n\t\t\t\t\tauto customCoreFeatures = loadCustomFeatures(coreNode);\n\n\t\t\t\t\tbool coreFound = false;\n\n\t\t\t\t\tfor (auto sys : SystemData::sSystemVector)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (sys->mEmulators.size() == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ Try to handle systems without emulators defined\n\t\t\t\t\t\t\tstd::string command = sys->getLaunchCommand(emulatorName, coreName);\n\t\t\t\t\t\t\tif (command.find(\" \" + coreName + \" \") != std::string::npos || command.find(coreName + \"_libretro\") != std::string::npos)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tEmulatorData emul;\n\t\t\t\t\t\t\t\temul.name = emulatorName;\n\t\t\t\t\t\t\t\temul.features = emulatorFeatures;\n\n\t\t\t\t\t\t\t\tfor (auto feat : customEmulatorFeatures)\n\t\t\t\t\t\t\t\t\temul.customFeatures.push_back(feat);\n\n\t\t\t\t\t\t\t\tCoreData core;\n\t\t\t\t\t\t\t\tcore.name = coreName;\n\t\t\t\t\t\t\t\tcore.features = coreFeatures;\n\t\t\t\t\t\t\t\tcore.customFeatures = customCoreFeatures;\n\t\t\t\t\t\t\t\temul.cores.push_back(core);\n\n\t\t\t\t\t\t\t\tsys->mEmulators.push_back(emul);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor (auto& emul : sys->mEmulators)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (emul.name == emulatorName || (emulatorName == \"libretro\" && Utils::String::startsWith(emul.name, \"lr-\")))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tfor (auto& core : emul.cores)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif (core.name == coreName)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tcoreFound = true;\n\t\t\t\t\t\t\t\t\t\t\tcore.features = core.features | coreFeatures;\n\n\t\t\t\t\t\t\t\t\t\t\tfor (auto feat : customCoreFeatures)\n\t\t\t\t\t\t\t\t\t\t\t\tcore.customFeatures.push_back(feat);\n\n\t\t\t\t\t\t\t\t\t\t\tcore.netplay = coreFeatures & EmulatorFeatures::Features::netplay;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tpugi::xml_node systemsCoresNode = coreNode.child(\"systems\");\n\t\t\t\t\tif (systemsCoresNode == nullptr)\n\t\t\t\t\t\tsystemsCoresNode = coreNode;\n\n\t\t\t\t\tfor (pugi::xml_node systemNode = systemsCoresNode.child(\"system\"); systemNode; systemNode = systemNode.next_sibling(\"system\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!systemNode.attribute(\"name\") || !systemNode.attribute(\"features\"))\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tstd::string systemName = systemNode.attribute(\"name\").value();\n\t\t\t\t\t\tEmulatorFeatures::Features systemFeatures = EmulatorFeatures::parseFeatures(systemNode.attribute(\"features\").value());\n\t\t\t\t\t\tauto customSystemFeatures = loadCustomFeatures(systemNode);\n\n\t\t\t\t\t\tfor (auto sys : SystemData::sSystemVector)\n\t\t\t\t\t\t\tif (sys->getName() == systemName)\n\t\t\t\t\t\t\t\tfor (auto& emul : sys->mEmulators)\n\t\t\t\t\t\t\t\t\tfor (auto& core : emul.cores)\n\t\t\t\t\t\t\t\t\t\tif (core.name == coreName) {\n\t\t\t\t\t\t\t\t\t\t\tcore.features = core.features | systemFeatures;\n\t\t\t\t\t\t\t\t\t\t\tfor (auto ft : customSystemFeatures) core.customFeatures.push_back(ft);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (emulatorFeatures != EmulatorFeatures::Features::none || customEmulatorFeatures.size() > 0)\n\t\t\t{\n\t\t\t\tfor (auto sys : SystemData::sSystemVector)\n\t\t\t\t{\n\t\t\t\t\tif (sys->mEmulators.size() == 0 && sys->getName() == emulatorName)\n\t\t\t\t\t{\n\t\t\t\t\t\tEmulatorData emul;\n\t\t\t\t\t\temul.name = emulatorName;\n\t\t\t\t\t\temul.features = emulatorFeatures;\n\n\t\t\t\t\t\tfor (auto feat : customEmulatorFeatures)\n\t\t\t\t\t\t\temul.customFeatures.push_back(feat);\n\n\t\t\t\t\t\tsys->mEmulators.push_back(emul);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpugi::xml_node systemsNode = emulator.child(\"systems\");\n\t\tif (systemsNode == nullptr)\n\t\t\tsystemsNode = emulator;\n\n\t\tfor (pugi::xml_node systemNode = systemsNode.child(\"system\"); systemNode; systemNode = systemNode.next_sibling(\"system\"))\n\t\t{\n\t\t\tif (!systemNode.attribute(\"name\") || !systemNode.attribute(\"features\"))\n\t\t\t\tcontinue;\n\n\t\t\tstd::string systemName = systemNode.attribute(\"name\").value();\n\t\t\tEmulatorFeatures::Features systemFeatures = EmulatorFeatures::parseFeatures(systemNode.attribute(\"features\").value());\n\n\t\t\tauto customSystemFeatures = loadCustomFeatures(systemNode);\n\n\t\t\tfor (auto sys : SystemData::sSystemVector)\n\t\t\t\tif (sys->getName() == systemName)\n\t\t\t\t\tfor (auto& emul : sys->mEmulators) {\n\t\t\t\t\t\temul.features = emul.features | systemFeatures;\n\t\t\t\t\t\tfor (auto ft : customSystemFeatures)\n\t\t\t\t\t\t\temul.customFeatures.push_back(ft);\n\t\t\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}\n\nbool SystemData::isCurrentFeatureSupported(EmulatorFeatures::Features feature)\n{\n\treturn isFeatureSupported(getEmulator(), getCore(), feature);\n}\n\n\nbool SystemData::hasFeatures()\n{\n\tif (isCollection() || hasPlatformId(PlatformIds::PLATFORM_IGNORE))\n\t\treturn false;\n\n\tfor (auto emulator : mEmulators)\n\t{\n\t\tfor (auto& core : emulator.cores)\n\t\t\tif (core.features != EmulatorFeatures::Features::none || core.customFeatures.size() > 0)\n\t\t\t\treturn true;\n\n\t\tif (emulator.features != EmulatorFeatures::Features::none || emulator.customFeatures.size() > 0)\n\t\t\treturn true;\n\t}\n\n\treturn !es_features_loaded;\n}\n\nstd::vector<CustomFeature> SystemData::getCustomFeatures(std::string emulatorName, std::string coreName)\n{\n\tstd::vector<CustomFeature> ret;\n\n\tif (emulatorName.empty() || emulatorName == \"auto\")\n\t\temulatorName = getEmulator();\n\n\tif (coreName.empty() || coreName == \"auto\")\n\t\tcoreName = getCore();\n\n\tfor (auto emulator : mEmulators)\n\t{\n\t\tif (emulator.name == emulatorName)\n\t\t{\n\t\t\tfor (auto ft : emulator.customFeatures)\n\t\t\t\tret.push_back(ft);\n\n\t\t\tfor (auto& core : emulator.cores)\n\t\t\t\tif (coreName == core.name)\n\t\t\t\t\tfor (auto ft : core.customFeatures)\n\t\t\t\t\t\tret.push_back(ft);\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn ret;\n}\n\nbool SystemData::isFeatureSupported(std::string emulatorName, std::string coreName, EmulatorFeatures::Features feature)\n{\n\tif (emulatorName.empty() || emulatorName == \"auto\")\n\t\temulatorName = getEmulator();\n\n\tif (coreName.empty() || coreName == \"auto\")\n\t\tcoreName = getCore();\n\n\tfor (auto emulator : mEmulators)\n\t{\n\t\tif (emulator.name == emulatorName)\n\t\t{\n\t\t\tfor (auto& core : emulator.cores)\n\t\t\t\tif (coreName == core.name)\n\t\t\t\t\tif ((core.features & feature) == feature)\n\t\t\t\t\t\treturn true;\n\n\t\t\treturn (emulator.features & feature) == feature;\n\t\t}\n\t}\n\n\treturn !es_features_loaded;\n}\n\n\/\/ Load custom additionnal config from : \/userdata\/system\/configs\/emulationstation\/es_systems_*.cfg\nvoid SystemData::loadAdditionnalConfig(pugi::xml_node& srcSystems)\n{\n\tfor (auto customPath : Utils::FileSystem::getDirContent(Utils::FileSystem::getEsConfigPath(), false, false))\n\t{\n\t\tif (Utils::FileSystem::getExtension(customPath) != \".cfg\")\n\t\t\tcontinue;\n\n\t\tif (!Utils::String::startsWith(Utils::FileSystem::getFileName(customPath), \"es_systems_\"))\n\t\t\tcontinue;\n\n\t\tpugi::xml_document doc;\n\t\tpugi::xml_parse_result res = doc.load_file(customPath.c_str());\n\t\tif (!res)\n\t\t{\n\t\t\tLOG(LogError) << \"Could not parse \" << Utils::FileSystem::getFileName(customPath) << \" file!\";\n\t\t\treturn;\n\t\t}\n\n\t\tpugi::xml_node systemList = doc.child(\"systemList\");\n\t\tif (!systemList)\n\t\t{\n\t\t\tLOG(LogError) << Utils::FileSystem::getFileName(customPath) << \" is missing the <systemList> tag !\";\n\t\t\treturn;\n\t\t}\n\n\t\tfor (pugi::xml_node system = systemList.child(\"system\"); system; system = system.next_sibling(\"system\"))\n\t\t{\n\t\t\tif (!system.child(\"name\"))\n\t\t\t\tcontinue;\n\n\t\t\tstd::string name = system.child(\"name\").text().get();\n\t\t\tif (name.empty())\n\t\t\t\tcontinue;\n\n\t\t\tbool found = false;\n\n\t\t\t\/\/ Remove existing one\n\t\t\tfor (pugi::xml_node& srcSystem : srcSystems.children())\n\t\t\t{\n\t\t\t\tif (std::string(srcSystem.name()) != \"system\")\n\t\t\t\t\tcontinue;\n\n\t\t\t\tstd::string srcName = srcSystem.child(\"name\").text().get();\n\t\t\t\tif (srcName != name)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tfound = true;\n\n\t\t\t\tfor (pugi::xml_node& child : system.children())\n\t\t\t\t{\n\t\t\t\t\tstd::string tag = child.name();\n\t\t\t\t\tif (tag == \"name\")\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tsrcSystem.remove_child(tag.c_str());\n\n\t\t\t\t\tif (tag == \"emulators\" || !std::string(child.text().get()).empty())\n\t\t\t\t\t\tsrcSystem.append_copy(child);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!found)\n\t\t\t\tsrcSystems.append_copy(system);\n\t\t}\n\t}\n}\n\n\/\/creates systems from information located in a config file\nbool SystemData::loadConfig(Window* window)\n{\n\tdeleteSystems();\n\tThemeData::setDefaultTheme(nullptr);\n\n\tstd::string path = getConfigPath(false);\n\n\tLOG(LogInfo) << \"Loading system config file \" << path << \"...\";\n\n\tif (!Utils::FileSystem::exists(path))\n\t{\n\t\tLOG(LogError) << \"es_systems.cfg file does not exist!\";\n\t\twriteExampleConfig(getConfigPath(true));\n\t\treturn false;\n\t}\n\n\tpugi::xml_document doc;\n\tpugi::xml_parse_result res = doc.load_file(path.c_str());\n\n\tif (!res)\n\t{\n\t\tLOG(LogError) << \"Could not parse es_systems.cfg file!\";\n\t\tLOG(LogError) << res.description();\n\t\treturn false;\n\t}\n\n\t\/\/actually read the file\n\tpugi::xml_node systemList = doc.child(\"systemList\");\n\tif (!systemList)\n\t{\n\t\tLOG(LogError) << \"es_systems.cfg is missing the <systemList> tag!\";\n\t\treturn false;\n\t}\n\n\tloadAdditionnalConfig(systemList);\n\n\tstd::vector<std::string> systemsNames;\n\n\tint systemCount = 0;\n\tfor (pugi::xml_node system = systemList.child(\"system\"); system; system = system.next_sibling(\"system\"))\n\t{\n\t\tsystemsNames.push_back(system.child(\"fullname\").text().get());\n\t\tsystemCount++;\n\t}\n\n\tif (systemCount == 0)\n\t{\n\t\tLOG(LogError) << \"no system found in es_systems.cfg\";\n\t\treturn false;\n\t}\n\n\tUtils::FileSystem::FileSystemCacheActivator fsc;\n\n\tint currentSystem = 0;\n\n\ttypedef SystemData* SystemDataPtr;\n\n\tThreadPool* pThreadPool = NULL;\n\tSystemDataPtr* systems = NULL;\n\n\t\/\/ Allow threaded loading only if processor threads > 2 so it does not apply on machines like Pi0.\n\tif (std::thread::hardware_concurrency() > 2 && Settings::getInstance()->getBool(\"ThreadedLoading\"))\n\t{\n\t\tpThreadPool = new ThreadPool();\n\n\t\tsystems = new SystemDataPtr[systemCount];\n\t\tfor (int i = 0; i < systemCount; i++)\n\t\t\tsystems[i] = nullptr;\n\n\t\tpThreadPool->queueWorkItem([] { CollectionSystemManager::get()->loadCollectionSystems(true); });\n\t}\n\n\tint processedSystem = 0;\n\n\tfor (pugi::xml_node system = systemList.child(\"system\"); system; system = system.next_sibling(\"system\"))\n\t{\n\t\tif (pThreadPool != NULL)\n\t\t{\n\t\t\tpThreadPool->queueWorkItem([system, currentSystem, systems, &processedSystem]\n\t\t\t{\n\t\t\t\tsystems[currentSystem] = loadSystem(system);\n\t\t\t\tprocessedSystem++;\n\t\t\t});\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::string fullname = system.child(\"fullname\").text().get();\n\n\t\t\tif (window != NULL)\n\t\t\t\twindow->renderSplashScreen(fullname, systemCount == 0 ? 0 : (float)currentSystem \/ (float)(systemCount + 1));\n\n\t\t\tstd::string nm = system.child(\"name\").text().get();\n\n\t\t\tSystemData* pSystem = loadSystem(system);\n\t\t\tif (pSystem != nullptr)\n\t\t\t\tsSystemVector.push_back(pSystem);\n\t\t}\n\n\t\tcurrentSystem++;\n\t}\n\n\tif (pThreadPool != NULL)\n\t{\n\t\tif (window != NULL)\n\t\t{\n\t\t\tpThreadPool->wait([window, &processedSystem, systemCount, &systemsNames]\n\t\t\t{\n\t\t\t\tint px = processedSystem - 1;\n\t\t\t\tif (px >= 0 && px < systemsNames.size())\n\t\t\t\t\twindow->renderSplashScreen(systemsNames.at(px), (float)px \/ (float)(systemCount + 1));\n\t\t\t}, 50);\n\t\t}\n\t\telse\n\t\t\tpThreadPool->wait();\n\n\t\tfor (int i = 0; i < systemCount; i++)\n\t\t{\n\t\t\tSystemData* pSystem = systems[i];\n\t\t\tif (pSystem != nullptr)\n\t\t\t\tsSystemVector.push_back(pSystem);\n\t\t}\n\n\t\tdelete[] systems;\n\t\tdelete pThreadPool;\n\n\n\n\t\tif (window != NULL)\n\t\t\twindow->renderSplashScreen(_(\"Collections\"), systemCount == 0 ? 0 : currentSystem \/ systemCount);\n\n\t\t\/\/ updateSystemsList can't be run async, systems have to be created before\n\t\tcreateGroupedSystems();\n\t\tCollectionSystemManager::get()->updateSystemsList();\n\t}\n\telse\n\t{\n\t\tif (window != NULL)\n\t\t\twindow->renderSplashScreen(_(\"Collections\"), systemCount == 0 ? 0 : currentSystem \/ systemCount);\n\n\t\tcreateGroupedSystems();\n\t\tCollectionSystemManager::get()->loadCollectionSystems();\n\t}\n\n\tif (SystemData::sSystemVector.size() > 0)\n\t{\n\t\tauto theme = SystemData::sSystemVector.at(0)->getTheme();\n\t\tViewController::get()->onThemeChanged(theme);\n\t}\n\n\tloadFeatures();\n\n\tif (window != nullptr && SystemConf::getInstance()->getBool(\"global.netplay\") && !ThreadedHasher::isRunning())\n\t{\n\t\tif (Settings::getInstance()->getBool(\"NetPlayCheckIndexesAtStart\"))\n\t\t\tThreadedHasher::start(window, ThreadedHasher::HASH_NETPLAY_CRC, false, true);\n\t}\n\n\treturn true;\n}\n\nSystemData* SystemData::loadSystem(std::string systemName, bool fullMode)\n{\n\tstd::string path = getConfigPath(false);\n\tif (!Utils::FileSystem::exists(path))\n\t\treturn nullptr;\n\n\tpugi::xml_document doc;\n\tpugi::xml_parse_result res = doc.load_file(path.c_str());\n\tif (!res)\n\t\treturn nullptr;\n\n\t\/\/actually read the file\n\tpugi::xml_node systemList = doc.child(\"systemList\");\n\tif (!systemList)\n\t\treturn nullptr;\n\n\tloadAdditionnalConfig(systemList);\n\n\tfor (pugi::xml_node system = systemList.child(\"system\"); system; system = system.next_sibling(\"system\"))\n\t{\n\t\tstd::string name = system.child(\"name\").text().get();\n\t\tif (name == systemName)\n\t\t\treturn loadSystem(system, fullMode);\n\t}\n\n\treturn nullptr;\n}\n\nstd::map<std::string, std::string> SystemData::getKnownSystemNames()\n{\n\tstd::map<std::string, std::string> ret;\n\n\tstd::string path = getConfigPath(false);\n\tif (!Utils::FileSystem::exists(path))\n\t\treturn ret;\n\n\tpugi::xml_document doc;\n\tpugi::xml_parse_result res = doc.load_file(path.c_str());\n\tif (!res)\n\t\treturn ret;\n\n\t\/\/actually read the file\n\tpugi::xml_node systemList = doc.child(\"systemList\");\n\tif (!systemList)\n\t\treturn ret;\n\n\tloadAdditionnalConfig(systemList);\n\n\tfor (pugi::xml_node system = systemList.child(\"system\"); system; system = system.next_sibling(\"system\"))\n\t{\n\t\tstd::string name = system.child(\"name\").text().get();\n\t\tif (name.empty())\n\t\t\tcontinue;\n\n\t\tstd::string fullName = system.child(\"fullname\").text().get();\n\t\tif (fullName.empty())\n\t\t\tcontinue;\n\n\t\tret[name] = fullName;\n\t}\n\n\treturn ret;\n}\n\nSystemData* SystemData::loadSystem(pugi::xml_node system, bool fullMode)\n{\n\tstd::string path, cmd; \/\/ , name, fullname, themeFolder;\n\n\tpath = system.child(\"path\").text().get();\n\n\tSystemMetadata md;\n\tmd.name = system.child(\"name\").text().get();\n\tmd.fullName = system.child(\"fullname\").text().get();\n\tmd.manufacturer = system.child(\"manufacturer\").text().get();\n\tmd.releaseYear = atoi(system.child(\"release\").text().get());\n\tmd.hardwareType = system.child(\"hardware\").text().get();\n\tmd.themeFolder = system.child(\"theme\").text().as_string(md.name.c_str());\n\n\t\/\/ convert extensions list from a string into a vector of strings\n\tstd::vector<std::string> extensions;\n\tfor (auto ext : readList(system.child(\"extension\").text().get()))\n\t{\n\t\tstd::string extlow = Utils::String::toLower(ext);\n\t\tif (std::find(extensions.cbegin(), extensions.cend(), extlow) == extensions.cend())\n\t\t\textensions.push_back(extlow);\n\t}\n\n\tcmd = system.child(\"command\").text().get();\n\n\t\/\/ platform id list\n\tconst char* platformList = system.child(\"platform\").text().get();\n\tstd::vector<std::string> platformStrs = readList(platformList);\n\tstd::vector<PlatformIds::PlatformId> platformIds;\n\tfor (auto it = platformStrs.cbegin(); it != platformStrs.cend(); it++)\n\t{\n\t\tconst char* str = it->c_str();\n\t\tPlatformIds::PlatformId platformId = PlatformIds::getPlatformId(str);\n\n\t\tif (platformId == PlatformIds::PLATFORM_IGNORE)\n\t\t{\n\t\t\t\/\/ when platform is ignore, do not allow other platforms\n\t\t\tplatformIds.clear();\n\n\t\t\tif (md.name == \"imageviewer\")\n\t\t\t\tplatformIds.push_back(PlatformIds::IMAGEVIEWER);\n\t\t\telse\n\t\t\t\tplatformIds.push_back(platformId);\n\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ if there appears to be an actual platform ID supplied but it didn't match the list, warn\n\t\tif (platformId != PlatformIds::PLATFORM_UNKNOWN)\n\t\t\tplatformIds.push_back(platformId);\n\t\telse if (str != NULL && str[0] != '\\0' && platformId == PlatformIds::PLATFORM_UNKNOWN)\n\t\t\tLOG(LogWarning) << \"  Unknown platform for system \\\"\" << md.name << \"\\\" (platform \\\"\" << str << \"\\\" from list \\\"\" << platformList << \"\\\")\";\n\t}\n\n\t\/\/validate\n\tif (md.name.empty() || path.empty() || extensions.empty() || cmd.empty())\n\t{\n\t\tLOG(LogError) << \"System \\\"\" << md.name << \"\\\" is missing name, path, extension, or command!\";\n\t\treturn nullptr;\n\t}\n\n\t\/\/convert path to generic directory seperators\n\tpath = Utils::FileSystem::getGenericPath(path);\n\n\t\/\/expand home symbol if the startpath contains ~\n\tif (path[0] == '~')\n\t{\n\t\tpath.erase(0, 1);\n\t\tpath.insert(0, Utils::FileSystem::getHomePath());\n\t\tpath = Utils::FileSystem::getCanonicalPath(path);\n\t}\n\n\t\/\/create the system runtime environment data\n\tSystemEnvironmentData* envData = new SystemEnvironmentData;\n\tenvData->mStartPath = path;\n\tenvData->mSearchExtensions = extensions;\n\tenvData->mLaunchCommand = cmd;\n\tenvData->mPlatformIds = platformIds;\n\tenvData->mGroup = system.child(\"group\").text().get();\n\n\t\/\/ batocera\n\/\/ emulators and cores\n\n\tstd::vector<EmulatorData> systemEmulators;\n\n\tpugi::xml_node emulatorsNode = system.child(\"emulators\");\n\tif (emulatorsNode != nullptr)\n\t{\n\t\tfor (pugi::xml_node emuNode = emulatorsNode.child(\"emulator\"); emuNode; emuNode = emuNode.next_sibling(\"emulator\"))\n\t\t{\n\t\t\tEmulatorData emulatorData;\n\t\t\temulatorData.name = emuNode.attribute(\"name\").value();\n\t\t\temulatorData.customCommandLine = emuNode.attribute(\"command\").value();\n\t\t\temulatorData.features = EmulatorFeatures::Features::all;\n\n\t\t\tif (emuNode.attribute(\"incompatible_extensions\"))\n\t\t\t{\n\t\t\t\tfor (auto ext : readList(emuNode.attribute(\"incompatible_extensions\").value()))\n\t\t\t\t{\n\t\t\t\t\tstd::string extlow = Utils::String::toLower(ext);\n\t\t\t\t\tif (std::find(emulatorData.incompatibleExtensions.cbegin(), emulatorData.incompatibleExtensions.cend(), extlow) == emulatorData.incompatibleExtensions.cend())\n\t\t\t\t\t\temulatorData.incompatibleExtensions.push_back(extlow);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpugi::xml_node coresNode = emuNode.child(\"cores\");\n\t\t\tif (coresNode != nullptr)\n\t\t\t{\n\t\t\t\tfor (pugi::xml_node coreNode = coresNode.child(\"core\"); coreNode; coreNode = coreNode.next_sibling(\"core\"))\n\t\t\t\t{\n\t\t\t\t\tCoreData core;\n\t\t\t\t\tcore.name = coreNode.text().as_string();\n\t\t\t\t\tcore.netplay = coreNode.attribute(\"netplay\") && strcmp(coreNode.attribute(\"netplay\").value(), \"true\") == 0;\n\t\t\t\t\tcore.isDefault = coreNode.attribute(\"default\") && strcmp(coreNode.attribute(\"default\").value(), \"true\") == 0;\n\n\t\t\t\t\tif (coreNode.attribute(\"incompatible_extensions\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (auto ext : readList(coreNode.attribute(\"incompatible_extensions\").value()))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::string extlow = Utils::String::toLower(ext);\n\t\t\t\t\t\t\tif (std::find(core.incompatibleExtensions.cbegin(), core.incompatibleExtensions.cend(), extlow) == core.incompatibleExtensions.cend())\n\t\t\t\t\t\t\t\tcore.incompatibleExtensions.push_back(extlow);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcore.features = EmulatorFeatures::Features::all;\n\t\t\t\t\tcore.customCommandLine = coreNode.attribute(\"command\").value();\n\n\t\t\t\t\temulatorData.cores.push_back(core);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsystemEmulators.push_back(emulatorData);\n\t\t}\n\t}\n\n\tSystemData* newSys = new SystemData(md, envData, &systemEmulators, false, false, fullMode, true); \/\/ batocera\n\n\tif (!fullMode)\n\t\treturn newSys;\n\n\tif (newSys->getRootFolder()->getChildren().size() == 0)\n\t{\n\t\tLOG(LogWarning) << \"System \\\"\" << md.name << \"\\\" has no games! Ignoring it.\";\n\t\tdelete newSys;\n\t\treturn nullptr;\n\t}\n\n\treturn newSys;\n}\n\nvoid SystemData::writeExampleConfig(const std::string& path)\n{\n\tstd::ofstream file(path.c_str());\n\n\tfile << \"<!-- This is the EmulationStation Systems configuration file.\\n\"\n\t\t\t\"All systems must be contained within the <systemList> tag.-->\\n\"\n\t\t\t\"\\n\"\n\t\t\t\"<systemList>\\n\"\n\t\t\t\"\t<!-- Here's an example system to get you started. -->\\n\"\n\t\t\t\"\t<system>\\n\"\n\t\t\t\"\\n\"\n\t\t\t\"\t\t<!-- A short name, used internally. Traditionally lower-case. -->\\n\"\n\t\t\t\"\t\t<name>nes<\/name>\\n\"\n\t\t\t\"\\n\"\n\t\t\t\"\t\t<!-- A \\\"pretty\\\" name, displayed in menus and such. -->\\n\"\n\t\t\t\"\t\t<fullname>Nintendo Entertainment System<\/fullname>\\n\"\n\t\t\t\"\\n\"\n\t\t\t\"\t\t<!-- The path to start searching for ROMs in. '~' will be expanded to $HOME on Linux or %HOMEPATH% on Windows. -->\\n\"\n\t\t\t\"\t\t<path>~\/roms\/nes<\/path>\\n\"\n\t\t\t\"\\n\"\n\t\t\t\"\t\t<!-- A list of extensions to search for, delimited by any of the whitespace characters (\\\", \\\\r\\\\n\\\\t\\\").\\n\"\n\t\t\t\"\t\tYou MUST include the period at the start of the extension! It's also case sensitive. -->\\n\"\n\t\t\t\"\t\t<extension>.nes .NES<\/extension>\\n\"\n\t\t\t\"\\n\"\n\t\t\t\"\t\t<!-- The shell command executed when a game is selected. A few special tags are replaced if found in a command:\\n\"\n\t\t\t\"\t\t%ROM% is replaced by a bash-special-character-escaped absolute path to the ROM.\\n\"\n\t\t\t\"\t\t%BASENAME% is replaced by the \\\"base\\\" name of the ROM.  For example, \\\"\/foo\/bar.rom\\\" would have a basename of \\\"bar\\\". Useful for MAME.\\n\"\n\t\t\t\"\t\t%ROM_RAW% is the raw, unescaped path to the ROM. -->\\n\"\n\t\t\t\"\t\t<command>retroarch -L ~\/cores\/libretro-fceumm.so %ROM%<\/command>\\n\"\n\t\t\t\"\\n\"\n\t\t\t\"\t\t<!-- The platform to use when scraping. You can see the full list of accepted platforms in src\/PlatformIds.cpp.\\n\"\n\t\t\t\"\t\tIt's case sensitive, but everything is lowercase. This tag is optional.\\n\"\n\t\t\t\"\t\tYou can use multiple platforms too, delimited with any of the whitespace characters (\\\", \\\\r\\\\n\\\\t\\\"), eg: \\\"genesis, megadrive\\\" -->\\n\"\n\t\t\t\"\t\t<platform>nes<\/platform>\\n\"\n\t\t\t\"\\n\"\n\t\t\t\"\t\t<!-- The theme to load from the current theme set.  See THEMES.md for more information.\\n\"\n\t\t\t\"\t\tThis tag is optional. If not set, it will default to the value of <name>. -->\\n\"\n\t\t\t\"\t\t<theme>nes<\/theme>\\n\"\n\t\t\t\"\t<\/system>\\n\"\n\t\t\t\"<\/systemList>\\n\";\n\n\tfile.close();\n\n\tLOG(LogError) << \"Example config written!  Go read it at \\\"\" << path << \"\\\"!\";\n}\n\nbool SystemData::isManufacturerSupported()\n{\n\tfor (auto sys : sSystemVector)\n\t{\n\t\tif (!sys->isGameSystem() || sys->isCollection())\n\t\t\tcontinue;\n\n\t\tif (!sys->getSystemMetadata().manufacturer.empty())\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool SystemData::hasDirtySystems()\n{\n\tbool saveOnExit = !Settings::getInstance()->getBool(\"IgnoreGamelist\") && Settings::getInstance()->getBool(\"SaveGamelistsOnExit\");\n\tif (!saveOnExit)\n\t\treturn false;\n\n\tfor (unsigned int i = 0; i < sSystemVector.size(); i++)\n\t{\n\t\tSystemData* pData = sSystemVector.at(i);\n\t\tif (pData->mIsCollectionSystem)\n\t\t\tcontinue;\n\n\t\tif (hasDirtyFile(pData))\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nvoid SystemData::deleteSystems()\n{\n\tbool saveOnExit = !Settings::getInstance()->getBool(\"IgnoreGamelist\") && Settings::getInstance()->getBool(\"SaveGamelistsOnExit\");\n\n\tfor (unsigned int i = 0; i < sSystemVector.size(); i++)\n\t{\n\t\tSystemData* pData = sSystemVector.at(i);\n\t\tpData->getRootFolder()->removeVirtualFolders();\n\n\t\tif (saveOnExit && !pData->mIsCollectionSystem)\n\t\t\tupdateGamelist(pData);\n\n\t\tdelete pData;\n\t}\n\n\tsSystemVector.clear();\n}\n\nstd::string SystemData::getConfigPath(bool forWrite)\n{\n#if WIN32\n\tstd::string customPath = Utils::FileSystem::getSharedConfigPath() + \"\/es_systems_custom.cfg\"; \/\/ \/usr\/share\/emulationstation\/es_systems.cfg\n\tif (Utils::FileSystem::exists(customPath))\n\t\treturn customPath;\n#endif\n\n\tstd::string userdataPath = Utils::FileSystem::getEsConfigPath() + \"\/es_systems.cfg\"; \/\/ \/userdata\/system\/configs\/emulationstation\/es_systems.cfg\n\tif(forWrite || Utils::FileSystem::exists(userdataPath))\n\t\treturn userdataPath;\n\n#if !WIN32\n\tstd::string customPath = Utils::FileSystem::getSharedConfigPath() + \"\/es_systems.cfg\"; \/\/ \/usr\/share\/emulationstation\/es_systems.cfg\n\tif (Utils::FileSystem::exists(customPath))\n\t\treturn customPath;\n#endif\n\n\treturn \"\/etc\/emulationstation\/es_systems.cfg\";\n}\n\nbool SystemData::isVisible()\n{\n\tif (isGroupChildSystem())\n\t\treturn false;\n\n\tif ((getGameCountInfo()->totalGames > 0 ||\n\t\t(UIModeController::getInstance()->isUIModeFull() && mIsCollectionSystem) ||\n\t\t(mIsCollectionSystem && mMetadata.name == \"favorites\")))\n\t{\n\t\tif (!mIsCollectionSystem)\n\t\t{\n\t\t\tauto hiddenSystems = Utils::String::split(Settings::getInstance()->getString(\"HiddenSystems\"), ';');\n\t\t\treturn std::find(hiddenSystems.cbegin(), hiddenSystems.cend(), getName()) == hiddenSystems.cend();\n\t\t}\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nSystemData* SystemData::getNext() const\n{\n\tstd::vector<SystemData*>::const_iterator it = getIterator();\n\n\tdo {\n\t\tit++;\n\t\tif (it == sSystemVector.cend())\n\t\t\tit = sSystemVector.cbegin();\n\t} while (!(*it)->isVisible());\n\t\/\/ as we are starting in a valid gamelistview, this will always succeed, even if we have to come full circle.\n\n\treturn *it;\n}\n\nSystemData* SystemData::getPrev() const\n{\n\tstd::vector<SystemData*>::const_reverse_iterator it = getRevIterator();\n\n\tdo {\n\t\tit++;\n\t\tif (it == sSystemVector.crend())\n\t\t\tit = sSystemVector.crbegin();\n\t} while (!(*it)->isVisible());\n\t\/\/ as we are starting in a valid gamelistview, this will always succeed, even if we have to come full circle.\n\n\treturn *it;\n}\n\nstd::string SystemData::getGamelistPath(bool forWrite) const\n{\n\tstd::string filePath;\n\n\tfilePath = mRootFolder->getPath() + \"\/gamelist.xml\";\n\tif(Utils::FileSystem::exists(filePath))\n\t\treturn filePath;\n\n\tstd::string localPath = Utils::FileSystem::getEsConfigPath() + \"\/gamelists\/\" + mMetadata.name + \"\/gamelist.xml\";\n\tif (Utils::FileSystem::exists(localPath))\n\t\treturn localPath;\n\n\tif (forWrite)\n\t\tUtils::FileSystem::createDirectory(Utils::FileSystem::getParent(filePath));\n\n\treturn filePath;\n}\n\nstd::string SystemData::getThemePath() const\n{\n\t\/\/ where we check for themes, in order:\n\t\/\/ 1. [SYSTEM_PATH]\/theme.xml\n\t\/\/ 2. system theme from currently selected theme set [CURRENT_THEME_PATH]\/[SYSTEM]\/theme.xml\n\t\/\/ 3. default system theme from currently selected theme set [CURRENT_THEME_PATH]\/theme.xml\n\n\t\/\/ first, check game folder\n\n\tif (!mEnvData->mStartPath.empty())\n\t{\n\t\tstd::string rootThemePath = mRootFolder->getPath() + \"\/theme.xml\";\n\t\tif (Utils::FileSystem::exists(rootThemePath))\n\t\t\treturn rootThemePath;\n\t}\n\n\t\/\/ not in game folder, try system theme in theme sets\n\tstd::string localThemePath = ThemeData::getThemeFromCurrentSet(mMetadata.themeFolder);\n\tif (Utils::FileSystem::exists(localThemePath))\n\t\treturn localThemePath;\n\n\t\/\/ not system theme, try default system theme in theme set\n\tlocalThemePath = Utils::FileSystem::getParent(Utils::FileSystem::getParent(localThemePath)) + \"\/theme.xml\";\n\n\treturn localThemePath;\n}\n\nbool SystemData::hasGamelist() const\n{\n\treturn (Utils::FileSystem::exists(getGamelistPath(false)));\n}\n\nunsigned int SystemData::getGameCount() const\n{\n\treturn (unsigned int)mRootFolder->getFilesRecursive(GAME).size();\n}\n\nSystemData* SystemData::getRandomSystem()\n{\n\t\/\/  this is a bit brute force. It might be more efficient to just to a while (!gameSystem) do random again...\n\tunsigned int total = 0;\n\tfor(auto it = sSystemVector.cbegin(); it != sSystemVector.cend(); it++)\n\t{\n\t\tif ((*it)->isGameSystem())\n\t\t\ttotal ++;\n\t}\n\n\t\/\/ get random number in range\n\tint target = (int)Math::round((std::rand() \/ (float)RAND_MAX) * (total - 1));\n\tfor (auto it = sSystemVector.cbegin(); it != sSystemVector.cend(); it++)\n\t{\n\t\tif ((*it)->isGameSystem())\n\t\t{\n\t\t\tif (target > 0)\n\t\t\t{\n\t\t\t\ttarget--;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn (*it);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ if we end up here, there is no valid system\n\treturn NULL;\n}\n\nFileData* SystemData::getRandomGame()\n{\n\tstd::vector<FileData*> list = mRootFolder->getFilesRecursive(GAME, true);\n\tunsigned int total = (int)list.size();\n\tint target = 0;\n\t\/\/ get random number in range\n\tif (total == 0)\n\t\treturn NULL;\n\ttarget = (int)Math::round((std::rand() \/ (float)RAND_MAX) * (total - 1));\n\treturn list.at(target);\n}\n\nGameCountInfo* SystemData::getGameCountInfo()\n{\n\tif (mGameCountInfo != nullptr)\n\t\treturn mGameCountInfo;\n\n\tstd::vector<FileData*> games = mRootFolder->getFilesRecursive(GAME, true);\n\n\tint realTotal = games.size();\n\tif (mFilterIndex != nullptr)\n\t{\n\t\tauto savedFilter = mFilterIndex;\n\t\tmFilterIndex = nullptr;\n\t\trealTotal = mRootFolder->getFilesRecursive(GAME, true).size();\n\t\tmFilterIndex = savedFilter;\n\t}\n\n\n\tmGameCountInfo = new GameCountInfo();\n\tmGameCountInfo->visibleGames = games.size();\n\tmGameCountInfo->totalGames = realTotal;\n\tmGameCountInfo->favoriteCount = 0;\n\tmGameCountInfo->hiddenCount = 0;\n\tmGameCountInfo->playCount = 0;\n\tmGameCountInfo->gamesPlayed = 0;\n\n\tint mostPlayCount = 0;\n\n\tfor (auto game : games)\n\t{\n\t\tif (game->getFavorite())\n\t\t\tmGameCountInfo->favoriteCount++;\n\n\t\tif (game->getHidden())\n\t\t\tmGameCountInfo->hiddenCount++;\n\n\t\tint playCount = Utils::String::toInteger(game->getMetadata(MetaDataId::PlayCount));\n\t\tif (playCount > 0)\n\t\t{\n\t\t\tmGameCountInfo->gamesPlayed++;\n\t\t\tmGameCountInfo->playCount += playCount;\n\n\t\t\tif (playCount > mostPlayCount)\n\t\t\t{\n\t\t\t\tmGameCountInfo->mostPlayed = game->getName();\n\t\t\t\tmostPlayCount = playCount;\n\t\t\t}\n\t\t}\n\n\t\tauto lastPlayed = game->getMetadata(MetaDataId::LastPlayed);\n\t\tif (!lastPlayed.empty() && lastPlayed > mGameCountInfo->lastPlayedDate)\n\t\t\tmGameCountInfo->lastPlayedDate = lastPlayed;\n\t}\n\n\treturn mGameCountInfo;\n\t\/*\n\tif (this == CollectionSystemManager::get()->getCustomCollectionsBundle())\n\t\tmGameCount = mRootFolder->getChildren().size();\n\telse\n\t\tmGameCount = mRootFolder->getFilesRecursive(GAME, true).size();\n\n\treturn mGameCount;*\/\n}\n\nvoid SystemData::updateDisplayedGameCount()\n{\n\tif (mGameCountInfo != nullptr)\n\t\tdelete mGameCountInfo;\n\n\tmGameCountInfo = nullptr;\n}\n\nvoid SystemData::loadTheme()\n{\n\tmTheme = std::make_shared<ThemeData>();\n\n\tstd::string path = getThemePath();\n\n\tif(!Utils::FileSystem::exists(path)) \/\/ no theme available for this platform\n\t\treturn;\n\n\ttry\n\t{\n\t\t\/\/ build map with system variables for theme to use,\n\t\tstd::map<std::string, std::string> sysData;\n\t\tsysData.insert(std::pair<std::string, std::string>(\"system.name\", getName()));\n\t\tsysData.insert(std::pair<std::string, std::string>(\"system.theme\", getThemeFolder()));\n\t\tsysData.insert(std::pair<std::string, std::string>(\"system.fullName\", Utils::String::proper(getFullName())));\n\n\t\tsysData.insert(std::pair<std::string, std::string>(\"system.manufacturer\", getSystemMetadata().manufacturer));\n\t\tsysData.insert(std::pair<std::string, std::string>(\"system.hardwareType\", Utils::String::proper(getSystemMetadata().hardwareType)));\n\n\t\tif (Settings::getInstance()->getString(\"SortSystems\") == \"hardware\")\n\t\t\tsysData.insert(std::pair<std::string, std::string>(\"system.sortedBy\", Utils::String::proper(getSystemMetadata().hardwareType)));\n\t\telse\n\t\t\tsysData.insert(std::pair<std::string, std::string>(\"system.sortedBy\", getSystemMetadata().manufacturer));\n\n\t\tif (getSystemMetadata().releaseYear > 0)\n\t\t{\n\t\t\tsysData.insert(std::pair<std::string, std::string>(\"system.releaseYearOrNull\", std::to_string(getSystemMetadata().releaseYear)));\n\t\t\tsysData.insert(std::pair<std::string, std::string>(\"system.releaseYear\", std::to_string(getSystemMetadata().releaseYear)));\n\t\t}\n\t\telse\n\t\t\tsysData.insert(std::pair<std::string, std::string>(\"system.releaseYear\", _(\"Unknown\")));\n\n\t\tif (isCheevosSupported() || isCollection() || isGroupSystem())\n\t\t\tsysData.insert(std::pair<std::string, std::string>(\"system.cheevos\", \"true\"));\n\n\t\tmTheme->loadFile(getThemeFolder(), sysData, path);\n\t}\n\tcatch(ThemeException& e)\n\t{\n\t\tLOG(LogError) << e.what();\n\t\tmTheme = std::make_shared<ThemeData>(); \/\/ reset to empty\n\t}\n}\n\nvoid SystemData::setSortId(const unsigned int sortId)\n{\n\tmSortId = sortId;\n\tSettings::getInstance()->setInt(getName() + \".sort\", mSortId);\n}\n\nbool SystemData::setSystemViewMode(std::string newViewMode, Vector2f gridSizeOverride, bool setChanged)\n{\n\tif (newViewMode == \"automatic\")\n\t\tnewViewMode = \"\";\n\n\tif (mViewMode == newViewMode && gridSizeOverride == mGridSizeOverride)\n\t\treturn false;\n\n\tmGridSizeOverride = gridSizeOverride;\n\tmViewMode = newViewMode;\n\n\tif (setChanged)\n\t{\n\t\tSettings::getInstance()->setString(getName() + \".defaultView\", mViewMode == \"automatic\" ? \"\" : mViewMode);\n\t\tSettings::getInstance()->setString(getName() + \".gridSize\", Utils::String::replace(Utils::String::replace(mGridSizeOverride.toString(), \".000000\", \"\"), \"0 0\", \"\"));\n\t}\n\n\treturn true;\n}\n\nVector2f SystemData::getGridSizeOverride()\n{\n\treturn mGridSizeOverride;\n}\n\nbool SystemData::isNetplaySupported()\n{\n\tfor (auto emul : mEmulators)\n\t\tfor (auto core : emul.cores)\n\t\t\tif (core.netplay)\n\t\t\t\treturn true;\n\n\tif (isGroupSystem())\n\t\treturn false;\n\n\tif (!SystemData::es_features_loaded)\n\t\treturn getSystemEnvData() != nullptr && getSystemEnvData()->mLaunchCommand.find(\"%NETPLAY%\") != std::string::npos;\n\n\treturn false;\n}\n\nstd::string SystemData::getCompatibleCoreNames(EmulatorFeatures::Features feature)\n{\n\tstd::string ret;\n\n\tfor (auto emul : mEmulators)\n\t\tfor (auto core : emul.cores)\n\t\t\tif ((core.features & EmulatorFeatures::cheevos) == EmulatorFeatures::cheevos)\n\t\t\t\tret += ret.empty() ? core.name : \", \" + core.name;\n\n\treturn ret;\n}\n\n\nbool SystemData::isCheevosSupported()\n{\n\tif (isCollection())\n\t\treturn false;\n\n\tif (mIsCheevosSupported < 0)\n\t{\n\t\tmIsCheevosSupported = 0;\n\n\tconst std::set<std::string> cheevosSystems = {\n\t\t\"arcade\",\"atari2600\",\"atari7800\",\"atarilynx\",\"colecovision\",\"fbn\",\"gamegear\",\"gb\",\n\t\t\"gba\",\"gbc\",\"genesis\",\"intellivision\",\"mastersystem\",\"megacd\",\"megadrive\",\"msx\",\"msx2\",\"n64\",\"neogeo\",\"nes\",\"ngp\",\n\t\t\"ngpc\",\"odyssey2\",\"pcengine\",\"pcenginecd\",\"pokemini\",\"psx\",\"sega32x\",\"segacd\",\"sg-1000\",\n\t\t\"snes\",\"snesmsu1\",\"supervision\",\"tg16\",\"tg16cd\",\"vectrex\",\"virtualboy\",\"wonderswan\",\"wonderswancolor\"};\n\n\t\tif (cheevosSystems.find(getName()) != cheevosSystems.cend())\n\t\t{\n\t\t\tif (!es_features_loaded)\n\t\t\t{\n\t\t\t\tmIsCheevosSupported = 1;\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tfor (auto emul : mEmulators)\n\t\t\t{\n\t\t\t\tfor (auto core : emul.cores)\n\t\t\t\t{\n\t\t\t\t\tif ((core.features & EmulatorFeatures::cheevos) == EmulatorFeatures::cheevos)\n\t\t\t\t\t{\n\t\t\t\t\t\tmIsCheevosSupported = 1;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn mIsCheevosSupported != 0;\n}\n\nbool SystemData::isNetplayActivated()\n{\n\tfor (auto sys : SystemData::sSystemVector)\n\t\tif (sys->isNetplaySupported())\n\t\t\treturn true;\n\n\treturn false;\n}\n\nbool SystemData::isGroupChildSystem()\n{\n\tif (mEnvData != nullptr && !mEnvData->mGroup.empty())\n\t\treturn !Settings::getInstance()->getBool(mEnvData->mGroup + \".ungroup\");\n\n\treturn false;\n}\n\nstd::unordered_set<std::string> SystemData::getAllGroupNames()\n{\n\tstd::unordered_set<std::string> names;\n\n\tfor (auto sys : SystemData::sSystemVector)\n\t{\n\t\tif (sys->isGroupSystem())\n\t\t\tnames.insert(sys->getName());\n\t\telse if (sys->mEnvData != nullptr && !sys->mEnvData->mGroup.empty())\n\t\t\tnames.insert(sys->mEnvData->mGroup);\n\t}\n\n\treturn names;\n}\n\nstd::unordered_set<std::string> SystemData::getGroupChildSystemNames(const std::string groupName)\n{\n\tstd::unordered_set<std::string> names;\n\n\tfor (auto sys : SystemData::sSystemVector)\n\t\tif (sys->mEnvData != nullptr && sys->mEnvData->mGroup == groupName)\n\t\t\tnames.insert(sys->getFullName());\n\n\treturn names;\n}\n\nSystemData* SystemData::getParentGroupSystem()\n{\n\tif (!isGroupChildSystem() || isGroupSystem())\n\t\treturn this;\n\n\tfor (auto sys : SystemData::sSystemVector)\n\t\tif (sys->isGroupSystem() && sys->getName() == mEnvData->mGroup)\n\t\t\treturn sys;\n\n\treturn this;\n}\n\n\nstd::string SystemData::getEmulator(bool resolveDefault)\n{\n#if WIN32 && !_DEBUG\n\tstd::string emulator = Settings::getInstance()->getString(getName() + \".emulator\");\n#else\n\tstd::string emulator = SystemConf::getInstance()->get(getName() + \".emulator\");\n#endif\n\n\tfor (auto emul : mEmulators)\n\t\tif (emul.name == emulator)\n\t\t\treturn emulator;\n\n\tif (resolveDefault)\n\t\treturn getDefaultEmulator();\n\n\treturn \"\";\n}\n\nstd::string SystemData::getCore(bool resolveDefault)\n{\n#if WIN32 && !_DEBUG\n\tstd::string core = Settings::getInstance()->getString(getName() + \".core\");\n#else\n\tstd::string core = SystemConf::getInstance()->get(getName() + \".core\");\n#endif\n\n\tif (!core.empty() && core != \"auto\")\n\t{\n\t\tauto emul = getEmulator(true);\n\n\t\tfor (auto memul : mEmulators)\n\t\t\tif (memul.name == emul)\n\t\t\t\tfor (auto mcore : memul.cores)\n\t\t\t\t\tif (mcore.name == core)\n\t\t\t\t\t\treturn core;\n\t}\n\n\tif (!getEmulator(false).empty())\n\t\treturn getDefaultCore(getEmulator(false));\n\n\tif (resolveDefault)\n\t\treturn getDefaultCore(getEmulator(true));\n\n\treturn \"\";\n}\n\n\nstd::string SystemData::getDefaultEmulator()\n{\n\t\/\/ Seeking default=\"true\" attribute\n\tfor (auto emul : mEmulators)\n\t\tfor (auto core : emul.cores)\n\t\t\tif (core.isDefault)\n\t\t\t\treturn emul.name;\n\n\tauto emulators = getEmulators();\n\tif (emulators.size() > 0)\n\t\treturn emulators.begin()->name;\n\n\treturn \"\";\n}\n\nstd::string SystemData::getDefaultCore(const std::string emulatorName)\n{\n\tstd::string emul = emulatorName;\n\tif (emul.empty() || emul == \"auto\")\n\t\temul = getDefaultEmulator();\n\n\tif (emul.empty())\n\t\treturn \"\";\n\n\tfor (auto it : mEmulators)\n\t{\n\t\tif (it.name == emul)\n\t\t{\n\t\t\tfor (auto core : it.cores)\n\t\t\t\tif (core.isDefault)\n\t\t\t\t\treturn core.name;\n\n\t\t\tif (it.cores.size() > 0)\n\t\t\t\treturn it.cores.begin()->name;\n\t\t}\n\t}\n\n\treturn \"\";\n}\n\nstd::string SystemData::getLaunchCommand(const std::string emulatorName, const std::string coreName)\n{\n\tfor (auto emulator : mEmulators)\n\t{\n\t\tif (emulator.name == emulatorName)\n\t\t{\n\t\t\tfor (auto& core : emulator.cores)\n\t\t\t\tif (coreName == core.name && !core.customCommandLine.empty())\n\t\t\t\t\treturn core.customCommandLine;\n\n\t\t\tif (!emulator.customCommandLine.empty())\n\t\t\t\treturn emulator.customCommandLine;\n\t\t}\n\t}\n\n\treturn getSystemEnvData()->mLaunchCommand;\n}\n\nstd::vector<std::string> SystemData::getCoreNames(std::string emulatorName)\n{\n\tstd::vector<std::string> list;\n\n\tfor (auto& emulator : mEmulators)\n\t\tif (emulatorName == emulator.name)\n\t\t\tfor(auto& core : emulator.cores)\n\t\t\t\tlist.push_back(core.name);\n\n\treturn list;\n}\n\nbool SystemData::hasEmulatorSelection()\n{\n\tif (isCollection() || hasPlatformId(PlatformIds::PLATFORM_IGNORE))\n\t\treturn false;\n\n\tint ec = 0;\n\tint cc = 0;\n\n\tfor (auto& emulator : mEmulators)\n\t{\n\t\tec++;\n\t\tfor (auto& core : emulator.cores)\n\t\t\tcc++;\n\t}\n\n\treturn ec > 1 || cc > 1;\n}\n\nSystemData* SystemData::getSystem(const std::string name)\n{\n\tfor (auto sys : SystemData::sSystemVector)\n\t\tif (sys->getName() == name)\n\t\t\treturn sys;\n\n\treturn nullptr;\n}\n\n\/*# ${rom}.keys\n    # \/userdata\/system\/config\/evmapy\/${system}.${emulator}.${core}.keys\n    # \/userdata\/system\/config\/evmapy\/${system}.${emulator}.keys\n    # \/userdata\/system\/config\/evmapy\/${system}.keys\n    # \/usr\/share\/evmapy\/${system}.${emulator}.${core}.keys\n    # \/usr\/share\/evmapy\/${system}.${emulator}.keys\n    # \/usr\/share\/evmapy\/${system}.keys*\/\n\nstd::string SystemData::getKeyboardMappingFilePath()\n{\n#if WIN32\n\treturn Utils::FileSystem::getEsConfigPath() + \"\/padtokey\/\" + getName() + \".keys\";\n#else\n\treturn \"\/userdata\/system\/config\/evmapy\/\" + getName() + \".keys\";\n#endif\n}\n\nbool SystemData::hasKeyboardMapping()\n{\n\tif (isCollection())\n\t\treturn false;\n\n\treturn Utils::FileSystem::exists(getKeyboardMappingFilePath());\n}\n\nKeyMappingFile SystemData::getKeyboardMapping()\n{\n\tKeyMappingFile ret;\n\n\tif (Utils::FileSystem::exists(getKeyboardMappingFilePath()))\n\t\tret = KeyMappingFile::load(getKeyboardMappingFilePath());\n#if WIN32\n\telse\n\t{\n\t\tstd::string win32path = Win32ApiSystem::getEmulatorLauncherPath(\"system.padtokey\");\n\t\tif (!win32path.empty())\n\t\t\tret = KeyMappingFile::load(win32path + \"\/\" + getName() + \".keys\");\n\t}\n#else\n\telse if (Utils::FileSystem::exists(\"\/usr\/share\/evmapy\/\" + getName() + \".keys\")) \/\/ Load existing predefined settings\n\t\tret = KeyMappingFile::load(\"\/usr\/share\/evmapy\/\" + getName() + \".keys\");\n#endif\n\n\n\tret.path = getKeyboardMappingFilePath();\n\treturn ret;\n}\n\nbool SystemData::shouldExtractHashesFromArchives()\n{\n\treturn\n\t\t!hasPlatformId(PlatformIds::ARCADE) &&\n\t\t!hasPlatformId(PlatformIds::NEOGEO) &&\n\t\t!hasPlatformId(PlatformIds::DAPHNE) &&\n\t\t!hasPlatformId(PlatformIds::LUTRO) &&\n\t\t!hasPlatformId(PlatformIds::SEGA_DREAMCAST) &&\n\t\t!hasPlatformId(PlatformIds::ATOMISWAVE) &&\n\t\t!hasPlatformId(PlatformIds::NAOMI);\n}\n\nvoid SystemData::resetSettings()\n{\n\tfor(auto sys : sSystemVector)\n\t\tsys->mShowFilenames.reset();\n}\n\nbool SystemData::getShowFilenames()\n{\n\tif (mShowFilenames == nullptr)\n\t{\n\t\tauto curFn = Settings::getInstance()->getString(getName() + \".ShowFilenames\");\n\t\tif (curFn.empty())\n\t\t\tmShowFilenames = std::make_shared<bool>(Settings::getInstance()->getBool(\"ShowFilenames\"));\n\t\telse\n\t\t\tmShowFilenames = std::make_shared<bool>(curFn == \"1\");\n\t}\n\n\treturn *mShowFilenames;\n}\n\nSaveStateRepository* SystemData::getSaveStateRepository()\n{\n\tif (mSaveRepository == nullptr)\n\t\tmSaveRepository = new SaveStateRepository(this);\n\n\treturn mSaveRepository;\n}\n","avg_line_length":28.6810126582,"max_line_length":224,"alphanum_fraction":0.6872451231,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2077,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n   Product name: redemption, a FLOSS RDP proxy\n   Copyright (C) Wallix 2010\n   Author(s): Christophe Grosjean\n\n   Unit test to RDP BrushCache object\n   Using lib boost functions for testing\n*\/\n\n#include \"test_only\/test_framework\/redemption_unit_tests.hpp\"\n\n#include \"core\/RDP\/capabilities\/cap_brushcache.hpp\"\n\nRED_AUTO_TEST_CASE(TestCapabilityBrushCacheEmit)\n{\n    BrushCacheCaps brushcache_caps;\n    brushcache_caps.brushSupportLevel = BRUSH_COLOR_8X8;\n\n    RED_CHECK_EQUAL(brushcache_caps.capabilityType, static_cast<uint16_t>(CAPSTYPE_BRUSH));\n    RED_CHECK_EQUAL(brushcache_caps.len, static_cast<uint16_t>(CAPLEN_BRUSH));\n    RED_CHECK_EQUAL(brushcache_caps.brushSupportLevel, static_cast<uint32_t>(BRUSH_COLOR_8X8));\n\n    StaticOutStream<1024> out_stream;\n    brushcache_caps.emit(out_stream);\n\n    InStream stream(out_stream.get_produced_bytes());\n\n\n    BrushCacheCaps brushcache_caps2;\n\n    RED_CHECK_EQUAL(brushcache_caps2.capabilityType, static_cast<uint16_t>(CAPSTYPE_BRUSH));\n    RED_CHECK_EQUAL(brushcache_caps2.len, static_cast<uint16_t>(CAPLEN_BRUSH));\n\n    RED_CHECK_EQUAL(static_cast<uint16_t>(CAPSTYPE_BRUSH), stream.in_uint16_le());\n    RED_CHECK_EQUAL(static_cast<uint16_t>(CAPLEN_BRUSH), stream.in_uint16_le());\n    brushcache_caps2.recv(stream, CAPLEN_BRUSH);\n\n    RED_CHECK_EQUAL(brushcache_caps2.brushSupportLevel, static_cast<uint32_t>(BRUSH_COLOR_8X8));\n}\n","avg_line_length":38.462962963,"max_line_length":96,"alphanum_fraction":0.7852672123,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1390,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"#include \"..\/rpi_gpio.hpp\"\n#include <iostream>\n#include <thread>\n#include <chrono>\n#include <csignal>\n#include <functional>\n#include <atomic>\n#include <unistd.h>\n\nstd::atomic_bool stop(false);\n\nvoid sigIntHandler(int sigNum)\n{\n    stop = true;\n}\n\nvoid IRQThread(unsigned pin, bool high, const std::function<void()> &callback) {\n    try {\n        GPIO::Controller &gpio = GPIO::Controller::GetInstance();\n        while (!stop) {\n            for (auto event : gpio.GetEvents()) {\n                if ((event.number == pin) && (event.high == high)) {\n                    callback();\n                }\n            }\n            std::this_thread::sleep_for(std::chrono::milliseconds(100));\n        }\n    } catch (std::exception &error) {\n        std::cout << error.what() << std::endl;\n        stop = true;\n    }\n}\n\nint main(int argc, char** argv) {\n    unsigned pin = GPIO4;\n    int opt;\n    while ((opt = getopt(argc, argv, \"p:\")) != -1) {\n        switch (opt) {\n        case 'p':\n            pin = std::atoi(optarg);\n            break;\n        }\n    }\n\n    std::signal(SIGINT, sigIntHandler);\n    std::signal(SIGTSTP, sigIntHandler);\n\n    std::thread irqThread(IRQThread, pin, true, [&]() {\n        std::cout << \"Rising edge detected\" << std::endl;\n    });\n    while (!stop) {\n        std::this_thread::sleep_for(std::chrono::seconds(1));\n    }\n    irqThread.join();\n    return EXIT_SUCCESS;\n}","avg_line_length":24.8214285714,"max_line_length":80,"alphanum_fraction":0.5446043165,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1102,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <GL\/glew.h>\n#include <GLFW\/glfw3.h>\n\n#include <iostream>\n\nint main(void) {\n  GLFWwindow *window;\n\n  \/* Initialize the library *\/\n  if (!glfwInit())\n    return -1;\n\n  \/* Create a windowed mode window and its OpenGL context *\/\n  window = glfwCreateWindow(640, 480, \"Hello World\", NULL, NULL);\n  if (!window) {\n    glfwTerminate();\n    return -1;\n  }\n\n  \/* Make the window's context current *\/\n  glfwMakeContextCurrent(window);\n\n  if (GLEW_OK != glewInit()) { \/\/ This needs to be after setting current context\n    std::cout << \"Error!\" << std::endl;\n  }\n\n  \/\/ unsigned int a;\n  \/\/ glGenBuffers(1, &a);\n\n  std::cout << glGetString(GL_VERSION) << std::endl;\n\n  \/* Loop until the user closes the window *\/\n  while (!glfwWindowShouldClose(window)) {\n    \/* Render here *\/\n    glClear(GL_COLOR_BUFFER_BIT);\n\n    glBegin(GL_TRIANGLES);\n    glVertex2f(-0.5f, -0.5f);\n    glVertex2f(+0.5f, -0.5f);\n    glVertex2f(0, +0.5f);\n    glEnd();\n\n    \/* Swap front and back buffers *\/\n    glfwSwapBuffers(window);\n\n    \/* Poll for and process events *\/\n    glfwPollEvents();\n  }\n\n  glfwTerminate();\n  return 0;\n}\n","avg_line_length":20.7924528302,"max_line_length":80,"alphanum_fraction":0.6261343013,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1408,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":5.0,"content":"#include \"registry.h\"\n\nnamespace {\n\tusing data_t\t\t\t = std::vector<std::string>;\n\tconstexpr int day_number = 2;\n\n\tauto get_input = [](data_t& data) -> void {\n\t\tusing namespace std::literals::string_literals;\n\t\tstd::ifstream input{ \"day\" + std::to_string(day_number) + \".txt\" };\n\n\t\tstd::string buf;\n\t\twhile (std::getline(input, buf)) {\n\t\t\tdata.push_back(buf);\n\t\t}\n\t};\n\n\tauto p1 = [](const data_t& data) -> int64_t {\n\t\tstd::regex r{ \"(\\\\d+)-(\\\\d+) ([a-z]): ([a-z]+)\" };\n\t\tint valid = 0;\n\n\t\tfor (auto line : data) {\n\t\t\tstd::smatch m;\n\t\t\tif (std::regex_match(line, m, r)) {\n\t\t\t\tint number_of_c = 0;\n\t\t\t\tfor (char c : m[4].str()) {\n\t\t\t\t\tif (c == m[3].str()[0]) {\n\t\t\t\t\t\t++number_of_c;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (number_of_c <= std::stoi(m[2].str()) &&\n\t\t\t\t\tnumber_of_c >= std::stoi(m[1].str())) {\n\t\t\t\t\t++valid;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn valid;\n\t};\n\n\tauto p2 = [](const data_t& data) -> int64_t {\n\t\tstd::regex r{ \"(\\\\d+)-(\\\\d+) ([a-z]): ([a-z]+)\" };\n\t\tint valid = 0;\n\n\t\tfor (auto line : data) {\n\t\t\tstd::smatch m;\n\t\t\tif (std::regex_match(line, m, r)) {\n\t\t\t\tstd::string pwd = m[4].str();\n\t\t\t\tchar c\t\t\t= m[3].str()[0];\n\t\t\t\tint lower_pos\t= std::stoi(m[1].str()) - 1;\n\t\t\t\tint upper_pos\t= std::stoi(m[2].str()) - 1;\n\n\t\t\t\tif (pwd[lower_pos] != pwd[upper_pos] &&\n\t\t\t\t\t(pwd[lower_pos] == c || pwd[upper_pos] == c)) {\n\t\t\t\t\t++valid;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn valid;\n\t};\n}\n\nday<data_t> day2 = day<data_t>(day_number, get_input, p1, p2);","avg_line_length":22.3492063492,"max_line_length":69,"alphanum_fraction":0.5255681818,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4042,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":3.0,"content":"#include <opencv2\/opencv.hpp>\n#include <iostream>\n\n#include \"imgStream.h\"\n#include \"TLD.h\"\n\nusing namespace std;\nusing namespace cv;\n\ncv::Mat imgDisplay, tmp;\ncv::Rect initRect;\nint initBreak;\nstatic void on_mouse(int event, int x, int y, int flags, void *ustc);\nvoid configureTracker(tld::TLD *tracker, Mat grey);\n\nint main(int argc, char **argv)\n{\n\timgStream *test;\n\tint initWaitKey = 0;\n\tif (argc != 3)\n\t{\n\t\ttest = new imgStream();\n\t\tinitWaitKey = 20;\n\t}\n\telse\n\t{\n\t\tint method = IMACQ_CAM;\n\t\tif (strcmp(argv[1], \"-IMG\") == 0)\n\t\t{\n\t\t\tmethod = IMACQ_IMGS;\n\t\t\tinitWaitKey = 0;\n\t\t}\n\t\tif (strcmp(argv[1], \"-VID\") == 0)\n\t\t{\n\t\t\tmethod = IMACQ_VID;\n\t\t\tinitWaitKey = 0;\n\t\t}\n\t\tif (strcmp(argv[1], \"-CAM\") == 0)\n\t\t{\n\t\t\tmethod = IMACQ_CAM;\n\t\t\tinitWaitKey = 20;\n\t\t}\n\t\tstring imgPath(argv[2]);\n\t\ttest = new imgStream(method, imgPath);\n\t\tcout << imgPath << endl;\n\t}\n\n\tint seed = 0;\n\tsrand(seed);\n\tinitBreak = 0;\n\tnamedWindow(\"img\");\n\tsetMouseCallback(\"img\", on_mouse, 0);\n\twhile (test->getCurrImage() == 1)\n\t{\n\t\ttest->currImage.copyTo(imgDisplay);\n\t\ttest->currImage.copyTo(tmp);\n\t\tif (initBreak == 1)\n\t\t\tbreak;\n\t\timshow(\"img\", tmp);\n\t\twaitKey(initWaitKey);\n\t}\n\n\tMat grey(imgDisplay.rows, imgDisplay.cols, CV_8UC1);\n\tcvtColor(imgDisplay, grey, CV_BGR2GRAY);\n\n\ttld::TLD *trackerTLD = new tld::TLD();\n\tconfigureTracker(trackerTLD, grey);\n\ttrackerTLD->selectObject(grey, imgDisplay, &initRect);\n\n\tcv::Mat imageCurr;\n\twhile (test->getCurrImage() == 1)\n\t{\n\t\ttest->currImage.copyTo(imageCurr);\n\t\timageCurr.copyTo(imgDisplay);\n\t\tdouble tic = cvGetTickCount();\n\t\ttrackerTLD->processImage(imageCurr);\n\t\tdouble toc = (cvGetTickCount() - tic) \/ cvGetTickFrequency();\n\t\ttoc = toc \/ 1000000;\n\t\tfloat fps = 1 \/ toc;\n\t\tostringstream getString;\n\t\tgetString << \"fps: \" << fps;\n\t\tcv::putText(imgDisplay, getString.str(), Point(20, 30), FONT_HERSHEY_SIMPLEX, 1, Scalar(0, 0, 255, 255));\n\t\tif (trackerTLD->currBB != NULL)\n\t\t\tcv::rectangle(imgDisplay, Rect(trackerTLD->currBB->x, trackerTLD->currBB->y, trackerTLD->currBB->width, trackerTLD->currBB->height), Scalar(0, 255, 0, 255), 4);\n\t\tcv::imshow(\"img\", imgDisplay);\n\t\tchar key = cv::waitKey(20);\n\t\tif (key == 'q')\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\tdelete trackerTLD;\n\tdelete test;\n\treturn 0;\n}\n\n\nvoid configureTracker(tld::TLD *tracker, Mat grey)\n{\n\n\ttracker->alternating = false;\n\ttracker->trackerEnabled = true;\n\ttracker->learningEnabled = true;\n\ttracker->detectorCascade->varianceFilter->enabled = true;\n\ttracker->detectorCascade->ensembleClassifier->enabled = true;\n\ttracker->detectorCascade->nnClassifier->enabled = true;\n\n\t\/\/ classifier\n\ttracker->detectorCascade->useShift = true;\n\ttracker->detectorCascade->shift = 0.1;\n\ttracker->detectorCascade->minScale = -10;\n\ttracker->detectorCascade->maxScale = 10;\n\ttracker->detectorCascade->minSize = 25;\n\ttracker->detectorCascade->numTrees = 10;\n\ttracker->detectorCascade->numFeatures = 13;\n\ttracker->detectorCascade->nnClassifier->thetaTP = 0.65;\n\ttracker->detectorCascade->nnClassifier->thetaFP = 0.5;\n\n\ttracker->detectorCascade->imgWidth = grey.cols;\n\ttracker->detectorCascade->imgHeight = grey.rows;\n\ttracker->detectorCascade->imgWidthStep = grey.step;\n\n}\n\n\nstatic void on_mouse(int event, int x, int y, int flags, void *ustc)\n{\n\tstatic Point pre_pt(-1, -1);\n\tstatic Point cur_pt(-1, -1);\n\tchar temp[16];\n\n\tif (event == CV_EVENT_LBUTTONDOWN)\n\t{\n\t\tpre_pt = Point(x, y);\n\t}\n\telse if (event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON))\n\t{\n\t\ttmp.copyTo(imgDisplay);\n\t\tcur_pt = Point(x, y);\n\t\trectangle(imgDisplay, pre_pt, cur_pt, Scalar(0, 255, 0, 0), 2, 8, 0);\n\t\timshow(\"img\", imgDisplay);\n\t}\n\telse if (event == CV_EVENT_LBUTTONUP)\n\t{\n\t\tprintf(temp, \"(%d,%d)\", x, y);\n\t\tcur_pt = Point(x, y);\n\t\trectangle(tmp, pre_pt, cur_pt, Scalar(0, 255, 0, 0), 2, 8, 0);\n\t\timshow(\"img\", tmp);\n\t\tint width = abs(pre_pt.x - cur_pt.x);\n\t\tint height = abs(pre_pt.y - cur_pt.y);\n\t\tif (width == 0 || height == 0)\n\t\t{\n\t\t\tprintf(\"width == 0 || height == 0\");\n\t\t\treturn;\n\t\t}\n\t\tinitRect = Rect(min(cur_pt.x, pre_pt.x), min(cur_pt.y, pre_pt.y), width, height);\n\t\tinitBreak = 1;\n\t}\n\twaitKey(1);\n}\n","avg_line_length":25.1055900621,"max_line_length":163,"alphanum_fraction":0.6697179614,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":808,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"kalman_filter.h\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nnamespace kalman_filter {\n\n\/\/ Update x and P, given the motion model and uncertainty\nvoid Predict(VectorXd &x, MatrixXd &P, const MatrixXd &F, const MatrixXd &Q) {\n\n  x = F * x;\n  P = F * P * (F.transpose()) + Q;\n\n}\n\n\/\/ Update x and P given the measurement residual\nvoid Update(VectorXd &x, MatrixXd &P, const MatrixXd &H, const MatrixXd &R, const VectorXd& yk) {\n\n  const int nx = x.size();\n  const MatrixXd Idx = MatrixXd::Identity(nx,nx);\n  const MatrixXd Sk = H * P * (H.transpose()) + R;\n  const MatrixXd Kk = P * (H.transpose()) * (Sk.inverse());\n  x = x + Kk * yk;\n  P = (Idx - Kk*H) * P * (Idx - Kk * H).transpose()  +  Kk * R * Kk.transpose(); \/\/ this form helps to maintain symmetric P\n\n}\n\n}   \/\/ namespace kalman_filter\n\n\n","avg_line_length":26.064516129,"max_line_length":123,"alphanum_fraction":0.6410891089,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2505,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/*\n *******************************************************************************\n * Copyright (c) 2020-2021, STMicroelectronics\n * All rights reserved.\n *\n * This software component is licensed by ST under BSD 3-Clause license,\n * the \"License\"; You may not use this file except in compliance with the\n * License. You may obtain a copy of the License at:\n *                        opensource.org\/licenses\/BSD-3-Clause\n *\n *******************************************************************************\n *\/\n#if defined(ARDUINO_GENERIC_H730VBHX) || defined(ARDUINO_GENERIC_H730VBTX)\n#include \"pins_arduino.h\"\n\n\/\/ Digital PinName array\nconst PinName digitalPin[] = {\n  PA_0,   \/\/ D1\/A0\n  PA_1,   \/\/ D2\/A1\n  PA_2,   \/\/ D3\/A2\n  PA_3,   \/\/ D4\/A3\n  PA_4,   \/\/ D5\/A4\n  PA_5,   \/\/ D6\/A5\n  PA_6,   \/\/ D7\/A6\n  PA_7,   \/\/ D8\/A7\n  PA_8,   \/\/ D9\n  PA_9,   \/\/ D10\n  PA_10,  \/\/ D11\n  PA_11,  \/\/ D12\n  PA_12,  \/\/ D13\n  PA_13,  \/\/ D14\n  PA_14,  \/\/ D15\n  PA_15,  \/\/ D16\n  PB_0,   \/\/ D17\/A8\n  PB_1,   \/\/ D18\/A9\n  PB_2,   \/\/ D19\n  PB_3,   \/\/ D20\n  PB_4,   \/\/ D21\n  PB_5,   \/\/ D22\n  PB_6,   \/\/ D23\n  PB_7,   \/\/ D24\n  PB_8,   \/\/ D25\n  PB_9,   \/\/ D26\n  PB_10,  \/\/ D27\n  PB_11,  \/\/ D28\n  PB_12,  \/\/ D29\n  PB_13,  \/\/ D30\n  PB_14,  \/\/ D31\n  PB_15,  \/\/ D32\n  PC_0,   \/\/ D33\/A10\n  PC_1,   \/\/ D34\/A11\n  PC_4,   \/\/ D35\/A12\n  PC_5,   \/\/ D36\/A13\n  PC_6,   \/\/ D37\n  PC_7,   \/\/ D38\n  PC_8,   \/\/ D39\n  PC_9,   \/\/ D40\n  PC_10,  \/\/ D41\n  PC_11,  \/\/ D42\n  PC_12,  \/\/ D43\n  PC_13,  \/\/ D44\n  PC_14,  \/\/ D45\n  PC_15,  \/\/ D46\n  PD_0,   \/\/ D47\n  PD_1,   \/\/ D48\n  PD_2,   \/\/ D49\n  PD_3,   \/\/ D50\n  PD_4,   \/\/ D51\n  PD_5,   \/\/ D52\n  PD_6,   \/\/ D53\n  PD_7,   \/\/ D54\n  PD_8,   \/\/ D55\n  PD_9,   \/\/ D56\n  PD_10,  \/\/ D57\n  PD_11,  \/\/ D58\n  PD_12,  \/\/ D59\n  PD_13,  \/\/ D60\n  PD_14,  \/\/ D61\n  PD_15,  \/\/ D62\n  PE_0,   \/\/ D63\n  PE_1,   \/\/ D64\n  PE_2,   \/\/ D65\n  PE_3,   \/\/ D66\n  PE_4,   \/\/ D67\n  PE_5,   \/\/ D68\n  PE_6,   \/\/ D69\n  PE_7,   \/\/ D70\n  PE_8,   \/\/ D71\n  PE_9,   \/\/ D72\n  PE_10,  \/\/ D73\n  PE_11,  \/\/ D74\n  PE_12,  \/\/ D75\n  PE_13,  \/\/ D76\n  PE_14,  \/\/ D77\n  PE_15,  \/\/ D78\n  PH_0,   \/\/ D79\n  PH_1,   \/\/ D80\n  PC_2_C, \/\/ D81\/A14\n  PC_3_C  \/\/ D82\/A15\n};\n\n\/\/ Analog (Ax) pin number array\nconst uint32_t analogInputPin[] = {\n  0,  \/\/ A0,  PA0\n  1,  \/\/ A1,  PA1\n  2,  \/\/ A2,  PA2\n  3,  \/\/ A3,  PA3\n  4,  \/\/ A4,  PA4\n  5,  \/\/ A5,  PA5\n  6,  \/\/ A6,  PA6\n  7,  \/\/ A7,  PA7\n  16, \/\/ A8,  PB0\n  17, \/\/ A9,  PB1\n  32, \/\/ A10, PC0\n  33, \/\/ A11, PC1\n  34, \/\/ A12, PC4\n  35, \/\/ A13, PC5\n  80, \/\/ A14, PC2_C\n  81  \/\/ A15, PC3_C\n};\n\n#endif \/* ARDUINO_GENERIC_* *\/\n","avg_line_length":20.3658536585,"max_line_length":80,"alphanum_fraction":0.4710578842,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":18526,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2012-2013 The PPCoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/assign\/list_of.hpp>\n\n#include \"kernel.h\"\n#include \"db.h\"\n\nusing namespace std;\n\nextern int nStakeMaxAge;\nextern int nStakeTargetSpacing;\n\n\/\/ Modifier interval: time to elapse before new modifier is computed\n\/\/ Set to 6-hour for production network and 20-minute for test network\nunsigned int nModifierInterval = MODIFIER_INTERVAL;\n\n\/\/ Hard checkpoints of stake modifiers to ensure they are deterministic\nstatic std::map<int, unsigned int> mapStakeModifierCheckpoints =\n    boost::assign::map_list_of\n    ( 0, 0x0e00670bu )\n\t\/\/( 124000, 0xe791f02cu )\n    \n    ;\n\n\/\/ Get the last stake modifier and its generation time from a given block\nstatic bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)\n{\n    if (!pindex)\n        return error(\"GetLastStakeModifier: null pindex\");\n    while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())\n        pindex = pindex->pprev;\n    if (!pindex->GeneratedStakeModifier())\n        return error(\"GetLastStakeModifier: no generation at genesis block\");\n    nStakeModifier = pindex->nStakeModifier;\n    nModifierTime = pindex->GetBlockTime();\n    return true;\n}\n\n\/\/ Get selection interval section (in seconds)\nstatic int64 GetStakeModifierSelectionIntervalSection(int nSection)\n{\n    assert (nSection >= 0 && nSection < 64);\n    return (nModifierInterval * 63 \/ (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));\n}\n\n\/\/ Get stake modifier selection interval (in seconds)\nstatic int64 GetStakeModifierSelectionInterval()\n{\n    int64 nSelectionInterval = 0;\n    for (int nSection=0; nSection<64; nSection++)\n        nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);\n    return nSelectionInterval;\n}\n\n\/\/ select a block from the candidate blocks in vSortedByTimestamp, excluding\n\/\/ already selected blocks in vSelectedBlocks, and with timestamp up to\n\/\/ nSelectionIntervalStop.\nstatic bool SelectBlockFromCandidates(\n    vector<pair<int64, uint256> >& vSortedByTimestamp,\n    map<uint256, const CBlockIndex*>& mapSelectedBlocks,\n    int64 nSelectionIntervalStop, uint64 nStakeModifierPrev,\n    const CBlockIndex** pindexSelected)\n{\n    bool fSelected = false;\n    uint256 hashBest = 0;\n    *pindexSelected = (const CBlockIndex*) 0;\n    BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)\n    {\n        if (!mapBlockIndex.count(item.second))\n            return error(\"SelectBlockFromCandidates: failed to find block index for candidate block %s\", item.second.ToString().c_str());\n        const CBlockIndex* pindex = mapBlockIndex[item.second];\n        if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)\n            break;\n        if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)\n            continue;\n        \/\/ compute the selection hash by hashing its proof-hash and the\n        \/\/ previous proof-of-stake modifier\n        uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();\n        CDataStream ss(SER_GETHASH, 0);\n        ss << hashProof << nStakeModifierPrev;\n        uint256 hashSelection = Hash(ss.begin(), ss.end());\n        \/\/ the selection hash is divided by 2**32 so that proof-of-stake block\n        \/\/ is always favored over proof-of-work block. this is to preserve\n        \/\/ the energy efficiency property\n        if (pindex->IsProofOfStake())\n            hashSelection >>= 32;\n        if (fSelected && hashSelection < hashBest)\n        {\n            hashBest = hashSelection;\n            *pindexSelected = (const CBlockIndex*) pindex;\n        }\n        else if (!fSelected)\n        {\n            fSelected = true;\n            hashBest = hashSelection;\n            *pindexSelected = (const CBlockIndex*) pindex;\n        }\n    }\n    if (fDebug && GetBoolArg(\"-printstakemodifier\"))\n        printf(\"SelectBlockFromCandidates: selection hash=%s\\n\", hashBest.ToString().c_str());\n    return fSelected;\n}\n\n\/\/ Stake Modifier (hash modifier of proof-of-stake):\n\/\/ The purpose of stake modifier is to prevent a txout (coin) owner from\n\/\/ computing future proof-of-stake generated by this txout at the time\n\/\/ of transaction confirmation. To meet kernel protocol, the txout\n\/\/ must hash with a future stake modifier to generate the proof.\n\/\/ Stake modifier consists of bits each of which is contributed from a\n\/\/ selected block of a given block group in the past.\n\/\/ The selection of a block is based on a hash of the block's proof-hash and\n\/\/ the previous stake modifier.\n\/\/ Stake modifier is recomputed at a fixed time interval instead of every \n\/\/ block. This is to make it difficult for an attacker to gain control of\n\/\/ additional bits in the stake modifier, even after generating a chain of\n\/\/ blocks.\nbool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier)\n{\n    nStakeModifier = 0;\n    fGeneratedStakeModifier = false;\n    if (!pindexPrev)\n    {\n        fGeneratedStakeModifier = true;\n        return true;  \/\/ genesis block's modifier is 0\n    }\n    \/\/ First find current stake modifier and its generation block time\n    \/\/ if it's not old enough, return the same stake modifier\n    int64 nModifierTime = 0;\n    if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))\n        return error(\"ComputeNextStakeModifier: unable to get last modifier\");\n    if (fDebug)\n    {\n        printf(\"ComputeNextStakeModifier: prev modifier=0x%016\"PRI64x\" time=%s\\n\", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());\n    }\n    if (nModifierTime \/ nModifierInterval >= pindexPrev->GetBlockTime() \/ nModifierInterval)\n        return true;\n\n    \/\/ Sort candidate blocks by timestamp\n    vector<pair<int64, uint256> > vSortedByTimestamp;\n    vSortedByTimestamp.reserve(64 * nModifierInterval \/ nStakeTargetSpacing);\n    int64 nSelectionInterval = GetStakeModifierSelectionInterval();\n    int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() \/ nModifierInterval) * nModifierInterval - nSelectionInterval;\n    const CBlockIndex* pindex = pindexPrev;\n    while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)\n    {\n        vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));\n        pindex = pindex->pprev;\n    }\n    int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;\n    reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());\n    sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());\n\n    \/\/ Select 64 blocks from candidate blocks to generate stake modifier\n    uint64 nStakeModifierNew = 0;\n    int64 nSelectionIntervalStop = nSelectionIntervalStart;\n    map<uint256, const CBlockIndex*> mapSelectedBlocks;\n    for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)\n    {\n        \/\/ add an interval section to the current selection round\n        nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);\n        \/\/ select a block from the candidates of current round\n        if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))\n            return error(\"ComputeNextStakeModifier: unable to select block at round %d\", nRound);\n        \/\/ write the entropy bit of the selected block\n        nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);\n        \/\/ add the selected block from candidates to selected list\n        mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));\n        if (fDebug && GetBoolArg(\"-printstakemodifier\"))\n            printf(\"ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\\n\",\n                nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());\n    }\n\n    \/\/ Print selection map for visualization of the selected blocks\n    if (fDebug && GetBoolArg(\"-printstakemodifier\"))\n    {\n        string strSelectionMap = \"\";\n        \/\/ '-' indicates proof-of-work blocks not selected\n        strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');\n        pindex = pindexPrev;\n        while (pindex && pindex->nHeight >= nHeightFirstCandidate)\n        {\n            \/\/ '=' indicates proof-of-stake blocks not selected\n            if (pindex->IsProofOfStake())\n                strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, \"=\");\n            pindex = pindex->pprev;\n        }\n        BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)\n        {\n            \/\/ 'S' indicates selected proof-of-stake blocks\n            \/\/ 'W' indicates selected proof-of-work blocks\n            strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? \"S\" : \"W\");\n        }\n        printf(\"ComputeNextStakeModifier: selection height [%d, %d] map %s\\n\", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());\n    }\n    if (fDebug)\n    {\n        printf(\"ComputeNextStakeModifier: new modifier=0x%016\"PRI64x\" time=%s\\n\", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());\n    }\n\n    nStakeModifier = nStakeModifierNew;\n    fGeneratedStakeModifier = true;\n    return true;\n}\n\n\/\/ The stake modifier used to hash for a stake kernel is chosen as the stake\n\/\/ modifier about a selection interval later than the coin generating the kernel\nstatic bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)\n{\n    nStakeModifier = 0;\n    if (!mapBlockIndex.count(hashBlockFrom))\n        return error(\"GetKernelStakeModifier() : block not indexed\");\n    const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];\n    nStakeModifierHeight = pindexFrom->nHeight;\n    nStakeModifierTime = pindexFrom->GetBlockTime();\n    int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();\n    const CBlockIndex* pindex = pindexFrom;\n    \/\/ loop to find the stake modifier later by a selection interval\n    while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)\n    {\n        if (!pindex->pnext)\n        {   \/\/ reached best block; may happen if node is behind on block chain\n            if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))\n                return error(\"GetKernelStakeModifier() : reached best block %s at height %d from block %s\",\n                    pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());\n            else\n                return false;\n        }\n        pindex = pindex->pnext;\n        if (pindex->GeneratedStakeModifier())\n        {\n            nStakeModifierHeight = pindex->nHeight;\n            nStakeModifierTime = pindex->GetBlockTime();\n        }\n    }\n    nStakeModifier = pindex->nStakeModifier;\n    return true;\n}\n\n\/\/ ppcoin kernel protocol\n\/\/ coinstake must meet hash target according to the protocol:\n\/\/ kernel (input 0) must meet the formula\n\/\/     hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight\n\/\/ this ensures that the chance of getting a coinstake is proportional to the\n\/\/ amount of coin age one owns.\n\/\/ The reason this hash is chosen is the following:\n\/\/   nStakeModifier: \n\/\/       (v0.3) scrambles computation to make it very difficult to precompute\n\/\/              future proof-of-stake at the time of the coin's confirmation\n\/\/       (v0.2) nBits (deprecated): encodes all past block timestamps\n\/\/   txPrev.block.nTime: prevent nodes from guessing a good timestamp to\n\/\/                       generate transaction for future advantage\n\/\/   txPrev.offset: offset of txPrev inside block, to reduce the chance of \n\/\/                  nodes generating coinstake at the same time\n\/\/   txPrev.nTime: reduce the chance of nodes generating coinstake at the same\n\/\/                 time\n\/\/   txPrev.vout.n: output number of txPrev, to reduce the chance of nodes\n\/\/                  generating coinstake at the same time\n\/\/   block\/tx hash should not be used here as they can be generated in vast\n\/\/   quantities so as to generate blocks faster, degrading the system back into\n\/\/   a proof-of-work situation.\n\/\/\nbool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, bool fPrintProofOfStake)\n{\n    if (nTimeTx < txPrev.nTime)  \/\/ Transaction timestamp violation\n        return error(\"CheckStakeKernelHash() : nTime violation\");\n\n    unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();\n    if (nTimeBlockFrom + nStakeMinAge > nTimeTx) \/\/ Min age requirement\n        return error(\"CheckStakeKernelHash() : min age violation\");\n\n    CBigNum bnTargetPerCoinDay;\n    bnTargetPerCoinDay.SetCompact(nBits);\n    int64 nValueIn = txPrev.vout[prevout.n].nValue;\n\n    \/\/ v0.3 protocol kernel hash weight starts from 0 at the 30-day min age\n    \/\/ this change increases active coins participating the hash and helps\n    \/\/ to secure the network when proof-of-stake difficulty is low\n    int64 nTimeWeight = min((int64)nTimeTx - txPrev.nTime, (int64)nStakeMaxAge) - nStakeMinAge;\n    CBigNum bnCoinDayWeight = CBigNum(nValueIn) * nTimeWeight \/ COIN \/ (24 * 60 * 60);\n\n    \/\/ Calculate hash\n    CDataStream ss(SER_GETHASH, 0);\n    uint64 nStakeModifier = 0;\n    int nStakeModifierHeight = 0;\n    int64 nStakeModifierTime = 0;\n\n    if (!GetKernelStakeModifier(blockFrom.GetHash(), nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))\n        return false;\n    ss << nStakeModifier;\n\n    ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;\n    hashProofOfStake = Hash(ss.begin(), ss.end());\n    if (fPrintProofOfStake)\n    {\n        printf(\"CheckStakeKernelHash() : using modifier 0x%016\"PRI64x\" at height=%d timestamp=%s for block from height=%d timestamp=%s\\n\",\n            nStakeModifier, nStakeModifierHeight,\n            DateTimeStrFormat(nStakeModifierTime).c_str(),\n            mapBlockIndex[blockFrom.GetHash()]->nHeight,\n            DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());\n        printf(\"CheckStakeKernelHash() : check protocol=%s modifier=0x%016\"PRI64x\" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\\n\",\n            \"0.3\",\n            nStakeModifier,\n            nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,\n            hashProofOfStake.ToString().c_str());\n    }\n\n    \/\/ Now check if proof-of-stake hash meets target protocol\n    if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)\n        return false;\n    if (fDebug && !fPrintProofOfStake)\n    {\n        printf(\"CheckStakeKernelHash() : using modifier 0x%016\"PRI64x\" at height=%d timestamp=%s for block from height=%d timestamp=%s\\n\",\n            nStakeModifier, nStakeModifierHeight, \n            DateTimeStrFormat(nStakeModifierTime).c_str(),\n            mapBlockIndex[blockFrom.GetHash()]->nHeight,\n            DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());\n        printf(\"CheckStakeKernelHash() : pass protocol=%s modifier=0x%016\"PRI64x\" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\\n\",\n            \"0.3\",\n            nStakeModifier,\n            nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,\n            hashProofOfStake.ToString().c_str());\n    }\n    return true;\n}\n\n\/\/ Check kernel hash target and coinstake signature\nbool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake)\n{\n    if (!tx.IsCoinStake())\n        return error(\"CheckProofOfStake() : called on non-coinstake %s\", tx.GetHash().ToString().c_str());\n\n    \/\/ Kernel (input 0) must match the stake hash target per coin age (nBits)\n    const CTxIn& txin = tx.vin[0];\n\n    \/\/ First try finding the previous transaction in database\n    CTxDB txdb(\"r\");\n    CTransaction txPrev;\n    CTxIndex txindex;\n    if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))\n        return tx.DoS(1, error(\"CheckProofOfStake() : INFO: read txPrev failed\"));  \/\/ previous transaction not in main chain, may occur during initial download\n    txdb.Close();\n\n    \/\/ Verify signature\n    if (!VerifySignature(txPrev, tx, 0, true, 0))\n        return tx.DoS(100, error(\"CheckProofOfStake() : VerifySignature failed on coinstake %s\", tx.GetHash().ToString().c_str()));\n\n    \/\/ Read block header\n    CBlock block;\n    if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))\n        return fDebug? error(\"CheckProofOfStake() : read block failed\") : false; \/\/ unable to read block of previous transaction\n\n    if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, fDebug))\n        return tx.DoS(1, error(\"CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s\", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str())); \/\/ may occur during initial download or if behind on block chain sync\n\n    return true;\n}\n\n\/\/ Check whether the coinstake timestamp meets protocol\nbool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx)\n{\n    \/\/ v0.3 protocol\n    return (nTimeBlock == nTimeTx);\n}\n\n\/\/ Get stake modifier checksum\nunsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)\n{\n    assert (pindex->pprev || pindex->GetBlockHash() == hashGenesisBlock);\n    \/\/ Hash previous checksum with flags, hashProofOfStake and nStakeModifier\n    CDataStream ss(SER_GETHASH, 0);\n    if (pindex->pprev)\n        ss << pindex->pprev->nStakeModifierChecksum;\n    ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;\n    uint256 hashChecksum = Hash(ss.begin(), ss.end());\n    hashChecksum >>= (256 - 32);\n    return hashChecksum.Get64();\n}\n\n\/\/ Check stake modifier hard checkpoints\nbool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)\n{\n    if (fTestNet) return true; \/\/ Testnet has no checkpoints\n    if (mapStakeModifierCheckpoints.count(nHeight))\n        return nStakeModifierChecksum == mapStakeModifierCheckpoints[nHeight];\n    return true;\n}\n","avg_line_length":47.6246786632,"max_line_length":253,"alphanum_fraction":0.7011227464,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":573,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include<iostream>\n#include<bits\/stdc++.h>\n\nusing namespace std;\n\nint Bin_1(int num)\n{\n    int sum=0;\n    while(num!=0)\n    {\n        sum += num%2;\n        num\/=2;\n    }\n    return sum;\n}\n\nint HEX(int num)\n{\n    int hex;\n    int sum=0;\n    while(num!=0)\n    {\n        hex = num%10;\n\n        sum+=Bin_1(hex);\n       \/\/ cout<<sum<<endl;\n\n        num\/=10;\n    }\n\n    return sum;\n\n}\n\nint main()\n{\n    int test,num;\n    cin>>test;\n    while(test--)\n    {\n        cin>>num;\n        int bin1 = Bin_1(num);\n        int bin2 = HEX(num);\n        printf(\"%d %d\\n\",bin1,bin2);\n    }\n}\n","avg_line_length":12.1914893617,"max_line_length":36,"alphanum_fraction":0.4537521815,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":33258,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2.0,"content":"\/*\n * Copyright (c) 2021 Huawei Device Co., Ltd.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"account_log_wrapper.h\"\n#include \"app_account_data_storage.h\"\n#include \"app_account_info.h\"\n#include \"ipc_skeleton.h\"\n#include \"ohos_account_kits.h\"\n#include \"singleton.h\"\n\n#include \"app_account_control_manager.h\"\n\nnamespace OHOS {\nnamespace AccountSA {\nAppAccountControlManager::AppAccountControlManager()\n{\n    ACCOUNT_LOGI(\"enter\");\n}\n\nAppAccountControlManager::~AppAccountControlManager()\n{\n    ACCOUNT_LOGI(\"enter\");\n}\n\nErrCode AppAccountControlManager::AddAccount(const std::string &name, const std::string &extraInfo,\n    const std::string &bundleName, AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n    ACCOUNT_LOGI(\"extraInfo = %{public}s\", extraInfo.c_str());\n\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n\n        result = appAccountInfo.SetExtraInfo(extraInfo);\n        if (result != ERR_OK) {\n            ACCOUNT_LOGI(\"failed to set extra info\");\n            return ERR_APPACCOUNT_SERVICE_SET_EXTRA_INFO;\n        }\n\n        result = AddAccountInfoIntoDataStorage(appAccountInfo);\n        if (result != ERR_OK) {\n            ACCOUNT_LOGE(\"failed to add account info into data storage\");\n            return result;\n        }\n    } else {\n        ACCOUNT_LOGE(\"add existing account\");\n        return ERR_APPACCOUNT_SERVICE_ADD_EXISTING_ACCOUNT;\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::DeleteAccount(\n    const std::string &name, const std::string &bundleName, AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n\n    ErrCode result = DeleteAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to delete account info from data storage\");\n        return result;\n    }\n\n    auto it = dataCache_.find(appAccountInfo.GetPrimeKey());\n    if (it == dataCache_.end()) {\n        ACCOUNT_LOGE(\"failed to get account info from data cache\");\n    } else {\n        dataCache_.erase(it);\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::GetAccountExtraInfo(\n    const std::string &name, std::string &extraInfo, const std::string &bundleName)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n    ACCOUNT_LOGI(\"extraInfo = %{public}s\", extraInfo.c_str());\n\n    AppAccountInfo appAccountInfo(name, bundleName);\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    result = appAccountInfo.GetExtraInfo(extraInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGI(\"failed to get extra info\");\n        return ERR_APPACCOUNT_SERVICE_GET_EXTRA_INFO;\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::SetAccountExtraInfo(const std::string &name, const std::string &extraInfo,\n    const std::string &bundleName, AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n    ACCOUNT_LOGI(\"extraInfo = %{public}s\", extraInfo.c_str());\n\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    result = appAccountInfo.SetExtraInfo(extraInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGI(\"failed to set extra info\");\n        return ERR_APPACCOUNT_SERVICE_SET_EXTRA_INFO;\n    }\n\n    result = SaveAccountInfoIntoDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to save account info into data storage\");\n        return result;\n    }\n\n    ACCOUNT_LOGI(\"end, result = %{public}d\", result);\n\n    return result;\n}\n\nErrCode AppAccountControlManager::EnableAppAccess(const std::string &name, const std::string &authorizedApp,\n    const std::string &bundleName, AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n    ACCOUNT_LOGI(\"authorizedApp = %{public}s\", authorizedApp.c_str());\n    ACCOUNT_LOGI(\"bundleName = %{public}s\", bundleName.c_str());\n\n    if (authorizedApp == bundleName) {\n        ACCOUNT_LOGE(\"authorizedApp is the same to owner\");\n        return ERR_APPACCOUNT_SERVICE_BUNDLE_NAME_IS_THE_SAME;\n    }\n\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    result = appAccountInfo.EnableAppAccess(authorizedApp);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGI(\"failed to enable app access\");\n        return ERR_APPACCOUNT_SERVICE_ENABLE_APP_ACCESS_ALREADY_EXISTS;\n    }\n\n    result = SaveAccountInfoIntoDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to save account info into data storage\");\n        return result;\n    }\n\n    \/\/ save authorized account into data storage\n    result = SaveAuthorizedAccount(authorizedApp, appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to save authorized account into data storage\");\n        return result;\n    }\n\n    ACCOUNT_LOGI(\"end, result = %{public}d\", result);\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::DisableAppAccess(const std::string &name, const std::string &authorizedApp,\n    const std::string &bundleName, AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n    ACCOUNT_LOGI(\"authorizedApp = %{public}s\", authorizedApp.c_str());\n\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    result = appAccountInfo.DisableAppAccess(authorizedApp);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGI(\"failed to disable app access\");\n        return ERR_APPACCOUNT_SERVICE_DISABLE_APP_ACCESS_NOT_EXISTED;\n    }\n\n    result = SaveAccountInfoIntoDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to save account info into data storage\");\n        return result;\n    }\n\n    \/\/ remove authorized account from data storage\n    result = RemoveAuthorizedAccount(authorizedApp, appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to save authorized account into data storage\");\n        return result;\n    }\n\n    ACCOUNT_LOGI(\"end, result = %{public}d\", result);\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::CheckAppAccountSyncEnable(\n    const std::string &name, bool &syncEnable, const std::string &bundleName)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n\n    AppAccountInfo appAccountInfo(name, bundleName);\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    result = appAccountInfo.GetSyncEnable(syncEnable);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get sync enable\");\n        return ERR_APPACCOUNT_SERVICE_GET_SYNC_ENABLE;\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::SetAppAccountSyncEnable(\n    const std::string &name, const bool &syncEnable, const std::string &bundleName, AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n    ACCOUNT_LOGI(\"syncEnable = %{public}d\", syncEnable);\n\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    result = appAccountInfo.SetSyncEnable(syncEnable);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to set sync enable\");\n        return ERR_APPACCOUNT_SERVICE_GET_SYNC_ENABLE;\n    }\n\n    result = SaveAccountInfoIntoDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to save account info into data storage\");\n        return result;\n    }\n\n    ACCOUNT_LOGI(\"end, result = %{public}d\", result);\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::GetAssociatedData(\n    const std::string &name, const std::string &key, std::string &value, const std::string &bundleName)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n    ACCOUNT_LOGI(\"key = %{public}s, value = %{public}s\", key.c_str(), value.c_str());\n\n    AppAccountInfo appAccountInfo(name, bundleName);\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    std::string associatedData;\n    result = appAccountInfo.GetAssociatedData(key, value);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get associated data\");\n        return ERR_APPACCOUNT_SERVICE_GET_ASSOCIATED_DATA;\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::SetAssociatedData(const std::string &name, const std::string &key,\n    const std::string &value, const std::string &bundleName, AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n    ACCOUNT_LOGI(\"key = %{public}s, value = %{public}s\", key.c_str(), value.c_str());\n\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    result = appAccountInfo.SetAssociatedData(key, value);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGI(\"failed to set associated data\");\n        return ERR_APPACCOUNT_SERVICE_SET_ASSOCIATED_DATA;\n    }\n\n    result = SaveAccountInfoIntoDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to save account info into data storage\");\n        return result;\n    }\n\n    ACCOUNT_LOGI(\"end, result = %{public}d\", result);\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::GetAccountCredential(\n    const std::string &name, const std::string &credentialType, std::string &credential, const std::string &bundleName)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n    ACCOUNT_LOGI(\"credentialType = %{public}s\", credentialType.c_str());\n\n    AppAccountInfo appAccountInfo(name, bundleName);\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    std::string accountCredential;\n    result = appAccountInfo.GetAccountCredential(credentialType, credential);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account credential\");\n        return ERR_APPACCOUNT_SERVICE_GET_ACCOUNT_CREDENTIAL;\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::SetAccountCredential(const std::string &name, const std::string &credentialType,\n    const std::string &credential, const std::string &bundleName, AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n    ACCOUNT_LOGI(\"credentialType = %{public}s, credential = %{public}s\", credentialType.c_str(), credential.c_str());\n\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    result = appAccountInfo.SetAccountCredential(credentialType, credential);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGI(\"failed to set account credential\");\n        return ERR_APPACCOUNT_SERVICE_SET_ACCOUNT_CREDENTIAL;\n    }\n\n    result = SaveAccountInfoIntoDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to save account info into data storage\");\n        return result;\n    }\n\n    ACCOUNT_LOGI(\"end, result = %{public}d\", result);\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::GetOAuthToken(\n    const std::string &name, std::string &token, const std::string &bundleName)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n    ACCOUNT_LOGI(\"token = %{public}s\", token.c_str());\n    ACCOUNT_LOGI(\"bundleName = %{public}s\", bundleName.c_str());\n\n    AppAccountInfo appAccountInfo(name, bundleName);\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    auto it = dataCache_.find(appAccountInfo.GetPrimeKey());\n    if (it == dataCache_.end()) {\n        ACCOUNT_LOGE(\"failed to get account info from data cache\");\n        dataCache_.emplace(appAccountInfo.GetPrimeKey(), \"\");\n        it = dataCache_.find(appAccountInfo.GetPrimeKey());\n    }\n\n    token = it->second;\n\n    ACCOUNT_LOGI(\"end, token = %{public}s\", token.c_str());\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::SetOAuthToken(\n    const std::string &name, const std::string &token, const std::string &bundleName)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n    ACCOUNT_LOGI(\"token = %{public}s\", token.c_str());\n    ACCOUNT_LOGI(\"bundleName = %{public}s\", bundleName.c_str());\n\n    AppAccountInfo appAccountInfo(name, bundleName);\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    auto it = dataCache_.find(appAccountInfo.GetPrimeKey());\n    if (it == dataCache_.end()) {\n        dataCache_.emplace(appAccountInfo.GetPrimeKey(), token);\n    } else {\n        dataCache_[appAccountInfo.GetPrimeKey()] = token;\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::ClearOAuthToken(const std::string &name, const std::string &bundleName)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"name = %{public}s\", name.c_str());\n    ACCOUNT_LOGI(\"bundleName = %{public}s\", bundleName.c_str());\n\n    AppAccountInfo appAccountInfo(name, bundleName);\n    ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    auto it = dataCache_.find(appAccountInfo.GetPrimeKey());\n    if (it != dataCache_.end()) {\n        ACCOUNT_LOGI(\"it->second = %{public}s\", it->second.c_str());\n        dataCache_.erase(it);\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::GetAllAccounts(\n    const std::string &owner, std::vector<AppAccountInfo> &appAccounts, const std::string &bundleName)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"owner = %{public}s\", owner.c_str());\n\n    appAccounts.clear();\n\n    auto dataStoragePtr = GetDataStorage();\n    if (dataStoragePtr == nullptr) {\n        ACCOUNT_LOGE(\"dataStoragePtr is nullptr\");\n        return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;\n    }\n\n    std::map<std::string, std::shared_ptr<IAccountInfo>> accounts;\n    ErrCode result = dataStoragePtr->LoadDataByLocalFuzzyQuery(owner, accounts);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get accounts by owner\");\n        return ERR_APPACCOUNT_SERVICE_GET_IACCOUNT_INFO_BY_OWNER;\n    }\n\n    for (auto account : accounts) {\n        appAccounts.emplace_back(*(std::static_pointer_cast<AppAccountInfo>(account.second)));\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::GetAllAccessibleAccounts(\n    std::vector<AppAccountInfo> &appAccounts, const std::string &bundleName)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    appAccounts.clear();\n\n    auto dataStoragePtr = GetDataStorage();\n    if (dataStoragePtr == nullptr) {\n        ACCOUNT_LOGE(\"dataStoragePtr is nullptr\");\n        return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;\n    }\n\n    std::vector<std::string> accessibleAccounts;\n    ErrCode result = dataStoragePtr->GetAccessibleAccountsFromDataStorage(bundleName, accessibleAccounts);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get accessiable account from data storage\");\n        return result;\n    }\n\n    for (auto account : accessibleAccounts) {\n        AppAccountInfo appAccountInfo;\n\n        result = dataStoragePtr->GetAccountInfoById(account, appAccountInfo);\n        if (result != ERR_OK) {\n            ACCOUNT_LOGE(\"failed to get account info by id\");\n            return ERR_APPACCOUNT_SERVICE_GET_ACCOUNT_INFO_BY_ID;\n        }\n\n        appAccounts.emplace_back(appAccountInfo);\n    }\n\n    std::vector<AppAccountInfo> currentAppAccounts;\n\n    result = GetAllAccounts(bundleName, currentAppAccounts, bundleName);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get all accounts\");\n        return result;\n    }\n\n    for (auto account : currentAppAccounts) {\n        appAccounts.emplace_back(account);\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::OnPackageRemoved(const int32_t &uid, const std::string &bundleName)\n{\n    ACCOUNT_LOGI(\"enter\");\n    ACCOUNT_LOGI(\"uid = %{public}d, bundleName = %{public}s\", uid, bundleName.c_str());\n\n    auto dataStoragePtr = GetDataStorage(false, uid);\n    if (dataStoragePtr == nullptr) {\n        ACCOUNT_LOGE(\"dataStoragePtr is nullptr\");\n        return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;\n    }\n\n    auto dataStorageSyncPtr = GetDataStorage(true, uid);\n    if (dataStorageSyncPtr == nullptr) {\n        ACCOUNT_LOGE(\"dataStorageSyncPtr is nullptr\");\n        return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;\n    }\n\n    std::map<std::string, std::shared_ptr<IAccountInfo>> accounts;\n    ErrCode result = dataStoragePtr->LoadDataByLocalFuzzyQuery(bundleName, accounts);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get accounts by bundleName\");\n        return ERR_APPACCOUNT_SERVICE_GET_IACCOUNT_INFO_BY_OWNER;\n    }\n\n    AppAccountInfo appAccountInfo;\n    for (auto account : accounts) {\n        appAccountInfo = *(std::static_pointer_cast<AppAccountInfo>(account.second));\n\n        std::set<std::string> apps;\n        appAccountInfo.GetAuthorizedApps(apps);\n        for (auto app : apps) {\n            result = RemoveAuthorizedAccountFromDataStorage(app, appAccountInfo);\n            ACCOUNT_LOGI(\"remove authorized account from data storage, result = %{public}d\", result);\n\n            \/\/ for sync data storage\n            if (NeedSyncDataStorage(appAccountInfo) == true) {\n                result = RemoveAuthorizedAccountFromDataStorage(app, appAccountInfo, true);\n                ACCOUNT_LOGI(\"remove authorized account from data storage, result = %{public}d\", result);\n            }\n        }\n\n        result = dataStoragePtr->DeleteAccountInfoFromDataStorage(appAccountInfo);\n        ACCOUNT_LOGI(\"delete account info from data storage, result = %{public}d\", result);\n\n        \/\/ for sync data storage\n        if (NeedSyncDataStorage(appAccountInfo) == true) {\n            result = dataStorageSyncPtr->DeleteAccountInfoFromDataStorage(appAccountInfo);\n            ACCOUNT_LOGI(\"delete account info from data storage, result = %{public}d\", result);\n        }\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::SaveAuthorizedAccount(const std::string &bundleName, AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ErrCode result = SaveAuthorizedAccountIntoDataStorage(bundleName, appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to save authorized account\");\n        return result;\n    }\n\n    \/\/ for sync data storage\n    if (NeedSyncDataStorage(appAccountInfo) == true) {\n        result = SaveAuthorizedAccountIntoDataStorage(bundleName, appAccountInfo, true);\n        if (result != ERR_OK) {\n            ACCOUNT_LOGE(\"failed to save authorized account\");\n            return result;\n        }\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::RemoveAuthorizedAccount(const std::string &bundleName, AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ErrCode result = RemoveAuthorizedAccountFromDataStorage(bundleName, appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to save authorized account\");\n        return result;\n    }\n\n    \/\/ for sync data storage\n    if (NeedSyncDataStorage(appAccountInfo) == true) {\n        result = RemoveAuthorizedAccountFromDataStorage(bundleName, appAccountInfo, true);\n        if (result != ERR_OK) {\n            ACCOUNT_LOGE(\"failed to save authorized account\");\n            return result;\n        }\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::SaveAuthorizedAccountIntoDataStorage(\n    const std::string &authorizedApp, AppAccountInfo &appAccountInfo, const bool &autoSync)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"authorizedApp = %{public}s\", authorizedApp.c_str());\n    ACCOUNT_LOGI(\"autoSync = %{public}d\", autoSync);\n\n    auto dataStoragePtr = GetDataStorage(autoSync);\n    if (dataStoragePtr == nullptr) {\n        ACCOUNT_LOGE(\"dataStoragePtr is nullptr\");\n        return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;\n    }\n\n    bool hasAuthorizedAccounts = true;\n    std::string authorizedAccounts;\n    ErrCode result = dataStoragePtr->GetConfigById(AppAccountDataStorage::AUTHORIZED_ACCOUNTS, authorizedAccounts);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get config by id from data storage\");\n        hasAuthorizedAccounts = false;\n    }\n\n    std::vector<std::string> accessibleAccounts;\n    auto jsonObject = dataStoragePtr->GetAccessibleAccountsFromAuthorizedAccounts(\n        authorizedAccounts, authorizedApp, accessibleAccounts);\n\n    auto accountId = appAccountInfo.GetPrimeKey();\n    ACCOUNT_LOGI(\"accountId = %{public}s\", accountId.c_str());\n\n    auto it = std::find(accessibleAccounts.begin(), accessibleAccounts.end(), accountId);\n    if (it == accessibleAccounts.end()) {\n        ACCOUNT_LOGI(\"failed to find accountId, accountId = %{public}s\", accountId.c_str());\n        accessibleAccounts.emplace_back(accountId);\n    }\n\n    auto accessibleAccountArray = Json::array();\n    ACCOUNT_LOGI(\"accessibleAccounts.size() = %{public}zu\", accessibleAccounts.size());\n    for (auto account : accessibleAccounts) {\n        ACCOUNT_LOGI(\"account = %{public}s\", account.c_str());\n        accessibleAccountArray.emplace_back(account);\n    }\n    ACCOUNT_LOGI(\"accessibleAccountArray.dump() = %{public}s\", accessibleAccountArray.dump().c_str());\n\n    jsonObject[authorizedApp] = accessibleAccountArray;\n    authorizedAccounts = jsonObject.dump();\n\n    ACCOUNT_LOGI(\"authorizedAccounts = %{public}s\", authorizedAccounts.c_str());\n\n    if (hasAuthorizedAccounts == false) {\n        result = dataStoragePtr->AddConfigInfo(AppAccountDataStorage::AUTHORIZED_ACCOUNTS, authorizedAccounts);\n        if (result != ERR_OK) {\n            ACCOUNT_LOGE(\"failed to add config info\");\n            return result;\n        }\n    } else {\n        result = dataStoragePtr->SavConfigInfo(AppAccountDataStorage::AUTHORIZED_ACCOUNTS, authorizedAccounts);\n        if (result != ERR_OK) {\n            ACCOUNT_LOGE(\"failed to save config info\");\n            return result;\n        }\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::RemoveAuthorizedAccountFromDataStorage(\n    const std::string &authorizedApp, AppAccountInfo &appAccountInfo, const bool &autoSync)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    ACCOUNT_LOGI(\"authorizedApp = %{public}s\", authorizedApp.c_str());\n    ACCOUNT_LOGI(\"autoSync = %{public}d\", autoSync);\n\n    auto dataStoragePtr = GetDataStorage(autoSync);\n    if (dataStoragePtr == nullptr) {\n        ACCOUNT_LOGE(\"dataStoragePtr is nullptr\");\n        return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;\n    }\n\n    std::string authorizedAccounts;\n    ErrCode result = dataStoragePtr->GetConfigById(AppAccountDataStorage::AUTHORIZED_ACCOUNTS, authorizedAccounts);\n    ACCOUNT_LOGI(\"authorizedAccounts = %{public}s\", authorizedAccounts.c_str());\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get config by id from data storage\");\n    }\n\n    std::vector<std::string> accessibleAccounts;\n    auto jsonObject = dataStoragePtr->GetAccessibleAccountsFromAuthorizedAccounts(\n        authorizedAccounts, authorizedApp, accessibleAccounts);\n\n    auto accountId = appAccountInfo.GetPrimeKey();\n    ACCOUNT_LOGI(\"accountId = %{public}s\", accountId.c_str());\n\n    auto it = std::find(accessibleAccounts.begin(), accessibleAccounts.end(), accountId);\n    if (it != accessibleAccounts.end()) {\n        accessibleAccounts.erase(it);\n    }\n\n    auto accessibleAccountArray = Json::array();\n    ACCOUNT_LOGI(\"accessibleAccounts.size() = %{public}zu\", accessibleAccounts.size());\n    for (auto account : accessibleAccounts) {\n        ACCOUNT_LOGI(\"account = %{public}s\", account.c_str());\n        accessibleAccountArray.emplace_back(account);\n    }\n    ACCOUNT_LOGI(\"accessibleAccountArray.dump() = %{public}s\", accessibleAccountArray.dump().c_str());\n\n    jsonObject[authorizedApp] = accessibleAccountArray;\n    authorizedAccounts = jsonObject.dump();\n\n    ACCOUNT_LOGI(\"authorizedAccounts = %{public}s\", authorizedAccounts.c_str());\n\n    result = dataStoragePtr->SavConfigInfo(AppAccountDataStorage::AUTHORIZED_ACCOUNTS, authorizedAccounts);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to save config info\");\n        return result;\n    }\n\n    ACCOUNT_LOGI(\"authorizedAccounts = %{public}s\", authorizedAccounts.c_str());\n\n    return ERR_OK;\n}\n\nstd::shared_ptr<AppAccountDataStorage> AppAccountControlManager::GetDataStorage(const bool &autoSync, const int32_t uid)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    std::string storeId;\n    ErrCode result = GetStoreId(storeId, uid);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get store id, result = %{public}d\", result);\n        return nullptr;\n    }\n\n    if (autoSync == true) {\n        storeId = storeId + AppAccountDataStorage::DATA_STORAGE_SUFFIX;\n    }\n\n    ACCOUNT_LOGI(\"storeId = %{public}s\", storeId.c_str());\n\n    return std::make_shared<AppAccountDataStorage>(storeId, autoSync);\n}\n\nErrCode AppAccountControlManager::GetStoreId(std::string &storeId, int32_t uid)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    if (uid == AppExecFwk::Constants::INVALID_UID) {\n        uid = IPCSkeleton::GetCallingUid();\n    }\n    ACCOUNT_LOGI(\"uid = %{public}d\", uid);\n\n    auto deviceAccountId = OhosAccountKits::GetInstance().GetDeviceAccountIdByUID(uid);\n    ACCOUNT_LOGI(\"deviceAccountId = %{public}d\", deviceAccountId);\n\n    storeId = std::to_string(deviceAccountId);\n\n    ACCOUNT_LOGI(\"end, storeId = %{public}s\", storeId.c_str());\n\n    return ERR_OK;\n}\n\nbool AppAccountControlManager::NeedSyncDataStorage(const AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    bool syncEnable = false;\n    ErrCode result = appAccountInfo.GetSyncEnable(syncEnable);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get sync enable\");\n        return false;\n    }\n\n    ACCOUNT_LOGI(\"syncEnable = %{public}d\", syncEnable);\n\n    if (syncEnable == false) {\n        return false;\n    }\n    return true;\n}\n\nErrCode AppAccountControlManager::GetAccountInfoFromDataStorage(AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    auto dataStoragePtr = GetDataStorage();\n    if (dataStoragePtr == nullptr) {\n        ACCOUNT_LOGE(\"dataStoragePtr is nullptr\");\n        return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;\n    }\n\n    ErrCode result = dataStoragePtr->GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::AddAccountInfoIntoDataStorage(AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    auto dataStoragePtr = GetDataStorage();\n    if (dataStoragePtr == nullptr) {\n        ACCOUNT_LOGE(\"dataStoragePtr is nullptr\");\n        return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;\n    }\n\n    std::string owner;\n    ErrCode result = appAccountInfo.GetOwner(owner);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get owner\");\n        return ERR_APPACCOUNT_SERVICE_GET_OWNER;\n    }\n\n    std::map<std::string, std::shared_ptr<IAccountInfo>> accounts;\n    result = dataStoragePtr->LoadDataByLocalFuzzyQuery(owner, accounts);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get accounts by owner\");\n        return ERR_APPACCOUNT_SERVICE_GET_IACCOUNT_INFO_BY_OWNER;\n    }\n\n    if (accounts.size() == ACCOUNT_MAX_SIZE) {\n        ACCOUNT_LOGE(\"account exceeds max size\");\n        return ERR_APPACCOUNT_SERVICE_ACCOUNT_MAX_SIZE;\n    }\n\n    result = dataStoragePtr->AddAccountInfoIntoDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to add account info into data storage\");\n        return result;\n    }\n\n    \/\/ for sync data storage\n    if (NeedSyncDataStorage(appAccountInfo) == true) {\n        dataStoragePtr = GetDataStorage(true);\n        if (dataStoragePtr == nullptr) {\n            ACCOUNT_LOGE(\"dataStoragePtr is nullptr\");\n            return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;\n        }\n\n        result = dataStoragePtr->AddAccountInfoIntoDataStorage(appAccountInfo);\n        if (result != ERR_OK) {\n            ACCOUNT_LOGE(\"failed to add account info into data storage\");\n            return result;\n        }\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::SaveAccountInfoIntoDataStorage(AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    auto dataStoragePtr = GetDataStorage();\n    if (dataStoragePtr == nullptr) {\n        ACCOUNT_LOGE(\"dataStoragePtr is nullptr\");\n        return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;\n    }\n\n    ErrCode result = dataStoragePtr->SaveAccountInfoIntoDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to save account info into data storage\");\n        return result;\n    }\n\n    \/\/ for sync data storage\n    if (NeedSyncDataStorage(appAccountInfo) == true) {\n        dataStoragePtr = GetDataStorage(true);\n        if (dataStoragePtr == nullptr) {\n            ACCOUNT_LOGE(\"dataStoragePtr is nullptr\");\n            return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;\n        }\n\n        std::string appAccountInfoFromDataStorage;\n        result = dataStoragePtr->GetConfigById(appAccountInfo.GetPrimeKey(), appAccountInfoFromDataStorage);\n        if (result != ERR_OK) {\n            ACCOUNT_LOGI(\"failed to get config by id from data storage\");\n\n            result = dataStoragePtr->AddAccountInfo(appAccountInfo);\n            if (result != ERR_OK) {\n                ACCOUNT_LOGI(\"failed to add account info, result = %{public}d\", result);\n                return ERR_APPACCOUNT_SERVICE_ADD_ACCOUNT_INFO;\n            }\n        } else {\n            result = dataStoragePtr->SaveAccountInfo(appAccountInfo);\n            if (result != ERR_OK) {\n                ACCOUNT_LOGI(\"failed to save account info, result = %{public}d\", result);\n                return ERR_APPACCOUNT_SERVICE_SAVE_ACCOUNT_INFO;\n            }\n        }\n    }\n\n    return ERR_OK;\n}\n\nErrCode AppAccountControlManager::DeleteAccountInfoFromDataStorage(AppAccountInfo &appAccountInfo)\n{\n    ACCOUNT_LOGI(\"enter\");\n\n    auto dataStoragePtr = GetDataStorage();\n    if (dataStoragePtr == nullptr) {\n        ACCOUNT_LOGE(\"dataStoragePtr is nullptr\");\n        return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;\n    }\n\n    ErrCode result = dataStoragePtr->GetAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to get account info from data storage\");\n        return result;\n    }\n\n    result = dataStoragePtr->DeleteAccountInfoFromDataStorage(appAccountInfo);\n    if (result != ERR_OK) {\n        ACCOUNT_LOGE(\"failed to delete account info from data storage\");\n        return result;\n    }\n\n    \/\/ for sync data storage\n    if (NeedSyncDataStorage(appAccountInfo) == true) {\n        \/\/ for sync data storage\n        dataStoragePtr = GetDataStorage(true);\n        if (dataStoragePtr == nullptr) {\n            ACCOUNT_LOGE(\"dataStoragePtr is nullptr\");\n            return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;\n        }\n\n        result = dataStoragePtr->DeleteAccountInfoFromDataStorage(appAccountInfo);\n        if (result != ERR_OK) {\n            ACCOUNT_LOGI(\"failed to delete account info from data storage\");\n        }\n    }\n\n    return ERR_OK;\n}\n}  \/\/ namespace AccountSA\n}  \/\/ namespace OHOS\n","avg_line_length":33.7302231237,"max_line_length":120,"alphanum_fraction":0.6893379037,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":19152,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/\/ Copyright (C) 2018-2020 Intel Corporation\n\/\/ SPDX-License-Identifier: Apache-2.0\n\/\/\n\n#include <gtest\/gtest.h>\n#include <ie_core.hpp>\n\n#include \"tests_common.hpp\"\n#include \"single_layer_common.hpp\"\n#include \"..\/common_single_layer_tests\/conv_ref.hpp\"\n#include <single_layer_common.hpp>\n#include <string>\n#include \"common_test_utils\/common_layers_params.hpp\"\n\nusing namespace ::testing;\nusing namespace InferenceEngine;\nusing std::vector;\n\nstruct conv_base_params {\n    vector<size_t> in_dims;\n    vector<size_t> kernel;\n    vector<size_t> strides;\n    vector<size_t> pads_begin;\n    vector<size_t> pads_end;\n    vector<size_t> dilations;\n\n    size_t out_c;\n    size_t grp_c;\n\n    vector<size_t> out_dims;\n};\n\nstruct conv_test_params : conv_base_params {\n    std::string device_name;\n\n    conv_test_params(std::string name, conv_base_params params) :\n            conv_base_params(params), device_name(name) {}\n};\n\nclass smoke_ConvolutionOnlyTest : public TestsCommon,\n                            public WithParamInterface<conv_test_params> {\n\n    std::string model_t_4D = R\"V0G0N(\n<net name=\"Convolution_Only\" version=\"3\" precision=\"FP32\" batch=\"1\">\n    <layers>\n        <layer name=\"in1\" type=\"Input\" precision=\"FP32\" id=\"0\">\n            <output>\n                <port id=\"0\">\n                    <dim>_IN_<\/dim>\n                    <dim>_IC_<\/dim>\n                    <dim>_IH_<\/dim>\n                    <dim>_IW_<\/dim>\n                <\/port>\n            <\/output>\n        <\/layer>\n        <layer name=\"conv1\" id=\"1\" type=\"Convolution\" precision=\"FP32\">\n            <convolution strides=\"_KS_\"\n                         pads_begin=\"_PB_\" pads_end=\"_PE_\"\n                         kernel=\"_K_\"\n                         dilations=\"_DL_\"\n                         output=\"_OC_\" group=\"_GC_\"\/>\n\n            <weights offset=\"0\" size=\"_S1_\" \/>\n            <biases offset=\"_S1_\" size=\"_S2_\" \/>\n\n            <input>\n                <port id=\"1\">\n                    <dim>_IN_<\/dim>\n                    <dim>_IC_<\/dim>\n                    <dim>_IH_<\/dim>\n                    <dim>_IW_<\/dim>\n                <\/port>\n            <\/input>\n            <output>\n                <port id=\"2\">\n                    <dim>_IN_<\/dim>\n                    <dim>_OC_<\/dim>\n                    <dim>_OH_<\/dim>\n                    <dim>_OW_<\/dim>\n                <\/port>\n            <\/output>\n        <\/layer>\n    <\/layers>\n    <edges>\n        <edge from-layer=\"0\" from-port=\"0\" to-layer=\"1\" to-port=\"1\"\/>\n    <\/edges>\n<\/net>\n)V0G0N\";\n\n    std::string model_t_5D = R\"V0G0N(\n<net name=\"Convolution_Only\" version=\"3\" precision=\"FP32\" batch=\"1\">\n    <layers>\n        <layer name=\"in1\" type=\"Input\" precision=\"FP32\" id=\"0\">\n            <output>\n                <port id=\"0\">\n                    <dim>_IN_<\/dim>\n                    <dim>_IC_<\/dim>\n                    <dim>_ID_<\/dim>\n                    <dim>_IH_<\/dim>\n                    <dim>_IW_<\/dim>\n                <\/port>\n            <\/output>\n        <\/layer>\n        <layer name=\"conv1\" id=\"1\" type=\"Convolution\" precision=\"FP32\">\n            <convolution strides=\"_KS_\"\n                         pads_begin=\"_PB_\"  pads_end=\"_PE_\"\n                         kernel=\"_K_\"\n                         dilations=\"_DL_\"\n                         output=\"_OC_\"  group=\"_GC_\"\/>\n\n            <weights offset=\"0\" size=\"_S1_\" \/>\n            <biases offset=\"_S1_\" size=\"_S2_\" \/>\n\n            <input>\n                <port id=\"1\">\n                    <dim>_IN_<\/dim>\n                    <dim>_IC_<\/dim>\n                    <dim>_ID_<\/dim>\n                    <dim>_IH_<\/dim>\n                    <dim>_IW_<\/dim>\n                <\/port>\n            <\/input>\n            <output>\n                <port id=\"2\">\n                    <dim>_IN_<\/dim>\n                    <dim>_OC_<\/dim>\n                    <dim>_OD_<\/dim>\n                    <dim>_OH_<\/dim>\n                    <dim>_OW_<\/dim>\n                <\/port>\n            <\/output>\n        <\/layer>\n    <\/layers>\n    <edges>\n        <edge from-layer=\"0\" from-port=\"0\" to-layer=\"1\" to-port=\"1\"\/>\n    <\/edges>\n<\/net>\n)V0G0N\";\n\nprotected:\n\n    size_t calculateOutDim(size_t in_dim, size_t kernel, size_t stride, size_t pad_begin) {\n        return (in_dim + 2lu * pad_begin - kernel) \/ stride + 1lu;\n    }\n\n    void createBlobs(const conv_test_params &p, TBlob<float>::Ptr &src, TBlob<float>::Ptr &dst, TBlob<float>::Ptr &dst_ref) {\n        auto in_size = p.in_dims.size();\n        auto out_size = p.out_dims.size();\n        SizeVector dims_dst = {\n                p.out_dims[out_size - 1] == 0 ?\n                    calculateOutDim(p.in_dims[in_size - 1], p.kernel[X_AXIS], p.strides[X_AXIS], p.pads_begin[X_AXIS]) : p.out_dims[out_size - 1],\n                p.out_dims[out_size - 2] == 0 ?\n                    calculateOutDim(p.in_dims[in_size - 2], p.kernel[Y_AXIS], p.strides[Y_AXIS], p.pads_begin[Y_AXIS]) : p.out_dims[out_size - 2],\n                p.out_c,\n                1lu};\n        SizeVector dims_src;\n        for (int i = in_size; i > 0; i--) {\n            dims_src.push_back(p.in_dims[i - 1]);\n        }\n\n        Layout layout = NCHW;\n        if (in_size == 5) {\n            layout = NCDHW;\n            dims_dst.insert(dims_dst.begin() + 2, p.out_dims.size() > 2 ?\n                (p.out_dims[out_size - 3] == 0 ?\n                    calculateOutDim(p.in_dims[in_size - 3], p.kernel[Z_AXIS], p.strides[Z_AXIS], p.pads_begin[Z_AXIS]) : p.out_dims[out_size - 3]) : 1lu);\n        }\n\n        src = make_shared_blob<float>(TensorDesc(Precision::FP32, SizeVector(dims_src.rbegin(), dims_src.rend()), layout));\n        src->allocate();\n\n        dst = make_shared_blob<float>(TensorDesc(Precision::FP32, SizeVector(dims_dst.rbegin(), dims_dst.rend()), layout));\n        dst->allocate();\n\n        dst_ref = make_shared_blob<float>(TensorDesc(Precision::FP32, SizeVector(dims_dst.rbegin(), dims_dst.rend()), layout));\n        dst_ref->allocate();\n    }\n\n    TBlob<uint8_t>::Ptr fillWeights(const conv_test_params &p) {\n        auto KZ = p.kernel.size() > Z_AXIS ? p.kernel[Z_AXIS] : 1lu;\n        TBlob<uint8_t> *weights_ptr = new TBlob<uint8_t>(TensorDesc(Precision::U8,\n                    {(p.kernel[X_AXIS] * p.kernel[Y_AXIS] * KZ * p.out_c * p.in_dims[1] \/ p.grp_c + p.out_c)\n                     * sizeof(float)}, C));\n        weights_ptr->allocate();\n        fill_data((float *) weights_ptr->buffer(), weights_ptr->size() \/ sizeof(float));\n        return TBlob<uint8_t>::Ptr(weights_ptr);\n    }\n\n    void calculateRef(const TBlob<uint8_t>::Ptr &weights, const conv_test_params &p, const TBlob<float>::Ptr &src,\n                      TBlob<float>::Ptr &dst_ref) {\n        const float *weights_data = (const float *) weights->buffer();\n        size_t bias_size = p.out_c;\n        size_t weights_size = weights->size() \/ sizeof(float) - bias_size;\n        const float *bias_data = weights_data + weights_size;\n        CommonTestUtils::conv_common_params params;\n        for (int i = 0; i < p.kernel.size(); i++)\n            params.kernel.insert(i, p.kernel[i]);\n        for (int i = 0; i < p.strides.size(); i++)\n            params.stride.insert(i, p.strides[i]);\n        for (int i = 0; i < p.pads_begin.size(); i++)\n            params.pads_begin.insert(i, p.pads_begin[i]);\n        for (int i = 0; i < p.dilations.size(); i++)\n            params.dilation.insert(i, p.dilations[i]);\n        params.group = p.grp_c;\n        params.out_c = p.out_c;\n        ref_conv_common<>({ src }, *dst_ref.get(), weights_data, weights_size, bias_data, bias_size, params);\n    }\n\n    CNNNetwork getNetwork(const TBlob<uint8_t>::Ptr &weights, const conv_test_params &p) {\n        Core ie;\n        return ie.ReadNetwork(getModel(p), weights);\n    }\n\n    virtual void\n    infer(CNNNetwork &network, const conv_test_params &p, TBlob<float>::Ptr &src, TBlob<float>::Ptr &dst) {\n        Blob::Ptr srcPtr = std::shared_ptr<Blob>(src);\n        Blob::Ptr dstPtr = std::shared_ptr<Blob>(dst);\n\n        Core ie;\n        ExecutableNetwork exeNetwork = ie.LoadNetwork(network, \"CPU\");\n        InferRequest inferRequest = exeNetwork.CreateInferRequest();\n        OutputsDataMap outInfo;\n        outInfo = network.getOutputsInfo();\n        ASSERT_EQ(outInfo.size(), 1);\n        ASSERT_NE(outInfo.begin()->second, nullptr);\n        inferRequest.SetBlob(network.getInputsInfo().begin()->first, srcPtr);\n        inferRequest.SetBlob(outInfo.begin()->first, dstPtr);\n        inferRequest.Infer();\n    }\n\n    void SetUp() override {\n        try {\n            conv_test_params p = ::testing::WithParamInterface<conv_test_params>::GetParam();\n            TBlob<float>::Ptr src, dst, dst_ref;\n            createBlobs(p, src, dst, dst_ref);\n            fill_data(src->data(), src->size());\n            auto weights = fillWeights(p);\n            calculateRef(weights, p, src, dst_ref);\n            CNNNetwork network = getNetwork(weights, p);\n            infer(network, p, src, dst);\n            compare(*dst, *dst_ref);\n        } catch (const InferenceEngine::details::InferenceEngineException &e) {\n            FAIL() << e.what();\n        }\n    }\n\n    virtual std::string getModel(conv_test_params p) {\n        std::string model;\n        auto in_dims_size = p.in_dims.size();\n        if (in_dims_size == 4) {\n            model = model_t_4D;\n        } else if (in_dims_size == 5) {\n            model = model_t_5D;\n        }\n\n        REPLACE_WITH_NUM(model, \"_IW_\", p.in_dims[in_dims_size - 1]);\n        REPLACE_WITH_NUM(model, \"_IH_\", p.in_dims[in_dims_size - 2]);\n        REPLACE_WITH_NUM(model, \"_ID_\", p.in_dims[in_dims_size - 3]);\n        REPLACE_WITH_NUM(model, \"_IC_\", p.in_dims[1]);\n        REPLACE_WITH_NUM(model, \"_IN_\", p.in_dims[0]);\n\n        REPLACE_WITH_NUM_VECTOR_REVERSE(model, \"_K_\", p.kernel);\n        REPLACE_WITH_NUM_VECTOR_REVERSE(model, \"_KS_\", p.strides);\n        REPLACE_WITH_NUM_VECTOR_REVERSE(model, \"_PB_\", p.pads_begin);\n        REPLACE_WITH_NUM_VECTOR_REVERSE(model, \"_PE_\", p.pads_end);\n        REPLACE_WITH_NUM_VECTOR_REVERSE(model, \"_DL_\", p.dilations);\n\n        auto out_dims_size = p.out_dims.size();\n        REPLACE_WITH_NUM(model, \"_GC_\", p.grp_c);\n        REPLACE_WITH_NUM(model, \"_OC_\", p.out_c);\n        REPLACE_WITH_NUM(model, \"_OD_\", out_dims_size > 2 ?\n                (p.out_dims[out_dims_size - 3] == 0 ?\n                    calculateOutDim(p.in_dims[in_dims_size - 3], p.kernel[Z_AXIS], p.strides[Z_AXIS], p.pads_begin[Z_AXIS]) : p.out_dims[out_dims_size - 3]) :\n                        1lu);\n        REPLACE_WITH_NUM(model, \"_OH_\", p.out_dims[out_dims_size - 2] == 0 ?\n                calculateOutDim(p.in_dims[in_dims_size - 2], p.kernel[Y_AXIS], p.strides[Y_AXIS], p.pads_begin[Y_AXIS]) : p.out_dims[out_dims_size - 2]);\n        REPLACE_WITH_NUM(model, \"_OW_\", p.out_dims[out_dims_size - 1] == 0 ?\n                calculateOutDim(p.in_dims[in_dims_size - 1], p.kernel[X_AXIS], p.strides[X_AXIS], p.pads_begin[X_AXIS]) : p.out_dims[out_dims_size - 1]);\n\n        size_t KD = p.kernel.size() > Z_AXIS ? p.kernel[Z_AXIS] : 1lu;\n        size_t w_data_size = (p.kernel[X_AXIS] * p.kernel[Y_AXIS] * KD * p.out_c * p.in_dims[1] \/ p.grp_c) * sizeof(float);\n        size_t b_data_size = p.out_c * sizeof(float);\n        REPLACE_WITH_NUM(model, \"_S1_\", w_data_size);\n        REPLACE_WITH_NUM(model, \"_S2_\", b_data_size);\n        return model;\n    }\n};\n\nclass smoke_ConvolutionReshapeTest : public smoke_ConvolutionOnlyTest {\nprotected:\n    void SetUp() override {\n        try {\n            conv_test_params p = ::testing::WithParamInterface<conv_test_params>::GetParam();\n            TBlob<float>::Ptr src, dst, dst_ref;\n            auto weights = fillWeights(p);\n            CNNNetwork network = getNetwork(weights, p);\n            infer(network, p, src, dst);\n            updatePaddings(network, p);\n            dst_ref = std::make_shared<TBlob<float>>(dst->getTensorDesc());\n            dst_ref->allocate();\n            calculateRef(weights, p, src, dst_ref);\n            compare(*dst, *dst_ref);\n        } catch (const InferenceEngine::details::InferenceEngineException &e) {\n            FAIL() << e.what();\n        }\n    }\n\n    void updatePaddings(const CNNNetwork &network, conv_test_params& p) {\n        details::CNNNetworkIterator i(network), end;\n        auto found = std::find_if(i, end, [](const CNNLayer::Ptr& layer) {\n            return layer->type == \"Convolution\";\n        });\n        ASSERT_NE(found, end);\n        auto convLayer = std::dynamic_pointer_cast<ConvolutionLayer>(*found);\n        auto allPad = getPaddings(*convLayer.get());\n        p.pads_begin[X_AXIS] = allPad.begin[X_AXIS];\n        p.pads_begin[Y_AXIS] = allPad.begin[Y_AXIS];\n        if (p.pads_begin.size() > Z_AXIS)\n            p.pads_begin[Z_AXIS] = allPad.begin[Z_AXIS];\n    }\n    void\n    infer(CNNNetwork &network, const conv_test_params &p, TBlob<float>::Ptr &src, TBlob<float>::Ptr &dst) override {\n        Core ie;\n        auto firstInputInfo = *network.getInputsInfo().begin();\n        std::string inputName = firstInputInfo.first;\n        auto firstOutputInfo = *network.getOutputsInfo().begin();\n        std::string outputName = firstOutputInfo.first;\n        auto inputShapes = network.getInputShapes();\n        IE_ASSERT(inputShapes.size() == 1);\n        inputShapes.begin()->second = p.in_dims;\n        ASSERT_NO_THROW(network.reshape(inputShapes));\n\n        ExecutableNetwork exeNetwork = ie.LoadNetwork(network, p.device_name);\n        InferRequest request = exeNetwork.CreateInferRequest();\n        Blob::Ptr src_b = request.GetBlob(inputName);\n\n        src = std::dynamic_pointer_cast<TBlob<float>>(src_b);\n        fill_data(src->data(), src->size());\n        request.Infer();\n        Blob::Ptr dst_b = request.GetBlob(outputName);\n        dst = std::dynamic_pointer_cast<TBlob<float>>(dst_b);\n    }\n\n    std::string getModel(conv_test_params p) override {\n        std::string model = smoke_ConvolutionOnlyTest::getModel(p);\n        REPLACE_WITH_STR(model, \"convolution\", \"convolution auto_pad=\\\"same_upper\\\"\");\n        std::string pads_pattern = \"pads_begin=\\\"\";\n        for (int i = p.pads_begin.size(); i > 0; i--) {\n            pads_pattern += std::to_string(p.pads_begin[i - 1]) + \",\";\n        }\n        std::string pads = \"pads_begin=\\\"0,0\\\"\";\n        if (p.pads_begin.size() == 3) {\n            pads = \"pads_begin=\\\"0,0,0\\\"\";\n        }\n        REPLACE_WITH_NUM_VECTOR(model, pads_pattern, pads);\n        return model;\n    }\n};\n\n#define case_1  conv_base_params({{1lu, 9lu, 16lu, 32lu},  {1lu, 1lu}, {1lu, 1lu}, {0lu, 0lu}, {0lu, 0lu}, {1lu, 1lu}, 17lu, 1lu, {0lu, 0lu}})\n#define case_2  conv_base_params({{1lu, 9lu, 32lu, 16lu},  {2lu, 4lu}, {1lu, 1lu}, {0lu, 0lu}, {0lu, 0lu}, {1lu, 1lu}, 17lu, 1lu, {0lu, 0lu}})\n#define case_3  conv_base_params({{1lu, 9lu, 32lu, 16lu},  {2lu, 4lu}, {2lu, 1lu}, {0lu, 0lu}, {0lu, 0lu}, {1lu, 1lu}, 17lu, 1lu, {0lu, 0lu}})\n#define case_4  conv_base_params({{1lu, 3lu, 40lu, 40lu},  {3lu, 3lu}, {1lu, 2lu}, {0lu, 0lu}, {0lu, 0lu}, {1lu, 1lu}, 20lu, 1lu, {0lu, 0lu}})\n#define case_5  conv_base_params({{1lu, 9lu, 16lu, 32lu},  {7lu, 7lu}, {2lu, 2lu}, {3lu, 3lu}, {0lu, 0lu}, {1lu, 1lu}, 17lu, 1lu, {0lu, 0lu}})\n#define case_6  conv_base_params({{1lu, 3lu, 224lu, 224lu}, {7lu, 7lu}, {2lu, 2lu}, {2lu, 2lu}, {0lu, 0lu}, {1lu, 1lu}, 64lu, 1lu, {112lu, 112lu}})\n#define case_7  conv_base_params({{1lu, 16lu, 40lu, 40lu}, {3lu, 3lu}, {1lu, 1lu}, {0lu, 0lu}, {0lu, 0lu}, {1lu, 1lu}, 16lu, 16lu, {0lu, 0lu}})\n#define case_8  conv_base_params({{1lu, 32lu, 16lu, 32lu}, {7lu, 7lu}, {2lu, 2lu}, {3lu, 3lu}, {0lu, 0lu}, {1lu, 1lu}, 32lu, 32lu, {0lu, 0lu}})\n#define case_9  conv_base_params({{1lu, 16lu, 40lu, 40lu}, {3lu, 3lu}, {1lu, 1lu}, {0lu, 0lu}, {0lu, 0lu}, {9lu, 9lu}, 16lu, 16lu, {0lu, 0lu}})\n#define case_10 conv_base_params({{1lu, 32lu, 16lu, 32lu}, {7lu, 7lu}, {2lu, 2lu}, {3lu, 3lu}, {0lu, 0lu}, {9lu, 9lu}, 32lu, 32lu, {0lu, 0lu}})\n#define case_11 conv_base_params({{1lu, 4lu, 16lu, 32lu},  {7lu, 7lu}, {2lu, 2lu}, {3lu, 3lu}, {0lu, 0lu}, {9lu, 9lu}, 4lu, 4lu, {0lu, 0lu}})\n#define case_12 conv_base_params({{1lu, 3lu, 224lu, 224lu}, {10lu, 10lu}, {1lu, 1lu}, {4lu, 4lu}, {0lu, 0lu}, {1lu, 1lu}, 4lu, 1lu, {224lu, 224lu}})\n#define case_13 conv_base_params({{1lu, 32lu, 1lu, 15000lu}, {11lu, 1lu}, {1lu, 1lu}, {5lu, 0lu}, {0lu, 0lu}, {4lu, 1lu}, 32lu, 1lu, {15000lu, 1lu}})\n\n\n#define case_14  conv_base_params({{1lu, 3lu, 16lu, 32lu, 32lu},  {1lu, 1lu, 1lu}, {1lu, 1lu, 1lu}, {0lu, 0lu, 0lu}, {0lu, 0lu, 0lu}, {1lu, 1lu, 1lu}, 17lu, 1lu, {0lu, 0lu, 0lu}})\n#define case_15  conv_base_params({{1lu, 3lu, 16lu, 32lu, 32lu},  {3lu, 3lu, 3lu}, {2lu, 2lu, 1lu}, {0lu, 0lu, 0lu}, {0lu, 0lu, 0lu}, {1lu, 1lu, 1lu}, 64lu, 1lu, {0lu, 0lu, 0lu}})\n\n\/\/ NOTE: always auto_pad = same_upper. IR with zero_pads, pad from params is used for ref_conv after reshape\n#define case_si_1 conv_base_params({{1lu, 144lu, 75lu, 75lu}, {3lu, 3lu}, {2lu, 2lu}, {1lu, 1lu}, {0lu, 0lu}, {1lu, 1lu}, 144lu, 144lu, {1lu, 1lu}})\n\nTEST_P(smoke_ConvolutionReshapeTest, TestsReshapeConvolution) {\n}\n\nstd::string getTestCaseName(testing::TestParamInfo<conv_test_params> obj) {\n    auto in_dims_size = obj.param.in_dims.size();\n    return obj.param.device_name +\n        \"_w\" + std::to_string(obj.param.in_dims[in_dims_size - 1]) +\n        \"_h\" + std::to_string(obj.param.in_dims[in_dims_size - 2]) +\n        (obj.param.in_dims.size() > 4 ? \"_d\" + std::to_string(obj.param.in_dims[in_dims_size - 3]) : \"\") +\n        \"_c\" + std::to_string(obj.param.in_dims[1]) +\n        \"_kw\" + std::to_string(obj.param.kernel[X_AXIS]) +\n        \"_kh\" + std::to_string(obj.param.kernel[Y_AXIS]) +\n        (obj.param.kernel.size() > Z_AXIS ? \"_kd\" + std::to_string(obj.param.kernel[Z_AXIS]) : \"\") +\n        \"_sw\" + std::to_string(obj.param.strides[X_AXIS]) +\n        \"_sh\" + std::to_string(obj.param.strides[Y_AXIS]) +\n        (obj.param.strides.size() > Z_AXIS ? \"_sd\" + std::to_string(obj.param.strides[Z_AXIS]) : \"\") +\n        \"_dilw\" + std::to_string(obj.param.dilations[X_AXIS]) +\n        \"_dilh\" + std::to_string(obj.param.dilations[Y_AXIS]) +\n        (obj.param.dilations.size() > Z_AXIS ? \"_dild\" + std::to_string(obj.param.dilations[Z_AXIS]) : \"\") +\n        \"_grpc\" + std::to_string(obj.param.grp_c);\n}\n\nconv_test_params conv_only_test_cases[] = {\n        conv_test_params(\"CPU\", case_1),\n        conv_test_params(\"CPU\", case_2),\n        conv_test_params(\"CPU\", case_3),\n        conv_test_params(\"CPU\", case_4),\n        conv_test_params(\"CPU\", case_5),\n        conv_test_params(\"CPU\", case_6),\n        conv_test_params(\"CPU\", case_7),\n        conv_test_params(\"CPU\", case_8),\n        conv_test_params(\"CPU\", case_9),\n        conv_test_params(\"CPU\", case_10),\n        conv_test_params(\"CPU\", case_11),\n        conv_test_params(\"CPU\", case_12),\n        conv_test_params(\"CPU\", case_13),\n        conv_test_params(\"CPU\", case_14),\n        conv_test_params(\"CPU\", case_15)\n};\n\nINSTANTIATE_TEST_CASE_P(\n        TestConvolution, smoke_ConvolutionOnlyTest, ::testing::ValuesIn(conv_only_test_cases), getTestCaseName);\n\nINSTANTIATE_TEST_CASE_P(\n        TestSameUpperConvolution, smoke_ConvolutionReshapeTest,\n        ::testing::Values(conv_test_params(\"CPU\", case_si_1)),\n        getTestCaseName);\n\n","avg_line_length":44.6433566434,"max_line_length":179,"alphanum_fraction":0.581871345,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1696,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/*\n * Copyright (C) 2010-2013 Geometer Plus <contact@geometerplus.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n * 02110-1301, USA.\n *\/\n\n#include \"ZLFileUtil.h\"\n\nstd::string ZLFileUtil::normalizeUnixPath(const std::string &path) {\n\tstd::string nPath = path;\n\twhile (nPath.length() >= 2 && nPath.substr(2) == \".\/\") {\n\t\tnPath.erase(0, 2);\n\t}\n\tint index;\n\twhile ((index = nPath.find(\"\/..\/\")) != -1) {\n\t\tconst int prevIndex = (int)nPath.rfind('\/', index - 1);\n\t\tif (prevIndex == -1) {\n\t\t\tnPath.erase(0, index + 4);\n\t\t} else {\n\t\t\tnPath.erase(prevIndex, index + 3 - prevIndex);\n\t\t}\n\t}\n\tint len = nPath.length();\n\tif ((len >= 3) && (nPath.substr(len - 3) == \"\/..\")) {\n\t\tint prevIndex = std::max((int)nPath.rfind('\/', len - 4), 0);\n\t\tnPath.erase(prevIndex);\n\t}\n\twhile ((index = nPath.find(\"\/.\/\")) != -1) {\n\t\tnPath.erase(index, 2);\n\t}\n\twhile (nPath.length() >= 2 &&\n\t\t\t\t nPath.substr(nPath.length() - 2) == \"\/.\") {\n\t\tnPath.erase(nPath.length() - 2);\n\t}\n\twhile ((index = nPath.find(\"\/\/\")) != -1) {\n\t\tnPath.erase(index, 1);\n\t}\n\treturn nPath;\n}\n","avg_line_length":32.0,"max_line_length":71,"alphanum_fraction":0.6456367925,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10347,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include \"non_local_bayes.h\"\n#include \"hoNDArray.h\"\n#include \"vector_td_utilities.h\"\n#include <GadgetronTimer.h>\n#include \"hoArmadillo.h\"\n#include <numeric>\n\nnamespace Gadgetron {\n    namespace Denoise {\n\n        namespace {\n\n            template<class T>\n            arma::Col<T> get_patch(const hoNDArray<T> &image, int x, int y, int patch_size,\n                                   const vector_td<int, 2> &image_dims) {\n\n                const int N = patch_size * patch_size;\n                arma::Col<T> window = arma::Col<T>(N);\n                for (int ky = 0; ky < patch_size; ky++) {\n                    for (int kx = 0; kx < patch_size; kx++) {\n                        window[kx + ky * patch_size] = image(\n                                ((kx - patch_size \/ 2) + x + image_dims[0]) % image_dims[0],\n                                ((ky - patch_size \/ 2) + y + image_dims[1]) % image_dims[1]);\n\n                    }\n                }\n                return window;\n            };\n\n\n\n            template<class T>\n            struct ImagePatch {\n                arma::Col<T> patch;\n                int center_x, center_y;\n            };\n\n\n            template<class T>\n            std::vector<ImagePatch<T>>\n            create_patches(const hoNDArray<T> &image, int kx, int ky, int patch_size, int search_window,\n                           const vector_td<int, 2> &image_dims) {\n\n                std::vector<ImagePatch<T>> result;\n                result.reserve(search_window);\n\n                for (int dy = std::max(ky - search_window \/ 2, 0);\n                     dy < std::min(search_window \/ 2 + ky, image_dims[1]); dy++) {\n                    for (int dx = std::max(kx - search_window \/ 2, 0);\n                         dx < std::min(search_window \/ 2 + kx, image_dims[0]); dx++) {\n\n                        result.push_back(ImagePatch<T>{get_patch(image, dx, dy, patch_size, image_dims), dx, dy});\n                    }\n                }\n\n                return result;\n\n            };\n\n\n            template<class T>\n            void add_patch(ImagePatch<T> &patch, hoNDArray<T> &image, hoNDArray<int> &count, int patch_size,\n                           const vector_td<int, 2> &image_dims) {\n\n\n                for (int ky = 0; ky < patch_size; ky++) {\n                    auto output_ky = (patch.center_y + ky - patch_size \/ 2 + image_dims[1]) % image_dims[1];\n                    for (int kx = 0; kx < patch_size; kx++) {\n                        auto output_kx = (patch.center_x + kx - patch_size \/ 2 + image_dims[0]) % image_dims[0];\n                        image(output_kx, output_ky) += patch.patch[kx + ky * patch_size];\n                        count(output_kx, output_ky)++;\n                    }\n                }\n\n            };\n\n\n            template<class T>\n            float distance(const arma::Col<T> &patch1, const arma::Col<T> &patch2) {\n                arma::Col<T> diff = patch1 - patch2;\n\n                float result = 0;\n                for (auto d : diff) result += std::norm(d);\n\n                result \/= patch1.size() * patch1.size();\n                return result;\n            };\n\n            template<class T>\n            arma::Col<T> get_mean_patch(const std::vector<ImagePatch<T>> &patches) {\n\n                auto mean_patch = arma::Col<T>(patches.front().patch.size(), arma::fill::zeros);\n\n                for (auto &patch : patches) {\n                    mean_patch += patch.patch;\n                }\n\n                mean_patch \/= patches.size();\n\n                return mean_patch;\n            }\n\n            template<class T>\n            arma::Mat<T>\n            get_covariance_matrix(const std::vector<ImagePatch<T>> &patches, const arma::Col<T> &mean_patch) {\n\n                auto covariance_matrix = arma::Mat<T>(mean_patch.size(), mean_patch.size(), arma::fill::zeros);\n\n                for (auto &patch : patches) {\n                    covariance_matrix += (patch.patch - mean_patch) * (patch.patch - mean_patch).t();\n                }\n                covariance_matrix \/= patches.size() - 1;\n\n                return covariance_matrix;\n            }\n\n\n            template<class T>\n            void\n            filter_patches(std::vector<ImagePatch<T>> &patches, int max_n_patches, const arma::Col<T> &reference_patch) {\n\n                auto distances = std::vector<float>(patches.size());\n                transform(patches.begin(), patches.end(), distances.begin(),\n                          [&](auto patch) { return distance(patch.patch, reference_patch); });\n\n                std::vector<size_t> patch_indices(patches.size());\n                std::iota(patch_indices.begin(), patch_indices.end(), 0);\n\n                sort(patch_indices.begin(), patch_indices.end(),\n                     [&](auto v1, auto v2) { return distances[v1] < distances[v2]; });\n\n                int n_patches = std::min<int>(patches.size(),max_n_patches);\n                std::vector<ImagePatch<T>> best_patches(n_patches);\n\n                for (int i = 0; i < n_patches; i++) {\n                    best_patches[i] = std::move(patches[patch_indices[i]]);\n                }\n\n                patches = std::move(best_patches);\n            }\n\n            template<class T>\n            bool is_homogenous_area(std::vector<ImagePatch<T>> &patches, float noise_std) {\n\n                float std2 = std::accumulate(patches.begin(), patches.end(), 0.0f,\n                                             [](auto cur, auto patch) {\n                                                 float std = arma::stddev(patch.patch);\n                                                 return cur + std * std;\n                                             }\n                ) * patches.size() \/ float(patches.size() - 1);\n\n                return std2 < noise_std * noise_std * 1.1;\n            }\n\n\n            template<class T>\n            void denoise_patches(std::vector<ImagePatch<T>> &patches, float noise_std) {\n                auto mean_patch = get_mean_patch(patches);\n\n                if (is_homogenous_area(patches, noise_std)) {\n                    auto mean_value = arma::mean(mean_patch);\n                    for (auto &patch: patches) patch.patch.fill(mean_value);\n                    return;\n                }\n\n                auto covariance_matrix = get_covariance_matrix(patches, mean_patch);\n                arma::Mat<T> noise_covariance = covariance_matrix + noise_std * noise_std * arma::eye<arma::Mat<T>>(\n                        arma::size(covariance_matrix));\n                auto inv_cov = arma::Mat<T>(arma::size(covariance_matrix));\n                if (inv(inv_cov, noise_covariance)) {\n                    for (auto &patch : patches) {\n                        patch.patch = mean_patch + inv_cov * covariance_matrix * (patch.patch - mean_patch);\n                    }\n                }\n\n            }\n\n            template<class T>\n            hoNDArray<T> non_local_bayes_single_image(const hoNDArray<T> &image, float noise_std, int search_window) {\n\n\n                if (image.get_number_of_dimensions() != 2)\n                    throw std::invalid_argument(\"non_local_bayes: image must be 2 dimensional\");\n\n                constexpr int patch_size = 5;\n                constexpr int n_patches = 50;\n\n                hoNDArray<T> result(image.dimensions());\n                result.fill(0);\n\n                hoNDArray<bool> mask(image.dimensions());\n                mask.fill(true);\n\n                hoNDArray<int> count(image.dimensions());\n                count.fill(0);\n\n                const vector_td<int, 2> image_dims = vector_td<int, 2>(\n                        from_std_vector<size_t, 2>(image.dimensions())\n                );\n\n#pragma omp parallel for num_threads(4)\n                for (int ky = 0; ky < image.get_size(1); ky++) {\n                    for (int kx = 0; kx < image.get_size(0); kx++) {\n\n                        if (mask(kx, ky)) {\n                            auto reference_patch = get_patch(image, kx, ky, patch_size, image_dims);\n                            auto patches = create_patches(image, kx, ky, patch_size, search_window, image_dims);\n\n                            filter_patches(patches, n_patches, reference_patch);\n                            denoise_patches(patches, noise_std);\n\n                            for (auto &patch : patches) {\n                                #pragma omp critical\n                                add_patch(patch, result, count, patch_size, image_dims);\n                                mask(patch.center_x, patch.center_y) = false;\n                            }\n                        }\n                    }\n                }\n\n                for (size_t i = 0; i < result.get_number_of_elements(); i++) {\n                    result[i] \/= count[i];\n                }\n\n                return result;\n\n            }\n\n\n            template<class T>\n            hoNDArray<T> non_local_bayes_T(const hoNDArray<T> &image, float noise_std, unsigned int search_window) {\n\n                size_t n_images = image.get_number_of_elements() \/ (image.get_size(0) * image.get_size(1));\n\n                std::vector<size_t> image_dims = {image.get_size(0), image.get_size(1)};\n                size_t image_elements = image_dims[0] * image_dims[1];\n\n                auto result = hoNDArray<T>(image.dimensions());\n\n                hoNDArray<T> result_view;\n                result_view.create(image_dims);\n                #pragma omp parallel for\n                for (int i = 0; i < n_images; i++) {\n\n                    auto image_view = hoNDArray<T>(image_dims, const_cast<T*>(image.get_data_ptr() + i * image_elements));\n                    result_view = non_local_bayes_single_image(image_view, noise_std, search_window);\n\n                    memcpy(result.begin() + i * image_elements, result_view.begin(), result_view.get_number_of_bytes());\n                }\n                return result;\n            }\n        }\n\n\n        hoNDArray<float> non_local_bayes(const hoNDArray<float> &image, float noise_std, unsigned int search_window) {\n            return non_local_bayes_T(image, noise_std, search_window);\n        }\n\n        hoNDArray<std::complex<float>>\n        non_local_bayes(const hoNDArray<std::complex<float>> &image, float noise_std, unsigned int search_window) {\n            return non_local_bayes_T(image, noise_std, search_window);\n        }\n    }\n\n}\n","avg_line_length":38.8984962406,"max_line_length":122,"alphanum_fraction":0.4975355175,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1375,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <Graphics\/Window.h>\n\nvoid WindowResizeCallback(GLFWwindow* window, int width, int height);\n\nWindow::Window(std::string title, int width, int height) :\n\tm_Title(title), m_Width(width), m_Height(height)\n{\n\tif (!this->Initialize())\n\t{\n\t\tglfwTerminate();\n\t}\n\n\tInput::Initialize(this);\n}\n\nWindow::~Window()\n{\n\tglfwTerminate();\n}\n\nbool Window::Initialize()\n{\n\tif (!glfwInit())\n\t{\n\t\tstd::cout << \"Window::Initialize: Failed to initialize GLFW!\\n\";\n\t\treturn false;\n\t}\n\n\tthis->m_Window = glfwCreateWindow(this->m_Width, this->m_Height, this->m_Title.c_str(), nullptr, nullptr);\n\tif (!this->m_Window)\n\t{\n\t\tstd::cout << \"Window::Initialize: Failed to create window!\\n\";\n\t\treturn false;\n\t}\n\n\tglfwSetWindowSizeCallback(this->m_Window, WindowResizeCallback);\n\n\tthis->MakeContextCurrent();\n\n\tif (glewInit() != GLEW_OK)\n\t{\n\t\tstd::cout << \"Window::Initialize: Failed to initialize GLEW!\\n\";\n\t\treturn false;\n\t}\n\n\tstd::cout << \"OpenGL \" << glGetString(GL_VERSION) << \"\\n\";\n\treturn true;\n}\n\nvoid Window::Clear()\n{\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n}\n\nvoid Window::Update()\n{\n\tglfwPollEvents();\n\tglfwSwapBuffers(this->m_Window);\n}\n\nvoid Window::SetTitle(std::string title)\n{\n\tthis->m_Title = title;\n\tglfwSetWindowTitle(this->m_Window, this->m_Title.c_str());\n}\n\nvoid WindowResizeCallback(GLFWwindow* window, int width, int height)\n{\n\tglViewport(0, 0, width, height);\n}","avg_line_length":19.6428571429,"max_line_length":107,"alphanum_fraction":0.6974545455,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":24251,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":2.0,"content":"\/\/========= Copyright Valve Corporation, All rights reserved. ============\/\/\n\/\/\n\/\/ Purpose:\t\tPlayer for HL2.\n\/\/\n\/\/=============================================================================\/\/\n\n#include \"cbase.h\"\n#include \"vcollide_parse.h\"\n#include \"c_hl2mp_player.h\"\n#include \"view.h\"\n#include \"takedamageinfo.h\"\n#include \"hl2mp_gamerules.h\"\n#include \"in_buttons.h\"\n#include \"iviewrender_beams.h\"\t\t\t\/\/ flashlight beam\n#include \"r_efx.h\"\n#include \"dlight.h\"\n\n\/\/ Don't alias here\n#if defined( CHL2MP_Player )\n#undef CHL2MP_Player\t\n#endif\n\n#ifndef HL2RP\nLINK_ENTITY_TO_CLASS( player, C_HL2MP_Player );\n#endif \/\/ !HL2RP\n\nIMPLEMENT_CLIENTCLASS_DT(C_HL2MP_Player, DT_HL2MP_Player, CHL2MP_Player)\n\tRecvPropFloat( RECVINFO( m_angEyeAngles[0] ) ),\n\tRecvPropFloat( RECVINFO( m_angEyeAngles[1] ) ),\n\tRecvPropEHandle( RECVINFO( m_hRagdoll ) ),\n\tRecvPropInt( RECVINFO( m_iSpawnInterpCounter ) ),\n\tRecvPropInt( RECVINFO( m_iPlayerSoundType) ),\n\n\tRecvPropBool( RECVINFO( m_fIsWalking ) ),\nEND_RECV_TABLE()\n\nBEGIN_PREDICTION_DATA( C_HL2MP_Player )\n\tDEFINE_PRED_FIELD( m_fIsWalking, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ),\nEND_PREDICTION_DATA()\n\n#define\tHL2_WALK_SPEED 150\n#define\tHL2_NORM_SPEED 190\n#define\tHL2_SPRINT_SPEED 320\n\nstatic ConVar cl_playermodel( \"cl_playermodel\", \"none\", FCVAR_USERINFO | FCVAR_ARCHIVE | FCVAR_SERVER_CAN_EXECUTE, \"Default Player Model\");\nstatic ConVar cl_defaultweapon( \"cl_defaultweapon\", \"weapon_physcannon\", FCVAR_USERINFO | FCVAR_ARCHIVE, \"Default Spawn Weapon\");\n\nvoid SpawnBlood (Vector vecSpot, const Vector &vecDir, int bloodColor, float flDamage);\n\nC_HL2MP_Player::C_HL2MP_Player() : m_PlayerAnimState( this ), m_iv_angEyeAngles( \"C_HL2MP_Player::m_iv_angEyeAngles\" )\n{\n\tm_iIDEntIndex = 0;\n\tm_iSpawnInterpCounterCache = 0;\n\n\tm_angEyeAngles.Init();\n\n\tAddVar( &m_angEyeAngles, &m_iv_angEyeAngles, LATCH_SIMULATION_VAR );\n\n\tm_EntClientFlags |= ENTCLIENTFLAG_DONTUSEIK;\n\tm_blinkTimer.Invalidate();\n\n\tm_pFlashlightBeam = NULL;\n}\n\nC_HL2MP_Player::~C_HL2MP_Player( void )\n{\n\tReleaseFlashlight();\n}\n\nint C_HL2MP_Player::GetIDTarget() const\n{\n\treturn m_iIDEntIndex;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Update this client's target entity\n\/\/-----------------------------------------------------------------------------\nvoid C_HL2MP_Player::UpdateIDTarget()\n{\n\tif ( !IsLocalPlayer() )\n\t\treturn;\n\n\t\/\/ Clear old target and find a new one\n\tm_iIDEntIndex = 0;\n\n\t\/\/ don't show IDs in chase spec mode\n\tif ( GetObserverMode() == OBS_MODE_CHASE || \n\t\t GetObserverMode() == OBS_MODE_DEATHCAM )\n\t\t return;\n\n\ttrace_t tr;\n\tVector vecStart, vecEnd;\n\tVectorMA( MainViewOrigin(), 1500, MainViewForward(), vecEnd );\n\tVectorMA( MainViewOrigin(), 10,   MainViewForward(), vecStart );\n\tUTIL_TraceLine( vecStart, vecEnd, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr );\n\n\tif ( !tr.startsolid && tr.DidHitNonWorldEntity() )\n\t{\n\t\tC_BaseEntity *pEntity = tr.m_pEnt;\n\n\t\tif ( pEntity && (pEntity != this) )\n\t\t{\n\t\t\tm_iIDEntIndex = pEntity->entindex();\n\t\t}\n\t}\n}\n\nvoid C_HL2MP_Player::TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator )\n{\n\tVector vecOrigin = ptr->endpos - vecDir * 4;\n\n\tfloat flDistance = 0.0f;\n\t\n\tif ( info.GetAttacker() )\n\t{\n\t\tflDistance = (ptr->endpos - info.GetAttacker()->GetAbsOrigin()).Length();\n\t}\n\n\tif ( m_takedamage )\n\t{\n\t\tAddMultiDamage( info, this );\n\n\t\tint blood = BloodColor();\n\t\t\n\t\tCBaseEntity *pAttacker = info.GetAttacker();\n\n\t\tif ( pAttacker )\n\t\t{\n\t\t\tif ( HL2MPRules()->IsTeamplay() && pAttacker->InSameTeam( this ) == true )\n\t\t\t\treturn;\n\t\t}\n\n\t\tif ( blood != DONT_BLEED )\n\t\t{\n\t\t\tSpawnBlood( vecOrigin, vecDir, blood, flDistance );\/\/ a little surface blood.\n\t\t\tTraceBleed( flDistance, vecDir, ptr, info.GetDamageType() );\n\t\t}\n\t}\n}\n\n\nC_HL2MP_Player* C_HL2MP_Player::GetLocalHL2MPPlayer()\n{\n\treturn (C_HL2MP_Player*)C_BasePlayer::GetLocalPlayer();\n}\n\nvoid C_HL2MP_Player::Initialize( void )\n{\n\tm_headYawPoseParam = LookupPoseParameter( \"head_yaw\" );\n\tGetPoseParameterRange( m_headYawPoseParam, m_headYawMin, m_headYawMax );\n\n\tm_headPitchPoseParam = LookupPoseParameter( \"head_pitch\" );\n\tGetPoseParameterRange( m_headPitchPoseParam, m_headPitchMin, m_headPitchMax );\n\n\tCStudioHdr *hdr = GetModelPtr();\n\tfor ( int i = 0; i < hdr->GetNumPoseParameters() ; i++ )\n\t{\n\t\tSetPoseParameter( hdr, i, 0.0 );\n\t}\n}\n\nCStudioHdr *C_HL2MP_Player::OnNewModel( void )\n{\n\tCStudioHdr *hdr = BaseClass::OnNewModel();\n\t\n\tInitialize( );\n\n\treturn hdr;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/**\n * Orient head and eyes towards m_lookAt.\n *\/\nvoid C_HL2MP_Player::UpdateLookAt( void )\n{\n\t\/\/ head yaw\n\tif (m_headYawPoseParam < 0 || m_headPitchPoseParam < 0)\n\t\treturn;\n\n\t\/\/ orient eyes\n\tm_viewtarget = m_vLookAtTarget;\n\n\t\/\/ blinking\n\tif (m_blinkTimer.IsElapsed())\n\t{\n\t\tm_blinktoggle = !m_blinktoggle;\n\t\tm_blinkTimer.Start( RandomFloat( 1.5f, 4.0f ) );\n\t}\n\n\t\/\/ Figure out where we want to look in world space.\n\tQAngle desiredAngles;\n\tVector to = m_vLookAtTarget - EyePosition();\n\tVectorAngles( to, desiredAngles );\n\n\t\/\/ Figure out where our body is facing in world space.\n\tQAngle bodyAngles( 0, 0, 0 );\n\tbodyAngles[YAW] = GetLocalAngles()[YAW];\n\n\n\tfloat flBodyYawDiff = bodyAngles[YAW] - m_flLastBodyYaw;\n\tm_flLastBodyYaw = bodyAngles[YAW];\n\t\n\n\t\/\/ Set the head's yaw.\n\tfloat desired = AngleNormalize( desiredAngles[YAW] - bodyAngles[YAW] );\n\tdesired = clamp( desired, m_headYawMin, m_headYawMax );\n\tm_flCurrentHeadYaw = ApproachAngle( desired, m_flCurrentHeadYaw, 130 * gpGlobals->frametime );\n\n\t\/\/ Counterrotate the head from the body rotation so it doesn't rotate past its target.\n\tm_flCurrentHeadYaw = AngleNormalize( m_flCurrentHeadYaw - flBodyYawDiff );\n\tdesired = clamp( desired, m_headYawMin, m_headYawMax );\n\t\n\tSetPoseParameter( m_headYawPoseParam, m_flCurrentHeadYaw );\n\n\t\n\t\/\/ Set the head's yaw.\n\tdesired = AngleNormalize( desiredAngles[PITCH] );\n\tdesired = clamp( desired, m_headPitchMin, m_headPitchMax );\n\t\n\tm_flCurrentHeadPitch = ApproachAngle( desired, m_flCurrentHeadPitch, 130 * gpGlobals->frametime );\n\tm_flCurrentHeadPitch = AngleNormalize( m_flCurrentHeadPitch );\n\tSetPoseParameter( m_headPitchPoseParam, m_flCurrentHeadPitch );\n}\n\nvoid C_HL2MP_Player::ClientThink( void )\n{\n\tbool bFoundViewTarget = false;\n\t\n\tVector vForward;\n\tAngleVectors( GetLocalAngles(), &vForward );\n\n\tfor( int iClient = 1; iClient <= gpGlobals->maxClients; ++iClient )\n\t{\n\t\tCBaseEntity *pEnt = UTIL_PlayerByIndex( iClient );\n\t\tif(!pEnt || !pEnt->IsPlayer())\n\t\t\tcontinue;\n\n\t\tif ( pEnt->entindex() == entindex() )\n\t\t\tcontinue;\n\n\t\tVector vTargetOrigin = pEnt->GetAbsOrigin();\n\t\tVector vMyOrigin =  GetAbsOrigin();\n\n\t\tVector vDir = vTargetOrigin - vMyOrigin;\n\t\t\n\t\tif ( vDir.Length() > 128 ) \n\t\t\tcontinue;\n\n\t\tVectorNormalize( vDir );\n\n\t\tif ( DotProduct( vForward, vDir ) < 0.0f )\n\t\t\t continue;\n\n\t\tm_vLookAtTarget = pEnt->EyePosition();\n\t\tbFoundViewTarget = true;\n\t\tbreak;\n\t}\n\n\tif ( bFoundViewTarget == false )\n\t{\n\t\tm_vLookAtTarget = GetAbsOrigin() + vForward * 512;\n\t}\n\n\tUpdateIDTarget();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nint C_HL2MP_Player::DrawModel( int flags )\n{\n\tif ( !m_bReadyToDraw )\n\t\treturn 0;\n\n    return BaseClass::DrawModel(flags);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Should this object receive shadows?\n\/\/-----------------------------------------------------------------------------\nbool C_HL2MP_Player::ShouldReceiveProjectedTextures( int flags )\n{\n\tAssert( flags & SHADOW_FLAGS_PROJECTED_TEXTURE_TYPE_MASK );\n\n\tif ( IsEffectActive( EF_NODRAW ) )\n\t\t return false;\n\n\tif( flags & SHADOW_FLAGS_FLASHLIGHT )\n\t{\n\t\treturn true;\n\t}\n\n\treturn BaseClass::ShouldReceiveProjectedTextures( flags );\n}\n\nvoid C_HL2MP_Player::DoImpactEffect( trace_t &tr, int nDamageType )\n{\n\tif ( GetActiveWeapon() )\n\t{\n\t\tGetActiveWeapon()->DoImpactEffect( tr, nDamageType );\n\t\treturn;\n\t}\n\n\tBaseClass::DoImpactEffect( tr, nDamageType );\n}\n\nvoid C_HL2MP_Player::PreThink( void )\n{\n\tQAngle vTempAngles = GetLocalAngles();\n\n\tif ( GetLocalPlayer() == this )\n\t{\n\t\tvTempAngles[PITCH] = EyeAngles()[PITCH];\n\t}\n\telse\n\t{\n\t\tvTempAngles[PITCH] = m_angEyeAngles[PITCH];\n\t}\n\n\tif ( vTempAngles[YAW] < 0.0f )\n\t{\n\t\tvTempAngles[YAW] += 360.0f;\n\t}\n\n\tSetLocalAngles( vTempAngles );\n\n\tBaseClass::PreThink();\n\n\tHandleSpeedChanges();\n\n\tif ( m_HL2Local.m_flSuitPower <= 0.0f )\n\t{\n\t\tif( IsSprinting() )\n\t\t{\n\t\t\tStopSprinting();\n\t\t}\n\t}\n}\n\nconst QAngle &C_HL2MP_Player::EyeAngles()\n{\n\tif( IsLocalPlayer() )\n\t{\n\t\treturn BaseClass::EyeAngles();\n\t}\n\telse\n\t{\n\t\treturn m_angEyeAngles;\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid C_HL2MP_Player::AddEntity( void )\n{\n\tBaseClass::AddEntity();\n\n\tQAngle vTempAngles = GetLocalAngles();\n\tvTempAngles[PITCH] = m_angEyeAngles[PITCH];\n\n\tSetLocalAngles( vTempAngles );\n\t\t\n\tm_PlayerAnimState.Update();\n\n\t\/\/ Zero out model pitch, blending takes care of all of it.\n\tSetLocalAnglesDim( X_INDEX, 0 );\n\n\tif( this != C_BasePlayer::GetLocalPlayer() )\n\t{\n\t\tif ( IsEffectActive( EF_DIMLIGHT ) )\n\t\t{\n\t\t\tint iAttachment = LookupAttachment( \"anim_attachment_RH\" );\n\n\t\t\tif ( iAttachment < 0 )\n\t\t\t\treturn;\n\n\t\t\tVector vecOrigin;\n\t\t\tQAngle eyeAngles = m_angEyeAngles;\n\t\n\t\t\tGetAttachment( iAttachment, vecOrigin, eyeAngles );\n\n\t\t\tVector vForward;\n\t\t\tAngleVectors( eyeAngles, &vForward );\n\t\t\t\t\n\t\t\ttrace_t tr;\n\t\t\tUTIL_TraceLine( vecOrigin, vecOrigin + (vForward * 200), MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );\n\n\t\t\tif( !m_pFlashlightBeam )\n\t\t\t{\n\t\t\t\tBeamInfo_t beamInfo;\n\t\t\t\tbeamInfo.m_nType = TE_BEAMPOINTS;\n\t\t\t\tbeamInfo.m_vecStart = tr.startpos;\n\t\t\t\tbeamInfo.m_vecEnd = tr.endpos;\n\t\t\t\tbeamInfo.m_pszModelName = \"sprites\/glow01.vmt\";\n\t\t\t\tbeamInfo.m_pszHaloName = \"sprites\/glow01.vmt\";\n\t\t\t\tbeamInfo.m_flHaloScale = 3.0;\n\t\t\t\tbeamInfo.m_flWidth = 8.0f;\n\t\t\t\tbeamInfo.m_flEndWidth = 35.0f;\n\t\t\t\tbeamInfo.m_flFadeLength = 300.0f;\n\t\t\t\tbeamInfo.m_flAmplitude = 0;\n\t\t\t\tbeamInfo.m_flBrightness = 60.0;\n\t\t\t\tbeamInfo.m_flSpeed = 0.0f;\n\t\t\t\tbeamInfo.m_nStartFrame = 0.0;\n\t\t\t\tbeamInfo.m_flFrameRate = 0.0;\n\t\t\t\tbeamInfo.m_flRed = 255.0;\n\t\t\t\tbeamInfo.m_flGreen = 255.0;\n\t\t\t\tbeamInfo.m_flBlue = 255.0;\n\t\t\t\tbeamInfo.m_nSegments = 8;\n\t\t\t\tbeamInfo.m_bRenderable = true;\n\t\t\t\tbeamInfo.m_flLife = 0.5;\n\t\t\t\tbeamInfo.m_nFlags = FBEAM_FOREVER | FBEAM_ONLYNOISEONCE | FBEAM_NOTILE | FBEAM_HALOBEAM;\n\t\t\t\t\n\t\t\t\tm_pFlashlightBeam = beams->CreateBeamPoints( beamInfo );\n\t\t\t}\n\n\t\t\tif( m_pFlashlightBeam )\n\t\t\t{\n\t\t\t\tBeamInfo_t beamInfo;\n\t\t\t\tbeamInfo.m_vecStart = tr.startpos;\n\t\t\t\tbeamInfo.m_vecEnd = tr.endpos;\n\t\t\t\tbeamInfo.m_flRed = 255.0;\n\t\t\t\tbeamInfo.m_flGreen = 255.0;\n\t\t\t\tbeamInfo.m_flBlue = 255.0;\n\n\t\t\t\tbeams->UpdateBeamInfo( m_pFlashlightBeam, beamInfo );\n\n\t\t\t\tdlight_t *el = effects->CL_AllocDlight( 0 );\n\t\t\t\tel->origin = tr.endpos;\n\t\t\t\tel->radius = 50; \n\t\t\t\tel->color.r = 200;\n\t\t\t\tel->color.g = 200;\n\t\t\t\tel->color.b = 200;\n\t\t\t\tel->die = gpGlobals->curtime + 0.1;\n\t\t\t}\n\t\t}\n\t\telse if ( m_pFlashlightBeam )\n\t\t{\n\t\t\tReleaseFlashlight();\n\t\t}\n\t}\n}\n\nShadowType_t C_HL2MP_Player::ShadowCastType( void ) \n{\n\tif ( !IsVisible() )\n\t\t return SHADOWS_NONE;\n\n\treturn SHADOWS_RENDER_TO_TEXTURE_DYNAMIC;\n}\n\n\nconst QAngle& C_HL2MP_Player::GetRenderAngles()\n{\n\tif ( IsRagdoll() )\n\t{\n\t\treturn vec3_angle;\n\t}\n\telse\n\t{\n\t\treturn m_PlayerAnimState.GetRenderAngles();\n\t}\n}\n\nbool C_HL2MP_Player::ShouldDraw( void )\n{\n\t\/\/ If we're dead, our ragdoll will be drawn for us instead.\n\tif ( !IsAlive() )\n\t\treturn false;\n\n\/\/\tif( GetTeamNumber() == TEAM_SPECTATOR )\n\/\/\t\treturn false;\n\n\tif( IsLocalPlayer() && IsRagdoll() )\n\t\treturn true;\n\t\n\tif ( IsRagdoll() )\n\t\treturn false;\n\n\treturn BaseClass::ShouldDraw();\n}\n\nvoid C_HL2MP_Player::NotifyShouldTransmit( ShouldTransmitState_t state )\n{\n\tif ( state == SHOULDTRANSMIT_END )\n\t{\n\t\tif( m_pFlashlightBeam != NULL )\n\t\t{\n\t\t\tReleaseFlashlight();\n\t\t}\n\t}\n\n\tBaseClass::NotifyShouldTransmit( state );\n}\n\nvoid C_HL2MP_Player::OnDataChanged( DataUpdateType_t type )\n{\n\tBaseClass::OnDataChanged( type );\n\n\tif ( type == DATA_UPDATE_CREATED )\n\t{\n\t\tSetNextClientThink( CLIENT_THINK_ALWAYS );\n\t}\n\n\tUpdateVisibility();\n}\n\nvoid C_HL2MP_Player::PostDataUpdate( DataUpdateType_t updateType )\n{\n\tif ( m_iSpawnInterpCounter != m_iSpawnInterpCounterCache )\n\t{\n\t\tMoveToLastReceivedPosition( true );\n\t\tResetLatched();\n\t\tm_iSpawnInterpCounterCache = m_iSpawnInterpCounter;\n\t}\n\n\tBaseClass::PostDataUpdate( updateType );\n}\n\nvoid C_HL2MP_Player::ReleaseFlashlight( void )\n{\n\tif( m_pFlashlightBeam )\n\t{\n\t\tm_pFlashlightBeam->flags = 0;\n\t\tm_pFlashlightBeam->die = gpGlobals->curtime - 1;\n\n\t\tm_pFlashlightBeam = NULL;\n\t}\n}\n\nfloat C_HL2MP_Player::GetFOV( void )\n{\n\t\/\/Find our FOV with offset zoom value\n\tfloat flFOVOffset = C_BasePlayer::GetFOV() + GetZoom();\n\n\t\/\/ Clamp FOV in MP\n\tint min_fov = GetMinFOV();\n\t\n\t\/\/ Don't let it go too low\n\tflFOVOffset = MAX( min_fov, flFOVOffset );\n\n\treturn flFOVOffset;\n}\n\n\/\/=========================================================\n\/\/ Autoaim\n\/\/ set crosshair position to point to enemey\n\/\/=========================================================\nVector C_HL2MP_Player::GetAutoaimVector( float flDelta )\n{\n\t\/\/ Never autoaim a predicted weapon (for now)\n\tVector\tforward;\n\tAngleVectors( EyeAngles() + m_Local.m_vecPunchAngle, &forward );\n\treturn\tforward;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Returns whether or not we are allowed to sprint now.\n\/\/-----------------------------------------------------------------------------\nbool C_HL2MP_Player::CanSprint( void )\n{\n\treturn ( (!m_Local.m_bDucked && !m_Local.m_bDucking) && (GetWaterLevel() != 3) );\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\nvoid C_HL2MP_Player::StartSprinting( void )\n{\n\tif( m_HL2Local.m_flSuitPower < 10 )\n\t{\n\t\t\/\/ Don't sprint unless there's a reasonable\n\t\t\/\/ amount of suit power.\n\t\tCPASAttenuationFilter filter( this );\n\t\tfilter.UsePredictionRules();\n\t\tEmitSound( filter, entindex(), \"HL2Player.SprintNoPower\" );\n\t\treturn;\n\t}\n\n\tCPASAttenuationFilter filter( this );\n\tfilter.UsePredictionRules();\n\tEmitSound( filter, entindex(), \"HL2Player.SprintStart\" );\n\n\tSetMaxSpeed( HL2_SPRINT_SPEED );\n\tm_fIsSprinting = true;\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\nvoid C_HL2MP_Player::StopSprinting( void )\n{\n\tSetMaxSpeed( HL2_NORM_SPEED );\n\tm_fIsSprinting = false;\n}\n\nvoid C_HL2MP_Player::HandleSpeedChanges( void )\n{\n\tint buttonsChanged = m_afButtonPressed | m_afButtonReleased;\n\n\tif( buttonsChanged & IN_SPEED )\n\t{\n\t\t\/\/ The state of the sprint\/run button has changed.\n\t\tif ( IsSuitEquipped() )\n\t\t{\n\t\t\tif ( !(m_afButtonPressed & IN_SPEED)  && IsSprinting() )\n\t\t\t{\n\t\t\t\tStopSprinting();\n\t\t\t}\n\t\t\telse if ( (m_afButtonPressed & IN_SPEED) && !IsSprinting() )\n\t\t\t{\n\t\t\t\tif ( CanSprint() )\n\t\t\t\t{\n\t\t\t\t\tStartSprinting();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ Reset key, so it will be activated post whatever is suppressing it.\n\t\t\t\t\tm_nButtons &= ~IN_SPEED;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tHandleWalkChanges(buttonsChanged);\n}\n\nvoid C_HL2MP_Player::HandleWalkChanges(int buttonsChanged)\n{\n\tif (FBitSet(buttonsChanged, IN_SPEED | IN_WALK) == IN_WALK)\n\t{\n\t\tif ( IsSuitEquipped() )\n\t\t{\n\t\t\t\/\/ The state of the WALK button has changed. \n\t\t\tif( IsWalking() && !(m_afButtonPressed & IN_WALK) )\n\t\t\t{\n\t\t\t\tStopWalking();\n\t\t\t}\n\t\t\telse if( !IsWalking() && !IsSprinting() && (m_afButtonPressed & IN_WALK) && !(m_nButtons & IN_DUCK) )\n\t\t\t{\n\t\t\t\tStartWalking();\n\t\t\t}\n\t\t}\n\t}\n\n\tif ( IsSuitEquipped() && m_fIsWalking && !(m_nButtons & IN_WALK)  ) \n\t\tStopWalking();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\nvoid C_HL2MP_Player::StartWalking( void )\n{\n\tSetMaxSpeed( HL2_WALK_SPEED );\n\tm_fIsWalking = true;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\nvoid C_HL2MP_Player::StopWalking( void )\n{\n\tSetMaxSpeed( HL2_NORM_SPEED );\n\tm_fIsWalking = false;\n}\n\nvoid C_HL2MP_Player::ItemPreFrame( void )\n{\n\tif ( GetFlags() & FL_FROZEN )\n\t\t return;\n\n\t\/\/ Disallow shooting while zooming\n\tif ( m_nButtons & IN_ZOOM )\n\t{\n\t\t\/\/FIXME: Held weapons like the grenade get sad when this happens\n\t\tm_nButtons &= ~(IN_ATTACK|IN_ATTACK2);\n\t}\n\n\tBaseClass::ItemPreFrame();\n\n}\n\t\nvoid C_HL2MP_Player::ItemPostFrame( void )\n{\n\tif ( GetFlags() & FL_FROZEN )\n\t\t return;\n\n\tBaseClass::ItemPostFrame();\n}\n\nC_BaseAnimating *C_HL2MP_Player::BecomeRagdollOnClient()\n{\n\t\/\/ Let the C_CSRagdoll entity do this.\n\t\/\/ m_builtRagdoll = true;\n\treturn NULL;\n}\n\nvoid C_HL2MP_Player::CalcView( Vector &eyeOrigin, QAngle &eyeAngles, float &zNear, float &zFar, float &fov )\n{\n\tif ( m_lifeState != LIFE_ALIVE && !IsObserver() )\n\t{\n\t\tVector origin = EyePosition();\t\t\t\n\n\t\tIRagdoll *pRagdoll = GetRepresentativeRagdoll();\n\n\t\tif ( pRagdoll )\n\t\t{\n\t\t\torigin = pRagdoll->GetRagdollOrigin();\n\t\t\torigin.z += VEC_DEAD_VIEWHEIGHT_SCALED( this ).z; \/\/ look over ragdoll, not through\n\t\t}\n\n\t\tBaseClass::CalcView( eyeOrigin, eyeAngles, zNear, zFar, fov );\n\n\t\teyeOrigin = origin;\n\t\t\n\t\tVector vForward; \n\t\tAngleVectors( eyeAngles, &vForward );\n\n\t\tVectorNormalize( vForward );\n\t\tVectorMA( origin, -CHASE_CAM_DISTANCE_MAX, vForward, eyeOrigin );\n\n\t\tVector WALL_MIN( -WALL_OFFSET, -WALL_OFFSET, -WALL_OFFSET );\n\t\tVector WALL_MAX( WALL_OFFSET, WALL_OFFSET, WALL_OFFSET );\n\n\t\ttrace_t trace; \/\/ clip against world\n\t\tC_BaseEntity::PushEnableAbsRecomputations( false ); \/\/ HACK don't recompute positions while doing RayTrace\n\t\tUTIL_TraceHull( origin, eyeOrigin, WALL_MIN, WALL_MAX, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &trace );\n\t\tC_BaseEntity::PopEnableAbsRecomputations();\n\n\t\tif (trace.fraction < 1.0)\n\t\t{\n\t\t\teyeOrigin = trace.endpos;\n\t\t}\n\t\t\n\t\treturn;\n\t}\n\n\tBaseClass::CalcView( eyeOrigin, eyeAngles, zNear, zFar, fov );\n}\n\nIRagdoll* C_HL2MP_Player::GetRepresentativeRagdoll() const\n{\n\tif ( m_hRagdoll.Get() )\n\t{\n\t\tC_HL2MPRagdoll *pRagdoll = (C_HL2MPRagdoll*)m_hRagdoll.Get();\n\n\t\treturn pRagdoll->GetIRagdoll();\n\t}\n\telse\n\t{\n\t\treturn NULL;\n\t}\n}\n\n\/\/HL2MPRAGDOLL\n\n\nIMPLEMENT_CLIENTCLASS_DT_NOBASE( C_HL2MPRagdoll, DT_HL2MPRagdoll, CHL2MPRagdoll )\n\tRecvPropVector( RECVINFO(m_vecRagdollOrigin) ),\n\tRecvPropEHandle( RECVINFO( m_hPlayer ) ),\n\tRecvPropInt( RECVINFO( m_nModelIndex ) ),\n\tRecvPropInt( RECVINFO(m_nForceBone) ),\n\tRecvPropVector( RECVINFO(m_vecForce) ),\n\tRecvPropVector( RECVINFO( m_vecRagdollVelocity ) )\nEND_RECV_TABLE()\n\n\n\nC_HL2MPRagdoll::C_HL2MPRagdoll()\n{\n\n}\n\nC_HL2MPRagdoll::~C_HL2MPRagdoll()\n{\n\tPhysCleanupFrictionSounds( this );\n\n\tif ( m_hPlayer )\n\t{\n\t\tm_hPlayer->CreateModelInstance();\n\t}\n}\n\nvoid C_HL2MPRagdoll::Interp_Copy( C_BaseAnimatingOverlay *pSourceEntity )\n{\n\tif ( !pSourceEntity )\n\t\treturn;\n\t\n\tVarMapping_t *pSrc = pSourceEntity->GetVarMapping();\n\tVarMapping_t *pDest = GetVarMapping();\n    \t\n\t\/\/ Find all the VarMapEntry_t's that represent the same variable.\n\tfor ( int i = 0; i < pDest->m_Entries.Count(); i++ )\n\t{\n\t\tVarMapEntry_t *pDestEntry = &pDest->m_Entries[i];\n\t\tconst char *pszName = pDestEntry->watcher->GetDebugName();\n\t\tfor ( int j=0; j < pSrc->m_Entries.Count(); j++ )\n\t\t{\n\t\t\tVarMapEntry_t *pSrcEntry = &pSrc->m_Entries[j];\n\t\t\tif ( !Q_strcmp( pSrcEntry->watcher->GetDebugName(), pszName ) )\n\t\t\t{\n\t\t\t\tpDestEntry->watcher->Copy( pSrcEntry->watcher );\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid C_HL2MPRagdoll::ImpactTrace( trace_t *pTrace, int iDamageType, const char *pCustomImpactName )\n{\n\tIPhysicsObject *pPhysicsObject = VPhysicsGetObject();\n\n\tif( !pPhysicsObject )\n\t\treturn;\n\n\tVector dir = pTrace->endpos - pTrace->startpos;\n\n\tif ( iDamageType == DMG_BLAST )\n\t{\n\t\tdir *= 4000;  \/\/ adjust impact strenght\n\t\t\t\t\n\t\t\/\/ apply force at object mass center\n\t\tpPhysicsObject->ApplyForceCenter( dir );\n\t}\n\telse\n\t{\n\t\tVector hitpos;  \n\t\n\t\tVectorMA( pTrace->startpos, pTrace->fraction, dir, hitpos );\n\t\tVectorNormalize( dir );\n\n\t\tdir *= 4000;  \/\/ adjust impact strenght\n\n\t\t\/\/ apply force where we hit it\n\t\tpPhysicsObject->ApplyForceOffset( dir, hitpos );\t\n\n\t\t\/\/ Blood spray!\n\/\/\t\tFX_CS_BloodSpray( hitpos, dir, 10 );\n\t}\n\n\tm_pRagdoll->ResetRagdollSleepAfterTime();\n}\n\n\nvoid C_HL2MPRagdoll::CreateHL2MPRagdoll( void )\n{\n\t\/\/ First, initialize all our data. If we have the player's entity on our client,\n\t\/\/ then we can make ourselves start out exactly where the player is.\n\tC_HL2MP_Player *pPlayer = dynamic_cast< C_HL2MP_Player* >( m_hPlayer.Get() );\n\t\n\tif ( pPlayer && !pPlayer->IsDormant() )\n\t{\n\t\t\/\/ move my current model instance to the ragdoll's so decals are preserved.\n\t\tpPlayer->SnatchModelInstance( this );\n\n\t\tVarMapping_t *varMap = GetVarMapping();\n\n\t\t\/\/ Copy all the interpolated vars from the player entity.\n\t\t\/\/ The entity uses the interpolated history to get bone velocity.\n\t\tbool bRemotePlayer = (pPlayer != C_BasePlayer::GetLocalPlayer());\t\t\t\n\t\tif ( bRemotePlayer )\n\t\t{\n\t\t\tInterp_Copy( pPlayer );\n\n\t\t\tSetAbsAngles( pPlayer->GetRenderAngles() );\n\t\t\tGetRotationInterpolator().Reset();\n\n\t\t\tm_flAnimTime = pPlayer->m_flAnimTime;\n\t\t\tSetSequence( pPlayer->GetSequence() );\n\t\t\tm_flPlaybackRate = pPlayer->GetPlaybackRate();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ This is the local player, so set them in a default\n\t\t\t\/\/ pose and slam their velocity, angles and origin\n\t\t\tSetAbsOrigin( m_vecRagdollOrigin );\n\t\t\t\n\t\t\tSetAbsAngles( pPlayer->GetRenderAngles() );\n\n\t\t\tSetAbsVelocity( m_vecRagdollVelocity );\n\n\t\t\tint iSeq = pPlayer->GetSequence();\n\t\t\tif ( iSeq == -1 )\n\t\t\t{\n\t\t\t\tAssert( false );\t\/\/ missing walk_lower?\n\t\t\t\tiSeq = 0;\n\t\t\t}\n\t\t\t\n\t\t\tSetSequence( iSeq );\t\/\/ walk_lower, basic pose\n\t\t\tSetCycle( 0.0 );\n\n\t\t\tInterp_Reset( varMap );\n\t\t}\t\t\n\t}\n\telse\n\t{\n\t\t\/\/ overwrite network origin so later interpolation will\n\t\t\/\/ use this position\n\t\tSetNetworkOrigin( m_vecRagdollOrigin );\n\n\t\tSetAbsOrigin( m_vecRagdollOrigin );\n\t\tSetAbsVelocity( m_vecRagdollVelocity );\n\n\t\tInterp_Reset( GetVarMapping() );\n\t\t\n\t}\n\n\tSetModelIndex( m_nModelIndex );\n\n\t\/\/ Make us a ragdoll..\n\tm_nRenderFX = kRenderFxRagdoll;\n\n\tmatrix3x4_t boneDelta0[MAXSTUDIOBONES];\n\tmatrix3x4_t boneDelta1[MAXSTUDIOBONES];\n\tmatrix3x4_t currentBones[MAXSTUDIOBONES];\n\tconst float boneDt = 0.05f;\n\n\tif ( pPlayer && !pPlayer->IsDormant() )\n\t{\n\t\tpPlayer->GetRagdollInitBoneArrays( boneDelta0, boneDelta1, currentBones, boneDt );\n\t}\n\telse\n\t{\n\t\tGetRagdollInitBoneArrays( boneDelta0, boneDelta1, currentBones, boneDt );\n\t}\n\n\tInitAsClientRagdoll( boneDelta0, boneDelta1, currentBones, boneDt );\n}\n\n\nvoid C_HL2MPRagdoll::OnDataChanged( DataUpdateType_t type )\n{\n\tBaseClass::OnDataChanged( type );\n\n\tif ( type == DATA_UPDATE_CREATED )\n\t{\n\t\tCreateHL2MPRagdoll();\n\t}\n}\n\nIRagdoll* C_HL2MPRagdoll::GetIRagdoll() const\n{\n\treturn m_pRagdoll;\n}\n\nvoid C_HL2MPRagdoll::UpdateOnRemove( void )\n{\n\tVPhysicsSetObject( NULL );\n\n\tBaseClass::UpdateOnRemove();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: clear out any face\/eye values stored in the material system\n\/\/-----------------------------------------------------------------------------\nvoid C_HL2MPRagdoll::SetupWeights( const matrix3x4_t *pBoneToWorld, int nFlexWeightCount, float *pFlexWeights, float *pFlexDelayedWeights )\n{\n\tBaseClass::SetupWeights( pBoneToWorld, nFlexWeightCount, pFlexWeights, pFlexDelayedWeights );\n\n\tstatic float destweight[128];\n\tstatic bool bIsInited = false;\n\n\tCStudioHdr *hdr = GetModelPtr();\n\tif ( !hdr )\n\t\treturn;\n\n\tint nFlexDescCount = hdr->numflexdesc();\n\tif ( nFlexDescCount )\n\t{\n\t\tAssert( !pFlexDelayedWeights );\n\t\tmemset( pFlexWeights, 0, nFlexWeightCount * sizeof(float) );\n\t}\n\n\tif ( m_iEyeAttachment > 0 )\n\t{\n\t\tmatrix3x4_t attToWorld;\n\t\tif (GetAttachment( m_iEyeAttachment, attToWorld ))\n\t\t{\n\t\t\tVector local, tmp;\n\t\t\tlocal.Init( 1000.0f, 0.0f, 0.0f );\n\t\t\tVectorTransform( local, attToWorld, tmp );\n\t\t\tmodelrender->SetViewTarget( GetModelPtr(), GetBody(), tmp );\n\t\t}\n\t}\n}\n\nvoid C_HL2MP_Player::PostThink( void )\n{\n\tBaseClass::PostThink();\n\n\t\/\/ Store the eye angles pitch so the client can compute its animation state correctly.\n\tm_angEyeAngles = EyeAngles();\n}","avg_line_length":24.4219536757,"max_line_length":139,"alphanum_fraction":0.6537050019,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":608,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n    long long N, a, i;\r\n    int c;\r\n    while (cin >> N && N != 0)\r\n    {\r\n        if (N < 0)\r\n        {\r\n            N *= -1;\r\n        }\r\n        a = -1;\r\n        c = 0;\r\n        for (i = 2; i * i <= N && N != 1; i++) {\r\n            while (N % i == 0) {\r\n                N \/= i;\r\n                a = i;\r\n            }\r\n            if (a == i) {\r\n                c++;\r\n            }\r\n        }\r\n        if (N != 1 && a != -1)\r\n            a = N;\r\n        else if (c == 1)\r\n            a = -1;\r\n\r\n        cout << a << endl;\r\n    }\r\n    return 0;\r\n}","avg_line_length":18.4242424242,"max_line_length":49,"alphanum_fraction":0.2253289474,"low_alphanum":true,"long_lines":false,"lexable":true}
{"size":554,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include \"IndexBuffer.h\"\n#include \"OpenGL.h\"\n#include <GL\/glew.h>\n\nnamespace Allmund::Graphics::OPENGL {\n\n\tIndexBuffer::IndexBuffer(unsigned int* data, unsigned int count){\n\t\tGLCall(glGenBuffers(1, &buffer_id));\n\t\tBind();\n\t\tGLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(unsigned int), data, GL_STATIC_DRAW));\n\t\tUnbind();\n\t}\n\n\n\tIndexBuffer::~IndexBuffer(){\n\n\t}\n\n\tvoid IndexBuffer::Bind() {\n\t\tGLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer_id));\n\t}\n\n\tvoid IndexBuffer::Unbind() {\n\t\tGLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));\n\t}\n\n}","avg_line_length":20.5185185185,"max_line_length":100,"alphanum_fraction":0.7274368231,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3098,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":5.0,"content":"\n\/\/\u6b64\u6e90\u7801\u88ab\u6e05\u534e\u5b66\u795e\u5c39\u6210\u5927\u9b54\u738b\u4e13\u4e1a\u7ffb\u8bd1\u5206\u6790\u5e76\u4fee\u6539\n\/\/\u5c39\u6210QQ77025077\n\/\/\u5c39\u6210\u5fae\u4fe118510341407\n\/\/\u5c39\u6210\u6240\u5728QQ\u7fa4721929980\n\/\/\u5c39\u6210\u90ae\u7bb1 yinc13@mails.tsinghua.edu.cn\n\/\/\u5c39\u6210\u6bd5\u4e1a\u4e8e\u6e05\u534e\u5927\u5b66,\u5fae\u8f6f\u533a\u5757\u94fe\u9886\u57df\u5168\u7403\u6700\u6709\u4ef7\u503c\u4e13\u5bb6\n\/\/https:\/\/mvp.microsoft.com\/zh-cn\/PublicProfile\/4033620\n\/\/\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\n\/*\n    \u6b64\u6587\u4ef6\u662fRippled\u7684\u4e00\u90e8\u5206\uff1ahttps:\/\/github.com\/ripple\/rippled\n    \u7248\u6743\u6240\u6709\uff08c\uff092012\uff0c2013 Ripple Labs Inc.\n\n    \u4f7f\u7528\u3001\u590d\u5236\u3001\u4fee\u6539\u548c\/\u6216\u5206\u53d1\u672c\u8f6f\u4ef6\u7684\u6743\u9650\n    \u7279\u6b64\u6388\u4e88\u514d\u8d39\u6216\u4e0d\u6536\u8d39\u7684\u76ee\u7684\uff0c\u524d\u63d0\u662f\n    \u7248\u6743\u58f0\u660e\u548c\u672c\u8bb8\u53ef\u58f0\u660e\u51fa\u73b0\u5728\u6240\u6709\u526f\u672c\u4e2d\u3002\n\n    \u672c\u8f6f\u4ef6\u6309\u201c\u539f\u6837\u201d\u63d0\u4f9b\uff0c\u4f5c\u8005\u4e0d\u4f5c\u4efb\u4f55\u4fdd\u8bc1\u3002\n    \u5173\u4e8e\u672c\u8f6f\u4ef6\uff0c\u5305\u62ec\n    \u9002\u9500\u6027\u548c\u9002\u7528\u6027\u3002\u5728\u4efb\u4f55\u60c5\u51b5\u4e0b\uff0c\u4f5c\u8005\u90fd\u4e0d\u5bf9\n    \u4efb\u4f55\u7279\u6b8a\u3001\u76f4\u63a5\u3001\u95f4\u63a5\u6216\u540e\u679c\u6027\u635f\u5bb3\u6216\u4efb\u4f55\u635f\u5bb3\n    \u56e0\u4f7f\u7528\u3001\u6570\u636e\u6216\u5229\u6da6\u635f\u5931\u800c\u5bfc\u81f4\u7684\u4efb\u4f55\u60c5\u51b5\uff0c\u65e0\u8bba\u662f\u5728\n    \u5408\u540c\u884c\u4e3a\u3001\u758f\u5ffd\u6216\u5176\u4ed6\u4fb5\u6743\u884c\u4e3a\n    \u6216\u4e0e\u672c\u8f6f\u4ef6\u7684\u4f7f\u7528\u6216\u6027\u80fd\u6709\u5173\u3002\n**\/\n\n\/\/==============================================================\n\n#include <ripple\/app\/ledger\/ConsensusTransSetSF.h>\n#include <ripple\/app\/ledger\/TransactionMaster.h>\n#include <ripple\/app\/main\/Application.h>\n#include <ripple\/app\/misc\/NetworkOPs.h>\n#include <ripple\/app\/misc\/Transaction.h>\n#include <ripple\/basics\/Log.h>\n#include <ripple\/protocol\/digest.h>\n#include <ripple\/core\/JobQueue.h>\n#include <ripple\/nodestore\/Database.h>\n#include <ripple\/protocol\/HashPrefix.h>\n\nnamespace ripple {\n\nConsensusTransSetSF::ConsensusTransSetSF (Application& app, NodeCache& nodeCache)\n    : app_ (app)\n    , m_nodeCache (nodeCache)\n    , j_ (app.journal (\"TransactionAcquire\"))\n{\n}\n\nvoid\nConsensusTransSetSF::gotNode(bool fromFilter, SHAMapHash const& nodeHash,\n    std::uint32_t, Blob&& nodeData, SHAMapTreeNode::TNType type) const\n{\n    if (fromFilter)\n        return;\n\n    m_nodeCache.insert (nodeHash, nodeData);\n\n    if ((type == SHAMapTreeNode::tnTRANSACTION_NM) && (nodeData.size () > 16))\n    {\n\/\/\u8fd9\u662f\u4e00\u7b14\u4ea4\u6613\uff0c\u6211\u4eec\u6ca1\u6709\n        JLOG (j_.debug())\n                << \"Node on our acquiring TX set is TXN we may not have\";\n\n        try\n        {\n\/\/\u8df3\u8fc7\u524d\u7f00\n            Serializer s (nodeData.data() + 4, nodeData.size() - 4);\n            SerialIter sit (s.slice());\n            auto stx = std::make_shared<STTx const> (std::ref (sit));\n            assert (stx->getTransactionID () == nodeHash.as_uint256());\n            auto const pap = &app_;\n            app_.getJobQueue ().addJob (\n                jtTRANSACTION, \"TXS->TXN\",\n                [pap, stx] (Job&) {\n                    pap->getOPs().submitTransaction(stx);\n                });\n        }\n        catch (std::exception const&)\n        {\n            JLOG (j_.warn())\n                    << \"Fetched invalid transaction in proposed set\";\n        }\n    }\n}\n\nboost::optional<Blob>\nConsensusTransSetSF::getNode (SHAMapHash const& nodeHash) const\n{\n    Blob nodeData;\n    if (m_nodeCache.retrieve (nodeHash, nodeData))\n        return nodeData;\n\n    auto txn = app_.getMasterTransaction().fetch(nodeHash.as_uint256(), false);\n\n    if (txn)\n    {\n\/\/\u8fd9\u662f\u4e00\u7b14\u4ea4\u6613\uff0c\u6211\u4eec\u6709\u5b83\n        JLOG (j_.trace())\n                << \"Node in our acquiring TX set is TXN we have\";\n        Serializer s;\n        s.add32 (HashPrefix::transactionID);\n        txn->getSTransaction ()->add (s);\n        assert(sha512Half(s.slice()) == nodeHash.as_uint256());\n        nodeData = s.peekData ();\n        return nodeData;\n    }\n\n    return boost::none;\n}\n\n} \/\/\u6d9f\u6f2a\n","avg_line_length":27.6607142857,"max_line_length":114,"alphanum_fraction":0.5936087799,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2438,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <string.h>\n#include <vector>\n\n#include \"OBJLoader.h\"\n#include \"Mesh.h\"\n\nstatic const unsigned char MAX_CHAR_SIZE = 64;\n\nnamespace OBJLoader\n{\n\tbool LoadOBJ(char* path, Mesh &mesh)\n\t{\n\t\tFILE* file;\n\t\tfopen_s(&file, path, \"r\");\n\t\tif (file == NULL)\n\t\t{\n\t\t\tprintf(\"Opening file failed\");\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tstd::vector<Vector3> vertices, normals;\n\t\tstd::vector<Vector2> uvs;\n\t\tstd::vector<Face> faces;\n\n\t\twhile (true)\n\t\t{\n\t\t\tchar lineHeader[MAX_CHAR_SIZE];\n\t\t\t\n\t\t\t\/\/ read the first word of the line\n\t\t\tint res = fscanf_s(file, \"%s\", lineHeader, sizeof(lineHeader));\n\t\t\tif (res == EOF)\n\t\t\t\tbreak;\n\n\t\t\tif (strcmp(lineHeader, \"v\") == 0)\n\t\t\t{\n\t\t\t\tVector3 vertex;\n\t\t\t\tfscanf_s(file, \"%f %f %f\\n\", &vertex.x, &vertex.y, &vertex.z);\n\t\t\t\tvertices.push_back(vertex);\n\t\t\t}\n\t\t\telse if (strcmp(lineHeader, \"vt\") == 0)\n\t\t\t{\n\t\t\t\tVector2 uv;\n\t\t\t\tfscanf_s(file, \"%f %f\\n\", &uv.x, &uv.y);\n\t\t\t\tuvs.push_back(uv);\n\t\t\t}\n\t\t\telse if (strcmp(lineHeader, \"vn\") == 0)\n\t\t\t{\n\t\t\t\tVector3 normal;\n\t\t\t\tfscanf_s(file, \"%f %f %f\\n\", &normal.x, &normal.y, &normal.z);\n\t\t\t\tnormals.push_back(normal);\n\t\t\t}\n\t\t\telse if (strcmp(lineHeader, \"f\") == 0)\n\t\t\t{\n\t\t\t\tFace face;\n\t\t\t\tint matches = fscanf_s(file, \"%d\/%d\/%d %d\/%d\/%d %d\/%d\/%d\\n\",\n\t\t\t\t\t&face.v1[0], &face.v1[1], &face.v1[2],\n\t\t\t\t\t&face.v2[0], &face.v2[1], &face.v2[2],\n\t\t\t\t\t&face.v3[0], &face.v3[1], &face.v3[2]);\n\t\t\t\tif (matches != 9)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"File can't be read by our simple parser : ( Try exporting with other options\\n\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Indexes for .obj faces start at 1. Our array's start at 0.\n\t\t\t\tfor (int i = 0; i < 3; i++)\n\t\t\t\t{\n\t\t\t\t\tface.v1[i]--;\n\t\t\t\t\tface.v2[i]--;\n\t\t\t\t\tface.v3[i]--;\n\t\t\t\t}\n\n\t\t\t\tfaces.push_back(face);\n\t\t\t}\n\t\t}\n\n\t\tmesh.ClearMesh();\n\t\t\n\t\tmesh.vertexCount = vertices.size();\n\t\tmesh.normalCount = normals.size();\n\t\tmesh.uvCount = uvs.size();\n\t\tmesh.faceCount = faces.size();\n\n\t\tmesh.vertices = new Vector3[vertices.size()];\n\t\tmesh.normals = new Vector3[normals.size()];\n\t\tmesh.uvs = new Vector2[uvs.size()];\n\t\tmesh.faces = new Face[faces.size()];\n\n\t\tfor (unsigned int i = 0; i < vertices.size(); i++)\n\t\t{\n\t\t\tmesh.vertices[i] = vertices[i];\n\t\t}\n\t\tfor (unsigned int i = 0; i < normals.size(); i++)\n\t\t{\n\t\t\tmesh.normals[i] = normals[i];\n\t\t}\n\t\tfor (unsigned int i = 0; i < uvs.size(); i++)\n\t\t{\n\t\t\tmesh.uvs[i] = uvs[i];\n\t\t}\n\t\tfor (unsigned int i = 0; i < faces.size(); i++)\n\t\t{\n\t\t\tmesh.faces[i] = faces[i];\n\t\t}\n\n\t\tmesh.GenerateBoundingBox();\n\n\t\treturn true;\n\t}\n}","avg_line_length":22.1636363636,"max_line_length":94,"alphanum_fraction":0.5721903199,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3601,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*****************************************************************************\/\n\/**\n *  @file   MarchingPrismTable.cpp\n *  @author Naohisa Sakamoto\n *\/\n\/*----------------------------------------------------------------------------\n *\n *  Copyright (c) Visualization Laboratory, Kyoto University.\n *  All rights reserved.\n *  See http:\/\/www.viz.media.kyoto-u.ac.jp\/kvs\/copyright\/ for details.\n *\n *  $Id$\n *\/\n\/*****************************************************************************\/\n#include \"MarchingPrismTable.h\"\n\n\nnamespace kvs\n{\n\nnamespace MarchingPrismTable\n{\n\nconst int TriangleID[64][10] =\n{\n    {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, \/\/  0\n    { 0, 6, 2,-1,-1,-1,-1,-1,-1,-1}, \/\/  1\n    { 0, 1, 7,-1,-1,-1,-1,-1,-1,-1}, \/\/  2\n    { 1, 6, 2, 1, 7, 6,-1,-1,-1,-1}, \/\/  3\n\n    { 1, 2, 8,-1,-1,-1,-1,-1,-1,-1}, \/\/  4\n    { 0, 6, 1, 1, 6, 8,-1,-1,-1,-1}, \/\/  5\n    { 0, 2, 7, 2, 8, 7,-1,-1,-1,-1}, \/\/  6\n    { 6, 8, 7,-1,-1,-1,-1,-1,-1,-1}, \/\/  7\n\n    { 3, 5, 6,-1,-1,-1,-1,-1,-1,-1}, \/\/  8\n    { 0, 3, 5, 0, 5, 2,-1,-1,-1,-1}, \/\/  9\n    { 0, 1, 7, 3, 5, 6,-1,-1,-1,-1}, \/\/ 10\n    { 1, 5, 2, 1, 7, 5, 3, 5, 7,-1}, \/\/ 11\n\n    { 1, 2, 8, 3, 5, 6,-1,-1,-1,-1}, \/\/ 12\n    { 0, 3, 5, 0, 5, 1, 1, 5, 8,-1}, \/\/ 13\n    { 0, 2, 7, 2, 8, 7, 3, 5, 6,-1}, \/\/ 14\n    { 3, 5, 7, 5, 8, 7,-1,-1,-1,-1}, \/\/ 15\n\n    { 3, 7, 4,-1,-1,-1,-1,-1,-1,-1}, \/\/ 16\n    { 0, 6, 2, 3, 7, 4,-1,-1,-1,-1}, \/\/ 17\n    { 0, 1, 3, 1, 4, 3,-1,-1,-1,-1}, \/\/ 18\n    { 2, 3, 6, 2, 4, 3, 1, 4, 2,-1}, \/\/ 19\n\n    { 3, 7, 4, 2, 8, 1,-1,-1,-1,-1}, \/\/ 20\n    { 0, 6, 1, 1, 6, 8, 3, 7, 4,-1}, \/\/ 21\n    { 0, 2, 3, 2, 8, 3, 3, 8, 4,-1}, \/\/ 22\n    { 3, 6, 8, 3, 8, 4,-1,-1,-1,-1}, \/\/ 23\n\n    { 5, 6, 7, 4, 5, 7,-1,-1,-1,-1}, \/\/ 24\n    { 0, 7, 2, 2, 7, 5, 4, 5, 7,-1}, \/\/ 25\n    { 0, 5, 6, 0, 1, 5, 1, 4, 5,-1}, \/\/ 26\n    { 1, 5, 2, 1, 4, 5,-1,-1,-1,-1}, \/\/ 27\n\n    { 5, 6, 7, 4, 5, 7, 1, 2, 8,-1}, \/\/ 28\n    { 0, 7, 1, 4, 5, 8,-1,-1,-1,-1}, \/\/ 29\n    { 0, 2, 6, 4, 5, 8,-1,-1,-1,-1}, \/\/ 30\n    { 4, 5, 8,-1,-1,-1,-1,-1,-1,-1}, \/\/ 31\n\n    { 4, 8, 5,-1,-1,-1,-1,-1,-1,-1}, \/\/ 32\n    { 0, 6, 2, 4, 8, 5,-1,-1,-1,-1}, \/\/ 33\n    { 0, 1, 7, 4, 8, 5,-1,-1,-1,-1}, \/\/ 34\n    { 1, 6, 2, 1, 7, 6, 4, 8, 5,-1}, \/\/ 35\n\n    { 1, 2, 5, 1, 5, 4,-1,-1,-1,-1}, \/\/ 36\n    { 0, 5, 1, 1, 5, 4, 0, 6, 5,-1}, \/\/ 37\n    { 0, 2, 7, 2, 5, 7, 4, 7, 5,-1}, \/\/ 38\n    { 5, 7, 6, 4, 7, 5,-1,-1,-1,-1}, \/\/ 39\n\n    { 3, 8, 6, 3, 4, 8,-1,-1,-1,-1}, \/\/ 40\n    { 0, 3, 2, 2, 3, 8, 3, 4, 8,-1}, \/\/ 41\n    { 0, 1, 6, 1, 8, 6, 3, 4, 7,-1}, \/\/ 42\n    { 1, 8, 2, 3, 4, 7,-1,-1,-1,-1}, \/\/ 43\n\n    { 1, 2, 3, 1, 3, 4,-1,-1,-1,-1}, \/\/ 44\n    { 0, 3, 1, 1, 3, 4,-1,-1,-1,-1}, \/\/ 45\n    { 0, 2, 6, 3, 4, 7,-1,-1,-1,-1}, \/\/ 46\n    { 3, 4, 7,-1,-1,-1,-1,-1,-1,-1}, \/\/ 47\n\n    { 3, 7, 5, 5, 7, 8,-1,-1,-1,-1}, \/\/ 48\n    { 0, 6, 2, 3, 7, 5, 5, 7, 8,-1}, \/\/ 49\n    { 0, 5, 3, 0, 8, 5, 0, 1, 8,-1}, \/\/ 50\n    { 1, 8, 2, 3, 6, 5,-1,-1,-1,-1}, \/\/ 51\n\n    { 2, 3, 7, 1, 2, 7,-1,-1,-1,-1}, \/\/ 52\n    { 0, 7, 1, 3, 6, 5,-1,-1,-1,-1}, \/\/ 53\n    { 0, 5, 3, 0, 2, 5,-1,-1,-1,-1}, \/\/ 54\n    { 3, 6, 5,-1,-1,-1,-1,-1,-1,-1}, \/\/ 55\n\n    { 6, 7, 8,-1,-1,-1,-1,-1,-1,-1}, \/\/ 56\n    { 0, 7, 2, 2, 7, 8,-1,-1,-1,-1}, \/\/ 57\n    { 0, 8, 6, 0, 1, 8,-1,-1,-1,-1}, \/\/ 58\n    { 1, 8, 2,-1,-1,-1,-1,-1,-1,-1}, \/\/ 59\n\n    { 2, 6, 7, 1, 2, 7,-1,-1,-1,-1}, \/\/ 60\n    { 0, 7, 1,-1,-1,-1,-1,-1,-1,-1}, \/\/ 61\n    { 0, 2, 6,-1,-1,-1,-1,-1,-1,-1}, \/\/ 62\n    {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}  \/\/ 63\n};\n\nconst int VertexID[9][2] =\n{\n    { 0, 1 },\n    { 1, 2 },\n    { 2, 0 },\n    { 3, 4 },\n    { 4, 5 },\n    { 5, 3 },\n    { 0, 3 },\n    { 1, 4 },\n    { 2, 5 }\n};\n\n} \/\/ end of namespace MarchingPrismTable\n\n} \/\/ end of namespace kvs\n","avg_line_length":29.2764227642,"max_line_length":79,"alphanum_fraction":0.3035267981,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5293,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0","Zlib","Apache-2.0"],"max_stars_count":1.0,"content":"\/\/ --------------------------------------------------------------------------\n\/\/                   OpenMS -- Open-Source Mass Spectrometry\n\/\/ --------------------------------------------------------------------------\n\/\/ Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n\/\/ ETH Zurich, and Freie Universitaet Berlin 2002-2018.\n\/\/\n\/\/ This software is released under a three-clause BSD license:\n\/\/  * Redistributions of source code must retain the above copyright\n\/\/    notice, this list of conditions and the following disclaimer.\n\/\/  * Redistributions in binary form must reproduce the above copyright\n\/\/    notice, this list of conditions and the following disclaimer in the\n\/\/    documentation and\/or other materials provided with the distribution.\n\/\/  * Neither the name of any author or any participating institution\n\/\/    may be used to endorse or promote products derived from this software\n\/\/    without specific prior written permission.\n\/\/ For a full list of authors, refer to the file AUTHORS.\n\/\/ --------------------------------------------------------------------------\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n\/\/ INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n\/\/ OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n\/\/ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n\/\/ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n\/\/ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ --------------------------------------------------------------------------\n\/\/ $Maintainer: Hannes Roest, Witold Wolski $\n\/\/ $Authors: Witold Wolski $\n\/\/ --------------------------------------------------------------------------\n\n#include <OpenMS\/CONCEPT\/ClassTest.h>\n#include <OpenMS\/test_config.h>\n\n#include <OpenMS\/OPENSWATHALGO\/DATAACCESS\/SpectrumHelpers.h>\n#include \"OpenMS\/OPENSWATHALGO\/DATAACCESS\/MockObjects.h\"\n\nusing namespace std;\nusing namespace OpenMS;\nusing namespace OpenSwath;\n\nSTART_TEST(DiaPrescore2, \"$Id$\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\nSTART_SECTION ( [EXTRA] testscorefunction)\n{\n\n\n  OpenSwath::SpectrumPtr sptr = (OpenSwath::SpectrumPtr)(new OpenSwath::Spectrum);\n  std::vector<OpenSwath::BinaryDataArrayPtr> binaryDataArrayPtrs;\n  OpenSwath::BinaryDataArrayPtr data1(new OpenSwath::BinaryDataArray);\n  OpenSwath::BinaryDataArrayPtr data2(new OpenSwath::BinaryDataArray);\n\n  static const double arr1[] = {\n\n    10, 20, 50, 100, 50, 20, 10, \/\/ peak at 499\n    3, 7, 15, 30, 15, 7, 3,      \/\/ peak at 500\n    1, 3, 9, 15, 9, 3, 1,        \/\/ peak at 501\n    3, 9, 3,                     \/\/ peak at 502\n\n    10, 20, 50, 100, 50, 20, 10, \/\/ peak at 600\n    3, 7, 15, 30, 15, 7, 3,      \/\/ peak at 601\n    1, 3, 9, 15, 9, 3, 1,        \/\/ peak at 602\n    3, 9, 3                      \/\/ peak at 603\n  };\n  std::vector<double> intensity (arr1, arr1 + sizeof(arr1) \/ sizeof(arr1[0]) );\n  static const double arr2[] = {\n    498.97, 498.98, 498.99, 499.0, 499.01, 499.02, 499.03,\n    499.97, 499.98, 499.99, 500.0, 500.01, 500.02, 500.03,\n    500.97, 500.98, 500.99, 501.0, 501.01, 501.02, 501.03,\n    501.99, 502.0, 502.01,\n    599.97, 599.98, 599.99, 600.0, 600.01, 600.02, 600.03,\n    600.97, 600.98, 600.99, 601.0, 601.01, 601.02, 601.03,\n    601.97, 601.98, 601.99, 602.0, 602.01, 602.02, 602.03,\n    602.99, 603.0, 603.01\n  };\n  std::vector<double> mz (arr2, arr2 + sizeof(arr2) \/ sizeof(arr2[0]) );\n  data1->data = mz;\n  data2->data = intensity;\n  sptr->setMZArray( data1);\n  sptr->setIntensityArray( data2);\n\n  double mzres, intensityres;\n  OpenSwath::integrateWindow(sptr,499.,501.,mzres, intensityres);\n\n  TEST_REAL_SIMILAR(mzres, 499.392014652015);\n  TEST_REAL_SIMILAR(intensityres,273 );\n\n\n  \/\/ >> exp = [240, 74, 39, 15, 0] > 121 \/ 500.338842975207\n  \/\/ >> theo = [1, 0.325757771553019, 0.0678711748364005, 0.0105918703087134, 0.00134955223787482]\n  \/\/ >> from scipy.stats.stats import pearsonr\n  \/\/ >> pearsonr(exp, theo)\n  \/\/ (0.99463189043051314, 0.00047175434098498532)\n  \/\/\n  OpenSwath::integrateWindow(sptr,499.6,501.4,mzres, intensityres);\n\n  std::cout << \"mz\" << mzres << std::endl;\n  std::cout << \"intensity\" << intensityres << std::endl;\n  TEST_REAL_SIMILAR(mzres, 500.338842975207);\n  TEST_REAL_SIMILAR(intensityres,121 );\n\n  std::vector<double> wincenter, mzresv, intresv;\n  wincenter.push_back(300.);\n  wincenter.push_back(200.);\n  wincenter.push_back(500.);\n  wincenter.push_back(600.);\n  OpenSwath::integrateWindows(sptr,wincenter,0.5, intresv, mzresv);\n  TEST_REAL_SIMILAR(mzresv[0], 300);\n  TEST_REAL_SIMILAR(intresv[0],0 );\n  TEST_REAL_SIMILAR(mzresv[1],200 );\n  TEST_REAL_SIMILAR(intresv[1],0 );\n}\nEND_SECTION\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n\n","avg_line_length":41.3515625,"max_line_length":98,"alphanum_fraction":0.611562441,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":20657,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":26.0,"content":"\/\/ bslalg_hashutil.t.cpp                                              -*-C++-*-\n\n#include <bslalg_hashutil.h>\n\n#include <bslma_default.h>\n#include <bslma_defaultallocatorguard.h>\n#include <bslma_testallocator.h>\n#include <bslma_testallocatormonitor.h>\n\n#include <bslmf_issame.h>\n\n#include <bsls_assert.h>\n#include <bsls_asserttest.h>\n#include <bsls_bsltestutil.h>\n#include <bsls_stopwatch.h>\n#include <bsls_types.h>\n\n#include <limits.h>  \/\/ INT_MAX\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace BloombergLP;\nusing bslalg::HashUtil;\n\n\/\/=============================================================================\n\/\/                                 TEST PLAN\n\/\/-----------------------------------------------------------------------------\n\/\/                                  Overview\n\/\/                                  --------\n\/\/ The component under test provides two hash functions.  We test them on a\n\/\/ two kinds of buffers (fixed-length - integer, and variable-length) during\n\/\/ the breathing test.  Together with the usage example which performs various\n\/\/ experiments to be reported on in the component-level documentation, this is\n\/\/ appropriate testing.  There are no other concerns about this component.\n\/\/-----------------------------------------------------------------------------\n\/\/ [ 1] BREATHING TEST\n\/\/ [ 2] HASHING FUNDAMENTAL TYPES\n\/\/ [ 3] USAGE EXAMPLE\n\/\/-----------------------------------------------------------------------------\n\n\/\/ ============================================================================\n\/\/                    STANDARD BDE ASSERT TEST MACROS\n\/\/ ----------------------------------------------------------------------------\n\nnamespace {\n\nint testStatus = 0;\n\nvoid aSsErT(bool b, const char *s, int i)\n{\n    if (b) {\n        printf(\"Error \" __FILE__ \"(%d): %s    (failed)\\n\", i, s);\n        if (testStatus >= 0 && testStatus <= 100) ++testStatus;\n    }\n}\n\n}  \/\/ close unnamed namespace\n\n\/\/=============================================================================\n\/\/                       STANDARD BDE TEST DRIVER MACROS\n\/\/-----------------------------------------------------------------------------\n\n#define ASSERT       BSLS_BSLTESTUTIL_ASSERT\n#define LOOP_ASSERT  BSLS_BSLTESTUTIL_LOOP_ASSERT\n#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT\n#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT\n#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT\n#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT\n#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT\n#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT\n#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT\n#define ASSERTV      BSLS_BSLTESTUTIL_ASSERTV\n\n#define Q   BSLS_BSLTESTUTIL_Q   \/\/ Quote identifier literally.\n#define P   BSLS_BSLTESTUTIL_P   \/\/ Print identifier and value.\n#define P_  BSLS_BSLTESTUTIL_P_  \/\/ P(X) without '\\n'.\n#define T_  BSLS_BSLTESTUTIL_T_  \/\/ Print a tab (w\/o newline).\n#define L_  BSLS_BSLTESTUTIL_L_  \/\/ current Line number\n\n\/\/ ============================================================================\n\/\/                  PRINTF FORMAT MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ZU BSLS_BSLTESTUTIL_FORMAT_ZU\n\n\/\/ ============================================================================\n\/\/                  NEGATIVE-TEST MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)\n#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)\n#define ASSERT_PASS(EXPR)      BSLS_ASSERTTEST_ASSERT_PASS(EXPR)\n#define ASSERT_FAIL(EXPR)      BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)\n#define ASSERT_OPT_PASS(EXPR)  BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)\n#define ASSERT_OPT_FAIL(EXPR)  BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)\n\n\/\/=============================================================================\n\/\/                  GLOBAL TYPEDEFS\/CONSTANTS FOR TESTING\n\/\/-----------------------------------------------------------------------------\n\nint verbose;\nint veryVerbose;\nint veryVeryVerbose;\n\nconst int LENGTH = 1257;  \/\/ not a power of two\n\ntemplate <class TYPE>\nvoid time_computeHash(const TYPE&   key,\n                const char   *TYPEID)\n{\n    enum { ITERATIONS = 1000000 }; \/\/ 1M\n    native_std::size_t value = 0;\n    bsls::Stopwatch timer;\n    timer.start();\n    for (int i = 0; i < ITERATIONS; ++i) {\n        value += HashUtil::computeHash(key) % LENGTH;\n    }\n    timer.stop();\n    printf(\"Hashing 1M values (in seconds): %g\\tof type %s\\n\",\n           timer.elapsedTime(),\n           TYPEID);\n    (void) value;\n}\n\nnative_std::size_t countBits(native_std::size_t value)\n{\n    native_std::size_t ret = 0;\n    for (; value; value >>= 1) {\n        ret += static_cast<int>(value & 1);\n    }\n\n    return ret;\n}\n\n\/\/=============================================================================\n\/\/                              MAIN PROGRAM\n\/\/-----------------------------------------------------------------------------\n\nint main(int argc, char *argv[])\n{\n    int test = argc > 1 ? atoi(argv[1]) : 0;\n    verbose = argc > 2;\n    veryVerbose = argc > 3;\n    veryVeryVerbose = argc > 4;\n\n    (void) veryVerbose;\n    (void) veryVeryVerbose;\n\n    printf(\"TEST \" __FILE__ \" CASE %d\\n\", test);\n\n    switch (test) { case 0:  \/\/ Zero is always the leading case.\n      case 3: {\n        \/\/ --------------------------------------------------------------------\n        \/\/ USAGE EXAMPLE\n        \/\/   This test is at the same time a usage example and a set of\n        \/\/   measurement experiments.\n        \/\/\n        \/\/ Plan:\n        \/\/   Verify that the code compiles and output the results of\n        \/\/   the experiments.\n        \/\/\n        \/\/ Testing:\n        \/\/   USAGE EXAMPLE\n        \/\/ --------------------------------------------------------------------\n\n        if (verbose) printf(\"\\nUSAGE EXAMPLE\"\n                            \"\\n=============\\n\");\n\n\/\/ Suppose we want to analyze our hash function by seeing how it distributes\n\/\/ integers across buckets.   We will declare 64 buckets, and distribute hits\n\/\/ among the bucket by indexing them with the low order 6 bits of the hash.\n\/\/ Then we will display the distribution of hits in each bucket, to see if\n\/\/ the hash function is distributing them evenly.\n\n        int buckets[64];\n\n\/\/ First, we hash on the values of i in the range '[ 0, 1 << 15 )':\n\n        {\n            memset(buckets, 0, sizeof(buckets));\n            for (int i = 0; i < (1 << 15); ++i) {\n                native_std::size_t hash = bslalg::HashUtil::computeHash(i);\n\n                ++buckets[hash & 63];\n            }\n            if (verbose) printf(\"Straight hash:\\n\");\n            int col = 0;\n            for (int i = 0; i < 64; ++i) {\n                if (verbose) printf(\"%s%5d\", (0 == col ? \"    \" : \", \"),\n                                                                  buckets[i]);\n                ++col;\n                if (8 == col) {\n                    col = 0;\n                    if (verbose) printf(\"\\n\");\n                }\n            }\n        }\n\n\/\/ Then, we will hash on the values of '4 * i' for i in the range\n\/\/ '[ 0, 1 << 15 )'.  This is interesting because pointers will often be 4-byte\n\/\/ aligned and have the 2 low-order bits always zero, so this will be a\n\/\/ simulation of that:\n\n        {\n            memset(buckets, 0, sizeof(buckets));\n            for (int i = 0; i < (1 << 15); ++i) {\n                native_std::size_t hash = bslalg::HashUtil::computeHash(4 * i);\n\n                ++buckets[hash & 63];\n            }\n            if (verbose) printf(\"\\nStraight * 4 hash:\\n\");\n            int col = 0;\n            for (int i = 0; i < 64; ++i) {\n                if (verbose) printf(\"%s%5d\", (0 == col ? \"    \" : \", \"),\n                                                                  buckets[i]);\n                ++col;\n                if (8 == col) {\n                    col = 0;\n                    if (verbose) printf(\"\\n\");\n                }\n            }\n        }\n\n\/\/ Next, we will xor the bottom 30 bits of the hash into the bottom 6 bits, so\n\/\/ we'll be observing more of the whole word:\n\n        {\n            memset(buckets, 0, sizeof(buckets));\n            for (int i = 0; i < (1 << 15); ++i) {\n                native_std::size_t hash = bslalg::HashUtil::computeHash(i);\n                hash = hash ^ (hash >> 6) ^ (hash >> 12) ^ (hash >> 18) ^\n                              (hash >> 24);\n\n                ++buckets[hash & 63];\n            }\n            if (verbose) printf(\"\\nFolded hash:\\n\");\n            int col = 0;\n            for (int i = 0; i < 64; ++i) {\n                if (verbose) printf(\"%s%5d\", (0 == col ? \"    \" : \", \"),\n                                                                  buckets[i]);\n                ++col;\n                if (8 == col) {\n                    col = 0;\n                    if (verbose) printf(\"\\n\");\n                }\n            }\n        }\n\n\/\/ Now, bear in mind that an identity hash will perform very optimally on the\n\/\/ first and third tests we did.  This time we will take the difference between\n\/\/ the current hash and the previous one, a test for which the identity\n\/\/ function would perform abominably:\n\n        {\n            memset(buckets, 0, sizeof(buckets));\n            native_std::size_t prev = 0;\n            for (int i = 0; i < (1 << 15); ++i) {\n                native_std::size_t hash = bslalg::HashUtil::computeHash(i);\n\n                ++buckets[(hash - prev) & 63];\n                prev = hash;\n            }\n            if (verbose) printf(\"\\nDiff hash:\\n\");\n            int col = 0;\n            for (int i = 0; i < 64; ++i) {\n                if (verbose) printf(\"%s%5d\", (0 == col ? \"    \" : \", \"),\n                                                                  buckets[i]);\n                ++col;\n                if (8 == col) {\n                    col = 0;\n                    if (verbose) printf(\"\\n\");\n                }\n            }\n        }\n\n\/\/ Finally, take the difference between the previous hash and the current one,\n\/\/ only this time, instead of subtracting, take a bitwise xor:\n\n        {\n            memset(buckets, 0, sizeof(buckets));\n            native_std::size_t prev = 0;\n            for (int i = 0; i < (1 << 15); ++i) {\n                native_std::size_t hash = bslalg::HashUtil::computeHash(i);\n\n                ++buckets[(hash ^ prev) & 63];\n                prev = hash;\n            }\n            if (verbose) printf(\"\\nXor diff hash:\\n\");\n            int col = 0;\n            for (int i = 0; i < 64; ++i) {\n                if (verbose) printf(\"%s%5d\", (0 == col ? \"    \" : \", \"),\n                                                                  buckets[i]);\n                ++col;\n                if (8 == col) {\n                    col = 0;\n                    if (verbose) printf(\"\\n\");\n                }\n            }\n        }\n      } break;\n      case 2: {\n        \/\/ --------------------------------------------------------------------\n        \/\/ TESTING HASHING FUNDAMENTAL TYPES\n        \/\/\n        \/\/ Concerns:\n        \/\/   The hash should output a reasonable value, which does not depend\n        \/\/   on the endianness of the platform.\n        \/\/\n        \/\/ Plan:\n        \/\/   Compare return value to expected values computed on a given\n        \/\/   platform.\n        \/\/\n        \/\/ Testing:\n        \/\/    HashUtil::computeHash(char);\n        \/\/    HashUtil::computeHash(signed char);\n        \/\/    HashUtil::computeHash(unsigned char);\n        \/\/    HashUtil::computeHash(short);\n        \/\/    HashUtil::computeHash(unsigned short);\n        \/\/    HashUtil::computeHash(int);\n        \/\/    HashUtil::computeHash(unsigned int);\n        \/\/    HashUtil::computeHash(long);\n        \/\/    HashUtil::computeHash(unsigned long);\n        \/\/    HashUtil::computeHash(long long);\n        \/\/    HashUtil::computeHash(unsigned long long);\n        \/\/    HashUtil::computeHash(float);\n        \/\/    HashUtil::computeHash(double);\n        \/\/    HashUtil::computeHash(void*);\n        \/\/ --------------------------------------------------------------------\n\n        if (verbose) printf(\"\\nHASHING FUNDAMENTAL TYPES\"\n                            \"\\n=========================\\n\");\n\n        ASSERT(3392050242U == HashUtil::computeHash((char)'a'));\n        ASSERT(3392050242U == HashUtil::computeHash((signed char)'a'));\n        ASSERT(3392050242U == HashUtil::computeHash((unsigned char)'a'));\n        ASSERT(3111500981U == HashUtil::computeHash((short)12355));\n        ASSERT(3111500981U == HashUtil::computeHash((unsigned short)12355));\n        ASSERT(2509914878U == HashUtil::computeHash((int)0x12345678));\n        ASSERT(2509914878U == HashUtil::computeHash((unsigned int)0x12345678));\n        ASSERT(2509914878U == HashUtil::computeHash((long)0x12345678));\n        ASSERT(2509914878U ==\n                             HashUtil::computeHash((unsigned long)0x12345678));\n        ASSERT(2509914878U ==\n                   HashUtil::computeHash((long long)0x12345678));\n        ASSERT(2509914878U ==\n                  HashUtil::computeHash((unsigned long long)0x12345678));\n        ASSERT(2343743579U == HashUtil::computeHash((float)3.1415926536));\n        ASSERT(3721749206U ==\n                        HashUtil::computeHash((double)3.14159265358979323844));\n#ifdef BSLS_PLATFORM_CPU_64_BIT\n        ASSERT(2631003531U ==\n                           HashUtil::computeHash((void*)0xffab13f1324e5473LL));\n#else\n        ASSERT(1747622670U == HashUtil::computeHash((void*)0xffab13f1));\n#endif\n      } break;\n      case 1: {\n        \/\/ --------------------------------------------------------------------\n        \/\/ BREATHING TEST\n        \/\/   This case exercises (but does not fully test) basic functionality.\n        \/\/\n        \/\/ Concerns:\n        \/\/: 1 The class is sufficiently functional to enable comprehensive\n        \/\/:   testing in subsequent test cases.\n        \/\/\n        \/\/ Plan:\n        \/\/: 1 Perform and ad-hoc test of the primary modifiers and accessors.\n        \/\/:   Verify that small changes to the input value result in many\n        \/\/:   bits being toggled in the output.  Note that the hash function\n        \/\/:   currently only sets the low-order 32 bits of the result.  When\n        \/\/:   this is fixed the asserts should be changed to demand that at\n        \/\/:   least a quarter of the bits in a 'size_t' have chagned.\n        \/\/\n        \/\/ Testing:\n        \/\/   BREATHING TEST\n        \/\/ --------------------------------------------------------------------\n\n        if (verbose) printf(\"\\nBREATHING TEST\"\n                            \"\\n==============\\n\");\n\n        if (verbose) Q(Incrementing integers);\n\n        native_std::size_t lastHash = -1;\n        for (int i = 0; i < 100; ++i) {\n            native_std::size_t hash = HashUtil::computeHash(i);\n            native_std::size_t changed = countBits(hash ^ lastHash);\n            ASSERTV(i, changed, hash, lastHash,\n                                           changed > sizeof(unsigned) * 8 \/ 4);\n            ASSERT(changed > sizeof(unsigned) * 8 \/ 4);\n            if (verbose) printf(\n                       \"%2d: %8x, hash: %8x, lastHash: %8x, changed: \" ZU \"\\n\",\n                  i, i, (unsigned) hash, (unsigned) lastHash, changed);\n            lastHash = hash;\n        }\n\n        if (verbose) Q(Shifting Bit);\n\n        lastHash = -1;\n        long long valueToHash;\n        for (int i = 0; i < 64; ++i) {\n            valueToHash = (long long) 1 << i;\n            native_std::size_t hash = HashUtil::computeHash(valueToHash);\n            native_std::size_t changed = countBits(hash ^ lastHash);\n            ASSERT(changed > sizeof(unsigned) * 8 \/ 4);\n            if (verbose) printf(\n                    \"%2d: %16llx, hash: %8x, lastHash: %8x, changed: \" ZU \"\\n\",\n                i, valueToHash, (unsigned) hash, (unsigned) lastHash, changed);\n            lastHash = hash;\n        }\n\n        if (verbose) Q(Setting One Bit at a Time);\n\n        lastHash = -1;\n        valueToHash = 0;\n        for (int i = 0; i < 64; ++i) {\n            valueToHash |= (long long) 1 << i;\n            native_std::size_t hash = HashUtil::computeHash(\n                                                           (long long) 1 << i);\n            native_std::size_t changed = countBits(hash ^ lastHash);\n            ASSERT(changed > sizeof(unsigned) * 8 \/ 4);\n            if (verbose) printf(\n                    \"%2d: %16llx, hash: %8x, lastHash: %8x, changed: \" ZU \"\\n\",\n                i, valueToHash, (unsigned) hash, (unsigned) lastHash, changed);\n            lastHash = hash;\n        }\n\n        if (verbose) Q(Clearing One Bit at a Time);\n\n        valueToHash = -1;\n        for (int i = 0; i < 64; ++i) {\n            valueToHash &= ~((long long) 1 << i);\n            native_std::size_t hash = HashUtil::computeHash(\n                                                           (long long) 1 << i);\n            native_std::size_t changed = countBits(hash ^ lastHash);\n            ASSERT(changed > sizeof(unsigned) * 8 \/ 4);\n            if (verbose) printf(\n                    \"%2d: %16llx, hash: %8x, lastHash: %8x, changed: \" ZU \"\\n\",\n                i, valueToHash, (unsigned) hash, (unsigned) lastHash, changed);\n            lastHash = hash;\n        }\n      } break;\n      case -1: {\n        \/\/ --------------------------------------------------------------------\n        \/\/ PERFORMANCE MEASUREMENTS\n        \/\/\n        \/\/ Concerns:\n        \/\/   The hash are fairly thorough but are they fast?  Let's evaluate\n        \/\/   performance here.\n        \/\/\n        \/\/ Plan:\n        \/\/   Perform the test of case 2 inside a loop and report the timing\n        \/\/   using a 'bdes_stopwatch'.\n        \/\/\n        \/\/ Testing:\n        \/\/    HashUtil::computeHash(char);\n        \/\/    HashUtil::computeHash(signed char);\n        \/\/    HashUtil::computeHash(unsigned char);\n        \/\/    HashUtil::computeHash(short);\n        \/\/    HashUtil::computeHash(unsigned short);\n        \/\/    HashUtil::computeHash(int);\n        \/\/    HashUtil::computeHash(unsigned int);\n        \/\/    HashUtil::computeHash(long);\n        \/\/    HashUtil::computeHash(unsigned long);\n        \/\/    HashUtil::computeHash(long long);\n        \/\/    HashUtil::computeHash(unsigned long long);\n        \/\/    HashUtil::computeHash(float);\n        \/\/    HashUtil::computeHash(double);\n        \/\/    HashUtil::computeHash(void*);\n        \/\/ --------------------------------------------------------------------\n\n        if (verbose) printf(\"\\nHASHING FUNDAMENTAL TYPES\"\n                            \"\\n=========================\\n\");\n\n        time_computeHash((char)'a', \"char\");\n        time_computeHash((signed char)'a', \"signed char\");\n        time_computeHash((unsigned char)'a', \"unsigned char\");\n        time_computeHash((short)12355, \"short\");\n        time_computeHash((unsigned short)12355, \"unsigned short\");\n        time_computeHash((int)0x12345678, \"int\");\n        time_computeHash((unsigned int)0x12345678, \"unsigned int\");\n        time_computeHash((long)0x12345678, \"long\");\n        time_computeHash((unsigned long)0x12345678, \"unsigned long\");\n        time_computeHash((long long)0x12345678, \"bsls_Types::Int64\");\n        time_computeHash((unsigned long long)0x12345678,\n                         \"bsls_Types::Uint64\");\n        time_computeHash((float)3.1415926536, \"float\");\n        time_computeHash((double)3.14159265358979323844, \"double\");\n#ifdef BSLS_PLATFORM_CPU_64_BIT\n        time_computeHash((void*)0xffab13f1324e5473LL, \"void*\");\n#else\n        time_computeHash((void*)0xffab13f1, \"void*\");\n#endif\n      } break;\n      default: {\n        fprintf(stderr, \"WARNING: CASE `%d' NOT FOUND.\\n\", test);\n        testStatus = -1;\n      }\n    }\n\n    if (testStatus > 0) {\n        fprintf(stderr, \"Error, non-zero test status = %d.\\n\", testStatus);\n    }\n    return testStatus;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2013 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n","avg_line_length":39.4971319312,"max_line_length":79,"alphanum_fraction":0.4869051653,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":15753,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/\/ bsla_printf.t.cpp                                                  -*-C++-*-\n#include <bsla_printf.h>\n\n#include <bsls_assert.h>\n#include <bsls_bsltestutil.h>\n#include <bsls_platform.h>\n\n#include <string>\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>  \/\/ 'calloc', 'realloc', 'atoi'\n#include <string.h>  \/\/ 'strcmp'\n\n\/\/ Set this preprocessor macro to 1 to enable compile warnings being generated,\n\/\/ 0 to disable them.\n\n#define U_TRIGGER_WARNINGS 0\n\n\/\/ ============================================================================\n\/\/                                 TEST PLAN\n\/\/ ----------------------------------------------------------------------------\n\/\/                                 Overview\n\/\/                                 --------\n\/\/ This test driver serves as a framework for manually checking the annotations\n\/\/ (macros) defined in this component.  The tester must repeatedly rebuild this\n\/\/ test driver using a compliant compiler, each time defining different values\n\/\/ of the boolean 'U_TRIGGER_WARNINGS' preprocessor macro.  In each case, the\n\/\/ concerns are:\n\/\/\n\/\/: o Did the build succeed or not?\n\/\/:\n\/\/: o Was the expected warning observed or not?\n\/\/:\n\/\/: o Was the expected suppression of some warning suppressed or not?\n\/\/:\n\/\/: o For annotations taking arguments, do the results show if the arguments\n\/\/:   were properly passed to the underlying compiler directives?\n\/\/\n\/\/ The single run-time \"test\" provided by this test driver, the BREATHING TEST,\n\/\/ does nothing other than print out the values of the macros in verbose mode.\n\/\/\n\/\/ The controlling preprocessor macro is 'U_TRIGGER_WARNINGS', which, if set to\n\/\/ 1, provokes all the compiler warnings caused by the macros under test.  If\n\/\/ set to 0, prevents any warnings from happening.\n\/\/\n\/\/ The table below classifies each of the annotations provided by this\n\/\/ component by the entities to which it can be applied (i.e., function,\n\/\/ variable, and type) and the expected result (optimization, error, warning,\n\/\/ conditional warning, absence of warning).  The tag(s) found in the\n\/\/ right-most column appear as comments throughout this test driver.  They can\n\/\/ be used as an aid to navigation to the test code for each annotation, and an\n\/\/ aid to assuring test coverage.\n\/\/..\n\/\/  Annotation                            Result\n\/\/  ------------------------------------  --------\n\/\/  BSLA_PRINTF(FMTIDX, STARTIDX)         Warning\n\/\/..\n\/\/ ----------------------------------------------------------------------------\n\/\/ [ 2] USAGE EXAMPLE\n\/\/ [ 1] BREATHING TEST\n\/\/ ----------------------------------------------------------------------------\n\nnamespace bsls = BloombergLP::bsls;\n\n\/\/ ============================================================================\n\/\/                     STANDARD BSL ASSERT TEST FUNCTION\n\/\/ ----------------------------------------------------------------------------\n\nnamespace {\n\nint testStatus = 0;\n\nvoid aSsErT(bool condition, const char *message, int line)\n{\n    if (condition) {\n        printf(\"Error \" __FILE__ \"(%d): %s    (failed)\\n\", line, message);\n\n        if (0 <= testStatus && testStatus <= 100) {\n            ++testStatus;\n        }\n    }\n}\n\n}  \/\/ close unnamed namespace\n\n\/\/ ============================================================================\n\/\/               STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ASSERT       BSLS_BSLTESTUTIL_ASSERT\n#define ASSERTV      BSLS_BSLTESTUTIL_ASSERTV\n\n#define LOOP_ASSERT  BSLS_BSLTESTUTIL_LOOP_ASSERT\n#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT\n#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT\n#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT\n#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT\n#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT\n#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT\n#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT\n\n#define Q            BSLS_BSLTESTUTIL_Q   \/\/ Quote identifier literally.\n#define P            BSLS_BSLTESTUTIL_P   \/\/ Print identifier and value.\n#define P_           BSLS_BSLTESTUTIL_P_  \/\/ P(X) without '\\n'.\n#define T_           BSLS_BSLTESTUTIL_T_  \/\/ Print a tab (w\/o newline).\n#define L_           BSLS_BSLTESTUTIL_L_  \/\/ current Line number\n\n#define STRINGIFY2(...) \"\" #__VA_ARGS__\n#define STRINGIFY(a) STRINGIFY2(a)\n\n\/\/ ============================================================================\n\/\/                                USAGE EXAMPLE\n\/\/ ----------------------------------------------------------------------------\n\n\/\/\n\/\/\/Usage\n\/\/\/-----\n\/\/ This section illustrates intended use of this component.\n\/\/\n\/\/\/Example 1: 'printf'-Like Function That Returns a 'bsl::string' by Value\n\/\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\/\/ First, we define a function, 'strPrintf', that takes a variable number of\n\/\/ arguments.  The second argument is the format string, and we annotate it\n\/\/ with 'BSLA_PRINTF':\n\/\/..\n    std::string strPrintf(size_t *numChars, const char *format, ...)\n                                                             BSLA_PRINTF(2, 3);\n    std::string strPrintf(size_t *numChars, const char *format, ...)\n        \/\/ Do a 'sprintf'-style write to a 'std::string' and return the string\n        \/\/ by value.  Ensure that the write can't overflow unless memory or\n        \/\/ address space is exhausted.  The specified '*numChars' is the number\n        \/\/ of characters written, the specified 'format' is the 'printf'-style\n        \/\/ format string, and the specified '...' is the variable-length list\n        \/\/ of arguments to be formatted.\n    {\n        std::string ret = \" \";\n\/\/\n        va_list ap;\n        va_start(ap, format);\n\n        \/\/ 'vsnprintf' returns the number of characters that WOULD have been\n        \/\/ written (not including the terminating '\\0') had the buffer been\n        \/\/ long enough.\n\n        *numChars = ::vsnprintf(&ret[0], 1, format, ap);\n        va_end(ap);\n\/\/\n        ret.resize(*numChars + 1);\n\/\/\n        va_start(ap, format);\n        *numChars = ::vsnprintf(&ret[0], *numChars + 1, format, ap);\n        va_end(ap);\n\/\/\n        BSLS_ASSERT(::strlen(ret.c_str()) == *numChars);\n\/\/\n        ret.resize(*numChars);\n        return ret;\n    }\n\/\/..\n\n\/\/ ============================================================================\n\/\/                  DECLARATION\/DEFINITION OF ANNOTATED FUNCTIONS\n\/\/ ----------------------------------------------------------------------------\n\nvoid test_PRINTF(const char *pattern, ...) BSLA_PRINTF(1, 2);\nvoid test_PRINTF(const char *pattern, ...)\n    \/\/ Do nothing with the specified 'pattern'.\n{\n    (void) pattern;\n}\n\n\/\/ ============================================================================\n\/\/                  DEFINITION OF ANNOTATED VARIABLES\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ ============================================================================\n\/\/                  DEFINITION OF ANNOTATED TYPES\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ ============================================================================\n\/\/                  USAGE WITH NO EXPECTED COMPILER WARNINGS\n\/\/ ----------------------------------------------------------------------------\n\nvoid use_without_diagnostic_message_PRINTF()\n    \/\/ Call 'test_PRINTF' a few times with correct arguments.\n{\n    test_PRINTF(\"%s\", \"string\");\n    test_PRINTF(\"%d\", 1);\n    test_PRINTF(\"%f\", 3.14159);\n}\n\n\/\/ ============================================================================\n\/\/                  USAGE WITH EXPECTED COMPILER WARNINGS\n\/\/ ----------------------------------------------------------------------------\n\n#if U_TRIGGER_WARNINGS\n\nvoid use_with_warning_message_PRINTF()\n{\n    test_PRINTF(\"%s\", 3.14159);\n    test_PRINTF(\"%d\", \"string\");\n    test_PRINTF(\"%f\", \"other string\");\n}\n\n#endif\n\n\/\/ ============================================================================\n\/\/                  USAGE WITH EXPECTED COMPILER ERRORS\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ ============================================================================\n\/\/                              HELPER FUNCTIONS\n\/\/ ----------------------------------------------------------------------------\n\nstatic void printFlags()\n    \/\/ Print a diagnostic message to standard output if any of the preprocessor\n    \/\/ flags of interest are defined, and their value if a value had been set.\n    \/\/ An \"Enter\" and \"Leave\" message is printed unconditionally so there is\n    \/\/ some report even if all of the flags are undefined.\n{\n    printf(\"printFlags: Enter\\n\");\n\n    printf(\"\\nprintFlags: bsls_annotation Macros\\n\");\n\n    printf(\"\\nBSLA_PRINTF(fmt, arg): \");\n#ifdef BSLA_PRINTF\n    printf(\"%s\\n\", STRINGIFY(BSLA_PRINTF(fmt, arg)) );\n#else\n    printf(\"UNDEFINED\\n\");\n#endif\n\n    printf(\"\\n\\n------------------------------\\n\");\n    printf(    \"printFlags: *_IS_ACTIVE Macros\\n\\n\");\n\n    P(BSLA_PRINTF_IS_ACTIVE);\n\n    printf(\"\\n\\n---------------------------------------------\\n\");\n    printf(    \"printFlags: bsls_annotation Referenced Macros\\n\");\n\n    printf(\"\\nBSLS_PLATFORM_CMP_CLANG: \");\n#ifdef BSLS_PLATFORM_CMP_CLANG\n    printf(\"%s\\n\", STRINGIFY(BSLS_PLATFORM_CMP_CLANG) );\n#else\n    printf(\"UNDEFINED\\n\");\n#endif\n\n    printf(\"\\nBSLS_PLATFORM_CMP_GNU: \");\n#ifdef BSLS_PLATFORM_CMP_GNU\n    printf(\"%s\\n\", STRINGIFY(BSLS_PLATFORM_CMP_GNU) );\n#else\n    printf(\"UNDEFINED\\n\");\n#endif\n\n    printf(\"\\nBSLS_PLATFORM_CMP_HP: \");\n#ifdef BSLS_PLATFORM_CMP_HP\n    printf(\"%s\\n\", STRINGIFY(BSLS_PLATFORM_CMP_HP) );\n#else\n    printf(\"UNDEFINED\\n\");\n#endif\n\n    printf(\"\\nBSLS_PLATFORM_CMP_IBM: \");\n#ifdef BSLS_PLATFORM_CMP_IBM\n    printf(\"%s\\n\", STRINGIFY(BSLS_PLATFORM_CMP_IBM) );\n#else\n    printf(\"UNDEFINED\\n\");\n#endif\n\n    printf(\"\\n\\nprintFlags: Leave\\n\");\n}\n\n\/\/ ============================================================================\n\/\/                            MAIN PROGRAM\n\/\/ ----------------------------------------------------------------------------\n\nint main(int argc, char **argv)\n{\n    int                 test = argc > 1 ? atoi(argv[1]) : 0;\n    bool             verbose = argc > 2;\n    bool         veryVerbose = argc > 3;\n    bool     veryVeryVerbose = argc > 4;\n\n    (void)        veryVerbose;  \/\/ unused variable warning\n    (void)    veryVeryVerbose;  \/\/ unused variable warning\n\n    printf( \"TEST %s CASE %d\\n\", __FILE__, test);\n\n    if (veryVeryVerbose) {\n        printFlags();\n    }\n\n    switch (test) { case 0:\n      case 2: {\n        \/\/ --------------------------------------------------------------------\n        \/\/ USAGE EXAMPLE\n        \/\/\n        \/\/ Concern:\n        \/\/: 1 That the usage example builds and performs as expected.\n        \/\/\n        \/\/ Plan:\n        \/\/: 1 Build and test the usage example.\n        \/\/\n        \/\/ Testing:\n        \/\/   USAGE EXAMPLE\n        \/\/ --------------------------------------------------------------------\n\n        if (verbose) printf(\"USAGE EXAMPLE\\n\"\n                            \"=============\\n\");\n\n#if BSLS_PLATFORM_OS_WINDOWS\n        \/\/ '::vsnprintf' doesn't behave the same on Windows as it does on other\n        \/\/ platforms, though MSDN says that it should.\n\n        break;\n#endif\n\n\/\/ Then, in 'main', we call the function correctly a couple of times:\n\/\/..\n        size_t len;\n        std::string s;\n\/\/\n        s = strPrintf(&len, \"%s %s %s %g\\n\", \"woof\", \"meow\", \"arf\", 23.5);\n        ASSERT(\"woof meow arf 23.5\\n\" == s);\n        ASSERT(19 == len);\n        ASSERT(len == s.length());\n\/\/\n        s = strPrintf(&len, \"%s %s %s %s %s %s %s %s %s\\n\",\n                               \"The\", \"rain\", \"in\", \"Spain\", \"falls\", \"mainly\",\n                                                         \"in\", \"the\", \"plain\");\n        ASSERT(\"The rain in Spain falls mainly in the plain\\n\" == s);\n        ASSERT(44 == len);\n        ASSERT(len == s.length());\n\/\/..\n\/\/ Now, we call it with too many arguments and of the wrong type:\n\/\/..\n#if U_TRIGGER_WARNINGS\n        s = strPrintf(&len, \"%c %f %g\", \"arf\", 27, 32, 65, 27);\n#endif\n\/\/..\n\/\/ Finally, we observe the compiler warnings with clang:\n\/\/..\n\/\/  ...\/bsla_printf.t.cpp:328:41: warning: format specifies type 'int' but the\n\/\/  argument has type 'const char *' [-Wformat]\n\/\/      s = strPrintf(&len, \"%c %f %g\", \"arf\", 27, 32, 65, 27);\n\/\/                           ~~         ^~~~~\n\/\/                           %s\n\/\/  ...\/bsla_printf.t.cpp:328:48: warning: format specifies type 'double' but\n\/\/  the argument has type 'int' [-Wformat]\n\/\/      s = strPrintf(&len, \"%c %f %g\", \"arf\", 27, 32, 65, 27);\n\/\/                              ~~             ^~\n\/\/                              %d\n\/\/  ...\/bsla_printf.t.cpp:328:52: warning: format specifies type 'double' but\n\/\/  the argument has type 'int' [-Wformat]\n\/\/      s = strPrintf(&len, \"%c %f %g\", \"arf\", 27, 32, 65, 27);\n\/\/                                 ~~              ^~\n\/\/                                 %d\n\/\/  ...\/bsla_printf.t.cpp:328:56: warning: data argument not used by format\n\/\/  string [-Wformat-extra-args]\n\/\/      s = strPrintf(&len, \"%c %f %g\", \"arf\", 27, 32, 65, 27);\n\/\/                          ~~~~~~~~~~                 ^\n\/\/..\n        (void) s;\n      } break;\n      case 1: {\n        \/\/ --------------------------------------------------------------------\n        \/\/ BREATHING TEST\n        \/\/\n        \/\/ Concerns:\n        \/\/: 1 This test driver builds with all expected compiler warning\n        \/\/:   messages and no unexpected warnings when the 'U_TRIGGER_WARNINGS'\n        \/\/:   preprocessor variable is defined to 1.\n        \/\/:\n        \/\/: 2 When 'U_TRIGGER_WARNINGS' is defined to 0, the compile is\n        \/\/:   successful and with no warnings.\n        \/\/\n        \/\/ Plan:\n        \/\/: 1 Build with 'U_TRIGGER_WARNINGS' defined to 1 and externally\n        \/\/:   examine compiler output for expected warnings and the absence of\n        \/\/:   warnings expected to be suppressed.  (C-1)\n        \/\/:\n        \/\/: 2 Build with 'U_TRIGGER_WARNINGS' defined to 0 and observe that the\n        \/\/:   compile is successful with no warnings.  (C-2)\n        \/\/\n        \/\/ Testing:\n        \/\/   BREATHING TEST\n        \/\/ --------------------------------------------------------------------\n\n        if (verbose) printf(\"\\nBREATHING TEST\"\n                            \"\\n==============\\n\");\n\n        if (verbose) {\n            printf(\"\\nThere are no run-time tests for this component.\"\n                   \"\\nManually run build-time tests using a conforming \"\n                   \"compiler.\");\n\n            if (!veryVeryVerbose) printFlags();\n\n            ASSERT(true); \/\/ remove unused warning for 'aSsErT'\n        }\n\n      } break;\n      default: {\n        fprintf( stderr, \"WARNING: CASE `%d` NOT FOUND.\\n\" , test);\n        testStatus = -1;\n      }\n    }\n\n    if (testStatus > 0) {\n        fprintf( stderr, \"Error, non-zero test status = %d.\\n\", testStatus );\n    }\n\n    return testStatus;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2019 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n","avg_line_length":36.6348837209,"max_line_length":79,"alphanum_fraction":0.4927315432,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8299,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause-No-Nuclear-License-2014","BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n * Copyright (C) 2010 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"core\/html\/forms\/DateTimeLocalInputType.h\"\n\n#include \"bindings\/core\/v8\/ExceptionState.h\"\n#include \"core\/HTMLNames.h\"\n#include \"core\/InputTypeNames.h\"\n#include \"core\/html\/HTMLInputElement.h\"\n#include \"core\/html\/forms\/DateTimeFieldsState.h\"\n#include \"platform\/DateComponents.h\"\n#include \"platform\/text\/PlatformLocale.h\"\n#include \"platform\/wtf\/text\/WTFString.h\"\n\nnamespace blink {\n\nusing blink::WebLocalizedString;\nusing namespace HTMLNames;\n\nstatic const int kDateTimeLocalDefaultStep = 60;\nstatic const int kDateTimeLocalDefaultStepBase = 0;\nstatic const int kDateTimeLocalStepScaleFactor = 1000;\n\nInputType* DateTimeLocalInputType::Create(HTMLInputElement& element) {\n  return new DateTimeLocalInputType(element);\n}\n\nvoid DateTimeLocalInputType::CountUsage() {\n  CountUsageIfVisible(WebFeature::kInputTypeDateTimeLocal);\n}\n\nconst AtomicString& DateTimeLocalInputType::FormControlType() const {\n  return InputTypeNames::datetime_local;\n}\n\ndouble DateTimeLocalInputType::ValueAsDate() const {\n  \/\/ valueAsDate doesn't work for the datetime-local type according to the\n  \/\/ standard.\n  return DateComponents::InvalidMilliseconds();\n}\n\nvoid DateTimeLocalInputType::SetValueAsDate(\n    double value,\n    ExceptionState& exception_state) const {\n  \/\/ valueAsDate doesn't work for the datetime-local type according to the\n  \/\/ standard.\n  InputType::SetValueAsDate(value, exception_state);\n}\n\nStepRange DateTimeLocalInputType::CreateStepRange(\n    AnyStepHandling any_step_handling) const {\n  DEFINE_STATIC_LOCAL(const StepRange::StepDescription, step_description,\n                      (kDateTimeLocalDefaultStep, kDateTimeLocalDefaultStepBase,\n                       kDateTimeLocalStepScaleFactor,\n                       StepRange::kScaledStepValueShouldBeInteger));\n\n  return InputType::CreateStepRange(\n      any_step_handling, kDateTimeLocalDefaultStepBase,\n      Decimal::FromDouble(DateComponents::MinimumDateTime()),\n      Decimal::FromDouble(DateComponents::MaximumDateTime()), step_description);\n}\n\nbool DateTimeLocalInputType::ParseToDateComponentsInternal(\n    const String& string,\n    DateComponents* out) const {\n  DCHECK(out);\n  unsigned end;\n  return out->ParseDateTimeLocal(string, 0, end) && end == string.length();\n}\n\nbool DateTimeLocalInputType::SetMillisecondToDateComponents(\n    double value,\n    DateComponents* date) const {\n  DCHECK(date);\n  return date->SetMillisecondsSinceEpochForDateTimeLocal(value);\n}\n\nString DateTimeLocalInputType::LocalizeValue(\n    const String& proposed_value) const {\n  DateComponents date;\n  if (!ParseToDateComponents(proposed_value, &date))\n    return proposed_value;\n\n  Locale::FormatType format_type = ShouldHaveSecondField(date)\n                                       ? Locale::kFormatTypeMedium\n                                       : Locale::kFormatTypeShort;\n  String localized = GetElement().GetLocale().FormatDateTime(date, format_type);\n  return localized.IsEmpty() ? proposed_value : localized;\n}\n\nvoid DateTimeLocalInputType::WarnIfValueIsInvalid(const String& value) const {\n  if (value != GetElement().SanitizeValue(value))\n    AddWarningToConsole(\n        \"The specified value %s does not conform to the required format.  The \"\n        \"format is \\\"yyyy-MM-ddThh:mm\\\" followed by optional \\\":ss\\\" or \"\n        \"\\\":ss.SSS\\\".\",\n        value);\n}\n\nString DateTimeLocalInputType::FormatDateTimeFieldsState(\n    const DateTimeFieldsState& date_time_fields_state) const {\n  if (!date_time_fields_state.HasDayOfMonth() ||\n      !date_time_fields_state.HasMonth() || !date_time_fields_state.HasYear() ||\n      !date_time_fields_state.HasHour() ||\n      !date_time_fields_state.HasMinute() || !date_time_fields_state.HasAMPM())\n    return g_empty_string;\n\n  if (date_time_fields_state.HasMillisecond() &&\n      date_time_fields_state.Millisecond()) {\n    return String::Format(\n        \"%04u-%02u-%02uT%02u:%02u:%02u.%03u\", date_time_fields_state.Year(),\n        date_time_fields_state.Month(), date_time_fields_state.DayOfMonth(),\n        date_time_fields_state.Hour23(), date_time_fields_state.Minute(),\n        date_time_fields_state.HasSecond() ? date_time_fields_state.Second()\n                                           : 0,\n        date_time_fields_state.Millisecond());\n  }\n\n  if (date_time_fields_state.HasSecond() && date_time_fields_state.Second()) {\n    return String::Format(\n        \"%04u-%02u-%02uT%02u:%02u:%02u\", date_time_fields_state.Year(),\n        date_time_fields_state.Month(), date_time_fields_state.DayOfMonth(),\n        date_time_fields_state.Hour23(), date_time_fields_state.Minute(),\n        date_time_fields_state.Second());\n  }\n\n  return String::Format(\n      \"%04u-%02u-%02uT%02u:%02u\", date_time_fields_state.Year(),\n      date_time_fields_state.Month(), date_time_fields_state.DayOfMonth(),\n      date_time_fields_state.Hour23(), date_time_fields_state.Minute());\n}\n\nvoid DateTimeLocalInputType::SetupLayoutParameters(\n    DateTimeEditElement::LayoutParameters& layout_parameters,\n    const DateComponents& date) const {\n  if (ShouldHaveSecondField(date)) {\n    layout_parameters.date_time_format =\n        layout_parameters.locale.DateTimeFormatWithSeconds();\n    layout_parameters.fallback_date_time_format = \"yyyy-MM-dd'T'HH:mm:ss\";\n  } else {\n    layout_parameters.date_time_format =\n        layout_parameters.locale.DateTimeFormatWithoutSeconds();\n    layout_parameters.fallback_date_time_format = \"yyyy-MM-dd'T'HH:mm\";\n  }\n  if (!ParseToDateComponents(GetElement().FastGetAttribute(minAttr),\n                             &layout_parameters.minimum))\n    layout_parameters.minimum = DateComponents();\n  if (!ParseToDateComponents(GetElement().FastGetAttribute(maxAttr),\n                             &layout_parameters.maximum))\n    layout_parameters.maximum = DateComponents();\n  layout_parameters.placeholder_for_day = GetLocale().QueryString(\n      WebLocalizedString::kPlaceholderForDayOfMonthField);\n  layout_parameters.placeholder_for_month =\n      GetLocale().QueryString(WebLocalizedString::kPlaceholderForMonthField);\n  layout_parameters.placeholder_for_year =\n      GetLocale().QueryString(WebLocalizedString::kPlaceholderForYearField);\n}\n\nbool DateTimeLocalInputType::IsValidFormat(bool has_year,\n                                           bool has_month,\n                                           bool has_week,\n                                           bool has_day,\n                                           bool has_ampm,\n                                           bool has_hour,\n                                           bool has_minute,\n                                           bool has_second) const {\n  return has_year && has_month && has_day && has_ampm && has_hour && has_minute;\n}\n\n}  \/\/ namespace blink\n","avg_line_length":41.9141414141,"max_line_length":80,"alphanum_fraction":0.7174358356,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5858,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":5.0,"content":"\r\n\/\/                            Copyright James P. McNellis 2011 - 2013.                            \/\/\r\n\/\/                   Distributed under the Boost Software License, Version 1.0.                   \/\/\r\n\/\/     (See accompanying file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)    \/\/\r\n\r\n#include \"cxxreflect\/windows_runtime\/precompiled_headers.hpp\"\r\n\r\n#ifdef CXXREFLECT_ENABLE_WINDOWS_RUNTIME_INTEGRATION\r\n\r\n#include \"cxxreflect\/windows_runtime\/inspection.hpp\"\r\n#include \"cxxreflect\/windows_runtime\/utility.hpp\"\r\n#include \"cxxreflect\/windows_runtime\/detail\/call_invoker_utility.hpp\"\r\n#include \"cxxreflect\/windows_runtime\/detail\/runtime_utility.hpp\"\r\n\r\n#include <roapi.h>\r\n#include <rometadata.h>\r\n#include <rometadataapi.h>\r\n#include <rometadataresolution.h>\r\n#include <wrl\/client.h>\r\n\r\n#include <windows.applicationModel.h>\r\n#include <windows.foundation.h>\r\n#include <windows.storage.h>\r\n\r\nusing namespace Microsoft::WRL;\r\n\r\nnamespace cxxreflect { namespace windows_runtime { namespace detail { namespace {\r\n\r\n\r\n} } } }\r\n\r\nnamespace cxxreflect { namespace windows_runtime { namespace detail {\r\n\r\n    auto compute_function_pointer(void const* const instance, unsigned const slot) -> void const*\r\n    {\r\n        core::assert_not_null(instance);\r\n\r\n        \/\/ There are two levels of indirection to get to the function pointer:\r\n        \/\/\r\n        \/\/                  object            vtable\r\n        \/\/               +----------+      +----------+\r\n        \/\/ instance ---> | vptr     | ---> | slot 0   |\r\n        \/\/               |~~~~~~~~~~|      | slot 1   |\r\n        \/\/                                 | slot 2   |\r\n        \/\/                                 |~~~~~~~~~~|\r\n        \/\/\r\n        \/\/ This is fundamentally unsafe, so be very careful when calling. :-)\r\n        return (*reinterpret_cast<void const* const* const*>(instance))[slot];\r\n    }\r\n\r\n    auto compute_method_slot_index(reflection::method const& method) -> core::size_type\r\n    {\r\n        core::assert_initialized(method);\r\n\r\n        \/\/ TODO We should really add this as a member function on 'method'.  We can trivially compute\r\n        \/\/ it by determining the index of the method in its element context table.  We should also\r\n        \/\/ only scan declared methods, not all methods.\r\n        reflection::type const type(method.reflected_type());\r\n\r\n        core::size_type slot_index(0);\r\n        for (auto it(begin(type.methods(metadata::binding_attribute::all_instance))); it != end(type.methods()); ++it)\r\n        {\r\n            if (*it == method)\r\n                break;\r\n\r\n            ++slot_index;\r\n        }\r\n\r\n        \/\/ TODO Error checking?\r\n        return slot_index;\r\n    }\r\n\r\n    auto find_matching_interface_method(reflection::method const& runtime_type_method) -> reflection::method\r\n    {\r\n        core::assert_initialized(runtime_type_method);\r\n\r\n        \/\/ TODO Reconsider the way that we find methods originally; it is absurd to go through all\r\n        \/\/ of this work just to re-resolve a method.\r\n\r\n        metadata::binding_flags const flags(\r\n            metadata::binding_attribute::public_ |\r\n            metadata::binding_attribute::instance);\r\n\r\n        reflection::type const runtime_type(runtime_type_method.reflected_type());\r\n        if (runtime_type.is_interface())\r\n            return runtime_type_method;\r\n\r\n        for (auto if_it(begin(runtime_type.interfaces())); if_it != end(runtime_type.interfaces()); ++if_it)\r\n        {\r\n            reflection::type const t(*if_it);\r\n            for (auto method_it(begin(t.methods(flags))); method_it != end(t.methods()); ++method_it)\r\n            {\r\n                \/\/ TODO This does not handle the ImplMap. Do we have to do that for WinRT?\r\n                if (method_it->name() != runtime_type_method.name())\r\n                    continue;\r\n\r\n                if (method_it->return_type() != runtime_type_method.return_type())\r\n                    continue;\r\n\r\n                if (!core::range_checked_equal(\r\n                        begin(method_it->parameters()), end(method_it->parameters()),\r\n                        begin(runtime_type_method.parameters()), end(runtime_type_method.parameters())))\r\n                    continue;\r\n\r\n                return *method_it;\r\n            }\r\n        }\r\n\r\n        return reflection::method();\r\n    }\r\n\r\n    auto get_activation_factory_interface(core::string_reference const& type_full_name,\r\n                                          reflection::guid       const& interface_guid) -> unique_inspectable\r\n    {\r\n        core::assert_true([&]{ return !type_full_name.empty() && interface_guid != reflection::guid::empty; });\r\n\r\n        utility::smart_hstring const type_full_name_hstring(type_full_name.c_str());\r\n\r\n        ComPtr<IInspectable> factory;\r\n        core::hresult const hr(::RoGetActivationFactory(\r\n            type_full_name_hstring.value(),\r\n            to_com_guid(interface_guid),\r\n            reinterpret_cast<void**>(factory.GetAddressOf())));\r\n\r\n        if (FAILED(hr) || factory == nullptr)\r\n            throw core::runtime_error(L\"failed to get requested activation factory interface\");\r\n\r\n        return unique_inspectable(factory.Detach());\r\n    }\r\n\r\n    auto query_interface(IInspectable* const instance, reflection::type const& interface_type) -> unique_inspectable\r\n    {\r\n        core::assert_true([&]{ return instance != nullptr && interface_type.is_interface(); });\r\n\r\n        reflection::guid const interface_guid(get_guid(interface_type));\r\n        \r\n        ComPtr<IInspectable> interface_pointer;\r\n        utility::throw_on_failure(instance->QueryInterface(\r\n            to_com_guid(interface_guid),\r\n            reinterpret_cast<void**>(interface_pointer.GetAddressOf())));\r\n\r\n        return unique_inspectable(interface_pointer.Detach());\r\n    }\r\n\r\n} } }\r\n\r\n#endif \/\/ ENABLE_WINDOWS_RUNTIME_INTEGRATION\r\n","avg_line_length":39.5810810811,"max_line_length":119,"alphanum_fraction":0.6002048481,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":319362,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\ufeff#include \"il2cpp-config.h\"\n\n#ifndef _MSC_VER\n# include <alloca.h>\n#else\n# include <malloc.h>\n#endif\n\n\n#include <cstring>\n#include <string.h>\n#include <stdio.h>\n#include <cmath>\n#include <limits>\n#include <assert.h>\n#include <stdint.h>\n\n#include \"il2cpp-class-internals.h\"\n#include \"codegen\/il2cpp-codegen.h\"\n#include \"il2cpp-object-internals.h\"\n\n\n\/\/ Mono.Security.Protocol.Tls.SslStreamBase\nstruct SslStreamBase_t1667413407;\n\/\/ System.AsyncCallback\nstruct AsyncCallback_t3962456242;\n\/\/ System.Byte[]\nstruct ByteU5BU5D_t4116647657;\n\/\/ System.Char[]\nstruct CharU5BU5D_t3528271667;\n\/\/ System.Collections.ArrayList\nstruct ArrayList_t2718874744;\n\/\/ System.Collections.Generic.Dictionary`2<System.String,System.Int32>\nstruct Dictionary_2_t2736202052;\n\/\/ System.Collections.Generic.IList`1<System.ArraySegment`1<System.Byte>>\nstruct IList_1_t2098880770;\n\/\/ System.Collections.Generic.List`1<System.Net.Cookie>\nstruct List_1_t2465948139;\n\/\/ System.Collections.Hashtable\nstruct Hashtable_t1853889766;\n\/\/ System.Collections.IComparer\nstruct IComparer_t1540313114;\n\/\/ System.Collections.IDictionary\nstruct IDictionary_t1363984059;\n\/\/ System.Collections.IEqualityComparer\nstruct IEqualityComparer_t1493878338;\n\/\/ System.Collections.IHashCodeProvider\nstruct IHashCodeProvider_t267601189;\n\/\/ System.Collections.Queue\nstruct Queue_t3637523393;\n\/\/ System.Collections.Specialized.HybridDictionary\nstruct HybridDictionary_t4070033136;\n\/\/ System.Collections.Specialized.NameObjectCollectionBase\/KeysCollection\nstruct KeysCollection_t1318642398;\n\/\/ System.Collections.Specialized.NameObjectCollectionBase\/_Item\nstruct _Item_t2272350267;\n\/\/ System.ComponentModel.EventHandlerList\nstruct EventHandlerList_t1108123056;\n\/\/ System.ComponentModel.ISite\nstruct ISite_t4006303512;\n\/\/ System.ComponentModel.ListEntry\nstruct ListEntry_t1182276877;\n\/\/ System.Delegate\nstruct Delegate_t1188392813;\n\/\/ System.DelegateData\nstruct DelegateData_t1677132599;\n\/\/ System.EventHandler\nstruct EventHandler_t1348719766;\n\/\/ System.Exception\nstruct Exception_t;\n\/\/ System.IAsyncResult\nstruct IAsyncResult_t767004451;\n\/\/ System.IO.Compression.DeflateStream\nstruct DeflateStream_t4175168077;\n\/\/ System.IO.Compression.DeflateStream\/UnmanagedReadOrWrite\nstruct UnmanagedReadOrWrite_t876388624;\n\/\/ System.IO.FileStream\nstruct FileStream_t4292183065;\n\/\/ System.IO.Stream\nstruct Stream_t1273022909;\n\/\/ System.IO.StreamReader\nstruct StreamReader_t4009935899;\n\/\/ System.Int32[]\nstruct Int32U5BU5D_t385246372;\n\/\/ System.IntPtr[]\nstruct IntPtrU5BU5D_t4013366056;\n\/\/ System.Net.CookieCollection\nstruct CookieCollection_t3881042616;\n\/\/ System.Net.CookieCollection\/CookieCollectionComparer\nstruct CookieCollectionComparer_t1373927847;\n\/\/ System.Net.CookieContainer\nstruct CookieContainer_t2331592909;\n\/\/ System.Net.DigestHeaderParser\nstruct DigestHeaderParser_t341650829;\n\/\/ System.Net.EndPoint\nstruct EndPoint_t982345378;\n\/\/ System.Net.FileWebRequest\nstruct FileWebRequest_t591858885;\n\/\/ System.Net.FileWebResponse\nstruct FileWebResponse_t544571260;\n\/\/ System.Net.FtpAsyncResult\nstruct FtpAsyncResult_t3265664217;\n\/\/ System.Net.FtpWebRequest\nstruct FtpWebRequest_t1577818305;\n\/\/ System.Net.FtpWebResponse\nstruct FtpWebResponse_t3940763575;\n\/\/ System.Net.HttpContinueDelegate\nstruct HttpContinueDelegate_t3009151163;\n\/\/ System.Net.HttpWebResponse\nstruct HttpWebResponse_t3286585418;\n\/\/ System.Net.IAuthenticationModule\nstruct IAuthenticationModule_t3112562943;\n\/\/ System.Net.ICredentialPolicy\nstruct ICredentialPolicy_t1002784953;\n\/\/ System.Net.ICredentials\nstruct ICredentials_t725721261;\n\/\/ System.Net.IPAddress[]\nstruct IPAddressU5BU5D_t596328627;\n\/\/ System.Net.IPEndPoint\nstruct IPEndPoint_t3791887218;\n\/\/ System.Net.IPHostEntry\nstruct IPHostEntry_t263743900;\n\/\/ System.Net.IWebProxy\nstruct IWebProxy_t688979836;\n\/\/ System.Net.NetworkCredential\nstruct NetworkCredential_t3282608323;\n\/\/ System.Net.Security.LocalCertificateSelectionCallback\nstruct LocalCertificateSelectionCallback_t2354453884;\n\/\/ System.Net.Security.RemoteCertificateValidationCallback\nstruct RemoteCertificateValidationCallback_t3014364904;\n\/\/ System.Net.Security.SslStream\nstruct SslStream_t2700741536;\n\/\/ System.Net.ServicePoint\nstruct ServicePoint_t2786966844;\n\/\/ System.Net.Sockets.Socket\nstruct Socket_t1119025450;\n\/\/ System.Net.Sockets.Socket\/SocketAsyncResult\nstruct SocketAsyncResult_t2080034863;\n\/\/ System.Net.WebAsyncResult\nstruct WebAsyncResult_t3421962937;\n\/\/ System.Net.WebConnection\nstruct WebConnection_t3982808322;\n\/\/ System.Net.WebConnectionStream\nstruct WebConnectionStream_t2170064850;\n\/\/ System.Net.WebHeaderCollection\nstruct WebHeaderCollection_t1942268960;\n\/\/ System.Net.WebResponse\nstruct WebResponse_t229922639;\n\/\/ System.Reflection.MethodInfo\nstruct MethodInfo_t;\n\/\/ System.Runtime.Remoting.ServerIdentity\nstruct ServerIdentity_t2342208608;\n\/\/ System.Runtime.Serialization.SerializationInfo\nstruct SerializationInfo_t950877179;\n\/\/ System.Security.Cryptography.HashAlgorithm\nstruct HashAlgorithm_t1432317219;\n\/\/ System.Security.Cryptography.RandomNumberGenerator\nstruct RandomNumberGenerator_t386037858;\n\/\/ System.Security.Cryptography.X509Certificates.X509Certificate\nstruct X509Certificate_t713131622;\n\/\/ System.Security.Cryptography.X509Certificates.X509CertificateCollection\nstruct X509CertificateCollection_t3399372417;\n\/\/ System.String\nstruct String_t;\n\/\/ System.String[]\nstruct StringU5BU5D_t1281789340;\n\/\/ System.Text.StringBuilder\nstruct StringBuilder_t;\n\/\/ System.Threading.AutoResetEvent\nstruct AutoResetEvent_t1333520283;\n\/\/ System.Threading.ManualResetEvent\nstruct ManualResetEvent_t451242010;\n\/\/ System.Threading.Thread\nstruct Thread_t2300836069;\n\/\/ System.Threading.WaitHandle\nstruct WaitHandle_t1743403487;\n\/\/ System.Uri\nstruct Uri_t100236324;\n\/\/ System.Version\nstruct Version_t3456873960;\n\/\/ System.Void\nstruct Void_t1185182177;\n\n\n\n\n#ifndef RUNTIMEOBJECT_H\n#define RUNTIMEOBJECT_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Object\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ RUNTIMEOBJECT_H\n#ifndef ATTRIBUTE_T861562559_H\n#define ATTRIBUTE_T861562559_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Attribute\nstruct  Attribute_t861562559  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ ATTRIBUTE_T861562559_H\n#ifndef NAMEOBJECTCOLLECTIONBASE_T2091847364_H\n#define NAMEOBJECTCOLLECTIONBASE_T2091847364_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Collections.Specialized.NameObjectCollectionBase\nstruct  NameObjectCollectionBase_t2091847364  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Collections.Hashtable System.Collections.Specialized.NameObjectCollectionBase::m_ItemsContainer\n\tHashtable_t1853889766 * ___m_ItemsContainer_0;\n\t\/\/ System.Collections.Specialized.NameObjectCollectionBase\/_Item System.Collections.Specialized.NameObjectCollectionBase::m_NullKeyItem\n\t_Item_t2272350267 * ___m_NullKeyItem_1;\n\t\/\/ System.Collections.ArrayList System.Collections.Specialized.NameObjectCollectionBase::m_ItemsArray\n\tArrayList_t2718874744 * ___m_ItemsArray_2;\n\t\/\/ System.Collections.IHashCodeProvider System.Collections.Specialized.NameObjectCollectionBase::m_hashprovider\n\tRuntimeObject* ___m_hashprovider_3;\n\t\/\/ System.Collections.IComparer System.Collections.Specialized.NameObjectCollectionBase::m_comparer\n\tRuntimeObject* ___m_comparer_4;\n\t\/\/ System.Int32 System.Collections.Specialized.NameObjectCollectionBase::m_defCapacity\n\tint32_t ___m_defCapacity_5;\n\t\/\/ System.Boolean System.Collections.Specialized.NameObjectCollectionBase::m_readonly\n\tbool ___m_readonly_6;\n\t\/\/ System.Runtime.Serialization.SerializationInfo System.Collections.Specialized.NameObjectCollectionBase::infoCopy\n\tSerializationInfo_t950877179 * ___infoCopy_7;\n\t\/\/ System.Collections.Specialized.NameObjectCollectionBase\/KeysCollection System.Collections.Specialized.NameObjectCollectionBase::keyscoll\n\tKeysCollection_t1318642398 * ___keyscoll_8;\n\t\/\/ System.Collections.IEqualityComparer System.Collections.Specialized.NameObjectCollectionBase::equality_comparer\n\tRuntimeObject* ___equality_comparer_9;\n\npublic:\n\tinline static int32_t get_offset_of_m_ItemsContainer_0() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ___m_ItemsContainer_0)); }\n\tinline Hashtable_t1853889766 * get_m_ItemsContainer_0() const { return ___m_ItemsContainer_0; }\n\tinline Hashtable_t1853889766 ** get_address_of_m_ItemsContainer_0() { return &___m_ItemsContainer_0; }\n\tinline void set_m_ItemsContainer_0(Hashtable_t1853889766 * value)\n\t{\n\t\t___m_ItemsContainer_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_ItemsContainer_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_m_NullKeyItem_1() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ___m_NullKeyItem_1)); }\n\tinline _Item_t2272350267 * get_m_NullKeyItem_1() const { return ___m_NullKeyItem_1; }\n\tinline _Item_t2272350267 ** get_address_of_m_NullKeyItem_1() { return &___m_NullKeyItem_1; }\n\tinline void set_m_NullKeyItem_1(_Item_t2272350267 * value)\n\t{\n\t\t___m_NullKeyItem_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_NullKeyItem_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_m_ItemsArray_2() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ___m_ItemsArray_2)); }\n\tinline ArrayList_t2718874744 * get_m_ItemsArray_2() const { return ___m_ItemsArray_2; }\n\tinline ArrayList_t2718874744 ** get_address_of_m_ItemsArray_2() { return &___m_ItemsArray_2; }\n\tinline void set_m_ItemsArray_2(ArrayList_t2718874744 * value)\n\t{\n\t\t___m_ItemsArray_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_ItemsArray_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_m_hashprovider_3() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ___m_hashprovider_3)); }\n\tinline RuntimeObject* get_m_hashprovider_3() const { return ___m_hashprovider_3; }\n\tinline RuntimeObject** get_address_of_m_hashprovider_3() { return &___m_hashprovider_3; }\n\tinline void set_m_hashprovider_3(RuntimeObject* value)\n\t{\n\t\t___m_hashprovider_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_hashprovider_3), value);\n\t}\n\n\tinline static int32_t get_offset_of_m_comparer_4() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ___m_comparer_4)); }\n\tinline RuntimeObject* get_m_comparer_4() const { return ___m_comparer_4; }\n\tinline RuntimeObject** get_address_of_m_comparer_4() { return &___m_comparer_4; }\n\tinline void set_m_comparer_4(RuntimeObject* value)\n\t{\n\t\t___m_comparer_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_comparer_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_m_defCapacity_5() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ___m_defCapacity_5)); }\n\tinline int32_t get_m_defCapacity_5() const { return ___m_defCapacity_5; }\n\tinline int32_t* get_address_of_m_defCapacity_5() { return &___m_defCapacity_5; }\n\tinline void set_m_defCapacity_5(int32_t value)\n\t{\n\t\t___m_defCapacity_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of_m_readonly_6() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ___m_readonly_6)); }\n\tinline bool get_m_readonly_6() const { return ___m_readonly_6; }\n\tinline bool* get_address_of_m_readonly_6() { return &___m_readonly_6; }\n\tinline void set_m_readonly_6(bool value)\n\t{\n\t\t___m_readonly_6 = value;\n\t}\n\n\tinline static int32_t get_offset_of_infoCopy_7() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ___infoCopy_7)); }\n\tinline SerializationInfo_t950877179 * get_infoCopy_7() const { return ___infoCopy_7; }\n\tinline SerializationInfo_t950877179 ** get_address_of_infoCopy_7() { return &___infoCopy_7; }\n\tinline void set_infoCopy_7(SerializationInfo_t950877179 * value)\n\t{\n\t\t___infoCopy_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___infoCopy_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_keyscoll_8() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ___keyscoll_8)); }\n\tinline KeysCollection_t1318642398 * get_keyscoll_8() const { return ___keyscoll_8; }\n\tinline KeysCollection_t1318642398 ** get_address_of_keyscoll_8() { return &___keyscoll_8; }\n\tinline void set_keyscoll_8(KeysCollection_t1318642398 * value)\n\t{\n\t\t___keyscoll_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___keyscoll_8), value);\n\t}\n\n\tinline static int32_t get_offset_of_equality_comparer_9() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ___equality_comparer_9)); }\n\tinline RuntimeObject* get_equality_comparer_9() const { return ___equality_comparer_9; }\n\tinline RuntimeObject** get_address_of_equality_comparer_9() { return &___equality_comparer_9; }\n\tinline void set_equality_comparer_9(RuntimeObject* value)\n\t{\n\t\t___equality_comparer_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___equality_comparer_9), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ NAMEOBJECTCOLLECTIONBASE_T2091847364_H\n#ifndef EVENTHANDLERLIST_T1108123056_H\n#define EVENTHANDLERLIST_T1108123056_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.EventHandlerList\nstruct  EventHandlerList_t1108123056  : public RuntimeObject\n{\npublic:\n\t\/\/ System.ComponentModel.ListEntry System.ComponentModel.EventHandlerList::entries\n\tListEntry_t1182276877 * ___entries_0;\n\t\/\/ System.Delegate System.ComponentModel.EventHandlerList::null_entry\n\tDelegate_t1188392813 * ___null_entry_1;\n\npublic:\n\tinline static int32_t get_offset_of_entries_0() { return static_cast<int32_t>(offsetof(EventHandlerList_t1108123056, ___entries_0)); }\n\tinline ListEntry_t1182276877 * get_entries_0() const { return ___entries_0; }\n\tinline ListEntry_t1182276877 ** get_address_of_entries_0() { return &___entries_0; }\n\tinline void set_entries_0(ListEntry_t1182276877 * value)\n\t{\n\t\t___entries_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___entries_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_null_entry_1() { return static_cast<int32_t>(offsetof(EventHandlerList_t1108123056, ___null_entry_1)); }\n\tinline Delegate_t1188392813 * get_null_entry_1() const { return ___null_entry_1; }\n\tinline Delegate_t1188392813 ** get_address_of_null_entry_1() { return &___null_entry_1; }\n\tinline void set_null_entry_1(Delegate_t1188392813 * value)\n\t{\n\t\t___null_entry_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___null_entry_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ EVENTHANDLERLIST_T1108123056_H\n#ifndef LISTENTRY_T1182276877_H\n#define LISTENTRY_T1182276877_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.ListEntry\nstruct  ListEntry_t1182276877  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Object System.ComponentModel.ListEntry::key\n\tRuntimeObject * ___key_0;\n\t\/\/ System.Delegate System.ComponentModel.ListEntry::value\n\tDelegate_t1188392813 * ___value_1;\n\t\/\/ System.ComponentModel.ListEntry System.ComponentModel.ListEntry::next\n\tListEntry_t1182276877 * ___next_2;\n\npublic:\n\tinline static int32_t get_offset_of_key_0() { return static_cast<int32_t>(offsetof(ListEntry_t1182276877, ___key_0)); }\n\tinline RuntimeObject * get_key_0() const { return ___key_0; }\n\tinline RuntimeObject ** get_address_of_key_0() { return &___key_0; }\n\tinline void set_key_0(RuntimeObject * value)\n\t{\n\t\t___key_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___key_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(ListEntry_t1182276877, ___value_1)); }\n\tinline Delegate_t1188392813 * get_value_1() const { return ___value_1; }\n\tinline Delegate_t1188392813 ** get_address_of_value_1() { return &___value_1; }\n\tinline void set_value_1(Delegate_t1188392813 * value)\n\t{\n\t\t___value_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___value_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_next_2() { return static_cast<int32_t>(offsetof(ListEntry_t1182276877, ___next_2)); }\n\tinline ListEntry_t1182276877 * get_next_2() const { return ___next_2; }\n\tinline ListEntry_t1182276877 ** get_address_of_next_2() { return &___next_2; }\n\tinline void set_next_2(ListEntry_t1182276877 * value)\n\t{\n\t\t___next_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___next_2), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ LISTENTRY_T1182276877_H\n#ifndef TYPECONVERTER_T2249118273_H\n#define TYPECONVERTER_T2249118273_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.TypeConverter\nstruct  TypeConverter_t2249118273  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ TYPECONVERTER_T2249118273_H\n#ifndef EVENTARGS_T3591816995_H\n#define EVENTARGS_T3591816995_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.EventArgs\nstruct  EventArgs_t3591816995  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\nstruct EventArgs_t3591816995_StaticFields\n{\npublic:\n\t\/\/ System.EventArgs System.EventArgs::Empty\n\tEventArgs_t3591816995 * ___Empty_0;\n\npublic:\n\tinline static int32_t get_offset_of_Empty_0() { return static_cast<int32_t>(offsetof(EventArgs_t3591816995_StaticFields, ___Empty_0)); }\n\tinline EventArgs_t3591816995 * get_Empty_0() const { return ___Empty_0; }\n\tinline EventArgs_t3591816995 ** get_address_of_Empty_0() { return &___Empty_0; }\n\tinline void set_Empty_0(EventArgs_t3591816995 * value)\n\t{\n\t\t___Empty_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Empty_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ EVENTARGS_T3591816995_H\n#ifndef EXCEPTION_T_H\n#define EXCEPTION_T_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Exception\nstruct  Exception_t  : public RuntimeObject\n{\npublic:\n\t\/\/ System.IntPtr[] System.Exception::trace_ips\n\tIntPtrU5BU5D_t4013366056* ___trace_ips_0;\n\t\/\/ System.Exception System.Exception::inner_exception\n\tException_t * ___inner_exception_1;\n\t\/\/ System.String System.Exception::message\n\tString_t* ___message_2;\n\t\/\/ System.String System.Exception::help_link\n\tString_t* ___help_link_3;\n\t\/\/ System.String System.Exception::class_name\n\tString_t* ___class_name_4;\n\t\/\/ System.String System.Exception::stack_trace\n\tString_t* ___stack_trace_5;\n\t\/\/ System.String System.Exception::_remoteStackTraceString\n\tString_t* ____remoteStackTraceString_6;\n\t\/\/ System.Int32 System.Exception::remote_stack_index\n\tint32_t ___remote_stack_index_7;\n\t\/\/ System.Int32 System.Exception::hresult\n\tint32_t ___hresult_8;\n\t\/\/ System.String System.Exception::source\n\tString_t* ___source_9;\n\t\/\/ System.Collections.IDictionary System.Exception::_data\n\tRuntimeObject* ____data_10;\n\npublic:\n\tinline static int32_t get_offset_of_trace_ips_0() { return static_cast<int32_t>(offsetof(Exception_t, ___trace_ips_0)); }\n\tinline IntPtrU5BU5D_t4013366056* get_trace_ips_0() const { return ___trace_ips_0; }\n\tinline IntPtrU5BU5D_t4013366056** get_address_of_trace_ips_0() { return &___trace_ips_0; }\n\tinline void set_trace_ips_0(IntPtrU5BU5D_t4013366056* value)\n\t{\n\t\t___trace_ips_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___trace_ips_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_inner_exception_1() { return static_cast<int32_t>(offsetof(Exception_t, ___inner_exception_1)); }\n\tinline Exception_t * get_inner_exception_1() const { return ___inner_exception_1; }\n\tinline Exception_t ** get_address_of_inner_exception_1() { return &___inner_exception_1; }\n\tinline void set_inner_exception_1(Exception_t * value)\n\t{\n\t\t___inner_exception_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___inner_exception_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_message_2() { return static_cast<int32_t>(offsetof(Exception_t, ___message_2)); }\n\tinline String_t* get_message_2() const { return ___message_2; }\n\tinline String_t** get_address_of_message_2() { return &___message_2; }\n\tinline void set_message_2(String_t* value)\n\t{\n\t\t___message_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___message_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_help_link_3() { return static_cast<int32_t>(offsetof(Exception_t, ___help_link_3)); }\n\tinline String_t* get_help_link_3() const { return ___help_link_3; }\n\tinline String_t** get_address_of_help_link_3() { return &___help_link_3; }\n\tinline void set_help_link_3(String_t* value)\n\t{\n\t\t___help_link_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___help_link_3), value);\n\t}\n\n\tinline static int32_t get_offset_of_class_name_4() { return static_cast<int32_t>(offsetof(Exception_t, ___class_name_4)); }\n\tinline String_t* get_class_name_4() const { return ___class_name_4; }\n\tinline String_t** get_address_of_class_name_4() { return &___class_name_4; }\n\tinline void set_class_name_4(String_t* value)\n\t{\n\t\t___class_name_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___class_name_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_stack_trace_5() { return static_cast<int32_t>(offsetof(Exception_t, ___stack_trace_5)); }\n\tinline String_t* get_stack_trace_5() const { return ___stack_trace_5; }\n\tinline String_t** get_address_of_stack_trace_5() { return &___stack_trace_5; }\n\tinline void set_stack_trace_5(String_t* value)\n\t{\n\t\t___stack_trace_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___stack_trace_5), value);\n\t}\n\n\tinline static int32_t get_offset_of__remoteStackTraceString_6() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackTraceString_6)); }\n\tinline String_t* get__remoteStackTraceString_6() const { return ____remoteStackTraceString_6; }\n\tinline String_t** get_address_of__remoteStackTraceString_6() { return &____remoteStackTraceString_6; }\n\tinline void set__remoteStackTraceString_6(String_t* value)\n\t{\n\t\t____remoteStackTraceString_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____remoteStackTraceString_6), value);\n\t}\n\n\tinline static int32_t get_offset_of_remote_stack_index_7() { return static_cast<int32_t>(offsetof(Exception_t, ___remote_stack_index_7)); }\n\tinline int32_t get_remote_stack_index_7() const { return ___remote_stack_index_7; }\n\tinline int32_t* get_address_of_remote_stack_index_7() { return &___remote_stack_index_7; }\n\tinline void set_remote_stack_index_7(int32_t value)\n\t{\n\t\t___remote_stack_index_7 = value;\n\t}\n\n\tinline static int32_t get_offset_of_hresult_8() { return static_cast<int32_t>(offsetof(Exception_t, ___hresult_8)); }\n\tinline int32_t get_hresult_8() const { return ___hresult_8; }\n\tinline int32_t* get_address_of_hresult_8() { return &___hresult_8; }\n\tinline void set_hresult_8(int32_t value)\n\t{\n\t\t___hresult_8 = value;\n\t}\n\n\tinline static int32_t get_offset_of_source_9() { return static_cast<int32_t>(offsetof(Exception_t, ___source_9)); }\n\tinline String_t* get_source_9() const { return ___source_9; }\n\tinline String_t** get_address_of_source_9() { return &___source_9; }\n\tinline void set_source_9(String_t* value)\n\t{\n\t\t___source_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___source_9), value);\n\t}\n\n\tinline static int32_t get_offset_of__data_10() { return static_cast<int32_t>(offsetof(Exception_t, ____data_10)); }\n\tinline RuntimeObject* get__data_10() const { return ____data_10; }\n\tinline RuntimeObject** get_address_of__data_10() { return &____data_10; }\n\tinline void set__data_10(RuntimeObject* value)\n\t{\n\t\t____data_10 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____data_10), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ EXCEPTION_T_H\n#ifndef STREAM_T1273022909_H\n#define STREAM_T1273022909_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.IO.Stream\nstruct  Stream_t1273022909  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\nstruct Stream_t1273022909_StaticFields\n{\npublic:\n\t\/\/ System.IO.Stream System.IO.Stream::Null\n\tStream_t1273022909 * ___Null_0;\n\npublic:\n\tinline static int32_t get_offset_of_Null_0() { return static_cast<int32_t>(offsetof(Stream_t1273022909_StaticFields, ___Null_0)); }\n\tinline Stream_t1273022909 * get_Null_0() const { return ___Null_0; }\n\tinline Stream_t1273022909 ** get_address_of_Null_0() { return &___Null_0; }\n\tinline void set_Null_0(Stream_t1273022909 * value)\n\t{\n\t\t___Null_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Null_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ STREAM_T1273022909_H\n#ifndef MARSHALBYREFOBJECT_T2760389100_H\n#define MARSHALBYREFOBJECT_T2760389100_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.MarshalByRefObject\nstruct  MarshalByRefObject_t2760389100  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Runtime.Remoting.ServerIdentity System.MarshalByRefObject::_identity\n\tServerIdentity_t2342208608 * ____identity_0;\n\npublic:\n\tinline static int32_t get_offset_of__identity_0() { return static_cast<int32_t>(offsetof(MarshalByRefObject_t2760389100, ____identity_0)); }\n\tinline ServerIdentity_t2342208608 * get__identity_0() const { return ____identity_0; }\n\tinline ServerIdentity_t2342208608 ** get_address_of__identity_0() { return &____identity_0; }\n\tinline void set__identity_0(ServerIdentity_t2342208608 * value)\n\t{\n\t\t____identity_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____identity_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ MARSHALBYREFOBJECT_T2760389100_H\n#ifndef AUTHENTICATIONMANAGER_T2084001809_H\n#define AUTHENTICATIONMANAGER_T2084001809_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.AuthenticationManager\nstruct  AuthenticationManager_t2084001809  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\nstruct AuthenticationManager_t2084001809_StaticFields\n{\npublic:\n\t\/\/ System.Collections.ArrayList System.Net.AuthenticationManager::modules\n\tArrayList_t2718874744 * ___modules_0;\n\t\/\/ System.Object System.Net.AuthenticationManager::locker\n\tRuntimeObject * ___locker_1;\n\t\/\/ System.Net.ICredentialPolicy System.Net.AuthenticationManager::credential_policy\n\tRuntimeObject* ___credential_policy_2;\n\npublic:\n\tinline static int32_t get_offset_of_modules_0() { return static_cast<int32_t>(offsetof(AuthenticationManager_t2084001809_StaticFields, ___modules_0)); }\n\tinline ArrayList_t2718874744 * get_modules_0() const { return ___modules_0; }\n\tinline ArrayList_t2718874744 ** get_address_of_modules_0() { return &___modules_0; }\n\tinline void set_modules_0(ArrayList_t2718874744 * value)\n\t{\n\t\t___modules_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___modules_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_locker_1() { return static_cast<int32_t>(offsetof(AuthenticationManager_t2084001809_StaticFields, ___locker_1)); }\n\tinline RuntimeObject * get_locker_1() const { return ___locker_1; }\n\tinline RuntimeObject ** get_address_of_locker_1() { return &___locker_1; }\n\tinline void set_locker_1(RuntimeObject * value)\n\t{\n\t\t___locker_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___locker_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_credential_policy_2() { return static_cast<int32_t>(offsetof(AuthenticationManager_t2084001809_StaticFields, ___credential_policy_2)); }\n\tinline RuntimeObject* get_credential_policy_2() const { return ___credential_policy_2; }\n\tinline RuntimeObject** get_address_of_credential_policy_2() { return &___credential_policy_2; }\n\tinline void set_credential_policy_2(RuntimeObject* value)\n\t{\n\t\t___credential_policy_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___credential_policy_2), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ AUTHENTICATIONMANAGER_T2084001809_H\n#ifndef AUTHORIZATION_T542416582_H\n#define AUTHORIZATION_T542416582_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Authorization\nstruct  Authorization_t542416582  : public RuntimeObject\n{\npublic:\n\t\/\/ System.String System.Net.Authorization::token\n\tString_t* ___token_0;\n\t\/\/ System.Boolean System.Net.Authorization::complete\n\tbool ___complete_1;\n\t\/\/ System.String System.Net.Authorization::connectionGroupId\n\tString_t* ___connectionGroupId_2;\n\t\/\/ System.Net.IAuthenticationModule System.Net.Authorization::module\n\tRuntimeObject* ___module_3;\n\npublic:\n\tinline static int32_t get_offset_of_token_0() { return static_cast<int32_t>(offsetof(Authorization_t542416582, ___token_0)); }\n\tinline String_t* get_token_0() const { return ___token_0; }\n\tinline String_t** get_address_of_token_0() { return &___token_0; }\n\tinline void set_token_0(String_t* value)\n\t{\n\t\t___token_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___token_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_complete_1() { return static_cast<int32_t>(offsetof(Authorization_t542416582, ___complete_1)); }\n\tinline bool get_complete_1() const { return ___complete_1; }\n\tinline bool* get_address_of_complete_1() { return &___complete_1; }\n\tinline void set_complete_1(bool value)\n\t{\n\t\t___complete_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_connectionGroupId_2() { return static_cast<int32_t>(offsetof(Authorization_t542416582, ___connectionGroupId_2)); }\n\tinline String_t* get_connectionGroupId_2() const { return ___connectionGroupId_2; }\n\tinline String_t** get_address_of_connectionGroupId_2() { return &___connectionGroupId_2; }\n\tinline void set_connectionGroupId_2(String_t* value)\n\t{\n\t\t___connectionGroupId_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___connectionGroupId_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_module_3() { return static_cast<int32_t>(offsetof(Authorization_t542416582, ___module_3)); }\n\tinline RuntimeObject* get_module_3() const { return ___module_3; }\n\tinline RuntimeObject** get_address_of_module_3() { return &___module_3; }\n\tinline void set_module_3(RuntimeObject* value)\n\t{\n\t\t___module_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___module_3), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ AUTHORIZATION_T542416582_H\n#ifndef BASICCLIENT_T3463561396_H\n#define BASICCLIENT_T3463561396_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.BasicClient\nstruct  BasicClient_t3463561396  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ BASICCLIENT_T3463561396_H\n#ifndef CHUNK_T1455545707_H\n#define CHUNK_T1455545707_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.ChunkStream\/Chunk\nstruct  Chunk_t1455545707  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Byte[] System.Net.ChunkStream\/Chunk::Bytes\n\tByteU5BU5D_t4116647657* ___Bytes_0;\n\t\/\/ System.Int32 System.Net.ChunkStream\/Chunk::Offset\n\tint32_t ___Offset_1;\n\npublic:\n\tinline static int32_t get_offset_of_Bytes_0() { return static_cast<int32_t>(offsetof(Chunk_t1455545707, ___Bytes_0)); }\n\tinline ByteU5BU5D_t4116647657* get_Bytes_0() const { return ___Bytes_0; }\n\tinline ByteU5BU5D_t4116647657** get_address_of_Bytes_0() { return &___Bytes_0; }\n\tinline void set_Bytes_0(ByteU5BU5D_t4116647657* value)\n\t{\n\t\t___Bytes_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Bytes_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_Offset_1() { return static_cast<int32_t>(offsetof(Chunk_t1455545707, ___Offset_1)); }\n\tinline int32_t get_Offset_1() const { return ___Offset_1; }\n\tinline int32_t* get_address_of_Offset_1() { return &___Offset_1; }\n\tinline void set_Offset_1(int32_t value)\n\t{\n\t\t___Offset_1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CHUNK_T1455545707_H\n#ifndef COOKIECOLLECTION_T3881042616_H\n#define COOKIECOLLECTION_T3881042616_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.CookieCollection\nstruct  CookieCollection_t3881042616  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Collections.Generic.List`1<System.Net.Cookie> System.Net.CookieCollection::list\n\tList_1_t2465948139 * ___list_0;\n\npublic:\n\tinline static int32_t get_offset_of_list_0() { return static_cast<int32_t>(offsetof(CookieCollection_t3881042616, ___list_0)); }\n\tinline List_1_t2465948139 * get_list_0() const { return ___list_0; }\n\tinline List_1_t2465948139 ** get_address_of_list_0() { return &___list_0; }\n\tinline void set_list_0(List_1_t2465948139 * value)\n\t{\n\t\t___list_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___list_0), value);\n\t}\n};\n\nstruct CookieCollection_t3881042616_StaticFields\n{\npublic:\n\t\/\/ System.Net.CookieCollection\/CookieCollectionComparer System.Net.CookieCollection::Comparer\n\tCookieCollectionComparer_t1373927847 * ___Comparer_1;\n\npublic:\n\tinline static int32_t get_offset_of_Comparer_1() { return static_cast<int32_t>(offsetof(CookieCollection_t3881042616_StaticFields, ___Comparer_1)); }\n\tinline CookieCollectionComparer_t1373927847 * get_Comparer_1() const { return ___Comparer_1; }\n\tinline CookieCollectionComparer_t1373927847 ** get_address_of_Comparer_1() { return &___Comparer_1; }\n\tinline void set_Comparer_1(CookieCollectionComparer_t1373927847 * value)\n\t{\n\t\t___Comparer_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Comparer_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ COOKIECOLLECTION_T3881042616_H\n#ifndef COOKIECOLLECTIONCOMPARER_T1373927847_H\n#define COOKIECOLLECTIONCOMPARER_T1373927847_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.CookieCollection\/CookieCollectionComparer\nstruct  CookieCollectionComparer_t1373927847  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ COOKIECOLLECTIONCOMPARER_T1373927847_H\n#ifndef COOKIECONTAINER_T2331592909_H\n#define COOKIECONTAINER_T2331592909_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.CookieContainer\nstruct  CookieContainer_t2331592909  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Int32 System.Net.CookieContainer::capacity\n\tint32_t ___capacity_0;\n\t\/\/ System.Int32 System.Net.CookieContainer::perDomainCapacity\n\tint32_t ___perDomainCapacity_1;\n\t\/\/ System.Int32 System.Net.CookieContainer::maxCookieSize\n\tint32_t ___maxCookieSize_2;\n\t\/\/ System.Net.CookieCollection System.Net.CookieContainer::cookies\n\tCookieCollection_t3881042616 * ___cookies_3;\n\npublic:\n\tinline static int32_t get_offset_of_capacity_0() { return static_cast<int32_t>(offsetof(CookieContainer_t2331592909, ___capacity_0)); }\n\tinline int32_t get_capacity_0() const { return ___capacity_0; }\n\tinline int32_t* get_address_of_capacity_0() { return &___capacity_0; }\n\tinline void set_capacity_0(int32_t value)\n\t{\n\t\t___capacity_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_perDomainCapacity_1() { return static_cast<int32_t>(offsetof(CookieContainer_t2331592909, ___perDomainCapacity_1)); }\n\tinline int32_t get_perDomainCapacity_1() const { return ___perDomainCapacity_1; }\n\tinline int32_t* get_address_of_perDomainCapacity_1() { return &___perDomainCapacity_1; }\n\tinline void set_perDomainCapacity_1(int32_t value)\n\t{\n\t\t___perDomainCapacity_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_maxCookieSize_2() { return static_cast<int32_t>(offsetof(CookieContainer_t2331592909, ___maxCookieSize_2)); }\n\tinline int32_t get_maxCookieSize_2() const { return ___maxCookieSize_2; }\n\tinline int32_t* get_address_of_maxCookieSize_2() { return &___maxCookieSize_2; }\n\tinline void set_maxCookieSize_2(int32_t value)\n\t{\n\t\t___maxCookieSize_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_cookies_3() { return static_cast<int32_t>(offsetof(CookieContainer_t2331592909, ___cookies_3)); }\n\tinline CookieCollection_t3881042616 * get_cookies_3() const { return ___cookies_3; }\n\tinline CookieCollection_t3881042616 ** get_address_of_cookies_3() { return &___cookies_3; }\n\tinline void set_cookies_3(CookieCollection_t3881042616 * value)\n\t{\n\t\t___cookies_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___cookies_3), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ COOKIECONTAINER_T2331592909_H\n#ifndef COOKIEPARSER_T2349142305_H\n#define COOKIEPARSER_T2349142305_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.CookieParser\nstruct  CookieParser_t2349142305  : public RuntimeObject\n{\npublic:\n\t\/\/ System.String System.Net.CookieParser::header\n\tString_t* ___header_0;\n\t\/\/ System.Int32 System.Net.CookieParser::pos\n\tint32_t ___pos_1;\n\t\/\/ System.Int32 System.Net.CookieParser::length\n\tint32_t ___length_2;\n\npublic:\n\tinline static int32_t get_offset_of_header_0() { return static_cast<int32_t>(offsetof(CookieParser_t2349142305, ___header_0)); }\n\tinline String_t* get_header_0() const { return ___header_0; }\n\tinline String_t** get_address_of_header_0() { return &___header_0; }\n\tinline void set_header_0(String_t* value)\n\t{\n\t\t___header_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___header_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_pos_1() { return static_cast<int32_t>(offsetof(CookieParser_t2349142305, ___pos_1)); }\n\tinline int32_t get_pos_1() const { return ___pos_1; }\n\tinline int32_t* get_address_of_pos_1() { return &___pos_1; }\n\tinline void set_pos_1(int32_t value)\n\t{\n\t\t___pos_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_length_2() { return static_cast<int32_t>(offsetof(CookieParser_t2349142305, ___length_2)); }\n\tinline int32_t get_length_2() const { return ___length_2; }\n\tinline int32_t* get_address_of_length_2() { return &___length_2; }\n\tinline void set_length_2(int32_t value)\n\t{\n\t\t___length_2 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ COOKIEPARSER_T2349142305_H\n#ifndef DEFAULTCERTIFICATEPOLICY_T3607119947_H\n#define DEFAULTCERTIFICATEPOLICY_T3607119947_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.DefaultCertificatePolicy\nstruct  DefaultCertificatePolicy_t3607119947  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DEFAULTCERTIFICATEPOLICY_T3607119947_H\n#ifndef DIGESTCLIENT_T660790528_H\n#define DIGESTCLIENT_T660790528_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.DigestClient\nstruct  DigestClient_t660790528  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\nstruct DigestClient_t660790528_StaticFields\n{\npublic:\n\t\/\/ System.Collections.Hashtable System.Net.DigestClient::cache\n\tHashtable_t1853889766 * ___cache_0;\n\npublic:\n\tinline static int32_t get_offset_of_cache_0() { return static_cast<int32_t>(offsetof(DigestClient_t660790528_StaticFields, ___cache_0)); }\n\tinline Hashtable_t1853889766 * get_cache_0() const { return ___cache_0; }\n\tinline Hashtable_t1853889766 ** get_address_of_cache_0() { return &___cache_0; }\n\tinline void set_cache_0(Hashtable_t1853889766 * value)\n\t{\n\t\t___cache_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___cache_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DIGESTCLIENT_T660790528_H\n#ifndef DIGESTHEADERPARSER_T341650829_H\n#define DIGESTHEADERPARSER_T341650829_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.DigestHeaderParser\nstruct  DigestHeaderParser_t341650829  : public RuntimeObject\n{\npublic:\n\t\/\/ System.String System.Net.DigestHeaderParser::header\n\tString_t* ___header_0;\n\t\/\/ System.Int32 System.Net.DigestHeaderParser::length\n\tint32_t ___length_1;\n\t\/\/ System.Int32 System.Net.DigestHeaderParser::pos\n\tint32_t ___pos_2;\n\t\/\/ System.String[] System.Net.DigestHeaderParser::values\n\tStringU5BU5D_t1281789340* ___values_4;\n\npublic:\n\tinline static int32_t get_offset_of_header_0() { return static_cast<int32_t>(offsetof(DigestHeaderParser_t341650829, ___header_0)); }\n\tinline String_t* get_header_0() const { return ___header_0; }\n\tinline String_t** get_address_of_header_0() { return &___header_0; }\n\tinline void set_header_0(String_t* value)\n\t{\n\t\t___header_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___header_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_length_1() { return static_cast<int32_t>(offsetof(DigestHeaderParser_t341650829, ___length_1)); }\n\tinline int32_t get_length_1() const { return ___length_1; }\n\tinline int32_t* get_address_of_length_1() { return &___length_1; }\n\tinline void set_length_1(int32_t value)\n\t{\n\t\t___length_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_pos_2() { return static_cast<int32_t>(offsetof(DigestHeaderParser_t341650829, ___pos_2)); }\n\tinline int32_t get_pos_2() const { return ___pos_2; }\n\tinline int32_t* get_address_of_pos_2() { return &___pos_2; }\n\tinline void set_pos_2(int32_t value)\n\t{\n\t\t___pos_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_values_4() { return static_cast<int32_t>(offsetof(DigestHeaderParser_t341650829, ___values_4)); }\n\tinline StringU5BU5D_t1281789340* get_values_4() const { return ___values_4; }\n\tinline StringU5BU5D_t1281789340** get_address_of_values_4() { return &___values_4; }\n\tinline void set_values_4(StringU5BU5D_t1281789340* value)\n\t{\n\t\t___values_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___values_4), value);\n\t}\n};\n\nstruct DigestHeaderParser_t341650829_StaticFields\n{\npublic:\n\t\/\/ System.String[] System.Net.DigestHeaderParser::keywords\n\tStringU5BU5D_t1281789340* ___keywords_3;\n\npublic:\n\tinline static int32_t get_offset_of_keywords_3() { return static_cast<int32_t>(offsetof(DigestHeaderParser_t341650829_StaticFields, ___keywords_3)); }\n\tinline StringU5BU5D_t1281789340* get_keywords_3() const { return ___keywords_3; }\n\tinline StringU5BU5D_t1281789340** get_address_of_keywords_3() { return &___keywords_3; }\n\tinline void set_keywords_3(StringU5BU5D_t1281789340* value)\n\t{\n\t\t___keywords_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___keywords_3), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DIGESTHEADERPARSER_T341650829_H\n#ifndef DNS_T384099571_H\n#define DNS_T384099571_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Dns\nstruct  Dns_t384099571  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DNS_T384099571_H\n#ifndef ENDPOINT_T982345378_H\n#define ENDPOINT_T982345378_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.EndPoint\nstruct  EndPoint_t982345378  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ ENDPOINT_T982345378_H\n#ifndef FILEWEBREQUESTCREATOR_T1781329382_H\n#define FILEWEBREQUESTCREATOR_T1781329382_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FileWebRequestCreator\nstruct  FileWebRequestCreator_t1781329382  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FILEWEBREQUESTCREATOR_T1781329382_H\n#ifndef FTPASYNCRESULT_T3265664217_H\n#define FTPASYNCRESULT_T3265664217_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FtpAsyncResult\nstruct  FtpAsyncResult_t3265664217  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Net.FtpWebResponse System.Net.FtpAsyncResult::response\n\tFtpWebResponse_t3940763575 * ___response_0;\n\t\/\/ System.Threading.ManualResetEvent System.Net.FtpAsyncResult::waitHandle\n\tManualResetEvent_t451242010 * ___waitHandle_1;\n\t\/\/ System.Exception System.Net.FtpAsyncResult::exception\n\tException_t * ___exception_2;\n\t\/\/ System.AsyncCallback System.Net.FtpAsyncResult::callback\n\tAsyncCallback_t3962456242 * ___callback_3;\n\t\/\/ System.IO.Stream System.Net.FtpAsyncResult::stream\n\tStream_t1273022909 * ___stream_4;\n\t\/\/ System.Object System.Net.FtpAsyncResult::state\n\tRuntimeObject * ___state_5;\n\t\/\/ System.Boolean System.Net.FtpAsyncResult::completed\n\tbool ___completed_6;\n\t\/\/ System.Boolean System.Net.FtpAsyncResult::synch\n\tbool ___synch_7;\n\t\/\/ System.Object System.Net.FtpAsyncResult::locker\n\tRuntimeObject * ___locker_8;\n\npublic:\n\tinline static int32_t get_offset_of_response_0() { return static_cast<int32_t>(offsetof(FtpAsyncResult_t3265664217, ___response_0)); }\n\tinline FtpWebResponse_t3940763575 * get_response_0() const { return ___response_0; }\n\tinline FtpWebResponse_t3940763575 ** get_address_of_response_0() { return &___response_0; }\n\tinline void set_response_0(FtpWebResponse_t3940763575 * value)\n\t{\n\t\t___response_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___response_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_waitHandle_1() { return static_cast<int32_t>(offsetof(FtpAsyncResult_t3265664217, ___waitHandle_1)); }\n\tinline ManualResetEvent_t451242010 * get_waitHandle_1() const { return ___waitHandle_1; }\n\tinline ManualResetEvent_t451242010 ** get_address_of_waitHandle_1() { return &___waitHandle_1; }\n\tinline void set_waitHandle_1(ManualResetEvent_t451242010 * value)\n\t{\n\t\t___waitHandle_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___waitHandle_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_exception_2() { return static_cast<int32_t>(offsetof(FtpAsyncResult_t3265664217, ___exception_2)); }\n\tinline Exception_t * get_exception_2() const { return ___exception_2; }\n\tinline Exception_t ** get_address_of_exception_2() { return &___exception_2; }\n\tinline void set_exception_2(Exception_t * value)\n\t{\n\t\t___exception_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___exception_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_callback_3() { return static_cast<int32_t>(offsetof(FtpAsyncResult_t3265664217, ___callback_3)); }\n\tinline AsyncCallback_t3962456242 * get_callback_3() const { return ___callback_3; }\n\tinline AsyncCallback_t3962456242 ** get_address_of_callback_3() { return &___callback_3; }\n\tinline void set_callback_3(AsyncCallback_t3962456242 * value)\n\t{\n\t\t___callback_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___callback_3), value);\n\t}\n\n\tinline static int32_t get_offset_of_stream_4() { return static_cast<int32_t>(offsetof(FtpAsyncResult_t3265664217, ___stream_4)); }\n\tinline Stream_t1273022909 * get_stream_4() const { return ___stream_4; }\n\tinline Stream_t1273022909 ** get_address_of_stream_4() { return &___stream_4; }\n\tinline void set_stream_4(Stream_t1273022909 * value)\n\t{\n\t\t___stream_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___stream_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_state_5() { return static_cast<int32_t>(offsetof(FtpAsyncResult_t3265664217, ___state_5)); }\n\tinline RuntimeObject * get_state_5() const { return ___state_5; }\n\tinline RuntimeObject ** get_address_of_state_5() { return &___state_5; }\n\tinline void set_state_5(RuntimeObject * value)\n\t{\n\t\t___state_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___state_5), value);\n\t}\n\n\tinline static int32_t get_offset_of_completed_6() { return static_cast<int32_t>(offsetof(FtpAsyncResult_t3265664217, ___completed_6)); }\n\tinline bool get_completed_6() const { return ___completed_6; }\n\tinline bool* get_address_of_completed_6() { return &___completed_6; }\n\tinline void set_completed_6(bool value)\n\t{\n\t\t___completed_6 = value;\n\t}\n\n\tinline static int32_t get_offset_of_synch_7() { return static_cast<int32_t>(offsetof(FtpAsyncResult_t3265664217, ___synch_7)); }\n\tinline bool get_synch_7() const { return ___synch_7; }\n\tinline bool* get_address_of_synch_7() { return &___synch_7; }\n\tinline void set_synch_7(bool value)\n\t{\n\t\t___synch_7 = value;\n\t}\n\n\tinline static int32_t get_offset_of_locker_8() { return static_cast<int32_t>(offsetof(FtpAsyncResult_t3265664217, ___locker_8)); }\n\tinline RuntimeObject * get_locker_8() const { return ___locker_8; }\n\tinline RuntimeObject ** get_address_of_locker_8() { return &___locker_8; }\n\tinline void set_locker_8(RuntimeObject * value)\n\t{\n\t\t___locker_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___locker_8), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FTPASYNCRESULT_T3265664217_H\n#ifndef FTPREQUESTCREATOR_T2926281497_H\n#define FTPREQUESTCREATOR_T2926281497_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FtpRequestCreator\nstruct  FtpRequestCreator_t2926281497  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FTPREQUESTCREATOR_T2926281497_H\n#ifndef GLOBALPROXYSELECTION_T1166292522_H\n#define GLOBALPROXYSELECTION_T1166292522_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.GlobalProxySelection\nstruct  GlobalProxySelection_t1166292522  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ GLOBALPROXYSELECTION_T1166292522_H\n#ifndef HTTPREQUESTCREATOR_T1984314013_H\n#define HTTPREQUESTCREATOR_T1984314013_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.HttpRequestCreator\nstruct  HttpRequestCreator_t1984314013  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ HTTPREQUESTCREATOR_T1984314013_H\n#ifndef HTTPVERSION_T346520293_H\n#define HTTPVERSION_T346520293_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.HttpVersion\nstruct  HttpVersion_t346520293  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\nstruct HttpVersion_t346520293_StaticFields\n{\npublic:\n\t\/\/ System.Version System.Net.HttpVersion::Version10\n\tVersion_t3456873960 * ___Version10_0;\n\t\/\/ System.Version System.Net.HttpVersion::Version11\n\tVersion_t3456873960 * ___Version11_1;\n\npublic:\n\tinline static int32_t get_offset_of_Version10_0() { return static_cast<int32_t>(offsetof(HttpVersion_t346520293_StaticFields, ___Version10_0)); }\n\tinline Version_t3456873960 * get_Version10_0() const { return ___Version10_0; }\n\tinline Version_t3456873960 ** get_address_of_Version10_0() { return &___Version10_0; }\n\tinline void set_Version10_0(Version_t3456873960 * value)\n\t{\n\t\t___Version10_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Version10_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_Version11_1() { return static_cast<int32_t>(offsetof(HttpVersion_t346520293_StaticFields, ___Version11_1)); }\n\tinline Version_t3456873960 * get_Version11_1() const { return ___Version11_1; }\n\tinline Version_t3456873960 ** get_address_of_Version11_1() { return &___Version11_1; }\n\tinline void set_Version11_1(Version_t3456873960 * value)\n\t{\n\t\t___Version11_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Version11_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ HTTPVERSION_T346520293_H\n#ifndef U3CBEGINAUTHENTICATEASCLIENTU3EC__ANONSTOREY7_T1222040293_H\n#define U3CBEGINAUTHENTICATEASCLIENTU3EC__ANONSTOREY7_T1222040293_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Security.SslStream\/<BeginAuthenticateAsClient>c__AnonStorey7\nstruct  U3CBeginAuthenticateAsClientU3Ec__AnonStorey7_t1222040293  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Security.Cryptography.X509Certificates.X509CertificateCollection System.Net.Security.SslStream\/<BeginAuthenticateAsClient>c__AnonStorey7::clientCertificates\n\tX509CertificateCollection_t3399372417 * ___clientCertificates_0;\n\t\/\/ System.Net.Security.SslStream System.Net.Security.SslStream\/<BeginAuthenticateAsClient>c__AnonStorey7::<>f__this\n\tSslStream_t2700741536 * ___U3CU3Ef__this_1;\n\npublic:\n\tinline static int32_t get_offset_of_clientCertificates_0() { return static_cast<int32_t>(offsetof(U3CBeginAuthenticateAsClientU3Ec__AnonStorey7_t1222040293, ___clientCertificates_0)); }\n\tinline X509CertificateCollection_t3399372417 * get_clientCertificates_0() const { return ___clientCertificates_0; }\n\tinline X509CertificateCollection_t3399372417 ** get_address_of_clientCertificates_0() { return &___clientCertificates_0; }\n\tinline void set_clientCertificates_0(X509CertificateCollection_t3399372417 * value)\n\t{\n\t\t___clientCertificates_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___clientCertificates_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_U3CU3Ef__this_1() { return static_cast<int32_t>(offsetof(U3CBeginAuthenticateAsClientU3Ec__AnonStorey7_t1222040293, ___U3CU3Ef__this_1)); }\n\tinline SslStream_t2700741536 * get_U3CU3Ef__this_1() const { return ___U3CU3Ef__this_1; }\n\tinline SslStream_t2700741536 ** get_address_of_U3CU3Ef__this_1() { return &___U3CU3Ef__this_1; }\n\tinline void set_U3CU3Ef__this_1(SslStream_t2700741536 * value)\n\t{\n\t\t___U3CU3Ef__this_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___U3CU3Ef__this_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ U3CBEGINAUTHENTICATEASCLIENTU3EC__ANONSTOREY7_T1222040293_H\n#ifndef U3CBEGINAUTHENTICATEASSERVERU3EC__ANONSTOREY8_T2934725513_H\n#define U3CBEGINAUTHENTICATEASSERVERU3EC__ANONSTOREY8_T2934725513_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Security.SslStream\/<BeginAuthenticateAsServer>c__AnonStorey8\nstruct  U3CBeginAuthenticateAsServerU3Ec__AnonStorey8_t2934725513  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Security.Cryptography.X509Certificates.X509Certificate System.Net.Security.SslStream\/<BeginAuthenticateAsServer>c__AnonStorey8::serverCertificate\n\tX509Certificate_t713131622 * ___serverCertificate_0;\n\t\/\/ System.Net.Security.SslStream System.Net.Security.SslStream\/<BeginAuthenticateAsServer>c__AnonStorey8::<>f__this\n\tSslStream_t2700741536 * ___U3CU3Ef__this_1;\n\npublic:\n\tinline static int32_t get_offset_of_serverCertificate_0() { return static_cast<int32_t>(offsetof(U3CBeginAuthenticateAsServerU3Ec__AnonStorey8_t2934725513, ___serverCertificate_0)); }\n\tinline X509Certificate_t713131622 * get_serverCertificate_0() const { return ___serverCertificate_0; }\n\tinline X509Certificate_t713131622 ** get_address_of_serverCertificate_0() { return &___serverCertificate_0; }\n\tinline void set_serverCertificate_0(X509Certificate_t713131622 * value)\n\t{\n\t\t___serverCertificate_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___serverCertificate_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_U3CU3Ef__this_1() { return static_cast<int32_t>(offsetof(U3CBeginAuthenticateAsServerU3Ec__AnonStorey8_t2934725513, ___U3CU3Ef__this_1)); }\n\tinline SslStream_t2700741536 * get_U3CU3Ef__this_1() const { return ___U3CU3Ef__this_1; }\n\tinline SslStream_t2700741536 ** get_address_of_U3CU3Ef__this_1() { return &___U3CU3Ef__this_1; }\n\tinline void set_U3CU3Ef__this_1(SslStream_t2700741536 * value)\n\t{\n\t\t___U3CU3Ef__this_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___U3CU3Ef__this_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ U3CBEGINAUTHENTICATEASSERVERU3EC__ANONSTOREY8_T2934725513_H\n#ifndef LINGEROPTION_T2688985448_H\n#define LINGEROPTION_T2688985448_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.LingerOption\nstruct  LingerOption_t2688985448  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Boolean System.Net.Sockets.LingerOption::enabled\n\tbool ___enabled_0;\n\t\/\/ System.Int32 System.Net.Sockets.LingerOption::seconds\n\tint32_t ___seconds_1;\n\npublic:\n\tinline static int32_t get_offset_of_enabled_0() { return static_cast<int32_t>(offsetof(LingerOption_t2688985448, ___enabled_0)); }\n\tinline bool get_enabled_0() const { return ___enabled_0; }\n\tinline bool* get_address_of_enabled_0() { return &___enabled_0; }\n\tinline void set_enabled_0(bool value)\n\t{\n\t\t___enabled_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_seconds_1() { return static_cast<int32_t>(offsetof(LingerOption_t2688985448, ___seconds_1)); }\n\tinline int32_t get_seconds_1() const { return ___seconds_1; }\n\tinline int32_t* get_address_of_seconds_1() { return &___seconds_1; }\n\tinline void set_seconds_1(int32_t value)\n\t{\n\t\t___seconds_1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ LINGEROPTION_T2688985448_H\n#ifndef MULTICASTOPTION_T3861143239_H\n#define MULTICASTOPTION_T3861143239_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.MulticastOption\nstruct  MulticastOption_t3861143239  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ MULTICASTOPTION_T3861143239_H\n#ifndef WORKER_T2051517921_H\n#define WORKER_T2051517921_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.Socket\/Worker\nstruct  Worker_t2051517921  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Net.Sockets.Socket\/SocketAsyncResult System.Net.Sockets.Socket\/Worker::result\n\tSocketAsyncResult_t2080034863 * ___result_0;\n\t\/\/ System.Boolean System.Net.Sockets.Socket\/Worker::requireSocketSecurity\n\tbool ___requireSocketSecurity_1;\n\t\/\/ System.Int32 System.Net.Sockets.Socket\/Worker::send_so_far\n\tint32_t ___send_so_far_2;\n\npublic:\n\tinline static int32_t get_offset_of_result_0() { return static_cast<int32_t>(offsetof(Worker_t2051517921, ___result_0)); }\n\tinline SocketAsyncResult_t2080034863 * get_result_0() const { return ___result_0; }\n\tinline SocketAsyncResult_t2080034863 ** get_address_of_result_0() { return &___result_0; }\n\tinline void set_result_0(SocketAsyncResult_t2080034863 * value)\n\t{\n\t\t___result_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___result_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_requireSocketSecurity_1() { return static_cast<int32_t>(offsetof(Worker_t2051517921, ___requireSocketSecurity_1)); }\n\tinline bool get_requireSocketSecurity_1() const { return ___requireSocketSecurity_1; }\n\tinline bool* get_address_of_requireSocketSecurity_1() { return &___requireSocketSecurity_1; }\n\tinline void set_requireSocketSecurity_1(bool value)\n\t{\n\t\t___requireSocketSecurity_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_send_so_far_2() { return static_cast<int32_t>(offsetof(Worker_t2051517921, ___send_so_far_2)); }\n\tinline int32_t get_send_so_far_2() const { return ___send_so_far_2; }\n\tinline int32_t* get_address_of_send_so_far_2() { return &___send_so_far_2; }\n\tinline void set_send_so_far_2(int32_t value)\n\t{\n\t\t___send_so_far_2 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ WORKER_T2051517921_H\n#ifndef GENERICIDENTITY_T2319019448_H\n#define GENERICIDENTITY_T2319019448_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Security.Principal.GenericIdentity\nstruct  GenericIdentity_t2319019448  : public RuntimeObject\n{\npublic:\n\t\/\/ System.String System.Security.Principal.GenericIdentity::m_name\n\tString_t* ___m_name_0;\n\t\/\/ System.String System.Security.Principal.GenericIdentity::m_type\n\tString_t* ___m_type_1;\n\npublic:\n\tinline static int32_t get_offset_of_m_name_0() { return static_cast<int32_t>(offsetof(GenericIdentity_t2319019448, ___m_name_0)); }\n\tinline String_t* get_m_name_0() const { return ___m_name_0; }\n\tinline String_t** get_address_of_m_name_0() { return &___m_name_0; }\n\tinline void set_m_name_0(String_t* value)\n\t{\n\t\t___m_name_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_name_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_m_type_1() { return static_cast<int32_t>(offsetof(GenericIdentity_t2319019448, ___m_type_1)); }\n\tinline String_t* get_m_type_1() const { return ___m_type_1; }\n\tinline String_t** get_address_of_m_type_1() { return &___m_type_1; }\n\tinline void set_m_type_1(String_t* value)\n\t{\n\t\t___m_type_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_type_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ GENERICIDENTITY_T2319019448_H\n#ifndef VALUETYPE_T3640485471_H\n#define VALUETYPE_T3640485471_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ValueType\nstruct  ValueType_t3640485471  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.ValueType\nstruct ValueType_t3640485471_marshaled_pinvoke\n{\n};\n\/\/ Native definition for COM marshalling of System.ValueType\nstruct ValueType_t3640485471_marshaled_com\n{\n};\n#endif \/\/ VALUETYPE_T3640485471_H\n#ifndef NAMEVALUECOLLECTION_T407452768_H\n#define NAMEVALUECOLLECTION_T407452768_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Collections.Specialized.NameValueCollection\nstruct  NameValueCollection_t407452768  : public NameObjectCollectionBase_t2091847364\n{\npublic:\n\t\/\/ System.String[] System.Collections.Specialized.NameValueCollection::cachedAllKeys\n\tStringU5BU5D_t1281789340* ___cachedAllKeys_10;\n\t\/\/ System.String[] System.Collections.Specialized.NameValueCollection::cachedAll\n\tStringU5BU5D_t1281789340* ___cachedAll_11;\n\npublic:\n\tinline static int32_t get_offset_of_cachedAllKeys_10() { return static_cast<int32_t>(offsetof(NameValueCollection_t407452768, ___cachedAllKeys_10)); }\n\tinline StringU5BU5D_t1281789340* get_cachedAllKeys_10() const { return ___cachedAllKeys_10; }\n\tinline StringU5BU5D_t1281789340** get_address_of_cachedAllKeys_10() { return &___cachedAllKeys_10; }\n\tinline void set_cachedAllKeys_10(StringU5BU5D_t1281789340* value)\n\t{\n\t\t___cachedAllKeys_10 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___cachedAllKeys_10), value);\n\t}\n\n\tinline static int32_t get_offset_of_cachedAll_11() { return static_cast<int32_t>(offsetof(NameValueCollection_t407452768, ___cachedAll_11)); }\n\tinline StringU5BU5D_t1281789340* get_cachedAll_11() const { return ___cachedAll_11; }\n\tinline StringU5BU5D_t1281789340** get_address_of_cachedAll_11() { return &___cachedAll_11; }\n\tinline void set_cachedAll_11(StringU5BU5D_t1281789340* value)\n\t{\n\t\t___cachedAll_11 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___cachedAll_11), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ NAMEVALUECOLLECTION_T407452768_H\n#ifndef CATEGORYATTRIBUTE_T39585132_H\n#define CATEGORYATTRIBUTE_T39585132_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.CategoryAttribute\nstruct  CategoryAttribute_t39585132  : public Attribute_t861562559\n{\npublic:\n\t\/\/ System.String System.ComponentModel.CategoryAttribute::category\n\tString_t* ___category_0;\n\t\/\/ System.Boolean System.ComponentModel.CategoryAttribute::IsLocalized\n\tbool ___IsLocalized_1;\n\npublic:\n\tinline static int32_t get_offset_of_category_0() { return static_cast<int32_t>(offsetof(CategoryAttribute_t39585132, ___category_0)); }\n\tinline String_t* get_category_0() const { return ___category_0; }\n\tinline String_t** get_address_of_category_0() { return &___category_0; }\n\tinline void set_category_0(String_t* value)\n\t{\n\t\t___category_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___category_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_IsLocalized_1() { return static_cast<int32_t>(offsetof(CategoryAttribute_t39585132, ___IsLocalized_1)); }\n\tinline bool get_IsLocalized_1() const { return ___IsLocalized_1; }\n\tinline bool* get_address_of_IsLocalized_1() { return &___IsLocalized_1; }\n\tinline void set_IsLocalized_1(bool value)\n\t{\n\t\t___IsLocalized_1 = value;\n\t}\n};\n\nstruct CategoryAttribute_t39585132_StaticFields\n{\npublic:\n\t\/\/ System.Object System.ComponentModel.CategoryAttribute::lockobj\n\tRuntimeObject * ___lockobj_2;\n\npublic:\n\tinline static int32_t get_offset_of_lockobj_2() { return static_cast<int32_t>(offsetof(CategoryAttribute_t39585132_StaticFields, ___lockobj_2)); }\n\tinline RuntimeObject * get_lockobj_2() const { return ___lockobj_2; }\n\tinline RuntimeObject ** get_address_of_lockobj_2() { return &___lockobj_2; }\n\tinline void set_lockobj_2(RuntimeObject * value)\n\t{\n\t\t___lockobj_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___lockobj_2), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CATEGORYATTRIBUTE_T39585132_H\n#ifndef COMPONENT_T3620823400_H\n#define COMPONENT_T3620823400_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.Component\nstruct  Component_t3620823400  : public MarshalByRefObject_t2760389100\n{\npublic:\n\t\/\/ System.ComponentModel.EventHandlerList System.ComponentModel.Component::event_handlers\n\tEventHandlerList_t1108123056 * ___event_handlers_1;\n\t\/\/ System.ComponentModel.ISite System.ComponentModel.Component::mySite\n\tRuntimeObject* ___mySite_2;\n\t\/\/ System.Object System.ComponentModel.Component::disposedEvent\n\tRuntimeObject * ___disposedEvent_3;\n\npublic:\n\tinline static int32_t get_offset_of_event_handlers_1() { return static_cast<int32_t>(offsetof(Component_t3620823400, ___event_handlers_1)); }\n\tinline EventHandlerList_t1108123056 * get_event_handlers_1() const { return ___event_handlers_1; }\n\tinline EventHandlerList_t1108123056 ** get_address_of_event_handlers_1() { return &___event_handlers_1; }\n\tinline void set_event_handlers_1(EventHandlerList_t1108123056 * value)\n\t{\n\t\t___event_handlers_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___event_handlers_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_mySite_2() { return static_cast<int32_t>(offsetof(Component_t3620823400, ___mySite_2)); }\n\tinline RuntimeObject* get_mySite_2() const { return ___mySite_2; }\n\tinline RuntimeObject** get_address_of_mySite_2() { return &___mySite_2; }\n\tinline void set_mySite_2(RuntimeObject* value)\n\t{\n\t\t___mySite_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___mySite_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_disposedEvent_3() { return static_cast<int32_t>(offsetof(Component_t3620823400, ___disposedEvent_3)); }\n\tinline RuntimeObject * get_disposedEvent_3() const { return ___disposedEvent_3; }\n\tinline RuntimeObject ** get_address_of_disposedEvent_3() { return &___disposedEvent_3; }\n\tinline void set_disposedEvent_3(RuntimeObject * value)\n\t{\n\t\t___disposedEvent_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___disposedEvent_3), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ COMPONENT_T3620823400_H\n#ifndef DEFAULTEVENTATTRIBUTE_T3124666540_H\n#define DEFAULTEVENTATTRIBUTE_T3124666540_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.DefaultEventAttribute\nstruct  DefaultEventAttribute_t3124666540  : public Attribute_t861562559\n{\npublic:\n\t\/\/ System.String System.ComponentModel.DefaultEventAttribute::eventName\n\tString_t* ___eventName_0;\n\npublic:\n\tinline static int32_t get_offset_of_eventName_0() { return static_cast<int32_t>(offsetof(DefaultEventAttribute_t3124666540, ___eventName_0)); }\n\tinline String_t* get_eventName_0() const { return ___eventName_0; }\n\tinline String_t** get_address_of_eventName_0() { return &___eventName_0; }\n\tinline void set_eventName_0(String_t* value)\n\t{\n\t\t___eventName_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___eventName_0), value);\n\t}\n};\n\nstruct DefaultEventAttribute_t3124666540_StaticFields\n{\npublic:\n\t\/\/ System.ComponentModel.DefaultEventAttribute System.ComponentModel.DefaultEventAttribute::Default\n\tDefaultEventAttribute_t3124666540 * ___Default_1;\n\npublic:\n\tinline static int32_t get_offset_of_Default_1() { return static_cast<int32_t>(offsetof(DefaultEventAttribute_t3124666540_StaticFields, ___Default_1)); }\n\tinline DefaultEventAttribute_t3124666540 * get_Default_1() const { return ___Default_1; }\n\tinline DefaultEventAttribute_t3124666540 ** get_address_of_Default_1() { return &___Default_1; }\n\tinline void set_Default_1(DefaultEventAttribute_t3124666540 * value)\n\t{\n\t\t___Default_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Default_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DEFAULTEVENTATTRIBUTE_T3124666540_H\n#ifndef DEFAULTPROPERTYATTRIBUTE_T1952442862_H\n#define DEFAULTPROPERTYATTRIBUTE_T1952442862_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.DefaultPropertyAttribute\nstruct  DefaultPropertyAttribute_t1952442862  : public Attribute_t861562559\n{\npublic:\n\t\/\/ System.String System.ComponentModel.DefaultPropertyAttribute::property_name\n\tString_t* ___property_name_0;\n\npublic:\n\tinline static int32_t get_offset_of_property_name_0() { return static_cast<int32_t>(offsetof(DefaultPropertyAttribute_t1952442862, ___property_name_0)); }\n\tinline String_t* get_property_name_0() const { return ___property_name_0; }\n\tinline String_t** get_address_of_property_name_0() { return &___property_name_0; }\n\tinline void set_property_name_0(String_t* value)\n\t{\n\t\t___property_name_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___property_name_0), value);\n\t}\n};\n\nstruct DefaultPropertyAttribute_t1952442862_StaticFields\n{\npublic:\n\t\/\/ System.ComponentModel.DefaultPropertyAttribute System.ComponentModel.DefaultPropertyAttribute::Default\n\tDefaultPropertyAttribute_t1952442862 * ___Default_1;\n\npublic:\n\tinline static int32_t get_offset_of_Default_1() { return static_cast<int32_t>(offsetof(DefaultPropertyAttribute_t1952442862_StaticFields, ___Default_1)); }\n\tinline DefaultPropertyAttribute_t1952442862 * get_Default_1() const { return ___Default_1; }\n\tinline DefaultPropertyAttribute_t1952442862 ** get_address_of_Default_1() { return &___Default_1; }\n\tinline void set_Default_1(DefaultPropertyAttribute_t1952442862 * value)\n\t{\n\t\t___Default_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Default_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DEFAULTPROPERTYATTRIBUTE_T1952442862_H\n#ifndef DEFAULTVALUEATTRIBUTE_T587583663_H\n#define DEFAULTVALUEATTRIBUTE_T587583663_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.DefaultValueAttribute\nstruct  DefaultValueAttribute_t587583663  : public Attribute_t861562559\n{\npublic:\n\t\/\/ System.Object System.ComponentModel.DefaultValueAttribute::DefaultValue\n\tRuntimeObject * ___DefaultValue_0;\n\npublic:\n\tinline static int32_t get_offset_of_DefaultValue_0() { return static_cast<int32_t>(offsetof(DefaultValueAttribute_t587583663, ___DefaultValue_0)); }\n\tinline RuntimeObject * get_DefaultValue_0() const { return ___DefaultValue_0; }\n\tinline RuntimeObject ** get_address_of_DefaultValue_0() { return &___DefaultValue_0; }\n\tinline void set_DefaultValue_0(RuntimeObject * value)\n\t{\n\t\t___DefaultValue_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___DefaultValue_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DEFAULTVALUEATTRIBUTE_T587583663_H\n#ifndef DESCRIPTIONATTRIBUTE_T874390736_H\n#define DESCRIPTIONATTRIBUTE_T874390736_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.DescriptionAttribute\nstruct  DescriptionAttribute_t874390736  : public Attribute_t861562559\n{\npublic:\n\t\/\/ System.String System.ComponentModel.DescriptionAttribute::desc\n\tString_t* ___desc_0;\n\npublic:\n\tinline static int32_t get_offset_of_desc_0() { return static_cast<int32_t>(offsetof(DescriptionAttribute_t874390736, ___desc_0)); }\n\tinline String_t* get_desc_0() const { return ___desc_0; }\n\tinline String_t** get_address_of_desc_0() { return &___desc_0; }\n\tinline void set_desc_0(String_t* value)\n\t{\n\t\t___desc_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___desc_0), value);\n\t}\n};\n\nstruct DescriptionAttribute_t874390736_StaticFields\n{\npublic:\n\t\/\/ System.ComponentModel.DescriptionAttribute System.ComponentModel.DescriptionAttribute::Default\n\tDescriptionAttribute_t874390736 * ___Default_1;\n\npublic:\n\tinline static int32_t get_offset_of_Default_1() { return static_cast<int32_t>(offsetof(DescriptionAttribute_t874390736_StaticFields, ___Default_1)); }\n\tinline DescriptionAttribute_t874390736 * get_Default_1() const { return ___Default_1; }\n\tinline DescriptionAttribute_t874390736 ** get_address_of_Default_1() { return &___Default_1; }\n\tinline void set_Default_1(DescriptionAttribute_t874390736 * value)\n\t{\n\t\t___Default_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Default_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DESCRIPTIONATTRIBUTE_T874390736_H\n#ifndef DESIGNERCATEGORYATTRIBUTE_T2912925731_H\n#define DESIGNERCATEGORYATTRIBUTE_T2912925731_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.DesignerCategoryAttribute\nstruct  DesignerCategoryAttribute_t2912925731  : public Attribute_t861562559\n{\npublic:\n\t\/\/ System.String System.ComponentModel.DesignerCategoryAttribute::category\n\tString_t* ___category_0;\n\npublic:\n\tinline static int32_t get_offset_of_category_0() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_t2912925731, ___category_0)); }\n\tinline String_t* get_category_0() const { return ___category_0; }\n\tinline String_t** get_address_of_category_0() { return &___category_0; }\n\tinline void set_category_0(String_t* value)\n\t{\n\t\t___category_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___category_0), value);\n\t}\n};\n\nstruct DesignerCategoryAttribute_t2912925731_StaticFields\n{\npublic:\n\t\/\/ System.ComponentModel.DesignerCategoryAttribute System.ComponentModel.DesignerCategoryAttribute::Component\n\tDesignerCategoryAttribute_t2912925731 * ___Component_1;\n\t\/\/ System.ComponentModel.DesignerCategoryAttribute System.ComponentModel.DesignerCategoryAttribute::Form\n\tDesignerCategoryAttribute_t2912925731 * ___Form_2;\n\t\/\/ System.ComponentModel.DesignerCategoryAttribute System.ComponentModel.DesignerCategoryAttribute::Generic\n\tDesignerCategoryAttribute_t2912925731 * ___Generic_3;\n\t\/\/ System.ComponentModel.DesignerCategoryAttribute System.ComponentModel.DesignerCategoryAttribute::Default\n\tDesignerCategoryAttribute_t2912925731 * ___Default_4;\n\npublic:\n\tinline static int32_t get_offset_of_Component_1() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_t2912925731_StaticFields, ___Component_1)); }\n\tinline DesignerCategoryAttribute_t2912925731 * get_Component_1() const { return ___Component_1; }\n\tinline DesignerCategoryAttribute_t2912925731 ** get_address_of_Component_1() { return &___Component_1; }\n\tinline void set_Component_1(DesignerCategoryAttribute_t2912925731 * value)\n\t{\n\t\t___Component_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Component_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_Form_2() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_t2912925731_StaticFields, ___Form_2)); }\n\tinline DesignerCategoryAttribute_t2912925731 * get_Form_2() const { return ___Form_2; }\n\tinline DesignerCategoryAttribute_t2912925731 ** get_address_of_Form_2() { return &___Form_2; }\n\tinline void set_Form_2(DesignerCategoryAttribute_t2912925731 * value)\n\t{\n\t\t___Form_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Form_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_Generic_3() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_t2912925731_StaticFields, ___Generic_3)); }\n\tinline DesignerCategoryAttribute_t2912925731 * get_Generic_3() const { return ___Generic_3; }\n\tinline DesignerCategoryAttribute_t2912925731 ** get_address_of_Generic_3() { return &___Generic_3; }\n\tinline void set_Generic_3(DesignerCategoryAttribute_t2912925731 * value)\n\t{\n\t\t___Generic_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Generic_3), value);\n\t}\n\n\tinline static int32_t get_offset_of_Default_4() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_t2912925731_StaticFields, ___Default_4)); }\n\tinline DesignerCategoryAttribute_t2912925731 * get_Default_4() const { return ___Default_4; }\n\tinline DesignerCategoryAttribute_t2912925731 ** get_address_of_Default_4() { return &___Default_4; }\n\tinline void set_Default_4(DesignerCategoryAttribute_t2912925731 * value)\n\t{\n\t\t___Default_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Default_4), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DESIGNERCATEGORYATTRIBUTE_T2912925731_H\n#ifndef PROGRESSCHANGEDEVENTARGS_T3227452477_H\n#define PROGRESSCHANGEDEVENTARGS_T3227452477_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.ProgressChangedEventArgs\nstruct  ProgressChangedEventArgs_t3227452477  : public EventArgs_t3591816995\n{\npublic:\n\t\/\/ System.Int32 System.ComponentModel.ProgressChangedEventArgs::progress\n\tint32_t ___progress_1;\n\t\/\/ System.Object System.ComponentModel.ProgressChangedEventArgs::state\n\tRuntimeObject * ___state_2;\n\npublic:\n\tinline static int32_t get_offset_of_progress_1() { return static_cast<int32_t>(offsetof(ProgressChangedEventArgs_t3227452477, ___progress_1)); }\n\tinline int32_t get_progress_1() const { return ___progress_1; }\n\tinline int32_t* get_address_of_progress_1() { return &___progress_1; }\n\tinline void set_progress_1(int32_t value)\n\t{\n\t\t___progress_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_state_2() { return static_cast<int32_t>(offsetof(ProgressChangedEventArgs_t3227452477, ___state_2)); }\n\tinline RuntimeObject * get_state_2() const { return ___state_2; }\n\tinline RuntimeObject ** get_address_of_state_2() { return &___state_2; }\n\tinline void set_state_2(RuntimeObject * value)\n\t{\n\t\t___state_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___state_2), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ PROGRESSCHANGEDEVENTARGS_T3227452477_H\n#ifndef RECOMMENDEDASCONFIGURABLEATTRIBUTE_T279829077_H\n#define RECOMMENDEDASCONFIGURABLEATTRIBUTE_T279829077_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.RecommendedAsConfigurableAttribute\nstruct  RecommendedAsConfigurableAttribute_t279829077  : public Attribute_t861562559\n{\npublic:\n\t\/\/ System.Boolean System.ComponentModel.RecommendedAsConfigurableAttribute::recommendedAsConfigurable\n\tbool ___recommendedAsConfigurable_0;\n\npublic:\n\tinline static int32_t get_offset_of_recommendedAsConfigurable_0() { return static_cast<int32_t>(offsetof(RecommendedAsConfigurableAttribute_t279829077, ___recommendedAsConfigurable_0)); }\n\tinline bool get_recommendedAsConfigurable_0() const { return ___recommendedAsConfigurable_0; }\n\tinline bool* get_address_of_recommendedAsConfigurable_0() { return &___recommendedAsConfigurable_0; }\n\tinline void set_recommendedAsConfigurable_0(bool value)\n\t{\n\t\t___recommendedAsConfigurable_0 = value;\n\t}\n};\n\nstruct RecommendedAsConfigurableAttribute_t279829077_StaticFields\n{\npublic:\n\t\/\/ System.ComponentModel.RecommendedAsConfigurableAttribute System.ComponentModel.RecommendedAsConfigurableAttribute::Default\n\tRecommendedAsConfigurableAttribute_t279829077 * ___Default_1;\n\t\/\/ System.ComponentModel.RecommendedAsConfigurableAttribute System.ComponentModel.RecommendedAsConfigurableAttribute::No\n\tRecommendedAsConfigurableAttribute_t279829077 * ___No_2;\n\t\/\/ System.ComponentModel.RecommendedAsConfigurableAttribute System.ComponentModel.RecommendedAsConfigurableAttribute::Yes\n\tRecommendedAsConfigurableAttribute_t279829077 * ___Yes_3;\n\npublic:\n\tinline static int32_t get_offset_of_Default_1() { return static_cast<int32_t>(offsetof(RecommendedAsConfigurableAttribute_t279829077_StaticFields, ___Default_1)); }\n\tinline RecommendedAsConfigurableAttribute_t279829077 * get_Default_1() const { return ___Default_1; }\n\tinline RecommendedAsConfigurableAttribute_t279829077 ** get_address_of_Default_1() { return &___Default_1; }\n\tinline void set_Default_1(RecommendedAsConfigurableAttribute_t279829077 * value)\n\t{\n\t\t___Default_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Default_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_No_2() { return static_cast<int32_t>(offsetof(RecommendedAsConfigurableAttribute_t279829077_StaticFields, ___No_2)); }\n\tinline RecommendedAsConfigurableAttribute_t279829077 * get_No_2() const { return ___No_2; }\n\tinline RecommendedAsConfigurableAttribute_t279829077 ** get_address_of_No_2() { return &___No_2; }\n\tinline void set_No_2(RecommendedAsConfigurableAttribute_t279829077 * value)\n\t{\n\t\t___No_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___No_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_Yes_3() { return static_cast<int32_t>(offsetof(RecommendedAsConfigurableAttribute_t279829077_StaticFields, ___Yes_3)); }\n\tinline RecommendedAsConfigurableAttribute_t279829077 * get_Yes_3() const { return ___Yes_3; }\n\tinline RecommendedAsConfigurableAttribute_t279829077 ** get_address_of_Yes_3() { return &___Yes_3; }\n\tinline void set_Yes_3(RecommendedAsConfigurableAttribute_t279829077 * value)\n\t{\n\t\t___Yes_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Yes_3), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ RECOMMENDEDASCONFIGURABLEATTRIBUTE_T279829077_H\n#ifndef TYPECONVERTERATTRIBUTE_T3271584429_H\n#define TYPECONVERTERATTRIBUTE_T3271584429_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.TypeConverterAttribute\nstruct  TypeConverterAttribute_t3271584429  : public Attribute_t861562559\n{\npublic:\n\t\/\/ System.String System.ComponentModel.TypeConverterAttribute::converter_type\n\tString_t* ___converter_type_1;\n\npublic:\n\tinline static int32_t get_offset_of_converter_type_1() { return static_cast<int32_t>(offsetof(TypeConverterAttribute_t3271584429, ___converter_type_1)); }\n\tinline String_t* get_converter_type_1() const { return ___converter_type_1; }\n\tinline String_t** get_address_of_converter_type_1() { return &___converter_type_1; }\n\tinline void set_converter_type_1(String_t* value)\n\t{\n\t\t___converter_type_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___converter_type_1), value);\n\t}\n};\n\nstruct TypeConverterAttribute_t3271584429_StaticFields\n{\npublic:\n\t\/\/ System.ComponentModel.TypeConverterAttribute System.ComponentModel.TypeConverterAttribute::Default\n\tTypeConverterAttribute_t3271584429 * ___Default_0;\n\npublic:\n\tinline static int32_t get_offset_of_Default_0() { return static_cast<int32_t>(offsetof(TypeConverterAttribute_t3271584429_StaticFields, ___Default_0)); }\n\tinline TypeConverterAttribute_t3271584429 * get_Default_0() const { return ___Default_0; }\n\tinline TypeConverterAttribute_t3271584429 ** get_address_of_Default_0() { return &___Default_0; }\n\tinline void set_Default_0(TypeConverterAttribute_t3271584429 * value)\n\t{\n\t\t___Default_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Default_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ TYPECONVERTERATTRIBUTE_T3271584429_H\n#ifndef ENUM_T4135868527_H\n#define ENUM_T4135868527_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Enum\nstruct  Enum_t4135868527  : public ValueType_t3640485471\n{\npublic:\n\npublic:\n};\n\nstruct Enum_t4135868527_StaticFields\n{\npublic:\n\t\/\/ System.Char[] System.Enum::split_char\n\tCharU5BU5D_t3528271667* ___split_char_0;\n\npublic:\n\tinline static int32_t get_offset_of_split_char_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___split_char_0)); }\n\tinline CharU5BU5D_t3528271667* get_split_char_0() const { return ___split_char_0; }\n\tinline CharU5BU5D_t3528271667** get_address_of_split_char_0() { return &___split_char_0; }\n\tinline void set_split_char_0(CharU5BU5D_t3528271667* value)\n\t{\n\t\t___split_char_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___split_char_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.Enum\nstruct Enum_t4135868527_marshaled_pinvoke\n{\n};\n\/\/ Native definition for COM marshalling of System.Enum\nstruct Enum_t4135868527_marshaled_com\n{\n};\n#endif \/\/ ENUM_T4135868527_H\n#ifndef GZIPSTREAM_T3417139389_H\n#define GZIPSTREAM_T3417139389_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.IO.Compression.GZipStream\nstruct  GZipStream_t3417139389  : public Stream_t1273022909\n{\npublic:\n\t\/\/ System.IO.Compression.DeflateStream System.IO.Compression.GZipStream::deflateStream\n\tDeflateStream_t4175168077 * ___deflateStream_1;\n\npublic:\n\tinline static int32_t get_offset_of_deflateStream_1() { return static_cast<int32_t>(offsetof(GZipStream_t3417139389, ___deflateStream_1)); }\n\tinline DeflateStream_t4175168077 * get_deflateStream_1() const { return ___deflateStream_1; }\n\tinline DeflateStream_t4175168077 ** get_address_of_deflateStream_1() { return &___deflateStream_1; }\n\tinline void set_deflateStream_1(DeflateStream_t4175168077 * value)\n\t{\n\t\t___deflateStream_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___deflateStream_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ GZIPSTREAM_T3417139389_H\n#ifndef INT32_T2950945753_H\n#define INT32_T2950945753_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Int32\nstruct  Int32_t2950945753 \n{\npublic:\n\t\/\/ System.Int32 System.Int32::m_value\n\tint32_t ___m_value_2;\n\npublic:\n\tinline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Int32_t2950945753, ___m_value_2)); }\n\tinline int32_t get_m_value_2() const { return ___m_value_2; }\n\tinline int32_t* get_address_of_m_value_2() { return &___m_value_2; }\n\tinline void set_m_value_2(int32_t value)\n\t{\n\t\t___m_value_2 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INT32_T2950945753_H\n#ifndef INTPTR_T_H\n#define INTPTR_T_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.IntPtr\nstruct  IntPtr_t \n{\npublic:\n\t\/\/ System.Void* System.IntPtr::m_value\n\tvoid* ___m_value_0;\n\npublic:\n\tinline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); }\n\tinline void* get_m_value_0() const { return ___m_value_0; }\n\tinline void** get_address_of_m_value_0() { return &___m_value_0; }\n\tinline void set_m_value_0(void* value)\n\t{\n\t\t___m_value_0 = value;\n\t}\n};\n\nstruct IntPtr_t_StaticFields\n{\npublic:\n\t\/\/ System.IntPtr System.IntPtr::Zero\n\tintptr_t ___Zero_1;\n\npublic:\n\tinline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); }\n\tinline intptr_t get_Zero_1() const { return ___Zero_1; }\n\tinline intptr_t* get_address_of_Zero_1() { return &___Zero_1; }\n\tinline void set_Zero_1(intptr_t value)\n\t{\n\t\t___Zero_1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTPTR_T_H\n#ifndef FTPDATASTREAM_T1366729715_H\n#define FTPDATASTREAM_T1366729715_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FtpDataStream\nstruct  FtpDataStream_t1366729715  : public Stream_t1273022909\n{\npublic:\n\t\/\/ System.Net.FtpWebRequest System.Net.FtpDataStream::request\n\tFtpWebRequest_t1577818305 * ___request_1;\n\t\/\/ System.IO.Stream System.Net.FtpDataStream::networkStream\n\tStream_t1273022909 * ___networkStream_2;\n\t\/\/ System.Boolean System.Net.FtpDataStream::disposed\n\tbool ___disposed_3;\n\t\/\/ System.Boolean System.Net.FtpDataStream::isRead\n\tbool ___isRead_4;\n\t\/\/ System.Int32 System.Net.FtpDataStream::totalRead\n\tint32_t ___totalRead_5;\n\npublic:\n\tinline static int32_t get_offset_of_request_1() { return static_cast<int32_t>(offsetof(FtpDataStream_t1366729715, ___request_1)); }\n\tinline FtpWebRequest_t1577818305 * get_request_1() const { return ___request_1; }\n\tinline FtpWebRequest_t1577818305 ** get_address_of_request_1() { return &___request_1; }\n\tinline void set_request_1(FtpWebRequest_t1577818305 * value)\n\t{\n\t\t___request_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___request_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_networkStream_2() { return static_cast<int32_t>(offsetof(FtpDataStream_t1366729715, ___networkStream_2)); }\n\tinline Stream_t1273022909 * get_networkStream_2() const { return ___networkStream_2; }\n\tinline Stream_t1273022909 ** get_address_of_networkStream_2() { return &___networkStream_2; }\n\tinline void set_networkStream_2(Stream_t1273022909 * value)\n\t{\n\t\t___networkStream_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___networkStream_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_disposed_3() { return static_cast<int32_t>(offsetof(FtpDataStream_t1366729715, ___disposed_3)); }\n\tinline bool get_disposed_3() const { return ___disposed_3; }\n\tinline bool* get_address_of_disposed_3() { return &___disposed_3; }\n\tinline void set_disposed_3(bool value)\n\t{\n\t\t___disposed_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_isRead_4() { return static_cast<int32_t>(offsetof(FtpDataStream_t1366729715, ___isRead_4)); }\n\tinline bool get_isRead_4() const { return ___isRead_4; }\n\tinline bool* get_address_of_isRead_4() { return &___isRead_4; }\n\tinline void set_isRead_4(bool value)\n\t{\n\t\t___isRead_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_totalRead_5() { return static_cast<int32_t>(offsetof(FtpDataStream_t1366729715, ___totalRead_5)); }\n\tinline int32_t get_totalRead_5() const { return ___totalRead_5; }\n\tinline int32_t* get_address_of_totalRead_5() { return &___totalRead_5; }\n\tinline void set_totalRead_5(int32_t value)\n\t{\n\t\t___totalRead_5 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FTPDATASTREAM_T1366729715_H\n#ifndef HTTPLISTENERBASICIDENTITY_T3019963659_H\n#define HTTPLISTENERBASICIDENTITY_T3019963659_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.HttpListenerBasicIdentity\nstruct  HttpListenerBasicIdentity_t3019963659  : public GenericIdentity_t2319019448\n{\npublic:\n\t\/\/ System.String System.Net.HttpListenerBasicIdentity::password\n\tString_t* ___password_2;\n\npublic:\n\tinline static int32_t get_offset_of_password_2() { return static_cast<int32_t>(offsetof(HttpListenerBasicIdentity_t3019963659, ___password_2)); }\n\tinline String_t* get_password_2() const { return ___password_2; }\n\tinline String_t** get_address_of_password_2() { return &___password_2; }\n\tinline void set_password_2(String_t* value)\n\t{\n\t\t___password_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___password_2), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ HTTPLISTENERBASICIDENTITY_T3019963659_H\n#ifndef AUTHENTICATEDSTREAM_T3415418016_H\n#define AUTHENTICATEDSTREAM_T3415418016_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Security.AuthenticatedStream\nstruct  AuthenticatedStream_t3415418016  : public Stream_t1273022909\n{\npublic:\n\t\/\/ System.IO.Stream System.Net.Security.AuthenticatedStream::innerStream\n\tStream_t1273022909 * ___innerStream_1;\n\t\/\/ System.Boolean System.Net.Security.AuthenticatedStream::leaveStreamOpen\n\tbool ___leaveStreamOpen_2;\n\npublic:\n\tinline static int32_t get_offset_of_innerStream_1() { return static_cast<int32_t>(offsetof(AuthenticatedStream_t3415418016, ___innerStream_1)); }\n\tinline Stream_t1273022909 * get_innerStream_1() const { return ___innerStream_1; }\n\tinline Stream_t1273022909 ** get_address_of_innerStream_1() { return &___innerStream_1; }\n\tinline void set_innerStream_1(Stream_t1273022909 * value)\n\t{\n\t\t___innerStream_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___innerStream_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_leaveStreamOpen_2() { return static_cast<int32_t>(offsetof(AuthenticatedStream_t3415418016, ___leaveStreamOpen_2)); }\n\tinline bool get_leaveStreamOpen_2() const { return ___leaveStreamOpen_2; }\n\tinline bool* get_address_of_leaveStreamOpen_2() { return &___leaveStreamOpen_2; }\n\tinline void set_leaveStreamOpen_2(bool value)\n\t{\n\t\t___leaveStreamOpen_2 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ AUTHENTICATEDSTREAM_T3415418016_H\n#ifndef WEBRESPONSE_T229922639_H\n#define WEBRESPONSE_T229922639_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.WebResponse\nstruct  WebResponse_t229922639  : public MarshalByRefObject_t2760389100\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ WEBRESPONSE_T229922639_H\n#ifndef GCHANDLE_T3351438187_H\n#define GCHANDLE_T3351438187_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.InteropServices.GCHandle\nstruct  GCHandle_t3351438187 \n{\npublic:\n\t\/\/ System.Int32 System.Runtime.InteropServices.GCHandle::handle\n\tint32_t ___handle_0;\n\npublic:\n\tinline static int32_t get_offset_of_handle_0() { return static_cast<int32_t>(offsetof(GCHandle_t3351438187, ___handle_0)); }\n\tinline int32_t get_handle_0() const { return ___handle_0; }\n\tinline int32_t* get_address_of_handle_0() { return &___handle_0; }\n\tinline void set_handle_0(int32_t value)\n\t{\n\t\t___handle_0 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ GCHANDLE_T3351438187_H\n#ifndef SYSTEMEXCEPTION_T176217640_H\n#define SYSTEMEXCEPTION_T176217640_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.SystemException\nstruct  SystemException_t176217640  : public Exception_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SYSTEMEXCEPTION_T176217640_H\n#ifndef TIMESPAN_T881159249_H\n#define TIMESPAN_T881159249_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.TimeSpan\nstruct  TimeSpan_t881159249 \n{\npublic:\n\t\/\/ System.Int64 System.TimeSpan::_ticks\n\tint64_t ____ticks_3;\n\npublic:\n\tinline static int32_t get_offset_of__ticks_3() { return static_cast<int32_t>(offsetof(TimeSpan_t881159249, ____ticks_3)); }\n\tinline int64_t get__ticks_3() const { return ____ticks_3; }\n\tinline int64_t* get_address_of__ticks_3() { return &____ticks_3; }\n\tinline void set__ticks_3(int64_t value)\n\t{\n\t\t____ticks_3 = value;\n\t}\n};\n\nstruct TimeSpan_t881159249_StaticFields\n{\npublic:\n\t\/\/ System.TimeSpan System.TimeSpan::MaxValue\n\tTimeSpan_t881159249  ___MaxValue_0;\n\t\/\/ System.TimeSpan System.TimeSpan::MinValue\n\tTimeSpan_t881159249  ___MinValue_1;\n\t\/\/ System.TimeSpan System.TimeSpan::Zero\n\tTimeSpan_t881159249  ___Zero_2;\n\npublic:\n\tinline static int32_t get_offset_of_MaxValue_0() { return static_cast<int32_t>(offsetof(TimeSpan_t881159249_StaticFields, ___MaxValue_0)); }\n\tinline TimeSpan_t881159249  get_MaxValue_0() const { return ___MaxValue_0; }\n\tinline TimeSpan_t881159249 * get_address_of_MaxValue_0() { return &___MaxValue_0; }\n\tinline void set_MaxValue_0(TimeSpan_t881159249  value)\n\t{\n\t\t___MaxValue_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_MinValue_1() { return static_cast<int32_t>(offsetof(TimeSpan_t881159249_StaticFields, ___MinValue_1)); }\n\tinline TimeSpan_t881159249  get_MinValue_1() const { return ___MinValue_1; }\n\tinline TimeSpan_t881159249 * get_address_of_MinValue_1() { return &___MinValue_1; }\n\tinline void set_MinValue_1(TimeSpan_t881159249  value)\n\t{\n\t\t___MinValue_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_Zero_2() { return static_cast<int32_t>(offsetof(TimeSpan_t881159249_StaticFields, ___Zero_2)); }\n\tinline TimeSpan_t881159249  get_Zero_2() const { return ___Zero_2; }\n\tinline TimeSpan_t881159249 * get_address_of_Zero_2() { return &___Zero_2; }\n\tinline void set_Zero_2(TimeSpan_t881159249  value)\n\t{\n\t\t___Zero_2 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ TIMESPAN_T881159249_H\n#ifndef VOID_T1185182177_H\n#define VOID_T1185182177_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Void\nstruct  Void_t1185182177 \n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ VOID_T1185182177_H\n#ifndef EDITORBROWSABLESTATE_T2839071299_H\n#define EDITORBROWSABLESTATE_T2839071299_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.EditorBrowsableState\nstruct  EditorBrowsableState_t2839071299 \n{\npublic:\n\t\/\/ System.Int32 System.ComponentModel.EditorBrowsableState::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(EditorBrowsableState_t2839071299, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ EDITORBROWSABLESTATE_T2839071299_H\n#ifndef DATETIMEKIND_T3468814247_H\n#define DATETIMEKIND_T3468814247_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.DateTimeKind\nstruct  DateTimeKind_t3468814247 \n{\npublic:\n\t\/\/ System.Int32 System.DateTimeKind::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(DateTimeKind_t3468814247, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DATETIMEKIND_T3468814247_H\n#ifndef DELEGATE_T1188392813_H\n#define DELEGATE_T1188392813_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Delegate\nstruct  Delegate_t1188392813  : public RuntimeObject\n{\npublic:\n\t\/\/ System.IntPtr System.Delegate::method_ptr\n\tIl2CppMethodPointer ___method_ptr_0;\n\t\/\/ System.IntPtr System.Delegate::invoke_impl\n\tintptr_t ___invoke_impl_1;\n\t\/\/ System.Object System.Delegate::m_target\n\tRuntimeObject * ___m_target_2;\n\t\/\/ System.IntPtr System.Delegate::method\n\tintptr_t ___method_3;\n\t\/\/ System.IntPtr System.Delegate::delegate_trampoline\n\tintptr_t ___delegate_trampoline_4;\n\t\/\/ System.IntPtr System.Delegate::method_code\n\tintptr_t ___method_code_5;\n\t\/\/ System.Reflection.MethodInfo System.Delegate::method_info\n\tMethodInfo_t * ___method_info_6;\n\t\/\/ System.Reflection.MethodInfo System.Delegate::original_method_info\n\tMethodInfo_t * ___original_method_info_7;\n\t\/\/ System.DelegateData System.Delegate::data\n\tDelegateData_t1677132599 * ___data_8;\n\npublic:\n\tinline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_ptr_0)); }\n\tinline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; }\n\tinline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; }\n\tinline void set_method_ptr_0(Il2CppMethodPointer value)\n\t{\n\t\t___method_ptr_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___invoke_impl_1)); }\n\tinline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; }\n\tinline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; }\n\tinline void set_invoke_impl_1(intptr_t value)\n\t{\n\t\t___invoke_impl_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___m_target_2)); }\n\tinline RuntimeObject * get_m_target_2() const { return ___m_target_2; }\n\tinline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; }\n\tinline void set_m_target_2(RuntimeObject * value)\n\t{\n\t\t___m_target_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_target_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_3)); }\n\tinline intptr_t get_method_3() const { return ___method_3; }\n\tinline intptr_t* get_address_of_method_3() { return &___method_3; }\n\tinline void set_method_3(intptr_t value)\n\t{\n\t\t___method_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___delegate_trampoline_4)); }\n\tinline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; }\n\tinline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; }\n\tinline void set_delegate_trampoline_4(intptr_t value)\n\t{\n\t\t___delegate_trampoline_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_method_code_5() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_code_5)); }\n\tinline intptr_t get_method_code_5() const { return ___method_code_5; }\n\tinline intptr_t* get_address_of_method_code_5() { return &___method_code_5; }\n\tinline void set_method_code_5(intptr_t value)\n\t{\n\t\t___method_code_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of_method_info_6() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_info_6)); }\n\tinline MethodInfo_t * get_method_info_6() const { return ___method_info_6; }\n\tinline MethodInfo_t ** get_address_of_method_info_6() { return &___method_info_6; }\n\tinline void set_method_info_6(MethodInfo_t * value)\n\t{\n\t\t___method_info_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___method_info_6), value);\n\t}\n\n\tinline static int32_t get_offset_of_original_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___original_method_info_7)); }\n\tinline MethodInfo_t * get_original_method_info_7() const { return ___original_method_info_7; }\n\tinline MethodInfo_t ** get_address_of_original_method_info_7() { return &___original_method_info_7; }\n\tinline void set_original_method_info_7(MethodInfo_t * value)\n\t{\n\t\t___original_method_info_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___original_method_info_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_data_8() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___data_8)); }\n\tinline DelegateData_t1677132599 * get_data_8() const { return ___data_8; }\n\tinline DelegateData_t1677132599 ** get_address_of_data_8() { return &___data_8; }\n\tinline void set_data_8(DelegateData_t1677132599 * value)\n\t{\n\t\t___data_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___data_8), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DELEGATE_T1188392813_H\n#ifndef FORMATEXCEPTION_T154580423_H\n#define FORMATEXCEPTION_T154580423_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.FormatException\nstruct  FormatException_t154580423  : public SystemException_t176217640\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FORMATEXCEPTION_T154580423_H\n#ifndef COMPRESSIONMODE_T3714291783_H\n#define COMPRESSIONMODE_T3714291783_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.IO.Compression.CompressionMode\nstruct  CompressionMode_t3714291783 \n{\npublic:\n\t\/\/ System.Int32 System.IO.Compression.CompressionMode::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(CompressionMode_t3714291783, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ COMPRESSIONMODE_T3714291783_H\n#ifndef FILEACCESS_T1659085276_H\n#define FILEACCESS_T1659085276_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.IO.FileAccess\nstruct  FileAccess_t1659085276 \n{\npublic:\n\t\/\/ System.Int32 System.IO.FileAccess::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(FileAccess_t1659085276, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FILEACCESS_T1659085276_H\n#ifndef STATE_T4053927353_H\n#define STATE_T4053927353_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.ChunkStream\/State\nstruct  State_t4053927353 \n{\npublic:\n\t\/\/ System.Int32 System.Net.ChunkStream\/State::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(State_t4053927353, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ STATE_T4053927353_H\n#ifndef DECOMPRESSIONMETHODS_T1612219745_H\n#define DECOMPRESSIONMETHODS_T1612219745_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.DecompressionMethods\nstruct  DecompressionMethods_t1612219745 \n{\npublic:\n\t\/\/ System.Int32 System.Net.DecompressionMethods::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(DecompressionMethods_t1612219745, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DECOMPRESSIONMETHODS_T1612219745_H\n#ifndef DOWNLOADPROGRESSCHANGEDEVENTARGS_T2828131725_H\n#define DOWNLOADPROGRESSCHANGEDEVENTARGS_T2828131725_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.DownloadProgressChangedEventArgs\nstruct  DownloadProgressChangedEventArgs_t2828131725  : public ProgressChangedEventArgs_t3227452477\n{\npublic:\n\t\/\/ System.Int64 System.Net.DownloadProgressChangedEventArgs::received\n\tint64_t ___received_3;\n\t\/\/ System.Int64 System.Net.DownloadProgressChangedEventArgs::total\n\tint64_t ___total_4;\n\npublic:\n\tinline static int32_t get_offset_of_received_3() { return static_cast<int32_t>(offsetof(DownloadProgressChangedEventArgs_t2828131725, ___received_3)); }\n\tinline int64_t get_received_3() const { return ___received_3; }\n\tinline int64_t* get_address_of_received_3() { return &___received_3; }\n\tinline void set_received_3(int64_t value)\n\t{\n\t\t___received_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_total_4() { return static_cast<int32_t>(offsetof(DownloadProgressChangedEventArgs_t2828131725, ___total_4)); }\n\tinline int64_t get_total_4() const { return ___total_4; }\n\tinline int64_t* get_address_of_total_4() { return &___total_4; }\n\tinline void set_total_4(int64_t value)\n\t{\n\t\t___total_4 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DOWNLOADPROGRESSCHANGEDEVENTARGS_T2828131725_H\n#ifndef FILEWEBRESPONSE_T544571260_H\n#define FILEWEBRESPONSE_T544571260_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FileWebResponse\nstruct  FileWebResponse_t544571260  : public WebResponse_t229922639\n{\npublic:\n\t\/\/ System.Uri System.Net.FileWebResponse::responseUri\n\tUri_t100236324 * ___responseUri_1;\n\t\/\/ System.IO.FileStream System.Net.FileWebResponse::fileStream\n\tFileStream_t4292183065 * ___fileStream_2;\n\t\/\/ System.Int64 System.Net.FileWebResponse::contentLength\n\tint64_t ___contentLength_3;\n\t\/\/ System.Net.WebHeaderCollection System.Net.FileWebResponse::webHeaders\n\tWebHeaderCollection_t1942268960 * ___webHeaders_4;\n\t\/\/ System.Boolean System.Net.FileWebResponse::disposed\n\tbool ___disposed_5;\n\npublic:\n\tinline static int32_t get_offset_of_responseUri_1() { return static_cast<int32_t>(offsetof(FileWebResponse_t544571260, ___responseUri_1)); }\n\tinline Uri_t100236324 * get_responseUri_1() const { return ___responseUri_1; }\n\tinline Uri_t100236324 ** get_address_of_responseUri_1() { return &___responseUri_1; }\n\tinline void set_responseUri_1(Uri_t100236324 * value)\n\t{\n\t\t___responseUri_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___responseUri_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_fileStream_2() { return static_cast<int32_t>(offsetof(FileWebResponse_t544571260, ___fileStream_2)); }\n\tinline FileStream_t4292183065 * get_fileStream_2() const { return ___fileStream_2; }\n\tinline FileStream_t4292183065 ** get_address_of_fileStream_2() { return &___fileStream_2; }\n\tinline void set_fileStream_2(FileStream_t4292183065 * value)\n\t{\n\t\t___fileStream_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___fileStream_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_contentLength_3() { return static_cast<int32_t>(offsetof(FileWebResponse_t544571260, ___contentLength_3)); }\n\tinline int64_t get_contentLength_3() const { return ___contentLength_3; }\n\tinline int64_t* get_address_of_contentLength_3() { return &___contentLength_3; }\n\tinline void set_contentLength_3(int64_t value)\n\t{\n\t\t___contentLength_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_webHeaders_4() { return static_cast<int32_t>(offsetof(FileWebResponse_t544571260, ___webHeaders_4)); }\n\tinline WebHeaderCollection_t1942268960 * get_webHeaders_4() const { return ___webHeaders_4; }\n\tinline WebHeaderCollection_t1942268960 ** get_address_of_webHeaders_4() { return &___webHeaders_4; }\n\tinline void set_webHeaders_4(WebHeaderCollection_t1942268960 * value)\n\t{\n\t\t___webHeaders_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___webHeaders_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_disposed_5() { return static_cast<int32_t>(offsetof(FileWebResponse_t544571260, ___disposed_5)); }\n\tinline bool get_disposed_5() const { return ___disposed_5; }\n\tinline bool* get_address_of_disposed_5() { return &___disposed_5; }\n\tinline void set_disposed_5(bool value)\n\t{\n\t\t___disposed_5 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FILEWEBRESPONSE_T544571260_H\n#ifndef FTPSTATUSCODE_T58879933_H\n#define FTPSTATUSCODE_T58879933_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FtpStatusCode\nstruct  FtpStatusCode_t58879933 \n{\npublic:\n\t\/\/ System.Int32 System.Net.FtpStatusCode::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(FtpStatusCode_t58879933, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FTPSTATUSCODE_T58879933_H\n#ifndef REQUESTSTATE_T4091696808_H\n#define REQUESTSTATE_T4091696808_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FtpWebRequest\/RequestState\nstruct  RequestState_t4091696808 \n{\npublic:\n\t\/\/ System.Int32 System.Net.FtpWebRequest\/RequestState::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(RequestState_t4091696808, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ REQUESTSTATE_T4091696808_H\n#ifndef HTTPREQUESTHEADER_T4258090762_H\n#define HTTPREQUESTHEADER_T4258090762_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.HttpRequestHeader\nstruct  HttpRequestHeader_t4258090762 \n{\npublic:\n\t\/\/ System.Int32 System.Net.HttpRequestHeader::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(HttpRequestHeader_t4258090762, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ HTTPREQUESTHEADER_T4258090762_H\n#ifndef HTTPRESPONSEHEADER_T1526164768_H\n#define HTTPRESPONSEHEADER_T1526164768_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.HttpResponseHeader\nstruct  HttpResponseHeader_t1526164768 \n{\npublic:\n\t\/\/ System.Int32 System.Net.HttpResponseHeader::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(HttpResponseHeader_t1526164768, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ HTTPRESPONSEHEADER_T1526164768_H\n#ifndef HTTPSTATUSCODE_T3035121829_H\n#define HTTPSTATUSCODE_T3035121829_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.HttpStatusCode\nstruct  HttpStatusCode_t3035121829 \n{\npublic:\n\t\/\/ System.Int32 System.Net.HttpStatusCode::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(HttpStatusCode_t3035121829, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ HTTPSTATUSCODE_T3035121829_H\n#ifndef AUTHENTICATIONLEVEL_T1236753641_H\n#define AUTHENTICATIONLEVEL_T1236753641_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Security.AuthenticationLevel\nstruct  AuthenticationLevel_t1236753641 \n{\npublic:\n\t\/\/ System.Int32 System.Net.Security.AuthenticationLevel::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(AuthenticationLevel_t1236753641, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ AUTHENTICATIONLEVEL_T1236753641_H\n#ifndef SSLPOLICYERRORS_T2205227823_H\n#define SSLPOLICYERRORS_T2205227823_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Security.SslPolicyErrors\nstruct  SslPolicyErrors_t2205227823 \n{\npublic:\n\t\/\/ System.Int32 System.Net.Security.SslPolicyErrors::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(SslPolicyErrors_t2205227823, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SSLPOLICYERRORS_T2205227823_H\n#ifndef SSLSTREAM_T2700741536_H\n#define SSLSTREAM_T2700741536_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Security.SslStream\nstruct  SslStream_t2700741536  : public AuthenticatedStream_t3415418016\n{\npublic:\n\t\/\/ Mono.Security.Protocol.Tls.SslStreamBase System.Net.Security.SslStream::ssl_stream\n\tSslStreamBase_t1667413407 * ___ssl_stream_3;\n\t\/\/ System.Net.Security.RemoteCertificateValidationCallback System.Net.Security.SslStream::validation_callback\n\tRemoteCertificateValidationCallback_t3014364904 * ___validation_callback_4;\n\t\/\/ System.Net.Security.LocalCertificateSelectionCallback System.Net.Security.SslStream::selection_callback\n\tLocalCertificateSelectionCallback_t2354453884 * ___selection_callback_5;\n\npublic:\n\tinline static int32_t get_offset_of_ssl_stream_3() { return static_cast<int32_t>(offsetof(SslStream_t2700741536, ___ssl_stream_3)); }\n\tinline SslStreamBase_t1667413407 * get_ssl_stream_3() const { return ___ssl_stream_3; }\n\tinline SslStreamBase_t1667413407 ** get_address_of_ssl_stream_3() { return &___ssl_stream_3; }\n\tinline void set_ssl_stream_3(SslStreamBase_t1667413407 * value)\n\t{\n\t\t___ssl_stream_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___ssl_stream_3), value);\n\t}\n\n\tinline static int32_t get_offset_of_validation_callback_4() { return static_cast<int32_t>(offsetof(SslStream_t2700741536, ___validation_callback_4)); }\n\tinline RemoteCertificateValidationCallback_t3014364904 * get_validation_callback_4() const { return ___validation_callback_4; }\n\tinline RemoteCertificateValidationCallback_t3014364904 ** get_address_of_validation_callback_4() { return &___validation_callback_4; }\n\tinline void set_validation_callback_4(RemoteCertificateValidationCallback_t3014364904 * value)\n\t{\n\t\t___validation_callback_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___validation_callback_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_selection_callback_5() { return static_cast<int32_t>(offsetof(SslStream_t2700741536, ___selection_callback_5)); }\n\tinline LocalCertificateSelectionCallback_t2354453884 * get_selection_callback_5() const { return ___selection_callback_5; }\n\tinline LocalCertificateSelectionCallback_t2354453884 ** get_address_of_selection_callback_5() { return &___selection_callback_5; }\n\tinline void set_selection_callback_5(LocalCertificateSelectionCallback_t2354453884 * value)\n\t{\n\t\t___selection_callback_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___selection_callback_5), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SSLSTREAM_T2700741536_H\n#ifndef ADDRESSFAMILY_T2612549059_H\n#define ADDRESSFAMILY_T2612549059_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.AddressFamily\nstruct  AddressFamily_t2612549059 \n{\npublic:\n\t\/\/ System.Int32 System.Net.Sockets.AddressFamily::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(AddressFamily_t2612549059, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ ADDRESSFAMILY_T2612549059_H\n#ifndef PROTOCOLTYPE_T303635025_H\n#define PROTOCOLTYPE_T303635025_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.ProtocolType\nstruct  ProtocolType_t303635025 \n{\npublic:\n\t\/\/ System.Int32 System.Net.Sockets.ProtocolType::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ProtocolType_t303635025, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ PROTOCOLTYPE_T303635025_H\n#ifndef SELECTMODE_T1123767949_H\n#define SELECTMODE_T1123767949_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.SelectMode\nstruct  SelectMode_t1123767949 \n{\npublic:\n\t\/\/ System.Int32 System.Net.Sockets.SelectMode::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(SelectMode_t1123767949, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SELECTMODE_T1123767949_H\n#ifndef SOCKETOPERATION_T1288882297_H\n#define SOCKETOPERATION_T1288882297_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.Socket\/SocketOperation\nstruct  SocketOperation_t1288882297 \n{\npublic:\n\t\/\/ System.Int32 System.Net.Sockets.Socket\/SocketOperation::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(SocketOperation_t1288882297, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SOCKETOPERATION_T1288882297_H\n#ifndef SOCKETERROR_T3760144386_H\n#define SOCKETERROR_T3760144386_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.SocketError\nstruct  SocketError_t3760144386 \n{\npublic:\n\t\/\/ System.Int32 System.Net.Sockets.SocketError::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(SocketError_t3760144386, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SOCKETERROR_T3760144386_H\n#ifndef SOCKETFLAGS_T2969870452_H\n#define SOCKETFLAGS_T2969870452_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.SocketFlags\nstruct  SocketFlags_t2969870452 \n{\npublic:\n\t\/\/ System.Int32 System.Net.Sockets.SocketFlags::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(SocketFlags_t2969870452, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SOCKETFLAGS_T2969870452_H\n#ifndef SOCKETOPTIONLEVEL_T201167901_H\n#define SOCKETOPTIONLEVEL_T201167901_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.SocketOptionLevel\nstruct  SocketOptionLevel_t201167901 \n{\npublic:\n\t\/\/ System.Int32 System.Net.Sockets.SocketOptionLevel::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(SocketOptionLevel_t201167901, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SOCKETOPTIONLEVEL_T201167901_H\n#ifndef SOCKETOPTIONNAME_T403346465_H\n#define SOCKETOPTIONNAME_T403346465_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.SocketOptionName\nstruct  SocketOptionName_t403346465 \n{\npublic:\n\t\/\/ System.Int32 System.Net.Sockets.SocketOptionName::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(SocketOptionName_t403346465, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SOCKETOPTIONNAME_T403346465_H\n#ifndef SOCKETSHUTDOWN_T2687738148_H\n#define SOCKETSHUTDOWN_T2687738148_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.SocketShutdown\nstruct  SocketShutdown_t2687738148 \n{\npublic:\n\t\/\/ System.Int32 System.Net.Sockets.SocketShutdown::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(SocketShutdown_t2687738148, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SOCKETSHUTDOWN_T2687738148_H\n#ifndef SOCKETTYPE_T2175930299_H\n#define SOCKETTYPE_T2175930299_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.SocketType\nstruct  SocketType_t2175930299 \n{\npublic:\n\t\/\/ System.Int32 System.Net.Sockets.SocketType::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(SocketType_t2175930299, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SOCKETTYPE_T2175930299_H\n#ifndef EXTERNALEXCEPTION_T3544951457_H\n#define EXTERNALEXCEPTION_T3544951457_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Runtime.InteropServices.ExternalException\nstruct  ExternalException_t3544951457  : public SystemException_t176217640\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ EXTERNALEXCEPTION_T3544951457_H\n#ifndef EDITORBROWSABLEATTRIBUTE_T1475454531_H\n#define EDITORBROWSABLEATTRIBUTE_T1475454531_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.EditorBrowsableAttribute\nstruct  EditorBrowsableAttribute_t1475454531  : public Attribute_t861562559\n{\npublic:\n\t\/\/ System.ComponentModel.EditorBrowsableState System.ComponentModel.EditorBrowsableAttribute::state\n\tint32_t ___state_0;\n\npublic:\n\tinline static int32_t get_offset_of_state_0() { return static_cast<int32_t>(offsetof(EditorBrowsableAttribute_t1475454531, ___state_0)); }\n\tinline int32_t get_state_0() const { return ___state_0; }\n\tinline int32_t* get_address_of_state_0() { return &___state_0; }\n\tinline void set_state_0(int32_t value)\n\t{\n\t\t___state_0 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ EDITORBROWSABLEATTRIBUTE_T1475454531_H\n#ifndef WIN32EXCEPTION_T3234146298_H\n#define WIN32EXCEPTION_T3234146298_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ComponentModel.Win32Exception\nstruct  Win32Exception_t3234146298  : public ExternalException_t3544951457\n{\npublic:\n\t\/\/ System.Int32 System.ComponentModel.Win32Exception::native_error_code\n\tint32_t ___native_error_code_11;\n\npublic:\n\tinline static int32_t get_offset_of_native_error_code_11() { return static_cast<int32_t>(offsetof(Win32Exception_t3234146298, ___native_error_code_11)); }\n\tinline int32_t get_native_error_code_11() const { return ___native_error_code_11; }\n\tinline int32_t* get_address_of_native_error_code_11() { return &___native_error_code_11; }\n\tinline void set_native_error_code_11(int32_t value)\n\t{\n\t\t___native_error_code_11 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ WIN32EXCEPTION_T3234146298_H\n#ifndef DATETIME_T3738529785_H\n#define DATETIME_T3738529785_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.DateTime\nstruct  DateTime_t3738529785 \n{\npublic:\n\t\/\/ System.TimeSpan System.DateTime::ticks\n\tTimeSpan_t881159249  ___ticks_0;\n\t\/\/ System.DateTimeKind System.DateTime::kind\n\tint32_t ___kind_1;\n\npublic:\n\tinline static int32_t get_offset_of_ticks_0() { return static_cast<int32_t>(offsetof(DateTime_t3738529785, ___ticks_0)); }\n\tinline TimeSpan_t881159249  get_ticks_0() const { return ___ticks_0; }\n\tinline TimeSpan_t881159249 * get_address_of_ticks_0() { return &___ticks_0; }\n\tinline void set_ticks_0(TimeSpan_t881159249  value)\n\t{\n\t\t___ticks_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_kind_1() { return static_cast<int32_t>(offsetof(DateTime_t3738529785, ___kind_1)); }\n\tinline int32_t get_kind_1() const { return ___kind_1; }\n\tinline int32_t* get_address_of_kind_1() { return &___kind_1; }\n\tinline void set_kind_1(int32_t value)\n\t{\n\t\t___kind_1 = value;\n\t}\n};\n\nstruct DateTime_t3738529785_StaticFields\n{\npublic:\n\t\/\/ System.DateTime System.DateTime::MaxValue\n\tDateTime_t3738529785  ___MaxValue_2;\n\t\/\/ System.DateTime System.DateTime::MinValue\n\tDateTime_t3738529785  ___MinValue_3;\n\t\/\/ System.String[] System.DateTime::ParseTimeFormats\n\tStringU5BU5D_t1281789340* ___ParseTimeFormats_4;\n\t\/\/ System.String[] System.DateTime::ParseYearDayMonthFormats\n\tStringU5BU5D_t1281789340* ___ParseYearDayMonthFormats_5;\n\t\/\/ System.String[] System.DateTime::ParseYearMonthDayFormats\n\tStringU5BU5D_t1281789340* ___ParseYearMonthDayFormats_6;\n\t\/\/ System.String[] System.DateTime::ParseDayMonthYearFormats\n\tStringU5BU5D_t1281789340* ___ParseDayMonthYearFormats_7;\n\t\/\/ System.String[] System.DateTime::ParseMonthDayYearFormats\n\tStringU5BU5D_t1281789340* ___ParseMonthDayYearFormats_8;\n\t\/\/ System.String[] System.DateTime::MonthDayShortFormats\n\tStringU5BU5D_t1281789340* ___MonthDayShortFormats_9;\n\t\/\/ System.String[] System.DateTime::DayMonthShortFormats\n\tStringU5BU5D_t1281789340* ___DayMonthShortFormats_10;\n\t\/\/ System.Int32[] System.DateTime::daysmonth\n\tInt32U5BU5D_t385246372* ___daysmonth_11;\n\t\/\/ System.Int32[] System.DateTime::daysmonthleap\n\tInt32U5BU5D_t385246372* ___daysmonthleap_12;\n\t\/\/ System.Object System.DateTime::to_local_time_span_object\n\tRuntimeObject * ___to_local_time_span_object_13;\n\t\/\/ System.Int64 System.DateTime::last_now\n\tint64_t ___last_now_14;\n\npublic:\n\tinline static int32_t get_offset_of_MaxValue_2() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___MaxValue_2)); }\n\tinline DateTime_t3738529785  get_MaxValue_2() const { return ___MaxValue_2; }\n\tinline DateTime_t3738529785 * get_address_of_MaxValue_2() { return &___MaxValue_2; }\n\tinline void set_MaxValue_2(DateTime_t3738529785  value)\n\t{\n\t\t___MaxValue_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_MinValue_3() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___MinValue_3)); }\n\tinline DateTime_t3738529785  get_MinValue_3() const { return ___MinValue_3; }\n\tinline DateTime_t3738529785 * get_address_of_MinValue_3() { return &___MinValue_3; }\n\tinline void set_MinValue_3(DateTime_t3738529785  value)\n\t{\n\t\t___MinValue_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_ParseTimeFormats_4() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___ParseTimeFormats_4)); }\n\tinline StringU5BU5D_t1281789340* get_ParseTimeFormats_4() const { return ___ParseTimeFormats_4; }\n\tinline StringU5BU5D_t1281789340** get_address_of_ParseTimeFormats_4() { return &___ParseTimeFormats_4; }\n\tinline void set_ParseTimeFormats_4(StringU5BU5D_t1281789340* value)\n\t{\n\t\t___ParseTimeFormats_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___ParseTimeFormats_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_ParseYearDayMonthFormats_5() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___ParseYearDayMonthFormats_5)); }\n\tinline StringU5BU5D_t1281789340* get_ParseYearDayMonthFormats_5() const { return ___ParseYearDayMonthFormats_5; }\n\tinline StringU5BU5D_t1281789340** get_address_of_ParseYearDayMonthFormats_5() { return &___ParseYearDayMonthFormats_5; }\n\tinline void set_ParseYearDayMonthFormats_5(StringU5BU5D_t1281789340* value)\n\t{\n\t\t___ParseYearDayMonthFormats_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___ParseYearDayMonthFormats_5), value);\n\t}\n\n\tinline static int32_t get_offset_of_ParseYearMonthDayFormats_6() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___ParseYearMonthDayFormats_6)); }\n\tinline StringU5BU5D_t1281789340* get_ParseYearMonthDayFormats_6() const { return ___ParseYearMonthDayFormats_6; }\n\tinline StringU5BU5D_t1281789340** get_address_of_ParseYearMonthDayFormats_6() { return &___ParseYearMonthDayFormats_6; }\n\tinline void set_ParseYearMonthDayFormats_6(StringU5BU5D_t1281789340* value)\n\t{\n\t\t___ParseYearMonthDayFormats_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___ParseYearMonthDayFormats_6), value);\n\t}\n\n\tinline static int32_t get_offset_of_ParseDayMonthYearFormats_7() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___ParseDayMonthYearFormats_7)); }\n\tinline StringU5BU5D_t1281789340* get_ParseDayMonthYearFormats_7() const { return ___ParseDayMonthYearFormats_7; }\n\tinline StringU5BU5D_t1281789340** get_address_of_ParseDayMonthYearFormats_7() { return &___ParseDayMonthYearFormats_7; }\n\tinline void set_ParseDayMonthYearFormats_7(StringU5BU5D_t1281789340* value)\n\t{\n\t\t___ParseDayMonthYearFormats_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___ParseDayMonthYearFormats_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_ParseMonthDayYearFormats_8() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___ParseMonthDayYearFormats_8)); }\n\tinline StringU5BU5D_t1281789340* get_ParseMonthDayYearFormats_8() const { return ___ParseMonthDayYearFormats_8; }\n\tinline StringU5BU5D_t1281789340** get_address_of_ParseMonthDayYearFormats_8() { return &___ParseMonthDayYearFormats_8; }\n\tinline void set_ParseMonthDayYearFormats_8(StringU5BU5D_t1281789340* value)\n\t{\n\t\t___ParseMonthDayYearFormats_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___ParseMonthDayYearFormats_8), value);\n\t}\n\n\tinline static int32_t get_offset_of_MonthDayShortFormats_9() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___MonthDayShortFormats_9)); }\n\tinline StringU5BU5D_t1281789340* get_MonthDayShortFormats_9() const { return ___MonthDayShortFormats_9; }\n\tinline StringU5BU5D_t1281789340** get_address_of_MonthDayShortFormats_9() { return &___MonthDayShortFormats_9; }\n\tinline void set_MonthDayShortFormats_9(StringU5BU5D_t1281789340* value)\n\t{\n\t\t___MonthDayShortFormats_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___MonthDayShortFormats_9), value);\n\t}\n\n\tinline static int32_t get_offset_of_DayMonthShortFormats_10() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___DayMonthShortFormats_10)); }\n\tinline StringU5BU5D_t1281789340* get_DayMonthShortFormats_10() const { return ___DayMonthShortFormats_10; }\n\tinline StringU5BU5D_t1281789340** get_address_of_DayMonthShortFormats_10() { return &___DayMonthShortFormats_10; }\n\tinline void set_DayMonthShortFormats_10(StringU5BU5D_t1281789340* value)\n\t{\n\t\t___DayMonthShortFormats_10 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___DayMonthShortFormats_10), value);\n\t}\n\n\tinline static int32_t get_offset_of_daysmonth_11() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___daysmonth_11)); }\n\tinline Int32U5BU5D_t385246372* get_daysmonth_11() const { return ___daysmonth_11; }\n\tinline Int32U5BU5D_t385246372** get_address_of_daysmonth_11() { return &___daysmonth_11; }\n\tinline void set_daysmonth_11(Int32U5BU5D_t385246372* value)\n\t{\n\t\t___daysmonth_11 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___daysmonth_11), value);\n\t}\n\n\tinline static int32_t get_offset_of_daysmonthleap_12() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___daysmonthleap_12)); }\n\tinline Int32U5BU5D_t385246372* get_daysmonthleap_12() const { return ___daysmonthleap_12; }\n\tinline Int32U5BU5D_t385246372** get_address_of_daysmonthleap_12() { return &___daysmonthleap_12; }\n\tinline void set_daysmonthleap_12(Int32U5BU5D_t385246372* value)\n\t{\n\t\t___daysmonthleap_12 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___daysmonthleap_12), value);\n\t}\n\n\tinline static int32_t get_offset_of_to_local_time_span_object_13() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___to_local_time_span_object_13)); }\n\tinline RuntimeObject * get_to_local_time_span_object_13() const { return ___to_local_time_span_object_13; }\n\tinline RuntimeObject ** get_address_of_to_local_time_span_object_13() { return &___to_local_time_span_object_13; }\n\tinline void set_to_local_time_span_object_13(RuntimeObject * value)\n\t{\n\t\t___to_local_time_span_object_13 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___to_local_time_span_object_13), value);\n\t}\n\n\tinline static int32_t get_offset_of_last_now_14() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___last_now_14)); }\n\tinline int64_t get_last_now_14() const { return ___last_now_14; }\n\tinline int64_t* get_address_of_last_now_14() { return &___last_now_14; }\n\tinline void set_last_now_14(int64_t value)\n\t{\n\t\t___last_now_14 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DATETIME_T3738529785_H\n#ifndef DEFLATESTREAM_T4175168077_H\n#define DEFLATESTREAM_T4175168077_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.IO.Compression.DeflateStream\nstruct  DeflateStream_t4175168077  : public Stream_t1273022909\n{\npublic:\n\t\/\/ System.IO.Stream System.IO.Compression.DeflateStream::base_stream\n\tStream_t1273022909 * ___base_stream_1;\n\t\/\/ System.IO.Compression.CompressionMode System.IO.Compression.DeflateStream::mode\n\tint32_t ___mode_2;\n\t\/\/ System.Boolean System.IO.Compression.DeflateStream::leaveOpen\n\tbool ___leaveOpen_3;\n\t\/\/ System.Boolean System.IO.Compression.DeflateStream::disposed\n\tbool ___disposed_4;\n\t\/\/ System.IO.Compression.DeflateStream\/UnmanagedReadOrWrite System.IO.Compression.DeflateStream::feeder\n\tUnmanagedReadOrWrite_t876388624 * ___feeder_5;\n\t\/\/ System.IntPtr System.IO.Compression.DeflateStream::z_stream\n\tintptr_t ___z_stream_6;\n\t\/\/ System.Byte[] System.IO.Compression.DeflateStream::io_buffer\n\tByteU5BU5D_t4116647657* ___io_buffer_7;\n\t\/\/ System.Runtime.InteropServices.GCHandle System.IO.Compression.DeflateStream::data\n\tGCHandle_t3351438187  ___data_8;\n\npublic:\n\tinline static int32_t get_offset_of_base_stream_1() { return static_cast<int32_t>(offsetof(DeflateStream_t4175168077, ___base_stream_1)); }\n\tinline Stream_t1273022909 * get_base_stream_1() const { return ___base_stream_1; }\n\tinline Stream_t1273022909 ** get_address_of_base_stream_1() { return &___base_stream_1; }\n\tinline void set_base_stream_1(Stream_t1273022909 * value)\n\t{\n\t\t___base_stream_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___base_stream_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_mode_2() { return static_cast<int32_t>(offsetof(DeflateStream_t4175168077, ___mode_2)); }\n\tinline int32_t get_mode_2() const { return ___mode_2; }\n\tinline int32_t* get_address_of_mode_2() { return &___mode_2; }\n\tinline void set_mode_2(int32_t value)\n\t{\n\t\t___mode_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_leaveOpen_3() { return static_cast<int32_t>(offsetof(DeflateStream_t4175168077, ___leaveOpen_3)); }\n\tinline bool get_leaveOpen_3() const { return ___leaveOpen_3; }\n\tinline bool* get_address_of_leaveOpen_3() { return &___leaveOpen_3; }\n\tinline void set_leaveOpen_3(bool value)\n\t{\n\t\t___leaveOpen_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_disposed_4() { return static_cast<int32_t>(offsetof(DeflateStream_t4175168077, ___disposed_4)); }\n\tinline bool get_disposed_4() const { return ___disposed_4; }\n\tinline bool* get_address_of_disposed_4() { return &___disposed_4; }\n\tinline void set_disposed_4(bool value)\n\t{\n\t\t___disposed_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_feeder_5() { return static_cast<int32_t>(offsetof(DeflateStream_t4175168077, ___feeder_5)); }\n\tinline UnmanagedReadOrWrite_t876388624 * get_feeder_5() const { return ___feeder_5; }\n\tinline UnmanagedReadOrWrite_t876388624 ** get_address_of_feeder_5() { return &___feeder_5; }\n\tinline void set_feeder_5(UnmanagedReadOrWrite_t876388624 * value)\n\t{\n\t\t___feeder_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___feeder_5), value);\n\t}\n\n\tinline static int32_t get_offset_of_z_stream_6() { return static_cast<int32_t>(offsetof(DeflateStream_t4175168077, ___z_stream_6)); }\n\tinline intptr_t get_z_stream_6() const { return ___z_stream_6; }\n\tinline intptr_t* get_address_of_z_stream_6() { return &___z_stream_6; }\n\tinline void set_z_stream_6(intptr_t value)\n\t{\n\t\t___z_stream_6 = value;\n\t}\n\n\tinline static int32_t get_offset_of_io_buffer_7() { return static_cast<int32_t>(offsetof(DeflateStream_t4175168077, ___io_buffer_7)); }\n\tinline ByteU5BU5D_t4116647657* get_io_buffer_7() const { return ___io_buffer_7; }\n\tinline ByteU5BU5D_t4116647657** get_address_of_io_buffer_7() { return &___io_buffer_7; }\n\tinline void set_io_buffer_7(ByteU5BU5D_t4116647657* value)\n\t{\n\t\t___io_buffer_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___io_buffer_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_data_8() { return static_cast<int32_t>(offsetof(DeflateStream_t4175168077, ___data_8)); }\n\tinline GCHandle_t3351438187  get_data_8() const { return ___data_8; }\n\tinline GCHandle_t3351438187 * get_address_of_data_8() { return &___data_8; }\n\tinline void set_data_8(GCHandle_t3351438187  value)\n\t{\n\t\t___data_8 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DEFLATESTREAM_T4175168077_H\n#ifndef FILESTREAM_T4292183065_H\n#define FILESTREAM_T4292183065_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.IO.FileStream\nstruct  FileStream_t4292183065  : public Stream_t1273022909\n{\npublic:\n\t\/\/ System.IO.FileAccess System.IO.FileStream::access\n\tint32_t ___access_1;\n\t\/\/ System.Boolean System.IO.FileStream::owner\n\tbool ___owner_2;\n\t\/\/ System.Boolean System.IO.FileStream::async\n\tbool ___async_3;\n\t\/\/ System.Boolean System.IO.FileStream::canseek\n\tbool ___canseek_4;\n\t\/\/ System.Int64 System.IO.FileStream::append_startpos\n\tint64_t ___append_startpos_5;\n\t\/\/ System.Boolean System.IO.FileStream::anonymous\n\tbool ___anonymous_6;\n\t\/\/ System.Byte[] System.IO.FileStream::buf\n\tByteU5BU5D_t4116647657* ___buf_7;\n\t\/\/ System.Int32 System.IO.FileStream::buf_size\n\tint32_t ___buf_size_8;\n\t\/\/ System.Int32 System.IO.FileStream::buf_length\n\tint32_t ___buf_length_9;\n\t\/\/ System.Int32 System.IO.FileStream::buf_offset\n\tint32_t ___buf_offset_10;\n\t\/\/ System.Boolean System.IO.FileStream::buf_dirty\n\tbool ___buf_dirty_11;\n\t\/\/ System.Int64 System.IO.FileStream::buf_start\n\tint64_t ___buf_start_12;\n\t\/\/ System.String System.IO.FileStream::name\n\tString_t* ___name_13;\n\t\/\/ System.IntPtr System.IO.FileStream::handle\n\tintptr_t ___handle_14;\n\npublic:\n\tinline static int32_t get_offset_of_access_1() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___access_1)); }\n\tinline int32_t get_access_1() const { return ___access_1; }\n\tinline int32_t* get_address_of_access_1() { return &___access_1; }\n\tinline void set_access_1(int32_t value)\n\t{\n\t\t___access_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_owner_2() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___owner_2)); }\n\tinline bool get_owner_2() const { return ___owner_2; }\n\tinline bool* get_address_of_owner_2() { return &___owner_2; }\n\tinline void set_owner_2(bool value)\n\t{\n\t\t___owner_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_async_3() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___async_3)); }\n\tinline bool get_async_3() const { return ___async_3; }\n\tinline bool* get_address_of_async_3() { return &___async_3; }\n\tinline void set_async_3(bool value)\n\t{\n\t\t___async_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_canseek_4() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___canseek_4)); }\n\tinline bool get_canseek_4() const { return ___canseek_4; }\n\tinline bool* get_address_of_canseek_4() { return &___canseek_4; }\n\tinline void set_canseek_4(bool value)\n\t{\n\t\t___canseek_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_append_startpos_5() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___append_startpos_5)); }\n\tinline int64_t get_append_startpos_5() const { return ___append_startpos_5; }\n\tinline int64_t* get_address_of_append_startpos_5() { return &___append_startpos_5; }\n\tinline void set_append_startpos_5(int64_t value)\n\t{\n\t\t___append_startpos_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of_anonymous_6() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___anonymous_6)); }\n\tinline bool get_anonymous_6() const { return ___anonymous_6; }\n\tinline bool* get_address_of_anonymous_6() { return &___anonymous_6; }\n\tinline void set_anonymous_6(bool value)\n\t{\n\t\t___anonymous_6 = value;\n\t}\n\n\tinline static int32_t get_offset_of_buf_7() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___buf_7)); }\n\tinline ByteU5BU5D_t4116647657* get_buf_7() const { return ___buf_7; }\n\tinline ByteU5BU5D_t4116647657** get_address_of_buf_7() { return &___buf_7; }\n\tinline void set_buf_7(ByteU5BU5D_t4116647657* value)\n\t{\n\t\t___buf_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___buf_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_buf_size_8() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___buf_size_8)); }\n\tinline int32_t get_buf_size_8() const { return ___buf_size_8; }\n\tinline int32_t* get_address_of_buf_size_8() { return &___buf_size_8; }\n\tinline void set_buf_size_8(int32_t value)\n\t{\n\t\t___buf_size_8 = value;\n\t}\n\n\tinline static int32_t get_offset_of_buf_length_9() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___buf_length_9)); }\n\tinline int32_t get_buf_length_9() const { return ___buf_length_9; }\n\tinline int32_t* get_address_of_buf_length_9() { return &___buf_length_9; }\n\tinline void set_buf_length_9(int32_t value)\n\t{\n\t\t___buf_length_9 = value;\n\t}\n\n\tinline static int32_t get_offset_of_buf_offset_10() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___buf_offset_10)); }\n\tinline int32_t get_buf_offset_10() const { return ___buf_offset_10; }\n\tinline int32_t* get_address_of_buf_offset_10() { return &___buf_offset_10; }\n\tinline void set_buf_offset_10(int32_t value)\n\t{\n\t\t___buf_offset_10 = value;\n\t}\n\n\tinline static int32_t get_offset_of_buf_dirty_11() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___buf_dirty_11)); }\n\tinline bool get_buf_dirty_11() const { return ___buf_dirty_11; }\n\tinline bool* get_address_of_buf_dirty_11() { return &___buf_dirty_11; }\n\tinline void set_buf_dirty_11(bool value)\n\t{\n\t\t___buf_dirty_11 = value;\n\t}\n\n\tinline static int32_t get_offset_of_buf_start_12() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___buf_start_12)); }\n\tinline int64_t get_buf_start_12() const { return ___buf_start_12; }\n\tinline int64_t* get_address_of_buf_start_12() { return &___buf_start_12; }\n\tinline void set_buf_start_12(int64_t value)\n\t{\n\t\t___buf_start_12 = value;\n\t}\n\n\tinline static int32_t get_offset_of_name_13() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___name_13)); }\n\tinline String_t* get_name_13() const { return ___name_13; }\n\tinline String_t** get_address_of_name_13() { return &___name_13; }\n\tinline void set_name_13(String_t* value)\n\t{\n\t\t___name_13 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___name_13), value);\n\t}\n\n\tinline static int32_t get_offset_of_handle_14() { return static_cast<int32_t>(offsetof(FileStream_t4292183065, ___handle_14)); }\n\tinline intptr_t get_handle_14() const { return ___handle_14; }\n\tinline intptr_t* get_address_of_handle_14() { return &___handle_14; }\n\tinline void set_handle_14(intptr_t value)\n\t{\n\t\t___handle_14 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FILESTREAM_T4292183065_H\n#ifndef MULTICASTDELEGATE_T_H\n#define MULTICASTDELEGATE_T_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.MulticastDelegate\nstruct  MulticastDelegate_t  : public Delegate_t1188392813\n{\npublic:\n\t\/\/ System.MulticastDelegate System.MulticastDelegate::prev\n\tMulticastDelegate_t * ___prev_9;\n\t\/\/ System.MulticastDelegate System.MulticastDelegate::kpm_next\n\tMulticastDelegate_t * ___kpm_next_10;\n\npublic:\n\tinline static int32_t get_offset_of_prev_9() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___prev_9)); }\n\tinline MulticastDelegate_t * get_prev_9() const { return ___prev_9; }\n\tinline MulticastDelegate_t ** get_address_of_prev_9() { return &___prev_9; }\n\tinline void set_prev_9(MulticastDelegate_t * value)\n\t{\n\t\t___prev_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___prev_9), value);\n\t}\n\n\tinline static int32_t get_offset_of_kpm_next_10() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___kpm_next_10)); }\n\tinline MulticastDelegate_t * get_kpm_next_10() const { return ___kpm_next_10; }\n\tinline MulticastDelegate_t ** get_address_of_kpm_next_10() { return &___kpm_next_10; }\n\tinline void set_kpm_next_10(MulticastDelegate_t * value)\n\t{\n\t\t___kpm_next_10 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___kpm_next_10), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ MULTICASTDELEGATE_T_H\n#ifndef CHUNKSTREAM_T2634567336_H\n#define CHUNKSTREAM_T2634567336_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.ChunkStream\nstruct  ChunkStream_t2634567336  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Net.WebHeaderCollection System.Net.ChunkStream::headers\n\tWebHeaderCollection_t1942268960 * ___headers_0;\n\t\/\/ System.Int32 System.Net.ChunkStream::chunkSize\n\tint32_t ___chunkSize_1;\n\t\/\/ System.Int32 System.Net.ChunkStream::chunkRead\n\tint32_t ___chunkRead_2;\n\t\/\/ System.Net.ChunkStream\/State System.Net.ChunkStream::state\n\tint32_t ___state_3;\n\t\/\/ System.Text.StringBuilder System.Net.ChunkStream::saved\n\tStringBuilder_t * ___saved_4;\n\t\/\/ System.Boolean System.Net.ChunkStream::sawCR\n\tbool ___sawCR_5;\n\t\/\/ System.Boolean System.Net.ChunkStream::gotit\n\tbool ___gotit_6;\n\t\/\/ System.Int32 System.Net.ChunkStream::trailerState\n\tint32_t ___trailerState_7;\n\t\/\/ System.Collections.ArrayList System.Net.ChunkStream::chunks\n\tArrayList_t2718874744 * ___chunks_8;\n\npublic:\n\tinline static int32_t get_offset_of_headers_0() { return static_cast<int32_t>(offsetof(ChunkStream_t2634567336, ___headers_0)); }\n\tinline WebHeaderCollection_t1942268960 * get_headers_0() const { return ___headers_0; }\n\tinline WebHeaderCollection_t1942268960 ** get_address_of_headers_0() { return &___headers_0; }\n\tinline void set_headers_0(WebHeaderCollection_t1942268960 * value)\n\t{\n\t\t___headers_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___headers_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_chunkSize_1() { return static_cast<int32_t>(offsetof(ChunkStream_t2634567336, ___chunkSize_1)); }\n\tinline int32_t get_chunkSize_1() const { return ___chunkSize_1; }\n\tinline int32_t* get_address_of_chunkSize_1() { return &___chunkSize_1; }\n\tinline void set_chunkSize_1(int32_t value)\n\t{\n\t\t___chunkSize_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_chunkRead_2() { return static_cast<int32_t>(offsetof(ChunkStream_t2634567336, ___chunkRead_2)); }\n\tinline int32_t get_chunkRead_2() const { return ___chunkRead_2; }\n\tinline int32_t* get_address_of_chunkRead_2() { return &___chunkRead_2; }\n\tinline void set_chunkRead_2(int32_t value)\n\t{\n\t\t___chunkRead_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_state_3() { return static_cast<int32_t>(offsetof(ChunkStream_t2634567336, ___state_3)); }\n\tinline int32_t get_state_3() const { return ___state_3; }\n\tinline int32_t* get_address_of_state_3() { return &___state_3; }\n\tinline void set_state_3(int32_t value)\n\t{\n\t\t___state_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_saved_4() { return static_cast<int32_t>(offsetof(ChunkStream_t2634567336, ___saved_4)); }\n\tinline StringBuilder_t * get_saved_4() const { return ___saved_4; }\n\tinline StringBuilder_t ** get_address_of_saved_4() { return &___saved_4; }\n\tinline void set_saved_4(StringBuilder_t * value)\n\t{\n\t\t___saved_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___saved_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_sawCR_5() { return static_cast<int32_t>(offsetof(ChunkStream_t2634567336, ___sawCR_5)); }\n\tinline bool get_sawCR_5() const { return ___sawCR_5; }\n\tinline bool* get_address_of_sawCR_5() { return &___sawCR_5; }\n\tinline void set_sawCR_5(bool value)\n\t{\n\t\t___sawCR_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of_gotit_6() { return static_cast<int32_t>(offsetof(ChunkStream_t2634567336, ___gotit_6)); }\n\tinline bool get_gotit_6() const { return ___gotit_6; }\n\tinline bool* get_address_of_gotit_6() { return &___gotit_6; }\n\tinline void set_gotit_6(bool value)\n\t{\n\t\t___gotit_6 = value;\n\t}\n\n\tinline static int32_t get_offset_of_trailerState_7() { return static_cast<int32_t>(offsetof(ChunkStream_t2634567336, ___trailerState_7)); }\n\tinline int32_t get_trailerState_7() const { return ___trailerState_7; }\n\tinline int32_t* get_address_of_trailerState_7() { return &___trailerState_7; }\n\tinline void set_trailerState_7(int32_t value)\n\t{\n\t\t___trailerState_7 = value;\n\t}\n\n\tinline static int32_t get_offset_of_chunks_8() { return static_cast<int32_t>(offsetof(ChunkStream_t2634567336, ___chunks_8)); }\n\tinline ArrayList_t2718874744 * get_chunks_8() const { return ___chunks_8; }\n\tinline ArrayList_t2718874744 ** get_address_of_chunks_8() { return &___chunks_8; }\n\tinline void set_chunks_8(ArrayList_t2718874744 * value)\n\t{\n\t\t___chunks_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___chunks_8), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ CHUNKSTREAM_T2634567336_H\n#ifndef COOKIEEXCEPTION_T2325395694_H\n#define COOKIEEXCEPTION_T2325395694_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.CookieException\nstruct  CookieException_t2325395694  : public FormatException_t154580423\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ COOKIEEXCEPTION_T2325395694_H\n#ifndef FTPSTATUS_T2376455776_H\n#define FTPSTATUS_T2376455776_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FtpStatus\nstruct  FtpStatus_t2376455776  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Net.FtpStatusCode System.Net.FtpStatus::statusCode\n\tint32_t ___statusCode_0;\n\t\/\/ System.String System.Net.FtpStatus::statusDescription\n\tString_t* ___statusDescription_1;\n\npublic:\n\tinline static int32_t get_offset_of_statusCode_0() { return static_cast<int32_t>(offsetof(FtpStatus_t2376455776, ___statusCode_0)); }\n\tinline int32_t get_statusCode_0() const { return ___statusCode_0; }\n\tinline int32_t* get_address_of_statusCode_0() { return &___statusCode_0; }\n\tinline void set_statusCode_0(int32_t value)\n\t{\n\t\t___statusCode_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_statusDescription_1() { return static_cast<int32_t>(offsetof(FtpStatus_t2376455776, ___statusDescription_1)); }\n\tinline String_t* get_statusDescription_1() const { return ___statusDescription_1; }\n\tinline String_t** get_address_of_statusDescription_1() { return &___statusDescription_1; }\n\tinline void set_statusDescription_1(String_t* value)\n\t{\n\t\t___statusDescription_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___statusDescription_1), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FTPSTATUS_T2376455776_H\n#ifndef HTTPWEBRESPONSE_T3286585418_H\n#define HTTPWEBRESPONSE_T3286585418_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.HttpWebResponse\nstruct  HttpWebResponse_t3286585418  : public WebResponse_t229922639\n{\npublic:\n\t\/\/ System.Uri System.Net.HttpWebResponse::uri\n\tUri_t100236324 * ___uri_1;\n\t\/\/ System.Net.WebHeaderCollection System.Net.HttpWebResponse::webHeaders\n\tWebHeaderCollection_t1942268960 * ___webHeaders_2;\n\t\/\/ System.Net.CookieCollection System.Net.HttpWebResponse::cookieCollection\n\tCookieCollection_t3881042616 * ___cookieCollection_3;\n\t\/\/ System.String System.Net.HttpWebResponse::method\n\tString_t* ___method_4;\n\t\/\/ System.Version System.Net.HttpWebResponse::version\n\tVersion_t3456873960 * ___version_5;\n\t\/\/ System.Net.HttpStatusCode System.Net.HttpWebResponse::statusCode\n\tint32_t ___statusCode_6;\n\t\/\/ System.String System.Net.HttpWebResponse::statusDescription\n\tString_t* ___statusDescription_7;\n\t\/\/ System.Int64 System.Net.HttpWebResponse::contentLength\n\tint64_t ___contentLength_8;\n\t\/\/ System.String System.Net.HttpWebResponse::contentType\n\tString_t* ___contentType_9;\n\t\/\/ System.Net.CookieContainer System.Net.HttpWebResponse::cookie_container\n\tCookieContainer_t2331592909 * ___cookie_container_10;\n\t\/\/ System.Boolean System.Net.HttpWebResponse::disposed\n\tbool ___disposed_11;\n\t\/\/ System.IO.Stream System.Net.HttpWebResponse::stream\n\tStream_t1273022909 * ___stream_12;\n\t\/\/ System.String[] System.Net.HttpWebResponse::cookieExpiresFormats\n\tStringU5BU5D_t1281789340* ___cookieExpiresFormats_13;\n\npublic:\n\tinline static int32_t get_offset_of_uri_1() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418, ___uri_1)); }\n\tinline Uri_t100236324 * get_uri_1() const { return ___uri_1; }\n\tinline Uri_t100236324 ** get_address_of_uri_1() { return &___uri_1; }\n\tinline void set_uri_1(Uri_t100236324 * value)\n\t{\n\t\t___uri_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___uri_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_webHeaders_2() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418, ___webHeaders_2)); }\n\tinline WebHeaderCollection_t1942268960 * get_webHeaders_2() const { return ___webHeaders_2; }\n\tinline WebHeaderCollection_t1942268960 ** get_address_of_webHeaders_2() { return &___webHeaders_2; }\n\tinline void set_webHeaders_2(WebHeaderCollection_t1942268960 * value)\n\t{\n\t\t___webHeaders_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___webHeaders_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_cookieCollection_3() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418, ___cookieCollection_3)); }\n\tinline CookieCollection_t3881042616 * get_cookieCollection_3() const { return ___cookieCollection_3; }\n\tinline CookieCollection_t3881042616 ** get_address_of_cookieCollection_3() { return &___cookieCollection_3; }\n\tinline void set_cookieCollection_3(CookieCollection_t3881042616 * value)\n\t{\n\t\t___cookieCollection_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___cookieCollection_3), value);\n\t}\n\n\tinline static int32_t get_offset_of_method_4() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418, ___method_4)); }\n\tinline String_t* get_method_4() const { return ___method_4; }\n\tinline String_t** get_address_of_method_4() { return &___method_4; }\n\tinline void set_method_4(String_t* value)\n\t{\n\t\t___method_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___method_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_version_5() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418, ___version_5)); }\n\tinline Version_t3456873960 * get_version_5() const { return ___version_5; }\n\tinline Version_t3456873960 ** get_address_of_version_5() { return &___version_5; }\n\tinline void set_version_5(Version_t3456873960 * value)\n\t{\n\t\t___version_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___version_5), value);\n\t}\n\n\tinline static int32_t get_offset_of_statusCode_6() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418, ___statusCode_6)); }\n\tinline int32_t get_statusCode_6() const { return ___statusCode_6; }\n\tinline int32_t* get_address_of_statusCode_6() { return &___statusCode_6; }\n\tinline void set_statusCode_6(int32_t value)\n\t{\n\t\t___statusCode_6 = value;\n\t}\n\n\tinline static int32_t get_offset_of_statusDescription_7() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418, ___statusDescription_7)); }\n\tinline String_t* get_statusDescription_7() const { return ___statusDescription_7; }\n\tinline String_t** get_address_of_statusDescription_7() { return &___statusDescription_7; }\n\tinline void set_statusDescription_7(String_t* value)\n\t{\n\t\t___statusDescription_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___statusDescription_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_contentLength_8() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418, ___contentLength_8)); }\n\tinline int64_t get_contentLength_8() const { return ___contentLength_8; }\n\tinline int64_t* get_address_of_contentLength_8() { return &___contentLength_8; }\n\tinline void set_contentLength_8(int64_t value)\n\t{\n\t\t___contentLength_8 = value;\n\t}\n\n\tinline static int32_t get_offset_of_contentType_9() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418, ___contentType_9)); }\n\tinline String_t* get_contentType_9() const { return ___contentType_9; }\n\tinline String_t** get_address_of_contentType_9() { return &___contentType_9; }\n\tinline void set_contentType_9(String_t* value)\n\t{\n\t\t___contentType_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___contentType_9), value);\n\t}\n\n\tinline static int32_t get_offset_of_cookie_container_10() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418, ___cookie_container_10)); }\n\tinline CookieContainer_t2331592909 * get_cookie_container_10() const { return ___cookie_container_10; }\n\tinline CookieContainer_t2331592909 ** get_address_of_cookie_container_10() { return &___cookie_container_10; }\n\tinline void set_cookie_container_10(CookieContainer_t2331592909 * value)\n\t{\n\t\t___cookie_container_10 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___cookie_container_10), value);\n\t}\n\n\tinline static int32_t get_offset_of_disposed_11() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418, ___disposed_11)); }\n\tinline bool get_disposed_11() const { return ___disposed_11; }\n\tinline bool* get_address_of_disposed_11() { return &___disposed_11; }\n\tinline void set_disposed_11(bool value)\n\t{\n\t\t___disposed_11 = value;\n\t}\n\n\tinline static int32_t get_offset_of_stream_12() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418, ___stream_12)); }\n\tinline Stream_t1273022909 * get_stream_12() const { return ___stream_12; }\n\tinline Stream_t1273022909 ** get_address_of_stream_12() { return &___stream_12; }\n\tinline void set_stream_12(Stream_t1273022909 * value)\n\t{\n\t\t___stream_12 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___stream_12), value);\n\t}\n\n\tinline static int32_t get_offset_of_cookieExpiresFormats_13() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418, ___cookieExpiresFormats_13)); }\n\tinline StringU5BU5D_t1281789340* get_cookieExpiresFormats_13() const { return ___cookieExpiresFormats_13; }\n\tinline StringU5BU5D_t1281789340** get_address_of_cookieExpiresFormats_13() { return &___cookieExpiresFormats_13; }\n\tinline void set_cookieExpiresFormats_13(StringU5BU5D_t1281789340* value)\n\t{\n\t\t___cookieExpiresFormats_13 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___cookieExpiresFormats_13), value);\n\t}\n};\n\nstruct HttpWebResponse_t3286585418_StaticFields\n{\npublic:\n\t\/\/ System.Collections.Generic.Dictionary`2<System.String,System.Int32> System.Net.HttpWebResponse::<>f__switch$map8\n\tDictionary_2_t2736202052 * ___U3CU3Ef__switchU24map8_14;\n\npublic:\n\tinline static int32_t get_offset_of_U3CU3Ef__switchU24map8_14() { return static_cast<int32_t>(offsetof(HttpWebResponse_t3286585418_StaticFields, ___U3CU3Ef__switchU24map8_14)); }\n\tinline Dictionary_2_t2736202052 * get_U3CU3Ef__switchU24map8_14() const { return ___U3CU3Ef__switchU24map8_14; }\n\tinline Dictionary_2_t2736202052 ** get_address_of_U3CU3Ef__switchU24map8_14() { return &___U3CU3Ef__switchU24map8_14; }\n\tinline void set_U3CU3Ef__switchU24map8_14(Dictionary_2_t2736202052 * value)\n\t{\n\t\t___U3CU3Ef__switchU24map8_14 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___U3CU3Ef__switchU24map8_14), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ HTTPWEBRESPONSE_T3286585418_H\n#ifndef NETWORKSTREAM_T4071955934_H\n#define NETWORKSTREAM_T4071955934_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.NetworkStream\nstruct  NetworkStream_t4071955934  : public Stream_t1273022909\n{\npublic:\n\t\/\/ System.IO.FileAccess System.Net.Sockets.NetworkStream::access\n\tint32_t ___access_1;\n\t\/\/ System.Net.Sockets.Socket System.Net.Sockets.NetworkStream::socket\n\tSocket_t1119025450 * ___socket_2;\n\t\/\/ System.Boolean System.Net.Sockets.NetworkStream::owns_socket\n\tbool ___owns_socket_3;\n\t\/\/ System.Boolean System.Net.Sockets.NetworkStream::readable\n\tbool ___readable_4;\n\t\/\/ System.Boolean System.Net.Sockets.NetworkStream::writeable\n\tbool ___writeable_5;\n\t\/\/ System.Boolean System.Net.Sockets.NetworkStream::disposed\n\tbool ___disposed_6;\n\npublic:\n\tinline static int32_t get_offset_of_access_1() { return static_cast<int32_t>(offsetof(NetworkStream_t4071955934, ___access_1)); }\n\tinline int32_t get_access_1() const { return ___access_1; }\n\tinline int32_t* get_address_of_access_1() { return &___access_1; }\n\tinline void set_access_1(int32_t value)\n\t{\n\t\t___access_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_socket_2() { return static_cast<int32_t>(offsetof(NetworkStream_t4071955934, ___socket_2)); }\n\tinline Socket_t1119025450 * get_socket_2() const { return ___socket_2; }\n\tinline Socket_t1119025450 ** get_address_of_socket_2() { return &___socket_2; }\n\tinline void set_socket_2(Socket_t1119025450 * value)\n\t{\n\t\t___socket_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___socket_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_owns_socket_3() { return static_cast<int32_t>(offsetof(NetworkStream_t4071955934, ___owns_socket_3)); }\n\tinline bool get_owns_socket_3() const { return ___owns_socket_3; }\n\tinline bool* get_address_of_owns_socket_3() { return &___owns_socket_3; }\n\tinline void set_owns_socket_3(bool value)\n\t{\n\t\t___owns_socket_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_readable_4() { return static_cast<int32_t>(offsetof(NetworkStream_t4071955934, ___readable_4)); }\n\tinline bool get_readable_4() const { return ___readable_4; }\n\tinline bool* get_address_of_readable_4() { return &___readable_4; }\n\tinline void set_readable_4(bool value)\n\t{\n\t\t___readable_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_writeable_5() { return static_cast<int32_t>(offsetof(NetworkStream_t4071955934, ___writeable_5)); }\n\tinline bool get_writeable_5() const { return ___writeable_5; }\n\tinline bool* get_address_of_writeable_5() { return &___writeable_5; }\n\tinline void set_writeable_5(bool value)\n\t{\n\t\t___writeable_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of_disposed_6() { return static_cast<int32_t>(offsetof(NetworkStream_t4071955934, ___disposed_6)); }\n\tinline bool get_disposed_6() const { return ___disposed_6; }\n\tinline bool* get_address_of_disposed_6() { return &___disposed_6; }\n\tinline void set_disposed_6(bool value)\n\t{\n\t\t___disposed_6 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ NETWORKSTREAM_T4071955934_H\n#ifndef SOCKET_T1119025450_H\n#define SOCKET_T1119025450_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.Socket\nstruct  Socket_t1119025450  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Collections.Queue System.Net.Sockets.Socket::readQ\n\tQueue_t3637523393 * ___readQ_0;\n\t\/\/ System.Collections.Queue System.Net.Sockets.Socket::writeQ\n\tQueue_t3637523393 * ___writeQ_1;\n\t\/\/ System.Boolean System.Net.Sockets.Socket::islistening\n\tbool ___islistening_2;\n\t\/\/ System.Boolean System.Net.Sockets.Socket::useoverlappedIO\n\tbool ___useoverlappedIO_3;\n\t\/\/ System.Int32 System.Net.Sockets.Socket::MinListenPort\n\tint32_t ___MinListenPort_4;\n\t\/\/ System.Int32 System.Net.Sockets.Socket::MaxListenPort\n\tint32_t ___MaxListenPort_5;\n\t\/\/ System.Int32 System.Net.Sockets.Socket::linger_timeout\n\tint32_t ___linger_timeout_8;\n\t\/\/ System.IntPtr System.Net.Sockets.Socket::socket\n\tintptr_t ___socket_9;\n\t\/\/ System.Net.Sockets.AddressFamily System.Net.Sockets.Socket::address_family\n\tint32_t ___address_family_10;\n\t\/\/ System.Net.Sockets.SocketType System.Net.Sockets.Socket::socket_type\n\tint32_t ___socket_type_11;\n\t\/\/ System.Net.Sockets.ProtocolType System.Net.Sockets.Socket::protocol_type\n\tint32_t ___protocol_type_12;\n\t\/\/ System.Boolean System.Net.Sockets.Socket::blocking\n\tbool ___blocking_13;\n\t\/\/ System.Threading.Thread System.Net.Sockets.Socket::blocking_thread\n\tThread_t2300836069 * ___blocking_thread_14;\n\t\/\/ System.Boolean System.Net.Sockets.Socket::isbound\n\tbool ___isbound_15;\n\t\/\/ System.Int32 System.Net.Sockets.Socket::max_bind_count\n\tint32_t ___max_bind_count_17;\n\t\/\/ System.Boolean System.Net.Sockets.Socket::connected\n\tbool ___connected_18;\n\t\/\/ System.Boolean System.Net.Sockets.Socket::closed\n\tbool ___closed_19;\n\t\/\/ System.Boolean System.Net.Sockets.Socket::disposed\n\tbool ___disposed_20;\n\t\/\/ System.Net.EndPoint System.Net.Sockets.Socket::seed_endpoint\n\tEndPoint_t982345378 * ___seed_endpoint_21;\n\npublic:\n\tinline static int32_t get_offset_of_readQ_0() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___readQ_0)); }\n\tinline Queue_t3637523393 * get_readQ_0() const { return ___readQ_0; }\n\tinline Queue_t3637523393 ** get_address_of_readQ_0() { return &___readQ_0; }\n\tinline void set_readQ_0(Queue_t3637523393 * value)\n\t{\n\t\t___readQ_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___readQ_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_writeQ_1() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___writeQ_1)); }\n\tinline Queue_t3637523393 * get_writeQ_1() const { return ___writeQ_1; }\n\tinline Queue_t3637523393 ** get_address_of_writeQ_1() { return &___writeQ_1; }\n\tinline void set_writeQ_1(Queue_t3637523393 * value)\n\t{\n\t\t___writeQ_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___writeQ_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_islistening_2() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___islistening_2)); }\n\tinline bool get_islistening_2() const { return ___islistening_2; }\n\tinline bool* get_address_of_islistening_2() { return &___islistening_2; }\n\tinline void set_islistening_2(bool value)\n\t{\n\t\t___islistening_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_useoverlappedIO_3() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___useoverlappedIO_3)); }\n\tinline bool get_useoverlappedIO_3() const { return ___useoverlappedIO_3; }\n\tinline bool* get_address_of_useoverlappedIO_3() { return &___useoverlappedIO_3; }\n\tinline void set_useoverlappedIO_3(bool value)\n\t{\n\t\t___useoverlappedIO_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_MinListenPort_4() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___MinListenPort_4)); }\n\tinline int32_t get_MinListenPort_4() const { return ___MinListenPort_4; }\n\tinline int32_t* get_address_of_MinListenPort_4() { return &___MinListenPort_4; }\n\tinline void set_MinListenPort_4(int32_t value)\n\t{\n\t\t___MinListenPort_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_MaxListenPort_5() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___MaxListenPort_5)); }\n\tinline int32_t get_MaxListenPort_5() const { return ___MaxListenPort_5; }\n\tinline int32_t* get_address_of_MaxListenPort_5() { return &___MaxListenPort_5; }\n\tinline void set_MaxListenPort_5(int32_t value)\n\t{\n\t\t___MaxListenPort_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of_linger_timeout_8() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___linger_timeout_8)); }\n\tinline int32_t get_linger_timeout_8() const { return ___linger_timeout_8; }\n\tinline int32_t* get_address_of_linger_timeout_8() { return &___linger_timeout_8; }\n\tinline void set_linger_timeout_8(int32_t value)\n\t{\n\t\t___linger_timeout_8 = value;\n\t}\n\n\tinline static int32_t get_offset_of_socket_9() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___socket_9)); }\n\tinline intptr_t get_socket_9() const { return ___socket_9; }\n\tinline intptr_t* get_address_of_socket_9() { return &___socket_9; }\n\tinline void set_socket_9(intptr_t value)\n\t{\n\t\t___socket_9 = value;\n\t}\n\n\tinline static int32_t get_offset_of_address_family_10() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___address_family_10)); }\n\tinline int32_t get_address_family_10() const { return ___address_family_10; }\n\tinline int32_t* get_address_of_address_family_10() { return &___address_family_10; }\n\tinline void set_address_family_10(int32_t value)\n\t{\n\t\t___address_family_10 = value;\n\t}\n\n\tinline static int32_t get_offset_of_socket_type_11() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___socket_type_11)); }\n\tinline int32_t get_socket_type_11() const { return ___socket_type_11; }\n\tinline int32_t* get_address_of_socket_type_11() { return &___socket_type_11; }\n\tinline void set_socket_type_11(int32_t value)\n\t{\n\t\t___socket_type_11 = value;\n\t}\n\n\tinline static int32_t get_offset_of_protocol_type_12() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___protocol_type_12)); }\n\tinline int32_t get_protocol_type_12() const { return ___protocol_type_12; }\n\tinline int32_t* get_address_of_protocol_type_12() { return &___protocol_type_12; }\n\tinline void set_protocol_type_12(int32_t value)\n\t{\n\t\t___protocol_type_12 = value;\n\t}\n\n\tinline static int32_t get_offset_of_blocking_13() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___blocking_13)); }\n\tinline bool get_blocking_13() const { return ___blocking_13; }\n\tinline bool* get_address_of_blocking_13() { return &___blocking_13; }\n\tinline void set_blocking_13(bool value)\n\t{\n\t\t___blocking_13 = value;\n\t}\n\n\tinline static int32_t get_offset_of_blocking_thread_14() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___blocking_thread_14)); }\n\tinline Thread_t2300836069 * get_blocking_thread_14() const { return ___blocking_thread_14; }\n\tinline Thread_t2300836069 ** get_address_of_blocking_thread_14() { return &___blocking_thread_14; }\n\tinline void set_blocking_thread_14(Thread_t2300836069 * value)\n\t{\n\t\t___blocking_thread_14 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___blocking_thread_14), value);\n\t}\n\n\tinline static int32_t get_offset_of_isbound_15() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___isbound_15)); }\n\tinline bool get_isbound_15() const { return ___isbound_15; }\n\tinline bool* get_address_of_isbound_15() { return &___isbound_15; }\n\tinline void set_isbound_15(bool value)\n\t{\n\t\t___isbound_15 = value;\n\t}\n\n\tinline static int32_t get_offset_of_max_bind_count_17() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___max_bind_count_17)); }\n\tinline int32_t get_max_bind_count_17() const { return ___max_bind_count_17; }\n\tinline int32_t* get_address_of_max_bind_count_17() { return &___max_bind_count_17; }\n\tinline void set_max_bind_count_17(int32_t value)\n\t{\n\t\t___max_bind_count_17 = value;\n\t}\n\n\tinline static int32_t get_offset_of_connected_18() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___connected_18)); }\n\tinline bool get_connected_18() const { return ___connected_18; }\n\tinline bool* get_address_of_connected_18() { return &___connected_18; }\n\tinline void set_connected_18(bool value)\n\t{\n\t\t___connected_18 = value;\n\t}\n\n\tinline static int32_t get_offset_of_closed_19() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___closed_19)); }\n\tinline bool get_closed_19() const { return ___closed_19; }\n\tinline bool* get_address_of_closed_19() { return &___closed_19; }\n\tinline void set_closed_19(bool value)\n\t{\n\t\t___closed_19 = value;\n\t}\n\n\tinline static int32_t get_offset_of_disposed_20() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___disposed_20)); }\n\tinline bool get_disposed_20() const { return ___disposed_20; }\n\tinline bool* get_address_of_disposed_20() { return &___disposed_20; }\n\tinline void set_disposed_20(bool value)\n\t{\n\t\t___disposed_20 = value;\n\t}\n\n\tinline static int32_t get_offset_of_seed_endpoint_21() { return static_cast<int32_t>(offsetof(Socket_t1119025450, ___seed_endpoint_21)); }\n\tinline EndPoint_t982345378 * get_seed_endpoint_21() const { return ___seed_endpoint_21; }\n\tinline EndPoint_t982345378 ** get_address_of_seed_endpoint_21() { return &___seed_endpoint_21; }\n\tinline void set_seed_endpoint_21(EndPoint_t982345378 * value)\n\t{\n\t\t___seed_endpoint_21 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___seed_endpoint_21), value);\n\t}\n};\n\nstruct Socket_t1119025450_StaticFields\n{\npublic:\n\t\/\/ System.Int32 System.Net.Sockets.Socket::ipv4Supported\n\tint32_t ___ipv4Supported_6;\n\t\/\/ System.Int32 System.Net.Sockets.Socket::ipv6Supported\n\tint32_t ___ipv6Supported_7;\n\t\/\/ System.Int32 System.Net.Sockets.Socket::current_bind_count\n\tint32_t ___current_bind_count_16;\n\t\/\/ System.Reflection.MethodInfo System.Net.Sockets.Socket::check_socket_policy\n\tMethodInfo_t * ___check_socket_policy_22;\n\npublic:\n\tinline static int32_t get_offset_of_ipv4Supported_6() { return static_cast<int32_t>(offsetof(Socket_t1119025450_StaticFields, ___ipv4Supported_6)); }\n\tinline int32_t get_ipv4Supported_6() const { return ___ipv4Supported_6; }\n\tinline int32_t* get_address_of_ipv4Supported_6() { return &___ipv4Supported_6; }\n\tinline void set_ipv4Supported_6(int32_t value)\n\t{\n\t\t___ipv4Supported_6 = value;\n\t}\n\n\tinline static int32_t get_offset_of_ipv6Supported_7() { return static_cast<int32_t>(offsetof(Socket_t1119025450_StaticFields, ___ipv6Supported_7)); }\n\tinline int32_t get_ipv6Supported_7() const { return ___ipv6Supported_7; }\n\tinline int32_t* get_address_of_ipv6Supported_7() { return &___ipv6Supported_7; }\n\tinline void set_ipv6Supported_7(int32_t value)\n\t{\n\t\t___ipv6Supported_7 = value;\n\t}\n\n\tinline static int32_t get_offset_of_current_bind_count_16() { return static_cast<int32_t>(offsetof(Socket_t1119025450_StaticFields, ___current_bind_count_16)); }\n\tinline int32_t get_current_bind_count_16() const { return ___current_bind_count_16; }\n\tinline int32_t* get_address_of_current_bind_count_16() { return &___current_bind_count_16; }\n\tinline void set_current_bind_count_16(int32_t value)\n\t{\n\t\t___current_bind_count_16 = value;\n\t}\n\n\tinline static int32_t get_offset_of_check_socket_policy_22() { return static_cast<int32_t>(offsetof(Socket_t1119025450_StaticFields, ___check_socket_policy_22)); }\n\tinline MethodInfo_t * get_check_socket_policy_22() const { return ___check_socket_policy_22; }\n\tinline MethodInfo_t ** get_address_of_check_socket_policy_22() { return &___check_socket_policy_22; }\n\tinline void set_check_socket_policy_22(MethodInfo_t * value)\n\t{\n\t\t___check_socket_policy_22 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___check_socket_policy_22), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SOCKET_T1119025450_H\n#ifndef SOCKETASYNCRESULT_T2080034863_H\n#define SOCKETASYNCRESULT_T2080034863_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.Socket\/SocketAsyncResult\nstruct  SocketAsyncResult_t2080034863  : public RuntimeObject\n{\npublic:\n\t\/\/ System.Net.Sockets.Socket System.Net.Sockets.Socket\/SocketAsyncResult::Sock\n\tSocket_t1119025450 * ___Sock_0;\n\t\/\/ System.IntPtr System.Net.Sockets.Socket\/SocketAsyncResult::handle\n\tintptr_t ___handle_1;\n\t\/\/ System.Object System.Net.Sockets.Socket\/SocketAsyncResult::state\n\tRuntimeObject * ___state_2;\n\t\/\/ System.AsyncCallback System.Net.Sockets.Socket\/SocketAsyncResult::callback\n\tAsyncCallback_t3962456242 * ___callback_3;\n\t\/\/ System.Threading.WaitHandle System.Net.Sockets.Socket\/SocketAsyncResult::waithandle\n\tWaitHandle_t1743403487 * ___waithandle_4;\n\t\/\/ System.Exception System.Net.Sockets.Socket\/SocketAsyncResult::delayedException\n\tException_t * ___delayedException_5;\n\t\/\/ System.Net.EndPoint System.Net.Sockets.Socket\/SocketAsyncResult::EndPoint\n\tEndPoint_t982345378 * ___EndPoint_6;\n\t\/\/ System.Byte[] System.Net.Sockets.Socket\/SocketAsyncResult::Buffer\n\tByteU5BU5D_t4116647657* ___Buffer_7;\n\t\/\/ System.Int32 System.Net.Sockets.Socket\/SocketAsyncResult::Offset\n\tint32_t ___Offset_8;\n\t\/\/ System.Int32 System.Net.Sockets.Socket\/SocketAsyncResult::Size\n\tint32_t ___Size_9;\n\t\/\/ System.Net.Sockets.SocketFlags System.Net.Sockets.Socket\/SocketAsyncResult::SockFlags\n\tint32_t ___SockFlags_10;\n\t\/\/ System.Net.Sockets.Socket System.Net.Sockets.Socket\/SocketAsyncResult::AcceptSocket\n\tSocket_t1119025450 * ___AcceptSocket_11;\n\t\/\/ System.Net.IPAddress[] System.Net.Sockets.Socket\/SocketAsyncResult::Addresses\n\tIPAddressU5BU5D_t596328627* ___Addresses_12;\n\t\/\/ System.Int32 System.Net.Sockets.Socket\/SocketAsyncResult::Port\n\tint32_t ___Port_13;\n\t\/\/ System.Collections.Generic.IList`1<System.ArraySegment`1<System.Byte>> System.Net.Sockets.Socket\/SocketAsyncResult::Buffers\n\tRuntimeObject* ___Buffers_14;\n\t\/\/ System.Boolean System.Net.Sockets.Socket\/SocketAsyncResult::ReuseSocket\n\tbool ___ReuseSocket_15;\n\t\/\/ System.Net.Sockets.Socket System.Net.Sockets.Socket\/SocketAsyncResult::acc_socket\n\tSocket_t1119025450 * ___acc_socket_16;\n\t\/\/ System.Int32 System.Net.Sockets.Socket\/SocketAsyncResult::total\n\tint32_t ___total_17;\n\t\/\/ System.Boolean System.Net.Sockets.Socket\/SocketAsyncResult::completed_sync\n\tbool ___completed_sync_18;\n\t\/\/ System.Boolean System.Net.Sockets.Socket\/SocketAsyncResult::completed\n\tbool ___completed_19;\n\t\/\/ System.Boolean System.Net.Sockets.Socket\/SocketAsyncResult::blocking\n\tbool ___blocking_20;\n\t\/\/ System.Int32 System.Net.Sockets.Socket\/SocketAsyncResult::error\n\tint32_t ___error_21;\n\t\/\/ System.Net.Sockets.Socket\/SocketOperation System.Net.Sockets.Socket\/SocketAsyncResult::operation\n\tint32_t ___operation_22;\n\t\/\/ System.Object System.Net.Sockets.Socket\/SocketAsyncResult::ares\n\tRuntimeObject * ___ares_23;\n\t\/\/ System.Int32 System.Net.Sockets.Socket\/SocketAsyncResult::EndCalled\n\tint32_t ___EndCalled_24;\n\npublic:\n\tinline static int32_t get_offset_of_Sock_0() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___Sock_0)); }\n\tinline Socket_t1119025450 * get_Sock_0() const { return ___Sock_0; }\n\tinline Socket_t1119025450 ** get_address_of_Sock_0() { return &___Sock_0; }\n\tinline void set_Sock_0(Socket_t1119025450 * value)\n\t{\n\t\t___Sock_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Sock_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_handle_1() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___handle_1)); }\n\tinline intptr_t get_handle_1() const { return ___handle_1; }\n\tinline intptr_t* get_address_of_handle_1() { return &___handle_1; }\n\tinline void set_handle_1(intptr_t value)\n\t{\n\t\t___handle_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_state_2() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___state_2)); }\n\tinline RuntimeObject * get_state_2() const { return ___state_2; }\n\tinline RuntimeObject ** get_address_of_state_2() { return &___state_2; }\n\tinline void set_state_2(RuntimeObject * value)\n\t{\n\t\t___state_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___state_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_callback_3() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___callback_3)); }\n\tinline AsyncCallback_t3962456242 * get_callback_3() const { return ___callback_3; }\n\tinline AsyncCallback_t3962456242 ** get_address_of_callback_3() { return &___callback_3; }\n\tinline void set_callback_3(AsyncCallback_t3962456242 * value)\n\t{\n\t\t___callback_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___callback_3), value);\n\t}\n\n\tinline static int32_t get_offset_of_waithandle_4() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___waithandle_4)); }\n\tinline WaitHandle_t1743403487 * get_waithandle_4() const { return ___waithandle_4; }\n\tinline WaitHandle_t1743403487 ** get_address_of_waithandle_4() { return &___waithandle_4; }\n\tinline void set_waithandle_4(WaitHandle_t1743403487 * value)\n\t{\n\t\t___waithandle_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___waithandle_4), value);\n\t}\n\n\tinline static int32_t get_offset_of_delayedException_5() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___delayedException_5)); }\n\tinline Exception_t * get_delayedException_5() const { return ___delayedException_5; }\n\tinline Exception_t ** get_address_of_delayedException_5() { return &___delayedException_5; }\n\tinline void set_delayedException_5(Exception_t * value)\n\t{\n\t\t___delayedException_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___delayedException_5), value);\n\t}\n\n\tinline static int32_t get_offset_of_EndPoint_6() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___EndPoint_6)); }\n\tinline EndPoint_t982345378 * get_EndPoint_6() const { return ___EndPoint_6; }\n\tinline EndPoint_t982345378 ** get_address_of_EndPoint_6() { return &___EndPoint_6; }\n\tinline void set_EndPoint_6(EndPoint_t982345378 * value)\n\t{\n\t\t___EndPoint_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___EndPoint_6), value);\n\t}\n\n\tinline static int32_t get_offset_of_Buffer_7() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___Buffer_7)); }\n\tinline ByteU5BU5D_t4116647657* get_Buffer_7() const { return ___Buffer_7; }\n\tinline ByteU5BU5D_t4116647657** get_address_of_Buffer_7() { return &___Buffer_7; }\n\tinline void set_Buffer_7(ByteU5BU5D_t4116647657* value)\n\t{\n\t\t___Buffer_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Buffer_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_Offset_8() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___Offset_8)); }\n\tinline int32_t get_Offset_8() const { return ___Offset_8; }\n\tinline int32_t* get_address_of_Offset_8() { return &___Offset_8; }\n\tinline void set_Offset_8(int32_t value)\n\t{\n\t\t___Offset_8 = value;\n\t}\n\n\tinline static int32_t get_offset_of_Size_9() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___Size_9)); }\n\tinline int32_t get_Size_9() const { return ___Size_9; }\n\tinline int32_t* get_address_of_Size_9() { return &___Size_9; }\n\tinline void set_Size_9(int32_t value)\n\t{\n\t\t___Size_9 = value;\n\t}\n\n\tinline static int32_t get_offset_of_SockFlags_10() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___SockFlags_10)); }\n\tinline int32_t get_SockFlags_10() const { return ___SockFlags_10; }\n\tinline int32_t* get_address_of_SockFlags_10() { return &___SockFlags_10; }\n\tinline void set_SockFlags_10(int32_t value)\n\t{\n\t\t___SockFlags_10 = value;\n\t}\n\n\tinline static int32_t get_offset_of_AcceptSocket_11() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___AcceptSocket_11)); }\n\tinline Socket_t1119025450 * get_AcceptSocket_11() const { return ___AcceptSocket_11; }\n\tinline Socket_t1119025450 ** get_address_of_AcceptSocket_11() { return &___AcceptSocket_11; }\n\tinline void set_AcceptSocket_11(Socket_t1119025450 * value)\n\t{\n\t\t___AcceptSocket_11 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___AcceptSocket_11), value);\n\t}\n\n\tinline static int32_t get_offset_of_Addresses_12() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___Addresses_12)); }\n\tinline IPAddressU5BU5D_t596328627* get_Addresses_12() const { return ___Addresses_12; }\n\tinline IPAddressU5BU5D_t596328627** get_address_of_Addresses_12() { return &___Addresses_12; }\n\tinline void set_Addresses_12(IPAddressU5BU5D_t596328627* value)\n\t{\n\t\t___Addresses_12 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Addresses_12), value);\n\t}\n\n\tinline static int32_t get_offset_of_Port_13() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___Port_13)); }\n\tinline int32_t get_Port_13() const { return ___Port_13; }\n\tinline int32_t* get_address_of_Port_13() { return &___Port_13; }\n\tinline void set_Port_13(int32_t value)\n\t{\n\t\t___Port_13 = value;\n\t}\n\n\tinline static int32_t get_offset_of_Buffers_14() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___Buffers_14)); }\n\tinline RuntimeObject* get_Buffers_14() const { return ___Buffers_14; }\n\tinline RuntimeObject** get_address_of_Buffers_14() { return &___Buffers_14; }\n\tinline void set_Buffers_14(RuntimeObject* value)\n\t{\n\t\t___Buffers_14 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___Buffers_14), value);\n\t}\n\n\tinline static int32_t get_offset_of_ReuseSocket_15() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___ReuseSocket_15)); }\n\tinline bool get_ReuseSocket_15() const { return ___ReuseSocket_15; }\n\tinline bool* get_address_of_ReuseSocket_15() { return &___ReuseSocket_15; }\n\tinline void set_ReuseSocket_15(bool value)\n\t{\n\t\t___ReuseSocket_15 = value;\n\t}\n\n\tinline static int32_t get_offset_of_acc_socket_16() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___acc_socket_16)); }\n\tinline Socket_t1119025450 * get_acc_socket_16() const { return ___acc_socket_16; }\n\tinline Socket_t1119025450 ** get_address_of_acc_socket_16() { return &___acc_socket_16; }\n\tinline void set_acc_socket_16(Socket_t1119025450 * value)\n\t{\n\t\t___acc_socket_16 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___acc_socket_16), value);\n\t}\n\n\tinline static int32_t get_offset_of_total_17() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___total_17)); }\n\tinline int32_t get_total_17() const { return ___total_17; }\n\tinline int32_t* get_address_of_total_17() { return &___total_17; }\n\tinline void set_total_17(int32_t value)\n\t{\n\t\t___total_17 = value;\n\t}\n\n\tinline static int32_t get_offset_of_completed_sync_18() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___completed_sync_18)); }\n\tinline bool get_completed_sync_18() const { return ___completed_sync_18; }\n\tinline bool* get_address_of_completed_sync_18() { return &___completed_sync_18; }\n\tinline void set_completed_sync_18(bool value)\n\t{\n\t\t___completed_sync_18 = value;\n\t}\n\n\tinline static int32_t get_offset_of_completed_19() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___completed_19)); }\n\tinline bool get_completed_19() const { return ___completed_19; }\n\tinline bool* get_address_of_completed_19() { return &___completed_19; }\n\tinline void set_completed_19(bool value)\n\t{\n\t\t___completed_19 = value;\n\t}\n\n\tinline static int32_t get_offset_of_blocking_20() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___blocking_20)); }\n\tinline bool get_blocking_20() const { return ___blocking_20; }\n\tinline bool* get_address_of_blocking_20() { return &___blocking_20; }\n\tinline void set_blocking_20(bool value)\n\t{\n\t\t___blocking_20 = value;\n\t}\n\n\tinline static int32_t get_offset_of_error_21() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___error_21)); }\n\tinline int32_t get_error_21() const { return ___error_21; }\n\tinline int32_t* get_address_of_error_21() { return &___error_21; }\n\tinline void set_error_21(int32_t value)\n\t{\n\t\t___error_21 = value;\n\t}\n\n\tinline static int32_t get_offset_of_operation_22() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___operation_22)); }\n\tinline int32_t get_operation_22() const { return ___operation_22; }\n\tinline int32_t* get_address_of_operation_22() { return &___operation_22; }\n\tinline void set_operation_22(int32_t value)\n\t{\n\t\t___operation_22 = value;\n\t}\n\n\tinline static int32_t get_offset_of_ares_23() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___ares_23)); }\n\tinline RuntimeObject * get_ares_23() const { return ___ares_23; }\n\tinline RuntimeObject ** get_address_of_ares_23() { return &___ares_23; }\n\tinline void set_ares_23(RuntimeObject * value)\n\t{\n\t\t___ares_23 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___ares_23), value);\n\t}\n\n\tinline static int32_t get_offset_of_EndCalled_24() { return static_cast<int32_t>(offsetof(SocketAsyncResult_t2080034863, ___EndCalled_24)); }\n\tinline int32_t get_EndCalled_24() const { return ___EndCalled_24; }\n\tinline int32_t* get_address_of_EndCalled_24() { return &___EndCalled_24; }\n\tinline void set_EndCalled_24(int32_t value)\n\t{\n\t\t___EndCalled_24 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.Net.Sockets.Socket\/SocketAsyncResult\nstruct SocketAsyncResult_t2080034863_marshaled_pinvoke\n{\n\tSocket_t1119025450 * ___Sock_0;\n\tintptr_t ___handle_1;\n\tIl2CppIUnknown* ___state_2;\n\tIl2CppMethodPointer ___callback_3;\n\tWaitHandle_t1743403487 * ___waithandle_4;\n\tException_t * ___delayedException_5;\n\tEndPoint_t982345378 * ___EndPoint_6;\n\tuint8_t* ___Buffer_7;\n\tint32_t ___Offset_8;\n\tint32_t ___Size_9;\n\tint32_t ___SockFlags_10;\n\tSocket_t1119025450 * ___AcceptSocket_11;\n\tIPAddressU5BU5D_t596328627* ___Addresses_12;\n\tint32_t ___Port_13;\n\tRuntimeObject* ___Buffers_14;\n\tint32_t ___ReuseSocket_15;\n\tSocket_t1119025450 * ___acc_socket_16;\n\tint32_t ___total_17;\n\tint32_t ___completed_sync_18;\n\tint32_t ___completed_19;\n\tint32_t ___blocking_20;\n\tint32_t ___error_21;\n\tint32_t ___operation_22;\n\tIl2CppIUnknown* ___ares_23;\n\tint32_t ___EndCalled_24;\n};\n\/\/ Native definition for COM marshalling of System.Net.Sockets.Socket\/SocketAsyncResult\nstruct SocketAsyncResult_t2080034863_marshaled_com\n{\n\tSocket_t1119025450 * ___Sock_0;\n\tintptr_t ___handle_1;\n\tIl2CppIUnknown* ___state_2;\n\tIl2CppMethodPointer ___callback_3;\n\tWaitHandle_t1743403487 * ___waithandle_4;\n\tException_t * ___delayedException_5;\n\tEndPoint_t982345378 * ___EndPoint_6;\n\tuint8_t* ___Buffer_7;\n\tint32_t ___Offset_8;\n\tint32_t ___Size_9;\n\tint32_t ___SockFlags_10;\n\tSocket_t1119025450 * ___AcceptSocket_11;\n\tIPAddressU5BU5D_t596328627* ___Addresses_12;\n\tint32_t ___Port_13;\n\tRuntimeObject* ___Buffers_14;\n\tint32_t ___ReuseSocket_15;\n\tSocket_t1119025450 * ___acc_socket_16;\n\tint32_t ___total_17;\n\tint32_t ___completed_sync_18;\n\tint32_t ___completed_19;\n\tint32_t ___blocking_20;\n\tint32_t ___error_21;\n\tint32_t ___operation_22;\n\tIl2CppIUnknown* ___ares_23;\n\tint32_t ___EndCalled_24;\n};\n#endif \/\/ SOCKETASYNCRESULT_T2080034863_H\n#ifndef WEBREQUEST_T1939381076_H\n#define WEBREQUEST_T1939381076_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.WebRequest\nstruct  WebRequest_t1939381076  : public MarshalByRefObject_t2760389100\n{\npublic:\n\t\/\/ System.Net.Security.AuthenticationLevel System.Net.WebRequest::authentication_level\n\tint32_t ___authentication_level_4;\n\npublic:\n\tinline static int32_t get_offset_of_authentication_level_4() { return static_cast<int32_t>(offsetof(WebRequest_t1939381076, ___authentication_level_4)); }\n\tinline int32_t get_authentication_level_4() const { return ___authentication_level_4; }\n\tinline int32_t* get_address_of_authentication_level_4() { return &___authentication_level_4; }\n\tinline void set_authentication_level_4(int32_t value)\n\t{\n\t\t___authentication_level_4 = value;\n\t}\n};\n\nstruct WebRequest_t1939381076_StaticFields\n{\npublic:\n\t\/\/ System.Collections.Specialized.HybridDictionary System.Net.WebRequest::prefixes\n\tHybridDictionary_t4070033136 * ___prefixes_1;\n\t\/\/ System.Boolean System.Net.WebRequest::isDefaultWebProxySet\n\tbool ___isDefaultWebProxySet_2;\n\t\/\/ System.Net.IWebProxy System.Net.WebRequest::defaultWebProxy\n\tRuntimeObject* ___defaultWebProxy_3;\n\t\/\/ System.Object System.Net.WebRequest::lockobj\n\tRuntimeObject * ___lockobj_5;\n\npublic:\n\tinline static int32_t get_offset_of_prefixes_1() { return static_cast<int32_t>(offsetof(WebRequest_t1939381076_StaticFields, ___prefixes_1)); }\n\tinline HybridDictionary_t4070033136 * get_prefixes_1() const { return ___prefixes_1; }\n\tinline HybridDictionary_t4070033136 ** get_address_of_prefixes_1() { return &___prefixes_1; }\n\tinline void set_prefixes_1(HybridDictionary_t4070033136 * value)\n\t{\n\t\t___prefixes_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___prefixes_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_isDefaultWebProxySet_2() { return static_cast<int32_t>(offsetof(WebRequest_t1939381076_StaticFields, ___isDefaultWebProxySet_2)); }\n\tinline bool get_isDefaultWebProxySet_2() const { return ___isDefaultWebProxySet_2; }\n\tinline bool* get_address_of_isDefaultWebProxySet_2() { return &___isDefaultWebProxySet_2; }\n\tinline void set_isDefaultWebProxySet_2(bool value)\n\t{\n\t\t___isDefaultWebProxySet_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_defaultWebProxy_3() { return static_cast<int32_t>(offsetof(WebRequest_t1939381076_StaticFields, ___defaultWebProxy_3)); }\n\tinline RuntimeObject* get_defaultWebProxy_3() const { return ___defaultWebProxy_3; }\n\tinline RuntimeObject** get_address_of_defaultWebProxy_3() { return &___defaultWebProxy_3; }\n\tinline void set_defaultWebProxy_3(RuntimeObject* value)\n\t{\n\t\t___defaultWebProxy_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___defaultWebProxy_3), value);\n\t}\n\n\tinline static int32_t get_offset_of_lockobj_5() { return static_cast<int32_t>(offsetof(WebRequest_t1939381076_StaticFields, ___lockobj_5)); }\n\tinline RuntimeObject * get_lockobj_5() const { return ___lockobj_5; }\n\tinline RuntimeObject ** get_address_of_lockobj_5() { return &___lockobj_5; }\n\tinline void set_lockobj_5(RuntimeObject * value)\n\t{\n\t\t___lockobj_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___lockobj_5), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ WEBREQUEST_T1939381076_H\n#ifndef READMETHOD_T893206259_H\n#define READMETHOD_T893206259_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.IO.Compression.DeflateStream\/ReadMethod\nstruct  ReadMethod_t893206259  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ READMETHOD_T893206259_H\n#ifndef UNMANAGEDREADORWRITE_T876388624_H\n#define UNMANAGEDREADORWRITE_T876388624_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.IO.Compression.DeflateStream\/UnmanagedReadOrWrite\nstruct  UnmanagedReadOrWrite_t876388624  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ UNMANAGEDREADORWRITE_T876388624_H\n#ifndef WRITEMETHOD_T2538911768_H\n#define WRITEMETHOD_T2538911768_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.IO.Compression.DeflateStream\/WriteMethod\nstruct  WriteMethod_t2538911768  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ WRITEMETHOD_T2538911768_H\n#ifndef COOKIE_T993873397_H\n#define COOKIE_T993873397_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Cookie\nstruct  Cookie_t993873397  : public RuntimeObject\n{\npublic:\n\t\/\/ System.String System.Net.Cookie::comment\n\tString_t* ___comment_0;\n\t\/\/ System.Uri System.Net.Cookie::commentUri\n\tUri_t100236324 * ___commentUri_1;\n\t\/\/ System.Boolean System.Net.Cookie::discard\n\tbool ___discard_2;\n\t\/\/ System.String System.Net.Cookie::domain\n\tString_t* ___domain_3;\n\t\/\/ System.DateTime System.Net.Cookie::expires\n\tDateTime_t3738529785  ___expires_4;\n\t\/\/ System.Boolean System.Net.Cookie::httpOnly\n\tbool ___httpOnly_5;\n\t\/\/ System.String System.Net.Cookie::name\n\tString_t* ___name_6;\n\t\/\/ System.String System.Net.Cookie::path\n\tString_t* ___path_7;\n\t\/\/ System.String System.Net.Cookie::port\n\tString_t* ___port_8;\n\t\/\/ System.Int32[] System.Net.Cookie::ports\n\tInt32U5BU5D_t385246372* ___ports_9;\n\t\/\/ System.Boolean System.Net.Cookie::secure\n\tbool ___secure_10;\n\t\/\/ System.DateTime System.Net.Cookie::timestamp\n\tDateTime_t3738529785  ___timestamp_11;\n\t\/\/ System.String System.Net.Cookie::val\n\tString_t* ___val_12;\n\t\/\/ System.Int32 System.Net.Cookie::version\n\tint32_t ___version_13;\n\t\/\/ System.Boolean System.Net.Cookie::exact_domain\n\tbool ___exact_domain_17;\n\npublic:\n\tinline static int32_t get_offset_of_comment_0() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___comment_0)); }\n\tinline String_t* get_comment_0() const { return ___comment_0; }\n\tinline String_t** get_address_of_comment_0() { return &___comment_0; }\n\tinline void set_comment_0(String_t* value)\n\t{\n\t\t___comment_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___comment_0), value);\n\t}\n\n\tinline static int32_t get_offset_of_commentUri_1() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___commentUri_1)); }\n\tinline Uri_t100236324 * get_commentUri_1() const { return ___commentUri_1; }\n\tinline Uri_t100236324 ** get_address_of_commentUri_1() { return &___commentUri_1; }\n\tinline void set_commentUri_1(Uri_t100236324 * value)\n\t{\n\t\t___commentUri_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___commentUri_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_discard_2() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___discard_2)); }\n\tinline bool get_discard_2() const { return ___discard_2; }\n\tinline bool* get_address_of_discard_2() { return &___discard_2; }\n\tinline void set_discard_2(bool value)\n\t{\n\t\t___discard_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_domain_3() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___domain_3)); }\n\tinline String_t* get_domain_3() const { return ___domain_3; }\n\tinline String_t** get_address_of_domain_3() { return &___domain_3; }\n\tinline void set_domain_3(String_t* value)\n\t{\n\t\t___domain_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___domain_3), value);\n\t}\n\n\tinline static int32_t get_offset_of_expires_4() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___expires_4)); }\n\tinline DateTime_t3738529785  get_expires_4() const { return ___expires_4; }\n\tinline DateTime_t3738529785 * get_address_of_expires_4() { return &___expires_4; }\n\tinline void set_expires_4(DateTime_t3738529785  value)\n\t{\n\t\t___expires_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_httpOnly_5() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___httpOnly_5)); }\n\tinline bool get_httpOnly_5() const { return ___httpOnly_5; }\n\tinline bool* get_address_of_httpOnly_5() { return &___httpOnly_5; }\n\tinline void set_httpOnly_5(bool value)\n\t{\n\t\t___httpOnly_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of_name_6() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___name_6)); }\n\tinline String_t* get_name_6() const { return ___name_6; }\n\tinline String_t** get_address_of_name_6() { return &___name_6; }\n\tinline void set_name_6(String_t* value)\n\t{\n\t\t___name_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___name_6), value);\n\t}\n\n\tinline static int32_t get_offset_of_path_7() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___path_7)); }\n\tinline String_t* get_path_7() const { return ___path_7; }\n\tinline String_t** get_address_of_path_7() { return &___path_7; }\n\tinline void set_path_7(String_t* value)\n\t{\n\t\t___path_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___path_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_port_8() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___port_8)); }\n\tinline String_t* get_port_8() const { return ___port_8; }\n\tinline String_t** get_address_of_port_8() { return &___port_8; }\n\tinline void set_port_8(String_t* value)\n\t{\n\t\t___port_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___port_8), value);\n\t}\n\n\tinline static int32_t get_offset_of_ports_9() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___ports_9)); }\n\tinline Int32U5BU5D_t385246372* get_ports_9() const { return ___ports_9; }\n\tinline Int32U5BU5D_t385246372** get_address_of_ports_9() { return &___ports_9; }\n\tinline void set_ports_9(Int32U5BU5D_t385246372* value)\n\t{\n\t\t___ports_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___ports_9), value);\n\t}\n\n\tinline static int32_t get_offset_of_secure_10() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___secure_10)); }\n\tinline bool get_secure_10() const { return ___secure_10; }\n\tinline bool* get_address_of_secure_10() { return &___secure_10; }\n\tinline void set_secure_10(bool value)\n\t{\n\t\t___secure_10 = value;\n\t}\n\n\tinline static int32_t get_offset_of_timestamp_11() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___timestamp_11)); }\n\tinline DateTime_t3738529785  get_timestamp_11() const { return ___timestamp_11; }\n\tinline DateTime_t3738529785 * get_address_of_timestamp_11() { return &___timestamp_11; }\n\tinline void set_timestamp_11(DateTime_t3738529785  value)\n\t{\n\t\t___timestamp_11 = value;\n\t}\n\n\tinline static int32_t get_offset_of_val_12() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___val_12)); }\n\tinline String_t* get_val_12() const { return ___val_12; }\n\tinline String_t** get_address_of_val_12() { return &___val_12; }\n\tinline void set_val_12(String_t* value)\n\t{\n\t\t___val_12 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___val_12), value);\n\t}\n\n\tinline static int32_t get_offset_of_version_13() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___version_13)); }\n\tinline int32_t get_version_13() const { return ___version_13; }\n\tinline int32_t* get_address_of_version_13() { return &___version_13; }\n\tinline void set_version_13(int32_t value)\n\t{\n\t\t___version_13 = value;\n\t}\n\n\tinline static int32_t get_offset_of_exact_domain_17() { return static_cast<int32_t>(offsetof(Cookie_t993873397, ___exact_domain_17)); }\n\tinline bool get_exact_domain_17() const { return ___exact_domain_17; }\n\tinline bool* get_address_of_exact_domain_17() { return &___exact_domain_17; }\n\tinline void set_exact_domain_17(bool value)\n\t{\n\t\t___exact_domain_17 = value;\n\t}\n};\n\nstruct Cookie_t993873397_StaticFields\n{\npublic:\n\t\/\/ System.Char[] System.Net.Cookie::reservedCharsName\n\tCharU5BU5D_t3528271667* ___reservedCharsName_14;\n\t\/\/ System.Char[] System.Net.Cookie::portSeparators\n\tCharU5BU5D_t3528271667* ___portSeparators_15;\n\t\/\/ System.String System.Net.Cookie::tspecials\n\tString_t* ___tspecials_16;\n\npublic:\n\tinline static int32_t get_offset_of_reservedCharsName_14() { return static_cast<int32_t>(offsetof(Cookie_t993873397_StaticFields, ___reservedCharsName_14)); }\n\tinline CharU5BU5D_t3528271667* get_reservedCharsName_14() const { return ___reservedCharsName_14; }\n\tinline CharU5BU5D_t3528271667** get_address_of_reservedCharsName_14() { return &___reservedCharsName_14; }\n\tinline void set_reservedCharsName_14(CharU5BU5D_t3528271667* value)\n\t{\n\t\t___reservedCharsName_14 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___reservedCharsName_14), value);\n\t}\n\n\tinline static int32_t get_offset_of_portSeparators_15() { return static_cast<int32_t>(offsetof(Cookie_t993873397_StaticFields, ___portSeparators_15)); }\n\tinline CharU5BU5D_t3528271667* get_portSeparators_15() const { return ___portSeparators_15; }\n\tinline CharU5BU5D_t3528271667** get_address_of_portSeparators_15() { return &___portSeparators_15; }\n\tinline void set_portSeparators_15(CharU5BU5D_t3528271667* value)\n\t{\n\t\t___portSeparators_15 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___portSeparators_15), value);\n\t}\n\n\tinline static int32_t get_offset_of_tspecials_16() { return static_cast<int32_t>(offsetof(Cookie_t993873397_StaticFields, ___tspecials_16)); }\n\tinline String_t* get_tspecials_16() const { return ___tspecials_16; }\n\tinline String_t** get_address_of_tspecials_16() { return &___tspecials_16; }\n\tinline void set_tspecials_16(String_t* value)\n\t{\n\t\t___tspecials_16 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___tspecials_16), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ COOKIE_T993873397_H\n#ifndef DIGESTSESSION_T1433627624_H\n#define DIGESTSESSION_T1433627624_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.DigestSession\nstruct  DigestSession_t1433627624  : public RuntimeObject\n{\npublic:\n\t\/\/ System.DateTime System.Net.DigestSession::lastUse\n\tDateTime_t3738529785  ___lastUse_1;\n\t\/\/ System.Int32 System.Net.DigestSession::_nc\n\tint32_t ____nc_2;\n\t\/\/ System.Security.Cryptography.HashAlgorithm System.Net.DigestSession::hash\n\tHashAlgorithm_t1432317219 * ___hash_3;\n\t\/\/ System.Net.DigestHeaderParser System.Net.DigestSession::parser\n\tDigestHeaderParser_t341650829 * ___parser_4;\n\t\/\/ System.String System.Net.DigestSession::_cnonce\n\tString_t* ____cnonce_5;\n\npublic:\n\tinline static int32_t get_offset_of_lastUse_1() { return static_cast<int32_t>(offsetof(DigestSession_t1433627624, ___lastUse_1)); }\n\tinline DateTime_t3738529785  get_lastUse_1() const { return ___lastUse_1; }\n\tinline DateTime_t3738529785 * get_address_of_lastUse_1() { return &___lastUse_1; }\n\tinline void set_lastUse_1(DateTime_t3738529785  value)\n\t{\n\t\t___lastUse_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of__nc_2() { return static_cast<int32_t>(offsetof(DigestSession_t1433627624, ____nc_2)); }\n\tinline int32_t get__nc_2() const { return ____nc_2; }\n\tinline int32_t* get_address_of__nc_2() { return &____nc_2; }\n\tinline void set__nc_2(int32_t value)\n\t{\n\t\t____nc_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_hash_3() { return static_cast<int32_t>(offsetof(DigestSession_t1433627624, ___hash_3)); }\n\tinline HashAlgorithm_t1432317219 * get_hash_3() const { return ___hash_3; }\n\tinline HashAlgorithm_t1432317219 ** get_address_of_hash_3() { return &___hash_3; }\n\tinline void set_hash_3(HashAlgorithm_t1432317219 * value)\n\t{\n\t\t___hash_3 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___hash_3), value);\n\t}\n\n\tinline static int32_t get_offset_of_parser_4() { return static_cast<int32_t>(offsetof(DigestSession_t1433627624, ___parser_4)); }\n\tinline DigestHeaderParser_t341650829 * get_parser_4() const { return ___parser_4; }\n\tinline DigestHeaderParser_t341650829 ** get_address_of_parser_4() { return &___parser_4; }\n\tinline void set_parser_4(DigestHeaderParser_t341650829 * value)\n\t{\n\t\t___parser_4 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___parser_4), value);\n\t}\n\n\tinline static int32_t get_offset_of__cnonce_5() { return static_cast<int32_t>(offsetof(DigestSession_t1433627624, ____cnonce_5)); }\n\tinline String_t* get__cnonce_5() const { return ____cnonce_5; }\n\tinline String_t** get_address_of__cnonce_5() { return &____cnonce_5; }\n\tinline void set__cnonce_5(String_t* value)\n\t{\n\t\t____cnonce_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&____cnonce_5), value);\n\t}\n};\n\nstruct DigestSession_t1433627624_StaticFields\n{\npublic:\n\t\/\/ System.Security.Cryptography.RandomNumberGenerator System.Net.DigestSession::rng\n\tRandomNumberGenerator_t386037858 * ___rng_0;\n\npublic:\n\tinline static int32_t get_offset_of_rng_0() { return static_cast<int32_t>(offsetof(DigestSession_t1433627624_StaticFields, ___rng_0)); }\n\tinline RandomNumberGenerator_t386037858 * get_rng_0() const { return ___rng_0; }\n\tinline RandomNumberGenerator_t386037858 ** get_address_of_rng_0() { return &___rng_0; }\n\tinline void set_rng_0(RandomNumberGenerator_t386037858 * value)\n\t{\n\t\t___rng_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___rng_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DIGESTSESSION_T1433627624_H\n#ifndef FILEWEBREQUEST_T591858885_H\n#define FILEWEBREQUEST_T591858885_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FileWebRequest\nstruct  FileWebRequest_t591858885  : public WebRequest_t1939381076\n{\npublic:\n\t\/\/ System.Uri System.Net.FileWebRequest::uri\n\tUri_t100236324 * ___uri_6;\n\t\/\/ System.Net.WebHeaderCollection System.Net.FileWebRequest::webHeaders\n\tWebHeaderCollection_t1942268960 * ___webHeaders_7;\n\t\/\/ System.Net.ICredentials System.Net.FileWebRequest::credentials\n\tRuntimeObject* ___credentials_8;\n\t\/\/ System.String System.Net.FileWebRequest::connectionGroup\n\tString_t* ___connectionGroup_9;\n\t\/\/ System.Int64 System.Net.FileWebRequest::contentLength\n\tint64_t ___contentLength_10;\n\t\/\/ System.IO.FileAccess System.Net.FileWebRequest::fileAccess\n\tint32_t ___fileAccess_11;\n\t\/\/ System.String System.Net.FileWebRequest::method\n\tString_t* ___method_12;\n\t\/\/ System.Net.IWebProxy System.Net.FileWebRequest::proxy\n\tRuntimeObject* ___proxy_13;\n\t\/\/ System.Boolean System.Net.FileWebRequest::preAuthenticate\n\tbool ___preAuthenticate_14;\n\t\/\/ System.Int32 System.Net.FileWebRequest::timeout\n\tint32_t ___timeout_15;\n\t\/\/ System.Net.FileWebResponse System.Net.FileWebRequest::webResponse\n\tFileWebResponse_t544571260 * ___webResponse_16;\n\t\/\/ System.Threading.AutoResetEvent System.Net.FileWebRequest::requestEndEvent\n\tAutoResetEvent_t1333520283 * ___requestEndEvent_17;\n\t\/\/ System.Boolean System.Net.FileWebRequest::requesting\n\tbool ___requesting_18;\n\t\/\/ System.Boolean System.Net.FileWebRequest::asyncResponding\n\tbool ___asyncResponding_19;\n\npublic:\n\tinline static int32_t get_offset_of_uri_6() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___uri_6)); }\n\tinline Uri_t100236324 * get_uri_6() const { return ___uri_6; }\n\tinline Uri_t100236324 ** get_address_of_uri_6() { return &___uri_6; }\n\tinline void set_uri_6(Uri_t100236324 * value)\n\t{\n\t\t___uri_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___uri_6), value);\n\t}\n\n\tinline static int32_t get_offset_of_webHeaders_7() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___webHeaders_7)); }\n\tinline WebHeaderCollection_t1942268960 * get_webHeaders_7() const { return ___webHeaders_7; }\n\tinline WebHeaderCollection_t1942268960 ** get_address_of_webHeaders_7() { return &___webHeaders_7; }\n\tinline void set_webHeaders_7(WebHeaderCollection_t1942268960 * value)\n\t{\n\t\t___webHeaders_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___webHeaders_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_credentials_8() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___credentials_8)); }\n\tinline RuntimeObject* get_credentials_8() const { return ___credentials_8; }\n\tinline RuntimeObject** get_address_of_credentials_8() { return &___credentials_8; }\n\tinline void set_credentials_8(RuntimeObject* value)\n\t{\n\t\t___credentials_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___credentials_8), value);\n\t}\n\n\tinline static int32_t get_offset_of_connectionGroup_9() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___connectionGroup_9)); }\n\tinline String_t* get_connectionGroup_9() const { return ___connectionGroup_9; }\n\tinline String_t** get_address_of_connectionGroup_9() { return &___connectionGroup_9; }\n\tinline void set_connectionGroup_9(String_t* value)\n\t{\n\t\t___connectionGroup_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___connectionGroup_9), value);\n\t}\n\n\tinline static int32_t get_offset_of_contentLength_10() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___contentLength_10)); }\n\tinline int64_t get_contentLength_10() const { return ___contentLength_10; }\n\tinline int64_t* get_address_of_contentLength_10() { return &___contentLength_10; }\n\tinline void set_contentLength_10(int64_t value)\n\t{\n\t\t___contentLength_10 = value;\n\t}\n\n\tinline static int32_t get_offset_of_fileAccess_11() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___fileAccess_11)); }\n\tinline int32_t get_fileAccess_11() const { return ___fileAccess_11; }\n\tinline int32_t* get_address_of_fileAccess_11() { return &___fileAccess_11; }\n\tinline void set_fileAccess_11(int32_t value)\n\t{\n\t\t___fileAccess_11 = value;\n\t}\n\n\tinline static int32_t get_offset_of_method_12() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___method_12)); }\n\tinline String_t* get_method_12() const { return ___method_12; }\n\tinline String_t** get_address_of_method_12() { return &___method_12; }\n\tinline void set_method_12(String_t* value)\n\t{\n\t\t___method_12 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___method_12), value);\n\t}\n\n\tinline static int32_t get_offset_of_proxy_13() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___proxy_13)); }\n\tinline RuntimeObject* get_proxy_13() const { return ___proxy_13; }\n\tinline RuntimeObject** get_address_of_proxy_13() { return &___proxy_13; }\n\tinline void set_proxy_13(RuntimeObject* value)\n\t{\n\t\t___proxy_13 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___proxy_13), value);\n\t}\n\n\tinline static int32_t get_offset_of_preAuthenticate_14() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___preAuthenticate_14)); }\n\tinline bool get_preAuthenticate_14() const { return ___preAuthenticate_14; }\n\tinline bool* get_address_of_preAuthenticate_14() { return &___preAuthenticate_14; }\n\tinline void set_preAuthenticate_14(bool value)\n\t{\n\t\t___preAuthenticate_14 = value;\n\t}\n\n\tinline static int32_t get_offset_of_timeout_15() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___timeout_15)); }\n\tinline int32_t get_timeout_15() const { return ___timeout_15; }\n\tinline int32_t* get_address_of_timeout_15() { return &___timeout_15; }\n\tinline void set_timeout_15(int32_t value)\n\t{\n\t\t___timeout_15 = value;\n\t}\n\n\tinline static int32_t get_offset_of_webResponse_16() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___webResponse_16)); }\n\tinline FileWebResponse_t544571260 * get_webResponse_16() const { return ___webResponse_16; }\n\tinline FileWebResponse_t544571260 ** get_address_of_webResponse_16() { return &___webResponse_16; }\n\tinline void set_webResponse_16(FileWebResponse_t544571260 * value)\n\t{\n\t\t___webResponse_16 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___webResponse_16), value);\n\t}\n\n\tinline static int32_t get_offset_of_requestEndEvent_17() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___requestEndEvent_17)); }\n\tinline AutoResetEvent_t1333520283 * get_requestEndEvent_17() const { return ___requestEndEvent_17; }\n\tinline AutoResetEvent_t1333520283 ** get_address_of_requestEndEvent_17() { return &___requestEndEvent_17; }\n\tinline void set_requestEndEvent_17(AutoResetEvent_t1333520283 * value)\n\t{\n\t\t___requestEndEvent_17 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___requestEndEvent_17), value);\n\t}\n\n\tinline static int32_t get_offset_of_requesting_18() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___requesting_18)); }\n\tinline bool get_requesting_18() const { return ___requesting_18; }\n\tinline bool* get_address_of_requesting_18() { return &___requesting_18; }\n\tinline void set_requesting_18(bool value)\n\t{\n\t\t___requesting_18 = value;\n\t}\n\n\tinline static int32_t get_offset_of_asyncResponding_19() { return static_cast<int32_t>(offsetof(FileWebRequest_t591858885, ___asyncResponding_19)); }\n\tinline bool get_asyncResponding_19() const { return ___asyncResponding_19; }\n\tinline bool* get_address_of_asyncResponding_19() { return &___asyncResponding_19; }\n\tinline void set_asyncResponding_19(bool value)\n\t{\n\t\t___asyncResponding_19 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FILEWEBREQUEST_T591858885_H\n#ifndef FILEWEBSTREAM_T586107972_H\n#define FILEWEBSTREAM_T586107972_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FileWebRequest\/FileWebStream\nstruct  FileWebStream_t586107972  : public FileStream_t4292183065\n{\npublic:\n\t\/\/ System.Net.FileWebRequest System.Net.FileWebRequest\/FileWebStream::webRequest\n\tFileWebRequest_t591858885 * ___webRequest_15;\n\npublic:\n\tinline static int32_t get_offset_of_webRequest_15() { return static_cast<int32_t>(offsetof(FileWebStream_t586107972, ___webRequest_15)); }\n\tinline FileWebRequest_t591858885 * get_webRequest_15() const { return ___webRequest_15; }\n\tinline FileWebRequest_t591858885 ** get_address_of_webRequest_15() { return &___webRequest_15; }\n\tinline void set_webRequest_15(FileWebRequest_t591858885 * value)\n\t{\n\t\t___webRequest_15 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___webRequest_15), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FILEWEBSTREAM_T586107972_H\n#ifndef GETRESPONSECALLBACK_T2326689408_H\n#define GETRESPONSECALLBACK_T2326689408_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FileWebRequest\/GetResponseCallback\nstruct  GetResponseCallback_t2326689408  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ GETRESPONSECALLBACK_T2326689408_H\n#ifndef READDELEGATE_T4266946825_H\n#define READDELEGATE_T4266946825_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FtpDataStream\/ReadDelegate\nstruct  ReadDelegate_t4266946825  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ READDELEGATE_T4266946825_H\n#ifndef WRITEDELEGATE_T2016697242_H\n#define WRITEDELEGATE_T2016697242_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FtpDataStream\/WriteDelegate\nstruct  WriteDelegate_t2016697242  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ WRITEDELEGATE_T2016697242_H\n#ifndef FTPWEBREQUEST_T1577818305_H\n#define FTPWEBREQUEST_T1577818305_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FtpWebRequest\nstruct  FtpWebRequest_t1577818305  : public WebRequest_t1939381076\n{\npublic:\n\t\/\/ System.Uri System.Net.FtpWebRequest::requestUri\n\tUri_t100236324 * ___requestUri_6;\n\t\/\/ System.String System.Net.FtpWebRequest::file_name\n\tString_t* ___file_name_7;\n\t\/\/ System.Net.ServicePoint System.Net.FtpWebRequest::servicePoint\n\tServicePoint_t2786966844 * ___servicePoint_8;\n\t\/\/ System.IO.Stream System.Net.FtpWebRequest::origDataStream\n\tStream_t1273022909 * ___origDataStream_9;\n\t\/\/ System.IO.Stream System.Net.FtpWebRequest::dataStream\n\tStream_t1273022909 * ___dataStream_10;\n\t\/\/ System.IO.Stream System.Net.FtpWebRequest::controlStream\n\tStream_t1273022909 * ___controlStream_11;\n\t\/\/ System.IO.StreamReader System.Net.FtpWebRequest::controlReader\n\tStreamReader_t4009935899 * ___controlReader_12;\n\t\/\/ System.Net.NetworkCredential System.Net.FtpWebRequest::credentials\n\tNetworkCredential_t3282608323 * ___credentials_13;\n\t\/\/ System.Net.IPHostEntry System.Net.FtpWebRequest::hostEntry\n\tIPHostEntry_t263743900 * ___hostEntry_14;\n\t\/\/ System.Net.IPEndPoint System.Net.FtpWebRequest::localEndPoint\n\tIPEndPoint_t3791887218 * ___localEndPoint_15;\n\t\/\/ System.Net.IWebProxy System.Net.FtpWebRequest::proxy\n\tRuntimeObject* ___proxy_16;\n\t\/\/ System.Int32 System.Net.FtpWebRequest::timeout\n\tint32_t ___timeout_17;\n\t\/\/ System.Int32 System.Net.FtpWebRequest::rwTimeout\n\tint32_t ___rwTimeout_18;\n\t\/\/ System.Int64 System.Net.FtpWebRequest::offset\n\tint64_t ___offset_19;\n\t\/\/ System.Boolean System.Net.FtpWebRequest::binary\n\tbool ___binary_20;\n\t\/\/ System.Boolean System.Net.FtpWebRequest::enableSsl\n\tbool ___enableSsl_21;\n\t\/\/ System.Boolean System.Net.FtpWebRequest::usePassive\n\tbool ___usePassive_22;\n\t\/\/ System.Boolean System.Net.FtpWebRequest::keepAlive\n\tbool ___keepAlive_23;\n\t\/\/ System.String System.Net.FtpWebRequest::method\n\tString_t* ___method_24;\n\t\/\/ System.String System.Net.FtpWebRequest::renameTo\n\tString_t* ___renameTo_25;\n\t\/\/ System.Object System.Net.FtpWebRequest::locker\n\tRuntimeObject * ___locker_26;\n\t\/\/ System.Net.FtpWebRequest\/RequestState System.Net.FtpWebRequest::requestState\n\tint32_t ___requestState_27;\n\t\/\/ System.Net.FtpAsyncResult System.Net.FtpWebRequest::asyncResult\n\tFtpAsyncResult_t3265664217 * ___asyncResult_28;\n\t\/\/ System.Net.FtpWebResponse System.Net.FtpWebRequest::ftpResponse\n\tFtpWebResponse_t3940763575 * ___ftpResponse_29;\n\t\/\/ System.IO.Stream System.Net.FtpWebRequest::requestStream\n\tStream_t1273022909 * ___requestStream_30;\n\t\/\/ System.String System.Net.FtpWebRequest::initial_path\n\tString_t* ___initial_path_31;\n\t\/\/ System.Net.Security.RemoteCertificateValidationCallback System.Net.FtpWebRequest::callback\n\tRemoteCertificateValidationCallback_t3014364904 * ___callback_33;\n\npublic:\n\tinline static int32_t get_offset_of_requestUri_6() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___requestUri_6)); }\n\tinline Uri_t100236324 * get_requestUri_6() const { return ___requestUri_6; }\n\tinline Uri_t100236324 ** get_address_of_requestUri_6() { return &___requestUri_6; }\n\tinline void set_requestUri_6(Uri_t100236324 * value)\n\t{\n\t\t___requestUri_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___requestUri_6), value);\n\t}\n\n\tinline static int32_t get_offset_of_file_name_7() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___file_name_7)); }\n\tinline String_t* get_file_name_7() const { return ___file_name_7; }\n\tinline String_t** get_address_of_file_name_7() { return &___file_name_7; }\n\tinline void set_file_name_7(String_t* value)\n\t{\n\t\t___file_name_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___file_name_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_servicePoint_8() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___servicePoint_8)); }\n\tinline ServicePoint_t2786966844 * get_servicePoint_8() const { return ___servicePoint_8; }\n\tinline ServicePoint_t2786966844 ** get_address_of_servicePoint_8() { return &___servicePoint_8; }\n\tinline void set_servicePoint_8(ServicePoint_t2786966844 * value)\n\t{\n\t\t___servicePoint_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___servicePoint_8), value);\n\t}\n\n\tinline static int32_t get_offset_of_origDataStream_9() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___origDataStream_9)); }\n\tinline Stream_t1273022909 * get_origDataStream_9() const { return ___origDataStream_9; }\n\tinline Stream_t1273022909 ** get_address_of_origDataStream_9() { return &___origDataStream_9; }\n\tinline void set_origDataStream_9(Stream_t1273022909 * value)\n\t{\n\t\t___origDataStream_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___origDataStream_9), value);\n\t}\n\n\tinline static int32_t get_offset_of_dataStream_10() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___dataStream_10)); }\n\tinline Stream_t1273022909 * get_dataStream_10() const { return ___dataStream_10; }\n\tinline Stream_t1273022909 ** get_address_of_dataStream_10() { return &___dataStream_10; }\n\tinline void set_dataStream_10(Stream_t1273022909 * value)\n\t{\n\t\t___dataStream_10 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___dataStream_10), value);\n\t}\n\n\tinline static int32_t get_offset_of_controlStream_11() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___controlStream_11)); }\n\tinline Stream_t1273022909 * get_controlStream_11() const { return ___controlStream_11; }\n\tinline Stream_t1273022909 ** get_address_of_controlStream_11() { return &___controlStream_11; }\n\tinline void set_controlStream_11(Stream_t1273022909 * value)\n\t{\n\t\t___controlStream_11 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___controlStream_11), value);\n\t}\n\n\tinline static int32_t get_offset_of_controlReader_12() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___controlReader_12)); }\n\tinline StreamReader_t4009935899 * get_controlReader_12() const { return ___controlReader_12; }\n\tinline StreamReader_t4009935899 ** get_address_of_controlReader_12() { return &___controlReader_12; }\n\tinline void set_controlReader_12(StreamReader_t4009935899 * value)\n\t{\n\t\t___controlReader_12 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___controlReader_12), value);\n\t}\n\n\tinline static int32_t get_offset_of_credentials_13() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___credentials_13)); }\n\tinline NetworkCredential_t3282608323 * get_credentials_13() const { return ___credentials_13; }\n\tinline NetworkCredential_t3282608323 ** get_address_of_credentials_13() { return &___credentials_13; }\n\tinline void set_credentials_13(NetworkCredential_t3282608323 * value)\n\t{\n\t\t___credentials_13 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___credentials_13), value);\n\t}\n\n\tinline static int32_t get_offset_of_hostEntry_14() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___hostEntry_14)); }\n\tinline IPHostEntry_t263743900 * get_hostEntry_14() const { return ___hostEntry_14; }\n\tinline IPHostEntry_t263743900 ** get_address_of_hostEntry_14() { return &___hostEntry_14; }\n\tinline void set_hostEntry_14(IPHostEntry_t263743900 * value)\n\t{\n\t\t___hostEntry_14 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___hostEntry_14), value);\n\t}\n\n\tinline static int32_t get_offset_of_localEndPoint_15() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___localEndPoint_15)); }\n\tinline IPEndPoint_t3791887218 * get_localEndPoint_15() const { return ___localEndPoint_15; }\n\tinline IPEndPoint_t3791887218 ** get_address_of_localEndPoint_15() { return &___localEndPoint_15; }\n\tinline void set_localEndPoint_15(IPEndPoint_t3791887218 * value)\n\t{\n\t\t___localEndPoint_15 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___localEndPoint_15), value);\n\t}\n\n\tinline static int32_t get_offset_of_proxy_16() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___proxy_16)); }\n\tinline RuntimeObject* get_proxy_16() const { return ___proxy_16; }\n\tinline RuntimeObject** get_address_of_proxy_16() { return &___proxy_16; }\n\tinline void set_proxy_16(RuntimeObject* value)\n\t{\n\t\t___proxy_16 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___proxy_16), value);\n\t}\n\n\tinline static int32_t get_offset_of_timeout_17() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___timeout_17)); }\n\tinline int32_t get_timeout_17() const { return ___timeout_17; }\n\tinline int32_t* get_address_of_timeout_17() { return &___timeout_17; }\n\tinline void set_timeout_17(int32_t value)\n\t{\n\t\t___timeout_17 = value;\n\t}\n\n\tinline static int32_t get_offset_of_rwTimeout_18() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___rwTimeout_18)); }\n\tinline int32_t get_rwTimeout_18() const { return ___rwTimeout_18; }\n\tinline int32_t* get_address_of_rwTimeout_18() { return &___rwTimeout_18; }\n\tinline void set_rwTimeout_18(int32_t value)\n\t{\n\t\t___rwTimeout_18 = value;\n\t}\n\n\tinline static int32_t get_offset_of_offset_19() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___offset_19)); }\n\tinline int64_t get_offset_19() const { return ___offset_19; }\n\tinline int64_t* get_address_of_offset_19() { return &___offset_19; }\n\tinline void set_offset_19(int64_t value)\n\t{\n\t\t___offset_19 = value;\n\t}\n\n\tinline static int32_t get_offset_of_binary_20() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___binary_20)); }\n\tinline bool get_binary_20() const { return ___binary_20; }\n\tinline bool* get_address_of_binary_20() { return &___binary_20; }\n\tinline void set_binary_20(bool value)\n\t{\n\t\t___binary_20 = value;\n\t}\n\n\tinline static int32_t get_offset_of_enableSsl_21() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___enableSsl_21)); }\n\tinline bool get_enableSsl_21() const { return ___enableSsl_21; }\n\tinline bool* get_address_of_enableSsl_21() { return &___enableSsl_21; }\n\tinline void set_enableSsl_21(bool value)\n\t{\n\t\t___enableSsl_21 = value;\n\t}\n\n\tinline static int32_t get_offset_of_usePassive_22() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___usePassive_22)); }\n\tinline bool get_usePassive_22() const { return ___usePassive_22; }\n\tinline bool* get_address_of_usePassive_22() { return &___usePassive_22; }\n\tinline void set_usePassive_22(bool value)\n\t{\n\t\t___usePassive_22 = value;\n\t}\n\n\tinline static int32_t get_offset_of_keepAlive_23() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___keepAlive_23)); }\n\tinline bool get_keepAlive_23() const { return ___keepAlive_23; }\n\tinline bool* get_address_of_keepAlive_23() { return &___keepAlive_23; }\n\tinline void set_keepAlive_23(bool value)\n\t{\n\t\t___keepAlive_23 = value;\n\t}\n\n\tinline static int32_t get_offset_of_method_24() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___method_24)); }\n\tinline String_t* get_method_24() const { return ___method_24; }\n\tinline String_t** get_address_of_method_24() { return &___method_24; }\n\tinline void set_method_24(String_t* value)\n\t{\n\t\t___method_24 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___method_24), value);\n\t}\n\n\tinline static int32_t get_offset_of_renameTo_25() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___renameTo_25)); }\n\tinline String_t* get_renameTo_25() const { return ___renameTo_25; }\n\tinline String_t** get_address_of_renameTo_25() { return &___renameTo_25; }\n\tinline void set_renameTo_25(String_t* value)\n\t{\n\t\t___renameTo_25 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___renameTo_25), value);\n\t}\n\n\tinline static int32_t get_offset_of_locker_26() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___locker_26)); }\n\tinline RuntimeObject * get_locker_26() const { return ___locker_26; }\n\tinline RuntimeObject ** get_address_of_locker_26() { return &___locker_26; }\n\tinline void set_locker_26(RuntimeObject * value)\n\t{\n\t\t___locker_26 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___locker_26), value);\n\t}\n\n\tinline static int32_t get_offset_of_requestState_27() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___requestState_27)); }\n\tinline int32_t get_requestState_27() const { return ___requestState_27; }\n\tinline int32_t* get_address_of_requestState_27() { return &___requestState_27; }\n\tinline void set_requestState_27(int32_t value)\n\t{\n\t\t___requestState_27 = value;\n\t}\n\n\tinline static int32_t get_offset_of_asyncResult_28() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___asyncResult_28)); }\n\tinline FtpAsyncResult_t3265664217 * get_asyncResult_28() const { return ___asyncResult_28; }\n\tinline FtpAsyncResult_t3265664217 ** get_address_of_asyncResult_28() { return &___asyncResult_28; }\n\tinline void set_asyncResult_28(FtpAsyncResult_t3265664217 * value)\n\t{\n\t\t___asyncResult_28 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___asyncResult_28), value);\n\t}\n\n\tinline static int32_t get_offset_of_ftpResponse_29() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___ftpResponse_29)); }\n\tinline FtpWebResponse_t3940763575 * get_ftpResponse_29() const { return ___ftpResponse_29; }\n\tinline FtpWebResponse_t3940763575 ** get_address_of_ftpResponse_29() { return &___ftpResponse_29; }\n\tinline void set_ftpResponse_29(FtpWebResponse_t3940763575 * value)\n\t{\n\t\t___ftpResponse_29 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___ftpResponse_29), value);\n\t}\n\n\tinline static int32_t get_offset_of_requestStream_30() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___requestStream_30)); }\n\tinline Stream_t1273022909 * get_requestStream_30() const { return ___requestStream_30; }\n\tinline Stream_t1273022909 ** get_address_of_requestStream_30() { return &___requestStream_30; }\n\tinline void set_requestStream_30(Stream_t1273022909 * value)\n\t{\n\t\t___requestStream_30 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___requestStream_30), value);\n\t}\n\n\tinline static int32_t get_offset_of_initial_path_31() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___initial_path_31)); }\n\tinline String_t* get_initial_path_31() const { return ___initial_path_31; }\n\tinline String_t** get_address_of_initial_path_31() { return &___initial_path_31; }\n\tinline void set_initial_path_31(String_t* value)\n\t{\n\t\t___initial_path_31 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___initial_path_31), value);\n\t}\n\n\tinline static int32_t get_offset_of_callback_33() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305, ___callback_33)); }\n\tinline RemoteCertificateValidationCallback_t3014364904 * get_callback_33() const { return ___callback_33; }\n\tinline RemoteCertificateValidationCallback_t3014364904 ** get_address_of_callback_33() { return &___callback_33; }\n\tinline void set_callback_33(RemoteCertificateValidationCallback_t3014364904 * value)\n\t{\n\t\t___callback_33 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___callback_33), value);\n\t}\n};\n\nstruct FtpWebRequest_t1577818305_StaticFields\n{\npublic:\n\t\/\/ System.String[] System.Net.FtpWebRequest::supportedCommands\n\tStringU5BU5D_t1281789340* ___supportedCommands_32;\n\t\/\/ System.Net.Security.RemoteCertificateValidationCallback System.Net.FtpWebRequest::<>f__am$cache1C\n\tRemoteCertificateValidationCallback_t3014364904 * ___U3CU3Ef__amU24cache1C_34;\n\t\/\/ System.Collections.Generic.Dictionary`2<System.String,System.Int32> System.Net.FtpWebRequest::<>f__switch$map5\n\tDictionary_2_t2736202052 * ___U3CU3Ef__switchU24map5_35;\n\t\/\/ System.Collections.Generic.Dictionary`2<System.String,System.Int32> System.Net.FtpWebRequest::<>f__switch$map6\n\tDictionary_2_t2736202052 * ___U3CU3Ef__switchU24map6_36;\n\npublic:\n\tinline static int32_t get_offset_of_supportedCommands_32() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305_StaticFields, ___supportedCommands_32)); }\n\tinline StringU5BU5D_t1281789340* get_supportedCommands_32() const { return ___supportedCommands_32; }\n\tinline StringU5BU5D_t1281789340** get_address_of_supportedCommands_32() { return &___supportedCommands_32; }\n\tinline void set_supportedCommands_32(StringU5BU5D_t1281789340* value)\n\t{\n\t\t___supportedCommands_32 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___supportedCommands_32), value);\n\t}\n\n\tinline static int32_t get_offset_of_U3CU3Ef__amU24cache1C_34() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305_StaticFields, ___U3CU3Ef__amU24cache1C_34)); }\n\tinline RemoteCertificateValidationCallback_t3014364904 * get_U3CU3Ef__amU24cache1C_34() const { return ___U3CU3Ef__amU24cache1C_34; }\n\tinline RemoteCertificateValidationCallback_t3014364904 ** get_address_of_U3CU3Ef__amU24cache1C_34() { return &___U3CU3Ef__amU24cache1C_34; }\n\tinline void set_U3CU3Ef__amU24cache1C_34(RemoteCertificateValidationCallback_t3014364904 * value)\n\t{\n\t\t___U3CU3Ef__amU24cache1C_34 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___U3CU3Ef__amU24cache1C_34), value);\n\t}\n\n\tinline static int32_t get_offset_of_U3CU3Ef__switchU24map5_35() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305_StaticFields, ___U3CU3Ef__switchU24map5_35)); }\n\tinline Dictionary_2_t2736202052 * get_U3CU3Ef__switchU24map5_35() const { return ___U3CU3Ef__switchU24map5_35; }\n\tinline Dictionary_2_t2736202052 ** get_address_of_U3CU3Ef__switchU24map5_35() { return &___U3CU3Ef__switchU24map5_35; }\n\tinline void set_U3CU3Ef__switchU24map5_35(Dictionary_2_t2736202052 * value)\n\t{\n\t\t___U3CU3Ef__switchU24map5_35 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___U3CU3Ef__switchU24map5_35), value);\n\t}\n\n\tinline static int32_t get_offset_of_U3CU3Ef__switchU24map6_36() { return static_cast<int32_t>(offsetof(FtpWebRequest_t1577818305_StaticFields, ___U3CU3Ef__switchU24map6_36)); }\n\tinline Dictionary_2_t2736202052 * get_U3CU3Ef__switchU24map6_36() const { return ___U3CU3Ef__switchU24map6_36; }\n\tinline Dictionary_2_t2736202052 ** get_address_of_U3CU3Ef__switchU24map6_36() { return &___U3CU3Ef__switchU24map6_36; }\n\tinline void set_U3CU3Ef__switchU24map6_36(Dictionary_2_t2736202052 * value)\n\t{\n\t\t___U3CU3Ef__switchU24map6_36 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___U3CU3Ef__switchU24map6_36), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FTPWEBREQUEST_T1577818305_H\n#ifndef FTPWEBRESPONSE_T3940763575_H\n#define FTPWEBRESPONSE_T3940763575_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.FtpWebResponse\nstruct  FtpWebResponse_t3940763575  : public WebResponse_t229922639\n{\npublic:\n\t\/\/ System.IO.Stream System.Net.FtpWebResponse::stream\n\tStream_t1273022909 * ___stream_1;\n\t\/\/ System.Uri System.Net.FtpWebResponse::uri\n\tUri_t100236324 * ___uri_2;\n\t\/\/ System.Net.FtpStatusCode System.Net.FtpWebResponse::statusCode\n\tint32_t ___statusCode_3;\n\t\/\/ System.DateTime System.Net.FtpWebResponse::lastModified\n\tDateTime_t3738529785  ___lastModified_4;\n\t\/\/ System.String System.Net.FtpWebResponse::bannerMessage\n\tString_t* ___bannerMessage_5;\n\t\/\/ System.String System.Net.FtpWebResponse::welcomeMessage\n\tString_t* ___welcomeMessage_6;\n\t\/\/ System.String System.Net.FtpWebResponse::exitMessage\n\tString_t* ___exitMessage_7;\n\t\/\/ System.String System.Net.FtpWebResponse::statusDescription\n\tString_t* ___statusDescription_8;\n\t\/\/ System.String System.Net.FtpWebResponse::method\n\tString_t* ___method_9;\n\t\/\/ System.Boolean System.Net.FtpWebResponse::disposed\n\tbool ___disposed_10;\n\t\/\/ System.Net.FtpWebRequest System.Net.FtpWebResponse::request\n\tFtpWebRequest_t1577818305 * ___request_11;\n\t\/\/ System.Int64 System.Net.FtpWebResponse::contentLength\n\tint64_t ___contentLength_12;\n\npublic:\n\tinline static int32_t get_offset_of_stream_1() { return static_cast<int32_t>(offsetof(FtpWebResponse_t3940763575, ___stream_1)); }\n\tinline Stream_t1273022909 * get_stream_1() const { return ___stream_1; }\n\tinline Stream_t1273022909 ** get_address_of_stream_1() { return &___stream_1; }\n\tinline void set_stream_1(Stream_t1273022909 * value)\n\t{\n\t\t___stream_1 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___stream_1), value);\n\t}\n\n\tinline static int32_t get_offset_of_uri_2() { return static_cast<int32_t>(offsetof(FtpWebResponse_t3940763575, ___uri_2)); }\n\tinline Uri_t100236324 * get_uri_2() const { return ___uri_2; }\n\tinline Uri_t100236324 ** get_address_of_uri_2() { return &___uri_2; }\n\tinline void set_uri_2(Uri_t100236324 * value)\n\t{\n\t\t___uri_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___uri_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_statusCode_3() { return static_cast<int32_t>(offsetof(FtpWebResponse_t3940763575, ___statusCode_3)); }\n\tinline int32_t get_statusCode_3() const { return ___statusCode_3; }\n\tinline int32_t* get_address_of_statusCode_3() { return &___statusCode_3; }\n\tinline void set_statusCode_3(int32_t value)\n\t{\n\t\t___statusCode_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_lastModified_4() { return static_cast<int32_t>(offsetof(FtpWebResponse_t3940763575, ___lastModified_4)); }\n\tinline DateTime_t3738529785  get_lastModified_4() const { return ___lastModified_4; }\n\tinline DateTime_t3738529785 * get_address_of_lastModified_4() { return &___lastModified_4; }\n\tinline void set_lastModified_4(DateTime_t3738529785  value)\n\t{\n\t\t___lastModified_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_bannerMessage_5() { return static_cast<int32_t>(offsetof(FtpWebResponse_t3940763575, ___bannerMessage_5)); }\n\tinline String_t* get_bannerMessage_5() const { return ___bannerMessage_5; }\n\tinline String_t** get_address_of_bannerMessage_5() { return &___bannerMessage_5; }\n\tinline void set_bannerMessage_5(String_t* value)\n\t{\n\t\t___bannerMessage_5 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___bannerMessage_5), value);\n\t}\n\n\tinline static int32_t get_offset_of_welcomeMessage_6() { return static_cast<int32_t>(offsetof(FtpWebResponse_t3940763575, ___welcomeMessage_6)); }\n\tinline String_t* get_welcomeMessage_6() const { return ___welcomeMessage_6; }\n\tinline String_t** get_address_of_welcomeMessage_6() { return &___welcomeMessage_6; }\n\tinline void set_welcomeMessage_6(String_t* value)\n\t{\n\t\t___welcomeMessage_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___welcomeMessage_6), value);\n\t}\n\n\tinline static int32_t get_offset_of_exitMessage_7() { return static_cast<int32_t>(offsetof(FtpWebResponse_t3940763575, ___exitMessage_7)); }\n\tinline String_t* get_exitMessage_7() const { return ___exitMessage_7; }\n\tinline String_t** get_address_of_exitMessage_7() { return &___exitMessage_7; }\n\tinline void set_exitMessage_7(String_t* value)\n\t{\n\t\t___exitMessage_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___exitMessage_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_statusDescription_8() { return static_cast<int32_t>(offsetof(FtpWebResponse_t3940763575, ___statusDescription_8)); }\n\tinline String_t* get_statusDescription_8() const { return ___statusDescription_8; }\n\tinline String_t** get_address_of_statusDescription_8() { return &___statusDescription_8; }\n\tinline void set_statusDescription_8(String_t* value)\n\t{\n\t\t___statusDescription_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___statusDescription_8), value);\n\t}\n\n\tinline static int32_t get_offset_of_method_9() { return static_cast<int32_t>(offsetof(FtpWebResponse_t3940763575, ___method_9)); }\n\tinline String_t* get_method_9() const { return ___method_9; }\n\tinline String_t** get_address_of_method_9() { return &___method_9; }\n\tinline void set_method_9(String_t* value)\n\t{\n\t\t___method_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___method_9), value);\n\t}\n\n\tinline static int32_t get_offset_of_disposed_10() { return static_cast<int32_t>(offsetof(FtpWebResponse_t3940763575, ___disposed_10)); }\n\tinline bool get_disposed_10() const { return ___disposed_10; }\n\tinline bool* get_address_of_disposed_10() { return &___disposed_10; }\n\tinline void set_disposed_10(bool value)\n\t{\n\t\t___disposed_10 = value;\n\t}\n\n\tinline static int32_t get_offset_of_request_11() { return static_cast<int32_t>(offsetof(FtpWebResponse_t3940763575, ___request_11)); }\n\tinline FtpWebRequest_t1577818305 * get_request_11() const { return ___request_11; }\n\tinline FtpWebRequest_t1577818305 ** get_address_of_request_11() { return &___request_11; }\n\tinline void set_request_11(FtpWebRequest_t1577818305 * value)\n\t{\n\t\t___request_11 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___request_11), value);\n\t}\n\n\tinline static int32_t get_offset_of_contentLength_12() { return static_cast<int32_t>(offsetof(FtpWebResponse_t3940763575, ___contentLength_12)); }\n\tinline int64_t get_contentLength_12() const { return ___contentLength_12; }\n\tinline int64_t* get_address_of_contentLength_12() { return &___contentLength_12; }\n\tinline void set_contentLength_12(int64_t value)\n\t{\n\t\t___contentLength_12 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ FTPWEBRESPONSE_T3940763575_H\n#ifndef HTTPWEBREQUEST_T1669436515_H\n#define HTTPWEBREQUEST_T1669436515_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.HttpWebRequest\nstruct  HttpWebRequest_t1669436515  : public WebRequest_t1939381076\n{\npublic:\n\t\/\/ System.Uri System.Net.HttpWebRequest::requestUri\n\tUri_t100236324 * ___requestUri_6;\n\t\/\/ System.Uri System.Net.HttpWebRequest::actualUri\n\tUri_t100236324 * ___actualUri_7;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::hostChanged\n\tbool ___hostChanged_8;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::allowAutoRedirect\n\tbool ___allowAutoRedirect_9;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::allowBuffering\n\tbool ___allowBuffering_10;\n\t\/\/ System.Security.Cryptography.X509Certificates.X509CertificateCollection System.Net.HttpWebRequest::certificates\n\tX509CertificateCollection_t3399372417 * ___certificates_11;\n\t\/\/ System.String System.Net.HttpWebRequest::connectionGroup\n\tString_t* ___connectionGroup_12;\n\t\/\/ System.Int64 System.Net.HttpWebRequest::contentLength\n\tint64_t ___contentLength_13;\n\t\/\/ System.Net.HttpContinueDelegate System.Net.HttpWebRequest::continueDelegate\n\tHttpContinueDelegate_t3009151163 * ___continueDelegate_14;\n\t\/\/ System.Net.CookieContainer System.Net.HttpWebRequest::cookieContainer\n\tCookieContainer_t2331592909 * ___cookieContainer_15;\n\t\/\/ System.Net.ICredentials System.Net.HttpWebRequest::credentials\n\tRuntimeObject* ___credentials_16;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::haveResponse\n\tbool ___haveResponse_17;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::haveRequest\n\tbool ___haveRequest_18;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::requestSent\n\tbool ___requestSent_19;\n\t\/\/ System.Net.WebHeaderCollection System.Net.HttpWebRequest::webHeaders\n\tWebHeaderCollection_t1942268960 * ___webHeaders_20;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::keepAlive\n\tbool ___keepAlive_21;\n\t\/\/ System.Int32 System.Net.HttpWebRequest::maxAutoRedirect\n\tint32_t ___maxAutoRedirect_22;\n\t\/\/ System.String System.Net.HttpWebRequest::mediaType\n\tString_t* ___mediaType_23;\n\t\/\/ System.String System.Net.HttpWebRequest::method\n\tString_t* ___method_24;\n\t\/\/ System.String System.Net.HttpWebRequest::initialMethod\n\tString_t* ___initialMethod_25;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::pipelined\n\tbool ___pipelined_26;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::preAuthenticate\n\tbool ___preAuthenticate_27;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::usedPreAuth\n\tbool ___usedPreAuth_28;\n\t\/\/ System.Version System.Net.HttpWebRequest::version\n\tVersion_t3456873960 * ___version_29;\n\t\/\/ System.Version System.Net.HttpWebRequest::actualVersion\n\tVersion_t3456873960 * ___actualVersion_30;\n\t\/\/ System.Net.IWebProxy System.Net.HttpWebRequest::proxy\n\tRuntimeObject* ___proxy_31;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::sendChunked\n\tbool ___sendChunked_32;\n\t\/\/ System.Net.ServicePoint System.Net.HttpWebRequest::servicePoint\n\tServicePoint_t2786966844 * ___servicePoint_33;\n\t\/\/ System.Int32 System.Net.HttpWebRequest::timeout\n\tint32_t ___timeout_34;\n\t\/\/ System.Net.WebConnectionStream System.Net.HttpWebRequest::writeStream\n\tWebConnectionStream_t2170064850 * ___writeStream_35;\n\t\/\/ System.Net.HttpWebResponse System.Net.HttpWebRequest::webResponse\n\tHttpWebResponse_t3286585418 * ___webResponse_36;\n\t\/\/ System.Net.WebAsyncResult System.Net.HttpWebRequest::asyncWrite\n\tWebAsyncResult_t3421962937 * ___asyncWrite_37;\n\t\/\/ System.Net.WebAsyncResult System.Net.HttpWebRequest::asyncRead\n\tWebAsyncResult_t3421962937 * ___asyncRead_38;\n\t\/\/ System.EventHandler System.Net.HttpWebRequest::abortHandler\n\tEventHandler_t1348719766 * ___abortHandler_39;\n\t\/\/ System.Int32 System.Net.HttpWebRequest::aborted\n\tint32_t ___aborted_40;\n\t\/\/ System.Int32 System.Net.HttpWebRequest::redirects\n\tint32_t ___redirects_41;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::expectContinue\n\tbool ___expectContinue_42;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::authCompleted\n\tbool ___authCompleted_43;\n\t\/\/ System.Byte[] System.Net.HttpWebRequest::bodyBuffer\n\tByteU5BU5D_t4116647657* ___bodyBuffer_44;\n\t\/\/ System.Int32 System.Net.HttpWebRequest::bodyBufferLength\n\tint32_t ___bodyBufferLength_45;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::getResponseCalled\n\tbool ___getResponseCalled_46;\n\t\/\/ System.Exception System.Net.HttpWebRequest::saved_exc\n\tException_t * ___saved_exc_47;\n\t\/\/ System.Object System.Net.HttpWebRequest::locker\n\tRuntimeObject * ___locker_48;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::is_ntlm_auth\n\tbool ___is_ntlm_auth_49;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::finished_reading\n\tbool ___finished_reading_50;\n\t\/\/ System.Net.WebConnection System.Net.HttpWebRequest::WebConnection\n\tWebConnection_t3982808322 * ___WebConnection_51;\n\t\/\/ System.Net.DecompressionMethods System.Net.HttpWebRequest::auto_decomp\n\tint32_t ___auto_decomp_52;\n\t\/\/ System.Int32 System.Net.HttpWebRequest::readWriteTimeout\n\tint32_t ___readWriteTimeout_54;\n\t\/\/ System.Boolean System.Net.HttpWebRequest::unsafe_auth_blah\n\tbool ___unsafe_auth_blah_55;\n\npublic:\n\tinline static int32_t get_offset_of_requestUri_6() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___requestUri_6)); }\n\tinline Uri_t100236324 * get_requestUri_6() const { return ___requestUri_6; }\n\tinline Uri_t100236324 ** get_address_of_requestUri_6() { return &___requestUri_6; }\n\tinline void set_requestUri_6(Uri_t100236324 * value)\n\t{\n\t\t___requestUri_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___requestUri_6), value);\n\t}\n\n\tinline static int32_t get_offset_of_actualUri_7() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___actualUri_7)); }\n\tinline Uri_t100236324 * get_actualUri_7() const { return ___actualUri_7; }\n\tinline Uri_t100236324 ** get_address_of_actualUri_7() { return &___actualUri_7; }\n\tinline void set_actualUri_7(Uri_t100236324 * value)\n\t{\n\t\t___actualUri_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___actualUri_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_hostChanged_8() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___hostChanged_8)); }\n\tinline bool get_hostChanged_8() const { return ___hostChanged_8; }\n\tinline bool* get_address_of_hostChanged_8() { return &___hostChanged_8; }\n\tinline void set_hostChanged_8(bool value)\n\t{\n\t\t___hostChanged_8 = value;\n\t}\n\n\tinline static int32_t get_offset_of_allowAutoRedirect_9() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___allowAutoRedirect_9)); }\n\tinline bool get_allowAutoRedirect_9() const { return ___allowAutoRedirect_9; }\n\tinline bool* get_address_of_allowAutoRedirect_9() { return &___allowAutoRedirect_9; }\n\tinline void set_allowAutoRedirect_9(bool value)\n\t{\n\t\t___allowAutoRedirect_9 = value;\n\t}\n\n\tinline static int32_t get_offset_of_allowBuffering_10() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___allowBuffering_10)); }\n\tinline bool get_allowBuffering_10() const { return ___allowBuffering_10; }\n\tinline bool* get_address_of_allowBuffering_10() { return &___allowBuffering_10; }\n\tinline void set_allowBuffering_10(bool value)\n\t{\n\t\t___allowBuffering_10 = value;\n\t}\n\n\tinline static int32_t get_offset_of_certificates_11() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___certificates_11)); }\n\tinline X509CertificateCollection_t3399372417 * get_certificates_11() const { return ___certificates_11; }\n\tinline X509CertificateCollection_t3399372417 ** get_address_of_certificates_11() { return &___certificates_11; }\n\tinline void set_certificates_11(X509CertificateCollection_t3399372417 * value)\n\t{\n\t\t___certificates_11 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___certificates_11), value);\n\t}\n\n\tinline static int32_t get_offset_of_connectionGroup_12() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___connectionGroup_12)); }\n\tinline String_t* get_connectionGroup_12() const { return ___connectionGroup_12; }\n\tinline String_t** get_address_of_connectionGroup_12() { return &___connectionGroup_12; }\n\tinline void set_connectionGroup_12(String_t* value)\n\t{\n\t\t___connectionGroup_12 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___connectionGroup_12), value);\n\t}\n\n\tinline static int32_t get_offset_of_contentLength_13() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___contentLength_13)); }\n\tinline int64_t get_contentLength_13() const { return ___contentLength_13; }\n\tinline int64_t* get_address_of_contentLength_13() { return &___contentLength_13; }\n\tinline void set_contentLength_13(int64_t value)\n\t{\n\t\t___contentLength_13 = value;\n\t}\n\n\tinline static int32_t get_offset_of_continueDelegate_14() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___continueDelegate_14)); }\n\tinline HttpContinueDelegate_t3009151163 * get_continueDelegate_14() const { return ___continueDelegate_14; }\n\tinline HttpContinueDelegate_t3009151163 ** get_address_of_continueDelegate_14() { return &___continueDelegate_14; }\n\tinline void set_continueDelegate_14(HttpContinueDelegate_t3009151163 * value)\n\t{\n\t\t___continueDelegate_14 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___continueDelegate_14), value);\n\t}\n\n\tinline static int32_t get_offset_of_cookieContainer_15() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___cookieContainer_15)); }\n\tinline CookieContainer_t2331592909 * get_cookieContainer_15() const { return ___cookieContainer_15; }\n\tinline CookieContainer_t2331592909 ** get_address_of_cookieContainer_15() { return &___cookieContainer_15; }\n\tinline void set_cookieContainer_15(CookieContainer_t2331592909 * value)\n\t{\n\t\t___cookieContainer_15 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___cookieContainer_15), value);\n\t}\n\n\tinline static int32_t get_offset_of_credentials_16() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___credentials_16)); }\n\tinline RuntimeObject* get_credentials_16() const { return ___credentials_16; }\n\tinline RuntimeObject** get_address_of_credentials_16() { return &___credentials_16; }\n\tinline void set_credentials_16(RuntimeObject* value)\n\t{\n\t\t___credentials_16 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___credentials_16), value);\n\t}\n\n\tinline static int32_t get_offset_of_haveResponse_17() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___haveResponse_17)); }\n\tinline bool get_haveResponse_17() const { return ___haveResponse_17; }\n\tinline bool* get_address_of_haveResponse_17() { return &___haveResponse_17; }\n\tinline void set_haveResponse_17(bool value)\n\t{\n\t\t___haveResponse_17 = value;\n\t}\n\n\tinline static int32_t get_offset_of_haveRequest_18() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___haveRequest_18)); }\n\tinline bool get_haveRequest_18() const { return ___haveRequest_18; }\n\tinline bool* get_address_of_haveRequest_18() { return &___haveRequest_18; }\n\tinline void set_haveRequest_18(bool value)\n\t{\n\t\t___haveRequest_18 = value;\n\t}\n\n\tinline static int32_t get_offset_of_requestSent_19() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___requestSent_19)); }\n\tinline bool get_requestSent_19() const { return ___requestSent_19; }\n\tinline bool* get_address_of_requestSent_19() { return &___requestSent_19; }\n\tinline void set_requestSent_19(bool value)\n\t{\n\t\t___requestSent_19 = value;\n\t}\n\n\tinline static int32_t get_offset_of_webHeaders_20() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___webHeaders_20)); }\n\tinline WebHeaderCollection_t1942268960 * get_webHeaders_20() const { return ___webHeaders_20; }\n\tinline WebHeaderCollection_t1942268960 ** get_address_of_webHeaders_20() { return &___webHeaders_20; }\n\tinline void set_webHeaders_20(WebHeaderCollection_t1942268960 * value)\n\t{\n\t\t___webHeaders_20 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___webHeaders_20), value);\n\t}\n\n\tinline static int32_t get_offset_of_keepAlive_21() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___keepAlive_21)); }\n\tinline bool get_keepAlive_21() const { return ___keepAlive_21; }\n\tinline bool* get_address_of_keepAlive_21() { return &___keepAlive_21; }\n\tinline void set_keepAlive_21(bool value)\n\t{\n\t\t___keepAlive_21 = value;\n\t}\n\n\tinline static int32_t get_offset_of_maxAutoRedirect_22() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___maxAutoRedirect_22)); }\n\tinline int32_t get_maxAutoRedirect_22() const { return ___maxAutoRedirect_22; }\n\tinline int32_t* get_address_of_maxAutoRedirect_22() { return &___maxAutoRedirect_22; }\n\tinline void set_maxAutoRedirect_22(int32_t value)\n\t{\n\t\t___maxAutoRedirect_22 = value;\n\t}\n\n\tinline static int32_t get_offset_of_mediaType_23() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___mediaType_23)); }\n\tinline String_t* get_mediaType_23() const { return ___mediaType_23; }\n\tinline String_t** get_address_of_mediaType_23() { return &___mediaType_23; }\n\tinline void set_mediaType_23(String_t* value)\n\t{\n\t\t___mediaType_23 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___mediaType_23), value);\n\t}\n\n\tinline static int32_t get_offset_of_method_24() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___method_24)); }\n\tinline String_t* get_method_24() const { return ___method_24; }\n\tinline String_t** get_address_of_method_24() { return &___method_24; }\n\tinline void set_method_24(String_t* value)\n\t{\n\t\t___method_24 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___method_24), value);\n\t}\n\n\tinline static int32_t get_offset_of_initialMethod_25() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___initialMethod_25)); }\n\tinline String_t* get_initialMethod_25() const { return ___initialMethod_25; }\n\tinline String_t** get_address_of_initialMethod_25() { return &___initialMethod_25; }\n\tinline void set_initialMethod_25(String_t* value)\n\t{\n\t\t___initialMethod_25 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___initialMethod_25), value);\n\t}\n\n\tinline static int32_t get_offset_of_pipelined_26() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___pipelined_26)); }\n\tinline bool get_pipelined_26() const { return ___pipelined_26; }\n\tinline bool* get_address_of_pipelined_26() { return &___pipelined_26; }\n\tinline void set_pipelined_26(bool value)\n\t{\n\t\t___pipelined_26 = value;\n\t}\n\n\tinline static int32_t get_offset_of_preAuthenticate_27() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___preAuthenticate_27)); }\n\tinline bool get_preAuthenticate_27() const { return ___preAuthenticate_27; }\n\tinline bool* get_address_of_preAuthenticate_27() { return &___preAuthenticate_27; }\n\tinline void set_preAuthenticate_27(bool value)\n\t{\n\t\t___preAuthenticate_27 = value;\n\t}\n\n\tinline static int32_t get_offset_of_usedPreAuth_28() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___usedPreAuth_28)); }\n\tinline bool get_usedPreAuth_28() const { return ___usedPreAuth_28; }\n\tinline bool* get_address_of_usedPreAuth_28() { return &___usedPreAuth_28; }\n\tinline void set_usedPreAuth_28(bool value)\n\t{\n\t\t___usedPreAuth_28 = value;\n\t}\n\n\tinline static int32_t get_offset_of_version_29() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___version_29)); }\n\tinline Version_t3456873960 * get_version_29() const { return ___version_29; }\n\tinline Version_t3456873960 ** get_address_of_version_29() { return &___version_29; }\n\tinline void set_version_29(Version_t3456873960 * value)\n\t{\n\t\t___version_29 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___version_29), value);\n\t}\n\n\tinline static int32_t get_offset_of_actualVersion_30() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___actualVersion_30)); }\n\tinline Version_t3456873960 * get_actualVersion_30() const { return ___actualVersion_30; }\n\tinline Version_t3456873960 ** get_address_of_actualVersion_30() { return &___actualVersion_30; }\n\tinline void set_actualVersion_30(Version_t3456873960 * value)\n\t{\n\t\t___actualVersion_30 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___actualVersion_30), value);\n\t}\n\n\tinline static int32_t get_offset_of_proxy_31() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___proxy_31)); }\n\tinline RuntimeObject* get_proxy_31() const { return ___proxy_31; }\n\tinline RuntimeObject** get_address_of_proxy_31() { return &___proxy_31; }\n\tinline void set_proxy_31(RuntimeObject* value)\n\t{\n\t\t___proxy_31 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___proxy_31), value);\n\t}\n\n\tinline static int32_t get_offset_of_sendChunked_32() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___sendChunked_32)); }\n\tinline bool get_sendChunked_32() const { return ___sendChunked_32; }\n\tinline bool* get_address_of_sendChunked_32() { return &___sendChunked_32; }\n\tinline void set_sendChunked_32(bool value)\n\t{\n\t\t___sendChunked_32 = value;\n\t}\n\n\tinline static int32_t get_offset_of_servicePoint_33() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___servicePoint_33)); }\n\tinline ServicePoint_t2786966844 * get_servicePoint_33() const { return ___servicePoint_33; }\n\tinline ServicePoint_t2786966844 ** get_address_of_servicePoint_33() { return &___servicePoint_33; }\n\tinline void set_servicePoint_33(ServicePoint_t2786966844 * value)\n\t{\n\t\t___servicePoint_33 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___servicePoint_33), value);\n\t}\n\n\tinline static int32_t get_offset_of_timeout_34() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___timeout_34)); }\n\tinline int32_t get_timeout_34() const { return ___timeout_34; }\n\tinline int32_t* get_address_of_timeout_34() { return &___timeout_34; }\n\tinline void set_timeout_34(int32_t value)\n\t{\n\t\t___timeout_34 = value;\n\t}\n\n\tinline static int32_t get_offset_of_writeStream_35() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___writeStream_35)); }\n\tinline WebConnectionStream_t2170064850 * get_writeStream_35() const { return ___writeStream_35; }\n\tinline WebConnectionStream_t2170064850 ** get_address_of_writeStream_35() { return &___writeStream_35; }\n\tinline void set_writeStream_35(WebConnectionStream_t2170064850 * value)\n\t{\n\t\t___writeStream_35 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___writeStream_35), value);\n\t}\n\n\tinline static int32_t get_offset_of_webResponse_36() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___webResponse_36)); }\n\tinline HttpWebResponse_t3286585418 * get_webResponse_36() const { return ___webResponse_36; }\n\tinline HttpWebResponse_t3286585418 ** get_address_of_webResponse_36() { return &___webResponse_36; }\n\tinline void set_webResponse_36(HttpWebResponse_t3286585418 * value)\n\t{\n\t\t___webResponse_36 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___webResponse_36), value);\n\t}\n\n\tinline static int32_t get_offset_of_asyncWrite_37() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___asyncWrite_37)); }\n\tinline WebAsyncResult_t3421962937 * get_asyncWrite_37() const { return ___asyncWrite_37; }\n\tinline WebAsyncResult_t3421962937 ** get_address_of_asyncWrite_37() { return &___asyncWrite_37; }\n\tinline void set_asyncWrite_37(WebAsyncResult_t3421962937 * value)\n\t{\n\t\t___asyncWrite_37 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___asyncWrite_37), value);\n\t}\n\n\tinline static int32_t get_offset_of_asyncRead_38() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___asyncRead_38)); }\n\tinline WebAsyncResult_t3421962937 * get_asyncRead_38() const { return ___asyncRead_38; }\n\tinline WebAsyncResult_t3421962937 ** get_address_of_asyncRead_38() { return &___asyncRead_38; }\n\tinline void set_asyncRead_38(WebAsyncResult_t3421962937 * value)\n\t{\n\t\t___asyncRead_38 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___asyncRead_38), value);\n\t}\n\n\tinline static int32_t get_offset_of_abortHandler_39() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___abortHandler_39)); }\n\tinline EventHandler_t1348719766 * get_abortHandler_39() const { return ___abortHandler_39; }\n\tinline EventHandler_t1348719766 ** get_address_of_abortHandler_39() { return &___abortHandler_39; }\n\tinline void set_abortHandler_39(EventHandler_t1348719766 * value)\n\t{\n\t\t___abortHandler_39 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___abortHandler_39), value);\n\t}\n\n\tinline static int32_t get_offset_of_aborted_40() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___aborted_40)); }\n\tinline int32_t get_aborted_40() const { return ___aborted_40; }\n\tinline int32_t* get_address_of_aborted_40() { return &___aborted_40; }\n\tinline void set_aborted_40(int32_t value)\n\t{\n\t\t___aborted_40 = value;\n\t}\n\n\tinline static int32_t get_offset_of_redirects_41() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___redirects_41)); }\n\tinline int32_t get_redirects_41() const { return ___redirects_41; }\n\tinline int32_t* get_address_of_redirects_41() { return &___redirects_41; }\n\tinline void set_redirects_41(int32_t value)\n\t{\n\t\t___redirects_41 = value;\n\t}\n\n\tinline static int32_t get_offset_of_expectContinue_42() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___expectContinue_42)); }\n\tinline bool get_expectContinue_42() const { return ___expectContinue_42; }\n\tinline bool* get_address_of_expectContinue_42() { return &___expectContinue_42; }\n\tinline void set_expectContinue_42(bool value)\n\t{\n\t\t___expectContinue_42 = value;\n\t}\n\n\tinline static int32_t get_offset_of_authCompleted_43() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___authCompleted_43)); }\n\tinline bool get_authCompleted_43() const { return ___authCompleted_43; }\n\tinline bool* get_address_of_authCompleted_43() { return &___authCompleted_43; }\n\tinline void set_authCompleted_43(bool value)\n\t{\n\t\t___authCompleted_43 = value;\n\t}\n\n\tinline static int32_t get_offset_of_bodyBuffer_44() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___bodyBuffer_44)); }\n\tinline ByteU5BU5D_t4116647657* get_bodyBuffer_44() const { return ___bodyBuffer_44; }\n\tinline ByteU5BU5D_t4116647657** get_address_of_bodyBuffer_44() { return &___bodyBuffer_44; }\n\tinline void set_bodyBuffer_44(ByteU5BU5D_t4116647657* value)\n\t{\n\t\t___bodyBuffer_44 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___bodyBuffer_44), value);\n\t}\n\n\tinline static int32_t get_offset_of_bodyBufferLength_45() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___bodyBufferLength_45)); }\n\tinline int32_t get_bodyBufferLength_45() const { return ___bodyBufferLength_45; }\n\tinline int32_t* get_address_of_bodyBufferLength_45() { return &___bodyBufferLength_45; }\n\tinline void set_bodyBufferLength_45(int32_t value)\n\t{\n\t\t___bodyBufferLength_45 = value;\n\t}\n\n\tinline static int32_t get_offset_of_getResponseCalled_46() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___getResponseCalled_46)); }\n\tinline bool get_getResponseCalled_46() const { return ___getResponseCalled_46; }\n\tinline bool* get_address_of_getResponseCalled_46() { return &___getResponseCalled_46; }\n\tinline void set_getResponseCalled_46(bool value)\n\t{\n\t\t___getResponseCalled_46 = value;\n\t}\n\n\tinline static int32_t get_offset_of_saved_exc_47() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___saved_exc_47)); }\n\tinline Exception_t * get_saved_exc_47() const { return ___saved_exc_47; }\n\tinline Exception_t ** get_address_of_saved_exc_47() { return &___saved_exc_47; }\n\tinline void set_saved_exc_47(Exception_t * value)\n\t{\n\t\t___saved_exc_47 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___saved_exc_47), value);\n\t}\n\n\tinline static int32_t get_offset_of_locker_48() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___locker_48)); }\n\tinline RuntimeObject * get_locker_48() const { return ___locker_48; }\n\tinline RuntimeObject ** get_address_of_locker_48() { return &___locker_48; }\n\tinline void set_locker_48(RuntimeObject * value)\n\t{\n\t\t___locker_48 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___locker_48), value);\n\t}\n\n\tinline static int32_t get_offset_of_is_ntlm_auth_49() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___is_ntlm_auth_49)); }\n\tinline bool get_is_ntlm_auth_49() const { return ___is_ntlm_auth_49; }\n\tinline bool* get_address_of_is_ntlm_auth_49() { return &___is_ntlm_auth_49; }\n\tinline void set_is_ntlm_auth_49(bool value)\n\t{\n\t\t___is_ntlm_auth_49 = value;\n\t}\n\n\tinline static int32_t get_offset_of_finished_reading_50() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___finished_reading_50)); }\n\tinline bool get_finished_reading_50() const { return ___finished_reading_50; }\n\tinline bool* get_address_of_finished_reading_50() { return &___finished_reading_50; }\n\tinline void set_finished_reading_50(bool value)\n\t{\n\t\t___finished_reading_50 = value;\n\t}\n\n\tinline static int32_t get_offset_of_WebConnection_51() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___WebConnection_51)); }\n\tinline WebConnection_t3982808322 * get_WebConnection_51() const { return ___WebConnection_51; }\n\tinline WebConnection_t3982808322 ** get_address_of_WebConnection_51() { return &___WebConnection_51; }\n\tinline void set_WebConnection_51(WebConnection_t3982808322 * value)\n\t{\n\t\t___WebConnection_51 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___WebConnection_51), value);\n\t}\n\n\tinline static int32_t get_offset_of_auto_decomp_52() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___auto_decomp_52)); }\n\tinline int32_t get_auto_decomp_52() const { return ___auto_decomp_52; }\n\tinline int32_t* get_address_of_auto_decomp_52() { return &___auto_decomp_52; }\n\tinline void set_auto_decomp_52(int32_t value)\n\t{\n\t\t___auto_decomp_52 = value;\n\t}\n\n\tinline static int32_t get_offset_of_readWriteTimeout_54() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___readWriteTimeout_54)); }\n\tinline int32_t get_readWriteTimeout_54() const { return ___readWriteTimeout_54; }\n\tinline int32_t* get_address_of_readWriteTimeout_54() { return &___readWriteTimeout_54; }\n\tinline void set_readWriteTimeout_54(int32_t value)\n\t{\n\t\t___readWriteTimeout_54 = value;\n\t}\n\n\tinline static int32_t get_offset_of_unsafe_auth_blah_55() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515, ___unsafe_auth_blah_55)); }\n\tinline bool get_unsafe_auth_blah_55() const { return ___unsafe_auth_blah_55; }\n\tinline bool* get_address_of_unsafe_auth_blah_55() { return &___unsafe_auth_blah_55; }\n\tinline void set_unsafe_auth_blah_55(bool value)\n\t{\n\t\t___unsafe_auth_blah_55 = value;\n\t}\n};\n\nstruct HttpWebRequest_t1669436515_StaticFields\n{\npublic:\n\t\/\/ System.Int32 System.Net.HttpWebRequest::defaultMaxResponseHeadersLength\n\tint32_t ___defaultMaxResponseHeadersLength_53;\n\npublic:\n\tinline static int32_t get_offset_of_defaultMaxResponseHeadersLength_53() { return static_cast<int32_t>(offsetof(HttpWebRequest_t1669436515_StaticFields, ___defaultMaxResponseHeadersLength_53)); }\n\tinline int32_t get_defaultMaxResponseHeadersLength_53() const { return ___defaultMaxResponseHeadersLength_53; }\n\tinline int32_t* get_address_of_defaultMaxResponseHeadersLength_53() { return &___defaultMaxResponseHeadersLength_53; }\n\tinline void set_defaultMaxResponseHeadersLength_53(int32_t value)\n\t{\n\t\t___defaultMaxResponseHeadersLength_53 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ HTTPWEBREQUEST_T1669436515_H\n#ifndef SOCKETASYNCCALL_T1521370843_H\n#define SOCKETASYNCCALL_T1521370843_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.Socket\/SocketAsyncCall\nstruct  SocketAsyncCall_t1521370843  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SOCKETASYNCCALL_T1521370843_H\n#ifndef SOCKETEXCEPTION_T3852068672_H\n#define SOCKETEXCEPTION_T3852068672_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Net.Sockets.SocketException\nstruct  SocketException_t3852068672  : public Win32Exception_t3234146298\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ SOCKETEXCEPTION_T3852068672_H\n\n\n\n\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1000 = { sizeof (NameValueCollection_t407452768), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1000[2] = \n{\n\tNameValueCollection_t407452768::get_offset_of_cachedAllKeys_10(),\n\tNameValueCollection_t407452768::get_offset_of_cachedAll_11(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1001 = { sizeof (CategoryAttribute_t39585132), -1, sizeof(CategoryAttribute_t39585132_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1001[3] = \n{\n\tCategoryAttribute_t39585132::get_offset_of_category_0(),\n\tCategoryAttribute_t39585132::get_offset_of_IsLocalized_1(),\n\tCategoryAttribute_t39585132_StaticFields::get_offset_of_lockobj_2(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1002 = { sizeof (Component_t3620823400), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1002[3] = \n{\n\tComponent_t3620823400::get_offset_of_event_handlers_1(),\n\tComponent_t3620823400::get_offset_of_mySite_2(),\n\tComponent_t3620823400::get_offset_of_disposedEvent_3(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1003 = { sizeof (DefaultEventAttribute_t3124666540), -1, sizeof(DefaultEventAttribute_t3124666540_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1003[2] = \n{\n\tDefaultEventAttribute_t3124666540::get_offset_of_eventName_0(),\n\tDefaultEventAttribute_t3124666540_StaticFields::get_offset_of_Default_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1004 = { sizeof (DefaultPropertyAttribute_t1952442862), -1, sizeof(DefaultPropertyAttribute_t1952442862_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1004[2] = \n{\n\tDefaultPropertyAttribute_t1952442862::get_offset_of_property_name_0(),\n\tDefaultPropertyAttribute_t1952442862_StaticFields::get_offset_of_Default_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1005 = { sizeof (DefaultValueAttribute_t587583663), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1005[1] = \n{\n\tDefaultValueAttribute_t587583663::get_offset_of_DefaultValue_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1006 = { sizeof (DescriptionAttribute_t874390736), -1, sizeof(DescriptionAttribute_t874390736_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1006[2] = \n{\n\tDescriptionAttribute_t874390736::get_offset_of_desc_0(),\n\tDescriptionAttribute_t874390736_StaticFields::get_offset_of_Default_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1007 = { sizeof (DesignerCategoryAttribute_t2912925731), -1, sizeof(DesignerCategoryAttribute_t2912925731_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1007[5] = \n{\n\tDesignerCategoryAttribute_t2912925731::get_offset_of_category_0(),\n\tDesignerCategoryAttribute_t2912925731_StaticFields::get_offset_of_Component_1(),\n\tDesignerCategoryAttribute_t2912925731_StaticFields::get_offset_of_Form_2(),\n\tDesignerCategoryAttribute_t2912925731_StaticFields::get_offset_of_Generic_3(),\n\tDesignerCategoryAttribute_t2912925731_StaticFields::get_offset_of_Default_4(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1008 = { sizeof (EditorBrowsableAttribute_t1475454531), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1008[1] = \n{\n\tEditorBrowsableAttribute_t1475454531::get_offset_of_state_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1009 = { sizeof (EditorBrowsableState_t2839071299)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1009[4] = \n{\n\tEditorBrowsableState_t2839071299::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1010 = { sizeof (ListEntry_t1182276877), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1010[3] = \n{\n\tListEntry_t1182276877::get_offset_of_key_0(),\n\tListEntry_t1182276877::get_offset_of_value_1(),\n\tListEntry_t1182276877::get_offset_of_next_2(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1011 = { sizeof (EventHandlerList_t1108123056), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1011[2] = \n{\n\tEventHandlerList_t1108123056::get_offset_of_entries_0(),\n\tEventHandlerList_t1108123056::get_offset_of_null_entry_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1012 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1013 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1014 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1015 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1016 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1017 = { sizeof (ProgressChangedEventArgs_t3227452477), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1017[2] = \n{\n\tProgressChangedEventArgs_t3227452477::get_offset_of_progress_1(),\n\tProgressChangedEventArgs_t3227452477::get_offset_of_state_2(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1018 = { sizeof (RecommendedAsConfigurableAttribute_t279829077), -1, sizeof(RecommendedAsConfigurableAttribute_t279829077_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1018[4] = \n{\n\tRecommendedAsConfigurableAttribute_t279829077::get_offset_of_recommendedAsConfigurable_0(),\n\tRecommendedAsConfigurableAttribute_t279829077_StaticFields::get_offset_of_Default_1(),\n\tRecommendedAsConfigurableAttribute_t279829077_StaticFields::get_offset_of_No_2(),\n\tRecommendedAsConfigurableAttribute_t279829077_StaticFields::get_offset_of_Yes_3(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1019 = { sizeof (TypeConverter_t2249118273), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1020 = { sizeof (TypeConverterAttribute_t3271584429), -1, sizeof(TypeConverterAttribute_t3271584429_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1020[2] = \n{\n\tTypeConverterAttribute_t3271584429_StaticFields::get_offset_of_Default_0(),\n\tTypeConverterAttribute_t3271584429::get_offset_of_converter_type_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1021 = { sizeof (Win32Exception_t3234146298), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1021[1] = \n{\n\tWin32Exception_t3234146298::get_offset_of_native_error_code_11(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1022 = { sizeof (CompressionMode_t3714291783)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1022[3] = \n{\n\tCompressionMode_t3714291783::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1023 = { sizeof (DeflateStream_t4175168077), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1023[8] = \n{\n\tDeflateStream_t4175168077::get_offset_of_base_stream_1(),\n\tDeflateStream_t4175168077::get_offset_of_mode_2(),\n\tDeflateStream_t4175168077::get_offset_of_leaveOpen_3(),\n\tDeflateStream_t4175168077::get_offset_of_disposed_4(),\n\tDeflateStream_t4175168077::get_offset_of_feeder_5(),\n\tDeflateStream_t4175168077::get_offset_of_z_stream_6(),\n\tDeflateStream_t4175168077::get_offset_of_io_buffer_7(),\n\tDeflateStream_t4175168077::get_offset_of_data_8(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1024 = { sizeof (UnmanagedReadOrWrite_t876388624), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1025 = { sizeof (ReadMethod_t893206259), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1026 = { sizeof (WriteMethod_t2538911768), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1027 = { sizeof (GZipStream_t3417139389), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1027[1] = \n{\n\tGZipStream_t3417139389::get_offset_of_deflateStream_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1028 = { sizeof (AuthenticatedStream_t3415418016), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1028[2] = \n{\n\tAuthenticatedStream_t3415418016::get_offset_of_innerStream_1(),\n\tAuthenticatedStream_t3415418016::get_offset_of_leaveStreamOpen_2(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1029 = { sizeof (AuthenticationLevel_t1236753641)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1029[4] = \n{\n\tAuthenticationLevel_t1236753641::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1030 = { sizeof (SslPolicyErrors_t2205227823)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1030[5] = \n{\n\tSslPolicyErrors_t2205227823::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1031 = { sizeof (SslStream_t2700741536), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1031[3] = \n{\n\tSslStream_t2700741536::get_offset_of_ssl_stream_3(),\n\tSslStream_t2700741536::get_offset_of_validation_callback_4(),\n\tSslStream_t2700741536::get_offset_of_selection_callback_5(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1032 = { sizeof (U3CBeginAuthenticateAsClientU3Ec__AnonStorey7_t1222040293), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1032[2] = \n{\n\tU3CBeginAuthenticateAsClientU3Ec__AnonStorey7_t1222040293::get_offset_of_clientCertificates_0(),\n\tU3CBeginAuthenticateAsClientU3Ec__AnonStorey7_t1222040293::get_offset_of_U3CU3Ef__this_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1033 = { sizeof (U3CBeginAuthenticateAsServerU3Ec__AnonStorey8_t2934725513), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1033[2] = \n{\n\tU3CBeginAuthenticateAsServerU3Ec__AnonStorey8_t2934725513::get_offset_of_serverCertificate_0(),\n\tU3CBeginAuthenticateAsServerU3Ec__AnonStorey8_t2934725513::get_offset_of_U3CU3Ef__this_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1034 = { sizeof (AddressFamily_t2612549059)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1034[32] = \n{\n\tAddressFamily_t2612549059::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1035 = { sizeof (LingerOption_t2688985448), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1035[2] = \n{\n\tLingerOption_t2688985448::get_offset_of_enabled_0(),\n\tLingerOption_t2688985448::get_offset_of_seconds_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1036 = { sizeof (MulticastOption_t3861143239), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1037 = { sizeof (NetworkStream_t4071955934), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1037[6] = \n{\n\tNetworkStream_t4071955934::get_offset_of_access_1(),\n\tNetworkStream_t4071955934::get_offset_of_socket_2(),\n\tNetworkStream_t4071955934::get_offset_of_owns_socket_3(),\n\tNetworkStream_t4071955934::get_offset_of_readable_4(),\n\tNetworkStream_t4071955934::get_offset_of_writeable_5(),\n\tNetworkStream_t4071955934::get_offset_of_disposed_6(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1038 = { sizeof (ProtocolType_t303635025)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1038[26] = \n{\n\tProtocolType_t303635025::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1039 = { sizeof (SelectMode_t1123767949)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1039[4] = \n{\n\tSelectMode_t1123767949::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1040 = { sizeof (Socket_t1119025450), -1, sizeof(Socket_t1119025450_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1040[23] = \n{\n\tSocket_t1119025450::get_offset_of_readQ_0(),\n\tSocket_t1119025450::get_offset_of_writeQ_1(),\n\tSocket_t1119025450::get_offset_of_islistening_2(),\n\tSocket_t1119025450::get_offset_of_useoverlappedIO_3(),\n\tSocket_t1119025450::get_offset_of_MinListenPort_4(),\n\tSocket_t1119025450::get_offset_of_MaxListenPort_5(),\n\tSocket_t1119025450_StaticFields::get_offset_of_ipv4Supported_6(),\n\tSocket_t1119025450_StaticFields::get_offset_of_ipv6Supported_7(),\n\tSocket_t1119025450::get_offset_of_linger_timeout_8(),\n\tSocket_t1119025450::get_offset_of_socket_9(),\n\tSocket_t1119025450::get_offset_of_address_family_10(),\n\tSocket_t1119025450::get_offset_of_socket_type_11(),\n\tSocket_t1119025450::get_offset_of_protocol_type_12(),\n\tSocket_t1119025450::get_offset_of_blocking_13(),\n\tSocket_t1119025450::get_offset_of_blocking_thread_14(),\n\tSocket_t1119025450::get_offset_of_isbound_15(),\n\tSocket_t1119025450_StaticFields::get_offset_of_current_bind_count_16(),\n\tSocket_t1119025450::get_offset_of_max_bind_count_17(),\n\tSocket_t1119025450::get_offset_of_connected_18(),\n\tSocket_t1119025450::get_offset_of_closed_19(),\n\tSocket_t1119025450::get_offset_of_disposed_20(),\n\tSocket_t1119025450::get_offset_of_seed_endpoint_21(),\n\tSocket_t1119025450_StaticFields::get_offset_of_check_socket_policy_22(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1041 = { sizeof (SocketOperation_t1288882297)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1041[15] = \n{\n\tSocketOperation_t1288882297::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1042 = { sizeof (SocketAsyncResult_t2080034863), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1042[25] = \n{\n\tSocketAsyncResult_t2080034863::get_offset_of_Sock_0(),\n\tSocketAsyncResult_t2080034863::get_offset_of_handle_1(),\n\tSocketAsyncResult_t2080034863::get_offset_of_state_2(),\n\tSocketAsyncResult_t2080034863::get_offset_of_callback_3(),\n\tSocketAsyncResult_t2080034863::get_offset_of_waithandle_4(),\n\tSocketAsyncResult_t2080034863::get_offset_of_delayedException_5(),\n\tSocketAsyncResult_t2080034863::get_offset_of_EndPoint_6(),\n\tSocketAsyncResult_t2080034863::get_offset_of_Buffer_7(),\n\tSocketAsyncResult_t2080034863::get_offset_of_Offset_8(),\n\tSocketAsyncResult_t2080034863::get_offset_of_Size_9(),\n\tSocketAsyncResult_t2080034863::get_offset_of_SockFlags_10(),\n\tSocketAsyncResult_t2080034863::get_offset_of_AcceptSocket_11(),\n\tSocketAsyncResult_t2080034863::get_offset_of_Addresses_12(),\n\tSocketAsyncResult_t2080034863::get_offset_of_Port_13(),\n\tSocketAsyncResult_t2080034863::get_offset_of_Buffers_14(),\n\tSocketAsyncResult_t2080034863::get_offset_of_ReuseSocket_15(),\n\tSocketAsyncResult_t2080034863::get_offset_of_acc_socket_16(),\n\tSocketAsyncResult_t2080034863::get_offset_of_total_17(),\n\tSocketAsyncResult_t2080034863::get_offset_of_completed_sync_18(),\n\tSocketAsyncResult_t2080034863::get_offset_of_completed_19(),\n\tSocketAsyncResult_t2080034863::get_offset_of_blocking_20(),\n\tSocketAsyncResult_t2080034863::get_offset_of_error_21(),\n\tSocketAsyncResult_t2080034863::get_offset_of_operation_22(),\n\tSocketAsyncResult_t2080034863::get_offset_of_ares_23(),\n\tSocketAsyncResult_t2080034863::get_offset_of_EndCalled_24(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1043 = { sizeof (Worker_t2051517921), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1043[3] = \n{\n\tWorker_t2051517921::get_offset_of_result_0(),\n\tWorker_t2051517921::get_offset_of_requireSocketSecurity_1(),\n\tWorker_t2051517921::get_offset_of_send_so_far_2(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1044 = { sizeof (SocketAsyncCall_t1521370843), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1045 = { sizeof (SocketError_t3760144386)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1045[48] = \n{\n\tSocketError_t3760144386::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1046 = { sizeof (SocketException_t3852068672), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1047 = { sizeof (SocketFlags_t2969870452)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1047[11] = \n{\n\tSocketFlags_t2969870452::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1048 = { sizeof (SocketOptionLevel_t201167901)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1048[6] = \n{\n\tSocketOptionLevel_t201167901::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1049 = { sizeof (SocketOptionName_t403346465)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1049[44] = \n{\n\tSocketOptionName_t403346465::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1050 = { sizeof (SocketShutdown_t2687738148)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1050[4] = \n{\n\tSocketShutdown_t2687738148::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1051 = { sizeof (SocketType_t2175930299)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1051[7] = \n{\n\tSocketType_t2175930299::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1052 = { sizeof (AuthenticationManager_t2084001809), -1, sizeof(AuthenticationManager_t2084001809_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1052[3] = \n{\n\tAuthenticationManager_t2084001809_StaticFields::get_offset_of_modules_0(),\n\tAuthenticationManager_t2084001809_StaticFields::get_offset_of_locker_1(),\n\tAuthenticationManager_t2084001809_StaticFields::get_offset_of_credential_policy_2(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1053 = { sizeof (Authorization_t542416582), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1053[4] = \n{\n\tAuthorization_t542416582::get_offset_of_token_0(),\n\tAuthorization_t542416582::get_offset_of_complete_1(),\n\tAuthorization_t542416582::get_offset_of_connectionGroupId_2(),\n\tAuthorization_t542416582::get_offset_of_module_3(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1054 = { sizeof (BasicClient_t3463561396), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1055 = { sizeof (ChunkStream_t2634567336), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1055[9] = \n{\n\tChunkStream_t2634567336::get_offset_of_headers_0(),\n\tChunkStream_t2634567336::get_offset_of_chunkSize_1(),\n\tChunkStream_t2634567336::get_offset_of_chunkRead_2(),\n\tChunkStream_t2634567336::get_offset_of_state_3(),\n\tChunkStream_t2634567336::get_offset_of_saved_4(),\n\tChunkStream_t2634567336::get_offset_of_sawCR_5(),\n\tChunkStream_t2634567336::get_offset_of_gotit_6(),\n\tChunkStream_t2634567336::get_offset_of_trailerState_7(),\n\tChunkStream_t2634567336::get_offset_of_chunks_8(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1056 = { sizeof (State_t4053927353)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1056[5] = \n{\n\tState_t4053927353::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1057 = { sizeof (Chunk_t1455545707), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1057[2] = \n{\n\tChunk_t1455545707::get_offset_of_Bytes_0(),\n\tChunk_t1455545707::get_offset_of_Offset_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1058 = { sizeof (Cookie_t993873397), -1, sizeof(Cookie_t993873397_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1058[18] = \n{\n\tCookie_t993873397::get_offset_of_comment_0(),\n\tCookie_t993873397::get_offset_of_commentUri_1(),\n\tCookie_t993873397::get_offset_of_discard_2(),\n\tCookie_t993873397::get_offset_of_domain_3(),\n\tCookie_t993873397::get_offset_of_expires_4(),\n\tCookie_t993873397::get_offset_of_httpOnly_5(),\n\tCookie_t993873397::get_offset_of_name_6(),\n\tCookie_t993873397::get_offset_of_path_7(),\n\tCookie_t993873397::get_offset_of_port_8(),\n\tCookie_t993873397::get_offset_of_ports_9(),\n\tCookie_t993873397::get_offset_of_secure_10(),\n\tCookie_t993873397::get_offset_of_timestamp_11(),\n\tCookie_t993873397::get_offset_of_val_12(),\n\tCookie_t993873397::get_offset_of_version_13(),\n\tCookie_t993873397_StaticFields::get_offset_of_reservedCharsName_14(),\n\tCookie_t993873397_StaticFields::get_offset_of_portSeparators_15(),\n\tCookie_t993873397_StaticFields::get_offset_of_tspecials_16(),\n\tCookie_t993873397::get_offset_of_exact_domain_17(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1059 = { sizeof (CookieCollection_t3881042616), -1, sizeof(CookieCollection_t3881042616_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1059[2] = \n{\n\tCookieCollection_t3881042616::get_offset_of_list_0(),\n\tCookieCollection_t3881042616_StaticFields::get_offset_of_Comparer_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1060 = { sizeof (CookieCollectionComparer_t1373927847), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1061 = { sizeof (CookieContainer_t2331592909), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1061[4] = \n{\n\tCookieContainer_t2331592909::get_offset_of_capacity_0(),\n\tCookieContainer_t2331592909::get_offset_of_perDomainCapacity_1(),\n\tCookieContainer_t2331592909::get_offset_of_maxCookieSize_2(),\n\tCookieContainer_t2331592909::get_offset_of_cookies_3(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1062 = { sizeof (CookieException_t2325395694), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1063 = { sizeof (DecompressionMethods_t1612219745)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1063[4] = \n{\n\tDecompressionMethods_t1612219745::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1064 = { sizeof (DefaultCertificatePolicy_t3607119947), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1065 = { sizeof (DigestHeaderParser_t341650829), -1, sizeof(DigestHeaderParser_t341650829_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1065[5] = \n{\n\tDigestHeaderParser_t341650829::get_offset_of_header_0(),\n\tDigestHeaderParser_t341650829::get_offset_of_length_1(),\n\tDigestHeaderParser_t341650829::get_offset_of_pos_2(),\n\tDigestHeaderParser_t341650829_StaticFields::get_offset_of_keywords_3(),\n\tDigestHeaderParser_t341650829::get_offset_of_values_4(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1066 = { sizeof (DigestSession_t1433627624), -1, sizeof(DigestSession_t1433627624_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1066[6] = \n{\n\tDigestSession_t1433627624_StaticFields::get_offset_of_rng_0(),\n\tDigestSession_t1433627624::get_offset_of_lastUse_1(),\n\tDigestSession_t1433627624::get_offset_of__nc_2(),\n\tDigestSession_t1433627624::get_offset_of_hash_3(),\n\tDigestSession_t1433627624::get_offset_of_parser_4(),\n\tDigestSession_t1433627624::get_offset_of__cnonce_5(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1067 = { sizeof (DigestClient_t660790528), -1, sizeof(DigestClient_t660790528_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1067[1] = \n{\n\tDigestClient_t660790528_StaticFields::get_offset_of_cache_0(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1068 = { sizeof (Dns_t384099571), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1069 = { sizeof (DownloadProgressChangedEventArgs_t2828131725), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1069[2] = \n{\n\tDownloadProgressChangedEventArgs_t2828131725::get_offset_of_received_3(),\n\tDownloadProgressChangedEventArgs_t2828131725::get_offset_of_total_4(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1070 = { sizeof (EndPoint_t982345378), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1071 = { sizeof (FileWebRequest_t591858885), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1071[14] = \n{\n\tFileWebRequest_t591858885::get_offset_of_uri_6(),\n\tFileWebRequest_t591858885::get_offset_of_webHeaders_7(),\n\tFileWebRequest_t591858885::get_offset_of_credentials_8(),\n\tFileWebRequest_t591858885::get_offset_of_connectionGroup_9(),\n\tFileWebRequest_t591858885::get_offset_of_contentLength_10(),\n\tFileWebRequest_t591858885::get_offset_of_fileAccess_11(),\n\tFileWebRequest_t591858885::get_offset_of_method_12(),\n\tFileWebRequest_t591858885::get_offset_of_proxy_13(),\n\tFileWebRequest_t591858885::get_offset_of_preAuthenticate_14(),\n\tFileWebRequest_t591858885::get_offset_of_timeout_15(),\n\tFileWebRequest_t591858885::get_offset_of_webResponse_16(),\n\tFileWebRequest_t591858885::get_offset_of_requestEndEvent_17(),\n\tFileWebRequest_t591858885::get_offset_of_requesting_18(),\n\tFileWebRequest_t591858885::get_offset_of_asyncResponding_19(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1072 = { sizeof (FileWebStream_t586107972), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1072[1] = \n{\n\tFileWebStream_t586107972::get_offset_of_webRequest_15(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1073 = { sizeof (GetResponseCallback_t2326689408), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1074 = { sizeof (FileWebRequestCreator_t1781329382), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1075 = { sizeof (FileWebResponse_t544571260), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1075[5] = \n{\n\tFileWebResponse_t544571260::get_offset_of_responseUri_1(),\n\tFileWebResponse_t544571260::get_offset_of_fileStream_2(),\n\tFileWebResponse_t544571260::get_offset_of_contentLength_3(),\n\tFileWebResponse_t544571260::get_offset_of_webHeaders_4(),\n\tFileWebResponse_t544571260::get_offset_of_disposed_5(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1076 = { sizeof (FtpAsyncResult_t3265664217), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1076[9] = \n{\n\tFtpAsyncResult_t3265664217::get_offset_of_response_0(),\n\tFtpAsyncResult_t3265664217::get_offset_of_waitHandle_1(),\n\tFtpAsyncResult_t3265664217::get_offset_of_exception_2(),\n\tFtpAsyncResult_t3265664217::get_offset_of_callback_3(),\n\tFtpAsyncResult_t3265664217::get_offset_of_stream_4(),\n\tFtpAsyncResult_t3265664217::get_offset_of_state_5(),\n\tFtpAsyncResult_t3265664217::get_offset_of_completed_6(),\n\tFtpAsyncResult_t3265664217::get_offset_of_synch_7(),\n\tFtpAsyncResult_t3265664217::get_offset_of_locker_8(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1077 = { sizeof (FtpDataStream_t1366729715), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1077[5] = \n{\n\tFtpDataStream_t1366729715::get_offset_of_request_1(),\n\tFtpDataStream_t1366729715::get_offset_of_networkStream_2(),\n\tFtpDataStream_t1366729715::get_offset_of_disposed_3(),\n\tFtpDataStream_t1366729715::get_offset_of_isRead_4(),\n\tFtpDataStream_t1366729715::get_offset_of_totalRead_5(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1078 = { sizeof (WriteDelegate_t2016697242), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1079 = { sizeof (ReadDelegate_t4266946825), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1080 = { sizeof (FtpRequestCreator_t2926281497), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1081 = { sizeof (FtpStatus_t2376455776), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1081[2] = \n{\n\tFtpStatus_t2376455776::get_offset_of_statusCode_0(),\n\tFtpStatus_t2376455776::get_offset_of_statusDescription_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1082 = { sizeof (FtpStatusCode_t58879933)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1082[38] = \n{\n\tFtpStatusCode_t58879933::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1083 = { sizeof (FtpWebRequest_t1577818305), -1, sizeof(FtpWebRequest_t1577818305_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1083[31] = \n{\n\tFtpWebRequest_t1577818305::get_offset_of_requestUri_6(),\n\tFtpWebRequest_t1577818305::get_offset_of_file_name_7(),\n\tFtpWebRequest_t1577818305::get_offset_of_servicePoint_8(),\n\tFtpWebRequest_t1577818305::get_offset_of_origDataStream_9(),\n\tFtpWebRequest_t1577818305::get_offset_of_dataStream_10(),\n\tFtpWebRequest_t1577818305::get_offset_of_controlStream_11(),\n\tFtpWebRequest_t1577818305::get_offset_of_controlReader_12(),\n\tFtpWebRequest_t1577818305::get_offset_of_credentials_13(),\n\tFtpWebRequest_t1577818305::get_offset_of_hostEntry_14(),\n\tFtpWebRequest_t1577818305::get_offset_of_localEndPoint_15(),\n\tFtpWebRequest_t1577818305::get_offset_of_proxy_16(),\n\tFtpWebRequest_t1577818305::get_offset_of_timeout_17(),\n\tFtpWebRequest_t1577818305::get_offset_of_rwTimeout_18(),\n\tFtpWebRequest_t1577818305::get_offset_of_offset_19(),\n\tFtpWebRequest_t1577818305::get_offset_of_binary_20(),\n\tFtpWebRequest_t1577818305::get_offset_of_enableSsl_21(),\n\tFtpWebRequest_t1577818305::get_offset_of_usePassive_22(),\n\tFtpWebRequest_t1577818305::get_offset_of_keepAlive_23(),\n\tFtpWebRequest_t1577818305::get_offset_of_method_24(),\n\tFtpWebRequest_t1577818305::get_offset_of_renameTo_25(),\n\tFtpWebRequest_t1577818305::get_offset_of_locker_26(),\n\tFtpWebRequest_t1577818305::get_offset_of_requestState_27(),\n\tFtpWebRequest_t1577818305::get_offset_of_asyncResult_28(),\n\tFtpWebRequest_t1577818305::get_offset_of_ftpResponse_29(),\n\tFtpWebRequest_t1577818305::get_offset_of_requestStream_30(),\n\tFtpWebRequest_t1577818305::get_offset_of_initial_path_31(),\n\tFtpWebRequest_t1577818305_StaticFields::get_offset_of_supportedCommands_32(),\n\tFtpWebRequest_t1577818305::get_offset_of_callback_33(),\n\tFtpWebRequest_t1577818305_StaticFields::get_offset_of_U3CU3Ef__amU24cache1C_34(),\n\tFtpWebRequest_t1577818305_StaticFields::get_offset_of_U3CU3Ef__switchU24map5_35(),\n\tFtpWebRequest_t1577818305_StaticFields::get_offset_of_U3CU3Ef__switchU24map6_36(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1084 = { sizeof (RequestState_t4091696808)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1084[10] = \n{\n\tRequestState_t4091696808::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1085 = { sizeof (FtpWebResponse_t3940763575), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1085[12] = \n{\n\tFtpWebResponse_t3940763575::get_offset_of_stream_1(),\n\tFtpWebResponse_t3940763575::get_offset_of_uri_2(),\n\tFtpWebResponse_t3940763575::get_offset_of_statusCode_3(),\n\tFtpWebResponse_t3940763575::get_offset_of_lastModified_4(),\n\tFtpWebResponse_t3940763575::get_offset_of_bannerMessage_5(),\n\tFtpWebResponse_t3940763575::get_offset_of_welcomeMessage_6(),\n\tFtpWebResponse_t3940763575::get_offset_of_exitMessage_7(),\n\tFtpWebResponse_t3940763575::get_offset_of_statusDescription_8(),\n\tFtpWebResponse_t3940763575::get_offset_of_method_9(),\n\tFtpWebResponse_t3940763575::get_offset_of_disposed_10(),\n\tFtpWebResponse_t3940763575::get_offset_of_request_11(),\n\tFtpWebResponse_t3940763575::get_offset_of_contentLength_12(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1086 = { sizeof (GlobalProxySelection_t1166292522), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1087 = { sizeof (HttpListenerBasicIdentity_t3019963659), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1087[1] = \n{\n\tHttpListenerBasicIdentity_t3019963659::get_offset_of_password_2(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1088 = { sizeof (HttpRequestCreator_t1984314013), -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1089 = { sizeof (HttpRequestHeader_t4258090762)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1089[42] = \n{\n\tHttpRequestHeader_t4258090762::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1090 = { sizeof (HttpResponseHeader_t1526164768)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1090[31] = \n{\n\tHttpResponseHeader_t1526164768::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1091 = { sizeof (HttpStatusCode_t3035121829)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };\nextern const int32_t g_FieldOffsetTable1091[47] = \n{\n\tHttpStatusCode_t3035121829::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1092 = { sizeof (HttpVersion_t346520293), -1, sizeof(HttpVersion_t346520293_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1092[2] = \n{\n\tHttpVersion_t346520293_StaticFields::get_offset_of_Version10_0(),\n\tHttpVersion_t346520293_StaticFields::get_offset_of_Version11_1(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1093 = { sizeof (HttpWebRequest_t1669436515), -1, sizeof(HttpWebRequest_t1669436515_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1093[50] = \n{\n\tHttpWebRequest_t1669436515::get_offset_of_requestUri_6(),\n\tHttpWebRequest_t1669436515::get_offset_of_actualUri_7(),\n\tHttpWebRequest_t1669436515::get_offset_of_hostChanged_8(),\n\tHttpWebRequest_t1669436515::get_offset_of_allowAutoRedirect_9(),\n\tHttpWebRequest_t1669436515::get_offset_of_allowBuffering_10(),\n\tHttpWebRequest_t1669436515::get_offset_of_certificates_11(),\n\tHttpWebRequest_t1669436515::get_offset_of_connectionGroup_12(),\n\tHttpWebRequest_t1669436515::get_offset_of_contentLength_13(),\n\tHttpWebRequest_t1669436515::get_offset_of_continueDelegate_14(),\n\tHttpWebRequest_t1669436515::get_offset_of_cookieContainer_15(),\n\tHttpWebRequest_t1669436515::get_offset_of_credentials_16(),\n\tHttpWebRequest_t1669436515::get_offset_of_haveResponse_17(),\n\tHttpWebRequest_t1669436515::get_offset_of_haveRequest_18(),\n\tHttpWebRequest_t1669436515::get_offset_of_requestSent_19(),\n\tHttpWebRequest_t1669436515::get_offset_of_webHeaders_20(),\n\tHttpWebRequest_t1669436515::get_offset_of_keepAlive_21(),\n\tHttpWebRequest_t1669436515::get_offset_of_maxAutoRedirect_22(),\n\tHttpWebRequest_t1669436515::get_offset_of_mediaType_23(),\n\tHttpWebRequest_t1669436515::get_offset_of_method_24(),\n\tHttpWebRequest_t1669436515::get_offset_of_initialMethod_25(),\n\tHttpWebRequest_t1669436515::get_offset_of_pipelined_26(),\n\tHttpWebRequest_t1669436515::get_offset_of_preAuthenticate_27(),\n\tHttpWebRequest_t1669436515::get_offset_of_usedPreAuth_28(),\n\tHttpWebRequest_t1669436515::get_offset_of_version_29(),\n\tHttpWebRequest_t1669436515::get_offset_of_actualVersion_30(),\n\tHttpWebRequest_t1669436515::get_offset_of_proxy_31(),\n\tHttpWebRequest_t1669436515::get_offset_of_sendChunked_32(),\n\tHttpWebRequest_t1669436515::get_offset_of_servicePoint_33(),\n\tHttpWebRequest_t1669436515::get_offset_of_timeout_34(),\n\tHttpWebRequest_t1669436515::get_offset_of_writeStream_35(),\n\tHttpWebRequest_t1669436515::get_offset_of_webResponse_36(),\n\tHttpWebRequest_t1669436515::get_offset_of_asyncWrite_37(),\n\tHttpWebRequest_t1669436515::get_offset_of_asyncRead_38(),\n\tHttpWebRequest_t1669436515::get_offset_of_abortHandler_39(),\n\tHttpWebRequest_t1669436515::get_offset_of_aborted_40(),\n\tHttpWebRequest_t1669436515::get_offset_of_redirects_41(),\n\tHttpWebRequest_t1669436515::get_offset_of_expectContinue_42(),\n\tHttpWebRequest_t1669436515::get_offset_of_authCompleted_43(),\n\tHttpWebRequest_t1669436515::get_offset_of_bodyBuffer_44(),\n\tHttpWebRequest_t1669436515::get_offset_of_bodyBufferLength_45(),\n\tHttpWebRequest_t1669436515::get_offset_of_getResponseCalled_46(),\n\tHttpWebRequest_t1669436515::get_offset_of_saved_exc_47(),\n\tHttpWebRequest_t1669436515::get_offset_of_locker_48(),\n\tHttpWebRequest_t1669436515::get_offset_of_is_ntlm_auth_49(),\n\tHttpWebRequest_t1669436515::get_offset_of_finished_reading_50(),\n\tHttpWebRequest_t1669436515::get_offset_of_WebConnection_51(),\n\tHttpWebRequest_t1669436515::get_offset_of_auto_decomp_52(),\n\tHttpWebRequest_t1669436515_StaticFields::get_offset_of_defaultMaxResponseHeadersLength_53(),\n\tHttpWebRequest_t1669436515::get_offset_of_readWriteTimeout_54(),\n\tHttpWebRequest_t1669436515::get_offset_of_unsafe_auth_blah_55(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1094 = { sizeof (HttpWebResponse_t3286585418), -1, sizeof(HttpWebResponse_t3286585418_StaticFields), 0 };\nextern const int32_t g_FieldOffsetTable1094[14] = \n{\n\tHttpWebResponse_t3286585418::get_offset_of_uri_1(),\n\tHttpWebResponse_t3286585418::get_offset_of_webHeaders_2(),\n\tHttpWebResponse_t3286585418::get_offset_of_cookieCollection_3(),\n\tHttpWebResponse_t3286585418::get_offset_of_method_4(),\n\tHttpWebResponse_t3286585418::get_offset_of_version_5(),\n\tHttpWebResponse_t3286585418::get_offset_of_statusCode_6(),\n\tHttpWebResponse_t3286585418::get_offset_of_statusDescription_7(),\n\tHttpWebResponse_t3286585418::get_offset_of_contentLength_8(),\n\tHttpWebResponse_t3286585418::get_offset_of_contentType_9(),\n\tHttpWebResponse_t3286585418::get_offset_of_cookie_container_10(),\n\tHttpWebResponse_t3286585418::get_offset_of_disposed_11(),\n\tHttpWebResponse_t3286585418::get_offset_of_stream_12(),\n\tHttpWebResponse_t3286585418::get_offset_of_cookieExpiresFormats_13(),\n\tHttpWebResponse_t3286585418_StaticFields::get_offset_of_U3CU3Ef__switchU24map8_14(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1095 = { sizeof (CookieParser_t2349142305), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable1095[3] = \n{\n\tCookieParser_t2349142305::get_offset_of_header_0(),\n\tCookieParser_t2349142305::get_offset_of_pos_1(),\n\tCookieParser_t2349142305::get_offset_of_length_2(),\n};\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1096 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1097 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1098 = { 0, -1, 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1099 = { 0, -1, 0, 0 };\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n","avg_line_length":39.3109305761,"max_line_length":200,"alphanum_fraction":0.8168692581,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":15152,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":9.0,"content":"#define __STDC_LIMIT_MACROS\n#include <stdint.h>\n\n\/\/ Fix for PROGMEM warning.\n#include <avr\/pgmspace.h>\n#undef PROGMEM\n#define PROGMEM __attribute__((section(\".progmem.data\")))\n#undef PSTR\n#define PSTR(s) (__extension__({static prog_char __c[] PROGMEM = (s); &__c[0];}))\n\n#include <Arduino.h>\n#include <SoftwareSerial.h>\n#include <TinyGPS.h>\n#include <EtherCard.h>\n\n\/\/ 'off_t' is defined in stdio.h which we don't use on Arduino.\n\/\/ We don't really need this but it's useful to document the purpose of\n\/\/ a variable with a type.\ntypedef size_t off_t;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GPS\n\n#define GPS_RATE_1HZ  F(\"$PMTK220,1000*1F\")\n#define GPS_RATE_5HZ  F(\"$PMTK220,200*2C\")\n#define GPS_RATE_10HZ F(\"$PMTK220,100*2F\")\n\n\/\/ NOTE: You must set SoftwareSerial.h _SS_MAX_RX_BUFF 64 to 128 in\n\/\/ order to receive more than one NMEA string.\n#define GPS_OUTPUT_GGA       F(\"$PMTK314,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0*29\")\n#define GPS_OUTPUT_RMCGGA    F(\"$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0*28\")\n#define GPS_OUTPUT_RMCGGAGSA F(\"$PMTK314,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0*29\")\n#define GPS_OUTPUT_RMCGSA    F(\"$PMTK314,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0*28\")\n#define GPS_OUTPUT_RMC       F(\"$PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*29\")\n#define GPS_OUTPUT_ALLDATA   F(\"$PMTK314,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0*29\")\n\n#define GPS_BAUD_4800   F(\"$PMTK251,4800*14\")\n#define GPS_BAUD_9600   F(\"$PMTK251,9600*17\")\n#define GPS_BAUD_19200  F(\"$PMTK251,19200*22\")\n#define GPS_BAUD_38400  F(\"$PMTK251,38400*27\")\n#define GPS_BAUD_57600  F(\"$PMTK251,57600*2C\")\n#define GPS_BAUD_115200 F(\"$PMTK251,115200*1F\")\n\n#define GPS_RX 8\n#define GPS_TX 9\n\nstatic TinyGPS gps;\nstatic SoftwareSerial gps_serial(GPS_RX, GPS_TX);\n\nstatic void gps_setup()\n{\n    \/\/ Ensure GPS is using baud rate of 9600.\n    gps_serial.begin(9600);\n    gps_serial.println(GPS_BAUD_9600);\n    gps_serial.begin(19200);\n    gps_serial.println(GPS_BAUD_9600);\n    gps_serial.begin(38400);\n    gps_serial.println(GPS_BAUD_9600);\n    gps_serial.begin(57600);\n    gps_serial.println(GPS_BAUD_9600);\n    gps_serial.begin(115200);\n    gps_serial.println(GPS_BAUD_9600);\n\n    \/\/ Set our baud rate to 9600.\n    gps_serial.begin(9600);\n\n    \/\/ Set 1Hz update rate.\n    gps_serial.println(GPS_RATE_1HZ);\n\n    \/\/ Set the output sentence to RMC. RMC is the only sentence\n    \/\/ available on this GPS receiver which has the date as well\n    \/\/ as the time in the message.\n    gps_serial.println(GPS_OUTPUT_RMC);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PPS\n\n\/\/ ATmega 168 and 328:\n\/\/  - Pin 2 = Interrupt 0\n\/\/  - Pin 3 = Interrupt 1\n\n#define LED_PIN A4\n#define PPS_PIN 3\n#define PPS_INT 1\n\nstatic volatile uint32_t g_pps_time;\nstatic volatile bool g_waiting_for_fix;\n\nstatic void pps_interrupt()\n{\n    g_pps_time = micros();\n    g_waiting_for_fix = true;\n}\n\nstatic void pps_setup()\n{\n    g_pps_time = micros();\n\n    pinMode(LED_PIN, OUTPUT);\n    digitalWrite(LED_PIN, LOW);\n\n    pinMode(PPS_PIN, INPUT);\n    digitalWrite(PPS_PIN, HIGH);\n    attachInterrupt(PPS_INT, pps_interrupt, RISING);\n}\n\nstatic void pps_loop()\n{\n    uint32_t pps_state = micros() - g_pps_time < 100000 ? HIGH : LOW;\n    digitalWrite(LED_PIN, pps_state);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Web Server Utils\n\nextern int __bss_end;\nextern void *__brkval;\n\nstatic int32_t get_free_memory()\n{\n    int32_t free_memory;\n\n    if(__brkval)\n        free_memory = ((int32_t)&free_memory) - ((int32_t)__brkval);\n    else\n        free_memory = ((int32_t)&free_memory) - ((int32_t)&__bss_end);\n\n    return free_memory;\n}\n\nstatic char* print_dms(float degrees, char* buffer)\n{\n    float fValue = fabs(degrees);\n    int deg = (int) fValue;\n    float remainder = fValue-deg;\n    fValue = remainder*60.0;\n    int mins = (int) fValue;\n    remainder = fValue - mins;\n    fValue = remainder * 100.0;\n    int secs = (int) fValue;\n    remainder = fValue- secs;\n    fValue = remainder *1000;\n    int ptSec = (int) fValue;\n\n    sprintf(buffer, \"%d:%d:%d.%d\", deg, mins, secs, ptSec);\n\n    return buffer;\n}\n\nstatic char* print_ms_time(long ms, char* buffer)\n{\n    long t  = ms \/ 1000;\n    word h  = t \/ 3600;\n    byte m  = (t \/ 60) % 60;\n    byte s  = t % 60;\n    byte ss = (ms % 1000)\/100;\n\n    sprintf(buffer, \"%d%d:%0d%d:%d%d.%d\",\n        h\/10, h%10, m\/10, m%10, s\/10, s%10, ss);\n\n    return buffer;\n}\n\nstatic char* print_gps_time(char *buffer)\n{\n    int year;\n    byte month, day, hour, minute, second, hundredths;\n\n    gps.crack_datetime(\n        &year, &month, &day,\n        &hour, &minute, &second, &hundredths);\n\n    sprintf(buffer, \"%d-%02d-%02d %02d:%02d:%02d.%02d\",\n        year, month, day,\n        hour, minute, second, hundredths);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Web Server\n\nstatic void write_status_page(BufferFiller &response)\n{\n    char buffer[32];\n\n    response.emit_p(PSTR(\n        \"HTTP\/1.0 200 OK\\r\\n\"\n        \"Content-Type: text\/html\\r\\n\"\n        \"Pragma: no-cache\\r\\n\"\n        \"\\r\\n\"\n        \"<meta http-equiv='refresh' content='1'\/>\"\n        \"<title>Jystic NTP Server v0.1<\/title>\"));\n\n    print_gps_time(buffer);\n    response.emit_p(PSTR(\"<h1>UTC $S<h1>\"), buffer);\n\n    response.emit_p(PSTR(\"Running $S\\n\"),\n        print_ms_time(millis(), buffer));\n\n    response.emit_p(PSTR(\"Free mem $D\\n\"),\n        get_free_memory() );\n\n    uint32_t time_since_pps = micros() - g_pps_time;\n    response.emit_p(PSTR(\"Since PPS $S\\n\"),\n        print_ms_time(time_since_pps\/1000, buffer));\n}\n\n\/\/ NOTE: The request and response share the same underlying buffer, so\n\/\/ NOTE: make sure you don't access the request after you start writing\n\/\/ NOTE: the response.\nstatic word process_http_request(const char *request, BufferFiller &response)\n{\n    \/\/size_t r = strchr(request, '\\r') - request;\n    \/\/Serial.write((const uint8_t*)request, r);\n    \/\/Serial.println();\n\n    write_status_page(response);\n}\n\nstatic void http_loop(word pos)\n{\n    const char *request   = (const char *)ether.buffer + pos;\n    BufferFiller response = ether.tcpOffset();\n\n    \/\/ Process the request and build the response.\n    process_http_request(request, response);\n\n    \/\/ Send the response to the client.\n    ether.httpServerReply(response.position());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Ethernet Utils\n\n#define g_packet ether.buffer\n\ninline static uint8_t read_uint8(off_t offset)\n{\n    return g_packet[offset];\n}\n\nstatic uint16_t read_uint16(off_t offset)\n{\n    return ((uint16_t)g_packet[offset + 0] << 8)\n         | ((uint16_t)g_packet[offset + 1]);\n}\n\nstatic uint32_t read_uint32(off_t offset)\n{\n    return ((uint32_t)g_packet[offset + 0] << 24)\n         | ((uint32_t)g_packet[offset + 1] << 16)\n         | ((uint32_t)g_packet[offset + 2] <<  8)\n         | ((uint32_t)g_packet[offset + 3]      );\n}\n\nstatic void write_uint32(off_t offset, uint32_t value)\n{\n    g_packet[offset + 0] = (value >> 24) & 0xFF;\n    g_packet[offset + 1] = (value >> 16) & 0xFF;\n    g_packet[offset + 2] = (value >>  8) & 0xFF;\n    g_packet[offset + 3] = (value      ) & 0xFF;\n}\n\nstatic bool packet_is_udp(size_t len)\n{\n    return len >= 42\n        && g_packet[ETH_TYPE_H_P] == ETHTYPE_IP_H_V\n        && g_packet[ETH_TYPE_L_P] == ETHTYPE_IP_L_V\n        && g_packet[IP_HEADER_LEN_VER_P] == 0x45\n        && g_packet[IP_PROTO_P] == IP_PROTO_UDP_V;\n}\n\nstatic bool udp_dst_port_is(uint8_t port)\n{\n    return g_packet[UDP_DST_PORT_H_P] == 0\n        && g_packet[UDP_DST_PORT_L_P] == port;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NTP Time Utils\n\n#define NTP_EPOCH0 1900UL\n#define NTP_FRAC_MAX UINT32_MAX\n\n#define SECS_PER_MIN  (60UL)\n#define SECS_PER_HOUR (3600UL)\n#define SECS_PER_DAY  (SECS_PER_HOUR * 24UL)\n#define SECS_PER_YEAR (SECS_PER_DAY * 365UL)\n\nconst uint16_t g_month_days[] = {0,31,59,90,120,151,181,212,243,273,304,334};\n\n\/\/ The 64-bit NTP timestamp.\ntypedef struct {\n    uint32_t secs; \/\/ Seconds since 1 Jan 1900 UTC\n    uint32_t frac; \/\/ Fractions of a second, 1 unit == 1\/UINT32_MAX secs\n} timestamp_t;\n\ninline static bool is_leap_year(uint16_t year)\n{\n    return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);\n}\n\nstatic timestamp_t timestamp(\n    uint16_t year,\n    uint8_t month,\n    uint8_t day,\n    uint8_t hour,\n    uint8_t minute,\n    uint8_t second,\n    uint8_t hundredths)\n{\n    timestamp_t t;\n\n    t.secs = SECS_PER_YEAR * (year - NTP_EPOCH0)\n           + SECS_PER_DAY  * g_month_days[month-1]\n           + SECS_PER_DAY  * (day - 1)\n           + SECS_PER_HOUR * hour\n           + SECS_PER_MIN  * minute\n           + second;\n\n    \/\/ add extra day for each leap year since epoch 0\n    for (uint16_t y = NTP_EPOCH0; y < year; y++)\n    {\n        if (is_leap_year(y))\n        {\n            t.secs += SECS_PER_DAY;\n        }\n    }\n\n    \/\/ add extra day if this year is a leap year and we\n    \/\/ have passed February 29\n    if (is_leap_year(year) && month > 2)\n    {\n        t.secs += SECS_PER_DAY;\n    }\n\n    t.frac = hundredths * (NTP_FRAC_MAX\/100);\n\n    return t;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NTP Server\n\n#define NTP_PORT 123\n#define NTP_DATA_LEN 48\n\n#define NTP_DATA_P            (UDP_DATA_P + 0)\n#define NTP_FLAGS_P           (NTP_DATA_P + 0)\n#define NTP_STRATUM_P         (NTP_DATA_P + 1)\n#define NTP_POLL_P            (NTP_DATA_P + 2)\n#define NTP_PRECISION_P       (NTP_DATA_P + 3)\n#define NTP_ROOT_DELAY_P      (NTP_DATA_P + 4)\n#define NTP_ROOT_DISPERSION_P (NTP_DATA_P + 8)\n#define NTP_REFERENCE_ID_P    (NTP_DATA_P + 12)\n#define NTP_REFERENCE_TIME_P  (NTP_DATA_P + 16)\n#define NTP_TIME1_P           (NTP_DATA_P + 24)\n#define NTP_TIME2_P           (NTP_DATA_P + 32)\n#define NTP_TIME3_P           (NTP_DATA_P + 40)\n\nstatic void read_flags(uint8_t *leap_indicator, uint8_t *version, uint8_t *mode)\n{\n    uint8_t flags = read_uint8(NTP_FLAGS_P);\n\n    *leap_indicator = flags >> 6;\n    *version        = (flags & 0x38) >> 3;\n    *mode           = (flags & 0x7);\n}\n\nstatic timestamp_t last_fix_time()\n{\n    int year;\n    byte month, day, hour, minute, second, hundredths;\n\n    gps.crack_datetime(\n        &year, &month, &day,\n        &hour, &minute, &second, &hundredths);\n\n    return timestamp(\n        year, month, day,\n        hour, minute, second, hundredths);\n}\n\nstatic timestamp_t micros_to_timestamp(uint32_t micros)\n{\n    uint64_t us_since_pps = micros - g_pps_time;\n    uint64_t frac_since_pps = (NTP_FRAC_MAX * us_since_pps) \/ 1000000;\n\n    timestamp_t time = last_fix_time();\n\n    if (g_waiting_for_fix)\n    {\n        \/\/ pps is for the next fix\n        time.secs++;\n    }\n\n    uint64_t frac = time.frac + frac_since_pps;\n\n    while (frac > NTP_FRAC_MAX)\n    {\n        time.secs++;\n        frac -= NTP_FRAC_MAX;\n    }\n\n    time.frac += frac;\n\n    return time;\n}\n\nstatic volatile uint32_t g_receive_time;\n\nstatic timestamp_t last_receive_time()\n{\n    return micros_to_timestamp(g_receive_time);\n}\n\nstatic timestamp_t current_time()\n{\n    return micros_to_timestamp(micros());\n}\n\nstatic timestamp_t read_timestamp(off_t offset)\n{\n    timestamp_t t;\n    t.secs = read_uint32(offset+0);\n    t.frac = read_uint32(offset+4);\n    return t;\n}\n\nstatic void write_timestamp(off_t offset, timestamp_t time)\n{\n    write_uint32(offset+0, time.secs);\n    write_uint32(offset+4, time.frac);\n}\n\n\/\/ Check RFC5905 for further details about the format.\nconst uint8_t ntp_header[] PROGMEM = {\n    0x24,    \/\/ No warning \/ Version 3 \/ Server (packed bitfield)\n    1,       \/\/ Stratum 1 server (connected to GPS)\n    3,       \/\/ Polling interval\n    -20,     \/\/ Precision in log2 seconds (2^-20 is about 1us)\n    0,0,0,0, \/\/ Delay to reference clock (we have PPS, so effectively zero)\n    0,0,0,1, \/\/ Jitter of reference clock (the PPS is rated to +\/- 50ns)\n    'G','P','S',0, \/\/ Reference ID - we are using a GPS receiver\n};\n\nstatic void ntp_loop(uint32_t rxtime)\n{\n    if (!udp_dst_port_is(NTP_PORT)) return;\n\n    uint16_t len = read_uint16(UDP_LEN_H_P);\n\n    if (len < UDP_HEADER_LEN + NTP_DATA_LEN) return;\n\n    timestamp_t time1 = read_timestamp(NTP_TIME3_P);\n    timestamp_t time2 = micros_to_timestamp(rxtime);\n\n    memcpy_P(g_packet + NTP_DATA_P, ntp_header, sizeof ntp_header);\n\n    timestamp_t ref_time = last_fix_time();\n\n    write_timestamp(NTP_REFERENCE_TIME_P, ref_time);\n    write_timestamp(NTP_TIME1_P, time1);\n    write_timestamp(NTP_TIME2_P, time2);\n\n    timestamp_t time3 = current_time();\n    write_timestamp(NTP_TIME3_P, time3);\n\n    ether.makeUdpReply(\n        (char *)(g_packet + NTP_DATA_P), NTP_DATA_LEN, NTP_PORT);\n\n    Serial.print(F(\"NTP request from \"));\n    uint8_t *dst_ip = &g_packet[IP_DST_P];\n    ether.printIp(\"\", dst_ip);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Ethernet\n\n\/\/ MAC address must be unique on the LAN.\nstatic uint8_t mac_address[] = { 0x74,0x69,0x69,0x2D,0x30,0x32 };\nstatic uint8_t ip_address[] = { 1,1,1,100 };\n\n#define ETHERNET_BUFFER_SIZE 550\nuint8_t Ethernet::buffer[ETHERNET_BUFFER_SIZE];\n\n#define ETHERNET_CS_PIN 10\n\n#define ETHERNET_INT 0 \/\/ Pin 2 (on ATmega 168 and 328)\n\nstatic void packet_received_interrupt()\n{\n    g_receive_time = micros();\n}\n\nstatic void ethernet_setup()\n{\n    if (!ether.begin(ETHERNET_BUFFER_SIZE, mac_address, ETHERNET_CS_PIN))\n        Serial.println(F(\"Failed to access Ethernet controller\"));\n\n    ether.staticSetup(ip_address);\n\n    attachInterrupt(ETHERNET_INT, packet_received_interrupt, FALLING);\n}\n\nstatic void ethernet_loop()\n{\n    bool rxtime_valid = true;\n\n    for (;;)\n    {\n        uint8_t pktcnt = ether.packetCount();\n\n        if (pktcnt == 0)\n        {\n            \/\/ all packets processed, do\n            \/\/ housekeeping then return\n            ether.packetLoop(0);\n            return;\n        }\n\n        uint32_t rxtime = g_receive_time;\n        uint16_t len = ether.packetReceive();\n\n        if (rxtime_valid && packet_is_udp(len))\n        {\n            ntp_loop(rxtime);\n        }\n\n        uint16_t pos = ether.packetLoop(len);\n\n        \/\/ If we received a TCP packet then 'pos' is the index\n        \/\/ where the packet's data is stored in 'ether.buffer'.\n        if (pos != 0)\n        {\n            \/\/ Assume that it's an HTTP request.\n            http_loop(pos);\n        }\n\n        \/\/ The packet received interrupt only fires once per group\n        \/\/ of packets, so the time is only valid for the first packet\n        \/\/ after the 'pktcnt' is reset to zero.\n        rxtime_valid = false;\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Main\n\n\/\/ Baud rate for the UART serial port used for diagnostics.\n#define UART_BAUD_RATE 57600\n\nvoid setup()\n{\n    Serial.begin(UART_BAUD_RATE);\n    Serial.println(F(\"Jystic NTP Server v0.1\"));\n\n    pps_setup();\n    gps_setup();\n    ethernet_setup();\n}\n\nstatic void gps_loop()\n{\n    while (gps_serial.available())\n    {\n        char c = gps_serial.read();\n        \/\/Serial.write(c);\n        if (gps.encode(c))\n        {\n            g_waiting_for_fix = false;\n        }\n    }\n}\n\nvoid loop()\n{\n    pps_loop();\n    gps_loop();\n    ethernet_loop();\n}\n\n\/\/ vim: ft=arduino\n","avg_line_length":25.9452054795,"max_line_length":81,"alphanum_fraction":0.6200501584,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":30258,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Copyright (c) 2009-2017 The Bitcoin Core developers\n\/\/ Copyright (c) 2019 The NAQD Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include <config\/bitcoin-config.h>\n#endif\n\n#include <base58.h>\n#include <clientversion.h>\n#include <coins.h>\n#include <consensus\/consensus.h>\n#include <core_io.h>\n#include <keystore.h>\n#include <policy\/policy.h>\n#include <policy\/rbf.h>\n#include <primitives\/transaction.h>\n#include <script\/script.h>\n#include <script\/sign.h>\n#include <univalue.h>\n#include <util.h>\n#include <utilmoneystr.h>\n#include <utilstrencodings.h>\n\n#include <memory>\n#include <stdio.h>\n\n#include <boost\/algorithm\/string.hpp>\n\nstatic bool fCreateBlank;\nstatic std::map<std::string,UniValue> registers;\nstatic const int CONTINUE_EXECUTION=-1;\n\n\/\/\n\/\/ This function returns either one of EXIT_ codes when it's expected to stop the process or\n\/\/ CONTINUE_EXECUTION when it's expected to continue further.\n\/\/\nstatic int AppInitRawTx(int argc, char* argv[])\n{\n    \/\/\n    \/\/ Parameters\n    \/\/\n    gArgs.ParseParameters(argc, argv);\n\n    \/\/ Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)\n    try {\n        SelectParams(ChainNameFromCommandLine());\n    } catch (const std::exception& e) {\n        fprintf(stderr, \"Error: %s\\n\", e.what());\n        return EXIT_FAILURE;\n    }\n\n    fCreateBlank = gArgs.GetBoolArg(\"-create\", false);\n\n    if (argc<2 || gArgs.IsArgSet(\"-?\") || gArgs.IsArgSet(\"-h\") || gArgs.IsArgSet(\"-help\"))\n    {\n        \/\/ First part of help message is specific to this utility\n        std::string strUsage = strprintf(_(\"%s naqd-tx utility version\"), _(PACKAGE_NAME)) + \" \" + FormatFullVersion() + \"\\n\\n\" +\n            _(\"Usage:\") + \"\\n\" +\n              \"  naqd-tx [options] <hex-tx> [commands]  \" + _(\"Update hex-encoded naqd transaction\") + \"\\n\" +\n              \"  naqd-tx [options] -create [commands]   \" + _(\"Create hex-encoded naqd transaction\") + \"\\n\" +\n              \"\\n\";\n\n        fprintf(stdout, \"%s\", strUsage.c_str());\n\n        strUsage = HelpMessageGroup(_(\"Options:\"));\n        strUsage += HelpMessageOpt(\"-?\", _(\"This help message\"));\n        strUsage += HelpMessageOpt(\"-create\", _(\"Create new, empty TX.\"));\n        strUsage += HelpMessageOpt(\"-json\", _(\"Select JSON output\"));\n        strUsage += HelpMessageOpt(\"-txid\", _(\"Output only the hex-encoded transaction id of the resultant transaction.\"));\n        AppendParamsHelpMessages(strUsage);\n\n        fprintf(stdout, \"%s\", strUsage.c_str());\n\n        strUsage = HelpMessageGroup(_(\"Commands:\"));\n        strUsage += HelpMessageOpt(\"delin=N\", _(\"Delete input N from TX\"));\n        strUsage += HelpMessageOpt(\"delout=N\", _(\"Delete output N from TX\"));\n        strUsage += HelpMessageOpt(\"in=TXID:VOUT(:SEQUENCE_NUMBER)\", _(\"Add input to TX\"));\n        strUsage += HelpMessageOpt(\"locktime=N\", _(\"Set TX lock time to N\"));\n        strUsage += HelpMessageOpt(\"nversion=N\", _(\"Set TX version to N\"));\n        strUsage += HelpMessageOpt(\"replaceable(=N)\", _(\"Set RBF opt-in sequence number for input N (if not provided, opt-in all available inputs)\"));\n        strUsage += HelpMessageOpt(\"outaddr=VALUE:ADDRESS\", _(\"Add address-based output to TX\"));\n        strUsage += HelpMessageOpt(\"outpubkey=VALUE:PUBKEY[:FLAGS]\", _(\"Add pay-to-pubkey output to TX\") + \". \" +\n            _(\"Optionally add the \\\"W\\\" flag to produce a pay-to-witness-pubkey-hash output\") + \". \" +\n            _(\"Optionally add the \\\"S\\\" flag to wrap the output in a pay-to-script-hash.\"));\n        strUsage += HelpMessageOpt(\"outdata=[VALUE:]DATA\", _(\"Add data-based output to TX\"));\n        strUsage += HelpMessageOpt(\"outscript=VALUE:SCRIPT[:FLAGS]\", _(\"Add raw script output to TX\") + \". \" +\n            _(\"Optionally add the \\\"W\\\" flag to produce a pay-to-witness-script-hash output\") + \". \" +\n            _(\"Optionally add the \\\"S\\\" flag to wrap the output in a pay-to-script-hash.\"));\n        strUsage += HelpMessageOpt(\"outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]\", _(\"Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS\") + \". \" +\n            _(\"Optionally add the \\\"W\\\" flag to produce a pay-to-witness-script-hash output\") + \". \" +\n            _(\"Optionally add the \\\"S\\\" flag to wrap the output in a pay-to-script-hash.\"));\n        strUsage += HelpMessageOpt(\"sign=SIGHASH-FLAGS\", _(\"Add zero or more signatures to transaction\") + \". \" +\n            _(\"This command requires JSON registers:\") +\n            _(\"prevtxs=JSON object\") + \", \" +\n            _(\"privatekeys=JSON object\") + \". \" +\n            _(\"See signrawtransaction docs for format of sighash flags, JSON objects.\"));\n        fprintf(stdout, \"%s\", strUsage.c_str());\n\n        strUsage = HelpMessageGroup(_(\"Register Commands:\"));\n        strUsage += HelpMessageOpt(\"load=NAME:FILENAME\", _(\"Load JSON file FILENAME into register NAME\"));\n        strUsage += HelpMessageOpt(\"set=NAME:JSON-STRING\", _(\"Set register NAME to given JSON-STRING\"));\n        fprintf(stdout, \"%s\", strUsage.c_str());\n\n        if (argc < 2) {\n            fprintf(stderr, \"Error: too few parameters\\n\");\n            return EXIT_FAILURE;\n        }\n        return EXIT_SUCCESS;\n    }\n    return CONTINUE_EXECUTION;\n}\n\nstatic void RegisterSetJson(const std::string& key, const std::string& rawJson)\n{\n    UniValue val;\n    if (!val.read(rawJson)) {\n        std::string strErr = \"Cannot parse JSON for key \" + key;\n        throw std::runtime_error(strErr);\n    }\n\n    registers[key] = val;\n}\n\nstatic void RegisterSet(const std::string& strInput)\n{\n    \/\/ separate NAME:VALUE in string\n    size_t pos = strInput.find(':');\n    if ((pos == std::string::npos) ||\n        (pos == 0) ||\n        (pos == (strInput.size() - 1)))\n        throw std::runtime_error(\"Register input requires NAME:VALUE\");\n\n    std::string key = strInput.substr(0, pos);\n    std::string valStr = strInput.substr(pos + 1, std::string::npos);\n\n    RegisterSetJson(key, valStr);\n}\n\nstatic void RegisterLoad(const std::string& strInput)\n{\n    \/\/ separate NAME:FILENAME in string\n    size_t pos = strInput.find(':');\n    if ((pos == std::string::npos) ||\n        (pos == 0) ||\n        (pos == (strInput.size() - 1)))\n        throw std::runtime_error(\"Register load requires NAME:FILENAME\");\n\n    std::string key = strInput.substr(0, pos);\n    std::string filename = strInput.substr(pos + 1, std::string::npos);\n\n    FILE *f = fopen(filename.c_str(), \"r\");\n    if (!f) {\n        std::string strErr = \"Cannot open file \" + filename;\n        throw std::runtime_error(strErr);\n    }\n\n    \/\/ load file chunks into one big buffer\n    std::string valStr;\n    while ((!feof(f)) && (!ferror(f))) {\n        char buf[4096];\n        int bread = fread(buf, 1, sizeof(buf), f);\n        if (bread <= 0)\n            break;\n\n        valStr.insert(valStr.size(), buf, bread);\n    }\n\n    int error = ferror(f);\n    fclose(f);\n\n    if (error) {\n        std::string strErr = \"Error reading file \" + filename;\n        throw std::runtime_error(strErr);\n    }\n\n    \/\/ evaluate as JSON buffer register\n    RegisterSetJson(key, valStr);\n}\n\nstatic CAmount ExtractAndValidateValue(const std::string& strValue)\n{\n    CAmount value;\n    if (!ParseMoney(strValue, value))\n        throw std::runtime_error(\"invalid TX output value\");\n    return value;\n}\n\nstatic void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)\n{\n    int64_t newVersion = atoi64(cmdVal);\n    if (newVersion < 1 || newVersion > CTransaction::MAX_STANDARD_VERSION)\n        throw std::runtime_error(\"Invalid TX version requested\");\n\n    tx.nVersion = (int) newVersion;\n}\n\nstatic void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)\n{\n    int64_t newLocktime = atoi64(cmdVal);\n    if (newLocktime < 0LL || newLocktime > 0xffffffffLL)\n        throw std::runtime_error(\"Invalid TX locktime requested\");\n\n    tx.nLockTime = (unsigned int) newLocktime;\n}\n\nstatic void MutateTxRBFOptIn(CMutableTransaction& tx, const std::string& strInIdx)\n{\n    \/\/ parse requested index\n    int inIdx = atoi(strInIdx);\n    if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {\n        throw std::runtime_error(\"Invalid TX input index '\" + strInIdx + \"'\");\n    }\n\n    \/\/ set the nSequence to MAX_INT - 2 (= RBF opt in flag)\n    int cnt = 0;\n    for (CTxIn& txin : tx.vin) {\n        if (strInIdx == \"\" || cnt == inIdx) {\n            if (txin.nSequence > MAX_BIP125_RBF_SEQUENCE) {\n                txin.nSequence = MAX_BIP125_RBF_SEQUENCE;\n            }\n        }\n        ++cnt;\n    }\n}\n\nstatic void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)\n{\n    std::vector<std::string> vStrInputParts;\n    boost::split(vStrInputParts, strInput, boost::is_any_of(\":\"));\n\n    \/\/ separate TXID:VOUT in string\n    if (vStrInputParts.size()<2)\n        throw std::runtime_error(\"TX input missing separator\");\n\n    \/\/ extract and validate TXID\n    std::string strTxid = vStrInputParts[0];\n    if ((strTxid.size() != 64) || !IsHex(strTxid))\n        throw std::runtime_error(\"invalid TX input txid\");\n    uint256 txid(uint256S(strTxid));\n\n    static const unsigned int minTxOutSz = 9;\n    static const unsigned int maxVout = MAX_BLOCK_WEIGHT \/ (WITNESS_SCALE_FACTOR * minTxOutSz);\n\n    \/\/ extract and validate vout\n    std::string strVout = vStrInputParts[1];\n    int vout = atoi(strVout);\n    if ((vout < 0) || (vout > (int)maxVout))\n        throw std::runtime_error(\"invalid TX input vout\");\n\n    \/\/ extract the optional sequence number\n    uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max();\n    if (vStrInputParts.size() > 2)\n        nSequenceIn = std::stoul(vStrInputParts[2]);\n\n    \/\/ append to transaction input list\n    CTxIn txin(txid, vout, CScript(), nSequenceIn);\n    tx.vin.push_back(txin);\n}\n\nstatic void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)\n{\n    \/\/ Separate into VALUE:ADDRESS\n    std::vector<std::string> vStrInputParts;\n    boost::split(vStrInputParts, strInput, boost::is_any_of(\":\"));\n\n    if (vStrInputParts.size() != 2)\n        throw std::runtime_error(\"TX output missing or too many separators\");\n\n    \/\/ Extract and validate VALUE\n    CAmount value = ExtractAndValidateValue(vStrInputParts[0]);\n\n    \/\/ extract and validate ADDRESS\n    std::string strAddr = vStrInputParts[1];\n    CTxDestination destination = DecodeDestination(strAddr);\n    if (!IsValidDestination(destination)) {\n        throw std::runtime_error(\"invalid TX output address\");\n    }\n    CScript scriptPubKey = GetScriptForDestination(destination);\n\n    \/\/ construct TxOut, append to transaction output list\n    CTxOut txout(value, scriptPubKey);\n    tx.vout.push_back(txout);\n}\n\nstatic void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& strInput)\n{\n    \/\/ Separate into VALUE:PUBKEY[:FLAGS]\n    std::vector<std::string> vStrInputParts;\n    boost::split(vStrInputParts, strInput, boost::is_any_of(\":\"));\n\n    if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3)\n        throw std::runtime_error(\"TX output missing or too many separators\");\n\n    \/\/ Extract and validate VALUE\n    CAmount value = ExtractAndValidateValue(vStrInputParts[0]);\n\n    \/\/ Extract and validate PUBKEY\n    CPubKey pubkey(ParseHex(vStrInputParts[1]));\n    if (!pubkey.IsFullyValid())\n        throw std::runtime_error(\"invalid TX output pubkey\");\n    CScript scriptPubKey = GetScriptForRawPubKey(pubkey);\n\n    \/\/ Extract and validate FLAGS\n    bool bSegWit = false;\n    bool bScriptHash = false;\n    if (vStrInputParts.size() == 3) {\n        std::string flags = vStrInputParts[2];\n        bSegWit = (flags.find('W') != std::string::npos);\n        bScriptHash = (flags.find('S') != std::string::npos);\n    }\n\n    if (bSegWit) {\n        if (!pubkey.IsCompressed()) {\n            throw std::runtime_error(\"Uncompressed pubkeys are not useable for SegWit outputs\");\n        }\n        \/\/ Call GetScriptForWitness() to build a P2WSH scriptPubKey\n        scriptPubKey = GetScriptForWitness(scriptPubKey);\n    }\n    if (bScriptHash) {\n        \/\/ Get the ID for the script, and then construct a P2SH destination for it.\n        scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));\n    }\n\n    \/\/ construct TxOut, append to transaction output list\n    CTxOut txout(value, scriptPubKey);\n    tx.vout.push_back(txout);\n}\n\nstatic void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput)\n{\n    \/\/ Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]\n    std::vector<std::string> vStrInputParts;\n    boost::split(vStrInputParts, strInput, boost::is_any_of(\":\"));\n\n    \/\/ Check that there are enough parameters\n    if (vStrInputParts.size()<3)\n        throw std::runtime_error(\"Not enough multisig parameters\");\n\n    \/\/ Extract and validate VALUE\n    CAmount value = ExtractAndValidateValue(vStrInputParts[0]);\n\n    \/\/ Extract REQUIRED\n    uint32_t required = stoul(vStrInputParts[1]);\n\n    \/\/ Extract NUMKEYS\n    uint32_t numkeys = stoul(vStrInputParts[2]);\n\n    \/\/ Validate there are the correct number of pubkeys\n    if (vStrInputParts.size() < numkeys + 3)\n        throw std::runtime_error(\"incorrect number of multisig pubkeys\");\n\n    if (required < 1 || required > 20 || numkeys < 1 || numkeys > 20 || numkeys < required)\n        throw std::runtime_error(\"multisig parameter mismatch. Required \" \\\n                            + std::to_string(required) + \" of \" + std::to_string(numkeys) + \"signatures.\");\n\n    \/\/ extract and validate PUBKEYs\n    std::vector<CPubKey> pubkeys;\n    for(int pos = 1; pos <= int(numkeys); pos++) {\n        CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));\n        if (!pubkey.IsFullyValid())\n            throw std::runtime_error(\"invalid TX output pubkey\");\n        pubkeys.push_back(pubkey);\n    }\n\n    \/\/ Extract FLAGS\n    bool bSegWit = false;\n    bool bScriptHash = false;\n    if (vStrInputParts.size() == numkeys + 4) {\n        std::string flags = vStrInputParts.back();\n        bSegWit = (flags.find('W') != std::string::npos);\n        bScriptHash = (flags.find('S') != std::string::npos);\n    }\n    else if (vStrInputParts.size() > numkeys + 4) {\n        \/\/ Validate that there were no more parameters passed\n        throw std::runtime_error(\"Too many parameters\");\n    }\n\n    CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);\n\n    if (bSegWit) {\n        for (CPubKey& pubkey : pubkeys) {\n            if (!pubkey.IsCompressed()) {\n                throw std::runtime_error(\"Uncompressed pubkeys are not useable for SegWit outputs\");\n            }\n        }\n        \/\/ Call GetScriptForWitness() to build a P2WSH scriptPubKey\n        scriptPubKey = GetScriptForWitness(scriptPubKey);\n    }\n    if (bScriptHash) {\n        if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {\n            throw std::runtime_error(strprintf(\n                        \"redeemScript exceeds size limit: %d > %d\", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));\n        }\n        \/\/ Get the ID for the script, and then construct a P2SH destination for it.\n        scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));\n    }\n\n    \/\/ construct TxOut, append to transaction output list\n    CTxOut txout(value, scriptPubKey);\n    tx.vout.push_back(txout);\n}\n\nstatic void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)\n{\n    CAmount value = 0;\n\n    \/\/ separate [VALUE:]DATA in string\n    size_t pos = strInput.find(':');\n\n    if (pos==0)\n        throw std::runtime_error(\"TX output value not specified\");\n\n    if (pos != std::string::npos) {\n        \/\/ Extract and validate VALUE\n        value = ExtractAndValidateValue(strInput.substr(0, pos));\n    }\n\n    \/\/ extract and validate DATA\n    std::string strData = strInput.substr(pos + 1, std::string::npos);\n\n    if (!IsHex(strData))\n        throw std::runtime_error(\"invalid TX output data\");\n\n    std::vector<unsigned char> data = ParseHex(strData);\n\n    CTxOut txout(value, CScript() << OP_RETURN << data);\n    tx.vout.push_back(txout);\n}\n\nstatic void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)\n{\n    \/\/ separate VALUE:SCRIPT[:FLAGS]\n    std::vector<std::string> vStrInputParts;\n    boost::split(vStrInputParts, strInput, boost::is_any_of(\":\"));\n    if (vStrInputParts.size() < 2)\n        throw std::runtime_error(\"TX output missing separator\");\n\n    \/\/ Extract and validate VALUE\n    CAmount value = ExtractAndValidateValue(vStrInputParts[0]);\n\n    \/\/ extract and validate script\n    std::string strScript = vStrInputParts[1];\n    CScript scriptPubKey = ParseScript(strScript);\n\n    \/\/ Extract FLAGS\n    bool bSegWit = false;\n    bool bScriptHash = false;\n    if (vStrInputParts.size() == 3) {\n        std::string flags = vStrInputParts.back();\n        bSegWit = (flags.find('W') != std::string::npos);\n        bScriptHash = (flags.find('S') != std::string::npos);\n    }\n\n    if (scriptPubKey.size() > MAX_SCRIPT_SIZE) {\n        throw std::runtime_error(strprintf(\n                    \"script exceeds size limit: %d > %d\", scriptPubKey.size(), MAX_SCRIPT_SIZE));\n    }\n\n    if (bSegWit) {\n        scriptPubKey = GetScriptForWitness(scriptPubKey);\n    }\n    if (bScriptHash) {\n        if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {\n            throw std::runtime_error(strprintf(\n                        \"redeemScript exceeds size limit: %d > %d\", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));\n        }\n        scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));\n    }\n\n    \/\/ construct TxOut, append to transaction output list\n    CTxOut txout(value, scriptPubKey);\n    tx.vout.push_back(txout);\n}\n\nstatic void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)\n{\n    \/\/ parse requested deletion index\n    int inIdx = atoi(strInIdx);\n    if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {\n        std::string strErr = \"Invalid TX input index '\" + strInIdx + \"'\";\n        throw std::runtime_error(strErr.c_str());\n    }\n\n    \/\/ delete input from transaction\n    tx.vin.erase(tx.vin.begin() + inIdx);\n}\n\nstatic void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)\n{\n    \/\/ parse requested deletion index\n    int outIdx = atoi(strOutIdx);\n    if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {\n        std::string strErr = \"Invalid TX output index '\" + strOutIdx + \"'\";\n        throw std::runtime_error(strErr.c_str());\n    }\n\n    \/\/ delete output from transaction\n    tx.vout.erase(tx.vout.begin() + outIdx);\n}\n\nstatic const unsigned int N_SIGHASH_OPTS = 6;\nstatic const struct {\n    const char *flagStr;\n    int flags;\n} sighashOptions[N_SIGHASH_OPTS] = {\n    {\"ALL\", SIGHASH_ALL},\n    {\"NONE\", SIGHASH_NONE},\n    {\"SINGLE\", SIGHASH_SINGLE},\n    {\"ALL|ANYONECANPAY\", SIGHASH_ALL|SIGHASH_ANYONECANPAY},\n    {\"NONE|ANYONECANPAY\", SIGHASH_NONE|SIGHASH_ANYONECANPAY},\n    {\"SINGLE|ANYONECANPAY\", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},\n};\n\nstatic bool findSighashFlags(int& flags, const std::string& flagStr)\n{\n    flags = 0;\n\n    for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {\n        if (flagStr == sighashOptions[i].flagStr) {\n            flags = sighashOptions[i].flags;\n            return true;\n        }\n    }\n\n    return false;\n}\n\nstatic CAmount AmountFromValue(const UniValue& value)\n{\n    if (!value.isNum() && !value.isStr())\n        throw std::runtime_error(\"Amount is not a number or string\");\n    CAmount amount;\n    if (!ParseFixedPoint(value.getValStr(), 8, &amount))\n        throw std::runtime_error(\"Invalid amount\");\n    if (!MoneyRange(amount))\n        throw std::runtime_error(\"Amount out of range\");\n    return amount;\n}\n\nstatic void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)\n{\n    int nHashType = SIGHASH_ALL;\n\n    if (flagStr.size() > 0)\n        if (!findSighashFlags(nHashType, flagStr))\n            throw std::runtime_error(\"unknown sighash flag\/sign option\");\n\n    std::vector<CTransaction> txVariants;\n    txVariants.push_back(tx);\n\n    \/\/ mergedTx will end up with all the signatures; it\n    \/\/ starts as a clone of the raw tx:\n    CMutableTransaction mergedTx(txVariants[0]);\n    bool fComplete = true;\n    CCoinsView viewDummy;\n    CCoinsViewCache view(&viewDummy);\n\n    if (!registers.count(\"privatekeys\"))\n        throw std::runtime_error(\"privatekeys register variable must be set.\");\n    CBasicKeyStore tempKeystore;\n    UniValue keysObj = registers[\"privatekeys\"];\n\n    for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {\n        if (!keysObj[kidx].isStr())\n            throw std::runtime_error(\"privatekey not a std::string\");\n        CBitcoinSecret vchSecret;\n        bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());\n        if (!fGood)\n            throw std::runtime_error(\"privatekey not valid\");\n\n        CKey key = vchSecret.GetKey();\n        tempKeystore.AddKey(key);\n    }\n\n    \/\/ Add previous txouts given in the RPC call:\n    if (!registers.count(\"prevtxs\"))\n        throw std::runtime_error(\"prevtxs register variable must be set.\");\n    UniValue prevtxsObj = registers[\"prevtxs\"];\n    {\n        for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {\n            UniValue prevOut = prevtxsObj[previdx];\n            if (!prevOut.isObject())\n                throw std::runtime_error(\"expected prevtxs internal object\");\n\n            std::map<std::string, UniValue::VType> types = {\n                {\"txid\", UniValue::VSTR},\n                {\"vout\", UniValue::VNUM},\n                {\"scriptPubKey\", UniValue::VSTR},\n            };\n            if (!prevOut.checkObject(types))\n                throw std::runtime_error(\"prevtxs internal object typecheck fail\");\n\n            uint256 txid = ParseHashUV(prevOut[\"txid\"], \"txid\");\n\n            int nOut = atoi(prevOut[\"vout\"].getValStr());\n            if (nOut < 0)\n                throw std::runtime_error(\"vout must be positive\");\n\n            COutPoint out(txid, nOut);\n            std::vector<unsigned char> pkData(ParseHexUV(prevOut[\"scriptPubKey\"], \"scriptPubKey\"));\n            CScript scriptPubKey(pkData.begin(), pkData.end());\n\n            {\n                const Coin& coin = view.AccessCoin(out);\n                if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {\n                    std::string err(\"Previous output scriptPubKey mismatch:\\n\");\n                    err = err + ScriptToAsmStr(coin.out.scriptPubKey) + \"\\nvs:\\n\"+\n                        ScriptToAsmStr(scriptPubKey);\n                    throw std::runtime_error(err);\n                }\n                Coin newcoin;\n                newcoin.out.scriptPubKey = scriptPubKey;\n                newcoin.out.nValue = 0;\n                if (prevOut.exists(\"amount\")) {\n                    newcoin.out.nValue = AmountFromValue(prevOut[\"amount\"]);\n                }\n                newcoin.nHeight = 1;\n                view.AddCoin(out, std::move(newcoin), true);\n            }\n\n            \/\/ if redeemScript given and private keys given,\n            \/\/ add redeemScript to the tempKeystore so it can be signed:\n            if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&\n                prevOut.exists(\"redeemScript\")) {\n                UniValue v = prevOut[\"redeemScript\"];\n                std::vector<unsigned char> rsData(ParseHexUV(v, \"redeemScript\"));\n                CScript redeemScript(rsData.begin(), rsData.end());\n                tempKeystore.AddCScript(redeemScript);\n            }\n        }\n    }\n\n    const CKeyStore& keystore = tempKeystore;\n\n    bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);\n\n    \/\/ Sign what we can:\n    for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {\n        CTxIn& txin = mergedTx.vin[i];\n        const Coin& coin = view.AccessCoin(txin.prevout);\n        if (coin.IsSpent()) {\n            fComplete = false;\n            continue;\n        }\n        const CScript& prevPubKey = coin.out.scriptPubKey;\n        const CAmount& amount = coin.out.nValue;\n\n        SignatureData sigdata;\n        \/\/ Only sign SIGHASH_SINGLE if there's a corresponding output:\n        if (!fHashSingle || (i < mergedTx.vout.size()))\n            ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);\n\n        \/\/ ... and merge in other signatures:\n        for (const CTransaction& txv : txVariants)\n            sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));\n        UpdateTransaction(mergedTx, i, sigdata);\n\n        if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))\n            fComplete = false;\n    }\n\n    if (fComplete) {\n        \/\/ do nothing... for now\n        \/\/ perhaps store this for later optional JSON output\n    }\n\n    tx = mergedTx;\n}\n\nclass Secp256k1Init\n{\n    ECCVerifyHandle globalVerifyHandle;\n\npublic:\n    Secp256k1Init() {\n        ECC_Start();\n    }\n    ~Secp256k1Init() {\n        ECC_Stop();\n    }\n};\n\nstatic void MutateTx(CMutableTransaction& tx, const std::string& command,\n                     const std::string& commandVal)\n{\n    std::unique_ptr<Secp256k1Init> ecc;\n\n    if (command == \"nversion\")\n        MutateTxVersion(tx, commandVal);\n    else if (command == \"locktime\")\n        MutateTxLocktime(tx, commandVal);\n    else if (command == \"replaceable\") {\n        MutateTxRBFOptIn(tx, commandVal);\n    }\n\n    else if (command == \"delin\")\n        MutateTxDelInput(tx, commandVal);\n    else if (command == \"in\")\n        MutateTxAddInput(tx, commandVal);\n\n    else if (command == \"delout\")\n        MutateTxDelOutput(tx, commandVal);\n    else if (command == \"outaddr\")\n        MutateTxAddOutAddr(tx, commandVal);\n    else if (command == \"outpubkey\") {\n        ecc.reset(new Secp256k1Init());\n        MutateTxAddOutPubKey(tx, commandVal);\n    } else if (command == \"outmultisig\") {\n        ecc.reset(new Secp256k1Init());\n        MutateTxAddOutMultiSig(tx, commandVal);\n    } else if (command == \"outscript\")\n        MutateTxAddOutScript(tx, commandVal);\n    else if (command == \"outdata\")\n        MutateTxAddOutData(tx, commandVal);\n\n    else if (command == \"sign\") {\n        ecc.reset(new Secp256k1Init());\n        MutateTxSign(tx, commandVal);\n    }\n\n    else if (command == \"load\")\n        RegisterLoad(commandVal);\n\n    else if (command == \"set\")\n        RegisterSet(commandVal);\n\n    else\n        throw std::runtime_error(\"unknown command\");\n}\n\nstatic void OutputTxJSON(const CTransaction& tx)\n{\n    UniValue entry(UniValue::VOBJ);\n    TxToUniv(tx, uint256(), entry);\n\n    std::string jsonOutput = entry.write(4);\n    fprintf(stdout, \"%s\\n\", jsonOutput.c_str());\n}\n\nstatic void OutputTxHash(const CTransaction& tx)\n{\n    std::string strHexHash = tx.GetHash().GetHex(); \/\/ the hex-encoded transaction hash (aka the transaction id)\n\n    fprintf(stdout, \"%s\\n\", strHexHash.c_str());\n}\n\nstatic void OutputTxHex(const CTransaction& tx)\n{\n    std::string strHex = EncodeHexTx(tx);\n\n    fprintf(stdout, \"%s\\n\", strHex.c_str());\n}\n\nstatic void OutputTx(const CTransaction& tx)\n{\n    if (gArgs.GetBoolArg(\"-json\", false))\n        OutputTxJSON(tx);\n    else if (gArgs.GetBoolArg(\"-txid\", false))\n        OutputTxHash(tx);\n    else\n        OutputTxHex(tx);\n}\n\nstatic std::string readStdin()\n{\n    char buf[4096];\n    std::string ret;\n\n    while (!feof(stdin)) {\n        size_t bread = fread(buf, 1, sizeof(buf), stdin);\n        ret.append(buf, bread);\n        if (bread < sizeof(buf))\n            break;\n    }\n\n    if (ferror(stdin))\n        throw std::runtime_error(\"error reading stdin\");\n\n    boost::algorithm::trim_right(ret);\n\n    return ret;\n}\n\nstatic int CommandLineRawTx(int argc, char* argv[])\n{\n    std::string strPrint;\n    int nRet = 0;\n    try {\n        \/\/ Skip switches; Permit common stdin convention \"-\"\n        while (argc > 1 && IsSwitchChar(argv[1][0]) &&\n               (argv[1][1] != 0)) {\n            argc--;\n            argv++;\n        }\n\n        CMutableTransaction tx;\n        int startArg;\n\n        if (!fCreateBlank) {\n            \/\/ require at least one param\n            if (argc < 2)\n                throw std::runtime_error(\"too few parameters\");\n\n            \/\/ param: hex-encoded bitcoin transaction\n            std::string strHexTx(argv[1]);\n            if (strHexTx == \"-\")                 \/\/ \"-\" implies standard input\n                strHexTx = readStdin();\n\n            if (!DecodeHexTx(tx, strHexTx, true))\n                throw std::runtime_error(\"invalid transaction encoding\");\n\n            startArg = 2;\n        } else\n            startArg = 1;\n\n        for (int i = startArg; i < argc; i++) {\n            std::string arg = argv[i];\n            std::string key, value;\n            size_t eqpos = arg.find('=');\n            if (eqpos == std::string::npos)\n                key = arg;\n            else {\n                key = arg.substr(0, eqpos);\n                value = arg.substr(eqpos + 1);\n            }\n\n            MutateTx(tx, key, value);\n        }\n\n        OutputTx(tx);\n    }\n\n    catch (const boost::thread_interrupted&) {\n        throw;\n    }\n    catch (const std::exception& e) {\n        strPrint = std::string(\"error: \") + e.what();\n        nRet = EXIT_FAILURE;\n    }\n    catch (...) {\n        PrintExceptionContinue(nullptr, \"CommandLineRawTx()\");\n        throw;\n    }\n\n    if (strPrint != \"\") {\n        fprintf((nRet == 0 ? stdout : stderr), \"%s\\n\", strPrint.c_str());\n    }\n    return nRet;\n}\n\nint main(int argc, char* argv[])\n{\n    SetupEnvironment();\n\n    try {\n        int ret = AppInitRawTx(argc, argv);\n        if (ret != CONTINUE_EXECUTION)\n            return ret;\n    }\n    catch (const std::exception& e) {\n        PrintExceptionContinue(&e, \"AppInitRawTx()\");\n        return EXIT_FAILURE;\n    } catch (...) {\n        PrintExceptionContinue(nullptr, \"AppInitRawTx()\");\n        return EXIT_FAILURE;\n    }\n\n    int ret = EXIT_FAILURE;\n    try {\n        ret = CommandLineRawTx(argc, argv);\n    }\n    catch (const std::exception& e) {\n        PrintExceptionContinue(&e, \"CommandLineRawTx()\");\n    } catch (...) {\n        PrintExceptionContinue(nullptr, \"CommandLineRawTx()\");\n    }\n    return ret;\n}\n","avg_line_length":34.3450624291,"max_line_length":183,"alphanum_fraction":0.6216868266,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1760,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":256.0,"content":"#include <iostream>\n#include <vector>\n#include <queue>\nusing namespace std;\n\n\/\/ Data Structure to store a linked list node\nstruct Node\n{\n\tint data;\n\tNode *next, *child;\n};\n\n\/\/ Helper function to create a new node with the given data and\n\/\/ pushes it onto the front of the list\nvoid push(Node* &headRef, int data)\n{\n\tNode* newNode = new Node;\n\n\tnewNode->data = data;\n\tnewNode->next = headRef;\n\tnewNode->child = nullptr;\n\theadRef = newNode;\n}\n\n\/\/ Helper function to create a linked list with elements of given vector\nNode* createHorizontalList(vector<int> const &input)\n{\n\tNode* head = nullptr;\n\tfor (int i = input.size() - 1; i >= 0; i--)\n\t\tpush(head, input[i]);\n\n\treturn head;\n}\n\n\/\/ Function to convert a multilevel linked list to a singly linked list\nvoid convertList(Node* const head)\n{\n\tNode* curr = head;\n\tqueue<Node*> q;\n\n\t\/\/ process all nodes\n\twhile (curr)\n\t{\n\t\t\/\/ last node is reached\n\t\tif (curr->next == nullptr)\n\t\t{\n\t\t\t\/\/ pop a node from queue and set it as next node of current node\n\t\t\tcurr->next = q.front();\n\t\t\tq.pop();\n\t\t}\n\n\t\t\/\/ if current node has a child\n\t\tif (curr->child)\n\t\t{\n\t\t\tq.push(curr->child);\n\t\t}\n\n\t\t\/\/ advance the current node\n\t\tcurr = curr->next;\n\t}\n}\n\n\/\/ Helper function to print given linked list\nvoid printList(Node* const head)\n{\n\tNode* ptr = head;\n\twhile (ptr)\n\t{\n\t\tcout << ptr->data << \" -> \";\n\t\tptr = ptr->next;\n\t}\n\n\tcout << \"nullptr\" << endl;\n}\n\nint main()\n{\n\t\/\/ create a multilevel linked list\n\tNode* head = createHorizontalList({1, 2, 3, 4, 5});\n\thead->child = createHorizontalList({6, 7});\n\thead->next->next->child = createHorizontalList({8, 9});\n\thead->child->next->child = createHorizontalList({10, 11});\n\thead->child->next->child->child = createHorizontalList({12});\n\n\tconvertList(head);\n\tprintList(head);\n\n\treturn 0;\n}\n","avg_line_length":19.5555555556,"max_line_length":72,"alphanum_fraction":0.6573863636,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1172,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":12278.0,"content":"\n\/\/  (C) Copyright John Maddock 2000. \n\/\/  Use, modification and distribution are subject to the \n\/\/  Boost Software License, Version 1.0. (See accompanying file \n\/\/  LICENSE_1_0.txt or copy at http:\/\/www.tt.org\/LICENSE_1_0.txt)\n\n#ifdef TEST_STD\n#  include <type_traits>\n#else\n#  include <boost\/type_traits\/add_pointer.hpp>\n#endif\n#include \"test.hpp\"\n#include \"check_type.hpp\"\n\nBOOST_DECL_TRANSFORM_TEST(add_pointer_test_1, ::tt::add_pointer, const, const*)\nBOOST_DECL_TRANSFORM_TEST(add_pointer_test_2, ::tt::add_pointer, volatile, volatile*)\nBOOST_DECL_TRANSFORM_TEST(add_pointer_test_3, ::tt::add_pointer, *, **)\nBOOST_DECL_TRANSFORM_TEST2(add_pointer_test_4, ::tt::add_pointer, *)\nBOOST_DECL_TRANSFORM_TEST(add_pointer_test_7, ::tt::add_pointer, *volatile, *volatile*)\nBOOST_DECL_TRANSFORM_TEST(add_pointer_test_10, ::tt::add_pointer, const*, const**)\nBOOST_DECL_TRANSFORM_TEST(add_pointer_test_11, ::tt::add_pointer, volatile*, volatile**)\n\nTT_TEST_BEGIN(add_pointer)\n\n   add_pointer_test_1();\n   add_pointer_test_2();\n   add_pointer_test_3();\n   add_pointer_test_4();\n   add_pointer_test_7();\n   add_pointer_test_10();\n   add_pointer_test_11();\n\nTT_TEST_END\n\n\n\n\n\n\n\n\n","avg_line_length":27.9047619048,"max_line_length":88,"alphanum_fraction":0.7704778157,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2865,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Zlib"],"max_stars_count":1.0,"content":"#include <SFGUI\/Engines\/BREW.hpp>\n#include <SFGUI\/Context.hpp>\n#include <SFGUI\/Renderer.hpp>\n#include <SFGUI\/Frame.hpp>\n\n#include <SFML\/Graphics\/Text.hpp>\n#include <cmath>\n\nnamespace sfg {\nnamespace eng {\n\nRenderQueue* BREW::CreateFrameDrawable( SharedPtr<const Frame> frame ) const {\n\tsf::Color border_color( GetProperty<sf::Color>( \"BorderColor\", frame ) );\n\tsf::Color color( GetProperty<sf::Color>( \"Color\", frame ) );\n\tsf::Color background_color( GetProperty<sf::Color>( \"BackgroundColor\", frame ) );\n\tfloat border_width( GetProperty<float>( \"BorderWidth\", frame ) );\n\tconst std::string& font_name( GetProperty<std::string>( \"FontName\", frame ) );\n\tunsigned int font_size( GetProperty<unsigned int>( \"FontSize\", frame ) );\n\tconst sf::Font& font( *GetResourceManager().GetFont( font_name ) );\n\tfloat label_padding( GetProperty<float>( \"LabelPadding\", frame ) );\n\n\tfloat line_height = GetLineHeight( font, font_size );\n\n\tRenderQueue* queue( new RenderQueue );\n\n\t\/\/ Right\n\tqueue->Add(\n\t\tRenderer::Get().CreateLine(\n\t\t\tsf::Vector2f( frame->GetAllocation().width - border_width, line_height \/ 2.f ),\n\t\t\tsf::Vector2f( frame->GetAllocation().width - border_width, frame->GetAllocation().height - border_width ),\n\t\t\tborder_color,\n\t\t\tborder_width\n\t\t)\n\t);\n\n\t\/\/ Bottom\n\tqueue->Add(\n\t\tRenderer::Get().CreateLine(\n\t\t\tsf::Vector2f( frame->GetAllocation().width, frame->GetAllocation().height - border_width ),\n\t\t\tsf::Vector2f( 0.f, frame->GetAllocation().height - border_width ),\n\t\t\tborder_color,\n\t\t\tborder_width\n\t\t)\n\t);\n\n\t\/\/ Left\n\tqueue->Add(\n\t\tRenderer::Get().CreateLine(\n\t\t\tsf::Vector2f( 0.f, frame->GetAllocation().height - border_width ),\n\t\t\tsf::Vector2f( 0.f, line_height \/ 2.f ),\n\t\t\tborder_color,\n\t\t\tborder_width\n\t\t)\n\t);\n\n\tfloat label_start_x = line_height;\n\tfloat label_end_x = line_height;\n\n\tfloat alignment = frame->GetAlignment().x;\n\n\tif( frame->GetLabel().getSize() > 0 ) {\n\t\tsf::Vector2f metrics = GetTextMetrics( frame->GetLabel(), font, font_size );\n\t\tmetrics.x += ( 2 * label_padding );\n\n\t\tlabel_start_x += ( alignment * ( frame->GetAllocation().width - 2 * line_height - metrics.x ) );\n\t\tlabel_end_x += ( metrics.x + alignment * ( frame->GetAllocation().width - 2 * line_height - metrics.x ) );\n\n\t\tsf::Text text( frame->GetLabel(), font, font_size );\n\t\ttext.setPosition( label_start_x + label_padding, .0f );\n\t\ttext.setColor( color );\n\t\tqueue->Add( Renderer::Get().CreateText( text, background_color ) );\n\t}\n\n\t\/\/ Top Left\n\tqueue->Add(\n\t\tRenderer::Get().CreateLine(\n\t\t\tsf::Vector2f( 0.f, line_height \/ 2.f ),\n\t\t\tsf::Vector2f( label_start_x, line_height \/ 2.f ),\n\t\t\tborder_color,\n\t\t\tborder_width\n\t\t)\n\t);\n\n\t\/\/ Top Right\n\tqueue->Add(\n\t\tRenderer::Get().CreateLine(\n\t\t\tsf::Vector2f( label_end_x, line_height \/ 2.f ),\n\t\t\tsf::Vector2f( frame->GetAllocation().width - border_width, line_height \/ 2.f ),\n\t\t\tborder_color,\n\t\t\tborder_width\n\t\t)\n\t);\n\n\treturn queue;\n}\n\n}\n}\n","avg_line_length":28.9393939394,"max_line_length":109,"alphanum_fraction":0.6844677138,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":684,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":3.0,"content":"\/\/\n\/\/ Copyright (c) 2018 The nanoFramework project contributors\n\/\/ See LICENSE file in the project root for full license information.\n\/\/\n\n#include \"win_dev_adc_native_target.h\"\n\nconst NF_PAL_ADC_PORT_PIN_CHANNEL AdcPortPinConfig[] = {\n    \n    \/\/ ADC1\n    {1, GPIOA, 6, ADC_CHANNEL_IN6},\n    {1, GPIOA, 4, ADC_CHANNEL_IN4},\n    {1, GPIOC, 2, ADC_CHANNEL_IN12},\n    {1, GPIOF, 10, ADC_CHANNEL_IN8},\n\n    \/\/ ADC3\n    {3, GPIOF, 8, ADC_CHANNEL_IN6},\n\n    \/\/ these are the internal sources, available only at ADC1\n    {1, NULL, 0, ADC_CHANNEL_SENSOR},\n    {1, NULL, 0, ADC_CHANNEL_VREFINT},\n    {1, NULL, 0, ADC_CHANNEL_VBAT},\n};\n\nconst int AdcChannelCount = ARRAYSIZE(AdcPortPinConfig);\n","avg_line_length":26.3076923077,"max_line_length":69,"alphanum_fraction":0.6856725146,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1956,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"#include <stdlib.h>\n#include <stdio.h>\n#include <assert.h>\n#include <emscripten.h>\n\ndouble prevTime = -1.0;\nint frame = 0;\n\nvoid final(void*) {\n  assert(frame == 100);\n  int result = 0;\n#ifdef REPORT_RESULT\n  REPORT_RESULT();\n#endif\n}\n\nvoid looper() {\n  frame++;\n  double curTime = emscripten_get_now();\n  double timeSincePrevious = (prevTime >= 0) ? (curTime - prevTime) : (1000.0\/60.0);\n  printf(\"frame: %d. dt: %g\\n\", frame, timeSincePrevious);\n  if (timeSincePrevious <= 1.0)\n  {\n    printf(\"Abort: main loop tick was called too quickly after the previous frame!\\n\");\n    int result = 1;\n#ifdef REPORT_RESULT\n    REPORT_RESULT();\n#endif\n    emscripten_cancel_main_loop();\n    exit(0);\n  }\n  prevTime = curTime;\n  if ((frame == 25 || frame == 45 || frame == 65) && timeSincePrevious < 30) {\n    printf(\"Abort: With swap interval of 4, we should be running at most 15fps! (or 30fps on 120Hz displays) but seems like swap control is not working and we are running at 60fps!\\n\");\n    int result = 1;\n#ifdef REPORT_RESULT\n    REPORT_RESULT();\n#endif\n    emscripten_cancel_main_loop();\n    exit(0);\n  }\n  if (frame > 0 && frame < 90 && frame % 10 == 0) {\n    emscripten_cancel_main_loop();\n    emscripten_set_main_loop(looper, 0, 0);\n    int ret;\n    int mode,value;\n    if (frame % 20 == 0) {\n      ret = emscripten_set_main_loop_timing(EM_TIMING_RAF, 4);\n      emscripten_get_main_loop_timing(&mode, &value);\n      assert(mode == EM_TIMING_RAF && value == 4);\n    } else {\n      ret = emscripten_set_main_loop_timing(EM_TIMING_RAF, 0);\n      emscripten_get_main_loop_timing(&mode, &value);\n      assert(mode == EM_TIMING_RAF && value == 0);\n    }\n    assert(ret == 0);\n  } else if (frame == 90) {\n    emscripten_cancel_main_loop();\n    emscripten_set_main_loop(looper, 100, 1);\n  } else if (frame == 100) {\n    emscripten_cancel_main_loop();\n    emscripten_async_call(final, (void*)0, 1000);\n  }\n}\n\nint main() {\n  emscripten_set_main_loop(looper, 5, 1);\n}\n","avg_line_length":28.347826087,"max_line_length":185,"alphanum_fraction":0.6538854806,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1888,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Spencer-94"],"max_stars_count":null,"content":"#include \"genarchive.h\"\n#include \"log_core.h\"\n\n#include <fstream>\n\nvoid GenArchive::setupOptions()\n{\n    options.add_options()\n        (\"logdir,l\", po::value<string>(&logdir)->required(),\n            \"Directory containing the log to be archived\")\n        (\"archdir,a\", po::value<string>(&archdir)->required(),\n            \"Directory where the archive runs will be stored (must exist)\")\n        \/\/ (\"maxLogSize,m\", po::value<long>(&maxLogSize)->default_value(m),\n        \/\/     \"max_logsize parameter of Shore-MT (default should be fine)\")\n    ;\n}\n\nvoid GenArchive::run()\n{\n    \/\/ check if directory exists\n    ifstream f(archdir);\n    bool exists = f.good();\n    f.close();\n\n    if (!exists) {\n        \/\/ TODO make command and handler exceptions\n        throw runtime_error(\"Directory does not exist: \" + archdir);\n    }\n\n    \/*\n     * TODO if we add boost filesystem, we can create the directory\n     * and if it already exists, check if there are any files in it\n     *\/\n\n    const size_t blockSize = 1048576;\n    const size_t workspaceSize = 300 * blockSize;\n\n    start_base();\n    start_log(logdir);\n    start_archiver(archdir, workspaceSize, blockSize);\n\n    lsn_t durableLSN = smlevel_0::log->durable_lsn();\n    cerr << \"Activating log archiver until LSN \" << durableLSN << endl;\n\n    LogArchiver* la = smlevel_0::logArchiver;\n    la->fork();\n\n    \/\/ wait for log record to be consumed\n    while (la->getNextConsumedLSN() < durableLSN) {\n        la->activate(durableLSN, true);\n        ::usleep(10000); \/\/ 10ms\n    }\n\n    \/\/ Time to wait until requesting a log archive flush (msec). If we're\n    \/\/ lucky, log is archiving very fast and a flush request is not needed.\n    int waitBeforeFlush = 100;\n    ::usleep(waitBeforeFlush * 1000);\n\n    if (la->getDirectory()->getLastLSN() < durableLSN) {\n        la->requestFlushSync(durableLSN);\n    }\n\n    la->shutdown();\n    la->join();\n}\n","avg_line_length":28.6060606061,"max_line_length":76,"alphanum_fraction":0.6308262712,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":62501,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["PHP-3.01","Zend-2.0"],"max_stars_count":1.0,"content":"\/*\n   +----------------------------------------------------------------------+\n   | HipHop for PHP                                                       |\n   +----------------------------------------------------------------------+\n   | Copyright (c) 2010-2015 Facebook, Inc. (http:\/\/www.facebook.com)     |\n   | Copyright (c) 1997-2010 The PHP Group                                |\n   +----------------------------------------------------------------------+\n   | This source file is subject to version 3.01 of the PHP license,      |\n   | that is bundled with this package in the file LICENSE, and is        |\n   | available through the world-wide-web at the following url:           |\n   | http:\/\/www.php.net\/license\/3_01.txt                                  |\n   | If you did not receive a copy of the PHP license and are unable to   |\n   | obtain it through the world-wide-web, please send a note to          |\n   | license@php.net so we can mail you a copy immediately.               |\n   +----------------------------------------------------------------------+\n*\/\n\n#include \"hphp\/runtime\/ext\/string\/ext_string.h\"\n#include \"hphp\/util\/bstring.h\"\n#include \"hphp\/runtime\/base\/comparisons.h\"\n#include \"hphp\/runtime\/base\/container-functions.h\"\n#include \"hphp\/runtime\/base\/actrec-args.h\"\n#include \"hphp\/runtime\/base\/plain-file.h\"\n#include \"hphp\/runtime\/base\/request-event-handler.h\"\n#include \"hphp\/runtime\/base\/request-local.h\"\n#include \"hphp\/runtime\/base\/string-buffer.h\"\n#include \"hphp\/runtime\/base\/string-util.h\"\n#include \"hphp\/runtime\/base\/zend-scanf.h\"\n#include \"hphp\/runtime\/base\/zend-string.h\"\n#include \"hphp\/runtime\/base\/zend-url.h\"\n#include \"hphp\/runtime\/ext\/std\/ext_std_classobj.h\"\n#include \"hphp\/runtime\/ext\/std\/ext_std_math.h\"\n#include \"hphp\/runtime\/ext\/std\/ext_std_variable.h\"\n#include \"hphp\/runtime\/server\/http-protocol.h\"\n#include \"hphp\/runtime\/server\/http-request-handler.h\"\n#include \"hphp\/util\/lock.h\"\n#include \"hphp\/zend\/html-table.h\"\n\n#include <folly\/Unicode.h>\n#include <locale.h>\n\nnamespace HPHP {\n\nstatic Mutex s_mutex;\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate <class Op> ALWAYS_INLINE\nString stringForEachBuffered(uint32_t bufLen, const String& str, Op action) {\n  StringBuffer sb(bufLen);\n  StringSlice sl  = str.slice();\n  const char* src = sl.begin();\n  const char* end = sl.end();\n\n  for (; src < end; ++src) {\n    action(sb, src, end);\n  }\n\n  return sb.detach();\n}\n\ntemplate <bool mutate, class Op> ALWAYS_INLINE\nString stringForEach(uint32_t len, const String& str, Op action) {\n  String ret = mutate ? str : String(len, ReserveString);\n\n  StringSlice srcSlice = str.slice();\n\n  const char* src = srcSlice.begin();\n  const char* end = srcSlice.end();\n\n  char* dst = ret.mutableData();\n\n  for (; src != end; ++src, ++dst) {\n    *dst = action(*src);\n  }\n\n  if (!mutate) ret.setSize(len);\n  return ret;\n}\n\ntemplate <class Op> ALWAYS_INLINE\nString stringForEachFast(const String& str, Op action) {\n  if (str.empty()) {\n    return str;\n  }\n\n  return stringForEach<false>(str.size(), str, action);\n}\n\nString HHVM_FUNCTION(addcslashes,\n                     const String& str,\n                     const String& charlist) {\n  if (str.empty() || (!charlist.isNull() && charlist.empty())) {\n    return str;\n  }\n\n  int masklen = charlist.isNull() ? 10 : charlist.size();\n  const char* list = charlist.isNull() ? \"\\\\\\x00\\x01..\\x1f\\x7f..\\xff\"\n                                       : charlist.c_str();\n\n  char flags[256];\n  string_charmask(list, masklen, flags);\n\n  return stringForEachBuffered(str.size(), str,\n    [&] (StringBuffer& ret, const char* src, const char* end) {\n      int c = (unsigned char)*src;\n\n      if (flags[c]) {\n        ret.append('\\\\');\n        if ((c < 32) || (c > 126)) {\n          switch (c) {\n            case '\\n': ret.append('n'); break;\n            case '\\t': ret.append('t'); break;\n            case '\\r': ret.append('r'); break;\n            case '\\a': ret.append('a'); break;\n            case '\\v': ret.append('v'); break;\n            case '\\b': ret.append('b'); break;\n            case '\\f': ret.append('f'); break;\n            default: ret.append((char)('0' + (c \/ 64))); c %= 64;\n                     ret.append((char)('0' + (c \/  8))); c %=  8;\n                     ret.append((char)('0' + c));\n          }\n          return;\n        }\n      }\n      ret.append((char)c);\n    });\n}\n\nString HHVM_FUNCTION(stripcslashes,\n                     const String& str) {\n  if (str.empty()) {\n    return str;\n  }\n\n  return stringForEachBuffered(str.size(), str,\n    [&] (StringBuffer& ret, const char*& src, const char* end) {\n      char c;\n      const char* p;\n\n      if (*src != '\\\\' || src + 1 == end) {\n        ret.append(*src);\n        return;\n      }\n\n      switch (*++src) {\n        case 'n': ret.append('\\n'); break;\n        case 'r': ret.append('\\r'); break;\n        case 'a': ret.append('\\a'); break;\n        case 't': ret.append('\\t'); break;\n        case 'v': ret.append('\\v'); break;\n        case 'b': ret.append('\\b'); break;\n        case 'f': ret.append('\\f'); break;\n        case '\\\\': ret.append('\\\\'); break;\n        case 'x':\n          if (src + 1 == end || !isxdigit(src[1])) {\n            ret.append(*src);\n            break;\n          }\n\n          for (c = 0, ++src, p = src + 2; src < p && src < end &&\n               isxdigit(*src); ++src) {\n            c *= 16;\n            c += (*src < 'A' ? *src - '0' :\n                  *src < 'a' ? *src - 'A' + 10 :\n                               *src - 'a' + 10);\n          }\n          ret.append(c);\n          src--;\n          break;\n\n        default:\n          if (*src < '0' || '7' < *src) {\n            \/\/ The character after the slash is nothing special. Append it\n            \/\/ unchanged to the result.\n            ret.append(*src);\n            break;\n          }\n\n          \/\/ Decode a base 8 number up to 3 characters long.\n          for (c = 0, p = src + 3; src < p && src < end && '0' <= *src &&\n               *src < '8'; ++src) {\n            c *= 8;\n            c += (*src - '0');\n          }\n          ret.append(c);\n          src--;\n      }\n    });\n}\n\nString HHVM_FUNCTION(addslashes,\n                     const String& str) {\n  if (str.empty()) {\n    return str;\n  }\n\n  return stringForEachBuffered(str.size(), str,\n    [&] (StringBuffer& ret, const char* src, const char* end) {\n      switch (*src) {\n        case '\\0':\n          ret.append('\\\\');\n          ret.append('0');\n          break;\n        case '\\\\': case '\\\"': case '\\'':\n          ret.append('\\\\');\n          \/* fall through *\/\n        default:\n          ret.append(*src);\n      }\n    });\n}\n\nString HHVM_FUNCTION(stripslashes,\n                     const String& str) {\n  if (str.empty()) {\n    return str;\n  }\n\n  return stringForEachBuffered(str.size(), str,\n    [&] (StringBuffer& ret, const char*& src, const char* end) {\n      if (*src == '\\\\' && *++src == '0') {\n        ret.append('\\0');\n        return;\n      }\n      if (src < end) {\n        ret.append(*src);\n      }\n    });\n}\n\nString HHVM_FUNCTION(bin2hex,\n                     const String& str) {\n  if (str.empty()) {\n    return str;\n  }\n\n  return stringForEachBuffered(str.size(), str,\n    [&] (StringBuffer& ret, const char* src, const char* end) {\n      static char hexconvtab[] = \"0123456789abcdef\";\n      ret.append(hexconvtab[(unsigned char)*src >> 4]);\n      ret.append(hexconvtab[(unsigned char)*src & 15]);\n    });\n}\n\nVariant HHVM_FUNCTION(hex2bin,\n                      const String& str) {\n  if (str.empty()) {\n    return str;\n  }\n\n  if (str.size() % 2) {\n    raise_warning(\"hex2bin: malformed input\");\n    return false;\n  }\n\n  StringBuffer ret(str.size() \/ 2 + 1);\n\n  StringSlice sl  = str.slice();\n  const char* src = sl.begin();\n  const char* end = sl.end();\n\n  for (; src != end; ++src) {\n    int val;\n    if (isdigit(*src))                   val = 16 * (*src++ - '0');\n    else if ('a' <= *src && *src <= 'f') val = 16 * (*src++ - 'a' + 10);\n    else if ('A' <= *src && *src <= 'F') val = 16 * (*src++ - 'A' + 10);\n    else {\n      raise_warning(\"hex2bin: malformed input\");\n      return false;\n    }\n\n    if (isdigit(*src))                   val += (*src - '0');\n    else if ('a' <= *src && *src <= 'f') val += (*src - 'a' + 10);\n    else if ('A' <= *src && *src <= 'F') val += (*src - 'A' + 10);\n    else {\n      raise_warning(\"hex2bin: malformed input\");\n      return false;\n    }\n\n    ret.append((char)val);\n  }\n\n  return ret.detach();\n}\n\nconst StaticString\n  s_br(\"<br \/>\"),\n  s_non_xhtml_br(\"<br>\");\n\nString HHVM_FUNCTION(nl2br,\n                     const String& str,\n                     bool is_xhtml \/* = true *\/) {\n  if (str.empty()) {\n    return str;\n  }\n  String htmlType;\n\n  if (is_xhtml) {\n    htmlType = s_br;\n  } else {\n    htmlType = s_non_xhtml_br;\n  }\n\n  return stringForEachBuffered(str.size(), str,\n    [&] (StringBuffer& ret, const char*& src, const char* end) {\n      \/\/ PHP treats a carriage return beside a newline as the same break\n      \/\/ no matter what order they're in.  Don't do it for two of the same in\n      \/\/ a row, though...\n      switch (*src) {\n      case '\\n':\n        ret.append(htmlType);\n        \/\/ skip next if carriage return\n        if (*(src + 1) == '\\r') {\n          ret.append(*src);\n          ++src;\n        }\n        ret.append(*src);\n        break;\n      case '\\r':\n        ret.append(htmlType);\n        \/\/ skip next if newline\n        if (*(src + 1) == '\\n') {\n          ret.append(*src);\n          ++src;\n        }\n        \/* fall through *\/\n      default:\n        ret.append(*src);\n      }\n    });\n}\n\nString HHVM_FUNCTION(quotemeta,\n                     const String& str) {\n  if (str.empty()) {\n    return str;\n  }\n\n  return stringForEachBuffered(str.size(), str,\n    [&] (StringBuffer& ret, const char* src, const char* end) {\n      switch (*src) {\n        case '.': case '\\\\': case '+': case '*': case '?': case '[': case ']':\n        case '^': case '$': case '(': case ')':\n          ret.append('\\\\');\n          \/* fall through *\/\n        default:\n          ret.append(*src);\n      }\n    });\n}\n\nString HHVM_FUNCTION(str_shuffle,\n                     const String& str) {\n  if (str.size() <= 1) {\n    return str;\n  }\n\n  String ret(str, CopyString);\n  char* buf  = ret.get()->mutableData();\n  int left   = ret.size();\n\n  while (--left) {\n    int idx = HHVM_FN(rand)(0, left);\n    if (idx != left) {\n      char temp = buf[left];\n      buf[left] = buf[idx];\n      buf[idx] = temp;\n    }\n  }\n  return ret;\n}\n\nString HHVM_FUNCTION(strrev,\n                     const String& str) {\n  auto len = str.size();\n\n  String ret(len, ReserveString);\n\n  const char* data = str.data();\n  char* dest = ret.get()->mutableData();\n\n  for (int i = 0; i < len; ++i) {\n    dest[i] = data[len - i - 1];\n  }\n\n  ret.setSize(len);\n  return ret;\n}\n\nString HHVM_FUNCTION(strtolower,\n                     const String& str) {\n  return stringForEachFast(str, tolower);\n}\n\nString HHVM_FUNCTION(strtoupper,\n                     const String& str) {\n  return stringForEachFast(str, toupper);\n}\n\ntemplate <class OpTo, class OpIs> ALWAYS_INLINE\nString stringToCaseFirst(const String& str, OpTo tocase, OpIs iscase) {\n  if (str.empty() || iscase(str[0])) {\n    return str;\n  }\n\n  String ret(str, CopyString);\n  char* first = ret.get()->mutableData();\n\n  *first = tocase(*first);\n  return ret;\n}\n\nString HHVM_FUNCTION(ucfirst,\n                     const String& str) {\n  return stringToCaseFirst(str, toupper, isupper);\n}\n\nString HHVM_FUNCTION(lcfirst,\n                     const String& str) {\n  return stringToCaseFirst(str, tolower, islower);\n}\n\nString HHVM_FUNCTION(ucwords,\n                     const String& str) {\n  char last = ' ';\n  return stringForEachFast(str, [&] (char c) {\n    char ret = isspace(last) ? toupper(c) : c;\n    last = c;\n    return ret;\n  });\n}\n\nString HHVM_FUNCTION(strip_tags,\n                     const String& str,\n                     const Variant& allowable_tags \/* = \"\" *\/) {\n  return StringUtil::StripHTMLTags(str, allowable_tags.toString());\n}\n\ntemplate <bool left, bool right> ALWAYS_INLINE\nString stringTrim(const String& str, const String& charlist) {\n  char flags[256];\n  string_charmask(charlist.c_str(), charlist.size(), flags);\n\n  auto len = str.size();\n  int start = 0, end = len - 1;\n\n  if (left) {\n    for (; start < len && flags[(unsigned char)str[start]]; ++start)\n      \/* do nothing *\/;\n  }\n\n  if (right) {\n    for (; end >= start && flags[(unsigned char)str[end]]; --end) {}\n  }\n\n  return str.substr(start, end - start + 1);\n}\n\nString HHVM_FUNCTION(trim,\n                     const String& str,\n                     const String& charlist \/* = k_HPHP_TRIM_CHARLIST *\/) {\n  return stringTrim<true,true>(str, charlist);\n}\n\nString HHVM_FUNCTION(ltrim,\n                     const String& str,\n                     const String& charlist \/* = k_HPHP_TRIM_CHARLIST *\/) {\n  return stringTrim<true,false>(str, charlist);\n}\n\nString HHVM_FUNCTION(rtrim,\n                     const String& str,\n                     const String& charlist \/* = k_HPHP_TRIM_CHARLIST *\/) {\n  return stringTrim<false,true>(str, charlist);\n}\n\nString HHVM_FUNCTION(chop,\n                      const String& str,\n                      const String& charlist \/* = k_HPHP_TRIM_CHARLIST *\/) {\n  return stringTrim<false,true>(str, charlist);\n}\n\nVariant HHVM_FUNCTION(explode,\n                      const String& delimiter,\n                      const String& str,\n                      int limit \/* = 0x7FFFFFFF *\/) {\n  return StringUtil::Explode(str, delimiter, limit);\n}\n\nString HHVM_FUNCTION(implode,\n                     const Variant& arg1,\n                     const Variant& arg2 \/* = null_variant *\/) {\n  Array items;\n  String delim;\n  if (isContainer(arg1)) {\n    items = arg1;\n    delim = arg2.toString();\n  } else if (isContainer(arg2)) {\n    items = arg2;\n    delim = arg1.toString();\n  } else {\n    throw_bad_type_exception(\"implode() expects a container as \"\n                             \"one of the arguments\");\n    return String();\n  }\n  return StringUtil::Implode(items, delim, false);\n}\n\nString HHVM_FUNCTION(join,\n                     const Variant& arg1,\n                     const Variant& arg2 \/* = null_variant *\/) {\n  return HHVM_FN(implode)(arg1, arg2);\n}\n\nVariant HHVM_FUNCTION(str_split,\n                      const String& str,\n                      int64_t split_length \/* = 1 *\/) {\n  return StringUtil::Split(str, split_length);\n}\n\nVariant HHVM_FUNCTION(chunk_split,\n                      const String& body,\n                      int chunklen \/* = 76 *\/,\n                      const String& end \/* = \"\\r\\n\" *\/) {\n  return StringUtil::ChunkSplit(body, chunklen, end);\n}\n\nstruct TokenizerData final : RequestEventHandler {\n  String str;\n  int pos;\n  int mask[256];\n\n  void requestInit() override {\n    str.reset();\n    pos = 0;\n    memset(&mask, 0, sizeof(mask));\n  }\n  void requestShutdown() override {\n    requestInit();\n  }\n};\nIMPLEMENT_STATIC_REQUEST_LOCAL(TokenizerData, s_tokenizer_data);\n\nVariant HHVM_FUNCTION(strtok,\n                      const String& str,\n                      const Variant& token \/* = null_variant *\/) {\n  String stoken;\n  if (!token.isNull()) {\n    s_tokenizer_data->str = str;\n    s_tokenizer_data->pos = 0;\n    stoken = token.toString();\n  } else {\n    stoken = str;\n  }\n\n  String sstr = s_tokenizer_data->str;\n  int pos = s_tokenizer_data->pos;\n  if (pos >= sstr.size()) {\n    return false;\n  }\n\n  \/\/ set up mask\n  int *mask = s_tokenizer_data->mask;\n  for (int i = 0; i < stoken.size(); i++) {\n    mask[(unsigned char)stoken.data()[i]] = 1;\n  }\n\n  \/\/ skip leading delimiters\n  const char *s0 = sstr.data();\n  int i = pos;\n  for (; i < sstr.size(); i++) {\n    if (!mask[(unsigned char)s0[i]]) {\n      break;\n    }\n  }\n  int pos0 = i;\n  for (; i < sstr.size(); i++) {\n    if (mask[(unsigned char)s0[i]]) {\n      break;\n    }\n  }\n\n  \/\/ reset mask\n  for (int i = 0; i < stoken.size(); i++) {\n    mask[(unsigned char)stoken.data()[i]] = 0;\n  }\n\n  if (pos0 == sstr.size()) {\n    return false;\n  }\n\n  String ret(s0 + pos0, i - pos0, CopyString);\n  s_tokenizer_data->pos = i + 1;\n\n  return ret;\n}\n\nstatic\nVariant str_replace(const Variant& search, const Variant& replace, const String& subject,\n                    int &count, bool caseSensitive) {\n  count = 0;\n  if (search.is(KindOfArray)) {\n    String ret = subject;\n    int c = 0;\n\n    Array searchArr = search.toArray();\n    if (replace.is(KindOfArray)) {\n      Array replArr = replace.toArray();\n      ArrayIter replIter(replArr);\n      for (ArrayIter iter(searchArr); iter; ++iter) {\n        if (replIter) {\n          ret = string_replace(ret, iter.second().toString(),\n                               replIter.second().toString(),\n                               c, caseSensitive);\n          ++replIter;\n        } else {\n          ret = string_replace(ret, iter.second().toString(),\n                               \"\", c, caseSensitive);\n        }\n        count +=c;\n      }\n      return ret;\n    }\n\n    String repl = replace.toString();\n    for (ArrayIter iter(searchArr); iter; ++iter) {\n      ret = string_replace(ret, iter.second().toString(), repl, c,\n                           caseSensitive);\n      count += c;\n    }\n    return ret;\n  }\n\n  if (replace.is(KindOfArray)) {\n    raise_notice(\"Array to string conversion\");\n  }\n  return string_replace(subject, search.toString(), replace.toString(), count,\n                        caseSensitive);\n}\n\nstatic Variant str_replace(const Variant& search, const Variant& replace, const Variant& subject,\n                           int &count, bool caseSensitive) {\n  count = 0;\n  if (subject.is(KindOfArray)) {\n    Array arr = subject.toArray();\n    Array ret = Array::Create();\n    int c;\n    for (ArrayIter iter(arr); iter; ++iter) {\n      if (iter.second().is(KindOfArray) || iter.second().is(KindOfObject)) {\n        ret.set(iter.first(), iter.second());\n        continue;\n      }\n\n      String replaced = str_replace(search, replace, iter.second().toString(),\n                                    c, caseSensitive);\n      ret.set(iter.first(), replaced);\n      count += c;\n    }\n    return ret;\n  }\n  return str_replace(search, replace, subject.toString(), count,\n                     caseSensitive);\n}\n\nVariant HHVM_FUNCTION(str_replace,\n                      const Variant& search,\n                      const Variant& replace,\n                      const Variant& subject,\n                      VRefParam count \/* = null *\/) {\n  int nCount = 0;\n  Variant ret;\n  if (LIKELY(search.isString() && replace.isString() && subject.isString())) {\n    \/\/ Short-cut for the most common (and simplest) case\n    ret = string_replace(subject.asCStrRef(), search.asCStrRef(),\n                         replace.asCStrRef(), nCount, true);\n  } else {\n    \/\/ search, replace, and subject can all be arrays. str_replace() reduces all\n    \/\/ the valid combinations to multiple string_replace() calls.\n    ret = str_replace(search, replace, subject, nCount, true);\n  }\n  if (auto ref = count.getRefDataOrNull()) *ref->var() = nCount;\n  return ret;\n}\n\nVariant HHVM_FUNCTION(str_ireplace,\n                      const Variant& search,\n                      const Variant& replace,\n                      const Variant& subject,\n                      VRefParam count \/* = null *\/) {\n  int nCount = 0;\n  Variant ret = str_replace(search, replace, subject, nCount, false);\n  if (auto ref = count.getRefDataOrNull()) *ref->var() = nCount;\n  return ret;\n}\n\nVariant HHVM_FUNCTION(substr_replace,\n                      const Variant& str,\n                      const Variant& replacement,\n                      const Variant& start,\n                      const Variant& length \/* = 0x7FFFFFFF *\/) {\n  if (!str.is(KindOfArray)) {\n    String repl;\n    if (replacement.is(KindOfArray)) {\n      repl = replacement.asCArrRef()[0].toString();\n    } else {\n      repl = replacement.toString();\n    }\n    if (start.is(KindOfArray)) {\n      if (!length.is(KindOfArray)) {\n        throw_invalid_argument(\"start and length should be of same type - \"\n                               \"numerical or array\");\n        return str;\n      }\n      Array startArr = start.toArray();\n      Array lengthArr = length.toArray();\n      if (startArr.size() != lengthArr.size()) {\n        throw_invalid_argument(\"start and length: (different item count)\");\n        return str;\n      }\n      throw_invalid_argument(\"start and length as arrays not implemented\");\n      return str;\n    }\n    return string_replace(str.toString(), start.toInt32(), length.toInt32(),\n                          repl);\n  }\n\n  \/\/ 'start' and 'length' can be arrays (in which case we step through them in\n  \/\/ sync with stepping through 'str'), or not arrays, in which case we convert\n  \/\/ them to ints and always use those.\n  Array ret;\n  Array strArr = str.toArray();\n  folly::Optional<int> opStart;\n  folly::Optional<int> opLength;\n  if (!start.isArray()) {\n    opStart = start.toInt32();\n  }\n  if (!length.isArray()) {\n    opLength = length.toInt32();\n  }\n\n  Array startArr = start.toArray();\n  Array lengthArr = length.toArray();\n  ArrayIter startIter(startArr);\n  ArrayIter lengthIter(lengthArr);\n\n  if (replacement.is(KindOfArray)) {\n    Array replArr = replacement.toArray();\n    ArrayIter replIter(replArr);\n    for (ArrayIter iter(strArr); iter; ++iter) {\n      auto str = iter.second().toString();\n      \/\/ If 'start' or 'length' are arrays and we've gone past the end, default\n      \/\/ to 0 for start and the length of the input string for length.\n      int nStart =\n        (opStart.hasValue()\n         ? opStart.value()\n         : (startIter ? startIter.second().toInt32() : 0));\n      int nLength =\n        (opLength.hasValue()\n         ? opLength.value()\n         : (lengthIter ? lengthIter.second().toInt32() : str.length()));\n      if (startIter) ++startIter;\n      if (lengthIter) ++lengthIter;\n\n      String repl;\n      if (replIter) {\n        repl = replIter.second().toString();\n        ++replIter;\n      } else {\n        repl = empty_string();\n      }\n      auto s2 = string_replace(str, nStart, nLength, repl);\n      ret.append(s2);\n    }\n  } else {\n    String repl = replacement.toString();\n    for (ArrayIter iter(strArr); iter; ++iter) {\n      auto str = iter.second().toString();\n      int nStart =\n        (opStart.hasValue()\n         ? opStart.value()\n         : (startIter ? startIter.second().toInt32() : 0));\n      int nLength =\n        (opLength.hasValue()\n         ? opLength.value()\n         : (lengthIter ? lengthIter.second().toInt32() : str.length()));\n      if (startIter) ++startIter;\n      if (lengthIter) ++lengthIter;\n\n      auto s2 = string_replace(str, nStart, nLength, repl);\n      ret.append(s2);\n    }\n  }\n  return ret;\n}\n\nVariant HHVM_FUNCTION(substr,\n                      const String& str,\n                      int start,\n                      int length \/* = 0x7FFFFFFF *\/) {\n  String ret = str.substr(start, length, true);\n  if (ret.isNull()) return false;\n  return ret;\n}\n\nString HHVM_FUNCTION(str_pad,\n                     const String& input,\n                     int pad_length,\n                     const String& pad_string \/* = \" \" *\/,\n                     int pad_type \/* = k_STR_PAD_RIGHT *\/) {\n  return StringUtil::Pad(input, pad_length, pad_string,\n                         (StringUtil::PadType)pad_type);\n}\n\nString HHVM_FUNCTION(str_repeat,\n                     const String& input,\n                     int multiplier) {\n  if (input.empty()) {\n    return input;\n  }\n\n  if (multiplier < 0) {\n    raise_warning(\"Second argument has to be greater than or equal to 0\");\n    return String();\n  }\n\n  if (multiplier == 0) {\n    return empty_string();\n  }\n\n  if (input.size() == 1) {\n    String ret(multiplier, ReserveString);\n\n    memset(ret.mutableData(), *input.data(), multiplier);\n    ret.setSize(multiplier);\n    return ret;\n  }\n\n  StringBuffer ret(input.size() * multiplier);\n\n  while (multiplier--) {\n    ret.append(input);\n  }\n\n  return ret.detach();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nVariant sscanfImpl(const String& str,\n                   const String& format,\n                   const std::vector<Variant*>& args) {\n  Variant ret;\n  int result;\n  result = string_sscanf(str.c_str(), format.c_str(), args.size(), ret);\n  if (SCAN_ERROR_WRONG_PARAM_COUNT == result) return init_null();\n  if (args.empty()) return ret;\n\n  if (ret.isArray()) {\n    auto& retArray = ret.toArrRef();\n    for (int i = 0; i < retArray.size(); i++) {\n      auto var = args.at(i);\n      if (var) {\n        *var->getRefData() = retArray[i];\n      }\n    }\n    return retArray.size();\n  }\n  if (ret.isNull()) return 0;\n  return ret;\n}\n\nTypedValue* HHVM_FN(sscanf)(ActRec* ar) {\n  String str{getArg<KindOfString>(ar, 0)};\n  if (ar->numArgs() < 1) {\n    return arReturn(ar, init_null());\n  }\n  String format{getArg<KindOfString>(ar, 1)};\n\n  std::vector<Variant*> args;\n  for (int i = 2; i < ar->numArgs(); ++i) {\n    args.push_back(getArg<KindOfRef>(ar, i));\n  }\n\n  return arReturn(ar, sscanfImpl(str, format, args));\n}\n\nString HHVM_FUNCTION(chr, const Variant& ascii) {\n  \/\/ This is the only known occurance of ParamCoerceModeNullByte,\n  \/\/ so we treat it specially using an explicit tvCoerce call\n  Variant v(ascii);\n  auto tv = v.asTypedValue();\n  char c = 0;\n  if (tvCoerceParamToInt64InPlace(tv)) {\n    c = tv->m_data.num & 0xFF;\n  }\n  return String::FromChar(c);\n}\n\nint64_t HHVM_FUNCTION(ord,\n                      const String& str) {\n  return (int64_t)(unsigned char)str[0];\n}\n\nVariant HHVM_FUNCTION(money_format,\n                      const String& format,\n                      double number) {\n  String s = StringUtil::MoneyFormat(format.c_str(), number);\n  if (s.isNull()) return false;\n  return s;\n}\n\nString HHVM_FUNCTION(number_format,\n                     double number,\n                     int decimals \/* = 0 *\/,\n                     const Variant& dec_point_in \/* = \".\" *\/,\n                     const Variant& thousands_sep_in \/* = \",\" *\/) {\n\n  String dec_point(\".\");\n  if (!dec_point_in.isNull()) {\n    dec_point = dec_point_in.toString();\n  }\n  String thousands_sep(\",\");\n  if (!thousands_sep_in.isNull()) {\n    thousands_sep = thousands_sep_in.toString();\n  }\n\n  return string_number_format(number, decimals, dec_point, thousands_sep);\n}\n\nint64_t HHVM_FUNCTION(strcmp,\n                      const String& str1,\n                      const String& str2) {\n  return string_strcmp(str1.data(), str1.size(), str2.data(), str2.size());\n}\n\nVariant HHVM_FUNCTION(strncmp,\n                      const String& str1,\n                      const String& str2,\n                      int len) {\n  if (len < 0) {\n    raise_warning(\"Length must be greater than or equal to 0\");\n    return false;\n  }\n  return string_strncmp(str1.data(), str1.size(), str2.data(), str2.size(),\n                        len);\n}\n\nint64_t HHVM_FUNCTION(strnatcmp,\n                      const String& str1,\n                      const String& str2) {\n  return string_natural_cmp(str1.data(), str1.size(), str2.data(), str2.size(),\n                            false);\n}\n\nint64_t HHVM_FUNCTION(strcasecmp,\n                      const String& str1,\n                      const String& str2) {\n  return bstrcasecmp(str1.data(), str1.size(), str2.data(), str2.size());\n}\n\nVariant HHVM_FUNCTION(strncasecmp,\n                      const String& str1,\n                      const String& str2,\n                      int len) {\n  if (len < 0) {\n    raise_warning(\"Length must be greater than or equal to 0\");\n    return false;\n  }\n  return string_strncasecmp(str1.data(), str1.size(), str2.data(), str2.size(),\n                            len);\n}\n\nint64_t HHVM_FUNCTION(strnatcasecmp,\n                      const String& str1,\n                      const String& str2) {\n  return string_natural_cmp(str1.data(), str1.size(), str2.data(), str2.size(),\n                            true);\n}\n\nint64_t HHVM_FUNCTION(strcoll,\n                      const String& str1,\n                      const String& str2) {\n  return strcoll(str1.c_str(), str2.c_str());\n}\n\nVariant HHVM_FUNCTION(substr_compare,\n                      const String& main_str,\n                      const String& str,\n                      int offset,\n                      int length \/* = INT_MAX *\/,\n                      bool case_insensitivity \/* = false *\/) {\n  int s1_len = main_str.size();\n  int s2_len = str.size();\n\n  if (length <= 0) {\n    raise_warning(\"The length must be greater than zero\");\n    return false;\n  }\n\n  if (offset < 0) {\n    offset = s1_len + offset;\n    if (offset < 0) offset = 0;\n  }\n\n  if (offset >= s1_len) {\n    raise_warning(\"The start position cannot exceed initial string length\");\n    return false;\n  }\n\n  int cmp_len = s1_len - offset;\n  if (cmp_len < s2_len) cmp_len = s2_len;\n  if (cmp_len > length) cmp_len = length;\n\n  const char *s1 = main_str.data();\n  if (case_insensitivity) {\n    return bstrcasecmp(s1 + offset, cmp_len, str.data(), cmp_len);\n  }\n  return string_ncmp(s1 + offset, str.data(), cmp_len);\n}\n\nVariant HHVM_FUNCTION(strstr,\n                      const String& haystack,\n                      const Variant& needle,\n                      bool before_needle \/* = false *\/) {\n  Variant ret = HHVM_FN(strpos)(haystack, needle);\n  if (same(ret, false)) {\n    return false;\n  }\n  if (before_needle) {\n    return haystack.substr(0, ret.toInt32());\n  } else {\n    return haystack.substr(ret.toInt32());\n  }\n}\n\nVariant HHVM_FUNCTION(stristr,\n                      const String& haystack,\n                      const Variant& needle,\n                      bool before_needle \/* = false *\/) {\n  Variant ret = HHVM_FN(stripos)(haystack, needle);\n  if (same(ret, false)) {\n    return false;\n  }\n  if (before_needle) {\n    return haystack.substr(0, ret.toInt32());\n  } else {\n    return haystack.substr(ret.toInt32());\n  }\n}\n\ntemplate<bool existence_only>\nstatic NEVER_INLINE\nVariant strpbrk_char_list_has_nulls_slow(const String& haystack,\n                                         const String& char_list) {\n\n  auto const charListSz = char_list.size();\n  auto const charListData = char_list.c_str();\n  assert(memchr(charListData, '\\0', charListSz) != nullptr);\n\n  \/\/ in order to use strcspn, remove all null byte(s) from char_list\n  auto charListWithoutNull = (char*) req::malloc(charListSz);\n  SCOPE_EXIT { req::free(charListWithoutNull); };\n\n  auto copy_ptr = charListWithoutNull;\n  auto const charListStop = charListData + char_list.size();\n  for (auto ptr = charListData; ptr != charListStop; ++ptr) {\n    if (*ptr != '\\0') { *copy_ptr++ = *ptr; }\n  }\n  assert((copy_ptr - charListWithoutNull) < charListSz);\n  \/\/ at least one of charListData chars was null, so there must be room:\n  *copy_ptr = '\\0';\n\n  \/\/ Use strcspn instead of strpbrk because the latter doesn't report when\n  \/\/ its terminated due to a null byte in haystack in any manageable way.\n  auto haySize = haystack.size();\n  auto hayData = haystack.c_str();\n\n  size_t idx = strcspn(hayData, charListWithoutNull);\n  if (idx < haySize) {\n    \/\/ we know that char_list contains null bytes, being terminated because\n    \/\/ haystack has null bytes is just dandy\n    if (existence_only) { return true; }\n    return String(hayData + idx, haySize - idx, CopyString);\n  }\n  return false;\n}\n\ntemplate<bool existence_only>\nstatic ALWAYS_INLINE\nVariant strpbrk_impl(const String& haystack, const String& char_list) {\n  if (char_list.empty()) {\n    throw_invalid_argument(\"char_list: (empty)\");\n    return false;\n  }\n  if (haystack.empty()) {\n    return false;\n  }\n\n  auto charListData = char_list.c_str();\n\n  \/\/ equivalent to rawmemchr(charListData, '\\0') ... charListData must be\n  \/\/ null-terminated\n  auto firstNull = charListData;\n  while (*firstNull != '\\0') { ++firstNull; }\n\n  auto const hasNullByte = (firstNull - charListData) < char_list.size();\n\n  if (UNLIKELY(hasNullByte)) {\n    if ((firstNull - charListData) == (char_list.size() - 1)) {\n      \/\/ the first null is the last character in char_list\n    } else if (firstNull == charListData) {\n      \/\/ the first null is the first character in char_list\n      auto secondNull = firstNull + 1;\n      while (*secondNull != '\\0') { ++secondNull; }\n\n      if ((secondNull - charListData) != char_list.size()) {\n        return\n          strpbrk_char_list_has_nulls_slow<existence_only>(haystack, char_list);\n      }\n      ++charListData; \/\/ we can remember the null byte\n    } else {\n      return\n        strpbrk_char_list_has_nulls_slow<existence_only>(haystack, char_list);\n    }\n  }\n\n  \/\/ Use strcspn instead of strpbrk because the latter doesn't report when\n  \/\/ it's terminated due to a null byte in haystack in any manageable way.\n  auto haySize = haystack.size();\n  auto hayData = haystack.c_str();\nretry:\n  size_t idx = strcspn(hayData, charListData);\n  if (idx < haySize) {\n    if (UNLIKELY(hayData[idx] == '\\0' && !hasNullByte)) {\n      hayData += idx + 1;\n      haySize -= idx + 1;\n      goto retry;\n    }\n    if (existence_only) { return true; }\n\n    return String(hayData + idx, haySize - idx, CopyString);\n  }\n  return false;\n}\n\nbool str_contains_any_of(const String& haystack, const String& char_list) {\n  return strpbrk_impl<true>(haystack, char_list).toBooleanVal();\n}\n\nVariant HHVM_FUNCTION(strpbrk,\n                      const String& haystack,\n                      const String& char_list) {\n  return strpbrk_impl<false>(haystack, char_list);\n}\n\nVariant HHVM_FUNCTION(strpos,\n                      const String& haystack,\n                      const Variant& needle,\n                      int offset \/* = 0 *\/) {\n  if (offset < 0 || offset > haystack.size()) {\n    raise_warning(\"Offset not contained in string\");\n    return false;\n  }\n  int pos;\n  if (needle.isString()) {\n    String n(needle.toString());\n    if (n.length() == 0) {\n      raise_warning(\"Empty delimiter\");\n      return false;\n    }\n    pos = haystack.find(n, offset);\n  } else {\n    pos = haystack.find(needle.toByte(), offset);\n  }\n  if (pos >= 0) return pos;\n  return false;\n}\n\nVariant HHVM_FUNCTION(stripos,\n                      const String& haystack,\n                      const Variant& needle,\n                      int offset \/* = 0 *\/) {\n  if (offset < 0 || offset > haystack.size()) {\n    raise_warning(\"Offset not contained in string\");\n    return false;\n  }\n  int pos;\n  if (needle.isString()) {\n    pos = haystack.find(needle.toString(), offset, false);\n  } else {\n    pos = haystack.find(needle.toByte(), offset, false);\n  }\n  if (pos >= 0) return pos;\n  return false;\n}\n\nstatic bool is_valid_strrpos_args(\n    const String& haystack,\n    const Variant& needle,\n    int offset) {\n  if (haystack.size() == 0) {\n    return false;\n  }\n  if (needle.isString() && needle.toString().size() == 0) {\n    return false;\n  }\n  if (offset < -haystack.size() || offset > haystack.size()) {\n    raise_warning(\"Offset is greater than the length of haystack string\");\n    return false;\n  }\n  return true;\n}\n\nVariant HHVM_FUNCTION(strchr,\n                      const String& haystack,\n                      const Variant& needle) {\n  return HHVM_FN(strstr)(haystack, needle);\n}\n\nVariant HHVM_FUNCTION(strrchr,\n                      const String& haystack,\n                      const Variant& needle) {\n  if (haystack.size() == 0) {\n    return false;\n  }\n\n  int pos;\n  if (needle.isString() && needle.toString().size() > 0) {\n    pos = haystack.rfind(needle.toString().data()[0], false);\n  } else {\n    pos = haystack.rfind(needle.toByte(), false);\n  }\n  if (pos < 0) return false;\n  return haystack.substr(pos);\n}\n\nVariant HHVM_FUNCTION(strrpos,\n                      const String& haystack,\n                      const Variant& needle,\n                      int offset \/* = 0 *\/) {\n  if (!is_valid_strrpos_args(haystack, needle, offset)) {\n    return false;\n  }\n  int pos;\n  if (needle.isString()) {\n    pos = haystack.rfind(needle.toString(), offset);\n  } else {\n    pos = haystack.rfind(needle.toByte(), offset);\n  }\n  if (pos >= 0) return pos;\n  return false;\n}\n\nVariant HHVM_FUNCTION(strripos,\n                      const String& haystack,\n                      const Variant& needle,\n                      int offset \/* = 0 *\/) {\n  if (!is_valid_strrpos_args(haystack, needle, offset)) {\n    return false;\n  }\n  int pos;\n  if (needle.isString()) {\n    pos = haystack.rfind(needle.toString(), offset, false);\n  } else {\n    pos = haystack.rfind(needle.toByte(), offset, false);\n  }\n  if (pos >= 0) return pos;\n  return false;\n}\n\nVariant HHVM_FUNCTION(substr_count,\n                      const String& haystack,\n                      const String& needle,\n                      int offset \/* = 0 *\/,\n                      int length \/* = 0x7FFFFFFF *\/) {\n  int lenNeedle = needle.size();\n  if (lenNeedle == 0) {\n    throw_invalid_argument(\"needle: (empty)\");\n    return false;\n  }\n\n  if (offset < 0 || offset > haystack.size()) {\n    throw_invalid_argument(\"offset: (out of range)\");\n    return false;\n  }\n  if (length == 0x7FFFFFFF) {\n    length = haystack.size() - offset;\n  } else if (length <= 0 || length > haystack.size() - offset) {\n    throw_invalid_argument(\"length: (out of range)\");\n    return false;\n  }\n\n  int count = 0;\n  int posMax = offset + length - lenNeedle;\n  for (int pos = haystack.find(needle, offset);\n       pos != -1 && pos <= posMax;\n       pos = haystack.find(needle, pos + lenNeedle)) {\n    ++count;\n  }\n  return count;\n}\n\nnamespace {\n  bool string_strspn_check(int inputLength, int &start, int &scanLength) {\n    if (start < 0) {\n      start += inputLength;\n      if (start < 0) {\n        start = 0;\n      }\n    } else if (start > inputLength) {\n      return false;\n    }\n\n    if (scanLength < 0) {\n      scanLength += (inputLength - start);\n      if (scanLength < 0) {\n        scanLength = 0;\n      }\n    }\n    if (scanLength > inputLength - start) {\n      scanLength = inputLength - start;\n    }\n    return true;\n  }\n}\n\nVariant HHVM_FUNCTION(strspn,\n                      const String& str1,\n                      const String& str2,\n                      int start \/* = 0 *\/,\n                      int length \/* = 0x7FFFFFFF *\/) {\n  const char *s1 = str1.data();\n  const char *s2 = str2.data();\n  int s1_len = str1.size();\n  int s2_len = str2.size();\n\n  if (!string_strspn_check(s1_len, start, length)) {\n    return false;\n  }\n\n  s1 += start;\n  for (int pos = 0; pos < length; ++pos) {\n    if (memchr(s2, *(s1++), s2_len) == NULL) return pos;\n  }\n\n  return length;\n}\n\nVariant HHVM_FUNCTION(strcspn,\n                      const String& str1,\n                      const String& str2,\n                      int start \/* = 0 *\/,\n                      int length \/* = 0x7FFFFFFF *\/) {\n  const char *s1 = str1.data();\n  const char *s2 = str2.data();\n  int s1_len = str1.size();\n  int s2_len = str2.size();\n\n  if (!string_strspn_check(s1_len, start, length)) {\n    return false;\n  }\n\n  s1 += start;\n  for (int pos = 0; pos < length; ++pos) {\n    if (memchr(s2, *(s1++), s2_len) != NULL) return pos;\n  }\n\n  return length;\n}\n\nVariant HHVM_FUNCTION(strlen,\n                      const Variant& vstr) {\n  auto const cell = vstr.asCell();\n  switch (cell->m_type) {\n    case KindOfStaticString:\n    case KindOfString:\n      return Variant(cell->m_data.pstr->size());\n\n    case KindOfArray:\n      raise_warning(\"strlen() expects parameter 1 to be string, \"\n                    \"array given\");\n      return init_null();\n\n    case KindOfResource:\n      raise_warning(\"strlen() expects parameter 1 to be string, \"\n                    \"resource given\");\n      return init_null();\n\n    case KindOfObject:\n      if (!HHVM_FN(method_exists)(vstr, \"__toString\")) {\n        raise_warning(\"strlen() expects parameter 1 to be string, \"\n                      \"object given\");\n        return init_null();\n      }\n      \/\/ else fallback to default\n    case KindOfUninit:\n    case KindOfNull:\n    case KindOfBoolean:\n    case KindOfInt64:\n    case KindOfDouble: {\n      const String& str = vstr.toString();\n      return Variant(str.size());\n    }\n\n    case KindOfRef:\n    case KindOfClass:\n      break;\n  }\n  not_reached();\n}\n\nArray HHVM_FUNCTION(str_getcsv,\n                    const String& str,\n                    const String& delimiter \/* = \",\" *\/,\n                    const String& enclosure \/* = \"\\\"\" *\/,\n                    const String& escape \/* = \"\\\\\" *\/) {\n  if (str.empty()) {\n    return Array::Create(null_variant);\n  }\n\n  auto check_arg = [](const String& arg, char default_arg) {\n    return arg.size() > 0 ? arg[0] : default_arg;\n  };\n\n  char delimiter_char = check_arg(delimiter, ',');\n  char enclosure_char = check_arg(enclosure, '\"');\n  char escape_char = check_arg(escape, '\\\\');\n\n  auto dummy = req::make<PlainFile>();\n  return dummy->readCSV(0, delimiter_char, enclosure_char, escape_char, &str);\n}\n\nVariant HHVM_FUNCTION(count_chars,\n                      const String& str,\n                      int64_t mode \/* = 0 *\/) {\n  int chars[256];\n  memset((void*)chars, 0, sizeof(chars));\n  const unsigned char *buf = (const unsigned char *)str.data();\n  for (int len = str.size(); len > 0; len--) {\n    chars[*buf++]++;\n  }\n\n  Array retarr = Array::Create();\n  char retstr[256];\n  int retlen = 0;\n  switch (mode) {\n  case 0:\n    for (int inx = 0; inx < 256; inx++) {\n      retarr.set(inx, chars[inx]);\n    }\n    return retarr;\n  case 1:\n    for (int inx = 0; inx < 256; inx++) {\n      if (chars[inx] != 0) {\n        retarr.set(inx, chars[inx]);\n      }\n    }\n    return retarr;\n  case 2:\n    for (int inx = 0; inx < 256; inx++) {\n      if (chars[inx] == 0) {\n        retarr.set(inx, chars[inx]);\n      }\n    }\n    return retarr;\n  case 3:\n    for (int inx = 0; inx < 256; inx++) {\n      if (chars[inx] != 0) {\n        retstr[retlen++] = inx;\n      }\n    }\n    return String(retstr, retlen, CopyString);\n  case 4:\n    for (int inx = 0; inx < 256; inx++) {\n      if (chars[inx] == 0) {\n        retstr[retlen++] = inx;\n      }\n    }\n    return String(retstr, retlen, CopyString);\n  }\n\n  throw_invalid_argument(\"mode: %\" PRId64, mode);\n  return false;\n}\n\n\/**\n * Counts the number of words inside a string. If format of 1 is specified,\n * then the function will return an array containing all the words\n * found inside the string. If format of 2 is specified, then the function\n * will return an associated array where the position of the word is the key\n * and the word itself is the value.\n *\n * For the purpose of this function, 'word' is defined as a locale dependent\n * string containing alphabetic characters, which also may contain, but not\n * start with \"'\" and \"-\" characters.\n *\/\nVariant HHVM_FUNCTION(str_word_count,\n                      const String& str,\n                      int64_t format \/* = 0 *\/,\n                      const String& charlist \/* = \"\" *\/) {\n  int str_len = str.size();\n  switch (format) {\n  case 1:\n  case 2:\n    if (!str_len) {\n      return empty_array();\n    }\n    break;\n  case 0:\n    if (!str_len) {\n      return 0LL;\n    }\n    break;\n  default:\n    throw_invalid_argument(\"format: %\" PRId64, format);\n    return false;\n  }\n\n  char ch[256];\n  const char *char_list = charlist.data();\n  if (*char_list) {\n    string_charmask(char_list, charlist.size(), ch);\n  } else {\n    char_list = NULL;\n  }\n\n  int word_count = 0;\n  const char *s0 = str.data();\n  const char *p = s0;\n  const char *e = p + str_len;\n\n  \/\/ first character cannot be ' or -, unless explicitly allowed by the user\n  if ((*p == '\\'' && (!char_list || !ch[(int)'\\''])) ||\n      (*p == '-' && (!char_list || !ch[(int)'-']))) {\n    p++;\n  }\n\n  \/\/ last character cannot be -, unless explicitly allowed by the user\n  if (*(e - 1) == '-' && (!char_list || !ch[(int)'-'])) {\n    e--;\n  }\n\n  Array ret;\n  while (p < e) {\n    const char *s = p;\n    while (p < e &&\n           (isalpha(*p) || (char_list && ch[(unsigned char)*p]) ||\n            *p == '\\'' || *p == '-')) {\n      p++;\n    }\n    if (p > s) {\n      switch (format) {\n      case 1:\n        ret.append(String(s, p - s, CopyString));\n        break;\n      case 2:\n        ret.set((int)(s - s0), String(s, p - s, CopyString));\n        break;\n      default:\n        word_count++;\n        break;\n      }\n    }\n    p++;\n  }\n\n  if (!format) {\n    return word_count;\n  }\n  return ret.isNull() ? Array::Create() : ret;\n}\n\nint64_t HHVM_FUNCTION(levenshtein,\n                      const String& str1,\n                      const String& str2,\n                      int cost_ins \/* = 1 *\/,\n                      int cost_rep \/* = 1 *\/,\n                      int cost_del \/* = 1 *\/) {\n  return string_levenshtein(str1.data(), str1.size(), str2.data(), str2.size(),\n                            cost_ins, cost_rep, cost_del);\n}\n\nint64_t HHVM_FUNCTION(similar_text,\n                      const String& first,\n                      const String& second,\n                      VRefParam percent \/* = uninit_null() *\/) {\n  float p;\n  int ret = string_similar_text(first.data(), first.size(),\n                                second.data(), second.size(), &p);\n  percent.assignIfRef(p);\n  return ret;\n}\n\nVariant HHVM_FUNCTION(soundex,\n                      const String& str) {\n  if (str.empty()) return false;\n  return string_soundex(str);\n}\n\nVariant HHVM_FUNCTION(metaphone,\n                      const String& str,\n                      int phones \/* = 0 *\/) {\n  return string_metaphone(str.data(), str.size(), 0, 1);\n}\n\nString HHVM_FUNCTION(html_entity_decode,\n                     const String& str,\n                     int flags \/* = k_ENT_COMPAT *\/,\n                     const String& charset \/* = \"UTF-8\" *\/) {\n  const char *scharset = charset.data();\n  if (!*scharset) scharset = \"ISO-8859-1\";\n  return StringUtil::HtmlDecode(str, StringUtil::toQuoteStyle(flags),\n                                scharset, true);\n}\n\nString HHVM_FUNCTION(htmlentities,\n                     const String& str,\n                     int flags \/* = k_ENT_COMPAT *\/,\n                     const String& charset \/* = \"UTF-8\" *\/,\n                     bool double_encode \/* = true *\/) {\n  \/\/ dropping double_encode parameters and see runtime\/base\/zend-html.h\n  const char *scharset = charset.data();\n  if (!*scharset) scharset = \"ISO-8859-1\";\n  return StringUtil::HtmlEncode(str, StringUtil::toQuoteStyleBitmask(flags),\n                                scharset, double_encode, true);\n}\n\nString HHVM_FUNCTION(htmlspecialchars_decode,\n                     const String& str,\n                     int flags \/* = k_ENT_COMPAT *\/) {\n  return StringUtil::HtmlDecode(str, StringUtil::toQuoteStyle(flags),\n                                \"UTF-8\", false);\n}\n\nString HHVM_FUNCTION(htmlspecialchars,\n                     const String& str,\n                     int flags \/* = k_ENT_COMPAT *\/,\n                     const String& charset \/* = \"UTF-8\" *\/,\n                     bool double_encode \/* = true *\/) {\n  \/\/ dropping double_encode parameters and see runtime\/base\/zend-html.h\n  const char *scharset = charset.data();\n  if (!*scharset) scharset = \"ISO-8859-1\";\n  return StringUtil::HtmlEncode(str, StringUtil::toQuoteStyleBitmask(flags),\n                                scharset, double_encode, false);\n}\n\nString HHVM_FUNCTION(fb_htmlspecialchars,\n                     const String& str,\n                     int flags \/* = k_ENT_COMPAT *\/,\n                     const String& charset \/* = \"ISO-8859-1\" *\/,\n                     const Variant& extra \/* = empty_array_ref *\/) {\n  if (!extra.isNull() && !extra.isArray()) {\n    throw_expected_array_exception(\"fb_htmlspecialchars\");\n  }\n  const Array& arr_extra = extra.isNull() ? empty_array_ref : extra.toArray();\n  return StringUtil::HtmlEncodeExtra(str, StringUtil::toQuoteStyle(flags),\n                                     charset.data(), false, arr_extra);\n}\n\nString HHVM_FUNCTION(quoted_printable_encode,\n                     const String& str) {\n  return StringUtil::QuotedPrintableEncode(str);\n}\n\nString HHVM_FUNCTION(quoted_printable_decode,\n                     const String& str) {\n  return StringUtil::QuotedPrintableDecode(str);\n}\n\nVariant HHVM_FUNCTION(convert_uudecode,\n                      const String& data) {\n  String ret = StringUtil::UUDecode(data);\n  if (ret.isNull()) {\n    raise_warning(\n      \"convert_uudecode(): \"\n      \"The given parameter is not a valid uuencoded string\");\n    return false; \/\/ bad format\n  }\n  return ret;\n}\n\nVariant HHVM_FUNCTION(convert_uuencode,\n                      const String& data) {\n  if (data.empty()) return false;\n  return StringUtil::UUEncode(data);\n}\n\nString HHVM_FUNCTION(str_rot13,\n                     const String& str) {\n  return StringUtil::ROT13(str);\n}\n\nint64_t HHVM_FUNCTION(crc32,\n                      const String& str) {\n  return (uint32_t)StringUtil::CRC32(str);\n}\n\nString HHVM_FUNCTION(crypt,\n                     const String& str,\n                     const String& salt \/* = \"\" *\/) {\n  return StringUtil::Crypt(str, salt.c_str());\n}\n\nString HHVM_FUNCTION(md5,\n                     const String& str,\n                     bool raw_output \/* = false *\/) {\n  return StringUtil::MD5(str, raw_output);\n}\n\nString HHVM_FUNCTION(sha1,\n                     const String& str,\n                     bool raw_output \/* = false *\/) {\n  return StringUtil::SHA1(str, raw_output);\n}\n\nbool strtr_slow(const Array& arr, StringBuffer& result, String& key,\n                const char*s, int& pos, int minlen, int maxlen) {\n\n  memcpy(key.mutableData(), s + pos, maxlen);\n  for (int len = maxlen; len >= minlen; len--) {\n    key.setSize(len);\n    auto const& var = arr->get(key.toKey());\n    if (&var != &null_variant) {\n      String replace = var.toString();\n      if (!replace.empty()) {\n        result.append(replace);\n      }\n      pos += len;\n      return true;\n    }\n  }\n  return false;\n}\n\nVariant strtr_fast(const String& str, const Array& arr,\n                   int minlen, int maxlen) {\n  uint64_t mask[maxlen][256];\n\n  memset(&mask[0][0], 0, sizeof(mask));\n\n  int pattern_id = 0;\n  for (ArrayIter iter(arr); iter; ++iter, pattern_id++) {\n    String search = iter.first();\n    StringSlice slice = search.slice();\n\n    for (auto i = 0; i < slice.len; i++) {\n      mask[i][(unsigned char)slice.ptr[i]] |= (1 << pattern_id);\n    }\n  }\n  const char* s = str.data();\n  int slen = str.size();\n  StringBuffer result(slen);\n  String key(maxlen, ReserveString);\n\n  for (auto i = 0; i < slen;) {\n    if ((i + maxlen) > slen) {\n      maxlen = slen - i;\n    }\n    uint64_t match = ~0x0ULL;\n    bool possible_match = false;\n\n    for (auto pos = 0; pos < maxlen; pos++) {\n      match &= mask[pos][(unsigned char)s[i + pos]];\n      if (!match) break;\n      if (pos >= minlen - 1) {\n        possible_match = true;\n        break;\n      }\n    }\n    bool found = false;\n    if (possible_match) {\n      found = strtr_slow(arr, result, key, s, i, minlen, maxlen);\n    }\n    if (!found) {\n      result.append(s[i++]);\n    }\n  }\n  return result.detach();\n}\n\nstatic constexpr int kBitsPerQword = CHAR_BIT * sizeof(uint64_t);\n\nVariant HHVM_FUNCTION(strtr,\n                      const String& str,\n                      const Variant& from,\n                      const Variant& to \/* = null_variant *\/) {\n  if (str.empty()) {\n    return str;\n  }\n\n  if (!to.isNull()) {\n    return StringUtil::Translate(str, from.toString(), to.toString());\n  }\n\n  if (!from.is(KindOfArray)) {\n    throw_invalid_argument(\"2nd argument: (not array)\");\n    return false;\n  }\n\n  int maxlen = 0;\n  int minlen = -1;\n  Array arr = from.toArray();\n\n  if (arr.empty()) {\n    \/\/ Nothing to translate\n    return str;\n  }\n\n  for (ArrayIter iter(arr); iter; ++iter) {\n    String search = iter.first();\n    int len = search.size();\n    if (len < 1) return false;\n    if (maxlen < len) maxlen = len;\n    if (minlen == -1 || minlen > len) minlen = len;\n  }\n\n  if (arr.size() <= kBitsPerQword && maxlen <= 16) {\n    return strtr_fast(str, arr, minlen, maxlen);\n  }\n\n  const char *s = str.data();\n  int slen = str.size();\n\n  StringBuffer result(slen);\n  String key(maxlen, ReserveString);\n\n  for (int pos = 0; pos < slen; ) {\n    if ((pos + maxlen) > slen) {\n      maxlen = slen - pos;\n    }\n    bool found = strtr_slow(arr, result, key, s, pos, minlen, maxlen);\n    if (!found) {\n      result.append(s[pos++]);\n    }\n  }\n  return result.detach();\n}\n\nVariant HHVM_FUNCTION(setlocale,\n                      int category,\n                      const Variant& locale,\n                      const Array& _argv \/* = null_array *\/) {\n  Array argv = _argv;\n  if (locale.is(KindOfArray)) {\n    if (!argv.empty()) throw_invalid_argument(\"locale: not string)\");\n    argv = locale; \/\/ ignore _argv\n  }\n\n  for (int i = -1; i < argv.size(); i++) {\n    String slocale;\n    if (i == -1) {\n      if (locale.is(KindOfArray)) continue;\n      slocale = locale.toString();\n    } else {\n      slocale = argv[i].toString();\n    }\n\n    const char *loc = slocale.c_str();\n    if (slocale.size() >= 255) {\n      throw_invalid_argument(\"locale name is too long: %s\", loc);\n      return false;\n    }\n    if (strcmp(\"0\", loc) == 0) {\n      loc = NULL;\n    }\n    {\n      Lock lock(s_mutex);\n      const char *retval = setlocale(category, loc);\n      if (retval) {\n        return String(retval, CopyString);\n      }\n    }\n  }\n  return false;\n}\n\nconst StaticString\n  s_decimal_point(\"decimal_point\"),\n  s_thousands_sep(\"thousands_sep\"),\n  s_int_curr_symbol(\"int_curr_symbol\"),\n  s_currency_symbol(\"currency_symbol\"),\n  s_mon_decimal_point(\"mon_decimal_point\"),\n  s_mon_thousands_sep(\"mon_thousands_sep\"),\n  s_positive_sign(\"positive_sign\"),\n  s_negative_sign(\"negative_sign\"),\n  s_int_frac_digits(\"int_frac_digits\"),\n  s_frac_digits(\"frac_digits\"),\n  s_p_cs_precedes(\"p_cs_precedes\"),\n  s_p_sep_by_space(\"p_sep_by_space\"),\n  s_n_cs_precedes(\"n_cs_precedes\"),\n  s_n_sep_by_space(\"n_sep_by_space\"),\n  s_p_sign_posn(\"p_sign_posn\"),\n  s_n_sign_posn(\"n_sign_posn\"),\n  s_grouping(\"grouping\"),\n  s_mon_grouping(\"mon_grouping\");\n\nArray HHVM_FUNCTION(localeconv) {\n  struct lconv currlocdata;\n  {\n    Lock lock(s_mutex);\n    struct lconv *res = localeconv();\n    currlocdata = *res;\n  }\n\n  Array ret;\n#define SET_LOCALE_STRING(x) ret.set(s_ ## x, String(currlocdata.x, CopyString))\n  SET_LOCALE_STRING(decimal_point);\n  SET_LOCALE_STRING(thousands_sep);\n  SET_LOCALE_STRING(int_curr_symbol);\n  SET_LOCALE_STRING(currency_symbol);\n  SET_LOCALE_STRING(mon_decimal_point);\n  SET_LOCALE_STRING(mon_thousands_sep);\n  SET_LOCALE_STRING(positive_sign);\n  SET_LOCALE_STRING(negative_sign);\n#define SET_LOCALE_INTEGER(x) ret.set(s_ ## x, currlocdata.x)\n  SET_LOCALE_INTEGER(int_frac_digits);\n  SET_LOCALE_INTEGER(frac_digits);\n  SET_LOCALE_INTEGER(p_cs_precedes);\n  SET_LOCALE_INTEGER(p_sep_by_space);\n  SET_LOCALE_INTEGER(n_cs_precedes);\n  SET_LOCALE_INTEGER(n_sep_by_space);\n  SET_LOCALE_INTEGER(p_sign_posn);\n  SET_LOCALE_INTEGER(n_sign_posn);\n\n  Array grouping, mon_grouping;\n\n  \/* Grab the grouping data out of the array *\/\n  int len = strlen(currlocdata.grouping);\n  for (int i = 0; i < len; i++) {\n    grouping.set(i, currlocdata.grouping[i]);\n  }\n  ret.set(s_grouping, grouping);\n\n  \/* Grab the monetary grouping data out of the array *\/\n  len = strlen(currlocdata.mon_grouping);\n  for (int i = 0; i < len; i++) {\n    mon_grouping.set(i, currlocdata.mon_grouping[i]);\n  }\n  ret.set(s_mon_grouping, mon_grouping);\n\n  return ret;\n}\n\nString HHVM_FUNCTION(nl_langinfo,\n                     int item) {\n  return nl_langinfo(item);\n}\n\nString HHVM_FUNCTION(convert_cyr_string,\n                     const String& str,\n                     const String& from,\n                     const String& to) {\n  return string_convert_cyrillic_string(str, from[0], to[0]);\n}\n\n\nconst StaticString\n  s_amp(\"&\"),\n  s_ampsemi(\"&amp;\");\n\n\n#define ENT_HTML_QUOTE_NONE     0\n#define ENT_HTML_QUOTE_SINGLE   1\n#define ENT_HTML_QUOTE_DOUBLE   2\n\nstatic const HtmlBasicEntity basic_entities_noapos[] = {\n  { '\"',  \"&quot;\",   6,  ENT_HTML_QUOTE_DOUBLE },\n  { '\\'', \"&#039;\",   6,  ENT_HTML_QUOTE_SINGLE },\n  { '<',  \"&lt;\",     4,  0 },\n  { '>',  \"&gt;\",     4,  0 },\n  { 0,    nullptr,    0,  0 }\n};\n\nstatic const HtmlBasicEntity basic_entities_apos[] = {\n  { '\"',  \"&quot;\",   6,  ENT_HTML_QUOTE_DOUBLE },\n  { '\\'', \"&apos;\",   6,  ENT_HTML_QUOTE_SINGLE },\n  { '<',  \"&lt;\",     4,  0 },\n  { '>',  \"&gt;\",     4,  0 },\n  { 0,     nullptr,   0,  0 }\n};\n\nconst HtmlBasicEntity* get_basic_table(bool all, entity_doctype doctype) {\n  if (doctype == entity_doctype::xhtml) {\n    return all ? basic_entities_noapos : basic_entities_apos;\n  }\n\n  if (doctype == entity_doctype::html401) {\n    return basic_entities_noapos;\n  }\n\n  return basic_entities_apos;\n}\n\n#define ENT_HTML_DOC_TYPE_MASK  (16|32)\n#define ENT_HTML_DOC_HTML401    0\n#define ENT_HTML_DOC_XML1       16\n#define ENT_HTML_DOC_XHTML      32\n#define ENT_HTML_DOC_HTML5      (16|32)\n\nentity_doctype determine_doctype(int flags) {\n  int mask = flags & ENT_HTML_DOC_TYPE_MASK;\n  switch (mask) {\n    case ENT_HTML_DOC_HTML401: return entity_doctype::html401;\n    case ENT_HTML_DOC_XML1: return entity_doctype::xml1;\n    case ENT_HTML_DOC_XHTML: return entity_doctype::xhtml;\n    case ENT_HTML_DOC_HTML5: return entity_doctype::html5;\n  }\n  not_reached();\n}\n\nString encode_as_utf8(int code_point) {\n  auto res = folly::codePointToUtf8(code_point);\n  return String::FromCStr(res.data());\n}\n\nArray HHVM_FUNCTION(get_html_translation_table,\n                    int table \/* = 0 *\/,\n                    int flags \/* = k_ENT_COMPAT *\/,\n                    const String& encoding \/* = \"UTF-8\" *\/) {\n  using namespace entity_charset_enum;\n  auto charset = determine_charset(encoding.data());\n  if (charset == cs_unknown) {\n    charset = cs_utf_8;\n    if (!encoding.empty()) {\n      raise_warning(\"get_html_translation_table(): charset `%s' not supported\"\n                    \", assuming utf-8\", encoding.data());\n    }\n  }\n  auto doctype = determine_doctype(flags);\n\n  const int HTML_SPECIALCHARS = 0;\n  const int HTML_ENTITIES = 1;\n  bool all = (table == HTML_ENTITIES);\n\n  Array ret;\n  switch (table) {\n  case HTML_ENTITIES: {\n    if (charset == cs_utf_8) {\n      auto entity_map = get_doctype_entity_table(doctype);\n      for (const auto& item : *entity_map) {\n        auto key = encode_as_utf8(item.first);\n\n        char buffer[32];\n        snprintf(buffer, sizeof(buffer), \"&%s;\", item.second.c_str());\n        ret.set(key, String(buffer, CopyString));\n      }\n      if (doctype == entity_doctype::html5) {\n        for (const auto& item: *get_multicode_table()) {\n          auto codes = item.first;\n          String key = encode_as_utf8(codes.first);\n          key += encode_as_utf8(codes.second);\n\n          char buffer[32];\n          snprintf(buffer, sizeof(buffer), \"&%s\", item.second.c_str());\n          ret.set(key, String(buffer, CopyString));\n        }\n      }\n    } else {\n      const auto& entity_map = get_doctype_entity_table(doctype);\n      auto charset_table = get_charset_table(charset);\n      for (const auto& item : *charset_table) {\n        const auto iter = entity_map->find(item.second);\n        if (iter != entity_map->end()) {\n          char buffer[16];\n          snprintf(buffer, sizeof(buffer), \"&%s;\", iter->second.c_str());\n\n          auto key = String::FromChar(item.first);\n          ret.set(key, String(buffer, CopyString));\n        }\n      }\n    }\n    \/* fall thru *\/\n  }\n  case HTML_SPECIALCHARS:\n    const auto& basic_table = get_basic_table(all, doctype);\n    for (int j = 0; basic_table[j].charcode != 0; j++) {\n      const auto& item = basic_table[j];\n      if (item.flags && (flags & item.flags) == 0)\n        continue;\n\n      ret.set(String::FromChar(item.charcode), item.entity);\n    }\n    ret.set(s_amp, s_ampsemi);\n    break;\n  }\n\n  return ret;\n}\n\nString HHVM_FUNCTION(hebrev,\n                     const String& hebrew_text,\n                     int max_chars_per_line \/* = 0 *\/) {\n  if (hebrew_text.empty()) return hebrew_text;\n  return string_convert_hebrew_string(hebrew_text, max_chars_per_line, false);\n}\n\nString HHVM_FUNCTION(hebrevc,\n                     const String& hebrew_text,\n                     int max_chars_per_line \/* = 0 *\/) {\n  if (hebrew_text.empty()) return hebrew_text;\n  return string_convert_hebrew_string(hebrew_text, max_chars_per_line, true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass StringExtension final : public Extension {\npublic:\n  StringExtension() : Extension(\"string\") {}\n  void moduleInit() override {\n    setlocale(LC_CTYPE, \"\");\n\n    HHVM_FE(addcslashes);\n    HHVM_FE(stripcslashes);\n    HHVM_FE(addslashes);\n    HHVM_FE(stripslashes);\n    HHVM_FE(bin2hex);\n    HHVM_FE(hex2bin);\n    HHVM_FE(nl2br);\n    HHVM_FE(quotemeta);\n    HHVM_FE(str_shuffle);\n    HHVM_FE(strrev);\n    HHVM_FE(strtolower);\n    HHVM_FE(strtoupper);\n    HHVM_FE(ucfirst);\n    HHVM_FE(lcfirst);\n    HHVM_FE(ucwords);\n    HHVM_FE(strip_tags);\n    HHVM_FE(trim);\n    HHVM_FE(ltrim);\n    HHVM_FE(rtrim);\n    HHVM_FE(chop);\n    HHVM_FE(explode);\n    HHVM_FE(implode);\n    HHVM_FE(join);\n    HHVM_FE(str_split);\n    HHVM_FE(chunk_split);\n    HHVM_FE(strtok);\n    HHVM_FE(str_replace);\n    HHVM_FE(str_ireplace);\n    HHVM_FE(substr_replace);\n    HHVM_FE(substr);\n    HHVM_FE(str_pad);\n    HHVM_FE(str_repeat);\n    HHVM_FE(html_entity_decode);\n    HHVM_FE(htmlentities);\n    HHVM_FE(htmlspecialchars_decode);\n    HHVM_FE(htmlspecialchars);\n    HHVM_FE(fb_htmlspecialchars);\n    HHVM_FE(quoted_printable_encode);\n    HHVM_FE(quoted_printable_decode);\n    HHVM_FE(convert_uudecode);\n    HHVM_FE(convert_uuencode);\n    HHVM_FE(str_rot13);\n    HHVM_FE(crc32);\n    HHVM_FE(crypt);\n    HHVM_FE(md5);\n    HHVM_FE(sha1);\n    HHVM_FE(strtr);\n    HHVM_FE(convert_cyr_string);\n    HHVM_FE(get_html_translation_table);\n    HHVM_FE(hebrev);\n    HHVM_FE(hebrevc);\n    HHVM_FE(setlocale);\n    HHVM_FE(localeconv);\n    HHVM_FE(nl_langinfo);\n    HHVM_FE(sscanf);\n    HHVM_FE(chr);\n    HHVM_FE(ord);\n    HHVM_FE(money_format);\n    HHVM_FE(number_format);\n    HHVM_FE(strcmp);\n    HHVM_FE(strncmp);\n    HHVM_FE(strnatcmp);\n    HHVM_FE(strcasecmp);\n    HHVM_FE(strncasecmp);\n    HHVM_FE(strnatcasecmp);\n    HHVM_FE(strcoll);\n    HHVM_FE(substr_compare);\n    HHVM_FE(strchr);\n    HHVM_FE(strrchr);\n    HHVM_FE(strstr);\n    HHVM_FE(stristr);\n    HHVM_FE(strpbrk);\n    HHVM_FE(strpos);\n    HHVM_FE(stripos);\n    HHVM_FE(strrpos);\n    HHVM_FE(strripos);\n    HHVM_FE(substr_count);\n    HHVM_FE(strspn);\n    HHVM_FE(strcspn);\n    HHVM_FE(strlen);\n    HHVM_FE(str_getcsv);\n    HHVM_FE(count_chars);\n    HHVM_FE(str_word_count);\n    HHVM_FE(levenshtein);\n    HHVM_FE(similar_text);\n    HHVM_FE(soundex);\n    HHVM_FE(metaphone);\n\n    loadSystemlib();\n  }\n} s_string_extension;\n\n}\n","avg_line_length":28.3451247166,"max_line_length":97,"alphanum_fraction":0.5689188973,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":33770,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":65.0,"content":"\/*\nResembla\nhttps:\/\/github.com\/tuem\/resembla\n\nCopyright 2017 Takashi Uemura\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <memory>\n#include <unordered_map>\n#include <unordered_set>\n\n#include <simstring\/simstring.h>\n#include <paramset.hpp>\n\n#include \"resembla_util.hpp\"\n#include \"csv_reader.hpp\"\n\n#include \"measure\/asis_preprocessor.hpp\"\n#include \"measure\/pronunciation_preprocessor.hpp\"\n#include \"measure\/romaji_preprocessor.hpp\"\n\n#include \"history.hpp\"\n\nusing namespace resembla;\n\n\/\/ list of {true_text, list of {input_text, freq}}\nusing TestData = std::vector<std::pair<string_type, std::vector<std::pair<string_type, int>>>>;\n\nconstexpr auto DELIMITER = column_delimiter<string_type::value_type>();\nconstexpr char WORD_FREQ_SEPARATOR = '\/';\nconstexpr char NONE[] = \"NONE\";\n\n\/\/ generates SimString index and test data\ntemplate<typename Indexer>\nTestData prepare_data(std::string test_data_path, std::string db_path, std::string inverse_path,\n        int simstring_ngram_unit, std::shared_ptr<Indexer> index)\n{\n    std::unordered_map<string_type, std::unordered_set<string_type>> inverse;\n    TestData test_data;\n\n    simstring::ngram_generator gen(simstring_ngram_unit, false);\n    simstring::writer_base<string_type> dbw(gen, db_path);\n    bool first = true;\n    for(const auto& columns: CsvReader<>(test_data_path, 1, DELIMITER)){\n        \/\/ skip header\n        if(first){\n            first = false;\n            continue;\n        }\n\n        \/\/ format: {true}\\t{input0}\/{freq0}\\t{input1}\\t{freq1}...\n        const auto original = cast_string<string_type>(columns[0]);\n        auto indexed = (*index)(original);\n        if(inverse.count(indexed) == 0){\n            dbw.insert(indexed);\n            inverse[indexed] = {original};\n        }\n        else{\n            inverse[indexed].insert(original);\n        }\n        test_data.push_back(std::make_pair(original, std::vector<std::pair<string_type, int>>()));\n\n        for(size_t i = 1; i < columns.size(); ++i){\n            auto values = split(columns[i], WORD_FREQ_SEPARATOR);\n            auto text = cast_string<string_type>(values[0]);\n            if(text.empty()){\n                continue;\n            }\n\n            int freq = 0;\n            if(values.size() > 1){\n                freq = std::stoi(values[1]);\n            }\n\n            test_data.back().second.push_back(std::make_pair(text, freq));\n        }\n    }\n    dbw.close();\n\n    std::basic_ofstream<string_type::value_type> ofs;\n    ofs.open(inverse_path);\n    for(auto p: inverse){\n        for(auto original: p.second){\n            ofs << p.first << DELIMITER << original << std::endl;\n        }\n    }\n    return test_data;\n}\n\nint main(int argc, char* argv[])\n{\n    History history;\n    init_locale();\n\n    paramset::definitions defs = {\n        {\"resembla_measure\", STR(weighted_word_edit_distance), {\"resembla\", \"measure\"}, \"measure\", 'm', \"measure for scoring\"},\n        {\"resembla_threshold\", 0.2, {\"resembla\", \"threshold\"}, \"threshold\", 't', \"measure for scoring\"},\n        {\"resembla_max_response\", 20, {\"resembla\", \"max_response\"}, \"max-response\", 'n', \"max number of responses from Resembla\"},\n        {\"resembla_max_reranking_num\", 1000, {\"resembla\", \"max_reranking_num\"}, \"max-reranking-num\", 'r', \"max number of reranking texts in Resembla\"},\n        {\"simstring_ngram_unit\", 2, {\"simstring\", \"ngram_unit\"}, \"simstring-ngram-unit\", 'N', \"Unit of N-gram for SimString\"},\n        {\"simstring_text_preprocess\", \"asis\", {\"simstring\", \"text_preprocess\"}, \"simstring-text-preprocess\", 'P', \"preprocessing method for texts to create index\"},\n        {\"simstring_measure_str\", \"cosine\", {\"simstring\", \"measure\"}, \"simstring-measure\", 's', \"SimString measure\"},\n        {\"simstring_threshold\", 0.2, {\"simstring\", \"threshold\"}, \"simstring-threshold\", 'T', \"SimString threshold\"},\n        {\"index_romaji_mecab_options\", \"\", {\"index\", \"romaji\", \"mecab_options\"}, \"index-romaji-mecab-options\", 0, \"MeCab options for romaji indexer\"},\n        {\"index_romaji_mecab_feature_pos\", 7, {\"index\", \"romaji\", \"mecab_feature_pos\"}, \"index-romaji-mecab-feature-pos\", 0, \"Position of pronunciation in feature for romaji indexer\"},\n        {\"index_romaji_mecab_pronunciation_of_marks\", \"\", {\"index\", \"romaji\", \"mecab_pronunciation_of_marks\"}, \"index-romaji-mecab-pronunciation-of-marks\", 0, \"pronunciation in MeCab features when input is a mark\"},\n        {\"ed_simstring_ngram_unit\", -1, {\"edit_distance\", \"simstring_ngram_unit\"}, \"ed-simstring-ngram-unit\", 0, \"Unit of N-gram for input text\"},\n        {\"ed_simstring_threshold\", -1, {\"edit_distance\", \"simstring_threshold\"}, \"ed-simstring-threshold\", 0, \"SimString threshold for edit distance\"},\n        {\"ed_max_reranking_num\", -1, {\"edit_distance\", \"max_reranking_num\"}, \"ed-max-reranking-num\", 0, \"max number of reranking texts for edit distance\"},\n        {\"ed_ensemble_weight\", 0.5, {\"edit_distance\", \"ensemble_weight\"}, \"ed-ensemble-weight\", 0, \"weight coefficient for edit distance in ensemble mode\"},\n        {\"wwed_simstring_ngram_unit\", -1, {\"weighted_word_edit_distance\", \"simstring_ngram_unit\"}, \"wwed-simstring-ngram-unit\", 0, \"Unit of N-gram for input text\"},\n        {\"wwed_simstring_threshold\", -1, {\"weighted_word_edit_distance\", \"simstring_threshold\"}, \"wwed-simstring-threshold\", 0, \"SimString threshold for weighted word edit distance\"},\n        {\"wwed_max_reranking_num\", -1, {\"weighted_word_edit_distance\", \"max_reranking_num\"}, \"wwed-max-reranking-num\", 0, \"max number of reranking texts for weighted word edit distance\"},\n        {\"wwed_mecab_options\", \"\", {\"weighted_word_edit_distance\", \"mecab_options\"}, \"wwed-mecab-options\", 0, \"MeCab options for weighted word edit distance\"},\n        {\"wwed_base_weight\", 1L, {\"weighted_word_edit_distance\", \"base_weight\"}, \"wwed-base-weight\", 0, \"base weight for weighted word edit distance\"},\n        {\"wwed_delete_insert_ratio\", 10L, {\"weighted_word_edit_distance\", \"delete_insert_ratio\"}, \"wwed-del-ins-ratio\", 0, \"cost ratio of deletion and insertion for weighted word edit distance\"},\n        {\"wwed_noun_coefficient\", 10L, {\"weighted_word_edit_distance\", \"noun_coefficient\"}, \"wwed-noun-coefficient\", 0, \"coefficient of nouns for weighted word edit distance\"},\n        {\"wwed_verb_coefficient\", 10L, {\"weighted_word_edit_distance\", \"verb_coefficient\"}, \"wwed-verb-coefficient\", 0, \"coefficient of verbs for weighted word edit distance\"},\n        {\"wwed_adj_coefficient\", 5L, {\"weighted_word_edit_distance\", \"adj_coefficient\"}, \"wwed-adj-coefficient\", 0, \"coefficient of adjectives for weighted word edit distance\"},\n        {\"wwed_ensemble_weight\", 0.5, {\"weighted_word_edit_distance\", \"ensemble_weight\"}, \"wwed-ensemble-weight\", 0, \"weight coefficient for weighted word edit distance in ensemble mode\"},\n        {\"wped_simstring_ngram_unit\", -1, {\"weighted_pronunciation_edit_distance\", \"simstring_ngram_unit\"}, \"wped-simstring-ngram-unit\", 0, \"Unit of N-gram for pronunciation of input text\"},\n        {\"wped_simstring_threshold\", -1, {\"weighted_pronunciation_edit_distance\", \"simstring_threshold\"}, \"wped-simstring-threshold\", 0, \"SimString threshold for weighted pronunciation edit distance\"},\n        {\"wped_max_reranking_num\", -1, {\"weighted_pronunciation_edit_distance\", \"max_reranking_num\"}, \"wped-max-reranking-num\", 0, \"max number of reranking texts for weighted pronunciation edit distance\"},\n        {\"wped_mecab_options\", \"\", {\"weighted_pronunciation_edit_distance\", \"mecab_options\"}, \"wped-mecab-options\", 0, \"MeCab options for weighted pronunciation edit distance\"},\n        {\"wped_mecab_feature_pos\", 7, {\"weighted_pronunciation_edit_distance\", \"mecab_feature_pos\"}, \"wped-mecab-feature-pos\", 0, \"Position of pronunciation in feature for weighted pronunciation edit distance\"},\n        {\"wped_mecab_pronunciation_of_marks\", \"\", {\"weighted_pronunciation_edit_distance\", \"mecab_pronunciation_of_marks\"}, \"wped-mecab-pronunciation-of-marks\", 0, \"pronunciation in MeCab features when input is a mark\"},\n        {\"wped_base_weight\", 1L, {\"weighted_pronunciation_edit_distance\", \"base_weight\"}, \"wped-base-weight\", 0, \"base weight for weighted pronunciation edit distance\"},\n        {\"wped_delete_insert_ratio\", 10L, {\"weighted_pronunciation_edit_distance\", \"delete_insert_ratio\"}, \"wped-del-ins-ratio\", 0, \"cost ratio of deletion and insertion for weighted pronunciation edit distance\"},\n        {\"wped_letter_weight_path\", \"\", {\"weighted_pronunciation_edit_distance\", \"letter_weight_path\"}, \"wped-letter-weight-path\", 0, \"weights of kana letters for weighted pronunciation edit distance\"},\n        {\"wped_mismatch_cost_path\", \"\", {\"weighted_pronunciation_edit_distance\", \"mismatch_cost_path\"}, \"wped-mismatch-cost-path\", 0, \"costs to replace similar letters for weighted pronunciation edit distance\"},\n        {\"wped_ensemble_weight\", 0.5, {\"weighted_pronunciation_edit_distance\", \"ensemble_weight\"}, \"wped-ensemble-weight\", 0, \"weight coefficient for weighted pronunciation edit distance in ensemble mode\"},\n        {\"wred_simstring_ngram_unit\", -1, {\"weighted_romaji_edit_distance\", \"simstring_ngram_unit\"}, \"wred-simstring-ngram-unit\", 0, \"Unit of N-gram for romaji notation of input text\"},\n        {\"wred_simstring_threshold\", -1, {\"weighted_romaji_edit_distance\", \"simstring_threshold\"}, \"wred-simstring-threshold\", 0, \"SimString threshold for weighted romaji edit distance\"},\n        {\"wred_max_reranking_num\", -1, {\"weighted_romaji_edit_distance\", \"max_reranking_num\"}, \"wred-max-reranking-num\", 0, \"max number of reranking texts for weighted romaji edit distance\"},\n        {\"wred_mecab_options\", \"\", {\"weighted_romaji_edit_distance\", \"mecab_options\"}, \"wred-mecab-options\", 0, \"MeCab options for weighted romaji edit distance\"},\n        {\"wred_mecab_feature_pos\", 7, {\"weighted_romaji_edit_distance\", \"mecab_feature_pos\"}, \"wred-mecab-feature-pos\", 0, \"Position of pronunciation in feature for weighted romaji edit distance\"},\n        {\"wred_mecab_pronunciation_of_marks\", \"\", {\"weighted_romaji_edit_distance\", \"mecab_pronunciation_of_marks\"}, \"wred-mecab-pronunciation-of-marks\", 0, \"pronunciation in MeCab features when input is a mark\"},\n        {\"wred_base_weight\", 1L, {\"weighted_romaji_edit_distance\", \"base_weight\"}, \"wred-base-weight\", 0, \"base weight for weighted romaji edit distance\"},\n        {\"wred_delete_insert_ratio\", 10L, {\"weighted_romaji_edit_distance\", \"delete_insert_ratio\"}, \"wred-del-ins-ratio\", 0, \"cost ratio of deletion and insertion for weighted romaji edit distance\"},\n        {\"wred_uppercase_coefficient\", 1L, {\"weighted_romaji_edit_distance\", \"uppercase_coefficient\"}, \"wred-uppercase-coefficient\", 0, \"coefficient for uppercase letters for weighted romaji edit distance\"},\n        {\"wred_lowercase_coefficient\", 1L, {\"weighted_romaji_edit_distance\", \"lowercase_coefficient\"}, \"wred-lowercase-coefficient\", 0, \"coefficient for lowercase letters for weighted romaji edit distance\"},\n        {\"wred_vowel_coefficient\", 1L, {\"weighted_romaji_edit_distance\", \"vowel_coefficient\"}, \"wred-vowel-coefficient\", 0, \"coefficient for vowels for weighted romaji edit distance\"},\n        {\"wred_consonant_coefficient\", 1L, {\"weighted_romaji_edit_distance\", \"consonant_coefficient\"}, \"wred-consonant-coefficient\", 0, \"coefficient for consonants for weighted romaji edit distance\"},\n        {\"wred_case_mismatch_cost\", 1L, {\"weighted_romaji_edit_distance\", \"case_mismatch_cost\"}, \"wred-case-mismatch-cost\", 0, \"cost to replace case mismatches for weighted romaji edit distance\"},\n        {\"wred_similar_letter_cost\", 1L, {\"weighted_romaji_edit_distance\", \"similar_letter_cost\"}, \"wred-similar-letter-cost\", 0, \"cost to replace similar letters for weighted romaji edit distance\"},\n        {\"wred_mismatch_cost_path\", \"\", {\"weighted_romaji_edit_distance\", \"mismatch_cost_path\"}, \"wred-mismatch-cost-path\", 0, \"costs to replace similar letters for weighted romaji edit distance\"},\n        {\"wred_ensemble_weight\", 0.5, {\"weighted_romaji_edit_distance\", \"ensemble_weight\"}, \"wred-ensemble-weight\", 0, \"weight coefficient for weighted romaji edit distance in ensemble mode\"},\n        {\"km_simstring_ngram_unit\", -1, {\"keyword_match\", \"simstring_ngram_unit\"}, \"km-simstring-ngram-unit\", 0, \"Unit of N-gram for input text\"},\n        {\"km_simstring_threshold\", -1, {\"keyword_match\", \"simstring_threshold\"}, \"km-simstring-threshold\", 0, \"SimString threshold for keyword match\"},\n        {\"km_max_reranking_num\", -1, {\"keyword_match\", \"max_reranking_num\"}, \"km-max-reranking-num\", 0, \"max number of reranking texts for keyword match\"},\n        {\"km_ensemble_weight\", 0.2, {\"keyword_match\", \"ensemble_weight\"}, \"km-ensemble-weight\", 0, \"weight coefficient for keyword match in ensemble mode\"},\n        {\"ensemble_simstring_ngram_unit\", -1, {\"ensemble\", \"simstring_ngram_unit\"}, \"ensemble-simstring-ngram-unit\", 0, \"Unit of N-gram for romaji notation of input text\"},\n        {\"ensemble_simstring_threshold\", -1, {\"ensemble\", \"simstring_threshold\"}, \"ensemble-simstring-threshold\", 0, \"SimString threshold for ensemble\"},\n        {\"ensemble_max_candidate\", 100, {\"ensemble\", \"max_candidate\"}, \"ensemble-max-candidate\", 0, \"max number of candidates for ensemble method\"},\n        {\"svr_simstring_ngram_unit\", -1, {\"svr\", \"simstring_ngram_unit\"}, \"svr-simstring-ngram-unit\", 0, \"Unit of N-gram for input text\"},\n        {\"svr_simstring_threshold\", -1, {\"svr\", \"simstring_threshold\"}, \"svr-simstring-threshold\", 0, \"SimString threshold for svr\"},\n        {\"svr_max_candidate\", 2000, {\"svr\", \"max_candidate\"}, \"svr-max-candidate\", 0, \"max number of candidates for support vector regression\"},\n        {\"svr_features_path\", \"features.tsv\", {\"svr\", \"features_path\"}, \"svr-features-path\", 0, \"feature definition file for support vector regression\"},\n        {\"svr_patterns_home\", \".\", {\"svr\", \"patterns_home\"}, \"svr-patterns-home\", 0, \"directory for pattern files for regular expression-based feature extractors\"},\n        {\"svr_model_path\", \"model\", {\"svr\", \"model_path\"}, \"svr-model-path\", 0, \"LibSVM model file\"},\n        {\"svr_features_col\", 2, {\"svr\", \"features_col\"}, \"svr-features-col\", 0, \"column number of features for support vector regression\"},\n        {\"corpus_path\", \"\", {\"common\", \"corpus_path\"}},\n        {\"id_col\", 0, {\"common\", \"id_col\"}, \"id-col\", 0, \"column number (starts with 1) of ID in corpus rows. ignored if id_col==0\"},\n        {\"text_col\", 1, {\"common\", \"text_col\"}, \"text-col\", 0, \"column mumber of text in corpus rows\"},\n        {\"features_col\", 2, {\"common\", \"features_col\"}, \"features-col\", 0, \"column number of features in corpus rows\"},\n        {\"conf_path\", \"\", \"config\", 'c', \"config file path\"}\n    };\n    paramset::manager pm(defs);\n    try{\n        pm.load(argc, argv, \"config\");\n\n        if(pm.rest.size() > 0){\n            pm[\"corpus_path\"] = pm.rest.front().as<std::string>();\n        }\n        if(pm.get<std::string>(\"corpus_path\").empty()){\n            throw std::invalid_argument(\"no corpus file specified\");\n        }\n        std::string corpus_path = pm.get<std::string>(\"corpus_path\");\n\n        int resembla_max_response = pm.get<int>(\"resembla_max_response\");\n        double resembla_threshold = pm.get<double>(\"resembla_threshold\");\n        auto resembla_measures = split_to_resembla_measures(pm[\"resembla_measure\"]);\n        int ensemble_count = 0;\n        for(auto resembla_measure: resembla_measures){\n            switch(resembla_measure){\n                case edit_distance:\n                case weighted_word_edit_distance:\n                case weighted_pronunciation_edit_distance:\n                case weighted_romaji_edit_distance:\n                case keyword_match:\n                    ++ensemble_count;\n                    break;\n                default:\n                    break;\n            }\n        }\n        bool use_ensemble = ensemble_count > 1;\n\n        pm[\"simstring_measure\"] = simstring_measure_from_string(pm.get<std::string>(\"simstring_measure_str\"));\n\n        if(pm.get<int>(\"ed_simstring_ngram_unit\") == -1){\n            pm[\"ed_simstring_ngram_unit\"] = pm.get<int>(\"simstring_ngram_unit\");\n        }\n        if(pm.get<int>(\"wwed_simstring_ngram_unit\") == -1){\n            pm[\"wwed_simstring_ngram_unit\"] = pm.get<int>(\"simstring_ngram_unit\");\n        }\n        if(pm.get<int>(\"wped_simstring_ngram_unit\") == -1){\n            pm[\"wped_simstring_ngram_unit\"] = pm.get<int>(\"simstring_ngram_unit\");\n        }\n        if(pm.get<int>(\"wred_simstring_ngram_unit\") == -1){\n            pm[\"wred_simstring_ngram_unit\"] = pm.get<int>(\"simstring_ngram_unit\");\n        }\n        if(pm.get<int>(\"km_simstring_ngram_unit\") == -1){\n            pm[\"km_simstring_ngram_unit\"] = pm.get<int>(\"simstring_ngram_unit\");\n        }\n        if(pm.get<int>(\"ensemble_simstring_ngram_unit\") == -1){\n            pm[\"ensemble_simstring_ngram_unit\"] = pm.get<int>(\"simstring_ngram_unit\");\n        }\n        if(pm.get<int>(\"svr_simstring_ngram_unit\") == -1){\n            pm[\"svr_simstring_ngram_unit\"] = pm.get<int>(\"simstring_ngram_unit\");\n        }\n\n        if(pm.get<double>(\"ed_simstring_threshold\") == -1){\n            pm[\"ed_simstring_threshold\"] = pm.get<double>(\"simstring_threshold\");\n        }\n        if(pm.get<double>(\"wwed_simstring_threshold\") == -1){\n            pm[\"wwed_simstring_threshold\"] = pm.get<double>(\"simstring_threshold\");\n        }\n        if(pm.get<double>(\"wped_simstring_threshold\") == -1){\n            pm[\"wped_simstring_threshold\"] = pm.get<double>(\"simstring_threshold\");\n        }\n        if(pm.get<double>(\"wred_simstring_threshold\") == -1){\n            pm[\"wred_simstring_threshold\"] = pm.get<double>(\"simstring_threshold\");\n        }\n        if(pm.get<double>(\"km_simstring_threshold\") == -1){\n            pm[\"km_simstring_threshold\"] = pm.get<double>(\"simstring_threshold\");\n        }\n        if(pm.get<double>(\"ensemble_simstring_threshold\") == -1){\n            pm[\"ensemble_simstring_threshold\"] = pm.get<double>(\"simstring_threshold\");\n        }\n        if(pm.get<double>(\"svr_simstring_threshold\") == -1){\n            pm[\"svr_simstring_threshold\"] = pm.get<double>(\"simstring_threshold\");\n        }\n\n        if(pm.get<int>(\"ed_max_reranking_num\") == -1){\n            pm[\"ed_max_reranking_num\"] = pm.get<int>(\"resembla_max_reranking_num\");\n        }\n        if(pm.get<int>(\"wwed_max_reranking_num\") == -1){\n            pm[\"wwed_max_reranking_num\"] = pm.get<int>(\"resembla_max_reranking_num\");\n        }\n        if(pm.get<int>(\"wped_max_reranking_num\") == -1){\n            pm[\"wped_max_reranking_num\"] = pm.get<int>(\"resembla_max_reranking_num\");\n        }\n        if(pm.get<int>(\"wred_max_reranking_num\") == -1){\n            pm[\"wred_max_reranking_num\"] = pm.get<int>(\"resembla_max_reranking_num\");\n        }\n        if(pm.get<int>(\"km_max_reranking_num\") == -1){\n            pm[\"km_max_reranking_num\"] = pm.get<int>(\"resembla_max_reranking_num\");\n        }\n\n        std::cerr << \"  Common:\" << std::endl;\n        std::cerr << \"    corpus_path=\" << corpus_path << std::endl;\n        std::cerr << \"  SimString:\" << std::endl;\n        std::cerr << \"    ngram_unit=\" << pm.get<int>(\"simstring_ngram_unit\") << std::endl;\n        std::cerr << \"    measure=\" << pm.get<std::string>(\"simstring_measure_str\") << std::endl;\n        std::cerr << \"    threshold=\" << pm.get<double>(\"simstring_threshold\") << std::endl;\n        std::cerr << \"  Resembla:\" << std::endl;\n        std::cerr << \"    measure=\" << pm.get<std::string>(\"resembla_measure\") << std::endl;\n        std::cerr << \"    threshold=\" << pm.get<double>(\"resembla_threshold\") << std::endl;\n        std::cerr << \"    max_reranking_num=\" << pm.get<int>(\"resembla_max_reranking_num\") << std::endl;\n        std::cerr << \"    max_response=\" << pm.get<int>(\"resembla_max_response\") << std::endl;\n        if(use_ensemble){\n            std::cerr << \"  measure=\" << STR(ensemble) << std::endl;\n            std::cerr << \"    simstring_ngram_unit=\" << pm.get<int>(\"ensemble_simstring_ngram_unit\") << std::endl;\n            std::cerr << \"    simstring_threshold=\" << pm.get<int>(\"ensemble_simstring_threshold\") << std::endl;\n            std::cerr << \"    max_candidate=\" << pm.get<int>(\"ensemble_max_candidate\") << std::endl;\n        }\n        for(const auto& resembla_measure: resembla_measures){\n            if(resembla_measure == edit_distance && pm.get<double>(\"ed_ensemble_weight\") > 0){\n                std::cerr << \"  Edit distance:\" << std::endl;\n                std::cerr << \"    simstring_ngram_unit=\" << pm.get<int>(\"ed_simstring_ngram_unit\") << std::endl;\n                std::cerr << \"    simstring_threshold=\" << pm.get<double>(\"ed_simstring_threshold\") << std::endl;\n                std::cerr << \"    max_reranking_num=\" << pm.get<int>(\"ed_max_reranking_num\") << std::endl;\n                std::cerr << \"    ensemble_weight=\" << pm.get<double>(\"ed_ensemble_weight\") << std::endl;\n            }\n            if(resembla_measure == weighted_word_edit_distance && pm.get<double>(\"wwed_ensemble_weight\") > 0){\n                std::cerr << \"  Weighted word edit distance:\" << std::endl;\n                std::cerr << \"    simstring_ngram_unit=\" << pm.get<int>(\"wwed_simstring_ngram_unit\") << std::endl;\n                std::cerr << \"    simstring_threshold=\" << pm.get<double>(\"wwed_simstring_threshold\") << std::endl;\n                std::cerr << \"    max_reranking_num=\" << pm.get<int>(\"wwed_max_reranking_num\") << std::endl;\n                std::cerr << \"    mecab_options=\" << pm.get<std::string>(\"wwed_mecab_options\") << std::endl;\n                std::cerr << \"    base_weight=\" << pm.get<double>(\"wwed_base_weight\") << std::endl;\n                std::cerr << \"    delete_insert_ratio=\" << pm.get<double>(\"wwed_delete_insert_ratio\") << std::endl;\n                std::cerr << \"    noun_coefficient=\" << pm.get<double>(\"wwed_noun_coefficient\") << std::endl;\n                std::cerr << \"    verb_coefficient=\" << pm.get<double>(\"wwed_verb_coefficient\") << std::endl;\n                std::cerr << \"    adj_coefficient=\" << pm.get<double>(\"wwed_adj_coefficient\") << std::endl;\n                std::cerr << \"    ensemble_weight=\" << pm.get<double>(\"wwed_ensemble_weight\") << std::endl;\n            }\n            else if(resembla_measure == weighted_pronunciation_edit_distance && pm.get<double>(\"wped_ensemble_weight\") > 0){\n                std::cerr << \"  Weighted pronunciation edit distance:\" << std::endl;\n                std::cerr << \"    simstring_ngram_unit=\" << pm.get<int>(\"wped_simstring_ngram_unit\") << std::endl;\n                std::cerr << \"    simstring_threshold=\" << pm.get<double>(\"wped_simstring_threshold\") << std::endl;\n                std::cerr << \"    max_reranking_num=\" << pm.get<int>(\"wped_max_reranking_num\") << std::endl;\n                std::cerr << \"    mecab_options=\" << pm.get<std::string>(\"wped_mecab_options\") << std::endl;\n                std::cerr << \"    mecab_feature_pos=\" << pm.get<int>(\"wped_mecab_feature_pos\") << std::endl;\n                std::cerr << \"    mecab_pronunciation_of_marks=\" << pm.get<std::string>(\"wped_mecab_pronunciation_of_marks\") << std::endl;\n                std::cerr << \"    base_weight=\" << pm.get<double>(\"wped_base_weight\") << std::endl;\n                std::cerr << \"    delete_insert_ratio=\" << pm.get<double>(\"wped_delete_insert_ratio\") << std::endl;\n                std::cerr << \"    letter_weight_path=\" << pm.get<std::string>(\"wped_letter_weight_path\") << std::endl;\n                std::cerr << \"    mismatch_cost_path=\" << pm.get<std::string>(\"wped_mismatch_cost_path\") << std::endl;\n                std::cerr << \"    ensemble_weight=\" << pm.get<double>(\"wped_ensemble_weight\") << std::endl;\n            }\n            else if(resembla_measure == weighted_romaji_edit_distance && pm.get<double>(\"wred_ensemble_weight\") > 0){\n                std::cerr << \"  Weighted romaji edit distance:\" << std::endl;\n                std::cerr << \"    simstring_ngram_unit=\" << pm.get<int>(\"wred_simstring_ngram_unit\") << std::endl;\n                std::cerr << \"    simstring_threshold=\" << pm.get<double>(\"wred_simstring_threshold\") << std::endl;\n                std::cerr << \"    max_reranking_num=\" << pm.get<int>(\"wred_max_reranking_num\") << std::endl;\n                std::cerr << \"    mecab_options=\" << pm.get<std::string>(\"wred_mecab_options\") << std::endl;\n                std::cerr << \"    mecab_feature_pos=\" << pm.get<int>(\"wred_mecab_feature_pos\") << std::endl;\n                std::cerr << \"    mecab_pronunciation_of_marks=\" << pm.get<std::string>(\"wred_mecab_pronunciation_of_marks\") << std::endl;\n                std::cerr << \"    base_weight=\" << pm.get<double>(\"wred_base_weight\") << std::endl;\n                std::cerr << \"    delete_insert_ratio=\" << pm.get<double>(\"wred_delete_insert_ratio\") << std::endl;\n                std::cerr << \"    uppercase_coefficient=\" << pm.get<double>(\"wred_uppercase_coefficient\") << std::endl;\n                std::cerr << \"    lowercase_coefficient=\" << pm.get<double>(\"wred_lowercase_coefficient\") << std::endl;\n                std::cerr << \"    vowel_coefficient=\" << pm.get<double>(\"wred_vowel_coefficient\") << std::endl;\n                std::cerr << \"    consonant_coefficient=\" << pm.get<double>(\"wred_consonant_coefficient\") << std::endl;\n                std::cerr << \"    case_mismatch_cost=\" << pm.get<double>(\"wred_case_mismatch_cost\") << std::endl;\n                std::cerr << \"    similar_letter_cost=\" << pm.get<double>(\"wred_similar_letter_cost\") << std::endl;\n                std::cerr << \"    mismatch_cost_path=\" << pm.get<std::string>(\"wred_mismatch_cost_path\") << std::endl;\n                std::cerr << \"    ensemble_weight=\" << pm.get<double>(\"wred_ensemble_weight\") << std::endl;\n            }\n            else if(resembla_measure == keyword_match && pm.get<double>(\"km_ensemble_weight\") > 0){\n                std::cerr << \"  Keyword matching:\" << std::endl;\n                std::cerr << \"    simstring_ngram_unit=\" << pm.get<int>(\"km_simstring_ngram_unit\") << std::endl;\n                std::cerr << \"    simstring_threshold=\" << pm.get<double>(\"km_simstring_threshold\") << std::endl;\n                std::cerr << \"    max_reranking_num=\" << pm.get<int>(\"km_max_reranking_num\") << std::endl;\n            }\n            else if(resembla_measure == svr){\n                std::cerr << \"  SVR:\" << std::endl;\n                std::cerr << \"    simstring_ngram_unit=\" << pm.get<int>(\"svr_simstring_ngram_unit\") << std::endl;\n                std::cerr << \"    simstring_threshold=\" << pm.get<double>(\"svr_simstring_threshold\") << std::endl;\n                std::cerr << \"    max_candidate=\" << pm.get<int>(\"svr_max_candidate\") << std::endl;\n                std::cerr << \"    features_path=\" << pm.get<std::string>(\"svr_features_path\") << std::endl;\n                std::cerr << \"    patterns_home=\" << pm.get<std::string>(\"svr_patterns_home\") << std::endl;\n                std::cerr << \"    model_path=\" << pm.get<std::string>(\"svr_model_path\") << std::endl;\n            }\n        }\n        history.record(\"config\");\n\n        \/\/ load test data and create index for each measure\n        TestData test_data;\n        for(const auto& resembla_measure: resembla_measures){\n            std::string db_path = db_path_from_resembla_measure(corpus_path, resembla_measure);\n            std::string inverse_path = inverse_path_from_resembla_measure(corpus_path, resembla_measure);\n            switch(resembla_measure){\n                case svr: {\n                    auto indexer = std::make_shared<RomajiPreprocessor>(pm.get<std::string>(\"index_romaji_mecab_options\"),\n                            pm.get<int>(\"index_romaji_mecab_feature_pos\"), pm.get<std::string>(\"index_romaji_mecab_pronunciation_of_marks\"));\n                    test_data = prepare_data(corpus_path, db_path, inverse_path, pm.get<int>(\"svr_simstring_ngram_unit\"), indexer);\n\n                    break;\n                }\n                case edit_distance: {\n                    if(pm.get<double>(\"ed_ensemble_weight\") > 0){\n                        auto indexer = std::make_shared<AsIsPreprocessor<string_type>>();\n                        test_data = prepare_data(corpus_path, db_path, inverse_path, pm.get<int>(\"ed_simstring_ngram_unit\"), indexer);\n                    }\n                    break;\n                }\n                case weighted_word_edit_distance: {\n                    if(pm.get<double>(\"wwed_ensemble_weight\") > 0){\n                        auto indexer = std::make_shared<AsIsPreprocessor<string_type>>();\n                        test_data = prepare_data(corpus_path, db_path, inverse_path, pm.get<int>(\"wwed_simstring_ngram_unit\"), indexer);\n                    }\n                    break;\n                }\n                case weighted_pronunciation_edit_distance: {\n                    if(pm.get<double>(\"wped_ensemble_weight\") > 0){\n                        auto indexer = std::make_shared<PronunciationPreprocessor>(pm.get<std::string>(\"wped_mecab_options\"),\n                            pm.get<int>(\"wped_mecab_feature_pos\"), pm.get<std::string>(\"wped_mecab_pronunciation_of_marks\"));\n                        test_data = prepare_data(corpus_path, db_path, inverse_path, pm.get<int>(\"wped_simstring_ngram_unit\"), indexer);\n                    }\n                    break;\n                }\n                case weighted_romaji_edit_distance: {\n                    if(pm.get<double>(\"wred_ensemble_weight\") > 0){\n                        auto indexer = std::make_shared<RomajiPreprocessor>(pm.get<std::string>(\"wred_mecab_options\"),\n                            pm.get<int>(\"wred_mecab_feature_pos\"), pm.get<std::string>(\"wred_mecab_pronunciation_of_marks\"));\n                        test_data = prepare_data(corpus_path, db_path, inverse_path, pm.get<int>(\"wred_simstring_ngram_unit\"), indexer);\n                    }\n                    break;\n                }\n                case keyword_match: {\n                    if(pm.get<double>(\"km_ensemble_weight\") > 0){\n                        auto indexer = std::make_shared<AsIsPreprocessor<string_type>>();\n                        test_data = prepare_data(corpus_path, db_path, inverse_path, pm.get<int>(\"km_simstring_ngram_unit\"), indexer);\n                    }\n                    break;\n                }\n                default:\n                    break;\n            }\n        }\n\n        if(use_ensemble){\n            std::string db_path = db_path_from_resembla_measure(corpus_path, ensemble);\n            std::string inverse_path = inverse_path_from_resembla_measure(corpus_path, ensemble);\n\n            auto indexer = std::make_shared<RomajiPreprocessor>(pm.get<std::string>(\"index_romaji_mecab_options\"),\n                pm.get<int>(\"index_romaji_mecab_feature_pos\"),\n                pm.get<std::string>(\"index_romaji_mecab_pronunciation_of_marks\"));\n            test_data = prepare_data(corpus_path, db_path, inverse_path, pm.get<int>(\"ensemble_simstring_ngram_unit\"), indexer);\n        }\n\n        if(test_data.empty()){\n            throw std::invalid_argument(\"no data for evaluation\");\n        }\n        history.record(\"index\");\n\n        \/\/ initialize Resembla with created indexes\n        auto resembla = construct_resembla(pm);\n        history.record(\"load\");\n\n        \/\/ execute evaluation\n        std::vector<std::vector<ResemblaInterface::output_type>> answers;\n        for(const auto& d: test_data){\n            for(const auto& i: d.second){\n                answers.push_back(resembla->find(i.first, resembla_threshold, resembla_max_response));\n            }\n        }\n        history.record(\"answer\");\n\n        \/\/ output results\n        auto it = std::begin(answers);\n        std::cout <<\n            \"freq\" << \"\\t\"<<\n            \"input\" << \"\\t\" <<\n            \"pred\" << \"\\t\" <<\n            \"true\" << \"\\t\" <<\n            \"score\" << \"\\t\" <<\n            \"score_of_correct_answer\" << \"\\t\" <<\n            \"rank_of_correct_answer\" << std::endl;\n        for(const auto& d: test_data){\n            const auto& original = d.first;\n            for(const auto& i: d.second){\n                const auto query = cast_string<std::string>(i.first);\n                const auto& freq = i.second;\n\n                auto response = *it++;\n\n                auto best = !response.empty() ? cast_string<std::string>(response[0].text) : NONE;\n                double score_best = !response.empty() ? response[0].score : -1;\n                auto p = std::find_if(std::begin(response), std::end(response),\n                        [original](ResemblaInterface::output_type& r) -> bool {return original == r.text;});\n                int rank_correct = p != std::end(response) ? p - std::begin(response) + 1 : -1;\n                double score_correct = rank_correct != -1 ? response[rank_correct - 1].score : -1;\n\n                std::cout <<\n                    freq << \"\\t\" <<\n                    query << \"\\t\" <<\n                    best << \"\\t\" <<\n                    cast_string<std::string>(original) << \"\\t\" <<\n                    score_best << \"\\t\" <<\n                    score_correct << \"\\t\" <<\n                    rank_correct << std::endl;\n            }\n        }\n        history.record(\"output\");\n\n        history.dump(std::cerr);\n    }\n    catch(const std::exception& e){\n        std::cerr << \"error: \" << e.what() << std::endl;\n        exit(1);\n    }\n\n    return 0;\n}\n","avg_line_length":68.3603238866,"max_line_length":220,"alphanum_fraction":0.6274207877,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4387,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\ufeff\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the Siv3D Engine.\n\/\/\n\/\/\tCopyright (c) 2008-2018 Ryo Suzuki\n\/\/\tCopyright (c) 2016-2018 OpenSiv3D Project\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# include \"..\/Siv3DEngine.hpp\"\n# include \"ITextInput.hpp\"\n# include <Siv3D\/TextInput.hpp>\n# include <Siv3D\/Window.hpp>\n# include <Siv3D\/Font.hpp>\n# include <Siv3D\/Indexed.hpp>\n# include <Siv3D\/Logger.hpp>\n\nnamespace s3d\n{\n\tnamespace TextInput\n\t{\n\t\tString GetRawInput()\n\t\t{\n\t\t\treturn Siv3DEngine::GetTextInput()->getChars();\n\t\t}\n\t\t\n\t\tsize_t UpdateText(String& text, size_t cursorPos, const TextInputMode mode)\n\t\t{\n\t\t\tconst String chars = Siv3DEngine::GetTextInput()->getChars();\n\t\t\t\n\t\t\tif (chars.empty())\n\t\t\t{\n\t\t\t\treturn cursorPos;\n\t\t\t}\n\t\t\t\n\t\t\tconst bool allowEnter = static_cast<uint32>(mode) & static_cast<uint32>(TextInputMode::AllowEnter);\n\t\t\tconst bool allowTab = static_cast<uint32>(mode) & static_cast<uint32>(TextInputMode::AllowTab);\n\t\t\tconst bool allowBackSpace = static_cast<uint32>(mode) & static_cast<uint32>(TextInputMode::AllowBackSpace);\n\t\t\tconst bool allowDelete = static_cast<uint32>(mode) & static_cast<uint32>(TextInputMode::AllowDelete);\n\n\t\t\tif (text.size() < cursorPos)\n\t\t\t{\n\t\t\t\tcursorPos = text.size();\n\t\t\t}\n\t\t\t\n\t\t\tfor (auto const ch : chars)\n\t\t\t{\n\t\t\t\tif (ch == U'\\r')\n\t\t\t\t{\n\t\t\t\t\tif (allowEnter)\n\t\t\t\t\t{\n\t\t\t\t\t\ttext.insert(text.begin() + cursorPos, U'\\n');\n\t\t\t\t\t\t++cursorPos;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (ch == U'\\b')\n\t\t\t\t{\n\t\t\t\t\tif (allowBackSpace && 0 < cursorPos)\n\t\t\t\t\t{\n\t\t\t\t\t\ttext.erase(text.begin() + cursorPos - 1);\n\t\t\t\t\t\t--cursorPos;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (ch == U'\\t')\n\t\t\t\t{\n\t\t\t\t\tif (allowTab)\n\t\t\t\t\t{\n\t\t\t\t\t\ttext.insert(text.begin() + cursorPos, U'\\t');\n\t\t\t\t\t\t++cursorPos;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (ch == char32(0x7F))\n\t\t\t\t{\n\t\t\t\t\tif (allowDelete && cursorPos < text.size())\n\t\t\t\t\t{\n\t\t\t\t\t\ttext.erase(text.begin() + cursorPos);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (!IsControl(ch))\n\t\t\t\t{\n\t\t\t\t\ttext.insert(text.begin() + cursorPos, ch);\n\t\t\t\t\t++cursorPos;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn cursorPos;\n\t\t}\n\t\t\n\t\tString GetEditingText()\n\t\t{\n\t\t\treturn Siv3DEngine::GetTextInput()->getEditingText();\n\t\t}\n\t}\n\n# if defined(SIV3D_TARGET_WINDOWS)\n\n\tnamespace win::TextInput\n\t{\n\t\tvoid DisableIME()\n\t\t{\n\t\t\tSiv3DEngine::GetTextInput()->enableIME(false);\n\t\t}\n\n\t\tconst Array<String>& GetCandidates()\n\t\t{\n\t\t\treturn Siv3DEngine::GetTextInput()->getCandidates();\n\t\t}\n\n\t\tstd::pair<int32, int32> GetCursorIndex()\n\t\t{\n\t\t\treturn Siv3DEngine::GetTextInput()->getCursorIndex();\n\t\t}\n\n\t\tvoid DrawCandidateWindow(const Font& font,\n\t\t\tconst Vec2& basePos,\n\t\t\tconst ColorF& boxColor,\n\t\t\tconst ColorF& selectedBackgroundColor,\n\t\t\tconst ColorF& frameColor,\n\t\t\tconst ColorF& textColor)\n\t\t{\n\t\t\tconst double candidatesMargin = 4.0;\n\t\t\tconst String editingText = s3d::TextInput::GetEditingText();\n\t\t\tconst auto[editingCursorIndex, editingTargetlength] = win::TextInput::GetCursorIndex();\n\t\t\tconst bool hasEditingTarget = (editingTargetlength > 0);\n\t\t\tconst String editingTargetText = editingText.substr(editingCursorIndex, editingTargetlength);\n\t\t\tconst auto cadidates = win::TextInput::GetCandidates();\n\t\t\tconst double candidateItemHeight = font.height() + candidatesMargin;\n\n\t\t\tdouble boxWidth = 0.0;\n\n\t\t\tfor (const auto& canditate : cadidates)\n\t\t\t{\n\t\t\t\tboxWidth = Max<double>(boxWidth, font(canditate).region().w);\n\t\t\t}\n\n\t\t\tconst double leftOffset = hasEditingTarget ? font(U\"1  \").region().w : 0.0;\n\t\t\tconst Vec2 boxPos(Clamp(basePos.x - leftOffset, 7.0, Window::Width() - boxWidth - leftOffset - 12.0), basePos.y);\n\n\t\t\tboxWidth += leftOffset + 5;\n\n\t\t\tif (cadidates)\n\t\t\t{\n\t\t\t\tRectF(boxPos, boxWidth, candidateItemHeight * cadidates.size()).stretched(5, 0)\n\t\t\t\t\t.draw(boxColor).drawFrame(1, 0, frameColor);\n\t\t\t}\n\n\t\t\tfor (auto[i, text] : Indexed(cadidates))\n\t\t\t{\n\t\t\t\tbool selected = false;\n\n\t\t\t\tif (editingTargetText == text)\n\t\t\t\t{\n\t\t\t\t\tselected = true;\n\n\t\t\t\t\tRectF(boxPos.x, boxPos.y + i * candidateItemHeight, boxWidth, candidateItemHeight)\n\t\t\t\t\t\t.stretched(5, 0).draw(selectedBackgroundColor);\n\t\t\t\t}\n\n\t\t\t\tif (text)\n\t\t\t\t{\n\t\t\t\t\tconst Vec2 posNumber(boxPos.x, boxPos.y + i * candidateItemHeight + (candidatesMargin) \/ 2);\n\t\t\t\t\tconst Vec2 posLabel(posNumber.x + leftOffset, posNumber.y);\n\n\t\t\t\t\tif (hasEditingTarget)\n\t\t\t\t\t{\n\t\t\t\t\t\tfont(i + 1).draw(posNumber, textColor);\n\t\t\t\t\t}\n\n\t\t\t\t\tfont(text).draw(posLabel, textColor);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n# endif\n}\n","avg_line_length":24.5083798883,"max_line_length":116,"alphanum_fraction":0.6304992022,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":12062,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":2.0,"content":"\/\/ Copyright (c) 2012-2016, The CryptoNote developers, The Bytecoin developers\n\/\/\n\/\/ This file is part of DCRS.\n\/\/\n\/\/ DCRS is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ DCRS is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with DCRS.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"gtest\/gtest.h\"\n\n#include \"Transfers\/BlockchainSynchronizer.h\"\n#include \"Transfers\/TransfersSynchronizer.h\"\n\n#include \"INodeStubs.h\"\n#include \"TestBlockchainGenerator.h\"\n#include \"TransactionApiHelpers.h\"\n#include \"CryptoNoteCore\/TransactionApi.h\"\n\n#include <boost\/scoped_array.hpp>\n\n#include <future>\n#include <algorithm>\n\n#include <Logging\/ConsoleLogger.h>\n\nusing namespace CryptoNote;\n\nclass TransfersObserver : public ITransfersObserver {\npublic:\n\n  virtual void onTransactionUpdated(ITransfersSubscription* object, const Hash& transactionHash) override {\n    std::lock_guard<std::mutex> lk(m_mutex);\n    m_transfers.emplace_back(transactionHash);\n  }\n\n  std::vector<Hash> m_transfers;\n  std::mutex m_mutex;\n};\n\nclass TransfersApi : public ::testing::Test, public IBlockchainSynchronizerObserver {\npublic:\n\n  TransfersApi() :\n    m_logger(Logging::ERROR),\n    m_currency(CryptoNote::CurrencyBuilder(m_logger).currency()),\n    generator(m_currency),\n    m_node(generator),\n    m_sync(m_node, m_logger, m_currency.genesisBlockHash()),\n    m_transfersSync(m_currency, m_logger, m_sync, m_node) {\n  }\n\n  void addAccounts(size_t count) {\n    while (count--) {\n      m_accounts.push_back(generateAccountKeys());\n    }\n  }\n\n  void addPaymentAccounts(size_t count) {\n    KeyPair p1;\n    Crypto::generate_keys(p1.publicKey, p1.secretKey);\n    auto viewKeys = p1;\n    while (count--) {\n      Crypto::generate_keys(p1.publicKey, p1.secretKey);\n      m_accounts.push_back(accountKeysFromKeypairs(viewKeys, p1));\n    }\n  }\n\n  void addMinerAccount() {\n    m_accounts.push_back(reinterpret_cast<const AccountKeys&>(generator.getMinerAccount()));\n  }\n\n  AccountSubscription createSubscription(size_t acc, uint64_t timestamp = 0) {\n    const auto& keys = m_accounts[acc];\n    AccountSubscription sub;\n    sub.keys = keys;\n    sub.syncStart.timestamp = timestamp;\n    sub.syncStart.height = 0;\n    sub.transactionSpendableAge = 5;\n    return sub;\n  }\n\n  void subscribeAccounts() {\n\n    m_transferObservers.reset(new TransfersObserver[m_accounts.size()]);\n      \n    for (size_t i = 0; i < m_accounts.size(); ++i) {\n      m_subscriptions.push_back(&m_transfersSync.addSubscription(createSubscription(i)));\n      m_subscriptions.back()->addObserver(&m_transferObservers[i]);\n    }\n  }\n\n  void startSync() {\n    syncCompleted = std::promise<std::error_code>();\n    syncCompletedFuture = syncCompleted.get_future();\n    m_sync.addObserver(this);\n    m_sync.start();\n    syncCompletedFuture.get();\n    m_sync.removeObserver(this);\n  }\n\n  void refreshSync() {\n    syncCompleted = std::promise<std::error_code>();\n    syncCompletedFuture = syncCompleted.get_future();\n    m_sync.addObserver(this);\n    m_sync.lastKnownBlockHeightUpdated(0);\n    syncCompletedFuture.get();\n    m_sync.removeObserver(this);\n  }\n\n  void synchronizationCompleted(std::error_code result) override {\n    decltype(syncCompleted) detachedPromise = std::move(syncCompleted);\n    detachedPromise.set_value(result);\n  }\n\n  void generateMoneyForAccount(size_t idx) {\n    generator.getBlockRewardForAddress(\n      reinterpret_cast<const CryptoNote::AccountPublicAddress&>(m_accounts[idx].address));\n  }\n\n  std::error_code submitTransaction(ITransactionReader& tx) {\n    auto data = tx.getTransactionData();\n    Transaction outTx;\n    CryptoNote::fromBinaryArray(outTx, data);\n\n    std::promise<std::error_code> result;\n    m_node.relayTransaction(outTx, [&result](std::error_code ec) {\n      std::promise<std::error_code> detachedPromise = std::move(result);\n      detachedPromise.set_value(ec);\n    });\n    return result.get_future().get();\n  }\n\nprotected:\n\n  boost::scoped_array<TransfersObserver> m_transferObservers;\n  std::vector<AccountKeys> m_accounts;\n  std::vector<ITransfersSubscription*> m_subscriptions;\n\n  Logging::ConsoleLogger m_logger;\n  CryptoNote::Currency m_currency;\n  TestBlockchainGenerator generator;\n  INodeTrivialRefreshStub m_node;\n  BlockchainSynchronizer m_sync;\n  TransfersSyncronizer m_transfersSync;\n\n  std::promise<std::error_code> syncCompleted;\n  std::future<std::error_code> syncCompletedFuture;\n};\n\n\nnamespace CryptoNote {\n  inline bool operator == (const TransactionOutputInformation& t1, const TransactionOutputInformation& t2) {\n    return \n      t1.type == t2.type &&\n      t1.amount == t2.amount &&\n      t1.outputInTransaction == t2.outputInTransaction &&\n      t1.transactionPublicKey == t2.transactionPublicKey;\n  }\n}\n\n\nTEST_F(TransfersApi, testSubscriptions) {\n  addAccounts(1);\n\n  m_transfersSync.addSubscription(createSubscription(0));\n\n  std::vector<AccountPublicAddress> subscriptions;\n\n  m_transfersSync.getSubscriptions(subscriptions);\n\n  const auto& addr = m_accounts[0].address;\n\n  ASSERT_EQ(1, subscriptions.size());\n  ASSERT_EQ(addr, subscriptions[0]);\n  ASSERT_TRUE(m_transfersSync.getSubscription(addr) != 0);\n  ASSERT_TRUE(m_transfersSync.removeSubscription(addr));\n\n  subscriptions.clear();\n  m_transfersSync.getSubscriptions(subscriptions);\n  ASSERT_EQ(0, subscriptions.size());\n}\n\nTEST_F(TransfersApi, syncOneBlock) { \n  addAccounts(2);\n  subscribeAccounts();\n\n  generator.getBlockRewardForAddress(m_accounts[0].address);\n  generator.generateEmptyBlocks(15);\n\n  startSync();\n\n  auto& tc1 = m_transfersSync.getSubscription(m_accounts[0].address)->getContainer();\n  auto& tc2 = m_transfersSync.getSubscription(m_accounts[1].address)->getContainer();\n  \n  ASSERT_NE(&tc1, &tc2);\n\n  ASSERT_GT(tc1.balance(ITransfersContainer::IncludeAll), 0);\n  ASSERT_GT(tc1.transfersCount(), 0);\n  ASSERT_EQ(0, tc2.transfersCount());\n}\n\n\nTEST_F(TransfersApi, syncMinerAcc) {\n  addMinerAccount();\n  subscribeAccounts();\n  \n  generator.generateEmptyBlocks(10);\n\n  startSync();\n\n  ASSERT_NE(0, m_subscriptions[0]->getContainer().transfersCount());\n}\n\n\nnamespace {\n  std::unique_ptr<ITransaction> createMoneyTransfer(\n    uint64_t amount,\n    uint64_t fee,\n    const AccountKeys& senderKeys,\n  const AccountPublicAddress& reciever,\n  ITransfersContainer& tc) {\n\n  std::vector<TransactionOutputInformation> transfers;\n  tc.getOutputs(transfers, ITransfersContainer::IncludeAllUnlocked);\n\n  auto tx = createTransaction();\n\n  std::vector<std::pair<TransactionTypes::InputKeyInfo, KeyPair>> inputs;\n\n  uint64_t foundMoney = 0;\n\n  for (const auto& t : transfers) {\n    TransactionTypes::InputKeyInfo info;\n\n    info.amount = t.amount;\n\n    TransactionTypes::GlobalOutput globalOut;\n    globalOut.outputIndex = t.globalOutputIndex;\n    globalOut.targetKey = t.outputKey;\n    info.outputs.push_back(globalOut);\n\n    info.realOutput.outputInTransaction = t.outputInTransaction;\n    info.realOutput.transactionIndex = 0;\n    info.realOutput.transactionPublicKey = t.transactionPublicKey;\n\n    KeyPair kp;\n    tx->addInput(senderKeys, info, kp);\n\n    inputs.push_back(std::make_pair(info, kp));\n\n    foundMoney += info.amount;\n\n    if (foundMoney >= amount + fee) {\n      break;\n  }\n    }\n\n  \/\/ output to reciever\n  tx->addOutput(amount, reciever);\n  \/\/ change\n  uint64_t change = foundMoney - amount - fee;\n  if (change) {\n    tx->addOutput(change, senderKeys.address);\n  }\n\n  for (size_t inputIdx = 0; inputIdx < inputs.size(); ++inputIdx) {\n    tx->signInputKey(inputIdx, inputs[inputIdx].first, inputs[inputIdx].second);\n  }\n\n  return tx;\n  }\n}\n\nTEST_F(TransfersApi, moveMoney) {\n  addMinerAccount();\n  addAccounts(2);\n  subscribeAccounts();\n\n  generator.generateEmptyBlocks(2 * m_currency.minedMoneyUnlockWindow());\n\n  \/\/ sendAmount is an even number\n  uint64_t sendAmount = (get_outs_money_amount(generator.getBlockchain()[1].baseTransaction) \/ 4) * 2;\n  auto fee = m_currency.minimumFee();\n\n  startSync();\n\n  auto& tc0 = m_subscriptions[0]->getContainer();\n\n  ASSERT_LE(sendAmount, tc0.balance(ITransfersContainer::IncludeAllUnlocked));\n\n  auto tx = createMoneyTransfer(sendAmount, fee, m_accounts[0], m_accounts[1].address, tc0);\n  submitTransaction(*tx);\n\n  refreshSync();\n\n  ASSERT_EQ(1, m_transferObservers[1].m_transfers.size());\n  ASSERT_EQ(tx->getTransactionHash(), m_transferObservers[1].m_transfers[0]);\n\n  auto& tc1 = m_subscriptions[1]->getContainer();\n\n  ASSERT_EQ(sendAmount, tc1.balance(ITransfersContainer::IncludeAll));\n  ASSERT_EQ(0, tc1.balance(ITransfersContainer::IncludeAllUnlocked));\n\n  generator.generateEmptyBlocks(m_currency.minedMoneyUnlockWindow()); \/\/ unlock money\n\n  refreshSync();\n\n  ASSERT_EQ(sendAmount, tc1.balance(ITransfersContainer::IncludeAllUnlocked));\n\n  auto tx2 = createMoneyTransfer(sendAmount \/ 2, fee, m_accounts[1], m_accounts[2].address, tc1);\n  submitTransaction(*tx2);\n\n  refreshSync();\n\n  ASSERT_EQ(2, m_transferObservers[1].m_transfers.size());\n  ASSERT_EQ(tx2->getTransactionHash(), m_transferObservers[1].m_transfers.back());\n\n  ASSERT_EQ(sendAmount \/ 2 - fee, m_subscriptions[1]->getContainer().balance(ITransfersContainer::IncludeAll));\n  ASSERT_EQ(sendAmount \/ 2, m_subscriptions[2]->getContainer().balance(ITransfersContainer::IncludeAll));\n}\n\n\nstruct lessOutKey {\n  bool operator()(const TransactionOutputInformation& t1, const TransactionOutputInformation& t2) {\n    return std::hash<PublicKey>()(t1.outputKey) <  std::hash<PublicKey>()(t2.outputKey);\n  }\n};\n\nbool compareStates(TransfersSyncronizer& sync1, TransfersSyncronizer& sync2) {\n\n  std::vector<AccountPublicAddress> subs;\n  sync1.getSubscriptions(subs);\n\n  for (const auto& s : subs) {\n    auto& tc1 = sync1.getSubscription(s)->getContainer();\n\n    if (sync2.getSubscription(s) == nullptr)\n      return false;\n\n    auto& tc2 = sync2.getSubscription(s)->getContainer();\n\n    std::vector<TransactionOutputInformation> out1;\n    std::vector<TransactionOutputInformation> out2;\n\n    tc1.getOutputs(out1);\n    tc2.getOutputs(out2);\n\n    std::sort(out1.begin(), out1.end(), lessOutKey());\n    std::sort(out2.begin(), out2.end(), lessOutKey());\n\n    if (out1 != out2)\n      return false;\n\n  }\n\n  return true;\n}\n\nTEST_F(TransfersApi, state) {\n  addMinerAccount();\n  subscribeAccounts();\n\n  generator.generateEmptyBlocks(20);\n\n  startSync();\n\n  m_sync.stop();\n  std::stringstream memstm;\n  m_transfersSync.save(memstm);\n  m_sync.start();\n\n  BlockchainSynchronizer bsync2(m_node, m_logger, m_currency.genesisBlockHash());\n  TransfersSyncronizer sync2(m_currency, m_logger, bsync2, m_node);\n\n  for (size_t i = 0; i < m_accounts.size(); ++i) {\n    sync2.addSubscription(createSubscription(i));\n  }\n\n  sync2.load(memstm);\n\n  \/\/ compare transfers\n  ASSERT_TRUE(compareStates(m_transfersSync, sync2));\n\n  \/\/ generate more blocks\n  generator.generateEmptyBlocks(10);\n\n  refreshSync();\n\n  syncCompleted = std::promise<std::error_code>();\n  syncCompletedFuture = syncCompleted.get_future();\n  bsync2.addObserver(this);\n  bsync2.start();\n  syncCompletedFuture.get();\n  bsync2.removeObserver(this);\n\n  \/\/ check again\n  ASSERT_TRUE(compareStates(m_transfersSync, sync2));\n}\n\nTEST_F(TransfersApi, sameTrackingKey) {\n\n  size_t offset = 2; \/\/ miner account + ordinary account\n  size_t paymentAddresses = 1000;\n  size_t payments = 10;\n\n  addMinerAccount();\n  addAccounts(1);\n  addPaymentAccounts(paymentAddresses);\n\n  subscribeAccounts();\n\n  for (size_t i = 0; i < payments; ++i) {\n    generateMoneyForAccount(i + offset);\n  }\n\n  startSync();\n\n  for (size_t i = 0; i < payments; ++i) {\n    auto sub = m_subscriptions[offset + i];\n    EXPECT_NE(0, sub->getContainer().balance(ITransfersContainer::IncludeAll));\n  }\n\n}\n","avg_line_length":27.856812933,"max_line_length":111,"alphanum_fraction":0.7298126347,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":810,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/ AUTOGENERATED FILE - DO NOT MODIFY!\n\/\/ This file generated by Djinni from example.djinni\n\n#include <iostream> \/\/ for debugging\n#include <cassert>\n#include \"wrapper_marshal.hpp\"\n#include \"sort_order.hpp\"\n\nint32_t int32_from_enum_sort_order(std::experimental::optional<::textsort::sort_order> e) {\n    if (e) {\n        return static_cast<int32_t>(* e);\n    }\n    return -1; \/\/ -1 to signal null boxed enum\n}\n\nint32_t int32_from_enum_sort_order(::textsort::sort_order e) {\n    return static_cast<int32_t>(e);\n}\nstd::experimental::optional<::textsort::sort_order> get_boxed_enum_sort_order_from_int32(int32_t e) {\n    if (e == -1) { \/\/ to signal null enum\n        return std::experimental::nullopt;\n    }\n    return std::experimental::optional<::textsort::sort_order>(static_cast<::textsort::sort_order>(e));\n}\n","avg_line_length":32.4,"max_line_length":103,"alphanum_fraction":0.7098765432,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13521,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["PHP-3.01","Zend-2.0"],"max_stars_count":1.0,"content":"\/*\n   +----------------------------------------------------------------------+\n   | HipHop for PHP                                                       |\n   +----------------------------------------------------------------------+\n   | Copyright (c) 2010-2014 Facebook, Inc. (http:\/\/www.facebook.com)     |\n   +----------------------------------------------------------------------+\n   | This source file is subject to version 3.01 of the PHP license,      |\n   | that is bundled with this package in the file LICENSE, and is        |\n   | available through the world-wide-web at the following url:           |\n   | http:\/\/www.php.net\/license\/3_01.txt                                  |\n   | If you did not receive a copy of the PHP license and are unable to   |\n   | obtain it through the world-wide-web, please send a note to          |\n   | license@php.net so we can mail you a copy immediately.               |\n   +----------------------------------------------------------------------+\n*\/\n\n#include \"hphp\/compiler\/construct.h\"\n#include \"hphp\/compiler\/parser\/parser.h\"\n#include \"hphp\/util\/string-vsnprintf.h\"\n\n#include \"hphp\/compiler\/analysis\/file_scope.h\"\n#include \"hphp\/compiler\/analysis\/function_scope.h\"\n#include \"hphp\/compiler\/analysis\/class_scope.h\"\n#include \"hphp\/compiler\/analysis\/analysis_result.h\"\n#include \"hphp\/compiler\/analysis\/ast_walker.h\"\n#include \"hphp\/compiler\/analysis\/exceptions.h\"\n#include \"hphp\/parser\/parse-time-fatal-exception.h\"\n\n#include \"hphp\/compiler\/statement\/function_statement.h\"\n\n#include \"hphp\/compiler\/expression\/simple_function_call.h\"\n#include \"hphp\/compiler\/expression\/simple_variable.h\"\n#include \"hphp\/compiler\/expression\/closure_expression.h\"\n#include <iomanip>\n\nusing namespace HPHP;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nConstruct::Construct(BlockScopePtr scope, LocationPtr loc, KindOf kindOf)\n  : m_blockScope(scope)\n  , m_flagsVal(0)\n  , m_kindOf(kindOf)\n  , m_loc(loc)\n  , m_containedEffects(0)\n  , m_effectsTag(0)\n{\n}\n\nvoid Construct::resetScope(BlockScopeRawPtr scope, bool resetOrigScope) {\n  setBlockScope(scope);\n  if (resetOrigScope) {\n    ExpressionPtr expr =\n      dynamic_pointer_cast<Expression>(shared_from_this());\n    if (expr) {\n      expr->setOriginalScope(scope);\n    }\n  }\n  for (int i = 0, n = getKidCount(); i < n; i++) {\n    if (ConstructPtr kid = getNthKid(i)) {\n      if (FunctionWalker::SkipRecurse(kid)) continue;\n      kid->resetScope(scope, resetOrigScope);\n    }\n  }\n}\n\nvoid Construct::recomputeEffects() {\n  BlockScopeRawPtr scope = getScope();\n  if (scope) scope->incEffectsTag();\n}\n\nint Construct::getChildrenEffects() const {\n  int childrenEffects = NoEffect;\n  for (int i = getKidCount(); i--; ) {\n    ConstructPtr child = getNthKid(i);\n    if (child) {\n      if (FunctionWalker::SkipRecurse(child)) continue;\n      childrenEffects |= child->getContainedEffects();\n      if ((childrenEffects & UnknownEffect) == UnknownEffect) {\n        break;\n      }\n    }\n  }\n  return childrenEffects;\n}\n\nint Construct::getContainedEffects() const {\n  BlockScopeRawPtr scope = getScope();\n  int curTag = scope ? scope->getEffectsTag() : m_effectsTag + 1;\n  if (m_effectsTag != curTag) {\n    m_effectsTag = curTag;\n    m_containedEffects = getLocalEffects() | getChildrenEffects();\n  }\n  return m_containedEffects;\n}\n\nvoid LocalEffectsContainer::setLocalEffect(Construct::Effect effect) {\n  if ((m_localEffects & effect) != effect) {\n    effectsCallback();\n    m_localEffects |= effect;\n  }\n}\n\nvoid LocalEffectsContainer::clearLocalEffect(Construct::Effect effect) {\n  if (m_localEffects & effect) {\n    effectsCallback();\n    m_localEffects &= ~effect;\n  }\n}\n\nbool LocalEffectsContainer::hasLocalEffect(Construct::Effect effect) const {\n  return m_localEffects & effect;\n}\n\nExpressionPtr Construct::makeConstant(AnalysisResultConstPtr ar,\n                                      const std::string &value) const {\n  return Expression::MakeConstant(ar, getScope(), getLocation(), value);\n}\n\nExpressionPtr Construct::makeScalarExpression(AnalysisResultConstPtr ar,\n                                               const Variant &value) const {\n  return Expression::MakeScalarExpression(ar, getScope(), getLocation(), value);\n}\n\nstd::string Construct::getText(bool useCache \/* = false *\/,\n                               bool translate \/* = false *\/,\n                               AnalysisResultPtr ar\n                               \/* = AnalysisResultPtr() *\/) {\n  std::string &text = m_text;\n  if (useCache && !text.empty()) return text;\n  std::ostringstream o;\n  CodeGenerator cg(&o, CodeGenerator::PickledPHP);\n  cg.translatePredefined(translate);\n  outputPHP(cg, ar);\n  text = o.str();\n  return text;\n}\n\nvoid Construct::serialize(JSON::CodeError::OutputStream &out) const {\n  JSON::CodeError::ListStream ls(out);\n  ls << m_loc->file << m_loc->line0 << m_loc->char0 <<\n                       m_loc->line1 << m_loc->char1;\n  ls.done();\n}\n\nvoid Construct::printSource(CodeGenerator &cg) {\n  if (m_loc) {\n    cg_printf(\"\/* SRC: %s line %d *\/\\n\", m_loc->file, m_loc->line0);\n  }\n}\n\nvoid Construct::dumpNode(int spc, AnalysisResultConstPtr ar) {\n  dumpNode(spc);\n}\n\nvoid Construct::dumpNode(int spc) const {\n  \/\/ evil, but helpful!\n  const_cast<Construct*>(this)->dumpNode(spc);\n}\n\nvoid Construct::dumpNode(int spc) {\n  int nkid = getKidCount();\n  const char *name = 0;\n  int type = 0;\n  std::string scontext = \"\";\n  std::string value = \"\";\n  std::string type_info = \"\";\n  unsigned id = 0;\n  ExpressionPtr idPtr = ExpressionPtr();\n  int ef = 0;\n\n  if (isStatement()) {\n    Statement *s = static_cast<Statement*>(this);\n    auto stype = s->getKindOf();\n    name = Statement::nameOfKind(stype);\n    value = s->getName();\n    type = (int)stype;\n  } else {\n    assert(isExpression());\n    Expression *e = static_cast<Expression*>(this);\n    id = e->getCanonID();\n    idPtr = e->getCanonLVal();\n\n    ef = e->getLocalEffects();\n\n    Expression::KindOf etype = e->getKindOf();\n    name = Expression::nameOfKind(etype);\n    switch (etype) {\n      case Expression::KindOfSimpleFunctionCall:\n        value = static_cast<SimpleFunctionCall*>(e)->getName();\n        break;\n      case Expression::KindOfSimpleVariable:\n        value = static_cast<SimpleVariable*>(e)->getName();\n        break;\n      case Expression::KindOfConstantExpression:\n        value = e->getText();\n        break;\n      case Expression::KindOfScalarExpression:\n        value = e->getText();\n        break;\n      default: break;\n    }\n\n    int c = e->getContext();\n    if ((c & Expression::Declaration) == Expression::Declaration) {\n      scontext += \"|Declaration\";\n    } else if (c & Expression::LValue) {\n      scontext += \"|LValue\";\n    }\n    if (c & Expression::NoLValueWrapper) {\n      scontext += \"|NoLValueWrapper\";\n    }\n    if (c & Expression::RefValue) {\n      scontext += \"|RefValue\";\n    }\n    if (c & Expression::RefParameter) {\n      scontext += \"|RefParameter\";\n    }\n    if (c & Expression::DeepReference) {\n      scontext += \"|DeepReference\";\n    }\n    if (c & Expression::ObjectContext) {\n      scontext += \"|ObjectContext\";\n    }\n    if (c & Expression::InParameterExpression) {\n      scontext += \"|InParameterExpression\";\n    }\n    if (c & Expression::ExistContext) {\n      scontext += \"|ExistContext\";\n    }\n    if (c & Expression::UnsetContext) {\n      scontext += \"|UnsetContext\";\n    }\n    if (c & Expression::AssignmentLHS) {\n      scontext += \"|AssignmentLHS\";\n    }\n    if (c & Expression::RefAssignmentLHS) {\n      scontext += \"|RefAssignmentLHS\";\n    }\n    if (c & Expression::DeepAssignmentLHS) {\n      scontext += \"|DeepAssignmentLHS\";\n    }\n    if (c & Expression::AssignmentRHS) {\n      scontext += \"|AssignmentRHS\";\n    }\n    if (c & Expression::InvokeArgument) {\n      scontext += \"|InvokeArgument\";\n    }\n    if (c & Expression::OprLValue) {\n      scontext += \"|OprLValue\";\n    }\n    if (c & Expression::DeepOprLValue) {\n      scontext += \"|DeepOprLValue\";\n    }\n    if (c & Expression::AccessContext) {\n      scontext += \"|AccessContext\";\n    }\n    if (c & Expression::ReturnContext) {\n      scontext += \"|ReturnContext\";\n    }\n\n    if (scontext != \"\") {\n      scontext = \" (\" + scontext.substr(1) + \")\";\n    }\n\n    type = (int)etype;\n\n    if (e->getActualType()) {\n      type_info = e->getActualType()->toString();\n      if (e->getExpectedType()) {\n        type_info += \":\" + e->getExpectedType()->toString();\n      } else {\n        type_info += \":\";\n      }\n      type_info = \"{\" + type_info + \"} \";\n    }\n  }\n\n  int s = spc;\n  while (s > 0) {\n    int n = s > 10 ? 10 : s;\n    std::cout << (\"          \"+10-n);\n    s -= n;\n  }\n\n  std::cout << \"-> 0x\" << std::hex << std::setfill('0')\n            << std::setw(10) << (int64_t)this << std::dec;\n\n  std::cout << \" \" << name << \"(\" << type << \") \";\n  if (id) {\n    std::cout << \"id=\" << id << \" \";\n  }\n  if (idPtr) {\n    std::cout << \"idp=0x\" <<\n      std::hex << std::setfill('0') << std::setw(10) <<\n      (int64_t)idPtr.get() << \" \";\n  }\n\n  if (value != \"\") {\n    std::cout << \"[\" << value << \"] \";\n  }\n\n  string sef;\n  if ((ef & UnknownEffect) == UnknownEffect) {\n    sef = \"|UnknownEffect\";\n  } else {\n    if (ef & IOEffect) sef += \"|IOEffect\";\n    if (ef & AssignEffect) sef += \"|AssignEffect\";\n    if (ef & GlobalEffect) sef += \"|GlobalEffect\";\n    if (ef & LocalEffect) sef += \"|LocalEffect\";\n    if (ef & ParamEffect) sef += \"|ParamEffect\";\n    if (ef & DeepParamEffect) sef += \"|DeepParamEffect\";\n    if (ef & DynamicParamEffect) sef += \"|DynamicParamEffect\";\n    if (ef & CanThrow) sef += \"|CanThrow\";\n    if (ef & AccessorEffect) sef += \"|AccessorEffect\";\n    if (ef & CreateEffect) sef += \"|CreateEffect\";\n    if (ef & DiagnosticEffect) sef += \"|DiagnosticEffect\";\n    if (ef & OtherEffect) sef += \"|OtherEffect\";\n  }\n  if (sef != \"\") {\n    sef = \" (\" + sef.substr(1) + \")\";\n  }\n\n  string localtered;\n  if (Expression *e = dynamic_cast<Expression*>(this)) {\n    localtered = e->isLocalExprAltered() ? \"LocalAltered\" : \"NotLocalAltered\";\n  }\n  if (localtered != \"\") {\n    localtered = \" (\" + localtered + \")\";\n  }\n\n  string refstr;\n  if (dynamic_cast<SimpleVariable*>(this) != nullptr) {\n    if (isReferencedValid()) {\n      if (isReferenced()) {\n        refstr += \",Referenced\";\n      } else {\n        refstr += \",NotReferenced\";\n      }\n    }\n    if (!maybeRefCounted()) refstr += \",NotRefCounted\";\n    if (!maybeInited()) refstr += \",NotInited\";\n    if (isNonNull()) refstr += \",NotNull\";\n    if (refstr.empty()) refstr = \",NoRefInfo\";\n  }\n  if (refstr != \"\") refstr = \" (\" + refstr.substr(1) + \")\";\n\n  string objstr;\n  if (dynamic_cast<SimpleVariable*>(this) != nullptr) {\n    objstr = \" (NoObjInfo)\";\n  }\n\n  string noremoved;\n  if (isNoRemove()) {\n    noremoved = \" (NoRemove)\";\n  }\n\n  std::cout << type_info << nkid << scontext << sef\n    << localtered << refstr << objstr << noremoved;\n  if (m_loc) {\n    std::cout << \" \" << m_loc->file << \":\"\n      << \"[\" << m_loc->line0 << \"@\" << m_loc->char0 << \", \"\n      << m_loc->line1 << \"@\" << m_loc->char1 << \"]\";\n  }\n  std::cout << \"\\n\";\n}\n\nclass ConstructDumper : public FunctionWalker {\npublic:\n  ConstructDumper(int spc, AnalysisResultConstPtr ar,\n                  bool functionOnly = false) :\n      m_spc(spc), m_ar(ar), m_functionOnly(functionOnly), m_showEnds(true) {}\n\n  void walk(AstWalkerStateVec state,\n            ConstructRawPtr endBefore, ConstructRawPtr endAfter) {\n    AstWalker::walk(*this, state, endBefore, endAfter);\n  }\n  int before(ConstructRawPtr cp) {\n    int ret = m_functionOnly ? FunctionWalker::before(cp) : WalkContinue;\n    cp->dumpNode(m_spc, m_ar);\n    m_spc += 2;\n    m_showEnds = false;\n    return ret;\n  }\n  int after(ConstructRawPtr cp) {\n    if (m_showEnds) {\n      int s = m_spc;\n      while (s > 0) {\n        int n = s > 10 ? 10 : s;\n        std::cout << (\"          \"+10-n);\n        s -= n;\n      }\n      std::cout << \"<<\";\n      cp->dumpNode(0, m_ar);\n    }\n    m_spc -= 2;\n    \/\/ HACK: dump the closure function as a \"child\" of the\n    \/\/ closure expression\n    ClosureExpressionPtr c =\n      dynamic_pointer_cast<ClosureExpression>(cp);\n    if (c) {\n      c->getClosureFunction()->dump(m_spc, m_ar);\n    }\n    return WalkContinue;\n  }\nprivate:\n  int m_spc;\n  AnalysisResultConstPtr m_ar;\n  bool m_functionOnly;\n  bool m_showEnds;\n};\n\nvoid Construct::dump(int spc, AnalysisResultConstPtr ar) {\n  ConstructDumper cd(spc, ar);\n  cd.walk(AstWalkerStateVec(ConstructRawPtr(this)),\n    ConstructRawPtr(), ConstructRawPtr());\n}\n\nvoid Construct::dump(int spc, AnalysisResultConstPtr ar, bool functionOnly,\n                     const AstWalkerStateVec &state,\n                     ConstructPtr endBefore, ConstructPtr endAfter) {\n  ConstructDumper cd(spc, ar, functionOnly);\n  cd.walk(state, endBefore, endAfter);\n}\n\nvoid Construct::parseTimeFatal(Compiler::ErrorType err, const char *fmt, ...) {\n  va_list ap;\n  va_start(ap, fmt);\n  string msg;\n  string_vsnprintf(msg, fmt, ap);\n  va_end(ap);\n\n  if (err != Compiler::NoError) Compiler::Error(err, shared_from_this());\n  throw ParseTimeFatalException(m_loc->file, m_loc->line0, \"%s\", msg.c_str());\n}\n\nvoid Construct::analysisTimeFatal(Compiler::ErrorType err,\n                                  const char *fmt, ...) {\n  va_list ap;\n  va_start(ap, fmt);\n  string msg;\n  string_vsnprintf(msg, fmt, ap);\n  va_end(ap);\n\n  assert(err != Compiler::NoError);\n  Compiler::Error(err, shared_from_this());\n  throw AnalysisTimeFatalException(m_loc->file, m_loc->line0,\n                                   \"%s [analysis]\", msg.c_str());\n}\n","avg_line_length":30.0466666667,"max_line_length":80,"alphanum_fraction":0.5884180164,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1186,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint min_refills(int dist, int tank, vector<int>& stops, int start, int count) {\r\n    if ((start + tank) >= dist) {\r\n        return count;\r\n    }\r\n    if (stops.size() == 0) {\r\n        return -1;\r\n    }\r\n    int old_start = start;\r\n    for (int i = 0; i < stops.size(); i++) {\r\n        if (stops[i] <= (start + tank)) {\r\n            old_start = stops[i];\r\n        }\r\n        else {\r\n            if (i != 0) {\r\n                stops.erase(stops.begin(), stops.begin() + i);\r\n            }\r\n            else {\r\n                stops.erase(stops.begin());\r\n            }\r\n            return min_refills(dist, tank, stops, old_start, count + 1);\r\n        }\r\n    }\r\n    return (old_start + tank) >= dist ? count + 1 : -1;\r\n}\r\n\r\nint compute_min_refills(int dist, int tank, vector<int>& stops) {\r\n    return min_refills(dist, tank, stops, 0, 0);\r\n}\r\n\r\nint main() {\r\n    int d = 0;\r\n    cin >> d;\r\n    int m = 0;\r\n    cin >> m;\r\n    int n = 0;\r\n    cin >> n;\r\n\r\n    vector<int> stops(n);\r\n    for (size_t i = 0; i < n; ++i)\r\n        cin >> stops.at(i);\r\n\r\n    cout << compute_min_refills(d, m, stops) << \"\\n\";\r\n\r\n    return 0;\r\n}","avg_line_length":23.72,"max_line_length":80,"alphanum_fraction":0.4620573356,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":554,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/**\n * @file Stack.cpp\n * @author Boran Seckin (seckinb@mcmaster.ca)\n *\/\n\n#include \"Stack.h\"\n#include <iostream>\n\ntemplate <class T>\nStack<T>::Stack()\n{\n  stack = std::vector<T>();\n}\n\ntemplate <class T>\nvoid Stack<T>::push(T t)\n{\n  if (t != NULL) stack.push_back(t);\n}\n\ntemplate <class T>\nT Stack<T>::pop()\n{\n  if (stack.size() == 0) return NULL;\n  T last = stack.back();\n  stack.pop_back();\n  return last;\n}\n\ntemplate <class T>\nint Stack<T>::size()\n{\n  return stack.size();\n}\n\ntemplate <class T>\nbool Stack<T>::isEmpty()\n{\n  return stack.size() == 0;\n}\n","avg_line_length":13.512195122,"max_line_length":45,"alphanum_fraction":0.6101083032,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4646,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":11.0,"content":"\/*\n * Copyright 2020 Yohan Pipereau\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <iostream>\n#include <memory>\n#include <chrono>\n#include <getopt.h>\n\n#include <grpcpp\/grpcpp.h>\n#include <grpcpp\/server.h>\n#include <grpcpp\/server_builder.h>\n\n#include \"gnmi\/gnmi.h\"\n#include <security\/authentication.h>\n#include <utils\/log.h>\n\nusing namespace std;\n\nvoid RunServer(string bind_addr, shared_ptr<ServerCredentials> cred)\n{\n  ServerBuilder builder;\n  GNMIService gnmi(\"gnmi\"); \/\/gNMI Service\n\n  builder.AddListeningPort(bind_addr, cred);\n  builder.RegisterService(&gnmi);\n  unique_ptr<Server> server(builder.BuildAndStart());\n  cout << \"Using grpc \" << grpc::Version() << endl;\n\n  if (bind_addr.find(\":\") == string::npos) {\n    cout << \"Server listening on \" << bind_addr << \":443\" << endl;\n  } else {\n    cout << \"Server listening on \" << bind_addr << endl;\n  }\n\n  server->Wait();\n}\n\nstatic void show_usage(string name)\n{\n  cerr << \"Usage: \" << name << \" <option(s)>\\n\"\n    << \"Options:\\n\"\n    << \"\\t-h,--help\\t\\t\\tShow this help message\\n\"\n    << \"\\t-u,--username USERNAME\\t\\tDefine connection username\\n\"\n    << \"\\t-p,--password PASSWORD\\t\\tDefine connection password\\n\"\n    << \"\\t-f,--force-insecure\\t\\tNo TLS connection, no password authentication\\n\"\n    << \"\\t-k,--private-key PRIVATE_KEY\\tpath to server TLS private key\\n\"\n    << \"\\t-c,--cert CERTIFICATE\\tpath to server TLS certificate\\n\"\n    << \"\\t-r,--ca CERTIFICATE\\tpath to root certificate\/CA certificate\\n\"\n    << \"\\t-l,--log-level LOG_LEVEL\\tLog level\\n\"\n    << \"\\t\\t 0 = all logging turned off\\n\"\n    << \"\\t\\t 1 = log only error messages\\n\"\n    << \"\\t\\t 2 = (default) log error and warning messages\\n\"\n    << \"\\t\\t 3 = log error, warning and informational messages\\n\"\n    << \"\\t\\t 4 = log everything, including development debug messages\\n\"\n    << \"\\t-b,--bind URI\\t\\t\\tBind to an URI\\n\"\n    << \"\\t\\t URI = PREFIX:\/\/IP:PORT\\n\"\n    << \"\\t\\t URI = IP:PORT, default to dns:\/\/ prefix\\n\"\n    << \"\\t\\t URI = IP, default to dns:\/\/ prefix and port 443\\n\"\n    << endl;\n}\n\nint main (int argc, char* argv[]) {\n  int c;\n  extern char *optarg;\n  int option_index = 0;\n  string bind_addr = \"localhost:50051\";\n  string username, password;\n  Log();\n  AuthBuilder auth;\n\n  static struct option long_options[] =\n  {\n    {\"help\", no_argument, 0, 'h'},\n    {\"log-level\", required_argument, 0, 'l'}, \/\/log level\n    {\"username\", required_argument, 0, 'u'},\n    {\"password\", required_argument, 0, 'p'},\n    {\"private-key\", required_argument, 0, 'k'}, \/\/private key\n    {\"cert\", required_argument, 0, 'c'}, \/\/certificate chain\n    {\"ca\", required_argument, 0, 'r'}, \/\/certificate chain\n    {\"force-insecure\", no_argument, 0, 'f'}, \/\/insecure mode\n    {\"bind\", required_argument, 0, 'b'}, \/\/insecure mode\n    {0, 0, 0, 0}\n  };\n\n  \/*\n   * An option character followed by ('') indicates no argument\n   * An option character followed by (\u2018:\u2019) indicates a required argument.\n   * An option character is followed by (\u2018::\u2019) indicates an optional argument.\n   * Here: no argument after (h,f) ; mandatory argument after (p,u,l,b,c,k,r)\n   *\/\n  while ((c = getopt_long(argc, argv, \"hfl:p:u:c:k:r:b:\", long_options, &option_index))\n         != -1) {\n    switch (c)\n    {\n      case '?': \/\/help\n      case 'h':\n        show_usage(argv[0]);\n        exit(0);\n        break;\n      case 'u': \/\/username\n        auth.setUsername(string(optarg));\n        break;\n      case 'p': \/\/password\n        auth.setPassword(string(optarg));\n        break;\n      case 'k': \/\/server private key\n        auth.setKeyPath(string(optarg));\n        break;\n      case 'c': \/\/server certificate\n        auth.setCertPath(string(optarg));\n        break;\n      case 'r': \/\/CA\/root certificate\n        auth.setRootCertPath(string(optarg));\n        break;\n      case 'l': \/\/log level\n        Log::setLevel(atoi(optarg));\n        break;\n      case 'b': \/\/binding address\n        bind_addr = optarg;\n        break;\n      case 'f': \/\/force insecure connection\n        auth.setInsecure(true);\n        break;\n      default: \/* You won't get there *\/\n        exit(1);\n    }\n  }\n\n  RunServer(bind_addr, auth.build());\n\n  return 0;\n}\n","avg_line_length":31.8219178082,"max_line_length":87,"alphanum_fraction":0.6248385708,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2410,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include <iostream>\n#include <memory>\n#include <sdbusplus\/bus.hpp>\n#include <phosphor-logging\/log.hpp>\n#include \"argument.hpp\"\n#include \"cooling_type.hpp\"\n#include \"sdbusplus.hpp\"\n\nusing namespace phosphor::cooling::type;\nusing namespace phosphor::fan::util;\nusing namespace phosphor::logging;\n\nint main(int argc, char* argv[])\n{\n    auto rc = 1;\n    auto options = ArgumentParser(argc, argv);\n\n    auto objpath = (options)[\"path\"];\n    if (argc < 2)\n    {\n        std::cerr << std::endl << \"Too few arguments\" << std::endl;\n        log<level::ERR>(\"Too few arguments\");\n        options.usage(argv);\n    }\n    else if (objpath == ArgumentParser::empty_string)\n    {\n        log<level::ERR>(\"Bus path argument required\");\n    }\n    else\n    {\n        auto bus = sdbusplus::bus::new_default();\n        CoolingType coolingType(bus);\n\n        try\n        {\n            auto air = (options)[\"air\"];\n            if (air != ArgumentParser::empty_string)\n            {\n                coolingType.setAirCooled();\n            }\n\n            auto water = (options)[\"water\"];\n            if (water != ArgumentParser::empty_string)\n            {\n                coolingType.setWaterCooled();\n            }\n\n            auto gpiopath = (options)[\"dev\"];\n            if (gpiopath != ArgumentParser::empty_string)\n            {\n                auto keycode = (options)[\"event\"];\n                if (keycode != ArgumentParser::empty_string)\n                {\n                    auto gpiocode = std::stoul(keycode);\n                    coolingType.readGpio(gpiopath, gpiocode);\n                }\n                else\n                {\n                    log<level::ERR>(\"--event=<keycode> argument required\\n\");\n                    return rc;\n                }\n            }\n\n            coolingType.updateInventory(objpath);\n            rc = 0;\n        }\n        catch (DBusMethodError& dme)\n        {\n            log<level::ERR>(\"Uncaught DBus method failure exception\",\n                    entry(\"BUSNAME=%s\", dme.busName.c_str()),\n                    entry(\"PATH=%s\", dme.path.c_str()),\n                    entry(\"INTERFACE=%s\", dme.interface.c_str()),\n                    entry(\"METHOD=%s\", dme.method.c_str()));\n        }\n        catch (std::exception& err)\n        {\n            log<phosphor::logging::level::ERR>(err.what());\n        }\n\n    }\n\n    return rc;\n}\n\n\/\/ vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n","avg_line_length":28.023255814,"max_line_length":77,"alphanum_fraction":0.5095435685,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":711,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <2017\/Day11Puzzle.hpp>\n#include <zeno-engine\/Utility\/StringExtensions.hpp>\n\nnamespace TwentySeventeen {\n\t\n\tDay11Puzzle::Day11Puzzle() :\n\t\tcore::PuzzleBase(\"Untitled Puzzle\", 2017, 11) {\n\n\t}\n\tDay11Puzzle::~Day11Puzzle() {\n\n\t}\n\n\n\tvoid Day11Puzzle::initialise(const core::InitialisationInfo& _initialisationInfo) {\n\t\tsetInputLines(ze::StringExtensions::splitStringByDelimeter(ze::StringExtensions::loadFileToString(_initialisationInfo.parameters[0]), \"\\n\"));\n\t}\n\n\tvoid Day11Puzzle::setInputLines(const std::vector<std::string>& _inputLines) {\n\t\tm_InputLines = std::vector<std::string>(_inputLines);\n\t}\n\n\tstd::pair<std::string, std::string> Day11Puzzle::fastSolve() {\n\t\treturn { \"Part 1\", \"Part 2\" };\n\t}\n}\n","avg_line_length":26.3333333333,"max_line_length":143,"alphanum_fraction":0.735583685,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":14609,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Copyright (c) 2012-2015 The Bitcoin Core developers\n\/\/ Copyright (c) 2014-2017 The Zalgocoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"netbase.h\"\n#include \"test\/test_zalgocoin.h\"\n\n#include <string>\n\n#include <boost\/assign\/list_of.hpp>\n#include <boost\/test\/unit_test.hpp>\n\nBOOST_FIXTURE_TEST_SUITE(netbase_tests, BasicTestingSetup)\n\nstatic CNetAddr ResolveIP(const char* ip)\n{\n    CNetAddr addr;\n    LookupHost(ip, addr, false);\n    return addr;\n}\n\nstatic CSubNet ResolveSubNet(const char* subnet)\n{\n    CSubNet ret;\n    LookupSubNet(subnet, ret);\n    return ret;\n}\n\nBOOST_AUTO_TEST_CASE(netbase_networks)\n{\n    BOOST_CHECK(ResolveIP(\"127.0.0.1\").GetNetwork()                              == NET_UNROUTABLE);\n    BOOST_CHECK(ResolveIP(\"::1\").GetNetwork()                                    == NET_UNROUTABLE);\n    BOOST_CHECK(ResolveIP(\"8.8.8.8\").GetNetwork()                                == NET_IPV4);\n    BOOST_CHECK(ResolveIP(\"2001::8888\").GetNetwork()                             == NET_IPV6);\n    BOOST_CHECK(ResolveIP(\"FD87:D87E:EB43:edb1:8e4:3588:e546:35ca\").GetNetwork() == NET_TOR);\n\n}\n\nBOOST_AUTO_TEST_CASE(netbase_properties)\n{\n\n    BOOST_CHECK(ResolveIP(\"127.0.0.1\").IsIPv4());\n    BOOST_CHECK(ResolveIP(\"::FFFF:192.168.1.1\").IsIPv4());\n    BOOST_CHECK(ResolveIP(\"::1\").IsIPv6());\n    BOOST_CHECK(ResolveIP(\"10.0.0.1\").IsRFC1918());\n    BOOST_CHECK(ResolveIP(\"192.168.1.1\").IsRFC1918());\n    BOOST_CHECK(ResolveIP(\"172.31.255.255\").IsRFC1918());\n    BOOST_CHECK(ResolveIP(\"2001:0DB8::\").IsRFC3849());\n    BOOST_CHECK(ResolveIP(\"169.254.1.1\").IsRFC3927());\n    BOOST_CHECK(ResolveIP(\"2002::1\").IsRFC3964());\n    BOOST_CHECK(ResolveIP(\"FC00::\").IsRFC4193());\n    BOOST_CHECK(ResolveIP(\"2001::2\").IsRFC4380());\n    BOOST_CHECK(ResolveIP(\"2001:10::\").IsRFC4843());\n    BOOST_CHECK(ResolveIP(\"FE80::\").IsRFC4862());\n    BOOST_CHECK(ResolveIP(\"64:FF9B::\").IsRFC6052());\n    BOOST_CHECK(ResolveIP(\"FD87:D87E:EB43:edb1:8e4:3588:e546:35ca\").IsTor());\n    BOOST_CHECK(ResolveIP(\"127.0.0.1\").IsLocal());\n    BOOST_CHECK(ResolveIP(\"::1\").IsLocal());\n    BOOST_CHECK(ResolveIP(\"8.8.8.8\").IsRoutable());\n    BOOST_CHECK(ResolveIP(\"2001::1\").IsRoutable());\n    BOOST_CHECK(ResolveIP(\"127.0.0.1\").IsValid());\n\n}\n\nbool static TestSplitHost(std::string test, std::string host, int port)\n{\n    std::string hostOut;\n    int portOut = -1;\n    SplitHostPort(test, portOut, hostOut);\n    return hostOut == host && port == portOut;\n}\n\nBOOST_AUTO_TEST_CASE(netbase_splithost)\n{\n    BOOST_CHECK(TestSplitHost(\"www.bitcoin.org\", \"www.bitcoin.org\", -1));\n    BOOST_CHECK(TestSplitHost(\"[www.bitcoin.org]\", \"www.bitcoin.org\", -1));\n    BOOST_CHECK(TestSplitHost(\"www.bitcoin.org:80\", \"www.bitcoin.org\", 80));\n    BOOST_CHECK(TestSplitHost(\"[www.bitcoin.org]:80\", \"www.bitcoin.org\", 80));\n    BOOST_CHECK(TestSplitHost(\"127.0.0.1\", \"127.0.0.1\", -1));\n    BOOST_CHECK(TestSplitHost(\"127.0.0.1:9888\", \"127.0.0.1\", 9888));\n    BOOST_CHECK(TestSplitHost(\"[127.0.0.1]\", \"127.0.0.1\", -1));\n    BOOST_CHECK(TestSplitHost(\"[127.0.0.1]:9888\", \"127.0.0.1\", 9888));\n    BOOST_CHECK(TestSplitHost(\"::ffff:127.0.0.1\", \"::ffff:127.0.0.1\", -1));\n    BOOST_CHECK(TestSplitHost(\"[::ffff:127.0.0.1]:9888\", \"::ffff:127.0.0.1\", 9888));\n    BOOST_CHECK(TestSplitHost(\"[::]:9888\", \"::\", 9888));\n    BOOST_CHECK(TestSplitHost(\"::9888\", \"::9888\", -1));\n    BOOST_CHECK(TestSplitHost(\":9888\", \"\", 9888));\n    BOOST_CHECK(TestSplitHost(\"[]:9888\", \"\", 9888));\n    BOOST_CHECK(TestSplitHost(\"\", \"\", -1));\n}\n\nbool static TestParse(std::string src, std::string canon)\n{\n    CService addr(LookupNumeric(src.c_str(), 65535));\n    return canon == addr.ToString();\n}\n\nBOOST_AUTO_TEST_CASE(netbase_lookupnumeric)\n{\n    BOOST_CHECK(TestParse(\"127.0.0.1\", \"127.0.0.1:65535\"));\n    BOOST_CHECK(TestParse(\"127.0.0.1:9888\", \"127.0.0.1:9888\"));\n    BOOST_CHECK(TestParse(\"::ffff:127.0.0.1\", \"127.0.0.1:65535\"));\n    BOOST_CHECK(TestParse(\"::\", \"[::]:65535\"));\n    BOOST_CHECK(TestParse(\"[::]:9888\", \"[::]:9888\"));\n    BOOST_CHECK(TestParse(\"[127.0.0.1]\", \"127.0.0.1:65535\"));\n    BOOST_CHECK(TestParse(\":::\", \"[::]:0\"));\n}\n\nBOOST_AUTO_TEST_CASE(onioncat_test)\n{\n\n    \/\/ values from https:\/\/web.archive.org\/web\/20121122003543\/http:\/\/www.cypherpunk.at\/onioncat\/wiki\/OnionCat\n    CNetAddr addr1(ResolveIP(\"5wyqrzbvrdsumnok.onion\"));\n    CNetAddr addr2(ResolveIP(\"FD87:D87E:EB43:edb1:8e4:3588:e546:35ca\"));\n    BOOST_CHECK(addr1 == addr2);\n    BOOST_CHECK(addr1.IsTor());\n    BOOST_CHECK(addr1.ToStringIP() == \"5wyqrzbvrdsumnok.onion\");\n    BOOST_CHECK(addr1.IsRoutable());\n\n}\n\nBOOST_AUTO_TEST_CASE(subnet_test)\n{\n\n    BOOST_CHECK(ResolveSubNet(\"1.2.3.0\/24\") == ResolveSubNet(\"1.2.3.0\/255.255.255.0\"));\n    BOOST_CHECK(ResolveSubNet(\"1.2.3.0\/24\") != ResolveSubNet(\"1.2.4.0\/255.255.255.0\"));\n    BOOST_CHECK(ResolveSubNet(\"1.2.3.0\/24\").Match(ResolveIP(\"1.2.3.4\")));\n    BOOST_CHECK(!ResolveSubNet(\"1.2.2.0\/24\").Match(ResolveIP(\"1.2.3.4\")));\n    BOOST_CHECK(ResolveSubNet(\"1.2.3.4\").Match(ResolveIP(\"1.2.3.4\")));\n    BOOST_CHECK(ResolveSubNet(\"1.2.3.4\/32\").Match(ResolveIP(\"1.2.3.4\")));\n    BOOST_CHECK(!ResolveSubNet(\"1.2.3.4\").Match(ResolveIP(\"5.6.7.8\")));\n    BOOST_CHECK(!ResolveSubNet(\"1.2.3.4\/32\").Match(ResolveIP(\"5.6.7.8\")));\n    BOOST_CHECK(ResolveSubNet(\"::ffff:127.0.0.1\").Match(ResolveIP(\"127.0.0.1\")));\n    BOOST_CHECK(ResolveSubNet(\"1:2:3:4:5:6:7:8\").Match(ResolveIP(\"1:2:3:4:5:6:7:8\")));\n    BOOST_CHECK(!ResolveSubNet(\"1:2:3:4:5:6:7:8\").Match(ResolveIP(\"1:2:3:4:5:6:7:9\")));\n    BOOST_CHECK(ResolveSubNet(\"1:2:3:4:5:6:7:0\/112\").Match(ResolveIP(\"1:2:3:4:5:6:7:1234\")));\n    BOOST_CHECK(ResolveSubNet(\"192.168.0.1\/24\").Match(ResolveIP(\"192.168.0.2\")));\n    BOOST_CHECK(ResolveSubNet(\"192.168.0.20\/29\").Match(ResolveIP(\"192.168.0.18\")));\n    BOOST_CHECK(ResolveSubNet(\"1.2.2.1\/24\").Match(ResolveIP(\"1.2.2.4\")));\n    BOOST_CHECK(ResolveSubNet(\"1.2.2.110\/31\").Match(ResolveIP(\"1.2.2.111\")));\n    BOOST_CHECK(ResolveSubNet(\"1.2.2.20\/26\").Match(ResolveIP(\"1.2.2.63\")));\n    \/\/ All-Matching IPv6 Matches arbitrary IPv4 and IPv6\n    BOOST_CHECK(ResolveSubNet(\"::\/0\").Match(ResolveIP(\"1:2:3:4:5:6:7:1234\")));\n    BOOST_CHECK(ResolveSubNet(\"::\/0\").Match(ResolveIP(\"1.2.3.4\")));\n    \/\/ All-Matching IPv4 does not Match IPv6\n    BOOST_CHECK(!ResolveSubNet(\"0.0.0.0\/0\").Match(ResolveIP(\"1:2:3:4:5:6:7:1234\")));\n    \/\/ Invalid subnets Match nothing (not even invalid addresses)\n    BOOST_CHECK(!CSubNet().Match(ResolveIP(\"1.2.3.4\")));\n    BOOST_CHECK(!ResolveSubNet(\"\").Match(ResolveIP(\"4.5.6.7\")));\n    BOOST_CHECK(!ResolveSubNet(\"bloop\").Match(ResolveIP(\"0.0.0.0\")));\n    BOOST_CHECK(!ResolveSubNet(\"bloop\").Match(ResolveIP(\"hab\")));\n    \/\/ Check valid\/invalid\n    BOOST_CHECK(ResolveSubNet(\"1.2.3.0\/0\").IsValid());\n    BOOST_CHECK(!ResolveSubNet(\"1.2.3.0\/-1\").IsValid());\n    BOOST_CHECK(ResolveSubNet(\"1.2.3.0\/32\").IsValid());\n    BOOST_CHECK(!ResolveSubNet(\"1.2.3.0\/33\").IsValid());\n    BOOST_CHECK(ResolveSubNet(\"1:2:3:4:5:6:7:8\/0\").IsValid());\n    BOOST_CHECK(ResolveSubNet(\"1:2:3:4:5:6:7:8\/33\").IsValid());\n    BOOST_CHECK(!ResolveSubNet(\"1:2:3:4:5:6:7:8\/-1\").IsValid());\n    BOOST_CHECK(ResolveSubNet(\"1:2:3:4:5:6:7:8\/128\").IsValid());\n    BOOST_CHECK(!ResolveSubNet(\"1:2:3:4:5:6:7:8\/129\").IsValid());\n    BOOST_CHECK(!ResolveSubNet(\"fuzzy\").IsValid());\n\n    \/\/CNetAddr constructor test\n    BOOST_CHECK(CSubNet(ResolveIP(\"127.0.0.1\")).IsValid());\n    BOOST_CHECK(CSubNet(ResolveIP(\"127.0.0.1\")).Match(ResolveIP(\"127.0.0.1\")));\n    BOOST_CHECK(!CSubNet(ResolveIP(\"127.0.0.1\")).Match(ResolveIP(\"127.0.0.2\")));\n    BOOST_CHECK(CSubNet(ResolveIP(\"127.0.0.1\")).ToString() == \"127.0.0.1\/32\");\n\n    CSubNet subnet = CSubNet(ResolveIP(\"1.2.3.4\"), 32);\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.3.4\/32\");\n    subnet = CSubNet(ResolveIP(\"1.2.3.4\"), 8);\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.0.0.0\/8\");\n    subnet = CSubNet(ResolveIP(\"1.2.3.4\"), 0);\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"0.0.0.0\/0\");\n\n    subnet = CSubNet(ResolveIP(\"1.2.3.4\"), ResolveIP(\"255.255.255.255\"));\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.3.4\/32\");\n    subnet = CSubNet(ResolveIP(\"1.2.3.4\"), ResolveIP(\"255.0.0.0\"));\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.0.0.0\/8\");\n    subnet = CSubNet(ResolveIP(\"1.2.3.4\"), ResolveIP(\"0.0.0.0\"));\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"0.0.0.0\/0\");\n\n    BOOST_CHECK(CSubNet(ResolveIP(\"1:2:3:4:5:6:7:8\")).IsValid());\n    BOOST_CHECK(CSubNet(ResolveIP(\"1:2:3:4:5:6:7:8\")).Match(ResolveIP(\"1:2:3:4:5:6:7:8\")));\n    BOOST_CHECK(!CSubNet(ResolveIP(\"1:2:3:4:5:6:7:8\")).Match(ResolveIP(\"1:2:3:4:5:6:7:9\")));\n    BOOST_CHECK(CSubNet(ResolveIP(\"1:2:3:4:5:6:7:8\")).ToString() == \"1:2:3:4:5:6:7:8\/128\");\n\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.255.255\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.3.4\/32\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.255.254\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.3.4\/31\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.255.252\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.3.4\/30\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.255.248\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.3.0\/29\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.255.240\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.3.0\/28\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.255.224\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.3.0\/27\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.255.192\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.3.0\/26\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.255.128\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.3.0\/25\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.255.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.3.0\/24\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.254.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.2.0\/23\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.252.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.0.0\/22\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.248.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.0.0\/21\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.240.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.0.0\/20\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.224.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.0.0\/19\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.192.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.0.0\/18\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.128.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.0.0\/17\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.0.0\/16\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.254.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.0.0\/15\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.252.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.0.0.0\/14\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.248.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.0.0.0\/13\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.240.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.0.0.0\/12\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.224.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.0.0.0\/11\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.192.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.0.0.0\/10\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.128.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.0.0.0\/9\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.0.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.0.0.0\/8\");\n    subnet = ResolveSubNet(\"1.2.3.4\/254.0.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"0.0.0.0\/7\");\n    subnet = ResolveSubNet(\"1.2.3.4\/252.0.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"0.0.0.0\/6\");\n    subnet = ResolveSubNet(\"1.2.3.4\/248.0.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"0.0.0.0\/5\");\n    subnet = ResolveSubNet(\"1.2.3.4\/240.0.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"0.0.0.0\/4\");\n    subnet = ResolveSubNet(\"1.2.3.4\/224.0.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"0.0.0.0\/3\");\n    subnet = ResolveSubNet(\"1.2.3.4\/192.0.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"0.0.0.0\/2\");\n    subnet = ResolveSubNet(\"1.2.3.4\/128.0.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"0.0.0.0\/1\");\n    subnet = ResolveSubNet(\"1.2.3.4\/0.0.0.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"0.0.0.0\/0\");\n\n    subnet = ResolveSubNet(\"1:2:3:4:5:6:7:8\/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1:2:3:4:5:6:7:8\/128\");\n    subnet = ResolveSubNet(\"1:2:3:4:5:6:7:8\/ffff:0000:0000:0000:0000:0000:0000:0000\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1::\/16\");\n    subnet = ResolveSubNet(\"1:2:3:4:5:6:7:8\/0000:0000:0000:0000:0000:0000:0000:0000\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"::\/0\");\n    subnet = ResolveSubNet(\"1.2.3.4\/255.255.232.0\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1.2.0.0\/255.255.232.0\");\n    subnet = ResolveSubNet(\"1:2:3:4:5:6:7:8\/ffff:ffff:ffff:fffe:ffff:ffff:ffff:ff0f\");\n    BOOST_CHECK_EQUAL(subnet.ToString(), \"1:2:3:4:5:6:7:8\/ffff:ffff:ffff:fffe:ffff:ffff:ffff:ff0f\");\n\n}\n\nBOOST_AUTO_TEST_CASE(netbase_getgroup)\n{\n\n    BOOST_CHECK(ResolveIP(\"127.0.0.1\").GetGroup() == boost::assign::list_of(0)); \/\/ Local -> !Routable()\n    BOOST_CHECK(ResolveIP(\"257.0.0.1\").GetGroup() == boost::assign::list_of(0)); \/\/ !Valid -> !Routable()\n    BOOST_CHECK(ResolveIP(\"10.0.0.1\").GetGroup() == boost::assign::list_of(0)); \/\/ RFC1918 -> !Routable()\n    BOOST_CHECK(ResolveIP(\"169.254.1.1\").GetGroup() == boost::assign::list_of(0)); \/\/ RFC3927 -> !Routable()\n    BOOST_CHECK(ResolveIP(\"1.2.3.4\").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); \/\/ IPv4\n    BOOST_CHECK(ResolveIP(\"::FFFF:0:102:304\").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); \/\/ RFC6145\n    BOOST_CHECK(ResolveIP(\"64:FF9B::102:304\").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); \/\/ RFC6052\n    BOOST_CHECK(ResolveIP(\"2002:102:304:9999:9999:9999:9999:9999\").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); \/\/ RFC3964\n    BOOST_CHECK(ResolveIP(\"2001:0:9999:9999:9999:9999:FEFD:FCFB\").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); \/\/ RFC4380\n    BOOST_CHECK(ResolveIP(\"FD87:D87E:EB43:edb1:8e4:3588:e546:35ca\").GetGroup() == boost::assign::list_of((unsigned char)NET_TOR)(239)); \/\/ Tor\n    BOOST_CHECK(ResolveIP(\"2001:470:abcd:9999:9999:9999:9999:9999\").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV6)(32)(1)(4)(112)(175)); \/\/he.net\n    BOOST_CHECK(ResolveIP(\"2001:2001:9999:9999:9999:9999:9999:9999\").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV6)(32)(1)(32)(1)); \/\/IPv6\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":50.5501730104,"max_line_length":160,"alphanum_fraction":0.6529536587,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":556,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include<bits\/stdc++.h>\n#include<string>\n#include<cstring>\nusing namespace std;\nint main()\n{\n    int k=0;\n    string str;\n    while(getline(cin,str))\n    {\n        for(int i=0;str[i]!='\\0';i++)\n        {\n            if(str[i]=='\"' && k%2==0)\n            {\n                cout<<\"``\";\n                ++k;\n            }\n           else if(str[i]=='\"' && k%2==1)\n            {\n                cout<<\"''\";\n                ++k;\n            }\n            else\n            {\n                cout<<str[i];\n            }\n        }cout<<endl;\n    }\n    return 0;\n}\n","avg_line_length":17.935483871,"max_line_length":41,"alphanum_fraction":0.309352518,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7130,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":5.0,"content":"\/****************************************************************************\n *\n * Copyright (c) 2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file df_isl29501_wrapper.cpp\n * Driver to access the ISL29501 of the DriverFramework.\n *\n * @author Zach Lovett <zach.lovett@3drobotics.com>\n * @author Siddharth B Purohit <sid@3drobotics.com>\n *\/\n\n#include <px4_config.h>\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <stdint.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <unistd.h>\n#include <px4_getopt.h>\n#include <errno.h>\n#include <string>\n\n#include <systemlib\/perf_counter.h>\n#include <systemlib\/err.h>\n\n#include <drivers\/drv_range_finder.h>\n\n#include <uORB\/uORB.h>\n#include <uORB\/topics\/subsystem_info.h>\n#include <uORB\/topics\/distance_sensor.h>\n\n#include <board_config.h>\n\n#include <isl29501\/isl29501.hpp>\n#include <DevMgr.hpp>\n\n\nextern \"C\" { __EXPORT int df_isl29501_wrapper_main(int argc, char *argv[]); }\n\nusing namespace DriverFramework;\n\n\nclass DfISL29501Wrapper : public ISL29501\n{\npublic:\n\tDfISL29501Wrapper();\n\t~DfISL29501Wrapper();\n\n\n\t\/**\n\t * Start automatic measurement.\n\t *\n\t * @return 0 on success\n\t *\/\n\tint\t\tstart();\n\n\t\/**\n\t * Stop automatic measurement.\n\t *\n\t * @return 0 on success\n\t *\/\n\tint\t\tstop();\n\nprivate:\n\tint _publish(struct range_sensor_data &data);\n\n\torb_advert_t\t\t_range_topic;\n\n\tint\t\t\t_orb_class_instance;\n\n\t\/\/ perf_counter_t\t\t_range_sample_perf;\n\n};\n\nDfISL29501Wrapper::DfISL29501Wrapper(\/*enum Rotation rotation*\/) :\n\tISL29501(ISL_DEVICE_PATH),\n\t_range_topic(nullptr),\n\t_orb_class_instance(-1)\n{\n}\n\nDfISL29501Wrapper::~DfISL29501Wrapper()\n{\n}\n\nint DfISL29501Wrapper::start()\n{\n\tint ret;\n\tret = ISL29501::init();\n\n\tif (ret != 0) {\n\t\tPX4_ERR(\"ISL init fail: %d\", ret);\n\t\treturn ret;\n\t}\n\n\tret = ISL29501::start();\n\n\tif (ret != 0) {\n\t\tPX4_ERR(\"ISL start fail: %d\", ret);\n\t\treturn ret;\n\t}\n\n\treturn 0;\n}\n\nint DfISL29501Wrapper::stop()\n{\n\t\/* Stop sensor. *\/\n\tint ret = ISL29501::stop();\n\n\tif (ret != 0) {\n\t\tPX4_ERR(\"ISL stop fail: %d\", ret);\n\t\treturn ret;\n\t}\n\n\treturn 0;\n}\n\nint DfISL29501Wrapper::_publish(struct range_sensor_data &data)\n{\n\tstruct distance_sensor_s d;\n\n\tmemset(&d, 0, sizeof(d));\n\n\td.timestamp = hrt_absolute_time();\n\n\td.min_distance = float(ISL_MIN_DISTANCE); \/* m *\/\n\n\td.max_distance = float(ISL_MAX_DISTANCE); \/* m *\/\n\n\td.current_distance = float(data.dist);\n\n\td.type = distance_sensor_s::MAV_DISTANCE_SENSOR_LASER;\n\n\td.id = 0; \/\/ TODO set proper ID\n\n\td.covariance = 0.0f;\n\n\tif (_range_topic == nullptr) {\n\t\t_range_topic = orb_advertise_multi(ORB_ID(distance_sensor), &d,\n\t\t\t\t\t\t   &_orb_class_instance, ORB_PRIO_DEFAULT);\n\n\t} else {\n\t\torb_publish(ORB_ID(distance_sensor), _range_topic, &d);\n\t}\n\n\t\/* Notify anyone waiting for data. *\/\n\tDevMgr::updateNotify(*this);\n\n\treturn 0;\n};\n\n\nnamespace df_isl29501_wrapper\n{\n\nDfISL29501Wrapper *g_dev = nullptr;\n\nint start();\nint stop();\nint info();\nint probe();\nint calibration();\nvoid usage();\n\nint start()\n{\n\tPX4_ERR(\"start\");\n\tg_dev = new DfISL29501Wrapper();\n\n\tif (g_dev == nullptr) {\n\t\tPX4_ERR(\"failed instantiating DfISL29501Wrapper object\");\n\t\treturn -1;\n\t}\n\n\tint ret = g_dev->start();\n\n\tif (ret != 0) {\n\t\tPX4_ERR(\"DfISL29501Wrapper start failed\");\n\t\treturn ret;\n\t}\n\n\t\/\/ Open the range sensor\n\tDevHandle h;\n\tDevMgr::getHandle(ISL_DEVICE_PATH, h);\n\n\tif (!h.isValid()) {\n\t\tDF_LOG_INFO(\"Error: unable to obtain a valid handle for the receiver at: %s (%d)\",\n\t\t\t    ISL_DEVICE_PATH, h.getError());\n\t\treturn -1;\n\t}\n\n\tDevMgr::releaseHandle(h);\n\n\treturn 0;\n}\n\nint stop()\n{\n\tif (g_dev == nullptr) {\n\t\tPX4_ERR(\"driver not running\");\n\t\treturn 1;\n\t}\n\n\tint ret = g_dev->stop();\n\n\tif (ret != 0) {\n\t\tPX4_ERR(\"driver could not be stopped\");\n\t\treturn ret;\n\t}\n\n\tdelete g_dev;\n\tg_dev = nullptr;\n\treturn 0;\n}\n\n\/**\n * Print a little info about the driver.\n *\/\nint\ninfo()\n{\n\tif (g_dev == nullptr) {\n\t\tPX4_ERR(\"driver not running\");\n\t\treturn 1;\n\t}\n\n\tPX4_DEBUG(\"state @ %p\", g_dev);\n\n\treturn 0;\n}\n\n\/**\n * Who am i\n *\/\nint\nprobe()\n{\n\tint ret;\n\n\tif (g_dev == nullptr) {\n\t\tret = start();\n\n\t\tif (ret) {\n\t\t\tPX4_ERR(\"Failed to start\");\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\tret = g_dev->probe();\n\n\tif (ret) {\n\t\tPX4_ERR(\"Failed to probe\");\n\t\treturn ret;\n\t}\n\n\tPX4_DEBUG(\"state @ %p\", g_dev);\n\n\treturn 0;\n}\n\n\/**\n * Calibration\n * runs calibration routine for ISL29501\n * TODO: implement calibration user interface and parameter system to store calib\n * Note: Currently only serves debugging purpose, user is required to manually\n * set offset inside code.\n *\/\nint\ncalibration()\n{\n\tint ret;\n\n\tif (g_dev == nullptr) {\n\t\tret = start();\n\n\t\tif (ret) {\n\t\t\tPX4_ERR(\"Failed to start\");\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\tret = g_dev->calibration();\n\n\tif (ret) {\n\t\tPX4_ERR(\"Failed to calibrate\");\n\t\treturn ret;\n\t}\n\n\tPX4_DEBUG(\"state @ %p\", g_dev);\n\n\treturn 0;\n}\n\n\nvoid\nusage()\n{\n\tPX4_WARN(\"Usage: df_isl_wrapper 'start', 'info', 'stop', 'calib', 'probe'\");\n}\n\n} \/\/ namespace df_isl_wrapper\n\n\nint\ndf_isl29501_wrapper_main(int argc, char *argv[])\n{\n\tint ret = 0;\n\tint myoptind = 1;\n\n\tif (argc <= 1) {\n\t\tdf_isl29501_wrapper::usage();\n\t\treturn 1;\n\t}\n\n\tconst char *verb = argv[myoptind];\n\n\n\tif (!strcmp(verb, \"start\")) {\n\t\tret = df_isl29501_wrapper::start(\/*rotation*\/);\n\t}\n\n\telse if (!strcmp(verb, \"stop\")) {\n\t\tret = df_isl29501_wrapper::stop();\n\t}\n\n\telse if (!strcmp(verb, \"info\")) {\n\t\tret = df_isl29501_wrapper::info();\n\t}\n\n\telse if (!strcmp(verb, \"probe\")) {\n\t\tret = df_isl29501_wrapper::probe();\n\t}\n\n\telse if (!strcmp(verb, \"calib\")) {\n\t\tdf_isl29501_wrapper::calibration();\n\t\treturn 1;\n\t}\n\n\telse {\n\t\tdf_isl29501_wrapper::usage();\n\t\treturn 1;\n\t}\n\n\treturn ret;\n}\n","avg_line_length":18.7631578947,"max_line_length":84,"alphanum_fraction":0.6680224404,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4595,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":43.0,"content":"\/*\n * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <tencentcloud\/dcdb\/v20180411\/model\/DescribeShardSpecResponse.h>\n#include <tencentcloud\/core\/utils\/rapidjson\/document.h>\n#include <tencentcloud\/core\/utils\/rapidjson\/writer.h>\n#include <tencentcloud\/core\/utils\/rapidjson\/stringbuffer.h>\n\nusing TencentCloud::CoreInternalOutcome;\nusing namespace TencentCloud::Dcdb::V20180411::Model;\nusing namespace std;\n\nDescribeShardSpecResponse::DescribeShardSpecResponse() :\n    m_specConfigHasBeenSet(false)\n{\n}\n\nCoreInternalOutcome DescribeShardSpecResponse::Deserialize(const string &payload)\n{\n    rapidjson::Document d;\n    d.Parse(payload.c_str());\n    if (d.HasParseError() || !d.IsObject())\n    {\n        return CoreInternalOutcome(Core::Error(\"response not json format\"));\n    }\n    if (!d.HasMember(\"Response\") || !d[\"Response\"].IsObject())\n    {\n        return CoreInternalOutcome(Core::Error(\"response `Response` is null or not object\"));\n    }\n    rapidjson::Value &rsp = d[\"Response\"];\n    if (!rsp.HasMember(\"RequestId\") || !rsp[\"RequestId\"].IsString())\n    {\n        return CoreInternalOutcome(Core::Error(\"response `Response.RequestId` is null or not string\"));\n    }\n    string requestId(rsp[\"RequestId\"].GetString());\n    SetRequestId(requestId);\n\n    if (rsp.HasMember(\"Error\"))\n    {\n        if (!rsp[\"Error\"].IsObject() ||\n            !rsp[\"Error\"].HasMember(\"Code\") || !rsp[\"Error\"][\"Code\"].IsString() ||\n            !rsp[\"Error\"].HasMember(\"Message\") || !rsp[\"Error\"][\"Message\"].IsString())\n        {\n            return CoreInternalOutcome(Core::Error(\"response `Response.Error` format error\").SetRequestId(requestId));\n        }\n        string errorCode(rsp[\"Error\"][\"Code\"].GetString());\n        string errorMsg(rsp[\"Error\"][\"Message\"].GetString());\n        return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));\n    }\n\n\n    if (rsp.HasMember(\"SpecConfig\") && !rsp[\"SpecConfig\"].IsNull())\n    {\n        if (!rsp[\"SpecConfig\"].IsArray())\n            return CoreInternalOutcome(Core::Error(\"response `SpecConfig` is not array type\"));\n\n        const rapidjson::Value &tmpValue = rsp[\"SpecConfig\"];\n        for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)\n        {\n            SpecConfig item;\n            CoreInternalOutcome outcome = item.Deserialize(*itr);\n            if (!outcome.IsSuccess())\n            {\n                outcome.GetError().SetRequestId(requestId);\n                return outcome;\n            }\n            m_specConfig.push_back(item);\n        }\n        m_specConfigHasBeenSet = true;\n    }\n\n\n    return CoreInternalOutcome(true);\n}\n\nstring DescribeShardSpecResponse::ToJsonString() const\n{\n    rapidjson::Document value;\n    value.SetObject();\n    rapidjson::Document::AllocatorType& allocator = value.GetAllocator();\n\n    if (m_specConfigHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"SpecConfig\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);\n\n        int i=0;\n        for (auto itr = m_specConfig.begin(); itr != m_specConfig.end(); ++itr, ++i)\n        {\n            value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);\n            (*itr).ToJsonObject(value[key.c_str()][i], allocator);\n        }\n    }\n\n    rapidjson::Value iKey(rapidjson::kStringType);\n    string key = \"RequestId\";\n    iKey.SetString(key.c_str(), allocator);\n    value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);\n    \n    rapidjson::StringBuffer buffer;\n    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n    value.Accept(writer);\n    return buffer.GetString();\n}\n\n\nvector<SpecConfig> DescribeShardSpecResponse::GetSpecConfig() const\n{\n    return m_specConfig;\n}\n\nbool DescribeShardSpecResponse::SpecConfigHasBeenSet() const\n{\n    return m_specConfigHasBeenSet;\n}\n\n\n","avg_line_length":34.5488721805,"max_line_length":118,"alphanum_fraction":0.6663764962,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":12014,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <vector>\r\n#include <boost\/test\/unit_test.hpp>\r\n#include <boost\/foreach.hpp>\r\n\r\n#include \"main.h\"\r\n#include \"wallet.h\"\r\n#include \"util.h\"\r\n\r\nusing namespace std;\r\n\r\nBOOST_AUTO_TEST_SUITE(util_tests)\r\n\r\nBOOST_AUTO_TEST_CASE(util_criticalsection)\r\n{\r\n    CCriticalSection cs;\r\n\r\n    do {\r\n        LOCK(cs);\r\n        break;\r\n\r\n        BOOST_ERROR(\"break was swallowed!\");\r\n    } while(0);\r\n\r\n    do {\r\n        TRY_LOCK(cs, lockTest);\r\n        if (lockTest)\r\n            break;\r\n\r\n        BOOST_ERROR(\"break was swallowed!\");\r\n    } while(0);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(util_MedianFilter)\r\n{    \r\n    CMedianFilter<int> filter(5, 15);\r\n\r\n    BOOST_CHECK_EQUAL(filter.median(), 15);\r\n\r\n    filter.input(20); \/\/ [15 20]\r\n    BOOST_CHECK_EQUAL(filter.median(), 17);\r\n\r\n    filter.input(30); \/\/ [15 20 30]\r\n    BOOST_CHECK_EQUAL(filter.median(), 20);\r\n\r\n    filter.input(3); \/\/ [3 15 20 30]\r\n    BOOST_CHECK_EQUAL(filter.median(), 17);\r\n\r\n    filter.input(7); \/\/ [3 7 15 20 30]\r\n    BOOST_CHECK_EQUAL(filter.median(), 15);\r\n\r\n    filter.input(18); \/\/ [3 7 18 20 30]\r\n    BOOST_CHECK_EQUAL(filter.median(), 18);\r\n\r\n    filter.input(0); \/\/ [0 3 7 18 30]\r\n    BOOST_CHECK_EQUAL(filter.median(), 7);\r\n}\r\n\r\nstatic const unsigned char ParseHex_expected[65] = {\r\n    0x04, 0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, 0x48, 0x27, 0x19, 0x67, 0xf1, 0xa6, 0x71, 0x30, 0xb7, \r\n    0x10, 0x5c, 0xd6, 0xa8, 0x28, 0xe0, 0x39, 0x09, 0xa6, 0x79, 0x62, 0xe0, 0xea, 0x1f, 0x61, 0xde, \r\n    0xb6, 0x49, 0xf6, 0xbc, 0x3f, 0x4c, 0xef, 0x38, 0xc4, 0xf3, 0x55, 0x04, 0xe5, 0x1e, 0xc1, 0x12, \r\n    0xde, 0x5c, 0x38, 0x4d, 0xf7, 0xba, 0x0b, 0x8d, 0x57, 0x8a, 0x4c, 0x70, 0x2b, 0x6b, 0xf1, 0x1d, \r\n    0x5f\r\n};\r\nBOOST_AUTO_TEST_CASE(util_ParseHex)\r\n{\r\n    std::vector<unsigned char> result;\r\n    std::vector<unsigned char> expected(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected));\r\n    \/\/ Basic test vector\r\n    result = ParseHex(\"04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f\");\r\n    BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());\r\n\r\n    \/\/ Spaces between bytes must be supported\r\n    result = ParseHex(\"12 34 56 78\");\r\n    BOOST_CHECK(result.size() == 4 && result[0] == 0x12 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78);\r\n\r\n    \/\/ Stop parsing at invalid value\r\n    result = ParseHex(\"1234 invalid 1234\");\r\n    BOOST_CHECK(result.size() == 2 && result[0] == 0x12 && result[1] == 0x34);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(util_HexStr)\r\n{\r\n    BOOST_CHECK_EQUAL(\r\n        HexStr(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected)),\r\n        \"04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f\");\r\n\r\n    BOOST_CHECK_EQUAL(\r\n        HexStr(ParseHex_expected, ParseHex_expected + 5, true),\r\n        \"04 67 8a fd b0\");\r\n\r\n    BOOST_CHECK_EQUAL(\r\n        HexStr(ParseHex_expected, ParseHex_expected, true),\r\n        \"\");\r\n\r\n    std::vector<unsigned char> ParseHex_vec(ParseHex_expected, ParseHex_expected + 5);\r\n\r\n    BOOST_CHECK_EQUAL(\r\n        HexStr(ParseHex_vec, true),\r\n        \"04 67 8a fd b0\");\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(util_DateTimeStrFormat)\r\n{\r\n\/*These are platform-dependant and thus removed to avoid useless test failures\r\n    BOOST_CHECK_EQUAL(DateTimeStrFormat(\"%x %H:%M:%S\", 0), \"01\/01\/70 00:00:00\");\r\n    BOOST_CHECK_EQUAL(DateTimeStrFormat(\"%x %H:%M:%S\", 0x7FFFFFFF), \"01\/19\/38 03:14:07\");\r\n    \/\/ Formats used within Bitcoin\r\n    BOOST_CHECK_EQUAL(DateTimeStrFormat(\"%x %H:%M:%S\", 1317425777), \"09\/30\/11 23:36:17\");\r\n    BOOST_CHECK_EQUAL(DateTimeStrFormat(\"%x %H:%M\", 1317425777), \"09\/30\/11 23:36\");\r\n*\/\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(util_ParseParameters)\r\n{\r\n    const char *argv_test[] = {\"-ignored\", \"-a\", \"-b\", \"-ccc=argument\", \"-ccc=multiple\", \"f\", \"-d=e\"};\r\n\r\n    ParseParameters(0, (char**)argv_test);\r\n    BOOST_CHECK(mapArgs.empty() && mapMultiArgs.empty());\r\n\r\n    ParseParameters(1, (char**)argv_test);\r\n    BOOST_CHECK(mapArgs.empty() && mapMultiArgs.empty());\r\n\r\n    ParseParameters(5, (char**)argv_test);\r\n    \/\/ expectation: -ignored is ignored (program name argument), \r\n    \/\/ -a, -b and -ccc end up in map, -d ignored because it is after\r\n    \/\/ a non-option argument (non-GNU option parsing)\r\n    BOOST_CHECK(mapArgs.size() == 3 && mapMultiArgs.size() == 3);\r\n    BOOST_CHECK(mapArgs.count(\"-a\") && mapArgs.count(\"-b\") && mapArgs.count(\"-ccc\") \r\n                && !mapArgs.count(\"f\") && !mapArgs.count(\"-d\"));\r\n    BOOST_CHECK(mapMultiArgs.count(\"-a\") && mapMultiArgs.count(\"-b\") && mapMultiArgs.count(\"-ccc\") \r\n                && !mapMultiArgs.count(\"f\") && !mapMultiArgs.count(\"-d\"));\r\n\r\n    BOOST_CHECK(mapArgs[\"-a\"] == \"\" && mapArgs[\"-ccc\"] == \"multiple\");\r\n    BOOST_CHECK(mapMultiArgs[\"-ccc\"].size() == 2);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(util_GetArg)\r\n{\r\n    mapArgs.clear();\r\n    mapArgs[\"strtest1\"] = \"string...\";\r\n    \/\/ strtest2 undefined on purpose\r\n    mapArgs[\"inttest1\"] = \"12345\";\r\n    mapArgs[\"inttest2\"] = \"81985529216486895\";\r\n    \/\/ inttest3 undefined on purpose\r\n    mapArgs[\"booltest1\"] = \"\";\r\n    \/\/ booltest2 undefined on purpose\r\n    mapArgs[\"booltest3\"] = \"0\";\r\n    mapArgs[\"booltest4\"] = \"1\";\r\n\r\n    BOOST_CHECK_EQUAL(GetArg(\"strtest1\", \"default\"), \"string...\");\r\n    BOOST_CHECK_EQUAL(GetArg(\"strtest2\", \"default\"), \"default\");\r\n    BOOST_CHECK_EQUAL(GetArg(\"inttest1\", -1), 12345);\r\n    BOOST_CHECK_EQUAL(GetArg(\"inttest2\", -1), 81985529216486895LL);\r\n    BOOST_CHECK_EQUAL(GetArg(\"inttest3\", -1), -1);\r\n    BOOST_CHECK_EQUAL(GetBoolArg(\"booltest1\"), true);\r\n    BOOST_CHECK_EQUAL(GetBoolArg(\"booltest2\"), false);\r\n    BOOST_CHECK_EQUAL(GetBoolArg(\"booltest3\"), false);\r\n    BOOST_CHECK_EQUAL(GetBoolArg(\"booltest4\"), true);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(util_WildcardMatch)\r\n{\r\n    BOOST_CHECK(WildcardMatch(\"127.0.0.1\", \"*\"));\r\n    BOOST_CHECK(WildcardMatch(\"127.0.0.1\", \"127.*\"));\r\n    BOOST_CHECK(WildcardMatch(\"abcdef\", \"a?cde?\"));\r\n    BOOST_CHECK(!WildcardMatch(\"abcdef\", \"a?cde??\"));\r\n    BOOST_CHECK(WildcardMatch(\"abcdef\", \"a*f\"));\r\n    BOOST_CHECK(!WildcardMatch(\"abcdef\", \"a*x\"));\r\n    BOOST_CHECK(WildcardMatch(\"\", \"*\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(util_FormatMoney)\r\n{\r\n    BOOST_CHECK_EQUAL(FormatMoney(0, false), \"0.00\");\r\n    BOOST_CHECK_EQUAL(FormatMoney((COIN\/10000)*123456789, false), \"12345.6789\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN, true), \"+1.00\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(-COIN, false), \"-1.00\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(-COIN, true), \"-1.00\");\r\n\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN*100000000, false), \"100000000.00\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN*10000000, false), \"10000000.00\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN*1000000, false), \"1000000.00\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN*100000, false), \"100000.00\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN*10000, false), \"10000.00\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN*1000, false), \"1000.00\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN*100, false), \"100.00\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN*10, false), \"10.00\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN, false), \"1.00\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN\/10, false), \"0.10\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN\/100, false), \"0.01\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN\/1000, false), \"0.001\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN\/10000, false), \"0.0001\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN\/100000, false), \"0.00001\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN\/1000000, false), \"0.000001\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN\/10000000, false), \"0.0000001\");\r\n    BOOST_CHECK_EQUAL(FormatMoney(COIN\/100000000, false), \"0.00000001\");\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(util_ParseMoney)\r\n{\r\n    int64 ret = 0;\r\n    BOOST_CHECK(ParseMoney(\"0.0\", ret));\r\n    BOOST_CHECK_EQUAL(ret, 0);\r\n\r\n    BOOST_CHECK(ParseMoney(\"12345.6789\", ret));\r\n    BOOST_CHECK_EQUAL(ret, (COIN\/10000)*123456789);\r\n\r\n    BOOST_CHECK(ParseMoney(\"100000000.00\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN*100000000);\r\n    BOOST_CHECK(ParseMoney(\"10000000.00\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN*10000000);\r\n    BOOST_CHECK(ParseMoney(\"1000000.00\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN*1000000);\r\n    BOOST_CHECK(ParseMoney(\"100000.00\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN*100000);\r\n    BOOST_CHECK(ParseMoney(\"10000.00\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN*10000);\r\n    BOOST_CHECK(ParseMoney(\"1000.00\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN*1000);\r\n    BOOST_CHECK(ParseMoney(\"100.00\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN*100);\r\n    BOOST_CHECK(ParseMoney(\"10.00\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN*10);\r\n    BOOST_CHECK(ParseMoney(\"1.00\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN);\r\n    BOOST_CHECK(ParseMoney(\"0.1\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN\/10);\r\n    BOOST_CHECK(ParseMoney(\"0.01\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN\/100);\r\n    BOOST_CHECK(ParseMoney(\"0.001\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN\/1000);\r\n    BOOST_CHECK(ParseMoney(\"0.0001\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN\/10000);\r\n    BOOST_CHECK(ParseMoney(\"0.00001\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN\/100000);\r\n    BOOST_CHECK(ParseMoney(\"0.000001\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN\/1000000);\r\n    BOOST_CHECK(ParseMoney(\"0.0000001\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN\/10000000);\r\n    BOOST_CHECK(ParseMoney(\"0.00000001\", ret));\r\n    BOOST_CHECK_EQUAL(ret, COIN\/100000000);\r\n\r\n    \/\/ Attempted 63 bit overflow should fail\r\n    BOOST_CHECK(!ParseMoney(\"92233720368.54775808\", ret));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(util_IsHex)\r\n{\r\n    BOOST_CHECK(IsHex(\"00\"));\r\n    BOOST_CHECK(IsHex(\"00112233445566778899aabbccddeeffAABBCCDDEEFF\"));\r\n    BOOST_CHECK(IsHex(\"ff\"));\r\n    BOOST_CHECK(IsHex(\"FF\"));\r\n\r\n    BOOST_CHECK(!IsHex(\"\"));\r\n    BOOST_CHECK(!IsHex(\"0\"));\r\n    BOOST_CHECK(!IsHex(\"a\"));\r\n    BOOST_CHECK(!IsHex(\"eleven\"));\r\n    BOOST_CHECK(!IsHex(\"00xx00\"));\r\n    BOOST_CHECK(!IsHex(\"0x0000\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(util_seed_insecure_rand)\r\n{\r\n    \/\/ Expected results for the determinstic seed.\r\n    const uint32_t exp_vals[11] = {  91632771U,1889679809U,3842137544U,3256031132U,\r\n                                   1761911779U, 489223532U,2692793790U,2737472863U,\r\n                                   2796262275U,1309899767U,840571781U};\r\n    \/\/ Expected 0s in rand()%(idx+2) for the determinstic seed.\r\n    const int exp_count[9] = {5013,3346,2415,1972,1644,1386,1176,1096,1009};\r\n    int i;\r\n    int count=0;\r\n\r\n    seed_insecure_rand();\r\n\r\n    \/\/Does the non-determistic rand give us results that look too like the determinstic one?\r\n    for (i=0;i<10;i++)\r\n    {\r\n        int match = 0;\r\n        uint32_t rval = insecure_rand();\r\n        for (int j=0;j<11;j++)match |= rval==exp_vals[j];\r\n        count += match;\r\n    }\r\n    \/\/ sum(binomial(10,i)*(11\/(2^32))^i*(1-(11\/(2^32)))^(10-i),i,0,4) ~= 1-1\/2^134.73\r\n    \/\/ So _very_ unlikely to throw a false failure here.\r\n    BOOST_CHECK(count<=4);\r\n\r\n    for (int mod=2;mod<11;mod++)\r\n    {\r\n        int mask = 1;\r\n        \/\/ Really rough binomal confidence approximation.\r\n        int err = 30*10000.\/mod*sqrt((1.\/mod*(1-1.\/mod))\/10000.);\r\n        \/\/mask is 2^ceil(log2(mod))-1\r\n        while(mask<mod-1)mask=(mask<<1)+1;\r\n\r\n        count = 0;\r\n        \/\/How often does it get a zero from the uniform range [0,mod)?\r\n        for (i=0;i<10000;i++)\r\n        {\r\n            uint32_t rval;\r\n            do{\r\n                rval=insecure_rand()&mask;\r\n            }while(rval>=(uint32_t)mod);\r\n            count += rval==0;\r\n        }\r\n        BOOST_CHECK(count<=10000\/mod+err);\r\n        BOOST_CHECK(count>=10000\/mod-err);\r\n    }\r\n\r\n    seed_insecure_rand(true);\r\n\r\n    for (i=0;i<11;i++)\r\n    {\r\n        BOOST_CHECK_EQUAL(insecure_rand(),exp_vals[i]);\r\n    }\r\n\r\n    for (int mod=2;mod<11;mod++)\r\n    {\r\n        count = 0;\r\n        for (i=0;i<10000;i++) count += insecure_rand()%mod==0;\r\n        BOOST_CHECK_EQUAL(count,exp_count[mod-2]);\r\n    }\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n","avg_line_length":36.7400611621,"max_line_length":157,"alphanum_fraction":0.6415015815,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8139,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":7.0,"content":"\/\/\n\/\/ Created by AJ Poulter on 24\/05\/2018.\n\/\/\n\n#include \"SRUP_Observed_Base.h\"\n\nSRUP_MSG_OBS_BASE::SRUP_MSG_OBS_BASE()\n{\n    m_crypto = new SRUP_Crypto();\n}\n\nSRUP_MSG_OBS_BASE::~SRUP_MSG_OBS_BASE()\n{\n    delete(m_crypto);\n}\n\nconst uint8_t *SRUP_MSG_OBS_BASE::encrypted_data(bool key_string, char* key)\n{\n    if (m_crypto->crypt() != nullptr)\n    {\n        if (key_string)\n            return m_crypto->Decrypt(key);\n        else\n            return m_crypto->DecryptF(key);\n    }\n    else\n        return nullptr;\n}\n\nbool SRUP_MSG_OBS_BASE::encrypt_data(uint8_t *data, uint16_t length, bool key_string, char* key)\n{\n     if (key_string)\n         return(m_crypto->Encrypt(data, length, key));\n     else\n         return(m_crypto->EncryptF(data, length, key));\n}\n\nunsigned char *SRUP_MSG_OBS_BASE::Serialized()\n{\n    if (Serialize(false))\n        return m_serialized;\n    else\n        return nullptr;\n}\n\nbool SRUP_MSG_OBS_BASE::DeSerialize(const uint8_t *serial_data)\n{\n    uint16_t x;\n    uint32_t p=0;\n    uint8_t bytes[2];\n\n    \/\/ We need to unmarshall the data to reconstruct the object...\n    \/\/ We can start with the two bytes for the header.\n    \/\/ One for the version - and one for the message type.\n\n    std::memcpy(m_version, (uint8_t*) serial_data, 1);\n    p+=1;\n    std::memcpy(m_msgtype, (uint8_t*) serial_data + p, 1);\n    p+=1;\n\n    \/\/ Now we have to unmarshall the sequence ID...\n    uint8_t sid_bytes[8];\n    for (unsigned char & sid_byte : sid_bytes)\n    {\n        std::memcpy(&sid_byte, (uint8_t*) serial_data + p, 1);\n        ++p;\n    }\n\n    \/\/ ... then we copy them into m_sequence_ID\n    if (m_sequence_ID != nullptr)\n        delete(m_sequence_ID);\n    m_sequence_ID = new uint64_t;\n    std::memcpy(m_sequence_ID, sid_bytes, 8);\n\n    \/\/ Next we have to unmarshall the sender ID...\n    uint8_t snd_bytes[8];\n    for (unsigned char & snd_byte : snd_bytes)\n    {\n        std::memcpy(&snd_byte, (uint8_t*) serial_data + p, 1);\n        ++p;\n    }\n\n    \/\/ ... then we copy them into the sender ID\n    if (m_sender_ID != nullptr)\n        delete(m_sender_ID);\n    m_sender_ID = new uint64_t;\n    std::memcpy(m_sender_ID, snd_bytes, 8);\n\n    \/\/ Now we have two-bytes for the size of the token ... and x bytes for the token\n    std::memcpy(bytes, serial_data + p, 2);\n    x = decodeLength(bytes);\n    p+=2;\n    delete[] m_token;\n    m_token = new uint8_t[x+1];\n    std::memcpy(m_token, (uint8_t *) serial_data + p, x);\n    m_token_len = x;\n    p+=x;\n\n    \/\/ The next two bytes are the size of the signature...\n    std::memcpy(bytes, serial_data + p, 2);\n    x = decodeLength(bytes);\n    p+=2;\n\n    m_sig_len = x;\n\n    \/\/ The next x bytes are the value of the signature.\n    delete[] m_signature;\n    m_signature = new uint8_t[x];\n    std::memcpy(m_signature, serial_data + p, x);\n\n    p+=x;\n\n    \/\/ Lastly we have the encrypted data.\n    std::memcpy(bytes, serial_data + p, 2);\n    x = decodeLength(bytes);\n    p+=2;\n\n    auto* encrypted_data = new uint8_t[x];\n\n    std::memcpy(encrypted_data, (uint8_t *) serial_data + p, x);\n    m_crypto->crypt(encrypted_data, x);\n\n    delete[] encrypted_data;\n\n    return true;\n}\n\nuint32_t SRUP_MSG_OBS_BASE::SerializedLength()\n{\n    if (!m_is_serialized)\n        Serialize(false);\n\n    return m_serial_length;\n}\n\nbool SRUP_MSG_OBS_BASE::Serialize(bool preSign)\n{\n    \/\/ As we're using dynamic memory - and only storing \/ sending the length of the data we have\n    \/\/ we need to know how long all of the fields are so that we can unmarshall the data at\n    \/\/ the other end...\n\n    const uint16_t header_size = 18; \/\/ Two-bytes for the main header - plus 8 for the sequence ID & 8 for the sender ID...\n    const uint8_t field_length_size = 2;\n\n    \/\/ We need the number of variable length fields - including the m_sig_len...\n    \/\/ ... this can't be const as we need to change it depending on whether or not we're in pre-sign.\n    \/\/ (If we are we need to reduce it by one for the unused m_sig_len)\n    \/\/ Here it will be 3 - signature, token, and encrypted_data...\n    uint8_t var_length_field_count = 3;\n\n    uint32_t serial_len;\n    uint32_t p=0;\n\n    uint8_t * msb;\n    uint8_t * lsb;\n\n    if (m_token == nullptr)\n        return false;\n\n    \/\/ Now check that we have a sequence ID...\n    if (m_sequence_ID == nullptr)\n        return false;\n\n    \/\/ ...and check that we have a sender ID ...\n    if (m_sender_ID == nullptr)\n        return false;\n\n    msb=new uint8_t[1];\n    lsb=new uint8_t[1];\n\n    \/\/ If we're calling this as a prelude to signing \/ verifying then we need to exclude the signature data from the\n    \/\/ serial data we generate...\n\n    if (preSign)\n    {\n        serial_len = m_token_len + m_crypto->cryptLen();\n        var_length_field_count--;\n    }\n    else\n        serial_len = m_sig_len + m_token_len + m_crypto->cryptLen();\n\n    m_serial_length = serial_len + header_size + (field_length_size * var_length_field_count);\n\n    delete[] m_serialized;\n\n    m_serialized = new uint8_t[m_serial_length];\n    std::memset(m_serialized, 0, m_serial_length);\n\n    \/\/ The first two fields are fixed length (1 byte each).\n    std::memcpy(m_serialized, m_version, 1);\n    p+=1;\n    std::memcpy(m_serialized + p, m_msgtype, 1);\n    p+=1;\n\n    \/\/ Now we need to add the Sequence ID (uint64_t)\n    \/\/ See SRUP_Init.cpp for details...\n    for (int x=0;x<8;x++)\n    {\n        uint8_t byte;\n        byte = getByteVal(*m_sequence_ID, x);\n        std::memcpy(m_serialized + p, &byte, 1);\n        p+=1;\n    }\n\n    \/\/ And we need to do the same thing for the Sender ID (uint64_t)\n    for (int x=0;x<8;x++)\n    {\n        uint8_t byte;\n        byte = getByteVal(*m_sender_ID, x);\n        std::memcpy(m_serialized + p, &byte, 1);\n        p+=1;\n    }\n\n    \/\/ For the other fields need their length to be specified...\n\n    \/\/ The token...\n    encodeLength(lsb, msb, m_token_len);\n    std::memcpy(m_serialized + p, msb, 1);\n    p+=1;\n    std::memcpy(m_serialized + p, lsb, 1);\n    p+=1;\n    std::memcpy(m_serialized + p, m_token, m_token_len);\n    p+=m_token_len;\n\n    \/\/ If we're executing Serialize as a part of generating the signature - we can't marshall the signature\n    \/\/ as we haven't calculated it yet. So only do the signature if we're not in preSign\n\n    if (!preSign)\n    {\n        if (m_signature == nullptr)\n        {\n            delete[] msb;\n            delete[] lsb;\n            return false;\n        }\n        else\n        {\n            if (m_sig_len == 0)\n            {\n                delete[] msb;\n                delete[] lsb;\n                return false;\n            }\n            else\n            {\n                encodeLength(lsb, msb, m_sig_len);\n                std::memcpy(m_serialized + p, msb, 1);\n                p += 1;\n                std::memcpy(m_serialized + p, lsb, 1);\n                p += 1;\n                std::memcpy(m_serialized + p, m_signature, m_sig_len);\n                p += m_sig_len;\n            }\n        }\n    }\n\n    \/\/ Lastly we need to add the encrypted data...\n    int crypt_len = m_crypto->cryptLen();\n    encodeLength(lsb, msb, crypt_len);\n    std::memcpy(m_serialized + p, msb, 1);\n    p+=1;\n    std::memcpy(m_serialized + p, lsb, 1);\n    p+=1;\n\n    uint8_t* encrypted_data=m_crypto->crypt();\n    std::memcpy(m_serialized + p, encrypted_data, crypt_len);\n    \/\/ p+=crypt_len; - Not used as this is the final operation\n\n    delete[] msb;\n    delete[] lsb;\n\n    \/\/ If we're in preSign we don't have a real value for m_serialized - so copy the data to m_unsigned_message\n    \/\/ and discard (and reset) m_serialized & m_serial_length...\n    if (preSign)\n    {\n        delete[] m_unsigned_message;\n        m_unsigned_message = new unsigned char[m_serial_length];\n\n        std::memcpy(m_unsigned_message, m_serialized, m_serial_length);\n        m_unsigned_length = m_serial_length;\n\n        m_serial_length = 0;\n        delete[] m_serialized;\n        m_serialized = nullptr;\n    }\n\n    m_is_serialized = true;\n    return true;\n}\n\nbool SRUP_MSG_OBS_BASE::DataCheck()\n{\n    if ((m_crypto->crypt() != nullptr) && (m_token != nullptr) && (m_sequence_ID != nullptr) && (m_sender_ID != nullptr))\n        return true;\n    else\n        return false;\n}\n\n\n","avg_line_length":27.13,"max_line_length":123,"alphanum_fraction":0.6083056887,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1833,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1460.0,"content":"\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2018 Nathan Osman\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include <QPixmap>\n\n#include <nitroshare\/application.h>\n\n#include \"conclusionpage.h\"\n#include \"devicepage.h\"\n#include \"discoverypage.h\"\n#include \"intropage.h\"\n#include \"wizard.h\"\n\nWizard::Wizard(Application *application)\n    : mApplication(application)\n{\n    setPixmap(QWizard::LogoPixmap, QPixmap(\":\/wizard\/logo.png\"));\n    setWizardStyle(QWizard::ModernStyle);\n    setWindowTitle(tr(\"Setup Wizard\"));\n\n    \/\/ Adjust the wizard to a reasonable size\n    resize(400, 300);\n\n    addPage(new IntroPage);\n    addPage(new DevicePage(application->deviceName()));\n    addPage(new DiscoveryPage);\n    addPage(new ConclusionPage);\n}\n\nvoid Wizard::accept()\n{\n    \/\/ TODO\n\n    QWizard::accept();\n}\n","avg_line_length":32.1578947368,"max_line_length":79,"alphanum_fraction":0.7354064375,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":39284,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":7.0,"content":"\/\/=========================================================================\n\/\/ Copyright (C) 2012 The Elastos Open Source Project\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/=========================================================================\n\n#include \"Elastos.Droid.Widget.h\"\n#include <Elastos.CoreLibrary.IO.h>\n#include <Elastos.CoreLibrary.Utility.h>\n#include \"elastos\/droid\/widget\/ImageView.h\"\n#include \"elastos\/droid\/graphics\/CPaint.h\"\n#include \"elastos\/droid\/graphics\/CMatrix.h\"\n#include \"elastos\/droid\/graphics\/CCanvas.h\"\n#include \"elastos\/droid\/graphics\/CPorterDuffColorFilter.h\"\n#include \"elastos\/droid\/graphics\/CRectF.h\"\n#include \"elastos\/droid\/graphics\/drawable\/CBitmapDrawable.h\"\n#include \"elastos\/droid\/graphics\/drawable\/CDrawableHelper.h\"\n#include \"elastos\/droid\/graphics\/drawable\/Drawable.h\"\n#include \"elastos\/droid\/os\/Build.h\"\n#include \"elastos\/droid\/R.h\"\n#include \"elastos\/droid\/text\/TextUtils.h\"\n#include <elastos\/core\/StringBuffer.h>\n#include <elastos\/core\/Math.h>\n#include <elastos\/utility\/logging\/Logger.h>\n\nusing Elastos::Droid::Content::IContentResolver;\nusing Elastos::Droid::Content::IContentResolverOpenResourceIdResult;\nusing Elastos::Droid::Content::Pm::IApplicationInfo;\nusing Elastos::Droid::Graphics::CMatrix;\nusing Elastos::Droid::Graphics::CPorterDuffColorFilter;\nusing Elastos::Droid::Graphics::CRectF;\nusing Elastos::Droid::Graphics::IPixelFormat;\nusing Elastos::Droid::Graphics::IPorterDuffColorFilter;\nusing Elastos::Droid::Graphics::Drawable::CBitmapDrawable;\nusing Elastos::Droid::Graphics::Drawable::EIID_IDrawableCallback;\nusing Elastos::Droid::Graphics::Drawable::IBitmapDrawable;\nusing Elastos::Droid::Graphics::Drawable::IDrawableHelper;\nusing Elastos::Droid::Graphics::Drawable::CDrawableHelper;\nusing Elastos::Droid::Graphics::Drawable::IDrawableCallback;\nusing Elastos::Droid::Graphics::Drawable::Drawable;\nusing Elastos::Droid::Os::Build;\nusing Elastos::Droid::Text::TextUtils;\nusing Elastos::Droid::View::Accessibility::IAccessibilityRecord;\nusing Elastos::Droid::View::IView;\nusing Elastos::Core::StringBuffer;\nusing Elastos::Utility::Logging::Logger;\n\nnamespace Elastos {\nnamespace Droid {\nnamespace Widget {\n\nstatic const String TAG(\"ImageView\");\n\nconst ImageViewScaleType ImageView::sScaleTypeArray[] = {\n    ImageViewScaleType_MATRIX,\n    ImageViewScaleType_FIT_XY,\n    ImageViewScaleType_FIT_START,\n    ImageViewScaleType_FIT_CENTER,\n    ImageViewScaleType_FIT_END,\n    ImageViewScaleType_CENTER,\n    ImageViewScaleType_CENTER_CROP,\n    ImageViewScaleType_CENTER_INSIDE\n};\n\nCAR_INTERFACE_IMPL(ImageView, View, IImageView);\n\nImageView::ImageView()\n    : mResource(0)\n    , mScaleType(ImageViewScaleType_FIT_CENTER)\n    , mHaveFrame(FALSE)\n    , mAdjustViewBounds(FALSE)\n    , mMaxWidth(Elastos::Core::Math::INT32_MAX_VALUE)\n    , mMaxHeight(Elastos::Core::Math::INT32_MAX_VALUE)\n    , mHasColorFilter(FALSE)\n    , mAlpha(255)\n    , mViewAlphaScale(256)\n    , mColorMod(FALSE)\n    , mDrawableTintMode(-1)\n    , mHasDrawableTint(FALSE)\n    , mHasDrawableTintMode(FALSE)\n    , mMergeState(FALSE)\n    , mLevel(0)\n    , mDrawableWidth(0)\n    , mDrawableHeight(0)\n    , mCropToPadding(FALSE)\n    , mBaseline(-1)\n    , mBaselineAlignBottom(FALSE)\n    , mAdjustViewBoundsCompat(FALSE)\n{\n}\n\nECode ImageView::constructor(\n    \/* [in] *\/ IContext* context)\n{\n    View::constructor(context);\n    InitImageView();\n    return NOERROR;\n}\n\nECode ImageView::constructor(\n    \/* [in] *\/ IContext* context,\n    \/* [in] *\/ IAttributeSet* attrs)\n{\n    return constructor(context, attrs, 0);\n}\n\nECode ImageView::constructor(\n    \/* [in] *\/ IContext* context,\n    \/* [in] *\/ IAttributeSet* attrs,\n    \/* [in] *\/ Int32 defStyleAttr)\n{\n    return constructor(context, attrs, defStyleAttr, 0);;\n}\n\nECode ImageView::constructor(\n    \/* [in] *\/ IContext* context,\n    \/* [in] *\/ IAttributeSet* attrs,\n    \/* [in] *\/ Int32 defStyleAttr,\n    \/* [in] *\/ Int32 defStyleRes)\n{\n    View::constructor(context, attrs, defStyleAttr, defStyleRes);\n    InitImageView();\n    return InitFromAttributes(context, attrs, defStyleAttr, defStyleRes);\n}\n\nECode ImageView::InitFromAttributes(\n    \/* [in] *\/ IContext* context,\n    \/* [in] *\/ IAttributeSet* attrs,\n    \/* [in] *\/ Int32 defStyleAttr,\n    \/* [in] *\/ Int32 defStyleRes)\n{\n    AutoPtr<ArrayOf<Int32> > attrIds = TO_ATTRS_ARRAYOF(R::styleable::ImageView);\n    AutoPtr<ITypedArray> a;\n    FAIL_RETURN(context->ObtainStyledAttributes(\n        attrs, attrIds, defStyleAttr, defStyleRes, (ITypedArray**)&a));\n\n    AutoPtr<IDrawable> d;\n    FAIL_RETURN(a->GetDrawable(R::styleable::ImageView_src, (IDrawable**)&d));\n    if (d != NULL) {\n        SetImageDrawable(d);\n    }\n\n    a->GetBoolean(R::styleable::ImageView_baselineAlignBottom, FALSE,\n            &mBaselineAlignBottom);\n\n    a->GetDimensionPixelSize(R::styleable::ImageView_baseline, -1,\n            &mBaseline);\n\n    Boolean bv;\n    a->GetBoolean(R::styleable::ImageView_adjustViewBounds, FALSE, &bv);\n    SetAdjustViewBounds(bv);\n\n    Int32 iv;\n    a->GetDimensionPixelSize(R::styleable::ImageView_maxWidth,\n            Elastos::Core::Math::INT32_MAX_VALUE, &iv);\n    SetMaxWidth(iv);\n\n    a->GetDimensionPixelSize(R::styleable::ImageView_maxHeight,\n            Elastos::Core::Math::INT32_MAX_VALUE, &iv);\n    SetMaxHeight(iv);\n\n    Int32 index;\n    a->GetInt32(R::styleable::ImageView_scaleType, -1, &index);\n    if (index >= 0) {\n        SetScaleType(sScaleTypeArray[index]);\n    }\n\n    Boolean has = FALSE;\n    if (a->HasValue(R::styleable::ImageView_tint, &has), has) {\n        a->GetColorStateList(R::styleable::ImageView_tint, (IColorStateList**)&mDrawableTintList);\n        mHasDrawableTint = TRUE;\n\n        \/\/ Prior to L, this attribute would always set a color filter with\n        \/\/ blending mode SRC_ATOP. Preserve that default behavior.\n        mDrawableTintMode = Elastos::Droid::Graphics::PorterDuffMode_SRC_ATOP;\n        mHasDrawableTintMode = TRUE;\n    }\n\n    if (a->HasValue(R::styleable::ImageView_tintMode, &has), has) {\n        a->GetInt32(R::styleable::ImageView_tintMode, -1, &iv);\n        Drawable::ParseTintMode(iv, mDrawableTintMode, &mDrawableTintMode);\n        mHasDrawableTintMode = TRUE;\n    }\n\n    ApplyImageTint();\n\n    Int32 alpha;\n    a->GetInt32(R::styleable::ImageView_drawableAlpha, 255, &alpha);\n    if (alpha != 255) {\n        SetAlpha(alpha);\n    }\n\n    a->GetBoolean(R::styleable::ImageView_cropToPadding, FALSE, &mCropToPadding);\n\n    a->Recycle();\n\n    \/\/need inflate syntax\/reader for matrix\n    return NOERROR;\n}\n\nvoid ImageView::InitImageView()\n{\n    ASSERT_SUCCEEDED(CRectF::New((IRectF**)&mTempSrc));\n    ASSERT_SUCCEEDED(CRectF::New((IRectF**)&mTempDst));\n    ASSERT_SUCCEEDED(CMatrix::New((IMatrix**)&mMatrix));\n    mScaleType = ImageViewScaleType_FIT_CENTER;\n    AutoPtr<IApplicationInfo> info;\n    mContext->GetApplicationInfo((IApplicationInfo**)&info);\n    Int32 value = 0;\n    info->GetTargetSdkVersion(&value);\n    mAdjustViewBoundsCompat = value <= Build::VERSION_CODES::JELLY_BEAN_MR1;\n}\n\nBoolean ImageView::VerifyDrawable(\n    \/* [in] *\/ IDrawable* dr)\n{\n    return mDrawable.Get() == dr || View::VerifyDrawable(dr);\n}\n\nECode ImageView::JumpDrawablesToCurrentState()\n{\n    Elastos::Droid::View::View::JumpDrawablesToCurrentState();\n    if (mDrawable != NULL)\n        return mDrawable->JumpToCurrentState();\n    return NOERROR;\n}\n\nECode ImageView::InvalidateDrawable(\n    \/* [in] *\/ IDrawable* dr)\n{\n    if (dr == mDrawable) {\n        \/* we invalidate the whole view in this case because it's very\n         * hard to know where the drawable actually is. This is made\n         * complicated because of the offsets and transformations that\n         * can be applied. In theory we could get the drawable's bounds\n         * and run them through the transformation and offsets, but this\n         * is probably not worth the effort.\n         *\/\n        Invalidate();\n        return NOERROR;\n    } else {\n        return View::InvalidateDrawable(dr);\n    }\n}\n\nECode ImageView::HasOverlappingRendering(\n    \/* [out] *\/ Boolean* has)\n{\n    VALIDATE_NOT_NULL(has);\n    *has = FALSE;\n\n    AutoPtr<IDrawable> bk;\n    GetBackground((IDrawable**)&bk);\n    if (bk != NULL) {\n        AutoPtr<IDrawable> current;\n        bk->GetCurrent((IDrawable**)&current);\n        *has = current != NULL;\n    }\n    return NOERROR;\n}\n\nECode ImageView::OnPopulateAccessibilityEvent(\n    \/* [in] *\/ IAccessibilityEvent* event)\n{\n    if (event != NULL) {\n        Elastos::Droid::View::View::OnPopulateAccessibilityEvent(event);\n        AutoPtr<ICharSequence> contentDescription;\n        GetContentDescription((ICharSequence**)&contentDescription);\n        if (!TextUtils::IsEmpty(contentDescription)) {\n            AutoPtr<IList> texts;\n            IAccessibilityRecord::Probe(event)->GetText((IList**)&texts);\n            texts->Add(contentDescription);\n        }\n    }\n\n    return NOERROR;\n}\n\nECode ImageView::GetAdjustViewBounds(\n    \/* [out] *\/ Boolean* result)\n{\n    VALIDATE_NOT_NULL(result);\n    *result = mAdjustViewBounds;\n    return NOERROR;\n}\n\nECode ImageView::SetAdjustViewBounds(\n    \/* [in] *\/ Boolean adjustViewBounds)\n{\n    mAdjustViewBounds = adjustViewBounds;\n    if (adjustViewBounds) {\n        SetScaleType(ImageViewScaleType_FIT_CENTER);\n    }\n    return NOERROR;\n}\n\nECode ImageView::GetMaxWidth(\n    \/* [out] *\/ Int32* width)\n{\n    VALIDATE_NOT_NULL(width);\n    *width = mMaxWidth;\n    return NOERROR;\n}\n\nECode ImageView::SetMaxWidth(\n    \/* [in] *\/ Int32 maxWidth)\n{\n    mMaxWidth = maxWidth;\n    return NOERROR;\n}\n\nECode ImageView::GetMaxHeight(\n    \/* [out] *\/ Int32* height)\n{\n    VALIDATE_NOT_NULL(height);\n    *height = mMaxHeight;\n    return NOERROR;\n}\n\nECode ImageView::SetMaxHeight(\n    \/* [in] *\/ Int32 maxHeight)\n{\n    mMaxHeight = maxHeight;\n    return NOERROR;\n}\n\nECode ImageView::GetDrawable(\n    \/* [out] *\/ IDrawable** drawable)\n{\n    VALIDATE_NOT_NULL(drawable);\n    *drawable = mDrawable;\n    REFCOUNT_ADD(*drawable);\n    return NOERROR;\n}\n\nECode ImageView::SetImageResource(\n    \/* [in] *\/ Int32 resId)\n{\n    if (mUri != NULL || mResource != resId) {\n        const Int32 oldWidth = mDrawableWidth;\n        const Int32 oldHeight = mDrawableHeight;\n\n        UpdateDrawable(NULL);\n        mResource = resId;\n        mUri = NULL;\n\n        ResolveUri();\n\n        if (oldWidth != mDrawableWidth || oldHeight != mDrawableHeight) {\n            RequestLayout();\n        }\n        Invalidate();\n    }\n    return NOERROR;\n}\n\nECode ImageView::SetImageURI(\n    \/* [in] *\/ IUri* uri)\n{\n    if (mResource != 0\n        || (mUri.Get() != uri\n            && (uri == NULL || mUri == NULL || !Object::Equals(mUri, uri)))\n    ) {\n        UpdateDrawable(NULL);\n        mResource = 0;\n        mUri = uri;\n\n        const Int32 oldWidth = mDrawableWidth;\n        const Int32 oldHeight = mDrawableHeight;\n\n        ResolveUri();\n\n        if (oldWidth != mDrawableWidth || oldHeight != mDrawableHeight) {\n            RequestLayout();\n        }\n        Invalidate();\n    }\n    return NOERROR;\n}\n\nECode ImageView::SetImageDrawable(\n    \/* [in] *\/ IDrawable* drawable)\n{\n    if (mDrawable.Get() != drawable) {\n        mResource = 0;\n        mUri = NULL;\n\n        const Int32 oldWidth = mDrawableWidth;\n        const Int32 oldHeight = mDrawableHeight;\n\n        UpdateDrawable(drawable);\n\n        if (oldWidth != mDrawableWidth || oldHeight != mDrawableHeight) {\n            RequestLayout();\n        }\n        Invalidate();\n    }\n    return NOERROR;\n}\n\nECode ImageView::SetImageTintList(\n    \/* [in] *\/ \/*@Nullable*\/ IColorStateList* tint)\n{\n    mDrawableTintList = tint;\n    mHasDrawableTint = TRUE;\n\n    ApplyImageTint();\n    return NOERROR;\n}\n\nECode ImageView::GetImageTintList(\n    \/* [out] *\/ IColorStateList** list)\n{\n    VALIDATE_NOT_NULL(list);\n    *list = mDrawableTintList;\n    REFCOUNT_ADD(*list);\n    return NOERROR;\n}\n\nECode ImageView::SetImageTintMode(\n    \/* [in] *\/ \/*@Nullable*\/ PorterDuffMode tintMode)\n{\n    mDrawableTintMode = tintMode;\n    mHasDrawableTintMode = TRUE;\n\n    ApplyImageTint();\n    return NOERROR;\n}\n\nECode ImageView::GetImageTintMode(\n    \/* [out] *\/ PorterDuffMode* mode)\n{\n    VALIDATE_NOT_NULL(mode);\n    *mode = mDrawableTintMode;\n    return NOERROR;\n}\n\nvoid ImageView::ApplyImageTint()\n{\n    if (mDrawable != NULL && (mHasDrawableTint || mHasDrawableTintMode)) {\n        mDrawable->Mutate();\n\n        if (mHasDrawableTint) {\n            mDrawable->SetTintList(mDrawableTintList);\n        }\n\n        if (mHasDrawableTintMode) {\n            mDrawable->SetTintMode(mDrawableTintMode);\n        }\n    }\n}\n\nECode ImageView::SetImageBitmap(\n    \/* [in] *\/ IBitmap* bm)\n{\n    \/\/ if this is used frequently, may handle bitmaps explicitly\n    \/\/ to reduce the intermediate drawable object\n    AutoPtr<IResources> res;\n    mContext->GetResources((IResources**)&res);\n    AutoPtr<IDrawable> bd;\n    CBitmapDrawable::New(res.Get(), bm, (IDrawable**)&bd);\n    SetImageDrawable(bd);\n    return NOERROR;\n}\n\nECode ImageView::SetImageState(\n    \/* [in] *\/ ArrayOf<Int32>* state,\n    \/* [in] *\/ Boolean merge)\n{\n    VALIDATE_NOT_NULL(state);\n    mState = NULL;\n    mState = state->Clone();\n    mMergeState = merge;\n    if (mDrawable != NULL) {\n        RefreshDrawableState();\n        ResizeFromDrawable();\n    }\n    return NOERROR;\n}\n\nECode ImageView::SetSelected(\n    \/* [in] *\/ Boolean selected)\n{\n    Elastos::Droid::View::View::SetSelected(selected);\n    ResizeFromDrawable();\n    return NOERROR;\n}\n\nECode ImageView::SetImageLevel(\n    \/* [in] *\/ Int32 level)\n{\n    mLevel = level;\n    if (mDrawable != NULL) {\n        Boolean changed;\n        mDrawable->SetLevel(level, &changed);\n        ResizeFromDrawable();\n    }\n    return NOERROR;\n}\n\nECode ImageView::SetScaleType(\n    \/* [in] *\/ ImageViewScaleType scaleType)\n{\n    if (mScaleType != scaleType) {\n        mScaleType = scaleType;\n\n        SetWillNotCacheDrawing(mScaleType == ImageViewScaleType_CENTER);\n\n        RequestLayout();\n        Invalidate();\n    }\n    return NOERROR;\n}\n\nECode ImageView::GetScaleType(\n    \/* [out] *\/ ImageViewScaleType* type)\n{\n    VALIDATE_NOT_NULL(type);\n    *type = mScaleType;\n    return NOERROR;\n}\n\nECode ImageView::GetImageMatrix(\n    \/* [out] *\/ IMatrix** matrix)\n{\n    VALIDATE_NOT_NULL(matrix);\n    if (mDrawMatrix == NULL) {\n        return CMatrix::New(CMatrix::IDENTITY_MATRIX, matrix);\n    }\n    *matrix = mDrawMatrix;\n    REFCOUNT_ADD(*matrix);\n    return NOERROR;\n}\n\nECode ImageView::SetImageMatrix(\n    \/* [in] *\/ IMatrix* inMatrix)\n{\n    Boolean isIdentity;\n    AutoPtr<IMatrix> matrix = inMatrix;\n    \/\/ collaps null and identity to just null\n    if (matrix != NULL) {\n        matrix->IsIdentity(&isIdentity);\n        if (isIdentity) {\n            matrix = NULL;\n        }\n    }\n\n    \/\/ don't invalidate unless we're actually changing our matrix\n    if ((matrix == NULL && (mMatrix->IsIdentity(&isIdentity), !isIdentity))\n        || (matrix != NULL && !Object::Equals(mMatrix, matrix))) {\n        mMatrix->Set(matrix);\n        ConfigureBounds();\n        Invalidate();\n    }\n    return NOERROR;\n}\n\nECode ImageView::GetCropToPadding(\n    \/* [out] *\/ Boolean* result)\n{\n    VALIDATE_NOT_NULL(result);\n    *result = mCropToPadding;\n    return NOERROR;\n}\n\nECode ImageView::SetCropToPadding(\n    \/* [in] *\/ Boolean cropToPadding)\n{\n    if (mCropToPadding != cropToPadding) {\n        mCropToPadding = cropToPadding;\n        RequestLayout();\n        Invalidate();\n    }\n    return NOERROR;\n}\n\nvoid ImageView::ResolveUri()\n{\n    if (mDrawable != NULL) {\n        return;\n    }\n\n    AutoPtr<IResources> rsrc;\n    GetResources((IResources**)&rsrc);\n    if (rsrc == NULL) {\n        return;\n    }\n\n    AutoPtr<IDrawable> d;\n\n    if (mResource != 0) {\n        if (FAILED(mContext->GetDrawable(mResource, (IDrawable**)&d))) {\n            Logger::W(\"ImageView\", \"Unable to find resource: %d\", mResource);\n            \/\/Don't try again.\n            mUri = NULL;\n        }\n    }\n    else if (mUri != NULL) {\n        String scheme;\n        mUri->GetScheme(&scheme);\n        if (!scheme.IsNull() && scheme.Equals(IContentResolver::SCHEME_ANDROID_RESOURCE)) {\n\/\/            try {\n                \/\/ Load drawable through Resources, to get the source density information\n                AutoPtr<IContentResolver> resolver;\n                AutoPtr<IContentResolverOpenResourceIdResult> r;\n                mContext->GetContentResolver((IContentResolver**)&resolver);\n                resolver->GetResourceId(mUri.Get(), (IContentResolverOpenResourceIdResult**)&r);\n                AutoPtr<IResources> res;\n                r->GetResources((IResources**)&res);\n                Int32 resId;\n                r->GetResourceId(&resId);\n                AutoPtr<IResourcesTheme> theme;\n                mContext->GetTheme((IResourcesTheme**)&theme);\n                res->GetDrawable(resId, theme, (IDrawable**)&d);\n\/\/            } catch (Exception e) {\n\/\/                Log.w(\"ImageView\", \"Unable to open content: \" + mUri, e);\n\/\/            }\n        }\n        else if (IContentResolver::SCHEME_CONTENT.Equals(scheme)\n                || IContentResolver::SCHEME_FILE.Equals(scheme)) {\n\/\/          try {\n            AutoPtr<IContentResolver> resolver;\n            mContext->GetContentResolver((IContentResolver**)&resolver);\n            AutoPtr<IInputStream> stream;\n            resolver->OpenInputStream(mUri.Get(), (IInputStream**)&stream);\n            String nullStr;\n\n            AutoPtr<IDrawableHelper> helper;\n            CDrawableHelper::AcquireSingleton((IDrawableHelper**)&helper);\n            Elastos::Droid::Graphics::Drawable::Drawable::CreateFromStream(stream.Get(), nullStr, (IDrawable**)&d);\n\/\/            } catch (Exception e) {\n\/\/                Log.w(\"ImageView\", \"Unable to open content: \" + mUri, e);\n\/\/            }\n            if (stream != NULL) {\n                \/\/ try {\n                stream->Close();\n                \/\/ } catch (IOException e) {\n                \/\/     Log.w(\"ImageView\", \"Unable to close content: \" + mUri, e);\n                \/\/ }\n            }\n        }\n        else {\n            String uriDes = Object::ToString(mUri);\n            AutoPtr<IDrawableHelper> helper;\n            CDrawableHelper::AcquireSingleton((IDrawableHelper**)&helper);\n            Elastos::Droid::Graphics::Drawable::Drawable::CreateFromPath(uriDes, (IDrawable**)&d);\n        }\n\n        if (d == NULL) {\n            Logger::W(\"ImageView\", \"resolveUri failed on bad bitmap uri: %s\", TO_CSTR(mUri));\n            \/\/ Don't try again.\n            mUri = NULL;\n        }\n    }\n    else {\n        return;\n    }\n\n    UpdateDrawable(d);\n}\n\nECode ImageView::OnCreateDrawableState(\n    \/* [in] *\/ Int32 extraSpace,\n    \/* [out, callee] *\/ ArrayOf<Int32>** drawableState)\n{\n    VALIDATE_NOT_NULL(drawableState);\n    *drawableState = NULL;\n\n    AutoPtr<ArrayOf<Int32> > ds;\n    if (mState == NULL) {\n        FAIL_RETURN(View::OnCreateDrawableState(extraSpace, (ArrayOf<Int32>**)&ds));\n        *drawableState = ds;\n        REFCOUNT_ADD(*drawableState);\n        return NOERROR;\n    }\n    else if (!mMergeState) {\n        *drawableState = mState;\n        REFCOUNT_ADD(*drawableState);\n        return NOERROR;\n    }\n    else {\n        FAIL_RETURN(Elastos::Droid::View::View::OnCreateDrawableState(extraSpace + mState->GetLength(),\n                (ArrayOf<Int32>**)&ds));\n        MergeDrawableStates(ds, mState);\n        *drawableState = ds;\n        REFCOUNT_ADD(*drawableState);\n        return NOERROR;\n    }\n}\n\nvoid ImageView::UpdateDrawable(\n    \/* [in] *\/ IDrawable* d)\n{\n    if (mDrawable != NULL) {\n        mDrawable->SetCallback(NULL);\n        UnscheduleDrawable(mDrawable);\n    }\n    mDrawable = d;\n    if (d != NULL) {\n        d->SetCallback(this);\n        Int32 value = 0;\n        GetLayoutDirection(&value);\n        d->SetLayoutDirection(value);\n        Boolean stateful;\n        d->IsStateful(&stateful);\n        if (stateful) {\n            AutoPtr<ArrayOf<Int32> > drawableState;\n            GetDrawableState((ArrayOf<Int32>**)&drawableState);\n            d->SetState(drawableState, &stateful);\n        }\n\n        GetVisibility(&value);\n        Boolean bval;\n        d->SetVisible(value == IView::VISIBLE, TRUE, &bval);\n        d->SetLevel(mLevel, &bval);\n        d->GetIntrinsicWidth(&mDrawableWidth);\n        d->GetIntrinsicHeight(&mDrawableHeight);\n        ApplyImageTint();\n        ApplyColorMod();\n        ConfigureBounds();\n    }\n    else {\n        mDrawableWidth = mDrawableHeight = -1;\n    }\n}\n\nvoid ImageView::ResizeFromDrawable()\n{\n    AutoPtr<IDrawable> d = mDrawable;\n    if (d != NULL) {\n        Int32 w;\n        d->GetIntrinsicWidth(&w);\n        if (w < 0) w = mDrawableWidth;\n        Int32 h;\n        d->GetIntrinsicHeight(&h);\n        if (h < 0) h = mDrawableHeight;\n        if (w != mDrawableWidth || h != mDrawableHeight) {\n            mDrawableWidth = w;\n            mDrawableHeight = h;\n            RequestLayout();\n        }\n    }\n}\n\nECode ImageView::OnRtlPropertiesChanged(\n    \/* [in] *\/ Int32 layoutDirection)\n{\n    View::OnRtlPropertiesChanged(layoutDirection);\n\n    if (mDrawable != NULL) {\n        mDrawable->SetLayoutDirection(layoutDirection);\n    }\n    return NOERROR;\n}\n\nconst MatrixScaleToFit ImageView::sS2FArray[4] = {\n    Elastos::Droid::Graphics::MatrixScaleToFit_FILL,\n    Elastos::Droid::Graphics::MatrixScaleToFit_START,\n    Elastos::Droid::Graphics::MatrixScaleToFit_CENTER,\n    Elastos::Droid::Graphics::MatrixScaleToFit_END\n};\n\nMatrixScaleToFit ImageView::ScaleTypeToScaleToFit(\n    \/* [in] *\/ ImageViewScaleType st)\n{\n    \/\/ ScaleToFit enum to their corresponding Matrix.ScaleToFit values\n    return sS2FArray[st - 1];\n}\n\nECode ImageView::OnMeasure(\n    \/* [in] *\/ Int32 widthMeasureSpec,\n    \/* [in] *\/ Int32 heightMeasureSpec)\n{\n    ResolveUri();\n    Int32 w;\n    Int32 h;\n\n    \/\/ Desired aspect ratio of the view's contents (not including padding)\n    Float desiredAspect = 0.0f;\n\n    \/\/ We are allowed to change the view's width\n    Boolean resizeWidth = FALSE;\n\n    \/\/ We are allowed to change the view's height\n    Boolean resizeHeight = FALSE;\n\n    int widthSpecMode = MeasureSpec::GetMode(widthMeasureSpec);\n    int heightSpecMode = MeasureSpec::GetMode(heightMeasureSpec);\n\n    if (mDrawable == NULL) {\n        \/\/ If no drawable, its intrinsic size is 0.\n        mDrawableWidth = -1;\n        mDrawableHeight = -1;\n        w = h = 0;\n    }\n    else {\n        w = mDrawableWidth;\n        h = mDrawableHeight;\n        if (w <= 0) w = 1;\n        if (h <= 0) h = 1;\n\n        \/\/ We are supposed to adjust view bounds to match the aspect\n        \/\/ ratio of our drawable. See if that is possible.\n        if (mAdjustViewBounds) {\n            resizeWidth = widthSpecMode != MeasureSpec::EXACTLY;\n            resizeHeight = heightSpecMode != MeasureSpec::EXACTLY;\n\n            desiredAspect = (Float)w\/(Float)h;\n        }\n    }\n\n    Int32 pleft = mPaddingLeft;\n    Int32 pright = mPaddingRight;\n    Int32 ptop = mPaddingTop;\n    Int32 pbottom = mPaddingBottom;\n\n    Int32 widthSize;\n    Int32 heightSize;\n\n    if (resizeWidth || resizeHeight) {\n        \/* If we get here, it means we want to resize to match the\n            drawables aspect ratio, and we have the freedom to change at\n            least one dimension.\n        *\/\n\n        \/\/ Get the max possible width given our constraints\n        widthSize = ResolveAdjustedSize(w + pleft + pright,\n                                             mMaxWidth, widthMeasureSpec);\n\n        \/\/ Get the max possible height given our constraints\n        heightSize = ResolveAdjustedSize(h + ptop + pbottom,\n                                            mMaxHeight, heightMeasureSpec);\n\n        if (desiredAspect != 0.0f) {\n            \/\/ See what our actual aspect ratio is\n            Float actualAspect = (Float)(widthSize - pleft - pright) \/\n                                    (heightSize - ptop - pbottom);\n\n            if (Elastos::Core::Math::Abs(actualAspect - desiredAspect) > 0.0000001) {\n\n                Boolean done = FALSE;\n\n                \/\/ Try adjusting width to be proportional to height\n                if (resizeWidth) {\n                    Int32 newWidth = (Int32)(desiredAspect *\n                                        (heightSize - ptop - pbottom))\n                                        + pleft + pright;\n\n                    \/\/ Allow the width to outgrow its original estimate if height is fixed.\n                    if (!resizeHeight && !mAdjustViewBoundsCompat) {\n                        widthSize = ResolveAdjustedSize(newWidth, mMaxWidth, widthMeasureSpec);\n                    }\n                    if (newWidth <= widthSize) {\n                        widthSize = newWidth;\n                        done = TRUE;\n                    }\n                }\n\n                \/\/ Try adjusting height to be proportional to width\n                if (!done && resizeHeight) {\n                    Int32 newHeight = (Int32)((widthSize - pleft - pright)\n                                        \/ desiredAspect) + ptop + pbottom;\n\n                    \/\/ Allow the height to outgrow its original estimate if width is fixed.\n                    if (!resizeWidth && !mAdjustViewBoundsCompat) {\n                        heightSize = ResolveAdjustedSize(newHeight, mMaxHeight,\n                                heightMeasureSpec);\n                    }\n                    if (newHeight <= heightSize) {\n                        heightSize = newHeight;\n                    }\n                }\n            }\n        }\n    }\n    else {\n        \/* We are either don't want to preserve the drawables aspect ratio,\n           or we are not allowed to change view dimensions. Just measure in\n           the normal way.\n        *\/\n        w += pleft + pright;\n        h += ptop + pbottom;\n\n        w = Elastos::Core::Math::Max(w, GetSuggestedMinimumWidth());\n        h = Elastos::Core::Math::Max(h, GetSuggestedMinimumHeight());\n\n        widthSize = ResolveSizeAndState(w, widthMeasureSpec, 0);\n        heightSize = ResolveSizeAndState(h, heightMeasureSpec, 0);\n    }\n\n    SetMeasuredDimension(widthSize, heightSize);\n    return NOERROR;\n}\n\nInt32 ImageView::ResolveAdjustedSize(\n    \/* [in] *\/ Int32 desiredSize,\n    \/* [in] *\/ Int32 maxSize,\n    \/* [in] *\/ Int32 measureSpec)\n{\n    Int32 result = desiredSize;\n    Int32 specMode = MeasureSpec::GetMode(measureSpec);\n    Int32 specSize =  MeasureSpec::GetSize(measureSpec);\n    switch (specMode) {\n        case MeasureSpec::UNSPECIFIED:\n            \/* Parent says we can be as big as we want. Just don't be larger\n               than max size imposed on ourselves.\n            *\/\n            result = Elastos::Core::Math::Min(desiredSize, maxSize);\n            break;\n        case MeasureSpec::AT_MOST:\n            \/\/ Parent says we can be as big as we want, up to specSize.\n            \/\/ Don't be larger than specSize, and don't be larger than\n            \/\/ the max size imposed on ourselves.\n            result = Elastos::Core::Math::Min(Elastos::Core::Math::Min(desiredSize, specSize), maxSize);\n            break;\n        case MeasureSpec::EXACTLY:\n            \/\/ No choice. Do what we are told.\n            result = specSize;\n            break;\n    }\n    return result;\n}\n\nBoolean ImageView::SetFrame(\n    \/* [in] *\/ Int32 left,\n    \/* [in] *\/ Int32 top,\n    \/* [in] *\/ Int32 right,\n    \/* [in] *\/ Int32 bottom)\n{\n    Boolean changed = View::SetFrame(left, top, right, bottom);\n    mHaveFrame = TRUE;\n    ConfigureBounds();\n    return changed;\n}\n\nvoid ImageView::ConfigureBounds()\n{\n    if (mDrawable == NULL || !mHaveFrame) {\n        return;\n    }\n\n    Int32 dwidth = mDrawableWidth;\n    Int32 dheight = mDrawableHeight;\n\n    Int32 tmp = 0;\n    Int32 vwidth = (GetWidth(&tmp), tmp) - mPaddingLeft - mPaddingRight;\n    Int32 vheight = (GetHeight(&tmp), tmp) - mPaddingTop - mPaddingBottom;\n\n    Boolean fits = (dwidth < 0 || vwidth == dwidth) && (dheight < 0 || vheight == dheight);\n\n    if (dwidth <= 0 || dheight <= 0 || ImageViewScaleType_FIT_XY == mScaleType) {\n        \/* If the drawable has no intrinsic size, or we're told to\n            scaletofit, then we just fill our entire view.\n        *\/\n        mDrawable->SetBounds(0, 0, vwidth, vheight);\n        mDrawMatrix = NULL;\n    }\n    else {\n        Boolean result;\n\n        \/\/ We need to do the scaling ourself, so have the drawable\n        \/\/ use its native size.\n        mDrawable->SetBounds(0, 0, dwidth, dheight);\n\n        if (ImageViewScaleType_MATRIX == mScaleType) {\n            \/\/ Use the specified matrix as-is.\n            Boolean isIdentity;\n            mMatrix->IsIdentity(&isIdentity);\n            if (isIdentity) {\n                mDrawMatrix = NULL;\n            }\n            else {\n                mDrawMatrix = mMatrix;\n            }\n        }\n        else if (fits) {\n            \/\/ The bitmap fits exactly, no transform needed.\n            mDrawMatrix = NULL;\n        }\n        else if (ImageViewScaleType_CENTER == mScaleType) {\n            \/\/ Center bitmap in view, no scaling.\n            mDrawMatrix = mMatrix;\n            mDrawMatrix->SetTranslate((Int32)((vwidth - dwidth) * 0.5f + 0.5f),\n                                     (Int32)((vheight - dheight) * 0.5f + 0.5f));\n        }\n        else if (ImageViewScaleType_CENTER_CROP == mScaleType) {\n            mDrawMatrix = mMatrix;\n\n            Float scale;\n            Float dx = 0, dy = 0;\n\n            if (dwidth * vheight > vwidth * dheight) {\n                scale = (Float)vheight \/ (Float)dheight;\n                dx = (vwidth - dwidth * scale) * 0.5f;\n            }\n            else {\n                scale = (Float)vwidth \/ (Float)dwidth;\n                dy = (vheight - dheight * scale) * 0.5f;\n            }\n\n            mDrawMatrix->SetScale(scale, scale);\n            mDrawMatrix->PostTranslate(dx + 0.5f, dy + 0.5f, &result);\n        }\n        else if (ImageViewScaleType_CENTER_INSIDE == mScaleType) {\n            mDrawMatrix = mMatrix;\n            Float scale;\n            Float dx;\n            Float dy;\n\n            if (dwidth <= vwidth && dheight <= vheight) {\n                scale = 1.0f;\n            }\n            else {\n                scale = Elastos::Core::Math::Min((Float)vwidth \/ (Float)dwidth,\n                        (Float)vheight \/ (Float)dheight);\n            }\n\n            dx = (Int32)((vwidth - dwidth * scale) * 0.5f + 0.5f);\n            dy = (Int32)((vheight - dheight * scale) * 0.5f + 0.5f);\n\n            mDrawMatrix->SetScale(scale, scale);\n            mDrawMatrix->PostTranslate(dx, dy, &result);;\n        }\n        else {\n            \/\/ Generate the required transform.\n            mTempSrc->Set(0, 0, dwidth, dheight);\n            mTempDst->Set(0, 0, vwidth, vheight);\n\n            mDrawMatrix = mMatrix;\n            mDrawMatrix->SetRectToRect(mTempSrc, mTempDst, ScaleTypeToScaleToFit(mScaleType), &result);\n        }\n    }\n}\n\nECode ImageView::DrawableHotspotChanged(\n    \/* [in] *\/ Float x,\n    \/* [in] *\/ Float y)\n{\n    View::DrawableHotspotChanged(x, y);\n\n    if (mDrawable != NULL) {\n        mDrawable->SetHotspot(x, y);\n    }\n    return NOERROR;\n}\n\nECode ImageView::AnimateTransform(\n    \/* [in] *\/ IMatrix* matrix)\n{\n    if (matrix == NULL) {\n        Int32 w = 0, h = 0;\n        GetWidth(&w);\n        GetHeight(&h);\n        mDrawable->SetBounds(0, 0, w, h);\n    } else {\n        mDrawable->SetBounds(0, 0, mDrawableWidth, mDrawableHeight);\n        if (mDrawMatrix == NULL) {\n            CMatrix::New((IMatrix**)&mDrawMatrix);\n        }\n        mDrawMatrix->Set(matrix);\n    }\n    Invalidate();\n    return NOERROR;\n}\n\nECode ImageView::DrawableStateChanged()\n{\n    FAIL_RETURN(View::DrawableStateChanged());\n    AutoPtr<IDrawable> d = mDrawable;\n    if (d != NULL) {\n        Boolean stateful;\n        d->IsStateful(&stateful);\n        if (stateful) {\n            AutoPtr<ArrayOf<Int32> > drawableState;\n            GetDrawableState((ArrayOf<Int32>**)&drawableState);\n            d->SetState(drawableState, &stateful);\n        }\n    }\n    return NOERROR;\n}\n\nvoid ImageView::OnDraw(\n    \/* [in] *\/ ICanvas* canvas)\n{\n    View::OnDraw(canvas);\n\n    if (mDrawable == NULL) {\n        return; \/\/ couldn't resolve the URI\n    }\n\n    if (mDrawableWidth == 0 || mDrawableHeight == 0) {\n        return;     \/\/ nothing to draw (empty bounds)\n    }\n\n    if (mDrawMatrix == NULL && mPaddingTop == 0 && mPaddingLeft == 0) {\n        mDrawable->Draw(canvas);\n    }\n    else {\n        Int32 saveCount1, saveCount2;\n        canvas->GetSaveCount(&saveCount1);\n        canvas->Save(&saveCount2);\n        if (mCropToPadding) {\n            Boolean isNonEmpty;\n            canvas->ClipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,\n                mScrollX + mRight - mLeft - mPaddingRight,\n                mScrollY + mBottom - mTop - mPaddingBottom,\n                &isNonEmpty);\n        }\n\n        canvas->Translate(mPaddingLeft, mPaddingTop);\n        if (mDrawMatrix != NULL) {\n            canvas->Concat(mDrawMatrix);\n        }\n\n        mDrawable->Draw(canvas);\n        canvas->RestoreToCount(saveCount1);\n    }\n}\n\nECode ImageView::GetBaseline(\n    \/* [out] *\/ Int32* baseLine)\n{\n    VALIDATE_NOT_NULL(baseLine);\n    Int32 height = 0;\n    GetMeasuredHeight(&height);\n    *baseLine = mBaselineAlignBottom ? height : -1;\n    return NOERROR;\n}\n\nECode ImageView::SetBaseline(\n    \/* [in] *\/ Int32 baseline)\n{\n    if (mBaseline != baseline) {\n        mBaseline = baseline;\n        RequestLayout();\n    }\n    return NOERROR;\n}\n\nECode ImageView::SetBaselineAlignBottom(\n    \/* [in] *\/ Boolean aligned)\n{\n    if (mBaselineAlignBottom != aligned) {\n        mBaselineAlignBottom = aligned;\n        RequestLayout();\n    }\n    return NOERROR;\n}\n\nECode ImageView::GetBaselineAlignBottom(\n    \/* [out] *\/ Boolean* result)\n{\n    VALIDATE_NOT_NULL(result);\n    *result = mBaselineAlignBottom;\n    return NOERROR;\n}\n\nECode ImageView::SetColorFilter(\n    \/* [in] *\/ Int32 color,\n    \/* [in] *\/ PorterDuffMode mode)\n{\n    AutoPtr<IColorFilter> cf;\n    CPorterDuffColorFilter::New(color, mode, (IColorFilter**)&cf);\n    return SetColorFilter(cf.Get());\n}\n\nECode ImageView::SetColorFilter(\n    \/* [in] *\/ Int32 color)\n{\n    return SetColorFilter(color, Elastos::Droid::Graphics::PorterDuffMode_SRC_ATOP);\n}\n\nECode ImageView::SetXfermode(\n    \/* [in] *\/ IXfermode* mode)\n{\n    if (mXfermode.Get() != mode) {\n        mXfermode = mode;\n        mColorMod = TRUE;\n        ApplyColorMod();\n        Invalidate();\n    }\n    return NOERROR;\n}\n\nECode ImageView::ClearColorFilter()\n{\n    return SetColorFilter((IColorFilter*)NULL);\n}\n\nECode ImageView::GetColorFilter(\n    \/* [out] *\/ IColorFilter** filter)\n{\n    VALIDATE_NOT_NULL(filter);\n    *filter = mColorFilter;\n    REFCOUNT_ADD(*filter);\n    return NOERROR;\n}\n\nECode ImageView::SetColorFilter(\n    \/* [in] *\/ IColorFilter* cf)\n{\n    if (mColorFilter.Get() != cf) {\n        mColorFilter = cf;\n        mHasColorFilter = TRUE;\n        mColorMod = TRUE;\n        ApplyColorMod();\n        Invalidate();\n    }\n    return NOERROR;\n}\n\nECode ImageView::GetImageAlpha(\n    \/* [out] *\/ Int32* alpha)\n{\n    VALIDATE_NOT_NULL(alpha);\n    *alpha = mAlpha;\n    return NOERROR;\n}\n\nECode ImageView::SetImageAlpha(\n    \/* [in] *\/ Int32 alpha)\n{\n    return SetAlpha(alpha);\n}\n\nECode ImageView::SetAlpha(\n    \/* [in] *\/ Int32 alpha)\n{\n    alpha &= 0xFF;          \/\/ keep it legal\n    if (mAlpha != alpha) {\n        mAlpha = alpha;\n        mColorMod = TRUE;\n        ApplyColorMod();\n        Invalidate();\n    }\n    return NOERROR;\n}\n\nvoid ImageView::ApplyColorMod()\n{\n    \/\/ Only mutate and apply when modifications have occurred. This should\n    \/\/ not reset the mColorMod flag, since these filters need to be\n    \/\/ re-applied if the Drawable is changed.\n    if (mDrawable != NULL && mColorMod) {\n        mDrawable->Mutate();\n        if (mHasColorFilter) {\n            mDrawable->SetColorFilter(mColorFilter);\n        }\n        ((Drawable*)mDrawable.Get())->SetXfermode(mXfermode);\n        mDrawable->SetAlpha(mAlpha * mViewAlphaScale >> 8);\n    }\n}\n\nECode ImageView::IsOpaque(\n    \/* [out] *\/ Boolean* opaque)\n{\n    VALIDATE_NOT_NULL(opaque);\n    View::IsOpaque(opaque);\n    Int32 opacity = 0;\n    *opaque = (*opaque) || (mDrawable != NULL && mXfermode == NULL\n        && (mDrawable->GetOpacity(&opacity), opacity) == IPixelFormat::OPAQUE\n        && mAlpha * mViewAlphaScale >> 8 == 255\n        && IsFilledByImage());\n    return NOERROR;\n}\n\nBoolean ImageView::IsFilledByImage()\n{\n    if (mDrawable == NULL) {\n        return FALSE;\n    }\n\n    AutoPtr<IRect> bounds;\n    mDrawable->GetBounds((IRect**)&bounds);\n    AutoPtr<IMatrix> matrix = mDrawMatrix;\n    Boolean state = FALSE;\n    if (matrix == NULL) {\n        Int32 left = 0, top = 0, right = 0, bottom = 0, w = 0, h = 0;\n        bounds->Get(&left, &top, &right, &bottom);\n        GetWidth(&w);\n        GetHeight(&h);\n        return left <= 0 && top <= 0 && right >= w && bottom >= h;\n    }\n    else if (matrix->RectStaysRect(&state), state) {\n        AutoPtr<IRectF> boundsSrc = mTempSrc;\n        AutoPtr<IRectF> boundsDst = mTempDst;\n        boundsSrc->Set(bounds);\n        matrix->MapRect(boundsDst, boundsSrc, &state);\n\n        Float left = 0, top = 0, right = 0, bottom = 0;\n        Int32 w = 0, h = 0;\n        boundsDst->Get(&left, &top, &right, &bottom);\n        GetWidth(&w);\n        GetHeight(&h);\n        return left <= 0 && top <= 0 && right >= w && bottom >= h;\n    }\n    else {\n        \/\/ If the matrix doesn't map to a rectangle, assume the worst.\n        return FALSE;\n    }\n}\n\nECode ImageView::SetVisibility(\n    \/* [in] *\/ Int32 visibility)\n{\n    Elastos::Droid::View::View::SetVisibility(visibility);\n    if (mDrawable != NULL) {\n        Boolean isDiff;\n        mDrawable->SetVisible(visibility == IView::VISIBLE, FALSE, &isDiff);\n    }\n    return NOERROR;\n}\n\nECode ImageView::OnAttachedToWindow()\n{\n    Elastos::Droid::View::View::OnAttachedToWindow();\n    if (mDrawable != NULL) {\n        Boolean isDiff = FALSE;\n        Int32 v = 0;\n        GetVisibility(&v);\n        mDrawable->SetVisible(v == IView::VISIBLE, FALSE, &isDiff);\n    }\n    return NOERROR;\n}\n\nECode ImageView::OnDetachedFromWindow()\n{\n    Elastos::Droid::View::View::OnDetachedFromWindow();\n    if (mDrawable != NULL) {\n        Boolean isDiff;\n        mDrawable->SetVisible(FALSE, FALSE, &isDiff);\n    }\n    return NOERROR;\n}\n\nECode ImageView::OnInitializeAccessibilityEvent(\n    \/* [in] *\/ IAccessibilityEvent* event)\n{\n    VALIDATE_NOT_NULL(event);\n    Elastos::Droid::View::View::OnInitializeAccessibilityEvent(event);\n    \/\/event->SetClassName(ImageView.class.getName());\n    return NOERROR;\n}\n\nECode ImageView::OnInitializeAccessibilityNodeInfo(\n    \/* [in] *\/ IAccessibilityNodeInfo* info)\n{\n    VALIDATE_NOT_NULL(info);\n    Elastos::Droid::View::View::OnInitializeAccessibilityNodeInfo(info);\n    \/\/info->SetClassName(ImageView.class.getName());\n    return NOERROR;\n}\n\n} \/\/ namespace Widget\n} \/\/ namespace Droid\n} \/\/ namespace Elastos\n","avg_line_length":28.7373811266,"max_line_length":115,"alphanum_fraction":0.6030190408,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2111,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":38.0,"content":"#include \"src\/cpu_affinity\/string_descripted_cpu_set_generator.h\"\n\n#include <gtest\/gtest.h>\n\nnamespace pos\n{\nTEST(StringDescriptedCpuSetGenerator, StringDescriptedCpuSetGenerator_Stack_NonMask)\n{\n    \/\/ Given\n    const CoreDescriptionArray TEST_CORE_DESCRIPTIONS =\n        {\n            CoreDescription{CoreType::REACTOR, {1, 0}, \"0\"},\n            CoreDescription{CoreType::UDD_IO_WORKER, {1, 0}, \"1\"},\n            CoreDescription{CoreType::EVENT_SCHEDULER, {1, 0}, \"2\"},\n            CoreDescription{CoreType::EVENT_WORKER, {3, 0}, \"3-5\"},\n            CoreDescription{CoreType::GENERAL_USAGE, {1, 0}, \"6\"},\n            CoreDescription{CoreType::QOS, {1, 0}, \"7\"},\n            CoreDescription{CoreType::META_SCHEDULER, {1, 0}, \"8\"},\n            CoreDescription{CoreType::META_IO, {2, 0}, \"9-10\"},\n            CoreDescription{CoreType::AIR, {1, 0}, \"11\"},\n        };\n    \/\/ When : Create StringDescriptedCpuSetGenerator on stack\n    StringDescriptedCpuSetGenerator stringDescriptedCpuSetGenerator(TEST_CORE_DESCRIPTIONS, false);\n\n    \/\/ Then : Do nothing\n}\n\nTEST(StringDescriptedCpuSetGenerator, StringDescriptedCpuSetGenerator_Heap_Mask)\n{\n    \/\/ Given\n    const CoreDescriptionArray TEST_CORE_DESCRIPTIONS =\n        {\n            CoreDescription{CoreType::REACTOR, {1, 0}, \"0x0\"},\n            CoreDescription{CoreType::UDD_IO_WORKER, {1, 0}, \"0x111\"},\n            CoreDescription{CoreType::EVENT_SCHEDULER, {1, 0}, \"2\"},\n            CoreDescription{CoreType::EVENT_WORKER, {3, 0}, \"3-5\"},\n            CoreDescription{CoreType::GENERAL_USAGE, {1, 0}, \"6\"},\n            CoreDescription{CoreType::QOS, {1, 0}, \"7\"},\n            CoreDescription{CoreType::META_SCHEDULER, {1, 0}, \"8\"},\n            CoreDescription{CoreType::META_IO, {2, 0}, \"9-10\"},\n            CoreDescription{CoreType::AIR, {1, 0}, \"11\"},\n        };\n    \/\/ When : Create StringDescriptedCpuSetGenerator on stack\n    StringDescriptedCpuSetGenerator* stringDescriptedCpuSetGenerator = new StringDescriptedCpuSetGenerator(TEST_CORE_DESCRIPTIONS, false);\n\n    \/\/ Then : Release memory\n    delete stringDescriptedCpuSetGenerator;\n}\n\n} \/\/ namespace pos\n","avg_line_length":41.3921568627,"max_line_length":138,"alphanum_fraction":0.6589294173,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8367,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause","BSD-3-Clause-No-Nuclear-License-2014","MIT","bzip2-1.0.6","OpenSSL","IJG","BSD-3-Clause"],"max_stars_count":360.0,"content":"\/*\r\n *  Original work: Copyright (c) 2014, Oculus VR, Inc.\r\n *  All rights reserved.\r\n *\r\n *  This source code is licensed under the BSD-style license found in the\r\n *  RakNet License.txt file in the licenses directory of this source tree. An additional grant \r\n *  of patent rights can be found in the RakNet Patents.txt file in the same directory.\r\n *\r\n *\r\n *  Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschr\u00e4nkt)\r\n *\r\n *  This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style\r\n *  license found in the license.txt file in the root directory of this source tree.\r\n *\/\r\n\r\n\/\/ Common includes\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include \"slikenet\/Kbhit.h\"\r\n\r\n#include \"slikenet\/GetTime.h\"\r\n#include \"slikenet\/peerinterface.h\"\r\n#include \"slikenet\/MessageIdentifiers.h\"\r\n#include \"slikenet\/BitStream.h\"\r\n#include \"slikenet\/StringCompressor.h\"\r\n#include \"slikenet\/FileListTransfer.h\"\r\n#include \"slikenet\/FileList.h\" \/\/ FLP_Printf\r\n#include \"AutopatcherServer.h\"\r\n#include \"AutopatcherMySQLRepository.h\"\r\n#include \"slikenet\/PacketizedTCP.h\"\r\n#include \"slikenet\/Gets.h\"\r\n#include \"slikenet\/linux_adapter.h\"\r\n#include \"slikenet\/osx_adapter.h\"\r\n\r\n#ifdef _WIN32\r\n#include \"slikenet\/WindowsIncludes.h\" \/\/ Sleep\r\n#else\r\n#include <unistd.h> \/\/ usleep\r\n#endif\r\n\r\n#define USE_TCP\r\n#define LISTEN_PORT 60000\r\n#define MAX_INCOMING_CONNECTIONS 128\r\n\r\nint main(int, char **)\r\n{\r\n\t\/\/ Avoids the Error: Got a packet bigger than 'max_allowed_packet' bytes\r\n\tprintf(\"Important: Requires that you first set the DB schema and the max packet size on the server.\\n\");\r\n\tprintf(\"See DependentExtensions\/AutopatcherMySQLRepository\/readme.txt\\n\");\r\n\t\/\/ \/\/ MySQL is extremely slow in AutopatcherMySQLRepository::GetFilePart\r\n\tprintf(\"WARNING: MySQL is an order of magnitude slower than PostgreSQL.\\nRecommended you use AutopatcherServer_PostgreSQL instead.\");\r\n\r\n\tprintf(\"Server starting... \");\r\n\tSLNet::AutopatcherServer autopatcherServer;\r\n\t\/\/ SLNet::FLP_Printf progressIndicator;\r\n\tSLNet::FileListTransfer fileListTransfer;\r\n\t\/\/ So only one thread runs per connection, we create an array of connection objects, and tell the autopatcher server to use one thread per item\r\n\tstatic const int workerThreadCount=4; \/\/ Used for checking patches only\r\n\tstatic const int sqlConnectionObjectCount=32; \/\/ Used for both checking patches and downloading\r\n\tSLNet::AutopatcherMySQLRepository connectionObject[sqlConnectionObjectCount];\r\n\tSLNet::AutopatcherRepositoryInterface *connectionObjectAddresses[sqlConnectionObjectCount];\r\n\tfor (int i=0; i < sqlConnectionObjectCount; i++)\r\n\t\tconnectionObjectAddresses[i]=&connectionObject[i];\r\n\t\/\/ fileListTransfer.AddCallback(&progressIndicator);\r\n\tautopatcherServer.SetFileListTransferPlugin(&fileListTransfer);\r\n\t\/\/ MySQL is extremely slow in AutopatcherMySQLRepository::GetFilePart so running tho incremental reads in a thread allows multiple concurrent users to read\r\n\t\/\/ Without this, only one user would be sent files at a time basically\r\n\tfileListTransfer.StartIncrementalReadThreads(sqlConnectionObjectCount);\r\n\tautopatcherServer.SetMaxConurrentUsers(MAX_INCOMING_CONNECTIONS); \/\/ More users than this get queued up\r\n\tSLNet::AutopatcherServerLoadNotifier_Printf loadNotifier;\r\n\tautopatcherServer.SetLoadManagementCallback(&loadNotifier);\r\n#ifdef USE_TCP\r\n\tSLNet::PacketizedTCP packetizedTCP;\r\n\tif (packetizedTCP.Start(LISTEN_PORT,MAX_INCOMING_CONNECTIONS)==false)\r\n\t{\r\n\t\tprintf(\"Failed to start TCP. Is the port already in use?\");\r\n\t\treturn 1;\r\n\t}\r\n\tpacketizedTCP.AttachPlugin(&autopatcherServer);\r\n\tpacketizedTCP.AttachPlugin(&fileListTransfer);\r\n#else\r\n\tSLNet::RakPeerInterface *rakPeer;\r\n\trakPeer = SLNet::RakPeerInterface::GetInstance();\r\n\tSLNet::SocketDescriptor socketDescriptor(LISTEN_PORT,0);\r\n\trakPeer->Startup(MAX_INCOMING_CONNECTIONS,&socketDescriptor, 1);\r\n\trakPeer->SetMaximumIncomingConnections(MAX_INCOMING_CONNECTIONS);\r\n\trakPeer->AttachPlugin(&autopatcherServer);\r\n\trakPeer->AttachPlugin(&fileListTransfer);\r\n#endif\r\n\tprintf(\"started.\\n\");\r\n\r\n\tprintf(\"Enter database password:\\n\");\r\n\tchar password[128];\r\n\tchar username[256];\r\n\tstrcpy_s(username, \"root\");\r\n\tGets(password,sizeof(password));\r\n\tif (password[0]==0)\r\n\t\tstrcpy_s(password,\"aaaa\");\r\n\tchar db[256];\r\n\tprintf(\"Enter DB schema: \");\r\n\t\/\/ To create the schema, go to the command line client and type create schema autopatcher;\r\n\t\/\/ You also have to add \r\n\t\/\/ max_allowed_packet=128M\r\n\t\/\/ Where 128 is the maximum size file in megabytes you'll ever add\r\n\t\/\/ to MySQL\\MySQL Server 5.1\\my.ini in the [mysqld] section\r\n\t\/\/ Be sure to restart the service after doing so\r\n\tGets(db,sizeof(db));\r\n\tif (db[0]==0)\r\n\t\tstrcpy_s(db,\"autopatcher\");\r\n\tfor (int conIdx=0; conIdx < sqlConnectionObjectCount; conIdx++)\r\n\t{\r\n\t\tif (!connectionObject[conIdx].Connect(\"localhost\", username, password, db, 0, nullptr, 0))\r\n\t\t{\r\n\t\t\tprintf(\"Database connection failed.\\n\");\r\n\t\t\treturn 1;\r\n\t\t}\r\n\t}\r\n\tprintf(\"Database connection suceeded.\\n\");\r\n\r\n\r\n\tprintf(\"Starting threads\\n\");\r\n\tautopatcherServer.StartThreads(workerThreadCount, sqlConnectionObjectCount, connectionObjectAddresses);\r\n\tprintf(\"System ready for connections\\n\");\r\n\r\n\tprintf(\"(D)rop database\\n(C)reate database.\\n(A)dd application\\n(U)pdate revision.\\n(R)emove application\\n(Q)uit\\n\");\r\n\r\n\tint ch;\r\n\tSLNet::Packet *p;\r\n\tfor(;;)\r\n\t{\r\n#ifdef USE_TCP\r\n\t\tSLNet::SystemAddress notificationAddress;\r\n\t\tnotificationAddress=packetizedTCP.HasCompletedConnectionAttempt();\r\n\t\tif (notificationAddress!= SLNet::UNASSIGNED_SYSTEM_ADDRESS)\r\n\t\t\tprintf(\"ID_CONNECTION_REQUEST_ACCEPTED\\n\");\r\n\t\tnotificationAddress=packetizedTCP.HasNewIncomingConnection();\r\n\t\tif (notificationAddress!= SLNet::UNASSIGNED_SYSTEM_ADDRESS)\r\n\t\t\tprintf(\"ID_NEW_INCOMING_CONNECTION\\n\");\r\n\t\tnotificationAddress=packetizedTCP.HasLostConnection();\r\n\t\tif (notificationAddress!= SLNet::UNASSIGNED_SYSTEM_ADDRESS)\r\n\t\t\tprintf(\"ID_CONNECTION_LOST\\n\");\r\n\r\n\t\tp=packetizedTCP.Receive();\r\n\t\twhile (p)\r\n\t\t{\r\n\t\t\tpacketizedTCP.DeallocatePacket(p);\r\n\t\t\tp=packetizedTCP.Receive();\r\n\t\t}\r\n#else\r\n\t\tp=rakPeer->Receive();\r\n\t\twhile (p)\r\n\t\t{\r\n\t\t\tif (p->data[0]==ID_NEW_INCOMING_CONNECTION)\r\n\t\t\t\tprintf(\"ID_NEW_INCOMING_CONNECTION\\n\");\r\n\t\t\telse if (p->data[0]==ID_DISCONNECTION_NOTIFICATION)\r\n\t\t\t\tprintf(\"ID_DISCONNECTION_NOTIFICATION\\n\");\r\n\t\t\telse if (p->data[0]==ID_CONNECTION_LOST)\r\n\t\t\t\tprintf(\"ID_CONNECTION_LOST\\n\");\r\n\r\n\t\t\trakPeer->DeallocatePacket(p);\r\n\t\t\tp=rakPeer->Receive();\r\n\t\t}\r\n#endif\r\n\t\tif (_kbhit())\r\n\t\t{\r\n\t\t\tch=_getch();\r\n\t\t\tif (ch=='q')\r\n\t\t\t\tbreak;\r\n\t\t\telse if (ch=='c')\r\n\t\t\t{\r\n\t\t\t\tif (connectionObject[0].CreateAutopatcherTables()==false)\r\n\t\t\t\t\tprintf(\"Error: %s\\n\", connectionObject[0].GetLastError());\r\n\t\t\t\telse\r\n\t\t\t\t\tprintf(\"Created\\n\");\r\n\t\t\t}\r\n\t\t\telse if (ch=='d')\r\n\t\t\t{\r\n\t\t\t\tif (connectionObject[0].DestroyAutopatcherTables()==false)\r\n\t\t\t\t\tprintf(\"Error: %s\\n\", connectionObject[0].GetLastError());\r\n\t\t\t\telse\r\n\t\t\t\t\tprintf(\"Destroyed\\n\");\r\n\t\t\t}\r\n\t\t\telse if (ch=='a')\r\n\t\t\t{\r\n\t\t\t\tprintf(\"Enter application name to add: \");\r\n\t\t\t\tchar appName[512];\r\n\t\t\t\tGets(appName,sizeof(appName));\r\n\t\t\t\tif (appName[0]==0)\r\n\t\t\t\t\tstrcpy_s(appName, \"TestApp\");\r\n\r\n\t\t\t\tif (connectionObject[0].AddApplication(appName, username)==false)\r\n\t\t\t\t\tprintf(\"Error: %s\\n\", connectionObject[0].GetLastError());\r\n\t\t\t\telse\r\n\t\t\t\t\tprintf(\"Done\\n\");\r\n\t\t\t}\r\n\t\t\telse if (ch=='r')\r\n\t\t\t{\r\n\t\t\t\tprintf(\"Enter application name to remove: \");\r\n\t\t\t\tchar appName[512];\r\n\t\t\t\tGets(appName,sizeof(appName));\r\n\t\t\t\tif (appName[0]==0)\r\n\t\t\t\t\tstrcpy_s(appName, \"TestApp\");\r\n\r\n\t\t\t\tif (connectionObject[0].RemoveApplication(appName)==false)\r\n\t\t\t\t\tprintf(\"Error: %s\\n\", connectionObject[0].GetLastError());\r\n\t\t\t\telse\r\n\t\t\t\t\tprintf(\"Done\\n\");\r\n\t\t\t}\r\n\t\t\telse if (ch=='u')\r\n\t\t\t{\r\n\t\t\t\tprintf(\"Enter application name: \");\r\n\t\t\t\tchar appName[512];\r\n\t\t\t\tGets(appName,sizeof(appName));\r\n\t\t\t\tif (appName[0]==0)\r\n\t\t\t\t\tstrcpy_s(appName, \"TestApp\");\r\n\r\n\t\t\t\tprintf(\"Enter application directory: \");\r\n\t\t\t\tchar appDir[512];\r\n\t\t\t\tGets(appDir,sizeof(appName));\r\n\t\t\t\tif (appDir[0]==0)\r\n\t\t\t\t\tstrcpy_s(appDir, \"C:\/temp\");\r\n\r\n\t\t\t\tif (connectionObject[0].UpdateApplicationFiles(appName, appDir, username, 0)==false)\r\n\t\t\t\t{\r\n\t\t\t\t\tprintf(\"Error: %s\\n\", connectionObject[0].GetLastError());\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tprintf(\"Update success.\\n\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tRakSleep(30);\r\n\r\n\r\n\t}\r\n\r\n#ifdef USE_TCP\r\n\tpacketizedTCP.Stop();\r\n#else\r\n\tSLNet::RakPeerInterface::DestroyInstance(rakPeer);\r\n#endif\r\n}\r\n","avg_line_length":34.1510204082,"max_line_length":157,"alphanum_fraction":0.712919804,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":9497,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/*\n * Copyright (c) 2011, Michael Feathers, James Grenning and Bas Vodde\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and\/or other materials provided with the distribution.\n *     * Neither the name of the <organization> nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifdef CPPUTEST_USE_REAL_GTEST\n\n#undef new\n\n\/* Enormous hack!\n *\n * This sucks enormously. We need to do two things in GTest that seem to not be possible without\n * this hack. Hopefully there is *another way*.\n *\n * We need to access the factory in the TestInfo in order to be able to create tests. The factory\n * is private and there seems to be no way to access it...\n *\n * We need to be able to call the Test SetUp and TearDown methods, but they are protected for\n * some reason. We can't subclass either as the tests are created with the TEST macro.\n *\n * If anyone knows how to get the above things done *without* these ugly #defines, let me know!\n *\n *\/\n\n#define private public\n#define protected public\n\n#include \"gtest\/gtest.h\"\n#include \"gtest\/gtest-spi.h\"\n#include \"gtest\/gtest-death-test.h\"\n#include \"gmock\/gmock.h\"\n\n#ifdef ADD_FAILURE_AT\n#define GTEST_VERSION_GTEST_1_6\n#else\n#define GTEST_VERSION_GTEST_1_5\n#endif\n\n\/*\n * We really need some of its internals as they don't have a public interface.\n *\n *\/\n#define GTEST_IMPLEMENTATION_ 1\n#include \"src\/gtest-internal-inl.h\"\n\n\n#include \"CppUTestExt\/GTestConvertor.h\"\n#include \"CppUTest\/TestRegistry.h\"\n#include \"CppUTest\/TestFailure.h\"\n#include \"CppUTest\/TestResult.h\"\n\n\/* Store some of the flags as we'll need to reset them each test to avoid leaking memory *\/\n\nstatic ::testing::internal::String GTestFlagcolor;\nstatic ::testing::internal::String GTestFlagfilter;\nstatic ::testing::internal::String GTestFlagoutput;\nstatic ::testing::internal::String GTestFlagdeath_test_style;\nstatic ::testing::internal::String GTestFlaginternal_run_death_test;\n#ifndef GTEST_VERSION_GTEST_1_5\nstatic ::testing::internal::String GTestFlagstream_result_to;\n#endif\n\nstatic void storeValuesOfGTestFLags()\n{\n\tGTestFlagcolor = ::testing::GTEST_FLAG(color);\n\tGTestFlagfilter = ::testing::GTEST_FLAG(filter);\n\tGTestFlagoutput = ::testing::GTEST_FLAG(output);\n\tGTestFlagdeath_test_style = ::testing::GTEST_FLAG(death_test_style);\n\tGTestFlaginternal_run_death_test = ::testing::internal::GTEST_FLAG(internal_run_death_test);\n\t#ifndef GTEST_VERSION_GTEST_1_5\n\tGTestFlagstream_result_to = ::testing::GTEST_FLAG(stream_result_to);\n\t#endif\n}\n\nstatic void resetValuesOfGTestFlags()\n{\n\t::testing::GTEST_FLAG(color) = GTestFlagcolor;\n\t::testing::GTEST_FLAG(filter) = GTestFlagfilter;\n\t::testing::GTEST_FLAG(output) = GTestFlagoutput;\n\t::testing::GTEST_FLAG(death_test_style) = GTestFlagdeath_test_style;\n\t::testing::internal::GTEST_FLAG(internal_run_death_test) = GTestFlaginternal_run_death_test;\n\t#ifndef GTEST_VERSION_GTEST_1_5\n\t::testing::GTEST_FLAG(stream_result_to) = GTestFlagstream_result_to;\n\t#endif\n}\n\nvoid setGTestFLagValuesToNULLToAvoidMemoryLeaks()\n{\n\t::testing::GTEST_FLAG(color) = NULL;\n\t::testing::GTEST_FLAG(filter) = NULL;\n\t::testing::GTEST_FLAG(output) = NULL;\n\t::testing::GTEST_FLAG(death_test_style) = NULL;\n\t::testing::internal::GTEST_FLAG(internal_run_death_test) = NULL;\n\t#ifndef GTEST_VERSION_GTEST_1_5\n\t::testing::GTEST_FLAG(stream_result_to) = NULL;\n\t#endif\n}\n\n\/* Left a global to avoid a header dependency to gtest.h *\/\n\nclass GTestDummyResultReporter : public ::testing::ScopedFakeTestPartResultReporter\n{\npublic:\n\tGTestDummyResultReporter () : ::testing::ScopedFakeTestPartResultReporter(INTERCEPT_ALL_THREADS, NULL) {}\n\tvirtual void ReportTestPartResult(const ::testing::TestPartResult& \/*result*\/) {}\n};\n\nclass GTestResultReporter : public ::testing::ScopedFakeTestPartResultReporter\n{\npublic:\n\tGTestResultReporter () : ::testing::ScopedFakeTestPartResultReporter(INTERCEPT_ALL_THREADS, NULL) {}\n\n\tvirtual void ReportTestPartResult(const ::testing::TestPartResult& result)\n\t{\n\t\tFailFailure failure(UtestShell::getCurrent(), result.file_name(), result.line_number(), result.message());\n\t\tUtestShell::getCurrent()->getTestResult()->addFailure(failure);\n\n\t\t\/*\n\t\t * When using GMock, it throws an exception fromt he destructor leaving\n\t\t * the system in an unstable state.\n\t\t * Therefore, when the test fails because of failed gmock expectation\n\t\t * then don't throw the exception, but let it return. Usually this should\n\t\t * already be at the end of the test, so it doesn't matter much\n\t\t *\/\n\t\tif (!SimpleString(result.message()).contains(\"Actual: never called\") &&\n\t\t\t!SimpleString(result.message()).contains(\"Actual function call count doesn't match\"))\n\t\t\tthrow CppUTestFailedException();\n\t}\n};\n\nGTestShell::GTestShell(::testing::TestInfo* testinfo, GTestShell* next) : testinfo_(testinfo), next_(next)\n{\n\tsetGroupName(testinfo->test_case_name());\n\tsetTestName(testinfo->name());\n}\n\nGTestShell* GTestShell::nextGTest()\n{\n\treturn next_;\n}\n\nclass GTestUTest: public Utest {\npublic:\n\tGTestUTest(::testing::TestInfo* testinfo) : testinfo_(testinfo), test_(NULL)\n\t{\n\n\t}\n\n\tvoid testBody()\n\t{\n\t\ttry {\n\t\t\ttest_->TestBody();\n\t\t}\n\t\tcatch (CppUTestFailedException& ex)\n\t\t{\n\t\t}\n\t}\n\n\tvoid setup()\n\t{\n\t\tresetValuesOfGTestFlags();\n\n\t\t#ifdef GTEST_VERSION_GTEST_1_5\n\t\ttest_ = testinfo_->impl()->factory_->CreateTest();\n\t#else\n\t\ttest_ = testinfo_->factory_->CreateTest();\n\t#endif\n\n\t\t::testing::UnitTest::GetInstance()->impl()->set_current_test_info(testinfo_);\n\t\ttry {\n\t\t\ttest_->SetUp();\n\t\t}\n\t\tcatch (CppUTestFailedException& ex)\n\t\t{\n\t\t}\n\t}\n\n\tvoid teardown()\n\t{\n\t\ttry {\n\t\t\ttest_->TearDown();\n\t\t}\n\t\tcatch (CppUTestFailedException& ex)\n\t\t{\n\t\t}\n\t\t::testing::UnitTest::GetInstance()->impl()->set_current_test_info(NULL);\n\t\tdelete test_;\n\n\t\tsetGTestFLagValuesToNULLToAvoidMemoryLeaks();\n\t\t::testing::internal::DeathTest::set_last_death_test_message(NULL);\n\t}\n\nprivate:\n\t::testing::Test* test_;\n\t::testing::TestInfo* testinfo_;\n};\n\nUtest* GTestShell::createTest()\n{\n\treturn new GTestUTest(testinfo_);\n};\n\nvoid GTestConvertor::simulateGTestFailureToPreAllocateAllTheThreadLocalData()\n{\n\tGTestDummyResultReporter *dummyReporter = new GTestDummyResultReporter();\n\tASSERT_TRUE(false);\n\tdelete dummyReporter;\n}\n\nGTestConvertor::GTestConvertor(bool shouldSimulateFailureAtCreationToAllocateThreadLocalData) : first_(NULL)\n{\n\tif (shouldSimulateFailureAtCreationToAllocateThreadLocalData)\n\t\tsimulateGTestFailureToPreAllocateAllTheThreadLocalData();\n\treporter_ = new GTestResultReporter();\n}\n\nGTestConvertor::~GTestConvertor()\n{\n\tdelete reporter_;\n\n\twhile (first_) {\n\t\tGTestShell* next = first_->nextGTest();\n\t\tdelete first_;\n\t\tfirst_ = next;\n\t}\n}\n\nvoid GTestConvertor::addNewTestCaseForTestInfo(::testing::TestInfo* testinfo)\n{\n\tfirst_ = new GTestShell(testinfo, first_);\n\tTestRegistry::getCurrentRegistry()->addTest(first_);\n}\n\nvoid GTestConvertor::addAllTestsFromTestCaseToTestRegistry(::testing::TestCase* testcase)\n{\n\tint currentTestCount = 0;\n\t::testing::TestInfo* currentTest = (::testing::TestInfo*) testcase->GetTestInfo(currentTestCount);\n\twhile (currentTest) {\n\t\taddNewTestCaseForTestInfo(currentTest);\n\t\tcurrentTestCount++;\n\t\tcurrentTest = (::testing::TestInfo*) testcase->GetTestInfo(currentTestCount);\n\t}\n}\n\nvoid GTestConvertor::createDummyInSequenceToAndFailureReporterAvoidMemoryLeakInGMock()\n{\n#ifdef CPPUTEST_USE_REAL_GMOCK\n\t::testing::InSequence seq;\n\t::testing::internal::GetFailureReporter();\n#endif\n}\n\nvoid GTestConvertor::addAllGTestToTestRegistry()\n{\n\tcreateDummyInSequenceToAndFailureReporterAvoidMemoryLeakInGMock();\n\tstoreValuesOfGTestFLags();\n\n#ifdef CPPUTEST_USE_REAL_GMOCK\n\tint argc = 2;\n\tconst char * argv[] = {\"NameOfTheProgram\", \"--gmock_catch_leaked_mocks=0\"};\n\t::testing::InitGoogleMock(&argc, (char**) argv);\n#endif\n\n\t::testing::UnitTest* unitTests = ::testing::UnitTest::GetInstance();\n\n\tint currentUnitTestCount = 0;\n\t::testing::TestCase* currentTestCase = (::testing::TestCase*) unitTests->GetTestCase(currentUnitTestCount);\n\twhile (currentTestCase) {\n\t\taddAllTestsFromTestCaseToTestRegistry(currentTestCase);\n\t\tcurrentUnitTestCount++;\n\t\tcurrentTestCase = (::testing::TestCase*) unitTests->GetTestCase(currentUnitTestCount);\n\t}\n}\n#else\n\nint totallyDummySymbolToNotCauseAnyLinkerWarningsAboutEmptyCompilationUnits = 0;\n\n#endif\n","avg_line_length":31.5514950166,"max_line_length":108,"alphanum_fraction":0.7637148573,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7085,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/**\n *    Copyright (C) 2014 MongoDB Inc.\n *\n *    This program is free software: you can redistribute it and\/or  modify\n *    it under the terms of the GNU Affero General Public License, version 3,\n *    as published by the Free Software Foundation.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU Affero General Public License for more details.\n *\n *    You should have received a copy of the GNU Affero General Public License\n *    along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *    As a special exception, the copyright holders give permission to link the\n *    code of portions of this program with the OpenSSL library under certain\n *    conditions as described in each individual source file and distribute\n *    linked combinations including the program with the OpenSSL library. You\n *    must comply with the GNU Affero General Public License in all respects for\n *    all of the code used other than as permitted herein. If you modify file(s)\n *    with this exception, you may extend this exception to your version of the\n *    file(s), but you are not obligated to do so. If you do not wish to do so,\n *    delete this exception statement from your version. If you delete this\n *    exception statement from all source files in the program, then also delete\n *    it in the license file.\n *\/\n\n#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kDefault\n\n#include \"mongo\/db\/dbdirectclient.h\"\n\n#include \"mongo\/db\/client.h\"\n#include \"mongo\/db\/commands.h\"\n#include \"mongo\/db\/instance.h\"\n#include \"mongo\/db\/lasterror.h\"\n#include \"mongo\/db\/operation_context.h\"\n#include \"mongo\/util\/log.h\"\n\nnamespace mongo {\n\n    using std::auto_ptr;\n    using std::endl;\n    using std::string;\n\n    \/\/ Called from scripting\/engine.cpp and scripting\/v8_db.cpp.\n    DBClientBase* createDirectClient(OperationContext* txn) {\n        return new DBDirectClient(txn);\n    }\n\n    namespace {\n\n        class DirectClientScope {\n            MONGO_DISALLOW_COPYING(DirectClientScope);\n        public:\n            explicit DirectClientScope(OperationContext* txn)\n                : _txn(txn), _prev(_txn->getClient()->isInDirectClient()) {\n                _txn->getClient()->setInDirectClient(true);\n            }\n\n            ~DirectClientScope() {\n                _txn->getClient()->setInDirectClient(_prev);\n            }\n\n        private:\n            OperationContext* const _txn;\n            const bool _prev;\n        };\n\n    }  \/\/ namespace\n\n\n    DBDirectClient::DBDirectClient(OperationContext* txn)  : _txn(txn) { }\n\n    bool DBDirectClient::isFailed() const {\n        return false;\n    }\n\n    bool DBDirectClient::isStillConnected() {\n        return true;\n    }\n\n    std::string DBDirectClient::toString() const {\n        return \"DBDirectClient\";\n    }\n\n    std::string DBDirectClient::getServerAddress() const {\n        return \"localhost\"; \/\/ TODO: should this have the port?\n    }\n\n    void DBDirectClient::sayPiggyBack(Message& toSend) {\n        \/\/ don't need to piggy back when connected locally\n        return say(toSend);\n    }\n\n    bool DBDirectClient::callRead(Message& toSend, Message& response) {\n        return call(toSend, response);\n    }\n\n    ConnectionString::ConnectionType DBDirectClient::type() const {\n        return ConnectionString::MASTER;\n    }\n\n    double DBDirectClient::getSoTimeout() const {\n        return 0;\n    }\n\n    bool DBDirectClient::lazySupported() const {\n        return true;\n    }\n\n    void DBDirectClient::setOpCtx(OperationContext* txn) {\n        _txn = txn;\n    }\n\n    QueryOptions DBDirectClient::_lookupAvailableOptions() {\n        \/\/ Exhaust mode is not available in DBDirectClient.\n        return QueryOptions(DBClientBase::_lookupAvailableOptions() & ~QueryOption_Exhaust);\n    }\n\n    bool DBDirectClient::call(Message& toSend,\n                              Message& response,\n                              bool assertOk,\n                              string* actualServer) {\n        DirectClientScope directClientScope(_txn);\n        LastError::get(_txn->getClient()).startRequest();\n\n        DbResponse dbResponse;\n        assembleResponse(_txn, toSend, dbResponse, dummyHost);\n        verify(dbResponse.response);\n\n        \/\/ can get rid of this if we make response handling smarter\n        dbResponse.response->concat();\n        response = *dbResponse.response;\n\n        return true;\n    }\n\n    void DBDirectClient::say(Message& toSend, bool isRetry, string* actualServer) {\n        DirectClientScope directClientScope(_txn);\n        LastError::get(_txn->getClient()).startRequest();\n\n        DbResponse dbResponse;\n        assembleResponse(_txn, toSend, dbResponse, dummyHost);\n    }\n\n    auto_ptr<DBClientCursor> DBDirectClient::query(const string& ns,\n                                                   Query query,\n                                                   int nToReturn,\n                                                   int nToSkip,\n                                                   const BSONObj* fieldsToReturn,\n                                                   int queryOptions,\n                                                   int batchSize) {\n\n        return DBClientBase::query(ns,\n                                   query,\n                                   nToReturn,\n                                   nToSkip,\n                                   fieldsToReturn,\n                                   queryOptions,\n                                   batchSize);\n    }\n\n    void DBDirectClient::killCursor(long long id) {\n        \/\/ The killCursor command on the DB client is only used by sharding,\n        \/\/ so no need to have it for MongoD.\n        verify(!\"killCursor should not be used in MongoD\");\n    }\n\n    const HostAndPort DBDirectClient::dummyHost(\"0.0.0.0\", 0);\n\n    unsigned long long DBDirectClient::count(const string& ns,\n                                             const BSONObj& query,\n                                             int options,\n                                             int limit,\n                                             int skip) {\n        BSONObj cmdObj = _countCmd(ns, query, options, limit, skip);\n\n        NamespaceString nsString(ns);\n        std::string dbname = nsString.db().toString();\n\n        Command* countCmd = Command::findCommand(\"count\");\n        invariant(countCmd);\n\n        std::string errmsg;\n        BSONObjBuilder result;\n        bool runRetval = countCmd->run(_txn, dbname, cmdObj, options, errmsg, result);\n        if (!runRetval) {\n            Command::appendCommandStatus(result, runRetval, errmsg);\n            Status commandStatus = Command::getStatusFromCommandResult(result.obj());\n            invariant(!commandStatus.isOK());\n            uassertStatusOK(commandStatus);\n        }\n\n        BSONObj resultObj = result.obj();\n        return static_cast<unsigned long long>(resultObj[\"n\"].numberLong());\n    }\n\n}  \/\/ namespace mongo\n","avg_line_length":35.425,"max_line_length":92,"alphanum_fraction":0.5968948483,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6069,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2018 The Bitcoin developers\n\/\/ Copyright (c) 2014-2018 The Dash developers\n\/\/ Copyright (c) 2015-2018 The PIVX developers\n\/\/ Copyright (c) 2018 The BETXOIN Developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"clientversion.h\"\n#include \"init.h\"\n#include \"main.h\"\n#include \"masternodeconfig.h\"\n#include \"noui.h\"\n#include \"rpcserver.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/thread.hpp>\n\n\/* Introduction text for doxygen: *\/\n\n\/*! \\mainpage Developer documentation\n *\n * \\section intro_sec Introduction\n *\n * This is the developer documentation of the reference client for an experimental new digital currency called BETXOIN (http:\/\/www.betxoin.io),\n * which enables instant payments to anyone, anywhere in the world. BETXOIN uses peer-to-peer technology to operate\n * with no central authority: managing transactions and issuing money are carried out collectively by the network.\n *\n * The software is a community-driven open source project, released under the MIT license.\n *\n * \\section Navigation\n * Use the buttons <code>Namespaces<\/code>, <code>Classes<\/code> or <code>Files<\/code> at the top of the page to start navigating the code.\n *\/\n\nstatic bool fDaemon;\n\nvoid DetectShutdownThread(boost::thread_group* threadGroup)\n{\n    bool fShutdown = ShutdownRequested();\n    \/\/ Tell the main threads to shutdown.\n    while (!fShutdown) {\n        MilliSleep(200);\n        fShutdown = ShutdownRequested();\n    }\n    if (threadGroup) {\n        threadGroup->interrupt_all();\n        threadGroup->join_all();\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Start\n\/\/\nbool AppInit(int argc, char* argv[])\n{\n    boost::thread_group threadGroup;\n    boost::thread* detectShutdownThread = NULL;\n\n    bool fRet = false;\n\n    \/\/\n    \/\/ Parameters\n    \/\/\n    \/\/ If Qt is used, parameters\/betxoin.conf are parsed in qt\/betxoin.cpp's main()\n    ParseParameters(argc, argv);\n\n    \/\/ Process help and version before taking care about datadir\n    if (mapArgs.count(\"-?\") || mapArgs.count(\"-help\") || mapArgs.count(\"-version\")) {\n        std::string strUsage = _(\"BETXOIN Core Daemon\") + \" \" + _(\"version\") + \" \" + FormatFullVersion() + \"\\n\";\n\n        if (mapArgs.count(\"-version\")) {\n            strUsage += LicenseInfo();\n        } else {\n            strUsage += \"\\n\" + _(\"Usage:\") + \"\\n\" +\n                        \"  betxoind [options]                     \" + _(\"Start BETXOIN Core Daemon\") + \"\\n\";\n\n            strUsage += \"\\n\" + HelpMessage(HMM_BITCOIND);\n        }\n\n        fprintf(stdout, \"%s\", strUsage.c_str());\n        return false;\n    }\n\n    try {\n        if (!boost::filesystem::is_directory(GetDataDir(false))) {\n            fprintf(stderr, \"Error: Specified data directory \\\"%s\\\" does not exist.\\n\", mapArgs[\"-datadir\"].c_str());\n            return false;\n        }\n        try {\n            ReadConfigFile(mapArgs, mapMultiArgs);\n        } catch (std::exception& e) {\n            fprintf(stderr, \"Error reading configuration file: %s\\n\", e.what());\n            return false;\n        }\n        \/\/ Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)\n        if (!SelectParamsFromCommandLine()) {\n            fprintf(stderr, \"Error: Invalid combination of -regtest and -testnet.\\n\");\n            return false;\n        }\n\n        \/\/ parse masternode.conf\n        std::string strErr;\n        if (!masternodeConfig.read(strErr)) {\n            fprintf(stderr, \"Error reading masternode configuration file: %s\\n\", strErr.c_str());\n            return false;\n        }\n\n        \/\/ Command-line RPC\n        bool fCommandLine = false;\n        for (int i = 1; i < argc; i++)\n            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], \"betxoin:\"))\n                fCommandLine = true;\n\n        if (fCommandLine) {\n            fprintf(stderr, \"Error: There is no RPC client functionality in betxoind anymore. Use the betxoin-cli utility instead.\\n\");\n            exit(1);\n        }\n#ifndef WIN32\n        fDaemon = GetBoolArg(\"-daemon\", false);\n        if (fDaemon) {\n            fprintf(stdout, \"BETXOIN server starting\\n\");\n\n            \/\/ Daemonize\n            pid_t pid = fork();\n            if (pid < 0) {\n                fprintf(stderr, \"Error: fork() returned %d errno %d\\n\", pid, errno);\n                return false;\n            }\n            if (pid > 0) \/\/ Parent process, pid is child process id\n            {\n                return true;\n            }\n            \/\/ Child process falls through to rest of initialization\n\n            pid_t sid = setsid();\n            if (sid < 0)\n                fprintf(stderr, \"Error: setsid() returned %d errno %d\\n\", sid, errno);\n        }\n#endif\n        SoftSetBoolArg(\"-server\", true);\n\n        detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));\n        fRet = AppInit2(threadGroup);\n    } catch (std::exception& e) {\n        PrintExceptionContinue(&e, \"AppInit()\");\n    } catch (...) {\n        PrintExceptionContinue(NULL, \"AppInit()\");\n    }\n\n    if (!fRet) {\n        if (detectShutdownThread)\n            detectShutdownThread->interrupt();\n\n        threadGroup.interrupt_all();\n        \/\/ threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of\n        \/\/ the startup-failure cases to make sure they don't result in a hang due to some\n        \/\/ thread-blocking-waiting-for-another-thread-during-startup case\n    }\n\n    if (detectShutdownThread) {\n        detectShutdownThread->join();\n        delete detectShutdownThread;\n        detectShutdownThread = NULL;\n    }\n    Shutdown();\n\n    return fRet;\n}\n\nint main(int argc, char* argv[])\n{\n    SetupEnvironment();\n\n    \/\/ Connect betxoind signal handlers\n    noui_connect();\n\n    return (AppInit(argc, argv) ? 0 : 1);\n}\n","avg_line_length":33.1639344262,"max_line_length":143,"alphanum_fraction":0.6024056681,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13886,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":4.0,"content":"\/*\n###############################################################################\n# If you use PhysiCell in your project, please cite PhysiCell and the version #\n# number, such as below:                                                      #\n#                                                                             #\n# We implemented and solved the model using PhysiCell (Version x.y.z) [1].    #\n#                                                                             #\n# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #\n#     PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu-  #\n#     lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018                   #\n#     DOI: 10.1371\/journal.pcbi.1005991                                       #\n#                                                                             #\n# See VERSION.txt or call get_PhysiCell_version() to get the current version  #\n#     x.y.z. Call display_citations() to get detailed information on all cite-#\n#     able software used in your PhysiCell application.                       #\n#                                                                             #\n# Because PhysiCell extensively uses BioFVM, we suggest you also cite BioFVM  #\n#     as below:                                                               #\n#                                                                             #\n# We implemented and solved the model using PhysiCell (Version x.y.z) [1],    #\n# with BioFVM [2] to solve the transport equations.                           #\n#                                                                             #\n# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #\n#     PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu-  #\n#     lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018                   #\n#     DOI: 10.1371\/journal.pcbi.1005991                                       #\n#                                                                             #\n# [2] A Ghaffarizadeh, SH Friedman, and P Macklin, BioFVM: an efficient para- #\n#     llelized diffusive transport solver for 3-D biological simulations,     #\n#     Bioinformatics 32(8): 1256-8, 2016. DOI: 10.1093\/bioinformatics\/btv730  #\n#                                                                             #\n###############################################################################\n#                                                                             #\n# BSD 3-Clause License (see https:\/\/opensource.org\/licenses\/BSD-3-Clause)     #\n#                                                                             #\n# Copyright (c) 2015-2021, Paul Macklin and the PhysiCell Project             #\n# All rights reserved.                                                        #\n#                                                                             #\n# Redistribution and use in source and binary forms, with or without          #\n# modification, are permitted provided that the following conditions are met: #\n#                                                                             #\n# 1. Redistributions of source code must retain the above copyright notice,   #\n# this list of conditions and the following disclaimer.                       #\n#                                                                             #\n# 2. Redistributions in binary form must reproduce the above copyright        #\n# notice, this list of conditions and the following disclaimer in the         #\n# documentation and\/or other materials provided with the distribution.        #\n#                                                                             #\n# 3. Neither the name of the copyright holder nor the names of its            #\n# contributors may be used to endorse or promote products derived from this   #\n# software without specific prior written permission.                         #\n#                                                                             #\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" #\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE   #\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE  #\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE   #\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR         #\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF        #\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS    #\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN     #\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)     #\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE  #\n# POSSIBILITY OF SUCH DAMAGE.                                                 #\n#                                                                             #\n###############################################################################\n*\/\n\n#include \".\/custom.h\"\n\nvoid create_cell_types( void )\n{\n\t\/\/ set the random seed \n\tSeedRandom( parameters.ints(\"random_seed\") );  \n\t\n\t\/* \n\t   Put any modifications to default cell definition here if you \n\t   want to have \"inherited\" by other cell types. \n\t   \n\t   This is a good place to set default functions. \n\t*\/ \n\t\n\tinitialize_default_cell_definition(); \n\tcell_defaults.phenotype.secretion.sync_to_microenvironment( &microenvironment ); \n\t\n\tcell_defaults.functions.volume_update_function = standard_volume_update_function;\n\tcell_defaults.functions.update_velocity = standard_update_cell_velocity;\n\n\tcell_defaults.functions.update_migration_bias = NULL; \n\tcell_defaults.functions.update_phenotype = NULL; \/\/ update_cell_and_death_parameters_O2_based; \n\tcell_defaults.functions.custom_cell_rule = NULL; \n\t\n\tcell_defaults.functions.add_cell_basement_membrane_interactions = NULL;  \n\tcell_defaults.functions.calculate_distance_to_membrane = NULL; \n\t\n\t\/*\n\t   This parses the cell definitions in the XML config file. \n\t*\/\n\t\n\tinitialize_cell_definitions_from_pugixml(); \n\t\n\t\/* \n\t   Put any modifications to individual cell definitions here. \n\t   \n\t   This is a good place to set custom functions. \n\t*\/ \n\t\n\tcell_defaults.functions.update_phenotype = NULL; \n\tcell_defaults.functions.custom_cell_rule = custom_function; \n\tcell_defaults.functions.contact_function = contact_function; \n\t\n\tcell_defaults.phenotype.mechanics.attachment_elastic_constant = \n\t\tparameters.doubles(\"attachment_elastic_constant\"); \n\t\t\n\t\/*\n\t   This builds the map of cell definitions and summarizes the setup. \n\t*\/\n\t\t\n\tbuild_cell_definitions_maps(); \n\tdisplay_cell_definitions( std::cout ); \n\t\n\treturn; \n}\n\nvoid setup_microenvironment( void )\n{\n\t\/\/ set domain parameters \n\t\n\t\/\/ put any custom code to set non-homogeneous initial conditions or \n\t\/\/ extra Dirichlet nodes here. \n\t\n\t\/\/ initialize BioFVM \n\t\n\tinitialize_microenvironment(); \t\n\t\n\treturn; \n}\n\nvoid setup_tissue( void )\n{\n\tdouble Xmin = microenvironment.mesh.bounding_box[0]; \n\tdouble Ymin = microenvironment.mesh.bounding_box[1]; \n\tdouble Zmin = microenvironment.mesh.bounding_box[2]; \n\n\tdouble Xmax = microenvironment.mesh.bounding_box[3]; \n\tdouble Ymax = microenvironment.mesh.bounding_box[4]; \n\tdouble Zmax = microenvironment.mesh.bounding_box[5]; \n\t\n\tif( default_microenvironment_options.simulate_2D == true )\n\t{\n\t\tZmin = 0.0; \n\t\tZmax = 0.0; \n\t}\n\t\n\tdouble Xrange = Xmax - Xmin; \n\tdouble Yrange = Ymax - Ymin; \n\tdouble Zrange = Zmax - Zmin; \n\t\n\t\/\/ create some of each type of cell \n\t\n\tCell* pC;\n\t\n\tfor( int k=0; k < cell_definitions_by_index.size() ; k++ )\n\t{\n\t\tCell_Definition* pCD = cell_definitions_by_index[k]; \n\t\tstd::cout << \"Placing cells of type \" << pCD->name << \" ... \" << std::endl; \n\t\tfor( int n = 0 ; n < parameters.ints(\"number_of_cells\") ; n++ )\n\t\t{\n\t\t\tstd::vector<double> position = {0,0,0}; \n\t\t\tposition[0] = Xmin + UniformRandom()*Xrange; \n\t\t\tposition[1] = Ymin + UniformRandom()*Yrange; \n\t\t\tposition[2] = Zmin + UniformRandom()*Zrange; \n\t\t\t\n\t\t\tpC = create_cell( *pCD ); \n\t\t\tpC->assign_position( position );\n\t\t}\n\t}\n\tstd::cout << std::endl; \n\t\n\t\/\/ load cells from your CSV file (if enabled)\n\tload_cells_from_pugixml(); \t\n\t\n\t\/\/ set the initial value of all the cells \n\tfor( int n=0; n < (*all_cells).size(); n++ )\n\t{\n\t\tCell* pC = (*all_cells)[n]; \n\t\tpC->custom_data[\"head\"] = UniformRandom(); \n\t\tpC->custom_data[\"head_initial\"] = pC->custom_data[\"head\"];\n\t}\n\t\n\treturn; \n}\n\nstd::vector<std::string> my_coloring_function( Cell* pCell )\n{\n\tif( pCell->state.number_of_attached_cells() == 0 )\n\t{ return { \"grey\", \"black\", \"grey\", \"grey\"}; }\n\n\tif( pCell->state.number_of_attached_cells() == 1 )\n\t{\n\t\tif( pCell->custom_data[\"head\"] > pCell->state.attached_cells[0]->custom_data[\"head\"] )\n\t\t{ return { \"red\", \"black\", \"red\", \"red\"};  } \n\t\t\n\t\treturn { \"orange\", \"black\", \"orange\", \"orange\"}; \n\t}\n\n\tif( pCell->state.number_of_attached_cells() >= 2 )\n\t{\n\t\t\/\/ shaed by head protein value \n\t\tint intensity = (int) floor( 255.0 * pCell->custom_data[\"head\"] ); \n\t\tstd::string strColor = std::to_string(intensity); \n\t\tstd::string color = \"rgb(\" + strColor + \",\" + strColor + \",255)\"; \n\t\t\n\t\tif( pCell->state.number_of_attached_cells() > 2 )\n\t\t{ return { \"yellow\", \"black\" , color, color }; }\n\n\t\treturn { color , \"black\", color, color}; \t\n\t}\n\n\treturn { \"yellow\", \"black\", \"yellow\", \"yellow\" }; \n}\n\nvoid phenotype_function( Cell* pCell, Phenotype& phenotype, double dt )\n{ return; }\n\nvoid custom_function( Cell* pCell, Phenotype& phenotype , double dt )\n{\n\t\/\/ bookkeeping \n\t\n\tstatic int nSignal = microenvironment.find_density_index(\"signal\");\n\t\n\t\/\/ look for cells to form attachments, if 0 attachments\n\tint number_of_attachments = pCell->state.number_of_attached_cells(); \n\tstd::vector<Cell*> nearby = pCell->nearby_interacting_cells(); \n\t\n\tif( number_of_attachments == 0 )\n\t{\n\t\tint n = 0; \n\t\twhile( number_of_attachments < (int) pCell->custom_data[\"max_attachments\"] && n < nearby.size() )\n\t\t{\n\t\t\tif( nearby[n]->state.number_of_attached_cells() < nearby[n]->custom_data[\"max_attachments\"] )\n\t\t\t{\n\t\t\t\tattach_cells( nearby[n] , pCell ); \n\t\t\t\tnumber_of_attachments++;\n\t\t\t}\n\t\t\tn++; \n\t\t}\n\t}\n\n\t\/\/ if no attachments, use chemotaxis \n\tif( number_of_attachments == 0 )\n\t{ pCell->functions.update_migration_bias = chemotaxis_function; } \n\t\n\t\/\/ if 1 attachment, do some logic  \n\tif( number_of_attachments == 1 )\n\t{\n\t\t\/\/ constant expression in end cells \n\t\tpCell->custom_data[\"head\"] = pCell->custom_data[\"head_initial\"];\n\n\t\t\/\/ am I the head? \n\t\tbool head = false; \n\t\tif( pCell->custom_data[\"head\"] > pCell->state.attached_cells[0]->custom_data[\"head\"] )\n\t\t{ head = true; } \n\t\t\n\t\tif( head )\n\t\t{ pCell->functions.update_migration_bias = head_migration_direction; }\n\t\telse\n\t\t{ pCell->functions.update_migration_bias = tail_migration_direction; }\n\t\tphenotype.secretion.secretion_rates[nSignal] = 100; \n\t} \n\t\n\t\/\/ if 2 or more attachments, use middle \n\tif( number_of_attachments > 1 )\n\t{\n\t\tpCell->functions.update_migration_bias = middle_migration_direction;\n\t\tphenotype.secretion.secretion_rates[nSignal] = 1; \n\t} \n\t\n\treturn; \n} \n\nvoid contact_function( Cell* pMe, Phenotype& phenoMe, \n\tCell* pOther, Phenotype& phenoOther, double dt )\n{\n\t\/\/ spring-like adhesion \n\tstandard_elastic_contact_function(pMe,phenoMe,pOther,phenoOther,dt);\n\n\t\/\/ juxtacrine \n\tif( pMe->state.number_of_attached_cells() > 0 )\n\t{\n\t\tdouble head_me = pMe->custom_data[\"head\"];\n\t\tdouble head_other = pOther->custom_data[\"head\"]; \n\t\t\n\t\t\/\/ avoid double-counting transfer: \n\t\t\/\/ Only do the high -> low transfers\n\t\t\/\/ One cell of each pair will satisfy this. \n\t\t\t\n\t\t\/\/ make the transfer \n\t\tif( head_me > head_other )\n\t\t{\n\t\t\tdouble amount_to_transfer = dt * pMe->custom_data[\"transfer_rate\"] \n\t\t\t\t* (head_me - head_other ); \n\t\t\tpMe->custom_data[\"head\"] -= amount_to_transfer; \n\t\t\t#pragma omp critical\n\t\t\t{ pOther->custom_data[\"head\"] += amount_to_transfer; }\n\t\t}\t\n\t}\n\n}\n\nvoid head_migration_direction( Cell* pCell, Phenotype& phenotype, double dt )\n{\n\tphenotype.motility.chemotaxis_direction = parameters.doubles(\"head_migration_direction\"); \n\t\n\tphenotype.motility.migration_speed = parameters.doubles(\"head_migration_speed\"); \n\tphenotype.motility.migration_bias = parameters.doubles(\"head_migration_bias\");\n\tphenotype.motility.persistence_time =parameters.doubles(\"head_migration_persistence\"); \n\t\n\t\/\/ use this for fun rotational paths \n\t\/*\n\tdouble r = norm( pCell->position ) + 1e-16; \n\tphenotype.motility.migration_bias_direction[0] = - pCell->position[1] \/ r; \n\tphenotype.motility.migration_bias_direction[1] = pCell->position[0] \/ r; \n\n\tnormalize( &(phenotype.motility.migration_bias_direction) ); \n\treturn; \n\t*\/\n\t\n\treturn chemotaxis_function( pCell,phenotype,dt); \n}\n\nvoid tail_migration_direction( Cell* pCell, Phenotype& phenotype, double dt )\n{\n\tphenotype.motility.chemotaxis_direction = parameters.doubles(\"tail_migration_direction\"); \n\t\n\tphenotype.motility.migration_speed = parameters.doubles(\"tail_migration_speed\");  0; \n\tphenotype.motility.migration_bias = parameters.doubles(\"tail_migration_bias\");0.5; \n\tphenotype.motility.persistence_time = parameters.doubles(\"tail_migration_persistence\"); 100; \n\n\treturn chemotaxis_function( pCell,phenotype,dt); \n}\n\nvoid middle_migration_direction( Cell* pCell, Phenotype& phenotype , double dt )\n{\n\t\/\/ get velocity from \"Upstream\" \n\tCell* pUpstream = pCell->state.attached_cells[0]; \n\n\tif( pCell->state.attached_cells[1]->custom_data[\"head\"] > \n\t\tpCell->state.attached_cells[0]->custom_data[\"head\"] )\n\t{ pUpstream = pCell->state.attached_cells[1]; }\n\t\n\tphenotype.motility.migration_speed = parameters.doubles(\"middle_migration_speed\"); \n\tphenotype.motility.migration_bias_direction = \n\t\tpUpstream->phenotype.motility.migration_bias_direction;\n\t\t\n\tnormalize( &(phenotype.motility.migration_bias_direction) ); \n\t\t\n\treturn; \n}\n\n\n","avg_line_length":38.4653739612,"max_line_length":99,"alphanum_fraction":0.6133515771,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1976,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2012-2013 The Bitcoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"pubkey.h\"\n#include \"key.h\"\n#include \"script\/script.h\"\n#include \"script\/standard.h\"\n#include \"arith_uint256.h\"\n\n#include <vector>\n\n#include <boost\/foreach.hpp>\n#include <boost\/test\/unit_test.hpp>\n\nusing namespace std;\n\n\/\/ Helpers:\nstatic std::vector<unsigned char>\nSerialize(const CScript& s)\n{\n    std::vector<unsigned char> sSerialized(s);\n    return sSerialized;\n}\n\nBOOST_AUTO_TEST_SUITE(sigopcount_tests)\n\nBOOST_AUTO_TEST_CASE(GetSigOpCount)\n{\n    \/\/ Test CScript::GetSigOpCount()\n    CScript s1;\n    BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 0U);\n    BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 0U);\n\n    uint160 dummy(0);\n    s1 << OP_1 << ToByteVector(dummy) << ToByteVector(dummy) << OP_2 << OP_CHECKMULTISIG;\n    BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 2U);\n    s1 << OP_IF << OP_CHECKSIG << OP_ENDIF;\n    BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 3U);\n    BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 21U);\n\n    CScript p2sh = GetScriptForDestination(CScriptID(s1));\n    CScript scriptSig;\n    scriptSig << OP_0 << Serialize(s1);\n    BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig), 3U);\n\n    std::vector<CPubKey> keys;\n    for (int i = 0; i < 3; i++)\n    {\n        CKey k;\n        k.MakeNewKey(true);\n        keys.push_back(k.GetPubKey());\n    }\n    CScript s2 = GetScriptForMultisig(1, keys);\n    BOOST_CHECK_EQUAL(s2.GetSigOpCount(true), 3U);\n    BOOST_CHECK_EQUAL(s2.GetSigOpCount(false), 20U);\n\n    p2sh = GetScriptForDestination(CScriptID(s2));\n    BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(true), 0U);\n    BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(false), 0U);\n    CScript scriptSig2;\n    scriptSig2 << OP_1 << ToByteVector(dummy) << ToByteVector(dummy) << Serialize(s2);\n    BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig2), 3U);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":29.4925373134,"max_line_length":89,"alphanum_fraction":0.7110323887,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4684,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n * StreamEncoderRAW.cpp\n * --------------------\n * Purpose: Exporting streamed music files.\n * Notes  : none\n * Authors: Joern Heusipp\n *          OpenMPT Devs\n * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.\n *\/\n\n#include \"stdafx.h\"\n\n#include \"StreamEncoder.h\"\n#include \"StreamEncoderRAW.h\"\n\n#include \"Mptrack.h\"\n#include \"TrackerSettings.h\"\n\n#include \"..\/common\/mptFileIO.h\"\n#include \"..\/soundlib\/Sndfile.h\"\n\n\nOPENMPT_NAMESPACE_BEGIN\n\n\nclass RawStreamWriter : public IAudioStreamEncoder\n{\nprivate:\n\tconst RAWEncoder &enc;\n\tstd::ostream &f;\n\tEncoder::Settings settings;\n\npublic:\n\tRawStreamWriter(const RAWEncoder &enc_, std::ostream &file, const Encoder::Settings &settings_, const FileTags &tags)\n\t\t: enc(enc_)\n\t\t, f(file)\n\t\t, settings(settings_)\n\t{\n\t\tMPT_ASSERT(settings.Samplerate > 0);\n\t\tMPT_ASSERT(settings.Channels > 0);\n\t\tMPT_UNREFERENCED_PARAMETER(tags);\n\t}\n\tSampleFormat GetSampleFormat() const override\n\t{\n\t\treturn settings.Format.GetSampleFormat();\n\t}\n\tvoid WriteInterleaved(std::size_t frameCount, const double *interleaved) override\n\t{\n\t\tWriteInterleavedBE(f, settings.Channels, settings.Format, frameCount, interleaved);\n\t}\n\tvoid WriteInterleaved(std::size_t frameCount, const float *interleaved) override\n\t{\n\t\tWriteInterleavedBE(f, settings.Channels, settings.Format, frameCount, interleaved);\n\t}\n\tvoid WriteInterleaved(std::size_t frameCount, const int32 *interleaved) override\n\t{\n\t\tWriteInterleavedBE(f, settings.Channels, settings.Format, frameCount, interleaved);\n\t}\n\tvoid WriteInterleaved(std::size_t frameCount, const int24 *interleaved) override\n\t{\n\t\tWriteInterleavedBE(f, settings.Channels, settings.Format, frameCount, interleaved);\n\t}\n\tvoid WriteInterleaved(std::size_t frameCount, const int16 *interleaved) override\n\t{\n\t\tWriteInterleavedBE(f, settings.Channels, settings.Format, frameCount, interleaved);\n\t}\n\tvoid WriteInterleaved(std::size_t frameCount, const int8 *interleaved) override\n\t{\n\t\tWriteInterleavedBE(f, settings.Channels, settings.Format, frameCount, interleaved);\n\t}\n\tvoid WriteInterleaved(std::size_t frameCount, const uint8 *interleaved) override\n\t{\n\t\tWriteInterleavedBE(f, settings.Channels, settings.Format, frameCount, interleaved);\n\t}\n\tvoid WriteCues(const std::vector<uint64> &cues) override\n\t{\n\t\tMPT_UNREFERENCED_PARAMETER(cues);\n\t}\n\tvoid WriteFinalize() override\n\t{\n\t\t\/\/ nothing\n\t}\n\tvirtual ~RawStreamWriter()\n\t{\n\t\t\/\/ nothing\n\t}\n};\n\n\n\nRAWEncoder::RAWEncoder()\n{\n\tEncoder::Traits traits;\n\ttraits.fileExtension = P_(\"raw\");\n\ttraits.fileShortDescription = U_(\"Raw PCM\");\n\ttraits.fileDescription = U_(\"Headerless raw little-endian PCM\");\n\ttraits.encoderSettingsName = U_(\"RAW\");\n\ttraits.canTags = false;\n\ttraits.canCues = false;\n\ttraits.maxChannels = 4;\n\ttraits.samplerates = TrackerSettings::Instance().GetSampleRates();\n\ttraits.modes = Encoder::ModeLossless;\n\ttraits.formats.push_back({ Encoder::Format::Encoding::Float, 64, mpt::endian::little });\n\ttraits.formats.push_back({ Encoder::Format::Encoding::Float, 64, mpt::endian::big });\n\ttraits.formats.push_back({ Encoder::Format::Encoding::Float, 32, mpt::endian::little });\n\ttraits.formats.push_back({ Encoder::Format::Encoding::Float, 32, mpt::endian::big });\n\ttraits.formats.push_back({ Encoder::Format::Encoding::Integer, 32, mpt::endian::little });\n\ttraits.formats.push_back({ Encoder::Format::Encoding::Integer, 32, mpt::endian::big });\n\ttraits.formats.push_back({ Encoder::Format::Encoding::Integer, 24, mpt::endian::little });\n\ttraits.formats.push_back({ Encoder::Format::Encoding::Integer, 24, mpt::endian::big });\n\ttraits.formats.push_back({ Encoder::Format::Encoding::Integer, 16, mpt::endian::little });\n\ttraits.formats.push_back({ Encoder::Format::Encoding::Integer, 16, mpt::endian::big });\n\ttraits.formats.push_back({ Encoder::Format::Encoding::Integer, 8, mpt::endian::little });\n\ttraits.formats.push_back({ Encoder::Format::Encoding::Unsigned, 8, mpt::endian::little });\n\ttraits.formats.push_back({ Encoder::Format::Encoding::Alaw, 16, mpt::get_endian() });\n\ttraits.formats.push_back({ Encoder::Format::Encoding::ulaw, 16, mpt::get_endian() });\n\ttraits.defaultSamplerate = 48000;\n\ttraits.defaultChannels = 2;\n\ttraits.defaultMode = Encoder::ModeLossless;\n\ttraits.defaultFormat = { Encoder::Format::Encoding::Float, 32, mpt::endian::little };\n\tSetTraits(traits);\n}\n\n\nbool RAWEncoder::IsAvailable() const\n{\n\treturn true;\n}\n\n\nstd::unique_ptr<IAudioStreamEncoder> RAWEncoder::ConstructStreamEncoder(std::ostream &file, const Encoder::Settings &settings, const FileTags &tags) const\n{\n\tif(!IsAvailable())\n\t{\n\t\treturn nullptr;\n\t}\n\treturn std::make_unique<RawStreamWriter>(*this, file, settings, tags);\n}\n\n\nOPENMPT_NAMESPACE_END\n","avg_line_length":32.985915493,"max_line_length":154,"alphanum_fraction":0.7429547395,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3895,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n *  Copyright (c) 2016, The OpenThread Authors.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions are met:\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and\/or other materials provided with the distribution.\n *  3. Neither the name of the copyright holder nor the\n *     names of its contributors may be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n *   This file implements the OpenThread Network Data API.\n *\/\n\n#include \"openthread-core-config.h\"\n\n#include <openthread\/netdata.h>\n\n#include \"common\/instance.hpp\"\n#include \"common\/locator-getters.hpp\"\n\nusing namespace ot;\n\notError otNetDataGet(otInstance *aInstance, bool aStable, uint8_t *aData, uint8_t *aDataLength)\n{\n    Instance &instance = *static_cast<Instance *>(aInstance);\n\n    OT_ASSERT(aData != NULL && aDataLength != NULL);\n\n    return instance.Get<NetworkData::Leader>().GetNetworkData(aStable, aData, *aDataLength);\n}\n\notError otNetDataGetNextOnMeshPrefix(otInstance *           aInstance,\n                                     otNetworkDataIterator *aIterator,\n                                     otBorderRouterConfig * aConfig)\n{\n    otError   error    = OT_ERROR_NONE;\n    Instance &instance = *static_cast<Instance *>(aInstance);\n\n    VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS);\n\n    error = instance.Get<NetworkData::Leader>().GetNextOnMeshPrefix(*aIterator, *aConfig);\n\nexit:\n    return error;\n}\n\notError otNetDataGetNextRoute(otInstance *aInstance, otNetworkDataIterator *aIterator, otExternalRouteConfig *aConfig)\n{\n    otError   error    = OT_ERROR_NONE;\n    Instance &instance = *static_cast<Instance *>(aInstance);\n\n    VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS);\n\n    error = instance.Get<NetworkData::Leader>().GetNextExternalRoute(*aIterator, *aConfig);\n\nexit:\n    return error;\n}\n\notError otNetDataGetNextService(otInstance *aInstance, otNetworkDataIterator *aIterator, otServiceConfig *aConfig)\n{\n    otError   error    = OT_ERROR_NONE;\n    Instance &instance = *static_cast<Instance *>(aInstance);\n\n    VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS);\n\n    error = instance.Get<NetworkData::Leader>().GetNextService(*aIterator, *aConfig);\n\nexit:\n    return error;\n}\n\nuint8_t otNetDataGetVersion(otInstance *aInstance)\n{\n    Instance &instance = *static_cast<Instance *>(aInstance);\n\n    return instance.Get<Mle::MleRouter>().GetLeaderDataTlv().GetDataVersion();\n}\n\nuint8_t otNetDataGetStableVersion(otInstance *aInstance)\n{\n    Instance &instance = *static_cast<Instance *>(aInstance);\n\n    return instance.Get<Mle::MleRouter>().GetLeaderDataTlv().GetStableDataVersion();\n}\n","avg_line_length":36.7452830189,"max_line_length":118,"alphanum_fraction":0.7340179718,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":98259,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n * By downloading, copying, installing or using the software you agree to this license.\n * If you do not agree to this license, do not download, install,\n * copy or use the software.\n *\n *\n *                           License Agreement\n *                For Open Source Computer Vision Library\n *                        (3-clause BSD License)\n *\n * Copyright (C) 2015, NVIDIA Corporation, all rights reserved.\n * Third party copyrights are property of their respective owners.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *   * Redistributions of source code must retain the above copyright notice,\n *     this list of conditions and the following disclaimer.\n *\n *   * Redistributions in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and\/or other materials provided with the distribution.\n *\n *   * Neither the names of the copyright holders nor the names of the contributors\n *     may be used to endorse or promote products derived from this software\n *     without specific prior written permission.\n *\n * This software is provided by the copyright holders and contributors \"as is\" and\n * any express or implied warranties, including, but not limited to, the implied\n * warranties of merchantability and fitness for a particular purpose are disclaimed.\n * In no event shall copyright holders or contributors be liable for any direct,\n * indirect, incidental, special, exemplary, or consequential damages\n * (including, but not limited to, procurement of substitute goods or services;\n * loss of use, data, or profits; or business interruption) however caused\n * and on any theory of liability, whether in contract, strict liability,\n * or tort (including negligence or otherwise) arising in any way out of\n * the use of this software, even if advised of the possibility of such damage.\n *\/\n\n#include \"common.hpp\"\n#include \"vtransform.hpp\"\n\n#include <cmath>\n#include <vector>\n#include <algorithm>\n\nnamespace CAROTENE_NS {\n\nbool isResizeNearestNeighborSupported(const Size2D &ssize, u32 elemSize)\n{\n#if SIZE_MAX <= UINT32_MAX\n    (void)ssize;\n#endif\n    bool supportedElemSize = (elemSize == 1) || (elemSize == 3) || (elemSize == 4);\n    return isSupportedConfiguration()\n#if SIZE_MAX > UINT32_MAX\n           && !(ssize.width > 0xffffFFFF || ssize.height > 0xffffFFFF)\/\/ Restrict image size since internally used resizeGeneric performs\n                                                                      \/\/ index evaluation with u32\n#endif\n           && supportedElemSize;\n}\n\nbool isResizeAreaSupported(f32 wr, f32 hr, u32 channels)\n{\n    bool supportedRatio = false;\n\n    if (channels == 1)\n        supportedRatio = (hr == wr) && ((wr == 2.0f) || (wr == 4.0f) || (wr == 0.5));\n    else if (channels == 3)\n        supportedRatio = (hr == wr) && ((wr == 2.0f) || (wr == 4.0f) || (wr == 0.5f));\n    else if (channels == 4)\n        supportedRatio = (hr == wr) && ((wr == 2.0f) || (wr == 4.0f) || (wr == 0.5f));\n\n    return isSupportedConfiguration() && supportedRatio;\n}\n\nbool isResizeLinearSupported(const Size2D &ssize, const Size2D &dsize,\n                             f32 wr, f32 hr, u32 channels)\n{\n    if ((wr <= 2.0f) && (hr <= 2.0f))\n    {\n        bool channelsSupport = (channels == 1) || (channels == 3) || (channels == 4);\n        return (ssize.width >= 16) && (dsize.height >= 8) &&\n                (dsize.width >= 8) && channelsSupport;\n    }\n\n    return false;\n}\n\nbool isResizeLinearOpenCVSupported(const Size2D &ssize, const Size2D &dsize, u32 channels)\n{\n    switch(channels)\n    {\n    case 1:\n        if (ssize.width >= 8\n#if SIZE_MAX > UINT32_MAX\n            && !(ssize.width > 0xffffFFFF || ssize.height > 0xffffFFFF)\/\/ Restrict image size since internal index evaluation\n                                                                       \/\/ is performed with u32\n#endif\n            && dsize.width >= 8 && dsize.height >= 8)\n            return isSupportedConfiguration();\n        return false;\n    case 4:\n        if (ssize.width >= 2\n#if SIZE_MAX > UINT32_MAX\n            && !(ssize.width > 0xffffFFFF || ssize.height > 0xffffFFFF)\/\/ Restrict image size since internal index evaluation\n                                                                       \/\/ is performed with u32\n#endif\n            && dsize.width >= 2 && dsize.height >= 8)\n            return isSupportedConfiguration();\n    default:\n        return false;\n    };\n}\n\n#ifdef CAROTENE_NEON\n\nnamespace {\n\nu32 * calcLUT(size_t size, f32 ratio,\n              std::vector<u32> & _ofs)\n{\n    _ofs.resize(size);\n    u32 * ofs = &_ofs[0];\n\n    size_t roiw8 = size >= 7 ? size - 7 : 0;\n    size_t roiw4 = size >= 3 ? size - 3 : 0;\n    size_t x = 0;\n\n    f32 indeces[4] = { 0, 1, 2, 3 };\n    float32x4_t v_index = vld1q_f32(indeces), v_inc = vdupq_n_f32(4);\n    float32x4_t v_05 = vdupq_n_f32(0.5f), v_ratio = vdupq_n_f32(ratio);\n\n    for ( ; x < roiw8; x += 8)\n    {\n        float32x4_t v_dstf = vmulq_f32(vaddq_f32(v_index, v_05), v_ratio);\n        vst1q_u32(ofs + x, vcvtq_u32_f32(v_dstf));\n        v_index = vaddq_f32(v_index, v_inc);\n\n        v_dstf = vmulq_f32(vaddq_f32(v_index, v_05), v_ratio);\n        vst1q_u32(ofs + x + 4, vcvtq_u32_f32(v_dstf));\n        v_index = vaddq_f32(v_index, v_inc);\n    }\n\n    for ( ; x < roiw4; x += 4)\n    {\n        float32x4_t v_dstf = vmulq_f32(vaddq_f32(v_index, v_05), v_ratio);\n        vst1q_u32(ofs + x, vcvtq_u32_f32(v_dstf));\n        v_index = vaddq_f32(v_index, v_inc);\n    }\n\n    for ( ; x < size; ++x)\n    {\n        ofs[x] = static_cast<u32>(floorf((x + 0.5f) * ratio));\n    }\n\n    return ofs;\n}\n\ntemplate <typename T>\nvoid resizeGeneric(const Size2D &dsize,\n                   const void * srcBase, ptrdiff_t srcStride,\n                   void * dstBase, ptrdiff_t dstStride,\n                   f32 wr, f32 hr)\n{\n    std::vector<u32> _x_ofs;\n    u32 * x_ofs = calcLUT(dsize.width, wr, _x_ofs);\/\/32bit LUT is used so we could get issues on src image dimensions greater than (2^32-1)\n\n    for (size_t dst_y = 0; dst_y < dsize.height; ++dst_y)\n    {\n        size_t src_y = static_cast<size_t>(floorf((dst_y + 0.5f) * hr));\n        const T * src = internal::getRowPtr(static_cast<const T *>(srcBase), srcStride, src_y);\n        T * dst = internal::getRowPtr(static_cast<T *>(dstBase), dstStride, dst_y);\n\n        for (size_t dst_x = 0; dst_x < dsize.width; ++dst_x)\n        {\n            internal::prefetch(src + dst_x);\n            dst[dst_x] = src[x_ofs[dst_x]];\n        }\n    }\n}\n\ntypedef struct _24bit_\n{\n    u8 a[3];\n} _24bit;\n\n} \/\/ namespace\n\n\n#endif\n\nvoid resizeNearestNeighbor(const Size2D &ssize, const Size2D &dsize,\n                           const void * srcBase, ptrdiff_t srcStride,\n                           void * dstBase, ptrdiff_t dstStride,\n                           f32 wr, f32 hr, u32 elemSize)\n{\n    internal::assertSupportedConfiguration(wr > 0 && hr > 0 &&\n                                           (dsize.width - 0.5) * wr < ssize.width &&\n                                           (dsize.height - 0.5) * hr < ssize.height &&  \/\/ Ensure we have enough source data\n                                           (dsize.width + 0.5) * wr >= ssize.width &&\n                                           (dsize.height + 0.5) * hr >= ssize.height && \/\/ Ensure source isn't too big\n                                           isResizeNearestNeighborSupported(ssize, elemSize));\n#ifdef CAROTENE_NEON\n\n    if (elemSize == 1)\n    {\n        resizeGeneric<u8>(dsize,\n                          srcBase, srcStride,\n                          dstBase, dstStride,\n                          wr, hr);\n    }\n    else if (elemSize == 3)\n    {\n        resizeGeneric<_24bit>(dsize,\n                              srcBase, srcStride,\n                              dstBase, dstStride,\n                              wr, hr);\n    }\n    else if (elemSize == 4)\n    {\n        resizeGeneric<u32>(dsize,\n                           srcBase, srcStride,\n                           dstBase, dstStride,\n                           wr, hr);\n    }\n\n#else\n    (void)dsize;\n    (void)srcBase;\n    (void)srcStride;\n    (void)dstBase;\n    (void)dstStride;\n    (void)wr;\n    (void)hr;\n#endif\n}\n\n#ifdef CAROTENE_NEON\ntemplate <bool opencv_like, int shiftsize>\ninline uint8x8_t areaDownsamplingDivision(uint16x8_t data)\n{\n    return vshrn_n_u16(data, shiftsize);\n}\ntemplate <>\ninline uint8x8_t areaDownsamplingDivision<true,2>(uint16x8_t data)\n{\n    \/\/ rounding\n    return vrshrn_n_u16(data,2);\n}\ntemplate <>\ninline uint8x8_t areaDownsamplingDivision<true,4>(uint16x8_t data)\n{\n    \/\/ bankers rounding\n    return vrshrn_n_u16(vqsubq_u16(data, vshrq_n_u16(vbicq_u16(vdupq_n_u16(1<<4), data), 4)),4);\n}\n\ntemplate <bool opencv_like, int shiftsize>\ninline u8 areaDownsamplingDivision(u16 data)\n{\n    return data >> shiftsize;\n}\ntemplate <>\ninline u8 areaDownsamplingDivision<true,2>(u16 data)\n{\n    \/\/ rounding\n    return (data + 2) >> 2;\n}\ntemplate <>\ninline u8 areaDownsamplingDivision<true,4>(u16 data)\n{\n    \/\/ bankers rounding\n    return (data - (((1<<4) & ~data) >> 4) + 8) >> 4;\n}\n#endif\n\ntemplate <bool opencv_like>\ninline void resizeAreaRounding(const Size2D &ssize, const Size2D &dsize,\n                               const u8 * srcBase, ptrdiff_t srcStride,\n                               u8 * dstBase, ptrdiff_t dstStride,\n                               f32 wr, f32 hr, u32 channels)\n{\n    internal::assertSupportedConfiguration(isResizeAreaSupported(wr, hr, channels) &&\n                                           std::abs(dsize.width  * wr -  ssize.width) < 0.1 &&\n                                           std::abs(dsize.height * hr - ssize.height) < 0.1);\n#ifdef CAROTENE_NEON\n    if (channels == 1)\n    {\n        if ((wr == 2.0f) && (hr == 2.0f))\n        {\n            size_t roiw8 = dsize.width >= 7 ? dsize.width - 7 : 0;\n\n            for (size_t i = 0; i < dsize.height; ++i)\n            {\n                const u8 * src0_row = internal::getRowPtr(srcBase, srcStride, i << 1);\n                const u8 * src1_row = internal::getRowPtr(srcBase, srcStride, (i << 1) + 1);\n                u8 * dst_row = internal::getRowPtr(dstBase, dstStride, i);\n                size_t sj = 0, dj = 0;\n\n                for ( ; dj < roiw8; dj += 8, sj += 16)\n                {\n                    internal::prefetch(src0_row + sj);\n                    internal::prefetch(src1_row + sj);\n\n                    uint16x8_t vSum1 = vpaddlq_u8(vld1q_u8(src0_row + sj));\n                    uint16x8_t vSum2 = vpaddlq_u8(vld1q_u8(src1_row + sj));\n                    uint8x8_t vRes1 = areaDownsamplingDivision<opencv_like,2>(vaddq_u16(vSum1, vSum2));\n\n                    vst1_u8(dst_row + dj, vRes1);\n                }\n\n                for ( ; dj < dsize.width; ++dj, sj += 2)\n                {\n                    dst_row[dj] = areaDownsamplingDivision<opencv_like,2>(\n                                      (u16)src0_row[sj] + src0_row[sj + 1] +\n                                      src1_row[sj] + src1_row[sj + 1]);\n                }\n            }\n        }\n        else if ((wr == 0.5f) && (hr == 0.5f))\n        {\n            size_t roiw32 = dsize.width >= 31 ? dsize.width - 31 : 0;\n            size_t roiw16 = dsize.width >= 15 ? dsize.width - 15 : 0;\n\n            for (size_t i = 0; i < dsize.height; i += 2)\n            {\n                const u8 * src_row = internal::getRowPtr(srcBase, srcStride, i >> 1);\n                u8 * dst0_row = internal::getRowPtr(dstBase, dstStride, i);\n                u8 * dst1_row = internal::getRowPtr(dstBase, dstStride, std::min(i + 1, dsize.height - 1));\n                size_t sj = 0, dj = 0;\n\n                for ( ; dj < roiw32; dj += 32, sj += 16)\n                {\n                    internal::prefetch(src_row + sj);\n\n                    uint8x16x2_t v_dst;\n                    v_dst.val[0] = v_dst.val[1] = vld1q_u8(src_row + sj);\n\n                    vst2q_u8(dst0_row + dj, v_dst);\n                    vst2q_u8(dst1_row + dj, v_dst);\n                }\n\n                for ( ; dj < roiw16; dj += 16, sj += 8)\n                {\n                    uint8x8x2_t v_dst;\n                    v_dst.val[0] = v_dst.val[1] = vld1_u8(src_row + sj);\n\n                    vst2_u8(dst0_row + dj, v_dst);\n                    vst2_u8(dst1_row + dj, v_dst);\n                }\n\n                for ( ; dj < dsize.width; dj += 2, ++sj)\n                {\n                    u8 src_val = src_row[sj];\n                    dst0_row[dj] = dst0_row[dj + 1] = src_val;\n                    dst1_row[dj] = dst1_row[dj + 1] = src_val;\n                }\n            }\n        }\n        else \/\/if ((wr == 4.0f) && (hr == 4.0f)) \/\/the only scale that lasts after isSupported check\n        {\n#ifndef ANDROID\n            size_t roiw16 = dsize.width >= 15 ? dsize.width - 15 : 0;\n#endif\n            size_t roiw8 = dsize.width >= 7 ? dsize.width - 7 : 0;\n\n            for (size_t i = 0; i < dsize.height; ++i)\n            {\n                const u8 * src0_row = internal::getRowPtr(srcBase, srcStride, i << 2);\n                const u8 * src1_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 1);\n                const u8 * src2_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 2);\n                const u8 * src3_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 3);\n                u8 * dst_row = internal::getRowPtr(dstBase, dstStride, i);\n                size_t sj = 0, dj = 0;\n\n#ifndef ANDROID\n                for ( ; dj < roiw16; dj += 16, sj += 64)\n                {\n                    internal::prefetch(src0_row + sj);\n                    internal::prefetch(src1_row + sj);\n                    internal::prefetch(src2_row + sj);\n                    internal::prefetch(src3_row + sj);\n\n                    uint8x16x4_t vLane1 = vld4q_u8(src0_row + sj);\n                    uint8x16x4_t vLane2 = vld4q_u8(src1_row + sj);\n                    uint8x16x4_t vLane3 = vld4q_u8(src2_row + sj);\n                    uint8x16x4_t vLane4 = vld4q_u8(src3_row + sj);\n\n                    uint16x8_t vSum_0 = vaddl_u8(vget_low_u8(vLane1.val[0]), vget_low_u8(vLane1.val[1]));\n                    vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane1.val[2]), vget_low_u8(vLane1.val[3])));\n                    vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane2.val[0]), vget_low_u8(vLane2.val[1])));\n                    vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane2.val[2]), vget_low_u8(vLane2.val[3])));\n                    vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane3.val[0]), vget_low_u8(vLane3.val[1])));\n                    vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane3.val[2]), vget_low_u8(vLane3.val[3])));\n                    vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane4.val[0]), vget_low_u8(vLane4.val[1])));\n                    vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane4.val[2]), vget_low_u8(vLane4.val[3])));\n\n                    uint16x8_t vSum_1 = vaddl_u8(vget_high_u8(vLane1.val[0]), vget_high_u8(vLane1.val[1]));\n                    vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane1.val[2]), vget_high_u8(vLane1.val[3])));\n                    vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane2.val[0]), vget_high_u8(vLane2.val[1])));\n                    vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane2.val[2]), vget_high_u8(vLane2.val[3])));\n                    vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane3.val[0]), vget_high_u8(vLane3.val[1])));\n                    vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane3.val[2]), vget_high_u8(vLane3.val[3])));\n                    vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane4.val[0]), vget_high_u8(vLane4.val[1])));\n                    vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane4.val[2]), vget_high_u8(vLane4.val[3])));\n\n                    uint8x8_t vRes_0 = areaDownsamplingDivision<opencv_like,4>(vSum_0);\n                    uint8x8_t vRes_1 = areaDownsamplingDivision<opencv_like,4>(vSum_1);\n\n                    vst1q_u8(dst_row + dj, vcombine_u8(vRes_0, vRes_1));\n                }\n#endif\n\n                for ( ; dj < roiw8; dj += 8, sj += 32)\n                {\n                    internal::prefetch(src0_row + sj);\n                    internal::prefetch(src1_row + sj);\n                    internal::prefetch(src2_row + sj);\n                    internal::prefetch(src3_row + sj);\n\n                    uint8x8x4_t vLane1 = vld4_u8(src0_row + sj);\n                    uint8x8x4_t vLane2 = vld4_u8(src1_row + sj);\n                    uint8x8x4_t vLane3 = vld4_u8(src2_row + sj);\n                    uint8x8x4_t vLane4 = vld4_u8(src3_row + sj);\n\n                    uint16x8_t vSum = vaddl_u8(vLane1.val[0], vLane1.val[1]);\n                    vSum = vaddq_u16(vSum, vaddl_u8(vLane1.val[2], vLane1.val[3]));\n                    vSum = vaddq_u16(vSum, vaddl_u8(vLane2.val[0], vLane2.val[1]));\n                    vSum = vaddq_u16(vSum, vaddl_u8(vLane2.val[2], vLane2.val[3]));\n                    vSum = vaddq_u16(vSum, vaddl_u8(vLane3.val[0], vLane3.val[1]));\n                    vSum = vaddq_u16(vSum, vaddl_u8(vLane3.val[2], vLane3.val[3]));\n                    vSum = vaddq_u16(vSum, vaddl_u8(vLane4.val[0], vLane4.val[1]));\n                    vSum = vaddq_u16(vSum, vaddl_u8(vLane4.val[2], vLane4.val[3]));\n\n                    vst1_u8(dst_row + dj, areaDownsamplingDivision<opencv_like,4>(vSum));\n                }\n\n                for ( ; dj < dsize.width; ++dj, sj += 4)\n                {\n                    dst_row[dj] = areaDownsamplingDivision<opencv_like,4>(\n                                      (u16)src0_row[sj] + src0_row[sj + 1] + src0_row[sj + 2] + src0_row[sj + 3] +\n                                      src1_row[sj] + src1_row[sj + 1] + src1_row[sj + 2] + src1_row[sj + 3] +\n                                      src2_row[sj] + src2_row[sj + 1] + src2_row[sj + 2] + src2_row[sj + 3] +\n                                      src3_row[sj] + src3_row[sj + 1] + src3_row[sj + 2] + src3_row[sj + 3]);\n                }\n            }\n        }\n    }\n    else if (channels == 4)\n    {\n        if ((wr == 2.0f) && (hr == 2.0f))\n        {\n#ifndef ANDROID\n            size_t roiw4 = dsize.width >= 3 ? (dsize.width - 3) << 2 : 0;\n#endif\n            size_t roiw2 = dsize.width >= 1 ? (dsize.width - 1) << 2 : 0;\n\n            for (size_t i = 0; i < dsize.height; ++i)\n            {\n                const u8 * src0_row = internal::getRowPtr(srcBase, srcStride, i << 1);\n                const u8 * src1_row = internal::getRowPtr(srcBase, srcStride, (i << 1) + 1);\n                u8 * dst_row = internal::getRowPtr(dstBase, dstStride, i);\n                size_t sj = 0, dj = 0;\n\n#ifndef ANDROID\n                for ( ; dj < roiw4; dj += 16, sj += 32)\n                {\n                    internal::prefetch(src0_row + sj);\n                    internal::prefetch(src1_row + sj);\n\n                    uint8x8_t vRes_0, vRes_1;\n\n                    {\n                        uint8x16_t vLane1 = vld1q_u8(src0_row + sj);\n                        uint8x16_t vLane2 = vld1q_u8(src1_row + sj);\n\n                        uint16x8_t vLane_l = vaddl_u8(vget_low_u8(vLane1), vget_low_u8(vLane2));\n                        uint16x8_t vLane_h = vaddl_u8(vget_high_u8(vLane1), vget_high_u8(vLane2));\n\n                        uint16x4_t vSum_l = vadd_u16(vget_low_u16(vLane_l), vget_high_u16(vLane_l));\n                        uint16x4_t vSum_h = vadd_u16(vget_low_u16(vLane_h), vget_high_u16(vLane_h));\n\n                        vRes_0 = areaDownsamplingDivision<opencv_like,2>(vcombine_u16(vSum_l, vSum_h));\n                    }\n\n                    {\n                        uint8x16_t vLane1 = vld1q_u8(src0_row + sj + 16);\n                        uint8x16_t vLane2 = vld1q_u8(src1_row + sj + 16);\n\n                        uint16x8_t vLane_l = vaddl_u8(vget_low_u8(vLane1), vget_low_u8(vLane2));\n                        uint16x8_t vLane_h = vaddl_u8(vget_high_u8(vLane1), vget_high_u8(vLane2));\n\n                        uint16x4_t vSum_l = vadd_u16(vget_low_u16(vLane_l), vget_high_u16(vLane_l));\n                        uint16x4_t vSum_h = vadd_u16(vget_low_u16(vLane_h), vget_high_u16(vLane_h));\n\n                        vRes_1 = areaDownsamplingDivision<opencv_like,2>(vcombine_u16(vSum_l, vSum_h));\n                    }\n\n                    vst1q_u8(dst_row + dj, vcombine_u8(vRes_0, vRes_1));\n                }\n#endif\n\n                for ( ; dj < roiw2; dj += 8, sj += 16)\n                {\n                    internal::prefetch(src0_row + sj);\n                    internal::prefetch(src1_row + sj);\n\n                    uint8x16_t vLane1 = vld1q_u8(src0_row + sj);\n                    uint8x16_t vLane2 = vld1q_u8(src1_row + sj);\n\n                    uint16x8_t vLane_l = vaddl_u8(vget_low_u8(vLane1), vget_low_u8(vLane2));\n                    uint16x8_t vLane_h = vaddl_u8(vget_high_u8(vLane1), vget_high_u8(vLane2));\n\n                    uint16x4_t vSum_l = vadd_u16(vget_low_u16(vLane_l), vget_high_u16(vLane_l));\n                    uint16x4_t vSum_h = vadd_u16(vget_low_u16(vLane_h), vget_high_u16(vLane_h));\n\n                    uint8x8_t vRes = areaDownsamplingDivision<opencv_like,2>(vcombine_u16(vSum_l, vSum_h));\n                    vst1_u8(dst_row + dj, vRes);\n                }\n\n                for (size_t dwidth = dsize.width << 2; dj < dwidth; dj += 4, sj += 8)\n                {\n                    dst_row[dj    ] = areaDownsamplingDivision<opencv_like,2>(\n                                          (u16)src0_row[sj    ] + src0_row[sj + 4] +\n                                               src1_row[sj    ] + src1_row[sj + 4]);\n                    dst_row[dj + 1] = areaDownsamplingDivision<opencv_like,2>(\n                                          (u16)src0_row[sj + 1] + src0_row[sj + 5] +\n                                               src1_row[sj + 1] + src1_row[sj + 5]);\n                    dst_row[dj + 2] = areaDownsamplingDivision<opencv_like,2>(\n                                          (u16)src0_row[sj + 2] + src0_row[sj + 6] +\n                                               src1_row[sj + 2] + src1_row[sj + 6]);\n                    dst_row[dj + 3] = areaDownsamplingDivision<opencv_like,2>(\n                                          (u16)src0_row[sj + 3] + src0_row[sj + 7] +\n                                               src1_row[sj + 3] + src1_row[sj + 7]);\n                }\n            }\n        }\n        else if ((wr == 0.5f) && (hr == 0.5f))\n        {\n#ifndef ANDROID\n            size_t roiw32 = dsize.width >= 31 ? (dsize.width - 31) << 2 : 0;\n#endif\n            size_t roiw16 = dsize.width >= 15 ? (dsize.width - 15) << 2 : 0;\n\n            for (size_t i = 0; i < dsize.height; i += 2)\n            {\n                const u8 * src_row = internal::getRowPtr(srcBase, srcStride, i >> 1);\n                u8 * dst0_row = internal::getRowPtr(dstBase, dstStride, i);\n                u8 * dst1_row = internal::getRowPtr(dstBase, dstStride, std::min(i + 1, dsize.height - 1));\n                size_t sj = 0, dj = 0;\n\n#ifndef ANDROID\n                for ( ; dj < roiw32; dj += 128, sj += 64)\n                {\n                    internal::prefetch(src_row + sj);\n\n                    uint8x16x4_t v_src = vld4q_u8(src_row + sj);\n                    uint8x16x2_t v_c0 = vzipq_u8(v_src.val[0], v_src.val[0]);\n                    uint8x16x2_t v_c1 = vzipq_u8(v_src.val[1], v_src.val[1]);\n                    uint8x16x2_t v_c2 = vzipq_u8(v_src.val[2], v_src.val[2]);\n                    uint8x16x2_t v_c3 = vzipq_u8(v_src.val[3], v_src.val[3]);\n\n                    uint8x16x4_t v_dst;\n                    v_dst.val[0] = v_c0.val[0];\n                    v_dst.val[1] = v_c1.val[0];\n                    v_dst.val[2] = v_c2.val[0];\n                    v_dst.val[3] = v_c3.val[0];\n                    vst4q_u8(dst0_row + dj, v_dst);\n                    vst4q_u8(dst1_row + dj, v_dst);\n\n                    v_dst.val[0] = v_c0.val[1];\n                    v_dst.val[1] = v_c1.val[1];\n                    v_dst.val[2] = v_c2.val[1];\n                    v_dst.val[3] = v_c3.val[1];\n                    vst4q_u8(dst0_row + dj + 64, v_dst);\n                    vst4q_u8(dst1_row + dj + 64, v_dst);\n                }\n#endif\n\n                for ( ; dj < roiw16; dj += 64, sj += 32)\n                {\n                    internal::prefetch(src_row + sj);\n\n                    uint8x8x4_t v_src = vld4_u8(src_row + sj);\n                    uint8x8x2_t v_c0 = vzip_u8(v_src.val[0], v_src.val[0]);\n                    uint8x8x2_t v_c1 = vzip_u8(v_src.val[1], v_src.val[1]);\n                    uint8x8x2_t v_c2 = vzip_u8(v_src.val[2], v_src.val[2]);\n                    uint8x8x2_t v_c3 = vzip_u8(v_src.val[3], v_src.val[3]);\n\n                    uint8x16x4_t v_dst;\n                    v_dst.val[0] = vcombine_u8(v_c0.val[0], v_c0.val[1]);\n                    v_dst.val[1] = vcombine_u8(v_c1.val[0], v_c1.val[1]);\n                    v_dst.val[2] = vcombine_u8(v_c2.val[0], v_c2.val[1]);\n                    v_dst.val[3] = vcombine_u8(v_c3.val[0], v_c3.val[1]);\n                    vst4q_u8(dst0_row + dj, v_dst);\n                    vst4q_u8(dst1_row + dj, v_dst);\n                }\n\n                for (size_t dwidth = dsize.width << 2; dj < dwidth; dj += 8, sj += 4)\n                {\n                    u8 src_val = src_row[sj];\n                    dst0_row[dj] = dst0_row[dj + 4] = src_val;\n                    dst1_row[dj] = dst1_row[dj + 4] = src_val;\n\n                    src_val = src_row[sj + 1];\n                    dst0_row[dj + 1] = dst0_row[dj + 5] = src_val;\n                    dst1_row[dj + 1] = dst1_row[dj + 5] = src_val;\n\n                    src_val = src_row[sj + 2];\n                    dst0_row[dj + 2] = dst0_row[dj + 6] = src_val;\n                    dst1_row[dj + 2] = dst1_row[dj + 6] = src_val;\n\n                    src_val = src_row[sj + 3];\n                    dst0_row[dj + 3] = dst0_row[dj + 7] = src_val;\n                    dst1_row[dj + 3] = dst1_row[dj + 7] = src_val;\n                }\n            }\n        }\n        else \/\/if ((hr == 4.0f) && (wr == 4.0f)) \/\/the only scale that lasts after isSupported check\n        {\n            size_t roiw4 = dsize.width >= 3 ? (dsize.width - 3) << 2 : 0;\n            size_t roiw2 = dsize.width >= 1 ? (dsize.width - 1) << 2 : 0;\n\n            for (size_t i = 0; i < dsize.height; ++i)\n            {\n                const u8 * src0_row = internal::getRowPtr(srcBase, srcStride, i << 2);\n                const u8 * src1_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 1);\n                const u8 * src2_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 2);\n                const u8 * src3_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 3);\n                u8 * dst_row = internal::getRowPtr(dstBase, dstStride, i);\n                size_t sj = 0, dj = 0;\n\n                for ( ; dj < roiw4; dj += 16, sj += 64)\n                {\n                    internal::prefetch(src0_row + sj);\n                    internal::prefetch(src1_row + sj);\n                    internal::prefetch(src2_row + sj);\n                    internal::prefetch(src3_row + sj);\n\n                    uint8x16_t vLane10 = vld1q_u8(src0_row + sj), vLane11 = vld1q_u8(src0_row + sj + 16);\n                    uint8x16_t vLane20 = vld1q_u8(src1_row + sj), vLane21 = vld1q_u8(src1_row + sj + 16);\n                    uint8x16_t vLane30 = vld1q_u8(src2_row + sj), vLane31 = vld1q_u8(src2_row + sj + 16);\n                    uint8x16_t vLane40 = vld1q_u8(src3_row + sj), vLane41 = vld1q_u8(src3_row + sj + 16);\n\n                    uint16x8_t v_part_0, v_part_1;\n                    {\n                        uint16x8_t v_sum0 = vaddl_u8(vget_low_u8(vLane10), vget_high_u8(vLane10));\n                        v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane20), vget_high_u8(vLane20)));\n                        v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane30), vget_high_u8(vLane30)));\n                        v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane40), vget_high_u8(vLane40)));\n\n                        uint16x8_t v_sum1 = vaddl_u8(vget_low_u8(vLane11), vget_high_u8(vLane11));\n                        v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane21), vget_high_u8(vLane21)));\n                        v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane31), vget_high_u8(vLane31)));\n                        v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane41), vget_high_u8(vLane41)));\n\n                        v_part_0 = vcombine_u16(vadd_u16(vget_low_u16(v_sum0), vget_high_u16(v_sum0)),\n                                                vadd_u16(vget_low_u16(v_sum1), vget_high_u16(v_sum1)));\n                    }\n\n                    vLane10 = vld1q_u8(src0_row + sj + 32);\n                    vLane11 = vld1q_u8(src0_row + sj + 48);\n                    vLane20 = vld1q_u8(src1_row + sj + 32);\n                    vLane21 = vld1q_u8(src1_row + sj + 48);\n                    vLane30 = vld1q_u8(src2_row + sj + 32);\n                    vLane31 = vld1q_u8(src2_row + sj + 48);\n                    vLane40 = vld1q_u8(src3_row + sj + 32);\n                    vLane41 = vld1q_u8(src3_row + sj + 48);\n\n                    {\n                        uint16x8_t v_sum0 = vaddl_u8(vget_low_u8(vLane10), vget_high_u8(vLane10));\n                        v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane20), vget_high_u8(vLane20)));\n                        v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane30), vget_high_u8(vLane30)));\n                        v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane40), vget_high_u8(vLane40)));\n\n                        uint16x8_t v_sum1 = vaddl_u8(vget_low_u8(vLane11), vget_high_u8(vLane11));\n                        v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane21), vget_high_u8(vLane21)));\n                        v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane31), vget_high_u8(vLane31)));\n                        v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane41), vget_high_u8(vLane41)));\n\n                        v_part_1 = vcombine_u16(vadd_u16(vget_low_u16(v_sum0), vget_high_u16(v_sum0)),\n                                                vadd_u16(vget_low_u16(v_sum1), vget_high_u16(v_sum1)));\n                    }\n\n                    vst1q_u8(dst_row + dj, vcombine_u8(areaDownsamplingDivision<opencv_like,4>(v_part_0),\n                                                       areaDownsamplingDivision<opencv_like,4>(v_part_1)));\n                }\n\n                for ( ; dj < roiw2; dj += 8, sj += 32)\n                {\n                    uint8x16_t vLane10 = vld1q_u8(src0_row + sj), vLane11 = vld1q_u8(src0_row + sj + 16);\n                    uint8x16_t vLane20 = vld1q_u8(src1_row + sj), vLane21 = vld1q_u8(src1_row + sj + 16);\n                    uint8x16_t vLane30 = vld1q_u8(src2_row + sj), vLane31 = vld1q_u8(src2_row + sj + 16);\n                    uint8x16_t vLane40 = vld1q_u8(src3_row + sj), vLane41 = vld1q_u8(src3_row + sj + 16);\n\n                    uint16x8_t v_sum0 = vaddl_u8(vget_low_u8(vLane10), vget_high_u8(vLane10));\n                    v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane20), vget_high_u8(vLane20)));\n                    v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane30), vget_high_u8(vLane30)));\n                    v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane40), vget_high_u8(vLane40)));\n\n                    uint16x8_t v_sum1 = vaddl_u8(vget_low_u8(vLane11), vget_high_u8(vLane11));\n                    v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane21), vget_high_u8(vLane21)));\n                    v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane31), vget_high_u8(vLane31)));\n                    v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane41), vget_high_u8(vLane41)));\n\n                    uint16x8_t v_sum = vcombine_u16(vadd_u16(vget_low_u16(v_sum0), vget_high_u16(v_sum0)),\n                                                    vadd_u16(vget_low_u16(v_sum1), vget_high_u16(v_sum1)));\n\n                    vst1_u8(dst_row + dj, areaDownsamplingDivision<opencv_like,4>(v_sum));\n                }\n\n                for (size_t dwidth = dsize.width << 2; dj < dwidth; dj += 4, sj += 16)\n                {\n                    dst_row[dj    ] = areaDownsamplingDivision<opencv_like,4>(\n                                            (u16)src0_row[sj     ] + src0_row[sj +  4] +\n                                                 src0_row[sj +  8] + src0_row[sj + 12] +\n                                                 src1_row[sj     ] + src1_row[sj +  4] +\n                                                 src1_row[sj +  8] + src1_row[sj + 12] +\n                                                 src2_row[sj     ] + src2_row[sj +  4] +\n                                                 src2_row[sj +  8] + src2_row[sj + 12] +\n                                                 src3_row[sj     ] + src3_row[sj +  4] +\n                                                 src3_row[sj +  8] + src3_row[sj + 12]);\n\n                    dst_row[dj + 1] = areaDownsamplingDivision<opencv_like,4>(\n                                            (u16)src0_row[sj +  1] + src0_row[sj +  5] +\n                                                 src0_row[sj +  9] + src0_row[sj + 13] +\n                                                 src1_row[sj +  1] + src1_row[sj +  5] +\n                                                 src1_row[sj +  9] + src1_row[sj + 13] +\n                                                 src2_row[sj +  1] + src2_row[sj +  5] +\n                                                 src2_row[sj +  9] + src2_row[sj + 13] +\n                                                 src3_row[sj +  1] + src3_row[sj +  5] +\n                                                 src3_row[sj +  9] + src3_row[sj + 13]);\n\n                    dst_row[dj + 2] = areaDownsamplingDivision<opencv_like,4>(\n                                            (u16)src0_row[sj +  2] + src0_row[sj +  6] +\n                                                 src0_row[sj + 10] + src0_row[sj + 14] +\n                                                 src1_row[sj +  2] + src1_row[sj +  6] +\n                                                 src1_row[sj + 10] + src1_row[sj + 14] +\n                                                 src2_row[sj +  2] + src2_row[sj +  6] +\n                                                 src2_row[sj + 10] + src2_row[sj + 14] +\n                                                 src3_row[sj +  2] + src3_row[sj +  6] +\n                                                 src3_row[sj + 10] + src3_row[sj + 14]);\n\n                    dst_row[dj + 3] = areaDownsamplingDivision<opencv_like,4>(\n                                            (u16)src0_row[sj +  3] + src0_row[sj +  7] +\n                                                 src0_row[sj + 11] + src0_row[sj + 15] +\n                                                 src1_row[sj +  3] + src1_row[sj +  7] +\n                                                 src1_row[sj + 11] + src1_row[sj + 15] +\n                                                 src2_row[sj +  3] + src2_row[sj +  7] +\n                                                 src2_row[sj + 11] + src2_row[sj + 15] +\n                                                 src3_row[sj +  3] + src3_row[sj +  7] +\n                                                 src3_row[sj + 11] + src3_row[sj + 15]);\n                }\n            }\n        }\n    }\n    else if (channels == 3)\n    {\n        if ((wr == 2.0f) && (wr == 2.0f))\n        {\n#ifndef ANDROID\n            size_t roiw16 = dsize.width >= 15 ? (dsize.width - 15) * 3 : 0;\n#endif\n            size_t roiw8 = dsize.width >= 7 ? (dsize.width - 7) * 3 : 0;\n\n            for (size_t i = 0; i < dsize.height; ++i)\n            {\n                const u8 * src0_row = internal::getRowPtr(srcBase, srcStride, i << 1);\n                const u8 * src1_row = internal::getRowPtr(srcBase, srcStride, (i << 1) + 1);\n                u8 * dst_row = internal::getRowPtr(dstBase, dstStride, i);\n                size_t sj = 0, dj = 0;\n\n#ifndef ANDROID\n                for ( ; dj < roiw16; dj += 48, sj += 96)\n                {\n                    internal::prefetch(src0_row + sj);\n                    internal::prefetch(src1_row + sj);\n\n                    uint8x16x3_t vLane1 = vld3q_u8(src0_row + sj);\n                    uint8x16x3_t vLane2 = vld3q_u8(src1_row + sj);\n\n                    uint8x8x3_t v_dst0, v_dst1;\n                    {\n                        uint16x8_t v_el0 = vpaddlq_u8(vLane1.val[0]);\n                        uint16x8_t v_el1 = vpaddlq_u8(vLane1.val[1]);\n                        uint16x8_t v_el2 = vpaddlq_u8(vLane1.val[2]);\n                        v_el0 = vpadalq_u8(v_el0, vLane2.val[0]);\n                        v_el1 = vpadalq_u8(v_el1, vLane2.val[1]);\n                        v_el2 = vpadalq_u8(v_el2, vLane2.val[2]);\n\n                        v_dst0.val[0] = areaDownsamplingDivision<opencv_like,2>(v_el0);\n                        v_dst0.val[1] = areaDownsamplingDivision<opencv_like,2>(v_el1);\n                        v_dst0.val[2] = areaDownsamplingDivision<opencv_like,2>(v_el2);\n                    }\n\n                    vLane1 = vld3q_u8(src0_row + sj + 48);\n                    vLane2 = vld3q_u8(src1_row + sj + 48);\n                    {\n                        uint16x8_t v_el0 = vpaddlq_u8(vLane1.val[0]);\n                        uint16x8_t v_el1 = vpaddlq_u8(vLane1.val[1]);\n                        uint16x8_t v_el2 = vpaddlq_u8(vLane1.val[2]);\n                        v_el0 = vpadalq_u8(v_el0, vLane2.val[0]);\n                        v_el1 = vpadalq_u8(v_el1, vLane2.val[1]);\n                        v_el2 = vpadalq_u8(v_el2, vLane2.val[2]);\n\n                        v_dst1.val[0] = areaDownsamplingDivision<opencv_like,2>(v_el0);\n                        v_dst1.val[1] = areaDownsamplingDivision<opencv_like,2>(v_el1);\n                        v_dst1.val[2] = areaDownsamplingDivision<opencv_like,2>(v_el2);\n                    }\n\n                    uint8x16x3_t v_dst;\n                    v_dst.val[0] = vcombine_u8(v_dst0.val[0], v_dst1.val[0]);\n                    v_dst.val[1] = vcombine_u8(v_dst0.val[1], v_dst1.val[1]);\n                    v_dst.val[2] = vcombine_u8(v_dst0.val[2], v_dst1.val[2]);\n\n                    vst3q_u8(dst_row + dj, v_dst);\n                }\n#endif\n\n                for ( ; dj < roiw8; dj += 24, sj += 48)\n                {\n                    internal::prefetch(src0_row + sj);\n                    internal::prefetch(src1_row + sj);\n\n                    uint8x16x3_t vLane1 = vld3q_u8(src0_row + sj);\n                    uint8x16x3_t vLane2 = vld3q_u8(src1_row + sj);\n\n                    uint16x8_t v_el0 = vpaddlq_u8(vLane1.val[0]);\n                    uint16x8_t v_el1 = vpaddlq_u8(vLane1.val[1]);\n                    uint16x8_t v_el2 = vpaddlq_u8(vLane1.val[2]);\n                    v_el0 = vpadalq_u8(v_el0, vLane2.val[0]);\n                    v_el1 = vpadalq_u8(v_el1, vLane2.val[1]);\n                    v_el2 = vpadalq_u8(v_el2, vLane2.val[2]);\n\n                    uint8x8x3_t v_dst;\n                    v_dst.val[0] = areaDownsamplingDivision<opencv_like,2>(v_el0);\n                    v_dst.val[1] = areaDownsamplingDivision<opencv_like,2>(v_el1);\n                    v_dst.val[2] = areaDownsamplingDivision<opencv_like,2>(v_el2);\n\n                    vst3_u8(dst_row + dj, v_dst);\n                }\n\n                for (size_t dwidth = dsize.width * 3; dj < dwidth; dj += 3, sj += 6)\n                {\n                    dst_row[dj    ] = areaDownsamplingDivision<opencv_like,2>(\n                                          (u16)src0_row[sj    ] + src0_row[sj + 3] +\n                                               src1_row[sj    ] + src1_row[sj + 3]);\n                    dst_row[dj + 1] = areaDownsamplingDivision<opencv_like,2>(\n                                          (u16)src0_row[sj + 1] + src0_row[sj + 4] +\n                                               src1_row[sj + 1] + src1_row[sj + 4]);\n                    dst_row[dj + 2] = areaDownsamplingDivision<opencv_like,2>(\n                                          (u16)src0_row[sj + 2] + src0_row[sj + 5] +\n                                               src1_row[sj + 2] + src1_row[sj + 5]);\n                }\n            }\n        }\n        else if ((wr == 0.5f) && (hr == 0.5f))\n        {\n#ifndef ANDROID\n            size_t roiw32 = dsize.width >= 31 ? (dsize.width - 31) * 3 : 0;\n#endif\n            size_t roiw16 = dsize.width >= 15 ? (dsize.width - 15) * 3 : 0;\n\n            for (size_t i = 0; i < dsize.height; i += 2)\n            {\n                const u8 * src_row = internal::getRowPtr(srcBase, srcStride, i >> 1);\n                u8 * dst0_row = internal::getRowPtr(dstBase, dstStride, i);\n                u8 * dst1_row = internal::getRowPtr(dstBase, dstStride, std::min(i + 1, dsize.height - 1));\n                size_t sj = 0, dj = 0;\n\n#ifndef ANDROID\n                for ( ; dj < roiw32; dj += 96, sj += 48)\n                {\n                    internal::prefetch(src_row + sj);\n\n                    uint8x16x3_t v_src = vld3q_u8(src_row + sj);\n                    uint8x16x2_t v_c0 = vzipq_u8(v_src.val[0], v_src.val[0]);\n                    uint8x16x2_t v_c1 = vzipq_u8(v_src.val[1], v_src.val[1]);\n                    uint8x16x2_t v_c2 = vzipq_u8(v_src.val[2], v_src.val[2]);\n\n                    uint8x16x3_t v_dst;\n                    v_dst.val[0] = v_c0.val[0];\n                    v_dst.val[1] = v_c1.val[0];\n                    v_dst.val[2] = v_c2.val[0];\n                    vst3q_u8(dst0_row + dj, v_dst);\n                    vst3q_u8(dst1_row + dj, v_dst);\n\n                    v_dst.val[0] = v_c0.val[1];\n                    v_dst.val[1] = v_c1.val[1];\n                    v_dst.val[2] = v_c2.val[1];\n                    vst3q_u8(dst0_row + dj + 48, v_dst);\n                    vst3q_u8(dst1_row + dj + 48, v_dst);\n                }\n#endif\n\n                for ( ; dj < roiw16; dj += 48, sj += 24)\n                {\n                    internal::prefetch(src_row + sj);\n\n                    uint8x8x3_t v_src = vld3_u8(src_row + sj);\n                    uint8x8x2_t v_c0 = vzip_u8(v_src.val[0], v_src.val[0]);\n                    uint8x8x2_t v_c1 = vzip_u8(v_src.val[1], v_src.val[1]);\n                    uint8x8x2_t v_c2 = vzip_u8(v_src.val[2], v_src.val[2]);\n\n                    uint8x16x3_t v_dst;\n                    v_dst.val[0] = vcombine_u8(v_c0.val[0], v_c0.val[1]);\n                    v_dst.val[1] = vcombine_u8(v_c1.val[0], v_c1.val[1]);\n                    v_dst.val[2] = vcombine_u8(v_c2.val[0], v_c2.val[1]);\n                    vst3q_u8(dst0_row + dj, v_dst);\n                    vst3q_u8(dst1_row + dj, v_dst);\n                }\n\n                for (size_t dwidth = dsize.width * 3; dj < dwidth; dj += 6, sj += 3)\n                {\n                    u8 src_val = src_row[sj];\n                    dst0_row[dj] = dst0_row[dj + 3] = src_val;\n                    dst1_row[dj] = dst1_row[dj + 3] = src_val;\n\n                    src_val = src_row[sj + 1];\n                    dst0_row[dj + 1] = dst0_row[dj + 4] = src_val;\n                    dst1_row[dj + 1] = dst1_row[dj + 4] = src_val;\n\n                    src_val = src_row[sj + 2];\n                    dst0_row[dj + 2] = dst0_row[dj + 5] = src_val;\n                    dst1_row[dj + 2] = dst1_row[dj + 5] = src_val;\n                }\n            }\n        }\n        else \/\/if ((hr == 4.0f) && (wr == 4.0f)) \/\/the only scale that lasts after isSupported check\n        {\n#ifndef ANDROID\n            size_t roiw8 = dsize.width >= 7 ? (dsize.width - 7) * 3 : 0;\n#endif\n\n            for (size_t i = 0; i < dsize.height; ++i)\n            {\n                const u8 * src0_row = internal::getRowPtr(srcBase, srcStride, i << 2);\n                const u8 * src1_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 1);\n                const u8 * src2_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 2);\n                const u8 * src3_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 3);\n                u8 * dst_row = internal::getRowPtr(dstBase, dstStride, i);\n                size_t sj = 0, dj = 0;\n\n#ifndef ANDROID\n                for ( ; dj < roiw8; dj += 24, sj += 96)\n                {\n                    internal::prefetch(src0_row + sj);\n                    internal::prefetch(src1_row + sj);\n                    internal::prefetch(src2_row + sj);\n                    internal::prefetch(src3_row + sj);\n\n                    uint8x16x3_t vLane10 = vld3q_u8(src0_row + sj), vLane11 = vld3q_u8(src0_row + sj + 48);\n                    uint8x16x3_t vLane20 = vld3q_u8(src1_row + sj), vLane21 = vld3q_u8(src1_row + sj + 48);\n                    uint8x16x3_t vLane30 = vld3q_u8(src2_row + sj), vLane31 = vld3q_u8(src2_row + sj + 48);\n                    uint8x16x3_t vLane40 = vld3q_u8(src3_row + sj), vLane41 = vld3q_u8(src3_row + sj + 48);\n\n                    uint8x8x3_t v_dst;\n\n                    \/\/ channel 0\n                    {\n                        uint16x8_t v_lane0 = vpaddlq_u8(vLane10.val[0]);\n                        uint16x8_t v_lane1 = vpaddlq_u8(vLane20.val[0]);\n                        uint16x8_t v_lane2 = vpaddlq_u8(vLane30.val[0]);\n                        uint16x8_t v_lane3 = vpaddlq_u8(vLane40.val[0]);\n                        v_lane0 = vaddq_u16(v_lane0, v_lane1);\n                        v_lane0 = vaddq_u16(v_lane0, v_lane2);\n                        v_lane0 = vaddq_u16(v_lane0, v_lane3);\n\n                        uint16x8_t v_lane0_ = vpaddlq_u8(vLane11.val[0]);\n                        uint16x8_t v_lane1_ = vpaddlq_u8(vLane21.val[0]);\n                        uint16x8_t v_lane2_ = vpaddlq_u8(vLane31.val[0]);\n                        uint16x8_t v_lane3_ = vpaddlq_u8(vLane41.val[0]);\n                        v_lane0_ = vaddq_u16(v_lane0_, v_lane1_);\n                        v_lane0_ = vaddq_u16(v_lane0_, v_lane2_);\n                        v_lane0_ = vaddq_u16(v_lane0_, v_lane3_);\n\n                        v_dst.val[0] = areaDownsamplingDivision<opencv_like,4>(\n                                           vcombine_u16(vmovn_u32(vpaddlq_u16(v_lane0)),\n                                                        vmovn_u32(vpaddlq_u16(v_lane0_))));\n                    }\n\n                    \/\/ channel 1\n                    {\n                        uint16x8_t v_lane0 = vpaddlq_u8(vLane10.val[1]);\n                        uint16x8_t v_lane1 = vpaddlq_u8(vLane20.val[1]);\n                        uint16x8_t v_lane2 = vpaddlq_u8(vLane30.val[1]);\n                        uint16x8_t v_lane3 = vpaddlq_u8(vLane40.val[1]);\n                        v_lane0 = vaddq_u16(v_lane0, v_lane1);\n                        v_lane0 = vaddq_u16(v_lane0, v_lane2);\n                        v_lane0 = vaddq_u16(v_lane0, v_lane3);\n\n                        uint16x8_t v_lane0_ = vpaddlq_u8(vLane11.val[1]);\n                        uint16x8_t v_lane1_ = vpaddlq_u8(vLane21.val[1]);\n                        uint16x8_t v_lane2_ = vpaddlq_u8(vLane31.val[1]);\n                        uint16x8_t v_lane3_ = vpaddlq_u8(vLane41.val[1]);\n                        v_lane0_ = vaddq_u16(v_lane0_, v_lane1_);\n                        v_lane0_ = vaddq_u16(v_lane0_, v_lane2_);\n                        v_lane0_ = vaddq_u16(v_lane0_, v_lane3_);\n\n                        v_dst.val[1] = areaDownsamplingDivision<opencv_like,4>(\n                                           vcombine_u16(vmovn_u32(vpaddlq_u16(v_lane0)),\n                                                        vmovn_u32(vpaddlq_u16(v_lane0_))));\n                    }\n\n                    \/\/ channel 2\n                    {\n                        uint16x8_t v_lane0 = vpaddlq_u8(vLane10.val[2]);\n                        uint16x8_t v_lane1 = vpaddlq_u8(vLane20.val[2]);\n                        uint16x8_t v_lane2 = vpaddlq_u8(vLane30.val[2]);\n                        uint16x8_t v_lane3 = vpaddlq_u8(vLane40.val[2]);\n                        v_lane0 = vaddq_u16(v_lane0, v_lane1);\n                        v_lane0 = vaddq_u16(v_lane0, v_lane2);\n                        v_lane0 = vaddq_u16(v_lane0, v_lane3);\n\n                        uint16x8_t v_lane0_ = vpaddlq_u8(vLane11.val[2]);\n                        uint16x8_t v_lane1_ = vpaddlq_u8(vLane21.val[2]);\n                        uint16x8_t v_lane2_ = vpaddlq_u8(vLane31.val[2]);\n                        uint16x8_t v_lane3_ = vpaddlq_u8(vLane41.val[2]);\n                        v_lane0_ = vaddq_u16(v_lane0_, v_lane1_);\n                        v_lane0_ = vaddq_u16(v_lane0_, v_lane2_);\n                        v_lane0_ = vaddq_u16(v_lane0_, v_lane3_);\n\n                        v_dst.val[2] = areaDownsamplingDivision<opencv_like,4>(\n                                           vcombine_u16(vmovn_u32(vpaddlq_u16(v_lane0)),\n                                                        vmovn_u32(vpaddlq_u16(v_lane0_))));\n                    }\n\n                    vst3_u8(dst_row + dj, v_dst);\n                }\n#endif\n\n                for (size_t dwidth = dsize.width * 3; dj < dwidth; dj += 3, sj += 12)\n                {\n                    dst_row[dj    ] = areaDownsamplingDivision<opencv_like,4>(\n                                          (u16)src0_row[sj    ] + src0_row[sj +  3] +\n                                               src0_row[sj + 6] + src0_row[sj +  9] +\n                                               src1_row[sj    ] + src1_row[sj +  3] +\n                                               src1_row[sj + 6] + src1_row[sj +  9] +\n                                               src2_row[sj    ] + src2_row[sj +  3] +\n                                               src2_row[sj + 6] + src2_row[sj +  9] +\n                                               src3_row[sj    ] + src3_row[sj +  3] +\n                                               src3_row[sj + 6] + src3_row[sj +  9]);\n\n                    dst_row[dj + 1] = areaDownsamplingDivision<opencv_like,4>(\n                                          (u16)src0_row[sj + 1] + src0_row[sj +  4] +\n                                               src0_row[sj + 7] + src0_row[sj + 10] +\n                                               src1_row[sj + 1] + src1_row[sj +  4] +\n                                               src1_row[sj + 7] + src1_row[sj + 10] +\n                                               src2_row[sj + 1] + src2_row[sj +  4] +\n                                               src2_row[sj + 7] + src2_row[sj + 10] +\n                                               src3_row[sj + 1] + src3_row[sj +  4] +\n                                               src3_row[sj + 7] + src3_row[sj + 10]);\n\n                    dst_row[dj + 2] = areaDownsamplingDivision<opencv_like,4>(\n                                          (u16)src0_row[sj + 2] + src0_row[sj +  5] +\n                                               src0_row[sj + 8] + src0_row[sj + 11] +\n                                               src1_row[sj + 2] + src1_row[sj +  5] +\n                                               src1_row[sj + 8] + src1_row[sj + 11] +\n                                               src2_row[sj + 2] + src2_row[sj +  5] +\n                                               src2_row[sj + 8] + src2_row[sj + 11] +\n                                               src3_row[sj + 2] + src3_row[sj +  5] +\n                                               src3_row[sj + 8] + src3_row[sj + 11]);\n                }\n            }\n        }\n    }\n#else\n    (void)dsize;\n    (void)srcBase;\n    (void)srcStride;\n    (void)dstBase;\n    (void)dstStride;\n    (void)wr;\n    (void)hr;\n#endif\n    (void)ssize;\n}\n\nvoid resizeAreaOpenCV(const Size2D &ssize, const Size2D &dsize,\n                const u8 * srcBase, ptrdiff_t srcStride,\n                u8 * dstBase, ptrdiff_t dstStride,\n                f32 wr, f32 hr, u32 channels)\n{\n   resizeAreaRounding<true>(ssize, dsize, srcBase, srcStride, dstBase, dstStride, wr, hr, channels);\n}\n\nvoid resizeArea(const Size2D &ssize, const Size2D &dsize,\n                const u8 * srcBase, ptrdiff_t srcStride,\n                u8 * dstBase, ptrdiff_t dstStride,\n                f32 wr, f32 hr, u32 channels)\n{\n   resizeAreaRounding<false>(ssize, dsize, srcBase, srcStride, dstBase, dstStride, wr, hr, channels);\n}\n\n#ifdef CAROTENE_NEON\n\nnamespace {\n\nuint8x8_t resizeLinearStep(uint8x16_t vr1, uint8x16_t vr2,\n                           uint8x8_t vlutl, uint8x8_t vluth,\n                           float32x4_t vrw, float32x4_t vcw0, float32x4_t vcw1)\n{\n    uint8x8_t vr1l = internal::vqtbl1_u8(vr1, vlutl);\n    uint8x8_t vr1h = internal::vqtbl1_u8(vr1, vluth);\n    uint8x8_t vr2l = internal::vqtbl1_u8(vr2, vlutl);\n    uint8x8_t vr2h = internal::vqtbl1_u8(vr2, vluth);\n\n    uint16x8_t v1hw = vmovl_u8(vr1h);\n    uint16x8_t v2hw = vmovl_u8(vr2h);\n\n    int16x8_t v1df = vreinterpretq_s16_u16(vsubl_u8(vr1l, vr1h));\n    int16x8_t v2df = vreinterpretq_s16_u16(vsubl_u8(vr2l, vr2h));\n\n    float32x4_t v1L = vcvtq_f32_u32(vmovl_u16(vget_low_u16(v1hw)));\n    float32x4_t v1H = vcvtq_f32_u32(vmovl_u16(vget_high_u16(v1hw)));\n    float32x4_t v2L = vcvtq_f32_u32(vmovl_u16(vget_low_u16(v2hw)));\n    float32x4_t v2H = vcvtq_f32_u32(vmovl_u16(vget_high_u16(v2hw)));\n\n    v1L = vmlaq_f32(v1L, vcvtq_f32_s32(vmovl_s16(vget_low_s16(v1df))), vcw0);\n    v1H = vmlaq_f32(v1H, vcvtq_f32_s32(vmovl_s16(vget_high_s16(v1df))), vcw1);\n    v2L = vmlaq_f32(v2L, vcvtq_f32_s32(vmovl_s16(vget_low_s16(v2df))), vcw0);\n    v2H = vmlaq_f32(v2H, vcvtq_f32_s32(vmovl_s16(vget_high_s16(v2df))), vcw1);\n\n    float32x4_t vdiffL = vsubq_f32(v1L, v2L);\n    float32x4_t vdiffH = vsubq_f32(v1H, v2H);\n\n    float32x4_t vL = vmlaq_f32(v2L, vdiffL, vrw);\n    float32x4_t vH = vmlaq_f32(v2H, vdiffH, vrw);\n    uint16x4_t vL_ = vmovn_u32(vcvtq_u32_f32(vL));\n    uint16x4_t vH_ = vmovn_u32(vcvtq_u32_f32(vH));\n    return vmovn_u16(vcombine_u16(vL_, vH_));\n}\n\n} \/\/ namespace\n\nnamespace {\n\nvoid resize_bilinear_rows(const Size2D &ssize, const Size2D &dsize,\n                        const u8 * srcBase, ptrdiff_t srcStride,\n                        u8 * dstBase, ptrdiff_t dstStride,\n                        f32 hr, const u8** gcols, u8* gcweight, u8* buf)\n{\n    f32 scale_y_offset = 0.5f * hr - 0.5f;\n\n    size_t dst_h8 = dsize.height & ~7;\n    size_t dst_w8 = dsize.width & ~7;\n    size_t src_w8 = ssize.width & ~7;\n\n    size_t r = 0;\n    for (; r < dst_h8; r += 8)\n    {\nresize8u_xystretch:\n        const u8* rows[16];\n        u8 rweight[8];\n\n        for (u32 i = 0; i < 8; ++i)\n        {\n            f32 w = (i + r) * hr + scale_y_offset;\n            ptrdiff_t src_row = floorf(w);\n            ptrdiff_t src_row2 = src_row + 1;\n\n            rweight[i] = (u8)((src_row2-w) * 128);\n\n            if (src_row < 0)\n                src_row = 0;\n            if (src_row2 >= (ptrdiff_t)ssize.height)\n                src_row2 = ssize.height-1;\n\n            rows[2 * i] = srcBase + src_row * srcStride;\n            rows[2 * i + 1] = srcBase + src_row2 * srcStride;\n        }\n\n        uint8x8_t vr0w = vdup_n_u8(rweight[0]);\n        uint8x8_t vr1w = vdup_n_u8(rweight[1]);\n        uint8x8_t vr2w = vdup_n_u8(rweight[2]);\n        uint8x8_t vr3w = vdup_n_u8(rweight[3]);\n        uint8x8_t vr4w = vdup_n_u8(rweight[4]);\n        uint8x8_t vr5w = vdup_n_u8(rweight[5]);\n        uint8x8_t vr6w = vdup_n_u8(rweight[6]);\n        uint8x8_t vr7w = vdup_n_u8(rweight[7]);\n\n        uint8x8_t vr0w2 = vdup_n_u8(128 - rweight[0]);\n        uint8x8_t vr1w2 = vdup_n_u8(128 - rweight[1]);\n        uint8x8_t vr2w2 = vdup_n_u8(128 - rweight[2]);\n        uint8x8_t vr3w2 = vdup_n_u8(128 - rweight[3]);\n        uint8x8_t vr4w2 = vdup_n_u8(128 - rweight[4]);\n        uint8x8_t vr5w2 = vdup_n_u8(128 - rweight[5]);\n        uint8x8_t vr6w2 = vdup_n_u8(128 - rweight[6]);\n        uint8x8_t vr7w2 = vdup_n_u8(128 - rweight[7]);\n\n        size_t col = 0;\n        for(; col < src_w8; col += 8)\n        {\n            internal::prefetch(rows[3] + col);\n            internal::prefetch(rows[7] + col);\n            internal::prefetch(rows[11] + col);\n            internal::prefetch(rows[15] + col);\nresize8u_ystretch:\n            uint8x8_t vsrc0l1 = vld1_u8(rows[0] + col);\n            uint8x8_t vsrc0l2 = vld1_u8(rows[1] + col);\n            uint8x8_t vsrc1l1 = vld1_u8(rows[2] + col);\n            uint8x8_t vsrc1l2 = vld1_u8(rows[3] + col);\n\n            \/\/ (l1 * w + l2 * (128 - w) + 64) \/ 128\n            uint16x8_t vdst0l = vmull_u8(vsrc0l1, vr0w);\n            uint16x8_t vdst1l = vmull_u8(vsrc1l1, vr1w);\n\n            uint8x8_t vsrc2l1 = vld1_u8(rows[4] + col);\n            uint8x8_t vsrc2l2 = vld1_u8(rows[5] + col);\n            uint8x8_t vsrc3l1 = vld1_u8(rows[6] + col);\n            uint8x8_t vsrc3l2 = vld1_u8(rows[7] + col);\n\n            vdst0l = vmlal_u8(vdst0l, vsrc0l2, vr0w2);\n            vdst1l = vmlal_u8(vdst1l, vsrc1l2, vr1w2);\n            uint16x8_t vdst2l = vmull_u8(vsrc2l1, vr2w);\n            uint16x8_t vdst3l = vmull_u8(vsrc3l1, vr3w);\n\n            uint8x8_t vsrc4l1 = vld1_u8(rows[8] + col);\n            uint8x8_t vsrc4l2 = vld1_u8(rows[9] + col);\n            uint8x8_t vsrc5l1 = vld1_u8(rows[10] + col);\n            uint8x8_t vsrc5l2 = vld1_u8(rows[11] + col);\n\n            vdst2l = vmlal_u8(vdst2l, vsrc2l2, vr2w2);\n            vdst3l = vmlal_u8(vdst3l, vsrc3l2, vr3w2);\n            uint16x8_t vdst4l = vmull_u8(vsrc4l1, vr4w);\n            uint16x8_t vdst5l = vmull_u8(vsrc5l1, vr5w);\n\n            uint8x8_t vsrc6l1 = vld1_u8(rows[12] + col);\n            uint8x8_t vsrc6l2 = vld1_u8(rows[13] + col);\n            uint8x8_t vsrc7l1 = vld1_u8(rows[14] + col);\n            uint8x8_t vsrc7l2 = vld1_u8(rows[15] + col);\n\n            uint8x8_t vdst0 = vrshrn_n_u16(vdst0l, 7);\n            uint8x8_t vdst1 = vrshrn_n_u16(vdst1l, 7);\n            vdst4l = vmlal_u8(vdst4l, vsrc4l2, vr4w2);\n            vdst5l = vmlal_u8(vdst5l, vsrc5l2, vr5w2);\n            uint16x8_t vdst6l = vmull_u8(vsrc6l1, vr6w);\n            uint16x8_t vdst7l = vmull_u8(vsrc7l1, vr7w);\n\n            uint8x8_t vdst2 = vrshrn_n_u16(vdst2l, 7);\n            uint8x8_t vdst3 = vrshrn_n_u16(vdst3l, 7);\n            vdst6l = vmlal_u8(vdst6l, vsrc6l2, vr6w2);\n            vdst7l = vmlal_u8(vdst7l, vsrc7l2, vr7w2);\n\n            uint8x8_t vdst4 = vrshrn_n_u16(vdst4l, 7);\n            uint8x8_t vdst5 = vrshrn_n_u16(vdst5l, 7);\n            uint8x8_t vdst6 = vrshrn_n_u16(vdst6l, 7);\n            uint8x8_t vdst7 = vrshrn_n_u16(vdst7l, 7);\n\n            \/\/ == 8x8 matrix transpose ==\n\n            \/\/00 01 02 03 04 05 06 07   d0\n            \/\/10 11 12 13 14 15 16 17   d1\n            \/\/20 21 22 23 24 25 26 27   d2\n            \/\/30 31 32 33 34 35 36 37   d3\n            \/\/40 41 42 43 44 45 46 47   d4\n            \/\/50 51 52 53 54 55 56 57   d5\n            \/\/60 61 62 63 64 65 66 67   d6\n            \/\/70 71 72 73 74 75 76 77   d7\n\n            uint8x8x2_t vdst10t = vtrn_u8(vdst0, vdst1);\n            uint8x8x2_t vdst32t = vtrn_u8(vdst2, vdst3);\n            uint8x8x2_t vdst54t = vtrn_u8(vdst4, vdst5);\n            uint8x8x2_t vdst76t = vtrn_u8(vdst6, vdst7);\n\n            uint8x16_t vd1d0 = vcombine_u8(vdst10t.val[0], vdst10t.val[1]);\n            uint8x16_t vd3d2 = vcombine_u8(vdst32t.val[0], vdst32t.val[1]);\n            uint8x16_t vd5d4 = vcombine_u8(vdst54t.val[0], vdst54t.val[1]);\n            uint8x16_t vd7d6 = vcombine_u8(vdst76t.val[0], vdst76t.val[1]);\n\n            \/\/00 10 02 12 04 14 06 16   d0\n            \/\/01 11 03 13 05 15 07 17   d1\n            \/\/20 30 22 32 24 34 26 36   d2\n            \/\/21 31 23 33 25 35 27 37   d3\n            \/\/40 50 42 52 44 54 46 56   d4\n            \/\/41 51 43 53 45 55 47 57   d5\n            \/\/60 70 62 72 64 74 66 76   d6\n            \/\/61 71 63 73 65 75 67 77   d7\n\n            uint16x8x2_t vq1q0t = vtrnq_u16((uint16x8_t)vd1d0, (uint16x8_t)vd3d2);\n            uint16x8x2_t vq3q2t = vtrnq_u16((uint16x8_t)vd5d4, (uint16x8_t)vd7d6);\n\n            \/\/00 10 20 30 04 14 24 34   d0\n            \/\/01 11 21 31 05 15 25 35   d1\n            \/\/02 12 22 32 06 16 26 36   d2\n            \/\/03 13 23 33 07 17 27 37   d3\n            \/\/40 50 60 70 44 54 64 74   d4\n            \/\/41 51 61 71 45 55 65 75   d5\n            \/\/42 52 62 72 46 56 66 76   d6\n            \/\/43 53 63 73 47 57 67 77   d7\n\n            uint32x4x2_t vq2q0t = vtrnq_u32((uint32x4_t)vq1q0t.val[0], (uint32x4_t)vq3q2t.val[0]);\n            uint32x4x2_t vq3q1t = vtrnq_u32((uint32x4_t)vq1q0t.val[1], (uint32x4_t)vq3q2t.val[1]);\n\n            \/\/00 10 20 30 40 50 60 70   d0\n            \/\/01 11 21 31 41 51 61 71   d1\n            \/\/02 12 22 32 42 52 62 72   d2\n            \/\/03 13 23 33 43 53 63 73   d3\n            \/\/04 14 24 34 44 54 64 74   d4\n            \/\/05 15 25 35 45 55 65 75   d5\n            \/\/06 16 26 36 46 56 66 76   d6\n            \/\/07 17 27 37 47 57 67 77   d7\n\n            vst1q_u8(buf + col * 8 +  0, (uint8x16_t)vq2q0t.val[0]);\n            vst1q_u8(buf + col * 8 + 16, (uint8x16_t)vq3q1t.val[0]);\n            vst1q_u8(buf + col * 8 + 32, (uint8x16_t)vq2q0t.val[1]);\n            vst1q_u8(buf + col * 8 + 48, (uint8x16_t)vq3q1t.val[1]);\n        }\n\n        if (col < ssize.width)\n        {\n            col = ssize.width - 8;\n            goto resize8u_ystretch;\n        }\n\n        u8* dst_data = dstBase + r * dstStride;\n        const u8** cols = gcols;\n        u8* cweight = gcweight;\n\n        size_t dcol = 0;\n        for (; dcol < dst_w8; dcol += 8, cols += 16, cweight += 8)\n        {\n            internal::prefetch(cols[0], 64*4);\nresize8u_xstretch:\n            uint8x8_t vc0w = vdup_n_u8(cweight[0]);\n            uint8x8_t vc1w = vdup_n_u8(cweight[1]);\n            uint8x8_t vc2w = vdup_n_u8(cweight[2]);\n            uint8x8_t vc3w = vdup_n_u8(cweight[3]);\n            uint8x8_t vc4w = vdup_n_u8(cweight[4]);\n            uint8x8_t vc5w = vdup_n_u8(cweight[5]);\n            uint8x8_t vc6w = vdup_n_u8(cweight[6]);\n            uint8x8_t vc7w = vdup_n_u8(cweight[7]);\n\n            uint8x8_t vc0w2 = vdup_n_u8(128 - cweight[0]);\n            uint8x8_t vc1w2 = vdup_n_u8(128 - cweight[1]);\n            uint8x8_t vc2w2 = vdup_n_u8(128 - cweight[2]);\n            uint8x8_t vc3w2 = vdup_n_u8(128 - cweight[3]);\n            uint8x8_t vc4w2 = vdup_n_u8(128 - cweight[4]);\n            uint8x8_t vc5w2 = vdup_n_u8(128 - cweight[5]);\n            uint8x8_t vc6w2 = vdup_n_u8(128 - cweight[6]);\n            uint8x8_t vc7w2 = vdup_n_u8(128 - cweight[7]);\n\n            uint8x8_t vsrc0l1 = vld1_u8(cols[0]);\n            uint8x8_t vsrc0l2 = vld1_u8(cols[1]);\n            uint8x8_t vsrc1l1 = vld1_u8(cols[2]);\n            uint8x8_t vsrc1l2 = vld1_u8(cols[3]);\n            uint8x8_t vsrc2l1 = vld1_u8(cols[4]);\n            uint8x8_t vsrc2l2 = vld1_u8(cols[5]);\n            uint8x8_t vsrc3l1 = vld1_u8(cols[6]);\n            uint8x8_t vsrc3l2 = vld1_u8(cols[7]);\n            uint8x8_t vsrc4l1 = vld1_u8(cols[8]);\n            uint8x8_t vsrc4l2 = vld1_u8(cols[9]);\n            uint8x8_t vsrc5l1 = vld1_u8(cols[10]);\n            uint8x8_t vsrc5l2 = vld1_u8(cols[11]);\n            uint8x8_t vsrc6l1 = vld1_u8(cols[12]);\n            uint8x8_t vsrc6l2 = vld1_u8(cols[13]);\n            uint8x8_t vsrc7l1 = vld1_u8(cols[14]);\n            uint8x8_t vsrc7l2 = vld1_u8(cols[15]);\n\n            \/\/ (l1 * w + l2 * (128 - w) + 64) \/ 128\n            uint16x8_t vdst0l = vmull_u8(vsrc0l1, vc0w);\n            uint16x8_t vdst1l = vmull_u8(vsrc1l1, vc1w);\n            uint16x8_t vdst2l = vmull_u8(vsrc2l1, vc2w);\n            uint16x8_t vdst3l = vmull_u8(vsrc3l1, vc3w);\n            uint16x8_t vdst4l = vmull_u8(vsrc4l1, vc4w);\n            uint16x8_t vdst5l = vmull_u8(vsrc5l1, vc5w);\n            uint16x8_t vdst6l = vmull_u8(vsrc6l1, vc6w);\n            uint16x8_t vdst7l = vmull_u8(vsrc7l1, vc7w);\n\n            vdst0l = vmlal_u8(vdst0l, vsrc0l2, vc0w2);\n            vdst1l = vmlal_u8(vdst1l, vsrc1l2, vc1w2);\n            vdst2l = vmlal_u8(vdst2l, vsrc2l2, vc2w2);\n            vdst3l = vmlal_u8(vdst3l, vsrc3l2, vc3w2);\n            vdst4l = vmlal_u8(vdst4l, vsrc4l2, vc4w2);\n            vdst5l = vmlal_u8(vdst5l, vsrc5l2, vc5w2);\n            vdst6l = vmlal_u8(vdst6l, vsrc6l2, vc6w2);\n            vdst7l = vmlal_u8(vdst7l, vsrc7l2, vc7w2);\n\n            uint8x8_t vdst0 = vrshrn_n_u16(vdst0l, 7);\n            uint8x8_t vdst1 = vrshrn_n_u16(vdst1l, 7);\n            uint8x8_t vdst2 = vrshrn_n_u16(vdst2l, 7);\n            uint8x8_t vdst3 = vrshrn_n_u16(vdst3l, 7);\n            uint8x8_t vdst4 = vrshrn_n_u16(vdst4l, 7);\n            uint8x8_t vdst5 = vrshrn_n_u16(vdst5l, 7);\n            uint8x8_t vdst6 = vrshrn_n_u16(vdst6l, 7);\n            uint8x8_t vdst7 = vrshrn_n_u16(vdst7l, 7);\n\n            \/\/ == 8x8 matrix transpose ==\n            uint8x8x2_t vdst10t = vtrn_u8(vdst0, vdst1);\n            uint8x8x2_t vdst32t = vtrn_u8(vdst2, vdst3);\n            uint8x8x2_t vdst54t = vtrn_u8(vdst4, vdst5);\n            uint8x8x2_t vdst76t = vtrn_u8(vdst6, vdst7);\n            uint8x16_t vd1d0 = vcombine_u8(vdst10t.val[0], vdst10t.val[1]);\n            uint8x16_t vd3d2 = vcombine_u8(vdst32t.val[0], vdst32t.val[1]);\n            uint8x16_t vd5d4 = vcombine_u8(vdst54t.val[0], vdst54t.val[1]);\n            uint8x16_t vd7d6 = vcombine_u8(vdst76t.val[0], vdst76t.val[1]);\n            uint16x8x2_t vq1q0t = vtrnq_u16((uint16x8_t)vd1d0, (uint16x8_t)vd3d2);\n            uint16x8x2_t vq3q2t = vtrnq_u16((uint16x8_t)vd5d4, (uint16x8_t)vd7d6);\n            uint32x4x2_t vq2q0t = vtrnq_u32((uint32x4_t)vq1q0t.val[0], (uint32x4_t)vq3q2t.val[0]);\n            uint32x4x2_t vq3q1t = vtrnq_u32((uint32x4_t)vq1q0t.val[1], (uint32x4_t)vq3q2t.val[1]);\n\n            \/\/save results\n            vst1_u8(dst_data + 0 * dstStride + dcol, (uint8x8_t)vget_low_u32(vq2q0t.val[0]));\n            vst1_u8(dst_data + 1 * dstStride + dcol, (uint8x8_t)vget_high_u32(vq2q0t.val[0]));\n            vst1_u8(dst_data + 2 * dstStride + dcol, (uint8x8_t)vget_low_u32(vq3q1t.val[0]));\n            vst1_u8(dst_data + 3 * dstStride + dcol, (uint8x8_t)vget_high_u32(vq3q1t.val[0]));\n            vst1_u8(dst_data + 4 * dstStride + dcol, (uint8x8_t)vget_low_u32(vq2q0t.val[1]));\n            vst1_u8(dst_data + 5 * dstStride + dcol, (uint8x8_t)vget_high_u32(vq2q0t.val[1]));\n            vst1_u8(dst_data + 6 * dstStride + dcol, (uint8x8_t)vget_low_u32(vq3q1t.val[1]));\n            vst1_u8(dst_data + 7 * dstStride + dcol, (uint8x8_t)vget_high_u32(vq3q1t.val[1]));\n        }\n\n        if (dcol < dsize.width)\n        {\n            dcol = dsize.width - 8;\n            cols = gcols + dcol * 2;\n            cweight = gcweight + dcol;\n            goto resize8u_xstretch;\n        }\n    }\n\n    if (r < dsize.height)\n    {\n        r = dsize.height - 8;\n        goto resize8u_xystretch;\n    }\n}\n\ntemplate <int channels> struct resizeLinearInternals;\ntemplate <> struct resizeLinearInternals<1>\n{\n    int32x4_t vc_upd;\n    int32x4_t vc0;\n    int32x4_t vcmax;\n\n    inline resizeLinearInternals(int32x4_t & vi, u32 srccols)\n    {\n        vc_upd = vdupq_n_s32(4);\n        vc0 = vdupq_n_s32(0);\n        vcmax = vdupq_n_s32(srccols-1);\n\n        s32 tmp0123[] = {0, 1, 2, 3 };\n        vi = vld1q_s32(tmp0123);\n    }\n    inline void updateIndexes(int32x4_t & vi, int32x4_t & vsrch, int32x4_t & vsrcl)\n    {\n        vsrch = vminq_s32(vsrch, vcmax);\n        vsrcl = vmaxq_s32(vsrcl, vc0);\n        vsrcl = vminq_s32(vsrcl, vcmax);\/\/for safe tail\n        vsrch = vshlq_n_s32(vsrch, 3);\n        vsrcl = vshlq_n_s32(vsrcl, 3);\n        vi = vaddq_s32(vi, vc_upd);\n    }\n};\ntemplate <> struct resizeLinearInternals<4>\n{\n    int32x4_t vc_upd;\n    int32x4_t vc0;\n    int32x4_t vcmax;\n    int32x4_t v0123x8;\n\n    inline resizeLinearInternals(int32x4_t & vi, u32 srccols)\n    {\n        vc_upd = vdupq_n_s32(1);\n        vc0 = vdupq_n_s32(0);\n        vcmax = vdupq_n_s32(srccols-1);\n        s32 tmp0123x8[] = {0, 8, 16, 24};\n        v0123x8 = vld1q_s32(tmp0123x8);\n\n        vi = vc0;\n    }\n    inline void updateIndexes(int32x4_t & vi, int32x4_t & vsrch, int32x4_t & vsrcl)\n    {\n        vsrch = vminq_s32(vsrch, vcmax);\n        vsrcl = vmaxq_s32(vsrcl, vc0);\n        vsrch = vshlq_n_s32(vsrch, 5);\n        vsrcl = vshlq_n_s32(vsrcl, 5);\n        vsrch = vaddq_s32(vsrch, v0123x8);\n        vsrcl = vaddq_s32(vsrcl, v0123x8);\n        vi = vaddq_s32(vi, vc_upd);\n    }\n};\n\ntemplate <int channels>\nvoid resizeLinearOpenCVchan(const Size2D &_ssize, const Size2D &_dsize,\n                            const u8 * srcBase, ptrdiff_t srcStride,\n                            u8 * dstBase, ptrdiff_t dstStride,\n                            f32 wr, f32 hr)\n{\n    float scale_x_offset = 0.5f * wr - 0.5f;\n\n    Size2D ssize(_ssize.width*channels, _ssize.height);\n    Size2D dsize(_dsize.width*channels, _dsize.height);\n\n    std::vector<u8> gcweight((dsize.width + 7) & ~7);\n    std::vector<const u8*> gcols(((dsize.width + 7) & ~7) * 2);\n    std::vector<u8> buf(((ssize.width + 7) & ~7) * 8); \/\/ (8 rows) x (width of src)\n\n    float32x4_t vscale_x = vdupq_n_f32(wr);\n    float32x4_t vscale_x_offset = vdupq_n_f32(scale_x_offset);\n    int32x4_t vc1 = vdupq_n_s32(1);\n    float32x4_t vc128f = vdupq_n_f32(128.0f);\n\n    int32x4_t vi;\n    resizeLinearInternals<channels> indexes(vi, _ssize.width);\/\/u32 is used to store indexes\n                                                              \/\/so we could get issues on src image dimensions greater than (2^32-1)\n\n    for (size_t dcol = 0; dcol < dsize.width; dcol += 8)\n    {\n        s32 idx[16];\n\n        float32x4_t vif = vcvtq_f32_s32(vi);\n        float32x4_t vw = vmlaq_f32(vscale_x_offset, vscale_x, vif);\n        int32x4_t vwi = vcvtq_s32_f32(vw);\n        float32x4_t vwif = vcvtq_f32_s32(vwi);\n        int32x4_t vmask = (int32x4_t)vcltq_f32(vwif, vw);\n        int32x4_t vsrch = vsubq_s32(vwi, vmask);\n        int32x4_t vsrcl = vsubq_s32(vsrch, vc1);\n        float32x4_t vsrchf = vcvtq_f32_s32(vsrch);\n        float32x4_t vw2 = vsubq_f32(vsrchf, vw);\n\n        vw2 = vmulq_f32(vw2, vc128f);\n        uint32x4_t vw32u = vcvtq_u32_f32(vw2);\n        uint16x4_t vw16ul = vmovn_u32(vw32u);\n        indexes.updateIndexes(vi, vsrch, vsrcl);\n\n        vst1q_s32(idx + 0, vsrcl);\n        vst1q_s32(idx + 8, vsrch);\n\n        vif = vcvtq_f32_s32(vi);\n        vw = vmlaq_f32(vscale_x_offset, vscale_x, vif);\n        vwi = vcvtq_s32_f32(vw);\n        vwif = vcvtq_f32_s32(vwi);\n        vmask = (int32x4_t)vcltq_f32(vwif, vw);\n        vsrch = vsubq_s32(vwi, vmask);\n        vsrcl = vsubq_s32(vsrch, vc1);\n        vsrchf = vcvtq_f32_s32(vsrch);\n        vw2 = vsubq_f32(vsrchf, vw);\n\n        vw2 = vmulq_f32(vw2, vc128f);\n        vw32u = vcvtq_u32_f32(vw2);\n        indexes.updateIndexes(vi, vsrch, vsrcl);\n\n        uint16x4_t vw16uh = vmovn_u32(vw32u);\n\n        vst1q_s32(idx + 4, vsrcl);\n        vst1q_s32(idx + 12, vsrch);\n\n        uint8x8_t vw8u = vmovn_u16(vcombine_u16(vw16ul, vw16uh));\n\n        for (u32 i = 0; i < 8; ++i)\n        {\n            gcols[dcol * 2 + i*2] = &buf[idx[i]];\n            gcols[dcol * 2 + i*2 + 1] = &buf[idx[i + 8]];\n        }\n\n        vst1_u8(&gcweight[dcol], vw8u);\n    }\n\n    resize_bilinear_rows(ssize, dsize, srcBase, srcStride, dstBase, dstStride, hr, &gcols[0], &gcweight[0], &buf[0]);\n}\n\nvoid downsample_bilinear_8uc1(const Size2D &ssize, const Size2D &dsize,\n                              const u8 * srcBase, ptrdiff_t srcStride,\n                              u8 * dstBase, ptrdiff_t dstStride,\n                              f32 wr, f32 hr)\n{\n    internal::assertSupportedConfiguration(wr <= 2.f && hr <= 2.f);\n\n    enum { SHIFT_BITS = 11 };\n\n    f32 scale_x_offset = 0.5f * wr - 0.5f;\n    f32 scale_y_offset = 0.5f * hr - 0.5f;\n\n    std::vector<s32> _buf(dsize.height*(2*(sizeof(ptrdiff_t)\/sizeof(s32))+1)+1);\n    ptrdiff_t* buf = (ptrdiff_t*)&_buf[0];\n    s32* buf2 = (s32*)buf+2*(sizeof(ptrdiff_t)\/sizeof(s32))*dsize.height;\n    for(size_t row = 0; row < (size_t)dsize.height; ++row)\n    {\n        f32 r = row * hr + scale_y_offset;\n        ptrdiff_t src_row = floorf(r);\n        ptrdiff_t src_row2 = src_row + 1;\n\n        f32 rweight = src_row2 - r;\n        buf2[row] = floorf(rweight * (1 << SHIFT_BITS) + 0.5f);\n        buf[0 * dsize.height + row] = std::max<ptrdiff_t>(0, src_row);\n        buf[1 * dsize.height + row] = std::min((ptrdiff_t)ssize.height-1, src_row2);\n    }\n\n#define USE_CORRECT_VERSION 0\n\n    ptrdiff_t col = 0;\n\/***********************************************\/\n    for(; col <= (ptrdiff_t)dsize.width-16; col+=16)\n    {\n        ptrdiff_t col1[16];\n        ptrdiff_t col2[16];\n        s16 cwi[16];\n\n        for(s32 k = 0; k < 16; ++k)\n        {\n            f32 c = (col + k) * wr + scale_x_offset;\n            col1[k] = (ptrdiff_t)c;\n            col2[k] = col1[k] + 1;\n\n            cwi[k] = (short)floorf((col2[k] - c) * (1 << SHIFT_BITS) + 0.5f);\n\n            if(col1[k] < 0) col1[k] = 0;\n            if(col2[k] >= (ptrdiff_t)ssize.width) col2[k] = ssize.width-1;\n        }\n\n        ptrdiff_t x = std::min(col1[0], (ptrdiff_t)ssize.width-16);\n        ptrdiff_t y = std::min(col1[8], (ptrdiff_t)ssize.width-16);\n        u8 lutl[16];\n        u8 luth[16];\n        for(s32 k = 0; k < 8; ++k)\n        {\n            lutl[k] = (u8)(col1[k] - x);\n            luth[k] = (u8)(col2[k] - x);\n            lutl[k+8] = (u8)(col1[k+8] - y);\n            luth[k+8] = (u8)(col2[k+8] - y);\n        }\n\n        uint8x8_t vlutl = vld1_u8(lutl);\n        uint8x8_t vluth = vld1_u8(luth);\n        int16x8_t vcw = vld1q_s16(cwi);\n\n        uint8x8_t vlutl_ = vld1_u8(lutl+8);\n        uint8x8_t vluth_ = vld1_u8(luth+8);\n        int16x8_t vcw_ = vld1q_s16(cwi+8);\n\n        for(ptrdiff_t row = 0; row < (ptrdiff_t)dsize.height; ++row)\n        {\n#if USE_CORRECT_VERSION\n            int32x4_t vrw = vdupq_n_s32(buf2[row]);\n#else\n            int16x8_t vrw = vdupq_n_s16((int16_t)buf2[row]);\n            int16x8_t vrW = vdupq_n_s16((int16_t)((1 << SHIFT_BITS) - buf2[row]));\n#endif\n\n            internal::prefetch(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + x, 2*srcStride);\n            internal::prefetch(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + x, 3*srcStride);\n\n            {\n                union { uint8x16_t v; uint8x8x2_t w; } vr1 = { vld1q_u8(internal::getRowPtr(srcBase, srcStride, buf[0*dsize.height + row]) + x) };\n                union { uint8x16_t v; uint8x8x2_t w; } vr2 = { vld1q_u8(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + x) };\n\n                uint8x8_t vr1l = vtbl2_u8(vr1.w, vlutl);\n                uint8x8_t vr1h = vtbl2_u8(vr1.w, vluth);\n                uint8x8_t vr2l = vtbl2_u8(vr2.w, vlutl);\n                uint8x8_t vr2h = vtbl2_u8(vr2.w, vluth);\n\n                uint16x8_t v1hw = vmovl_u8(vr1h);\n                uint16x8_t v2hw = vmovl_u8(vr2h);\n\n                int16x8_t v1df = vreinterpretq_s16_u16(vsubl_u8(vr1l, vr1h));\n                int16x8_t v2df = vreinterpretq_s16_u16(vsubl_u8(vr2l, vr2h));\n\n                int32x4_t v1L = vreinterpretq_s32_u32(vshll_n_u16(vget_low_u16(v1hw),  SHIFT_BITS));\n                int32x4_t v1H = vreinterpretq_s32_u32(vshll_n_u16(vget_high_u16(v1hw), SHIFT_BITS));\n                int32x4_t v2L = vreinterpretq_s32_u32(vshll_n_u16(vget_low_u16(v2hw),  SHIFT_BITS));\n                int32x4_t v2H = vreinterpretq_s32_u32(vshll_n_u16(vget_high_u16(v2hw), SHIFT_BITS));\n\n                v1L = vmlal_s16(v1L, vget_low_s16(v1df), vget_low_s16(vcw));\n                v1H = vmlal_s16(v1H, vget_high_s16(v1df), vget_high_s16(vcw));\n                v2L = vmlal_s16(v2L, vget_low_s16(v2df), vget_low_s16(vcw));\n                v2H = vmlal_s16(v2H, vget_high_s16(v2df), vget_high_s16(vcw));\n\n#if USE_CORRECT_VERSION\n                \/* correct version *\/\n                int32x4_t vL = vshlq_n_s32(v2L, SHIFT_BITS);\n                int32x4_t vH = vshlq_n_s32(v2H, SHIFT_BITS);\n                int32x4_t vdiffL = vsubq_s32(v1L, v2L);\n                int32x4_t vdiffH = vsubq_s32(v1H, v2H);\n\n                vL = vmlaq_s32(vL, vdiffL, vrw);\n                vH = vmlaq_s32(vH, vdiffH, vrw);\n                uint16x4_t vL_ = vqrshrun_n_s32(vL, 2*SHIFT_BITS - 8);\n                uint16x4_t vH_ = vqrshrun_n_s32(vH, 2*SHIFT_BITS - 8);\n                uint8x8_t vres = vrshrn_n_u16(vcombine_u16(vL_, vH_), 8);\n                vst1_u8(internal::getRowPtr(dstBase, dstStride, row) + col, vres);\n#else\n                \/* ugly version matching to OpenCV's SSE optimization *\/\n                int16x4_t v1Ls = vshrn_n_s32(v1L, 4);\n                int16x4_t v1Hs = vshrn_n_s32(v1H, 4);\n                int16x4_t v2Ls = vshrn_n_s32(v2L, 4);\n                int16x4_t v2Hs = vshrn_n_s32(v2H, 4);\n\n                int16x8_t v1s = vqdmulhq_s16(vcombine_s16(v1Ls, v1Hs), vrw);\n                int16x8_t v2s = vqdmulhq_s16(vcombine_s16(v2Ls, v2Hs), vrW);\n\n                int16x8_t vsum = vaddq_s16(vshrq_n_s16(v1s,1), vshrq_n_s16(v2s,1));\n                uint8x8_t vres = vqrshrun_n_s16(vsum, 2);\n\n                vst1_u8(internal::getRowPtr(dstBase, dstStride, row) + col, vres);\n#endif\n            }\n\n            {\n                union { uint8x16_t v; uint8x8x2_t w; } vr1 = { vld1q_u8(internal::getRowPtr(srcBase, srcStride, buf[0*dsize.height + row]) + y) };\n                union { uint8x16_t v; uint8x8x2_t w; } vr2 = { vld1q_u8(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + y) };\n\n                uint8x8_t vr1l = vtbl2_u8(vr1.w, vlutl_);\n                uint8x8_t vr1h = vtbl2_u8(vr1.w, vluth_);\n                uint8x8_t vr2l = vtbl2_u8(vr2.w, vlutl_);\n                uint8x8_t vr2h = vtbl2_u8(vr2.w, vluth_);\n\n                uint16x8_t v1hw = vmovl_u8(vr1h);\n                uint16x8_t v2hw = vmovl_u8(vr2h);\n\n                int16x8_t v1df = vreinterpretq_s16_u16(vsubl_u8(vr1l, vr1h));\n                int16x8_t v2df = vreinterpretq_s16_u16(vsubl_u8(vr2l, vr2h));\n\n                int32x4_t v1L = vreinterpretq_s32_u32(vshll_n_u16(vget_low_u16(v1hw),  SHIFT_BITS));\n                int32x4_t v1H = vreinterpretq_s32_u32(vshll_n_u16(vget_high_u16(v1hw), SHIFT_BITS));\n                int32x4_t v2L = vreinterpretq_s32_u32(vshll_n_u16(vget_low_u16(v2hw),  SHIFT_BITS));\n                int32x4_t v2H = vreinterpretq_s32_u32(vshll_n_u16(vget_high_u16(v2hw), SHIFT_BITS));\n\n                v1L = vmlal_s16(v1L, vget_low_s16(v1df), vget_low_s16(vcw_));\n                v1H = vmlal_s16(v1H, vget_high_s16(v1df), vget_high_s16(vcw_));\n                v2L = vmlal_s16(v2L, vget_low_s16(v2df), vget_low_s16(vcw_));\n                v2H = vmlal_s16(v2H, vget_high_s16(v2df), vget_high_s16(vcw_));\n\n#if USE_CORRECT_VERSION\n                \/* correct version *\/\n                int32x4_t vL = vshlq_n_s32(v2L, SHIFT_BITS);\n                int32x4_t vH = vshlq_n_s32(v2H, SHIFT_BITS);\n                int32x4_t vdiffL = vsubq_s32(v1L, v2L);\n                int32x4_t vdiffH = vsubq_s32(v1H, v2H);\n\n                vL = vmlaq_s32(vL, vdiffL, vrw);\n                vH = vmlaq_s32(vH, vdiffH, vrw);\n                uint16x4_t vL_ = vqrshrun_n_s32(vL, 2*SHIFT_BITS - 8);\n                uint16x4_t vH_ = vqrshrun_n_s32(vH, 2*SHIFT_BITS - 8);\n                uint8x8_t vres = vrshrn_n_u16(vcombine_u16(vL_, vH_), 8);\n                vst1_u8(internal::getRowPtr(dstBase, dstStride, row) + col + 8, vres);\n#else\n                \/* ugly version matching to OpenCV's SSE optimization *\/\n                int16x4_t v1Ls = vshrn_n_s32(v1L, 4);\n                int16x4_t v1Hs = vshrn_n_s32(v1H, 4);\n                int16x4_t v2Ls = vshrn_n_s32(v2L, 4);\n                int16x4_t v2Hs = vshrn_n_s32(v2H, 4);\n\n                int16x8_t v1s = vqdmulhq_s16(vcombine_s16(v1Ls, v1Hs), vrw);\n                int16x8_t v2s = vqdmulhq_s16(vcombine_s16(v2Ls, v2Hs), vrW);\n\n                int16x8_t vsum = vaddq_s16(vshrq_n_s16(v1s,1), vshrq_n_s16(v2s,1));\n                uint8x8_t vres = vqrshrun_n_s16(vsum, 2);\n\n                vst1_u8(internal::getRowPtr(dstBase, dstStride, row) + col + 8, vres);\n#endif\n            }\n        }\n    }\n\/***********************************************\/\n    for(; col <= (ptrdiff_t)dsize.width-8; col+=8)\n    {\ndownsample_bilinear_8uc1_col_loop8:\n        ptrdiff_t col1[8];\n        ptrdiff_t col2[8];\n        s16 cwi[8];\n\n        for(s32 k = 0; k < 8; ++k)\n        {\n            f32 c = (col + k) * wr + scale_x_offset;\n            col1[k] = (ptrdiff_t)c;\n            col2[k] = col1[k] + 1;\n\n            cwi[k] = (s16)floorf((col2[k] - c) * (1 << SHIFT_BITS) + 0.5f);\n\n            if(col1[k] < 0) col1[k] = 0;\n            if(col2[k] >= (ptrdiff_t)ssize.width) col2[k] = (ptrdiff_t)ssize.width-1;\n        }\n\n        ptrdiff_t x = std::min(col1[0], (ptrdiff_t)ssize.width-16);\n        u8 lutl[8];\n        u8 luth[8];\n        for(s32 k = 0; k < 8; ++k)\n        {\n            lutl[k] = (u8)(col1[k] - x);\n            luth[k] = (u8)(col2[k] - x);\n        }\n\n        uint8x8_t vlutl = vld1_u8(lutl);\n        uint8x8_t vluth = vld1_u8(luth);\n        int16x8_t vcw = vld1q_s16(cwi);\n\n        for(ptrdiff_t row = 0; row < (ptrdiff_t)dsize.height; ++row)\n        {\n#if USE_CORRECT_VERSION\n            int32x4_t vrw = vdupq_n_s32(buf2[row]);\n#else\n            int16x8_t vrw = vdupq_n_s16((int16_t)buf2[row]);\n            int16x8_t vrW = vdupq_n_s16((int16_t)((1 << SHIFT_BITS) - buf2[row]));\n#endif\n\n            internal::prefetch(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + x, 2*srcStride);\n            internal::prefetch(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + x, 3*srcStride);\n\n            union { uint8x16_t v; uint8x8x2_t w; } vr1 = { vld1q_u8(internal::getRowPtr(srcBase, srcStride, buf[0*dsize.height + row]) + x) };\n            union { uint8x16_t v; uint8x8x2_t w; } vr2 = { vld1q_u8(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + x) };\n\n            uint8x8_t vr1l = vtbl2_u8(vr1.w, vlutl);\n            uint8x8_t vr1h = vtbl2_u8(vr1.w, vluth);\n            uint8x8_t vr2l = vtbl2_u8(vr2.w, vlutl);\n            uint8x8_t vr2h = vtbl2_u8(vr2.w, vluth);\n\n            uint16x8_t v1hw = vmovl_u8(vr1h);\n            uint16x8_t v2hw = vmovl_u8(vr2h);\n\n            int16x8_t v1df = vreinterpretq_s16_u16(vsubl_u8(vr1l, vr1h));\n            int16x8_t v2df = vreinterpretq_s16_u16(vsubl_u8(vr2l, vr2h));\n\n            int32x4_t v1L = vreinterpretq_s32_u32(vshll_n_u16(vget_low_u16(v1hw),  SHIFT_BITS));\n            int32x4_t v1H = vreinterpretq_s32_u32(vshll_n_u16(vget_high_u16(v1hw), SHIFT_BITS));\n            int32x4_t v2L = vreinterpretq_s32_u32(vshll_n_u16(vget_low_u16(v2hw),  SHIFT_BITS));\n            int32x4_t v2H = vreinterpretq_s32_u32(vshll_n_u16(vget_high_u16(v2hw), SHIFT_BITS));\n\n            v1L = vmlal_s16(v1L, vget_low_s16(v1df), vget_low_s16(vcw));\n            v1H = vmlal_s16(v1H, vget_high_s16(v1df), vget_high_s16(vcw));\n            v2L = vmlal_s16(v2L, vget_low_s16(v2df), vget_low_s16(vcw));\n            v2H = vmlal_s16(v2H, vget_high_s16(v2df), vget_high_s16(vcw));\n\n#if USE_CORRECT_VERSION\n            \/* correct version *\/\n            int32x4_t vL = vshlq_n_s32(v2L, SHIFT_BITS);\n            int32x4_t vH = vshlq_n_s32(v2H, SHIFT_BITS);\n            int32x4_t vdiffL = vsubq_s32(v1L, v2L);\n            int32x4_t vdiffH = vsubq_s32(v1H, v2H);\n\n            vL = vmlaq_s32(vL, vdiffL, vrw);\n            vH = vmlaq_s32(vH, vdiffH, vrw);\n            uint16x4_t vL_ = vqrshrun_n_s32(vL, 2*SHIFT_BITS - 8);\n            uint16x4_t vH_ = vqrshrun_n_s32(vH, 2*SHIFT_BITS - 8);\n            uint8x8_t vres = vrshrn_n_u16(vcombine_u16(vL_, vH_), 8);\n            vst1_u8(internal::getRowPtr(dstBase, dstStride, row) + col, vres);\n#else\n            \/* ugly version matching to OpenCV's SSE optimization *\/\n            int16x4_t v1Ls = vshrn_n_s32(v1L, 4);\n            int16x4_t v1Hs = vshrn_n_s32(v1H, 4);\n            int16x4_t v2Ls = vshrn_n_s32(v2L, 4);\n            int16x4_t v2Hs = vshrn_n_s32(v2H, 4);\n\n            int16x8_t v1s = vqdmulhq_s16(vcombine_s16(v1Ls, v1Hs), vrw);\n            int16x8_t v2s = vqdmulhq_s16(vcombine_s16(v2Ls, v2Hs), vrW);\n\n            int16x8_t vsum = vaddq_s16(vshrq_n_s16(v1s,1), vshrq_n_s16(v2s,1));\n            uint8x8_t vres = vqrshrun_n_s16(vsum, 2);\n\n            vst1_u8(internal::getRowPtr(dstBase, dstStride, row) + col, vres);\n#endif\n        }\n    }\n    if (col < (ptrdiff_t)dsize.width)\n    {\n        col = dsize.width - 8;\n        goto downsample_bilinear_8uc1_col_loop8;\n    }\n}\n\n} \/\/ namespace\n\n#endif\n\nvoid resizeLinearOpenCV(const Size2D &ssize, const Size2D &dsize,\n                        const u8 * srcBase, ptrdiff_t srcStride,\n                        u8 * dstBase, ptrdiff_t dstStride,\n                        f32 wr, f32 hr, u32 channels)\n{\n    internal::assertSupportedConfiguration(wr > 0 && hr > 0 &&\n                                           (dsize.width - 0.5) * wr - 0.5 < ssize.width &&\n                                           (dsize.height - 0.5) * hr - 0.5 < ssize.height &&  \/\/ Ensure we have enough source data\n                                           (dsize.width + 0.5) * wr + 0.5 >= ssize.width &&\n                                           (dsize.height + 0.5) * hr + 0.5 >= ssize.height && \/\/ Ensure source isn't too big\n                                           isResizeLinearOpenCVSupported(ssize, dsize, channels));\n#ifdef CAROTENE_NEON\n        if(1 == channels)\n        {\n            if (wr <= 1.f && hr <= 1.f)\n                resizeLinearOpenCVchan<1>(ssize, dsize, srcBase, srcStride, dstBase, dstStride, wr, hr);\n            else if (wr <= 2.0f && hr <= 2.0f && ssize.width >= 16)\n                downsample_bilinear_8uc1(ssize, dsize, srcBase, srcStride, dstBase, dstStride, wr, hr);\n            else\n                resizeLinearOpenCVchan<1>(ssize, dsize, srcBase, srcStride, dstBase, dstStride, wr, hr);\n        }\n        else if(4 == channels)\n            resizeLinearOpenCVchan<4>(ssize, dsize, srcBase, srcStride, dstBase, dstStride, wr, hr);\n#else\n    (void)ssize;\n    (void)dsize;\n    (void)srcBase;\n    (void)srcStride;\n    (void)dstBase;\n    (void)dstStride;\n    (void)wr;\n    (void)hr;\n    (void)channels;\n#endif\n}\n\nvoid resizeLinear(const Size2D &ssize, const Size2D &dsize,\n                  const u8 * srcBase, ptrdiff_t srcStride,\n                  u8 * dstBase, ptrdiff_t dstStride,\n                  f32 wr, f32 hr, u32 channels)\n{\n    internal::assertSupportedConfiguration(wr > 0 && hr > 0 &&\n                                           (dsize.width - 0.5) * wr - 0.5 < ssize.width &&\n                                           (dsize.height - 0.5) * hr - 0.5 < ssize.height &&  \/\/ Ensure we have enough source data\n                                           (dsize.width + 0.5) * wr + 0.5 >= ssize.width &&\n                                           (dsize.height + 0.5) * hr + 0.5 >= ssize.height && \/\/ Ensure source isn't too big\n                                           isResizeLinearSupported(ssize, dsize,\n                                                                   wr, hr, channels));\n#ifdef CAROTENE_NEON\n    f32 scale_x = wr;\n    f32 scale_x_offset = 0.5f * scale_x - 0.5f;\n    f32 scale_y = hr;\n    f32 scale_y_offset = 0.5f * scale_y - 0.5f;\n\n    std::vector<ptrdiff_t> _buf(dsize.height * 3 + 1);\n    std::vector<f32> coeff(dsize.height);\n    ptrdiff_t * buf = &_buf[0];\n\n    for (size_t row = 0; row < dsize.height; ++row)\n    {\n        f32 r = row * scale_y + scale_y_offset;\n        ptrdiff_t src_row = floorf(r);\n        ptrdiff_t src_row2 = src_row + 1;\n\n        f32 rweight = src_row2 - r;\n        buf[0 * dsize.height + row] = std::max<ptrdiff_t>(0, src_row);\n        buf[1 * dsize.height + row] = std::min<ptrdiff_t>(ssize.height - 1, src_row2);\n        coeff[row] = rweight;\n    }\n\n    size_t col = 0;\n    for ( ; col + 16 <= dsize.width; col += 16)\n    {\n        ptrdiff_t col1[16], col2[16];\n        f32 cwi[16];\n\n        for(s32 k = 0; k < 16; ++k)\n        {\n            f32 c = (col + k) * scale_x + scale_x_offset;\n            col1[k] = floorf(c);\n            col2[k] = col1[k] + 1;\n\n            cwi[k] = col2[k] - c;\n\n            if (col1[k] < 0)\n                col1[k] = 0;\n            if (col2[k] >= (ptrdiff_t)ssize.width)\n                col2[k] = ssize.width - 1;\n        }\n\n        ptrdiff_t x = std::min<ptrdiff_t>(col1[0], ssize.width - 16);\n        ptrdiff_t y = std::min<ptrdiff_t>(col1[8], ssize.width - 16);\n        u8 lutl[16], luth[16];\n\n        for (s32 k = 0; k < 8; ++k)\n        {\n            lutl[k] = (u8)(col1[k] - x);\n            luth[k] = (u8)(col2[k] - x);\n            lutl[k + 8] = (u8)(col1[k + 8] - y);\n            luth[k + 8] = (u8)(col2[k + 8] - y);\n        }\n\n        uint8x8_t vlutl = vld1_u8(lutl);\n        uint8x8_t vluth = vld1_u8(luth);\n        float32x4_t vcw0 = vld1q_f32(cwi);\n        float32x4_t vcw1 = vld1q_f32(cwi + 4);\n\n        uint8x8_t vlutl_ = vld1_u8(lutl + 8);\n        uint8x8_t vluth_ = vld1_u8(luth + 8);\n        float32x4_t vcw0_ = vld1q_f32(cwi + 8);\n        float32x4_t vcw1_ = vld1q_f32(cwi + 12);\n\n        if (channels == 1)\n        {\n            for (size_t row = 0; row < dsize.height; ++row)\n            {\n                float32x4_t vrw = vdupq_n_f32(coeff[row]);\n\n                const u8 * srow0 = internal::getRowPtr(srcBase, srcStride, buf[0 * dsize.height + row]);\n                const u8 * srow1 = internal::getRowPtr(srcBase, srcStride, buf[1 * dsize.height + row]);\n                u8 * drow = internal::getRowPtr(dstBase, dstStride, row);\n\n                internal::prefetch(srow0 + x + 2 * srcStride);\n                internal::prefetch(srow1 + x + 2 * srcStride);\n\n                uint8x8_t vres0 = resizeLinearStep(vld1q_u8(srow0 + x), vld1q_u8(srow1 + x),\n                                                   vlutl, vluth,\n                                                   vrw, vcw0, vcw1);\n\n                uint8x8_t vres1 = resizeLinearStep(vld1q_u8(srow0 + y), vld1q_u8(srow1 + y),\n                                                   vlutl_, vluth_,\n                                                   vrw, vcw0_, vcw1_);\n\n                vst1q_u8(drow + col, vcombine_u8(vres0, vres1));\n            }\n        }\n        else if (channels == 3)\n        {\n            for (size_t row = 0; row < dsize.height; ++row)\n            {\n                float32x4_t vrw = vdupq_n_f32(coeff[row]);\n\n                const u8 * srow0 = internal::getRowPtr(srcBase, srcStride, buf[0 * dsize.height + row]);\n                const u8 * srow1 = internal::getRowPtr(srcBase, srcStride, buf[1 * dsize.height + row]);\n                u8 * drow = internal::getRowPtr(dstBase, dstStride, row);\n\n                internal::prefetch(srow0 + x + 2 * srcStride);\n                internal::prefetch(srow1 + x + 2 * srcStride);\n\n                uint8x16x3_t v_src10 = vld3q_u8(srow0 + (x * 3));\n                uint8x16x3_t v_src20 = vld3q_u8(srow1 + (x * 3));\n\n                uint8x16x3_t v_src11 = vld3q_u8(srow0 + (y * 3));\n                uint8x16x3_t v_src21 = vld3q_u8(srow1 + (y * 3));\n\n                uint8x16x3_t v_dst;\n\n                v_dst.val[0] = vcombine_u8(resizeLinearStep(v_src10.val[0], v_src20.val[0], vlutl, vluth, vrw, vcw0, vcw1),\n                                           resizeLinearStep(v_src11.val[0], v_src21.val[0], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n                v_dst.val[1] = vcombine_u8(resizeLinearStep(v_src10.val[1], v_src20.val[1], vlutl, vluth, vrw, vcw0, vcw1),\n                                           resizeLinearStep(v_src11.val[1], v_src21.val[1], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n                v_dst.val[2] = vcombine_u8(resizeLinearStep(v_src10.val[2], v_src20.val[2], vlutl, vluth, vrw, vcw0, vcw1),\n                                           resizeLinearStep(v_src11.val[2], v_src21.val[2], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n\n                vst3q_u8(drow + (col * 3), v_dst);\n            }\n        }\n        else if (channels == 4)\n        {\n            for (size_t row = 0; row < dsize.height; ++row)\n            {\n                float32x4_t vrw = vdupq_n_f32(coeff[row]);\n\n                const u8 * srow0 = internal::getRowPtr(srcBase, srcStride, buf[0 * dsize.height + row]);\n                const u8 * srow1 = internal::getRowPtr(srcBase, srcStride, buf[1 * dsize.height + row]);\n                u8 * drow = internal::getRowPtr(dstBase, dstStride, row);\n\n                internal::prefetch(srow0 + x + 2 * srcStride);\n                internal::prefetch(srow1 + x + 2 * srcStride);\n\n                uint8x16x4_t v_src10 = vld4q_u8(srow0 + (x << 2));\n                uint8x16x4_t v_src20 = vld4q_u8(srow1 + (x << 2));\n\n                uint8x16x4_t v_src11 = vld4q_u8(srow0 + (y << 2));\n                uint8x16x4_t v_src21 = vld4q_u8(srow1 + (y << 2));\n\n                uint8x16x4_t v_dst;\n\n                v_dst.val[0] = vcombine_u8(resizeLinearStep(v_src10.val[0], v_src20.val[0], vlutl, vluth, vrw, vcw0, vcw1),\n                                           resizeLinearStep(v_src11.val[0], v_src21.val[0], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n                v_dst.val[1] = vcombine_u8(resizeLinearStep(v_src10.val[1], v_src20.val[1], vlutl, vluth, vrw, vcw0, vcw1),\n                                           resizeLinearStep(v_src11.val[1], v_src21.val[1], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n                v_dst.val[2] = vcombine_u8(resizeLinearStep(v_src10.val[2], v_src20.val[2], vlutl, vluth, vrw, vcw0, vcw1),\n                                           resizeLinearStep(v_src11.val[2], v_src21.val[2], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n                v_dst.val[3] = vcombine_u8(resizeLinearStep(v_src10.val[3], v_src20.val[3], vlutl, vluth, vrw, vcw0, vcw1),\n                                           resizeLinearStep(v_src11.val[3], v_src21.val[3], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n\n                vst4q_u8(drow + (col << 2), v_dst);\n            }\n        }\n    }\n\n    for ( ; col + 8 <= dsize.width; col += 8)\n    {\ndownsample_bilinear_8uc1_col_loop8:\n        ptrdiff_t col1[8], col2[8];\n        f32 cwi[8];\n\n        for (s32 k = 0; k < 8; ++k)\n        {\n            f32 c = (col + k) * scale_x + scale_x_offset;\n            col1[k] = floorf(c);\n            col2[k] = col1[k] + 1;\n\n            cwi[k] = col2[k] - c;\n\n            if (col1[k] < 0)\n                col1[k] = 0;\n            if (col2[k] >= (ptrdiff_t)ssize.width)\n                col2[k] = ssize.width - 1;\n        }\n\n        ptrdiff_t x = std::min<ptrdiff_t>(col1[0], ssize.width - 16);\n        u8 lutl[8], luth[8];\n        for (s32 k = 0; k < 8; ++k)\n        {\n            lutl[k] = (u8)(col1[k] - x);\n            luth[k] = (u8)(col2[k] - x);\n        }\n\n        uint8x8_t vlutl = vld1_u8(lutl);\n        uint8x8_t vluth = vld1_u8(luth);\n        float32x4_t vcw0 = vld1q_f32(cwi);\n        float32x4_t vcw1 = vld1q_f32(cwi + 4);\n\n        if (channels == 1)\n        {\n            for (size_t row = 0; row < dsize.height; ++row)\n            {\n                float32x4_t vrw = vdupq_n_f32(coeff[row]);\n\n                const u8 * srow0 = internal::getRowPtr(srcBase, srcStride, buf[0 * dsize.height + row]);\n                const u8 * srow1 = internal::getRowPtr(srcBase, srcStride, buf[1 * dsize.height + row]);\n                u8 * drow = internal::getRowPtr(dstBase, dstStride, row);\n\n                internal::prefetch(srow0 + x + 2 * srcStride);\n                internal::prefetch(srow1 + x + 2 * srcStride);\n\n                uint8x8_t vres = resizeLinearStep(vld1q_u8(srow0 + x), vld1q_u8(srow1 + x),\n                                                  vlutl, vluth,\n                                                  vrw, vcw0, vcw1);\n                vst1_u8(drow + col, vres);\n            }\n        }\n        else if (channels == 3)\n        {\n            for (size_t row = 0; row < dsize.height; ++row)\n            {\n                float32x4_t vrw = vdupq_n_f32(coeff[row]);\n\n                const u8 * srow0 = internal::getRowPtr(srcBase, srcStride, buf[0 * dsize.height + row]);\n                const u8 * srow1 = internal::getRowPtr(srcBase, srcStride, buf[1 * dsize.height + row]);\n                u8 * drow = internal::getRowPtr(dstBase, dstStride, row);\n\n                internal::prefetch(srow0 + x + 2 * srcStride);\n                internal::prefetch(srow1 + x + 2 * srcStride);\n\n                uint8x16x3_t v_src1 = vld3q_u8(srow0 + (x * 3));\n                uint8x16x3_t v_src2 = vld3q_u8(srow1 + (x * 3));\n\n                uint8x8x3_t v_dst;\n\n                v_dst.val[0] = resizeLinearStep(v_src1.val[0], v_src2.val[0], vlutl, vluth, vrw, vcw0, vcw1);\n                v_dst.val[1] = resizeLinearStep(v_src1.val[1], v_src2.val[1], vlutl, vluth, vrw, vcw0, vcw1);\n                v_dst.val[2] = resizeLinearStep(v_src1.val[2], v_src2.val[2], vlutl, vluth, vrw, vcw0, vcw1);\n\n                vst3_u8(drow + (col * 3), v_dst);\n            }\n        }\n        else if (channels == 4)\n        {\n            for (size_t row = 0; row < dsize.height; ++row)\n            {\n                float32x4_t vrw = vdupq_n_f32(coeff[row]);\n\n                const u8 * srow0 = internal::getRowPtr(srcBase, srcStride, buf[0 * dsize.height + row]);\n                const u8 * srow1 = internal::getRowPtr(srcBase, srcStride, buf[1 * dsize.height + row]);\n                u8 * drow = internal::getRowPtr(dstBase, dstStride, row);\n\n                internal::prefetch(srow0 + x + 2 * srcStride);\n                internal::prefetch(srow1 + x + 2 * srcStride);\n\n                uint8x16x4_t v_src1 = vld4q_u8(srow0 + (x << 2));\n                uint8x16x4_t v_src2 = vld4q_u8(srow1 + (x << 2));\n\n                uint8x8x4_t v_dst;\n\n                v_dst.val[0] = resizeLinearStep(v_src1.val[0], v_src2.val[0], vlutl, vluth, vrw, vcw0, vcw1);\n                v_dst.val[1] = resizeLinearStep(v_src1.val[1], v_src2.val[1], vlutl, vluth, vrw, vcw0, vcw1);\n                v_dst.val[2] = resizeLinearStep(v_src1.val[2], v_src2.val[2], vlutl, vluth, vrw, vcw0, vcw1);\n                v_dst.val[3] = resizeLinearStep(v_src1.val[3], v_src2.val[3], vlutl, vluth, vrw, vcw0, vcw1);\n\n                vst4_u8(drow + (col << 2), v_dst);\n            }\n        }\n    }\n\n    if (col < dsize.width)\n    {\n        col = dsize.width - 8;\n        goto downsample_bilinear_8uc1_col_loop8;\n    }\n\n#else\n    (void)ssize;\n    (void)dsize;\n    (void)srcBase;\n    (void)srcStride;\n    (void)dstBase;\n    (void)dstStride;\n    (void)wr;\n    (void)hr;\n    (void)channels;\n#endif\n}\n\n} \/\/ namespace CAROTENE_NS\n","avg_line_length":44.8261861314,"max_line_length":146,"alphanum_fraction":0.5156474216,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5066,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":27.0,"content":"\/\/ Copyright (c) 2019 Graphcore Ltd. All rights reserved.\n\n#include <popart\/op.hpp>\n#include <popart\/shapeinference.hpp>\n#include <popart\/names.hpp>\n#include <popart\/opmanager.hpp>\n#include <popart\/region.hpp>\n#include <popart\/popx\/opx.hpp>\n#include <popart\/popx\/opxmanager.hpp>\n#include <popart\/popx\/devicex.hpp>\n\n#include <popops\/ElementWise.hpp>\n#include <popops\/Cast.hpp>\n#include <popops\/Rearrange.hpp>\n\n#include <poputil\/TileMapping.hpp>\n\n#include <random>\n\nusing namespace popart;\nusing namespace popart::popx;\nusing namespace popops::expr;\n    \nnamespace CustomOperators {\n    const popart::OperatorIdentifier AttentionMask = {\"ai.graphcore\", \"AttentionMask\", 1};\n} \/\/ namespace CustomOperators\n\n\/\/ An InplaceIdentityOp that doesn't return any grad ops. This allows you to disconnect the flow of gradients when creating the backwards pass\nclass AttentionMaskOp : public popart::Op {\npublic:\n\n    poplar::Type dataType;\n\n    AttentionMaskOp(const popart::OperatorIdentifier &_opid, \n                    const Op::Settings &settings_,\n                    poplar::Type &dataTypeIn)\n        : Op(_opid, settings_), dataType(dataTypeIn) {}\n\n    void setup() final { \n    \/\/ input shape [B, S]\n    Shape inShape = inInfo(0).shape();\n    Shape refShape = inInfo(1).shape();\n\n    \/\/ output shape [B, 1, S, S] \n    Shape outShape = {inShape.at(0), 1, inShape.at(1), inShape.at(1)};\n\n    if (dataType == poplar::HALF)\n        outInfo(0) = {\"FLOAT16\", outShape};\n    else\n        outInfo(0) = {\"FLOAT32\", outShape};\n    }\n\n    std::unique_ptr<Op> clone() const final {\n    return std::make_unique<AttentionMaskOp>(*this);\n    }\n\n    float getSubgraphValue() const final { return getLowSubgraphValue(); }\n};\n\nstatic popart::OpDefinition attentionMaskOpDef({});\n\nstatic popart::OpCreator<AttentionMaskOp> attentionMaskOpCreator(\n    popart::OpDefinitions({{CustomOperators::AttentionMask, attentionMaskOpDef}}),\n    [](const popart::OpCreatorInfo &oci) -> std::unique_ptr<popart::Op> {\n        std::string type = oci.attributes.getAttribute<Attributes::String>(\"dataType\");\n        poplar::Type dataType  = (type == \"FLOAT\") ? poplar::FLOAT : poplar::HALF;\n\n        return std::unique_ptr<AttentionMaskOp>(\n            new AttentionMaskOp(oci.opid, oci.settings, dataType));\n    },\n    true);\n\nclass AttentionMaskOpX : public popart::popx::Opx\n{\npublic:\n    AttentionMaskOpX(popart::Op *op, popart::popx::Devicex *devicex) : popart::popx::Opx(op, devicex) {\n    verifyOp<AttentionMaskOp>(op, CustomOperators::AttentionMask);\n    }\n\n    popart::popx::InputCreatorType getInputCreatorType(popart::InIndex) const {\n    return popart::popx::InputCreatorType::CanUnwind;\n    }\n\n    poplar::Tensor unwindTensorLayout(poplar::Tensor tensor, popart::InIndex, popart::OutIndex) const {\n    return tensor;\n    }\n\n    popart::view::RegMap unwindRegion(popart::InIndex, popart::OutIndex) const {\n    return [this](const popart::view::Region &r) {\n        return popart::view::Regions(1, r);\n    };\n    }\n\n    void grow(poplar::program::Sequence &prog) const final {\n    AttentionMaskOp &myOp = getOp<AttentionMaskOp>();\n\n    poplar::Type dataType = myOp.dataType;\n    poplar::Graph &graph = Opx::graph();\n\n    \/\/ input tensor shape [B, S]\n    poplar::Tensor seqIndex  = getInTensor(0);\n    std::size_t batchSize = seqIndex.dim(0);\n    std::size_t seqLength = seqIndex.dim(1);\n    seqIndex = seqIndex.reshape({batchSize, seqLength, 1});\n    seqIndex = popops::cast(graph, seqIndex, dataType, prog, \"input_mask_f\");\n    poplar::Tensor attentionMatrix  = getInTensor(1);\n\n    const auto dimOrdering = poputil::detectDimGroupings(graph, attentionMatrix);\n    bool swapOrder = !dimOrdering.empty() && dimOrdering.front().first == 2;\n    auto seqMask = swapOrder ?\n            popops::sub(graph, seqIndex.dimShuffle({0, 2, 1}), seqIndex, prog, \"maskVal\").dimShuffle({0, 2, 1}):\n            popops::sub(graph, seqIndex, seqIndex.dimShuffle({0, 2, 1}), prog, \"maskVal\");\n    popops::absInPlace(graph, seqMask, prog);\n    popops::tanhInPlace(graph, seqMask, prog);\n\n    \/\/ Create constant tensor;\n    std::mt19937 randomEngine;\n    unsigned totalTile = graph.getTarget().getTilesPerIPU();\n    std::uniform_int_distribution<> distrib(0, totalTile - 1);\n    int tileForConst = distrib(randomEngine);\n    poplar::Tensor minValue = graph.addConstant(dataType, {}, -10000.0);\n    graph.setTileMapping(minValue, tileForConst);\n\n    \/\/ Create log mask\n    popops::mulInPlace(graph, seqMask, minValue, prog);\n    seqMask = seqMask.reshape({batchSize, 1, seqLength, seqLength});\n    setOutTensor(0, seqMask);\n    }\n};\n\nstatic popart::popx::OpxCreator<AttentionMaskOpX>\n    attentionMaskOpxCreator(CustomOperators::AttentionMask);\n\nstatic popart::RegisterShapeInferenceFunction AttentionMaskShapeInfer(\n    CustomOperators::AttentionMask,\n            [](ShapeInferenceContext &ctx) {\n            auto B = ctx.inInfo(1).shape().at(0);\n            auto S = ctx.inInfo(1).shape().at(3);\n            auto dtype = ctx.inInfo(1).data_type();\n            ctx.outInfo(0) = {dtype, Shape({B, 1, S, S})};\n    });","avg_line_length":35.9290780142,"max_line_length":142,"alphanum_fraction":0.6798262929,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6717,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":null,"content":"#include <chrono>\n#include <ctime>\n#include <exception>\n#include <iostream>\n#include <sstream>\n#include <thread>\n\n#include \"Client_controller.h\"\n#include \"Base_state.h\"\n#include \"Connecting_state.h\"\n#include \"Reading_state.h\"\n#include \"Sending_state.h\"\n\n#include \"..\/RADS_common\/Sensor.h\"\n\nusing std::chrono::seconds;\nusing std::cout;\nusing std::endl;\nusing std::logic_error;\nusing std::ostringstream;\nusing std::this_thread::sleep_for;\nusing std::time;\n\nusing Readings::Sensor;\n\nnamespace RADS_client {\n    Client_controller::Client_controller(string id, vector<Sensor_reader*> sensor_readers,\n            int transmission_frequency, int data_hourly_limit, string ip, int port\n    ) {\n        \/\/ Add sensor readers\n        for (Sensor_reader * reader : sensor_readers) {\n            this->sensor_readers.push_back(reader);\n        }\n        \n        \/\/ Set transmission frequency\n        this->transmission_frequency = transmission_frequency;\n        \n        \/\/ Set ID\n        this->id = id;\n\n        \/\/ Set data limitations\n        this->data_hourly_limit = data_hourly_limit;\n        this->data_period_start_datetime = time(NULL);\n        this->data_sent_bytes = 0;\n\n        \/\/ Set IP and port\n        this->ip = ip;\n        this->port = port;\n          \n        cout << \"Client controller: Using IP Address \" << this->ip << endl;\n        cout << \"Client controller: Using port \" << this->port << endl;\n        cout << \"Client controller: Transmision frequency set to \" << this->transmission_frequency << \" seconds.\" << endl;\n        cout << \"Client Controller: Sender ID set to \" << this->id << endl;\n        cout << \"Client Controller: Hourly data limitation set to \" << this->data_hourly_limit << \" bytes\" << endl << endl;\n    }\n\n    Client_controller::~Client_controller() {}\n\n    void Client_controller::perform() {\n        State::Base* state = NULL;\n\n        switch (this->current_state) {\n        case READING:\n            state = new State::Reading();\n            break;\n        case CONNECTING:\n            state = new State::Connecting();\n            break;\n        case SENDING:\n            state = new State::Sending();\n            break;\n        default:\n            throw logic_error(\"Client controller is in not-existent state\");\n        }\n\n        state->set_client_controller(this);\n        state->perform();\n\n        \/\/ Delete pointer to the state after it's done doing its job.\n        delete state;\n    }\n\n    void Client_controller::start_communicating() {\n        \/\/ Create new network client\n        delete this->network_client;\n        this->network_client = new Network_client(this->ip, this->port);\n\n        \/\/ Wait for transmission.\n        long int next_transmission = this->transmission_frequency + this->last_transmission;\n\n        if (next_transmission > time(NULL)) {\n            long int waiting_time = next_transmission - time(NULL);\n\n            cout << \"Client controller: Waiting \" << waiting_time << \" seconds for next transmission\" << endl;\n            sleep_for(seconds(waiting_time));\n        }\n\n        \/\/ Check data limits.\n        int result = 0;\n        int tries = 0;\n        cout << \"Client controller: So far sent \" << this->data_sent_bytes << \" bytes in the current period.\" << endl;\n\n        do {\n            result = this->check_data_limitation();\n\n            if (tries > 0 && result != 0) {\n                cout << \"Client controller: Waiting until can send more data due to the hourly limitation (\" << tries << \" tries).\" << endl;\n                sleep_for(seconds(30));\n            }\n\n            tries++;\n        } while (result != 0);\n\n        \/\/ Set state to connecting and then sending.\n        this->set_state(CONNECTING);\n        this->perform();\n\n        this->set_state(SENDING);\n        this->perform();\n\n        \/\/ Set last transmission time to now.\n        this->last_transmission = time(NULL);\n    }\n\n    void Client_controller::clean_sensor_readers() {\n        for (Sensor_reader *sensor_reader : this->sensor_readers) {\n            sensor_reader->clear_readings();\n        }\n\n        cout << \"Client controller: Cleared readings from the memory\" << endl;\n    }\n\n    void Client_controller::start_reading() {\n        this->set_state(READING);\n        this->perform();\n    }\n\n    Network_client* Client_controller::get_network_client() {\n        return this->network_client;\n    }\n\n    vector<Sensor_reader*> Client_controller::get_sensor_readers() {\n        return this->sensor_readers;\n    }\n\n    void Client_controller::add_bytes_sent(int bytes) {\n        this->data_sent_bytes += bytes;\n    }\n\n    Reading_data* Client_controller::get_reading_data() {\n        \/\/ Construct vector of readings from all the sensors mixed all together.\n        vector<Sensor*> data;\n\n        \/\/ Variables for the first and last reading time.\n        time_t min_time = 0;\n        time_t max_time = 0;\n\n        \/\/ Loop through all the sensor readers.\n        for (Sensor_reader *sensor_reader : this->sensor_readers) {\n            \n            \/\/ Loop through all the readings for the particular sensor reader.\n            for (Sensor *sensor : sensor_reader->get_readings()) {\n\n                \/\/ Find out the minimum time of readings\n                if (min_time == 0 || sensor->get_datetime() < min_time) {\n                    min_time = sensor->get_datetime();\n                }\n\n                \/\/ Find out the maximum time of readings\n                if (sensor->get_datetime() > max_time) {\n                    max_time = sensor->get_datetime();\n                }\n\n                \/\/ Add data from the sensor to the vector containing all the types of readings.\n                data.push_back(sensor);\n            }\n        }\n\n        \/\/ Construct new Reading_data container with the current readings.\n        return new Reading_data(min_time, max_time, data);\n    }\n\n    void Client_controller::set_state(Client_controller_state state) {\n        this->current_state = state;\n    }\n\n    int Client_controller::check_data_limitation() {\n        \/\/ Calculate time when the data limitations will be resetted.\n        time_t reset_time = this->data_period_start_datetime + 60 * 60;\n\n        \/\/ If it's time for data limit reset...\n        if (time(NULL) >= reset_time) {\n            cout << \"Client controller: Reset data throotling\" << endl;\n            this->data_period_start_datetime = time(NULL);\n            this->data_sent_bytes = 0;\n            return 0;\n        }\n\n        \/\/ Return 1 if we are over limit.\n        if (this->data_sent_bytes >= this->data_hourly_limit) {\n            return 1;\n        }\n\n        \/\/ We are not over the limit so return 0.\n        return 0;\n    }\n\n    string Client_controller::get_id() {\n        return this->id;\n    }\n}\n","avg_line_length":31.6839622642,"max_line_length":140,"alphanum_fraction":0.5966949531,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2454,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":16.0,"content":"\/*\r\nSeComLib\r\nCopyright 2012-2013 TU Delft, Information Security & Privacy Lab (http:\/\/isplab.tudelft.nl\/)\r\n\r\nContributors:\r\nInald Lagendijk (R.L.Lagendijk@TUDelft.nl)\r\nMihai Todor (todormihai@gmail.com)\r\nThijs Veugen (P.J.M.Veugen@tudelft.nl)\r\nZekeriya Erkin (z.erkin@tudelft.nl)\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n*\/\r\n\/**\r\n@file utils\/config.cpp\r\n@brief Implementation of class Config.\r\n@details Singleton class used to parse the configuration ini file\r\n@author Mihai Todor (todormihai@gmail.com)\r\n*\/\r\n\r\n#include \"config.h\"\r\n\r\nnamespace SeComLib {\r\nnamespace Utils {\r\n\t\/\/\/ The default configuration file is located in the same directory as the application (defaults to config.xml)\r\n\tstd::string Config::configFile (\"config.xml\");\r\n\r\n\t\/**\r\n\tInitialize the name of the XML configuration file root node\r\n\t*\/\r\n\tconst std::string Config::xmlRootElementName (\"config\");\r\n\r\n\t\/**\r\n\tCreates a static instance of this class and returns it.\r\n\tThe instance will be destroyed when the application terminates (singleton pattern).\r\n\r\n\t@return The static instance of this class\r\n\t*\/\r\n\tConfig &Config::GetInstance () {\r\n\t\tstatic Config instance;\r\n\t\treturn instance;\r\n\t}\r\n\r\n\t\/**\r\n\t@param configFile the location and name of the configuration file\r\n\t*\/\r\n\tvoid Config::SetConfigFile(const std::string &configFile) {\r\n\t\tConfig::configFile = configFile;\r\n\t}\r\n\r\n\t\/**\r\n\tParses the configuration file into the boost::property_tree::ptree structure\r\n\r\n\tIf not otherwise specified, it will pick up the file called config.xml in the current directory\r\n\r\n\t@throws std::runtime_error the provided input file does not exist or can't be read\r\n\t*\/\r\n\tConfig::Config () {\r\n\t\ttry {\r\n\t\t\tboost::property_tree::xml_parser::read_xml(Config::configFile, this->propertyTree);\r\n\t\t}\r\n\t\tcatch (const boost::property_tree::xml_parser_error &exception) {\r\n\t\t\t\/\/\/ @todo throw a custom exception here\r\n\t\t\tthrow std::runtime_error(exception.what());\r\n\t\t}\r\n\t}\r\n\r\n}\/\/namespace Utils\r\n}\/\/namespace SeComLib","avg_line_length":31.4615384615,"max_line_length":113,"alphanum_fraction":0.7339038305,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3640,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":1.0,"content":"\/\/\n\/\/ Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2022\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n#include \"td\/telegram\/net\/AuthDataShared.h\"\n\n#include \"td\/telegram\/Global.h\"\n#include \"td\/telegram\/TdDb.h\"\n\n#include \"td\/utils\/algorithm.h\"\n#include \"td\/utils\/format.h\"\n#include \"td\/utils\/logging.h\"\n#include \"td\/utils\/port\/RwMutex.h\"\n#include \"td\/utils\/SliceBuilder.h\"\n#include \"td\/utils\/tl_helpers.h\"\n\nnamespace td {\n\nclass AuthDataSharedImpl final : public AuthDataShared {\n public:\n  AuthDataSharedImpl(DcId dc_id, std::shared_ptr<PublicRsaKeyShared> public_rsa_key, std::shared_ptr<Guard> guard)\n      : dc_id_(dc_id), public_rsa_key_(std::move(public_rsa_key)), guard_(std::move(guard)) {\n    log_auth_key(get_auth_key());\n  }\n\n  DcId dc_id() const final {\n    return dc_id_;\n  }\n\n  const std::shared_ptr<PublicRsaKeyShared> &public_rsa_key() final {\n    return public_rsa_key_;\n  }\n\n  mtproto::AuthKey get_auth_key() final {\n    string dc_key = G()->td_db()->get_binlog_pmc()->get(auth_key_key());\n\n    mtproto::AuthKey res;\n    if (!dc_key.empty()) {\n      unserialize(res, dc_key).ensure();\n    }\n    return res;\n  }\n\n  AuthKeyState get_auth_key_state() final {\n    return AuthDataShared::get_auth_key_state(get_auth_key());\n  }\n\n  void set_auth_key(const mtproto::AuthKey &auth_key) final {\n    G()->td_db()->get_binlog_pmc()->set(auth_key_key(), serialize(auth_key));\n    log_auth_key(auth_key);\n\n    notify();\n  }\n\n  \/\/ TODO: extract it from G()\n  void update_server_time_difference(double diff) final {\n    G()->update_server_time_difference(diff);\n  }\n\n  double get_server_time_difference() final {\n    return G()->get_server_time_difference();\n  }\n\n  void add_auth_key_listener(unique_ptr<Listener> listener) final {\n    if (listener->notify()) {\n      auto lock = rw_mutex_.lock_write();\n      auth_key_listeners_.push_back(std::move(listener));\n    }\n  }\n\n  void set_future_salts(const std::vector<mtproto::ServerSalt> &future_salts) final {\n    G()->td_db()->get_binlog_pmc()->set(future_salts_key(), serialize(future_salts));\n  }\n\n  std::vector<mtproto::ServerSalt> get_future_salts() final {\n    string future_salts = G()->td_db()->get_binlog_pmc()->get(future_salts_key());\n    std::vector<mtproto::ServerSalt> res;\n    if (!future_salts.empty()) {\n      unserialize(res, future_salts).ensure();\n    }\n    return res;\n  }\n\n private:\n  DcId dc_id_;\n  std::vector<unique_ptr<Listener>> auth_key_listeners_;\n  std::shared_ptr<PublicRsaKeyShared> public_rsa_key_;\n  std::shared_ptr<Guard> guard_;\n  RwMutex rw_mutex_;\n\n  string auth_key_key() const {\n    return PSTRING() << \"auth\" << dc_id_.get_raw_id();\n  }\n  string future_salts_key() const {\n    return PSTRING() << \"salt\" << dc_id_.get_raw_id();\n  }\n\n  void notify() {\n    auto lock = rw_mutex_.lock_read();\n\n    td::remove_if(auth_key_listeners_, [&](auto &listener) { return !listener->notify(); });\n  }\n\n  void log_auth_key(const mtproto::AuthKey &auth_key) {\n    LOG(WARNING) << dc_id_ << \" \" << tag(\"auth_key_id\", auth_key.id())\n                 << tag(\"state\", AuthDataShared::get_auth_key_state(auth_key))\n                 << tag(\"created_at\", auth_key.created_at());\n  }\n};\n\nstd::shared_ptr<AuthDataShared> AuthDataShared::create(DcId dc_id, std::shared_ptr<PublicRsaKeyShared> public_rsa_key,\n                                                       std::shared_ptr<Guard> guard) {\n  return std::make_shared<AuthDataSharedImpl>(dc_id, std::move(public_rsa_key), std::move(guard));\n}\n\n}  \/\/ namespace td\n","avg_line_length":30.5882352941,"max_line_length":118,"alphanum_fraction":0.6865384615,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1688,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/************************************************************************************\n *\n * D++, A Lightweight C++ library for Discord\n *\n * Copyright 2021 Craig Edwards and D++ contributors \n * (https:\/\/github.com\/brainboxdotcc\/DPP\/graphs\/contributors)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ************************************************************************************\/\n#include <dpp\/discord.h>\n#include <dpp\/event.h>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <dpp\/discordclient.h>\n#include <dpp\/discord.h>\n#include <dpp\/cache.h>\n#include <dpp\/stringops.h>\n#include <dpp\/nlohmann\/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace dpp { namespace events {\n\nusing namespace dpp;\n\n\/**\n * @brief Handle event\n * \n * @param client Websocket client (current shard)\n * @param j JSON data for the event\n * @param raw Raw JSON string\n *\/\nvoid invite_create::handle(discord_client* client, json &j, const std::string &raw) {\n\tif (client->creator->dispatch.invite_create) {\n\t\tjson& d = j[\"d\"];\n\t\tdpp::invite_create_t ci(client, raw);\n\t\tci.created_invite = dpp::invite().fill_from_json(&d);\n\t\tclient->creator->dispatch.invite_create(ci);\n\t}\n}\n\n}};","avg_line_length":31.2592592593,"max_line_length":86,"alphanum_fraction":0.6475118483,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1182,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/\n\/\/  Demo.cpp\n\/\/  operatorOverload\n\/\/\n\/\/  First version by Adam Lev-Ari on 29\/12\/2019.\n\/\/  Second version by Erel Segal-Halevi on 22\/04\/2020.\n\/\/\n\n#include <iostream>\n#include <complex>\n#include \"solver.hpp\"\n\nusing namespace std;\nusing solver::solve, solver::RealVariable, solver::ComplexVariable;\n\nint main() {\n    RealVariable x;\n\n    cout << solve(2*x-4 == 10) << endl;  \/\/ 7\n    cout << solve((x^2) == 16) << endl;   \/\/ 4 or -4\n    \n    try {\n        cout << solve((x^2) == -16) << endl;\n\t} catch (const exception& ex) {\n\tcout << ex.what() << endl;  \/\/ prints \"There is no real solution\"\n\t} \/\/ exception: no real solution\n\n    cout << solve((x^2) + 2*x + 4.0 == 20 + 6.0*x\/2 - x) << endl;   \/\/ 4 or -4\n    double xvalue = solve(2*x-4.0 == 10.0);   \/\/ xvalue == 7\n\n    ComplexVariable y;\n    std::complex<double> yvalue = solve(2*y-4 == 10);\n    cout << yvalue << endl;  \/\/ 7+0i  (can be in any other format)\n\n    cout << solve((y^2) == 16) << endl;   \/\/ 4+0i or -4+0i\n    cout << solve((y^2) == -16) << endl;  \/\/ 0+4i or 0-4i\n    cout << solve((y^2) + 2*y + 4 == 20 + 6*y\/2 - y) << endl;   \/\/ 4+0i or -4+0i\n    cout << solve(y+5i == 2*y+3i) << endl;   \/\/ 0+2i\n\n    return 0;\n}\n","avg_line_length":28.1428571429,"max_line_length":80,"alphanum_fraction":0.5397631134,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":990,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":16.0,"content":"\n#include <iostream>\n#include \"foo_client_interface_impl.hpp\"\n\nnamespace testsuite {\n\nstd::shared_ptr<FooClientInterface> FooClientInterface::create() {\n    return std::make_shared<FooClientInterfaceImpl>();\n}\n\nvoid FooClientInterfaceImpl::set_record(const FooClientReturnedRecord & rec) {\n    m_record = rec;\n}\n\nFooClientReturnedRecord FooClientInterfaceImpl::get_record() {\n    return m_record;\n}\n\nvoid FooClientInterfaceImpl::set_extensible_record(const FooExtensibleRecord & rec) {\n    m_ext_record = rec;\n}\n\nFooExtensibleRecord FooClientInterfaceImpl::get_extensible_record() {\n    return m_ext_record;\n}\n\nint32_t FooClientInterfaceImpl::get_extensible_record_number2() {\n    return m_ext_record.number2;\n}\n\nstd::string FooClientInterfaceImpl::get_extensible_record_string2() {\n    return m_ext_record.string2;\n}\n\nFooClientInterfaceImpl::FooClientInterfaceImpl(): m_record(FooClientReturnedRecord(5,\"hi\", FooSomeOtherRecord(1,2))),\n m_ext_record(6, \"bye\"){};\n\n} \/\/ namespace testsuite\n","avg_line_length":25.3846153846,"max_line_length":117,"alphanum_fraction":0.7888888889,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":99618,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"src\/gpu\/v1\/SurfaceDrawContext_v1.h\"\n\n#include \"include\/core\/SkDrawable.h\"\n#include \"include\/core\/SkVertices.h\"\n#include \"include\/gpu\/GrBackendSemaphore.h\"\n#include \"include\/gpu\/GrDirectContext.h\"\n#include \"include\/gpu\/GrRecordingContext.h\"\n#include \"include\/private\/GrImageContext.h\"\n#include \"include\/private\/SkShadowFlags.h\"\n#include \"include\/private\/SkVx.h\"\n#include \"include\/utils\/SkShadowUtils.h\"\n#include \"src\/core\/SkAutoPixmapStorage.h\"\n#include \"src\/core\/SkConvertPixels.h\"\n#include \"src\/core\/SkCustomMeshPriv.h\"\n#include \"src\/core\/SkDrawProcs.h\"\n#include \"src\/core\/SkDrawShadowInfo.h\"\n#include \"src\/core\/SkGlyphRunPainter.h\"\n#include \"src\/core\/SkLatticeIter.h\"\n#include \"src\/core\/SkMatrixPriv.h\"\n#include \"src\/core\/SkMatrixProvider.h\"\n#include \"src\/core\/SkRRectPriv.h\"\n#include \"src\/gpu\/GrAppliedClip.h\"\n#include \"src\/gpu\/GrAttachment.h\"\n#include \"src\/gpu\/GrCaps.h\"\n#include \"src\/gpu\/GrClip.h\"\n#include \"src\/gpu\/GrColor.h\"\n#include \"src\/gpu\/GrColorSpaceXform.h\"\n#include \"src\/gpu\/GrDataUtils.h\"\n#include \"src\/gpu\/GrDirectContextPriv.h\"\n#include \"src\/gpu\/GrDrawingManager.h\"\n#include \"src\/gpu\/GrGpuResourcePriv.h\"\n#include \"src\/gpu\/GrImageContextPriv.h\"\n#include \"src\/gpu\/GrImageInfo.h\"\n#include \"src\/gpu\/GrMemoryPool.h\"\n#include \"src\/gpu\/GrProxyProvider.h\"\n#include \"src\/gpu\/GrRenderTarget.h\"\n#include \"src\/gpu\/GrResourceProvider.h\"\n#include \"src\/gpu\/GrSemaphore.h\"\n#include \"src\/gpu\/GrStencilSettings.h\"\n#include \"src\/gpu\/GrStyle.h\"\n#include \"src\/gpu\/GrTracing.h\"\n#include \"src\/gpu\/SkGr.h\"\n#include \"src\/gpu\/effects\/GrBicubicEffect.h\"\n#include \"src\/gpu\/effects\/GrBlendFragmentProcessor.h\"\n#include \"src\/gpu\/effects\/GrDisableColorXP.h\"\n#include \"src\/gpu\/effects\/GrRRectEffect.h\"\n#include \"src\/gpu\/effects\/GrTextureEffect.h\"\n#include \"src\/gpu\/geometry\/GrQuad.h\"\n#include \"src\/gpu\/geometry\/GrQuadUtils.h\"\n#include \"src\/gpu\/geometry\/GrStyledShape.h\"\n#include \"src\/gpu\/ops\/ClearOp.h\"\n#include \"src\/gpu\/ops\/DrawAtlasOp.h\"\n#include \"src\/gpu\/ops\/DrawCustomMeshOp.h\"\n#include \"src\/gpu\/ops\/DrawableOp.h\"\n#include \"src\/gpu\/ops\/FillRRectOp.h\"\n#include \"src\/gpu\/ops\/FillRectOp.h\"\n#include \"src\/gpu\/ops\/GrDrawOp.h\"\n#include \"src\/gpu\/ops\/GrOp.h\"\n#include \"src\/gpu\/ops\/GrOvalOpFactory.h\"\n#include \"src\/gpu\/ops\/LatticeOp.h\"\n#include \"src\/gpu\/ops\/RegionOp.h\"\n#include \"src\/gpu\/ops\/ShadowRRectOp.h\"\n#include \"src\/gpu\/ops\/StrokeRectOp.h\"\n#include \"src\/gpu\/ops\/TextureOp.h\"\n#include \"src\/gpu\/text\/GrSDFTControl.h\"\n#include \"src\/gpu\/text\/GrTextBlobRedrawCoordinator.h\"\n#include \"src\/gpu\/v1\/PathRenderer.h\"\n\n#define ASSERT_OWNED_RESOURCE(R) SkASSERT(!(R) || (R)->getContext() == this->drawingManager()->getContext())\n#define ASSERT_SINGLE_OWNER        SKGPU_ASSERT_SINGLE_OWNER(this->singleOwner())\n#define RETURN_IF_ABANDONED        if (fContext->abandoned()) { return; }\n#define RETURN_FALSE_IF_ABANDONED  if (fContext->abandoned()) { return false; }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace {\n\nvoid op_bounds(SkRect* bounds, const GrOp* op) {\n    *bounds = op->bounds();\n    if (op->hasZeroArea()) {\n        if (op->hasAABloat()) {\n            bounds->outset(0.5f, 0.5f);\n        } else {\n            \/\/ We don't know which way the particular GPU will snap lines or points at integer\n            \/\/ coords. So we ensure that the bounds is large enough for either snap.\n            SkRect before = *bounds;\n            bounds->roundOut(bounds);\n            if (bounds->fLeft == before.fLeft) {\n                bounds->fLeft -= 1;\n            }\n            if (bounds->fTop == before.fTop) {\n                bounds->fTop -= 1;\n            }\n            if (bounds->fRight == before.fRight) {\n                bounds->fRight += 1;\n            }\n            if (bounds->fBottom == before.fBottom) {\n                bounds->fBottom += 1;\n            }\n        }\n    }\n}\n\n} \/\/ anonymous namespace\n\nnamespace skgpu::v1 {\n\nusing DoSimplify = GrStyledShape::DoSimplify;\n\nclass AutoCheckFlush {\npublic:\n    AutoCheckFlush(GrDrawingManager* drawingManager) : fDrawingManager(drawingManager) {\n        SkASSERT(fDrawingManager);\n    }\n    ~AutoCheckFlush() { fDrawingManager->flushIfNecessary(); }\n\nprivate:\n    GrDrawingManager* fDrawingManager;\n};\n\nstd::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::Make(GrRecordingContext* rContext,\n                                                             GrColorType colorType,\n                                                             sk_sp<GrSurfaceProxy> proxy,\n                                                             sk_sp<SkColorSpace> colorSpace,\n                                                             GrSurfaceOrigin origin,\n                                                             const SkSurfaceProps& surfaceProps,\n                                                             bool flushTimeOpsTask) {\n    if (!rContext || !proxy || colorType == GrColorType::kUnknown) {\n        return nullptr;\n    }\n\n    const GrBackendFormat& format = proxy->backendFormat();\n    skgpu::Swizzle readSwizzle = rContext->priv().caps()->getReadSwizzle(format, colorType);\n    skgpu::Swizzle writeSwizzle = rContext->priv().caps()->getWriteSwizzle(format, colorType);\n\n    GrSurfaceProxyView readView (          proxy,  origin, readSwizzle);\n    GrSurfaceProxyView writeView(std::move(proxy), origin, writeSwizzle);\n\n    return std::make_unique<SurfaceDrawContext>(rContext,\n                                                std::move(readView),\n                                                std::move(writeView),\n                                                colorType,\n                                                std::move(colorSpace),\n                                                surfaceProps,\n                                                flushTimeOpsTask);\n}\n\nstd::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::Make(\n        GrRecordingContext* rContext,\n        sk_sp<SkColorSpace> colorSpace,\n        SkBackingFit fit,\n        SkISize dimensions,\n        const GrBackendFormat& format,\n        int sampleCnt,\n        GrMipmapped mipMapped,\n        GrProtected isProtected,\n        skgpu::Swizzle readSwizzle,\n        skgpu::Swizzle writeSwizzle,\n        GrSurfaceOrigin origin,\n        SkBudgeted budgeted,\n        const SkSurfaceProps& surfaceProps) {\n    \/\/ It is probably not necessary to check if the context is abandoned here since uses of the\n    \/\/ SurfaceDrawContext which need the context will mostly likely fail later on without an\n    \/\/ issue. However having this hear adds some reassurance in case there is a path doesn't handle\n    \/\/ an abandoned context correctly. It also lets us early out of some extra work.\n    if (rContext->abandoned()) {\n        return nullptr;\n    }\n\n    sk_sp<GrTextureProxy> proxy = rContext->priv().proxyProvider()->createProxy(\n            format,\n            dimensions,\n            GrRenderable::kYes,\n            sampleCnt,\n            mipMapped,\n            fit,\n            budgeted,\n            isProtected);\n    if (!proxy) {\n        return nullptr;\n    }\n\n    GrSurfaceProxyView readView (           proxy, origin,  readSwizzle);\n    GrSurfaceProxyView writeView(std::move(proxy), origin, writeSwizzle);\n\n    auto sdc = std::make_unique<SurfaceDrawContext>(rContext,\n                                                    std::move(readView),\n                                                    std::move(writeView),\n                                                    GrColorType::kUnknown,\n                                                    std::move(colorSpace),\n                                                    surfaceProps);\n    sdc->discard();\n    return sdc;\n}\n\nstd::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::Make(\n        GrRecordingContext* rContext,\n        GrColorType colorType,\n        sk_sp<SkColorSpace> colorSpace,\n        SkBackingFit fit,\n        SkISize dimensions,\n        const SkSurfaceProps& surfaceProps,\n        int sampleCnt,\n        GrMipmapped mipMapped,\n        GrProtected isProtected,\n        GrSurfaceOrigin origin,\n        SkBudgeted budgeted) {\n    if (!rContext) {\n        return nullptr;\n    }\n\n    auto format = rContext->priv().caps()->getDefaultBackendFormat(colorType, GrRenderable::kYes);\n    if (!format.isValid()) {\n        return nullptr;\n    }\n    sk_sp<GrTextureProxy> proxy = rContext->priv().proxyProvider()->createProxy(format,\n                                                                                dimensions,\n                                                                                GrRenderable::kYes,\n                                                                                sampleCnt,\n                                                                                mipMapped,\n                                                                                fit,\n                                                                                budgeted,\n                                                                                isProtected);\n    if (!proxy) {\n        return nullptr;\n    }\n\n    return SurfaceDrawContext::Make(rContext,\n                                    colorType,\n                                    std::move(proxy),\n                                    std::move(colorSpace),\n                                    origin,\n                                    surfaceProps);\n}\n\nstd::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::MakeWithFallback(\n        GrRecordingContext* rContext,\n        GrColorType colorType,\n        sk_sp<SkColorSpace> colorSpace,\n        SkBackingFit fit,\n        SkISize dimensions,\n        const SkSurfaceProps& surfaceProps,\n        int sampleCnt,\n        GrMipmapped mipMapped,\n        GrProtected isProtected,\n        GrSurfaceOrigin origin,\n        SkBudgeted budgeted) {\n    const GrCaps* caps = rContext->priv().caps();\n    auto [ct, _] = caps->getFallbackColorTypeAndFormat(colorType, sampleCnt);\n    if (ct == GrColorType::kUnknown) {\n        return nullptr;\n    }\n    return SurfaceDrawContext::Make(rContext, ct, colorSpace, fit, dimensions, surfaceProps,\n                                    sampleCnt, mipMapped, isProtected, origin, budgeted);\n}\n\nstd::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::MakeFromBackendTexture(\n        GrRecordingContext* rContext,\n        GrColorType colorType,\n        sk_sp<SkColorSpace> colorSpace,\n        const GrBackendTexture& tex,\n        int sampleCnt,\n        GrSurfaceOrigin origin,\n        const SkSurfaceProps& surfaceProps,\n        sk_sp<skgpu::RefCntedCallback> releaseHelper) {\n    SkASSERT(sampleCnt > 0);\n    sk_sp<GrTextureProxy> proxy(rContext->priv().proxyProvider()->wrapRenderableBackendTexture(\n            tex, sampleCnt, kBorrow_GrWrapOwnership, GrWrapCacheable::kNo,\n            std::move(releaseHelper)));\n    if (!proxy) {\n        return nullptr;\n    }\n\n    return SurfaceDrawContext::Make(rContext, colorType, std::move(proxy), std::move(colorSpace),\n                                    origin, surfaceProps);\n}\n\n\/\/ In MDB mode the reffing of the 'getLastOpsTask' call's result allows in-progress\n\/\/ OpsTask to be picked up and added to by SurfaceDrawContexts lower in the call\n\/\/ stack. When this occurs with a closed OpsTask, a new one will be allocated\n\/\/ when the surfaceDrawContext attempts to use it (via getOpsTask).\nSurfaceDrawContext::SurfaceDrawContext(GrRecordingContext* rContext,\n                                       GrSurfaceProxyView readView,\n                                       GrSurfaceProxyView writeView,\n                                       GrColorType colorType,\n                                       sk_sp<SkColorSpace> colorSpace,\n                                       const SkSurfaceProps& surfaceProps,\n                                       bool flushTimeOpsTask)\n        : SurfaceFillContext(rContext,\n                             std::move(readView),\n                             std::move(writeView),\n                             {colorType, kPremul_SkAlphaType, std::move(colorSpace)},\n                             flushTimeOpsTask)\n        , fSurfaceProps(surfaceProps)\n        , fCanUseDynamicMSAA(\n                (fSurfaceProps.flags() & SkSurfaceProps::kDynamicMSAA_Flag) &&\n                rContext->priv().caps()->supportsDynamicMSAA(this->asRenderTargetProxy()))\n        , fGlyphPainter(*this) {\n    SkDEBUGCODE(this->validate();)\n}\n\nSurfaceDrawContext::~SurfaceDrawContext() {\n    ASSERT_SINGLE_OWNER\n}\n\nvoid SurfaceDrawContext::willReplaceOpsTask(OpsTask* prevTask, OpsTask* nextTask) {\n    if (prevTask && fNeedsStencil) {\n        \/\/ Store the stencil values in memory upon completion of fOpsTask.\n        prevTask->setMustPreserveStencil();\n        \/\/ Reload the stencil buffer content at the beginning of newOpsTask.\n        \/\/ FIXME: Could the topo sort insert a task between these two that modifies the stencil\n        \/\/ values?\n        nextTask->setInitialStencilContent(OpsTask::StencilContent::kPreserved);\n    }\n#if GR_GPU_STATS && GR_TEST_UTILS\n    if (fCanUseDynamicMSAA) {\n        fContext->priv().dmsaaStats().fNumRenderPasses++;\n    }\n#endif\n}\n\nvoid SurfaceDrawContext::drawGlyphRunListNoCache(SkCanvas* canvas,\n                                                 const GrClip* clip,\n                                                 const SkMatrixProvider& viewMatrix,\n                                                 const SkGlyphRunList& glyphRunList,\n                                                 const SkPaint& paint) {\n    GrSDFTControl control =\n            fContext->priv().getSDFTControl(fSurfaceProps.isUseDeviceIndependentFonts());\n    const SkPoint drawOrigin = glyphRunList.origin();\n    SkMatrix drawMatrix = viewMatrix.localToDevice();\n    drawMatrix.preTranslate(drawOrigin.x(), drawOrigin.y());\n    GrSubRunAllocator* const alloc = this->subRunAlloc();\n\n    GrSubRunNoCachePainter painter{canvas, this, alloc, clip, viewMatrix, glyphRunList, paint};\n    for (auto& glyphRun : glyphRunList) {\n        \/\/ Make and add the text ops.\n        fGlyphPainter.processGlyphRun(&painter,\n                                      glyphRun,\n                                      drawMatrix,\n                                      paint,\n                                      control);\n    }\n}\n\n\/\/ choose to use the GrTextBlob cache or not.\nbool gGrDrawTextNoCache = false;\nvoid SurfaceDrawContext::drawGlyphRunList(SkCanvas* canvas,\n                                          const GrClip* clip,\n                                          const SkMatrixProvider& viewMatrix,\n                                          const SkGlyphRunList& glyphRunList,\n                                          const SkPaint& paint) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawGlyphRunList\", fContext);\n\n    \/\/ Drawing text can cause us to do inline uploads. This is not supported for wrapped vulkan\n    \/\/ secondary command buffers because it would require stopping and starting a render pass which\n    \/\/ we don't have access to.\n    if (this->wrapsVkSecondaryCB()) {\n        return;\n    }\n\n    if (gGrDrawTextNoCache || glyphRunList.blob() == nullptr) {\n        \/\/ If the glyphRunList does not have an associated text blob, then it was created by one of\n        \/\/ the direct draw APIs (drawGlyphs, etc.). There is no need to create a GrTextBlob just\n        \/\/ build the sub run directly and place it in the op.\n        this->drawGlyphRunListNoCache(canvas, clip, viewMatrix, glyphRunList, paint);\n    } else {\n        GrTextBlobRedrawCoordinator* textBlobCache = fContext->priv().getTextBlobCache();\n        textBlobCache->drawGlyphRunList(canvas, clip, viewMatrix, glyphRunList, paint, this);\n    }\n}\n\nvoid SurfaceDrawContext::drawPaint(const GrClip* clip,\n                                   GrPaint&& paint,\n                                   const SkMatrix& viewMatrix) {\n    \/\/ Start with the render target, since that is the maximum content we could possibly fill.\n    \/\/ drawFilledQuad() will automatically restrict it to clip bounds for us if possible.\n    if (!paint.numTotalFragmentProcessors()) {\n        \/\/ The paint is trivial so we won't need to use local coordinates, so skip calculating the\n        \/\/ inverse view matrix.\n        SkRect r = this->asSurfaceProxy()->getBoundsRect();\n        this->fillRectToRect(clip, std::move(paint), GrAA::kNo, SkMatrix::I(), r, r);\n    } else {\n        \/\/ Use the inverse view matrix to arrive at appropriate local coordinates for the paint.\n        SkMatrix localMatrix;\n        if (!viewMatrix.invert(&localMatrix)) {\n            return;\n        }\n        SkIRect bounds = SkIRect::MakeSize(this->asSurfaceProxy()->dimensions());\n        this->fillPixelsWithLocalMatrix(clip, std::move(paint), bounds, localMatrix);\n    }\n}\n\nenum class SurfaceDrawContext::QuadOptimization {\n    \/\/ The rect to draw doesn't intersect clip or render target, so no draw op should be added\n    kDiscarded,\n    \/\/ The rect to draw was converted to some other op and appended to the oplist, so no additional\n    \/\/ op is necessary. Currently this can convert it to a clear op or a rrect op. Only valid if\n    \/\/ a constColor is provided.\n    kSubmitted,\n    \/\/ The clip was folded into the device quad, with updated edge flags and local coords, and\n    \/\/ caller is responsible for adding an appropriate op.\n    kClipApplied,\n    \/\/ No change to clip, but quad updated to better fit clip\/render target, and caller is\n    \/\/ responsible for adding an appropriate op.\n    kCropped\n};\n\nSurfaceDrawContext::QuadOptimization SurfaceDrawContext::attemptQuadOptimization(\n        const GrClip* clip, const GrUserStencilSettings* stencilSettings, GrAA* aa, DrawQuad* quad,\n        GrPaint* paint) {\n    \/\/ Optimization requirements:\n    \/\/ 1. kDiscard applies when clip bounds and quad bounds do not intersect\n    \/\/ 2a. kSubmitted applies when constColor and final geom is pixel aligned rect;\n    \/\/       pixel aligned rect requires rect clip and (rect quad or quad covers clip) OR\n    \/\/ 2b. kSubmitted applies when constColor and rrect clip and quad covers clip\n    \/\/ 4. kClipApplied applies when rect clip and (rect quad or quad covers clip)\n    \/\/ 5. kCropped in all other scenarios (although a crop may be a no-op)\n    const SkPMColor4f* constColor = nullptr;\n    SkPMColor4f paintColor;\n    if (!stencilSettings && paint && !paint->hasCoverageFragmentProcessor() &&\n        paint->isConstantBlendedColor(&paintColor)) {\n        \/\/ Only consider clears\/rrects when it's easy to guarantee 100% fill with single color\n        constColor = &paintColor;\n    }\n\n    \/\/ Save the old AA flags since CropToRect will modify 'quad' and if kCropped is returned, it's\n    \/\/ better to just keep the old flags instead of introducing mixed edge flags.\n    GrQuadAAFlags oldFlags = quad->fEdgeFlags;\n\n    \/\/ Use the logical size of the render target, which allows for \"fullscreen\" clears even if\n    \/\/ the render target has an approximate backing fit\n    SkRect rtRect = this->asSurfaceProxy()->getBoundsRect();\n\n    \/\/ For historical reasons, we assume AA for exact bounds checking in IsOutsideClip.\n    \/\/ TODO(michaelludwig) - Hopefully that can be revisited when the clipping optimizations are\n    \/\/ refactored to work better with round rects and dmsaa.\n    SkRect drawBounds = quad->fDevice.bounds();\n    if (!quad->fDevice.isFinite() || drawBounds.isEmpty() ||\n        GrClip::IsOutsideClip(SkIRect::MakeSize(this->dimensions()), drawBounds, GrAA::kYes)) {\n        return QuadOptimization::kDiscarded;\n    } else if (GrQuadUtils::WillUseHairline(quad->fDevice, GrAAType::kCoverage, quad->fEdgeFlags)) {\n        \/\/ Don't try to apply the clip early if we know rendering will use hairline methods, as this\n        \/\/ has an effect on the op bounds not otherwise taken into account in this function.\n        return QuadOptimization::kCropped;\n    }\n\n    auto conservativeCrop = [&]() {\n        static constexpr int kLargeDrawLimit = 15000;\n        \/\/ Crop the quad to the render target. This doesn't change the visual results of drawing but\n        \/\/ is meant to help numerical stability for excessively large draws.\n        if (drawBounds.width() > kLargeDrawLimit || drawBounds.height() > kLargeDrawLimit) {\n            GrQuadUtils::CropToRect(rtRect, *aa, quad, \/* compute local *\/ !constColor);\n        }\n    };\n\n    bool simpleColor = !stencilSettings && constColor;\n    GrClip::PreClipResult result = clip ? clip->preApply(drawBounds, *aa)\n                                        : GrClip::PreClipResult(GrClip::Effect::kUnclipped);\n    switch(result.fEffect) {\n        case GrClip::Effect::kClippedOut:\n            return QuadOptimization::kDiscarded;\n        case GrClip::Effect::kUnclipped:\n            if (!simpleColor) {\n                conservativeCrop();\n                return QuadOptimization::kClipApplied;\n            } else {\n                \/\/ Update result to store the render target bounds in order and then fall\n                \/\/ through to attempt the draw->native clear optimization\n                result = GrClip::PreClipResult(SkRRect::MakeRect(rtRect), *aa);\n            }\n            break;\n        case GrClip::Effect::kClipped:\n            if (!result.fIsRRect || (stencilSettings && result.fAA != *aa) ||\n                (!result.fRRect.isRect() && !simpleColor)) {\n                \/\/ The clip and draw state are too complicated to try and reduce\n                conservativeCrop();\n                return QuadOptimization::kCropped;\n            } \/\/ Else fall through to attempt to combine the draw and clip geometry together\n            break;\n        default:\n            SkUNREACHABLE;\n    }\n\n    \/\/ If we reached here, we know we're an axis-aligned clip that is either a rect or a round rect,\n    \/\/ so we can potentially combine it with the draw geometry so that no clipping is needed.\n    SkASSERT(result.fEffect == GrClip::Effect::kClipped && result.fIsRRect);\n    SkRect clippedBounds = result.fRRect.getBounds();\n    clippedBounds.intersect(rtRect);\n    if (!drawBounds.intersect(clippedBounds)) {\n        \/\/ Our fractional bounds aren't actually inside the clip. GrClip::preApply() can sometimes\n        \/\/ think in terms of rounded-out bounds. Discard the draw.\n        return QuadOptimization::kDiscarded;\n    }\n    \/\/ Guard against the clipped draw turning into a hairline draw after intersection\n    if (drawBounds.width() < 1.f || drawBounds.height() < 1.f) {\n        return QuadOptimization::kCropped;\n    }\n\n    if (result.fRRect.isRect()) {\n        \/\/ No rounded corners, so we might be able to become a native clear or we might be able to\n        \/\/ modify geometry and edge flags to represent intersected shape of clip and draw.\n        if (GrQuadUtils::CropToRect(clippedBounds, result.fAA, quad,\n                                    \/*compute local*\/ !constColor)) {\n            if (simpleColor && quad->fDevice.quadType() == GrQuad::Type::kAxisAligned) {\n                \/\/ Clear optimization is possible\n                drawBounds = quad->fDevice.bounds();\n                if (drawBounds.contains(rtRect)) {\n                    \/\/ Fullscreen clear\n                    this->clear(*constColor);\n                    return QuadOptimization::kSubmitted;\n                } else if (GrClip::IsPixelAligned(drawBounds) &&\n                           drawBounds.width() > 256 && drawBounds.height() > 256) {\n                    \/\/ Scissor + clear (round shouldn't do anything since we are pixel aligned)\n                    SkIRect scissorRect;\n                    drawBounds.round(&scissorRect);\n                    this->clear(scissorRect, *constColor);\n                    return QuadOptimization::kSubmitted;\n                }\n            }\n\n            \/\/ else the draw and clip were combined so just update the AA to reflect combination\n            if (*aa == GrAA::kNo && result.fAA == GrAA::kYes &&\n                quad->fEdgeFlags != GrQuadAAFlags::kNone) {\n                \/\/ The clip was anti-aliased and now the draw needs to be upgraded to AA to\n                \/\/ properly reflect the smooth edge of the clip.\n                *aa = GrAA::kYes;\n            }\n            \/\/ We intentionally do not downgrade AA here because we don't know if we need to\n            \/\/ preserve MSAA (see GrQuadAAFlags docs). But later in the pipeline, the ops can\n            \/\/ use GrResolveAATypeForQuad() to turn off coverage AA when all flags are off.\n            \/\/ deviceQuad is exactly the intersection of original quad and clip, so it can be\n            \/\/ drawn with no clip (submitted by caller)\n            return QuadOptimization::kClipApplied;\n        }\n    } else {\n        \/\/ Rounded corners and constant filled color (limit ourselves to solid colors because\n        \/\/ there is no way to use custom local coordinates with drawRRect).\n        SkASSERT(simpleColor);\n        if (GrQuadUtils::CropToRect(clippedBounds, result.fAA, quad,\n                                    \/* compute local *\/ false) &&\n            quad->fDevice.quadType() == GrQuad::Type::kAxisAligned &&\n            quad->fDevice.bounds().contains(clippedBounds)) {\n            \/\/ Since the cropped quad became a rectangle which covered the bounds of the rrect,\n            \/\/ we can draw the rrect directly and ignore the edge flags\n            this->drawRRect(nullptr, std::move(*paint), result.fAA, SkMatrix::I(), result.fRRect,\n                            GrStyle::SimpleFill());\n            return QuadOptimization::kSubmitted;\n        }\n    }\n\n    \/\/ The quads have been updated to better fit the clip bounds, but can't get rid of\n    \/\/ the clip entirely\n    quad->fEdgeFlags = oldFlags;\n    return QuadOptimization::kCropped;\n}\n\nvoid SurfaceDrawContext::drawFilledQuad(const GrClip* clip,\n                                        GrPaint&& paint,\n                                        GrAA aa,\n                                        DrawQuad* quad,\n                                        const GrUserStencilSettings* ss) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawFilledQuad\", fContext);\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    QuadOptimization opt = this->attemptQuadOptimization(clip, ss, &aa, quad, &paint);\n    if (opt >= QuadOptimization::kClipApplied) {\n        \/\/ These optimizations require caller to add an op themselves\n        const GrClip* finalClip = opt == QuadOptimization::kClipApplied ? nullptr : clip;\n        GrAAType aaType;\n        if (ss) {\n            aaType = (aa == GrAA::kYes) ? GrAAType::kMSAA : GrAAType::kNone;\n        } else if (fCanUseDynamicMSAA && aa == GrAA::kNo) {\n            \/\/ The SkGpuDevice ensures GrAA is always kYes when using dmsaa. If the caller calls\n            \/\/ into here with GrAA::kNo, trust that they know what they're doing and that the\n            \/\/ rendering will be equal with or without msaa.\n            aaType = GrAAType::kNone;\n        } else {\n            aaType = this->chooseAAType(aa);\n        }\n        this->addDrawOp(finalClip, FillRectOp::Make(fContext, std::move(paint), aaType,\n                                                    quad, ss));\n    }\n    \/\/ All other optimization levels were completely handled inside attempt(), so no extra op needed\n}\n\nvoid SurfaceDrawContext::drawTexture(const GrClip* clip,\n                                     GrSurfaceProxyView view,\n                                     SkAlphaType srcAlphaType,\n                                     GrSamplerState::Filter filter,\n                                     GrSamplerState::MipmapMode mm,\n                                     SkBlendMode blendMode,\n                                     const SkPMColor4f& color,\n                                     const SkRect& srcRect,\n                                     const SkRect& dstRect,\n                                     GrAA aa,\n                                     GrQuadAAFlags edgeAA,\n                                     SkCanvas::SrcRectConstraint constraint,\n                                     const SkMatrix& viewMatrix,\n                                     sk_sp<GrColorSpaceXform> colorSpaceXform) {\n    \/\/ If we are using dmsaa then go through FillRRectOp (via fillRectToRect).\n    if ((this->alwaysAntialias() || this->caps()->reducedShaderMode()) && aa == GrAA::kYes) {\n        GrPaint paint;\n        paint.setColor4f(color);\n        std::unique_ptr<GrFragmentProcessor> fp;\n        if (constraint == SkCanvas::kStrict_SrcRectConstraint) {\n            fp = GrTextureEffect::MakeSubset(view, srcAlphaType, SkMatrix::I(),\n                                             GrSamplerState(filter, mm), srcRect,\n                                             *this->caps());\n        } else {\n            fp = GrTextureEffect::Make(view, srcAlphaType, SkMatrix::I(), filter, mm);\n        }\n        if (colorSpaceXform) {\n            fp = GrColorSpaceXformEffect::Make(std::move(fp), std::move(colorSpaceXform));\n        }\n        fp = GrBlendFragmentProcessor::Make(std::move(fp), nullptr, SkBlendMode::kModulate);\n        paint.setColorFragmentProcessor(std::move(fp));\n        if (blendMode != SkBlendMode::kSrcOver) {\n            paint.setXPFactory(SkBlendMode_AsXPFactory(blendMode));\n        }\n        this->fillRectToRect(clip, std::move(paint), GrAA::kYes, viewMatrix, dstRect, srcRect);\n        return;\n    }\n\n    const SkRect* subset = constraint == SkCanvas::kStrict_SrcRectConstraint ?\n            &srcRect : nullptr;\n    DrawQuad quad{GrQuad::MakeFromRect(dstRect, viewMatrix), GrQuad(srcRect), edgeAA};\n\n    this->drawTexturedQuad(clip, std::move(view), srcAlphaType, std::move(colorSpaceXform), filter,\n                           mm, color, blendMode, aa, &quad, subset);\n}\n\nvoid SurfaceDrawContext::drawTexturedQuad(const GrClip* clip,\n                                          GrSurfaceProxyView proxyView,\n                                          SkAlphaType srcAlphaType,\n                                          sk_sp<GrColorSpaceXform> textureXform,\n                                          GrSamplerState::Filter filter,\n                                          GrSamplerState::MipmapMode mm,\n                                          const SkPMColor4f& color,\n                                          SkBlendMode blendMode,\n                                          GrAA aa,\n                                          DrawQuad* quad,\n                                          const SkRect* subset) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    SkASSERT(proxyView.asTextureProxy());\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawTexturedQuad\", fContext);\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    \/\/ Functionally this is very similar to drawFilledQuad except that there's no constColor to\n    \/\/ enable the kSubmitted optimizations, no stencil settings support, and its a TextureOp.\n    QuadOptimization opt = this->attemptQuadOptimization(clip, nullptr\/*stencil*\/, &aa, quad,\n                                                         nullptr\/*paint*\/);\n\n    SkASSERT(opt != QuadOptimization::kSubmitted);\n    if (opt != QuadOptimization::kDiscarded) {\n        \/\/ And the texture op if not discarded\n        const GrClip* finalClip = opt == QuadOptimization::kClipApplied ? nullptr : clip;\n        GrAAType aaType = this->chooseAAType(aa);\n        auto clampType = GrColorTypeClampType(this->colorInfo().colorType());\n        auto saturate = clampType == GrClampType::kManual ? TextureOp::Saturate::kYes\n                                                          : TextureOp::Saturate::kNo;\n        \/\/ Use the provided subset, although hypothetically we could detect that the cropped local\n        \/\/ quad is sufficiently inside the subset and the constraint could be dropped.\n        this->addDrawOp(finalClip,\n                        TextureOp::Make(fContext, std::move(proxyView), srcAlphaType,\n                                        std::move(textureXform), filter, mm, color, saturate,\n                                        blendMode, aaType, quad, subset));\n    }\n}\n\nvoid SurfaceDrawContext::drawRect(const GrClip* clip,\n                                  GrPaint&& paint,\n                                  GrAA aa,\n                                  const SkMatrix& viewMatrix,\n                                  const SkRect& rect,\n                                  const GrStyle* style) {\n    if (!style) {\n        style = &GrStyle::SimpleFill();\n    }\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawRect\", fContext);\n\n    \/\/ Path effects should've been devolved to a path in SkGpuDevice\n    SkASSERT(!style->pathEffect());\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    const SkStrokeRec& stroke = style->strokeRec();\n    if (stroke.getStyle() == SkStrokeRec::kFill_Style) {\n        \/\/ Fills the rect, using rect as its own local coordinates\n        this->fillRectToRect(clip, std::move(paint), aa, viewMatrix, rect, rect);\n        return;\n    } else if ((stroke.getStyle() == SkStrokeRec::kStroke_Style ||\n                stroke.getStyle() == SkStrokeRec::kHairline_Style) &&\n               rect.width()                                        &&\n               rect.height()                                       &&\n               !this->caps()->reducedShaderMode()) {\n        \/\/ Only use the StrokeRectOp for non-empty rectangles. Empty rectangles will be processed by\n        \/\/ GrStyledShape to handle stroke caps and dashing properly.\n        \/\/\n        \/\/ http:\/\/skbug.com\/12206 -- there is a double-blend issue with the bevel version of\n        \/\/ AAStrokeRectOp, and if we increase the AA bloat for MSAA it becomes more pronounced.\n        \/\/ Don't use the bevel version with DMSAA.\n        GrAAType aaType = (fCanUseDynamicMSAA &&\n                           stroke.getJoin() == SkPaint::kMiter_Join &&\n                           stroke.getMiter() >= SK_ScalarSqrt2) ? GrAAType::kCoverage\n                                                                : this->chooseAAType(aa);\n        GrOp::Owner op = StrokeRectOp::Make(fContext, std::move(paint), aaType, viewMatrix,\n                                            rect, stroke);\n        \/\/ op may be null if the stroke is not supported or if using coverage aa and the view matrix\n        \/\/ does not preserve rectangles.\n        if (op) {\n            this->addDrawOp(clip, std::move(op));\n            return;\n        }\n    }\n    assert_alive(paint);\n    this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,\n                                     GrStyledShape(rect, *style, DoSimplify::kNo));\n}\n\nvoid SurfaceDrawContext::fillRectToRect(const GrClip* clip,\n                                        GrPaint&& paint,\n                                        GrAA aa,\n                                        const SkMatrix& viewMatrix,\n                                        const SkRect& rectToDraw,\n                                        const SkRect& localRect) {\n    DrawQuad quad{GrQuad::MakeFromRect(rectToDraw, viewMatrix), GrQuad(localRect),\n                  aa == GrAA::kYes ? GrQuadAAFlags::kAll : GrQuadAAFlags::kNone};\n\n    \/\/ If we are using dmsaa then attempt to draw the rect with FillRRectOp.\n    if ((fContext->priv().caps()->reducedShaderMode() || this->alwaysAntialias()) &&\n        this->caps()->drawInstancedSupport()                                      &&\n        aa == GrAA::kYes) {  \/\/ If aa is kNo when using dmsaa, the rect is axis aligned. Don't use\n                             \/\/ FillRRectOp because it might require dual source blending.\n                             \/\/ http:\/\/skbug.com\/11756\n        QuadOptimization opt = this->attemptQuadOptimization(clip, nullptr\/*stencil*\/, &aa, &quad,\n                                                             &paint);\n        if (opt < QuadOptimization::kClipApplied) {\n            \/\/ The optimization was completely handled inside attempt().\n            return;\n        }\n\n        SkRect croppedRect, croppedLocal{};\n        const GrClip* optimizedClip = clip;\n        if (clip && viewMatrix.isScaleTranslate() && quad.fDevice.asRect(&croppedRect) &&\n            (!paint.usesLocalCoords() || quad.fLocal.asRect(&croppedLocal))) {\n            \/\/ The cropped quad is still a rect, and our view matrix preserves rects. Map it back\n            \/\/ to pre-matrix space.\n            SkMatrix inverse;\n            if (!viewMatrix.invert(&inverse)) {\n                return;\n            }\n            SkASSERT(inverse.rectStaysRect());\n            inverse.mapRect(&croppedRect);\n            if (opt == QuadOptimization::kClipApplied) {\n                optimizedClip = nullptr;\n            }\n        } else {\n            \/\/ Even if attemptQuadOptimization gave us an optimized quad, FillRRectOp needs a rect\n            \/\/ in pre-matrix space, so use the original rect. Also preserve the original clip.\n            croppedRect = rectToDraw;\n            croppedLocal = localRect;\n        }\n\n        if (auto op = FillRRectOp::Make(fContext, this->arenaAlloc(), std::move(paint),\n                                        viewMatrix, SkRRect::MakeRect(croppedRect), croppedLocal,\n                                        GrAA::kYes)) {\n            this->addDrawOp(optimizedClip, std::move(op));\n            return;\n        }\n    }\n\n    assert_alive(paint);\n    this->drawFilledQuad(clip, std::move(paint), aa, &quad);\n}\n\nvoid SurfaceDrawContext::drawQuadSet(const GrClip* clip,\n                                     GrPaint&& paint,\n                                     GrAA aa,\n                                     const SkMatrix& viewMatrix,\n                                     const GrQuadSetEntry quads[],\n                                     int cnt) {\n    GrAAType aaType = this->chooseAAType(aa);\n\n    FillRectOp::AddFillRectOps(this, clip, fContext, std::move(paint), aaType, viewMatrix,\n                               quads, cnt);\n}\n\nint SurfaceDrawContext::maxWindowRectangles() const {\n    return this->asRenderTargetProxy()->maxWindowRectangles(*this->caps());\n}\n\nOpsTask::CanDiscardPreviousOps SurfaceDrawContext::canDiscardPreviousOpsOnFullClear() const {\n#if GR_TEST_UTILS\n    if (fPreserveOpsOnFullClear_TestingOnly) {\n        return OpsTask::CanDiscardPreviousOps::kNo;\n    }\n#endif\n    \/\/ Regardless of how the clear is implemented (native clear or a fullscreen quad), all prior ops\n    \/\/ would normally be overwritten. The one exception is if the render target context is marked as\n    \/\/ needing a stencil buffer then there may be a prior op that writes to the stencil buffer.\n    \/\/ Although the clear will ignore the stencil buffer, following draw ops may not so we can't get\n    \/\/ rid of all the preceding ops. Beware! If we ever add any ops that have a side effect beyond\n    \/\/ modifying the stencil buffer we will need a more elaborate tracking system (skbug.com\/7002).\n    return OpsTask::CanDiscardPreviousOps(!fNeedsStencil);\n}\n\nvoid SurfaceDrawContext::setNeedsStencil() {\n    \/\/ Don't clear stencil until after we've set fNeedsStencil. This ensures we don't loop forever\n    \/\/ in the event that there are driver bugs and we need to clear as a draw.\n    bool hasInitializedStencil = fNeedsStencil;\n    fNeedsStencil = true;\n    if (!hasInitializedStencil) {\n        this->asRenderTargetProxy()->setNeedsStencil();\n        if (this->caps()->performStencilClearsAsDraws()) {\n            \/\/ There is a driver bug with clearing stencil. We must use an op to manually clear the\n            \/\/ stencil buffer before the op that required 'setNeedsStencil'.\n            this->internalStencilClear(nullptr, \/* inside mask *\/ false);\n        } else {\n            this->getOpsTask()->setInitialStencilContent(\n                    OpsTask::StencilContent::kUserBitsCleared);\n        }\n    }\n}\n\nvoid SurfaceDrawContext::internalStencilClear(const SkIRect* scissor, bool insideStencilMask) {\n    this->setNeedsStencil();\n\n    GrScissorState scissorState(this->asSurfaceProxy()->backingStoreDimensions());\n    if (scissor && !scissorState.set(*scissor)) {\n        \/\/ The requested clear region is off screen, so nothing to do.\n        return;\n    }\n\n    bool clearWithDraw = this->caps()->performStencilClearsAsDraws() ||\n                         (scissorState.enabled() && this->caps()->performPartialClearsAsDraws());\n    if (clearWithDraw) {\n        const GrUserStencilSettings* ss = GrStencilSettings::SetClipBitSettings(insideStencilMask);\n\n        \/\/ Configure the paint to have no impact on the color buffer\n        GrPaint paint;\n        paint.setXPFactory(GrDisableColorXPFactory::Get());\n        this->addDrawOp(nullptr,\n                        FillRectOp::MakeNonAARect(fContext, std::move(paint), SkMatrix::I(),\n                                                  SkRect::Make(scissorState.rect()), ss));\n    } else {\n        this->addOp(ClearOp::MakeStencilClip(fContext, scissorState, insideStencilMask));\n    }\n}\n\nbool SurfaceDrawContext::stencilPath(const GrHardClip* clip,\n                                     GrAA doStencilMSAA,\n                                     const SkMatrix& viewMatrix,\n                                     const SkPath& path) {\n    SkIRect clipBounds = clip ? clip->getConservativeBounds()\n                              : SkIRect::MakeSize(this->dimensions());\n    GrStyledShape shape(path, GrStyledShape::DoSimplify::kNo);\n\n    PathRenderer::CanDrawPathArgs canDrawArgs;\n    canDrawArgs.fCaps = fContext->priv().caps();\n    canDrawArgs.fProxy = this->asRenderTargetProxy();\n    canDrawArgs.fClipConservativeBounds = &clipBounds;\n    canDrawArgs.fViewMatrix = &viewMatrix;\n    canDrawArgs.fShape = &shape;\n    canDrawArgs.fPaint = nullptr;\n    canDrawArgs.fSurfaceProps = &fSurfaceProps;\n    canDrawArgs.fAAType = (doStencilMSAA == GrAA::kYes) ? GrAAType::kMSAA : GrAAType::kNone;\n    canDrawArgs.fHasUserStencilSettings = false;\n    auto pr = this->drawingManager()->getPathRenderer(canDrawArgs,\n                                                      false,\n                                                      PathRendererChain::DrawType::kStencil);\n    if (!pr) {\n        SkDebugf(\"WARNING: No path renderer to stencil path.\\n\");\n        return false;\n    }\n\n    PathRenderer::StencilPathArgs args;\n    args.fContext = fContext;\n    args.fSurfaceDrawContext = this;\n    args.fClip = clip;\n    args.fClipConservativeBounds = &clipBounds;\n    args.fViewMatrix = &viewMatrix;\n    args.fShape = &shape;\n    args.fDoStencilMSAA = doStencilMSAA;\n    pr->stencilPath(args);\n    return true;\n}\n\nvoid SurfaceDrawContext::drawTextureSet(const GrClip* clip,\n                                        GrTextureSetEntry set[],\n                                        int cnt,\n                                        int proxyRunCnt,\n                                        GrSamplerState::Filter filter,\n                                        GrSamplerState::MipmapMode mm,\n                                        SkBlendMode mode,\n                                        GrAA aa,\n                                        SkCanvas::SrcRectConstraint constraint,\n                                        const SkMatrix& viewMatrix,\n                                        sk_sp<GrColorSpaceXform> texXform) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawTextureSet\", fContext);\n\n    \/\/ Create the minimum number of GrTextureOps needed to draw this set. Individual\n    \/\/ GrTextureOps can rebind the texture between draws thus avoiding GrPaint (re)creation.\n    AutoCheckFlush acf(this->drawingManager());\n    GrAAType aaType = this->chooseAAType(aa);\n    auto clampType = GrColorTypeClampType(this->colorInfo().colorType());\n    auto saturate = clampType == GrClampType::kManual ? TextureOp::Saturate::kYes\n                                                      : TextureOp::Saturate::kNo;\n    TextureOp::AddTextureSetOps(this, clip, fContext, set, cnt, proxyRunCnt, filter, mm, saturate,\n                                mode, aaType, constraint, viewMatrix, std::move(texXform));\n}\n\nvoid SurfaceDrawContext::drawVertices(const GrClip* clip,\n                                      GrPaint&& paint,\n                                      const SkMatrixProvider& matrixProvider,\n                                      sk_sp<SkVertices> vertices,\n                                      GrPrimitiveType* overridePrimType,\n                                      bool skipColorXform) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawVertices\", fContext);\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    SkASSERT(vertices);\n    auto xform = skipColorXform ? nullptr : this->colorInfo().refColorSpaceXformFromSRGB();\n    GrAAType aaType = fCanUseDynamicMSAA ? GrAAType::kMSAA : this->chooseAAType(GrAA::kNo);\n    GrOp::Owner op = DrawCustomMeshOp::Make(fContext,\n                                            std::move(paint),\n                                            std::move(vertices),\n                                            overridePrimType,\n                                            matrixProvider,\n                                            aaType,\n                                            std::move(xform));\n    this->addDrawOp(clip, std::move(op));\n}\n\nvoid SurfaceDrawContext::drawCustomMesh(const GrClip* clip,\n                                        GrPaint&& paint,\n                                        const SkMatrixProvider& matrixProvider,\n                                        SkCustomMesh cm) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawCustomMesh\", fContext);\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    SkASSERT(SkValidateCustomMesh(cm));\n\n    auto xform = GrColorSpaceXform::Make(SkCustomMeshSpecificationPriv::ColorSpace(*cm.spec),\n                                         SkCustomMeshSpecificationPriv::AlphaType(*cm.spec),\n                                         this->colorInfo().colorSpace(),\n                                         this->colorInfo().alphaType());\n    GrAAType aaType = fCanUseDynamicMSAA ? GrAAType::kMSAA : this->chooseAAType(GrAA::kNo);\n    GrOp::Owner op = DrawCustomMeshOp::Make(fContext,\n                                            std::move(paint),\n                                            std::move(cm),\n                                            matrixProvider,\n                                            aaType,\n                                            std::move(xform));\n    this->addDrawOp(clip, std::move(op));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SurfaceDrawContext::drawAtlas(const GrClip* clip,\n                                   GrPaint&& paint,\n                                   const SkMatrix& viewMatrix,\n                                   int spriteCount,\n                                   const SkRSXform xform[],\n                                   const SkRect texRect[],\n                                   const SkColor colors[]) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawAtlas\", fContext);\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    GrAAType aaType = this->chooseAAType(GrAA::kNo);\n    GrOp::Owner op = DrawAtlasOp::Make(fContext, std::move(paint), viewMatrix,\n                                       aaType, spriteCount, xform, texRect, colors);\n    this->addDrawOp(clip, std::move(op));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SurfaceDrawContext::drawRRect(const GrClip* origClip,\n                                   GrPaint&& paint,\n                                   GrAA aa,\n                                   const SkMatrix& viewMatrix,\n                                   const SkRRect& rrect,\n                                   const GrStyle& style) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawRRect\", fContext);\n\n    SkASSERT(!style.pathEffect()); \/\/ this should've been devolved to a path in SkGpuDevice\n\n    const SkStrokeRec& stroke = style.strokeRec();\n    if (stroke.getStyle() == SkStrokeRec::kFill_Style && rrect.isEmpty()) {\n       return;\n    }\n\n    const GrClip* clip = origClip;\n    \/\/ It is not uncommon to clip to a round rect and then draw that same round rect. Since our\n    \/\/ lower level clip code works from op bounds, which are SkRects, it doesn't detect that the\n    \/\/ clip can be ignored. The following test attempts to mitigate the stencil clip cost but only\n    \/\/ works for axis-aligned round rects. This also only works for filled rrects since the stroke\n    \/\/ width outsets beyond the rrect itself.\n    \/\/ TODO: skbug.com\/10462 - There was mixed performance wins and regressions when this\n    \/\/ optimization was turned on outside of Android Framework. I (michaelludwig) believe this is\n    \/\/ do to the overhead in determining if an SkClipStack is just a rrect. Once that is improved,\n    \/\/ re-enable this and see if we avoid the regressions.\n#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK\n    SkRRect devRRect;\n    if (clip && stroke.getStyle() == SkStrokeRec::kFill_Style &&\n        rrect.transform(viewMatrix, &devRRect)) {\n        GrClip::PreClipResult result = clip->preApply(devRRect.getBounds(), aa);\n        switch(result.fEffect) {\n            case GrClip::Effect::kClippedOut:\n                return;\n            case GrClip::Effect::kUnclipped:\n                clip = nullptr;\n                break;\n            case GrClip::Effect::kClipped:\n                \/\/ Currently there's no general-purpose rrect-to-rrect contains function, and if we\n                \/\/ got here, we know the devRRect's bounds aren't fully contained by the clip.\n                \/\/ Testing for equality between the two is a reasonable stop-gap for now.\n                if (result.fIsRRect && result.fRRect == devRRect) {\n                    \/\/ NOTE: On the android framework, we allow this optimization even when the clip\n                    \/\/ is non-AA and the draw is AA.\n                    if (result.fAA == aa || (result.fAA == GrAA::kNo && aa == GrAA::kYes)) {\n                        clip = nullptr;\n                    }\n                }\n                break;\n            default:\n                SkUNREACHABLE;\n        }\n    }\n#endif\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    GrAAType aaType = this->chooseAAType(aa);\n\n    GrOp::Owner op;\n    if (aaType == GrAAType::kCoverage                          &&\n        !fCanUseDynamicMSAA                                    &&\n        !this->caps()->reducedShaderMode()                     &&\n        rrect.isSimple()                                       &&\n        rrect.getSimpleRadii().fX == rrect.getSimpleRadii().fY &&\n        viewMatrix.rectStaysRect() && viewMatrix.isSimilarity()) {\n        \/\/ In specific cases we use a dedicated circular round rect op to try and get better perf.\n        assert_alive(paint);\n        op = GrOvalOpFactory::MakeCircularRRectOp(fContext, std::move(paint), viewMatrix, rrect,\n                                                  stroke, this->caps()->shaderCaps());\n    }\n    if (!op && style.isSimpleFill()) {\n        assert_alive(paint);\n        op = FillRRectOp::Make(fContext, this->arenaAlloc(), std::move(paint), viewMatrix, rrect,\n                               rrect.rect(), GrAA(aaType != GrAAType::kNone));\n    }\n    if (!op && (aaType == GrAAType::kCoverage || fCanUseDynamicMSAA)) {\n        assert_alive(paint);\n        op = GrOvalOpFactory::MakeRRectOp(\n                fContext, std::move(paint), viewMatrix, rrect, stroke, this->caps()->shaderCaps());\n    }\n    if (op) {\n        this->addDrawOp(clip, std::move(op));\n        return;\n    }\n\n    assert_alive(paint);\n    this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,\n                                     GrStyledShape(rrect, style, DoSimplify::kNo));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool SurfaceDrawContext::drawFastShadow(const GrClip* clip,\n                                        const SkMatrix& viewMatrix,\n                                        const SkPath& path,\n                                        const SkDrawShadowRec& rec) {\n    ASSERT_SINGLE_OWNER\n    if (fContext->abandoned()) {\n        return true;\n    }\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawFastShadow\", fContext);\n\n    \/\/ check z plane\n    bool tiltZPlane = SkToBool(!SkScalarNearlyZero(rec.fZPlaneParams.fX) ||\n                               !SkScalarNearlyZero(rec.fZPlaneParams.fY));\n    bool skipAnalytic = SkToBool(rec.fFlags & SkShadowFlags::kGeometricOnly_ShadowFlag);\n    if (tiltZPlane || skipAnalytic || !viewMatrix.rectStaysRect() || !viewMatrix.isSimilarity()) {\n        return false;\n    }\n\n    SkRRect rrect;\n    SkRect rect;\n    \/\/ we can only handle rects, circles, and simple rrects with circular corners\n    bool isRRect = path.isRRect(&rrect) && SkRRectPriv::IsNearlySimpleCircular(rrect) &&\n                   rrect.getSimpleRadii().fX > SK_ScalarNearlyZero;\n    if (!isRRect &&\n        path.isOval(&rect) && SkScalarNearlyEqual(rect.width(), rect.height()) &&\n        rect.width() > SK_ScalarNearlyZero) {\n        rrect.setOval(rect);\n        isRRect = true;\n    }\n    if (!isRRect && path.isRect(&rect)) {\n        rrect.setRect(rect);\n        isRRect = true;\n    }\n\n    if (!isRRect) {\n        return false;\n    }\n\n    if (rrect.isEmpty()) {\n        return true;\n    }\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    SkPoint3 devLightPos = rec.fLightPos;\n    bool directional = SkToBool(rec.fFlags & kDirectionalLight_ShadowFlag);\n    if (!directional) {\n        \/\/ transform light\n        viewMatrix.mapPoints((SkPoint*)&devLightPos.fX, 1);\n    }\n\n    \/\/ 1\/scale\n    SkScalar devToSrcScale = viewMatrix.isScaleTranslate() ?\n        SkScalarInvert(SkScalarAbs(viewMatrix[SkMatrix::kMScaleX])) :\n        sk_float_rsqrt(viewMatrix[SkMatrix::kMScaleX] * viewMatrix[SkMatrix::kMScaleX] +\n                       viewMatrix[SkMatrix::kMSkewX] * viewMatrix[SkMatrix::kMSkewX]);\n\n    SkScalar occluderHeight = rec.fZPlaneParams.fZ;\n    bool transparent = SkToBool(rec.fFlags & SkShadowFlags::kTransparentOccluder_ShadowFlag);\n\n    if (SkColorGetA(rec.fAmbientColor) > 0) {\n        SkScalar devSpaceInsetWidth = SkDrawShadowMetrics::AmbientBlurRadius(occluderHeight);\n        const SkScalar umbraRecipAlpha = SkDrawShadowMetrics::AmbientRecipAlpha(occluderHeight);\n        const SkScalar devSpaceAmbientBlur = devSpaceInsetWidth * umbraRecipAlpha;\n\n        \/\/ Outset the shadow rrect to the border of the penumbra\n        SkScalar ambientPathOutset = devSpaceInsetWidth * devToSrcScale;\n        SkRRect ambientRRect;\n        SkRect outsetRect = rrect.rect().makeOutset(ambientPathOutset, ambientPathOutset);\n        \/\/ If the rrect was an oval then its outset will also be one.\n        \/\/ We set it explicitly to avoid errors.\n        if (rrect.isOval()) {\n            ambientRRect = SkRRect::MakeOval(outsetRect);\n        } else {\n            SkScalar outsetRad = SkRRectPriv::GetSimpleRadii(rrect).fX + ambientPathOutset;\n            ambientRRect = SkRRect::MakeRectXY(outsetRect, outsetRad, outsetRad);\n        }\n\n        \/\/ The ShadowRRectOp still uses 8888 colors, so it might get clamped if the shadow color\n        \/\/ does not fit in bytes after being transformed to the destination color space. This can\n        \/\/ happen if the destination color space is smaller than sRGB, which is highly unlikely.\n        GrColor ambientColor = SkColorToPMColor4f(rec.fAmbientColor, colorInfo()).toBytes_RGBA();\n        if (transparent) {\n            \/\/ set a large inset to force a fill\n            devSpaceInsetWidth = ambientRRect.width();\n        }\n\n        GrOp::Owner op = ShadowRRectOp::Make(fContext,\n                                             ambientColor,\n                                             viewMatrix,\n                                             ambientRRect,\n                                             devSpaceAmbientBlur,\n                                             devSpaceInsetWidth);\n        if (op) {\n            this->addDrawOp(clip, std::move(op));\n        }\n    }\n\n    if (SkColorGetA(rec.fSpotColor) > 0) {\n        SkScalar devSpaceSpotBlur;\n        SkScalar spotScale;\n        SkVector spotOffset;\n        if (directional) {\n            SkDrawShadowMetrics::GetDirectionalParams(occluderHeight, devLightPos.fX,\n                                                      devLightPos.fY, devLightPos.fZ,\n                                                      rec.fLightRadius, &devSpaceSpotBlur,\n                                                      &spotScale, &spotOffset);\n        } else {\n            SkDrawShadowMetrics::GetSpotParams(occluderHeight, devLightPos.fX, devLightPos.fY,\n                                               devLightPos.fZ, rec.fLightRadius,\n                                               &devSpaceSpotBlur, &spotScale, &spotOffset);\n        }\n        \/\/ handle scale of radius due to CTM\n        const SkScalar srcSpaceSpotBlur = devSpaceSpotBlur * devToSrcScale;\n\n        \/\/ Adjust translate for the effect of the scale.\n        spotOffset.fX += spotScale*viewMatrix[SkMatrix::kMTransX];\n        spotOffset.fY += spotScale*viewMatrix[SkMatrix::kMTransY];\n        \/\/ This offset is in dev space, need to transform it into source space.\n        SkMatrix ctmInverse;\n        if (viewMatrix.invert(&ctmInverse)) {\n            ctmInverse.mapPoints(&spotOffset, 1);\n        } else {\n            \/\/ Since the matrix is a similarity, this should never happen, but just in case...\n            SkDebugf(\"Matrix is degenerate. Will not render spot shadow correctly!\\n\");\n            SkASSERT(false);\n        }\n\n        \/\/ Compute the transformed shadow rrect\n        SkRRect spotShadowRRect;\n        SkMatrix shadowTransform;\n        shadowTransform.setScaleTranslate(spotScale, spotScale, spotOffset.fX, spotOffset.fY);\n        rrect.transform(shadowTransform, &spotShadowRRect);\n        SkScalar spotRadius = spotShadowRRect.getSimpleRadii().fX;\n\n        \/\/ Compute the insetWidth\n        SkScalar blurOutset = srcSpaceSpotBlur;\n        SkScalar insetWidth = blurOutset;\n        if (transparent) {\n            \/\/ If transparent, just do a fill\n            insetWidth += spotShadowRRect.width();\n        } else {\n            \/\/ For shadows, instead of using a stroke we specify an inset from the penumbra\n            \/\/ border. We want to extend this inset area so that it meets up with the caster\n            \/\/ geometry. The inset geometry will by default already be inset by the blur width.\n            \/\/\n            \/\/ We compare the min and max corners inset by the radius between the original\n            \/\/ rrect and the shadow rrect. The distance between the two plus the difference\n            \/\/ between the scaled radius and the original radius gives the distance from the\n            \/\/ transformed shadow shape to the original shape in that corner. The max\n            \/\/ of these gives the maximum distance we need to cover.\n            \/\/\n            \/\/ Since we are outsetting by 1\/2 the blur distance, we just add the maxOffset to\n            \/\/ that to get the full insetWidth.\n            SkScalar maxOffset;\n            if (rrect.isRect()) {\n                \/\/ Manhattan distance works better for rects\n                maxOffset = std::max(std::max(SkTAbs(spotShadowRRect.rect().fLeft -\n                                                 rrect.rect().fLeft),\n                                          SkTAbs(spotShadowRRect.rect().fTop -\n                                                 rrect.rect().fTop)),\n                                   std::max(SkTAbs(spotShadowRRect.rect().fRight -\n                                                 rrect.rect().fRight),\n                                          SkTAbs(spotShadowRRect.rect().fBottom -\n                                                 rrect.rect().fBottom)));\n            } else {\n                SkScalar dr = spotRadius - SkRRectPriv::GetSimpleRadii(rrect).fX;\n                SkPoint upperLeftOffset = SkPoint::Make(spotShadowRRect.rect().fLeft -\n                                                        rrect.rect().fLeft + dr,\n                                                        spotShadowRRect.rect().fTop -\n                                                        rrect.rect().fTop + dr);\n                SkPoint lowerRightOffset = SkPoint::Make(spotShadowRRect.rect().fRight -\n                                                         rrect.rect().fRight - dr,\n                                                         spotShadowRRect.rect().fBottom -\n                                                         rrect.rect().fBottom - dr);\n                maxOffset = SkScalarSqrt(std::max(SkPointPriv::LengthSqd(upperLeftOffset),\n                                                  SkPointPriv::LengthSqd(lowerRightOffset))) + dr;\n            }\n            insetWidth += std::max(blurOutset, maxOffset);\n        }\n\n        \/\/ Outset the shadow rrect to the border of the penumbra\n        SkRect outsetRect = spotShadowRRect.rect().makeOutset(blurOutset, blurOutset);\n        if (spotShadowRRect.isOval()) {\n            spotShadowRRect = SkRRect::MakeOval(outsetRect);\n        } else {\n            SkScalar outsetRad = spotRadius + blurOutset;\n            spotShadowRRect = SkRRect::MakeRectXY(outsetRect, outsetRad, outsetRad);\n        }\n\n        \/\/ The ShadowRRectOp still uses 8888 colors, so it might get clamped if the shadow color\n        \/\/ does not fit in bytes after being transformed to the destination color space. This can\n        \/\/ happen if the destination color space is smaller than sRGB, which is highly unlikely.\n        GrColor spotColor = SkColorToPMColor4f(rec.fSpotColor, colorInfo()).toBytes_RGBA();\n        GrOp::Owner op = ShadowRRectOp::Make(fContext,\n                                             spotColor,\n                                             viewMatrix,\n                                             spotShadowRRect,\n                                             2.0f * devSpaceSpotBlur,\n                                             insetWidth);\n        if (op) {\n            this->addDrawOp(clip, std::move(op));\n        }\n    }\n\n    return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SurfaceDrawContext::drawRegion(const GrClip* clip,\n                                    GrPaint&& paint,\n                                    GrAA aa,\n                                    const SkMatrix& viewMatrix,\n                                    const SkRegion& region,\n                                    const GrStyle& style,\n                                    const GrUserStencilSettings* ss) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawRegion\", fContext);\n\n    if (GrAA::kYes == aa) {\n        \/\/ GrRegionOp performs no antialiasing but is much faster, so here we check the matrix\n        \/\/ to see whether aa is really required.\n        if (!SkToBool(viewMatrix.getType() & ~(SkMatrix::kTranslate_Mask)) &&\n            SkScalarIsInt(viewMatrix.getTranslateX()) &&\n            SkScalarIsInt(viewMatrix.getTranslateY())) {\n            aa = GrAA::kNo;\n        }\n    }\n    bool complexStyle = !style.isSimpleFill();\n    if (complexStyle || GrAA::kYes == aa) {\n        SkPath path;\n        region.getBoundaryPath(&path);\n        path.setIsVolatile(true);\n\n        return this->drawPath(clip, std::move(paint), aa, viewMatrix, path, style);\n    }\n\n    GrAAType aaType = (this->numSamples() > 1) ? GrAAType::kMSAA : GrAAType::kNone;\n    GrOp::Owner op = RegionOp::Make(fContext, std::move(paint), viewMatrix, region, aaType, ss);\n    this->addDrawOp(clip, std::move(op));\n}\n\nvoid SurfaceDrawContext::drawOval(const GrClip* clip,\n                                  GrPaint&& paint,\n                                  GrAA aa,\n                                  const SkMatrix& viewMatrix,\n                                  const SkRect& oval,\n                                  const GrStyle& style) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawOval\", fContext);\n\n    const SkStrokeRec& stroke = style.strokeRec();\n\n    if (oval.isEmpty() && !style.pathEffect()) {\n        if (stroke.getStyle() == SkStrokeRec::kFill_Style) {\n            return;\n        }\n\n        this->drawRect(clip, std::move(paint), aa, viewMatrix, oval, &style);\n        return;\n    }\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    GrAAType aaType = this->chooseAAType(aa);\n\n    GrOp::Owner op;\n    if (aaType == GrAAType::kCoverage      &&\n        !fCanUseDynamicMSAA                &&\n        !this->caps()->reducedShaderMode() &&\n        oval.width() > SK_ScalarNearlyZero &&\n        oval.width() == oval.height()      &&\n        viewMatrix.isSimilarity()) {\n        \/\/ In specific cases we use a dedicated circle op to try and get better perf.\n        assert_alive(paint);\n        op = GrOvalOpFactory::MakeCircleOp(fContext, std::move(paint), viewMatrix, oval, style,\n                                           this->caps()->shaderCaps());\n    }\n    if (!op && style.isSimpleFill()) {\n        \/\/ FillRRectOp has special geometry and a fragment-shader branch to conditionally evaluate\n        \/\/ the arc equation. This same special geometry and fragment branch also turn out to be a\n        \/\/ substantial optimization for drawing ovals (namely, by not evaluating the arc equation\n        \/\/ inside the oval's inner diamond). Given these optimizations, it's a clear win to draw\n        \/\/ ovals the exact same way we do round rects.\n        assert_alive(paint);\n        op = FillRRectOp::Make(fContext, this->arenaAlloc(), std::move(paint), viewMatrix,\n                               SkRRect::MakeOval(oval), oval, GrAA(aaType != GrAAType::kNone));\n    }\n    if (!op && (aaType == GrAAType::kCoverage || fCanUseDynamicMSAA)) {\n        assert_alive(paint);\n        op = GrOvalOpFactory::MakeOvalOp(fContext, std::move(paint), viewMatrix, oval, style,\n                                         this->caps()->shaderCaps());\n    }\n    if (op) {\n        this->addDrawOp(clip, std::move(op));\n        return;\n    }\n\n    assert_alive(paint);\n    this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,\n                                     GrStyledShape(SkRRect::MakeOval(oval), SkPathDirection::kCW, 2,\n                                                   false, style, DoSimplify::kNo));\n}\n\nvoid SurfaceDrawContext::drawArc(const GrClip* clip,\n                                 GrPaint&& paint,\n                                 GrAA aa,\n                                 const SkMatrix& viewMatrix,\n                                 const SkRect& oval,\n                                 SkScalar startAngle,\n                                 SkScalar sweepAngle,\n                                 bool useCenter,\n                                 const GrStyle& style) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n            GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawArc\", fContext);\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    GrAAType aaType = this->chooseAAType(aa);\n    if (aaType == GrAAType::kCoverage) {\n        const GrShaderCaps* shaderCaps = this->caps()->shaderCaps();\n        GrOp::Owner op = GrOvalOpFactory::MakeArcOp(fContext,\n                                                    std::move(paint),\n                                                    viewMatrix,\n                                                    oval,\n                                                    startAngle,\n                                                    sweepAngle,\n                                                    useCenter,\n                                                    style,\n                                                    shaderCaps);\n        if (op) {\n            this->addDrawOp(clip, std::move(op));\n            return;\n        }\n        assert_alive(paint);\n    }\n    this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,\n                                     GrStyledShape::MakeArc(oval, startAngle, sweepAngle, useCenter,\n                                                            style, DoSimplify::kNo));\n}\n\nvoid SurfaceDrawContext::drawImageLattice(const GrClip* clip,\n                                          GrPaint&& paint,\n                                          const SkMatrix& viewMatrix,\n                                          GrSurfaceProxyView view,\n                                          SkAlphaType alphaType,\n                                          sk_sp<GrColorSpaceXform> csxf,\n                                          GrSamplerState::Filter filter,\n                                          std::unique_ptr<SkLatticeIter> iter,\n                                          const SkRect& dst) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawImageLattice\", fContext);\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    GrOp::Owner op =\n              LatticeOp::MakeNonAA(fContext, std::move(paint), viewMatrix, std::move(view),\n                                   alphaType, std::move(csxf), filter, std::move(iter), dst);\n    this->addDrawOp(clip, std::move(op));\n}\n\nvoid SurfaceDrawContext::drawDrawable(std::unique_ptr<SkDrawable::GpuDrawHandler> drawable,\n                                      const SkRect& bounds) {\n    GrOp::Owner op(DrawableOp::Make(fContext, std::move(drawable), bounds));\n    SkASSERT(op);\n    this->addOp(std::move(op));\n}\n\nvoid SurfaceDrawContext::setLastClip(uint32_t clipStackGenID,\n                                     const SkIRect& devClipBounds,\n                                     int numClipAnalyticElements) {\n    auto opsTask = this->getOpsTask();\n    opsTask->fLastClipStackGenID = clipStackGenID;\n    opsTask->fLastDevClipBounds = devClipBounds;\n    opsTask->fLastClipNumAnalyticElements = numClipAnalyticElements;\n}\n\nbool SurfaceDrawContext::mustRenderClip(uint32_t clipStackGenID,\n                                        const SkIRect& devClipBounds,\n                                        int numClipAnalyticElements) {\n    auto opsTask = this->getOpsTask();\n    return opsTask->fLastClipStackGenID != clipStackGenID ||\n           !opsTask->fLastDevClipBounds.contains(devClipBounds) ||\n           opsTask->fLastClipNumAnalyticElements != numClipAnalyticElements;\n}\n\nbool SurfaceDrawContext::waitOnSemaphores(int numSemaphores,\n                                          const GrBackendSemaphore waitSemaphores[],\n                                          bool deleteSemaphoresAfterWait) {\n    ASSERT_SINGLE_OWNER\n    RETURN_FALSE_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"waitOnSemaphores\", fContext);\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    if (numSemaphores && !this->caps()->semaphoreSupport()) {\n        return false;\n    }\n\n    auto direct = fContext->asDirectContext();\n    if (!direct) {\n        return false;\n    }\n\n    auto resourceProvider = direct->priv().resourceProvider();\n\n    GrWrapOwnership ownership =\n            deleteSemaphoresAfterWait ? kAdopt_GrWrapOwnership : kBorrow_GrWrapOwnership;\n\n    std::unique_ptr<std::unique_ptr<GrSemaphore>[]> grSemaphores(\n            new std::unique_ptr<GrSemaphore>[numSemaphores]);\n    for (int i = 0; i < numSemaphores; ++i) {\n        grSemaphores[i] = resourceProvider->wrapBackendSemaphore(waitSemaphores[i],\n                                                                 GrSemaphoreWrapType::kWillWait,\n                                                                 ownership);\n    }\n    this->drawingManager()->newWaitRenderTask(this->asSurfaceProxyRef(), std::move(grSemaphores),\n                                              numSemaphores);\n    return true;\n}\n\nvoid SurfaceDrawContext::drawPath(const GrClip* clip,\n                                  GrPaint&& paint,\n                                  GrAA aa,\n                                  const SkMatrix& viewMatrix,\n                                  const SkPath& path,\n                                  const GrStyle& style) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawPath\", fContext);\n\n    GrStyledShape shape(path, style, DoSimplify::kNo);\n    this->drawShape(clip, std::move(paint), aa, viewMatrix, std::move(shape));\n}\n\nvoid SurfaceDrawContext::drawShape(const GrClip* clip,\n                                   GrPaint&& paint,\n                                   GrAA aa,\n                                   const SkMatrix& viewMatrix,\n                                   GrStyledShape&& shape) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawShape\", fContext);\n\n    if (shape.isEmpty()) {\n        if (shape.inverseFilled()) {\n            this->drawPaint(clip, std::move(paint), viewMatrix);\n        }\n        return;\n    }\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    \/\/ If we get here in drawShape(), we definitely need to use path rendering\n    this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix, std::move(shape),\n                                     \/* attemptDrawSimple *\/ true);\n}\n\nstatic SkIRect get_clip_bounds(const SurfaceDrawContext* sdc, const GrClip* clip) {\n    return clip ? clip->getConservativeBounds() : SkIRect::MakeWH(sdc->width(), sdc->height());\n}\n\nbool SurfaceDrawContext::drawAndStencilPath(const GrHardClip* clip,\n                                            const GrUserStencilSettings* ss,\n                                            SkRegion::Op op,\n                                            bool invert,\n                                            GrAA aa,\n                                            const SkMatrix& viewMatrix,\n                                            const SkPath& path) {\n    ASSERT_SINGLE_OWNER\n    RETURN_FALSE_IF_ABANDONED\n    SkDEBUGCODE(this->validate();)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"drawAndStencilPath\", fContext);\n\n    if (path.isEmpty() && path.isInverseFillType()) {\n        GrPaint paint;\n        paint.setCoverageSetOpXPFactory(op, invert);\n        this->stencilRect(clip, ss, std::move(paint), GrAA::kNo, SkMatrix::I(),\n                          SkRect::Make(this->dimensions()));\n        return true;\n    }\n\n    AutoCheckFlush acf(this->drawingManager());\n\n    \/\/ An Assumption here is that path renderer would use some form of tweaking\n    \/\/ the src color (either the input alpha or in the frag shader) to implement\n    \/\/ aa. If we have some future driver-mojo path AA that can do the right\n    \/\/ thing WRT to the blend then we'll need some query on the PR.\n    GrAAType aaType = this->chooseAAType(aa);\n    bool hasUserStencilSettings = !ss->isUnused();\n\n    SkIRect clipConservativeBounds = get_clip_bounds(this, clip);\n\n    GrPaint paint;\n    paint.setCoverageSetOpXPFactory(op, invert);\n\n    GrStyledShape shape(path, GrStyle::SimpleFill());\n    PathRenderer::CanDrawPathArgs canDrawArgs;\n    canDrawArgs.fCaps = this->caps();\n    canDrawArgs.fProxy = this->asRenderTargetProxy();\n    canDrawArgs.fViewMatrix = &viewMatrix;\n    canDrawArgs.fShape = &shape;\n    canDrawArgs.fPaint = &paint;\n    canDrawArgs.fSurfaceProps = &fSurfaceProps;\n    canDrawArgs.fClipConservativeBounds = &clipConservativeBounds;\n    canDrawArgs.fAAType = aaType;\n    canDrawArgs.fHasUserStencilSettings = hasUserStencilSettings;\n\n    using DrawType = PathRendererChain::DrawType;\n\n    \/\/ Don't allow the SW renderer\n    auto pr = this->drawingManager()->getPathRenderer(canDrawArgs,\n                                                      false,\n                                                      DrawType::kStencilAndColor);\n    if (!pr) {\n        return false;\n    }\n\n    PathRenderer::DrawPathArgs args{this->drawingManager()->getContext(),\n                                    std::move(paint),\n                                    ss,\n                                    this,\n                                    clip,\n                                    &clipConservativeBounds,\n                                    &viewMatrix,\n                                    &shape,\n                                    aaType,\n                                    this->colorInfo().isLinearlyBlended()};\n    pr->drawPath(args);\n    return true;\n}\n\nSkBudgeted SurfaceDrawContext::isBudgeted() const {\n    ASSERT_SINGLE_OWNER\n\n    if (fContext->abandoned()) {\n        return SkBudgeted::kNo;\n    }\n\n    SkDEBUGCODE(this->validate();)\n\n    return this->asSurfaceProxy()->isBudgeted();\n}\n\nvoid SurfaceDrawContext::drawStrokedLine(const GrClip* clip,\n                                         GrPaint&& paint,\n                                         GrAA aa,\n                                         const SkMatrix& viewMatrix,\n                                         const SkPoint points[2],\n                                         const SkStrokeRec& stroke) {\n    ASSERT_SINGLE_OWNER\n\n    SkASSERT(stroke.getStyle() == SkStrokeRec::kStroke_Style);\n    SkASSERT(stroke.getWidth() > 0);\n    \/\/ Adding support for round capping would require a\n    \/\/ SurfaceDrawContext::fillRRectWithLocalMatrix entry point\n    SkASSERT(SkPaint::kRound_Cap != stroke.getCap());\n\n    const SkScalar halfWidth = 0.5f * stroke.getWidth();\n    if (halfWidth <= 0.f) {\n        \/\/ Prevents underflow when stroke width is epsilon > 0 (so technically not a hairline).\n        \/\/ The CTM would need to have a scale near 1\/epsilon in order for this to have meaningful\n        \/\/ coverage (although that would likely overflow elsewhere and cause the draw to drop due\n        \/\/ to non-finite bounds). At any other scale, this line is so thin, it's coverage is\n        \/\/ negligible, so discarding the draw is visually equivalent.\n        return;\n    }\n\n    SkVector parallel = points[1] - points[0];\n\n    if (!SkPoint::Normalize(&parallel)) {\n        parallel.fX = 1.0f;\n        parallel.fY = 0.0f;\n    }\n    parallel *= halfWidth;\n\n    SkVector ortho = { parallel.fY, -parallel.fX };\n    SkPoint p0 = points[0], p1 = points[1];\n    if (stroke.getCap() == SkPaint::kSquare_Cap) {\n        \/\/ Extra extension for square caps\n        p0 -= parallel;\n        p1 += parallel;\n    }\n\n    \/\/ If we are using dmsaa or reduced shader mode then attempt to draw with FillRRectOp.\n    if (this->caps()->drawInstancedSupport() &&\n        (this->alwaysAntialias() ||\n         (fContext->priv().caps()->reducedShaderMode() && aa == GrAA::kYes))) {\n        SkMatrix localMatrix = SkMatrix::MakeAll(p1.fX - p0.fX, ortho.fX, p0.fX,\n                                                 p1.fY - p0.fY, ortho.fY, p0.fY,\n                                                 0, 0, 1);\n        if (auto op = FillRRectOp::Make(fContext,\n                                        this->arenaAlloc(),\n                                        std::move(paint),\n                                        SkMatrix::Concat(viewMatrix, localMatrix),\n                                        SkRRect::MakeRect({0,-1,1,1}),\n                                        localMatrix,\n                                        GrAA::kYes)) {\n            this->addDrawOp(clip, std::move(op));\n            return;\n        }\n    }\n\n    \/\/ Order is TL, TR, BR, BL where arbitrarily \"down\" is p0 to p1 and \"right\" is positive\n    SkPoint corners[4] = { p0 - ortho,\n                           p0 + ortho,\n                           p1 + ortho,\n                           p1 - ortho };\n\n    GrQuadAAFlags edgeAA = (aa == GrAA::kYes) ? GrQuadAAFlags::kAll : GrQuadAAFlags::kNone;\n\n    assert_alive(paint);\n    this->fillQuadWithEdgeAA(clip, std::move(paint), aa, edgeAA, viewMatrix, corners, nullptr);\n}\n\nbool SurfaceDrawContext::drawSimpleShape(const GrClip* clip,\n                                         GrPaint* paint,\n                                         GrAA aa,\n                                         const SkMatrix& viewMatrix,\n                                         const GrStyledShape& shape) {\n    if (!shape.style().hasPathEffect()) {\n        GrAAType aaType = this->chooseAAType(aa);\n        SkPoint linePts[2];\n        SkRRect rrect;\n        \/\/ We can ignore the starting point and direction since there is no path effect.\n        bool inverted;\n        if (shape.asLine(linePts, &inverted) && !inverted &&\n            shape.style().strokeRec().getStyle() == SkStrokeRec::kStroke_Style &&\n            shape.style().strokeRec().getCap() != SkPaint::kRound_Cap) {\n            \/\/ The stroked line is an oriented rectangle, which looks the same or better (if\n            \/\/ perspective) compared to path rendering. The exception is subpixel\/hairline lines\n            \/\/ that are non-AA or MSAA, in which case the default path renderer achieves higher\n            \/\/ quality.\n            \/\/ FIXME(michaelludwig): If the fill rect op could take an external coverage, or checks\n            \/\/ for and outsets thin non-aa rects to 1px, the path renderer could be skipped.\n            SkScalar coverage;\n            if (aaType == GrAAType::kCoverage ||\n                !SkDrawTreatAAStrokeAsHairline(shape.style().strokeRec().getWidth(), viewMatrix,\n                                               &coverage)) {\n                this->drawStrokedLine(clip, std::move(*paint), aa, viewMatrix, linePts,\n                                      shape.style().strokeRec());\n                return true;\n            }\n        } else if (shape.asRRect(&rrect, nullptr, nullptr, &inverted) && !inverted) {\n            if (rrect.isRect()) {\n                this->drawRect(clip, std::move(*paint), aa, viewMatrix, rrect.rect(),\n                               &shape.style());\n                return true;\n            } else if (rrect.isOval()) {\n                this->drawOval(clip, std::move(*paint), aa, viewMatrix, rrect.rect(),\n                               shape.style());\n                return true;\n            }\n            this->drawRRect(clip, std::move(*paint), aa, viewMatrix, rrect, shape.style());\n            return true;\n        } else if (GrAAType::kCoverage == aaType &&\n                   shape.style().isSimpleFill()  &&\n                   viewMatrix.rectStaysRect()    &&\n                   !this->caps()->reducedShaderMode()) {\n            \/\/ TODO: the rectStaysRect restriction could be lifted if we were willing to apply the\n            \/\/ matrix to all the points individually rather than just to the rect\n            SkRect rects[2];\n            if (shape.asNestedRects(rects)) {\n                \/\/ Concave AA paths are expensive - try to avoid them for special cases\n                GrOp::Owner op = StrokeRectOp::MakeNested(fContext, std::move(*paint),\n                                                          viewMatrix, rects);\n                if (op) {\n                    this->addDrawOp(clip, std::move(op));\n                    return true;\n                }\n                \/\/ Fall through to let path renderer handle subpixel nested rects with unequal\n                \/\/ stroke widths along X\/Y.\n            }\n        }\n    }\n    return false;\n}\n\nvoid SurfaceDrawContext::drawShapeUsingPathRenderer(const GrClip* clip,\n                                                    GrPaint&& paint,\n                                                    GrAA aa,\n                                                    const SkMatrix& viewMatrix,\n                                                    GrStyledShape&& shape,\n                                                    bool attemptDrawSimple) {\n    ASSERT_SINGLE_OWNER\n    RETURN_IF_ABANDONED\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"internalDrawPath\", fContext);\n\n    if (!viewMatrix.isFinite() || !shape.bounds().isFinite()) {\n        return;\n    }\n\n    SkIRect clipConservativeBounds = get_clip_bounds(this, clip);\n\n    \/\/ Always allow paths to trigger DMSAA.\n    GrAAType aaType = fCanUseDynamicMSAA ? GrAAType::kMSAA : this->chooseAAType(aa);\n\n    PathRenderer::CanDrawPathArgs canDrawArgs;\n    canDrawArgs.fCaps = this->caps();\n    canDrawArgs.fProxy = this->asRenderTargetProxy();\n    canDrawArgs.fViewMatrix = &viewMatrix;\n    canDrawArgs.fShape = &shape;\n    canDrawArgs.fPaint = &paint;\n    canDrawArgs.fSurfaceProps = &fSurfaceProps;\n    canDrawArgs.fClipConservativeBounds = &clipConservativeBounds;\n    canDrawArgs.fHasUserStencilSettings = false;\n    canDrawArgs.fAAType = aaType;\n\n    constexpr static bool kDisallowSWPathRenderer = false;\n    constexpr static bool kAllowSWPathRenderer = true;\n    using DrawType = PathRendererChain::DrawType;\n\n    PathRenderer* pr = nullptr;\n\n    if (!shape.style().strokeRec().isFillStyle() && !shape.isEmpty()) {\n        \/\/ Give the tessellation path renderer a chance to claim this stroke before we simplify it.\n        PathRenderer* tess = this->drawingManager()->getTessellationPathRenderer();\n        if (tess && tess->canDrawPath(canDrawArgs) == PathRenderer::CanDrawPath::kYes) {\n            pr = tess;\n        }\n    }\n\n    if (!pr) {\n        \/\/ The shape isn't a stroke that can be drawn directly. Simplify if possible.\n        shape.simplify();\n\n        if (shape.isEmpty() && !shape.inverseFilled()) {\n            return;\n        }\n\n        if (attemptDrawSimple || shape.simplified()) {\n            \/\/ Usually we enter drawShapeUsingPathRenderer() because the shape+style was too complex\n            \/\/ for dedicated draw ops. However, if GrStyledShape was able to reduce something we\n            \/\/ ought to try again instead of going right to path rendering.\n            if (this->drawSimpleShape(clip, &paint, aa, viewMatrix, shape)) {\n                return;\n            }\n        }\n\n        \/\/ Try a 1st time without applying any of the style to the geometry (and barring sw)\n        pr = this->drawingManager()->getPathRenderer(canDrawArgs, kDisallowSWPathRenderer,\n                                                     DrawType::kColor);\n    }\n\n    SkScalar styleScale =  GrStyle::MatrixToScaleFactor(viewMatrix);\n    if (styleScale == 0.0f) {\n        return;\n    }\n\n    if (!pr && shape.style().pathEffect()) {\n        \/\/ It didn't work above, so try again with the path effect applied.\n        shape = shape.applyStyle(GrStyle::Apply::kPathEffectOnly, styleScale);\n        if (shape.isEmpty()) {\n            return;\n        }\n        pr = this->drawingManager()->getPathRenderer(canDrawArgs, kDisallowSWPathRenderer,\n                                                     DrawType::kColor);\n    }\n    if (!pr) {\n        if (shape.style().applies()) {\n            shape = shape.applyStyle(GrStyle::Apply::kPathEffectAndStrokeRec, styleScale);\n            if (shape.isEmpty()) {\n                return;\n            }\n            \/\/ This time, allow SW renderer\n            pr = this->drawingManager()->getPathRenderer(canDrawArgs, kAllowSWPathRenderer,\n                                                         DrawType::kColor);\n        } else {\n            pr = this->drawingManager()->getSoftwarePathRenderer();\n#if GR_PATH_RENDERER_SPEW\n            SkDebugf(\"falling back to: %s\\n\", pr->name());\n#endif\n        }\n    }\n\n    if (!pr) {\n#ifdef SK_DEBUG\n        SkDebugf(\"Unable to find path renderer compatible with path.\\n\");\n#endif\n        return;\n    }\n\n    PathRenderer::DrawPathArgs args{this->drawingManager()->getContext(),\n                                    std::move(paint),\n                                    &GrUserStencilSettings::kUnused,\n                                    this,\n                                    clip,\n                                    &clipConservativeBounds,\n                                    &viewMatrix,\n                                    canDrawArgs.fShape,\n                                    aaType,\n                                    this->colorInfo().isLinearlyBlended()};\n    pr->drawPath(args);\n}\n\nvoid SurfaceDrawContext::addDrawOp(const GrClip* clip,\n                                   GrOp::Owner op,\n                                   const std::function<WillAddOpFn>& willAddFn) {\n    ASSERT_SINGLE_OWNER\n    if (fContext->abandoned()) {\n        return;\n    }\n    GrDrawOp* drawOp = (GrDrawOp*)op.get();\n    SkDEBUGCODE(this->validate();)\n    SkDEBUGCODE(drawOp->fAddDrawOpCalled = true;)\n    GR_CREATE_TRACE_MARKER_CONTEXT(\"SurfaceDrawContext\", \"addDrawOp\", fContext);\n\n    \/\/ Setup clip\n    SkRect bounds;\n    op_bounds(&bounds, op.get());\n    GrAppliedClip appliedClip(this->dimensions(), this->asSurfaceProxy()->backingStoreDimensions());\n    const bool opUsesMSAA = drawOp->usesMSAA();\n    bool skipDraw = false;\n    if (clip) {\n        \/\/ Have a complex clip, so defer to its early clip culling\n        GrAAType aaType;\n        if (opUsesMSAA) {\n            aaType = GrAAType::kMSAA;\n        } else {\n            aaType = op->hasAABloat() ? GrAAType::kCoverage : GrAAType::kNone;\n        }\n        skipDraw = clip->apply(fContext, this, drawOp, aaType,\n                               &appliedClip, &bounds) == GrClip::Effect::kClippedOut;\n    } else {\n        \/\/ No clipping, so just clip the bounds against the logical render target dimensions\n        skipDraw = !bounds.intersect(this->asSurfaceProxy()->getBoundsRect());\n    }\n\n    if (skipDraw) {\n        return;\n    }\n\n    GrClampType clampType = GrColorTypeClampType(this->colorInfo().colorType());\n    GrProcessorSet::Analysis analysis = drawOp->finalize(*this->caps(), &appliedClip, clampType);\n\n    const bool opUsesStencil = drawOp->usesStencil();\n\n    \/\/ Always trigger DMSAA when there is stencil. This ensures stencil contents get properly\n    \/\/ preserved between render passes, if needed.\n    const bool drawNeedsMSAA = opUsesMSAA || (fCanUseDynamicMSAA && opUsesStencil);\n\n    \/\/ Must be called before setDstProxyView so that it sees the final bounds of the op.\n    op->setClippedBounds(bounds);\n\n    \/\/ Determine if the Op will trigger the use of a separate DMSAA attachment that requires manual\n    \/\/ resolves.\n    \/\/ TODO: Currently usesAttachmentIfDMSAA checks if this is a textureProxy or not. This check is\n    \/\/ really only for GL which uses a normal texture sampling when using barriers. For Vulkan it\n    \/\/ is possible to use the msaa buffer as an input attachment even if this is not a texture.\n    \/\/ However, support for that is not fully implemented yet in Vulkan. Once it is, this check\n    \/\/ should change to a virtual caps check that returns whether we need to break up an OpsTask\n    \/\/ if it has barriers and we are about to promote to MSAA.\n    bool usesAttachmentIfDMSAA =\n            fCanUseDynamicMSAA &&\n            (!this->caps()->msaaResolvesAutomatically() || !this->asTextureProxy());\n    bool opRequiresDMSAAAttachment = usesAttachmentIfDMSAA && drawNeedsMSAA;\n    bool opTriggersDMSAAAttachment =\n            opRequiresDMSAAAttachment && !this->getOpsTask()->usesMSAASurface();\n    if (opTriggersDMSAAAttachment) {\n        \/\/ This will be the op that actually triggers use of a DMSAA attachment. Texture barriers\n        \/\/ can't be moved to a DMSAA attachment, so if there already are any on the current opsTask\n        \/\/ then we need to split.\n        if (this->getOpsTask()->renderPassXferBarriers() & GrXferBarrierFlags::kTexture) {\n            SkASSERT(!this->getOpsTask()->isColorNoOp());\n            this->replaceOpsTask()->setCannotMergeBackward();\n        }\n    }\n\n    GrDstProxyView dstProxyView;\n    if (analysis.requiresDstTexture()) {\n        if (!this->setupDstProxyView(drawOp->bounds(), drawNeedsMSAA, &dstProxyView)) {\n            return;\n        }\n#ifdef SK_DEBUG\n        if (fCanUseDynamicMSAA && drawNeedsMSAA && !this->caps()->msaaResolvesAutomatically()) {\n            \/\/ Since we aren't literally writing to the render target texture while using a DMSAA\n            \/\/ attachment, we need to resolve that texture before sampling it. Ensure the current\n            \/\/ opsTask got closed off in order to initiate an implicit resolve.\n            SkASSERT(this->getOpsTask()->isEmpty());\n        }\n#endif\n    }\n\n    auto opsTask = this->getOpsTask();\n    if (willAddFn) {\n        willAddFn(op.get(), opsTask->uniqueID());\n    }\n\n    \/\/ Note if the op needs stencil. Stencil clipping already called setNeedsStencil for itself, if\n    \/\/ needed.\n    if (opUsesStencil) {\n        this->setNeedsStencil();\n    }\n\n#if GR_GPU_STATS && GR_TEST_UTILS\n    if (fCanUseDynamicMSAA && drawNeedsMSAA) {\n        if (!opsTask->usesMSAASurface()) {\n            fContext->priv().dmsaaStats().fNumMultisampleRenderPasses++;\n        }\n        fContext->priv().dmsaaStats().fTriggerCounts[op->name()]++;\n    }\n#endif\n\n    opsTask->addDrawOp(this->drawingManager(), std::move(op), drawNeedsMSAA, analysis,\n                       std::move(appliedClip), dstProxyView,\n                       GrTextureResolveManager(this->drawingManager()), *this->caps());\n\n#ifdef SK_DEBUG\n    if (fCanUseDynamicMSAA && drawNeedsMSAA) {\n        SkASSERT(opsTask->usesMSAASurface());\n    }\n#endif\n}\n\nbool SurfaceDrawContext::setupDstProxyView(const SkRect& opBounds,\n                                           bool opRequiresMSAA,\n                                           GrDstProxyView* dstProxyView) {\n    \/\/ If we are wrapping a vulkan secondary command buffer, we can't make a dst copy because we\n    \/\/ don't actually have a VkImage to make a copy of. Additionally we don't have the power to\n    \/\/ start and stop the render pass in order to make the copy.\n    if (this->asRenderTargetProxy()->wrapsVkSecondaryCB()) {\n        return false;\n    }\n\n    \/\/ First get the dstSampleFlags as if we will put the draw into the current OpsTask\n    auto dstSampleFlags = this->caps()->getDstSampleFlagsForProxy(\n            this->asRenderTargetProxy(), this->getOpsTask()->usesMSAASurface() || opRequiresMSAA);\n\n    \/\/ If we don't have barriers for this draw then we will definitely be breaking up the OpsTask.\n    \/\/ However, if using dynamic MSAA, the new OpsTask will not have MSAA already enabled on it\n    \/\/ and that may allow us to use texture barriers. So we check if we can use barriers on the new\n    \/\/ ops task and then break it up if so.\n    if (!(dstSampleFlags & GrDstSampleFlags::kRequiresTextureBarrier) &&\n        fCanUseDynamicMSAA && this->getOpsTask()->usesMSAASurface() && !opRequiresMSAA) {\n        auto newFlags =\n                this->caps()->getDstSampleFlagsForProxy(this->asRenderTargetProxy(),\n                                                        false\/*=opRequiresMSAA*\/);\n        if (newFlags & GrDstSampleFlags::kRequiresTextureBarrier) {\n            \/\/ We can't have an empty ops task if we are in DMSAA and the ops task already returns\n            \/\/ true for usesMSAASurface.\n            SkASSERT(!this->getOpsTask()->isColorNoOp());\n            this->replaceOpsTask()->setCannotMergeBackward();\n            dstSampleFlags = newFlags;\n        }\n    }\n\n    if (dstSampleFlags & GrDstSampleFlags::kRequiresTextureBarrier) {\n        \/\/ If we require a barrier to sample the dst it means we are sampling the RT itself\n        \/\/ either as a texture or input attachment. In this case we don't need to break up the\n        \/\/ OpsTask.\n        dstProxyView->setProxyView(this->readSurfaceView());\n        dstProxyView->setOffset(0, 0);\n        dstProxyView->setDstSampleFlags(dstSampleFlags);\n        return true;\n    }\n    SkASSERT(dstSampleFlags == GrDstSampleFlags::kNone);\n\n    \/\/ We are using a different surface from the main color attachment to sample the dst from. If we\n    \/\/ are in DMSAA we can just use the single sampled RT texture itself. Otherwise, we must do a\n    \/\/ copy.\n    \/\/ We do have to check if we ended up here becasue we don't have texture barriers but do have\n    \/\/ msaaResolvesAutomatically (i.e. render-to-msaa-texture). In that case there will be no op or\n    \/\/ barrier between draws to flush the render target before being used as a texture in the next\n    \/\/ draw. So in that case we just fall through to doing a copy.\n    if (fCanUseDynamicMSAA && opRequiresMSAA && this->asTextureProxy() &&\n        !this->caps()->msaaResolvesAutomatically() &&\n        this->caps()->dmsaaResolveCanBeUsedAsTextureInSameRenderPass()) {\n        this->replaceOpsTaskIfModifiesColor()->setCannotMergeBackward();\n        dstProxyView->setProxyView(this->readSurfaceView());\n        dstProxyView->setOffset(0, 0);\n        dstProxyView->setDstSampleFlags(dstSampleFlags);\n        return true;\n    }\n\n    \/\/ Now we fallback to doing a copy.\n\n    GrColorType colorType = this->colorInfo().colorType();\n    \/\/ MSAA consideration: When there is support for reading MSAA samples in the shader we could\n    \/\/ have per-sample dst values by making the copy multisampled.\n    GrCaps::DstCopyRestrictions restrictions = this->caps()->getDstCopyRestrictions(\n            this->asRenderTargetProxy(), colorType);\n\n    SkIRect copyRect = SkIRect::MakeSize(this->asSurfaceProxy()->backingStoreDimensions());\n    if (!restrictions.fMustCopyWholeSrc) {\n        \/\/ If we don't need the whole source, restrict to the op's bounds. We add an extra pixel\n        \/\/ of padding to account for AA bloat and the unpredictable rounding of coords near pixel\n        \/\/ centers during rasterization.\n        SkIRect conservativeDrawBounds = opBounds.roundOut();\n        conservativeDrawBounds.outset(1, 1);\n        SkAssertResult(copyRect.intersect(conservativeDrawBounds));\n    }\n\n    SkIPoint dstOffset;\n    SkBackingFit fit;\n    if (restrictions.fRectsMustMatch == GrSurfaceProxy::RectsMustMatch::kYes) {\n        dstOffset = {0, 0};\n        fit = SkBackingFit::kExact;\n    } else {\n        dstOffset = {copyRect.fLeft, copyRect.fTop};\n        fit = SkBackingFit::kApprox;\n    }\n    auto copy = GrSurfaceProxy::Copy(fContext,\n                                     this->asSurfaceProxyRef(),\n                                     this->origin(),\n                                     GrMipmapped::kNo,\n                                     copyRect,\n                                     fit,\n                                     SkBudgeted::kYes,\n                                     restrictions.fRectsMustMatch);\n    SkASSERT(copy);\n\n    dstProxyView->setProxyView({std::move(copy), this->origin(), this->readSwizzle()});\n    dstProxyView->setOffset(dstOffset);\n    dstProxyView->setDstSampleFlags(dstSampleFlags);\n    return true;\n}\n\nOpsTask* SurfaceDrawContext::replaceOpsTaskIfModifiesColor() {\n    if (!this->getOpsTask()->isColorNoOp()) {\n        this->replaceOpsTask();\n    }\n    return this->getOpsTask();\n}\n\n} \/\/ namespace skgpu::v1\n","avg_line_length":46.441958042,"max_line_length":108,"alphanum_fraction":0.5734505812,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1401,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/**\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"Reachability.h\"\n\n#include <ostream>\n\n#include \"Creators.h\"\n#include \"Debug.h\"\n#include \"DexAnnotation.h\"\n#include \"DexClass.h\"\n#include \"RedexContext.h\"\n\nusing namespace reachability;\n\nstd::unique_ptr<ReachableObjectGraph> generate_graph() {\n  auto graph = std::make_unique<ReachableObjectGraph>();\n  auto seed = ReachableObject();\n\n  ClassCreator cc(DexType::make_type(\"LFoo;\"));\n  cc.set_super(get_object_type());\n  auto cls = ReachableObject(cc.create());\n\n  auto field = ReachableObject(DexField::make_field(\"LFoo;.field1:I\"));\n  auto method = ReachableObject(DexMethod::make_method(\"LFoo;.method1:()I\"));\n  auto anno = ReachableObject(\n      new DexAnnotation(DexType::make_type(\"LAnno;\"), DAV_RUNTIME));\n\n  graph->emplace(cls, ReachableObjectSet{seed});\n  graph->emplace(anno, ReachableObjectSet{cls});\n  graph->emplace(method, ReachableObjectSet{cls});\n  graph->emplace(field, ReachableObjectSet{method});\n  return graph;\n}\n\nint main(int argc, char** argv) {\n  always_assert(argc == 2);\n  const auto* outfile = argv[1];\n\n  g_redex = new RedexContext();\n\n  const auto& graph = generate_graph();\n  std::ofstream os;\n  os.open(outfile);\n  dump_graph(os, *graph);\n\n  delete g_redex;\n\n  return 0;\n}\n","avg_line_length":25.4727272727,"max_line_length":77,"alphanum_fraction":0.715917202,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13408,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":14.0,"content":"\/\/ Copyright (c) 2011-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <qt\/transactiondesc.h>\n\n#include <qt\/magpiecoinunits.h>\n#include <qt\/guiutil.h>\n#include <qt\/paymentserver.h>\n#include <qt\/transactionrecord.h>\n\n#include <consensus\/consensus.h>\n#include <interfaces\/node.h>\n#include <key_io.h>\n#include <validation.h>\n#include <script\/script.h>\n#include <timedata.h>\n#include <util.h>\n#include <wallet\/db.h>\n#include <wallet\/wallet.h>\n#include <policy\/policy.h>\n\n#include <stdint.h>\n#include <string>\n\nQString TransactionDesc::FormatTxStatus(const interfaces::WalletTx& wtx, const interfaces::WalletTxStatus& status, bool inMempool, int numBlocks, int64_t adjustedTime)\n{\n    if (!status.is_final)\n    {\n        if (wtx.tx->nLockTime < LOCKTIME_THRESHOLD)\n            return tr(\"Open for %n more block(s)\", \"\", wtx.tx->nLockTime - numBlocks);\n        else\n            return tr(\"Open until %1\").arg(GUIUtil::dateTimeStr(wtx.tx->nLockTime));\n    }\n    else\n    {\n        int nDepth = status.depth_in_main_chain;\n        if (nDepth < 0)\n            return tr(\"conflicted with a transaction with %1 confirmations\").arg(-nDepth);\n        else if (nDepth == 0)\n            return tr(\"0\/unconfirmed, %1\").arg((inMempool ? tr(\"in memory pool\") : tr(\"not in memory pool\"))) + (status.is_abandoned ? \", \"+tr(\"abandoned\") : \"\");\n        else if (nDepth < 6)\n            return tr(\"%1\/unconfirmed\").arg(nDepth);\n        else\n            return tr(\"%1 confirmations\").arg(nDepth);\n    }\n}\n\nQString TransactionDesc::toHTML(interfaces::Node& node, interfaces::Wallet& wallet, TransactionRecord *rec, int unit)\n{\n    int numBlocks;\n    int64_t adjustedTime;\n    interfaces::WalletTxStatus status;\n    interfaces::WalletOrderForm orderForm;\n    bool inMempool;\n    interfaces::WalletTx wtx = wallet.getWalletTxDetails(rec->hash, status, orderForm, inMempool, numBlocks, adjustedTime);\n\n    QString strHTML;\n\n    strHTML.reserve(4000);\n    strHTML += \"<html><font face='verdana, arial, helvetica, sans-serif'>\";\n\n    int64_t nTime = wtx.time;\n    CAmount nCredit = wtx.credit;\n    CAmount nDebit = wtx.debit;\n    CAmount nNet = nCredit - nDebit;\n\n    strHTML += \"<b>\" + tr(\"Status\") + \":<\/b> \" + FormatTxStatus(wtx, status, inMempool, numBlocks, adjustedTime);\n    strHTML += \"<br>\";\n\n    strHTML += \"<b>\" + tr(\"Date\") + \":<\/b> \" + (nTime ? GUIUtil::dateTimeStr(nTime) : \"\") + \"<br>\";\n\n    \/\/\n    \/\/ From\n    \/\/\n    if (wtx.is_coinbase)\n    {\n        strHTML += \"<b>\" + tr(\"Source\") + \":<\/b> \" + tr(\"Generated\") + \"<br>\";\n    }\n    else if (wtx.value_map.count(\"from\") && !wtx.value_map[\"from\"].empty())\n    {\n        \/\/ Online transaction\n        strHTML += \"<b>\" + tr(\"From\") + \":<\/b> \" + GUIUtil::HtmlEscape(wtx.value_map[\"from\"]) + \"<br>\";\n    }\n    else\n    {\n        \/\/ Offline transaction\n        if (nNet > 0)\n        {\n            \/\/ Credit\n            CTxDestination address = DecodeDestination(rec->address);\n            if (IsValidDestination(address)) {\n                std::string name;\n                isminetype ismine;\n                if (wallet.getAddress(address, &name, &ismine, \/* purpose= *\/ nullptr))\n                {\n                    strHTML += \"<b>\" + tr(\"From\") + \":<\/b> \" + tr(\"unknown\") + \"<br>\";\n                    strHTML += \"<b>\" + tr(\"To\") + \":<\/b> \";\n                    strHTML += GUIUtil::HtmlEscape(rec->address);\n                    QString addressOwned = ismine == ISMINE_SPENDABLE ? tr(\"own address\") : tr(\"watch-only\");\n                    if (!name.empty())\n                        strHTML += \" (\" + addressOwned + \", \" + tr(\"label\") + \": \" + GUIUtil::HtmlEscape(name) + \")\";\n                    else\n                        strHTML += \" (\" + addressOwned + \")\";\n                    strHTML += \"<br>\";\n                }\n            }\n        }\n    }\n\n    \/\/\n    \/\/ To\n    \/\/\n    if (wtx.value_map.count(\"to\") && !wtx.value_map[\"to\"].empty())\n    {\n        \/\/ Online transaction\n        std::string strAddress = wtx.value_map[\"to\"];\n        strHTML += \"<b>\" + tr(\"To\") + \":<\/b> \";\n        CTxDestination dest = DecodeDestination(strAddress);\n        std::string name;\n        if (wallet.getAddress(\n                dest, &name, \/* is_mine= *\/ nullptr, \/* purpose= *\/ nullptr) && !name.empty())\n            strHTML += GUIUtil::HtmlEscape(name) + \" \";\n        strHTML += GUIUtil::HtmlEscape(strAddress) + \"<br>\";\n    }\n\n    \/\/\n    \/\/ Amount\n    \/\/\n    if (wtx.is_coinbase && nCredit == 0)\n    {\n        \/\/\n        \/\/ Coinbase\n        \/\/\n        CAmount nUnmatured = 0;\n        for (const CTxOut& txout : wtx.tx->vout)\n            nUnmatured += wallet.getCredit(txout, ISMINE_ALL);\n        strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \";\n        if (status.is_in_main_chain)\n            strHTML += MagpieCoinUnits::formatHtmlWithUnit(unit, nUnmatured)+ \" (\" + tr(\"matures in %n more block(s)\", \"\", status.blocks_to_maturity) + \")\";\n        else\n            strHTML += \"(\" + tr(\"not accepted\") + \")\";\n        strHTML += \"<br>\";\n    }\n    else if (nNet > 0)\n    {\n        \/\/\n        \/\/ Credit\n        \/\/\n        strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \" + MagpieCoinUnits::formatHtmlWithUnit(unit, nNet) + \"<br>\";\n    }\n    else\n    {\n        isminetype fAllFromMe = ISMINE_SPENDABLE;\n        for (isminetype mine : wtx.txin_is_mine)\n        {\n            if(fAllFromMe > mine) fAllFromMe = mine;\n        }\n\n        isminetype fAllToMe = ISMINE_SPENDABLE;\n        for (isminetype mine : wtx.txout_is_mine)\n        {\n            if(fAllToMe > mine) fAllToMe = mine;\n        }\n\n        if (fAllFromMe)\n        {\n            if(fAllFromMe & ISMINE_WATCH_ONLY)\n                strHTML += \"<b>\" + tr(\"From\") + \":<\/b> \" + tr(\"watch-only\") + \"<br>\";\n\n            \/\/\n            \/\/ Debit\n            \/\/\n            auto mine = wtx.txout_is_mine.begin();\n            for (const CTxOut& txout : wtx.tx->vout)\n            {\n                \/\/ Ignore change\n                isminetype toSelf = *(mine++);\n                if ((toSelf == ISMINE_SPENDABLE) && (fAllFromMe == ISMINE_SPENDABLE))\n                    continue;\n\n                if (!wtx.value_map.count(\"to\") || wtx.value_map[\"to\"].empty())\n                {\n                    \/\/ Offline transaction\n                    CTxDestination address;\n                    if (ExtractDestination(txout.scriptPubKey, address))\n                    {\n                        strHTML += \"<b>\" + tr(\"To\") + \":<\/b> \";\n                        std::string name;\n                        if (wallet.getAddress(\n                                address, &name, \/* is_mine= *\/ nullptr, \/* purpose= *\/ nullptr) && !name.empty())\n                            strHTML += GUIUtil::HtmlEscape(name) + \" \";\n                        strHTML += GUIUtil::HtmlEscape(EncodeDestination(address));\n                        if(toSelf == ISMINE_SPENDABLE)\n                            strHTML += \" (own address)\";\n                        else if(toSelf & ISMINE_WATCH_ONLY)\n                            strHTML += \" (watch-only)\";\n                        strHTML += \"<br>\";\n                    }\n                }\n\n                strHTML += \"<b>\" + tr(\"Debit\") + \":<\/b> \" + MagpieCoinUnits::formatHtmlWithUnit(unit, -txout.nValue) + \"<br>\";\n                if(toSelf)\n                    strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \" + MagpieCoinUnits::formatHtmlWithUnit(unit, txout.nValue) + \"<br>\";\n            }\n\n            if (fAllToMe)\n            {\n                \/\/ Payment to self\n                CAmount nChange = wtx.change;\n                CAmount nValue = nCredit - nChange;\n                strHTML += \"<b>\" + tr(\"Total debit\") + \":<\/b> \" + MagpieCoinUnits::formatHtmlWithUnit(unit, -nValue) + \"<br>\";\n                strHTML += \"<b>\" + tr(\"Total credit\") + \":<\/b> \" + MagpieCoinUnits::formatHtmlWithUnit(unit, nValue) + \"<br>\";\n            }\n\n            CAmount nTxFee = nDebit - wtx.tx->GetValueOut();\n            if (nTxFee > 0)\n                strHTML += \"<b>\" + tr(\"Transaction fee\") + \":<\/b> \" + MagpieCoinUnits::formatHtmlWithUnit(unit, -nTxFee) + \"<br>\";\n        }\n        else\n        {\n            \/\/\n            \/\/ Mixed debit transaction\n            \/\/\n            auto mine = wtx.txin_is_mine.begin();\n            for (const CTxIn& txin : wtx.tx->vin) {\n                if (*(mine++)) {\n                    strHTML += \"<b>\" + tr(\"Debit\") + \":<\/b> \" + MagpieCoinUnits::formatHtmlWithUnit(unit, -wallet.getDebit(txin, ISMINE_ALL)) + \"<br>\";\n                }\n            }\n            mine = wtx.txout_is_mine.begin();\n            for (const CTxOut& txout : wtx.tx->vout) {\n                if (*(mine++)) {\n                    strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \" + MagpieCoinUnits::formatHtmlWithUnit(unit, wallet.getCredit(txout, ISMINE_ALL)) + \"<br>\";\n                }\n            }\n        }\n    }\n\n    strHTML += \"<b>\" + tr(\"Net amount\") + \":<\/b> \" + MagpieCoinUnits::formatHtmlWithUnit(unit, nNet, true) + \"<br>\";\n\n    \/\/\n    \/\/ Message\n    \/\/\n    if (wtx.value_map.count(\"message\") && !wtx.value_map[\"message\"].empty())\n        strHTML += \"<br><b>\" + tr(\"Message\") + \":<\/b><br>\" + GUIUtil::HtmlEscape(wtx.value_map[\"message\"], true) + \"<br>\";\n    if (wtx.value_map.count(\"comment\") && !wtx.value_map[\"comment\"].empty())\n        strHTML += \"<br><b>\" + tr(\"Comment\") + \":<\/b><br>\" + GUIUtil::HtmlEscape(wtx.value_map[\"comment\"], true) + \"<br>\";\n\n    strHTML += \"<b>\" + tr(\"Transaction ID\") + \":<\/b> \" + rec->getTxHash() + \"<br>\";\n    strHTML += \"<b>\" + tr(\"Transaction total size\") + \":<\/b> \" + QString::number(wtx.tx->GetTotalSize()) + \" bytes<br>\";\n    strHTML += \"<b>\" + tr(\"Transaction virtual size\") + \":<\/b> \" + QString::number(GetVirtualTransactionSize(*wtx.tx)) + \" bytes<br>\";\n    strHTML += \"<b>\" + tr(\"Output index\") + \":<\/b> \" + QString::number(rec->getOutputIndex()) + \"<br>\";\n\n    \/\/ Message from normal magpiecoin:URI (magpiecoin:123...?message=example)\n    for (const std::pair<std::string, std::string>& r : orderForm)\n        if (r.first == \"Message\")\n            strHTML += \"<br><b>\" + tr(\"Message\") + \":<\/b><br>\" + GUIUtil::HtmlEscape(r.second, true) + \"<br>\";\n\n    \/\/\n    \/\/ PaymentRequest info:\n    \/\/\n    for (const std::pair<std::string, std::string>& r : orderForm)\n    {\n        if (r.first == \"PaymentRequest\")\n        {\n            PaymentRequestPlus req;\n            req.parse(QByteArray::fromRawData(r.second.data(), r.second.size()));\n            QString merchant;\n            if (req.getMerchant(PaymentServer::getCertStore(), merchant))\n                strHTML += \"<b>\" + tr(\"Merchant\") + \":<\/b> \" + GUIUtil::HtmlEscape(merchant) + \"<br>\";\n        }\n    }\n\n    if (wtx.is_coinbase)\n    {\n        quint32 numBlocksToMaturity = COINBASE_MATURITY +  1;\n        strHTML += \"<br>\" + tr(\"Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \\\"not accepted\\\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.\").arg(QString::number(numBlocksToMaturity)) + \"<br>\";\n    }\n\n    \/\/\n    \/\/ Debug view\n    \/\/\n    if (node.getLogCategories() != BCLog::NONE)\n    {\n        strHTML += \"<hr><br>\" + tr(\"Debug information\") + \"<br><br>\";\n        for (const CTxIn& txin : wtx.tx->vin)\n            if(wallet.txinIsMine(txin))\n                strHTML += \"<b>\" + tr(\"Debit\") + \":<\/b> \" + MagpieCoinUnits::formatHtmlWithUnit(unit, -wallet.getDebit(txin, ISMINE_ALL)) + \"<br>\";\n        for (const CTxOut& txout : wtx.tx->vout)\n            if(wallet.txoutIsMine(txout))\n                strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \" + MagpieCoinUnits::formatHtmlWithUnit(unit, wallet.getCredit(txout, ISMINE_ALL)) + \"<br>\";\n\n        strHTML += \"<br><b>\" + tr(\"Transaction\") + \":<\/b><br>\";\n        strHTML += GUIUtil::HtmlEscape(wtx.tx->ToString(), true);\n\n        strHTML += \"<br><b>\" + tr(\"Inputs\") + \":<\/b>\";\n        strHTML += \"<ul>\";\n\n        for (const CTxIn& txin : wtx.tx->vin)\n        {\n            COutPoint prevout = txin.prevout;\n\n            Coin prev;\n            if(node.getUnspentOutput(prevout, prev))\n            {\n                {\n                    strHTML += \"<li>\";\n                    const CTxOut &vout = prev.out;\n                    CTxDestination address;\n                    if (ExtractDestination(vout.scriptPubKey, address))\n                    {\n                        std::string name;\n                        if (wallet.getAddress(address, &name, \/* is_mine= *\/ nullptr, \/* purpose= *\/ nullptr) && !name.empty())\n                            strHTML += GUIUtil::HtmlEscape(name) + \" \";\n                        strHTML += QString::fromStdString(EncodeDestination(address));\n                    }\n                    strHTML = strHTML + \" \" + tr(\"Amount\") + \"=\" + MagpieCoinUnits::formatHtmlWithUnit(unit, vout.nValue);\n                    strHTML = strHTML + \" IsMine=\" + (wallet.txoutIsMine(vout) & ISMINE_SPENDABLE ? tr(\"true\") : tr(\"false\")) + \"<\/li>\";\n                    strHTML = strHTML + \" IsWatchOnly=\" + (wallet.txoutIsMine(vout) & ISMINE_WATCH_ONLY ? tr(\"true\") : tr(\"false\")) + \"<\/li>\";\n                }\n            }\n        }\n\n        strHTML += \"<\/ul>\";\n    }\n\n    strHTML += \"<\/font><\/html>\";\n    return strHTML;\n}\n","avg_line_length":40.5075528701,"max_line_length":442,"alphanum_fraction":0.5132756563,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":21161,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":575.0,"content":"\/\/ Copyright 2018 Proyectos y Sistemas de Mantenimiento SL (eProsima).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <fastrtps\/types\/MemberDescriptor.h>\n#include <fastrtps\/types\/DynamicType.h>\n#include <fastrtps\/types\/TypeDescriptor.h>\n#include <fastrtps\/types\/AnnotationDescriptor.h>\n#include <fastrtps\/types\/DynamicTypeBuilderFactory.h>\n#include <fastdds\/dds\/log\/Log.hpp>\n\nnamespace eprosima {\nnamespace fastrtps {\nnamespace types {\n\nMemberDescriptor::MemberDescriptor()\n    : name_(\"\")\n    , id_(MEMBER_ID_INVALID)\n    , type_(nullptr)\n    , default_value_(\"\")\n    , index_(INDEX_INVALID)\n    , default_label_(false)\n{\n}\n\nMemberDescriptor::MemberDescriptor(\n        uint32_t index,\n        const std::string& name)\n    : name_(name)\n    , id_(MEMBER_ID_INVALID)\n    , type_(nullptr)\n    , default_value_(\"\")\n    , index_(index)\n    , default_label_(false)\n{\n}\n\nMemberDescriptor::MemberDescriptor(\n        const MemberDescriptor* descriptor)\n    : name_(\"\")\n    , id_(MEMBER_ID_INVALID)\n    , type_(nullptr)\n    , default_value_(\"\")\n    , index_(INDEX_INVALID)\n    , default_label_(false)\n{\n    copy_from(descriptor);\n}\n\nMemberDescriptor::MemberDescriptor(\n        MemberId id,\n        const std::string& name,\n        DynamicType_ptr type_)\n    : name_(name)\n    , id_(id)\n    , type_(type_)\n    , default_value_(\"\")\n    , index_(INDEX_INVALID)\n    , default_label_(false)\n{\n\n}\n\nMemberDescriptor::MemberDescriptor(\n        MemberId id,\n        const std::string& name,\n        DynamicType_ptr type_,\n        const std::string& defaultValue)\n    : name_(name)\n    , id_(id)\n    , type_(type_)\n    , default_value_(defaultValue)\n    , index_(INDEX_INVALID)\n    , default_label_(false)\n{\n}\n\nMemberDescriptor::MemberDescriptor(\n        MemberId id,\n        const std::string& name,\n        DynamicType_ptr type_,\n        const std::string& defaultValue,\n        const std::vector<uint64_t>& unionLabels,\n        bool isDefaultLabel)\n    : name_(name)\n    , id_(id)\n    , type_(type_)\n    , default_value_(defaultValue)\n    , index_(INDEX_INVALID)\n    , default_label_(isDefaultLabel)\n{\n    labels_ = unionLabels;\n}\n\nMemberDescriptor::~MemberDescriptor()\n{\n    for (auto it = annotation_.begin(); it != annotation_.end(); ++it)\n    {\n        delete *it;\n    }\n    annotation_.clear();\n    type_ = nullptr;\n}\n\nvoid MemberDescriptor::add_union_case_index(\n        uint64_t value)\n{\n    labels_.push_back(value);\n}\n\nbool MemberDescriptor::check_union_labels(\n        const std::vector<uint64_t>& labels) const\n{\n    for (auto it = labels.begin(); it != labels.end(); ++it)\n    {\n        if (std::find(labels_.begin(), labels_.end(), *it) != labels_.end())\n        {\n            return false;\n        }\n    }\n    return true;\n}\n\nReturnCode_t MemberDescriptor::copy_from(\n        const MemberDescriptor* other)\n{\n    if (other != nullptr)\n    {\n        try\n        {\n            \/\/ Clear annotations\n            for (auto it = annotation_.begin(); it != annotation_.end(); ++it)\n            {\n                delete *it;\n            }\n            annotation_.clear();\n\n            \/\/ Copy them\n            for (auto it = other->annotation_.begin(); it != other->annotation_.end(); ++it)\n            {\n                AnnotationDescriptor* newDescriptor = new AnnotationDescriptor(*it);\n                annotation_.push_back(newDescriptor);\n            }\n\n            type_ = other->type_;\n            name_ = other->name_;\n            id_ = other->id_;\n            default_value_ = other->default_value_;\n            index_ = other->index_;\n            default_label_ = other->default_label_;\n            labels_ = other->labels_;\n            return ReturnCode_t::RETCODE_OK;\n        }\n        catch (std::exception& \/*e*\/)\n        {\n            return ReturnCode_t::RETCODE_ERROR;\n        }\n    }\n    else\n    {\n        logError(DYN_TYPES, \"Error copying MemberDescriptor, invalid input descriptor\");\n        return ReturnCode_t::RETCODE_BAD_PARAMETER;\n    }\n}\n\nbool MemberDescriptor::equals(\n        const MemberDescriptor* other) const\n{\n    if (other != nullptr && name_ == other->name_ && id_ == other->id_ &&\n            ((type_ == nullptr && other->type_ == nullptr) || type_->equals(other->type_.get())) &&\n            default_value_ == other->default_value_ && index_ == other->index_ &&\n            default_label_ == other->default_label_ &&\n            labels_.size() == other->labels_.size())\n    {\n        for (auto it = labels_.begin(), it2 = other->labels_.begin(); it != labels_.end(); ++it, ++it2)\n        {\n            if (*it != *it2)\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n    return false;\n}\n\nMemberId MemberDescriptor::get_id() const\n{\n    return id_;\n}\n\nuint32_t MemberDescriptor::get_index() const\n{\n    return index_;\n}\n\nTypeKind MemberDescriptor::get_kind() const\n{\n    if (type_ != nullptr)\n    {\n        return type_->get_kind();\n    }\n    return 0;\n}\n\nstd::string MemberDescriptor::get_name() const\n{\n    return name_;\n}\n\nstd::vector<uint64_t> MemberDescriptor::get_union_labels() const\n{\n    return labels_;\n}\n\nbool MemberDescriptor::is_consistent(\n        TypeKind parentKind) const\n{\n    \/\/ The type field is mandatory in every type except bitmasks and enums.\n    if ((parentKind != TK_BITMASK && parentKind != TK_ENUM) && type_ == nullptr)\n    {\n        return false;\n    }\n\n    \/\/ Only aggregated types must use the ID value.\n    if (id_ != MEMBER_ID_INVALID && parentKind != TK_UNION && parentKind != TK_STRUCTURE &&\n            parentKind != TK_BITSET && parentKind != TK_ANNOTATION)\n    {\n        return false;\n    }\n\n    if (!is_default_value_consistent(default_value_))\n    {\n        return false;\n    }\n\n    if (type_ != nullptr && !is_type_name_consistent(type_->name_)) \/\/ Enums and bitmask don't have type\n    {\n        return false;\n    }\n\n    \/\/ Only Unions need the field \"label\"\n    if (labels_.size() != 0 && parentKind != TK_UNION)\n    {\n        return false;\n    }\n    \/\/ If the field isn't the default value for the union, it must have a label value.\n    else if (parentKind == TK_UNION && default_label_ == false && labels_.size() == 0)\n    {\n        return false;\n    }\n\n    return true;\n}\n\nbool MemberDescriptor::is_default_union_value() const\n{\n    return default_label_;\n}\n\nbool MemberDescriptor::is_default_value_consistent(\n        const std::string& sDefaultValue) const\n{\n    if (sDefaultValue.length() > 0)\n    {\n        try\n        {\n            switch (get_kind())\n            {\n                default:\n                    return true;\n                case TK_INT32:\n                {\n                    int32_t value(0);\n                    value = stoi(sDefaultValue);\n                    (void)value;\n                }\n                break;\n                case TK_UINT32:\n                {\n                    uint32_t value(0);\n                    value = stoul(sDefaultValue);\n                    (void)value;\n                }\n                break;\n                case TK_INT16:\n                {\n                    int16_t value(0);\n                    value = static_cast<int16_t>(stoi(sDefaultValue));\n                    (void)value;\n                }\n                break;\n                case TK_UINT16:\n                {\n                    uint16_t value(0);\n                    value = static_cast<uint16_t>(stoul(sDefaultValue));\n                    (void)value;\n                }\n                break;\n                case TK_INT64:\n                {\n                    int64_t value(0);\n                    value = stoll(sDefaultValue);\n                    (void)value;\n                }\n                break;\n                case TK_UINT64:\n                {\n                    uint64_t value(0);\n                    value = stoul(sDefaultValue);\n                    (void)value;\n                }\n                break;\n                case TK_FLOAT32:\n                {\n                    float value(0.0f);\n                    value = stof(sDefaultValue);\n                    (void)value;\n                }\n                break;\n                case TK_FLOAT64:\n                {\n                    double value(0.0f);\n                    value = stod(sDefaultValue);\n                    (void)value;\n                }\n                break;\n                case TK_FLOAT128:\n                {\n                    long double value(0.0f);\n                    value = stold(sDefaultValue);\n                    (void)value;\n                }\n                break;\n                case TK_CHAR8: {\n                    return sDefaultValue.length() >= 1;\n                }\n                case TK_CHAR16:\n                {\n                    std::wstring temp = std::wstring(sDefaultValue.begin(), sDefaultValue.end());\n                    (void)temp;\n                }\n                break;\n                case TK_BOOLEAN:\n                {\n                    if (sDefaultValue == CONST_TRUE || sDefaultValue == CONST_FALSE)\n                    {\n                        return true;\n                    }\n                    int value(0);\n                    value = stoi(sDefaultValue);\n                    (void)value;\n                }\n                break;\n                case TK_BYTE: {\n                    return sDefaultValue.length() >= 1;\n                }\n                break;\n                case TK_STRING16: {\n                    return true;\n                }\n                case TK_STRING8: {\n                    return true;\n                }\n                case TK_ENUM:\n                {\n                    uint32_t value(0);\n                    value = stoul(sDefaultValue);\n                    (void)value;\n                }\n                break;\n                case TK_BITMASK:\n                {\n                    int value(0);\n                    value = stoi(sDefaultValue);\n                    (void)value;\n                }\n                break;\n                case TK_ARRAY: {\n                    return true;\n                }\n                case TK_SEQUENCE: {\n                    return true;\n                }\n                case TK_MAP: {\n                    return true;\n                }\n            }\n        }\n        catch (...)\n        {\n            return false;\n        }\n    }\n    return true;\n}\n\nbool MemberDescriptor::is_type_name_consistent(\n        const std::string& sName) const\n{\n    return TypeDescriptor::is_type_name_consistent(sName);\n}\n\nvoid MemberDescriptor::set_id(\n        MemberId id)\n{\n    id_ = id;\n}\n\nvoid MemberDescriptor::set_index(\n        uint32_t index)\n{\n    index_ = index;\n}\n\nvoid MemberDescriptor::set_name(\n        const std::string& name)\n{\n    name_ = name;\n}\n\nvoid MemberDescriptor::set_type(\n        DynamicType_ptr type)\n{\n    type_ = type;\n}\n\nvoid MemberDescriptor::set_default_union_value(\n        bool bDefault)\n{\n    default_label_ = bDefault;\n}\n\n\/\/ Annotations application\nbool MemberDescriptor::annotation_is_optional() const\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_OPTIONAL_ID);\n    if (ann != nullptr)\n    {\n        std::string value;\n        if (ann->get_value(value) == ReturnCode_t::RETCODE_OK)\n        {\n            return value == CONST_TRUE;\n        }\n    }\n    return false;\n}\n\nbool MemberDescriptor::annotation_is_key() const\n{\n    return annotation_get_key();\n}\n\nbool MemberDescriptor::annotation_get_key() const\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_KEY_ID);\n    if (ann == nullptr)\n    {\n        ann = get_annotation(ANNOTATION_EPKEY_ID);\n    }\n    if (ann != nullptr)\n    {\n        std::string value;\n        if (ann->get_value(value) == ReturnCode_t::RETCODE_OK)\n        {\n            return value == CONST_TRUE;\n        }\n    }\n    return false;\n}\n\nbool MemberDescriptor::annotation_is_must_understand() const\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_MUST_UNDERSTAND_ID);\n    if (ann != nullptr)\n    {\n        std::string value;\n        if (ann->get_value(value) == ReturnCode_t::RETCODE_OK)\n        {\n            return value == CONST_TRUE;\n        }\n    }\n    return false;\n}\n\nbool MemberDescriptor::annotation_is_non_serialized() const\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_NON_SERIALIZED_ID);\n    if (ann != nullptr)\n    {\n        std::string value;\n        if (ann->get_value(value) == ReturnCode_t::RETCODE_OK)\n        {\n            return value == CONST_TRUE;\n        }\n    }\n    return false;\n}\n\nbool MemberDescriptor::annotation_is_value() const\n{\n    return get_annotation(ANNOTATION_VALUE_ID) != nullptr;\n}\n\nbool MemberDescriptor::annotation_is_default_literal() const\n{\n    return get_annotation(ANNOTATION_DEFAULT_LITERAL_ID) != nullptr;\n}\n\nbool MemberDescriptor::annotation_is_position() const\n{\n    return get_annotation(ANNOTATION_OPTIONAL_ID) != nullptr;\n}\n\n\/\/ Annotations getters\nstd::string MemberDescriptor::annotation_get_value() const\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_VALUE_ID);\n    if (ann != nullptr)\n    {\n        std::string value;\n        if (ann->get_value(value) == ReturnCode_t::RETCODE_OK)\n        {\n            return value;\n        }\n    }\n    return \"\";\n}\n\nstd::string MemberDescriptor::annotation_get_default() const\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_DEFAULT_ID);\n    if (ann != nullptr)\n    {\n        std::string value;\n        if (ann->get_value(value) == ReturnCode_t::RETCODE_OK)\n        {\n            return value;\n        }\n    }\n    return \"\";\n}\n\nuint16_t MemberDescriptor::annotation_get_position() const\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_POSITION_ID);\n    if (ann != nullptr)\n    {\n        std::string value;\n        if (ann->get_value(value) == ReturnCode_t::RETCODE_OK)\n        {\n            return static_cast<uint16_t>(std::stoi(value));\n        }\n    }\n    return static_cast<uint16_t>(-1);\n}\n\n\/\/ Annotations setters\nvoid MemberDescriptor::annotation_set_optional(\n        bool optional)\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_OPTIONAL_ID);\n    if (ann == nullptr)\n    {\n        ann = new AnnotationDescriptor();\n        ann->set_type(DynamicTypeBuilderFactory::get_instance()->create_annotation_primitive(ANNOTATION_OPTIONAL_ID));\n        apply_annotation(*ann);\n        delete ann;\n        ann = get_annotation(ANNOTATION_OPTIONAL_ID);\n    }\n    ann->set_value(\"value\", optional ? \"true\" : \"false\");\n}\n\nvoid MemberDescriptor::annotation_set_key(\n        bool key)\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_KEY_ID);\n    if (ann == nullptr)\n    {\n        ann = new AnnotationDescriptor();\n        ann->set_type(DynamicTypeBuilderFactory::get_instance()->create_annotation_primitive(ANNOTATION_KEY_ID));\n        apply_annotation(*ann);\n        delete ann;\n        ann = get_annotation(ANNOTATION_KEY_ID);\n    }\n    ann->set_value(\"value\", key ? \"true\" : \"false\");\n}\n\nvoid MemberDescriptor::annotation_set_must_understand(\n        bool must_understand)\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_MUST_UNDERSTAND_ID);\n    if (ann == nullptr)\n    {\n        ann = new AnnotationDescriptor();\n        ann->set_type(\n            DynamicTypeBuilderFactory::get_instance()->create_annotation_primitive(ANNOTATION_MUST_UNDERSTAND_ID));\n        apply_annotation(*ann);\n        delete ann;\n        ann = get_annotation(ANNOTATION_MUST_UNDERSTAND_ID);\n    }\n    ann->set_value(\"value\", must_understand ? \"true\" : \"false\");\n}\n\nvoid MemberDescriptor::annotation_set_non_serialized(\n        bool non_serialized)\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_NON_SERIALIZED_ID);\n    if (ann == nullptr)\n    {\n        ann = new AnnotationDescriptor();\n        ann->set_type(\n            DynamicTypeBuilderFactory::get_instance()->create_annotation_primitive(ANNOTATION_NON_SERIALIZED_ID));\n        apply_annotation(*ann);\n        delete ann;\n        ann = get_annotation(ANNOTATION_NON_SERIALIZED_ID);\n    }\n    ann->set_value(\"value\", non_serialized ? \"true\" : \"false\");\n}\n\nvoid MemberDescriptor::annotation_set_value(\n        const std::string& value)\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_VALUE_ID);\n    if (ann == nullptr)\n    {\n        ann = new AnnotationDescriptor();\n        ann->set_type(DynamicTypeBuilderFactory::get_instance()->create_annotation_primitive(ANNOTATION_VALUE_ID));\n        apply_annotation(*ann);\n        delete ann;\n        ann = get_annotation(ANNOTATION_VALUE_ID);\n    }\n    ann->set_value(\"value\", value);\n}\n\nvoid MemberDescriptor::annotation_set_default_literal()\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_DEFAULT_LITERAL_ID);\n    if (ann == nullptr)\n    {\n        ann = new AnnotationDescriptor();\n        ann->set_type(\n            DynamicTypeBuilderFactory::get_instance()->create_annotation_primitive(ANNOTATION_DEFAULT_LITERAL_ID));\n        apply_annotation(*ann);\n        delete ann;\n        ann = get_annotation(ANNOTATION_DEFAULT_LITERAL_ID);\n    }\n    ann->set_value(\"value\", \"true\");\n}\n\nvoid MemberDescriptor::annotation_set_position(\n        uint16_t position)\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_POSITION_ID);\n    if (ann == nullptr)\n    {\n        ann = new AnnotationDescriptor();\n        ann->set_type(DynamicTypeBuilderFactory::get_instance()->create_annotation_primitive(ANNOTATION_POSITION_ID));\n        apply_annotation(*ann);\n        delete ann;\n        ann = get_annotation(ANNOTATION_POSITION_ID);\n    }\n    ann->set_value(\"value\", std::to_string(position));\n}\n\nvoid MemberDescriptor::annotation_set_default(\n        const std::string& default_value)\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_DEFAULT_ID);\n    if (ann == nullptr)\n    {\n        ann = new AnnotationDescriptor();\n        ann->set_type(DynamicTypeBuilderFactory::get_instance()->create_annotation_primitive(ANNOTATION_DEFAULT_ID));\n        apply_annotation(*ann);\n        delete ann;\n        ann = get_annotation(ANNOTATION_DEFAULT_ID);\n    }\n    ann->set_value(\"value\", default_value);\n}\n\nbool MemberDescriptor::annotation_is_bit_bound() const\n{\n    return get_annotation(ANNOTATION_BIT_BOUND_ID) != nullptr;\n}\n\nuint16_t MemberDescriptor::annotation_get_bit_bound() const\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_BIT_BOUND_ID);\n    if (ann != nullptr)\n    {\n        std::string value;\n        if (ann->get_value(value) == ReturnCode_t::RETCODE_OK)\n        {\n            return static_cast<uint16_t>(std::stoi(value));\n        }\n    }\n    return 32; \/\/ Default value\n}\n\nvoid MemberDescriptor::annotation_set_bit_bound(\n        uint16_t bit_bound)\n{\n    AnnotationDescriptor* ann = get_annotation(ANNOTATION_BIT_BOUND_ID);\n    if (ann == nullptr)\n    {\n        ann = new AnnotationDescriptor();\n        ann->set_type(DynamicTypeBuilderFactory::get_instance()->create_annotation_primitive(ANNOTATION_BIT_BOUND_ID));\n        apply_annotation(*ann);\n        delete ann;\n        ann = get_annotation(ANNOTATION_BIT_BOUND_ID);\n    }\n    ann->set_value(\"value\", std::to_string(bit_bound));\n}\n\nReturnCode_t MemberDescriptor::apply_annotation(\n        AnnotationDescriptor& descriptor)\n{\n    if (descriptor.is_consistent())\n    {\n        AnnotationDescriptor* pNewDescriptor = new AnnotationDescriptor();\n        pNewDescriptor->copy_from(&descriptor);\n        annotation_.push_back(pNewDescriptor);\n        return ReturnCode_t::RETCODE_OK;\n    }\n    else\n    {\n        logError(DYN_TYPES, \"Error applying annotation. The input descriptor isn't consistent.\");\n        return ReturnCode_t::RETCODE_BAD_PARAMETER;\n    }\n}\n\nReturnCode_t MemberDescriptor::apply_annotation(\n        const std::string& annotation_name,\n        const std::string& key,\n        const std::string& value)\n{\n    AnnotationDescriptor* ann = get_annotation(annotation_name);\n    if (ann != nullptr)\n    {\n        ann->set_value(key, value);\n    }\n    else\n    {\n        AnnotationDescriptor* pNewDescriptor = new AnnotationDescriptor();\n        pNewDescriptor->set_type(\n            DynamicTypeBuilderFactory::get_instance()->create_annotation_primitive(annotation_name));\n        pNewDescriptor->set_value(key, value);\n        annotation_.push_back(pNewDescriptor);\n    }\n    return ReturnCode_t::RETCODE_OK;\n}\n\nAnnotationDescriptor* MemberDescriptor::get_annotation(\n        const std::string& name) const\n{\n    auto it = annotation_.begin();\n\n    for (; it != annotation_.end(); ++it)\n    {\n        AnnotationDescriptor* ann = *it;\n        if (ann->type()->get_name().compare(name) == 0)\n        {\n            return ann;\n        }\n    }\n    return nullptr;\n}\n\n} \/\/ namespace types\n} \/\/ namespace fastrtps\n} \/\/ namespace eprosima\n","avg_line_length":27.0601023018,"max_line_length":119,"alphanum_fraction":0.5857946222,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":769,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":305.0,"content":"\/\/===-- Implementation of strtok ------------------------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"src\/string\/strtok.h\"\n\n#include \"src\/__support\/common.h\"\n#include \"src\/string\/string_utils.h\"\n\nnamespace __llvm_libc {\n\nstatic char *strtok_str = nullptr;\n\nchar *LLVM_LIBC_ENTRYPOINT(strtok)(char *__restrict src,\n                                   const char *__restrict delimiter_string) {\n  return internal::string_token(src, delimiter_string, &strtok_str);\n}\n\n} \/\/ namespace __llvm_libc\n","avg_line_length":32.0416666667,"max_line_length":80,"alphanum_fraction":0.5955786736,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":17089,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":10.0,"content":"\/\/\n\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\/\/\n\/\/\n\n\/\/\n\/\/ ===========================================================================\n\/\/ File: path.cpp\n\/\/\n\/\/ Path APIs ported from shlwapi (especially for Fusion)\n\/\/ ===========================================================================\n\n#include \"common.h\"\n\n\n\n#define CH_SLASH W('\/')\n#define CH_WHACK W('\\\\')\n\n\/\/\n\/\/ Inline function to check for a double-backslash at the\n\/\/ beginning of a string\n\/\/\n\nstatic __inline BOOL DBL_BSLASH(LPCWSTR psz)\n{\n    return (psz[0] == W('\\\\') && psz[1] == W('\\\\'));\n}\n\n\/\/\n\/\/ Inline function to check for a path separator character.\n\/\/\n\nstatic __inline BOOL IsPathSeparator(WCHAR ch)\n{\n    return (ch == CH_SLASH || ch == CH_WHACK);\n}\n\n__inline BOOL ChrCmpW_inline(WCHAR w1, WCHAR wMatch)\n{\n    return(!(w1 == wMatch));\n}\n\nSTDAPI_(LPWSTR) StrRChrW(LPCWSTR lpStart, LPCWSTR lpEnd, WCHAR wMatch)\n{\n    LPCWSTR lpFound = NULL;\n\n    RIPMSG(lpStart && IS_VALID_STRING_PTRW(lpStart, -1), \"StrRChrW: caller passed bad lpStart\");\n    RIPMSG(!lpEnd || lpEnd <= lpStart + lstrlenW(lpStart), \"StrRChrW: caller passed bad lpEnd\");\n    \/\/ don't need to check for NULL lpStart\n\n    if (!lpEnd)\n        lpEnd = lpStart + lstrlenW(lpStart);\n\n    for ( ; lpStart < lpEnd; lpStart++)\n    {\n        if (!ChrCmpW_inline(*lpStart, wMatch))\n            lpFound = lpStart;\n    }\n    return ((LPWSTR)lpFound);\n}\n\n\n\/\/ check if a path is a root\n\/\/\n\/\/ returns:\n\/\/  TRUE \n\/\/      \"\\\" \"X:\\\" \"\\\\\" \"\\\\foo\" \"\\\\foo\\bar\"\n\/\/\n\/\/  FALSE for others including \"\\\\foo\\bar\\\" (!)\n\/\/\nSTDAPI_(BOOL) PathIsRootW(LPCWSTR pPath)\n{\n    RIPMSG(pPath && IS_VALID_STRING_PTR(pPath, -1), \"PathIsRoot: caller passed bad pPath\");\n    \n    if (!pPath || !*pPath)\n    {\n        return FALSE;\n    }\n    \n    if (!lstrcmpiW(pPath + 1, W(\":\\\\\")))\n    {\n        return TRUE;    \/\/ \"X:\\\" case\n    }\n    \n    if (IsPathSeparator(*pPath) && (*(pPath + 1) == 0))\n    {\n        return TRUE;    \/\/ \"\/\" or \"\\\" case\n    }\n    \n    if (DBL_BSLASH(pPath))      \/\/ smells like UNC name\n    {\n        LPCWSTR p;\n        int cBackslashes = 0;\n        \n        for (p = pPath + 2; *p; p++)\n        {\n            if (*p == W('\\\\')) \n            {\n                \/\/\n                \/\/  return FALSE for \"\\\\server\\share\\dir\"\n                \/\/  so just check if there is more than one slash\n                \/\/\n                \/\/  \"\\\\server\\\" without a share name causes\n                \/\/  problems for WNet APIs.  we should return\n                \/\/  FALSE for this as well\n                \/\/\n                if ((++cBackslashes > 1) || !*(p+1))\n                    return FALSE;   \n            }\n        }\n        \/\/ end of string with only 1 more backslash\n        \/\/ must be a bare UNC, which looks like a root dir\n        return TRUE;\n    }\n    return FALSE;\n}\n\n\/*\n\/\/ rips the last part of the path off including the backslash\n\/\/      C:\\foo      -> C:\\\n\/\/      C:\\foo\\bar  -> C:\\foo\n\/\/      C:\\foo\\     -> C:\\foo\n\/\/      \\\\x\\y\\x     -> \\\\x\\y\n\/\/      \\\\x\\y       -> \\\\x\n\/\/      \\\\x         -> \\\\ (Just the double slash!)\n\/\/      \\foo        -> \\  (Just the slash!)\n\/\/\n\/\/ in\/out:\n\/\/      pFile   fully qualified path name\n\/\/ returns:\n\/\/      TRUE    we stripped something\n\/\/      FALSE   didn't strip anything (root directory case)\n\/\/\n*\/\nSTDAPI_(BOOL) PathRemoveFileSpecW(LPWSTR pFile)\n{\n    RIPMSG(pFile && IS_VALID_STRING_PTR(pFile, -1), \"PathRemoveFileSpec: caller passed bad pFile\");\n\n    if (pFile)\n    {\n        LPWSTR pT;\n        LPWSTR pT2 = pFile;\n\n        for (pT = pT2; *pT2; pT2++)\n        {\n            if (IsPathSeparator(*pT2))\n            {\n                pT = pT2;             \/\/ last \"\\\" found, (we will strip here)\n            }\n            else if (*pT2 == W(':'))     \/\/ skip \":\\\" so we don't\n            {\n                if (IsPathSeparator(pT2[1]))    \/\/ strip the \"\\\" from \"C:\\\"\n                {\n                    pT2++;\n                }\n                pT = pT2 + 1;\n            }\n        }\n\n        if (*pT == 0)\n        {\n            \/\/ didn't strip anything\n            return FALSE;\n        }\n        else if (((pT == pFile) && IsPathSeparator(*pT)) ||                     \/\/  is it the \"\\foo\" case?\n                 ((pT == pFile+1) && (*pT == CH_WHACK && *pFile == CH_WHACK)))  \/\/  or the \"\\\\bar\" case?\n        {\n            \/\/ Is it just a '\\'?\n            if (*(pT+1) != W('\\0'))\n            {\n                \/\/ Nope.\n                *(pT+1) = W('\\0');\n                return TRUE;        \/\/ stripped something\n            }\n            else\n            {\n                \/\/ Yep.\n                return FALSE;\n            }\n        }\n        else\n        {\n            *pT = 0;\n            return TRUE;    \/\/ stripped something\n        }\n    }\n    return  FALSE;\n}\n\n\/\/\n\/\/ Return a pointer to the end of the next path component in the string.\n\/\/ ie return a pointer to the next backslash or terminating NULL.\n\/\/\nLPCWSTR GetPCEnd(LPCWSTR lpszStart)\n{\n    LPCWSTR lpszEnd;\n    LPCWSTR lpszSlash;\n\n    lpszEnd = StrChr(lpszStart, CH_WHACK);\n    lpszSlash = StrChr(lpszStart, CH_SLASH);\n    if ((lpszSlash && lpszSlash < lpszEnd) ||\n        !lpszEnd)\n    {\n        lpszEnd = lpszSlash;\n    }\n    if (!lpszEnd)\n    {\n        lpszEnd = lpszStart + lstrlenW(lpszStart);\n    }\n\n    return lpszEnd;\n}\n\n\/\/\n\/\/ Given a pointer to the end of a path component, return a pointer to\n\/\/ its begining.\n\/\/ ie return a pointer to the previous backslash (or start of the string).\n\/\/\nLPCWSTR PCStart(LPCWSTR lpszStart, LPCWSTR lpszEnd)\n{\n    LPCWSTR lpszBegin = StrRChrW(lpszStart, lpszEnd, CH_WHACK);\n    LPCWSTR lpszSlash = StrRChrW(lpszStart, lpszEnd, CH_SLASH);\n    if (lpszSlash > lpszBegin)\n    {\n        lpszBegin = lpszSlash;\n    }\n    if (!lpszBegin)\n    {\n        lpszBegin = lpszStart;\n    }\n    return lpszBegin;\n}\n\n\/\/\n\/\/ Fix up a few special cases so that things roughly make sense.\n\/\/\nvoid NearRootFixups(LPWSTR lpszPath, BOOL fUNC)\n{\n    \/\/ Check for empty path.\n    if (lpszPath[0] == W('\\0'))\n    {\n        \/\/ Fix up.\n#ifndef PLATFORM_UNIX        \n        lpszPath[0] = CH_WHACK;\n#else\n        lpszPath[0] = CH_SLASH;\n#endif\n        lpszPath[1] = W('\\0');\n    }\n    \/\/ Check for missing slash.\n    if (lpszPath[1] == W(':') && lpszPath[2] == W('\\0'))\n    {\n        \/\/ Fix up.\n        lpszPath[2] = W('\\\\');\n        lpszPath[3] = W('\\0');\n    }\n    \/\/ Check for UNC root.\n    if (fUNC && lpszPath[0] == W('\\\\') && lpszPath[1] == W('\\0'))\n    {\n        \/\/ Fix up.\n        \/\/lpszPath[0] = W('\\\\'); \/\/ already checked in if guard\n        lpszPath[1] = W('\\\\');\n        lpszPath[2] = W('\\0');\n    }\n}\n\n\/*----------------------------------------------------------\nPurpose: Canonicalize a path.\n\nReturns:\nCond:    --\n*\/\nSTDAPI_(BOOL) PathCanonicalizeW(LPWSTR lpszDst, LPCWSTR lpszSrc)\n{\n    LPCWSTR lpchSrc;\n    LPCWSTR lpchPCEnd;      \/\/ Pointer to end of path component.\n    LPWSTR lpchDst;\n    BOOL fUNC;\n    int cchPC;\n\n    RIPMSG(lpszDst && IS_VALID_WRITE_BUFFER(lpszDst, WCHAR, MAX_PATH), \"PathCanonicalize: caller passed bad lpszDst\");\n    RIPMSG(lpszSrc && IS_VALID_STRING_PTR(lpszSrc, -1), \"PathCanonicalize: caller passed bad lpszSrc\");\n    RIPMSG(lpszDst != lpszSrc, \"PathCanonicalize: caller passed the same buffer for lpszDst and lpszSrc\");\n\n    if (!lpszDst || !lpszSrc)\n    {\n        SetLastError(ERROR_INVALID_PARAMETER);\n        return FALSE;\n    }\n\n    *lpszDst = W('\\0');\n    \n    fUNC = PathIsUNCW(lpszSrc);    \/\/ Check for UNCness.\n\n    \/\/ Init.\n    lpchSrc = lpszSrc;\n    lpchDst = lpszDst;\n\n    while (*lpchSrc)\n    {\n        lpchPCEnd = GetPCEnd(lpchSrc);\n        cchPC = (int) (lpchPCEnd - lpchSrc)+1;\n\n        if (cchPC == 1 && IsPathSeparator(*lpchSrc))   \/\/ Check for slashes.\n        {\n            \/\/ Just copy them.\n#ifndef PLATFORM_UNIX            \n            *lpchDst = CH_WHACK;\n#else\n            *lpchDst = CH_SLASH;\n#endif\n            lpchDst++;\n            lpchSrc++;\n        }\n        else if (cchPC == 2 && *lpchSrc == W('.'))  \/\/ Check for dots.\n        {\n            \/\/ Skip it...\n            \/\/ Are we at the end?\n            if (*(lpchSrc+1) == W('\\0'))\n            {\n                lpchSrc++;\n\n                \/\/ remove the last slash we copied (if we've copied one), but don't make a mal-formed root\n                if ((lpchDst > lpszDst) && !PathIsRootW(lpszDst))\n                    lpchDst--;\n            }\n            else\n            {\n                lpchSrc += 2;\n            }\n        }\n        else if (cchPC == 3 && *lpchSrc == W('.') && *(lpchSrc + 1) == W('.')) \/\/ Check for dot dot.\n        {\n            \/\/ make sure we aren't already at the root\n            if (!PathIsRootW(lpszDst))\n            {\n                \/\/ Go up... Remove the previous path component.\n                lpchDst = (LPWSTR)PCStart(lpszDst, lpchDst - 1);\n            }\n            else\n            {\n                \/\/ When we can't back up, skip the trailing backslash\n                \/\/ so we don't copy one again. (C:\\..\\FOO would otherwise\n                \/\/ turn into C:\\\\FOO).\n                if (IsPathSeparator(*(lpchSrc + 2)))\n                {\n                    lpchSrc++;\n                }\n            }\n\n            \/\/ skip \"..\"\n            lpchSrc += 2;       \n        }\n        else                                                                        \/\/ Everything else\n        {\n            \/\/ Just copy it.\n            lstrcpynW(lpchDst, lpchSrc, cchPC);\n            lpchDst += cchPC - 1;\n            lpchSrc += cchPC - 1;\n        }\n\n        \/\/ Keep everything nice and tidy.\n        *lpchDst = W('\\0');\n    }\n\n    \/\/ Check for weirdo root directory stuff.\n    NearRootFixups(lpszDst, fUNC);\n\n    return TRUE;\n}\n\n\/\/ Modifies:\n\/\/      pszRoot\n\/\/\n\/\/ Returns:\n\/\/      TRUE if a drive root was found\n\/\/      FALSE otherwise\n\/\/\nSTDAPI_(BOOL) PathStripToRootW(LPWSTR pszRoot)\n{\n    RIPMSG(pszRoot && IS_VALID_STRING_PTR(pszRoot, -1), \"PathStripToRoot: caller passed bad pszRoot\");\n\n    if (pszRoot)\n    {\n        while (!PathIsRootW(pszRoot))\n        {\n            if (!PathRemoveFileSpecW(pszRoot))\n            {\n                \/\/ If we didn't strip anything off,\n                \/\/ must be current drive\n                return FALSE;\n            }\n        }\n        return TRUE;\n    }\n    return FALSE;\n}\n\n\n\n\/*----------------------------------------------------------\nPurpose: Concatenate lpszDir and lpszFile into a properly formed\n         path and canonicalize any relative path pieces.\n\n         lpszDest and lpszFile can be the same buffer\n         lpszDest and lpszDir can be the same buffer\n\nReturns: pointer to lpszDest\n*\/\nSTDAPI_(LPWSTR) PathCombineW(LPWSTR lpszDest, LPCWSTR lpszDir, LPCWSTR lpszFile)\n{\n#ifdef DEBUG\n    RIPMSG(lpszDest && IS_VALID_WRITE_BUFFER(lpszDest, TCHAR, MAX_LONGPATH), \"PathCombine: caller passed bad lpszDest\");\n    RIPMSG(!lpszDir || IS_VALID_STRING_PTR(lpszDir, -1), \"PathCombine: caller passed bad lpszDir\");\n    RIPMSG(!lpszFile || IS_VALID_STRING_PTR(lpszFile, -1), \"PathCombine: caller passed bad lpszFile\");\n    RIPMSG(lpszDir || lpszFile, \"PathCombine: caller neglected to pass lpszDir or lpszFile\");\n#endif \/\/ DEBUG\n\n\n    if (lpszDest)\n    {\n        TCHAR szTemp[MAX_LONGPATH];\n        LPWSTR pszT;\n\n        *szTemp = W('\\0');\n\n        if (lpszDir && *lpszDir)\n        {\n            if (!lpszFile || *lpszFile==W('\\0'))\n            {\n                lstrcpynW(szTemp, lpszDir, ARRAYSIZE(szTemp));       \/\/ lpszFile is empty\n            }\n            else if (PathIsRelativeW(lpszFile))\n            {\n                lstrcpynW(szTemp, lpszDir, ARRAYSIZE(szTemp));\n                pszT = PathAddBackslashW(szTemp);\n                if (pszT)\n                {\n                    int iRemaining = (int)(ARRAYSIZE(szTemp) - (pszT - szTemp));\n\n                    if (lstrlenW(lpszFile) < iRemaining)\n                    {\n                        lstrcpynW(pszT, lpszFile, iRemaining);\n                    }\n                    else\n                    {\n                        *szTemp = W('\\0');\n                    }\n                }\n                else\n                {\n                    *szTemp = W('\\0');\n                }\n            }\n            else if (IsPathSeparator(*lpszFile) && !PathIsUNCW(lpszFile))\n            {\n                lstrcpynW(szTemp, lpszDir, ARRAYSIZE(szTemp));\n                \/\/ FEATURE: Note that we do not check that an actual root is returned;\n                \/\/ it is assumed that we are given valid parameters\n                PathStripToRootW(szTemp);\n\n                pszT = PathAddBackslashW(szTemp);\n                if (pszT)\n                {\n                    \/\/ Skip the backslash when copying\n                    \/\/ Note: We don't support strings longer than 4GB, but that's\n                    \/\/ okay because we already barf at MAX_PATH\n                    lstrcpynW(pszT, lpszFile+1, (int)(ARRAYSIZE(szTemp) - (pszT - szTemp)));\n                }\n                else\n                {\n                    *szTemp = W('\\0');\n                }\n            }\n            else\n            {\n                lstrcpynW(szTemp, lpszFile, ARRAYSIZE(szTemp));     \/\/ already fully qualified file part\n            }\n        }\n        else if (lpszFile && *lpszFile)\n        {\n            lstrcpynW(szTemp, lpszFile, ARRAYSIZE(szTemp));     \/\/ no dir just use file.\n        }\n\n        \/\/\n        \/\/ if szTemp has something in it we succeeded.  Also if szTemp is empty and\n        \/\/ the input strings are empty we succeed and PathCanonicalize() will\n        \/\/ return \"\\\"\n        \/\/ \n        if (*szTemp || ((lpszDir || lpszFile) && !((lpszDir && *lpszDir) || (lpszFile && *lpszFile))))\n        {\n            PathCanonicalizeW(lpszDest, szTemp); \/\/ this deals with .. and . stuff\n                                                \/\/ returns \"\\\" on empty szTemp\n        }\n        else\n        {\n            *lpszDest = W('\\0');   \/\/ set output buffer to empty string.\n            lpszDest  = NULL;         \/\/ return failure.\n        }\n    }\n\n    return lpszDest;\n}\n\n\/\/ add a backslash to a qualified path\n\/\/\n\/\/ in:\n\/\/  lpszPath    path (A:, C:\\foo, etc)\n\/\/\n\/\/ out:\n\/\/  lpszPath    A:\\, C:\\foo\\    ;\n\/\/\n\/\/ returns:\n\/\/  pointer to the NULL that terminates the path\n\/\/\nSTDAPI_(LPWSTR) PathAddBackslashW(LPWSTR lpszPath)\n{\n    LPWSTR lpszRet = NULL;\n\n    RIPMSG(lpszPath && IS_VALID_STRING_PTR(lpszPath, -1), \"PathAddBackslash: caller passed bad lpszPath\");\n\n    if (lpszPath)\n    {\n        int    ichPath = lstrlenW(lpszPath);\n        LPWSTR lpszEnd = lpszPath + ichPath;\n\n        if (ichPath)\n        {\n\n            \/\/ Get the end of the source directory\n            switch(*(lpszEnd-1))\n            {\n                case CH_SLASH:\n                case CH_WHACK:\n                    break;\n\n                default:\n                    \/\/ try to keep us from tromping over MAX_PATH in size.\n                    \/\/ if we find these cases, return NULL.  Note: We need to\n                    \/\/ check those places that call us to handle their GP fault\n                    \/\/ if they try to use the NULL!\n                    if (ichPath >= (MAX_PATH - 2)) \/\/ -2 because ichPath doesn't include NULL, and we're adding a CH_WHACK.\n                    {\n                        return(NULL);\n                    }\n\n                    *lpszEnd++ = CH_WHACK;\n                    *lpszEnd = W('\\0');\n            }\n        }\n\n        lpszRet = lpszEnd;\n    }\n\n    return lpszRet;\n}\n\n\n\n\n\/\/---------------------------------------------------------------------------\n\/\/ Returns TRUE if the given string is a UNC path.\n\/\/\n\/\/ TRUE\n\/\/      \"\\\\foo\\bar\"\n\/\/      \"\\\\foo\"         <- careful\n\/\/      \"\\\\\"\n\/\/ FALSE\n\/\/      \"\\foo\"\n\/\/      \"foo\"\n\/\/      \"c:\\foo\"\n\/\/\n\/\/\nSTDAPI_(BOOL) PathIsUNCW(LPCWSTR pszPath)\n{\n    RIPMSG(pszPath && IS_VALID_STRING_PTR(pszPath, -1), \"PathIsUNC: caller passed bad pszPath\");\n\n    if (pszPath)\n    {\n        return DBL_BSLASH(pszPath);\n    }\n    return FALSE;\n}\n\n\n\n\n\n\/\/---------------------------------------------------------------------------\n\/\/ Return TRUE if the path isn't absoulte.\n\/\/\n\/\/ TRUE\n\/\/      \"foo.exe\"\n\/\/      \".\\foo.exe\"\n\/\/      \"..\\boo\\foo.exe\"\n\/\/\n\/\/ FALSE\n\/\/      \"\\foo\"\n\/\/      \"c:bar\"     <- be careful\n\/\/      \"c:\\bar\"\n\/\/      \"\\\\foo\\bar\"\n\/\/\nSTDAPI_(BOOL) PathIsRelativeW(LPCWSTR lpszPath)\n{\n    RIPMSG(lpszPath && IS_VALID_STRING_PTR(lpszPath, -1), \"PathIsRelative: caller passed bad lpszPath\");\n\n    if (!lpszPath || *lpszPath == 0)\n    {\n        \/\/ The NULL path is assumed relative\n        return TRUE;\n    }\n\n    if (IsPathSeparator(lpszPath[0]))\n    {\n        \/\/ Does it begin with a slash ?\n        return FALSE;\n    }\n    else if (lpszPath[1] == W(':'))\n    {\n        \/\/ Does it begin with a drive and a colon ?\n        return FALSE;\n    }\n    else\n    {\n        \/\/ Probably relative.\n        return TRUE;\n    }\n}\n\n\/\/ find the next slash or null terminator\nLPWSTR StrSlash(LPCWSTR psz)\n{\n    for (; *psz && !IsPathSeparator(*psz); psz++);\n\n    \/\/ Cast to a non-const string to mimic the behavior\n    \/\/ of wcschr\/StrChr and strchr.\n    return (LPWSTR) psz;\n}\n\n\n\n","avg_line_length":26.5357142857,"max_line_length":123,"alphanum_fraction":0.4845222073,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1433,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/---------------------------------------------------------------------------\r\n\r\n\r\n#pragma hdrstop\r\n\r\n#include \"Progress.h\"\r\n#include \"mainform.h\"\r\n#include <windows.hpp>\r\n\r\n\/\/---------------------------------------------------------------------------\r\nint FiltersTotal, FiltersDone;\r\nint Percent;\r\nint FilterStepsTotal, FilterStepsDone;\r\nint LastTickCount=0;\r\n\r\nvoid ProgressInit(int Filters)\r\n{\r\n  Form1->CGauge1->Progress = 0;\r\n  FiltersTotal = Filters;\r\n  FiltersDone = -1;\r\n  Percent = 0;\r\n  Form1->InProgress = true;\r\n  Form1->RePaint();\r\n}\r\n\r\nvoid ProgressNextFilter(int Steps)\r\n{\r\n  FilterStepsTotal = Steps;\r\n  FilterStepsDone = 0;\r\n  FiltersDone++;\r\n}\r\n\r\nvoid ProgressDraw()\r\n{\r\n  Form1->CGauge1->Progress = Percent;\r\n}\r\n\r\nvoid ProgressUpdate(int Steps)\r\n{\r\n  FilterStepsDone += Steps;\r\n  int NewPercent = 100 * (1.0 * FiltersDone \/ FiltersTotal + 1.0 * FilterStepsDone \/ (FilterStepsTotal * FiltersTotal));\r\n  if (NewPercent != Percent)\r\n  {\r\n    Percent = NewPercent;\r\n    ProgressDraw();\r\n  }\r\n  int TickCount = GetTickCount();\r\n  if (NewPercent != Percent || TickCount - LastTickCount > 250)\r\n    Application->ProcessMessages();\r\n}\r\n\r\nvoid ProgressUpdate()\r\n{\r\n  ProgressUpdate(1);\r\n}\r\n\r\nvoid ProgressUpdateSet(int Steps)\r\n{\r\n  FilterStepsDone = Steps;\r\n  ProgressUpdate(0);\r\n}\r\n\r\nvoid ProgressClear()\r\n{\r\n  Percent = 0;\r\n  Form1->CGauge1->Progress = 0;\r\n  Form1->InProgress = false;\r\n}\r\n\r\n#pragma package(smart_init)\r\n","avg_line_length":20.1830985915,"max_line_length":121,"alphanum_fraction":0.5910676902,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":18123,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":605.0,"content":"\/\/===--- CERTTidyModule.cpp - clang-tidy ----------------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"..\/ClangTidy.h\"\n#include \"..\/ClangTidyModule.h\"\n#include \"..\/ClangTidyModuleRegistry.h\"\n#include \"..\/bugprone\/BadSignalToKillThreadCheck.h\"\n#include \"..\/bugprone\/ReservedIdentifierCheck.h\"\n#include \"..\/bugprone\/SignalHandlerCheck.h\"\n#include \"..\/bugprone\/SignedCharMisuseCheck.h\"\n#include \"..\/bugprone\/SpuriouslyWakeUpFunctionsCheck.h\"\n#include \"..\/bugprone\/SuspiciousMemoryComparisonCheck.h\"\n#include \"..\/bugprone\/UnhandledSelfAssignmentCheck.h\"\n#include \"..\/bugprone\/UnusedReturnValueCheck.h\"\n#include \"..\/concurrency\/ThreadCanceltypeAsynchronousCheck.h\"\n#include \"..\/google\/UnnamedNamespaceInHeaderCheck.h\"\n#include \"..\/misc\/NewDeleteOverloadsCheck.h\"\n#include \"..\/misc\/NonCopyableObjects.h\"\n#include \"..\/misc\/StaticAssertCheck.h\"\n#include \"..\/misc\/ThrowByValueCatchByReferenceCheck.h\"\n#include \"..\/performance\/MoveConstructorInitCheck.h\"\n#include \"..\/readability\/UppercaseLiteralSuffixCheck.h\"\n#include \"CommandProcessorCheck.h\"\n#include \"DefaultOperatorNewAlignmentCheck.h\"\n#include \"DontModifyStdNamespaceCheck.h\"\n#include \"FloatLoopCounter.h\"\n#include \"LimitedRandomnessCheck.h\"\n#include \"MutatingCopyCheck.h\"\n#include \"NonTrivialTypesLibcMemoryCallsCheck.h\"\n#include \"PostfixOperatorCheck.h\"\n#include \"ProperlySeededRandomGeneratorCheck.h\"\n#include \"SetLongJmpCheck.h\"\n#include \"StaticObjectExceptionCheck.h\"\n#include \"StrToNumCheck.h\"\n#include \"ThrownExceptionTypeCheck.h\"\n#include \"VariadicFunctionDefCheck.h\"\n\nnamespace {\n\n\/\/ Checked functions for cert-err33-c.\n\/\/ The following functions are deliberately excluded because they can be called\n\/\/ with NULL argument and in this case the check is not applicable:\n\/\/ `mblen, mbrlen, mbrtowc, mbtowc, wctomb, wctomb_s`.\n\/\/ FIXME: The check can be improved to handle such cases.\nconst llvm::StringRef CertErr33CCheckedFunctions = \"::aligned_alloc;\"\n                                                   \"::asctime_s;\"\n                                                   \"::at_quick_exit;\"\n                                                   \"::atexit;\"\n                                                   \"::bsearch;\"\n                                                   \"::bsearch_s;\"\n                                                   \"::btowc;\"\n                                                   \"::c16rtomb;\"\n                                                   \"::c32rtomb;\"\n                                                   \"::calloc;\"\n                                                   \"::clock;\"\n                                                   \"::cnd_broadcast;\"\n                                                   \"::cnd_init;\"\n                                                   \"::cnd_signal;\"\n                                                   \"::cnd_timedwait;\"\n                                                   \"::cnd_wait;\"\n                                                   \"::ctime_s;\"\n                                                   \"::fclose;\"\n                                                   \"::fflush;\"\n                                                   \"::fgetc;\"\n                                                   \"::fgetpos;\"\n                                                   \"::fgets;\"\n                                                   \"::fgetwc;\"\n                                                   \"::fopen;\"\n                                                   \"::fopen_s;\"\n                                                   \"::fprintf;\"\n                                                   \"::fprintf_s;\"\n                                                   \"::fputc;\"\n                                                   \"::fputs;\"\n                                                   \"::fputwc;\"\n                                                   \"::fputws;\"\n                                                   \"::fread;\"\n                                                   \"::freopen;\"\n                                                   \"::freopen_s;\"\n                                                   \"::fscanf;\"\n                                                   \"::fscanf_s;\"\n                                                   \"::fseek;\"\n                                                   \"::fsetpos;\"\n                                                   \"::ftell;\"\n                                                   \"::fwprintf;\"\n                                                   \"::fwprintf_s;\"\n                                                   \"::fwrite;\"\n                                                   \"::fwscanf;\"\n                                                   \"::fwscanf_s;\"\n                                                   \"::getc;\"\n                                                   \"::getchar;\"\n                                                   \"::getenv;\"\n                                                   \"::getenv_s;\"\n                                                   \"::gets_s;\"\n                                                   \"::getwc;\"\n                                                   \"::getwchar;\"\n                                                   \"::gmtime;\"\n                                                   \"::gmtime_s;\"\n                                                   \"::localtime;\"\n                                                   \"::localtime_s;\"\n                                                   \"::malloc;\"\n                                                   \"::mbrtoc16;\"\n                                                   \"::mbrtoc32;\"\n                                                   \"::mbsrtowcs;\"\n                                                   \"::mbsrtowcs_s;\"\n                                                   \"::mbstowcs;\"\n                                                   \"::mbstowcs_s;\"\n                                                   \"::memchr;\"\n                                                   \"::mktime;\"\n                                                   \"::mtx_init;\"\n                                                   \"::mtx_lock;\"\n                                                   \"::mtx_timedlock;\"\n                                                   \"::mtx_trylock;\"\n                                                   \"::mtx_unlock;\"\n                                                   \"::printf_s;\"\n                                                   \"::putc;\"\n                                                   \"::putwc;\"\n                                                   \"::raise;\"\n                                                   \"::realloc;\"\n                                                   \"::remove;\"\n                                                   \"::rename;\"\n                                                   \"::scanf;\"\n                                                   \"::scanf_s;\"\n                                                   \"::setlocale;\"\n                                                   \"::setvbuf;\"\n                                                   \"::signal;\"\n                                                   \"::snprintf;\"\n                                                   \"::snprintf_s;\"\n                                                   \"::sprintf;\"\n                                                   \"::sprintf_s;\"\n                                                   \"::sscanf;\"\n                                                   \"::sscanf_s;\"\n                                                   \"::strchr;\"\n                                                   \"::strerror_s;\"\n                                                   \"::strftime;\"\n                                                   \"::strpbrk;\"\n                                                   \"::strrchr;\"\n                                                   \"::strstr;\"\n                                                   \"::strtod;\"\n                                                   \"::strtof;\"\n                                                   \"::strtoimax;\"\n                                                   \"::strtok;\"\n                                                   \"::strtok_s;\"\n                                                   \"::strtol;\"\n                                                   \"::strtold;\"\n                                                   \"::strtoll;\"\n                                                   \"::strtoul;\"\n                                                   \"::strtoull;\"\n                                                   \"::strtoumax;\"\n                                                   \"::strxfrm;\"\n                                                   \"::swprintf;\"\n                                                   \"::swprintf_s;\"\n                                                   \"::swscanf;\"\n                                                   \"::swscanf_s;\"\n                                                   \"::thrd_create;\"\n                                                   \"::thrd_detach;\"\n                                                   \"::thrd_join;\"\n                                                   \"::thrd_sleep;\"\n                                                   \"::time;\"\n                                                   \"::timespec_get;\"\n                                                   \"::tmpfile;\"\n                                                   \"::tmpfile_s;\"\n                                                   \"::tmpnam;\"\n                                                   \"::tmpnam_s;\"\n                                                   \"::tss_create;\"\n                                                   \"::tss_get;\"\n                                                   \"::tss_set;\"\n                                                   \"::ungetc;\"\n                                                   \"::ungetwc;\"\n                                                   \"::vfprintf;\"\n                                                   \"::vfprintf_s;\"\n                                                   \"::vfscanf;\"\n                                                   \"::vfscanf_s;\"\n                                                   \"::vfwprintf;\"\n                                                   \"::vfwprintf_s;\"\n                                                   \"::vfwscanf;\"\n                                                   \"::vfwscanf_s;\"\n                                                   \"::vprintf_s;\"\n                                                   \"::vscanf;\"\n                                                   \"::vscanf_s;\"\n                                                   \"::vsnprintf;\"\n                                                   \"::vsnprintf_s;\"\n                                                   \"::vsprintf;\"\n                                                   \"::vsprintf_s;\"\n                                                   \"::vsscanf;\"\n                                                   \"::vsscanf_s;\"\n                                                   \"::vswprintf;\"\n                                                   \"::vswprintf_s;\"\n                                                   \"::vswscanf;\"\n                                                   \"::vswscanf_s;\"\n                                                   \"::vwprintf_s;\"\n                                                   \"::vwscanf;\"\n                                                   \"::vwscanf_s;\"\n                                                   \"::wcrtomb;\"\n                                                   \"::wcschr;\"\n                                                   \"::wcsftime;\"\n                                                   \"::wcspbrk;\"\n                                                   \"::wcsrchr;\"\n                                                   \"::wcsrtombs;\"\n                                                   \"::wcsrtombs_s;\"\n                                                   \"::wcsstr;\"\n                                                   \"::wcstod;\"\n                                                   \"::wcstof;\"\n                                                   \"::wcstoimax;\"\n                                                   \"::wcstok;\"\n                                                   \"::wcstok_s;\"\n                                                   \"::wcstol;\"\n                                                   \"::wcstold;\"\n                                                   \"::wcstoll;\"\n                                                   \"::wcstombs;\"\n                                                   \"::wcstombs_s;\"\n                                                   \"::wcstoul;\"\n                                                   \"::wcstoull;\"\n                                                   \"::wcstoumax;\"\n                                                   \"::wcsxfrm;\"\n                                                   \"::wctob;\"\n                                                   \"::wctrans;\"\n                                                   \"::wctype;\"\n                                                   \"::wmemchr;\"\n                                                   \"::wprintf_s;\"\n                                                   \"::wscanf;\"\n                                                   \"::wscanf_s;\";\n\n} \/\/ namespace\n\nnamespace clang {\nnamespace tidy {\nnamespace cert {\n\nclass CERTModule : public ClangTidyModule {\npublic:\n  void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {\n    \/\/ C++ checkers\n    \/\/ CON\n    CheckFactories.registerCheck<bugprone::SpuriouslyWakeUpFunctionsCheck>(\n        \"cert-con54-cpp\");\n    \/\/ DCL\n    CheckFactories.registerCheck<PostfixOperatorCheck>(\n        \"cert-dcl21-cpp\");\n    CheckFactories.registerCheck<VariadicFunctionDefCheck>(\"cert-dcl50-cpp\");\n    CheckFactories.registerCheck<bugprone::ReservedIdentifierCheck>(\n        \"cert-dcl51-cpp\");\n    CheckFactories.registerCheck<misc::NewDeleteOverloadsCheck>(\n        \"cert-dcl54-cpp\");\n    CheckFactories.registerCheck<DontModifyStdNamespaceCheck>(\n        \"cert-dcl58-cpp\");\n    CheckFactories.registerCheck<google::build::UnnamedNamespaceInHeaderCheck>(\n        \"cert-dcl59-cpp\");\n    \/\/ ERR\n    CheckFactories.registerCheck<misc::ThrowByValueCatchByReferenceCheck>(\n        \"cert-err09-cpp\");\n    CheckFactories.registerCheck<SetLongJmpCheck>(\"cert-err52-cpp\");\n    CheckFactories.registerCheck<StaticObjectExceptionCheck>(\"cert-err58-cpp\");\n    CheckFactories.registerCheck<ThrownExceptionTypeCheck>(\"cert-err60-cpp\");\n    CheckFactories.registerCheck<misc::ThrowByValueCatchByReferenceCheck>(\n        \"cert-err61-cpp\");\n    \/\/ MEM\n    CheckFactories.registerCheck<DefaultOperatorNewAlignmentCheck>(\n        \"cert-mem57-cpp\");\n    \/\/ MSC\n    CheckFactories.registerCheck<LimitedRandomnessCheck>(\"cert-msc50-cpp\");\n    CheckFactories.registerCheck<ProperlySeededRandomGeneratorCheck>(\n        \"cert-msc51-cpp\");\n    \/\/ OOP\n    CheckFactories.registerCheck<performance::MoveConstructorInitCheck>(\n        \"cert-oop11-cpp\");\n    CheckFactories.registerCheck<bugprone::UnhandledSelfAssignmentCheck>(\n        \"cert-oop54-cpp\");\n    CheckFactories.registerCheck<NonTrivialTypesLibcMemoryCallsCheck>(\n        \"cert-oop57-cpp\");\n    CheckFactories.registerCheck<MutatingCopyCheck>(\n        \"cert-oop58-cpp\");\n\n    \/\/ C checkers\n    \/\/ CON\n    CheckFactories.registerCheck<bugprone::SpuriouslyWakeUpFunctionsCheck>(\n        \"cert-con36-c\");\n    \/\/ DCL\n    CheckFactories.registerCheck<misc::StaticAssertCheck>(\"cert-dcl03-c\");\n    CheckFactories.registerCheck<readability::UppercaseLiteralSuffixCheck>(\n        \"cert-dcl16-c\");\n    CheckFactories.registerCheck<bugprone::ReservedIdentifierCheck>(\n        \"cert-dcl37-c\");\n    \/\/ ENV\n    CheckFactories.registerCheck<CommandProcessorCheck>(\"cert-env33-c\");\n    \/\/ ERR\n    CheckFactories.registerCheck<bugprone::UnusedReturnValueCheck>(\n        \"cert-err33-c\");\n    CheckFactories.registerCheck<StrToNumCheck>(\"cert-err34-c\");\n    \/\/ EXP\n    CheckFactories.registerCheck<bugprone::SuspiciousMemoryComparisonCheck>(\n        \"cert-exp42-c\");\n    \/\/ FLP\n    CheckFactories.registerCheck<FloatLoopCounter>(\"cert-flp30-c\");\n    CheckFactories.registerCheck<bugprone::SuspiciousMemoryComparisonCheck>(\n        \"cert-flp37-c\");\n    \/\/ FIO\n    CheckFactories.registerCheck<misc::NonCopyableObjectsCheck>(\"cert-fio38-c\");\n    \/\/ MSC\n    CheckFactories.registerCheck<LimitedRandomnessCheck>(\"cert-msc30-c\");\n    CheckFactories.registerCheck<ProperlySeededRandomGeneratorCheck>(\n        \"cert-msc32-c\");\n    \/\/ POS\n    CheckFactories.registerCheck<bugprone::BadSignalToKillThreadCheck>(\n        \"cert-pos44-c\");\n    CheckFactories\n        .registerCheck<concurrency::ThreadCanceltypeAsynchronousCheck>(\n            \"cert-pos47-c\");\n    \/\/ SIG\n    CheckFactories.registerCheck<bugprone::SignalHandlerCheck>(\"cert-sig30-c\");\n    \/\/ STR\n    CheckFactories.registerCheck<bugprone::SignedCharMisuseCheck>(\n        \"cert-str34-c\");\n  }\n\n  ClangTidyOptions getModuleOptions() override {\n    ClangTidyOptions Options;\n    ClangTidyOptions::OptionMap &Opts = Options.CheckOptions;\n    Opts[\"cert-dcl16-c.NewSuffixes\"] = \"L;LL;LU;LLU\";\n    Opts[\"cert-err33-c.CheckedFunctions\"] = CertErr33CCheckedFunctions;\n    Opts[\"cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField\"] = \"false\";\n    Opts[\"cert-str34-c.DiagnoseSignedUnsignedCharComparisons\"] = \"false\";\n    return Options;\n  }\n};\n\n} \/\/ namespace cert\n\n\/\/ Register the MiscTidyModule using this statically initialized variable.\nstatic ClangTidyModuleRegistry::Add<cert::CERTModule>\n    X(\"cert-module\",\n      \"Adds lint checks corresponding to CERT secure coding guidelines.\");\n\n\/\/ This anchor is used to force the linker to link in the generated object file\n\/\/ and thus register the CERTModule.\nvolatile int CERTModuleAnchorSource = 0;\n\n} \/\/ namespace tidy\n} \/\/ namespace clang\n","avg_line_length":52.6831395349,"max_line_length":80,"alphanum_fraction":0.3475142085,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4383,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\n\/*\n    Filename:\n        common.cpp\n    Author:\n        Vincent Heins \/ TheMysteriousVincent\n    Description:\n        This class holds static functions for common things, like converting an string to an int, e.g...\n*\/\n\n#include \"common.h\"\n\n\/*\n    Publicity: public\n    Return type: void\n    Name\/Type: strReplace()\n    Description: replaces each char in *oldChar with *New\n*\/\nvoid A3URLCommon::StrReplace(std::string *s, const char *oldArr, const char *New)\n{\n    std::string chars(oldArr);\n    for (const char &c : chars)\n    {\n        \/\/TODO: create for loop for comparison -> less loops.\n        size_t found = s->find(c);\n        while (found != std::string::npos)\n        {\n            if (strcmp(New, \"\") == 0)\n            {\n                s->erase(found, 1);\n            }\n            else\n            {\n                s->replace(found, 1, New);\n            }\n\n            found = s->find(c);\n        }\n    }\n}\n\n\/*\n    Publicity: public\n    Return type: int\n    Name\/Type: strToInt()\n    Description: converts a std::string to int !safely!\n*\/\nint A3URLCommon::StrToInt(std::string s)\n{\n    int i;\n    try\n    {\n        A3URLCommon::StrReplace(&s, \"\\\"'abcdefghijklmnopqrstuvzxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\u00f6\u00e4\u00fc\u00d6\u00c4\u00dc-_*~+#`\u00b4?\\\\\u00df}{[]()\/&%\", \"\");\n        i = std::stoi(s);\n    }\n    catch (const std::invalid_argument &e)\n    {\n        i = 0;\n    }\n    catch (const std::out_of_range &e)\n    {\n        i = 0;\n    }\n\n    return i;\n};\n\n\/\/A3URLCommon::StrUnquote unquotes a given string pointer\nvoid A3URLCommon::StrUnqoute(std::string *s)\n{\n    if (s->size() > 0)\n    {\n        if (s->compare(s->size() - 1, 1, \"\\\"\") == 0)\n            s->erase(s->size() - 1);\n\n        if (s->compare(0, 1, \"\\\"\") == 0)\n            s->erase(0, 1);\n    }\n};\n\n\/\/A3URLCommon::MergeStringMaps merges two given std::map<std::string, std::string> maps\nstd::map<std::string, std::string> A3URLCommon::MergeStringMaps(std::map<std::string, std::string> m1, std::map<std::string, std::string> m2)\n{\n    \/\/m2 -> overwrites -> m1\n    for (std::map<std::string, std::string>::iterator it = m2.begin(); it != m2.end(); ++it)\n        m1[it->first] = it->second;\n    \n    return m1;\n};\n\n\/\/A3URLCommon::ToArray is the init function for the json array to ArmA 3 array convertion\nstd::string A3URLCommon::ToArray(std::string jTxt)\n{\n    nlohmann::json j = nlohmann::json::parse(jTxt);\n    std::stringstream res;\n\n    if (j.is_array())\n    {\n        res << \"[\\\"array\\\",\" << A3URLCommon::toArray_array(j) << \"]\";\n    }\n    else if (j.is_object())\n    {\n        res << \"[\\\"object\\\",\" << A3URLCommon::toArray_object(j) << \"]\";\n    }\n\n    return res.str();\n};\n\n\/\/A3URLCommon::toArray_array formats only JSON arrays to an ArmA 3 array\nstd::string A3URLCommon::toArray_array(nlohmann::json j)\n{\n    std::stringstream res;\n\n    res << \"[\";\n    for (unsigned int i = 0; i < j.size(); i++)\n    {\n        if (i != 0)\n            res << \",\";\n\n        if (j[i].is_number() || j[i].is_boolean() || j[i].is_string())\n        {\n            res << j[i];\n        }\n        else if (j[i].is_null())\n        {\n            res << \"null\";\n        }\n        else if (j[i].is_object())\n        {\n            res << \"[\\\"object\\\",\" << A3URLCommon::toArray_object(j[i]) << \"]\";\n        }\n        else if (j[i].is_array())\n        {\n            res << \"[\\\"array\\\",\" << A3URLCommon::toArray_array(j[i]) << \"]\";\n        }\n    }\n    res << \"]\";\n\n    return res.str();\n};\n\n\/\/A3URLCommon::toArray_object formats a JSON object to an ArmA 3 array\nstd::string A3URLCommon::toArray_object(nlohmann::json j)\n{\n    std::stringstream res;\n\n    res << \"[\";\n    for (nlohmann::json::iterator it = j.begin(); it != j.end(); ++it)\n    {\n        if (it != j.begin())\n            res << \",\";\n\n        if (it.value().is_number() || it.value().is_boolean() || it.value().is_string())\n        {\n            res << \"[\\\"\" << it.key() << \"\\\",\" << it.value() << \"]\";\n        }\n        else if (it.value().is_null())\n        {\n            res << \"[\\\"\" << it.key() << \",null]\";\n        }\n        else if (it.value().is_object())\n        {\n            res << \"[\\\"\" << it.key() << \"\\\",[\\\"object\\\",\" << A3URLCommon::toArray_object(it.value()) << \"]]\";\n        }\n        else if (it.value().is_array())\n        {\n            res << \"[\\\"\" << it.key() << \"\\\",[\\\"array\\\",\" << A3URLCommon::toArray_array(it.value()) << \"]]\";\n        }\n    }\n    res << \"]\";\n\n    return res.str();\n};\n","avg_line_length":25.1896551724,"max_line_length":141,"alphanum_fraction":0.501026694,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2143,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\ufeff\/\/ Copyright (C) 2018-2021 Intel Corporation\n\/\/ SPDX-License-Identifier: Apache-2.0\n\/\/\n\n#include \"low_precision\/avg_pool.hpp\"\n\n#include <memory>\n#include <ngraph\/ngraph.hpp>\n#include <ngraph\/opsets\/opset1.hpp>\n\n#include \"low_precision\/network_helper.hpp\"\n\nnamespace ngraph {\nnamespace pass {\nnamespace low_precision {\n\nAvgPoolTransformation::AvgPoolTransformation(const Params& params) : LayerTransformation(params) {\n}\n\nvoid AvgPoolTransformation::registerMatcherIn(GraphRewrite &pass, TransformationContext &context) const {\n    addPattern(\n        pass,\n        context,\n        make_op_pattern<opset1::AvgPool>({ make_op_label<opset1::Multiply>() }));\n}\n\nbool AvgPoolTransformation::transform(TransformationContext& context, ngraph::pattern::Matcher &m) const {\n    if (!canBeTransformed(context, m.get_match_root())) {\n        return false;\n    }\n\n    const std::shared_ptr<Node> pooling = NetworkHelper::separateInStandaloneBranch(m.get_match_root());\n\n    const std::vector<std::shared_ptr<ngraph::Node>> children = getChildrenRecursivelyExceptPrecisionPreserved(pooling);\n\n    bool updatePrecision;\n    if ((children.size() == 1ul) && (!this->layerTransformationsManager->isQuantized(children[0]))) {\n        updatePrecision = false;\n    } else {\n        updatePrecision = NetworkHelper::notAllChildrensAreFQ(children);\n    }\n\n    moveDequantizationAfter(context, pooling, NetworkHelper::getDequantization(pooling), updatePrecision);\n    return true;\n}\n\nbool AvgPoolTransformation::canBeTransformed(const TransformationContext& context, std::shared_ptr<Node> operation) const {\n    if (!LayerTransformation::canBeTransformed(context, operation)) {\n        return false;\n    }\n\n    auto dequantization = NetworkHelper::getDequantization(operation);\n\n    return !dequantization.empty();\n}\n\nbool AvgPoolTransformation::isPrecisionPreserved(std::shared_ptr<Node> layer) const noexcept {\n    const std::vector<std::shared_ptr<ngraph::Node>> children = getChildrenRecursivelyExceptPrecisionPreserved(layer);\n    return NetworkHelper::notAllChildrensAreFQ(children);\n}\n\n} \/\/ namespace low_precision\n} \/\/ namespace pass\n} \/\/ namespace ngraph\n","avg_line_length":32.9692307692,"max_line_length":123,"alphanum_fraction":0.74895007,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5844,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"stdafx.h\"\n\n#include \"V8Helpers.h\"\n#include \"helpers\/BindHelpers.h\"\n#include \"V8ResourceImpl.h\"\n\nusing namespace alt;\n\nstatic void IsEntityIn(const v8::FunctionCallbackInfo<v8::Value>& info)\n{\n    V8_GET_ISOLATE_CONTEXT();\n    V8_CHECK_ARGS_LEN(1);\n    V8_GET_THIS_BASE_OBJECT(_this, IColShape);\n    V8_ARG_TO_BASE_OBJECT(1, ent, IEntity, \"Entity\");\n\n    V8_RETURN_BOOLEAN(_this->IsEntityIn(ent));\n}\n\nstatic void IsPointIn(const v8::FunctionCallbackInfo<v8::Value>& info)\n{\n    V8_GET_ISOLATE_CONTEXT();\n    V8_CHECK_ARGS_LEN(1);\n    V8_GET_THIS_BASE_OBJECT(_this, IColShape);\n    V8_ARG_TO_VECTOR3(1, point);\n\n    V8_RETURN_BOOLEAN(_this->IsPointIn(point));\n}\n\nextern V8Class v8WorldObject;\nextern V8Class v8Colshape(\"Colshape\", v8WorldObject, nullptr, [](v8::Local<v8::FunctionTemplate> tpl) {\n    v8::Isolate* isolate = v8::Isolate::GetCurrent();\n\n    V8Helpers::SetAccessor<IColShape, IColShape::ColShapeType, &IColShape::GetColshapeType>(isolate, tpl, \"colshapeType\");\n    V8Helpers::SetAccessor<IColShape, bool, &IColShape::IsPlayersOnly, &IColShape::SetPlayersOnly>(isolate, tpl, \"playersOnly\");\n\n    V8Helpers::SetMethod(isolate, tpl, \"isEntityIn\", IsEntityIn);\n    V8Helpers::SetMethod(isolate, tpl, \"isPointIn\", IsPointIn);\n});\n\nextern V8Class v8ColshapeCylinder(\n  \"ColshapeCylinder\",\n  v8Colshape,\n  [](const v8::FunctionCallbackInfo<v8::Value>& info) {\n      V8_GET_ISOLATE_CONTEXT_RESOURCE();\n\n      V8_CHECK(info.IsConstructCall(), \"ColshapeCylinder constructor is not a function\");\n      V8_CHECK_ARGS_LEN(5);\n\n      V8_ARG_TO_NUMBER(1, x);\n      V8_ARG_TO_NUMBER(2, y);\n      V8_ARG_TO_NUMBER(3, z);\n      V8_ARG_TO_NUMBER(4, radius);\n      V8_ARG_TO_NUMBER(5, height);\n\n      Ref<IColShape> cs = ICore::Instance().CreateColShapeCylinder({ x, y, z }, radius, height);\n      V8_CHECK(!cs.IsEmpty(), \"Failed to create ColshapeCylinder\");\n\n      resource->BindEntity(info.This(), cs.Get());\n  },\n  [](v8::Local<v8::FunctionTemplate> tpl) {});\n\nextern V8Class v8ColshapeSphere(\n  \"ColshapeSphere\",\n  v8Colshape,\n  [](const v8::FunctionCallbackInfo<v8::Value>& info) {\n      V8_GET_ISOLATE_CONTEXT_RESOURCE();\n\n      V8_CHECK(info.IsConstructCall(), \"ColshapeSphere constructor is not a function\");\n      V8_CHECK_ARGS_LEN(4);\n\n      V8_ARG_TO_NUMBER(1, x);\n      V8_ARG_TO_NUMBER(2, y);\n      V8_ARG_TO_NUMBER(3, z);\n      V8_ARG_TO_NUMBER(4, radius);\n\n      Ref<IColShape> cs = alt::ICore::Instance().CreateColShapeSphere({ x, y, z }, radius);\n      V8_CHECK(!cs.IsEmpty(), \"Failed to create ColshapeSphere\");\n\n      resource->BindEntity(info.This(), cs.Get());\n  },\n  [](v8::Local<v8::FunctionTemplate> tpl) {});\n\nextern V8Class v8ColshapeCircle(\n  \"ColshapeCircle\",\n  v8Colshape,\n  [](const v8::FunctionCallbackInfo<v8::Value>& info) {\n      V8_GET_ISOLATE_CONTEXT_RESOURCE();\n\n      V8_CHECK(info.IsConstructCall(), \"ColshapeCircle constructor is not a function\");\n      V8_CHECK_ARGS_LEN(3);\n\n      V8_ARG_TO_NUMBER(1, x);\n      V8_ARG_TO_NUMBER(2, y);\n      V8_ARG_TO_NUMBER(3, radius);\n\n      Ref<IColShape> cs = alt::ICore::Instance().CreateColShapeCircle({ x, y, 0 }, radius);\n      V8_CHECK(!cs.IsEmpty(), \"Failed to create ColshapeCircle\");\n\n      resource->BindEntity(info.This(), cs.Get());\n  },\n  [](v8::Local<v8::FunctionTemplate> tpl) {});\n\nextern V8Class v8ColshapeCuboid(\n  \"ColshapeCuboid\",\n  v8Colshape,\n  [](const v8::FunctionCallbackInfo<v8::Value>& info) {\n      V8_GET_ISOLATE_CONTEXT_RESOURCE();\n\n      V8_CHECK(info.IsConstructCall(), \"ColshapeCuboid constructor is not a function\");\n      V8_CHECK_ARGS_LEN(6);\n\n      V8_ARG_TO_NUMBER(1, x1);\n      V8_ARG_TO_NUMBER(2, y1);\n      V8_ARG_TO_NUMBER(3, z1);\n      V8_ARG_TO_NUMBER(4, x2);\n      V8_ARG_TO_NUMBER(5, y2);\n      V8_ARG_TO_NUMBER(6, z2);\n\n      Ref<IColShape> cs = alt::ICore::Instance().CreateColShapeCube({ x1, y1, z1 }, { x2, y2, z2 });\n      V8_CHECK(!cs.IsEmpty(), \"Failed to create ColshapeCuboid\");\n\n      resource->BindEntity(info.This(), cs.Get());\n  },\n  [](v8::Local<v8::FunctionTemplate> tpl) {});\n\nextern V8Class v8ColshapeRectangle(\n  \"ColshapeRectangle\",\n  v8Colshape,\n  [](const v8::FunctionCallbackInfo<v8::Value>& info) {\n      V8_GET_ISOLATE_CONTEXT_RESOURCE();\n\n      V8_CHECK(info.IsConstructCall(), \"ColshapeRectangle constructor is not a function\");\n      V8_CHECK_ARGS_LEN(4);\n\n      V8_ARG_TO_NUMBER(1, x1);\n      V8_ARG_TO_NUMBER(2, y1);\n      V8_ARG_TO_NUMBER(3, x2);\n      V8_ARG_TO_NUMBER(4, y2);\n\n      Ref<IColShape> cs = alt::ICore::Instance().CreateColShapeRectangle(x1, y1, x2, y2, 0);\n      V8_CHECK(!cs.IsEmpty(), \"Failed to create ColshapeRectangle\");\n\n      resource->BindEntity(info.This(), cs.Get());\n  },\n  [](v8::Local<v8::FunctionTemplate> tpl) {});\n\nextern V8Class v8ColshapePolygon(\n  \"ColshapePolygon\",\n  v8Colshape,\n  [](const v8::FunctionCallbackInfo<v8::Value>& info) {\n      V8_GET_ISOLATE_CONTEXT_RESOURCE();\n      V8_CHECK_CONSTRUCTOR();\n      V8_CHECK_ARGS_LEN(3);\n\n      V8_ARG_TO_NUMBER(1, minZ);\n      V8_ARG_TO_NUMBER(2, maxZ);\n\n      V8_CHECK(info[2]->IsArray(), \"Argument 3 is not an array\");\n      v8::Local<v8::Array> arr = info[2].As<v8::Array>();\n      std::vector<Vector2f> points;\n      uint32_t len = arr->Length();\n      for(uint32_t i = 0; i < len; ++i)\n      {\n          v8::MaybeLocal<v8::Value> maybeVal = arr->Get(ctx, i);\n          if(maybeVal.IsEmpty()) continue;\n          v8::Local<v8::Value> val = maybeVal.ToLocalChecked();\n          V8_CHECK(resource->IsVector2(val), \"Invalid item in array, expected Vector2\");\n          V8_TO_VECTOR2(val, point);\n          points.push_back(point);\n      }\n\n      Ref<IColShape> cs = alt::ICore::Instance().CreateColShapePolygon(minZ, maxZ, points);\n      V8_CHECK(!cs.IsEmpty(), \"Failed to create ColShapePolygon\");\n\n      resource->BindEntity(info.This(), cs.Get());\n  },\n  [](v8::Local<v8::FunctionTemplate> tpl) {});\n","avg_line_length":32.8314606742,"max_line_length":128,"alphanum_fraction":0.6735112936,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1513,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n    Copyright (c) 2018-2021 Xavier Leclercq\n\n    Permission is hereby granted, free of charge, to any person obtaining a\n    copy of this software and associated documentation files (the \"Software\"),\n    to deal in the Software without restriction, including without limitation\n    the rights to use, copy, modify, merge, publish, distribute, sublicense,\n    and\/or sell copies of the Software, and to permit persons to whom the\n    Software is furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n    IN THE SOFTWARE.\n*\/\n\n#include \"TreeDBKeyTests.h\"\n#include \"TreeDBValueTests.h\"\n#include <Ishiko\/Tests.h>\n\nusing namespace Ishiko::Tests;\n\nint main(int argc, char* argv[])\n{\n    TestHarness theTestHarness(\"DiplodocusTreeDBCore\");\n\n    TestSequence& theTests = theTestHarness.tests();\n    theTests.append<TreeDBKeyTests>();\n    theTests.append<TreeDBValueTests>();\n\n    return theTestHarness.run();\n}\n","avg_line_length":38.7948717949,"max_line_length":80,"alphanum_fraction":0.7501652346,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1648,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":28.0,"content":"\/* TEMPLATE GENERATED TESTCASE FILE\r\nFilename: CWE590_Free_Memory_Not_on_Heap__delete_int64_t_alloca_68b.cpp\r\nLabel Definition File: CWE590_Free_Memory_Not_on_Heap__delete.pointer.label.xml\r\nTemplate File: sources-sink-68b.tmpl.cpp\r\n*\/\r\n\/*\r\n * @description\r\n * CWE: 590 Free Memory Not on Heap\r\n * BadSource: alloca Data buffer is allocated on the stack with alloca()\r\n * GoodSource: Allocate memory on the heap\r\n * Sink:\r\n *    BadSink : Print then free data\r\n * Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files\r\n *\r\n * *\/\r\n\r\n#include \"std_testcase.h\"\r\n\r\n#include <wchar.h>\r\n\r\nextern int64_t * CWE590_Free_Memory_Not_on_Heap__delete_int64_t_alloca_68_badData;\r\nextern int64_t * CWE590_Free_Memory_Not_on_Heap__delete_int64_t_alloca_68_goodG2BData;\r\n\r\nnamespace CWE590_Free_Memory_Not_on_Heap__delete_int64_t_alloca_68\r\n{\r\n\r\n\/* all the sinks are the same, we just want to know where the hit originated if a tool flags one *\/\r\n\r\n#ifndef OMITBAD\r\n\r\nvoid badSink()\r\n{\r\n    int64_t * data = CWE590_Free_Memory_Not_on_Heap__delete_int64_t_alloca_68_badData;\r\n    printLongLongLine(*data);\r\n    \/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack *\/\r\n    delete data;\r\n}\r\n\r\n#endif \/* OMITBAD *\/\r\n\r\n#ifndef OMITGOOD\r\n\r\n\/* goodG2B uses the GoodSource with the BadSink *\/\r\nvoid goodG2BSink()\r\n{\r\n    int64_t * data = CWE590_Free_Memory_Not_on_Heap__delete_int64_t_alloca_68_goodG2BData;\r\n    printLongLongLine(*data);\r\n    \/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack *\/\r\n    delete data;\r\n}\r\n\r\n#endif \/* OMITGOOD *\/\r\n\r\n} \/* close namespace *\/\r\n","avg_line_length":29.9636363636,"max_line_length":119,"alphanum_fraction":0.7524271845,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2013,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/ RUN: %clangxx -fsycl -fsyntax-only -Xclang -verify %s -Xclang -verify-ignore-unexpected=note\n\n#include <sycl\/ext\/oneapi\/atomic_ref.hpp>\n\nstruct A {};\n\nint main() {\n  double d = 10.0;\n  auto ref_d =\n      sycl::ext::oneapi::atomic_ref<double,\n                                    sycl::ext::oneapi::memory_order_acq_rel,\n                                    sycl::ext::oneapi::memory_scope_device,\n                                    sycl::access::address_space::local_space>(\n          d);\n  \/\/ expected-warning@-5 {{is deprecated: use 'sycl::atomic_ref' instead}}\n  \/\/ expected-warning@-5 {{'memory_order_acq_rel' is deprecated: use 'sycl::memory_order_acq_rel' instead}}\n  \/\/ expected-warning@-5 {{'memory_scope_device' is deprecated: use 'sycl::memory_scope_device' instead}}\n\n  int i = 10;\n  auto ref_i =\n      sycl::ext::oneapi::atomic_ref<int,\n                                    sycl::ext::oneapi::memory_order_acq_rel,\n                                    sycl::ext::oneapi::memory_scope_device,\n                                    sycl::access::address_space::local_space>(\n          i);\n  \/\/ expected-warning@-5 {{is deprecated: use 'sycl::atomic_ref' instead}}\n  \/\/ expected-warning@-5 {{'memory_order_acq_rel' is deprecated: use 'sycl::memory_order_acq_rel' instead}}\n  \/\/ expected-warning@-5 {{'memory_scope_device' is deprecated: use 'sycl::memory_scope_device' instead}}\n\n  A a;\n  A *p = &a;\n  auto ref_p =\n      sycl::ext::oneapi::atomic_ref<A *,\n                                    sycl::ext::oneapi::memory_order_acq_rel,\n                                    sycl::ext::oneapi::memory_scope_device,\n                                    sycl::access::address_space::local_space>(\n          p);\n  \/\/ expected-warning@-5 {{is deprecated: use 'sycl::atomic_ref' instead}}\n  \/\/ expected-warning@-5 {{'memory_order_acq_rel' is deprecated: use 'sycl::memory_order_acq_rel' instead}}\n  \/\/ expected-warning@-5 {{'memory_scope_device' is deprecated: use 'sycl::memory_scope_device' instead}}\n\n  return 0;\n}\n","avg_line_length":45.75,"max_line_length":107,"alphanum_fraction":0.5931445604,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4835,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":4.0,"content":"\/*\nCopyright (c) 1999 - 2010, Vodafone Group Services Ltd\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n    * 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.\n    * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS 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.\n*\/\n\n#include \"config.h\"\n\n#include \"RedLineSettings.h\"\n\n#include \"Packet.h\"\n#include \"PacketHelpers.h\"\n\nnamespace {\n   static RedLineSettings::speedVect_t createDefaultSpeedVect()\n   {\n      RedLineSettings::speedVect_t vect;\n      \/\/ 50 meters from 0 km\/h and up\n      vect.push_back( make_pair( 0, 50 ) );\n      return vect;\n   }\n}\n\n\/\/ Init the default vector\nRedLineSettings::speedVect_t \nRedLineSettings::c_defaultSpeedVect = createDefaultSpeedVect();\n\nRedLineSettings::RedLineSettings( bool include_connecting_roads,\n                                  const speedVect_t& speedvect )\n      : m_speedVect( speedvect ),\n        m_incConnecting( include_connecting_roads )\n{\n   \/\/ All is well that ends well\n   \/\/ Good.\n}\n\nRedLineSettings::RedLineSettings() : m_speedVect( c_defaultSpeedVect ),\n                                     m_incConnecting( false )\n{\n}\n\nstatic void writeSpeedVect( Packet* packet,\n                            int& pos,\n                            const RedLineSettings::speedVect_t& vect )\n{\n   packet->incWriteLong( pos, vect.size() );\n   for ( RedLineSettings::speedVect_t::const_iterator it = vect.begin();\n         it != vect.end();\n         ++it ) {      \n      packet->incWriteLong( pos, it->first );\n      packet->incWriteLong( pos, it->second );\n      mc2dbg8 << \"[RLH]: Writing \" << it->first << \"_\" << it->second << endl;\n   }\n}\n\nint\nRedLineSettings::save( Packet* packet, int& pos ) const\n{\n   \/\/ Save the length\n   SaveLengthHelper slh( packet, pos );\n   slh.writeDummyLength( pos );\n\n   \/\/ Save the data\n   packet->incWriteLong( pos, m_incConnecting );\n\n   writeSpeedVect( packet, pos, m_speedVect );\n   writeSpeedVect( packet, pos, m_bboxSpeedVect );\n   \n   \/\/ Update the length\n   mc2dbg8 << \"[RLS]: Save Endpos before = \" << pos << endl;\n   uint32 tmp = slh.updateLengthUsingEndPos( pos );\n   mc2dbg8 << \"[RLS]: Save Endpos AFTER = \" << pos << endl;\n   return tmp;\n}\n\nstatic void readSpeedVect( const Packet* packet,\n                           int& pos,\n                           RedLineSettings::speedVect_t& vect )\n{\n   int vectSize = packet->incReadLong( pos );\n   vect.resize( vectSize );\n   for ( int i = 0; i < vectSize; ++i ) {\n      vect[i].first  = packet->incReadLong( pos );\n      vect[i].second = packet->incReadLong( pos );\n   }\n}\n\nint\nRedLineSettings::load( const Packet* packet, int& pos )\n{\n   \/\/ Clear the data\n   m_speedVect.clear();\n   m_bboxSpeedVect.clear();\n\n   \/\/ Init the helper and load the length.\n   LoadLengthHelper llh( packet, pos, \"[RedLineS]\" );\n   llh.loadLength( pos );\n\n   \/\/ Load the known data\n   packet->incReadLong( pos, m_incConnecting );\n\n   readSpeedVect( packet, pos, m_speedVect );\n   if( llh.available( pos ) > 0 )\n      readSpeedVect( packet, pos, m_bboxSpeedVect );\n   \n   \/\/ Skip unknown\n   return llh.skipUnknown( pos );   \n}\n\nuint32\nRedLineSettings::getSizeInPacket() const\n{\n   return 4 + 4 + 4 + 8 * m_speedVect.size();\n}\n\nostream& operator<<(ostream& o, const RedLineSettings& s )\n{\n   o << \"[RLS]: Con=\" << s.m_incConnecting\n     << \" \";\n   const char* comma = \"\";\n   for ( RedLineSettings::speedVect_t::const_iterator it =\n            s.m_speedVect.begin();\n         it != s.m_speedVect.end();\n         ++it ) {\n      o << comma;\n      o << it->first << \"_\" << it->second;\n      comma = \",\";\n   }\n   return o;\n}\n\n","avg_line_length":34.7841726619,"max_line_length":755,"alphanum_fraction":0.6692864529,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":114006,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2015, 2016, 2017 Howard Hinnant\n\/\/ Copyright (c) 2015 Ville Voutilainen\n\/\/ Copyright (c) 2016 Alexander Kormanovsky\n\/\/ Copyright (c) 2016, 2017 Jiangang Zhuang\n\/\/ Copyright (c) 2017 Nicolas Veloz Savino\n\/\/ Copyright (c) 2017 Florian Dang\n\/\/ Copyright (c) 2017 Aaron Bishop\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ Our apologies.  When the previous paragraph was written, lowercase had not yet\n\/\/ been invented (that would involve another several millennia of evolution).\n\/\/ We did not mean to shout.\n\n#ifdef _WIN32\n   \/\/ windows.h will be included directly and indirectly (e.g. by curl).\n   \/\/ We need to define these macros to prevent windows.h bringing in\n   \/\/ more than we need and do it early so windows.h doesn't get included\n   \/\/ without these macros having been defined.\n   \/\/ min\/max macros interfere with the C++ versions.\n#  ifndef NOMINMAX\n#    define NOMINMAX\n#  endif\n   \/\/ We don't need all that Windows has to offer.\n#  ifndef WIN32_LEAN_AND_MEAN\n#    define WIN32_LEAN_AND_MEAN\n#  endif\n\n   \/\/ for wcstombs\n#  ifndef _CRT_SECURE_NO_WARNINGS\n#    define _CRT_SECURE_NO_WARNINGS\n#  endif\n\n   \/\/ None of this happens with the MS SDK (at least VS14 which I tested), but:\n   \/\/ Compiling with mingw, we get \"error: 'KF_FLAG_DEFAULT' was not declared in this scope.\"\n   \/\/ and error: 'SHGetKnownFolderPath' was not declared in this scope.\".\n   \/\/ It seems when using mingw NTDDI_VERSION is undefined and that\n   \/\/ causes KNOWN_FOLDER_FLAG and the KF_ flags to not get defined.\n   \/\/ So we must define NTDDI_VERSION to get those flags on mingw.\n   \/\/ The docs say though here:\n   \/\/ https:\/\/msdn.microsoft.com\/en-nz\/library\/windows\/desktop\/aa383745(v=vs.85).aspx\n   \/\/ that \"If you define NTDDI_VERSION, you must also define _WIN32_WINNT.\"\n   \/\/ So we declare we require Vista or greater.\n#  ifdef __MINGW32__\n\n#    ifndef NTDDI_VERSION\n#      define NTDDI_VERSION 0x06000000\n#      define _WIN32_WINNT _WIN32_WINNT_VISTA\n#    elif NTDDI_VERSION < 0x06000000\n#      warning \"If this fails to compile NTDDI_VERSION may be to low. See comments above.\"\n#    endif\n     \/\/ But once we define the values above we then get this linker error:\n     \/\/ \"tz.cpp:(.rdata$.refptr.FOLDERID_Downloads[.refptr.FOLDERID_Downloads]+0x0): \"\n     \/\/     \"undefined reference to `FOLDERID_Downloads'\"\n     \/\/ which #include <initguid.h> cures see:\n     \/\/ https:\/\/support.microsoft.com\/en-us\/kb\/130869\n#    include <initguid.h>\n     \/\/ But with <initguid.h> included, the error moves on to:\n     \/\/ error: 'FOLDERID_Downloads' was not declared in this scope\n     \/\/ Which #include <knownfolders.h> cures.\n#    include <knownfolders.h>\n\n#  endif  \/\/ __MINGW32__\n\n#  include <windows.h>\n#endif  \/\/ _WIN32\n\n#include \"date\/tz_private.h\"\n\n#ifdef __APPLE__\n#  include \"date\/ios.h\"\n#else\n#  define TARGET_OS_IPHONE 0\n#endif\n\n#if USE_OS_TZDB\n#  include <dirent.h>\n#endif\n#include <algorithm>\n#include <cctype>\n#include <cstdlib>\n#include <cstring>\n#include <cwchar>\n#include <exception>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <memory>\n#if USE_OS_TZDB\n#  include <queue>\n#endif\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <vector>\n#include <sys\/stat.h>\n\n\/\/ unistd.h is used on some platforms as part of the the means to get\n\/\/ the current time zone. On Win32 windows.h provides a means to do it.\n\/\/ gcc\/mingw supports unistd.h on Win32 but MSVC does not.\n\n#ifdef _WIN32\n#  ifdef WINAPI_FAMILY\n#    include <winapifamily.h>\n#    if WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP\n#      define WINRT\n#      define INSTALL .\n#    endif\n#  endif\n\n#  include <io.h> \/\/ _unlink etc.\n\n#  if defined(__clang__)\n    struct IUnknown;    \/\/ fix for issue with static_cast<> in objbase.h\n                        \/\/   (see https:\/\/github.com\/philsquared\/Catch\/issues\/690)\n#  endif\n\n#  include <shlobj.h> \/\/ CoTaskFree, ShGetKnownFolderPath etc.\n#  if HAS_REMOTE_API\n#    include <direct.h> \/\/ _mkdir\n#    include <shellapi.h> \/\/ ShFileOperation etc.\n#  endif  \/\/ HAS_REMOTE_API\n#else   \/\/ !_WIN32\n#  include <unistd.h>\n#  if !USE_OS_TZDB\n#    include <wordexp.h>\n#  endif\n#  include <limits.h>\n#  include <string.h>\n#  if !USE_SHELL_API\n#    include <sys\/stat.h>\n#    include <sys\/fcntl.h>\n#    include <dirent.h>\n#    include <cstring>\n#    include <sys\/wait.h>\n#    include <sys\/types.h>\n#  endif \/\/!USE_SHELL_API\n#endif  \/\/ !_WIN32\n\n\n#if HAS_REMOTE_API\n   \/\/ Note curl includes windows.h so we must include curl AFTER definitions of things\n   \/\/ that affect windows.h such as NOMINMAX.\n#if defined(_MSC_VER) && defined(SHORTENED_CURL_INCLUDE)\n   \/\/ For rmt_curl nuget package\n#  include <curl.h>\n#else\n#  include <curl\/curl.h>\n#endif\n#endif\n\n#ifdef _WIN32\nstatic CONSTDATA char folder_delimiter = '\\\\';\n#else   \/\/ !_WIN32\nstatic CONSTDATA char folder_delimiter = '\/';\n#endif  \/\/ !_WIN32\n\n#if defined(__GNUC__) && __GNUC__ < 5\n   \/\/ GCC 4.9 Bug 61489 Wrong warning with -Wmissing-field-initializers\n#  pragma GCC diagnostic push\n#  pragma GCC diagnostic ignored \"-Wmissing-field-initializers\"\n#endif  \/\/ defined(__GNUC__) && __GNUC__ < 5\n\n#if !USE_OS_TZDB\n\n#  ifdef _WIN32\n#    ifndef WINRT\n\nnamespace\n{\n    struct task_mem_deleter\n    {\n        void operator()(wchar_t buf[])\n        {\n            if (buf != nullptr)\n                CoTaskMemFree(buf);\n        }\n    };\n    using co_task_mem_ptr = std::unique_ptr<wchar_t[], task_mem_deleter>;\n}\n\n\/\/ We might need to know certain locations even if not using the remote API,\n\/\/ so keep these routines out of that block for now.\nstatic\nstd::string\nget_known_folder(const GUID& folderid)\n{\n    std::string folder;\n    PWSTR pfolder = nullptr;\n    HRESULT hr = SHGetKnownFolderPath(folderid, KF_FLAG_DEFAULT, nullptr, &pfolder);\n    if (SUCCEEDED(hr))\n    {\n        co_task_mem_ptr folder_ptr(pfolder);\n        const wchar_t* fptr = folder_ptr.get();\n        auto state = std::mbstate_t();\n        const auto required = std::wcsrtombs(nullptr, &fptr, 0, &state);\n        if (required != 0 && required != std::size_t(-1))\n        {\n            folder.resize(required);\n            std::wcsrtombs(&folder[0], &fptr, folder.size(), &state);\n        }\n    }\n    return folder;\n}\n\n#      ifndef INSTALL\n\n\/\/ Usually something like \"c:\\Users\\username\\Downloads\".\nstatic\nstd::string\nget_download_folder()\n{\n    return get_known_folder(FOLDERID_Downloads);\n}\n\n#      endif  \/\/ !INSTALL\n\n#    endif \/\/ WINRT\n#  else \/\/ !_WIN32\n\n#    if !defined(INSTALL)\n\nstatic\nstd::string\nexpand_path(std::string path)\n{\n#      if TARGET_OS_IPHONE\n    return date::iOSUtils::get_tzdata_path();\n#      else  \/\/ !TARGET_OS_IPHONE\n    ::wordexp_t w{};\n    std::unique_ptr<::wordexp_t, void(*)(::wordexp_t*)> hold{&w, ::wordfree};\n    ::wordexp(path.c_str(), &w, 0);\n    if (w.we_wordc != 1)\n        throw std::runtime_error(\"Cannot expand path: \" + path);\n    path = w.we_wordv[0];\n    return path;\n#      endif  \/\/ !TARGET_OS_IPHONE\n}\n\nstatic\nstd::string\nget_download_folder()\n{\n    return expand_path(\"~\/Downloads\");\n}\n\n#    endif \/\/ !defined(INSTALL)\n\n#  endif  \/\/ !_WIN32\n\n#endif  \/\/ !USE_OS_TZDB\n\nnamespace date\n{\n\/\/ +---------------------+\n\/\/ | Begin Configuration |\n\/\/ +---------------------+\n\nusing namespace detail;\n\n#if !USE_OS_TZDB\n\nstatic\nstd::string&\naccess_install()\n{\n    static std::string install\n#ifndef INSTALL\n\n    = get_download_folder() + folder_delimiter + \"tzdata\";\n\n#else   \/\/ !INSTALL\n\n#  define STRINGIZEIMP(x) #x\n#  define STRINGIZE(x) STRINGIZEIMP(x)\n\n    = STRINGIZE(INSTALL) + std::string(1, folder_delimiter) + \"tzdata\";\n\n    #undef STRINGIZEIMP\n    #undef STRINGIZE\n#endif  \/\/ !INSTALL\n\n    return install;\n}\n\nvoid\nset_install(const std::string& s)\n{\n    access_install() = s;\n}\n\nstatic\nconst std::string&\nget_install()\n{\n    static const std::string& ref = access_install();\n    return ref;\n}\n\n#if HAS_REMOTE_API\nstatic\nstd::string\nget_download_gz_file(const std::string& version)\n{\n    auto file = get_install() + version + \".tar.gz\";\n    return file;\n}\n#endif  \/\/ HAS_REMOTE_API\n\n#endif  \/\/ !USE_OS_TZDB\n\n\/\/ These can be used to reduce the range of the database to save memory\nCONSTDATA auto min_year = date::year::min();\nCONSTDATA auto max_year = date::year::max();\n\nCONSTDATA auto min_day = date::January\/1;\nCONSTDATA auto max_day = date::December\/31;\n\n#if USE_OS_TZDB\n\nCONSTCD14 const sys_seconds min_seconds = sys_days(min_year\/min_day);\n\n#endif  \/\/ USE_OS_TZDB\n\n#ifndef _WIN32\n\nstatic\nstd::string\ndiscover_tz_dir()\n{\n    struct stat sb;\n    using namespace std;\n#  ifndef __APPLE__\n    CONSTDATA auto tz_dir_default = \"\/usr\/share\/zoneinfo\";\n    CONSTDATA auto tz_dir_buildroot = \"\/usr\/share\/zoneinfo\/uclibc\";\n\n    \/\/ Check special path which is valid for buildroot with uclibc builds\n    if(stat(tz_dir_buildroot, &sb) == 0 && S_ISDIR(sb.st_mode))\n        return tz_dir_buildroot;\n    else if(stat(tz_dir_default, &sb) == 0 && S_ISDIR(sb.st_mode))\n        return tz_dir_default;\n    else\n        throw runtime_error(\"discover_tz_dir failed to find zoneinfo\\n\");\n#  else  \/\/ __APPLE__\n#      if TARGET_OS_IPHONE\n    return \"\/var\/db\/timezone\/zoneinfo\";\n#      else\n    CONSTDATA auto timezone = \"\/etc\/localtime\";\n    if (!(lstat(timezone, &sb) == 0 && S_ISLNK(sb.st_mode) && sb.st_size > 0))\n        throw runtime_error(\"discover_tz_dir failed\\n\");\n    string result;\n    char rp[PATH_MAX+1] = {};\n    if (readlink(timezone, rp, sizeof(rp)-1) > 0)\n        result = string(rp);\n    else\n        throw system_error(errno, system_category(), \"readlink() failed\");\n    auto i = result.find(\"zoneinfo\");\n    if (i == string::npos)\n        throw runtime_error(\"discover_tz_dir failed to find zoneinfo\\n\");\n    i = result.find('\/', i);\n    if (i == string::npos)\n        throw runtime_error(\"discover_tz_dir failed to find '\/'\\n\");\n    return result.substr(0, i);\n#      endif\n#  endif  \/\/ __APPLE__\n}\n\nstatic\nconst std::string&\nget_tz_dir()\n{\n    static const std::string tz_dir = discover_tz_dir();\n    return tz_dir;\n}\n\n#endif\n\n\/\/ +-------------------+\n\/\/ | End Configuration |\n\/\/ +-------------------+\n\n#ifndef _MSC_VER\nstatic_assert(min_year <= max_year, \"Configuration error\");\n#endif\n\nstatic std::unique_ptr<tzdb> init_tzdb();\n\ntzdb_list::~tzdb_list()\n{\n    const tzdb* ptr = head_;\n    head_ = nullptr;\n    while (ptr != nullptr)\n    {\n        auto next = ptr->next;\n        delete ptr;\n        ptr = next;\n    }\n}\n\ntzdb_list::tzdb_list(tzdb_list&& x) noexcept\n   : head_{x.head_.exchange(nullptr)}\n{\n}\n\nvoid\ntzdb_list::push_front(tzdb* tzdb) noexcept\n{\n    tzdb->next = head_;\n    head_ = tzdb;\n}\n\ntzdb_list::const_iterator\ntzdb_list::erase_after(const_iterator p) noexcept\n{\n    auto t = p.p_->next;\n    p.p_->next = p.p_->next->next;\n    delete t;\n    return ++p;\n}\n\nstruct tzdb_list::undocumented_helper\n{\n    static void push_front(tzdb_list& db_list, tzdb* tzdb) noexcept\n    {\n        db_list.push_front(tzdb);\n    }\n};\n\nstatic\ntzdb_list\ncreate_tzdb()\n{\n    tzdb_list tz_db;\n    tzdb_list::undocumented_helper::push_front(tz_db, init_tzdb().release());\n    return tz_db;\n}\n\ntzdb_list&\nget_tzdb_list()\n{\n    static tzdb_list tz_db = create_tzdb();\n    return tz_db;\n}\n\n#if !USE_OS_TZDB\n\n#ifdef _WIN32\n\nstatic\nvoid\nsort_zone_mappings(std::vector<date::detail::timezone_mapping>& mappings)\n{\n    std::sort(mappings.begin(), mappings.end(),\n        [](const date::detail::timezone_mapping& lhs,\n           const date::detail::timezone_mapping& rhs)->bool\n    {\n        auto other_result = lhs.other.compare(rhs.other);\n        if (other_result < 0)\n            return true;\n        else if (other_result == 0)\n        {\n            auto territory_result = lhs.territory.compare(rhs.territory);\n            if (territory_result < 0)\n                return true;\n            else if (territory_result == 0)\n            {\n                if (lhs.type < rhs.type)\n                    return true;\n            }\n        }\n        return false;\n    });\n}\n\nstatic\nbool\nnative_to_standard_timezone_name(const std::string& native_tz_name,\n                                 std::string& standard_tz_name)\n{\n    \/\/ TOOD! Need be a case insensitive compare?\n    if (native_tz_name == \"UTC\")\n    {\n        standard_tz_name = \"Etc\/UTC\";\n        return true;\n    }\n    standard_tz_name.clear();\n    \/\/ TODO! we can improve on linear search.\n    const auto& mappings = date::get_tzdb().mappings;\n    for (const auto& tzm : mappings)\n    {\n        if (tzm.other == native_tz_name)\n        {\n            standard_tz_name = tzm.type;\n            return true;\n        }\n    }\n    return false;\n}\n\n\/\/ Parse this XML file:\n\/\/ https:\/\/raw.githubusercontent.com\/unicode-org\/cldr\/master\/common\/supplemental\/windowsZones.xml\n\/\/ The parsing method is designed to be simple and quick. It is not overly\n\/\/ forgiving of change but it should diagnose basic format issues.\n\/\/ See timezone_mapping structure for more info.\nstatic\nstd::vector<detail::timezone_mapping>\nload_timezone_mappings_from_xml_file(const std::string& input_path)\n{\n    std::size_t line_num = 0;\n    std::vector<detail::timezone_mapping> mappings;\n    std::string line;\n\n    std::ifstream is(input_path);\n    if (!is.is_open())\n    {\n        \/\/ We don't emit file exceptions because that's an implementation detail.\n        std::string msg = \"Error opening time zone mapping file \\\"\";\n        msg += input_path;\n        msg += \"\\\".\";\n        throw std::runtime_error(msg);\n    }\n\n    auto error = [&input_path, &line_num](const char* info)\n    {\n        std::string msg = \"Error loading time zone mapping file \\\"\";\n        msg += input_path;\n        msg += \"\\\" at line \";\n        msg += std::to_string(line_num);\n        msg += \": \";\n        msg += info;\n        throw std::runtime_error(msg);\n    };\n    \/\/ [optional space]a=\"b\"\n    auto read_attribute = [&line, &error]\n                          (const char* name, std::string& value, std::size_t startPos)\n                          ->std::size_t\n    {\n        value.clear();\n        \/\/ Skip leading space before attribute name.\n        std::size_t spos = line.find_first_not_of(' ', startPos);\n        if (spos == std::string::npos)\n            spos = startPos;\n        \/\/ Assume everything up to next = is the attribute name\n        \/\/ and that an = will always delimit that.\n        std::size_t epos = line.find('=', spos);\n        if (epos == std::string::npos)\n            error(\"Expected \\'=\\' right after attribute name.\");\n        std::size_t name_len = epos - spos;\n        \/\/ Expect the name we find matches the name we expect.\n        if (line.compare(spos, name_len, name) != 0)\n        {\n            std::string msg;\n            msg = \"Expected attribute name \\'\";\n            msg += name;\n            msg += \"\\' around position \";\n            msg += std::to_string(spos);\n            msg += \" but found something else.\";\n            error(msg.c_str());\n        }\n        ++epos; \/\/ Skip the '=' that is after the attribute name.\n        spos = epos;\n        if (spos < line.length() && line[spos] == '\\\"')\n            ++spos; \/\/ Skip the quote that is before the attribute value.\n        else\n        {\n            std::string msg = \"Expected '\\\"' to begin value of attribute \\'\";\n            msg += name;\n            msg += \"\\'.\";\n            error(msg.c_str());\n        }\n        epos = line.find('\\\"', spos);\n        if (epos == std::string::npos)\n        {\n            std::string msg = \"Expected '\\\"' to end value of attribute \\'\";\n            msg += name;\n            msg += \"\\'.\";\n            error(msg.c_str());\n        }\n        \/\/ Extract everything in between the quotes. Note no escaping is done.\n        std::size_t value_len = epos - spos;\n        value.assign(line, spos, value_len);\n        ++epos; \/\/ Skip the quote that is after the attribute value;\n        return epos;\n    };\n\n    \/\/ Quick but not overly forgiving XML mapping file processing.\n    bool mapTimezonesOpenTagFound = false;\n    bool mapTimezonesCloseTagFound = false;\n    std::size_t mapZonePos = std::string::npos;\n    std::size_t mapTimezonesPos = std::string::npos;\n    CONSTDATA char mapTimeZonesOpeningTag[] = { \"<mapTimezones \" };\n    CONSTDATA char mapZoneOpeningTag[] = { \"<mapZone \" };\n    CONSTDATA std::size_t mapZoneOpeningTagLen = sizeof(mapZoneOpeningTag) \/\n                                                 sizeof(mapZoneOpeningTag[0]) - 1;\n    while (!mapTimezonesOpenTagFound)\n    {\n        std::getline(is, line);\n        ++line_num;\n        if (is.eof())\n        {\n            \/\/ If there is no mapTimezones tag is it an error?\n            \/\/ Perhaps if there are no mapZone mappings it might be ok for\n            \/\/ its parent mapTimezones element to be missing?\n            \/\/ We treat this as an error though on the assumption that if there\n            \/\/ really are no mappings we should still get a mapTimezones parent\n            \/\/ element but no mapZone elements inside. Assuming we must\n            \/\/ find something will hopefully at least catch more drastic formatting\n            \/\/ changes or errors than if we don't do this and assume nothing found.\n            error(\"Expected a mapTimezones opening tag.\");\n        }\n        mapTimezonesPos = line.find(mapTimeZonesOpeningTag);\n        mapTimezonesOpenTagFound = (mapTimezonesPos != std::string::npos);\n    }\n\n    \/\/ NOTE: We could extract the version info that follows the opening\n    \/\/ mapTimezones tag and compare that to the version of other data we have.\n    \/\/ I would have expected them to be kept in synch but testing has shown\n    \/\/ it typically does not match anyway. So what's the point?\n    while (!mapTimezonesCloseTagFound)\n    {\n        std::ws(is);\n        std::getline(is, line);\n        ++line_num;\n        if (is.eof())\n            error(\"Expected a mapTimezones closing tag.\");\n        if (line.empty())\n            continue;\n        mapZonePos = line.find(mapZoneOpeningTag);\n        if (mapZonePos != std::string::npos)\n        {\n            mapZonePos += mapZoneOpeningTagLen;\n            detail::timezone_mapping zm{};\n            std::size_t pos = read_attribute(\"other\", zm.other, mapZonePos);\n            pos = read_attribute(\"territory\", zm.territory, pos);\n            read_attribute(\"type\", zm.type, pos);\n            mappings.push_back(std::move(zm));\n\n            continue;\n        }\n        mapTimezonesPos = line.find(\"<\/mapTimezones>\");\n        mapTimezonesCloseTagFound = (mapTimezonesPos != std::string::npos);\n        if (!mapTimezonesCloseTagFound)\n        {\n            std::size_t commentPos = line.find(\"<!--\");\n            if (commentPos == std::string::npos)\n                error(\"Unexpected mapping record found. A xml mapZone or comment \"\n                      \"attribute or mapTimezones closing tag was expected.\");\n        }\n    }\n\n    is.close();\n    return mappings;\n}\n\n#endif  \/\/ _WIN32\n\n\/\/ Parsing helpers\n\nstatic\nstd::string\nparse3(std::istream& in)\n{\n    std::string r(3, ' ');\n    ws(in);\n    r[0] = static_cast<char>(in.get());\n    r[1] = static_cast<char>(in.get());\n    r[2] = static_cast<char>(in.get());\n    return r;\n}\n\nstatic\nunsigned\nparse_dow(std::istream& in)\n{\n    CONSTDATA char*const dow_names[] =\n        {\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"};\n    auto s = parse3(in);\n    auto dow = std::find(std::begin(dow_names), std::end(dow_names), s) - dow_names;\n    if (dow >= std::end(dow_names) - std::begin(dow_names))\n        throw std::runtime_error(\"oops: bad dow name: \" + s);\n    return static_cast<unsigned>(dow);\n}\n\nstatic\nunsigned\nparse_month(std::istream& in)\n{\n    CONSTDATA char*const month_names[] =\n        {\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n         \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"};\n    auto s = parse3(in);\n    auto m = std::find(std::begin(month_names), std::end(month_names), s) - month_names;\n    if (m >= std::end(month_names) - std::begin(month_names))\n        throw std::runtime_error(\"oops: bad month name: \" + s);\n    return static_cast<unsigned>(++m);\n}\n\nstatic\nstd::chrono::seconds\nparse_unsigned_time(std::istream& in)\n{\n    using namespace std::chrono;\n    int x;\n    in >> x;\n    auto r = seconds{hours{x}};\n    if (!in.eof() && in.peek() == ':')\n    {\n        in.get();\n        in >> x;\n        r += minutes{x};\n        if (!in.eof() && in.peek() == ':')\n        {\n            in.get();\n            in >> x;\n            r += seconds{x};\n        }\n    }\n    return r;\n}\n\nstatic\nstd::chrono::seconds\nparse_signed_time(std::istream& in)\n{\n    ws(in);\n    auto sign = 1;\n    if (in.peek() == '-')\n    {\n        sign = -1;\n        in.get();\n    }\n    else if (in.peek() == '+')\n        in.get();\n    return sign * parse_unsigned_time(in);\n}\n\n\/\/ MonthDayTime\n\ndetail::MonthDayTime::MonthDayTime(local_seconds tp, tz timezone)\n    : zone_(timezone)\n{\n    using namespace date;\n    const auto dp = date::floor<days>(tp);\n    const auto hms = make_time(tp - dp);\n    const auto ymd = year_month_day(dp);\n    u = ymd.month() \/ ymd.day();\n    h_ = hms.hours();\n    m_ = hms.minutes();\n    s_ = hms.seconds();\n}\n\ndetail::MonthDayTime::MonthDayTime(const date::month_day& md, tz timezone)\n    : zone_(timezone)\n{\n    u = md;\n}\n\ndate::day\ndetail::MonthDayTime::day() const\n{\n    switch (type_)\n    {\n    case month_day:\n        return u.month_day_.day();\n    case month_last_dow:\n        return date::day{31};\n    case lteq:\n    case gteq:\n        break;\n    }\n    return u.month_day_weekday_.month_day_.day();\n}\n\ndate::month\ndetail::MonthDayTime::month() const\n{\n    switch (type_)\n    {\n    case month_day:\n        return u.month_day_.month();\n    case month_last_dow:\n        return u.month_weekday_last_.month();\n    case lteq:\n    case gteq:\n        break;\n    }\n    return u.month_day_weekday_.month_day_.month();\n}\n\nint\ndetail::MonthDayTime::compare(date::year y, const MonthDayTime& x, date::year yx,\n                      std::chrono::seconds offset, std::chrono::minutes prev_save) const\n{\n    if (zone_ != x.zone_)\n    {\n        auto dp0 = to_sys_days(y);\n        auto dp1 = x.to_sys_days(yx);\n        if (std::abs((dp0-dp1).count()) > 1)\n            return dp0 < dp1 ? -1 : 1;\n        if (zone_ == tz::local)\n        {\n            auto tp0 = to_time_point(y) - prev_save;\n            if (x.zone_ == tz::utc)\n                tp0 -= offset;\n            auto tp1 = x.to_time_point(yx);\n            return tp0 < tp1 ? -1 : tp0 == tp1 ? 0 : 1;\n        }\n        else if (zone_ == tz::standard)\n        {\n            auto tp0 = to_time_point(y);\n            auto tp1 = x.to_time_point(yx);\n            if (x.zone_ == tz::local)\n                tp1 -= prev_save;\n            else\n                tp0 -= offset;\n            return tp0 < tp1 ? -1 : tp0 == tp1 ? 0 : 1;\n        }\n        \/\/ zone_ == tz::utc\n        auto tp0 = to_time_point(y);\n        auto tp1 = x.to_time_point(yx);\n        if (x.zone_ == tz::local)\n            tp1 -= offset + prev_save;\n        else\n            tp1 -= offset;\n        return tp0 < tp1 ? -1 : tp0 == tp1 ? 0 : 1;\n    }\n    auto const t0 = to_time_point(y);\n    auto const t1 = x.to_time_point(yx);\n    return t0 < t1 ? -1 : t0 == t1 ? 0 : 1;\n}\n\nsys_seconds\ndetail::MonthDayTime::to_sys(date::year y, std::chrono::seconds offset,\n                     std::chrono::seconds save) const\n{\n    using namespace date;\n    using namespace std::chrono;\n    auto until_utc = to_time_point(y);\n    if (zone_ == tz::standard)\n        until_utc -= offset;\n    else if (zone_ == tz::local)\n        until_utc -= offset + save;\n    return until_utc;\n}\n\ndetail::MonthDayTime::U&\ndetail::MonthDayTime::U::operator=(const date::month_day& x)\n{\n    month_day_ = x;\n    return *this;\n}\n\ndetail::MonthDayTime::U&\ndetail::MonthDayTime::U::operator=(const date::month_weekday_last& x)\n{\n    month_weekday_last_ = x;\n    return *this;\n}\n\ndetail::MonthDayTime::U&\ndetail::MonthDayTime::U::operator=(const pair& x)\n{\n    month_day_weekday_ = x;\n    return *this;\n}\n\ndate::sys_days\ndetail::MonthDayTime::to_sys_days(date::year y) const\n{\n    using namespace std::chrono;\n    using namespace date;\n    switch (type_)\n    {\n    case month_day:\n        return sys_days(y\/u.month_day_);\n    case month_last_dow:\n        return sys_days(y\/u.month_weekday_last_);\n    case lteq:\n        {\n            auto const x = y\/u.month_day_weekday_.month_day_;\n            auto const wd1 = weekday(static_cast<sys_days>(x));\n            auto const wd0 = u.month_day_weekday_.weekday_;\n            return sys_days(x) - (wd1-wd0);\n        }\n    case gteq:\n        break;\n    }\n    auto const x = y\/u.month_day_weekday_.month_day_;\n    auto const wd1 = u.month_day_weekday_.weekday_;\n    auto const wd0 = weekday(static_cast<sys_days>(x));\n    return sys_days(x) + (wd1-wd0);\n}\n\nsys_seconds\ndetail::MonthDayTime::to_time_point(date::year y) const\n{\n    \/\/ Add seconds first to promote to largest rep early to prevent overflow\n    return to_sys_days(y) + s_ + h_ + m_;\n}\n\nvoid\ndetail::MonthDayTime::canonicalize(date::year y)\n{\n    using namespace std::chrono;\n    using namespace date;\n    switch (type_)\n    {\n    case month_day:\n        return;\n    case month_last_dow:\n        {\n            auto const ymd = year_month_day(sys_days(y\/u.month_weekday_last_));\n            u.month_day_ = ymd.month()\/ymd.day();\n            type_ = month_day;\n            return;\n        }\n    case lteq:\n        {\n            auto const x = y\/u.month_day_weekday_.month_day_;\n            auto const wd1 = weekday(static_cast<sys_days>(x));\n            auto const wd0 = u.month_day_weekday_.weekday_;\n            auto const ymd = year_month_day(sys_days(x) - (wd1-wd0));\n            u.month_day_ = ymd.month()\/ymd.day();\n            type_ = month_day;\n            return;\n        }\n    case gteq:\n        {\n            auto const x = y\/u.month_day_weekday_.month_day_;\n            auto const wd1 = u.month_day_weekday_.weekday_;\n            auto const wd0 = weekday(static_cast<sys_days>(x));\n            auto const ymd = year_month_day(sys_days(x) + (wd1-wd0));\n            u.month_day_ = ymd.month()\/ymd.day();\n            type_ = month_day;\n            return;\n        }\n    }\n}\n\nstd::istream&\ndetail::operator>>(std::istream& is, MonthDayTime& x)\n{\n    using namespace date;\n    using namespace std::chrono;\n    assert(((std::ios::failbit | std::ios::badbit) & is.exceptions()) ==\n            (std::ios::failbit | std::ios::badbit));\n    x = MonthDayTime{};\n    if (!is.eof() && ws(is) && !is.eof() && is.peek() != '#')\n    {\n        auto m = parse_month(is);\n        if (!is.eof() && ws(is) && !is.eof() && is.peek() != '#')\n        {\n            if (is.peek() == 'l')\n            {\n                for (int i = 0; i < 4; ++i)\n                    is.get();\n                auto dow = parse_dow(is);\n                x.type_ = MonthDayTime::month_last_dow;\n                x.u = date::month(m)\/weekday(dow)[last];\n            }\n            else if (std::isalpha(is.peek()))\n            {\n                auto dow = parse_dow(is);\n                char c{};\n                is >> c;\n                if (c == '<' || c == '>')\n                {\n                    char c2{};\n                    is >> c2;\n                    if (c2 != '=')\n                        throw std::runtime_error(std::string(\"bad operator: \") + c + c2);\n                    int d;\n                    is >> d;\n                    if (d < 1 || d > 31)\n                        throw std::runtime_error(std::string(\"bad operator: \") + c + c2\n                                 + std::to_string(d));\n                    x.type_ = c == '<' ? MonthDayTime::lteq : MonthDayTime::gteq;\n                    x.u = MonthDayTime::pair{ date::month(m) \/ d, date::weekday(dow) };\n                }\n                else\n                    throw std::runtime_error(std::string(\"bad operator: \") + c);\n            }\n            else  \/\/ if (std::isdigit(is.peek())\n            {\n                int d;\n                is >> d;\n                if (d < 1 || d > 31)\n                    throw std::runtime_error(std::string(\"day of month: \")\n                             + std::to_string(d));\n                x.type_ = MonthDayTime::month_day;\n                x.u = date::month(m)\/d;\n            }\n            if (!is.eof() && ws(is) && !is.eof() && is.peek() != '#')\n            {\n                int t;\n                is >> t;\n                x.h_ = hours{t};\n                if (!is.eof() && is.peek() == ':')\n                {\n                    is.get();\n                    is >> t;\n                    x.m_ = minutes{t};\n                    if (!is.eof() && is.peek() == ':')\n                    {\n                        is.get();\n                        is >> t;\n                        x.s_ = seconds{t};\n                    }\n                }\n                if (!is.eof() && std::isalpha(is.peek()))\n                {\n                    char c;\n                    is >> c;\n                    switch (c)\n                    {\n                    case 's':\n                        x.zone_ = tz::standard;\n                        break;\n                    case 'u':\n                        x.zone_ = tz::utc;\n                        break;\n                    }\n                }\n            }\n        }\n        else\n        {\n            x.u = month{m}\/1;\n        }\n    }\n    return is;\n}\n\nstd::ostream&\ndetail::operator<<(std::ostream& os, const MonthDayTime& x)\n{\n    switch (x.type_)\n    {\n    case MonthDayTime::month_day:\n        os << x.u.month_day_ << \"                  \";\n        break;\n    case MonthDayTime::month_last_dow:\n        os << x.u.month_weekday_last_ << \"           \";\n        break;\n    case MonthDayTime::lteq:\n        os << x.u.month_day_weekday_.weekday_ << \" on or before \"\n           << x.u.month_day_weekday_.month_day_ << \"  \";\n        break;\n    case MonthDayTime::gteq:\n        if ((static_cast<unsigned>(x.day()) - 1) % 7 == 0)\n        {\n            os << (x.u.month_day_weekday_.month_day_.month() \/\n                   x.u.month_day_weekday_.weekday_[\n                       (static_cast<unsigned>(x.day()) - 1)\/7+1]) << \"              \";\n        }\n        else\n        {\n            os << x.u.month_day_weekday_.weekday_ << \" on or after \"\n               << x.u.month_day_weekday_.month_day_ << \"  \";\n        }\n        break;\n    }\n    os << date::make_time(x.s_ + x.h_ + x.m_);\n    if (x.zone_ == tz::utc)\n        os << \"UTC   \";\n    else if (x.zone_ == tz::standard)\n        os << \"STD   \";\n    else\n        os << \"      \";\n    return os;\n}\n\n\/\/ Rule\n\ndetail::Rule::Rule(const std::string& s)\n{\n    try\n    {\n        using namespace date;\n        using namespace std::chrono;\n        std::istringstream in(s);\n        in.exceptions(std::ios::failbit | std::ios::badbit);\n        std::string word;\n        in >> word >> name_;\n        int x;\n        ws(in);\n        if (std::isalpha(in.peek()))\n        {\n            in >> word;\n            if (word == \"min\")\n            {\n                starting_year_ = year::min();\n            }\n            else\n                throw std::runtime_error(\"Didn't find expected word: \" + word);\n        }\n        else\n        {\n            in >> x;\n            starting_year_ = year{x};\n        }\n        std::ws(in);\n        if (std::isalpha(in.peek()))\n        {\n            in >> word;\n            if (word == \"only\")\n            {\n                ending_year_ = starting_year_;\n            }\n            else if (word == \"max\")\n            {\n                ending_year_ = year::max();\n            }\n            else\n                throw std::runtime_error(\"Didn't find expected word: \" + word);\n        }\n        else\n        {\n            in >> x;\n            ending_year_ = year{x};\n        }\n        in >> word;  \/\/ TYPE (always \"-\")\n        assert(word == \"-\");\n        in >> starting_at_;\n        save_ = duration_cast<minutes>(parse_signed_time(in));\n        in >> abbrev_;\n        if (abbrev_ == \"-\")\n            abbrev_.clear();\n        assert(hours{-1} <= save_ && save_ <= hours{2});\n    }\n    catch (...)\n    {\n        std::cerr << s << '\\n';\n        std::cerr << *this << '\\n';\n        throw;\n    }\n}\n\ndetail::Rule::Rule(const Rule& r, date::year starting_year, date::year ending_year)\n    : name_(r.name_)\n    , starting_year_(starting_year)\n    , ending_year_(ending_year)\n    , starting_at_(r.starting_at_)\n    , save_(r.save_)\n    , abbrev_(r.abbrev_)\n{\n}\n\nbool\ndetail::operator==(const Rule& x, const Rule& y)\n{\n    if (std::tie(x.name_, x.save_, x.starting_year_, x.ending_year_) ==\n        std::tie(y.name_, y.save_, y.starting_year_, y.ending_year_))\n        return x.month() == y.month() && x.day() == y.day();\n    return false;\n}\n\nbool\ndetail::operator<(const Rule& x, const Rule& y)\n{\n    using namespace std::chrono;\n    auto const xm = x.month();\n    auto const ym = y.month();\n    if (std::tie(x.name_, x.starting_year_, xm, x.ending_year_) <\n        std::tie(y.name_, y.starting_year_, ym, y.ending_year_))\n        return true;\n    if (std::tie(x.name_, x.starting_year_, xm, x.ending_year_) >\n        std::tie(y.name_, y.starting_year_, ym, y.ending_year_))\n        return false;\n    return x.day() < y.day();\n}\n\nbool\ndetail::operator==(const Rule& x, const date::year& y)\n{\n    return x.starting_year_ <= y && y <= x.ending_year_;\n}\n\nbool\ndetail::operator<(const Rule& x, const date::year& y)\n{\n    return x.ending_year_ < y;\n}\n\nbool\ndetail::operator==(const date::year& x, const Rule& y)\n{\n    return y.starting_year_ <= x && x <= y.ending_year_;\n}\n\nbool\ndetail::operator<(const date::year& x, const Rule& y)\n{\n    return x < y.starting_year_;\n}\n\nbool\ndetail::operator==(const Rule& x, const std::string& y)\n{\n    return x.name() == y;\n}\n\nbool\ndetail::operator<(const Rule& x, const std::string& y)\n{\n    return x.name() < y;\n}\n\nbool\ndetail::operator==(const std::string& x, const Rule& y)\n{\n    return y.name() == x;\n}\n\nbool\ndetail::operator<(const std::string& x, const Rule& y)\n{\n    return x < y.name();\n}\n\nstd::ostream&\ndetail::operator<<(std::ostream& os, const Rule& r)\n{\n    using namespace date;\n    using namespace std::chrono;\n    detail::save_ostream<char> _(os);\n    os.fill(' ');\n    os.flags(std::ios::dec | std::ios::left);\n    os.width(15);\n    os << r.name_;\n    os << r.starting_year_ << \"    \" << r.ending_year_ << \"    \";\n    os << r.starting_at_;\n    if (r.save_ >= minutes{0})\n        os << ' ';\n    os << date::make_time(r.save_) << \"   \";\n    os << r.abbrev_;\n    return os;\n}\n\ndate::day\ndetail::Rule::day() const\n{\n    return starting_at_.day();\n}\n\ndate::month\ndetail::Rule::month() const\n{\n    return starting_at_.month();\n}\n\nstruct find_rule_by_name\n{\n    bool operator()(const Rule& x, const std::string& nm) const\n    {\n        return x.name() < nm;\n    }\n\n    bool operator()(const std::string& nm, const Rule& x) const\n    {\n        return nm < x.name();\n    }\n};\n\nbool\ndetail::Rule::overlaps(const Rule& x, const Rule& y)\n{\n    \/\/ assume x.starting_year_ <= y.starting_year_;\n    if (!(x.starting_year_ <= y.starting_year_))\n    {\n        std::cerr << x << '\\n';\n        std::cerr << y << '\\n';\n        assert(x.starting_year_ <= y.starting_year_);\n    }\n    if (y.starting_year_ > x.ending_year_)\n        return false;\n    return !(x.starting_year_ == y.starting_year_ && x.ending_year_ == y.ending_year_);\n}\n\nvoid\ndetail::Rule::split(std::vector<Rule>& rules, std::size_t i, std::size_t k, std::size_t& e)\n{\n    using namespace date;\n    using difference_type = std::vector<Rule>::iterator::difference_type;\n    \/\/ rules[i].starting_year_ <= rules[k].starting_year_ &&\n    \/\/     rules[i].ending_year_ >= rules[k].starting_year_ &&\n    \/\/     (rules[i].starting_year_ != rules[k].starting_year_ ||\n    \/\/      rules[i].ending_year_ != rules[k].ending_year_)\n    assert(rules[i].starting_year_ <= rules[k].starting_year_ &&\n           rules[i].ending_year_ >= rules[k].starting_year_ &&\n           (rules[i].starting_year_ != rules[k].starting_year_ ||\n            rules[i].ending_year_ != rules[k].ending_year_));\n    if (rules[i].starting_year_ == rules[k].starting_year_)\n    {\n        if (rules[k].ending_year_ < rules[i].ending_year_)\n        {\n            rules.insert(rules.begin() + static_cast<difference_type>(k+1),\n                         Rule(rules[i], rules[k].ending_year_ + years{1},\n                              std::move(rules[i].ending_year_)));\n            ++e;\n            rules[i].ending_year_ = rules[k].ending_year_;\n        }\n        else  \/\/ rules[k].ending_year_ > rules[i].ending_year_\n        {\n            rules.insert(rules.begin() + static_cast<difference_type>(k+1),\n                         Rule(rules[k], rules[i].ending_year_ + years{1},\n                              std::move(rules[k].ending_year_)));\n            ++e;\n            rules[k].ending_year_ = rules[i].ending_year_;\n        }\n    }\n    else  \/\/ rules[i].starting_year_ < rules[k].starting_year_\n    {\n        if (rules[k].ending_year_ < rules[i].ending_year_)\n        {\n            rules.insert(rules.begin() + static_cast<difference_type>(k),\n                         Rule(rules[i], rules[k].starting_year_, rules[k].ending_year_));\n            ++k;\n            rules.insert(rules.begin() + static_cast<difference_type>(k+1),\n                         Rule(rules[i], rules[k].ending_year_ + years{1},\n                              std::move(rules[i].ending_year_)));\n            rules[i].ending_year_ = rules[k].starting_year_ - years{1};\n            e += 2;\n        }\n        else if (rules[k].ending_year_ > rules[i].ending_year_)\n        {\n            rules.insert(rules.begin() + static_cast<difference_type>(k),\n                         Rule(rules[i], rules[k].starting_year_, rules[i].ending_year_));\n            ++k;\n            rules.insert(rules.begin() + static_cast<difference_type>(k+1),\n                         Rule(rules[k], rules[i].ending_year_ + years{1},\n                         std::move(rules[k].ending_year_)));\n            e += 2;\n            rules[k].ending_year_ = std::move(rules[i].ending_year_);\n            rules[i].ending_year_ = rules[k].starting_year_ - years{1};\n        }\n        else  \/\/ rules[k].ending_year_ == rules[i].ending_year_\n        {\n            rules.insert(rules.begin() + static_cast<difference_type>(k),\n                         Rule(rules[i], rules[k].starting_year_,\n                         std::move(rules[i].ending_year_)));\n            ++k;\n            ++e;\n            rules[i].ending_year_ = rules[k].starting_year_ - years{1};\n        }\n    }\n}\n\nvoid\ndetail::Rule::split_overlaps(std::vector<Rule>& rules, std::size_t i, std::size_t& e)\n{\n    using difference_type = std::vector<Rule>::iterator::difference_type;\n    auto j = i;\n    for (; i + 1 < e; ++i)\n    {\n        for (auto k = i + 1; k < e; ++k)\n        {\n            if (overlaps(rules[i], rules[k]))\n            {\n                split(rules, i, k, e);\n                std::sort(rules.begin() + static_cast<difference_type>(i),\n                          rules.begin() + static_cast<difference_type>(e));\n            }\n        }\n    }\n    for (; j < e; ++j)\n    {\n        if (rules[j].starting_year() == rules[j].ending_year())\n            rules[j].starting_at_.canonicalize(rules[j].starting_year());\n    }\n}\n\nvoid\ndetail::Rule::split_overlaps(std::vector<Rule>& rules)\n{\n    using difference_type = std::vector<Rule>::iterator::difference_type;\n    for (std::size_t i = 0; i < rules.size();)\n    {\n        auto e = static_cast<std::size_t>(std::upper_bound(\n            rules.cbegin()+static_cast<difference_type>(i), rules.cend(), rules[i].name(),\n            [](const std::string& nm, const Rule& x)\n            {\n                return nm < x.name();\n            }) - rules.cbegin());\n        split_overlaps(rules, i, e);\n        auto first_rule = rules.begin() + static_cast<difference_type>(i);\n        auto last_rule = rules.begin() + static_cast<difference_type>(e);\n        auto t = std::lower_bound(first_rule, last_rule, min_year);\n        if (t > first_rule+1)\n        {\n            if (t == last_rule || t->starting_year() >= min_year)\n                --t;\n            auto d = static_cast<std::size_t>(t - first_rule);\n            rules.erase(first_rule, t);\n            e -= d;\n        }\n        first_rule = rules.begin() + static_cast<difference_type>(i);\n        last_rule = rules.begin() + static_cast<difference_type>(e);\n        t = std::upper_bound(first_rule, last_rule, max_year);\n        if (t != last_rule)\n        {\n            auto d = static_cast<std::size_t>(last_rule - t);\n            rules.erase(t, last_rule);\n            e -= d;\n        }\n        i = e;\n    }\n    rules.shrink_to_fit();\n}\n\n\/\/ Find the rule that comes chronologically before Rule r.  For multi-year rules,\n\/\/ y specifies which rules in r.  For single year rules, y is assumed to be equal\n\/\/ to the year specified by r.\n\/\/ Returns a pointer to the chronologically previous rule, and the year within\n\/\/ that rule.  If there is no previous rule, returns nullptr and year::min().\n\/\/ Preconditions:\n\/\/     r->starting_year() <= y && y <= r->ending_year()\nstatic\nstd::pair<const Rule*, date::year>\nfind_previous_rule(const Rule* r, date::year y)\n{\n    using namespace date;\n    auto const& rules = get_tzdb().rules;\n    if (y == r->starting_year())\n    {\n        if (r == &rules.front() || r->name() != r[-1].name())\n            std::terminate();  \/\/ never called with first rule\n        --r;\n        if (y == r->starting_year())\n            return {r, y};\n        return {r, r->ending_year()};\n    }\n    if (r == &rules.front() || r->name() != r[-1].name() ||\n        r[-1].starting_year() < r->starting_year())\n    {\n        while (r < &rules.back() && r->name() == r[1].name() &&\n               r->starting_year() == r[1].starting_year())\n            ++r;\n        return {r, --y};\n    }\n    --r;\n    return {r, y};\n}\n\n\/\/ Find the rule that comes chronologically after Rule r.  For multi-year rules,\n\/\/ y specifies which rules in r.  For single year rules, y is assumed to be equal\n\/\/ to the year specified by r.\n\/\/ Returns a pointer to the chronologically next rule, and the year within\n\/\/ that rule.  If there is no next rule, return a pointer to a defaulted rule\n\/\/ and y+1.\n\/\/ Preconditions:\n\/\/     first <= r && r < last && r->starting_year() <= y && y <= r->ending_year()\n\/\/     [first, last) all have the same name\nstatic\nstd::pair<const Rule*, date::year>\nfind_next_rule(const Rule* first_rule, const Rule* last_rule, const Rule* r, date::year y)\n{\n    using namespace date;\n    if (y == r->ending_year())\n    {\n        if (r == last_rule-1)\n            return {nullptr, year::max()};\n        ++r;\n        if (y == r->ending_year())\n            return {r, y};\n        return {r, r->starting_year()};\n    }\n    if (r == last_rule-1 || r->ending_year() < r[1].ending_year())\n    {\n        while (r > first_rule && r->starting_year() == r[-1].starting_year())\n            --r;\n        return {r, ++y};\n    }\n    ++r;\n    return {r, y};\n}\n\n\/\/ Find the rule that comes chronologically after Rule r.  For multi-year rules,\n\/\/ y specifies which rules in r.  For single year rules, y is assumed to be equal\n\/\/ to the year specified by r.\n\/\/ Returns a pointer to the chronologically next rule, and the year within\n\/\/ that rule.  If there is no next rule, return nullptr and year::max().\n\/\/ Preconditions:\n\/\/     r->starting_year() <= y && y <= r->ending_year()\nstatic\nstd::pair<const Rule*, date::year>\nfind_next_rule(const Rule* r, date::year y)\n{\n    using namespace date;\n    auto const& rules = get_tzdb().rules;\n    if (y == r->ending_year())\n    {\n        if (r == &rules.back() || r->name() != r[1].name())\n            return {nullptr, year::max()};\n        ++r;\n        if (y == r->ending_year())\n            return {r, y};\n        return {r, r->starting_year()};\n    }\n    if (r == &rules.back() || r->name() != r[1].name() ||\n        r->ending_year() < r[1].ending_year())\n    {\n        while (r > &rules.front() && r->name() == r[-1].name() &&\n               r->starting_year() == r[-1].starting_year())\n            --r;\n        return {r, ++y};\n    }\n    ++r;\n    return {r, y};\n}\n\nstatic\nconst Rule*\nfind_first_std_rule(const std::pair<const Rule*, const Rule*>& eqr)\n{\n    auto r = eqr.first;\n    auto ry = r->starting_year();\n    while (r->save() != std::chrono::minutes{0})\n    {\n        std::tie(r, ry) = find_next_rule(eqr.first, eqr.second, r, ry);\n        if (r == nullptr)\n            throw std::runtime_error(\"Could not find standard offset in rule \"\n                                     + eqr.first->name());\n    }\n    return r;\n}\n\nstatic\nstd::pair<const Rule*, date::year>\nfind_rule_for_zone(const std::pair<const Rule*, const Rule*>& eqr,\n                   const date::year& y, const std::chrono::seconds& offset,\n                   const MonthDayTime& mdt)\n{\n    assert(eqr.first != nullptr);\n    assert(eqr.second != nullptr);\n\n    using namespace std::chrono;\n    using namespace date;\n    auto r = eqr.first;\n    auto ry = r->starting_year();\n    auto prev_save = minutes{0};\n    auto prev_year = year::min();\n    const Rule* prev_rule = nullptr;\n    while (r != nullptr)\n    {\n        if (mdt.compare(y, r->mdt(), ry, offset, prev_save) <= 0)\n            break;\n        prev_rule = r;\n        prev_year = ry;\n        prev_save = prev_rule->save();\n        std::tie(r, ry) = find_next_rule(eqr.first, eqr.second, r, ry);\n    }\n    return {prev_rule, prev_year};\n}\n\nstatic\nstd::pair<const Rule*, date::year>\nfind_rule_for_zone(const std::pair<const Rule*, const Rule*>& eqr,\n                   const sys_seconds& tp_utc,\n                   const local_seconds& tp_std,\n                   const local_seconds& tp_loc)\n{\n    using namespace std::chrono;\n    using namespace date;\n    auto r = eqr.first;\n    auto ry = r->starting_year();\n    auto prev_save = minutes{0};\n    auto prev_year = year::min();\n    const Rule* prev_rule = nullptr;\n    while (r != nullptr)\n    {\n        bool found = false;\n        switch (r->mdt().zone())\n        {\n        case tz::utc:\n            found = tp_utc < r->mdt().to_time_point(ry);\n            break;\n        case tz::standard:\n            found = sys_seconds{tp_std.time_since_epoch()} < r->mdt().to_time_point(ry);\n            break;\n        case tz::local:\n            found = sys_seconds{tp_loc.time_since_epoch()} < r->mdt().to_time_point(ry);\n            break;\n        }\n        if (found)\n            break;\n        prev_rule = r;\n        prev_year = ry;\n        prev_save = prev_rule->save();\n        std::tie(r, ry) = find_next_rule(eqr.first, eqr.second, r, ry);\n    }\n    return {prev_rule, prev_year};\n}\n\nstatic\nsys_info\nfind_rule(const std::pair<const Rule*, date::year>& first_rule,\n          const std::pair<const Rule*, date::year>& last_rule,\n          const date::year& y, const std::chrono::seconds& offset,\n          const MonthDayTime& mdt, const std::chrono::minutes& initial_save,\n          const std::string& initial_abbrev)\n{\n    using namespace std::chrono;\n    using namespace date;\n    auto r = first_rule.first;\n    auto ry = first_rule.second;\n    sys_info x{sys_days(year::min()\/min_day), sys_days(year::max()\/max_day),\n               seconds{0}, initial_save, initial_abbrev};\n    while (r != nullptr)\n    {\n        auto tr = r->mdt().to_sys(ry, offset, x.save);\n        auto tx = mdt.to_sys(y, offset, x.save);\n        \/\/ Find last rule where tx >= tr\n        if (tx <= tr || (r == last_rule.first && ry == last_rule.second))\n        {\n            if (tx < tr && r == first_rule.first && ry == first_rule.second)\n            {\n                x.end = r->mdt().to_sys(ry, offset, x.save);\n                break;\n            }\n            if (tx < tr)\n            {\n                std::tie(r, ry) = find_previous_rule(r, ry);  \/\/ can't return nullptr for r\n                assert(r != nullptr);\n            }\n            \/\/ r != nullptr && tx >= tr (if tr were to be recomputed)\n            auto prev_save = initial_save;\n            if (!(r == first_rule.first && ry == first_rule.second))\n                prev_save = find_previous_rule(r, ry).first->save();\n            x.begin = r->mdt().to_sys(ry, offset, prev_save);\n            x.save = r->save();\n            x.abbrev = r->abbrev();\n            if (!(r == last_rule.first && ry == last_rule.second))\n            {\n                std::tie(r, ry) = find_next_rule(r, ry);  \/\/ can't return nullptr for r\n                assert(r != nullptr);\n                x.end = r->mdt().to_sys(ry, offset, x.save);\n            }\n            else\n                x.end = sys_days(year::max()\/max_day);\n            break;\n        }\n        x.save = r->save();\n        std::tie(r, ry) = find_next_rule(r, ry);  \/\/ Can't return nullptr for r\n        assert(r != nullptr);\n    }\n    return x;\n}\n\n\/\/ zonelet\n\ndetail::zonelet::~zonelet()\n{\n#if !defined(_MSC_VER) || (_MSC_VER >= 1900)\n    using minutes = std::chrono::minutes;\n    using string = std::string;\n    if (tag_ == has_save)\n        u.save_.~minutes();\n    else\n        u.rule_.~string();\n#endif\n}\n\ndetail::zonelet::zonelet()\n{\n#if !defined(_MSC_VER) || (_MSC_VER >= 1900)\n    ::new(&u.rule_) std::string();\n#endif\n}\n\ndetail::zonelet::zonelet(const zonelet& i)\n    : gmtoff_(i.gmtoff_)\n    , tag_(i.tag_)\n    , format_(i.format_)\n    , until_year_(i.until_year_)\n    , until_date_(i.until_date_)\n    , until_utc_(i.until_utc_)\n    , until_std_(i.until_std_)\n    , until_loc_(i.until_loc_)\n    , initial_save_(i.initial_save_)\n    , initial_abbrev_(i.initial_abbrev_)\n    , first_rule_(i.first_rule_)\n    , last_rule_(i.last_rule_)\n{\n#if !defined(_MSC_VER) || (_MSC_VER >= 1900)\n    if (tag_ == has_save)\n        ::new(&u.save_) std::chrono::minutes(i.u.save_);\n    else\n        ::new(&u.rule_) std::string(i.u.rule_);\n#else\n    if (tag_ == has_save)\n        u.save_ = i.u.save_;\n    else\n        u.rule_ = i.u.rule_;\n#endif\n}\n\n#endif  \/\/ !USE_OS_TZDB\n\n\/\/ time_zone\n\n#if USE_OS_TZDB\n\ntime_zone::time_zone(const std::string& s, detail::undocumented)\n    : name_(s)\n    , adjusted_(new std::once_flag{})\n{\n}\n\nenum class endian\n{\n    native = __BYTE_ORDER__,\n    little = __ORDER_LITTLE_ENDIAN__,\n    big    = __ORDER_BIG_ENDIAN__\n};\n\nstatic\ninline\nstd::uint32_t\nreverse_bytes(std::uint32_t i)\n{\n    return\n        (i & 0xff000000u) >> 24 |\n        (i & 0x00ff0000u) >> 8 |\n        (i & 0x0000ff00u) << 8 |\n        (i & 0x000000ffu) << 24;\n}\n\nstatic\ninline\nstd::uint64_t\nreverse_bytes(std::uint64_t i)\n{\n    return\n        (i & 0xff00000000000000ull) >> 56 |\n        (i & 0x00ff000000000000ull) >> 40 |\n        (i & 0x0000ff0000000000ull) >> 24 |\n        (i & 0x000000ff00000000ull) >> 8 |\n        (i & 0x00000000ff000000ull) << 8 |\n        (i & 0x0000000000ff0000ull) << 24 |\n        (i & 0x000000000000ff00ull) << 40 |\n        (i & 0x00000000000000ffull) << 56;\n}\n\ntemplate <class T>\nstatic\ninline\nvoid\nmaybe_reverse_bytes(T&, std::false_type)\n{\n}\n\nstatic\ninline\nvoid\nmaybe_reverse_bytes(std::int32_t& t, std::true_type)\n{\n    t = static_cast<std::int32_t>(reverse_bytes(static_cast<std::uint32_t>(t)));\n}\n\nstatic\ninline\nvoid\nmaybe_reverse_bytes(std::int64_t& t, std::true_type)\n{\n    t = static_cast<std::int64_t>(reverse_bytes(static_cast<std::uint64_t>(t)));\n}\n\ntemplate <class T>\nstatic\ninline\nvoid\nmaybe_reverse_bytes(T& t)\n{\n    maybe_reverse_bytes(t, std::integral_constant<bool,\n                                                  endian::native == endian::little>{});\n}\n\nstatic\nvoid\nload_header(std::istream& inf)\n{\n    \/\/ Read TZif\n    auto t = inf.get();\n    auto z = inf.get();\n    auto i = inf.get();\n    auto f = inf.get();\n#ifndef NDEBUG\n    assert(t == 'T');\n    assert(z == 'Z');\n    assert(i == 'i');\n    assert(f == 'f');\n#else\n    (void)t;\n    (void)z;\n    (void)i;\n    (void)f;\n#endif\n}\n\nstatic\nunsigned char\nload_version(std::istream& inf)\n{\n    \/\/ Read version\n    auto v = inf.get();\n    assert(v != EOF);\n    return static_cast<unsigned char>(v);\n}\n\nstatic\nvoid\nskip_reserve(std::istream& inf)\n{\n    inf.ignore(15);\n}\n\nstatic\nvoid\nload_counts(std::istream& inf,\n            std::int32_t& tzh_ttisgmtcnt, std::int32_t& tzh_ttisstdcnt,\n            std::int32_t& tzh_leapcnt,    std::int32_t& tzh_timecnt,\n            std::int32_t& tzh_typecnt,    std::int32_t& tzh_charcnt)\n{\n    \/\/ Read counts;\n    inf.read(reinterpret_cast<char*>(&tzh_ttisgmtcnt), 4);\n    maybe_reverse_bytes(tzh_ttisgmtcnt);\n    inf.read(reinterpret_cast<char*>(&tzh_ttisstdcnt), 4);\n    maybe_reverse_bytes(tzh_ttisstdcnt);\n    inf.read(reinterpret_cast<char*>(&tzh_leapcnt), 4);\n    maybe_reverse_bytes(tzh_leapcnt);\n    inf.read(reinterpret_cast<char*>(&tzh_timecnt), 4);\n    maybe_reverse_bytes(tzh_timecnt);\n    inf.read(reinterpret_cast<char*>(&tzh_typecnt), 4);\n    maybe_reverse_bytes(tzh_typecnt);\n    inf.read(reinterpret_cast<char*>(&tzh_charcnt), 4);\n    maybe_reverse_bytes(tzh_charcnt);\n}\n\ntemplate <class TimeType>\nstatic\nstd::vector<detail::transition>\nload_transitions(std::istream& inf, std::int32_t tzh_timecnt)\n{\n    \/\/ Read transitions\n    using namespace std::chrono;\n    std::vector<detail::transition> transitions;\n    transitions.reserve(static_cast<unsigned>(tzh_timecnt));\n    for (std::int32_t i = 0; i < tzh_timecnt; ++i)\n    {\n        TimeType t;\n        inf.read(reinterpret_cast<char*>(&t), sizeof(t));\n        maybe_reverse_bytes(t);\n        transitions.emplace_back(sys_seconds{seconds{t}});\n        if (transitions.back().timepoint < min_seconds)\n            transitions.back().timepoint = min_seconds;\n    }\n    return transitions;\n}\n\nstatic\nstd::vector<std::uint8_t>\nload_indices(std::istream& inf, std::int32_t tzh_timecnt)\n{\n    \/\/ Read indices\n    std::vector<std::uint8_t> indices;\n    indices.reserve(static_cast<unsigned>(tzh_timecnt));\n    for (std::int32_t i = 0; i < tzh_timecnt; ++i)\n    {\n        std::uint8_t t;\n        inf.read(reinterpret_cast<char*>(&t), sizeof(t));\n        indices.emplace_back(t);\n    }\n    return indices;\n}\n\nstatic\nstd::vector<ttinfo>\nload_ttinfo(std::istream& inf, std::int32_t tzh_typecnt)\n{\n    \/\/ Read ttinfo\n    std::vector<ttinfo> ttinfos;\n    ttinfos.reserve(static_cast<unsigned>(tzh_typecnt));\n    for (std::int32_t i = 0; i < tzh_typecnt; ++i)\n    {\n        ttinfo t;\n        inf.read(reinterpret_cast<char*>(&t), 6);\n        maybe_reverse_bytes(t.tt_gmtoff);\n        ttinfos.emplace_back(t);\n    }\n    return ttinfos;\n}\n\nstatic\nstd::string\nload_abbreviations(std::istream& inf, std::int32_t tzh_charcnt)\n{\n    \/\/ Read abbreviations\n    std::string abbrev;\n    abbrev.resize(static_cast<unsigned>(tzh_charcnt), '\\0');\n    inf.read(&abbrev[0], tzh_charcnt);\n    return abbrev;\n}\n\n#if !MISSING_LEAP_SECONDS\n\ntemplate <class TimeType>\nstatic\nstd::vector<leap>\nload_leaps(std::istream& inf, std::int32_t tzh_leapcnt)\n{\n    \/\/ Read tzh_leapcnt pairs\n    using namespace std::chrono;\n    std::vector<leap> leap_seconds;\n    leap_seconds.reserve(static_cast<std::size_t>(tzh_leapcnt));\n    for (std::int32_t i = 0; i < tzh_leapcnt; ++i)\n    {\n        TimeType     t0;\n        std::int32_t t1;\n        inf.read(reinterpret_cast<char*>(&t0), sizeof(t0));\n        inf.read(reinterpret_cast<char*>(&t1), sizeof(t1));\n        maybe_reverse_bytes(t0);\n        maybe_reverse_bytes(t1);\n        leap_seconds.emplace_back(sys_seconds{seconds{t0 - (t1-1)}},\n                                  detail::undocumented{});\n    }\n    return leap_seconds;\n}\n\ntemplate <class TimeType>\nstatic\nstd::vector<leap>\nload_leap_data(std::istream& inf,\n               std::int32_t tzh_leapcnt, std::int32_t tzh_timecnt,\n               std::int32_t tzh_typecnt, std::int32_t tzh_charcnt)\n{\n    inf.ignore(tzh_timecnt*static_cast<std::int32_t>(sizeof(TimeType)) + tzh_timecnt +\n               tzh_typecnt*6 + tzh_charcnt);\n    return load_leaps<TimeType>(inf, tzh_leapcnt);\n}\n\nstatic\nstd::vector<leap>\nload_just_leaps(std::istream& inf)\n{\n    \/\/ Read tzh_leapcnt pairs\n    using namespace std::chrono;\n    load_header(inf);\n    auto v = load_version(inf);\n    std::int32_t tzh_ttisgmtcnt, tzh_ttisstdcnt, tzh_leapcnt,\n                 tzh_timecnt,    tzh_typecnt,    tzh_charcnt;\n    skip_reserve(inf);\n    load_counts(inf, tzh_ttisgmtcnt, tzh_ttisstdcnt, tzh_leapcnt,\n                     tzh_timecnt,    tzh_typecnt,    tzh_charcnt);\n    if (v == 0)\n        return load_leap_data<int32_t>(inf, tzh_leapcnt, tzh_timecnt, tzh_typecnt,\n                                       tzh_charcnt);\n#if !defined(NDEBUG)\n    inf.ignore((4+1)*tzh_timecnt + 6*tzh_typecnt + tzh_charcnt + 8*tzh_leapcnt +\n               tzh_ttisstdcnt + tzh_ttisgmtcnt);\n    load_header(inf);\n    auto v2 = load_version(inf);\n    assert(v == v2);\n    skip_reserve(inf);\n#else  \/\/ defined(NDEBUG)\n    inf.ignore((4+1)*tzh_timecnt + 6*tzh_typecnt + tzh_charcnt + 8*tzh_leapcnt +\n               tzh_ttisstdcnt + tzh_ttisgmtcnt + (4+1+15));\n#endif  \/\/ defined(NDEBUG)\n    load_counts(inf, tzh_ttisgmtcnt, tzh_ttisstdcnt, tzh_leapcnt,\n                     tzh_timecnt,    tzh_typecnt,    tzh_charcnt);\n    return load_leap_data<int64_t>(inf, tzh_leapcnt, tzh_timecnt, tzh_typecnt,\n                                   tzh_charcnt);\n}\n\n#endif  \/\/ !MISSING_LEAP_SECONDS\n\ntemplate <class TimeType>\nvoid\ntime_zone::load_data(std::istream& inf,\n                     std::int32_t tzh_leapcnt, std::int32_t tzh_timecnt,\n                     std::int32_t tzh_typecnt, std::int32_t tzh_charcnt)\n{\n    using namespace std::chrono;\n    transitions_ = load_transitions<TimeType>(inf, tzh_timecnt);\n    auto indices = load_indices(inf, tzh_timecnt);\n    auto infos = load_ttinfo(inf, tzh_typecnt);\n    auto abbrev = load_abbreviations(inf, tzh_charcnt);\n#if !MISSING_LEAP_SECONDS\n    auto& leap_seconds = get_tzdb_list().front().leaps;\n    if (leap_seconds.empty() && tzh_leapcnt > 0)\n        leap_seconds = load_leaps<TimeType>(inf, tzh_leapcnt);\n#endif\n    ttinfos_.reserve(infos.size());\n    for (auto& info : infos)\n    {\n        ttinfos_.push_back({seconds{info.tt_gmtoff},\n                            abbrev.c_str() + info.tt_abbrind,\n                            info.tt_isdst != 0});\n    }\n    auto i = 0u;\n    if (transitions_.empty() || transitions_.front().timepoint != min_seconds)\n    {\n        transitions_.emplace(transitions_.begin(), min_seconds);\n        auto tf = std::find_if(ttinfos_.begin(), ttinfos_.end(),\n                               [](const expanded_ttinfo& ti)\n                                   {return ti.is_dst == 0;});\n        if (tf == ttinfos_.end())\n            tf = ttinfos_.begin();\n        transitions_[i].info = &*tf;\n        ++i;\n    }\n    for (auto j = 0u; i < transitions_.size(); ++i, ++j)\n        transitions_[i].info = ttinfos_.data() + indices[j];\n}\n\nvoid\ntime_zone::init_impl()\n{\n    using namespace std;\n    using namespace std::chrono;\n    auto name = get_tz_dir() + ('\/' + name_);\n    std::ifstream inf(name);\n    if (!inf.is_open())\n        throw std::runtime_error{\"Unable to open \" + name};\n    inf.exceptions(std::ios::failbit | std::ios::badbit);\n    load_header(inf);\n    auto v = load_version(inf);\n    std::int32_t tzh_ttisgmtcnt, tzh_ttisstdcnt, tzh_leapcnt,\n                 tzh_timecnt,    tzh_typecnt,    tzh_charcnt;\n    skip_reserve(inf);\n    load_counts(inf, tzh_ttisgmtcnt, tzh_ttisstdcnt, tzh_leapcnt,\n                     tzh_timecnt,    tzh_typecnt,    tzh_charcnt);\n    if (v == 0)\n    {\n        load_data<int32_t>(inf, tzh_leapcnt, tzh_timecnt, tzh_typecnt, tzh_charcnt);\n    }\n    else\n    {\n#if !defined(NDEBUG)\n        inf.ignore((4+1)*tzh_timecnt + 6*tzh_typecnt + tzh_charcnt + 8*tzh_leapcnt +\n                   tzh_ttisstdcnt + tzh_ttisgmtcnt);\n        load_header(inf);\n        auto v2 = load_version(inf);\n        assert(v == v2);\n        skip_reserve(inf);\n#else  \/\/ defined(NDEBUG)\n        inf.ignore((4+1)*tzh_timecnt + 6*tzh_typecnt + tzh_charcnt + 8*tzh_leapcnt +\n                   tzh_ttisstdcnt + tzh_ttisgmtcnt + (4+1+15));\n#endif  \/\/ defined(NDEBUG)\n        load_counts(inf, tzh_ttisgmtcnt, tzh_ttisstdcnt, tzh_leapcnt,\n                         tzh_timecnt,    tzh_typecnt,    tzh_charcnt);\n        load_data<int64_t>(inf, tzh_leapcnt, tzh_timecnt, tzh_typecnt, tzh_charcnt);\n    }\n#if !MISSING_LEAP_SECONDS\n    if (tzh_leapcnt > 0)\n    {\n        auto& leap_seconds = get_tzdb_list().front().leaps;\n        auto itr = leap_seconds.begin();\n        auto l = itr->date();\n        seconds leap_count{0};\n        for (auto t = std::upper_bound(transitions_.begin(), transitions_.end(), l,\n                                       [](const sys_seconds& x, const transition& ct)\n                                       {\n                                           return x < ct.timepoint;\n                                       });\n                  t != transitions_.end(); ++t)\n        {\n            while (t->timepoint >= l)\n            {\n                ++leap_count;\n                if (++itr == leap_seconds.end())\n                    l = sys_days(max_year\/max_day);\n                else\n                    l = itr->date() + leap_count;\n            }\n            t->timepoint -= leap_count;\n        }\n    }\n#endif  \/\/ !MISSING_LEAP_SECONDS\n    auto b = transitions_.begin();\n    auto i = transitions_.end();\n    if (i != b)\n    {\n        for (--i; i != b; --i)\n        {\n            if (i->info->offset == i[-1].info->offset &&\n                i->info->abbrev == i[-1].info->abbrev &&\n                i->info->is_dst == i[-1].info->is_dst)\n                i = transitions_.erase(i);\n        }\n    }\n}\n\nvoid\ntime_zone::init() const\n{\n    std::call_once(*adjusted_, [this]() {const_cast<time_zone*>(this)->init_impl();});\n}\n\nsys_info\ntime_zone::load_sys_info(std::vector<detail::transition>::const_iterator i) const\n{\n    using namespace std::chrono;\n    assert(!transitions_.empty());\n    assert(i != transitions_.begin());\n    sys_info r;\n    r.begin = i[-1].timepoint;\n    r.end = i != transitions_.end() ? i->timepoint :\n                                      sys_seconds(sys_days(year::max()\/max_day));\n    r.offset = i[-1].info->offset;\n    r.save = i[-1].info->is_dst ? minutes{1} : minutes{0};\n    r.abbrev = i[-1].info->abbrev;\n    return r;\n}\n\nsys_info\ntime_zone::get_info_impl(sys_seconds tp) const\n{\n    using namespace std;\n    init();\n    return load_sys_info(upper_bound(transitions_.begin(), transitions_.end(), tp,\n                                     [](const sys_seconds& x, const transition& t)\n                                     {\n                                         return x < t.timepoint;\n                                     }));\n}\n\nlocal_info\ntime_zone::get_info_impl(local_seconds tp) const\n{\n    using namespace std::chrono;\n    init();\n    local_info i;\n    i.result = local_info::unique;\n    auto tr = upper_bound(transitions_.begin(), transitions_.end(), tp,\n                          [](const local_seconds& x, const transition& t)\n                          {\n                              return sys_seconds{x.time_since_epoch()} -\n                                                         t.info->offset < t.timepoint;\n                          });\n    i.first = load_sys_info(tr);\n    auto tps = sys_seconds{(tp - i.first.offset).time_since_epoch()};\n    if (tps < i.first.begin + days{1} && tr != transitions_.begin())\n    {\n        i.second = load_sys_info(--tr);\n        tps = sys_seconds{(tp - i.second.offset).time_since_epoch()};\n        if (tps < i.second.end)\n        {\n           i.result = local_info::ambiguous;\n           std::swap(i.first, i.second);\n        }\n        else\n        {\n            i.second = {};\n        }\n    }\n    else if (tps >= i.first.end && tr != transitions_.end())\n    {\n        i.second = load_sys_info(++tr);\n        tps = sys_seconds{(tp - i.second.offset).time_since_epoch()};\n        if (tps < i.second.begin)\n            i.result = local_info::nonexistent;\n        else\n            i.second = {};\n    }\n    return i;\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const time_zone& z)\n{\n    using namespace std::chrono;\n    z.init();\n    os << z.name_ << '\\n';\n    os << \"Initially:           \";\n    auto const& t = z.transitions_.front();\n    if (t.info->offset >= seconds{0})\n        os << '+';\n    os << make_time(t.info->offset);\n    if (t.info->is_dst > 0)\n        os << \" daylight \";\n    else\n        os << \" standard \";\n    os << t.info->abbrev << '\\n';\n    for (auto i = std::next(z.transitions_.cbegin()); i < z.transitions_.cend(); ++i)\n        os << *i << '\\n';\n    return os;\n}\n\n#if !MISSING_LEAP_SECONDS\n\nleap::leap(const sys_seconds& s, detail::undocumented)\n    : date_(s)\n{\n}\n\n#endif  \/\/ !MISSING_LEAP_SECONDS\n\n#else  \/\/ !USE_OS_TZDB\n\ntime_zone::time_zone(const std::string& s, detail::undocumented)\n    : adjusted_(new std::once_flag{})\n{\n    try\n    {\n        using namespace date;\n        std::istringstream in(s);\n        in.exceptions(std::ios::failbit | std::ios::badbit);\n        std::string word;\n        in >> word >> name_;\n        parse_info(in);\n    }\n    catch (...)\n    {\n        std::cerr << s << '\\n';\n        std::cerr << *this << '\\n';\n        zonelets_.pop_back();\n        throw;\n    }\n}\n\nsys_info\ntime_zone::get_info_impl(sys_seconds tp) const\n{\n    return get_info_impl(tp, static_cast<int>(tz::utc));\n}\n\nlocal_info\ntime_zone::get_info_impl(local_seconds tp) const\n{\n    using namespace std::chrono;\n    local_info i{};\n    i.first = get_info_impl(sys_seconds{tp.time_since_epoch()}, static_cast<int>(tz::local));\n    auto tps = sys_seconds{(tp - i.first.offset).time_since_epoch()};\n    if (tps < i.first.begin)\n    {\n        i.second = std::move(i.first);\n        i.first = get_info_impl(i.second.begin - seconds{1}, static_cast<int>(tz::utc));\n        i.result = local_info::nonexistent;\n    }\n    else if (i.first.end - tps <= days{1})\n    {\n        i.second = get_info_impl(i.first.end, static_cast<int>(tz::utc));\n        tps = sys_seconds{(tp - i.second.offset).time_since_epoch()};\n        if (tps >= i.second.begin)\n            i.result = local_info::ambiguous;\n        else\n            i.second = {};\n    }\n    return i;\n}\n\nvoid\ntime_zone::add(const std::string& s)\n{\n    try\n    {\n        std::istringstream in(s);\n        in.exceptions(std::ios::failbit | std::ios::badbit);\n        ws(in);\n        if (!in.eof() && in.peek() != '#')\n            parse_info(in);\n    }\n    catch (...)\n    {\n        std::cerr << s << '\\n';\n        std::cerr << *this << '\\n';\n        zonelets_.pop_back();\n        throw;\n    }\n}\n\nvoid\ntime_zone::parse_info(std::istream& in)\n{\n    using namespace date;\n    using namespace std::chrono;\n    zonelets_.emplace_back();\n    auto& zonelet = zonelets_.back();\n    zonelet.gmtoff_ = parse_signed_time(in);\n    in >> zonelet.u.rule_;\n    if (zonelet.u.rule_ == \"-\")\n        zonelet.u.rule_.clear();\n    in >> zonelet.format_;\n    if (!in.eof())\n        ws(in);\n    if (in.eof() || in.peek() == '#')\n    {\n        zonelet.until_year_ = year::max();\n        zonelet.until_date_ = MonthDayTime(max_day, tz::utc);\n    }\n    else\n    {\n        int y;\n        in >> y;\n        zonelet.until_year_ = year{y};\n        in >> zonelet.until_date_;\n        zonelet.until_date_.canonicalize(zonelet.until_year_);\n    }\n    if ((zonelet.until_year_ < min_year) ||\n            (zonelets_.size() > 1 && zonelets_.end()[-2].until_year_ > max_year))\n        zonelets_.pop_back();\n}\n\nvoid\ntime_zone::adjust_infos(const std::vector<Rule>& rules)\n{\n    using namespace std::chrono;\n    using namespace date;\n    const zonelet* prev_zonelet = nullptr;\n    for (auto& z : zonelets_)\n    {\n        std::pair<const Rule*, const Rule*> eqr{};\n        std::istringstream in;\n        in.exceptions(std::ios::failbit | std::ios::badbit);\n        \/\/ Classify info as rule-based, has save, or neither\n        if (!z.u.rule_.empty())\n        {\n            \/\/ Find out if this zonelet has a rule or a save\n            eqr = std::equal_range(rules.data(), rules.data() + rules.size(), z.u.rule_);\n            if (eqr.first == eqr.second)\n            {\n                \/\/ The rule doesn't exist.  Assume this is a save\n                try\n                {\n                    using namespace std::chrono;\n                    using string = std::string;\n                    in.str(z.u.rule_);\n                    auto tmp = duration_cast<minutes>(parse_signed_time(in));\n#if !defined(_MSC_VER) || (_MSC_VER >= 1900)\n                    z.u.rule_.~string();\n                    z.tag_ = zonelet::has_save;\n                    ::new(&z.u.save_) minutes(tmp);\n#else\n                    z.u.rule_.clear();\n                    z.tag_ = zonelet::has_save;\n                    z.u.save_ = tmp;\n#endif\n                }\n                catch (...)\n                {\n                    std::cerr << name_ << \" : \" << z.u.rule_ << '\\n';\n                    throw;\n                }\n            }\n        }\n        else\n        {\n            \/\/ This zone::zonelet has no rule and no save\n            z.tag_ = zonelet::is_empty;\n        }\n\n        minutes final_save{0};\n        if (z.tag_ == zonelet::has_save)\n        {\n            final_save = z.u.save_;\n        }\n        else if (z.tag_ == zonelet::has_rule)\n        {\n            z.last_rule_ = find_rule_for_zone(eqr, z.until_year_, z.gmtoff_,\n                                              z.until_date_);\n            if (z.last_rule_.first != nullptr)\n                final_save = z.last_rule_.first->save();\n        }\n        z.until_utc_ = z.until_date_.to_sys(z.until_year_, z.gmtoff_, final_save);\n        z.until_std_ = local_seconds{z.until_utc_.time_since_epoch()} + z.gmtoff_;\n        z.until_loc_ = z.until_std_ + final_save;\n\n        if (z.tag_ == zonelet::has_rule)\n        {\n            if (prev_zonelet != nullptr)\n            {\n                z.first_rule_ = find_rule_for_zone(eqr, prev_zonelet->until_utc_,\n                                                        prev_zonelet->until_std_,\n                                                        prev_zonelet->until_loc_);\n                if (z.first_rule_.first != nullptr)\n                {\n                    z.initial_save_ = z.first_rule_.first->save();\n                    z.initial_abbrev_ = z.first_rule_.first->abbrev();\n                    if (z.first_rule_ != z.last_rule_)\n                    {\n                        z.first_rule_ = find_next_rule(eqr.first, eqr.second,\n                                                       z.first_rule_.first,\n                                                       z.first_rule_.second);\n                    }\n                    else\n                    {\n                        z.first_rule_ = std::make_pair(nullptr, year::min());\n                        z.last_rule_ = std::make_pair(nullptr, year::max());\n                    }\n                }\n            }\n            if (z.first_rule_.first == nullptr && z.last_rule_.first != nullptr)\n            {\n                z.first_rule_ = std::make_pair(eqr.first, eqr.first->starting_year());\n                z.initial_abbrev_ = find_first_std_rule(eqr)->abbrev();\n            }\n        }\n\n#ifndef NDEBUG\n        if (z.first_rule_.first == nullptr)\n        {\n            assert(z.first_rule_.second == year::min());\n            assert(z.last_rule_.first == nullptr);\n            assert(z.last_rule_.second == year::max());\n        }\n        else\n        {\n            assert(z.last_rule_.first != nullptr);\n        }\n#endif\n        prev_zonelet = &z;\n    }\n}\n\nstatic\nstd::string\nformat_abbrev(std::string format, const std::string& variable, std::chrono::seconds off,\n                                                               std::chrono::minutes save)\n{\n    using namespace std::chrono;\n    auto k = format.find(\"%s\");\n    if (k != std::string::npos)\n    {\n        format.replace(k, 2, variable);\n    }\n    else\n    {\n        k = format.find('\/');\n        if (k != std::string::npos)\n        {\n            if (save == minutes{0})\n                format.erase(k);\n            else\n                format.erase(0, k+1);\n        }\n        else\n        {\n            k = format.find(\"%z\");\n            if (k != std::string::npos)\n            {\n                std::string temp;\n                if (off < seconds{0})\n                {\n                    temp = '-';\n                    off = -off;\n                }\n                else\n                    temp = '+';\n                auto h = date::floor<hours>(off);\n                off -= h;\n                if (h < hours{10})\n                    temp += '0';\n                temp += std::to_string(h.count());\n                if (off > seconds{0})\n                {\n                    auto m = date::floor<minutes>(off);\n                    off -= m;\n                    if (m < minutes{10})\n                        temp += '0';\n                    temp += std::to_string(m.count());\n                    if (off > seconds{0})\n                    {\n                        if (off < seconds{10})\n                            temp += '0';\n                        temp += std::to_string(off.count());\n                    }\n                }\n                format.replace(k, 2, temp);\n            }\n        }\n    }\n    return format;\n}\n\nsys_info\ntime_zone::get_info_impl(sys_seconds tp, int tz_int) const\n{\n    using namespace std::chrono;\n    using namespace date;\n    tz timezone = static_cast<tz>(tz_int);\n    assert(timezone != tz::standard);\n    auto y = year_month_day(floor<days>(tp)).year();\n    if (y < min_year || y > max_year)\n        throw std::runtime_error(\"The year \" + std::to_string(static_cast<int>(y)) +\n            \" is out of range:[\" + std::to_string(static_cast<int>(min_year)) + \", \"\n                                 + std::to_string(static_cast<int>(max_year)) + \"]\");\n    std::call_once(*adjusted_,\n                   [this]()\n                   {\n                       const_cast<time_zone*>(this)->adjust_infos(get_tzdb().rules);\n                   });\n    auto i = std::upper_bound(zonelets_.begin(), zonelets_.end(), tp,\n        [timezone](sys_seconds t, const zonelet& zl)\n        {\n            return timezone == tz::utc ? t < zl.until_utc_ :\n                                         t < sys_seconds{zl.until_loc_.time_since_epoch()};\n        });\n\n    sys_info r{};\n    if (i != zonelets_.end())\n    {\n        if (i->tag_ == zonelet::has_save)\n        {\n            if (i != zonelets_.begin())\n                r.begin = i[-1].until_utc_;\n            else\n                r.begin = sys_days(year::min()\/min_day);\n            r.end = i->until_utc_;\n            r.offset = i->gmtoff_ + i->u.save_;\n            r.save = i->u.save_;\n        }\n        else if (i->u.rule_.empty())\n        {\n            if (i != zonelets_.begin())\n                r.begin = i[-1].until_utc_;\n            else\n                r.begin = sys_days(year::min()\/min_day);\n            r.end = i->until_utc_;\n            r.offset = i->gmtoff_;\n        }\n        else\n        {\n            r = find_rule(i->first_rule_, i->last_rule_, y, i->gmtoff_,\n                          MonthDayTime(local_seconds{tp.time_since_epoch()}, timezone),\n                          i->initial_save_, i->initial_abbrev_);\n            r.offset = i->gmtoff_ + r.save;\n            if (i != zonelets_.begin() && r.begin < i[-1].until_utc_)\n                r.begin = i[-1].until_utc_;\n            if (r.end > i->until_utc_)\n                r.end = i->until_utc_;\n        }\n        r.abbrev = format_abbrev(i->format_, r.abbrev, r.offset, r.save);\n        assert(r.begin < r.end);\n    }\n    return r;\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const time_zone& z)\n{\n    using namespace date;\n    using namespace std::chrono;\n    detail::save_ostream<char> _(os);\n    os.fill(' ');\n    os.flags(std::ios::dec | std::ios::left);\n    std::call_once(*z.adjusted_,\n                   [&z]()\n                   {\n                       const_cast<time_zone&>(z).adjust_infos(get_tzdb().rules);\n                   });\n    os.width(35);\n    os << z.name_;\n    std::string indent;\n    for (auto const& s : z.zonelets_)\n    {\n        os << indent;\n        if (s.gmtoff_ >= seconds{0})\n            os << ' ';\n        os << make_time(s.gmtoff_) << \"   \";\n        os.width(15);\n        if (s.tag_ != zonelet::has_save)\n            os << s.u.rule_;\n        else\n        {\n            std::ostringstream tmp;\n            tmp << make_time(s.u.save_);\n            os <<  tmp.str();\n        }\n        os.width(8);\n        os << s.format_ << \"   \";\n        os << s.until_year_ << ' ' << s.until_date_;\n        os << \"   \" << s.until_utc_ << \" UTC\";\n        os << \"   \" << s.until_std_ << \" STD\";\n        os << \"   \" << s.until_loc_;\n        os << \"   \" << make_time(s.initial_save_);\n        os << \"   \" << s.initial_abbrev_;\n        if (s.first_rule_.first != nullptr)\n            os << \"   {\" << *s.first_rule_.first << \", \" << s.first_rule_.second << '}';\n        else\n            os << \"   {\" << \"nullptr\" << \", \" << s.first_rule_.second << '}';\n        if (s.last_rule_.first != nullptr)\n            os << \"   {\" << *s.last_rule_.first << \", \" << s.last_rule_.second << '}';\n        else\n            os << \"   {\" << \"nullptr\" << \", \" << s.last_rule_.second << '}';\n        os << '\\n';\n        if (indent.empty())\n            indent = std::string(35, ' ');\n    }\n    return os;\n}\n\n#endif  \/\/ !USE_OS_TZDB\n\n#if !MISSING_LEAP_SECONDS\n\nstd::ostream&\noperator<<(std::ostream& os, const leap& x)\n{\n    using namespace date;\n    return os << x.date_ << \"  +\";\n}\n\n#endif  \/\/ !MISSING_LEAP_SECONDS\n\n#if USE_OS_TZDB\n\n# ifdef __APPLE__\nstatic\nstd::string\nget_version()\n{\n    using namespace std;\n    auto path = get_tz_dir() + string(\"\/+VERSION\");\n    ifstream in{path};\n    string version;\n    in >> version;\n    if (in.fail())\n        throw std::runtime_error(\"Unable to get Timezone database version from \" + path);\n    return version;\n}\n# endif\n\nstatic\nstd::unique_ptr<tzdb>\ninit_tzdb()\n{\n    std::unique_ptr<tzdb> db(new tzdb);\n\n    \/\/Iterate through folders\n    std::queue<std::string> subfolders;\n    subfolders.emplace(get_tz_dir());\n    struct dirent* d;\n    struct stat s;\n    while (!subfolders.empty())\n    {\n        auto dirname = std::move(subfolders.front());\n        subfolders.pop();\n        auto dir = opendir(dirname.c_str());\n        if (!dir)\n            continue;\n        while ((d = readdir(dir)) != nullptr)\n        {\n            \/\/ Ignore these files:\n            if (d->d_name[0]                      == '.'    || \/\/ curdir, prevdir, hidden\n                memcmp(d->d_name, \"posix\", 5)     == 0      || \/\/ starts with posix\n                strcmp(d->d_name, \"Factory\")      == 0      ||\n                strcmp(d->d_name, \"iso3166.tab\")  == 0      ||\n                strcmp(d->d_name, \"right\")        == 0      ||\n                strcmp(d->d_name, \"+VERSION\")     == 0      ||\n                strcmp(d->d_name, \"zone.tab\")     == 0      ||\n                strcmp(d->d_name, \"zone1970.tab\") == 0      ||\n                strcmp(d->d_name, \"tzdata.zi\")    == 0      ||\n                strcmp(d->d_name, \"leapseconds\")  == 0      ||\n                strcmp(d->d_name, \"leap-seconds.list\") == 0   )\n                continue;\n            auto subname = dirname + folder_delimiter + d->d_name;\n            if(stat(subname.c_str(), &s) == 0)\n            {\n                if(S_ISDIR(s.st_mode))\n                {\n                    if(!S_ISLNK(s.st_mode))\n                    {\n                        subfolders.push(subname);\n                    }\n                }\n                else\n                {\n                    db->zones.emplace_back(subname.substr(get_tz_dir().size()+1),\n                                           detail::undocumented{});\n                }\n            }\n        }\n        closedir(dir);\n    }\n    db->zones.shrink_to_fit();\n    std::sort(db->zones.begin(), db->zones.end());\n#  if !MISSING_LEAP_SECONDS\n    std::ifstream in(get_tz_dir() + std::string(1, folder_delimiter) + \"right\/UTC\",\n                     std::ios_base::binary);\n    if (in)\n    {\n        in.exceptions(std::ios::failbit | std::ios::badbit);\n        db->leaps = load_just_leaps(in);\n    }\n    else\n    {\n        in.clear();\n        in.open(get_tz_dir() + std::string(1, folder_delimiter) +\n                \"UTC\", std::ios_base::binary);\n        if (!in)\n            throw std::runtime_error(\"Unable to extract leap second information\");\n        in.exceptions(std::ios::failbit | std::ios::badbit);\n        db->leaps = load_just_leaps(in);\n    }\n#  endif  \/\/ !MISSING_LEAP_SECONDS\n#  ifdef __APPLE__\n    db->version = get_version();\n#  endif\n    return db;\n}\n\n#else  \/\/ !USE_OS_TZDB\n\n\/\/ link\n\nlink::link(const std::string& s)\n{\n    using namespace date;\n    std::istringstream in(s);\n    in.exceptions(std::ios::failbit | std::ios::badbit);\n    std::string word;\n    in >> word >> target_ >> name_;\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const link& x)\n{\n    using namespace date;\n    detail::save_ostream<char> _(os);\n    os.fill(' ');\n    os.flags(std::ios::dec | std::ios::left);\n    os.width(35);\n    return os << x.name_ << \" --> \" << x.target_;\n}\n\n\/\/ leap\n\nleap::leap(const std::string& s, detail::undocumented)\n{\n    using namespace date;\n    std::istringstream in(s);\n    in.exceptions(std::ios::failbit | std::ios::badbit);\n    std::string word;\n    int y;\n    MonthDayTime date;\n    in >> word >> y >> date;\n    date_ = date.to_time_point(year(y));\n}\n\nstatic\nbool\nfile_exists(const std::string& filename)\n{\n#ifdef _WIN32\n    return ::_access(filename.c_str(), 0) == 0;\n#else\n    return ::access(filename.c_str(), F_OK) == 0;\n#endif\n}\n\n#if HAS_REMOTE_API\n\n\/\/ CURL tools\n\nstatic\nint\ncurl_global()\n{\n    if (::curl_global_init(CURL_GLOBAL_DEFAULT) != 0)\n        throw std::runtime_error(\"CURL global initialization failed\");\n    return 0;\n}\n\nnamespace\n{\n\nstruct curl_deleter\n{\n    void operator()(CURL* p) const\n    {\n        ::curl_easy_cleanup(p);\n    }\n};\n\n}  \/\/ unnamed namespace\n\nstatic\nstd::unique_ptr<CURL, curl_deleter>\ncurl_init()\n{\n    static const auto curl_is_now_initiailized = curl_global();\n    (void)curl_is_now_initiailized;\n    return std::unique_ptr<CURL, curl_deleter>{::curl_easy_init()};\n}\n\nstatic\nbool\ndownload_to_string(const std::string& url, std::string& str)\n{\n    str.clear();\n    auto curl = curl_init();\n    if (!curl)\n        return false;\n    std::string version;\n    curl_easy_setopt(curl.get(), CURLOPT_USERAGENT, \"curl\");\n    curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());\n    curl_write_callback write_cb = [](char* contents, std::size_t size, std::size_t nmemb,\n                                      void* userp) -> std::size_t\n    {\n        auto& userstr = *static_cast<std::string*>(userp);\n        auto realsize = size * nmemb;\n        userstr.append(contents, realsize);\n        return realsize;\n    };\n    curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_cb);\n    curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &str);\n    curl_easy_setopt(curl.get(), CURLOPT_SSL_VERIFYPEER, false);\n    auto res = curl_easy_perform(curl.get());\n    return (res == CURLE_OK);\n}\n\nnamespace\n{\n    enum class download_file_options { binary, text };\n}\n\nstatic\nbool\ndownload_to_file(const std::string& url, const std::string& local_filename,\n                 download_file_options opts)\n{\n    auto curl = curl_init();\n    if (!curl)\n        return false;\n    curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());\n    curl_easy_setopt(curl.get(), CURLOPT_SSL_VERIFYPEER, false);\n    curl_write_callback write_cb = [](char* contents, std::size_t size, std::size_t nmemb,\n                                      void* userp) -> std::size_t\n    {\n        auto& of = *static_cast<std::ofstream*>(userp);\n        auto realsize = size * nmemb;\n        of.write(contents, static_cast<std::streamsize>(realsize));\n        return realsize;\n    };\n    curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_cb);\n    decltype(curl_easy_perform(curl.get())) res;\n    {\n        std::ofstream of(local_filename,\n                         opts == download_file_options::binary ?\n                             std::ofstream::out | std::ofstream::binary :\n                             std::ofstream::out);\n        of.exceptions(std::ios::badbit);\n        curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &of);\n        res = curl_easy_perform(curl.get());\n    }\n    return res == CURLE_OK;\n}\n\nstd::string\nremote_version()\n{\n    std::string version;\n    std::string str;\n    if (download_to_string(\"https:\/\/www.iana.org\/time-zones\", str))\n    {\n        CONSTDATA char db[] = \"\/time-zones\/releases\/tzdata\";\n        CONSTDATA auto db_size = sizeof(db) - 1;\n        auto p = str.find(db, 0, db_size);\n        const int ver_str_len = 5;\n        if (p != std::string::npos && p + (db_size + ver_str_len) <= str.size())\n            version = str.substr(p + db_size, ver_str_len);\n    }\n    return version;\n}\n\n\n\/\/ TODO! Using system() create a process and a console window.\n\/\/ This is useful to see what errors may occur but is slow and distracting.\n\/\/ Consider implementing this functionality more directly, such as\n\/\/ using _mkdir and CreateProcess etc.\n\/\/ But use the current means now as matches Unix implementations and while\n\/\/ in proof of concept \/ testing phase.\n\/\/ TODO! Use <filesystem> eventually.\nstatic\nbool\nremove_folder_and_subfolders(const std::string& folder)\n{\n#  ifdef _WIN32\n#    if USE_SHELL_API\n    \/\/ Delete the folder contents by deleting the folder.\n    std::string cmd = \"rd \/s \/q \\\"\";\n    cmd += folder;\n    cmd += '\\\"';\n    return std::system(cmd.c_str()) == EXIT_SUCCESS;\n#    else  \/\/ !USE_SHELL_API\n    \/\/ Create a buffer containing the path to delete. It must be terminated\n    \/\/ by two nuls. Who designs these API's...\n    std::vector<char> from;\n    from.assign(folder.begin(), folder.end());\n    from.push_back('\\0');\n    from.push_back('\\0');\n    SHFILEOPSTRUCT fo{}; \/\/ Zero initialize.\n    fo.wFunc = FO_DELETE;\n    fo.pFrom = from.data();\n    fo.fFlags = FOF_NO_UI;\n    int ret = SHFileOperation(&fo);\n    if (ret == 0 && !fo.fAnyOperationsAborted)\n        return true;\n    return false;\n#    endif  \/\/ !USE_SHELL_API\n#  else   \/\/ !_WIN32\n#    if USE_SHELL_API\n    return std::system((\"rm -R \" + folder).c_str()) == EXIT_SUCCESS;\n#    else \/\/ !USE_SHELL_API\n    struct dir_deleter {\n        dir_deleter() {}\n        void operator()(DIR* d) const\n        {\n            if (d != nullptr)\n            {\n                int result = closedir(d);\n                assert(result == 0);\n            }\n        }\n    };\n    using closedir_ptr = std::unique_ptr<DIR, dir_deleter>;\n\n    std::string filename;\n    struct stat statbuf;\n    std::size_t folder_len = folder.length();\n    struct dirent* p = nullptr;\n\n    closedir_ptr d(opendir(folder.c_str()));\n    bool r = d.get() != nullptr;\n    while (r && (p=readdir(d.get())) != nullptr)\n    {\n        if (strcmp(p->d_name, \".\") == 0 || strcmp(p->d_name, \"..\") == 0)\n           continue;\n\n        \/\/ + 2 for path delimiter and nul terminator.\n        std::size_t buf_len = folder_len + strlen(p->d_name) + 2;\n        filename.resize(buf_len);\n        std::size_t path_len = static_cast<std::size_t>(\n            snprintf(&filename[0], buf_len, \"%s\/%s\", folder.c_str(), p->d_name));\n        assert(path_len == buf_len - 1);\n        filename.resize(path_len);\n\n        if (stat(filename.c_str(), &statbuf) == 0)\n            r = S_ISDIR(statbuf.st_mode)\n              ? remove_folder_and_subfolders(filename)\n              : unlink(filename.c_str()) == 0;\n    }\n    d.reset();\n\n    if (r)\n        r = rmdir(folder.c_str()) == 0;\n\n    return r;\n#    endif \/\/ !USE_SHELL_API\n#  endif  \/\/ !_WIN32\n}\n\nstatic\nbool\nmake_directory(const std::string& folder)\n{\n#  ifdef _WIN32\n#    if USE_SHELL_API\n    \/\/ Re-create the folder.\n    std::string cmd = \"mkdir \\\"\";\n    cmd += folder;\n    cmd += '\\\"';\n    return std::system(cmd.c_str()) == EXIT_SUCCESS;\n#    else  \/\/ !USE_SHELL_API\n    return _mkdir(folder.c_str()) == 0;\n#    endif \/\/ !USE_SHELL_API\n#  else  \/\/ !_WIN32\n#    if USE_SHELL_API\n    return std::system((\"mkdir -p \" + folder).c_str()) == EXIT_SUCCESS;\n#    else  \/\/ !USE_SHELL_API\n    return mkdir(folder.c_str(), 0777) == 0;\n#    endif  \/\/ !USE_SHELL_API\n#  endif  \/\/ !_WIN32\n}\n\nstatic\nbool\ndelete_file(const std::string& file)\n{\n#  ifdef _WIN32\n#    if USE_SHELL_API\n    std::string cmd = \"del \\\"\";\n    cmd += file;\n    cmd += '\\\"';\n    return std::system(cmd.c_str()) == 0;\n#    else  \/\/ !USE_SHELL_API\n    return _unlink(file.c_str()) == 0;\n#    endif \/\/ !USE_SHELL_API\n#  else  \/\/ !_WIN32\n#    if USE_SHELL_API\n    return std::system((\"rm \" + file).c_str()) == EXIT_SUCCESS;\n#    else \/\/ !USE_SHELL_API\n    return unlink(file.c_str()) == 0;\n#    endif \/\/ !USE_SHELL_API\n#  endif  \/\/ !_WIN32\n}\n\n#  ifdef _WIN32\n\nstatic\nbool\nmove_file(const std::string& from, const std::string& to)\n{\n#    if USE_SHELL_API\n    std::string cmd = \"move \\\"\";\n    cmd += from;\n    cmd += \"\\\" \\\"\";\n    cmd += to;\n    cmd += '\\\"';\n    return std::system(cmd.c_str()) == EXIT_SUCCESS;\n#    else  \/\/ !USE_SHELL_API\n    return !!::MoveFile(from.c_str(), to.c_str());\n#    endif \/\/ !USE_SHELL_API\n}\n\n\/\/ Usually something like \"c:\\Program Files\".\nstatic\nstd::string\nget_program_folder()\n{\n    return get_known_folder(FOLDERID_ProgramFiles);\n}\n\n\/\/ Note folder can and usually does contain spaces.\nstatic\nstd::string\nget_unzip_program()\n{\n    std::string path;\n\n    \/\/ 7-Zip appears to note its location in the registry.\n    \/\/ If that doesn't work, fall through and take a guess, but it will likely be wrong.\n    HKEY hKey = nullptr;\n    if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, \"SOFTWARE\\\\7-Zip\", 0, KEY_READ, &hKey) == ERROR_SUCCESS)\n    {\n        char value_buffer[MAX_PATH + 1]; \/\/ fyi 260 at time of writing.\n        \/\/ in\/out parameter. Documentation say that size is a count of bytes not chars.\n        DWORD size = sizeof(value_buffer) - sizeof(value_buffer[0]);\n        DWORD tzi_type = REG_SZ;\n        \/\/ Testing shows Path key value is \"C:\\Program Files\\7-Zip\\\" i.e. always with trailing \\.\n        bool got_value = (RegQueryValueExA(hKey, \"Path\", nullptr, &tzi_type,\n            reinterpret_cast<LPBYTE>(value_buffer), &size) == ERROR_SUCCESS);\n        RegCloseKey(hKey); \/\/ Close now incase of throw later.\n        if (got_value)\n        {\n            \/\/ Function does not guarantee to null terminate.\n            value_buffer[size \/ sizeof(value_buffer[0])] = '\\0';\n            path = value_buffer;\n            if (!path.empty())\n            {\n                path += \"7z.exe\";\n                return path;\n            }\n        }\n    }\n    path += get_program_folder();\n    path += folder_delimiter;\n    path += \"7-Zip\\\\7z.exe\";\n    return path;\n}\n\n#    if !USE_SHELL_API\nstatic\nint\nrun_program(const std::string& command)\n{\n    STARTUPINFO si{};\n    si.cb = sizeof(si);\n    PROCESS_INFORMATION pi{};\n\n    \/\/ Allegedly CreateProcess overwrites the command line. Ugh.\n    std::string mutable_command(command);\n    if (CreateProcess(nullptr, &mutable_command[0],\n        nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi))\n    {\n        WaitForSingleObject(pi.hProcess, INFINITE);\n        DWORD exit_code;\n        bool got_exit_code = !!GetExitCodeProcess(pi.hProcess, &exit_code);\n        CloseHandle(pi.hProcess);\n        CloseHandle(pi.hThread);\n        \/\/ Not 100% sure about this still active thing is correct,\n        \/\/ but I'm going with it because I *think* WaitForSingleObject might\n        \/\/ return in some cases without INFINITE-ly waiting.\n        \/\/ But why\/wouldn't GetExitCodeProcess return false in that case?\n        if (got_exit_code && exit_code != STILL_ACTIVE)\n            return static_cast<int>(exit_code);\n    }\n    return EXIT_FAILURE;\n}\n#    endif \/\/ !USE_SHELL_API\n\nstatic\nstd::string\nget_download_tar_file(const std::string& version)\n{\n    auto file = get_install();\n    file += folder_delimiter;\n    file += \"tzdata\";\n    file += version;\n    file += \".tar\";\n    return file;\n}\n\nstatic\nbool\nextract_gz_file(const std::string& version, const std::string& gz_file,\n                const std::string& dest_folder)\n{\n    auto unzip_prog = get_unzip_program();\n    bool unzip_result = false;\n    \/\/ Use the unzip program to extract the tar file from the archive.\n\n    \/\/ Aim to create a string like:\n    \/\/ \"C:\\Program Files\\7-Zip\\7z.exe\" x \"C:\\Users\\SomeUser\\Downloads\\tzdata2016d.tar.gz\"\n    \/\/     -o\"C:\\Users\\SomeUser\\Downloads\\tzdata\"\n    std::string cmd;\n    cmd = '\\\"';\n    cmd += unzip_prog;\n    cmd += \"\\\" x \\\"\";\n    cmd += gz_file;\n    cmd += \"\\\" -o\\\"\";\n    cmd += dest_folder;\n    cmd += '\\\"';\n\n#    if USE_SHELL_API\n    \/\/ When using shelling out with std::system() extra quotes are required around the\n    \/\/ whole command. It's weird but necessary it seems, see:\n    \/\/ http:\/\/stackoverflow.com\/q\/27975969\/576911\n\n    cmd = \"\\\"\" + cmd + \"\\\"\";\n    if (std::system(cmd.c_str()) == EXIT_SUCCESS)\n        unzip_result = true;\n#    else  \/\/ !USE_SHELL_API\n    if (run_program(cmd) == EXIT_SUCCESS)\n        unzip_result = true;\n#    endif \/\/ !USE_SHELL_API\n    if (unzip_result)\n        delete_file(gz_file);\n\n    \/\/ Use the unzip program extract the data from the tar file that was\n    \/\/ just extracted from the archive.\n    auto tar_file = get_download_tar_file(version);\n    cmd = '\\\"';\n    cmd += unzip_prog;\n    cmd += \"\\\" x \\\"\";\n    cmd += tar_file;\n    cmd += \"\\\" -o\\\"\";\n    cmd += get_install();\n    cmd += '\\\"';\n#    if USE_SHELL_API\n    cmd = \"\\\"\" + cmd + \"\\\"\";\n    if (std::system(cmd.c_str()) == EXIT_SUCCESS)\n        unzip_result = true;\n#    else  \/\/ !USE_SHELL_API\n    if (run_program(cmd) == EXIT_SUCCESS)\n        unzip_result = true;\n#    endif \/\/ !USE_SHELL_API\n\n    if (unzip_result)\n        delete_file(tar_file);\n\n    return unzip_result;\n}\n\nstatic\nstd::string\nget_download_mapping_file(const std::string& version)\n{\n    auto file = get_install() + version + \"windowsZones.xml\";\n    return file;\n}\n\n#  else  \/\/ !_WIN32\n\n#    if !USE_SHELL_API\nstatic\nint\nrun_program(const char* prog, const char*const args[])\n{\n    pid_t pid = fork();\n    if (pid == -1) \/\/ Child failed to start.\n        return EXIT_FAILURE;\n\n    if (pid != 0)\n    {\n        \/\/ We are in the parent. Child started. Wait for it.\n        pid_t ret;\n        int status;\n        while ((ret = waitpid(pid, &status, 0)) == -1)\n        {\n            if (errno != EINTR)\n                break;\n        }\n        if (ret != -1)\n        {\n            if (WIFEXITED(status))\n                return WEXITSTATUS(status);\n        }\n        printf(\"Child issues!\\n\");\n\n        return EXIT_FAILURE; \/\/ Not sure what status of child is.\n    }\n    else \/\/ We are in the child process. Start the program the parent wants to run.\n    {\n\n        if (execv(prog, const_cast<char**>(args)) == -1) \/\/ Does not return.\n        {\n            perror(\"unreachable 0\\n\");\n            _Exit(127);\n        }\n        printf(\"unreachable 2\\n\");\n    }\n    printf(\"unreachable 2\\n\");\n    \/\/ Unreachable.\n    assert(false);\n    exit(EXIT_FAILURE);\n    return EXIT_FAILURE;\n}\n#    endif \/\/ !USE_SHELL_API\n\nstatic\nbool\nextract_gz_file(const std::string&, const std::string& gz_file, const std::string&)\n{\n#    if USE_SHELL_API\n    bool unzipped = std::system((\"tar -xzf \" + gz_file + \" -C \" + get_install()).c_str()) == EXIT_SUCCESS;\n#    else  \/\/ !USE_SHELL_API\n    const char prog[] = {\"\/usr\/bin\/tar\"};\n    const char*const args[] =\n    {\n        prog, \"-xzf\", gz_file.c_str(), \"-C\", get_install().c_str(), nullptr\n    };\n    bool unzipped = (run_program(prog, args) == EXIT_SUCCESS);\n#    endif \/\/ !USE_SHELL_API\n    if (unzipped)\n    {\n        delete_file(gz_file);\n        return true;\n    }\n    return false;\n}\n\n#  endif \/\/ !_WIN32\n\nbool\nremote_download(const std::string& version)\n{\n    assert(!version.empty());\n\n#  ifdef _WIN32\n    \/\/ Download folder should be always available for Windows\n#  else  \/\/ !_WIN32\n    \/\/ Create download folder if it does not exist on UNIX system\n    auto download_folder = get_install();\n    if (!file_exists(download_folder))\n    {\n        if (!make_directory(download_folder))\n            return false;\n    }\n#  endif  \/\/ _WIN32\n\n    auto url = \"https:\/\/data.iana.org\/time-zones\/releases\/tzdata\" + version +\n               \".tar.gz\";\n    bool result = download_to_file(url, get_download_gz_file(version),\n                                   download_file_options::binary);\n#  ifdef _WIN32\n    if (result)\n    {\n        auto mapping_file = get_download_mapping_file(version);\n        result = download_to_file(\n\t\t\t\"https:\/\/raw.githubusercontent.com\/unicode-org\/cldr\/master\/\"\n\t\t\t\"common\/supplemental\/windowsZones.xml\",\n            mapping_file, download_file_options::text);\n    }\n#  endif  \/\/ _WIN32\n    return result;\n}\n\nbool\nremote_install(const std::string& version)\n{\n    auto success = false;\n    assert(!version.empty());\n\n    std::string install = get_install();\n    auto gz_file = get_download_gz_file(version);\n    if (file_exists(gz_file))\n    {\n        if (file_exists(install))\n            remove_folder_and_subfolders(install);\n        if (make_directory(install))\n        {\n            if (extract_gz_file(version, gz_file, install))\n                success = true;\n#  ifdef _WIN32\n            auto mapping_file_source = get_download_mapping_file(version);\n            auto mapping_file_dest = get_install();\n            mapping_file_dest += folder_delimiter;\n            mapping_file_dest += \"windowsZones.xml\";\n            if (!move_file(mapping_file_source, mapping_file_dest))\n                success = false;\n#  endif  \/\/ _WIN32\n        }\n    }\n    return success;\n}\n\n#endif  \/\/ HAS_REMOTE_API\n\nstatic\nstd::string\nget_version(const std::string& path)\n{\n    std::string version;\n    std::ifstream infile(path + \"version\");\n    if (infile.is_open())\n    {\n        infile >> version;\n        if (!infile.fail())\n            return version;\n    }\n    else\n    {\n        infile.open(path + \"NEWS\");\n        while (infile)\n        {\n            infile >> version;\n            if (version == \"Release\")\n            {\n                infile >> version;\n                return version;\n            }\n        }\n    }\n    throw std::runtime_error(\"Unable to get Timezone database version from \" + path);\n}\n\nstatic\nstd::unique_ptr<tzdb>\ninit_tzdb()\n{\n    using namespace date;\n    const std::string install = get_install();\n    const std::string path = install + folder_delimiter;\n    std::string line;\n    bool continue_zone = false;\n    std::unique_ptr<tzdb> db(new tzdb);\n\n#if AUTO_DOWNLOAD\n    if (!file_exists(install))\n    {\n        auto rv = remote_version();\n        if (!rv.empty() && remote_download(rv))\n        {\n            if (!remote_install(rv))\n            {\n                std::string msg = \"Timezone database version \\\"\";\n                msg += rv;\n                msg += \"\\\" did not install correctly to \\\"\";\n                msg += install;\n                msg += \"\\\"\";\n                throw std::runtime_error(msg);\n            }\n        }\n        if (!file_exists(install))\n        {\n            std::string msg = \"Timezone database not found at \\\"\";\n            msg += install;\n            msg += \"\\\"\";\n            throw std::runtime_error(msg);\n        }\n        db->version = get_version(path);\n    }\n    else\n    {\n        db->version = get_version(path);\n        auto rv = remote_version();\n        if (!rv.empty() && db->version != rv)\n        {\n            if (remote_download(rv))\n            {\n                remote_install(rv);\n                db->version = get_version(path);\n            }\n        }\n    }\n#else  \/\/ !AUTO_DOWNLOAD\n    if (!file_exists(install))\n    {\n        std::string msg = \"Timezone database not found at \\\"\";\n        msg += install;\n        msg += \"\\\"\";\n        throw std::runtime_error(msg);\n    }\n    db->version = get_version(path);\n#endif  \/\/ !AUTO_DOWNLOAD\n\n    CONSTDATA char*const files[] =\n    {\n        \"africa\", \"antarctica\", \"asia\", \"australasia\", \"backward\", \"etcetera\", \"europe\",\n        \"pacificnew\", \"northamerica\", \"southamerica\", \"systemv\", \"leapseconds\"\n    };\n\n    for (const auto& filename : files)\n    {\n        std::ifstream infile(path + filename);\n        while (infile)\n        {\n            std::getline(infile, line);\n            if (!line.empty() && line[0] != '#')\n            {\n                std::istringstream in(line);\n                std::string word;\n                in >> word;\n                if (word == \"Rule\")\n                {\n                    db->rules.push_back(Rule(line));\n                    continue_zone = false;\n                }\n                else if (word == \"Link\")\n                {\n                    db->links.push_back(link(line));\n                    continue_zone = false;\n                }\n                else if (word == \"Leap\")\n                {\n                    db->leaps.push_back(leap(line, detail::undocumented{}));\n                    continue_zone = false;\n                }\n                else if (word == \"Zone\")\n                {\n                    db->zones.push_back(time_zone(line, detail::undocumented{}));\n                    continue_zone = true;\n                }\n                else if (line[0] == '\\t' && continue_zone)\n                {\n                    db->zones.back().add(line);\n                }\n                else\n                {\n                    std::cerr << line << '\\n';\n                }\n            }\n        }\n    }\n    std::sort(db->rules.begin(), db->rules.end());\n    Rule::split_overlaps(db->rules);\n    std::sort(db->zones.begin(), db->zones.end());\n    db->zones.shrink_to_fit();\n    std::sort(db->links.begin(), db->links.end());\n    db->links.shrink_to_fit();\n    std::sort(db->leaps.begin(), db->leaps.end());\n    db->leaps.shrink_to_fit();\n\n#ifdef _WIN32\n    std::string mapping_file = get_install() + folder_delimiter + \"windowsZones.xml\";\n    db->mappings = load_timezone_mappings_from_xml_file(mapping_file);\n    sort_zone_mappings(db->mappings);\n#endif \/\/ _WIN32\n\n    return db;\n}\n\nconst tzdb&\nreload_tzdb()\n{\n#if AUTO_DOWNLOAD\n    auto const& v = get_tzdb_list().front().version;\n    if (!v.empty() && v == remote_version())\n        return get_tzdb_list().front();\n#endif  \/\/ AUTO_DOWNLOAD\n    tzdb_list::undocumented_helper::push_front(get_tzdb_list(), init_tzdb().release());\n    return get_tzdb_list().front();\n}\n\n#endif  \/\/ !USE_OS_TZDB\n\nconst tzdb&\nget_tzdb()\n{\n    return get_tzdb_list().front();\n}\n\nconst time_zone*\n#if HAS_STRING_VIEW\ntzdb::locate_zone(std::string_view tz_name) const\n#else\ntzdb::locate_zone(const std::string& tz_name) const\n#endif\n{\n    auto zi = std::lower_bound(zones.begin(), zones.end(), tz_name,\n#if HAS_STRING_VIEW\n        [](const time_zone& z, const std::string_view& nm)\n#else\n        [](const time_zone& z, const std::string& nm)\n#endif\n        {\n            return z.name() < nm;\n        });\n    if (zi == zones.end() || zi->name() != tz_name)\n    {\n#if !USE_OS_TZDB\n        auto li = std::lower_bound(links.begin(), links.end(), tz_name,\n#if HAS_STRING_VIEW\n        [](const link& z, const std::string_view& nm)\n#else\n        [](const link& z, const std::string& nm)\n#endif\n        {\n            return z.name() < nm;\n        });\n        if (li != links.end() && li->name() == tz_name)\n        {\n            zi = std::lower_bound(zones.begin(), zones.end(), li->target(),\n                [](const time_zone& z, const std::string& nm)\n                {\n                    return z.name() < nm;\n                });\n            if (zi != zones.end() && zi->name() == li->target())\n                return &*zi;\n        }\n#endif  \/\/ !USE_OS_TZDB\n        throw std::runtime_error(std::string(tz_name) + \" not found in timezone database\");\n    }\n    return &*zi;\n}\n\nconst time_zone*\n#if HAS_STRING_VIEW\nlocate_zone(std::string_view tz_name)\n#else\nlocate_zone(const std::string& tz_name)\n#endif\n{\n    return get_tzdb().locate_zone(tz_name);\n}\n\n#if USE_OS_TZDB\n\nstd::ostream&\noperator<<(std::ostream& os, const tzdb& db)\n{\n    os << \"Version: \" << db.version << \"\\n\\n\";\n    for (const auto& x : db.zones)\n        os << x << '\\n';\n#if !MISSING_LEAP_SECONDS\n    os << '\\n';\n    for (const auto& x : db.leaps)\n        os << x << '\\n';\n#endif  \/\/ !MISSING_LEAP_SECONDS\n    return os;\n}\n\n#else  \/\/ !USE_OS_TZDB\n\nstd::ostream&\noperator<<(std::ostream& os, const tzdb& db)\n{\n    os << \"Version: \" << db.version << '\\n';\n    std::string title(\"--------------------------------------------\"\n                      \"--------------------------------------------\\n\"\n                      \"Name           \"\"Start Y \"\"End Y   \"\n                      \"Beginning                              \"\"Offset  \"\n                      \"Designator\\n\"\n                      \"--------------------------------------------\"\n                      \"--------------------------------------------\\n\");\n    int count = 0;\n    for (const auto& x : db.rules)\n    {\n        if (count++ % 50 == 0)\n            os << title;\n        os << x << '\\n';\n    }\n    os << '\\n';\n    title = std::string(\"---------------------------------------------------------\"\n                        \"--------------------------------------------------------\\n\"\n                        \"Name                               \"\"Offset      \"\n                        \"Rule           \"\"Abrev      \"\"Until\\n\"\n                        \"---------------------------------------------------------\"\n                        \"--------------------------------------------------------\\n\");\n    count = 0;\n    for (const auto& x : db.zones)\n    {\n        if (count++ % 10 == 0)\n            os << title;\n        os << x << '\\n';\n    }\n    os << '\\n';\n    title = std::string(\"---------------------------------------------------------\"\n                        \"--------------------------------------------------------\\n\"\n                        \"Alias                                   \"\"To\\n\"\n                        \"---------------------------------------------------------\"\n                        \"--------------------------------------------------------\\n\");\n    count = 0;\n    for (const auto& x : db.links)\n    {\n        if (count++ % 45 == 0)\n            os << title;\n        os << x << '\\n';\n    }\n    os << '\\n';\n    title = std::string(\"---------------------------------------------------------\"\n                        \"--------------------------------------------------------\\n\"\n                        \"Leap second on\\n\"\n                        \"---------------------------------------------------------\"\n                        \"--------------------------------------------------------\\n\");\n    os << title;\n    for (const auto& x : db.leaps)\n        os << x << '\\n';\n    return os;\n}\n\n#endif  \/\/ !USE_OS_TZDB\n\n\/\/ -----------------------\n\n#ifdef _WIN32\n\nstatic\nstd::string\ngetTimeZoneKeyName()\n{\n    DYNAMIC_TIME_ZONE_INFORMATION dtzi{};\n    auto result = GetDynamicTimeZoneInformation(&dtzi);\n    if (result == TIME_ZONE_ID_INVALID)\n        throw std::runtime_error(\"current_zone(): GetDynamicTimeZoneInformation()\"\n                                 \" reported TIME_ZONE_ID_INVALID.\");\n    auto wlen = wcslen(dtzi.TimeZoneKeyName);\n    char buf[128] = {};\n    assert(sizeof(buf) >= wlen+1);\n    wcstombs(buf, dtzi.TimeZoneKeyName, wlen);\n    if (strcmp(buf, \"Coordinated Universal Time\") == 0)\n        return \"UTC\";\n    return buf;\n}\n\nconst time_zone*\ntzdb::current_zone() const\n{\n    std::string win_tzid = getTimeZoneKeyName();\n    std::string standard_tzid;\n    if (!native_to_standard_timezone_name(win_tzid, standard_tzid))\n    {\n        std::string msg;\n        msg = \"current_zone() failed: A mapping from the Windows Time Zone id \\\"\";\n        msg += win_tzid;\n        msg += \"\\\" was not found in the time zone mapping database.\";\n        throw std::runtime_error(msg);\n    }\n    return locate_zone(standard_tzid);\n}\n\n#else  \/\/ !_WIN32\n# ifndef TZDB_NO_CURRENT_ZONE\nconst time_zone*\ntzdb::current_zone() const\n{\n    \/\/ On some OS's a file called \/etc\/localtime may\n    \/\/ exist and it may be either a real file\n    \/\/ containing time zone details or a symlink to such a file.\n    \/\/ On MacOS and BSD Unix if this file is a symlink it\n    \/\/ might resolve to a path like this:\n    \/\/ \"\/usr\/share\/zoneinfo\/America\/Los_Angeles\"\n    \/\/ If it does, we try to determine the current\n    \/\/ timezone from the remainder of the path by removing the prefix\n    \/\/ and hoping the rest resolves to a valid timezone.\n    \/\/ It may not always work though. If it doesn't then an\n    \/\/ exception will be thrown by local_timezone.\n    \/\/ The path may also take a relative form:\n    \/\/ \"..\/usr\/share\/zoneinfo\/America\/Los_Angeles\".\n    {\n        struct stat sb;\n        CONSTDATA auto timezone = \"\/etc\/localtime\";\n        if (lstat(timezone, &sb) == 0 && S_ISLNK(sb.st_mode) && sb.st_size > 0) {\n            using namespace std;\n            char rp[PATH_MAX+1] = {};\n            if (realpath(timezone, rp) == nullptr)\n                throw system_error(errno, system_category(), \"realpath() failed\");\n#if HAS_STRING_VIEW\n            string_view result = rp;\n            CONSTDATA string_view zoneinfo = \"zoneinfo\";\n            size_t pos = result.rfind(zoneinfo);\n            if (pos == result.npos)\n                throw runtime_error(\n                    \"current_zone() failed to find \\\"zoneinfo\\\" in \" + string(result));\n            pos = result.find('\/', pos);\n            result.remove_prefix(pos + 1);\n#else\n            string result = rp;\n            CONSTDATA char zoneinfo[] = \"zoneinfo\";\n            size_t pos = result.rfind(zoneinfo);\n            if (pos == result.npos)\n                throw runtime_error(\n                    \"current_zone() failed to find \\\"zoneinfo\\\" in \" + result);\n            pos = result.find('\/', pos);\n            result.erase(0, pos + 1);\n#endif\n            return locate_zone(result);\n        }\n    }\n    \/\/ On embedded systems e.g. buildroot with uclibc the timezone is linked\n    \/\/ into \/etc\/TZ which is a symlink to path like this:\n    \/\/ \"\/usr\/share\/zoneinfo\/uclibc\/America\/Los_Angeles\"\n    \/\/ If it does, we try to determine the current\n    \/\/ timezone from the remainder of the path by removing the prefix\n    \/\/ and hoping the rest resolves to valid timezone.\n    \/\/ It may not always work though. If it doesn't then an\n    \/\/ exception will be thrown by local_timezone.\n    \/\/ The path may also take a relative form:\n    \/\/ \"..\/usr\/share\/zoneinfo\/uclibc\/America\/Los_Angeles\".\n    {\n        struct stat sb;\n        CONSTDATA auto timezone = \"\/etc\/TZ\";\n        if (lstat(timezone, &sb) == 0 && S_ISLNK(sb.st_mode) && sb.st_size > 0) {\n            using namespace std;\n            string result;\n            char rp[PATH_MAX+1] = {};\n            if (readlink(timezone, rp, sizeof(rp)-1) > 0)\n                result = string(rp);\n            else\n                throw system_error(errno, system_category(), \"readlink() failed\");\n\n            const size_t pos = result.find(get_tz_dir());\n            if (pos != result.npos)\n                result.erase(0, get_tz_dir().size() + 1 + pos);\n            return locate_zone(result);\n        }\n    }\n    {\n    \/\/ On some versions of some linux distro's (e.g. Ubuntu),\n    \/\/ the current timezone might be in the first line of\n    \/\/ the \/etc\/timezone file.\n        std::ifstream timezone_file(\"\/etc\/timezone\");\n        if (timezone_file.is_open())\n        {\n            std::string result;\n            std::getline(timezone_file, result);\n            if (!result.empty())\n                return locate_zone(result);\n        }\n        \/\/ Fall through to try other means.\n    }\n    {\n    \/\/ On some versions of some bsd distro's (e.g. FreeBSD),\n    \/\/ the current timezone might be in the first line of\n    \/\/ the \/var\/db\/zoneinfo file.\n        std::ifstream timezone_file(\"\/var\/db\/zoneinfo\");\n        if (timezone_file.is_open())\n        {\n            std::string result;\n            std::getline(timezone_file, result);\n            if (!result.empty())\n                return locate_zone(result);\n        }\n        \/\/ Fall through to try other means.\n    }\n    {\n    \/\/ On some versions of some bsd distro's (e.g. iOS),\n    \/\/ it is not possible to use file based approach,\n    \/\/ we switch to system API, calling functions in\n    \/\/ CoreFoundation framework.\n#if TARGET_OS_IPHONE\n        std::string result = date::iOSUtils::get_current_timezone();\n        if (!result.empty())\n            return locate_zone(result);\n#endif\n    \/\/ Fall through to try other means.\n    }\n    {\n    \/\/ On some versions of some linux distro's (e.g. Red Hat),\n    \/\/ the current timezone might be in the first line of\n    \/\/ the \/etc\/sysconfig\/clock file as:\n    \/\/ ZONE=\"US\/Eastern\"\n        std::ifstream timezone_file(\"\/etc\/sysconfig\/clock\");\n        std::string result;\n        while (timezone_file)\n        {\n            std::getline(timezone_file, result);\n            auto p = result.find(\"ZONE=\\\"\");\n            if (p != std::string::npos)\n            {\n                result.erase(p, p+6);\n                result.erase(result.rfind('\"'));\n                return locate_zone(result);\n            }\n        }\n        \/\/ Fall through to try other means.\n    }\n    throw std::runtime_error(\"Could not get current timezone\");\n}\n# endif\n#endif  \/\/ !_WIN32\n\n#ifndef TZDB_NO_CURRENT_ZONE\nconst time_zone*\ncurrent_zone()\n{\n    return get_tzdb().current_zone();\n}\n#endif\n\n}  \/\/ namespace date\n\n#if defined(__GNUC__) && __GNUC__ < 5\n# pragma GCC diagnostic pop\n#endif\n","avg_line_length":29.7976999477,"max_line_length":106,"alphanum_fraction":0.5502605126,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":707,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":9.0,"content":"#include \"pch.h\"\n#include \"Texture.h\"\n#include \"Sail\/Application.h\"\n\nTexture::Texture(const std::string& filename)\n\t: m_name(filename)\n\t, texIsCubeMap(false)\n\t, readyToUse(false)\n{ }\n\nconst std::string& Texture::getName() const {\n\treturn m_name;\n}\n\nbool Texture::isCubeMap() const {\n\treturn texIsCubeMap;\n}\n\nbool Texture::isReadyToUse() const {\n\treturn readyToUse;\n}\n\nTextureData& Texture::getTextureData(const std::string& filename, bool useAbsolutePath) const {\n\t\/\/ Load the texture file it if is not loaded already\n\tauto& rm = Application::getInstance()->getResourceManager();\n\tif (!rm.hasTextureData(filename)) {\n\t\trm.loadTextureData(filename, useAbsolutePath);\n\t}\n\treturn rm.getTextureData(filename);\n}","avg_line_length":23.5666666667,"max_line_length":95,"alphanum_fraction":0.7397454031,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4057,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":88.0,"content":"#include \"Core\/Renderer\/PM\/PPMRadianceEvaluationWork.h\"\n#include \"Common\/assertion.h\"\n#include \"Core\/Intersectable\/Primitive.h\"\n#include \"Core\/Intersectable\/PrimitiveMetadata.h\"\n#include \"Core\/SurfaceBehavior\/SurfaceBehavior.h\"\n#include \"Core\/SurfaceBehavior\/SurfaceOptics.h\"\n#include \"Core\/SurfaceHit.h\"\n#include \"Core\/Renderer\/PM\/PMRenderer.h\"\n#include \"Core\/Emitter\/Emitter.h\"\n#include \"Core\/LTABuildingBlock\/TSurfaceEventDispatcher.h\"\n#include \"Core\/LTABuildingBlock\/lta.h\"\n#include \"Common\/Logger.h\"\n\nnamespace ph\n{\n\nnamespace\n{\n\tconst Logger logger(LogSender(\"PPM Radiance Evaluator\"));\n}\n\nPPMRadianceEvaluationWork::PPMRadianceEvaluationWork(\n\n\tconst TPhotonMap<FullPhoton>* const photonMap,\n\tconst std::size_t                   numPhotonPaths,\n\n\tHdrRgbFilm* const    film,\n\tFullViewpoint* const viewpoints,\n\tconst std::size_t    numViewpoints,\n\tconst Scene* const   scene) :\n\n\tTRadianceEvaluationWork(photonMap, numPhotonPaths),\n\n\tm_film         (film),\n\tm_viewpoints   (viewpoints),\n\tm_numViewpoints(numViewpoints),\n\tm_scene        (scene)\n{\n\tPH_ASSERT(film);\n\n\tsetPMStatistics(nullptr);\n\tsetAlpha(2.0_r \/ 3.0_r);\n}\n\nvoid PPMRadianceEvaluationWork::doWork()\n{\n\tsanitizeVariables();\n\tTSurfaceEventDispatcher<ESaPolicy::STRICT> surfaceEvent(m_scene);\n\n\tstd::vector<FullPhoton> photonCache;\n\tfor(std::size_t i = 0; i < m_numViewpoints; ++i)\n\t{\n\t\tFullViewpoint& viewpoint = m_viewpoints[i];\n\n\t\tconst SurfaceHit& surfaceHit = viewpoint.get<EViewpointData::SURFACE_HIT>();\n\t\tconst Vector3R    L          = viewpoint.get<EViewpointData::VIEW_DIR>();\n\t\tconst Vector3R    Ng         = surfaceHit.getGeometryNormal();\n\t\tconst Vector3R    Ns         = surfaceHit.getShadingNormal();\n\t\tconst real        R          = viewpoint.get<EViewpointData::RADIUS>();\n\n\t\tphotonCache.clear();\n\t\tgetPhotonMap()->findWithinRange(surfaceHit.getPosition(), R, photonCache);\n\n\t\tconst real N    = viewpoint.get<EViewpointData::NUM_PHOTONS>();\n\t\tconst real M    = static_cast<real>(photonCache.size());\n\t\tconst real newN = N + m_alpha * M;\n\t\tconst real newR = (N + M) != 0.0_r ? R * std::sqrt(newN \/ (N + M)) : R;\n\n\t\tSpectralStrength tauM(0);\n\t\tBsdfEvaluation   bsdfEval;\n\t\tfor(const auto& photon : photonCache)\n\t\t{\n\t\t\tconst Vector3R V = photon.get<EPhotonData::FROM_DIR>();\n\n\t\t\tbsdfEval.inputs.set(surfaceHit, L, V, ALL_ELEMENTALS, ETransport::IMPORTANCE);\n\t\t\tif(!surfaceEvent.doBsdfEvaluation(surfaceHit, bsdfEval))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tSpectralStrength tau = photon.get<EPhotonData::THROUGHPUT_RADIANCE>();\n\t\t\ttau.mulLocal(bsdfEval.outputs.bsdf);\n\t\t\ttau.mulLocal(lta::importance_BSDF_Ns_corrector(Ns, Ng, L, V));\n\n\t\t\ttauM.addLocal(tau);\n\t\t}\n\t\tconst SpectralStrength tauN   = viewpoint.get<EViewpointData::TAU>();\n\t\tconst SpectralStrength newTau = (N + M) != 0.0_r ? (tauN + tauM) * (newN \/ (N + M)) : SpectralStrength(0);\n\n\t\tviewpoint.set<EViewpointData::RADIUS>(newR);\n\t\tviewpoint.set<EViewpointData::NUM_PHOTONS>(newN);\n\t\tviewpoint.set<EViewpointData::TAU>(newTau);\n\t\t\n\t\t\/\/ evaluate radiance using current iteration's data\n\n\t\tconst real kernelArea         = newR * newR * constant::pi<real>;\n\t\tconst real radianceMultiplier = 1.0_r \/ (kernelArea * static_cast<real>(numPhotonPaths()));\n\n\t\tSpectralStrength radiance(viewpoint.get<EViewpointData::TAU>() * radianceMultiplier);\n\t\tradiance.addLocal(viewpoint.get<EViewpointData::VIEW_RADIANCE>());\n\t\tradiance.mulLocal(viewpoint.get<EViewpointData::VIEW_THROUGHPUT>());\n\n\t\tconst Vector2R filmNdc = viewpoint.get<EViewpointData::FILM_NDC>();\n\t\tconst real filmXPx = filmNdc.x * static_cast<real>(m_film->getActualResPx().x);\n\t\tconst real filmYPx = filmNdc.y * static_cast<real>(m_film->getActualResPx().y);\n\t\tm_film->addSample(filmXPx, filmYPx, radiance);\n\t}\n}\n\nvoid PPMRadianceEvaluationWork::sanitizeVariables()\n{\n\treal sanitizedAlpha = m_alpha;\n\tif(m_alpha < 0.0_r || m_alpha > 1.0_r)\n\t{\n\t\tlogger.log(ELogLevel::WARNING_MED, \n\t\t\t\"alpha must be in [0, 1], \" + std::to_string(m_alpha) + \" provided, clamping\");\n\n\t\tsanitizedAlpha = math::clamp(m_alpha, 0.0_r, 1.0_r);\n\t}\n\n\tm_alpha = sanitizedAlpha;\n}\n\n}\/\/ end namespace ph\n","avg_line_length":32.456,"max_line_length":108,"alphanum_fraction":0.7204831156,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1254,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2018-2019,  Zhirnov Andrey. For more information see 'LICENSE'\n\n#include \"Utils.h\"\n\n\nextern void Test_Shader2 (VPipelineCompiler* compiler)\n{\n\tComputePipelineDesc\tppln;\n\n\tppln.AddShader( EShaderLangFormat::GLSL_450, \"main\", R\"#(\n#pragma shader_stage(compute)\n\nlayout (local_size_x=16, local_size_y=8, local_size_z=1) in;\n\nlayout(binding=0, rgba8) writeonly uniform image2D  un_OutImage;\n\nlayout(binding=1, std140) readonly buffer un_SSBO\n{\n\tvec4 ssb_data;\n};\n\nvoid main ()\n{\n\tvec2 uv = vec2(gl_GlobalInvocationID.xy) \/ vec2((gl_WorkGroupSize * gl_NumWorkGroups).xy);\n\n\tvec4 fragColor = vec4(sin(uv.x), cos(uv.y), 1.0, ssb_data.r);\n\n\timageStore( un_OutImage, ivec2(gl_GlobalInvocationID.xy), fragColor );\n}\n)#\" );\n\n\n\tTEST( compiler->Compile( INOUT ppln, EShaderLangFormat::SPIRV_100 ));\n\n\tauto ds = FindDescriptorSet( ppln, DescriptorSetID(\"0\") );\n\tTEST( ds );\n\n\tTEST( TestImageUniform( *ds, UniformID(\"un_OutImage\"), EImage::Tex2D, EPixelFormat::RGBA8_UNorm, EShaderAccess::WriteOnly, 0, EShaderStages::Compute ));\n\tTEST( TestStorageBuffer( *ds, UniformID(\"un_SSBO\"), 16_b, 0_b, EShaderAccess::ReadOnly, 1, EShaderStages::Compute ));\n\n\tTEST(All( ppln._defaultLocalGroupSize == uint3(16, 8, 1) ));\n\n\tFG_LOGI( \"Test_Shader2 - passed\" );\n}\n","avg_line_length":27.8666666667,"max_line_length":153,"alphanum_fraction":0.7320574163,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5618,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"#include <futurepia\/blockchain_statistics\/blockchain_statistics_api.hpp>\n\nnamespace futurepia { namespace blockchain_statistics {\n\nnamespace detail\n{\n   class blockchain_statistics_api_impl\n   {\n      public:\n         blockchain_statistics_api_impl( futurepia::app::application& app )\n            :_app( app ) {}\n\n         statistics get_stats_for_time( fc::time_point_sec open, uint32_t interval )const;\n         statistics get_stats_for_interval( fc::time_point_sec start, fc::time_point_sec end )const;\n         statistics get_lifetime_stats()const;\n\n         futurepia::app::application& _app;\n   };\n\n   statistics blockchain_statistics_api_impl::get_stats_for_time( fc::time_point_sec open, uint32_t interval )const\n   {\n      statistics result;\n      const auto& bucket_idx = _app.chain_database()->get_index< bucket_index >().indices().get< by_bucket >();\n      auto itr = bucket_idx.lower_bound( boost::make_tuple( interval, open ) );\n\n      if( itr != bucket_idx.end() )\n         result += *itr;\n\n      return result;\n   }\n\n   statistics blockchain_statistics_api_impl::get_stats_for_interval( fc::time_point_sec start, fc::time_point_sec end )const\n   {\n      statistics result;\n      const auto& bucket_itr = _app.chain_database()->get_index< bucket_index >().indices().get< by_bucket >();\n      const auto& sizes = _app.get_plugin< blockchain_statistics_plugin >( BLOCKCHAIN_STATISTICS_PLUGIN_NAME )->get_tracked_buckets();\n      auto size_itr = sizes.rbegin();\n      auto time = start;\n\n      \/\/ This is a greedy algorithm, same as the ubiquitous \"making change\" problem.\n      \/\/ So long as the bucket sizes share a common denominator, the greedy solution\n      \/\/ has the same efficiency as the dynamic solution.\n      while( size_itr != sizes.rend() && time < end )\n      {\n         auto itr = bucket_itr.find( boost::make_tuple( *size_itr, time ) );\n\n         while( itr != bucket_itr.end() && itr->seconds == *size_itr && time + itr->seconds <= end )\n         {\n            time += *size_itr;\n            result += *itr;\n            itr++;\n         }\n\n         size_itr++;\n      }\n\n      return result;\n   }\n\n   statistics blockchain_statistics_api_impl::get_lifetime_stats()const\n   {\n      statistics result;\n      result += _app.chain_database()->get( bucket_id_type() );\n\n      return result;\n   }\n} \/\/ detail\n\nblockchain_statistics_api::blockchain_statistics_api( const futurepia::app::api_context& ctx )\n{\n   my = std::make_shared< detail::blockchain_statistics_api_impl >( ctx.app );\n}\n\nvoid blockchain_statistics_api::on_api_startup() {}\n\nstatistics blockchain_statistics_api::get_stats_for_time( fc::time_point_sec open, uint32_t interval )const\n{\n   return my->_app.chain_database()->with_read_lock( [&]()\n   {\n      return my->get_stats_for_time( open, interval );\n   });\n}\n\nstatistics blockchain_statistics_api::get_stats_for_interval( fc::time_point_sec start, fc::time_point_sec end )const\n{\n   return my->_app.chain_database()->with_read_lock( [&]()\n   {\n      return my->get_stats_for_interval( start, end );\n   });\n}\n\nstatistics blockchain_statistics_api::get_lifetime_stats()const\n{\n   return my->_app.chain_database()->with_read_lock( [&]()\n   {\n      return my->get_lifetime_stats();\n   });\n}\n\nstatistics& statistics::operator +=( const bucket_object& b )\n{\n   this->blocks                                 += b.blocks;\n   this->bandwidth                              += b.bandwidth;\n   this->operations                             += b.operations;\n   this->transactions                           += b.transactions;\n   this->transfers                              += b.transfers;\n   this->pia_transferred                        += b.pia_transferred;\n   this->snac_transferred                       += b.snac_transferred;\n   this->accounts_created                       += b.accounts_created;\n   this->total_comments                         += b.root_comments + b.replies;\n   this->total_comment_edits                    += b.root_comment_edits + b.reply_edits;\n   this->total_comments_deleted                 += b.root_comments_deleted + b.replies_deleted;\n   this->root_comments                          += b.root_comments;\n   this->root_comment_edits                     += b.root_comment_edits;\n   this->root_comments_deleted                  += b.root_comments_deleted;\n   this->replies                                += b.replies;\n   this->reply_edits                            += b.reply_edits;\n   this->replies_deleted                        += b.replies_deleted;\n   this->total_votes                            += b.new_root_votes + b.new_reply_votes;\n   this->new_votes                              += b.new_root_votes + b.new_reply_votes;\n   this->total_root_votes                       += b.new_root_votes;\n   this->new_root_votes                         += b.new_root_votes;\n   this->total_reply_votes                      += b.new_reply_votes ;\n   this->new_reply_votes                        += b.new_reply_votes;\n   this->like_count                             += b.like_count;\n   this->dislike_count                          += b.dislike_count;\n   this->recommend_count                        += b.recommend_count;\n   this->betting_count                          += b.betting_count;\n   this->snac_conversion_requests_created       += b.snac_conversion_requests_created;\n   this->snac_to_be_converted                   += b.snac_to_be_converted;\n   this->snac_conversion_requests_filled        += b.snac_conversion_requests_filled;\n   this->pia_converted                          += b.pia_converted;\n\n   return ( *this );\n}\n\n} } \/\/ futurepia::blockchain_statistics\n","avg_line_length":40.7101449275,"max_line_length":134,"alphanum_fraction":0.6119615522,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11136,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":26.0,"content":"\/\/ license:BSD-3-Clause\n\/\/ copyright-holders:Zsolt Vasvari\n\/***************************************************************************\n\n    Allied Leisure Clay Shoot hardware\n\n    driver by Zsolt Vasvari\n\n    Games supported:\n        * Clay Shoot\n\n    Known issues:\n        * no sound\n        * cocktail mode, dipswitch or alternate romset?\n          (cocktail set has a color overlay, upright set has a backdrop)\n\n****************************************************************************\/\n\n#include \"emu.h\"\n#include \"cpu\/z80\/z80.h\"\n#include \"machine\/i8255.h\"\n#include \"machine\/watchdog.h\"\n#include \"screen.h\"\n\n\nclass clayshoo_state : public driver_device\n{\npublic:\n\tclayshoo_state(const machine_config &mconfig, device_type type, const char *tag)\n\t\t: driver_device(mconfig, type, tag),\n\t\tm_videoram(*this, \"videoram\"),\n\t\tm_maincpu(*this, \"maincpu\")\n\t{ }\n\n\tvoid clayshoo(machine_config &config);\n\nprotected:\n\tvoid analog_reset_w(uint8_t data);\n\tuint8_t analog_r();\n\tvoid input_port_select_w(uint8_t data);\n\tuint8_t input_port_r();\n\tuint32_t screen_update_clayshoo(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect);\n\tTIMER_CALLBACK_MEMBER(reset_analog_bit);\n\tuint8_t difficulty_input_port_r(int bit);\n\tvoid create_analog_timers();\n\n\tvirtual void machine_start() override;\n\tvirtual void machine_reset() override;\n\tvoid main_io_map(address_map &map);\n\tvoid main_map(address_map &map);\n\nprivate:\n\t\/* memory pointers *\/\n\trequired_shared_ptr<uint8_t> m_videoram;\n\n\t\/* misc *\/\n\temu_timer *m_analog_timer_1, *m_analog_timer_2;\n\tuint8_t m_input_port_select;\n\tuint8_t m_analog_port_val;\n\n\trequired_device<cpu_device> m_maincpu;\n};\n\n\n\/*************************************\n *\n *  Digital control handling functions\n *\n *************************************\/\n\nvoid clayshoo_state::input_port_select_w(uint8_t data)\n{\n\tm_input_port_select = data;\n}\n\n\nuint8_t clayshoo_state::difficulty_input_port_r( int bit )\n{\n\tuint8_t ret = 0;\n\n\t\/* read fake port and remap the buttons to 2 bits *\/\n\tuint8_t   raw = ioport(\"FAKE\")->read();\n\n\tif (raw & (1 << (bit + 1)))\n\t\tret = 0x03;     \/* expert *\/\n\telse if (raw & (1 << (bit + 2)))\n\t\tret = 0x01;     \/* pro *\/\n\telse\n\t\tret = 0x00;     \/* amateur otherwise *\/\n\n\treturn ret;\n}\n\n\nuint8_t clayshoo_state::input_port_r()\n{\n\tuint8_t ret = 0;\n\n\tswitch (m_input_port_select)\n\t{\n\tcase 0x01:  ret = ioport(\"IN0\")->read(); break;\n\tcase 0x02:  ret = ioport(\"IN1\")->read(); break;\n\tcase 0x04:  ret = (ioport(\"IN2\")->read() & 0xf0) | difficulty_input_port_r(0) |\n\t\t\t\t\t\t(difficulty_input_port_r(3) << 2); break;\n\tcase 0x08:  ret = ioport(\"IN3\")->read(); break;\n\tcase 0x10:\n\tcase 0x20:  break;  \/* these two are not really used *\/\n\tdefault: logerror(\"Unexpected port read: %02X\\n\", m_input_port_select);\n\t}\n\treturn ret;\n}\n\n\n\n\/*************************************\n *\n *  Analog control handling functions\n *\n *************************************\/\n\nTIMER_CALLBACK_MEMBER(clayshoo_state::reset_analog_bit)\n{\n\tm_analog_port_val &= ~param;\n}\n\n\nstatic attotime compute_duration( device_t *device, int analog_pos )\n{\n\t\/* the 58 comes from the length of the loop used to\n\t   read the analog position *\/\n\treturn downcast<cpu_device *>(device)->cycles_to_attotime(58 * analog_pos);\n}\n\n\nvoid clayshoo_state::analog_reset_w(uint8_t data)\n{\n\t\/* reset the analog value, and start the two times that will fire\n\t   off in a short period proportional to the position of the\n\t   analog control and set the appropriate bit. *\/\n\n\tm_analog_port_val = 0xff;\n\n\tm_analog_timer_1->adjust(compute_duration(m_maincpu.target(), ioport(\"AN1\")->read()), 0x02);\n\tm_analog_timer_2->adjust(compute_duration(m_maincpu.target(), ioport(\"AN2\")->read()), 0x01);\n}\n\n\nuint8_t clayshoo_state::analog_r()\n{\n\treturn m_analog_port_val;\n}\n\n\nvoid clayshoo_state::create_analog_timers(  )\n{\n\tm_analog_timer_1 = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(clayshoo_state::reset_analog_bit),this));\n\tm_analog_timer_2 = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(clayshoo_state::reset_analog_bit),this));\n}\n\n\n\n\/*************************************\n *\n *  Machine setup\n *\n *************************************\/\n\nvoid clayshoo_state::machine_start()\n{\n\tcreate_analog_timers();\n\n\t\/* register for state saving *\/\n\tsave_item(NAME(m_input_port_select));\n\tsave_item(NAME(m_analog_port_val));\n}\n\n\n\n\/*************************************\n *\n *  Video hardware\n *\n *************************************\/\n\nuint32_t clayshoo_state::screen_update_clayshoo(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)\n{\n\toffs_t offs;\n\n\tfor (offs = 0; offs < m_videoram.bytes(); offs++)\n\t{\n\t\tint i;\n\t\tuint8_t x = offs << 3;\n\t\tuint8_t y = ~(offs >> 5);\n\t\tuint8_t data = m_videoram[offs];\n\n\t\tfor (i = 0; i < 8; i++)\n\t\t{\n\t\t\tpen_t pen = (data & 0x80) ? rgb_t::white() : rgb_t::black();\n\t\t\tbitmap.pix(y, x) = pen;\n\n\t\t\tdata = data << 1;\n\t\t\tx = x + 1;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n\n\n\/*************************************\n *\n *  Memory handlers\n *\n *************************************\/\n\nvoid clayshoo_state::main_map(address_map &map)\n{\n\tmap(0x0000, 0x1fff).rom();\n\tmap(0x2000, 0x23ff).ram();\n\tmap(0x4000, 0x47ff).rom();\n\tmap(0x8000, 0x97ff).ram().share(\"videoram\");    \/* 6k of video ram according to readme *\/\n\tmap(0x9800, 0xa800).nopw();      \/* not really mapped, but cleared *\/\n\tmap(0xc800, 0xc800).rw(FUNC(clayshoo_state::analog_r), FUNC(clayshoo_state::analog_reset_w));\n}\n\n\n\n\/*************************************\n *\n *  Port handlers\n *\n *************************************\/\n\nvoid clayshoo_state::main_io_map(address_map &map)\n{\n\tmap.global_mask(0xff);\n\tmap(0x00, 0x00).w(\"watchdog\", FUNC(watchdog_timer_device::reset_w));\n\tmap(0x20, 0x23).rw(\"ppi8255_0\", FUNC(i8255_device::read), FUNC(i8255_device::write));\n\tmap(0x30, 0x33).rw(\"ppi8255_1\", FUNC(i8255_device::read), FUNC(i8255_device::write));\n\/\/  map(0x40, 0x43).noprw(); \/\/ 8253 for sound?\n\/\/  map(0x50, 0x50).noprw(); \/\/ ?\n\/\/  map(0x60, 0x60).noprw(); \/\/ ?\n}\n\n\n\n\/*************************************\n *\n *  Port definitions\n *\n *************************************\/\n\nstatic INPUT_PORTS_START( clayshoo )\n\tPORT_START(\"IN0\")\n\tPORT_DIPNAME( 0x03, 0x00, DEF_STR( Coinage ) )\n\tPORT_DIPSETTING(    0x00, DEF_STR( 1C_1C ) )\n\tPORT_DIPSETTING(    0x02, DEF_STR( 2C_3C ) )\n\tPORT_DIPSETTING(    0x01, DEF_STR( 1C_2C ) )\n\tPORT_DIPSETTING(    0x03, DEF_STR( Free_Play ) )\n\tPORT_BIT( 0x3c, IP_ACTIVE_LOW, IPT_UNKNOWN )        \/* doesn't appear to be used *\/\n\tPORT_DIPNAME( 0x40, 0x40, DEF_STR( Demo_Sounds ) )  \/* not 100% positive *\/\n\tPORT_DIPSETTING(    0x00, DEF_STR( Off ) )\n\tPORT_DIPSETTING(    0x40, DEF_STR( On ) )\n\tPORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) )      \/* used *\/\n\tPORT_DIPSETTING(    0x00, DEF_STR( Off ) )\n\tPORT_DIPSETTING(    0x80, DEF_STR( On ) )\n\n\tPORT_START(\"IN1\")\n\tPORT_DIPNAME( 0x07, 0x01, \"Time\/Bonus 1P-2P\" )\n\tPORT_DIPSETTING(    0x00, \"60\/6k-90\/6k\" )\n\tPORT_DIPSETTING(    0x01, \"60\/6k-120\/8k\" )\n\tPORT_DIPSETTING(    0x02, \"90\/9.5k-150\/9.5k\" )\n\tPORT_DIPSETTING(    0x03, \"90\/9.5k-190\/11k\" )\n\tPORT_DIPSETTING(    0x04, \"60\/8k-90\/8k\" )\n\tPORT_DIPSETTING(    0x05, \"60\/8k-120\/10k\" )\n\tPORT_DIPSETTING(    0x06, \"90\/11.5k-150\/11.5k\" )\n\tPORT_DIPSETTING(    0x07, \"90\/11.5k-190\/13k\" )\n\tPORT_BIT( 0xf8, IP_ACTIVE_LOW, IPT_UNKNOWN )    \/* doesn't appear to be used *\/\n\n\tPORT_START(\"IN2\")\n\tPORT_BIT( 0x03, IP_ACTIVE_LOW, IPT_CUSTOM )    \/* amateur\/expert\/pro Player 2 *\/\n\tPORT_BIT( 0x0c, IP_ACTIVE_LOW, IPT_CUSTOM )    \/* amateur\/expert\/pro Player 1 *\/\n\tPORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START1 )\n\tPORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START2 )\n\tPORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)\n\tPORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1)\n\n\tPORT_START(\"IN3\")\n\tPORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )\n\tPORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNKNOWN )\n\n\tPORT_START(\"AN1\")  \/* IN4 - Fake analog control.  Visible in $c800 bit 1 *\/\n\tPORT_BIT( 0x0f, 0x08, IPT_AD_STICK_Y ) PORT_MINMAX(0,0x0f) PORT_SENSITIVITY(10) PORT_KEYDELTA(10) PORT_REVERSE PORT_PLAYER(1)\n\tPORT_BIT( 0xf0, IP_ACTIVE_HIGH, IPT_UNUSED )\n\n\tPORT_START(\"AN2\")  \/* IN5 - Fake analog control.  Visible in $c800 bit 0 *\/\n\tPORT_BIT( 0x0f, 0x08, IPT_AD_STICK_Y ) PORT_MINMAX(0,0x0f) PORT_SENSITIVITY(10) PORT_KEYDELTA(10) PORT_REVERSE PORT_PLAYER(2)\n\tPORT_BIT( 0xf0, IP_ACTIVE_HIGH, IPT_UNUSED )\n\n\tPORT_START(\"FAKE\")  \/* IN6 - Fake.  Visible in IN2 bits 0-1 and 2-3 *\/\n\tPORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_TOGGLE PORT_PLAYER(2) PORT_NAME(\"P2 Amateur Difficulty\")\n\tPORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_BUTTON3 ) PORT_TOGGLE PORT_PLAYER(2) PORT_NAME(\"P2 Expert Difficulty\")\n\tPORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_BUTTON4 ) PORT_TOGGLE PORT_PLAYER(2) PORT_NAME(\"P2 Pro Difficulty\")\n\tPORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_TOGGLE PORT_PLAYER(1) PORT_NAME(\"P1 Amateur Difficulty\")\n\tPORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON3 ) PORT_TOGGLE PORT_PLAYER(1) PORT_NAME(\"P1 Expert Difficulty\")\n\tPORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON4 ) PORT_TOGGLE PORT_PLAYER(1) PORT_NAME(\"P2 Pro Difficulty\")\n\tPORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )\nINPUT_PORTS_END\n\n\n\n\/*************************************\n *\n *  Machine driver\n *\n *************************************\/\n\nvoid clayshoo_state::machine_reset()\n{\n\tm_input_port_select = 0;\n\tm_analog_port_val = 0;\n}\n\nvoid clayshoo_state::clayshoo(machine_config &config)\n{\n\t\/* basic machine hardware *\/\n\tZ80(config, m_maincpu, 5068000\/4);      \/* 5.068\/4 Mhz (divider is a guess) *\/\n\tm_maincpu->set_addrmap(AS_PROGRAM, &clayshoo_state::main_map);\n\tm_maincpu->set_addrmap(AS_IO, &clayshoo_state::main_io_map);\n\tm_maincpu->set_vblank_int(\"screen\", FUNC(clayshoo_state::irq0_line_hold));\n\n\tWATCHDOG_TIMER(config, \"watchdog\");\n\n\t\/* video hardware *\/\n\tscreen_device &screen(SCREEN(config, \"screen\", SCREEN_TYPE_RASTER));\n\tscreen.set_size(256, 256);\n\tscreen.set_visarea(0, 255, 64, 255);\n\tscreen.set_refresh_hz(60);\n\tscreen.set_vblank_time(ATTOSECONDS_IN_USEC(2500) \/* not accurate *\/);\n\tscreen.set_screen_update(FUNC(clayshoo_state::screen_update_clayshoo));\n\n\tI8255A(config, \"ppi8255_0\");\n\n\ti8255_device &ppi1(I8255A(config, \"ppi8255_1\"));\n\tppi1.out_pa_callback().set(FUNC(clayshoo_state::input_port_select_w));\n\tppi1.in_pb_callback().set(FUNC(clayshoo_state::input_port_r));\n}\n\n\n\n\/*************************************\n *\n *  ROM definitions\n *\n *************************************\/\n\nROM_START( clayshoo )\n\tROM_REGION( 0x10000, \"maincpu\", 0 )\n\tROM_LOAD( \"0\",      0x0000, 0x0800, CRC(9df9d9e3) SHA1(8ce71a6faf5df9c8c3dbb92a443b62c0f376491c) )\n\tROM_LOAD( \"1\",      0x0800, 0x0800, CRC(5134a631) SHA1(f0764a5161934564fd0416be26087cf812e0c422) )\n\tROM_LOAD( \"2\",      0x1000, 0x0800, CRC(5b5a67f6) SHA1(c97b4d44e6dc5dd0c42e04ffceed8934975fe769) )\n\tROM_LOAD( \"3\",      0x1800, 0x0800, CRC(7eda8e44) SHA1(2974f8b06653aee2ffd96ff402707acfc059bc91) )\n\tROM_LOAD( \"4\",      0x4000, 0x0800, CRC(3da16196) SHA1(eb0c0cf0c8fc3db05ac0c469fb20fe92ae6f27ce) )\nROM_END\n\n\n\n\/*************************************\n *\n *  Game drivers\n *\n *************************************\/\n\nGAME( 1979, clayshoo, 0, clayshoo, clayshoo, clayshoo_state, empty_init, ROT0, \"Allied Leisure\", \"Clay Shoot\", MACHINE_NO_SOUND | MACHINE_SUPPORTS_SAVE )\n","avg_line_length":29.6170212766,"max_line_length":153,"alphanum_fraction":0.6543642241,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4333,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"bitcoinunits.h\"\n\n#include <QStringList>\n\nBitcoinUnits::BitcoinUnits(QObject *parent):\n        QAbstractListModel(parent),\n        unitlist(availableUnits())\n{\n}\n\nQList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()\n{\n    QList<BitcoinUnits::Unit> unitlist;\n    unitlist.append(BTC);\n    unitlist.append(mBTC);\n    unitlist.append(uBTC);\n    return unitlist;\n}\n\nbool BitcoinUnits::valid(int unit)\n{\n    switch(unit)\n    {\n    case BTC:\n    case mBTC:\n    case uBTC:\n        return true;\n    default:\n        return false;\n    }\n}\n\nQString BitcoinUnits::name(int unit)\n{\n    switch(unit)\n    {\n    case BTC: return QString(\"GEO\");\n    case mBTC: return QString(\"mGEO\");\n    case uBTC: return QString::fromUtf8(\"\u03bcGEO\");\n    default: return QString(\"???\");\n    }\n}\n\nQString BitcoinUnits::description(int unit)\n{\n    switch(unit)\n    {\n    case BTC: return QString(\"CoinTer\");\n    case mBTC: return QString(\"milliCoinTer (1 \/ 1,000)\");\n    case uBTC: return QString(\"microCoinTer (1 \/ 1,000,000)\");\n    default: return QString(\"???\");\n    }\n}\n\/\/a single unit (.00000001) of CoinTer is called a \"wander.\"\nqint64 BitcoinUnits::factor(int unit)\n{\n    switch(unit)\n    {\n    case BTC:  return 100000000;\n    case mBTC: return 100000;\n    case uBTC: return 100;\n    default:   return 100000000;\n    }\n}\n\nint BitcoinUnits::amountDigits(int unit)\n{\n    switch(unit)\n    {\n    case BTC: return 8; \/\/ 21,000,000 (# digits, without commas)\n    case mBTC: return 11; \/\/ 21,000,000,000\n    case uBTC: return 14; \/\/ 21,000,000,000,000\n    default: return 0;\n    }\n}\n\nint BitcoinUnits::decimals(int unit)\n{\n    switch(unit)\n    {\n    case BTC: return 8;\n    case mBTC: return 5;\n    case uBTC: return 2;\n    default: return 0;\n    }\n}\n\nQString BitcoinUnits::format(int unit, qint64 n, bool fPlus)\n{\n    \/\/ Note: not using straight sprintf here because we do NOT want\n    \/\/ localized number formatting.\n    if(!valid(unit))\n        return QString(); \/\/ Refuse to format invalid unit\n    qint64 coin = factor(unit);\n    int num_decimals = decimals(unit);\n    qint64 n_abs = (n > 0 ? n : -n);\n    qint64 quotient = n_abs \/ coin;\n    qint64 remainder = n_abs % coin;\n    QString quotient_str = QString::number(quotient);\n    QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');\n\n    \/\/ Right-trim excess 0's after the decimal point\n    int nTrim = 0;\n    for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)\n        ++nTrim;\n    remainder_str.chop(nTrim);\n\n    if (n < 0)\n        quotient_str.insert(0, '-');\n    else if (fPlus && n > 0)\n        quotient_str.insert(0, '+');\n    return quotient_str + QString(\".\") + remainder_str;\n}\n\nQString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)\n{\n    return format(unit, amount, plussign) + QString(\" \") + name(unit);\n}\n\nbool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)\n{\n    if(!valid(unit) || value.isEmpty())\n        return false; \/\/ Refuse to parse invalid unit or empty string\n    int num_decimals = decimals(unit);\n    QStringList parts = value.split(\".\");\n\n    if(parts.size() > 2)\n    {\n        return false; \/\/ More than one dot\n    }\n    QString whole = parts[0];\n    QString decimals;\n\n    if(parts.size() > 1)\n    {\n        decimals = parts[1];\n    }\n    if(decimals.size() > num_decimals)\n    {\n        return false; \/\/ Exceeds max precision\n    }\n    bool ok = false;\n    QString str = whole + decimals.leftJustified(num_decimals, '0');\n\n    if(str.size() > 18)\n    {\n        return false; \/\/ Longer numbers will exceed 63 bits\n    }\n    qint64 retvalue = str.toLongLong(&ok);\n    if(val_out)\n    {\n        *val_out = retvalue;\n    }\n    return ok;\n}\n\nint BitcoinUnits::rowCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return unitlist.size();\n}\n\nQVariant BitcoinUnits::data(const QModelIndex &index, int role) const\n{\n    int row = index.row();\n    if(row >= 0 && row < unitlist.size())\n    {\n        Unit unit = unitlist.at(row);\n        switch(role)\n        {\n        case Qt::EditRole:\n        case Qt::DisplayRole:\n            return QVariant(name(unit));\n        case Qt::ToolTipRole:\n            return QVariant(description(unit));\n        case UnitRole:\n            return QVariant(static_cast<int>(unit));\n        }\n    }\n    return QVariant();\n}\n","avg_line_length":23.8076923077,"max_line_length":89,"alphanum_fraction":0.6145857374,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4230,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":123.0,"content":"#ifndef _WIN32\n#include \"graysvr.h\"\t\/\/ predef header\n#include \"CUnixTerminal.h\"\n#ifndef _USECURSES\n\t#include <stdio.h>\n\t#include <unistd.h>\n\t#include <sys\/time.h>\n#endif\n\nCUnixTerminal g_UnixTerminal;\n\nCUnixTerminal::CUnixTerminal()\n{\n\tprepare();\n}\n\nCUnixTerminal::~CUnixTerminal()\n{\n\trestore();\n}\n\nbool CUnixTerminal::isReady()\n{\n\tADDTOCALLSTACK(\"CUnixTerminal::isReady\");\n\tif ( m_szNextChar != '\\0' )\n\t\treturn true;\n\n#ifdef _USECURSES\n\tint ch = wgetch(m_pWindow);\n\tif ( ch == ERR )\n\t\treturn false;\n\n\tif ( (ch >= 0) && (ch <= 255) )\n\t{\n\t\t\/\/ Character input received\n\t\tm_szNextChar = static_cast<TCHAR>(ch);\n\t\treturn true;\n\t}\n\telse switch ( ch )\n\t{\n\t\t\/\/ Special character input received\n\t\tcase KEY_BACKSPACE:\n\t\t\tm_szNextChar = '\\b';\n\t\t\treturn true;\n\t\tcase KEY_ENTER:\n\t\t\tm_szNextChar = '\\n';\n\t\t\treturn true;\n\t\t\/\/case KEY_RESIZE:\t\t\/\/ to-do: resize window\n\t\t\/\/case KEY_MOUSE:\t\t\/\/ to-do: handle mouse event\n\t\tdefault:\n\t\t\treturn false;\n\t}\n#else\n\t\/\/ Check if input is waiting\n\tfd_set consoleFds;\n\tFD_ZERO(&consoleFds);\n\tFD_SET(STDIN_FILENO, &consoleFds);\n\n\ttimeval tvTimeout;\n\ttvTimeout.tv_sec = 0;\n\ttvTimeout.tv_usec = 1;\n\n\tif ( select(1, &consoleFds, 0, 0, &tvTimeout) <= 0 )\n\t\treturn false;\n\n\t\/\/ Get next character\n\tint ch = fgetc(stdin);\n\tif ( (ch < 0) || (ch > 255) )\n\t\treturn false;\n\n\t\/\/ Map backspace\n\tif ( ch == m_terminal.c_cc[VERASE] )\n\t\tch = '\\b';\n\n\t\/\/ Echo to console\n\tfputc(ch, stdout);\n\tfflush(stdout);\n\n\tm_szNextChar = static_cast<TCHAR>(ch);\n\treturn (m_szNextChar != '\\0');\n#endif\n}\n\nTCHAR CUnixTerminal::read()\n{\n\tADDTOCALLSTACK(\"CUnixTerminal::read\");\n\tTCHAR ch = m_szNextChar;\n\tm_szNextChar = '\\0';\n\treturn ch;\n}\n\nvoid CUnixTerminal::setColor(COLOR_TYPE color)\n{\n\tif ( !m_fColorEnabled )\n\t\treturn;\n\tif ( (color < COL_DEFAULT) || (color >= COL_QTY) )\n\t\tcolor = COL_DEFAULT;\n\n#ifdef _USECURSES\n\twattrset(m_pWindow, COLOR_PAIR(color));\n#else\n\tif ( color == COL_DEFAULT )\n\t\tfprintf(stdout, \"\\033[0m\");\n\telse\n\t\tfprintf(stdout, \"\\033[0;%dm\", 30 + static_cast<int>(color));\n#endif\n}\n\nvoid CUnixTerminal::print(LPCTSTR pszText)\n{\n\tADDTOCALLSTACK(\"CUnixTerminal::print\");\n\tASSERT(pszText);\n#ifdef _USECURSES\n\twaddstr(m_pWindow, pszText);\n\twrefresh(m_pWindow);\n#else\n\tfputs(pszText, stdout);\n#endif\n}\n\nvoid CUnixTerminal::prepare()\n{\n\tADDTOCALLSTACK(\"CUnixTerminal::prepare\");\n\tASSERT(!m_fPrepared);\n\n#ifdef _USECURSES\n\tinitscr();\t\/\/ init screen\n\tcbreak();\t\/\/ read one character at a time\n\techo();\t\t\/\/ echo input\n\n\t\/\/ Create a window (same size as terminal)\n\tint lines, columns;\n\tgetmaxyx(stdscr, lines, columns);\n\tm_pWindow = newwin(lines, columns, 0, 0);\n\n\tkeypad(m_pWindow, TRUE);\t\t\/\/ process special chars\n\tnodelay(m_pWindow, TRUE);\t\t\/\/ non-blocking input\n\tscrollok(m_pWindow, TRUE);\t\t\/\/ allow scrolling\n\trefresh();\t\t\t\t\t\t\/\/ draw screen\n\n\t\/\/ Initialize colors, and map enums to color codes\n\tm_fColorEnabled = has_colors();\n\tif ( m_fColorEnabled )\n\t{\n\t\tstart_color();\n\t\tinit_pair(COL_RED, COLOR_RED, COLOR_BLACK);\n\t\tinit_pair(COL_GREEN, COLOR_GREEN, COLOR_BLACK);\n\t\tinit_pair(COL_YELLOW, COLOR_YELLOW, COLOR_BLACK);\n\t\tinit_pair(COL_BLUE, COLOR_BLUE, COLOR_BLACK);\n\t\tinit_pair(COL_CYAN, COLOR_CYAN, COLOR_BLACK);\n\t\tinit_pair(COL_MAGENTA, COLOR_MAGENTA, COLOR_BLACK);\n\t\tinit_pair(COL_WHITE, COLOR_WHITE, COLOR_BLACK);\n\t}\n#else\n\t\/\/ Save existing attributes\n\tif ( tcgetattr(STDIN_FILENO, &m_terminal) != 0 )\n\t\tthrow CGrayError(LOGL_WARN, 0, \"failed to get terminal attributes\");\n\n\t\/\/ Set new terminal attributes\n\ttermios term_caps = m_terminal;\n\tterm_caps.c_lflag &= ~(ICANON|ECHO);\n\tterm_caps.c_cc[VMIN] = 1;\n\n\tif ( tcsetattr(STDIN_FILENO, TCSANOW, &term_caps) != 0 )\n\t\tthrow CGrayError(LOGL_WARN, 0, \"failed to set terminal attributes\");\n\n\tsetbuf(stdin, NULL);\n\tm_fColorEnabled = true;\t\t\/\/ assume every modern terminal support colors\n#endif\n\n\tm_szNextChar = '\\0';\n\tm_fPrepared = true;\n}\n\nvoid CUnixTerminal::restore()\n{\n\tADDTOCALLSTACK(\"CUnixTerminal::restore\");\n\tEXC_TRY(\"Restore\");\n\tASSERT(m_fPrepared);\n\n#ifdef _USECURSES\n\tendwin();\t\/\/ clean up\n\tm_pWindow = NULL;\n\tm_szNextChar = '\\0';\n#else\n\t\/\/ Restore original terminal state\n\tif ( tcsetattr(STDIN_FILENO, TCSANOW, &m_terminal) != 0 )\n\t\tthrow CGrayError(LOGL_WARN, 0, \"failed to restore terminal attributes\");\n#endif\n\n\tm_fPrepared = false;\n\tEXC_CATCH;\n}\n\n#endif\t\/\/ _WIN32\n","avg_line_length":21.5816326531,"max_line_length":74,"alphanum_fraction":0.6976359338,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":193689,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n * Copyright 2019 Google LLC\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"include\/core\/SkStream.h\"\n#include \"include\/core\/SkString.h\"\n#include \"include\/private\/SkHalf.h\"\n#include \"include\/private\/SkTFitsIn.h\"\n#include \"include\/private\/SkThreadID.h\"\n#include \"src\/core\/SkColorSpacePriv.h\"\n#include \"src\/core\/SkColorSpaceXformSteps.h\"\n#include \"src\/core\/SkCpu.h\"\n#include \"src\/core\/SkEnumerate.h\"\n#include \"src\/core\/SkOpts.h\"\n#include \"src\/core\/SkVM.h\"\n#include <algorithm>\n#include <atomic>\n#include <queue>\n\n#if defined(SKVM_LLVM)\n    #include <future>\n    #include <llvm\/Bitcode\/BitcodeWriter.h>\n    #include <llvm\/ExecutionEngine\/ExecutionEngine.h>\n    #include <llvm\/IR\/IRBuilder.h>\n    #include <llvm\/IR\/Verifier.h>\n    #include <llvm\/Support\/TargetSelect.h>\n    #include <llvm\/Support\/Host.h>\n\n    \/\/ Platform-specific intrinsics got their own files in LLVM 10.\n    #if __has_include(<llvm\/IR\/IntrinsicsX86.h>)\n        #include <llvm\/IR\/IntrinsicsX86.h>\n    #endif\n#endif\n\n\/\/ #define SKVM_LLVM_WAIT_FOR_COMPILATION\n\nbool gSkVMAllowJIT{false};\nbool gSkVMJITViaDylib{false};\n\n#if defined(SKVM_JIT)\n    #if defined(SK_BUILD_FOR_WIN)\n        #include \"src\/core\/SkLeanWindows.h\"\n        #include <memoryapi.h>\n\n        static void* alloc_jit_buffer(size_t* len) {\n            return VirtualAlloc(NULL, *len, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);\n        }\n        static void remap_as_executable(void* ptr, size_t len) {\n            DWORD old;\n            VirtualProtect(ptr, len, PAGE_EXECUTE_READ, &old);\n            SkASSERT(old == PAGE_READWRITE);\n        }\n        #if !defined(SKVM_LLVM)\n        static void unmap_jit_buffer(void* ptr, size_t len) {\n            VirtualFree(ptr, 0, MEM_RELEASE);\n        }\n        static void close_dylib(void* dylib) {\n            SkASSERT(false);  \/\/ TODO?  For now just assert we never make one.\n        }\n        #endif\n    #else\n        #include <dlfcn.h>\n        #include <sys\/mman.h>\n\n        static void* alloc_jit_buffer(size_t* len) {\n            \/\/ While mprotect and VirtualAlloc both work at page granularity,\n            \/\/ mprotect doesn't round up for you, and instead requires *len is at page granularity.\n            const size_t page = sysconf(_SC_PAGESIZE);\n            *len = ((*len + page - 1) \/ page) * page;\n            return mmap(nullptr,*len, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, -1,0);\n        }\n        static void remap_as_executable(void* ptr, size_t len) {\n            mprotect(ptr, len, PROT_READ|PROT_EXEC);\n            __builtin___clear_cache((char*)ptr,\n                                    (char*)ptr + len);\n        }\n        #if !defined(SKVM_LLVM)\n        static void unmap_jit_buffer(void* ptr, size_t len) {\n            munmap(ptr, len);\n        }\n        static void close_dylib(void* dylib) {\n            dlclose(dylib);\n        }\n        #endif\n    #endif\n\n    #if defined(SKVM_JIT_VTUNE)\n        #include <jitprofiling.h>\n        static void notify_vtune(const char* name, void* addr, size_t len) {\n            if (iJIT_IsProfilingActive() == iJIT_SAMPLING_ON) {\n                iJIT_Method_Load event;\n                memset(&event, 0, sizeof(event));\n                event.method_id           = iJIT_GetNewMethodID();\n                event.method_name         = const_cast<char*>(name);\n                event.method_load_address = addr;\n                event.method_size         = len;\n                iJIT_NotifyEvent(iJVM_EVENT_TYPE_METHOD_LOAD_FINISHED, &event);\n            }\n        }\n    #else\n        static void notify_vtune(const char* name, void* addr, size_t len) {}\n    #endif\n#endif\n\n\/\/ JIT code isn't MSAN-instrumented, so we won't see when it uses\n\/\/ uninitialized memory, and we'll not see the writes it makes as properly\n\/\/ initializing memory.  Instead force the interpreter, which should let\n\/\/ MSAN see everything our programs do properly.\n\/\/\n\/\/ Similarly, we can't get ASAN's checks unless we let it instrument our interpreter.\n#if defined(__has_feature)\n    #if __has_feature(memory_sanitizer) || __has_feature(address_sanitizer)\n        #define SKVM_JIT_BUT_IGNORE_IT\n    #endif\n#endif\n\n#if defined(SKSL_STANDALONE)\n    \/\/ skslc needs to link against this module (for the VM code generator). This module pulls in\n    \/\/ color-space code, but attempting to add those transitive dependencies to skslc gets out of\n    \/\/ hand. So we terminate the chain here with stub functions. Note that skslc's usage of SkVM\n    \/\/ never cares about color management.\n    skvm::F32 sk_program_transfer_fn(\n        skvm::F32 v, TFKind tf_kind,\n        skvm::F32 G, skvm::F32 A, skvm::F32 B, skvm::F32 C, skvm::F32 D, skvm::F32 E, skvm::F32 F) {\n            return v;\n    }\n\n    const skcms_TransferFunction* skcms_sRGB_TransferFunction() { return nullptr; }\n    const skcms_TransferFunction* skcms_sRGB_Inverse_TransferFunction() { return nullptr; }\n#endif\n\nnamespace skvm {\n\n    static Features detect_features() {\n        static const bool fma =\n        #if defined(SK_CPU_X86)\n            SkCpu::Supports(SkCpu::HSW);\n        #elif defined(SK_CPU_ARM64)\n            true;\n        #else\n            false;\n        #endif\n\n        static const bool fp16 = false;  \/\/ TODO\n\n        return { fma, fp16 };\n    }\n\n    Builder::Builder()                  : fFeatures(detect_features()) {}\n    Builder::Builder(Features features) : fFeatures(features         ) {}\n\n\n    struct Program::Impl {\n        std::vector<InterpreterInstruction> instructions;\n        int regs = 0;\n        int loop = 0;\n        std::vector<int> strides;\n\n        std::atomic<void*> jit_entry{nullptr};   \/\/ TODO: minimal std::memory_orders\n        size_t jit_size = 0;\n        void*  dylib    = nullptr;\n\n    #if defined(SKVM_LLVM)\n        std::unique_ptr<llvm::LLVMContext>     llvm_ctx;\n        std::unique_ptr<llvm::ExecutionEngine> llvm_ee;\n        std::future<void>                      llvm_compiling;\n    #endif\n    };\n\n    \/\/ Debugging tools, mostly for printing various data structures out to a stream.\n\n    namespace {\n        class SkDebugfStream final : public SkWStream {\n            size_t fBytesWritten = 0;\n\n            bool write(const void* buffer, size_t size) override {\n                SkDebugf(\"%.*s\", (int)size, (const char*)buffer);\n                fBytesWritten += size;\n                return true;\n            }\n\n            size_t bytesWritten() const override {\n                return fBytesWritten;\n            }\n        };\n\n        struct V { Val id; };\n        struct R { Reg id; };\n        struct Shift { int bits; };\n        struct Splat { int bits; };\n        struct Hex   { int bits; };\n        \/\/ For op `trace_line` or `trace_call`\n        struct Line  { int bits; };\n        \/\/ For op `trace_var`\n        struct VarSlot { int bits; };\n        struct VarType { int bits; };\n        static constexpr VarType kVarTypeInt{0};\n        static constexpr VarType kVarTypeFloat{1};\n        static constexpr VarType kVarTypeBool{2};\n        \/\/ For op `trace_call`\n        struct CallType { int bits; };\n        static constexpr CallType kCallTypeEnter{1};\n        static constexpr CallType kCallTypeExit{0};\n\n        static void write(SkWStream* o, const char* s) {\n            o->writeText(s);\n        }\n\n        static const char* name(Op op) {\n            switch (op) {\n            #define M(x) case Op::x: return #x;\n                SKVM_OPS(M)\n            #undef M\n            }\n            return \"unknown op\";\n        }\n\n        static void write(SkWStream* o, Op op) {\n            o->writeText(name(op));\n        }\n        static void write(SkWStream* o, Ptr p) {\n            write(o, \"ptr\");\n            o->writeDecAsText(p.ix);\n        }\n        static void write(SkWStream* o, V v) {\n            write(o, \"v\");\n            o->writeDecAsText(v.id);\n        }\n        static void write(SkWStream* o, R r) {\n            write(o, \"r\");\n            o->writeDecAsText(r.id);\n        }\n        static void write(SkWStream* o, Shift s) {\n            o->writeDecAsText(s.bits);\n        }\n        static void write(SkWStream* o, Splat s) {\n            float f;\n            memcpy(&f, &s.bits, 4);\n            o->writeHexAsText(s.bits);\n            write(o, \" (\");\n            o->writeScalarAsText(f);\n            write(o, \")\");\n        }\n        static void write(SkWStream* o, Hex h) {\n            o->writeHexAsText(h.bits);\n        }\n        static void write(SkWStream* o, Line d) {\n            write(o, \"L\");\n            o->writeDecAsText(d.bits);\n        }\n        static void write(SkWStream* o, VarSlot s) {\n            write(o, \"$\");\n            o->writeDecAsText(s.bits);\n        }\n        static void write(SkWStream* o, VarType n) {\n            if (n.bits == kVarTypeFloat.bits) {\n                write(o, \"(F32)\");\n            } else if (n.bits == kVarTypeInt.bits) {\n                write(o, \"(I32)\");\n            } else if (n.bits == kVarTypeBool.bits) {\n                write(o, \"(bool)\");\n            } else {\n                write(o, \"???\");\n            }\n        }\n        static void write(SkWStream* o, CallType n) {\n            if (n.bits == kCallTypeEnter.bits) {\n                write(o, \"(enter)\");\n            } else if (n.bits == kCallTypeExit.bits) {\n                write(o, \"(exit)\");\n            } else {\n                write(o, \"???\");\n            }\n        }\n\n        template <typename T, typename... Ts>\n        static void write(SkWStream* o, T first, Ts... rest) {\n            write(o, first);\n            write(o, \" \");\n            write(o, rest...);\n        }\n    }  \/\/ namespace\n\n    static void write_one_instruction(Val id, const OptimizedInstruction& inst, SkWStream* o) {\n        Op  op = inst.op;\n        Val  x = inst.x,\n             y = inst.y,\n             z = inst.z,\n             w = inst.w;\n        int immA = inst.immA,\n            immB = inst.immB,\n            immC = inst.immC;\n        switch (op) {\n            case Op::assert_true: write(o, op, V{x}, V{y}); break;\n\n            case Op::trace_line: write(o, op, V{x}, Line{immA}); break;\n            case Op::trace_var:  write(o, op, V{x}, VarSlot{immA}, \"=\", V{y}, VarType{immB}); break;\n            case Op::trace_call: write(o, op, V{x}, Line{immA}, CallType{immB}); break;\n\n            case Op::store8:   write(o, op, Ptr{immA}, V{x}               ); break;\n            case Op::store16:  write(o, op, Ptr{immA}, V{x}               ); break;\n            case Op::store32:  write(o, op, Ptr{immA}, V{x}               ); break;\n            case Op::store64:  write(o, op, Ptr{immA}, V{x},V{y}          ); break;\n            case Op::store128: write(o, op, Ptr{immA}, V{x},V{y},V{z},V{w}); break;\n\n            case Op::index: write(o, V{id}, \"=\", op); break;\n\n            case Op::load8:   write(o, V{id}, \"=\", op, Ptr{immA}); break;\n            case Op::load16:  write(o, V{id}, \"=\", op, Ptr{immA}); break;\n            case Op::load32:  write(o, V{id}, \"=\", op, Ptr{immA}); break;\n            case Op::load64:  write(o, V{id}, \"=\", op, Ptr{immA}, Hex{immB}); break;\n            case Op::load128: write(o, V{id}, \"=\", op, Ptr{immA}, Hex{immB}); break;\n\n            case Op::gather8:  write(o, V{id}, \"=\", op, Ptr{immA}, Hex{immB}, V{x}); break;\n            case Op::gather16: write(o, V{id}, \"=\", op, Ptr{immA}, Hex{immB}, V{x}); break;\n            case Op::gather32: write(o, V{id}, \"=\", op, Ptr{immA}, Hex{immB}, V{x}); break;\n\n            case Op::uniform32: write(o, V{id}, \"=\", op, Ptr{immA}, Hex{immB}); break;\n            case Op::array32:   write(o, V{id}, \"=\", op, Ptr{immA}, Hex{immB}, Hex{immC}); break;\n\n            case Op::splat: write(o, V{id}, \"=\", op, Splat{immA}); break;\n\n            case Op:: add_f32: write(o, V{id}, \"=\", op, V{x}, V{y}      ); break;\n            case Op:: sub_f32: write(o, V{id}, \"=\", op, V{x}, V{y}      ); break;\n            case Op:: mul_f32: write(o, V{id}, \"=\", op, V{x}, V{y}      ); break;\n            case Op:: div_f32: write(o, V{id}, \"=\", op, V{x}, V{y}      ); break;\n            case Op:: min_f32: write(o, V{id}, \"=\", op, V{x}, V{y}      ); break;\n            case Op:: max_f32: write(o, V{id}, \"=\", op, V{x}, V{y}      ); break;\n            case Op:: fma_f32: write(o, V{id}, \"=\", op, V{x}, V{y}, V{z}); break;\n            case Op:: fms_f32: write(o, V{id}, \"=\", op, V{x}, V{y}, V{z}); break;\n            case Op::fnma_f32: write(o, V{id}, \"=\", op, V{x}, V{y}, V{z}); break;\n\n\n            case Op::sqrt_f32: write(o, V{id}, \"=\", op, V{x}); break;\n\n            case Op:: eq_f32: write(o, V{id}, \"=\", op, V{x}, V{y}); break;\n            case Op::neq_f32: write(o, V{id}, \"=\", op, V{x}, V{y}); break;\n            case Op:: gt_f32: write(o, V{id}, \"=\", op, V{x}, V{y}); break;\n            case Op::gte_f32: write(o, V{id}, \"=\", op, V{x}, V{y}); break;\n\n\n            case Op::add_i32: write(o, V{id}, \"=\", op, V{x}, V{y}); break;\n            case Op::sub_i32: write(o, V{id}, \"=\", op, V{x}, V{y}); break;\n            case Op::mul_i32: write(o, V{id}, \"=\", op, V{x}, V{y}); break;\n\n            case Op::shl_i32: write(o, V{id}, \"=\", op, V{x}, Shift{immA}); break;\n            case Op::shr_i32: write(o, V{id}, \"=\", op, V{x}, Shift{immA}); break;\n            case Op::sra_i32: write(o, V{id}, \"=\", op, V{x}, Shift{immA}); break;\n\n            case Op::eq_i32: write(o, V{id}, \"=\", op, V{x}, V{y}); break;\n            case Op::gt_i32: write(o, V{id}, \"=\", op, V{x}, V{y}); break;\n\n\n            case Op::bit_and  : write(o, V{id}, \"=\", op, V{x}, V{y}); break;\n            case Op::bit_or   : write(o, V{id}, \"=\", op, V{x}, V{y}); break;\n            case Op::bit_xor  : write(o, V{id}, \"=\", op, V{x}, V{y}); break;\n            case Op::bit_clear: write(o, V{id}, \"=\", op, V{x}, V{y}); break;\n\n            case Op::select: write(o, V{id}, \"=\", op, V{x}, V{y}, V{z}); break;\n\n            case Op::ceil:      write(o, V{id}, \"=\", op, V{x}); break;\n            case Op::floor:     write(o, V{id}, \"=\", op, V{x}); break;\n            case Op::to_f32:    write(o, V{id}, \"=\", op, V{x}); break;\n            case Op::to_fp16:   write(o, V{id}, \"=\", op, V{x}); break;\n            case Op::from_fp16: write(o, V{id}, \"=\", op, V{x}); break;\n            case Op::trunc:     write(o, V{id}, \"=\", op, V{x}); break;\n            case Op::round:     write(o, V{id}, \"=\", op, V{x}); break;\n        }\n\n        write(o, \"\\n\");\n    }\n\n    void Builder::dump(SkWStream* o) const {\n        SkDebugfStream debug;\n        if (!o) { o = &debug; }\n\n        std::vector<OptimizedInstruction> optimized = this->optimize();\n        o->writeDecAsText(optimized.size());\n        o->writeText(\" values (originally \");\n        o->writeDecAsText(fProgram.size());\n        o->writeText(\"):\\n\");\n        for (Val id = 0; id < (Val)optimized.size(); id++) {\n            const OptimizedInstruction& inst = optimized[id];\n            write(o, inst.can_hoist ? \"\u2191 \" : \"  \");\n            write_one_instruction(id, inst, o);\n        }\n    }\n\n    void Program::dump(SkWStream* o) const {\n        SkDebugfStream debug;\n        if (!o) { o = &debug; }\n\n        o->writeDecAsText(fImpl->regs);\n        o->writeText(\" registers, \");\n        o->writeDecAsText(fImpl->instructions.size());\n        o->writeText(\" instructions:\\n\");\n        for (Val i = 0; i < (Val)fImpl->instructions.size(); i++) {\n            if (i == fImpl->loop) { write(o, \"loop:\\n\"); }\n            o->writeDecAsText(i);\n            o->writeText(\"\\t\");\n            if (i >= fImpl->loop) { write(o, \"    \"); }\n            const InterpreterInstruction& inst = fImpl->instructions[i];\n            Op   op = inst.op;\n            Reg   d = inst.d,\n                  x = inst.x,\n                  y = inst.y,\n                  z = inst.z,\n                  w = inst.w;\n            int immA = inst.immA,\n                immB = inst.immB,\n                immC = inst.immC;\n            switch (op) {\n                case Op::assert_true: write(o, op, R{x}, R{y}); break;\n\n                case Op::trace_line: write(o, op, R{x}, Line{immA}); break;\n                case Op::trace_var: write(o, op, R{x}, VarSlot{immA}, \"=\", R{y}, VarType{immB});\n                                    break;\n                case Op::trace_call: write(o, op, R{x}, Line{immA}, CallType{immB}); break;\n\n                case Op::store8:   write(o, op, Ptr{immA}, R{x}                  ); break;\n                case Op::store16:  write(o, op, Ptr{immA}, R{x}                  ); break;\n                case Op::store32:  write(o, op, Ptr{immA}, R{x}                  ); break;\n                case Op::store64:  write(o, op, Ptr{immA}, R{x}, R{y}            ); break;\n                case Op::store128: write(o, op, Ptr{immA}, R{x}, R{y}, R{z}, R{w}); break;\n\n                case Op::index: write(o, R{d}, \"=\", op); break;\n\n                case Op::load8:   write(o, R{d}, \"=\", op, Ptr{immA}); break;\n                case Op::load16:  write(o, R{d}, \"=\", op, Ptr{immA}); break;\n                case Op::load32:  write(o, R{d}, \"=\", op, Ptr{immA}); break;\n                case Op::load64:  write(o, R{d}, \"=\", op, Ptr{immA}, Hex{immB}); break;\n                case Op::load128: write(o, R{d}, \"=\", op, Ptr{immA}, Hex{immB}); break;\n\n                case Op::gather8:  write(o, R{d}, \"=\", op, Ptr{immA}, Hex{immB}, R{x}); break;\n                case Op::gather16: write(o, R{d}, \"=\", op, Ptr{immA}, Hex{immB}, R{x}); break;\n                case Op::gather32: write(o, R{d}, \"=\", op, Ptr{immA}, Hex{immB}, R{x}); break;\n\n                case Op::uniform32: write(o, R{d}, \"=\", op, Ptr{immA}, Hex{immB}); break;\n                case Op::array32:   write(o, R{d}, \"=\", op, Ptr{immA}, Hex{immB}, Hex{immC}); break;\n\n                case Op::splat:     write(o, R{d}, \"=\", op, Splat{immA}); break;\n\n                case Op::add_f32: write(o, R{d}, \"=\", op, R{x}, R{y}      ); break;\n                case Op::sub_f32: write(o, R{d}, \"=\", op, R{x}, R{y}      ); break;\n                case Op::mul_f32: write(o, R{d}, \"=\", op, R{x}, R{y}      ); break;\n                case Op::div_f32: write(o, R{d}, \"=\", op, R{x}, R{y}      ); break;\n                case Op::min_f32: write(o, R{d}, \"=\", op, R{x}, R{y}      ); break;\n                case Op::max_f32: write(o, R{d}, \"=\", op, R{x}, R{y}      ); break;\n                case Op::fma_f32: write(o, R{d}, \"=\", op, R{x}, R{y}, R{z}); break;\n                case Op::fms_f32: write(o, R{d}, \"=\", op, R{x}, R{y}, R{z}); break;\n                case Op::fnma_f32: write(o, R{d}, \"=\", op, R{x}, R{y}, R{z}); break;\n\n                case Op::sqrt_f32: write(o, R{d}, \"=\", op, R{x}); break;\n\n                case Op:: eq_f32: write(o, R{d}, \"=\", op, R{x}, R{y}); break;\n                case Op::neq_f32: write(o, R{d}, \"=\", op, R{x}, R{y}); break;\n                case Op:: gt_f32: write(o, R{d}, \"=\", op, R{x}, R{y}); break;\n                case Op::gte_f32: write(o, R{d}, \"=\", op, R{x}, R{y}); break;\n\n\n                case Op::add_i32: write(o, R{d}, \"=\", op, R{x}, R{y}); break;\n                case Op::sub_i32: write(o, R{d}, \"=\", op, R{x}, R{y}); break;\n                case Op::mul_i32: write(o, R{d}, \"=\", op, R{x}, R{y}); break;\n\n                case Op::shl_i32: write(o, R{d}, \"=\", op, R{x}, Shift{immA}); break;\n                case Op::shr_i32: write(o, R{d}, \"=\", op, R{x}, Shift{immA}); break;\n                case Op::sra_i32: write(o, R{d}, \"=\", op, R{x}, Shift{immA}); break;\n\n                case Op::eq_i32: write(o, R{d}, \"=\", op, R{x}, R{y}); break;\n                case Op::gt_i32: write(o, R{d}, \"=\", op, R{x}, R{y}); break;\n\n                case Op::bit_and  : write(o, R{d}, \"=\", op, R{x}, R{y}); break;\n                case Op::bit_or   : write(o, R{d}, \"=\", op, R{x}, R{y}); break;\n                case Op::bit_xor  : write(o, R{d}, \"=\", op, R{x}, R{y}); break;\n                case Op::bit_clear: write(o, R{d}, \"=\", op, R{x}, R{y}); break;\n\n                case Op::select: write(o, R{d}, \"=\", op, R{x}, R{y}, R{z}); break;\n\n                case Op::ceil:      write(o, R{d}, \"=\", op, R{x}); break;\n                case Op::floor:     write(o, R{d}, \"=\", op, R{x}); break;\n                case Op::to_f32:    write(o, R{d}, \"=\", op, R{x}); break;\n                case Op::to_fp16:   write(o, R{d}, \"=\", op, R{x}); break;\n                case Op::from_fp16: write(o, R{d}, \"=\", op, R{x}); break;\n                case Op::trunc:     write(o, R{d}, \"=\", op, R{x}); break;\n                case Op::round:     write(o, R{d}, \"=\", op, R{x}); break;\n            }\n            write(o, \"\\n\");\n        }\n    }\n\n    std::vector<Instruction> eliminate_dead_code(std::vector<Instruction> program) {\n        \/\/ Determine which Instructions are live by working back from side effects.\n        std::vector<bool> live(program.size(), false);\n        for (Val id = program.size(); id--;) {\n            if (live[id] || has_side_effect(program[id].op)) {\n                live[id] = true;\n                const Instruction& inst = program[id];\n                for (Val arg : {inst.x, inst.y, inst.z, inst.w}) {\n                    if (arg != NA) { live[arg] = true; }\n                }\n            }\n        }\n\n        \/\/ After removing non-live instructions, we can be left with redundant back-to-back\n        \/\/ trace_line instructions. (e.g. one line could have multiple statements on it.)\n        \/\/ Eliminate any duplicate ops.\n        int lastId = -1;\n        for (Val id = 0; id < (Val)program.size(); id++) {\n            if (!live[id]) {\n                continue;\n            }\n            const Instruction& inst = program[id];\n            if (inst.op != Op::trace_line) {\n                lastId = -1;\n                continue;\n            }\n            if (lastId >= 0) {\n                const Instruction& last = program[lastId];\n                if (inst.immA == last.immA && inst.x == last.x) {\n                    \/\/ Found two matching trace_lines in a row. Mark the first one as dead.\n                    live[lastId] = false;\n                }\n            }\n            lastId = id;\n        }\n\n        \/\/ Rewrite the program with only live Instructions:\n        \/\/   - remap IDs in live Instructions to what they'll be once dead Instructions are removed;\n        \/\/   - then actually remove the dead Instructions.\n        std::vector<Val> new_id(program.size(), NA);\n        for (Val id = 0, next = 0; id < (Val)program.size(); id++) {\n            if (live[id]) {\n                Instruction& inst = program[id];\n                for (Val* arg : {&inst.x, &inst.y, &inst.z, &inst.w}) {\n                    if (*arg != NA) {\n                        *arg = new_id[*arg];\n                        SkASSERT(*arg != NA);\n                    }\n                }\n                new_id[id] = next++;\n            }\n        }\n\n        \/\/ Eliminate any non-live ops.\n        auto it = std::remove_if(program.begin(), program.end(), [&](const Instruction& inst) {\n            Val id = (Val)(&inst - program.data());\n            return !live[id];\n        });\n        program.erase(it, program.end());\n\n        return program;\n    }\n\n    std::vector<OptimizedInstruction> finalize(const std::vector<Instruction> program) {\n        std::vector<OptimizedInstruction> optimized(program.size());\n        for (Val id = 0; id < (Val)program.size(); id++) {\n            Instruction inst = program[id];\n            optimized[id] = {inst.op, inst.x,inst.y,inst.z,inst.w,\n                             inst.immA,inst.immB,inst.immC,\n                             \/*death=*\/id, \/*can_hoist=*\/true};\n        }\n\n        \/\/ Each Instruction's inputs need to live at least until that Instruction issues.\n        for (Val id = 0; id < (Val)optimized.size(); id++) {\n            OptimizedInstruction& inst = optimized[id];\n            for (Val arg : {inst.x, inst.y, inst.z, inst.w}) {\n                \/\/ (We're walking in order, so this is the same as max()ing with the existing Val.)\n                if (arg != NA) { optimized[arg].death = id; }\n            }\n        }\n\n        \/\/ Mark which values don't depend on the loop and can be hoisted.\n        for (OptimizedInstruction& inst : optimized) {\n            \/\/ Varying loads (and gathers) and stores cannot be hoisted out of the loop.\n            if (is_always_varying(inst.op) || is_trace(inst.op)) {\n                inst.can_hoist = false;\n            }\n\n            \/\/ If any of an instruction's inputs can't be hoisted, it can't be hoisted itself.\n            if (inst.can_hoist) {\n                for (Val arg : {inst.x, inst.y, inst.z, inst.w}) {\n                    if (arg != NA) { inst.can_hoist &= optimized[arg].can_hoist; }\n                }\n            }\n        }\n\n        \/\/ Extend the lifetime of any hoisted value that's used in the loop to infinity.\n        for (OptimizedInstruction& inst : optimized) {\n            if (!inst.can_hoist \/*i.e. we're in the loop, so the arguments are used-in-loop*\/) {\n                for (Val arg : {inst.x, inst.y, inst.z, inst.w}) {\n                    if (arg != NA && optimized[arg].can_hoist) {\n                        optimized[arg].death = (Val)program.size();\n                    }\n                }\n            }\n        }\n\n        return optimized;\n    }\n\n    std::vector<OptimizedInstruction> Builder::optimize() const {\n        std::vector<Instruction> program = this->program();\n        program = eliminate_dead_code(std::move(program));\n        return    finalize           (std::move(program));\n    }\n\n    Program Builder::done(const char* debug_name, bool allow_jit) const {\n        char buf[64] = \"skvm-jit-\";\n        if (!debug_name) {\n            *SkStrAppendU32(buf+9, this->hash()) = '\\0';\n            debug_name = buf;\n        }\n\n        return {this->optimize(), fStrides, debug_name, allow_jit};\n    }\n\n    uint64_t Builder::hash() const {\n        uint32_t lo = SkOpts::hash(fProgram.data(), fProgram.size() * sizeof(Instruction), 0),\n                 hi = SkOpts::hash(fProgram.data(), fProgram.size() * sizeof(Instruction), 1);\n        return (uint64_t)lo | (uint64_t)hi << 32;\n    }\n\n    bool operator!=(Ptr a, Ptr b) { return a.ix != b.ix; }\n\n    bool operator==(const Instruction& a, const Instruction& b) {\n        return a.op   == b.op\n            && a.x    == b.x\n            && a.y    == b.y\n            && a.z    == b.z\n            && a.w    == b.w\n            && a.immA == b.immA\n            && a.immB == b.immB\n            && a.immC == b.immC;\n    }\n\n    uint32_t InstructionHash::operator()(const Instruction& inst, uint32_t seed) const {\n        return SkOpts::hash(&inst, sizeof(inst), seed);\n    }\n\n\n    \/\/ Most instructions produce a value and return it by ID,\n    \/\/ the value-producing instruction's own index in the program vector.\n    Val Builder::push(Instruction inst) {\n        \/\/ Basic common subexpression elimination:\n        \/\/ if we've already seen this exact Instruction, use it instead of creating a new one.\n        \/\/\n        \/\/ But we never dedup loads or stores: an intervening store could change that memory.\n        \/\/ Uniforms and gathers touch only uniform memory, so they're fine to dedup,\n        \/\/ and index is varying but doesn't touch memory, so it's fine to dedup too.\n        if (!touches_varying_memory(inst.op) && !is_trace(inst.op)) {\n            if (Val* id = fIndex.find(inst)) {\n                return *id;\n            }\n        }\n        Val id = static_cast<Val>(fProgram.size());\n        fProgram.push_back(inst);\n        fIndex.set(inst, id);\n        return id;\n    }\n\n    Ptr Builder::arg(int stride) {\n        int ix = (int)fStrides.size();\n        fStrides.push_back(stride);\n        return {ix};\n    }\n\n    void Builder::assert_true(I32 cond, I32 debug) {\n    #ifdef SK_DEBUG\n        int imm;\n        if (this->allImm(cond.id,&imm)) { SkASSERT(imm); return; }\n        (void)push(Op::assert_true, cond.id, debug.id);\n    #endif\n    }\n\n    void Builder::trace_line(I32 mask, int line) {\n        if (this->isImm(mask.id, 0)) { return; }\n        (void)push(Op::trace_line, mask.id,NA,NA,NA, line);\n    }\n    void Builder::trace_var(I32 mask, int slot, I32 val) {\n        if (this->isImm(mask.id, 0)) { return; }\n        (void)push(Op::trace_var, mask.id,val.id,NA,NA, slot, kVarTypeInt.bits);\n    }\n    void Builder::trace_var(I32 mask, int slot, F32 val) {\n        if (this->isImm(mask.id, 0)) { return; }\n        (void)push(Op::trace_var, mask.id,val.id,NA,NA, slot, kVarTypeFloat.bits);\n    }\n    void Builder::trace_var(I32 mask, int slot, bool b) {\n        if (this->isImm(mask.id, 0)) { return; }\n        I32 val = b ? this->splat(1) : this->splat(0);\n        (void)push(Op::trace_var, mask.id,val.id,NA,NA, slot, kVarTypeBool.bits);\n    }\n    void Builder::trace_call_enter(I32 mask, int line) {\n        if (this->isImm(mask.id, 0)) { return; }\n        (void)push(Op::trace_call, mask.id,NA,NA,NA, line, kCallTypeEnter.bits);\n    }\n    void Builder::trace_call_exit(I32 mask, int line) {\n        if (this->isImm(mask.id, 0)) { return; }\n        (void)push(Op::trace_call, mask.id,NA,NA,NA, line, kCallTypeExit.bits);\n    }\n\n    void Builder::store8 (Ptr ptr, I32 val) { (void)push(Op::store8 , val.id,NA,NA,NA, ptr.ix); }\n    void Builder::store16(Ptr ptr, I32 val) { (void)push(Op::store16, val.id,NA,NA,NA, ptr.ix); }\n    void Builder::store32(Ptr ptr, I32 val) { (void)push(Op::store32, val.id,NA,NA,NA, ptr.ix); }\n    void Builder::store64(Ptr ptr, I32 lo, I32 hi) {\n        (void)push(Op::store64, lo.id,hi.id,NA,NA, ptr.ix);\n    }\n    void Builder::store128(Ptr ptr, I32 x, I32 y, I32 z, I32 w) {\n        (void)push(Op::store128, x.id,y.id,z.id,w.id, ptr.ix);\n    }\n\n    I32 Builder::index() { return {this, push(Op::index)}; }\n\n    I32 Builder::load8 (Ptr ptr) { return {this, push(Op::load8 , NA,NA,NA,NA, ptr.ix) }; }\n    I32 Builder::load16(Ptr ptr) { return {this, push(Op::load16, NA,NA,NA,NA, ptr.ix) }; }\n    I32 Builder::load32(Ptr ptr) { return {this, push(Op::load32, NA,NA,NA,NA, ptr.ix) }; }\n    I32 Builder::load64(Ptr ptr, int lane) {\n        return {this, push(Op::load64 , NA,NA,NA,NA, ptr.ix,lane) };\n    }\n    I32 Builder::load128(Ptr ptr, int lane) {\n        return {this, push(Op::load128, NA,NA,NA,NA, ptr.ix,lane) };\n    }\n\n    I32 Builder::gather8 (UPtr ptr, int offset, I32 index) {\n        return {this, push(Op::gather8 , index.id,NA,NA,NA, ptr.ix,offset)};\n    }\n    I32 Builder::gather16(UPtr ptr, int offset, I32 index) {\n        return {this, push(Op::gather16, index.id,NA,NA,NA, ptr.ix,offset)};\n    }\n    I32 Builder::gather32(UPtr ptr, int offset, I32 index) {\n        return {this, push(Op::gather32, index.id,NA,NA,NA, ptr.ix,offset)};\n    }\n\n    I32 Builder::uniform32(UPtr ptr, int offset) {\n        return {this, push(Op::uniform32, NA,NA,NA,NA, ptr.ix, offset)};\n    }\n\n    \/\/ Note: this converts the array index into a byte offset for the op.\n    I32 Builder::array32  (UPtr ptr, int offset, int index) {\n        return {this, push(Op::array32, NA,NA,NA,NA, ptr.ix, offset, index * sizeof(int))};\n    }\n\n    I32 Builder::splat(int n) { return {this, push(Op::splat, NA,NA,NA,NA, n) }; }\n\n    \/\/ Be careful peepholing float math!  Transformations you might expect to\n    \/\/ be legal can fail in the face of NaN\/Inf, e.g. 0*x is not always 0.\n    \/\/ Float peepholes must pass this equivalence test for all ~4B floats:\n    \/\/\n    \/\/     bool equiv(float x, float y) { return (x == y) || (isnanf(x) && isnanf(y)); }\n    \/\/\n    \/\/     unsigned bits = 0;\n    \/\/     do {\n    \/\/        float f;\n    \/\/        memcpy(&f, &bits, 4);\n    \/\/        if (!equiv(f, ...)) {\n    \/\/           abort();\n    \/\/        }\n    \/\/     } while (++bits != 0);\n\n    F32 Builder::add(F32 x, F32 y) {\n        if (float X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X+Y); }\n        if (this->isImm(y.id, 0.0f)) { return x; }   \/\/ x+0 == x\n        if (this->isImm(x.id, 0.0f)) { return y; }   \/\/ 0+y == y\n\n        if (fFeatures.fma) {\n            if (fProgram[x.id].op == Op::mul_f32) {\n                return {this, this->push(Op::fma_f32, fProgram[x.id].x, fProgram[x.id].y, y.id)};\n            }\n            if (fProgram[y.id].op == Op::mul_f32) {\n                return {this, this->push(Op::fma_f32, fProgram[y.id].x, fProgram[y.id].y, x.id)};\n            }\n        }\n        return {this, this->push(Op::add_f32, x.id, y.id)};\n    }\n\n    F32 Builder::sub(F32 x, F32 y) {\n        if (float X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X-Y); }\n        if (this->isImm(y.id, 0.0f)) { return x; }   \/\/ x-0 == x\n        if (fFeatures.fma) {\n            if (fProgram[x.id].op == Op::mul_f32) {\n                return {this, this->push(Op::fms_f32, fProgram[x.id].x, fProgram[x.id].y, y.id)};\n            }\n            if (fProgram[y.id].op == Op::mul_f32) {\n                return {this, this->push(Op::fnma_f32, fProgram[y.id].x, fProgram[y.id].y, x.id)};\n            }\n        }\n        return {this, this->push(Op::sub_f32, x.id, y.id)};\n    }\n\n    F32 Builder::mul(F32 x, F32 y) {\n        if (float X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X*Y); }\n        if (this->isImm(y.id, 1.0f)) { return x; }  \/\/ x*1 == x\n        if (this->isImm(x.id, 1.0f)) { return y; }  \/\/ 1*y == y\n        return {this, this->push(Op::mul_f32, x.id, y.id)};\n    }\n\n    F32 Builder::fast_mul(F32 x, F32 y) {\n        if (this->isImm(x.id, 0.0f) || this->isImm(y.id, 0.0f)) { return splat(0.0f); }\n        return mul(x,y);\n    }\n\n    F32 Builder::div(F32 x, F32 y) {\n        if (float X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(sk_ieee_float_divide(X,Y)); }\n        if (this->isImm(y.id, 1.0f)) { return x; }  \/\/ x\/1 == x\n        return {this, this->push(Op::div_f32, x.id, y.id)};\n    }\n\n    F32 Builder::sqrt(F32 x) {\n        if (float X; this->allImm(x.id,&X)) { return splat(std::sqrt(X)); }\n        return {this, this->push(Op::sqrt_f32, x.id)};\n    }\n\n    \/\/ See http:\/\/www.machinedlearnings.com\/2011\/06\/fast-approximate-logarithm-exponential.html.\n    F32 Builder::approx_log2(F32 x) {\n        \/\/ e - 127 is a fair approximation of log2(x) in its own right...\n        F32 e = mul(to_F32(pun_to_I32(x)), splat(1.0f \/ (1<<23)));\n\n        \/\/ ... but using the mantissa to refine its error is _much_ better.\n        F32 m = pun_to_F32(bit_or(bit_and(pun_to_I32(x), 0x007fffff),\n                                0x3f000000));\n        F32 approx = sub(e,        124.225514990f);\n            approx = sub(approx, mul(1.498030302f, m));\n            approx = sub(approx, div(1.725879990f, add(0.3520887068f, m)));\n\n        return approx;\n    }\n\n    F32 Builder::approx_pow2(F32 x) {\n        F32 f = fract(x);\n        F32 approx = add(x,         121.274057500f);\n            approx = sub(approx, mul( 1.490129070f, f));\n            approx = add(approx, div(27.728023300f, sub(4.84252568f, f)));\n\n        return pun_to_F32(round(mul(1.0f * (1<<23), approx)));\n    }\n\n    F32 Builder::approx_powf(F32 x, F32 y) {\n        \/\/ TODO: assert this instead?  Sometimes x is very slightly negative.  See skia:10210.\n        x = max(0.0f, x);\n\n        auto is_x = bit_or(eq(x, 0.0f),\n                           eq(x, 1.0f));\n        return select(is_x, x, approx_pow2(mul(approx_log2(x), y)));\n    }\n\n    \/\/ Bhaskara I's sine approximation\n    \/\/ 16x(pi - x) \/ (5*pi^2 - 4x(pi - x)\n    \/\/ ... divide by 4\n    \/\/ 4x(pi - x) \/ 5*pi^2\/4 - x(pi - x)\n    \/\/\n    \/\/ This is a good approximation only for 0 <= x <= pi, so we use symmetries to get\n    \/\/ radians into that range first.\n    \/\/\n    F32 Builder::approx_sin(F32 radians) {\n        constexpr float Pi = SK_ScalarPI;\n        \/\/ x = radians mod 2pi\n        F32 x = fract(radians * (0.5f\/Pi)) * (2*Pi);\n        I32 neg = x > Pi;   \/\/ are we pi < x < 2pi --> need to negate result\n        x = select(neg, x - Pi, x);\n\n        F32 pair = x * (Pi - x);\n        x = 4.0f * pair \/ ((5*Pi*Pi\/4) - pair);\n        x = select(neg, -x, x);\n        return x;\n    }\n\n    \/*  \"GENERATING ACCURATE VALUES FOR THE TANGENT FUNCTION\"\n         https:\/\/mae.ufl.edu\/~uhk\/ACCURATE-TANGENT.pdf\n\n        approx = x + (1\/3)x^3 + (2\/15)x^5 + (17\/315)x^7 + (62\/2835)x^9\n\n        Some simplifications:\n        1. tan(x) is periodic, -PI\/2 < x < PI\/2\n        2. tan(x) is odd, so tan(-x) = -tan(x)\n        3. Our polynomial approximation is best near zero, so we use the following identity\n                        tan(x) + tan(y)\n           tan(x + y) = -----------------\n                       1 - tan(x)*tan(y)\n           tan(PI\/4) = 1\n\n           So for x > PI\/8, we do the following refactor:\n           x' = x - PI\/4\n\n                    1 + tan(x')\n           tan(x) = ------------\n                    1 - tan(x')\n     *\/\n    F32 Builder::approx_tan(F32 x) {\n        constexpr float Pi = SK_ScalarPI;\n        \/\/ periodic between -pi\/2 ... pi\/2\n        \/\/ shift to 0...Pi, scale 1\/Pi to get into 0...1, then fract, scale-up, shift-back\n        x = fract((1\/Pi)*x + 0.5f) * Pi - (Pi\/2);\n\n        I32 neg = (x < 0.0f);\n        x = select(neg, -x, x);\n\n        \/\/ minimize total error by shifting if x > pi\/8\n        I32 use_quotient = (x > (Pi\/8));\n        x = select(use_quotient, x - (Pi\/4), x);\n\n        \/\/ 9th order poly = 4th order(x^2) * x\n        x = poly(x*x, 62\/2835.0f, 17\/315.0f, 2\/15.0f, 1\/3.0f, 1.0f) * x;\n        x = select(use_quotient, (1+x)\/(1-x), x);\n        x = select(neg, -x, x);\n        return x;\n    }\n\n     \/\/ http:\/\/mathforum.org\/library\/drmath\/view\/54137.html\n     \/\/ referencing Handbook of Mathematical Functions,\n     \/\/             by Milton Abramowitz and Irene Stegun\n     F32 Builder::approx_asin(F32 x) {\n         I32 neg = (x < 0.0f);\n         x = select(neg, -x, x);\n         x = SK_ScalarPI\/2 - sqrt(1-x) * poly(x, -0.0187293f, 0.0742610f, -0.2121144f, 1.5707288f);\n         x = select(neg, -x, x);\n         return x;\n     }\n\n    \/*  Use 4th order polynomial approximation from https:\/\/arachnoid.com\/polysolve\/\n     *      with 129 values of x,atan(x) for x:[0...1]\n     *  This only works for 0 <= x <= 1\n     *\/\n    static F32 approx_atan_unit(F32 x) {\n        \/\/ for now we might be given NaN... let that through\n        x->assert_true((x != x) | ((x >= 0) & (x <= 1)));\n        return poly(x, 0.14130025741326729f,\n                      -0.34312835980675116f,\n                      -0.016172900528248768f,\n                       1.0037696976200385f,\n                      -0.00014758242182738969f);\n    }\n\n    \/*  Use identity atan(x) = pi\/2 - atan(1\/x) for x > 1\n     *\/\n    F32 Builder::approx_atan(F32 x) {\n        I32 neg = (x < 0.0f);\n        x = select(neg, -x, x);\n        I32 flip = (x > 1.0f);\n        x = select(flip, 1\/x, x);\n        x = approx_atan_unit(x);\n        x = select(flip, SK_ScalarPI\/2 - x, x);\n        x = select(neg, -x, x);\n        return x;\n    }\n\n    \/*  Use identity atan(x) = pi\/2 - atan(1\/x) for x > 1\n     *  By swapping y,x to ensure the ratio is <= 1, we can safely call atan_unit()\n     *  which avoids a 2nd divide instruction if we had instead called atan().\n     *\/\n    F32 Builder::approx_atan2(F32 y0, F32 x0) {\n\n        I32 flip = (abs(y0) > abs(x0));\n        F32 y = select(flip, x0, y0);\n        F32 x = select(flip, y0, x0);\n        F32 arg = y\/x;\n\n        I32 neg = (arg < 0.0f);\n        arg = select(neg, -arg, arg);\n\n        F32 r = approx_atan_unit(arg);\n        r = select(flip, SK_ScalarPI\/2 - r, r);\n        r = select(neg, -r, r);\n\n        \/\/ handle quadrant distinctions\n        r = select((y0 >= 0) & (x0  < 0), r + SK_ScalarPI, r);\n        r = select((y0  < 0) & (x0 <= 0), r - SK_ScalarPI, r);\n        \/\/ Note: we don't try to handle 0,0 or infinities (yet)\n        return r;\n    }\n\n    F32 Builder::min(F32 x, F32 y) {\n        if (float X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(std::min(X,Y)); }\n        return {this, this->push(Op::min_f32, x.id, y.id)};\n    }\n    F32 Builder::max(F32 x, F32 y) {\n        if (float X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(std::max(X,Y)); }\n        return {this, this->push(Op::max_f32, x.id, y.id)};\n    }\n\n    SK_ATTRIBUTE(no_sanitize(\"signed-integer-overflow\"))\n    I32 Builder::add(I32 x, I32 y) {\n        if (int X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X+Y); }\n        if (this->isImm(x.id, 0)) { return y; }\n        if (this->isImm(y.id, 0)) { return x; }\n        return {this, this->push(Op::add_i32, x.id, y.id)};\n    }\n    SK_ATTRIBUTE(no_sanitize(\"signed-integer-overflow\"))\n    I32 Builder::sub(I32 x, I32 y) {\n        if (int X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X-Y); }\n        if (this->isImm(y.id, 0)) { return x; }\n        return {this, this->push(Op::sub_i32, x.id, y.id)};\n    }\n    SK_ATTRIBUTE(no_sanitize(\"signed-integer-overflow\"))\n    I32 Builder::mul(I32 x, I32 y) {\n        if (int X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X*Y); }\n        if (this->isImm(x.id, 0)) { return splat(0); }\n        if (this->isImm(y.id, 0)) { return splat(0); }\n        if (this->isImm(x.id, 1)) { return y; }\n        if (this->isImm(y.id, 1)) { return x; }\n        return {this, this->push(Op::mul_i32, x.id, y.id)};\n    }\n\n    SK_ATTRIBUTE(no_sanitize(\"shift\"))\n    I32 Builder::shl(I32 x, int bits) {\n        if (bits == 0) { return x; }\n        if (int X; this->allImm(x.id,&X)) { return splat(X << bits); }\n        return {this, this->push(Op::shl_i32, x.id,NA,NA,NA, bits)};\n    }\n    I32 Builder::shr(I32 x, int bits) {\n        if (bits == 0) { return x; }\n        if (int X; this->allImm(x.id,&X)) { return splat(unsigned(X) >> bits); }\n        return {this, this->push(Op::shr_i32, x.id,NA,NA,NA, bits)};\n    }\n    I32 Builder::sra(I32 x, int bits) {\n        if (bits == 0) { return x; }\n        if (int X; this->allImm(x.id,&X)) { return splat(X >> bits); }\n        return {this, this->push(Op::sra_i32, x.id,NA,NA,NA, bits)};\n    }\n\n    I32 Builder:: eq(F32 x, F32 y) {\n        if (float X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X==Y ? ~0 : 0); }\n        return {this, this->push(Op::eq_f32, x.id, y.id)};\n    }\n    I32 Builder::neq(F32 x, F32 y) {\n        if (float X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X!=Y ? ~0 : 0); }\n        return {this, this->push(Op::neq_f32, x.id, y.id)};\n    }\n    I32 Builder::lt(F32 x, F32 y) {\n        if (float X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(Y> X ? ~0 : 0); }\n        return {this, this->push(Op::gt_f32, y.id, x.id)};\n    }\n    I32 Builder::lte(F32 x, F32 y) {\n        if (float X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(Y>=X ? ~0 : 0); }\n        return {this, this->push(Op::gte_f32, y.id, x.id)};\n    }\n    I32 Builder::gt(F32 x, F32 y) {\n        if (float X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X> Y ? ~0 : 0); }\n        return {this, this->push(Op::gt_f32, x.id, y.id)};\n    }\n    I32 Builder::gte(F32 x, F32 y) {\n        if (float X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X>=Y ? ~0 : 0); }\n        return {this, this->push(Op::gte_f32, x.id, y.id)};\n    }\n\n    I32 Builder:: eq(I32 x, I32 y) {\n        if (x.id == y.id) { return splat(~0); }\n        if (int X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X==Y ? ~0 : 0); }\n        return {this, this->push(Op:: eq_i32, x.id, y.id)};\n    }\n    I32 Builder::neq(I32 x, I32 y) {\n        if (int X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X!=Y ? ~0 : 0); }\n        return ~(x == y);\n    }\n    I32 Builder:: gt(I32 x, I32 y) {\n        if (int X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X> Y ? ~0 : 0); }\n        return {this, this->push(Op:: gt_i32, x.id, y.id)};\n    }\n    I32 Builder::gte(I32 x, I32 y) {\n        if (x.id == y.id) { return splat(~0); }\n        if (int X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X>=Y ? ~0 : 0); }\n        return ~(x < y);\n    }\n    I32 Builder:: lt(I32 x, I32 y) { return y>x; }\n    I32 Builder::lte(I32 x, I32 y) { return y>=x; }\n\n    I32 Builder::bit_and(I32 x, I32 y) {\n        if (x.id == y.id) { return x; }\n        if (int X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X&Y); }\n        if (this->isImm(y.id, 0)) { return splat(0); }   \/\/ (x & false) == false\n        if (this->isImm(x.id, 0)) { return splat(0); }   \/\/ (false & y) == false\n        if (this->isImm(y.id,~0)) { return x; }          \/\/ (x & true) == x\n        if (this->isImm(x.id,~0)) { return y; }          \/\/ (true & y) == y\n        return {this, this->push(Op::bit_and, x.id, y.id)};\n    }\n    I32 Builder::bit_or(I32 x, I32 y) {\n        if (x.id == y.id) { return x; }\n        if (int X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X|Y); }\n        if (this->isImm(y.id, 0)) { return x; }           \/\/ (x | false) == x\n        if (this->isImm(x.id, 0)) { return y; }           \/\/ (false | y) == y\n        if (this->isImm(y.id,~0)) { return splat(~0); }   \/\/ (x | true) == true\n        if (this->isImm(x.id,~0)) { return splat(~0); }   \/\/ (true | y) == true\n        return {this, this->push(Op::bit_or, x.id, y.id)};\n    }\n    I32 Builder::bit_xor(I32 x, I32 y) {\n        if (x.id == y.id) { return splat(0); }\n        if (int X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X^Y); }\n        if (this->isImm(y.id, 0)) { return x; }   \/\/ (x ^ false) == x\n        if (this->isImm(x.id, 0)) { return y; }   \/\/ (false ^ y) == y\n        return {this, this->push(Op::bit_xor, x.id, y.id)};\n    }\n\n    I32 Builder::bit_clear(I32 x, I32 y) {\n        if (x.id == y.id) { return splat(0); }\n        if (int X,Y; this->allImm(x.id,&X, y.id,&Y)) { return splat(X&~Y); }\n        if (this->isImm(y.id, 0)) { return x; }          \/\/ (x & ~false) == x\n        if (this->isImm(y.id,~0)) { return splat(0); }   \/\/ (x & ~true) == false\n        if (this->isImm(x.id, 0)) { return splat(0); }   \/\/ (false & ~y) == false\n        return {this, this->push(Op::bit_clear, x.id, y.id)};\n    }\n\n    I32 Builder::select(I32 x, I32 y, I32 z) {\n        if (y.id == z.id) { return y; }\n        if (int X,Y,Z; this->allImm(x.id,&X, y.id,&Y, z.id,&Z)) { return splat(X?Y:Z); }\n        if (this->isImm(x.id,~0)) { return y; }               \/\/ true  ? y : z == y\n        if (this->isImm(x.id, 0)) { return z; }               \/\/ false ? y : z == z\n        if (this->isImm(y.id, 0)) { return bit_clear(z,x); }  \/\/     x ? 0 : z == ~x&z\n        if (this->isImm(z.id, 0)) { return bit_and  (y,x); }  \/\/     x ? y : 0 ==  x&y\n        return {this, this->push(Op::select, x.id, y.id, z.id)};\n    }\n\n    I32 Builder::extract(I32 x, int bits, I32 z) {\n        if (unsigned Z; this->allImm(z.id,&Z) && (~0u>>bits) == Z) { return shr(x, bits); }\n        return bit_and(z, shr(x, bits));\n    }\n\n    I32 Builder::pack(I32 x, I32 y, int bits) {\n        return bit_or(x, shl(y, bits));\n    }\n\n    F32 Builder::ceil(F32 x) {\n        if (float X; this->allImm(x.id,&X)) { return splat(ceilf(X)); }\n        return {this, this->push(Op::ceil, x.id)};\n    }\n    F32 Builder::floor(F32 x) {\n        if (float X; this->allImm(x.id,&X)) { return splat(floorf(X)); }\n        return {this, this->push(Op::floor, x.id)};\n    }\n    F32 Builder::to_F32(I32 x) {\n        if (int X; this->allImm(x.id,&X)) { return splat((float)X); }\n        return {this, this->push(Op::to_f32, x.id)};\n    }\n    I32 Builder::trunc(F32 x) {\n        if (float X; this->allImm(x.id,&X)) { return splat((int)X); }\n        return {this, this->push(Op::trunc, x.id)};\n    }\n    I32 Builder::round(F32 x) {\n        if (float X; this->allImm(x.id,&X)) { return splat((int)lrintf(X)); }\n        return {this, this->push(Op::round, x.id)};\n    }\n\n    I32 Builder::to_fp16(F32 x) {\n        if (float X; this->allImm(x.id,&X)) { return splat((int)SkFloatToHalf(X)); }\n        return {this, this->push(Op::to_fp16, x.id)};\n    }\n    F32 Builder::from_fp16(I32 x) {\n        if (int X; this->allImm(x.id,&X)) { return splat(SkHalfToFloat(X)); }\n        return {this, this->push(Op::from_fp16, x.id)};\n    }\n\n    F32 Builder::from_unorm(int bits, I32 x) {\n        F32 limit = splat(1 \/ ((1<<bits)-1.0f));\n        return mul(to_F32(x), limit);\n    }\n    I32 Builder::to_unorm(int bits, F32 x) {\n        F32 limit = splat((1<<bits)-1.0f);\n        return round(mul(x, limit));\n    }\n\n    PixelFormat SkColorType_to_PixelFormat(SkColorType ct) {\n        auto UNORM = PixelFormat::UNORM,\n             SRGB  = PixelFormat::SRGB,\n             FLOAT = PixelFormat::FLOAT;\n        switch (ct) {\n            case kUnknown_SkColorType: break;\n\n            case kRGBA_F32_SkColorType: return {FLOAT,32,32,32,32, 0,32,64,96};\n\n            case kRGBA_F16Norm_SkColorType:       return {FLOAT,16,16,16,16, 0,16,32,48};\n            case kRGBA_F16_SkColorType:           return {FLOAT,16,16,16,16, 0,16,32,48};\n            case kR16G16B16A16_unorm_SkColorType: return {UNORM,16,16,16,16, 0,16,32,48};\n\n            case kA16_float_SkColorType:    return {FLOAT,  0, 0,0,16, 0, 0,0,0};\n            case kR16G16_float_SkColorType: return {FLOAT, 16,16,0, 0, 0,16,0,0};\n\n            case kAlpha_8_SkColorType: return {UNORM, 0,0,0,8, 0,0,0,0};\n            case kGray_8_SkColorType:  return {UNORM, 8,8,8,0, 0,0,0,0};  \/\/ Subtle.\n\n            case kRGB_565_SkColorType:   return {UNORM, 5,6,5,0, 11,5,0,0};  \/\/ (BGR)\n            case kARGB_4444_SkColorType: return {UNORM, 4,4,4,4, 12,8,4,0};  \/\/ (ABGR)\n\n            case kRGBA_8888_SkColorType:  return {UNORM, 8,8,8,8,  0,8,16,24};\n            case kRGB_888x_SkColorType:   return {UNORM, 8,8,8,0,  0,8,16,32};  \/\/ 32-bit\n            case kBGRA_8888_SkColorType:  return {UNORM, 8,8,8,8, 16,8, 0,24};\n            case kSRGBA_8888_SkColorType: return { SRGB, 8,8,8,8,  0,8,16,24};\n\n            case kRGBA_1010102_SkColorType: return {UNORM, 10,10,10,2,  0,10,20,30};\n            case kBGRA_1010102_SkColorType: return {UNORM, 10,10,10,2, 20,10, 0,30};\n            case kRGB_101010x_SkColorType:  return {UNORM, 10,10,10,0,  0,10,20, 0};\n            case kBGR_101010x_SkColorType:  return {UNORM, 10,10,10,0, 20,10, 0, 0};\n\n            case kR8G8_unorm_SkColorType:   return {UNORM,  8, 8,0, 0, 0, 8,0,0};\n            case kR16G16_unorm_SkColorType: return {UNORM, 16,16,0, 0, 0,16,0,0};\n            case kA16_unorm_SkColorType:    return {UNORM,  0, 0,0,16, 0, 0,0,0};\n        }\n        SkASSERT(false);\n        return {UNORM, 0,0,0,0, 0,0,0,0};\n    }\n\n    static int byte_size(PixelFormat f) {\n        \/\/ What's the highest bit we read?\n        int bits = std::max(f.r_bits + f.r_shift,\n                   std::max(f.g_bits + f.g_shift,\n                   std::max(f.b_bits + f.b_shift,\n                            f.a_bits + f.a_shift)));\n        \/\/ Round up to bytes.\n        return (bits + 7) \/ 8;\n    }\n\n    static Color unpack(PixelFormat f, I32 x) {\n        SkASSERT(byte_size(f) <= 4);\n\n        auto from_srgb = [](int bits, I32 channel) -> F32 {\n            const skcms_TransferFunction* tf = skcms_sRGB_TransferFunction();\n            F32 v = from_unorm(bits, channel);\n            return sk_program_transfer_fn(v, sRGBish_TF,\n                                          v->splat(tf->g),\n                                          v->splat(tf->a),\n                                          v->splat(tf->b),\n                                          v->splat(tf->c),\n                                          v->splat(tf->d),\n                                          v->splat(tf->e),\n                                          v->splat(tf->f));\n        };\n\n        auto unpack_rgb = [=](int bits, int shift) -> F32 {\n            I32 channel = extract(x, shift, (1<<bits)-1);\n            switch (f.encoding) {\n                case PixelFormat::UNORM: return from_unorm(bits, channel);\n                case PixelFormat:: SRGB: return from_srgb (bits, channel);\n                case PixelFormat::FLOAT: return from_fp16 (      channel);\n            }\n            SkUNREACHABLE;\n        };\n        auto unpack_alpha = [=](int bits, int shift) -> F32 {\n            I32 channel = extract(x, shift, (1<<bits)-1);\n            switch (f.encoding) {\n                case PixelFormat::UNORM:\n                case PixelFormat:: SRGB: return from_unorm(bits, channel);\n                case PixelFormat::FLOAT: return from_fp16 (      channel);\n            }\n            SkUNREACHABLE;\n        };\n        return {\n            f.r_bits ? unpack_rgb  (f.r_bits, f.r_shift) : x->splat(0.0f),\n            f.g_bits ? unpack_rgb  (f.g_bits, f.g_shift) : x->splat(0.0f),\n            f.b_bits ? unpack_rgb  (f.b_bits, f.b_shift) : x->splat(0.0f),\n            f.a_bits ? unpack_alpha(f.a_bits, f.a_shift) : x->splat(1.0f),\n        };\n    }\n\n    static void split_disjoint_8byte_format(PixelFormat f, PixelFormat* lo, PixelFormat* hi) {\n        SkASSERT(byte_size(f) == 8);\n        \/\/ We assume some of the channels are in the low 32 bits, some in the high 32 bits.\n        \/\/ The assert on byte_size(lo) will trigger if this assumption is violated.\n        *lo = f;\n        if (f.r_shift >= 32) { lo->r_bits = 0; lo->r_shift = 32; }\n        if (f.g_shift >= 32) { lo->g_bits = 0; lo->g_shift = 32; }\n        if (f.b_shift >= 32) { lo->b_bits = 0; lo->b_shift = 32; }\n        if (f.a_shift >= 32) { lo->a_bits = 0; lo->a_shift = 32; }\n        SkASSERT(byte_size(*lo) == 4);\n\n        *hi = f;\n        if (f.r_shift < 32) { hi->r_bits = 0; hi->r_shift = 32; } else { hi->r_shift -= 32; }\n        if (f.g_shift < 32) { hi->g_bits = 0; hi->g_shift = 32; } else { hi->g_shift -= 32; }\n        if (f.b_shift < 32) { hi->b_bits = 0; hi->b_shift = 32; } else { hi->b_shift -= 32; }\n        if (f.a_shift < 32) { hi->a_bits = 0; hi->a_shift = 32; } else { hi->a_shift -= 32; }\n        SkASSERT(byte_size(*hi) == 4);\n    }\n\n    \/\/ The only 16-byte format we support today is RGBA F32,\n    \/\/ though, TODO, we could generalize that to any swizzle, and to allow UNORM too.\n    static void assert_16byte_is_rgba_f32(PixelFormat f) {\n    #if defined(SK_DEBUG)\n        SkASSERT(byte_size(f) == 16);\n        PixelFormat rgba_f32 = SkColorType_to_PixelFormat(kRGBA_F32_SkColorType);\n\n        SkASSERT(f.encoding == rgba_f32.encoding);\n\n        SkASSERT(f.r_bits == rgba_f32.r_bits);\n        SkASSERT(f.g_bits == rgba_f32.g_bits);\n        SkASSERT(f.b_bits == rgba_f32.b_bits);\n        SkASSERT(f.a_bits == rgba_f32.a_bits);\n\n        SkASSERT(f.r_shift == rgba_f32.r_shift);\n        SkASSERT(f.g_shift == rgba_f32.g_shift);\n        SkASSERT(f.b_shift == rgba_f32.b_shift);\n        SkASSERT(f.a_shift == rgba_f32.a_shift);\n    #endif\n    }\n\n    Color Builder::load(PixelFormat f, Ptr ptr) {\n        switch (byte_size(f)) {\n            case 1: return unpack(f, load8 (ptr));\n            case 2: return unpack(f, load16(ptr));\n            case 4: return unpack(f, load32(ptr));\n            case 8: {\n                PixelFormat lo,hi;\n                split_disjoint_8byte_format(f, &lo,&hi);\n                Color l = unpack(lo, load64(ptr, 0)),\n                      h = unpack(hi, load64(ptr, 1));\n                return {\n                    lo.r_bits ? l.r : h.r,\n                    lo.g_bits ? l.g : h.g,\n                    lo.b_bits ? l.b : h.b,\n                    lo.a_bits ? l.a : h.a,\n                };\n            }\n            case 16: {\n                assert_16byte_is_rgba_f32(f);\n                return {\n                    pun_to_F32(load128(ptr, 0)),\n                    pun_to_F32(load128(ptr, 1)),\n                    pun_to_F32(load128(ptr, 2)),\n                    pun_to_F32(load128(ptr, 3)),\n                };\n            }\n            default: SkUNREACHABLE;\n        }\n        return {};\n    }\n\n    Color Builder::gather(PixelFormat f, UPtr ptr, int offset, I32 index) {\n        switch (byte_size(f)) {\n            case 1: return unpack(f, gather8 (ptr, offset, index));\n            case 2: return unpack(f, gather16(ptr, offset, index));\n            case 4: return unpack(f, gather32(ptr, offset, index));\n            case 8: {\n                PixelFormat lo,hi;\n                split_disjoint_8byte_format(f, &lo,&hi);\n                Color l = unpack(lo, gather32(ptr, offset, (index<<1)+0)),\n                      h = unpack(hi, gather32(ptr, offset, (index<<1)+1));\n                return {\n                    lo.r_bits ? l.r : h.r,\n                    lo.g_bits ? l.g : h.g,\n                    lo.b_bits ? l.b : h.b,\n                    lo.a_bits ? l.a : h.a,\n                };\n            }\n            case 16: {\n                assert_16byte_is_rgba_f32(f);\n                return {\n                    gatherF(ptr, offset, (index<<2)+0),\n                    gatherF(ptr, offset, (index<<2)+1),\n                    gatherF(ptr, offset, (index<<2)+2),\n                    gatherF(ptr, offset, (index<<2)+3),\n                };\n            }\n            default: SkUNREACHABLE;\n        }\n        return {};\n    }\n\n    static I32 pack32(PixelFormat f, Color c) {\n        SkASSERT(byte_size(f) <= 4);\n\n        auto to_srgb = [](int bits, F32 v) {\n            const skcms_TransferFunction* tf = skcms_sRGB_Inverse_TransferFunction();\n            return to_unorm(bits, sk_program_transfer_fn(v, sRGBish_TF,\n                                                         v->splat(tf->g),\n                                                         v->splat(tf->a),\n                                                         v->splat(tf->b),\n                                                         v->splat(tf->c),\n                                                         v->splat(tf->d),\n                                                         v->splat(tf->e),\n                                                         v->splat(tf->f)));\n        };\n\n        I32 packed = c->splat(0);\n        auto pack_rgb = [&](F32 channel, int bits, int shift) {\n            I32 encoded;\n            switch (f.encoding) {\n                case PixelFormat::UNORM: encoded = to_unorm(bits, channel); break;\n                case PixelFormat:: SRGB: encoded = to_srgb (bits, channel); break;\n                case PixelFormat::FLOAT: encoded = to_fp16 (      channel); break;\n            }\n            packed = pack(packed, encoded, shift);\n        };\n        auto pack_alpha = [&](F32 channel, int bits, int shift) {\n            I32 encoded;\n            switch (f.encoding) {\n                case PixelFormat::UNORM:\n                case PixelFormat:: SRGB: encoded = to_unorm(bits, channel); break;\n                case PixelFormat::FLOAT: encoded = to_fp16 (      channel); break;\n            }\n            packed = pack(packed, encoded, shift);\n        };\n        if (f.r_bits) { pack_rgb  (c.r, f.r_bits, f.r_shift); }\n        if (f.g_bits) { pack_rgb  (c.g, f.g_bits, f.g_shift); }\n        if (f.b_bits) { pack_rgb  (c.b, f.b_bits, f.b_shift); }\n        if (f.a_bits) { pack_alpha(c.a, f.a_bits, f.a_shift); }\n        return packed;\n    }\n\n    void Builder::store(PixelFormat f, Ptr ptr, Color c) {\n        \/\/ Detect a grayscale PixelFormat: r,g,b bit counts and shifts all equal.\n        if (f.r_bits  == f.g_bits  && f.g_bits  == f.b_bits &&\n            f.r_shift == f.g_shift && f.g_shift == f.b_shift) {\n\n            \/\/ TODO: pull these coefficients from an SkColorSpace?  This is sRGB luma\/luminance.\n            c.r = c.r * 0.2126f\n                + c.g * 0.7152f\n                + c.b * 0.0722f;\n            f.g_bits = f.b_bits = 0;\n        }\n\n        switch (byte_size(f)) {\n            case 1: store8 (ptr, pack32(f,c)); break;\n            case 2: store16(ptr, pack32(f,c)); break;\n            case 4: store32(ptr, pack32(f,c)); break;\n            case 8: {\n                PixelFormat lo,hi;\n                split_disjoint_8byte_format(f, &lo,&hi);\n                store64(ptr, pack32(lo,c)\n                           , pack32(hi,c));\n                break;\n            }\n            case 16: {\n                assert_16byte_is_rgba_f32(f);\n                store128(ptr, pun_to_I32(c.r), pun_to_I32(c.g), pun_to_I32(c.b), pun_to_I32(c.a));\n                break;\n            }\n            default: SkUNREACHABLE;\n        }\n    }\n\n    void Builder::unpremul(F32* r, F32* g, F32* b, F32 a) {\n        skvm::F32 invA = 1.0f \/ a,\n                  inf  = pun_to_F32(splat(0x7f800000));\n        \/\/ If a is 0, so are *r,*g,*b, so set invA to 0 to avoid 0*inf=NaN (instead 0*0 = 0).\n        invA = select(invA < inf, invA\n                                , 0.0f);\n        *r *= invA;\n        *g *= invA;\n        *b *= invA;\n    }\n\n    void Builder::premul(F32* r, F32* g, F32* b, F32 a) {\n        *r *= a;\n        *g *= a;\n        *b *= a;\n    }\n\n    Color Builder::uniformColor(SkColor4f color, Uniforms* uniforms) {\n        auto [r,g,b,a] = color;\n        return {\n            uniformF(uniforms->pushF(r)),\n            uniformF(uniforms->pushF(g)),\n            uniformF(uniforms->pushF(b)),\n            uniformF(uniforms->pushF(a)),\n        };\n    }\n\n    F32 Builder::lerp(F32 lo, F32 hi, F32 t) {\n        if (this->isImm(t.id, 0.0f)) { return lo; }\n        if (this->isImm(t.id, 1.0f)) { return hi; }\n        return mad(sub(hi, lo), t, lo);\n    }\n\n    Color Builder::lerp(Color lo, Color hi, F32 t) {\n        return {\n            lerp(lo.r, hi.r, t),\n            lerp(lo.g, hi.g, t),\n            lerp(lo.b, hi.b, t),\n            lerp(lo.a, hi.a, t),\n        };\n    }\n\n    HSLA Builder::to_hsla(Color c) {\n        F32 mx = max(max(c.r,c.g),c.b),\n            mn = min(min(c.r,c.g),c.b),\n             d = mx - mn,\n          invd = 1.0f \/ d,\n        g_lt_b = select(c.g < c.b, splat(6.0f)\n                                 , splat(0.0f));\n\n        F32 h = (1\/6.0f) * select(mx == mn,  0.0f,\n                           select(mx == c.r, invd * (c.g - c.b) + g_lt_b,\n                           select(mx == c.g, invd * (c.b - c.r) + 2.0f\n                                           , invd * (c.r - c.g) + 4.0f)));\n\n        F32 sum = mx + mn,\n              l = sum * 0.5f,\n              s = select(mx == mn, 0.0f\n                                 , d \/ select(l > 0.5f, 2.0f - sum\n                                                      , sum));\n        return {h, s, l, c.a};\n    }\n\n    Color Builder::to_rgba(HSLA c) {\n        \/\/ See GrRGBToHSLFilterEffect.fp\n\n        auto [h,s,l,a] = c;\n        F32 x = s * (1.0f - abs(l + l - 1.0f));\n\n        auto hue_to_rgb = [&,l=l](auto hue) {\n            auto q = abs(6.0f * fract(hue) - 3.0f) - 1.0f;\n            return x * (clamp01(q) - 0.5f) + l;\n        };\n\n        return {\n            hue_to_rgb(h + 0\/3.0f),\n            hue_to_rgb(h + 2\/3.0f),\n            hue_to_rgb(h + 1\/3.0f),\n            c.a,\n        };\n    }\n\n    \/\/ We're basing our implementation of non-separable blend modes on\n    \/\/   https:\/\/www.w3.org\/TR\/compositing-1\/#blendingnonseparable.\n    \/\/ and\n    \/\/   https:\/\/www.khronos.org\/registry\/OpenGL\/specs\/es\/3.2\/es_spec_3.2.pdf\n    \/\/ They're equivalent, but ES' math has been better simplified.\n    \/\/\n    \/\/ Anything extra we add beyond that is to make the math work with premul inputs.\n\n    static skvm::F32 saturation(skvm::F32 r, skvm::F32 g, skvm::F32 b) {\n        return max(r, max(g, b))\n             - min(r, min(g, b));\n    }\n\n    static skvm::F32 luminance(skvm::F32 r, skvm::F32 g, skvm::F32 b) {\n        return r*0.30f + g*0.59f + b*0.11f;\n    }\n\n    static void set_sat(skvm::F32* r, skvm::F32* g, skvm::F32* b, skvm::F32 s) {\n        F32 mn  = min(*r, min(*g, *b)),\n            mx  = max(*r, max(*g, *b)),\n            sat = mx - mn;\n\n        \/\/ Map min channel to 0, max channel to s, and scale the middle proportionally.\n        auto scale = [&](skvm::F32 c) {\n            auto scaled = ((c - mn) * s) \/ sat;\n            return select(is_finite(scaled), scaled, 0.0f);\n        };\n        *r = scale(*r);\n        *g = scale(*g);\n        *b = scale(*b);\n    }\n\n    static void set_lum(skvm::F32* r, skvm::F32* g, skvm::F32* b, skvm::F32 lu) {\n        auto diff = lu - luminance(*r, *g, *b);\n        *r += diff;\n        *g += diff;\n        *b += diff;\n    }\n\n    static void clip_color(skvm::F32* r, skvm::F32* g, skvm::F32* b, skvm::F32 a) {\n        F32 mn  = min(*r, min(*g, *b)),\n            mx  = max(*r, max(*g, *b)),\n            lu = luminance(*r, *g, *b);\n\n        auto clip = [&](auto c) {\n            c = select(mn >= 0, c\n                              , lu + ((c-lu)*(  lu)) \/ (lu-mn));\n            c = select(mx >  a, lu + ((c-lu)*(a-lu)) \/ (mx-lu)\n                              , c);\n            return clamp01(c);  \/\/ May be a little negative, or worse, NaN.\n        };\n        *r = clip(*r);\n        *g = clip(*g);\n        *b = clip(*b);\n    }\n\n    Color Builder::blend(SkBlendMode mode, Color src, Color dst) {\n        auto mma = [](skvm::F32 x, skvm::F32 y, skvm::F32 z, skvm::F32 w) {\n            return x*y + z*w;\n        };\n\n        auto two = [](skvm::F32 x) { return x+x; };\n\n        auto apply_rgba = [&](auto fn) {\n            return Color {\n                fn(src.r, dst.r),\n                fn(src.g, dst.g),\n                fn(src.b, dst.b),\n                fn(src.a, dst.a),\n            };\n        };\n\n        auto apply_rgb_srcover_a = [&](auto fn) {\n            return Color {\n                fn(src.r, dst.r),\n                fn(src.g, dst.g),\n                fn(src.b, dst.b),\n                mad(dst.a, 1-src.a, src.a),   \/\/ srcover for alpha\n            };\n        };\n\n        auto non_sep = [&](auto R, auto G, auto B) {\n            return Color{\n                R + mma(src.r, 1-dst.a,  dst.r, 1-src.a),\n                G + mma(src.g, 1-dst.a,  dst.g, 1-src.a),\n                B + mma(src.b, 1-dst.a,  dst.b, 1-src.a),\n                mad(dst.a, 1-src.a, src.a),   \/\/ srcover for alpha\n            };\n        };\n\n        switch (mode) {\n            default:\n                SkASSERT(false);\n                [[fallthrough]]; \/*but also, for safety, fallthrough*\/\n\n            case SkBlendMode::kClear: return { splat(0.0f), splat(0.0f), splat(0.0f), splat(0.0f) };\n\n            case SkBlendMode::kSrc: return src;\n            case SkBlendMode::kDst: return dst;\n\n            case SkBlendMode::kDstOver: std::swap(src, dst); [[fallthrough]];\n            case SkBlendMode::kSrcOver:\n                return apply_rgba([&](auto s, auto d) {\n                    return mad(d,1-src.a, s);\n                });\n\n            case SkBlendMode::kDstIn: std::swap(src, dst); [[fallthrough]];\n            case SkBlendMode::kSrcIn:\n                return apply_rgba([&](auto s, auto d) {\n                    return s * dst.a;\n                });\n\n            case SkBlendMode::kDstOut: std::swap(src, dst); [[fallthrough]];\n\n            case SkBlendMode::kSrcOut:\n                return apply_rgba([&](auto s, auto d) {\n                    return s * (1-dst.a);\n                });\n\n            case SkBlendMode::kDstATop: std::swap(src, dst); [[fallthrough]];\n            case SkBlendMode::kSrcATop:\n                return apply_rgba([&](auto s, auto d) {\n                    return mma(s, dst.a,  d, 1-src.a);\n                });\n\n            case SkBlendMode::kXor:\n                return apply_rgba([&](auto s, auto d) {\n                    return mma(s, 1-dst.a,  d, 1-src.a);\n                });\n\n            case SkBlendMode::kPlus:\n                return apply_rgba([&](auto s, auto d) {\n                    return min(s+d, 1.0f);\n                });\n\n            case SkBlendMode::kModulate:\n                return apply_rgba([&](auto s, auto d) {\n                    return s * d;\n                });\n\n            case SkBlendMode::kScreen:\n                \/\/ (s+d)-(s*d) gave us trouble with our \"r,g,b <= after blending\" asserts.\n                \/\/ It's kind of plausible that s + (d - sd) keeps more precision?\n                return apply_rgba([&](auto s, auto d) {\n                    return s + (d - s*d);\n                });\n\n            case SkBlendMode::kDarken:\n                return apply_rgb_srcover_a([&](auto s, auto d) {\n                    return s + (d - max(s * dst.a,\n                                        d * src.a));\n                });\n\n            case SkBlendMode::kLighten:\n                return apply_rgb_srcover_a([&](auto s, auto d) {\n                    return s + (d - min(s * dst.a,\n                                        d * src.a));\n                });\n\n            case SkBlendMode::kDifference:\n                return apply_rgb_srcover_a([&](auto s, auto d) {\n                    return s + (d - two(min(s * dst.a,\n                                            d * src.a)));\n                });\n\n            case SkBlendMode::kExclusion:\n                return apply_rgb_srcover_a([&](auto s, auto d) {\n                    return s + (d - two(s * d));\n                });\n\n            case SkBlendMode::kColorBurn:\n                return apply_rgb_srcover_a([&](auto s, auto d) {\n                    auto mn   = min(dst.a,\n                                    src.a * (dst.a - d) \/ s),\n                         burn = src.a * (dst.a - mn) + mma(s, 1-dst.a, d, 1-src.a);\n                    return select(d == dst.a     , s * (1-dst.a) + d,\n                           select(is_finite(burn), burn\n                                                 , d * (1-src.a) + s));\n                });\n\n            case SkBlendMode::kColorDodge:\n                return apply_rgb_srcover_a([&](auto s, auto d) {\n                    auto dodge = src.a * min(dst.a,\n                                             d * src.a \/ (src.a - s))\n                                       + mma(s, 1-dst.a, d, 1-src.a);\n                    return select(d == 0.0f       , s * (1-dst.a) + d,\n                           select(is_finite(dodge), dodge\n                                                  , d * (1-src.a) + s));\n                });\n\n            case SkBlendMode::kHardLight:\n                return apply_rgb_srcover_a([&](auto s, auto d) {\n                    return mma(s, 1-dst.a, d, 1-src.a) +\n                           select(two(s) <= src.a,\n                                  two(s * d),\n                                  src.a * dst.a - two((dst.a - d) * (src.a - s)));\n                });\n\n            case SkBlendMode::kOverlay:\n                return apply_rgb_srcover_a([&](auto s, auto d) {\n                    return mma(s, 1-dst.a, d, 1-src.a) +\n                           select(two(d) <= dst.a,\n                                  two(s * d),\n                                  src.a * dst.a - two((dst.a - d) * (src.a - s)));\n                });\n\n            case SkBlendMode::kMultiply:\n                return apply_rgba([&](auto s, auto d) {\n                    return mma(s, 1-dst.a, d, 1-src.a) + s * d;\n                });\n\n            case SkBlendMode::kSoftLight:\n                return apply_rgb_srcover_a([&](auto s, auto d) {\n                    auto  m = select(dst.a > 0.0f, d \/ dst.a\n                                                 , 0.0f),\n                         s2 = two(s),\n                         m4 = 4*m;\n\n                         \/\/ The logic forks three ways:\n                         \/\/    1. dark src?\n                         \/\/    2. light src, dark dst?\n                         \/\/    3. light src, light dst?\n\n                         \/\/ Used in case 1\n                    auto darkSrc = d * ((s2-src.a) * (1-m) + src.a),\n                         \/\/ Used in case 2\n                         darkDst = (m4 * m4 + m4) * (m-1) + 7*m,\n                         \/\/ Used in case 3.\n                         liteDst = sqrt(m) - m,\n                         \/\/ Used in 2 or 3?\n                         liteSrc = dst.a * (s2 - src.a) * select(4*d <= dst.a, darkDst\n                                                                             , liteDst)\n                                   + d * src.a;\n                    return s * (1-dst.a) + d * (1-src.a) + select(s2 <= src.a, darkSrc\n                                                                             , liteSrc);\n                });\n\n            case SkBlendMode::kHue: {\n                skvm::F32 R = src.r * src.a,\n                          G = src.g * src.a,\n                          B = src.b * src.a;\n\n                set_sat   (&R, &G, &B, src.a * saturation(dst.r, dst.g, dst.b));\n                set_lum   (&R, &G, &B, src.a * luminance (dst.r, dst.g, dst.b));\n                clip_color(&R, &G, &B, src.a * dst.a);\n\n                return non_sep(R, G, B);\n            }\n\n            case SkBlendMode::kSaturation: {\n                skvm::F32 R = dst.r * src.a,\n                          G = dst.g * src.a,\n                          B = dst.b * src.a;\n\n                set_sat   (&R, &G, &B, dst.a * saturation(src.r, src.g, src.b));\n                set_lum   (&R, &G, &B, src.a * luminance (dst.r, dst.g, dst.b));\n                clip_color(&R, &G, &B, src.a * dst.a);\n\n                return non_sep(R, G, B);\n            }\n\n            case SkBlendMode::kColor: {\n                skvm::F32 R = src.r * dst.a,\n                          G = src.g * dst.a,\n                          B = src.b * dst.a;\n\n                set_lum   (&R, &G, &B, src.a * luminance(dst.r, dst.g, dst.b));\n                clip_color(&R, &G, &B, src.a * dst.a);\n\n                return non_sep(R, G, B);\n            }\n\n            case SkBlendMode::kLuminosity: {\n                skvm::F32 R = dst.r * src.a,\n                          G = dst.g * src.a,\n                          B = dst.b * src.a;\n\n                set_lum   (&R, &G, &B, dst.a * luminance(src.r, src.g, src.b));\n                clip_color(&R, &G, &B, dst.a * src.a);\n\n                return non_sep(R, G, B);\n            }\n        }\n    }\n\n    \/\/ ~~~~ Program::eval() and co. ~~~~ \/\/\n\n    \/\/ Handy references for x86-64 instruction encoding:\n    \/\/ https:\/\/wiki.osdev.org\/X86-64_Instruction_Encoding\n    \/\/ https:\/\/www-user.tu-chemnitz.de\/~heha\/viewchm.php\/hs\/x86.chm\/x64.htm\n    \/\/ https:\/\/www-user.tu-chemnitz.de\/~heha\/viewchm.php\/hs\/x86.chm\/x86.htm\n    \/\/ http:\/\/ref.x86asm.net\/coder64.html\n\n    \/\/ Used for ModRM \/ immediate instruction encoding.\n    static uint8_t _233(int a, int b, int c) {\n        return (a & 3) << 6\n             | (b & 7) << 3\n             | (c & 7) << 0;\n    }\n\n    \/\/ ModRM byte encodes the arguments of an opcode.\n    enum class Mod { Indirect, OneByteImm, FourByteImm, Direct };\n    static uint8_t mod_rm(Mod mod, int reg, int rm) {\n        return _233((int)mod, reg, rm);\n    }\n\n    static Mod mod(int imm) {\n        if (imm == 0)               { return Mod::Indirect; }\n        if (SkTFitsIn<int8_t>(imm)) { return Mod::OneByteImm; }\n        return Mod::FourByteImm;\n    }\n\n    static int imm_bytes(Mod mod) {\n        switch (mod) {\n            case Mod::Indirect:    return 0;\n            case Mod::OneByteImm:  return 1;\n            case Mod::FourByteImm: return 4;\n            case Mod::Direct: SkUNREACHABLE;\n        }\n        SkUNREACHABLE;\n    }\n\n    \/\/ SIB byte encodes a memory address, base + (index * scale).\n    static uint8_t sib(Assembler::Scale scale, int index, int base) {\n        return _233((int)scale, index, base);\n    }\n\n    \/\/ The REX prefix is used to extend most old 32-bit instructions to 64-bit.\n    static uint8_t rex(bool W,   \/\/ If set, operation is 64-bit, otherwise default, usually 32-bit.\n                       bool R,   \/\/ Extra top bit to select ModRM reg, registers 8-15.\n                       bool X,   \/\/ Extra top bit for SIB index register.\n                       bool B) { \/\/ Extra top bit for SIB base or ModRM rm register.\n        return 0b01000000   \/\/ Fixed 0100 for top four bits.\n             | (W << 3)\n             | (R << 2)\n             | (X << 1)\n             | (B << 0);\n    }\n\n\n    \/\/ The VEX prefix extends SSE operations to AVX.  Used generally, even with XMM.\n    struct VEX {\n        int     len;\n        uint8_t bytes[3];\n    };\n\n    static VEX vex(bool  WE,   \/\/ Like REX W for int operations, or opcode extension for float?\n                   bool   R,   \/\/ Same as REX R.  Pass high bit of dst register, dst>>3.\n                   bool   X,   \/\/ Same as REX X.\n                   bool   B,   \/\/ Same as REX B.  Pass y>>3 for 3-arg ops, x>>3 for 2-arg.\n                   int  map,   \/\/ SSE opcode map selector: 0x0f, 0x380f, 0x3a0f.\n                   int vvvv,   \/\/ 4-bit second operand register.  Pass our x for 3-arg ops.\n                   bool   L,   \/\/ Set for 256-bit ymm operations, off for 128-bit xmm.\n                   int   pp) { \/\/ SSE mandatory prefix: 0x66, 0xf3, 0xf2, else none.\n\n        \/\/ Pack x86 opcode map selector to 5-bit VEX encoding.\n        map = [map]{\n            switch (map) {\n                case   0x0f: return 0b00001;\n                case 0x380f: return 0b00010;\n                case 0x3a0f: return 0b00011;\n                \/\/ Several more cases only used by XOP \/ TBM.\n            }\n            SkUNREACHABLE;\n        }();\n\n        \/\/ Pack  mandatory SSE opcode prefix byte to 2-bit VEX encoding.\n        pp = [pp]{\n            switch (pp) {\n                case 0x66: return 0b01;\n                case 0xf3: return 0b10;\n                case 0xf2: return 0b11;\n            }\n            return 0b00;\n        }();\n\n        VEX vex = {0, {0,0,0}};\n        if (X == 0 && B == 0 && WE == 0 && map == 0b00001) {\n            \/\/ With these conditions met, we can optionally compress VEX to 2-byte.\n            vex.len = 2;\n            vex.bytes[0] = 0xc5;\n            vex.bytes[1] = (pp      &  3) << 0\n                         | (L       &  1) << 2\n                         | (~vvvv   & 15) << 3\n                         | (~(int)R &  1) << 7;\n        } else {\n            \/\/ We could use this 3-byte VEX prefix all the time if we like.\n            vex.len = 3;\n            vex.bytes[0] = 0xc4;\n            vex.bytes[1] = (map     & 31) << 0\n                         | (~(int)B &  1) << 5\n                         | (~(int)X &  1) << 6\n                         | (~(int)R &  1) << 7;\n            vex.bytes[2] = (pp    &  3) << 0\n                         | (L     &  1) << 2\n                         | (~vvvv & 15) << 3\n                         | (WE    &  1) << 7;\n        }\n        return vex;\n    }\n\n    Assembler::Assembler(void* buf) : fCode((uint8_t*)buf), fSize(0) {}\n\n    size_t Assembler::size() const { return fSize; }\n\n    void Assembler::bytes(const void* p, int n) {\n        if (fCode) {\n            memcpy(fCode+fSize, p, n);\n        }\n        fSize += n;\n    }\n\n    void Assembler::byte(uint8_t b) { this->bytes(&b, 1); }\n    void Assembler::word(uint32_t w) { this->bytes(&w, 4); }\n\n    void Assembler::align(int mod) {\n        while (this->size() % mod) {\n            this->byte(0x00);\n        }\n    }\n\n    void Assembler::int3() {\n        this->byte(0xcc);\n    }\n\n    void Assembler::vzeroupper() {\n        this->byte(0xc5);\n        this->byte(0xf8);\n        this->byte(0x77);\n    }\n    void Assembler::ret() { this->byte(0xc3); }\n\n    void Assembler::op(int opcode, Operand dst, GP64 x) {\n        if (dst.kind == Operand::REG) {\n            this->byte(rex(W1,x>>3,0,dst.reg>>3));\n            this->bytes(&opcode, SkTFitsIn<uint8_t>(opcode) ? 1 : 2);\n            this->byte(mod_rm(Mod::Direct, x, dst.reg&7));\n        } else {\n            SkASSERT(dst.kind == Operand::MEM);\n            const Mem& m = dst.mem;\n            const bool need_SIB = (m.base&7) == rsp\n                               || m.index != rsp;\n\n            this->byte(rex(W1,x>>3,m.index>>3,m.base>>3));\n            this->bytes(&opcode, SkTFitsIn<uint8_t>(opcode) ? 1 : 2);\n            this->byte(mod_rm(mod(m.disp), x&7, (need_SIB ? rsp : m.base)&7));\n            if (need_SIB) {\n                this->byte(sib(m.scale, m.index&7, m.base&7));\n            }\n            this->bytes(&m.disp, imm_bytes(mod(m.disp)));\n        }\n    }\n\n    void Assembler::op(int opcode, int opcode_ext, Operand dst, int imm) {\n        opcode |= 0b1000'0000;   \/\/ top bit set for instructions with any immediate\n\n        int imm_bytes = 4;\n        if (SkTFitsIn<int8_t>(imm)) {\n            imm_bytes = 1;\n            opcode |= 0b0000'0010;  \/\/ second bit set for 8-bit immediate, else 32-bit.\n        }\n\n        this->op(opcode, dst, (GP64)opcode_ext);\n        this->bytes(&imm, imm_bytes);\n    }\n\n    void Assembler::add(Operand dst, int imm) { this->op(0x01,0b000, dst,imm); }\n    void Assembler::sub(Operand dst, int imm) { this->op(0x01,0b101, dst,imm); }\n    void Assembler::cmp(Operand dst, int imm) { this->op(0x01,0b111, dst,imm); }\n\n    \/\/ These don't work quite like the other instructions with immediates:\n    \/\/ these immediates are always fixed size at 4 bytes or 1 byte.\n    void Assembler::mov(Operand dst, int imm) {\n        this->op(0xC7,dst,(GP64)0b000);\n        this->word(imm);\n    }\n    void Assembler::movb(Operand dst, int imm) {\n        this->op(0xC6,dst,(GP64)0b000);\n        this->byte(imm);\n    }\n\n    void Assembler::add (Operand dst, GP64 x) { this->op(0x01, dst,x); }\n    void Assembler::sub (Operand dst, GP64 x) { this->op(0x29, dst,x); }\n    void Assembler::cmp (Operand dst, GP64 x) { this->op(0x39, dst,x); }\n    void Assembler::mov (Operand dst, GP64 x) { this->op(0x89, dst,x); }\n    void Assembler::movb(Operand dst, GP64 x) { this->op(0x88, dst,x); }\n\n    void Assembler::add (GP64 dst, Operand x) { this->op(0x03, x,dst); }\n    void Assembler::sub (GP64 dst, Operand x) { this->op(0x2B, x,dst); }\n    void Assembler::cmp (GP64 dst, Operand x) { this->op(0x3B, x,dst); }\n    void Assembler::mov (GP64 dst, Operand x) { this->op(0x8B, x,dst); }\n    void Assembler::movb(GP64 dst, Operand x) { this->op(0x8A, x,dst); }\n\n    void Assembler::movzbq(GP64 dst, Operand x) { this->op(0xB60F, x,dst); }\n    void Assembler::movzwq(GP64 dst, Operand x) { this->op(0xB70F, x,dst); }\n\n    void Assembler::vpaddd (Ymm dst, Ymm x, Operand y) { this->op(0x66,  0x0f,0xfe, dst,x,y); }\n    void Assembler::vpsubd (Ymm dst, Ymm x, Operand y) { this->op(0x66,  0x0f,0xfa, dst,x,y); }\n    void Assembler::vpmulld(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0x40, dst,x,y); }\n\n    void Assembler::vpaddw   (Ymm dst, Ymm x, Operand y) { this->op(0x66,  0x0f,0xfd, dst,x,y); }\n    void Assembler::vpsubw   (Ymm dst, Ymm x, Operand y) { this->op(0x66,  0x0f,0xf9, dst,x,y); }\n    void Assembler::vpmullw  (Ymm dst, Ymm x, Operand y) { this->op(0x66,  0x0f,0xd5, dst,x,y); }\n    void Assembler::vpavgw   (Ymm dst, Ymm x, Operand y) { this->op(0x66,  0x0f,0xe3, dst,x,y); }\n    void Assembler::vpmulhrsw(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0x0b, dst,x,y); }\n    void Assembler::vpminsw  (Ymm dst, Ymm x, Operand y) { this->op(0x66,  0x0f,0xea, dst,x,y); }\n    void Assembler::vpmaxsw  (Ymm dst, Ymm x, Operand y) { this->op(0x66,  0x0f,0xee, dst,x,y); }\n    void Assembler::vpminuw  (Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0x3a, dst,x,y); }\n    void Assembler::vpmaxuw  (Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0x3e, dst,x,y); }\n\n    void Assembler::vpabsw(Ymm dst, Operand x) { this->op(0x66,0x380f,0x1d, dst,x); }\n\n\n    void Assembler::vpand (Ymm dst, Ymm x, Operand y) { this->op(0x66,0x0f,0xdb, dst,x,y); }\n    void Assembler::vpor  (Ymm dst, Ymm x, Operand y) { this->op(0x66,0x0f,0xeb, dst,x,y); }\n    void Assembler::vpxor (Ymm dst, Ymm x, Operand y) { this->op(0x66,0x0f,0xef, dst,x,y); }\n    void Assembler::vpandn(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x0f,0xdf, dst,x,y); }\n\n    void Assembler::vaddps(Ymm dst, Ymm x, Operand y) { this->op(0,0x0f,0x58, dst,x,y); }\n    void Assembler::vsubps(Ymm dst, Ymm x, Operand y) { this->op(0,0x0f,0x5c, dst,x,y); }\n    void Assembler::vmulps(Ymm dst, Ymm x, Operand y) { this->op(0,0x0f,0x59, dst,x,y); }\n    void Assembler::vdivps(Ymm dst, Ymm x, Operand y) { this->op(0,0x0f,0x5e, dst,x,y); }\n    void Assembler::vminps(Ymm dst, Ymm x, Operand y) { this->op(0,0x0f,0x5d, dst,x,y); }\n    void Assembler::vmaxps(Ymm dst, Ymm x, Operand y) { this->op(0,0x0f,0x5f, dst,x,y); }\n\n    void Assembler::vfmadd132ps(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0x98, dst,x,y); }\n    void Assembler::vfmadd213ps(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0xa8, dst,x,y); }\n    void Assembler::vfmadd231ps(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0xb8, dst,x,y); }\n\n    void Assembler::vfmsub132ps(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0x9a, dst,x,y); }\n    void Assembler::vfmsub213ps(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0xaa, dst,x,y); }\n    void Assembler::vfmsub231ps(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0xba, dst,x,y); }\n\n    void Assembler::vfnmadd132ps(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0x9c, dst,x,y); }\n    void Assembler::vfnmadd213ps(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0xac, dst,x,y); }\n    void Assembler::vfnmadd231ps(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0xbc, dst,x,y); }\n\n    void Assembler::vpackusdw(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0x2b, dst,x,y); }\n    void Assembler::vpackuswb(Ymm dst, Ymm x, Operand y) { this->op(0x66,  0x0f,0x67, dst,x,y); }\n\n    void Assembler::vpunpckldq(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x0f,0x62, dst,x,y); }\n    void Assembler::vpunpckhdq(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x0f,0x6a, dst,x,y); }\n\n    void Assembler::vpcmpeqd(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x0f,0x76, dst,x,y); }\n    void Assembler::vpcmpeqw(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x0f,0x75, dst,x,y); }\n    void Assembler::vpcmpgtd(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x0f,0x66, dst,x,y); }\n    void Assembler::vpcmpgtw(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x0f,0x65, dst,x,y); }\n\n\n    void Assembler::imm_byte_after_operand(const Operand& operand, int imm) {\n        \/\/ When we've embedded a label displacement in the middle of an instruction,\n        \/\/ we need to tweak it a little so that the resolved displacement starts\n        \/\/ from the end of the instruction and not the end of the displacement.\n        if (operand.kind == Operand::LABEL && fCode) {\n            int disp;\n            memcpy(&disp, fCode+fSize-4, 4);\n            disp--;\n            memcpy(fCode+fSize-4, &disp, 4);\n        }\n        this->byte(imm);\n    }\n\n    void Assembler::vcmpps(Ymm dst, Ymm x, Operand y, int imm) {\n        this->op(0,0x0f,0xc2, dst,x,y);\n        this->imm_byte_after_operand(y, imm);\n    }\n\n    void Assembler::vpblendvb(Ymm dst, Ymm x, Operand y, Ymm z) {\n        this->op(0x66,0x3a0f,0x4c, dst,x,y);\n        this->imm_byte_after_operand(y, z << 4);\n    }\n\n    \/\/ Shift instructions encode their opcode extension as \"dst\", dst as x, and x as y.\n    void Assembler::vpslld(Ymm dst, Ymm x, int imm) {\n        this->op(0x66,0x0f,0x72,(Ymm)6, dst,x);\n        this->byte(imm);\n    }\n    void Assembler::vpsrld(Ymm dst, Ymm x, int imm) {\n        this->op(0x66,0x0f,0x72,(Ymm)2, dst,x);\n        this->byte(imm);\n    }\n    void Assembler::vpsrad(Ymm dst, Ymm x, int imm) {\n        this->op(0x66,0x0f,0x72,(Ymm)4, dst,x);\n        this->byte(imm);\n    }\n    void Assembler::vpsllw(Ymm dst, Ymm x, int imm) {\n        this->op(0x66,0x0f,0x71,(Ymm)6, dst,x);\n        this->byte(imm);\n    }\n    void Assembler::vpsrlw(Ymm dst, Ymm x, int imm) {\n        this->op(0x66,0x0f,0x71,(Ymm)2, dst,x);\n        this->byte(imm);\n    }\n    void Assembler::vpsraw(Ymm dst, Ymm x, int imm) {\n        this->op(0x66,0x0f,0x71,(Ymm)4, dst,x);\n        this->byte(imm);\n    }\n\n    void Assembler::vpermq(Ymm dst, Operand x, int imm) {\n        \/\/ A bit unusual among the instructions we use, this is 64-bit operation, so we set W.\n        this->op(0x66,0x3a0f,0x00, dst,x,W1);\n        this->imm_byte_after_operand(x, imm);\n    }\n\n    void Assembler::vperm2f128(Ymm dst, Ymm x, Operand y, int imm) {\n        this->op(0x66,0x3a0f,0x06, dst,x,y);\n        this->imm_byte_after_operand(y, imm);\n    }\n\n    void Assembler::vpermps(Ymm dst, Ymm ix, Operand src) {\n        this->op(0x66,0x380f,0x16, dst,ix,src);\n    }\n\n    void Assembler::vroundps(Ymm dst, Operand x, Rounding imm) {\n        this->op(0x66,0x3a0f,0x08, dst,x);\n        this->imm_byte_after_operand(x, imm);\n    }\n\n    void Assembler::vmovdqa(Ymm dst, Operand src) { this->op(0x66,0x0f,0x6f, dst,src); }\n    void Assembler::vmovups(Ymm dst, Operand src) { this->op(   0,0x0f,0x10, dst,src); }\n    void Assembler::vmovups(Xmm dst, Operand src) { this->op(   0,0x0f,0x10, dst,src); }\n    void Assembler::vmovups(Operand dst, Ymm src) { this->op(   0,0x0f,0x11, src,dst); }\n    void Assembler::vmovups(Operand dst, Xmm src) { this->op(   0,0x0f,0x11, src,dst); }\n\n    void Assembler::vcvtdq2ps (Ymm dst, Operand x) { this->op(   0,0x0f,0x5b, dst,x); }\n    void Assembler::vcvttps2dq(Ymm dst, Operand x) { this->op(0xf3,0x0f,0x5b, dst,x); }\n    void Assembler::vcvtps2dq (Ymm dst, Operand x) { this->op(0x66,0x0f,0x5b, dst,x); }\n    void Assembler::vsqrtps   (Ymm dst, Operand x) { this->op(   0,0x0f,0x51, dst,x); }\n\n    void Assembler::vcvtps2ph(Operand dst, Ymm x, Rounding imm) {\n        this->op(0x66,0x3a0f,0x1d, x,dst);\n        this->imm_byte_after_operand(dst, imm);\n    }\n    void Assembler::vcvtph2ps(Ymm dst, Operand x) {\n        this->op(0x66,0x380f,0x13, dst,x);\n    }\n\n    int Assembler::disp19(Label* l) {\n        SkASSERT(l->kind == Label::NotYetSet ||\n                 l->kind == Label::ARMDisp19);\n        int here = (int)this->size();\n        l->kind = Label::ARMDisp19;\n        l->references.push_back(here);\n        \/\/ ARM 19-bit instruction count, from the beginning of this instruction.\n        return (l->offset - here) \/ 4;\n    }\n\n    int Assembler::disp32(Label* l) {\n        SkASSERT(l->kind == Label::NotYetSet ||\n                 l->kind == Label::X86Disp32);\n        int here = (int)this->size();\n        l->kind = Label::X86Disp32;\n        l->references.push_back(here);\n        \/\/ x86 32-bit byte count, from the end of this instruction.\n        return l->offset - (here + 4);\n    }\n\n    void Assembler::op(int prefix, int map, int opcode, int dst, int x, Operand y, W w, L l) {\n        switch (y.kind) {\n            case Operand::REG: {\n                VEX v = vex(w, dst>>3, 0, y.reg>>3,\n                            map, x, l, prefix);\n                this->bytes(v.bytes, v.len);\n                this->byte(opcode);\n                this->byte(mod_rm(Mod::Direct, dst&7, y.reg&7));\n            } return;\n\n            case Operand::MEM: {\n                \/\/ Passing rsp as the rm argument to mod_rm() signals an SIB byte follows;\n                \/\/ without an SIB byte, that's where the base register would usually go.\n                \/\/ This means we have to use an SIB byte if we want to use rsp as a base register.\n                const Mem& m = y.mem;\n                const bool need_SIB = m.base  == rsp\n                                   || m.index != rsp;\n\n                VEX v = vex(w, dst>>3, m.index>>3, m.base>>3,\n                            map, x, l, prefix);\n                this->bytes(v.bytes, v.len);\n                this->byte(opcode);\n                this->byte(mod_rm(mod(m.disp), dst&7, (need_SIB ? rsp : m.base)&7));\n                if (need_SIB) {\n                    this->byte(sib(m.scale, m.index&7, m.base&7));\n                }\n                this->bytes(&m.disp, imm_bytes(mod(m.disp)));\n            } return;\n\n            case Operand::LABEL: {\n                \/\/ IP-relative addressing uses Mod::Indirect with the R\/M encoded as-if rbp or r13.\n                const int rip = rbp;\n\n                VEX v = vex(w, dst>>3, 0, rip>>3,\n                            map, x, l, prefix);\n                this->bytes(v.bytes, v.len);\n                this->byte(opcode);\n                this->byte(mod_rm(Mod::Indirect, dst&7, rip&7));\n                this->word(this->disp32(y.label));\n            } return;\n        }\n    }\n\n    void Assembler::vpshufb(Ymm dst, Ymm x, Operand y) { this->op(0x66,0x380f,0x00, dst,x,y); }\n\n    void Assembler::vptest(Ymm x, Operand y) { this->op(0x66, 0x380f, 0x17, x,y); }\n\n    void Assembler::vbroadcastss(Ymm dst, Operand y) { this->op(0x66,0x380f,0x18, dst,y); }\n\n    void Assembler::jump(uint8_t condition, Label* l) {\n        \/\/ These conditional jumps can be either 2 bytes (short) or 6 bytes (near):\n        \/\/    7?     one-byte-disp\n        \/\/    0F 8? four-byte-disp\n        \/\/ We always use the near displacement to make updating labels simpler (no resizing).\n        this->byte(0x0f);\n        this->byte(condition);\n        this->word(this->disp32(l));\n    }\n    void Assembler::je (Label* l) { this->jump(0x84, l); }\n    void Assembler::jne(Label* l) { this->jump(0x85, l); }\n    void Assembler::jl (Label* l) { this->jump(0x8c, l); }\n    void Assembler::jc (Label* l) { this->jump(0x82, l); }\n\n    void Assembler::jmp(Label* l) {\n        \/\/ Like above in jump(), we could use 8-bit displacement here, but always use 32-bit.\n        this->byte(0xe9);\n        this->word(this->disp32(l));\n    }\n\n    void Assembler::vpmovzxwd(Ymm dst, Operand src) { this->op(0x66,0x380f,0x33, dst,src); }\n    void Assembler::vpmovzxbd(Ymm dst, Operand src) { this->op(0x66,0x380f,0x31, dst,src); }\n\n    void Assembler::vmovq(Operand dst, Xmm src) { this->op(0x66,0x0f,0xd6, src,dst); }\n\n    void Assembler::vmovd(Operand dst, Xmm src) { this->op(0x66,0x0f,0x7e, src,dst); }\n    void Assembler::vmovd(Xmm dst, Operand src) { this->op(0x66,0x0f,0x6e, dst,src); }\n\n    void Assembler::vpinsrd(Xmm dst, Xmm src, Operand y, int imm) {\n        this->op(0x66,0x3a0f,0x22, dst,src,y);\n        this->imm_byte_after_operand(y, imm);\n    }\n    void Assembler::vpinsrw(Xmm dst, Xmm src, Operand y, int imm) {\n        this->op(0x66,0x0f,0xc4, dst,src,y);\n        this->imm_byte_after_operand(y, imm);\n    }\n    void Assembler::vpinsrb(Xmm dst, Xmm src, Operand y, int imm) {\n        this->op(0x66,0x3a0f,0x20, dst,src,y);\n        this->imm_byte_after_operand(y, imm);\n    }\n\n    void Assembler::vextracti128(Operand dst, Ymm src, int imm) {\n        this->op(0x66,0x3a0f,0x39, src,dst);\n        SkASSERT(dst.kind != Operand::LABEL);\n        this->byte(imm);\n    }\n    void Assembler::vpextrd(Operand dst, Xmm src, int imm) {\n        this->op(0x66,0x3a0f,0x16, src,dst);\n        SkASSERT(dst.kind != Operand::LABEL);\n        this->byte(imm);\n    }\n    void Assembler::vpextrw(Operand dst, Xmm src, int imm) {\n        this->op(0x66,0x3a0f,0x15, src,dst);\n        SkASSERT(dst.kind != Operand::LABEL);\n        this->byte(imm);\n    }\n    void Assembler::vpextrb(Operand dst, Xmm src, int imm) {\n        this->op(0x66,0x3a0f,0x14, src,dst);\n        SkASSERT(dst.kind != Operand::LABEL);\n        this->byte(imm);\n    }\n\n    void Assembler::vgatherdps(Ymm dst, Scale scale, Ymm ix, GP64 base, Ymm mask) {\n        \/\/ Unlike most instructions, no aliasing is permitted here.\n        SkASSERT(dst != ix);\n        SkASSERT(dst != mask);\n        SkASSERT(mask != ix);\n\n        int prefix = 0x66,\n            map    = 0x380f,\n            opcode = 0x92;\n        VEX v = vex(0, dst>>3, ix>>3, base>>3,\n                    map, mask, \/*ymm?*\/1, prefix);\n        this->bytes(v.bytes, v.len);\n        this->byte(opcode);\n        this->byte(mod_rm(Mod::Indirect, dst&7, rsp\/*use SIB*\/));\n        this->byte(sib(scale, ix&7, base&7));\n    }\n\n    \/\/ https:\/\/static.docs.arm.com\/ddi0596\/a\/DDI_0596_ARM_a64_instruction_set_architecture.pdf\n\n    static int operator\"\" _mask(unsigned long long bits) { return (1<<(int)bits)-1; }\n\n    void Assembler::op(uint32_t hi, V m, uint32_t lo, V n, V d) {\n        this->word( (hi & 11_mask) << 21\n                  | (m  &  5_mask) << 16\n                  | (lo &  6_mask) << 10\n                  | (n  &  5_mask) <<  5\n                  | (d  &  5_mask) <<  0);\n    }\n    void Assembler::op(uint32_t op22, V n, V d, int imm) {\n        this->word( (op22 & 22_mask) << 10\n                  | imm  \/\/ size and location depends on the instruction\n                  | (n    &  5_mask) <<  5\n                  | (d    &  5_mask) <<  0);\n    }\n\n    void Assembler::and16b(V d, V n, V m) { this->op(0b0'1'0'01110'00'1, m, 0b00011'1, n, d); }\n    void Assembler::orr16b(V d, V n, V m) { this->op(0b0'1'0'01110'10'1, m, 0b00011'1, n, d); }\n    void Assembler::eor16b(V d, V n, V m) { this->op(0b0'1'1'01110'00'1, m, 0b00011'1, n, d); }\n    void Assembler::bic16b(V d, V n, V m) { this->op(0b0'1'0'01110'01'1, m, 0b00011'1, n, d); }\n    void Assembler::bsl16b(V d, V n, V m) { this->op(0b0'1'1'01110'01'1, m, 0b00011'1, n, d); }\n    void Assembler::not16b(V d, V n)      { this->op(0b0'1'1'01110'00'10000'00101'10,  n, d); }\n\n    void Assembler::add4s(V d, V n, V m) { this->op(0b0'1'0'01110'10'1, m, 0b10000'1, n, d); }\n    void Assembler::sub4s(V d, V n, V m) { this->op(0b0'1'1'01110'10'1, m, 0b10000'1, n, d); }\n    void Assembler::mul4s(V d, V n, V m) { this->op(0b0'1'0'01110'10'1, m, 0b10011'1, n, d); }\n\n    void Assembler::cmeq4s(V d, V n, V m) { this->op(0b0'1'1'01110'10'1, m, 0b10001'1, n, d); }\n    void Assembler::cmgt4s(V d, V n, V m) { this->op(0b0'1'0'01110'10'1, m, 0b0011'0'1, n, d); }\n\n    void Assembler::sub8h(V d, V n, V m) { this->op(0b0'1'1'01110'01'1, m, 0b10000'1, n, d); }\n    void Assembler::mul8h(V d, V n, V m) { this->op(0b0'1'0'01110'01'1, m, 0b10011'1, n, d); }\n\n    void Assembler::fadd4s(V d, V n, V m) { this->op(0b0'1'0'01110'0'0'1, m, 0b11010'1, n, d); }\n    void Assembler::fsub4s(V d, V n, V m) { this->op(0b0'1'0'01110'1'0'1, m, 0b11010'1, n, d); }\n    void Assembler::fmul4s(V d, V n, V m) { this->op(0b0'1'1'01110'0'0'1, m, 0b11011'1, n, d); }\n    void Assembler::fdiv4s(V d, V n, V m) { this->op(0b0'1'1'01110'0'0'1, m, 0b11111'1, n, d); }\n    void Assembler::fmin4s(V d, V n, V m) { this->op(0b0'1'0'01110'1'0'1, m, 0b11110'1, n, d); }\n    void Assembler::fmax4s(V d, V n, V m) { this->op(0b0'1'0'01110'0'0'1, m, 0b11110'1, n, d); }\n\n    void Assembler::fneg4s (V d, V n) { this->op(0b0'1'1'01110'1'0'10000'01111'10, n,d); }\n    void Assembler::fsqrt4s(V d, V n) { this->op(0b0'1'1'01110'1'0'10000'11111'10, n,d); }\n\n    void Assembler::fcmeq4s(V d, V n, V m) { this->op(0b0'1'0'01110'0'0'1, m, 0b1110'0'1, n, d); }\n    void Assembler::fcmgt4s(V d, V n, V m) { this->op(0b0'1'1'01110'1'0'1, m, 0b1110'0'1, n, d); }\n    void Assembler::fcmge4s(V d, V n, V m) { this->op(0b0'1'1'01110'0'0'1, m, 0b1110'0'1, n, d); }\n\n    void Assembler::fmla4s(V d, V n, V m) { this->op(0b0'1'0'01110'0'0'1, m, 0b11001'1, n, d); }\n    void Assembler::fmls4s(V d, V n, V m) { this->op(0b0'1'0'01110'1'0'1, m, 0b11001'1, n, d); }\n\n    void Assembler::tbl(V d, V n, V m) { this->op(0b0'1'001110'00'0, m, 0b0'00'0'00, n, d); }\n\n    void Assembler::uzp14s(V d, V n, V m) { this->op(0b0'1'001110'10'0, m, 0b0'0'01'10, n, d); }\n    void Assembler::uzp24s(V d, V n, V m) { this->op(0b0'1'001110'10'0, m, 0b0'1'01'10, n, d); }\n    void Assembler::zip14s(V d, V n, V m) { this->op(0b0'1'001110'10'0, m, 0b0'0'11'10, n, d); }\n    void Assembler::zip24s(V d, V n, V m) { this->op(0b0'1'001110'10'0, m, 0b0'1'11'10, n, d); }\n\n    void Assembler::sli4s(V d, V n, int imm5) {\n        this->op(0b0'1'1'011110'0100'000'01010'1,    n, d, ( imm5 & 5_mask)<<16);\n    }\n    void Assembler::shl4s(V d, V n, int imm5) {\n        this->op(0b0'1'0'011110'0100'000'01010'1,    n, d, ( imm5 & 5_mask)<<16);\n    }\n    void Assembler::sshr4s(V d, V n, int imm5) {\n        this->op(0b0'1'0'011110'0100'000'00'0'0'0'1, n, d, (-imm5 & 5_mask)<<16);\n    }\n    void Assembler::ushr4s(V d, V n, int imm5) {\n        this->op(0b0'1'1'011110'0100'000'00'0'0'0'1, n, d, (-imm5 & 5_mask)<<16);\n    }\n    void Assembler::ushr8h(V d, V n, int imm4) {\n        this->op(0b0'1'1'011110'0010'000'00'0'0'0'1, n, d, (-imm4 & 4_mask)<<16);\n    }\n\n    void Assembler::scvtf4s (V d, V n) { this->op(0b0'1'0'01110'0'0'10000'11101'10, n,d); }\n    void Assembler::fcvtzs4s(V d, V n) { this->op(0b0'1'0'01110'1'0'10000'1101'1'10, n,d); }\n    void Assembler::fcvtns4s(V d, V n) { this->op(0b0'1'0'01110'0'0'10000'1101'0'10, n,d); }\n    void Assembler::frintp4s(V d, V n) { this->op(0b0'1'0'01110'1'0'10000'1100'0'10, n,d); }\n    void Assembler::frintm4s(V d, V n) { this->op(0b0'1'0'01110'0'0'10000'1100'1'10, n,d); }\n\n    void Assembler::fcvtn(V d, V n) { this->op(0b0'0'0'01110'0'0'10000'10110'10, n,d); }\n    void Assembler::fcvtl(V d, V n) { this->op(0b0'0'0'01110'0'0'10000'10111'10, n,d); }\n\n    void Assembler::xtns2h(V d, V n) { this->op(0b0'0'0'01110'01'10000'10010'10, n,d); }\n    void Assembler::xtnh2b(V d, V n) { this->op(0b0'0'0'01110'00'10000'10010'10, n,d); }\n\n    void Assembler::uxtlb2h(V d, V n) { this->op(0b0'0'1'011110'0001'000'10100'1, n,d); }\n    void Assembler::uxtlh2s(V d, V n) { this->op(0b0'0'1'011110'0010'000'10100'1, n,d); }\n\n    void Assembler::uminv4s(V d, V n) { this->op(0b0'1'1'01110'10'11000'1'1010'10, n,d); }\n\n    void Assembler::brk(int imm16) {\n        this->op(0b11010100'001'00000000000, (imm16 & 16_mask) << 5);\n    }\n\n    void Assembler::ret(X n) { this->op(0b1101011'0'0'10'11111'0000'0'0, n, (X)0); }\n\n    void Assembler::add(X d, X n, int imm12) {\n        this->op(0b1'0'0'10001'00'000000000000, n,d, (imm12 & 12_mask) << 10);\n    }\n    void Assembler::sub(X d, X n, int imm12) {\n        this->op(0b1'1'0'10001'00'000000000000, n,d, (imm12 & 12_mask) << 10);\n    }\n    void Assembler::subs(X d, X n, int imm12) {\n        this->op(0b1'1'1'10001'00'000000000000, n,d, (imm12 & 12_mask) << 10);\n    }\n\n    void Assembler::add(X d, X n, X m, Shift shift, int imm6) {\n        SkASSERT(shift != ROR);\n\n        int imm = (imm6  & 6_mask) << 0\n                | (m     & 5_mask) << 6\n                | (0     & 1_mask) << 11\n                | (shift & 2_mask) << 12;\n        this->op(0b1'0'0'01011'00'0'00000'000000, n,d, imm << 10);\n    }\n\n    void Assembler::b(Condition cond, Label* l) {\n        const int imm19 = this->disp19(l);\n        this->op(0b0101010'0'00000000000000, (X)0, (V)cond, (imm19 & 19_mask) << 5);\n    }\n    void Assembler::cbz(X t, Label* l) {\n        const int imm19 = this->disp19(l);\n        this->op(0b1'011010'0'00000000000000, (X)0, t, (imm19 & 19_mask) << 5);\n    }\n    void Assembler::cbnz(X t, Label* l) {\n        const int imm19 = this->disp19(l);\n        this->op(0b1'011010'1'00000000000000, (X)0, t, (imm19 & 19_mask) << 5);\n    }\n\n    void Assembler::ldrd(X dst, X src, int imm12) {\n        this->op(0b11'111'0'01'01'000000000000, src, dst, (imm12 & 12_mask) << 10);\n    }\n    void Assembler::ldrs(X dst, X src, int imm12) {\n        this->op(0b10'111'0'01'01'000000000000, src, dst, (imm12 & 12_mask) << 10);\n    }\n    void Assembler::ldrh(X dst, X src, int imm12) {\n        this->op(0b01'111'0'01'01'000000000000, src, dst, (imm12 & 12_mask) << 10);\n    }\n    void Assembler::ldrb(X dst, X src, int imm12) {\n        this->op(0b00'111'0'01'01'000000000000, src, dst, (imm12 & 12_mask) << 10);\n    }\n\n    void Assembler::ldrq(V dst, X src, int imm12) {\n        this->op(0b00'111'1'01'11'000000000000, src, dst, (imm12 & 12_mask) << 10);\n    }\n    void Assembler::ldrd(V dst, X src, int imm12) {\n        this->op(0b11'111'1'01'01'000000000000, src, dst, (imm12 & 12_mask) << 10);\n    }\n    void Assembler::ldrs(V dst, X src, int imm12) {\n        this->op(0b10'111'1'01'01'000000000000, src, dst, (imm12 & 12_mask) << 10);\n    }\n    void Assembler::ldrh(V dst, X src, int imm12) {\n        this->op(0b01'111'1'01'01'000000000000, src, dst, (imm12 & 12_mask) << 10);\n    }\n    void Assembler::ldrb(V dst, X src, int imm12) {\n        this->op(0b00'111'1'01'01'000000000000, src, dst, (imm12 & 12_mask) << 10);\n    }\n\n    void Assembler::strs(X src, X dst, int imm12) {\n        this->op(0b10'111'0'01'00'000000000000, dst, src, (imm12 & 12_mask) << 10);\n    }\n\n    void Assembler::strq(V src, X dst, int imm12) {\n        this->op(0b00'111'1'01'10'000000000000, dst, src, (imm12 & 12_mask) << 10);\n    }\n    void Assembler::strd(V src, X dst, int imm12) {\n        this->op(0b11'111'1'01'00'000000000000, dst, src, (imm12 & 12_mask) << 10);\n    }\n    void Assembler::strs(V src, X dst, int imm12) {\n        this->op(0b10'111'1'01'00'000000000000, dst, src, (imm12 & 12_mask) << 10);\n    }\n    void Assembler::strh(V src, X dst, int imm12) {\n        this->op(0b01'111'1'01'00'000000000000, dst, src, (imm12 & 12_mask) << 10);\n    }\n    void Assembler::strb(V src, X dst, int imm12) {\n        this->op(0b00'111'1'01'00'000000000000, dst, src, (imm12 & 12_mask) << 10);\n    }\n\n    void Assembler::movs(X dst, V src, int lane) {\n        int imm5 = (lane << 3) | 0b100;\n        this->op(0b0'0'0'01110000'00000'0'01'1'1'1, src, dst, (imm5 & 5_mask) << 16);\n    }\n    void Assembler::inss(V dst, X src, int lane) {\n        int imm5 = (lane << 3) | 0b100;\n        this->op(0b0'1'0'01110000'00000'0'0011'1, src, dst, (imm5 & 5_mask) << 16);\n    }\n\n\n    void Assembler::ldrq(V dst, Label* l) {\n        const int imm19 = this->disp19(l);\n        this->op(0b10'011'1'00'00000000000000, (V)0, dst, (imm19 & 19_mask) << 5);\n    }\n\n    void Assembler::dup4s(V dst, X src) {\n        this->op(0b0'1'0'01110000'00100'0'0001'1, src, dst);\n    }\n\n    void Assembler::ld1r4s(V dst, X src) {\n        this->op(0b0'1'0011010'1'0'00000'110'0'10, src, dst);\n    }\n    void Assembler::ld1r8h(V dst, X src) {\n        this->op(0b0'1'0011010'1'0'00000'110'0'01, src, dst);\n    }\n    void Assembler::ld1r16b(V dst, X src) {\n        this->op(0b0'1'0011010'1'0'00000'110'0'00, src, dst);\n    }\n\n    void Assembler::ld24s(V dst, X src) { this->op(0b0'1'0011000'1'000000'1000'10, src, dst); }\n    void Assembler::ld44s(V dst, X src) { this->op(0b0'1'0011000'1'000000'0000'10, src, dst); }\n    void Assembler::st24s(V src, X dst) { this->op(0b0'1'0011000'0'000000'1000'10, dst, src); }\n    void Assembler::st44s(V src, X dst) { this->op(0b0'1'0011000'0'000000'0000'10, dst, src); }\n\n    void Assembler::ld24s(V dst, X src, int lane) {\n        int Q = (lane & 2)>>1,\n            S = (lane & 1);\n                 \/*  Q                       S *\/\n        this->op(0b0'0'0011010'1'1'00000'100'0'00, src, dst, (Q<<30)|(S<<12));\n    }\n    void Assembler::ld44s(V dst, X src, int lane) {\n        int Q = (lane & 2)>>1,\n            S = (lane & 1);\n        this->op(0b0'0'0011010'1'1'00000'101'0'00, src, dst, (Q<<30)|(S<<12));\n    }\n\n    void Assembler::label(Label* l) {\n        if (fCode) {\n            \/\/ The instructions all currently point to l->offset.\n            \/\/ We'll want to add a delta to point them to here.\n            int here = (int)this->size();\n            int delta = here - l->offset;\n            l->offset = here;\n\n            if (l->kind == Label::ARMDisp19) {\n                for (int ref : l->references) {\n                    \/\/ ref points to a 32-bit instruction with 19-bit displacement in instructions.\n                    uint32_t inst;\n                    memcpy(&inst, fCode + ref, 4);\n\n                    \/\/ [ 8 bits to preserve] [ 19 bit signed displacement ] [ 5 bits to preserve ]\n                    int disp = (int)(inst << 8) >> 13;\n\n                    disp += delta\/4;  \/\/ delta is in bytes, we want instructions.\n\n                    \/\/ Put it all back together, preserving the high 8 bits and low 5.\n                    inst = ((disp << 5) &  (19_mask << 5))\n                         | ((inst     ) & ~(19_mask << 5));\n                    memcpy(fCode + ref, &inst, 4);\n                }\n            }\n\n            if (l->kind == Label::X86Disp32) {\n                for (int ref : l->references) {\n                    \/\/ ref points to a 32-bit displacement in bytes.\n                    int disp;\n                    memcpy(&disp, fCode + ref, 4);\n\n                    disp += delta;\n\n                    memcpy(fCode + ref, &disp, 4);\n                }\n            }\n        }\n    }\n\n    void Program::eval(int n, void* args[]) const {\n    #define SKVM_JIT_STATS 0\n    #if SKVM_JIT_STATS\n        static std::atomic<int64_t>  calls{0}, jits{0},\n                                    pixels{0}, fast{0};\n        pixels += n;\n        if (0 == calls++) {\n            atexit([]{\n                int64_t num = jits .load(),\n                        den = calls.load();\n                SkDebugf(\"%.3g%% of %lld eval() calls went through JIT.\\n\", (100.0 * num)\/den, den);\n                num = fast  .load();\n                den = pixels.load();\n                SkDebugf(\"%.3g%% of %lld pixels went through JIT.\\n\", (100.0 * num)\/den, den);\n            });\n        }\n    #endif\n\n    #if !defined(SKVM_JIT_BUT_IGNORE_IT)\n        const void* jit_entry = fImpl->jit_entry.load();\n        \/\/ jit_entry may be null either simply because we can't JIT, or when using LLVM\n        \/\/ if the work represented by fImpl->llvm_compiling hasn't finished yet.\n        \/\/\n        \/\/ Ordinarily we'd never find ourselves with non-null jit_entry and !gSkVMAllowJIT, but it\n        \/\/ can happen during interactive programs like Viewer that toggle gSkVMAllowJIT on and off,\n        \/\/ due to timing or program caching.\n        if (jit_entry != nullptr && gSkVMAllowJIT) {\n        #if SKVM_JIT_STATS\n            jits++;\n            fast += n;\n        #endif\n            void** a = args;\n            switch (fImpl->strides.size()) {\n                case 0: return ((void(*)(int                        ))jit_entry)(n               );\n                case 1: return ((void(*)(int,void*                  ))jit_entry)(n,a[0]          );\n                case 2: return ((void(*)(int,void*,void*            ))jit_entry)(n,a[0],a[1]     );\n                case 3: return ((void(*)(int,void*,void*,void*      ))jit_entry)(n,a[0],a[1],a[2]);\n                case 4: return ((void(*)(int,void*,void*,void*,void*))jit_entry)\n                                (n,a[0],a[1],a[2],a[3]);\n                case 5: return ((void(*)(int,void*,void*,void*,void*,void*))jit_entry)\n                                (n,a[0],a[1],a[2],a[3],a[4]);\n                case 6: return ((void(*)(int,void*,void*,void*,void*,void*,void*))jit_entry)\n                                (n,a[0],a[1],a[2],a[3],a[4],a[5]);\n                case 7: return ((void(*)(int,void*,void*,void*,void*,void*,void*,void*))jit_entry)\n                                (n,a[0],a[1],a[2],a[3],a[4],a[5],a[6]);\n                default: break; \/\/SkASSERT(fImpl->strides.size() <= 7);\n            }\n        }\n    #endif\n\n        \/\/ So we'll sometimes use the interpreter here even if later calls will use the JIT.\n        SkOpts::interpret_skvm(fImpl->instructions.data(), (int)fImpl->instructions.size(),\n                               this->nregs(), this->loop(), fImpl->strides.data(), this->nargs(),\n                               n, args);\n    }\n\n    #if defined(SKVM_LLVM)\n    \/\/ -- SKVM_LLVM --------------------------------------------------------------------------------\n    void Program::setupLLVM(const std::vector<OptimizedInstruction>& instructions,\n                            const char* debug_name) {\n        auto ctx = std::make_unique<llvm::LLVMContext>();\n\n        auto mod = std::make_unique<llvm::Module>(\"\", *ctx);\n        \/\/ All the scary bare pointers from here on are owned by ctx or mod, I think.\n\n        \/\/ Everything I've tested runs faster at K=8 (using ymm) than K=16 (zmm) on SKX machines.\n        const int K = (true && SkCpu::Supports(SkCpu::HSW)) ? 8 : 4;\n\n        llvm::Type *ptr = llvm::Type::getInt8Ty(*ctx)->getPointerTo(),\n                   *i32 = llvm::Type::getInt32Ty(*ctx);\n\n        std::vector<llvm::Type*> arg_types = { i32 };\n        for (size_t i = 0; i < fImpl->strides.size(); i++) {\n            arg_types.push_back(ptr);\n        }\n\n        llvm::FunctionType* fn_type = llvm::FunctionType::get(llvm::Type::getVoidTy(*ctx),\n                                                              arg_types, \/*vararg?=*\/false);\n        llvm::Function* fn\n            = llvm::Function::Create(fn_type, llvm::GlobalValue::ExternalLinkage, debug_name, *mod);\n        for (size_t i = 0; i < fImpl->strides.size(); i++) {\n            fn->addParamAttr(i+1, llvm::Attribute::NoAlias);\n        }\n\n        llvm::BasicBlock *enter  = llvm::BasicBlock::Create(*ctx, \"enter\" , fn),\n                         *hoistK = llvm::BasicBlock::Create(*ctx, \"hoistK\", fn),\n                         *testK  = llvm::BasicBlock::Create(*ctx, \"testK\" , fn),\n                         *loopK  = llvm::BasicBlock::Create(*ctx, \"loopK\" , fn),\n                         *hoist1 = llvm::BasicBlock::Create(*ctx, \"hoist1\", fn),\n                         *test1  = llvm::BasicBlock::Create(*ctx, \"test1\" , fn),\n                         *loop1  = llvm::BasicBlock::Create(*ctx, \"loop1\" , fn),\n                         *leave  = llvm::BasicBlock::Create(*ctx, \"leave\" , fn);\n\n        using IRBuilder = llvm::IRBuilder<>;\n\n        llvm::PHINode*                 n;\n        std::vector<llvm::PHINode*> args;\n        std::vector<llvm::Value*> vals(instructions.size());\n\n        auto emit = [&](size_t i, bool scalar, IRBuilder* b) {\n            auto [op, x,y,z,w, immA,immB,immC, death,can_hoist] = instructions[i];\n\n            llvm::Type *i1    = llvm::Type::getInt1Ty (*ctx),\n                       *i8    = llvm::Type::getInt8Ty (*ctx),\n                       *i16   = llvm::Type::getInt16Ty(*ctx),\n                       *f32   = llvm::Type::getFloatTy(*ctx),\n                       *I1    = scalar ? i1    : llvm::VectorType::get(i1 , K, false  ),\n                       *I8    = scalar ? i8    : llvm::VectorType::get(i8 , K, false  ),\n                       *I16   = scalar ? i16   : llvm::VectorType::get(i16, K, false  ),\n                       *I32   = scalar ? i32   : llvm::VectorType::get(i32, K, false  ),\n                       *F32   = scalar ? f32   : llvm::VectorType::get(f32, K, false  );\n\n            auto I  = [&](llvm::Value* v) { return b->CreateBitCast(v, I32  ); };\n            auto F  = [&](llvm::Value* v) { return b->CreateBitCast(v, F32  ); };\n\n            auto S = [&](llvm::Type* dst, llvm::Value* v) { return b->CreateSExt(v, dst); };\n\n            llvm::Type* vt = nullptr;\n            switch (llvm::Type* t = nullptr; op) {\n                default:\n                    SkDebugf(\"can't llvm %s (%d)\\n\", name(op), op);\n                    return false;\n\n                case Op::assert_true: \/*TODO*\/ break;\n\n                case Op::trace_line:\n                case Op::trace_var:\n                case Op::trace_call:\n                    \/* Only supported in the interpreter. *\/\n                    break;\n\n                case Op::index:\n                    if (I32->isVectorTy()) {\n                        std::vector<llvm::Constant*> iota(K);\n                        for (int j = 0; j < K; j++) {\n                            iota[j] = b->getInt32(j);\n                        }\n                        vals[i] = b->CreateSub(b->CreateVectorSplat(K, n),\n                                               llvm::ConstantVector::get(iota));\n                    } else {\n                        vals[i] = n;\n                    } break;\n\n                case Op::load8:  t = I8 ; goto load;\n                case Op::load16: t = I16; goto load;\n                case Op::load32: t = I32; goto load;\n                load: {\n                    llvm::Value* ptr = b->CreateBitCast(args[immA], t->getPointerTo());\n                    vals[i] = b->CreateZExt(\n                            b->CreateAlignedLoad(t, ptr, llvm::MaybeAlign{1}), I32);\n                } break;\n\n\n                case Op::splat: vals[i] = llvm::ConstantInt::get(I32, immA); break;\n\n                case Op::uniform32: {\n                    llvm::Value* ptr = b->CreateBitCast(\n                            b->CreateConstInBoundsGEP1_32(i8, args[immA], immB),\n                            i32->getPointerTo());\n                    llvm::Value* val = b->CreateZExt(\n                            b->CreateAlignedLoad(i32, ptr, llvm::MaybeAlign{1}), i32);\n                    vals[i] = I32->isVectorTy() ? b->CreateVectorSplat(K, val)\n                                                : val;\n                } break;\n\n                case Op::gather8:  t = i8 ; vt = I8; goto gather;\n                case Op::gather16: t = i16; vt = I16; goto gather;\n                case Op::gather32: t = i32; vt = I32; goto gather;\n                gather: {\n                    \/\/ Our gather base pointer is immB bytes off of uniform immA.\n                    llvm::Value* base =\n                        b->CreateLoad(b->CreateBitCast(\n                                b->CreateConstInBoundsGEP1_32(i8, args[immA],immB),\n                                t->getPointerTo()->getPointerTo()));\n\n                    llvm::Value* ptr = b->CreateInBoundsGEP(t, base, vals[x]);\n                    llvm::Value* gathered;\n                    if (ptr->getType()->isVectorTy()) {\n                        gathered = b->CreateMaskedGather(\n                                vt,\n                                ptr,\n                                llvm::Align{1});\n                    } else {\n                        gathered = b->CreateAlignedLoad(vt, ptr, llvm::MaybeAlign{1});\n                    }\n                    vals[i] = b->CreateZExt(gathered, I32);\n                } break;\n\n                case Op::store8:  t = I8 ; goto store;\n                case Op::store16: t = I16; goto store;\n                case Op::store32: t = I32; goto store;\n                store: {\n                    llvm::Value* val = b->CreateTrunc(vals[x], t);\n                    llvm::Value* ptr = b->CreateBitCast(args[immA],\n                                                        val->getType()->getPointerTo());\n                    vals[i] = b->CreateAlignedStore(val, ptr, llvm::MaybeAlign{1});\n                } break;\n\n                case Op::bit_and:   vals[i] = b->CreateAnd(vals[x], vals[y]); break;\n                case Op::bit_or :   vals[i] = b->CreateOr (vals[x], vals[y]); break;\n                case Op::bit_xor:   vals[i] = b->CreateXor(vals[x], vals[y]); break;\n                case Op::bit_clear: vals[i] = b->CreateAnd(vals[x], b->CreateNot(vals[y])); break;\n\n                case Op::select:\n                    vals[i] = b->CreateSelect(b->CreateTrunc(vals[x], I1), vals[y], vals[z]);\n                    break;\n\n                case Op::add_i32: vals[i] = b->CreateAdd(vals[x], vals[y]); break;\n                case Op::sub_i32: vals[i] = b->CreateSub(vals[x], vals[y]); break;\n                case Op::mul_i32: vals[i] = b->CreateMul(vals[x], vals[y]); break;\n\n                case Op::shl_i32: vals[i] = b->CreateShl (vals[x], immA); break;\n                case Op::sra_i32: vals[i] = b->CreateAShr(vals[x], immA); break;\n                case Op::shr_i32: vals[i] = b->CreateLShr(vals[x], immA); break;\n\n                case Op:: eq_i32: vals[i] = S(I32, b->CreateICmpEQ (vals[x], vals[y])); break;\n                case Op:: gt_i32: vals[i] = S(I32, b->CreateICmpSGT(vals[x], vals[y])); break;\n\n                case Op::add_f32: vals[i] = I(b->CreateFAdd(F(vals[x]), F(vals[y]))); break;\n                case Op::sub_f32: vals[i] = I(b->CreateFSub(F(vals[x]), F(vals[y]))); break;\n                case Op::mul_f32: vals[i] = I(b->CreateFMul(F(vals[x]), F(vals[y]))); break;\n                case Op::div_f32: vals[i] = I(b->CreateFDiv(F(vals[x]), F(vals[y]))); break;\n\n                case Op:: eq_f32: vals[i] = S(I32, b->CreateFCmpOEQ(F(vals[x]), F(vals[y]))); break;\n                case Op::neq_f32: vals[i] = S(I32, b->CreateFCmpUNE(F(vals[x]), F(vals[y]))); break;\n                case Op:: gt_f32: vals[i] = S(I32, b->CreateFCmpOGT(F(vals[x]), F(vals[y]))); break;\n                case Op::gte_f32: vals[i] = S(I32, b->CreateFCmpOGE(F(vals[x]), F(vals[y]))); break;\n\n                case Op::fma_f32:\n                    vals[i] = I(b->CreateIntrinsic(llvm::Intrinsic::fma, {F32},\n                                                   {F(vals[x]), F(vals[y]), F(vals[z])}));\n                    break;\n\n                case Op::fms_f32:\n                    vals[i] = I(b->CreateIntrinsic(llvm::Intrinsic::fma, {F32},\n                                                   {F(vals[x]), F(vals[y]),\n                                                    b->CreateFNeg(F(vals[z]))}));\n                    break;\n\n                case Op::fnma_f32:\n                    vals[i] = I(b->CreateIntrinsic(llvm::Intrinsic::fma, {F32},\n                                                   {b->CreateFNeg(F(vals[x])), F(vals[y]),\n                                                    F(vals[z])}));\n                    break;\n\n                case Op::ceil:\n                    vals[i] = I(b->CreateUnaryIntrinsic(llvm::Intrinsic::ceil, F(vals[x])));\n                    break;\n                case Op::floor:\n                    vals[i] = I(b->CreateUnaryIntrinsic(llvm::Intrinsic::floor, F(vals[x])));\n                    break;\n\n                case Op::max_f32:\n                    vals[i] = I(b->CreateSelect(b->CreateFCmpOLT(F(vals[x]), F(vals[y])),\n                                                F(vals[y]), F(vals[x])));\n                    break;\n                case Op::min_f32:\n                    vals[i] = I(b->CreateSelect(b->CreateFCmpOLT(F(vals[y]), F(vals[x])),\n                                                F(vals[y]), F(vals[x])));\n                    break;\n\n                case Op::sqrt_f32:\n                    vals[i] = I(b->CreateUnaryIntrinsic(llvm::Intrinsic::sqrt, F(vals[x])));\n                    break;\n\n                case Op::to_f32: vals[i] = I(b->CreateSIToFP(  vals[x] , F32)); break;\n                case Op::trunc : vals[i] =   b->CreateFPToSI(F(vals[x]), I32) ; break;\n                case Op::round : {\n                    \/\/ Basic impl when we can't use cvtps2dq and co.\n                    auto round = b->CreateUnaryIntrinsic(llvm::Intrinsic::rint, F(vals[x]));\n                    vals[i] = b->CreateFPToSI(round, I32);\n\n                #if 1 && defined(SK_CPU_X86)\n                    \/\/ Using b->CreateIntrinsic(..., {}, {...}) to avoid name mangling.\n                    if (scalar) {\n                        \/\/ cvtss2si is float x4 -> int, ignoring input lanes 1,2,3.  \u00af\\_(\u30c4)_\/\u00af\n                        llvm::Value* v = llvm::UndefValue::get(\n                                llvm::VectorType::get(f32, 4, false));\n                        v = b->CreateInsertElement(v, F(vals[x]), (uint64_t)0);\n                        vals[i] = b->CreateIntrinsic(llvm::Intrinsic::x86_sse_cvtss2si, {}, {v});\n                    } else {\n                        SkASSERT(K == 4  || K == 8);\n                        auto intr = K == 4 ?   llvm::Intrinsic::x86_sse2_cvtps2dq :\n                                 \/* K == 8 ?*\/ llvm::Intrinsic::x86_avx_cvt_ps2dq_256;\n                        vals[i] = b->CreateIntrinsic(intr, {}, {F(vals[x])});\n                    }\n                #endif\n                } break;\n\n            }\n            return true;\n        };\n\n        {\n            IRBuilder b(enter);\n            b.CreateBr(hoistK);\n        }\n\n        \/\/ hoistK: emit each hoistable vector instruction; goto testK;\n        \/\/ LLVM can do this sort of thing itself, but we've got the information cheap,\n        \/\/ and pointer aliasing makes it easier to manually hoist than teach LLVM it's safe.\n        {\n            IRBuilder b(hoistK);\n\n            \/\/ Hoisted instructions will need args (think, uniforms), so set that up now.\n            \/\/ These phi nodes are degenerate... they'll always be the passed-in args from enter.\n            \/\/ Later on when we start looping the phi nodes will start looking useful.\n            llvm::Argument* arg = fn->arg_begin();\n            (void)arg++;  \/\/ Leave n as nullptr... it'd be a bug to use n in a hoisted instruction.\n            for (size_t i = 0; i < fImpl->strides.size(); i++) {\n                args.push_back(b.CreatePHI(arg->getType(), 1));\n                args.back()->addIncoming(arg++, enter);\n            }\n\n            for (size_t i = 0; i < instructions.size(); i++) {\n                if (instructions[i].can_hoist && !emit(i, false, &b)) {\n                    return;\n                }\n            }\n\n            b.CreateBr(testK);\n        }\n\n        \/\/ testK:  if (N >= K) goto loopK; else goto hoist1;\n        {\n            IRBuilder b(testK);\n\n            \/\/ New phi nodes for `n` and each pointer argument from hoistK; later we'll add loopK.\n            \/\/ These also start as the initial function arguments; hoistK can't have changed them.\n            llvm::Argument* arg = fn->arg_begin();\n\n            n = b.CreatePHI(arg->getType(), 2);\n            n->addIncoming(arg++, hoistK);\n\n            for (size_t i = 0; i < fImpl->strides.size(); i++) {\n                args[i] = b.CreatePHI(arg->getType(), 2);\n                args[i]->addIncoming(arg++, hoistK);\n            }\n\n            b.CreateCondBr(b.CreateICmpSGE(n, b.getInt32(K)), loopK, hoist1);\n        }\n\n        \/\/ loopK:  ... insts on K x T vectors; N -= K, args += K*stride; goto testK;\n        {\n            IRBuilder b(loopK);\n            for (size_t i = 0; i < instructions.size(); i++) {\n                if (!instructions[i].can_hoist && !emit(i, false, &b)) {\n                    return;\n                }\n            }\n\n            \/\/ n -= K\n            llvm::Value* n_next = b.CreateSub(n, b.getInt32(K));\n            n->addIncoming(n_next, loopK);\n\n            \/\/ Each arg ptr += K\n            for (size_t i = 0; i < fImpl->strides.size(); i++) {\n                llvm::Value* arg_next\n                    = b.CreateConstInBoundsGEP1_32(\n                            llvm::Type::getInt8Ty (*ctx),\n                            args[i],\n                            K*fImpl->strides[i]);\n                args[i]->addIncoming(arg_next, loopK);\n            }\n            b.CreateBr(testK);\n        }\n\n        \/\/ hoist1: emit each hoistable scalar instruction; goto test1;\n        {\n            IRBuilder b(hoist1);\n            for (size_t i = 0; i < instructions.size(); i++) {\n                if (instructions[i].can_hoist && !emit(i, true, &b)) {\n                    return;\n                }\n            }\n            b.CreateBr(test1);\n        }\n\n        \/\/ test1:  if (N >= 1) goto loop1; else goto leave;\n        {\n            IRBuilder b(test1);\n\n            \/\/ Set up new phi nodes for `n` and each pointer argument, now from hoist1 and loop1.\n            llvm::PHINode* n_new = b.CreatePHI(n->getType(), 2);\n            n_new->addIncoming(n, hoist1);\n            n = n_new;\n\n            for (size_t i = 0; i < fImpl->strides.size(); i++) {\n                llvm::PHINode* arg_new = b.CreatePHI(args[i]->getType(), 2);\n                arg_new->addIncoming(args[i], hoist1);\n                args[i] = arg_new;\n            }\n\n            b.CreateCondBr(b.CreateICmpSGE(n, b.getInt32(1)), loop1, leave);\n        }\n\n        \/\/ loop1:  ... insts on scalars; N -= 1, args += stride; goto test1;\n        {\n            IRBuilder b(loop1);\n            for (size_t i = 0; i < instructions.size(); i++) {\n                if (!instructions[i].can_hoist && !emit(i, true, &b)) {\n                    return;\n                }\n            }\n\n            \/\/ n -= 1\n            llvm::Value* n_next = b.CreateSub(n, b.getInt32(1));\n            n->addIncoming(n_next, loop1);\n\n            \/\/ Each arg ptr += 1\n            for (size_t i = 0; i < fImpl->strides.size(); i++) {\n                llvm::Value* arg_next\n                    = b.CreateConstInBoundsGEP1_32(\n                            llvm::Type::getInt8Ty (*ctx), args[i], fImpl->strides[i]);\n                args[i]->addIncoming(arg_next, loop1);\n            }\n            b.CreateBr(test1);\n        }\n\n        \/\/ leave:  ret\n        {\n            IRBuilder b(leave);\n            b.CreateRetVoid();\n        }\n\n        SkASSERT(false == llvm::verifyModule(*mod, &llvm::outs()));\n\n        if (true) {\n            SkString path = SkStringPrintf(\"\/tmp\/%s.bc\", debug_name);\n            std::error_code err;\n            llvm::raw_fd_ostream os(path.c_str(), err);\n            if (err) {\n                return;\n            }\n            llvm::WriteBitcodeToFile(*mod, os);\n        }\n\n        static SkOnce once;\n        once([]{\n            SkAssertResult(false == llvm::InitializeNativeTarget());\n            SkAssertResult(false == llvm::InitializeNativeTargetAsmPrinter());\n        });\n\n        if (llvm::ExecutionEngine* ee = llvm::EngineBuilder(std::move(mod))\n                                            .setEngineKind(llvm::EngineKind::JIT)\n                                            .setMCPU(llvm::sys::getHostCPUName())\n                                            .create()) {\n            fImpl->llvm_ctx = std::move(ctx);\n            fImpl->llvm_ee.reset(ee);\n\n            #if defined(SKVM_LLVM_WAIT_FOR_COMPILATION)\n            \/\/ Wait for llvm to compile\n            void* function = (void*)ee->getFunctionAddress(debug_name);\n            fImpl->jit_entry.store(function);\n            \/\/ We have to be careful here about what we close over and how, in case fImpl moves.\n            \/\/ fImpl itself may change, but its pointee fields won't, so close over them by value.\n            \/\/ Also, debug_name will almost certainly leave scope, so copy it.\n            #else\n            fImpl->llvm_compiling = std::async(std::launch::async, [dst  = &fImpl->jit_entry,\n                                                                    ee   =  fImpl->llvm_ee.get(),\n                                                                    name = std::string(debug_name)]{\n                \/\/ std::atomic<void*>*    dst;\n                \/\/ llvm::ExecutionEngine* ee;\n                \/\/ std::string            name;\n                dst->store( (void*)ee->getFunctionAddress(name.c_str()) );\n            });\n            #endif\n        }\n    }\n    #endif  \/\/ SKVM_LLVM\n\n    void Program::waitForLLVM() const {\n    #if defined(SKVM_LLVM) && !defined(SKVM_LLVM_WAIT_FOR_COMPILATION)\n        if (fImpl->llvm_compiling.valid()) {\n            fImpl->llvm_compiling.wait();\n        }\n    #endif\n    }\n\n    bool Program::hasJIT() const {\n        \/\/ Program::hasJIT() is really just a debugging \/ test aid,\n        \/\/ so we don't mind adding a sync point here to wait for compilation.\n        this->waitForLLVM();\n\n        return fImpl->jit_entry.load() != nullptr;\n    }\n\n    void Program::dropJIT() {\n    #if defined(SKVM_LLVM)\n        this->waitForLLVM();\n        fImpl->llvm_ee .reset(nullptr);\n        fImpl->llvm_ctx.reset(nullptr);\n    #elif defined(SKVM_JIT)\n        if (fImpl->dylib) {\n            close_dylib(fImpl->dylib);\n        } else if (auto jit_entry = fImpl->jit_entry.load()) {\n            unmap_jit_buffer(jit_entry, fImpl->jit_size);\n        }\n    #else\n        SkASSERT(!this->hasJIT());\n    #endif\n\n        fImpl->jit_entry.store(nullptr);\n        fImpl->jit_size  = 0;\n        fImpl->dylib     = nullptr;\n    }\n\n    Program::Program() : fImpl(std::make_unique<Impl>()) {}\n\n    Program::~Program() {\n        \/\/ Moved-from Programs may have fImpl == nullptr.\n        if (fImpl) {\n            this->dropJIT();\n        }\n    }\n\n    Program::Program(Program&& other) : fImpl(std::move(other.fImpl)) {}\n\n    Program& Program::operator=(Program&& other) {\n        fImpl = std::move(other.fImpl);\n        return *this;\n    }\n\n    Program::Program(const std::vector<OptimizedInstruction>& instructions,\n                     const std::vector<int>& strides,\n                     const char* debug_name, bool allow_jit) : Program() {\n        fImpl->strides = strides;\n        if (gSkVMAllowJIT && allow_jit) {\n        #if 1 && defined(SKVM_LLVM)\n            this->setupLLVM(instructions, debug_name);\n        #elif 1 && defined(SKVM_JIT)\n            this->setupJIT(instructions, debug_name);\n        #endif\n        }\n\n        \/\/ Might as well do this after setupLLVM() to get a little more time to compile.\n        this->setupInterpreter(instructions);\n    }\n\n    std::vector<InterpreterInstruction> Program::instructions() const { return fImpl->instructions; }\n    int  Program::nargs() const { return (int)fImpl->strides.size(); }\n    int  Program::nregs() const { return fImpl->regs; }\n    int  Program::loop () const { return fImpl->loop; }\n    bool Program::empty() const { return fImpl->instructions.empty(); }\n\n    \/\/ Translate OptimizedInstructions to InterpreterInstructions.\n    void Program::setupInterpreter(const std::vector<OptimizedInstruction>& instructions) {\n        \/\/ Register each instruction is assigned to.\n        std::vector<Reg> reg(instructions.size());\n\n        \/\/ This next bit is a bit more complicated than strictly necessary;\n        \/\/ we could just assign every instruction to its own register.\n        \/\/\n        \/\/ But recycling registers is fairly cheap, and good practice for the\n        \/\/ JITs where minimizing register pressure really is important.\n        \/\/\n        \/\/ We have effectively infinite registers, so we hoist any value we can.\n        \/\/ (The JIT may choose a more complex policy to reduce register pressure.)\n\n        fImpl->regs = 0;\n        std::vector<Reg> avail;\n\n        \/\/ Assign this value to a register, recycling them where we can.\n        auto assign_register = [&](Val id) {\n            const OptimizedInstruction& inst = instructions[id];\n\n            \/\/ If this is a real input and it's lifetime ends at this instruction,\n            \/\/ we can recycle the register it's occupying.\n            auto maybe_recycle_register = [&](Val input) {\n                if (input != NA && instructions[input].death == id) {\n                    avail.push_back(reg[input]);\n                }\n            };\n\n            \/\/ Take care to not recycle the same register twice.\n            const Val x = inst.x, y = inst.y, z = inst.z, w = inst.w;\n            if (true                      ) { maybe_recycle_register(x); }\n            if (y != x                    ) { maybe_recycle_register(y); }\n            if (z != x && z != y          ) { maybe_recycle_register(z); }\n            if (w != x && w != y && w != z) { maybe_recycle_register(w); }\n\n            \/\/ Instructions that die at themselves (stores) don't need a register.\n            if (inst.death != id) {\n                \/\/ Allocate a register if we have to, preferring to reuse anything available.\n                if (avail.empty()) {\n                    reg[id] = fImpl->regs++;\n                } else {\n                    reg[id] = avail.back();\n                    avail.pop_back();\n                }\n            }\n        };\n\n        \/\/ Assign a register to each hoisted instruction, then each non-hoisted loop instruction.\n        for (Val id = 0; id < (Val)instructions.size(); id++) {\n            if ( instructions[id].can_hoist) { assign_register(id); }\n        }\n        for (Val id = 0; id < (Val)instructions.size(); id++) {\n            if (!instructions[id].can_hoist) { assign_register(id); }\n        }\n\n        \/\/ Translate OptimizedInstructions to InterpreterIstructions by mapping values to\n        \/\/ registers.  This will be two passes, first hoisted instructions, then inside the loop.\n\n        \/\/ The loop begins at the fImpl->loop'th Instruction.\n        fImpl->loop = 0;\n        fImpl->instructions.reserve(instructions.size());\n\n        \/\/ Add a mapping for the N\/A sentinel Val to any arbitrary register\n        \/\/ so lookups don't have to know which arguments are used by which Ops.\n        auto lookup_register = [&](Val id) {\n            return id == NA ? (Reg)0\n                            : reg[id];\n        };\n\n        auto push_instruction = [&](Val id, const OptimizedInstruction& inst) {\n            InterpreterInstruction pinst{\n                inst.op,\n                lookup_register(id),\n                lookup_register(inst.x),\n                lookup_register(inst.y),\n                lookup_register(inst.z),\n                lookup_register(inst.w),\n                inst.immA,\n                inst.immB,\n                inst.immC,\n            };\n            fImpl->instructions.push_back(pinst);\n        };\n\n        for (Val id = 0; id < (Val)instructions.size(); id++) {\n            const OptimizedInstruction& inst = instructions[id];\n            if (inst.can_hoist) {\n                push_instruction(id, inst);\n                fImpl->loop++;\n            }\n        }\n        for (Val id = 0; id < (Val)instructions.size(); id++) {\n            const OptimizedInstruction& inst = instructions[id];\n            if (!inst.can_hoist) {\n                push_instruction(id, inst);\n            }\n        }\n    }\n\n#if defined(SKVM_JIT)\n\n    namespace SkVMJitTypes {\n    #if defined(__x86_64__) || defined(_M_X64)\n        using Reg = Assembler::Ymm;\n    #elif defined(__aarch64__)\n        using Reg = Assembler::V;\n    #endif\n    }  \/\/ namespace SkVMJitTypes\n\n    bool Program::jit(const std::vector<OptimizedInstruction>& instructions,\n                      int* stack_hint,\n                      uint32_t* registers_used,\n                      Assembler* a) const {\n        using A = Assembler;\n        using SkVMJitTypes::Reg;\n\n        SkTHashMap<int, A::Label> constants;    \/\/ Constants (mostly splats) share the same pool.\n        A::Label                  iota;         \/\/ Varies per lane, for Op::index.\n        A::Label                  load64_index; \/\/ Used to load low or high half of 64-bit lanes.\n\n        \/\/ The `regs` array tracks everything we know about each register's state:\n        \/\/   - NA:   empty\n        \/\/   - RES:  reserved by ABI\n        \/\/   - TMP:  holding a temporary\n        \/\/   - id:   holding Val id\n        constexpr Val RES = NA-1,\n                      TMP = RES-1;\n\n        \/\/ Map val -> stack slot.\n        std::vector<int> stack_slot(instructions.size(), NA);\n        int next_stack_slot = 0;\n\n        const int nstack_slots = *stack_hint >= 0 ? *stack_hint\n                                                  : stack_slot.size();\n    #if defined(__x86_64__) || defined(_M_X64)\n        if (!SkCpu::Supports(SkCpu::HSW)) {\n            return false;\n        }\n        const int K = 8;\n        #if defined(_M_X64)  \/\/ Important to check this first; clang-cl defines both.\n            const A::GP64 N = A::rcx,\n                        GP0 = A::rax,\n                        GP1 = A::r11,\n                        arg[]    = { A::rdx, A::r8, A::r9, A::r10, A::rdi, A::rsi };\n\n            \/\/ xmm6-15 need are callee-saved.\n            std::array<Val,16> regs = {\n                 NA, NA, NA, NA,  NA, NA,RES,RES,\n                RES,RES,RES,RES, RES,RES,RES,RES,\n            };\n            const uint32_t incoming_registers_used = *registers_used;\n\n            auto enter = [&]{\n                \/\/ rcx,rdx,r8,r9 are all already holding their correct values.\n                \/\/ Load caller-saved r10 from rsp+40 if there's a fourth arg.\n                if (fImpl->strides.size() >= 4) {\n                    a->mov(A::r10, A::Mem{A::rsp, 40});\n                }\n                \/\/ Load callee-saved rdi from rsp+48 if there's a fifth arg,\n                \/\/ first saving it to ABI reserved shadow area rsp+8.\n                if (fImpl->strides.size() >= 5) {\n                    a->mov(A::Mem{A::rsp, 8}, A::rdi);\n                    a->mov(A::rdi, A::Mem{A::rsp, 48});\n                }\n                \/\/ Load callee-saved rsi from rsp+56 if there's a sixth arg,\n                \/\/ first saving it to ABI reserved shadow area rsp+16.\n                if (fImpl->strides.size() >= 6) {\n                    a->mov(A::Mem{A::rsp, 16}, A::rsi);\n                    a->mov(A::rsi, A::Mem{A::rsp, 56});\n                }\n\n                \/\/ Allocate stack for our values and callee-saved xmm6-15.\n                int stack_needed = nstack_slots*K*4;\n                for (int r = 6; r < 16; r++) {\n                    if (incoming_registers_used & (1<<r)) {\n                        stack_needed += 16;\n                    }\n                }\n                if (stack_needed) { a->sub(A::rsp, stack_needed); }\n\n                int next_saved_xmm = nstack_slots*K*4;\n                for (int r = 6; r < 16; r++) {\n                    if (incoming_registers_used & (1<<r)) {\n                        a->vmovups(A::Mem{A::rsp, next_saved_xmm}, (A::Xmm)r);\n                        next_saved_xmm += 16;\n                        regs[r] = NA;\n                    }\n                }\n            };\n            auto exit  = [&]{\n                \/\/ The second pass of jit() shouldn't use any register it didn't in the first pass.\n                SkASSERT((*registers_used & incoming_registers_used) == *registers_used);\n\n                \/\/ Restore callee-saved xmm6-15 and the stack pointer.\n                int stack_used = nstack_slots*K*4;\n                for (int r = 6; r < 16; r++) {\n                    if (incoming_registers_used & (1<<r)) {\n                        a->vmovups((A::Xmm)r, A::Mem{A::rsp, stack_used});\n                        stack_used += 16;\n                    }\n                }\n                if (stack_used) { a->add(A::rsp, stack_used); }\n\n                \/\/ Restore callee-saved rdi\/rsi if we used them.\n                if (fImpl->strides.size() >= 5) {\n                    a->mov(A::rdi, A::Mem{A::rsp, 8});\n                }\n                if (fImpl->strides.size() >= 6) {\n                    a->mov(A::rsi, A::Mem{A::rsp, 16});\n                }\n\n                a->vzeroupper();\n                a->ret();\n            };\n        #elif defined(__x86_64__)\n            const A::GP64 N = A::rdi,\n                        GP0 = A::rax,\n                        GP1 = A::r11,\n                        arg[]    = { A::rsi, A::rdx, A::rcx, A::r8, A::r9, A::r10 };\n\n            \/\/ All 16 ymm registers are available to use.\n            std::array<Val,16> regs = {\n                NA,NA,NA,NA, NA,NA,NA,NA,\n                NA,NA,NA,NA, NA,NA,NA,NA,\n            };\n\n            auto enter = [&]{\n                \/\/ Load caller-saved r10 from rsp+8 if there's a sixth arg.\n                if (fImpl->strides.size() >= 6) {\n                    a->mov(A::r10, A::Mem{A::rsp, 8});\n                }\n                if (nstack_slots) { a->sub(A::rsp, nstack_slots*K*4); }\n            };\n            auto exit  = [&]{\n                if (nstack_slots) { a->add(A::rsp, nstack_slots*K*4); }\n                a->vzeroupper();\n                a->ret();\n            };\n        #endif\n\n        auto load_from_memory = [&](Reg r, Val v) {\n            if (instructions[v].op == Op::splat) {\n                if (instructions[v].immA == 0) {\n                    a->vpxor(r,r,r);\n                } else {\n                    a->vmovups(r, constants.find(instructions[v].immA));\n                }\n            } else {\n                SkASSERT(stack_slot[v] != NA);\n                a->vmovups(r, A::Mem{A::rsp, stack_slot[v]*K*4});\n            }\n        };\n        auto store_to_stack = [&](Reg r, Val v) {\n            SkASSERT(next_stack_slot < nstack_slots);\n            stack_slot[v] = next_stack_slot++;\n            a->vmovups(A::Mem{A::rsp, stack_slot[v]*K*4}, r);\n        };\n    #elif defined(__aarch64__)\n        const int K = 4;\n        const A::X N     = A::x0,\n                   GP0   = A::x8,\n                   GP1   = A::x9,\n                   arg[] = { A::x1, A::x2, A::x3, A::x4, A::x5, A::x6, A::x7 };\n\n        \/\/ We can use v0-v7 and v16-v31 freely; we'd need to preserve v8-v15 in enter\/exit.\n        std::array<Val,32> regs = {\n             NA, NA, NA, NA,  NA, NA, NA, NA,\n            RES,RES,RES,RES, RES,RES,RES,RES,\n             NA, NA, NA, NA,  NA, NA, NA, NA,\n             NA, NA, NA, NA,  NA, NA, NA, NA,\n        };\n\n        auto enter = [&]{ if (nstack_slots) { a->sub(A::sp, A::sp, nstack_slots*K*4); } };\n        auto exit  = [&]{ if (nstack_slots) { a->add(A::sp, A::sp, nstack_slots*K*4); }\n                          a->ret(A::x30); };\n\n        auto load_from_memory = [&](Reg r, Val v) {\n            if (instructions[v].op == Op::splat) {\n                if (instructions[v].immA == 0) {\n                    a->eor16b(r,r,r);\n                } else {\n                    a->ldrq(r, constants.find(instructions[v].immA));\n                }\n            } else {\n                SkASSERT(stack_slot[v] != NA);\n                a->ldrq(r, A::sp, stack_slot[v]);\n            }\n        };\n        auto store_to_stack  = [&](Reg r, Val v) {\n            SkASSERT(next_stack_slot < nstack_slots);\n            stack_slot[v] = next_stack_slot++;\n            a->strq(r, A::sp, stack_slot[v]);\n        };\n    #endif\n\n        *registers_used = 0;  \/\/ We'll update this as we go.\n\n        if (SK_ARRAY_COUNT(arg) < fImpl->strides.size()) {\n            return false;\n        }\n\n        auto emit = [&](Val id, bool scalar) {\n            const int active_lanes = scalar ? 1 : K;\n            const OptimizedInstruction& inst = instructions[id];\n            const Op op = inst.op;\n            const Val x = inst.x,\n                      y = inst.y,\n                      z = inst.z,\n                      w = inst.w;\n            const int immA = inst.immA,\n                      immB = inst.immB,\n                      immC = inst.immC;\n\n            \/\/ alloc_tmp() returns the first of N adjacent temporary registers,\n            \/\/ each freed manually with free_tmp() or noted as our result with mark_tmp_as_dst().\n            auto alloc_tmp = [&](int N=1) -> Reg {\n                auto needs_spill = [&](Val v) -> bool {\n                    SkASSERT(v >= 0);   \/\/ {NA,TMP,RES} need to be handled before calling this.\n                    return stack_slot[v] == NA               \/\/ We haven't spilled it already?\n                        && instructions[v].op != Op::splat;  \/\/ No need to spill constants.\n                };\n\n                \/\/ We want to find a block of N adjacent registers requiring the fewest spills.\n                int best_block = -1,\n                    min_spills = 0x7fff'ffff;\n                for (int block = 0; block+N <= (int)regs.size(); block++) {\n                    int spills = 0;\n                    for (int r = block; r < block+N; r++) {\n                        Val v = regs[r];\n                        \/\/ Registers holding NA (nothing) are ideal, nothing to spill.\n                        if (v == NA) {\n                            continue;\n                        }\n                        \/\/ We can't spill anything REServed or that we'll need this instruction.\n                        if (v == RES ||\n                            v == TMP || v == id || v == x || v == y || v == z || v == w) {\n                            spills = 0x7fff'ffff;\n                            block  = r;   \/\/ (optimization) continue outer loop at next register.\n                            break;\n                        }\n                        \/\/ Usually here we've got a value v that we'd have to spill to the stack\n                        \/\/ before reusing its register, but sometimes even now we get a freebie.\n                        spills += needs_spill(v) ? 1 : 0;\n                    }\n\n                    \/\/ TODO: non-arbitrary tie-breaking?\n                    if (min_spills > spills) {\n                        min_spills = spills;\n                        best_block = block;\n                    }\n                    if (min_spills == 0) {\n                        break;  \/\/ (optimization) stop early if we find an unbeatable block.\n                    }\n                }\n\n                \/\/ TODO: our search's success isn't obviously guaranteed... it depends on N\n                \/\/ and the number and relative position in regs of any unspillable values.\n                \/\/ I think we should be able to get away with N\u22642 on x86-64 and N\u22644 on arm64;\n                \/\/ we'll need to revisit this logic should this assert fire.\n                SkASSERT(min_spills <= N);\n\n                \/\/ Spill what needs spilling, and mark the block all as TMP.\n                for (int r = best_block; r < best_block+N; r++) {\n                    Val& v = regs[r];\n                    *registers_used |= (1<<r);\n\n                    SkASSERT(v == NA || v >= 0);\n                    if (v >= 0 && needs_spill(v)) {\n                        store_to_stack((Reg)r, v);\n                        SkASSERT(!needs_spill(v));\n                        min_spills--;\n                    }\n\n                    v = TMP;\n                }\n                SkASSERT(min_spills == 0);\n                return (Reg)best_block;\n            };\n\n            auto free_tmp = [&](Reg r) {\n                SkASSERT(regs[r] == TMP);\n                regs[r] = NA;\n            };\n\n            \/\/ Which register holds dst,x,y,z,w for this instruction?  NA if none does yet.\n            int rd = NA,\n                rx = NA,\n                ry = NA,\n                rz = NA,\n                rw = NA;\n\n            auto update_regs = [&](Reg r, Val v) {\n                if (v == id) { rd = r; }\n                if (v ==  x) { rx = r; }\n                if (v ==  y) { ry = r; }\n                if (v ==  z) { rz = r; }\n                if (v ==  w) { rw = r; }\n                return r;\n            };\n\n            auto find_existing_reg = [&](Val v) -> int {\n                \/\/ Quick-check our working registers.\n                if (v == id && rd != NA) { return rd; }\n                if (v ==  x && rx != NA) { return rx; }\n                if (v ==  y && ry != NA) { return ry; }\n                if (v ==  z && rz != NA) { return rz; }\n                if (v ==  w && rw != NA) { return rw; }\n\n                \/\/ Search inter-instruction register map.\n                for (auto [r,val] : SkMakeEnumerate(regs)) {\n                    if (val == v) {\n                        return update_regs((Reg)r, v);\n                    }\n                }\n                return NA;\n            };\n\n            \/\/ Return a register for Val, holding that value if it already exists.\n            \/\/ During this instruction all calls to r(v) will return the same register.\n            auto r = [&](Val v) -> Reg {\n                SkASSERT(v >= 0);\n\n                if (int found = find_existing_reg(v); found != NA) {\n                    return (Reg)found;\n                }\n\n                Reg r = alloc_tmp();\n                SkASSERT(regs[r] == TMP);\n\n                SkASSERT(v <= id);\n                if (v < id) {\n                    \/\/ If v < id, we're loading one of this instruction's inputs.\n                    \/\/ If v == id we're just allocating its destination register.\n                    load_from_memory(r, v);\n                }\n                regs[r] = v;\n                return update_regs(r, v);\n            };\n\n            auto dies_here = [&](Val v) -> bool {\n                SkASSERT(v >= 0);\n                return instructions[v].death == id;\n            };\n\n            \/\/ Alias dst() to r(v) if dies_here(v).\n            auto try_alias = [&](Val v) -> bool {\n                SkASSERT(v == x || v == y || v == z || v == w);\n                if (dies_here(v)) {\n                    rd = r(v);      \/\/ Vals v and id share a register for this instruction.\n                    regs[rd] = id;  \/\/ Next instruction, Val id will be in the register, not Val v.\n                    return true;\n                }\n                return false;\n            };\n\n            \/\/ Generally r(id),\n            \/\/ but with a hint, try to alias dst() to r(v) if dies_here(v).\n            auto dst = [&](Val hint1 = NA, Val hint2 = NA) -> Reg {\n                if (hint1 != NA && try_alias(hint1)) { return r(id); }\n                if (hint2 != NA && try_alias(hint2)) { return r(id); }\n                return r(id);\n            };\n\n        #if defined(__aarch64__)  \/\/ Nothing sneaky, just unused on x86-64.\n            auto mark_tmp_as_dst = [&](Reg tmp) {\n                SkASSERT(regs[tmp] == TMP);\n                rd = tmp;\n                regs[rd] = id;\n                SkASSERT(dst() == tmp);\n            };\n        #endif\n\n        #if defined(__x86_64__) || defined(_M_X64)\n            \/\/ On x86 we can work with many values directly from the stack or program constant pool.\n            auto any = [&](Val v) -> A::Operand {\n                SkASSERT(v >= 0);\n                SkASSERT(v < id);\n\n                if (int found = find_existing_reg(v); found != NA) {\n                    return (Reg)found;\n                }\n                if (instructions[v].op == Op::splat) {\n                    return constants.find(instructions[v].immA);\n                }\n                return A::Mem{A::rsp, stack_slot[v]*K*4};\n            };\n\n            \/\/ This is never really worth asking except when any() might be used;\n            \/\/ if we need this value in ARM, might as well just call r(v) to get it into a register.\n            auto in_reg = [&](Val v) -> bool {\n                return find_existing_reg(v) != NA;\n            };\n        #endif\n\n            switch (op) {\n                \/\/ Make sure splat constants can be found by load_from_memory() or any().\n                case Op::splat:\n                    (void)constants[immA];\n                    break;\n\n            #if defined(__x86_64__) || defined(_M_X64)\n                case Op::assert_true: {\n                    a->vptest (r(x), &constants[0xffffffff]);\n                    A::Label all_true;\n                    a->jc(&all_true);\n                    a->int3();\n                    a->label(&all_true);\n                } break;\n\n                case Op::trace_line:\n                case Op::trace_var:\n                case Op::trace_call:\n                    \/* Only supported in the interpreter. *\/\n                    break;\n\n                case Op::store8:\n                    if (scalar) {\n                        a->vpextrb(A::Mem{arg[immA]}, (A::Xmm)r(x), 0);\n                    } else {\n                        a->vpackusdw(dst(x), r(x), r(x));\n                        a->vpermq   (dst(), dst(), 0xd8);\n                        a->vpackuswb(dst(), dst(), dst());\n                        a->vmovq    (A::Mem{arg[immA]}, (A::Xmm)dst());\n                    } break;\n\n                case Op::store16:\n                    if (scalar) {\n                        a->vpextrw(A::Mem{arg[immA]}, (A::Xmm)r(x), 0);\n                    } else {\n                        a->vpackusdw(dst(x), r(x), r(x));\n                        a->vpermq   (dst(), dst(), 0xd8);\n                        a->vmovups  (A::Mem{arg[immA]}, (A::Xmm)dst());\n                    } break;\n\n                case Op::store32: if (scalar) { a->vmovd  (A::Mem{arg[immA]}, (A::Xmm)r(x)); }\n                                  else        { a->vmovups(A::Mem{arg[immA]},         r(x)); }\n                                  break;\n\n                case Op::store64: if (scalar) {\n                                      a->vmovd(A::Mem{arg[immA],0}, (A::Xmm)r(x));\n                                      a->vmovd(A::Mem{arg[immA],4}, (A::Xmm)r(y));\n                                  } else {\n                                      \/\/ r(x) = {a,b,c,d|e,f,g,h}\n                                      \/\/ r(y) = {i,j,k,l|m,n,o,p}\n                                      \/\/ We want to write a,i,b,j,c,k,d,l,e,m...\n                                      A::Ymm L = alloc_tmp(),\n                                             H = alloc_tmp();\n                                      a->vpunpckldq(L, r(x), any(y));  \/\/ L = {a,i,b,j|e,m,f,n}\n                                      a->vpunpckhdq(H, r(x), any(y));  \/\/ H = {c,k,d,l|g,o,h,p}\n                                      a->vperm2f128(dst(), L,H, 0x20); \/\/   = {a,i,b,j|c,k,d,l}\n                                      a->vmovups(A::Mem{arg[immA], 0}, dst());\n                                      a->vperm2f128(dst(), L,H, 0x31); \/\/   = {e,m,f,n|g,o,h,p}\n                                      a->vmovups(A::Mem{arg[immA],32}, dst());\n                                      free_tmp(L);\n                                      free_tmp(H);\n                                  } break;\n\n                case Op::store128: {\n                    \/\/ TODO: >32-bit stores\n                    a->vmovd  (A::Mem{arg[immA], 0*16 +  0}, (A::Xmm)r(x)   );\n                    a->vmovd  (A::Mem{arg[immA], 0*16 +  4}, (A::Xmm)r(y)   );\n                    a->vmovd  (A::Mem{arg[immA], 0*16 +  8}, (A::Xmm)r(z)   );\n                    a->vmovd  (A::Mem{arg[immA], 0*16 + 12}, (A::Xmm)r(w)   );\n                    if (scalar) { break; }\n\n                    a->vpextrd(A::Mem{arg[immA], 1*16 +  0}, (A::Xmm)r(x), 1);\n                    a->vpextrd(A::Mem{arg[immA], 1*16 +  4}, (A::Xmm)r(y), 1);\n                    a->vpextrd(A::Mem{arg[immA], 1*16 +  8}, (A::Xmm)r(z), 1);\n                    a->vpextrd(A::Mem{arg[immA], 1*16 + 12}, (A::Xmm)r(w), 1);\n\n                    a->vpextrd(A::Mem{arg[immA], 2*16 +  0}, (A::Xmm)r(x), 2);\n                    a->vpextrd(A::Mem{arg[immA], 2*16 +  4}, (A::Xmm)r(y), 2);\n                    a->vpextrd(A::Mem{arg[immA], 2*16 +  8}, (A::Xmm)r(z), 2);\n                    a->vpextrd(A::Mem{arg[immA], 2*16 + 12}, (A::Xmm)r(w), 2);\n\n                    a->vpextrd(A::Mem{arg[immA], 3*16 +  0}, (A::Xmm)r(x), 3);\n                    a->vpextrd(A::Mem{arg[immA], 3*16 +  4}, (A::Xmm)r(y), 3);\n                    a->vpextrd(A::Mem{arg[immA], 3*16 +  8}, (A::Xmm)r(z), 3);\n                    a->vpextrd(A::Mem{arg[immA], 3*16 + 12}, (A::Xmm)r(w), 3);\n                    \/\/ Now we need to store the upper 128 bits of x,y,z,w.\n                    \/\/ Storing in this order rather than interlacing minimizes temporaries.\n                    a->vextracti128(dst(), r(x), 1);\n                    a->vmovd  (A::Mem{arg[immA], 4*16 +  0}, (A::Xmm)dst()   );\n                    a->vpextrd(A::Mem{arg[immA], 5*16 +  0}, (A::Xmm)dst(), 1);\n                    a->vpextrd(A::Mem{arg[immA], 6*16 +  0}, (A::Xmm)dst(), 2);\n                    a->vpextrd(A::Mem{arg[immA], 7*16 +  0}, (A::Xmm)dst(), 3);\n\n                    a->vextracti128(dst(), r(y), 1);\n                    a->vmovd  (A::Mem{arg[immA], 4*16 +  4}, (A::Xmm)dst()   );\n                    a->vpextrd(A::Mem{arg[immA], 5*16 +  4}, (A::Xmm)dst(), 1);\n                    a->vpextrd(A::Mem{arg[immA], 6*16 +  4}, (A::Xmm)dst(), 2);\n                    a->vpextrd(A::Mem{arg[immA], 7*16 +  4}, (A::Xmm)dst(), 3);\n\n                    a->vextracti128(dst(), r(z), 1);\n                    a->vmovd  (A::Mem{arg[immA], 4*16 +  8}, (A::Xmm)dst()   );\n                    a->vpextrd(A::Mem{arg[immA], 5*16 +  8}, (A::Xmm)dst(), 1);\n                    a->vpextrd(A::Mem{arg[immA], 6*16 +  8}, (A::Xmm)dst(), 2);\n                    a->vpextrd(A::Mem{arg[immA], 7*16 +  8}, (A::Xmm)dst(), 3);\n\n                    a->vextracti128(dst(), r(w), 1);\n                    a->vmovd  (A::Mem{arg[immA], 4*16 + 12}, (A::Xmm)dst()   );\n                    a->vpextrd(A::Mem{arg[immA], 5*16 + 12}, (A::Xmm)dst(), 1);\n                    a->vpextrd(A::Mem{arg[immA], 6*16 + 12}, (A::Xmm)dst(), 2);\n                    a->vpextrd(A::Mem{arg[immA], 7*16 + 12}, (A::Xmm)dst(), 3);\n                } break;\n\n                case Op::load8:  if (scalar) {\n                                     a->vpxor  (dst(), dst(), dst());\n                                     a->vpinsrb((A::Xmm)dst(), (A::Xmm)dst(), A::Mem{arg[immA]}, 0);\n                                 } else {\n                                     a->vpmovzxbd(dst(), A::Mem{arg[immA]});\n                                 } break;\n\n                case Op::load16: if (scalar) {\n                                     a->vpxor  (dst(), dst(), dst());\n                                     a->vpinsrw((A::Xmm)dst(), (A::Xmm)dst(), A::Mem{arg[immA]}, 0);\n                                 } else {\n                                     a->vpmovzxwd(dst(), A::Mem{arg[immA]});\n                                 } break;\n\n                case Op::load32: if (scalar) { a->vmovd  ((A::Xmm)dst(), A::Mem{arg[immA]}); }\n                                 else        { a->vmovups(        dst(), A::Mem{arg[immA]}); }\n                                 break;\n\n                case Op::load64: if (scalar) {\n                                    a->vmovd((A::Xmm)dst(), A::Mem{arg[immA], 4*immB});\n                                 } else {\n                                    A::Ymm tmp = alloc_tmp();\n                                    a->vmovups(tmp, &load64_index);\n                                    a->vpermps(dst(), tmp, A::Mem{arg[immA],  0});\n                                    a->vpermps(  tmp, tmp, A::Mem{arg[immA], 32});\n                                    \/\/ Low 128 bits holds immB=0 lanes, high 128 bits holds immB=1.\n                                    a->vperm2f128(dst(), dst(),tmp, immB ? 0x31 : 0x20);\n                                    free_tmp(tmp);\n                                 } break;\n\n                case Op::load128: if (scalar) {\n                                      a->vmovd((A::Xmm)dst(), A::Mem{arg[immA], 4*immB});\n                                  } else {\n                                      \/\/ Load 4 low values into xmm tmp,\n                                      A::Ymm tmp = alloc_tmp();\n                                      A::Xmm t = (A::Xmm)tmp;\n                                      a->vmovd  (t,   A::Mem{arg[immA], 0*16 + 4*immB}   );\n                                      a->vpinsrd(t,t, A::Mem{arg[immA], 1*16 + 4*immB}, 1);\n                                      a->vpinsrd(t,t, A::Mem{arg[immA], 2*16 + 4*immB}, 2);\n                                      a->vpinsrd(t,t, A::Mem{arg[immA], 3*16 + 4*immB}, 3);\n\n                                      \/\/ Load 4 high values into xmm dst(),\n                                      A::Xmm d = (A::Xmm)dst();\n                                      a->vmovd  (d,   A::Mem{arg[immA], 4*16 + 4*immB}   );\n                                      a->vpinsrd(d,d, A::Mem{arg[immA], 5*16 + 4*immB}, 1);\n                                      a->vpinsrd(d,d, A::Mem{arg[immA], 6*16 + 4*immB}, 2);\n                                      a->vpinsrd(d,d, A::Mem{arg[immA], 7*16 + 4*immB}, 3);\n\n                                      \/\/ Merge the two, ymm dst() = {xmm tmp|xmm dst()}\n                                      a->vperm2f128(dst(), tmp,dst(), 0x20);\n                                      free_tmp(tmp);\n                                  } break;\n\n                case Op::gather8: {\n                    \/\/ As usual, the gather base pointer is immB bytes off of uniform immA.\n                    a->mov(GP0, A::Mem{arg[immA], immB});\n\n                    A::Ymm tmp = alloc_tmp();\n                    a->vmovups(tmp, any(x));\n\n                    for (int i = 0; i < active_lanes; i++) {\n                        if (i == 4) {\n                            \/\/ vpextrd can only pluck indices out from an Xmm register,\n                            \/\/ so we manually swap over to the top when we're halfway through.\n                            a->vextracti128((A::Xmm)tmp, tmp, 1);\n                        }\n                        a->vpextrd(GP1, (A::Xmm)tmp, i%4);\n                        a->vpinsrb((A::Xmm)dst(), (A::Xmm)dst(), A::Mem{GP0,0,GP1,A::ONE}, i);\n                    }\n                    a->vpmovzxbd(dst(), dst());\n                    free_tmp(tmp);\n                } break;\n\n                case Op::gather16: {\n                    \/\/ Just as gather8 except vpinsrb->vpinsrw, ONE->TWO, and vpmovzxbd->vpmovzxwd.\n                    a->mov(GP0, A::Mem{arg[immA], immB});\n\n                    A::Ymm tmp = alloc_tmp();\n                    a->vmovups(tmp, any(x));\n\n                    for (int i = 0; i < active_lanes; i++) {\n                        if (i == 4) {\n                            a->vextracti128((A::Xmm)tmp, tmp, 1);\n                        }\n                        a->vpextrd(GP1, (A::Xmm)tmp, i%4);\n                        a->vpinsrw((A::Xmm)dst(), (A::Xmm)dst(), A::Mem{GP0,0,GP1,A::TWO}, i);\n                    }\n                    a->vpmovzxwd(dst(), dst());\n                    free_tmp(tmp);\n                } break;\n\n                case Op::gather32:\n                if (scalar) {\n                    \/\/ Our gather base pointer is immB bytes off of uniform immA.\n                    a->mov(GP0, A::Mem{arg[immA], immB});\n\n                    \/\/ Grab our index from lane 0 of the index argument.\n                    a->vmovd(GP1, (A::Xmm)r(x));\n\n                    \/\/ dst = *(base + 4*index)\n                    a->vmovd((A::Xmm)dst(x), A::Mem{GP0, 0, GP1, A::FOUR});\n                } else {\n                    a->mov(GP0, A::Mem{arg[immA], immB});\n\n                    A::Ymm mask = alloc_tmp();\n                    a->vpcmpeqd(mask, mask, mask);   \/\/ (All lanes enabled.)\n\n                    a->vgatherdps(dst(), A::FOUR, r(x), GP0, mask);\n                    free_tmp(mask);\n                }\n                break;\n\n                case Op::uniform32: a->vbroadcastss(dst(), A::Mem{arg[immA], immB});\n                                    break;\n\n                case Op::array32: a->mov(GP0, A::Mem{arg[immA], immB});\n                                  a->vbroadcastss(dst(), A::Mem{GP0, immC});\n                                  break;\n\n                case Op::index: a->vmovd((A::Xmm)dst(), N);\n                                a->vbroadcastss(dst(), dst());\n                                a->vpsubd(dst(), dst(), &iota);\n                                break;\n\n                \/\/ We can swap the arguments of symmetric instructions to make better use of any().\n                case Op::add_f32:\n                    if (in_reg(x)) { a->vaddps(dst(x), r(x), any(y)); }\n                    else           { a->vaddps(dst(y), r(y), any(x)); }\n                                     break;\n\n                case Op::mul_f32:\n                    if (in_reg(x)) { a->vmulps(dst(x), r(x), any(y)); }\n                    else           { a->vmulps(dst(y), r(y), any(x)); }\n                                     break;\n\n                case Op::sub_f32: a->vsubps(dst(x), r(x), any(y)); break;\n                case Op::div_f32: a->vdivps(dst(x), r(x), any(y)); break;\n                case Op::min_f32: a->vminps(dst(y), r(y), any(x)); break;  \/\/ Order matters,\n                case Op::max_f32: a->vmaxps(dst(y), r(y), any(x)); break;  \/\/ see test SkVM_min_max.\n\n                case Op::fma_f32:\n                    if (try_alias(x)) { a->vfmadd132ps(dst(x), r(z), any(y)); } else\n                    if (try_alias(y)) { a->vfmadd213ps(dst(y), r(x), any(z)); } else\n                    if (try_alias(z)) { a->vfmadd231ps(dst(z), r(x), any(y)); } else\n                                      { a->vmovups    (dst(), any(x));\n                                        a->vfmadd132ps(dst(), r(z), any(y)); }\n                                        break;\n\n                case Op::fms_f32:\n                    if (try_alias(x)) { a->vfmsub132ps(dst(x), r(z), any(y)); } else\n                    if (try_alias(y)) { a->vfmsub213ps(dst(y), r(x), any(z)); } else\n                    if (try_alias(z)) { a->vfmsub231ps(dst(z), r(x), any(y)); } else\n                                      { a->vmovups    (dst(), any(x));\n                                        a->vfmsub132ps(dst(), r(z), any(y)); }\n                                        break;\n\n                case Op::fnma_f32:\n                    if (try_alias(x)) { a->vfnmadd132ps(dst(x), r(z), any(y)); } else\n                    if (try_alias(y)) { a->vfnmadd213ps(dst(y), r(x), any(z)); } else\n                    if (try_alias(z)) { a->vfnmadd231ps(dst(z), r(x), any(y)); } else\n                                      { a->vmovups     (dst(), any(x));\n                                        a->vfnmadd132ps(dst(), r(z), any(y)); }\n                                        break;\n\n                \/\/ In situations like this we want to try aliasing dst(x) when x is\n                \/\/ already in a register, but not if we'd have to load it from the stack\n                \/\/ just to alias it.  That's done better directly into the new register.\n                case Op::sqrt_f32:\n                    if (in_reg(x)) { a->vsqrtps(dst(x),  r(x)); }\n                    else           { a->vsqrtps(dst(), any(x)); }\n                                     break;\n\n                case Op::add_i32:\n                    if (in_reg(x)) { a->vpaddd(dst(x), r(x), any(y)); }\n                    else           { a->vpaddd(dst(y), r(y), any(x)); }\n                                     break;\n\n                case Op::mul_i32:\n                    if (in_reg(x)) { a->vpmulld(dst(x), r(x), any(y)); }\n                    else           { a->vpmulld(dst(y), r(y), any(x)); }\n                                     break;\n\n                case Op::sub_i32: a->vpsubd(dst(x), r(x), any(y)); break;\n\n                case Op::bit_and:\n                    if (in_reg(x)) { a->vpand(dst(x), r(x), any(y)); }\n                    else           { a->vpand(dst(y), r(y), any(x)); }\n                                     break;\n                case Op::bit_or:\n                    if (in_reg(x)) { a->vpor(dst(x), r(x), any(y)); }\n                    else           { a->vpor(dst(y), r(y), any(x)); }\n                                     break;\n                case Op::bit_xor:\n                    if (in_reg(x)) { a->vpxor(dst(x), r(x), any(y)); }\n                    else           { a->vpxor(dst(y), r(y), any(x)); }\n                                     break;\n\n                case Op::bit_clear: a->vpandn(dst(y), r(y), any(x)); break; \/\/ Notice, y then x.\n\n                case Op::select:\n                    if (try_alias(z)) { a->vpblendvb(dst(z), r(z), any(y), r(x)); }\n                    else              { a->vpblendvb(dst(x), r(z), any(y), r(x)); }\n                                        break;\n\n                case Op::shl_i32: a->vpslld(dst(x), r(x), immA); break;\n                case Op::shr_i32: a->vpsrld(dst(x), r(x), immA); break;\n                case Op::sra_i32: a->vpsrad(dst(x), r(x), immA); break;\n\n                case Op::eq_i32:\n                    if (in_reg(x)) { a->vpcmpeqd(dst(x), r(x), any(y)); }\n                    else           { a->vpcmpeqd(dst(y), r(y), any(x)); }\n                                     break;\n\n                case Op::gt_i32: a->vpcmpgtd(dst(), r(x), any(y)); break;\n\n                case Op::eq_f32:\n                    if (in_reg(x)) { a->vcmpeqps(dst(x), r(x), any(y)); }\n                    else           { a->vcmpeqps(dst(y), r(y), any(x)); }\n                                     break;\n                case Op::neq_f32:\n                    if (in_reg(x)) { a->vcmpneqps(dst(x), r(x), any(y)); }\n                    else           { a->vcmpneqps(dst(y), r(y), any(x)); }\n                                     break;\n\n                case Op:: gt_f32: a->vcmpltps (dst(y), r(y), any(x)); break;\n                case Op::gte_f32: a->vcmpleps (dst(y), r(y), any(x)); break;\n\n                case Op::ceil:\n                    if (in_reg(x)) { a->vroundps(dst(x),  r(x), Assembler::CEIL); }\n                    else           { a->vroundps(dst(), any(x), Assembler::CEIL); }\n                                     break;\n\n                case Op::floor:\n                    if (in_reg(x)) { a->vroundps(dst(x),  r(x), Assembler::FLOOR); }\n                    else           { a->vroundps(dst(), any(x), Assembler::FLOOR); }\n                                     break;\n\n                case Op::to_f32:\n                    if (in_reg(x)) { a->vcvtdq2ps(dst(x),  r(x)); }\n                    else           { a->vcvtdq2ps(dst(), any(x)); }\n                                     break;\n\n                case Op::trunc:\n                    if (in_reg(x)) { a->vcvttps2dq(dst(x),  r(x)); }\n                    else           { a->vcvttps2dq(dst(), any(x)); }\n                                     break;\n\n                case Op::round:\n                    if (in_reg(x)) { a->vcvtps2dq(dst(x),  r(x)); }\n                    else           { a->vcvtps2dq(dst(), any(x)); }\n                                     break;\n\n                case Op::to_fp16:\n                    a->vcvtps2ph(dst(x), r(x), A::CURRENT);  \/\/ f32 ymm -> f16 xmm\n                    a->vpmovzxwd(dst(), dst());              \/\/ f16 xmm -> f16 ymm\n                    break;\n\n                case Op::from_fp16:\n                    a->vpackusdw(dst(x), r(x), r(x));  \/\/ f16 ymm -> f16 xmm\n                    a->vpermq   (dst(), dst(), 0xd8);  \/\/ swap middle two 64-bit lanes\n                    a->vcvtph2ps(dst(), dst());        \/\/ f16 xmm -> f32 ymm\n                    break;\n\n            #elif defined(__aarch64__)\n                case Op::assert_true: {\n                    a->uminv4s(dst(), r(x));   \/\/ uminv acts like an all() across the vector.\n                    a->movs(GP0, dst(), 0);\n                    A::Label all_true;\n                    a->cbnz(GP0, &all_true);\n                    a->brk(0);\n                    a->label(&all_true);\n                } break;\n\n                case Op::trace_line:\n                case Op::trace_var:\n                case Op::trace_call:\n                    \/* Only supported in the interpreter. *\/\n                    break;\n\n                case Op::index: {\n                    A::V tmp = alloc_tmp();\n                    a->ldrq (tmp, &iota);\n                    a->dup4s(dst(), N);\n                    a->sub4s(dst(), dst(), tmp);\n                    free_tmp(tmp);\n                } break;\n\n                case Op::store8: a->xtns2h(dst(x), r(x));\n                                 a->xtnh2b(dst(), dst());\n                   if (scalar) { a->strb  (dst(), arg[immA]); }\n                   else        { a->strs  (dst(), arg[immA]); }\n                                 break;\n\n                case Op::store16: a->xtns2h(dst(x), r(x));\n                    if (scalar) { a->strh  (dst(), arg[immA]); }\n                    else        { a->strd  (dst(), arg[immA]); }\n                                  break;\n\n                case Op::store32: if (scalar) { a->strs(r(x), arg[immA]); }\n                                  else        { a->strq(r(x), arg[immA]); }\n                                                break;\n\n                case Op::store64: if (scalar) {\n                                      a->strs(r(x), arg[immA], 0);\n                                      a->strs(r(y), arg[immA], 1);\n                                  } else if (r(y) == r(x)+1) {\n                                      a->st24s(r(x), arg[immA]);\n                                  } else {\n                                      Reg tmp0 = alloc_tmp(2),\n                                          tmp1 = (Reg)(tmp0+1);\n                                      a->orr16b(tmp0, r(x), r(x));\n                                      a->orr16b(tmp1, r(y), r(y));\n                                      a-> st24s(tmp0, arg[immA]);\n                                      free_tmp(tmp0);\n                                      free_tmp(tmp1);\n                                  } break;\n\n                case Op::store128:\n                    if (scalar) {\n                        a->strs(r(x), arg[immA], 0);\n                        a->strs(r(y), arg[immA], 1);\n                        a->strs(r(z), arg[immA], 2);\n                        a->strs(r(w), arg[immA], 3);\n                    } else if (r(y) == r(x)+1 &&\n                               r(z) == r(x)+2 &&\n                               r(w) == r(x)+3) {\n                        a->st44s(r(x), arg[immA]);\n                    } else {\n                        Reg tmp0 = alloc_tmp(4),\n                            tmp1 = (Reg)(tmp0+1),\n                            tmp2 = (Reg)(tmp0+2),\n                            tmp3 = (Reg)(tmp0+3);\n                        a->orr16b(tmp0, r(x), r(x));\n                        a->orr16b(tmp1, r(y), r(y));\n                        a->orr16b(tmp2, r(z), r(z));\n                        a->orr16b(tmp3, r(w), r(w));\n                        a-> st44s(tmp0, arg[immA]);\n                        free_tmp(tmp0);\n                        free_tmp(tmp1);\n                        free_tmp(tmp2);\n                        free_tmp(tmp3);\n                    } break;\n\n\n                case Op::load8: if (scalar) { a->ldrb(dst(), arg[immA]); }\n                                else        { a->ldrs(dst(), arg[immA]); }\n                                              a->uxtlb2h(dst(), dst());\n                                              a->uxtlh2s(dst(), dst());\n                                              break;\n\n                case Op::load16: if (scalar) { a->ldrh(dst(), arg[immA]); }\n                                 else        { a->ldrd(dst(), arg[immA]); }\n                                               a->uxtlh2s(dst(), dst());\n                                               break;\n\n                case Op::load32: if (scalar) { a->ldrs(dst(), arg[immA]); }\n                                 else        { a->ldrq(dst(), arg[immA]); }\n                                               break;\n\n                case Op::load64: if (scalar) {\n                                    a->ldrs(dst(), arg[immA], immB);\n                                 } else {\n                                    Reg tmp0 = alloc_tmp(2),\n                                        tmp1 = (Reg)(tmp0+1);\n                                    a->ld24s(tmp0, arg[immA]);\n                                    \/\/ TODO: return both\n                                    switch (immB) {\n                                        case 0: mark_tmp_as_dst(tmp0); free_tmp(tmp1); break;\n                                        case 1: mark_tmp_as_dst(tmp1); free_tmp(tmp0); break;\n                                    }\n                                 } break;\n\n                case Op::load128: if (scalar) {\n                                      a->ldrs(dst(), arg[immA], immB);\n                                  } else {\n                                      Reg tmp0 = alloc_tmp(4),\n                                          tmp1 = (Reg)(tmp0+1),\n                                          tmp2 = (Reg)(tmp0+2),\n                                          tmp3 = (Reg)(tmp0+3);\n                                      a->ld44s(tmp0, arg[immA]);\n                                      \/\/ TODO: return all four\n                                      switch (immB) {\n                                          case 0: mark_tmp_as_dst(tmp0); break;\n                                          case 1: mark_tmp_as_dst(tmp1); break;\n                                          case 2: mark_tmp_as_dst(tmp2); break;\n                                          case 3: mark_tmp_as_dst(tmp3); break;\n                                      }\n                                      if (immB != 0) { free_tmp(tmp0); }\n                                      if (immB != 1) { free_tmp(tmp1); }\n                                      if (immB != 2) { free_tmp(tmp2); }\n                                      if (immB != 3) { free_tmp(tmp3); }\n                                  } break;\n\n                case Op::uniform32: a->add(GP0, arg[immA], immB);\n                                    a->ld1r4s(dst(), GP0);\n                                    break;\n\n                case Op::array32: a->add(GP0, arg[immA], immB);\n                                  a->ldrd(GP0, GP0);\n                                  a->add(GP0, GP0, immC);\n                                  a->ld1r4s(dst(), GP0);\n                                  break;\n\n                case Op::gather8: {\n                    \/\/ As usual, the gather base pointer is immB bytes off of uniform immA.\n                    a->add (GP0, arg[immA], immB);  \/\/ GP0 = &(gather base pointer)\n                    a->ldrd(GP0, GP0);              \/\/ GP0 =   gather base pointer\n\n                    for (int i = 0; i < active_lanes; i++) {\n                        a->movs(GP1, r(x), i);    \/\/ Extract index lane i into GP1.\n                        a->add (GP1, GP0, GP1);   \/\/ Add the gather base pointer.\n                        a->ldrb(GP1, GP1);        \/\/ Load that byte.\n                        a->inss(dst(x), GP1, i);  \/\/ Insert it into dst() lane i.\n                    }\n                } break;\n\n                \/\/ See gather8 for general idea; comments here only where gather16 differs.\n                case Op::gather16: {\n                    a->add (GP0, arg[immA], immB);\n                    a->ldrd(GP0, GP0);\n                    for (int i = 0; i < active_lanes; i++) {\n                        a->movs(GP1, r(x), i);\n                        a->add (GP1, GP0, GP1, A::LSL, 1);  \/\/ Scale index 2x into a byte offset.\n                        a->ldrh(GP1, GP1);                  \/\/ 2-byte load.\n                        a->inss(dst(x), GP1, i);\n                    }\n                } break;\n\n                \/\/ See gather8 for general idea; comments here only where gather32 differs.\n                case Op::gather32: {\n                    a->add (GP0, arg[immA], immB);\n                    a->ldrd(GP0, GP0);\n                    for (int i = 0; i < active_lanes; i++) {\n                        a->movs(GP1, r(x), i);\n                        a->add (GP1, GP0, GP1, A::LSL, 2);  \/\/ Scale index 4x into a byte offset.\n                        a->ldrs(GP1, GP1);                  \/\/ 4-byte load.\n                        a->inss(dst(x), GP1, i);\n                    }\n                } break;\n\n                case Op::add_f32: a->fadd4s(dst(x,y), r(x), r(y)); break;\n                case Op::sub_f32: a->fsub4s(dst(x,y), r(x), r(y)); break;\n                case Op::mul_f32: a->fmul4s(dst(x,y), r(x), r(y)); break;\n                case Op::div_f32: a->fdiv4s(dst(x,y), r(x), r(y)); break;\n\n                case Op::sqrt_f32: a->fsqrt4s(dst(x), r(x)); break;\n\n                case Op::fma_f32: \/\/ fmla.4s is z += x*y\n                    if (try_alias(z)) { a->fmla4s( r(z), r(x), r(y)); }\n                    else              { a->orr16b(dst(), r(z), r(z));\n                                        a->fmla4s(dst(), r(x), r(y)); }\n                                        break;\n\n                case Op::fnma_f32:  \/\/ fmls.4s is z -= x*y\n                    if (try_alias(z)) { a->fmls4s( r(z), r(x), r(y)); }\n                    else              { a->orr16b(dst(), r(z), r(z));\n                                        a->fmls4s(dst(), r(x), r(y)); }\n                                        break;\n\n                case Op::fms_f32:   \/\/ calculate z - xy, then negate to xy - z\n                    if (try_alias(z)) { a->fmls4s( r(z), r(x), r(y)); }\n                    else              { a->orr16b(dst(), r(z), r(z));\n                                        a->fmls4s(dst(), r(x), r(y)); }\n                                        a->fneg4s(dst(), dst());\n                                        break;\n\n                case Op:: gt_f32: a->fcmgt4s (dst(x,y), r(x), r(y)); break;\n                case Op::gte_f32: a->fcmge4s (dst(x,y), r(x), r(y)); break;\n                case Op:: eq_f32: a->fcmeq4s (dst(x,y), r(x), r(y)); break;\n                case Op::neq_f32: a->fcmeq4s (dst(x,y), r(x), r(y));\n                                  a->not16b  (dst(), dst());         break;\n\n\n                case Op::add_i32: a->add4s(dst(x,y), r(x), r(y)); break;\n                case Op::sub_i32: a->sub4s(dst(x,y), r(x), r(y)); break;\n                case Op::mul_i32: a->mul4s(dst(x,y), r(x), r(y)); break;\n\n                case Op::bit_and  : a->and16b(dst(x,y), r(x), r(y)); break;\n                case Op::bit_or   : a->orr16b(dst(x,y), r(x), r(y)); break;\n                case Op::bit_xor  : a->eor16b(dst(x,y), r(x), r(y)); break;\n                case Op::bit_clear: a->bic16b(dst(x,y), r(x), r(y)); break;\n\n                case Op::select: \/\/ bsl16b is x = x ? y : z\n                    if (try_alias(x)) { a->bsl16b( r(x), r(y), r(z)); }\n                    else              { a->orr16b(dst(), r(x), r(x));\n                                        a->bsl16b(dst(), r(y), r(z)); }\n                                        break;\n\n                \/\/ fmin4s and fmax4s don't work the way we want with NaN,\n                \/\/ so we write them the long way:\n                case Op::min_f32: \/\/ min(x,y) = y<x ? y : x\n                                  a->fcmgt4s(dst(), r(x), r(y));\n                                  a->bsl16b (dst(), r(y), r(x));\n                                  break;\n\n                case Op::max_f32: \/\/ max(x,y) = x<y ? y : x\n                                  a->fcmgt4s(dst(), r(y), r(x));\n                                  a->bsl16b (dst(), r(y), r(x));\n                                  break;\n\n                case Op::shl_i32: a-> shl4s(dst(x), r(x), immA); break;\n                case Op::shr_i32: a->ushr4s(dst(x), r(x), immA); break;\n                case Op::sra_i32: a->sshr4s(dst(x), r(x), immA); break;\n\n                case Op::eq_i32: a->cmeq4s(dst(x,y), r(x), r(y)); break;\n                case Op::gt_i32: a->cmgt4s(dst(x,y), r(x), r(y)); break;\n\n                case Op::to_f32: a->scvtf4s (dst(x), r(x)); break;\n                case Op::trunc:  a->fcvtzs4s(dst(x), r(x)); break;\n                case Op::round:  a->fcvtns4s(dst(x), r(x)); break;\n                case Op::ceil:   a->frintp4s(dst(x), r(x)); break;\n                case Op::floor:  a->frintm4s(dst(x), r(x)); break;\n\n                case Op::to_fp16:\n                    a->fcvtn  (dst(x), r(x));    \/\/ 4x f32 -> 4x f16 in bottom four lanes\n                    a->uxtlh2s(dst(), dst());    \/\/ expand to 4x f16 in even 16-bit lanes\n                    break;\n\n                case Op::from_fp16:\n                    a->xtns2h(dst(x), r(x));     \/\/ pack even 16-bit lanes into bottom four lanes\n                    a->fcvtl (dst(), dst());     \/\/ 4x f16 -> 4x f32\n                    break;\n            #endif\n            }\n\n            \/\/ Proactively free the registers holding any value that dies here.\n            if (rd != NA &&                   dies_here(regs[rd])) { regs[rd] = NA; }\n            if (rx != NA && regs[rx] != NA && dies_here(regs[rx])) { regs[rx] = NA; }\n            if (ry != NA && regs[ry] != NA && dies_here(regs[ry])) { regs[ry] = NA; }\n            if (rz != NA && regs[rz] != NA && dies_here(regs[rz])) { regs[rz] = NA; }\n            if (rw != NA && regs[rw] != NA && dies_here(regs[rw])) { regs[rw] = NA; }\n            return true;\n        };\n\n        #if defined(__x86_64__) || defined(_M_X64)\n            auto jump_if_less = [&](A::Label* l) { a->jl (l); };\n            auto jump         = [&](A::Label* l) { a->jmp(l); };\n\n            auto add = [&](A::GP64 gp, int imm) { a->add(gp, imm); };\n            auto sub = [&](A::GP64 gp, int imm) { a->sub(gp, imm); };\n        #elif defined(__aarch64__)\n            auto jump_if_less = [&](A::Label* l) { a->blt(l); };\n            auto jump         = [&](A::Label* l) { a->b  (l); };\n\n            auto add = [&](A::X gp, int imm) { a->add(gp, gp, imm); };\n            auto sub = [&](A::X gp, int imm) { a->sub(gp, gp, imm); };\n        #endif\n\n        A::Label body,\n                 tail,\n                 done;\n\n        enter();\n        for (Val id = 0; id < (Val)instructions.size(); id++) {\n            if (instructions[id].can_hoist && !emit(id, \/*scalar=*\/false)) {\n                return false;\n            }\n        }\n\n        \/\/ This point marks a kind of canonical fixed point for register contents: if loop\n        \/\/ code is generated as if these registers are holding these values, the next time\n        \/\/ the loop comes around we'd better find those same registers holding those same values.\n        auto restore_incoming_regs = [&,incoming=regs,saved_stack_slot=stack_slot,\n                                      saved_next_stack_slot=next_stack_slot]{\n            for (int r = 0; r < (int)regs.size(); r++) {\n                if (regs[r] != incoming[r]) {\n                    regs[r]  = incoming[r];\n                    if (regs[r] >= 0) {\n                        load_from_memory((Reg)r, regs[r]);\n                    }\n                }\n            }\n            *stack_hint = std::max(*stack_hint, next_stack_slot);\n            stack_slot = saved_stack_slot;\n            next_stack_slot = saved_next_stack_slot;\n        };\n\n        a->label(&body);\n        {\n            a->cmp(N, K);\n            jump_if_less(&tail);\n            for (Val id = 0; id < (Val)instructions.size(); id++) {\n                if (!instructions[id].can_hoist && !emit(id, \/*scalar=*\/false)) {\n                    return false;\n                }\n            }\n            restore_incoming_regs();\n            for (int i = 0; i < (int)fImpl->strides.size(); i++) {\n                if (fImpl->strides[i]) {\n                    add(arg[i], K*fImpl->strides[i]);\n                }\n            }\n            sub(N, K);\n            jump(&body);\n        }\n\n        a->label(&tail);\n        {\n            a->cmp(N, 1);\n            jump_if_less(&done);\n            for (Val id = 0; id < (Val)instructions.size(); id++) {\n                if (!instructions[id].can_hoist && !emit(id, \/*scalar=*\/true)) {\n                    return false;\n                }\n            }\n            restore_incoming_regs();\n            for (int i = 0; i < (int)fImpl->strides.size(); i++) {\n                if (fImpl->strides[i]) {\n                    add(arg[i], 1*fImpl->strides[i]);\n                }\n            }\n            sub(N, 1);\n            jump(&tail);\n        }\n\n        a->label(&done);\n        {\n            exit();\n        }\n\n        \/\/ Except for explicit aligned load and store instructions, AVX allows\n        \/\/ memory operands to be unaligned.  So even though we're creating 16\n        \/\/ byte patterns on ARM or 32-byte patterns on x86, we only need to\n        \/\/ align to 4 bytes, the element size and alignment requirement.\n\n        constants.foreach([&](int imm, A::Label* label) {\n            a->align(4);\n            a->label(label);\n            for (int i = 0; i < K; i++) {\n                a->word(imm);\n            }\n        });\n\n        if (!iota.references.empty()) {\n            a->align(4);\n            a->label(&iota);        \/\/ 0,1,2,3,4,...\n            for (int i = 0; i < K; i++) {\n                a->word(i);\n            }\n        }\n\n        if (!load64_index.references.empty()) {\n            a->align(4);\n            a->label(&load64_index);  \/\/ {0,2,4,6|1,3,5,7}\n            a->word(0); a->word(2); a->word(4); a->word(6);\n            a->word(1); a->word(3); a->word(5); a->word(7);\n        }\n\n        return true;\n    }\n\n    void Program::setupJIT(const std::vector<OptimizedInstruction>& instructions,\n                           const char* debug_name) {\n        \/\/ Assemble with no buffer to determine a.size() (the number of bytes we'll assemble)\n        \/\/ and stack_hint\/registers_used to feed forward into the next jit() call.\n        Assembler a{nullptr};\n        int stack_hint = -1;\n        uint32_t registers_used = 0xffff'ffff;  \/\/ Start conservatively with all.\n        if (!this->jit(instructions, &stack_hint, &registers_used, &a)) {\n            return;\n        }\n\n        fImpl->jit_size = a.size();\n        void* jit_entry = alloc_jit_buffer(&fImpl->jit_size);\n        fImpl->jit_entry.store(jit_entry);\n\n        \/\/ Assemble the program for real with stack_hint\/registers_used as feedback from first call.\n        a = Assembler{jit_entry};\n        SkAssertResult(this->jit(instructions, &stack_hint, &registers_used, &a));\n        SkASSERT(a.size() <= fImpl->jit_size);\n\n        \/\/ Remap as executable, and flush caches on platforms that need that.\n        remap_as_executable(jit_entry, fImpl->jit_size);\n\n        notify_vtune(debug_name, jit_entry, fImpl->jit_size);\n\n    #if !defined(SK_BUILD_FOR_WIN)\n        \/\/ For profiling and debugging, it's helpful to have this code loaded\n        \/\/ dynamically rather than just jumping info fImpl->jit_entry.\n        if (gSkVMJITViaDylib) {\n            \/\/ Dump the raw program binary.\n            SkString path = SkStringPrintf(\"\/tmp\/%s.XXXXXX\", debug_name);\n            int fd = mkstemp(path.writable_str());\n            ::write(fd, jit_entry, a.size());\n            close(fd);\n\n            this->dropJIT();  \/\/ (unmap and null out fImpl->jit_entry.)\n\n            \/\/ Convert it in-place to a dynamic library with a single symbol \"skvm_jit\":\n            SkString cmd = SkStringPrintf(\n                    \"echo '.global _skvm_jit\\n_skvm_jit: .incbin \\\"%s\\\"'\"\n                    \" | clang -x assembler -shared - -o %s\",\n                    path.c_str(), path.c_str());\n            system(cmd.c_str());\n\n            \/\/ Load that dynamic library and look up skvm_jit().\n            fImpl->dylib = dlopen(path.c_str(), RTLD_NOW|RTLD_LOCAL);\n            void* sym = nullptr;\n            for (const char* name : {\"skvm_jit\", \"_skvm_jit\"} ) {\n                if (!sym) { sym = dlsym(fImpl->dylib, name); }\n            }\n            fImpl->jit_entry.store(sym);\n        }\n    #endif\n    }\n\n    void Program::disassemble(SkWStream* o) const {\n    #if !defined(SK_BUILD_FOR_WIN)\n        SkDebugfStream debug;\n        if (!o) { o = &debug; }\n\n        const void* jit_entry = fImpl->jit_entry.load();\n        size_t jit_size = fImpl->jit_size;\n\n        if (!jit_entry) {\n            o->writeText(\"Program not JIT'd. Did you pass --jit?\\n\");\n            return;\n        }\n\n        char path[] = \"\/tmp\/skvm-jit.XXXXXX\";\n        int fd = mkstemp(path);\n        ::write(fd, jit_entry, jit_size);\n        close(fd);\n\n        \/\/ Convert it in-place to a dynamic library with a single symbol \"skvm_jit\":\n        SkString cmd = SkStringPrintf(\n                \"echo '.global _skvm_jit\\n_skvm_jit: .incbin \\\"%s\\\"'\"\n                \" | clang -x assembler -shared - -o %s\",\n                path, path);\n        system(cmd.c_str());\n\n        \/\/ Now objdump to disassemble our function:\n        \/\/ TODO: We could trim this down to just our code using '--disassemble=<symbol name>`,\n        \/\/ but the symbol name varies with OS, and that option may be missing from objdump on some\n        \/\/ machines? There also apears to be quite a bit of junk after the end of the JIT'd code.\n        \/\/ Trimming that would let us pass '--visualize-jumps' and get the loop annotated.\n        \/\/ With the junk, we tend to end up with a bunch of stray jumps that pollute the ASCII art.\n        cmd = SkStringPrintf(\"objdump -D %s\", path);\n    #if defined(SK_BUILD_FOR_UNIX)\n        cmd.append(\" --section=.text\");\n    #endif\n        FILE* fp = popen(cmd.c_str(), \"r\");\n        if (!fp) {\n            o->writeText(\"objdump failed\\n\");\n            return;\n        }\n\n        char line[1024];\n        while (fgets(line, sizeof(line), fp)) {\n            o->writeText(line);\n        }\n\n        pclose(fp);\n    #endif\n    }\n\n#endif\n\n}  \/\/ namespace skvm\n","avg_line_length":43.3114937388,"max_line_length":101,"alphanum_fraction":0.4640531987,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2764,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2012-2015 The Bitcoin Core developers\n\/\/ Copyright (c) 2014-2015 The Syscoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"limitedmap.h\"\n\n#include \"test\/test_syscoin.h\"\n\n#include <boost\/test\/unit_test.hpp>\n\nBOOST_FIXTURE_TEST_SUITE(limitedmap_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(limitedmap_test)\n{\n    \/\/ create a limitedmap capped at 10 items\n    limitedmap<int, int> map(10);\n\n    \/\/ check that the max size is 10\n    BOOST_CHECK(map.max_size() == 10);\n\n    \/\/ check that it's empty\n    BOOST_CHECK(map.size() == 0);\n\n    \/\/ insert (-1, -1)\n    map.insert(std::pair<int, int>(-1, -1));\n\n    \/\/ make sure that the size is updated\n    BOOST_CHECK(map.size() == 1);\n\n    \/\/ make sure that the new item is in the map\n    BOOST_CHECK(map.count(-1) == 1);\n\n    \/\/ insert 10 new items\n    for (int i = 0; i < 10; i++) {\n        map.insert(std::pair<int, int>(i, i + 1));\n    }\n\n    \/\/ make sure that the map now contains 10 items...\n    BOOST_CHECK(map.size() == 10);\n\n    \/\/ ...and that the first item has been discarded\n    BOOST_CHECK(map.count(-1) == 0);\n\n    \/\/ iterate over the map, both with an index and an iterator\n    limitedmap<int, int>::const_iterator it = map.begin();\n    for (int i = 0; i < 10; i++) {\n        \/\/ make sure the item is present\n        BOOST_CHECK(map.count(i) == 1);\n\n        \/\/ use the iterator to check for the expected key and value\n        BOOST_CHECK(it->first == i);\n        BOOST_CHECK(it->second == i + 1);\n        \n        \/\/ use find to check for the value\n        BOOST_CHECK(map.find(i)->second == i + 1);\n        \n        \/\/ update and recheck\n        map.update(it, i + 2);\n        BOOST_CHECK(map.find(i)->second == i + 2);\n\n        it++;\n    }\n\n    \/\/ check that we've exhausted the iterator\n    BOOST_CHECK(it == map.end());\n\n    \/\/ resize the map to 5 items\n    map.max_size(5);\n\n    \/\/ check that the max size and size are now 5\n    BOOST_CHECK(map.max_size() == 5);\n    BOOST_CHECK(map.size() == 5);\n\n    \/\/ check that items less than 5 have been discarded\n    \/\/ and items greater than 5 are retained\n    for (int i = 0; i < 10; i++) {\n        if (i < 5) {\n            BOOST_CHECK(map.count(i) == 0);\n        } else {\n            BOOST_CHECK(map.count(i) == 1);\n        }\n    }\n\n    \/\/ erase some items not in the map\n    for (int i = 100; i < 1000; i += 100) {\n        map.erase(i);\n    }\n\n    \/\/ check that the size is unaffected\n    BOOST_CHECK(map.size() == 5);\n\n    \/\/ erase the remaining elements\n    for (int i = 5; i < 10; i++) {\n        map.erase(i);\n    }\n\n    \/\/ check that the map is now empty\n    BOOST_CHECK(map.empty());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":26.8349514563,"max_line_length":70,"alphanum_fraction":0.5908104197,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":891,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause-FreeBSD"],"max_stars_count":null,"content":"--- xbmc\/settings\/Settings.cpp.orig\t2019-12-29 01:23:43 UTC\n+++ xbmc\/settings\/Settings.cpp\n@@ -537,6 +537,9 @@ bool CSettings::InitializeDefinitions()\n     CLog::Log(LOGFATAL, \"Unable to load rbp-specific settings definitions\");\n   if (g_RBP.RaspberryPiVersion() > 1 && CFile::Exists(SETTINGS_XML_FOLDER \"rbp2.xml\") && !Initialize(SETTINGS_XML_FOLDER \"rbp2.xml\"))\n     CLog::Log(LOGFATAL, \"Unable to load rbp2-specific settings definitions\");\n+#elif defined(TARGET_DRAGONFLY)\n+  if (CFile::Exists(SETTINGS_XML_FOLDER \"dragonfly.xml\") && !Initialize(SETTINGS_XML_FOLDER \"dragonfly.xml\"))\n+    CLog::Log(LOGFATAL, \"Unable to load dragonfly-specific settings definitions\");\n #elif defined(TARGET_FREEBSD)\n   if (CFile::Exists(SETTINGS_XML_FOLDER \"freebsd.xml\") && !Initialize(SETTINGS_XML_FOLDER \"freebsd.xml\"))\n     CLog::Log(LOGFATAL, \"Unable to load freebsd-specific settings definitions\");\n","avg_line_length":68.5384615385,"max_line_length":134,"alphanum_fraction":0.746352413,"low_alphanum":false,"long_lines":false,"lexable":false}
{"size":2942,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/**************************************************************************\\\n *\n *  This file is part of the Coin 3D visualization library.\n *  Copyright (C) by Kongsberg Oil & Gas Technologies.\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU General Public License\n *  (\"GPL\") version 2 as published by the Free Software Foundation.\n *  See the file LICENSE.GPL at the root directory of this source\n *  distribution for additional information about the GNU GPL.\n *\n *  For using Coin with software that can not be combined with the GNU\n *  GPL, and for taking advantage of the additional benefits of our\n *  support services, please contact Kongsberg Oil & Gas Technologies\n *  about acquiring a Coin Professional Edition License.\n *\n *  See http:\/\/www.coin3d.org\/ for more information.\n *\n *  Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.\n *  http:\/\/www.sim.no\/  sales@sim.no  coin-support@coin3d.org\n *\n\\**************************************************************************\/\n\n\/*!\n  \\class SoLightModelElement Inventor\/elements\/SoLightModelElement.h\n  \\brief The SoLightModelElement class is yet to be documented.\n  \\ingroup elements\n\n  FIXME: write doc.\n*\/\n\n#include \"coindefs.h\"\n#include \"SbBasicP.h\"\n\n#include <Inventor\/elements\/SoLightModelElement.h>\n#include <Inventor\/elements\/SoLazyElement.h>\n#include <cassert>\n\n\/*!\n  \\fn SoLightModelElement::Model\n\n  FIXME: write doc.\n*\/\n\nSO_ELEMENT_SOURCE(SoLightModelElement);\n\n\/*!\n  This static method initializes static data for the\n  SoLightModelElement class.\n*\/\n\nvoid\nSoLightModelElement::initClass()\n{\n  SO_ELEMENT_INIT_CLASS(SoLightModelElement, inherited);\n}\n\n\/*!\n  The destructor.\n*\/\n\nSoLightModelElement::~SoLightModelElement()\n{\n}\n\n\/\/! FIXME: write doc.\n\nvoid\nSoLightModelElement::init(SoState * \/* state *\/)\n{\n}\n\n\/\/! FIXME: write doc.\n\nvoid\nSoLightModelElement::set(SoState * const state, const Model model)\n{\n  SoLazyElement::setLightModel(state, static_cast<int32_t>(model));\n}\n\n\/\/! FIXME: write doc.\n\nvoid\nSoLightModelElement::set(SoState * const state, SoNode * const COIN_UNUSED_ARG(node),\n                         const Model model)\n{\n  SoLazyElement::setLightModel(state, static_cast<int32_t>(model));\n}\n\n\/\/! FIXME: write doc.\n\nSoLightModelElement::Model\nSoLightModelElement::get(SoState * const state)\n{\n  return static_cast<SoLightModelElement::Model>(SoLazyElement::getLightModel(state));\n}\n\n\/\/! FIXME: write doc.\n\nSoLightModelElement::Model\nSoLightModelElement::getDefault()\n{\n  return static_cast<SoLightModelElement::Model>(SoLazyElement::getDefaultLightModel());\n}\n\n\/\/! FIXME: write doc\n\nconst SoLightModelElement *\nSoLightModelElement::getInstance(SoState *state)\n{\n  \/\/FIXME: Can this function or any of the similar functions ever\n  \/\/return NULL? BFG 20080916\n  return coin_assert_cast<const SoLightModelElement *>\n    (\n     state->getElementNoPush(classStackIndex)\n     );\n}\n","avg_line_length":24.9322033898,"max_line_length":88,"alphanum_fraction":0.7002039429,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":15055,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"rpc\/server.h\"\n\n#include \"base58.h\"\n#include \"init.h\"\n#include \"random.h\"\n#include \"sync.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n\n#include <univalue.h>\n\n#include <boost\/bind.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/iostreams\/concepts.hpp>\n#include <boost\/iostreams\/stream.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/signals2\/signal.hpp>\n#include <boost\/thread.hpp>\n#include <boost\/algorithm\/string\/case_conv.hpp> \/\/ for to_upper()\n\nusing namespace RPCServer;\nusing namespace std;\n\nstatic bool fRPCRunning = false;\nstatic bool fRPCInWarmup = true;\nstatic std::string rpcWarmupStatus(\"RPC server started\");\nstatic CCriticalSection cs_rpcWarmup;\n\/* Timer-creating functions *\/\nstatic RPCTimerInterface* timerInterface = NULL;\n\/* Map of name to timer.\n * @note Can be changed to std::unique_ptr when C++11 *\/\nstatic std::map<std::string, boost::shared_ptr<RPCTimerBase> > deadlineTimers;\n\nstatic struct CRPCSignals\n{\n    boost::signals2::signal<void ()> Started;\n    boost::signals2::signal<void ()> Stopped;\n    boost::signals2::signal<void (const CRPCCommand&)> PreCommand;\n    boost::signals2::signal<void (const CRPCCommand&)> PostCommand;\n} g_rpcSignals;\n\nvoid RPCServer::OnStarted(boost::function<void ()> slot)\n{\n    g_rpcSignals.Started.connect(slot);\n}\n\nvoid RPCServer::OnStopped(boost::function<void ()> slot)\n{\n    g_rpcSignals.Stopped.connect(slot);\n}\n\nvoid RPCServer::OnPreCommand(boost::function<void (const CRPCCommand&)> slot)\n{\n    g_rpcSignals.PreCommand.connect(boost::bind(slot, _1));\n}\n\nvoid RPCServer::OnPostCommand(boost::function<void (const CRPCCommand&)> slot)\n{\n    g_rpcSignals.PostCommand.connect(boost::bind(slot, _1));\n}\n\nvoid RPCTypeCheck(const UniValue& params,\n                  const list<UniValue::VType>& typesExpected,\n                  bool fAllowNull)\n{\n    unsigned int i = 0;\n    BOOST_FOREACH(UniValue::VType t, typesExpected)\n    {\n        if (params.size() <= i)\n            break;\n\n        const UniValue& v = params[i];\n        if (!((v.type() == t) || (fAllowNull && (v.isNull()))))\n        {\n            string err = strprintf(\"Expected type %s, got %s\",\n                                   uvTypeName(t), uvTypeName(v.type()));\n            throw JSONRPCError(RPC_TYPE_ERROR, err);\n        }\n        i++;\n    }\n}\n\nvoid RPCTypeCheckObj(const UniValue& o,\n    const map<string, UniValueType>& typesExpected,\n    bool fAllowNull,\n    bool fStrict)\n{\n    for (const auto& t : typesExpected) {\n        const UniValue& v = find_value(o, t.first);\n        if (!fAllowNull && v.isNull())\n            throw JSONRPCError(RPC_TYPE_ERROR, strprintf(\"Missing %s\", t.first));\n\n        if (!(t.second.typeAny || v.type() == t.second.type || (fAllowNull && v.isNull()))) {\n            string err = strprintf(\"Expected type %s for %s, got %s\",\n                uvTypeName(t.second.type), t.first, uvTypeName(v.type()));\n            throw JSONRPCError(RPC_TYPE_ERROR, err);\n        }\n    }\n\n    if (fStrict)\n    {\n        BOOST_FOREACH(const string& k, o.getKeys())\n        {\n            if (typesExpected.count(k) == 0)\n            {\n                string err = strprintf(\"Unexpected key %s\", k);\n                throw JSONRPCError(RPC_TYPE_ERROR, err);\n            }\n        }\n    }\n}\n\nCAmount AmountFromValue(const UniValue& value)\n{\n    if (!value.isNum() && !value.isStr())\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Amount is not a number or string\");\n    CAmount amount;\n    if (!ParseFixedPoint(value.getValStr(), 8, &amount))\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid amount\");\n    if (!MoneyRange(amount))\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Amount out of range\");\n    return amount;\n}\n\nUniValue ValueFromAmount(const CAmount& amount)\n{\n    bool sign = amount < 0;\n    int64_t n_abs = (sign ? -amount : amount);\n    int64_t quotient = n_abs \/ COIN;\n    int64_t remainder = n_abs % COIN;\n    return UniValue(UniValue::VNUM,\n            strprintf(\"%s%d.%08d\", sign ? \"-\" : \"\", quotient, remainder));\n}\n\nuint256 ParseHashV(const UniValue& v, string strName)\n{\n    string strHex;\n    if (v.isStr())\n        strHex = v.get_str();\n    if (!IsHex(strHex)) \/\/ Note: IsHex(\"\") is false\n        throw JSONRPCError(RPC_INVALID_PARAMETER, strName+\" must be hexadecimal string (not '\"+strHex+\"')\");\n    if (64 != strHex.length())\n        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf(\"%s must be of length %d (not %d)\", strName, 64, strHex.length()));\n    uint256 result;\n    result.SetHex(strHex);\n    return result;\n}\nuint256 ParseHashO(const UniValue& o, string strKey)\n{\n    return ParseHashV(find_value(o, strKey), strKey);\n}\nvector<unsigned char> ParseHexV(const UniValue& v, string strName)\n{\n    string strHex;\n    if (v.isStr())\n        strHex = v.get_str();\n    if (!IsHex(strHex))\n        throw JSONRPCError(RPC_INVALID_PARAMETER, strName+\" must be hexadecimal string (not '\"+strHex+\"')\");\n    return ParseHex(strHex);\n}\nvector<unsigned char> ParseHexO(const UniValue& o, string strKey)\n{\n    return ParseHexV(find_value(o, strKey), strKey);\n}\n\n\/**\n * Note: This interface may still be subject to change.\n *\/\n\nstd::string CRPCTable::help(const std::string& strCommand) const\n{\n    string strRet;\n    string category;\n    set<rpcfn_type> setDone;\n    vector<pair<string, const CRPCCommand*> > vCommands;\n\n    for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)\n        vCommands.push_back(make_pair(mi->second->category + mi->first, mi->second));\n    sort(vCommands.begin(), vCommands.end());\n\n    BOOST_FOREACH(const PAIRTYPE(string, const CRPCCommand*)& command, vCommands)\n    {\n        const CRPCCommand *pcmd = command.second;\n        string strMethod = pcmd->name;\n        \/\/ We already filter duplicates, but these deprecated screw up the sort order\n        if (strMethod.find(\"label\") != string::npos)\n            continue;\n        if ((strCommand != \"\" || pcmd->category == \"hidden\") && strMethod != strCommand)\n            continue;\n        try\n        {\n            UniValue params;\n            rpcfn_type pfn = pcmd->actor;\n            if (setDone.insert(pfn).second)\n                (*pfn)(params, true);\n        }\n        catch (const std::exception& e)\n        {\n            \/\/ Help text is returned in an exception\n            string strHelp = string(e.what());\n            if (strCommand == \"\")\n            {\n                if (strHelp.find('\\n') != string::npos)\n                    strHelp = strHelp.substr(0, strHelp.find('\\n'));\n\n                if (category != pcmd->category)\n                {\n                    if (!category.empty())\n                        strRet += \"\\n\";\n                    category = pcmd->category;\n                    string firstLetter = category.substr(0,1);\n                    boost::to_upper(firstLetter);\n                    strRet += \"== \" + firstLetter + category.substr(1) + \" ==\\n\";\n                }\n            }\n            strRet += strHelp + \"\\n\";\n        }\n    }\n    if (strRet == \"\")\n        strRet = strprintf(\"help: unknown command: %s\\n\", strCommand);\n    strRet = strRet.substr(0,strRet.size()-1);\n    return strRet;\n}\n\nUniValue help(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() > 1)\n        throw runtime_error(\n            \"help ( \\\"command\\\" )\\n\"\n            \"\\nList all commands, or get help for a specified command.\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"command\\\"     (string, optional) The command to get help on\\n\"\n            \"\\nResult:\\n\"\n            \"\\\"text\\\"     (string) The help text\\n\"\n        );\n\n    string strCommand;\n    if (params.size() > 0)\n        strCommand = params[0].get_str();\n\n    return tableRPC.help(strCommand);\n}\n\n\nUniValue stop(const UniValue& params, bool fHelp)\n{\n    \/\/ Accept the deprecated and ignored 'detach' boolean argument\n    if (fHelp || params.size() > 1)\n        throw runtime_error(\n            \"stop\\n\"\n            \"\\nStop Viacoin server.\");\n    \/\/ Event loop will exit after current HTTP requests have been handled, so\n    \/\/ this reply will get back to the client.\n    StartShutdown();\n    return \"Viacoin server stopping\";\n}\n\n\/**\n * Call Table\n *\/\nstatic const CRPCCommand vRPCCommands[] =\n{ \/\/  category              name                      actor (function)         okSafeMode\n  \/\/  --------------------- ------------------------  -----------------------  ----------\n    \/* Overall control\/query calls *\/\n    { \"control\",            \"help\",                   &help,                   true  },\n    { \"control\",            \"stop\",                   &stop,                   true  },\n};\n\nCRPCTable::CRPCTable()\n{\n    unsigned int vcidx;\n    for (vcidx = 0; vcidx < (sizeof(vRPCCommands) \/ sizeof(vRPCCommands[0])); vcidx++)\n    {\n        const CRPCCommand *pcmd;\n\n        pcmd = &vRPCCommands[vcidx];\n        mapCommands[pcmd->name] = pcmd;\n    }\n}\n\nconst CRPCCommand *CRPCTable::operator[](const std::string &name) const\n{\n    map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);\n    if (it == mapCommands.end())\n        return NULL;\n    return (*it).second;\n}\n\nbool CRPCTable::appendCommand(const std::string& name, const CRPCCommand* pcmd)\n{\n    if (IsRPCRunning())\n        return false;\n\n    \/\/ don't allow overwriting for now\n    map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);\n    if (it != mapCommands.end())\n        return false;\n\n    mapCommands[name] = pcmd;\n    return true;\n}\n\nbool StartRPC()\n{\n    LogPrint(\"rpc\", \"Starting RPC\\n\");\n    fRPCRunning = true;\n    g_rpcSignals.Started();\n    return true;\n}\n\nvoid InterruptRPC()\n{\n    LogPrint(\"rpc\", \"Interrupting RPC\\n\");\n    \/\/ Interrupt e.g. running longpolls\n    fRPCRunning = false;\n}\n\nvoid StopRPC()\n{\n    LogPrint(\"rpc\", \"Stopping RPC\\n\");\n    deadlineTimers.clear();\n    g_rpcSignals.Stopped();\n}\n\nbool IsRPCRunning()\n{\n    return fRPCRunning;\n}\n\nvoid SetRPCWarmupStatus(const std::string& newStatus)\n{\n    LOCK(cs_rpcWarmup);\n    rpcWarmupStatus = newStatus;\n}\n\nvoid SetRPCWarmupFinished()\n{\n    LOCK(cs_rpcWarmup);\n    assert(fRPCInWarmup);\n    fRPCInWarmup = false;\n}\n\nbool RPCIsInWarmup(std::string *outStatus)\n{\n    LOCK(cs_rpcWarmup);\n    if (outStatus)\n        *outStatus = rpcWarmupStatus;\n    return fRPCInWarmup;\n}\n\nvoid JSONRequest::parse(const UniValue& valRequest)\n{\n    \/\/ Parse request\n    if (!valRequest.isObject())\n        throw JSONRPCError(RPC_INVALID_REQUEST, \"Invalid Request object\");\n    const UniValue& request = valRequest.get_obj();\n\n    \/\/ Parse id now so errors from here on will have the id\n    id = find_value(request, \"id\");\n\n    \/\/ Parse method\n    UniValue valMethod = find_value(request, \"method\");\n    if (valMethod.isNull())\n        throw JSONRPCError(RPC_INVALID_REQUEST, \"Missing method\");\n    if (!valMethod.isStr())\n        throw JSONRPCError(RPC_INVALID_REQUEST, \"Method must be a string\");\n    strMethod = valMethod.get_str();\n    if (strMethod != \"getblocktemplate\")\n        LogPrint(\"rpc\", \"ThreadRPCServer method=%s\\n\", SanitizeString(strMethod));\n\n    \/\/ Parse params\n    UniValue valParams = find_value(request, \"params\");\n    if (valParams.isArray())\n        params = valParams.get_array();\n    else if (valParams.isNull())\n        params = UniValue(UniValue::VARR);\n    else\n        throw JSONRPCError(RPC_INVALID_REQUEST, \"Params must be an array\");\n}\n\nstatic UniValue JSONRPCExecOne(const UniValue& req)\n{\n    UniValue rpc_result(UniValue::VOBJ);\n\n    JSONRequest jreq;\n    try {\n        jreq.parse(req);\n\n        UniValue result = tableRPC.execute(jreq.strMethod, jreq.params);\n        rpc_result = JSONRPCReplyObj(result, NullUniValue, jreq.id);\n    }\n    catch (const UniValue& objError)\n    {\n        rpc_result = JSONRPCReplyObj(NullUniValue, objError, jreq.id);\n    }\n    catch (const std::exception& e)\n    {\n        rpc_result = JSONRPCReplyObj(NullUniValue,\n                                     JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);\n    }\n\n    return rpc_result;\n}\n\nstd::string JSONRPCExecBatch(const UniValue& vReq)\n{\n    UniValue ret(UniValue::VARR);\n    for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)\n        ret.push_back(JSONRPCExecOne(vReq[reqIdx]));\n\n    return ret.write() + \"\\n\";\n}\n\nUniValue CRPCTable::execute(const std::string &strMethod, const UniValue &params) const\n{\n    \/\/ Return immediately if in warmup\n    {\n        LOCK(cs_rpcWarmup);\n        if (fRPCInWarmup)\n            throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus);\n    }\n\n    \/\/ Find method\n    const CRPCCommand *pcmd = tableRPC[strMethod];\n    if (!pcmd)\n        throw JSONRPCError(RPC_METHOD_NOT_FOUND, \"Method not found\");\n\n    g_rpcSignals.PreCommand(*pcmd);\n\n    try\n    {\n        \/\/ Execute\n        return pcmd->actor(params, false);\n    }\n    catch (const std::exception& e)\n    {\n        throw JSONRPCError(RPC_MISC_ERROR, e.what());\n    }\n\n    g_rpcSignals.PostCommand(*pcmd);\n}\n\nstd::vector<std::string> CRPCTable::listCommands() const\n{\n    std::vector<std::string> commandList;\n    typedef std::map<std::string, const CRPCCommand*> commandMap;\n\n    std::transform( mapCommands.begin(), mapCommands.end(),\n                   std::back_inserter(commandList),\n                   boost::bind(&commandMap::value_type::first,_1) );\n    return commandList;\n}\n\nstd::string HelpExampleCli(const std::string& methodname, const std::string& args)\n{\n    return \"> viacoin-cli \" + methodname + \" \" + args + \"\\n\";\n}\n\nstd::string HelpExampleRpc(const std::string& methodname, const std::string& args)\n{\n    return \"> curl --user myusername --data-binary '{\\\"jsonrpc\\\": \\\"1.0\\\", \\\"id\\\":\\\"curltest\\\", \"\n        \"\\\"method\\\": \\\"\" + methodname + \"\\\", \\\"params\\\": [\" + args + \"] }' -H 'content-type: text\/plain;' http:\/\/127.0.0.1:5222\/\\n\";\n}\n\nvoid RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)\n{\n    if (!timerInterface)\n        timerInterface = iface;\n}\n\nvoid RPCSetTimerInterface(RPCTimerInterface *iface)\n{\n    timerInterface = iface;\n}\n\nvoid RPCUnsetTimerInterface(RPCTimerInterface *iface)\n{\n    if (timerInterface == iface)\n        timerInterface = NULL;\n}\n\nvoid RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds)\n{\n    if (!timerInterface)\n        throw JSONRPCError(RPC_INTERNAL_ERROR, \"No timer handler registered for RPC\");\n    deadlineTimers.erase(name);\n    LogPrint(\"rpc\", \"queue run of timer %s in %i seconds (using %s)\\n\", name, nSeconds, timerInterface->Name());\n    deadlineTimers.insert(std::make_pair(name, boost::shared_ptr<RPCTimerBase>(timerInterface->NewTimer(func, nSeconds*1000))));\n}\n\nint RPCSerializationFlags()\n{\n    int flag = 0;\n    if (GetArg(\"-rpcserialversion\", DEFAULT_RPC_SERIALIZE_VERSION) == 0)\n        flag |= SERIALIZE_TRANSACTION_NO_WITNESS;\n    return flag;\n}\n\nCRPCTable tableRPC;\n","avg_line_length":29.6942800789,"max_line_length":132,"alphanum_fraction":0.6213882431,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":15582,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"ParseUtils.h\"\n#include \"rapidjson\\document.h\"\n#include \"JSONTools.h\"\n#include \"BuildOrder.h\"\n#include \"StrategyManager.h\"\n#include \"Global.h\"\n\nusing namespace UAlbertaBot;\n\nvoid ParseUtils::ParseConfigFile(const std::string &filename)\n{\n\tPROFILE_FUNCTION();\n\n\trapidjson::Document doc;\n\tBWAPI::Race race = BWAPI::Broodwar->self()->getRace();\n\tconst char *ourRace = race.getName().c_str();\n\n\tstd::string config = FileUtils::ReadFile(filename);\n\n\tif (config.length() == 0)\n\t{\n\t\treturn;\n\t}\n\n\tConfig::ConfigFile::ConfigFileFound = true;\n\n\tbool parsingFailed = doc.Parse(config.c_str()).HasParseError();\n\tif (parsingFailed)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ Parse the Bot Info\n\tif (doc.HasMember(\"Bot Info\") && doc[\"Bot Info\"].IsObject())\n\t{\n\t\tconst rapidjson::Value &info = doc[\"Bot Info\"];\n\t\tJSONTools::ReadString(\"BotName\", info, Config::BotInfo::BotName);\n\t\tJSONTools::ReadString(\"Authors\", info, Config::BotInfo::Authors);\n\t\tJSONTools::ReadBool(\"PrintInfoOnStart\", info, Config::BotInfo::PrintInfoOnStart);\n\t}\n\n\t\/\/ Parse the BWAPI Options\n\tif (doc.HasMember(\"BWAPI\") && doc[\"BWAPI\"].IsObject())\n\t{\n\t\tconst rapidjson::Value &bwapi = doc[\"BWAPI\"];\n\t\tJSONTools::ReadInt(\"SetLocalSpeed\", bwapi, Config::BWAPIOptions::SetLocalSpeed);\n\t\tJSONTools::ReadInt(\"SetFrameSkip\", bwapi, Config::BWAPIOptions::SetFrameSkip);\n\t\tJSONTools::ReadBool(\"UserInput\", bwapi, Config::BWAPIOptions::EnableUserInput);\n\t\tJSONTools::ReadBool(\"CompleteMapInformation\", bwapi, Config::BWAPIOptions::EnableCompleteMapInformation);\n\t}\n\n\t\/\/ Parse the Micro Options\n\tif (doc.HasMember(\"Micro\") && doc[\"Micro\"].IsObject())\n\t{\n\t\tconst rapidjson::Value &micro = doc[\"Micro\"];\n\t\tJSONTools::ReadBool(\"UseSparcraftSimulation\", micro, Config::Micro::UseSparcraftSimulation);\n\t\tJSONTools::ReadBool(\"KiteWithRangedUnits\", micro, Config::Micro::KiteWithRangedUnits);\n\t\tJSONTools::ReadBool(\"WorkersDefendRush\", micro, Config::Micro::WorkersDefendRush);\n\t\tJSONTools::ReadInt(\"RetreatMeleeUnitShields\", micro, Config::Micro::RetreatMeleeUnitShields);\n\t\tJSONTools::ReadInt(\"RetreatMeleeUnitHP\", micro, Config::Micro::RetreatMeleeUnitHP);\n\t\tJSONTools::ReadInt(\"InCombatRadius\", micro, Config::Micro::CombatRadius);\n\t\tJSONTools::ReadInt(\"RegroupRadius\", micro, Config::Micro::CombatRegroupRadius);\n\t\tJSONTools::ReadInt(\"UnitNearEnemyRadius\", micro, Config::Micro::UnitNearEnemyRadius);\n\n\t\tif (micro.HasMember(\"KiteLongerRangedUnits\") && micro[\"KiteLongerRangedUnits\"].IsArray())\n\t\t{\n\t\t\tconst rapidjson::Value &kite = micro[\"KiteLongerRangedUnits\"];\n\n\t\t\tfor (size_t i(0); i < kite.Size(); ++i)\n\t\t\t{\n\t\t\t\tif (kite[i].IsString())\n\t\t\t\t{\n\t\t\t\t\tMetaType type(kite[i].GetString());\n\t\t\t\t\tConfig::Micro::KiteLongerRangedUnits.insert(type.getUnitType());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Parse the Macro Options\n\tif (doc.HasMember(\"Macro\") && doc[\"Macro\"].IsObject())\n\t{\n\t\tconst rapidjson::Value &macro = doc[\"Macro\"];\n\t\tJSONTools::ReadInt(\"BOSSFrameLimit\", macro, Config::Macro::BOSSFrameLimit);\n\t\tJSONTools::ReadInt(\"BuildingSpacing\", macro, Config::Macro::BuildingSpacing);\n\t\tJSONTools::ReadInt(\"PylongSpacing\", macro, Config::Macro::PylonSpacing);\n\t\tJSONTools::ReadInt(\"WorkersPerRefinery\", macro, Config::Macro::WorkersPerRefinery);\n\t}\n\n\t\/\/ Parse the Debug Options\n\tif (doc.HasMember(\"Debug\") && doc[\"Debug\"].IsObject())\n\t{\n\t\tconst rapidjson::Value &debug = doc[\"Debug\"];\n\t\tJSONTools::ReadString(\"ErrorLogFilename\", debug, Config::Debug::ErrorLogFilename);\n\t\tJSONTools::ReadBool(\"LogAssertToErrorFile\", debug, Config::Debug::LogAssertToErrorFile);\n\t\tJSONTools::ReadBool(\"DrawGameInfo\", debug, Config::Debug::DrawGameInfo);\n\t\tJSONTools::ReadBool(\"DrawBuildOrderSearchInfo\", debug, Config::Debug::DrawBuildOrderSearchInfo);\n\t\tJSONTools::ReadBool(\"DrawUnitHealthBars\", debug, Config::Debug::DrawUnitHealthBars);\n\t\tJSONTools::ReadBool(\"DrawResourceInfo\", debug, Config::Debug::DrawResourceInfo);\n\t\tJSONTools::ReadBool(\"DrawWorkerInfo\", debug, Config::Debug::DrawWorkerInfo);\n\t\tJSONTools::ReadBool(\"DrawProductionInfo\", debug, Config::Debug::DrawProductionInfo);\n\t\tJSONTools::ReadBool(\"DrawScoutInfo\", debug, Config::Debug::DrawScoutInfo);\n\t\tJSONTools::ReadBool(\"DrawSquadInfo\", debug, Config::Debug::DrawSquadInfo);\n\t\tJSONTools::ReadBool(\"DrawCombatSimInfo\", debug, Config::Debug::DrawCombatSimulationInfo);\n\t\tJSONTools::ReadBool(\"DrawBuildingInfo\", debug, Config::Debug::DrawBuildingInfo);\n\t\tJSONTools::ReadBool(\"DrawModuleTimers\", debug, Config::Debug::DrawModuleTimers);\n\t\tJSONTools::ReadBool(\"DrawMouseCursorInfo\", debug, Config::Debug::DrawMouseCursorInfo);\n\t\tJSONTools::ReadBool(\"DrawEnemyUnitInfo\", debug, Config::Debug::DrawEnemyUnitInfo);\n\t\tJSONTools::ReadBool(\"DrawBWTAInfo\", debug, Config::Debug::DrawBWTAInfo);\n\t\tJSONTools::ReadBool(\"DrawMapGrid\", debug, Config::Debug::DrawMapGrid);\n\t\tJSONTools::ReadBool(\"DrawUnitTargetInfo\", debug, Config::Debug::DrawUnitTargetInfo);\n\t\tJSONTools::ReadBool(\"DrawReservedBuildingTiles\", debug, Config::Debug::DrawReservedBuildingTiles);\n\t\tJSONTools::ReadBool(\"DrawBOSSStateInfo\", debug, Config::Debug::DrawBOSSStateInfo);\n\t\tJSONTools::ReadBool(\"DrawTileInfo\", debug, Config::Debug::DrawTileInfo);\n\t\tJSONTools::ReadBool(\"DrawWalkableSectors\", debug, Config::Debug::DrawWalkableSectors);\n\t\tJSONTools::ReadBool(\"PrintModuleTimeout\", debug, Config::Debug::PrintModuleTimeout);\n\t}\n\n\t\/\/ Parse the Module Options\n\tif (doc.HasMember(\"Modules\") && doc[\"Modules\"].IsObject())\n\t{\n\t\tconst rapidjson::Value &module = doc[\"Modules\"];\n\n\t\tJSONTools::ReadBool(\"UseGameCommander\", module, Config::Modules::UsingGameCommander);\n\t\tJSONTools::ReadBool(\"UseScoutManager\", module, Config::Modules::UsingScoutManager);\n\t\tJSONTools::ReadBool(\"UseCombatCommander\", module, Config::Modules::UsingCombatCommander);\n\t\tJSONTools::ReadBool(\"UseBuildOrderSearch\", module, Config::Modules::UsingBuildOrderSearch);\n\t\tJSONTools::ReadBool(\"UseStrategyIO\", module, Config::Modules::UsingStrategyIO);\n\t\tJSONTools::ReadBool(\"UseUnitCommandManager\", module, Config::Modules::UsingUnitCommandManager);\n\t\tJSONTools::ReadBool(\"UseAutoObserver\", module, Config::Modules::UsingAutoObserver);\n\t}\n\n\t\/\/ Parse the Tool Options\n\tif (doc.HasMember(\"Tools\") && doc[\"Tools\"].IsObject())\n\t{\n\t\tconst rapidjson::Value &tool = doc[\"Tools\"];\n\n\t\tJSONTools::ReadInt(\"MapGridSize\", tool, Config::Tools::MAP_GRID_SIZE);\n\t}\n\n\t\/\/ Parse the Strategy Options\n\tif (doc.HasMember(\"Strategy\") && doc[\"Strategy\"].IsObject())\n\t{\n\t\tconst rapidjson::Value &strategy = doc[\"Strategy\"];\n\n\t\t\/\/ read in the various strategic elements\n\t\tJSONTools::ReadBool(\"ScoutGasSteal\", strategy, Config::Strategy::GasStealWithScout);\n\t\tJSONTools::ReadBool(\"ScoutHarassEnemy\", strategy, Config::Strategy::ScoutHarassEnemy);\n\t\tJSONTools::ReadString(\"ReadDirectory\", strategy, Config::Strategy::ReadDir);\n\t\tJSONTools::ReadString(\"WriteDirectory\", strategy, Config::Strategy::WriteDir);\n\n\t\t\/\/ if we have set a strategy for the current race, use it\n\t\tif (strategy.HasMember(race.c_str()) && strategy[race.c_str()].IsString())\n\t\t{\n\t\t\tConfig::Strategy::StrategyName = strategy[race.c_str()].GetString();\n\t\t}\n\n\t\t\/\/ check if we are using an enemy specific strategy\n\t\tJSONTools::ReadBool(\"UseEnemySpecificStrategy\", strategy, Config::Strategy::UseEnemySpecificStrategy);\n\t\tif (Config::Strategy::UseEnemySpecificStrategy && strategy.HasMember(\"EnemySpecificStrategy\") && strategy[\"EnemySpecificStrategy\"].IsObject())\n\t\t{\n\t\t\tconst std::string enemyName = BWAPI::Broodwar->enemy()->getName();\n\t\t\tconst rapidjson::Value &specific = strategy[\"EnemySpecificStrategy\"];\n\n\t\t\t\/\/ check to see if our current enemy name is listed anywhere in the specific strategies\n\t\t\tif (specific.HasMember(enemyName.c_str()) && specific[enemyName.c_str()].IsObject())\n\t\t\t{\n\t\t\t\tconst rapidjson::Value &enemyStrategies = specific[enemyName.c_str()];\n\n\t\t\t\t\/\/ if that enemy has a strategy listed for our current race, use it\n\t\t\t\tif (enemyStrategies.HasMember(ourRace) && enemyStrategies[ourRace].IsString())\n\t\t\t\t{\n\t\t\t\t\tConfig::Strategy::StrategyName = enemyStrategies[ourRace].GetString();\n\t\t\t\t\tConfig::Strategy::FoundEnemySpecificStrategy = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Parse all the Strategies\n\t\tif (strategy.HasMember(\"Strategies\") && strategy[\"Strategies\"].IsObject())\n\t\t{\n\t\t\tconst rapidjson::Value &strategies = strategy[\"Strategies\"];\n\t\t\tfor (rapidjson::Value::ConstMemberIterator itr = strategies.MemberBegin(); itr != strategies.MemberEnd(); ++itr)\n\t\t\t{\n\t\t\t\tconst std::string &name = itr->name.GetString();\n\t\t\t\tconst rapidjson::Value &val = itr->value;\n\n\t\t\t\tBWAPI::Race strategyRace;\n\t\t\t\tif (val.HasMember(\"Race\") && val[\"Race\"].IsString())\n\t\t\t\t{\n\t\t\t\t\tstrategyRace = GetRace(val[\"Race\"].GetString());\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tUAB_ASSERT_WARNING(false, \"Strategy must have a Race string. Skipping strategy %s\", name.c_str());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tBuildOrder buildOrder(strategyRace);\n\t\t\t\tif (val.HasMember(\"OpeningBuildOrder\") && val[\"OpeningBuildOrder\"].IsArray())\n\t\t\t\t{\n\t\t\t\t\tconst rapidjson::Value &build = val[\"OpeningBuildOrder\"];\n\n\t\t\t\t\tfor (size_t b(0); b < build.Size(); ++b)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (build[b].IsString())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tMetaType type(build[b].GetString());\n\n\t\t\t\t\t\t\tif (type.getRace() != BWAPI::Races::None)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tbuildOrder.add(type);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tUAB_ASSERT_WARNING(false, \"Build order item must be a string %s\", name.c_str());\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tGlobal::Strategy().addStrategy(name, Strategy(name, strategyRace, buildOrder));\n\t\t\t}\n\t\t}\n\t}\n\n\tConfig::ConfigFile::ConfigFileParsed = true;\n}\n\nvoid ParseUtils::ParseTextCommand(const std::string &commandString)\n{\n\tstd::stringstream ss(commandString);\n\n\tstd::string command;\n\tstd::transform(command.begin(), command.end(), command.begin(), ::tolower);\n\n\tstd::string variableName;\n\tstd::transform(variableName.begin(), variableName.end(), variableName.begin(), ::tolower);\n\n\tstd::string val;\n\n\tss >> command;\n\tss >> variableName;\n\tss >> val;\n\n\tif (command == \"\/set\")\n\t{\n\t\t\/\/ BWAPI options\n\t\tif (variableName == \"setlocalspeed\")\n\t\t{\n\t\t\tConfig::BWAPIOptions::SetLocalSpeed = GetIntFromString(val);\n\t\t\tBWAPI::Broodwar->setLocalSpeed(Config::BWAPIOptions::SetLocalSpeed);\n\t\t}\n\t\telse if (variableName == \"setframeskip\")\n\t\t{\n\t\t\tConfig::BWAPIOptions::SetFrameSkip = GetIntFromString(val);\n\t\t\tBWAPI::Broodwar->setFrameSkip(Config::BWAPIOptions::SetFrameSkip);\n\t\t}\n\t\telse if (variableName == \"userinput\")\n\t\t{\n\t\t\tConfig::BWAPIOptions::EnableUserInput = GetBoolFromString(val);\n\t\t\tif (Config::BWAPIOptions::EnableUserInput)\n\t\t\t\tBWAPI::Broodwar->enableFlag(BWAPI::Flag::UserInput);\n\t\t}\n\t\telse if (variableName == \"completemapinformation\")\n\t\t{\n\t\t\tConfig::BWAPIOptions::EnableCompleteMapInformation = GetBoolFromString(val);\n\t\t\tif (Config::BWAPIOptions::EnableCompleteMapInformation)\n\t\t\t\tBWAPI::Broodwar->enableFlag(BWAPI::Flag::UserInput);\n\t\t}\n\n\t\t\/\/ Micro Options\n\t\telse if (variableName == \"usesparcraftsimulation\")\n\t\t{\n\t\t\tConfig::Micro::UseSparcraftSimulation = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"workersdefendrush\")\n\t\t{\n\t\t\tConfig::Micro::WorkersDefendRush = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"incombatradius\")\n\t\t{\n\t\t\tConfig::Micro::CombatRadius = GetIntFromString(val);\n\t\t}\n\t\telse if (variableName == \"regroupradius\")\n\t\t{\n\t\t\tConfig::Micro::CombatRegroupRadius = GetIntFromString(val);\n\t\t}\n\t\telse if (variableName == \"unitnearenemyradius\")\n\t\t{\n\t\t\tConfig::Micro::UnitNearEnemyRadius = GetIntFromString(val);\n\t\t}\n\n\t\t\/\/ Macro Options\n\t\telse if (variableName == \"buildingspacing\")\n\t\t{\n\t\t\tConfig::Macro::BuildingSpacing = GetIntFromString(val);\n\t\t}\n\t\telse if (variableName == \"pylonspacing\")\n\t\t{\n\t\t\tConfig::Macro::PylonSpacing = GetIntFromString(val);\n\t\t}\n\n\t\t\/\/ Debug Options\n\t\telse if (variableName == \"errorlogfilename\")\n\t\t{\n\t\t\tConfig::Debug::ErrorLogFilename = val;\n\t\t}\n\t\telse if (variableName == \"printmoduletimeout\")\n\t\t{\n\t\t\tConfig::Debug::PrintModuleTimeout = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawbuildordersearchinfo\")\n\t\t{\n\t\t\tConfig::Debug::DrawBuildOrderSearchInfo = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawunithealthbars\")\n\t\t{\n\t\t\tConfig::Debug::DrawUnitHealthBars = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawproductioninfo\")\n\t\t{\n\t\t\tConfig::Debug::DrawProductionInfo = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawenemyunitinfo\")\n\t\t{\n\t\t\tConfig::Debug::DrawEnemyUnitInfo = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawmoduletimers\")\n\t\t{\n\t\t\tConfig::Debug::DrawModuleTimers = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawresourceinfo\")\n\t\t{\n\t\t\tConfig::Debug::DrawResourceInfo = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawcombatsiminfo\")\n\t\t{\n\t\t\tConfig::Debug::DrawCombatSimulationInfo = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawunittargetinfo\")\n\t\t{\n\t\t\tConfig::Debug::DrawUnitTargetInfo = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawbwtainfo\")\n\t\t{\n\t\t\tConfig::Debug::DrawBWTAInfo = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawmapgrid\")\n\t\t{\n\t\t\tConfig::Debug::DrawMapGrid = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawsquadinfo\")\n\t\t{\n\t\t\tConfig::Debug::DrawSquadInfo = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawworkerinfo\")\n\t\t{\n\t\t\tConfig::Debug::DrawWorkerInfo = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawmousecursorinfo\")\n\t\t{\n\t\t\tConfig::Debug::DrawMouseCursorInfo = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawbuildinginfo\")\n\t\t{\n\t\t\tConfig::Debug::DrawBuildingInfo = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"drawreservedbuildingtiles\")\n\t\t{\n\t\t\tConfig::Debug::DrawReservedBuildingTiles = GetBoolFromString(val);\n\t\t}\n\n\t\t\/\/ Module Options\n\t\telse if (variableName == \"usegamecommander\")\n\t\t{\n\t\t\tConfig::Modules::UsingGameCommander = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"usescoutmanager\")\n\t\t{\n\t\t\tConfig::Modules::UsingScoutManager = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"usecombatcommander\")\n\t\t{\n\t\t\tConfig::Modules::UsingCombatCommander = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"usebuildordersearch\")\n\t\t{\n\t\t\tConfig::Modules::UsingBuildOrderSearch = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"useautoobserver\")\n\t\t{\n\t\t\tConfig::Modules::UsingAutoObserver = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"usestrategyio\")\n\t\t{\n\t\t\tConfig::Modules::UsingStrategyIO = GetBoolFromString(val);\n\t\t}\n\t\telse if (variableName == \"useunitcommandmanager\")\n\t\t{\n\t\t\tConfig::Modules::UsingUnitCommandManager = GetBoolFromString(val);\n\t\t}\n\n\t\telse\n\t\t{\n\t\t\tUAB_ASSERT_WARNING(false, \"Unknown variable name for \/set: %s\", variableName.c_str());\n\t\t}\n\t}\n\telse\n\t{\n\t\tUAB_ASSERT_WARNING(false, \"Unknown command: %s\", command.c_str());\n\t}\n}\n\nBWAPI::Race ParseUtils::GetRace(const std::string &raceName)\n{\n\tif (raceName == \"Protoss\")\n\t{\n\t\treturn BWAPI::Races::Protoss;\n\t}\n\n\tif (raceName == \"Terran\")\n\t{\n\t\treturn BWAPI::Races::Terran;\n\t}\n\n\tif (raceName == \"Zerg\")\n\t{\n\t\treturn BWAPI::Races::Zerg;\n\t}\n\n\tif (raceName == \"Random\")\n\t{\n\t\treturn BWAPI::Races::Random;\n\t}\n\n\tUAB_ASSERT_WARNING(false, \"Race not found: %s\", raceName.c_str());\n\treturn BWAPI::Races::None;\n}\n\nint ParseUtils::GetIntFromString(const std::string &str)\n{\n\tstd::stringstream ss(str);\n\tint a = 0;\n\tss >> a;\n\treturn a;\n}\n\nbool ParseUtils::GetBoolFromString(const std::string &str)\n{\n\tstd::string boolStr(str);\n\tstd::transform(boolStr.begin(), boolStr.end(), boolStr.begin(), ::tolower);\n\n\tif (boolStr == \"true\" || boolStr == \"t\")\n\t{\n\t\treturn true;\n\t}\n\telse if (boolStr == \"false\" || boolStr == \"f\")\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\tUAB_ASSERT_WARNING(false, \"Unknown bool from string: %s\", str.c_str());\n\t}\n\n\treturn false;\n}","avg_line_length":33.223880597,"max_line_length":144,"alphanum_fraction":0.7109485304,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7269,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"#include \"RosKCF.h\"\n#include <ros\/ros.h>\n#include <iostream>\n#include <opencv2\/opencv.hpp>\n#include <image_transport\/image_transport.h>\n#include <cv_bridge\/cv_bridge.h> \n#include <sensor_msgs\/image_encodings.h> \n#include \"ros_kcf\/InitRect.h\"\n#include \"std_msgs\/Int32MultiArray.h\"\n#include \"sensor_msgs\/PointCloud.h\"\n\n#include <vector>\n#include \"kcftracker.hpp\"\n\nusing namespace std;\nusing namespace cv;\n\nRosKCF::RosKCF():_rgb_topic(\"\/realsense\/color\/image_raw\"), \n                 _dsp_topic(\"\/realsense\/depth\/image_rect_raw\"), \n                 _camera_info(\"\/realsense\/color\/camera_info\"),\n                 track_rect_(\"\/track_rect_pub\"),\n                 target_pose_(\"\/target_pose\")                 \n{\n    this->service = nodeHandle.advertiseService(\"init_rect\", &RosKCF::setInitRect, this);\n    this->trackPub = nodeHandle.advertise<std_msgs::Int32MultiArray>(track_rect_, 1000);\n    this->targetPosePub = nodeHandle.advertise<sensor_msgs::PointCloud>(target_pose_, 1000);\n    image_transport::ImageTransport it(nodeHandle);\n    ros::NodeHandle nh_;\n    this->imageSub = it.subscribe(_rgb_topic, 100, &RosKCF::buildAndTrack, this);\n    this->dispritySub = it.subscribe(_dsp_topic, 100, &RosKCF::computerTrackPose, this);\n    this->cameraInfoSub = nh_.subscribe(_camera_info, 100, &RosKCF::onCameraInfoCb, this);\n    this->initRectPtr = NULL;\n    this->kcfPtr = NULL;\n}\n\nbool RosKCF::setInitRect(ros_kcf::InitRect::Request &req, ros_kcf::InitRect::Response &res)\n{\n    int tlx = req.xmin;\n    int tly = req.ymin;\n    int brx = req.xmax;\n    int bry = req.ymax;\n    res.sum = 10000; \/\/ test\n    this->initRectPtr = new cv::Rect(Point2d(tlx, tly), Point2d(brx, bry));\n    std::cout<<\"Init received rect: \" << *initRectPtr << std::endl;\n    return true;\n}\n\nvoid RosKCF::buildAndTrack(const sensor_msgs::ImageConstPtr &msg)\n{\n    try{\n        cv::Mat img = cv_bridge::toCvShare(msg, \"bgr8\")->image;\n        if (initRectPtr == NULL) return;\n\n        if (kcfPtr == NULL && initRectPtr != NULL)\n        {\n            cout<<\"Set KCF init Rect!\"<<endl;\n            kcfPtr = new KCFTracker(HOG, FIXEDWINDOW, MULTISCALE, LAB);\n            kcfPtr->init(*initRectPtr, img);\n\n            return ;\n        }\n        else\n        {\n            \n            result_ = kcfPtr->update(img);\n\n            int x1 = result_.tl().x;\n            int y1 = result_.tl().y;\n            int x2 = result_.br().x;\n            int y2 = result_.br().y;\n            cout<<\"Track rect: {[\"<< x1 << \" \" << y1 << \"], [\"<< x2 << \" \"<< y2 <<\"]}\"<<endl;\n\n            vector<int> trackResult;\n            trackResult.push_back(result_.tl().x);\n            trackResult.push_back(result_.tl().y);\n            trackResult.push_back(result_.br().x);\n            trackResult.push_back(result_.br().y);\n            trackResultMsg.data = trackResult;\n            trackPub.publish(trackResultMsg);\n\n            getTrackShow(img, result_);\n            return ;\n        }\n        \n    }catch(cv_bridge::Exception &e){\n        ROS_ERROR(\"Could not convert from '%s' to 'bgr8'.\", msg->encoding.c_str());\n    }\n}\n\nvoid RosKCF::onCameraInfoCb(const sensor_msgs::CameraInfoConstPtr &msg)\n{\n    width_ = msg->width;\n    height_ = msg->height;\n    fBaseline_ = msg->K[3];\n    fFocus_ = msg->K[0];\n    cx_ = msg->K[2];\n    cy_ = msg->K[5];\n    fBF_ = fFocus_ * fBaseline_;\n#if 0    \n    ROS_INFO(\"Recive_CameraInfo: Camera Height: %u, Width: %u, BF: %f, Baseline: %f, Focus: %f\",\n                    height_, width_, fBF_, fBaseline_, fFocus_);\n#endif\n}\n\nvoid RosKCF::computerTrackPose(const sensor_msgs::ImageConstPtr &msg)\n{\n    try{\n        depth_img_ = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::TYPE_32FC1)->image;     \n        computerDepthRegion();\n    }catch(cv_bridge::Exception &e){\n        ROS_ERROR(\"Could not convert from '%s' to 'TYPE_32FC1'.\", msg->encoding.c_str());\n    }\n}\n\nvoid RosKCF::computerDepthRegion()\n{\n    float xx_ = 0;\n    float yy_ = 0;\n    cv::Mat roi_depth = depth_img_(result_);\n    \/\/ drawHistGraph(roi_depth); \n    goal_.z = cmpRegionDepth(roi_depth);\n    if(goal_.z > 0.1f && result_.area() > 0) {\n        goal_.x = (((result_.x + cvRound(result_.width\/2.0)) - cx_)*goal_.z)\/fFocus_;\n        goal_.y = (((result_.y + cvRound(result_.height\/2.0)) - cy_)*goal_.z)\/fFocus_;\n    }\n\n    sensor_msgs::PointCloud _goal_point;\n    _goal_point.header.stamp = ros::Time::now();\n    _goal_point.header.frame_id = \"base_link\";\n    _goal_point.points.resize(1);\n    _goal_point.channels.resize(1);\n    _goal_point.channels[0].name = \"current\";    \n    _goal_point.points[0].x = goal_.z;\n    _goal_point.points[0].y = -goal_.x;\n    _goal_point.points[0].z = goal_.y;\n\n    targetPosePub.publish(_goal_point);\n\n#if 0\n    std::cout << \"Goal : \" << goal_ << std::endl;\n    std::cout << \"ROI:\" << roi_depth.cols << \" \" << roi_depth.rows << std::endl;    \n#endif    \n}\n\nvoid RosKCF::drawHistGraph(cv::Mat _img)\n{\n    int histSize[1] = {200};    \/\/ \u6307\u7684\u662f\u76f4\u65b9\u56fe\u5206\u6210\u591a\u5c11\u4e2a\u533a\u95f4\n    int channels[1] = {0};\n    float hr1[] = {0, 20};      \/\/\u77e9\u9635b\u7684\u6df1\u5ea6\u503c\u6709\u6548\u8303\u56f4\u662f0<=V<20\n    const float* ranges[] = {hr1};    \n    int hist_h = 200;       \/\/\u76f4\u65b9\u56fe\u7684\u56fe\u50cf\u7684\u9ad8\n    int hist_w = 400;       \/\/\u76f4\u65b9\u56fe\u7684\u56fe\u50cf\u7684\u5bbd    \n    int bin_w = hist_w \/ histSize[0];  \/\/\u76f4\u65b9\u56fe\u7684\u7b49\u7ea7\n    float max_hist = 0.0;\n    Point max_point(0.0, 0.0);\n\n    cv::Mat histImage = cv::Mat(hist_h, hist_w, CV_8UC1, Scalar(0));\/\/\u7ed8\u5236\u76f4\u65b9\u56fe\u663e\u793a\u7684\u56fe\u50cf\n    calcHist(&_img, 1, channels, Mat(), hist_, 1, histSize, ranges, true);\n    normalize(hist_, hist_, 0, hist_h, cv::NORM_MINMAX, -1, Mat());   \/\/\u5f52\u4e00\u5316\n\tfor (int i = 1; i < histSize[0]; i++)\n\t{\n        if(hist_.at<float>(i - 1) > max_hist) {\n            max_hist = hist_.at<float>(i - 1);\n            max_point.x = float(i)\/10;\n            max_point.y = max_hist;\n        }\n\n\t\tline(histImage, Point((i - 1)*bin_w, hist_h - cvRound(hist_.at<float>(i - 1))),\n\t\t\tPoint((i)*bin_w, hist_h - cvRound(hist_.at<float>(i))), Scalar(100), 1, CV_AA);\n#if 0\n\t\tline(histImage, Point((i - 1)*bin_w, hist_h),  \n            Point((i - 1)*bin_w, hist_h - cvRound(hist_.at<float>(i - 1))), Scalar(100), 1);      \n#endif              \n\t}\n\n    std::cout << \"Max Point : \" << max_point << std::endl;\n\tcv::imshow(output, histImage);\n    cv::waitKey(10);\n}\n\nfloat RosKCF::cmpRegionDepth(cv::Mat _img)\n{\n    int ocp_pixels = 0;\n    float accm_value = 0.0f;    \n    auto pixels_num = result_.area();\n    float avg_depth = 0.0f;\n    float avg_sat = 0.0f;\n\n    std::vector<float> ocp_depths(pixels_num);\n    if (!_img.empty()) {\n        for (int x = 0; x < _img.cols; x++) {\n            for (int y = 0; y < _img.rows; y++) {\n                float d = _img.at<float>(y, x);\n                if (d > 0.1f) {\n                    ocp_depths[ocp_pixels] = d;\n                    accm_value += d;\n                    ocp_pixels++;\n                }\n            }\n        }\n    }\n    if(ocp_pixels > 0) {\n        avg_depth = accm_value \/ ocp_pixels;\n        avg_sat = (float)ocp_pixels \/ pixels_num; \n    }\n \n#if 1    \n    std::cout << \"AVG_DEPTH : \" << avg_depth << \", AVG_STATION : \" << avg_sat << \", ocp_pixels : \" << ocp_pixels << std::endl;\n#endif\n    return avg_depth;\n}\n\nvoid RosKCF::getTrackShow(cv::Mat _img, cv::Rect _rect)\n{\n    cv::rectangle(_img, _rect, Scalar(255, 0, 0), 1, 1, 0);\n    cv::imshow(\"TrackerShow\", _img);\n    if (waitKey(2) >= 0)\n        return;   \n}\n","avg_line_length":33.0409090909,"max_line_length":126,"alphanum_fraction":0.5857752098,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6234,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":4054.0,"content":"\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \"matchengine.h\"\n#include <vespa\/searchcore\/proton\/common\/state_reporter_utils.h>\n#include <vespa\/searchlib\/fef\/indexproperties.h>\n#include <vespa\/vespalib\/data\/slime\/cursor.h>\n#include <vespa\/vespalib\/data\/smart_buffer.h>\n#include <vespa\/vespalib\/data\/slime\/binary_format.h>\n#include <vespa\/vespalib\/util\/size_literals.h>\n\n#include <vespa\/log\/log.h>\n\nLOG_SETUP(\".proton.matchengine.matchengine\");\n\nnamespace {\n\nclass SearchTask : public vespalib::Executor::Task {\nprivate:\n    proton::MatchEngine                   &_engine;\n    search::engine::SearchRequest::Source  _request;\n    search::engine::SearchClient          &_client;\n\npublic:\n    SearchTask(proton::MatchEngine &engine,\n               search::engine::SearchRequest::Source request,\n               search::engine::SearchClient &client)\n        : _engine(engine),\n          _request(std::move(request)),\n          _client(client)\n    { }\n\n    void run() override {\n        _client.searchDone(_engine.performSearch(std::move(_request)));\n    }\n};\n\nVESPA_THREAD_STACK_TAG(match_engine_executor)\n\n} \/\/ namespace anon\n\nnamespace proton {\n\nusing namespace vespalib::slime;\n\nMatchEngine::MatchEngine(size_t numThreads, size_t threadsPerSearch, uint32_t distributionKey, bool async)\n    : _lock(),\n      _distributionKey(distributionKey),\n      _async(async),\n      _closed(false),\n      _handlers(),\n      _executor(std::max(size_t(1), numThreads \/ threadsPerSearch), 256_Ki, match_engine_executor),\n      _threadBundlePool(std::max(size_t(1), threadsPerSearch)),\n      _nodeUp(false)\n{\n}\n\nMatchEngine::~MatchEngine()\n{\n    _executor.shutdown().sync();\n}\n\nvoid\nMatchEngine::close()\n{\n    LOG(debug, \"Closing search interface.\");\n    {\n        std::lock_guard<std::mutex> guard(_lock);\n        _closed = true;\n    }\n\n    LOG(debug, \"Handshaking with task manager.\");\n    _executor.sync();\n}\n\nISearchHandler::SP\nMatchEngine::putSearchHandler(const DocTypeName &docTypeName,\n                              const ISearchHandler::SP &searchHandler)\n{\n    std::lock_guard<std::mutex> guard(_lock);\n    return _handlers.putHandler(docTypeName, searchHandler);\n}\n\nISearchHandler::SP\nMatchEngine::getSearchHandler(const DocTypeName &docTypeName)\n{\n    std::lock_guard<std::mutex> guard(_lock);\n    return _handlers.getHandler(docTypeName);\n}\n\nISearchHandler::SP\nMatchEngine::removeSearchHandler(const DocTypeName &docTypeName)\n{\n    std::lock_guard<std::mutex> guard(_lock);\n    return _handlers.removeHandler(docTypeName);\n}\n\nsearch::engine::SearchReply::UP\nMatchEngine::search(search::engine::SearchRequest::Source request,\n                    search::engine::SearchClient &client)\n{\n    if (_closed || !_nodeUp) {\n        auto ret = std::make_unique<search::engine::SearchReply>();\n        ret->setDistributionKey(_distributionKey);\n\n        \/\/ TODO: Notify closed.\n\n        return ret;\n    }\n    if (_async) {\n        _executor.execute(std::make_unique<SearchTask>(*this, std::move(request), client));\n        return search::engine::SearchReply::UP();\n    }\n    return performSearch(std::move(request));\n}\n\nstd::unique_ptr<search::engine::SearchReply>\nMatchEngine::performSearch(search::engine::SearchRequest::Source req)\n{\n    auto my_issues = std::make_unique<search::UniqueIssues>();\n    auto capture_issues = vespalib::Issue::listen(*my_issues);\n\n    auto ret = std::make_unique<search::engine::SearchReply>();\n\n    const search::engine::SearchRequest * searchRequest = req.get();\n    if (searchRequest) {\n        \/\/ 3 is the minimum level required for backend tracing.\n        searchRequest->setTraceLevel(search::fef::indexproperties::trace::Level::lookup(searchRequest->propertiesMap.modelOverrides(), searchRequest->getTraceLevel()), 3);\n        ISearchHandler::SP searchHandler;\n        vespalib::SimpleThreadBundle::UP threadBundle = _threadBundlePool.obtain();\n        { \/\/ try to find the match handler corresponding to the specified search doc type\n            DocTypeName docTypeName(*searchRequest);\n            std::lock_guard<std::mutex> guard(_lock);\n            searchHandler = _handlers.getHandler(docTypeName);\n        }\n        if (searchHandler) {\n            ret = searchHandler->match(*searchRequest, *threadBundle);\n        } else {\n            HandlerMap<ISearchHandler>::Snapshot snapshot;\n            {\n                std::lock_guard<std::mutex> guard(_lock);\n                snapshot = _handlers.snapshot();\n            }\n            if (snapshot.valid()) {\n                ret = snapshot.get()->match(*searchRequest, *threadBundle); \/\/ use the first handler\n            }\n        }\n        _threadBundlePool.release(std::move(threadBundle));\n    }\n    ret->request = req.release();\n    ret->my_issues = std::move(my_issues);\n    ret->setDistributionKey(_distributionKey);\n    if ((ret->request->trace().getLevel() > 0) && ret->request->trace().hasTrace()) {\n        ret->request->trace().getRoot().setLong(\"distribution-key\", _distributionKey);\n        ret->request->trace().done();\n        search::fef::Properties & trace = ret->propertiesMap.lookupCreate(\"trace\");\n        vespalib::SmartBuffer output(4_Ki);\n        vespalib::slime::BinaryFormat::encode(ret->request->trace().getSlime(), output);\n        trace.add(\"slime\", output.obtain().make_stringref());\n    }\n    return ret;\n}\n\nbool MatchEngine::isOnline() const {\n    return _nodeUp;\n}\n\n\nvoid\nMatchEngine::setNodeUp(bool nodeUp)\n{\n    _nodeUp = nodeUp;\n}\n\n\nStatusReport::UP\nMatchEngine::reportStatus() const\n{\n    if (isOnline()) {\n        return StatusReport::create(StatusReport::Params(\"matchengine\").\n                state(StatusReport::UPOK).\n                internalState(\"ONLINE\"));\n    } else {\n        return StatusReport::create(StatusReport::Params(\"matchengine\").\n                state(StatusReport::DOWN).\n                internalState(\"OFFLINE\").\n                message(\"Search interface is offline\"));\n    }\n}\n\nvoid\nMatchEngine::get_state(const Inserter &inserter, bool full) const\n{\n    (void) full;\n    Cursor &object = inserter.insertObject();\n    StateReporterUtils::convertToSlime(*reportStatus(), ObjectInserter(object, \"status\"));\n}\n\n} \/\/ namespace proton\n","avg_line_length":31.4848484848,"max_line_length":171,"alphanum_fraction":0.6657042028,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":120,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <bits\/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int a,b;\r\n    cin >> a >> b;\r\n    cout << a+b;\r\n}","avg_line_length":12.0,"max_line_length":25,"alphanum_fraction":0.4666666667,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1748,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":19.0,"content":"\/\/ Tote Grasp state for APC\n\/\/ Author: Christian Lenz <chrislenz@uni-bonn.de>\n\n#include <ros\/console.h>\n#include <apc_control\/control.h>\n#include <apc_control\/states\/stowing\/tote_grasp.h>\n#include <apc_control\/states\/stowing\/tote_retract.h>\n#include <apc_control\/states\/check_grasp.h>\n\n#include <apc_control\/apc_database.h>\n\n#include <nimbro_keyframe_server\/keyframe.h>\n\n#include <eigen_conversions\/eigen_msg.h>\n\n\n\nnamespace apc_control\n{\n\tToteGrasp::ToteGrasp(bool tryAgain)\n\t : m_tryAgain(tryAgain)\n\t{\n\t}\n\n\tToteGrasp::~ToteGrasp()\n\t{\n\t}\n\n\tnimbro_keyframe_server::PlayMotionGoal ToteGrasp::computeGoal()\n\t{\n\t\tnimbro_keyframe_server::PlayMotionGoal goal;\n\n\t\tif(m_tryAgain)\n\t\t{\n\t\t\tgoal.motion_msg = driver()->getGrasp()->toMsg();\n\t\t\tgoal.motion_name=\"tote_grasp\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgoal.motion_msg = driver()->getGrasp2()->toMsg();\n\t\t\tgoal.motion_name=\"tote_grasp2\";\n\t\t}\n\t\tgoal.use_existing_motion=false;\n\n\t\treturn goal;\n\t}\n\n\n\tnimbro_fsm::StateBase* ToteGrasp::nextState()\n\t{\n\t\tif(m_tryAgain){\n\t\t\tdriver()->switchVacuum(true);\n\t\t\treturn new CheckGrasp();\n\t\t}\n\t\telse\n\t\t\treturn new ToteRetract();\n\t}\n\n\tnimbro_fsm::StateBase* ToteGrasp::execute()\n\t{\n\t\tif(driver()->objectWellAttached())\n\t\t{\n\t\t\tROS_INFO(\"I already got it! (in ToteGrasp state)\");\n\t\t\treturn new ToteRetract();\n\t\t}\n\n\t\treturn MoveArm::execute();\n\t}\n\n\tnimbro_fsm::StateBase* ToteGrasp::onProtectiveStop(const nimbro_keyframe_server::PlayMotionResultConstPtr& result)\n\t{\n\t\tif(result->finish_state == nimbro_keyframe_server::PlayMotionResult::REJECTED)\n\t\t\treturn MoveArm::onProtectiveStop(result);\n\n\t\tROS_ERROR(\"Trying to retract...\");\n\t\tif(unlockProtectiveStop())\n\t\t{\n\t\t\tdriver()->switchVacuum(true);\n\t\t\tsleep(1);\n\t\t\treturn new ToteRetract();\n\t\t}\n\n\t\tdriver()->shutdown();\n\t\treturn 0;\n\t}\n\n\n}\n","avg_line_length":19.6404494382,"max_line_length":115,"alphanum_fraction":0.7145308924,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6936,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/\n\/\/  DeviceJavaInterface.cpp\n\/\/  Chilli Source\n\/\/  Created by Scott Downie on 24\/09\/2014.\n\/\/\n\/\/  The MIT License (MIT)\n\/\/\n\/\/  Copyright (c) 2014 Tag Games Limited\n\/\/\n\/\/  Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/  of this software and associated documentation files (the \"Software\"), to deal\n\/\/  in the Software without restriction, including without limitation the rights\n\/\/  to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/  copies of the Software, and to permit persons to whom the Software is\n\/\/  furnished to do so, subject to the following conditions:\n\/\/\n\/\/  The above copyright notice and this permission notice shall be included in\n\/\/  all copies or substantial portions of the Software.\n\/\/\n\/\/  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/  THE SOFTWARE.\n\/\/\n\n#ifdef CS_TARGETPLATFORM_ANDROID\n\n#include <CSBackend\/Platform\/Android\/Core\/Base\/DeviceJavaInterface.h>\n\n#include <CSBackend\/Platform\/Android\/ForwardDeclarations.h>\n#include <CSBackend\/Platform\/Android\/Core\/JNI\/JavaInterfaceManager.h>\n#include <CSBackend\/Platform\/Android\/Core\/JNI\/JavaInterfaceUtils.h>\n\nnamespace CSBackend\n{\n\tnamespace Android\n\t{\n\t\tCS_DEFINE_NAMEDTYPE(DeviceJavaInterface);\n\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\tDeviceJavaInterface::DeviceJavaInterface()\n\t\t: m_OSVersionCode(-1), m_numberOfCores(-1)\n\t\t{\n\t\t\tCreateNativeInterface(\"com\/chilliworks\/chillisource\/core\/DeviceNativeInterface\");\n\t\t\tCreateMethodReference(\"getDefaultLocaleCode\", \"()Ljava\/lang\/String;\");\n\t\t\tCreateMethodReference(\"getDeviceModel\", \"()Ljava\/lang\/String;\");\n\t\t\tCreateMethodReference(\"getDeviceManufacturer\", \"()Ljava\/lang\/String;\");\n\t\t\tCreateMethodReference(\"getDeviceModelType\", \"()Ljava\/lang\/String;\");\n\t\t\tCreateMethodReference(\"getOSVersion\", \"()I\");\n\t\t\tCreateMethodReference(\"getNumberOfCores\", \"()I\");\n\t\t\tCreateMethodReference(\"getUniqueId\", \"()Ljava\/lang\/String;\");\n\t\t}\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\tbool DeviceJavaInterface::IsA(CSCore::InterfaceIDType in_interfaceId) const\n\t\t{\n\t\t\treturn (in_interfaceId == DeviceJavaInterface::InterfaceID);\n\t\t}\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\tstd::string DeviceJavaInterface::GetDefaultLocaleCode()\n\t\t{\n\t\t\tif (m_localeCode == \"\")\n\t\t\t{\n\t\t\t\tJNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();\n\t\t\t\tjstring jstrLocalCode = static_cast<jstring>(env->CallObjectMethod(GetJavaObject(), GetMethodID(\"getDefaultLocaleCode\")));\n\t\t\t\tm_localeCode = JavaInterfaceUtils::CreateSTDStringFromJString(jstrLocalCode);\n\t\t\t\tenv->DeleteLocalRef(jstrLocalCode);\n\t\t\t}\n\t\t\treturn m_localeCode;\n\t\t}\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\tstd::string DeviceJavaInterface::GetDeviceModel()\n\t\t{\n\t\t\tif (m_deviceModel == \"\")\n\t\t\t{\n\t\t\t\tJNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();\n\t\t\t\tjstring jstrDeviceModel = static_cast<jstring>(env->CallObjectMethod(GetJavaObject(), GetMethodID(\"getDeviceModel\")));\n\t\t\t\tm_deviceModel = JavaInterfaceUtils::CreateSTDStringFromJString(jstrDeviceModel);\n\t\t\t\tenv->DeleteLocalRef(jstrDeviceModel);\n\t\t\t}\n\t\t\treturn m_deviceModel;\n\t\t}\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\tstd::string DeviceJavaInterface::GetDeviceModelType()\n\t\t{\n\t\t\tif (m_deviceModelType == \"\")\n\t\t\t{\n\t\t\t\tJNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();\n\t\t\t\tjstring jstrDeviceModelType = static_cast<jstring>(env->CallObjectMethod(GetJavaObject(), GetMethodID(\"getDeviceModelType\")));\n\t\t\t\tm_deviceModelType = JavaInterfaceUtils::CreateSTDStringFromJString(jstrDeviceModelType);\n\t\t\t\tenv->DeleteLocalRef(jstrDeviceModelType);\n\t\t\t}\n\t\t\treturn m_deviceModelType;\n\t\t}\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\tstd::string DeviceJavaInterface::GetDeviceManufacturer()\n\t\t{\n\t\t\tif (m_deviceManufacturer == \"\")\n\t\t\t{\n\t\t\t\tJNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();\n\t\t\t\tjstring jstrDeviceManufacturer = static_cast<jstring>(env->CallObjectMethod(GetJavaObject(), GetMethodID(\"getDeviceManufacturer\")));\n\t\t\t\tm_deviceManufacturer = JavaInterfaceUtils::CreateSTDStringFromJString(jstrDeviceManufacturer);\n\t\t\t\tenv->DeleteLocalRef(jstrDeviceManufacturer);\n\t\t\t}\n\t\t\treturn m_deviceManufacturer;\n\t\t}\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\ts32 DeviceJavaInterface::GetOSVersionCode()\n\t\t{\n\t\t\tif (m_OSVersionCode == -1)\n\t\t\t{\n\t\t\t\tJNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();\n\t\t\t\tm_OSVersionCode = env->CallIntMethod(GetJavaObject(), GetMethodID(\"getOSVersion\"));\n\t\t\t}\n\t\t\treturn m_OSVersionCode;\n\t\t}\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\t\/\/--------------------------------------------------------------------------------------\n\t\ts32 DeviceJavaInterface::GetNumberOfCores()\n\t\t{\n\t\t\tif (m_numberOfCores == -1)\n\t\t\t{\n\t\t\t\tJNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();\n\t\t\t\tm_numberOfCores = env->CallIntMethod(GetJavaObject(), GetMethodID(\"getNumberOfCores\"));\n\t\t\t}\n\t\t\treturn m_numberOfCores;\n\t\t}\n\t\t\/\/--------------------------------------------------------------\n\t\t\/\/--------------------------------------------------------------\n\t\tstd::string DeviceJavaInterface::GetUniqueId()\n\t\t{\n\t\t\tstd::string output = \"\";\n\t\t\tJNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();\n\t\t\tjstring adId = static_cast<jstring>(env->CallObjectMethod(GetJavaObject(), GetMethodID(\"getUniqueId\")));\n\t\t\toutput = JavaInterfaceUtils::CreateSTDStringFromJString(adId);\n\t\t\tenv->DeleteLocalRef(adId);\n\t\t\treturn output;\n\t\t}\n\t}\n}\n\n#endif\n","avg_line_length":45.6315789474,"max_line_length":136,"alphanum_fraction":0.5803056517,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":554,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\nusing std::cout;\nusing std::cin;\n\n#include <string>\nusing std::string;\n\nint main()\n{\n\tstring name;\n\tcout << \"Who are you? \";\n\tcin >> name;\n\tstring greeting = \"Hello, \" + name;\n\tif (name == \"Nate\")\n\t{\n\t\tgreeting += \", I know you!\";\n\t}\n\tcout << greeting << '\\n';\n\n\tint l = greeting.length();\n\tcout << \"\\\"\" + greeting + \"\\\" is \" << l << \" characters long.\" << '\\n';\n\tstring beginning = greeting.substr(greeting.find(' ') + 1);\n\tcout << beginning << '\\n';\n\tif (beginning == name)\n\t{\n\t\tcout << \"expected result.\" << '\\n';\n\t}\n\n\n\treturn 0;\n}","avg_line_length":17.8709677419,"max_line_length":72,"alphanum_fraction":0.5577617329,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6604,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":null,"content":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"interrupts.hpp\"\n#include \"console.hpp\"\n#include \"kernel_utils.hpp\"\n#include \"gdt.hpp\"\n\n#include \"isrs.hpp\"\n#include \"irqs.hpp\"\n\n#include \"stl\/types.hpp\"\n\nnamespace {\n\nstruct idt_entry {\n    uint16_t offset_low;\n    uint16_t segment_selector;\n    uint8_t  zero;\n    uint8_t flags;\n    uint16_t offset_middle;\n    uint32_t offset_high;\n    uint32_t reserved;\n} __attribute__((packed));\n\nstatic_assert(sizeof(idt_entry) == 16, \"The size of an IDT entry should be 16 bits\");\n\nstruct idtr {\n    uint16_t limit;\n    uint64_t base;\n} __attribute__((packed));\n\nidt_entry idt_64[64];\nidtr idtr_64;\n\nvoid idt_set_gate(size_t gate, void (*function)(void), uint16_t gdt_selector, uint8_t flags){\n    auto& entry = idt_64[gate];\n\n    entry.segment_selector = gdt_selector;\n    entry.flags = flags;\n    entry.reserved = 0;\n    entry.zero = 0;\n\n    auto function_address = reinterpret_cast<uintptr_t>(function);\n    entry.offset_low = function_address & 0xFFFF;\n    entry.offset_middle = (function_address >> 16) & 0xFFFF;\n    entry.offset_high= function_address  >> 32;\n}\n\nvoid (*irq_handlers[16])();\n\nuint16_t get_cr2(){\n    uint16_t value;\n    __asm__ __volatile__(\"mov rax, cr2; mov %0, rax;\" : \"=m\" (value));\n    return value;\n}\n\n} \/\/end of anonymous namespace\n\nstruct regs {\n    uint64_t error_no;\n    uint64_t error_code;\n    uint64_t rip;\n    uint64_t rflags;\n    uint64_t cs;\n    uint64_t rsp;\n    uint64_t ss;\n} __attribute__((packed));\n\nextern \"C\" {\n\nvoid _fault_handler(regs regs){\n    k_printf(\"Exception (%u) occured\\n\", regs.error_no);\n    k_printf(\"error_code=%u\\n\", regs.error_code);\n    k_printf(\"rip=%h\\n\", regs.rip);\n    k_printf(\"rflags=%h\\n\", regs.rflags);\n    k_printf(\"cs=%h\\n\", regs.cs);\n    k_printf(\"rsp=%h\\n\", regs.rsp);\n    k_printf(\"ss=%h\\n\", regs.ss);\n    k_printf(\"cr2=%h\\n\", get_cr2());\n\n    \/\/TODO Improve that with kind of blue screen\n    \/\/TODO Display the title of the exception\n\n    __asm__ __volatile__(\"hlt\" : : );\n}\n\nvoid _irq_handler(size_t code){\n    \/\/If there is an handler, call it\n    if(irq_handlers[code]){\n        irq_handlers[code]();\n    }\n\n    \/\/If the IRQ is on the slaved controller, send EOI to it\n    if(code >= 8){\n        out_byte(0xA0, 0x20);\n    }\n\n    \/\/Send EOI to the master controller\n    out_byte(0x20, 0x20);\n}\n\n} \/\/end of extern \"C\"\n\nvoid interrupt::install_idt(){\n    \/\/Set the correct values inside IDTR\n    idtr_64.limit = (64 * 16) - 1;\n    idtr_64.base = reinterpret_cast<size_t>(&idt_64[0]);\n\n    \/\/Clear the IDT\n    std::fill_n(reinterpret_cast<size_t*>(idt_64), 64 * sizeof(idt_entry) \/ sizeof(size_t), 0);\n\n    \/\/Clear the IRQ handlers\n    std::fill_n(irq_handlers, 16, nullptr);\n\n    \/\/Give the IDTR address to the CPU\n    __asm__ __volatile__(\"lidt [%0]\" : : \"m\" (idtr_64));\n}\n\nvoid interrupt::install_isrs(){\n    \/\/TODO The GDT Selector should be computed in a better way\n\n    idt_set_gate(0, _isr0, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(1, _isr1, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(2, _isr2, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(3, _isr3, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(4, _isr4, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(5, _isr5, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(6, _isr6, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(7, _isr7, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(8, _isr8, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(9, _isr9, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(10, _isr10, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(11, _isr11, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(12, _isr12, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(13, _isr13, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(14, _isr14, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(15, _isr15, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(16, _isr16, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(17, _isr17, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(18, _isr18, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(19, _isr19, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(20, _isr20, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(21, _isr21, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(22, _isr22, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(23, _isr23, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(24, _isr24, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(25, _isr25, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(26, _isr26, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(27, _isr27, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(28, _isr28, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(29, _isr29, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(30, _isr30, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(31, _isr31, gdt::LONG_SELECTOR, 0x8E);\n}\n\nvoid interrupt::remap_irqs(){\n    \/\/Restart the both PICs\n    out_byte(0x20, 0x11);\n    out_byte(0xA0, 0x11);\n\n    out_byte(0x21, 0x20); \/\/Make PIC1 start at 32\n    out_byte(0xA1, 0x28); \/\/Make PIC2 start at 40\n\n    \/\/Setup cascading for both PICs\n    out_byte(0x21, 0x04);\n    out_byte(0xA1, 0x02);\n\n    \/\/8086 mode for both PICs\n    out_byte(0x21, 0x01);\n    out_byte(0xA1, 0x01);\n\n    \/\/Activate all IRQs in both PICs\n    out_byte(0x21, 0x0);\n    out_byte(0xA1, 0x0);\n}\n\nvoid interrupt::install_irqs(){\n    \/\/TODO The GDT Selector should be computed in a better way\n\n    idt_set_gate(32, _irq0, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(33, _irq1, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(34, _irq2, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(35, _irq3, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(36, _irq4, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(37, _irq5, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(38, _irq6, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(39, _irq7, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(40, _irq8, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(41, _irq9, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(42, _irq10, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(43, _irq11, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(44, _irq12, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(45, _irq13, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(46, _irq14, gdt::LONG_SELECTOR, 0x8E);\n    idt_set_gate(47, _irq15, gdt::LONG_SELECTOR, 0x8E);\n}\n\nvoid interrupt::register_irq_handler(size_t irq, void (*handler)()){\n    irq_handlers[irq] = handler;\n}\n\nvoid interrupt::enable_interrupts(){\n    __asm__ __volatile__(\"sti\" : : );\n}\n","avg_line_length":31.4476190476,"max_line_length":95,"alphanum_fraction":0.6692913386,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1210,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include<bits\/stdc++.h>\n\nusing namespace std;\n\nclass Node{\n    public:\n    int val;\n    Node *left;\n    Node *right;\n    Node(int x): val(x), left(NULL), right(NULL){}\n};\n\nbool cmp(pair<int,pair<int,int>> &p1, pair<int,pair<int,int>> &p2);\nvoid vertical_traversal(const Node *root, int h_dist, int v_dist,  map<int, vector<pair<int,pair<int,int>>>> &mp);\n\nint main(int argc, char const *argv[])\n{\n    \/* code *\/\n    Node *root= new Node(3);\n    root->left= new Node(9);\n    root->right= new Node(20);\n    root->right->left= new Node(15);\n    root->right->right= new Node(7);\n\n    map<int, vector<pair<int,pair<int,int>>>> mp;\n\n    vertical_traversal(root, 0,0, mp);\n    \n    for(auto x:mp){\n        std::sort(x.second.begin(), x.second.end(),cmp);\n        for(auto y:x.second){\n            cout<<y.first<<\" \";\n        }\n        cout<<endl;\n    }\n\n\n\n\n    return 0;\n}\n\n\n\n\nvoid vertical_traversal(const Node *root, int h_dist, int v_dist,  map<int,vector<pair<int,pair<int,int>>>>  &mp){\n    if(root){\n        mp[h_dist].push_back(make_pair(root->val,make_pair(h_dist,v_dist)));\n        vertical_traversal(root->left, h_dist-1,v_dist-1,mp);\n        vertical_traversal(root->right, h_dist+1,v_dist-1, mp);\n    }\n}\n","avg_line_length":22.8301886792,"max_line_length":114,"alphanum_fraction":0.5966942149,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":18163,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"demo.h\"\n#include \"triangle_mesh.h\"\n\n#include \"glfw\/glfw3.h\"\n#include \"imgui\/imgui.h\"\n#include \"imgui\/imgui_internal.h\"\n#include \"imgui\/impl\/imgui_impl_vulkan.h\"\n#include \"imgui\/impl\/imgui_impl_glfw.h\"\n\nnamespace {\nstruct Uniform_Buffer {\n    Matrix4x4 model_view_proj;\n};\n}\n\nstatic VkFormat get_depth_image_format() {\n    VkFormat candidates[2] = { VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D32_SFLOAT_S8_UINT };\n    for (auto format : candidates) {\n        VkFormatProperties props;\n        vkGetPhysicalDeviceFormatProperties(vk.physical_device, format, &props);\n        if ((props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) != 0) {\n            return format;\n        }\n    }\n    error(\"failed to select depth attachment format\");\n    return VK_FORMAT_UNDEFINED;\n}\n\nvoid Vk_Demo::initialize(GLFWwindow* window, bool enable_validation_layers) {\n    vk_initialize(window, enable_validation_layers);\n\n    \/\/ Device properties.\n    {\n        VkPhysicalDeviceProperties2 physical_device_properties { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2 };\n        vkGetPhysicalDeviceProperties2(vk.physical_device, &physical_device_properties);\n        printf(\"Device: %s\\n\", physical_device_properties.properties.deviceName);\n        printf(\"Vulkan API version: %d.%d.%d\\n\",\n            VK_VERSION_MAJOR(physical_device_properties.properties.apiVersion),\n            VK_VERSION_MINOR(physical_device_properties.properties.apiVersion),\n            VK_VERSION_PATCH(physical_device_properties.properties.apiVersion)\n        );\n    }\n\n    \/\/ Geometry buffers.\n    {\n        Triangle_Mesh mesh = load_obj_model((get_data_directory() \/ \"model\/mesh.obj\").string(), 1.25f);\n        {\n            const VkDeviceSize size = mesh.vertices.size() * sizeof(mesh.vertices[0]);\n            VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;\n            gpu_mesh.vertex_buffer = vk_create_buffer(size, usage, mesh.vertices.data(), \"vertex_buffer\");\n            gpu_mesh.vertex_count = uint32_t(mesh.vertices.size());\n        }\n        {\n            const VkDeviceSize size = mesh.indices.size() * sizeof(mesh.indices[0]);\n            VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;\n            gpu_mesh.index_buffer = vk_create_buffer(size, usage, mesh.indices.data(), \"index_buffer\");\n            gpu_mesh.index_count = uint32_t(mesh.indices.size());\n        }\n    }\n\n    \/\/ Texture.\n    {\n        texture = vk_load_texture((get_data_directory() \/ \"model\/diffuse.jpg\").string());\n\n        VkSamplerCreateInfo create_info { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };\n        create_info.magFilter = VK_FILTER_LINEAR;\n        create_info.minFilter = VK_FILTER_LINEAR;\n        create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;\n        create_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;\n        create_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;\n        create_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;\n        create_info.mipLodBias = 0.0f;\n        create_info.anisotropyEnable = VK_FALSE;\n        create_info.maxAnisotropy = 1;\n        create_info.minLod = 0.0f;\n        create_info.maxLod = 12.0f;\n\n        VK_CHECK(vkCreateSampler(vk.device, &create_info, nullptr, &sampler));\n        vk_set_debug_name(sampler, \"diffuse_texture_sampler\");\n    }\n\n    uniform_buffer = vk_create_mapped_buffer(static_cast<VkDeviceSize>(sizeof(Uniform_Buffer)),\n        VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, &mapped_uniform_buffer, \"uniform_buffer\");\n\n    descriptor_set_layout = Descriptor_Set_Layout()\n        .uniform_buffer(0, VK_SHADER_STAGE_VERTEX_BIT)\n        .sampled_image(1, VK_SHADER_STAGE_FRAGMENT_BIT)\n        .sampler(2, VK_SHADER_STAGE_FRAGMENT_BIT)\n        .create(\"set_layout\");\n\n    \/\/ Pipeline layout.\n    {\n        VkPipelineLayoutCreateInfo create_info{ VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };\n        create_info.setLayoutCount = 1;\n        create_info.pSetLayouts = &descriptor_set_layout;\n\n\t\tVK_CHECK(vkCreatePipelineLayout(vk.device, &create_info, nullptr, &pipeline_layout));\n        vk_set_debug_name(pipeline_layout, \"pipeline_layout\");\n    }\n\n\t\/\/ UI render pass.\n\t{\n\t\tVkAttachmentDescription attachments[1] = {};\n\t\tattachments[0].format = vk.surface_format.format;\n\t\tattachments[0].samples = VK_SAMPLE_COUNT_1_BIT;\n\t\tattachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;\n\t\tattachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;\n\t\tattachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;\n\t\tattachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;\n\t\tattachments[0].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n\t\tattachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;  \/\/ VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n\n\t\tVkAttachmentReference color_attachment_ref;\n\t\tcolor_attachment_ref.attachment = 0;\n\t\tcolor_attachment_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n\n\t\tVkSubpassDescription subpass{};\n\t\tsubpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;\n\t\tsubpass.colorAttachmentCount = 1;\n\t\tsubpass.pColorAttachments = &color_attachment_ref;\n\n\t\tVkRenderPassCreateInfo create_info{ VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO };\n\t\tcreate_info.attachmentCount = (uint32_t)std::size(attachments);\n\t\tcreate_info.pAttachments = attachments;\n\t\tcreate_info.subpassCount = 1;\n\t\tcreate_info.pSubpasses = &subpass;\n\n\t\tVK_CHECK(vkCreateRenderPass(vk.device, &create_info, nullptr, &ui_render_pass));\n\t\tvk_set_debug_name(ui_render_pass, \"ui_render_pass\");\n\t}\n\n    \/\/ Pipeline.\n    {\n\t\tShader_Module vertex_shader(\"spirv\/mesh.vert.spv\");\n\t\tShader_Module fragment_shader(\"spirv\/mesh.frag.spv\");\n\n        Vk_Graphics_Pipeline_State state = get_default_graphics_pipeline_state();\n\n        \/\/ VkVertexInputBindingDescription\n        state.vertex_bindings[0].binding = 0;\n        state.vertex_bindings[0].stride = sizeof(Vertex);\n        state.vertex_bindings[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;\n        state.vertex_binding_count = 1;\n\n        \/\/ VkVertexInputAttributeDescription\n        state.vertex_attributes[0].location = 0; \/\/ position\n        state.vertex_attributes[0].binding = 0;\n        state.vertex_attributes[0].format = VK_FORMAT_R32G32B32_SFLOAT;\n        state.vertex_attributes[0].offset = 0;\n\n        state.vertex_attributes[1].location = 1; \/\/ uv\n        state.vertex_attributes[1].binding = 0;\n        state.vertex_attributes[1].format = VK_FORMAT_R32G32_SFLOAT;\n        state.vertex_attributes[1].offset = 12;\n\n        state.vertex_attribute_count = 2;\n\n        state.depth_attachment_format = get_depth_image_format();\n\n        pipeline = vk_create_graphics_pipeline(state, pipeline_layout, vertex_shader.handle, fragment_shader.handle);\n    }\n\n    \/\/ Descriptor sets.\n    {\n        VkDescriptorSetAllocateInfo desc { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };\n        desc.descriptorPool = vk.descriptor_pool;\n        desc.descriptorSetCount = 1;\n        desc.pSetLayouts = &descriptor_set_layout;\n        VK_CHECK(vkAllocateDescriptorSets(vk.device, &desc, &descriptor_set));\n\n        Descriptor_Writes(descriptor_set)\n            .uniform_buffer(0, uniform_buffer.handle, 0, sizeof(Uniform_Buffer))\n            .sampled_image(1, texture.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)\n            .sampler(2, sampler);\n    }\n\n    \/\/ ImGui setup.\n    {\n        ImGui::CreateContext();\n        ImGui_ImplGlfw_InitForVulkan(window, true);\n\n        ImGui_ImplVulkan_InitInfo init_info{};\n        init_info.Instance = vk.instance;\n        init_info.PhysicalDevice = vk.physical_device;\n        init_info.Device = vk.device;\n        init_info.QueueFamily = vk.queue_family_index;\n        init_info.Queue = vk.queue;\n        init_info.DescriptorPool = vk.descriptor_pool;\n\t\tinit_info.MinImageCount = 2;\n\t\tinit_info.ImageCount = (uint32_t)vk.swapchain_info.images.size();\n        ImGui_ImplVulkan_Init(&init_info, ui_render_pass);\n        ImGui::StyleColorsDark();\n\n        vk_execute(vk.command_pools[0], vk.queue, [](VkCommandBuffer cb) {\n            ImGui_ImplVulkan_CreateFontsTexture(cb);\n        });\n\t\tImGui_ImplVulkan_DestroyFontUploadObjects();\n    }\n\n    restore_resolution_dependent_resources();\n\n    gpu_times.frame = time_keeper.allocate_time_interval();\n    gpu_times.draw = time_keeper.allocate_time_interval();\n    gpu_times.ui = time_keeper.allocate_time_interval();\n    time_keeper.initialize_time_intervals();\n}\n\nvoid Vk_Demo::shutdown() {\n    VK_CHECK(vkDeviceWaitIdle(vk.device));\n\n    ImGui_ImplVulkan_Shutdown();\n    ImGui_ImplGlfw_Shutdown();\n    ImGui::DestroyContext();\n\n    gpu_mesh.destroy();\n    texture.destroy();\n    vkDestroySampler(vk.device, sampler, nullptr);\n    vkDestroyRenderPass(vk.device, ui_render_pass, nullptr);\n    release_resolution_dependent_resources();\n    uniform_buffer.destroy();\n    vkDestroyDescriptorSetLayout(vk.device, descriptor_set_layout, nullptr);\n    vkDestroyPipelineLayout(vk.device, pipeline_layout, nullptr);\n    vkDestroyPipeline(vk.device, pipeline, nullptr);\n\n    vk_shutdown();\n}\n\nvoid Vk_Demo::release_resolution_dependent_resources() {\n\tfor (VkFramebuffer framebuffer : ui_framebuffers) {\n\t\tvkDestroyFramebuffer(vk.device, framebuffer, nullptr);\n\t}\n\tui_framebuffers.clear();\n    depth_buffer_image.destroy();\n}\n\nvoid Vk_Demo::restore_resolution_dependent_resources() {\n    \/\/ create depth buffer\n    {\n        VkFormat depth_format = get_depth_image_format();\n        depth_buffer_image = vk_create_image(vk.surface_size.width, vk.surface_size.height, depth_format,\n            VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, \"depth_buffer\");\n\n        vk_execute(vk.command_pools[0], vk.queue, [this](VkCommandBuffer command_buffer) {\n            VkImageSubresourceRange subresource_range{};\n            subresource_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;\n            subresource_range.levelCount = 1;\n            subresource_range.layerCount = 1;\n\n            vk_cmd_image_barrier_for_subresource(command_buffer, depth_buffer_image.handle, subresource_range,\n                VK_PIPELINE_STAGE_NONE, 0, VK_IMAGE_LAYOUT_UNDEFINED,\n                VK_PIPELINE_STAGE_NONE, 0, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);\n            });\n    }\n\n    \/\/ imgui framebuffers\n\t{\n\t\tVkImageView attachments[] = {\n\t\t\tVK_NULL_HANDLE, \/\/ color attachment, set in the loop below\n\t\t};\n\t\tVkFramebufferCreateInfo create_info{ VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO };\n\t\tcreate_info.renderPass = ui_render_pass;\n\t\tcreate_info.attachmentCount = (uint32_t)std::size(attachments);\n\t\tcreate_info.pAttachments = attachments;\n\t\tcreate_info.width = vk.surface_size.width;\n\t\tcreate_info.height = vk.surface_size.height;\n\t\tcreate_info.layers = 1;\n\n\t\tui_framebuffers.resize(vk.swapchain_info.images.size());\n\t\tfor (size_t i = 0; i < vk.swapchain_info.images.size(); i++) {\n\t\t\tattachments[0] = vk.swapchain_info.image_views[i];\n\t\t\tVK_CHECK(vkCreateFramebuffer(vk.device, &create_info, nullptr, &ui_framebuffers[i]));\n\t\t\tvk_set_debug_name(ui_framebuffers[i], \"ui_framebuffer\");\n\t\t}\n\t}\n\n    last_frame_time = Clock::now();\n}\n\nvoid Vk_Demo::run_frame() {\n    Time current_time = Clock::now();\n    if (animate) {\n        double time_delta = std::chrono::duration_cast<std::chrono::microseconds>(current_time - last_frame_time).count() \/ 1e6;\n        sim_time += time_delta;\n    }\n    last_frame_time = current_time;\n\n\tfloat aspect_ratio = (float)vk.surface_size.width \/ (float)vk.surface_size.height;\n\tMatrix4x4 projection_transform = perspective_transform_opengl_z01(radians(45.0f), aspect_ratio, 0.1f, 50.0f);\n\tMatrix3x4 view_transform = look_at_transform(camera_pos, Vector3(0), Vector3(0, 1, 0));\n    Matrix3x4 model_transform = rotate_y(Matrix3x4::identity, (float)sim_time * radians(20.0f));\n    Matrix4x4 model_view_proj = projection_transform * view_transform * model_transform;\n    memcpy(mapped_uniform_buffer, &model_view_proj, sizeof(model_view_proj));\n\n    do_imgui();\n    draw_frame();\n}\n\nvoid Vk_Demo::draw_frame() {\n    vk_begin_frame();\n    begin_gpu_marker_scope(vk.command_buffer, \"draw_frame\");\n    time_keeper.next_frame();\n    gpu_times.frame->begin();\n\n    draw_rasterized_image();\n    draw_imgui();\n\n    gpu_times.frame->end();\n    end_gpu_marker_scope(vk.command_buffer);\n    vk_end_frame();\n}\n\nvoid Vk_Demo::draw_rasterized_image() {\n    GPU_MARKER_SCOPE(vk.command_buffer, \"draw_rasterized_image\");\n    GPU_TIME_SCOPE(gpu_times.draw);\n\n    vk_cmd_image_barrier(vk.command_buffer, vk.swapchain_info.images[vk.swapchain_image_index],\n        VK_PIPELINE_STAGE_NONE, 0, VK_IMAGE_LAYOUT_UNDEFINED,\n        VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);\n\n    VkViewport viewport{};\n    viewport.width = static_cast<float>(vk.surface_size.width);\n    viewport.height = static_cast<float>(vk.surface_size.height);\n    viewport.minDepth = 0.0f;\n    viewport.maxDepth = 1.0f;\n\n    VkRect2D scissor{};\n    scissor.extent = vk.surface_size;\n\n    vkCmdSetViewport(vk.command_buffer, 0, 1, &viewport);\n    vkCmdSetScissor(vk.command_buffer, 0, 1, &scissor);\n\n\tVkRenderingAttachmentInfo color_attachment{ VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO };\n\tcolor_attachment.imageView = vk.swapchain_info.image_views[vk.swapchain_image_index];\n\tcolor_attachment.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n\tcolor_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;\n\tcolor_attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;\n\tcolor_attachment.clearValue.color = { 0.32f, 0.32f, 0.4f, 0.0f };\n\n\tVkRenderingAttachmentInfo depth_attachment{ VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO };\n\tdepth_attachment.imageView = depth_buffer_image.view;\n\tdepth_attachment.imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;\n\tdepth_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;\n\tdepth_attachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;\n\tdepth_attachment.clearValue.depthStencil = { 1.f, 0 };\n\n\tVkRenderingInfo rendering_info{ VK_STRUCTURE_TYPE_RENDERING_INFO };\n\trendering_info.renderArea.extent = vk.surface_size;\n\trendering_info.layerCount = 1;\n\trendering_info.colorAttachmentCount = 1;\n\trendering_info.pColorAttachments = &color_attachment;\n\trendering_info.pDepthAttachment = &depth_attachment;\n\n\tvkCmdBeginRendering(vk.command_buffer, &rendering_info);\n    const VkDeviceSize zero_offset = 0;\n    vkCmdBindVertexBuffers(vk.command_buffer, 0, 1, &gpu_mesh.vertex_buffer.handle, &zero_offset);\n    vkCmdBindIndexBuffer(vk.command_buffer, gpu_mesh.index_buffer.handle, 0, VK_INDEX_TYPE_UINT32);\n    vkCmdBindDescriptorSets(vk.command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &descriptor_set, 0, nullptr);\n    vkCmdBindPipeline(vk.command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);\n    vkCmdDrawIndexed(vk.command_buffer, gpu_mesh.index_count, 1, 0, 0, 0);\n\tvkCmdEndRendering(vk.command_buffer);\n}\n\nvoid Vk_Demo::draw_imgui() {\n    GPU_MARKER_SCOPE(vk.command_buffer, \"draw_imgui\");\n    GPU_TIME_SCOPE(gpu_times.ui);\n\n    ImGui::Render();\n\n    VkRenderPassBeginInfo render_pass_begin_info{ VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };\n    render_pass_begin_info.renderPass = ui_render_pass;\n    render_pass_begin_info.framebuffer = ui_framebuffers[vk.swapchain_image_index];\n    render_pass_begin_info.renderArea.extent = vk.surface_size;\n\n    vkCmdBeginRenderPass(vk.command_buffer, &render_pass_begin_info, VK_SUBPASS_CONTENTS_INLINE);\n    ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), vk.command_buffer);\n    vkCmdEndRenderPass(vk.command_buffer);\n}\n\nvoid Vk_Demo::do_imgui() {\n    ImGuiIO& io = ImGui::GetIO();\n\n    ImGui_ImplVulkan_NewFrame();\n    ImGui_ImplGlfw_NewFrame();\n    ImGui::NewFrame();\n\n    if (!io.WantCaptureKeyboard) {\n        if (ImGui::IsKeyPressed(GLFW_KEY_F10)) {\n            show_ui = !show_ui;\n        }\n        if (ImGui::IsKeyPressed(GLFW_KEY_W) || ImGui::IsKeyPressed(GLFW_KEY_UP)) {\n            camera_pos.z -= 0.2f;\n        }\n        if (ImGui::IsKeyPressed(GLFW_KEY_S) || ImGui::IsKeyPressed(GLFW_KEY_DOWN)) {\n            camera_pos.z += 0.2f;\n        }\n    }\n\n    if (show_ui) {\n        const float DISTANCE = 10.0f;\n        static int corner = 0;\n\n        ImVec2 window_pos = ImVec2((corner & 1) ? ImGui::GetIO().DisplaySize.x - DISTANCE : DISTANCE,\n                                   (corner & 2) ? ImGui::GetIO().DisplaySize.y - DISTANCE : DISTANCE);\n\n        ImVec2 window_pos_pivot = ImVec2((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f);\n\n        if (corner != -1)\n            ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot);\n        ImGui::SetNextWindowBgAlpha(0.3f);\n\n        if (ImGui::Begin(\"UI\", &show_ui, \n            (corner != -1 ? ImGuiWindowFlags_NoMove : 0) | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |\n            ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings |\n            ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav))\n        {\n            ImGui::Text(\"%.1f FPS (%.3f ms\/frame)\", ImGui::GetIO().Framerate, 1000.0f \/ ImGui::GetIO().Framerate);\n            ImGui::Text(\"Frame time         : %.2f ms\", gpu_times.frame->length_ms);\n            ImGui::Text(\"Draw time          : %.2f ms\", gpu_times.draw->length_ms);\n            ImGui::Text(\"UI time            : %.2f ms\", gpu_times.ui->length_ms);\n            ImGui::Separator();\n            ImGui::Spacing();\n            ImGui::Checkbox(\"Vertical sync\", &vsync);\n            ImGui::Checkbox(\"Animate\", &animate);\n\n            if (ImGui::BeginPopupContextWindow()) {\n                if (ImGui::MenuItem(\"Custom\",       NULL, corner == -1)) corner = -1;\n                if (ImGui::MenuItem(\"Top-left\",     NULL, corner == 0)) corner = 0;\n                if (ImGui::MenuItem(\"Top-right\",    NULL, corner == 1)) corner = 1;\n                if (ImGui::MenuItem(\"Bottom-left\",  NULL, corner == 2)) corner = 2;\n                if (ImGui::MenuItem(\"Bottom-right\", NULL, corner == 3)) corner = 3;\n                if (ImGui::MenuItem(\"Close\")) show_ui = false;\n                ImGui::EndPopup();\n            }\n        }\n        ImGui::End();\n    }\n}\n","avg_line_length":41.4680365297,"max_line_length":135,"alphanum_fraction":0.7192644387,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4945,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":64.0,"content":"\/*=========================================================================\n\n  Program:   WXDialog - wxWidgets X-platform GUI Front-End for CMake\n  Module:    $RCSfile: CommandLineInfo.cpp,v $\n  Language:  C++\n  Date:      $Date: 2012\/03\/29 17:21:10 $\n  Version:   $Revision: 1.1.1.1 $\n\n  Author:    Jorgen Bodde\n\n  Copyright (c) 2002 Kitware, Inc., Insight Consortium.  All rights reserved.\n  See Copyright.txt or http:\/\/www.cmake.org\/HTML\/Copyright.html for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even \n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n     PURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include \"wx\/wx.h\"\n#endif\n\n#include \"CommandLineInfo.h\" \n\n#include \"cmSystemTools.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ cmCommandLineInfo \n\ncmCommandLineInfo::cmCommandLineInfo()\n{\n    m_WhereSource = _(\"\");\n    m_WhereBuild = _(\"\");\n    m_AdvancedValues = false;\n    m_GeneratorChoiceString.Empty();\n    m_LastUnknownParameter = \"\";\n    m_ValidArguments = \"\";\n    m_ExitAfterLoad = false;\n} \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ncmCommandLineInfo::~cmCommandLineInfo()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool cmCommandLineInfo::ParseCommandLine(int argc, char* argv[])\n{\n    bool result = true;\n    wxString cachePath;\n    \n    \/\/ parse all commands\n    int cc = 1;\n    if(argc < cc)\n        return true;    \/\/ no command line options\n\n    while(cc < argc)\n    {\n        wxString arg = argv[cc];\n\n        \/\/ if we have a switch\n        if(arg.Len() > 1 && arg.GetChar(0) == '-')\n        {\n            int next_argc = ParseSwitch(argv, cc, argc);\n            if(next_argc > 0)\n                cc += next_argc;\n            else\n                return false; \/\/ sorry error while parsing\n        }\n        else\n        {\n            \/\/ gather all what is left\n            for(int leftcc = cc; leftcc < argc; leftcc++)\n            {\n                if(cc != leftcc)\n                    m_WhereBuild << _(\" \");\n                m_WhereBuild << argv[leftcc];\n            }\n            break;\n        }\n    }\n\n    m_ExecutablePath = cmSystemTools::GetFilenamePath(argv[0]).c_str();\n\n    return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint cmCommandLineInfo::GetBoolValue(const wxString& v) {\n\n    wxString value = v.Lower();\n  \n    if (!value.Cmp(\"1\") || \n        !value.Cmp(\"on\") || \n        !value.Cmp(\"true\") || \n        !value.Cmp(\"yes\"))\n    {\n        \/\/ true\n        return 1;\n    }\n    else if (!value.Cmp(\"0\") || \n             !value.Cmp(\"off\") || \n             !value.Cmp(\"false\") || \n             !value.Cmp(\"no\"))\n    {\n        \/\/ false\n        return -1;\n    }\n\n    \/\/ not recognised\n    return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Parse param\n\nsize_t cmCommandLineInfo::ParseSwitch(char **argv, int arg_index, int argc)\n{        \n    wxString param = argv[arg_index];\n    \n    \/\/ we need this for a switch, at least 2\n    if(param.Len() > 1)\n    {\n        \/\/ determine switch type\n        switch (param.GetChar(1))\n        {\n        case 'G':\n            \/\/ when it's G<.....> we split else we take the \n            \/\/ other argc\n            if(param.Len() > 2)\n            {\n                m_GeneratorChoiceString = GetStringParam(param.Mid(2));\n                return 1;   \/\/ one arg is passed\n            }\n            else\n            {\n                if((arg_index+1) < argc)\n                {\n                    m_GeneratorChoiceString = GetStringParam(wxString(argv[arg_index+1]));\n                    return 2;   \/\/ two args are passed\n                }\n            }\n            \/\/ no luck\n            return 0;\n    \n        case 'Q':\n            m_ExitAfterLoad = true;\n            return 1;\n\n        \/\/ unknown param\n        default:\n            break;\n        }\n    }\n\n    \/\/ error, unrecognised or too small arg\n    return 0;\n}\n\n\/\/ When the string param given has string quotes around it\n\/\/ we remove them and we pass back the string. If not, we \n\/\/ simply pass back the string as-is\nwxString cmCommandLineInfo::GetStringParam(const wxString &str)\n{\n    wxString mystr = str.Strip(wxString::both);\n\n    \/\/ if we have only one (or no chars return the current string)\n    if(mystr.Len() < 2)\n        return str;\n\n    \/\/ if we have quotes\n    if(mystr.GetChar(0) == '\\\"' && mystr.Last() == '\\\"')\n    {\n        \/\/ when we only have 2 in size, return empty string\n        if(mystr.Len() == 2)\n            return wxEmptyString;\n\n        \/\/ now remove the outer and inner, and return\n        return mystr.Mid(1, mystr.Len()-1);\n    }\n\n    return str;\n}\n","avg_line_length":25.7552083333,"max_line_length":90,"alphanum_fraction":0.4930232558,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5257,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"#ifdef USE_UPNP\n#include <string>\n#include <thread>\n\n#include <boost\/thread\/thread.hpp>\n#include <boost\/asio.hpp>\n#include <boost\/bind.hpp>\n\n#include \"Log.h\"\n\n#include \"RouterContext.h\"\n#include \"UPnP.h\"\n#include \"NetDb.hpp\"\n#include \"util.h\"\n#include \"RouterInfo.h\"\n#include \"Config.h\"\n\n#include <miniupnpc\/miniupnpc.h>\n#include <miniupnpc\/upnpcommands.h>\n\nnamespace i2p\n{\nnamespace transport\n{\n\tUPnP::UPnP () : m_IsRunning(false), m_Thread (nullptr), m_Timer (m_Service)\n\t{\n\t}\n\n\tvoid UPnP::Stop ()\n\t{\n\t\tif (m_IsRunning)\n\t\t{\n\t\t\tLogPrint(eLogInfo, \"UPnP: stopping\");\n\t\t\tm_IsRunning = false;\n\t\t\tm_Timer.cancel ();\n\t\t\tm_Service.stop ();\n\t\t\tif (m_Thread)\n\t\t\t{\n\t\t\t\tm_Thread->join ();\n\t\t\t\tm_Thread.reset (nullptr);\n\t\t\t}\n\t\t\tCloseMapping ();\n\t\t\tClose ();\n\t\t}\n\t}\n\n\tvoid UPnP::Start()\n\t{\n\t\tm_IsRunning = true;\n\t\tLogPrint(eLogInfo, \"UPnP: starting\");\n\t\tm_Service.post (std::bind (&UPnP::Discover, this));\n\t\tstd::unique_lock<std::mutex> l(m_StartedMutex);\n\t\tm_Thread.reset (new std::thread (std::bind (&UPnP::Run, this)));\n\t\tm_Started.wait_for (l, std::chrono::seconds (5)); \/\/ 5 seconds maximum\n\t}\n\n\tUPnP::~UPnP ()\n\t{\n\t\tStop ();\n\t}\n\n\tvoid UPnP::Run ()\n\t{\n\t\twhile (m_IsRunning)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tm_Service.run ();\n\t\t\t\t\/\/ Discover failed\n\t\t\t\tbreak; \/\/ terminate the thread\n\t\t\t}\n\t\t\tcatch (std::exception& ex)\n\t\t\t{\n\t\t\t\tLogPrint (eLogError, \"UPnP: runtime exception: \", ex.what ());\n\t\t\t\tPortMapping ();\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid UPnP::Discover ()\n\t{\n#if MINIUPNPC_API_VERSION >= 14\n\t\tint nerror = 0;\n\t\tm_Devlist = upnpDiscover (2000, m_MulticastIf, m_Minissdpdpath, 0, 0, 2, &nerror);\n#elif ( MINIUPNPC_API_VERSION >= 8 || defined(UPNPDISCOVER_SUCCESS) )\n\t\tint nerror = 0;\n\t\tm_Devlist = upnpDiscover (2000, m_MulticastIf, m_Minissdpdpath, 0, 0, &nerror);\n#else\n\t\tm_Devlist = upnpDiscover (2000, m_MulticastIf, m_Minissdpdpath, 0);\n#endif\n\t\t{\n\t\t\t\/\/ notify satrting thread\n\t\t\tstd::unique_lock<std::mutex> l(m_StartedMutex);\n\t\t\tm_Started.notify_all ();\n\t\t}\n\n\t\tint r;\n\t\tr = UPNP_GetValidIGD (m_Devlist, &m_upnpUrls, &m_upnpData, m_NetworkAddr, sizeof (m_NetworkAddr));\n\t\tif (r == 1)\n\t\t{\n\t\t\tr = UPNP_GetExternalIPAddress (m_upnpUrls.controlURL, m_upnpData.first.servicetype, m_externalIPAddress);\n\t\t\tif(r != UPNPCOMMAND_SUCCESS)\n\t\t\t{\n\t\t\t\tLogPrint (eLogError, \"UPnP: UPNP_GetExternalIPAddress() returned \", r);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (!m_externalIPAddress[0])\n\t\t\t\t{\n\t\t\t\t\tLogPrint (eLogError, \"UPnP: GetExternalIPAddress() failed.\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLogPrint (eLogError, \"UPnP: GetValidIGD() failed.\");\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ UPnP discovered\n\t\tLogPrint (eLogDebug, \"UPnP: ExternalIPAddress is \", m_externalIPAddress);\n\t\ti2p::context.UpdateAddress (boost::asio::ip::address::from_string (m_externalIPAddress));\n\t\t\/\/ port mapping\n\t\tPortMapping ();\n\t}\n\n\tvoid UPnP::PortMapping ()\n\t{\n\t\tconst auto& a = context.GetRouterInfo().GetAddresses();\n\t\tfor (const auto& address : a)\n\t\t{\n\t\t\tif (!address->host.is_v6 () && address->port)\n\t\t\t\tTryPortMapping (address);\n\t\t}\n\t\tm_Timer.expires_from_now (boost::posix_time::minutes(20));\t\/\/ every 20 minutes\n\t\tm_Timer.async_wait ([this](const boost::system::error_code& ecode)\n\t\t{\n\t\t\tif (ecode != boost::asio::error::operation_aborted)\n\t\t\tPortMapping ();\n\t\t});\n\n\t}\n\n\tvoid UPnP::CloseMapping ()\n\t{\n\t\tconst auto& a = context.GetRouterInfo().GetAddresses();\n\t\tfor (const auto& address : a)\n\t\t{\n\t\t\tif (!address->host.is_v6 () && address->port)\n\t\t\tCloseMapping (address);\n\t\t}\n\t}\n\n\tvoid UPnP::TryPortMapping (std::shared_ptr<i2p::data::RouterInfo::Address> address)\n\t{\n\t\tstd::string strType (GetProto (address)), strPort (std::to_string (address->port));\n\t\tint r;\n\t\tstd::string strDesc; i2p::config::GetOption(\"upnp.name\", strDesc);\n#ifdef UPNPDISCOVER_SUCCESS\n\t\tr = UPNP_AddPortMapping (m_upnpUrls.controlURL, m_upnpData.first.servicetype, strPort.c_str (), strPort.c_str (), m_NetworkAddr, strDesc.c_str (), strType.c_str (), 0, \"0\");\n#else\n\t\tr = UPNP_AddPortMapping (m_upnpUrls.controlURL, m_upnpData.first.servicetype, strPort.c_str (), strPort.c_str (), m_NetworkAddr, strDesc.c_str (), strType.c_str (), 0);\n#endif\n\t\tif (r!=UPNPCOMMAND_SUCCESS)\n\t\t{\n\t\t\tLogPrint (eLogError, \"UPnP: AddPortMapping (\", m_NetworkAddr, \":\", strPort, \") failed with code \", r);\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLogPrint (eLogDebug, \"UPnP: Port Mapping successful. (\", m_NetworkAddr ,\":\", strPort, \" type \", strType, \" -> \", m_externalIPAddress ,\":\", strPort ,\")\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tvoid UPnP::CloseMapping (std::shared_ptr<i2p::data::RouterInfo::Address> address)\n\t{\n\t\tstd::string strType (GetProto (address)), strPort (std::to_string (address->port));\n\t\tint r = 0;\n\t\tr = UPNP_DeletePortMapping (m_upnpUrls.controlURL, m_upnpData.first.servicetype, strPort.c_str (), strType.c_str (), 0);\n\t\tLogPrint (eLogError, \"UPnP: DeletePortMapping() returned : \", r);\n\t}\n\n\tvoid UPnP::Close ()\n\t{\n\t\tfreeUPNPDevlist (m_Devlist);\n\t\tm_Devlist = 0;\n\t\tFreeUPNPUrls (&m_upnpUrls);\n\t}\n\n\tstd::string UPnP::GetProto (std::shared_ptr<i2p::data::RouterInfo::Address> address)\n\t{\n\t\tswitch (address->transportStyle)\n\t\t{\n\t\t\tcase i2p::data::RouterInfo::eTransportNTCP:\n\t\t\treturn \"TCP\";\n\t\t\tbreak;\n\t\t\tcase i2p::data::RouterInfo::eTransportSSU:\n\t\t\tdefault:\n\t\t\treturn \"UDP\";\n\t\t}\n\t}\n}\n}\n#else \/* USE_UPNP *\/\nnamespace i2p {\nnamespace transport {\n}\n}\n#endif \/* USE_UPNP *\/\n","avg_line_length":24.6807511737,"max_line_length":175,"alphanum_fraction":0.6663496291,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2885,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*===================================================================\n\n The Medical Imaging Interaction Toolkit (MITK)\n\n Copyright (c) German Cancer Research Center,\n Division of Medical and Biological Informatics.\n All rights reserved.\n\n This software is distributed WITHOUT ANY WARRANTY; without\n even the implied warranty of MERCHANTABILITY or FITNESS FOR\n A PARTICULAR PURPOSE.\n\n See LICENSE.txt or http:\/\/www.mitk.org for details.\n\n ===================================================================*\/\n\n#include \"mitkInteractionEventConst.h\"\n\nnamespace mitk {\n\nconst std::string InteractionEventConst::xmlTagConfigRoot()\n{\n  static const std::string xmlTagConfigRoot = \"config\";\n  return xmlTagConfigRoot;\n}\n\nconst std::string InteractionEventConst::xmlTagParam()\n{\n  static const std::string xmlTagParam = \"param\";\n  return xmlTagParam;\n\n}\n\nconst std::string InteractionEventConst::xmlTagEventVariant()\n{\n  static const std::string xmlTagEventVariant = \"event_variant\";\n  return xmlTagEventVariant;\n}\n\nconst std::string InteractionEventConst::xmlTagAttribute()\n{\n  static const std::string xmlTagAttribute = \"attribute\";\n  return xmlTagAttribute;\n}\n\nconst std::string InteractionEventConst::xmlParameterName()\n{\n  static const std::string xmlParameterName = \"name\";\n  return xmlParameterName;\n}\n\nconst std::string InteractionEventConst::xmlParameterValue()\n{\n  static const std::string xmlParameterValue = \"value\";\n  return xmlParameterValue;\n}\n\nconst std::string InteractionEventConst::xmlParameterEventVariant()\n{\n  static const std::string xmlParameterEventVariant = \"event_variant\";\n  return xmlParameterEventVariant;\n}\n\nconst std::string InteractionEventConst::xmlParameterEventClass()\n{\n  static const std::string xmlParameterEventClass = \"class\";\n  return xmlParameterEventClass;\n}\n\nconst std::string InteractionEventConst::xmlEventPropertyModifier()\n{\n  static const std::string xmlEventPropertyModifier = \"Modifiers\";\n  return xmlEventPropertyModifier;\n}\n\nconst std::string InteractionEventConst::xmlEventPropertyEventButton()\n{\n  static const std::string xmlEventPropertyEventButton = \"EventButton\";\n  return xmlEventPropertyEventButton;\n}\n\nconst std::string InteractionEventConst::xmlEventPropertyButtonState()\n{\n  static const std::string xmlEventPropertyButtonState = \"ButtonState\";\n  return xmlEventPropertyButtonState;\n}\n\nconst std::string InteractionEventConst::xmlEventPropertyKey()\n{\n  static const std::string xmlEventPropertyKey = \"Key\";\n  return xmlEventPropertyKey;\n}\n\nconst std::string InteractionEventConst::xmlEventPropertyScrollDirection()\n{\n  static const std::string xmlEventPropertyScrollDirection = \"ScrollDirection\";\n  return xmlEventPropertyScrollDirection;\n}\n\nconst std::string InteractionEventConst::xmlEventPropertySignalName()\n{\n  static const std::string xmlEventPropertySignalName = \"SignalName\";\n  return xmlEventPropertySignalName;\n}\n\n\n}\n","avg_line_length":26.712962963,"max_line_length":79,"alphanum_fraction":0.7587521664,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1389,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <bits\/stdc++.h>\nusing namespace std;\n#define rep(i,a,n) for (int i=a;i<n;i++)\n#define per(i,a,n) for (int i=n-1;i>=a;i--)\n#define pb push_back\n#define eb emplace_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n#define SZ(x) ((int)(x).size())\ntypedef vector<int> VI;\ntypedef basic_string<int> BI;\ntypedef long long ll;\ntypedef pair<int, int> PII;\ntypedef double db;\nmt19937 mrand(random_device{}());\nconst ll mod = 1000000007;\nint rnd(int x) { return mrand() % x;}\nll powmod(ll a, ll b) {ll res = 1; a %= mod; assert(b >= 0); for (; b; b >>= 1) {if (b & 1)res = res * a % mod; a = a * a % mod;} return res;}\nll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a;}\n\/\/ head\n\n\/\/https:\/\/atcoder.jp\/contests\/abc251\/submissions\/31663993\n\/\/\u73af\u4e0aDP\n\/\/\u5f53\u524d\u4f4d\u7f6e\u4e0d\u9009\uff0c\u4e0a\u4e2a\u4f4d\u7f6e\u4e00\u5b9a\u8981\u9009\n\/\/\u5f53\u524d\u4f4d\u7f6e\u9009\u4e86\uff0c\u4e0a\u4e00\u4e2a\u65e0\u6240\u8c13\n\nconst int N = 301000;\nint n, a[N];\nll dp[N][2], ans = 1ll << 60;\nint main() {\n    scanf(\"%d\", &n);\n    rep(i, 0, n) scanf(\"%d\", a + i);\n    rep(bt, 0, 2) { \/\/\u679a\u4e3e\u7b2c\u4e00\u4e2a\u662f\u5426\u9009 \u4e0b\u6807\u4ece0\u5f00\u59cb\n        if (bt == 0) dp[0][0] = 0, dp[0][1] = a[0];\n        else dp[0][1] = a[0], dp[0][0] = 1ll << 60; \/\/\u4e3a\u4ec0\u4e48\u8981\u8fd9\u6837\u521d\u59cb\u5316?\n        rep(i, 1, n) {\n            dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]) + a[i];\n            dp[i][0] = dp[i - 1][1];\n        }\n        if (bt == 0) ans = dp[n - 1][1];\n        else ans = min(ans, min(dp[n - 1][0], dp[n - 1][1]));\n    }\n    printf(\"%lld\\n\", ans);\n}\n","avg_line_length":29.5531914894,"max_line_length":142,"alphanum_fraction":0.5370770338,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":492,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <mbed.h>\n\n\/\/Define Peripherals here.\nSerial pc((PinName)PA_2, (PinName)PA_15, 115200);\n\n\/\/Low power timer enables stop mode.\nLowPowerTimer timer;\n\n\/\/App Start\n\nint main()\n{\n\ttimer.start();\n\twhile(true)\n\t{\n\t\tpc.printf(\"Time Elapsed: %10f[sec]\\n\", timer.read());\n\t\tThisThread::sleep_for(1000);\n\t}\n}\n\n\/\/Comment this out if you dont want the blinking led on crash\nvoid mbed_die(void)\n{\n\t\/\/\n\tcore_util_critical_section_enter();\n\twhile(1)\n\t{\n\t\twait_us(30000000);\n\t\tNVIC_SystemReset();\n\t}\n}","avg_line_length":15.8709677419,"max_line_length":61,"alphanum_fraction":0.6930894309,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1134,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n * Copyright (C) QM Ltd.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include <test\/catch.hpp>\n","avg_line_length":47.25,"max_line_length":81,"alphanum_fraction":0.758377425,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":512,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC0-1.0"],"max_stars_count":1.0,"content":"\/*Given an array of non-negative integers, A, you are initially positioned at the first index of the array.\n\nEach element in the array represents your maximum jump length at that position.\n\nDetermine if you are able to reach the last index.*\/\n\nint Solution::canJump(vector<int> &A) {\n    int maxindex=0;\n    if(A.size()==1) return 1;\n    for(int i=0;i<A.size();i++)\n    {\n        maxindex=max(maxindex,i+A[i]);\n        if(i>=maxindex) return 0;\n        if(maxindex >= A.size()-1) return 1;\n    }\n    return 0;\n}\n","avg_line_length":28.4444444444,"max_line_length":107,"alphanum_fraction":0.64453125,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8232,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"assert.h\"\n\n#include \"chainparams.h\"\n#include \"main.h\"\n#include \"util.h\"\n\n#include <boost\/assign\/list_of.hpp>\n\nusing namespace boost::assign;\n\nstruct SeedSpec6 {\n    uint8_t addr[16];\n    uint16_t port;\n};\n\n#include \"chainparamsseeds.h\"\n\n\/\/\n\/\/ Main network\n\/\/\n\n\/\/ Convert the pnSeeds6 array into usable address objects.\nstatic void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)\n{\n    \/\/ It'll only connect to one or two seed nodes because once it connects,\n    \/\/ it'll get a pile of addresses with newer timestamps.\n    \/\/ Seed nodes are given a random 'last seen time' of between one and two\n    \/\/ weeks ago.\n    const int64_t nOneWeek = 7*24*60*60;\n    for (unsigned int i = 0; i < count; i++)\n    {\n        struct in6_addr ip;\n        memcpy(&ip, data[i].addr, sizeof(ip));\n        CAddress addr(CService(ip, data[i].port));\n        addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;\n        vSeedsOut.push_back(addr);\n    }\n}\n\nclass CMainParams : public CChainParams {\npublic:\n    CMainParams() {\n        \/\/ The message start string is designed to be unlikely to occur in normal data.\n        \/\/ The characters are rarely used upper ASCII, not valid as UTF-8, and produce\n        \/\/ a large 4-byte int at any alignment.\n        pchMessageStart[0] = 0x27;\n        pchMessageStart[1] = 0x01;\n        pchMessageStart[2] = 0x22;\n        pchMessageStart[3] = 0x05;\n        vAlertPubKey = ParseHex(\"1234bce1bac0d543f104cbff2bd23680056a3b9ea05e1137d2ff90eeb5e08472eb500322593a2cb06fbf8297d7beb6cd30cb90f98153b5b7cce1493749e41e0284\");\n        nDefaultPort = 9333;\n        nRPCPort = 9332;\n        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);\n\n        \/\/ Build the genesis block. Note that the output of the genesis coinbase cannot\n        \/\/ be spent as it did not originally exist in the database.\n        \/\/\n        \/\/CBlock(hash=000001faef25dec4fbcf906e6242621df2c183bf232f263d0ba5b101911e4563, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1393221600, nBits=1e0fffff, nNonce=164482, vtx=1, vchBlockSig=)\n        \/\/  Coinbase(hash=12630d16a9, nTime=1393221600, ver=1, vin.size=1, vout.size=1, nLockTime=0)\n        \/\/    CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341)\n        \/\/    CTxOut(empty)\n        \/\/  vMerkleTree: 12630d16a9\n        const char* pszTimestamp = \"22 Jan 2017 Bitcoin whiz jumps ship at Wells Fargo for rival IBM\";\n        std::vector<CTxIn> vin;\n        vin.resize(1);\n        vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));\n        std::vector<CTxOut> vout;\n        vout.resize(1);\n        vout[0].SetEmpty();\n        CTransaction txNew(1, 1393221600, vin, vout, 0);\n        genesis.vtx.push_back(txNew);\n        genesis.hashPrevBlock = 0;\n        genesis.hashMerkleRoot = genesis.BuildMerkleTree();\n        genesis.nVersion = 1;\n        genesis.nTime    = 1488450687;\n        genesis.nBits    = bnProofOfWorkLimit.GetCompact();\n        genesis.nNonce   = 37037;\n\n        hashGenesisBlock = genesis.GetHash();\n\n        assert(hashGenesisBlock == uint256(\"0x9209a3ca9aa3b53c37fdec0241da73a25a6c91e8bd206ba66d19dd5f89627aa6\"));\n        assert(genesis.hashMerkleRoot == uint256(\"0x579b91d5372e56c8436a122abee31c440c915370622a3152509455558011d374\"));\n\n        vSeeds.push_back(CDNSSeedData(\"62.84.146.205\", \"62.84.146.205\"));\n\n        base58Prefixes[PUBKEY_ADDRESS] = list_of(25);\n        base58Prefixes[SCRIPT_ADDRESS] = list_of(85);\n        base58Prefixes[SECRET_KEY] =     list_of(153);\n        base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E);\n        base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4);\n\n        convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));\n\n        nLastPOWBlock = 10000;\n    }\n\n    virtual const CBlock& GenesisBlock() const { return genesis; }\n    virtual Network NetworkID() const { return CChainParams::MAIN; }\n\n    virtual const vector<CAddress>& FixedSeeds() const {\n        return vFixedSeeds;\n    }\nprotected:\n    CBlock genesis;\n    vector<CAddress> vFixedSeeds;\n};\nstatic CMainParams mainParams;\n\n\n\/\/\n\/\/ Testnet\n\/\/\n\nclass CTestNetParams : public CMainParams {\npublic:\n    CTestNetParams() {\n        \/\/ The message start string is designed to be unlikely to occur in normal data.\n        \/\/ The characters are rarely used upper ASCII, not valid as UTF-8, and produce\n        \/\/ a large 4-byte int at any alignment.\n        pchMessageStart[0] = 0xcd;\n        pchMessageStart[1] = 0xf2;\n        pchMessageStart[2] = 0xc0;\n        pchMessageStart[3] = 0xef;\n        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);\n        vAlertPubKey = ParseHex(\"0471dc165db490094d35cde15b1f5d755fa6ad6f2b5ed0f340e3f17f57389c3c2af113a8cbcc885bde73305a553b5640c83021128008ddf882e856336269080496\");\n        nDefaultPort = 25714;\n        nRPCPort = 25715;\n        strDataDir = \"testnet\";\n\n        \/\/ Modify the testnet genesis block so the timestamp is valid for a later start.\n        genesis.nBits  = bnProofOfWorkLimit.GetCompact();\n        genesis.nNonce = 216178;\n        hashGenesisBlock = genesis.GetHash();\n        assert(hashGenesisBlock == uint256(\"0x6b94f75518fa4fd5999880f0aff90de641c6151c9ba46319ed4bfa743d81b823\"));\n\n        vFixedSeeds.clear();\n        vSeeds.clear();\n\n        base58Prefixes[PUBKEY_ADDRESS] = list_of(111);\n        base58Prefixes[SCRIPT_ADDRESS] = list_of(196);\n        base58Prefixes[SECRET_KEY]     = list_of(239);\n        base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF);\n        base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94);\n\n        convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));\n\n        nLastPOWBlock = 0x7fffffff;\n    }\n    virtual Network NetworkID() const { return CChainParams::TESTNET; }\n};\nstatic CTestNetParams testNetParams;\n\n\n\/\/\n\/\/ Regression test\n\/\/\nclass CRegTestParams : public CTestNetParams {\npublic:\n    CRegTestParams() {\n        pchMessageStart[0] = 0xfa;\n        pchMessageStart[1] = 0xbf;\n        pchMessageStart[2] = 0xb5;\n        pchMessageStart[3] = 0xda;\n        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);\n        genesis.nTime = 1411111111;\n        genesis.nBits  = bnProofOfWorkLimit.GetCompact();\n        genesis.nNonce = 2;\n        hashGenesisBlock = genesis.GetHash();\n        nDefaultPort = 18444;\n        strDataDir = \"regtest\";\n        assert(hashGenesisBlock == uint256(\"0xb8851e0bd36876f25149e8fd911d53f4f8e1e14661b1627f49e569c32f4c5250\"));\n\n        vSeeds.clear();  \/\/ Regtest mode doesn't have any DNS seeds.\n    }\n\n    virtual bool RequireRPCPassword() const { return false; }\n    virtual Network NetworkID() const { return CChainParams::REGTEST; }\n};\nstatic CRegTestParams regTestParams;\n\nstatic CChainParams *pCurrentParams = &mainParams;\n\nconst CChainParams &Params() {\n    return *pCurrentParams;\n}\n\nvoid SelectParams(CChainParams::Network network) {\n    switch (network) {\n        case CChainParams::MAIN:\n            pCurrentParams = &mainParams;\n            break;\n        case CChainParams::TESTNET:\n            pCurrentParams = &testNetParams;\n            break;\n        case CChainParams::REGTEST:\n            pCurrentParams = &regTestParams;\n            break;\n        default:\n            assert(false && \"Unimplemented network\");\n            return;\n    }\n}\n\nbool SelectParamsFromCommandLine() {\n    bool fRegTest = GetBoolArg(\"-regtest\", false);\n    bool fTestNet = GetBoolArg(\"-testnet\", false);\n\n    if (fTestNet && fRegTest) {\n        return false;\n    }\n\n    if (fRegTest) {\n        SelectParams(CChainParams::REGTEST);\n    } else if (fTestNet) {\n        SelectParams(CChainParams::TESTNET);\n    } else {\n        SelectParams(CChainParams::MAIN);\n    }\n    return true;\n}\n","avg_line_length":36.4247787611,"max_line_length":325,"alphanum_fraction":0.6789358601,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2951,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":16.0,"content":"\/\/\n\/\/  PhyisicsDebugRenderable.cpp\n\/\/  BulletChapter1\n\/\/\n\/\/  Created by Ryan Bartley on 1\/24\/14.\n\/\/\n\/\/\n\n#include \"Cinder-Bullet3D\/PhysicsDebugRenderable.h\"\n#include \"cinder\/gl\/gl.h\"\n#include \"cinder\/gl\/Vao.h\"\n#include \"cinder\/gl\/Vbo.h\"\n#include \"cinder\/gl\/Shader.h\"\n#include \"cinder\/gl\/TextureFont.h\"\n\nusing namespace cinder;\n\nnamespace bullet {\n\t\nPhysicsDebugRenderable::PhysicsDebugRenderable()\n: mNewInfo( false ), mDebugMode( 0 ), mTextureFont( gl::TextureFont::create( Font( Font::getNames()[0], 20 ) ) )\n{\n}\n\t\nvoid PhysicsDebugRenderable::drawLine( const btVector3& from,const btVector3& to,const btVector3& color )\n{\n\tmPositionBuffer.push_back( fromBullet( from ) );\n\tmPositionBuffer.push_back( fromBullet( color ) );\n\n\tmPositionBuffer.push_back( fromBullet( to ) );\n\tmPositionBuffer.push_back( fromBullet( color ) );\n\tmNewInfo = true;\n}\n\t\nvoid PhysicsDebugRenderable::drawContactPoint(const btVector3 &pointOnB, const btVector3 &normalOnB, btScalar distance, int lifeTime, const btVector3 &color)\n{\n\t\/\/ draws a line between two contact points\n\tbtVector3 const startPoint = pointOnB;\n\tbtVector3 const endPoint = pointOnB + normalOnB * distance;\n\tdrawLine( startPoint, endPoint, color );\n}\n\t\nvoid PhysicsDebugRenderable::toggleDebugFlag( const int flag ) {\n\t\/\/ checks if a flag is set and enables\/\n\t\/\/ disables it\n\tif (mDebugMode & flag)\n\t\t\/\/ flag is enabled, so disable it\n\t\tmDebugMode = mDebugMode & (~flag);\n\telse\n\t\t\/\/ flag is disabled, so enable it\n\t\tmDebugMode |= flag;\n}\n\t\nvoid PhysicsDebugRenderable::initBuffers()\n{\n\tif( !mNewInfo )\n\t\treturn;\n\t\n\tif( !mPositionVbo )\n\t\tmPositionVbo = gl::Vbo::create( GL_ARRAY_BUFFER );\n\t\n\tmPositionVbo->bufferData( mPositionBuffer.size() * sizeof(vec3), mPositionBuffer.data(), GL_DYNAMIC_DRAW );\n\t\n\tif( mVao ) return;\n\t\n\tmVao = gl::Vao::create();\n\t\n\tgl::ScopedVao mVaoScope( mVao );\n\tgl::ScopedBuffer mVboScope( mPositionVbo );\n\t\n\tgl::enableVertexAttribArray(0);\n\tgl::vertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 2 * sizeof(vec3), 0 );\n\t\n\tgl::enableVertexAttribArray(1);\n\tgl::vertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 2 * sizeof(vec3), (void*)sizeof(vec3) );\n}\n\t\nvoid PhysicsDebugRenderable::draw3dText( const btVector3 &location, const char *textString )\n{\n\tmText.push_back( std::make_pair( fromBullet( location ), textString ) );\n}\n\t\nvoid PhysicsDebugRenderable::draw()\n{\n\tinitBuffers();\n\t\n\tgl::ScopedVao mVaoScope( mVao );\n\tgl::ScopedGlslProg mGlslScope( gl::getStockShader( gl::ShaderDef().color() ) );\n\t\n\tgl::setDefaultShaderVars();\n\t\n\tgl::drawArrays( GL_LINES, 0, mPositionBuffer.size() \/ 2 );\n\t\n\tif( mText.size() > 0 ) {\n\t\tgl::pushMatrices();\n\t\tauto textIt = mText.begin();\n\t\tauto end = mText.end();\n\t\twhile( textIt != end ) {\n\t\t\tgl::pushModelMatrix();\n\t\t\tgl::translate( (*textIt).first );\n\t\t\tmTextureFont->drawString( (*textIt).second, vec2( 0.0f ) );\n\t\t\tgl::popModelMatrix();\n\t\t\t++textIt;\n\t\t}\n\t\tgl::popMatrices();\n\t}\n\t\n\tmNewInfo = false;\n\tmPositionBuffer.clear();\n\tmText.clear();\n}\n\t\n\t\n}","avg_line_length":25.8859649123,"max_line_length":157,"alphanum_fraction":0.7068790241,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1123,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Copyright (C) 2012 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"FastMixerState.h\"\n\nnamespace android {\n\nFastTrack::FastTrack() :\n    mBufferProvider(NULL), mVolumeProvider(NULL),\n    mChannelMask(AUDIO_CHANNEL_OUT_STEREO), mFormat(AUDIO_FORMAT_INVALID), mGeneration(0)\n{\n}\n\nFastTrack::~FastTrack()\n{\n}\n\nFastMixerState::FastMixerState() : FastThreadState(),\n    \/\/ mFastTracks\n    mFastTracksGen(0), mTrackMask(0), mOutputSink(NULL), mOutputSinkGen(0),\n    mFrameCount(0), mTeeSink(NULL)\n{\n}\n\nFastMixerState::~FastMixerState()\n{\n}\n\n}   \/\/ namespace android\n","avg_line_length":26.1162790698,"max_line_length":89,"alphanum_fraction":0.731967943,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10786,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/******************************************************************************\n * Copyright (c) 2017 Philipp Schubert.\n * All rights reserved. This program and the accompanying materials are made\n * available under the terms of LICENSE.txt.\n *\n * Contributors:\n *     Philipp Schubert and others\n *****************************************************************************\/\n\n\/*\n *  DTAResolver.cpp\n *\n *  Created on: 20.07.2018\n *      Author: nicolas bellec\n *\/\n\n#include \"llvm\/IR\/CallSite.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/DerivedTypes.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/Instruction.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n\n#include \"phasar\/DB\/ProjectIRDB.h\"\n#include \"phasar\/PhasarLLVM\/ControlFlow\/LLVMBasedICFG.h\"\n#include \"phasar\/PhasarLLVM\/ControlFlow\/Resolver\/OTFResolver.h\"\n#include \"phasar\/PhasarLLVM\/Pointer\/LLVMPointsToGraph.h\"\n#include \"phasar\/PhasarLLVM\/Pointer\/LLVMPointsToInfo.h\"\n#include \"phasar\/PhasarLLVM\/TypeHierarchy\/LLVMTypeHierarchy.h\"\n#include \"phasar\/Utils\/LLVMShorthands.h\"\n#include \"phasar\/Utils\/Logger.h\"\n#include \"phasar\/Utils\/Utilities.h\"\n\nusing namespace std;\nusing namespace psr;\n\nOTFResolver::OTFResolver(ProjectIRDB &IRDB, LLVMTypeHierarchy &TH,\n                         LLVMBasedICFG &ICF, LLVMPointsToInfo &PT)\n    : CHAResolver(IRDB, TH), ICF(ICF), PT(PT) {}\n\nvoid OTFResolver::preCall(const llvm::Instruction *Inst) {}\n\nvoid OTFResolver::handlePossibleTargets(\n    llvm::ImmutableCallSite CS,\n    std::set<const llvm::Function *> &CalleeTargets) {\n  \/\/ if we have no inter-procedural points-to information, use call-graph\n  \/\/ information to simulate inter-procedural points-to information\n  if (!PT.isInterProcedural()) {\n    for (const auto *CalleeTarget : CalleeTargets) {\n      LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG)\n                    << \"Target name: \" << CalleeTarget->getName().str());\n      \/\/ do the merge of the points-to information for all possible targets, but\n      \/\/ only if they are available\n      if (!CalleeTarget->isDeclaration()) {\n        \/\/ handle parameter pairs\n        auto Pairs = getActualFormalPointerPairs(CS, CalleeTarget);\n        for (auto &[Actual, Formal] : Pairs) {\n          PT.introduceAlias(Actual, Formal, CS.getInstruction());\n        }\n        \/\/ handle return value\n        if (CalleeTarget->getReturnType()->isPointerTy()) {\n          for (const auto &ExitPoint : ICF.getExitPointsOf(CalleeTarget)) {\n            \/\/ get the function's return value\n            if (const auto *Ret = llvm::dyn_cast<llvm::ReturnInst>(ExitPoint)) {\n              \/\/ introduce alias to the returned value\n              PT.introduceAlias(CS.getInstruction(), Ret->getReturnValue(),\n                                CS.getInstruction());\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid OTFResolver::postCall(const llvm::Instruction *Inst) {}\n\nset<const llvm::Function *>\nOTFResolver::resolveVirtualCall(llvm::ImmutableCallSite CS) {\n  set<const llvm::Function *> PossibleCallTargets;\n\n  LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG)\n                << \"Call virtual function: \"\n                << llvmIRToString(CS.getInstruction()));\n\n  auto VtableIndex = getVFTIndex(CS);\n  if (VtableIndex < 0) {\n    \/\/ An error occured\n    LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG)\n                  << \"Error with resolveVirtualCall : impossible to retrieve \"\n                     \"the vtable index\\n\"\n                  << llvmIRToString(CS.getInstruction()) << \"\\n\");\n    return {};\n  }\n\n  LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG)\n                << \"Virtual function table entry is: \" << VtableIndex);\n\n  const llvm::Value *Receiver = CS.getArgOperand(0);\n\n  \/\/ Use points-to information to resolve the indirect call\n  auto AllocSites = PT.getReachableAllocationSites(Receiver);\n  auto PossibleAllocatedTypes = getReachableTypes(*AllocSites);\n\n  \/\/ Now we must check if we have found some allocated struct types\n  set<const llvm::StructType *> PossibleTypes;\n  for (const auto *Type : PossibleAllocatedTypes) {\n    if (const auto *StructType =\n            llvm::dyn_cast<llvm::StructType>(stripPointer(Type))) {\n      PossibleTypes.insert(StructType);\n    }\n  }\n\n  for (const auto *PossibleTypeStruct : PossibleTypes) {\n    const auto *Target =\n        getNonPureVirtualVFTEntry(PossibleTypeStruct, VtableIndex, CS);\n    if (Target) {\n      PossibleCallTargets.insert(Target);\n    }\n  }\n  if (PossibleCallTargets.empty()) {\n    return CHAResolver::resolveVirtualCall(CS);\n  }\n\n  return PossibleCallTargets;\n}\n\nstd::set<const llvm::Function *>\nOTFResolver::resolveFunctionPointer(llvm::ImmutableCallSite CS) {\n  std::set<const llvm::Function *> Callees;\n  if (CS.getCalledValue() && CS.getCalledValue()->getType()->isPointerTy()) {\n    if (const llvm::FunctionType *FTy = llvm::dyn_cast<llvm::FunctionType>(\n            CS.getCalledValue()->getType()->getPointerElementType())) {\n      const auto PTS = PT.getPointsToSet(CS.getCalledValue());\n      for (const auto *P : *PTS) {\n        if (P->getType()->isPointerTy() &&\n            P->getType()->getPointerElementType()->isFunctionTy()) {\n          if (const auto *F = llvm::dyn_cast<llvm::Function>(P)) {\n            if (matchesSignature(F, FTy, false)) {\n              Callees.insert(F);\n            }\n          }\n        }\n        std::vector<const llvm::GlobalVariable *> GlobalVariableWL;\n        std::stack<const llvm::ConstantAggregate *> ConstantAggregateWL;\n        if (auto *CE = llvm::dyn_cast<llvm::ConstantExpr>(P)) {\n          \/\/ Unfortunately this allocates\n          auto *AsI = CE->getAsInstruction();\n          for (auto &Op : AsI->operands()) {\n            if (auto *GVOp = llvm::dyn_cast<llvm::GlobalVariable>(Op)) {\n              GlobalVariableWL.push_back(GVOp);\n            }\n          }\n          AsI->deleteValue();\n        }\n        if (auto *GVP = llvm::dyn_cast<llvm::GlobalVariable>(P)) {\n          GlobalVariableWL.push_back(GVP);\n        }\n        for (auto *GV : GlobalVariableWL) {\n          if (!GV->hasInitializer()) {\n            continue;\n          }\n          auto InitConst = GV->getInitializer();\n          if (auto *InitConstAggregate =\n                  llvm::dyn_cast<llvm::ConstantAggregate>(InitConst)) {\n            ConstantAggregateWL.push(InitConstAggregate);\n          }\n        }\n        std::unordered_set<const llvm::ConstantAggregate *>\n            VisitedConstantAggregates;\n        while (!ConstantAggregateWL.empty()) {\n          auto ConstAggregateItem = ConstantAggregateWL.top();\n          ConstantAggregateWL.pop();\n          \/\/ We may have already processed the item, avoid an infinite loop\n          if (!VisitedConstantAggregates.insert(ConstAggregateItem).second) {\n            continue;\n          }\n          for (const auto &Op : ConstAggregateItem->operands()) {\n            if (auto *CE = llvm::dyn_cast<llvm::ConstantExpr>(Op)) {\n              auto *AsI = CE->getAsInstruction();\n              if (AsI->getType()->getPointerElementType() == FTy) {\n                if (auto *BC = llvm::dyn_cast<llvm::BitCastInst>(AsI)) {\n                  if (auto *F =\n                          llvm::dyn_cast<llvm::Function>(BC->getOperand(0))) {\n                    Callees.insert(F);\n                  }\n                }\n              }\n              AsI->deleteValue();\n            }\n            if (auto *F = llvm::dyn_cast<llvm::Function>(Op)) {\n              if (matchesSignature(F, FTy, false)) {\n                Callees.insert(F);\n              }\n            }\n            if (auto *CA = llvm::dyn_cast<llvm::ConstantAggregate>(Op)) {\n              ConstantAggregateWL.push(CA);\n            }\n            if (auto *GV = llvm::dyn_cast<llvm::GlobalVariable>(Op)) {\n              if (!GV->hasInitializer()) {\n                continue;\n              }\n              if (auto *GVCA = llvm::dyn_cast<llvm::ConstantAggregate>(\n                      GV->getInitializer())) {\n                ConstantAggregateWL.push(GVCA);\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n  return Callees;\n}\n\nstd::set<const llvm::Type *> OTFResolver::getReachableTypes(\n    const std::unordered_set<const llvm::Value *> &Values) {\n  std::set<const llvm::Type *> Types;\n  \/\/ an allocation site can either be an AllocaInst or a call to an\n  \/\/ allocating function\n  for (const auto *V : Values) {\n    if (const auto *Alloc = llvm::dyn_cast<llvm::AllocaInst>(V)) {\n      Types.insert(Alloc->getAllocatedType());\n    } else {\n      \/\/ usually if an allocating function is called, it is immediately\n      \/\/ bit-casted\n      \/\/ to the desired allocated value and hence we can determine it from\n      \/\/ the destination type of that cast instruction.\n      for (const auto *User : V->users()) {\n        if (const auto *Cast = llvm::dyn_cast<llvm::BitCastInst>(User)) {\n          Types.insert(Cast->getDestTy());\n        }\n      }\n    }\n  }\n  return Types;\n}\n\nstd::vector<std::pair<const llvm::Value *, const llvm::Value *>>\nOTFResolver::getActualFormalPointerPairs(llvm::ImmutableCallSite CS,\n                                         const llvm::Function *CalleeTarget) {\n  std::vector<std::pair<const llvm::Value *, const llvm::Value *>> Pairs;\n  \/\/ ordinary case\n  if (!CalleeTarget->isVarArg()) {\n    Pairs.reserve(CS.arg_size());\n    for (unsigned Idx = 0;\n         Idx < CS.arg_size() && Idx < CalleeTarget->arg_size(); ++Idx) {\n      \/\/ only collect pointer typed pairs\n      if (CS.getArgOperand(Idx)->getType()->isPointerTy() &&\n          CalleeTarget->getArg(Idx)->getType()->isPointerTy()) {\n        Pairs.emplace_back(CS.getArgOperand(Idx), CalleeTarget->getArg(Idx));\n      }\n    }\n  } else {\n    \/\/ in case of vararg, we can pair-up incoming pointer parameters with the\n    \/\/ vararg pack of the callee target. the vararg pack will alias\n    \/\/ (intra-procedurally) with any pointer values loaded from the pack\n    const llvm::AllocaInst *VarArgs = nullptr;\n    for (const auto &BB : *CalleeTarget) {\n      for (const auto &I : BB) {\n        if (const auto *Alloca = llvm::dyn_cast<llvm::AllocaInst>(&I)) {\n          if (const auto *AT =\n                  llvm::dyn_cast<llvm::ArrayType>(Alloca->getAllocatedType())) {\n            if (const auto *ST = llvm::dyn_cast<llvm::StructType>(\n                    AT->getArrayElementType())) {\n              if (ST->hasName() && ST->getName() == \"struct.__va_list_tag\") {\n                VarArgs = Alloca;\n                break;\n              }\n            }\n          }\n        }\n      }\n    }\n    if (VarArgs) {\n      for (unsigned Idx = 0; Idx < CS.arg_size(); ++Idx) {\n        if (CS.getArgOperand(Idx)->getType()->isPointerTy()) {\n          Pairs.emplace_back(CS.getArgOperand(Idx), VarArgs);\n        }\n      }\n    }\n  }\n  return Pairs;\n}\n","avg_line_length":37.5818815331,"max_line_length":80,"alphanum_fraction":0.5930836269,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2437,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include \"MessageHub.h\"\n\n#include <jd-util\/Exception.h>\n\n#include \"AbstractActor.h\"\n#include \"Message.h\"\n#include <jd-util\/Json.h>\n\nQ_LOGGING_CATEGORY(Messages, \"tablesync.messages\")\n\nMessageHub::MessageHub() {}\nMessageHub::~MessageHub() {}\n\nvoid MessageHub::registerActor(AbstractActor *actor)\n{\n\tQ_ASSERT_X(!m_actors.contains(actor), \"MessageHub::registerActor\", \"the given actor is already registered\");\n\tQ_ASSERT_X(actor->m_hub == this, \"MessageHub::registerActor\", \"attempting to register an actor belonging to a different hub\");\n\tm_actors.insert(actor);\n\t\/\/ re-subscribe to channels\n\tfor (const QString &channel : actor->m_channels) {\n\t\tsubscribeActorTo(actor, channel);\n\t}\n}\nvoid MessageHub::unregisterActor(AbstractActor *actor)\n{\n\tQ_ASSERT_X(m_actors.contains(actor), \"MessageHub::unregisterActor\", \"the given actor is not yet registered\");\n\tm_actors.remove(actor);\n\tfor (const QString &channel : actor->m_channels) {\n\t\tunsubscribeActorFrom(actor, channel);\n\t}\n}\n\nvoid MessageHub::subscribeActorTo(AbstractActor *actor, const QString &channel)\n{\n\tQ_ASSERT(actor);\n\tif (!m_subscriptions.contains(channel)) {\n\t\tsendToAllActors(Message(\"client\", \"subscribe\", QJsonObject({{\"channel\", channel}})));\n\t}\n\tm_subscriptions[channel].insert(actor);\n}\nvoid MessageHub::unsubscribeActorFrom(AbstractActor *actor, const QString &channel)\n{\n\tQ_ASSERT(actor);\n\tm_subscriptions[channel].remove(actor);\n\tif (m_subscriptions[channel].isEmpty()) {\n\t\tsendToAllActors(Message(\"client\", \"unsubscribe\", QJsonObject({{\"channel\", channel}})));\n\t\tm_subscriptions.remove(channel);\n\t}\n}\n\nvoid MessageHub::messageFromActor(AbstractActor *actor, const Message &msg)\n{\n\tqCDebug(Messages) << \"routing\" << msg;\n\n\tif (msg.to()) {\n\t\tmsg.to()->receive(msg);\n\t} else if (msg.channel() == \"client\") {\n\t\tif (msg.command() == \"reset\") {\n\t\t\tfor (AbstractActor *a : m_actors) {\n\t\t\t\ta->reset();\n\t\t\t}\n\t\t}\n\t} else {\n\t\tsendToAllActors(msg);\n\t}\n}\n\nvoid MessageHub::sendToAllActors(const Message &msg)\n{\n\tauto actors = [this, msg]() { return (m_subscriptions.value(msg.channel()) + m_subscriptions.value(\"*\")).toList().toSet(); };\n\n\tfor (AbstractActor *a : actors()) {\n\t\t\/\/ actors might unsubscribe, or even get deleted, when handling a message, thus we double-check to make sure it's still there\n\t\tif (actors().contains(a) && a != msg.from()) {\n\t\t\ttry {\n\t\t\t\ta->receive(msg);\n\t\t\t} catch (Exception &e) {\n\t\t\t\tmessageFromActor(a, msg.createErrorReply(e.cause()));\n\t\t\t}\n\t\t}\n\t}\n}\n","avg_line_length":29.3614457831,"max_line_length":127,"alphanum_fraction":0.7090685269,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":603,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"class Solution {\npublic:\n    bool isHappy(int n) {\n        set<int> appear;\n        int curr = n;\n        while(1){\n            \n            int temp = 0;\n            while(curr > 0){\n                temp += ((curr%10)*(curr%10));\n                curr \/= 10;\n            }\n            \n            \n            curr = temp;\n            \n            if(appear.find(1) != appear.end()){\n                return 1;\n            }\n            else if(appear.find(curr) != appear.end()){\n                return 0;\n            }\n            appear.insert(curr);\n            \n        }\n        return 0;\n    }\n};","avg_line_length":21.5357142857,"max_line_length":55,"alphanum_fraction":0.3250414594,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1891,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\ufeff\/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0.\n *\/\n\n#include <aws\/iot\/model\/ReportType.h>\n#include <aws\/core\/utils\/HashingUtils.h>\n#include <aws\/core\/Globals.h>\n#include <aws\/core\/utils\/EnumParseOverflowContainer.h>\n\nusing namespace Aws::Utils;\n\n\nnamespace Aws\n{\n  namespace IoT\n  {\n    namespace Model\n    {\n      namespace ReportTypeMapper\n      {\n\n        static const int ERRORS_HASH = HashingUtils::HashString(\"ERRORS\");\n        static const int RESULTS_HASH = HashingUtils::HashString(\"RESULTS\");\n\n\n        ReportType GetReportTypeForName(const Aws::String& name)\n        {\n          int hashCode = HashingUtils::HashString(name.c_str());\n          if (hashCode == ERRORS_HASH)\n          {\n            return ReportType::ERRORS;\n          }\n          else if (hashCode == RESULTS_HASH)\n          {\n            return ReportType::RESULTS;\n          }\n          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();\n          if(overflowContainer)\n          {\n            overflowContainer->StoreOverflow(hashCode, name);\n            return static_cast<ReportType>(hashCode);\n          }\n\n          return ReportType::NOT_SET;\n        }\n\n        Aws::String GetNameForReportType(ReportType enumValue)\n        {\n          switch(enumValue)\n          {\n          case ReportType::ERRORS:\n            return \"ERRORS\";\n          case ReportType::RESULTS:\n            return \"RESULTS\";\n          default:\n            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();\n            if(overflowContainer)\n            {\n              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));\n            }\n\n            return {};\n          }\n        }\n\n      } \/\/ namespace ReportTypeMapper\n    } \/\/ namespace Model\n  } \/\/ namespace IoT\n} \/\/ namespace Aws\n","avg_line_length":26.6338028169,"max_line_length":92,"alphanum_fraction":0.5980962454,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1947,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/\/ Copyright 2020 Krasilnikov Alexey\n\n#include \"..\/..\/..\/modules\/task_1\/krasilnikov_a_count_sentences\/count_sentences.h\"\n#include <mpi.h>\n#include <ctime>\n#include <random>\n#include <string>\n\n\nstd::string getRandomString(const size_t size) {\n  std::mt19937 generator;\n  std::string str(size, '_');\n  for (auto &symbol : str) {\n    if (generator() % 10 == 0) {\n      symbol = '.';\n    } else {\n      symbol = static_cast<char>(generator() % 128);\n    }\n  }\n  return str;\n}\n\nuint32_t getCountSentencesSequential(const std::string& str) {\n  uint32_t count_sentences = 0;\n  for (const auto symbol : str) {\n    if (symbol == '.') {\n      ++count_sentences;\n    }\n  }\n  return count_sentences;\n}\n\nuint32_t getCountSentencesParallel(const std::string& str, const size_t size_str) {\n  int rank, size;\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n  MPI_Comm_size(MPI_COMM_WORLD, &size);\n  uint32_t total_count = 0;\n  std::string local_str;\n  const uint32_t delta = size_str \/ size;\n  const uint32_t remain = size_str % size;\n  if (rank == 0) {\n    for (size_t process = 0; process < remain; ++process) {\n      MPI_Send(&str[0] + process * (delta + 1), delta + 1, MPI_CHAR, process + 1, 0, MPI_COMM_WORLD);\n    }\n    for (size_t process = remain; static_cast<int>(process) < size - 1; ++process) {\n      MPI_Send(&str[0] + process * delta + remain, delta, MPI_CHAR, process + 1, 0, MPI_COMM_WORLD);\n    }\n    local_str = str.substr((size - 1) * delta + remain);\n  } else {\n    MPI_Status status;\n    if (rank <= static_cast<int>(remain)) {\n      local_str.resize(delta + 1);\n      MPI_Recv(&local_str[0], delta + 1, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &status);\n    } else {\n      local_str.resize(delta);\n      MPI_Recv(&local_str[0], delta, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &status);\n    }\n  }\n  uint32_t local_count = getCountSentencesSequential(local_str);\n  MPI_Reduce(&local_count, &total_count, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);\n  return total_count;\n}\n","avg_line_length":30.9047619048,"max_line_length":101,"alphanum_fraction":0.6553672316,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6908,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com *\/\r\n#include <sstream>\r\n#include <limits>\r\n\r\n#include \"ifcpp\/model\/AttributeObject.h\"\r\n#include \"ifcpp\/model\/BuildingException.h\"\r\n#include \"ifcpp\/model\/BuildingGuid.h\"\r\n#include \"ifcpp\/reader\/ReaderUtil.h\"\r\n#include \"ifcpp\/writer\/WriterUtil.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcFlowInstrument.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcFlowInstrumentTypeEnum.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcGloballyUniqueId.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcIdentifier.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcLabel.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcObjectPlacement.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcOwnerHistory.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcProductRepresentation.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelAggregates.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelAssigns.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelAssignsToProduct.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelAssociates.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelConnectsElements.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelConnectsPortToElement.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelConnectsWithRealizingElements.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelContainedInSpatialStructure.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelCoversBldgElements.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelDeclares.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelDefinesByObject.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelDefinesByProperties.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelDefinesByType.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelFillsElement.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelFlowControlElements.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelInterferesElements.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelNests.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelProjectsElement.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelReferencedInSpatialStructure.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelSpaceBoundary.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcRelVoidsElement.h\"\r\n#include \"ifcpp\/IFC4\/include\/IfcText.h\"\r\n\r\n\/\/ ENTITY IfcFlowInstrument \r\nIfcFlowInstrument::IfcFlowInstrument() {}\r\nIfcFlowInstrument::IfcFlowInstrument( int id ) { m_entity_id = id; }\r\nIfcFlowInstrument::~IfcFlowInstrument() {}\r\nshared_ptr<BuildingObject> IfcFlowInstrument::getDeepCopy( BuildingCopyOptions& options )\r\n{\r\n\tshared_ptr<IfcFlowInstrument> copy_self( new IfcFlowInstrument() );\r\n\tif( m_GlobalId )\r\n\t{\r\n\t\tif( options.create_new_IfcGloballyUniqueId ) { copy_self->m_GlobalId = shared_ptr<IfcGloballyUniqueId>(new IfcGloballyUniqueId( createBase64Uuid<wchar_t>().data() ) ); }\r\n\t\telse { copy_self->m_GlobalId = dynamic_pointer_cast<IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); }\r\n\t}\r\n\tif( m_OwnerHistory )\r\n\t{\r\n\t\tif( options.shallow_copy_IfcOwnerHistory ) { copy_self->m_OwnerHistory = m_OwnerHistory; }\r\n\t\telse { copy_self->m_OwnerHistory = dynamic_pointer_cast<IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); }\r\n\t}\r\n\tif( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); }\r\n\tif( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); }\r\n\tif( m_ObjectType ) { copy_self->m_ObjectType = dynamic_pointer_cast<IfcLabel>( m_ObjectType->getDeepCopy(options) ); }\r\n\tif( m_ObjectPlacement ) { copy_self->m_ObjectPlacement = dynamic_pointer_cast<IfcObjectPlacement>( m_ObjectPlacement->getDeepCopy(options) ); }\r\n\tif( m_Representation ) { copy_self->m_Representation = dynamic_pointer_cast<IfcProductRepresentation>( m_Representation->getDeepCopy(options) ); }\r\n\tif( m_Tag ) { copy_self->m_Tag = dynamic_pointer_cast<IfcIdentifier>( m_Tag->getDeepCopy(options) ); }\r\n\tif( m_PredefinedType ) { copy_self->m_PredefinedType = dynamic_pointer_cast<IfcFlowInstrumentTypeEnum>( m_PredefinedType->getDeepCopy(options) ); }\r\n\treturn copy_self;\r\n}\r\nvoid IfcFlowInstrument::getStepLine( std::stringstream& stream ) const\r\n{\r\n\tstream << \"#\" << m_entity_id << \"= IFCFLOWINSTRUMENT\" << \"(\";\r\n\tif( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << \"$\"; }\r\n\tstream << \",\";\r\n\tif( m_OwnerHistory ) { stream << \"#\" << m_OwnerHistory->m_entity_id; } else { stream << \"$\"; }\r\n\tstream << \",\";\r\n\tif( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << \"$\"; }\r\n\tstream << \",\";\r\n\tif( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << \"$\"; }\r\n\tstream << \",\";\r\n\tif( m_ObjectType ) { m_ObjectType->getStepParameter( stream ); } else { stream << \"$\"; }\r\n\tstream << \",\";\r\n\tif( m_ObjectPlacement ) { stream << \"#\" << m_ObjectPlacement->m_entity_id; } else { stream << \"$\"; }\r\n\tstream << \",\";\r\n\tif( m_Representation ) { stream << \"#\" << m_Representation->m_entity_id; } else { stream << \"$\"; }\r\n\tstream << \",\";\r\n\tif( m_Tag ) { m_Tag->getStepParameter( stream ); } else { stream << \"$\"; }\r\n\tstream << \",\";\r\n\tif( m_PredefinedType ) { m_PredefinedType->getStepParameter( stream ); } else { stream << \"$\"; }\r\n\tstream << \");\";\r\n}\r\nvoid IfcFlowInstrument::getStepParameter( std::stringstream& stream, bool ) const { stream << \"#\" << m_entity_id; }\r\nconst std::wstring IfcFlowInstrument::toString() const { return L\"IfcFlowInstrument\"; }\r\nvoid IfcFlowInstrument::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map )\r\n{\r\n\tconst size_t num_args = args.size();\r\n\tif( num_args != 9 ){ std::stringstream err; err << \"Wrong parameter count for entity IfcFlowInstrument, expecting 9, having \" << num_args << \". Entity ID: \" << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); }\r\n\tm_GlobalId = IfcGloballyUniqueId::createObjectFromSTEP( args[0], map );\r\n\treadEntityReference( args[1], m_OwnerHistory, map );\r\n\tm_Name = IfcLabel::createObjectFromSTEP( args[2], map );\r\n\tm_Description = IfcText::createObjectFromSTEP( args[3], map );\r\n\tm_ObjectType = IfcLabel::createObjectFromSTEP( args[4], map );\r\n\treadEntityReference( args[5], m_ObjectPlacement, map );\r\n\treadEntityReference( args[6], m_Representation, map );\r\n\tm_Tag = IfcIdentifier::createObjectFromSTEP( args[7], map );\r\n\tm_PredefinedType = IfcFlowInstrumentTypeEnum::createObjectFromSTEP( args[8], map );\r\n}\r\nvoid IfcFlowInstrument::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes )\r\n{\r\n\tIfcDistributionControlElement::getAttributes( vec_attributes );\r\n\tvec_attributes.push_back( std::make_pair( \"PredefinedType\", m_PredefinedType ) );\r\n}\r\nvoid IfcFlowInstrument::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse )\r\n{\r\n\tIfcDistributionControlElement::getAttributesInverse( vec_attributes_inverse );\r\n}\r\nvoid IfcFlowInstrument::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity )\r\n{\r\n\tIfcDistributionControlElement::setInverseCounterparts( ptr_self_entity );\r\n}\r\nvoid IfcFlowInstrument::unlinkFromInverseCounterparts()\r\n{\r\n\tIfcDistributionControlElement::unlinkFromInverseCounterparts();\r\n}\r\n","avg_line_length":56.6229508197,"max_line_length":235,"alphanum_fraction":0.748552403,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10768,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2019 The PIVX developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <qt\/pivx\/receivewidget.h>\n#include <qt\/pivx\/forms\/ui_receivewidget.h>\n#include <qt\/pivx\/requestdialog.h>\n#include <qt\/pivx\/addnewcontactdialog.h>\n#include <qt\/pivx\/qtutils.h>\n#include <qt\/pivx\/myaddressrow.h>\n#include <qt\/pivx\/furlistrow.h>\n#include <walletmodel.h>\n#include <guiutil.h>\n\n#include <QModelIndex>\n#include <QColor>\n#include <QDateTime>\n\n#define DECORATION_SIZE 70\n#define NUM_ITEMS 3\n\nclass AddressHolder : public FurListRow<QWidget*>\n{\npublic:\n    AddressHolder();\n\n    explicit AddressHolder(bool _isLightTheme) : FurListRow(), isLightTheme(_isLightTheme){}\n\n    MyAddressRow* createHolder(int pos) override{\n        if (!cachedRow) cachedRow = new MyAddressRow();\n        return cachedRow;\n    }\n\n    void init(QWidget* holder,const QModelIndex &index, bool isHovered, bool isSelected) const override{\n        MyAddressRow *row = static_cast<MyAddressRow*>(holder);\n        QString address = index.data(Qt::DisplayRole).toString();\n        QString label = index.sibling(index.row(), AddressTableModel::Label).data(Qt::DisplayRole).toString();\n        uint time = index.sibling(index.row(), AddressTableModel::Date).data(Qt::DisplayRole).toUInt();\n        QString date = (time == 0) ? \"\" : GUIUtil::dateTimeStr(QDateTime::fromTime_t(time));\n        row->updateView(address, label, date);\n    }\n\n    QColor rectColor(bool isHovered, bool isSelected) override{\n        return getRowColor(isLightTheme, isHovered, isSelected);\n    }\n\n    ~AddressHolder() override{}\n\n    bool isLightTheme;\n    MyAddressRow* cachedRow = nullptr;\n};\n\nReceiveWidget::ReceiveWidget(ALQOGUI* parent) :\n    PWidget(parent),\n    ui(new Ui::ReceiveWidget)\n{\n    ui->setupUi(this);\n    this->setStyleSheet(parent->styleSheet());\n\n    delegate = new FurAbstractListItemDelegate(\n                DECORATION_SIZE,\n                new AddressHolder(isLightTheme()),\n                this\n                );\n\n    \/\/ Containers\n    setCssProperty(ui->left, \"container\");\n    ui->left->setContentsMargins(20,20,20,20);\n    setCssProperty(ui->right, \"container-right\");\n    ui->right->setContentsMargins(0,9,0,0);\n\n    \/\/ Title\n    ui->labelTitle->setText(tr(\"Receive\"));\n    ui->labelSubtitle1->setText(tr(\"Scan the QR code or copy the address to receive ALQO.\"));\n    setCssTitleScreen(ui->labelTitle);\n    setCssSubtitleScreen(ui->labelSubtitle1);\n\n    \/\/ Address\n    ui->labelAddress->setText(tr(\"No address \"));\n    setCssProperty(ui->labelAddress, \"label-address-box\");\n\n    ui->labelDate->setText(\"Dec. 19, 2018\");\n    setCssSubtitleScreen(ui->labelDate);\n    ui->labelLabel->setText(\"\");\n    setCssSubtitleScreen(ui->labelLabel);\n\n    \/\/ Options\n    ui->btnMyAddresses->setTitleClassAndText(\"btn-title-grey\", \"My Addresses\");\n    ui->btnMyAddresses->setSubTitleClassAndText(\"text-subtitle\", \"List your own addresses.\");\n    ui->btnMyAddresses->layout()->setMargin(0);\n    ui->btnMyAddresses->setRightIconClass(\"ic-arrow\");\n\n    ui->btnRequest->setTitleClassAndText(\"btn-title-grey\", \"Create Request\");\n    ui->btnRequest->setSubTitleClassAndText(\"text-subtitle\", \"Request payment with a fixed amount.\");\n    ui->btnRequest->layout()->setMargin(0);\n\n    ui->pushButtonLabel->setText(tr(\"Add Label\"));\n    ui->pushButtonLabel->setLayoutDirection(Qt::RightToLeft);\n    setCssProperty(ui->pushButtonLabel, \"btn-secundary-label\");\n\n    ui->pushButtonNewAddress->setText(tr(\"Generate Address\"));\n    ui->pushButtonNewAddress->setLayoutDirection(Qt::RightToLeft);\n    setCssProperty(ui->pushButtonNewAddress, \"btn-secundary-new-address\");\n\n    ui->pushButtonCopy->setText(tr(\"Copy\"));\n    ui->pushButtonCopy->setLayoutDirection(Qt::RightToLeft);\n    setCssProperty(ui->pushButtonCopy, \"btn-secundary-copy\");\n\n    \/\/ List Addresses\n    setCssProperty(ui->listViewAddress, \"container\");\n    ui->listViewAddress->setItemDelegate(delegate);\n    ui->listViewAddress->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));\n    ui->listViewAddress->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));\n    ui->listViewAddress->setAttribute(Qt::WA_MacShowFocusRect, false);\n    ui->listViewAddress->setSelectionBehavior(QAbstractItemView::SelectRows);\n\n    spacer = new QSpacerItem(40, 20, QSizePolicy::Maximum, QSizePolicy::Expanding);\n    ui->btnMyAddresses->setChecked(true);\n    ui->container_right->addItem(spacer);\n    ui->listViewAddress->setVisible(false);\n\n    \/\/ Connect\n    connect(ui->pushButtonLabel, SIGNAL(clicked()), this, SLOT(onLabelClicked()));\n    connect(ui->pushButtonCopy, SIGNAL(clicked()), this, SLOT(onCopyClicked()));\n    connect(ui->pushButtonNewAddress, SIGNAL(clicked()), this, SLOT(onNewAddressClicked()));\n    connect(ui->listViewAddress, SIGNAL(clicked(QModelIndex)), this, SLOT(handleAddressClicked(QModelIndex)));\n    connect(ui->btnRequest, SIGNAL(clicked()), this, SLOT(onRequestClicked()));\n    connect(ui->btnMyAddresses, SIGNAL(clicked()), this, SLOT(onMyAddressesClicked()));\n}\n\nvoid ReceiveWidget::loadWalletModel(){\n    if(walletModel) {\n        this->addressTableModel = walletModel->getAddressTableModel();\n        this->filter = new AddressFilterProxyModel(AddressTableModel::Receive, this);\n        this->filter->setSourceModel(addressTableModel);\n        ui->listViewAddress->setModel(this->filter);\n        ui->listViewAddress->setModelColumn(AddressTableModel::Address);\n\n        if(!info) info = new SendCoinsRecipient();\n        refreshView();\n\n        \/\/ data change\n        connect(this->addressTableModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(refreshView()));\n    }\n}\n\nvoid ReceiveWidget::refreshView(QString refreshAddress){\n    try {\n        QString latestAddress = (refreshAddress.isEmpty()) ? this->addressTableModel->getLastUnusedAddress() : refreshAddress;\n        if (latestAddress.isEmpty()) \/\/ new default address\n           latestAddress = QString::fromStdString(walletModel->getNewAddress(\"Default\").ToString());\n        ui->labelAddress->setText(latestAddress);\n        int64_t time = walletModel->getKeyCreationTime(CBitcoinAddress(latestAddress.toStdString()));\n        ui->labelDate->setText(GUIUtil::dateTimeStr(QDateTime::fromTime_t(static_cast<uint>(time))));\n        updateQr(latestAddress);\n        updateLabel();\n    } catch (const std::runtime_error& error){\n        ui->labelQrImg->setText(tr(\"No available address, try unlocking the wallet\"));\n        inform(tr(\"Error generating address\"));\n    }\n}\n\nvoid ReceiveWidget::updateLabel(){\n    if(!info->address.isEmpty()) {\n        \/\/ Check if address label exists\n        QString label = addressTableModel->labelForAddress(info->address);\n        if (!label.isEmpty()) {\n            ui->labelLabel->setVisible(true);\n            ui->labelLabel->setText(label);\n            ui->pushButtonLabel->setText(tr(\"Change Label\"));\n        }else{\n            ui->labelLabel->setVisible(false);\n        }\n    }\n}\n\nvoid ReceiveWidget::updateQr(QString address){\n    info->address = address;\n    QString uri = GUIUtil::formatBitcoinURI(*info);\n    ui->labelQrImg->setText(\"\");\n\n    QString error;\n    QColor qrColor(\"#002d4d\");\n    QPixmap pixmap = encodeToQr(uri, error, qrColor);\n    if(!pixmap.isNull()){\n        qrImage = &pixmap;\n        ui->labelQrImg->setPixmap(qrImage->scaled(ui->labelQrImg->width(), ui->labelQrImg->height()));\n    }else{\n        ui->labelQrImg->setText(!error.isEmpty() ? error : \"Error encoding address\");\n    }\n}\n\nvoid ReceiveWidget::handleAddressClicked(const QModelIndex &index){\n    QModelIndex rIndex = filter->mapToSource(index);\n    refreshView(rIndex.data(Qt::DisplayRole).toString());\n}\n\nvoid ReceiveWidget::onLabelClicked(){\n    if(walletModel && !isShowingDialog) {\n        isShowingDialog = true;\n        showHideOp(true);\n        AddNewContactDialog *dialog = new AddNewContactDialog(window);\n        dialog->setTexts(tr(\"Edit Address Label\"));\n        dialog->setData(info->address, addressTableModel->labelForAddress(info->address));\n        if (openDialogWithOpaqueBackgroundY(dialog, window, 3.5, 6)) {\n            QString label = dialog->getLabel();\n            const CBitcoinAddress address = CBitcoinAddress(info->address.toUtf8().constData());\n            if (!label.isEmpty() && walletModel->updateAddressBookLabels(\n                    address.Get(),\n                    label.toUtf8().constData(),\n                    \"receive\"\n            )\n                    ) {\n                \/\/ update label status (icon color)\n                updateLabel();\n                inform(tr(\"Address label saved\"));\n            } else {\n                inform(tr(\"Error storing address label\"));\n            }\n        }\n        isShowingDialog = false;\n    }\n}\n\nvoid ReceiveWidget::onNewAddressClicked(){\n    try {\n        if (!verifyWalletUnlocked()) return;\n        CBitcoinAddress address = walletModel->getNewAddress(\"\");\n        updateQr(QString::fromStdString(address.ToString()));\n        ui->labelAddress->setText(!info->address.isEmpty() ? info->address : tr(\"No address\"));\n        updateLabel();\n        inform(tr(\"New address created\"));\n    } catch (const std::runtime_error& error){\n        \/\/ Error generating address\n        inform(\"Error generating address\");\n    }\n}\n\nvoid ReceiveWidget::onCopyClicked(){\n    GUIUtil::setClipboard(info->address);\n    inform(tr(\"Address copied\"));\n}\n\n\nvoid ReceiveWidget::onRequestClicked(){\n    if(walletModel && !isShowingDialog) {\n        if (!verifyWalletUnlocked()) return;\n        isShowingDialog = true;\n        showHideOp(true);\n        RequestDialog *dialog = new RequestDialog(window);\n        dialog->setWalletModel(walletModel);\n        openDialogWithOpaqueBackgroundY(dialog, window, 3.5, 12);\n        if (dialog->res == 1){\n            inform(tr(\"URI copied to clipboard\"));\n        } else if (dialog->res == 2){\n            inform(tr(\"Address copied to clipboard\"));\n        }\n        dialog->deleteLater();\n        isShowingDialog = false;\n    }\n}\n\nvoid ReceiveWidget::onMyAddressesClicked(){\n    bool isVisible = ui->listViewAddress->isVisible();\n    if(!isVisible){\n        ui->btnMyAddresses->setRightIconClass(\"btn-dropdown\", true);\n        ui->listViewAddress->setVisible(true);\n        ui->container_right->removeItem(spacer);\n        ui->listViewAddress->update();\n    }else{\n        ui->btnMyAddresses->setRightIconClass(\"ic-arrow\", true);\n        ui->container_right->addItem(spacer);\n        ui->listViewAddress->setVisible(false);\n    }\n}\n\nvoid ReceiveWidget::changeTheme(bool isLightTheme, QString& theme){\n    static_cast<AddressHolder*>(this->delegate->getRowFactory())->isLightTheme = isLightTheme;\n}\n\nReceiveWidget::~ReceiveWidget(){\n    delete ui;\n}\n","avg_line_length":37.9154929577,"max_line_length":126,"alphanum_fraction":0.6718982169,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1511,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":28.0,"content":"\/* TEMPLATE GENERATED TESTCASE FILE\r\nFilename: CWE36_Absolute_Path_Traversal__char_environment_open_53c.cpp\r\nLabel Definition File: CWE36_Absolute_Path_Traversal.label.xml\r\nTemplate File: sources-sink-53c.tmpl.cpp\r\n*\/\r\n\/*\r\n * @description\r\n * CWE: 36 Absolute Path Traversal\r\n * BadSource: environment Read input from an environment variable\r\n * GoodSource: Full path and file name\r\n * Sink: open\r\n *    BadSink : Open the file named in data using open()\r\n * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files\r\n *\r\n * *\/\r\n\r\n#include \"std_testcase.h\"\r\n\r\n#ifndef _WIN32\r\n#include <wchar.h>\r\n#endif\r\n\r\n#define ENV_VARIABLE \"ADD\"\r\n\r\n#ifdef _WIN32\r\n#define GETENV getenv\r\n#else\r\n#define GETENV getenv\r\n#endif\r\n\r\n#ifdef _WIN32\r\n#define OPEN _open\r\n#define CLOSE _close\r\n#else\r\n#include <unistd.h>\r\n#define OPEN open\r\n#define CLOSE close\r\n#endif\r\n\r\nnamespace CWE36_Absolute_Path_Traversal__char_environment_open_53\r\n{\r\n\r\n\/* all the sinks are the same, we just want to know where the hit originated if a tool flags one *\/\r\n\r\n#ifndef OMITBAD\r\n\r\n\/* bad function declaration *\/\r\nvoid badSink_d(char * data);\r\n\r\nvoid badSink_c(char * data)\r\n{\r\n    badSink_d(data);\r\n}\r\n\r\n#endif \/* OMITBAD *\/\r\n\r\n#ifndef OMITGOOD\r\n\r\n\/* goodG2B uses the GoodSource with the BadSink *\/\r\nvoid goodG2BSink_d(char * data);\r\n\r\nvoid goodG2BSink_c(char * data)\r\n{\r\n    goodG2BSink_d(data);\r\n}\r\n\r\n#endif \/* OMITGOOD *\/\r\n\r\n} \/* close namespace *\/\r\n","avg_line_length":21.5857142857,"max_line_length":157,"alphanum_fraction":0.7167438782,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1396,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense","OpenSSL","MIT"],"max_stars_count":null,"content":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ CoinVault\n\/\/\n\/\/ passphrasedialog.cpp\n\/\/\n\/\/ Copyright (c) 2014 Eric Lombrozo\n\/\/\n\/\/ All Rights Reserved.\n\n#include \"passphrasedialog.h\"\n\n#include <QDialogButtonBox>\n#include <QHBoxLayout>\n#include <QVBoxLayout>\n#include <QLineEdit>\n#include <QLabel>\n\nPassphraseDialog::PassphraseDialog(const QString& prompt, QWidget* parent)\n    : QDialog(parent)\n{\n    \/\/ Buttons\n    QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok\n                                     | QDialogButtonBox::Cancel);\n\n    connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));\n    connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));\n    \/\/ Prompt\n\n    QLabel* promptLabel = new QLabel();\n    promptLabel->setText(prompt);\n\n    \/\/ Text Edit\n    passphraseEdit = new QLineEdit();\n    passphraseEdit->setEchoMode(QLineEdit::Password);\n\n    QVBoxLayout* mainLayout = new QVBoxLayout();\n    mainLayout->setSizeConstraint(QLayout::SetNoConstraint);\n    mainLayout->addWidget(promptLabel);\n    mainLayout->addWidget(passphraseEdit);\n    mainLayout->addWidget(buttonBox);\n    setLayout(mainLayout);\n\n    resize(500, 140);\n}\n\nQString PassphraseDialog::getPassphrase() const\n{\n    if (passphraseEdit->text().isEmpty())\n        throw std::runtime_error(\"Passphrase is empty.\");\n\n    return passphraseEdit->text();\n}\n","avg_line_length":25.8518518519,"max_line_length":79,"alphanum_fraction":0.6489971347,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":850,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":9.0,"content":"\/*\n\tTITLE\t\t\t    Implement reassignment     Chapter7Exercise12.cpp\n\t\"Software - Principles and Practice using C++\" by Bjarne Stroustrup\"\n\tCOMMENT\n\t\t\tObjective: Implement reassignment for the used defined variables.\n\t\t\t\t\t   Already provided in all of the previous exercises.\n\t\t\t\t\t   \n\t\t\t\t\t   Advantages of reassignment:\n\t\t\t\t\t   - the existence of non-const variables, i.e.\n\t\t\t\t\t   variables that could be assigned value after definition.\n\n\t\t\t\t\t   Possible source of errors during reassignment:\n\n\t\t\t\t\t   1. In case we want to define new variable, but:\n\t\t\t\t\t\t\t- forget the keyword \"let\"\n\t\t\t\t\t\t\t- forget that there is an existent varaible with the same name.\n\t\t\t\t\t\t  Instead of defining new variable we will override the existent.\n\n\t\t\t\tInput: - \n\t\t\t   Output: -\n\t\t\t   Author: Chris B. Kirov\n\t\t\t     Date: 25.02.2015\n*\/\n#include <iostream>\n\nint main()\n{\n\n}","avg_line_length":29.3103448276,"max_line_length":71,"alphanum_fraction":0.6694117647,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":20492,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":5.0,"content":"\/\/ ======================================================================\n\/\/ \\title  ZmqAdapter\/test\/ut\/TesterBase.cpp\n\/\/ \\author Auto-generated\n\/\/ \\brief  cpp file for ZmqAdapter component test harness base class\n\/\/\n\/\/ \\copyright\n\/\/ Copyright 2009-2016, by the California Institute of Technology.\n\/\/ ALL RIGHTS RESERVED.  United States Government Sponsorship\n\/\/ acknowledged. Any commercial use must be negotiated with the Office\n\/\/ of Technology Transfer at the California Institute of Technology.\n\/\/\n\/\/ This software may be subject to U.S. export control laws and\n\/\/ regulations.  By accepting this document, the user agrees to comply\n\/\/ with all U.S. export laws and regulations.  User has the\n\/\/ responsibility to obtain export licenses, or other export authority\n\/\/ as may be required before exporting such information to foreign\n\/\/ countries or providing access to foreign persons.\n\/\/ ======================================================================\n\n#include <stdlib.h>\n#include <string.h>\n#include \"TesterBase.hpp\"\n\nnamespace Zmq {\n\n  \/\/ ----------------------------------------------------------------------\n  \/\/ Construction, initialization, and destruction\n  \/\/ ----------------------------------------------------------------------\n\n  ZmqAdapterTesterBase ::\n    ZmqAdapterTesterBase(\n#if FW_OBJECT_NAMES == 1\n        const char *const compName,\n        const U32 maxHistorySize\n#else\n        const U32 maxHistorySize\n#endif\n    ) :\n#if FW_OBJECT_NAMES == 1\n      Fw::PassiveComponentBase(compName)\n#else\n      Fw::PassiveComponentBase()\n#endif\n  {\n    \/\/ Initialize telemetry histories\n    this->tlmHistory_ZA_BytesSent = \n      new History<TlmEntry_ZA_BytesSent>(maxHistorySize);\n    this->tlmHistory_ZA_BytesReceived = \n      new History<TlmEntry_ZA_BytesReceived>(maxHistorySize);\n    \/\/ Initialize event histories\n#if FW_ENABLE_TEXT_LOGGING\n    this->textLogHistory = new History<TextLogEntry>(maxHistorySize);\n#endif\n    \/\/ Clear history\n    this->clearHistory();\n  }\n\n  ZmqAdapterTesterBase ::\n    ~ZmqAdapterTesterBase(void) \n  {\n    \/\/ Destroy telemetry histories\n    delete this->tlmHistory_ZA_BytesSent;\n    delete this->tlmHistory_ZA_BytesReceived;\n    \/\/ Destroy event histories\n#if FW_ENABLE_TEXT_LOGGING\n    delete this->textLogHistory;\n#endif\n  }\n\n  void ZmqAdapterTesterBase ::\n    init(\n        const NATIVE_INT_TYPE instance\n    )\n  {\n\n    \/\/ Initialize base class\n\n\t\tFw::PassiveComponentBase::init(instance);\n\n    \/\/ Attach input port PortsOut\n\n    for (\n        NATIVE_INT_TYPE _port = 0;\n        _port < this->getNum_from_PortsOut();\n        ++_port\n    ) {\n\n      this->m_from_PortsOut[_port].init();\n      this->m_from_PortsOut[_port].addCallComp(\n          this,\n          from_PortsOut_static\n      );\n      this->m_from_PortsOut[_port].setPortNum(_port);\n\n#if FW_OBJECT_NAMES == 1\n      char _portName[80];\n      (void) snprintf(\n          _portName,\n          sizeof(_portName),\n          \"%s_from_PortsOut[%d]\",\n          this->m_objName,\n          _port\n      );\n      this->m_from_PortsOut[_port].setObjName(_portName);\n#endif\n\n    }\n\n    \/\/ Attach input port Tlm\n\n    for (\n        NATIVE_INT_TYPE _port = 0;\n        _port < this->getNum_from_Tlm();\n        ++_port\n    ) {\n\n      this->m_from_Tlm[_port].init();\n      this->m_from_Tlm[_port].addCallComp(\n          this,\n          from_Tlm_static\n      );\n      this->m_from_Tlm[_port].setPortNum(_port);\n\n#if FW_OBJECT_NAMES == 1\n      char _portName[80];\n      (void) snprintf(\n          _portName,\n          sizeof(_portName),\n          \"%s_from_Tlm[%d]\",\n          this->m_objName,\n          _port\n      );\n      this->m_from_Tlm[_port].setObjName(_portName);\n#endif\n\n    }\n\n    \/\/ Attach input port Time\n\n    for (\n        NATIVE_INT_TYPE _port = 0;\n        _port < this->getNum_from_Time();\n        ++_port\n    ) {\n\n      this->m_from_Time[_port].init();\n      this->m_from_Time[_port].addCallComp(\n          this,\n          from_Time_static\n      );\n      this->m_from_Time[_port].setPortNum(_port);\n\n#if FW_OBJECT_NAMES == 1\n      char _portName[80];\n      (void) snprintf(\n          _portName,\n          sizeof(_portName),\n          \"%s_from_Time[%d]\",\n          this->m_objName,\n          _port\n      );\n      this->m_from_Time[_port].setObjName(_portName);\n#endif\n\n    }\n\n    \/\/ Attach input port Log\n\n    for (\n        NATIVE_INT_TYPE _port = 0;\n        _port < this->getNum_from_Log();\n        ++_port\n    ) {\n\n      this->m_from_Log[_port].init();\n      this->m_from_Log[_port].addCallComp(\n          this,\n          from_Log_static\n      );\n      this->m_from_Log[_port].setPortNum(_port);\n\n#if FW_OBJECT_NAMES == 1\n      char _portName[80];\n      (void) snprintf(\n          _portName,\n          sizeof(_portName),\n          \"%s_from_Log[%d]\",\n          this->m_objName,\n          _port\n      );\n      this->m_from_Log[_port].setObjName(_portName);\n#endif\n\n    }\n\n    \/\/ Attach input port LogText\n\n#if FW_ENABLE_TEXT_LOGGING == 1\n    for (\n        NATIVE_INT_TYPE _port = 0;\n        _port < this->getNum_from_LogText();\n        ++_port\n    ) {\n\n      this->m_from_LogText[_port].init();\n      this->m_from_LogText[_port].addCallComp(\n          this,\n          from_LogText_static\n      );\n      this->m_from_LogText[_port].setPortNum(_port);\n\n#if FW_OBJECT_NAMES == 1\n      char _portName[80];\n      (void) snprintf(\n          _portName,\n          sizeof(_portName),\n          \"%s_from_LogText[%d]\",\n          this->m_objName,\n          _port\n      );\n      this->m_from_LogText[_port].setObjName(_portName);\n#endif\n\n    }\n#endif\n\n    \/\/ Initialize output port Sched\n\n    for (\n        NATIVE_INT_TYPE _port = 0;\n        _port < this->getNum_to_Sched();\n        ++_port\n    ) {\n      this->m_to_Sched[_port].init();\n\n#if FW_OBJECT_NAMES == 1\n      char _portName[80];\n      snprintf(\n          _portName,\n          sizeof(_portName),\n          \"%s_to_Sched[%d]\",\n          this->m_objName,\n          _port\n      );\n      this->m_to_Sched[_port].setObjName(_portName);\n#endif\n\n    }\n\n    \/\/ Initialize output port PortsIn\n\n    for (\n        NATIVE_INT_TYPE _port = 0;\n        _port < this->getNum_to_PortsIn();\n        ++_port\n    ) {\n      this->m_to_PortsIn[_port].init();\n\n#if FW_OBJECT_NAMES == 1\n      char _portName[80];\n      snprintf(\n          _portName,\n          sizeof(_portName),\n          \"%s_to_PortsIn[%d]\",\n          this->m_objName,\n          _port\n      );\n      this->m_to_PortsIn[_port].setObjName(_portName);\n#endif\n\n    }\n\n  }\n\n  \/\/ ----------------------------------------------------------------------\n  \/\/ Getters for port counts\n  \/\/ ----------------------------------------------------------------------\n\n  NATIVE_INT_TYPE ZmqAdapterTesterBase ::\n    getNum_to_Sched(void) const\n  {\n    return (NATIVE_INT_TYPE) FW_NUM_ARRAY_ELEMENTS(this->m_to_Sched);\n  }\n\n  NATIVE_INT_TYPE ZmqAdapterTesterBase ::\n    getNum_to_PortsIn(void) const\n  {\n    return (NATIVE_INT_TYPE) FW_NUM_ARRAY_ELEMENTS(this->m_to_PortsIn);\n  }\n\n  NATIVE_INT_TYPE ZmqAdapterTesterBase ::\n    getNum_from_PortsOut(void) const\n  {\n    return (NATIVE_INT_TYPE) FW_NUM_ARRAY_ELEMENTS(this->m_from_PortsOut);\n  }\n\n  NATIVE_INT_TYPE ZmqAdapterTesterBase ::\n    getNum_from_Tlm(void) const\n  {\n    return (NATIVE_INT_TYPE) FW_NUM_ARRAY_ELEMENTS(this->m_from_Tlm);\n  }\n\n  NATIVE_INT_TYPE ZmqAdapterTesterBase ::\n    getNum_from_Time(void) const\n  {\n    return (NATIVE_INT_TYPE) FW_NUM_ARRAY_ELEMENTS(this->m_from_Time);\n  }\n\n  NATIVE_INT_TYPE ZmqAdapterTesterBase ::\n    getNum_from_Log(void) const\n  {\n    return (NATIVE_INT_TYPE) FW_NUM_ARRAY_ELEMENTS(this->m_from_Log);\n  }\n\n#if FW_ENABLE_TEXT_LOGGING == 1\n  NATIVE_INT_TYPE ZmqAdapterTesterBase ::\n    getNum_from_LogText(void) const\n  {\n    return (NATIVE_INT_TYPE) FW_NUM_ARRAY_ELEMENTS(this->m_from_LogText);\n  }\n#endif\n\n  \/\/ ----------------------------------------------------------------------\n  \/\/ Connectors for to ports \n  \/\/ ----------------------------------------------------------------------\n\n  void ZmqAdapterTesterBase ::\n    connect_to_Sched(\n        const NATIVE_INT_TYPE portNum,\n        Svc::InputSchedPort *const Sched\n    ) \n  {\n    FW_ASSERT(portNum < this->getNum_to_Sched(),static_cast<AssertArg>(portNum));\n    this->m_to_Sched[portNum].addCallPort(Sched);\n  }\n\n  void ZmqAdapterTesterBase ::\n    connect_to_PortsIn(\n        const NATIVE_INT_TYPE portNum,\n        Fw::InputSerializePort *const PortsIn\n    ) \n  {\n    FW_ASSERT(portNum < this->getNum_to_PortsIn(),static_cast<AssertArg>(portNum));\n    this->m_to_PortsIn[portNum].registerSerialPort(PortsIn);\n  }\n\n\n  \/\/ ----------------------------------------------------------------------\n  \/\/ Invocation functions for to ports\n  \/\/ ----------------------------------------------------------------------\n\n  void ZmqAdapterTesterBase ::\n    invoke_to_Sched(\n        const NATIVE_INT_TYPE portNum,\n        NATIVE_UINT_TYPE context\n    )\n  {\n    FW_ASSERT(portNum < this->getNum_to_Sched(),static_cast<AssertArg>(portNum));\n    FW_ASSERT(portNum < this->getNum_to_Sched(),static_cast<AssertArg>(portNum));\n    this->m_to_Sched[portNum].invoke(\n        context\n    );\n  }\n\n  void ZmqAdapterTesterBase ::\n    invoke_to_PortsIn(\n      NATIVE_INT_TYPE portNum, \/\/!< The port number\n      Fw::SerializeBufferBase& Buffer\n    )\n  {\n    FW_ASSERT(portNum < this->getNum_to_PortsIn(),static_cast<AssertArg>(portNum));\n    this->m_to_PortsIn[portNum].invokeSerial(Buffer);\n  }\n\n  \/\/ ----------------------------------------------------------------------\n  \/\/ Connection status for to ports\n  \/\/ ----------------------------------------------------------------------\n\n  bool ZmqAdapterTesterBase ::\n    isConnected_to_Sched(const NATIVE_INT_TYPE portNum)\n  {\n    FW_ASSERT(portNum < this->getNum_to_Sched(), static_cast<AssertArg>(portNum));\n    return this->m_to_Sched[portNum].isConnected();\n  }\n\n  bool ZmqAdapterTesterBase ::\n    isConnected_to_PortsIn(const NATIVE_INT_TYPE portNum)\n  {\n    FW_ASSERT(portNum < this->getNum_to_PortsIn(), static_cast<AssertArg>(portNum));\n    return this->m_to_PortsIn[portNum].isConnected();\n  }\n\n  \/\/ ----------------------------------------------------------------------\n  \/\/ Getters for from ports\n  \/\/ ----------------------------------------------------------------------\n \n  Fw::InputSerializePort *ZmqAdapterTesterBase ::\n    get_from_PortsOut(const NATIVE_INT_TYPE portNum)\n  {\n    FW_ASSERT(portNum < this->getNum_from_PortsOut(),static_cast<AssertArg>(portNum));\n    return &this->m_from_PortsOut[portNum];\n  }\n\n  Fw::InputTlmPort *ZmqAdapterTesterBase ::\n    get_from_Tlm(const NATIVE_INT_TYPE portNum)\n  {\n    FW_ASSERT(portNum < this->getNum_from_Tlm(),static_cast<AssertArg>(portNum));\n    return &this->m_from_Tlm[portNum];\n  }\n\n  Fw::InputTimePort *ZmqAdapterTesterBase ::\n    get_from_Time(const NATIVE_INT_TYPE portNum)\n  {\n    FW_ASSERT(portNum < this->getNum_from_Time(),static_cast<AssertArg>(portNum));\n    return &this->m_from_Time[portNum];\n  }\n\n  Fw::InputLogPort *ZmqAdapterTesterBase ::\n    get_from_Log(const NATIVE_INT_TYPE portNum)\n  {\n    FW_ASSERT(portNum < this->getNum_from_Log(),static_cast<AssertArg>(portNum));\n    return &this->m_from_Log[portNum];\n  }\n\n#if FW_ENABLE_TEXT_LOGGING == 1\n  Fw::InputLogTextPort *ZmqAdapterTesterBase ::\n    get_from_LogText(const NATIVE_INT_TYPE portNum)\n  {\n    FW_ASSERT(portNum < this->getNum_from_LogText(),static_cast<AssertArg>(portNum));\n    return &this->m_from_LogText[portNum];\n  }\n#endif\n\n  \/\/ ----------------------------------------------------------------------\n  \/\/ Static functions for from ports\n  \/\/ ----------------------------------------------------------------------\n\n  void ZmqAdapterTesterBase ::\n    from_PortsOut_static(\n      Fw::PassiveComponentBase *const callComp, \/\/!< The component instance\n      const NATIVE_INT_TYPE portNum, \/\/!< The port number\n      Fw::SerializeBufferBase& Buffer \/\/!< serialized data buffer\n    )\n  {\n    FW_ASSERT(callComp);\n    ZmqAdapterTesterBase* _testerBase = \n      static_cast<ZmqAdapterTesterBase*>(callComp);\n\n    _testerBase->from_PortsOut_handlerBase(\n        portNum,\n        Buffer\n    );\n  }  \n\n  void ZmqAdapterTesterBase ::\n    from_PortsOut_handlerBase(\n        NATIVE_INT_TYPE portNum, \/*!< The port number*\/\n        Fw::SerializeBufferBase &Buffer \/*!< The serialization buffer*\/\n    )\n  {\n    FW_ASSERT(portNum < this->getNum_from_PortsOut(),static_cast<AssertArg>(portNum));\n    this->from_PortsOut_handler(\n        portNum,\n        Buffer\n    );\n  } \n   \n  void ZmqAdapterTesterBase ::\n    from_Tlm_static(\n        Fw::PassiveComponentBase *const component,\n        NATIVE_INT_TYPE portNum,\n        FwChanIdType id,\n        Fw::Time &timeTag,\n        Fw::TlmBuffer &val\n    )\n  {\n    ZmqAdapterTesterBase* _testerBase =\n      static_cast<ZmqAdapterTesterBase*>(component);\n    _testerBase->dispatchTlm(id, timeTag, val);\n  }\n\n  void ZmqAdapterTesterBase ::\n    from_Log_static(\n        Fw::PassiveComponentBase *const component,\n        const NATIVE_INT_TYPE portNum,\n        FwEventIdType id,\n        Fw::Time &timeTag,\n        Fw::LogSeverity severity,\n        Fw::LogBuffer &args\n    )\n  {\n    ZmqAdapterTesterBase* _testerBase =\n      static_cast<ZmqAdapterTesterBase*>(component);\n    _testerBase->dispatchEvents(id, timeTag, severity, args);\n  }\n\n#if FW_ENABLE_TEXT_LOGGING == 1\n  void ZmqAdapterTesterBase ::\n    from_LogText_static(\n        Fw::PassiveComponentBase *const component,\n        const NATIVE_INT_TYPE portNum,\n        FwEventIdType id,\n        Fw::Time &timeTag,\n        Fw::TextLogSeverity severity,\n        Fw::TextLogString &text\n    )\n  {\n    ZmqAdapterTesterBase* _testerBase =\n      static_cast<ZmqAdapterTesterBase*>(component);\n    _testerBase->textLogIn(id,timeTag,severity,text);\n  }\n#endif\n\n  void ZmqAdapterTesterBase ::\n    from_Time_static(\n        Fw::PassiveComponentBase *const component,\n        const NATIVE_INT_TYPE portNum,\n        Fw::Time& time\n    )\n  {\n    ZmqAdapterTesterBase* _testerBase =\n      static_cast<ZmqAdapterTesterBase*>(component);\n    time = _testerBase->m_testTime;\n  }\n\n  \/\/ ----------------------------------------------------------------------\n  \/\/ History \n  \/\/ ----------------------------------------------------------------------\n\n  void ZmqAdapterTesterBase ::\n    clearHistory()\n  {\n    this->clearTlm();\n    this->textLogHistory->clear();\n    this->clearEvents();\n  }\n\n  \/\/ ----------------------------------------------------------------------\n  \/\/ Time\n  \/\/ ----------------------------------------------------------------------\n\n  void ZmqAdapterTesterBase ::\n    setTestTime(const Fw::Time& time)\n  {\n    this->m_testTime = time;\n  }\n\n  \/\/ ----------------------------------------------------------------------\n  \/\/ Telemetry dispatch\n  \/\/ ----------------------------------------------------------------------\n\n  void ZmqAdapterTesterBase ::\n    dispatchTlm(\n        const FwChanIdType id,\n        const Fw::Time &timeTag,\n        Fw::TlmBuffer &val\n    )\n  {\n\n    val.resetDeser();\n\n    const U32 idBase = this->getIdBase();\n    FW_ASSERT(id >= idBase, id, idBase);\n\n    switch (id - idBase) {\n\n      case ZmqAdapterComponentBase::CHANNELID_ZA_BYTESSENT:\n      {\n        U32 arg;\n        const Fw::SerializeStatus _status = val.deserialize(arg);\n        if (_status != Fw::FW_SERIALIZE_OK) {\n          printf(\"Error deserializing ZA_BytesSent: %d\\n\", _status);\n          return;\n        }\n        this->tlmInput_ZA_BytesSent(timeTag, arg);\n        break;\n      }\n\n      case ZmqAdapterComponentBase::CHANNELID_ZA_BYTESRECEIVED:\n      {\n        U32 arg;\n        const Fw::SerializeStatus _status = val.deserialize(arg);\n        if (_status != Fw::FW_SERIALIZE_OK) {\n          printf(\"Error deserializing ZA_BytesReceived: %d\\n\", _status);\n          return;\n        }\n        this->tlmInput_ZA_BytesReceived(timeTag, arg);\n        break;\n      }\n\n      default: {\n        FW_ASSERT(0, id);\n        break;\n      }\n\n    }\n\n  }\n\n  void ZmqAdapterTesterBase ::\n    clearTlm(void)\n  {\n    this->tlmSize = 0;\n    this->tlmHistory_ZA_BytesSent->clear();\n    this->tlmHistory_ZA_BytesReceived->clear();\n  }\n\n  \/\/ ---------------------------------------------------------------------- \n  \/\/ Channel: ZA_BytesSent\n  \/\/ ---------------------------------------------------------------------- \n\n  void ZmqAdapterTesterBase ::\n    tlmInput_ZA_BytesSent(\n        const Fw::Time& timeTag,\n        const U32& val\n    )\n  {\n    TlmEntry_ZA_BytesSent e = { timeTag, val };\n    this->tlmHistory_ZA_BytesSent->push_back(e);\n    ++this->tlmSize;\n  }\n\n  \/\/ ---------------------------------------------------------------------- \n  \/\/ Channel: ZA_BytesReceived\n  \/\/ ---------------------------------------------------------------------- \n\n  void ZmqAdapterTesterBase ::\n    tlmInput_ZA_BytesReceived(\n        const Fw::Time& timeTag,\n        const U32& val\n    )\n  {\n    TlmEntry_ZA_BytesReceived e = { timeTag, val };\n    this->tlmHistory_ZA_BytesReceived->push_back(e);\n    ++this->tlmSize;\n  }\n\n  \/\/ ----------------------------------------------------------------------\n  \/\/ Event dispatch\n  \/\/ ----------------------------------------------------------------------\n\n  void ZmqAdapterTesterBase ::\n    dispatchEvents(\n        const FwEventIdType id,\n        Fw::Time &timeTag,\n        const Fw::LogSeverity severity,\n        Fw::LogBuffer &args\n    )\n  {\n\n    args.resetDeser();\n\n    const U32 idBase = this->getIdBase();\n    FW_ASSERT(id >= idBase, id, idBase);\n    switch (id - idBase) {\n\n      case ZmqAdapterComponentBase::EVENTID_ZA_SERVERCONNECTIONOPENED: \n      {\n\n#if FW_AMPCS_COMPATIBLE\n        \/\/ For AMPCS, decode zero arguments\n        Fw::SerializeStatus _zero_status = Fw::FW_SERIALIZE_OK;\n        U8 _noArgs;\n        _zero_status = args.deserialize(_noArgs);\n        FW_ASSERT(\n            _zero_status == Fw::FW_SERIALIZE_OK,\n            static_cast<AssertArg>(_zero_status)\n        );\n#endif    \n        this->logIn_ACTIVITY_HI_ZA_ServerConnectionOpened();\n\n        break;\n\n      }\n\n      default: {\n        FW_ASSERT(0, id);\n        break;\n      }\n\n    }\n\n  }\n\n  void ZmqAdapterTesterBase ::\n    clearEvents(void)\n  {\n    this->eventsSize = 0;\n    this->eventsSize_ZA_ServerConnectionOpened = 0;\n  }\n\n#if FW_ENABLE_TEXT_LOGGING\n\n  \/\/ ----------------------------------------------------------------------\n  \/\/ Text events \n  \/\/ ----------------------------------------------------------------------\n\n  void ZmqAdapterTesterBase ::\n    textLogIn(\n        const U32 id,\n        Fw::Time &timeTag,\n        const Fw::TextLogSeverity severity,\n        const Fw::TextLogString &text\n    )\n  {\n    TextLogEntry e = { id, timeTag, severity, text };\n    textLogHistory->push_back(e);\n  }\n\n  void ZmqAdapterTesterBase ::\n    printTextLogHistoryEntry(\n        const TextLogEntry& e,\n        FILE* file\n    )\n  {\n    const char *severityString = \"UNKNOWN\";\n    switch (e.severity) {\n      case Fw::LOG_FATAL:\n        severityString = \"FATAL\";\n        break;\n      case Fw::LOG_WARNING_HI:\n        severityString = \"WARNING_HI\";\n        break;\n      case Fw::LOG_WARNING_LO:\n        severityString = \"WARNING_LO\";\n        break;\n      case Fw::LOG_COMMAND:\n        severityString = \"COMMAND\";\n        break;\n      case Fw::LOG_ACTIVITY_HI:\n        severityString = \"ACTIVITY_HI\";\n        break;\n      case Fw::LOG_ACTIVITY_LO:\n        severityString = \"ACTIVITY_LO\";\n        break;\n      case Fw::LOG_DIAGNOSTIC:\n       severityString = \"DIAGNOSTIC\";\n        break;\n      default:\n        severityString = \"SEVERITY ERROR\";\n        break;\n    }\n\n    fprintf(\n        file,\n        \"EVENT: (%d) (%d:%d,%d) %s: %s\\n\",\n        e.id,\n        const_cast<TextLogEntry&>(e).timeTag.getTimeBase(),\n        const_cast<TextLogEntry&>(e).timeTag.getSeconds(),\n        const_cast<TextLogEntry&>(e).timeTag.getUSeconds(),\n        severityString,\n        e.text.toChar()\n    );\n\n  }\n\n  void ZmqAdapterTesterBase ::\n    printTextLogHistory(FILE *file) \n  {\n    for (U32 i = 0; i < this->textLogHistory->size(); ++i) {\n      this->printTextLogHistoryEntry(\n          this->textLogHistory->at(i), \n          file\n      );\n    }\n  }\n\n#endif\n\n  \/\/ ----------------------------------------------------------------------\n  \/\/ Event: ZA_ServerConnectionOpened \n  \/\/ ----------------------------------------------------------------------\n\n  void ZmqAdapterTesterBase ::\n    logIn_ACTIVITY_HI_ZA_ServerConnectionOpened(\n        void\n    )\n  {\n    ++this->eventsSize_ZA_ServerConnectionOpened;\n    ++this->eventsSize;\n  }\n\n} \/\/ end namespace Zmq\n","avg_line_length":26.137755102,"max_line_length":86,"alphanum_fraction":0.5656841694,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":366247,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Copyright (c) 2015-2019 The Khronos Group Inc.\n * Copyright (c) 2015-2019 Valve Corporation\n * Copyright (c) 2015-2019 LunarG, Inc.\n * Copyright (c) 2015-2019 Google, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Author: Chia-I Wu <olvaffe@gmail.com>\n * Author: Chris Forbes <chrisf@ijw.co.nz>\n * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>\n * Author: Mark Lobodzinski <mark@lunarg.com>\n * Author: Mike Stroyan <mike@LunarG.com>\n * Author: Tobin Ehlis <tobine@google.com>\n * Author: Tony Barbour <tony@LunarG.com>\n * Author: Cody Northrop <cnorthrop@google.com>\n * Author: Dave Houlton <daveh@lunarg.com>\n * Author: Jeremy Kniager <jeremyk@lunarg.com>\n * Author: Shannon McPherson <shannon@lunarg.com>\n * Author: John Zulauf <jzulauf@lunarg.com>\n *\/\n\n#include \"cast_utils.h\"\n#include \"layer_validation_tests.h\"\n\nTEST_F(VkLayerTest, BufferExtents) {\n    TEST_DESCRIPTION(\"Perform copies across a buffer, provoking out-of-range errors.\");\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    const VkDeviceSize buffer_size = 2048;\n\n    VkBufferObj buffer_one;\n    VkBufferObj buffer_two;\n    VkMemoryPropertyFlags reqs = 0;\n    buffer_one.init_as_src_and_dst(*m_device, buffer_size, reqs);\n    buffer_two.init_as_src_and_dst(*m_device, buffer_size, reqs);\n\n    m_commandBuffer->begin();\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdCopyBuffer-srcOffset-00113\");\n    VkBufferCopy copy_info = {4096, 256, 256};\n    vk::CmdCopyBuffer(m_commandBuffer->handle(), buffer_one.handle(), buffer_two.handle(), 1, &copy_info);\n    m_errorMonitor->VerifyFound();\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdCopyBuffer-dstOffset-00114\");\n    copy_info = {256, 4096, 256};\n    vk::CmdCopyBuffer(m_commandBuffer->handle(), buffer_one.handle(), buffer_two.handle(), 1, &copy_info);\n    m_errorMonitor->VerifyFound();\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdCopyBuffer-size-00115\");\n    copy_info = {1024, 256, 1280};\n    vk::CmdCopyBuffer(m_commandBuffer->handle(), buffer_one.handle(), buffer_two.handle(), 1, &copy_info);\n    m_errorMonitor->VerifyFound();\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdCopyBuffer-size-00116\");\n    copy_info = {256, 1024, 1280};\n    vk::CmdCopyBuffer(m_commandBuffer->handle(), buffer_one.handle(), buffer_two.handle(), 1, &copy_info);\n    m_errorMonitor->VerifyFound();\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdCopyBuffer-pRegions-00117\");\n    copy_info = {256, 512, 512};\n    vk::CmdCopyBuffer(m_commandBuffer->handle(), buffer_two.handle(), buffer_two.handle(), 1, &copy_info);\n    m_errorMonitor->VerifyFound();\n\n    m_commandBuffer->end();\n}\n\nTEST_F(VkLayerTest, MirrorClampToEdgeNotEnabled) {\n    TEST_DESCRIPTION(\"Validation should catch using CLAMP_TO_EDGE addressing mode if the extension is not enabled.\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkSamplerCreateInfo-addressModeU-01079\");\n    VkSampler sampler = VK_NULL_HANDLE;\n    VkSamplerCreateInfo sampler_info = SafeSaneSamplerCreateInfo();\n    \/\/ Set the modes to cause the error\n    sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE;\n    sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE;\n    sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE;\n\n    vk::CreateSampler(m_device->device(), &sampler_info, NULL, &sampler);\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, AnisotropyFeatureDisabled) {\n    TEST_DESCRIPTION(\"Validation should check anisotropy parameters are correct with samplerAnisotropy disabled.\");\n\n    \/\/ Determine if required device features are available\n    VkPhysicalDeviceFeatures device_features = {};\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    ASSERT_NO_FATAL_FAILURE(GetPhysicalDeviceFeatures(&device_features));\n    device_features.samplerAnisotropy = VK_FALSE;  \/\/ force anisotropy off\n    ASSERT_NO_FATAL_FAILURE(InitState(&device_features));\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkSamplerCreateInfo-anisotropyEnable-01070\");\n    VkSamplerCreateInfo sampler_info = SafeSaneSamplerCreateInfo();\n    \/\/ With the samplerAnisotropy disable, the sampler must not enable it.\n    sampler_info.anisotropyEnable = VK_TRUE;\n    VkSampler sampler = VK_NULL_HANDLE;\n\n    VkResult err;\n    err = vk::CreateSampler(m_device->device(), &sampler_info, NULL, &sampler);\n    m_errorMonitor->VerifyFound();\n    if (VK_SUCCESS == err) {\n        vk::DestroySampler(m_device->device(), sampler, NULL);\n    }\n    sampler = VK_NULL_HANDLE;\n}\n\nTEST_F(VkLayerTest, AnisotropyFeatureEnabled) {\n    TEST_DESCRIPTION(\"Validation must check several conditions that apply only when Anisotropy is enabled.\");\n\n    \/\/ Determine if required device features are available\n    VkPhysicalDeviceFeatures device_features = {};\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    ASSERT_NO_FATAL_FAILURE(GetPhysicalDeviceFeatures(&device_features));\n\n    \/\/ These tests require that the device support anisotropic filtering\n    if (VK_TRUE != device_features.samplerAnisotropy) {\n        printf(\"%s Test requires unsupported samplerAnisotropy feature. Skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    bool cubic_support = false;\n    if (DeviceExtensionSupported(gpu(), nullptr, \"VK_IMG_filter_cubic\")) {\n        m_device_extension_names.push_back(\"VK_IMG_filter_cubic\");\n        cubic_support = true;\n    }\n\n    VkSamplerCreateInfo sampler_info_ref = SafeSaneSamplerCreateInfo();\n    sampler_info_ref.anisotropyEnable = VK_TRUE;\n    VkSamplerCreateInfo sampler_info = sampler_info_ref;\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    \/\/ maxAnisotropy out-of-bounds low.\n    sampler_info.maxAnisotropy = NearestSmaller(1.0F);\n    CreateSamplerTest(*this, &sampler_info, \"VUID-VkSamplerCreateInfo-anisotropyEnable-01071\");\n    sampler_info.maxAnisotropy = sampler_info_ref.maxAnisotropy;\n\n    \/\/ maxAnisotropy out-of-bounds high.\n    sampler_info.maxAnisotropy = NearestGreater(m_device->phy().properties().limits.maxSamplerAnisotropy);\n    CreateSamplerTest(*this, &sampler_info, \"VUID-VkSamplerCreateInfo-anisotropyEnable-01071\");\n    sampler_info.maxAnisotropy = sampler_info_ref.maxAnisotropy;\n\n    \/\/ Both anisotropy and unnormalized coords enabled\n    sampler_info.unnormalizedCoordinates = VK_TRUE;\n    \/\/ If unnormalizedCoordinates is VK_TRUE, minLod and maxLod must be zero\n    sampler_info.minLod = 0;\n    sampler_info.maxLod = 0;\n    CreateSamplerTest(*this, &sampler_info, \"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01076\");\n    sampler_info.unnormalizedCoordinates = sampler_info_ref.unnormalizedCoordinates;\n\n    \/\/ Both anisotropy and cubic filtering enabled\n    if (cubic_support) {\n        sampler_info.minFilter = VK_FILTER_CUBIC_IMG;\n        CreateSamplerTest(*this, &sampler_info, \"VUID-VkSamplerCreateInfo-magFilter-01081\");\n        sampler_info.minFilter = sampler_info_ref.minFilter;\n\n        sampler_info.magFilter = VK_FILTER_CUBIC_IMG;\n        CreateSamplerTest(*this, &sampler_info, \"VUID-VkSamplerCreateInfo-magFilter-01081\");\n        sampler_info.magFilter = sampler_info_ref.magFilter;\n    } else {\n        printf(\"%s Test requires unsupported extension \\\"VK_IMG_filter_cubic\\\". Skipped.\\n\", kSkipPrefix);\n    }\n}\n\nTEST_F(VkLayerTest, UnnormalizedCoordinatesEnabled) {\n    TEST_DESCRIPTION(\"Validate restrictions on sampler parameters when unnormalizedCoordinates is true.\");\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    VkSamplerCreateInfo sampler_info_ref = SafeSaneSamplerCreateInfo();\n    sampler_info_ref.unnormalizedCoordinates = VK_TRUE;\n    sampler_info_ref.minLod = 0.0f;\n    sampler_info_ref.maxLod = 0.0f;\n    VkSamplerCreateInfo sampler_info = sampler_info_ref;\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    \/\/ min and mag filters must be the same\n    sampler_info.minFilter = VK_FILTER_NEAREST;\n    sampler_info.magFilter = VK_FILTER_LINEAR;\n    CreateSamplerTest(*this, &sampler_info, \"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01072\");\n    std::swap(sampler_info.minFilter, sampler_info.magFilter);\n    CreateSamplerTest(*this, &sampler_info, \"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01072\");\n    sampler_info = sampler_info_ref;\n\n    \/\/ mipmapMode must be NEAREST\n    sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;\n    CreateSamplerTest(*this, &sampler_info, \"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01073\");\n    sampler_info = sampler_info_ref;\n\n    \/\/ minlod and maxlod must be zero\n    sampler_info.maxLod = 3.14159f;\n    CreateSamplerTest(*this, &sampler_info, \"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01074\");\n    sampler_info.minLod = 2.71828f;\n    CreateSamplerTest(*this, &sampler_info, \"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01074\");\n    sampler_info = sampler_info_ref;\n\n    \/\/ addressModeU and addressModeV must both be CLAMP_TO_EDGE or CLAMP_TO_BORDER\n    \/\/ checks all 12 invalid combinations out of 16 total combinations\n    const std::array<VkSamplerAddressMode, 4> kAddressModes = {{\n        VK_SAMPLER_ADDRESS_MODE_REPEAT,\n        VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT,\n        VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,\n        VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,\n    }};\n    for (const auto umode : kAddressModes) {\n        for (const auto vmode : kAddressModes) {\n            if ((umode != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && umode != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) ||\n                (vmode != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && vmode != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER)) {\n                sampler_info.addressModeU = umode;\n                sampler_info.addressModeV = vmode;\n                CreateSamplerTest(*this, &sampler_info, \"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075\");\n            }\n        }\n    }\n    sampler_info = sampler_info_ref;\n\n    \/\/ VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01076 is tested in AnisotropyFeatureEnabled above\n    \/\/ Since it requires checking\/enabling the anisotropic filtering feature, it's easier to do it\n    \/\/ with the other anisotropic tests.\n\n    \/\/ compareEnable must be VK_FALSE\n    sampler_info.compareEnable = VK_TRUE;\n    CreateSamplerTest(*this, &sampler_info, \"VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01077\");\n    sampler_info = sampler_info_ref;\n}\n\nTEST_F(VkLayerTest, UpdateBufferAlignment) {\n    TEST_DESCRIPTION(\"Check alignment parameters for vkCmdUpdateBuffer\");\n    uint32_t updateData[] = {1, 2, 3, 4, 5, 6, 7, 8};\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkMemoryPropertyFlags reqs = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;\n    VkBufferObj buffer;\n    buffer.init_as_dst(*m_device, (VkDeviceSize)20, reqs);\n\n    m_commandBuffer->begin();\n    \/\/ Introduce failure by using dstOffset that is not multiple of 4\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \" is not a multiple of 4\");\n    m_commandBuffer->UpdateBuffer(buffer.handle(), 1, 4, updateData);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Introduce failure by using dataSize that is not multiple of 4\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \" is not a multiple of 4\");\n    m_commandBuffer->UpdateBuffer(buffer.handle(), 0, 6, updateData);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Introduce failure by using dataSize that is < 0\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"must be greater than zero and less than or equal to 65536\");\n    m_commandBuffer->UpdateBuffer(buffer.handle(), 0, (VkDeviceSize)-44, updateData);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Introduce failure by using dataSize that is > 65536\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"must be greater than zero and less than or equal to 65536\");\n    m_commandBuffer->UpdateBuffer(buffer.handle(), 0, (VkDeviceSize)80000, updateData);\n    m_errorMonitor->VerifyFound();\n\n    m_commandBuffer->end();\n}\n\nTEST_F(VkLayerTest, FillBufferAlignment) {\n    TEST_DESCRIPTION(\"Check alignment parameters for vkCmdFillBuffer\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkMemoryPropertyFlags reqs = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;\n    VkBufferObj buffer;\n    buffer.init_as_dst(*m_device, (VkDeviceSize)20, reqs);\n\n    m_commandBuffer->begin();\n\n    \/\/ Introduce failure by using dstOffset that is not multiple of 4\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \" is not a multiple of 4\");\n    m_commandBuffer->FillBuffer(buffer.handle(), 1, 4, 0x11111111);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Introduce failure by using size that is not multiple of 4\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \" is not a multiple of 4\");\n    m_commandBuffer->FillBuffer(buffer.handle(), 0, 6, 0x11111111);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Introduce failure by using size that is zero\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"must be greater than zero\");\n    m_commandBuffer->FillBuffer(buffer.handle(), 0, 0, 0x11111111);\n    m_errorMonitor->VerifyFound();\n\n    m_commandBuffer->end();\n}\n\nTEST_F(VkLayerTest, SparseBindingImageBufferCreate) {\n    TEST_DESCRIPTION(\"Create buffer\/image with sparse attributes but without the sparse_binding bit set\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkBufferCreateInfo buf_info = {};\n    buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;\n    buf_info.pNext = NULL;\n    buf_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;\n    buf_info.size = 2048;\n    buf_info.queueFamilyIndexCount = 0;\n    buf_info.pQueueFamilyIndices = NULL;\n    buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n\n    if (m_device->phy().features().sparseResidencyBuffer) {\n        buf_info.flags = VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT;\n        CreateBufferTest(*this, &buf_info, \"VUID-VkBufferCreateInfo-flags-00918\");\n    } else {\n        printf(\"%s Test requires unsupported sparseResidencyBuffer feature. Skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    if (m_device->phy().features().sparseResidencyAliased) {\n        buf_info.flags = VK_BUFFER_CREATE_SPARSE_ALIASED_BIT;\n        CreateBufferTest(*this, &buf_info, \"VUID-VkBufferCreateInfo-flags-00918\");\n    } else {\n        printf(\"%s Test requires unsupported sparseResidencyAliased feature. Skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = VK_FORMAT_R8G8B8A8_UNORM;\n    image_create_info.extent.width = 512;\n    image_create_info.extent.height = 64;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;\n    image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n    image_create_info.queueFamilyIndexCount = 0;\n    image_create_info.pQueueFamilyIndices = NULL;\n    image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n\n    if (m_device->phy().features().sparseResidencyImage2D) {\n        image_create_info.flags = VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT;\n        CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-flags-00987\");\n    } else {\n        printf(\"%s Test requires unsupported sparseResidencyImage2D feature. Skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    if (m_device->phy().features().sparseResidencyAliased) {\n        image_create_info.flags = VK_IMAGE_CREATE_SPARSE_ALIASED_BIT;\n        CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-flags-00987\");\n    } else {\n        printf(\"%s Test requires unsupported sparseResidencyAliased feature. Skipped.\\n\", kSkipPrefix);\n        return;\n    }\n}\n\nTEST_F(VkLayerTest, SparseResidencyImageCreateUnsupportedTypes) {\n    TEST_DESCRIPTION(\"Create images with sparse residency with unsupported types\");\n\n    \/\/ Determine which device feature are available\n    VkPhysicalDeviceFeatures device_features = {};\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    ASSERT_NO_FATAL_FAILURE(GetPhysicalDeviceFeatures(&device_features));\n\n    \/\/ Mask out device features we don't want and initialize device state\n    device_features.sparseResidencyImage2D = VK_FALSE;\n    device_features.sparseResidencyImage3D = VK_FALSE;\n    ASSERT_NO_FATAL_FAILURE(InitState(&device_features));\n\n    if (!m_device->phy().features().sparseBinding) {\n        printf(\"%s Test requires unsupported sparseBinding feature. Skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_1D;\n    image_create_info.format = VK_FORMAT_R8G8B8A8_UNORM;\n    image_create_info.extent.width = 512;\n    image_create_info.extent.height = 1;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;\n    image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n    image_create_info.queueFamilyIndexCount = 0;\n    image_create_info.pQueueFamilyIndices = NULL;\n    image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n    image_create_info.flags = VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT | VK_BUFFER_CREATE_SPARSE_BINDING_BIT;\n\n    \/\/ 1D image w\/ sparse residency is an error\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-imageType-00970\");\n\n    \/\/ 2D image w\/ sparse residency when feature isn't available\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.extent.height = 64;\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-imageType-00971\");\n\n    \/\/ 3D image w\/ sparse residency when feature isn't available\n    image_create_info.imageType = VK_IMAGE_TYPE_3D;\n    image_create_info.extent.depth = 8;\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-imageType-00972\");\n}\n\nTEST_F(VkLayerTest, SparseResidencyImageCreateUnsupportedSamples) {\n    TEST_DESCRIPTION(\"Create images with sparse residency with unsupported tiling or sample counts\");\n\n    \/\/ Determine which device feature are available\n    VkPhysicalDeviceFeatures device_features = {};\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    ASSERT_NO_FATAL_FAILURE(GetPhysicalDeviceFeatures(&device_features));\n\n    \/\/ These tests require that the device support sparse residency for 2D images\n    if (VK_TRUE != device_features.sparseResidencyImage2D) {\n        printf(\"%s Test requires unsupported SparseResidencyImage2D feature. Skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    \/\/ Mask out device features we don't want and initialize device state\n    device_features.sparseResidency2Samples = VK_FALSE;\n    device_features.sparseResidency4Samples = VK_FALSE;\n    device_features.sparseResidency8Samples = VK_FALSE;\n    device_features.sparseResidency16Samples = VK_FALSE;\n    ASSERT_NO_FATAL_FAILURE(InitState(&device_features));\n\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = VK_FORMAT_R8G8B8A8_UNORM;\n    image_create_info.extent.width = 64;\n    image_create_info.extent.height = 64;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_LINEAR;\n    image_create_info.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;\n    image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n    image_create_info.queueFamilyIndexCount = 0;\n    image_create_info.pQueueFamilyIndices = NULL;\n    image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n    image_create_info.flags = VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT | VK_BUFFER_CREATE_SPARSE_BINDING_BIT;\n\n    \/\/ 2D image w\/ sparse residency and linear tiling is an error\n    CreateImageTest(*this, &image_create_info,\n                    \"VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT then image tiling of VK_IMAGE_TILING_LINEAR is not supported\");\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n\n    \/\/ Multi-sample image w\/ sparse residency when feature isn't available (4 flavors)\n    image_create_info.samples = VK_SAMPLE_COUNT_2_BIT;\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-imageType-00973\");\n\n    image_create_info.samples = VK_SAMPLE_COUNT_4_BIT;\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-imageType-00974\");\n\n    image_create_info.samples = VK_SAMPLE_COUNT_8_BIT;\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-imageType-00975\");\n\n    image_create_info.samples = VK_SAMPLE_COUNT_16_BIT;\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-imageType-00976\");\n}\n\nTEST_F(VkLayerTest, InvalidMemoryMapping) {\n    TEST_DESCRIPTION(\"Attempt to map memory in a number of incorrect ways\");\n    VkResult err;\n    bool pass;\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkBuffer buffer;\n    VkDeviceMemory mem;\n    VkMemoryRequirements mem_reqs;\n\n    const VkDeviceSize atom_size = m_device->props.limits.nonCoherentAtomSize;\n\n    VkBufferCreateInfo buf_info = {};\n    buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;\n    buf_info.pNext = NULL;\n    buf_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;\n    buf_info.size = 256;\n    buf_info.queueFamilyIndexCount = 0;\n    buf_info.pQueueFamilyIndices = NULL;\n    buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n    buf_info.flags = 0;\n    err = vk::CreateBuffer(m_device->device(), &buf_info, NULL, &buffer);\n    ASSERT_VK_SUCCESS(err);\n\n    vk::GetBufferMemoryRequirements(m_device->device(), buffer, &mem_reqs);\n    VkMemoryAllocateInfo alloc_info = {};\n    alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n    alloc_info.pNext = NULL;\n    alloc_info.memoryTypeIndex = 0;\n\n    \/\/ Ensure memory is big enough for both bindings\n    static const VkDeviceSize allocation_size = 0x10000;\n    alloc_info.allocationSize = allocation_size;\n    pass = m_device->phy().set_memory_type(mem_reqs.memoryTypeBits, &alloc_info, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);\n    if (!pass) {\n        printf(\"%s Failed to set memory type.\\n\", kSkipPrefix);\n        vk::DestroyBuffer(m_device->device(), buffer, NULL);\n        return;\n    }\n    err = vk::AllocateMemory(m_device->device(), &alloc_info, NULL, &mem);\n    ASSERT_VK_SUCCESS(err);\n\n    uint8_t *pData;\n    \/\/ Attempt to map memory size 0 is invalid\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VkMapMemory: Attempting to map memory range of size zero\");\n    err = vk::MapMemory(m_device->device(), mem, 0, 0, 0, (void **)&pData);\n    m_errorMonitor->VerifyFound();\n    \/\/ Map memory twice\n    err = vk::MapMemory(m_device->device(), mem, 0, mem_reqs.size, 0, (void **)&pData);\n    ASSERT_VK_SUCCESS(err);\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"UNASSIGNED-CoreValidation-MemTrack-InvalidMap\");\n    err = vk::MapMemory(m_device->device(), mem, 0, mem_reqs.size, 0, (void **)&pData);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Unmap the memory to avoid re-map error\n    vk::UnmapMemory(m_device->device(), mem);\n    \/\/ overstep allocation with VK_WHOLE_SIZE\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \" with size of VK_WHOLE_SIZE oversteps total array size 0x\");\n    err = vk::MapMemory(m_device->device(), mem, allocation_size + 1, VK_WHOLE_SIZE, 0, (void **)&pData);\n    m_errorMonitor->VerifyFound();\n    \/\/ overstep allocation w\/o VK_WHOLE_SIZE\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \" oversteps total array size 0x\");\n    err = vk::MapMemory(m_device->device(), mem, 1, allocation_size, 0, (void **)&pData);\n    m_errorMonitor->VerifyFound();\n    \/\/ Now error due to unmapping memory that's not mapped\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"Unmapping Memory without memory being mapped: \");\n    vk::UnmapMemory(m_device->device(), mem);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Now map memory and cause errors due to flushing invalid ranges\n    err = vk::MapMemory(m_device->device(), mem, 4 * atom_size, VK_WHOLE_SIZE, 0, (void **)&pData);\n    ASSERT_VK_SUCCESS(err);\n    VkMappedMemoryRange mmr = {};\n    mmr.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;\n    mmr.memory = mem;\n    mmr.offset = atom_size;  \/\/ Error b\/c offset less than offset of mapped mem\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkMappedMemoryRange-size-00685\");\n    vk::FlushMappedMemoryRanges(m_device->device(), 1, &mmr);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Now flush range that oversteps mapped range\n    vk::UnmapMemory(m_device->device(), mem);\n    err = vk::MapMemory(m_device->device(), mem, 0, 4 * atom_size, 0, (void **)&pData);\n    ASSERT_VK_SUCCESS(err);\n    mmr.offset = atom_size;\n    mmr.size = 4 * atom_size;  \/\/ Flushing bounds exceed mapped bounds\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkMappedMemoryRange-size-00685\");\n    vk::FlushMappedMemoryRanges(m_device->device(), 1, &mmr);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Now flush range with VK_WHOLE_SIZE that oversteps offset\n    vk::UnmapMemory(m_device->device(), mem);\n    err = vk::MapMemory(m_device->device(), mem, 2 * atom_size, 4 * atom_size, 0, (void **)&pData);\n    ASSERT_VK_SUCCESS(err);\n    mmr.offset = atom_size;\n    mmr.size = VK_WHOLE_SIZE;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkMappedMemoryRange-size-00686\");\n    vk::FlushMappedMemoryRanges(m_device->device(), 1, &mmr);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Some platforms have an atomsize of 1 which makes the test meaningless\n    if (atom_size > 3) {\n        \/\/ Now with an offset NOT a multiple of the device limit\n        vk::UnmapMemory(m_device->device(), mem);\n        err = vk::MapMemory(m_device->device(), mem, 0, 4 * atom_size, 0, (void **)&pData);\n        ASSERT_VK_SUCCESS(err);\n        mmr.offset = 3;  \/\/ Not a multiple of atom_size\n        mmr.size = VK_WHOLE_SIZE;\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkMappedMemoryRange-offset-00687\");\n        vk::FlushMappedMemoryRanges(m_device->device(), 1, &mmr);\n        m_errorMonitor->VerifyFound();\n\n        \/\/ Now with a size NOT a multiple of the device limit\n        vk::UnmapMemory(m_device->device(), mem);\n        err = vk::MapMemory(m_device->device(), mem, 0, 4 * atom_size, 0, (void **)&pData);\n        ASSERT_VK_SUCCESS(err);\n        mmr.offset = atom_size;\n        mmr.size = 2 * atom_size + 1;  \/\/ Not a multiple of atom_size\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkMappedMemoryRange-size-01390\");\n        vk::FlushMappedMemoryRanges(m_device->device(), 1, &mmr);\n        m_errorMonitor->VerifyFound();\n    }\n\n    pass = m_device->phy().set_memory_type(mem_reqs.memoryTypeBits, &alloc_info, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,\n                                           VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);\n    if (!pass) {\n        printf(\"%s Failed to set memory type.\\n\", kSkipPrefix);\n        vk::FreeMemory(m_device->device(), mem, NULL);\n        vk::DestroyBuffer(m_device->device(), buffer, NULL);\n        return;\n    }\n    \/\/ TODO : If we can get HOST_VISIBLE w\/o HOST_COHERENT we can test cases of\n    \/\/  kVUID_Core_MemTrack_InvalidMap in validateAndCopyNoncoherentMemoryToDriver()\n\n    vk::DestroyBuffer(m_device->device(), buffer, NULL);\n    vk::FreeMemory(m_device->device(), mem, NULL);\n}\n\nTEST_F(VkLayerTest, MapMemWithoutHostVisibleBit) {\n    TEST_DESCRIPTION(\"Allocate memory that is not mappable and then attempt to map it.\");\n    VkResult err;\n    bool pass;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkMapMemory-memory-00682\");\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkMemoryAllocateInfo mem_alloc = {};\n    mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n    mem_alloc.pNext = NULL;\n    mem_alloc.allocationSize = 1024;\n\n    pass = m_device->phy().set_memory_type(0xFFFFFFFF, &mem_alloc, 0, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);\n    if (!pass) {  \/\/ If we can't find any unmappable memory this test doesn't\n                  \/\/ make sense\n        printf(\"%s No unmappable memory types found, skipping test\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkDeviceMemory mem;\n    err = vk::AllocateMemory(m_device->device(), &mem_alloc, NULL, &mem);\n    ASSERT_VK_SUCCESS(err);\n\n    void *mappedAddress = NULL;\n    err = vk::MapMemory(m_device->device(), mem, 0, VK_WHOLE_SIZE, 0, &mappedAddress);\n    m_errorMonitor->VerifyFound();\n\n    vk::FreeMemory(m_device->device(), mem, NULL);\n}\n\nTEST_F(VkLayerTest, RebindMemory) {\n    VkResult err;\n    bool pass;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindImageMemory-image-01044\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    \/\/ Create an image, allocate memory, free it, and then try to bind it\n    VkImage image;\n    VkDeviceMemory mem1;\n    VkDeviceMemory mem2;\n    VkMemoryRequirements mem_reqs;\n\n    const VkFormat tex_format = VK_FORMAT_B8G8R8A8_UNORM;\n    const int32_t tex_width = 32;\n    const int32_t tex_height = 32;\n\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = tex_format;\n    image_create_info.extent.width = tex_width;\n    image_create_info.extent.height = tex_height;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT;\n    image_create_info.flags = 0;\n\n    VkMemoryAllocateInfo mem_alloc = {};\n    mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n    mem_alloc.pNext = NULL;\n    mem_alloc.allocationSize = 0;\n    mem_alloc.memoryTypeIndex = 0;\n\n    \/\/ Introduce failure, do NOT set memProps to\n    \/\/ VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT\n    mem_alloc.memoryTypeIndex = 1;\n    err = vk::CreateImage(m_device->device(), &image_create_info, NULL, &image);\n    ASSERT_VK_SUCCESS(err);\n\n    vk::GetImageMemoryRequirements(m_device->device(), image, &mem_reqs);\n\n    mem_alloc.allocationSize = mem_reqs.size;\n    pass = m_device->phy().set_memory_type(mem_reqs.memoryTypeBits, &mem_alloc, 0);\n    ASSERT_TRUE(pass);\n\n    \/\/ allocate 2 memory objects\n    err = vk::AllocateMemory(m_device->device(), &mem_alloc, NULL, &mem1);\n    ASSERT_VK_SUCCESS(err);\n    err = vk::AllocateMemory(m_device->device(), &mem_alloc, NULL, &mem2);\n    ASSERT_VK_SUCCESS(err);\n\n    \/\/ Bind first memory object to Image object\n    err = vk::BindImageMemory(m_device->device(), image, mem1, 0);\n    ASSERT_VK_SUCCESS(err);\n\n    \/\/ Introduce validation failure, try to bind a different memory object to\n    \/\/ the same image object\n    err = vk::BindImageMemory(m_device->device(), image, mem2, 0);\n\n    m_errorMonitor->VerifyFound();\n\n    vk::DestroyImage(m_device->device(), image, NULL);\n    vk::FreeMemory(m_device->device(), mem1, NULL);\n    vk::FreeMemory(m_device->device(), mem2, NULL);\n}\n\nTEST_F(VkLayerTest, QueryMemoryCommitmentWithoutLazyProperty) {\n    TEST_DESCRIPTION(\"Attempt to query memory commitment on memory without lazy allocation\");\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    auto image_ci = vk_testing::Image::create_info();\n    image_ci.imageType = VK_IMAGE_TYPE_2D;\n    image_ci.format = VK_FORMAT_B8G8R8A8_UNORM;\n    image_ci.extent.width = 32;\n    image_ci.extent.height = 32;\n    image_ci.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_ci.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;\n    VkImageObj image(m_device);\n    image.init_no_mem(*m_device, image_ci);\n\n    auto mem_reqs = image.memory_requirements();\n    \/\/ memory_type_index is set to 0 here, but is set properly below\n    auto image_alloc_info = vk_testing::DeviceMemory::alloc_info(mem_reqs.size, 0);\n\n    bool pass;\n    \/\/ the last argument is the \"forbid\" argument for set_memory_type, disallowing\n    \/\/ that particular memory type rather than requiring it\n    pass = m_device->phy().set_memory_type(mem_reqs.memoryTypeBits, &image_alloc_info, 0, VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT);\n    if (!pass) {\n        printf(\"%s Failed to set memory type.\\n\", kSkipPrefix);\n        return;\n    }\n    vk_testing::DeviceMemory mem;\n    mem.init(*m_device, image_alloc_info);\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkGetDeviceMemoryCommitment-memory-00690\");\n    VkDeviceSize size;\n    vk::GetDeviceMemoryCommitment(m_device->device(), mem.handle(), &size);\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, InvalidUsageBits) {\n    TEST_DESCRIPTION(\n        \"Specify wrong usage for image then create conflicting view of image Initialize buffer with wrong usage then perform copy \"\n        \"expecting errors from both the image and the buffer (2 calls)\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    auto format = FindSupportedDepthStencilFormat(gpu());\n    if (!format) {\n        printf(\"%s No Depth + Stencil format found. Skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkImageObj image(m_device);\n    \/\/ Initialize image with transfer source usage\n    image.Init(128, 128, 1, format, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_IMAGE_TILING_OPTIMAL, 0);\n    ASSERT_TRUE(image.initialized());\n\n    VkImageView dsv;\n    VkImageViewCreateInfo dsvci = {};\n    dsvci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    dsvci.image = image.handle();\n    dsvci.viewType = VK_IMAGE_VIEW_TYPE_2D;\n    dsvci.format = format;\n    dsvci.subresourceRange.layerCount = 1;\n    dsvci.subresourceRange.baseMipLevel = 0;\n    dsvci.subresourceRange.levelCount = 1;\n    dsvci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;\n\n    \/\/ Create a view with depth \/ stencil aspect for image with different usage\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"UNASSIGNED-CoreValidation-MemTrack-InvalidUsageFlag\");\n    vk::CreateImageView(m_device->device(), &dsvci, NULL, &dsv);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Initialize buffer with TRANSFER_DST usage\n    VkBufferObj buffer;\n    VkMemoryPropertyFlags reqs = 0;\n    buffer.init_as_dst(*m_device, 128 * 128, reqs);\n    VkBufferImageCopy region = {};\n    region.bufferRowLength = 128;\n    region.bufferImageHeight = 128;\n    region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;\n    region.imageSubresource.layerCount = 1;\n    region.imageExtent.height = 16;\n    region.imageExtent.width = 16;\n    region.imageExtent.depth = 1;\n\n    \/\/ Buffer usage not set to TRANSFER_SRC and image usage not set to TRANSFER_DST\n    m_commandBuffer->begin();\n\n    \/\/ two separate errors from this call:\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdCopyBufferToImage-dstImage-00177\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdCopyBufferToImage-srcBuffer-00174\");\n\n    vk::CmdCopyBufferToImage(m_commandBuffer->handle(), buffer.handle(), image.handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1,\n                             &region);\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, CopyBufferToCompressedImage) {\n    TEST_DESCRIPTION(\"Copy buffer to compressed image when buffer is larger than image.\");\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    \/\/ Verify format support\n    if (!ImageFormatAndFeaturesSupported(gpu(), VK_FORMAT_BC1_RGBA_SRGB_BLOCK, VK_IMAGE_TILING_OPTIMAL,\n                                         VK_FORMAT_FEATURE_TRANSFER_DST_BIT_KHR)) {\n        printf(\"%s Required formats\/features not supported - CopyBufferToCompressedImage skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkImageObj width_image(m_device);\n    VkImageObj height_image(m_device);\n    VkBufferObj buffer;\n    VkMemoryPropertyFlags reqs = 0;\n    buffer.init_as_src(*m_device, 8 * 4 * 2, reqs);\n    VkBufferImageCopy region = {};\n    region.bufferRowLength = 0;\n    region.bufferImageHeight = 0;\n    region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    region.imageSubresource.layerCount = 1;\n    region.imageExtent.width = 8;\n    region.imageExtent.height = 4;\n    region.imageExtent.depth = 1;\n\n    width_image.Init(5, 4, 1, VK_FORMAT_BC1_RGBA_SRGB_BLOCK, VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_TILING_OPTIMAL);\n    height_image.Init(8, 3, 1, VK_FORMAT_BC1_RGBA_SRGB_BLOCK, VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_TILING_OPTIMAL);\n    if (!width_image.initialized() || (!height_image.initialized())) {\n        printf(\"%s Unable to initialize surfaces - UncompressedToCompressedImageCopy skipped.\\n\", kSkipPrefix);\n        return;\n    }\n    m_commandBuffer->begin();\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkBufferImageCopy-imageOffset-00197\");\n    vk::CmdCopyBufferToImage(m_commandBuffer->handle(), buffer.handle(), width_image.handle(), VK_IMAGE_LAYOUT_GENERAL, 1, &region);\n    m_errorMonitor->VerifyFound();\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkBufferImageCopy-imageOffset-00200\");\n    m_errorMonitor->SetUnexpectedError(\"VUID-vkCmdCopyBufferToImage-pRegions-00172\");\n\n    VkResult err;\n    VkImageCreateInfo depth_image_create_info = {};\n    depth_image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    depth_image_create_info.pNext = NULL;\n    depth_image_create_info.imageType = VK_IMAGE_TYPE_3D;\n    depth_image_create_info.format = VK_FORMAT_BC1_RGBA_SRGB_BLOCK;\n    depth_image_create_info.extent.width = 8;\n    depth_image_create_info.extent.height = 4;\n    depth_image_create_info.extent.depth = 1;\n    depth_image_create_info.mipLevels = 1;\n    depth_image_create_info.arrayLayers = 1;\n    depth_image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    depth_image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    depth_image_create_info.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;\n    depth_image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n    depth_image_create_info.queueFamilyIndexCount = 0;\n    depth_image_create_info.pQueueFamilyIndices = NULL;\n\n    VkImage depth_image = VK_NULL_HANDLE;\n    err = vk::CreateImage(m_device->handle(), &depth_image_create_info, NULL, &depth_image);\n    ASSERT_VK_SUCCESS(err);\n\n    VkDeviceMemory mem1;\n    VkMemoryRequirements mem_reqs;\n    mem_reqs.memoryTypeBits = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;\n    VkMemoryAllocateInfo mem_alloc = {};\n    mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n    mem_alloc.pNext = NULL;\n    mem_alloc.allocationSize = 0;\n    mem_alloc.memoryTypeIndex = 0;\n    mem_alloc.memoryTypeIndex = 1;\n    vk::GetImageMemoryRequirements(m_device->device(), depth_image, &mem_reqs);\n    mem_alloc.allocationSize = mem_reqs.size;\n    bool pass = m_device->phy().set_memory_type(mem_reqs.memoryTypeBits, &mem_alloc, 0);\n    ASSERT_TRUE(pass);\n    err = vk::AllocateMemory(m_device->device(), &mem_alloc, NULL, &mem1);\n    ASSERT_VK_SUCCESS(err);\n    err = vk::BindImageMemory(m_device->device(), depth_image, mem1, 0);\n\n    region.imageExtent.depth = 2;\n    vk::CmdCopyBufferToImage(m_commandBuffer->handle(), buffer.handle(), depth_image, VK_IMAGE_LAYOUT_GENERAL, 1, &region);\n    m_errorMonitor->VerifyFound();\n\n    vk::DestroyImage(m_device->device(), depth_image, NULL);\n    vk::FreeMemory(m_device->device(), mem1, NULL);\n    m_commandBuffer->end();\n}\n\nTEST_F(VkLayerTest, CreateUnknownObject) {\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkGetImageMemoryRequirements-image-parameter\");\n\n    TEST_DESCRIPTION(\"Pass an invalid image object handle into a Vulkan API call.\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    \/\/ Pass bogus handle into GetImageMemoryRequirements\n    VkMemoryRequirements mem_reqs;\n    uint64_t fakeImageHandle = 0xCADECADE;\n    VkImage fauxImage = reinterpret_cast<VkImage &>(fakeImageHandle);\n\n    vk::GetImageMemoryRequirements(m_device->device(), fauxImage, &mem_reqs);\n\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, BindImageInvalidMemoryType) {\n    VkResult err;\n\n    TEST_DESCRIPTION(\"Test validation check for an invalid memory type index during bind[Buffer|Image]Memory time\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    \/\/ Create an image, allocate memory, set a bad typeIndex and then try to\n    \/\/ bind it\n    VkImage image;\n    VkDeviceMemory mem;\n    VkMemoryRequirements mem_reqs;\n    const VkFormat tex_format = VK_FORMAT_B8G8R8A8_UNORM;\n    const int32_t tex_width = 32;\n    const int32_t tex_height = 32;\n\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = tex_format;\n    image_create_info.extent.width = tex_width;\n    image_create_info.extent.height = tex_height;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT;\n    image_create_info.flags = 0;\n\n    VkMemoryAllocateInfo mem_alloc = {};\n    mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n    mem_alloc.pNext = NULL;\n    mem_alloc.allocationSize = 0;\n    mem_alloc.memoryTypeIndex = 0;\n\n    err = vk::CreateImage(m_device->device(), &image_create_info, NULL, &image);\n    ASSERT_VK_SUCCESS(err);\n\n    vk::GetImageMemoryRequirements(m_device->device(), image, &mem_reqs);\n    mem_alloc.allocationSize = mem_reqs.size;\n\n    \/\/ Introduce Failure, select invalid TypeIndex\n    VkPhysicalDeviceMemoryProperties memory_info;\n\n    vk::GetPhysicalDeviceMemoryProperties(gpu(), &memory_info);\n    unsigned int i;\n    for (i = 0; i < memory_info.memoryTypeCount; i++) {\n        if ((mem_reqs.memoryTypeBits & (1 << i)) == 0) {\n            mem_alloc.memoryTypeIndex = i;\n            break;\n        }\n    }\n    if (i >= memory_info.memoryTypeCount) {\n        printf(\"%s No invalid memory type index could be found; skipped.\\n\", kSkipPrefix);\n        vk::DestroyImage(m_device->device(), image, NULL);\n        return;\n    }\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"for this object type are not compatible with the memory\");\n\n    err = vk::AllocateMemory(m_device->device(), &mem_alloc, NULL, &mem);\n    ASSERT_VK_SUCCESS(err);\n\n    err = vk::BindImageMemory(m_device->device(), image, mem, 0);\n    (void)err;\n\n    m_errorMonitor->VerifyFound();\n\n    vk::DestroyImage(m_device->device(), image, NULL);\n    vk::FreeMemory(m_device->device(), mem, NULL);\n}\n\nTEST_F(VkLayerTest, BindInvalidMemory) {\n    VkResult err;\n    bool pass;\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;\n    const int32_t tex_width = 256;\n    const int32_t tex_height = 256;\n\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = tex_format;\n    image_create_info.extent.width = tex_width;\n    image_create_info.extent.height = tex_height;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT;\n    image_create_info.flags = 0;\n\n    VkBufferCreateInfo buffer_create_info = {};\n    buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;\n    buffer_create_info.pNext = NULL;\n    buffer_create_info.flags = 0;\n    buffer_create_info.size = 4 * 1024 * 1024;\n    buffer_create_info.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;\n    buffer_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n\n    \/\/ Create an image\/buffer, allocate memory, free it, and then try to bind it\n    {\n        VkImage image = VK_NULL_HANDLE;\n        VkBuffer buffer = VK_NULL_HANDLE;\n        err = vk::CreateImage(device(), &image_create_info, NULL, &image);\n        ASSERT_VK_SUCCESS(err);\n        err = vk::CreateBuffer(device(), &buffer_create_info, NULL, &buffer);\n        ASSERT_VK_SUCCESS(err);\n        VkMemoryRequirements image_mem_reqs = {}, buffer_mem_reqs = {};\n        vk::GetImageMemoryRequirements(device(), image, &image_mem_reqs);\n        vk::GetBufferMemoryRequirements(device(), buffer, &buffer_mem_reqs);\n\n        VkMemoryAllocateInfo image_mem_alloc = {}, buffer_mem_alloc = {};\n        image_mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n        image_mem_alloc.allocationSize = image_mem_reqs.size;\n        pass = m_device->phy().set_memory_type(image_mem_reqs.memoryTypeBits, &image_mem_alloc, 0);\n        ASSERT_TRUE(pass);\n        buffer_mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n        buffer_mem_alloc.allocationSize = buffer_mem_reqs.size;\n        pass = m_device->phy().set_memory_type(buffer_mem_reqs.memoryTypeBits, &buffer_mem_alloc, 0);\n        ASSERT_TRUE(pass);\n\n        VkDeviceMemory image_mem = VK_NULL_HANDLE, buffer_mem = VK_NULL_HANDLE;\n        err = vk::AllocateMemory(device(), &image_mem_alloc, NULL, &image_mem);\n        ASSERT_VK_SUCCESS(err);\n        err = vk::AllocateMemory(device(), &buffer_mem_alloc, NULL, &buffer_mem);\n        ASSERT_VK_SUCCESS(err);\n\n        vk::FreeMemory(device(), image_mem, NULL);\n        vk::FreeMemory(device(), buffer_mem, NULL);\n\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindImageMemory-memory-parameter\");\n        err = vk::BindImageMemory(device(), image, image_mem, 0);\n        (void)err;  \/\/ This may very well return an error.\n        m_errorMonitor->VerifyFound();\n\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindBufferMemory-memory-parameter\");\n        err = vk::BindBufferMemory(device(), buffer, buffer_mem, 0);\n        (void)err;  \/\/ This may very well return an error.\n        m_errorMonitor->VerifyFound();\n\n        vk::DestroyImage(m_device->device(), image, NULL);\n        vk::DestroyBuffer(m_device->device(), buffer, NULL);\n    }\n\n    \/\/ Try to bind memory to an object that already has a memory binding\n    {\n        VkImage image = VK_NULL_HANDLE;\n        err = vk::CreateImage(device(), &image_create_info, NULL, &image);\n        ASSERT_VK_SUCCESS(err);\n        VkBuffer buffer = VK_NULL_HANDLE;\n        err = vk::CreateBuffer(device(), &buffer_create_info, NULL, &buffer);\n        ASSERT_VK_SUCCESS(err);\n        VkMemoryRequirements image_mem_reqs = {}, buffer_mem_reqs = {};\n        vk::GetImageMemoryRequirements(device(), image, &image_mem_reqs);\n        vk::GetBufferMemoryRequirements(device(), buffer, &buffer_mem_reqs);\n        VkMemoryAllocateInfo image_alloc_info = {}, buffer_alloc_info = {};\n        image_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n        image_alloc_info.allocationSize = image_mem_reqs.size;\n        buffer_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n        buffer_alloc_info.allocationSize = buffer_mem_reqs.size;\n        pass = m_device->phy().set_memory_type(image_mem_reqs.memoryTypeBits, &image_alloc_info, 0);\n        ASSERT_TRUE(pass);\n        pass = m_device->phy().set_memory_type(buffer_mem_reqs.memoryTypeBits, &buffer_alloc_info, 0);\n        ASSERT_TRUE(pass);\n        VkDeviceMemory image_mem, buffer_mem;\n        err = vk::AllocateMemory(device(), &image_alloc_info, NULL, &image_mem);\n        ASSERT_VK_SUCCESS(err);\n        err = vk::AllocateMemory(device(), &buffer_alloc_info, NULL, &buffer_mem);\n        ASSERT_VK_SUCCESS(err);\n\n        err = vk::BindImageMemory(device(), image, image_mem, 0);\n        ASSERT_VK_SUCCESS(err);\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindImageMemory-image-01044\");\n        err = vk::BindImageMemory(device(), image, image_mem, 0);\n        (void)err;  \/\/ This may very well return an error.\n        m_errorMonitor->VerifyFound();\n\n        err = vk::BindBufferMemory(device(), buffer, buffer_mem, 0);\n        ASSERT_VK_SUCCESS(err);\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindBufferMemory-buffer-01029\");\n        err = vk::BindBufferMemory(device(), buffer, buffer_mem, 0);\n        (void)err;  \/\/ This may very well return an error.\n        m_errorMonitor->VerifyFound();\n\n        vk::FreeMemory(device(), image_mem, NULL);\n        vk::FreeMemory(device(), buffer_mem, NULL);\n        vk::DestroyImage(device(), image, NULL);\n        vk::DestroyBuffer(device(), buffer, NULL);\n    }\n\n    \/\/ Try to bind memory to an object with an invalid memoryOffset\n    {\n        VkImage image = VK_NULL_HANDLE;\n        err = vk::CreateImage(device(), &image_create_info, NULL, &image);\n        ASSERT_VK_SUCCESS(err);\n        VkBuffer buffer = VK_NULL_HANDLE;\n        err = vk::CreateBuffer(device(), &buffer_create_info, NULL, &buffer);\n        ASSERT_VK_SUCCESS(err);\n        VkMemoryRequirements image_mem_reqs = {}, buffer_mem_reqs = {};\n        vk::GetImageMemoryRequirements(device(), image, &image_mem_reqs);\n        vk::GetBufferMemoryRequirements(device(), buffer, &buffer_mem_reqs);\n        VkMemoryAllocateInfo image_alloc_info = {}, buffer_alloc_info = {};\n        image_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n        \/\/ Leave some extra space for alignment wiggle room\n        image_alloc_info.allocationSize = image_mem_reqs.size + image_mem_reqs.alignment;\n        buffer_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n        buffer_alloc_info.allocationSize = buffer_mem_reqs.size + buffer_mem_reqs.alignment;\n        pass = m_device->phy().set_memory_type(image_mem_reqs.memoryTypeBits, &image_alloc_info, 0);\n        ASSERT_TRUE(pass);\n        pass = m_device->phy().set_memory_type(buffer_mem_reqs.memoryTypeBits, &buffer_alloc_info, 0);\n        ASSERT_TRUE(pass);\n        VkDeviceMemory image_mem, buffer_mem;\n        err = vk::AllocateMemory(device(), &image_alloc_info, NULL, &image_mem);\n        ASSERT_VK_SUCCESS(err);\n        err = vk::AllocateMemory(device(), &buffer_alloc_info, NULL, &buffer_mem);\n        ASSERT_VK_SUCCESS(err);\n\n        \/\/ Test unaligned memory offset\n        {\n            if (image_mem_reqs.alignment > 1) {\n                VkDeviceSize image_offset = 1;\n                m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindImageMemory-memoryOffset-01048\");\n                err = vk::BindImageMemory(device(), image, image_mem, image_offset);\n                (void)err;  \/\/ This may very well return an error.\n                m_errorMonitor->VerifyFound();\n            }\n\n            if (buffer_mem_reqs.alignment > 1) {\n                VkDeviceSize buffer_offset = 1;\n                m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindBufferMemory-memoryOffset-01036\");\n                err = vk::BindBufferMemory(device(), buffer, buffer_mem, buffer_offset);\n                (void)err;  \/\/ This may very well return an error.\n                m_errorMonitor->VerifyFound();\n            }\n        }\n\n        \/\/ Test memory offsets outside the memory allocation\n        {\n            VkDeviceSize image_offset =\n                (image_alloc_info.allocationSize + image_mem_reqs.alignment) & ~(image_mem_reqs.alignment - 1);\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindImageMemory-memoryOffset-01046\");\n            err = vk::BindImageMemory(device(), image, image_mem, image_offset);\n            (void)err;  \/\/ This may very well return an error.\n            m_errorMonitor->VerifyFound();\n\n            VkDeviceSize buffer_offset =\n                (buffer_alloc_info.allocationSize + buffer_mem_reqs.alignment) & ~(buffer_mem_reqs.alignment - 1);\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindBufferMemory-memoryOffset-01031\");\n            err = vk::BindBufferMemory(device(), buffer, buffer_mem, buffer_offset);\n            (void)err;  \/\/ This may very well return an error.\n            m_errorMonitor->VerifyFound();\n        }\n\n        \/\/ Test memory offsets within the memory allocation, but which leave too little memory for\n        \/\/ the resource.\n        {\n            VkDeviceSize image_offset = (image_mem_reqs.size - 1) & ~(image_mem_reqs.alignment - 1);\n            if ((image_offset > 0) && (image_mem_reqs.size < (image_alloc_info.allocationSize - image_mem_reqs.alignment))) {\n                m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindImageMemory-size-01049\");\n                err = vk::BindImageMemory(device(), image, image_mem, image_offset);\n                (void)err;  \/\/ This may very well return an error.\n                m_errorMonitor->VerifyFound();\n            }\n\n            VkDeviceSize buffer_offset = (buffer_mem_reqs.size - 1) & ~(buffer_mem_reqs.alignment - 1);\n            if (buffer_offset > 0) {\n                m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindBufferMemory-size-01037\");\n                err = vk::BindBufferMemory(device(), buffer, buffer_mem, buffer_offset);\n                (void)err;  \/\/ This may very well return an error.\n                m_errorMonitor->VerifyFound();\n            }\n        }\n\n        vk::FreeMemory(device(), image_mem, NULL);\n        vk::FreeMemory(device(), buffer_mem, NULL);\n        vk::DestroyImage(device(), image, NULL);\n        vk::DestroyBuffer(device(), buffer, NULL);\n    }\n\n    \/\/ Try to bind memory to an object with an invalid memory type\n    {\n        VkImage image = VK_NULL_HANDLE;\n        err = vk::CreateImage(device(), &image_create_info, NULL, &image);\n        ASSERT_VK_SUCCESS(err);\n        VkBuffer buffer = VK_NULL_HANDLE;\n        err = vk::CreateBuffer(device(), &buffer_create_info, NULL, &buffer);\n        ASSERT_VK_SUCCESS(err);\n        VkMemoryRequirements image_mem_reqs = {}, buffer_mem_reqs = {};\n        vk::GetImageMemoryRequirements(device(), image, &image_mem_reqs);\n        vk::GetBufferMemoryRequirements(device(), buffer, &buffer_mem_reqs);\n        VkMemoryAllocateInfo image_alloc_info = {}, buffer_alloc_info = {};\n        image_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n        image_alloc_info.allocationSize = image_mem_reqs.size;\n        buffer_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n        buffer_alloc_info.allocationSize = buffer_mem_reqs.size;\n        \/\/ Create a mask of available memory types *not* supported by these resources,\n        \/\/ and try to use one of them.\n        VkPhysicalDeviceMemoryProperties memory_properties = {};\n        vk::GetPhysicalDeviceMemoryProperties(m_device->phy().handle(), &memory_properties);\n        VkDeviceMemory image_mem, buffer_mem;\n\n        uint32_t image_unsupported_mem_type_bits = ((1 << memory_properties.memoryTypeCount) - 1) & ~image_mem_reqs.memoryTypeBits;\n        if (image_unsupported_mem_type_bits != 0) {\n            pass = m_device->phy().set_memory_type(image_unsupported_mem_type_bits, &image_alloc_info, 0);\n            ASSERT_TRUE(pass);\n            err = vk::AllocateMemory(device(), &image_alloc_info, NULL, &image_mem);\n            ASSERT_VK_SUCCESS(err);\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindImageMemory-memory-01047\");\n            err = vk::BindImageMemory(device(), image, image_mem, 0);\n            (void)err;  \/\/ This may very well return an error.\n            m_errorMonitor->VerifyFound();\n            vk::FreeMemory(device(), image_mem, NULL);\n        }\n\n        uint32_t buffer_unsupported_mem_type_bits =\n            ((1 << memory_properties.memoryTypeCount) - 1) & ~buffer_mem_reqs.memoryTypeBits;\n        if (buffer_unsupported_mem_type_bits != 0) {\n            pass = m_device->phy().set_memory_type(buffer_unsupported_mem_type_bits, &buffer_alloc_info, 0);\n            ASSERT_TRUE(pass);\n            err = vk::AllocateMemory(device(), &buffer_alloc_info, NULL, &buffer_mem);\n            ASSERT_VK_SUCCESS(err);\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindBufferMemory-memory-01035\");\n            err = vk::BindBufferMemory(device(), buffer, buffer_mem, 0);\n            (void)err;  \/\/ This may very well return an error.\n            m_errorMonitor->VerifyFound();\n            vk::FreeMemory(device(), buffer_mem, NULL);\n        }\n\n        vk::DestroyImage(device(), image, NULL);\n        vk::DestroyBuffer(device(), buffer, NULL);\n    }\n\n    \/\/ Try to bind memory to an image created with sparse memory flags\n    {\n        VkImageCreateInfo sparse_image_create_info = image_create_info;\n        sparse_image_create_info.flags |= VK_IMAGE_CREATE_SPARSE_BINDING_BIT;\n        VkImageFormatProperties image_format_properties = {};\n        err = vk::GetPhysicalDeviceImageFormatProperties(m_device->phy().handle(), sparse_image_create_info.format,\n                                                         sparse_image_create_info.imageType, sparse_image_create_info.tiling,\n                                                         sparse_image_create_info.usage, sparse_image_create_info.flags,\n                                                         &image_format_properties);\n        if (!m_device->phy().features().sparseResidencyImage2D || err == VK_ERROR_FORMAT_NOT_SUPPORTED) {\n            \/\/ most likely means sparse formats aren't supported here; skip this test.\n        } else {\n            ASSERT_VK_SUCCESS(err);\n            if (image_format_properties.maxExtent.width == 0) {\n                printf(\"%s Sparse image format not supported; skipped.\\n\", kSkipPrefix);\n                return;\n            } else {\n                VkImage sparse_image = VK_NULL_HANDLE;\n                err = vk::CreateImage(m_device->device(), &sparse_image_create_info, NULL, &sparse_image);\n                ASSERT_VK_SUCCESS(err);\n                VkMemoryRequirements sparse_mem_reqs = {};\n                vk::GetImageMemoryRequirements(m_device->device(), sparse_image, &sparse_mem_reqs);\n                if (sparse_mem_reqs.memoryTypeBits != 0) {\n                    VkMemoryAllocateInfo sparse_mem_alloc = {};\n                    sparse_mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n                    sparse_mem_alloc.pNext = NULL;\n                    sparse_mem_alloc.allocationSize = sparse_mem_reqs.size;\n                    sparse_mem_alloc.memoryTypeIndex = 0;\n                    pass = m_device->phy().set_memory_type(sparse_mem_reqs.memoryTypeBits, &sparse_mem_alloc, 0);\n                    ASSERT_TRUE(pass);\n                    VkDeviceMemory sparse_mem = VK_NULL_HANDLE;\n                    err = vk::AllocateMemory(m_device->device(), &sparse_mem_alloc, NULL, &sparse_mem);\n                    ASSERT_VK_SUCCESS(err);\n                    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindImageMemory-image-01045\");\n                    err = vk::BindImageMemory(m_device->device(), sparse_image, sparse_mem, 0);\n                    \/\/ This may very well return an error.\n                    (void)err;\n                    m_errorMonitor->VerifyFound();\n                    vk::FreeMemory(m_device->device(), sparse_mem, NULL);\n                }\n                vk::DestroyImage(m_device->device(), sparse_image, NULL);\n            }\n        }\n    }\n\n    \/\/ Try to bind memory to a buffer created with sparse memory flags\n    {\n        VkBufferCreateInfo sparse_buffer_create_info = buffer_create_info;\n        sparse_buffer_create_info.flags |= VK_IMAGE_CREATE_SPARSE_BINDING_BIT;\n        if (!m_device->phy().features().sparseResidencyBuffer) {\n            \/\/ most likely means sparse formats aren't supported here; skip this test.\n        } else {\n            VkBuffer sparse_buffer = VK_NULL_HANDLE;\n            err = vk::CreateBuffer(m_device->device(), &sparse_buffer_create_info, NULL, &sparse_buffer);\n            ASSERT_VK_SUCCESS(err);\n            VkMemoryRequirements sparse_mem_reqs = {};\n            vk::GetBufferMemoryRequirements(m_device->device(), sparse_buffer, &sparse_mem_reqs);\n            if (sparse_mem_reqs.memoryTypeBits != 0) {\n                VkMemoryAllocateInfo sparse_mem_alloc = {};\n                sparse_mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n                sparse_mem_alloc.pNext = NULL;\n                sparse_mem_alloc.allocationSize = sparse_mem_reqs.size;\n                sparse_mem_alloc.memoryTypeIndex = 0;\n                pass = m_device->phy().set_memory_type(sparse_mem_reqs.memoryTypeBits, &sparse_mem_alloc, 0);\n                ASSERT_TRUE(pass);\n                VkDeviceMemory sparse_mem = VK_NULL_HANDLE;\n                err = vk::AllocateMemory(m_device->device(), &sparse_mem_alloc, NULL, &sparse_mem);\n                ASSERT_VK_SUCCESS(err);\n                m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindBufferMemory-buffer-01030\");\n                err = vk::BindBufferMemory(m_device->device(), sparse_buffer, sparse_mem, 0);\n                \/\/ This may very well return an error.\n                (void)err;\n                m_errorMonitor->VerifyFound();\n                vk::FreeMemory(m_device->device(), sparse_mem, NULL);\n            }\n            vk::DestroyBuffer(m_device->device(), sparse_buffer, NULL);\n        }\n    }\n}\n\nTEST_F(VkLayerTest, BindMemoryToDestroyedObject) {\n    VkResult err;\n    bool pass;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindImageMemory-image-parameter\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    \/\/ Create an image object, allocate memory, destroy the object and then try\n    \/\/ to bind it\n    VkImage image;\n    VkDeviceMemory mem;\n    VkMemoryRequirements mem_reqs;\n\n    const VkFormat tex_format = VK_FORMAT_B8G8R8A8_UNORM;\n    const int32_t tex_width = 32;\n    const int32_t tex_height = 32;\n\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = tex_format;\n    image_create_info.extent.width = tex_width;\n    image_create_info.extent.height = tex_height;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT;\n    image_create_info.flags = 0;\n\n    VkMemoryAllocateInfo mem_alloc = {};\n    mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n    mem_alloc.pNext = NULL;\n    mem_alloc.allocationSize = 0;\n    mem_alloc.memoryTypeIndex = 0;\n\n    err = vk::CreateImage(m_device->device(), &image_create_info, NULL, &image);\n    ASSERT_VK_SUCCESS(err);\n\n    vk::GetImageMemoryRequirements(m_device->device(), image, &mem_reqs);\n\n    mem_alloc.allocationSize = mem_reqs.size;\n    pass = m_device->phy().set_memory_type(mem_reqs.memoryTypeBits, &mem_alloc, 0);\n    ASSERT_TRUE(pass);\n\n    \/\/ Allocate memory\n    err = vk::AllocateMemory(m_device->device(), &mem_alloc, NULL, &mem);\n    ASSERT_VK_SUCCESS(err);\n\n    \/\/ Introduce validation failure, destroy Image object before binding\n    vk::DestroyImage(m_device->device(), image, NULL);\n    ASSERT_VK_SUCCESS(err);\n\n    \/\/ Now Try to bind memory to this destroyed object\n    err = vk::BindImageMemory(m_device->device(), image, mem, 0);\n    \/\/ This may very well return an error.\n    (void)err;\n\n    m_errorMonitor->VerifyFound();\n\n    vk::FreeMemory(m_device->device(), mem, NULL);\n}\n\nTEST_F(VkLayerTest, ExceedMemoryAllocationCount) {\n    VkResult err = VK_SUCCESS;\n    const int max_mems = 32;\n    VkDeviceMemory mems[max_mems + 1];\n\n    if (!EnableDeviceProfileLayer()) {\n        printf(\"%s Failed to enable device profile layer.\\n\", kSkipPrefix);\n        return;\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n\n    PFN_vkSetPhysicalDeviceLimitsEXT fpvkSetPhysicalDeviceLimitsEXT =\n        (PFN_vkSetPhysicalDeviceLimitsEXT)vk::GetInstanceProcAddr(instance(), \"vkSetPhysicalDeviceLimitsEXT\");\n    PFN_vkGetOriginalPhysicalDeviceLimitsEXT fpvkGetOriginalPhysicalDeviceLimitsEXT =\n        (PFN_vkGetOriginalPhysicalDeviceLimitsEXT)vk::GetInstanceProcAddr(instance(), \"vkGetOriginalPhysicalDeviceLimitsEXT\");\n\n    if (!(fpvkSetPhysicalDeviceLimitsEXT) || !(fpvkGetOriginalPhysicalDeviceLimitsEXT)) {\n        printf(\"%s Can't find device_profile_api functions; skipped.\\n\", kSkipPrefix);\n        return;\n    }\n    VkPhysicalDeviceProperties props;\n    fpvkGetOriginalPhysicalDeviceLimitsEXT(gpu(), &props.limits);\n    if (props.limits.maxMemoryAllocationCount > max_mems) {\n        props.limits.maxMemoryAllocationCount = max_mems;\n        fpvkSetPhysicalDeviceLimitsEXT(gpu(), &props.limits);\n    }\n    ASSERT_NO_FATAL_FAILURE(InitState());\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"Number of currently valid memory objects is not less than the maximum allowed\");\n\n    VkMemoryAllocateInfo mem_alloc = {};\n    mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n    mem_alloc.pNext = NULL;\n    mem_alloc.memoryTypeIndex = 0;\n    mem_alloc.allocationSize = 4;\n\n    int i;\n    for (i = 0; i <= max_mems; i++) {\n        err = vk::AllocateMemory(m_device->device(), &mem_alloc, NULL, &mems[i]);\n        if (err != VK_SUCCESS) {\n            break;\n        }\n    }\n    m_errorMonitor->VerifyFound();\n\n    for (int j = 0; j < i; j++) {\n        vk::FreeMemory(m_device->device(), mems[j], NULL);\n    }\n}\n\nTEST_F(VkLayerTest, ImageSampleCounts) {\n    TEST_DESCRIPTION(\"Use bad sample counts in image transfer calls to trigger validation errors.\");\n    ASSERT_NO_FATAL_FAILURE(Init(nullptr, nullptr, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT));\n\n    VkMemoryPropertyFlags reqs = 0;\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = VK_FORMAT_B8G8R8A8_UNORM;\n    image_create_info.extent.width = 256;\n    image_create_info.extent.height = 256;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.flags = 0;\n\n    VkImageBlit blit_region = {};\n    blit_region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blit_region.srcSubresource.baseArrayLayer = 0;\n    blit_region.srcSubresource.layerCount = 1;\n    blit_region.srcSubresource.mipLevel = 0;\n    blit_region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blit_region.dstSubresource.baseArrayLayer = 0;\n    blit_region.dstSubresource.layerCount = 1;\n    blit_region.dstSubresource.mipLevel = 0;\n    blit_region.srcOffsets[0] = {0, 0, 0};\n    blit_region.srcOffsets[1] = {256, 256, 1};\n    blit_region.dstOffsets[0] = {0, 0, 0};\n    blit_region.dstOffsets[1] = {128, 128, 1};\n\n    \/\/ Create two images, the source with sampleCount = 4, and attempt to blit\n    \/\/ between them\n    {\n        image_create_info.samples = VK_SAMPLE_COUNT_4_BIT;\n        image_create_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n        VkImageObj src_image(m_device);\n        src_image.init(&image_create_info);\n        src_image.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);\n        image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n        image_create_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n        VkImageObj dst_image(m_device);\n        dst_image.init(&image_create_info);\n        dst_image.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);\n        m_commandBuffer->begin();\n        \/\/ TODO: These 2 VUs are redundant - expect one of them to go away\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00233\");\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00228\");\n        vk::CmdBlitImage(m_commandBuffer->handle(), src_image.handle(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst_image.handle(),\n                         VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit_region, VK_FILTER_NEAREST);\n        m_errorMonitor->VerifyFound();\n        m_commandBuffer->end();\n    }\n\n    \/\/ Create two images, the dest with sampleCount = 4, and attempt to blit\n    \/\/ between them\n    {\n        image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n        image_create_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n        VkImageObj src_image(m_device);\n        src_image.init(&image_create_info);\n        src_image.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);\n        image_create_info.samples = VK_SAMPLE_COUNT_4_BIT;\n        image_create_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n        VkImageObj dst_image(m_device);\n        dst_image.init(&image_create_info);\n        dst_image.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);\n        m_commandBuffer->begin();\n        \/\/ TODO: These 2 VUs are redundant - expect one of them to go away\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-dstImage-00234\");\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00228\");\n        vk::CmdBlitImage(m_commandBuffer->handle(), src_image.handle(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst_image.handle(),\n                         VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit_region, VK_FILTER_NEAREST);\n        m_errorMonitor->VerifyFound();\n        m_commandBuffer->end();\n    }\n\n    VkBufferImageCopy copy_region = {};\n    copy_region.bufferRowLength = 128;\n    copy_region.bufferImageHeight = 128;\n    copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    copy_region.imageSubresource.layerCount = 1;\n    copy_region.imageExtent.height = 64;\n    copy_region.imageExtent.width = 64;\n    copy_region.imageExtent.depth = 1;\n\n    \/\/ Create src buffer and dst image with sampleCount = 4 and attempt to copy\n    \/\/ buffer to image\n    {\n        VkBufferObj src_buffer;\n        src_buffer.init_as_src(*m_device, 128 * 128 * 4, reqs);\n        image_create_info.samples = VK_SAMPLE_COUNT_4_BIT;\n        image_create_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n        VkImageObj dst_image(m_device);\n        dst_image.init(&image_create_info);\n        dst_image.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);\n        m_commandBuffer->begin();\n        m_errorMonitor->SetDesiredFailureMsg(\n            VK_DEBUG_REPORT_ERROR_BIT_EXT,\n            \"was created with a sample count of VK_SAMPLE_COUNT_4_BIT but must be VK_SAMPLE_COUNT_1_BIT\");\n        vk::CmdCopyBufferToImage(m_commandBuffer->handle(), src_buffer.handle(), dst_image.handle(),\n                                 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy_region);\n        m_errorMonitor->VerifyFound();\n        m_commandBuffer->end();\n    }\n\n    \/\/ Create dst buffer and src image with sampleCount = 4 and attempt to copy\n    \/\/ image to buffer\n    {\n        VkBufferObj dst_buffer;\n        dst_buffer.init_as_dst(*m_device, 128 * 128 * 4, reqs);\n        image_create_info.samples = VK_SAMPLE_COUNT_4_BIT;\n        image_create_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n        vk_testing::Image src_image;\n        src_image.init(*m_device, (const VkImageCreateInfo &)image_create_info, reqs);\n        m_commandBuffer->begin();\n        m_errorMonitor->SetDesiredFailureMsg(\n            VK_DEBUG_REPORT_ERROR_BIT_EXT,\n            \"was created with a sample count of VK_SAMPLE_COUNT_4_BIT but must be VK_SAMPLE_COUNT_1_BIT\");\n        vk::CmdCopyImageToBuffer(m_commandBuffer->handle(), src_image.handle(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,\n                                 dst_buffer.handle(), 1, &copy_region);\n        m_errorMonitor->VerifyFound();\n        m_commandBuffer->end();\n    }\n}\n\nTEST_F(VkLayerTest, BlitImageFormatTypes) {\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkFormat f_unsigned = VK_FORMAT_R8G8B8A8_UINT;\n    VkFormat f_signed = VK_FORMAT_R8G8B8A8_SINT;\n    VkFormat f_float = VK_FORMAT_R32_SFLOAT;\n    VkFormat f_depth = VK_FORMAT_D32_SFLOAT_S8_UINT;\n    VkFormat f_depth2 = VK_FORMAT_D32_SFLOAT;\n\n    if (!ImageFormatIsSupported(gpu(), f_unsigned, VK_IMAGE_TILING_OPTIMAL) ||\n        !ImageFormatIsSupported(gpu(), f_signed, VK_IMAGE_TILING_OPTIMAL) ||\n        !ImageFormatIsSupported(gpu(), f_float, VK_IMAGE_TILING_OPTIMAL) ||\n        !ImageFormatIsSupported(gpu(), f_depth, VK_IMAGE_TILING_OPTIMAL) ||\n        !ImageFormatIsSupported(gpu(), f_depth2, VK_IMAGE_TILING_OPTIMAL)) {\n        printf(\"%s Requested formats not supported - BlitImageFormatTypes skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    \/\/ Note any missing feature bits\n    bool usrc = !ImageFormatAndFeaturesSupported(gpu(), f_unsigned, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_BLIT_SRC_BIT);\n    bool udst = !ImageFormatAndFeaturesSupported(gpu(), f_unsigned, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_BLIT_DST_BIT);\n    bool ssrc = !ImageFormatAndFeaturesSupported(gpu(), f_signed, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_BLIT_SRC_BIT);\n    bool sdst = !ImageFormatAndFeaturesSupported(gpu(), f_signed, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_BLIT_DST_BIT);\n    bool fsrc = !ImageFormatAndFeaturesSupported(gpu(), f_float, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_BLIT_SRC_BIT);\n    bool fdst = !ImageFormatAndFeaturesSupported(gpu(), f_float, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_BLIT_DST_BIT);\n    bool d1dst = !ImageFormatAndFeaturesSupported(gpu(), f_depth, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_BLIT_DST_BIT);\n    bool d2src = !ImageFormatAndFeaturesSupported(gpu(), f_depth2, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_BLIT_SRC_BIT);\n\n    VkImageObj unsigned_image(m_device);\n    unsigned_image.Init(64, 64, 1, f_unsigned, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,\n                        VK_IMAGE_TILING_OPTIMAL, 0);\n    ASSERT_TRUE(unsigned_image.initialized());\n    unsigned_image.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL);\n\n    VkImageObj signed_image(m_device);\n    signed_image.Init(64, 64, 1, f_signed, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,\n                      VK_IMAGE_TILING_OPTIMAL, 0);\n    ASSERT_TRUE(signed_image.initialized());\n    signed_image.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL);\n\n    VkImageObj float_image(m_device);\n    float_image.Init(64, 64, 1, f_float, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_TILING_OPTIMAL,\n                     0);\n    ASSERT_TRUE(float_image.initialized());\n    float_image.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL);\n\n    VkImageObj depth_image(m_device);\n    depth_image.Init(64, 64, 1, f_depth, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_TILING_OPTIMAL,\n                     0);\n    ASSERT_TRUE(depth_image.initialized());\n    depth_image.SetLayout(VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_LAYOUT_GENERAL);\n\n    VkImageObj depth_image2(m_device);\n    depth_image2.Init(64, 64, 1, f_depth2, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,\n                      VK_IMAGE_TILING_OPTIMAL, 0);\n    ASSERT_TRUE(depth_image2.initialized());\n    depth_image2.SetLayout(VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_LAYOUT_GENERAL);\n\n    VkImageBlit blitRegion = {};\n    blitRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blitRegion.srcSubresource.baseArrayLayer = 0;\n    blitRegion.srcSubresource.layerCount = 1;\n    blitRegion.srcSubresource.mipLevel = 0;\n    blitRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blitRegion.dstSubresource.baseArrayLayer = 0;\n    blitRegion.dstSubresource.layerCount = 1;\n    blitRegion.dstSubresource.mipLevel = 0;\n    blitRegion.srcOffsets[0] = {0, 0, 0};\n    blitRegion.srcOffsets[1] = {64, 64, 1};\n    blitRegion.dstOffsets[0] = {0, 0, 0};\n    blitRegion.dstOffsets[1] = {32, 32, 1};\n\n    m_commandBuffer->begin();\n\n    \/\/ Unsigned int vs not an int\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00230\");\n    if (usrc) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-01999\");\n    if (fdst) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-dstImage-02000\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), unsigned_image.image(), unsigned_image.Layout(), float_image.image(),\n                     float_image.Layout(), 1, &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00230\");\n    if (fsrc) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-01999\");\n    if (udst) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-dstImage-02000\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), float_image.image(), float_image.Layout(), unsigned_image.image(),\n                     unsigned_image.Layout(), 1, &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Signed int vs not an int,\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00229\");\n    if (ssrc) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-01999\");\n    if (fdst) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-dstImage-02000\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), signed_image.image(), signed_image.Layout(), float_image.image(),\n                     float_image.Layout(), 1, &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00229\");\n    if (fsrc) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-01999\");\n    if (sdst) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-dstImage-02000\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), float_image.image(), float_image.Layout(), signed_image.image(),\n                     signed_image.Layout(), 1, &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Signed vs Unsigned int - generates both VUs\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00229\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00230\");\n    if (ssrc) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-01999\");\n    if (udst) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-dstImage-02000\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), signed_image.image(), signed_image.Layout(), unsigned_image.image(),\n                     unsigned_image.Layout(), 1, &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00229\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00230\");\n    if (usrc) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-01999\");\n    if (sdst) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-dstImage-02000\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), unsigned_image.image(), unsigned_image.Layout(), signed_image.image(),\n                     signed_image.Layout(), 1, &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Depth vs any non-identical depth format\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00231\");\n    blitRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;\n    blitRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;\n    if (d2src) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-01999\");\n    if (d1dst) m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-dstImage-02000\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), depth_image2.image(), depth_image2.Layout(), depth_image.image(),\n                     depth_image.Layout(), 1, &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    m_commandBuffer->end();\n}\n\nTEST_F(VkLayerTest, BlitImageFilters) {\n    bool cubic_support = false;\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    if (DeviceExtensionSupported(gpu(), nullptr, \"VK_IMG_filter_cubic\")) {\n        m_device_extension_names.push_back(\"VK_IMG_filter_cubic\");\n        cubic_support = true;\n    }\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    VkFormat fmt = VK_FORMAT_R8_UINT;\n    if (!ImageFormatIsSupported(gpu(), fmt, VK_IMAGE_TILING_OPTIMAL)) {\n        printf(\"%s No R8_UINT format support - BlitImageFilters skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    \/\/ Create 2D images\n    VkImageObj src2D(m_device);\n    VkImageObj dst2D(m_device);\n    src2D.Init(64, 64, 1, fmt, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_IMAGE_TILING_OPTIMAL, 0);\n    dst2D.Init(64, 64, 1, fmt, VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_TILING_OPTIMAL, 0);\n    ASSERT_TRUE(src2D.initialized());\n    ASSERT_TRUE(dst2D.initialized());\n    src2D.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL);\n    dst2D.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL);\n\n    \/\/ Create 3D image\n    VkImageCreateInfo ci;\n    ci.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    ci.pNext = NULL;\n    ci.flags = 0;\n    ci.imageType = VK_IMAGE_TYPE_3D;\n    ci.format = fmt;\n    ci.extent = {64, 64, 4};\n    ci.mipLevels = 1;\n    ci.arrayLayers = 1;\n    ci.samples = VK_SAMPLE_COUNT_1_BIT;\n    ci.tiling = VK_IMAGE_TILING_OPTIMAL;\n    ci.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n    ci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n    ci.queueFamilyIndexCount = 0;\n    ci.pQueueFamilyIndices = NULL;\n    ci.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n\n    VkImageObj src3D(m_device);\n    src3D.init(&ci);\n    ASSERT_TRUE(src3D.initialized());\n\n    VkImageBlit blitRegion = {};\n    blitRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blitRegion.srcSubresource.baseArrayLayer = 0;\n    blitRegion.srcSubresource.layerCount = 1;\n    blitRegion.srcSubresource.mipLevel = 0;\n    blitRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blitRegion.dstSubresource.baseArrayLayer = 0;\n    blitRegion.dstSubresource.layerCount = 1;\n    blitRegion.dstSubresource.mipLevel = 0;\n    blitRegion.srcOffsets[0] = {0, 0, 0};\n    blitRegion.srcOffsets[1] = {48, 48, 1};\n    blitRegion.dstOffsets[0] = {0, 0, 0};\n    blitRegion.dstOffsets[1] = {64, 64, 1};\n\n    m_commandBuffer->begin();\n\n    \/\/ UINT format should not support linear filtering, but check to be sure\n    if (!ImageFormatAndFeaturesSupported(gpu(), fmt, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)) {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-filter-02001\");\n        vk::CmdBlitImage(m_commandBuffer->handle(), src2D.image(), src2D.Layout(), dst2D.image(), dst2D.Layout(), 1, &blitRegion,\n                         VK_FILTER_LINEAR);\n        m_errorMonitor->VerifyFound();\n    }\n\n    if (cubic_support && !ImageFormatAndFeaturesSupported(gpu(), fmt, VK_IMAGE_TILING_OPTIMAL,\n                                                          VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG)) {\n        \/\/ Invalid filter CUBIC_IMG\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-filter-02002\");\n        vk::CmdBlitImage(m_commandBuffer->handle(), src3D.image(), src3D.Layout(), dst2D.image(), dst2D.Layout(), 1, &blitRegion,\n                         VK_FILTER_CUBIC_IMG);\n        m_errorMonitor->VerifyFound();\n\n        \/\/ Invalid filter CUBIC_IMG + invalid 2D source image\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-filter-02002\");\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-filter-00237\");\n        vk::CmdBlitImage(m_commandBuffer->handle(), src2D.image(), src2D.Layout(), dst2D.image(), dst2D.Layout(), 1, &blitRegion,\n                         VK_FILTER_CUBIC_IMG);\n        m_errorMonitor->VerifyFound();\n    }\n\n    m_commandBuffer->end();\n}\n\nTEST_F(VkLayerTest, BlitImageLayout) {\n    TEST_DESCRIPTION(\"Incorrect vkCmdBlitImage layouts\");\n\n    ASSERT_NO_FATAL_FAILURE(Init(nullptr, nullptr, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT));\n\n    VkResult err;\n    VkFormat fmt = VK_FORMAT_R8G8B8A8_UNORM;\n\n    VkSubmitInfo submit_info = {};\n    submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;\n    submit_info.commandBufferCount = 1;\n    submit_info.pCommandBuffers = &m_commandBuffer->handle();\n\n    \/\/ Create images\n    VkImageObj img_src_transfer(m_device);\n    VkImageObj img_dst_transfer(m_device);\n    VkImageObj img_general(m_device);\n    VkImageObj img_color(m_device);\n\n    img_src_transfer.InitNoLayout(64, 64, 1, fmt, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,\n                                  VK_IMAGE_TILING_OPTIMAL, 0);\n    img_dst_transfer.InitNoLayout(64, 64, 1, fmt, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,\n                                  VK_IMAGE_TILING_OPTIMAL, 0);\n    img_general.InitNoLayout(64, 64, 1, fmt, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,\n                             VK_IMAGE_TILING_OPTIMAL, 0);\n    img_color.InitNoLayout(64, 64, 1, fmt,\n                           VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,\n                           VK_IMAGE_TILING_OPTIMAL, 0);\n\n    ASSERT_TRUE(img_src_transfer.initialized());\n    ASSERT_TRUE(img_dst_transfer.initialized());\n    ASSERT_TRUE(img_general.initialized());\n    ASSERT_TRUE(img_color.initialized());\n\n    img_src_transfer.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);\n    img_dst_transfer.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);\n    img_general.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL);\n    img_color.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);\n\n    VkImageBlit blit_region = {};\n    blit_region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blit_region.srcSubresource.baseArrayLayer = 0;\n    blit_region.srcSubresource.layerCount = 1;\n    blit_region.srcSubresource.mipLevel = 0;\n    blit_region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blit_region.dstSubresource.baseArrayLayer = 0;\n    blit_region.dstSubresource.layerCount = 1;\n    blit_region.dstSubresource.mipLevel = 0;\n    blit_region.srcOffsets[0] = {0, 0, 0};\n    blit_region.srcOffsets[1] = {48, 48, 1};\n    blit_region.dstOffsets[0] = {0, 0, 0};\n    blit_region.dstOffsets[1] = {64, 64, 1};\n\n    m_commandBuffer->begin();\n\n    \/\/ Illegal srcImageLayout\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImageLayout-00222\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), img_src_transfer.image(), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,\n                     img_dst_transfer.image(), img_dst_transfer.Layout(), 1, &blit_region, VK_FILTER_LINEAR);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Illegal destImageLayout\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-dstImageLayout-00227\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), img_src_transfer.image(), img_src_transfer.Layout(), img_dst_transfer.image(),\n                     VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, 1, &blit_region, VK_FILTER_LINEAR);\n\n    m_commandBuffer->end();\n    vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);\n    m_errorMonitor->VerifyFound();\n\n    err = vk::QueueWaitIdle(m_device->m_queue);\n    ASSERT_VK_SUCCESS(err);\n\n    m_commandBuffer->reset(0);\n    m_commandBuffer->begin();\n\n    \/\/ Source image in invalid layout at start of the CB\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"UNASSIGNED-CoreValidation-DrawState-InvalidImageLayout\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), img_src_transfer.image(), img_src_transfer.Layout(), img_color.image(),\n                     VK_IMAGE_LAYOUT_GENERAL, 1, &blit_region, VK_FILTER_LINEAR);\n\n    m_commandBuffer->end();\n    vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);\n    m_errorMonitor->VerifyFound();\n    err = vk::QueueWaitIdle(m_device->m_queue);\n    ASSERT_VK_SUCCESS(err);\n\n    m_commandBuffer->reset(0);\n    m_commandBuffer->begin();\n\n    \/\/ Destination image in invalid layout at start of the CB\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"UNASSIGNED-CoreValidation-DrawState-InvalidImageLayout\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), img_color.image(), VK_IMAGE_LAYOUT_GENERAL, img_dst_transfer.image(),\n                     img_dst_transfer.Layout(), 1, &blit_region, VK_FILTER_LINEAR);\n\n    m_commandBuffer->end();\n    vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);\n    m_errorMonitor->VerifyFound();\n    err = vk::QueueWaitIdle(m_device->m_queue);\n    ASSERT_VK_SUCCESS(err);\n\n    \/\/ Source image in invalid layout in the middle of CB\n    m_commandBuffer->reset(0);\n    m_commandBuffer->begin();\n\n    VkImageMemoryBarrier img_barrier = {};\n    img_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;\n    img_barrier.pNext = nullptr;\n    img_barrier.srcAccessMask = 0;\n    img_barrier.dstAccessMask = 0;\n    img_barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL;\n    img_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;\n    img_barrier.image = img_general.handle();\n    img_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    img_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    img_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    img_barrier.subresourceRange.baseArrayLayer = 0;\n    img_barrier.subresourceRange.baseMipLevel = 0;\n    img_barrier.subresourceRange.layerCount = 1;\n    img_barrier.subresourceRange.levelCount = 1;\n\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0,\n                           nullptr, 0, nullptr, 1, &img_barrier);\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImageLayout-00221\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), img_general.image(), VK_IMAGE_LAYOUT_GENERAL, img_dst_transfer.image(),\n                     img_dst_transfer.Layout(), 1, &blit_region, VK_FILTER_LINEAR);\n\n    m_commandBuffer->end();\n    vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);\n    m_errorMonitor->VerifyFound();\n    err = vk::QueueWaitIdle(m_device->m_queue);\n    ASSERT_VK_SUCCESS(err);\n\n    \/\/ Destination image in invalid layout in the middle of CB\n    m_commandBuffer->reset(0);\n    m_commandBuffer->begin();\n\n    img_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;\n    img_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;\n    img_barrier.image = img_dst_transfer.handle();\n\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0,\n                           nullptr, 0, nullptr, 1, &img_barrier);\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-dstImageLayout-00226\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), img_src_transfer.image(), img_src_transfer.Layout(), img_dst_transfer.image(),\n                     VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit_region, VK_FILTER_LINEAR);\n\n    m_commandBuffer->end();\n    vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);\n    m_errorMonitor->VerifyFound();\n    err = vk::QueueWaitIdle(m_device->m_queue);\n    ASSERT_VK_SUCCESS(err);\n}\n\nTEST_F(VkLayerTest, BlitImageOffsets) {\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkFormat fmt = VK_FORMAT_R8G8B8A8_UNORM;\n    if (!ImageFormatAndFeaturesSupported(gpu(), fmt, VK_IMAGE_TILING_OPTIMAL,\n                                         VK_FORMAT_FEATURE_BLIT_SRC_BIT | VK_FORMAT_FEATURE_BLIT_DST_BIT)) {\n        printf(\"%s No blit feature bits - BlitImageOffsets skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkImageCreateInfo ci;\n    ci.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    ci.pNext = NULL;\n    ci.flags = 0;\n    ci.imageType = VK_IMAGE_TYPE_1D;\n    ci.format = fmt;\n    ci.extent = {64, 1, 1};\n    ci.mipLevels = 1;\n    ci.arrayLayers = 1;\n    ci.samples = VK_SAMPLE_COUNT_1_BIT;\n    ci.tiling = VK_IMAGE_TILING_OPTIMAL;\n    ci.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n    ci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n    ci.queueFamilyIndexCount = 0;\n    ci.pQueueFamilyIndices = NULL;\n    ci.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n\n    VkImageObj image_1D(m_device);\n    image_1D.init(&ci);\n    ASSERT_TRUE(image_1D.initialized());\n\n    ci.imageType = VK_IMAGE_TYPE_2D;\n    ci.extent = {64, 64, 1};\n    VkImageObj image_2D(m_device);\n    image_2D.init(&ci);\n    ASSERT_TRUE(image_2D.initialized());\n\n    ci.imageType = VK_IMAGE_TYPE_3D;\n    ci.extent = {64, 64, 64};\n    VkImageObj image_3D(m_device);\n    image_3D.init(&ci);\n    ASSERT_TRUE(image_3D.initialized());\n\n    VkImageBlit blit_region = {};\n    blit_region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blit_region.srcSubresource.baseArrayLayer = 0;\n    blit_region.srcSubresource.layerCount = 1;\n    blit_region.srcSubresource.mipLevel = 0;\n    blit_region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blit_region.dstSubresource.baseArrayLayer = 0;\n    blit_region.dstSubresource.layerCount = 1;\n    blit_region.dstSubresource.mipLevel = 0;\n\n    m_commandBuffer->begin();\n\n    \/\/ 1D, with src\/dest y offsets other than (0,1)\n    blit_region.srcOffsets[0] = {0, 1, 0};\n    blit_region.srcOffsets[1] = {30, 1, 1};\n    blit_region.dstOffsets[0] = {32, 0, 0};\n    blit_region.dstOffsets[1] = {64, 1, 1};\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-srcImage-00245\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), image_1D.image(), image_1D.Layout(), image_1D.image(), image_1D.Layout(), 1,\n                     &blit_region, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    blit_region.srcOffsets[0] = {0, 0, 0};\n    blit_region.dstOffsets[0] = {32, 1, 0};\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-dstImage-00250\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), image_1D.image(), image_1D.Layout(), image_1D.image(), image_1D.Layout(), 1,\n                     &blit_region, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ 2D, with src\/dest z offsets other than (0,1)\n    blit_region.srcOffsets[0] = {0, 0, 1};\n    blit_region.srcOffsets[1] = {24, 31, 1};\n    blit_region.dstOffsets[0] = {32, 32, 0};\n    blit_region.dstOffsets[1] = {64, 64, 1};\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-srcImage-00247\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), image_2D.image(), image_2D.Layout(), image_2D.image(), image_2D.Layout(), 1,\n                     &blit_region, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    blit_region.srcOffsets[0] = {0, 0, 0};\n    blit_region.dstOffsets[0] = {32, 32, 1};\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-dstImage-00252\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), image_2D.image(), image_2D.Layout(), image_2D.image(), image_2D.Layout(), 1,\n                     &blit_region, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Source offsets exceeding source image dimensions\n    blit_region.srcOffsets[0] = {0, 0, 0};\n    blit_region.srcOffsets[1] = {65, 64, 1};  \/\/ src x\n    blit_region.dstOffsets[0] = {0, 0, 0};\n    blit_region.dstOffsets[1] = {64, 64, 1};\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-srcOffset-00243\");    \/\/ x\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-pRegions-00215\");  \/\/ src region\n    vk::CmdBlitImage(m_commandBuffer->handle(), image_3D.image(), image_3D.Layout(), image_2D.image(), image_2D.Layout(), 1,\n                     &blit_region, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    blit_region.srcOffsets[1] = {64, 65, 1};                                                                    \/\/ src y\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-srcOffset-00244\");    \/\/ y\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-pRegions-00215\");  \/\/ src region\n    vk::CmdBlitImage(m_commandBuffer->handle(), image_3D.image(), image_3D.Layout(), image_2D.image(), image_2D.Layout(), 1,\n                     &blit_region, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    blit_region.srcOffsets[0] = {0, 0, 65};  \/\/ src z\n    blit_region.srcOffsets[1] = {64, 64, 64};\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-srcOffset-00246\");    \/\/ z\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-pRegions-00215\");  \/\/ src region\n    vk::CmdBlitImage(m_commandBuffer->handle(), image_3D.image(), image_3D.Layout(), image_2D.image(), image_2D.Layout(), 1,\n                     &blit_region, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Dest offsets exceeding source image dimensions\n    blit_region.srcOffsets[0] = {0, 0, 0};\n    blit_region.srcOffsets[1] = {64, 64, 1};\n    blit_region.dstOffsets[0] = {96, 64, 32};  \/\/ dst x\n    blit_region.dstOffsets[1] = {64, 0, 33};\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-dstOffset-00248\");    \/\/ x\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-pRegions-00216\");  \/\/ dst region\n    vk::CmdBlitImage(m_commandBuffer->handle(), image_2D.image(), image_2D.Layout(), image_3D.image(), image_3D.Layout(), 1,\n                     &blit_region, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    blit_region.dstOffsets[0] = {0, 65, 32};                                                                    \/\/ dst y\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-dstOffset-00249\");    \/\/ y\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-pRegions-00216\");  \/\/ dst region\n    vk::CmdBlitImage(m_commandBuffer->handle(), image_2D.image(), image_2D.Layout(), image_3D.image(), image_3D.Layout(), 1,\n                     &blit_region, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    blit_region.dstOffsets[0] = {0, 64, 65};  \/\/ dst z\n    blit_region.dstOffsets[1] = {64, 0, 64};\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-dstOffset-00251\");    \/\/ z\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-pRegions-00216\");  \/\/ dst region\n    vk::CmdBlitImage(m_commandBuffer->handle(), image_2D.image(), image_2D.Layout(), image_3D.image(), image_3D.Layout(), 1,\n                     &blit_region, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    m_commandBuffer->end();\n}\n\nTEST_F(VkLayerTest, MiscBlitImageTests) {\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkFormat f_color = VK_FORMAT_R32_SFLOAT;  \/\/ Need features ..BLIT_SRC_BIT & ..BLIT_DST_BIT\n\n    if (!ImageFormatAndFeaturesSupported(gpu(), f_color, VK_IMAGE_TILING_OPTIMAL,\n                                         VK_FORMAT_FEATURE_BLIT_SRC_BIT | VK_FORMAT_FEATURE_BLIT_DST_BIT)) {\n        printf(\"%s Requested format features unavailable - MiscBlitImageTests skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkImageCreateInfo ci;\n    ci.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    ci.pNext = NULL;\n    ci.flags = 0;\n    ci.imageType = VK_IMAGE_TYPE_2D;\n    ci.format = f_color;\n    ci.extent = {64, 64, 1};\n    ci.mipLevels = 1;\n    ci.arrayLayers = 1;\n    ci.samples = VK_SAMPLE_COUNT_1_BIT;\n    ci.tiling = VK_IMAGE_TILING_OPTIMAL;\n    ci.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n    ci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n    ci.queueFamilyIndexCount = 0;\n    ci.pQueueFamilyIndices = NULL;\n    ci.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n\n    \/\/ 2D color image\n    VkImageObj color_img(m_device);\n    color_img.init(&ci);\n    ASSERT_TRUE(color_img.initialized());\n\n    \/\/ 2D multi-sample image\n    ci.samples = VK_SAMPLE_COUNT_4_BIT;\n    VkImageObj ms_img(m_device);\n    ms_img.init(&ci);\n    ASSERT_TRUE(ms_img.initialized());\n\n    \/\/ 3D color image\n    ci.samples = VK_SAMPLE_COUNT_1_BIT;\n    ci.imageType = VK_IMAGE_TYPE_3D;\n    ci.extent = {64, 64, 8};\n    VkImageObj color_3D_img(m_device);\n    color_3D_img.init(&ci);\n    ASSERT_TRUE(color_3D_img.initialized());\n\n    VkImageBlit blitRegion = {};\n    blitRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blitRegion.srcSubresource.baseArrayLayer = 0;\n    blitRegion.srcSubresource.layerCount = 1;\n    blitRegion.srcSubresource.mipLevel = 0;\n    blitRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blitRegion.dstSubresource.baseArrayLayer = 0;\n    blitRegion.dstSubresource.layerCount = 1;\n    blitRegion.dstSubresource.mipLevel = 0;\n    blitRegion.srcOffsets[0] = {0, 0, 0};\n    blitRegion.srcOffsets[1] = {16, 16, 1};\n    blitRegion.dstOffsets[0] = {32, 32, 0};\n    blitRegion.dstOffsets[1] = {64, 64, 1};\n\n    m_commandBuffer->begin();\n\n    \/\/ Blit with aspectMask errors\n    blitRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;\n    blitRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-aspectMask-00241\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-aspectMask-00242\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), color_img.image(), color_img.Layout(), color_img.image(), color_img.Layout(), 1,\n                     &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Blit with invalid src mip level\n    blitRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blitRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blitRegion.srcSubresource.mipLevel = ci.mipLevels;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkCmdBlitImage-srcSubresource-01705\");  \/\/ invalid srcSubresource.mipLevel\n    \/\/ Redundant unavoidable errors\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-VkImageBlit-srcOffset-00243\");  \/\/ out-of-bounds srcOffset.x\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-VkImageBlit-srcOffset-00244\");  \/\/ out-of-bounds srcOffset.y\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-VkImageBlit-srcOffset-00246\");  \/\/ out-of-bounds srcOffset.z\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkCmdBlitImage-pRegions-00215\");  \/\/ region not contained within src image\n    vk::CmdBlitImage(m_commandBuffer->handle(), color_img.image(), color_img.Layout(), color_img.image(), color_img.Layout(), 1,\n                     &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Blit with invalid dst mip level\n    blitRegion.srcSubresource.mipLevel = 0;\n    blitRegion.dstSubresource.mipLevel = ci.mipLevels;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkCmdBlitImage-dstSubresource-01706\");  \/\/ invalid dstSubresource.mipLevel\n    \/\/ Redundant unavoidable errors\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-VkImageBlit-dstOffset-00248\");  \/\/ out-of-bounds dstOffset.x\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-VkImageBlit-dstOffset-00249\");  \/\/ out-of-bounds dstOffset.y\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-VkImageBlit-dstOffset-00251\");  \/\/ out-of-bounds dstOffset.z\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkCmdBlitImage-pRegions-00216\");  \/\/ region not contained within dst image\n    vk::CmdBlitImage(m_commandBuffer->handle(), color_img.image(), color_img.Layout(), color_img.image(), color_img.Layout(), 1,\n                     &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Blit with invalid src array layer\n    blitRegion.dstSubresource.mipLevel = 0;\n    blitRegion.srcSubresource.baseArrayLayer = ci.arrayLayers;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkCmdBlitImage-srcSubresource-01707\");  \/\/ invalid srcSubresource layer range\n    vk::CmdBlitImage(m_commandBuffer->handle(), color_img.image(), color_img.Layout(), color_img.image(), color_img.Layout(), 1,\n                     &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Blit with invalid dst array layer\n    blitRegion.srcSubresource.baseArrayLayer = 0;\n    blitRegion.dstSubresource.baseArrayLayer = ci.arrayLayers;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkCmdBlitImage-dstSubresource-01708\");  \/\/ invalid dstSubresource layer range\n                                                                                       \/\/ Redundant unavoidable errors\n    vk::CmdBlitImage(m_commandBuffer->handle(), color_img.image(), color_img.Layout(), color_img.image(), color_img.Layout(), 1,\n                     &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    blitRegion.dstSubresource.baseArrayLayer = 0;\n\n    \/\/ Blit multi-sample image\n    \/\/ TODO: redundant VUs, one (1c8) or two (1d2 & 1d4) should be eliminated.\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00228\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-srcImage-00233\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-dstImage-00234\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), ms_img.image(), ms_img.Layout(), ms_img.image(), ms_img.Layout(), 1, &blitRegion,\n                     VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Blit 3D with baseArrayLayer != 0 or layerCount != 1\n    blitRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blitRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blitRegion.srcSubresource.baseArrayLayer = 1;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-srcImage-00240\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkCmdBlitImage-srcSubresource-01707\");  \/\/ base+count > total layer count\n    vk::CmdBlitImage(m_commandBuffer->handle(), color_3D_img.image(), color_3D_img.Layout(), color_3D_img.image(),\n                     color_3D_img.Layout(), 1, &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n    blitRegion.srcSubresource.baseArrayLayer = 0;\n    blitRegion.srcSubresource.layerCount = 0;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageBlit-srcImage-00240\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-VkImageSubresourceLayers-layerCount-01700\");  \/\/ layer count == 0 (src)\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-VkImageBlit-layerCount-00239\");  \/\/ src\/dst layer count mismatch\n    vk::CmdBlitImage(m_commandBuffer->handle(), color_3D_img.image(), color_3D_img.Layout(), color_3D_img.image(),\n                     color_3D_img.Layout(), 1, &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    m_commandBuffer->end();\n}\n\nTEST_F(VkLayerTest, BlitToDepthImageTests) {\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    \/\/ Need feature ..BLIT_SRC_BIT but not ..BLIT_DST_BIT\n    \/\/ TODO: provide more choices here; supporting D32_SFLOAT as BLIT_DST isn't unheard of.\n    VkFormat f_depth = VK_FORMAT_D32_SFLOAT;\n\n    if (!ImageFormatAndFeaturesSupported(gpu(), f_depth, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_BLIT_SRC_BIT) ||\n        ImageFormatAndFeaturesSupported(gpu(), f_depth, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_BLIT_DST_BIT)) {\n        printf(\"%s Requested format features unavailable - BlitToDepthImageTests skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkImageCreateInfo ci;\n    ci.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    ci.pNext = NULL;\n    ci.flags = 0;\n    ci.imageType = VK_IMAGE_TYPE_2D;\n    ci.format = f_depth;\n    ci.extent = {64, 64, 1};\n    ci.mipLevels = 1;\n    ci.arrayLayers = 1;\n    ci.samples = VK_SAMPLE_COUNT_1_BIT;\n    ci.tiling = VK_IMAGE_TILING_OPTIMAL;\n    ci.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n    ci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n    ci.queueFamilyIndexCount = 0;\n    ci.pQueueFamilyIndices = NULL;\n    ci.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n\n    \/\/ 2D depth image\n    VkImageObj depth_img(m_device);\n    depth_img.init(&ci);\n    ASSERT_TRUE(depth_img.initialized());\n\n    VkImageBlit blitRegion = {};\n    blitRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blitRegion.srcSubresource.baseArrayLayer = 0;\n    blitRegion.srcSubresource.layerCount = 1;\n    blitRegion.srcSubresource.mipLevel = 0;\n    blitRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    blitRegion.dstSubresource.baseArrayLayer = 0;\n    blitRegion.dstSubresource.layerCount = 1;\n    blitRegion.dstSubresource.mipLevel = 0;\n    blitRegion.srcOffsets[0] = {0, 0, 0};\n    blitRegion.srcOffsets[1] = {16, 16, 1};\n    blitRegion.dstOffsets[0] = {32, 32, 0};\n    blitRegion.dstOffsets[1] = {64, 64, 1};\n\n    m_commandBuffer->begin();\n\n    \/\/ Blit depth image - has SRC_BIT but not DST_BIT\n    blitRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;\n    blitRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBlitImage-dstImage-02000\");\n    vk::CmdBlitImage(m_commandBuffer->handle(), depth_img.image(), depth_img.Layout(), depth_img.image(), depth_img.Layout(), 1,\n                     &blitRegion, VK_FILTER_NEAREST);\n    m_errorMonitor->VerifyFound();\n\n    m_commandBuffer->end();\n}\n\nTEST_F(VkLayerTest, MinImageTransferGranularity) {\n    TEST_DESCRIPTION(\"Tests for validation of Queue Family property minImageTransferGranularity.\");\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    auto queue_family_properties = m_device->phy().queue_properties();\n    auto large_granularity_family =\n        std::find_if(queue_family_properties.begin(), queue_family_properties.end(), [](VkQueueFamilyProperties family_properties) {\n            VkExtent3D family_granularity = family_properties.minImageTransferGranularity;\n            \/\/ We need a queue family that supports copy operations and has a large enough minImageTransferGranularity for the tests\n            \/\/ below to make sense.\n            return (family_properties.queueFlags & VK_QUEUE_TRANSFER_BIT || family_properties.queueFlags & VK_QUEUE_GRAPHICS_BIT ||\n                    family_properties.queueFlags & VK_QUEUE_COMPUTE_BIT) &&\n                   family_granularity.depth >= 4 && family_granularity.width >= 4 && family_granularity.height >= 4;\n        });\n\n    if (large_granularity_family == queue_family_properties.end()) {\n        printf(\"%s No queue family has a large enough granularity for this test to be meaningful, skipping test\\n\", kSkipPrefix);\n        return;\n    }\n    const size_t queue_family_index = std::distance(queue_family_properties.begin(), large_granularity_family);\n    VkExtent3D granularity = queue_family_properties[queue_family_index].minImageTransferGranularity;\n    VkCommandPoolObj command_pool(m_device, queue_family_index, 0);\n\n    \/\/ Create two images of different types and try to copy between them\n    VkImage srcImage;\n    VkImage dstImage;\n\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_3D;\n    image_create_info.format = VK_FORMAT_B8G8R8A8_UNORM;\n    image_create_info.extent.width = granularity.width * 2;\n    image_create_info.extent.height = granularity.height * 2;\n    image_create_info.extent.depth = granularity.depth * 2;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n    image_create_info.flags = 0;\n\n    VkImageObj src_image_obj(m_device);\n    src_image_obj.init(&image_create_info);\n    ASSERT_TRUE(src_image_obj.initialized());\n    srcImage = src_image_obj.handle();\n\n    image_create_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n\n    VkImageObj dst_image_obj(m_device);\n    dst_image_obj.init(&image_create_info);\n    ASSERT_TRUE(dst_image_obj.initialized());\n    dstImage = dst_image_obj.handle();\n\n    VkCommandBufferObj command_buffer(m_device, &command_pool);\n    ASSERT_TRUE(command_buffer.initialized());\n    command_buffer.begin();\n\n    VkImageCopy copyRegion;\n    copyRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    copyRegion.srcSubresource.mipLevel = 0;\n    copyRegion.srcSubresource.baseArrayLayer = 0;\n    copyRegion.srcSubresource.layerCount = 1;\n    copyRegion.srcOffset.x = 0;\n    copyRegion.srcOffset.y = 0;\n    copyRegion.srcOffset.z = 0;\n    copyRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    copyRegion.dstSubresource.mipLevel = 0;\n    copyRegion.dstSubresource.baseArrayLayer = 0;\n    copyRegion.dstSubresource.layerCount = 1;\n    copyRegion.dstOffset.x = 0;\n    copyRegion.dstOffset.y = 0;\n    copyRegion.dstOffset.z = 0;\n    copyRegion.extent.width = granularity.width;\n    copyRegion.extent.height = granularity.height;\n    copyRegion.extent.depth = granularity.depth;\n\n    \/\/ Introduce failure by setting srcOffset to a bad granularity value\n    copyRegion.srcOffset.y = 3;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkCmdCopyImage-srcOffset-01783\");  \/\/ srcOffset image transfer granularity\n    command_buffer.CopyImage(srcImage, VK_IMAGE_LAYOUT_GENERAL, dstImage, VK_IMAGE_LAYOUT_GENERAL, 1, &copyRegion);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Introduce failure by setting extent to a granularity value that is bad\n    \/\/ for both the source and destination image.\n    copyRegion.srcOffset.y = 0;\n    copyRegion.extent.width = 3;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkCmdCopyImage-srcOffset-01783\");  \/\/ src extent image transfer granularity\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkCmdCopyImage-dstOffset-01784\");  \/\/ dst extent image transfer granularity\n    command_buffer.CopyImage(srcImage, VK_IMAGE_LAYOUT_GENERAL, dstImage, VK_IMAGE_LAYOUT_GENERAL, 1, &copyRegion);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Now do some buffer\/image copies\n    VkBufferObj buffer;\n    VkMemoryPropertyFlags reqs = 0;\n    buffer.init_as_src_and_dst(*m_device, 8 * granularity.height * granularity.width * granularity.depth, reqs);\n    VkBufferImageCopy region = {};\n    region.bufferOffset = 0;\n    region.bufferRowLength = 0;\n    region.bufferImageHeight = 0;\n    region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    region.imageSubresource.layerCount = 1;\n    region.imageExtent.height = granularity.height;\n    region.imageExtent.width = granularity.width;\n    region.imageExtent.depth = granularity.depth;\n    region.imageOffset.x = 0;\n    region.imageOffset.y = 0;\n    region.imageOffset.z = 0;\n\n    \/\/ Introduce failure by setting imageExtent to a bad granularity value\n    region.imageExtent.width = 3;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkCmdCopyImageToBuffer-imageOffset-01794\");  \/\/ image transfer granularity\n    vk::CmdCopyImageToBuffer(command_buffer.handle(), srcImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer.handle(), 1, &region);\n    m_errorMonitor->VerifyFound();\n    region.imageExtent.width = granularity.width;\n\n    \/\/ Introduce failure by setting imageOffset to a bad granularity value\n    region.imageOffset.z = 3;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkCmdCopyBufferToImage-imageOffset-01793\");  \/\/ image transfer granularity\n    vk::CmdCopyBufferToImage(command_buffer.handle(), buffer.handle(), dstImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);\n    m_errorMonitor->VerifyFound();\n\n    command_buffer.end();\n}\n\nTEST_F(VkLayerTest, ImageBarrierSubpassConflicts) {\n    TEST_DESCRIPTION(\"Add a pipeline barrier within a subpass that has conflicting state\");\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    \/\/ A renderpass with a single subpass that declared a self-dependency\n    VkAttachmentDescription attach[] = {\n        {0, VK_FORMAT_R8G8B8A8_UNORM, VK_SAMPLE_COUNT_1_BIT, VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE,\n         VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE, VK_IMAGE_LAYOUT_UNDEFINED,\n         VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL},\n    };\n    VkAttachmentReference ref = {0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};\n    VkSubpassDescription subpasses[] = {\n        {0, VK_PIPELINE_BIND_POINT_GRAPHICS, 0, nullptr, 1, &ref, nullptr, nullptr, 0, nullptr},\n    };\n    VkSubpassDependency dep = {0,\n                               0,\n                               VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                               VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                               VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,\n                               VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,\n                               VK_DEPENDENCY_BY_REGION_BIT};\n    VkRenderPassCreateInfo rpci = {VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, nullptr, 0, 1, attach, 1, subpasses, 1, &dep};\n    VkRenderPass rp;\n    VkRenderPass rp_noselfdep;\n\n    VkResult err = vk::CreateRenderPass(m_device->device(), &rpci, nullptr, &rp);\n    ASSERT_VK_SUCCESS(err);\n    rpci.dependencyCount = 0;\n    rpci.pDependencies = nullptr;\n    err = vk::CreateRenderPass(m_device->device(), &rpci, nullptr, &rp_noselfdep);\n    ASSERT_VK_SUCCESS(err);\n\n    VkImageObj image(m_device);\n    image.InitNoLayout(32, 32, 1, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL, 0);\n    VkImageView imageView = image.targetView(VK_FORMAT_R8G8B8A8_UNORM);\n\n    VkFramebufferCreateInfo fbci = {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, nullptr, 0, rp, 1, &imageView, 32, 32, 1};\n    VkFramebuffer fb;\n    err = vk::CreateFramebuffer(m_device->device(), &fbci, nullptr, &fb);\n    ASSERT_VK_SUCCESS(err);\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    m_commandBuffer->begin();\n    VkRenderPassBeginInfo rpbi = {VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,\n                                  nullptr,\n                                  rp_noselfdep,\n                                  fb,\n                                  {{\n                                       0,\n                                       0,\n                                   },\n                                   {32, 32}},\n                                  0,\n                                  nullptr};\n\n    vk::CmdBeginRenderPass(m_commandBuffer->handle(), &rpbi, VK_SUBPASS_CONTENTS_INLINE);\n    VkMemoryBarrier mem_barrier = {};\n    mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;\n    mem_barrier.pNext = NULL;\n    mem_barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;\n    mem_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, 0, 1,\n                           &mem_barrier, 0, nullptr, 0, nullptr);\n    m_errorMonitor->VerifyFound();\n    vk::CmdEndRenderPass(m_commandBuffer->handle());\n\n    rpbi.renderPass = rp;\n    vk::CmdBeginRenderPass(m_commandBuffer->handle(), &rpbi, VK_SUBPASS_CONTENTS_INLINE);\n    VkImageMemoryBarrier img_barrier = {};\n    img_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;\n    img_barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\n    img_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\n    img_barrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n    img_barrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n    img_barrier.image = image.handle();\n    img_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    img_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    img_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    img_barrier.subresourceRange.baseArrayLayer = 0;\n    img_barrier.subresourceRange.baseMipLevel = 0;\n    img_barrier.subresourceRange.layerCount = 1;\n    img_barrier.subresourceRange.levelCount = 1;\n    \/\/ Mis-match src stage mask\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                           VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 1, &img_barrier);\n    m_errorMonitor->VerifyFound();\n    \/\/ Now mis-match dst stage mask\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_HOST_BIT,\n                           VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 1, &img_barrier);\n    m_errorMonitor->VerifyFound();\n    \/\/ Set srcQueueFamilyIndex to something other than IGNORED\n    img_barrier.srcQueueFamilyIndex = 0;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-srcQueueFamilyIndex-01182\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                           VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 1,\n                           &img_barrier);\n    m_errorMonitor->VerifyFound();\n    img_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    \/\/ Mis-match mem barrier src access mask\n    mem_barrier = {};\n    mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;\n    mem_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;\n    mem_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                           VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_DEPENDENCY_BY_REGION_BIT, 1, &mem_barrier, 0, nullptr,\n                           0, nullptr);\n    m_errorMonitor->VerifyFound();\n    \/\/ Mis-match mem barrier dst access mask. Also set srcAccessMask to 0 which should not cause an error\n    mem_barrier.srcAccessMask = 0;\n    mem_barrier.dstAccessMask = VK_ACCESS_HOST_WRITE_BIT;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                           VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_DEPENDENCY_BY_REGION_BIT, 1, &mem_barrier, 0, nullptr,\n                           0, nullptr);\n    m_errorMonitor->VerifyFound();\n    \/\/ Mis-match image barrier src access mask\n    img_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                           VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 1,\n                           &img_barrier);\n    m_errorMonitor->VerifyFound();\n    \/\/ Mis-match image barrier dst access mask\n    img_barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\n    img_barrier.dstAccessMask = VK_ACCESS_HOST_WRITE_BIT;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                           VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 1,\n                           &img_barrier);\n    m_errorMonitor->VerifyFound();\n    \/\/ Mis-match dependencyFlags\n    img_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-pDependencies-02285\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                           VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0 \/* wrong *\/, 0, nullptr, 0, nullptr, 1, &img_barrier);\n    m_errorMonitor->VerifyFound();\n    \/\/ Send non-zero bufferMemoryBarrierCount\n    \/\/ Construct a valid BufferMemoryBarrier to avoid any parameter errors\n    \/\/ First we need a valid buffer to reference\n    VkBufferObj buffer;\n    VkMemoryPropertyFlags mem_reqs = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;\n    buffer.init_as_src_and_dst(*m_device, 256, mem_reqs);\n    VkBufferMemoryBarrier bmb = {};\n    bmb.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;\n    bmb.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;\n    bmb.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;\n    bmb.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    bmb.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    bmb.buffer = buffer.handle();\n    bmb.offset = 0;\n    bmb.size = VK_WHOLE_SIZE;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-bufferMemoryBarrierCount-01178\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                           VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 1, &bmb, 0,\n                           nullptr);\n    m_errorMonitor->VerifyFound();\n    \/\/ Add image barrier w\/ image handle that's not in framebuffer\n    VkImageObj lone_image(m_device);\n    lone_image.InitNoLayout(32, 32, 1, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL, 0);\n    img_barrier.image = lone_image.handle();\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-image-02635\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                           VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 1,\n                           &img_barrier);\n    m_errorMonitor->VerifyFound();\n    \/\/ Have image barrier with mis-matched layouts\n    img_barrier.image = image.handle();\n    img_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-oldLayout-01181\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                           VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 1,\n                           &img_barrier);\n    m_errorMonitor->VerifyFound();\n\n    img_barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL;\n    img_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-oldLayout-02636\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                           VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 1,\n                           &img_barrier);\n    m_errorMonitor->VerifyFound();\n    vk::CmdEndRenderPass(m_commandBuffer->handle());\n\n    vk::DestroyFramebuffer(m_device->device(), fb, nullptr);\n    vk::DestroyRenderPass(m_device->device(), rp, nullptr);\n    vk::DestroyRenderPass(m_device->device(), rp_noselfdep, nullptr);\n}\n\nTEST_F(VkLayerTest, InvalidCmdBufferBufferDestroyed) {\n    TEST_DESCRIPTION(\"Attempt to draw with a command buffer that is invalid due to a buffer dependency being destroyed.\");\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkBuffer buffer;\n    VkDeviceMemory mem;\n    VkMemoryRequirements mem_reqs;\n\n    VkBufferCreateInfo buf_info = {};\n    buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;\n    buf_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;\n    buf_info.size = 256;\n    buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n    VkResult err = vk::CreateBuffer(m_device->device(), &buf_info, NULL, &buffer);\n    ASSERT_VK_SUCCESS(err);\n\n    vk::GetBufferMemoryRequirements(m_device->device(), buffer, &mem_reqs);\n\n    VkMemoryAllocateInfo alloc_info = {};\n    alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n    alloc_info.allocationSize = mem_reqs.size;\n    bool pass = false;\n    pass = m_device->phy().set_memory_type(mem_reqs.memoryTypeBits, &alloc_info, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);\n    if (!pass) {\n        printf(\"%s Failed to set memory type.\\n\", kSkipPrefix);\n        vk::DestroyBuffer(m_device->device(), buffer, NULL);\n        return;\n    }\n    err = vk::AllocateMemory(m_device->device(), &alloc_info, NULL, &mem);\n    ASSERT_VK_SUCCESS(err);\n\n    err = vk::BindBufferMemory(m_device->device(), buffer, mem, 0);\n    ASSERT_VK_SUCCESS(err);\n\n    m_commandBuffer->begin();\n    vk::CmdFillBuffer(m_commandBuffer->handle(), buffer, 0, VK_WHOLE_SIZE, 0);\n    m_commandBuffer->end();\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkBuffer\");\n    \/\/ Destroy buffer dependency prior to submit to cause ERROR\n    vk::DestroyBuffer(m_device->device(), buffer, NULL);\n\n    VkSubmitInfo submit_info = {};\n    submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;\n    submit_info.commandBufferCount = 1;\n    submit_info.pCommandBuffers = &m_commandBuffer->handle();\n    vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);\n\n    m_errorMonitor->VerifyFound();\n    vk::QueueWaitIdle(m_device->m_queue);\n    vk::FreeMemory(m_device->handle(), mem, NULL);\n}\n\nTEST_F(VkLayerTest, InvalidCmdBufferBufferViewDestroyed) {\n    TEST_DESCRIPTION(\"Delete bufferView bound to cmd buffer, then attempt to submit cmd buffer.\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    OneOffDescriptorSet descriptor_set(m_device,\n                                       {\n                                           {0, VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr},\n                                       });\n    CreatePipelineHelper pipe(*this);\n    VkBufferCreateInfo buffer_create_info = {};\n    VkBufferViewCreateInfo bvci = {};\n    VkBufferView view;\n\n    {\n        uint32_t queue_family_index = 0;\n        buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;\n        buffer_create_info.size = 1024;\n        buffer_create_info.usage = VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;\n        buffer_create_info.queueFamilyIndexCount = 1;\n        buffer_create_info.pQueueFamilyIndices = &queue_family_index;\n        VkBufferObj buffer;\n        buffer.init(*m_device, buffer_create_info);\n\n        bvci.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;\n        bvci.buffer = buffer.handle();\n        bvci.format = VK_FORMAT_R32_SFLOAT;\n        bvci.range = VK_WHOLE_SIZE;\n\n        VkResult err = vk::CreateBufferView(m_device->device(), &bvci, NULL, &view);\n        ASSERT_VK_SUCCESS(err);\n\n        descriptor_set.WriteDescriptorBufferView(0, view);\n        descriptor_set.UpdateDescriptorSets();\n\n        char const *fsSource =\n            \"#version 450\\n\"\n            \"\\n\"\n            \"layout(set=0, binding=0, r32f) uniform readonly imageBuffer s;\\n\"\n            \"layout(location=0) out vec4 x;\\n\"\n            \"void main(){\\n\"\n            \"   x = imageLoad(s, 0);\\n\"\n            \"}\\n\";\n        VkShaderObj vs(m_device, bindStateVertShaderText, VK_SHADER_STAGE_VERTEX_BIT, this);\n        VkShaderObj fs(m_device, fsSource, VK_SHADER_STAGE_FRAGMENT_BIT, this);\n\n        pipe.InitInfo();\n        pipe.InitState();\n        pipe.shader_stages_ = {vs.GetStageCreateInfo(), fs.GetStageCreateInfo()};\n        pipe.pipeline_layout_ = VkPipelineLayoutObj(m_device, {&descriptor_set.layout_});\n        pipe.CreateGraphicsPipeline();\n\n        m_commandBuffer->begin();\n        m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);\n\n        VkViewport viewport = {0, 0, 16, 16, 0, 1};\n        vk::CmdSetViewport(m_commandBuffer->handle(), 0, 1, &viewport);\n        VkRect2D scissor = {{0, 0}, {16, 16}};\n        vk::CmdSetScissor(m_commandBuffer->handle(), 0, 1, &scissor);\n        \/\/ Bind pipeline to cmd buffer - This causes crash on Mali\n        vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_);\n        vk::CmdBindDescriptorSets(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_layout_.handle(), 0, 1,\n                                  &descriptor_set.set_, 0, nullptr);\n    }\n    \/\/ buffer is released.\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"Descriptor in binding #0 index 0 is using buffer\");\n    m_commandBuffer->Draw(1, 0, 0, 0);\n    m_errorMonitor->VerifyFound();\n\n    vk::DestroyBufferView(m_device->device(), view, NULL);\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"Descriptor in binding #0 index 0 is using bufferView\");\n    m_commandBuffer->Draw(1, 0, 0, 0);\n    m_errorMonitor->VerifyFound();\n\n    VkBufferObj buffer;\n    buffer.init(*m_device, buffer_create_info);\n\n    bvci.buffer = buffer.handle();\n    VkResult err = vk::CreateBufferView(m_device->device(), &bvci, NULL, &view);\n    ASSERT_VK_SUCCESS(err);\n    descriptor_set.descriptor_writes.clear();\n    descriptor_set.WriteDescriptorBufferView(0, view);\n    descriptor_set.UpdateDescriptorSets();\n\n    vk::CmdBindDescriptorSets(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_layout_.handle(), 0, 1,\n                              &descriptor_set.set_, 0, nullptr);\n    m_commandBuffer->Draw(1, 0, 0, 0);\n    m_commandBuffer->EndRenderPass();\n    m_commandBuffer->end();\n\n    \/\/ Delete BufferView in order to invalidate cmd buffer\n    vk::DestroyBufferView(m_device->device(), view, NULL);\n    \/\/ Now attempt submit of cmd buffer\n    VkSubmitInfo submit_info = {};\n    submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;\n    submit_info.commandBufferCount = 1;\n    submit_info.pCommandBuffers = &m_commandBuffer->handle();\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkBufferView\");\n    vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, InvalidCmdBufferImageDestroyed) {\n    TEST_DESCRIPTION(\"Attempt to draw with a command buffer that is invalid due to an image dependency being destroyed.\");\n    ASSERT_NO_FATAL_FAILURE(Init());\n    {\n        const VkFormat tex_format = VK_FORMAT_B8G8R8A8_UNORM;\n        VkImageCreateInfo image_create_info = {};\n        image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n        image_create_info.pNext = NULL;\n        image_create_info.imageType = VK_IMAGE_TYPE_2D;\n        image_create_info.format = tex_format;\n        image_create_info.extent.width = 32;\n        image_create_info.extent.height = 32;\n        image_create_info.extent.depth = 1;\n        image_create_info.mipLevels = 1;\n        image_create_info.arrayLayers = 1;\n        image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n        image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n        image_create_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n        image_create_info.flags = 0;\n        VkImageObj image(m_device);\n        image.init(&image_create_info);\n\n        m_commandBuffer->begin();\n        VkClearColorValue ccv;\n        ccv.float32[0] = 1.0f;\n        ccv.float32[1] = 1.0f;\n        ccv.float32[2] = 1.0f;\n        ccv.float32[3] = 1.0f;\n        VkImageSubresourceRange isr = {};\n        isr.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n        isr.baseArrayLayer = 0;\n        isr.baseMipLevel = 0;\n        isr.layerCount = 1;\n        isr.levelCount = 1;\n        vk::CmdClearColorImage(m_commandBuffer->handle(), image.handle(), VK_IMAGE_LAYOUT_GENERAL, &ccv, 1, &isr);\n        m_commandBuffer->end();\n    }\n    \/\/ Destroy image dependency prior to submit to cause ERROR\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkImage\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkDeviceMemory\");\n\n    VkSubmitInfo submit_info = {};\n    submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;\n    submit_info.commandBufferCount = 1;\n    submit_info.pCommandBuffers = &m_commandBuffer->handle();\n    vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);\n\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, InvalidCmdBufferFramebufferImageDestroyed) {\n    TEST_DESCRIPTION(\n        \"Attempt to draw with a command buffer that is invalid due to a framebuffer image dependency being destroyed.\");\n    ASSERT_NO_FATAL_FAILURE(Init());\n    VkFormatProperties format_properties;\n    VkResult err = VK_SUCCESS;\n    vk::GetPhysicalDeviceFormatProperties(gpu(), VK_FORMAT_B8G8R8A8_UNORM, &format_properties);\n    if (!(format_properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) {\n        printf(\"%s Image format doesn't support required features.\\n\", kSkipPrefix);\n        return;\n    }\n    VkFramebuffer fb;\n    VkImageView view;\n\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n    {\n        VkImageCreateInfo image_ci = {};\n        image_ci.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n        image_ci.pNext = NULL;\n        image_ci.imageType = VK_IMAGE_TYPE_2D;\n        image_ci.format = VK_FORMAT_B8G8R8A8_UNORM;\n        image_ci.extent.width = 32;\n        image_ci.extent.height = 32;\n        image_ci.extent.depth = 1;\n        image_ci.mipLevels = 1;\n        image_ci.arrayLayers = 1;\n        image_ci.samples = VK_SAMPLE_COUNT_1_BIT;\n        image_ci.tiling = VK_IMAGE_TILING_OPTIMAL;\n        image_ci.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;\n        image_ci.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n        image_ci.flags = 0;\n        VkImageObj image(m_device);\n        image.init(&image_ci);\n\n        VkImageViewCreateInfo ivci = {\n            VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,\n            nullptr,\n            0,\n            image.handle(),\n            VK_IMAGE_VIEW_TYPE_2D,\n            VK_FORMAT_B8G8R8A8_UNORM,\n            {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A},\n            {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},\n        };\n        err = vk::CreateImageView(m_device->device(), &ivci, nullptr, &view);\n        ASSERT_VK_SUCCESS(err);\n\n        VkFramebufferCreateInfo fci = {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, nullptr, 0, m_renderPass, 1, &view, 32, 32, 1};\n        err = vk::CreateFramebuffer(m_device->device(), &fci, nullptr, &fb);\n        ASSERT_VK_SUCCESS(err);\n\n        \/\/ Just use default renderpass with our framebuffer\n        m_renderPassBeginInfo.framebuffer = fb;\n        m_renderPassBeginInfo.renderArea.extent.width = 32;\n        m_renderPassBeginInfo.renderArea.extent.height = 32;\n        \/\/ Create Null cmd buffer for submit\n        m_commandBuffer->begin();\n        m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);\n        m_commandBuffer->EndRenderPass();\n        m_commandBuffer->end();\n    }\n    \/\/ Destroy image attached to framebuffer to invalidate cmd buffer\n    \/\/ Now attempt to submit cmd buffer and verify error\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkImage\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkDeviceMemory\");\n    m_commandBuffer->QueueCommandBuffer(false);\n    m_errorMonitor->VerifyFound();\n\n    vk::DestroyFramebuffer(m_device->device(), fb, nullptr);\n    vk::DestroyImageView(m_device->device(), view, nullptr);\n}\n\nTEST_F(VkLayerTest, ImageMemoryNotBound) {\n    TEST_DESCRIPTION(\"Attempt to draw with an image which has not had memory bound to it.\");\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkImage image;\n    const VkFormat tex_format = VK_FORMAT_B8G8R8A8_UNORM;\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = tex_format;\n    image_create_info.extent.width = 32;\n    image_create_info.extent.height = 32;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n    image_create_info.flags = 0;\n    VkResult err = vk::CreateImage(m_device->device(), &image_create_info, NULL, &image);\n    ASSERT_VK_SUCCESS(err);\n    \/\/ Have to bind memory to image before recording cmd in cmd buffer using it\n    VkMemoryRequirements mem_reqs;\n    VkDeviceMemory image_mem;\n    bool pass;\n    VkMemoryAllocateInfo mem_alloc = {};\n    mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n    mem_alloc.pNext = NULL;\n    mem_alloc.memoryTypeIndex = 0;\n    vk::GetImageMemoryRequirements(m_device->device(), image, &mem_reqs);\n    mem_alloc.allocationSize = mem_reqs.size;\n    pass = m_device->phy().set_memory_type(mem_reqs.memoryTypeBits, &mem_alloc, 0);\n    ASSERT_TRUE(pass);\n    err = vk::AllocateMemory(m_device->device(), &mem_alloc, NULL, &image_mem);\n    ASSERT_VK_SUCCESS(err);\n\n    \/\/ Introduce error, do not call vk::BindImageMemory(m_device->device(), image, image_mem, 0);\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \" used with no memory bound. Memory should be bound by calling vkBindImageMemory().\");\n\n    m_commandBuffer->begin();\n    VkClearColorValue ccv;\n    ccv.float32[0] = 1.0f;\n    ccv.float32[1] = 1.0f;\n    ccv.float32[2] = 1.0f;\n    ccv.float32[3] = 1.0f;\n    VkImageSubresourceRange isr = {};\n    isr.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    isr.baseArrayLayer = 0;\n    isr.baseMipLevel = 0;\n    isr.layerCount = 1;\n    isr.levelCount = 1;\n    vk::CmdClearColorImage(m_commandBuffer->handle(), image, VK_IMAGE_LAYOUT_GENERAL, &ccv, 1, &isr);\n    m_commandBuffer->end();\n\n    m_errorMonitor->VerifyFound();\n    vk::DestroyImage(m_device->device(), image, NULL);\n    vk::FreeMemory(m_device->device(), image_mem, nullptr);\n}\n\nTEST_F(VkLayerTest, BufferMemoryNotBound) {\n    TEST_DESCRIPTION(\"Attempt to copy from a buffer which has not had memory bound to it.\");\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkImageObj image(m_device);\n    image.Init(128, 128, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,\n               VK_IMAGE_TILING_OPTIMAL, 0);\n    ASSERT_TRUE(image.initialized());\n\n    VkBuffer buffer;\n    VkDeviceMemory mem;\n    VkMemoryRequirements mem_reqs;\n\n    VkBufferCreateInfo buf_info = {};\n    buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;\n    buf_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;\n    buf_info.size = 1024;\n    buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n    VkResult err = vk::CreateBuffer(m_device->device(), &buf_info, NULL, &buffer);\n    ASSERT_VK_SUCCESS(err);\n\n    vk::GetBufferMemoryRequirements(m_device->device(), buffer, &mem_reqs);\n\n    VkMemoryAllocateInfo alloc_info = {};\n    alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;\n    alloc_info.allocationSize = 1024;\n    bool pass = false;\n    pass = m_device->phy().set_memory_type(mem_reqs.memoryTypeBits, &alloc_info, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);\n    if (!pass) {\n        printf(\"%s Failed to set memory type.\\n\", kSkipPrefix);\n        vk::DestroyBuffer(m_device->device(), buffer, NULL);\n        return;\n    }\n    err = vk::AllocateMemory(m_device->device(), &alloc_info, NULL, &mem);\n    ASSERT_VK_SUCCESS(err);\n\n    \/\/ Introduce failure by not calling vkBindBufferMemory(m_device->device(), buffer, mem, 0);\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \" used with no memory bound. Memory should be bound by calling vkBindBufferMemory().\");\n    VkBufferImageCopy region = {};\n    region.bufferRowLength = 16;\n    region.bufferImageHeight = 16;\n    region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n\n    region.imageSubresource.layerCount = 1;\n    region.imageExtent.height = 4;\n    region.imageExtent.width = 4;\n    region.imageExtent.depth = 1;\n    m_commandBuffer->begin();\n    vk::CmdCopyBufferToImage(m_commandBuffer->handle(), buffer, image.handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);\n    m_commandBuffer->end();\n\n    m_errorMonitor->VerifyFound();\n\n    vk::DestroyBuffer(m_device->device(), buffer, NULL);\n    vk::FreeMemory(m_device->handle(), mem, NULL);\n}\n\nTEST_F(VkLayerTest, MultiplaneImageLayoutBadAspectFlags) {\n    TEST_DESCRIPTION(\"Query layout of a multiplane image using illegal aspect flag masks\");\n\n    \/\/ Enable KHR multiplane req'd extensions\n    bool mp_extensions = InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,\n                                                    VK_KHR_GET_MEMORY_REQUIREMENTS_2_SPEC_VERSION);\n    if (mp_extensions) {\n        m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n    }\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE1_EXTENSION_NAME);\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);\n    if (mp_extensions) {\n        m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);\n    } else {\n        printf(\"%s test requires KHR multiplane extensions, not available.  Skipping.\\n\", kSkipPrefix);\n        return;\n    }\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    VkImageCreateInfo ci = {};\n    ci.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    ci.pNext = NULL;\n    ci.flags = 0;\n    ci.imageType = VK_IMAGE_TYPE_2D;\n    ci.format = VK_FORMAT_G8_B8R8_2PLANE_420_UNORM_KHR;\n    ci.extent = {128, 128, 1};\n    ci.mipLevels = 1;\n    ci.arrayLayers = 1;\n    ci.samples = VK_SAMPLE_COUNT_1_BIT;\n    ci.tiling = VK_IMAGE_TILING_LINEAR;\n    ci.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n    ci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n    ci.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n\n    \/\/ Verify formats\n    bool supported = ImageFormatAndFeaturesSupported(instance(), gpu(), ci, VK_FORMAT_FEATURE_TRANSFER_SRC_BIT);\n    ci.format = VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM_KHR;\n    supported = supported && ImageFormatAndFeaturesSupported(instance(), gpu(), ci, VK_FORMAT_FEATURE_TRANSFER_SRC_BIT);\n    if (!supported) {\n        printf(\"%s Multiplane image format not supported.  Skipping test.\\n\", kSkipPrefix);\n        return;  \/\/ Assume there's low ROI on searching for different mp formats\n    }\n\n    VkImage image_2plane, image_3plane;\n    ci.format = VK_FORMAT_G8_B8R8_2PLANE_420_UNORM_KHR;\n    VkResult err = vk::CreateImage(device(), &ci, NULL, &image_2plane);\n    ASSERT_VK_SUCCESS(err);\n\n    ci.format = VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM_KHR;\n    err = vk::CreateImage(device(), &ci, NULL, &image_3plane);\n    ASSERT_VK_SUCCESS(err);\n\n    \/\/ Query layout of 3rd plane, for a 2-plane image\n    VkImageSubresource subres = {};\n    subres.aspectMask = VK_IMAGE_ASPECT_PLANE_2_BIT_KHR;\n    subres.mipLevel = 0;\n    subres.arrayLayer = 0;\n    VkSubresourceLayout layout = {};\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkGetImageSubresourceLayout-format-01581\");\n    vk::GetImageSubresourceLayout(device(), image_2plane, &subres, &layout);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Query layout using color aspect, for a 3-plane image\n    subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkGetImageSubresourceLayout-format-01582\");\n    vk::GetImageSubresourceLayout(device(), image_3plane, &subres, &layout);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Clean up\n    vk::DestroyImage(device(), image_2plane, NULL);\n    vk::DestroyImage(device(), image_3plane, NULL);\n}\n\nTEST_F(VkLayerTest, InvalidBufferViewObject) {\n    \/\/ Create a single TEXEL_BUFFER descriptor and send it an invalid bufferView\n    \/\/ First, cause the bufferView to be invalid due to underlying buffer being destroyed\n    \/\/ Then destroy view itself and verify that same error is hit\n    VkResult err;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkWriteDescriptorSet-descriptorType-00323\");\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    OneOffDescriptorSet descriptor_set(m_device, {\n                                                     {0, VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1, VK_SHADER_STAGE_ALL, nullptr},\n                                                 });\n    VkBufferView view;\n    {\n        \/\/ Create a valid bufferView to start with\n        uint32_t queue_family_index = 0;\n        VkBufferCreateInfo buffer_create_info = {};\n        buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;\n        buffer_create_info.size = 1024;\n        buffer_create_info.usage = VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;\n        buffer_create_info.queueFamilyIndexCount = 1;\n        buffer_create_info.pQueueFamilyIndices = &queue_family_index;\n        VkBufferObj buffer;\n        buffer.init(*m_device, buffer_create_info);\n\n        VkBufferViewCreateInfo bvci = {};\n        bvci.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;\n        bvci.buffer = buffer.handle();\n        bvci.format = VK_FORMAT_R32_SFLOAT;\n        bvci.range = VK_WHOLE_SIZE;\n\n        err = vk::CreateBufferView(m_device->device(), &bvci, NULL, &view);\n        ASSERT_VK_SUCCESS(err);\n    }\n    \/\/ First Destroy buffer underlying view which should hit error in CV\n\n    VkWriteDescriptorSet descriptor_write;\n    memset(&descriptor_write, 0, sizeof(descriptor_write));\n    descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;\n    descriptor_write.dstSet = descriptor_set.set_;\n    descriptor_write.dstBinding = 0;\n    descriptor_write.descriptorCount = 1;\n    descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;\n    descriptor_write.pTexelBufferView = &view;\n\n    vk::UpdateDescriptorSets(m_device->device(), 1, &descriptor_write, 0, NULL);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Now destroy view itself and verify same error, which is hit in PV this time\n    vk::DestroyBufferView(m_device->device(), view, NULL);\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkWriteDescriptorSet-descriptorType-00323\");\n    vk::UpdateDescriptorSets(m_device->device(), 1, &descriptor_write, 0, NULL);\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, CreateBufferViewNoMemoryBoundToBuffer) {\n    TEST_DESCRIPTION(\"Attempt to create a buffer view with a buffer that has no memory bound to it.\");\n\n    VkResult err;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \" used with no memory bound. Memory should be bound by calling vkBindBufferMemory().\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    \/\/ Create a buffer with no bound memory and then attempt to create\n    \/\/ a buffer view.\n    VkBufferCreateInfo buff_ci = {};\n    buff_ci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;\n    buff_ci.usage = VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT;\n    buff_ci.size = 256;\n    buff_ci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n    VkBuffer buffer;\n    err = vk::CreateBuffer(m_device->device(), &buff_ci, NULL, &buffer);\n    ASSERT_VK_SUCCESS(err);\n\n    VkBufferViewCreateInfo buff_view_ci = {};\n    buff_view_ci.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;\n    buff_view_ci.buffer = buffer;\n    buff_view_ci.format = VK_FORMAT_R8_UNORM;\n    buff_view_ci.range = VK_WHOLE_SIZE;\n    VkBufferView buff_view;\n    err = vk::CreateBufferView(m_device->device(), &buff_view_ci, NULL, &buff_view);\n\n    m_errorMonitor->VerifyFound();\n    vk::DestroyBuffer(m_device->device(), buffer, NULL);\n    \/\/ If last error is success, it still created the view, so delete it.\n    if (err == VK_SUCCESS) {\n        vk::DestroyBufferView(m_device->device(), buff_view, NULL);\n    }\n}\n\nTEST_F(VkLayerTest, InvalidBufferViewCreateInfoEntries) {\n    TEST_DESCRIPTION(\"Attempt to create a buffer view with invalid create info.\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    const VkPhysicalDeviceLimits &dev_limits = m_device->props.limits;\n    const VkDeviceSize minTexelBufferOffsetAlignment = dev_limits.minTexelBufferOffsetAlignment;\n    if (minTexelBufferOffsetAlignment == 1) {\n        printf(\"%s Test requires minTexelOffsetAlignment to not be equal to 1. \\n\", kSkipPrefix);\n        return;\n    }\n\n    const VkFormat format_with_uniform_texel_support = VK_FORMAT_R8G8B8A8_UNORM;\n    const char *format_with_uniform_texel_support_string = \"VK_FORMAT_R8G8B8A8_UNORM\";\n    const VkFormat format_without_texel_support = VK_FORMAT_R8G8B8_UNORM;\n    const char *format_without_texel_support_string = \"VK_FORMAT_R8G8B8_UNORM\";\n    VkFormatProperties format_properties;\n    vk::GetPhysicalDeviceFormatProperties(gpu(), format_with_uniform_texel_support, &format_properties);\n    if (!(format_properties.bufferFeatures & VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT)) {\n        printf(\"%s Test requires %s to support VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT\\n\", kSkipPrefix,\n               format_with_uniform_texel_support_string);\n        return;\n    }\n    vk::GetPhysicalDeviceFormatProperties(gpu(), format_without_texel_support, &format_properties);\n    if ((format_properties.bufferFeatures & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT) ||\n        (format_properties.bufferFeatures & VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT)) {\n        printf(\n            \"%s Test requires %s to not support VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT nor \"\n            \"VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT\\n\",\n            kSkipPrefix, format_without_texel_support_string);\n        return;\n    }\n\n    \/\/ Create a test buffer--buffer must have been created using VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT or\n    \/\/ VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, so use a different usage value instead to cause an error\n    const VkDeviceSize resource_size = 1024;\n    const VkBufferCreateInfo bad_buffer_info = VkBufferObj::create_info(resource_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);\n    VkBufferObj bad_buffer;\n    bad_buffer.init(*m_device, bad_buffer_info, (VkMemoryPropertyFlags)VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);\n\n    \/\/ Create a test buffer view\n    VkBufferViewCreateInfo buff_view_ci = {};\n    buff_view_ci.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;\n    buff_view_ci.buffer = bad_buffer.handle();\n    buff_view_ci.format = format_with_uniform_texel_support;\n    buff_view_ci.range = VK_WHOLE_SIZE;\n    CreateBufferViewTest(*this, &buff_view_ci, {\"VUID-VkBufferViewCreateInfo-buffer-00932\"});\n\n    \/\/ Create a better test buffer\n    const VkBufferCreateInfo buffer_info = VkBufferObj::create_info(resource_size, VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT);\n    VkBufferObj buffer;\n    buffer.init(*m_device, buffer_info, (VkMemoryPropertyFlags)VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);\n\n    \/\/ Offset must be less than the size of the buffer, so set it equal to the buffer size to cause an error\n    buff_view_ci.buffer = buffer.handle();\n    buff_view_ci.offset = buffer.create_info().size;\n    CreateBufferViewTest(*this, &buff_view_ci, {\"VUID-VkBufferViewCreateInfo-offset-00925\"});\n\n    \/\/ Offset must be a multiple of VkPhysicalDeviceLimits::minTexelBufferOffsetAlignment so add 1 to ensure it is not\n    buff_view_ci.offset = minTexelBufferOffsetAlignment + 1;\n    CreateBufferViewTest(*this, &buff_view_ci, {\"VUID-VkBufferViewCreateInfo-offset-02749\"});\n\n    \/\/ Set offset to acceptable value for range tests\n    buff_view_ci.offset = minTexelBufferOffsetAlignment;\n    \/\/ Setting range equal to 0 will cause an error to occur\n    buff_view_ci.range = 0;\n    CreateBufferViewTest(*this, &buff_view_ci, {\"VUID-VkBufferViewCreateInfo-range-00928\"});\n\n    uint32_t format_size = FormatElementSize(buff_view_ci.format);\n    \/\/ Range must be a multiple of the element size of format, so add one to ensure it is not\n    buff_view_ci.range = format_size + 1;\n    CreateBufferViewTest(*this, &buff_view_ci, {\"VUID-VkBufferViewCreateInfo-range-00929\"});\n\n    \/\/ Twice the element size of format multiplied by VkPhysicalDeviceLimits::maxTexelBufferElements guarantees range divided by the\n    \/\/ element size is greater than maxTexelBufferElements, causing failure\n    buff_view_ci.range = 2 * static_cast<VkDeviceSize>(format_size) * static_cast<VkDeviceSize>(dev_limits.maxTexelBufferElements);\n    CreateBufferViewTest(*this, &buff_view_ci,\n                         {\"VUID-VkBufferViewCreateInfo-range-00930\", \"VUID-VkBufferViewCreateInfo-offset-00931\"});\n\n    \/\/ Set rage to acceptable value for buffer tests\n    buff_view_ci.format = format_without_texel_support;\n    buff_view_ci.range = VK_WHOLE_SIZE;\n\n    \/\/ `buffer` was created using VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT so we can use that for the first buffer test\n    CreateBufferViewTest(*this, &buff_view_ci, {\"VUID-VkBufferViewCreateInfo-buffer-00933\"});\n\n    \/\/ Create a new buffer using VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT\n    const VkBufferCreateInfo storage_buffer_info =\n        VkBufferObj::create_info(resource_size, VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT);\n    VkBufferObj storage_buffer;\n    storage_buffer.init(*m_device, storage_buffer_info, (VkMemoryPropertyFlags)VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);\n\n    buff_view_ci.buffer = storage_buffer.handle();\n    CreateBufferViewTest(*this, &buff_view_ci, {\"VUID-VkBufferViewCreateInfo-buffer-00934\"});\n}\n\nTEST_F(VkLayerTest, InvalidTexelBufferAlignment) {\n    TEST_DESCRIPTION(\"Test VK_EXT_texel_buffer_alignment.\");\n\n    if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {\n        m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n    } else {\n        printf(\"%s Did not find required instance extension %s; skipped.\\n\", kSkipPrefix,\n               VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n        return;\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    std::array<const char *, 1> required_device_extensions = {{VK_EXT_TEXEL_BUFFER_ALIGNMENT_EXTENSION_NAME}};\n    for (auto device_extension : required_device_extensions) {\n        if (DeviceExtensionSupported(gpu(), nullptr, device_extension)) {\n            m_device_extension_names.push_back(device_extension);\n        } else {\n            printf(\"%s %s Extension not supported, skipping tests\\n\", kSkipPrefix, device_extension);\n            return;\n        }\n    }\n\n    if (DeviceIsMockICD() || DeviceSimulation()) {\n        printf(\"%s MockICD does not support this feature, skipping tests\\n\", kSkipPrefix);\n        return;\n    }\n\n    PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =\n        (PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), \"vkGetPhysicalDeviceFeatures2KHR\");\n    ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);\n\n    \/\/ Create a device that enables texel_buffer_alignment\n    auto texel_buffer_alignment_features = lvl_init_struct<VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT>();\n    auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&texel_buffer_alignment_features);\n    vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);\n    texel_buffer_alignment_features.texelBufferAlignment = VK_TRUE;\n\n    VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT align_props = {};\n    align_props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_PROPERTIES_EXT;\n    VkPhysicalDeviceProperties2 pd_props2 = {};\n    pd_props2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;\n    pd_props2.pNext = &align_props;\n    vk::GetPhysicalDeviceProperties2(gpu(), &pd_props2);\n\n    ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &features2));\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    const VkFormat format_with_uniform_texel_support = VK_FORMAT_R8G8B8A8_UNORM;\n\n    const VkDeviceSize resource_size = 1024;\n    VkBufferCreateInfo buffer_info = VkBufferObj::create_info(\n        resource_size, VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT);\n    VkBufferObj buffer;\n    buffer.init(*m_device, buffer_info, (VkMemoryPropertyFlags)VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);\n\n    \/\/ Create a test buffer view\n    VkBufferViewCreateInfo buff_view_ci = {};\n    buff_view_ci.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;\n    buff_view_ci.buffer = buffer.handle();\n    buff_view_ci.format = format_with_uniform_texel_support;\n    buff_view_ci.range = VK_WHOLE_SIZE;\n\n    buff_view_ci.offset = 1;\n    std::vector<std::string> expectedErrors;\n    if (buff_view_ci.offset < align_props.storageTexelBufferOffsetAlignmentBytes) {\n        expectedErrors.push_back(\"VUID-VkBufferViewCreateInfo-buffer-02750\");\n    }\n    if (buff_view_ci.offset < align_props.uniformTexelBufferOffsetAlignmentBytes) {\n        expectedErrors.push_back(\"VUID-VkBufferViewCreateInfo-buffer-02751\");\n    }\n    CreateBufferViewTest(*this, &buff_view_ci, expectedErrors);\n    expectedErrors.clear();\n\n    buff_view_ci.offset = 4;\n    if (buff_view_ci.offset < align_props.storageTexelBufferOffsetAlignmentBytes &&\n        !align_props.storageTexelBufferOffsetSingleTexelAlignment) {\n        expectedErrors.push_back(\"VUID-VkBufferViewCreateInfo-buffer-02750\");\n    }\n    if (buff_view_ci.offset < align_props.uniformTexelBufferOffsetAlignmentBytes &&\n        !align_props.uniformTexelBufferOffsetSingleTexelAlignment) {\n        expectedErrors.push_back(\"VUID-VkBufferViewCreateInfo-buffer-02751\");\n    }\n    CreateBufferViewTest(*this, &buff_view_ci, expectedErrors);\n    expectedErrors.clear();\n\n    \/\/ Test a 3-component format\n    VkFormatProperties format_properties;\n    vk::GetPhysicalDeviceFormatProperties(gpu(), VK_FORMAT_R32G32B32_SFLOAT, &format_properties);\n    if (format_properties.bufferFeatures & VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT) {\n        buffer_info.usage = VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT;\n        VkBufferObj buffer2;\n        buffer2.init(*m_device, buffer_info, (VkMemoryPropertyFlags)VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);\n\n        \/\/ Create a test buffer view\n        buff_view_ci.buffer = buffer2.handle();\n\n        buff_view_ci.format = VK_FORMAT_R32G32B32_SFLOAT;\n        buff_view_ci.offset = 1;\n        if (buff_view_ci.offset < align_props.uniformTexelBufferOffsetAlignmentBytes) {\n            expectedErrors.push_back(\"VUID-VkBufferViewCreateInfo-buffer-02751\");\n        }\n        CreateBufferViewTest(*this, &buff_view_ci, expectedErrors);\n        expectedErrors.clear();\n\n        buff_view_ci.offset = 4;\n        if (buff_view_ci.offset < align_props.uniformTexelBufferOffsetAlignmentBytes &&\n            !align_props.uniformTexelBufferOffsetSingleTexelAlignment) {\n            expectedErrors.push_back(\"VUID-VkBufferViewCreateInfo-buffer-02751\");\n        }\n        CreateBufferViewTest(*this, &buff_view_ci, expectedErrors);\n        expectedErrors.clear();\n    }\n}\n\nTEST_F(VkLayerTest, FillBufferWithinRenderPass) {\n    \/\/ Call CmdFillBuffer within an active renderpass\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdFillBuffer-renderpass\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    m_commandBuffer->begin();\n    m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);\n\n    VkMemoryPropertyFlags reqs = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;\n    VkBufferObj dstBuffer;\n    dstBuffer.init_as_dst(*m_device, (VkDeviceSize)1024, reqs);\n\n    m_commandBuffer->FillBuffer(dstBuffer.handle(), 0, 4, 0x11111111);\n\n    m_errorMonitor->VerifyFound();\n\n    m_commandBuffer->EndRenderPass();\n    m_commandBuffer->end();\n}\n\nTEST_F(VkLayerTest, UpdateBufferWithinRenderPass) {\n    \/\/ Call CmdUpdateBuffer within an active renderpass\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdUpdateBuffer-renderpass\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    m_commandBuffer->begin();\n    m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);\n\n    VkMemoryPropertyFlags reqs = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;\n    VkBufferObj dstBuffer;\n    dstBuffer.init_as_dst(*m_device, (VkDeviceSize)1024, reqs);\n\n    VkDeviceSize dstOffset = 0;\n    uint32_t Data[] = {1, 2, 3, 4, 5, 6, 7, 8};\n    VkDeviceSize dataSize = sizeof(Data) \/ sizeof(uint32_t);\n    vk::CmdUpdateBuffer(m_commandBuffer->handle(), dstBuffer.handle(), dstOffset, dataSize, &Data);\n\n    m_errorMonitor->VerifyFound();\n\n    m_commandBuffer->EndRenderPass();\n    m_commandBuffer->end();\n}\n\nTEST_F(VkLayerTest, ClearColorImageWithBadRange) {\n    TEST_DESCRIPTION(\"Record clear color with an invalid VkImageSubresourceRange\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    VkImageObj image(m_device);\n    image.Init(32, 32, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_TILING_OPTIMAL);\n    ASSERT_TRUE(image.create_info().arrayLayers == 1);\n    ASSERT_TRUE(image.initialized());\n    image.SetLayout(VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);\n\n    const VkClearColorValue clear_color = {{0.0f, 0.0f, 0.0f, 1.0f}};\n\n    m_commandBuffer->begin();\n    const auto cb_handle = m_commandBuffer->handle();\n\n    \/\/ Try baseMipLevel >= image.mipLevels with VK_REMAINING_MIP_LEVELS\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-baseMipLevel-01470\");\n        const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_REMAINING_MIP_LEVELS, 0, 1};\n        vk::CmdClearColorImage(cb_handle, image.handle(), image.Layout(), &clear_color, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try baseMipLevel >= image.mipLevels without VK_REMAINING_MIP_LEVELS\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-baseMipLevel-01470\");\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-pRanges-01692\");\n        const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 1, 1, 0, 1};\n        vk::CmdClearColorImage(cb_handle, image.handle(), image.Layout(), &clear_color, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try levelCount = 0\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-pRanges-01692\");\n        const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 0, 1};\n        vk::CmdClearColorImage(cb_handle, image.handle(), image.Layout(), &clear_color, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try baseMipLevel + levelCount > image.mipLevels\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-pRanges-01692\");\n        const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 2, 0, 1};\n        vk::CmdClearColorImage(cb_handle, image.handle(), image.Layout(), &clear_color, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try baseArrayLayer >= image.arrayLayers with VK_REMAINING_ARRAY_LAYERS\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-baseArrayLayer-01472\");\n        const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 1, VK_REMAINING_ARRAY_LAYERS};\n        vk::CmdClearColorImage(cb_handle, image.handle(), image.Layout(), &clear_color, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try baseArrayLayer >= image.arrayLayers without VK_REMAINING_ARRAY_LAYERS\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-baseArrayLayer-01472\");\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-pRanges-01693\");\n        const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 1, 1};\n        vk::CmdClearColorImage(cb_handle, image.handle(), image.Layout(), &clear_color, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try layerCount = 0\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-pRanges-01693\");\n        const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 0};\n        vk::CmdClearColorImage(cb_handle, image.handle(), image.Layout(), &clear_color, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try baseArrayLayer + layerCount > image.arrayLayers\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-pRanges-01693\");\n        const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 2};\n        vk::CmdClearColorImage(cb_handle, image.handle(), image.Layout(), &clear_color, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n}\n\nTEST_F(VkLayerTest, ClearDepthStencilWithBadRange) {\n    TEST_DESCRIPTION(\"Record clear depth with an invalid VkImageSubresourceRange\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    const auto depth_format = FindSupportedDepthStencilFormat(gpu());\n    if (!depth_format) {\n        printf(\"%s No Depth + Stencil format found. Skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkImageObj image(m_device);\n    image.Init(32, 32, 1, depth_format, VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_TILING_OPTIMAL);\n    ASSERT_TRUE(image.create_info().arrayLayers == 1);\n    ASSERT_TRUE(image.initialized());\n    const VkImageAspectFlags ds_aspect = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;\n    image.SetLayout(ds_aspect, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);\n\n    const VkClearDepthStencilValue clear_value = {};\n\n    m_commandBuffer->begin();\n    const auto cb_handle = m_commandBuffer->handle();\n\n    \/\/ Try baseMipLevel >= image.mipLevels with VK_REMAINING_MIP_LEVELS\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearDepthStencilImage-baseMipLevel-01474\");\n        const VkImageSubresourceRange range = {ds_aspect, 1, VK_REMAINING_MIP_LEVELS, 0, 1};\n        vk::CmdClearDepthStencilImage(cb_handle, image.handle(), image.Layout(), &clear_value, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try baseMipLevel >= image.mipLevels without VK_REMAINING_MIP_LEVELS\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearDepthStencilImage-baseMipLevel-01474\");\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearDepthStencilImage-pRanges-01694\");\n        const VkImageSubresourceRange range = {ds_aspect, 1, 1, 0, 1};\n        vk::CmdClearDepthStencilImage(cb_handle, image.handle(), image.Layout(), &clear_value, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try levelCount = 0\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearDepthStencilImage-pRanges-01694\");\n        const VkImageSubresourceRange range = {ds_aspect, 0, 0, 0, 1};\n        vk::CmdClearDepthStencilImage(cb_handle, image.handle(), image.Layout(), &clear_value, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try baseMipLevel + levelCount > image.mipLevels\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearDepthStencilImage-pRanges-01694\");\n        const VkImageSubresourceRange range = {ds_aspect, 0, 2, 0, 1};\n        vk::CmdClearDepthStencilImage(cb_handle, image.handle(), image.Layout(), &clear_value, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try baseArrayLayer >= image.arrayLayers with VK_REMAINING_ARRAY_LAYERS\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                             \"VUID-vkCmdClearDepthStencilImage-baseArrayLayer-01476\");\n        const VkImageSubresourceRange range = {ds_aspect, 0, 1, 1, VK_REMAINING_ARRAY_LAYERS};\n        vk::CmdClearDepthStencilImage(cb_handle, image.handle(), image.Layout(), &clear_value, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try baseArrayLayer >= image.arrayLayers without VK_REMAINING_ARRAY_LAYERS\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                             \"VUID-vkCmdClearDepthStencilImage-baseArrayLayer-01476\");\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearDepthStencilImage-pRanges-01695\");\n        const VkImageSubresourceRange range = {ds_aspect, 0, 1, 1, 1};\n        vk::CmdClearDepthStencilImage(cb_handle, image.handle(), image.Layout(), &clear_value, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try layerCount = 0\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearDepthStencilImage-pRanges-01695\");\n        const VkImageSubresourceRange range = {ds_aspect, 0, 1, 0, 0};\n        vk::CmdClearDepthStencilImage(cb_handle, image.handle(), image.Layout(), &clear_value, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ Try baseArrayLayer + layerCount > image.arrayLayers\n    {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearDepthStencilImage-pRanges-01695\");\n        const VkImageSubresourceRange range = {ds_aspect, 0, 1, 0, 2};\n        vk::CmdClearDepthStencilImage(cb_handle, image.handle(), image.Layout(), &clear_value, 1, &range);\n        m_errorMonitor->VerifyFound();\n    }\n}\n\nTEST_F(VkLayerTest, ClearColorImageWithinRenderPass) {\n    \/\/ Call CmdClearColorImage within an active RenderPass\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-renderpass\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    m_commandBuffer->begin();\n    m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);\n\n    VkClearColorValue clear_color;\n    memset(clear_color.uint32, 0, sizeof(uint32_t) * 4);\n    const VkFormat tex_format = VK_FORMAT_B8G8R8A8_UNORM;\n    const int32_t tex_width = 32;\n    const int32_t tex_height = 32;\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = tex_format;\n    image_create_info.extent.width = tex_width;\n    image_create_info.extent.height = tex_height;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n\n    VkImageObj dstImage(m_device);\n    dstImage.init(&image_create_info);\n\n    const VkImageSubresourceRange range = VkImageObj::subresource_range(image_create_info, VK_IMAGE_ASPECT_COLOR_BIT);\n\n    vk::CmdClearColorImage(m_commandBuffer->handle(), dstImage.handle(), VK_IMAGE_LAYOUT_GENERAL, &clear_color, 1, &range);\n\n    m_errorMonitor->VerifyFound();\n\n    m_commandBuffer->EndRenderPass();\n    m_commandBuffer->end();\n}\n\nTEST_F(VkLayerTest, ClearDepthStencilImageErrors) {\n    \/\/ Hit errors related to vk::CmdClearDepthStencilImage()\n    \/\/ 1. Use an image that doesn't have VK_IMAGE_USAGE_TRANSFER_DST_BIT set\n    \/\/ 2. Call CmdClearDepthStencilImage within an active RenderPass\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    auto depth_format = FindSupportedDepthStencilFormat(gpu());\n    if (!depth_format) {\n        printf(\"%s No Depth + Stencil format found. Skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkClearDepthStencilValue clear_value = {0};\n    VkImageCreateInfo image_create_info = VkImageObj::create_info();\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = depth_format;\n    image_create_info.extent.width = 64;\n    image_create_info.extent.height = 64;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    \/\/ Error here is that VK_IMAGE_USAGE_TRANSFER_DST_BIT is excluded for DS image that we'll call Clear on below\n    image_create_info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;\n\n    VkImageObj dst_image_bad_usage(m_device);\n    dst_image_bad_usage.init(&image_create_info);\n    const VkImageSubresourceRange range = VkImageObj::subresource_range(image_create_info, VK_IMAGE_ASPECT_DEPTH_BIT);\n\n    m_commandBuffer->begin();\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearDepthStencilImage-image-00009\");\n    vk::CmdClearDepthStencilImage(m_commandBuffer->handle(), dst_image_bad_usage.handle(), VK_IMAGE_LAYOUT_GENERAL, &clear_value, 1,\n                                  &range);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Fix usage for next test case\n    image_create_info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n    VkImageObj dst_image(m_device);\n    dst_image.init(&image_create_info);\n\n    m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearDepthStencilImage-renderpass\");\n    vk::CmdClearDepthStencilImage(m_commandBuffer->handle(), dst_image.handle(), VK_IMAGE_LAYOUT_GENERAL, &clear_value, 1, &range);\n    m_errorMonitor->VerifyFound();\n\n    m_commandBuffer->EndRenderPass();\n    m_commandBuffer->end();\n}\n\nTEST_F(VkLayerTest, BufferMemoryBarrierNoBuffer) {\n    \/\/ Try to add a buffer memory barrier with no buffer.\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"required parameter pBufferMemoryBarriers[0].buffer specified as VK_NULL_HANDLE\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    m_commandBuffer->begin();\n\n    VkBufferMemoryBarrier buf_barrier = {};\n    buf_barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;\n    buf_barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;\n    buf_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;\n    buf_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    buf_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    buf_barrier.buffer = VK_NULL_HANDLE;\n    buf_barrier.offset = 0;\n    buf_barrier.size = VK_WHOLE_SIZE;\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, 0, 0,\n                           nullptr, 1, &buf_barrier, 0, nullptr);\n\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, InvalidBarriers) {\n    TEST_DESCRIPTION(\"A variety of ways to get VK_INVALID_BARRIER \");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    auto depth_format = FindSupportedDepthStencilFormat(gpu());\n    if (!depth_format) {\n        printf(\"%s No Depth + Stencil format found. Skipped.\\n\", kSkipPrefix);\n        return;\n    }\n    \/\/ Add a token self-dependency for this test to avoid unexpected errors\n    m_addRenderPassSelfDependency = true;\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    const uint32_t submit_family = m_device->graphics_queue_node_index_;\n    const uint32_t invalid = static_cast<uint32_t>(m_device->queue_props.size());\n    const uint32_t other_family = submit_family != 0 ? 0 : 1;\n    const bool only_one_family = (invalid == 1) || (m_device->queue_props[other_family].queueCount == 0);\n    std::vector<uint32_t> qf_indices{{submit_family, other_family}};\n    if (only_one_family) {\n        qf_indices.resize(1);\n    }\n    BarrierQueueFamilyTestHelper::Context test_context(this, qf_indices);\n\n    \/\/ Use image unbound to memory in barrier\n    \/\/ Use buffer unbound to memory in barrier\n    BarrierQueueFamilyTestHelper conc_test(&test_context);\n    conc_test.Init(nullptr, false, false);\n\n    conc_test.image_barrier_.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n    conc_test(\" used with no memory bound. Memory should be bound by calling vkBindImageMemory()\",\n              \" used with no memory bound. Memory should be bound by calling vkBindBufferMemory()\");\n\n    VkBufferObj buffer;\n    VkMemoryPropertyFlags mem_reqs = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;\n    buffer.init_as_src_and_dst(*m_device, 256, mem_reqs);\n    conc_test.buffer_barrier_.buffer = buffer.handle();\n\n    VkImageObj image(m_device);\n    image.Init(128, 128, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL, 0);\n    conc_test.image_barrier_.image = image.handle();\n\n    \/\/ New layout can't be UNDEFINED\n    conc_test.image_barrier_.newLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n    conc_test(\"VUID-VkImageMemoryBarrier-newLayout-01198\", \"\");\n\n    \/\/ Transition image to color attachment optimal\n    conc_test.image_barrier_.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n    conc_test(\"\");\n\n    \/\/ TODO: this looks vestigal or incomplete...\n    m_commandBuffer->begin();\n    m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);\n\n    \/\/ Can't send buffer memory barrier during a render pass\n    vk::CmdEndRenderPass(m_commandBuffer->handle());\n\n    \/\/ Duplicate barriers that change layout\n    VkImageMemoryBarrier img_barrier = {};\n    img_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;\n    img_barrier.pNext = NULL;\n    img_barrier.image = image.handle();\n    img_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n    img_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;\n    img_barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\n    img_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;\n    img_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    img_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    img_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    img_barrier.subresourceRange.baseArrayLayer = 0;\n    img_barrier.subresourceRange.baseMipLevel = 0;\n    img_barrier.subresourceRange.layerCount = 1;\n    img_barrier.subresourceRange.levelCount = 1;\n    VkImageMemoryBarrier img_barriers[2] = {img_barrier, img_barrier};\n\n    \/\/ Transitions from UNDEFINED  are valid, even if duplicated\n    m_errorMonitor->ExpectSuccess();\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                           VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 2,\n                           img_barriers);\n    m_errorMonitor->VerifyNotFound();\n\n    \/\/ Duplication of layout transitions (not from undefined) are not valid\n    img_barriers[0].oldLayout = VK_IMAGE_LAYOUT_GENERAL;\n    img_barriers[0].newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n    img_barriers[1].oldLayout = img_barriers[0].oldLayout;\n    img_barriers[1].newLayout = img_barriers[0].newLayout;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-oldLayout-01197\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,\n                           VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 2,\n                           img_barriers);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Exceed the buffer size\n    conc_test.buffer_barrier_.offset = conc_test.buffer_.create_info().size + 1;\n    conc_test(\"\", \"VUID-VkBufferMemoryBarrier-offset-01187\");\n\n    conc_test.buffer_barrier_.offset = 0;\n    conc_test.buffer_barrier_.size = conc_test.buffer_.create_info().size + 1;\n    \/\/ Size greater than total size\n    conc_test(\"\", \"VUID-VkBufferMemoryBarrier-size-01189\");\n\n    conc_test.buffer_barrier_.size = VK_WHOLE_SIZE;\n\n    \/\/ Now exercise barrier aspect bit errors, first DS\n    VkDepthStencilObj ds_image(m_device);\n    ds_image.Init(m_device, 128, 128, depth_format);\n    ASSERT_TRUE(ds_image.initialized());\n\n    conc_test.image_barrier_.oldLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;\n    conc_test.image_barrier_.newLayout = VK_IMAGE_LAYOUT_GENERAL;\n    conc_test.image_barrier_.image = ds_image.handle();\n\n    \/\/ Not having DEPTH or STENCIL set is an error\n    conc_test.image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_METADATA_BIT;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageSubresource-aspectMask-parameter\");\n    conc_test(\"VUID-VkImageMemoryBarrier-image-01207\");\n\n    \/\/ Having only one of depth or stencil set for DS image is an error\n    conc_test.image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;\n    conc_test(\"VUID-VkImageMemoryBarrier-image-01207\");\n\n    \/\/ Having anything other than DEPTH and STENCIL is an error\n    conc_test.image_barrier_.subresourceRange.aspectMask =\n        VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_COLOR_BIT;\n    conc_test(\"VUID-VkImageSubresource-aspectMask-parameter\");\n\n    \/\/ Now test depth-only\n    VkFormatProperties format_props;\n    vk::GetPhysicalDeviceFormatProperties(m_device->phy().handle(), VK_FORMAT_D16_UNORM, &format_props);\n    if (format_props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) {\n        VkDepthStencilObj d_image(m_device);\n        d_image.Init(m_device, 128, 128, VK_FORMAT_D16_UNORM);\n        ASSERT_TRUE(d_image.initialized());\n\n        conc_test.image_barrier_.oldLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;\n        conc_test.image_barrier_.newLayout = VK_IMAGE_LAYOUT_GENERAL;\n        conc_test.image_barrier_.image = d_image.handle();\n\n        \/\/ DEPTH bit must be set\n        conc_test.image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_METADATA_BIT;\n        conc_test(\"Depth-only image formats must have the VK_IMAGE_ASPECT_DEPTH_BIT set.\");\n\n        \/\/ No bits other than DEPTH may be set\n        conc_test.image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_COLOR_BIT;\n        conc_test(\"Depth-only image formats can have only the VK_IMAGE_ASPECT_DEPTH_BIT set.\");\n    }\n\n    \/\/ Now test stencil-only\n    vk::GetPhysicalDeviceFormatProperties(m_device->phy().handle(), VK_FORMAT_S8_UINT, &format_props);\n    if (format_props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) {\n        VkDepthStencilObj s_image(m_device);\n        s_image.Init(m_device, 128, 128, VK_FORMAT_S8_UINT);\n        ASSERT_TRUE(s_image.initialized());\n\n        conc_test.image_barrier_.oldLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;\n        conc_test.image_barrier_.newLayout = VK_IMAGE_LAYOUT_GENERAL;\n        conc_test.image_barrier_.image = s_image.handle();\n\n        \/\/ Use of COLOR aspect on depth image is error\n        conc_test.image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n        conc_test(\"Stencil-only image formats must have the VK_IMAGE_ASPECT_STENCIL_BIT set.\");\n    }\n\n    \/\/ Finally test color\n    VkImageObj c_image(m_device);\n    c_image.Init(128, 128, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL, 0);\n    ASSERT_TRUE(c_image.initialized());\n    conc_test.image_barrier_.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n    conc_test.image_barrier_.newLayout = VK_IMAGE_LAYOUT_GENERAL;\n    conc_test.image_barrier_.image = c_image.handle();\n\n    \/\/ COLOR bit must be set\n    conc_test.image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_METADATA_BIT;\n    conc_test(\"Color image formats must have the VK_IMAGE_ASPECT_COLOR_BIT set.\");\n\n    \/\/ No bits other than COLOR may be set\n    conc_test.image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT | VK_IMAGE_ASPECT_DEPTH_BIT;\n    conc_test(\"Color image formats must have ONLY the VK_IMAGE_ASPECT_COLOR_BIT set.\");\n\n    \/\/ A barrier's new and old VkImageLayout must be compatible with an image's VkImageUsageFlags.\n    {\n        VkImageObj img_color(m_device);\n        img_color.Init(128, 128, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL);\n        ASSERT_TRUE(img_color.initialized());\n\n        VkImageObj img_ds(m_device);\n        img_ds.Init(128, 128, 1, depth_format, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL);\n        ASSERT_TRUE(img_ds.initialized());\n\n        VkImageObj img_xfer_src(m_device);\n        img_xfer_src.Init(128, 128, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_IMAGE_TILING_OPTIMAL);\n        ASSERT_TRUE(img_xfer_src.initialized());\n\n        VkImageObj img_xfer_dst(m_device);\n        img_xfer_dst.Init(128, 128, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_TILING_OPTIMAL);\n        ASSERT_TRUE(img_xfer_dst.initialized());\n\n        VkImageObj img_sampled(m_device);\n        img_sampled.Init(32, 32, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_TILING_OPTIMAL);\n        ASSERT_TRUE(img_sampled.initialized());\n\n        VkImageObj img_input(m_device);\n        img_input.Init(128, 128, 1, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL);\n        ASSERT_TRUE(img_input.initialized());\n\n        const struct {\n            VkImageObj &image_obj;\n            VkImageLayout bad_layout;\n            std::string msg_code;\n        } bad_buffer_layouts[] = {\n            \/\/ clang-format off\n            \/\/ images _without_ VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT\n            {img_ds,       VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,         \"VUID-VkImageMemoryBarrier-oldLayout-01208\"},\n            {img_xfer_src, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,         \"VUID-VkImageMemoryBarrier-oldLayout-01208\"},\n            {img_xfer_dst, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,         \"VUID-VkImageMemoryBarrier-oldLayout-01208\"},\n            {img_sampled,  VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,         \"VUID-VkImageMemoryBarrier-oldLayout-01208\"},\n            {img_input,    VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,         \"VUID-VkImageMemoryBarrier-oldLayout-01208\"},\n            \/\/ images _without_ VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT\n            {img_color,    VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, \"VUID-VkImageMemoryBarrier-oldLayout-01209\"},\n            {img_xfer_src, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, \"VUID-VkImageMemoryBarrier-oldLayout-01209\"},\n            {img_xfer_dst, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, \"VUID-VkImageMemoryBarrier-oldLayout-01209\"},\n            {img_sampled,  VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, \"VUID-VkImageMemoryBarrier-oldLayout-01209\"},\n            {img_input,    VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, \"VUID-VkImageMemoryBarrier-oldLayout-01209\"},\n            {img_color,    VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,  \"VUID-VkImageMemoryBarrier-oldLayout-01210\"},\n            {img_xfer_src, VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,  \"VUID-VkImageMemoryBarrier-oldLayout-01210\"},\n            {img_xfer_dst, VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,  \"VUID-VkImageMemoryBarrier-oldLayout-01210\"},\n            {img_sampled,  VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,  \"VUID-VkImageMemoryBarrier-oldLayout-01210\"},\n            {img_input,    VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,  \"VUID-VkImageMemoryBarrier-oldLayout-01210\"},\n            \/\/ images _without_ VK_IMAGE_USAGE_SAMPLED_BIT or VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT\n            {img_color,    VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,         \"VUID-VkImageMemoryBarrier-oldLayout-01211\"},\n            {img_ds,       VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,         \"VUID-VkImageMemoryBarrier-oldLayout-01211\"},\n            {img_xfer_src, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,         \"VUID-VkImageMemoryBarrier-oldLayout-01211\"},\n            {img_xfer_dst, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,         \"VUID-VkImageMemoryBarrier-oldLayout-01211\"},\n            \/\/ images _without_ VK_IMAGE_USAGE_TRANSFER_SRC_BIT\n            {img_color,    VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,             \"VUID-VkImageMemoryBarrier-oldLayout-01212\"},\n            {img_ds,       VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,             \"VUID-VkImageMemoryBarrier-oldLayout-01212\"},\n            {img_xfer_dst, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,             \"VUID-VkImageMemoryBarrier-oldLayout-01212\"},\n            {img_sampled,  VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,             \"VUID-VkImageMemoryBarrier-oldLayout-01212\"},\n            {img_input,    VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,             \"VUID-VkImageMemoryBarrier-oldLayout-01212\"},\n            \/\/ images _without_ VK_IMAGE_USAGE_TRANSFER_DST_BIT\n            {img_color,    VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,             \"VUID-VkImageMemoryBarrier-oldLayout-01213\"},\n            {img_ds,       VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,             \"VUID-VkImageMemoryBarrier-oldLayout-01213\"},\n            {img_xfer_src, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,             \"VUID-VkImageMemoryBarrier-oldLayout-01213\"},\n            {img_sampled,  VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,             \"VUID-VkImageMemoryBarrier-oldLayout-01213\"},\n            {img_input,    VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,             \"VUID-VkImageMemoryBarrier-oldLayout-01213\"},\n            \/\/ clang-format on\n        };\n        const uint32_t layout_count = sizeof(bad_buffer_layouts) \/ sizeof(bad_buffer_layouts[0]);\n\n        for (uint32_t i = 0; i < layout_count; ++i) {\n            conc_test.image_barrier_.image = bad_buffer_layouts[i].image_obj.handle();\n            const VkImageUsageFlags usage = bad_buffer_layouts[i].image_obj.usage();\n            conc_test.image_barrier_.subresourceRange.aspectMask = (usage == VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)\n                                                                       ? (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)\n                                                                       : VK_IMAGE_ASPECT_COLOR_BIT;\n\n            conc_test.image_barrier_.oldLayout = bad_buffer_layouts[i].bad_layout;\n            conc_test.image_barrier_.newLayout = VK_IMAGE_LAYOUT_GENERAL;\n            conc_test(bad_buffer_layouts[i].msg_code);\n\n            conc_test.image_barrier_.oldLayout = VK_IMAGE_LAYOUT_GENERAL;\n            conc_test.image_barrier_.newLayout = bad_buffer_layouts[i].bad_layout;\n            conc_test(bad_buffer_layouts[i].msg_code);\n        }\n\n        conc_test.image_barrier_.oldLayout = VK_IMAGE_LAYOUT_GENERAL;\n        conc_test.image_barrier_.newLayout = VK_IMAGE_LAYOUT_GENERAL;\n        conc_test.image_barrier_.image = image.handle();\n    }\n\n    \/\/ Attempt barrier where srcAccessMask is not supported by srcStageMask\n    \/\/ Have lower-order bit that's supported (shader write), but higher-order bit not supported to verify multi-bit validation\n    conc_test.buffer_barrier_.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT;\n    conc_test.buffer_barrier_.offset = 0;\n    conc_test.buffer_barrier_.size = VK_WHOLE_SIZE;\n    conc_test(\"\", \"VUID-vkCmdPipelineBarrier-pMemoryBarriers-01184\");\n\n    \/\/ Attempt barrier where dstAccessMask is not supported by dstStageMask\n    conc_test.buffer_barrier_.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;\n    conc_test.buffer_barrier_.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\n    conc_test(\"\", \"VUID-vkCmdPipelineBarrier-pMemoryBarriers-01185\");\n\n    \/\/ Attempt to mismatch barriers\/waitEvents calls with incompatible queues\n    \/\/ Create command pool with incompatible queueflags\n    const std::vector<VkQueueFamilyProperties> queue_props = m_device->queue_props;\n    uint32_t queue_family_index = m_device->QueueFamilyMatching(VK_QUEUE_GRAPHICS_BIT, VK_QUEUE_COMPUTE_BIT);\n    if (queue_family_index == UINT32_MAX) {\n        printf(\"%s No non-compute queue supporting graphics found; skipped.\\n\", kSkipPrefix);\n        return;  \/\/ NOTE: this exits the test function!\n    }\n\n    VkBufferMemoryBarrier buf_barrier = {};\n    buf_barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;\n    buf_barrier.pNext = NULL;\n    buf_barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\n    buf_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;\n    buf_barrier.buffer = buffer.handle();\n    buf_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    buf_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    buf_barrier.offset = 0;\n    buf_barrier.size = VK_WHOLE_SIZE;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdPipelineBarrier-srcStageMask-01183\");\n\n    VkCommandPoolObj command_pool(m_device, queue_family_index, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT);\n    VkCommandBufferObj bad_command_buffer(m_device, &command_pool);\n\n    bad_command_buffer.begin();\n    buf_barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;\n    \/\/ Set two bits that should both be supported as a bonus positive check\n    buf_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;\n    vk::CmdPipelineBarrier(bad_command_buffer.handle(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,\n                           VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 1, &buf_barrier, 0, nullptr);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Check for error for trying to wait on pipeline stage not supported by this queue. Specifically since our queue is not a\n    \/\/ compute queue, vk::CmdWaitEvents cannot have it's source stage mask be VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdWaitEvents-srcStageMask-01164\");\n    VkEvent event;\n    VkEventCreateInfo event_create_info{};\n    event_create_info.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;\n    vk::CreateEvent(m_device->device(), &event_create_info, nullptr, &event);\n    vk::CmdWaitEvents(bad_command_buffer.handle(), 1, &event, \/*source stage mask*\/ VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,\n                      VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, 0, nullptr, 0, nullptr, 0, nullptr);\n    m_errorMonitor->VerifyFound();\n    bad_command_buffer.end();\n\n    vk::DestroyEvent(m_device->device(), event, nullptr);\n}\n\nTEST_F(VkLayerTest, InvalidBarrierQueueFamily) {\n    TEST_DESCRIPTION(\"Create and submit barriers with invalid queue families\");\n    ASSERT_NO_FATAL_FAILURE(Init(nullptr, nullptr, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT));\n\n    \/\/ Find queues of two families\n    const uint32_t submit_family = m_device->graphics_queue_node_index_;\n    const uint32_t invalid = static_cast<uint32_t>(m_device->queue_props.size());\n    const uint32_t other_family = submit_family != 0 ? 0 : 1;\n    const bool only_one_family = (invalid == 1) || (m_device->queue_props[other_family].queueCount == 0);\n\n    std::vector<uint32_t> qf_indices{{submit_family, other_family}};\n    if (only_one_family) {\n        qf_indices.resize(1);\n    }\n    BarrierQueueFamilyTestHelper::Context test_context(this, qf_indices);\n\n    if (m_device->props.apiVersion >= VK_API_VERSION_1_1) {\n        printf(\n            \"%s Device has apiVersion greater than 1.0 -- skipping test cases that require external memory \"\n            \"to be \"\n            \"disabled.\\n\",\n            kSkipPrefix);\n    } else {\n        if (only_one_family) {\n            printf(\"%s Single queue family found -- VK_SHARING_MODE_CONCURRENT testcases skipped.\\n\", kSkipPrefix);\n        } else {\n            std::vector<uint32_t> families = {submit_family, other_family};\n            BarrierQueueFamilyTestHelper conc_test(&test_context);\n            conc_test.Init(&families);\n            \/\/ core_validation::barrier_queue_families::kSrcAndDestMustBeIgnore\n            conc_test(\"VUID-VkImageMemoryBarrier-image-01199\", \"VUID-VkBufferMemoryBarrier-buffer-01190\", VK_QUEUE_FAMILY_IGNORED,\n                      submit_family);\n            conc_test(\"VUID-VkImageMemoryBarrier-image-01199\", \"VUID-VkBufferMemoryBarrier-buffer-01190\", submit_family,\n                      VK_QUEUE_FAMILY_IGNORED);\n            conc_test(\"VUID-VkImageMemoryBarrier-image-01199\", \"VUID-VkBufferMemoryBarrier-buffer-01190\", submit_family,\n                      submit_family);\n            \/\/ true -> positive test\n            conc_test(\"VUID-VkImageMemoryBarrier-image-01199\", \"VUID-VkBufferMemoryBarrier-buffer-01190\", VK_QUEUE_FAMILY_IGNORED,\n                      VK_QUEUE_FAMILY_IGNORED, true);\n        }\n\n        BarrierQueueFamilyTestHelper excl_test(&test_context);\n        excl_test.Init(nullptr);  \/\/ no queue families means *exclusive* sharing mode.\n\n        \/\/ core_validation::barrier_queue_families::kBothIgnoreOrBothValid\n        excl_test(\"VUID-VkImageMemoryBarrier-image-01200\", \"VUID-VkBufferMemoryBarrier-buffer-01192\", VK_QUEUE_FAMILY_IGNORED,\n                  submit_family);\n        excl_test(\"VUID-VkImageMemoryBarrier-image-01200\", \"VUID-VkBufferMemoryBarrier-buffer-01192\", submit_family,\n                  VK_QUEUE_FAMILY_IGNORED);\n        \/\/ true -> positive test\n        excl_test(\"VUID-VkImageMemoryBarrier-image-01200\", \"VUID-VkBufferMemoryBarrier-buffer-01192\", submit_family, submit_family,\n                  true);\n        excl_test(\"VUID-VkImageMemoryBarrier-image-01200\", \"VUID-VkBufferMemoryBarrier-buffer-01192\", VK_QUEUE_FAMILY_IGNORED,\n                  VK_QUEUE_FAMILY_IGNORED, true);\n    }\n\n    if (only_one_family) {\n        printf(\"%s Single queue family found -- VK_SHARING_MODE_EXCLUSIVE submit testcases skipped.\\n\", kSkipPrefix);\n    } else {\n        BarrierQueueFamilyTestHelper excl_test(&test_context);\n        excl_test.Init(nullptr);\n\n        \/\/ core_validation::barrier_queue_families::kSubmitQueueMustMatchSrcOrDst\n        excl_test(\"VUID-VkImageMemoryBarrier-image-01205\", \"VUID-VkBufferMemoryBarrier-buffer-01196\", other_family, other_family,\n                  false, submit_family);\n\n        \/\/ true -> positive test (testing both the index logic and the QFO transfer tracking.\n        excl_test(\"POSITIVE_TEST\", \"POSITIVE_TEST\", submit_family, other_family, true, submit_family);\n        excl_test(\"POSITIVE_TEST\", \"POSITIVE_TEST\", submit_family, other_family, true, other_family);\n        excl_test(\"POSITIVE_TEST\", \"POSITIVE_TEST\", other_family, submit_family, true, other_family);\n        excl_test(\"POSITIVE_TEST\", \"POSITIVE_TEST\", other_family, submit_family, true, submit_family);\n\n        \/\/ negative testing for QFO transfer tracking\n        \/\/ Duplicate release in one CB\n        excl_test(\"UNASSIGNED-VkImageMemoryBarrier-image-00001\", \"UNASSIGNED-VkBufferMemoryBarrier-buffer-00001\", submit_family,\n                  other_family, false, submit_family, BarrierQueueFamilyTestHelper::DOUBLE_RECORD);\n        \/\/ Duplicate pending release\n        excl_test(\"UNASSIGNED-VkImageMemoryBarrier-image-00003\", \"UNASSIGNED-VkBufferMemoryBarrier-buffer-00003\", submit_family,\n                  other_family, false, submit_family);\n        \/\/ Duplicate acquire in one CB\n        excl_test(\"UNASSIGNED-VkImageMemoryBarrier-image-00001\", \"UNASSIGNED-VkBufferMemoryBarrier-buffer-00001\", submit_family,\n                  other_family, false, other_family, BarrierQueueFamilyTestHelper::DOUBLE_RECORD);\n        \/\/ No pending release\n        excl_test(\"UNASSIGNED-VkImageMemoryBarrier-image-00004\", \"UNASSIGNED-VkBufferMemoryBarrier-buffer-00004\", submit_family,\n                  other_family, false, other_family);\n        \/\/ Duplicate release in two CB\n        excl_test(\"UNASSIGNED-VkImageMemoryBarrier-image-00002\", \"UNASSIGNED-VkBufferMemoryBarrier-buffer-00002\", submit_family,\n                  other_family, false, submit_family, BarrierQueueFamilyTestHelper::DOUBLE_COMMAND_BUFFER);\n        \/\/ Duplicate acquire in two CB\n        excl_test(\"POSITIVE_TEST\", \"POSITIVE_TEST\", submit_family, other_family, true, submit_family);  \/\/ need a succesful release\n        excl_test(\"UNASSIGNED-VkImageMemoryBarrier-image-00002\", \"UNASSIGNED-VkBufferMemoryBarrier-buffer-00002\", submit_family,\n                  other_family, false, other_family, BarrierQueueFamilyTestHelper::DOUBLE_COMMAND_BUFFER);\n    }\n}\n\nTEST_F(VkLayerTest, InvalidBarrierQueueFamilyWithMemExt) {\n    TEST_DESCRIPTION(\"Create and submit barriers with invalid queue families when memory extension is enabled \");\n    std::vector<const char *> reqd_instance_extensions = {\n        {VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME}};\n    for (auto extension_name : reqd_instance_extensions) {\n        if (InstanceExtensionSupported(extension_name)) {\n            m_instance_extension_names.push_back(extension_name);\n        } else {\n            printf(\"%s Required instance extension %s not supported, skipping test\\n\", kSkipPrefix, extension_name);\n            return;\n        }\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    \/\/ Check for external memory device extensions\n    if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME)) {\n        m_device_extension_names.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);\n    } else {\n        printf(\"%s External memory extension not supported, skipping test\\n\", kSkipPrefix);\n        return;\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitState(nullptr, nullptr, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT));\n\n    \/\/ Find queues of two families\n    const uint32_t submit_family = m_device->graphics_queue_node_index_;\n    const uint32_t invalid = static_cast<uint32_t>(m_device->queue_props.size());\n    const uint32_t other_family = submit_family != 0 ? 0 : 1;\n    const bool only_one_family = (invalid == 1) || (m_device->queue_props[other_family].queueCount == 0);\n\n    std::vector<uint32_t> qf_indices{{submit_family, other_family}};\n    if (only_one_family) {\n        qf_indices.resize(1);\n    }\n    BarrierQueueFamilyTestHelper::Context test_context(this, qf_indices);\n\n    if (only_one_family) {\n        printf(\"%s Single queue family found -- VK_SHARING_MODE_CONCURRENT testcases skipped.\\n\", kSkipPrefix);\n    } else {\n        std::vector<uint32_t> families = {submit_family, other_family};\n        BarrierQueueFamilyTestHelper conc_test(&test_context);\n\n        \/\/ core_validation::barrier_queue_families::kSrcOrDstMustBeIgnore\n        conc_test.Init(&families);\n        conc_test(\"VUID-VkImageMemoryBarrier-image-01381\", \"VUID-VkBufferMemoryBarrier-buffer-01191\", submit_family, submit_family);\n        \/\/ true -> positive test\n        conc_test(\"VUID-VkImageMemoryBarrier-image-01381\", \"VUID-VkBufferMemoryBarrier-buffer-01191\", VK_QUEUE_FAMILY_IGNORED,\n                  VK_QUEUE_FAMILY_IGNORED, true);\n        conc_test(\"VUID-VkImageMemoryBarrier-image-01381\", \"VUID-VkBufferMemoryBarrier-buffer-01191\", VK_QUEUE_FAMILY_IGNORED,\n                  VK_QUEUE_FAMILY_EXTERNAL_KHR, true);\n        conc_test(\"VUID-VkImageMemoryBarrier-image-01381\", \"VUID-VkBufferMemoryBarrier-buffer-01191\", VK_QUEUE_FAMILY_EXTERNAL_KHR,\n                  VK_QUEUE_FAMILY_IGNORED, true);\n\n        \/\/ core_validation::barrier_queue_families::kSpecialOrIgnoreOnly\n        conc_test(\"VUID-VkImageMemoryBarrier-image-01766\", \"VUID-VkBufferMemoryBarrier-buffer-01763\", submit_family,\n                  VK_QUEUE_FAMILY_IGNORED);\n        conc_test(\"VUID-VkImageMemoryBarrier-image-01766\", \"VUID-VkBufferMemoryBarrier-buffer-01763\", VK_QUEUE_FAMILY_IGNORED,\n                  submit_family);\n        \/\/ This is to flag the errors that would be considered only \"unexpected\" in the parallel case above\n        \/\/ true -> positive test\n        conc_test(\"VUID-VkImageMemoryBarrier-image-01766\", \"VUID-VkBufferMemoryBarrier-buffer-01763\", VK_QUEUE_FAMILY_IGNORED,\n                  VK_QUEUE_FAMILY_EXTERNAL_KHR, true);\n        conc_test(\"VUID-VkImageMemoryBarrier-image-01766\", \"VUID-VkBufferMemoryBarrier-buffer-01763\", VK_QUEUE_FAMILY_EXTERNAL_KHR,\n                  VK_QUEUE_FAMILY_IGNORED, true);\n    }\n\n    BarrierQueueFamilyTestHelper excl_test(&test_context);\n    excl_test.Init(nullptr);  \/\/ no queue families means *exclusive* sharing mode.\n\n    \/\/ core_validation::barrier_queue_families::kSrcIgnoreRequiresDstIgnore\n    excl_test(\"VUID-VkImageMemoryBarrier-image-01201\", \"VUID-VkBufferMemoryBarrier-buffer-01193\", VK_QUEUE_FAMILY_IGNORED,\n              submit_family);\n    excl_test(\"VUID-VkImageMemoryBarrier-image-01201\", \"VUID-VkBufferMemoryBarrier-buffer-01193\", VK_QUEUE_FAMILY_IGNORED,\n              VK_QUEUE_FAMILY_EXTERNAL_KHR);\n    \/\/ true -> positive test\n    excl_test(\"VUID-VkImageMemoryBarrier-image-01201\", \"VUID-VkBufferMemoryBarrier-buffer-01193\", VK_QUEUE_FAMILY_IGNORED,\n              VK_QUEUE_FAMILY_IGNORED, true);\n\n    \/\/ core_validation::barrier_queue_families::kDstValidOrSpecialIfNotIgnore\n    excl_test(\"VUID-VkImageMemoryBarrier-image-01768\", \"VUID-VkBufferMemoryBarrier-buffer-01765\", submit_family, invalid);\n    \/\/ true -> positive test\n    excl_test(\"VUID-VkImageMemoryBarrier-image-01768\", \"VUID-VkBufferMemoryBarrier-buffer-01765\", submit_family, submit_family,\n              true);\n    excl_test(\"VUID-VkImageMemoryBarrier-image-01768\", \"VUID-VkBufferMemoryBarrier-buffer-01765\", submit_family,\n              VK_QUEUE_FAMILY_IGNORED, true);\n    excl_test(\"VUID-VkImageMemoryBarrier-image-01768\", \"VUID-VkBufferMemoryBarrier-buffer-01765\", submit_family,\n              VK_QUEUE_FAMILY_EXTERNAL_KHR, true);\n\n    \/\/ core_validation::barrier_queue_families::kSrcValidOrSpecialIfNotIgnore\n    excl_test(\"VUID-VkImageMemoryBarrier-image-01767\", \"VUID-VkBufferMemoryBarrier-buffer-01764\", invalid, submit_family);\n    \/\/ true -> positive test\n    excl_test(\"VUID-VkImageMemoryBarrier-image-01767\", \"VUID-VkBufferMemoryBarrier-buffer-01764\", submit_family, submit_family,\n              true);\n    excl_test(\"VUID-VkImageMemoryBarrier-image-01767\", \"VUID-VkBufferMemoryBarrier-buffer-01764\", VK_QUEUE_FAMILY_IGNORED,\n              VK_QUEUE_FAMILY_IGNORED, true);\n    excl_test(\"VUID-VkImageMemoryBarrier-image-01767\", \"VUID-VkBufferMemoryBarrier-buffer-01764\", VK_QUEUE_FAMILY_EXTERNAL_KHR,\n              submit_family, true);\n}\n\nTEST_F(VkLayerTest, ImageBarrierWithBadRange) {\n    TEST_DESCRIPTION(\"VkImageMemoryBarrier with an invalid subresourceRange\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    VkImageMemoryBarrier img_barrier_template = {};\n    img_barrier_template.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;\n    img_barrier_template.pNext = NULL;\n    img_barrier_template.srcAccessMask = 0;\n    img_barrier_template.dstAccessMask = 0;\n    img_barrier_template.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n    img_barrier_template.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n    img_barrier_template.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    img_barrier_template.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    \/\/ subresourceRange to be set later for the for the purposes of this test\n    img_barrier_template.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    img_barrier_template.subresourceRange.baseArrayLayer = 0;\n    img_barrier_template.subresourceRange.baseMipLevel = 0;\n    img_barrier_template.subresourceRange.layerCount = 0;\n    img_barrier_template.subresourceRange.levelCount = 0;\n\n    const uint32_t submit_family = m_device->graphics_queue_node_index_;\n    const uint32_t invalid = static_cast<uint32_t>(m_device->queue_props.size());\n    const uint32_t other_family = submit_family != 0 ? 0 : 1;\n    const bool only_one_family = (invalid == 1) || (m_device->queue_props[other_family].queueCount == 0);\n    std::vector<uint32_t> qf_indices{{submit_family, other_family}};\n    if (only_one_family) {\n        qf_indices.resize(1);\n    }\n    BarrierQueueFamilyTestHelper::Context test_context(this, qf_indices);\n\n    \/\/ Use image unbound to memory in barrier\n    \/\/ Use buffer unbound to memory in barrier\n    BarrierQueueFamilyTestHelper conc_test(&test_context);\n    conc_test.Init(nullptr);\n    img_barrier_template.image = conc_test.image_.handle();\n    conc_test.image_barrier_ = img_barrier_template;\n    \/\/ Nested scope here confuses clang-format, somehow\n    \/\/ clang-format off\n\n    \/\/ try for vk::CmdPipelineBarrier\n    {\n        \/\/ Try baseMipLevel >= image.mipLevels with VK_REMAINING_MIP_LEVELS\n        {\n            conc_test.image_barrier_.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_REMAINING_MIP_LEVELS, 0, 1};\n            conc_test(\"VUID-VkImageMemoryBarrier-subresourceRange-01486\");\n        }\n\n        \/\/ Try baseMipLevel >= image.mipLevels without VK_REMAINING_MIP_LEVELS\n        {\n            conc_test.image_barrier_.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 1, 1, 0, 1};\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-subresourceRange-01724\");\n            conc_test(\"VUID-VkImageMemoryBarrier-subresourceRange-01486\");\n        }\n\n        \/\/ Try levelCount = 0\n        {\n            conc_test.image_barrier_.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 0, 1};\n            conc_test(\"VUID-VkImageMemoryBarrier-subresourceRange-01724\");\n        }\n\n        \/\/ Try baseMipLevel + levelCount > image.mipLevels\n        {\n            conc_test.image_barrier_.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 2, 0, 1};\n            conc_test(\"VUID-VkImageMemoryBarrier-subresourceRange-01724\");\n        }\n\n        \/\/ Try baseArrayLayer >= image.arrayLayers with VK_REMAINING_ARRAY_LAYERS\n        {\n            conc_test.image_barrier_.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 1, VK_REMAINING_ARRAY_LAYERS};\n            conc_test(\"VUID-VkImageMemoryBarrier-subresourceRange-01488\");\n        }\n\n        \/\/ Try baseArrayLayer >= image.arrayLayers without VK_REMAINING_ARRAY_LAYERS\n        {\n            conc_test.image_barrier_.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 1, 1};\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-subresourceRange-01725\");\n            conc_test(\"VUID-VkImageMemoryBarrier-subresourceRange-01488\");\n        }\n\n        \/\/ Try layerCount = 0\n        {\n            conc_test.image_barrier_.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 0};\n            conc_test(\"VUID-VkImageMemoryBarrier-subresourceRange-01725\");\n        }\n\n        \/\/ Try baseArrayLayer + layerCount > image.arrayLayers\n        {\n            conc_test.image_barrier_.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 2};\n            conc_test(\"VUID-VkImageMemoryBarrier-subresourceRange-01725\");\n        }\n    }\n\n    m_commandBuffer->begin();\n    \/\/ try for vk::CmdWaitEvents\n    {\n        VkEvent event;\n        VkEventCreateInfo eci{VK_STRUCTURE_TYPE_EVENT_CREATE_INFO, NULL, 0};\n        VkResult err = vk::CreateEvent(m_device->handle(), &eci, nullptr, &event);\n        ASSERT_VK_SUCCESS(err);\n\n        \/\/ Try baseMipLevel >= image.mipLevels with VK_REMAINING_MIP_LEVELS\n        {\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-subresourceRange-01486\");\n            const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_REMAINING_MIP_LEVELS, 0, 1};\n            VkImageMemoryBarrier img_barrier = img_barrier_template;\n            img_barrier.subresourceRange = range;\n            vk::CmdWaitEvents(m_commandBuffer->handle(), 1, &event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,\n                            VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, nullptr, 0, nullptr, 1, &img_barrier);\n            m_errorMonitor->VerifyFound();\n        }\n\n        \/\/ Try baseMipLevel >= image.mipLevels without VK_REMAINING_MIP_LEVELS\n        {\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-subresourceRange-01486\");\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-subresourceRange-01724\");\n            const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 1, 1, 0, 1};\n            VkImageMemoryBarrier img_barrier = img_barrier_template;\n            img_barrier.subresourceRange = range;\n            vk::CmdWaitEvents(m_commandBuffer->handle(), 1, &event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,\n                            VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, nullptr, 0, nullptr, 1, &img_barrier);\n            m_errorMonitor->VerifyFound();\n        }\n\n        \/\/ Try levelCount = 0\n        {\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-subresourceRange-01724\");\n            const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 0, 1};\n            VkImageMemoryBarrier img_barrier = img_barrier_template;\n            img_barrier.subresourceRange = range;\n            vk::CmdWaitEvents(m_commandBuffer->handle(), 1, &event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,\n                            VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, nullptr, 0, nullptr, 1, &img_barrier);\n            m_errorMonitor->VerifyFound();\n        }\n\n        \/\/ Try baseMipLevel + levelCount > image.mipLevels\n        {\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-subresourceRange-01724\");\n            const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 2, 0, 1};\n            VkImageMemoryBarrier img_barrier = img_barrier_template;\n            img_barrier.subresourceRange = range;\n            vk::CmdWaitEvents(m_commandBuffer->handle(), 1, &event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,\n                            VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, nullptr, 0, nullptr, 1, &img_barrier);\n            m_errorMonitor->VerifyFound();\n        }\n\n        \/\/ Try baseArrayLayer >= image.arrayLayers with VK_REMAINING_ARRAY_LAYERS\n        {\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-subresourceRange-01488\");\n            const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 1, VK_REMAINING_ARRAY_LAYERS};\n            VkImageMemoryBarrier img_barrier = img_barrier_template;\n            img_barrier.subresourceRange = range;\n            vk::CmdWaitEvents(m_commandBuffer->handle(), 1, &event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,\n                            VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, nullptr, 0, nullptr, 1, &img_barrier);\n            m_errorMonitor->VerifyFound();\n        }\n\n        \/\/ Try baseArrayLayer >= image.arrayLayers without VK_REMAINING_ARRAY_LAYERS\n        {\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-subresourceRange-01488\");\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-subresourceRange-01725\");\n            const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 1, 1};\n            VkImageMemoryBarrier img_barrier = img_barrier_template;\n            img_barrier.subresourceRange = range;\n            vk::CmdWaitEvents(m_commandBuffer->handle(), 1, &event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,\n                            VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, nullptr, 0, nullptr, 1, &img_barrier);\n            m_errorMonitor->VerifyFound();\n        }\n\n        \/\/ Try layerCount = 0\n        {\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-subresourceRange-01725\");\n            const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 0};\n            VkImageMemoryBarrier img_barrier = img_barrier_template;\n            img_barrier.subresourceRange = range;\n            vk::CmdWaitEvents(m_commandBuffer->handle(), 1, &event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,\n                            VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, nullptr, 0, nullptr, 1, &img_barrier);\n            m_errorMonitor->VerifyFound();\n        }\n\n        \/\/ Try baseArrayLayer + layerCount > image.arrayLayers\n        {\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-subresourceRange-01725\");\n            const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 2};\n            VkImageMemoryBarrier img_barrier = img_barrier_template;\n            img_barrier.subresourceRange = range;\n            vk::CmdWaitEvents(m_commandBuffer->handle(), 1, &event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,\n                            VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, nullptr, 0, nullptr, 1, &img_barrier);\n            m_errorMonitor->VerifyFound();\n        }\n\n        vk::DestroyEvent(m_device->handle(), event, nullptr);\n    }\n    \/\/ clang-format on\n}\n\nTEST_F(VkLayerTest, IdxBufferAlignmentError) {\n    \/\/ Bind a BeginRenderPass within an active RenderPass\n    ASSERT_NO_FATAL_FAILURE(Init());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    uint32_t const indices[] = {0};\n    VkBufferCreateInfo buf_info = {};\n    buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;\n    buf_info.size = 1024;\n    buf_info.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT;\n    buf_info.queueFamilyIndexCount = 1;\n    buf_info.pQueueFamilyIndices = indices;\n\n    VkBufferObj buffer;\n    buffer.init(*m_device, buf_info);\n\n    m_commandBuffer->begin();\n\n    \/\/ vk::CmdBindPipeline(m_commandBuffer->handle(),\n    \/\/ VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.handle());\n    \/\/ Should error before calling to driver so don't care about actual data\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"vkCmdBindIndexBuffer() offset (0x7) does not fall on \");\n    vk::CmdBindIndexBuffer(m_commandBuffer->handle(), buffer.handle(), 7, VK_INDEX_TYPE_UINT16);\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, Bad2DArrayImageType) {\n    TEST_DESCRIPTION(\"Create an image with a flag specifying 2D_ARRAY_COMPATIBLE but not of imageType 3D.\");\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE1_EXTENSION_NAME)) {\n        m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);\n    } else {\n        printf(\"%s %s is not supported; skipping\\n\", kSkipPrefix, VK_KHR_MAINTENANCE1_EXTENSION_NAME);\n        return;\n    }\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    \/\/ Trigger check by setting imagecreateflags to 2d_array_compat and imageType to 2D\n    VkImageCreateInfo ici = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,\n                             nullptr,\n                             VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR,\n                             VK_IMAGE_TYPE_2D,\n                             VK_FORMAT_R8G8B8A8_UNORM,\n                             {32, 32, 1},\n                             1,\n                             1,\n                             VK_SAMPLE_COUNT_1_BIT,\n                             VK_IMAGE_TILING_OPTIMAL,\n                             VK_IMAGE_USAGE_SAMPLED_BIT,\n                             VK_SHARING_MODE_EXCLUSIVE,\n                             0,\n                             nullptr,\n                             VK_IMAGE_LAYOUT_UNDEFINED};\n    CreateImageTest(*this, &ici, \"VUID-VkImageCreateInfo-flags-00950\");\n}\n\nTEST_F(VkLayerTest, VertexBufferInvalid) {\n    TEST_DESCRIPTION(\n        \"Submit a command buffer using deleted vertex buffer, delete a buffer twice, use an invalid offset for each buffer type, \"\n        \"and attempt to bind a null buffer\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    ASSERT_NO_FATAL_FAILURE(InitViewport());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    CreatePipelineHelper pipe(*this);\n    pipe.InitInfo();\n    pipe.InitState();\n    pipe.CreateGraphicsPipeline();\n\n    m_commandBuffer->begin();\n    m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);\n    vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_);\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"CoreValidation-DrawState-InvalidCommandBuffer-VkBuffer\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"CoreValidation-DrawState-InvalidCommandBuffer-VkDeviceMemory\");\n\n    {\n        \/\/ Create and bind a vertex buffer in a reduced scope, which will cause it to be deleted upon leaving this scope\n        const float vbo_data[3] = {1.f, 0.f, 1.f};\n        VkVerticesObj draw_verticies(m_device, 1, 1, sizeof(vbo_data[0]), sizeof(vbo_data) \/ sizeof(vbo_data[0]), vbo_data);\n        draw_verticies.BindVertexBuffers(m_commandBuffer->handle());\n        draw_verticies.AddVertexInputToPipeHelpr(&pipe);\n\n        m_commandBuffer->Draw(1, 0, 0, 0);\n\n        m_commandBuffer->EndRenderPass();\n    }\n\n    vk::EndCommandBuffer(m_commandBuffer->handle());\n    m_errorMonitor->VerifyFound();\n\n    {\n        \/\/ Create and bind a vertex buffer in a reduced scope, and delete it\n        \/\/ twice, the second through the destructor\n        VkBufferTest buffer_test(m_device, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VkBufferTest::eDoubleDelete);\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkDestroyBuffer-buffer-parameter\");\n        buffer_test.TestDoubleDestroy();\n    }\n    m_errorMonitor->VerifyFound();\n\n    m_errorMonitor->SetUnexpectedError(\"value of pCreateInfo->usage must not be 0\");\n    if (VkBufferTest::GetTestConditionValid(m_device, VkBufferTest::eInvalidMemoryOffset)) {\n        \/\/ Create and bind a memory buffer with an invalid offset.\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindBufferMemory-memoryOffset-01036\");\n        m_errorMonitor->SetUnexpectedError(\n            \"If buffer was created with the VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT or VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, \"\n            \"memoryOffset must be a multiple of VkPhysicalDeviceLimits::minTexelBufferOffsetAlignment\");\n        VkBufferTest buffer_test(m_device, VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, VkBufferTest::eInvalidMemoryOffset);\n        (void)buffer_test;\n        m_errorMonitor->VerifyFound();\n    }\n\n    {\n        \/\/ Attempt to bind a null buffer.\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                             \"vkBindBufferMemory: required parameter buffer specified as VK_NULL_HANDLE\");\n        VkBufferTest buffer_test(m_device, 0, VkBufferTest::eBindNullBuffer);\n        (void)buffer_test;\n        m_errorMonitor->VerifyFound();\n    }\n\n    {\n        \/\/ Attempt to bind a fake buffer.\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindBufferMemory-buffer-parameter\");\n        VkBufferTest buffer_test(m_device, 0, VkBufferTest::eBindFakeBuffer);\n        (void)buffer_test;\n        m_errorMonitor->VerifyFound();\n    }\n\n    {\n        \/\/ Attempt to use an invalid handle to delete a buffer.\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkFreeMemory-memory-parameter\");\n        VkBufferTest buffer_test(m_device, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VkBufferTest::eFreeInvalidHandle);\n        (void)buffer_test;\n    }\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, BadVertexBufferOffset) {\n    TEST_DESCRIPTION(\"Submit an offset past the end of a vertex buffer\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n    static const float vbo_data[3] = {1.f, 0.f, 1.f};\n    VkConstantBufferObj vbo(m_device, sizeof(vbo_data), (const void *)&vbo_data, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);\n    m_commandBuffer->begin();\n    m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdBindVertexBuffers-pOffsets-00626\");\n    m_commandBuffer->BindVertexBuffer(&vbo, (VkDeviceSize)(3 * sizeof(float)), 1);  \/\/ Offset at the end of the buffer\n    m_errorMonitor->VerifyFound();\n\n    m_commandBuffer->EndRenderPass();\n    m_commandBuffer->end();\n}\n\n\/\/ INVALID_IMAGE_LAYOUT tests (one other case is hit by MapMemWithoutHostVisibleBit and not here)\nTEST_F(VkLayerTest, InvalidImageLayout) {\n    TEST_DESCRIPTION(\n        \"Hit all possible validation checks associated with the UNASSIGNED-CoreValidation-DrawState-InvalidImageLayout error. \"\n        \"Generally these involve having images in the wrong layout when they're copied or transitioned.\");\n    \/\/ 3 in ValidateCmdBufImageLayouts\n    \/\/ *  -1 Attempt to submit cmd buf w\/ deleted image\n    \/\/ *  -2 Cmd buf submit of image w\/ layout not matching first use w\/ subresource\n    \/\/ *  -3 Cmd buf submit of image w\/ layout not matching first use w\/o subresource\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    auto depth_format = FindSupportedDepthStencilFormat(gpu());\n    if (!depth_format) {\n        printf(\"%s No Depth + Stencil format found. Skipped.\\n\", kSkipPrefix);\n        return;\n    }\n    \/\/ Create src & dst images to use for copy operations\n    VkImageObj src_image(m_device);\n    VkImageObj dst_image(m_device);\n    VkImageObj depth_image(m_device);\n\n    const VkFormat tex_format = VK_FORMAT_B8G8R8A8_UNORM;\n    const int32_t tex_width = 32;\n    const int32_t tex_height = 32;\n\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = tex_format;\n    image_create_info.extent.width = tex_width;\n    image_create_info.extent.height = tex_height;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 4;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n    image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n    image_create_info.flags = 0;\n\n    src_image.init(&image_create_info);\n\n    image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n    dst_image.init(&image_create_info);\n\n    image_create_info.format = VK_FORMAT_D16_UNORM;\n    image_create_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;\n    depth_image.init(&image_create_info);\n\n    m_commandBuffer->begin();\n    VkImageCopy copy_region;\n    copy_region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    copy_region.srcSubresource.mipLevel = 0;\n    copy_region.srcSubresource.baseArrayLayer = 0;\n    copy_region.srcSubresource.layerCount = 1;\n    copy_region.srcOffset.x = 0;\n    copy_region.srcOffset.y = 0;\n    copy_region.srcOffset.z = 0;\n    copy_region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    copy_region.dstSubresource.mipLevel = 0;\n    copy_region.dstSubresource.baseArrayLayer = 0;\n    copy_region.dstSubresource.layerCount = 1;\n    copy_region.dstOffset.x = 0;\n    copy_region.dstOffset.y = 0;\n    copy_region.dstOffset.z = 0;\n    copy_region.extent.width = 1;\n    copy_region.extent.height = 1;\n    copy_region.extent.depth = 1;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,\n                                         \"layout should be VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL instead of GENERAL.\");\n    m_errorMonitor->SetUnexpectedError(\"layout should be VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL instead of GENERAL.\");\n\n    m_commandBuffer->CopyImage(src_image.handle(), VK_IMAGE_LAYOUT_GENERAL, dst_image.handle(), VK_IMAGE_LAYOUT_GENERAL, 1,\n                               &copy_region);\n    m_errorMonitor->VerifyFound();\n    \/\/ The first call hits the expected WARNING and skips the call down the chain, so call a second time to call down chain and\n    \/\/ update layer state\n    m_errorMonitor->SetUnexpectedError(\"layout should be VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL instead of GENERAL.\");\n    m_errorMonitor->SetUnexpectedError(\"layout should be VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL instead of GENERAL.\");\n    m_commandBuffer->CopyImage(src_image.handle(), VK_IMAGE_LAYOUT_GENERAL, dst_image.handle(), VK_IMAGE_LAYOUT_GENERAL, 1,\n                               &copy_region);\n    \/\/ Now cause error due to src image layout changing\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdCopyImage-srcImageLayout-00128\");\n    m_errorMonitor->SetUnexpectedError(\"is VK_IMAGE_LAYOUT_UNDEFINED but can only be VK_IMAGE_LAYOUT\");\n    m_commandBuffer->CopyImage(src_image.handle(), VK_IMAGE_LAYOUT_UNDEFINED, dst_image.handle(), VK_IMAGE_LAYOUT_GENERAL, 1,\n                               &copy_region);\n    m_errorMonitor->VerifyFound();\n    \/\/ Final src error is due to bad layout type\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdCopyImage-srcImageLayout-00129\");\n    m_errorMonitor->SetUnexpectedError(\n        \"with specific layout VK_IMAGE_LAYOUT_UNDEFINED that doesn't match the previously used layout VK_IMAGE_LAYOUT_GENERAL.\");\n    m_commandBuffer->CopyImage(src_image.handle(), VK_IMAGE_LAYOUT_UNDEFINED, dst_image.handle(), VK_IMAGE_LAYOUT_GENERAL, 1,\n                               &copy_region);\n    m_errorMonitor->VerifyFound();\n    \/\/ Now verify same checks for dst\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,\n                                         \"layout should be VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL instead of GENERAL.\");\n    m_errorMonitor->SetUnexpectedError(\"layout should be VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL instead of GENERAL.\");\n    m_commandBuffer->CopyImage(src_image.handle(), VK_IMAGE_LAYOUT_GENERAL, dst_image.handle(), VK_IMAGE_LAYOUT_GENERAL, 1,\n                               &copy_region);\n    m_errorMonitor->VerifyFound();\n    \/\/ Now cause error due to src image layout changing\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdCopyImage-dstImageLayout-00133\");\n    m_errorMonitor->SetUnexpectedError(\n        \"is VK_IMAGE_LAYOUT_UNDEFINED but can only be VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL or VK_IMAGE_LAYOUT_GENERAL.\");\n    m_commandBuffer->CopyImage(src_image.handle(), VK_IMAGE_LAYOUT_GENERAL, dst_image.handle(), VK_IMAGE_LAYOUT_UNDEFINED, 1,\n                               &copy_region);\n    m_errorMonitor->VerifyFound();\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdCopyImage-dstImageLayout-00134\");\n    m_errorMonitor->SetUnexpectedError(\n        \"with specific layout VK_IMAGE_LAYOUT_UNDEFINED that doesn't match the previously used layout VK_IMAGE_LAYOUT_GENERAL.\");\n    m_commandBuffer->CopyImage(src_image.handle(), VK_IMAGE_LAYOUT_GENERAL, dst_image.handle(), VK_IMAGE_LAYOUT_UNDEFINED, 1,\n                               &copy_region);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Convert dst and depth images to TRANSFER_DST for subsequent tests\n    VkImageMemoryBarrier transfer_dst_image_barrier[1] = {};\n    transfer_dst_image_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;\n    transfer_dst_image_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n    transfer_dst_image_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;\n    transfer_dst_image_barrier[0].srcAccessMask = 0;\n    transfer_dst_image_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;\n    transfer_dst_image_barrier[0].image = dst_image.handle();\n    transfer_dst_image_barrier[0].subresourceRange.layerCount = image_create_info.arrayLayers;\n    transfer_dst_image_barrier[0].subresourceRange.levelCount = image_create_info.mipLevels;\n    transfer_dst_image_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0,\n                           NULL, 0, NULL, 1, transfer_dst_image_barrier);\n    transfer_dst_image_barrier[0].image = depth_image.handle();\n    transfer_dst_image_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0,\n                           NULL, 0, NULL, 1, transfer_dst_image_barrier);\n\n    \/\/ Cause errors due to clearing with invalid image layouts\n    VkClearColorValue color_clear_value = {};\n    VkImageSubresourceRange clear_range;\n    clear_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    clear_range.baseMipLevel = 0;\n    clear_range.baseArrayLayer = 0;\n    clear_range.layerCount = 1;\n    clear_range.levelCount = 1;\n\n    \/\/ Fail due to explicitly prohibited layout for color clear (only GENERAL and TRANSFER_DST are permitted).\n    \/\/ Since the image is currently not in UNDEFINED layout, this will emit two errors.\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-imageLayout-00005\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-imageLayout-00004\");\n    m_commandBuffer->ClearColorImage(dst_image.handle(), VK_IMAGE_LAYOUT_UNDEFINED, &color_clear_value, 1, &clear_range);\n    m_errorMonitor->VerifyFound();\n    \/\/ Fail due to provided layout not matching actual current layout for color clear.\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearColorImage-imageLayout-00004\");\n    m_commandBuffer->ClearColorImage(dst_image.handle(), VK_IMAGE_LAYOUT_GENERAL, &color_clear_value, 1, &clear_range);\n    m_errorMonitor->VerifyFound();\n\n    VkClearDepthStencilValue depth_clear_value = {};\n    clear_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;\n\n    \/\/ Fail due to explicitly prohibited layout for depth clear (only GENERAL and TRANSFER_DST are permitted).\n    \/\/ Since the image is currently not in UNDEFINED layout, this will emit two errors.\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearDepthStencilImage-imageLayout-00012\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearDepthStencilImage-imageLayout-00011\");\n    m_commandBuffer->ClearDepthStencilImage(depth_image.handle(), VK_IMAGE_LAYOUT_UNDEFINED, &depth_clear_value, 1, &clear_range);\n    m_errorMonitor->VerifyFound();\n    \/\/ Fail due to provided layout not matching actual current layout for depth clear.\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkCmdClearDepthStencilImage-imageLayout-00011\");\n    m_commandBuffer->ClearDepthStencilImage(depth_image.handle(), VK_IMAGE_LAYOUT_GENERAL, &depth_clear_value, 1, &clear_range);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Now cause error due to bad image layout transition in PipelineBarrier\n    VkImageMemoryBarrier image_barrier[1] = {};\n    image_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;\n    image_barrier[0].oldLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;\n    image_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;\n    image_barrier[0].image = src_image.handle();\n    image_barrier[0].subresourceRange.layerCount = image_create_info.arrayLayers;\n    image_barrier[0].subresourceRange.levelCount = image_create_info.mipLevels;\n    image_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-oldLayout-01197\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageMemoryBarrier-oldLayout-01210\");\n    vk::CmdPipelineBarrier(m_commandBuffer->handle(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0,\n                           NULL, 0, NULL, 1, image_barrier);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Finally some layout errors at RenderPass create time\n    \/\/ Just hacking in specific state to get to the errors we want so don't copy this unless you know what you're doing.\n    VkAttachmentReference attach = {};\n    \/\/ perf warning for GENERAL layout w\/ non-DS input attachment\n    attach.layout = VK_IMAGE_LAYOUT_GENERAL;\n    VkSubpassDescription subpass = {};\n    subpass.inputAttachmentCount = 1;\n    subpass.pInputAttachments = &attach;\n    VkRenderPassCreateInfo rpci = {};\n    rpci.subpassCount = 1;\n    rpci.pSubpasses = &subpass;\n    rpci.attachmentCount = 1;\n    VkAttachmentDescription attach_desc = {};\n    attach_desc.format = VK_FORMAT_UNDEFINED;\n    attach_desc.samples = VK_SAMPLE_COUNT_1_BIT;\n    attach_desc.finalLayout = VK_IMAGE_LAYOUT_GENERAL;\n    rpci.pAttachments = &attach_desc;\n    rpci.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;\n    VkRenderPass rp;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,\n                                         \"Layout for input attachment is GENERAL but should be READ_ONLY_OPTIMAL.\");\n    vk::CreateRenderPass(m_device->device(), &rpci, NULL, &rp);\n    m_errorMonitor->VerifyFound();\n    \/\/ error w\/ non-general layout\n    attach.layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;\n\n    m_errorMonitor->SetDesiredFailureMsg(\n        VK_DEBUG_REPORT_ERROR_BIT_EXT,\n        \"Layout for input attachment is VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL but can only be READ_ONLY_OPTIMAL or GENERAL.\");\n    vk::CreateRenderPass(m_device->device(), &rpci, NULL, &rp);\n    m_errorMonitor->VerifyFound();\n    subpass.inputAttachmentCount = 0;\n    subpass.colorAttachmentCount = 1;\n    subpass.pColorAttachments = &attach;\n    attach.layout = VK_IMAGE_LAYOUT_GENERAL;\n    \/\/ perf warning for GENERAL layout on color attachment\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,\n                                         \"Layout for color attachment is GENERAL but should be COLOR_ATTACHMENT_OPTIMAL.\");\n    vk::CreateRenderPass(m_device->device(), &rpci, NULL, &rp);\n    m_errorMonitor->VerifyFound();\n    \/\/ error w\/ non-color opt or GENERAL layout for color attachment\n    attach.layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;\n    m_errorMonitor->SetDesiredFailureMsg(\n        VK_DEBUG_REPORT_ERROR_BIT_EXT,\n        \"Layout for color attachment is VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL but can only be COLOR_ATTACHMENT_OPTIMAL or GENERAL.\");\n    vk::CreateRenderPass(m_device->device(), &rpci, NULL, &rp);\n    m_errorMonitor->VerifyFound();\n    subpass.colorAttachmentCount = 0;\n    subpass.pDepthStencilAttachment = &attach;\n    attach.layout = VK_IMAGE_LAYOUT_GENERAL;\n    \/\/ perf warning for GENERAL layout on DS attachment\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,\n                                         \"GENERAL layout for depth attachment may not give optimal performance.\");\n    vk::CreateRenderPass(m_device->device(), &rpci, NULL, &rp);\n    m_errorMonitor->VerifyFound();\n    \/\/ error w\/ non-ds opt or GENERAL layout for color attachment\n    attach.layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"Layout for depth attachment is VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL but can only be \"\n                                         \"DEPTH_STENCIL_ATTACHMENT_OPTIMAL, DEPTH_STENCIL_READ_ONLY_OPTIMAL or GENERAL.\");\n    vk::CreateRenderPass(m_device->device(), &rpci, NULL, &rp);\n    m_errorMonitor->VerifyFound();\n    \/\/ For this error we need a valid renderpass so create default one\n    attach.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;\n    attach.attachment = 0;\n    attach_desc.format = depth_format;\n    attach_desc.samples = VK_SAMPLE_COUNT_1_BIT;\n    attach_desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;\n    attach_desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;\n    attach_desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;\n    \/\/ Can't do a CLEAR load on READ_ONLY initialLayout\n    attach_desc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;\n    attach_desc.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;\n    attach_desc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"with invalid first layout VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL\");\n    vk::CreateRenderPass(m_device->device(), &rpci, NULL, &rp);\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, InvalidStorageImageLayout) {\n    TEST_DESCRIPTION(\"Attempt to update a STORAGE_IMAGE descriptor w\/o GENERAL layout.\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;\n    VkImageTiling tiling;\n    VkFormatProperties format_properties;\n    vk::GetPhysicalDeviceFormatProperties(gpu(), tex_format, &format_properties);\n    if (format_properties.linearTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) {\n        tiling = VK_IMAGE_TILING_LINEAR;\n    } else if (format_properties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) {\n        tiling = VK_IMAGE_TILING_OPTIMAL;\n    } else {\n        printf(\"%s Device does not support VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT; skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    OneOffDescriptorSet descriptor_set(m_device,\n                                       {\n                                           {0, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr},\n                                       });\n\n    VkImageObj image(m_device);\n    image.Init(32, 32, 1, tex_format, VK_IMAGE_USAGE_STORAGE_BIT, tiling, 0);\n    ASSERT_TRUE(image.initialized());\n    VkImageView view = image.targetView(tex_format);\n\n    descriptor_set.WriteDescriptorImageInfo(0, view, VK_NULL_HANDLE, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \" of VK_DESCRIPTOR_TYPE_STORAGE_IMAGE type is being updated with layout \"\n                                         \"VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL but according to spec \");\n    descriptor_set.UpdateDescriptorSets();\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, CreateImageViewBreaksParameterCompatibilityRequirements) {\n    TEST_DESCRIPTION(\n        \"Attempts to create an Image View with a view type that does not match the image type it is being created from.\");\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE1_EXTENSION_NAME)) {\n        m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);\n    }\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    VkPhysicalDeviceMemoryProperties memProps;\n    vk::GetPhysicalDeviceMemoryProperties(m_device->phy().handle(), &memProps);\n\n    \/\/ Test mismatch detection for image of type VK_IMAGE_TYPE_1D\n    VkImageCreateInfo imgInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,\n                                 nullptr,\n                                 VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT,\n                                 VK_IMAGE_TYPE_1D,\n                                 VK_FORMAT_R8G8B8A8_UNORM,\n                                 {1, 1, 1},\n                                 1,\n                                 1,\n                                 VK_SAMPLE_COUNT_1_BIT,\n                                 VK_IMAGE_TILING_OPTIMAL,\n                                 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,\n                                 VK_SHARING_MODE_EXCLUSIVE,\n                                 0,\n                                 nullptr,\n                                 VK_IMAGE_LAYOUT_UNDEFINED};\n    VkImageObj image1D(m_device);\n    image1D.init(&imgInfo);\n    ASSERT_TRUE(image1D.initialized());\n\n    \/\/ Initialize VkImageViewCreateInfo with mismatched viewType\n    VkImageViewCreateInfo ivci = {};\n    ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    ivci.image = image1D.handle();\n    ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;\n    ivci.format = VK_FORMAT_R8G8B8A8_UNORM;\n    ivci.subresourceRange.layerCount = 1;\n    ivci.subresourceRange.baseMipLevel = 0;\n    ivci.subresourceRange.levelCount = 1;\n    ivci.subresourceRange.baseArrayLayer = 0;\n    ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n\n    \/\/ Test for error message\n    CreateImageViewTest(*this, &ivci,\n                        \"vkCreateImageView(): pCreateInfo->viewType VK_IMAGE_VIEW_TYPE_2D is not compatible with image\");\n\n    \/\/ Test mismatch detection for image of type VK_IMAGE_TYPE_2D\n    imgInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,\n               nullptr,\n               VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT,\n               VK_IMAGE_TYPE_2D,\n               VK_FORMAT_R8G8B8A8_UNORM,\n               {1, 1, 1},\n               1,\n               6,\n               VK_SAMPLE_COUNT_1_BIT,\n               VK_IMAGE_TILING_OPTIMAL,\n               VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,\n               VK_SHARING_MODE_EXCLUSIVE,\n               0,\n               nullptr,\n               VK_IMAGE_LAYOUT_UNDEFINED};\n    VkImageObj image2D(m_device);\n    image2D.init(&imgInfo);\n    ASSERT_TRUE(image2D.initialized());\n\n    \/\/ Initialize VkImageViewCreateInfo with mismatched viewType\n    ivci = {};\n    ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    ivci.image = image2D.handle();\n    ivci.viewType = VK_IMAGE_VIEW_TYPE_3D;\n    ivci.format = VK_FORMAT_R8G8B8A8_UNORM;\n    ivci.subresourceRange.layerCount = 1;\n    ivci.subresourceRange.baseMipLevel = 0;\n    ivci.subresourceRange.levelCount = 1;\n    ivci.subresourceRange.baseArrayLayer = 0;\n    ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n\n    \/\/ Test for error message\n    CreateImageViewTest(*this, &ivci,\n                        \"vkCreateImageView(): pCreateInfo->viewType VK_IMAGE_VIEW_TYPE_3D is not compatible with image\");\n\n    \/\/ Change VkImageViewCreateInfo to different mismatched viewType\n    ivci.viewType = VK_IMAGE_VIEW_TYPE_CUBE;\n    ivci.subresourceRange.layerCount = 6;\n\n    \/\/ Test for error message\n    CreateImageViewTest(*this, &ivci, \"VUID-VkImageViewCreateInfo-image-01003\");\n\n    \/\/ Test mismatch detection for image of type VK_IMAGE_TYPE_3D\n    imgInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,\n               nullptr,\n               VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT,\n               VK_IMAGE_TYPE_3D,\n               VK_FORMAT_R8G8B8A8_UNORM,\n               {1, 1, 1},\n               1,\n               1,\n               VK_SAMPLE_COUNT_1_BIT,\n               VK_IMAGE_TILING_OPTIMAL,\n               VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,\n               VK_SHARING_MODE_EXCLUSIVE,\n               0,\n               nullptr,\n               VK_IMAGE_LAYOUT_UNDEFINED};\n    VkImageObj image3D(m_device);\n    image3D.init(&imgInfo);\n    ASSERT_TRUE(image3D.initialized());\n\n    \/\/ Initialize VkImageViewCreateInfo with mismatched viewType\n    ivci = {};\n    ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    ivci.image = image3D.handle();\n    ivci.viewType = VK_IMAGE_VIEW_TYPE_1D;\n    ivci.format = VK_FORMAT_R8G8B8A8_UNORM;\n    ivci.subresourceRange.layerCount = 1;\n    ivci.subresourceRange.baseMipLevel = 0;\n    ivci.subresourceRange.levelCount = 1;\n    ivci.subresourceRange.baseArrayLayer = 0;\n    ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n\n    \/\/ Test for error message\n    CreateImageViewTest(*this, &ivci,\n                        \"vkCreateImageView(): pCreateInfo->viewType VK_IMAGE_VIEW_TYPE_1D is not compatible with image\");\n\n    \/\/ Change VkImageViewCreateInfo to different mismatched viewType\n    ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;\n\n    \/\/ Test for error message\n    if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE1_EXTENSION_NAME)) {\n        CreateImageViewTest(*this, &ivci, \"VUID-VkImageViewCreateInfo-image-01005\");\n    } else {\n        CreateImageViewTest(*this, &ivci, \"VUID-VkImageViewCreateInfo-subResourceRange-01021\");\n    }\n\n    \/\/ Check if the device can make the image required for this test case.\n    VkImageFormatProperties formProps = {{0, 0, 0}, 0, 0, 0, 0};\n    VkResult res = vk::GetPhysicalDeviceImageFormatProperties(\n        m_device->phy().handle(), VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TYPE_3D, VK_IMAGE_TILING_OPTIMAL,\n        VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,\n        VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR | VK_IMAGE_CREATE_SPARSE_BINDING_BIT,\n        &formProps);\n\n    \/\/ If not, skip this part of the test.\n    if (res || !m_device->phy().features().sparseBinding ||\n        !DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE1_EXTENSION_NAME)) {\n        printf(\"%s %s is not supported.\\n\", kSkipPrefix, VK_KHR_MAINTENANCE1_EXTENSION_NAME);\n        return;\n    }\n\n    \/\/ Initialize VkImageCreateInfo with VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR and VK_IMAGE_CREATE_SPARSE_BINDING_BIT which\n    \/\/ are incompatible create flags.\n    imgInfo = {\n        VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,\n        nullptr,\n        VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR | VK_IMAGE_CREATE_SPARSE_BINDING_BIT,\n        VK_IMAGE_TYPE_3D,\n        VK_FORMAT_R8G8B8A8_UNORM,\n        {1, 1, 1},\n        1,\n        1,\n        VK_SAMPLE_COUNT_1_BIT,\n        VK_IMAGE_TILING_OPTIMAL,\n        VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,\n        VK_SHARING_MODE_EXCLUSIVE,\n        0,\n        nullptr,\n        VK_IMAGE_LAYOUT_UNDEFINED};\n    VkImage imageSparse;\n\n    \/\/ Creating a sparse image means we should not bind memory to it.\n    res = vk::CreateImage(m_device->device(), &imgInfo, NULL, &imageSparse);\n    ASSERT_FALSE(res);\n\n    \/\/ Initialize VkImageViewCreateInfo to create a view that will attempt to utilize VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR.\n    ivci = {};\n    ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    ivci.image = imageSparse;\n    ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;\n    ivci.format = VK_FORMAT_R8G8B8A8_UNORM;\n    ivci.subresourceRange.layerCount = 1;\n    ivci.subresourceRange.baseMipLevel = 0;\n    ivci.subresourceRange.levelCount = 1;\n    ivci.subresourceRange.baseArrayLayer = 0;\n    ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n\n    \/\/ Test for error message\n    CreateImageViewTest(*this, &ivci,\n                        \" when the VK_IMAGE_CREATE_SPARSE_BINDING_BIT, VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT, or \"\n                        \"VK_IMAGE_CREATE_SPARSE_ALIASED_BIT flags are enabled.\");\n\n    \/\/ Clean up\n    vk::DestroyImage(m_device->device(), imageSparse, nullptr);\n}\n\nTEST_F(VkLayerTest, CreateImageViewFormatFeatureMismatch) {\n    TEST_DESCRIPTION(\"Create view with a format that does not have the same features as the image format.\");\n\n    if (!EnableDeviceProfileLayer()) {\n        printf(\"%s Failed to enable device profile layer.\\n\", kSkipPrefix);\n        return;\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    PFN_vkSetPhysicalDeviceFormatPropertiesEXT fpvkSetPhysicalDeviceFormatPropertiesEXT = nullptr;\n    PFN_vkGetOriginalPhysicalDeviceFormatPropertiesEXT fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT = nullptr;\n\n    \/\/ Load required functions\n    if (!LoadDeviceProfileLayer(fpvkSetPhysicalDeviceFormatPropertiesEXT, fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT)) {\n        printf(\"%s Failed to device profile layer.\\n\", kSkipPrefix);\n        return;\n    }\n\n    \/\/ List of features to be tested\n    VkFormatFeatureFlagBits features[] = {VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT, VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT,\n                                          VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT};\n    uint32_t feature_count = 4;\n    \/\/ List of usage cases for each feature test\n    VkImageUsageFlags usages[] = {VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_USAGE_STORAGE_BIT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,\n                                  VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT};\n    \/\/ List of errors that will be thrown in order of tests run\n    std::string optimal_error_codes[] = {\n        \"VUID-VkImageViewCreateInfo-usage-02274\",\n        \"VUID-VkImageViewCreateInfo-usage-02275\",\n        \"VUID-VkImageViewCreateInfo-usage-02276\",\n        \"VUID-VkImageViewCreateInfo-usage-02277\",\n    };\n\n    VkFormatProperties formatProps;\n\n    \/\/ First three tests\n    uint32_t i = 0;\n    for (i = 0; i < (feature_count - 1); i++) {\n        \/\/ Modify formats to have mismatched features\n\n        \/\/ Format for image\n        fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_R32G32B32A32_UINT, &formatProps);\n        formatProps.optimalTilingFeatures |= features[i];\n        fpvkSetPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_R32G32B32A32_UINT, formatProps);\n\n        memset(&formatProps, 0, sizeof(formatProps));\n\n        \/\/ Format for view\n        fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_R32G32B32A32_SINT, &formatProps);\n        formatProps.optimalTilingFeatures = features[(i + 1) % feature_count];\n        fpvkSetPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_R32G32B32A32_SINT, formatProps);\n\n        \/\/ Create image with modified format\n        VkImageCreateInfo imgInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,\n                                     nullptr,\n                                     VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT,\n                                     VK_IMAGE_TYPE_2D,\n                                     VK_FORMAT_R32G32B32A32_UINT,\n                                     {1, 1, 1},\n                                     1,\n                                     1,\n                                     VK_SAMPLE_COUNT_1_BIT,\n                                     VK_IMAGE_TILING_OPTIMAL,\n                                     usages[i],\n                                     VK_SHARING_MODE_EXCLUSIVE,\n                                     0,\n                                     nullptr,\n                                     VK_IMAGE_LAYOUT_UNDEFINED};\n        VkImageObj image(m_device);\n        image.init(&imgInfo);\n        ASSERT_TRUE(image.initialized());\n\n        \/\/ Initialize VkImageViewCreateInfo with modified format\n        VkImageViewCreateInfo ivci = {};\n        ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n        ivci.image = image.handle();\n        ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;\n        ivci.format = VK_FORMAT_R32G32B32A32_SINT;\n        ivci.subresourceRange.layerCount = 1;\n        ivci.subresourceRange.baseMipLevel = 0;\n        ivci.subresourceRange.levelCount = 1;\n        ivci.subresourceRange.baseArrayLayer = 0;\n        ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n\n        \/\/ Test for error message\n        CreateImageViewTest(*this, &ivci, optimal_error_codes[i]);\n    }\n\n    \/\/ Test for VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT.  Needs special formats\n\n    \/\/ Only run this test if format supported\n    if (!ImageFormatIsSupported(gpu(), VK_FORMAT_D24_UNORM_S8_UINT, VK_IMAGE_TILING_OPTIMAL)) {\n        printf(\"%s VK_FORMAT_D24_UNORM_S8_UINT format not supported - skipped.\\n\", kSkipPrefix);\n        return;\n    }\n    \/\/ Modify formats to have mismatched features\n\n    \/\/ Format for image\n    fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_D24_UNORM_S8_UINT, &formatProps);\n    formatProps.optimalTilingFeatures |= features[i];\n    fpvkSetPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_D24_UNORM_S8_UINT, formatProps);\n\n    memset(&formatProps, 0, sizeof(formatProps));\n\n    \/\/ Format for view\n    fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_D32_SFLOAT_S8_UINT, &formatProps);\n    formatProps.optimalTilingFeatures = features[(i + 1) % feature_count];\n    fpvkSetPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_D32_SFLOAT_S8_UINT, formatProps);\n\n    \/\/ Create image with modified format\n    VkImageCreateInfo imgInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,\n                                 nullptr,\n                                 VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT,\n                                 VK_IMAGE_TYPE_2D,\n                                 VK_FORMAT_D24_UNORM_S8_UINT,\n                                 {1, 1, 1},\n                                 1,\n                                 1,\n                                 VK_SAMPLE_COUNT_1_BIT,\n                                 VK_IMAGE_TILING_OPTIMAL,\n                                 usages[i],\n                                 VK_SHARING_MODE_EXCLUSIVE,\n                                 0,\n                                 nullptr,\n                                 VK_IMAGE_LAYOUT_UNDEFINED};\n    VkImageObj image(m_device);\n    image.init(&imgInfo);\n    ASSERT_TRUE(image.initialized());\n\n    \/\/ Initialize VkImageViewCreateInfo with modified format\n    VkImageViewCreateInfo ivci = {};\n    ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    ivci.image = image.handle();\n    ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;\n    ivci.format = VK_FORMAT_D32_SFLOAT_S8_UINT;\n    ivci.subresourceRange.layerCount = 1;\n    ivci.subresourceRange.baseMipLevel = 0;\n    ivci.subresourceRange.levelCount = 1;\n    ivci.subresourceRange.baseArrayLayer = 0;\n    ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;\n\n    \/\/ Test for error message\n    CreateImageViewTest(*this, &ivci, optimal_error_codes[i]);\n}\n\nTEST_F(VkLayerTest, InvalidImageViewUsageCreateInfo) {\n    TEST_DESCRIPTION(\"Usage modification via a chained VkImageViewUsageCreateInfo struct\");\n\n    if (!EnableDeviceProfileLayer()) {\n        printf(\"%s Test requires DeviceProfileLayer, unavailable - skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    if (!DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE2_EXTENSION_NAME)) {\n        printf(\"%s Test requires API >= 1.1 or KHR_MAINTENANCE2 extension, unavailable - skipped.\\n\", kSkipPrefix);\n        return;\n    }\n    m_device_extension_names.push_back(VK_KHR_MAINTENANCE2_EXTENSION_NAME);\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    PFN_vkSetPhysicalDeviceFormatPropertiesEXT fpvkSetPhysicalDeviceFormatPropertiesEXT = nullptr;\n    PFN_vkGetOriginalPhysicalDeviceFormatPropertiesEXT fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT = nullptr;\n\n    \/\/ Load required functions\n    if (!LoadDeviceProfileLayer(fpvkSetPhysicalDeviceFormatPropertiesEXT, fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT)) {\n        printf(\"%s Required extensions are not avaiable.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkFormatProperties formatProps;\n\n    \/\/ Ensure image format claims support for sampled and storage, excludes color attachment\n    memset(&formatProps, 0, sizeof(formatProps));\n    fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_R32G32B32A32_UINT, &formatProps);\n    formatProps.optimalTilingFeatures |= (VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT);\n    formatProps.optimalTilingFeatures = formatProps.optimalTilingFeatures & ~VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT;\n    fpvkSetPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_R32G32B32A32_UINT, formatProps);\n\n    \/\/ Create image with sampled and storage usages\n    VkImageCreateInfo imgInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,\n                                 nullptr,\n                                 VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT,\n                                 VK_IMAGE_TYPE_2D,\n                                 VK_FORMAT_R32G32B32A32_UINT,\n                                 {1, 1, 1},\n                                 1,\n                                 1,\n                                 VK_SAMPLE_COUNT_1_BIT,\n                                 VK_IMAGE_TILING_OPTIMAL,\n                                 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT,\n                                 VK_SHARING_MODE_EXCLUSIVE,\n                                 0,\n                                 nullptr,\n                                 VK_IMAGE_LAYOUT_UNDEFINED};\n    VkImageObj image(m_device);\n    image.init(&imgInfo);\n    ASSERT_TRUE(image.initialized());\n\n    \/\/ Force the imageview format to exclude storage feature, include color attachment\n    memset(&formatProps, 0, sizeof(formatProps));\n    fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_R32G32B32A32_SINT, &formatProps);\n    formatProps.optimalTilingFeatures |= VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT;\n    formatProps.optimalTilingFeatures = (formatProps.optimalTilingFeatures & ~VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT);\n    fpvkSetPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_R32G32B32A32_SINT, formatProps);\n\n    VkImageViewCreateInfo ivci = {};\n    ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    ivci.image = image.handle();\n    ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;\n    ivci.format = VK_FORMAT_R32G32B32A32_SINT;\n    ivci.subresourceRange.layerCount = 1;\n    ivci.subresourceRange.baseMipLevel = 0;\n    ivci.subresourceRange.levelCount = 1;\n    ivci.subresourceRange.baseArrayLayer = 0;\n    ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n\n    \/\/ ImageView creation should fail because view format doesn't support all the underlying image's usages\n    CreateImageViewTest(*this, &ivci, \"VUID-VkImageViewCreateInfo-usage-02275\");\n\n    \/\/ Add a chained VkImageViewUsageCreateInfo to override original image usage bits, removing storage\n    VkImageViewUsageCreateInfo usage_ci = {VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO, nullptr, VK_IMAGE_USAGE_SAMPLED_BIT};\n    \/\/ Link the VkImageViewUsageCreateInfo struct into the view's create info pNext chain\n    ivci.pNext = &usage_ci;\n\n    \/\/ ImageView should now succeed without error\n    CreateImageViewTest(*this, &ivci);\n\n    \/\/ Try a zero usage field\n    usage_ci.usage = 0;\n    CreateImageViewTest(*this, &ivci, \"VUID-VkImageViewUsageCreateInfo-usage-requiredbitmask\");\n\n    \/\/ Try an illegal bit in usage field\n    usage_ci.usage = 0x10000000 | VK_IMAGE_USAGE_SAMPLED_BIT;\n    CreateImageViewTest(*this, &ivci, \"VUID-VkImageViewUsageCreateInfo-usage-parameter\");\n}\n\nTEST_F(VkLayerTest, CreateImageViewNoMemoryBoundToImage) {\n    VkResult err;\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    \/\/ Create an image and try to create a view with no memory backing the image\n    VkImage image;\n\n    const VkFormat tex_format = VK_FORMAT_B8G8R8A8_UNORM;\n    const int32_t tex_width = 32;\n    const int32_t tex_height = 32;\n\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = tex_format;\n    image_create_info.extent.width = tex_width;\n    image_create_info.extent.height = tex_height;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT;\n    image_create_info.flags = 0;\n\n    err = vk::CreateImage(m_device->device(), &image_create_info, NULL, &image);\n    ASSERT_VK_SUCCESS(err);\n\n    VkImageViewCreateInfo image_view_create_info = {};\n    image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    image_view_create_info.image = image;\n    image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;\n    image_view_create_info.format = tex_format;\n    image_view_create_info.subresourceRange.layerCount = 1;\n    image_view_create_info.subresourceRange.baseMipLevel = 0;\n    image_view_create_info.subresourceRange.levelCount = 1;\n    image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n\n    CreateImageViewTest(*this, &image_view_create_info,\n                        \" used with no memory bound. Memory should be bound by calling vkBindImageMemory().\");\n    vk::DestroyImage(m_device->device(), image, NULL);\n}\n\nTEST_F(VkLayerTest, InvalidImageViewAspect) {\n    TEST_DESCRIPTION(\"Create an image and try to create a view with an invalid aspectMask\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    const VkFormat tex_format = VK_FORMAT_B8G8R8A8_UNORM;\n    VkImageObj image(m_device);\n    image.Init(32, 32, 1, tex_format, VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_TILING_LINEAR, 0);\n    ASSERT_TRUE(image.initialized());\n\n    VkImageViewCreateInfo image_view_create_info = {};\n    image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    image_view_create_info.image = image.handle();\n    image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;\n    image_view_create_info.format = tex_format;\n    image_view_create_info.subresourceRange.baseMipLevel = 0;\n    image_view_create_info.subresourceRange.levelCount = 1;\n    image_view_create_info.subresourceRange.layerCount = 1;\n    \/\/ Cause an error by setting an invalid image aspect\n    image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_METADATA_BIT;\n\n    CreateImageViewTest(*this, &image_view_create_info, \"VUID-VkImageSubresource-aspectMask-parameter\");\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, ExerciseGetImageSubresourceLayout) {\n    TEST_DESCRIPTION(\"Test vkGetImageSubresourceLayout() valid usages\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    VkSubresourceLayout subres_layout = {};\n\n    \/\/ VU 00732: image must have been created with tiling equal to VK_IMAGE_TILING_LINEAR\n    {\n        const VkImageTiling tiling = VK_IMAGE_TILING_OPTIMAL;  \/\/ ERROR: violates VU 00732\n        VkImageObj img(m_device);\n        img.InitNoLayout(32, 32, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, tiling);\n        ASSERT_TRUE(img.initialized());\n\n        VkImageSubresource subres = {};\n        subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n        subres.mipLevel = 0;\n        subres.arrayLayer = 0;\n\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkGetImageSubresourceLayout-image-00996\");\n        vk::GetImageSubresourceLayout(m_device->device(), img.image(), &subres, &subres_layout);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ VU 00733: The aspectMask member of pSubresource must only have a single bit set\n    {\n        VkImageObj img(m_device);\n        img.InitNoLayout(32, 32, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_TRANSFER_SRC_BIT);\n        ASSERT_TRUE(img.initialized());\n\n        VkImageSubresource subres = {};\n        subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT | VK_IMAGE_ASPECT_METADATA_BIT;  \/\/ ERROR: triggers VU 00733\n        subres.mipLevel = 0;\n        subres.arrayLayer = 0;\n\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkGetImageSubresourceLayout-aspectMask-00997\");\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageSubresource-aspectMask-parameter\");\n        vk::GetImageSubresourceLayout(m_device->device(), img.image(), &subres, &subres_layout);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ 00739 mipLevel must be less than the mipLevels specified in VkImageCreateInfo when the image was created\n    {\n        VkImageObj img(m_device);\n        img.InitNoLayout(32, 32, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_TRANSFER_SRC_BIT);\n        ASSERT_TRUE(img.initialized());\n\n        VkImageSubresource subres = {};\n        subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n        subres.mipLevel = 1;  \/\/ ERROR: triggers VU 00739\n        subres.arrayLayer = 0;\n\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkGetImageSubresourceLayout-mipLevel-01716\");\n        vk::GetImageSubresourceLayout(m_device->device(), img.image(), &subres, &subres_layout);\n        m_errorMonitor->VerifyFound();\n    }\n\n    \/\/ 00740 arrayLayer must be less than the arrayLayers specified in VkImageCreateInfo when the image was created\n    {\n        VkImageObj img(m_device);\n        img.InitNoLayout(32, 32, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_TRANSFER_SRC_BIT);\n        ASSERT_TRUE(img.initialized());\n\n        VkImageSubresource subres = {};\n        subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n        subres.mipLevel = 0;\n        subres.arrayLayer = 1;  \/\/ ERROR: triggers VU 00740\n\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkGetImageSubresourceLayout-arrayLayer-01717\");\n        vk::GetImageSubresourceLayout(m_device->device(), img.image(), &subres, &subres_layout);\n        m_errorMonitor->VerifyFound();\n    }\n}\n\nTEST_F(VkLayerTest, ImageLayerUnsupportedFormat) {\n    TEST_DESCRIPTION(\"Creating images with unsupported formats \");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    \/\/ Create image with unsupported format - Expect FORMAT_UNSUPPORTED\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = VK_FORMAT_UNDEFINED;\n    image_create_info.extent.width = 32;\n    image_create_info.extent.height = 32;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-format-00943\");\n}\n\nTEST_F(VkLayerTest, CreateImageViewFormatMismatchUnrelated) {\n    TEST_DESCRIPTION(\"Create an image with a color format, then try to create a depth view of it\");\n\n    if (!EnableDeviceProfileLayer()) {\n        printf(\"%s Failed to enable device profile layer.\\n\", kSkipPrefix);\n        return;\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    \/\/ Load required functions\n    PFN_vkSetPhysicalDeviceFormatPropertiesEXT fpvkSetPhysicalDeviceFormatPropertiesEXT =\n        (PFN_vkSetPhysicalDeviceFormatPropertiesEXT)vk::GetInstanceProcAddr(instance(), \"vkSetPhysicalDeviceFormatPropertiesEXT\");\n    PFN_vkGetOriginalPhysicalDeviceFormatPropertiesEXT fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT =\n        (PFN_vkGetOriginalPhysicalDeviceFormatPropertiesEXT)vk::GetInstanceProcAddr(\n            instance(), \"vkGetOriginalPhysicalDeviceFormatPropertiesEXT\");\n\n    if (!(fpvkSetPhysicalDeviceFormatPropertiesEXT) || !(fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT)) {\n        printf(\"%s Can't find device_profile_api functions; skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    auto depth_format = FindSupportedDepthStencilFormat(gpu());\n    if (!depth_format) {\n        printf(\"%s Couldn't find depth stencil image format.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkFormatProperties formatProps;\n\n    fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT(gpu(), depth_format, &formatProps);\n    formatProps.optimalTilingFeatures |= VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT;\n    fpvkSetPhysicalDeviceFormatPropertiesEXT(gpu(), depth_format, formatProps);\n\n    VkImageObj image(m_device);\n    image.Init(128, 128, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL, 0);\n    ASSERT_TRUE(image.initialized());\n\n    VkImageViewCreateInfo imgViewInfo = {};\n    imgViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    imgViewInfo.image = image.handle();\n    imgViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;\n    imgViewInfo.format = depth_format;\n    imgViewInfo.subresourceRange.layerCount = 1;\n    imgViewInfo.subresourceRange.baseMipLevel = 0;\n    imgViewInfo.subresourceRange.levelCount = 1;\n    imgViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n\n    \/\/ Can't use depth format for view into color image - Expect INVALID_FORMAT\n    CreateImageViewTest(*this, &imgViewInfo,\n                        \"Formats MUST be IDENTICAL unless VK_IMAGE_CREATE_MUTABLE_FORMAT BIT was set on image creation.\");\n}\n\nTEST_F(VkLayerTest, CreateImageViewNoMutableFormatBit) {\n    TEST_DESCRIPTION(\"Create an image view with a different format, when the image does not have MUTABLE_FORMAT bit\");\n\n    if (!EnableDeviceProfileLayer()) {\n        printf(\"%s Couldn't enable device profile layer.\\n\", kSkipPrefix);\n        return;\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    PFN_vkSetPhysicalDeviceFormatPropertiesEXT fpvkSetPhysicalDeviceFormatPropertiesEXT = nullptr;\n    PFN_vkGetOriginalPhysicalDeviceFormatPropertiesEXT fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT = nullptr;\n\n    \/\/ Load required functions\n    if (!LoadDeviceProfileLayer(fpvkSetPhysicalDeviceFormatPropertiesEXT, fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT)) {\n        printf(\"%s Required extensions are not present.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkImageObj image(m_device);\n    image.Init(128, 128, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL, 0);\n    ASSERT_TRUE(image.initialized());\n\n    VkFormatProperties formatProps;\n\n    fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_B8G8R8A8_UINT, &formatProps);\n    formatProps.optimalTilingFeatures |= VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT;\n    fpvkSetPhysicalDeviceFormatPropertiesEXT(gpu(), VK_FORMAT_B8G8R8A8_UINT, formatProps);\n\n    VkImageViewCreateInfo imgViewInfo = {};\n    imgViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    imgViewInfo.image = image.handle();\n    imgViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;\n    imgViewInfo.format = VK_FORMAT_B8G8R8A8_UINT;\n    imgViewInfo.subresourceRange.layerCount = 1;\n    imgViewInfo.subresourceRange.baseMipLevel = 0;\n    imgViewInfo.subresourceRange.levelCount = 1;\n    imgViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n\n    \/\/ Same compatibility class but no MUTABLE_FORMAT bit - Expect\n    \/\/ VIEW_CREATE_ERROR\n    CreateImageViewTest(*this, &imgViewInfo, \"VUID-VkImageViewCreateInfo-image-01019\");\n}\n\nTEST_F(VkLayerTest, CreateImageViewDifferentClass) {\n    TEST_DESCRIPTION(\"Passing bad parameters to CreateImageView\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    if (!(m_device->format_properties(VK_FORMAT_R8_UINT).optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) {\n        printf(\"%s Device does not support R8_UINT as color attachment; skipped\", kSkipPrefix);\n        return;\n    }\n\n    VkImageCreateInfo mutImgInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,\n                                    nullptr,\n                                    VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT,\n                                    VK_IMAGE_TYPE_2D,\n                                    VK_FORMAT_R8_UINT,\n                                    {128, 128, 1},\n                                    1,\n                                    1,\n                                    VK_SAMPLE_COUNT_1_BIT,\n                                    VK_IMAGE_TILING_OPTIMAL,\n                                    VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,\n                                    VK_SHARING_MODE_EXCLUSIVE,\n                                    0,\n                                    nullptr,\n                                    VK_IMAGE_LAYOUT_UNDEFINED};\n    VkImageObj mutImage(m_device);\n    mutImage.init(&mutImgInfo);\n    ASSERT_TRUE(mutImage.initialized());\n\n    VkImageViewCreateInfo imgViewInfo = {};\n    imgViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    imgViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;\n    imgViewInfo.format = VK_FORMAT_B8G8R8A8_UNORM;\n    imgViewInfo.subresourceRange.layerCount = 1;\n    imgViewInfo.subresourceRange.baseMipLevel = 0;\n    imgViewInfo.subresourceRange.levelCount = 1;\n    imgViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    imgViewInfo.image = mutImage.handle();\n\n    CreateImageViewTest(*this, &imgViewInfo, \"VUID-VkImageViewCreateInfo-image-01018\");\n}\n\nTEST_F(VkLayerTest, MultiplaneIncompatibleViewFormat) {\n    TEST_DESCRIPTION(\"Postive\/negative tests of multiplane imageview format compatibility\");\n\n    \/\/ Enable KHR multiplane req'd extensions\n    bool mp_extensions = InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,\n                                                    VK_KHR_GET_MEMORY_REQUIREMENTS_2_SPEC_VERSION);\n    if (mp_extensions) {\n        m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n    }\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE1_EXTENSION_NAME);\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);\n    if (mp_extensions) {\n        m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);\n    } else {\n        printf(\"%s test requires KHR multiplane extensions, not available.  Skipping.\\n\", kSkipPrefix);\n        return;\n    }\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    VkImageCreateInfo ci = {};\n    ci.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    ci.pNext = NULL;\n    ci.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;\n    ci.imageType = VK_IMAGE_TYPE_2D;\n    ci.format = VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM;\n    ci.tiling = VK_IMAGE_TILING_OPTIMAL;\n    ci.usage = VK_IMAGE_USAGE_SAMPLED_BIT;\n    ci.extent = {128, 128, 1};\n    ci.mipLevels = 1;\n    ci.arrayLayers = 1;\n    ci.samples = VK_SAMPLE_COUNT_1_BIT;\n    ci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n    ci.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n\n    \/\/ Verify format\n    VkFormatFeatureFlags features = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT;\n    bool supported = ImageFormatAndFeaturesSupported(instance(), gpu(), ci, features);\n    if (!supported) {\n        printf(\"%s Multiplane image format not supported.  Skipping test.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkImageObj image_obj(m_device);\n    image_obj.init(&ci);\n    ASSERT_TRUE(image_obj.initialized());\n\n    VkImageViewCreateInfo ivci = {};\n    ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    ivci.image = image_obj.image();\n    ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;\n    ivci.format = VK_FORMAT_R8_SNORM;  \/\/ Compat is VK_FORMAT_R8_UNORM\n    ivci.subresourceRange.layerCount = 1;\n    ivci.subresourceRange.baseMipLevel = 0;\n    ivci.subresourceRange.levelCount = 1;\n    ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_PLANE_1_BIT;\n\n    \/\/ Incompatible format error\n    CreateImageViewTest(*this, &ivci, \"VUID-VkImageViewCreateInfo-image-01586\");\n\n    \/\/ Correct format succeeds\n    ivci.format = VK_FORMAT_R8_UNORM;\n    CreateImageViewTest(*this, &ivci);\n\n    \/\/ Try a multiplane imageview\n    ivci.format = VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM;\n    ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    CreateImageViewTest(*this, &ivci);\n}\n\nTEST_F(VkLayerTest, CreateImageViewInvalidSubresourceRange) {\n    TEST_DESCRIPTION(\"Passing bad image subrange to CreateImageView\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkImageObj image(m_device);\n    image.Init(32, 32, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL);\n    ASSERT_TRUE(image.create_info().arrayLayers == 1);\n    ASSERT_TRUE(image.initialized());\n\n    VkImageViewCreateInfo img_view_info_template = {};\n    img_view_info_template.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    img_view_info_template.image = image.handle();\n    img_view_info_template.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY;\n    img_view_info_template.format = image.format();\n    \/\/ subresourceRange to be filled later for the purposes of this test\n    img_view_info_template.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    img_view_info_template.subresourceRange.baseMipLevel = 0;\n    img_view_info_template.subresourceRange.levelCount = 0;\n    img_view_info_template.subresourceRange.baseArrayLayer = 0;\n    img_view_info_template.subresourceRange.layerCount = 0;\n\n    \/\/ Try baseMipLevel >= image.mipLevels with VK_REMAINING_MIP_LEVELS\n    {\n        const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_REMAINING_MIP_LEVELS, 0, 1};\n        VkImageViewCreateInfo img_view_info = img_view_info_template;\n        img_view_info.subresourceRange = range;\n        CreateImageViewTest(*this, &img_view_info, \"VUID-VkImageViewCreateInfo-subresourceRange-01478\");\n    }\n\n    \/\/ Try baseMipLevel >= image.mipLevels without VK_REMAINING_MIP_LEVELS\n    {\n        const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 1, 1, 0, 1};\n        VkImageViewCreateInfo img_view_info = img_view_info_template;\n        img_view_info.subresourceRange = range;\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageViewCreateInfo-subresourceRange-01718\");\n        CreateImageViewTest(*this, &img_view_info, \"VUID-VkImageViewCreateInfo-subresourceRange-01478\");\n    }\n\n    \/\/ Try levelCount = 0\n    {\n        const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 0, 1};\n        VkImageViewCreateInfo img_view_info = img_view_info_template;\n        img_view_info.subresourceRange = range;\n        CreateImageViewTest(*this, &img_view_info, \"VUID-VkImageViewCreateInfo-subresourceRange-01718\");\n    }\n\n    \/\/ Try baseMipLevel + levelCount > image.mipLevels\n    {\n        const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 2, 0, 1};\n        VkImageViewCreateInfo img_view_info = img_view_info_template;\n        img_view_info.subresourceRange = range;\n        CreateImageViewTest(*this, &img_view_info, \"VUID-VkImageViewCreateInfo-subresourceRange-01718\");\n    }\n\n    \/\/ These tests rely on having the Maintenance1 extension not being enabled, and are invalid on all but version 1.0\n    if (m_device->props.apiVersion < VK_API_VERSION_1_1) {\n        \/\/ Try baseArrayLayer >= image.arrayLayers with VK_REMAINING_ARRAY_LAYERS\n        {\n            const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 1, VK_REMAINING_ARRAY_LAYERS};\n            VkImageViewCreateInfo img_view_info = img_view_info_template;\n            img_view_info.subresourceRange = range;\n            CreateImageViewTest(*this, &img_view_info, \"VUID-VkImageViewCreateInfo-subresourceRange-01480\");\n        }\n\n        \/\/ Try baseArrayLayer >= image.arrayLayers without VK_REMAINING_ARRAY_LAYERS\n        {\n            const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 1, 1};\n            VkImageViewCreateInfo img_view_info = img_view_info_template;\n            img_view_info.subresourceRange = range;\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                                 \"VUID-VkImageViewCreateInfo-subresourceRange-01719\");\n            CreateImageViewTest(*this, &img_view_info, \"VUID-VkImageViewCreateInfo-subresourceRange-01480\");\n        }\n\n        \/\/ Try layerCount = 0\n        {\n            const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 0};\n            VkImageViewCreateInfo img_view_info = img_view_info_template;\n            img_view_info.subresourceRange = range;\n            CreateImageViewTest(*this, &img_view_info, \"VUID-VkImageViewCreateInfo-subresourceRange-01719\");\n        }\n\n        \/\/ Try baseArrayLayer + layerCount > image.arrayLayers\n        {\n            const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 2};\n            VkImageViewCreateInfo img_view_info = img_view_info_template;\n            img_view_info.subresourceRange = range;\n            CreateImageViewTest(*this, &img_view_info, \"VUID-VkImageViewCreateInfo-subresourceRange-01719\");\n        }\n    }\n}\n\nTEST_F(VkLayerTest, CreateImageMiscErrors) {\n    TEST_DESCRIPTION(\"Misc leftover valid usage errors in VkImageCreateInfo struct\");\n\n    VkPhysicalDeviceFeatures features{};\n    ASSERT_NO_FATAL_FAILURE(Init(&features));\n\n    VkImageCreateInfo tmp_img_ci = {};\n    tmp_img_ci.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    tmp_img_ci.flags = 0;                          \/\/ assumably any is supported\n    tmp_img_ci.imageType = VK_IMAGE_TYPE_2D;       \/\/ any is supported\n    tmp_img_ci.format = VK_FORMAT_R8G8B8A8_UNORM;  \/\/ has mandatory support for all usages\n    tmp_img_ci.extent = {64, 64, 1};               \/\/ limit is 256 for 3D, or 4096\n    tmp_img_ci.mipLevels = 1;                      \/\/ any is supported\n    tmp_img_ci.arrayLayers = 1;                    \/\/ limit is 256\n    tmp_img_ci.samples = VK_SAMPLE_COUNT_1_BIT;    \/\/ needs to be 1 if TILING_LINEAR\n    \/\/ if VK_IMAGE_TILING_LINEAR imageType must be 2D, usage must be TRANSFER, and levels layers samplers all 1\n    tmp_img_ci.tiling = VK_IMAGE_TILING_OPTIMAL;\n    tmp_img_ci.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;  \/\/ depends on format\n    tmp_img_ci.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n    const VkImageCreateInfo safe_image_ci = tmp_img_ci;\n\n    ASSERT_VK_SUCCESS(GPDIFPHelper(gpu(), &safe_image_ci));\n\n    {\n        VkImageCreateInfo image_ci = safe_image_ci;\n        image_ci.sharingMode = VK_SHARING_MODE_CONCURRENT;\n        image_ci.queueFamilyIndexCount = 2;\n        image_ci.pQueueFamilyIndices = nullptr;\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-sharingMode-00941\");\n    }\n\n    {\n        VkImageCreateInfo image_ci = safe_image_ci;\n        image_ci.sharingMode = VK_SHARING_MODE_CONCURRENT;\n        image_ci.queueFamilyIndexCount = 1;\n        const uint32_t queue_family = 0;\n        image_ci.pQueueFamilyIndices = &queue_family;\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-sharingMode-00942\");\n    }\n\n    {\n        VkImageCreateInfo image_ci = safe_image_ci;\n        image_ci.format = VK_FORMAT_UNDEFINED;\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-format-00943\");\n    }\n\n    {\n        VkImageCreateInfo image_ci = safe_image_ci;\n        image_ci.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;\n        image_ci.arrayLayers = 6;\n        image_ci.imageType = VK_IMAGE_TYPE_1D;\n        m_errorMonitor->SetUnexpectedError(\"VUID-VkImageCreateInfo-imageType-00954\");\n        image_ci.extent = {64, 1, 1};\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-flags-00949\");\n\n        image_ci = safe_image_ci;\n        image_ci.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;\n        image_ci.imageType = VK_IMAGE_TYPE_3D;\n        m_errorMonitor->SetUnexpectedError(\"VUID-VkImageCreateInfo-imageType-00954\");\n        image_ci.extent = {4, 4, 4};\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-flags-00949\");\n\n        image_ci = safe_image_ci;\n        image_ci.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;\n        image_ci.imageType = VK_IMAGE_TYPE_2D;\n        image_ci.extent = {8, 6, 1};\n        image_ci.arrayLayers = 6;\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-imageType-00954\");\n\n        image_ci = safe_image_ci;\n        image_ci.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;\n        image_ci.imageType = VK_IMAGE_TYPE_2D;\n        image_ci.extent = {8, 8, 1};\n        image_ci.arrayLayers = 4;\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-imageType-00954\");\n    }\n\n    {\n        VkImageCreateInfo image_ci = safe_image_ci;\n        image_ci.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;  \/\/ always has 4 samples support\n        image_ci.samples = VK_SAMPLE_COUNT_4_BIT;\n        image_ci.imageType = VK_IMAGE_TYPE_3D;\n        image_ci.extent = {4, 4, 4};\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-samples-02257\");\n\n        image_ci = safe_image_ci;\n        image_ci.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;  \/\/ always has 4 samples support\n        image_ci.samples = VK_SAMPLE_COUNT_4_BIT;\n        image_ci.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;\n        image_ci.arrayLayers = 6;\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-samples-02257\");\n\n        image_ci = safe_image_ci;\n        image_ci.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;  \/\/ always has 4 samples support\n        image_ci.samples = VK_SAMPLE_COUNT_4_BIT;\n        image_ci.tiling = VK_IMAGE_TILING_LINEAR;\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-samples-02257\");\n\n        image_ci = safe_image_ci;\n        image_ci.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;  \/\/ always has 4 samples support\n        image_ci.samples = VK_SAMPLE_COUNT_4_BIT;\n        image_ci.mipLevels = 2;\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-samples-02257\");\n    }\n\n    {\n        VkImageCreateInfo image_ci = safe_image_ci;\n        image_ci.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;\n        image_ci.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-usage-00963\");\n\n        image_ci.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT;\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-usage-00966\");\n\n        image_ci.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT;\n        image_ci.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageCreateInfo-usage-00963\");\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-usage-00966\");\n    }\n\n    {\n        VkImageCreateInfo image_ci = safe_image_ci;\n        image_ci.flags = VK_IMAGE_CREATE_SPARSE_BINDING_BIT;\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-flags-00969\");\n    }\n\n    \/\/ InitialLayout not VK_IMAGE_LAYOUT_UNDEFINED or VK_IMAGE_LAYOUT_PREDEFINED\n    {\n        VkImageCreateInfo image_ci = safe_image_ci;\n        image_ci.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-initialLayout-00993\");\n    }\n}\n\nTEST_F(VkLayerTest, CreateImageMinLimitsViolation) {\n    TEST_DESCRIPTION(\"Create invalid image with invalid parameters violation minimum limit, such as being zero.\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkImage null_image;  \/\/ throwaway target for all the vk::CreateImage\n\n    VkImageCreateInfo tmp_img_ci = {};\n    tmp_img_ci.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    tmp_img_ci.flags = 0;                          \/\/ assumably any is supported\n    tmp_img_ci.imageType = VK_IMAGE_TYPE_2D;       \/\/ any is supported\n    tmp_img_ci.format = VK_FORMAT_R8G8B8A8_UNORM;  \/\/ has mandatory support for all usages\n    tmp_img_ci.extent = {1, 1, 1};                 \/\/ limit is 256 for 3D, or 4096\n    tmp_img_ci.mipLevels = 1;                      \/\/ any is supported\n    tmp_img_ci.arrayLayers = 1;                    \/\/ limit is 256\n    tmp_img_ci.samples = VK_SAMPLE_COUNT_1_BIT;    \/\/ needs to be 1 if TILING_LINEAR\n    \/\/ if VK_IMAGE_TILING_LINEAR imageType must be 2D, usage must be TRANSFER, and levels layers samplers all 1\n    tmp_img_ci.tiling = VK_IMAGE_TILING_OPTIMAL;\n    tmp_img_ci.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;  \/\/ depends on format\n    tmp_img_ci.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n    const VkImageCreateInfo safe_image_ci = tmp_img_ci;\n\n    enum Dimension { kWidth = 0x1, kHeight = 0x2, kDepth = 0x4 };\n\n    for (underlying_type<Dimension>::type bad_dimensions = 0x1; bad_dimensions < 0x8; ++bad_dimensions) {\n        VkExtent3D extent = {1, 1, 1};\n\n        if (bad_dimensions & kWidth) {\n            extent.width = 0;\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageCreateInfo-extent-00944\");\n        }\n\n        if (bad_dimensions & kHeight) {\n            extent.height = 0;\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageCreateInfo-extent-00945\");\n        }\n\n        if (bad_dimensions & kDepth) {\n            extent.depth = 0;\n            m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageCreateInfo-extent-00946\");\n        }\n\n        VkImageCreateInfo bad_image_ci = safe_image_ci;\n        bad_image_ci.imageType = VK_IMAGE_TYPE_3D;  \/\/ has to be 3D otherwise it might trigger the non-1 error instead\n        bad_image_ci.extent = extent;\n\n        vk::CreateImage(m_device->device(), &bad_image_ci, NULL, &null_image);\n\n        m_errorMonitor->VerifyFound();\n    }\n\n    {\n        VkImageCreateInfo bad_image_ci = safe_image_ci;\n        bad_image_ci.mipLevels = 0;\n        CreateImageTest(*this, &bad_image_ci, \"VUID-VkImageCreateInfo-mipLevels-00947\");\n    }\n\n    {\n        VkImageCreateInfo bad_image_ci = safe_image_ci;\n        bad_image_ci.arrayLayers = 0;\n        CreateImageTest(*this, &bad_image_ci, \"VUID-VkImageCreateInfo-arrayLayers-00948\");\n    }\n\n    {\n        VkImageCreateInfo bad_image_ci = safe_image_ci;\n        bad_image_ci.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;\n        bad_image_ci.arrayLayers = 5;\n        CreateImageTest(*this, &bad_image_ci, \"VUID-VkImageCreateInfo-imageType-00954\");\n\n        bad_image_ci.arrayLayers = 6;\n        bad_image_ci.extent = {64, 63, 1};\n        CreateImageTest(*this, &bad_image_ci, \"VUID-VkImageCreateInfo-imageType-00954\");\n    }\n\n    {\n        VkImageCreateInfo bad_image_ci = safe_image_ci;\n        bad_image_ci.imageType = VK_IMAGE_TYPE_1D;\n        bad_image_ci.extent = {64, 2, 1};\n        CreateImageTest(*this, &bad_image_ci, \"VUID-VkImageCreateInfo-imageType-00956\");\n\n        bad_image_ci.imageType = VK_IMAGE_TYPE_1D;\n        bad_image_ci.extent = {64, 1, 2};\n        CreateImageTest(*this, &bad_image_ci, \"VUID-VkImageCreateInfo-imageType-00956\");\n\n        bad_image_ci.imageType = VK_IMAGE_TYPE_2D;\n        bad_image_ci.extent = {64, 64, 2};\n        CreateImageTest(*this, &bad_image_ci, \"VUID-VkImageCreateInfo-imageType-00957\");\n\n        bad_image_ci.imageType = VK_IMAGE_TYPE_2D;\n        bad_image_ci.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;\n        bad_image_ci.arrayLayers = 6;\n        bad_image_ci.extent = {64, 64, 2};\n        CreateImageTest(*this, &bad_image_ci, \"VUID-VkImageCreateInfo-imageType-00957\");\n    }\n\n    {\n        VkImageCreateInfo bad_image_ci = safe_image_ci;\n        bad_image_ci.imageType = VK_IMAGE_TYPE_3D;\n        bad_image_ci.arrayLayers = 2;\n        CreateImageTest(*this, &bad_image_ci, \"VUID-VkImageCreateInfo-imageType-00961\");\n    }\n}\n\nTEST_F(VkLayerTest, CreateImageMaxLimitsViolation) {\n    TEST_DESCRIPTION(\"Create invalid image with invalid parameters exceeding physical device limits.\");\n\n    \/\/ Check for VK_KHR_get_physical_device_properties2\n    bool push_physical_device_properties_2_support =\n        InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n    if (push_physical_device_properties_2_support) {\n        m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n\n    bool push_fragment_density_support = false;\n\n    if (push_physical_device_properties_2_support) {\n        push_fragment_density_support = DeviceExtensionSupported(gpu(), nullptr, VK_EXT_FRAGMENT_DENSITY_MAP_EXTENSION_NAME);\n        if (push_fragment_density_support) m_device_extension_names.push_back(VK_EXT_FRAGMENT_DENSITY_MAP_EXTENSION_NAME);\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitState(nullptr, nullptr, 0));\n\n    VkImageCreateInfo tmp_img_ci = {};\n    tmp_img_ci.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    tmp_img_ci.flags = 0;                          \/\/ assumably any is supported\n    tmp_img_ci.imageType = VK_IMAGE_TYPE_2D;       \/\/ any is supported\n    tmp_img_ci.format = VK_FORMAT_R8G8B8A8_UNORM;  \/\/ has mandatory support for all usages\n    tmp_img_ci.extent = {1, 1, 1};                 \/\/ limit is 256 for 3D, or 4096\n    tmp_img_ci.mipLevels = 1;                      \/\/ any is supported\n    tmp_img_ci.arrayLayers = 1;                    \/\/ limit is 256\n    tmp_img_ci.samples = VK_SAMPLE_COUNT_1_BIT;    \/\/ needs to be 1 if TILING_LINEAR\n    \/\/ if VK_IMAGE_TILING_LINEAR imageType must be 2D, usage must be TRANSFER, and levels layers samplers all 1\n    tmp_img_ci.tiling = VK_IMAGE_TILING_OPTIMAL;\n    tmp_img_ci.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;  \/\/ depends on format\n    tmp_img_ci.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n    const VkImageCreateInfo safe_image_ci = tmp_img_ci;\n\n    ASSERT_VK_SUCCESS(GPDIFPHelper(gpu(), &safe_image_ci));\n\n    const VkPhysicalDeviceLimits &dev_limits = m_device->props.limits;\n\n    {\n        VkImageCreateInfo image_ci = safe_image_ci;\n        image_ci.extent = {8, 8, 1};\n        image_ci.mipLevels = 4 + 1;  \/\/ 4 = log2(8) + 1\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-mipLevels-00958\");\n\n        image_ci.extent = {8, 15, 1};\n        image_ci.mipLevels = 4 + 1;  \/\/ 4 = floor(log2(15)) + 1\n        CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-mipLevels-00958\");\n    }\n\n    {\n        VkImageCreateInfo image_ci = safe_image_ci;\n        image_ci.tiling = VK_IMAGE_TILING_LINEAR;\n        image_ci.extent = {64, 64, 1};\n        image_ci.format = FindFormatLinearWithoutMips(gpu(), image_ci);\n        image_ci.mipLevels = 2;\n\n        if (image_ci.format != VK_FORMAT_UNDEFINED) {\n            CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-mipLevels-02255\");\n        } else {\n            printf(\"%s Cannot find a format to test maxMipLevels limit; skipping part of test.\\n\", kSkipPrefix);\n        }\n    }\n\n    {\n        VkImageCreateInfo image_ci = safe_image_ci;\n\n        VkImageFormatProperties img_limits;\n        ASSERT_VK_SUCCESS(GPDIFPHelper(gpu(), &image_ci, &img_limits));\n\n        if (img_limits.maxArrayLayers != UINT32_MAX) {\n            image_ci.arrayLayers = img_limits.maxArrayLayers + 1;\n            CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-arrayLayers-02256\");\n        } else {\n            printf(\"%s VkImageFormatProperties::maxArrayLayers is already UINT32_MAX; skipping part of test.\\n\", kSkipPrefix);\n        }\n    }\n\n    {\n        VkImageCreateInfo image_ci = safe_image_ci;\n        bool found = FindFormatWithoutSamples(gpu(), image_ci);\n\n        if (found) {\n            CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-samples-02258\");\n        } else {\n            printf(\"%s Could not find a format with some unsupported samples; skipping part of test.\\n\", kSkipPrefix);\n        }\n    }\n\n    {\n        VkImageCreateInfo image_ci = safe_image_ci;\n        image_ci.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;  \/\/ (any attachment bit)\n\n        VkImageFormatProperties img_limits;\n        ASSERT_VK_SUCCESS(GPDIFPHelper(gpu(), &image_ci, &img_limits));\n\n        if (dev_limits.maxFramebufferWidth != UINT32_MAX) {\n            image_ci.extent = {dev_limits.maxFramebufferWidth + 1, 64, 1};\n            CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-usage-00964\");\n        } else {\n            printf(\"%s VkPhysicalDeviceLimits::maxFramebufferWidth is already UINT32_MAX; skipping part of test.\\n\", kSkipPrefix);\n        }\n\n        if (dev_limits.maxFramebufferHeight != UINT32_MAX) {\n            image_ci.usage = VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;  \/\/ try different one too\n            image_ci.extent = {64, dev_limits.maxFramebufferHeight + 1, 1};\n            CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-usage-00965\");\n        } else {\n            printf(\"%s VkPhysicalDeviceLimits::maxFramebufferHeight is already UINT32_MAX; skipping part of test.\\n\", kSkipPrefix);\n        }\n    }\n\n    {\n        if (!push_fragment_density_support) {\n            printf(\"%s VK_EXT_fragment_density_map Extension not supported, skipping tests\\n\", kSkipPrefix);\n        } else {\n            VkImageCreateInfo image_ci = safe_image_ci;\n            image_ci.usage = VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT;\n            VkImageFormatProperties img_limits;\n            ASSERT_VK_SUCCESS(GPDIFPHelper(gpu(), &image_ci, &img_limits));\n\n            image_ci.extent = {dev_limits.maxFramebufferWidth + 1, 64, 1};\n            CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-usage-02559\");\n\n            image_ci.extent = {64, dev_limits.maxFramebufferHeight + 1, 1};\n            CreateImageTest(*this, &image_ci, \"VUID-VkImageCreateInfo-usage-02560\");\n        }\n    }\n}\n\nTEST_F(VkLayerTest, MultiplaneImageSamplerConversionMismatch) {\n    TEST_DESCRIPTION(\n        \"Create sampler with ycbcr conversion and use with an image created without ycrcb conversion or immutable sampler\");\n\n    \/\/ Enable KHR multiplane req'd extensions\n    bool mp_extensions = InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,\n                                                    VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_SPEC_VERSION);\n    if (mp_extensions) {\n        m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n    }\n    SetTargetApiVersion(VK_API_VERSION_1_1);\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE1_EXTENSION_NAME);\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);\n    if (mp_extensions) {\n        m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);\n    } else {\n        printf(\"%s test requires KHR multiplane extensions, not available.  Skipping.\\n\", kSkipPrefix);\n        return;\n    }\n\n    \/\/ Enable Ycbcr Conversion Features\n    VkPhysicalDeviceSamplerYcbcrConversionFeatures ycbcr_features = {};\n    ycbcr_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES;\n    ycbcr_features.samplerYcbcrConversion = VK_TRUE;\n    ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &ycbcr_features));\n\n    PFN_vkCreateSamplerYcbcrConversionKHR vkCreateSamplerYcbcrConversionFunction = nullptr;\n    PFN_vkDestroySamplerYcbcrConversionKHR vkDestroySamplerYcbcrConversionFunction = nullptr;\n\n    if (DeviceValidationVersion() >= VK_API_VERSION_1_1) {\n        vkCreateSamplerYcbcrConversionFunction = vk::CreateSamplerYcbcrConversion;\n        vkDestroySamplerYcbcrConversionFunction = vk::DestroySamplerYcbcrConversion;\n    } else {\n        vkCreateSamplerYcbcrConversionFunction =\n            (PFN_vkCreateSamplerYcbcrConversionKHR)vk::GetDeviceProcAddr(m_device->handle(), \"vkCreateSamplerYcbcrConversionKHR\");\n        vkDestroySamplerYcbcrConversionFunction =\n            (PFN_vkDestroySamplerYcbcrConversionKHR)vk::GetDeviceProcAddr(m_device->handle(), \"vkDestroySamplerYcbcrConversionKHR\");\n    }\n\n    if (!vkCreateSamplerYcbcrConversionFunction || !vkDestroySamplerYcbcrConversionFunction) {\n        printf(\"%s Did not find required device extension %s; test skipped.\\n\", kSkipPrefix,\n               VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);\n        return;\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitViewport());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    const VkImageCreateInfo ci = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,\n                                  NULL,\n                                  0,\n                                  VK_IMAGE_TYPE_2D,\n                                  VK_FORMAT_G8_B8R8_2PLANE_420_UNORM_KHR,\n                                  {128, 128, 1},\n                                  1,\n                                  1,\n                                  VK_SAMPLE_COUNT_1_BIT,\n                                  VK_IMAGE_TILING_LINEAR,\n                                  VK_IMAGE_USAGE_SAMPLED_BIT,\n                                  VK_SHARING_MODE_EXCLUSIVE,\n                                  VK_IMAGE_LAYOUT_UNDEFINED};\n\n    \/\/ Verify formats\n    bool supported = ImageFormatAndFeaturesSupported(instance(), gpu(), ci, VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT);\n    if (!supported) {\n        printf(\"%s Multiplane image format not supported.  Skipping test.\\n\", kSkipPrefix);\n        return;\n    }\n\n    \/\/ Create Ycbcr conversion\n    VkSamplerYcbcrConversionCreateInfo ycbcr_create_info = {VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO,\n                                                            NULL,\n                                                            VK_FORMAT_G8_B8R8_2PLANE_420_UNORM_KHR,\n                                                            VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY,\n                                                            VK_SAMPLER_YCBCR_RANGE_ITU_FULL,\n                                                            {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,\n                                                             VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY},\n                                                            VK_CHROMA_LOCATION_COSITED_EVEN,\n                                                            VK_CHROMA_LOCATION_COSITED_EVEN,\n                                                            VK_FILTER_NEAREST,\n                                                            false};\n    VkSamplerYcbcrConversion conversions[2];\n    vkCreateSamplerYcbcrConversionFunction(m_device->handle(), &ycbcr_create_info, nullptr, &conversions[0]);\n    ycbcr_create_info.components.r = VK_COMPONENT_SWIZZLE_ZERO;  \/\/ Just anything different than above\n    vkCreateSamplerYcbcrConversionFunction(m_device->handle(), &ycbcr_create_info, nullptr, &conversions[1]);\n\n    VkSamplerYcbcrConversionInfo ycbcr_info = {};\n    ycbcr_info.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO;\n    ycbcr_info.conversion = conversions[0];\n\n    \/\/ Create a sampler using conversion\n    VkSamplerCreateInfo sci = SafeSaneSamplerCreateInfo();\n    sci.pNext = &ycbcr_info;\n    \/\/ Create two samplers with two different conversions, such that one will mismatch\n    \/\/ It will make the second sampler fail to see if the log prints the second sampler or the first sampler.\n    VkSampler samplers[2];\n    VkResult err = vk::CreateSampler(m_device->device(), &sci, NULL, &samplers[0]);\n    ASSERT_VK_SUCCESS(err);\n    ycbcr_info.conversion = conversions[1];  \/\/ Need two samplers with different conversions\n    err = vk::CreateSampler(m_device->device(), &sci, NULL, &samplers[1]);\n    ASSERT_VK_SUCCESS(err);\n\n    \/\/ Create an image without a Ycbcr conversion\n    VkImageObj mpimage(m_device);\n    mpimage.init(&ci);\n\n    VkImageView view;\n    VkImageViewCreateInfo ivci = {};\n    ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    ycbcr_info.conversion = conversions[0];  \/\/ Need two samplers with different conversions\n    ivci.pNext = &ycbcr_info;\n    ivci.image = mpimage.handle();\n    ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;\n    ivci.format = VK_FORMAT_G8_B8R8_2PLANE_420_UNORM_KHR;\n    ivci.subresourceRange.layerCount = 1;\n    ivci.subresourceRange.baseMipLevel = 0;\n    ivci.subresourceRange.levelCount = 1;\n    ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    vk::CreateImageView(m_device->device(), &ivci, nullptr, &view);\n\n    \/\/ Use the image and sampler together in a descriptor set\n    OneOffDescriptorSet descriptor_set(m_device,\n                                       {\n                                           {0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, VK_SHADER_STAGE_ALL, samplers},\n                                       });\n\n    \/\/ Use the same image view twice, using the same sampler, with the *second* mismatched with the *second* immutable sampler\n    VkDescriptorImageInfo image_infos[2];\n    image_infos[0] = {};\n    image_infos[0].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;\n    image_infos[0].imageView = view;\n    image_infos[0].sampler = samplers[0];\n    image_infos[1] = image_infos[0];\n\n    \/\/ Update the descriptor set expecting to get an error\n    VkWriteDescriptorSet descriptor_write = {};\n    descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;\n    descriptor_write.dstSet = descriptor_set.set_;\n    descriptor_write.dstBinding = 0;\n    descriptor_write.descriptorCount = 2;\n    descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n    descriptor_write.pImageInfo = image_infos;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkWriteDescriptorSet-descriptorType-01948\");\n    vk::UpdateDescriptorSets(m_device->device(), 1, &descriptor_write, 0, NULL);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ pImmutableSamplers = nullptr causes an error , VUID-VkWriteDescriptorSet-descriptorType-02738.\n    \/\/ Because if pNext chains a VkSamplerYcbcrConversionInfo, the sampler has to be a immutable sampler.\n    OneOffDescriptorSet descriptor_set_1947(m_device,\n                                            {\n                                                {0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, nullptr},\n                                            });\n    descriptor_write.dstSet = descriptor_set_1947.set_;\n    descriptor_write.descriptorCount = 1;\n    descriptor_write.pImageInfo = &image_infos[0];\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkWriteDescriptorSet-descriptorType-02738\");\n    vk::UpdateDescriptorSets(m_device->device(), 1, &descriptor_write, 0, NULL);\n    m_errorMonitor->VerifyFound();\n\n    vkDestroySamplerYcbcrConversionFunction(m_device->device(), conversions[0], nullptr);\n    vkDestroySamplerYcbcrConversionFunction(m_device->device(), conversions[1], nullptr);\n    vk::DestroyImageView(m_device->device(), view, NULL);\n    vk::DestroySampler(m_device->device(), samplers[0], nullptr);\n    vk::DestroySampler(m_device->device(), samplers[1], nullptr);\n}\n\nTEST_F(VkLayerTest, DepthStencilImageViewWithColorAspectBitError) {\n    \/\/ Create a single Image descriptor and cause it to first hit an error due\n    \/\/  to using a DS format, then cause it to hit error due to COLOR_BIT not\n    \/\/  set in aspect\n    \/\/ The image format check comes 2nd in validation so we trigger it first,\n    \/\/  then when we cause aspect fail next, bad format check will be preempted\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"Combination depth\/stencil image formats can have only the \");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n    auto depth_format = FindSupportedDepthStencilFormat(gpu());\n    if (!depth_format) {\n        printf(\"%s Couldn't find depth stencil format.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkImageObj image_bad(m_device);\n    VkImageObj image_good(m_device);\n    \/\/ One bad format and one good format for Color attachment\n    const VkFormat tex_format_bad = depth_format;\n    const VkFormat tex_format_good = VK_FORMAT_B8G8R8A8_UNORM;\n    const int32_t tex_width = 32;\n    const int32_t tex_height = 32;\n\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = tex_format_bad;\n    image_create_info.extent.width = tex_width;\n    image_create_info.extent.height = tex_height;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;\n    image_create_info.flags = 0;\n\n    image_bad.init(&image_create_info);\n\n    image_create_info.format = tex_format_good;\n    image_create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;\n    image_good.init(&image_create_info);\n\n    VkImageViewCreateInfo image_view_create_info = {};\n    image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n    image_view_create_info.image = image_bad.handle();\n    image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;\n    image_view_create_info.format = tex_format_bad;\n    image_view_create_info.subresourceRange.baseArrayLayer = 0;\n    image_view_create_info.subresourceRange.baseMipLevel = 0;\n    image_view_create_info.subresourceRange.layerCount = 1;\n    image_view_create_info.subresourceRange.levelCount = 1;\n    image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT | VK_IMAGE_ASPECT_DEPTH_BIT;\n\n    VkImageView view;\n    vk::CreateImageView(m_device->device(), &image_view_create_info, NULL, &view);\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, ExtensionNotEnabled) {\n    TEST_DESCRIPTION(\"Validate that using an API from an unenabled extension returns an error\");\n\n    if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {\n        m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n    } else {\n        printf(\"%s Did not find required instance extension %s; skipped.\\n\", kSkipPrefix,\n               VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n        return;\n    }\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n\n    \/\/ Required extensions except VK_KHR_GET_MEMORY_REQUIREMENTS_2 -- to create the needed error\n    std::vector<const char *> required_device_extensions = {VK_KHR_MAINTENANCE1_EXTENSION_NAME, VK_KHR_BIND_MEMORY_2_EXTENSION_NAME,\n                                                            VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME};\n    for (auto dev_ext : required_device_extensions) {\n        if (DeviceExtensionSupported(gpu(), nullptr, dev_ext)) {\n            m_device_extension_names.push_back(dev_ext);\n        } else {\n            printf(\"%s Did not find required device extension %s; skipped.\\n\", kSkipPrefix, dev_ext);\n            break;\n        }\n    }\n\n    \/\/ Need to ignore this error to get to the one we're testing\n    m_errorMonitor->SetUnexpectedError(\"VUID-vkCreateDevice-ppEnabledExtensionNames-01387\");\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    \/\/ Find address of extension API\n    auto vkCreateSamplerYcbcrConversionKHR =\n        (PFN_vkCreateSamplerYcbcrConversionKHR)vk::GetDeviceProcAddr(m_device->handle(), \"vkCreateSamplerYcbcrConversionKHR\");\n    if (vkCreateSamplerYcbcrConversionKHR == nullptr) {\n        printf(\"%s VK_KHR_sampler_ycbcr_conversion not supported by device; skipped.\\n\", kSkipPrefix);\n        return;\n    }\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"UNASSIGNED-GeneralParameterError-ExtensionNotEnabled\");\n    VkSamplerYcbcrConversionCreateInfo ycbcr_info = {VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO,\n                                                     NULL,\n                                                     VK_FORMAT_UNDEFINED,\n                                                     VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY,\n                                                     VK_SAMPLER_YCBCR_RANGE_ITU_FULL,\n                                                     {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,\n                                                      VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY},\n                                                     VK_CHROMA_LOCATION_COSITED_EVEN,\n                                                     VK_CHROMA_LOCATION_COSITED_EVEN,\n                                                     VK_FILTER_NEAREST,\n                                                     false};\n    VkSamplerYcbcrConversion conversion;\n    vkCreateSamplerYcbcrConversionKHR(m_device->handle(), &ycbcr_info, nullptr, &conversion);\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, InvalidCreateBufferSize) {\n    TEST_DESCRIPTION(\"Attempt to create VkBuffer with size of zero\");\n\n    ASSERT_NO_FATAL_FAILURE(Init());\n\n    VkBufferCreateInfo info = {};\n    info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;\n    info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;\n    info.size = 0;\n    CreateBufferTest(*this, &info, \"VUID-VkBufferCreateInfo-size-00912\");\n}\n\nTEST_F(VkLayerTest, DuplicateValidPNextStructures) {\n    TEST_DESCRIPTION(\"Create a pNext chain containing valid structures, but with a duplicate structure type\");\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    if (DeviceExtensionSupported(gpu(), nullptr, VK_NV_DEDICATED_ALLOCATION_EXTENSION_NAME)) {\n        m_device_extension_names.push_back(VK_NV_DEDICATED_ALLOCATION_EXTENSION_NAME);\n    } else {\n        printf(\"%s VK_NV_dedicated_allocation extension not supported, skipping test\\n\", kSkipPrefix);\n        return;\n    }\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    \/\/ Create two pNext structures which by themselves would be valid\n    VkDedicatedAllocationBufferCreateInfoNV dedicated_buffer_create_info = {};\n    VkDedicatedAllocationBufferCreateInfoNV dedicated_buffer_create_info_2 = {};\n    dedicated_buffer_create_info.sType = VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_BUFFER_CREATE_INFO_NV;\n    dedicated_buffer_create_info.pNext = &dedicated_buffer_create_info_2;\n    dedicated_buffer_create_info.dedicatedAllocation = VK_TRUE;\n\n    dedicated_buffer_create_info_2.sType = VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_BUFFER_CREATE_INFO_NV;\n    dedicated_buffer_create_info_2.pNext = nullptr;\n    dedicated_buffer_create_info_2.dedicatedAllocation = VK_TRUE;\n\n    uint32_t queue_family_index = 0;\n    VkBufferCreateInfo buffer_create_info = {};\n    buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;\n    buffer_create_info.pNext = &dedicated_buffer_create_info;\n    buffer_create_info.size = 1024;\n    buffer_create_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;\n    buffer_create_info.queueFamilyIndexCount = 1;\n    buffer_create_info.pQueueFamilyIndices = &queue_family_index;\n\n    CreateBufferTest(*this, &buffer_create_info, \"chain contains duplicate structure types\");\n}\n\nTEST_F(VkLayerTest, DedicatedAllocation) {\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME)) {\n        m_device_extension_names.push_back(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);\n    } else {\n        printf(\"%s Dedicated allocation extension not supported, skipping test\\n\", kSkipPrefix);\n        return;\n    }\n    ASSERT_NO_FATAL_FAILURE(InitState());\n\n    VkMemoryPropertyFlags mem_flags = 0;\n    const VkDeviceSize resource_size = 1024;\n    auto buffer_info = VkBufferObj::create_info(resource_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT);\n    VkBufferObj buffer;\n    buffer.init_no_mem(*m_device, buffer_info);\n    auto buffer_alloc_info = vk_testing::DeviceMemory::get_resource_alloc_info(*m_device, buffer.memory_requirements(), mem_flags);\n    auto buffer_dedicated_info = lvl_init_struct<VkMemoryDedicatedAllocateInfoKHR>();\n    buffer_dedicated_info.buffer = buffer.handle();\n    buffer_alloc_info.pNext = &buffer_dedicated_info;\n    vk_testing::DeviceMemory dedicated_buffer_memory;\n    dedicated_buffer_memory.init(*m_device, buffer_alloc_info);\n\n    VkBufferObj wrong_buffer;\n    wrong_buffer.init_no_mem(*m_device, buffer_info);\n\n    \/\/ Bind with wrong buffer\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindBufferMemory-memory-01508\");\n    vk::BindBufferMemory(m_device->handle(), wrong_buffer.handle(), dedicated_buffer_memory.handle(), 0);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Bind with non-zero offset (same VUID)\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkBindBufferMemory-memory-01508\");  \/\/ offset must be zero\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkBindBufferMemory-size-01037\");  \/\/ offset pushes us past size\n    auto offset = buffer.memory_requirements().alignment;\n    vk::BindBufferMemory(m_device->handle(), buffer.handle(), dedicated_buffer_memory.handle(), offset);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Bind correctly (depends on the \"skip\" above)\n    m_errorMonitor->ExpectSuccess();\n    vk::BindBufferMemory(m_device->handle(), buffer.handle(), dedicated_buffer_memory.handle(), 0);\n    m_errorMonitor->VerifyNotFound();\n\n    \/\/ And for images...\n    VkImageObj image(m_device);\n    VkImageObj wrong_image(m_device);\n    auto image_info = VkImageObj::create_info();\n    image_info.extent.width = resource_size;\n    image_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n    image_info.format = VK_FORMAT_R8G8B8A8_UNORM;\n    image.init_no_mem(*m_device, image_info);\n    wrong_image.init_no_mem(*m_device, image_info);\n\n    auto image_dedicated_info = lvl_init_struct<VkMemoryDedicatedAllocateInfoKHR>();\n    image_dedicated_info.image = image.handle();\n    auto image_alloc_info = vk_testing::DeviceMemory::get_resource_alloc_info(*m_device, image.memory_requirements(), mem_flags);\n    image_alloc_info.pNext = &image_dedicated_info;\n    vk_testing::DeviceMemory dedicated_image_memory;\n    dedicated_image_memory.init(*m_device, image_alloc_info);\n\n    \/\/ Bind with wrong image\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindImageMemory-memory-01509\");\n    vk::BindImageMemory(m_device->handle(), wrong_image.handle(), dedicated_image_memory.handle(), 0);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Bind with non-zero offset (same VUID)\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkBindImageMemory-memory-01509\");  \/\/ offset must be zero\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkBindImageMemory-size-01049\");  \/\/ offset pushes us past size\n    auto image_offset = image.memory_requirements().alignment;\n    vk::BindImageMemory(m_device->handle(), image.handle(), dedicated_image_memory.handle(), image_offset);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Bind correctly (depends on the \"skip\" above)\n    m_errorMonitor->ExpectSuccess();\n    vk::BindImageMemory(m_device->handle(), image.handle(), dedicated_image_memory.handle(), 0);\n    m_errorMonitor->VerifyNotFound();\n}\n\nTEST_F(VkLayerTest, DedicatedAllocationImageAliasing) {\n    if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {\n        m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n    } else {\n        printf(\"%s Did not find required instance extension %s; skipped.\\n\", kSkipPrefix,\n               VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n        return;\n    }\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n\n    if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME) &&\n        DeviceExtensionSupported(gpu(), nullptr, VK_NV_DEDICATED_ALLOCATION_IMAGE_ALIASING_EXTENSION_NAME)) {\n        m_device_extension_names.push_back(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_NV_DEDICATED_ALLOCATION_IMAGE_ALIASING_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);\n    } else {\n        printf(\"%s Dedicated allocation extension not supported, skipping test\\n\", kSkipPrefix);\n        return;\n    }\n\n    PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =\n        (PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), \"vkGetPhysicalDeviceFeatures2KHR\");\n    ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);\n\n    auto aliasing_features = lvl_init_struct<VkPhysicalDeviceDedicatedAllocationImageAliasingFeaturesNV>();\n    auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&aliasing_features);\n    vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);\n    aliasing_features.dedicatedAllocationImageAliasing = VK_TRUE;\n\n    ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &features2));\n\n    VkMemoryPropertyFlags mem_flags = 0;\n    const VkDeviceSize resource_size = 1024;\n\n    VkImageObj image(m_device);\n    VkImageObj identical_image(m_device);\n    auto image_info = VkImageObj::create_info();\n    image_info.extent.width = resource_size;\n    image_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n    image_info.format = VK_FORMAT_R8G8B8A8_UNORM;\n    image.init_no_mem(*m_device, image_info);\n    identical_image.init_no_mem(*m_device, image_info);\n\n    auto image_dedicated_info = lvl_init_struct<VkMemoryDedicatedAllocateInfoKHR>();\n    image_dedicated_info.image = image.handle();\n    auto image_alloc_info = vk_testing::DeviceMemory::get_resource_alloc_info(*m_device, image.memory_requirements(), mem_flags);\n    image_alloc_info.pNext = &image_dedicated_info;\n    vk_testing::DeviceMemory dedicated_image_memory;\n    dedicated_image_memory.init(*m_device, image_alloc_info);\n\n    \/\/ Bind with different but identical image\n    m_errorMonitor->ExpectSuccess();\n    vk::BindImageMemory(m_device->handle(), identical_image.handle(), dedicated_image_memory.handle(), 0);\n    m_errorMonitor->VerifyNotFound();\n\n    VkImageObj smaller_image(m_device);\n    image_info = VkImageObj::create_info();\n    image_info.extent.width = resource_size - 1;\n    image_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n    image_info.format = VK_FORMAT_R8G8B8A8_UNORM;\n    smaller_image.init_no_mem(*m_device, image_info);\n\n    \/\/ Bind with a smaller image\n    m_errorMonitor->ExpectSuccess();\n    vk::BindImageMemory(m_device->handle(), smaller_image.handle(), dedicated_image_memory.handle(), 0);\n    m_errorMonitor->VerifyNotFound();\n\n    VkImageObj larger_image(m_device);\n    image_info = VkImageObj::create_info();\n    image_info.extent.width = resource_size + 1;\n    image_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n    image_info.format = VK_FORMAT_R8G8B8A8_UNORM;\n    larger_image.init_no_mem(*m_device, image_info);\n\n    \/\/ Bind with a larger image (not supported, and not enough memory)\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindImageMemory-memory-02629\");\n    if (larger_image.memory_requirements().size > image.memory_requirements().size) {\n        m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkBindImageMemory-size-01049\");\n    }\n    vk::BindImageMemory(m_device->handle(), larger_image.handle(), dedicated_image_memory.handle(), 0);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Bind with non-zero offset\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkBindImageMemory-memory-02629\");  \/\/ offset must be zero\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT,\n                                         \"VUID-vkBindImageMemory-size-01049\");  \/\/ offset pushes us past size\n    auto image_offset = image.memory_requirements().alignment;\n    vk::BindImageMemory(m_device->handle(), image.handle(), dedicated_image_memory.handle(), image_offset);\n    m_errorMonitor->VerifyFound();\n\n    \/\/ Bind correctly (depends on the \"skip\" above)\n    m_errorMonitor->ExpectSuccess();\n    vk::BindImageMemory(m_device->handle(), image.handle(), dedicated_image_memory.handle(), 0);\n    m_errorMonitor->VerifyNotFound();\n}\n\nTEST_F(VkLayerTest, CornerSampledImageNV) {\n    TEST_DESCRIPTION(\"Test VK_NV_corner_sampled_image.\");\n\n    if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {\n        m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n    } else {\n        printf(\"%s Did not find required instance extension %s; skipped.\\n\", kSkipPrefix,\n               VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n        return;\n    }\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    std::array<const char *, 1> required_device_extensions = {{VK_NV_CORNER_SAMPLED_IMAGE_EXTENSION_NAME}};\n    for (auto device_extension : required_device_extensions) {\n        if (DeviceExtensionSupported(gpu(), nullptr, device_extension)) {\n            m_device_extension_names.push_back(device_extension);\n        } else {\n            printf(\"%s %s Extension not supported, skipping tests\\n\", kSkipPrefix, device_extension);\n            return;\n        }\n    }\n\n    PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =\n        (PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), \"vkGetPhysicalDeviceFeatures2KHR\");\n    ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);\n\n    \/\/ Create a device that enables exclusive scissor but disables multiViewport\n    auto corner_sampled_image_features = lvl_init_struct<VkPhysicalDeviceCornerSampledImageFeaturesNV>();\n    auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&corner_sampled_image_features);\n    vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);\n\n    ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &features2));\n\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.pNext = NULL;\n    image_create_info.imageType = VK_IMAGE_TYPE_1D;\n    image_create_info.format = VK_FORMAT_R8G8B8A8_UNORM;\n    image_create_info.extent.width = 2;\n    image_create_info.extent.height = 1;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\n    image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n    image_create_info.queueFamilyIndexCount = 0;\n    image_create_info.pQueueFamilyIndices = NULL;\n    image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n    image_create_info.flags = VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV;\n\n    \/\/ image type must be 2D or 3D\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-flags-02050\");\n\n    \/\/ cube\/depth not supported\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.extent.height = 2;\n    image_create_info.format = VK_FORMAT_D24_UNORM_S8_UINT;\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-flags-02051\");\n\n    image_create_info.format = VK_FORMAT_R8G8B8A8_UNORM;\n\n    \/\/ 2D width\/height must be > 1\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.extent.height = 1;\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-flags-02052\");\n\n    \/\/ 3D width\/height\/depth must be > 1\n    image_create_info.imageType = VK_IMAGE_TYPE_3D;\n    image_create_info.extent.height = 2;\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-flags-02053\");\n\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n\n    \/\/ Valid # of mip levels\n    image_create_info.extent = {7, 7, 1};\n    image_create_info.mipLevels = 3;  \/\/ 3 = ceil(log2(7))\n    CreateImageTest(*this, &image_create_info);\n\n    image_create_info.extent = {8, 8, 1};\n    image_create_info.mipLevels = 3;  \/\/ 3 = ceil(log2(8))\n    CreateImageTest(*this, &image_create_info);\n\n    image_create_info.extent = {9, 9, 1};\n    image_create_info.mipLevels = 3;  \/\/ 4 = ceil(log2(9))\n    CreateImageTest(*this, &image_create_info);\n\n    \/\/ Invalid # of mip levels\n    image_create_info.extent = {8, 8, 1};\n    image_create_info.mipLevels = 4;  \/\/ 3 = ceil(log2(8))\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-mipLevels-00958\");\n}\n\nTEST_F(VkLayerTest, CreateYCbCrSampler) {\n    TEST_DESCRIPTION(\"Verify YCbCr sampler creation.\");\n\n    \/\/ Test requires API 1.1 or (API 1.0 + SamplerYCbCr extension). Request API 1.1\n    SetTargetApiVersion(VK_API_VERSION_1_1);\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n\n    \/\/ In case we don't have API 1.1+, try enabling the extension directly (and it's dependencies)\n    if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME)) {\n        m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitState());\n    VkDevice dev = m_device->device();\n\n    PFN_vkCreateSamplerYcbcrConversionKHR vkCreateSamplerYcbcrConversionFunction = nullptr;\n    if (DeviceValidationVersion() >= VK_API_VERSION_1_1) {\n        vkCreateSamplerYcbcrConversionFunction = vk::CreateSamplerYcbcrConversion;\n    } else {\n        vkCreateSamplerYcbcrConversionFunction =\n            (PFN_vkCreateSamplerYcbcrConversionKHR)vk::GetDeviceProcAddr(m_device->handle(), \"vkCreateSamplerYcbcrConversionKHR\");\n    }\n\n    if (!vkCreateSamplerYcbcrConversionFunction) {\n        printf(\"%s Did not find required device support for YcbcrSamplerConversion; test skipped.\\n\", kSkipPrefix);\n        return;\n    }\n\n    \/\/ Verify we have the requested support\n    bool ycbcr_support = (DeviceExtensionEnabled(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME) ||\n                          (DeviceValidationVersion() >= VK_API_VERSION_1_1));\n    if (!ycbcr_support) {\n        printf(\"%s Did not find required device extension %s; test skipped.\\n\", kSkipPrefix,\n               VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);\n        return;\n    }\n\n    VkSamplerYcbcrConversion ycbcr_conv = VK_NULL_HANDLE;\n    VkSamplerYcbcrConversionCreateInfo sycci = {};\n    sycci.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO;\n    sycci.format = VK_FORMAT_UNDEFINED;\n    sycci.ycbcrModel = VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY;\n    sycci.ycbcrRange = VK_SAMPLER_YCBCR_RANGE_ITU_FULL;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkSamplerYcbcrConversionCreateInfo-format-01649\");\n    vkCreateSamplerYcbcrConversionFunction(dev, &sycci, NULL, &ycbcr_conv);\n    m_errorMonitor->VerifyFound();\n}\n\nTEST_F(VkLayerTest, BufferDeviceAddressEXT) {\n    TEST_DESCRIPTION(\"Test VK_EXT_buffer_device_address.\");\n\n    if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {\n        m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n    } else {\n        printf(\"%s Did not find required instance extension %s; skipped.\\n\", kSkipPrefix,\n               VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n        return;\n    }\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    std::array<const char *, 1> required_device_extensions = {{VK_EXT_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME}};\n    for (auto device_extension : required_device_extensions) {\n        if (DeviceExtensionSupported(gpu(), nullptr, device_extension)) {\n            m_device_extension_names.push_back(device_extension);\n        } else {\n            printf(\"%s %s Extension not supported, skipping tests\\n\", kSkipPrefix, device_extension);\n            return;\n        }\n    }\n\n    if (DeviceIsMockICD() || DeviceSimulation()) {\n        printf(\"%s MockICD does not support this feature, skipping tests\\n\", kSkipPrefix);\n        return;\n    }\n\n    PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =\n        (PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), \"vkGetPhysicalDeviceFeatures2KHR\");\n    ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);\n\n    \/\/ Create a device that enables buffer_device_address\n    auto buffer_device_address_features = lvl_init_struct<VkPhysicalDeviceBufferAddressFeaturesEXT>();\n    auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&buffer_device_address_features);\n    vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);\n    buffer_device_address_features.bufferDeviceAddressCaptureReplay = VK_FALSE;\n\n    ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &features2));\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    PFN_vkGetBufferDeviceAddressEXT vkGetBufferDeviceAddressEXT =\n        (PFN_vkGetBufferDeviceAddressEXT)vk::GetInstanceProcAddr(instance(), \"vkGetBufferDeviceAddressEXT\");\n\n    VkBufferCreateInfo buffer_create_info = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};\n    buffer_create_info.size = sizeof(uint32_t);\n    buffer_create_info.usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT;\n    buffer_create_info.flags = VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT_EXT;\n    CreateBufferTest(*this, &buffer_create_info, \"VUID-VkBufferCreateInfo-flags-02605\");\n\n    buffer_create_info.flags = 0;\n    VkBufferDeviceAddressCreateInfoEXT addr_ci = {VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_CREATE_INFO_EXT};\n    addr_ci.deviceAddress = 1;\n    buffer_create_info.pNext = &addr_ci;\n    CreateBufferTest(*this, &buffer_create_info, \"VUID-VkBufferCreateInfo-deviceAddress-02604\");\n\n    buffer_create_info.pNext = nullptr;\n    VkBuffer buffer;\n    VkResult err = vk::CreateBuffer(m_device->device(), &buffer_create_info, NULL, &buffer);\n    ASSERT_VK_SUCCESS(err);\n\n    VkBufferDeviceAddressInfoEXT info = {VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO_EXT};\n    info.buffer = buffer;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkBufferDeviceAddressInfoEXT-buffer-02600\");\n    vkGetBufferDeviceAddressEXT(m_device->device(), &info);\n    m_errorMonitor->VerifyFound();\n\n    vk::DestroyBuffer(m_device->device(), buffer, NULL);\n}\n\nTEST_F(VkLayerTest, BufferDeviceAddressEXTDisabled) {\n    TEST_DESCRIPTION(\"Test VK_EXT_buffer_device_address.\");\n\n    if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {\n        m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n    } else {\n        printf(\"%s Did not find required instance extension %s; skipped.\\n\", kSkipPrefix,\n               VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n        return;\n    }\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    std::array<const char *, 1> required_device_extensions = {{VK_EXT_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME}};\n    for (auto device_extension : required_device_extensions) {\n        if (DeviceExtensionSupported(gpu(), nullptr, device_extension)) {\n            m_device_extension_names.push_back(device_extension);\n        } else {\n            printf(\"%s %s Extension not supported, skipping tests\\n\", kSkipPrefix, device_extension);\n            return;\n        }\n    }\n\n    if (DeviceIsMockICD() || DeviceSimulation()) {\n        printf(\"%s MockICD does not support this feature, skipping tests\\n\", kSkipPrefix);\n        return;\n    }\n\n    PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =\n        (PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), \"vkGetPhysicalDeviceFeatures2KHR\");\n    ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);\n\n    \/\/ Create a device that disables buffer_device_address\n    auto buffer_device_address_features = lvl_init_struct<VkPhysicalDeviceBufferAddressFeaturesEXT>();\n    auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2KHR>(&buffer_device_address_features);\n    vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);\n    buffer_device_address_features.bufferDeviceAddress = VK_FALSE;\n    buffer_device_address_features.bufferDeviceAddressCaptureReplay = VK_FALSE;\n\n    ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &features2));\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    PFN_vkGetBufferDeviceAddressEXT vkGetBufferDeviceAddressEXT =\n        (PFN_vkGetBufferDeviceAddressEXT)vk::GetInstanceProcAddr(instance(), \"vkGetBufferDeviceAddressEXT\");\n\n    VkBufferCreateInfo buffer_create_info = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};\n    buffer_create_info.size = sizeof(uint32_t);\n    buffer_create_info.usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT;\n    CreateBufferTest(*this, &buffer_create_info, \"VUID-VkBufferCreateInfo-usage-02606\");\n\n    buffer_create_info.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT;\n    VkBuffer buffer;\n    VkResult err = vk::CreateBuffer(m_device->device(), &buffer_create_info, NULL, &buffer);\n    ASSERT_VK_SUCCESS(err);\n\n    VkBufferDeviceAddressInfoEXT info = {VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO_EXT};\n    info.buffer = buffer;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-vkGetBufferDeviceAddressEXT-None-02598\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkBufferDeviceAddressInfoEXT-buffer-02601\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkBufferDeviceAddressInfoEXT-buffer-02600\");\n    vkGetBufferDeviceAddressEXT(m_device->device(), &info);\n    m_errorMonitor->VerifyFound();\n\n    vk::DestroyBuffer(m_device->device(), buffer, NULL);\n}\n\nTEST_F(VkLayerTest, CreateImageYcbcrArrayLayers) {\n    TEST_DESCRIPTION(\"Creating images with out-of-range arrayLayers \");\n\n    \/\/ Enable KHR multiplane req'd extensions\n    bool mp_extensions = InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,\n                                                    VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_SPEC_VERSION);\n    if (mp_extensions) {\n        m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);\n    }\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_MAINTENANCE1_EXTENSION_NAME);\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);\n    mp_extensions = mp_extensions && DeviceExtensionSupported(gpu(), nullptr, VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);\n    if (mp_extensions) {\n        m_device_extension_names.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);\n        m_device_extension_names.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);\n    } else {\n        printf(\"%s test requires KHR multiplane extensions, not available.  Skipping.\\n\", kSkipPrefix);\n        return;\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitState());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n\n    \/\/ Create ycbcr image with unsupported arrayLayers\n    VkImageCreateInfo image_create_info = {};\n    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM;\n    image_create_info.extent.width = 32;\n    image_create_info.extent.height = 32;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n\n    bool supported = ImageFormatAndFeaturesSupported(instance(), gpu(), image_create_info, VK_FORMAT_FEATURE_TRANSFER_SRC_BIT);\n    if (!supported) {\n        printf(\"%s Multiplane image format not supported.  Skipping test.\\n\", kSkipPrefix);\n        return;\n    }\n\n    VkImageFormatProperties img_limits;\n    ASSERT_VK_SUCCESS(GPDIFPHelper(gpu(), &image_create_info, &img_limits));\n    if (img_limits.maxArrayLayers == 1) {\n        return;\n    }\n    image_create_info.arrayLayers = img_limits.maxArrayLayers;\n\n    CreateImageTest(*this, &image_create_info, \"VUID-VkImageCreateInfo-format-02653\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkImageCreateInfo-format-02653\");\n}\n\nTEST_F(VkLayerTest, BindImageMemorySwapchain) {\n    TEST_DESCRIPTION(\"Invalid bind image with a swapchain\");\n    SetTargetApiVersion(VK_API_VERSION_1_1);\n\n    if (!AddSurfaceInstanceExtension()) {\n        printf(\"%s surface extensions not supported, skipping BindSwapchainImageMemory test\\n\", kSkipPrefix);\n        return;\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n\n    if (!AddSwapchainDeviceExtension()) {\n        printf(\"%s swapchain extensions not supported, skipping BindSwapchainImageMemory test\\n\", kSkipPrefix);\n        return;\n    }\n\n    if (DeviceValidationVersion() < VK_API_VERSION_1_1) {\n        printf(\"%s VkBindImageMemoryInfo requires Vulkan 1.1+, skipping test\\n\", kSkipPrefix);\n        return;\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitState());\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n    if (!InitSwapchain()) {\n        printf(\"%s Cannot create surface or swapchain, skipping BindSwapchainImageMemory test\\n\", kSkipPrefix);\n        return;\n    }\n\n    auto image_create_info = lvl_init_struct<VkImageCreateInfo>();\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = VK_FORMAT_R8G8B8A8_UNORM;\n    image_create_info.extent.width = 64;\n    image_create_info.extent.height = 64;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;\n    image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n    image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n\n    auto image_swapchain_create_info = lvl_init_struct<VkImageSwapchainCreateInfoKHR>();\n    image_swapchain_create_info.swapchain = m_swapchain;\n    image_create_info.pNext = &image_swapchain_create_info;\n\n    VkImage image_from_swapchain;\n    vk::CreateImage(device(), &image_create_info, NULL, &image_from_swapchain);\n\n    VkMemoryRequirements mem_reqs = {};\n    vk::GetImageMemoryRequirements(device(), image_from_swapchain, &mem_reqs);\n\n    auto alloc_info = lvl_init_struct<VkMemoryAllocateInfo>();\n    alloc_info.memoryTypeIndex = 0;\n    alloc_info.allocationSize = mem_reqs.size;\n\n    bool pass = m_device->phy().set_memory_type(mem_reqs.memoryTypeBits, &alloc_info, 0);\n    ASSERT_TRUE(pass);\n\n    VkDeviceMemory mem;\n    VkResult err = vk::AllocateMemory(m_device->device(), &alloc_info, NULL, &mem);\n    ASSERT_VK_SUCCESS(err);\n\n    auto bind_info = lvl_init_struct<VkBindImageMemoryInfo>();\n    bind_info.image = image_from_swapchain;\n    bind_info.memory = VK_NULL_HANDLE;\n    bind_info.memoryOffset = 0;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkBindImageMemoryInfo-image-01630\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkBindImageMemoryInfo-pNext-01632\");\n    vk::BindImageMemory2(m_device->device(), 1, &bind_info);\n    m_errorMonitor->VerifyFound();\n\n    auto bind_swapchain_info = lvl_init_struct<VkBindImageMemorySwapchainInfoKHR>();\n    bind_swapchain_info.swapchain = VK_NULL_HANDLE;\n    bind_swapchain_info.imageIndex = 0;\n    bind_info.pNext = &bind_swapchain_info;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"UNASSIGNED-GeneralParameterError-RequiredParameter\");\n    vk::BindImageMemory2(m_device->device(), 1, &bind_info);\n    m_errorMonitor->VerifyFound();\n\n    bind_info.memory = mem;\n    bind_swapchain_info.swapchain = m_swapchain;\n    bind_swapchain_info.imageIndex = UINT32_MAX;\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkBindImageMemoryInfo-pNext-01631\");\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"VUID-VkBindImageMemorySwapchainInfoKHR-imageIndex-01644\");\n    vk::BindImageMemory2(m_device->device(), 1, &bind_info);\n    m_errorMonitor->VerifyFound();\n\n    vk::DestroyImage(m_device->device(), image_from_swapchain, NULL);\n    vk::FreeMemory(m_device->device(), mem, NULL);\n    DestroySwapchain();\n}\n\nTEST_F(VkLayerTest, TransferImageToSwapchainWithInvalidLayoutDeviceGroup) {\n    TEST_DESCRIPTION(\"Transfer an image to a swapchain's image with a invalid layout between device group\");\n\n#if defined(VK_USE_PLATFORM_ANDROID_KHR)\n    printf(\n        \"%s According to VUID-01631, VkBindImageMemoryInfo-memory should be NULL. But Android will crash if memory is NULL, \"\n        \"skipping test\\n\",\n        kSkipPrefix);\n    return;\n#endif\n\n    SetTargetApiVersion(VK_API_VERSION_1_1);\n\n    if (!AddSurfaceInstanceExtension()) {\n        printf(\"%s surface extensions not supported, skipping test\\n\", kSkipPrefix);\n        return;\n    }\n\n    ASSERT_NO_FATAL_FAILURE(InitFramework(myDbgFunc, m_errorMonitor));\n\n    if (!AddSwapchainDeviceExtension()) {\n        printf(\"%s swapchain extensions not supported, skipping test\\n\", kSkipPrefix);\n        return;\n    }\n\n    if (DeviceValidationVersion() < VK_API_VERSION_1_1) {\n        printf(\"%s VkBindImageMemoryInfo requires Vulkan 1.1+, skipping test\\n\", kSkipPrefix);\n        return;\n    }\n    uint32_t physical_device_group_count = 0;\n    vk::EnumeratePhysicalDeviceGroups(instance(), &physical_device_group_count, nullptr);\n\n    if (physical_device_group_count == 0) {\n        printf(\"%s physical_device_group_count is 0, skipping test\\n\", kSkipPrefix);\n        return;\n    }\n\n    std::vector<VkPhysicalDeviceGroupProperties> physical_device_group(physical_device_group_count,\n                                                                       {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES});\n    vk::EnumeratePhysicalDeviceGroups(instance(), &physical_device_group_count, physical_device_group.data());\n    VkDeviceGroupDeviceCreateInfo create_device_pnext = {};\n    create_device_pnext.sType = VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO;\n    create_device_pnext.physicalDeviceCount = physical_device_group[0].physicalDeviceCount;\n    create_device_pnext.pPhysicalDevices = physical_device_group[0].physicalDevices;\n    ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &create_device_pnext));\n    ASSERT_NO_FATAL_FAILURE(InitRenderTarget());\n    if (!InitSwapchain(VK_IMAGE_USAGE_TRANSFER_DST_BIT)) {\n        printf(\"%s Cannot create surface or swapchain, skipping test\\n\", kSkipPrefix);\n        return;\n    }\n\n    auto image_create_info = lvl_init_struct<VkImageCreateInfo>();\n    image_create_info.imageType = VK_IMAGE_TYPE_2D;\n    image_create_info.format = VK_FORMAT_R8G8B8A8_UNORM;\n    image_create_info.extent.width = 64;\n    image_create_info.extent.height = 64;\n    image_create_info.extent.depth = 1;\n    image_create_info.mipLevels = 1;\n    image_create_info.arrayLayers = 1;\n    image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;\n    image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;\n    image_create_info.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;\n    image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;\n    image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n\n    VkImageObj src_Image(m_device);\n    src_Image.init(&image_create_info);\n\n    image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n    image_create_info.flags = VK_IMAGE_CREATE_ALIAS_BIT;\n\n    auto image_swapchain_create_info = lvl_init_struct<VkImageSwapchainCreateInfoKHR>();\n    image_swapchain_create_info.swapchain = m_swapchain;\n    image_create_info.pNext = &image_swapchain_create_info;\n\n    VkImage peer_image;\n    vk::CreateImage(device(), &image_create_info, NULL, &peer_image);\n\n    auto bind_devicegroup_info = lvl_init_struct<VkBindImageMemoryDeviceGroupInfo>();\n    bind_devicegroup_info.deviceIndexCount = 2;\n    std::array<uint32_t, 2> deviceIndices = {0, 0};\n    bind_devicegroup_info.pDeviceIndices = deviceIndices.data();\n    bind_devicegroup_info.splitInstanceBindRegionCount = 0;\n    bind_devicegroup_info.pSplitInstanceBindRegions = nullptr;\n\n    auto bind_swapchain_info = lvl_init_struct<VkBindImageMemorySwapchainInfoKHR>(&bind_devicegroup_info);\n    bind_swapchain_info.swapchain = m_swapchain;\n    bind_swapchain_info.imageIndex = 0;\n\n    auto bind_info = lvl_init_struct<VkBindImageMemoryInfo>(&bind_swapchain_info);\n    bind_info.image = peer_image;\n    bind_info.memory = VK_NULL_HANDLE;\n    bind_info.memoryOffset = 0;\n\n    vk::BindImageMemory2(m_device->device(), 1, &bind_info);\n\n    uint32_t swapchain_images_count = 0;\n    vk::GetSwapchainImagesKHR(device(), m_swapchain, &swapchain_images_count, nullptr);\n    std::vector<VkImage> swapchain_images;\n    swapchain_images.resize(swapchain_images_count);\n    vk::GetSwapchainImagesKHR(device(), m_swapchain, &swapchain_images_count, swapchain_images.data());\n\n    m_commandBuffer->begin();\n\n    VkImageCopy copy_region = {};\n    copy_region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    copy_region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;\n    copy_region.srcSubresource.mipLevel = 0;\n    copy_region.dstSubresource.mipLevel = 0;\n    copy_region.srcSubresource.baseArrayLayer = 0;\n    copy_region.dstSubresource.baseArrayLayer = 0;\n    copy_region.srcSubresource.layerCount = 1;\n    copy_region.dstSubresource.layerCount = 1;\n    copy_region.srcOffset = {0, 0, 0};\n    copy_region.dstOffset = {0, 0, 0};\n    copy_region.extent = {10, 10, 1};\n    vk::CmdCopyImage(m_commandBuffer->handle(), src_Image.handle(), VK_IMAGE_LAYOUT_GENERAL, peer_image,\n                     VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy_region);\n\n    m_commandBuffer->end();\n\n    VkSubmitInfo submit_info = {};\n    submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;\n    submit_info.commandBufferCount = 1;\n    submit_info.pCommandBuffers = &m_commandBuffer->handle();\n\n    m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_ERROR_BIT_EXT, \"UNASSIGNED-CoreValidation-DrawState-InvalidImageLayout\");\n    vk::QueueSubmit(m_device->m_queue, 1, &submit_info, VK_NULL_HANDLE);\n    m_errorMonitor->VerifyFound();\n\n    vk::DestroyImage(m_device->device(), peer_image, NULL);\n    DestroySwapchain();\n}\n","avg_line_length":50.0953357954,"max_line_length":132,"alphanum_fraction":0.7243909165,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":995,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright https:\/\/github.com\/MothCocoon\/FlowGraph\/graphs\/contributors\n\n#include \"Nodes\/FlowPin.h\"\n\n#if !UE_BUILD_SHIPPING\n\nFString FPinRecord::NoActivations = TEXT(\"No activations\");\nFString FPinRecord::PinActivations = TEXT(\"Pin activations\");\nFString FPinRecord::ForcedActivation = TEXT(\" (forced activation)\");\n\nFPinRecord::FPinRecord()\n\t: Time(0.0f)\n\t, HumanReadableTime(FString())\n\t, bForcedActivation(false)\n{\n}\n\nFPinRecord::FPinRecord(const double InTime, const bool bInForcedActivation)\n\t: Time(InTime)\n\t, bForcedActivation(bInForcedActivation)\n{\n\tconst FDateTime SystemTime(FDateTime::Now());\n\tHumanReadableTime = DoubleDigit(SystemTime.GetHour()) + TEXT(\".\")\n\t\t+ DoubleDigit(SystemTime.GetMinute()) + TEXT(\".\")\n\t\t+ DoubleDigit(SystemTime.GetSecond()) + TEXT(\":\")\n\t\t+ DoubleDigit(SystemTime.GetMillisecond()).Left(3);\n}\n\nFORCEINLINE FString FPinRecord::DoubleDigit(const int32 Number)\n{\n\treturn Number > 9 ? FString::FromInt(Number) : TEXT(\"0\") + FString::FromInt(Number);\n}\n\n#endif\n","avg_line_length":28.4285714286,"max_line_length":85,"alphanum_fraction":0.7467336683,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13370,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/ Copyright (c) 2015-2017 The PIVX developers \n\/\/ Copyright (c) 2018 The GiveHope developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"transactionrecord.h\"\n\n#include \"base58.h\"\n#include \"Darksend.h\"\n#include \"Instantx.h\"\n#include \"timedata.h\"\n#include \"wallet.h\"\n\n#include <stdint.h>\n\n\/* Return positive answer if transaction should be shown in list.\n *\/\nbool TransactionRecord::showTransaction(const CWalletTx& wtx)\n{\n    if (wtx.IsCoinBase()) {\n        \/\/ Ensures we show generated coins \/ mined transactions at depth 1\n        if (!wtx.IsInMainChain()) {\n            return false;\n        }\n    }\n    return true;\n}\n\n\/*\n * Decompose CWallet transaction to model transaction records.\n *\/\nQList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet* wallet, const CWalletTx& wtx)\n{\n    QList<TransactionRecord> parts;\n    int64_t nTime = wtx.GetTxTime();\n    CAmount nCredit = wtx.GetCredit(ISMINE_ALL);\n    CAmount nDebit = wtx.GetDebit(ISMINE_ALL);\n    CAmount nNet = nCredit - nDebit;\n    uint256 hash = wtx.GetHash();\n    std::map<std::string, std::string> mapValue = wtx.mapValue;\n\n    if (wtx.IsCoinStake()) {\n        TransactionRecord sub(hash, nTime);\n        CTxDestination address;\n        if (!ExtractDestination(wtx.vout[1].scriptPubKey, address))\n            return parts;\n\n        if (!IsMine(*wallet, address)) {\n            \/\/if the address is not yours then it means you have a tx sent to you in someone elses coinstake tx\n            for (unsigned int i = 1; i < wtx.vout.size(); i++) {\n                CTxDestination outAddress;\n                if (ExtractDestination(wtx.vout[i].scriptPubKey, outAddress)) {\n                    if (IsMine(*wallet, outAddress)) {\n                        isminetype mine = wallet->IsMine(wtx.vout[i]);\n                        sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;\n                        sub.type = TransactionRecord::MNReward;\n                        sub.address = CBitcoinAddress(outAddress).ToString();\n                        sub.credit = wtx.vout[i].nValue;\n                    }\n                }\n            }\n        } else {\n            \/\/stake reward\n            isminetype mine = wallet->IsMine(wtx.vout[1]);\n            sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;\n            sub.type = TransactionRecord::StakeMint;\n            sub.address = CBitcoinAddress(address).ToString();\n            sub.credit = nNet;\n        }\n        parts.append(sub);\n    } else if (nNet > 0 || wtx.IsCoinBase()) {\n        \/\/\n        \/\/ Credit\n        \/\/\n        BOOST_FOREACH (const CTxOut& txout, wtx.vout) {\n            isminetype mine = wallet->IsMine(txout);\n            if (mine) {\n                TransactionRecord sub(hash, nTime);\n                CTxDestination address;\n                sub.idx = parts.size(); \/\/ sequence number\n                sub.credit = txout.nValue;\n                sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;\n                if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address)) {\n                    \/\/ Received by HOPC Address\n                    sub.type = TransactionRecord::RecvWithAddress;\n                    sub.address = CBitcoinAddress(address).ToString();\n                } else {\n                    \/\/ Received by IP connection (deprecated features), or a multisignature or other non-simple transaction\n                    sub.type = TransactionRecord::RecvFromOther;\n                    sub.address = mapValue[\"from\"];\n                }\n                if (wtx.IsCoinBase()) {\n                    \/\/ Generated\n                    sub.type = TransactionRecord::Generated;\n                }\n\t\t\t\t\n\t\t\t\tint nHeight = chainActive.Height();\n\t\t\t\tint64_t nSubsidy;\n\t\t\t\t\n\t\t\t\tif(nHeight <= 86400 && nHeight > 0) {\n\t\t\t\t\tnSubsidy = 200 * COIN;\n\t\t\t\t\tif(nSubsidy \/ 100 * 20 == txout.nValue) {\n\t\t\t\t\t\tsub.type = TransactionRecord::MNReward;\n\t\t\t\t\t}\n\t\t\t\t} else if (nHeight > 86400 && nHeight <= 151200) {\n\t\t\t\t\tnSubsidy = 150 * COIN;\n\t\t\t\t\tif(nSubsidy \/ 100 * 25 == txout.nValue) {\n\t\t\t\t\t\tsub.type = TransactionRecord::MNReward;\n\t\t\t\t\t}\n\t\t\t\t} else if (nHeight > 151200 && nHeight <= 152500) {\n\t\t\t\t\tnSubsidy = 125 * COIN;\n\t\t\t\t\tif(nSubsidy \/ 100 * 20 == txout.nValue) {\n\t\t\t\t\t\tsub.type = TransactionRecord::MNReward;\n\t\t\t\t\t}\n\t\t\t\t} else if (nHeight > 152500 && nHeight <= 302400) {\n\t\t\t\t\tnSubsidy = 125 * COIN;\n\t\t\t\t\tif(nSubsidy \/ 100 * 30 == txout.nValue) {\n\t\t\t\t\t\tsub.type = TransactionRecord::MNReward;\n\t\t\t\t\t}\n\t\t\t\t} else if (nHeight > 302400 && nHeight <= 345600) {\n\t\t\t\t\tnSubsidy = 100 * COIN;\n\t\t\t\t\tif(nSubsidy \/ 100 * 35 == txout.nValue) {\n\t\t\t\t\t\tsub.type = TransactionRecord::MNReward;\n\t\t\t\t\t}\n\t\t\t\t} else if (nHeight > 345600 && nHeight <= 388800) {\n\t\t\t\t\tnSubsidy = 75 * COIN;\n\t\t\t\t\tif(nSubsidy \/ 100 * 40 == txout.nValue) {\n\t\t\t\t\t\tsub.type = TransactionRecord::MNReward;\n\t\t\t\t\t}\n\t\t\t\t} else if (nHeight > 388800 && nHeight <= 475200) { \/\/ 475200 => LAST POW BLOCK\n\t\t\t\t\tnSubsidy = 50 * COIN;\n\t\t\t\t\tif(nSubsidy \/ 100 * 40 == txout.nValue) {\n\t\t\t\t\t\tsub.type = TransactionRecord::MNReward;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n                parts.append(sub);\n            }\n        }\n    } else {\n        bool fAllFromMeDenom = true;\n        int nFromMe = 0;\n        bool involvesWatchAddress = false;\n        isminetype fAllFromMe = ISMINE_SPENDABLE;\n        BOOST_FOREACH (const CTxIn& txin, wtx.vin) {\n            if (wallet->IsMine(txin)) {\n                fAllFromMeDenom = fAllFromMeDenom && wallet->IsDenominated(txin);\n                nFromMe++;\n            }\n            isminetype mine = wallet->IsMine(txin);\n            if (mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;\n            if (fAllFromMe > mine) fAllFromMe = mine;\n        }\n\n        isminetype fAllToMe = ISMINE_SPENDABLE;\n        bool fAllToMeDenom = true;\n        int nToMe = 0;\n        BOOST_FOREACH (const CTxOut& txout, wtx.vout) {\n            if (wallet->IsMine(txout)) {\n                fAllToMeDenom = fAllToMeDenom && wallet->IsDenominatedAmount(txout.nValue);\n                nToMe++;\n            }\n            isminetype mine = wallet->IsMine(txout);\n            if (mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;\n            if (fAllToMe > mine) fAllToMe = mine;\n        }\n\n        if (fAllFromMeDenom && fAllToMeDenom && nFromMe * nToMe) {\n            parts.append(TransactionRecord(hash, nTime, TransactionRecord::DarksendDenominate, \"\", -nDebit, nCredit));\n            parts.last().involvesWatchAddress = false; \/\/ maybe pass to TransactionRecord as constructor argument\n        } else if (fAllFromMe && fAllToMe) {\n            \/\/ Payment to self\n            \/\/ TODO: this section still not accurate but covers most cases,\n            \/\/ might need some additional work however\n\n            TransactionRecord sub(hash, nTime);\n            \/\/ Payment to self by default\n            sub.type = TransactionRecord::SendToSelf;\n            sub.address = \"\";\n\n            if (mapValue[\"DS\"] == \"1\") {\n                sub.type = TransactionRecord::Obfuscated;\n                CTxDestination address;\n                if (ExtractDestination(wtx.vout[0].scriptPubKey, address)) {\n                    \/\/ Sent to HOPC Address\n                    sub.address = CBitcoinAddress(address).ToString();\n                } else {\n                    \/\/ Sent to IP, or other non-address transaction like OP_EVAL\n                    sub.address = mapValue[\"to\"];\n                }\n            } else {\n                for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) {\n                    const CTxOut& txout = wtx.vout[nOut];\n                    sub.idx = parts.size();\n\n                    if (wallet->IsCollateralAmount(txout.nValue)) sub.type = TransactionRecord::DarksendMakeCollaterals;\n                    if (wallet->IsDenominatedAmount(txout.nValue)) sub.type = TransactionRecord::DarksendCreateDenominations;\n                    if (nDebit - wtx.GetValueOut() == DARKSEND_COLLATERAL) sub.type = TransactionRecord::DarksendCollateralPayment;\n                }\n            }\n\n            CAmount nChange = wtx.GetChange();\n\n            sub.debit = -(nDebit - nChange);\n            sub.credit = nCredit - nChange;\n            parts.append(sub);\n            parts.last().involvesWatchAddress = involvesWatchAddress; \/\/ maybe pass to TransactionRecord as constructor argument\n        } else if (fAllFromMe) {\n            \/\/\n            \/\/ Debit\n            \/\/\n            CAmount nTxFee = nDebit - wtx.GetValueOut();\n\n            for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) {\n                const CTxOut& txout = wtx.vout[nOut];\n                TransactionRecord sub(hash, nTime);\n                sub.idx = parts.size();\n                sub.involvesWatchAddress = involvesWatchAddress;\n\n                if (wallet->IsMine(txout)) {\n                    \/\/ Ignore parts sent to self, as this is usually the change\n                    \/\/ from a transaction sent back to our own address.\n                    continue;\n                }\n\n                CTxDestination address;\n                if (ExtractDestination(txout.scriptPubKey, address)) {\n                    \/\/ Sent to HOPC Address\n                    sub.type = TransactionRecord::SendToAddress;\n                    sub.address = CBitcoinAddress(address).ToString();\n                } else {\n                    \/\/ Sent to IP, or other non-address transaction like OP_EVAL\n                    sub.type = TransactionRecord::SendToOther;\n                    sub.address = mapValue[\"to\"];\n                }\n\n                if (mapValue[\"DS\"] == \"1\") {\n                    sub.type = TransactionRecord::Obfuscated;\n                }\n\n                CAmount nValue = txout.nValue;\n                \/* Add fee to first output *\/\n                if (nTxFee > 0) {\n                    nValue += nTxFee;\n                    nTxFee = 0;\n                }\n                sub.debit = -nValue;\n\n                parts.append(sub);\n            }\n        } else {\n            \/\/\n            \/\/ Mixed debit transaction, can't break down payees\n            \/\/\n            parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, \"\", nNet, 0));\n            parts.last().involvesWatchAddress = involvesWatchAddress;\n        }\n    }\n\n    return parts;\n}\n\nvoid TransactionRecord::updateStatus(const CWalletTx& wtx)\n{\n    AssertLockHeld(cs_main);\n    \/\/ Determine transaction status\n\n    \/\/ Find the block the tx is in\n    CBlockIndex* pindex = NULL;\n    BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);\n    if (mi != mapBlockIndex.end())\n        pindex = (*mi).second;\n\n    \/\/ Sort order, unrecorded transactions sort to the top\n    status.sortKey = strprintf(\"%010d-%01d-%010u-%03d\",\n        (pindex ? pindex->nHeight : std::numeric_limits<int>::max()),\n        (wtx.IsCoinBase() ? 1 : 0),\n        wtx.nTimeReceived,\n        idx);\n    status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);\n    status.depth = wtx.GetDepthInMainChain();\n    status.cur_num_blocks = chainActive.Height();\n    status.cur_num_ix_locks = nCompleteTXLocks;\n\n    if (!IsFinalTx(wtx, chainActive.Height() + 1)) {\n        if (wtx.nLockTime < LOCKTIME_THRESHOLD) {\n            status.status = TransactionStatus::OpenUntilBlock;\n            status.open_for = wtx.nLockTime - chainActive.Height();\n        } else {\n            status.status = TransactionStatus::OpenUntilDate;\n            status.open_for = wtx.nLockTime;\n        }\n    }\n    \/\/ For generated transactions, determine maturity\n    else if (type == TransactionRecord::Generated || type == TransactionRecord::StakeMint || type == TransactionRecord::MNReward) {\n        if (wtx.GetBlocksToMaturity() > 0) {\n            status.status = TransactionStatus::Immature;\n\n            if (wtx.IsInMainChain()) {\n                status.matures_in = wtx.GetBlocksToMaturity();\n\n                \/\/ Check if the block was requested by anyone\n                if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n                    status.status = TransactionStatus::MaturesWarning;\n            } else {\n                status.status = TransactionStatus::NotAccepted;\n            }\n        } else {\n            status.status = TransactionStatus::Confirmed;\n        }\n    } else {\n        if (status.depth < 0) {\n            status.status = TransactionStatus::Conflicted;\n        } else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) {\n            status.status = TransactionStatus::Offline;\n        } else if (status.depth == 0) {\n            status.status = TransactionStatus::Unconfirmed;\n        } else if (status.depth < RecommendedNumConfirmations) {\n            status.status = TransactionStatus::Confirming;\n        } else {\n            status.status = TransactionStatus::Confirmed;\n        }\n    }\n}\n\nbool TransactionRecord::statusUpdateNeeded()\n{\n    AssertLockHeld(cs_main);\n    return status.cur_num_blocks != chainActive.Height() || status.cur_num_ix_locks != nCompleteTXLocks;\n}\n\nQString TransactionRecord::getTxID() const\n{\n    return QString::fromStdString(hash.ToString());\n}\n\nint TransactionRecord::getOutputIndex() const\n{\n    return idx;\n}\n","avg_line_length":38.9795918367,"max_line_length":131,"alphanum_fraction":0.5684367988,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":12297,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2009-2014 The Bitcoin developers\r\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\r\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\r\n\r\n#include \"base58.h\"\r\n#include \"rpcserver.h\"\r\n#include \"init.h\"\r\n#include \"main.h\"\r\n#include \"sync.h\"\r\n#include \"wallet.h\"\r\n\r\n#include <fstream>\r\n#include <stdint.h>\r\n\r\n#include <boost\/algorithm\/string.hpp>\r\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\r\n#include \"json\/json_spirit_value.h\"\r\n\r\nusing namespace json_spirit;\r\nusing namespace std;\r\n\r\nvoid EnsureWalletIsUnlocked();\r\n\r\nstring static EncodeDumpTime(int64_t nTime) {\r\n    return DateTimeStrFormat(\"%Y-%m-%dT%H:%M:%SZ\", nTime);\r\n}\r\n\r\nint64_t static DecodeDumpTime(const string &str) {\r\n    static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);\r\n    static const locale loc(locale::classic(),\r\n        new boost::posix_time::time_input_facet(\"%Y-%m-%dT%H:%M:%SZ\"));\r\n    istringstream iss(str);\r\n    iss.imbue(loc);\r\n    boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);\r\n    iss >> ptime;\r\n    if (ptime.is_not_a_date_time())\r\n        return 0;\r\n    return (ptime - epoch).total_seconds();\r\n}\r\n\r\nstring static EncodeDumpString(const string &str) {\r\n    stringstream ret;\r\n    for (auto c : str) {\r\n        if (c <= 32 || c >= 128 || c == '%') {\r\n            ret << '%' << HexStr(&c, &c + 1);\r\n        } else {\r\n            ret << c;\r\n        }\r\n    }\r\n    return ret.str();\r\n}\r\n\r\nstring DecodeDumpString(const string &str) {\r\n    stringstream ret;\r\n    for (unsigned int pos = 0; pos < str.length(); pos++) {\r\n        unsigned char c = str[pos];\r\n        if (c == '%' && pos+2 < str.length()) {\r\n            c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | \r\n                ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));\r\n            pos += 2;\r\n        }\r\n        ret << c;\r\n    }\r\n    return ret.str();\r\n}\r\n\r\nValue importprivkey(const Array& params, bool fHelp)\r\n{\r\n    if (fHelp || params.size() < 1 || params.size() > 3)\r\n        throw runtime_error(\r\n            \"importprivkey \\\"bitcoinprivkey\\\" ( \\\"label\\\" rescan )\\n\"\r\n            \"\\nAdds a private key (as returned by dumpprivkey) to your wallet.\\n\"\r\n            \"\\nArguments:\\n\"\r\n            \"1. \\\"bitcoinprivkey\\\"   (string, required) The private key (see dumpprivkey)\\n\"\r\n            \"2. \\\"label\\\"            (string, optional) an optional label\\n\"\r\n            \"3. rescan               (boolean, optional, default=true) Rescan the wallet for transactions\\n\"\r\n            \"\\nExamples:\\n\"\r\n            \"\\nDump a private key\\n\"\r\n            + HelpExampleCli(\"dumpprivkey\", \"\\\"myaddress\\\"\") +\r\n            \"\\nImport the private key\\n\"\r\n            + HelpExampleCli(\"importprivkey\", \"\\\"mykey\\\"\") +\r\n            \"\\nImport using a label\\n\"\r\n            + HelpExampleCli(\"importprivkey\", \"\\\"mykey\\\" \\\"testing\\\" false\") +\r\n            \"\\nAs a json rpc call\\n\"\r\n            + HelpExampleRpc(\"importprivkey\", \"\\\"mykey\\\", \\\"testing\\\", false\")\r\n        );\r\n\r\n    EnsureWalletIsUnlocked();\r\n\r\n    string strSecret = params[0].get_str();\r\n    string strLabel = \"\";\r\n    if (params.size() > 1)\r\n        strLabel = params[1].get_str();\r\n\r\n    \/\/ Whether to perform rescan after import\r\n    bool fRescan = true;\r\n    if (params.size() > 2)\r\n        fRescan = params[2].get_bool();\r\n\r\n    CBitcoinSecret vchSecret;\r\n    bool fGood = vchSecret.SetString(strSecret);\r\n\r\n    if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid private key encoding\");\r\n\r\n    CKey key = vchSecret.GetKey();\r\n    if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Private key outside allowed range\");\r\n\r\n    CPubKey pubkey = key.GetPubKey();\r\n    CKeyID vchAddress = pubkey.GetID();\r\n    {\r\n        LOCK2(cs_main, pwalletMain->cs_wallet);\r\n\r\n\/\/        pwalletMain->MarkDirty();\r\n        pwalletMain->SetAddressBook(vchAddress, strLabel, \"receive\");\r\n\r\n        \/\/ Don't throw error in case a key is already there\r\n        if (pwalletMain->HaveKey(vchAddress))\r\n            return Value::null;\r\n\r\n        pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1;\r\n\r\n        if (!pwalletMain->AddKeyPubKey(key, pubkey))\r\n            throw JSONRPCError(RPC_WALLET_ERROR, \"Error adding key to wallet\");\r\n\r\n        \/\/ whenever a key is imported, we need to scan the whole chain\r\n        pwalletMain->nTimeFirstKey = 1; \/\/ 0 would be considered 'no value'\r\n\r\n        if (fRescan) {\r\n            pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);\r\n        }\r\n    }\r\n\r\n    return Value::null;\r\n}\r\n\r\nValue importwallet(const Array& params, bool fHelp)\r\n{\r\n    if (fHelp || params.size() != 1)\r\n        throw runtime_error(\r\n            \"importwallet \\\"filename\\\"\\n\"\r\n            \"\\nImports keys from a wallet dump file (see dumpwallet).\\n\"\r\n            \"\\nArguments:\\n\"\r\n            \"1. \\\"filename\\\"    (string, required) The wallet file\\n\"\r\n            \"\\nExamples:\\n\"\r\n            \"\\nDump the wallet\\n\"\r\n            + HelpExampleCli(\"dumpwallet\", \"\\\"test\\\"\") +\r\n            \"\\nImport the wallet\\n\"\r\n            + HelpExampleCli(\"importwallet\", \"\\\"test\\\"\") +\r\n            \"\\nImport using the json rpc call\\n\"\r\n            + HelpExampleRpc(\"importwallet\", \"\\\"test\\\"\")\r\n        );\r\n\r\n    EnsureWalletIsUnlocked();\r\n\r\n    ifstream file;\r\n    file.open(params[0].get_str().c_str(), ios::in | ios::ate);\r\n    if (!file.is_open())\r\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"Cannot open wallet dump file\");\r\n\r\n    int64_t nTimeBegin = chainActive.Tip()->nTime;\r\n\r\n    bool fGood = true;\r\n\r\n    int64_t nFilesize = max((int64_t)1, (int64_t)file.tellg());\r\n    file.seekg(0, file.beg);\r\n\r\n    pwalletMain->ShowProgress(_(\"Importing...\"), 0); \/\/ show progress dialog in GUI\r\n    while (file.good()) {\r\n        pwalletMain->ShowProgress(\"\", max(1, min(99, (int)(((double)file.tellg() \/ (double)nFilesize) * 100))));\r\n        string line;\r\n        getline(file, line);\r\n        if (line.empty() || line[0] == '#')\r\n            continue;\r\n\r\n        vector<string> vstr;\r\n        boost::split(vstr, line, boost::is_any_of(\" \"));\r\n        if (vstr.size() < 2)\r\n            continue;\r\n        CBitcoinSecret vchSecret;\r\n        if (!vchSecret.SetString(vstr[0]))\r\n            continue;\r\n        CKey key = vchSecret.GetKey();\r\n        CPubKey pubkey = key.GetPubKey();\r\n        CKeyID keyid = pubkey.GetID();\r\n        if (pwalletMain->HaveKey(keyid)) {\r\n            LogPrint(\"INFO\",\"Skipping import of %s (key already present)\\n\", CBitcoinAddress(keyid).ToString());\r\n            continue;\r\n        }\r\n        int64_t nTime = DecodeDumpTime(vstr[1]);\r\n        string strLabel;\r\n        bool fLabel = true;\r\n        for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {\r\n            if (boost::algorithm::starts_with(vstr[nStr], \"#\"))\r\n                break;\r\n            if (vstr[nStr] == \"change=1\")\r\n                fLabel = false;\r\n            if (vstr[nStr] == \"reserve=1\")\r\n                fLabel = false;\r\n            if (boost::algorithm::starts_with(vstr[nStr], \"label=\")) {\r\n                strLabel = DecodeDumpString(vstr[nStr].substr(6));\r\n                fLabel = true;\r\n            }\r\n        }\r\n        LogPrint(\"INFO\",\"Importing %s...\\n\", CBitcoinAddress(keyid).ToString());\r\n        if (!pwalletMain->AddKeyPubKey(key, pubkey)) {\r\n            fGood = false;\r\n            continue;\r\n        }\r\n        pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime;\r\n        if (fLabel)\r\n            pwalletMain->SetAddressBook(keyid, strLabel, \"receive\");\r\n        nTimeBegin = min(nTimeBegin, nTime);\r\n    }\r\n    file.close();\r\n    pwalletMain->ShowProgress(\"\", 100); \/\/ hide progress dialog in GUI\r\n\r\n    CBlockIndex *pindex = chainActive.Tip();\r\n    while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200)\r\n        pindex = pindex->pprev;\r\n\r\n    if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey)\r\n        pwalletMain->nTimeFirstKey = nTimeBegin;\r\n\r\n    LogPrint(\"INFO\",\"Rescanning last %i blocks\\n\", chainActive.Height() - pindex->nHeight + 1);\r\n    pwalletMain->ScanForWalletTransactions(pindex);\r\n\/\/    pwalletMain->MarkDirty();\r\n\r\n    if (!fGood)\r\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Error adding some keys to wallet\");\r\n\r\n    return Value::null;\r\n}\r\n\r\nValue dumpprivkey(const Array& params, bool fHelp)\r\n{\r\n    if (fHelp || params.size() != 1)\r\n        throw runtime_error(\r\n            \"dumpprivkey \\\"bitcoinaddress\\\"\\n\"\r\n            \"\\nReveals the private key corresponding to 'bitcoinaddress'.\\n\"\r\n            \"Then the importprivkey can be used with this output\\n\"\r\n            \"\\nArguments:\\n\"\r\n            \"1. \\\"bitcoinaddress\\\"   (string, required) The bitcoin address for the private key\\n\"\r\n            \"\\nResult:\\n\"\r\n            \"\\\"key\\\"                (string) The private key\\n\"\r\n            \"\\nExamples:\\n\"\r\n            + HelpExampleCli(\"dumpprivkey\", \"\\\"myaddress\\\"\")\r\n            + HelpExampleCli(\"importprivkey\", \"\\\"mykey\\\"\")\r\n            + HelpExampleRpc(\"dumpprivkey\", \"\\\"myaddress\\\"\")\r\n        );\r\n\r\n    EnsureWalletIsUnlocked();\r\n\r\n    string strAddress = params[0].get_str();\r\n    CBitcoinAddress address;\r\n    if (!address.SetString(strAddress))\r\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid Bitcoin address\");\r\n    CKeyID keyID;\r\n    if (!address.GetKeyID(keyID))\r\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Address does not refer to a key\");\r\n    CKey vchSecret;\r\n    if (!pwalletMain->GetKey(keyID, vchSecret))\r\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Private key for address \" + strAddress + \" is not known\");\r\n    return CBitcoinSecret(vchSecret).ToString();\r\n}\r\n\r\n\r\nValue dumpwallet(const Array& params, bool fHelp)\r\n{\r\n    if (fHelp || params.size() != 1)\r\n        throw runtime_error(\r\n            \"dumpwallet \\\"filename\\\"\\n\"\r\n            \"\\nDumps all wallet keys in a human-readable format.\\n\"\r\n            \"\\nArguments:\\n\"\r\n            \"1. \\\"filename\\\"    (string, required) The filename\\n\"\r\n            \"\\nExamples:\\n\"\r\n            + HelpExampleCli(\"dumpwallet\", \"\\\"test\\\"\")\r\n            + HelpExampleRpc(\"dumpwallet\", \"\\\"test\\\"\")\r\n        );\r\n\r\n    EnsureWalletIsUnlocked();\r\n\r\n    ofstream file;\r\n    file.open(params[0].get_str().c_str());\r\n    if (!file.is_open())\r\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"Cannot open wallet dump file\");\r\n\r\n    map<CKeyID, int64_t> mapKeyBirth;\r\n    set<CKeyID> setKeyPool;\r\n    pwalletMain->GetKeyBirthTimes(mapKeyBirth);\r\n    pwalletMain->GetAllReserveKeys(setKeyPool);\r\n\r\n    \/\/ sort time\/key pairs\r\n    vector<pair<int64_t, CKeyID> > vKeyBirth;\r\n    for (map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) {\r\n        vKeyBirth.push_back(make_pair(it->second, it->first));\r\n    }\r\n    mapKeyBirth.clear();\r\n    sort(vKeyBirth.begin(), vKeyBirth.end());\r\n\r\n    \/\/ produce output\r\n    file << strprintf(\"# Wallet dump created by Bitcoin %s (%s)\\n\", CLIENT_BUILD, CLIENT_DATE);\r\n    file << strprintf(\"# * Created on %s\\n\", EncodeDumpTime(GetTime()));\r\n    file << strprintf(\"# * Best block at time of backup was %i (%s),\\n\", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString());\r\n    file << strprintf(\"#   mined on %s\\n\", EncodeDumpTime(chainActive.Tip()->nTime));\r\n    file << \"\\n\";\r\n    for (vector<pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {\r\n        const CKeyID &keyid = it->second;\r\n        string strTime = EncodeDumpTime(it->first);\r\n        string strAddr = CBitcoinAddress(keyid).ToString();\r\n        CKey key;\r\n        if (pwalletMain->GetKey(keyid, key)) {\r\n            if (pwalletMain->mapAddressBook.count(keyid)) {\r\n                file << strprintf(\"%s %s label=%s # addr=%s\\n\", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr);\r\n            } else if (setKeyPool.count(keyid)) {\r\n                file << strprintf(\"%s %s reserve=1 # addr=%s\\n\", CBitcoinSecret(key).ToString(), strTime, strAddr);\r\n            } else {\r\n                file << strprintf(\"%s %s change=1 # addr=%s\\n\", CBitcoinSecret(key).ToString(), strTime, strAddr);\r\n            }\r\n        }\r\n    }\r\n    file << \"\\n\";\r\n    file << \"# End of dump\\n\";\r\n    file.close();\r\n    return Value::null;\r\n}\r\n","avg_line_length":37.7208588957,"max_line_length":174,"alphanum_fraction":0.5791656502,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":815,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause-Clear","Apache-2.0","MIT"],"max_stars_count":11.0,"content":"\/\/ Copyright (C) 2022 J\u00e9r\u00f4me \"Lynix\" Leclercq (lynix680@gmail.com)\n\/\/ This file is part of the \"Nazara Engine - Utility module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Utility\/Buffer.hpp>\n#include <Nazara\/Utility\/BufferMapper.hpp>\n#include <stdexcept>\n#include <vector>\n#include <Nazara\/Utility\/Debug.hpp>\n\nnamespace Nz\n{\n\tBuffer::~Buffer() = default;\n\n\tstd::shared_ptr<Buffer> Buffer::CopyContent(const BufferFactory& bufferFactory)\n\t{\n\t\tif (GetUsageFlags() & BufferUsage::DirectMapping)\n\t\t{\n\t\t\tBufferMapper<Buffer> mapper(*this, 0, GetSize());\n\t\t\treturn bufferFactory(GetType(), GetSize(), GetUsageFlags(), mapper.GetPointer());\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ TODO: Implement GPU to CPU\n\t\t\tthrow std::runtime_error(\"buffer is not mappable not implemented\");\n\t\t}\n\t}\n}\n","avg_line_length":28.1034482759,"max_line_length":84,"alphanum_fraction":0.7226993865,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1703,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC0-1.0"],"max_stars_count":8.0,"content":"#include <algorithm>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <set>\n#include <stack>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\nusing namespace std;\nconst int MAX_VALUE = 0x7FFFFFFF, MIN_VALUE = 0x80000000, INF = 0x3F3F3F3F, kMod = 1E9 + 7;\n#define fastio                                                                                                                                                                                         \\\n  ios_base::sync_with_stdio(false);                                                                                                                                                                    \\\n  cin.tie(0);                                                                                                                                                                                          \\\n  cout.tie(0);\n#define debug puts(\"pigtoria bling bling \u26a1\ufe0f\u26a1\ufe0f\");\n#define FOR(i, a, b) for (int i = a; i < b; i++)\n#define pii pair<int, int>\n#define LL long long\n#define LD long double\n#define PB push_back\n#define EB emplace_back\n#define MP make_pair\n#define FI first\n#define SE second\n\nclass Solution {\npublic:\n  int minimumSize(vector<int> &nums, int maxOperations) {\n    \/\/ https:\/\/www.bilibili.com\/video\/BV1bK4y1H7Ly\n    int l = 1, r = *max_element(nums.begin(), nums.end()) + 1;\n    while (l < r) {\n      int m = l + (r - l) \/ 2;\n      int ops = 0;\n      for (int x : nums) {\n        ops += (x + m - 1) \/ m - 1; \/\/ \u5411\u4e0a\u53d6\u6574-1\n      }\n      if (ops > maxOperations) { \/\/ \u8fd4\u56de\u2264\u7684l\n        l = m + 1;\n      } else {\n        r = m;\n      }\n    }\n    return l;\n  }\n};\n\nint main() {}","avg_line_length":33.3921568627,"max_line_length":200,"alphanum_fraction":0.4163241339,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3054,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":163.0,"content":"\/\/ Copyright mogemimi. Distributed under the MIT license.\n\n#include \"pomdog\/experimental\/skeletal2d\/blendtrees\/animation_cross_fade_node.hpp\"\n#include \"pomdog\/experimental\/skeletal2d\/blendtrees\/animation_graph_weight_collection.hpp\"\n#include \"pomdog\/experimental\/skeletal2d\/blendtrees\/weight_blending_helper.hpp\"\n#include \"pomdog\/experimental\/skeletal2d\/skeleton.hpp\"\n#include \"pomdog\/experimental\/skeletal2d\/skeleton_helper.hpp\"\n#include \"pomdog\/experimental\/skeletal2d\/skeleton_pose.hpp\"\n#include \"pomdog\/utility\/assert.hpp\"\n\nnamespace pomdog::skeletal2d::detail {\nnamespace {\n\nAnimationTimeInterval\nWrapTime(const AnimationTimeInterval& source, const AnimationTimeInterval& max)\n{\n    auto time = source;\n    while (time > max) {\n        time -= max;\n    }\n\n    POMDOG_ASSERT(time >= AnimationTimeInterval::zero());\n    POMDOG_ASSERT(time <= max);\n\n    return time;\n}\n\n} \/\/ namespace\n\nAnimationCrossFadeNode::AnimationCrossFadeNode(\n    const SkeletonAnimationState& currentAnimationIn,\n    const SkeletonAnimationState& nextAnimationIn,\n    const AnimationTimeInterval& transitionDurationIn,\n    const AnimationTimeInterval& currentAnimationStartTimeIn)\n    : currentAnimation(currentAnimationIn)\n    , nextAnimation(nextAnimationIn)\n    , transitionDuration(transitionDurationIn)\n    , currentAnimationStartTime(currentAnimationStartTimeIn)\n{\n}\n\nvoid AnimationCrossFadeNode::Calculate(\n    const AnimationTimeInterval& time,\n    const detail::AnimationGraphWeightCollection& weights,\n    const Skeleton& skeleton,\n    SkeletonPose& skeletonPose,\n    Skin* skin) const\n{\n    auto sourcePose1 = SkeletonPose::CreateBindPose(skeleton);\n    auto sourcePose2 = SkeletonPose::CreateBindPose(skeleton);\n\n    POMDOG_ASSERT(transitionDuration.count() > 0);\n    const float weight = (time \/ transitionDuration.count()).count();\n    POMDOG_ASSERT(weight >= 0.0f);\n    POMDOG_ASSERT(weight <= 1.0f);\n\n    Skin* skin1 = skin;\n    Skin* skin2 = nullptr;\n    if (weight >= 0.5f) {\n        std::swap(skin1, skin2);\n    }\n\n    {\n        auto sourceTime = WrapTime(currentAnimationStartTime + time, currentAnimation.Node->GetLength());\n\n        POMDOG_ASSERT(sourceTime >= AnimationTimeInterval::zero());\n        POMDOG_ASSERT(sourceTime <= currentAnimation.Node->GetLength());\n\n        POMDOG_ASSERT(currentAnimation.Node);\n        currentAnimation.Node->Calculate(sourceTime, weights, skeleton, sourcePose1, skin1);\n    }\n    {\n        auto sourceTime = WrapTime(time, nextAnimation.Node->GetLength());\n\n        POMDOG_ASSERT(sourceTime >= AnimationTimeInterval::zero());\n        POMDOG_ASSERT(sourceTime <= nextAnimation.Node->GetLength());\n\n        POMDOG_ASSERT(nextAnimation.Node);\n        nextAnimation.Node->Calculate(sourceTime, weights, skeleton, sourcePose2, skin2);\n    }\n\n    using detail::WeightBlendingHelper::Lerp;\n    Lerp(sourcePose1.JointPoses, sourcePose2.JointPoses, weight, skeletonPose.JointPoses);\n}\n\nAnimationTimeInterval AnimationCrossFadeNode::GetLength() const\n{\n    return transitionDuration;\n}\n\n} \/\/ namespace pomdog::skeletal2d::detail\n","avg_line_length":33.1956521739,"max_line_length":105,"alphanum_fraction":0.7465618861,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":122,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":5.0,"content":"#include \"SelectionListener.h\"\n\nSelectionListener::SelectionListener()\n{\n\n}\n\nSelectionListener::~SelectionListener()\n{\n\n}\n","avg_line_length":10.1666666667,"max_line_length":39,"alphanum_fraction":0.762295082,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4432,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2.0,"content":"\/*\n* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\").\n* You may not use this file except in compliance with the License.\n* A copy of the License is located at\n*\n*  http:\/\/aws.amazon.com\/apache2.0\n*\n* or in the \"license\" file accompanying this file. This file is distributed\n* on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n* express or implied. See the License for the specific language governing\n* permissions and limitations under the License.\n*\/\n#include <aws\/devicefarm\/model\/Test.h>\n#include <aws\/core\/utils\/json\/JsonSerializer.h>\n\n#include <utility>\n\nusing namespace Aws::Utils::Json;\nusing namespace Aws::Utils;\n\nnamespace Aws\n{\nnamespace DeviceFarm\n{\nnamespace Model\n{\n\nTest::Test() : \n    m_arnHasBeenSet(false),\n    m_nameHasBeenSet(false),\n    m_typeHasBeenSet(false),\n    m_createdHasBeenSet(false),\n    m_statusHasBeenSet(false),\n    m_resultHasBeenSet(false),\n    m_startedHasBeenSet(false),\n    m_stoppedHasBeenSet(false),\n    m_countersHasBeenSet(false),\n    m_messageHasBeenSet(false),\n    m_deviceMinutesHasBeenSet(false)\n{\n}\n\nTest::Test(const JsonValue& jsonValue) : \n    m_arnHasBeenSet(false),\n    m_nameHasBeenSet(false),\n    m_typeHasBeenSet(false),\n    m_createdHasBeenSet(false),\n    m_statusHasBeenSet(false),\n    m_resultHasBeenSet(false),\n    m_startedHasBeenSet(false),\n    m_stoppedHasBeenSet(false),\n    m_countersHasBeenSet(false),\n    m_messageHasBeenSet(false),\n    m_deviceMinutesHasBeenSet(false)\n{\n  *this = jsonValue;\n}\n\nTest& Test::operator =(const JsonValue& jsonValue)\n{\n  if(jsonValue.ValueExists(\"arn\"))\n  {\n    m_arn = jsonValue.GetString(\"arn\");\n\n    m_arnHasBeenSet = true;\n  }\n\n  if(jsonValue.ValueExists(\"name\"))\n  {\n    m_name = jsonValue.GetString(\"name\");\n\n    m_nameHasBeenSet = true;\n  }\n\n  if(jsonValue.ValueExists(\"type\"))\n  {\n    m_type = TestTypeMapper::GetTestTypeForName(jsonValue.GetString(\"type\"));\n\n    m_typeHasBeenSet = true;\n  }\n\n  if(jsonValue.ValueExists(\"created\"))\n  {\n    m_created = jsonValue.GetDouble(\"created\");\n\n    m_createdHasBeenSet = true;\n  }\n\n  if(jsonValue.ValueExists(\"status\"))\n  {\n    m_status = ExecutionStatusMapper::GetExecutionStatusForName(jsonValue.GetString(\"status\"));\n\n    m_statusHasBeenSet = true;\n  }\n\n  if(jsonValue.ValueExists(\"result\"))\n  {\n    m_result = ExecutionResultMapper::GetExecutionResultForName(jsonValue.GetString(\"result\"));\n\n    m_resultHasBeenSet = true;\n  }\n\n  if(jsonValue.ValueExists(\"started\"))\n  {\n    m_started = jsonValue.GetDouble(\"started\");\n\n    m_startedHasBeenSet = true;\n  }\n\n  if(jsonValue.ValueExists(\"stopped\"))\n  {\n    m_stopped = jsonValue.GetDouble(\"stopped\");\n\n    m_stoppedHasBeenSet = true;\n  }\n\n  if(jsonValue.ValueExists(\"counters\"))\n  {\n    m_counters = jsonValue.GetObject(\"counters\");\n\n    m_countersHasBeenSet = true;\n  }\n\n  if(jsonValue.ValueExists(\"message\"))\n  {\n    m_message = jsonValue.GetString(\"message\");\n\n    m_messageHasBeenSet = true;\n  }\n\n  if(jsonValue.ValueExists(\"deviceMinutes\"))\n  {\n    m_deviceMinutes = jsonValue.GetObject(\"deviceMinutes\");\n\n    m_deviceMinutesHasBeenSet = true;\n  }\n\n  return *this;\n}\n\nJsonValue Test::Jsonize() const\n{\n  JsonValue payload;\n\n  if(m_arnHasBeenSet)\n  {\n   payload.WithString(\"arn\", m_arn);\n\n  }\n\n  if(m_nameHasBeenSet)\n  {\n   payload.WithString(\"name\", m_name);\n\n  }\n\n  if(m_typeHasBeenSet)\n  {\n   payload.WithString(\"type\", TestTypeMapper::GetNameForTestType(m_type));\n  }\n\n  if(m_createdHasBeenSet)\n  {\n   payload.WithDouble(\"created\", m_created.SecondsWithMSPrecision());\n  }\n\n  if(m_statusHasBeenSet)\n  {\n   payload.WithString(\"status\", ExecutionStatusMapper::GetNameForExecutionStatus(m_status));\n  }\n\n  if(m_resultHasBeenSet)\n  {\n   payload.WithString(\"result\", ExecutionResultMapper::GetNameForExecutionResult(m_result));\n  }\n\n  if(m_startedHasBeenSet)\n  {\n   payload.WithDouble(\"started\", m_started.SecondsWithMSPrecision());\n  }\n\n  if(m_stoppedHasBeenSet)\n  {\n   payload.WithDouble(\"stopped\", m_stopped.SecondsWithMSPrecision());\n  }\n\n  if(m_countersHasBeenSet)\n  {\n   payload.WithObject(\"counters\", m_counters.Jsonize());\n\n  }\n\n  if(m_messageHasBeenSet)\n  {\n   payload.WithString(\"message\", m_message);\n\n  }\n\n  if(m_deviceMinutesHasBeenSet)\n  {\n   payload.WithObject(\"deviceMinutes\", m_deviceMinutes.Jsonize());\n\n  }\n\n  return payload;\n}\n\n} \/\/ namespace Model\n} \/\/ namespace DeviceFarm\n} \/\/ namespace Aws","avg_line_length":20.9056603774,"max_line_length":95,"alphanum_fraction":0.711868231,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6850,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":13.0,"content":"\/****************************************************************************\n *\n *   Copyright (c) 2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\n\/**\n * @file spektrum_rc.cpp\n *\n * This is a driver for a Spektrum satellite receiver connected to a Snapdragon\n * on the serial port. By default port J12 (next to J13, power module side) is used.\n *\/\n\n#include <string.h>\n\n#include <px4_platform_common\/tasks.h>\n#include <px4_platform_common\/posix.h>\n#include <px4_platform_common\/getopt.h>\n\n#include <lib\/rc\/dsm.h>\n#include <drivers\/drv_rc_input.h>\n#include <drivers\/drv_hrt.h>\n\n#include <uORB\/uORB.h>\n#include <uORB\/topics\/input_rc.h>\n\n\/\/ Snapdraogon: use J12 (next to J13, power module side)\n#define SPEKTRUM_UART_DEVICE_PATH \"\/dev\/tty-3\"\n\n#define UNUSED(x) (void)(x)\n\nextern \"C\" { __EXPORT int spektrum_rc_main(int argc, char *argv[]); }\n\n\nnamespace spektrum_rc\n{\n\nvolatile bool _task_should_exit = false;\nstatic bool _is_running = false;\nstatic px4_task_t _task_handle = -1;\n\nint start();\nint stop();\nint info();\nvoid usage();\nvoid task_main(int argc, char *argv[]);\n\nvoid fill_input_rc(uint16_t raw_rc_count, uint16_t raw_rc_values[input_rc_s::RC_INPUT_MAX_CHANNELS],\n\t\t   hrt_abstime now, bool frame_drop, bool failsafe, unsigned frame_drops, int rssi,\n\t\t   input_rc_s &input_rc);\n\nvoid task_main(int argc, char *argv[])\n{\n\tconst char *device_path = SPEKTRUM_UART_DEVICE_PATH;\n\tint ch;\n\tint myoptind = 1;\n\tconst char *myoptarg = NULL;\n\n\twhile ((ch = px4_getopt(argc, argv, \"d:\", &myoptind, &myoptarg)) != EOF) {\n\t\tswitch (ch) {\n\t\tcase 'd':\n\t\t\tdevice_path = myoptarg;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tint uart_fd = dsm_init(device_path);\n\n\tif (uart_fd < 1) {\n\t\tPX4_ERR(\"dsm init failed\");\n\t\treturn;\n\t}\n\n\torb_advert_t rc_pub = nullptr;\n\n\t\/\/ Use a buffer size of the double of the minimum, just to be safe.\n\tuint8_t rx_buf[2 * DSM_BUFFER_SIZE];\n\n\t_is_running = true;\n\tuint16_t raw_rc_values[input_rc_s::RC_INPUT_MAX_CHANNELS];\n\tuint16_t raw_rc_count = 0;\n\n\t\/\/ Main loop\n\twhile (!_task_should_exit) {\n\n\t\tint newbytes = ::read(uart_fd, &rx_buf[0], sizeof(rx_buf));\n\n\t\tif (newbytes < 0) {\n\t\t\tPX4_WARN(\"read failed\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (newbytes == 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst hrt_abstime now = hrt_absolute_time();\n\n\t\tbool dsm_11_bit;\n\t\tunsigned frame_drops;\n\t\tint8_t dsm_rssi;\n\n\t\t\/\/ parse new data\n\t\tbool rc_updated = dsm_parse(now, rx_buf, newbytes, &raw_rc_values[0], &raw_rc_count,\n\t\t\t\t\t    &dsm_11_bit, &frame_drops, &dsm_rssi, input_rc_s::RC_INPUT_MAX_CHANNELS);\n\t\tUNUSED(dsm_11_bit);\n\n\t\tif (rc_updated) {\n\n\t\t\tinput_rc_s input_rc = {};\n\n\t\t\tfill_input_rc(raw_rc_count, raw_rc_values, now, false, false, frame_drops, dsm_rssi,\n\t\t\t\t      input_rc);\n\n\t\t\tif (rc_pub == nullptr) {\n\t\t\t\trc_pub = orb_advertise(ORB_ID(input_rc), &input_rc);\n\n\t\t\t} else {\n\t\t\t\torb_publish(ORB_ID(input_rc), rc_pub, &input_rc);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ sleep since no poll for qurt\n\t\tusleep(10000);\n\n\t}\n\n\torb_unadvertise(rc_pub);\n\tdsm_deinit();\n\n\t_is_running = false;\n}\n\nvoid fill_input_rc(uint16_t raw_rc_count, uint16_t raw_rc_values[input_rc_s::RC_INPUT_MAX_CHANNELS],\n\t\t   hrt_abstime now, bool frame_drop, bool failsafe, unsigned frame_drops, int rssi,\n\t\t   input_rc_s &input_rc)\n{\n\tinput_rc.input_source = input_rc_s::RC_INPUT_SOURCE_QURT;\n\n\tinput_rc.channel_count = raw_rc_count;\n\n\tif (input_rc.channel_count > input_rc_s::RC_INPUT_MAX_CHANNELS) {\n\t\tinput_rc.channel_count = input_rc_s::RC_INPUT_MAX_CHANNELS;\n\t}\n\n\tunsigned valid_chans = 0;\n\n\tfor (unsigned i = 0; i < input_rc.channel_count; ++i) {\n\t\tinput_rc.values[i] = raw_rc_values[i];\n\n\t\tif (raw_rc_values[i] != UINT16_MAX) {\n\t\t\tvalid_chans++;\n\t\t}\n\t}\n\n\tinput_rc.timestamp = now;\n\tinput_rc.timestamp_last_signal = input_rc.timestamp;\n\tinput_rc.rc_ppm_frame_length = 0;\n\n\t\/* fake rssi if no value was provided *\/\n\tif (rssi == -1) {\n\n\t\tinput_rc.rssi = 255;\n\n\t} else {\n\t\tinput_rc.rssi = rssi;\n\t}\n\n\tif (valid_chans == 0) {\n\t\tinput_rc.rssi = 0;\n\t}\n\n\tinput_rc.rc_failsafe = failsafe;\n\tinput_rc.rc_lost = (valid_chans == 0);\n\tinput_rc.rc_lost_frame_count = frame_drops;\n\tinput_rc.rc_total_frame_count = 0;\n}\n\nint start(int argc, char *argv[])\n{\n\tif (_is_running) {\n\t\tPX4_WARN(\"already running\");\n\t\treturn -1;\n\t}\n\n\t_task_should_exit = false;\n\n\t_task_handle = px4_task_spawn_cmd(\"spektrum_rc_main\",\n\t\t\t\t\t  SCHED_DEFAULT,\n\t\t\t\t\t  SCHED_PRIORITY_DEFAULT,\n\t\t\t\t\t  2000,\n\t\t\t\t\t  (px4_main_t)&task_main,\n\t\t\t\t\t  (char *const *)argv);\n\n\tif (_task_handle < 0) {\n\t\tPX4_ERR(\"task start failed\");\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\nint stop()\n{\n\tif (!_is_running) {\n\t\tPX4_WARN(\"not running\");\n\t\treturn -1;\n\t}\n\n\t_task_should_exit = true;\n\n\twhile (_is_running) {\n\t\tusleep(200000);\n\t\tPX4_INFO(\".\");\n\t}\n\n\t_task_handle = -1;\n\treturn 0;\n}\n\nint info()\n{\n\tPX4_INFO(\"running: %s\", _is_running ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n\nvoid\nusage()\n{\n\tPX4_INFO(\"Usage: spektrum_rc {start|info|stop}\");\n}\n\n} \/\/ namespace spektrum_rc\n\n\nint spektrum_rc_main(int argc, char *argv[])\n{\n\tint myoptind = 1;\n\n\tif (argc <= 1) {\n\t\tspektrum_rc::usage();\n\t\treturn 1;\n\t}\n\n\tconst char *verb = argv[myoptind];\n\n\n\tif (!strcmp(verb, \"start\")) {\n\t\treturn spektrum_rc::start(argc - 1, argv + 1);\n\t}\n\n\telse if (!strcmp(verb, \"stop\")) {\n\t\treturn spektrum_rc::stop();\n\t}\n\n\telse if (!strcmp(verb, \"info\")) {\n\t\treturn spektrum_rc::info();\n\t}\n\n\telse {\n\t\tspektrum_rc::usage();\n\t\treturn 1;\n\t}\n}\n","avg_line_length":23.063973064,"max_line_length":100,"alphanum_fraction":0.6870072993,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10751,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2021. Happy GardenPI\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n\/\/\n\/\/ Created by Antonio Salsi on 16\/08\/21.\n\/\/\n\n#include <gtest\/gtest.h>\n\n#include <string>\nusing namespace std;\n\n#include <hgardenpi-protocol\/protocol.hpp>\n#include <hgardenpi-protocol\/packages\/aggregation.hpp>\n#include <hgardenpi-protocol\/packages\/data.hpp>\n#include <hgardenpi-protocol\/packages\/finish.hpp>\n#include <hgardenpi-protocol\/packages\/station.hpp>\n#include <hgardenpi-protocol\/packages\/synchro.hpp>\n#include <hgardenpi-protocol\/packages\/error.hpp>\n#include <hgardenpi-protocol\/utilities\/stringutils.hpp>\n#include <hgardenpi-protocol\/utilities\/numberutils.hpp>\nusing namespace hgardenpi::protocol;\n\n\nTEST(ProtocolTest, encodeAGG)\n{\n    auto agg = new Aggregation;\n\n    agg->id = 23;\n    agg->setDescription(\"desc\");\n    agg->setStart(\"start\");\n    agg->setEnd(\"end\");\n    agg->schedule.minute = 30;\n    agg->schedule.hour = 13;\n    agg->schedule.days = 0b0111'1111;\n    agg->sequential = false;\n    agg->weight = 20;\n    agg->status = hgardenpi::protocol::v2::Status::UNACTIVE;\n\n    auto enc = encode(agg, ACK);\n\n    delete agg;\n\n    EXPECT_EQ(enc.size(), 1);\n\n    auto head = decode(enc[0].first.get());\n    EXPECT_EQ(head->flags, AGG | ACK);\n\n    if (auto *ptr = dynamic_cast<Aggregation *>(head->deserialize()))\n    {\n        EXPECT_TRUE(ptr->getDescription() == string(\"desc\"));\n        EXPECT_TRUE(ptr->getStart() == string(\"start\"));\n        EXPECT_TRUE(ptr->getEnd() == string(\"end\"));\n        EXPECT_EQ(ptr->schedule.minute, 30);\n        EXPECT_EQ(ptr->schedule.hour, 13);\n        EXPECT_EQ(ptr->schedule.days, 0b0111'1111);\n        EXPECT_EQ(ptr->sequential, false);\n        EXPECT_EQ(ptr->weight, 20);\n        EXPECT_EQ(ptr->status, Status::UNACTIVE);\n        delete ptr;\n    }\n\n\n}\n\nTEST(ProtocolTest, encodeDAT)\n{\n    string datExample = \"ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQB\/nAmOjTmezNUDKYvEeIRf2YnwM9\/uUG1d0BYsc8\/tRtx+RGi7N2lUbp728MXGwdnL9od4cItzky\/zVdLZE2cycOa18xBK9cOWmcKS0A8FYBxEQWJ\/q9YVUgZbFKfYGaGQxsER+A0w\/fX8ALuk78ktP31K69LcQgxIsl7rNzxsoOQKJ\/CIxOGMMxczYTiEoLvQhapFQMs3FL96didKr\/QbrfB1WT6s3838SEaXfgZvLef1YB2xmfhbT9OXFE3FXvh2UPBfN+ffE7iiayQf\/2XR+8j4N4bW30DiPtOQLGUrH1y5X\/rpNZNlWW2+jGIxqZtgWg7lTy3mXy5x836Sj\/6L\";\n\n    auto dat = new Data;\n    dat->setPayload(datExample);\n\n    auto enc = encode(dat, ACK);\n\n    delete dat;\n\n    EXPECT_EQ(enc.size(), 3);\n\n    string datRet;\n    uint16_t i = 0;\n    for (auto &&buffer : enc)\n    {\n        auto head = decode(buffer.first.get());\n        if (head->flags & FIN && head->flags & ACK)\n        {\n            EXPECT_EQ(head->flags, FIN | ACK | CKN);\n            break;\n        }\n        if (head->flags & DAT && head->flags & ACK && head->flags & CKN)\n        {\n            EXPECT_EQ(head->flags, DAT | ACK | CKN);\n            if (auto *ptr = dynamic_cast<Data *>(head->deserialize(i)))\n            {\n                datRet += ptr->getChunk();\n                delete ptr;\n            }\n            i++;\n        }\n    }\n\n    EXPECT_TRUE(datExample == datRet);\n}\n\n\nTEST(ProtocolTest, encodeERR)\n{\n    string msgExample = move(generateRandomString(260));\n\n    auto err = new Error;\n    err->setMsg(msgExample);\n\n    auto enc = encode(err, ACK);\n    EXPECT_EQ(enc.size(), 3);\n\n    string msgRet;\n    uint16_t i = 0;\n    for (auto &&buffer : enc)\n    {\n        auto head = decode(buffer.first.get());\n        if (head->flags & FIN && head->flags & ACK)\n        {\n            EXPECT_EQ(head->flags, FIN | ACK | CKN);\n            break;\n        }\n        if (head->flags & ERR && head->flags & ACK && head->flags & CKN)\n        {\n            EXPECT_EQ(head->flags, ERR | ACK | CKN);\n            if (auto *ptr = dynamic_cast<Error *>(head->deserialize(i)))\n            {\n                string &&s = ptr->getChunk();\n                msgRet += s;\n                delete ptr;\n            }\n            i++;\n        }\n    }\n\n    delete err;\n\n    EXPECT_TRUE(msgExample == msgRet);\n}\n\n\n\nTEST(ProtocolTest, encodeFIN)\n{\n    auto fin = new Finish;\n\n    auto enc = encode(fin, ACK);\n    EXPECT_EQ(enc.size(), 1);\n\n    auto head = decode(enc[0].first.get());\n    EXPECT_EQ(head->flags, FIN | ACK);\n\n    delete fin;\n}\n\nTEST(ProtocolTest, encodeSTA)\n{\n    auto sta = new Station;\n    sta->setName(\"Name\");\n    sta->setDescription(\"Description\");\n    sta->relayNumber = 1;\n    sta->wateringTime = 10;\n    sta->wateringTimeLeft = 2;\n    sta->weight = 30;\n    sta->status = Status::INSERT;\n    auto encode1 = encode(sta);\n\n    auto enc = encode(sta, ACK);\n\n    delete sta;\n\n    EXPECT_EQ(enc.size(), 1);\n\n    auto head = decode(enc[0].first.get());\n    EXPECT_EQ(head->flags, STA | ACK);\n\n    if (auto *ptr = dynamic_cast<Station *>(head->deserialize()))\n    {\n\n        EXPECT_TRUE(ptr->getName() == string(\"Name\"));\n        EXPECT_TRUE(ptr->getDescription() == string(\"Description\"));\n        EXPECT_EQ(ptr->relayNumber, 1);\n        EXPECT_EQ(ptr->wateringTime, 10);\n        EXPECT_EQ(ptr->wateringTimeLeft, 2);\n        EXPECT_EQ(ptr->weight, 30);\n        EXPECT_EQ(ptr->status, Status::UNACTIVE);\n        delete ptr;\n    }\n\n}\n\n\nTEST(ProtocolTest, encodeSYN)\n{\n    auto syn = new Synchro;\n    syn->setSerial(\"serial123456789\");\n\n    auto enc = encode(syn, ACK);\n    EXPECT_EQ(enc.size(), 1);\n\n    auto head = decode(enc[0].first.get());\n    EXPECT_EQ(head->flags, SYN | ACK);\n\n    if (auto *ptr = dynamic_cast<Synchro *>(head->deserialize()))\n    {\n        EXPECT_TRUE(ptr->getSerial() == \"serial123456789\");\n        delete ptr;\n    }\n\n    delete syn;\n}\n\nTEST(ProtocolTest, encodeChangePackageId)\n{\n    auto syn = new Synchro;\n\n    string &&random = generateRandomString(128);\n\n    syn->setSerial(random);\n\n    auto enc = encode(syn, ACK);\n    EXPECT_EQ(enc.size(), 1);\n\n    updateIdToBufferEncoded(enc[0], 37);\n\n    auto head = decode(enc[0].first.get());\n    EXPECT_EQ(head->flags, SYN | ACK);\n\n    EXPECT_EQ(head->id, 37);\n\n    if (auto *ptr = dynamic_cast<Synchro *>(head->deserialize()))\n    {\n        EXPECT_TRUE(ptr->getSerial() == random);\n        delete ptr;\n    }\n\n    delete syn;\n}\n\nTEST(ProtocolTest, endCommunication)\n{\n    auto fin = new Finish;\n    auto encFin = encode(fin, ACK);\n    auto headFin = decode(encFin[0].first.get());\n    ASSERT_TRUE(::endCommunication(headFin));\n\n    auto err = new Error;\n    err->setMsg(generateRandomString(260));\n    auto encErr = encode(err, ACK);\n    auto headErr = decode(encErr[0].first.get());\n    ASSERT_FALSE(::endCommunication(headErr));\n    headErr = decode(encErr[1].first.get());\n    ASSERT_FALSE(::endCommunication(headErr));\n    headErr = decode(encErr[2].first.get());\n    ASSERT_TRUE(::endCommunication(headErr));\n\n    delete fin;\n    delete err;\n}\n\nTEST(ProtocolTest, composeDecodedChunks)\n{\n    auto sta = new Station;\n    sta->setName(\"Name\");\n    sta->setDescription(\"Description\");\n    sta->relayNumber = 1;\n    sta->wateringTime = 10;\n    sta->wateringTimeLeft = 2;\n    sta->weight = 30;\n    sta->status = Status::INSERT;\n    auto encSta = encode(sta, ACK);\n    auto headSta = decode(encSta[0].first.get());\n    auto pkgSta = composeDecodedChunks({headSta});\n\n    if (shared_ptr<Station> ptr = std::dynamic_pointer_cast<Station>( composeDecodedChunks({headSta}).second ))\n    {\n        EXPECT_TRUE(ptr->getName() == string(\"Name\"));\n        EXPECT_TRUE(ptr->getDescription() == string(\"Description\"));\n        EXPECT_EQ(ptr->relayNumber, 1);\n        EXPECT_EQ(ptr->wateringTime, 10);\n        EXPECT_EQ(ptr->wateringTimeLeft, 2);\n        EXPECT_EQ(ptr->weight, 30);\n        EXPECT_EQ(ptr->status, Status::UNACTIVE);\n    }\n\n    {\n        auto data = new Data;\n        auto &&payload = generateRandomString(260);\n        data->setPayload(payload);\n        auto encDat = encode(data, ACK);\n\n        Heads heads;\n        heads.push_back(move(decode(encDat[0].first.get())));\n        heads.push_back(move(decode(encDat[1].first.get())));\n        heads.push_back(move(decode(encDat[2].first.get())));\n\n        auto &&[flags, pkg] = composeDecodedChunks(heads);\n        if (shared_ptr<Data> ptr = std::dynamic_pointer_cast<Data>(pkg ))\n        {\n            EXPECT_TRUE(ptr->getPayload() == payload);\n        }\n        delete data;\n    }\n\n    {\n        auto err = new Error;\n        auto &&msg = generateRandomString(260);\n        err->setMsg(msg);\n        auto encErr = encode(err, ACK);\n\n        Heads heads;\n        heads.push_back(move(decode(encErr[0].first.get())));\n        heads.push_back(move(decode(encErr[1].first.get())));\n        heads.push_back(move(decode(encErr[2].first.get())));\n\n\n        auto &&[flags, pkg] = composeDecodedChunks(heads);\n        if (shared_ptr<Error> ptr = std::dynamic_pointer_cast<Error>( pkg ))\n        {\n            EXPECT_TRUE(ptr->getMsg() == msg);\n        }\n        delete err;\n    }\n\n    {\n        auto err = new Error;\n        auto &&msg = generateRandomString(100);\n        err->setMsg(msg);\n        auto encErr = encode(err, ACK);\n\n        Heads heads;\n        heads.push_back(move(decode(encErr[0].first.get())));\n\n        auto &&[flags, pkg] = composeDecodedChunks(heads);\n        if (shared_ptr<Error> ptr = std::dynamic_pointer_cast<Error>( pkg ))\n        {\n            EXPECT_TRUE(ptr->getMsg() == msg);\n        }\n        delete err;\n    }\n\n    delete sta;\n\n}\n\nTEST(ProtocolTest, generateRandomIntegral)\n{\n    auto i = generateRandomIntegral<uint8_t>();\n\n    auto h = make_shared<Head>(Head());\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wwritable-strings\"\n    char *payload = \"mario e luigi\";\n#pragma clang diagnostic pop\n    h->length = strlen(payload);\n    h->payload = new uint8_t [h->length];\n    memcpy(h->payload, payload,h->length);\n\n\n    EXPECT_TRUE(h->getHexPayload() == stringHexToString(h->payload, h->length));\n\n}","avg_line_length":27.9246753247,"max_line_length":403,"alphanum_fraction":0.6246860757,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11595,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"#include \"tarch\/parallel\/Node.h\"\n#include \"tarch\/Assertions.h\"\n#include \"tarch\/services\/ServiceRepository.h\"\n\n#include <sstream>\n#include <cstdlib>\n\n#include \"tarch\/compiler\/CompilerSpecificSettings.h\"\n#include \"tarch\/multicore\/MulticoreDefinitions.h\"\n\n\/**\n * For the machine name. If it doesn't work, switch it off in the file\n * CompilerSpecificSettings.h.\n *\/\n#ifdef CompilerHasUTSName\n#include <sys\/utsname.h>\n#endif\n\n\ntarch::logging::Log tarch::parallel::Node::_log(\"tarch::parallel::Node\");\n\n\nbool tarch::parallel::Node::_initIsCalled = false;\n\nnamespace {\n  int tagCounter = 0;\n}\n\n\nvoid tarch::parallel::Node::releaseTag(int tag) {\n  if (tag==tagCounter-1) {\n    tagCounter--;\n  }\n}\n\n\nint tarch::parallel::Node::reserveFreeTag(const std::string& fullQualifiedMessageName) {\n  tagCounter++;\n\n  \/\/ I protect the tag manually (not via log filter), as many tags are actually\n  \/\/ grabbed before most applications initialise their log filters properly.\n  \/\/\n  \/\/ We may not use isGlobalMaster() as this query checks whether the code is\n  \/\/ properly initialised. Please note rank is -1 as long as MPI is not properly\n  \/\/ initialised, i.e. any tag booking prior to the MPI initialisation is not\n  \/\/ logged properly.\n  if ( getInstance()._rank==getGlobalMasterRank() ) {\n    tarch::logging::Log _log(\"tarch::parallel::Node<static>\");\n    logInfo(\n      \"reserveFreeTag()\",\n      \"assigned message \" << fullQualifiedMessageName\n       << \" the free tag \" << tagCounter-1\n    );\n  }\n\n  return tagCounter-1;\n}\n\n\nbool tarch::parallel::Node::isInitialised() const {\n  return _initIsCalled;\n}\n\n\nvoid tarch::parallel::Node::ensureThatMessageQueuesAreEmpty( int fromRank, int tag ) {\n  #ifdef Parallel\n  int          flag;\n  MPI_Iprobe(fromRank, tag, _communicator, &flag, MPI_STATUS_IGNORE);\n  if (flag!=0) {\n    plotMessageQueues();\n  }\n  assertion3( flag==0, fromRank, tag, getRank() );\n  #endif\n}\n\n\nvoid tarch::parallel::Node::plotMessageQueues() {\n  #ifdef Parallel\n  int          flag;\n  MPI_Status   status;\n  MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, _communicator, &flag, &status);\n  if (flag==0) {\n    _log.error(\"plotMessageQueues()\", \"there are no messages from any sender in MPI queue\");\n  }\n  else {\n    logError(\n      \"plotMessageQueues()\",\n      \"there is still a message in queue \"\n      \" from rank \" << status.MPI_SOURCE <<\n      \" with tag \" << status.MPI_TAG\n    );\n  }\n  #endif\n}\n\n\nvoid tarch::parallel::Node::triggerDeadlockTimeOut(\n  const std::string&  className,\n  const std::string&  methodName,\n  int                 communicationPartnerRank,\n  int                 tag,\n  int                 numberOfExpectedMessages,\n  const std::string&  comment\n) {\n  std::ostringstream out;\n  out << \"operation \" << className << \"::\" << methodName << \" on node \"\n      << getRank() << \" had to wait more than \" << _deadlockTimeOut\n      << \" seconds for \" << numberOfExpectedMessages\n      << \" message(s) from node \" << communicationPartnerRank << \" with tag \" << tag\n      << \". Timeout. \" << comment;\n  _log.error( \"triggerDeadlockTimeOut(...)\", out.str() );\n\n  plotMessageQueues();\n\n  exit(DEADLOCK_EXIT_CODE);\n}\n\n\nvoid tarch::parallel::Node::writeTimeOutWarning(\n  const std::string&  className,\n  const std::string&  methodName,\n  int                 communicationPartnerRank,\n  int                 tag,\n  int                 numberOfExpectedMessages\n) {\n  std::ostringstream out;\n  out << \"operation \" << className << \"::\" << methodName << \" on node \"\n      << getRank() << \" had to wait more than \" << _timeOutWarning\n      << \" seconds for \" << numberOfExpectedMessages\n      << \" message(s) from node \" << communicationPartnerRank << \" with tag \" << tag << \". Application \"\n      << \"will terminate after \" << _deadlockTimeOut << \" seconds because \"\n      << \"of a deadlock\";\n  _log.warning( \"writeTimeOutWarning(...)\", out.str() );\n}\n\n\nclock_t tarch::parallel::Node::getDeadlockWarningTimeStamp() const {\n  clock_t result = clock() + _timeOutWarning * CLOCKS_PER_SEC;\n  assertion4( result>=0, result, clock(), _timeOutWarning, CLOCKS_PER_SEC);\n\n  return result;\n}\n\n\nclock_t tarch::parallel::Node::getDeadlockTimeOutTimeStamp() const {\n  clock_t result = clock() + _deadlockTimeOut * CLOCKS_PER_SEC;\n  assertion4( result>=0, result, clock(), _timeOutWarning, CLOCKS_PER_SEC);\n\n  return result;\n}\n\n\nbool tarch::parallel::Node::isTimeOutDeadlockEnabled() const {\n  return _areTimeoutsEnabled and _deadlockTimeOut > 0;\n}\n\n\nbool tarch::parallel::Node::isTimeOutWarningEnabled() const {\n  return _areTimeoutsEnabled and _timeOutWarning > 0;\n}\n\n\nvoid tarch::parallel::Node::suspendTimeouts( bool timeoutsDisabled ) {\n  _areTimeoutsEnabled = !timeoutsDisabled;\n}\n\n\nstd::string tarch::parallel::MPIReturnValueToString( int result ) {\n  std::ostringstream out;\n\n  #ifdef Parallel\n  int   resultlen;\n  char* string = new char[MPI_MAX_ERROR_STRING];  \/\/ (char *)malloc(MPI_MAX_ERROR_STRING * sizeof(char));\n  MPI_Error_string(result, string, &resultlen);\n\n  int   errorclass;\n  MPI_Error_class(result, &errorclass);\n\n  out << \"mpi error class: \" << errorclass << \"=\"\n      << \", mpi error text: \" << string;\n\n  switch ( errorclass ) {\n    case MPI_SUCCESS:      out << \"MPI_SUCCESS [no error]\"; break;\n    case MPI_ERR_BUFFER:   out << \"MPI_ERR_BUFFER [invalid buffer pointer]\"; break;\n    case MPI_ERR_COUNT:    out << \"MPI_ERR_COUNT [invalid count argument]\"; break;\n    case MPI_ERR_TYPE:     out << \"MPI_ERR_TYPE [invalid datatype]\"; break;\n    case MPI_ERR_TAG:      out << \"MPI_ERR_TAG [invalid tag]\"; break;\n    case MPI_ERR_COMM:     out << \"MPI_ERR_COMM [invalid communicator]\"; break;\n    case MPI_ERR_RANK:     out << \"MPI_ERR_RANK [invalid rank]\"; break;\n    case MPI_ERR_REQUEST:  out << \"MPI_ERR_REQUEST [invalid request handle]\"; break;\n    case MPI_ERR_ROOT:     out << \"MPI_ERR_ROOT [invalid root argument]\"; break;\n    case MPI_ERR_GROUP:    out << \"MPI_ERR_GROUP [invalid group]\"; break;\n    case MPI_ERR_OP:       out << \"MPI_ERR_OP [invalid operation]\"; break;\n    case MPI_ERR_TOPOLOGY: out << \"MPI_ERR_TOPOLOGY [invalid topology]\"; break;\n    case MPI_ERR_DIMS:     out << \"MPI_ERR_DIMS [invalid dimensions]\"; break;\n    case MPI_ERR_ARG:      out << \"MPI_ERR_ARG [invalid argument]\"; break;\n    case MPI_ERR_UNKNOWN:  out << \"MPI_ERR_UNKNOWN [unknown error]\"; break;\n    case MPI_ERR_TRUNCATE: out << \"MPI_ERR_TRUNCATE [message has been truncated by receiver]\"; break;\n    case MPI_ERR_OTHER:    out << \"MPI_ERR_OTHER [other unknown error]\"; break;\n    case MPI_ERR_INTERN:   out << \"MPI_ERR_INTERN [internal mpi error]\"; break;\n    default: out << \"unknown\"; break;\n  }\n\n  delete[] string;\n  #else\n  out << \"compiled without -DParallel\";\n  #endif\n\n  return out.str();\n}\n\n\nstd::string tarch::parallel::MPIStatusToString( const MPI_Status& status ) {\n  std::ostringstream out;\n  #ifdef Parallel\n  out << \"status flag:\"\n      << \" MPI_ERROR=\" << status.MPI_ERROR\n      << \" (\" << MPIReturnValueToString(status.MPI_ERROR)\n      << \") ,MPI_SOURCE=\" << status.MPI_SOURCE\n      << \",MPI_TAG=\" << status.MPI_TAG;\n  #else\n  out << \"compiled without -DParallel\";\n  #endif\n  return out.str();\n}\n\n\n#ifdef Parallel\ntarch::parallel::Node::Node():\n  _rank(-1),\n  _numberOfProcessors(-1),\n  _communicator( MPI_COMM_WORLD),\n  _timeOutWarning(0),\n  _deadlockTimeOut(0),\n  _areTimeoutsEnabled(true) {\n}\n#else\ntarch::parallel::Node::Node():\n  _rank(0),\n  _numberOfProcessors(1),\n  _communicator(-1),\n  _timeOutWarning(0),\n  _deadlockTimeOut(0),\n  _areTimeoutsEnabled(true) {\n}\n#endif\n\n\n#ifdef Parallel\ntarch::parallel::Node::Node(const parallel::Node& node):\n  _rank(-1),\n  _numberOfProcessors(-1),\n  _communicator( MPI_COMM_WORLD) {\n}\n#else\ntarch::parallel::Node::Node(const parallel::Node& node):\n  _rank(0),\n  _numberOfProcessors(-1),\n  _communicator(-1) {\n}\n#endif\n\n\ntarch::parallel::Node::~Node() {\n}\n\n\nvoid tarch::parallel::Node::shutdown() {\n  #ifdef Parallel\n  assertion( _rank!=-1 );\n\n  MPI_Barrier( _communicator );\n  MPI_Finalize();\n  _communicator = MPI_COMM_WORLD;\n  #endif\n\n  _rank         = -1;\n}\n\n\nint tarch::parallel::Node::getGlobalMasterRank() {\n  return 0;\n}\n\n\nbool tarch::parallel::Node::isGlobalMaster() const {\n  #ifdef Parallel\n  assertion(_initIsCalled);\n  return getRank() == getGlobalMasterRank();\n  #else\n  return true;\n  #endif\n}\n\n\nvoid tarch::parallel::Node::logStatus() const {\n  std::ostringstream statusMessage;\n  statusMessage << \"MPI status:\";\n\n  #ifdef CompilerHasUTSName\n  utsname* utsdata = new utsname();\n  assertion( utsdata!=NULL );\n  uname(utsdata);\n  statusMessage << \" nodename=\" << utsdata->nodename;\n  delete utsdata;\n  #else\n  statusMessage << \" nodename=undef\";\n  #endif\n\n  statusMessage << \", rank=\" << _rank;\n  statusMessage << \", communicator=\" << _communicator;\n  statusMessage << \", #processors=\" << _numberOfProcessors;\n\n  _log.info( \"logStatus()\", statusMessage.str() );\n}\n\n\nbool tarch::parallel::Node::init(int* argc, char*** argv) {\n  #ifdef Parallel\n  int result = MPI_SUCCESS;\n\n  #if defined( SharedMemoryParallelisation ) && defined( MultipleThreadsMayTriggerMPICalls )\n\n  int initThreadProvidedThreadLevelSupport;\n  result = MPI_Init_thread( argc, argv, MPI_THREAD_MULTIPLE, &initThreadProvidedThreadLevelSupport );\n  if (initThreadProvidedThreadLevelSupport!=MPI_THREAD_MULTIPLE ) {\n    std::cerr << \"warning: MPI implementation does not support MPI_THREAD_MULTIPLE. Support multithreading level is \"\n              << initThreadProvidedThreadLevelSupport << \" instead of \" << MPI_THREAD_MULTIPLE\n              << \". Disable MultipleThreadsMayTriggerMPICalls in the compiler-specific settings or via -DnoMultipleThreadsMayTriggerMPICalls.\"<< std::endl;\n    exit(-1);\n  }\n  #else\n  result = MPI_Init( argc, argv );\n  #endif\n\n  if (result!=MPI_SUCCESS) {\n    std::cerr << \"init(int*,char***)\\t initialisation failed: \" + MPIReturnValueToString(result) + \" (no logging available yet)\";\n    return false;\n  }\n\n  result = MPI_Comm_size( MPI_COMM_WORLD, &_numberOfProcessors );\n  if (result!=MPI_SUCCESS) {\n    std::cerr << \"init(int*,char***)\\t initialisation failed: \" + MPIReturnValueToString(result) + \" (no logging available yet)\";\n    return false;\n  }\n\n  result = MPI_Comm_rank( MPI_COMM_WORLD, &_rank );\n  if (result!=MPI_SUCCESS) {\n    std::cerr << \"init(int*,char***)\\t initialisation failed: \" + MPIReturnValueToString(result) + \" (no logging available yet)\";\n    return false;\n  }\n\n  #endif\n\n  _initIsCalled = true;\n  return true;\n}\n\n\nint tarch::parallel::Node::getRank() const {\n  #ifdef Parallel\n  assertion(_initIsCalled);\n  #endif\n  return _rank;\n}\n\n\ntarch::parallel::Node& tarch::parallel::Node::getInstance() {\n  static Node singleton;\n  return singleton;\n}\n\n\nMPI_Comm tarch::parallel::Node::getCommunicator() const {\n  assertion(_initIsCalled);\n  return _communicator;\n}\n\n\nint tarch::parallel::Node::getNumberOfNodes() const {\n  #ifdef Parallel\n  assertion(_initIsCalled);\n  #endif\n  return _numberOfProcessors;\n}\n\n\nvoid tarch::parallel::Node::setTimeOutWarning( const clock_t & value ) {\n  assertion( value>=0 );\n  _timeOutWarning = value;\n}\n\n\nvoid tarch::parallel::Node::setDeadlockTimeOut( const clock_t & value ) {\n  assertion( value>=0 );\n  _deadlockTimeOut = value;\n}\n\n\nvoid tarch::parallel::Node::setCommunicator( MPI_Comm communicator ) {\n  _communicator = communicator;\n}\n\n\nvoid tarch::parallel::Node::receiveDanglingMessages() {\n\/*\n  #ifdef Parallel\n  int          flag;\n  MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, _communicator, &flag, MPI_STATUS_IGNORE);\n  if (flag) {\n  #endif\n*\/\n  tarch::services::ServiceRepository::getInstance().receiveDanglingMessages();\n\/*\n  #ifdef Parallel\n  }\n  #endif\n*\/\n}\n","avg_line_length":27.6071428571,"max_line_length":155,"alphanum_fraction":0.6818456231,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4851,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":9.0,"content":"\/\/ Copyright (c) 2015-2022 Vector 35 Inc\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\n#include \"binaryninjaapi.h\"\n\nusing namespace BinaryNinja;\nusing namespace std;\n\n\nnamespace BinaryNinja {\n\tstruct UpdateProgress\n\t{\n\t\tfunction<bool(uint64_t progress, uint64_t total)> func;\n\n\t\tstatic bool UpdateCallback(void* ctxt, uint64_t progress, uint64_t total)\n\t\t{\n\t\t\tUpdateProgress* self = (UpdateProgress*)ctxt;\n\t\t\treturn self->func(progress, total);\n\t\t}\n\t};\n}  \/\/ namespace BinaryNinja\n\n\nvector<UpdateChannel> UpdateChannel::GetList()\n{\n\tsize_t count;\n\tchar* errors;\n\tBNUpdateChannel* channels = BNGetUpdateChannels(&count, &errors);\n\n\tif (errors)\n\t{\n\t\tstring errorStr = errors;\n\t\tBNFreeString(errors);\n\t\tthrow UpdateException(errorStr);\n\t}\n\n\tvector<UpdateChannel> result;\n\tresult.reserve(count);\n\tfor (size_t i = 0; i < count; i++)\n\t{\n\t\tUpdateChannel channel;\n\t\tchannel.name = channels[i].name;\n\t\tchannel.description = channels[i].description;\n\t\tchannel.latestVersion = channels[i].latestVersion;\n\t\tresult.push_back(channel);\n\t}\n\n\tBNFreeUpdateChannelList(channels, count);\n\treturn result;\n}\n\n\nbool UpdateChannel::AreUpdatesAvailable(uint64_t* expireTime, uint64_t* serverTime)\n{\n\tchar* errors;\n\tbool result = BNAreUpdatesAvailable(name.c_str(), expireTime, serverTime, &errors);\n\n\tif (errors)\n\t{\n\t\tstring errorStr = errors;\n\t\tBNFreeString(errors);\n\t\tthrow UpdateException(errorStr);\n\t}\n\n\treturn result;\n}\n\n\nBNUpdateResult UpdateChannel::UpdateToVersion(const string& version)\n{\n\treturn UpdateToVersion(version, [](uint64_t, uint64_t) { return true; });\n}\n\n\nBNUpdateResult UpdateChannel::UpdateToVersion(\n    const string& version, const function<bool(uint64_t progress, uint64_t total)>& progress)\n{\n\tUpdateProgress up;\n\tup.func = progress;\n\n\tchar* errors;\n\tBNUpdateResult result =\n\t    BNUpdateToVersion(name.c_str(), version.c_str(), &errors, UpdateProgress::UpdateCallback, &up);\n\n\tif (errors)\n\t{\n\t\tstring errorStr = errors;\n\t\tBNFreeString(errors);\n\t\tthrow UpdateException(errorStr);\n\t}\n\n\treturn result;\n}\n\n\nBNUpdateResult UpdateChannel::UpdateToLatestVersion()\n{\n\treturn UpdateToLatestVersion([](uint64_t, uint64_t) { return true; });\n}\n\n\nBNUpdateResult UpdateChannel::UpdateToLatestVersion(const function<bool(uint64_t progress, uint64_t total)>& progress)\n{\n\tUpdateProgress up;\n\tup.func = progress;\n\n\tchar* errors;\n\tBNUpdateResult result = BNUpdateToLatestVersion(name.c_str(), &errors, UpdateProgress::UpdateCallback, &up);\n\n\tif (errors)\n\t{\n\t\tstring errorStr = errors;\n\t\tBNFreeString(errors);\n\t\tthrow UpdateException(errorStr);\n\t}\n\n\treturn result;\n}\n\n\nvector<UpdateVersion> UpdateVersion::GetChannelVersions(const string& channel)\n{\n\tsize_t count;\n\tchar* errors;\n\tBNUpdateVersion* versions = BNGetUpdateChannelVersions(channel.c_str(), &count, &errors);\n\n\tif (errors)\n\t{\n\t\tstring errorStr = errors;\n\t\tBNFreeString(errors);\n\t\tthrow UpdateException(errorStr);\n\t}\n\n\tvector<UpdateVersion> result;\n\tresult.reserve(count);\n\tfor (size_t i = 0; i < count; i++)\n\t{\n\t\tUpdateVersion version;\n\t\tversion.version = versions[i].version;\n\t\tversion.notes = versions[i].notes;\n\t\tversion.time = (time_t)versions[i].time;\n\t\tresult.push_back(version);\n\t}\n\n\tBNFreeUpdateChannelVersionList(versions, count);\n\treturn result;\n}\n\n\nbool BinaryNinja::AreAutoUpdatesEnabled()\n{\n\treturn BNAreAutoUpdatesEnabled();\n}\n\n\nvoid BinaryNinja::SetAutoUpdatesEnabled(bool enabled)\n{\n\tBNSetAutoUpdatesEnabled(enabled);\n}\n\n\nuint64_t BinaryNinja::GetTimeSinceLastUpdateCheck()\n{\n\treturn BNGetTimeSinceLastUpdateCheck();\n}\n\n\nvoid BinaryNinja::UpdatesChecked()\n{\n\tBNUpdatesChecked();\n}\n\n\nstring BinaryNinja::GetActiveUpdateChannel()\n{\n\tchar* channel = BNGetActiveUpdateChannel();\n\tstring result = channel;\n\tBNFreeString(channel);\n\treturn result;\n}\n\n\nvoid BinaryNinja::SetActiveUpdateChannel(const string& channel)\n{\n\tBNSetActiveUpdateChannel(channel.c_str());\n}\n","avg_line_length":23.7794117647,"max_line_length":118,"alphanum_fraction":0.7526283241,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7789,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <vector>\r\n#include <string>\r\n#include <nlohmann\/json.hpp>\r\n#include <Vendor\/imgui\/imgui.h>\r\n#include <Vendor\/imgui\/imgui_stdlib.h>\r\n#include <Vendor\/imgui\/imgui_internal.h>\r\n#include <LilEngie.h>\r\n#include <Core\/System\/ISerializable.h>\r\n#include <Core\/Entity\/ComponentFactory.h>\r\n#include \"..\/ImGuiStyle.h\"\r\n#include \"IEditorWindow.h\"\r\n#include \"LilTreeWindow.h\"\r\n#include \"PropertiesWindow.h\"\r\n\r\nnamespace LilEddie\r\n{\r\n\tvoid PropertiesWindow::Init()\r\n\t{\r\n\t\tscnMgr = &game->sceneManager;\r\n\t}\r\n\r\n\tvoid PropertiesWindow::OnDraw()\r\n\t{\r\n\t\tActor* sa = scnMgr->scene->GetActor(treeWindow->selected);\r\n\r\n\t\tif (sa)\r\n\t\t{\r\n\t\t\t\/\/Name and uid\r\n\t\t\tImGui::InputText(\"Name\", &sa->name);\r\n\t\t\tImGui::InputText(\"uid\", &sa->uid);\r\n\t\t\tImGui::Dummy(ImVec2(0, 20));\r\n\r\n\t\t\t\/\/Add component button\r\n\t\t\tfloat width = ImGui::GetWindowWidth();\r\n\t\t\tif (ImGui::Button(\"New Component\", ImVec2(width - 20, 25)))\r\n\t\t\t\tImGui::OpenPopup(\"New Component\");\r\n\r\n\t\t\tif (ImGui::BeginPopup(\"New Component\"))\r\n\t\t\t{\r\n\t\t\t\tfor (int i = 0; i < ComponentFactory::core->componentNames.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (ImGui::Button(ComponentFactory::core->componentNames[i].c_str()))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/Add the component if not already existing\r\n\t\t\t\t\t\tstd::string componentType = ComponentFactory::core->componentNames[i];\r\n\t\t\t\t\t\tif (!sa->ContainsComponent(componentType))\r\n\t\t\t\t\t\t\tIComponent* comp = ComponentFactory::core->CreateComponent(sa, componentType.c_str());\r\n\r\n\t\t\t\t\t\tImGui::CloseCurrentPopup();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tImGui::EndPopup();\r\n\t\t\t}\r\n\r\n\t\t\t\/\/Component properties\r\n\t\t\t\/\/Get json data\r\n\t\t\tjson j;\r\n\t\t\tsa->Serialize(j);\r\n\r\n\t\t\t\/\/Present each individual component\r\n\t\t\tfor (int i = 0; i < sa->ComponentsCount(); i++)\r\n\t\t\t{\r\n\t\t\t\tstd::string typeName = sa->GetComponent(i)->TypeName();\r\n\t\t\t\tcurrent = sa->GetComponent(i);\r\n\r\n\t\t\t\t\/\/Kind of a slow solution, iterating components then checking each json comp for match\r\n\t\t\t\tfor (auto& component : j[\"components\"])\r\n\t\t\t\t{\r\n\t\t\t\t\tif (component[\"type\"] == typeName)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tstd::string type = component[\"type\"].get<std::string>();\r\n\r\n\t\t\t\t\t\t\/\/Split draw list to draw out of order foreground first\r\n\t\t\t\t\t\tImDrawList* drawList = ImGui::GetWindowDrawList();\r\n\t\t\t\t\t\tdrawList->ChannelsSplit(2);\r\n\t\t\t\t\t\tdrawList->ChannelsSetCurrent(1);\r\n\r\n\t\t\t\t\t\t\/\/Draw the properties dropdown in a group so that we can find the size\r\n\t\t\t\t\t\tImGui::Dummy(ImVec2(0, 10));\r\n\t\t\t\t\t\tImGui::BeginGroup();\r\n\r\n\t\t\t\t\t\t\/\/Draw the header for the component\r\n\t\t\t\t\t\tImGuiTreeNodeFlags headerFlags = ImGuiTreeNodeFlags_DefaultOpen;\r\n\t\t\t\t\t\theaderFlags |= ImGuiTreeNodeFlags_Framed;\r\n\t\t\t\t\t\theaderFlags |= ImGuiTreeNodeFlags_FramePadding;\r\n\t\t\t\t\t\theaderFlags |= ImGuiTreeNodeFlags_SpanAvailWidth;\r\n\t\t\t\t\t\theaderFlags |= ImGuiTreeNodeFlags_AllowItemOverlap;\r\n\r\n\t\t\t\t\t\tbool componentHeader = ImGui::TreeNodeEx((type + \"##CollapseHeader\").c_str(), headerFlags);\r\n\r\n\t\t\t\t\t\t\/\/Draw the destroy component button\r\n\t\t\t\t\t\tImGui::SameLine(ImGui::GetContentRegionAvail().x);\r\n\t\t\t\t\t\tImGui::Dummy(ImVec2(10, 10));\r\n\t\t\t\t\t\tif (ImGui::CloseButton(ImGui::GetID((\"x##\" + type).c_str()), ImGui::GetItemRectMin()))\r\n\t\t\t\t\t\t\tsa->DestroyComponent(sa->GetComponent(i));\r\n\r\n\t\t\t\t\t\t\/\/Draw actual component properties\r\n\t\t\t\t\t\tif (componentHeader)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tImGui::Indent();\r\n\t\t\t\t\t\t\tfor (json::iterator it = component[\"properties\"].begin(); it != component[\"properties\"].end(); it++)\r\n\t\t\t\t\t\t\t\tDrawProperty(it.key(), it.value());\r\n\t\t\t\t\t\t\tImGui::Unindent();\r\n\t\t\t\t\t\t\tImGui::Dummy(ImVec2(0, 10));\r\n\r\n\t\t\t\t\t\t\tImGui::TreePop();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tImGui::EndGroup();\r\n\r\n\t\t\t\t\t\t\/\/Draw the background after we know the size\r\n\t\t\t\t\t\tdrawList->ChannelsSetCurrent(0);\r\n\r\n\t\t\t\t\t\tImColor color = Gradient(0) * .8;\r\n\t\t\t\t\t\tImVec2 min = ImGui::GetItemRectMin();\r\n\t\t\t\t\t\tImVec2 max = ImGui::GetItemRectMax();\r\n\t\t\t\t\t\tmax.x = min.x + ImGui::GetContentRegionAvailWidth();\r\n\t\t\t\t\t\tdrawList->AddRectFilled(min, max, color, 5);\r\n\r\n\t\t\t\t\t\tdrawList->ChannelsMerge();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid PropertiesWindow::DrawProperty(std::string name, json value)\r\n\t{\r\n\t\tswitch (value.type())\r\n\t\t{\r\n\t\t\tcase json::value_t::null:\r\n\t\t\t\tImGui::TextDisabled((name + \" : NULL TYPE\").c_str());\r\n\t\t\t\tbreak;\r\n\t\t\tcase json::value_t::string:\r\n\t\t\t{\r\n\t\t\t\tstd::string s = value.get<std::string>();\r\n\t\t\t\tif (ImGui::InputText(name.c_str(), &s) && current)\r\n\t\t\t\t\tcurrent->SetProperty(name, s);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase json::value_t::boolean:\r\n\t\t\t{\r\n\t\t\t\tbool b = value.get<bool>();\r\n\t\t\t\tif (ImGui::Checkbox(name.c_str(), &b) && current)\r\n\t\t\t\t\tcurrent->SetProperty(name, b);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase json::value_t::number_integer:\r\n\t\t\t{\r\n\t\t\t\tint i = value.get<int>();\r\n\t\t\t\tif (ImGui::DragInt(name.c_str(), &i) && current)\r\n\t\t\t\t\tcurrent->SetProperty(name, i);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase json::value_t::number_unsigned:\r\n\t\t\t{\r\n\t\t\t\tint i = value.get<int>();\r\n\t\t\t\tif (ImGui::DragInt(name.c_str(), &i) && current)\r\n\t\t\t\t\tcurrent->SetProperty(name, i);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase json::value_t::number_float:\r\n\t\t\t{\r\n\t\t\t\tfloat f = value.get<float>();\r\n\t\t\t\tif (ImGui::DragFloat(name.c_str(), &f) && current)\r\n\t\t\t\t\tcurrent->SetProperty(name, f);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase json::value_t::array:\r\n\t\t\t{\r\n\t\t\t\tDrawArrayProperty(name, value);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase json::value_t::object:\r\n\t\t\tcase json::value_t::discarded:\r\n\t\t\tdefault:\r\n\t\t\t\tImGui::TextDisabled((name + \" : NOT DISPLAYABLE\").c_str());\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid PropertiesWindow::DrawArrayProperty(std::string& name, json arr)\r\n\t{\r\n\t\t\/\/Only draw like this if under 4 elements (TODO temp)\r\n\t\tif (arr.size() > 4)\r\n\t\t{\r\n\t\t\tImGui::TextDisabled((name + \" : NOT DISPLAYABLE\").c_str());\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t\/\/Draw properties (TODO: add other types when im not lazy)\r\n\t\tswitch (arr[0].type())\r\n\t\t{\r\n\t\t\tcase json::value_t::string:\r\n\t\t\t{\r\n\t\t\t\tstd::vector<std::string> vals = arr.get<std::vector<std::string>>();\r\n\r\n\t\t\t\t\/\/Only show for resource id's\r\n\t\t\t\tif (vals.size() != 2 || resourceTypeNames.find(vals[1]) == resourceTypeNames.end())\r\n\t\t\t\t{\r\n\t\t\t\t\tImGui::TextDisabled((name + \" : NOT DISPLAYABLE\").c_str());\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\/\/Make sure string size is large enough\r\n\t\t\t\tvals[0].resize(255);\r\n\r\n\t\t\t\t\/\/Display property\r\n\t\t\t\tImGui::Text(name.c_str());\r\n\r\n\t\t\t\tImGui::Indent();\r\n\t\t\t\tbool mod = false;\r\n\t\t\t\tmod = ImGui::InputText((\"##\" + name).c_str(), &vals[0]);\r\n\t\t\t\t\r\n\t\t\t\t\/\/Display type\r\n\t\t\t\tif (ImGui::BeginCombo((\"Type##\" + name).c_str(), vals[1].c_str()))\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (auto it = resourceTypeNames.begin(); it != resourceTypeNames.end(); it++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tbool isSelected = it->first == vals[1];\r\n\t\t\t\t\t\tif (ImGui::Selectable(it->first.c_str(), isSelected))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tvals[1] = it->first;\r\n\t\t\t\t\t\t\tmod = true;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif (isSelected)\r\n\t\t\t\t\t\t\tImGui::SetItemDefaultFocus();\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tImGui::EndCombo();\r\n\t\t\t\t}\r\n\r\n\t\t\t\tImGui::Unindent();\r\n\r\n\t\t\t\t\/\/Apply if modified\r\n\t\t\t\tif (mod && current)\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/Set if it does\r\n\t\t\t\t\tResourceId rid = ResourceId(vals[0], resourceTypeNames[vals[1]]);\r\n\t\t\t\t\tcurrent->SetProperty(name, rid);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase json::value_t::number_float:\r\n\t\t\t{\r\n\t\t\t\t\/\/Only show for vec3\/vec4\r\n\t\t\t\tif (arr.size() != 3 && arr.size() != 4)\r\n\t\t\t\t{\r\n\t\t\t\t\tImGui::TextDisabled((name + \" : NOT DISPLAYABLE\").c_str());\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tstd::vector<float> vals = arr.get<std::vector<float>>();\r\n\t\t\t\tbool mod = ImGui::DragScalarN(name.c_str(), ImGuiDataType_Float, &vals[0], vals.size(), .1f, 0, 0, \"%.5f\");\r\n\r\n\t\t\t\t\/\/assume vec3\/4, TODO: somehow figure out how to distinguish between vecs and arrays\r\n\t\t\t\tif (mod && current)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (arr.size() == 3)\r\n\t\t\t\t\t\tcurrent->SetProperty(name, vec3(vals[0], vals[1], vals[2]));\r\n\t\t\t\t\telse if (arr.size() == 4)\r\n\t\t\t\t\t\tcurrent->SetProperty(name, vec4(vals[0], vals[1], vals[2], vals[3]));\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tdefault:\r\n\t\t\t\tImGui::TextDisabled((name + \" : NOT DISPLAYABLE\").c_str());\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n","avg_line_length":28.4270072993,"max_line_length":112,"alphanum_fraction":0.5955835152,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":24214,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":3.0,"content":"#include \"maoflightmap.h\"\n\n#include <QMessageBox>\n#include <QNetworkProxy>\n\nextern const char* Head[15];\n\nQString Mao_Flight_DB_Path;\nQString Mao_Flight_HTML_File_Path;\nQString Mao_Flight_HTML_Lookup_Web_Path;\nQString Mao_Flight_HTML_Trace_Web_Path;\n\n#define Mao_Flight_Version \"1.5\"\n\nMaoFlightMap::MaoFlightMap(QWidget *parent)\n: QMainWindow(parent)\n{\n\n\tqRegisterMetaType<MaoUIsignalB>(\"MaoUIsignalB\");\n\tqRegisterMetaType<MaoUIsignalS>(\"MaoUIsignalS\");\n\n\t\/\/canPin = false;\n\tcurrentROW = -1;\n\tchina = QTextCodec::codecForLocale();\n\n\tui.setupUi(this);\n\tui.MaoTabFrame->removeTab(3);\n\n\tconnect(this, &MaoFlightMap::SHUTDOWN, &tFS, &MaoFSthread::SHUTDOWN);\n\tconnect(this, &MaoFlightMap::SHUTDOWN, &tFly, &MaoFlyThread::SHUTDOWN);\n\tconnect(this, &MaoFlightMap::SHUTDOWN, &tLookup, &MaoLookupThread::SHUTDOWN);\n\t\n\tconnect(this, &MaoFlightMap::pathReady, &tFly, &MaoFlyThread::pathReady);\n\tconnect(this, &MaoFlightMap::pathReady, &tLookup, &MaoLookupThread::pathReady);\n\n\tconnect(ui.MaoSOCflightList, &QTableWidget::iconSizeChanged, this, &MaoFlightMap::SocListFocusIn);\n\tconnect(ui.MaoFlightList, &QTableWidget::iconSizeChanged, this, &MaoFlightMap::FlightListFocusIn);\n\tconnect(ui.MaoSOCglobalMap, &QPushButton::clicked, this, &MaoFlightMap::tableShrink);\n\tconnect(ui.MaoGlobalMap, &QPushButton::clicked, this, &MaoFlightMap::tableShrink);\n\tconnect(ui.MaoLocalMap, &QPushButton::clicked, this, &MaoFlightMap::tableShrink);\n\tconnect(ui.MaoFlightMap, &QPushButton::clicked, this, &MaoFlightMap::tableShrink);\n\tconnect(ui.MaoTabFrame, &QTabWidget::currentChanged, this, &MaoFlightMap::tableShrinkTab);\n\n\tconnect(ui.MaoFlightNo, &QLineEdit::textChanged, this, &MaoFlightMap::lowToHigh);\n\tconnect(ui.MaoArrICAO, &QLineEdit::textChanged, this, &MaoFlightMap::lowToHigh);\n\tconnect(ui.MaoSOCusername, &QLineEdit::textChanged, this, &MaoFlightMap::lowToHigh);\n\n\tconnect(ui.MaoSOCglobalMap, &QPushButton::clicked, &tLookup, &MaoLookupThread::getSOCglobalMap);\n\tconnect(ui.MaoGlobalMap, &QPushButton::clicked, &tLookup, &MaoLookupThread::getGlobalMap);\n\tconnect(ui.MaoLocalMap, &QPushButton::clicked, &tLookup, &MaoLookupThread::getLocalMap);\n\tconnect(ui.MaoFlightMap, &QPushButton::clicked, this, &MaoFlightMap::lookupFlightMap);\n\tconnect(this, &MaoFlightMap::sGetFlightMap, &tLookup, &MaoLookupThread::getFlightMap);\n\n\tconnect(ui.MaoSOCupdate, &QPushButton::clicked, this, &MaoFlightMap::clickSOC);\n\tconnect(this, &MaoFlightMap::sGetSOC, &tLookup, &MaoLookupThread::getSOC);\n\n\n\tconnect(ui.MaoStartEndFlight, &QPushButton::clicked, this, &MaoFlightMap::startEndFlight);\n\tconnect(ui.MaoCancelFlight, &QPushButton::clicked, this, &MaoFlightMap::cancelFlight);\n\tconnect(&tLookup, &MaoLookupThread::webShow, this, &MaoFlightMap::lookupWebShow);\n\tconnect(&tLookup, &MaoLookupThread::reportB, this, &MaoFlightMap::showUIb);\n\tconnect(&tLookup, &MaoLookupThread::reportS, this, &MaoFlightMap::showUIs);\n\n\tconnect(&tFS, &MaoFSthread::connectResult, this, &MaoFlightMap::showUIb);\n\tconnect(&tFS, &MaoFSthread::pushFSdata, this, &MaoFlightMap::showUIs);\n\tconnect(&tFly, &MaoFlyThread::recordReport, this, &MaoFlightMap::showUIb);\n\tconnect(&tFly, &MaoFlyThread::pushFSdata, this, &MaoFlightMap::showUIs);\n\tconnect(&tFly, &MaoFlyThread::locTrace, this, &MaoFlightMap::markPin);\n\tconnect(this, &MaoFlightMap::startRecord, &tFly, &MaoFlyThread::recordFlight);\n\n\t\/\/TODO - connect(ui.MaoLookupView, &QWebEngineView::iconChanged, this, &MaoFlightMap::tableShrink);\n\n\tconnect(&update, &QNetworkAccessManager::finished, this, &MaoFlightMap::loadUpdate);\n\n\n\n\tinitDriveCheck();\n\n\tinitFlightListViewUI();\n\n\tinitDatabase();\n\n\tinitThread();\n\n\tinitWeb();\n\n\tenableNetworkProxy();\n\n\tloadFlightList();\n\tloadSocFlightList();\n\n\tthis->setWindowState(Qt::WindowMaximized);\n\n\tcheckUpdate();\n\n\tQTimer * tUpdateDB = new QTimer();\n\tconnect(tUpdateDB, &QTimer::timeout, this, &MaoFlightMap::checkDB);\n\ttUpdateDB->setSingleShot(true);\n\ttUpdateDB->start(1000);\n}\n\nMaoFlightMap::~MaoFlightMap()\n{\n\tif (true == tFS.isRunning()||\n\t\ttrue == tFly.isRunning()||\n\t\ttrue == tLookup.isRunning())\/\/\u4e3a\u4e86\u5347\u7ea7\u6570\u636e\u5e93\u88ab\u62d2\u7edd\u65f6\uff0c\u5b89\u5168\u5730\u5173\u95ed\u7a0b\u5e8f\uff0c\u53ef\u4ee5\u5bfb\u627e\u66f4\u6070\u5f53\u7684\u65b9\u6cd5\n\t\tshutdownThreads();\n\n\tQFile::remove(Mao_Flight_HTML_Lookup_Web_Path.section(\"\", 9));\/\/\u6e05\u7406\u4e34\u65f6\u7f51\u9875\u6587\u4ef6\n\tQFile::remove(Mao_Flight_HTML_Trace_Web_Path.section(\"\", 9));\n\n\tdb.close();\n}\n\nvoid MaoFlightMap::closeEvent(QCloseEvent* e)\n{\n\tshutdownThreads();\n\n\te->accept();\n}\nvoid MaoFlightMap::shutdownThreads()\n{\n\ttFS.setShutdown();\n\ttFly.setShutdown();\n\ttLookup.setShutdown();\n\n\temit SHUTDOWN();\n\n\tui.MaoStatusBar->showMessage(zh(\"\u6b63\u5728\u7ed3\u675f FS \u8fde\u63a5...\"));\n\twhile (true == tFS.isRunning())\n\t\tQApplication::processEvents();\n\n\tui.MaoStatusBar->showMessage(zh(\"\u6b63\u5728\u7ed3\u675f\u98de\u884c\u8bb0\u5f55...\"));\n\twhile (true == tFly.isRunning())\n\t\tQApplication::processEvents();\n\n\tui.MaoStatusBar->showMessage(zh(\"\u6b63\u5728\u7ed3\u675f\u822a\u73ed\u67e5\u627e...\"));\n\twhile (true == tLookup.isRunning())\n\t\tQApplication::processEvents();\n}\n\n\n\/\/ TODO\n\/\/void QWidget::focusInEvent(QFocusEvent *event)\n\/\/{\n\/\/\temit windowTitleChanged(nullptr);\/\/\u5229\u7528\u8fd9\u4e2a\u4fe1\u53f7\u6765\u901a\u77e5 UI\uff0c\u3010TODO - \u6ce8\u610f\u8fd9\u4e2a\u4fe1\u53f7\u4f1a\u4e0d\u4f1a\u88ab\u6b63\u5e38\u7f51\u9875\u53d1\u51fa\uff01\u3011\n\/\/}\nvoid QAbstractItemView::focusInEvent(QFocusEvent * event)\n{\n\temit iconSizeChanged(QSize(Mao_Flight_TableWidget_Width_Expend, 0));\/\/\u5229\u7528\u8fd9\u4e2a\u4fe1\u53f7\u6765\u901a\u77e5 UI\n}\nvoid QAbstractItemView::focusOutEvent(QFocusEvent * event) \/\/\u4e3a\u4e86\u5237\u65b0\u5f53\u524d\u884c\u53f7\n{\n\temit iconSizeChanged(QSize(0, 0));\/\/\u5229\u7528\u8fd9\u4e2a\u4fe1\u53f7\u6765\u901a\u77e5 UI\n}\nvoid MaoFlightMap::FlightListFocusIn(const QSize & newWidth)\n{\n\tif (Mao_Flight_TableWidget_Width_Expend == newWidth.width())\n\t{\n\t\tui.MaoTabFrame->setMinimumWidth(newWidth.width());\n\t\tui.MaoTabFrame->setMaximumWidth(newWidth.width());\n\t}\n\tcurrentROW = ui.MaoFlightList->currentRow();\n}\nvoid MaoFlightMap::SocListFocusIn(const QSize & newWidth)\n{\n\tif (Mao_Flight_TableWidget_Width_Expend == newWidth.width())\/\/is Mao_Flight_TableWidget_Width_Expend\n\t{\n\t\tui.MaoTabFrame->setMinimumWidth(Mao_Flight_TableWidget_Width_Expend_SOC);\n\t\tui.MaoTabFrame->setMaximumWidth(Mao_Flight_TableWidget_Width_Expend_SOC);\n\t}\n}\nvoid MaoFlightMap::tableShrink()\n{\n\tui.MaoTabFrame->setMinimumWidth(Mao_Flight_TableWidget_Width_Shrink);\n\tui.MaoTabFrame->setMaximumWidth(Mao_Flight_TableWidget_Width_Shrink);\n}\nvoid MaoFlightMap::tableShrinkTab(int index)\n{\n\tswitch (index)\n\t{\n\tcase 0:\n\t\tui.MaoTabFrame->setMinimumWidth(Mao_Flight_TableWidget_Width_Shrink);\n\t\tui.MaoTabFrame->setMaximumWidth(Mao_Flight_TableWidget_Width_Shrink);\n\t\tui.MaoLookupView->hide();\n\t\tui.MaoTraceView->show();\n\t\tbreak;\n\tcase 1:\n\t\tui.MaoTabFrame->setMinimumWidth(Mao_Flight_TableWidget_Width_Expend);\n\t\tui.MaoTabFrame->setMaximumWidth(Mao_Flight_TableWidget_Width_Expend);\n\t\tui.MaoTraceView->hide();\n\t\tui.MaoLookupView->show();\n\t\tbreak;\n\tcase 2:\n\t\tui.MaoTabFrame->setMinimumWidth(Mao_Flight_TableWidget_Width_Expend_SOC);\n\t\tui.MaoTabFrame->setMaximumWidth(Mao_Flight_TableWidget_Width_Expend_SOC);\n\t\tui.MaoTraceView->hide();\n\t\tui.MaoLookupView->show();\n\t\tbreak;\n\t}\n}\n\n\n\nvoid MaoFlightMap::checkDB()\n{\n\tQSqlQuery dbQuery(db);\n\tdbQuery.exec(\"SELECT StartLat FROM FlightList\");\n\t\n\tif (true == dbQuery.next())\/\/\u6709StartLat\u7b49\u5217\uff0c\u5f53\u524d\u662f\u8001\u6570\u636e\u5e93\uff0c\u9700\u8981\u66f4\u65b0\n\t{\n\t\tdbQuery.finish();\n\n\t\tQMessageBox::StandardButton canUpdate = QMessageBox::information(this,\n\t\t\tzh(\"\u6570\u636e\u5e93\u5347\u7ea7\"),\n\t\t\tzh(\"\u60a8\u7684\u822a\u73ed\u98de\u884c\u6570\u636e\u5e93\u662f1.0\uff5e1.2\u7248\u672c\u7684\uff0c\u9700\u8981\u5347\u7ea7\u540e\u624d\u80fd\u4f7f\u7528\u3002\\n\\n\") +\n\t\t\tzh(\"\u662f\u5426\u73b0\u5728\u5e2e\u60a8\u5347\u7ea7\uff1f\uff08\u4f1a\u5e2e\u60a8\u81ea\u52a8\u5907\u4efd\uff09\\n\\n\") +\n\t\t\tzh(\"\u6709\u9700\u8981\u53ef\u8054\u7cfb\u8f6f\u4ef6\u4f5c\u8005\uff1aMaoJianwei2012@126.com\"),\n\t\t\tQMessageBox::Yes | QMessageBox::No,\n\t\t\tQMessageBox::Yes\n\t\t\t);\n\t\tif (QMessageBox::Yes == canUpdate)\n\t\t{\n\t\t\tif (false == updateDB())\n\t\t\t{\n\t\t\t\tQMessageBox::information(this,\n\t\t\t\t\tzh(\"\u5907\u4efd\u5931\u8d25\"),\n\t\t\t\t\tzh(\"\u8bf7\u786e\u8ba4\u60a8\u662f\u5426\u62e5\u6709\u5199\u6587\u4ef6\u7684\u6743\u9650\uff1f\\n\\n\u4e3a\u907f\u514d\u6570\u636e\u4e22\u5931\uff0c\u5347\u7ea7\u5c06\u4e0d\u4f1a\u8fdb\u884c\u3002\"),\n\t\t\t\t\tQMessageBox::Ok);\n\t\t\t\tQApplication::exit(Mao_Flight_DB_Backup_Fail);\n\t\t\t}\n\t\t\telse\n\t\t\t\tQMessageBox::information(this,\n\t\t\t\t\tzh(\"\u6570\u636e\u5e93\u5347\u7ea7\"),\n\t\t\t\t\tzh(\"\u5347\u7ea7\u6210\u529f\uff0cWelcome aboard\uff01\"),\n\t\t\t\t\tQMessageBox::Ok);\n\t\t}\n\t\telse\n\t\t\tQApplication::exit(Mao_Flight_DB_Update_Reject);\n\t}\n\telse\n\t\tdbQuery.finish();\n\n\tdelete ((QTimer*)sender());\n}\nbool MaoFlightMap::updateDB()\n{\n\tif (false == backupDB())\n\t\treturn false;\n\n\t\/\/\u5f00\u59cb\u66f4\u65b0\n\treturn updateDBfromV12();\n}\nbool MaoFlightMap::backupDB()\n{\n\tQString backupFilename = Mao_Flight_DB_Path;\n\tbackupFilename.resize(backupFilename.size() - 3);\n\tbackupFilename += \"_v12_backup.db\";\n\n\tQFile::remove(backupFilename);\n\tif (false == QFile::copy(Mao_Flight_DB_Path, backupFilename))\n\t\treturn false;\n\telse\n\t\treturn true;\n}\nbool MaoFlightMap::updateDBfromV12()\n{\n\tQSqlQuery dbOldQuery(db);\n\tdbOldQuery.exec(\"ALTER TABLE FlightList RENAME TO FlightListOld\");\n\tdbOldQuery.exec(\"SELECT \"\n\t\t\"TaskNo,\"\n\t\t\"DepDate,\"\n\t\t\"DepTime,\"\n\t\t\"ArrDate,\"\n\t\t\"ArrTime,\"\n\t\t\"FlightNo,\"\n\t\t\"PlaneModel,\"\n\t\t\"DepICAO,\"\n\t\t\"ArrICAO,\"\n\t\t\"DivArrICAO,\"\n\t\t\"DetailTable\"\n\t\t\" FROM FlightListOld\");\n\n\n\n\tdb.transaction();\n\n\tQSqlQuery dbNewQuery(db);\n\tdbNewQuery.exec(\"CREATE TABLE FlightList (\"\n\t\t\"TaskNo INT primary key not null unique,\"\n\t\t\"DepDate text,\"\n\t\t\"DepTime text,\"\n\t\t\"ArrDate text,\"\n\t\t\"ArrTime text,\"\n\t\t\"FlightNo text,\"\n\t\t\"PlaneModel text,\"\n\t\t\"DepICAO text,\"\n\t\t\"ArrICAO text,\"\n\t\t\"DivArrICAO text,\"\n\t\t\"DetailTable text\"\n\t\t\")\");\n\n\tQString query = \"INSERT INTO FlightList VALUES (\"\n\t\t\"%1,\"\n\t\t\"\\\"%2\\\",\"\n\t\t\"\\\"%3\\\",\"\n\t\t\"\\\"%4\\\",\"\n\t\t\"\\\"%5\\\",\"\n\t\t\"\\\"%6\\\",\"\n\t\t\"\\\"%7\\\",\"\n\t\t\"\\\"%8\\\",\"\n\t\t\"\\\"%9\\\",\"\n\t\t\"\\\"%10\\\",\"\n\t\t\"\\\"%11\\\"\"\n\t\t\")\";\n\n\t\n\twhile (true == dbOldQuery.next())\n\t{\n\t\tdbNewQuery.exec(\n\t\t\tquery.arg(dbOldQuery.value(0).toInt())\n\t\t\t.arg(dbOldQuery.value(1).toString())\n\t\t\t.arg(dbOldQuery.value(2).toString())\n\t\t\t.arg(dbOldQuery.value(3).toString())\n\t\t\t.arg(dbOldQuery.value(4).toString())\n\t\t\t.arg(dbOldQuery.value(5).toString())\n\t\t\t.arg(dbOldQuery.value(6).toString())\n\t\t\t.arg(dbOldQuery.value(7).toString())\n\t\t\t.arg(dbOldQuery.value(8).toString())\n\t\t\t.arg(dbOldQuery.value(9).toString())\n\t\t\t.arg(dbOldQuery.value(10).toString())\n\t\t\t);\n\n\t}\n\n\tdbOldQuery.exec(\"DROP TABLE FlightListOld\");\n\n\tdb.commit();\n\n\n\treturn true;\n}\n\n\n\nvoid MaoFlightMap::lowToHigh(const QString & text)\n{\n\tqobject_cast<QLineEdit *>(sender())->setText(text.toUpper());\n}\n\n\nvoid MaoFlightMap::lookupFlightMap()\n{\n\tif (-1 != currentROW)\n\t{\n\t\temit sGetFlightMap(currentROW + 1);\n\t}\n}\nvoid MaoFlightMap::startEndFlight()\n{\n\tif (Record == tFly.getRecordControl())\n\t{\n\t\ttFly.setRecordControl(Complete);\n\t\ttFS.setAutoRefresh(true);\n\t}\n\telse\n\t{\n\t\tui.MaoArrDate->clear();\n\t\tui.MaoArrTime->clear();\n\t\tui.MaoDivArrICAO->clear();\n\n\t\ttFS.setAutoRefresh(false);\n\t\tgenTraceHTML();\n\t\temit startRecord(ui.MaoFlightNo->text(), ui.MaoArrICAO->text());\n\t}\n}\nvoid MaoFlightMap::genTraceHTML()\n{\n\tQFile::remove(Mao_Flight_HTML_Trace_Web_Path.section(\"\", 9));\n\tQFile::copy(\":\/MaoFlightMap\/MaoTraceWeb.html\", Mao_Flight_HTML_Trace_Web_Path.section(\"\", 9));\n\tQFile::setPermissions(Mao_Flight_HTML_Trace_Web_Path.section(\"\", 9), QFileDevice::WriteOwner | QFileDevice::ReadOwner);\n}\nvoid MaoFlightMap::cancelFlight()\n{\n\ttFly.setRecordControl(Cancel);\n\ttFS.setAutoRefresh(true);\n}\nvoid MaoFlightMap::clickSOC()\n{\n\tdisableNetworkProxy();\n\n\tui.MaoSOCglobalMap->setEnabled(false);\n\tui.MaoSOCupdate->setEnabled(false);\n\tui.MaoSOCusername->setReadOnly(true);\n\tui.MaoSOCpassword->setReadOnly(true);\n\temit sGetSOC(ui.MaoSOCusername->text(), ui.MaoSOCpassword->text());\n}\n\nvoid MaoFlightMap::initDriveCheck()\n{\n\tDWORD count = GetLogicalDrives();\n\tcount >>= 3;\/\/ \u4ece D \u76d8\u5f00\u59cb\u626b\n\tchar drive = 'D';\n\n\tint i = 4;\n\tfor (; i <= 26; i++)\/\/\u626b D~Z\n\t{\n\t\tif (0 == (count & 0x01))\n\t\t{\n\t\t\tcount >>= 1;\n\t\t\tdrive++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQString root = QString(drive) + \":\\\\\";\n\t\t\tunsigned int temp = GetDriveTypeA(root.toLocal8Bit().data());\n\t\t\tif (DRIVE_REMOVABLE == temp || DRIVE_FIXED == temp)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (i > 26)\n\t{\n\t\t\/\/TODO - error\n\t}\n\telse\n\t{\n\t\tMao_Flight_DB_Path = QString(drive) + \":\/MaoFlightRecord.db\";\n\t\tMao_Flight_HTML_File_Path = QString(drive) + \":\/MaoFlightRecord.html\";\n\t\tMao_Flight_HTML_Lookup_Web_Path = QString(\"file:\/\/\/\") + drive + \":\/MaoFlightRecord.html\";\n\t\tMao_Flight_HTML_Trace_Web_Path = QString(\"file:\/\/\/\") + drive + \":\/MaoTraceWeb.html\";\n\t\temit pathReady();\n\t}\n}\nvoid MaoFlightMap::initDatabase()\n{\n\tdb = QSqlDatabase::addDatabase(\"QSQLITE\", \"MaoFlightMap\");\n\tdb.setDatabaseName(Mao_Flight_DB_Path);\n\n\tif (false == db.open())\n\t\tthrow 0;\/\/TODO\n\n\tQSqlQuery dbQuery(db);\n\n\tdbQuery.exec(\"CREATE TABLE FlightList (\"\n\t\t\"TaskNo INT primary key not null unique,\"\n\t\t\"DepDate text,\"\n\t\t\"DepTime text,\"\n\t\t\"ArrDate text,\"\n\t\t\"ArrTime text,\"\n\t\t\"FlightNo text,\"\n\t\t\"PlaneModel text,\"\n\t\t\"DepICAO text,\"\n\t\t\"ArrICAO text,\"\n\t\t\"DivArrICAO text,\"\n\t\t\/\/\"StartLat text,\"\n\t\t\/\/\"StartLon text,\"\n\t\t\/\/\"EndLat text,\"\n\t\t\/\/\"EndLon text,\"\n\t\t\"DetailTable text\"\n\t\t\")\");\n\n\t\/\/**** 1.2 \u7248\n\t\/\/dbQuery.exec(\"CREATE TABLE FlightList (\"\n\t\/\/\t\"TaskNo INT primary key not null unique,\"\n\t\/\/\t\"DepDate text,\"\n\t\/\/\t\"DepTime text,\"\n\t\/\/\t\"ArrDate text,\"\n\t\/\/\t\"ArrTime text,\"\n\t\/\/\t\"FlightNo text,\"\n\t\/\/\t\"PlaneModel text,\"\n\t\/\/\t\"DepICAO text,\"\n\t\/\/\t\"ArrICAO text,\"\n\t\/\/\t\"DivArrICAO text,\"\n\t\/\/\t\"StartLat text,\"\n\t\/\/\t\"StartLon text,\"\n\t\/\/\t\"EndLat text,\"\n\t\/\/\t\"EndLon text,\"\n\t\/\/\t\"DetailTable text\"\n\t\/\/\t\")\");\n}\n\nvoid MaoFlightMap::initThread()\n{\n\ttFly.start();\n\ttFly.moveToThread(&tFly);\n\n\ttLookup.start();\n\ttLookup.moveToThread(&tLookup);\n\n\ttFS.start();\n\ttFS.moveToThread(&tFS);\n}\n\nvoid MaoFlightMap::initWeb()\n{\n\tui.MaoTraceView->setHtml(\"<img src=\\\"qrc:\/MaoFlightMap\/bupt.jpg\\\" style=\\\"max-width:100%;\\\"\/>\");\/\/load(QUrl(\"qrc:\/MaoFlightMap\/bupt\"));\n\n\tui.MaoLookupView->setHtml(\"<img src=\\\"qrc:\/MaoFlightMap\/bupt.jpg\\\" style=\\\"max-width:100%;\\\"\/>\");\n\tui.MaoLookupView->hide();\n}\n\nvoid MaoFlightMap::initFlightTableView()\n{\n\tui.MaoFlightList->clear();\n\tui.MaoFlightList->setRowCount(0);\n\n\tui.MaoFlightList->setColumnCount(Mao_Flight_DB_FlightList_Column);\n\n\tfor (int i = 0; i < Mao_Flight_DB_FlightList_Column; i++)\n\t\tui.MaoFlightList->setHorizontalHeaderItem(i, new QTableWidgetItem(zh(FlightHead[i])));\n}\nvoid MaoFlightMap::initSocTableView()\n{\n\tui.MaoSOCflightList->clear();\n\tui.MaoSOCflightList->setRowCount(0);\n\n\tui.MaoSOCflightList->setColumnCount(Mao_Flight_DB_SOC_Column);\n\n\tfor (int i = 0; i < Mao_Flight_DB_SOC_Column; i++)\n\t\tui.MaoSOCflightList->setHorizontalHeaderItem(i, new QTableWidgetItem(zh(SocHead[i])));\n}\n\nvoid MaoFlightMap::initFlightListViewUI()\n{\n\tui.MaoFlightList->setAcceptDrops(false);\n\tui.MaoFlightList->setAlternatingRowColors(true);\n\tui.MaoFlightList->setEditTriggers(QAbstractItemView::DoubleClicked);\n\tui.MaoFlightList->setShowGrid(true);\n\t\/\/ui.MaoFlightList->setSortingEnabled(true);\n\t\/\/ui.MaoFlightList->sortByColumn(0, Qt::AscendingOrder);\n\tui.MaoFlightList->setSelectionBehavior(QAbstractItemView::SelectRows);\n\tui.MaoFlightList->setSelectionMode(QAbstractItemView::SingleSelection);\n\tui.MaoFlightList->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);\n\t\/\/ui.MaoFlightList->setModel(&flightListModel);\n\t\/\/ui.MaoFlightList->horizontalHeader()->setMinimumWidth(40);\n\n\n\tui.MaoSOCflightList->setAcceptDrops(false);\n\tui.MaoSOCflightList->setAlternatingRowColors(true);\n\tui.MaoSOCflightList->setEditTriggers(QAbstractItemView::NoEditTriggers);\n\tui.MaoSOCflightList->setShowGrid(true);\n\t\/\/ui.MaoSOCflightList->setSortingEnabled(true);\n\t\/\/ui.MaoSOCflightList->sortByColumn(0, Qt::AscendingOrder);\n\tui.MaoSOCflightList->setSelectionBehavior(QAbstractItemView::SelectRows);\n\tui.MaoSOCflightList->setSelectionMode(QAbstractItemView::SingleSelection);\n\tui.MaoSOCflightList->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);\n\t\/\/ui.MaoSOCflightList->setModel(&flightListModel);\n\t\/\/ui.MaoSOCflightList->horizontalHeader()->setMinimumWidth(40);\n\n\n\t\/*\n\tui.MaoOneFlightDetial->setAcceptDrops(false);\n\tui.MaoOneFlightDetial->setAlternatingRowColors(true);\n\tui.MaoOneFlightDetial->setEditTriggers(QAbstractItemView::NoEditTriggers);\n\tui.MaoOneFlightDetial->setShowGrid(true);\n\t\/\/ui.MaoOneFlightDetial->setSortingEnabled(true);\n\t\/\/ui.MaoOneFlightDetial->sortByColumn(0, Qt::AscendingOrder);\n\tui.MaoOneFlightDetial->setSelectionBehavior(QAbstractItemView::SelectRows);\n\tui.MaoOneFlightDetial->setSelectionMode(QAbstractItemView::SingleSelection);\n\tui.MaoOneFlightDetial->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);\n\t\/\/ui.MaoOneFlightDetial->setModel(&flightListModel);\n\t\/\/ui.MaoOneFlightDetial->horizontalHeader()->setMinimumWidth(40);\n\n\n\tui.MaoOneFlightData->setAcceptDrops(false);\n\tui.MaoOneFlightData->setAlternatingRowColors(true);\n\tui.MaoOneFlightData->setEditTriggers(QAbstractItemView::NoEditTriggers);\n\tui.MaoOneFlightData->setShowGrid(true);\n\t\/\/ui.MaoOneFlightData->setSortingEnabled(true);\n\t\/\/ui.MaoOneFlightData->sortByColumn(0, Qt::AscendingOrder);\n\tui.MaoOneFlightData->setSelectionBehavior(QAbstractItemView::SelectRows);\n\tui.MaoOneFlightData->setSelectionMode(QAbstractItemView::SingleSelection);\n\tui.MaoOneFlightData->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);\n\t\/\/ui.MaoOneFlightData->setModel(&flightListModel);\n\t\/\/ui.MaoOneFlightData->horizontalHeader()->setMinimumWidth(40);\n\t*\/\n}\nvoid MaoFlightMap::enableNetworkProxy()\n{\n\t\/\/ use Mao Bing Javascript API, we don't need proxy. http:\/\/www.maojianwei.com\/softwareResource\/MaoBingMapControl_english\n\treturn;\n\t\/\/QNetworkProxy proxy;\n\t\/\/proxy.setType(QNetworkProxy::Socks5Proxy);\n\t\/\/proxy.setHostName(\"www.maojianwei.com\");\n\t\/\/proxy.setPort(1080);\n\t\/\/QNetworkProxy::setApplicationProxy(proxy);\n}\nvoid MaoFlightMap::disableNetworkProxy()\n{\n\t\/\/ use Mao Bing Javascript API, we don't need proxy. http:\/\/www.maojianwei.com\/softwareResource\/MaoBingMapControl_english\n\treturn;\n\t\/\/QNetworkProxy proxy;\n\t\/\/proxy.setType(QNetworkProxy::NoProxy);\n\t\/\/QNetworkProxy::setApplicationProxy(proxy);\n}\n\nvoid MaoFlightMap::loadFlightList()\n{\n\n\tinitFlightTableView();\n\tint row = 0;\n\tQSqlQuery dbQuery(db);\n\tdbQuery.exec(\"SELECT \"\n\t\t\"DepDate,\"\n\t\t\"DepTime,\"\n\t\t\"ArrDate,\"\n\t\t\"ArrTime,\"\n\t\t\"FlightNo,\"\n\t\t\"PlaneModel,\"\n\t\t\"DepICAO,\"\n\t\t\"ArrICAO,\"\n\t\t\"DivArrICAO \"\n\t\t\"FROM FlightList\");\n\n\tQTableWidgetItem * temp;\n\twhile (true == dbQuery.next())\n\t{\n\t\tui.MaoFlightList->setRowCount(ui.MaoFlightList->rowCount() + 1);\n\t\tfor (int i = 0; i < Mao_Flight_DB_FlightList_Column; i++)\n\t\t{\n\t\t\ttemp = new QTableWidgetItem(dbQuery.value(i).toString());\n\t\t\tif (i <= 4 || 7 == i)\n\t\t\t\ttemp->setFlags((temp->flags()) & (~Qt::ItemIsEditable));\/\/\u53ea\u5141\u8bb8\u4fee\u6b63\u201c\u673a\u578b\u201d\u3001\u201c\u8d77\u98de\u673a\u573a\u201d\u3001\u201c\u5907\u964d\u673a\u573a\u201d\n\t\t\ttemp->setTextAlignment(Qt::AlignCenter);\n\t\t\tui.MaoFlightList->setItem(row, i, temp);\n\t\t}\n\t\trow++;\n\t}\n}\nvoid MaoFlightMap::loadSocFlightList()\n{\n\tinitSocTableView();\n\tint row = 0;\n\n\tQSqlQuery dbQuery(db);\n\tdbQuery.exec(\"SELECT \"\n\t\t\"Date,\"\n\t\t\"FlightNo,\"\n\t\t\"PlaneModel,\"\n\t\t\"PlaneName,\"\n\t\t\"DepICAO,\"\n\t\t\"ArrICAO,\"\n\t\t\"Pilot,\"\n\t\t\"Passenger,\"\n\t\t\"Score,\"\n\t\t\"Reputation,\"\n\t\t\"Income\"\n\t\t\" FROM SocFlightList\");\n\n\tQTableWidgetItem * temp;\n\twhile (true == dbQuery.next())\n\t{\n\t\tui.MaoSOCflightList->setRowCount(ui.MaoSOCflightList->rowCount() + 1);\n\t\tfor (int i = 0; i < Mao_Flight_DB_SOC_Column; i++)\n\t\t{\n\t\t\ttemp = new QTableWidgetItem(dbQuery.value(i).toString());\n\t\t\ttemp->setTextAlignment(Qt::AlignCenter);\n\t\t\tui.MaoSOCflightList->setItem(row, i, temp);\n\t\t}\n\t\trow++;\n\t}\n}\n\nvoid MaoFlightMap::checkUpdate()\n{\n\tQUrl url = \"http:\/\/maojianwei.github.io\/softwareUpdate\/MaoFlightMap.html\";\n\tQNetworkRequest req = QNetworkRequest(url);\n\tupdate.get(req);\n}\nvoid MaoFlightMap::loadUpdate(QNetworkReply* reply)\n{\n\tQString data = reply->readAll();\n\tif (data.indexOf(';') >= 0)\n\t{\n\t\tQStringList edition = data.split(';');\n\t\tif (edition.length() >= 4)\n\t\t{\n\t\t\tQString version = edition[0];\n\t\t\tQByteArray url = edition[1].toLocal8Bit();\n\t\t\tQByteArray detail = edition[2].toLocal8Bit();\n\t\t\tQString backupStation = edition[3];\n\t\t\tif (Mao_Flight_Version != version)\n\t\t\t{\n\t\t\t\tQMessageBox::StandardButton choose = QMessageBox::information(this,\n\t\t\t\t\tzh(\"\u53d1\u73b0\u65b0\u7248\u672c\uff01\"),\n\t\t\t\t\tzh(\"\u5f53\u524d\u7248\u672c\uff1a\") + Mao_Flight_Version +\n\t\t\t\t\tzh(\"\\n\u6700\u65b0\u7248\u672c\uff1a\") + version +\n\t\t\t\t\tzh(\"\\n\\n\u66f4\u65b0\u5185\u5bb9\uff1a\\n\") +\n\t\t\t\t\tzh(detail.data()) +\n\t\t\t\t\tzh(\"\\n\\n\u5b98\u65b9\u5907\u7528\u4e0b\u8f7d\u70b9\uff1a\") + backupStation +\n\t\t\t\t\tzh(\"\uff08\u70b9\u51fb Help\uff09\"),\n\t\t\t\t\tQMessageBox::Ok | QMessageBox::Help | QMessageBox::Cancel, QMessageBox::Ok);\n\t\t\t\tif (QMessageBox::Ok == choose)\n\t\t\t\t\tShellExecuteA(NULL, \"open\", \"explorer.exe\", url.data(), NULL, SW_SHOW);\n\t\t\t\telse if (QMessageBox::Help == choose)\n\t\t\t\t\tShellExecuteA(NULL, \"open\", \"explorer.exe\", backupStation.toLocal8Bit(), NULL, SW_SHOW);\n\t\t\t}\n\t\t}\n\t}\n}\nvoid MaoFlightMap::markPin(double lat, double lon)\n{\n\tQString temp = \"updatePos(%1,%2)\";\n\ttemp = temp.arg(lat).arg(lon);\n\tui.MaoTraceView->page()->runJavaScript(temp);\n}\nvoid MaoFlightMap::traceWebShow()\n{\n\tenableNetworkProxy();\n\n\tui.MaoTraceView->stop();\n\tui.MaoTraceView->load(QUrl(Mao_Flight_HTML_Trace_Web_Path));\n}\n\n\nvoid MaoFlightMap::lookupWebShow()\n{\n\tenableNetworkProxy();\n\n\tui.MaoLookupView->stop();\n\tui.MaoLookupView->load(QUrl(Mao_Flight_HTML_Lookup_Web_Path));\n}\n\n\nQString MaoFlightMap::zh(const char* str)\n{\n\treturn china->toUnicode(str);\n}\n\/\/void MaoFlightMap::selectCell(int row, int column)\n\/\/{\n\/\/\tcurrentROW = row;\n\/\/}\n\nvoid MaoFlightMap::showUIs(MaoUIsignalS signal)\n{\n\tswitch (signal.type)\n\t{\n\tcase Mao_Flight_UI_TaskNo:\n\t\tui.MaoTaskNo->setText(signal.value);\n\t\tbreak;\n\tcase Mao_Flight_UI_DepDate:\n\t\tui.MaoDepDate->setText(signal.value);\n\t\tbreak;\n\tcase Mao_Flight_UI_DepTime:\n\t\tui.MaoDepTime->setText(signal.value);\n\t\tbreak;\n\tcase Mao_Flight_UI_ArrDate:\n\t\tui.MaoArrDate->setText(signal.value);\n\t\tbreak;\n\tcase Mao_Flight_UI_ArrTime:\n\t\tui.MaoArrTime->setText(signal.value);\n\t\tbreak;\n\tcase Mao_Flight_UI_PlaneModel:\n\t\tui.MaoPlaneModel->setText(signal.value);\n\t\tbreak;\n\tcase Mao_Flight_UI_DepICAO:\n\t\tui.MaoDepICAO->setText(signal.value);\n\t\tbreak;\n\tcase Mao_Flight_UI_DivArrICAO:\n\t\tui.MaoDivArrICAO->setText(signal.value);\n\t\tbreak;\n\tcase Mao_Flight_UI_Web_Trace:\n\t\tui.MaoTraceView->page()->runJavaScript(\"updatePos(\" + signal.value + \")\");\/\/ TODO - \u65b0\u7684\u4fe1\u53f7\u673a\u5236\uff0c\u5f85\u8c03 2015.09.30 10\uff1a45 \u6559\u4e8c201\n\t\tbreak;\n\tcase Mao_Flight_UI_Status_Message:\n\t\tui.MaoStatusBar->showMessage(signal.value);\n\t\tbreak;\n\tcase Mao_Flight_UI_Soc_Button_Message:\n\t\tui.MaoSOCupdate->setText(signal.value);\n\t\tbreak;\n\tcase Mao_Flight_UI_AirSpeed:\n\t\tui.MaoAirSpeed->setText(signal.value + zh(\" \u8282\"));\n\t\tbreak;\n\tcase Mao_Flight_UI_GNDspeed:\n\t\tui.MaoGNDspeed->setText(signal.value + \" Km\/h\");\n\t\tbreak;\n\n\n\n\n\tcase Mao_Flight_UI_Soc_Complete: \/\/ QString \u662f\u5269\u4f59\u5c1d\u8bd5\u6b21\u6570\n\t\tui.MaoSOCusername->setText(zh(\"\u8bf7\u8f93\u5165\u6b63\u786e\u7684 SOC \u8d26\u53f7\u3001\u5bc6\u7801\uff0c\u9700\u8981\u91cd\u542f\u8f6f\u4ef6\u518d\u8bd5\"));\n\t\tui.MaoSOCpassword->setText(zh(\"\u767b\u5f55\u5931\u8d25\uff0c\u8fd8\u53ef\u4ee5\u5c1d\u8bd5 %1 \u6b21\uff0c\u5931\u8d25\u8fc7\u591a\u9700\u7b49 15 \u5206\u949f\").arg(signal.value));\n\t\tui.MaoSOCpassword->setEchoMode(QLineEdit::EchoMode::Normal);\n\n\t\tui.MaoSOCusername->setReadOnly(true);\n\t\tui.MaoSOCpassword->setReadOnly(true);\n\t\tui.MaoSOCglobalMap->setEnabled(true);\n\t\tui.MaoSOCupdate->setEnabled(false);\n\t\tui.MaoSOCupdate->setText(zh(\"\u4ece SOC \u66f4\u65b0\"));\n\t\tbreak;\n\tdefault:\n\t\tthrow 0;\/\/TODO - \u4e0d\u5e94\u8be5\u51fa\u73b0\u8fd9\u79cd\u60c5\u51b5\n\t}\n}\nvoid MaoFlightMap::showUIb(MaoUIsignalB signal)\n{\n\tswitch (signal.type)\n\t{\n\tcase Mao_Flight_UI_ConnectStatus:\n\t\tif (true == signal.value)\n\t\t{\n\t\t\tui.MaoStartEndFlight->setEnabled(true);\n\t\t\tui.MaoStatusBar->showMessage(zh(\"FS \u8fde\u63a5\u6210\u529f\uff01\"));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tui.MaoStartEndFlight->setEnabled(false);\n\t\t\tui.MaoStatusBar->showMessage(zh(\"FS \u8fde\u63a5\u5931\u8d25\uff0c\u7b49\u5f85 FSX \u548c FSUIPC \u5f00\u542f...\"));\/\/\u4e0d\u80fd\u7ed3\u675f\u822a\u73ed\uff0c\u4f46\u53ef\u4ee5\u53d6\u6d88\u822a\u73ed\n\t\t}\n\t\tbreak;\n\tcase Mao_Flight_UI_Record_Complete:\n\t\tif (true == signal.value)\n\t\t{\n\t\t\tui.MaoCancelFlight->setEnabled(false);\n\t\t\tui.MaoStatusBar->showMessage(zh(\"\u822a\u73ed\u6210\u529f\u5b8c\u6210\uff01\"));\n\t\t\tloadFlightList();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tui.MaoCancelFlight->setEnabled(false);\n\t\t\tui.MaoStatusBar->showMessage(zh(\"\u672c\u6b21\u822a\u73ed\u53d6\u6d88\"));\n\t\t}\n\t\tui.MaoFlightNo->setReadOnly(false);\n\t\tui.MaoArrICAO->setReadOnly(false);\n\t\tbreak;\n\tcase Mao_Flight_UI_Record_Start:\n\t\ttraceWebShow();\n\t\tui.MaoFlightNo->setReadOnly(true);\n\t\tui.MaoArrICAO->setReadOnly(true);\n\t\tui.MaoCancelFlight->setEnabled(true);\n\t\tui.MaoStatusBar->showMessage(zh(\"\u5f00\u59cb\u6267\u98de\u822a\u73ed...\"));\n\t\tbreak;\n\tcase Mao_Flight_UI_Soc_Complete:\n\t\tif (true == signal.value)\n\t\t{\n\t\t\tloadSocFlightList();\n\t\t\tui.MaoSOCusername->setReadOnly(true); \/\/ \u4e0d\u80fd\u767b\u9646\u5176\u4ed6\u8d26\u53f7\uff0c\u9700\u8981\u91cd\u542f\u624d\u884c\n\t\t\tui.MaoSOCpassword->setReadOnly(true); \/\/ \u4e0d\u80fd\u767b\u9646\u5176\u4ed6\u8d26\u53f7\uff0c\u9700\u8981\u91cd\u542f\u624d\u884c\n\t\t\tui.MaoSOCupdate->setEnabled(true);    \/\/ \u53ef\u7ee7\u7eed\u83b7\u53d6\u672c\u8d26\u53f7\u7684\u822a\u73ed\u8bb0\u5f55\n\t\t\tui.MaoSOCupdate->setText(zh(\"\u4ece SOC \u66f4\u65b0\"));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tui.MaoSOCusername->setText(zh(\"\u8bf7\u8f93\u5165\u6b63\u786e\u7684 SOC \u8d26\u53f7\u3001\u5bc6\u7801\uff0c\u9700\u8981\u91cd\u542f\u8f6f\u4ef6\u518d\u8bd5\"));\n\t\t\tui.MaoSOCpassword->setText(zh(\"\u53ef\u80fd\u662f\u5176\u4ed6\u95ee\u9898\uff0c\u8054\u7cfb\u8f6f\u4ef6\u4f5c\u8005\uff0cwww.MaoJianwei.com\"));\n\t\t\tui.MaoSOCpassword->setEchoMode(QLineEdit::EchoMode::Normal);\n\t\t\tui.MaoSOCusername->setReadOnly(true); \/\/ \u4f3c\u4e4e\u5931\u8d25\u540e\u4e0d\u80fd\u91cd\u8bd5\n\t\t\tui.MaoSOCpassword->setReadOnly(true); \/\/ \u4f3c\u4e4e\u5931\u8d25\u540e\u4e0d\u80fd\u91cd\u8bd5\n\t\t\tui.MaoSOCupdate->setEnabled(false);\n\t\t}\n\t\tui.MaoSOCglobalMap->setEnabled(true);\n\t\tbreak;\n\tcase Mao_Flight_UI_Soc_Complete_Can_Retry:\n\t\tui.MaoSOCusername->setReadOnly(false);\n\t\tui.MaoSOCpassword->setReadOnly(false);\n\t\tui.MaoSOCglobalMap->setEnabled(true);\n\t\tui.MaoSOCupdate->setEnabled(true);\n\t\tui.MaoSOCupdate->setText(zh(\"\u4ece SOC \u66f4\u65b0\\n\u8d26\u53f7\u3001\u5bc6\u7801\u4e0d\u80fd\u4e3a\u7a7a\"));\n\t\tbreak;\n\tdefault:\n\t\tthrow 0;\/\/TODO - \u4e0d\u5e94\u8be5\u51fa\u73b0\u8fd9\u79cd\u60c5\u51b5\n\t}\n}","avg_line_length":27.9930635838,"max_line_length":136,"alphanum_fraction":0.7273891137,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6339,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/*\nRathin Bhargava\nIIIT Bangalore\n\n*\/\n#include<bits\/stdc++.h>\n#define mt make_tuple\n#define mp make_pair\n#define pu push_back\n#define INF 1000000001\n#define MOD 1000000007\n#define ll long long int\n#define ld long double\n#define fi first\n#define se second\n#define pr(v) { for(int i=0;i<v.size();i++) { v[i]==INF? cout<<\"INF \" : cout<<v[i]<<\" \"; } cout<<endl;}\n#define t1(x)                cerr<<#x<<\" : \"<<x<<endl\n#define t2(x, y)             cerr<<#x<<\" : \"<<x<<\" \"<<#y<<\" : \"<<y<<endl\n#define t3(x, y, z)          cerr<<#x<<\" : \" <<x<<\" \"<<#y<<\" : \"<<y<<\" \"<<#z<<\" : \"<<z<<endl\n#define t4(a,b,c,d)          cerr<<#a<<\" : \"<<a<<\" \"<<#b<<\" : \"<<b<<\" \"<<#c<<\" : \"<<c<<\" \"<<#d<<\" : \"<<d<<endl\n#define t5(a,b,c,d,e)          cerr<<#a<<\" : \"<<a<<\" \"<<#b<<\" : \"<<b<<\" \"<<#c<<\" : \"<<c<<\" \"<<#d<<\" : \"<<d<<\" \"<<#e<<\" : \"<<e<<endl\n#define t6(a,b,c,d,e,f)          cerr<<#a<<\" : \"<<a<<\" \"<<#b<<\" : \"<<b<<\" \"<<#c<<\" : \"<<c<<\" \"<<#d<<\" : \"<<d<<\" \"<<#e<<\" : \"<<e<<\" \"<<#f<<\" : \"<<f<<endl\n#define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME\n#define t(...) GET_MACRO(__VA_ARGS__,t6,t5, t4, t3, t2, t1)(__VA_ARGS__)\n#define _ cerr<<\"here\"<<endl;\n#define __ {ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);}\n\nusing namespace std;\ntemplate<class A, class B> ostream& operator<<(ostream& out, const pair<A, B> &a){ return out<<\"(\"<<a.first<<\", \"<<a.second<<\")\";}\ntemplate <typename T> ostream& operator<<(ostream& os, const vector<T>& v) { os << \"[\"; for (int i = 0; i < v.size(); ++i) { if(v[i]!=INF) os << v[i]; else os << \"INF\";if (i != v.size() - 1) os << \", \"; } os << \"]\\n\"; return os; } \n\nconst int MAXN = 2.5e5+1,MAXLOG = 25;\nvector<int> adj[MAXN] = {};\nint parent[MAXN][25] = {0};\nvector<vector<ll> > dp(MAXN,vector<ll>(MAXLOG));\nint height[MAXN] = {0};\nll sz[MAXN] = {0};\n\n\/\/ Counter1 is the total number of paths, not including the parent passing, through the current node\n\/\/ Counter2 is the total number of paths from root -> children. Any path coming from the parent goes from here\n\nll counter1[MAXN] = {0};\n\nint dfs1(int u = 0,int p = -1)\n{\n  sz[u] = 1;\n  for(auto v : adj[u]) if(v-p) sz[u]+=dfs1(v,u);\n  return sz[u];\n}\n\nvoid dfs2(int u = 0,int p = -1)\n{\n  \/\/ t(u);\n  if(p+1) height[u] = height[p]+1;\n  parent[u][0] = p;\n  for(int i=1;i<MAXLOG;i++)\n  {\n    if(parent[u][i-1]+1)\n    {\n      parent[u][i] = parent[parent[u][i-1]][i-1];\n    }\n  }\n\n  ll a = sz[u]-1; \/\/ Root -> children\n  ll cnt = 0; \/\/ Children -> Children + Root -> children\n  for(auto v : adj[u]) if(v-p) cnt+=sz[v]*(a-sz[v]);\n  cnt>>=1;\n  cnt+=a;\n\n  counter1[u] = cnt;\n\n  \/\/ if(sz[u]==1) counter1[u] = counter2[u] = 1;\n\n  if(p+1) \n  {\n    dp[u][0] = counter1[p] - (sz[p]-sz[u])*sz[u];\n  }\n\n  for(int i=1;i<MAXLOG;i++)\n  {\n    if(parent[u][i-1]+1 && parent[u][i]+1)\n    {\n      dp[u][i] += dp[parent[u][i-1]][i-1] + dp[u][i-1];\n    }\n  }\n\n  for(auto v : adj[u]) if(v-p) dfs2(v,u);\n}\n\nint LCA(int u,int v)\n{\n  \/\/ height means depth here\n  if(height[v]>height[u]) swap(u,v);\n\n  for(int i=MAXLOG-1;i>=0;i--)\n  {\n    if(parent[u][i]+1 && height[parent[u][i]]>=height[v]) u = parent[u][i];\n  }\n\n  \/\/ height[u]==height[v]\n  if(u==v) return u;\n  for(int i=MAXLOG-1;i>=0;i--)\n  {\n    if(parent[u][i]!=parent[v][i]) \n    {\n      u = parent[u][i];\n      v = parent[v][i];\n    }\n  }\n\n  return parent[v][0];\n}\n\nll find(int u,int lca,int n,int v = -1)\n{\n  int u1 = u, v1 = v;\n  if(v!=-1 && height[v]>height[u]) swap(u,v);\n\n  \/\/ t(u,lca,v);\n  \/\/ Get the nodes to the height of lca-1\n  ll cntu = 0, cntv = 0;\n  for(int i=MAXLOG-1;i>=0;i--)\n  {\n    if(parent[u][i]+1 && height[parent[u][i]]>=height[lca]+1) \n    {\n      cntu+=dp[u][i];\n      u = parent[u][i];\n    }\n    if(v+1 && parent[v][i]+1 && height[parent[v][i]]>=height[lca]+1) \n    {\n      cntv+=dp[v][i];\n      v = parent[v][i];\n    }\n  }\n\n  \/\/ t(u,v);\n  ll cnt = 0;\n  \/\/ Both u and v, if there, are the height of LCA - 1\n  \/\/ There are 2 nodes in the chain which we haven't taken care of. The LCA and the original nodes, u1 and v1\n  if(v==-1)\n  {\n    cntu+=dp[u][0];\n    cnt+=cntu;\n     \/\/ Anybody from the parent can intersect with the lca and can go anywhere apart from the subtree of u\n    cnt += (n-sz[lca])*(sz[lca]-sz[u]);\n    cnt+=counter1[u1];\n    cnt+=height[u1]-height[lca]+1; \/\/ My system never allowed (u,u) to be called a valid path, will try adding it in the dp\n  }\n  else\n  {\n    \/\/ cntu+=dp[u][0];\n    \/\/ cntv+=dp[v][0];\n    \/\/ t(dp[u][0],dp[v][0]);\n    \n    \/\/ Parent -> lca -> a node not in the subtree of u or v\n    cnt += (n-sz[lca])*(sz[lca]-sz[u]-sz[v]);\n    \/\/ A path involving the lca and not the parent should originate from a node which should not be in the subtree or u or v\n    \/\/ Or, all the paths involving the lca i.e. counter1[lca] and remove the paths which originate somewhere and go to subtree of either u or v\n    \n\n    ll a = sz[lca] - sz[u] - sz[v];\n    cnt+= counter1[lca] - a*(sz[u]+sz[v]) -sz[u]*sz[v];\n\n    cnt+=cntu+cntv;\n    \/\/ Correct stuff, pls don't touch this\n    cnt+=counter1[u1]+counter1[v1];\n    cnt+=height[u1]+height[v1]-2*height[lca]+1;\n  }\n  return cnt;\n}\n\nint main()\n{\n  __;\n  int t;\n  cin>>t;\n  \/\/ scanf(\"%d\",&t);\n  while(t--)\n  {\n    int n,q;\n    cin>>n>>q;\n    \/\/ scanf(\"%d %d\",&n,&q);\n    for(int i=0;i<n;i++) for(int j=0;j<MAXLOG;j++) parent[i][j] = -1;\n    for(int i=0;i<n-1;i++)\n    {\n      int a,b;\n      cin>>a>>b;\n      \/\/ scanf(\"%d %d\",&a,&b);\n      a--;b--;\n      adj[a].pu(b);\n      adj[b].pu(a);\n    }\n    dfs1();\n    dfs2();\n    \/\/ for(int i=0;i<n;i++) t(i,sz[i],counter1[i]);\n    \/\/ for(int i=0;i<n;i++)\n    \/\/ {\n    \/\/   for(int j=0;j<5;j++)\n    \/\/   {\n    \/\/     t(i,j,dp[i][j],parent[i][j]);\n    \/\/   }\n    \/\/ }\n    while(q--)\n    {\n      int a,b;\n      cin>>a>>b;\n      \/\/ scanf(\"%d %d\",&a,&b);\n      a--;b--;\n      int lca = LCA(a,b);\n      if(lca==a) {a = b; b = lca;}\n\n      if(lca!=a && lca!=b) cout<<find(a,lca,n,b)<<endl;\n      else if(a==b) cout<<(n-sz[a])*(sz[a])+counter1[a]+1<<endl;\n      else cout<<find(a,b,n)<<endl;\n      \/\/ if(lca!=a && lca!=b) printf(\"%lld\\n\",find(a,lca,n,b));\n      \/\/ else if(a==b) printf(\"%lld\\n\",(n-sz[a])*(sz[a])+counter1[a]+1);\n      \/\/ else printf(\"%lld\\n\",find(a,b,n));\n    }\n\n    for(int i=0;i<n;i++) for(int j=0;j<MAXLOG;j++) dp[i][j] = 0;\n    memset(height,0,sizeof(height));\n    memset(sz,0,sizeof(sz));  \n    memset(counter1,0,sizeof(counter1));\n    for(int i=0;i<n;i++) adj[i] = {};\n  }\n  return 0;\n}\n","avg_line_length":27.8026315789,"max_line_length":231,"alphanum_fraction":0.5033917022,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":276651,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Bitcode\/BitcodeReader.h\"\n#include \"MetadataLoader.h\"\n#include \"ValueList.h\"\n#include \"llvm\/ADT\/APFloat.h\"\n#include \"llvm\/ADT\/APInt.h\"\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/ADT\/Optional.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Bitcode\/BitcodeCommon.h\"\n#include \"llvm\/Bitcode\/LLVMBitCodes.h\"\n#include \"llvm\/Bitstream\/BitstreamReader.h\"\n#include \"llvm\/Config\/llvm-config.h\"\n#include \"llvm\/IR\/Argument.h\"\n#include \"llvm\/IR\/Attributes.h\"\n#include \"llvm\/IR\/AutoUpgrade.h\"\n#include \"llvm\/IR\/BasicBlock.h\"\n#include \"llvm\/IR\/CallingConv.h\"\n#include \"llvm\/IR\/Comdat.h\"\n#include \"llvm\/IR\/Constant.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/DebugInfo.h\"\n#include \"llvm\/IR\/DebugInfoMetadata.h\"\n#include \"llvm\/IR\/DebugLoc.h\"\n#include \"llvm\/IR\/DerivedTypes.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GVMaterializer.h\"\n#include \"llvm\/IR\/GetElementPtrTypeIterator.h\"\n#include \"llvm\/IR\/GlobalAlias.h\"\n#include \"llvm\/IR\/GlobalIFunc.h\"\n#include \"llvm\/IR\/GlobalObject.h\"\n#include \"llvm\/IR\/GlobalValue.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/IR\/InlineAsm.h\"\n#include \"llvm\/IR\/InstIterator.h\"\n#include \"llvm\/IR\/InstrTypes.h\"\n#include \"llvm\/IR\/Instruction.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Intrinsics.h\"\n#include \"llvm\/IR\/IntrinsicsAArch64.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Metadata.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/ModuleSummaryIndex.h\"\n#include \"llvm\/IR\/Operator.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/IR\/Value.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/Support\/AtomicOrdering.h\"\n#include \"llvm\/Support\/Casting.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Error.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/ErrorOr.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <algorithm>\n#include <cassert>\n#include <cstddef>\n#include <cstdint>\n#include <deque>\n#include <map>\n#include <memory>\n#include <set>\n#include <string>\n#include <system_error>\n#include <tuple>\n#include <utility>\n#include <vector>\n\nusing namespace llvm;\n\nstatic cl::opt<bool> PrintSummaryGUIDs(\n    \"print-summary-global-ids\", cl::init(false), cl::Hidden,\n    cl::desc(\n        \"Print the global id for each value when reading the module summary\"));\n\nnamespace {\n\nenum {\n  SWITCH_INST_MAGIC = 0x4B5 \/\/ May 2012 => 1205 => Hex\n};\n\n} \/\/ end anonymous namespace\n\nstatic Error error(const Twine &Message) {\n  return make_error<StringError>(\n      Message, make_error_code(BitcodeError::CorruptedBitcode));\n}\n\nstatic Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) {\n  if (!Stream.canSkipToPos(4))\n    return createStringError(std::errc::illegal_byte_sequence,\n                             \"file too small to contain bitcode header\");\n  for (unsigned C : {'B', 'C'})\n    if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {\n      if (Res.get() != C)\n        return createStringError(std::errc::illegal_byte_sequence,\n                                 \"file doesn't start with bitcode header\");\n    } else\n      return Res.takeError();\n  for (unsigned C : {0x0, 0xC, 0xE, 0xD})\n    if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {\n      if (Res.get() != C)\n        return createStringError(std::errc::illegal_byte_sequence,\n                                 \"file doesn't start with bitcode header\");\n    } else\n      return Res.takeError();\n  return Error::success();\n}\n\nstatic Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {\n  const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();\n  const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();\n\n  if (Buffer.getBufferSize() & 3)\n    return error(\"Invalid bitcode signature\");\n\n  \/\/ If we have a wrapper header, parse it and ignore the non-bc file contents.\n  \/\/ The magic number is 0x0B17C0DE stored in little endian.\n  if (isBitcodeWrapper(BufPtr, BufEnd))\n    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))\n      return error(\"Invalid bitcode wrapper header\");\n\n  BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));\n  if (Error Err = hasInvalidBitcodeHeader(Stream))\n    return std::move(Err);\n\n  return std::move(Stream);\n}\n\n\/\/\/ Convert a string from a record into an std::string, return true on failure.\ntemplate <typename StrTy>\nstatic bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,\n                            StrTy &Result) {\n  if (Idx > Record.size())\n    return true;\n\n  Result.append(Record.begin() + Idx, Record.end());\n  return false;\n}\n\n\/\/ Strip all the TBAA attachment for the module.\nstatic void stripTBAA(Module *M) {\n  for (auto &F : *M) {\n    if (F.isMaterializable())\n      continue;\n    for (auto &I : instructions(F))\n      I.setMetadata(LLVMContext::MD_tbaa, nullptr);\n  }\n}\n\n\/\/\/ Read the \"IDENTIFICATION_BLOCK_ID\" block, do some basic enforcement on the\n\/\/\/ \"epoch\" encoded in the bitcode, and return the producer name if any.\nstatic Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {\n  if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))\n    return std::move(Err);\n\n  \/\/ Read all the records.\n  SmallVector<uint64_t, 64> Record;\n\n  std::string ProducerIdentification;\n\n  while (true) {\n    BitstreamEntry Entry;\n    if (Error E = Stream.advance().moveInto(Entry))\n      return std::move(E);\n\n    switch (Entry.Kind) {\n    default:\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return ProducerIdentification;\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Read a record.\n    Record.clear();\n    Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeBitCode)\n      return MaybeBitCode.takeError();\n    switch (MaybeBitCode.get()) {\n    default: \/\/ Default behavior: reject\n      return error(\"Invalid value\");\n    case bitc::IDENTIFICATION_CODE_STRING: \/\/ IDENTIFICATION: [strchr x N]\n      convertToString(Record, 0, ProducerIdentification);\n      break;\n    case bitc::IDENTIFICATION_CODE_EPOCH: { \/\/ EPOCH: [epoch#]\n      unsigned epoch = (unsigned)Record[0];\n      if (epoch != bitc::BITCODE_CURRENT_EPOCH) {\n        return error(\n          Twine(\"Incompatible epoch: Bitcode '\") + Twine(epoch) +\n          \"' vs current: '\" + Twine(bitc::BITCODE_CURRENT_EPOCH) + \"'\");\n      }\n    }\n    }\n  }\n}\n\nstatic Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {\n  \/\/ We expect a number of well-defined blocks, though we don't necessarily\n  \/\/ need to understand them all.\n  while (true) {\n    if (Stream.AtEndOfStream())\n      return \"\";\n\n    BitstreamEntry Entry;\n    if (Error E = Stream.advance().moveInto(Entry))\n      return std::move(E);\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::EndBlock:\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n\n    case BitstreamEntry::SubBlock:\n      if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)\n        return readIdentificationBlock(Stream);\n\n      \/\/ Ignore other sub-blocks.\n      if (Error Err = Stream.SkipBlock())\n        return std::move(Err);\n      continue;\n    case BitstreamEntry::Record:\n      if (Error E = Stream.skipRecord(Entry.ID).takeError())\n        return std::move(E);\n      continue;\n    }\n  }\n}\n\nstatic Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {\n  if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))\n    return std::move(Err);\n\n  SmallVector<uint64_t, 64> Record;\n  \/\/ Read all the records for this module.\n\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return false;\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Read a record.\n    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeRecord)\n      return MaybeRecord.takeError();\n    switch (MaybeRecord.get()) {\n    default:\n      break; \/\/ Default behavior, ignore unknown content.\n    case bitc::MODULE_CODE_SECTIONNAME: { \/\/ SECTIONNAME: [strchr x N]\n      std::string S;\n      if (convertToString(Record, 0, S))\n        return error(\"Invalid section name record\");\n      \/\/ Check for the i386 and other (x86_64, ARM) conventions\n      if (S.find(\"__DATA,__objc_catlist\") != std::string::npos ||\n          S.find(\"__OBJC,__category\") != std::string::npos)\n        return true;\n      break;\n    }\n    }\n    Record.clear();\n  }\n  llvm_unreachable(\"Exit infinite loop\");\n}\n\nstatic Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {\n  \/\/ We expect a number of well-defined blocks, though we don't necessarily\n  \/\/ need to understand them all.\n  while (true) {\n    BitstreamEntry Entry;\n    if (Error E = Stream.advance().moveInto(Entry))\n      return std::move(E);\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return false;\n\n    case BitstreamEntry::SubBlock:\n      if (Entry.ID == bitc::MODULE_BLOCK_ID)\n        return hasObjCCategoryInModule(Stream);\n\n      \/\/ Ignore other sub-blocks.\n      if (Error Err = Stream.SkipBlock())\n        return std::move(Err);\n      continue;\n\n    case BitstreamEntry::Record:\n      if (Error E = Stream.skipRecord(Entry.ID).takeError())\n        return std::move(E);\n      continue;\n    }\n  }\n}\n\nstatic Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {\n  if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))\n    return std::move(Err);\n\n  SmallVector<uint64_t, 64> Record;\n\n  std::string Triple;\n\n  \/\/ Read all the records for this module.\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return Triple;\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Read a record.\n    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeRecord)\n      return MaybeRecord.takeError();\n    switch (MaybeRecord.get()) {\n    default: break;  \/\/ Default behavior, ignore unknown content.\n    case bitc::MODULE_CODE_TRIPLE: {  \/\/ TRIPLE: [strchr x N]\n      std::string S;\n      if (convertToString(Record, 0, S))\n        return error(\"Invalid triple record\");\n      Triple = S;\n      break;\n    }\n    }\n    Record.clear();\n  }\n  llvm_unreachable(\"Exit infinite loop\");\n}\n\nstatic Expected<std::string> readTriple(BitstreamCursor &Stream) {\n  \/\/ We expect a number of well-defined blocks, though we don't necessarily\n  \/\/ need to understand them all.\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advance();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return \"\";\n\n    case BitstreamEntry::SubBlock:\n      if (Entry.ID == bitc::MODULE_BLOCK_ID)\n        return readModuleTriple(Stream);\n\n      \/\/ Ignore other sub-blocks.\n      if (Error Err = Stream.SkipBlock())\n        return std::move(Err);\n      continue;\n\n    case BitstreamEntry::Record:\n      if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))\n        continue;\n      else\n        return Skipped.takeError();\n    }\n  }\n}\n\nnamespace {\n\nclass BitcodeReaderBase {\nprotected:\n  BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)\n      : Stream(std::move(Stream)), Strtab(Strtab) {\n    this->Stream.setBlockInfo(&BlockInfo);\n  }\n\n  BitstreamBlockInfo BlockInfo;\n  BitstreamCursor Stream;\n  StringRef Strtab;\n\n  \/\/\/ In version 2 of the bitcode we store names of global values and comdats in\n  \/\/\/ a string table rather than in the VST.\n  bool UseStrtab = false;\n\n  Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);\n\n  \/\/\/ If this module uses a string table, pop the reference to the string table\n  \/\/\/ and return the referenced string and the rest of the record. Otherwise\n  \/\/\/ just return the record itself.\n  std::pair<StringRef, ArrayRef<uint64_t>>\n  readNameFromStrtab(ArrayRef<uint64_t> Record);\n\n  Error readBlockInfo();\n\n  \/\/ Contains an arbitrary and optional string identifying the bitcode producer\n  std::string ProducerIdentification;\n\n  Error error(const Twine &Message);\n};\n\n} \/\/ end anonymous namespace\n\nError BitcodeReaderBase::error(const Twine &Message) {\n  std::string FullMsg = Message.str();\n  if (!ProducerIdentification.empty())\n    FullMsg += \" (Producer: '\" + ProducerIdentification + \"' Reader: 'LLVM \" +\n               LLVM_VERSION_STRING \"')\";\n  return ::error(FullMsg);\n}\n\nExpected<unsigned>\nBitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {\n  if (Record.empty())\n    return error(\"Invalid version record\");\n  unsigned ModuleVersion = Record[0];\n  if (ModuleVersion > 2)\n    return error(\"Invalid value\");\n  UseStrtab = ModuleVersion >= 2;\n  return ModuleVersion;\n}\n\nstd::pair<StringRef, ArrayRef<uint64_t>>\nBitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {\n  if (!UseStrtab)\n    return {\"\", Record};\n  \/\/ Invalid reference. Let the caller complain about the record being empty.\n  if (Record[0] + Record[1] > Strtab.size())\n    return {\"\", {}};\n  return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};\n}\n\nnamespace {\n\nclass BitcodeReader : public BitcodeReaderBase, public GVMaterializer {\n  LLVMContext &Context;\n  Module *TheModule = nullptr;\n  \/\/ Next offset to start scanning for lazy parsing of function bodies.\n  uint64_t NextUnreadBit = 0;\n  \/\/ Last function offset found in the VST.\n  uint64_t LastFunctionBlockBit = 0;\n  bool SeenValueSymbolTable = false;\n  uint64_t VSTOffset = 0;\n\n  std::vector<std::string> SectionTable;\n  std::vector<std::string> GCTable;\n\n  std::vector<Type *> TypeList;\n  \/\/\/ Track type IDs of contained types. Order is the same as the contained\n  \/\/\/ types of a Type*. This is used during upgrades of typed pointer IR in\n  \/\/\/ opaque pointer mode.\n  DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;\n  \/\/\/ In some cases, we need to create a type ID for a type that was not\n  \/\/\/ explicitly encoded in the bitcode, or we don't know about at the current\n  \/\/\/ point. For example, a global may explicitly encode the value type ID, but\n  \/\/\/ not have a type ID for the pointer to value type, for which we create a\n  \/\/\/ virtual type ID instead. This map stores the new type ID that was created\n  \/\/\/ for the given pair of Type and contained type ID.\n  DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs;\n  DenseMap<Function *, unsigned> FunctionTypeIDs;\n  BitcodeReaderValueList ValueList;\n  Optional<MetadataLoader> MDLoader;\n  std::vector<Comdat *> ComdatList;\n  DenseSet<GlobalObject *> ImplicitComdatObjects;\n  SmallVector<Instruction *, 64> InstructionList;\n\n  std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;\n  std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;\n\n  struct FunctionOperandInfo {\n    Function *F;\n    unsigned PersonalityFn;\n    unsigned Prefix;\n    unsigned Prologue;\n  };\n  std::vector<FunctionOperandInfo> FunctionOperands;\n\n  \/\/\/ The set of attributes by index.  Index zero in the file is for null, and\n  \/\/\/ is thus not represented here.  As such all indices are off by one.\n  std::vector<AttributeList> MAttributes;\n\n  \/\/\/ The set of attribute groups.\n  std::map<unsigned, AttributeList> MAttributeGroups;\n\n  \/\/\/ While parsing a function body, this is a list of the basic blocks for the\n  \/\/\/ function.\n  std::vector<BasicBlock*> FunctionBBs;\n\n  \/\/ When reading the module header, this list is populated with functions that\n  \/\/ have bodies later in the file.\n  std::vector<Function*> FunctionsWithBodies;\n\n  \/\/ When intrinsic functions are encountered which require upgrading they are\n  \/\/ stored here with their replacement function.\n  using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;\n  UpdatedIntrinsicMap UpgradedIntrinsics;\n  \/\/ Intrinsics which were remangled because of types rename\n  UpdatedIntrinsicMap RemangledIntrinsics;\n\n  \/\/ Several operations happen after the module header has been read, but\n  \/\/ before function bodies are processed. This keeps track of whether\n  \/\/ we've done this yet.\n  bool SeenFirstFunctionBody = false;\n\n  \/\/\/ When function bodies are initially scanned, this map contains info about\n  \/\/\/ where to find deferred function body in the stream.\n  DenseMap<Function*, uint64_t> DeferredFunctionInfo;\n\n  \/\/\/ When Metadata block is initially scanned when parsing the module, we may\n  \/\/\/ choose to defer parsing of the metadata. This vector contains info about\n  \/\/\/ which Metadata blocks are deferred.\n  std::vector<uint64_t> DeferredMetadataInfo;\n\n  \/\/\/ These are basic blocks forward-referenced by block addresses.  They are\n  \/\/\/ inserted lazily into functions when they're loaded.  The basic block ID is\n  \/\/\/ its index into the vector.\n  DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;\n  std::deque<Function *> BasicBlockFwdRefQueue;\n\n  \/\/\/ Indicates that we are using a new encoding for instruction operands where\n  \/\/\/ most operands in the current FUNCTION_BLOCK are encoded relative to the\n  \/\/\/ instruction number, for a more compact encoding.  Some instruction\n  \/\/\/ operands are not relative to the instruction ID: basic block numbers, and\n  \/\/\/ types. Once the old style function blocks have been phased out, we would\n  \/\/\/ not need this flag.\n  bool UseRelativeIDs = false;\n\n  \/\/\/ True if all functions will be materialized, negating the need to process\n  \/\/\/ (e.g.) blockaddress forward references.\n  bool WillMaterializeAllForwardRefs = false;\n\n  bool StripDebugInfo = false;\n  TBAAVerifier TBAAVerifyHelper;\n\n  std::vector<std::string> BundleTags;\n  SmallVector<SyncScope::ID, 8> SSIDs;\n\npublic:\n  BitcodeReader(BitstreamCursor Stream, StringRef Strtab,\n                StringRef ProducerIdentification, LLVMContext &Context);\n\n  Error materializeForwardReferencedFunctions();\n\n  Error materialize(GlobalValue *GV) override;\n  Error materializeModule() override;\n  std::vector<StructType *> getIdentifiedStructTypes() const override;\n\n  \/\/\/ Main interface to parsing a bitcode buffer.\n  \/\/\/ \\returns true if an error occurred.\n  Error parseBitcodeInto(\n      Module *M, bool ShouldLazyLoadMetadata = false, bool IsImporting = false,\n      DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; });\n\n  static uint64_t decodeSignRotatedValue(uint64_t V);\n\n  \/\/\/ Materialize any deferred Metadata block.\n  Error materializeMetadata() override;\n\n  void setStripDebugInfo() override;\n\nprivate:\n  std::vector<StructType *> IdentifiedStructTypes;\n  StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);\n  StructType *createIdentifiedStructType(LLVMContext &Context);\n\n  static constexpr unsigned InvalidTypeID = ~0u;\n\n  Type *getTypeByID(unsigned ID);\n  Type *getPtrElementTypeByID(unsigned ID);\n  unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0);\n  unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});\n\n  Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID) {\n    if (Ty && Ty->isMetadataTy())\n      return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));\n    return ValueList.getValueFwdRef(ID, Ty, TyID);\n  }\n\n  Metadata *getFnMetadataByID(unsigned ID) {\n    return MDLoader->getMetadataFwdRefOrLoad(ID);\n  }\n\n  BasicBlock *getBasicBlock(unsigned ID) const {\n    if (ID >= FunctionBBs.size()) return nullptr; \/\/ Invalid ID\n    return FunctionBBs[ID];\n  }\n\n  AttributeList getAttributes(unsigned i) const {\n    if (i-1 < MAttributes.size())\n      return MAttributes[i-1];\n    return AttributeList();\n  }\n\n  \/\/\/ Read a value\/type pair out of the specified record from slot 'Slot'.\n  \/\/\/ Increment Slot past the number of slots used in the record. Return true on\n  \/\/\/ failure.\n  bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,\n                        unsigned InstNum, Value *&ResVal, unsigned &TypeID) {\n    if (Slot == Record.size()) return true;\n    unsigned ValNo = (unsigned)Record[Slot++];\n    \/\/ Adjust the ValNo, if it was encoded relative to the InstNum.\n    if (UseRelativeIDs)\n      ValNo = InstNum - ValNo;\n    if (ValNo < InstNum) {\n      \/\/ If this is not a forward reference, just return the value we already\n      \/\/ have.\n      TypeID = ValueList.getTypeID(ValNo);\n      ResVal = getFnValueByID(ValNo, nullptr, TypeID);\n      assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) &&\n             \"Incorrect type ID stored for value\");\n      return ResVal == nullptr;\n    }\n    if (Slot == Record.size())\n      return true;\n\n    TypeID = (unsigned)Record[Slot++];\n    ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID);\n    return ResVal == nullptr;\n  }\n\n  \/\/\/ Read a value out of the specified record from slot 'Slot'. Increment Slot\n  \/\/\/ past the number of slots used by the value in the record. Return true if\n  \/\/\/ there is an error.\n  bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,\n                unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal) {\n    if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal))\n      return true;\n    \/\/ All values currently take a single record slot.\n    ++Slot;\n    return false;\n  }\n\n  \/\/\/ Like popValue, but does not increment the Slot number.\n  bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,\n                unsigned InstNum, Type *Ty, unsigned TyID,  Value *&ResVal) {\n    ResVal = getValue(Record, Slot, InstNum, Ty, TyID);\n    return ResVal == nullptr;\n  }\n\n  \/\/\/ Version of getValue that returns ResVal directly, or 0 if there is an\n  \/\/\/ error.\n  Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,\n                  unsigned InstNum, Type *Ty, unsigned TyID) {\n    if (Slot == Record.size()) return nullptr;\n    unsigned ValNo = (unsigned)Record[Slot];\n    \/\/ Adjust the ValNo, if it was encoded relative to the InstNum.\n    if (UseRelativeIDs)\n      ValNo = InstNum - ValNo;\n    return getFnValueByID(ValNo, Ty, TyID);\n  }\n\n  \/\/\/ Like getValue, but decodes signed VBRs.\n  Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,\n                        unsigned InstNum, Type *Ty, unsigned TyID) {\n    if (Slot == Record.size()) return nullptr;\n    unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);\n    \/\/ Adjust the ValNo, if it was encoded relative to the InstNum.\n    if (UseRelativeIDs)\n      ValNo = InstNum - ValNo;\n    return getFnValueByID(ValNo, Ty, TyID);\n  }\n\n  \/\/\/ Upgrades old-style typeless byval\/sret\/inalloca attributes by adding the\n  \/\/\/ corresponding argument's pointee type. Also upgrades intrinsics that now\n  \/\/\/ require an elementtype attribute.\n  Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);\n\n  \/\/\/ Converts alignment exponent (i.e. power of two (or zero)) to the\n  \/\/\/ corresponding alignment to use. If alignment is too large, returns\n  \/\/\/ a corresponding error code.\n  Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment);\n  Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);\n  Error parseModule(\n      uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,\n      DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; });\n\n  Error parseComdatRecord(ArrayRef<uint64_t> Record);\n  Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);\n  Error parseFunctionRecord(ArrayRef<uint64_t> Record);\n  Error parseGlobalIndirectSymbolRecord(unsigned BitCode,\n                                        ArrayRef<uint64_t> Record);\n\n  Error parseAttributeBlock();\n  Error parseAttributeGroupBlock();\n  Error parseTypeTable();\n  Error parseTypeTableBody();\n  Error parseOperandBundleTags();\n  Error parseSyncScopeNames();\n\n  Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,\n                                unsigned NameIndex, Triple &TT);\n  void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,\n                               ArrayRef<uint64_t> Record);\n  Error parseValueSymbolTable(uint64_t Offset = 0);\n  Error parseGlobalValueSymbolTable();\n  Error parseConstants();\n  Error rememberAndSkipFunctionBodies();\n  Error rememberAndSkipFunctionBody();\n  \/\/\/ Save the positions of the Metadata blocks and skip parsing the blocks.\n  Error rememberAndSkipMetadata();\n  Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);\n  Error parseFunctionBody(Function *F);\n  Error globalCleanup();\n  Error resolveGlobalAndIndirectSymbolInits();\n  Error parseUseLists();\n  Error findFunctionInStream(\n      Function *F,\n      DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);\n\n  SyncScope::ID getDecodedSyncScopeID(unsigned Val);\n};\n\n\/\/\/ Class to manage reading and parsing function summary index bitcode\n\/\/\/ files\/sections.\nclass ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {\n  \/\/\/ The module index built during parsing.\n  ModuleSummaryIndex &TheIndex;\n\n  \/\/\/ Indicates whether we have encountered a global value summary section\n  \/\/\/ yet during parsing.\n  bool SeenGlobalValSummary = false;\n\n  \/\/\/ Indicates whether we have already parsed the VST, used for error checking.\n  bool SeenValueSymbolTable = false;\n\n  \/\/\/ Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.\n  \/\/\/ Used to enable on-demand parsing of the VST.\n  uint64_t VSTOffset = 0;\n\n  \/\/ Map to save ValueId to ValueInfo association that was recorded in the\n  \/\/ ValueSymbolTable. It is used after the VST is parsed to convert\n  \/\/ call graph edges read from the function summary from referencing\n  \/\/ callees by their ValueId to using the ValueInfo instead, which is how\n  \/\/ they are recorded in the summary index being built.\n  \/\/ We save a GUID which refers to the same global as the ValueInfo, but\n  \/\/ ignoring the linkage, i.e. for values other than local linkage they are\n  \/\/ identical.\n  DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>\n      ValueIdToValueInfoMap;\n\n  \/\/\/ Map populated during module path string table parsing, from the\n  \/\/\/ module ID to a string reference owned by the index's module\n  \/\/\/ path string table, used to correlate with combined index\n  \/\/\/ summary records.\n  DenseMap<uint64_t, StringRef> ModuleIdMap;\n\n  \/\/\/ Original source file name recorded in a bitcode record.\n  std::string SourceFileName;\n\n  \/\/\/ The string identifier given to this module by the client, normally the\n  \/\/\/ path to the bitcode file.\n  StringRef ModulePath;\n\n  \/\/\/ For per-module summary indexes, the unique numerical identifier given to\n  \/\/\/ this module by the client.\n  unsigned ModuleId;\n\npublic:\n  ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,\n                                  ModuleSummaryIndex &TheIndex,\n                                  StringRef ModulePath, unsigned ModuleId);\n\n  Error parseModule();\n\nprivate:\n  void setValueGUID(uint64_t ValueID, StringRef ValueName,\n                    GlobalValue::LinkageTypes Linkage,\n                    StringRef SourceFileName);\n  Error parseValueSymbolTable(\n      uint64_t Offset,\n      DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);\n  std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);\n  std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,\n                                                    bool IsOldProfileFormat,\n                                                    bool HasProfile,\n                                                    bool HasRelBF);\n  Error parseEntireSummary(unsigned ID);\n  Error parseModuleStringTable();\n  void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);\n  void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,\n                                       TypeIdCompatibleVtableInfo &TypeId);\n  std::vector<FunctionSummary::ParamAccess>\n  parseParamAccesses(ArrayRef<uint64_t> Record);\n\n  std::pair<ValueInfo, GlobalValue::GUID>\n  getValueInfoFromValueId(unsigned ValueId);\n\n  void addThisModule();\n  ModuleSummaryIndex::ModuleInfo *getThisModule();\n};\n\n} \/\/ end anonymous namespace\n\nstd::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,\n                                                    Error Err) {\n  if (Err) {\n    std::error_code EC;\n    handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {\n      EC = EIB.convertToErrorCode();\n      Ctx.emitError(EIB.message());\n    });\n    return EC;\n  }\n  return std::error_code();\n}\n\nBitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,\n                             StringRef ProducerIdentification,\n                             LLVMContext &Context)\n    : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),\n      ValueList(Context, this->Stream.SizeInBytes()) {\n  this->ProducerIdentification = std::string(ProducerIdentification);\n}\n\nError BitcodeReader::materializeForwardReferencedFunctions() {\n  if (WillMaterializeAllForwardRefs)\n    return Error::success();\n\n  \/\/ Prevent recursion.\n  WillMaterializeAllForwardRefs = true;\n\n  while (!BasicBlockFwdRefQueue.empty()) {\n    Function *F = BasicBlockFwdRefQueue.front();\n    BasicBlockFwdRefQueue.pop_front();\n    assert(F && \"Expected valid function\");\n    if (!BasicBlockFwdRefs.count(F))\n      \/\/ Already materialized.\n      continue;\n\n    \/\/ Check for a function that isn't materializable to prevent an infinite\n    \/\/ loop.  When parsing a blockaddress stored in a global variable, there\n    \/\/ isn't a trivial way to check if a function will have a body without a\n    \/\/ linear search through FunctionsWithBodies, so just check it here.\n    if (!F->isMaterializable())\n      return error(\"Never resolved function from blockaddress\");\n\n    \/\/ Try to materialize F.\n    if (Error Err = materialize(F))\n      return Err;\n  }\n  assert(BasicBlockFwdRefs.empty() && \"Function missing from queue\");\n\n  \/\/ Reset state.\n  WillMaterializeAllForwardRefs = false;\n  return Error::success();\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  Helper functions to implement forward reference resolution, etc.\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic bool hasImplicitComdat(size_t Val) {\n  switch (Val) {\n  default:\n    return false;\n  case 1:  \/\/ Old WeakAnyLinkage\n  case 4:  \/\/ Old LinkOnceAnyLinkage\n  case 10: \/\/ Old WeakODRLinkage\n  case 11: \/\/ Old LinkOnceODRLinkage\n    return true;\n  }\n}\n\nstatic GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {\n  switch (Val) {\n  default: \/\/ Map unknown\/new linkages to external\n  case 0:\n    return GlobalValue::ExternalLinkage;\n  case 2:\n    return GlobalValue::AppendingLinkage;\n  case 3:\n    return GlobalValue::InternalLinkage;\n  case 5:\n    return GlobalValue::ExternalLinkage; \/\/ Obsolete DLLImportLinkage\n  case 6:\n    return GlobalValue::ExternalLinkage; \/\/ Obsolete DLLExportLinkage\n  case 7:\n    return GlobalValue::ExternalWeakLinkage;\n  case 8:\n    return GlobalValue::CommonLinkage;\n  case 9:\n    return GlobalValue::PrivateLinkage;\n  case 12:\n    return GlobalValue::AvailableExternallyLinkage;\n  case 13:\n    return GlobalValue::PrivateLinkage; \/\/ Obsolete LinkerPrivateLinkage\n  case 14:\n    return GlobalValue::PrivateLinkage; \/\/ Obsolete LinkerPrivateWeakLinkage\n  case 15:\n    return GlobalValue::ExternalLinkage; \/\/ Obsolete LinkOnceODRAutoHideLinkage\n  case 1: \/\/ Old value with implicit comdat.\n  case 16:\n    return GlobalValue::WeakAnyLinkage;\n  case 10: \/\/ Old value with implicit comdat.\n  case 17:\n    return GlobalValue::WeakODRLinkage;\n  case 4: \/\/ Old value with implicit comdat.\n  case 18:\n    return GlobalValue::LinkOnceAnyLinkage;\n  case 11: \/\/ Old value with implicit comdat.\n  case 19:\n    return GlobalValue::LinkOnceODRLinkage;\n  }\n}\n\nstatic FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {\n  FunctionSummary::FFlags Flags;\n  Flags.ReadNone = RawFlags & 0x1;\n  Flags.ReadOnly = (RawFlags >> 1) & 0x1;\n  Flags.NoRecurse = (RawFlags >> 2) & 0x1;\n  Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;\n  Flags.NoInline = (RawFlags >> 4) & 0x1;\n  Flags.AlwaysInline = (RawFlags >> 5) & 0x1;\n  Flags.NoUnwind = (RawFlags >> 6) & 0x1;\n  Flags.MayThrow = (RawFlags >> 7) & 0x1;\n  Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;\n  Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;\n  return Flags;\n}\n\n\/\/ Decode the flags for GlobalValue in the summary. The bits for each attribute:\n\/\/\n\/\/ linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,\n\/\/ visibility: [8, 10).\nstatic GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,\n                                                            uint64_t Version) {\n  \/\/ Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage\n  \/\/ like getDecodedLinkage() above. Any future change to the linkage enum and\n  \/\/ to getDecodedLinkage() will need to be taken into account here as above.\n  auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); \/\/ 4 bits\n  auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); \/\/ 2 bits\n  RawFlags = RawFlags >> 4;\n  bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;\n  \/\/ The Live flag wasn't introduced until version 3. For dead stripping\n  \/\/ to work correctly on earlier versions, we must conservatively treat all\n  \/\/ values as live.\n  bool Live = (RawFlags & 0x2) || Version < 3;\n  bool Local = (RawFlags & 0x4);\n  bool AutoHide = (RawFlags & 0x8);\n\n  return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,\n                                     Live, Local, AutoHide);\n}\n\n\/\/ Decode the flags for GlobalVariable in the summary\nstatic GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {\n  return GlobalVarSummary::GVarFlags(\n      (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,\n      (RawFlags & 0x4) ? true : false,\n      (GlobalObject::VCallVisibility)(RawFlags >> 3));\n}\n\nstatic GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {\n  switch (Val) {\n  default: \/\/ Map unknown visibilities to default.\n  case 0: return GlobalValue::DefaultVisibility;\n  case 1: return GlobalValue::HiddenVisibility;\n  case 2: return GlobalValue::ProtectedVisibility;\n  }\n}\n\nstatic GlobalValue::DLLStorageClassTypes\ngetDecodedDLLStorageClass(unsigned Val) {\n  switch (Val) {\n  default: \/\/ Map unknown values to default.\n  case 0: return GlobalValue::DefaultStorageClass;\n  case 1: return GlobalValue::DLLImportStorageClass;\n  case 2: return GlobalValue::DLLExportStorageClass;\n  }\n}\n\nstatic bool getDecodedDSOLocal(unsigned Val) {\n  switch(Val) {\n  default: \/\/ Map unknown values to preemptable.\n  case 0:  return false;\n  case 1:  return true;\n  }\n}\n\nstatic GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {\n  switch (Val) {\n    case 0: return GlobalVariable::NotThreadLocal;\n    default: \/\/ Map unknown non-zero value to general dynamic.\n    case 1: return GlobalVariable::GeneralDynamicTLSModel;\n    case 2: return GlobalVariable::LocalDynamicTLSModel;\n    case 3: return GlobalVariable::InitialExecTLSModel;\n    case 4: return GlobalVariable::LocalExecTLSModel;\n  }\n}\n\nstatic GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {\n  switch (Val) {\n    default: \/\/ Map unknown to UnnamedAddr::None.\n    case 0: return GlobalVariable::UnnamedAddr::None;\n    case 1: return GlobalVariable::UnnamedAddr::Global;\n    case 2: return GlobalVariable::UnnamedAddr::Local;\n  }\n}\n\nstatic int getDecodedCastOpcode(unsigned Val) {\n  switch (Val) {\n  default: return -1;\n  case bitc::CAST_TRUNC   : return Instruction::Trunc;\n  case bitc::CAST_ZEXT    : return Instruction::ZExt;\n  case bitc::CAST_SEXT    : return Instruction::SExt;\n  case bitc::CAST_FPTOUI  : return Instruction::FPToUI;\n  case bitc::CAST_FPTOSI  : return Instruction::FPToSI;\n  case bitc::CAST_UITOFP  : return Instruction::UIToFP;\n  case bitc::CAST_SITOFP  : return Instruction::SIToFP;\n  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;\n  case bitc::CAST_FPEXT   : return Instruction::FPExt;\n  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;\n  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;\n  case bitc::CAST_BITCAST : return Instruction::BitCast;\n  case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;\n  }\n}\n\nstatic int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {\n  bool IsFP = Ty->isFPOrFPVectorTy();\n  \/\/ UnOps are only valid for int\/fp or vector of int\/fp types\n  if (!IsFP && !Ty->isIntOrIntVectorTy())\n    return -1;\n\n  switch (Val) {\n  default:\n    return -1;\n  case bitc::UNOP_FNEG:\n    return IsFP ? Instruction::FNeg : -1;\n  }\n}\n\nstatic int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {\n  bool IsFP = Ty->isFPOrFPVectorTy();\n  \/\/ BinOps are only valid for int\/fp or vector of int\/fp types\n  if (!IsFP && !Ty->isIntOrIntVectorTy())\n    return -1;\n\n  switch (Val) {\n  default:\n    return -1;\n  case bitc::BINOP_ADD:\n    return IsFP ? Instruction::FAdd : Instruction::Add;\n  case bitc::BINOP_SUB:\n    return IsFP ? Instruction::FSub : Instruction::Sub;\n  case bitc::BINOP_MUL:\n    return IsFP ? Instruction::FMul : Instruction::Mul;\n  case bitc::BINOP_UDIV:\n    return IsFP ? -1 : Instruction::UDiv;\n  case bitc::BINOP_SDIV:\n    return IsFP ? Instruction::FDiv : Instruction::SDiv;\n  case bitc::BINOP_UREM:\n    return IsFP ? -1 : Instruction::URem;\n  case bitc::BINOP_SREM:\n    return IsFP ? Instruction::FRem : Instruction::SRem;\n  case bitc::BINOP_SHL:\n    return IsFP ? -1 : Instruction::Shl;\n  case bitc::BINOP_LSHR:\n    return IsFP ? -1 : Instruction::LShr;\n  case bitc::BINOP_ASHR:\n    return IsFP ? -1 : Instruction::AShr;\n  case bitc::BINOP_AND:\n    return IsFP ? -1 : Instruction::And;\n  case bitc::BINOP_OR:\n    return IsFP ? -1 : Instruction::Or;\n  case bitc::BINOP_XOR:\n    return IsFP ? -1 : Instruction::Xor;\n  }\n}\n\nstatic AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {\n  switch (Val) {\n  default: return AtomicRMWInst::BAD_BINOP;\n  case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;\n  case bitc::RMW_ADD: return AtomicRMWInst::Add;\n  case bitc::RMW_SUB: return AtomicRMWInst::Sub;\n  case bitc::RMW_AND: return AtomicRMWInst::And;\n  case bitc::RMW_NAND: return AtomicRMWInst::Nand;\n  case bitc::RMW_OR: return AtomicRMWInst::Or;\n  case bitc::RMW_XOR: return AtomicRMWInst::Xor;\n  case bitc::RMW_MAX: return AtomicRMWInst::Max;\n  case bitc::RMW_MIN: return AtomicRMWInst::Min;\n  case bitc::RMW_UMAX: return AtomicRMWInst::UMax;\n  case bitc::RMW_UMIN: return AtomicRMWInst::UMin;\n  case bitc::RMW_FADD: return AtomicRMWInst::FAdd;\n  case bitc::RMW_FSUB: return AtomicRMWInst::FSub;\n  }\n}\n\nstatic AtomicOrdering getDecodedOrdering(unsigned Val) {\n  switch (Val) {\n  case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;\n  case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;\n  case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;\n  case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;\n  case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;\n  case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;\n  default: \/\/ Map unknown orderings to sequentially-consistent.\n  case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;\n  }\n}\n\nstatic Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {\n  switch (Val) {\n  default: \/\/ Map unknown selection kinds to any.\n  case bitc::COMDAT_SELECTION_KIND_ANY:\n    return Comdat::Any;\n  case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:\n    return Comdat::ExactMatch;\n  case bitc::COMDAT_SELECTION_KIND_LARGEST:\n    return Comdat::Largest;\n  case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:\n    return Comdat::NoDeduplicate;\n  case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:\n    return Comdat::SameSize;\n  }\n}\n\nstatic FastMathFlags getDecodedFastMathFlags(unsigned Val) {\n  FastMathFlags FMF;\n  if (0 != (Val & bitc::UnsafeAlgebra))\n    FMF.setFast();\n  if (0 != (Val & bitc::AllowReassoc))\n    FMF.setAllowReassoc();\n  if (0 != (Val & bitc::NoNaNs))\n    FMF.setNoNaNs();\n  if (0 != (Val & bitc::NoInfs))\n    FMF.setNoInfs();\n  if (0 != (Val & bitc::NoSignedZeros))\n    FMF.setNoSignedZeros();\n  if (0 != (Val & bitc::AllowReciprocal))\n    FMF.setAllowReciprocal();\n  if (0 != (Val & bitc::AllowContract))\n    FMF.setAllowContract(true);\n  if (0 != (Val & bitc::ApproxFunc))\n    FMF.setApproxFunc();\n  return FMF;\n}\n\nstatic void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {\n  switch (Val) {\n  case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;\n  case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;\n  }\n}\n\nType *BitcodeReader::getTypeByID(unsigned ID) {\n  \/\/ The type table size is always specified correctly.\n  if (ID >= TypeList.size())\n    return nullptr;\n\n  if (Type *Ty = TypeList[ID])\n    return Ty;\n\n  \/\/ If we have a forward reference, the only possible case is when it is to a\n  \/\/ named struct.  Just create a placeholder for now.\n  return TypeList[ID] = createIdentifiedStructType(Context);\n}\n\nunsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) {\n  auto It = ContainedTypeIDs.find(ID);\n  if (It == ContainedTypeIDs.end())\n    return InvalidTypeID;\n\n  if (Idx >= It->second.size())\n    return InvalidTypeID;\n\n  return It->second[Idx];\n}\n\nType *BitcodeReader::getPtrElementTypeByID(unsigned ID) {\n  if (ID >= TypeList.size())\n    return nullptr;\n\n  Type *Ty = TypeList[ID];\n  if (!Ty->isPointerTy())\n    return nullptr;\n\n  Type *ElemTy = getTypeByID(getContainedTypeID(ID, 0));\n  if (!ElemTy)\n    return nullptr;\n\n  assert(cast<PointerType>(Ty)->isOpaqueOrPointeeTypeMatches(ElemTy) &&\n         \"Incorrect element type\");\n  return ElemTy;\n}\n\nunsigned BitcodeReader::getVirtualTypeID(Type *Ty,\n                                         ArrayRef<unsigned> ChildTypeIDs) {\n  unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0];\n  auto CacheKey = std::make_pair(Ty, ChildTypeID);\n  auto It = VirtualTypeIDs.find(CacheKey);\n  if (It != VirtualTypeIDs.end()) {\n    \/\/ The cmpxchg return value is the only place we need more than one\n    \/\/ contained type ID, however the second one will always be the same (i1),\n    \/\/ so we don't need to include it in the cache key. This asserts that the\n    \/\/ contained types are indeed as expected and there are no collisions.\n    assert((ChildTypeIDs.empty() ||\n            ContainedTypeIDs[It->second] == ChildTypeIDs) &&\n           \"Incorrect cached contained type IDs\");\n    return It->second;\n  }\n\n#ifndef NDEBUG\n  if (!Ty->isOpaquePointerTy()) {\n    assert(Ty->getNumContainedTypes() == ChildTypeIDs.size() &&\n           \"Wrong number of contained types\");\n    for (auto Pair : zip(Ty->subtypes(), ChildTypeIDs)) {\n      assert(std::get<0>(Pair) == getTypeByID(std::get<1>(Pair)) &&\n             \"Incorrect contained type ID\");\n    }\n  }\n#endif\n\n  unsigned TypeID = TypeList.size();\n  TypeList.push_back(Ty);\n  if (!ChildTypeIDs.empty())\n    append_range(ContainedTypeIDs[TypeID], ChildTypeIDs);\n  VirtualTypeIDs.insert({CacheKey, TypeID});\n  return TypeID;\n}\n\nStructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,\n                                                      StringRef Name) {\n  auto *Ret = StructType::create(Context, Name);\n  IdentifiedStructTypes.push_back(Ret);\n  return Ret;\n}\n\nStructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {\n  auto *Ret = StructType::create(Context);\n  IdentifiedStructTypes.push_back(Ret);\n  return Ret;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  Functions for parsing blocks from the bitcode file\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic uint64_t getRawAttributeMask(Attribute::AttrKind Val) {\n  switch (Val) {\n  case Attribute::EndAttrKinds:\n  case Attribute::EmptyKey:\n  case Attribute::TombstoneKey:\n    llvm_unreachable(\"Synthetic enumerators which should never get here\");\n\n  case Attribute::None:            return 0;\n  case Attribute::ZExt:            return 1 << 0;\n  case Attribute::SExt:            return 1 << 1;\n  case Attribute::NoReturn:        return 1 << 2;\n  case Attribute::InReg:           return 1 << 3;\n  case Attribute::StructRet:       return 1 << 4;\n  case Attribute::NoUnwind:        return 1 << 5;\n  case Attribute::NoAlias:         return 1 << 6;\n  case Attribute::ByVal:           return 1 << 7;\n  case Attribute::Nest:            return 1 << 8;\n  case Attribute::ReadNone:        return 1 << 9;\n  case Attribute::ReadOnly:        return 1 << 10;\n  case Attribute::NoInline:        return 1 << 11;\n  case Attribute::AlwaysInline:    return 1 << 12;\n  case Attribute::OptimizeForSize: return 1 << 13;\n  case Attribute::StackProtect:    return 1 << 14;\n  case Attribute::StackProtectReq: return 1 << 15;\n  case Attribute::Alignment:       return 31 << 16;\n  case Attribute::NoCapture:       return 1 << 21;\n  case Attribute::NoRedZone:       return 1 << 22;\n  case Attribute::NoImplicitFloat: return 1 << 23;\n  case Attribute::Naked:           return 1 << 24;\n  case Attribute::InlineHint:      return 1 << 25;\n  case Attribute::StackAlignment:  return 7 << 26;\n  case Attribute::ReturnsTwice:    return 1 << 29;\n  case Attribute::UWTable:         return 1 << 30;\n  case Attribute::NonLazyBind:     return 1U << 31;\n  case Attribute::SanitizeAddress: return 1ULL << 32;\n  case Attribute::MinSize:         return 1ULL << 33;\n  case Attribute::NoDuplicate:     return 1ULL << 34;\n  case Attribute::StackProtectStrong: return 1ULL << 35;\n  case Attribute::SanitizeThread:  return 1ULL << 36;\n  case Attribute::SanitizeMemory:  return 1ULL << 37;\n  case Attribute::NoBuiltin:       return 1ULL << 38;\n  case Attribute::Returned:        return 1ULL << 39;\n  case Attribute::Cold:            return 1ULL << 40;\n  case Attribute::Builtin:         return 1ULL << 41;\n  case Attribute::OptimizeNone:    return 1ULL << 42;\n  case Attribute::InAlloca:        return 1ULL << 43;\n  case Attribute::NonNull:         return 1ULL << 44;\n  case Attribute::JumpTable:       return 1ULL << 45;\n  case Attribute::Convergent:      return 1ULL << 46;\n  case Attribute::SafeStack:       return 1ULL << 47;\n  case Attribute::NoRecurse:       return 1ULL << 48;\n  case Attribute::InaccessibleMemOnly:         return 1ULL << 49;\n  case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;\n  case Attribute::SwiftSelf:       return 1ULL << 51;\n  case Attribute::SwiftError:      return 1ULL << 52;\n  case Attribute::WriteOnly:       return 1ULL << 53;\n  case Attribute::Speculatable:    return 1ULL << 54;\n  case Attribute::StrictFP:        return 1ULL << 55;\n  case Attribute::SanitizeHWAddress: return 1ULL << 56;\n  case Attribute::NoCfCheck:       return 1ULL << 57;\n  case Attribute::OptForFuzzing:   return 1ULL << 58;\n  case Attribute::ShadowCallStack: return 1ULL << 59;\n  case Attribute::SpeculativeLoadHardening:\n    return 1ULL << 60;\n  case Attribute::ImmArg:\n    return 1ULL << 61;\n  case Attribute::WillReturn:\n    return 1ULL << 62;\n  case Attribute::NoFree:\n    return 1ULL << 63;\n  default:\n    \/\/ Other attributes are not supported in the raw format,\n    \/\/ as we ran out of space.\n    return 0;\n  }\n  llvm_unreachable(\"Unsupported attribute type\");\n}\n\nstatic void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {\n  if (!Val) return;\n\n  for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;\n       I = Attribute::AttrKind(I + 1)) {\n    if (uint64_t A = (Val & getRawAttributeMask(I))) {\n      if (I == Attribute::Alignment)\n        B.addAlignmentAttr(1ULL << ((A >> 16) - 1));\n      else if (I == Attribute::StackAlignment)\n        B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));\n      else if (Attribute::isTypeAttrKind(I))\n        B.addTypeAttr(I, nullptr); \/\/ Type will be auto-upgraded.\n      else\n        B.addAttribute(I);\n    }\n  }\n}\n\n\/\/\/ This fills an AttrBuilder object with the LLVM attributes that have\n\/\/\/ been decoded from the given integer. This function must stay in sync with\n\/\/\/ 'encodeLLVMAttributesForBitcode'.\nstatic void decodeLLVMAttributesForBitcode(AttrBuilder &B,\n                                           uint64_t EncodedAttrs) {\n  \/\/ The alignment is stored as a 16-bit raw value from bits 31--16.  We shift\n  \/\/ the bits above 31 down by 11 bits.\n  unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;\n  assert((!Alignment || isPowerOf2_32(Alignment)) &&\n         \"Alignment must be a power of two.\");\n\n  if (Alignment)\n    B.addAlignmentAttr(Alignment);\n  addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |\n                          (EncodedAttrs & 0xffff));\n}\n\nError BitcodeReader::parseAttributeBlock() {\n  if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))\n    return Err;\n\n  if (!MAttributes.empty())\n    return error(\"Invalid multiple blocks\");\n\n  SmallVector<uint64_t, 64> Record;\n\n  SmallVector<AttributeList, 8> Attrs;\n\n  \/\/ Read all the records.\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return Error::success();\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Read a record.\n    Record.clear();\n    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeRecord)\n      return MaybeRecord.takeError();\n    switch (MaybeRecord.get()) {\n    default:  \/\/ Default behavior: ignore.\n      break;\n    case bitc::PARAMATTR_CODE_ENTRY_OLD: \/\/ ENTRY: [paramidx0, attr0, ...]\n      \/\/ Deprecated, but still needed to read old bitcode files.\n      if (Record.size() & 1)\n        return error(\"Invalid parameter attribute record\");\n\n      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {\n        AttrBuilder B(Context);\n        decodeLLVMAttributesForBitcode(B, Record[i+1]);\n        Attrs.push_back(AttributeList::get(Context, Record[i], B));\n      }\n\n      MAttributes.push_back(AttributeList::get(Context, Attrs));\n      Attrs.clear();\n      break;\n    case bitc::PARAMATTR_CODE_ENTRY: \/\/ ENTRY: [attrgrp0, attrgrp1, ...]\n      for (unsigned i = 0, e = Record.size(); i != e; ++i)\n        Attrs.push_back(MAttributeGroups[Record[i]]);\n\n      MAttributes.push_back(AttributeList::get(Context, Attrs));\n      Attrs.clear();\n      break;\n    }\n  }\n}\n\n\/\/ Returns Attribute::None on unrecognized codes.\nstatic Attribute::AttrKind getAttrFromCode(uint64_t Code) {\n  switch (Code) {\n  default:\n    return Attribute::None;\n  case bitc::ATTR_KIND_ALIGNMENT:\n    return Attribute::Alignment;\n  case bitc::ATTR_KIND_ALWAYS_INLINE:\n    return Attribute::AlwaysInline;\n  case bitc::ATTR_KIND_ARGMEMONLY:\n    return Attribute::ArgMemOnly;\n  case bitc::ATTR_KIND_BUILTIN:\n    return Attribute::Builtin;\n  case bitc::ATTR_KIND_BY_VAL:\n    return Attribute::ByVal;\n  case bitc::ATTR_KIND_IN_ALLOCA:\n    return Attribute::InAlloca;\n  case bitc::ATTR_KIND_COLD:\n    return Attribute::Cold;\n  case bitc::ATTR_KIND_CONVERGENT:\n    return Attribute::Convergent;\n  case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION:\n    return Attribute::DisableSanitizerInstrumentation;\n  case bitc::ATTR_KIND_ELEMENTTYPE:\n    return Attribute::ElementType;\n  case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:\n    return Attribute::InaccessibleMemOnly;\n  case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:\n    return Attribute::InaccessibleMemOrArgMemOnly;\n  case bitc::ATTR_KIND_INLINE_HINT:\n    return Attribute::InlineHint;\n  case bitc::ATTR_KIND_IN_REG:\n    return Attribute::InReg;\n  case bitc::ATTR_KIND_JUMP_TABLE:\n    return Attribute::JumpTable;\n  case bitc::ATTR_KIND_MIN_SIZE:\n    return Attribute::MinSize;\n  case bitc::ATTR_KIND_NAKED:\n    return Attribute::Naked;\n  case bitc::ATTR_KIND_NEST:\n    return Attribute::Nest;\n  case bitc::ATTR_KIND_NO_ALIAS:\n    return Attribute::NoAlias;\n  case bitc::ATTR_KIND_NO_BUILTIN:\n    return Attribute::NoBuiltin;\n  case bitc::ATTR_KIND_NO_CALLBACK:\n    return Attribute::NoCallback;\n  case bitc::ATTR_KIND_NO_CAPTURE:\n    return Attribute::NoCapture;\n  case bitc::ATTR_KIND_NO_DUPLICATE:\n    return Attribute::NoDuplicate;\n  case bitc::ATTR_KIND_NOFREE:\n    return Attribute::NoFree;\n  case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:\n    return Attribute::NoImplicitFloat;\n  case bitc::ATTR_KIND_NO_INLINE:\n    return Attribute::NoInline;\n  case bitc::ATTR_KIND_NO_RECURSE:\n    return Attribute::NoRecurse;\n  case bitc::ATTR_KIND_NO_MERGE:\n    return Attribute::NoMerge;\n  case bitc::ATTR_KIND_NON_LAZY_BIND:\n    return Attribute::NonLazyBind;\n  case bitc::ATTR_KIND_NON_NULL:\n    return Attribute::NonNull;\n  case bitc::ATTR_KIND_DEREFERENCEABLE:\n    return Attribute::Dereferenceable;\n  case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:\n    return Attribute::DereferenceableOrNull;\n  case bitc::ATTR_KIND_ALLOC_ALIGN:\n    return Attribute::AllocAlign;\n  case bitc::ATTR_KIND_ALLOC_SIZE:\n    return Attribute::AllocSize;\n  case bitc::ATTR_KIND_NO_RED_ZONE:\n    return Attribute::NoRedZone;\n  case bitc::ATTR_KIND_NO_RETURN:\n    return Attribute::NoReturn;\n  case bitc::ATTR_KIND_NOSYNC:\n    return Attribute::NoSync;\n  case bitc::ATTR_KIND_NOCF_CHECK:\n    return Attribute::NoCfCheck;\n  case bitc::ATTR_KIND_NO_PROFILE:\n    return Attribute::NoProfile;\n  case bitc::ATTR_KIND_NO_UNWIND:\n    return Attribute::NoUnwind;\n  case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS:\n    return Attribute::NoSanitizeBounds;\n  case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:\n    return Attribute::NoSanitizeCoverage;\n  case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:\n    return Attribute::NullPointerIsValid;\n  case bitc::ATTR_KIND_OPT_FOR_FUZZING:\n    return Attribute::OptForFuzzing;\n  case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:\n    return Attribute::OptimizeForSize;\n  case bitc::ATTR_KIND_OPTIMIZE_NONE:\n    return Attribute::OptimizeNone;\n  case bitc::ATTR_KIND_READ_NONE:\n    return Attribute::ReadNone;\n  case bitc::ATTR_KIND_READ_ONLY:\n    return Attribute::ReadOnly;\n  case bitc::ATTR_KIND_RETURNED:\n    return Attribute::Returned;\n  case bitc::ATTR_KIND_RETURNS_TWICE:\n    return Attribute::ReturnsTwice;\n  case bitc::ATTR_KIND_S_EXT:\n    return Attribute::SExt;\n  case bitc::ATTR_KIND_SPECULATABLE:\n    return Attribute::Speculatable;\n  case bitc::ATTR_KIND_STACK_ALIGNMENT:\n    return Attribute::StackAlignment;\n  case bitc::ATTR_KIND_STACK_PROTECT:\n    return Attribute::StackProtect;\n  case bitc::ATTR_KIND_STACK_PROTECT_REQ:\n    return Attribute::StackProtectReq;\n  case bitc::ATTR_KIND_STACK_PROTECT_STRONG:\n    return Attribute::StackProtectStrong;\n  case bitc::ATTR_KIND_SAFESTACK:\n    return Attribute::SafeStack;\n  case bitc::ATTR_KIND_SHADOWCALLSTACK:\n    return Attribute::ShadowCallStack;\n  case bitc::ATTR_KIND_STRICT_FP:\n    return Attribute::StrictFP;\n  case bitc::ATTR_KIND_STRUCT_RET:\n    return Attribute::StructRet;\n  case bitc::ATTR_KIND_SANITIZE_ADDRESS:\n    return Attribute::SanitizeAddress;\n  case bitc::ATTR_KIND_SANITIZE_HWADDRESS:\n    return Attribute::SanitizeHWAddress;\n  case bitc::ATTR_KIND_SANITIZE_THREAD:\n    return Attribute::SanitizeThread;\n  case bitc::ATTR_KIND_SANITIZE_MEMORY:\n    return Attribute::SanitizeMemory;\n  case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:\n    return Attribute::SpeculativeLoadHardening;\n  case bitc::ATTR_KIND_SWIFT_ERROR:\n    return Attribute::SwiftError;\n  case bitc::ATTR_KIND_SWIFT_SELF:\n    return Attribute::SwiftSelf;\n  case bitc::ATTR_KIND_SWIFT_ASYNC:\n    return Attribute::SwiftAsync;\n  case bitc::ATTR_KIND_UW_TABLE:\n    return Attribute::UWTable;\n  case bitc::ATTR_KIND_VSCALE_RANGE:\n    return Attribute::VScaleRange;\n  case bitc::ATTR_KIND_WILLRETURN:\n    return Attribute::WillReturn;\n  case bitc::ATTR_KIND_WRITEONLY:\n    return Attribute::WriteOnly;\n  case bitc::ATTR_KIND_Z_EXT:\n    return Attribute::ZExt;\n  case bitc::ATTR_KIND_IMMARG:\n    return Attribute::ImmArg;\n  case bitc::ATTR_KIND_SANITIZE_MEMTAG:\n    return Attribute::SanitizeMemTag;\n  case bitc::ATTR_KIND_PREALLOCATED:\n    return Attribute::Preallocated;\n  case bitc::ATTR_KIND_NOUNDEF:\n    return Attribute::NoUndef;\n  case bitc::ATTR_KIND_BYREF:\n    return Attribute::ByRef;\n  case bitc::ATTR_KIND_MUSTPROGRESS:\n    return Attribute::MustProgress;\n  case bitc::ATTR_KIND_HOT:\n    return Attribute::Hot;\n  }\n}\n\nError BitcodeReader::parseAlignmentValue(uint64_t Exponent,\n                                         MaybeAlign &Alignment) {\n  \/\/ Note: Alignment in bitcode files is incremented by 1, so that zero\n  \/\/ can be used for default alignment.\n  if (Exponent > Value::MaxAlignmentExponent + 1)\n    return error(\"Invalid alignment value\");\n  Alignment = decodeMaybeAlign(Exponent);\n  return Error::success();\n}\n\nError BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {\n  *Kind = getAttrFromCode(Code);\n  if (*Kind == Attribute::None)\n    return error(\"Unknown attribute kind (\" + Twine(Code) + \")\");\n  return Error::success();\n}\n\nError BitcodeReader::parseAttributeGroupBlock() {\n  if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))\n    return Err;\n\n  if (!MAttributeGroups.empty())\n    return error(\"Invalid multiple blocks\");\n\n  SmallVector<uint64_t, 64> Record;\n\n  \/\/ Read all the records.\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return Error::success();\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Read a record.\n    Record.clear();\n    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeRecord)\n      return MaybeRecord.takeError();\n    switch (MaybeRecord.get()) {\n    default:  \/\/ Default behavior: ignore.\n      break;\n    case bitc::PARAMATTR_GRP_CODE_ENTRY: { \/\/ ENTRY: [grpid, idx, a0, a1, ...]\n      if (Record.size() < 3)\n        return error(\"Invalid grp record\");\n\n      uint64_t GrpID = Record[0];\n      uint64_t Idx = Record[1]; \/\/ Index of the object this attribute refers to.\n\n      AttrBuilder B(Context);\n      for (unsigned i = 2, e = Record.size(); i != e; ++i) {\n        if (Record[i] == 0) {        \/\/ Enum attribute\n          Attribute::AttrKind Kind;\n          if (Error Err = parseAttrKind(Record[++i], &Kind))\n            return Err;\n\n          \/\/ Upgrade old-style byval attribute to one with a type, even if it's\n          \/\/ nullptr. We will have to insert the real type when we associate\n          \/\/ this AttributeList with a function.\n          if (Kind == Attribute::ByVal)\n            B.addByValAttr(nullptr);\n          else if (Kind == Attribute::StructRet)\n            B.addStructRetAttr(nullptr);\n          else if (Kind == Attribute::InAlloca)\n            B.addInAllocaAttr(nullptr);\n          else if (Kind == Attribute::UWTable)\n            B.addUWTableAttr(UWTableKind::Default);\n          else if (Attribute::isEnumAttrKind(Kind))\n            B.addAttribute(Kind);\n          else\n            return error(\"Not an enum attribute\");\n        } else if (Record[i] == 1) { \/\/ Integer attribute\n          Attribute::AttrKind Kind;\n          if (Error Err = parseAttrKind(Record[++i], &Kind))\n            return Err;\n          if (!Attribute::isIntAttrKind(Kind))\n            return error(\"Not an int attribute\");\n          if (Kind == Attribute::Alignment)\n            B.addAlignmentAttr(Record[++i]);\n          else if (Kind == Attribute::StackAlignment)\n            B.addStackAlignmentAttr(Record[++i]);\n          else if (Kind == Attribute::Dereferenceable)\n            B.addDereferenceableAttr(Record[++i]);\n          else if (Kind == Attribute::DereferenceableOrNull)\n            B.addDereferenceableOrNullAttr(Record[++i]);\n          else if (Kind == Attribute::AllocSize)\n            B.addAllocSizeAttrFromRawRepr(Record[++i]);\n          else if (Kind == Attribute::VScaleRange)\n            B.addVScaleRangeAttrFromRawRepr(Record[++i]);\n          else if (Kind == Attribute::UWTable)\n            B.addUWTableAttr(UWTableKind(Record[++i]));\n        } else if (Record[i] == 3 || Record[i] == 4) { \/\/ String attribute\n          bool HasValue = (Record[i++] == 4);\n          SmallString<64> KindStr;\n          SmallString<64> ValStr;\n\n          while (Record[i] != 0 && i != e)\n            KindStr += Record[i++];\n          assert(Record[i] == 0 && \"Kind string not null terminated\");\n\n          if (HasValue) {\n            \/\/ Has a value associated with it.\n            ++i; \/\/ Skip the '0' that terminates the \"kind\" string.\n            while (Record[i] != 0 && i != e)\n              ValStr += Record[i++];\n            assert(Record[i] == 0 && \"Value string not null terminated\");\n          }\n\n          B.addAttribute(KindStr.str(), ValStr.str());\n        } else if (Record[i] == 5 || Record[i] == 6) {\n          bool HasType = Record[i] == 6;\n          Attribute::AttrKind Kind;\n          if (Error Err = parseAttrKind(Record[++i], &Kind))\n            return Err;\n          if (!Attribute::isTypeAttrKind(Kind))\n            return error(\"Not a type attribute\");\n\n          B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);\n        } else {\n          return error(\"Invalid attribute group entry\");\n        }\n      }\n\n      UpgradeAttributes(B);\n      MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);\n      break;\n    }\n    }\n  }\n}\n\nError BitcodeReader::parseTypeTable() {\n  if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))\n    return Err;\n\n  return parseTypeTableBody();\n}\n\nError BitcodeReader::parseTypeTableBody() {\n  if (!TypeList.empty())\n    return error(\"Invalid multiple blocks\");\n\n  SmallVector<uint64_t, 64> Record;\n  unsigned NumRecords = 0;\n\n  SmallString<64> TypeName;\n\n  \/\/ Read all the records for this type table.\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      if (NumRecords != TypeList.size())\n        return error(\"Malformed block\");\n      return Error::success();\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Read a record.\n    Record.clear();\n    Type *ResultTy = nullptr;\n    SmallVector<unsigned> ContainedIDs;\n    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeRecord)\n      return MaybeRecord.takeError();\n    switch (MaybeRecord.get()) {\n    default:\n      return error(\"Invalid value\");\n    case bitc::TYPE_CODE_NUMENTRY: \/\/ TYPE_CODE_NUMENTRY: [numentries]\n      \/\/ TYPE_CODE_NUMENTRY contains a count of the number of types in the\n      \/\/ type list.  This allows us to reserve space.\n      if (Record.empty())\n        return error(\"Invalid numentry record\");\n      TypeList.resize(Record[0]);\n      continue;\n    case bitc::TYPE_CODE_VOID:      \/\/ VOID\n      ResultTy = Type::getVoidTy(Context);\n      break;\n    case bitc::TYPE_CODE_HALF:     \/\/ HALF\n      ResultTy = Type::getHalfTy(Context);\n      break;\n    case bitc::TYPE_CODE_BFLOAT:    \/\/ BFLOAT\n      ResultTy = Type::getBFloatTy(Context);\n      break;\n    case bitc::TYPE_CODE_FLOAT:     \/\/ FLOAT\n      ResultTy = Type::getFloatTy(Context);\n      break;\n    case bitc::TYPE_CODE_DOUBLE:    \/\/ DOUBLE\n      ResultTy = Type::getDoubleTy(Context);\n      break;\n    case bitc::TYPE_CODE_X86_FP80:  \/\/ X86_FP80\n      ResultTy = Type::getX86_FP80Ty(Context);\n      break;\n    case bitc::TYPE_CODE_FP128:     \/\/ FP128\n      ResultTy = Type::getFP128Ty(Context);\n      break;\n    case bitc::TYPE_CODE_PPC_FP128: \/\/ PPC_FP128\n      ResultTy = Type::getPPC_FP128Ty(Context);\n      break;\n    case bitc::TYPE_CODE_LABEL:     \/\/ LABEL\n      ResultTy = Type::getLabelTy(Context);\n      break;\n    case bitc::TYPE_CODE_METADATA:  \/\/ METADATA\n      ResultTy = Type::getMetadataTy(Context);\n      break;\n    case bitc::TYPE_CODE_X86_MMX:   \/\/ X86_MMX\n      ResultTy = Type::getX86_MMXTy(Context);\n      break;\n    case bitc::TYPE_CODE_X86_AMX:   \/\/ X86_AMX\n      ResultTy = Type::getX86_AMXTy(Context);\n      break;\n    case bitc::TYPE_CODE_TOKEN:     \/\/ TOKEN\n      ResultTy = Type::getTokenTy(Context);\n      break;\n    case bitc::TYPE_CODE_INTEGER: { \/\/ INTEGER: [width]\n      if (Record.empty())\n        return error(\"Invalid integer record\");\n\n      uint64_t NumBits = Record[0];\n      if (NumBits < IntegerType::MIN_INT_BITS ||\n          NumBits > IntegerType::MAX_INT_BITS)\n        return error(\"Bitwidth for integer type out of range\");\n      ResultTy = IntegerType::get(Context, NumBits);\n      break;\n    }\n    case bitc::TYPE_CODE_POINTER: { \/\/ POINTER: [pointee type] or\n                                    \/\/          [pointee type, address space]\n      if (Record.empty())\n        return error(\"Invalid pointer record\");\n      unsigned AddressSpace = 0;\n      if (Record.size() == 2)\n        AddressSpace = Record[1];\n      ResultTy = getTypeByID(Record[0]);\n      if (!ResultTy ||\n          !PointerType::isValidElementType(ResultTy))\n        return error(\"Invalid type\");\n      ContainedIDs.push_back(Record[0]);\n      ResultTy = PointerType::get(ResultTy, AddressSpace);\n      break;\n    }\n    case bitc::TYPE_CODE_OPAQUE_POINTER: { \/\/ OPAQUE_POINTER: [addrspace]\n      if (Record.size() != 1)\n        return error(\"Invalid opaque pointer record\");\n      if (Context.supportsTypedPointers())\n        return error(\n            \"Opaque pointers are only supported in -opaque-pointers mode\");\n      unsigned AddressSpace = Record[0];\n      ResultTy = PointerType::get(Context, AddressSpace);\n      break;\n    }\n    case bitc::TYPE_CODE_FUNCTION_OLD: {\n      \/\/ Deprecated, but still needed to read old bitcode files.\n      \/\/ FUNCTION: [vararg, attrid, retty, paramty x N]\n      if (Record.size() < 3)\n        return error(\"Invalid function record\");\n      SmallVector<Type*, 8> ArgTys;\n      for (unsigned i = 3, e = Record.size(); i != e; ++i) {\n        if (Type *T = getTypeByID(Record[i]))\n          ArgTys.push_back(T);\n        else\n          break;\n      }\n\n      ResultTy = getTypeByID(Record[2]);\n      if (!ResultTy || ArgTys.size() < Record.size()-3)\n        return error(\"Invalid type\");\n\n      ContainedIDs.append(Record.begin() + 2, Record.end());\n      ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);\n      break;\n    }\n    case bitc::TYPE_CODE_FUNCTION: {\n      \/\/ FUNCTION: [vararg, retty, paramty x N]\n      if (Record.size() < 2)\n        return error(\"Invalid function record\");\n      SmallVector<Type*, 8> ArgTys;\n      for (unsigned i = 2, e = Record.size(); i != e; ++i) {\n        if (Type *T = getTypeByID(Record[i])) {\n          if (!FunctionType::isValidArgumentType(T))\n            return error(\"Invalid function argument type\");\n          ArgTys.push_back(T);\n        }\n        else\n          break;\n      }\n\n      ResultTy = getTypeByID(Record[1]);\n      if (!ResultTy || ArgTys.size() < Record.size()-2)\n        return error(\"Invalid type\");\n\n      ContainedIDs.append(Record.begin() + 1, Record.end());\n      ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);\n      break;\n    }\n    case bitc::TYPE_CODE_STRUCT_ANON: {  \/\/ STRUCT: [ispacked, eltty x N]\n      if (Record.empty())\n        return error(\"Invalid anon struct record\");\n      SmallVector<Type*, 8> EltTys;\n      for (unsigned i = 1, e = Record.size(); i != e; ++i) {\n        if (Type *T = getTypeByID(Record[i]))\n          EltTys.push_back(T);\n        else\n          break;\n      }\n      if (EltTys.size() != Record.size()-1)\n        return error(\"Invalid type\");\n      ContainedIDs.append(Record.begin() + 1, Record.end());\n      ResultTy = StructType::get(Context, EltTys, Record[0]);\n      break;\n    }\n    case bitc::TYPE_CODE_STRUCT_NAME:   \/\/ STRUCT_NAME: [strchr x N]\n      if (convertToString(Record, 0, TypeName))\n        return error(\"Invalid struct name record\");\n      continue;\n\n    case bitc::TYPE_CODE_STRUCT_NAMED: { \/\/ STRUCT: [ispacked, eltty x N]\n      if (Record.empty())\n        return error(\"Invalid named struct record\");\n\n      if (NumRecords >= TypeList.size())\n        return error(\"Invalid TYPE table\");\n\n      \/\/ Check to see if this was forward referenced, if so fill in the temp.\n      StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);\n      if (Res) {\n        Res->setName(TypeName);\n        TypeList[NumRecords] = nullptr;\n      } else  \/\/ Otherwise, create a new struct.\n        Res = createIdentifiedStructType(Context, TypeName);\n      TypeName.clear();\n\n      SmallVector<Type*, 8> EltTys;\n      for (unsigned i = 1, e = Record.size(); i != e; ++i) {\n        if (Type *T = getTypeByID(Record[i]))\n          EltTys.push_back(T);\n        else\n          break;\n      }\n      if (EltTys.size() != Record.size()-1)\n        return error(\"Invalid named struct record\");\n      Res->setBody(EltTys, Record[0]);\n      ContainedIDs.append(Record.begin() + 1, Record.end());\n      ResultTy = Res;\n      break;\n    }\n    case bitc::TYPE_CODE_OPAQUE: {       \/\/ OPAQUE: []\n      if (Record.size() != 1)\n        return error(\"Invalid opaque type record\");\n\n      if (NumRecords >= TypeList.size())\n        return error(\"Invalid TYPE table\");\n\n      \/\/ Check to see if this was forward referenced, if so fill in the temp.\n      StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);\n      if (Res) {\n        Res->setName(TypeName);\n        TypeList[NumRecords] = nullptr;\n      } else  \/\/ Otherwise, create a new struct with no body.\n        Res = createIdentifiedStructType(Context, TypeName);\n      TypeName.clear();\n      ResultTy = Res;\n      break;\n    }\n    case bitc::TYPE_CODE_ARRAY:     \/\/ ARRAY: [numelts, eltty]\n      if (Record.size() < 2)\n        return error(\"Invalid array type record\");\n      ResultTy = getTypeByID(Record[1]);\n      if (!ResultTy || !ArrayType::isValidElementType(ResultTy))\n        return error(\"Invalid type\");\n      ContainedIDs.push_back(Record[1]);\n      ResultTy = ArrayType::get(ResultTy, Record[0]);\n      break;\n    case bitc::TYPE_CODE_VECTOR:    \/\/ VECTOR: [numelts, eltty] or\n                                    \/\/         [numelts, eltty, scalable]\n      if (Record.size() < 2)\n        return error(\"Invalid vector type record\");\n      if (Record[0] == 0)\n        return error(\"Invalid vector length\");\n      ResultTy = getTypeByID(Record[1]);\n      if (!ResultTy || !VectorType::isValidElementType(ResultTy))\n        return error(\"Invalid type\");\n      bool Scalable = Record.size() > 2 ? Record[2] : false;\n      ContainedIDs.push_back(Record[1]);\n      ResultTy = VectorType::get(ResultTy, Record[0], Scalable);\n      break;\n    }\n\n    if (NumRecords >= TypeList.size())\n      return error(\"Invalid TYPE table\");\n    if (TypeList[NumRecords])\n      return error(\n          \"Invalid TYPE table: Only named structs can be forward referenced\");\n    assert(ResultTy && \"Didn't read a type?\");\n    TypeList[NumRecords] = ResultTy;\n    if (!ContainedIDs.empty())\n      ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);\n    ++NumRecords;\n  }\n}\n\nError BitcodeReader::parseOperandBundleTags() {\n  if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))\n    return Err;\n\n  if (!BundleTags.empty())\n    return error(\"Invalid multiple blocks\");\n\n  SmallVector<uint64_t, 64> Record;\n\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return Error::success();\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Tags are implicitly mapped to integers by their order.\n\n    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeRecord)\n      return MaybeRecord.takeError();\n    if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)\n      return error(\"Invalid operand bundle record\");\n\n    \/\/ OPERAND_BUNDLE_TAG: [strchr x N]\n    BundleTags.emplace_back();\n    if (convertToString(Record, 0, BundleTags.back()))\n      return error(\"Invalid operand bundle record\");\n    Record.clear();\n  }\n}\n\nError BitcodeReader::parseSyncScopeNames() {\n  if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))\n    return Err;\n\n  if (!SSIDs.empty())\n    return error(\"Invalid multiple synchronization scope names blocks\");\n\n  SmallVector<uint64_t, 64> Record;\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      if (SSIDs.empty())\n        return error(\"Invalid empty synchronization scope names block\");\n      return Error::success();\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Synchronization scope names are implicitly mapped to synchronization\n    \/\/ scope IDs by their order.\n\n    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeRecord)\n      return MaybeRecord.takeError();\n    if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)\n      return error(\"Invalid sync scope record\");\n\n    SmallString<16> SSN;\n    if (convertToString(Record, 0, SSN))\n      return error(\"Invalid sync scope record\");\n\n    SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));\n    Record.clear();\n  }\n}\n\n\/\/\/ Associate a value with its name from the given index in the provided record.\nExpected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,\n                                             unsigned NameIndex, Triple &TT) {\n  SmallString<128> ValueName;\n  if (convertToString(Record, NameIndex, ValueName))\n    return error(\"Invalid record\");\n  unsigned ValueID = Record[0];\n  if (ValueID >= ValueList.size() || !ValueList[ValueID])\n    return error(\"Invalid record\");\n  Value *V = ValueList[ValueID];\n\n  StringRef NameStr(ValueName.data(), ValueName.size());\n  if (NameStr.find_first_of(0) != StringRef::npos)\n    return error(\"Invalid value name\");\n  V->setName(NameStr);\n  auto *GO = dyn_cast<GlobalObject>(V);\n  if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT())\n    GO->setComdat(TheModule->getOrInsertComdat(V->getName()));\n  return V;\n}\n\n\/\/\/ Helper to note and return the current location, and jump to the given\n\/\/\/ offset.\nstatic Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,\n                                                 BitstreamCursor &Stream) {\n  \/\/ Save the current parsing location so we can jump back at the end\n  \/\/ of the VST read.\n  uint64_t CurrentBit = Stream.GetCurrentBitNo();\n  if (Error JumpFailed = Stream.JumpToBit(Offset * 32))\n    return std::move(JumpFailed);\n  Expected<BitstreamEntry> MaybeEntry = Stream.advance();\n  if (!MaybeEntry)\n    return MaybeEntry.takeError();\n  if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock ||\n      MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID)\n    return error(\"Expected value symbol table subblock\");\n  return CurrentBit;\n}\n\nvoid BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,\n                                            Function *F,\n                                            ArrayRef<uint64_t> Record) {\n  \/\/ Note that we subtract 1 here because the offset is relative to one word\n  \/\/ before the start of the identification or module block, which was\n  \/\/ historically always the start of the regular bitcode header.\n  uint64_t FuncWordOffset = Record[1] - 1;\n  uint64_t FuncBitOffset = FuncWordOffset * 32;\n  DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;\n  \/\/ Set the LastFunctionBlockBit to point to the last function block.\n  \/\/ Later when parsing is resumed after function materialization,\n  \/\/ we can simply skip that last function block.\n  if (FuncBitOffset > LastFunctionBlockBit)\n    LastFunctionBlockBit = FuncBitOffset;\n}\n\n\/\/\/ Read a new-style GlobalValue symbol table.\nError BitcodeReader::parseGlobalValueSymbolTable() {\n  unsigned FuncBitcodeOffsetDelta =\n      Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;\n\n  if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))\n    return Err;\n\n  SmallVector<uint64_t, 64> Record;\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock:\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return Error::success();\n    case BitstreamEntry::Record:\n      break;\n    }\n\n    Record.clear();\n    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeRecord)\n      return MaybeRecord.takeError();\n    switch (MaybeRecord.get()) {\n    case bitc::VST_CODE_FNENTRY: { \/\/ [valueid, offset]\n      unsigned ValueID = Record[0];\n      if (ValueID >= ValueList.size() || !ValueList[ValueID])\n        return error(\"Invalid value reference in symbol table\");\n      setDeferredFunctionInfo(FuncBitcodeOffsetDelta,\n                              cast<Function>(ValueList[ValueID]), Record);\n      break;\n    }\n    }\n  }\n}\n\n\/\/\/ Parse the value symbol table at either the current parsing location or\n\/\/\/ at the given bit offset if provided.\nError BitcodeReader::parseValueSymbolTable(uint64_t Offset) {\n  uint64_t CurrentBit;\n  \/\/ Pass in the Offset to distinguish between calling for the module-level\n  \/\/ VST (where we want to jump to the VST offset) and the function-level\n  \/\/ VST (where we don't).\n  if (Offset > 0) {\n    Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);\n    if (!MaybeCurrentBit)\n      return MaybeCurrentBit.takeError();\n    CurrentBit = MaybeCurrentBit.get();\n    \/\/ If this module uses a string table, read this as a module-level VST.\n    if (UseStrtab) {\n      if (Error Err = parseGlobalValueSymbolTable())\n        return Err;\n      if (Error JumpFailed = Stream.JumpToBit(CurrentBit))\n        return JumpFailed;\n      return Error::success();\n    }\n    \/\/ Otherwise, the VST will be in a similar format to a function-level VST,\n    \/\/ and will contain symbol names.\n  }\n\n  \/\/ Compute the delta between the bitcode indices in the VST (the word offset\n  \/\/ to the word-aligned ENTER_SUBBLOCK for the function block, and that\n  \/\/ expected by the lazy reader. The reader's EnterSubBlock expects to have\n  \/\/ already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID\n  \/\/ (size BlockIDWidth). Note that we access the stream's AbbrevID width here\n  \/\/ just before entering the VST subblock because: 1) the EnterSubBlock\n  \/\/ changes the AbbrevID width; 2) the VST block is nested within the same\n  \/\/ outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same\n  \/\/ AbbrevID width before calling EnterSubBlock; and 3) when we want to\n  \/\/ jump to the FUNCTION_BLOCK using this offset later, we don't want\n  \/\/ to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.\n  unsigned FuncBitcodeOffsetDelta =\n      Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;\n\n  if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))\n    return Err;\n\n  SmallVector<uint64_t, 64> Record;\n\n  Triple TT(TheModule->getTargetTriple());\n\n  \/\/ Read all the records for this value table.\n  SmallString<128> ValueName;\n\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      if (Offset > 0)\n        if (Error JumpFailed = Stream.JumpToBit(CurrentBit))\n          return JumpFailed;\n      return Error::success();\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Read a record.\n    Record.clear();\n    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeRecord)\n      return MaybeRecord.takeError();\n    switch (MaybeRecord.get()) {\n    default:  \/\/ Default behavior: unknown type.\n      break;\n    case bitc::VST_CODE_ENTRY: {  \/\/ VST_CODE_ENTRY: [valueid, namechar x N]\n      Expected<Value *> ValOrErr = recordValue(Record, 1, TT);\n      if (Error Err = ValOrErr.takeError())\n        return Err;\n      ValOrErr.get();\n      break;\n    }\n    case bitc::VST_CODE_FNENTRY: {\n      \/\/ VST_CODE_FNENTRY: [valueid, offset, namechar x N]\n      Expected<Value *> ValOrErr = recordValue(Record, 2, TT);\n      if (Error Err = ValOrErr.takeError())\n        return Err;\n      Value *V = ValOrErr.get();\n\n      \/\/ Ignore function offsets emitted for aliases of functions in older\n      \/\/ versions of LLVM.\n      if (auto *F = dyn_cast<Function>(V))\n        setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);\n      break;\n    }\n    case bitc::VST_CODE_BBENTRY: {\n      if (convertToString(Record, 1, ValueName))\n        return error(\"Invalid bbentry record\");\n      BasicBlock *BB = getBasicBlock(Record[0]);\n      if (!BB)\n        return error(\"Invalid bbentry record\");\n\n      BB->setName(StringRef(ValueName.data(), ValueName.size()));\n      ValueName.clear();\n      break;\n    }\n    }\n  }\n}\n\n\/\/\/ Decode a signed value stored with the sign bit in the LSB for dense VBR\n\/\/\/ encoding.\nuint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {\n  if ((V & 1) == 0)\n    return V >> 1;\n  if (V != 1)\n    return -(V >> 1);\n  \/\/ There is no such thing as -0 with integers.  \"-0\" really means MININT.\n  return 1ULL << 63;\n}\n\n\/\/\/ Resolve all of the initializers for global values and aliases that we can.\nError BitcodeReader::resolveGlobalAndIndirectSymbolInits() {\n  std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;\n  std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;\n  std::vector<FunctionOperandInfo> FunctionOperandWorklist;\n\n  GlobalInitWorklist.swap(GlobalInits);\n  IndirectSymbolInitWorklist.swap(IndirectSymbolInits);\n  FunctionOperandWorklist.swap(FunctionOperands);\n\n  while (!GlobalInitWorklist.empty()) {\n    unsigned ValID = GlobalInitWorklist.back().second;\n    if (ValID >= ValueList.size()) {\n      \/\/ Not ready to resolve this yet, it requires something later in the file.\n      GlobalInits.push_back(GlobalInitWorklist.back());\n    } else {\n      if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))\n        GlobalInitWorklist.back().first->setInitializer(C);\n      else\n        return error(\"Expected a constant\");\n    }\n    GlobalInitWorklist.pop_back();\n  }\n\n  while (!IndirectSymbolInitWorklist.empty()) {\n    unsigned ValID = IndirectSymbolInitWorklist.back().second;\n    if (ValID >= ValueList.size()) {\n      IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());\n    } else {\n      Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);\n      if (!C)\n        return error(\"Expected a constant\");\n      GlobalValue *GV = IndirectSymbolInitWorklist.back().first;\n      if (auto *GA = dyn_cast<GlobalAlias>(GV)) {\n        if (C->getType() != GV->getType())\n          return error(\"Alias and aliasee types don't match\");\n        GA->setAliasee(C);\n      } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {\n        Type *ResolverFTy =\n            GlobalIFunc::getResolverFunctionType(GI->getValueType());\n        \/\/ Transparently fix up the type for compatiblity with older bitcode\n        GI->setResolver(\n            ConstantExpr::getBitCast(C, ResolverFTy->getPointerTo()));\n      } else {\n        return error(\"Expected an alias or an ifunc\");\n      }\n    }\n    IndirectSymbolInitWorklist.pop_back();\n  }\n\n  while (!FunctionOperandWorklist.empty()) {\n    FunctionOperandInfo &Info = FunctionOperandWorklist.back();\n    if (Info.PersonalityFn) {\n      unsigned ValID = Info.PersonalityFn - 1;\n      if (ValID < ValueList.size()) {\n        if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))\n          Info.F->setPersonalityFn(C);\n        else\n          return error(\"Expected a constant\");\n        Info.PersonalityFn = 0;\n      }\n    }\n    if (Info.Prefix) {\n      unsigned ValID = Info.Prefix - 1;\n      if (ValID < ValueList.size()) {\n        if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))\n          Info.F->setPrefixData(C);\n        else\n          return error(\"Expected a constant\");\n        Info.Prefix = 0;\n      }\n    }\n    if (Info.Prologue) {\n      unsigned ValID = Info.Prologue - 1;\n      if (ValID < ValueList.size()) {\n        if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))\n          Info.F->setPrologueData(C);\n        else\n          return error(\"Expected a constant\");\n        Info.Prologue = 0;\n      }\n    }\n    if (Info.PersonalityFn || Info.Prefix || Info.Prologue)\n      FunctionOperands.push_back(Info);\n    FunctionOperandWorklist.pop_back();\n  }\n\n  return Error::success();\n}\n\nAPInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {\n  SmallVector<uint64_t, 8> Words(Vals.size());\n  transform(Vals, Words.begin(),\n                 BitcodeReader::decodeSignRotatedValue);\n\n  return APInt(TypeBits, Words);\n}\n\nError BitcodeReader::parseConstants() {\n  if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))\n    return Err;\n\n  SmallVector<uint64_t, 64> Record;\n\n  \/\/ Read all the records for this value table.\n  Type *CurTy = Type::getInt32Ty(Context);\n  unsigned Int32TyID = getVirtualTypeID(CurTy);\n  unsigned CurTyID = Int32TyID;\n  Type *CurElemTy = nullptr;\n  unsigned NextCstNo = ValueList.size();\n\n  struct DelayedShufTy {\n    VectorType *OpTy;\n    unsigned OpTyID;\n    VectorType *RTy;\n    uint64_t Op0Idx;\n    uint64_t Op1Idx;\n    uint64_t Op2Idx;\n    unsigned CstNo;\n  };\n  std::vector<DelayedShufTy> DelayedShuffles;\n  struct DelayedSelTy {\n    Type *OpTy;\n    unsigned OpTyID;\n    uint64_t Op0Idx;\n    uint64_t Op1Idx;\n    uint64_t Op2Idx;\n    unsigned CstNo;\n  };\n  std::vector<DelayedSelTy> DelayedSelectors;\n\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      \/\/ Once all the constants have been read, go through and resolve forward\n      \/\/ references.\n      \/\/\n      \/\/ We have to treat shuffles specially because they don't have three\n      \/\/ operands anymore.  We need to convert the shuffle mask into an array,\n      \/\/ and we can't convert a forward reference.\n      for (auto &DelayedShuffle : DelayedShuffles) {\n        VectorType *OpTy = DelayedShuffle.OpTy;\n        unsigned OpTyID = DelayedShuffle.OpTyID;\n        VectorType *RTy = DelayedShuffle.RTy;\n        uint64_t Op0Idx = DelayedShuffle.Op0Idx;\n        uint64_t Op1Idx = DelayedShuffle.Op1Idx;\n        uint64_t Op2Idx = DelayedShuffle.Op2Idx;\n        uint64_t CstNo = DelayedShuffle.CstNo;\n        Constant *Op0 = ValueList.getConstantFwdRef(Op0Idx, OpTy, OpTyID);\n        Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy, OpTyID);\n        Type *ShufTy =\n            VectorType::get(Type::getInt32Ty(Context), RTy->getElementCount());\n        Constant *Op2 = ValueList.getConstantFwdRef(\n            Op2Idx, ShufTy, getVirtualTypeID(ShufTy, Int32TyID));\n        if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))\n          return error(\"Invalid shufflevector operands\");\n        SmallVector<int, 16> Mask;\n        ShuffleVectorInst::getShuffleMask(Op2, Mask);\n        Value *V = ConstantExpr::getShuffleVector(Op0, Op1, Mask);\n        if (Error Err = ValueList.assignValue(\n                CstNo, V,\n                getVirtualTypeID(V->getType(), getContainedTypeID(OpTyID))))\n          return Err;\n      }\n      for (auto &DelayedSelector : DelayedSelectors) {\n        Type *OpTy = DelayedSelector.OpTy;\n        unsigned OpTyID = DelayedSelector.OpTyID;\n        Type *SelectorTy = Type::getInt1Ty(Context);\n        unsigned SelectorTyID = getVirtualTypeID(SelectorTy);\n        uint64_t Op0Idx = DelayedSelector.Op0Idx;\n        uint64_t Op1Idx = DelayedSelector.Op1Idx;\n        uint64_t Op2Idx = DelayedSelector.Op2Idx;\n        uint64_t CstNo = DelayedSelector.CstNo;\n        Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy, OpTyID);\n        Constant *Op2 = ValueList.getConstantFwdRef(Op2Idx, OpTy, OpTyID);\n        \/\/ The selector might be an i1 or an <n x i1>\n        \/\/ Get the type from the ValueList before getting a forward ref.\n        if (VectorType *VTy = dyn_cast<VectorType>(OpTy)) {\n          Value *V = ValueList[Op0Idx];\n          assert(V);\n          if (SelectorTy != V->getType()) {\n            SelectorTy = VectorType::get(SelectorTy, VTy->getElementCount());\n            SelectorTyID = getVirtualTypeID(SelectorTy, SelectorTyID);\n          }\n        }\n        Constant *Op0 =\n            ValueList.getConstantFwdRef(Op0Idx, SelectorTy, SelectorTyID);\n        Value *V = ConstantExpr::getSelect(Op0, Op1, Op2);\n        if (Error Err = ValueList.assignValue(CstNo, V, OpTyID))\n          return Err;\n      }\n\n      if (NextCstNo != ValueList.size())\n        return error(\"Invalid constant reference\");\n\n      ValueList.resolveConstantForwardRefs();\n      return Error::success();\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Read a record.\n    Record.clear();\n    Type *VoidType = Type::getVoidTy(Context);\n    Value *V = nullptr;\n    Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeBitCode)\n      return MaybeBitCode.takeError();\n    switch (unsigned BitCode = MaybeBitCode.get()) {\n    default:  \/\/ Default behavior: unknown constant\n    case bitc::CST_CODE_UNDEF:     \/\/ UNDEF\n      V = UndefValue::get(CurTy);\n      break;\n    case bitc::CST_CODE_POISON:    \/\/ POISON\n      V = PoisonValue::get(CurTy);\n      break;\n    case bitc::CST_CODE_SETTYPE:   \/\/ SETTYPE: [typeid]\n      if (Record.empty())\n        return error(\"Invalid settype record\");\n      if (Record[0] >= TypeList.size() || !TypeList[Record[0]])\n        return error(\"Invalid settype record\");\n      if (TypeList[Record[0]] == VoidType)\n        return error(\"Invalid constant type\");\n      CurTyID = Record[0];\n      CurTy = TypeList[CurTyID];\n      CurElemTy = getPtrElementTypeByID(CurTyID);\n      continue;  \/\/ Skip the ValueList manipulation.\n    case bitc::CST_CODE_NULL:      \/\/ NULL\n      if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())\n        return error(\"Invalid type for a constant null value\");\n      V = Constant::getNullValue(CurTy);\n      break;\n    case bitc::CST_CODE_INTEGER:   \/\/ INTEGER: [intval]\n      if (!CurTy->isIntegerTy() || Record.empty())\n        return error(\"Invalid integer const record\");\n      V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));\n      break;\n    case bitc::CST_CODE_WIDE_INTEGER: {\/\/ WIDE_INTEGER: [n x intval]\n      if (!CurTy->isIntegerTy() || Record.empty())\n        return error(\"Invalid wide integer const record\");\n\n      APInt VInt =\n          readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());\n      V = ConstantInt::get(Context, VInt);\n\n      break;\n    }\n    case bitc::CST_CODE_FLOAT: {    \/\/ FLOAT: [fpval]\n      if (Record.empty())\n        return error(\"Invalid float const record\");\n      if (CurTy->isHalfTy())\n        V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),\n                                             APInt(16, (uint16_t)Record[0])));\n      else if (CurTy->isBFloatTy())\n        V = ConstantFP::get(Context, APFloat(APFloat::BFloat(),\n                                             APInt(16, (uint32_t)Record[0])));\n      else if (CurTy->isFloatTy())\n        V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),\n                                             APInt(32, (uint32_t)Record[0])));\n      else if (CurTy->isDoubleTy())\n        V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),\n                                             APInt(64, Record[0])));\n      else if (CurTy->isX86_FP80Ty()) {\n        \/\/ Bits are not stored the same way as a normal i80 APInt, compensate.\n        uint64_t Rearrange[2];\n        Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);\n        Rearrange[1] = Record[0] >> 48;\n        V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),\n                                             APInt(80, Rearrange)));\n      } else if (CurTy->isFP128Ty())\n        V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),\n                                             APInt(128, Record)));\n      else if (CurTy->isPPC_FP128Ty())\n        V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),\n                                             APInt(128, Record)));\n      else\n        V = UndefValue::get(CurTy);\n      break;\n    }\n\n    case bitc::CST_CODE_AGGREGATE: {\/\/ AGGREGATE: [n x value number]\n      if (Record.empty())\n        return error(\"Invalid aggregate record\");\n\n      unsigned Size = Record.size();\n      SmallVector<Constant*, 16> Elts;\n\n      if (StructType *STy = dyn_cast<StructType>(CurTy)) {\n        for (unsigned i = 0; i != Size; ++i)\n          Elts.push_back(ValueList.getConstantFwdRef(\n              Record[i], STy->getElementType(i),\n              getContainedTypeID(CurTyID, i)));\n        V = ConstantStruct::get(STy, Elts);\n      } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {\n        Type *EltTy = ATy->getElementType();\n        unsigned EltTyID = getContainedTypeID(CurTyID);\n        for (unsigned i = 0; i != Size; ++i)\n          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy,\n                                                     EltTyID));\n        V = ConstantArray::get(ATy, Elts);\n      } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {\n        Type *EltTy = VTy->getElementType();\n        unsigned EltTyID = getContainedTypeID(CurTyID);\n        for (unsigned i = 0; i != Size; ++i)\n          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy,\n                                                     EltTyID));\n        V = ConstantVector::get(Elts);\n      } else {\n        V = UndefValue::get(CurTy);\n      }\n      break;\n    }\n    case bitc::CST_CODE_STRING:    \/\/ STRING: [values]\n    case bitc::CST_CODE_CSTRING: { \/\/ CSTRING: [values]\n      if (Record.empty())\n        return error(\"Invalid string record\");\n\n      SmallString<16> Elts(Record.begin(), Record.end());\n      V = ConstantDataArray::getString(Context, Elts,\n                                       BitCode == bitc::CST_CODE_CSTRING);\n      break;\n    }\n    case bitc::CST_CODE_DATA: {\/\/ DATA: [n x value]\n      if (Record.empty())\n        return error(\"Invalid data record\");\n\n      Type *EltTy;\n      if (auto *Array = dyn_cast<ArrayType>(CurTy))\n        EltTy = Array->getElementType();\n      else\n        EltTy = cast<VectorType>(CurTy)->getElementType();\n      if (EltTy->isIntegerTy(8)) {\n        SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());\n        if (isa<VectorType>(CurTy))\n          V = ConstantDataVector::get(Context, Elts);\n        else\n          V = ConstantDataArray::get(Context, Elts);\n      } else if (EltTy->isIntegerTy(16)) {\n        SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());\n        if (isa<VectorType>(CurTy))\n          V = ConstantDataVector::get(Context, Elts);\n        else\n          V = ConstantDataArray::get(Context, Elts);\n      } else if (EltTy->isIntegerTy(32)) {\n        SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());\n        if (isa<VectorType>(CurTy))\n          V = ConstantDataVector::get(Context, Elts);\n        else\n          V = ConstantDataArray::get(Context, Elts);\n      } else if (EltTy->isIntegerTy(64)) {\n        SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());\n        if (isa<VectorType>(CurTy))\n          V = ConstantDataVector::get(Context, Elts);\n        else\n          V = ConstantDataArray::get(Context, Elts);\n      } else if (EltTy->isHalfTy()) {\n        SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());\n        if (isa<VectorType>(CurTy))\n          V = ConstantDataVector::getFP(EltTy, Elts);\n        else\n          V = ConstantDataArray::getFP(EltTy, Elts);\n      } else if (EltTy->isBFloatTy()) {\n        SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());\n        if (isa<VectorType>(CurTy))\n          V = ConstantDataVector::getFP(EltTy, Elts);\n        else\n          V = ConstantDataArray::getFP(EltTy, Elts);\n      } else if (EltTy->isFloatTy()) {\n        SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());\n        if (isa<VectorType>(CurTy))\n          V = ConstantDataVector::getFP(EltTy, Elts);\n        else\n          V = ConstantDataArray::getFP(EltTy, Elts);\n      } else if (EltTy->isDoubleTy()) {\n        SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());\n        if (isa<VectorType>(CurTy))\n          V = ConstantDataVector::getFP(EltTy, Elts);\n        else\n          V = ConstantDataArray::getFP(EltTy, Elts);\n      } else {\n        return error(\"Invalid type for value\");\n      }\n      break;\n    }\n    case bitc::CST_CODE_CE_UNOP: {  \/\/ CE_UNOP: [opcode, opval]\n      if (Record.size() < 2)\n        return error(\"Invalid unary op constexpr record\");\n      int Opc = getDecodedUnaryOpcode(Record[0], CurTy);\n      if (Opc < 0) {\n        V = UndefValue::get(CurTy);  \/\/ Unknown unop.\n      } else {\n        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy, CurTyID);\n        unsigned Flags = 0;\n        V = ConstantExpr::get(Opc, LHS, Flags);\n      }\n      break;\n    }\n    case bitc::CST_CODE_CE_BINOP: {  \/\/ CE_BINOP: [opcode, opval, opval]\n      if (Record.size() < 3)\n        return error(\"Invalid binary op constexpr record\");\n      int Opc = getDecodedBinaryOpcode(Record[0], CurTy);\n      if (Opc < 0) {\n        V = UndefValue::get(CurTy);  \/\/ Unknown binop.\n      } else {\n        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy, CurTyID);\n        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy, CurTyID);\n        unsigned Flags = 0;\n        if (Record.size() >= 4) {\n          if (Opc == Instruction::Add ||\n              Opc == Instruction::Sub ||\n              Opc == Instruction::Mul ||\n              Opc == Instruction::Shl) {\n            if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))\n              Flags |= OverflowingBinaryOperator::NoSignedWrap;\n            if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))\n              Flags |= OverflowingBinaryOperator::NoUnsignedWrap;\n          } else if (Opc == Instruction::SDiv ||\n                     Opc == Instruction::UDiv ||\n                     Opc == Instruction::LShr ||\n                     Opc == Instruction::AShr) {\n            if (Record[3] & (1 << bitc::PEO_EXACT))\n              Flags |= SDivOperator::IsExact;\n          }\n        }\n        V = ConstantExpr::get(Opc, LHS, RHS, Flags);\n      }\n      break;\n    }\n    case bitc::CST_CODE_CE_CAST: {  \/\/ CE_CAST: [opcode, opty, opval]\n      if (Record.size() < 3)\n        return error(\"Invalid cast constexpr record\");\n      int Opc = getDecodedCastOpcode(Record[0]);\n      if (Opc < 0) {\n        V = UndefValue::get(CurTy);  \/\/ Unknown cast.\n      } else {\n        unsigned OpTyID = Record[1];\n        Type *OpTy = getTypeByID(OpTyID);\n        if (!OpTy)\n          return error(\"Invalid cast constexpr record\");\n        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy, OpTyID);\n        V = UpgradeBitCastExpr(Opc, Op, CurTy);\n        if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);\n      }\n      break;\n    }\n    case bitc::CST_CODE_CE_INBOUNDS_GEP: \/\/ [ty, n x operands]\n    case bitc::CST_CODE_CE_GEP: \/\/ [ty, n x operands]\n    case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { \/\/ [ty, flags, n x\n                                                     \/\/ operands]\n      if (Record.size() < 2)\n        return error(\"Constant GEP record must have at least two elements\");\n      unsigned OpNum = 0;\n      Type *PointeeType = nullptr;\n      if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||\n          Record.size() % 2)\n        PointeeType = getTypeByID(Record[OpNum++]);\n\n      bool InBounds = false;\n      Optional<unsigned> InRangeIndex;\n      if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {\n        uint64_t Op = Record[OpNum++];\n        InBounds = Op & 1;\n        InRangeIndex = Op >> 1;\n      } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)\n        InBounds = true;\n\n      SmallVector<Constant*, 16> Elts;\n      unsigned BaseTypeID = Record[OpNum];\n      while (OpNum != Record.size()) {\n        unsigned ElTyID = Record[OpNum++];\n        Type *ElTy = getTypeByID(ElTyID);\n        if (!ElTy)\n          return error(\"Invalid getelementptr constexpr record\");\n        Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy,\n                                                   ElTyID));\n      }\n\n      if (Elts.size() < 1)\n        return error(\"Invalid gep with no operands\");\n\n      Type *BaseType = getTypeByID(BaseTypeID);\n      if (isa<VectorType>(BaseType)) {\n        BaseTypeID = getContainedTypeID(BaseTypeID, 0);\n        BaseType = getTypeByID(BaseTypeID);\n      }\n\n      PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType);\n      if (!OrigPtrTy)\n        return error(\"GEP base operand must be pointer or vector of pointer\");\n\n      if (!PointeeType) {\n        PointeeType = getPtrElementTypeByID(BaseTypeID);\n        if (!PointeeType)\n          return error(\"Missing element type for old-style constant GEP\");\n      } else if (!OrigPtrTy->isOpaqueOrPointeeTypeMatches(PointeeType))\n        return error(\"Explicit gep operator type does not match pointee type \"\n                     \"of pointer operand\");\n\n      ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());\n      V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,\n                                         InBounds, InRangeIndex);\n      break;\n    }\n    case bitc::CST_CODE_CE_SELECT: {  \/\/ CE_SELECT: [opval#, opval#, opval#]\n      if (Record.size() < 3)\n        return error(\"Invalid select constexpr record\");\n\n      DelayedSelectors.push_back(\n          {CurTy, CurTyID, Record[0], Record[1], Record[2], NextCstNo});\n      (void)ValueList.getConstantFwdRef(NextCstNo, CurTy, CurTyID);\n      ++NextCstNo;\n      continue;\n    }\n    case bitc::CST_CODE_CE_EXTRACTELT\n        : { \/\/ CE_EXTRACTELT: [opty, opval, opty, opval]\n      if (Record.size() < 3)\n        return error(\"Invalid extractelement constexpr record\");\n      unsigned OpTyID = Record[0];\n      VectorType *OpTy =\n        dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));\n      if (!OpTy)\n        return error(\"Invalid extractelement constexpr record\");\n      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy, OpTyID);\n      Constant *Op1 = nullptr;\n      if (Record.size() == 4) {\n        unsigned IdxTyID = Record[2];\n        Type *IdxTy = getTypeByID(IdxTyID);\n        if (!IdxTy)\n          return error(\"Invalid extractelement constexpr record\");\n        Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy, IdxTyID);\n      } else {\n        \/\/ Deprecated, but still needed to read old bitcode files.\n        Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context),\n                                          Int32TyID);\n      }\n      if (!Op1)\n        return error(\"Invalid extractelement constexpr record\");\n      V = ConstantExpr::getExtractElement(Op0, Op1);\n      break;\n    }\n    case bitc::CST_CODE_CE_INSERTELT\n        : { \/\/ CE_INSERTELT: [opval, opval, opty, opval]\n      VectorType *OpTy = dyn_cast<VectorType>(CurTy);\n      if (Record.size() < 3 || !OpTy)\n        return error(\"Invalid insertelement constexpr record\");\n      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy, CurTyID);\n      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],\n                                                  OpTy->getElementType(),\n                                                  getContainedTypeID(CurTyID));\n      Constant *Op2 = nullptr;\n      if (Record.size() == 4) {\n        unsigned IdxTyID = Record[2];\n        Type *IdxTy = getTypeByID(IdxTyID);\n        if (!IdxTy)\n          return error(\"Invalid insertelement constexpr record\");\n        Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy, IdxTyID);\n      } else {\n        \/\/ Deprecated, but still needed to read old bitcode files.\n        Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context),\n                                          Int32TyID);\n      }\n      if (!Op2)\n        return error(\"Invalid insertelement constexpr record\");\n      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);\n      break;\n    }\n    case bitc::CST_CODE_CE_SHUFFLEVEC: { \/\/ CE_SHUFFLEVEC: [opval, opval, opval]\n      VectorType *OpTy = dyn_cast<VectorType>(CurTy);\n      if (Record.size() < 3 || !OpTy)\n        return error(\"Invalid shufflevector constexpr record\");\n      DelayedShuffles.push_back(\n          {OpTy, CurTyID, OpTy, Record[0], Record[1], Record[2], NextCstNo});\n      ++NextCstNo;\n      continue;\n    }\n    case bitc::CST_CODE_CE_SHUFVEC_EX: { \/\/ [opty, opval, opval, opval]\n      VectorType *RTy = dyn_cast<VectorType>(CurTy);\n      VectorType *OpTy =\n        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));\n      if (Record.size() < 4 || !RTy || !OpTy)\n        return error(\"Invalid shufflevector constexpr record\");\n      DelayedShuffles.push_back(\n          {OpTy, CurTyID, RTy, Record[1], Record[2], Record[3], NextCstNo});\n      ++NextCstNo;\n      continue;\n    }\n    case bitc::CST_CODE_CE_CMP: {     \/\/ CE_CMP: [opty, opval, opval, pred]\n      if (Record.size() < 4)\n        return error(\"Invalid cmp constexpt record\");\n      unsigned OpTyID = Record[0];\n      Type *OpTy = getTypeByID(OpTyID);\n      if (!OpTy)\n        return error(\"Invalid cmp constexpr record\");\n      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy, OpTyID);\n      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy, OpTyID);\n\n      if (OpTy->isFPOrFPVectorTy())\n        V = ConstantExpr::getFCmp(Record[3], Op0, Op1);\n      else\n        V = ConstantExpr::getICmp(Record[3], Op0, Op1);\n      break;\n    }\n    \/\/ This maintains backward compatibility, pre-asm dialect keywords.\n    \/\/ Deprecated, but still needed to read old bitcode files.\n    case bitc::CST_CODE_INLINEASM_OLD: {\n      if (Record.size() < 2)\n        return error(\"Invalid inlineasm record\");\n      std::string AsmStr, ConstrStr;\n      bool HasSideEffects = Record[0] & 1;\n      bool IsAlignStack = Record[0] >> 1;\n      unsigned AsmStrSize = Record[1];\n      if (2+AsmStrSize >= Record.size())\n        return error(\"Invalid inlineasm record\");\n      unsigned ConstStrSize = Record[2+AsmStrSize];\n      if (3+AsmStrSize+ConstStrSize > Record.size())\n        return error(\"Invalid inlineasm record\");\n\n      for (unsigned i = 0; i != AsmStrSize; ++i)\n        AsmStr += (char)Record[2+i];\n      for (unsigned i = 0; i != ConstStrSize; ++i)\n        ConstrStr += (char)Record[3+AsmStrSize+i];\n      UpgradeInlineAsmString(&AsmStr);\n      if (!CurElemTy)\n        return error(\"Missing element type for old-style inlineasm\");\n      V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,\n                         HasSideEffects, IsAlignStack);\n      break;\n    }\n    \/\/ This version adds support for the asm dialect keywords (e.g.,\n    \/\/ inteldialect).\n    case bitc::CST_CODE_INLINEASM_OLD2: {\n      if (Record.size() < 2)\n        return error(\"Invalid inlineasm record\");\n      std::string AsmStr, ConstrStr;\n      bool HasSideEffects = Record[0] & 1;\n      bool IsAlignStack = (Record[0] >> 1) & 1;\n      unsigned AsmDialect = Record[0] >> 2;\n      unsigned AsmStrSize = Record[1];\n      if (2+AsmStrSize >= Record.size())\n        return error(\"Invalid inlineasm record\");\n      unsigned ConstStrSize = Record[2+AsmStrSize];\n      if (3+AsmStrSize+ConstStrSize > Record.size())\n        return error(\"Invalid inlineasm record\");\n\n      for (unsigned i = 0; i != AsmStrSize; ++i)\n        AsmStr += (char)Record[2+i];\n      for (unsigned i = 0; i != ConstStrSize; ++i)\n        ConstrStr += (char)Record[3+AsmStrSize+i];\n      UpgradeInlineAsmString(&AsmStr);\n      if (!CurElemTy)\n        return error(\"Missing element type for old-style inlineasm\");\n      V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,\n                         HasSideEffects, IsAlignStack,\n                         InlineAsm::AsmDialect(AsmDialect));\n      break;\n    }\n    \/\/ This version adds support for the unwind keyword.\n    case bitc::CST_CODE_INLINEASM_OLD3: {\n      if (Record.size() < 2)\n        return error(\"Invalid inlineasm record\");\n      unsigned OpNum = 0;\n      std::string AsmStr, ConstrStr;\n      bool HasSideEffects = Record[OpNum] & 1;\n      bool IsAlignStack = (Record[OpNum] >> 1) & 1;\n      unsigned AsmDialect = (Record[OpNum] >> 2) & 1;\n      bool CanThrow = (Record[OpNum] >> 3) & 1;\n      ++OpNum;\n      unsigned AsmStrSize = Record[OpNum];\n      ++OpNum;\n      if (OpNum + AsmStrSize >= Record.size())\n        return error(\"Invalid inlineasm record\");\n      unsigned ConstStrSize = Record[OpNum + AsmStrSize];\n      if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())\n        return error(\"Invalid inlineasm record\");\n\n      for (unsigned i = 0; i != AsmStrSize; ++i)\n        AsmStr += (char)Record[OpNum + i];\n      ++OpNum;\n      for (unsigned i = 0; i != ConstStrSize; ++i)\n        ConstrStr += (char)Record[OpNum + AsmStrSize + i];\n      UpgradeInlineAsmString(&AsmStr);\n      if (!CurElemTy)\n        return error(\"Missing element type for old-style inlineasm\");\n      V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,\n                         HasSideEffects, IsAlignStack,\n                         InlineAsm::AsmDialect(AsmDialect), CanThrow);\n      break;\n    }\n    \/\/ This version adds explicit function type.\n    case bitc::CST_CODE_INLINEASM: {\n      if (Record.size() < 3)\n        return error(\"Invalid inlineasm record\");\n      unsigned OpNum = 0;\n      auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));\n      ++OpNum;\n      if (!FnTy)\n        return error(\"Invalid inlineasm record\");\n      std::string AsmStr, ConstrStr;\n      bool HasSideEffects = Record[OpNum] & 1;\n      bool IsAlignStack = (Record[OpNum] >> 1) & 1;\n      unsigned AsmDialect = (Record[OpNum] >> 2) & 1;\n      bool CanThrow = (Record[OpNum] >> 3) & 1;\n      ++OpNum;\n      unsigned AsmStrSize = Record[OpNum];\n      ++OpNum;\n      if (OpNum + AsmStrSize >= Record.size())\n        return error(\"Invalid inlineasm record\");\n      unsigned ConstStrSize = Record[OpNum + AsmStrSize];\n      if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())\n        return error(\"Invalid inlineasm record\");\n\n      for (unsigned i = 0; i != AsmStrSize; ++i)\n        AsmStr += (char)Record[OpNum + i];\n      ++OpNum;\n      for (unsigned i = 0; i != ConstStrSize; ++i)\n        ConstrStr += (char)Record[OpNum + AsmStrSize + i];\n      UpgradeInlineAsmString(&AsmStr);\n      V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,\n                         InlineAsm::AsmDialect(AsmDialect), CanThrow);\n      break;\n    }\n    case bitc::CST_CODE_BLOCKADDRESS:{\n      if (Record.size() < 3)\n        return error(\"Invalid blockaddress record\");\n      unsigned FnTyID = Record[0];\n      Type *FnTy = getTypeByID(FnTyID);\n      if (!FnTy)\n        return error(\"Invalid blockaddress record\");\n      Function *Fn = dyn_cast_or_null<Function>(\n          ValueList.getConstantFwdRef(Record[1], FnTy, FnTyID));\n      if (!Fn)\n        return error(\"Invalid blockaddress record\");\n\n      \/\/ If the function is already parsed we can insert the block address right\n      \/\/ away.\n      BasicBlock *BB;\n      unsigned BBID = Record[2];\n      if (!BBID)\n        \/\/ Invalid reference to entry block.\n        return error(\"Invalid ID\");\n      if (!Fn->empty()) {\n        Function::iterator BBI = Fn->begin(), BBE = Fn->end();\n        for (size_t I = 0, E = BBID; I != E; ++I) {\n          if (BBI == BBE)\n            return error(\"Invalid ID\");\n          ++BBI;\n        }\n        BB = &*BBI;\n      } else {\n        \/\/ Otherwise insert a placeholder and remember it so it can be inserted\n        \/\/ when the function is parsed.\n        auto &FwdBBs = BasicBlockFwdRefs[Fn];\n        if (FwdBBs.empty())\n          BasicBlockFwdRefQueue.push_back(Fn);\n        if (FwdBBs.size() < BBID + 1)\n          FwdBBs.resize(BBID + 1);\n        if (!FwdBBs[BBID])\n          FwdBBs[BBID] = BasicBlock::Create(Context);\n        BB = FwdBBs[BBID];\n      }\n      V = BlockAddress::get(Fn, BB);\n      break;\n    }\n    case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {\n      if (Record.size() < 2)\n        return error(\"Invalid dso_local record\");\n      unsigned GVTyID = Record[0];\n      Type *GVTy = getTypeByID(GVTyID);\n      if (!GVTy)\n        return error(\"Invalid dso_local record\");\n      GlobalValue *GV = dyn_cast_or_null<GlobalValue>(\n          ValueList.getConstantFwdRef(Record[1], GVTy, GVTyID));\n      if (!GV)\n        return error(\"Invalid dso_local record\");\n\n      V = DSOLocalEquivalent::get(GV);\n      break;\n    }\n    case bitc::CST_CODE_NO_CFI_VALUE: {\n      if (Record.size() < 2)\n        return error(\"Invalid no_cfi record\");\n      unsigned GVTyID = Record[0];\n      Type *GVTy = getTypeByID(GVTyID);\n      if (!GVTy)\n        return error(\"Invalid no_cfi record\");\n      GlobalValue *GV = dyn_cast_or_null<GlobalValue>(\n          ValueList.getConstantFwdRef(Record[1], GVTy, GVTyID));\n      if (!GV)\n        return error(\"Invalid no_cfi record\");\n      V = NoCFIValue::get(GV);\n      break;\n    }\n    }\n\n    assert(V->getType() == getTypeByID(CurTyID) && \"Incorrect result type ID\");\n    if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID))\n      return Err;\n    ++NextCstNo;\n  }\n}\n\nError BitcodeReader::parseUseLists() {\n  if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))\n    return Err;\n\n  \/\/ Read all the records.\n  SmallVector<uint64_t, 64> Record;\n\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return Error::success();\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Read a use list record.\n    Record.clear();\n    bool IsBB = false;\n    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeRecord)\n      return MaybeRecord.takeError();\n    switch (MaybeRecord.get()) {\n    default:  \/\/ Default behavior: unknown type.\n      break;\n    case bitc::USELIST_CODE_BB:\n      IsBB = true;\n      LLVM_FALLTHROUGH;\n    case bitc::USELIST_CODE_DEFAULT: {\n      unsigned RecordLength = Record.size();\n      if (RecordLength < 3)\n        \/\/ Records should have at least an ID and two indexes.\n        return error(\"Invalid record\");\n      unsigned ID = Record.pop_back_val();\n\n      Value *V;\n      if (IsBB) {\n        assert(ID < FunctionBBs.size() && \"Basic block not found\");\n        V = FunctionBBs[ID];\n      } else\n        V = ValueList[ID];\n      unsigned NumUses = 0;\n      SmallDenseMap<const Use *, unsigned, 16> Order;\n      for (const Use &U : V->materialized_uses()) {\n        if (++NumUses > Record.size())\n          break;\n        Order[&U] = Record[NumUses - 1];\n      }\n      if (Order.size() != Record.size() || NumUses > Record.size())\n        \/\/ Mismatches can happen if the functions are being materialized lazily\n        \/\/ (out-of-order), or a value has been upgraded.\n        break;\n\n      V->sortUseList([&](const Use &L, const Use &R) {\n        return Order.lookup(&L) < Order.lookup(&R);\n      });\n      break;\n    }\n    }\n  }\n}\n\n\/\/\/ When we see the block for metadata, remember where it is and then skip it.\n\/\/\/ This lets us lazily deserialize the metadata.\nError BitcodeReader::rememberAndSkipMetadata() {\n  \/\/ Save the current stream state.\n  uint64_t CurBit = Stream.GetCurrentBitNo();\n  DeferredMetadataInfo.push_back(CurBit);\n\n  \/\/ Skip over the block for now.\n  if (Error Err = Stream.SkipBlock())\n    return Err;\n  return Error::success();\n}\n\nError BitcodeReader::materializeMetadata() {\n  for (uint64_t BitPos : DeferredMetadataInfo) {\n    \/\/ Move the bit stream to the saved position.\n    if (Error JumpFailed = Stream.JumpToBit(BitPos))\n      return JumpFailed;\n    if (Error Err = MDLoader->parseModuleMetadata())\n      return Err;\n  }\n\n  \/\/ Upgrade \"Linker Options\" module flag to \"llvm.linker.options\" module-level\n  \/\/ metadata. Only upgrade if the new option doesn't exist to avoid upgrade\n  \/\/ multiple times.\n  if (!TheModule->getNamedMetadata(\"llvm.linker.options\")) {\n    if (Metadata *Val = TheModule->getModuleFlag(\"Linker Options\")) {\n      NamedMDNode *LinkerOpts =\n          TheModule->getOrInsertNamedMetadata(\"llvm.linker.options\");\n      for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())\n        LinkerOpts->addOperand(cast<MDNode>(MDOptions));\n    }\n  }\n\n  DeferredMetadataInfo.clear();\n  return Error::success();\n}\n\nvoid BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }\n\n\/\/\/ When we see the block for a function body, remember where it is and then\n\/\/\/ skip it.  This lets us lazily deserialize the functions.\nError BitcodeReader::rememberAndSkipFunctionBody() {\n  \/\/ Get the function we are talking about.\n  if (FunctionsWithBodies.empty())\n    return error(\"Insufficient function protos\");\n\n  Function *Fn = FunctionsWithBodies.back();\n  FunctionsWithBodies.pop_back();\n\n  \/\/ Save the current stream state.\n  uint64_t CurBit = Stream.GetCurrentBitNo();\n  assert(\n      (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&\n      \"Mismatch between VST and scanned function offsets\");\n  DeferredFunctionInfo[Fn] = CurBit;\n\n  \/\/ Skip over the function block for now.\n  if (Error Err = Stream.SkipBlock())\n    return Err;\n  return Error::success();\n}\n\nError BitcodeReader::globalCleanup() {\n  \/\/ Patch the initializers for globals and aliases up.\n  if (Error Err = resolveGlobalAndIndirectSymbolInits())\n    return Err;\n  if (!GlobalInits.empty() || !IndirectSymbolInits.empty())\n    return error(\"Malformed global initializer set\");\n\n  \/\/ Look for intrinsic functions which need to be upgraded at some point\n  \/\/ and functions that need to have their function attributes upgraded.\n  for (Function &F : *TheModule) {\n    MDLoader->upgradeDebugIntrinsics(F);\n    Function *NewFn;\n    if (UpgradeIntrinsicFunction(&F, NewFn))\n      UpgradedIntrinsics[&F] = NewFn;\n    else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))\n      \/\/ Some types could be renamed during loading if several modules are\n      \/\/ loaded in the same LLVMContext (LTO scenario). In this case we should\n      \/\/ remangle intrinsics names as well.\n      RemangledIntrinsics[&F] = Remangled.getValue();\n    \/\/ Look for functions that rely on old function attribute behavior.\n    UpgradeFunctionAttributes(F);\n  }\n\n  \/\/ Look for global variables which need to be renamed.\n  std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;\n  for (GlobalVariable &GV : TheModule->globals())\n    if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))\n      UpgradedVariables.emplace_back(&GV, Upgraded);\n  for (auto &Pair : UpgradedVariables) {\n    Pair.first->eraseFromParent();\n    TheModule->getGlobalList().push_back(Pair.second);\n  }\n\n  \/\/ Force deallocation of memory for these vectors to favor the client that\n  \/\/ want lazy deserialization.\n  std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);\n  std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits);\n  return Error::success();\n}\n\n\/\/\/ Support for lazy parsing of function bodies. This is required if we\n\/\/\/ either have an old bitcode file without a VST forward declaration record,\n\/\/\/ or if we have an anonymous function being materialized, since anonymous\n\/\/\/ functions do not have a name and are therefore not in the VST.\nError BitcodeReader::rememberAndSkipFunctionBodies() {\n  if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))\n    return JumpFailed;\n\n  if (Stream.AtEndOfStream())\n    return error(\"Could not find function in stream\");\n\n  if (!SeenFirstFunctionBody)\n    return error(\"Trying to materialize functions before seeing function blocks\");\n\n  \/\/ An old bitcode file with the symbol table at the end would have\n  \/\/ finished the parse greedily.\n  assert(SeenValueSymbolTable);\n\n  SmallVector<uint64_t, 64> Record;\n\n  while (true) {\n    Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    llvm::BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    default:\n      return error(\"Expect SubBlock\");\n    case BitstreamEntry::SubBlock:\n      switch (Entry.ID) {\n      default:\n        return error(\"Expect function block\");\n      case bitc::FUNCTION_BLOCK_ID:\n        if (Error Err = rememberAndSkipFunctionBody())\n          return Err;\n        NextUnreadBit = Stream.GetCurrentBitNo();\n        return Error::success();\n      }\n    }\n  }\n}\n\nError BitcodeReaderBase::readBlockInfo() {\n  Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo =\n      Stream.ReadBlockInfoBlock();\n  if (!MaybeNewBlockInfo)\n    return MaybeNewBlockInfo.takeError();\n  Optional<BitstreamBlockInfo> NewBlockInfo =\n      std::move(MaybeNewBlockInfo.get());\n  if (!NewBlockInfo)\n    return error(\"Malformed block\");\n  BlockInfo = std::move(*NewBlockInfo);\n  return Error::success();\n}\n\nError BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {\n  \/\/ v1: [selection_kind, name]\n  \/\/ v2: [strtab_offset, strtab_size, selection_kind]\n  StringRef Name;\n  std::tie(Name, Record) = readNameFromStrtab(Record);\n\n  if (Record.empty())\n    return error(\"Invalid record\");\n  Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);\n  std::string OldFormatName;\n  if (!UseStrtab) {\n    if (Record.size() < 2)\n      return error(\"Invalid record\");\n    unsigned ComdatNameSize = Record[1];\n    if (ComdatNameSize > Record.size() - 2)\n      return error(\"Comdat name size too large\");\n    OldFormatName.reserve(ComdatNameSize);\n    for (unsigned i = 0; i != ComdatNameSize; ++i)\n      OldFormatName += (char)Record[2 + i];\n    Name = OldFormatName;\n  }\n  Comdat *C = TheModule->getOrInsertComdat(Name);\n  C->setSelectionKind(SK);\n  ComdatList.push_back(C);\n  return Error::success();\n}\n\nstatic void inferDSOLocal(GlobalValue *GV) {\n  \/\/ infer dso_local from linkage and visibility if it is not encoded.\n  if (GV->hasLocalLinkage() ||\n      (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))\n    GV->setDSOLocal(true);\n}\n\nError BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {\n  \/\/ v1: [pointer type, isconst, initid, linkage, alignment, section,\n  \/\/ visibility, threadlocal, unnamed_addr, externally_initialized,\n  \/\/ dllstorageclass, comdat, attributes, preemption specifier,\n  \/\/ partition strtab offset, partition strtab size] (name in VST)\n  \/\/ v2: [strtab_offset, strtab_size, v1]\n  StringRef Name;\n  std::tie(Name, Record) = readNameFromStrtab(Record);\n\n  if (Record.size() < 6)\n    return error(\"Invalid record\");\n  unsigned TyID = Record[0];\n  Type *Ty = getTypeByID(TyID);\n  if (!Ty)\n    return error(\"Invalid record\");\n  bool isConstant = Record[1] & 1;\n  bool explicitType = Record[1] & 2;\n  unsigned AddressSpace;\n  if (explicitType) {\n    AddressSpace = Record[1] >> 2;\n  } else {\n    if (!Ty->isPointerTy())\n      return error(\"Invalid type for value\");\n    AddressSpace = cast<PointerType>(Ty)->getAddressSpace();\n    TyID = getContainedTypeID(TyID);\n    Ty = getTypeByID(TyID);\n    if (!Ty)\n      return error(\"Missing element type for old-style global\");\n  }\n\n  uint64_t RawLinkage = Record[3];\n  GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);\n  MaybeAlign Alignment;\n  if (Error Err = parseAlignmentValue(Record[4], Alignment))\n    return Err;\n  std::string Section;\n  if (Record[5]) {\n    if (Record[5] - 1 >= SectionTable.size())\n      return error(\"Invalid ID\");\n    Section = SectionTable[Record[5] - 1];\n  }\n  GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;\n  \/\/ Local linkage must have default visibility.\n  \/\/ auto-upgrade `hidden` and `protected` for old bitcode.\n  if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))\n    Visibility = getDecodedVisibility(Record[6]);\n\n  GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;\n  if (Record.size() > 7)\n    TLM = getDecodedThreadLocalMode(Record[7]);\n\n  GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;\n  if (Record.size() > 8)\n    UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);\n\n  bool ExternallyInitialized = false;\n  if (Record.size() > 9)\n    ExternallyInitialized = Record[9];\n\n  GlobalVariable *NewGV =\n      new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,\n                         nullptr, TLM, AddressSpace, ExternallyInitialized);\n  NewGV->setAlignment(Alignment);\n  if (!Section.empty())\n    NewGV->setSection(Section);\n  NewGV->setVisibility(Visibility);\n  NewGV->setUnnamedAddr(UnnamedAddr);\n\n  if (Record.size() > 10)\n    NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));\n  else\n    upgradeDLLImportExportLinkage(NewGV, RawLinkage);\n\n  ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID));\n\n  \/\/ Remember which value to use for the global initializer.\n  if (unsigned InitID = Record[2])\n    GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));\n\n  if (Record.size() > 11) {\n    if (unsigned ComdatID = Record[11]) {\n      if (ComdatID > ComdatList.size())\n        return error(\"Invalid global variable comdat ID\");\n      NewGV->setComdat(ComdatList[ComdatID - 1]);\n    }\n  } else if (hasImplicitComdat(RawLinkage)) {\n    ImplicitComdatObjects.insert(NewGV);\n  }\n\n  if (Record.size() > 12) {\n    auto AS = getAttributes(Record[12]).getFnAttrs();\n    NewGV->setAttributes(AS);\n  }\n\n  if (Record.size() > 13) {\n    NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));\n  }\n  inferDSOLocal(NewGV);\n\n  \/\/ Check whether we have enough values to read a partition name.\n  if (Record.size() > 15)\n    NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));\n\n  return Error::success();\n}\n\nError BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {\n  \/\/ v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,\n  \/\/ visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,\n  \/\/ prefixdata,  personalityfn, preemption specifier, addrspace] (name in VST)\n  \/\/ v2: [strtab_offset, strtab_size, v1]\n  StringRef Name;\n  std::tie(Name, Record) = readNameFromStrtab(Record);\n\n  if (Record.size() < 8)\n    return error(\"Invalid record\");\n  unsigned FTyID = Record[0];\n  Type *FTy = getTypeByID(FTyID);\n  if (!FTy)\n    return error(\"Invalid record\");\n  if (isa<PointerType>(FTy)) {\n    FTyID = getContainedTypeID(FTyID, 0);\n    FTy = getTypeByID(FTyID);\n    if (!FTy)\n      return error(\"Missing element type for old-style function\");\n  }\n\n  if (!isa<FunctionType>(FTy))\n    return error(\"Invalid type for value\");\n  auto CC = static_cast<CallingConv::ID>(Record[1]);\n  if (CC & ~CallingConv::MaxID)\n    return error(\"Invalid calling convention ID\");\n\n  unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();\n  if (Record.size() > 16)\n    AddrSpace = Record[16];\n\n  Function *Func =\n      Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,\n                       AddrSpace, Name, TheModule);\n\n  assert(Func->getFunctionType() == FTy &&\n         \"Incorrect fully specified type provided for function\");\n  FunctionTypeIDs[Func] = FTyID;\n\n  Func->setCallingConv(CC);\n  bool isProto = Record[2];\n  uint64_t RawLinkage = Record[3];\n  Func->setLinkage(getDecodedLinkage(RawLinkage));\n  Func->setAttributes(getAttributes(Record[4]));\n\n  \/\/ Upgrade any old-style byval or sret without a type by propagating the\n  \/\/ argument's pointee type. There should be no opaque pointers where the byval\n  \/\/ type is implicit.\n  for (unsigned i = 0; i != Func->arg_size(); ++i) {\n    for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,\n                                     Attribute::InAlloca}) {\n      if (!Func->hasParamAttribute(i, Kind))\n        continue;\n\n      if (Func->getParamAttribute(i, Kind).getValueAsType())\n        continue;\n\n      Func->removeParamAttr(i, Kind);\n\n      unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);\n      Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);\n      if (!PtrEltTy)\n        return error(\"Missing param element type for attribute upgrade\");\n\n      Attribute NewAttr;\n      switch (Kind) {\n      case Attribute::ByVal:\n        NewAttr = Attribute::getWithByValType(Context, PtrEltTy);\n        break;\n      case Attribute::StructRet:\n        NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);\n        break;\n      case Attribute::InAlloca:\n        NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);\n        break;\n      default:\n        llvm_unreachable(\"not an upgraded type attribute\");\n      }\n\n      Func->addParamAttr(i, NewAttr);\n    }\n  }\n\n  if (Func->getCallingConv() == CallingConv::X86_INTR &&\n      !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) {\n    unsigned ParamTypeID = getContainedTypeID(FTyID, 1);\n    Type *ByValTy = getPtrElementTypeByID(ParamTypeID);\n    if (!ByValTy)\n      return error(\"Missing param element type for x86_intrcc upgrade\");\n    Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy);\n    Func->addParamAttr(0, NewAttr);\n  }\n\n  MaybeAlign Alignment;\n  if (Error Err = parseAlignmentValue(Record[5], Alignment))\n    return Err;\n  Func->setAlignment(Alignment);\n  if (Record[6]) {\n    if (Record[6] - 1 >= SectionTable.size())\n      return error(\"Invalid ID\");\n    Func->setSection(SectionTable[Record[6] - 1]);\n  }\n  \/\/ Local linkage must have default visibility.\n  \/\/ auto-upgrade `hidden` and `protected` for old bitcode.\n  if (!Func->hasLocalLinkage())\n    Func->setVisibility(getDecodedVisibility(Record[7]));\n  if (Record.size() > 8 && Record[8]) {\n    if (Record[8] - 1 >= GCTable.size())\n      return error(\"Invalid ID\");\n    Func->setGC(GCTable[Record[8] - 1]);\n  }\n  GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;\n  if (Record.size() > 9)\n    UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);\n  Func->setUnnamedAddr(UnnamedAddr);\n\n  FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};\n  if (Record.size() > 10)\n    OperandInfo.Prologue = Record[10];\n\n  if (Record.size() > 11)\n    Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));\n  else\n    upgradeDLLImportExportLinkage(Func, RawLinkage);\n\n  if (Record.size() > 12) {\n    if (unsigned ComdatID = Record[12]) {\n      if (ComdatID > ComdatList.size())\n        return error(\"Invalid function comdat ID\");\n      Func->setComdat(ComdatList[ComdatID - 1]);\n    }\n  } else if (hasImplicitComdat(RawLinkage)) {\n    ImplicitComdatObjects.insert(Func);\n  }\n\n  if (Record.size() > 13)\n    OperandInfo.Prefix = Record[13];\n\n  if (Record.size() > 14)\n    OperandInfo.PersonalityFn = Record[14];\n\n  if (Record.size() > 15) {\n    Func->setDSOLocal(getDecodedDSOLocal(Record[15]));\n  }\n  inferDSOLocal(Func);\n\n  \/\/ Record[16] is the address space number.\n\n  \/\/ Check whether we have enough values to read a partition name. Also make\n  \/\/ sure Strtab has enough values.\n  if (Record.size() > 18 && Strtab.data() &&\n      Record[17] + Record[18] <= Strtab.size()) {\n    Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));\n  }\n\n  ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID));\n\n  if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)\n    FunctionOperands.push_back(OperandInfo);\n\n  \/\/ If this is a function with a body, remember the prototype we are\n  \/\/ creating now, so that we can match up the body with them later.\n  if (!isProto) {\n    Func->setIsMaterializable(true);\n    FunctionsWithBodies.push_back(Func);\n    DeferredFunctionInfo[Func] = 0;\n  }\n  return Error::success();\n}\n\nError BitcodeReader::parseGlobalIndirectSymbolRecord(\n    unsigned BitCode, ArrayRef<uint64_t> Record) {\n  \/\/ v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)\n  \/\/ v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,\n  \/\/ dllstorageclass, threadlocal, unnamed_addr,\n  \/\/ preemption specifier] (name in VST)\n  \/\/ v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,\n  \/\/ visibility, dllstorageclass, threadlocal, unnamed_addr,\n  \/\/ preemption specifier] (name in VST)\n  \/\/ v2: [strtab_offset, strtab_size, v1]\n  StringRef Name;\n  std::tie(Name, Record) = readNameFromStrtab(Record);\n\n  bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;\n  if (Record.size() < (3 + (unsigned)NewRecord))\n    return error(\"Invalid record\");\n  unsigned OpNum = 0;\n  unsigned TypeID = Record[OpNum++];\n  Type *Ty = getTypeByID(TypeID);\n  if (!Ty)\n    return error(\"Invalid record\");\n\n  unsigned AddrSpace;\n  if (!NewRecord) {\n    auto *PTy = dyn_cast<PointerType>(Ty);\n    if (!PTy)\n      return error(\"Invalid type for value\");\n    AddrSpace = PTy->getAddressSpace();\n    TypeID = getContainedTypeID(TypeID);\n    Ty = getTypeByID(TypeID);\n    if (!Ty)\n      return error(\"Missing element type for old-style indirect symbol\");\n  } else {\n    AddrSpace = Record[OpNum++];\n  }\n\n  auto Val = Record[OpNum++];\n  auto Linkage = Record[OpNum++];\n  GlobalValue *NewGA;\n  if (BitCode == bitc::MODULE_CODE_ALIAS ||\n      BitCode == bitc::MODULE_CODE_ALIAS_OLD)\n    NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,\n                                TheModule);\n  else\n    NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,\n                                nullptr, TheModule);\n\n  \/\/ Local linkage must have default visibility.\n  \/\/ auto-upgrade `hidden` and `protected` for old bitcode.\n  if (OpNum != Record.size()) {\n    auto VisInd = OpNum++;\n    if (!NewGA->hasLocalLinkage())\n      NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));\n  }\n  if (BitCode == bitc::MODULE_CODE_ALIAS ||\n      BitCode == bitc::MODULE_CODE_ALIAS_OLD) {\n    if (OpNum != Record.size())\n      NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));\n    else\n      upgradeDLLImportExportLinkage(NewGA, Linkage);\n    if (OpNum != Record.size())\n      NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));\n    if (OpNum != Record.size())\n      NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));\n  }\n  if (OpNum != Record.size())\n    NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));\n  inferDSOLocal(NewGA);\n\n  \/\/ Check whether we have enough values to read a partition name.\n  if (OpNum + 1 < Record.size()) {\n    NewGA->setPartition(\n        StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));\n    OpNum += 2;\n  }\n\n  ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));\n  IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));\n  return Error::success();\n}\n\nError BitcodeReader::parseModule(uint64_t ResumeBit,\n                                 bool ShouldLazyLoadMetadata,\n                                 DataLayoutCallbackTy DataLayoutCallback) {\n  if (ResumeBit) {\n    if (Error JumpFailed = Stream.JumpToBit(ResumeBit))\n      return JumpFailed;\n  } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))\n    return Err;\n\n  SmallVector<uint64_t, 64> Record;\n\n  \/\/ Parts of bitcode parsing depend on the datalayout.  Make sure we\n  \/\/ finalize the datalayout before we run any of that code.\n  bool ResolvedDataLayout = false;\n  auto ResolveDataLayout = [&] {\n    if (ResolvedDataLayout)\n      return;\n\n    \/\/ datalayout and triple can't be parsed after this point.\n    ResolvedDataLayout = true;\n\n    \/\/ Upgrade data layout string.\n    std::string DL = llvm::UpgradeDataLayoutString(\n        TheModule->getDataLayoutStr(), TheModule->getTargetTriple());\n    TheModule->setDataLayout(DL);\n\n    if (auto LayoutOverride =\n            DataLayoutCallback(TheModule->getTargetTriple()))\n      TheModule->setDataLayout(*LayoutOverride);\n  };\n\n  \/\/ Read all the records for this module.\n  while (true) {\n    Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    llvm::BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      ResolveDataLayout();\n      return globalCleanup();\n\n    case BitstreamEntry::SubBlock:\n      switch (Entry.ID) {\n      default:  \/\/ Skip unknown content.\n        if (Error Err = Stream.SkipBlock())\n          return Err;\n        break;\n      case bitc::BLOCKINFO_BLOCK_ID:\n        if (Error Err = readBlockInfo())\n          return Err;\n        break;\n      case bitc::PARAMATTR_BLOCK_ID:\n        if (Error Err = parseAttributeBlock())\n          return Err;\n        break;\n      case bitc::PARAMATTR_GROUP_BLOCK_ID:\n        if (Error Err = parseAttributeGroupBlock())\n          return Err;\n        break;\n      case bitc::TYPE_BLOCK_ID_NEW:\n        if (Error Err = parseTypeTable())\n          return Err;\n        break;\n      case bitc::VALUE_SYMTAB_BLOCK_ID:\n        if (!SeenValueSymbolTable) {\n          \/\/ Either this is an old form VST without function index and an\n          \/\/ associated VST forward declaration record (which would have caused\n          \/\/ the VST to be jumped to and parsed before it was encountered\n          \/\/ normally in the stream), or there were no function blocks to\n          \/\/ trigger an earlier parsing of the VST.\n          assert(VSTOffset == 0 || FunctionsWithBodies.empty());\n          if (Error Err = parseValueSymbolTable())\n            return Err;\n          SeenValueSymbolTable = true;\n        } else {\n          \/\/ We must have had a VST forward declaration record, which caused\n          \/\/ the parser to jump to and parse the VST earlier.\n          assert(VSTOffset > 0);\n          if (Error Err = Stream.SkipBlock())\n            return Err;\n        }\n        break;\n      case bitc::CONSTANTS_BLOCK_ID:\n        if (Error Err = parseConstants())\n          return Err;\n        if (Error Err = resolveGlobalAndIndirectSymbolInits())\n          return Err;\n        break;\n      case bitc::METADATA_BLOCK_ID:\n        if (ShouldLazyLoadMetadata) {\n          if (Error Err = rememberAndSkipMetadata())\n            return Err;\n          break;\n        }\n        assert(DeferredMetadataInfo.empty() && \"Unexpected deferred metadata\");\n        if (Error Err = MDLoader->parseModuleMetadata())\n          return Err;\n        break;\n      case bitc::METADATA_KIND_BLOCK_ID:\n        if (Error Err = MDLoader->parseMetadataKinds())\n          return Err;\n        break;\n      case bitc::FUNCTION_BLOCK_ID:\n        ResolveDataLayout();\n\n        \/\/ If this is the first function body we've seen, reverse the\n        \/\/ FunctionsWithBodies list.\n        if (!SeenFirstFunctionBody) {\n          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());\n          if (Error Err = globalCleanup())\n            return Err;\n          SeenFirstFunctionBody = true;\n        }\n\n        if (VSTOffset > 0) {\n          \/\/ If we have a VST forward declaration record, make sure we\n          \/\/ parse the VST now if we haven't already. It is needed to\n          \/\/ set up the DeferredFunctionInfo vector for lazy reading.\n          if (!SeenValueSymbolTable) {\n            if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))\n              return Err;\n            SeenValueSymbolTable = true;\n            \/\/ Fall through so that we record the NextUnreadBit below.\n            \/\/ This is necessary in case we have an anonymous function that\n            \/\/ is later materialized. Since it will not have a VST entry we\n            \/\/ need to fall back to the lazy parse to find its offset.\n          } else {\n            \/\/ If we have a VST forward declaration record, but have already\n            \/\/ parsed the VST (just above, when the first function body was\n            \/\/ encountered here), then we are resuming the parse after\n            \/\/ materializing functions. The ResumeBit points to the\n            \/\/ start of the last function block recorded in the\n            \/\/ DeferredFunctionInfo map. Skip it.\n            if (Error Err = Stream.SkipBlock())\n              return Err;\n            continue;\n          }\n        }\n\n        \/\/ Support older bitcode files that did not have the function\n        \/\/ index in the VST, nor a VST forward declaration record, as\n        \/\/ well as anonymous functions that do not have VST entries.\n        \/\/ Build the DeferredFunctionInfo vector on the fly.\n        if (Error Err = rememberAndSkipFunctionBody())\n          return Err;\n\n        \/\/ Suspend parsing when we reach the function bodies. Subsequent\n        \/\/ materialization calls will resume it when necessary. If the bitcode\n        \/\/ file is old, the symbol table will be at the end instead and will not\n        \/\/ have been seen yet. In this case, just finish the parse now.\n        if (SeenValueSymbolTable) {\n          NextUnreadBit = Stream.GetCurrentBitNo();\n          \/\/ After the VST has been parsed, we need to make sure intrinsic name\n          \/\/ are auto-upgraded.\n          return globalCleanup();\n        }\n        break;\n      case bitc::USELIST_BLOCK_ID:\n        if (Error Err = parseUseLists())\n          return Err;\n        break;\n      case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:\n        if (Error Err = parseOperandBundleTags())\n          return Err;\n        break;\n      case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:\n        if (Error Err = parseSyncScopeNames())\n          return Err;\n        break;\n      }\n      continue;\n\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Read a record.\n    Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeBitCode)\n      return MaybeBitCode.takeError();\n    switch (unsigned BitCode = MaybeBitCode.get()) {\n    default: break;  \/\/ Default behavior, ignore unknown content.\n    case bitc::MODULE_CODE_VERSION: {\n      Expected<unsigned> VersionOrErr = parseVersionRecord(Record);\n      if (!VersionOrErr)\n        return VersionOrErr.takeError();\n      UseRelativeIDs = *VersionOrErr >= 1;\n      break;\n    }\n    case bitc::MODULE_CODE_TRIPLE: {  \/\/ TRIPLE: [strchr x N]\n      if (ResolvedDataLayout)\n        return error(\"target triple too late in module\");\n      std::string S;\n      if (convertToString(Record, 0, S))\n        return error(\"Invalid record\");\n      TheModule->setTargetTriple(S);\n      break;\n    }\n    case bitc::MODULE_CODE_DATALAYOUT: {  \/\/ DATALAYOUT: [strchr x N]\n      if (ResolvedDataLayout)\n        return error(\"datalayout too late in module\");\n      std::string S;\n      if (convertToString(Record, 0, S))\n        return error(\"Invalid record\");\n      Expected<DataLayout> MaybeDL = DataLayout::parse(S);\n      if (!MaybeDL)\n        return MaybeDL.takeError();\n      TheModule->setDataLayout(MaybeDL.get());\n      break;\n    }\n    case bitc::MODULE_CODE_ASM: {  \/\/ ASM: [strchr x N]\n      std::string S;\n      if (convertToString(Record, 0, S))\n        return error(\"Invalid record\");\n      TheModule->setModuleInlineAsm(S);\n      break;\n    }\n    case bitc::MODULE_CODE_DEPLIB: {  \/\/ DEPLIB: [strchr x N]\n      \/\/ Deprecated, but still needed to read old bitcode files.\n      std::string S;\n      if (convertToString(Record, 0, S))\n        return error(\"Invalid record\");\n      \/\/ Ignore value.\n      break;\n    }\n    case bitc::MODULE_CODE_SECTIONNAME: {  \/\/ SECTIONNAME: [strchr x N]\n      std::string S;\n      if (convertToString(Record, 0, S))\n        return error(\"Invalid record\");\n      SectionTable.push_back(S);\n      break;\n    }\n    case bitc::MODULE_CODE_GCNAME: {  \/\/ SECTIONNAME: [strchr x N]\n      std::string S;\n      if (convertToString(Record, 0, S))\n        return error(\"Invalid record\");\n      GCTable.push_back(S);\n      break;\n    }\n    case bitc::MODULE_CODE_COMDAT:\n      if (Error Err = parseComdatRecord(Record))\n        return Err;\n      break;\n    \/\/ FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}\n    \/\/ written by ThinLinkBitcodeWriter. See\n    \/\/ `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each\n    \/\/ record\n    \/\/ (https:\/\/github.com\/llvm\/llvm-project\/blob\/b6a93967d9c11e79802b5e75cec1584d6c8aa472\/llvm\/lib\/Bitcode\/Writer\/BitcodeWriter.cpp#L4714)\n    case bitc::MODULE_CODE_GLOBALVAR:\n      if (Error Err = parseGlobalVarRecord(Record))\n        return Err;\n      break;\n    case bitc::MODULE_CODE_FUNCTION:\n      ResolveDataLayout();\n      if (Error Err = parseFunctionRecord(Record))\n        return Err;\n      break;\n    case bitc::MODULE_CODE_IFUNC:\n    case bitc::MODULE_CODE_ALIAS:\n    case bitc::MODULE_CODE_ALIAS_OLD:\n      if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))\n        return Err;\n      break;\n    \/\/\/ MODULE_CODE_VSTOFFSET: [offset]\n    case bitc::MODULE_CODE_VSTOFFSET:\n      if (Record.empty())\n        return error(\"Invalid record\");\n      \/\/ Note that we subtract 1 here because the offset is relative to one word\n      \/\/ before the start of the identification or module block, which was\n      \/\/ historically always the start of the regular bitcode header.\n      VSTOffset = Record[0] - 1;\n      break;\n    \/\/\/ MODULE_CODE_SOURCE_FILENAME: [namechar x N]\n    case bitc::MODULE_CODE_SOURCE_FILENAME:\n      SmallString<128> ValueName;\n      if (convertToString(Record, 0, ValueName))\n        return error(\"Invalid record\");\n      TheModule->setSourceFileName(ValueName);\n      break;\n    }\n    Record.clear();\n  }\n}\n\nError BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,\n                                      bool IsImporting,\n                                      DataLayoutCallbackTy DataLayoutCallback) {\n  TheModule = M;\n  MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,\n                            [&](unsigned ID) { return getTypeByID(ID); });\n  return parseModule(0, ShouldLazyLoadMetadata, DataLayoutCallback);\n}\n\nError BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {\n  if (!isa<PointerType>(PtrType))\n    return error(\"Load\/Store operand is not a pointer type\");\n\n  if (!cast<PointerType>(PtrType)->isOpaqueOrPointeeTypeMatches(ValType))\n    return error(\"Explicit load\/store type does not match pointee \"\n                 \"type of pointer operand\");\n  if (!PointerType::isLoadableOrStorableType(ValType))\n    return error(\"Cannot load\/store from pointer\");\n  return Error::success();\n}\n\nError BitcodeReader::propagateAttributeTypes(CallBase *CB,\n                                             ArrayRef<unsigned> ArgTyIDs) {\n  AttributeList Attrs = CB->getAttributes();\n  for (unsigned i = 0; i != CB->arg_size(); ++i) {\n    for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,\n                                     Attribute::InAlloca}) {\n      if (!Attrs.hasParamAttr(i, Kind) ||\n          Attrs.getParamAttr(i, Kind).getValueAsType())\n        continue;\n\n      Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);\n      if (!PtrEltTy)\n        return error(\"Missing element type for typed attribute upgrade\");\n\n      Attribute NewAttr;\n      switch (Kind) {\n      case Attribute::ByVal:\n        NewAttr = Attribute::getWithByValType(Context, PtrEltTy);\n        break;\n      case Attribute::StructRet:\n        NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);\n        break;\n      case Attribute::InAlloca:\n        NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);\n        break;\n      default:\n        llvm_unreachable(\"not an upgraded type attribute\");\n      }\n\n      Attrs = Attrs.addParamAttribute(Context, i, NewAttr);\n    }\n  }\n\n  if (CB->isInlineAsm()) {\n    const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());\n    unsigned ArgNo = 0;\n    for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {\n      if (!CI.hasArg())\n        continue;\n\n      if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {\n        Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);\n        if (!ElemTy)\n          return error(\"Missing element type for inline asm upgrade\");\n        Attrs = Attrs.addParamAttribute(\n            Context, ArgNo,\n            Attribute::get(Context, Attribute::ElementType, ElemTy));\n      }\n\n      ArgNo++;\n    }\n  }\n\n  switch (CB->getIntrinsicID()) {\n  case Intrinsic::preserve_array_access_index:\n  case Intrinsic::preserve_struct_access_index:\n  case Intrinsic::aarch64_ldaxr:\n  case Intrinsic::aarch64_ldxr:\n  case Intrinsic::aarch64_stlxr:\n  case Intrinsic::aarch64_stxr: {\n    unsigned ArgNo = CB->getIntrinsicID() == Intrinsic::aarch64_stlxr ||\n                             CB->getIntrinsicID() == Intrinsic::aarch64_stxr\n                         ? 1\n                         : 0;\n    if (!Attrs.getParamElementType(ArgNo)) {\n      Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);\n      if (!ElTy)\n        return error(\"Missing element type for elementtype upgrade\");\n      Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);\n      Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr);\n    }\n    break;\n  }\n  default:\n    break;\n  }\n\n  CB->setAttributes(Attrs);\n  return Error::success();\n}\n\n\/\/\/ Lazily parse the specified function body block.\nError BitcodeReader::parseFunctionBody(Function *F) {\n  if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))\n    return Err;\n\n  \/\/ Unexpected unresolved metadata when parsing function.\n  if (MDLoader->hasFwdRefs())\n    return error(\"Invalid function metadata: incoming forward references\");\n\n  InstructionList.clear();\n  unsigned ModuleValueListSize = ValueList.size();\n  unsigned ModuleMDLoaderSize = MDLoader->size();\n\n  \/\/ Add all the function arguments to the value table.\n  unsigned ArgNo = 0;\n  unsigned FTyID = FunctionTypeIDs[F];\n  for (Argument &I : F->args()) {\n    unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);\n    assert(I.getType() == getTypeByID(ArgTyID) &&\n           \"Incorrect fully specified type for Function Argument\");\n    ValueList.push_back(&I, ArgTyID);\n    ++ArgNo;\n  }\n  unsigned NextValueNo = ValueList.size();\n  BasicBlock *CurBB = nullptr;\n  unsigned CurBBNo = 0;\n\n  DebugLoc LastLoc;\n  auto getLastInstruction = [&]() -> Instruction * {\n    if (CurBB && !CurBB->empty())\n      return &CurBB->back();\n    else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&\n             !FunctionBBs[CurBBNo - 1]->empty())\n      return &FunctionBBs[CurBBNo - 1]->back();\n    return nullptr;\n  };\n\n  std::vector<OperandBundleDef> OperandBundles;\n\n  \/\/ Read all the records.\n  SmallVector<uint64_t, 64> Record;\n\n  while (true) {\n    Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    llvm::BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      goto OutOfRecordLoop;\n\n    case BitstreamEntry::SubBlock:\n      switch (Entry.ID) {\n      default:  \/\/ Skip unknown content.\n        if (Error Err = Stream.SkipBlock())\n          return Err;\n        break;\n      case bitc::CONSTANTS_BLOCK_ID:\n        if (Error Err = parseConstants())\n          return Err;\n        NextValueNo = ValueList.size();\n        break;\n      case bitc::VALUE_SYMTAB_BLOCK_ID:\n        if (Error Err = parseValueSymbolTable())\n          return Err;\n        break;\n      case bitc::METADATA_ATTACHMENT_ID:\n        if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))\n          return Err;\n        break;\n      case bitc::METADATA_BLOCK_ID:\n        assert(DeferredMetadataInfo.empty() &&\n               \"Must read all module-level metadata before function-level\");\n        if (Error Err = MDLoader->parseFunctionMetadata())\n          return Err;\n        break;\n      case bitc::USELIST_BLOCK_ID:\n        if (Error Err = parseUseLists())\n          return Err;\n        break;\n      }\n      continue;\n\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Read a record.\n    Record.clear();\n    Instruction *I = nullptr;\n    unsigned ResTypeID = InvalidTypeID;\n    Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeBitCode)\n      return MaybeBitCode.takeError();\n    switch (unsigned BitCode = MaybeBitCode.get()) {\n    default: \/\/ Default behavior: reject\n      return error(\"Invalid value\");\n    case bitc::FUNC_CODE_DECLAREBLOCKS: {   \/\/ DECLAREBLOCKS: [nblocks]\n      if (Record.empty() || Record[0] == 0)\n        return error(\"Invalid record\");\n      \/\/ Create all the basic blocks for the function.\n      FunctionBBs.resize(Record[0]);\n\n      \/\/ See if anything took the address of blocks in this function.\n      auto BBFRI = BasicBlockFwdRefs.find(F);\n      if (BBFRI == BasicBlockFwdRefs.end()) {\n        for (BasicBlock *&BB : FunctionBBs)\n          BB = BasicBlock::Create(Context, \"\", F);\n      } else {\n        auto &BBRefs = BBFRI->second;\n        \/\/ Check for invalid basic block references.\n        if (BBRefs.size() > FunctionBBs.size())\n          return error(\"Invalid ID\");\n        assert(!BBRefs.empty() && \"Unexpected empty array\");\n        assert(!BBRefs.front() && \"Invalid reference to entry block\");\n        for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;\n             ++I)\n          if (I < RE && BBRefs[I]) {\n            BBRefs[I]->insertInto(F);\n            FunctionBBs[I] = BBRefs[I];\n          } else {\n            FunctionBBs[I] = BasicBlock::Create(Context, \"\", F);\n          }\n\n        \/\/ Erase from the table.\n        BasicBlockFwdRefs.erase(BBFRI);\n      }\n\n      CurBB = FunctionBBs[0];\n      continue;\n    }\n\n    case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  \/\/ DEBUG_LOC_AGAIN\n      \/\/ This record indicates that the last instruction is at the same\n      \/\/ location as the previous instruction with a location.\n      I = getLastInstruction();\n\n      if (!I)\n        return error(\"Invalid record\");\n      I->setDebugLoc(LastLoc);\n      I = nullptr;\n      continue;\n\n    case bitc::FUNC_CODE_DEBUG_LOC: {      \/\/ DEBUG_LOC: [line, col, scope, ia]\n      I = getLastInstruction();\n      if (!I || Record.size() < 4)\n        return error(\"Invalid record\");\n\n      unsigned Line = Record[0], Col = Record[1];\n      unsigned ScopeID = Record[2], IAID = Record[3];\n      bool isImplicitCode = Record.size() == 5 && Record[4];\n\n      MDNode *Scope = nullptr, *IA = nullptr;\n      if (ScopeID) {\n        Scope = dyn_cast_or_null<MDNode>(\n            MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));\n        if (!Scope)\n          return error(\"Invalid record\");\n      }\n      if (IAID) {\n        IA = dyn_cast_or_null<MDNode>(\n            MDLoader->getMetadataFwdRefOrLoad(IAID - 1));\n        if (!IA)\n          return error(\"Invalid record\");\n      }\n      LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,\n                                isImplicitCode);\n      I->setDebugLoc(LastLoc);\n      I = nullptr;\n      continue;\n    }\n    case bitc::FUNC_CODE_INST_UNOP: {    \/\/ UNOP: [opval, ty, opcode]\n      unsigned OpNum = 0;\n      Value *LHS;\n      unsigned TypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID) ||\n          OpNum+1 > Record.size())\n        return error(\"Invalid record\");\n\n      int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());\n      if (Opc == -1)\n        return error(\"Invalid record\");\n      I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);\n      ResTypeID = TypeID;\n      InstructionList.push_back(I);\n      if (OpNum < Record.size()) {\n        if (isa<FPMathOperator>(I)) {\n          FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);\n          if (FMF.any())\n            I->setFastMathFlags(FMF);\n        }\n      }\n      break;\n    }\n    case bitc::FUNC_CODE_INST_BINOP: {    \/\/ BINOP: [opval, ty, opval, opcode]\n      unsigned OpNum = 0;\n      Value *LHS, *RHS;\n      unsigned TypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID) ||\n          popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS) ||\n          OpNum+1 > Record.size())\n        return error(\"Invalid record\");\n\n      int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());\n      if (Opc == -1)\n        return error(\"Invalid record\");\n      I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);\n      ResTypeID = TypeID;\n      InstructionList.push_back(I);\n      if (OpNum < Record.size()) {\n        if (Opc == Instruction::Add ||\n            Opc == Instruction::Sub ||\n            Opc == Instruction::Mul ||\n            Opc == Instruction::Shl) {\n          if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))\n            cast<BinaryOperator>(I)->setHasNoSignedWrap(true);\n          if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))\n            cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);\n        } else if (Opc == Instruction::SDiv ||\n                   Opc == Instruction::UDiv ||\n                   Opc == Instruction::LShr ||\n                   Opc == Instruction::AShr) {\n          if (Record[OpNum] & (1 << bitc::PEO_EXACT))\n            cast<BinaryOperator>(I)->setIsExact(true);\n        } else if (isa<FPMathOperator>(I)) {\n          FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);\n          if (FMF.any())\n            I->setFastMathFlags(FMF);\n        }\n\n      }\n      break;\n    }\n    case bitc::FUNC_CODE_INST_CAST: {    \/\/ CAST: [opval, opty, destty, castopc]\n      unsigned OpNum = 0;\n      Value *Op;\n      unsigned OpTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID) ||\n          OpNum+2 != Record.size())\n        return error(\"Invalid record\");\n\n      ResTypeID = Record[OpNum];\n      Type *ResTy = getTypeByID(ResTypeID);\n      int Opc = getDecodedCastOpcode(Record[OpNum + 1]);\n      if (Opc == -1 || !ResTy)\n        return error(\"Invalid record\");\n      Instruction *Temp = nullptr;\n      if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {\n        if (Temp) {\n          InstructionList.push_back(Temp);\n          assert(CurBB && \"No current BB?\");\n          CurBB->getInstList().push_back(Temp);\n        }\n      } else {\n        auto CastOp = (Instruction::CastOps)Opc;\n        if (!CastInst::castIsValid(CastOp, Op, ResTy))\n          return error(\"Invalid cast\");\n        I = CastInst::Create(CastOp, Op, ResTy);\n      }\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:\n    case bitc::FUNC_CODE_INST_GEP_OLD:\n    case bitc::FUNC_CODE_INST_GEP: { \/\/ GEP: type, [n x operands]\n      unsigned OpNum = 0;\n\n      unsigned TyID;\n      Type *Ty;\n      bool InBounds;\n\n      if (BitCode == bitc::FUNC_CODE_INST_GEP) {\n        InBounds = Record[OpNum++];\n        TyID = Record[OpNum++];\n        Ty = getTypeByID(TyID);\n      } else {\n        InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;\n        TyID = InvalidTypeID;\n        Ty = nullptr;\n      }\n\n      Value *BasePtr;\n      unsigned BasePtrTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID))\n        return error(\"Invalid record\");\n\n      if (!Ty) {\n        TyID = getContainedTypeID(BasePtrTypeID);\n        if (BasePtr->getType()->isVectorTy())\n          TyID = getContainedTypeID(TyID);\n        Ty = getTypeByID(TyID);\n      } else if (!cast<PointerType>(BasePtr->getType()->getScalarType())\n                      ->isOpaqueOrPointeeTypeMatches(Ty)) {\n        return error(\n            \"Explicit gep type does not match pointee type of pointer operand\");\n      }\n\n      SmallVector<Value*, 16> GEPIdx;\n      while (OpNum != Record.size()) {\n        Value *Op;\n        unsigned OpTypeID;\n        if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))\n          return error(\"Invalid record\");\n        GEPIdx.push_back(Op);\n      }\n\n      I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);\n\n      ResTypeID = TyID;\n      if (cast<GEPOperator>(I)->getNumIndices() != 0) {\n        auto GTI = std::next(gep_type_begin(I));\n        for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {\n          unsigned SubType = 0;\n          if (GTI.isStruct()) {\n            ConstantInt *IdxC =\n                Idx->getType()->isVectorTy()\n                    ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue())\n                    : cast<ConstantInt>(Idx);\n            SubType = IdxC->getZExtValue();\n          }\n          ResTypeID = getContainedTypeID(ResTypeID, SubType);\n          ++GTI;\n        }\n      }\n\n      \/\/ At this point ResTypeID is the result element type. We need a pointer\n      \/\/ or vector of pointer to it.\n      ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);\n      if (I->getType()->isVectorTy())\n        ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);\n\n      InstructionList.push_back(I);\n      if (InBounds)\n        cast<GetElementPtrInst>(I)->setIsInBounds(true);\n      break;\n    }\n\n    case bitc::FUNC_CODE_INST_EXTRACTVAL: {\n                                       \/\/ EXTRACTVAL: [opty, opval, n x indices]\n      unsigned OpNum = 0;\n      Value *Agg;\n      unsigned AggTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID))\n        return error(\"Invalid record\");\n      Type *Ty = Agg->getType();\n\n      unsigned RecSize = Record.size();\n      if (OpNum == RecSize)\n        return error(\"EXTRACTVAL: Invalid instruction with 0 indices\");\n\n      SmallVector<unsigned, 4> EXTRACTVALIdx;\n      ResTypeID = AggTypeID;\n      for (; OpNum != RecSize; ++OpNum) {\n        bool IsArray = Ty->isArrayTy();\n        bool IsStruct = Ty->isStructTy();\n        uint64_t Index = Record[OpNum];\n\n        if (!IsStruct && !IsArray)\n          return error(\"EXTRACTVAL: Invalid type\");\n        if ((unsigned)Index != Index)\n          return error(\"Invalid value\");\n        if (IsStruct && Index >= Ty->getStructNumElements())\n          return error(\"EXTRACTVAL: Invalid struct index\");\n        if (IsArray && Index >= Ty->getArrayNumElements())\n          return error(\"EXTRACTVAL: Invalid array index\");\n        EXTRACTVALIdx.push_back((unsigned)Index);\n\n        if (IsStruct) {\n          Ty = Ty->getStructElementType(Index);\n          ResTypeID = getContainedTypeID(ResTypeID, Index);\n        } else {\n          Ty = Ty->getArrayElementType();\n          ResTypeID = getContainedTypeID(ResTypeID);\n        }\n      }\n\n      I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);\n      InstructionList.push_back(I);\n      break;\n    }\n\n    case bitc::FUNC_CODE_INST_INSERTVAL: {\n                           \/\/ INSERTVAL: [opty, opval, opty, opval, n x indices]\n      unsigned OpNum = 0;\n      Value *Agg;\n      unsigned AggTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID))\n        return error(\"Invalid record\");\n      Value *Val;\n      unsigned ValTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID))\n        return error(\"Invalid record\");\n\n      unsigned RecSize = Record.size();\n      if (OpNum == RecSize)\n        return error(\"INSERTVAL: Invalid instruction with 0 indices\");\n\n      SmallVector<unsigned, 4> INSERTVALIdx;\n      Type *CurTy = Agg->getType();\n      for (; OpNum != RecSize; ++OpNum) {\n        bool IsArray = CurTy->isArrayTy();\n        bool IsStruct = CurTy->isStructTy();\n        uint64_t Index = Record[OpNum];\n\n        if (!IsStruct && !IsArray)\n          return error(\"INSERTVAL: Invalid type\");\n        if ((unsigned)Index != Index)\n          return error(\"Invalid value\");\n        if (IsStruct && Index >= CurTy->getStructNumElements())\n          return error(\"INSERTVAL: Invalid struct index\");\n        if (IsArray && Index >= CurTy->getArrayNumElements())\n          return error(\"INSERTVAL: Invalid array index\");\n\n        INSERTVALIdx.push_back((unsigned)Index);\n        if (IsStruct)\n          CurTy = CurTy->getStructElementType(Index);\n        else\n          CurTy = CurTy->getArrayElementType();\n      }\n\n      if (CurTy != Val->getType())\n        return error(\"Inserted value type doesn't match aggregate type\");\n\n      I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);\n      ResTypeID = AggTypeID;\n      InstructionList.push_back(I);\n      break;\n    }\n\n    case bitc::FUNC_CODE_INST_SELECT: { \/\/ SELECT: [opval, ty, opval, opval]\n      \/\/ obsolete form of select\n      \/\/ handles select i1 ... in old bitcode\n      unsigned OpNum = 0;\n      Value *TrueVal, *FalseVal, *Cond;\n      unsigned TypeID;\n      Type *CondType = Type::getInt1Ty(Context);\n      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID) ||\n          popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,\n                   FalseVal) ||\n          popValue(Record, OpNum, NextValueNo, CondType,\n                   getVirtualTypeID(CondType), Cond))\n        return error(\"Invalid record\");\n\n      I = SelectInst::Create(Cond, TrueVal, FalseVal);\n      ResTypeID = TypeID;\n      InstructionList.push_back(I);\n      break;\n    }\n\n    case bitc::FUNC_CODE_INST_VSELECT: {\/\/ VSELECT: [ty,opval,opval,predty,pred]\n      \/\/ new form of select\n      \/\/ handles select i1 or select [N x i1]\n      unsigned OpNum = 0;\n      Value *TrueVal, *FalseVal, *Cond;\n      unsigned ValTypeID, CondTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID) ||\n          popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,\n                   FalseVal) ||\n          getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID))\n        return error(\"Invalid record\");\n\n      \/\/ select condition can be either i1 or [N x i1]\n      if (VectorType* vector_type =\n          dyn_cast<VectorType>(Cond->getType())) {\n        \/\/ expect <n x i1>\n        if (vector_type->getElementType() != Type::getInt1Ty(Context))\n          return error(\"Invalid type for value\");\n      } else {\n        \/\/ expect i1\n        if (Cond->getType() != Type::getInt1Ty(Context))\n          return error(\"Invalid type for value\");\n      }\n\n      I = SelectInst::Create(Cond, TrueVal, FalseVal);\n      ResTypeID = ValTypeID;\n      InstructionList.push_back(I);\n      if (OpNum < Record.size() && isa<FPMathOperator>(I)) {\n        FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);\n        if (FMF.any())\n          I->setFastMathFlags(FMF);\n      }\n      break;\n    }\n\n    case bitc::FUNC_CODE_INST_EXTRACTELT: { \/\/ EXTRACTELT: [opty, opval, opval]\n      unsigned OpNum = 0;\n      Value *Vec, *Idx;\n      unsigned VecTypeID, IdxTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID) ||\n          getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID))\n        return error(\"Invalid record\");\n      if (!Vec->getType()->isVectorTy())\n        return error(\"Invalid type for value\");\n      I = ExtractElementInst::Create(Vec, Idx);\n      ResTypeID = getContainedTypeID(VecTypeID);\n      InstructionList.push_back(I);\n      break;\n    }\n\n    case bitc::FUNC_CODE_INST_INSERTELT: { \/\/ INSERTELT: [ty, opval,opval,opval]\n      unsigned OpNum = 0;\n      Value *Vec, *Elt, *Idx;\n      unsigned VecTypeID, IdxTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID))\n        return error(\"Invalid record\");\n      if (!Vec->getType()->isVectorTy())\n        return error(\"Invalid type for value\");\n      if (popValue(Record, OpNum, NextValueNo,\n                   cast<VectorType>(Vec->getType())->getElementType(),\n                   getContainedTypeID(VecTypeID), Elt) ||\n          getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID))\n        return error(\"Invalid record\");\n      I = InsertElementInst::Create(Vec, Elt, Idx);\n      ResTypeID = VecTypeID;\n      InstructionList.push_back(I);\n      break;\n    }\n\n    case bitc::FUNC_CODE_INST_SHUFFLEVEC: {\/\/ SHUFFLEVEC: [opval,ty,opval,opval]\n      unsigned OpNum = 0;\n      Value *Vec1, *Vec2, *Mask;\n      unsigned Vec1TypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID) ||\n          popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,\n                   Vec2))\n        return error(\"Invalid record\");\n\n      unsigned MaskTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID))\n        return error(\"Invalid record\");\n      if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())\n        return error(\"Invalid type for value\");\n\n      I = new ShuffleVectorInst(Vec1, Vec2, Mask);\n      ResTypeID =\n          getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));\n      InstructionList.push_back(I);\n      break;\n    }\n\n    case bitc::FUNC_CODE_INST_CMP:   \/\/ CMP: [opty, opval, opval, pred]\n      \/\/ Old form of ICmp\/FCmp returning bool\n      \/\/ Existed to differentiate between icmp\/fcmp and vicmp\/vfcmp which were\n      \/\/ both legal on vectors but had different behaviour.\n    case bitc::FUNC_CODE_INST_CMP2: { \/\/ CMP2: [opty, opval, opval, pred]\n      \/\/ FCmp\/ICmp returning bool or vector of bool\n\n      unsigned OpNum = 0;\n      Value *LHS, *RHS;\n      unsigned LHSTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID) ||\n          popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS))\n        return error(\"Invalid record\");\n\n      if (OpNum >= Record.size())\n        return error(\n            \"Invalid record: operand number exceeded available operands\");\n\n      unsigned PredVal = Record[OpNum];\n      bool IsFP = LHS->getType()->isFPOrFPVectorTy();\n      FastMathFlags FMF;\n      if (IsFP && Record.size() > OpNum+1)\n        FMF = getDecodedFastMathFlags(Record[++OpNum]);\n\n      if (OpNum+1 != Record.size())\n        return error(\"Invalid record\");\n\n      if (LHS->getType()->isFPOrFPVectorTy())\n        I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);\n      else\n        I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);\n\n      ResTypeID = getVirtualTypeID(I->getType()->getScalarType());\n      if (LHS->getType()->isVectorTy())\n        ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);\n\n      if (FMF.any())\n        I->setFastMathFlags(FMF);\n      InstructionList.push_back(I);\n      break;\n    }\n\n    case bitc::FUNC_CODE_INST_RET: \/\/ RET: [opty,opval<optional>]\n      {\n        unsigned Size = Record.size();\n        if (Size == 0) {\n          I = ReturnInst::Create(Context);\n          InstructionList.push_back(I);\n          break;\n        }\n\n        unsigned OpNum = 0;\n        Value *Op = nullptr;\n        unsigned OpTypeID;\n        if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))\n          return error(\"Invalid record\");\n        if (OpNum != Record.size())\n          return error(\"Invalid record\");\n\n        I = ReturnInst::Create(Context, Op);\n        InstructionList.push_back(I);\n        break;\n      }\n    case bitc::FUNC_CODE_INST_BR: { \/\/ BR: [bb#, bb#, opval] or [bb#]\n      if (Record.size() != 1 && Record.size() != 3)\n        return error(\"Invalid record\");\n      BasicBlock *TrueDest = getBasicBlock(Record[0]);\n      if (!TrueDest)\n        return error(\"Invalid record\");\n\n      if (Record.size() == 1) {\n        I = BranchInst::Create(TrueDest);\n        InstructionList.push_back(I);\n      }\n      else {\n        BasicBlock *FalseDest = getBasicBlock(Record[1]);\n        Type *CondType = Type::getInt1Ty(Context);\n        Value *Cond = getValue(Record, 2, NextValueNo, CondType,\n                               getVirtualTypeID(CondType));\n        if (!FalseDest || !Cond)\n          return error(\"Invalid record\");\n        I = BranchInst::Create(TrueDest, FalseDest, Cond);\n        InstructionList.push_back(I);\n      }\n      break;\n    }\n    case bitc::FUNC_CODE_INST_CLEANUPRET: { \/\/ CLEANUPRET: [val] or [val,bb#]\n      if (Record.size() != 1 && Record.size() != 2)\n        return error(\"Invalid record\");\n      unsigned Idx = 0;\n      Type *TokenTy = Type::getTokenTy(Context);\n      Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,\n                                   getVirtualTypeID(TokenTy));\n      if (!CleanupPad)\n        return error(\"Invalid record\");\n      BasicBlock *UnwindDest = nullptr;\n      if (Record.size() == 2) {\n        UnwindDest = getBasicBlock(Record[Idx++]);\n        if (!UnwindDest)\n          return error(\"Invalid record\");\n      }\n\n      I = CleanupReturnInst::Create(CleanupPad, UnwindDest);\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_CATCHRET: { \/\/ CATCHRET: [val,bb#]\n      if (Record.size() != 2)\n        return error(\"Invalid record\");\n      unsigned Idx = 0;\n      Type *TokenTy = Type::getTokenTy(Context);\n      Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,\n                                 getVirtualTypeID(TokenTy));\n      if (!CatchPad)\n        return error(\"Invalid record\");\n      BasicBlock *BB = getBasicBlock(Record[Idx++]);\n      if (!BB)\n        return error(\"Invalid record\");\n\n      I = CatchReturnInst::Create(CatchPad, BB);\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_CATCHSWITCH: { \/\/ CATCHSWITCH: [tok,num,(bb)*,bb?]\n      \/\/ We must have, at minimum, the outer scope and the number of arguments.\n      if (Record.size() < 2)\n        return error(\"Invalid record\");\n\n      unsigned Idx = 0;\n\n      Type *TokenTy = Type::getTokenTy(Context);\n      Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,\n                                  getVirtualTypeID(TokenTy));\n\n      unsigned NumHandlers = Record[Idx++];\n\n      SmallVector<BasicBlock *, 2> Handlers;\n      for (unsigned Op = 0; Op != NumHandlers; ++Op) {\n        BasicBlock *BB = getBasicBlock(Record[Idx++]);\n        if (!BB)\n          return error(\"Invalid record\");\n        Handlers.push_back(BB);\n      }\n\n      BasicBlock *UnwindDest = nullptr;\n      if (Idx + 1 == Record.size()) {\n        UnwindDest = getBasicBlock(Record[Idx++]);\n        if (!UnwindDest)\n          return error(\"Invalid record\");\n      }\n\n      if (Record.size() != Idx)\n        return error(\"Invalid record\");\n\n      auto *CatchSwitch =\n          CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);\n      for (BasicBlock *Handler : Handlers)\n        CatchSwitch->addHandler(Handler);\n      I = CatchSwitch;\n      ResTypeID = getVirtualTypeID(I->getType());\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_CATCHPAD:\n    case bitc::FUNC_CODE_INST_CLEANUPPAD: { \/\/ [tok,num,(ty,val)*]\n      \/\/ We must have, at minimum, the outer scope and the number of arguments.\n      if (Record.size() < 2)\n        return error(\"Invalid record\");\n\n      unsigned Idx = 0;\n\n      Type *TokenTy = Type::getTokenTy(Context);\n      Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,\n                                  getVirtualTypeID(TokenTy));\n\n      unsigned NumArgOperands = Record[Idx++];\n\n      SmallVector<Value *, 2> Args;\n      for (unsigned Op = 0; Op != NumArgOperands; ++Op) {\n        Value *Val;\n        unsigned ValTypeID;\n        if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID))\n          return error(\"Invalid record\");\n        Args.push_back(Val);\n      }\n\n      if (Record.size() != Idx)\n        return error(\"Invalid record\");\n\n      if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)\n        I = CleanupPadInst::Create(ParentPad, Args);\n      else\n        I = CatchPadInst::Create(ParentPad, Args);\n      ResTypeID = getVirtualTypeID(I->getType());\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_SWITCH: { \/\/ SWITCH: [opty, op0, op1, ...]\n      \/\/ Check magic\n      if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {\n        \/\/ \"New\" SwitchInst format with case ranges. The changes to write this\n        \/\/ format were reverted but we still recognize bitcode that uses it.\n        \/\/ Hopefully someday we will have support for case ranges and can use\n        \/\/ this format again.\n\n        unsigned OpTyID = Record[1];\n        Type *OpTy = getTypeByID(OpTyID);\n        unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();\n\n        Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID);\n        BasicBlock *Default = getBasicBlock(Record[3]);\n        if (!OpTy || !Cond || !Default)\n          return error(\"Invalid record\");\n\n        unsigned NumCases = Record[4];\n\n        SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);\n        InstructionList.push_back(SI);\n\n        unsigned CurIdx = 5;\n        for (unsigned i = 0; i != NumCases; ++i) {\n          SmallVector<ConstantInt*, 1> CaseVals;\n          unsigned NumItems = Record[CurIdx++];\n          for (unsigned ci = 0; ci != NumItems; ++ci) {\n            bool isSingleNumber = Record[CurIdx++];\n\n            APInt Low;\n            unsigned ActiveWords = 1;\n            if (ValueBitWidth > 64)\n              ActiveWords = Record[CurIdx++];\n            Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),\n                                ValueBitWidth);\n            CurIdx += ActiveWords;\n\n            if (!isSingleNumber) {\n              ActiveWords = 1;\n              if (ValueBitWidth > 64)\n                ActiveWords = Record[CurIdx++];\n              APInt High = readWideAPInt(\n                  makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);\n              CurIdx += ActiveWords;\n\n              \/\/ FIXME: It is not clear whether values in the range should be\n              \/\/ compared as signed or unsigned values. The partially\n              \/\/ implemented changes that used this format in the past used\n              \/\/ unsigned comparisons.\n              for ( ; Low.ule(High); ++Low)\n                CaseVals.push_back(ConstantInt::get(Context, Low));\n            } else\n              CaseVals.push_back(ConstantInt::get(Context, Low));\n          }\n          BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);\n          for (ConstantInt *Cst : CaseVals)\n            SI->addCase(Cst, DestBB);\n        }\n        I = SI;\n        break;\n      }\n\n      \/\/ Old SwitchInst format without case ranges.\n\n      if (Record.size() < 3 || (Record.size() & 1) == 0)\n        return error(\"Invalid record\");\n      unsigned OpTyID = Record[0];\n      Type *OpTy = getTypeByID(OpTyID);\n      Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID);\n      BasicBlock *Default = getBasicBlock(Record[2]);\n      if (!OpTy || !Cond || !Default)\n        return error(\"Invalid record\");\n      unsigned NumCases = (Record.size()-3)\/2;\n      SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);\n      InstructionList.push_back(SI);\n      for (unsigned i = 0, e = NumCases; i != e; ++i) {\n        ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(\n            getFnValueByID(Record[3+i*2], OpTy, OpTyID));\n        BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);\n        if (!CaseVal || !DestBB) {\n          delete SI;\n          return error(\"Invalid record\");\n        }\n        SI->addCase(CaseVal, DestBB);\n      }\n      I = SI;\n      break;\n    }\n    case bitc::FUNC_CODE_INST_INDIRECTBR: { \/\/ INDIRECTBR: [opty, op0, op1, ...]\n      if (Record.size() < 2)\n        return error(\"Invalid record\");\n      unsigned OpTyID = Record[0];\n      Type *OpTy = getTypeByID(OpTyID);\n      Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID);\n      if (!OpTy || !Address)\n        return error(\"Invalid record\");\n      unsigned NumDests = Record.size()-2;\n      IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);\n      InstructionList.push_back(IBI);\n      for (unsigned i = 0, e = NumDests; i != e; ++i) {\n        if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {\n          IBI->addDestination(DestBB);\n        } else {\n          delete IBI;\n          return error(\"Invalid record\");\n        }\n      }\n      I = IBI;\n      break;\n    }\n\n    case bitc::FUNC_CODE_INST_INVOKE: {\n      \/\/ INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]\n      if (Record.size() < 4)\n        return error(\"Invalid record\");\n      unsigned OpNum = 0;\n      AttributeList PAL = getAttributes(Record[OpNum++]);\n      unsigned CCInfo = Record[OpNum++];\n      BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);\n      BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);\n\n      unsigned FTyID = InvalidTypeID;\n      FunctionType *FTy = nullptr;\n      if ((CCInfo >> 13) & 1) {\n        FTyID = Record[OpNum++];\n        FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));\n        if (!FTy)\n          return error(\"Explicit invoke type is not a function type\");\n      }\n\n      Value *Callee;\n      unsigned CalleeTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID))\n        return error(\"Invalid record\");\n\n      PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());\n      if (!CalleeTy)\n        return error(\"Callee is not a pointer\");\n      if (!FTy) {\n        FTyID = getContainedTypeID(CalleeTypeID);\n        FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));\n        if (!FTy)\n          return error(\"Callee is not of pointer to function type\");\n      } else if (!CalleeTy->isOpaqueOrPointeeTypeMatches(FTy))\n        return error(\"Explicit invoke type does not match pointee type of \"\n                     \"callee operand\");\n      if (Record.size() < FTy->getNumParams() + OpNum)\n        return error(\"Insufficient operands to call\");\n\n      SmallVector<Value*, 16> Ops;\n      SmallVector<unsigned, 16> ArgTyIDs;\n      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {\n        unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);\n        Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),\n                               ArgTyID));\n        ArgTyIDs.push_back(ArgTyID);\n        if (!Ops.back())\n          return error(\"Invalid record\");\n      }\n\n      if (!FTy->isVarArg()) {\n        if (Record.size() != OpNum)\n          return error(\"Invalid record\");\n      } else {\n        \/\/ Read type\/value pairs for varargs params.\n        while (OpNum != Record.size()) {\n          Value *Op;\n          unsigned OpTypeID;\n          if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))\n            return error(\"Invalid record\");\n          Ops.push_back(Op);\n          ArgTyIDs.push_back(OpTypeID);\n        }\n      }\n\n      I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,\n                             OperandBundles);\n      ResTypeID = getContainedTypeID(FTyID);\n      OperandBundles.clear();\n      InstructionList.push_back(I);\n      cast<InvokeInst>(I)->setCallingConv(\n          static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));\n      cast<InvokeInst>(I)->setAttributes(PAL);\n      if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {\n        I->deleteValue();\n        return Err;\n      }\n\n      break;\n    }\n    case bitc::FUNC_CODE_INST_RESUME: { \/\/ RESUME: [opval]\n      unsigned Idx = 0;\n      Value *Val = nullptr;\n      unsigned ValTypeID;\n      if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID))\n        return error(\"Invalid record\");\n      I = ResumeInst::Create(Val);\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_CALLBR: {\n      \/\/ CALLBR: [attr, cc, norm, transfs, fty, fnid, args]\n      unsigned OpNum = 0;\n      AttributeList PAL = getAttributes(Record[OpNum++]);\n      unsigned CCInfo = Record[OpNum++];\n\n      BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);\n      unsigned NumIndirectDests = Record[OpNum++];\n      SmallVector<BasicBlock *, 16> IndirectDests;\n      for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)\n        IndirectDests.push_back(getBasicBlock(Record[OpNum++]));\n\n      unsigned FTyID = InvalidTypeID;\n      FunctionType *FTy = nullptr;\n      if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {\n        FTyID = Record[OpNum++];\n        FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));\n        if (!FTy)\n          return error(\"Explicit call type is not a function type\");\n      }\n\n      Value *Callee;\n      unsigned CalleeTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID))\n        return error(\"Invalid record\");\n\n      PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());\n      if (!OpTy)\n        return error(\"Callee is not a pointer type\");\n      if (!FTy) {\n        FTyID = getContainedTypeID(CalleeTypeID);\n        FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));\n        if (!FTy)\n          return error(\"Callee is not of pointer to function type\");\n      } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))\n        return error(\"Explicit call type does not match pointee type of \"\n                     \"callee operand\");\n      if (Record.size() < FTy->getNumParams() + OpNum)\n        return error(\"Insufficient operands to call\");\n\n      SmallVector<Value*, 16> Args;\n      SmallVector<unsigned, 16> ArgTyIDs;\n      \/\/ Read the fixed params.\n      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {\n        Value *Arg;\n        unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);\n        if (FTy->getParamType(i)->isLabelTy())\n          Arg = getBasicBlock(Record[OpNum]);\n        else\n          Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),\n                         ArgTyID);\n        if (!Arg)\n          return error(\"Invalid record\");\n        Args.push_back(Arg);\n        ArgTyIDs.push_back(ArgTyID);\n      }\n\n      \/\/ Read type\/value pairs for varargs params.\n      if (!FTy->isVarArg()) {\n        if (OpNum != Record.size())\n          return error(\"Invalid record\");\n      } else {\n        while (OpNum != Record.size()) {\n          Value *Op;\n          unsigned OpTypeID;\n          if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))\n            return error(\"Invalid record\");\n          Args.push_back(Op);\n          ArgTyIDs.push_back(OpTypeID);\n        }\n      }\n\n      I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,\n                             OperandBundles);\n      ResTypeID = getContainedTypeID(FTyID);\n      OperandBundles.clear();\n      InstructionList.push_back(I);\n      cast<CallBrInst>(I)->setCallingConv(\n          static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));\n      cast<CallBrInst>(I)->setAttributes(PAL);\n      if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {\n        I->deleteValue();\n        return Err;\n      }\n      break;\n    }\n    case bitc::FUNC_CODE_INST_UNREACHABLE: \/\/ UNREACHABLE\n      I = new UnreachableInst(Context);\n      InstructionList.push_back(I);\n      break;\n    case bitc::FUNC_CODE_INST_PHI: { \/\/ PHI: [ty, val0,bb0, ...]\n      if (Record.empty())\n        return error(\"Invalid phi record\");\n      \/\/ The first record specifies the type.\n      unsigned TyID = Record[0];\n      Type *Ty = getTypeByID(TyID);\n      if (!Ty)\n        return error(\"Invalid phi record\");\n\n      \/\/ Phi arguments are pairs of records of [value, basic block].\n      \/\/ There is an optional final record for fast-math-flags if this phi has a\n      \/\/ floating-point type.\n      size_t NumArgs = (Record.size() - 1) \/ 2;\n      PHINode *PN = PHINode::Create(Ty, NumArgs);\n      if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {\n        PN->deleteValue();\n        return error(\"Invalid phi record\");\n      }\n      InstructionList.push_back(PN);\n\n      for (unsigned i = 0; i != NumArgs; i++) {\n        Value *V;\n        \/\/ With the new function encoding, it is possible that operands have\n        \/\/ negative IDs (for forward references).  Use a signed VBR\n        \/\/ representation to keep the encoding small.\n        if (UseRelativeIDs)\n          V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID);\n        else\n          V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID);\n        BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);\n        if (!V || !BB) {\n          PN->deleteValue();\n          return error(\"Invalid phi record\");\n        }\n        PN->addIncoming(V, BB);\n      }\n      I = PN;\n      ResTypeID = TyID;\n\n      \/\/ If there are an even number of records, the final record must be FMF.\n      if (Record.size() % 2 == 0) {\n        assert(isa<FPMathOperator>(I) && \"Unexpected phi type\");\n        FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);\n        if (FMF.any())\n          I->setFastMathFlags(FMF);\n      }\n\n      break;\n    }\n\n    case bitc::FUNC_CODE_INST_LANDINGPAD:\n    case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {\n      \/\/ LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]\n      unsigned Idx = 0;\n      if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {\n        if (Record.size() < 3)\n          return error(\"Invalid record\");\n      } else {\n        assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);\n        if (Record.size() < 4)\n          return error(\"Invalid record\");\n      }\n      ResTypeID = Record[Idx++];\n      Type *Ty = getTypeByID(ResTypeID);\n      if (!Ty)\n        return error(\"Invalid record\");\n      if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {\n        Value *PersFn = nullptr;\n        unsigned PersFnTypeID;\n        if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID))\n          return error(\"Invalid record\");\n\n        if (!F->hasPersonalityFn())\n          F->setPersonalityFn(cast<Constant>(PersFn));\n        else if (F->getPersonalityFn() != cast<Constant>(PersFn))\n          return error(\"Personality function mismatch\");\n      }\n\n      bool IsCleanup = !!Record[Idx++];\n      unsigned NumClauses = Record[Idx++];\n      LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);\n      LP->setCleanup(IsCleanup);\n      for (unsigned J = 0; J != NumClauses; ++J) {\n        LandingPadInst::ClauseType CT =\n          LandingPadInst::ClauseType(Record[Idx++]); (void)CT;\n        Value *Val;\n        unsigned ValTypeID;\n\n        if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID)) {\n          delete LP;\n          return error(\"Invalid record\");\n        }\n\n        assert((CT != LandingPadInst::Catch ||\n                !isa<ArrayType>(Val->getType())) &&\n               \"Catch clause has a invalid type!\");\n        assert((CT != LandingPadInst::Filter ||\n                isa<ArrayType>(Val->getType())) &&\n               \"Filter clause has invalid type!\");\n        LP->addClause(cast<Constant>(Val));\n      }\n\n      I = LP;\n      InstructionList.push_back(I);\n      break;\n    }\n\n    case bitc::FUNC_CODE_INST_ALLOCA: { \/\/ ALLOCA: [instty, opty, op, align]\n      if (Record.size() != 4 && Record.size() != 5)\n        return error(\"Invalid record\");\n      using APV = AllocaPackedValues;\n      const uint64_t Rec = Record[3];\n      const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);\n      const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);\n      unsigned TyID = Record[0];\n      Type *Ty = getTypeByID(TyID);\n      if (!Bitfield::get<APV::ExplicitType>(Rec)) {\n        TyID = getContainedTypeID(TyID);\n        Ty = getTypeByID(TyID);\n        if (!Ty)\n          return error(\"Missing element type for old-style alloca\");\n      }\n      unsigned OpTyID = Record[1];\n      Type *OpTy = getTypeByID(OpTyID);\n      Value *Size = getFnValueByID(Record[2], OpTy, OpTyID);\n      MaybeAlign Align;\n      uint64_t AlignExp =\n          Bitfield::get<APV::AlignLower>(Rec) |\n          (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);\n      if (Error Err = parseAlignmentValue(AlignExp, Align)) {\n        return Err;\n      }\n      if (!Ty || !Size)\n        return error(\"Invalid record\");\n\n      const DataLayout &DL = TheModule->getDataLayout();\n      unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();\n\n      SmallPtrSet<Type *, 4> Visited;\n      if (!Align && !Ty->isSized(&Visited))\n        return error(\"alloca of unsized type\");\n      if (!Align)\n        Align = DL.getPrefTypeAlign(Ty);\n\n      AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);\n      AI->setUsedWithInAlloca(InAlloca);\n      AI->setSwiftError(SwiftError);\n      I = AI;\n      ResTypeID = getVirtualTypeID(AI->getType(), TyID);\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_LOAD: { \/\/ LOAD: [opty, op, align, vol]\n      unsigned OpNum = 0;\n      Value *Op;\n      unsigned OpTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID) ||\n          (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))\n        return error(\"Invalid record\");\n\n      if (!isa<PointerType>(Op->getType()))\n        return error(\"Load operand is not a pointer type\");\n\n      Type *Ty = nullptr;\n      if (OpNum + 3 == Record.size()) {\n        ResTypeID = Record[OpNum++];\n        Ty = getTypeByID(ResTypeID);\n      } else {\n        ResTypeID = getContainedTypeID(OpTypeID);\n        Ty = getTypeByID(ResTypeID);\n        if (!Ty)\n          return error(\"Missing element type for old-style load\");\n      }\n\n      if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))\n        return Err;\n\n      MaybeAlign Align;\n      if (Error Err = parseAlignmentValue(Record[OpNum], Align))\n        return Err;\n      SmallPtrSet<Type *, 4> Visited;\n      if (!Align && !Ty->isSized(&Visited))\n        return error(\"load of unsized type\");\n      if (!Align)\n        Align = TheModule->getDataLayout().getABITypeAlign(Ty);\n      I = new LoadInst(Ty, Op, \"\", Record[OpNum + 1], *Align);\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_LOADATOMIC: {\n       \/\/ LOADATOMIC: [opty, op, align, vol, ordering, ssid]\n      unsigned OpNum = 0;\n      Value *Op;\n      unsigned OpTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID) ||\n          (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))\n        return error(\"Invalid record\");\n\n      if (!isa<PointerType>(Op->getType()))\n        return error(\"Load operand is not a pointer type\");\n\n      Type *Ty = nullptr;\n      if (OpNum + 5 == Record.size()) {\n        ResTypeID = Record[OpNum++];\n        Ty = getTypeByID(ResTypeID);\n      } else {\n        ResTypeID = getContainedTypeID(OpTypeID);\n        Ty = getTypeByID(ResTypeID);\n        if (!Ty)\n          return error(\"Missing element type for old style atomic load\");\n      }\n\n      if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))\n        return Err;\n\n      AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);\n      if (Ordering == AtomicOrdering::NotAtomic ||\n          Ordering == AtomicOrdering::Release ||\n          Ordering == AtomicOrdering::AcquireRelease)\n        return error(\"Invalid record\");\n      if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)\n        return error(\"Invalid record\");\n      SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);\n\n      MaybeAlign Align;\n      if (Error Err = parseAlignmentValue(Record[OpNum], Align))\n        return Err;\n      if (!Align)\n        return error(\"Alignment missing from atomic load\");\n      I = new LoadInst(Ty, Op, \"\", Record[OpNum + 1], *Align, Ordering, SSID);\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_STORE:\n    case bitc::FUNC_CODE_INST_STORE_OLD: { \/\/ STORE2:[ptrty, ptr, val, align, vol]\n      unsigned OpNum = 0;\n      Value *Val, *Ptr;\n      unsigned PtrTypeID, ValTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID))\n        return error(\"Invalid record\");\n\n      if (BitCode == bitc::FUNC_CODE_INST_STORE) {\n        if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID))\n          return error(\"Invalid record\");\n      } else {\n        ValTypeID = getContainedTypeID(PtrTypeID);\n        if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),\n                     ValTypeID, Val))\n          return error(\"Invalid record\");\n      }\n\n      if (OpNum + 2 != Record.size())\n        return error(\"Invalid record\");\n\n      if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))\n        return Err;\n      MaybeAlign Align;\n      if (Error Err = parseAlignmentValue(Record[OpNum], Align))\n        return Err;\n      SmallPtrSet<Type *, 4> Visited;\n      if (!Align && !Val->getType()->isSized(&Visited))\n        return error(\"store of unsized type\");\n      if (!Align)\n        Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());\n      I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_STOREATOMIC:\n    case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {\n      \/\/ STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]\n      unsigned OpNum = 0;\n      Value *Val, *Ptr;\n      unsigned PtrTypeID, ValTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID) ||\n          !isa<PointerType>(Ptr->getType()))\n        return error(\"Invalid record\");\n      if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {\n        if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID))\n          return error(\"Invalid record\");\n      } else {\n        ValTypeID = getContainedTypeID(PtrTypeID);\n        if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),\n                     ValTypeID, Val))\n          return error(\"Invalid record\");\n      }\n\n      if (OpNum + 4 != Record.size())\n        return error(\"Invalid record\");\n\n      if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))\n        return Err;\n      AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);\n      if (Ordering == AtomicOrdering::NotAtomic ||\n          Ordering == AtomicOrdering::Acquire ||\n          Ordering == AtomicOrdering::AcquireRelease)\n        return error(\"Invalid record\");\n      SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);\n      if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)\n        return error(\"Invalid record\");\n\n      MaybeAlign Align;\n      if (Error Err = parseAlignmentValue(Record[OpNum], Align))\n        return Err;\n      if (!Align)\n        return error(\"Alignment missing from atomic store\");\n      I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {\n      \/\/ CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,\n      \/\/ failure_ordering?, weak?]\n      const size_t NumRecords = Record.size();\n      unsigned OpNum = 0;\n      Value *Ptr = nullptr;\n      unsigned PtrTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID))\n        return error(\"Invalid record\");\n\n      if (!isa<PointerType>(Ptr->getType()))\n        return error(\"Cmpxchg operand is not a pointer type\");\n\n      Value *Cmp = nullptr;\n      unsigned CmpTypeID = getContainedTypeID(PtrTypeID);\n      if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),\n                   CmpTypeID, Cmp))\n        return error(\"Invalid record\");\n\n      Value *New = nullptr;\n      if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,\n                   New) ||\n          NumRecords < OpNum + 3 || NumRecords > OpNum + 5)\n        return error(\"Invalid record\");\n\n      const AtomicOrdering SuccessOrdering =\n          getDecodedOrdering(Record[OpNum + 1]);\n      if (SuccessOrdering == AtomicOrdering::NotAtomic ||\n          SuccessOrdering == AtomicOrdering::Unordered)\n        return error(\"Invalid record\");\n\n      const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);\n\n      if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))\n        return Err;\n\n      const AtomicOrdering FailureOrdering =\n          NumRecords < 7\n              ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)\n              : getDecodedOrdering(Record[OpNum + 3]);\n\n      if (FailureOrdering == AtomicOrdering::NotAtomic ||\n          FailureOrdering == AtomicOrdering::Unordered)\n        return error(\"Invalid record\");\n\n      const Align Alignment(\n          TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));\n\n      I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,\n                                FailureOrdering, SSID);\n      cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);\n\n      if (NumRecords < 8) {\n        \/\/ Before weak cmpxchgs existed, the instruction simply returned the\n        \/\/ value loaded from memory, so bitcode files from that era will be\n        \/\/ expecting the first component of a modern cmpxchg.\n        CurBB->getInstList().push_back(I);\n        I = ExtractValueInst::Create(I, 0);\n        ResTypeID = CmpTypeID;\n      } else {\n        cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);\n        unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));\n        ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});\n      }\n\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_CMPXCHG: {\n      \/\/ CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,\n      \/\/ failure_ordering, weak, align?]\n      const size_t NumRecords = Record.size();\n      unsigned OpNum = 0;\n      Value *Ptr = nullptr;\n      unsigned PtrTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID))\n        return error(\"Invalid record\");\n\n      if (!isa<PointerType>(Ptr->getType()))\n        return error(\"Cmpxchg operand is not a pointer type\");\n\n      Value *Cmp = nullptr;\n      unsigned CmpTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID))\n        return error(\"Invalid record\");\n\n      Value *Val = nullptr;\n      if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val))\n        return error(\"Invalid record\");\n\n      if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)\n        return error(\"Invalid record\");\n\n      const bool IsVol = Record[OpNum];\n\n      const AtomicOrdering SuccessOrdering =\n          getDecodedOrdering(Record[OpNum + 1]);\n      if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))\n        return error(\"Invalid cmpxchg success ordering\");\n\n      const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);\n\n      if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))\n        return Err;\n\n      const AtomicOrdering FailureOrdering =\n          getDecodedOrdering(Record[OpNum + 3]);\n      if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))\n        return error(\"Invalid cmpxchg failure ordering\");\n\n      const bool IsWeak = Record[OpNum + 4];\n\n      MaybeAlign Alignment;\n\n      if (NumRecords == (OpNum + 6)) {\n        if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))\n          return Err;\n      }\n      if (!Alignment)\n        Alignment =\n            Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));\n\n      I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,\n                                FailureOrdering, SSID);\n      cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);\n      cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);\n\n      unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));\n      ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});\n\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:\n    case bitc::FUNC_CODE_INST_ATOMICRMW: {\n      \/\/ ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]\n      \/\/ ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]\n      const size_t NumRecords = Record.size();\n      unsigned OpNum = 0;\n\n      Value *Ptr = nullptr;\n      unsigned PtrTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID))\n        return error(\"Invalid record\");\n\n      if (!isa<PointerType>(Ptr->getType()))\n        return error(\"Invalid record\");\n\n      Value *Val = nullptr;\n      unsigned ValTypeID = InvalidTypeID;\n      if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {\n        ValTypeID = getContainedTypeID(PtrTypeID);\n        if (popValue(Record, OpNum, NextValueNo,\n                     getTypeByID(ValTypeID), ValTypeID, Val))\n          return error(\"Invalid record\");\n      } else {\n        if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID))\n          return error(\"Invalid record\");\n      }\n\n      if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))\n        return error(\"Invalid record\");\n\n      const AtomicRMWInst::BinOp Operation =\n          getDecodedRMWOperation(Record[OpNum]);\n      if (Operation < AtomicRMWInst::FIRST_BINOP ||\n          Operation > AtomicRMWInst::LAST_BINOP)\n        return error(\"Invalid record\");\n\n      const bool IsVol = Record[OpNum + 1];\n\n      const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);\n      if (Ordering == AtomicOrdering::NotAtomic ||\n          Ordering == AtomicOrdering::Unordered)\n        return error(\"Invalid record\");\n\n      const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);\n\n      MaybeAlign Alignment;\n\n      if (NumRecords == (OpNum + 5)) {\n        if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))\n          return Err;\n      }\n\n      if (!Alignment)\n        Alignment =\n            Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));\n\n      I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);\n      ResTypeID = ValTypeID;\n      cast<AtomicRMWInst>(I)->setVolatile(IsVol);\n\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_FENCE: { \/\/ FENCE:[ordering, ssid]\n      if (2 != Record.size())\n        return error(\"Invalid record\");\n      AtomicOrdering Ordering = getDecodedOrdering(Record[0]);\n      if (Ordering == AtomicOrdering::NotAtomic ||\n          Ordering == AtomicOrdering::Unordered ||\n          Ordering == AtomicOrdering::Monotonic)\n        return error(\"Invalid record\");\n      SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);\n      I = new FenceInst(Context, Ordering, SSID);\n      InstructionList.push_back(I);\n      break;\n    }\n    case bitc::FUNC_CODE_INST_CALL: {\n      \/\/ CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]\n      if (Record.size() < 3)\n        return error(\"Invalid record\");\n\n      unsigned OpNum = 0;\n      AttributeList PAL = getAttributes(Record[OpNum++]);\n      unsigned CCInfo = Record[OpNum++];\n\n      FastMathFlags FMF;\n      if ((CCInfo >> bitc::CALL_FMF) & 1) {\n        FMF = getDecodedFastMathFlags(Record[OpNum++]);\n        if (!FMF.any())\n          return error(\"Fast math flags indicator set for call with no FMF\");\n      }\n\n      unsigned FTyID = InvalidTypeID;\n      FunctionType *FTy = nullptr;\n      if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {\n        FTyID = Record[OpNum++];\n        FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));\n        if (!FTy)\n          return error(\"Explicit call type is not a function type\");\n      }\n\n      Value *Callee;\n      unsigned CalleeTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID))\n        return error(\"Invalid record\");\n\n      PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());\n      if (!OpTy)\n        return error(\"Callee is not a pointer type\");\n      if (!FTy) {\n        FTyID = getContainedTypeID(CalleeTypeID);\n        FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));\n        if (!FTy)\n          return error(\"Callee is not of pointer to function type\");\n      } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))\n        return error(\"Explicit call type does not match pointee type of \"\n                     \"callee operand\");\n      if (Record.size() < FTy->getNumParams() + OpNum)\n        return error(\"Insufficient operands to call\");\n\n      SmallVector<Value*, 16> Args;\n      SmallVector<unsigned, 16> ArgTyIDs;\n      \/\/ Read the fixed params.\n      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {\n        unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);\n        if (FTy->getParamType(i)->isLabelTy())\n          Args.push_back(getBasicBlock(Record[OpNum]));\n        else\n          Args.push_back(getValue(Record, OpNum, NextValueNo,\n                                  FTy->getParamType(i), ArgTyID));\n        ArgTyIDs.push_back(ArgTyID);\n        if (!Args.back())\n          return error(\"Invalid record\");\n      }\n\n      \/\/ Read type\/value pairs for varargs params.\n      if (!FTy->isVarArg()) {\n        if (OpNum != Record.size())\n          return error(\"Invalid record\");\n      } else {\n        while (OpNum != Record.size()) {\n          Value *Op;\n          unsigned OpTypeID;\n          if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))\n            return error(\"Invalid record\");\n          Args.push_back(Op);\n          ArgTyIDs.push_back(OpTypeID);\n        }\n      }\n\n      I = CallInst::Create(FTy, Callee, Args, OperandBundles);\n      ResTypeID = getContainedTypeID(FTyID);\n      OperandBundles.clear();\n      InstructionList.push_back(I);\n      cast<CallInst>(I)->setCallingConv(\n          static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));\n      CallInst::TailCallKind TCK = CallInst::TCK_None;\n      if (CCInfo & 1 << bitc::CALL_TAIL)\n        TCK = CallInst::TCK_Tail;\n      if (CCInfo & (1 << bitc::CALL_MUSTTAIL))\n        TCK = CallInst::TCK_MustTail;\n      if (CCInfo & (1 << bitc::CALL_NOTAIL))\n        TCK = CallInst::TCK_NoTail;\n      cast<CallInst>(I)->setTailCallKind(TCK);\n      cast<CallInst>(I)->setAttributes(PAL);\n      if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {\n        I->deleteValue();\n        return Err;\n      }\n      if (FMF.any()) {\n        if (!isa<FPMathOperator>(I))\n          return error(\"Fast-math-flags specified for call without \"\n                       \"floating-point scalar or vector return type\");\n        I->setFastMathFlags(FMF);\n      }\n      break;\n    }\n    case bitc::FUNC_CODE_INST_VAARG: { \/\/ VAARG: [valistty, valist, instty]\n      if (Record.size() < 3)\n        return error(\"Invalid record\");\n      unsigned OpTyID = Record[0];\n      Type *OpTy = getTypeByID(OpTyID);\n      Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID);\n      ResTypeID = Record[2];\n      Type *ResTy = getTypeByID(ResTypeID);\n      if (!OpTy || !Op || !ResTy)\n        return error(\"Invalid record\");\n      I = new VAArgInst(Op, ResTy);\n      InstructionList.push_back(I);\n      break;\n    }\n\n    case bitc::FUNC_CODE_OPERAND_BUNDLE: {\n      \/\/ A call or an invoke can be optionally prefixed with some variable\n      \/\/ number of operand bundle blocks.  These blocks are read into\n      \/\/ OperandBundles and consumed at the next call or invoke instruction.\n\n      if (Record.empty() || Record[0] >= BundleTags.size())\n        return error(\"Invalid record\");\n\n      std::vector<Value *> Inputs;\n\n      unsigned OpNum = 1;\n      while (OpNum != Record.size()) {\n        Value *Op;\n        unsigned OpTypeID;\n        if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))\n          return error(\"Invalid record\");\n        Inputs.push_back(Op);\n      }\n\n      OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));\n      continue;\n    }\n\n    case bitc::FUNC_CODE_INST_FREEZE: { \/\/ FREEZE: [opty,opval]\n      unsigned OpNum = 0;\n      Value *Op = nullptr;\n      unsigned OpTypeID;\n      if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))\n        return error(\"Invalid record\");\n      if (OpNum != Record.size())\n        return error(\"Invalid record\");\n\n      I = new FreezeInst(Op);\n      ResTypeID = OpTypeID;\n      InstructionList.push_back(I);\n      break;\n    }\n    }\n\n    \/\/ Add instruction to end of current BB.  If there is no current BB, reject\n    \/\/ this file.\n    if (!CurBB) {\n      I->deleteValue();\n      return error(\"Invalid instruction with no BB\");\n    }\n    if (!OperandBundles.empty()) {\n      I->deleteValue();\n      return error(\"Operand bundles found with no consumer\");\n    }\n    CurBB->getInstList().push_back(I);\n\n    \/\/ If this was a terminator instruction, move to the next block.\n    if (I->isTerminator()) {\n      ++CurBBNo;\n      CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;\n    }\n\n    \/\/ Non-void values get registered in the value table for future use.\n    if (!I->getType()->isVoidTy()) {\n      assert(I->getType() == getTypeByID(ResTypeID) &&\n             \"Incorrect result type ID\");\n      if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID))\n        return Err;\n    }\n  }\n\nOutOfRecordLoop:\n\n  if (!OperandBundles.empty())\n    return error(\"Operand bundles found with no consumer\");\n\n  \/\/ Check the function list for unresolved values.\n  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {\n    if (!A->getParent()) {\n      \/\/ We found at least one unresolved value.  Nuke them all to avoid leaks.\n      for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){\n        if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {\n          A->replaceAllUsesWith(UndefValue::get(A->getType()));\n          delete A;\n        }\n      }\n      return error(\"Never resolved value found in function\");\n    }\n  }\n\n  \/\/ Unexpected unresolved metadata about to be dropped.\n  if (MDLoader->hasFwdRefs())\n    return error(\"Invalid function metadata: outgoing forward refs\");\n\n  \/\/ Trim the value list down to the size it was before we parsed this function.\n  ValueList.shrinkTo(ModuleValueListSize);\n  MDLoader->shrinkTo(ModuleMDLoaderSize);\n  std::vector<BasicBlock*>().swap(FunctionBBs);\n  return Error::success();\n}\n\n\/\/\/ Find the function body in the bitcode stream\nError BitcodeReader::findFunctionInStream(\n    Function *F,\n    DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {\n  while (DeferredFunctionInfoIterator->second == 0) {\n    \/\/ This is the fallback handling for the old format bitcode that\n    \/\/ didn't contain the function index in the VST, or when we have\n    \/\/ an anonymous function which would not have a VST entry.\n    \/\/ Assert that we have one of those two cases.\n    assert(VSTOffset == 0 || !F->hasName());\n    \/\/ Parse the next body in the stream and set its position in the\n    \/\/ DeferredFunctionInfo map.\n    if (Error Err = rememberAndSkipFunctionBodies())\n      return Err;\n  }\n  return Error::success();\n}\n\nSyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {\n  if (Val == SyncScope::SingleThread || Val == SyncScope::System)\n    return SyncScope::ID(Val);\n  if (Val >= SSIDs.size())\n    return SyncScope::System; \/\/ Map unknown synchronization scopes to system.\n  return SSIDs[Val];\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ GVMaterializer implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nError BitcodeReader::materialize(GlobalValue *GV) {\n  Function *F = dyn_cast<Function>(GV);\n  \/\/ If it's not a function or is already material, ignore the request.\n  if (!F || !F->isMaterializable())\n    return Error::success();\n\n  DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);\n  assert(DFII != DeferredFunctionInfo.end() && \"Deferred function not found!\");\n  \/\/ If its position is recorded as 0, its body is somewhere in the stream\n  \/\/ but we haven't seen it yet.\n  if (DFII->second == 0)\n    if (Error Err = findFunctionInStream(F, DFII))\n      return Err;\n\n  \/\/ Materialize metadata before parsing any function bodies.\n  if (Error Err = materializeMetadata())\n    return Err;\n\n  \/\/ Move the bit stream to the saved position of the deferred function body.\n  if (Error JumpFailed = Stream.JumpToBit(DFII->second))\n    return JumpFailed;\n  if (Error Err = parseFunctionBody(F))\n    return Err;\n  F->setIsMaterializable(false);\n\n  if (StripDebugInfo)\n    stripDebugInfo(*F);\n\n  \/\/ Upgrade any old intrinsic calls in the function.\n  for (auto &I : UpgradedIntrinsics) {\n    for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))\n      if (CallInst *CI = dyn_cast<CallInst>(U))\n        UpgradeIntrinsicCall(CI, I.second);\n  }\n\n  \/\/ Update calls to the remangled intrinsics\n  for (auto &I : RemangledIntrinsics)\n    for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))\n      \/\/ Don't expect any other users than call sites\n      cast<CallBase>(U)->setCalledFunction(I.second);\n\n  \/\/ Finish fn->subprogram upgrade for materialized functions.\n  if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))\n    F->setSubprogram(SP);\n\n  \/\/ Check if the TBAA Metadata are valid, otherwise we will need to strip them.\n  if (!MDLoader->isStrippingTBAA()) {\n    for (auto &I : instructions(F)) {\n      MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);\n      if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))\n        continue;\n      MDLoader->setStripTBAA(true);\n      stripTBAA(F->getParent());\n    }\n  }\n\n  for (auto &I : instructions(F)) {\n    \/\/ \"Upgrade\" older incorrect branch weights by dropping them.\n    if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {\n      if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {\n        MDString *MDS = cast<MDString>(MD->getOperand(0));\n        StringRef ProfName = MDS->getString();\n        \/\/ Check consistency of !prof branch_weights metadata.\n        if (!ProfName.equals(\"branch_weights\"))\n          continue;\n        unsigned ExpectedNumOperands = 0;\n        if (BranchInst *BI = dyn_cast<BranchInst>(&I))\n          ExpectedNumOperands = BI->getNumSuccessors();\n        else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))\n          ExpectedNumOperands = SI->getNumSuccessors();\n        else if (isa<CallInst>(&I))\n          ExpectedNumOperands = 1;\n        else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))\n          ExpectedNumOperands = IBI->getNumDestinations();\n        else if (isa<SelectInst>(&I))\n          ExpectedNumOperands = 2;\n        else\n          continue; \/\/ ignore and continue.\n\n        \/\/ If branch weight doesn't match, just strip branch weight.\n        if (MD->getNumOperands() != 1 + ExpectedNumOperands)\n          I.setMetadata(LLVMContext::MD_prof, nullptr);\n      }\n    }\n\n    \/\/ Remove incompatible attributes on function calls.\n    if (auto *CI = dyn_cast<CallBase>(&I)) {\n      CI->removeRetAttrs(AttributeFuncs::typeIncompatible(\n          CI->getFunctionType()->getReturnType()));\n\n      for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)\n        CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(\n                                        CI->getArgOperand(ArgNo)->getType()));\n    }\n  }\n\n  \/\/ Look for functions that rely on old function attribute behavior.\n  UpgradeFunctionAttributes(*F);\n\n  \/\/ Bring in any functions that this function forward-referenced via\n  \/\/ blockaddresses.\n  return materializeForwardReferencedFunctions();\n}\n\nError BitcodeReader::materializeModule() {\n  if (Error Err = materializeMetadata())\n    return Err;\n\n  \/\/ Promise to materialize all forward references.\n  WillMaterializeAllForwardRefs = true;\n\n  \/\/ Iterate over the module, deserializing any functions that are still on\n  \/\/ disk.\n  for (Function &F : *TheModule) {\n    if (Error Err = materialize(&F))\n      return Err;\n  }\n  \/\/ At this point, if there are any function bodies, parse the rest of\n  \/\/ the bits in the module past the last function block we have recorded\n  \/\/ through either lazy scanning or the VST.\n  if (LastFunctionBlockBit || NextUnreadBit)\n    if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit\n                                    ? LastFunctionBlockBit\n                                    : NextUnreadBit))\n      return Err;\n\n  \/\/ Check that all block address forward references got resolved (as we\n  \/\/ promised above).\n  if (!BasicBlockFwdRefs.empty())\n    return error(\"Never resolved function from blockaddress\");\n\n  \/\/ Upgrade any intrinsic calls that slipped through (should not happen!) and\n  \/\/ delete the old functions to clean up. We can't do this unless the entire\n  \/\/ module is materialized because there could always be another function body\n  \/\/ with calls to the old function.\n  for (auto &I : UpgradedIntrinsics) {\n    for (auto *U : I.first->users()) {\n      if (CallInst *CI = dyn_cast<CallInst>(U))\n        UpgradeIntrinsicCall(CI, I.second);\n    }\n    if (!I.first->use_empty())\n      I.first->replaceAllUsesWith(I.second);\n    I.first->eraseFromParent();\n  }\n  UpgradedIntrinsics.clear();\n  \/\/ Do the same for remangled intrinsics\n  for (auto &I : RemangledIntrinsics) {\n    I.first->replaceAllUsesWith(I.second);\n    I.first->eraseFromParent();\n  }\n  RemangledIntrinsics.clear();\n\n  UpgradeDebugInfo(*TheModule);\n\n  UpgradeModuleFlags(*TheModule);\n\n  UpgradeARCRuntime(*TheModule);\n\n  return Error::success();\n}\n\nstd::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {\n  return IdentifiedStructTypes;\n}\n\nModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(\n    BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,\n    StringRef ModulePath, unsigned ModuleId)\n    : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),\n      ModulePath(ModulePath), ModuleId(ModuleId) {}\n\nvoid ModuleSummaryIndexBitcodeReader::addThisModule() {\n  TheIndex.addModule(ModulePath, ModuleId);\n}\n\nModuleSummaryIndex::ModuleInfo *\nModuleSummaryIndexBitcodeReader::getThisModule() {\n  return TheIndex.getModule(ModulePath);\n}\n\nstd::pair<ValueInfo, GlobalValue::GUID>\nModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {\n  auto VGI = ValueIdToValueInfoMap[ValueId];\n  assert(VGI.first);\n  return VGI;\n}\n\nvoid ModuleSummaryIndexBitcodeReader::setValueGUID(\n    uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,\n    StringRef SourceFileName) {\n  std::string GlobalId =\n      GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);\n  auto ValueGUID = GlobalValue::getGUID(GlobalId);\n  auto OriginalNameID = ValueGUID;\n  if (GlobalValue::isLocalLinkage(Linkage))\n    OriginalNameID = GlobalValue::getGUID(ValueName);\n  if (PrintSummaryGUIDs)\n    dbgs() << \"GUID \" << ValueGUID << \"(\" << OriginalNameID << \") is \"\n           << ValueName << \"\\n\";\n\n  \/\/ UseStrtab is false for legacy summary formats and value names are\n  \/\/ created on stack. In that case we save the name in a string saver in\n  \/\/ the index so that the value name can be recorded.\n  ValueIdToValueInfoMap[ValueID] = std::make_pair(\n      TheIndex.getOrInsertValueInfo(\n          ValueGUID,\n          UseStrtab ? ValueName : TheIndex.saveString(ValueName)),\n      OriginalNameID);\n}\n\n\/\/ Specialized value symbol table parser used when reading module index\n\/\/ blocks where we don't actually create global values. The parsed information\n\/\/ is saved in the bitcode reader for use when later parsing summaries.\nError ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(\n    uint64_t Offset,\n    DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {\n  \/\/ With a strtab the VST is not required to parse the summary.\n  if (UseStrtab)\n    return Error::success();\n\n  assert(Offset > 0 && \"Expected non-zero VST offset\");\n  Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);\n  if (!MaybeCurrentBit)\n    return MaybeCurrentBit.takeError();\n  uint64_t CurrentBit = MaybeCurrentBit.get();\n\n  if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))\n    return Err;\n\n  SmallVector<uint64_t, 64> Record;\n\n  \/\/ Read all the records for this value table.\n  SmallString<128> ValueName;\n\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      \/\/ Done parsing VST, jump back to wherever we came from.\n      if (Error JumpFailed = Stream.JumpToBit(CurrentBit))\n        return JumpFailed;\n      return Error::success();\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Read a record.\n    Record.clear();\n    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeRecord)\n      return MaybeRecord.takeError();\n    switch (MaybeRecord.get()) {\n    default: \/\/ Default behavior: ignore (e.g. VST_CODE_BBENTRY records).\n      break;\n    case bitc::VST_CODE_ENTRY: { \/\/ VST_CODE_ENTRY: [valueid, namechar x N]\n      if (convertToString(Record, 1, ValueName))\n        return error(\"Invalid record\");\n      unsigned ValueID = Record[0];\n      assert(!SourceFileName.empty());\n      auto VLI = ValueIdToLinkageMap.find(ValueID);\n      assert(VLI != ValueIdToLinkageMap.end() &&\n             \"No linkage found for VST entry?\");\n      auto Linkage = VLI->second;\n      setValueGUID(ValueID, ValueName, Linkage, SourceFileName);\n      ValueName.clear();\n      break;\n    }\n    case bitc::VST_CODE_FNENTRY: {\n      \/\/ VST_CODE_FNENTRY: [valueid, offset, namechar x N]\n      if (convertToString(Record, 2, ValueName))\n        return error(\"Invalid record\");\n      unsigned ValueID = Record[0];\n      assert(!SourceFileName.empty());\n      auto VLI = ValueIdToLinkageMap.find(ValueID);\n      assert(VLI != ValueIdToLinkageMap.end() &&\n             \"No linkage found for VST entry?\");\n      auto Linkage = VLI->second;\n      setValueGUID(ValueID, ValueName, Linkage, SourceFileName);\n      ValueName.clear();\n      break;\n    }\n    case bitc::VST_CODE_COMBINED_ENTRY: {\n      \/\/ VST_CODE_COMBINED_ENTRY: [valueid, refguid]\n      unsigned ValueID = Record[0];\n      GlobalValue::GUID RefGUID = Record[1];\n      \/\/ The \"original name\", which is the second value of the pair will be\n      \/\/ overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.\n      ValueIdToValueInfoMap[ValueID] =\n          std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);\n      break;\n    }\n    }\n  }\n}\n\n\/\/ Parse just the blocks needed for building the index out of the module.\n\/\/ At the end of this routine the module Index is populated with a map\n\/\/ from global value id to GlobalValueSummary objects.\nError ModuleSummaryIndexBitcodeReader::parseModule() {\n  if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))\n    return Err;\n\n  SmallVector<uint64_t, 64> Record;\n  DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;\n  unsigned ValueId = 0;\n\n  \/\/ Read the index for this module.\n  while (true) {\n    Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    llvm::BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return Error::success();\n\n    case BitstreamEntry::SubBlock:\n      switch (Entry.ID) {\n      default: \/\/ Skip unknown content.\n        if (Error Err = Stream.SkipBlock())\n          return Err;\n        break;\n      case bitc::BLOCKINFO_BLOCK_ID:\n        \/\/ Need to parse these to get abbrev ids (e.g. for VST)\n        if (Error Err = readBlockInfo())\n          return Err;\n        break;\n      case bitc::VALUE_SYMTAB_BLOCK_ID:\n        \/\/ Should have been parsed earlier via VSTOffset, unless there\n        \/\/ is no summary section.\n        assert(((SeenValueSymbolTable && VSTOffset > 0) ||\n                !SeenGlobalValSummary) &&\n               \"Expected early VST parse via VSTOffset record\");\n        if (Error Err = Stream.SkipBlock())\n          return Err;\n        break;\n      case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:\n      case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:\n        \/\/ Add the module if it is a per-module index (has a source file name).\n        if (!SourceFileName.empty())\n          addThisModule();\n        assert(!SeenValueSymbolTable &&\n               \"Already read VST when parsing summary block?\");\n        \/\/ We might not have a VST if there were no values in the\n        \/\/ summary. An empty summary block generated when we are\n        \/\/ performing ThinLTO compiles so we don't later invoke\n        \/\/ the regular LTO process on them.\n        if (VSTOffset > 0) {\n          if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))\n            return Err;\n          SeenValueSymbolTable = true;\n        }\n        SeenGlobalValSummary = true;\n        if (Error Err = parseEntireSummary(Entry.ID))\n          return Err;\n        break;\n      case bitc::MODULE_STRTAB_BLOCK_ID:\n        if (Error Err = parseModuleStringTable())\n          return Err;\n        break;\n      }\n      continue;\n\n    case BitstreamEntry::Record: {\n        Record.clear();\n        Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);\n        if (!MaybeBitCode)\n          return MaybeBitCode.takeError();\n        switch (MaybeBitCode.get()) {\n        default:\n          break; \/\/ Default behavior, ignore unknown content.\n        case bitc::MODULE_CODE_VERSION: {\n          if (Error Err = parseVersionRecord(Record).takeError())\n            return Err;\n          break;\n        }\n        \/\/\/ MODULE_CODE_SOURCE_FILENAME: [namechar x N]\n        case bitc::MODULE_CODE_SOURCE_FILENAME: {\n          SmallString<128> ValueName;\n          if (convertToString(Record, 0, ValueName))\n            return error(\"Invalid record\");\n          SourceFileName = ValueName.c_str();\n          break;\n        }\n        \/\/\/ MODULE_CODE_HASH: [5*i32]\n        case bitc::MODULE_CODE_HASH: {\n          if (Record.size() != 5)\n            return error(\"Invalid hash length \" + Twine(Record.size()).str());\n          auto &Hash = getThisModule()->second.second;\n          int Pos = 0;\n          for (auto &Val : Record) {\n            assert(!(Val >> 32) && \"Unexpected high bits set\");\n            Hash[Pos++] = Val;\n          }\n          break;\n        }\n        \/\/\/ MODULE_CODE_VSTOFFSET: [offset]\n        case bitc::MODULE_CODE_VSTOFFSET:\n          if (Record.empty())\n            return error(\"Invalid record\");\n          \/\/ Note that we subtract 1 here because the offset is relative to one\n          \/\/ word before the start of the identification or module block, which\n          \/\/ was historically always the start of the regular bitcode header.\n          VSTOffset = Record[0] - 1;\n          break;\n        \/\/ v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]\n        \/\/ v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]\n        \/\/ v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]\n        \/\/ v2: [strtab offset, strtab size, v1]\n        case bitc::MODULE_CODE_GLOBALVAR:\n        case bitc::MODULE_CODE_FUNCTION:\n        case bitc::MODULE_CODE_ALIAS: {\n          StringRef Name;\n          ArrayRef<uint64_t> GVRecord;\n          std::tie(Name, GVRecord) = readNameFromStrtab(Record);\n          if (GVRecord.size() <= 3)\n            return error(\"Invalid record\");\n          uint64_t RawLinkage = GVRecord[3];\n          GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);\n          if (!UseStrtab) {\n            ValueIdToLinkageMap[ValueId++] = Linkage;\n            break;\n          }\n\n          setValueGUID(ValueId++, Name, Linkage, SourceFileName);\n          break;\n        }\n        }\n      }\n      continue;\n    }\n  }\n}\n\nstd::vector<ValueInfo>\nModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {\n  std::vector<ValueInfo> Ret;\n  Ret.reserve(Record.size());\n  for (uint64_t RefValueId : Record)\n    Ret.push_back(getValueInfoFromValueId(RefValueId).first);\n  return Ret;\n}\n\nstd::vector<FunctionSummary::EdgeTy>\nModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,\n                                              bool IsOldProfileFormat,\n                                              bool HasProfile, bool HasRelBF) {\n  std::vector<FunctionSummary::EdgeTy> Ret;\n  Ret.reserve(Record.size());\n  for (unsigned I = 0, E = Record.size(); I != E; ++I) {\n    CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;\n    uint64_t RelBF = 0;\n    ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;\n    if (IsOldProfileFormat) {\n      I += 1; \/\/ Skip old callsitecount field\n      if (HasProfile)\n        I += 1; \/\/ Skip old profilecount field\n    } else if (HasProfile)\n      Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);\n    else if (HasRelBF)\n      RelBF = Record[++I];\n    Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});\n  }\n  return Ret;\n}\n\nstatic void\nparseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,\n                                       WholeProgramDevirtResolution &Wpd) {\n  uint64_t ArgNum = Record[Slot++];\n  WholeProgramDevirtResolution::ByArg &B =\n      Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];\n  Slot += ArgNum;\n\n  B.TheKind =\n      static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);\n  B.Info = Record[Slot++];\n  B.Byte = Record[Slot++];\n  B.Bit = Record[Slot++];\n}\n\nstatic void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,\n                                              StringRef Strtab, size_t &Slot,\n                                              TypeIdSummary &TypeId) {\n  uint64_t Id = Record[Slot++];\n  WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];\n\n  Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);\n  Wpd.SingleImplName = {Strtab.data() + Record[Slot],\n                        static_cast<size_t>(Record[Slot + 1])};\n  Slot += 2;\n\n  uint64_t ResByArgNum = Record[Slot++];\n  for (uint64_t I = 0; I != ResByArgNum; ++I)\n    parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);\n}\n\nstatic void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,\n                                     StringRef Strtab,\n                                     ModuleSummaryIndex &TheIndex) {\n  size_t Slot = 0;\n  TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(\n      {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});\n  Slot += 2;\n\n  TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);\n  TypeId.TTRes.SizeM1BitWidth = Record[Slot++];\n  TypeId.TTRes.AlignLog2 = Record[Slot++];\n  TypeId.TTRes.SizeM1 = Record[Slot++];\n  TypeId.TTRes.BitMask = Record[Slot++];\n  TypeId.TTRes.InlineBits = Record[Slot++];\n\n  while (Slot < Record.size())\n    parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);\n}\n\nstd::vector<FunctionSummary::ParamAccess>\nModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {\n  auto ReadRange = [&]() {\n    APInt Lower(FunctionSummary::ParamAccess::RangeWidth,\n                BitcodeReader::decodeSignRotatedValue(Record.front()));\n    Record = Record.drop_front();\n    APInt Upper(FunctionSummary::ParamAccess::RangeWidth,\n                BitcodeReader::decodeSignRotatedValue(Record.front()));\n    Record = Record.drop_front();\n    ConstantRange Range{Lower, Upper};\n    assert(!Range.isFullSet());\n    assert(!Range.isUpperSignWrapped());\n    return Range;\n  };\n\n  std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;\n  while (!Record.empty()) {\n    PendingParamAccesses.emplace_back();\n    FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();\n    ParamAccess.ParamNo = Record.front();\n    Record = Record.drop_front();\n    ParamAccess.Use = ReadRange();\n    ParamAccess.Calls.resize(Record.front());\n    Record = Record.drop_front();\n    for (auto &Call : ParamAccess.Calls) {\n      Call.ParamNo = Record.front();\n      Record = Record.drop_front();\n      Call.Callee = getValueInfoFromValueId(Record.front()).first;\n      Record = Record.drop_front();\n      Call.Offsets = ReadRange();\n    }\n  }\n  return PendingParamAccesses;\n}\n\nvoid ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(\n    ArrayRef<uint64_t> Record, size_t &Slot,\n    TypeIdCompatibleVtableInfo &TypeId) {\n  uint64_t Offset = Record[Slot++];\n  ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first;\n  TypeId.push_back({Offset, Callee});\n}\n\nvoid ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(\n    ArrayRef<uint64_t> Record) {\n  size_t Slot = 0;\n  TypeIdCompatibleVtableInfo &TypeId =\n      TheIndex.getOrInsertTypeIdCompatibleVtableSummary(\n          {Strtab.data() + Record[Slot],\n           static_cast<size_t>(Record[Slot + 1])});\n  Slot += 2;\n\n  while (Slot < Record.size())\n    parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);\n}\n\nstatic void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,\n                           unsigned WOCnt) {\n  \/\/ Readonly and writeonly refs are in the end of the refs list.\n  assert(ROCnt + WOCnt <= Refs.size());\n  unsigned FirstWORef = Refs.size() - WOCnt;\n  unsigned RefNo = FirstWORef - ROCnt;\n  for (; RefNo < FirstWORef; ++RefNo)\n    Refs[RefNo].setReadOnly();\n  for (; RefNo < Refs.size(); ++RefNo)\n    Refs[RefNo].setWriteOnly();\n}\n\n\/\/ Eagerly parse the entire summary block. This populates the GlobalValueSummary\n\/\/ objects in the index.\nError ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {\n  if (Error Err = Stream.EnterSubBlock(ID))\n    return Err;\n  SmallVector<uint64_t, 64> Record;\n\n  \/\/ Parse version\n  {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    if (Entry.Kind != BitstreamEntry::Record)\n      return error(\"Invalid Summary Block: record for version expected\");\n    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeRecord)\n      return MaybeRecord.takeError();\n    if (MaybeRecord.get() != bitc::FS_VERSION)\n      return error(\"Invalid Summary Block: version expected\");\n  }\n  const uint64_t Version = Record[0];\n  const bool IsOldProfileFormat = Version == 1;\n  if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)\n    return error(\"Invalid summary version \" + Twine(Version) +\n                 \". Version should be in the range [1-\" +\n                 Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +\n                 \"].\");\n  Record.clear();\n\n  \/\/ Keep around the last seen summary to be used when we see an optional\n  \/\/ \"OriginalName\" attachement.\n  GlobalValueSummary *LastSeenSummary = nullptr;\n  GlobalValue::GUID LastSeenGUID = 0;\n\n  \/\/ We can expect to see any number of type ID information records before\n  \/\/ each function summary records; these variables store the information\n  \/\/ collected so far so that it can be used to create the summary object.\n  std::vector<GlobalValue::GUID> PendingTypeTests;\n  std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,\n      PendingTypeCheckedLoadVCalls;\n  std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,\n      PendingTypeCheckedLoadConstVCalls;\n  std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;\n\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return Error::success();\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Read a record. The record format depends on whether this\n    \/\/ is a per-module index or a combined index file. In the per-module\n    \/\/ case the records contain the associated value's ID for correlation\n    \/\/ with VST entries. In the combined index the correlation is done\n    \/\/ via the bitcode offset of the summary records (which were saved\n    \/\/ in the combined index VST entries). The records also contain\n    \/\/ information used for ThinLTO renaming and importing.\n    Record.clear();\n    Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeBitCode)\n      return MaybeBitCode.takeError();\n    switch (unsigned BitCode = MaybeBitCode.get()) {\n    default: \/\/ Default behavior: ignore.\n      break;\n    case bitc::FS_FLAGS: {  \/\/ [flags]\n      TheIndex.setFlags(Record[0]);\n      break;\n    }\n    case bitc::FS_VALUE_GUID: { \/\/ [valueid, refguid]\n      uint64_t ValueID = Record[0];\n      GlobalValue::GUID RefGUID = Record[1];\n      ValueIdToValueInfoMap[ValueID] =\n          std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);\n      break;\n    }\n    \/\/ FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,\n    \/\/                numrefs x valueid, n x (valueid)]\n    \/\/ FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,\n    \/\/                        numrefs x valueid,\n    \/\/                        n x (valueid, hotness)]\n    \/\/ FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,\n    \/\/                      numrefs x valueid,\n    \/\/                      n x (valueid, relblockfreq)]\n    case bitc::FS_PERMODULE:\n    case bitc::FS_PERMODULE_RELBF:\n    case bitc::FS_PERMODULE_PROFILE: {\n      unsigned ValueID = Record[0];\n      uint64_t RawFlags = Record[1];\n      unsigned InstCount = Record[2];\n      uint64_t RawFunFlags = 0;\n      unsigned NumRefs = Record[3];\n      unsigned NumRORefs = 0, NumWORefs = 0;\n      int RefListStartIndex = 4;\n      if (Version >= 4) {\n        RawFunFlags = Record[3];\n        NumRefs = Record[4];\n        RefListStartIndex = 5;\n        if (Version >= 5) {\n          NumRORefs = Record[5];\n          RefListStartIndex = 6;\n          if (Version >= 7) {\n            NumWORefs = Record[6];\n            RefListStartIndex = 7;\n          }\n        }\n      }\n\n      auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);\n      \/\/ The module path string ref set in the summary must be owned by the\n      \/\/ index's module string table. Since we don't have a module path\n      \/\/ string table section in the per-module index, we create a single\n      \/\/ module path string table entry with an empty (0) ID to take\n      \/\/ ownership.\n      int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;\n      assert(Record.size() >= RefListStartIndex + NumRefs &&\n             \"Record size inconsistent with number of references\");\n      std::vector<ValueInfo> Refs = makeRefList(\n          ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));\n      bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);\n      bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);\n      std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(\n          ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),\n          IsOldProfileFormat, HasProfile, HasRelBF);\n      setSpecialRefs(Refs, NumRORefs, NumWORefs);\n      auto FS = std::make_unique<FunctionSummary>(\n          Flags, InstCount, getDecodedFFlags(RawFunFlags), \/*EntryCount=*\/0,\n          std::move(Refs), std::move(Calls), std::move(PendingTypeTests),\n          std::move(PendingTypeTestAssumeVCalls),\n          std::move(PendingTypeCheckedLoadVCalls),\n          std::move(PendingTypeTestAssumeConstVCalls),\n          std::move(PendingTypeCheckedLoadConstVCalls),\n          std::move(PendingParamAccesses));\n      auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);\n      FS->setModulePath(getThisModule()->first());\n      FS->setOriginalName(VIAndOriginalGUID.second);\n      TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));\n      break;\n    }\n    \/\/ FS_ALIAS: [valueid, flags, valueid]\n    \/\/ Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as\n    \/\/ they expect all aliasee summaries to be available.\n    case bitc::FS_ALIAS: {\n      unsigned ValueID = Record[0];\n      uint64_t RawFlags = Record[1];\n      unsigned AliaseeID = Record[2];\n      auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);\n      auto AS = std::make_unique<AliasSummary>(Flags);\n      \/\/ The module path string ref set in the summary must be owned by the\n      \/\/ index's module string table. Since we don't have a module path\n      \/\/ string table section in the per-module index, we create a single\n      \/\/ module path string table entry with an empty (0) ID to take\n      \/\/ ownership.\n      AS->setModulePath(getThisModule()->first());\n\n      auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first;\n      auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);\n      if (!AliaseeInModule)\n        return error(\"Alias expects aliasee summary to be parsed\");\n      AS->setAliasee(AliaseeVI, AliaseeInModule);\n\n      auto GUID = getValueInfoFromValueId(ValueID);\n      AS->setOriginalName(GUID.second);\n      TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));\n      break;\n    }\n    \/\/ FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]\n    case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {\n      unsigned ValueID = Record[0];\n      uint64_t RawFlags = Record[1];\n      unsigned RefArrayStart = 2;\n      GlobalVarSummary::GVarFlags GVF(\/* ReadOnly *\/ false,\n                                      \/* WriteOnly *\/ false,\n                                      \/* Constant *\/ false,\n                                      GlobalObject::VCallVisibilityPublic);\n      auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);\n      if (Version >= 5) {\n        GVF = getDecodedGVarFlags(Record[2]);\n        RefArrayStart = 3;\n      }\n      std::vector<ValueInfo> Refs =\n          makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));\n      auto FS =\n          std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));\n      FS->setModulePath(getThisModule()->first());\n      auto GUID = getValueInfoFromValueId(ValueID);\n      FS->setOriginalName(GUID.second);\n      TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));\n      break;\n    }\n    \/\/ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,\n    \/\/                        numrefs, numrefs x valueid,\n    \/\/                        n x (valueid, offset)]\n    case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {\n      unsigned ValueID = Record[0];\n      uint64_t RawFlags = Record[1];\n      GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);\n      unsigned NumRefs = Record[3];\n      unsigned RefListStartIndex = 4;\n      unsigned VTableListStartIndex = RefListStartIndex + NumRefs;\n      auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);\n      std::vector<ValueInfo> Refs = makeRefList(\n          ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));\n      VTableFuncList VTableFuncs;\n      for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {\n        ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;\n        uint64_t Offset = Record[++I];\n        VTableFuncs.push_back({Callee, Offset});\n      }\n      auto VS =\n          std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));\n      VS->setModulePath(getThisModule()->first());\n      VS->setVTableFuncs(VTableFuncs);\n      auto GUID = getValueInfoFromValueId(ValueID);\n      VS->setOriginalName(GUID.second);\n      TheIndex.addGlobalValueSummary(GUID.first, std::move(VS));\n      break;\n    }\n    \/\/ FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,\n    \/\/               numrefs x valueid, n x (valueid)]\n    \/\/ FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,\n    \/\/                       numrefs x valueid, n x (valueid, hotness)]\n    case bitc::FS_COMBINED:\n    case bitc::FS_COMBINED_PROFILE: {\n      unsigned ValueID = Record[0];\n      uint64_t ModuleId = Record[1];\n      uint64_t RawFlags = Record[2];\n      unsigned InstCount = Record[3];\n      uint64_t RawFunFlags = 0;\n      uint64_t EntryCount = 0;\n      unsigned NumRefs = Record[4];\n      unsigned NumRORefs = 0, NumWORefs = 0;\n      int RefListStartIndex = 5;\n\n      if (Version >= 4) {\n        RawFunFlags = Record[4];\n        RefListStartIndex = 6;\n        size_t NumRefsIndex = 5;\n        if (Version >= 5) {\n          unsigned NumRORefsOffset = 1;\n          RefListStartIndex = 7;\n          if (Version >= 6) {\n            NumRefsIndex = 6;\n            EntryCount = Record[5];\n            RefListStartIndex = 8;\n            if (Version >= 7) {\n              RefListStartIndex = 9;\n              NumWORefs = Record[8];\n              NumRORefsOffset = 2;\n            }\n          }\n          NumRORefs = Record[RefListStartIndex - NumRORefsOffset];\n        }\n        NumRefs = Record[NumRefsIndex];\n      }\n\n      auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);\n      int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;\n      assert(Record.size() >= RefListStartIndex + NumRefs &&\n             \"Record size inconsistent with number of references\");\n      std::vector<ValueInfo> Refs = makeRefList(\n          ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));\n      bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);\n      std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(\n          ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),\n          IsOldProfileFormat, HasProfile, false);\n      ValueInfo VI = getValueInfoFromValueId(ValueID).first;\n      setSpecialRefs(Refs, NumRORefs, NumWORefs);\n      auto FS = std::make_unique<FunctionSummary>(\n          Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,\n          std::move(Refs), std::move(Edges), std::move(PendingTypeTests),\n          std::move(PendingTypeTestAssumeVCalls),\n          std::move(PendingTypeCheckedLoadVCalls),\n          std::move(PendingTypeTestAssumeConstVCalls),\n          std::move(PendingTypeCheckedLoadConstVCalls),\n          std::move(PendingParamAccesses));\n      LastSeenSummary = FS.get();\n      LastSeenGUID = VI.getGUID();\n      FS->setModulePath(ModuleIdMap[ModuleId]);\n      TheIndex.addGlobalValueSummary(VI, std::move(FS));\n      break;\n    }\n    \/\/ FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]\n    \/\/ Aliases must be emitted (and parsed) after all FS_COMBINED entries, as\n    \/\/ they expect all aliasee summaries to be available.\n    case bitc::FS_COMBINED_ALIAS: {\n      unsigned ValueID = Record[0];\n      uint64_t ModuleId = Record[1];\n      uint64_t RawFlags = Record[2];\n      unsigned AliaseeValueId = Record[3];\n      auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);\n      auto AS = std::make_unique<AliasSummary>(Flags);\n      LastSeenSummary = AS.get();\n      AS->setModulePath(ModuleIdMap[ModuleId]);\n\n      auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first;\n      auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());\n      AS->setAliasee(AliaseeVI, AliaseeInModule);\n\n      ValueInfo VI = getValueInfoFromValueId(ValueID).first;\n      LastSeenGUID = VI.getGUID();\n      TheIndex.addGlobalValueSummary(VI, std::move(AS));\n      break;\n    }\n    \/\/ FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]\n    case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {\n      unsigned ValueID = Record[0];\n      uint64_t ModuleId = Record[1];\n      uint64_t RawFlags = Record[2];\n      unsigned RefArrayStart = 3;\n      GlobalVarSummary::GVarFlags GVF(\/* ReadOnly *\/ false,\n                                      \/* WriteOnly *\/ false,\n                                      \/* Constant *\/ false,\n                                      GlobalObject::VCallVisibilityPublic);\n      auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);\n      if (Version >= 5) {\n        GVF = getDecodedGVarFlags(Record[3]);\n        RefArrayStart = 4;\n      }\n      std::vector<ValueInfo> Refs =\n          makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));\n      auto FS =\n          std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));\n      LastSeenSummary = FS.get();\n      FS->setModulePath(ModuleIdMap[ModuleId]);\n      ValueInfo VI = getValueInfoFromValueId(ValueID).first;\n      LastSeenGUID = VI.getGUID();\n      TheIndex.addGlobalValueSummary(VI, std::move(FS));\n      break;\n    }\n    \/\/ FS_COMBINED_ORIGINAL_NAME: [original_name]\n    case bitc::FS_COMBINED_ORIGINAL_NAME: {\n      uint64_t OriginalName = Record[0];\n      if (!LastSeenSummary)\n        return error(\"Name attachment that does not follow a combined record\");\n      LastSeenSummary->setOriginalName(OriginalName);\n      TheIndex.addOriginalName(LastSeenGUID, OriginalName);\n      \/\/ Reset the LastSeenSummary\n      LastSeenSummary = nullptr;\n      LastSeenGUID = 0;\n      break;\n    }\n    case bitc::FS_TYPE_TESTS:\n      assert(PendingTypeTests.empty());\n      llvm::append_range(PendingTypeTests, Record);\n      break;\n\n    case bitc::FS_TYPE_TEST_ASSUME_VCALLS:\n      assert(PendingTypeTestAssumeVCalls.empty());\n      for (unsigned I = 0; I != Record.size(); I += 2)\n        PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});\n      break;\n\n    case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:\n      assert(PendingTypeCheckedLoadVCalls.empty());\n      for (unsigned I = 0; I != Record.size(); I += 2)\n        PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});\n      break;\n\n    case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:\n      PendingTypeTestAssumeConstVCalls.push_back(\n          {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});\n      break;\n\n    case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:\n      PendingTypeCheckedLoadConstVCalls.push_back(\n          {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});\n      break;\n\n    case bitc::FS_CFI_FUNCTION_DEFS: {\n      std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();\n      for (unsigned I = 0; I != Record.size(); I += 2)\n        CfiFunctionDefs.insert(\n            {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});\n      break;\n    }\n\n    case bitc::FS_CFI_FUNCTION_DECLS: {\n      std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();\n      for (unsigned I = 0; I != Record.size(); I += 2)\n        CfiFunctionDecls.insert(\n            {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});\n      break;\n    }\n\n    case bitc::FS_TYPE_ID:\n      parseTypeIdSummaryRecord(Record, Strtab, TheIndex);\n      break;\n\n    case bitc::FS_TYPE_ID_METADATA:\n      parseTypeIdCompatibleVtableSummaryRecord(Record);\n      break;\n\n    case bitc::FS_BLOCK_COUNT:\n      TheIndex.addBlockCount(Record[0]);\n      break;\n\n    case bitc::FS_PARAM_ACCESS: {\n      PendingParamAccesses = parseParamAccesses(Record);\n      break;\n    }\n    }\n  }\n  llvm_unreachable(\"Exit infinite loop\");\n}\n\n\/\/ Parse the  module string table block into the Index.\n\/\/ This populates the ModulePathStringTable map in the index.\nError ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {\n  if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))\n    return Err;\n\n  SmallVector<uint64_t, 64> Record;\n\n  SmallString<128> ModulePath;\n  ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;\n\n  while (true) {\n    Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return Error::success();\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    Record.clear();\n    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeRecord)\n      return MaybeRecord.takeError();\n    switch (MaybeRecord.get()) {\n    default: \/\/ Default behavior: ignore.\n      break;\n    case bitc::MST_CODE_ENTRY: {\n      \/\/ MST_ENTRY: [modid, namechar x N]\n      uint64_t ModuleId = Record[0];\n\n      if (convertToString(Record, 1, ModulePath))\n        return error(\"Invalid record\");\n\n      LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);\n      ModuleIdMap[ModuleId] = LastSeenModule->first();\n\n      ModulePath.clear();\n      break;\n    }\n    \/\/\/ MST_CODE_HASH: [5*i32]\n    case bitc::MST_CODE_HASH: {\n      if (Record.size() != 5)\n        return error(\"Invalid hash length \" + Twine(Record.size()).str());\n      if (!LastSeenModule)\n        return error(\"Invalid hash that does not follow a module path\");\n      int Pos = 0;\n      for (auto &Val : Record) {\n        assert(!(Val >> 32) && \"Unexpected high bits set\");\n        LastSeenModule->second.second[Pos++] = Val;\n      }\n      \/\/ Reset LastSeenModule to avoid overriding the hash unexpectedly.\n      LastSeenModule = nullptr;\n      break;\n    }\n    }\n  }\n  llvm_unreachable(\"Exit infinite loop\");\n}\n\nnamespace {\n\n\/\/ FIXME: This class is only here to support the transition to llvm::Error. It\n\/\/ will be removed once this transition is complete. Clients should prefer to\n\/\/ deal with the Error value directly, rather than converting to error_code.\nclass BitcodeErrorCategoryType : public std::error_category {\n  const char *name() const noexcept override {\n    return \"llvm.bitcode\";\n  }\n\n  std::string message(int IE) const override {\n    BitcodeError E = static_cast<BitcodeError>(IE);\n    switch (E) {\n    case BitcodeError::CorruptedBitcode:\n      return \"Corrupted bitcode\";\n    }\n    llvm_unreachable(\"Unknown error type!\");\n  }\n};\n\n} \/\/ end anonymous namespace\n\nstatic ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;\n\nconst std::error_category &llvm::BitcodeErrorCategory() {\n  return *ErrorCategory;\n}\n\nstatic Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,\n                                            unsigned Block, unsigned RecordID) {\n  if (Error Err = Stream.EnterSubBlock(Block))\n    return std::move(Err);\n\n  StringRef Strtab;\n  while (true) {\n    Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    llvm::BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::EndBlock:\n      return Strtab;\n\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n\n    case BitstreamEntry::SubBlock:\n      if (Error Err = Stream.SkipBlock())\n        return std::move(Err);\n      break;\n\n    case BitstreamEntry::Record:\n      StringRef Blob;\n      SmallVector<uint64_t, 1> Record;\n      Expected<unsigned> MaybeRecord =\n          Stream.readRecord(Entry.ID, Record, &Blob);\n      if (!MaybeRecord)\n        return MaybeRecord.takeError();\n      if (MaybeRecord.get() == RecordID)\n        Strtab = Blob;\n      break;\n    }\n  }\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ External interface\n\/\/===----------------------------------------------------------------------===\/\/\n\nExpected<std::vector<BitcodeModule>>\nllvm::getBitcodeModuleList(MemoryBufferRef Buffer) {\n  auto FOrErr = getBitcodeFileContents(Buffer);\n  if (!FOrErr)\n    return FOrErr.takeError();\n  return std::move(FOrErr->Mods);\n}\n\nExpected<BitcodeFileContents>\nllvm::getBitcodeFileContents(MemoryBufferRef Buffer) {\n  Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);\n  if (!StreamOrErr)\n    return StreamOrErr.takeError();\n  BitstreamCursor &Stream = *StreamOrErr;\n\n  BitcodeFileContents F;\n  while (true) {\n    uint64_t BCBegin = Stream.getCurrentByteNo();\n\n    \/\/ We may be consuming bitcode from a client that leaves garbage at the end\n    \/\/ of the bitcode stream (e.g. Apple's ar tool). If we are close enough to\n    \/\/ the end that there cannot possibly be another module, stop looking.\n    if (BCBegin + 8 >= Stream.getBitcodeBytes().size())\n      return F;\n\n    Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();\n    if (!MaybeEntry)\n      return MaybeEntry.takeError();\n    llvm::BitstreamEntry Entry = MaybeEntry.get();\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::EndBlock:\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n\n    case BitstreamEntry::SubBlock: {\n      uint64_t IdentificationBit = -1ull;\n      if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {\n        IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;\n        if (Error Err = Stream.SkipBlock())\n          return std::move(Err);\n\n        {\n          Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();\n          if (!MaybeEntry)\n            return MaybeEntry.takeError();\n          Entry = MaybeEntry.get();\n        }\n\n        if (Entry.Kind != BitstreamEntry::SubBlock ||\n            Entry.ID != bitc::MODULE_BLOCK_ID)\n          return error(\"Malformed block\");\n      }\n\n      if (Entry.ID == bitc::MODULE_BLOCK_ID) {\n        uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;\n        if (Error Err = Stream.SkipBlock())\n          return std::move(Err);\n\n        F.Mods.push_back({Stream.getBitcodeBytes().slice(\n                              BCBegin, Stream.getCurrentByteNo() - BCBegin),\n                          Buffer.getBufferIdentifier(), IdentificationBit,\n                          ModuleBit});\n        continue;\n      }\n\n      if (Entry.ID == bitc::STRTAB_BLOCK_ID) {\n        Expected<StringRef> Strtab =\n            readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);\n        if (!Strtab)\n          return Strtab.takeError();\n        \/\/ This string table is used by every preceding bitcode module that does\n        \/\/ not have its own string table. A bitcode file may have multiple\n        \/\/ string tables if it was created by binary concatenation, for example\n        \/\/ with \"llvm-cat -b\".\n        for (BitcodeModule &I : llvm::reverse(F.Mods)) {\n          if (!I.Strtab.empty())\n            break;\n          I.Strtab = *Strtab;\n        }\n        \/\/ Similarly, the string table is used by every preceding symbol table;\n        \/\/ normally there will be just one unless the bitcode file was created\n        \/\/ by binary concatenation.\n        if (!F.Symtab.empty() && F.StrtabForSymtab.empty())\n          F.StrtabForSymtab = *Strtab;\n        continue;\n      }\n\n      if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {\n        Expected<StringRef> SymtabOrErr =\n            readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);\n        if (!SymtabOrErr)\n          return SymtabOrErr.takeError();\n\n        \/\/ We can expect the bitcode file to have multiple symbol tables if it\n        \/\/ was created by binary concatenation. In that case we silently\n        \/\/ ignore any subsequent symbol tables, which is fine because this is a\n        \/\/ low level function. The client is expected to notice that the number\n        \/\/ of modules in the symbol table does not match the number of modules\n        \/\/ in the input file and regenerate the symbol table.\n        if (F.Symtab.empty())\n          F.Symtab = *SymtabOrErr;\n        continue;\n      }\n\n      if (Error Err = Stream.SkipBlock())\n        return std::move(Err);\n      continue;\n    }\n    case BitstreamEntry::Record:\n      if (Error E = Stream.skipRecord(Entry.ID).takeError())\n        return std::move(E);\n      continue;\n    }\n  }\n}\n\n\/\/\/ Get a lazy one-at-time loading module from bitcode.\n\/\/\/\n\/\/\/ This isn't always used in a lazy context.  In particular, it's also used by\n\/\/\/ \\a parseModule().  If this is truly lazy, then we need to eagerly pull\n\/\/\/ in forward-referenced functions from block address references.\n\/\/\/\n\/\/\/ \\param[in] MaterializeAll Set to \\c true if we should materialize\n\/\/\/ everything.\nExpected<std::unique_ptr<Module>>\nBitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,\n                             bool ShouldLazyLoadMetadata, bool IsImporting,\n                             DataLayoutCallbackTy DataLayoutCallback) {\n  BitstreamCursor Stream(Buffer);\n\n  std::string ProducerIdentification;\n  if (IdentificationBit != -1ull) {\n    if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))\n      return std::move(JumpFailed);\n    if (Error E =\n            readIdentificationBlock(Stream).moveInto(ProducerIdentification))\n      return std::move(E);\n  }\n\n  if (Error JumpFailed = Stream.JumpToBit(ModuleBit))\n    return std::move(JumpFailed);\n  auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,\n                              Context);\n\n  std::unique_ptr<Module> M =\n      std::make_unique<Module>(ModuleIdentifier, Context);\n  M->setMaterializer(R);\n\n  \/\/ Delay parsing Metadata if ShouldLazyLoadMetadata is true.\n  if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,\n                                      IsImporting, DataLayoutCallback))\n    return std::move(Err);\n\n  if (MaterializeAll) {\n    \/\/ Read in the entire module, and destroy the BitcodeReader.\n    if (Error Err = M->materializeAll())\n      return std::move(Err);\n  } else {\n    \/\/ Resolve forward references from blockaddresses.\n    if (Error Err = R->materializeForwardReferencedFunctions())\n      return std::move(Err);\n  }\n  return std::move(M);\n}\n\nExpected<std::unique_ptr<Module>>\nBitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,\n                             bool IsImporting) {\n  return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,\n                       [](StringRef) { return None; });\n}\n\n\/\/ Parse the specified bitcode buffer and merge the index into CombinedIndex.\n\/\/ We don't use ModuleIdentifier here because the client may need to control the\n\/\/ module path used in the combined summary (e.g. when reading summaries for\n\/\/ regular LTO modules).\nError BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,\n                                 StringRef ModulePath, uint64_t ModuleId) {\n  BitstreamCursor Stream(Buffer);\n  if (Error JumpFailed = Stream.JumpToBit(ModuleBit))\n    return JumpFailed;\n\n  ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,\n                                    ModulePath, ModuleId);\n  return R.parseModule();\n}\n\n\/\/ Parse the specified bitcode buffer, returning the function info index.\nExpected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {\n  BitstreamCursor Stream(Buffer);\n  if (Error JumpFailed = Stream.JumpToBit(ModuleBit))\n    return std::move(JumpFailed);\n\n  auto Index = std::make_unique<ModuleSummaryIndex>(\/*HaveGVs=*\/false);\n  ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,\n                                    ModuleIdentifier, 0);\n\n  if (Error Err = R.parseModule())\n    return std::move(Err);\n\n  return std::move(Index);\n}\n\nstatic Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,\n                                                unsigned ID) {\n  if (Error Err = Stream.EnterSubBlock(ID))\n    return std::move(Err);\n  SmallVector<uint64_t, 64> Record;\n\n  while (true) {\n    BitstreamEntry Entry;\n    if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))\n      return std::move(E);\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::SubBlock: \/\/ Handled for us already.\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      \/\/ If no flags record found, conservatively return true to mimic\n      \/\/ behavior before this flag was added.\n      return true;\n    case BitstreamEntry::Record:\n      \/\/ The interesting case.\n      break;\n    }\n\n    \/\/ Look for the FS_FLAGS record.\n    Record.clear();\n    Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);\n    if (!MaybeBitCode)\n      return MaybeBitCode.takeError();\n    switch (MaybeBitCode.get()) {\n    default: \/\/ Default behavior: ignore.\n      break;\n    case bitc::FS_FLAGS: { \/\/ [flags]\n      uint64_t Flags = Record[0];\n      \/\/ Scan flags.\n      assert(Flags <= 0x7f && \"Unexpected bits in flag\");\n\n      return Flags & 0x8;\n    }\n    }\n  }\n  llvm_unreachable(\"Exit infinite loop\");\n}\n\n\/\/ Check if the given bitcode buffer contains a global value summary block.\nExpected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {\n  BitstreamCursor Stream(Buffer);\n  if (Error JumpFailed = Stream.JumpToBit(ModuleBit))\n    return std::move(JumpFailed);\n\n  if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))\n    return std::move(Err);\n\n  while (true) {\n    llvm::BitstreamEntry Entry;\n    if (Error E = Stream.advance().moveInto(Entry))\n      return std::move(E);\n\n    switch (Entry.Kind) {\n    case BitstreamEntry::Error:\n      return error(\"Malformed block\");\n    case BitstreamEntry::EndBlock:\n      return BitcodeLTOInfo{\/*IsThinLTO=*\/false, \/*HasSummary=*\/false,\n                            \/*EnableSplitLTOUnit=*\/false};\n\n    case BitstreamEntry::SubBlock:\n      if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {\n        Expected<bool> EnableSplitLTOUnit =\n            getEnableSplitLTOUnitFlag(Stream, Entry.ID);\n        if (!EnableSplitLTOUnit)\n          return EnableSplitLTOUnit.takeError();\n        return BitcodeLTOInfo{\/*IsThinLTO=*\/true, \/*HasSummary=*\/true,\n                              *EnableSplitLTOUnit};\n      }\n\n      if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {\n        Expected<bool> EnableSplitLTOUnit =\n            getEnableSplitLTOUnitFlag(Stream, Entry.ID);\n        if (!EnableSplitLTOUnit)\n          return EnableSplitLTOUnit.takeError();\n        return BitcodeLTOInfo{\/*IsThinLTO=*\/false, \/*HasSummary=*\/true,\n                              *EnableSplitLTOUnit};\n      }\n\n      \/\/ Ignore other sub-blocks.\n      if (Error Err = Stream.SkipBlock())\n        return std::move(Err);\n      continue;\n\n    case BitstreamEntry::Record:\n      if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))\n        continue;\n      else\n        return StreamFailed.takeError();\n    }\n  }\n}\n\nstatic Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {\n  Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);\n  if (!MsOrErr)\n    return MsOrErr.takeError();\n\n  if (MsOrErr->size() != 1)\n    return error(\"Expected a single module\");\n\n  return (*MsOrErr)[0];\n}\n\nExpected<std::unique_ptr<Module>>\nllvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,\n                           bool ShouldLazyLoadMetadata, bool IsImporting) {\n  Expected<BitcodeModule> BM = getSingleModule(Buffer);\n  if (!BM)\n    return BM.takeError();\n\n  return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);\n}\n\nExpected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(\n    std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,\n    bool ShouldLazyLoadMetadata, bool IsImporting) {\n  auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,\n                                     IsImporting);\n  if (MOrErr)\n    (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));\n  return MOrErr;\n}\n\nExpected<std::unique_ptr<Module>>\nBitcodeModule::parseModule(LLVMContext &Context,\n                           DataLayoutCallbackTy DataLayoutCallback) {\n  return getModuleImpl(Context, true, false, false, DataLayoutCallback);\n  \/\/ TODO: Restore the use-lists to the in-memory state when the bitcode was\n  \/\/ written.  We must defer until the Module has been fully materialized.\n}\n\nExpected<std::unique_ptr<Module>>\nllvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,\n                       DataLayoutCallbackTy DataLayoutCallback) {\n  Expected<BitcodeModule> BM = getSingleModule(Buffer);\n  if (!BM)\n    return BM.takeError();\n\n  return BM->parseModule(Context, DataLayoutCallback);\n}\n\nExpected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {\n  Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);\n  if (!StreamOrErr)\n    return StreamOrErr.takeError();\n\n  return readTriple(*StreamOrErr);\n}\n\nExpected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {\n  Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);\n  if (!StreamOrErr)\n    return StreamOrErr.takeError();\n\n  return hasObjCCategory(*StreamOrErr);\n}\n\nExpected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {\n  Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);\n  if (!StreamOrErr)\n    return StreamOrErr.takeError();\n\n  return readIdentificationCode(*StreamOrErr);\n}\n\nError llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,\n                                   ModuleSummaryIndex &CombinedIndex,\n                                   uint64_t ModuleId) {\n  Expected<BitcodeModule> BM = getSingleModule(Buffer);\n  if (!BM)\n    return BM.takeError();\n\n  return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);\n}\n\nExpected<std::unique_ptr<ModuleSummaryIndex>>\nllvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {\n  Expected<BitcodeModule> BM = getSingleModule(Buffer);\n  if (!BM)\n    return BM.takeError();\n\n  return BM->getSummary();\n}\n\nExpected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {\n  Expected<BitcodeModule> BM = getSingleModule(Buffer);\n  if (!BM)\n    return BM.takeError();\n\n  return BM->getLTOInfo();\n}\n\nExpected<std::unique_ptr<ModuleSummaryIndex>>\nllvm::getModuleSummaryIndexForFile(StringRef Path,\n                                   bool IgnoreEmptyThinLTOIndexFile) {\n  ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =\n      MemoryBuffer::getFileOrSTDIN(Path);\n  if (!FileOrErr)\n    return errorCodeToError(FileOrErr.getError());\n  if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())\n    return nullptr;\n  return getModuleSummaryIndex(**FileOrErr);\n}\n","avg_line_length":36.7642524917,"max_line_length":139,"alphanum_fraction":0.6432798002,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4921,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/* Copyright (c) 2018 vesoft inc. All rights reserved.\n *\n * This source code is licensed under Apache 2.0 License,\n * attached with Common Clause Condition 1.0, found in the LICENSES directory.\n *\/\n\n#include \"base\/Base.h\"\n#include <gtest\/gtest.h>\n#include <folly\/String.h>\n#include \"fs\/TempDir.h\"\n#include \"fs\/FileUtils.h\"\n#include \"thread\/GenericThreadPool.h\"\n#include \"network\/NetworkUtils.h\"\n#include \"kvstore\/wal\/BufferFlusher.h\"\n#include \"kvstore\/raftex\/RaftexService.h\"\n#include \"kvstore\/raftex\/test\/RaftexTestBase.h\"\n#include \"kvstore\/raftex\/test\/TestShard.h\"\n\nDECLARE_uint32(raft_heartbeat_interval_secs);\n\n\nnamespace nebula {\nnamespace raftex {\n\nclass LogCASTest : public RaftexTestFixture {\npublic:\n    LogCASTest() : RaftexTestFixture(\"log_cas_test\") {}\n};\n\nTEST_F(LogCASTest, StartWithValidCAS) {\n    \/\/ Append logs\n    LOG(INFO) << \"=====> Start appending logs\";\n    std::vector<std::string> msgs;\n    leader_->atomicOpAsync([] () {\n        return test::compareAndSet(\"TCAS Log Message\");\n    });\n    msgs.emplace_back(\"CAS Log Message\");\n    appendLogs(1, 9, leader_, msgs);\n    LOG(INFO) << \"<===== Finish appending logs\";\n\n    checkConsensus(copies_, 0, 9, msgs);\n}\n\n\nTEST_F(LogCASTest, StartWithInvalidCAS) {\n    \/\/ Append logs\n    LOG(INFO) << \"=====> Start appending logs\";\n    std::vector<std::string> msgs;\n    leader_->atomicOpAsync([] () { return test::compareAndSet(\"FCAS Log Message\");});\n    appendLogs(0, 9, leader_, msgs);\n    LOG(INFO) << \"<===== Finish appending logs\";\n\n    checkConsensus(copies_, 0, 9, msgs);\n}\n\n\nTEST_F(LogCASTest, ValidCASInMiddle) {\n    \/\/ Append logs\n    LOG(INFO) << \"=====> Start appending logs\";\n    std::vector<std::string> msgs;\n    appendLogs(0, 4, leader_, msgs);\n\n    leader_->atomicOpAsync([] () { return test::compareAndSet(\"TCAS Log Message\");});\n    msgs.emplace_back(\"CAS Log Message\");\n\n    appendLogs(6, 9, leader_, msgs);\n    LOG(INFO) << \"<===== Finish appending logs\";\n\n    checkConsensus(copies_, 0, 9, msgs);\n}\n\n\nTEST_F(LogCASTest, InvalidCASInMiddle) {\n    \/\/ Append logs\n    LOG(INFO) << \"=====> Start appending logs\";\n    std::vector<std::string> msgs;\n    appendLogs(0, 4, leader_, msgs);\n\n    leader_->atomicOpAsync([] () { return test::compareAndSet(\"FCAS Log Message\");});\n\n    appendLogs(5, 9, leader_, msgs);\n    LOG(INFO) << \"<===== Finish appending logs\";\n\n    checkConsensus(copies_, 0, 9, msgs);\n}\n\n\nTEST_F(LogCASTest, EndWithValidCAS) {\n    \/\/ Append logs\n    LOG(INFO) << \"=====> Start appending logs\";\n    std::vector<std::string> msgs;\n    appendLogs(0, 7, leader_, msgs);\n\n    leader_->atomicOpAsync([] () { return test::compareAndSet(\"TCAS Log Message\");});\n    msgs.emplace_back(\"CAS Log Message\");\n\n    auto fut = leader_->atomicOpAsync([] () { return test::compareAndSet(\"TCAS Log Message\");});\n    msgs.emplace_back(\"CAS Log Message\");\n    fut.wait();\n    LOG(INFO) << \"<===== Finish appending logs\";\n\n    checkConsensus(copies_, 0, 9, msgs);\n}\n\n\nTEST_F(LogCASTest, EndWithInvalidCAS) {\n    \/\/ Append logs\n    LOG(INFO) << \"=====> Start appending logs\";\n    std::vector<std::string> msgs;\n    appendLogs(0, 7, leader_, msgs);\n\n    leader_->atomicOpAsync([] () { return test::compareAndSet(\"FCAS Log Message\");});\n    auto fut = leader_->atomicOpAsync([] () { return test::compareAndSet(\"FCAS Log Message\");});\n    fut.wait();\n    LOG(INFO) << \"<===== Finish appending logs\";\n\n    checkConsensus(copies_, 0, 7, msgs);\n}\n\n\nTEST_F(LogCASTest, AllValidCAS) {\n    \/\/ Append logs\n    LOG(INFO) << \"=====> Start appending logs\";\n    std::vector<std::string> msgs;\n    for (int i = 1; i <= 10; ++i) {\n        auto fut = leader_->atomicOpAsync([] () { return test::compareAndSet(\"TTest CAS Log\");});\n        msgs.emplace_back(\"Test CAS Log\");\n        if (i == 10) {\n            fut.wait();\n        }\n    }\n    LOG(INFO) << \"<===== Finish appending logs\";\n\n    checkConsensus(copies_, 0, 9, msgs);\n}\n\n\nTEST_F(LogCASTest, AllInvalidCAS) {\n    \/\/ Append logs\n    LOG(INFO) << \"=====> Start appending logs\";\n    std::vector<std::string> msgs;\n    for (int i = 1; i <= 10; ++i) {\n        auto fut = leader_->atomicOpAsync([] () { return test::compareAndSet(\"FCAS Log\");});\n        if (i == 10) {\n            fut.wait();\n        }\n    }\n    LOG(INFO) << \"<===== Finish appending logs\";\n\n    \/\/ Sleep a while to make sure the last log has been committed on followers\n    sleep(FLAGS_raft_heartbeat_interval_secs);\n\n    \/\/ Check every copy\n    for (auto& c : copies_) {\n        ASSERT_EQ(0, c->getNumLogs());\n    }\n}\n\n}  \/\/ namespace raftex\n}  \/\/ namespace nebula\n\n\nint main(int argc, char** argv) {\n    testing::InitGoogleTest(&argc, argv);\n    folly::init(&argc, &argv, true);\n    google::SetStderrLogging(google::INFO);\n\n    \/\/ `flusher' is extern-declared in RaftexTestBase.h, defined in RaftexTestBase.cpp\n    using nebula::raftex::flusher;\n    flusher = std::make_unique<nebula::wal::BufferFlusher>();\n\n    return RUN_ALL_TESTS();\n}\n\n\n","avg_line_length":27.9602272727,"max_line_length":97,"alphanum_fraction":0.630359683,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3351,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*==============================================================================\n==============================================================================*\/\n\n\/\/******************************************************************************\n\/\/******************************************************************************\n\/\/******************************************************************************\n#include \"stdafx.h\"\n\n#include <iostream>\n#include \"prnPrint.h\"\n#include \"risFileFunctions.h\"\n#include \"risSystemCalls.h\"\n\nnamespace Ris\n{\n\n\/\/******************************************************************************\n\/\/******************************************************************************\n\/\/******************************************************************************\n\/\/ Regionals\n\n   \n\/\/******************************************************************************\n\/\/******************************************************************************\n\/\/******************************************************************************\n\/\/ Execute a system command. return zero if successful.\n\nint doSystemCommand(const char* aCommand)\n{\n   int tRet = system(aCommand);\n   if (tRet)\n   {\n      printf(\"doSystemCommand FAIL1 %s\\n\",aCommand);\n      return -1;\n   }\n   return 0;\n}\n\n\/\/******************************************************************************\n\/\/******************************************************************************\n\/\/******************************************************************************\n\/\/ Execute a system command. return zero if successful.\n\nint doSystemCommandSuppress(const char* aCommand)\n{\n   char* tString = new char[1000];\n   strcpy(tString, aCommand);\n   strcat(tString, \" >\/dev\/null 2>&1\");\n   int tRet = system(tString);\n   delete tString;\n   return tRet;\n}\n\n\/\/******************************************************************************\n\/\/******************************************************************************\n\/\/******************************************************************************\n\/\/ Execute a system command. return zero if successful.\n\/\/ Also return the output of the command into a list of strings.\n\nint doSystemCommand(const char* aCommand, std::vector<std::string>& aResponse)\n{\n   \/\/ Do this first.\n   aResponse.clear();\n\n   \/\/ Get a random temp file name.\n   std::string tTempFileName = doGetRandomFileName();\n\n   \/\/ Construct a command string from the input command string and redirect\n   \/\/ the command output to the random temp file.\n   char* tString = new char[1000];\n   sprintf(tString, \"%s > %s\", aCommand, tTempFileName.c_str());\n  \n   \/\/ Execute the system command with the output redireced to the random\n   \/\/ temp file.\n   int tRet = system(tString);\n   \/\/ Read the system command response into the output response list.\n   std::ifstream tTempFileStream(tTempFileName);\n   for (std::string tFileLine; std::getline(tTempFileStream, tFileLine); )\n   {\n      aResponse.push_back(tFileLine);\n   }\n\n   \/\/ Delete the temp file.\n   deleteFile(tTempFileName.c_str());\n   delete tString;\n   return tRet;\n}\n\n\/\/******************************************************************************\n\/\/******************************************************************************\n\/\/******************************************************************************\n}\/\/namespace\n\n","avg_line_length":35.6489361702,"max_line_length":80,"alphanum_fraction":0.3569083856,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5757,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":3.0,"content":"\/\/ Copyright (c) 2006-2018 Maxim Khizhinsky\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include \"intrusive_stack_push_pop.h\"\n\nnamespace cds_test {\n    \/*static*\/ size_t intrusive_stack_push_pop::s_nPushThreadCount = 4;\n    \/*static*\/ size_t intrusive_stack_push_pop::s_nPopThreadCount = 4;\n    \/*static*\/ size_t intrusive_stack_push_pop::s_nStackSize = 10000000;\n    \/*static*\/ size_t intrusive_stack_push_pop::s_nEliminationSize = 4;\n    \/*static*\/ bool intrusive_stack_push_pop::s_bFCIterative = false;\n    \/*static*\/ unsigned int intrusive_stack_push_pop::s_nFCCombinePassCount = 64;\n    \/*static*\/ unsigned int intrusive_stack_push_pop::s_nFCCompactFactor = 1024;\n\n    \/*static*\/ atomics::atomic<size_t> intrusive_stack_push_pop::s_nWorkingProducers( 0 );\n\n    \/*static*\/ void intrusive_stack_push_pop::SetUpTestCase()\n    {\n        cds_test::config const& cfg = get_config( \"IntrusiveStack_PushPop\" );\n\n        s_nPushThreadCount = cfg.get_size_t( \"PushThreadCount\", s_nPushThreadCount );\n        s_nPopThreadCount = cfg.get_size_t( \"PopThreadCount\", s_nPopThreadCount );\n        s_nStackSize = cfg.get_size_t( \"StackSize\", s_nStackSize );\n        s_nEliminationSize = cfg.get_size_t( \"EliminationSize\", s_nEliminationSize );\n        s_bFCIterative = cfg.get_bool( \"FCIterate\", s_bFCIterative );\n        s_nFCCombinePassCount = cfg.get_uint( \"FCCombinePassCount\", s_nFCCombinePassCount );\n        s_nFCCompactFactor = cfg.get_uint( \"FCCompactFactor\", s_nFCCompactFactor );\n\n        if ( s_nPushThreadCount == 0 )\n            s_nPushThreadCount = 1;\n        if ( s_nPopThreadCount == 0 )\n            s_nPopThreadCount = 1;\n        if ( s_nEliminationSize == 0 )\n            s_nEliminationSize = 1;\n    }\n} \/\/ namespace cds_test\n\nnamespace {\n    class intrusive_stack_push_pop : public cds_test::intrusive_stack_push_pop\n    {\n        typedef cds_test::intrusive_stack_push_pop base_class;\n    protected:\n        typedef base_class::value_type<> value_type;\n        typedef base_class::value_type< cds::intrusive::treiber_stack::node< cds::gc::HP >> hp_value_type;\n        typedef base_class::value_type< cds::intrusive::treiber_stack::node< cds::gc::DHP >> dhp_value_type;\n\n        template <typename Stack>\n        void test()\n        {\n            value_array<typename Stack::value_type> arrValue( s_nStackSize );\n            {\n                Stack stack;\n                do_test( stack, arrValue );\n            }\n            Stack::gc::force_dispose();\n        }\n\n        void check_elimination_stat( cds::intrusive::treiber_stack::empty_stat const& )\n        {}\n\n        void check_elimination_stat( cds::intrusive::treiber_stack::stat<> const& s )\n        {\n            EXPECT_EQ( s.m_PushCount.get() + s.m_ActivePushCollision.get() + s.m_PassivePushCollision.get(), s_nStackSize );\n            EXPECT_EQ( s.m_PopCount.get() + s.m_ActivePopCollision.get() + s.m_PassivePopCollision.get(), s_nStackSize );\n            EXPECT_EQ( s.m_PushCount.get(), s.m_PopCount.get());\n            EXPECT_EQ( s.m_ActivePopCollision.get(), s.m_PassivePushCollision.get());\n            EXPECT_EQ( s.m_ActivePushCollision.get(), s.m_PassivePopCollision.get());\n        }\n\n        template <typename Stack>\n        void test_elimination()\n        {\n            value_array<typename Stack::value_type> arrValue( s_nStackSize );\n            {\n                Stack stack( s_nEliminationSize );\n                do_test( stack, arrValue );\n                check_elimination_stat( stack.statistics());\n            }\n            Stack::gc::force_dispose();\n        }\n\n        template <typename Stack>\n        void test_std()\n        {\n            value_array<typename Stack::value_type> arrValue( s_nStackSize );\n            Stack stack;\n            do_test( stack, arrValue );\n        }\n    };\n\n    \/\/ TreiberStack<cds::gc::HP>\n#define CDSSTRESS_Stack_F( test_fixture, stack_impl ) \\\n    TEST_F( test_fixture, stack_impl ) \\\n    { \\\n        typedef typename istack::Types<hp_value_type>::stack_impl stack_type; \\\n        test< stack_type >(); \\\n    }\n\n    CDSSTRESS_TreiberStack_HP( intrusive_stack_push_pop )\n\n#undef CDSSTRESS_Stack_F\n\n    \/\/ TreiberStack<cds::gc::DHP>\n#define CDSSTRESS_Stack_F( test_fixture, stack_impl ) \\\n    TEST_F( test_fixture, stack_impl ) \\\n    { \\\n        typedef typename istack::Types<dhp_value_type>::stack_impl stack_type; \\\n        test< stack_type >(); \\\n    }\n\n    CDSSTRESS_TreiberStack_DHP( intrusive_stack_push_pop )\n\n#undef CDSSTRESS_Stack_F\n\n    \/\/ TreiberStack<cds::gc::HP> + elimination enabled\n#define CDSSTRESS_Stack_F( test_fixture, stack_impl ) \\\n    TEST_F( test_fixture, stack_impl ) \\\n    { \\\n        typedef typename istack::Types<hp_value_type>::stack_impl stack_type; \\\n        test_elimination< stack_type >(); \\\n    }\n\n    CDSSTRESS_EliminationStack_HP( intrusive_stack_push_pop )\n\n#undef CDSSTRESS_Stack_F\n\n\n    \/\/ TreiberStack<cds::gc::DHP> + elimination enabled\n#define CDSSTRESS_Stack_F( test_fixture, stack_impl ) \\\n    TEST_F( test_fixture, stack_impl ) \\\n    { \\\n        typedef typename istack::Types<dhp_value_type>::stack_impl stack_type; \\\n        test_elimination< stack_type >(); \\\n    }\n\n    CDSSTRESS_EliminationStack_DHP( intrusive_stack_push_pop )\n\n#undef CDSSTRESS_Stack_F\n\n\n    \/\/ StdStack\n#define CDSSTRESS_Stack_F( test_fixture, stack_impl ) \\\n    TEST_F( test_fixture, stack_impl ) \\\n    { \\\n        typedef typename istack::Types<value_type>::stack_impl stack_type; \\\n        test_std< stack_type >(); \\\n    }\n\n    CDSSTRESS_StdStack( intrusive_stack_push_pop )\n\n#undef CDSSTRESS_Stack_F\n\n    \/\/INSTANTIATE_TEST_CASE_P( a, intrusive_stack_push_pop, ::testing::Values(1));\n\n} \/\/ namespace\n","avg_line_length":36.4367088608,"max_line_length":124,"alphanum_fraction":0.6689247872,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7439,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/*\n * Copyright (C) 2012 Apple Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n * THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"ScrollingTreeScrollingNode.h\"\n\n#if ENABLE(ASYNC_SCROLLING)\n\n#include \"ScrollingStateTree.h\"\n#include \"ScrollingTree.h\"\n#include <wtf\/text\/TextStream.h>\n\nnamespace WebCore {\n\nScrollingTreeScrollingNode::ScrollingTreeScrollingNode(ScrollingTree& scrollingTree, ScrollingNodeType nodeType, ScrollingNodeID nodeID)\n    : ScrollingTreeNode(scrollingTree, nodeType, nodeID)\n{\n}\n\nScrollingTreeScrollingNode::~ScrollingTreeScrollingNode() = default;\n\nvoid ScrollingTreeScrollingNode::commitStateBeforeChildren(const ScrollingStateNode& stateNode)\n{\n    const ScrollingStateScrollingNode& state = downcast<ScrollingStateScrollingNode>(stateNode);\n\n    if (state.hasChangedProperty(ScrollingStateScrollingNode::ScrollableAreaSize))\n        m_scrollableAreaSize = state.scrollableAreaSize();\n\n    if (state.hasChangedProperty(ScrollingStateScrollingNode::TotalContentsSize)) {\n        if (scrollingTree().isRubberBandInProgress())\n            m_totalContentsSizeForRubberBand = m_totalContentsSize;\n        else\n            m_totalContentsSizeForRubberBand = state.totalContentsSize();\n\n        m_totalContentsSize = state.totalContentsSize();\n    }\n\n    if (state.hasChangedProperty(ScrollingStateScrollingNode::ReachableContentsSize))\n        m_reachableContentsSize = state.reachableContentsSize();\n\n    if (state.hasChangedProperty(ScrollingStateScrollingNode::ScrollPosition))\n        m_lastCommittedScrollPosition = state.scrollPosition();\n\n    if (state.hasChangedProperty(ScrollingStateScrollingNode::ScrollOrigin))\n        m_scrollOrigin = state.scrollOrigin();\n\n#if ENABLE(CSS_SCROLL_SNAP)\n    if (state.hasChangedProperty(ScrollingStateScrollingNode::HorizontalSnapOffsets))\n        m_snapOffsetsInfo.horizontalSnapOffsets = state.horizontalSnapOffsets();\n\n    if (state.hasChangedProperty(ScrollingStateScrollingNode::VerticalSnapOffsets))\n        m_snapOffsetsInfo.verticalSnapOffsets = state.verticalSnapOffsets();\n\n    if (state.hasChangedProperty(ScrollingStateScrollingNode::HorizontalSnapOffsetRanges))\n        m_snapOffsetsInfo.horizontalSnapOffsetRanges = state.horizontalSnapOffsetRanges();\n\n    if (state.hasChangedProperty(ScrollingStateScrollingNode::VerticalSnapOffsetRanges))\n        m_snapOffsetsInfo.verticalSnapOffsetRanges = state.verticalSnapOffsetRanges();\n\n    if (state.hasChangedProperty(ScrollingStateScrollingNode::CurrentHorizontalSnapOffsetIndex))\n        m_currentHorizontalSnapPointIndex = state.currentHorizontalSnapPointIndex();\n\n    if (state.hasChangedProperty(ScrollingStateScrollingNode::CurrentVerticalSnapOffsetIndex))\n        m_currentVerticalSnapPointIndex = state.currentVerticalSnapPointIndex();\n#endif\n\n    if (state.hasChangedProperty(ScrollingStateScrollingNode::ScrollableAreaParams))\n        m_scrollableAreaParameters = state.scrollableAreaParameters();\n}\n\nvoid ScrollingTreeScrollingNode::commitStateAfterChildren(const ScrollingStateNode& stateNode)\n{\n    const ScrollingStateScrollingNode& scrollingStateNode = downcast<ScrollingStateScrollingNode>(stateNode);\n    if (scrollingStateNode.hasChangedProperty(ScrollingStateScrollingNode::RequestedScrollPosition))\n        scrollingTree().scrollingTreeNodeRequestsScroll(scrollingNodeID(), scrollingStateNode.requestedScrollPosition(), scrollingStateNode.requestedScrollPositionRepresentsProgrammaticScroll());\n}\n\nvoid ScrollingTreeScrollingNode::updateLayersAfterAncestorChange(const ScrollingTreeNode& changedNode, const FloatRect& fixedPositionRect, const FloatSize& cumulativeDelta)\n{\n    if (!m_children)\n        return;\n\n    for (auto& child : *m_children)\n        child->updateLayersAfterAncestorChange(changedNode, fixedPositionRect, cumulativeDelta);\n}\n\nvoid ScrollingTreeScrollingNode::setScrollPosition(const FloatPoint& scrollPosition)\n{\n    FloatPoint newScrollPosition = scrollPosition.constrainedBetween(minimumScrollPosition(), maximumScrollPosition());\n    setScrollPositionWithoutContentEdgeConstraints(newScrollPosition);\n}\n\nvoid ScrollingTreeScrollingNode::setScrollPositionWithoutContentEdgeConstraints(const FloatPoint& scrollPosition)\n{\n    setScrollLayerPosition(scrollPosition, { });\n    scrollingTree().scrollingTreeNodeDidScroll(scrollingNodeID(), scrollPosition, std::nullopt);\n}\n\nFloatPoint ScrollingTreeScrollingNode::minimumScrollPosition() const\n{\n    return FloatPoint();\n}\n\nFloatPoint ScrollingTreeScrollingNode::maximumScrollPosition() const\n{\n    FloatPoint contentSizePoint(totalContentsSize());\n    return FloatPoint(contentSizePoint - scrollableAreaSize()).expandedTo(FloatPoint());\n}\n\nvoid ScrollingTreeScrollingNode::dumpProperties(TextStream& ts, ScrollingStateTreeAsTextBehavior behavior) const\n{\n    ScrollingTreeNode::dumpProperties(ts, behavior);\n    ts.dumpProperty(\"scrollable area size\", m_scrollableAreaSize);\n    ts.dumpProperty(\"total content size\", m_totalContentsSize);\n    if (m_totalContentsSizeForRubberBand != m_totalContentsSize)\n        ts.dumpProperty(\"total content size for rubber band\", m_totalContentsSizeForRubberBand);\n    if (m_reachableContentsSize != m_totalContentsSize)\n        ts.dumpProperty(\"reachable content size\", m_reachableContentsSize);\n    ts.dumpProperty(\"last committed scroll position\", m_lastCommittedScrollPosition);\n    if (m_scrollOrigin != IntPoint())\n        ts.dumpProperty(\"scroll origin\", m_scrollOrigin);\n\n#if ENABLE(CSS_SCROLL_SNAP)\n    if (m_snapOffsetsInfo.horizontalSnapOffsets.size())\n        ts.dumpProperty(\"horizontal snap offsets\", m_snapOffsetsInfo.horizontalSnapOffsets);\n\n    if (m_snapOffsetsInfo.verticalSnapOffsets.size())\n        ts.dumpProperty(\"vertical snap offsets\", m_snapOffsetsInfo.verticalSnapOffsets);\n\n    if (m_currentHorizontalSnapPointIndex)\n        ts.dumpProperty(\"current horizontal snap point index\", m_currentHorizontalSnapPointIndex);\n\n    if (m_currentVerticalSnapPointIndex)\n        ts.dumpProperty(\"current vertical snap point index\", m_currentVerticalSnapPointIndex);\n    \n#endif\n\n    ts.dumpProperty(\"scrollable area parameters\", m_scrollableAreaParameters);\n}\n\n} \/\/ namespace WebCore\n\n#endif \/\/ ENABLE(ASYNC_SCROLLING)\n","avg_line_length":44.813253012,"max_line_length":195,"alphanum_fraction":0.7959403146,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":28188,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Copyright (c) 2014 Samsung Electronics Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <dali\/dali.h>\n#include <dali-toolkit\/dali-toolkit.h>\n#include <dali-toolkit\/devel-api\/controls\/popup\/popup.h>\n#include \"shared\/view.h\"\n#include <iostream>\n\nusing namespace Dali;\nusing Toolkit::TextLabel;\n\nnamespace\n{\n\nconst char* BACKGROUND_IMAGE( DEMO_IMAGE_DIR \"background-gradient.jpg\" );\nconst Vector4 BACKGROUND_COLOUR( 1.0f, 1.0f, 1.0f, 0.15f );\n\nconst char* BORDER_IMAGE( DEMO_IMAGE_DIR \"border-4px.9.png\" );\nconst int BORDER_WIDTH = ( 11.0f + 4.0f ); \/\/ Shadow size = 11, border size = 4.\nconst char* RESIZE_HANDLE_IMAGE( DEMO_IMAGE_DIR \"resize-handle.png\" );\n\nconst int MARGIN_SIZE = 10;\n\nconst char* const NEXT_BUTTON_ID = \"NEXT_BUTTON\";\nconst char* const PREVIOUS_BUTTON_ID = \"PREVIOUS_BUTTON\";\nconst char * const DALI_ICON_PLAY = DEMO_IMAGE_DIR \"icon-play.png\";\n\nconst char* const FITTING_BUTTON_ID = \"FITTING_BUTTON\";\nconst char* const SAMPLING_BUTTON_ID = \"SAMPLING_BUTTON\";\nconst char* const FITTING_BUTTON_TEXT = \"Fitting\";\nconst char* const SAMPLING_BUTTON_TEXT = \"Sampling\";\n\nconst char* const STYLE_LABEL_TEXT  = \"grouplabel\";\nconst char* const STYLE_BUTTON_TEXT = \"buttonlabel\";\n\n\nconst char* IMAGE_PATHS[] =\n{\n  \/\/ Variety of sizes, shapes and formats:\n  DEMO_IMAGE_DIR \"dali-logo.png\",\n  DEMO_IMAGE_DIR \"layer1.png\",\n  DEMO_IMAGE_DIR \"layer2.png\",\n  DEMO_IMAGE_DIR \"animation-list.png\",\n  DEMO_IMAGE_DIR \"music-libray-main-screen.png\",\n  DEMO_IMAGE_DIR \"music-libray-record-cover.png\",\n  DEMO_IMAGE_DIR \"contacts-background.png\",\n  DEMO_IMAGE_DIR \"portrait_screen_primitive_shapes.gif\",\n  DEMO_IMAGE_DIR \"landscape_screen_primitive_shapes.gif\",\n  DEMO_IMAGE_DIR \"square_primitive_shapes.bmp\",\n  DEMO_IMAGE_DIR \"gallery-large-14.jpg\",\n  DEMO_IMAGE_DIR \"book-landscape-cover.jpg\",\n  DEMO_IMAGE_DIR \"book-portrait-p1.jpg\",\n  DEMO_IMAGE_DIR \"book-landscape-cover-back.jpg\",\n\n  \/\/ Worst case for aliasing in downscaling, 2k x 2k 1 bit per pixel dithered\n  \/\/ black and white image:\n  DEMO_IMAGE_DIR \"gallery-large-14.wbmp\",\n\n  DEMO_IMAGE_DIR \"background-1.jpg\",\n  DEMO_IMAGE_DIR \"background-blocks.jpg\",\n  DEMO_IMAGE_DIR \"background-magnifier.jpg\",\n  DEMO_IMAGE_DIR \"gallery-large-14.jpg\",\n  NULL\n};\nconst int NUM_IMAGE_PATHS = sizeof(IMAGE_PATHS) \/ sizeof(IMAGE_PATHS[0]) - 1u;\n\n\/** Cycle the scaling mode options. *\/\nFittingMode::Type NextScalingMode( FittingMode::Type oldMode )\n{\n  FittingMode::Type newMode = FittingMode::SHRINK_TO_FIT;\n  switch ( oldMode )\n  {\n    case FittingMode::SHRINK_TO_FIT:\n      newMode = FittingMode::SCALE_TO_FILL;\n      break;\n    case FittingMode::SCALE_TO_FILL:\n      newMode = FittingMode::FIT_WIDTH;\n      break;\n    case FittingMode::FIT_WIDTH:\n      newMode = FittingMode::FIT_HEIGHT;\n      break;\n    case FittingMode::FIT_HEIGHT:\n      newMode = FittingMode::SHRINK_TO_FIT;\n      break;\n  }\n  return newMode;\n}\n\n\/** Cycle through filter mode options. *\/\nSamplingMode::Type NextFilterMode( SamplingMode::Type oldMode )\n{\n  SamplingMode::Type newMode = SamplingMode::BOX;\n\n  switch ( oldMode )\n  {\n    case SamplingMode::BOX:\n      newMode = SamplingMode::NEAREST;\n      break;\n    case SamplingMode::NEAREST:\n      newMode = SamplingMode::LINEAR;\n      break;\n    case SamplingMode::LINEAR:\n      newMode = SamplingMode::BOX_THEN_NEAREST;\n      break;\n    case SamplingMode::BOX_THEN_NEAREST:\n      newMode = SamplingMode::BOX_THEN_LINEAR;\n      break;\n    case SamplingMode::BOX_THEN_LINEAR:\n      newMode = SamplingMode::NO_FILTER;\n      break;\n    case SamplingMode::NO_FILTER:\n      newMode = SamplingMode::BOX;\n      break;\n    case SamplingMode::DONT_CARE:\n      newMode = SamplingMode::BOX;\n      break;\n  }\n  return newMode;\n}\n\nconst char* StringFromScalingMode( FittingMode::Type scalingMode )\n{\n  return scalingMode == FittingMode::SCALE_TO_FILL ? \"SCALE_TO_FILL\" : scalingMode == FittingMode::SHRINK_TO_FIT ? \"SHRINK_TO_FIT\" : scalingMode == FittingMode::FIT_WIDTH ? \"FIT_WIDTH\" : scalingMode == FittingMode::FIT_HEIGHT ? \"FIT_HEIGHT\" : \"UnknownScalingMode\";\n}\n\nconst char* StringFromFilterMode( SamplingMode::Type filterMode )\n{\n  return filterMode == SamplingMode::BOX ? \"BOX\" : filterMode == SamplingMode::BOX_THEN_NEAREST ? \"BOX_THEN_NEAREST\" : filterMode == SamplingMode::BOX_THEN_LINEAR ? \"BOX_THEN_LINEAR\" : filterMode == SamplingMode::NEAREST ? \"NEAREST\" : filterMode == SamplingMode::LINEAR ? \"LINEAR\" : filterMode == SamplingMode::NO_FILTER ? \"NO_FILTER\" : filterMode == SamplingMode::DONT_CARE ? \"DONT_CARE\" : \"UnknownFilterMode\";\n}\n\n}\n\n\/\/ This example shows the load-time image scaling and filtering features.\n\/\/\nclass ImageScalingAndFilteringController : public ConnectionTracker\n{\npublic:\n\n  ImageScalingAndFilteringController( Application& application )\n  : mApplication( application ),\n    mImageStageScale( 0.5f, 0.5f ),\n    mCurrentPath( 0 ),\n    mFittingMode( FittingMode::FIT_WIDTH ),\n    mSamplingMode( SamplingMode::BOX_THEN_LINEAR),\n    mImageLoading( false ),\n    mQueuedImageLoad( false )\n  {\n    \/\/ Connect to the Application's Init signal\n    mApplication.InitSignal().Connect( this, &ImageScalingAndFilteringController::Create );\n  }\n\n  ~ImageScalingAndFilteringController()\n  {\n    \/\/ Nothing to do here;\n  }\n\n  \/\/ The Init signal is received once (only) during the Application lifetime\n  void Create( Application& application )\n  {\n    \/\/ Get a handle to the stage\n    Stage stage = Stage::GetCurrent();\n\n    \/\/ Background image:\n    Dali::Property::Map backgroundImage;\n    backgroundImage.Insert( Toolkit::Visual::Property::TYPE,  Toolkit::Visual::IMAGE );\n    backgroundImage.Insert( Toolkit::ImageVisual::Property::URL,  BACKGROUND_IMAGE );\n    backgroundImage.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, stage.GetSize().width );\n    backgroundImage.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, stage.GetSize().height );\n    backgroundImage.Insert( Toolkit::ImageVisual::Property::FITTING_MODE,   FittingMode::SCALE_TO_FILL );\n    backgroundImage.Insert( Toolkit::ImageVisual::Property::SAMPLING_MODE,   SamplingMode::BOX_THEN_NEAREST );\n\n    Toolkit::ImageView background = Toolkit::ImageView::New();\n    background.SetProperty( Toolkit::ImageView::Property::IMAGE, backgroundImage );\n    background.SetAnchorPoint( AnchorPoint::TOP_LEFT );\n    background.SetSize( stage.GetSize() );\n    stage.Add( background );\n\n    BufferImage heightBackground = BufferImage::WHITE();\n    PixelBuffer* const heightPixel = heightBackground.GetBuffer();\n    heightPixel[0] = 0x8f;\n    heightPixel[1] = 0x8f;\n    heightPixel[2] = 0x8f;\n\n    BufferImage widthBackground = BufferImage::WHITE();\n    PixelBuffer* const widthPixel = widthBackground.GetBuffer();\n    widthPixel[0] = 0x4f;\n    widthPixel[1] = 0x4f;\n    widthPixel[2] = 0x4f;\n\n    mHeightBox = Toolkit::ImageView::New( heightBackground );\n    mHeightBox.SetOpacity( 0.2f );\n    background.Add( mHeightBox );\n\n    mWidthBox = Toolkit::ImageView::New( widthBackground );\n    mWidthBox.SetOpacity( 0.2f );\n    background.Add( mWidthBox );\n\n    mDesiredBox = Toolkit::ImageView::New( BORDER_IMAGE );\n    background.Add( mDesiredBox );\n\n    mDesiredBox.SetSize( stage.GetSize() * mImageStageScale );\n    mDesiredBox.SetParentOrigin( ParentOrigin::CENTER );\n    mDesiredBox.SetAnchorPoint( AnchorPoint::CENTER );\n\n    mHeightBox.SetSize( stage.GetSize().width,  (stage.GetSize() * mImageStageScale).height );\n    mHeightBox.SetParentOrigin( ParentOrigin::CENTER );\n    mHeightBox.SetAnchorPoint( AnchorPoint::CENTER );\n\n    mWidthBox.SetSize( (stage.GetSize() * mImageStageScale).width, stage.GetSize().height );\n    mWidthBox.SetParentOrigin( ParentOrigin::CENTER );\n    mWidthBox.SetAnchorPoint( AnchorPoint::CENTER );\n\n    \/\/ Initialize the actor\n    mImageView = Toolkit::ImageView::New( IMAGE_PATHS[ 0 ] );\n\n    \/\/ Reposition the actor\n    mImageView.SetParentOrigin( ParentOrigin::CENTER );\n    mImageView.SetAnchorPoint( AnchorPoint::CENTER );\n\n    \/\/ Display the actor on the stage\n    mDesiredBox.Add( mImageView );\n\n    mImageView.SetSize( stage.GetSize() * mImageStageScale );\n\n    \/\/ Setup the pinch detector for scaling the desired image load dimensions:\n    mPinchDetector = PinchGestureDetector::New();\n    mPinchDetector.Attach( mImageView );\n    mPinchDetector.DetectedSignal().Connect( this, &ImageScalingAndFilteringController::OnPinch );\n\n    mGrabCorner = Toolkit::ImageView::New( RESIZE_HANDLE_IMAGE );\n    mGrabCorner.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );\n    mGrabCorner.SetName( \"GrabCorner\" );\n    mGrabCorner.SetAnchorPoint( AnchorPoint::BOTTOM_RIGHT );\n    mGrabCorner.SetParentOrigin( ParentOrigin::BOTTOM_RIGHT );\n    mGrabCorner.SetPosition( -BORDER_WIDTH, -BORDER_WIDTH );\n    mGrabCorner.SetOpacity( 0.6f );\n\n    Layer grabCornerLayer = Layer::New();\n    grabCornerLayer.SetAnchorPoint( AnchorPoint::BOTTOM_RIGHT );\n    grabCornerLayer.SetParentOrigin( ParentOrigin::BOTTOM_RIGHT );\n    grabCornerLayer.Add( mGrabCorner );\n    mDesiredBox.Add( grabCornerLayer );\n\n    mPanGestureDetector = PanGestureDetector::New();\n    mPanGestureDetector.Attach( mGrabCorner );\n    mPanGestureDetector.DetectedSignal().Connect( this, &ImageScalingAndFilteringController::OnPan );\n\n    \/\/ Tie-in input event handlers:\n    stage.KeyEventSignal().Connect( this, &ImageScalingAndFilteringController::OnKeyEvent );\n\n    CreateControls();\n\n    ResizeImage();\n  }\n\n  \/**\n   * Create the GUI controls which float above the scene\n   *\/\n  void CreateControls()\n  {\n    Stage stage = Stage::GetCurrent();\n\n    Dali::Layer controlsLayer = Dali::Layer::New();\n    controlsLayer.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );\n    controlsLayer.SetSizeModeFactor( Vector3( 1.0f, 1.0f, 1.0f ) );\n    controlsLayer.SetAnchorPoint( AnchorPoint::TOP_LEFT);\n    controlsLayer.SetParentOrigin( ParentOrigin::TOP_LEFT);\n    stage.Add( controlsLayer );\n\n    \/\/ Back and next image buttons in corners of stage:\n    unsigned int playWidth = std::min( stage.GetSize().x * (1 \/ 5.0f), 58.0f );\n    Toolkit::ImageView imagePrevious = Toolkit::ImageView::New( DALI_ICON_PLAY, ImageDimensions( playWidth, playWidth ) );\n\n    \/\/ Last image button:\n    imagePrevious.SetAnchorPoint( AnchorPoint::TOP_LEFT );\n    imagePrevious.RotateBy( Radian(3.14159265358979323846f), Vector3( 0, 1.0f, 0 ) );\n    imagePrevious.SetY( playWidth * 0.5f );\n    imagePrevious.SetX( playWidth + playWidth * 0.5f );\n    imagePrevious.SetOpacity( 0.6f );\n    controlsLayer.Add( imagePrevious );\n    imagePrevious.SetName( PREVIOUS_BUTTON_ID );\n    imagePrevious.TouchSignal().Connect( this, &ImageScalingAndFilteringController::OnControlTouched );\n\n    \/\/ Next image button:\n    Toolkit::ImageView imageNext = Toolkit::ImageView::New( DALI_ICON_PLAY, ImageDimensions( playWidth, playWidth ) );\n    imageNext.SetAnchorPoint( AnchorPoint::TOP_RIGHT );\n    imageNext.SetY( playWidth * 0.5f );\n    imageNext.SetX( stage.GetSize().x - playWidth * 0.5f );\n    imageNext.SetOpacity( 0.6f );\n    controlsLayer.Add( imageNext );\n    imageNext.SetName( NEXT_BUTTON_ID );\n    imageNext.TouchSignal().Connect( this, &ImageScalingAndFilteringController::OnControlTouched );\n\n    \/\/ Buttons to popup selectors for fitting and sampling modes:\n\n    \/\/ Wrapper table to hold two buttons side by side:\n    Toolkit::TableView modesGroupBackground = Toolkit::TableView::New( 1, 2 );\n    modesGroupBackground.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );\n    modesGroupBackground.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT );\n    modesGroupBackground.SetBackgroundColor( BACKGROUND_COLOUR );\n    modesGroupBackground.SetCellPadding( Size( MARGIN_SIZE * 0.5f, MARGIN_SIZE ) );\n    modesGroupBackground.SetFitHeight( 0 );\n\n    modesGroupBackground.SetAnchorPoint( AnchorPoint::BOTTOM_LEFT );\n    modesGroupBackground.SetParentOrigin( ParentOrigin::BOTTOM_LEFT );\n    modesGroupBackground.SetPosition( 0.0f, 0.0f );\n\n    controlsLayer.Add( modesGroupBackground );\n\n    {\n      \/\/ Vertical table to hold label and button:\n      Toolkit::TableView fittingModeGroup = Toolkit::TableView::New( 2, 1 );\n      fittingModeGroup.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );\n      fittingModeGroup.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT );\n      fittingModeGroup.SetBackgroundColor( BACKGROUND_COLOUR );\n      fittingModeGroup.SetCellPadding( Size( MARGIN_SIZE * 0.5f, MARGIN_SIZE * 0.5f ) );\n      fittingModeGroup.SetFitHeight( 0 );\n      fittingModeGroup.SetFitHeight( 1 );\n\n      TextLabel label = TextLabel::New( \"Image fitting mode:\" );\n      label.SetProperty( Toolkit::Control::Property::STYLE_NAME, STYLE_LABEL_TEXT );\n      fittingModeGroup.Add( label );\n\n      Toolkit::PushButton button = CreateButton( FITTING_BUTTON_ID, StringFromScalingMode( mFittingMode ) );\n      fittingModeGroup.Add( button );\n      mFittingModeButton = button;\n\n      modesGroupBackground.Add( fittingModeGroup );\n    }\n\n    {\n      \/\/ Vertical table to hold label and button:\n      Toolkit::TableView samplingModeGroup = Toolkit::TableView::New( 2, 1 );\n      samplingModeGroup.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );\n      samplingModeGroup.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT );\n      samplingModeGroup.SetBackgroundColor( BACKGROUND_COLOUR );\n      samplingModeGroup.SetCellPadding( Size( MARGIN_SIZE * 0.5f, MARGIN_SIZE * 0.5f ) );\n      samplingModeGroup.SetFitHeight( 0 );\n      samplingModeGroup.SetFitHeight( 1 );\n\n      TextLabel label = TextLabel::New( \"Image sampling mode:\" );\n      label.SetProperty( Toolkit::Control::Property::STYLE_NAME, STYLE_LABEL_TEXT );\n      samplingModeGroup.Add( label );\n\n      Toolkit::PushButton button = CreateButton( SAMPLING_BUTTON_ID, StringFromFilterMode( mSamplingMode ) );\n      samplingModeGroup.Add( button );\n      mSamplingModeButton = button;\n\n      modesGroupBackground.Add( samplingModeGroup );\n    }\n  }\n\n  Toolkit::PushButton CreateButton( const char * id, const char * label )\n  {\n    Toolkit::PushButton button = Toolkit::PushButton::New();\n    button.SetProperty( Toolkit::Control::Property::STYLE_NAME, STYLE_BUTTON_TEXT );\n    button.SetName( id );\n    button.SetLabelText( label );\n    button.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );\n    button.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT );\n    button.ClickedSignal().Connect( this, &ImageScalingAndFilteringController::OnButtonClicked );\n    return button;\n  }\n\n  Toolkit::Popup CreatePopup()\n  {\n    Stage stage = Stage::GetCurrent();\n    const float POPUP_WIDTH_DP = stage.GetSize().width * 0.75f;\n\n    Toolkit::Popup popup = Toolkit::Popup::New();\n    popup.SetName( \"POPUP\" );\n    popup.SetParentOrigin( ParentOrigin::CENTER );\n    popup.SetAnchorPoint( AnchorPoint::CENTER );\n    popup.SetSize( POPUP_WIDTH_DP, 0.0f );\n\n    popup.OutsideTouchedSignal().Connect( this, &ImageScalingAndFilteringController::OnPopupOutsideTouched );\n\n    return popup;\n  }\n\n  Toolkit::PushButton CreatePopupButton( Actor parent, const char* id )\n  {\n    Toolkit::PushButton button = Toolkit::PushButton::New();\n    button.SetName( id );\n    button.SetLabelText( id );\n\n    button.SetAnchorPoint( AnchorPoint::TOP_LEFT );\n    button.SetParentOrigin( ParentOrigin::BOTTOM_LEFT );\n    button.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );\n    button.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT );\n\n    button.ClickedSignal().Connect( this, &ImageScalingAndFilteringController::OnButtonClicked );\n\n    parent.Add( button );\n    return button;\n  }\n\n  bool OnButtonClicked( Toolkit::Button button )\n  {\n    if( button.GetName() == FITTING_BUTTON_ID )\n    {\n      mPopup = CreatePopup();\n\n      \/\/ Four-row table to hold buttons:\n      Toolkit::TableView fittingModes = Toolkit::TableView::New( 4, 1 );\n      fittingModes.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );\n      fittingModes.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT );\n      fittingModes.SetCellPadding( Size( MARGIN_SIZE, MARGIN_SIZE * 0.5 ) );\n      fittingModes.SetFitHeight( 0 );\n      fittingModes.SetFitHeight( 1 );\n      fittingModes.SetFitHeight( 2 );\n      fittingModes.SetFitHeight( 3 );\n\n      CreatePopupButton( fittingModes, StringFromScalingMode( FittingMode::SCALE_TO_FILL ) );\n      CreatePopupButton( fittingModes, StringFromScalingMode( FittingMode::SHRINK_TO_FIT ) );\n      CreatePopupButton( fittingModes, StringFromScalingMode( FittingMode::FIT_WIDTH ) );\n      CreatePopupButton( fittingModes, StringFromScalingMode( FittingMode::FIT_HEIGHT ) );\n\n      mPopup.SetContent( fittingModes );\n      Stage::GetCurrent().Add( mPopup );\n      mPopup.SetDisplayState( Toolkit::Popup::SHOWN );\n    }\n    else if( button.GetName() == SAMPLING_BUTTON_ID )\n    {\n      mPopup = CreatePopup();\n\n      \/\/ Table to hold buttons for each sampling mode:\n      Toolkit::TableView samplingModes = Toolkit::TableView::New( 6, 1 );\n      samplingModes.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );\n      samplingModes.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT );\n      samplingModes.SetCellPadding( Size( MARGIN_SIZE, MARGIN_SIZE * 0.5 ) );\n      samplingModes.SetFitHeight( 0 );\n      samplingModes.SetFitHeight( 1 );\n      samplingModes.SetFitHeight( 2 );\n      samplingModes.SetFitHeight( 3 );\n      samplingModes.SetFitHeight( 4 );\n      samplingModes.SetFitHeight( 5 );\n\n      CreatePopupButton( samplingModes, StringFromFilterMode( SamplingMode::NEAREST ) );\n      CreatePopupButton( samplingModes, StringFromFilterMode( SamplingMode::LINEAR ) );\n      CreatePopupButton( samplingModes, StringFromFilterMode( SamplingMode::BOX ) );\n      CreatePopupButton( samplingModes, StringFromFilterMode( SamplingMode::BOX_THEN_NEAREST ) );\n      CreatePopupButton( samplingModes, StringFromFilterMode( SamplingMode::BOX_THEN_LINEAR ) );\n      CreatePopupButton( samplingModes, StringFromFilterMode( SamplingMode::NO_FILTER ) );\n\n      mPopup.SetContent( samplingModes );\n      Stage::GetCurrent().Add( mPopup );\n      mPopup.SetDisplayState( Toolkit::Popup::SHOWN );\n    }\n    else if( CheckFittingModeButton( button, FittingMode::SCALE_TO_FILL) ||\n             CheckFittingModeButton( button, FittingMode::SHRINK_TO_FIT) ||\n             CheckFittingModeButton( button, FittingMode::FIT_WIDTH) ||\n             CheckFittingModeButton( button, FittingMode::FIT_HEIGHT) )\n    {\n    }\n    else if( CheckSamplingModeButton( button, SamplingMode::NEAREST ) ||\n             CheckSamplingModeButton( button, SamplingMode::LINEAR ) ||\n             CheckSamplingModeButton( button, SamplingMode::BOX ) ||\n             CheckSamplingModeButton( button, SamplingMode::LINEAR ) ||\n             CheckSamplingModeButton( button, SamplingMode::BOX_THEN_NEAREST ) ||\n             CheckSamplingModeButton( button, SamplingMode::BOX_THEN_LINEAR ) ||\n             CheckSamplingModeButton( button, SamplingMode::NO_FILTER ) )\n    {\n    }\n    return true;\n  }\n\n  bool CheckFittingModeButton( Actor &button, FittingMode::Type mode )\n  {\n    const char * const modeName = StringFromScalingMode( mode );\n    if( button.GetName() == modeName )\n    {\n      mFittingMode = mode;\n      mFittingModeButton.SetLabelText( modeName );\n      ResizeImage();\n      mPopup.SetDisplayState( Toolkit::Popup::HIDDEN );\n      mPopup.Reset();\n      return true;\n    }\n    return false;\n  }\n\n  bool CheckSamplingModeButton( Actor &button, SamplingMode::Type mode )\n  {\n    const char * const modeName = StringFromFilterMode( mode );\n    if( button.GetName() == modeName )\n    {\n      mSamplingMode = mode;\n      mSamplingModeButton.SetLabelText( modeName );\n      ResizeImage();\n      mPopup.SetDisplayState( Toolkit::Popup::HIDDEN );\n      mPopup.Reset();\n      return true;\n    }\n    return false;\n  }\n\n  void OnPopupOutsideTouched()\n  {\n    if( mPopup )\n    {\n      mPopup.SetDisplayState( Toolkit::Popup::HIDDEN );\n      mPopup.Reset();\n    }\n  }\n\n  void OnImageLoaded( ResourceImage image )\n  {\n    DALI_ASSERT_DEBUG( image == mNextImage );\n    mImageView.SetImage( image );\n    mImageView.SetSize( Size( image.GetWidth(), image.GetHeight() ) );\n    mImageLoading = false;\n\n    \/\/ We have finished loading, if a resize had occured during the load, trigger another load now.\n    if( mQueuedImageLoad )\n    {\n      mQueuedImageLoad = false;\n      LoadImage();\n    }\n  }\n\n  bool OnControlTouched( Actor actor, const TouchData& event )\n  {\n    if(event.GetPointCount() > 0)\n    {\n      switch( event.GetState( 0 ) )\n      {\n        case PointState::UP:\n        {\n          const std::string & name = actor.GetName();\n          if( name == NEXT_BUTTON_ID )\n          {\n            mCurrentPath = mCurrentPath + 1;\n            mCurrentPath = mCurrentPath <  NUM_IMAGE_PATHS ? mCurrentPath : 0;\n            ResizeImage();\n          }\n          else if( name == PREVIOUS_BUTTON_ID )\n          {\n            mCurrentPath = mCurrentPath - 1;\n            mCurrentPath = mCurrentPath >= 0 ? mCurrentPath : NUM_IMAGE_PATHS - 1;\n            ResizeImage();\n          }\n          break;\n        }\n        default:\n        {\n          break;\n        }\n      } \/\/ end switch\n    }\n\n    return false;\n  }\n\n  void OnPinch( Actor actor, const PinchGesture& pinch )\n  {\n    if( pinch.state == Gesture::Started )\n    {\n      mLastPinchScale = pinch.scale;\n    }\n    const float scale = pinch.scale;\n\n    if( ! Equals( scale, mLastPinchScale ) )\n    {\n      if ( scale < mLastPinchScale )\n      {\n        mImageStageScale.x = std::max( 0.05f, mImageStageScale.x * 0.9f );\n        mImageStageScale.y = std::max( 0.05f, mImageStageScale.y * 0.9f );\n      }\n      else\n      {\n        mImageStageScale.x = std::max( 0.05f, std::min( 1.0f, mImageStageScale.x * 1.1f ) );\n        mImageStageScale.y = std::max( 0.05f, std::min( 1.0f, mImageStageScale.y * 1.1f ) );\n      }\n      ResizeImage();\n    }\n    mLastPinchScale = scale;\n  }\n\n  void OnPan( Actor actor, const PanGesture& gesture )\n  {\n    Stage stage = Stage::GetCurrent();\n    \/\/ 1.0f and 0.75f are the maximum size caps of the resized image, as a factor of stage-size.\n    mImageStageScale.x = std::max( 0.05f, std::min( 0.95f,  mImageStageScale.x + ( gesture.displacement.x * 2.0f \/ stage.GetSize().width ) ) );\n    mImageStageScale.y = std::max( 0.05f, std::min( 0.70f, mImageStageScale.y + ( gesture.displacement.y * 2.0f \/ stage.GetSize().height ) ) );\n\n    ResizeImage();\n  }\n\n  void OnKeyEvent(const KeyEvent& event)\n  {\n    if( event.state == KeyEvent::Down )\n    {\n      if( IsKey( event, Dali::DALI_KEY_ESCAPE ) || IsKey( event, Dali::DALI_KEY_BACK ) )\n      {\n        if( mPopup && mPopup.IsVisible() )\n        {\n          mPopup.SetDisplayState( Toolkit::Popup::HIDDEN );\n          mPopup.Reset();\n        }\n        else\n        {\n          mApplication.Quit();\n        }\n      }\n      else if ( event.keyPressedName == \"Right\" )\n      {\n        mImageStageScale.x = std::max( 0.05f, std::min( 1.0f, mImageStageScale.x * 1.1f ) );\n      }\n      else if ( event.keyPressedName == \"Left\" )\n      {\n        mImageStageScale.x = std::max( 0.05f, mImageStageScale.x * 0.9f );\n      }\n      else if ( event.keyPressedName == \"Up\" )\n      {\n        mImageStageScale.y = std::max( 0.05f, std::min( 1.0f, mImageStageScale.y * 1.1f ) );\n      }\n      else if ( event.keyPressedName == \"Down\" )\n      {\n        mImageStageScale.y = std::max( 0.05f, mImageStageScale.y * 0.9f );\n      }\n      else if ( event.keyPressedName == \"o\" )\n      {\n        mImageStageScale.x = std::max( 0.05f, mImageStageScale.x * 0.9f );\n        mImageStageScale.y = std::max( 0.05f, mImageStageScale.y * 0.9f );\n      }\n      else if ( event.keyPressedName == \"p\" )\n      {\n        mImageStageScale.x = std::max( 0.05f, std::min( 1.0f, mImageStageScale.x * 1.1f ) );\n        mImageStageScale.y = std::max( 0.05f, std::min( 1.0f, mImageStageScale.y * 1.1f ) );\n      }\n      else if ( event.keyPressedName == \"n\" )\n      {\n        mCurrentPath = mCurrentPath + 1;\n        mCurrentPath = mCurrentPath <  NUM_IMAGE_PATHS ? mCurrentPath : 0;\n      }\n      else if ( event.keyPressedName == \"b\" )\n      {\n        mCurrentPath = mCurrentPath - 1;\n        mCurrentPath = mCurrentPath >= 0 ? mCurrentPath : NUM_IMAGE_PATHS - 1;\n      }\n      \/\/ Cycle filter and scaling modes:\n      else if ( event.keyPressedName == \"f\" )\n      {\n        mSamplingMode = NextFilterMode( mSamplingMode );\n        mSamplingModeButton.SetLabelText( StringFromFilterMode( mSamplingMode ) );\n      }\n      \/\/ Cycle filter and scaling modes:\n      else if ( event.keyPressedName == \"s\" )\n      {\n        mFittingMode = NextScalingMode( mFittingMode );\n        mFittingModeButton.SetLabelText( StringFromScalingMode( mFittingMode ) );\n      }\n      else\n      {\n        return;\n      }\n\n      ResizeImage();\n    }\n  }\n\nprivate:\n\n  void LoadImage()\n  {\n    mImageLoading = true;\n\n    const char * const path = IMAGE_PATHS[ mCurrentPath ];\n    Stage stage = Stage::GetCurrent();\n    Size imageSize = stage.GetSize() * mImageStageScale;\n    const ImageDimensions imageSizeInt = ImageDimensions::FromFloatArray( &imageSize.x );\n\n    ResourceImage image = ResourceImage::New( path, imageSizeInt, mFittingMode, mSamplingMode );\n\n    \/\/ If the image was cached, the load has already occured, bypass hooking the signal.\n    if( image.GetLoadingState() )\n    {\n      OnImageLoaded( image );\n    }\n    else\n    {\n      image.LoadingFinishedSignal().Connect( this, &ImageScalingAndFilteringController::OnImageLoaded );\n    }\n\n    mNextImage = image;\n  }\n\n  void ResizeImage()\n  {\n\n    Stage stage = Stage::GetCurrent();\n    Size imageSize = stage.GetSize() * mImageStageScale;\n\n    \/\/ If an image is already loading, queue another load when it has finished.\n    \/\/ This way we get continuous updates instead of constantly re-requesting loads.\n    if( mImageLoading )\n    {\n      mQueuedImageLoad = true;\n    }\n    else\n    {\n      LoadImage();\n    }\n\n    \/\/ Border size needs to be modified to take into account the width of the frame.\n    Vector2 borderScale( ( imageSize + Vector2( BORDER_WIDTH * 2.0f, BORDER_WIDTH * 2.0f ) ) \/ stage.GetSize() );\n    mDesiredBox.SetSize( stage.GetSize() * borderScale );\n\n    mHeightBox.SetSize( stage.GetSize().width, (stage.GetSize() * mImageStageScale).height );\n    mWidthBox.SetSize( (stage.GetSize() * mImageStageScale).width, stage.GetSize().height );\n  }\n\nprivate:\n  Application&  mApplication;\n  Toolkit::ImageView mDesiredBox; \/\/< Background rectangle to show requested image size.\n  Toolkit::ImageView mHeightBox;  \/\/< Background horizontal stripe to show requested image height.\n  Toolkit::ImageView mWidthBox;   \/\/< Background vertical stripe to show requested image width.\n  Toolkit::PushButton mFittingModeButton;\n  Toolkit::PushButton mSamplingModeButton;\n  Toolkit::Popup mPopup;\n  PinchGestureDetector mPinchDetector;\n  float mLastPinchScale;\n  Toolkit::ImageView mGrabCorner;\n  PanGestureDetector mPanGestureDetector;\n  Toolkit::ImageView mImageView;\n  ResourceImage mNextImage; \/\/< Currently-loading image\n  Vector2 mImageStageScale;\n  int mCurrentPath;\n  FittingMode::Type mFittingMode;\n  SamplingMode::Type mSamplingMode;\n  bool mImageLoading;\n  bool mQueuedImageLoad;\n\n};\n\nvoid RunTest( Application& application )\n{\n  ImageScalingAndFilteringController test( application );\n\n  application.MainLoop();\n}\n\n\/\/ Entry point for Linux & Tizen applications\nint DALI_EXPORT_API main( int argc, char **argv )\n{\n  Application application = Application::New( &argc, &argv, DEMO_THEME_PATH );\n\n  RunTest( application );\n\n  return 0;\n}\n","avg_line_length":36.703125,"max_line_length":411,"alphanum_fraction":0.6939477792,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1277,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":4.0,"content":"\n\n#include<iostream>\n#include<bits\/stdc++.h>\n#include<algorithm>\n#include<iomanip>\n#define ll long long\n#define mod 1000000007\nusing namespace std;\nconst int INF = 2e9 + 1;\n\n\/\/slow solution\nll get_ans(vector<ll>& hcost,ll i,ll j,ll val,ll m)\n{\n\t\/\/base case\n\tif(i==j)\n\t{\n\t\treturn val;\n\t}\n\n\tif(val <= m)\n\t{\n\t\treturn val;\n\t}\n\n\tll sa1=get_ans(hcost,i+1,j,val-hcost[i],m);\n\tll sa2=get_ans(hcost,i,j-1,val-hcost[j],m);\n\n\treturn max(sa1,sa2);\n\n}\n\n\nint main()\n{\n#ifndef ONLINE_JUDGE\n\tfreopen(\"input.txt\",\"r\",stdin);\n\tfreopen(\"output.txt\",\"w\",stdout);\n#endif\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n\nll n,m,ans=-1;\ncin>>n>>m;\n\nvector<ll> hcost(n,0);\n\nfor(ll i=0;i<n;i++)\n{\n\tcin>>hcost[i];\n}\n\n\n\/\/fast solution\nll fast,slow;\n\nll val=hcost[0];\n\nfast=slow=0;\n\nwhile( fast<n-1 || slow<n-1 )\n{\n\n\t\/\/one of the terminating cond\n\tif(val==m)\n\t{\n\t\tans=val;\n\t\tbreak;\n\t}\n\n\tif(val<m && fast<n-1)\n\t{\n\t\tfast++;\n\t\tval+=hcost[fast];\n\t\tif(val < m)\n\t\t{\n\t\t\tans=max(ans,val);\n\t\t}\n\t}\n\telse\n\tif(val>m && slow<fast)\n\t{\n\t\tval-=hcost[slow];\n\t\tslow++;\n\t\tif(val <= m)\n\t\t{\n\t\t\tans=max(ans,val);\n\t\t}\n\t}\n\telse\n\tif(val>m && slow==fast)\n\t{\n\t\tfast++;\n\t\tval+=hcost[fast];\n\t\tif(val <= m)\n\t\t{\n\t\t\tans=max(ans,val);\n\t\t}\t\t\n\t}\n\telse\n\tif(val<m && fast==n-1)\n\t{\n\t\tbreak;\n\t}\n\n\n}\n\ncout<<ans<<endl;\n\n\treturn 0;\n}\n","avg_line_length":11.201754386,"max_line_length":51,"alphanum_fraction":0.5771339076,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":132,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <iostream>\nusing namespace std;\n\nint main() {\n    for (int k=0; k<10; k++) {\n        cout<<k<<endl;\n    }\n\n    return 0;\n}\n","avg_line_length":12.0,"max_line_length":30,"alphanum_fraction":0.5075757576,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":22952,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"entity.hpp\"\r\n\r\n#include <cstdio>\r\n#include <string>\r\n#include <vector>\r\n\r\n#include \"character_def.hpp\"\r\n#include \"entities_items.hpp\"\r\n#include \"logger.h\"\r\n#include \"render_api.hpp\"\r\n#include \"rpc.hpp\"\r\n#include \"spawn_api.hpp\"\r\n#include \"state.hpp\"\r\n#include \"texture.hpp\"\r\n#include \"vtable_hook.hpp\"\r\n\r\nusing namespace std::chrono_literals;\r\nusing EntityMap = std::unordered_map<std::string, uint16_t>;\r\n\r\nstd::vector<EntityHooksInfo> g_entity_hooks;\r\n\r\nstruct EntityBucket\r\n{\r\n    void** begin;\r\n    void** current; \/\/ Note, counts down from end to begin instead of up from begin to end :shrug:\r\n    void** end;\r\n};\r\nstruct EntityPool\r\n{\r\n    std::uint32_t slot_size;\r\n    std::uint32_t initial_slots;\r\n    std::uint32_t slots_growth;\r\n    std::uint32_t current_slots;\r\n    std::uint64_t _ulong_0;\r\n    EntityBucket* _some_bucket;\r\n    EntityBucket* bucket;\r\n};\r\nstruct EntityFactory\r\n{\r\n    EntityDB types[0x395];\r\n    bool type_set[0x395];\r\n    std::unordered_map<std::uint32_t, OnHeapPointer<EntityPool>> entity_instance_map;\r\n    EntityMap entity_map;\r\n    void* _ptr_7;\r\n};\r\n\r\nEntityFactory* entity_factory()\r\n{\r\n    static EntityFactory* cache_entity_factory = *(EntityFactory**)get_address(\"entity_factory\"sv);\r\n    while (cache_entity_factory == 0)\r\n    {\r\n        std::this_thread::sleep_for(500ms);\r\n        cache_entity_factory = *(EntityFactory**)get_address(\"entity_factory\"sv);\r\n    }\r\n    return cache_entity_factory;\r\n}\r\n\r\nstd::vector<EntityItem> list_entities()\r\n{\r\n    const EntityFactory* entity_factory_ptr = entity_factory();\r\n    if (!entity_factory_ptr)\r\n        return {};\r\n\r\n    const EntityMap& map = entity_factory_ptr->entity_map;\r\n\r\n    std::vector<EntityItem> result;\r\n    for (const auto& [name, id] : map)\r\n    {\r\n        result.emplace_back(name, id);\r\n    }\r\n    return result;\r\n}\r\n\r\nEntityDB* get_type(uint32_t id)\r\n{\r\n    EntityFactory* entity_factory_ptr = entity_factory();\r\n\r\n    \/\/ Special case: map_ptr might be 0 if it's not initialized.\r\n    \/\/ This only occurs in list_entities; for others, do not check the pointer\r\n    \/\/ to see if this assumption works.\r\n    if (!entity_factory_ptr)\r\n        return nullptr;\r\n\r\n    return entity_factory_ptr->types + id;\r\n}\r\n\r\nENT_TYPE to_id(std::string_view name)\r\n{\r\n    const EntityFactory* entity_factory_ptr = entity_factory();\r\n    if (!entity_factory_ptr)\r\n        return {};\r\n    const EntityMap& map = entity_factory_ptr->entity_map;\r\n    auto it = map.find(std::string(name));\r\n    return it != map.end() ? it->second : -1;\r\n}\r\n\r\nvoid Entity::teleport(float dx, float dy, bool s, float vx, float vy, bool snap)\r\n{\r\n    if (overlay)\r\n        overlay->remove_item(uid);\r\n    overlay = NULL;\r\n    auto topmost = topmost_mount();\r\n    if (!s)\r\n    {\r\n        auto [x_pos, y_pos] = topmost->position();\r\n        \/\/ player relative coordinates\r\n        x_pos += dx;\r\n        y_pos += dy;\r\n        if (snap)\r\n        {\r\n            x_pos = round(x_pos);\r\n            y_pos = round(y_pos);\r\n        }\r\n        topmost->x = x_pos;\r\n        topmost->y = y_pos;\r\n    }\r\n    else\r\n    {\r\n        \/\/ screen coordinates -1..1\r\n        \/\/ log::debug!(\"Teleporting to screen {}, {}\", x, y);\r\n        auto state = State::get();\r\n        auto [x_pos, y_pos] = state.click_position(dx, dy);\r\n        if (snap && abs(vx) + abs(vy) <= 0.04f)\r\n        {\r\n            x_pos = round(x_pos);\r\n            y_pos = round(y_pos);\r\n        }\r\n        \/\/ log::debug!(\"Teleporting to {}, {}\", x, y);\r\n        topmost->x = x_pos;\r\n        topmost->y = y_pos;\r\n    }\r\n    \/\/ set velocity\r\n    if (topmost->is_movable())\r\n    {\r\n        auto movable_ent = (Movable*)topmost;\r\n        movable_ent->velocityx = vx;\r\n        movable_ent->velocityy = vy;\r\n    }\r\n    return;\r\n}\r\n\r\nvoid Entity::teleport_abs(float dx, float dy, float vx, float vy)\r\n{\r\n    if (overlay)\r\n        overlay->remove_item(uid);\r\n    overlay = NULL;\r\n    x = dx;\r\n    y = dy;\r\n    if (is_movable())\r\n    {\r\n        auto movable_ent = this->as<Movable>();\r\n        movable_ent->velocityx = vx;\r\n        movable_ent->velocityy = vy;\r\n    }\r\n}\r\n\r\nvoid Entity::set_layer(LAYER layer_to)\r\n{\r\n    uint8_t dest_layer = enum_to_layer(layer_to);\r\n    if (layer == dest_layer)\r\n        return;\r\n\r\n    auto state = State::get();\r\n    if (this != this->topmost_mount())\r\n        this->topmost_mount()->set_layer(layer_to);\r\n\r\n    if (layer == 0 || layer == 1)\r\n    {\r\n        auto ptr_from = state.ptr()->layers[layer];\r\n\r\n        using RemoveFromLayer = void(Layer*, Entity*);\r\n        static RemoveFromLayer* remove_from_layer = (RemoveFromLayer*)get_address(\"remove_from_layer\");\r\n        remove_from_layer(ptr_from, this);\r\n    }\r\n\r\n    auto ptr_to = state.ptr()->layers[dest_layer];\r\n\r\n    using AddToLayer = void(Layer*, Entity*);\r\n    static AddToLayer* add_to_layer = (AddToLayer*)get_address(\"add_to_layer\");\r\n    add_to_layer(ptr_to, this);\r\n\r\n    for (auto item : items)\r\n    {\r\n        item->set_layer(layer_to);\r\n    }\r\n}\r\n\r\nvoid Entity::remove()\r\n{\r\n    if (layer != 2)\r\n    {\r\n        auto state = State::get();\r\n        auto ptr_from = state.ptr()->layers[layer];\r\n        if ((this->type->search_flags & 1) == 0 || ((Player*)this)->ai != 0)\r\n        {\r\n            using RemoveFromLayer = void(Layer*, Entity*);\r\n            static RemoveFromLayer* remove_from_layer = (RemoveFromLayer*)get_address(\"remove_from_layer\");\r\n            remove_from_layer(ptr_from, this);\r\n\r\n            for (auto item : items)\r\n            {\r\n                item->remove();\r\n            }\r\n        }\r\n        layer = 2;\r\n    }\r\n}\r\n\r\nvoid Entity::respawn(LAYER layer_to)\r\n{\r\n    set_layer(layer_to);\r\n}\r\n\r\nvoid Entity::perform_teleport(uint8_t delta_x, uint8_t delta_y)\r\n{\r\n    using TeleportFun = void(Entity*, uint8_t, uint8_t);\r\n    static TeleportFun* tp = (TeleportFun*)get_address(\"teleport\");\r\n    tp(this, delta_x, delta_y);\r\n}\r\n\r\nstd::pair<float, float> Entity::position()\r\n{\r\n    auto [x_pos, y_pos] = position_self();\r\n\r\n    \/\/ overlay exists if player is riding something \/ etc\r\n    Entity* overlay_nested = overlay;\r\n    while (overlay_nested != nullptr)\r\n    {\r\n        x_pos += overlay_nested->x;\r\n        y_pos += overlay_nested->y;\r\n        overlay_nested = overlay_nested->overlay;\r\n    }\r\n    return {x_pos, y_pos};\r\n}\r\n\r\nstd::pair<float, float> Entity::position_self() const\r\n{\r\n    return std::pair<float, float>(x, y);\r\n}\r\n\r\nvoid Entity::remove_item(uint32_t item_uid)\r\n{\r\n    auto entity = get_entity_ptr(item_uid);\r\n    if (entity)\r\n        remove_item_ptr(entity);\r\n}\r\n\r\nvoid Player::set_jetpack_fuel(uint8_t fuel)\r\n{\r\n    static auto jetpackID = to_id(\"ENT_TYPE_ITEM_JETPACK\");\r\n    for (auto item : items)\r\n    {\r\n        if (item->type->id == jetpackID)\r\n        {\r\n            item->as<Jetpack>()->fuel = fuel;\r\n            break;\r\n        }\r\n    }\r\n}\r\n\r\nuint8_t Player::kapala_blood_amount()\r\n{\r\n    static auto kapalaPowerupID = to_id(\"ENT_TYPE_ITEM_POWERUP_KAPALA\");\r\n    for (auto item : items)\r\n    {\r\n        if (item->type->id == kapalaPowerupID)\r\n        {\r\n            return item->as<KapalaPowerup>()->amount_of_blood;\r\n        }\r\n    }\r\n    return 0;\r\n}\r\n\r\nvoid Movable::poison(int16_t frames)\r\n{\r\n    static size_t offset_first = 0;\r\n    static size_t offset_subsequent = 0;\r\n    if (offset_first == 0)\r\n    {\r\n        offset_first = get_address(\"first_poison_tick_timer_default\");\r\n        offset_subsequent = get_address(\"subsequent_poison_tick_timer_default\");\r\n    }\r\n    poison_tick_timer = frames;\r\n\r\n    if (frames == -1)\r\n    {\r\n        frames = 1800;\r\n    }\r\n    write_mem_prot(offset_first, frames, true);\r\n    write_mem_prot(offset_subsequent, frames, true);\r\n}\r\n\r\nbool Movable::is_poisoned()\r\n{\r\n    return (poison_tick_timer != -1);\r\n}\r\n\r\nvoid Movable::broken_damage(uint32_t damage_dealer_uid, int8_t damage_amount, uint16_t stun_time, float velocity_x, float velocity_y)\r\n{\r\n    damage(damage_dealer_uid, damage_amount, stun_time, velocity_x, velocity_y, 80);\r\n}\r\n\r\nvoid Movable::damage(uint32_t damage_dealer_uid, int8_t damage_amount, uint16_t stun_time, float velocity_x, float velocity_y, uint16_t iframes)\r\n{\r\n    if ((flags & (1 << 28)) > 0)\r\n    {\r\n        return;\r\n    }\r\n\r\n    auto dealer = get_entity_ptr(damage_dealer_uid);\r\n    if (dealer == nullptr)\r\n    {\r\n        return;\r\n    }\r\n\r\n    float velocities[] = {velocity_x, velocity_y};\r\n    float unknown[] = {0.0f, 0.0f};\r\n    on_regular_damage(dealer, damage_amount, 0x1000, velocities, unknown, stun_time, iframes);\r\n}\r\n\r\nbool Movable::is_button_pressed(BUTTON button)\r\n{\r\n    return (buttons & button) == button && (buttons_previous & button) == 0;\r\n}\r\nbool Movable::is_button_held(BUTTON button)\r\n{\r\n    return (buttons & button) == button && (buttons_previous & button) == button;\r\n}\r\nbool Movable::is_button_released(BUTTON button)\r\n{\r\n    return (buttons & button) == 0 && (buttons_previous & button) == button;\r\n}\r\n\r\nvoid hook_movable_state_machine(Movable* _self)\r\n{\r\n    hook_vtable<void(Movable*)>(\r\n        _self,\r\n        [](Movable* self, void (*original)(Movable*))\r\n        {\r\n            EntityHooksInfo& hook_info = self->get_hooks();\r\n\r\n            bool skip_orig = false;\r\n            for (auto& [id, pre] : hook_info.pre_statemachine)\r\n            {\r\n                if (pre(self))\r\n                {\r\n                    skip_orig = true;\r\n                }\r\n            }\r\n\r\n            if (!skip_orig)\r\n            {\r\n                original(self);\r\n            }\r\n\r\n            for (auto& [id, post] : hook_info.post_statemachine)\r\n            {\r\n                post(self);\r\n            }\r\n        },\r\n        0x2);\r\n}\r\nvoid Movable::set_pre_statemachine(std::uint32_t reserved_callback_id, std::function<bool(Movable*)> pre_state_machine)\r\n{\r\n    EntityHooksInfo& hook_info = get_hooks();\r\n    if (hook_info.pre_statemachine.empty() && hook_info.post_statemachine.empty())\r\n    {\r\n        hook_movable_state_machine(this);\r\n    }\r\n    hook_info.pre_statemachine.push_back({reserved_callback_id, std::move(pre_state_machine)});\r\n}\r\nvoid Movable::set_post_statemachine(std::uint32_t reserved_callback_id, std::function<void(Movable*)> post_state_machine)\r\n{\r\n    EntityHooksInfo& hook_info = get_hooks();\r\n    if (hook_info.pre_statemachine.empty() && hook_info.post_statemachine.empty())\r\n    {\r\n        hook_movable_state_machine(this);\r\n    }\r\n    hook_info.post_statemachine.push_back({reserved_callback_id, std::move(post_state_machine)});\r\n}\r\n\r\nstd::tuple<float, float, uint8_t> get_position(uint32_t uid)\r\n{\r\n    Entity* ent = get_entity_ptr(uid);\r\n    if (ent)\r\n        return std::make_tuple(ent->position().first, ent->position().second, ent->layer);\r\n\r\n    return {0.0f, 0.0f, (uint8_t)0};\r\n}\r\n\r\nstd::tuple<float, float, uint8_t> get_render_position(uint32_t uid)\r\n{\r\n    Entity* ent = get_entity_ptr(uid);\r\n    if (ent)\r\n    {\r\n        if (ent->rendering_info != nullptr && !ent->rendering_info->stop_render)\r\n            return std::make_tuple(ent->rendering_info->x, ent->rendering_info->y, ent->layer);\r\n        else\r\n            return get_position(uid);\r\n    }\r\n    return {0.0f, 0.0f, (uint8_t)0};\r\n}\r\n\r\nstd::tuple<float, float> get_velocity(uint32_t uid)\r\n{\r\n    if (Entity* ent = get_entity_ptr(uid))\r\n    {\r\n        float vx{0.0f};\r\n        float vy{0.0f};\r\n        if (ent->is_movable())\r\n        {\r\n            Movable* mov = ent->as<Movable>();\r\n            vx = mov->velocityx;\r\n            vy = mov->velocityy;\r\n        }\r\n        else if (ent->is_liquid())\r\n        {\r\n            auto liquid_engine = State::get().get_correct_liquid_engine(ent->type->id);\r\n            vx = liquid_engine->entity_velocities->first;\r\n            vy = liquid_engine->entity_velocities->second;\r\n        }\r\n        if (ent->overlay)\r\n        {\r\n            auto [ovx, ovy] = get_velocity(ent->overlay->uid);\r\n            vx += ovx;\r\n            vy += ovy;\r\n        }\r\n        return std::tuple{vx, vy};\r\n    }\r\n    return std::tuple{0.0f, 0.0f};\r\n}\r\n\r\nAABB get_hitbox(uint32_t uid, bool use_render_pos)\r\n{\r\n    if (Entity* ent = get_entity_ptr(uid))\r\n    {\r\n        auto [x, y, l] = (use_render_pos ? get_render_position : get_position)(uid);\r\n        return AABB{\r\n            x - ent->hitboxx + ent->offsetx,\r\n            y + ent->hitboxy + ent->offsety,\r\n            x + ent->hitboxx + ent->offsetx,\r\n            y - ent->hitboxy + ent->offsety,\r\n        };\r\n    }\r\n    return AABB{0.0f, 0.0f, 0.0f, 0.0f};\r\n}\r\n\r\nTEXTURE Entity::get_texture()\r\n{\r\n    return texture->id;\r\n}\r\nbool Entity::set_texture(TEXTURE texture_id)\r\n{\r\n    if (auto* new_texture = RenderAPI::get().get_texture(texture_id))\r\n    {\r\n        apply_texture(new_texture);\r\n        return true;\r\n    }\r\n    return false;\r\n}\r\n\r\nvoid Entity::unhook(std::uint32_t id)\r\n{\r\n    auto it = std::find_if(g_entity_hooks.begin(), g_entity_hooks.end(), [this](auto& hook)\r\n                           { return hook.entity == this; });\r\n    if (it != g_entity_hooks.end())\r\n    {\r\n        std::erase_if(it->on_dtor, [id](auto& hook)\r\n                      { return hook.id == id; });\r\n        std::erase_if(it->on_destroy, [id](auto& hook)\r\n                      { return hook.id == id; });\r\n        std::erase_if(it->on_kill, [id](auto& hook)\r\n                      { return hook.id == id; });\r\n        std::erase_if(it->on_player_instagib, [id](auto& hook)\r\n                      { return hook.id == id; });\r\n        std::erase_if(it->on_damage, [id](auto& hook)\r\n                      { return hook.id == id; });\r\n        std::erase_if(it->pre_statemachine, [id](auto& hook)\r\n                      { return hook.id == id; });\r\n        std::erase_if(it->post_statemachine, [id](auto& hook)\r\n                      { return hook.id == id; });\r\n        std::erase_if(it->on_open, [id](auto& hook)\r\n                      { return hook.id == id; });\r\n        std::erase_if(it->pre_collision1, [id](auto& hook)\r\n                      { return hook.id == id; });\r\n        std::erase_if(it->pre_collision2, [id](auto& hook)\r\n                      { return hook.id == id; });\r\n    }\r\n}\r\nEntityHooksInfo& Entity::get_hooks()\r\n{\r\n    auto it = std::find_if(g_entity_hooks.begin(), g_entity_hooks.end(), [this](auto& hook)\r\n                           { return hook.entity == this; });\r\n    if (it == g_entity_hooks.end())\r\n    {\r\n        hook_dtor(this, [](void* self)\r\n                  {\r\n                      auto _it = std::find_if(g_entity_hooks.begin(), g_entity_hooks.end(), [self](auto& hook)\r\n                                              { return hook.entity == self; });\r\n                      if (_it != g_entity_hooks.end())\r\n                      {\r\n                          for (auto& cb : _it->on_dtor)\r\n                          {\r\n                              cb.fun((Entity*)self);\r\n                          }\r\n                          g_entity_hooks.erase(_it);\r\n                      }\r\n                  });\r\n        g_entity_hooks.push_back({this});\r\n        return g_entity_hooks.back();\r\n    }\r\n    return *it;\r\n}\r\n\r\nstd::uint32_t Entity::set_on_dtor(std::function<void(Entity*)> cb)\r\n{\r\n    EntityHooksInfo& hook_info = get_hooks();\r\n    hook_info.on_dtor.push_back({hook_info.cbcount++, std::move(cb)});\r\n    return hook_info.on_dtor.back().id;\r\n}\r\nstd::uint32_t Entity::reserve_callback_id()\r\n{\r\n    EntityHooksInfo& hook_info = get_hooks();\r\n    return hook_info.cbcount++;\r\n}\r\nvoid Entity::set_on_destroy(std::uint32_t reserved_callback_id, std::function<void(Entity*)> on_destroy)\r\n{\r\n    EntityHooksInfo& hook_info = get_hooks();\r\n    if (hook_info.on_destroy.empty())\r\n    {\r\n        hook_vtable<void(Entity*)>(\r\n            this,\r\n            [](Entity* self, void (*original)(Entity*))\r\n            {\r\n                EntityHooksInfo& _hook_info = self->get_hooks();\r\n                for (auto& [id, on_destroy] : _hook_info.on_destroy)\r\n                {\r\n                    on_destroy(self);\r\n                }\r\n                original(self);\r\n            },\r\n            0x5);\r\n    }\r\n    hook_info.on_destroy.push_back({reserved_callback_id, std::move(on_destroy)});\r\n}\r\nvoid Entity::set_on_kill(std::uint32_t reserved_callback_id, std::function<void(Entity*, Entity*)> on_kill)\r\n{\r\n    EntityHooksInfo& hook_info = get_hooks();\r\n    if (hook_info.on_kill.empty())\r\n    {\r\n        hook_vtable<void(Entity*, bool, Entity*)>(\r\n            this,\r\n            [](Entity* self, bool _some_bool, Entity* from, void (*original)(Entity*, bool, Entity*))\r\n            {\r\n                EntityHooksInfo& _hook_info = self->get_hooks();\r\n                for (auto& [id, on_kill] : _hook_info.on_kill)\r\n                {\r\n                    on_kill(self, from);\r\n                }\r\n                original(self, _some_bool, from);\r\n            },\r\n            0x3);\r\n    }\r\n    hook_info.on_kill.push_back({reserved_callback_id, std::move(on_kill)});\r\n}\r\n\r\nvoid Entity::set_on_player_instagib(std::uint32_t reserved_callback_id, std::function<bool(Entity*)> on_instagib)\r\n{\r\n    EntityHooksInfo& hook_info = get_hooks();\r\n    \/\/ no hooking here, because the instagib function is hooked in rpc.cpp\r\n    hook_info.on_player_instagib.push_back({reserved_callback_id, std::move(on_instagib)});\r\n}\r\n\r\nvoid Entity::set_on_damage(std::uint32_t reserved_callback_id, std::function<bool(Entity*, Entity*, int8_t, float, float, uint16_t, uint8_t)> on_damage)\r\n{\r\n    EntityHooksInfo& hook_info = get_hooks();\r\n    if (hook_info.on_damage.empty())\r\n    {\r\n        if ((this->type->search_flags & 0x1) == 0x1)\r\n        {\r\n            \/\/ Can't hook player::on_damage here, because this is permanently hooked for the god function.\r\n            \/\/ The god function takes care of calling the script hooks in rpc.cpp\r\n        }\r\n        else\r\n        {\r\n            hook_vtable<void(Entity*, Entity*, int8_t, uint32_t, float*, float*, uint16_t, uint8_t)>(\r\n                this,\r\n                [](Entity* self, Entity* damage_dealer, int8_t damage_amount, uint32_t unknown1, float* velocities, float* unknown2, uint16_t stun_amount, uint8_t iframes, void (*original)(Entity*, Entity*, int8_t, uint32_t, float*, float*, uint16_t, uint8_t))\r\n                {\r\n                    EntityHooksInfo& _hook_info = self->get_hooks();\r\n                    bool skip_orig = false;\r\n                    for (auto& [id, on_damage] : _hook_info.on_damage)\r\n                    {\r\n                        if (on_damage(self, damage_dealer, damage_amount, velocities[0], velocities[1], stun_amount, iframes))\r\n                        {\r\n                            skip_orig = true;\r\n                        }\r\n                    }\r\n\r\n                    if (!skip_orig)\r\n                    {\r\n                        original(self, damage_dealer, damage_amount, unknown1, velocities, unknown2, stun_amount, iframes);\r\n                    }\r\n                },\r\n                0x30);\r\n        }\r\n    }\r\n    hook_info.on_damage.push_back({reserved_callback_id, std::move(on_damage)});\r\n}\r\n\r\nbool Entity::is_movable()\r\n{\r\n    static const ENT_TYPE first_logical = to_id(\"ENT_TYPE_LOGICAL_CONSTELLATION\");\r\n    if (type->search_flags & 0b11111111) \/\/ PLAYER | MOUNT | MONSTER | ITEM | ROPE | EXPLOSION | FX | ACTIVEFLOOR\r\n        return true;\r\n    else if (type->search_flags & 0x1000) \/\/ LOGICAL - as it has some movable entities\r\n        if (type->id < first_logical)     \/\/ actually check if it's not logical\r\n            return true;\r\n\r\n    return false;\r\n}\r\n\r\nbool Entity::is_liquid()\r\n{\r\n    static const ENT_TYPE liquid_water = to_id(\"ENT_TYPE_LIQUID_WATER\");\r\n    static const ENT_TYPE liquid_coarse_water = to_id(\"ENT_TYPE_LIQUID_COARSE_WATER\");\r\n    static const ENT_TYPE liquid_lava = to_id(\"ENT_TYPE_LIQUID_LAVA\");\r\n    static const ENT_TYPE liquid_stagnant_lava = to_id(\"ENT_TYPE_LIQUID_STAGNANT_LAVA\");\r\n    static const ENT_TYPE liquid_coarse_lava = to_id(\"ENT_TYPE_LIQUID_COARSE_LAVA\");\r\n\r\n    if (type->id == liquid_water || type->id == liquid_coarse_water || type->id == liquid_lava || type->id == liquid_stagnant_lava || type->id == liquid_coarse_lava)\r\n        return true;\r\n\r\n    return false;\r\n}\r\n\r\nvoid Container::set_on_open(std::uint32_t reserved_callback_id, std::function<void(Container*, Movable*)> on_open)\r\n{\r\n    EntityHooksInfo& hook_info = get_hooks();\r\n    if (hook_info.on_open.empty())\r\n    {\r\n        hook_vtable<void(Container*, Movable*)>(\r\n            this,\r\n            [](Container* self, Movable* opener, void (*original)(Container*, Movable*))\r\n            {\r\n                if (opener->movey > 0)\r\n                {\r\n                    EntityHooksInfo& _hook_info = self->get_hooks();\r\n                    for (auto& [id, on_open] : _hook_info.on_open)\r\n                    {\r\n                        on_open(self, opener);\r\n                    }\r\n                }\r\n                original(self, opener);\r\n            },\r\n            0x18);\r\n    }\r\n    hook_info.on_open.push_back({reserved_callback_id, std::move(on_open)});\r\n}\r\n\r\nvoid Entity::set_pre_collision1(std::uint32_t reserved_callback_id, std::function<bool(Entity*, Entity*)> pre_collision1)\r\n{\r\n    EntityHooksInfo& hook_info = get_hooks();\r\n    if (hook_info.pre_collision1.empty())\r\n    {\r\n        hook_vtable<void(Entity*, Entity*)>(\r\n            this,\r\n            [](Entity* self, Entity* collision_entity, void (*original)(Entity*, Entity*))\r\n            {\r\n                EntityHooksInfo& _hook_info = self->get_hooks();\r\n\r\n                bool skip_orig = false;\r\n                for (auto& [id, pre] : _hook_info.pre_collision1)\r\n                {\r\n                    if (pre(self, collision_entity))\r\n                    {\r\n                        skip_orig = true;\r\n                    }\r\n                }\r\n\r\n                if (!skip_orig)\r\n                {\r\n                    original(self, collision_entity);\r\n                }\r\n            },\r\n            0x4);\r\n    }\r\n    hook_info.pre_collision1.push_back({reserved_callback_id, std::move(pre_collision1)});\r\n}\r\n\r\nvoid Entity::set_pre_collision2(std::uint32_t reserved_callback_id, std::function<bool(Entity*, Entity*)> pre_collision2)\r\n{\r\n    EntityHooksInfo& hook_info = get_hooks();\r\n    if (hook_info.pre_collision2.empty())\r\n    {\r\n        hook_vtable<void(Entity*, Entity*)>(\r\n            this,\r\n            [](Entity* self, Entity* collision_entity, void (*original)(Entity*, Entity*))\r\n            {\r\n                EntityHooksInfo& _hook_info = self->get_hooks();\r\n\r\n                bool skip_orig = false;\r\n                for (auto& [id, pre] : _hook_info.pre_collision2)\r\n                {\r\n                    if (pre(self, collision_entity))\r\n                    {\r\n                        skip_orig = true;\r\n                    }\r\n                }\r\n\r\n                if (!skip_orig)\r\n                {\r\n                    original(self, collision_entity);\r\n                }\r\n            },\r\n            0x1A);\r\n    }\r\n    hook_info.pre_collision2.push_back({reserved_callback_id, std::move(pre_collision2)});\r\n}\r\n","avg_line_length":31.8777777778,"max_line_length":261,"alphanum_fraction":0.5638724294,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2018,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":45.0,"content":"#include <stdio.h>\n#include <string.h>\n\n#include \"WifiScanner.hpp\"\n#include \"icon_maps.h\"\n#include \"menu_semaphore.h\"\n#include \"wifi_func.hpp\"\n\n\/\/static const char *TAG = \"wifi-ap-scan\";\n\nvoid wifi_ApScan(void *arg) {\n    drawHeader(search_icon16x16, (char *)arg);\n\n    WifiScanner wifiScaner(false, 200);\n    if (!wifiScaner.open()) return;\n    while (true) {\n        wifiScaner.startScanner();\n        while (!wifiScaner.isScanDone()) {\n            blink(1);\n            vTaskDelay(100 \/ portTICK_RATE_MS);\n        }\n        WifiScanner::statistics_t s;\n        wifiScaner.getStatistics(&s);\n\n        scr_printf(1, 16 * 1, SCR_INFO_COLOR, \"%d AP: %d\/%d    \", s.count, s.ap_num, s.strong_ap_num);\n        if (s.auth_wep_num != 0 || s.auth_open_num != 0) {\n            scr_printf(1, 16 * 2, ST7735_Green, ST7735_Black, \"WEP:%2d OPEN:%2d  \", s.auth_wep_num, s.auth_open_num);\n        }\n        for (int i = 0; i < WifiScanner::SORT_LIST_SIZE; i++) {\n            if (s.sort_ssid_count[i] != 0)\n                scr_printf(1, 16 * (3 + i), SCR_DUMP_COLOR, \"%1d %s                \", s.sort_ssid_count[i], s.sort_ssid[i]);\n        }\n        if (getKeyPressed(500 \/ portTICK_RATE_MS) == GPIO_KEY_CANCEL) {\n            wifiScaner.haltScanner();\n            break;\n        }\n    }\n    \/\/-----------\n    FILE *f = fopen(FNAME_SCAN_AP_RESULT_JSON, \"w\");\n    if (f == NULL) {\n        scr_error(\"Failed to open file \" FNAME_SCAN_AP_RESULT_JSON \" for writing\");\n        return;\n    }\n    fputs(wifiScaner.getJson().c_str(), f);\n    fclose(f);\n    \/\/-----------\n    f = fopen(FNAME_SCAN_AP_RESULT_TXT, \"w\");\n    if (f == NULL) {\n        scr_error(\"Failed to open file \" FNAME_SCAN_AP_RESULT_TXT \" for writing\");\n        return;\n    }\n    std::vector<std::string> list = wifiScaner.getApList();\n    for (auto it = list.begin(); it != list.end(); it++) {\n        if (it != list.begin()) fputc('\\n', f);\n        fputs(it->c_str(), f);\n    }\n    fclose(f);\n    \/\/-----------\n    xSemaphoreGive(menu_semaphore);\n    vTaskDelete(NULL);\n}\n\n","avg_line_length":32.0317460317,"max_line_length":124,"alphanum_fraction":0.5629335976,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":231,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include <include\/common.h>\n\n#define greater(a, b, type) *(type*)a > *(type*)b\n\nint cmpint(const void *a, const void *b){\n\treturn greater(a, b, int);\n}\n\nint cmpdouble(const void *a, const void *b){\n\treturn greater(a, b, double);\n}\n","avg_line_length":19.25,"max_line_length":49,"alphanum_fraction":0.6493506494,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1723,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/**\n * \\file XLETemplatesParserTest.cpp\n *\n * \\brief Provide a parser for XLE TEMPLATES files based on XLETemplatesParserTest.cpp\n *\n * The purpose of this parser is to test the implementation of the BNF\n * grammar for XLE TEMPLATES and the resulting parser class generated by BNFC.\n *\n * \\author Damir Cavar &lt;dcavar@iu.edu&gt;\n *\n * \\version 0.1\n *\n * \\date 2016\/10\/25 01:53:00\n *\n * \\date Created on: Tue Oct 25 01:55:00 2016\n *\n * \\copyright Copyright 2016 by Damir Cavar\n *\n * \\license{Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.}\n *\n * \\see XLETemplatesParser\n *\n * \\note This code should be considered final.\n *\n * \\bug None\n *\/\n\n\n#include <fstream>\n#include <string>\n#include <stdio.h>\n\n#include \"XLETemplatesParser.h\"\n\n\nusing namespace xletemp;\n\n\nint main(int argc, char ** argv) {\n\n    if (argc > 1) {\n        std::ifstream ifs(argv[1]);\n        std::string content((std::istreambuf_iterator<char>(ifs)),\n                            (std::istreambuf_iterator<char>()));\n\n        \/\/XLETemplatesParser *p = new XLETemplatesParser();\n\n        \/\/ set the verbose level of the grammar parser\n        \/\/p->verbose = true;\n\n        \/\/p->getTemplates(content.c_str());\n        \/\/delete (p);\n    }\n  return 1;\n}\n\n","avg_line_length":25.7164179104,"max_line_length":86,"alphanum_fraction":0.6732443413,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5916,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":10.0,"content":"#include <ros\/ros.h>\n#include \"trial.h\"\n#include <std_msgs\/Float64MultiArray.h>\n#include <std_msgs\/Float64.h>\n#include <sysexits.h>\n#include <iostream>\n#include <fstream>\n#include <thread>\n#include \"read_para_bayes.h\"\n\nusing namespace std;\n\nclass RunTrial{\npublic:\n    RunTrial(ros::NodeHandle& nh){\n        nh_ = nh;\n        pub_cost_ =  nh.advertise<std_msgs::Float64>(\"cost\",10);\n        pub_state_his_ =  nh.advertise<std_msgs::Float64MultiArray>(\"stateHis\",10);\n        rb_ = ReadParaBayes(nh_);\n    }\n    void ProcessNoiseCallback(const std_msgs::Float64MultiArray::ConstPtr& msg){\n        std::cout<<\"get the noise.....................\"<<std::endl;\n\n        \/\/if true, we'll show the information of the parameters we read from yaml\n        bool show_read_info = true;\n        ReadParaVehicle rv_gt(nh_, !show_read_info);\n        ReadParaVehicle rv(nh_,!show_read_info);\n\n        int npn = msg->layout.dim[0].size; \/\/this is how many numbers that the process noise contain\n\n        \/\/msg->data is vector<double>, the first npn number is about process noise the rest is about measurement noise\n        std::vector<double> pn(msg->data.begin(), msg->data.begin()+npn);\n        std::vector<double> on(msg->data.begin()+npn, msg->data.end());\n\n        \/\/replace the estimator's process noise and observation noise by the data from bayesopt\n        rv.pnoise_ = pn;\n        rv.onoise_ = on;\n\n        std::cout<<\"process noise \";\n        for(double np: rv.pnoise_){\n            std::cout<<np<<\" \";\n        }\n        std::cout<<std::endl;\n        \n        std::cout<<\"observation noise \"<<rv.onoise_[0]<<std::endl;\n\n        std_msgs::Float64 cost;\n\n        int it_num = 2;\n        std::vector<double> pic_max(it_num,0.0);\n        \n        for(int k = 0; k<it_num; k++){\n            \/\/create thread and object array\n            std::vector<std::thread> th;\n            std::vector<Trial> t;\n\n            for(int i = 0; i<rv_gt.cpu_core_number_; i++)\n                t.push_back(Trial(rv_gt,rv));   \n\n\n            \/\/be careful we cannot put t.push_back into the same loop as th.push_back. When we create thread, they are hoped to be created continiously\n            for(int i = 0; i<rv_gt.cpu_core_number_; i++)\n                th.push_back(std::thread(&Trial::Run, &t[i])); \n\n            \/\/joint the thread\n            for(int i = 0; i<rv_gt.cpu_core_number_; i++) \n                th[i].join();\n\n            \n            if(rv.cost_choice_ == \"JNEES\" || rv.cost_choice_ == \"CNEES\"){\n                double average_nees = 0.0;\n                double average_var_nees = 0.0;\n                for(int i = 0; i<rv_gt.cpu_core_number_; i++){\n                    average_nees += t[i].get_average_nees()\/rv_gt.cpu_core_number_;\n                    average_var_nees += t[i].get_average_var_nees()\/rv_gt.cpu_core_number_;\n                }\n                double tmp_J_NEES  = std::abs(log(average_nees\/rv.state_dof_));\n                double tmp_NEES_var = std::abs(log(0.5*average_var_nees\/rv.state_dof_));\n                double J_NEES = tmp_J_NEES;\n                if(rv.cost_choice_ == \"CNEES\"){\n                    J_NEES += tmp_NEES_var;\n                }\n                pic_max[k] = J_NEES;\n                std::cout<<\"cost JNEES \"<<J_NEES<<std::endl;\n            }\n            else if(rv.cost_choice_ == \"JNIS\" || rv.cost_choice_ == \"CNIS\"){\n                double average_nis = 0.0;\n                double average_var_nis = 0.0;\n                for(int i = 0; i<rv_gt.cpu_core_number_; i++){\n                    average_nis += t[i].get_average_nis()\/rv_gt.cpu_core_number_;\n                    average_var_nis += t[i].get_average_var_nis()\/rv_gt.cpu_core_number_;\n                }\n                double tmp_J_NIS = std::abs(log(average_nis\/rv.observation_dof_));\n                double tmp_NIS_var = std::abs(log(0.5*average_var_nis\/rv.observation_dof_));\n                double J_NIS = tmp_J_NIS;\n                if(rv.cost_choice_ == \"CNIS\")\n                    J_NIS += tmp_NIS_var;\n\n                pic_max[k] = J_NIS;\n                std::cout<<\"cost JNIS \"<<J_NIS<<std::endl;\n                std::cout<<\"variance log value is \"<<tmp_NIS_var<<std::endl;\n            }\n\n            \/\/both choices should work\n            rv.dt_ = 1.0;\n            rv_gt.dt_ = 1.0;\n            rv.t_end_ = 201;\n            rv_gt.t_end_ = 201;\n            \/\/ rv.dt_ = 0.5;\n            \/\/ rv_gt.dt_ = 0.5;\n            \/\/ rv.t_end_ = 105.5;\n            \/\/ rv_gt.t_end_ = 105.5;\n            rv.max_iterations_ = (rv.t_end_- rv.t_start_)\/rv.dt_;\n            rv_gt.max_iterations_ = (rv_gt.t_end_ - rv_gt.t_start_)\/rv_gt.dt_;\n        }\n\n        std::cout<<pic_max[0]<<\",\"<<pic_max[1]<<std::endl;\n        double max_cost = *max_element(pic_max.begin(), pic_max.end());\n        int index_max = max_element(pic_max.begin(), pic_max.end()) - pic_max.begin();\n\n        it_count_++;\n        if(it_count_> rb_.n_init_samples_){\n            (index_max==1)?(dt1_count_++):(dt0_count_++);\n            std::cout<<\"it count \"<<it_count_-rb_.n_init_samples_<<\",\"<<dt0_count_<<\",\"<<dt1_count_<<std::endl;\n            std::cout<<\"freq of index0 and index1 \"<<(float)dt0_count_\/(float)(it_count_-rb_.n_init_samples_)<<\",\"<<(float)dt1_count_\/(float)(it_count_-rb_.n_init_samples_)<<std::endl;\n        }\n        cost.data = max_cost;\n\n        pub_cost_.publish(cost);\n        \n        std::cout<<\"publish the cost.....................\\n \\n\"<<std::endl;\n    }\n\nprivate:\n    ros::NodeHandle nh_;\n    double J_NEES,J_NIS;\n    ros::Publisher pub_cost_;\n    ros::Publisher pub_state_his_;\n    ros::Subscriber sub_noise_;\n    int it_count_ = 0, dt0_count_ = 0, dt1_count_ = 0;\n    ReadParaBayes rb_;\n};\n\nint main(int nargs, char *args[])\n{\n    ros::init(nargs,args,\"robot_1d_kf\");\n\n    ros::NodeHandle n;\n\n    RunTrial rT(n);\n\n    ros::Subscriber sub = n.subscribe(\"noise\",10, &RunTrial::ProcessNoiseCallback, &rT);\n\n    ros::spin();\n    \n    return EX_OK;\n}","avg_line_length":37.6815286624,"max_line_length":184,"alphanum_fraction":0.5627112914,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2634,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":1.0,"content":"#include \"osrm\/match_parameters.hpp\"\n#include \"osrm\/nearest_parameters.hpp\"\n#include \"osrm\/route_parameters.hpp\"\n#include \"osrm\/table_parameters.hpp\"\n#include \"osrm\/trip_parameters.hpp\"\n\n#include \"osrm\/coordinate.hpp\"\n#include \"osrm\/engine_config.hpp\"\n#include \"osrm\/json_container.hpp\"\n\n#include \"osrm\/osrm.hpp\"\n#include \"osrm\/status.hpp\"\n\n#include <exception>\n#include <iostream>\n#include <string>\n#include <utility>\n\n#include <cstdlib>\n\nint main(int argc, const char *argv[])\n{\n    if (argc < 2)\n    {\n        std::cerr << \"Usage: \" << argv[0] << \" data.osrm\\n\";\n        return EXIT_FAILURE;\n    }\n\n    using namespace osrm;\n\n    \/\/ Configure based on a .osrm base path, and no datasets in shared mem from osrm-datastore\n    EngineConfig config;\n    config.storage_config = {argv[1]};\n    config.use_shared_memory = false;\n\n    \/\/ Routing machine with several services (such as Route, Table, Nearest, Trip, Match)\n    const OSRM osrm{config};\n\n    \/\/ The following shows how to use the Route service; configure this service\n    RouteParameters params;\n\n    \/\/ Route in monaco\n    params.coordinates.push_back({util::FloatLongitude{7.419758}, util::FloatLatitude{43.731142}});\n    params.coordinates.push_back({util::FloatLongitude{7.419505}, util::FloatLatitude{43.736825}});\n\n    \/\/ Response is in JSON format\n    json::Object result;\n\n    \/\/ Execute routing request, this does the heavy lifting\n    const auto status = osrm.Route(params, result);\n\n    if (status == Status::Ok)\n    {\n        auto &routes = result.values[\"routes\"].get<json::Array>();\n\n        \/\/ Let's just use the first route\n        auto &route = routes.values.at(0).get<json::Object>();\n        const auto distance = route.values[\"distance\"].get<json::Number>().value;\n        const auto duration = route.values[\"duration\"].get<json::Number>().value;\n\n        \/\/ Warn users if extract does not contain the default Berlin coordinates from above\n        if (distance == 0 or duration == 0)\n        {\n            std::cout << \"Note: distance or duration is zero. \";\n            std::cout << \"You are probably doing a query outside of the OSM extract.\\n\\n\";\n        }\n\n        std::cout << \"Distance: \" << distance << \" meter\\n\";\n        std::cout << \"Duration: \" << duration << \" seconds\\n\";\n        return EXIT_SUCCESS;\n    }\n    else if (status == Status::Error)\n    {\n        const auto code = result.values[\"code\"].get<json::String>().value;\n        const auto message = result.values[\"message\"].get<json::String>().value;\n\n        std::cout << \"Code: \" << code << \"\\n\";\n        std::cout << \"Message: \" << code << \"\\n\";\n        return EXIT_FAILURE;\n    }\n}\n","avg_line_length":32.1219512195,"max_line_length":99,"alphanum_fraction":0.6397114655,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2553,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n * Copyright (C) 2011 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#define LOG_TAG \"InputWindow\"\n#define LOG_NDEBUG 0\n\n#include \"InputWindow.h\"\n\n#include <log\/log.h>\n\n#include <ui\/Rect.h>\n#include <ui\/Region.h>\n\nnamespace android {\n\n\/\/ --- InputWindowInfo ---\nvoid InputWindowInfo::addTouchableRegion(const Rect& region) {\n    touchableRegion.orSelf(region);\n}\n\nbool InputWindowInfo::touchableRegionContainsPoint(int32_t x, int32_t y) const {\n    return touchableRegion.contains(x,y);\n}\n\nbool InputWindowInfo::frameContainsPoint(int32_t x, int32_t y) const {\n    return x >= frameLeft && x < frameRight\n            && y >= frameTop && y < frameBottom;\n}\n\nbool InputWindowInfo::isTrustedOverlay() const {\n    return layoutParamsType == TYPE_INPUT_METHOD\n            || layoutParamsType == TYPE_INPUT_METHOD_DIALOG\n            || layoutParamsType == TYPE_MAGNIFICATION_OVERLAY\n            || layoutParamsType == TYPE_STATUS_BAR\n            || layoutParamsType == TYPE_NAVIGATION_BAR\n            || layoutParamsType == TYPE_NAVIGATION_BAR_PANEL\n            || layoutParamsType == TYPE_SECURE_SYSTEM_OVERLAY\n            || layoutParamsType == TYPE_DOCK_DIVIDER\n            || layoutParamsType == TYPE_ACCESSIBILITY_OVERLAY\n            || layoutParamsType == TYPE_INPUT_CONSUMER;\n}\n\nbool InputWindowInfo::supportsSplitTouch() const {\n    return layoutParamsFlags & FLAG_SPLIT_TOUCH;\n}\n\nbool InputWindowInfo::overlaps(const InputWindowInfo* other) const {\n    return frameLeft < other->frameRight && frameRight > other->frameLeft\n            && frameTop < other->frameBottom && frameBottom > other->frameTop;\n}\n\n\n\/\/ --- InputWindowHandle ---\n\nInputWindowHandle::InputWindowHandle(const sp<InputApplicationHandle>& inputApplicationHandle) :\n    inputApplicationHandle(inputApplicationHandle), mInfo(NULL) {\n}\n\nInputWindowHandle::~InputWindowHandle() {\n    delete mInfo;\n}\n\nvoid InputWindowHandle::releaseInfo() {\n    if (mInfo) {\n        delete mInfo;\n        mInfo = NULL;\n    }\n}\n\n} \/\/ namespace android\n","avg_line_length":30.3928571429,"max_line_length":96,"alphanum_fraction":0.7093615354,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":782,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Zlib"],"max_stars_count":1.0,"content":"#include \"box2dstepdriver.h\"\n#include \"box2dworld.h\"\n\nAnimationDriver::AnimationDriver(Box2DWorld *world) :\n\tQAbstractAnimation(),\n\tmWorld(world)\n{\n\tsetLoopCount(-1); \/\/ loop forever\n}\n\nint AnimationDriver::duration() const\n{\n\treturn 1000;\n}\n\nvoid AnimationDriver::start()\n{\n\tQAbstractAnimation::start();\n}\n\nvoid AnimationDriver::stop()\n{\n\tQAbstractAnimation::stop();\n}\n\nvoid AnimationDriver::updateCurrentTime(int)\n{\n\tmWorld->step();\n}\n\nEngineDriver::EngineDriver(Box2DWorld *world) :\n\tQObject(),\n\tmWorld(world),\n\tmActive(false)\n{}\n\nvoid EngineDriver::start()\n{\n\tqDebug(\"SPEEEEEEEED\");\n\tmActive = true;\n\tdoStep();\n}\n\nvoid EngineDriver::stop()\n{\n\tmActive = false;\n}\n\nvoid EngineDriver::doStep()\n{\n\tmWorld->step();\n\tQMetaObject::invokeMethod(this, \"doStep\", Qt::QueuedConnection);\n}\n","avg_line_length":14.4814814815,"max_line_length":65,"alphanum_fraction":0.716112532,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7823,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2017 The Cryptonote developers\n\/\/ Copyright (c) 2018 The Circle Foundation\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"Base58.h\"\n\n#include <assert.h>\n#include <string>\n#include <vector>\n\n#include \"crypto\/hash.h\"\n#include \"int-util.h\"\n#include \"Varint.h\"\n\nnamespace Tools\n{\n  namespace Base58\n  {\n    namespace\n    {\n      const char alphabet[] = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n      const size_t alphabet_size = sizeof(alphabet) - 1;\n      const size_t encoded_block_sizes[] = {0, 2, 3, 5, 6, 7, 9, 10, 11};\n      const size_t full_block_size = sizeof(encoded_block_sizes) \/ sizeof(encoded_block_sizes[0]) - 1;\n      const size_t full_encoded_block_size = encoded_block_sizes[full_block_size];\n      const size_t addr_checksum_size = 4;\n\n      struct reverse_alphabet\n      {\n        reverse_alphabet()\n        {\n          m_data.resize(alphabet[alphabet_size - 1] - alphabet[0] + 1, -1);\n\n          for (size_t i = 0; i < alphabet_size; ++i)\n          {\n            size_t idx = static_cast<size_t>(alphabet[i] - alphabet[0]);\n            m_data[idx] = static_cast<int8_t>(i);\n          }\n        }\n\n        int operator()(char letter) const\n        {\n          size_t idx = static_cast<size_t>(letter - alphabet[0]);\n          return idx < m_data.size() ? m_data[idx] : -1;\n        }\n\n        static reverse_alphabet instance;\n\n      private:\n        std::vector<int8_t> m_data;\n      };\n\n      reverse_alphabet reverse_alphabet::instance;\n\n      struct decoded_block_sizes\n      {\n        decoded_block_sizes()\n        {\n          m_data.resize(encoded_block_sizes[full_block_size] + 1, -1);\n          for (size_t i = 0; i <= full_block_size; ++i)\n          {\n            m_data[encoded_block_sizes[i]] = static_cast<int>(i);\n          }\n        }\n\n        int operator()(size_t encoded_block_size) const\n        {\n          assert(encoded_block_size <= full_encoded_block_size);\n          return m_data[encoded_block_size];\n        }\n\n        static decoded_block_sizes instance;\n\n      private:\n        std::vector<int> m_data;\n      };\n\n      decoded_block_sizes decoded_block_sizes::instance;\n\n      uint64_t uint_8be_to_64(const uint8_t* data, size_t size)\n      {\n        assert(1 <= size && size <= sizeof(uint64_t));\n\n        uint64_t res = 0;\n        switch (9 - size)\n        {\n        case 1:            res |= *data++; \/* FALLTHRU *\/\n        case 2: res <<= 8; res |= *data++; \/* FALLTHRU *\/\n        case 3: res <<= 8; res |= *data++; \/* FALLTHRU *\/\n        case 4: res <<= 8; res |= *data++; \/* FALLTHRU *\/\n        case 5: res <<= 8; res |= *data++; \/* FALLTHRU *\/\n        case 6: res <<= 8; res |= *data++; \/* FALLTHRU *\/\n        case 7: res <<= 8; res |= *data++; \/* FALLTHRU *\/\n        case 8: res <<= 8; res |= *data; break;\n        default: assert(false);\n        }\n\n        return res;\n      }\n\n      void uint_64_to_8be(uint64_t num, size_t size, uint8_t* data)\n      {\n        assert(1 <= size && size <= sizeof(uint64_t));\n\n        uint64_t num_be = SWAP64BE(num);\n        memcpy(data, reinterpret_cast<uint8_t*>(&num_be) + sizeof(uint64_t) - size, size);\n      }\n\n      void encode_block(const char* block, size_t size, char* res)\n      {\n        assert(1 <= size && size <= full_block_size);\n\n        uint64_t num = uint_8be_to_64(reinterpret_cast<const uint8_t*>(block), size);\n        int i = static_cast<int>(encoded_block_sizes[size]) - 1;\n        while (0 < num)\n        {\n          uint64_t remainder = num % alphabet_size;\n          num \/= alphabet_size;\n          res[i] = alphabet[remainder];\n          --i;\n        }\n      }\n\n      bool decode_block(const char* block, size_t size, char* res)\n      {\n        assert(1 <= size && size <= full_encoded_block_size);\n\n        int res_size = decoded_block_sizes::instance(size);\n        if (res_size <= 0)\n          return false; \/\/ Invalid block size\n\n        uint64_t res_num = 0;\n        uint64_t order = 1;\n        for (size_t i = size - 1; i < size; --i)\n        {\n          int digit = reverse_alphabet::instance(block[i]);\n          if (digit < 0)\n            return false; \/\/ Invalid symbol\n\n          uint64_t product_hi;\n          uint64_t tmp = res_num + mul128(order, digit, &product_hi);\n          if (tmp < res_num || 0 != product_hi)\n            return false; \/\/ Overflow\n\n          res_num = tmp;\n          order *= alphabet_size; \/\/ Never overflows, 58^10 < 2^64\n        }\n\n        if (static_cast<size_t>(res_size) < full_block_size && (UINT64_C(1) << (8 * res_size)) <= res_num)\n          return false; \/\/ Overflow\n\n        uint_64_to_8be(res_num, res_size, reinterpret_cast<uint8_t*>(res));\n\n        return true;\n      }\n    }\n\n    std::string encode(const std::string& data)\n    {\n      if (data.empty())\n        return std::string();\n\n      size_t full_block_count = data.size() \/ full_block_size;\n      size_t last_block_size = data.size() % full_block_size;\n      size_t res_size = full_block_count * full_encoded_block_size + encoded_block_sizes[last_block_size];\n\n      std::string res(res_size, alphabet[0]);\n      for (size_t i = 0; i < full_block_count; ++i)\n      {\n        encode_block(data.data() + i * full_block_size, full_block_size, &res[i * full_encoded_block_size]);\n      }\n\n      if (0 < last_block_size)\n      {\n        encode_block(data.data() + full_block_count * full_block_size, last_block_size, &res[full_block_count * full_encoded_block_size]);\n      }\n\n      return res;\n    }\n\n    bool decode(const std::string& enc, std::string& data)\n    {\n      if (enc.empty())\n      {\n        data.clear();\n        return true;\n      }\n\n      size_t full_block_count = enc.size() \/ full_encoded_block_size;\n      size_t last_block_size = enc.size() % full_encoded_block_size;\n      int last_block_decoded_size = decoded_block_sizes::instance(last_block_size);\n      if (last_block_decoded_size < 0)\n        return false; \/\/ Invalid enc length\n      size_t data_size = full_block_count * full_block_size + last_block_decoded_size;\n\n      data.resize(data_size, 0);\n      for (size_t i = 0; i < full_block_count; ++i)\n      {\n        if (!decode_block(enc.data() + i * full_encoded_block_size, full_encoded_block_size, &data[i * full_block_size]))\n          return false;\n      }\n\n      if (0 < last_block_size)\n      {\n        if (!decode_block(enc.data() + full_block_count * full_encoded_block_size, last_block_size,\n          &data[full_block_count * full_block_size]))\n          return false;\n      }\n\n      return true;\n    }\n\n    std::string encode_addr(uint64_t tag, const std::string& data)\n    {\n      std::string buf = get_varint_data(tag);\n      buf += data;\n      Crypto::Hash hash = Crypto::cn_fast_hash(buf.data(), buf.size());\n      const char* hash_data = reinterpret_cast<const char*>(&hash);\n      buf.append(hash_data, addr_checksum_size);\n      return encode(buf);\n    }\n\n    bool decode_addr(std::string addr, uint64_t& tag, std::string& data)\n    {\n      std::string addr_data;\n      bool r = decode(addr, addr_data);\n      if (!r) return false;\n      if (addr_data.size() <= addr_checksum_size) return false;\n\n      std::string checksum(addr_checksum_size, '\\0');\n      checksum = addr_data.substr(addr_data.size() - addr_checksum_size);\n\n      addr_data.resize(addr_data.size() - addr_checksum_size);\n      Crypto::Hash hash = Crypto::cn_fast_hash(addr_data.data(), addr_data.size());\n      std::string expected_checksum(reinterpret_cast<const char*>(&hash), addr_checksum_size);\n      if (expected_checksum != checksum) return false;\n\n      int read = Tools::read_varint(addr_data.begin(), addr_data.end(), tag);\n      if (read <= 0) return false;\n\n      data = addr_data.substr(read);\n      return true;\n    }\n  }\n}\n","avg_line_length":31.6720647773,"max_line_length":138,"alphanum_fraction":0.6001533938,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5603,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":null,"content":"#include \"VRDriver.hpp\"\n#include <Driver\/HMDDevice.hpp>\n#include <Driver\/TrackerDevice.hpp>\n#include <Driver\/ControllerDevice.hpp>\n#include <Driver\/TrackingReferenceDevice.hpp>\n\n\/\/ debug run: C:\\Program Files (x86)\\Steam\\steamapps\\common\\SteamVR\\bin\\win64\\vrstartup.exe\n\nvr::EVRInitError ExampleDriver::VRDriver::Init(vr::IVRDriverContext* pDriverContext)\n{\n    \/\/ Perform driver context initialisation\n    if (vr::EVRInitError init_error = vr::InitServerDriverContext(pDriverContext); init_error != vr::EVRInitError::VRInitError_None) {\n        return init_error;\n    }\n\n    Log(\"Activating ExampleDriver...\");\n\n    \/\/ Add a HMD\n    \/\/this->AddDevice(std::make_shared<HMDDevice>(\"Example_HMDDevice\"));\n\n    \/\/ Add a couple controllers\n    \/\/this->AddDevice(std::make_shared<ControllerDevice>(\"Example_ControllerDevice_Left\", ControllerDevice::Handedness::ANY));\n    \/\/this->AddDevice(std::make_shared<ControllerDevice>(\"Example_ControllerDevice_Right\", ControllerDevice::Handedness::ANY));\n    \/\/this->AddDevice(std::make_shared<ControllerDevice>(\"Example_ControllerDevice_Hip\", ControllerDevice::Handedness::ANY));\n\n    \/\/ Add a tracker\n    this->AddDevice(std::make_shared<TrackerDevice>(\"Example_TrackerDevice_Hip\"));\n    \/\/this->AddDevice(std::make_shared<TrackerDevice>(\"Example_TrackerDevice_LegL\"));\n    \/\/this->AddDevice(std::make_shared<TrackerDevice>(\"Example_TrackerDevice_LegR\"));\n\n    \/\/ Add a couple tracking references\n    \/\/this->AddDevice(std::make_shared<TrackingReferenceDevice>(\"Example_TrackingReference_A\"));\n    \/\/this->AddDevice(std::make_shared<TrackingReferenceDevice>(\"Example_TrackingReference_B\"));\n\n    Log(\"ExampleDriver Loaded Successfully\");\n\n\treturn vr::VRInitError_None;\n}\n\nvoid ExampleDriver::VRDriver::Cleanup()\n{\n}\n\nvoid ExampleDriver::VRDriver::RunFrame()\n{\n    \/\/ Collect events\n    vr::VREvent_t event;\n    std::vector<vr::VREvent_t> events;\n    while (vr::VRServerDriverHost()->PollNextEvent(&event, sizeof(event)))\n    {\n        events.push_back(event);\n    }\n    this->openvr_events_ = events;\n\n    \/\/ Update frame timing\n    std::chrono::system_clock::time_point now = std::chrono::system_clock::now();\n    this->frame_timing_ = std::chrono::duration_cast<std::chrono::milliseconds>(now - this->last_frame_time_);\n    this->last_frame_time_ = now;\n\n    \/\/ Update devices\n    for (auto& device : this->devices_)\n        device->Update();\n}\n\nbool ExampleDriver::VRDriver::ShouldBlockStandbyMode()\n{\n    return false;\n}\n\nvoid ExampleDriver::VRDriver::EnterStandby()\n{\n}\n\nvoid ExampleDriver::VRDriver::LeaveStandby()\n{\n}\n\nstd::vector<std::shared_ptr<ExampleDriver::IVRDevice>> ExampleDriver::VRDriver::GetDevices()\n{\n    return this->devices_;\n}\n\nstd::vector<vr::VREvent_t> ExampleDriver::VRDriver::GetOpenVREvents()\n{\n    return this->openvr_events_;\n}\n\nstd::chrono::milliseconds ExampleDriver::VRDriver::GetLastFrameTime()\n{\n    return this->frame_timing_;\n}\n\nbool ExampleDriver::VRDriver::AddDevice(std::shared_ptr<IVRDevice> device)\n{\n    vr::ETrackedDeviceClass openvr_device_class;\n    \/\/ Remember to update this switch when new device types are added\n    switch (device->GetDeviceType()) {\n        case DeviceType::CONTROLLER:\n            openvr_device_class = vr::ETrackedDeviceClass::TrackedDeviceClass_Controller;\n            break;\n        case DeviceType::HMD:\n            openvr_device_class = vr::ETrackedDeviceClass::TrackedDeviceClass_HMD;\n            break;\n        case DeviceType::TRACKER:\n            openvr_device_class = vr::ETrackedDeviceClass::TrackedDeviceClass_GenericTracker;\n            break;\n        case DeviceType::TRACKING_REFERENCE:\n            openvr_device_class = vr::ETrackedDeviceClass::TrackedDeviceClass_TrackingReference;\n            break;\n        default:\n            return false;\n    }\n    bool result = vr::VRServerDriverHost()->TrackedDeviceAdded(device->GetSerial().c_str(), openvr_device_class, device.get());\n    if(result)\n        this->devices_.push_back(device);\n    return result;\n}\n\nExampleDriver::SettingsValue ExampleDriver::VRDriver::GetSettingsValue(std::string key)\n{\n    vr::EVRSettingsError err = vr::EVRSettingsError::VRSettingsError_None;\n    int int_value = vr::VRSettings()->GetInt32(settings_key_.c_str(), key.c_str(), &err);\n    if (err == vr::EVRSettingsError::VRSettingsError_None) {\n        return int_value;\n    }\n    err = vr::EVRSettingsError::VRSettingsError_None;\n    float float_value = vr::VRSettings()->GetFloat(settings_key_.c_str(), key.c_str(), &err);\n    if (err == vr::EVRSettingsError::VRSettingsError_None) {\n        return float_value;\n    }\n    err = vr::EVRSettingsError::VRSettingsError_None;\n    bool bool_value = vr::VRSettings()->GetBool(settings_key_.c_str(), key.c_str(), &err);\n    if (err == vr::EVRSettingsError::VRSettingsError_None) {\n        return bool_value;\n    }\n    std::string str_value;\n    str_value.reserve(1024);\n    vr::VRSettings()->GetString(settings_key_.c_str(), key.c_str(), str_value.data(), 1024, &err);\n    if (err == vr::EVRSettingsError::VRSettingsError_None) {\n        return str_value;\n    }\n    err = vr::EVRSettingsError::VRSettingsError_None;\n\n    return SettingsValue();\n}\n\nvoid ExampleDriver::VRDriver::Log(std::string message)\n{\n    std::string message_endl = message + \"\\n\";\n    vr::VRDriverLog()->Log(message_endl.c_str());\n}\n\nvr::IVRDriverInput* ExampleDriver::VRDriver::GetInput()\n{\n    return vr::VRDriverInput();\n}\n\nvr::CVRPropertyHelpers* ExampleDriver::VRDriver::GetProperties()\n{\n    return vr::VRProperties();\n}\n\nvr::IVRServerDriverHost* ExampleDriver::VRDriver::GetDriverHost()\n{\n    return vr::VRServerDriverHost();\n}\n","avg_line_length":33.5508982036,"max_line_length":134,"alphanum_fraction":0.7135463145,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":30284,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements.  See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership.  The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License.  You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied.  See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include <gtest\/gtest.h>\n#include <string>\n#include <vector>\n\n#include \"common\/logging.h\"\n#include \"exec\/es\/es_query_builder.h\"\n#include \"exec\/es\/es_predicate.h\"\n#include \"rapidjson\/document.h\"\n#include \"rapidjson\/rapidjson.h\"\n#include \"rapidjson\/stringbuffer.h\"\n#include \"rapidjson\/writer.h\"\n#include \"runtime\/string_value.h\"\n\nnamespace doris {\n\nclass BooleanQueryBuilderTest : public testing::Test {\npublic:\n    BooleanQueryBuilderTest() { }\n    virtual ~BooleanQueryBuilderTest() { }\n};\n\nTEST_F(BooleanQueryBuilderTest, term_query) {\n    \/\/ content = \"wyf\" \n    char str[] = \"wyf\";\n    StringValue value(str, 3);\n    ExtLiteral term_literal(TYPE_VARCHAR, &value);\n    TypeDescriptor type_desc = TypeDescriptor::create_varchar_type(3);\n    std::string name = \"content\";\n    ExtBinaryPredicate term_predicate(TExprNodeType::BINARY_PRED, name, type_desc, TExprOpcode::EQ, term_literal);\n    TermQueryBuilder term_query(term_predicate);\n    rapidjson::Document document;\n    rapidjson::Value term_value(rapidjson::kObjectType);\n    term_value.SetObject();\n    term_query.to_json(&document, &term_value);\n    rapidjson::StringBuffer buffer;\n    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n    term_value.Accept(writer);\n    std::string actual_json = buffer.GetString();\n    \/\/LOG(INFO) << \"term query\" << actual_json;\n    ASSERT_STREQ(\"{\\\"term\\\":{\\\"content\\\":\\\"wyf\\\"}}\", actual_json.c_str());\n}\n\nTEST_F(BooleanQueryBuilderTest, range_query) {\n    \/\/ k >= a\n    char str[] = \"a\";\n    StringValue value(str, 1);\n    ExtLiteral term_literal(TYPE_VARCHAR, &value);\n    TypeDescriptor type_desc = TypeDescriptor::create_varchar_type(1);\n    std::string name = \"k\";\n    ExtBinaryPredicate range_predicate(TExprNodeType::BINARY_PRED, name, type_desc, TExprOpcode::GE, term_literal);\n    RangeQueryBuilder range_query(range_predicate);\n    rapidjson::Document document;\n    rapidjson::Value range_value(rapidjson::kObjectType);\n    range_value.SetObject();\n    range_query.to_json(&document, &range_value);\n    rapidjson::StringBuffer buffer;\n    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n    range_value.Accept(writer);\n    std::string actual_json = buffer.GetString();\n    \/\/LOG(INFO) << \"range query\" << actual_json;\n    ASSERT_STREQ(\"{\\\"range\\\":{\\\"k\\\":{\\\"gte\\\":\\\"a\\\"}}}\", actual_json.c_str());\n}\n\nTEST_F(BooleanQueryBuilderTest, es_query) {\n    \/\/ esquery('random', \"{\\\"bool\\\": {\\\"must_not\\\": {\\\"exists\\\": {\\\"field\\\": \\\"f1\\\"}}}}\")\n    char str[] = \"{\\\"bool\\\": {\\\"must_not\\\": {\\\"exists\\\": {\\\"field\\\": \\\"f1\\\"}}}}\";\n    int length = (int)strlen(str);\n    TypeDescriptor type_desc = TypeDescriptor::create_varchar_type(length);\n    std::string name = \"random\";\n    ExtColumnDesc col_des(name, type_desc);\n    std::vector<ExtColumnDesc> cols = {col_des};\n    StringValue value(str, length);\n    ExtLiteral term_literal(TYPE_VARCHAR, &value);\n    std::vector<ExtLiteral> values = {term_literal};\n    std::string function_name = \"esquery\";\n    ExtFunction function_predicate(TExprNodeType::FUNCTION_CALL, function_name, cols, values);\n    ESQueryBuilder es_query(function_predicate);\n    rapidjson::Document document;\n    rapidjson::Value es_query_value(rapidjson::kObjectType);\n    es_query_value.SetObject();\n    es_query.to_json(&document, &es_query_value);\n    rapidjson::StringBuffer buffer;\n    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n    es_query_value.Accept(writer);\n    std::string actual_json = buffer.GetString();\n    \/\/LOG(INFO) << \"es query\" << actual_json;\n    ASSERT_STREQ(\"{\\\"bool\\\":{\\\"must_not\\\":{\\\"exists\\\":{\\\"field\\\":\\\"f1\\\"}}}}\", actual_json.c_str());\n}\n\nTEST_F(BooleanQueryBuilderTest, like_query) {\n    \/\/ content like 'a%e%g_'\n    char str[] = \"a%e%g_\";\n    int length = (int)strlen(str);\n    LOG(INFO) << \"length \" << length;\n    TypeDescriptor type_desc = TypeDescriptor::create_varchar_type(length);\n    StringValue value(str, length);\n    ExtLiteral like_literal(TYPE_VARCHAR, &value);\n    std::string name = \"content\";\n    ExtLikePredicate like_predicate(TExprNodeType::LIKE_PRED, name, type_desc, like_literal);\n    WildCardQueryBuilder like_query(like_predicate);\n    rapidjson::Document document;\n    rapidjson::Value like_query_value(rapidjson::kObjectType);\n    like_query_value.SetObject();\n    like_query.to_json(&document, &like_query_value);\n    rapidjson::StringBuffer buffer;\n    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n    like_query_value.Accept(writer);\n    std::string actual_json = buffer.GetString();\n    \/\/ LOG(INFO) << \"wildcard query\" << actual_json;\n    ASSERT_STREQ(\"{\\\"wildcard\\\":{\\\"content\\\":\\\"a*e*g?\\\"}}\", actual_json.c_str());\n}\n\nTEST_F(BooleanQueryBuilderTest, terms_in_query) {\n    \/\/ dv in [\"2.0\", \"4.0\", \"8.0\"]\n    std::string terms_in_field = \"dv\";\n    int terms_in_field_length = terms_in_field.length();\n    TypeDescriptor terms_in_col_type_desc = TypeDescriptor::create_varchar_type(terms_in_field_length);\n\n    char value_1[] = \"2.0\";\n    int value_1_length = (int)strlen(value_1);\n    StringValue string_value_1(value_1, value_1_length);\n    ExtLiteral term_literal_1(TYPE_VARCHAR, &string_value_1);\n\n    char value_2[] = \"4.0\";\n    int value_2_length = (int)strlen(value_2);\n    StringValue string_value_2(value_2, value_2_length);\n    ExtLiteral term_literal_2(TYPE_VARCHAR, &string_value_2);\n\n    char value_3[] = \"8.0\";\n    int value_3_length = (int)strlen(value_3);\n    StringValue string_value_3(value_3, value_3_length);\n    ExtLiteral term_literal_3(TYPE_VARCHAR, &string_value_3);\n\n    std::vector<ExtLiteral> terms_values = {term_literal_1, term_literal_2, term_literal_3};\n    ExtInPredicate in_predicate(TExprNodeType::IN_PRED, false, terms_in_field, terms_in_col_type_desc, terms_values);\n    TermsInSetQueryBuilder terms_query(in_predicate);\n    rapidjson::Document document;\n    rapidjson::Value in_query_value(rapidjson::kObjectType);\n    in_query_value.SetObject();\n    terms_query.to_json(&document, &in_query_value);\n    rapidjson::StringBuffer buffer;\n    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n    in_query_value.Accept(writer);\n    std::string actual_json = buffer.GetString();\n    \/\/LOG(INFO) << \"terms in sets query\" << actual_json;\n    ASSERT_STREQ(\"{\\\"terms\\\":{\\\"dv\\\":[\\\"2.0\\\",\\\"4.0\\\",\\\"8.0\\\"]}}\", actual_json.c_str());\n}\n\nTEST_F(BooleanQueryBuilderTest, match_all_query) {\n    \/\/ match all docs\n    MatchAllQueryBuilder match_all_query;\n    rapidjson::Document document;\n    rapidjson::Value match_all_query_value(rapidjson::kObjectType);\n    match_all_query_value.SetObject();\n    match_all_query.to_json(&document, &match_all_query_value);\n    rapidjson::StringBuffer buffer;\n    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n    match_all_query_value.Accept(writer);\n    std::string actual_json = buffer.GetString();\n    \/\/LOG(INFO) << \"match all query\" << actual_json;\n    ASSERT_STREQ(\"{\\\"match_all\\\":{}}\", actual_json.c_str());\n}\n\nTEST_F(BooleanQueryBuilderTest, exists_query) {\n    \/\/ k1 is not null\n    \/\/ {\"exists\":{\"field\":\"k1\"}}\n    std::string exists_field = \"k1\";\n    int exists_field_length = exists_field.length();\n    TypeDescriptor exists_col_type_desc = TypeDescriptor::create_varchar_type(exists_field_length);\n    ExtIsNullPredicate isNullPredicate(TExprNodeType::IS_NULL_PRED, \"k1\", exists_col_type_desc, true);\n    ExistsQueryBuilder exists_query(isNullPredicate);\n    rapidjson::Document document;\n    rapidjson::Value exists_query_value(rapidjson::kObjectType);\n    exists_query_value.SetObject();\n    exists_query.to_json(&document, &exists_query_value);\n    rapidjson::StringBuffer buffer;\n    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n    exists_query_value.Accept(writer);\n    std::string actual_json = buffer.GetString();\n    ASSERT_STREQ(\"{\\\"exists\\\":{\\\"field\\\":\\\"k1\\\"}}\", actual_json.c_str());\n}\n\n\nTEST_F(BooleanQueryBuilderTest, bool_query) {\n    \/\/ content like 'a%e%g_'\n    char like_value[] = \"a%e%g_\";\n    int like_value_length = (int)strlen(like_value);\n    TypeDescriptor like_type_desc = TypeDescriptor::create_varchar_type(like_value_length);\n    StringValue like_term_value(like_value, like_value_length);\n    ExtLiteral like_literal(TYPE_VARCHAR, &like_term_value);\n    std::string like_field_name = \"content\";\n    ExtLikePredicate* like_predicate = new ExtLikePredicate(TExprNodeType::LIKE_PRED, like_field_name, like_type_desc, like_literal);\n    \/\/ esquery(\"random\", \"{\\\"bool\\\": {\\\"must_not\\\": {\\\"exists\\\": {\\\"field\\\": \\\"f1\\\"}}}}\")\n    char es_query_str[] = \"{\\\"bool\\\": {\\\"must_not\\\": {\\\"exists\\\": {\\\"field\\\": \\\"f1\\\"}}}}\";\n    int es_query_length = (int)strlen(es_query_str);\n    StringValue value(es_query_str, es_query_length);\n    TypeDescriptor es_query_type_desc = TypeDescriptor::create_varchar_type(es_query_length);\n    std::string es_query_field_name = \"random\";\n    ExtColumnDesc es_query_col_des(es_query_field_name, es_query_type_desc);\n    std::vector<ExtColumnDesc> es_query_cols = {es_query_col_des};\n    StringValue es_query_value(es_query_str, es_query_length);\n    ExtLiteral es_query_term_literal(TYPE_VARCHAR, &es_query_value);\n    std::vector<ExtLiteral> es_query_values = {es_query_term_literal};\n    std::string function_name = \"esquery\";\n    ExtFunction* function_predicate = new ExtFunction(TExprNodeType::FUNCTION_CALL, function_name, es_query_cols, es_query_values);\n    \/\/ k >= a\n    char range_value_str[] = \"a\";\n    int range_value_length = (int)strlen(range_value_str);\n    StringValue range_value(range_value_str, range_value_length);\n    ExtLiteral range_literal(TYPE_VARCHAR, &range_value);\n    TypeDescriptor range_type_desc = TypeDescriptor::create_varchar_type(range_value_length);\n    std::string range_field_name = \"k\";\n    ExtBinaryPredicate* range_predicate = new ExtBinaryPredicate(TExprNodeType::BINARY_PRED, range_field_name, range_type_desc, TExprOpcode::GE, range_literal);\n    \/\/ content = \"wyf\"\n    char term_str[] = \"wyf\";\n    int term_value_length = (int)strlen(term_str);\n    StringValue term_value(term_str, term_value_length);\n    ExtLiteral term_literal(TYPE_VARCHAR, &term_value);\n    TypeDescriptor term_type_desc = TypeDescriptor::create_varchar_type(term_value_length);\n    std::string term_field_name = \"content\";\n    ExtBinaryPredicate* term_predicate = new ExtBinaryPredicate(TExprNodeType::BINARY_PRED, term_field_name, term_type_desc, TExprOpcode::EQ, term_literal);\n    \n    \/\/ content like 'a%e%g_' or k >= a or content = \"wyf\"\n    std::vector<ExtPredicate*> or_predicates = {like_predicate, function_predicate, range_predicate, term_predicate};\n    BooleanQueryBuilder bool_query(or_predicates);\n    rapidjson::Document document;\n    rapidjson::Value bool_query_value(rapidjson::kObjectType);\n    bool_query_value.SetObject();\n    bool_query.to_json(&document, &bool_query_value);\n    rapidjson::StringBuffer buffer;\n    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n    bool_query_value.Accept(writer);\n    std::string actual_json = buffer.GetString();\n    std::string expected_json = \"{\\\"bool\\\":{\\\"should\\\":[{\\\"wildcard\\\":{\\\"content\\\":\\\"a*e*g?\\\"}},{\\\"bool\\\":{\\\"must_not\\\":{\\\"exists\\\":{\\\"field\\\":\\\"f1\\\"}}}},{\\\"range\\\":{\\\"k\\\":{\\\"gte\\\":\\\"a\\\"}}},{\\\"term\\\":{\\\"content\\\":\\\"wyf\\\"}}]}}\";\n    \/\/LOG(INFO) << \"bool query\" << actual_json;\n    ASSERT_STREQ(expected_json.c_str(), actual_json.c_str());\n}\n\nTEST_F(BooleanQueryBuilderTest, compound_bool_query) {\n    \/\/  content like \"a%e%g_\" or esquery(random, '{\"bool\": {\"must_not\": {\"exists\": {\"field\": \"f1\"}}}}')\n    char like_value[] = \"a%e%g_\";\n    int like_value_length = (int)strlen(like_value);\n    TypeDescriptor like_type_desc = TypeDescriptor::create_varchar_type(like_value_length);\n    StringValue like_term_value(like_value, like_value_length);\n    ExtLiteral like_literal(TYPE_VARCHAR, &like_term_value);\n    std::string like_field_name = \"content\";\n    ExtLikePredicate* like_predicate = new ExtLikePredicate(TExprNodeType::LIKE_PRED, like_field_name, like_type_desc, like_literal);\n\n    char es_query_str[] = \"{\\\"bool\\\": {\\\"must_not\\\": {\\\"exists\\\": {\\\"field\\\": \\\"f1\\\"}}}}\";\n    int es_query_length = (int)strlen(es_query_str);\n    StringValue value(es_query_str, es_query_length);\n    TypeDescriptor es_query_type_desc = TypeDescriptor::create_varchar_type(es_query_length);\n    std::string es_query_field_name = \"random\";\n    ExtColumnDesc es_query_col_des(es_query_field_name, es_query_type_desc);\n    std::vector<ExtColumnDesc> es_query_cols = {es_query_col_des};\n    StringValue es_query_value(es_query_str, es_query_length);\n    ExtLiteral es_query_term_literal(TYPE_VARCHAR, &es_query_value);\n    std::vector<ExtLiteral> es_query_values = {es_query_term_literal};\n    std::string function_name = \"esquery\";\n    ExtFunction* function_predicate = new ExtFunction(TExprNodeType::FUNCTION_CALL, function_name, es_query_cols, es_query_values);\n    std::vector<ExtPredicate*> bool_predicates_1 = {like_predicate, function_predicate};\n    EsPredicate* bool_predicate_1 = new EsPredicate(bool_predicates_1);\n\n    \/\/ k >= \"a\"\n    char range_value_str[] = \"a\";\n    int range_value_length = (int)strlen(range_value_str);\n    StringValue range_value(range_value_str, range_value_length);\n    ExtLiteral range_literal(TYPE_VARCHAR, &range_value);\n    TypeDescriptor range_type_desc = TypeDescriptor::create_varchar_type(range_value_length);\n    std::string range_field_name = \"k\";\n    ExtBinaryPredicate* range_predicate = new ExtBinaryPredicate(TExprNodeType::BINARY_PRED, range_field_name, range_type_desc, TExprOpcode::GE, range_literal);\n    \n    std::vector<ExtPredicate*> bool_predicates_2 = {range_predicate};\n    EsPredicate* bool_predicate_2 = new EsPredicate(bool_predicates_2);\n\n    \/\/ content != \"wyf\"\n    char term_str[] = \"wyf\";\n    int term_value_length = (int)strlen(term_str);\n    StringValue term_value(term_str, term_value_length);\n    ExtLiteral term_literal(TYPE_VARCHAR, &term_value);\n    TypeDescriptor term_type_desc = TypeDescriptor::create_varchar_type(term_value_length);\n    std::string term_field_name = \"content\";\n    ExtBinaryPredicate* term_ne_predicate = new ExtBinaryPredicate(TExprNodeType::BINARY_PRED, term_field_name, term_type_desc, TExprOpcode::NE, term_literal);\n    std::vector<ExtPredicate*> bool_predicates_3 = {term_ne_predicate};\n    EsPredicate* bool_predicate_3 = new EsPredicate(bool_predicates_3);\n\n    \/\/ fv not in [8.0, 16.0]\n    std::string terms_in_field = \"fv\";\n    int terms_in_field_length = terms_in_field.length();\n    TypeDescriptor terms_in_col_type_desc = TypeDescriptor::create_varchar_type(terms_in_field_length);\n\n    char value_1[] = \"8.0\";\n    int value_1_length = (int)strlen(value_1);\n    StringValue string_value_1(value_1, value_1_length);\n    ExtLiteral term_literal_1(TYPE_VARCHAR, &string_value_1);\n\n    char value_2[] = \"16.0\";\n    int value_2_length = (int)strlen(value_2);\n    StringValue string_value_2(value_2, value_2_length);\n    ExtLiteral term_literal_2(TYPE_VARCHAR, &string_value_2);\n\n    std::vector<ExtLiteral> terms_values = {term_literal_1, term_literal_2};\n    ExtInPredicate* in_predicate = new ExtInPredicate(TExprNodeType::IN_PRED, true, terms_in_field, terms_in_col_type_desc, terms_values);\n    std::vector<ExtPredicate*> bool_predicates_4 = {in_predicate};\n    EsPredicate* bool_predicate_4 = new EsPredicate(bool_predicates_4);\n\n    \/\/ (content like \"a%e%g_\" or esquery(random, '{\"bool\": {\"must_not\": {\"exists\": {\"field\": \"f1\"}}}}')) and content != \"wyf\" and fv not in [8.0, 16.0]\n    std::vector<EsPredicate*> and_bool_predicates = {bool_predicate_1, bool_predicate_2, bool_predicate_3, bool_predicate_4};\n    \n    rapidjson::Document document;\n    rapidjson::Value compound_bool_value(rapidjson::kObjectType);\n    compound_bool_value.SetObject();\n    BooleanQueryBuilder::to_query(and_bool_predicates, &document, &compound_bool_value);\n    rapidjson::StringBuffer buffer;\n    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n    compound_bool_value.Accept(writer);\n    std::string actual_bool_json = buffer.GetString();\n    std::string expected_json = \"{\\\"bool\\\":{\\\"filter\\\":[{\\\"bool\\\":{\\\"should\\\":[{\\\"wildcard\\\":{\\\"content\\\":\\\"a*e*g?\\\"}},{\\\"bool\\\":{\\\"must_not\\\":{\\\"exists\\\":{\\\"field\\\":\\\"f1\\\"}}}}]}},{\\\"bool\\\":{\\\"should\\\":[{\\\"range\\\":{\\\"k\\\":{\\\"gte\\\":\\\"a\\\"}}}]}},{\\\"bool\\\":{\\\"should\\\":[{\\\"bool\\\":{\\\"must_not\\\":[{\\\"term\\\":{\\\"content\\\":\\\"wyf\\\"}}]}}]}},{\\\"bool\\\":{\\\"should\\\":[{\\\"bool\\\":{\\\"must_not\\\":[{\\\"terms\\\":{\\\"fv\\\":[\\\"8.0\\\",\\\"16.0\\\"]}}]}}]}}]}}\";\n    \/\/LOG(INFO) << \"compound bool query\" << actual_bool_json;\n    ASSERT_STREQ(expected_json.c_str(), actual_bool_json.c_str());\n}\nTEST_F(BooleanQueryBuilderTest, validate_esquery) {\n    std::string function_name = \"esquery\";\n    char field[] = \"random\";\n    int field_length = (int)strlen(field);\n    TypeDescriptor es_query_type_desc = TypeDescriptor::create_varchar_type(field_length);\n    ExtColumnDesc es_query_col_des(field, es_query_type_desc);\n    std::vector<ExtColumnDesc> es_query_cols = {es_query_col_des};\n    char es_query_str[] = \"{\\\"bool\\\": {\\\"must_not\\\": {\\\"exists\\\": {\\\"field\\\": \\\"f1\\\"}}}}\";\n    int es_query_length = (int)strlen(es_query_str);\n    StringValue es_query_value(es_query_str, es_query_length);\n    ExtLiteral es_query_term_literal(TYPE_VARCHAR, &es_query_value);\n    std::vector<ExtLiteral> es_query_values = {es_query_term_literal};\n    ExtFunction legal_es_query(TExprNodeType::FUNCTION_CALL, function_name, es_query_cols, es_query_values);\n    auto st = BooleanQueryBuilder::check_es_query(legal_es_query);\n    ASSERT_TRUE(st.ok());\n    char empty_query[] = \"{}\";\n    int empty_query_length = (int)strlen(empty_query);\n    StringValue empty_query_value(empty_query, empty_query_length);\n    ExtLiteral empty_query_term_literal(TYPE_VARCHAR, &empty_query_value);\n    std::vector<ExtLiteral> empty_query_values = {empty_query_term_literal};\n    ExtFunction empty_es_query(TExprNodeType::FUNCTION_CALL, function_name, es_query_cols, empty_query_values);\n    st = BooleanQueryBuilder::check_es_query(empty_es_query);\n    ASSERT_STREQ(st.get_error_msg().c_str(), \"esquery must only one root\");\n    \/\/LOG(INFO) <<\"error msg:\" << st1.get_error_msg();\n    char malformed_query[] = \"{\\\"bool\\\": {\\\"must_not\\\": {\\\"exists\\\": {\";\n    int malformed_query_length = (int)strlen(malformed_query);\n    StringValue malformed_query_value(malformed_query, malformed_query_length);\n    ExtLiteral malformed_query_term_literal(TYPE_VARCHAR, &malformed_query_value);\n    std::vector<ExtLiteral> malformed_query_values = {malformed_query_term_literal};\n    ExtFunction malformed_es_query(TExprNodeType::FUNCTION_CALL, function_name, es_query_cols, malformed_query_values);\n    st = BooleanQueryBuilder::check_es_query(malformed_es_query);\n    ASSERT_STREQ(st.get_error_msg().c_str(), \"malformed esquery json\");\n    char illegal_query[] = \"{\\\"term\\\": {\\\"k1\\\" : \\\"2\\\"},\\\"match\\\": {\\\"k1\\\": \\\"3\\\"}}\";\n    int illegal_query_length = (int)strlen(illegal_query);\n    StringValue illegal_query_value(illegal_query, illegal_query_length);\n    ExtLiteral illegal_query_term_literal(TYPE_VARCHAR, &illegal_query_value);\n    std::vector<ExtLiteral> illegal_query_values = {illegal_query_term_literal};\n    ExtFunction illegal_es_query(TExprNodeType::FUNCTION_CALL, function_name, es_query_cols, illegal_query_values);\n    st = BooleanQueryBuilder::check_es_query(illegal_es_query);\n    ASSERT_STREQ(st.get_error_msg().c_str(), \"esquery must only one root\");\n    char illegal_key_query[] = \"[\\\"22\\\"]\";\n    int illegal_key_query_length = (int)strlen(illegal_key_query);\n    StringValue illegal_key_query_value(illegal_key_query, illegal_key_query_length);\n    ExtLiteral illegal_key_query_term_literal(TYPE_VARCHAR, &illegal_key_query_value);\n    std::vector<ExtLiteral> illegal_key_query_values = {illegal_key_query_term_literal};\n    ExtFunction illegal_key_es_query(TExprNodeType::FUNCTION_CALL, function_name, es_query_cols, illegal_key_query_values);\n    st = BooleanQueryBuilder::check_es_query(illegal_key_es_query);\n    ASSERT_STREQ(st.get_error_msg().c_str(), \"esquery must be a object\");\n}\n\nTEST_F(BooleanQueryBuilderTest, validate_partial) {\n    char like_value[] = \"a%e%g_\";\n    int like_value_length = (int)strlen(like_value);\n    TypeDescriptor like_type_desc = TypeDescriptor::create_varchar_type(like_value_length);\n    StringValue like_term_value(like_value, like_value_length);\n    ExtLiteral like_literal(TYPE_VARCHAR, &like_term_value);\n    std::string like_field_name = \"content\";\n    ExtLikePredicate* like_predicate = new ExtLikePredicate(TExprNodeType::LIKE_PRED, like_field_name, like_type_desc, like_literal);\n\n    \/\/ k >= \"a\"\n    char range_value_str[] = \"a\";\n    int range_value_length = (int)strlen(range_value_str);\n    StringValue range_value(range_value_str, range_value_length);\n    ExtLiteral range_literal(TYPE_VARCHAR, &range_value);\n    TypeDescriptor range_type_desc = TypeDescriptor::create_varchar_type(range_value_length);\n    std::string range_field_name = \"k\";\n    ExtBinaryPredicate* range_predicate = new ExtBinaryPredicate(TExprNodeType::BINARY_PRED, range_field_name, range_type_desc, TExprOpcode::GE, range_literal);\n    \n    std::vector<ExtPredicate*> bool_predicates_1 = {like_predicate, range_predicate};\n    EsPredicate* bool_predicate_1 = new EsPredicate(bool_predicates_1);\n\n    \/\/ fv not in [8.0, 16.0]\n    std::string terms_in_field = \"fv\";\n    int terms_in_field_length = terms_in_field.length();\n    TypeDescriptor terms_in_col_type_desc = TypeDescriptor::create_varchar_type(terms_in_field_length);\n\n    char value_1[] = \"8.0\";\n    int value_1_length = (int)strlen(value_1);\n    StringValue string_value_1(value_1, value_1_length);\n    ExtLiteral term_literal_1(TYPE_VARCHAR, &string_value_1);\n\n    char value_2[] = \"16.0\";\n    int value_2_length = (int)strlen(value_2);\n    StringValue string_value_2(value_2, value_2_length);\n    ExtLiteral term_literal_2(TYPE_VARCHAR, &string_value_2);\n\n    std::vector<ExtLiteral> terms_values = {term_literal_1, term_literal_2};\n    ExtInPredicate* in_predicate = new ExtInPredicate(TExprNodeType::IN_PRED, true, terms_in_field, terms_in_col_type_desc, terms_values);\n    std::vector<ExtPredicate*> bool_predicates_2 = {in_predicate};\n    EsPredicate* bool_predicate_2 = new EsPredicate(bool_predicates_2);\n\n    \/\/ content != \"wyf\"\n    char term_str[] = \"wyf\";\n    int term_value_length = (int)strlen(term_str);\n    StringValue term_value(term_str, term_value_length);\n    ExtLiteral term_literal(TYPE_VARCHAR, &term_value);\n    TypeDescriptor term_type_desc = TypeDescriptor::create_varchar_type(term_value_length);\n    std::string term_field_name = \"content\";\n    ExtBinaryPredicate* term_ne_predicate = new ExtBinaryPredicate(TExprNodeType::BINARY_PRED, term_field_name, term_type_desc, TExprOpcode::NE, term_literal);\n    \n    char es_query_str[] = \"{\\\"bool\\\": {\\\"must_not\\\": {\\\"exists\\\": {\\\"field\\\": \\\"f1\\\"}}}}\";\n    int es_query_length = (int)strlen(es_query_str);\n    StringValue value(es_query_str, es_query_length);\n    TypeDescriptor es_query_type_desc = TypeDescriptor::create_varchar_type(es_query_length);\n    std::string es_query_field_name = \"random\";\n    ExtColumnDesc es_query_col_des(es_query_field_name, es_query_type_desc);\n    std::vector<ExtColumnDesc> es_query_cols = {es_query_col_des};\n    StringValue es_query_value(es_query_str, es_query_length);\n    ExtLiteral es_query_term_literal(TYPE_VARCHAR, &es_query_value);\n    std::vector<ExtLiteral> es_query_values = {es_query_term_literal};\n    std::string function_name = \"esquery\";\n    ExtFunction* function_predicate = new ExtFunction(TExprNodeType::FUNCTION_CALL, function_name, es_query_cols, es_query_values);\n    std::vector<ExtPredicate*> bool_predicates_3 = {term_ne_predicate, function_predicate};\n    EsPredicate* bool_predicate_3 = new EsPredicate(bool_predicates_3);\n    \n    std::vector<EsPredicate*> and_bool_predicates = {bool_predicate_1, bool_predicate_2, bool_predicate_3};\n    std::vector<bool> result;\n    BooleanQueryBuilder::validate(and_bool_predicates, &result);\n    std::vector<bool> expected = {true, true, true};\n    ASSERT_TRUE(result == expected);\n    char illegal_query[] = \"{\\\"term\\\": {\\\"k1\\\" : \\\"2\\\"},\\\"match\\\": {\\\"k1\\\": \\\"3\\\"}}\";\n    int illegal_query_length = (int)strlen(illegal_query);\n    StringValue illegal_query_value(illegal_query, illegal_query_length);\n    ExtLiteral illegal_query_term_literal(TYPE_VARCHAR, &illegal_query_value);\n    std::vector<ExtLiteral> illegal_query_values = {illegal_query_term_literal};\n    ExtFunction* illegal_function_preficate = new ExtFunction(TExprNodeType::FUNCTION_CALL, function_name, es_query_cols, illegal_query_values);\n    std::vector<ExtPredicate*> illegal_bool_predicates_3 = {term_ne_predicate, illegal_function_preficate};\n    EsPredicate* illegal_bool_predicate_3 = new EsPredicate(illegal_bool_predicates_3);\n    std::vector<EsPredicate*> and_bool_predicates_1 = {bool_predicate_1, bool_predicate_2, illegal_bool_predicate_3};\n    std::vector<bool> result1;\n    BooleanQueryBuilder::validate(and_bool_predicates_1, &result1);\n    std::vector<bool> expected1 = {true, true, false};\n    ASSERT_TRUE(result1 == expected1);\n}\n\n\/\/ ( k >= \"a\" and (fv not in [8.0, 16.0]) or (content != \"wyf\") ) or content like \"a%e%g_\"\n\nTEST_F(BooleanQueryBuilderTest, validate_compound_and) {\n\n    std::string terms_in_field = \"fv\"; \/\/ fv not in [8.0, 16.0]\n    int terms_in_field_length = terms_in_field.length();\n    TypeDescriptor terms_in_col_type_desc = TypeDescriptor::create_varchar_type(terms_in_field_length);\n\n    char value_1[] = \"8.0\";\n    int value_1_length = (int)strlen(value_1);\n    StringValue string_value_1(value_1, value_1_length);\n    ExtLiteral term_literal_1(TYPE_VARCHAR, &string_value_1);\n\n    char value_2[] = \"16.0\";\n    int value_2_length = (int)strlen(value_2);\n    StringValue string_value_2(value_2, value_2_length);\n    ExtLiteral term_literal_2(TYPE_VARCHAR, &string_value_2);\n\n    std::vector<ExtLiteral> terms_values = {term_literal_1, term_literal_2};\n    ExtInPredicate* in_predicate = new ExtInPredicate(TExprNodeType::IN_PRED, true, terms_in_field, terms_in_col_type_desc, terms_values);\n\n    char term_str[] = \"wyf\";\n    int term_value_length = (int)strlen(term_str);\n    StringValue term_value(term_str, term_value_length);\n    ExtLiteral term_literal(TYPE_VARCHAR, &term_value);\n    TypeDescriptor term_type_desc = TypeDescriptor::create_varchar_type(term_value_length);\n    std::string term_field_name = \"content\";\n    ExtBinaryPredicate* term_ne_predicate = new ExtBinaryPredicate(TExprNodeType::BINARY_PRED, term_field_name, term_type_desc, TExprOpcode::NE, term_literal);\n\n    std::vector<ExtPredicate*> innner_or_content = {term_ne_predicate, in_predicate};\n\n    EsPredicate* innner_or_predicate = new EsPredicate(innner_or_content);\n\n    char range_value_str[] = \"a\"; \/\/ k >= \"a\"\n    int range_value_length = (int)strlen(range_value_str);\n    StringValue range_value(range_value_str, range_value_length);\n    ExtLiteral range_literal(TYPE_VARCHAR, &range_value);\n    TypeDescriptor range_type_desc = TypeDescriptor::create_varchar_type(range_value_length);\n    std::string range_field_name = \"k\";\n    ExtBinaryPredicate* range_predicate = new ExtBinaryPredicate(TExprNodeType::BINARY_PRED, range_field_name, range_type_desc, TExprOpcode::GE, range_literal);\n    std::vector<ExtPredicate*> range_predicates = {range_predicate};\n    EsPredicate* left_inner_or_predicate = new EsPredicate(range_predicates);\n\n    std::vector<EsPredicate*> ourter_left_predicates_1 = {left_inner_or_predicate, innner_or_predicate};\n\n    ExtCompPredicates* comp_predicate = new ExtCompPredicates(TExprOpcode::COMPOUND_AND, ourter_left_predicates_1);\n\n    char like_value[] = \"a%e%g_\";\n    int like_value_length = (int)strlen(like_value);\n    TypeDescriptor like_type_desc = TypeDescriptor::create_varchar_type(like_value_length);\n    StringValue like_term_value(like_value, like_value_length);\n    ExtLiteral like_literal(TYPE_VARCHAR, &like_term_value);\n    std::string like_field_name = \"content\";\n    ExtLikePredicate* like_predicate = new ExtLikePredicate(TExprNodeType::LIKE_PRED, like_field_name, like_type_desc, like_literal);\n\n    \n    std::vector<ExtPredicate*> or_predicate_vector = {comp_predicate, like_predicate};\n    EsPredicate* or_predicate = new EsPredicate(or_predicate_vector);\n\n    std::vector<EsPredicate*> or_predicates = {or_predicate};\n    std::vector<bool> result1;\n    BooleanQueryBuilder::validate(or_predicates, &result1);\n    std::vector<bool> expected1 = {true};\n    ASSERT_TRUE(result1 == expected1);\n\n    rapidjson::Document document;\n    rapidjson::Value compound_and_value(rapidjson::kObjectType);\n    compound_and_value.SetObject();\n    BooleanQueryBuilder::to_query(or_predicates, &document, &compound_and_value);\n    rapidjson::StringBuffer buffer;\n    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n    compound_and_value.Accept(writer);\n    std::string actual_bool_json = buffer.GetString();\n    std::string expected_json = \"{\\\"bool\\\":{\\\"filter\\\":[{\\\"bool\\\":{\\\"should\\\":[{\\\"bool\\\":{\\\"filter\\\":[{\\\"bool\\\":{\\\"should\\\":[{\\\"range\\\":{\\\"k\\\":{\\\"gte\\\":\\\"a\\\"}}}]}},{\\\"bool\\\":{\\\"should\\\":[{\\\"bool\\\":{\\\"must_not\\\":[{\\\"term\\\":{\\\"content\\\":\\\"wyf\\\"}}]}},{\\\"bool\\\":{\\\"must_not\\\":[{\\\"terms\\\":{\\\"fv\\\":[\\\"8.0\\\",\\\"16.0\\\"]}}]}}]}}]}},{\\\"wildcard\\\":{\\\"content\\\":\\\"a*e*g?\\\"}}]}}]}}\";\n    ASSERT_STREQ(expected_json.c_str(), actual_bool_json.c_str());\n}\n}\n\nint main(int argc, char* argv[]) {\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n","avg_line_length":54.4676258993,"max_line_length":427,"alphanum_fraction":0.7370228504,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11383,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":4.0,"content":"#include <Color.h>\r\n\r\n#include <array>\r\n#include <unordered_map>\r\n\r\nusing namespace pdfout;\r\n\r\nnamespace{\r\n\r\n  std::unordered_map<pdfout::ColorName, std::array<uint8_t, 3>> colorNameToRGB{\r\n    {ColorNameAliceBlue,            {0xF0, 0xF8, 0xFF}},\r\n    {ColorNameAntiqueWhite,         {0xFA, 0xEB, 0xD7}},\r\n    {ColorNameAqua,                 {0x00, 0xFF, 0xFF}},\r\n    {ColorNameAquamarine,           {0x7F, 0xFF, 0xD4}},\r\n    {ColorNameAzure,                {0xF0, 0xFF, 0xFF}},\r\n    {ColorNameBeige,                {0xF5, 0xF5, 0xDC}},\r\n    {ColorNameBisque,               {0xFF, 0xE4, 0xC4}},\r\n    {ColorNameBlack,                {0x00, 0x00, 0x00}},\r\n    {ColorNameBlanchedAlmond,       {0xFF, 0xEB, 0xCD}},\r\n    {ColorNameBlue,                 {0x00, 0x00, 0xFF}},\r\n    {ColorNameBlueViolet,           {0x8A, 0x2B, 0xE2}},\r\n    {ColorNameBrown,                {0xA5, 0x2A, 0x2A}},\r\n    {ColorNameBurlyWood,            {0xDE, 0xB8, 0x87}},\r\n    {ColorNameCadetBlue,            {0x5F, 0x9E, 0xA0}},\r\n    {ColorNameChartreuse,           {0x7F, 0xFF, 0x00}},\r\n    {ColorNameChocolate,            {0xD2, 0x69, 0x1E}},\r\n    {ColorNameCoral,                {0xFF, 0x7F, 0x50}},\r\n    {ColorNameCornflowerBlue,       {0x64, 0x95, 0xED}},\r\n    {ColorNameCornsilk,             {0xFF, 0xF8, 0xDC}},\r\n    {ColorNameCrimson,              {0xDC, 0x14, 0x3C}},\r\n    {ColorNameCyan,                 {0x00, 0xFF, 0xFF}},\r\n    {ColorNameDarkBlue,             {0x00, 0x00, 0x8B}},\r\n    {ColorNameDarkCyan,             {0x00, 0x8B, 0x8B}},\r\n    {ColorNameDarkGoldenRod,        {0xB8, 0x86, 0x0B}},\r\n    {ColorNameDarkGray,             {0xA9, 0xA9, 0xA9}},\r\n    {ColorNameDarkGrey,             {0xA9, 0xA9, 0xA9}},\r\n    {ColorNameDarkGreen,            {0x00, 0x64, 0x00}},\r\n    {ColorNameDarkKhaki,            {0xBD, 0xB7, 0x6B}},\r\n    {ColorNameDarkMagenta,          {0x8B, 0x00, 0x8B}},\r\n    {ColorNameDarkOliveGreen,       {0x55, 0x6B, 0x2F}},\r\n    {ColorNameDarkOrange,           {0xFF, 0x8C, 0x00}},\r\n    {ColorNameDarkOrchid,           {0x99, 0x32, 0xCC}},\r\n    {ColorNameDarkRed,              {0x8B, 0x00, 0x00}},\r\n    {ColorNameDarkSalmon,           {0xE9, 0x96, 0x7A}},\r\n    {ColorNameDarkSeaGreen,         {0x8F, 0xBC, 0x8F}},\r\n    {ColorNameDarkSlateBlue,        {0x48, 0x3D, 0x8B}},\r\n    {ColorNameDarkSlateGray,        {0x2F, 0x4F, 0x4F}},\r\n    {ColorNameDarkSlateGrey,        {0x2F, 0x4F, 0x4F}},\r\n    {ColorNameDarkTurquoise,        {0x00, 0xCE, 0xD1}},\r\n    {ColorNameDarkViolet,           {0x94, 0x00, 0xD3}},\r\n    {ColorNameDeepPink,             {0xFF, 0x14, 0x93}},\r\n    {ColorNameDeepSkyBlue,          {0x00, 0xBF, 0xFF}},\r\n    {ColorNameDimGray,              {0x69, 0x69, 0x69}},\r\n    {ColorNameDimGrey,              {0x69, 0x69, 0x69}},\r\n    {ColorNameDodgerBlue,           {0x1E, 0x90, 0xFF}},\r\n    {ColorNameFireBrick,            {0xB2, 0x22, 0x22}},\r\n    {ColorNameFloralWhite,          {0xFF, 0xFA, 0xF0}},\r\n    {ColorNameForestGreen,          {0x22, 0x8B, 0x22}},\r\n    {ColorNameFuchsia,              {0xFF, 0x00, 0xFF}},\r\n    {ColorNameGainsboro,            {0xDC, 0xDC, 0xDC}},\r\n    {ColorNameGhostWhite,           {0xF8, 0xF8, 0xFF}},\r\n    {ColorNameGold,                 {0xFF, 0xD7, 0x00}},\r\n    {ColorNameGoldenRod,            {0xDA, 0xA5, 0x20}},\r\n    {ColorNameGray,                 {0x80, 0x80, 0x80}},\r\n    {ColorNameGrey,                 {0x80, 0x80, 0x80}},\r\n    {ColorNameGreen,                {0x00, 0x80, 0x00}},\r\n    {ColorNameGreenYellow,          {0xAD, 0xFF, 0x2F}},\r\n    {ColorNameHoneyDew,             {0xF0, 0xFF, 0xF0}},\r\n    {ColorNameHotPink,              {0xFF, 0x69, 0xB4}},\r\n    {ColorNameIndianRed,            {0xCD, 0x5C, 0x5C}},\r\n    {ColorNameIndigo,               {0x4B, 0x00, 0x82}},\r\n    {ColorNameIvory,                {0xFF, 0xFF, 0xF0}},\r\n    {ColorNameKhaki,                {0xF0, 0xE6, 0x8C}},\r\n    {ColorNameLavender,             {0xE6, 0xE6, 0xFA}},\r\n    {ColorNameLavenderBlush,        {0xFF, 0xF0, 0xF5}},\r\n    {ColorNameLawnGreen,            {0x7C, 0xFC, 0x00}},\r\n    {ColorNameLemonChiffon,         {0xFF, 0xFA, 0xCD}},\r\n    {ColorNameLightBlue,            {0xAD, 0xD8, 0xE6}},\r\n    {ColorNameLightCoral,           {0xF0, 0x80, 0x80}},\r\n    {ColorNameLightCyan,            {0xE0, 0xFF, 0xFF}},\r\n    {ColorNameLightGoldenRodYellow, {0xFA, 0xFA, 0xD2}},\r\n    {ColorNameLightGray,            {0xD3, 0xD3, 0xD3}},\r\n    {ColorNameLightGrey,            {0xD3, 0xD3, 0xD3}},\r\n    {ColorNameLightGreen,           {0x90, 0xEE, 0x90}},\r\n    {ColorNameLightPink,            {0xFF, 0xB6, 0xC1}},\r\n    {ColorNameLightSalmon,          {0xFF, 0xA0, 0x7A}},\r\n    {ColorNameLightSeaGreen,        {0x20, 0xB2, 0xAA}},\r\n    {ColorNameLightSkyBlue,         {0x87, 0xCE, 0xFA}},\r\n    {ColorNameLightSlateGray,       {0x77, 0x88, 0x99}},\r\n    {ColorNameLightSlateGrey,       {0x77, 0x88, 0x99}},\r\n    {ColorNameLightSteelBlue,       {0xB0, 0xC4, 0xDE}},\r\n    {ColorNameLightYellow,          {0xFF, 0xFF, 0xE0}},\r\n    {ColorNameLime,                 {0x00, 0xFF, 0x00}},\r\n    {ColorNameLimeGreen,            {0x32, 0xCD, 0x32}},\r\n    {ColorNameLinen,                {0xFA, 0xF0, 0xE6}},\r\n    {ColorNameMagenta,              {0xFF, 0x00, 0xFF}},\r\n    {ColorNameMaroon,               {0x80, 0x00, 0x00}},\r\n    {ColorNameMediumAquaMarine,     {0x66, 0xCD, 0xAA}},\r\n    {ColorNameMediumBlue,           {0x00, 0x00, 0xCD}},\r\n    {ColorNameMediumOrchid,         {0xBA, 0x55, 0xD3}},\r\n    {ColorNameMediumPurple,         {0x93, 0x70, 0xDB}},\r\n    {ColorNameMediumSeaGreen,       {0x3C, 0xB3, 0x71}},\r\n    {ColorNameMediumSlateBlue,      {0x7B, 0x68, 0xEE}},\r\n    {ColorNameMediumSpringGreen,    {0x00, 0xFA, 0x9A}},\r\n    {ColorNameMediumTurquoise,      {0x48, 0xD1, 0xCC}},\r\n    {ColorNameMediumVioletRed,      {0xC7, 0x15, 0x85}},\r\n    {ColorNameMidnightBlue,         {0x19, 0x19, 0x70}},\r\n    {ColorNameMintCream,            {0xF5, 0xFF, 0xFA}},\r\n    {ColorNameMistyRose,            {0xFF, 0xE4, 0xE1}},\r\n    {ColorNameMoccasin,             {0xFF, 0xE4, 0xB5}},\r\n    {ColorNameNavajoWhite,          {0xFF, 0xDE, 0xAD}},\r\n    {ColorNameNavy,                 {0x00, 0x00, 0x80}},\r\n    {ColorNameOldLace,              {0xFD, 0xF5, 0xE6}},\r\n    {ColorNameOlive,                {0x80, 0x80, 0x00}},\r\n    {ColorNameOliveDrab,            {0x6B, 0x8E, 0x23}},\r\n    {ColorNameOrange,               {0xFF, 0xA5, 0x00}},\r\n    {ColorNameOrangeRed,            {0xFF, 0x45, 0x00}},\r\n    {ColorNameOrchid,               {0xDA, 0x70, 0xD6}},\r\n    {ColorNamePaleGoldenRod,        {0xEE, 0xE8, 0xAA}},\r\n    {ColorNamePaleGreen,            {0x98, 0xFB, 0x98}},\r\n    {ColorNamePaleTurquoise,        {0xAF, 0xEE, 0xEE}},\r\n    {ColorNamePaleVioletRed,        {0xDB, 0x70, 0x93}},\r\n    {ColorNamePapayaWhip,           {0xFF, 0xEF, 0xD5}},\r\n    {ColorNamePeachPuff,            {0xFF, 0xDA, 0xB9}},\r\n    {ColorNamePeru,                 {0xCD, 0x85, 0x3F}},\r\n    {ColorNamePink,                 {0xFF, 0xC0, 0xCB}},\r\n    {ColorNamePlum,                 {0xDD, 0xA0, 0xDD}},\r\n    {ColorNamePowderBlue,           {0xB0, 0xE0, 0xE6}},\r\n    {ColorNamePurple,               {0x80, 0x00, 0x80}},\r\n    {ColorNameRebeccaPurple,        {0x66, 0x33, 0x99}},\r\n    {ColorNameRed,                  {0xFF, 0x00, 0x00}},\r\n    {ColorNameRosyBrown,            {0xBC, 0x8F, 0x8F}},\r\n    {ColorNameRoyalBlue,            {0x41, 0x69, 0xE1}},\r\n    {ColorNameSaddleBrown,          {0x8B, 0x45, 0x13}},\r\n    {ColorNameSalmon,               {0xFA, 0x80, 0x72}},\r\n    {ColorNameSandyBrown,           {0xF4, 0xA4, 0x60}},\r\n    {ColorNameSeaGreen,             {0x2E, 0x8B, 0x57}},\r\n    {ColorNameSeaShell,             {0xFF, 0xF5, 0xEE}},\r\n    {ColorNameSienna,               {0xA0, 0x52, 0x2D}},\r\n    {ColorNameSilver,               {0xC0, 0xC0, 0xC0}},\r\n    {ColorNameSkyBlue,              {0x87, 0xCE, 0xEB}},\r\n    {ColorNameSlateBlue,            {0x6A, 0x5A, 0xCD}},\r\n    {ColorNameSlateGray,            {0x70, 0x80, 0x90}},\r\n    {ColorNameSlateGrey,            {0x70, 0x80, 0x90}},\r\n    {ColorNameSnow,                 {0xFF, 0xFA, 0xFA}},\r\n    {ColorNameSpringGreen,          {0x00, 0xFF, 0x7F}},\r\n    {ColorNameSteelBlue,            {0x46, 0x82, 0xB4}},\r\n    {ColorNameTan,                  {0xD2, 0xB4, 0x8C}},\r\n    {ColorNameTeal,                 {0x00, 0x80, 0x80}},\r\n    {ColorNameThistle,              {0xD8, 0xBF, 0xD8}},\r\n    {ColorNameTomato,               {0xFF, 0x63, 0x47}},\r\n    {ColorNameTurquoise,            {0x40, 0xE0, 0xD0}},\r\n    {ColorNameViolet,               {0xEE, 0x82, 0xEE}},\r\n    {ColorNameWheat,                {0xF5, 0xDE, 0xB3}},\r\n    {ColorNameWhite,                {0xFF, 0xFF, 0xFF}},\r\n    {ColorNameWhiteSmoke,           {0xF5, 0xF5, 0xF5}},\r\n    {ColorNameYellow,               {0xFF, 0xFF, 0x00}},\r\n    {ColorNameYellowGreen,          {0x9A, 0xCD, 0x32}}\r\n  };\r\n}\r\n\r\nnamespace pdfout{\r\n\r\n  Color Color::createRGB(float red, float green, float blue){\r\n    Color color;\r\n    color.mType = ColorTypeRGB;\r\n    color.mValue.mRGB.mRed = red;\r\n    color.mValue.mRGB.mGreen = green;\r\n    color.mValue.mRGB.mBlue = blue;\r\n    return color;\r\n  }\r\n\r\n  Color Color::createRGB(ColorName colorName){\r\n    Color color;\r\n    color.mType = ColorTypeRGB;\r\n\r\n    auto &value = colorNameToRGB[colorName];\r\n\r\n    color.mValue.mRGB.mRed = (float) value[0] \/ 255.f;\r\n    color.mValue.mRGB.mGreen = (float) value[1] \/ 255.f;\r\n    color.mValue.mRGB.mBlue = (float) value[2] \/ 255.f;\r\n    return color;\r\n  }\r\n\r\n  Color Color::createCMYK(float cyan, float magenta, float yellow, float black){\r\n    Color color;\r\n    color.mType = ColorTypeCMYK;\r\n    color.mValue.mCMYK.mCyan = cyan;\r\n    color.mValue.mCMYK.mMagenta = magenta;\r\n    color.mValue.mCMYK.mYellow = yellow;\r\n    color.mValue.mCMYK.mBlack = black;\r\n    return color;\r\n  }\r\n\r\n  Color Color::createCMYK(ColorName colorName){\r\n    Color color;\r\n    color.mType = ColorTypeCMYK;\r\n\r\n    auto &value = colorNameToRGB[colorName];\r\n    float const dr = (float) value[0] \/ 255.f;\r\n\t  float const dg = (float) value[1] \/ 255.f;\r\n\t  float const db = (float) value[2] \/ 255.f;\r\n\r\n    if (value[0] == 0 && value[1] == 0 && value[2] == 0){\r\n\t    color.mValue.mCMYK.mCyan = 0.f;\r\n\t    color.mValue.mCMYK.mMagenta = 0.f;\r\n\t    color.mValue.mCMYK.mYellow = 0.f;\r\n\t    color.mValue.mCMYK.mBlack = 1.f;\r\n    }\r\n    else{\r\n  \t  float const k = 1.f - std::max(std::max(dr, dg), db);\r\n\t    float const c = (1.f - dr - k) \/ (1.f - k);\r\n\t    float const m = (1.f - dg - k) \/ (1.f - k);\r\n\t    float const y = (1.f - db - k) \/ (1.f - k);\r\n\r\n\t    color.mValue.mCMYK.mCyan = (1.f - dr - k) \/ (1.f - k);\r\n\t    color.mValue.mCMYK.mMagenta = (1.f - dg - k) \/ (1.f - k);\r\n\t    color.mValue.mCMYK.mYellow = (1.f - db - k) \/ (1.f - k);\r\n\t    color.mValue.mCMYK.mBlack = 1.f - std::max(std::max(dr, dg), db);\r\n    }\r\n\r\n    return color;\r\n  }\r\n\r\n  Color Color::createGray(float gray){\r\n    Color color;\r\n    color.mType = ColorTypeGray;\r\n    color.mValue.mGray.mGray = gray;\r\n    return color;\r\n  }\r\n\r\n  Color Color::createGray(ColorName colorName){\r\n    auto &value = colorNameToRGB[colorName];\r\n    float const dr = (float) value[0] \/ 255.f;\r\n\t  float const dg = (float) value[1] \/ 255.f;\r\n\t  float const db = (float) value[2] \/ 255.f;\r\n\r\n    return createGray(0.21f * dr + 0.72f * dg + 0.07f * db);\r\n  }\r\n\r\n  Color Color::createIndex(uint32_t i){\r\n    Color color;\r\n    color.mType = ColorTypeIndex;\r\n    color.mValue.mIndex.mIndex = i;\r\n    return color;\r\n  }\r\n}\r\n","avg_line_length":45.8991935484,"max_line_length":81,"alphanum_fraction":0.5358868488,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8776,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Intel","BSD-3-Clause","MIT"],"max_stars_count":1.0,"content":"\/*\n* Copyright (c) 2017, Intel Corporation\n*\n* Permission is hereby granted, free of charge, to any person obtaining a\n* copy of this software and associated documentation files (the \"Software\"),\n* to deal in the Software without restriction, including without limitation\n* the rights to use, copy, modify, merge, publish, distribute, sublicense,\n* and\/or sell copies of the Software, and to permit persons to whom the\n* Software is furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included\n* in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n* OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\/\/!\n\/\/! \\file   mhw_vdbox_huc_hwcmd_g10_X.cpp\n\/\/! \\brief  Auto-generated definitions for MHW commands and states.\n\/\/!\n\n#include \"mhw_vdbox_huc_hwcmd_g10_X.h\"\n#include \"mos_utilities.h\"\n\nmhw_vdbox_huc_g10_X::HUC_PIPE_MODE_SELECT_CMD::HUC_PIPE_MODE_SELECT_CMD()\n{\n    DW0.Value                                        = 0;        \n    DW0.DwordLength                                  = GetOpLength(dwSize);\n    DW0.MediaInstructionCommand                      = MEDIA_INSTRUCTION_COMMAND_HUCPIPEMODESELECT;\n    DW0.MediaInstructionOpcode                       = MEDIA_INSTRUCTION_OPCODE_CODECENGINENAME;\n    DW0.PipelineType                                 = PIPELINE_TYPE_UNNAMED2;\n    DW0.CommandType                                  = COMMAND_TYPE_PARALLELVIDEOPIPE;\n\n    DW1.Value                                        = 0;        \n    DW1.IndirectStreamOutEnable                      = INDIRECT_STREAM_OUT_ENABLE_DISABLEINDIRECTSTREAMOUT;\n\n    DW2.Value                                        = 0;        \n    DW2.MediaSoftResetCounterPer1000Clocks           = MEDIA_SOFT_RESET_COUNTER_PER_1000_CLOCKS_DISABLE;\n\n}\n\nmhw_vdbox_huc_g10_X::GRAPHICSADDRESS63_6_CMD::GRAPHICSADDRESS63_6_CMD()\n{\n    DW0_1.Value[0] = DW0_1.Value[1]                  = 0;        \n\n}\n\nmhw_vdbox_huc_g10_X::HUC_IMEM_STATE_CMD::HUC_IMEM_STATE_CMD()\n{\n    DW0.Value                                        = 0;        \n    DW0.DwordLength                                  = GetOpLength(dwSize);\n    DW0.MediaInstructionCommand                      = MEDIA_INSTRUCTION_COMMAND_HUCIMEMSTATE;\n    DW0.MediaInstructionOpcode                       = MEDIA_INSTRUCTION_OPCODE_CODECENGINENAME;\n    DW0.PipelineType                                 = PIPELINE_TYPE_UNNAMED2;\n    DW0.CommandType                                  = COMMAND_TYPE_PARALLELVIDEOPIPE;\n\n    DW1.Value                                        = 0;        \n\n    DW2.Value                                        = 0;        \n\n    DW3.Value                                        = 0;        \n    DW3.ArbitrationPriorityControl                   = ARBITRATION_PRIORITY_CONTROL_HIGHESTPRIORITY;\n\n    DW4.Value                                        = 0;        \n    DW4.HucFirmwareDescriptor                        = HUC_FIRMWARE_DESCRIPTOR_UNNAMED0;\n\n}\n\nmhw_vdbox_huc_g10_X::HUC_DMEM_STATE_CMD::HUC_DMEM_STATE_CMD()\n{\n    DW0.Value                                        = 0;        \n    DW0.DwordLength                                  = GetOpLength(dwSize);\n    DW0.MediaInstructionCommand                      = MEDIA_INSTRUCTION_COMMAND_HUCDMEMSTATE;\n    DW0.MediaInstructionOpcode                       = MEDIA_INSTRUCTION_OPCODE_CODECENGINENAME;\n    DW0.PipelineType                                 = PIPELINE_TYPE_UNNAMED2;\n    DW0.CommandType                                  = COMMAND_TYPE_PARALLELVIDEOPIPE;\n\n    DW3.Value                                        = 0;        \n\n    DW4.Value                                        = 0;        \n\n    DW5.Value                                        = 0;        \n\n}\n\nmhw_vdbox_huc_g10_X::HUC_CFG_STATE_CMD::HUC_CFG_STATE_CMD()\n{\n    DW0.Value                                        = 0;        \n    DW0.DwordLength                                  = GetOpLength(dwSize);\n    DW0.MediaInstructionCommand                      = MEDIA_INSTRUCTION_COMMAND_HUCCFGSTATE;\n    DW0.MediaInstructionOpcode                       = MEDIA_INSTRUCTION_OPCODE_CODECENGINENAME;\n    DW0.PipelineType                                 = PIPELINE_TYPE_UNNAMED2;\n    DW0.CommandType                                  = COMMAND_TYPE_PARALLELVIDEOPIPE;\n\n    DW1.Value                                        = 0;        \n    DW1.P24CMinuteia                                 = P24C_MINUTEIA_NORMALOPERATION;\n\n}\n\nmhw_vdbox_huc_g10_X::HUC_VIRTUAL_ADDR_REGION_CMD::HUC_VIRTUAL_ADDR_REGION_CMD()\n{\n    DW2.Value                                        = 0;        \n    DW2.ArbitrationPriorityControl                   = ARBITRATION_PRIORITY_CONTROL_HIGHESTPRIORITY;\n\n}\n\nmhw_vdbox_huc_g10_X::HUC_VIRTUAL_ADDR_STATE_CMD::HUC_VIRTUAL_ADDR_STATE_CMD()\n{\n    DW0.Value                                        = 0;        \n    DW0.DwordLength                                  = GetOpLength(dwSize);\n    DW0.MediaInstructionCommand                      = MEDIA_INSTRUCTION_COMMAND_HUCVIRTUALADDRSTATE;\n    DW0.MediaInstructionOpcode                       = MEDIA_INSTRUCTION_OPCODE_CODECENGINENAME;\n    DW0.PipelineType                                 = PIPELINE_TYPE_UNNAMED2;\n    DW0.CommandType                                  = COMMAND_TYPE_PARALLELVIDEOPIPE;\n\n}\n\nmhw_vdbox_huc_g10_X::HUC_IND_OBJ_BASE_ADDR_STATE_CMD::HUC_IND_OBJ_BASE_ADDR_STATE_CMD()\n{\n    DW0.Value                                        = 0;        \n    DW0.DwordLength                                  = GetOpLength(dwSize);\n    DW0.MediaInstructionCommand                      = MEDIA_INSTRUCTION_COMMAND_HUCINDOBJBASEADDRSTATE;\n    DW0.MediaInstructionOpcode                       = MEDIA_INSTRUCTION_OPCODE_CODECENGINENAME;\n    DW0.PipelineType                                 = PIPELINE_TYPE_UNNAMED2;\n    DW0.CommandType                                  = COMMAND_TYPE_PARALLELVIDEOPIPE;\n\n    DW1_2.Value[0] = DW1_2.Value[1]                  = 0;        \n\n    DW3.Value                                        = 0;        \n\n    DW4_5.Value[0] = DW4_5.Value[1]                  = 0;        \n\n    DW6_7.Value[0] = DW6_7.Value[1]                  = 0;        \n\n    DW8.Value                                        = 0;        \n\n    DW9_10.Value[0] = DW9_10.Value[1]                = 0;        \n\n}\n\nmhw_vdbox_huc_g10_X::HUC_STREAM_OBJECT_CMD::HUC_STREAM_OBJECT_CMD()\n{\n    DW0.Value                                        = 0;        \n    DW0.DwordLength                                  = GetOpLength(dwSize);\n    DW0.MediaInstructionCommand                      = MEDIA_INSTRUCTION_COMMAND_HUCSTREAMOBJECT;\n    DW0.MediaInstructionOpcode                       = MEDIA_INSTRUCTION_OPCODE_CODECENGINENAME;\n    DW0.PipelineType                                 = PIPELINE_TYPE_UNNAMED2;\n    DW0.CommandType                                  = COMMAND_TYPE_PARALLELVIDEOPIPE;\n\n    DW1.Value                                        = 0;        \n\n    DW2.Value                                        = 0;        \n    DW2.HucProcessing                                = 0;\n\n    DW3.Value                                        = 0;        \n\n    DW4.Value                                        = 0;        \n    DW4.StartCodeSearchEngine                        = START_CODE_SEARCH_ENGINE_DISABLE;\n    DW4.EmulationPreventionByteRemoval               = EMULATION_PREVENTION_BYTE_REMOVAL_DISABLE;\n    DW4.StreamOut                                    = STREAM_OUT_DISABLE;\n    DW4.Drmlengthmode                                = DRMLENGTHMODE_STARTCODEMODE;\n    DW4.HucBitstreamEnable                           = HUC_BITSTREAM_ENABLE_DISABLE;\n\n}\n\nmhw_vdbox_huc_g10_X::HUC_START_CMD::HUC_START_CMD()\n{\n    DW0.Value                                        = 0;        \n    DW0.DwordLength                                  = GetOpLength(dwSize);\n    DW0.MediaInstructionCommand                      = MEDIA_INSTRUCTION_COMMAND_HUCSTART;\n    DW0.MediaInstructionOpcode                       = MEDIA_INSTRUCTION_OPCODE_CODECENGINENAME;\n    DW0.PipelineType                                 = PIPELINE_TYPE_UNNAMED2;\n    DW0.CommandType                                  = COMMAND_TYPE_PARALLELVIDEOPIPE;\n\n    DW1.Value                                        = 0;        \n    DW1.Laststreamobject                             = LASTSTREAMOBJECT_NOTLASTSTREAMOBJECT;\n\n}\n\n","avg_line_length":47.4378378378,"max_line_length":107,"alphanum_fraction":0.5299680948,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3247,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["0BSD"],"max_stars_count":7.0,"content":"\/\/these functions transform internal accesses to bus accesses, and handle conversions:\n\/\/* A1-A23 are passed to the bus\n\/\/* A0 in word mode is ignored, and drives both UDS and LDS\n\/\/* A0 in byte mode drives either UDS or LDS\n\/\/* upper = \/UDS (1 = selected; eg \/UDS is inverted)\n\/\/* lower = \/LDS (1 = selected; eg \/LDS is inverted)\n\/\/* \/UDS is where A0=0 and maps to D8-D15\n\/\/* \/LDS is where A0=1 and maps to D0-D7\n\ntemplate<> auto M68K::read<Byte>(uint32 address) -> uint32 {\n  wait(4);\n  if(address & 1) {\n    return read(0, 1, address & ~1).byte(0);  \/* \/LDS *\/\n  } else {\n    return read(1, 0, address & ~1).byte(1);  \/* \/UDS *\/\n  }\n}\n\ntemplate<> auto M68K::read<Word>(uint32 address) -> uint32 {\n  wait(4);\n  return read(1, 1, address & ~1);\n}\n\ntemplate<> auto M68K::read<Long>(uint32 address) -> uint32 {\n  wait(4);\n  uint32 data = read(1, 1, address + 0 & ~1) << 16;\n  wait(4);\n  return data | read(1, 1, address + 2 & ~1) <<  0;\n}\n\n\/\/\n\ntemplate<> auto M68K::write<Byte>(uint32 address, uint32 data) -> void {\n  wait(4);\n  if(address & 1) {\n    return write(0, 1, address & ~1, data << 8 | (uint8)data << 0);  \/* \/LDS *\/\n  } else {\n    return write(1, 0, address & ~1, data << 8 | (uint8)data << 0);  \/* \/UDS *\/\n  }\n}\n\ntemplate<> auto M68K::write<Word>(uint32 address, uint32 data) -> void {\n  wait(4);\n  return write(1, 1, address & ~1, data);\n}\n\ntemplate<> auto M68K::write<Long>(uint32 address, uint32 data) -> void {\n  wait(4);\n  write(1, 1, address + 0 & ~1, data >> 16);\n  wait(4);\n  write(1, 1, address + 2 & ~1, data >>  0);\n}\n\n\/\/\n\ntemplate<> auto M68K::write<Byte, Reverse>(uint32 address, uint32 data) -> void {\n  wait(4);\n  if(address & 1) {\n    return write(0, 1, address & ~1, data << 8 | (uint8)data << 0);  \/* \/LDS *\/\n  } else {\n    return write(1, 0, address & ~1, data << 8 | (uint8)data << 0);  \/* \/UDS *\/\n  }\n}\n\ntemplate<> auto M68K::write<Word, Reverse>(uint32 address, uint32 data) -> void {\n  wait(4);\n  return write(1, 1, address & ~1, data);\n}\n\ntemplate<> auto M68K::write<Long, Reverse>(uint32 address, uint32 data) -> void {\n  wait(4);\n  write(1, 1, address + 2 & ~1, data >>  0);\n  wait(4);\n  write(1, 1, address + 0 & ~1, data >> 16);\n}\n\n\/\/\n\ntemplate<> auto M68K::extension<Byte>() -> uint32 {\n  wait(4);\n  r.ir  = r.irc;\n  r.irc = read(1, 1, r.pc & ~1);\n  r.pc += 2;\n  return (uint8)r.ir;\n}\n\ntemplate<> auto M68K::extension<Word>() -> uint32 {\n  wait(4);\n  r.ir  = r.irc;\n  r.irc = read(1, 1, r.pc & ~1);\n  r.pc += 2;\n  return r.ir;\n}\n\ntemplate<> auto M68K::extension<Long>() -> uint32 {\n  auto hi = extension<Word>();\n  auto lo = extension<Word>();\n  return hi << 16 | lo << 0;\n}\n\n\/\/\n\nauto M68K::prefetch() -> uint16 {\n  wait(4);\n  r.ir  = r.irc;\n  r.irc = read(1, 1, r.pc & ~1);\n  r.pc += 2;\n  return r.ir;\n}\n\n\/\/take the prefetched value without reloading the prefetch.\n\/\/this is used by instructions such as JMP and JSR.\n\nauto M68K::prefetched() -> uint16 {\n  r.ir  = r.irc;\n  r.irc = 0x0000;\n  r.pc += 2;\n  return r.ir;\n}\n\n\/\/\n\ntemplate<uint Size> auto M68K::pop() -> uint32 {\n  auto data = read<Size>((uint32)r.a[7]);\n  r.a[7] += bytes<Size>();\n  return data;\n}\n\n\/\/\n\ntemplate<uint Size> auto M68K::push(uint32 data) -> void {\n  r.a[7] -= bytes<Size>();\n  return write<Size, Reverse>((uint32)r.a[7], data);\n}\n","avg_line_length":24.0518518519,"max_line_length":86,"alphanum_fraction":0.5796119495,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1453,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["AML"],"max_stars_count":5.0,"content":"\/*\n* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n* its licensors.\n*\n* For complete copyright and license terms please see the LICENSE at the root of this\n* distribution (the \"License\"). All use of this software is governed by the License,\n* or, if provided, by the license below or the license accompanying this file. Do not\n* remove or modify any license notices. This file is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n*\n*\/\n#include \"stdafx.h\"\n#include <AzTest\/AzTest.h>\n#include <Mocks\/ITimerMock.h>\n#include <Mocks\/ICryPakMock.h>\n#include <Mocks\/IConsoleMock.h>\n#include <AzCore\/Memory\/OSAllocator.h>\n\nusing ::testing::NiceMock;\n\nclass CryMovieTestEnvironment\n    : public AZ::Test::ITestEnvironment\n{\npublic:\n    AZ_TEST_CLASS_ALLOCATOR(CryMovieTestEnvironment);\n\n    virtual ~CryMovieTestEnvironment()\n    {}\n\nprotected:\n    void SetupEnvironment() override\n    {\n        m_stubEnv.pTimer = &m_stubTimer;\n        m_stubEnv.pCryPak = &m_stubPak;\n        m_stubEnv.pConsole = &m_stubConsole;\n        gEnv = &m_stubEnv;\n    }\n\n    void TeardownEnvironment() override\n    {}\n\nprivate:\n    SSystemGlobalEnvironment m_stubEnv;\n    NiceMock<TimerMock> m_stubTimer;\n    NiceMock<CryPakMock> m_stubPak;\n    NiceMock<ConsoleMock> m_stubConsole;\n};\n\nAZ_UNIT_TEST_HOOK(new CryMovieTestEnvironment)\n\nTEST(CryMovieSanityTest, Sanity)\n{\n    EXPECT_EQ(1, 1);\n}\n","avg_line_length":26.4181818182,"max_line_length":85,"alphanum_fraction":0.7322780454,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5253,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":1.0,"content":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  ThreadsPTHREADs.cpp - Implements the functions in Threads.h specifically\n\/\/  for any platform with posix style threads\n\/\/\n\/\/  Author: Aravind Krishnaswamy\n\/\/  Date of Birth: May 07, 2002\n\/\/  Tabs: 4\n\/\/  Comments:\n\/\/\n\/\/  License Information: Please see the attached LICENSE.TXT file\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"pch.h\"\n\n#ifndef WIN32\n\n#include \"Threads.h\"\n#include \"..\/..\/Interfaces\/ILog.h\"\n#include \"..\/RTime.h\"\n#ifndef NO_PTHREAD_SUPPORT\n\t#include <pthread.h>\n\t#include <semaphore.h>\n#endif\n\nusing namespace RISE;\n\nunsigned int Threading::riseCreateThread( THREAD_FUNC pFunc, void* pParam, unsigned int initial_stack_size, void* thread_attributes, RISETHREADID* threadid )\n{\n#ifdef NO_PTHREAD_SUPPORT\n\t\/\/ Just execute the code and forge it\n\tGlobalLog()->PrintEasyInfo( \"riseCreateThread:: NO PTHREAD support was compiled, simply executing code\" );\n\t(*pFunc)( pParam );\n\treturn 1;\n#else\n\tpthread_t\t\t\ttid;\n\tpthread_attr_t\t\tattr;\n\n\tpthread_attr_init( &attr );\n\tpthread_create( &tid, &attr, pFunc, pParam );\n\n\tif( threadid ) {\n\t\t*threadid = (RISETHREADID)tid;\n\t}\n\n\/\/\tGlobalLog()->PrintEx( eLog_Info, \"Starting Thread ID:%d\", tid );\n\treturn 1;\n#endif\n}\n\nunsigned int Threading::riseWaitUntilThreadFinishes( RISETHREADID threadid, void* threadreturncode )\n{\n#ifdef NO_PTHREAD_SUPPORT\n\tGlobalLog()->PrintEasyInfo( \"riseWaitUntilThreadFinishes:: NO PTHREAD support was compiled, nothing to do\" );\n\treturn 1;\n#else\n\tpthread_t\t\t\ttid = (pthread_t)threadid;\n\n\/\/\tGlobalLog()->PrintEx( eLog_Info, \"Waiting Thread ID:%d\", tid );\n\n\tpthread_join( tid, &threadreturncode );\n\treturn 1;\n#endif\n}\n\nRISETHREADID Threading::riseGetCurrentThread( )\n{\n#ifdef NO_PTHREAD_SUPPORT\n\treturn 0;\n#else\n\treturn (RISETHREADID)pthread_self();\n#endif\n}\n\nvoid Threading::riseSuspendThread( RISETHREADID threadid )\n{\n#ifndef NO_PTHREAD_SUPPORT\n\/\/\tpthread_suspend( (pthread_t)threadid );\n\tGlobalLog()->PrintEasyWarning( \"POSIX threads do not support suspend, don't use it\" );\n#endif\n}\n\nvoid Threading::riseResumeThread( RISETHREADID threadid )\n{\n#ifndef NO_PTHREAD_SUPPORT\n\/\/\tpthread_wakeup( (pthread_t)threadid );\n\tGlobalLog()->PrintEasyWarning( \"POSIX threads do not support resume, don't use it\" );\n#endif\n}\n\nRISEMUTEX Threading::riseCreateMutex( )\n{\n#ifndef NO_PTHREAD_SUPPORT\n\tpthread_mutex_t*\tmutex = new pthread_mutex_t;\n\/\/\tGlobalLog()->PrintNew( mutex, __FILE__, __LINE__, \"mutex\" );\n\tpthread_mutex_init( mutex, 0 );\n\treturn mutex;\n#else\n\treturn 0;\n#endif\n}\n\nvoid Threading::riseDestroyMutex( RISEMUTEX mut )\n{\n#ifndef NO_PTHREAD_SUPPORT\n\tpthread_mutex_t*\tmutex = (pthread_mutex_t*)mut;\n\tpthread_mutex_destroy( mutex );\n\/\/\tGlobalLog()->PrintDelete( mutex, __FILE__, __LINE__ );\n\tdelete mutex;\n#endif\n}\n\nvoid Threading::riseMutexLock( RISEMUTEX mut )\n{\n#ifndef NO_PTHREAD_SUPPORT\n\tpthread_mutex_t*\tmutex = (pthread_mutex_t*)mut;\n\tpthread_mutex_lock( mutex );\n#endif\n}\n\nbool Threading::riseMutexTryLock( RISEMUTEX mut )\n{\n#ifndef NO_PTHREAD_SUPPORT\n\tpthread_mutex_t*\tmutex = (pthread_mutex_t*)mut;\n\treturn !pthread_mutex_trylock( mutex );\n#else\n\treturn false;\n#endif\n}\n\nvoid Threading::riseMutexUnlock( RISEMUTEX mut )\n{\n#ifndef NO_PTHREAD_SUPPORT\n\tpthread_mutex_t*\tmutex = (pthread_mutex_t*)mut;\n\tpthread_mutex_unlock( mutex );\n#endif\n}\n\n#ifndef NO_PTHREAD_SUPPORT\n\/\/ The pthread version of sleep is done by creating a \n\/\/ condition object and a mutex\nnamespace RISE {\n\tstruct PTHREAD_SLEEP\n\t{\n\t\tpthread_cond_t* cond;\n\t\tpthread_mutex_t* mutex;\n\t};\n}\n#endif\n\nRISESLEEP Threading::riseCreateSleep( )\n{\n#ifndef NO_PTHREAD_SUPPORT\n\tPTHREAD_SLEEP*\tsleep = new PTHREAD_SLEEP;\n\tsleep->mutex = new pthread_mutex_t;\n\tsleep->cond = new pthread_cond_t;\n\tpthread_mutex_init( sleep->mutex, 0 );\n\tpthread_cond_init( sleep->cond, 0 );\n\treturn (void*)sleep;\n#endif\n\treturn 0;\n}\n\nvoid Threading::riseSleep( RISESLEEP risesleep, unsigned int duration )\n{\n#ifndef NO_PTHREAD_SUPPORT\n\tPTHREAD_SLEEP*\tsleep = (PTHREAD_SLEEP*)risesleep;\n\triseMutexLock( sleep->mutex );\n\t\/\/ Create the time structure\n\tunsigned int ms = GetMilliseconds();\n\tms += duration;\n\ttimespec\tts;\n\tts.tv_sec = ms \/ 1000;\n\tts.tv_nsec = (ms % 1000) * 1000000;\n\tpthread_cond_timedwait( sleep->cond, sleep->mutex, &ts );\n\triseMutexUnlock( sleep->mutex );\n#endif\n}\n\nvoid Threading::riseDestroySleep( RISESLEEP risesleep )\n{\n#ifndef NO_PTHREAD_SUPPORT\n\tPTHREAD_SLEEP*\tsleep = (PTHREAD_SLEEP*)risesleep;\n\tpthread_mutex_destroy( sleep->mutex );\n\tpthread_cond_destroy( sleep->cond );\n\tdelete sleep->mutex;\n\tdelete sleep->cond;\n\tdelete sleep;\n#endif\n}\n\nRISESEMAPHORE Threading::riseCreateSemaphore(\n\tint value\n\t)\n{\n#ifndef NO_PTHREAD_SUPPORT\n\tsem_t* sem = new sem_t;\n\tsem_init( sem, 0, value );\n\treturn (void*)sem;\n#endif\n\treturn 0;\n}\n\nvoid Threading::riseDestroySemaphore(\n\tRISESEMAPHORE sem\n\t)\n{\n#ifndef NO_PTHREAD_SUPPORT\n\tsem_t* pSem = (sem_t*)sem;\n\tsem_destroy( pSem );\n\tdelete pSem;\n#endif\n}\n\nvoid Threading::riseSemaphoreAcquire(\n\tRISESEMAPHORE sem\n\t)\n{\n#ifndef NO_PTHREAD_SUPPORT\n\tsem_t* pSem = (sem_t*)sem;\n\tsem_wait( pSem );\n#endif\n}\n\nvoid Threading::riseSemaphoreRelease(\n\tRISESEMAPHORE sem,\n\tint count\n\t)\n{\n#ifndef NO_PTHREAD_SUPPORT\n\tsem_t* pSem = (sem_t*)sem;\n\tsem_post( pSem );\n#endif\n}\n\n#endif\n\n","avg_line_length":21.9790794979,"max_line_length":157,"alphanum_fraction":0.724538359,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8906,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":4054.0,"content":"\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"updateoperation.h\"\n#include <vespa\/document\/fieldvalue\/document.h>\n#include <vespa\/document\/update\/documentupdate.h>\n#include <vespa\/storageapi\/message\/bucket.h>\n#include <vespa\/storageapi\/message\/persistence.h>\n#include <vespa\/storage\/distributor\/distributormetricsset.h>\n#include <vespa\/storage\/distributor\/distributor_bucket_space.h>\n#include <vespa\/vdslib\/state\/clusterstate.h>\n#include <vespa\/vespalib\/util\/stringfmt.h>\n\n#include <vespa\/log\/log.h>\n\nLOG_SETUP(\".distributor.callback.doc.update\");\n\nusing document::BucketSpace;\n\nnamespace storage::distributor {\n\nUpdateOperation::UpdateOperation(const DistributorNodeContext& node_ctx,\n                                 DistributorStripeOperationContext& op_ctx,\n                                 DistributorBucketSpace& bucketSpace,\n                                 const std::shared_ptr<api::UpdateCommand>& msg,\n                                 std::vector<BucketDatabase::Entry> entries,\n                                 UpdateMetricSet& metric)\n    : Operation(),\n      _trackerInstance(metric, std::make_shared<api::UpdateReply>(*msg),\n                       node_ctx, op_ctx, msg->getTimestamp()),\n      _tracker(_trackerInstance),\n      _msg(msg),\n      _entries(std::move(entries)),\n      _new_timestamp(_msg->getTimestamp()),\n      _is_auto_create_update(_msg->getUpdate()->getCreateIfNonExistent()),\n      _node_ctx(node_ctx),\n      _bucketSpace(bucketSpace),\n      _newestTimestampLocation(),\n      _infoAtSendTime(),\n      _metrics(metric)\n{\n}\n\nbool\nUpdateOperation::anyStorageNodesAvailable() const\n{\n    const auto& clusterState(_bucketSpace.getClusterState());\n    const auto storageNodeCount(\n            clusterState.getNodeCount(lib::NodeType::STORAGE));\n\n    for (uint16_t i = 0; i < storageNodeCount; ++i) {\n        const auto& ns(clusterState.getNodeState(\n                lib::Node(lib::NodeType::STORAGE, i)));\n        if (ns.getState() == lib::State::UP\n            || ns.getState() == lib::State::RETIRED)\n        {\n            return true;\n        }\n    }\n    return false;\n}\n\nvoid\nUpdateOperation::onStart(DistributorStripeMessageSender& sender)\n{\n    LOG(debug, \"Received UPDATE %s for bucket %\" PRIx64,\n        _msg->getDocumentId().toString().c_str(),\n        _node_ctx.bucket_id_factory().getBucketId(\n                _msg->getDocumentId()).getRawId());\n\n    \/\/ Don't do anything if all nodes are down.\n    if (!anyStorageNodesAvailable()) {\n        _tracker.fail(sender,\n                      api::ReturnCode(api::ReturnCode::NOT_CONNECTED,\n                                      \"Can't store document: No storage nodes \"\n                                      \"available\"));\n        return;\n    }\n\n    if (_entries.empty()) {\n        document::BucketId bucketId(_node_ctx.bucket_id_factory().getBucketId(_msg->getDocumentId()));\n        _bucketSpace.getBucketDatabase().getParents(bucketId, _entries);\n    }\n\n    if (_entries.empty()) {\n        _tracker.fail(sender,\n                      api::ReturnCode(api::ReturnCode::OK,\n                                      \"No buckets found for given document update\"));\n        return;\n    }\n\n    \/\/ An UpdateOperation should only be started iff all replicas are consistent\n    \/\/ with each other, so sampling a single replica should be equal to sampling them all.\n    assert(_entries[0].getBucketInfo().getNodeCount() > 0); \/\/ Empty buckets are not allowed\n    _infoAtSendTime = _entries[0].getBucketInfo().getNodeRef(0).getBucketInfo();\n\n    \/\/ FIXME(vekterli): this loop will happily update all replicas in the\n    \/\/ bucket sub-tree, but there is nothing here at all which will fail the\n    \/\/ update if we cannot satisfy a desired replication level (not even for\n    \/\/ n-of-m operations).\n    for (const auto& entry : _entries) {\n        LOG(spam, \"Found bucket %s\", entry.toString().c_str());\n\n        const std::vector<uint16_t>& nodes = entry->getNodes();\n\n        std::vector<MessageTracker::ToSend> messages;\n\n        for (uint16_t node : nodes) {\n            auto command = std::make_shared<api::UpdateCommand>(\n                    document::Bucket(_msg->getBucket().getBucketSpace(), entry.getBucketId()),\n                    _msg->getUpdate(),\n                    _msg->getTimestamp());\n            copyMessageSettings(*_msg, *command);\n            command->setOldTimestamp(_msg->getOldTimestamp());\n            command->setCondition(_msg->getCondition());\n            messages.emplace_back(std::move(command), node);\n        }\n\n        _tracker.queueMessageBatch(messages);\n    }\n\n    _tracker.flushQueue(sender);\n    _msg = std::shared_ptr<api::UpdateCommand>();\n};\n\nvoid\nUpdateOperation::onReceive(DistributorStripeMessageSender& sender,\n                          const std::shared_ptr<api::StorageReply> & msg)\n{\n    auto& reply = static_cast<api::UpdateReply&>(*msg);\n\n    if (msg->getType() == api::MessageType::UPDATE_REPLY) {\n        uint16_t node = _tracker.handleReply(reply);\n\n        if (node != (uint16_t)-1) {\n            if (reply.getResult().getResult() == api::ReturnCode::OK) {\n                _results.emplace_back(reply.getBucketId(), reply.getBucketInfo(),\n                                      adjusted_received_old_timestamp(reply.getOldTimestamp()), node);\n            }\n\n            if (_tracker.getReply().get()) {\n                auto& replyToSend = static_cast<api::UpdateReply&>(*_tracker.getReply());\n\n                uint64_t oldTs = 0;\n                uint64_t goodNode = 0;\n\n                \/\/ Find the highest old timestamp.\n                for (uint32_t i = 0; i < _results.size(); i++) {\n                    if (_results[i].oldTs > oldTs) {\n                        oldTs = _results[i].oldTs;\n                        goodNode = i;\n                    }\n                }\n\n                replyToSend.setOldTimestamp(oldTs);\n\n                for (uint32_t i = 0; i < _results.size(); i++) {\n                    if (_results[i].oldTs < oldTs) {\n                        LOG(error, \"Update operation for '%s' in bucket %s updated documents with different timestamps. \"\n                                   \"This should not happen and may indicate undetected replica divergence. \"\n                                   \"Found ts=%\" PRIu64 \" on node %u, ts=%\" PRIu64 \" on node %u\",\n                                   reply.getDocumentId().toString().c_str(),\n                                   reply.getBucket().toString().c_str(),\n                                   _results[i].oldTs, _results[i].nodeId,\n                                   _results[goodNode].oldTs, _results[goodNode].nodeId);\n                        _metrics.diverging_timestamp_updates.inc();\n\n                        replyToSend.setNodeWithNewestTimestamp(_results[goodNode].nodeId);\n                        _newestTimestampLocation.first  = _results[goodNode].bucketId;\n                        _newestTimestampLocation.second = _results[goodNode].nodeId;\n\n                        LOG(warning, \"Bucket info prior to update operation was: %s. After update, \"\n                                     \"info on node %u is %s, info on node %u is %s\",\n                                     _infoAtSendTime.toString().c_str(),\n                                     _results[i].nodeId, _results[i].bucketInfo.toString().c_str(),\n                                     _results[goodNode].nodeId, _results[goodNode].bucketInfo.toString().c_str());\n                        break;\n                    }\n                }\n            }\n\n            _tracker.updateFromReply(sender, reply, node);\n        }\n    } else {\n        _tracker.receiveReply(sender, static_cast<api::BucketInfoReply&>(*msg));\n    }\n}\n\nvoid\nUpdateOperation::onClose(DistributorStripeMessageSender& sender)\n{\n    _tracker.fail(sender, api::ReturnCode(api::ReturnCode::ABORTED, \"Process is shutting down\"));\n}\n\n\/\/ The backend behavior of \"create-if-missing\" updates is to return the timestamp of the\n\/\/ _new_ update operation if the document was created from scratch. The two-phase update\n\/\/ operation logic auto-detects unexpected inconsistencies and tries to reconcile\n\/\/ replicas by forcing document versions to that assumed most likely to preserve the history\n\/\/ of the document. Normally this is the highest updated timestamp, so to avoid newly created\n\/\/ replicas from overwriting updates that actually updated existing document versions, treat\n\/\/ a received timestamp == new timestamp as if it were actually a timestamp of zero.\n\/\/ This mirrors the received timestamp for regular updates that do not find a matching document.\napi::Timestamp UpdateOperation::adjusted_received_old_timestamp(api::Timestamp old_ts_from_node) const {\n    if (!_is_auto_create_update) {\n        return old_ts_from_node;\n    }\n    return (old_ts_from_node != _new_timestamp) ? old_ts_from_node : api::Timestamp(0);\n}\n\n}\n","avg_line_length":42.4095238095,"max_line_length":121,"alphanum_fraction":0.605097687,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2468,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/***************************************************************************\n  qgsrangefieldformatter.cpp - QgsRangeFieldFormatter\n\n ---------------------\n begin                : 01\/02\/2018\n copyright            : (C) 2018 by Alessandro Pasotti\n email                : elpaso at itopen dot it\n ***************************************************************************\n *                                                                         *\n *   This program is free software; you can redistribute it and\/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n ***************************************************************************\/\n\n#include <QLocale>\n\n#include \"qgsrangefieldformatter.h\"\n\n#include \"qgssettings.h\"\n#include \"qgsfield.h\"\n#include \"qgsvectorlayer.h\"\n#include \"qgsapplication.h\"\n\n\nQString QgsRangeFieldFormatter::id() const\n{\n  return QStringLiteral( \"Range\" );\n}\n\nQString QgsRangeFieldFormatter::representValue( QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value ) const\n{\n  Q_UNUSED( cache )\n  Q_UNUSED( config )\n\n  if ( value.isNull() )\n  {\n    return QgsApplication::nullRepresentation();\n  }\n\n  QString result;\n\n  const QgsField field = layer->fields().at( fieldIndex );\n\n  if ( field.type() == QVariant::Double &&\n       config.contains( QStringLiteral( \"Precision\" ) ) &&\n       value.isValid( ) )\n  {\n    bool ok;\n    double val( value.toDouble( &ok ) );\n    if ( ok )\n    {\n      int precision( config[ QStringLiteral( \"Precision\" ) ].toInt( &ok ) );\n      if ( ok )\n      {\n        \/\/ TODO: make the format configurable!\n        result = QLocale().toString( val, 'f', precision );\n      }\n    }\n  }\n  else if ( ( field.type() == QVariant::Int ) &&\n            value.isValid( ) )\n  {\n    bool ok;\n    double val( value.toInt( &ok ) );\n    if ( ok )\n    {\n      result =  QLocale().toString( val, 'f', 0 );\n    }\n  }\n  else if ( ( field.type() == QVariant::LongLong ) &&\n            value.isValid( ) )\n  {\n    bool ok;\n    double val( value.toLongLong( &ok ) );\n    if ( ok )\n    {\n      result =  QLocale().toString( val, 'f', 0 );\n    }\n  }\n  else\n  {\n    result = value.toString();\n  }\n  return result;\n}\n","avg_line_length":28.0454545455,"max_line_length":166,"alphanum_fraction":0.494732577,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3398,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":1.0,"content":"\/**\n *\tPlatform Specification Implementation\n *\tNana C++ Library(http:\/\/www.nanapro.org)\n *\tCopyright(C) 2003-2018 Jinhao(cnjinhao@hotmail.com)\n *\n *\tDistributed under the Boost Software License, Version 1.0.\n *\t(See accompanying file LICENSE_1_0.txt or copy at\n *\thttp:\/\/www.boost.org\/LICENSE_1_0.txt)\n *\n *\t@file: nana\/detail\/platform_spec.cpp\n *\n *\t@brief basis classes and data structures required by nana\n *\/\n\n#include \"platform_spec_selector.hpp\"\n#include \"platform_abstraction.hpp\"\n\n#if defined(NANA_WINDOWS)\n\n#include <stdexcept>\n#include <map>\n\n#include <windows.h>\n#include <shellapi.h>\n\n\n\nnamespace nana\n{\nnamespace detail\n{\n\tdrawable_impl_type::drawable_impl_type()\n\t{\n\t\tstring.tab_length = 4;\n\t\tstring.tab_pixels = 0;\n\t\tstring.whitespace_pixels = 0;\n\t}\n\n\tdrawable_impl_type::~drawable_impl_type()\n\t{\n\t\t::DeleteDC(context);\n\t\t::DeleteObject(pixmap);\n\t}\n\n\tunsigned drawable_impl_type::get_color() const\n\t{\n\t\treturn color_;\n\t}\n\n\tunsigned drawable_impl_type::get_text_color() const\n\t{\n\t\treturn text_color_;\n\t}\n\n\tvoid drawable_impl_type::set_color(const ::nana::color& clr)\n\t{\n\t\tcolor_ = (clr.px_color().value & 0xFFFFFF);\n\t}\n\n\tvoid drawable_impl_type::set_text_color(const ::nana::color& clr)\n\t{\n\t\tauto rgb = (clr.px_color().value & 0xFFFFFF);\n\t\tif (text_color_ != rgb)\n\t\t{\n\t\t\t::SetTextColor(context, NANA_RGB(rgb));\n\t\t\ttext_color_ = rgb;\n\t\t}\n\t}\n\n\t\/\/class platform_spec\n\tplatform_spec::co_initializer::co_initializer()\n\t\t: ole32_(::LoadLibrary(L\"OLE32.DLL\"))\n\t{\n\t\tif(ole32_)\n\t\t{\n\t\t\ttypedef HRESULT (__stdcall *CoInitializeEx_t)(LPVOID, DWORD);\n\t\t\tCoInitializeEx_t fn_init = reinterpret_cast<CoInitializeEx_t>(::GetProcAddress(ole32_, \"CoInitializeEx\"));\n\t\t\tif(0 == fn_init)\n\t\t\t{\n\t\t\t\t::FreeLibrary(ole32_);\n\t\t\t\tole32_ = 0;\n\t\t\t\tthrow std::runtime_error(\"Nana.PlatformSpec.Co_initializer: Can't locate the CoInitializeEx().\");\n\t\t\t}\n\t\t\telse\n\t\t\t\tfn_init(0, COINIT_APARTMENTTHREADED | \/*COINIT_DISABLE_OLE1DDE =*\/0x4);\n\t\t}\n\t\telse\n\t\t\tthrow std::runtime_error(\"Nana.PlatformSpec.Co_initializer: No Ole32.DLL Loaded.\");\n\t}\n\n\tplatform_spec::co_initializer::~co_initializer()\n\t{\n\t\tif(ole32_)\n\t\t{\n\t\t\ttypedef void (__stdcall *CoUninitialize_t)(void);\n\t\t\tCoUninitialize_t fn_unin = reinterpret_cast<CoUninitialize_t>(::GetProcAddress(ole32_, \"CoUninitialize\"));\n\t\t\tif(fn_unin)\n\t\t\t\tfn_unin();\n\t\t\t::FreeLibrary(ole32_);\n\t\t}\n\t}\n\n\tvoid platform_spec::co_initializer::task_mem_free(void* p)\n\t{\n\t\tif (ole32_)\n\t\t{\n\t\t\tusing CoTaskMemFree_t = void (__stdcall *)(LPVOID pv);\n\n\t\t\tCoTaskMemFree_t free_fn = reinterpret_cast<CoTaskMemFree_t>(::GetProcAddress(ole32_, \"CoTaskMemFree\"));\n\t\t\tif (free_fn)\n\t\t\t\tfree_fn(p);\n\t\t}\n\t}\n\n\tstruct platform_spec::implementation\n\t{\n\t\tstd::map<native_window_type, window_icons> iconbase;\n\t};\n\n\tplatform_spec::platform_spec()\n\t\t: impl_{ new implementation}\n\t{\n\t\tplatform_abstraction::initialize();\n\t}\n\n\tplatform_spec::~platform_spec()\n\t{\n\t\tplatform_abstraction::shutdown();\n\t\tdelete impl_;\n\t}\n\n\tplatform_spec& platform_spec::instance()\n\t{\n\t\tstatic platform_spec object;\n\t\treturn object;\n\t}\n\n\tvoid platform_spec::keep_window_icon(native_window_type wd, const paint::image& sml_icon, const paint::image& big_icon)\n\t{\n\t\tauto & icons = impl_->iconbase[wd];\n\t\ticons.sml_icon = sml_icon;\n\t\ticons.big_icon = big_icon;\n\t}\n\n\tvoid platform_spec::release_window_icon(native_window_type wd)\n\t{\n\t\timpl_->iconbase.erase(wd);\n\t}\n}\/\/end namespace detail\n}\/\/end namespace nana\n\n#endif \/\/NANA_WINDOWS\n","avg_line_length":22.2091503268,"max_line_length":120,"alphanum_fraction":0.7180694526,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":22968,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/******************************************************************************\n *\n * Project:  OpenGIS Simple Features Reference Implementation\n * Purpose:  Defines OGRLayerPool and OGRProxiedLayer class\n * Author:   Even Rouault, even dot rouault at mines dash paris dot org\n *\n ******************************************************************************\n * Copyright (c) 2012-2013, Even Rouault <even dot rouault at mines-paris dot org>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n ****************************************************************************\/\n\n#ifndef DOXYGEN_SKIP\n\n#include \"ogrlayerpool.h\"\n\nCPL_CVSID(\"$Id$\")\n\n\/************************************************************************\/\n\/*                      OGRAbstractProxiedLayer()                       *\/\n\/************************************************************************\/\n\nOGRAbstractProxiedLayer::OGRAbstractProxiedLayer( OGRLayerPool* poPoolIn ) :\n    poPrevLayer(NULL),\n    poNextLayer(NULL),\n    poPool(poPoolIn)\n{\n    CPLAssert(poPoolIn != NULL);\n}\n\n\/************************************************************************\/\n\/*                     ~OGRAbstractProxiedLayer()                       *\/\n\/************************************************************************\/\n\nOGRAbstractProxiedLayer::~OGRAbstractProxiedLayer()\n{\n    \/* Remove us from the list of LRU layers if necessary *\/\n    poPool->UnchainLayer(this);\n}\n\n\/************************************************************************\/\n\/*                            OGRLayerPool()                            *\/\n\/************************************************************************\/\n\nOGRLayerPool::OGRLayerPool(int nMaxSimultaneouslyOpenedIn) :\n    poMRULayer(NULL),\n    poLRULayer(NULL),\n    nMRUListSize(0),\n    nMaxSimultaneouslyOpened(nMaxSimultaneouslyOpenedIn)\n{}\n\n\/************************************************************************\/\n\/*                           ~OGRLayerPool()                            *\/\n\/************************************************************************\/\n\nOGRLayerPool::~OGRLayerPool()\n{\n    CPLAssert( poMRULayer == NULL );\n    CPLAssert( poLRULayer == NULL );\n    CPLAssert( nMRUListSize == 0 );\n}\n\n\/************************************************************************\/\n\/*                          SetLastUsedLayer()                          *\/\n\/************************************************************************\/\n\nvoid OGRLayerPool::SetLastUsedLayer(OGRAbstractProxiedLayer* poLayer)\n{\n    \/* If we are already the MRU layer, nothing to do *\/\n    if (poLayer == poMRULayer)\n        return;\n\n    \/\/CPLDebug(\"OGR\", \"SetLastUsedLayer(%s)\", poLayer->GetName());\n\n    if (poLayer->poPrevLayer != NULL || poLayer->poNextLayer != NULL)\n    {\n        \/* Remove current layer from its current place in the list *\/\n        UnchainLayer(poLayer);\n    }\n    else if (nMRUListSize == nMaxSimultaneouslyOpened)\n    {\n        \/* If we have reached the maximum allowed number of layers *\/\n        \/* simultaneously opened, then close the LRU one that *\/\n        \/* was still active until now *\/\n        CPLAssert(poLRULayer != NULL);\n\n        poLRULayer->CloseUnderlyingLayer();\n        UnchainLayer(poLRULayer);\n    }\n\n    \/* Put current layer on top of MRU list *\/\n    CPLAssert(poLayer->poPrevLayer == NULL);\n    CPLAssert(poLayer->poNextLayer == NULL);\n    poLayer->poNextLayer = poMRULayer;\n    if (poMRULayer != NULL)\n    {\n        CPLAssert(poMRULayer->poPrevLayer == NULL);\n        poMRULayer->poPrevLayer = poLayer;\n    }\n    poMRULayer = poLayer;\n    if (poLRULayer == NULL)\n        poLRULayer = poLayer;\n    nMRUListSize ++;\n}\n\n\/************************************************************************\/\n\/*                           UnchainLayer()                             *\/\n\/************************************************************************\/\n\nvoid OGRLayerPool::UnchainLayer(OGRAbstractProxiedLayer* poLayer)\n{\n    OGRAbstractProxiedLayer* poPrevLayer = poLayer->poPrevLayer;\n    OGRAbstractProxiedLayer* poNextLayer = poLayer->poNextLayer;\n\n    CPLAssert(poPrevLayer == NULL || poPrevLayer->poNextLayer == poLayer);\n    CPLAssert(poNextLayer == NULL || poNextLayer->poPrevLayer == poLayer);\n\n    if (poPrevLayer != NULL || poNextLayer != NULL || poLayer == poMRULayer)\n        nMRUListSize --;\n\n    if (poLayer == poMRULayer)\n        poMRULayer = poNextLayer;\n    if (poLayer == poLRULayer)\n        poLRULayer = poPrevLayer;\n    if (poPrevLayer != NULL)\n        poPrevLayer->poNextLayer = poNextLayer;\n    if (poNextLayer != NULL)\n        poNextLayer->poPrevLayer = poPrevLayer;\n    poLayer->poPrevLayer = NULL;\n    poLayer->poNextLayer = NULL;\n}\n\n\/************************************************************************\/\n\/*                          OGRProxiedLayer()                           *\/\n\/************************************************************************\/\n\nOGRProxiedLayer::OGRProxiedLayer( OGRLayerPool* poPoolIn,\n                                  OpenLayerFunc pfnOpenLayerIn,\n                                  FreeUserDataFunc pfnFreeUserDataIn,\n                                  void* pUserDataIn ) :\n    OGRAbstractProxiedLayer(poPoolIn),\n    pfnOpenLayer(pfnOpenLayerIn),\n    pfnFreeUserData(pfnFreeUserDataIn),\n    pUserData(pUserDataIn),\n    poUnderlyingLayer(NULL),\n    poFeatureDefn(NULL),\n    poSRS(NULL)\n{\n    CPLAssert(pfnOpenLayerIn != NULL);\n}\n\n\/************************************************************************\/\n\/*                         ~OGRProxiedLayer()                           *\/\n\/************************************************************************\/\n\nOGRProxiedLayer::~OGRProxiedLayer()\n{\n    delete poUnderlyingLayer;\n\n    if( poSRS )\n        poSRS->Release();\n\n    if( poFeatureDefn )\n        poFeatureDefn->Release();\n\n    if( pfnFreeUserData != NULL )\n        pfnFreeUserData(pUserData);\n}\n\n\/************************************************************************\/\n\/*                       OpenUnderlyingLayer()                          *\/\n\/************************************************************************\/\n\nint OGRProxiedLayer::OpenUnderlyingLayer()\n{\n    CPLDebug(\"OGR\", \"OpenUnderlyingLayer(%p)\", this);\n    CPLAssert(poUnderlyingLayer == NULL);\n    poPool->SetLastUsedLayer(this);\n    poUnderlyingLayer = pfnOpenLayer(pUserData);\n    if( poUnderlyingLayer == NULL )\n    {\n        CPLError(CE_Failure, CPLE_FileIO,\n                 \"Cannot open underlying layer\");\n    }\n    return poUnderlyingLayer != NULL;\n}\n\n\/************************************************************************\/\n\/*                         CloseUnderlyingLayer()                       *\/\n\/************************************************************************\/\n\nvoid OGRProxiedLayer::CloseUnderlyingLayer()\n{\n    CPLDebug(\"OGR\", \"CloseUnderlyingLayer(%p)\", this);\n    delete poUnderlyingLayer;\n    poUnderlyingLayer = NULL;\n}\n\n\/************************************************************************\/\n\/*                          GetUnderlyingLayer()                        *\/\n\/************************************************************************\/\n\nOGRLayer* OGRProxiedLayer::GetUnderlyingLayer()\n{\n    if( poUnderlyingLayer == NULL )\n    {\n        \/\/  If the open fails, poUnderlyingLayer will still be a nullptr\n        \/\/ and the user will be warned by the open call.\n        \/\/ coverity[check_return]\n        OpenUnderlyingLayer();\n    }\n    return poUnderlyingLayer;\n}\n\n\/************************************************************************\/\n\/*                          GetSpatialFilter()                          *\/\n\/************************************************************************\/\n\nOGRGeometry *OGRProxiedLayer::GetSpatialFilter()\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return NULL;\n    return poUnderlyingLayer->GetSpatialFilter();\n}\n\n\/************************************************************************\/\n\/*                          SetSpatialFilter()                          *\/\n\/************************************************************************\/\n\nvoid        OGRProxiedLayer::SetSpatialFilter( OGRGeometry * poGeom )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return;\n    poUnderlyingLayer->SetSpatialFilter(poGeom);\n}\n\n\/************************************************************************\/\n\/*                          SetSpatialFilter()                          *\/\n\/************************************************************************\/\n\nvoid        OGRProxiedLayer::SetSpatialFilter( int iGeomField, OGRGeometry * poGeom )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return;\n    poUnderlyingLayer->SetSpatialFilter(iGeomField, poGeom);\n}\n\/************************************************************************\/\n\/*                          SetAttributeFilter()                        *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::SetAttributeFilter( const char * poAttrFilter )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->SetAttributeFilter(poAttrFilter);\n}\n\n\/************************************************************************\/\n\/*                            ResetReading()                            *\/\n\/************************************************************************\/\n\nvoid        OGRProxiedLayer::ResetReading()\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return;\n    poUnderlyingLayer->ResetReading();\n}\n\n\/************************************************************************\/\n\/*                           GetNextFeature()                           *\/\n\/************************************************************************\/\n\nOGRFeature *OGRProxiedLayer::GetNextFeature()\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return NULL;\n    return poUnderlyingLayer->GetNextFeature();\n}\n\n\/************************************************************************\/\n\/*                           SetNextByIndex()                           *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::SetNextByIndex( GIntBig nIndex )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->SetNextByIndex(nIndex);\n}\n\n\/************************************************************************\/\n\/*                             GetFeature()                             *\/\n\/************************************************************************\/\n\nOGRFeature *OGRProxiedLayer::GetFeature( GIntBig nFID )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return NULL;\n    return poUnderlyingLayer->GetFeature(nFID);\n}\n\n\/************************************************************************\/\n\/*                             ISetFeature()                             *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::ISetFeature( OGRFeature *poFeature )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->SetFeature(poFeature);\n}\n\n\/************************************************************************\/\n\/*                            ICreateFeature()                           *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::ICreateFeature( OGRFeature *poFeature )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->CreateFeature(poFeature);\n}\n\n\/************************************************************************\/\n\/*                           DeleteFeature()                            *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::DeleteFeature( GIntBig nFID )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->DeleteFeature(nFID);\n}\n\n\/************************************************************************\/\n\/*                             GetName()                                *\/\n\/************************************************************************\/\n\nconst char *OGRProxiedLayer::GetName()\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return \"\";\n    return poUnderlyingLayer->GetName();\n}\n\n\/************************************************************************\/\n\/*                            GetGeomType()                             *\/\n\/************************************************************************\/\n\nOGRwkbGeometryType OGRProxiedLayer::GetGeomType()\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return wkbUnknown;\n    return poUnderlyingLayer->GetGeomType();\n}\n\n\/************************************************************************\/\n\/*                            GetLayerDefn()                            *\/\n\/************************************************************************\/\n\nOGRFeatureDefn *OGRProxiedLayer::GetLayerDefn()\n{\n    if( poFeatureDefn != NULL )\n        return poFeatureDefn;\n\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() )\n    {\n        poFeatureDefn = new OGRFeatureDefn(\"\");\n    }\n    else\n    {\n        poFeatureDefn = poUnderlyingLayer->GetLayerDefn();\n    }\n\n    poFeatureDefn->Reference();\n\n    return poFeatureDefn;\n}\n\n\/************************************************************************\/\n\/*                            GetSpatialRef()                           *\/\n\/************************************************************************\/\n\nOGRSpatialReference *OGRProxiedLayer::GetSpatialRef()\n{\n    if( poSRS != NULL )\n        return poSRS;\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return NULL;\n    OGRSpatialReference* poRet = poUnderlyingLayer->GetSpatialRef();\n    if( poRet != NULL )\n    {\n        poSRS = poRet;\n        poSRS->Reference();\n    }\n    return poRet;\n}\n\n\/************************************************************************\/\n\/*                          GetFeatureCount()                           *\/\n\/************************************************************************\/\n\nGIntBig         OGRProxiedLayer::GetFeatureCount( int bForce )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return 0;\n    return poUnderlyingLayer->GetFeatureCount(bForce);\n}\n\n\/************************************************************************\/\n\/*                             GetExtent()                              *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::GetExtent(int iGeomField, OGREnvelope *psExtent, int bForce)\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->GetExtent(iGeomField, psExtent, bForce);\n}\n\n\/************************************************************************\/\n\/*                             GetExtent()                              *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::GetExtent(OGREnvelope *psExtent, int bForce)\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->GetExtent(psExtent, bForce);\n}\n\n\/************************************************************************\/\n\/*                           TestCapability()                           *\/\n\/************************************************************************\/\n\nint         OGRProxiedLayer::TestCapability( const char * pszCapability )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return FALSE;\n    return poUnderlyingLayer->TestCapability(pszCapability);\n}\n\n\/************************************************************************\/\n\/*                            CreateField()                             *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::CreateField( OGRFieldDefn *poField,\n                                            int bApproxOK )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->CreateField(poField, bApproxOK);\n}\n\n\/************************************************************************\/\n\/*                            DeleteField()                             *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::DeleteField( int iField )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->DeleteField(iField);\n}\n\n\/************************************************************************\/\n\/*                            ReorderFields()                           *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::ReorderFields( int* panMap )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->ReorderFields(panMap);\n}\n\n\/************************************************************************\/\n\/*                           AlterFieldDefn()                           *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::AlterFieldDefn( int iField, OGRFieldDefn* poNewFieldDefn, int nFlagsIn )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->AlterFieldDefn(iField, poNewFieldDefn, nFlagsIn);\n}\n\n\/************************************************************************\/\n\/*                            SyncToDisk()                              *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::SyncToDisk()\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->SyncToDisk();\n}\n\n\/************************************************************************\/\n\/*                           GetStyleTable()                            *\/\n\/************************************************************************\/\n\nOGRStyleTable *OGRProxiedLayer::GetStyleTable()\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return NULL;\n    return poUnderlyingLayer->GetStyleTable();\n}\n\n\/************************************************************************\/\n\/*                       SetStyleTableDirectly()                        *\/\n\/************************************************************************\/\n\nvoid        OGRProxiedLayer::SetStyleTableDirectly( OGRStyleTable *poStyleTable )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return;\n    return poUnderlyingLayer->SetStyleTableDirectly(poStyleTable);\n}\n\n\/************************************************************************\/\n\/*                           SetStyleTable()                            *\/\n\/************************************************************************\/\n\nvoid        OGRProxiedLayer::SetStyleTable(OGRStyleTable *poStyleTable)\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return;\n    return poUnderlyingLayer->SetStyleTable(poStyleTable);\n}\n\n\/************************************************************************\/\n\/*                          StartTransaction()                          *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::StartTransaction()\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->StartTransaction();\n}\n\n\/************************************************************************\/\n\/*                          CommitTransaction()                         *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::CommitTransaction()\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->CommitTransaction();\n}\n\n\/************************************************************************\/\n\/*                        RollbackTransaction()                         *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::RollbackTransaction()\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->RollbackTransaction();\n}\n\n\/************************************************************************\/\n\/*                            GetFIDColumn()                            *\/\n\/************************************************************************\/\n\nconst char *OGRProxiedLayer::GetFIDColumn()\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return \"\";\n    return poUnderlyingLayer->GetFIDColumn();\n}\n\n\/************************************************************************\/\n\/*                          GetGeometryColumn()                         *\/\n\/************************************************************************\/\n\nconst char *OGRProxiedLayer::GetGeometryColumn()\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return \"\";\n    return poUnderlyingLayer->GetGeometryColumn();\n}\n\n\/************************************************************************\/\n\/*                          SetIgnoredFields()                          *\/\n\/************************************************************************\/\n\nOGRErr      OGRProxiedLayer::SetIgnoredFields( const char **papszFields )\n{\n    if( poUnderlyingLayer == NULL && !OpenUnderlyingLayer() ) return OGRERR_FAILURE;\n    return poUnderlyingLayer->SetIgnoredFields(papszFields);\n}\n\n#endif \/* #ifndef DOXYGEN_SKIP *\/\n","avg_line_length":39.3962264151,"max_line_length":101,"alphanum_fraction":0.419496691,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":970,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":3508.0,"content":"\/\/416. Partition Equal Subset Sum\n\nclass Solution {\npublic:\n    \/\/maximum size top-down dp table\n    bool dp[201][20001];\n    \n    bool equalPart(vector<int>& arr,int size,int sum){\n        for(int i=0;i<=size;i++){\n            dp[i][0]=true;\n        }\n        for(int i=1;i<=sum;i++){\n            dp[0][i]=false;\n        }\n        \n        for(int i=1;i<=size;i++){\n            for(int j=1;j<=sum;j++){\n                 \n                if(arr[i-1]<=j){\n                    dp[i][j] = dp[i-1][j] || dp[i-1][j-arr[i-1]];\n                }else{\n                    dp[i][j] = dp[i-1][j];\n                }\n                \n            }\n        }\n        \n        return dp[size][sum];\n    }\n    \n    bool canPartition(vector<int>& nums) {\n        int sum=0;\n        for(int i=0;i<nums.size();i++){\n            sum+=nums[i];\n        }\n        if(sum%2!=0){\n            return false;\n        }else{\n            return equalPart(nums,nums.size(),sum\/2);\n        }\n    }\n};\n","avg_line_length":22.5581395349,"max_line_length":65,"alphanum_fraction":0.3742268041,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":33593,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\n\n#include <QtGlobal>\n\n\/\/ Automatically generated by extract_strings.py\n#ifdef __GNUC__\n#define UNUSED __attribute__((unused))\n#else\n#define UNUSED\n#endif\nstatic const char UNUSED* lavas_strings[] = {\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"(1 = keep tx meta data e.g. account owner and payment request information, 2 \"\n                                   \"= drop tx meta data)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Allow JSON-RPC connections from specified source. Valid for <ip> are a \"\n                                   \"single IP (e.g. 1.2.3.4), a network\/netmask (e.g. 1.2.3.4\/255.255.255.0) or \"\n                                   \"a network\/CIDR (e.g. 1.2.3.4\/24). This option can be specified multiple times\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"An error occurred while setting up the RPC address %s port %u for listening: \"\n                                   \"%s\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Bind to given address and always listen on it. Use [host]:port notation for \"\n                                   \"IPv6\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Bind to given address and whitelist peers connecting to it. Use [host]:port \"\n                                   \"notation for IPv6\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Bind to given address to listen for JSON-RPC connections. Use [host]:port \"\n                                   \"notation for IPv6. This option can be specified multiple times (default: \"\n                                   \"bind to all interfaces)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Cannot obtain a lock on data directory %s. LAVAS Core is probably already \"\n                                   \"running.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Change automatic finalized budget voting behavior. mode=auto: Vote for only \"\n                                   \"exact finalized budget match to my generated budget. (string, default: auto)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Continuously rate-limit free transactions to <n>*1000 bytes per minute \"\n                                   \"(default:%u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Create new files with system default permissions, instead of umask 077 (only \"\n                                   \"effective with disabled wallet functionality)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Delete all wallet transactions and only recover those parts of the \"\n                                   \"blockchain through -rescan on startup\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Disable all LAVAS specific functionality (Masternodes, Darksend, InstantX, \"\n                                   \"Budgeting) (0-1, default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Distributed under the MIT software license, see the accompanying file \"\n                                   \"COPYING or <http:\/\/www.opensource.org\/licenses\/mit-license.php>.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Enable Instantx, show confirmations for locked transactions (bool, default: \"\n                                   \"%s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Enable use of automated Darksend for funds stored in this wallet (0-1, \"\n                                   \"default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Enter regression test mode, which uses a special chain in which blocks can \"\n                                   \"be solved instantly.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Error: Listening for incoming connections failed (listen returned error %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Error: Unsupported argument -socks found. Setting SOCKS version isn't \"\n                                   \"possible anymore, only SOCKS5 proxies are supported.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Execute command when a relevant alert is received or we see a really long \"\n                                   \"fork (%s in cmd is replaced by message)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Execute command when a wallet transaction changes (%s in cmd is replaced by \"\n                                   \"TxID)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Execute command when the best block changes (%s in cmd is replaced by block \"\n                                   \"hash)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Fees (in LAVAS\/Kb) smaller than this are considered zero fee for relaying \"\n                                   \"(default: %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Fees (in LAVAS\/Kb) smaller than this are considered zero fee for transaction \"\n                                   \"creation (default: %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Flush database activity from memory pool to disk log every <n> megabytes \"\n                                   \"(default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Found unconfirmed denominated outputs, will wait till they confirm to \"\n                                   \"continue.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"How thorough the block verification of -checkblocks is (0-4, default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"If paytxfee is not set, include enough fee so transactions begin \"\n                                   \"confirmation on average within n blocks (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"In this mode -genproclimit controls how many blocks are generated \"\n                                   \"immediately.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay \"\n                                   \"fee of %s to prevent stuck transactions)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Log transaction priority and fee per kB when mining blocks (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Maintain a full transaction index, used by the getrawtransaction rpc call \"\n                                   \"(default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Maximum size of data in data carrier transactions we relay and mine \"\n                                   \"(default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Maximum total fees to use in a single wallet transaction, setting too low \"\n                                   \"may abort large transactions (default: %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Name to construct url for KeePass entry that stores the wallet passphrase\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Number of seconds to keep misbehaving peers from reconnecting (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Darksend uses exact denominated amounts to send funds, you might simply \"\n                                   \"need to anonymize some more coins.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Output debugging information (default: %u, supplying <category> is optional)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Provide liquidity to Darksend by infrequently mixing coins on a continual \"\n                                   \"basis (0-100, default: %u, 1=very frequent, high fees, 100=very infrequent, \"\n                                   \"low fees)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Query for peer addresses via DNS lookup, if low on addresses (default: 1 \"\n                                   \"unless -connect)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Require high priority for relaying free or low-fee transactions (default:%u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Send trace\/debug info to console instead of debug.log file (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Set maximum size of high-priority\/low-fee transactions in bytes (default: %d)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Set the number of script verification threads (%u to %d, 0 = auto, <0 = \"\n                                   \"leave that many cores free, default: %d)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Set the number of threads for coin generation if enabled (-1 = all cores, \"\n                                   \"default: %d)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Show N confirmations for a successfully locked transaction (0-9999, default: \"\n                                   \"%u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"InstantX requires inputs with at least 6 confirmations, you might need to \"\n                                   \"wait a few minutes and try again.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"This is a pre-release test build - use at your own risk - do not use for \"\n                                   \"mining or merchant applications\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"This product includes software developed by the OpenSSL Project for use in \"\n                                   \"the OpenSSL Toolkit <https:\/\/www.openssl.org\/> and cryptographic software \"\n                                   \"written by Eric Young and UPnP software written by Thomas Bernard.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"To use lavasd, or the -server option to lavas-qt, you must set an rpcpassword \"\n                                   \"in the configuration file:\\n\"\n                                   \"%s\\n\"\n                                   \"It is recommended you use the following random password:\\n\"\n                                   \"rpcuser=lavasrpc\\n\"\n                                   \"rpcpassword=%s\\n\"\n                                   \"(you do not need to remember this password)\\n\"\n                                   \"The username and password MUST NOT be the same.\\n\"\n                                   \"If the file does not exist, create it with owner-readable-only file \"\n                                   \"permissions.\\n\"\n                                   \"It is also recommended to set alertnotify so you are notified of problems;\\n\"\n                                   \"for example: alertnotify=echo %%s | mail -s \\\"LAVAS Alert\\\" admin@foo.com\\n\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Unable to bind to %s on this computer. LAVAS Core is probably already running.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Unable to locate enough Darksend denominated funds for this transaction.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Unable to locate enough Darksend non-denominated funds for this \"\n                                   \"transaction that are not equal 10000 LAVAS.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Unable to locate enough funds for this transaction that are not equal 10000 \"\n                                   \"LAVAS.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: \"\n                                   \"%s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Warning: -maxtxfee is set very high! Fees this large could be paid on a \"\n                                   \"single transaction.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Warning: -paytxfee is set very high! This is the transaction fee you will \"\n                                   \"pay if you send a transaction.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Warning: Please check that your computer's date and time are correct! If \"\n                                   \"your clock is wrong LAVAS Core will not work properly.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Warning: The network does not appear to fully agree! Some miners appear to \"\n                                   \"be experiencing issues.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Warning: We do not appear to fully agree with our peers! You may need to \"\n                                   \"upgrade, or other nodes may need to upgrade.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Warning: error reading wallet.dat! All keys read correctly, but transaction \"\n                                   \"data or address book entries might be missing or incorrect.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as \"\n                                   \"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect \"\n                                   \"you should restore from a backup.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Whitelist peers connecting from the given netmask or IP address. Can be \"\n                                   \"specified multiple times.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"Whitelisted peers cannot be DoS banned and their transactions are always \"\n                                   \"relayed, even if they are already in the mempool, useful e.g. for a gateway\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"\"\n                                   \"You must specify a masternodeprivkey in the configuration. Please see \"\n                                   \"documentation for help.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"(51555 could be used only on mainnet)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"(default: %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"(default: 1)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"(must be 51555 for mainnet)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"<category> can be:\\n\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Accept command line and JSON-RPC commands\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Accept connections from outside (default: 1 if no -proxy or -connect)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Accept public REST requests (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Acceptable ciphers (default: %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Add a node to connect to and attempt to keep the connection open\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Allow DNS lookups for -addnode, -seednode and -connect\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Already have that input.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Always query for peer addresses via DNS lookup (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Attempt to recover private keys from a corrupt wallet.dat\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Block creation options:\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Can't denominate: no compatible inputs left.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Can't find random Masternode.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Can't mix while sync in progress.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Cannot downgrade wallet\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Cannot resolve -bind address: '%s'\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Cannot resolve -externalip address: '%s'\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Cannot resolve -whitebind address: '%s'\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Cannot write default address\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Collateral not valid.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Connect only to the specified node(s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Connect through SOCKS5 proxy\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Connect to KeePassHttp on port <port> (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Connect to a node to retrieve peer addresses, and disconnect\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Connection options:\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Copyright (C) 2009-%i The Bitcoin Core Developers\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Copyright (C) 2014-%i The Dash and PIVX Core Developers\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Copyright (C) 2015-%i The LAVAS Core Developers\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Corrupted block database detected\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Could not parse -rpcbind value %s as network address\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Could not parse masternode.conf\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Debugging\/Testing options:\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Disable safemode, override a real safe mode event (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Discover own IP address (default: 1 when listening and no -externalip)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Do not load the wallet and disable wallet RPC calls\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Do you want to rebuild the block database now?\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Done loading\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Enable the client to act as a masternode (0-1, default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Entries are full.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error connecting to Masternode.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error initializing block database\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error initializing wallet database environment %s!\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error loading block database\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error loading wallet.dat\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error loading wallet.dat: Wallet corrupted\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error loading wallet.dat: Wallet requires newer version of LAVAS Core\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error opening block database\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error reading from database, shutting down.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error recovering public key.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error: A fatal internal error occured, see debug.log for details\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error: Can't select current denominated inputs\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error: Disk space is low!\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error: Unsupported argument -tor found, use -onion.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error: Wallet locked, unable to create transaction!\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Error: You already have pending entries in the Darksend pool\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Failed to listen on any port. Use -listen=0 if you want this.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Failed to read block\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Fee (in LAVAS\/kB) to add to transactions you send (default: %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Finalizing transaction.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Force safe mode (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Found enough users, signing ( waiting %s )\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Found enough users, signing ...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Generate coins (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"How many blocks to check at startup (default: %u, 0 = all)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"If <category> is not supplied, output all debugging information.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Importing...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Imports blocks from external blk000??.dat file\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Include IP addresses in debug output (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Incompatible mode.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Incompatible version.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Incorrect or no genesis block found. Wrong datadir for network?\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Information\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Initialization sanity check failed. LAVAS Core is shutting down.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Input is not valid.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Insufficient funds.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Invalid -onion address: '%s'\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Invalid -proxy address: '%s'\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Invalid amount for -maxtxfee=<amount>: '%s'\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Invalid amount for -minrelaytxfee=<amount>: '%s'\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Invalid amount for -mintxfee=<amount>: '%s'\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Invalid amount for -paytxfee=<amount>: '%s'\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Invalid amount for -reservebalance=<amount>\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Invalid masternodeprivkey. Please see documenation.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Invalid netmask specified in -whitelist: '%s'\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Invalid port detected in masternode.conf\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Invalid private key.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Invalid script detected.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"KeePassHttp id for the established association\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"KeePassHttp key for AES encrypted communication with KeePass\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Keep N LAVAS anonymized (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Keep at most <n> unconnectable transactions in memory (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Last Darksend was too recent.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Last successful Darksend action was too recent.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Limit size of signature cache to <n> entries (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Line: %d\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Listen for connections on <port> (default: %u or testnet: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Loading addresses...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Loading block index...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Loading budget cache...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Loading masternode cache...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Loading masternode payment cache...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Loading wallet... (%3.2f %%)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Loading wallet...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Lock is already in place.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Lock masternodes from masternode configuration file (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Maintain at most <n> connections to peers (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Masternode options:\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Masternode queue is full.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Masternode:\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Maximum per-connection send buffer, <n>*1000 bytes (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Missing input transaction information.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Mixing in progress...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Need to specify a port with -whitebind: '%s'\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"No Masternodes detected.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"No compatible Masternode found.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"No funds detected in need of denominating.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"No matching denominations found for mixing.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Node relay options:\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Non-standard public key detected.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Not compatible with existing transactions.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Not enough file descriptors available.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Not in the Masternode list.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Number of automatic wallet backups (default: 10)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Darksend is idle.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Darksend options:\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Darksend request complete:\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Darksend request incomplete:\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Only accept block chain matching built-in checkpoints (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Only connect to nodes in network <net> (ipv4, ipv6 or onion)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Options:\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Password for JSON-RPC connections\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Prepend debug output with timestamp (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"RPC server options:\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"RPC support for HTTP persistent connections (default: %d)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Randomly drop 1 of every <n> network messages\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Randomly fuzz 1 of every <n> network messages\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Rebuild block chain index from current blk000??.dat files\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Receive and display P2P network alerts (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Relay and mine data carrier transactions (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Relay non-P2SH multisig (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Rescan the block chain for missing wallet transactions\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Rescanning...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Run a thread to flush wallet periodically (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Run in the background as a daemon and accept commands\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Send transactions as zero-fee transactions if possible (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Server certificate file (default: %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Server private key (default: %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Session not complete!\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Session timed out.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Set database cache size in megabytes (%d to %d, default: %d)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Set external address:port to get to this masternode (example: %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Set key pool size to <n> (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Set maximum block size in bytes (default: %d)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Set minimum block size in bytes (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Set the masternode private key\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Set the number of threads to service RPC calls (default: %d)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Sets the DB_PRIVATE flag in the wallet db environment (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Show all debugging options (usage: --help -help-debug)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Shrink debug.log file on client startup (default: 1 when no -debug)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Signing failed.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Signing timed out.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Signing transaction failed\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Specify configuration file (default: %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Specify connection timeout in milliseconds (minimum: 1, default: %d)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Specify data directory\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Specify masternode configuration file (default: %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Specify pid file (default: %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Specify wallet file (within data directory)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Specify your own public address\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Spend unconfirmed change when sending transactions (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Stop running after importing blocks from disk (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Submitted following entries to masternode: %u \/ %d\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Submitted to masternode, waiting for more entries ( %u \/ %d ) %s\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Submitted to masternode, waiting in queue %s\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"InstantX options:\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Synchronization failed\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Synchronization finished\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Synchronization pending...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Synchronizing budgets...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Synchronizing masternode winners...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Synchronizing masternodes...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Synchronizing sporks...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"This help message\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"This is experimental software.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"This is intended for regression testing tools and app development.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"This is not a Masternode.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Threshold for disconnecting misbehaving peers (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Transaction amount too small\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Transaction amounts must be positive\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Transaction created successfully.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Transaction fees are too high.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Transaction not valid.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Transaction too large for fee policy\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Transaction too large\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Transmitting final transaction.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Unable to bind to %s on this computer (bind returned error %s)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Unable to sign spork message, wrong key?\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Unknown network specified in -onlynet: '%s'\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Unknown state: id = %u\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Upgrade wallet to latest format\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Use KeePass 2 integration using KeePassHttp plugin (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Use N separate masternodes to anonymize funds  (2-8, default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Use OpenSSL (https) for JSON-RPC connections\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Use UPnP to map the listening port (default: %u)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Use UPnP to map the listening port (default: 1 when listening)\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Use the test network\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Username for JSON-RPC connections\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Value more than Darksend pool maximum allows.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Verifying blocks...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Verifying wallet...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Wallet %s resides outside data directory %s\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Wallet is locked.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Wallet needed to be rewritten: restart LAVAS Core to complete\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Wallet options:\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Wallet window title\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Warning\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Warning: This version is obsolete, upgrade required!\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Warning: Unsupported argument -benchmark ignored, use -debug=bench.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Warning: Unsupported argument -debugnet ignored, use -debug=net.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Will retry...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"You need to rebuild the database using -reindex to change -txindex\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Your entries added successfully.\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Your transaction was accepted into the pool!\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"Zapping all transactions from wallet...\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"on startup\"),\n    QT_TRANSLATE_NOOP(\"lavas-core\", \"wallet.dat corrupt, salvage failed\"),\n};\n","avg_line_length":75.6599099099,"max_line_length":117,"alphanum_fraction":0.6217664394,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10074,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/**\n * Copyright (C) 2018 MongoDB Inc.\n *\n * This program is free software: you can redistribute it and\/or  modify\n * it under the terms of the GNU Affero General Public License, version 3,\n * as published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n * As a special exception, the copyright holders give permission to link the\n * code of portions of this program with the OpenSSL library under certain\n * conditions as described in each individual source file and distribute\n * linked combinations including the program with the OpenSSL library. You\n * must comply with the GNU Affero General Public License in all respects\n * for all of the code used other than as permitted herein. If you modify\n * file(s) with this exception, you may extend this exception to your\n * version of the file(s), but you are not obligated to do so. If you do not\n * wish to do so, delete this exception statement from your version. If you\n * delete this exception statement from all source files in the program,\n * then also delete it in the license file.\n *\/\n#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kStorage\n\n#include \"mongo\/platform\/basic.h\"\n\n#include \"mongo\/db\/catalog\/catalog_control.h\"\n\n#include \"mongo\/db\/catalog\/collection.h\"\n#include \"mongo\/db\/catalog\/database.h\"\n#include \"mongo\/db\/catalog\/database_catalog_entry.h\"\n#include \"mongo\/db\/catalog\/database_holder.h\"\n#include \"mongo\/db\/catalog\/uuid_catalog.h\"\n#include \"mongo\/db\/ftdc\/ftdc_mongod.h\"\n#include \"mongo\/db\/namespace_string.h\"\n#include \"mongo\/db\/repair_database.h\"\n#include \"mongo\/util\/log.h\"\n\nnamespace mongo {\nnamespace catalog {\nMinVisibleTimestampMap closeCatalog(OperationContext* opCtx) {\n    invariant(opCtx->lockState()->isW());\n\n    MinVisibleTimestampMap minVisibleTimestampMap;\n    std::vector<std::string> allDbs;\n    opCtx->getServiceContext()->getStorageEngine()->listDatabases(&allDbs);\n\n    const auto& databaseHolder = DatabaseHolder::getDatabaseHolder();\n    for (auto&& dbName : allDbs) {\n        const auto db = databaseHolder.get(opCtx, dbName);\n        for (Collection* coll : *db) {\n            OptionalCollectionUUID uuid = coll->uuid();\n            boost::optional<Timestamp> minVisible = coll->getMinimumVisibleSnapshot();\n\n            \/\/ If there's a minimum visible, invariant there's also a UUID.\n            invariant(!minVisible || uuid);\n            if (uuid && minVisible) {\n                LOG(1) << \"closeCatalog: preserving min visible timestamp. Collection: \"\n                       << coll->ns() << \" UUID: \" << uuid << \" TS: \" << minVisible;\n                minVisibleTimestampMap[*uuid] = *minVisible;\n            }\n        }\n    }\n\n    \/\/ Need to mark the UUIDCatalog as open if we our closeAll fails, dismissed if successful.\n    auto reopenOnFailure = MakeGuard([opCtx] { UUIDCatalog::get(opCtx).onOpenCatalog(opCtx); });\n    \/\/ Closing UUID Catalog: only lookupNSSByUUID will fall back to using pre-closing state to\n    \/\/ allow authorization for currently unknown UUIDs. This is needed because authorization needs\n    \/\/ to work before acquiring locks, and might otherwise spuriously regard a UUID as unknown\n    \/\/ while reloading the catalog.\n    UUIDCatalog::get(opCtx).onCloseCatalog(opCtx);\n    LOG(1) << \"closeCatalog: closing UUID catalog\";\n\n    \/\/ Close all databases.\n    log() << \"closeCatalog: closing all databases\";\n    constexpr auto reason = \"closing databases for closeCatalog\";\n    DatabaseHolder::getDatabaseHolder().closeAll(opCtx, reason);\n\n    \/\/ Close the storage engine's catalog.\n    log() << \"closeCatalog: closing storage engine catalog\";\n    opCtx->getServiceContext()->getStorageEngine()->closeCatalog(opCtx);\n\n    reopenOnFailure.Dismiss();\n    return minVisibleTimestampMap;\n}\n\nvoid openCatalog(OperationContext* opCtx, const MinVisibleTimestampMap& minVisibleTimestampMap) {\n    invariant(opCtx->lockState()->isW());\n\n    \/\/ Load the catalog in the storage engine.\n    log() << \"openCatalog: loading storage engine catalog\";\n    auto storageEngine = opCtx->getServiceContext()->getStorageEngine();\n    storageEngine->loadCatalog(opCtx);\n\n    log() << \"openCatalog: reconciling catalog and idents\";\n    auto indexesToRebuild = storageEngine->reconcileCatalogAndIdents(opCtx);\n    fassert(40688, indexesToRebuild.getStatus());\n\n    \/\/ Determine which indexes need to be rebuilt. rebuildIndexesOnCollection() requires that all\n    \/\/ indexes on that collection are done at once, so we use a map to group them together.\n    StringMap<IndexNameObjs> nsToIndexNameObjMap;\n    for (auto indexNamespace : indexesToRebuild.getValue()) {\n        NamespaceString collNss(indexNamespace.first);\n        auto indexName = indexNamespace.second;\n\n        auto dbCatalogEntry = storageEngine->getDatabaseCatalogEntry(opCtx, collNss.db());\n        invariant(dbCatalogEntry,\n                  str::stream() << \"couldn't get database catalog entry for database \"\n                                << collNss.db());\n        auto collCatalogEntry = dbCatalogEntry->getCollectionCatalogEntry(collNss.toString());\n        invariant(collCatalogEntry,\n                  str::stream() << \"couldn't get collection catalog entry for collection \"\n                                << collNss.toString());\n\n        auto indexSpecs = getIndexNameObjs(\n            opCtx, dbCatalogEntry, collCatalogEntry, [&indexName](const std::string& name) {\n                return name == indexName;\n            });\n        if (!indexSpecs.isOK() || indexSpecs.getValue().first.empty()) {\n            fassert(40689,\n                    {ErrorCodes::InternalError,\n                     str::stream() << \"failed to get index spec for index \" << indexName\n                                   << \" in collection \"\n                                   << collNss.toString()});\n        }\n        auto indexesToRebuild = indexSpecs.getValue();\n        invariant(\n            indexesToRebuild.first.size() == 1,\n            str::stream() << \"expected to find a list containing exactly 1 index name, but found \"\n                          << indexesToRebuild.first.size());\n        invariant(\n            indexesToRebuild.second.size() == 1,\n            str::stream() << \"expected to find a list containing exactly 1 index spec, but found \"\n                          << indexesToRebuild.second.size());\n\n        auto& ino = nsToIndexNameObjMap[collNss.ns()];\n        ino.first.emplace_back(std::move(indexesToRebuild.first.back()));\n        ino.second.emplace_back(std::move(indexesToRebuild.second.back()));\n    }\n\n    for (const auto& entry : nsToIndexNameObjMap) {\n        NamespaceString collNss(entry.first);\n\n        auto dbCatalogEntry = storageEngine->getDatabaseCatalogEntry(opCtx, collNss.db());\n        invariant(dbCatalogEntry,\n                  str::stream() << \"couldn't get database catalog entry for database \"\n                                << collNss.db());\n        auto collCatalogEntry = dbCatalogEntry->getCollectionCatalogEntry(collNss.toString());\n        invariant(collCatalogEntry,\n                  str::stream() << \"couldn't get collection catalog entry for collection \"\n                                << collNss.toString());\n\n        for (const auto& indexName : entry.second.first) {\n            log() << \"openCatalog: rebuilding index: collection: \" << collNss.toString()\n                  << \", index: \" << indexName;\n        }\n        fassert(40690,\n                rebuildIndexesOnCollection(\n                    opCtx, dbCatalogEntry, collCatalogEntry, std::move(entry.second)));\n    }\n\n    \/\/ Open all databases and repopulate the UUID catalog.\n    log() << \"openCatalog: reopening all databases\";\n    auto& uuidCatalog = UUIDCatalog::get(opCtx);\n    std::vector<std::string> databasesToOpen;\n    storageEngine->listDatabases(&databasesToOpen);\n    for (auto&& dbName : databasesToOpen) {\n        LOG(1) << \"openCatalog: dbholder reopening database \" << dbName;\n        auto db = DatabaseHolder::getDatabaseHolder().openDb(opCtx, dbName);\n        invariant(db, str::stream() << \"failed to reopen database \" << dbName);\n\n        std::list<std::string> collections;\n        db->getDatabaseCatalogEntry()->getCollectionNamespaces(&collections);\n        for (auto&& collName : collections) {\n            \/\/ Note that the collection name already includes the database component.\n            NamespaceString collNss(collName);\n            auto collection = db->getCollection(opCtx, collName);\n            invariant(collection,\n                      str::stream() << \"failed to get valid collection pointer for namespace \"\n                                    << collName);\n\n            auto uuid = collection->uuid();\n            invariant(uuid);\n\n            LOG(1) << \"openCatalog: registering uuid \" << uuid->toString() << \" for collection \"\n                   << collName;\n            uuidCatalog.registerUUIDCatalogEntry(*uuid, collection);\n\n            if (minVisibleTimestampMap.count(*uuid) > 0) {\n                collection->setMinimumVisibleSnapshot(minVisibleTimestampMap.find(*uuid)->second);\n            }\n\n            \/\/ If this is the oplog collection, re-establish the replication system's cached pointer\n            \/\/ to the oplog.\n            if (collNss.isOplog()) {\n                log() << \"openCatalog: updating cached oplog pointer\";\n                repl::establishOplogCollectionForLogging(opCtx, collection);\n            }\n        }\n    }\n    \/\/ Opening UUID Catalog: The UUID catalog is now in sync with the storage engine catalog. Clear\n    \/\/ the pre-closing state.\n    UUIDCatalog::get(opCtx).onOpenCatalog(opCtx);\n    LOG(1) << \"openCatalog: finished reloading UUID catalog\";\n}\n}  \/\/ namespace catalog\n}  \/\/ namespace mongo\n","avg_line_length":47.2957746479,"max_line_length":100,"alphanum_fraction":0.6547548144,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1479,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":18.0,"content":"\/*\nSubsets\n\nGiven a set of distinct integers, nums, return all possible subsets (the power set).\n\nNote: The solution set must not contain duplicate subsets.\n\nExample:\n\nInput: nums = [1,2,3]\nOutput:\n[\n  [3],\n  [1],\n  [2],\n  [1,2,3],\n  [1,3],\n  [2,3],\n  [1,2],\n  []\n]\n*\/\n\n\/\/ bitmask\nclass Solution {\npublic:\n    vector<vector<int>> subsets(vector<int>& nums) {\n        int n = nums.size();\n        \/\/ number of subsets for n elements would be 2^n\n        \/\/ because for each element, you can choose to take it or not\n        \/\/ if take = 1, don't take = 0, then we can use bit manipulation \n        int p = 1 << n; \/\/ 1*2^n\n        vector<vector<int>> ans;\n        for(int i = 0; i < p; i++){\n            vector<int> t; \n            for(int j = 0; j < n; j++){\n               if((1 << j) & i) t.emplace_back(nums[j]); \n            }\n            ans.emplace_back(t);\n        }\n        return ans;\n    }\n};\n\n\/\/ backtracking \nclass Solution2 {\npublic:\n    void backtrack(vector<vector<int>>& ans, vector<int>& tmp, vector<int>& nums, int start) {\n        ans.push_back(tmp);    \n        for(int i = start; i < nums.size(); i++) {\n            tmp.push_back(nums[i]);\n            backtrack(ans, tmp, nums, i + 1);\n            tmp.pop_back();\n        }\n    }\n    \n    \n    vector<vector<int>> subsets(vector<int>& nums) {\n        vector<vector<int>> ans;\n        vector<int> tmp;\n        sort(nums.begin(), nums.end());\n        backtrack(ans, tmp, nums,  0);\n        return ans;\n    }\n};","avg_line_length":22.7538461538,"max_line_length":94,"alphanum_fraction":0.5131845842,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6591,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0","BSD-3-Clause"],"max_stars_count":1.0,"content":"\/*\n\nCopyright (c) 2005-2020, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and\/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"Hdf5ToMeshalyzerConverter.hpp\"\n#include \"MeshalyzerMeshWriter.hpp\"\n#include \"GenericMeshReader.hpp\"\n#include \"UblasCustomFunctions.hpp\"\n#include \"PetscTools.hpp\"\n#include \"Exception.hpp\"\n#include \"ReplicatableVector.hpp\"\n#include \"DistributedVector.hpp\"\n#include \"DistributedVectorFactory.hpp\"\n#include \"Version.hpp\"\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid Hdf5ToMeshalyzerConverter<ELEMENT_DIM,SPACE_DIM>::Write(std::string type)\n{\n\n    std::string filename = \"\";\n    if (this->mDatasetNames[this->mOpenDatasetIndex] == \"Data\")\n    {\n        filename += this->mFileBaseName + \"_\";\n    }\n    filename += type + \".dat\";\n\n    out_stream p_file = out_stream(nullptr);\n    if (PetscTools::AmMaster())\n    {\n        p_file = this->mpOutputFileHandler->OpenOutputFile(filename);\n\n        \/\/ Check how many digits are to be output in the solution (0 goes to default value of digits)\n        if (this->mPrecision != 0)\n        {\n           p_file->precision(this->mPrecision);\n        }\n    }\n\n    unsigned num_nodes = this->mpReader->GetNumberOfRows();\n    unsigned num_timesteps = this->mpReader->GetUnlimitedDimensionValues().size();\n\n    DistributedVectorFactory factory(num_nodes);\n\n    Vec data = factory.CreateVec();\n    ReplicatableVector repl_data(num_nodes);\n    for (unsigned time_step=0; time_step<num_timesteps; time_step++)\n    {\n        this->mpReader->GetVariableOverNodes(data, type, time_step);\n        repl_data.ReplicatePetscVector(data);\n\n        assert(repl_data.GetSize() == num_nodes);\n\n        if (PetscTools::AmMaster())\n        {\n            for (unsigned i=0; i<num_nodes; i++)\n            {\n                *p_file << repl_data[i] << \"\\n\";\n            }\n        }\n    }\n    PetscTools::Destroy(data);\n    if (PetscTools::AmMaster())\n    {\n        std::string comment = \"# \" + ChasteBuildInfo::GetProvenanceString();\n        *p_file << comment;\n        p_file->close();\n    }\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nHdf5ToMeshalyzerConverter<ELEMENT_DIM,SPACE_DIM>::Hdf5ToMeshalyzerConverter(const FileFinder& rInputDirectory,\n                                                                            const std::string& rFileBaseName,\n                                                                            AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* pMesh,\n                                                                            bool usingOriginalNodeOrdering,\n                                                                            unsigned precision)\n    : AbstractHdf5Converter<ELEMENT_DIM,SPACE_DIM>(rInputDirectory, rFileBaseName, pMesh, \"output\", precision)\n{\n    do\n    {\n        std::vector<std::string> variable_names = this->mpReader->GetVariableNames();\n        for (unsigned i=0; i<variable_names.size(); i++)\n        {\n            Write(variable_names[i]);\n        }\n    }\n    while ( this->MoveOntoNextDataset() );\n\n    \/\/ Now we might call this class more than once, so we don't always need to write the mesh out.\n    \/\/ so check to see if it is there already.\n    FileFinder test_output(\"\",RelativeTo::ChasteTestOutput);\n    std::string output_directory = rInputDirectory.GetRelativePath(test_output) + \"\/\" + this->mRelativeSubdirectory;\n    FileFinder mesh_file(output_directory + \"\/\" + rFileBaseName + \"_mesh.pts\", RelativeTo::ChasteTestOutput);\n\n    if (!mesh_file.IsFile())\n    {\n        \/\/ Write mesh in a suitable form for meshalyzer\n        MeshalyzerMeshWriter<ELEMENT_DIM,SPACE_DIM> mesh_writer(output_directory, rFileBaseName + \"_mesh\", false);\n\n        \/\/ Normal case is that the in-memory mesh is converted\n        if (!usingOriginalNodeOrdering || !this->mpMesh->IsMeshOnDisk())\n        {\n            \/\/ The second argument tells the writer to not follow original element ordering for performance reasons.\n            mesh_writer.WriteFilesUsingMesh(*(this->mpMesh), false);\n        }\n        else\n        {\n            \/\/ In this case we expect the mesh to have been read in from file\n            \/\/\/\\todo What if the mesh has been scaled, translated or rotated?\n            \/\/ Note that the next line will throw if the mesh has not been read from file\n            std::string original_file = this->mpMesh->GetMeshFileBaseName();\n            std::shared_ptr<AbstractMeshReader<ELEMENT_DIM, SPACE_DIM> > p_original_mesh_reader\n                = GenericMeshReader<ELEMENT_DIM, SPACE_DIM>(original_file);\n            mesh_writer.WriteFilesUsingMeshReader(*p_original_mesh_reader);\n        }\n    }\n    PetscTools::Barrier(\"Hdf5ToMeshalyzerConverter\");\n}\n\n\/\/ Explicit instantiation\ntemplate class Hdf5ToMeshalyzerConverter<1,1>;\ntemplate class Hdf5ToMeshalyzerConverter<1,2>;\ntemplate class Hdf5ToMeshalyzerConverter<2,2>;\ntemplate class Hdf5ToMeshalyzerConverter<1,3>;\ntemplate class Hdf5ToMeshalyzerConverter<2,3>;\ntemplate class Hdf5ToMeshalyzerConverter<3,3>;\n","avg_line_length":41.9808917197,"max_line_length":130,"alphanum_fraction":0.6842664239,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":796,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":32.0,"content":"\/*\n\tCopyright (c) 2019 Rat431 (https:\/\/github.com\/Rat431).\n\tThis software is under the MIT license, for more informations check the LICENSE file.\n*\/\n\n#include \"pch.h\"\n#include \"hooks.h\"\n\nchar ColdHisdepath[MAX_PATH] = { 0 };\n\nBOOL APIENTRY DllMain( HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)\n{\n\tif (ul_reason_for_call == DLL_PROCESS_ATTACH)\n\t{\n\t\tchar myfile[MAX_PATH] = { 0 };\n\t\tGetModuleFileNameA(hModule, myfile, MAX_PATH);\n\t\tint size = lstrlenA(myfile);\n\t\tfor (int i = size; i > 0; i--) {\n\t\t\tif (myfile[i] == '\\\\') {\n\t\t\t\tRtlFillMemory(&myfile[i + 1], size - i + 1, NULL);\n\t\t\t\tbreak;\n\n\t\t\t}\n\t\t}\n\t\tlstrcpyA(ColdHisdepath, myfile);\n\t\tHooks_Manager::Init((ULONG_PTR)hModule);\n\t}\n\tif (ul_reason_for_call == DLL_PROCESS_DETACH)\n\t{\n\t\tHooks_Manager::ShutDown();\n\t}\n\treturn TRUE;\n}\n\n","avg_line_length":22.7428571429,"max_line_length":86,"alphanum_fraction":0.6746231156,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2196,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":5.0,"content":"#include <IO\/ZlibInflatingReadBuffer.h>\n\n\nnamespace DB\n{\n\nZlibInflatingReadBuffer::ZlibInflatingReadBuffer(\n        ReadBuffer & in_,\n        ZlibCompressionMethod compression_method,\n        size_t buf_size,\n        char * existing_memory,\n        size_t alignment)\n    : BufferWithOwnMemory<ReadBuffer>(buf_size, existing_memory, alignment)\n    , in(in_)\n    , eof(false)\n{\n    zstr.zalloc    = Z_NULL;\n    zstr.zfree     = Z_NULL;\n    zstr.opaque    = Z_NULL;\n    zstr.next_in   = 0;\n    zstr.avail_in  = 0;\n    zstr.next_out  = 0;\n    zstr.avail_out = 0;\n\n    int window_bits = 15;\n    if (compression_method == ZlibCompressionMethod::Gzip)\n    {\n        window_bits += 16;\n    }\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wold-style-cast\"\n    int rc = inflateInit2(&zstr, window_bits);\n#pragma GCC diagnostic pop\n\n    if (rc != Z_OK)\n        throw Exception(std::string(\"inflateInit2 failed: \") + zError(rc) + \"; zlib version: \" + ZLIB_VERSION, ErrorCodes::ZLIB_INFLATE_FAILED);\n}\n\nZlibInflatingReadBuffer::~ZlibInflatingReadBuffer()\n{\n    inflateEnd(&zstr);\n}\n\nbool ZlibInflatingReadBuffer::nextImpl()\n{\n    if (eof)\n        return false;\n\n    if (!zstr.avail_in)\n    {\n        in.nextIfAtEnd();\n        zstr.next_in = reinterpret_cast<unsigned char *>(in.position());\n        zstr.avail_in = in.buffer().end() - in.position();\n    }\n    zstr.next_out = reinterpret_cast<unsigned char *>(internal_buffer.begin());\n    zstr.avail_out = internal_buffer.size();\n\n    int rc = inflate(&zstr, Z_NO_FLUSH);\n\n    in.position() = in.buffer().end() - zstr.avail_in;\n    working_buffer.resize(internal_buffer.size() - zstr.avail_out);\n\n    if (rc == Z_STREAM_END)\n    {\n        if (in.eof())\n        {\n            eof = true;\n            return working_buffer.size() != 0;\n        }\n        else\n        {\n            int rc = inflateReset(&zstr);\n            if (rc != Z_OK)\n                throw Exception(std::string(\"inflateReset failed: \") + zError(rc), ErrorCodes::ZLIB_INFLATE_FAILED);\n            return true;\n        }\n    }\n    if (rc != Z_OK)\n        throw Exception(std::string(\"inflate failed: \") + zError(rc), ErrorCodes::ZLIB_INFLATE_FAILED);\n\n    return true;\n}\n\n}\n","avg_line_length":25.5348837209,"max_line_length":144,"alphanum_fraction":0.6156648452,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1443,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <QApplication>\n#include <QDebug>\n#include <QFile>\n\n#include \"config.hpp\"\n#include \"main-window.hpp\"\n#include \"networking.hpp\"\n#include \"password-dialog.hpp\"\n#include \"theme.hpp\"\n\nint main(int argc, char *argv[]) {\n  QApplication::setApplicationName(\"nmpopup\");\n\n  \/\/ parse command line\n  auto args = QStringList();\n  std::transform(argv + 1, argv + argc, std::back_inserter(args),\n                 [&](auto s) { return s; });\n  config().parse(args);\n\n  \/\/ execute different commands\n  switch (config().command) {\n    case Command::Run: {\n      QApplication a(argc, argv);\n\n      if (config().darkPalette) {\n        theme().installDarkTheme();\n        theme().loadInternalDarkTheme();\n      }\n\n      \/\/ password dialog\n      QObject::connect(&networking(), &Networking::passwordRequired,\n                       [](const QString &ssid) {\n                         showPasswordDialog(ssid, [](const QString &ssid,\n                                                     const QString &password) {\n                           config().setPasswordForSsid(ssid, password);\n                           networking().connectWifi(ssid, password);\n                         });\n                       });\n\n      MainWindow w;\n      w.show();\n      return a.exec();\n    } \/\/ break;\n    case Command::ShowHelp: {\n      QFile help(\":\/help.txt\");\n      help.open(QIODevice::ReadOnly);\n      qInfo().noquote() << QString(help.readAll());\n    } break;\n  }\n}\n","avg_line_length":28.2941176471,"max_line_length":79,"alphanum_fraction":0.5426195426,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2726,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkPath.h\"\n#include \"include\/core\/SkRegion.h\"\n#include \"include\/core\/SkShader.h\"\n#include \"include\/effects\/SkCornerPathEffect.h\"\n#include \"include\/effects\/SkGradientShader.h\"\n#include \"samplecode\/Sample.h\"\n#include \"src\/utils\/SkUTF.h\"\n\nclass FillTypeView : public Sample {\n    SkPath fPath;\npublic:\n    FillTypeView() {\n        const SkScalar radius = SkIntToScalar(45);\n        fPath.addCircle(SkIntToScalar(50), SkIntToScalar(50), radius);\n        fPath.addCircle(SkIntToScalar(100), SkIntToScalar(100), radius);\n\n        this->setBGColor(0xFFDDDDDD);\n    }\n\nprotected:\n    SkString name() override{ return SkString(\"FillType\"); }\n\n    void showPath(SkCanvas* canvas, int x, int y, SkPathFillType ft,\n                  SkScalar scale, const SkPaint& paint) {\n\n        const SkRect r = { 0, 0, SkIntToScalar(150), SkIntToScalar(150) };\n\n        canvas->save();\n        canvas->translate(SkIntToScalar(x), SkIntToScalar(y));\n        canvas->clipRect(r);\n        canvas->drawColor(SK_ColorWHITE);\n        fPath.setFillType(ft);\n        canvas->translate(r.centerX(), r.centerY());\n        canvas->scale(scale, scale);\n        canvas->translate(-r.centerX(), -r.centerY());\n        canvas->drawPath(fPath, paint);\n        canvas->restore();\n    }\n\n    void showFour(SkCanvas* canvas, SkScalar scale, const SkPaint& paint) {\n        showPath(canvas,   0,   0, SkPathFillType::kWinding,\n                 scale, paint);\n        showPath(canvas, 200,   0, SkPathFillType::kEvenOdd,\n                 scale, paint);\n        showPath(canvas,  00, 200, SkPathFillType::kInverseWinding,\n                 scale, paint);\n        showPath(canvas, 200, 200, SkPathFillType::kInverseEvenOdd,\n                 scale, paint);\n    }\n\n    void onDrawContent(SkCanvas* canvas) override {\n        canvas->translate(SkIntToScalar(20), SkIntToScalar(20));\n\n        SkPaint paint;\n        const SkScalar scale = SkIntToScalar(5)\/4;\n\n        paint.setAntiAlias(false);\n        paint.setColor(0x8000FF00);\n\n        showFour(canvas, SK_Scalar1, paint);\n        canvas->translate(SkIntToScalar(450), 0);\n        showFour(canvas, scale, paint);\n\n        paint.setAntiAlias(true);\n\n        canvas->translate(SkIntToScalar(-450), SkIntToScalar(450));\n        showFour(canvas, SK_Scalar1, paint);\n        canvas->translate(SkIntToScalar(450), 0);\n        showFour(canvas, scale, paint);\n    }\n\nprivate:\n    typedef Sample INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nDEF_SAMPLE( return new FillTypeView(); )\n","avg_line_length":31.6976744186,"max_line_length":78,"alphanum_fraction":0.623624358,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":699,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n\/\/\n\/\/ Unit tests for block-chain checkpoints\n\/\/\n\n#include \"checkpoints.h\"\n\n#include \"uint256.h\"\n#include \"test\/test_rulaicoin.h\"\n#include \"chainparams.h\"\n\n#include <boost\/test\/unit_test.hpp>\n\nusing namespace std;\n\nBOOST_FIXTURE_TEST_SUITE(Checkpoints_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(sanity)\n{\n    const CCheckpointData& checkpoints = Params(CBaseChainParams::MAIN).Checkpoints();\n    BOOST_CHECK(Checkpoints::GetTotalBlocksEstimate(checkpoints) >= 107996);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":24.9642857143,"max_line_length":86,"alphanum_fraction":0.7811158798,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":762,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":7.0,"content":"#include \"draw.h\"\n\nnamespace draw {\n\nbool operator == (const Point& left, const Point& right) {\n\n    return left.x == right.x && left.y == right.y;\n}\n\nbool operator != (const Point& left, const Point& right) {\n\n    return !(left == right);\n}\n\nbool operator == (const Size& left, const Size& right) {\n\n    return left.width == right.width && left.height == right.height;\n}\n\nbool operator != (const Size& left, const Size& right) {\n\n    return !(left == right);\n}\n\nbool operator == (const Rect& left, const Rect& right) {\n\n    return left.left == right.left && left.bottom == right.bottom &&\n        left.right == right.right && left.top == right.top;\n}\n\nbool operator != (const Rect& left, const Rect& right) {\n\n    return !(left == right);\n}\n\n} \/\/ namespace draw","avg_line_length":21.1666666667,"max_line_length":68,"alphanum_fraction":0.6207349081,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":29484,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n    The Scopes Compiler Infrastructure\n    This file is distributed under the MIT License.\n    See LICENSE.md for details.\n*\/\n\n#include \"quote.hpp\"\n#include \"value.hpp\"\n#include \"types.hpp\"\n#include \"error.hpp\"\n#include \"prover.hpp\"\n\/\/#include \"closure.hpp\"\n#include \"stream_expr.hpp\"\n\/\/#include \"hash.hpp\"\n\/\/#include \"timer.hpp\"\n\/\/#include \"gc.hpp\"\n\/\/#include \"builtin.hpp\"\n\/\/#include \"verify_tools.inc\"\n#include \"dyn_cast.inc\"\n\/\/#include \"compiler_flags.hpp\"\n\/\/#include \"gen_llvm.hpp\"\n\/\/#include \"list.hpp\"\n\/\/#include \"expander.hpp\"\n#include \"globals.hpp\"\n#include \"anchor.hpp\"\n#include \"scopes\/scopes.h\"\n\n#include \"qualifier\/refer_qualifier.hpp\"\n#include \"qualifier.inc\"\n\n\/\/#pragma GCC diagnostic ignored \"-Wvla-extension\"\n\nnamespace scopes {\n\n#define REF(X) ref(_anchor, (X))\n\n#define LOCALREF(X) \\\n    ref(Anchor::from(Symbol(String::from(__FILE__)), __LINE__, 1), (X))\n\nstatic ValueRef canonicalize(const ExpressionRef &expr) {\n    if (expr->body.empty())\n        return expr->value;\n    return expr;\n}\n\nValueRef build_quoted_argument_list(const Anchor *_anchor, const Values &values) {\n    auto result = REF(Expression::unscoped_from());\n    auto numvals = (int)values.size();\n    auto numelems = REF(ConstInt::from(TYPE_I32, numvals));\n    auto buf = REF(CallTemplate::from(g_alloca_array, {\n            REF(ConstPointer::type_from(TYPE_ValueRef)),\n            numelems\n        }));\n    result->append(buf);\n    for (int i = 0; i < numvals; ++i) {\n        auto idx = REF(ConstInt::from(TYPE_I32, i));\n        result->append(\n            REF(CallTemplate::from(g_store, {\n                REF(CallTemplate::from(g_sc_identity, { values[i] })),\n                REF(CallTemplate::from(g_getelementptr, { buf, idx }))\n            })));\n    }\n    result->append(REF(CallTemplate::from(g_sc_argument_list_new,\n        { numelems, buf })));\n    return canonicalize(result);\n}\n\n\/\/------------------------------------------------------------------------------\n\nstruct Quoter {\n    Quoter(const ASTContext  &_ctx) :\n        ctx(_ctx) {}\n\n    SCOPES_RESULT(ValueRef) quote_Expression(int level, const ExpressionRef &node) {\n        SCOPES_RESULT_TYPE(ValueRef);\n        auto _anchor = node.anchor();\n        auto value = REF(CallTemplate::from(g_sc_expression_new, {}));\n        auto expr = REF(Expression::unscoped_from());\n        if (node->scoped) {\n            expr->append(REF(CallTemplate::from(g_sc_expression_set_scoped, { value })));\n        }\n        for (auto &&instr : node->body) {\n            expr->append(REF(CallTemplate::from(g_sc_expression_append,\n                { value, SCOPES_GET_RESULT(quote(level, instr)) })));\n        }\n        expr->append(REF(CallTemplate::from(g_sc_expression_append,\n            { value, SCOPES_GET_RESULT(quote(level, node->value)) })));\n        expr->append(value);\n        return canonicalize(expr);\n    }\n\n    SCOPES_RESULT(ValueRef) quote_ArgumentListTemplate(int level, const ArgumentListTemplateRef &node) {\n        SCOPES_RESULT_TYPE(ValueRef);\n        \/*if (node->values.size() == 1) {\n            return quote(level, node->values[0]);\n        } else*\/ {\n            Values newvalues;\n            auto &&values = node->values();\n            int count = (int)values.size();\n            newvalues.reserve(count);\n            for (int i = 0; i < count; ++i) {\n                newvalues.push_back(SCOPES_GET_RESULT(quote(level, values[i])));\n            }\n            auto _anchor = node.anchor();\n            return build_quoted_argument_list(_anchor, newvalues);\n        }\n    }\n\n    SCOPES_RESULT(CallTemplateRef) quote_ExtractArgumentTemplate(int level, const ExtractArgumentTemplateRef &node) {\n        SCOPES_RESULT_TYPE(CallTemplateRef);\n        auto _anchor = node.anchor();\n        if (node->vararg) {\n            return REF(CallTemplate::from(g_sc_extract_argument_list_new, {\n                    SCOPES_GET_RESULT(quote(level, node->value)),\n                    REF(ConstInt::from(TYPE_I32, node->index)) }));\n        } else {\n            return REF(CallTemplate::from(g_sc_extract_argument_new, {\n                    SCOPES_GET_RESULT(quote(level, node->value)),\n                    REF(ConstInt::from(TYPE_I32, node->index)) }));\n        }\n    }\n\n    SCOPES_RESULT(TypedValueRef) quote_param(const ParameterTemplateRef &node) {\n        SCOPES_RESULT_TYPE(TypedValueRef);\n        auto _anchor = node.anchor();\n        auto newparam = REF(CallTemplate::from(g_sc_parameter_new, {\n            REF(ConstInt::symbol_from(node->name)) }));\n        auto typednewparam = SCOPES_GET_RESULT(prove(ctx, newparam));\n        bind(node, typednewparam);\n        ctx.frame->bind(node, typednewparam);\n        return typednewparam;\n    }\n\n    SCOPES_RESULT(ValueRef) quote_Loop(int level, const LoopRef &node) {\n        SCOPES_RESULT_TYPE(ValueRef);\n        auto _anchor = node.anchor();\n        auto value = REF(CallTemplate::from(g_sc_loop_new, {\n            SCOPES_GET_RESULT(quote(level, node->init))\n        }));\n        auto args = REF(CallTemplate::from(g_sc_loop_arguments, { value }));\n        auto typedargs = SCOPES_GET_RESULT(prove(ctx, args));\n        ctx.frame->bind(args, typedargs);\n        bind(node->args, typedargs);\n        auto expr = REF(Expression::unscoped_from());\n        expr->append(value);\n        expr->append(args);\n        expr->append(REF(CallTemplate::from(g_sc_loop_set_body, { value,\n            SCOPES_GET_RESULT(quote(level, node->value)) })));\n        expr->append(value);\n        return canonicalize(expr);\n    }\n\n    SCOPES_RESULT(ValueRef) quote_CompileStage(int level, const CompileStageRef &node) {\n        SCOPES_RESULT_TYPE(ValueRef);\n        SCOPES_ERROR(QuoteUnsupportedValueKind, node->kind());\n    }\n\n    SCOPES_RESULT(CallTemplateRef) quote_KeyedTemplate(int level, const KeyedTemplateRef &node) {\n        SCOPES_RESULT_TYPE(CallTemplateRef);\n        auto value = SCOPES_GET_RESULT(quote(level, node->value));\n        auto _anchor = node.anchor();\n        return REF(CallTemplate::from(g_sc_keyed_new,\n            { REF(ConstInt::symbol_from(node->key)), value }));\n    }\n\n    SCOPES_RESULT(ValueRef) quote_CallTemplate(int level, const CallTemplateRef &node) {\n        SCOPES_RESULT_TYPE(ValueRef);\n        auto _anchor = node.anchor();\n        auto value = REF(CallTemplate::from(g_sc_call_new, {\n            SCOPES_GET_RESULT(quote(level, node->callee))\n        }));\n        auto expr = REF(Expression::unscoped_from());\n        if (node->is_rawcall()) {\n            expr->append(REF(CallTemplate::from(g_sc_call_set_rawcall, { value,\n                REF(ConstInt::from(TYPE_Bool, true)) })));\n        }\n        for (auto &&arg : node->args) {\n            expr->append(REF(CallTemplate::from(g_sc_call_append_argument,\n                { value, SCOPES_GET_RESULT(quote(level, arg)) })));\n        }\n        expr->append(value);\n        return canonicalize(expr);\n    }\n\n    SCOPES_RESULT(TypedValueRef) quote_ParameterTemplate(int level, const ParameterTemplateRef &sym) {\n        SCOPES_RESULT_TYPE(TypedValueRef);\n        auto value = resolve(sym);\n        if (!value) {\n            SCOPES_ERROR(QuoteUnboundValue, sym);\n        }\n        return value;\n    }\n\n    SCOPES_RESULT(TypedValueRef) quote_LoopArguments(int level, const LoopArgumentsRef &sym) {\n        SCOPES_RESULT_TYPE(TypedValueRef);\n        auto value = resolve(sym);\n        if (!value) {\n            SCOPES_ERROR(QuoteUnboundValue, sym);\n        }\n        return value;\n    }\n\n    SCOPES_RESULT(ValueRef) quote_CaseTemplate(int level, const CaseTemplateRef &node) {\n        SCOPES_RESULT_TYPE(ValueRef);\n        auto _anchor = node.anchor();\n        ValueRef result;\n        switch(node->case_kind) {\n        case CK_Case: {\n            result = REF(CallTemplate::from(g_sc_case_new, {\n                SCOPES_GET_RESULT(quote(level, node->literal)),\n                SCOPES_GET_RESULT(quote(level, node->value)) }));\n        } break;\n        case CK_Pass: {\n            result = REF(CallTemplate::from(g_sc_pass_case_new, {\n                SCOPES_GET_RESULT(quote(level, node->literal)),\n                SCOPES_GET_RESULT(quote(level, node->value)) }));\n        } break;\n        case CK_Do: {\n            result = REF(CallTemplate::from(g_sc_do_case_new, {\n                SCOPES_GET_RESULT(quote(level, node->value)) }));\n        } break;\n        case CK_Default: {\n            result = REF(CallTemplate::from(g_sc_default_case_new, {\n                SCOPES_GET_RESULT(quote(level, node->value)) }));\n        } break;\n        default: assert(false);\n        }\n        return result;\n    }\n\n    SCOPES_RESULT(ValueRef) quote_SwitchTemplate(int level, const SwitchTemplateRef &node) {\n        SCOPES_RESULT_TYPE(ValueRef);\n        auto _anchor = node.anchor();\n        auto value = REF(CallTemplate::from(g_sc_switch_new, {\n            SCOPES_GET_RESULT(quote(level, node->expr))\n        }));\n        auto expr = REF(Expression::unscoped_from());\n        for (auto &&_case : node->cases) {\n            auto _anchor = _case.anchor();\n            expr->append(REF(CallTemplate::from(g_sc_switch_append, { value,\n                SCOPES_GET_RESULT(quote(level, _case)) })));\n        }\n        expr->append(value);\n        return canonicalize(expr);\n    }\n\n    SCOPES_RESULT(ValueRef) quote_CondTemplate(int level, const CondTemplateRef &node) {\n        SCOPES_RESULT_TYPE(ValueRef);\n        auto _anchor = node.anchor();\n        return ValueRef(REF(CallTemplate::from(g_sc_cond_new, {\n            SCOPES_GET_RESULT(quote(level, node->cond)),\n            SCOPES_GET_RESULT(quote(level, node->then_value)),\n            SCOPES_GET_RESULT(quote(level, node->else_value))\n        })));\n    }\n\n    SCOPES_RESULT(ValueRef) quote_Template(int level, const TemplateRef &node) {\n        SCOPES_RESULT_TYPE(ValueRef);\n        auto _anchor = node.anchor();\n        auto value = REF(CallTemplate::from(g_sc_template_new,\n            { REF(ConstInt::symbol_from(node->name)) }));\n        auto expr = REF(Expression::unscoped_from());\n        if (node->is_inline()) {\n            expr->append(REF(CallTemplate::from(g_sc_template_set_inline, { value })));\n        }\n        for (auto &&param : node->params) {\n            expr->append(REF(CallTemplate::from(g_sc_template_append_parameter, {\n                value, SCOPES_GET_RESULT(quote_param(param))\n            })));\n        }\n        expr->append(REF(CallTemplate::from(g_sc_template_set_body, { value,\n            SCOPES_GET_RESULT(quote(level, node->value)) })));\n        expr->append(value);\n        return canonicalize(expr);\n    }\n\n    SCOPES_RESULT(CallTemplateRef) quote_Quote(int level, const QuoteRef &node) {\n        SCOPES_RESULT_TYPE(CallTemplateRef);\n        auto _anchor = node.anchor();\n        return REF(CallTemplate::from(g_sc_quote_new,\n            { SCOPES_GET_RESULT(quote(level+1, node->value)) }));\n    }\n\n    ValueRef quote_typed_argument_list(const ArgumentListRef &node) {\n        \/*if (node->values.size() == 1) {\n            return quote_typed(node->values[0]);\n        } else*\/ {\n            Values newvalues;\n            auto _anchor = node.anchor();\n            int count = (int)node->values.size();\n            newvalues.reserve(count);\n            for (int i = 0; i < count; ++i) {\n                newvalues.push_back(quote_typed(node->values[i]));\n            }\n            return build_quoted_argument_list(_anchor, newvalues);\n        }\n    }\n\n    ValueRef quote_typed(const TypedValueRef &node) {\n        auto T = node->get_type();\n        if (T == TYPE_ValueRef)\n            return node;\n        if (is_reference(T) && (strip_qualifiers(T) == TYPE_ValueRef)) {\n            auto _anchor = node.anchor();\n            return REF(CallTemplate::from(g_deref, { node }));\n        }\n\n        if (node.isa<ArgumentList>()) {\n            return quote_typed_argument_list(node.cast<ArgumentList>());\n        } else {\n            auto result = wrap_value(node->get_type(), node);\n            assert(result);\n            return result;\n        }\n    }\n\n    SCOPES_RESULT(ValueRef) quote_Unquote(int level, const UnquoteRef &node) {\n        SCOPES_RESULT_TYPE(ValueRef);\n        assert(level >= 0);\n        if (!level) {\n            auto value = SCOPES_GET_RESULT(prove(ctx, node->value));\n            auto T = value->get_type();\n            if (is_arguments_type(T)) {\n                auto at = cast<ArgumentsType>(T);\n                auto _anchor = node.anchor();\n                {\n                    Values newvalues;\n                    int count = (int)at->values.size();\n                    newvalues.reserve(count);\n                    for (int i = 0; i < count; ++i) {\n                        newvalues.push_back(ExtractArgument::from(value, i));\n                    }\n                    return build_quoted_argument_list(_anchor, newvalues);\n                }\n            } else {\n                return quote_typed(value);\n            }\n        } else {\n            auto _anchor = node.anchor();\n            return ValueRef(REF(CallTemplate::from(g_sc_unquote_new,\n                { SCOPES_GET_RESULT(quote(level-1, node->value)) })));\n        }\n    }\n\n    SCOPES_RESULT(CallTemplateRef) quote_MergeTemplate(int level, const MergeTemplateRef &node) {\n        SCOPES_RESULT_TYPE(CallTemplateRef);\n        auto _anchor = node.anchor();\n        return REF(CallTemplate::from(g_sc_merge_new, {\n            SCOPES_GET_RESULT(quote(level, node->label)),\n            SCOPES_GET_RESULT(quote(level, node->value))\n        }));\n    }\n\n    SCOPES_RESULT(ValueRef) quote_LabelTemplate(int level, const LabelTemplateRef &node) {\n        SCOPES_RESULT_TYPE(ValueRef);\n        auto _anchor = node.anchor();\n        auto value = REF(CallTemplate::from(g_sc_label_new, {\n            REF(ConstInt::from(TYPE_I32, node->label_kind)),\n            REF(ConstInt::symbol_from(node->name))\n        }));\n        auto typedvalue = SCOPES_GET_RESULT(prove(ctx, value));\n        bind(node, typedvalue);\n        ctx.frame->bind(node, typedvalue);\n        auto expr = REF(Expression::unscoped_from());\n        expr->append(REF(CallTemplate::from(g_sc_label_set_body, { typedvalue,\n            SCOPES_GET_RESULT(quote(level, node->value)) })));\n        expr->append(typedvalue);\n        return canonicalize(expr);\n    }\n\n    SCOPES_RESULT(ValueRef) quote_new_node(int level, const ValueRef &node) {\n        SCOPES_RESULT_TYPE(ValueRef);\n        assert(node);\n        ValueRef result;\n        if (node.isa<TypedValue>()) {\n            result = quote_typed(node.cast<TypedValue>());\n        } else {\n            \/\/ we shouldn't set an anchor here because sometimes the parent context\n            \/\/ is more indicative than the node position\n            \/\/SCOPES_CHECK_RESULT(verify_stack());\n            switch(node->kind()) {\n    #define T(NAME, BNAME, CLASS) \\\n            case NAME: result = SCOPES_GET_RESULT(quote_ ## CLASS(level, node.cast<CLASS>())); break;\n            SCOPES_UNTYPED_VALUE_KIND()\n    #undef T\n            default: assert(false);\n            }\n            assert(result);\n        }\n        return result;\n    }\n\n    SCOPES_RESULT(TypedValueRef) quote(int level, const ValueRef &node) {\n        SCOPES_RESULT_TYPE(TypedValueRef);\n        assert(node);\n        assert(ctx.frame);\n        {\n            \/\/ check if node is already typed\n            TypedValueRef result = SCOPES_GET_RESULT(ctx.frame->resolve(node, ctx.function));\n            if (result) {\n                \/\/ check if we have an existing wrap for the node\n                TypedValueRef wrapped = resolve(result);\n                if (!wrapped) {\n                    \/\/ wrap it anew and type it\n                    wrapped = SCOPES_GET_RESULT(prove(ctx, quote_typed(result)));\n                    bind(result, wrapped);\n                }\n                return wrapped;\n            }\n        }\n        \/\/ check if we have an existing quote for the node\n        TypedValueRef result = resolve(node);\n        if (result) return result;\n        \/\/ node is untyped or unbound yet\n        ValueRef untyped_result = SCOPES_GET_RESULT(quote_new_node(level, node));\n        if (untyped_result.isa<TypedValue>()) {\n            result = untyped_result.cast<TypedValue>();\n        } else {\n            result = SCOPES_GET_RESULT(prove(ctx, untyped_result));\n        }\n        bind(node, result);\n        if (!node.isa<TypedValue>()) {\n            #if 0\n            StyledStream ss;\n            ss << \"binding \";\n            stream_ast(ss, node, StreamASTFormat());\n            ss << \" to \";\n            stream_ast(ss, result, StreamASTFormat());\n            ss << std::endl;\n            #endif\n            \/\/ ensure that the unquoted context can access the typed result\n            ctx.frame->bind(node, result);\n        }\n        return result;\n    }\n\n    void bind(const ValueRef &oldnode, const TypedValueRef &newnode) {\n        auto it = map.insert({oldnode.unref(), newnode});\n        if (!it.second) {\n            it.first->second = newnode;\n        }\n    }\n\n    TypedValueRef resolve(const ValueRef &node) const {\n        auto it = map.find(node.unref());\n        if (it == map.end())\n            return TypedValueRef();\n        return it->second;\n    }\n\n    #define T(NAME, BNAME, CLASS) \\\n        SCOPES_RESULT(ConstAggregateRef) quote_ ## CLASS(int level, const ValueRef &node) { \\\n            return ConstAggregate::ast_from(node); \\\n        }\n    SCOPES_PURE_VALUE_KIND()\n    #undef T\n\n    std::unordered_map<Value *, TypedValueRef> map;\n    const ASTContext &ctx;\n};\n\nValueRef unwrap_value(const Type *T, const ValueRef &value) {\n    auto _anchor = value.anchor();\n    \/\/T = strip_qualifiers(T);\n    auto ST = storage_type(T).assert_ok();\n    auto kind = ST->kind();\n    switch(kind) {\n    case TK_Pointer: {\n        return REF(CallTemplate::from(g_bitcast, {\n                REF(CallTemplate::from(g_sc_const_pointer_extract, { value })),\n                REF(ConstPointer::type_from(T))\n            }));\n    } break;\n    case TK_Integer: {\n        auto ti = cast<IntegerType>(ST);\n        if (ti->width <= 64ull) {\n            return REF(CallTemplate::from(g_itrunc, {\n                    REF(CallTemplate::from(g_sc_const_int_extract, { value })),\n                    REF(ConstPointer::type_from(T))\n                }));\n        } else {\n            \/\/ big integer\n            auto result = REF(Expression::unscoped_from());\n            size_t numwords = (ti->width + 63ull) \/ 64ull;\n            auto mem = REF(CallTemplate::from(g_alloca_array, {\n                    REF(ConstPointer::type_from(TYPE_U64)),\n                    REF(ConstInt::from(TYPE_I32, numwords)),\n                }));\n            result->append(mem);\n            for (size_t i = 0; i < numwords; ++i) {\n                auto word = REF(CallTemplate::from(g_sc_const_int_extract_word, {\n                    value,\n                    REF(ConstInt::from(TYPE_I32, i)),\n                }));\n                result->append(word);\n                auto ptr = REF(CallTemplate::from(g_getelementptr, { mem,\n                    REF(ConstInt::from(TYPE_I32, i)) }));\n                result->append(ptr);\n                result->append(REF(CallTemplate::from(g_store, { word, ptr })));\n            }\n            auto castmem =\n                REF(CallTemplate::from(g_bitcast, { mem,\n                    REF(ConstPointer::type_from((local_ro_pointer_type(T)))) }));\n            result->append(castmem);\n            result->append(REF(CallTemplate::from(g_load, { castmem })));\n            return result;\n        }\n    } break;\n    case TK_Real: {\n        return REF(CallTemplate::from(g_fptrunc, {\n                REF(CallTemplate::from(g_sc_const_real_extract, { value })),\n                REF(ConstPointer::type_from(T))\n            }));\n    } break;\n    case TK_Vector: {\n        auto vt = cast<VectorType>(ST);\n        auto argT = vt->element_type;\n        auto numvals = (int)vt->count();\n        \/\/auto numelems = ConstInt::from(anchor, TYPE_I32, numvals);\n        ValueRef result = REF(Undef::from(T));\n        for (int i = 0; i < numvals; ++i) {\n            auto idx = REF(ConstInt::from(TYPE_I32, i));\n            auto arg =\n                REF(CallTemplate::from(g_sc_const_extract_at, { value, idx }));\n            auto unwrapped_arg = unwrap_value(argT, arg);\n            assert(unwrapped_arg);\n            result = REF(CallTemplate::from(g_insertelement, { result, unwrapped_arg, idx }));\n        }\n        return result;\n    } break;\n    case TK_Array:\n    case TK_Matrix: {\n        auto at = cast<ArrayLikeType>(ST);\n        auto argT = at->element_type;\n        auto numvals = (int)at->count();\n        \/\/auto numelems = ConstInt::from(anchor, TYPE_I32, numvals);\n        ValueRef result = REF(Undef::from(T));\n        for (int i = 0; i < numvals; ++i) {\n            auto idx = REF(ConstInt::from(TYPE_I32, i));\n            auto arg =\n                REF(CallTemplate::from(g_sc_const_extract_at, { value, idx }));\n            auto unwrapped_arg = unwrap_value(argT, arg);\n            assert(unwrapped_arg);\n            result = REF(CallTemplate::from(g_insertvalue, { result, unwrapped_arg, idx }));\n        }\n        return result;\n    } break;\n    case TK_Tuple: {\n        auto tt = cast<TupleType>(ST);\n        \/\/auto numelems = ConstInt::from(anchor, TYPE_I32, tt->values.size());\n        ValueRef result = REF(Undef::from(T));\n        for (int i = 0; i < tt->values.size(); ++i) {\n            auto idx = REF(ConstInt::from(TYPE_I32, i));\n            auto arg =\n                REF(CallTemplate::from(g_sc_const_extract_at, { value, idx }));\n            auto argT = tt->values[i];\n            auto unwrapped_arg = unwrap_value(argT, arg);\n            assert(unwrapped_arg);\n            result = REF(CallTemplate::from(g_insertvalue, { result, unwrapped_arg, idx }));\n        }\n        \/\/StyledStream ss;\n        \/\/stream_ast(ss, result, StreamASTFormat());\n        return result;\n    } break;\n    default:\n        break;\n    }\n    return ValueRef();\n}\n\nstatic ValueRef wrap_value_inner(const Type *T, const ValueRef &value, bool composite) {\n    auto _anchor = value.anchor();\n    bool isref = is_reference(T);\n    T = strip_qualifiers(T);\n    auto ST = storage_type(T).assert_ok();\n    auto kind = ST->kind();\n    switch(kind) {\n    case TK_Pointer: {\n        if (!composite && (T == TYPE_String)) {\n            return REF(CallTemplate::from(g_sc_const_string_new, { value }));\n        } else {\n            return REF(CallTemplate::from(g_sc_const_pointer_new, {\n                    REF(ConstPointer::type_from(T)),\n                    REF(CallTemplate::from(g_bitcast, { value, g_voidstar })) }));\n        }\n    } break;\n    case TK_Integer: {\n        auto ti = cast<IntegerType>(ST);\n        if (ti->width <= 64ull) {\n            return REF(CallTemplate::from(g_sc_const_int_new, {\n                    REF(ConstPointer::type_from(T)),\n                    REF(CallTemplate::from(ti->issigned?g_sext:g_zext, { value,\n                    g_u64 })) }));\n        } else {\n            \/\/ big integer\n            auto targettype = local_ro_pointer_type(TYPE_U64);\n            auto result = REF(Expression::unscoped_from());\n            auto mem = REF(CallTemplate::from(g_alloca, {\n                    REF(ConstPointer::type_from(T))\n                }));\n            result->append(mem);\n            result->append(REF(CallTemplate::from(g_store, { value, mem })));\n            auto castmem =\n                REF(CallTemplate::from(g_bitcast, { mem,\n                    REF(ConstPointer::type_from(targettype)) }));\n            result->append(castmem);\n            size_t numwords = (ti->width + 63ull) \/ 64ull;\n            result->append(REF(CallTemplate::from(g_sc_const_int_words_new, {\n                    REF(ConstPointer::type_from(T)),\n                    REF(ConstInt::from(TYPE_I32, numwords)),\n                    castmem\n                })));\n            return result;\n        }\n    } break;\n    case TK_Real: {\n        \/\/auto ti = cast<RealType>(ST);\n        return REF(CallTemplate::from(g_sc_const_real_new, {\n                REF(ConstPointer::type_from(T)),\n                REF(CallTemplate::from(g_fpext, { value,\n                g_f64 })) }));\n    } break;\n    case TK_Vector: {\n        auto at = cast<VectorType>(ST);\n        auto result = REF(Expression::unscoped_from());\n        auto ET = at->element_type;\n        auto numvals = (int)at->count();\n        auto numelems = REF(ConstInt::from(TYPE_I32, numvals));\n        auto buf = REF(CallTemplate::from(g_alloca_array, {\n                REF(ConstPointer::type_from(TYPE_ValueRef)),\n                numelems\n            }));\n        result->append(buf);\n        for (int i = 0; i < numvals; ++i) {\n            auto idx = REF(ConstInt::from(TYPE_I32, i));\n            auto arg =\n                REF(CallTemplate::from(g_extractelement, { value, idx }));\n            auto wrapped_arg = wrap_value(ET, arg, true);\n            assert(wrapped_arg);\n            result->append(\n                REF(CallTemplate::from(g_store, {\n                    wrapped_arg,\n                    REF(CallTemplate::from(g_getelementptr, { buf, idx }))\n                })));\n        }\n        result->append(REF(CallTemplate::from(g_sc_const_aggregate_new,\n            { REF(ConstPointer::type_from(T)), numelems, buf })));\n        return result;\n    } break;\n    case TK_Array:\n    case TK_Matrix: {\n        auto at = cast<ArrayLikeType>(ST);\n        auto result = REF(Expression::unscoped_from());\n        auto ET = at->element_type;\n        auto numvals = (int)at->count();\n        auto numelems = REF(ConstInt::from(TYPE_I32, numvals));\n        bool is_stringarray = (ET == TYPE_Char);\n        ValueRef buf;\n        if (is_stringarray && isref) {\n            const Type *rawstring = native_ro_pointer_type(TYPE_Char);\n            buf = REF(CallTemplate::from(g_bitcast, {\n                    REF(CallTemplate::from(g_reftoptr, { value })),\n                    REF(ConstPointer::type_from(rawstring))\n                }));\n            result->append(buf);\n        } else {\n            if (is_stringarray) {\n                buf = REF(CallTemplate::from(g_alloca_array, {\n                    REF(ConstPointer::type_from(TYPE_Char)),\n                    numelems\n                }));\n            } else {\n                buf = REF(CallTemplate::from(g_alloca_array, {\n                    REF(ConstPointer::type_from(TYPE_ValueRef)),\n                    numelems\n                }));\n            }\n            result->append(buf);\n            for (int i = 0; i < numvals; ++i) {\n                auto idx = REF(ConstInt::from(TYPE_I32, i));\n                ValueRef arg =\n                    REF(CallTemplate::from(g_extractvalue, { value, idx }));\n                if (!is_stringarray) {\n                    arg = wrap_value(ET, arg, true);\n                    assert(arg);\n                }\n                result->append(\n                    REF(CallTemplate::from(g_store, {\n                        arg,\n                        REF(CallTemplate::from(g_getelementptr, { buf, idx }))\n                    })));\n            }\n        }\n        if (is_stringarray) {\n            result->append(REF(CallTemplate::from(g_sc_const_string_new,\n                { REF(CallTemplate::from(g_sc_string_new, { buf, numelems })) })));\n        } else {\n            result->append(REF(CallTemplate::from(g_sc_const_aggregate_new,\n                { REF(ConstPointer::type_from(T)), numelems, buf })));\n        }\n        return result;\n    } break;\n    case TK_Tuple: {\n        auto tt = cast<TupleType>(ST);\n        auto result = REF(Expression::unscoped_from());\n        auto numelems = REF(ConstInt::from(TYPE_I32, tt->values.size()));\n        auto buf = REF(CallTemplate::from(g_alloca_array, {\n                REF(ConstPointer::type_from(TYPE_ValueRef)),\n                numelems\n            }));\n        result->append(buf);\n        for (int i = 0; i < tt->values.size(); ++i) {\n            auto idx = REF(ConstInt::from(TYPE_I32, i));\n            auto arg =\n                REF(CallTemplate::from(g_extractvalue, { value, idx }));\n            auto argT = tt->values[i];\n            auto wrapped_arg = wrap_value(argT, arg, true);\n            assert(wrapped_arg);\n            result->append(\n                REF(CallTemplate::from(g_store, {\n                    wrapped_arg,\n                    REF(CallTemplate::from(g_getelementptr, { buf, idx }))\n                })));\n        }\n        result->append(REF(CallTemplate::from(g_sc_const_aggregate_new,\n            { REF(ConstPointer::type_from(T)), numelems, buf })));\n        return result;\n    } break;\n    default:\n        break;\n    }\n    return ValueRef();\n}\n\nValueRef wrap_value(const Type *T, const ValueRef &value, bool composite) {\n    if (is_value_stage_constant(value)) {\n        return ConstAggregate::ast_from(value);\n    }\n    if (!is_opaque(T)) {\n        auto result = wrap_value_inner(T, value, composite);\n        if (!is_plain(T) && !is_view(T)) {\n            auto _anchor = value.anchor();\n            auto expr = REF(Expression::unscoped_from());\n            expr->append(result);\n            expr->append(REF(CallTemplate::from(g_lose, {value})));\n            expr->append(result);\n            return expr;\n        }\n        return result;\n    }\n    return ValueRef();\n}\n\nSCOPES_RESULT(TypedValueRef) quote(const ASTContext &ctx, const ValueRef &node) {\n    return Quoter(ctx).quote(0, node);\n}\n\n\/\/------------------------------------------------------------------------------\n\n} \/\/ namespace scopes\n","avg_line_length":38.7437582129,"max_line_length":117,"alphanum_fraction":0.5635938136,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":33949,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":4.0,"content":"\/\/ *************************************\n\/\/ C++ routines for this program are taken from\n\/\/ a translation of the FORTRAN code written by\n\/\/ U.S. Department of Commerce NTIA\/ITS\n\/\/ Institute for Telecommunication Sciences\n\/\/ *****************\n\/\/ Irregular Terrain Model (ITM) (Longley-Rice)\n\/\/ *************************************\n\n\n\n#include <math.h>\n#include <complex>\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h>\n#include <windows.h>\n\n#define THIRD  (1.0\/3.0)\n#define DllExport  __declspec( dllexport )\n\nusing namespace std;\n\nstruct tcomplex\n{\n\tdouble tcreal;\n\tdouble tcimag;\n};\n\nstruct prop_type\n{\n\tdouble aref;\n\tdouble dist;\n\tdouble hg[2];\n\tdouble wn;\n\tdouble dh;\n\tdouble ens;\n\tdouble gme;\n\tdouble zgndreal;\n\tdouble zgndimag;\n\tdouble he[2];\n\tdouble dl[2];\n\tdouble the[2];\n\tint kwx;\n\tint mdp;\n};\n\nstruct propv_type\n{\n\tdouble sgc;\n\tint lvar;\n\tint mdvar;\n\tint klim;\n};\n\nstruct propa_type\n{\n\tdouble dlsa;\n\tdouble dx;\n\tdouble ael;\n\tdouble ak1;\n\tdouble ak2;\n\tdouble aed;\n\tdouble emd;\n\tdouble aes;\n\tdouble ems;\n\tdouble dls[2];\n\tdouble dla;\n\tdouble tha;\n};\n\nint mymin(const int &i, const int &j)\n{\n\tif (i<j)\n\t\treturn i;\n\telse\n\t\treturn j;\n}\n\nint mymax(const int &i, const int &j)\n{\n\tif (i>j)\n\t\treturn i;\n\telse\n\t\treturn j;\n}\n\ndouble mymin(const double &a, const double &b)\n{\n\tif (a<b)\n\t\treturn a;\n\telse\n\t\treturn b;\n}\n\ndouble mymax(const double &a, const double &b)\n{\n\tif (a>b)\n\t\treturn a;\n\telse\n\t\treturn b;\n}\n\ndouble FORTRAN_DIM(const double &x, const double &y)\n{ \/\/ This performs the FORTRAN DIM function.\n  \/\/ result is x-y if x is greater than y; otherwise result is 0.0\n\tif (x>y)\n\t\treturn x - y;\n\telse\n\t\treturn 0.0;\n}\n\ndouble aknfe(const double &v2)\n{\n\tdouble a;\n\tif (v2<5.76)\n\t\ta = 6.02 + 9.11*sqrt(v2) - 1.27*v2;\n\telse\n\t\ta = 12.953 + 4.343*log(v2);\n\treturn a;\n}\n\ndouble fht(const double& x, const double& pk)\n{\n\tdouble w, fhtv;\n\tif (x<200.0)\n\t{\n\t\tw = -log(pk);\n\t\tif (pk < 1e-5 || x * pow(w, 3.0) > 5495.0)\n\t\t{\n\t\t\tfhtv = -117.0;\n\t\t\tif (x>1.0)\n\t\t\t\tfhtv = 17.372*log(x) + fhtv;\n\t\t}\n\t\telse\n\t\t\tfhtv = 2.5e-5*x*x \/ pk - 8.686*w - 15.0;\n\t}\n\telse\n\t{\n\t\tfhtv = 0.05751*x - 4.343*log(x);\n\t\tif (x<2000.0)\n\t\t{\n\t\t\tw = 0.0134*x*exp(-0.005*x);\n\t\t\tfhtv = (1.0 - w)*fhtv + w * (17.372*log(x) - 117.0);\n\t\t}\n\t}\n\treturn fhtv;\n}\n\ndouble h0f(double r, double et)\n{\n\tdouble a[5] = { 25.0, 80.0, 177.0, 395.0, 705.0 };\n\tdouble b[5] = { 24.0, 45.0,  68.0,  80.0, 105.0 };\n\tdouble q, x;\n\tint it;\n\tdouble h0fv;\n\tit = (int)et;\n\tif (it <= 0)\n\t{\n\t\tit = 1;\n\t\tq = 0.0;\n\t}\n\telse if (it >= 5)\n\t{\n\t\tit = 5;\n\t\tq = 0.0;\n\t}\n\telse\n\t\tq = et - it;\n\tx = pow(1.0 \/ r, 2.0);\n\th0fv = 4.343*log((a[it - 1] * x + b[it - 1])*x + 1.0);\n\tif (q != 0.0)\n\t\th0fv = (1.0 - q)*h0fv + q * 4.343*log((a[it] * x + b[it])*x + 1.0);\n\treturn h0fv;\n}\n\ndouble ahd(double td)\n{\n\tint i;\n\tdouble a[3] = { 133.4,    104.6,     71.8 };\n\tdouble b[3] = { 0.332e-3, 0.212e-3, 0.157e-3 };\n\tdouble c[3] = { -4.343,   -1.086,    2.171 };\n\tif (td <= 10e3)\n\t\ti = 0;\n\telse if (td <= 70e3)\n\t\ti = 1;\n\telse\n\t\ti = 2;\n\treturn a[i] + b[i] * td + c[i] * log(td);\n}\n\ndouble  adiff(double d, prop_type &prop, propa_type &propa)\n{\n\tcomplex<double> prop_zgnd(prop.zgndreal, prop.zgndimag);\n\tstatic double wd1, xd1, afo, qk, aht, xht;\n\tdouble a, q, pk, ds, th, wa, ar, wd, adiffv;\n\tif (d == 0)\n\t{\n\t\tq = prop.hg[0] * prop.hg[1];\n\t\tqk = prop.he[0] * prop.he[1] - q;\n\t\tif (prop.mdp<0.0)\n\t\t\tq += 10.0;\n\t\twd1 = sqrt(1.0 + qk \/ q);\n\t\txd1 = propa.dla + propa.tha \/ prop.gme;\n\t\tq = (1.0 - 0.8*exp(-propa.dlsa \/ 50e3))*prop.dh;\n\t\tq *= 0.78*exp(-pow(q \/ 16.0, 0.25));\n\t\tafo = mymin(15.0, 2.171*log(1.0 + 4.77e-4*prop.hg[0] * prop.hg[1] *\n\t\t\tprop.wn*q));\n\t\tqk = 1.0 \/ abs(prop_zgnd);\n\t\taht = 20.0;\n\t\txht = 0.0;\n\t\tfor (int j = 0; j<2; ++j)\n\t\t{\n\t\t\ta = 0.5*pow(prop.dl[j], 2.0) \/ prop.he[j];\n\t\t\twa = pow(a*prop.wn, THIRD);\n\t\t\tpk = qk \/ wa;\n\t\t\tq = (1.607 - pk)*151.0*wa*prop.dl[j] \/ a;\n\t\t\txht += q;\n\t\t\taht += fht(q, pk);\n\t\t}\n\t\tadiffv = 0.0;\n\t}\n\telse\n\t{\n\t\tth = propa.tha + d * prop.gme;\n\t\tds = d - propa.dla;\n\t\tq = 0.0795775*prop.wn*ds*pow(th, 2.0);\n\t\tadiffv = aknfe(q*prop.dl[0] \/ (ds + prop.dl[0])) + aknfe(q*prop.dl[1] \/ (ds + prop.dl[1]));\n\t\ta = ds \/ th;\n\t\twa = pow(a*prop.wn, THIRD);\n\t\tpk = qk \/ wa;\n\t\tq = (1.607 - pk)*151.0*wa*th + xht;\n\t\tar = 0.05751*q - 4.343*log(q) - aht;\n\t\tq = (wd1 + xd1 \/ d)*mymin(((1.0 - 0.8*exp(-d \/ 50e3))*prop.dh*prop.wn), 6283.2);\n\t\twd = 25.1 \/ (25.1 + sqrt(q));\n\t\tadiffv = ar * wd + (1.0 - wd)*adiffv + afo;\n\t}\n\treturn adiffv;\n}\n\ndouble  ascat(double d, prop_type &prop, propa_type &propa)\n{\n\tcomplex<double> prop_zgnd(prop.zgndreal, prop.zgndimag);\n\tstatic double ad, rr, etq, h0s;\n\tdouble h0, r1, r2, z0, ss, et, ett, th, q;\n\tdouble ascatv;\n\tif (d == 0.0)\n\t{\n\t\tad = prop.dl[0] - prop.dl[1];\n\t\trr = prop.he[1] \/ prop.he[0];\n\t\tif (ad<0.0)\n\t\t{\n\t\t\tad = -ad;\n\t\t\trr = 1.0 \/ rr;\n\t\t}\n\t\tetq = (5.67e-6*prop.ens - 2.32e-3)*prop.ens + 0.031;\n\t\th0s = -15.0;\n\t\tascatv = 0.0;\n\t}\n\telse\n\t{\n\t\tif (h0s>15.0)\n\t\t\th0 = h0s;\n\t\telse\n\t\t{\n\t\t\tth = prop.the[0] + prop.the[1] + d * prop.gme;\n\t\t\tr2 = 2.0*prop.wn*th;\n\t\t\tr1 = r2 * prop.he[0];\n\t\t\tr2 *= prop.he[1];\n\t\t\tif (r1<0.2 && r2<0.2)\n\t\t\t\treturn 1001.0;  \/\/ <==== early return\n\t\t\tss = (d - ad) \/ (d + ad);\n\t\t\tq = rr \/ ss;\n\t\t\tss = mymax(0.1, ss);\n\t\t\tq = mymin(mymax(0.1, q), 10.0);\n\t\t\tz0 = (d - ad)*(d + ad)*th*0.25 \/ d;\n\t\t\tet = (etq*exp(-pow(mymin(1.7, z0 \/ 8.0e3), 6.0)) + 1.0)*z0 \/ 1.7556e3;\n\t\t\tett = mymax(et, 1.0);\n\t\t\th0 = (h0f(r1, ett) + h0f(r2, ett))*0.5;\n\t\t\th0 += mymin(h0, (1.38 - log(ett))*log(ss)*log(q)*0.49);\n\t\t\th0 = FORTRAN_DIM(h0, 0.0);\n\t\t\tif (et<1.0)\n\t\t\t\th0 = et * h0 + (1.0 - et)*4.343*log(pow((1.0 + 1.4142 \/ r1) *\n\t\t\t\t(1.0 + 1.4142 \/ r2), 2.0)*(r1 + r2) \/ (r1 + r2 + 2.8284));\n\t\t\tif (h0>15.0 && h0s >= 0.0)\n\t\t\t\th0 = h0s;\n\t\t}\n\t\th0s = h0;\n\t\tth = propa.tha + d * prop.gme;\n\t\tascatv = ahd(th*d) + 4.343*log(47.7*prop.wn*pow(th, 4.0)) - 0.1 *\n\t\t\t(prop.ens - 301.0)*exp(-th * d \/ 40e3) + h0;\n\t}\n\treturn ascatv;\n}\n\ndouble DllExport _stdcall qerfi(double q)\n{\n\tdouble x, t, v;\n\tdouble c0 = 2.515516698;\n\tdouble c1 = 0.802853;\n\tdouble c2 = 0.010328;\n\tdouble d1 = 1.432788;\n\tdouble d2 = 0.189269;\n\tdouble d3 = 0.001308;\n\n\tx = 0.5 - q;\n\tt = mymax(0.5 - fabs(x), 0.000001);\n\tt = sqrt(-2.0 * log(t));\n\tv = t - ((c2 * t + c1) * t + c0) \/ (((d3 * t + d2) * t + d1) * t + 1.0);\n\tif (x < 0.0) v = -v;\n\treturn v;\n}\n\nvoid DllExport _stdcall qlrps(double fmhz, double zsys, double en0,\n\tint ipol, double eps, double sgm, prop_type &prop)\n{\n\tdouble gma = 157e-9;\n\tprop.wn = fmhz \/ 47.7;\n\tprop.ens = en0;\n\tif (zsys != 0.0)\n\t\tprop.ens *= exp(-zsys \/ 9460.0);\n\tprop.gme = gma * (1.0 - 0.04665*exp(prop.ens \/ 179.3));\n\tcomplex<double> zq, prop_zgnd(prop.zgndreal, prop.zgndimag);\n\tzq = complex<double>(eps, 376.62*sgm \/ prop.wn);\n\tprop_zgnd = sqrt(zq - 1.0);\n\tif (ipol != 0.0)\n\t\tprop_zgnd = prop_zgnd \/ zq;\n\n\tprop.zgndreal = prop_zgnd.real();  prop.zgndimag = prop_zgnd.imag();\n}\n\ndouble abq_alos(complex<double> r)\n{\n\treturn r.real()*r.real() + r.imag()*r.imag();\n}\n\ndouble  alos(double d, prop_type &prop, propa_type &propa)\n{\n\tcomplex<double> prop_zgnd(prop.zgndreal, prop.zgndimag);\n\tstatic double wls;\n\tcomplex<double> r;\n\tdouble s, sps, q;\n\tdouble alosv;\n\tif (d == 0.0)\n\t{\n\t\twls = 0.021 \/ (0.021 + prop.wn*prop.dh \/ mymax(10e3, propa.dlsa));\n\t\talosv = 0.0;\n\t}\n\telse\n\t{\n\t\tq = (1.0 - 0.8*exp(-d \/ 50e3))*prop.dh;\n\t\ts = 0.78*q*exp(-pow(q \/ 16.0, 0.25));\n\t\tq = prop.he[0] + prop.he[1];\n\t\tsps = q \/ sqrt(d*d + q * q);\n\t\tr = (sps - prop_zgnd) \/ (sps + prop_zgnd)*exp(-mymin(10.0, prop.wn*s*sps));\n\t\tq = abq_alos(r);\n\t\tif (q<0.25 || q<sps)\n\t\t\tr = r * sqrt(sps \/ q);\n\t\talosv = propa.emd*d + propa.aed;\n\t\tq = prop.wn*prop.he[0] * prop.he[1] * 2.0 \/ d;\n\t\tif (q>1.57)\n\t\t\tq = 3.14 - 2.4649 \/ q;\n\t\talosv = (-4.343*log(abq_alos(complex<double>(cos(q), -sin(q)) + r)) - alosv) *\n\t\t\twls + alosv;\n\t}\n\treturn alosv;\n}\n\n\nvoid DllExport _stdcall qlra(int kst[], int klimx, int mdvarx,\n\tprop_type &prop, propv_type &propv)\n{\n\tcomplex<double> prop_zgnd(prop.zgndreal, prop.zgndimag);\n\tdouble q;\n\tfor (int j = 0; j<2; ++j)\n\t{\n\t\tif (kst[j] <= 0)\n\t\t\tprop.he[j] = prop.hg[j];\n\t\telse\n\t\t{\n\t\t\tq = 4.0;\n\t\t\tif (kst[j] != 1)\n\t\t\t\tq = 9.0;\n\t\t\tif (prop.hg[j]<5.0)\n\t\t\t\tq *= sin(0.3141593*prop.hg[j]);\n\t\t\tprop.he[j] = prop.hg[j] + (1.0 + q)*exp(-mymin(20.0, 2.0*prop.hg[j] \/ mymax(1e-3, prop.dh)));\n\t\t}\n\t\tq = sqrt(2.0*prop.he[j] \/ prop.gme);\n\t\tprop.dl[j] = q * exp(-0.07*sqrt(prop.dh \/ mymax(prop.he[j], 5.0)));\n\t\tprop.the[j] = (0.65*prop.dh*(q \/ prop.dl[j] - 1.0) - 2.0*prop.he[j]) \/ q;\n\t}\n\tprop.mdp = 1;\n\tpropv.lvar = mymax(propv.lvar, 3);\n\tif (mdvarx >= 0)\n\t{\n\t\tpropv.mdvar = mdvarx;\n\t\tpropv.lvar = mymax(propv.lvar, 4);\n\t}\n\tif (klimx>0)\n\t{\n\t\tpropv.klim = klimx;\n\t\tpropv.lvar = 5;\n\t}\n}\n\nvoid DllExport _stdcall lrprop(double d,\n\tprop_type &prop, propa_type &propa)  \/\/ PaulM_lrprop\n{\n\tstatic bool wlos, wscat;\n\tstatic double dmin, xae;\n\tcomplex<double> prop_zgnd(prop.zgndreal, prop.zgndimag);\n\tdouble a0, a1, a2, a3, a4, a5, a6;\n\tdouble d0, d1, d2, d3, d4, d5, d6;\n\tbool wq;\n\tdouble q;\n\tint j;\n\n\tif (prop.mdp != 0)\n\t{\n\t\tfor (j = 0; j<2; j++)\n\t\t\tpropa.dls[j] = sqrt(2.0*prop.he[j] \/ prop.gme);\n\t\tpropa.dlsa = propa.dls[0] + propa.dls[1];\n\t\tpropa.dla = prop.dl[0] + prop.dl[1];\n\t\tpropa.tha = mymax(prop.the[0] + prop.the[1], -propa.dla*prop.gme);\n\t\twlos = false;\n\t\twscat = false;\n\t\tif (prop.wn<0.838 || prop.wn>210.0)\n\t\t{\n\t\t\tprop.kwx = mymax(prop.kwx, 1);\n\t\t}\n\t\tfor (j = 0; j<2; j++)\n\t\t\tif (prop.hg[j]<1.0 || prop.hg[j]>1000.0)\n\t\t\t{\n\t\t\t\tprop.kwx = mymax(prop.kwx, 1);\n\t\t\t}\n\t\tfor (j = 0; j<2; j++)\n\t\t\tif (abs(prop.the[j]) >200e-3 || prop.dl[j]<0.1*propa.dls[j] ||\n\t\t\t\tprop.dl[j]>3.0*propa.dls[j])\n\t\t\t{\n\t\t\t\tprop.kwx = mymax(prop.kwx, 3);\n\t\t\t}\n\t\tif (prop.ens < 250.0 || prop.ens > 400.0 ||\n\t\t\tprop.gme < 75e-9 || prop.gme > 250e-9 ||\n\t\t\tprop_zgnd.real() <= abs(prop_zgnd.imag()) ||\n\t\t\tprop.wn  < 0.419 || prop.wn  > 420.0)\n\t\t{\n\t\t\tprop.kwx = 4;\n\t\t}\n\t\tfor (j = 0; j<2; j++)\n\t\t\tif (prop.hg[j]<0.5 || prop.hg[j]>3000.0)\n\t\t\t{\n\t\t\t\tprop.kwx = 4;\n\t\t\t}\n\t\tdmin = abs(prop.he[0] - prop.he[1]) \/ 200e-3;\n\t\tq = adiff(0.0, prop, propa);\n\t\txae = pow(prop.wn*pow(prop.gme, 2), -THIRD);\n\t\td3 = mymax(propa.dlsa, 1.3787*xae + propa.dla);\n\t\td4 = d3 + 2.7574*xae;\n\t\ta3 = adiff(d3, prop, propa);\n\t\ta4 = adiff(d4, prop, propa);\n\t\tpropa.emd = (a4 - a3) \/ (d4 - d3);\n\t\tpropa.aed = a3 - propa.emd*d3;\n\t}\n\tif (prop.mdp >= 0)\n\t{\n\t\tprop.mdp = 0;\n\t\tprop.dist = d;\n\t}\n\tif (prop.dist>0.0)\n\t{\n\t\tif (prop.dist>1000e3)\n\t\t{\n\t\t\tprop.kwx = mymax(prop.kwx, 1);\n\t\t}\n\t\tif (prop.dist<dmin)\n\t\t{\n\t\t\tprop.kwx = mymax(prop.kwx, 3);\n\t\t}\n\t\tif (prop.dist<1e3 || prop.dist>2000e3)\n\t\t{\n\t\t\tprop.kwx = 4;\n\t\t}\n\t}\n\tif (prop.dist<propa.dlsa)\n\t{\n\t\tif (!wlos)\n\t\t{\n\t\t\tq = alos(0.0, prop, propa);\n\t\t\td2 = propa.dlsa;\n\t\t\ta2 = propa.aed + d2 * propa.emd;\n\t\t\td0 = 1.908*prop.wn*prop.he[0] * prop.he[1];\n\t\t\tif (propa.aed >= 0.0)\n\t\t\t{\n\t\t\t\td0 = mymin(d0, 0.5*propa.dla);\n\t\t\t\td1 = d0 + 0.25*(propa.dla - d0);\n\t\t\t}\n\t\t\telse\n\t\t\t\td1 = mymax(-propa.aed \/ propa.emd, 0.25*propa.dla);\n\t\t\ta1 = alos(d1, prop, propa);\n\t\t\twq = false;\n\t\t\tif (d0<d1)\n\t\t\t{\n\t\t\t\ta0 = alos(d0, prop, propa);\n\t\t\t\tq = log(d2 \/ d0);\n\t\t\t\tpropa.ak2 = mymax(0.0, ((d2 - d0)*(a1 - a0) - (d1 - d0)*(a2 - a0)) \/\n\t\t\t\t\t((d2 - d0)*log(d1 \/ d0) - (d1 - d0)*q));\n\t\t\t\twq = propa.aed >= 0.0 || propa.ak2>0.0;\n\t\t\t\tif (wq)\n\t\t\t\t{\n\t\t\t\t\tpropa.ak1 = (a2 - a0 - propa.ak2*q) \/ (d2 - d0);\n\t\t\t\t\tif (propa.ak1<0.0)\n\t\t\t\t\t{\n\t\t\t\t\t\tpropa.ak1 = 0.0;\n\t\t\t\t\t\tpropa.ak2 = FORTRAN_DIM(a2, a0) \/ q;\n\t\t\t\t\t\tif (propa.ak2 == 0.0) propa.ak1 = propa.emd;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!wq)\n\t\t\t{\n\t\t\t\tpropa.ak1 = FORTRAN_DIM(a2, a1) \/ (d2 - d1);\n\t\t\t\tpropa.ak2 = 0.0;\n\t\t\t\tif (propa.ak1 == 0.0)\tpropa.ak1 = propa.emd;\n\t\t\t}\n\t\t\tpropa.ael = a2 - propa.ak1*d2 - propa.ak2*log(d2);\n\t\t\twlos = true;\n\t\t}\n\t\tif (prop.dist>0.0)\n\t\t\tprop.aref = propa.ael + propa.ak1*prop.dist +\n\t\t\tpropa.ak2*log(prop.dist);\n\t}\n\tif (prop.dist <= 0.0 || prop.dist >= propa.dlsa)\n\t{\n\t\tif (!wscat)\n\t\t{\n\t\t\tq = ascat(0.0, prop, propa);\n\t\t\td5 = propa.dla + 200e3;\n\t\t\td6 = d5 + 200e3;\n\t\t\ta6 = ascat(d6, prop, propa);\n\t\t\ta5 = ascat(d5, prop, propa);\n\t\t\tif (a5<1000.0)\n\t\t\t{\n\t\t\t\tpropa.ems = (a6 - a5) \/ 200e3;\n\t\t\t\tpropa.dx = mymax(propa.dlsa, mymax(propa.dla + 0.3*xae *\n\t\t\t\t\tlog(47.7*prop.wn), (a5 - propa.aed - propa.ems*d5) \/\n\t\t\t\t\t(propa.emd - propa.ems)));\n\t\t\t\tpropa.aes = (propa.emd - propa.ems)*propa.dx + propa.aed;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpropa.ems = propa.emd;\n\t\t\t\tpropa.aes = propa.aed;\n\t\t\t\tpropa.dx = 10.e6;\n\t\t\t}\n\t\t\twscat = true;\n\t\t}\n\t\tif (prop.dist>propa.dx)\n\t\t\tprop.aref = propa.aes + propa.ems*prop.dist;\n\t\telse\n\t\t\tprop.aref = propa.aed + propa.emd*prop.dist;\n\t}\n\tprop.aref = mymax(prop.aref, 0.0);\n}\n\ndouble curve(double const &c1, double const &c2, double const &x1,\n\tdouble const &x2, double const &x3, double const &de)\n{\n\treturn (c1 + c2 \/ (1.0 + pow((de - x2) \/ x3, 2.0)))*pow(de \/ x1, 2.0) \/\n\t\t(1.0 + pow(de \/ x1, 2.0));\n}\n\ndouble DllExport _stdcall avar(double zzt, double zzl, double zzc,\n\tprop_type &prop, propv_type &propv)\n{\n\tstatic int kdv;\n\tstatic double dexa, de, vmd, vs0, sgl, sgtm, sgtp, sgtd, tgtd,\n\t\tgm, gp, cv1, cv2, yv1, yv2, yv3, csm1, csm2, ysm1, ysm2,\n\t\tysm3, csp1, csp2, ysp1, ysp2, ysp3, csd1, zd, cfm1, cfm2,\n\t\tcfm3, cfp1, cfp2, cfp3;\n\tdouble bv1[7] = { -9.67,-0.62,1.26,-9.21,-0.62,-0.39,3.15 };\n\tdouble bv2[7] = { 12.7,9.19,15.5,9.05,9.19,2.86,857.9 };\n\tdouble xv1[7] = { 144.9e3,228.9e3,262.6e3,84.1e3,228.9e3,141.7e3,2222.e3 };\n\tdouble xv2[7] = { 190.3e3,205.2e3,185.2e3,101.1e3,205.2e3,315.9e3,164.8e3 };\n\tdouble xv3[7] = { 133.8e3,143.6e3,99.8e3,98.6e3,143.6e3,167.4e3,116.3e3 };\n\tdouble bsm1[7] = { 2.13,2.66,6.11,1.98,2.68,6.86,8.51 };\n\tdouble bsm2[7] = { 159.5,7.67,6.65,13.11,7.16,10.38,169.8 };\n\tdouble xsm1[7] = { 762.2e3,100.4e3,138.2e3,139.1e3,93.7e3,187.8e3,609.8e3 };\n\tdouble xsm2[7] = { 123.6e3,172.5e3,242.2e3,132.7e3,186.8e3,169.6e3,119.9e3 };\n\tdouble xsm3[7] = { 94.5e3,136.4e3,178.6e3,193.5e3,133.5e3,108.9e3,106.6e3 };\n\tdouble bsp1[7] = { 2.11,6.87,10.08,3.68,4.75,8.58,8.43 };\n\tdouble bsp2[7] = { 102.3,15.53,9.60,159.3,8.12,13.97,8.19 };\n\tdouble xsp1[7] = { 636.9e3,138.7e3,165.3e3,464.4e3,93.2e3,216.0e3,136.2e3 };\n\tdouble xsp2[7] = { 134.8e3,143.7e3,225.7e3,93.1e3,135.9e3,152.0e3,188.5e3 };\n\tdouble xsp3[7] = { 95.6e3,98.6e3,129.7e3,94.2e3,113.4e3,122.7e3,122.9e3 };\n\tdouble bsd1[7] = { 1.224,0.801,1.380,1.000,1.224,1.518,1.518 };\n\tdouble bzd1[7] = { 1.282,2.161,1.282,20.,1.282,1.282,1.282 };\n\tdouble bfm1[7] = { 1.0,1.0,1.0,1.0,0.92,1.0,1.0 };\n\tdouble bfm2[7] = { 0.0,0.0,0.0,0.0,0.25,0.0,0.0 };\n\tdouble bfm3[7] = { 0.0,0.0,0.0,0.0,1.77,0.0,0.0 };\n\tdouble bfp1[7] = { 1.0,0.93,1.0,0.93,0.93,1.0,1.0 };\n\tdouble bfp2[7] = { 0.0,0.31,0.0,0.19,0.31,0.0,0.0 };\n\tdouble bfp3[7] = { 0.0,2.00,0.0,1.79,2.00,0.0,0.0 };\n\tstatic bool ws, w1;\n\tdouble rt = 7.8, rl = 24.0, avarv, q, vs, zt, zl, zc;\n\tdouble sgt, yr;\n\tint temp_klim = propv.klim - 1;\n\n\tif (propv.lvar>0)\n\t{\n\t\tswitch (propv.lvar)\n\t\t{\n\t\tdefault:\n\t\t\tif (propv.klim <= 0 || propv.klim>7)\n\t\t\t{\n\t\t\t\tpropv.klim = 5;\n\t\t\t\ttemp_klim = 4;\n\t\t\t\t{ prop.kwx = mymax(prop.kwx, 2);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcv1 = bv1[temp_klim];\n\t\t\tcv2 = bv2[temp_klim];\n\t\t\tyv1 = xv1[temp_klim];\n\t\t\tyv2 = xv2[temp_klim];\n\t\t\tyv3 = xv3[temp_klim];\n\t\t\tcsm1 = bsm1[temp_klim];\n\t\t\tcsm2 = bsm2[temp_klim];\n\t\t\tysm1 = xsm1[temp_klim];\n\t\t\tysm2 = xsm2[temp_klim];\n\t\t\tysm3 = xsm3[temp_klim];\n\t\t\tcsp1 = bsp1[temp_klim];\n\t\t\tcsp2 = bsp2[temp_klim];\n\t\t\tysp1 = xsp1[temp_klim];\n\t\t\tysp2 = xsp2[temp_klim];\n\t\t\tysp3 = xsp3[temp_klim];\n\t\t\tcsd1 = bsd1[temp_klim];\n\t\t\tzd = bzd1[temp_klim];\n\t\t\tcfm1 = bfm1[temp_klim];\n\t\t\tcfm2 = bfm2[temp_klim];\n\t\t\tcfm3 = bfm3[temp_klim];\n\t\t\tcfp1 = bfp1[temp_klim];\n\t\t\tcfp2 = bfp2[temp_klim];\n\t\t\tcfp3 = bfp3[temp_klim];\n\t\tcase 4:\n\t\t\tkdv = propv.mdvar;\n\t\t\tws = kdv >= 20;\n\t\t\tif (ws)\n\t\t\t\tkdv -= 20;\n\t\t\tw1 = kdv >= 10;\n\t\t\tif (w1)\n\t\t\t\tkdv -= 10;\n\t\t\tif (kdv<0 || kdv>3)\n\t\t\t{\n\t\t\t\tkdv = 0;\n\t\t\t\tprop.kwx = mymax(prop.kwx, 2);\n\t\t\t}\n\t\tcase 3:\n\t\t\tq = log(0.133*prop.wn);\n\t\t\tgm = cfm1 + cfm2 \/ (pow(cfm3*q, 2.0) + 1.0);\n\t\t\tgp = cfp1 + cfp2 \/ (pow(cfp3*q, 2.0) + 1.0);\n\t\tcase 2:\n\t\t\tdexa = sqrt(18e6*prop.he[0]) + sqrt(18e6*prop.he[1]) +\n\t\t\t\tpow((575.7e12 \/ prop.wn), THIRD);\n\t\tcase 1:\n\t\t\tif (prop.dist<dexa)\n\t\t\t\tde = 130e3*prop.dist \/ dexa;\n\t\t\telse\n\t\t\t\tde = 130e3 + prop.dist - dexa;\n\t\t}\n\t\tvmd = curve(cv1, cv2, yv1, yv2, yv3, de);\n\t\tsgtm = curve(csm1, csm2, ysm1, ysm2, ysm3, de) * gm;\n\t\tsgtp = curve(csp1, csp2, ysp1, ysp2, ysp3, de) * gp;\n\t\tsgtd = sgtp * csd1;\n\t\ttgtd = (sgtp - sgtd)*zd;\n\t\tif (w1)\n\t\t\tsgl = 0.0;\n\t\telse\n\t\t{\n\t\t\tq = (1.0 - 0.8*exp(-prop.dist \/ 50e3))*prop.dh*prop.wn;\n\t\t\tsgl = 10.0*q \/ (q + 13.0);\n\t\t}\n\t\tif (ws)\n\t\t\tvs0 = 0.0;\n\t\telse\n\t\t\tvs0 = pow(5.0 + 3.0*exp(-de \/ 100e3), 2.0);\n\t\tpropv.lvar = 0;\n\t}\n\tzt = zzt;\n\tzl = zzl;\n\tzc = zzc;\n\tswitch (kdv)\n\t{\n\tcase 0:\n\t\tzt = zc;\n\t\tzl = zc;\n\t\tbreak;\n\tcase 1:\n\t\tzl = zc;\n\t\tbreak;\n\tcase 2:\n\t\tzl = zt;\n\t}\n\tif (fabs(zt)>3.1 || fabs(zl)>3.1 || fabs(zc)>3.1)\n\t{\n\t\tprop.kwx = mymax(prop.kwx, 1);\n\t}\n\tif (zt<0.0)\n\t\tsgt = sgtm;\n\telse if (zt <= zd)\n\t\tsgt = sgtp;\n\telse\n\t\tsgt = sgtd + tgtd \/ zt;\n\tvs = vs0 + pow(sgt*zt, 2.0) \/ (rt + zc * zc) + pow(sgl*zl, 2.0) \/ (rl + zc * zc);\n\tif (kdv == 0)\n\t{\n\t\tyr = 0.0;\n\t\tpropv.sgc = sqrt(sgt*sgt + sgl * sgl + vs);\n\t}\n\telse if (kdv == 1)\n\t{\n\t\tyr = sgt * zt;\n\t\tpropv.sgc = sqrt(sgl*sgl + vs);\n\t}\n\telse if (kdv == 2)\n\t{\n\t\tyr = sqrt(sgt*sgt + sgl * sgl)*zt;\n\t\tpropv.sgc = sqrt(vs);\n\t}\n\telse\n\t{\n\t\tyr = sgt * zt + sgl * zl;\n\t\tpropv.sgc = sqrt(vs);\n\t}\n\tavarv = prop.aref - vmd - yr - propv.sgc*zc;\n\tif (avarv<0.0)\n\t\tavarv = avarv * (29.0 - avarv) \/ (29.0 - 10.0*avarv);\n\treturn avarv;\n\n}\n\nvoid hzns(double pfl[], prop_type &prop)\n{\n\tbool wq;\n\tint np;\n\tdouble xi, za, zb, qc, q, sb, sa;\n\n\tnp = (int)pfl[0];\n\txi = pfl[1];\n\tza = pfl[2] + prop.hg[0];\n\tzb = pfl[np + 2] + prop.hg[1];\n\tqc = 0.5*prop.gme;\n\tq = qc * prop.dist;\n\tprop.the[1] = (zb - za) \/ prop.dist;\n\tprop.the[0] = prop.the[1] - q;\n\tprop.the[1] = -prop.the[1] - q;\n\tprop.dl[0] = prop.dist;\n\tprop.dl[1] = prop.dist;\n\tif (np >= 2)\n\t{\n\t\tsa = 0.0;\n\t\tsb = prop.dist;\n\t\twq = true;\n\t\tfor (int i = 1; i<np; i++)\n\t\t{\n\t\t\tsa += xi;\n\t\t\tsb -= xi;\n\t\t\tq = pfl[i + 2] - (qc*sa + prop.the[0])*sa - za;\n\t\t\tif (q>0.0)\n\t\t\t{\n\t\t\t\tprop.the[0] += q \/ sa;\n\t\t\t\tprop.dl[0] = sa;\n\t\t\t\twq = false;\n\t\t\t}\n\t\t\tif (!wq)\n\t\t\t{\n\t\t\t\tq = pfl[i + 2] - (qc*sb + prop.the[1])*sb - zb;\n\t\t\t\tif (q>0.0)\n\t\t\t\t{\n\t\t\t\t\tprop.the[1] += q \/ sb;\n\t\t\t\t\tprop.dl[1] = sb;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid z1sq1(double z[], const double &x1, const double &x2,\n\tdouble& z0, double& zn)\n{\n\tdouble xn, xa, xb, x, a, b;\n\tint n, ja, jb;\n\txn = z[0];\n\txa = int(FORTRAN_DIM(x1 \/ z[1], 0.0));\n\txb = xn - int(FORTRAN_DIM(xn, x2 \/ z[1]));\n\tif (xb <= xa)\n\t{\n\t\txa = FORTRAN_DIM(xa, 1.0);\n\t\txb = xn - FORTRAN_DIM(xn, xb + 1.0);\n\t}\n\tja = (int)xa;\n\tjb = (int)xb;\n\tn = jb - ja;\n\txa = xb - xa;\n\tx = -0.5*xa;\n\txb += x;\n\ta = 0.5*(z[ja + 2] + z[jb + 2]);\n\tb = 0.5*(z[ja + 2] - z[jb + 2])*x;\n\tfor (int i = 2; i <= n; ++i)\n\t{\n\t\t++ja;\n\t\tx += 1.0;\n\t\ta += z[ja + 2];\n\t\tb += z[ja + 2] * x;\n\t}\n\ta \/= xa;\n\tb = b * 12.0 \/ ((xa*xa + 2.0)*xa);\n\tz0 = a - b * xb;\n\tzn = a + b * (xn - xb);\n}\n\ndouble qtile(const int &nn, double a[], const int &ir)\n{\n\tdouble q, r;\n\tint m, n, i, j, j1, i0, k;\n\tbool done = false;\n\tbool goto10 = true;\n\n\tm = 0;\n\tn = nn;\n\tk = mymin(mymax(0, ir), n);\n\twhile (!done)\n\t{\n\t\tif (goto10)\n\t\t{\n\t\t\tq = a[k];\n\t\t\ti0 = m;\n\t\t\tj1 = n;\n\t\t}\n\t\ti = i0;\n\t\twhile (i <= n && a[i] >= q)\n\t\t\ti++;\n\t\tif (i>n)\n\t\t\ti = n;\n\t\tj = j1;\n\t\twhile (j >= m && a[j] <= q)\n\t\t\tj--;\n\t\tif (j<m)\n\t\t\tj = m;\n\t\tif (i<j)\n\t\t{\n\t\t\tr = a[i]; a[i] = a[j]; a[j] = r;\n\t\t\ti0 = i + 1;\n\t\t\tj1 = j - 1;\n\t\t\tgoto10 = false;\n\t\t}\n\t\telse if (i<k)\n\t\t{\n\t\t\ta[k] = a[i];\n\t\t\ta[i] = q;\n\t\t\tm = i + 1;\n\t\t\tgoto10 = true;\n\t\t}\n\t\telse if (j>k)\n\t\t{\n\t\t\ta[k] = a[j];\n\t\t\ta[j] = q;\n\t\t\tn = j - 1;\n\t\t\tgoto10 = true;\n\t\t}\n\t\telse\n\t\t\tdone = true;\n\t}\n\treturn q;\n}\n\ndouble qerf(const double &z)\n{\n\tdouble b1 = 0.319381530, b2 = -0.356563782, b3 = 1.781477937;\n\tdouble b4 = -1.821255987, b5 = 1.330274429;\n\tdouble rp = 4.317008, rrt2pi = 0.398942280;\n\tdouble t, x, qerfv;\n\tx = z;\n\tt = fabs(x);\n\tif (t >= 10.0)\n\t\tqerfv = 0.0;\n\telse\n\t{\n\t\tt = rp \/ (t + rp);\n\t\tqerfv = exp(-0.5*x*x)*rrt2pi*((((b5*t + b4)*t + b3)*t + b2)*t + b1)*t;\n\t}\n\tif (x<0.0) qerfv = 1.0 - qerfv;\n\treturn qerfv;\n}\n\ndouble d1thx(double pfl[], const double &x1, const double &x2)\n{\n\tint np, ka, kb, n, k, j;\n\tdouble d1thxv, sn, xa, xb;\n\tdouble *s;\n\n\tnp = (int)pfl[0];\n\txa = x1 \/ pfl[1];\n\txb = x2 \/ pfl[1];\n\td1thxv = 0.0;\n\tif (xb - xa<2.0)  \/\/ exit out\n\t\treturn d1thxv;\n\tka = (int)(0.1*(xb - xa + 8.0));\n\tka = mymin(mymax(4, ka), 25);\n\tn = 10 * ka - 5;\n\tkb = n - ka + 1;\n\tsn = n - 1;\n\tassert((s = new double[n + 2]) != 0);\n\ts[0] = sn;\n\ts[1] = 1.0;\n\txb = (xb - xa) \/ sn;\n\tk = (int)(xa + 1.0);\n\txa -= (double)k;\n\tfor (j = 0; j<n; j++)\n\t{\n\t\twhile (xa>0.0 && k<np)\n\t\t{\n\t\t\txa -= 1.0;\n\t\t\t++k;\n\t\t}\n\t\ts[j + 2] = pfl[k + 2] + (pfl[k + 2] - pfl[k + 1])*xa;\n\t\txa = xa + xb;\n\t}\n\tz1sq1(s, 0.0, sn, xa, xb);\n\txb = (xb - xa) \/ sn;\n\tfor (j = 0; j<n; j++)\n\t{\n\t\ts[j + 2] -= xa;\n\t\txa = xa + xb;\n\t}\n\td1thxv = qtile(n - 1, s + 2, ka - 1) - qtile(n - 1, s + 2, kb - 1);\n\td1thxv \/= 1.0 - 0.8*exp(-(x2 - x1) \/ 50.0e3);\n\tdelete[] s;\n\treturn d1thxv;\n}\n\nvoid DllExport _stdcall qlrpfl(double pfl[], int klimx, int mdvarx,\n\tprop_type &prop, propa_type &propa, propv_type &propv)\n{\n\tint np, j;\n\tdouble xl[2], q, za, zb;\n\n\tprop.dist = pfl[0] * pfl[1];\n\tnp = (int)pfl[0];\n\thzns(pfl, prop);\n\tfor (j = 0; j<2; j++)\n\t\txl[j] = mymin(15.0*prop.hg[j], 0.1*prop.dl[j]);\n\txl[1] = prop.dist - xl[1];\n\tprop.dh = d1thx(pfl, xl[0], xl[1]);\n\tif (prop.dl[0] + prop.dl[1]>1.5*prop.dist)\n\t{\n\t\tz1sq1(pfl, xl[0], xl[1], za, zb);\n\t\tprop.he[0] = prop.hg[0] + FORTRAN_DIM(pfl[2], za);\n\t\tprop.he[1] = prop.hg[1] + FORTRAN_DIM(pfl[np + 2], zb);\n\t\tfor (j = 0; j<2; j++)\n\t\t\tprop.dl[j] = sqrt(2.0*prop.he[j] \/ prop.gme) *\n\t\t\texp(-0.07*sqrt(prop.dh \/ mymax(prop.he[j], 5.0)));\n\t\tq = prop.dl[0] + prop.dl[1];\n\n\t\tif (q <= prop.dist)\n\t\t{\n\t\t\tq = pow(prop.dist \/ q, 2.0);\n\t\t\tfor (j = 0; j<2; j++)\n\t\t\t{\n\t\t\t\tprop.he[j] *= q;\n\t\t\t\tprop.dl[j] = sqrt(2.0*prop.he[j] \/ prop.gme) *\n\t\t\t\t\texp(-0.07*sqrt(prop.dh \/ mymax(prop.he[j], 5.0)));\n\t\t\t}\n\t\t}\n\t\tfor (j = 0; j<2; j++)\n\t\t{\n\t\t\tq = sqrt(2.0*prop.he[j] \/ prop.gme);\n\t\t\tprop.the[j] = (0.65*prop.dh*(q \/ prop.dl[j] - 1.0) - 2.0 *\n\t\t\t\tprop.he[j]) \/ q;\n\t\t}\n\t}\n\telse\n\t{\n\t\tz1sq1(pfl, xl[0], 0.9*prop.dl[0], za, q);\n\t\tz1sq1(pfl, prop.dist - 0.9*prop.dl[1], xl[1], q, zb);\n\t\tprop.he[0] = prop.hg[0] + FORTRAN_DIM(pfl[2], za);\n\t\tprop.he[1] = prop.hg[1] + FORTRAN_DIM(pfl[np + 2], zb);\n\t}\n\tprop.mdp = -1;\n\tpropv.lvar = mymax(propv.lvar, 3);\n\tif (mdvarx >= 0)\n\t{\n\t\tpropv.mdvar = mdvarx;\n\t\tpropv.lvar = mymax(propv.lvar, 4);\n\t}\n\tif (klimx>0)\n\t{\n\t\tpropv.klim = klimx;\n\t\tpropv.lvar = 5;\n\t}\n\tlrprop(0.0, prop, propa);\n}\n\ndouble deg2rad(double d)\n{\n\treturn d * 3.1415926535897 \/ 180.0;\n}\n\n\/\/********************************************************\n\/\/* Point-To-Point Mode Calculations                     *\n\/\/********************************************************\n\nvoid DllExport _stdcall point_to_point(double elev[], double tht_m, double rht_m,\n\tdouble eps_dielect, double sgm_conductivity, double eno_ns_surfref,\n\tdouble frq_mhz, int radio_climate, int pol, double conf, double rel,\n\tdouble &dbloss, char *strmode, int &errnum)\n\t\/\/ pol: 0-Horizontal, 1-Vertical\n\t\/\/ radio_climate: 1-Equatorial, 2-Continental Subtropical, 3-Maritime Tropical,\n\t\/\/                4-Desert, 5-Continental Temperate, 6-Maritime Temperate, Over Land,\n\t\/\/                7-Maritime Temperate, Over Sea\n\t\/\/ conf, rel: .01 to .99\n\t\/\/ elev[]: [num points - 1], [delta dist(meters)], [height(meters) point 1], ..., [height(meters) point n]\n\t\/\/ errnum: 0- No Error.\n\t\/\/         1- Warning: Some parameters are nearly out of range.\n\t\/\/                     Results should be used with caution.\n\t\/\/         2- Note: Default parameters have been substituted for impossible ones.\n\t\/\/         3- Warning: A combination of parameters is out of range.\n\t\/\/                     Results are probably invalid.\n\t\/\/         Other-  Warning: Some parameters are out of range.\n\t\/\/                          Results are probably invalid.\n{\n\n\tprop_type   prop;\n\tpropv_type  propv;\n\tpropa_type  propa;\n\tdouble zsys = 0;\n\tdouble zc, zr;\n\tdouble eno, enso, q;\n\tlong ja, jb, i, np;\n\tdouble dkm, xkm;\n\tdouble fs;\n\n\tprop.hg[0] = tht_m;   prop.hg[1] = rht_m;\n\tpropv.klim = radio_climate;\n\tprop.kwx = 0;\n\tpropv.lvar = 5;\n\tprop.mdp = -1;\n\tzc = qerfi(conf);\n\tzr = qerfi(rel);\n\tnp = (long)elev[0];\n\tdkm = (elev[1] * elev[0]) \/ 1000.0;\n\txkm = elev[1] \/ 1000.0;\n\teno = eno_ns_surfref;\n\tenso = 0.0;\n\tq = enso;\n\tif (q <= 0.0)\n\t{\n\t\tja = 3.0 + 0.1 * elev[0];\n\t\tjb = np - ja + 6;\n\t\tfor (i = ja - 1; i<jb; ++i)\n\t\t\tzsys += elev[i];\n\t\tzsys \/= (jb - ja + 1);\n\t\tq = eno;\n\t}\n\tpropv.mdvar = 12;\n\tqlrps(frq_mhz, zsys, q, pol, eps_dielect, sgm_conductivity, prop);\n\tqlrpfl(elev, propv.klim, propv.mdvar, prop, propa, propv);\n\tfs = 32.45 + 20.0 * log10(frq_mhz) + 20.0 * log10(prop.dist \/ 1000.0);\n\tq = prop.dist - propa.dla;\n\tif (int(q)<0.0)\n\t\tstrcpy(strmode, \"Line-Of-Sight Mode\");\n\telse\n\t{\n\t\tif (int(q) == 0.0)\n\t\t\tstrcpy(strmode, \"Single Horizon\");\n\t\telse if (int(q)>0.0)\n\t\t\tstrcpy(strmode, \"Double Horizon\");\n\t\tif (prop.dist <= propa.dlsa || prop.dist <= propa.dx)\n\t\t\tstrcat(strmode, \", Diffraction Dominant\");\n\t\telse if (prop.dist>propa.dx)\n\t\t\tstrcat(strmode, \", Troposcatter Dominant\");\n\t}\n\tdbloss = avar(zr, 0.0, zc, prop, propv) + fs;\n\terrnum = prop.kwx;\n}\n\n\nextern \"C\" {\n\tvoid DllExport _stdcall point_to_pointMDH(double elev[], double tht_m, double rht_m,\n\t\tdouble eps_dielect, double sgm_conductivity, double eno_ns_surfref,\n\t\tdouble frq_mhz, int radio_climate, int pol, int mdvar, double timepct, double locpct, double confpct,\n\t\tdouble &dbloss, int &propmode, double &deltaH, int &errnum)\n\t\t\/\/ pol: 0-Horizontal, 1-Vertical\n\t\t\/\/ radio_climate: 1-Equatorial, 2-Continental Subtropical, 3-Maritime Tropical,\n\t\t\/\/                4-Desert, 5-Continental Temperate, 6-Maritime Temperate, Over Land,\n\t\t\/\/                7-Maritime Temperate, Over Sea\n\t\t\/\/ timepct, locpct, confpct: .01 to .99\n\t\t\/\/ elev[]: [num points - 1], [delta dist(meters)], [height(meters) point 1], ..., [height(meters) point n]\n\t\t\/\/ propmode:  Value   Mode\n\t\t\/\/             -1     mode is undefined\n\t\t\/\/              0     Line of Sight\n\t\t\/\/              5     Single Horizon, Diffraction\n\t\t\/\/              6     Single Horizon, Troposcatter\n\t\t\/\/              9     Double Horizon, Diffraction\n\t\t\/\/             10     Double Horizon, Troposcatter\n\t\t\/\/ errnum: 0- No Error.\n\t\t\/\/         1- Warning: Some parameters are nearly out of range.\n\t\t\/\/                     Results should be used with caution.\n\t\t\/\/         2- Note: Default parameters have been substituted for impossible ones.\n\t\t\/\/         3- Warning: A combination of parameters is out of range.\n\t\t\/\/                     Results are probably invalid.\n\t\t\/\/         Other-  Warning: Some parameters are out of range.\n\t\t\/\/                          Results are probably invalid.\n\t{\n\n\t\tprop_type   prop;\n\t\tpropv_type  propv;\n\t\tpropa_type  propa;\n\t\tdouble zsys = 0;\n\t\tdouble ztime, zloc, zconf;\n\t\tdouble eno, enso, q;\n\t\tlong ja, jb, i, np;\n\t\tdouble dkm, xkm;\n\t\tdouble fs;\n\n\t\tpropmode = -1;  \/\/ mode is undefined\n\t\tprop.hg[0] = tht_m;   prop.hg[1] = rht_m;\n\t\tpropv.klim = radio_climate;\n\t\tprop.kwx = 0;\n\t\tpropv.lvar = 5;\n\t\tprop.mdp = -1;\n\t\tztime = qerfi(timepct);\n\t\tzloc = qerfi(locpct);\n\t\tzconf = qerfi(confpct);\n\n\t\tnp = (long)elev[0];\n\t\tdkm = (elev[1] * elev[0]) \/ 1000.0;\n\t\txkm = elev[1] \/ 1000.0;\n\t\teno = eno_ns_surfref;\n\t\tenso = 0.0;\n\t\tq = enso;\n\t\tif (q <= 0.0)\n\t\t{\n\t\t\tja = 3.0 + 0.1 * elev[0];\n\t\t\tjb = np - ja + 6;\n\t\t\tfor (i = ja - 1; i < jb; ++i)\n\t\t\t\tzsys += elev[i];\n\t\t\tzsys \/= (jb - ja + 1);\n\t\t\tq = eno;\n\t\t}\n\t\tpropv.mdvar = 10 + mdvar;\n\t\tqlrps(frq_mhz, zsys, q, pol, eps_dielect, sgm_conductivity, prop);\n\t\tqlrpfl(elev, propv.klim, propv.mdvar, prop, propa, propv);\n\t\tfs = 32.45 + 20.0 * log10(frq_mhz) + 20.0 * log10(prop.dist \/ 1000.0);\n\t\tdeltaH = prop.dh;\n\t\tq = prop.dist - propa.dla;\n\t\tif (int(q) < 0.0)\n\t\t\tpropmode = 0;  \/\/ Line-Of-Sight Mode\n\t\telse\n\t\t{\n\t\t\tif (int(q) == 0.0)\n\t\t\t\tpropmode = 4;  \/\/ Single Horizon\n\t\t\telse if (int(q) > 0.0)\n\t\t\t\tpropmode = 8;  \/\/ Double Horizon\n\t\t\tif (prop.dist <= propa.dlsa || prop.dist <= propa.dx)\n\t\t\t\tpropmode += 1; \/\/ Diffraction Dominant\n\t\t\telse if (prop.dist > propa.dx)\n\t\t\t\tpropmode += 2; \/\/ Troposcatter Dominant\n\t\t}\n\t\tdbloss = avar(ztime, zloc, zconf, prop, propv) + fs;      \/\/avar(time,location,confidence)\n\t\terrnum = prop.kwx;\n\t}\n}\n\nvoid DllExport _stdcall point_to_pointDH(double elev[], double tht_m, double rht_m,\n\tdouble eps_dielect, double sgm_conductivity, double eno_ns_surfref,\n\tdouble frq_mhz, int radio_climate, int pol, double conf, double rel,\n\tdouble &dbloss, double &deltaH, int &errnum)\n\t\/\/ pol: 0-Horizontal, 1-Vertical\n\t\/\/ radio_climate: 1-Equatorial, 2-Continental Subtropical, 3-Maritime Tropical,\n\t\/\/                4-Desert, 5-Continental Temperate, 6-Maritime Temperate, Over Land,\n\t\/\/                7-Maritime Temperate, Over Sea\n\t\/\/ conf, rel: .01 to .99\n\t\/\/ elev[]: [num points - 1], [delta dist(meters)], [height(meters) point 1], ..., [height(meters) point n]\n\t\/\/ errnum: 0- No Error.\n\t\/\/         1- Warning: Some parameters are nearly out of range.\n\t\/\/                     Results should be used with caution.\n\t\/\/         2- Note: Default parameters have been substituted for impossible ones.\n\t\/\/         3- Warning: A combination of parameters is out of range.\n\t\/\/                     Results are probably invalid.\n\t\/\/         Other-  Warning: Some parameters are out of range.\n\t\/\/                          Results are probably invalid.\n{\n\n\tchar strmode[100];\n\tprop_type   prop;\n\tpropv_type  propv;\n\tpropa_type  propa;\n\tdouble zsys = 0;\n\tdouble zc, zr;\n\tdouble eno, enso, q;\n\tlong ja, jb, i, np;\n\tdouble dkm, xkm;\n\tdouble fs;\n\n\tprop.hg[0] = tht_m;   prop.hg[1] = rht_m;\n\tpropv.klim = radio_climate;\n\tprop.kwx = 0;\n\tpropv.lvar = 5;\n\tprop.mdp = -1;\n\tzc = qerfi(conf);\n\tzr = qerfi(rel);\n\tnp = (long)elev[0];\n\tdkm = (elev[1] * elev[0]) \/ 1000.0;\n\txkm = elev[1] \/ 1000.0;\n\teno = eno_ns_surfref;\n\tenso = 0.0;\n\tq = enso;\n\tif (q <= 0.0)\n\t{\n\t\tja = 3.0 + 0.1 * elev[0];\n\t\tjb = np - ja + 6;\n\t\tfor (i = ja - 1; i<jb; ++i)\n\t\t\tzsys += elev[i];\n\t\tzsys \/= (jb - ja + 1);\n\t\tq = eno;\n\t}\n\tpropv.mdvar = 12;\n\tqlrps(frq_mhz, zsys, q, pol, eps_dielect, sgm_conductivity, prop);\n\tqlrpfl(elev, propv.klim, propv.mdvar, prop, propa, propv);\n\tfs = 32.45 + 20.0 * log10(frq_mhz) + 20.0 * log10(prop.dist \/ 1000.0);\n\tdeltaH = prop.dh;\n\tq = prop.dist - propa.dla;\n\tif (int(q)<0.0)\n\t\tstrcpy(strmode, \"Line-Of-Sight Mode\");\n\telse\n\t{\n\t\tif (int(q) == 0.0)\n\t\t\tstrcpy(strmode, \"Single Horizon\");\n\t\telse if (int(q)>0.0)\n\t\t\tstrcpy(strmode, \"Double Horizon\");\n\t\tif (prop.dist <= propa.dlsa || prop.dist <= propa.dx)\n\t\t\tstrcat(strmode, \", Diffraction Dominant\");\n\t\telse if (prop.dist>propa.dx)\n\t\t\tstrcat(strmode, \", Troposcatter Dominant\");\n\t}\n\tdbloss = avar(zr, 0.0, zc, prop, propv) + fs;      \/\/avar(time,location,confidence)\n\terrnum = prop.kwx;\n}\n\n\n\/\/********************************************************\n\/\/* Area Mode Calculations                               *\n\/\/********************************************************\n\nextern \"C\" {\n\tvoid DllExport _stdcall area(long ModVar, double deltaH, double tht_m, double rht_m,\n\t\tdouble dist_km, int TSiteCriteria, int RSiteCriteria,\n\t\tdouble eps_dielect, double sgm_conductivity, double eno_ns_surfref,\n\t\tdouble frq_mhz, int radio_climate, int pol, double pctTime, double pctLoc,\n\t\tdouble pctConf, double &dbloss, char *strmode, int &errnum)\n\t{\n\t\t\/\/ pol: 0-Horizontal, 1-Vertical\n\t\t\/\/ TSiteCriteria, RSiteCriteria:\n\t\t\/\/\t\t   0 - random, 1 - careful, 2 - very careful\n\t\t\/\/ radio_climate: 1-Equatorial, 2-Continental Subtropical, 3-Maritime Tropical,\n\t\t\/\/                4-Desert, 5-Continental Temperate, 6-Maritime Temperate, Over Land,\n\t\t\/\/                7-Maritime Temperate, Over Sea\n\t\t\/\/ ModVar: 0 - Single: pctConf is \"Time\/Situation\/Location\", pctTime, pctLoc not used\n\t\t\/\/         1 - Individual: pctTime is \"Situation\/Location\", pctConf is \"Confidence\", pctLoc not used\n\t\t\/\/         2 - Mobile: pctTime is \"Time\/Locations (Reliability)\", pctConf is \"Confidence\", pctLoc not used\n\t\t\/\/         3 - Broadcast: pctTime is \"Time\", pctLoc is \"Location\", pctConf is \"Confidence\"\n\t\t\/\/ pctTime, pctLoc, pctConf: .01 to .99\n\t\t\/\/ errnum: 0- No Error.\n\t\t\/\/         1- Warning: Some parameters are nearly out of range.\n\t\t\/\/                     Results should be used with caution.\n\t\t\/\/         2- Note: Default parameters have been substituted for impossible ones.\n\t\t\/\/         3- Warning: A combination of parameters is out of range.\n\t\t\/\/                     Results are probably invalid.\n\t\t\/\/         Other-  Warning: Some parameters are out of range.\n\t\t\/\/                          Results are probably invalid.\n\t\t\/\/ NOTE: strmode is not used at this time.\n\t\tprop_type prop;\n\t\tpropv_type propv;\n\t\tpropa_type propa;\n\t\tdouble zt, zl, zc, xlb;\n\t\tdouble fs;\n\t\tlong ivar;\n\t\tdouble eps, eno, sgm;\n\t\tlong ipol;\n\t\tint kst[2];\n\n\t\tkst[0] = (int)TSiteCriteria;\n\t\tkst[1] = (int)RSiteCriteria;\n\t\tzt = qerfi(pctTime);\n\t\tzl = qerfi(pctLoc);\n\t\tzc = qerfi(pctConf);\n\t\teps = eps_dielect;\n\t\tsgm = sgm_conductivity;\n\t\teno = eno_ns_surfref;\n\t\tprop.dh = deltaH;\n\t\tprop.hg[0] = tht_m;  prop.hg[1] = rht_m;\n\t\tpropv.klim = (__int32)radio_climate;\n\t\tprop.ens = eno;\n\t\tprop.kwx = 0;\n\t\tivar = (long)ModVar;\n\t\tipol = (long)pol;\n\t\tqlrps(frq_mhz, 0.0, eno, ipol, eps, sgm, prop);\n\t\tqlra(kst, propv.klim, ivar, prop, propv);\n\t\tif (propv.lvar < 1) propv.lvar = 1;\n\t\tlrprop(dist_km * 1000.0, prop, propa);\n\t\tfs = 32.45 + 20.0 * log10(frq_mhz) + 20.0 * log10(prop.dist \/ 1000.0);\n\t\txlb = fs + avar(zt, zl, zc, prop, propv);\n\t\tdbloss = xlb;\n\t\tif (prop.kwx == 0)\n\t\t\terrnum = 0;\n\t\telse\n\t\t\terrnum = prop.kwx;\n\t}\n}\n\ndouble DllExport _stdcall ITMAreadBLoss(long ModVar, double deltaH, double tht_m, double rht_m,\n\tdouble dist_km, int TSiteCriteria, int RSiteCriteria,\n\tdouble eps_dielect, double sgm_conductivity, double eno_ns_surfref,\n\tdouble frq_mhz, int radio_climate, int pol, double pctTime, double pctLoc,\n\tdouble pctConf)\n{\n\tchar strmode[200];\n\tint errnum;\n\tdouble dbloss;\n\tarea(ModVar, deltaH, tht_m, rht_m, dist_km, TSiteCriteria, RSiteCriteria,\n\t\teps_dielect, sgm_conductivity, eno_ns_surfref,\n\t\tfrq_mhz, radio_climate, pol, pctTime, pctLoc,\n\t\tpctConf, dbloss, strmode, errnum);\n\treturn dbloss;\n}\n\ndouble  DllExport _stdcall ITMDLLVersion()\n{\n\treturn 7.0;\n}\n","avg_line_length":25.2973174367,"max_line_length":108,"alphanum_fraction":0.5574538278,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":36118,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2013 The Bitcoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/test\/unit_test.hpp>\n#include <stdint.h>\n#include <sstream>\n#include <iomanip>\n#include <limits>\n#include <cmath>\n#include \"uint256.h\"\n#include <string>\n#include \"version.h\"\n\nBOOST_AUTO_TEST_SUITE(uint256_tests)\n \nconst unsigned char R1Array[] = \n    \"\\x9c\\x52\\x4a\\xdb\\xcf\\x56\\x11\\x12\\x2b\\x29\\x12\\x5e\\x5d\\x35\\xd2\\xd2\"\n    \"\\x22\\x81\\xaa\\xb5\\x33\\xf0\\x08\\x32\\xd5\\x56\\xb1\\xf9\\xea\\xe5\\x1d\\x7d\";\nconst char R1ArrayHex[] = \"7D1DE5EAF9B156D53208F033B5AA8122D2d2355d5e12292b121156cfdb4a529c\";\nconst double R1Ldouble = 0.4887374590559308955; \/\/ R1L equals roughly R1Ldouble * 2^256\nconst double R1Sdouble = 0.7096329412477836074; \nconst uint256 R1L = uint256(std::vector<unsigned char>(R1Array,R1Array+32));\nconst uint160 R1S = uint160(std::vector<unsigned char>(R1Array,R1Array+20));\nconst uint64_t R1LLow64 = 0x121156cfdb4a529cULL;\n\nconst unsigned char R2Array[] = \n    \"\\x70\\x32\\x1d\\x7c\\x47\\xa5\\x6b\\x40\\x26\\x7e\\x0a\\xc3\\xa6\\x9c\\xb6\\xbf\"\n    \"\\x13\\x30\\x47\\xa3\\x19\\x2d\\xda\\x71\\x49\\x13\\x72\\xf0\\xb4\\xca\\x81\\xd7\";\nconst uint256 R2L = uint256(std::vector<unsigned char>(R2Array,R2Array+32));\nconst uint160 R2S = uint160(std::vector<unsigned char>(R2Array,R2Array+20));\n\nconst char R1LplusR2L[] = \"549FB09FEA236A1EA3E31D4D58F1B1369288D204211CA751527CFC175767850C\";\n\nconst unsigned char ZeroArray[] = \n    \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n    \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\";\nconst uint256 ZeroL = uint256(std::vector<unsigned char>(ZeroArray,ZeroArray+32));\nconst uint160 ZeroS = uint160(std::vector<unsigned char>(ZeroArray,ZeroArray+20));\n                             \nconst unsigned char OneArray[] = \n    \"\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n    \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\";\nconst uint256 OneL = uint256(std::vector<unsigned char>(OneArray,OneArray+32));\nconst uint160 OneS = uint160(std::vector<unsigned char>(OneArray,OneArray+20));\n\nconst unsigned char MaxArray[] = \n    \"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\"\n    \"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\";\nconst uint256 MaxL = uint256(std::vector<unsigned char>(MaxArray,MaxArray+32));\nconst uint160 MaxS = uint160(std::vector<unsigned char>(MaxArray,MaxArray+20));\n\nconst uint256 HalfL = (OneL << 255);\nconst uint160 HalfS = (OneS << 159);\nstd::string ArrayToString(const unsigned char A[], unsigned int width)\n{\n    std::stringstream Stream;\n    Stream << std::hex;\n    for (unsigned int i = 0; i < width; ++i) \n    {\n        Stream<<std::setw(2)<<std::setfill('0')<<(unsigned int)A[width-i-1];\n    }       \n    return Stream.str();\n}\n\nBOOST_AUTO_TEST_CASE( basics ) \/\/ constructors, equality, inequality\n{\n    BOOST_CHECK(1 == 0+1);\n    \/\/ constructor uint256(vector<char>):\n    BOOST_CHECK(R1L.ToString() == ArrayToString(R1Array,32));\n    BOOST_CHECK(R1S.ToString() == ArrayToString(R1Array,20));\n    BOOST_CHECK(R2L.ToString() == ArrayToString(R2Array,32));\n    BOOST_CHECK(R2S.ToString() == ArrayToString(R2Array,20));\n    BOOST_CHECK(ZeroL.ToString() == ArrayToString(ZeroArray,32));\n    BOOST_CHECK(ZeroS.ToString() == ArrayToString(ZeroArray,20));\n    BOOST_CHECK(OneL.ToString() == ArrayToString(OneArray,32));\n    BOOST_CHECK(OneS.ToString() == ArrayToString(OneArray,20));\n    BOOST_CHECK(MaxL.ToString() == ArrayToString(MaxArray,32));\n    BOOST_CHECK(MaxS.ToString() == ArrayToString(MaxArray,20));\n    BOOST_CHECK(OneL.ToString() != ArrayToString(ZeroArray,32));\n    BOOST_CHECK(OneS.ToString() != ArrayToString(ZeroArray,20));\n\n    \/\/ == and !=\n    BOOST_CHECK(R1L != R2L && R1S != R2S);\n    BOOST_CHECK(ZeroL != OneL && ZeroS != OneS);\n    BOOST_CHECK(OneL != ZeroL && OneS != ZeroS);\n    BOOST_CHECK(MaxL != ZeroL && MaxS != ZeroS);\n    BOOST_CHECK(~MaxL == ZeroL && ~MaxS == ZeroS);\n    BOOST_CHECK( ((R1L ^ R2L) ^ R1L) == R2L);\n    BOOST_CHECK( ((R1S ^ R2S) ^ R1S) == R2S);\n    \n    uint64_t Tmp64 = 0xc4dab720d9c7acaaULL;\n    for (unsigned int i = 0; i < 256; ++i) \n    {\n        BOOST_CHECK(ZeroL != (OneL << i)); \n        BOOST_CHECK((OneL << i) != ZeroL); \n        BOOST_CHECK(R1L != (R1L ^ (OneL << i)));\n        BOOST_CHECK(((uint256(Tmp64) ^ (OneL << i) ) != Tmp64 ));\n    }\n    BOOST_CHECK(ZeroL == (OneL << 256)); \n\n    for (unsigned int i = 0; i < 160; ++i) \n    {\n        BOOST_CHECK(ZeroS != (OneS << i)); \n        BOOST_CHECK((OneS << i) != ZeroS); \n        BOOST_CHECK(R1S != (R1S ^ (OneS << i)));\n        BOOST_CHECK(((uint160(Tmp64) ^ (OneS << i) ) != Tmp64 ));\n    }\n    BOOST_CHECK(ZeroS == (OneS << 256)); \n\n    \/\/ String Constructor and Copy Constructor\n    BOOST_CHECK(uint256(\"0x\"+R1L.ToString()) == R1L);\n    BOOST_CHECK(uint256(\"0x\"+R2L.ToString()) == R2L);\n    BOOST_CHECK(uint256(\"0x\"+ZeroL.ToString()) == ZeroL);\n    BOOST_CHECK(uint256(\"0x\"+OneL.ToString()) == OneL);\n    BOOST_CHECK(uint256(\"0x\"+MaxL.ToString()) == MaxL);\n    BOOST_CHECK(uint256(R1L.ToString()) == R1L);\n    BOOST_CHECK(uint256(\"   0x\"+R1L.ToString()+\"   \") == R1L);\n    BOOST_CHECK(uint256(\"\") == ZeroL);\n    BOOST_CHECK(R1L == uint256(R1ArrayHex));\n    BOOST_CHECK(uint256(R1L) == R1L);\n    BOOST_CHECK((uint256(R1L^R2L)^R2L) == R1L);\n    BOOST_CHECK(uint256(ZeroL) == ZeroL);\n    BOOST_CHECK(uint256(OneL) == OneL);\n\n    BOOST_CHECK(uint160(\"0x\"+R1S.ToString()) == R1S);\n    BOOST_CHECK(uint160(\"0x\"+R2S.ToString()) == R2S);\n    BOOST_CHECK(uint160(\"0x\"+ZeroS.ToString()) == ZeroS);\n    BOOST_CHECK(uint160(\"0x\"+OneS.ToString()) == OneS);\n    BOOST_CHECK(uint160(\"0x\"+MaxS.ToString()) == MaxS);\n    BOOST_CHECK(uint160(R1S.ToString()) == R1S);\n    BOOST_CHECK(uint160(\"   0x\"+R1S.ToString()+\"   \") == R1S); \n    BOOST_CHECK(uint160(\"\") == ZeroS);\n    BOOST_CHECK(R1S == uint160(R1ArrayHex));\n\n    BOOST_CHECK(uint160(R1S) == R1S);\n    BOOST_CHECK((uint160(R1S^R2S)^R2S) == R1S);\n    BOOST_CHECK(uint160(ZeroS) == ZeroS);\n    BOOST_CHECK(uint160(OneS) == OneS);\n\n    \/\/ uint64_t constructor\n    BOOST_CHECK( (R1L & uint256(\"0xffffffffffffffff\")) == uint256(R1LLow64));\n    BOOST_CHECK(ZeroL == uint256(0));\n    BOOST_CHECK(OneL == uint256(1));\n    BOOST_CHECK(uint256(\"0xffffffffffffffff\") = uint256(0xffffffffffffffffULL));\n    BOOST_CHECK( (R1S & uint160(\"0xffffffffffffffff\")) == uint160(R1LLow64));\n    BOOST_CHECK(ZeroS == uint160(0));\n    BOOST_CHECK(OneS == uint160(1));\n    BOOST_CHECK(uint160(\"0xffffffffffffffff\") = uint160(0xffffffffffffffffULL));\n\n    \/\/ Assignment (from base_uint)\n    uint256 tmpL = ~ZeroL; BOOST_CHECK(tmpL == ~ZeroL);\n    tmpL = ~OneL; BOOST_CHECK(tmpL == ~OneL);\n    tmpL = ~R1L; BOOST_CHECK(tmpL == ~R1L);\n    tmpL = ~R2L; BOOST_CHECK(tmpL == ~R2L);\n    tmpL = ~MaxL; BOOST_CHECK(tmpL == ~MaxL);\n    uint160 tmpS = ~ZeroS; BOOST_CHECK(tmpS == ~ZeroS);\n    tmpS = ~OneS; BOOST_CHECK(tmpS == ~OneS);\n    tmpS = ~R1S; BOOST_CHECK(tmpS == ~R1S);\n    tmpS = ~R2S; BOOST_CHECK(tmpS == ~R2S);\n    tmpS = ~MaxS; BOOST_CHECK(tmpS == ~MaxS);\n\n    \/\/ Wrong length must throw exception.\n    BOOST_CHECK_THROW(uint256(std::vector<unsigned char>(OneArray,OneArray+31)), uint_error);\n    BOOST_CHECK_THROW(uint256(std::vector<unsigned char>(OneArray,OneArray+20)), uint_error);\n    BOOST_CHECK_THROW(uint160(std::vector<unsigned char>(OneArray,OneArray+32)), uint_error);\n    BOOST_CHECK_THROW(uint160(std::vector<unsigned char>(OneArray,OneArray+19)), uint_error);\n}\n\nvoid shiftArrayRight(unsigned char* to, const unsigned char* from, unsigned int arrayLength, unsigned int bitsToShift) \n{\n    for (unsigned int T=0; T < arrayLength; ++T) \n    {\n        unsigned int F = (T+bitsToShift\/8);\n        if (F < arrayLength) \n            to[T]  = from[F] >> (bitsToShift%8);\n        else\n            to[T] = 0;\n        if (F + 1 < arrayLength) \n            to[T] |= from[(F+1)] << (8-bitsToShift%8);\n    }\n}\n\nvoid shiftArrayLeft(unsigned char* to, const unsigned char* from, unsigned int arrayLength, unsigned int bitsToShift) \n{\n    for (unsigned int T=0; T < arrayLength; ++T) \n    {\n        if (T >= bitsToShift\/8) \n        {\n            unsigned int F = T-bitsToShift\/8;\n            to[T]  = from[F] << (bitsToShift%8);\n            if (T >= bitsToShift\/8+1)\n                to[T] |= from[F-1] >> (8-bitsToShift%8);\n        }\n        else {\n            to[T] = 0;\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE( shifts ) { \/\/ \"<<\"  \">>\"  \"<<=\"  \">>=\"\n    unsigned char TmpArray[32];\n    uint256 TmpL;\n    for (unsigned int i = 0; i < 256; ++i)\n    {\n        shiftArrayLeft(TmpArray, OneArray, 32, i);\n        BOOST_CHECK(uint256(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (OneL << i));\n        TmpL = OneL; TmpL <<= i;\n        BOOST_CHECK(TmpL == (OneL << i));\n        BOOST_CHECK((HalfL >> (255-i)) == (OneL << i));\n        TmpL = HalfL; TmpL >>= (255-i);\n        BOOST_CHECK(TmpL == (OneL << i));\n                    \n        shiftArrayLeft(TmpArray, R1Array, 32, i);\n        BOOST_CHECK(uint256(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (R1L << i));\n        TmpL = R1L; TmpL <<= i;\n        BOOST_CHECK(TmpL == (R1L << i));\n\n        shiftArrayRight(TmpArray, R1Array, 32, i);\n        BOOST_CHECK(uint256(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (R1L >> i)); \n        TmpL = R1L; TmpL >>= i;\n        BOOST_CHECK(TmpL == (R1L >> i));\n\n        shiftArrayLeft(TmpArray, MaxArray, 32, i);\n        BOOST_CHECK(uint256(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (MaxL << i));\n        TmpL = MaxL; TmpL <<= i;\n        BOOST_CHECK(TmpL == (MaxL << i));\n\n        shiftArrayRight(TmpArray, MaxArray, 32, i);\n        BOOST_CHECK(uint256(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (MaxL >> i));\n        TmpL = MaxL; TmpL >>= i;\n        BOOST_CHECK(TmpL == (MaxL >> i));\n    }\n    uint256 c1L = uint256(0x0123456789abcdefULL);\n    uint256 c2L = c1L << 128;\n    for (unsigned int i = 0; i < 128; ++i) {\n        BOOST_CHECK((c1L << i) == (c2L >> (128-i)));\n    }\n    for (unsigned int i = 128; i < 256; ++i) {\n        BOOST_CHECK((c1L << i) == (c2L << (i-128)));\n    }\n\n    uint160 TmpS;\n    for (unsigned int i = 0; i < 160; ++i)\n    {\n        shiftArrayLeft(TmpArray, OneArray, 20, i);\n        BOOST_CHECK(uint160(std::vector<unsigned char>(TmpArray,TmpArray+20)) == (OneS << i));\n        TmpS = OneS; TmpS <<= i;\n        BOOST_CHECK(TmpS == (OneS << i));\n        BOOST_CHECK((HalfS >> (159-i)) == (OneS << i));\n        TmpS = HalfS; TmpS >>= (159-i);\n        BOOST_CHECK(TmpS == (OneS << i));\n                    \n        shiftArrayLeft(TmpArray, R1Array, 20, i);\n        BOOST_CHECK(uint160(std::vector<unsigned char>(TmpArray,TmpArray+20)) == (R1S << i));\n        TmpS = R1S; TmpS <<= i;\n        BOOST_CHECK(TmpS == (R1S << i));\n\n        shiftArrayRight(TmpArray, R1Array, 20, i);\n        BOOST_CHECK(uint160(std::vector<unsigned char>(TmpArray,TmpArray+20)) == (R1S >> i)); \n        TmpS = R1S; TmpS >>= i;\n        BOOST_CHECK(TmpS == (R1S >> i));\n\n        shiftArrayLeft(TmpArray, MaxArray, 20, i);\n        BOOST_CHECK(uint160(std::vector<unsigned char>(TmpArray,TmpArray+20)) == (MaxS << i));\n        TmpS = MaxS; TmpS <<= i;\n        BOOST_CHECK(TmpS == (MaxS << i));\n\n        shiftArrayRight(TmpArray, MaxArray, 20, i);\n        BOOST_CHECK(uint160(std::vector<unsigned char>(TmpArray,TmpArray+20)) == (MaxS >> i));\n        TmpS = MaxS; TmpS >>= i;\n        BOOST_CHECK(TmpS == (MaxS >> i));\n    }\n    uint160 c1S = uint160(0x0123456789abcdefULL);\n    uint160 c2S = c1S << 80;\n    for (unsigned int i = 0; i < 80; ++i) {\n        BOOST_CHECK((c1S << i) == (c2S >> (80-i)));\n    }\n    for (unsigned int i = 80; i < 160; ++i) {\n        BOOST_CHECK((c1S << i) == (c2S << (i-80)));\n    }\n}\n\nBOOST_AUTO_TEST_CASE( unaryOperators ) \/\/ !    ~    -\n{\n    BOOST_CHECK(!ZeroL);  BOOST_CHECK(!ZeroS);\n    BOOST_CHECK(!(!OneL));BOOST_CHECK(!(!OneS));\n    for (unsigned int i = 0; i < 256; ++i) \n        BOOST_CHECK(!(!(OneL<<i)));\n    for (unsigned int i = 0; i < 160; ++i) \n        BOOST_CHECK(!(!(OneS<<i)));\n    BOOST_CHECK(!(!R1L));BOOST_CHECK(!(!R1S));\n    BOOST_CHECK(!(!R2S));BOOST_CHECK(!(!R2S)); \n    BOOST_CHECK(!(!MaxL));BOOST_CHECK(!(!MaxS));\n\n    BOOST_CHECK(~ZeroL == MaxL); BOOST_CHECK(~ZeroS == MaxS);\n\n    unsigned char TmpArray[32];\n    for (unsigned int i = 0; i < 32; ++i) { TmpArray[i] = ~R1Array[i]; } \n    BOOST_CHECK(uint256(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (~R1L));\n    BOOST_CHECK(uint160(std::vector<unsigned char>(TmpArray,TmpArray+20)) == (~R1S));\n\n    BOOST_CHECK(-ZeroL == ZeroL); BOOST_CHECK(-ZeroS == ZeroS);\n    BOOST_CHECK(-R1L == (~R1L)+1);\n    BOOST_CHECK(-R1S == (~R1S)+1);\n    for (unsigned int i = 0; i < 256; ++i) \n        BOOST_CHECK(-(OneL<<i) == (MaxL << i));\n    for (unsigned int i = 0; i < 160; ++i) \n        BOOST_CHECK(-(OneS<<i) == (MaxS << i));\n}\n\n\n\/\/ Check if doing _A_ _OP_ _B_ results in the same as applying _OP_ onto each\n\/\/ element of Aarray and Barray, and then converting the result into a uint256.\n#define CHECKBITWISEOPERATOR(_A_,_B_,_OP_)                              \\\n    for (unsigned int i = 0; i < 32; ++i) { TmpArray[i] = _A_##Array[i] _OP_ _B_##Array[i]; } \\\n    BOOST_CHECK(uint256(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (_A_##L _OP_ _B_##L)); \\\n    for (unsigned int i = 0; i < 20; ++i) { TmpArray[i] = _A_##Array[i] _OP_ _B_##Array[i]; } \\\n    BOOST_CHECK(uint160(std::vector<unsigned char>(TmpArray,TmpArray+20)) == (_A_##S _OP_ _B_##S));\n\n#define CHECKASSIGNMENTOPERATOR(_A_,_B_,_OP_)                           \\\n    TmpL = _A_##L; TmpL _OP_##= _B_##L; BOOST_CHECK(TmpL == (_A_##L _OP_ _B_##L)); \\\n    TmpS = _A_##S; TmpS _OP_##= _B_##S; BOOST_CHECK(TmpS == (_A_##S _OP_ _B_##S));\n\nBOOST_AUTO_TEST_CASE( bitwiseOperators ) \n{\n    unsigned char TmpArray[32];\n    \n    CHECKBITWISEOPERATOR(R1,R2,|)\n    CHECKBITWISEOPERATOR(R1,R2,^)\n    CHECKBITWISEOPERATOR(R1,R2,&)\n    CHECKBITWISEOPERATOR(R1,Zero,|)\n    CHECKBITWISEOPERATOR(R1,Zero,^)\n    CHECKBITWISEOPERATOR(R1,Zero,&)\n    CHECKBITWISEOPERATOR(R1,Max,|)\n    CHECKBITWISEOPERATOR(R1,Max,^)\n    CHECKBITWISEOPERATOR(R1,Max,&)\n    CHECKBITWISEOPERATOR(Zero,R1,|)\n    CHECKBITWISEOPERATOR(Zero,R1,^)\n    CHECKBITWISEOPERATOR(Zero,R1,&)\n    CHECKBITWISEOPERATOR(Max,R1,|)\n    CHECKBITWISEOPERATOR(Max,R1,^)\n    CHECKBITWISEOPERATOR(Max,R1,&)\n\n    uint256 TmpL;\n    uint160 TmpS;\n    CHECKASSIGNMENTOPERATOR(R1,R2,|)\n    CHECKASSIGNMENTOPERATOR(R1,R2,^)\n    CHECKASSIGNMENTOPERATOR(R1,R2,&)\n    CHECKASSIGNMENTOPERATOR(R1,Zero,|)\n    CHECKASSIGNMENTOPERATOR(R1,Zero,^)\n    CHECKASSIGNMENTOPERATOR(R1,Zero,&)\n    CHECKASSIGNMENTOPERATOR(R1,Max,|)\n    CHECKASSIGNMENTOPERATOR(R1,Max,^)\n    CHECKASSIGNMENTOPERATOR(R1,Max,&)\n    CHECKASSIGNMENTOPERATOR(Zero,R1,|)\n    CHECKASSIGNMENTOPERATOR(Zero,R1,^)\n    CHECKASSIGNMENTOPERATOR(Zero,R1,&)\n    CHECKASSIGNMENTOPERATOR(Max,R1,|)\n    CHECKASSIGNMENTOPERATOR(Max,R1,^)\n    CHECKASSIGNMENTOPERATOR(Max,R1,&)\n\n    uint64_t Tmp64 = 0xe1db685c9a0b47a2ULL; \n    TmpL = R1L; TmpL |= Tmp64;  BOOST_CHECK(TmpL == (R1L | uint256(Tmp64)));\n    TmpS = R1S; TmpS |= Tmp64;  BOOST_CHECK(TmpS == (R1S | uint160(Tmp64)));\n    TmpL = R1L; TmpL |= 0; BOOST_CHECK(TmpL == R1L);\n    TmpS = R1S; TmpS |= 0; BOOST_CHECK(TmpS == R1S);\n    TmpL ^= 0; BOOST_CHECK(TmpL == R1L);\n    TmpS ^= 0; BOOST_CHECK(TmpS == R1S);\n    TmpL ^= Tmp64;  BOOST_CHECK(TmpL == (R1L ^ uint256(Tmp64)));\n    TmpS ^= Tmp64;  BOOST_CHECK(TmpS == (R1S ^ uint160(Tmp64)));\n}\n\nBOOST_AUTO_TEST_CASE( comparison ) \/\/ <= >= < >\n{\n    uint256 TmpL;\n    for (unsigned int i = 0; i < 256; ++i) {\n        TmpL= OneL<< i;\n        BOOST_CHECK( TmpL >= ZeroL && TmpL > ZeroL && ZeroL < TmpL && ZeroL <= TmpL);\n        BOOST_CHECK( TmpL >= 0 && TmpL > 0 && 0 < TmpL && 0 <= TmpL);\n        TmpL |= R1L;\n        BOOST_CHECK( TmpL >= R1L ); BOOST_CHECK( (TmpL == R1L) != (TmpL > R1L)); BOOST_CHECK( (TmpL == R1L) || !( TmpL <= R1L));\n        BOOST_CHECK( R1L <= TmpL ); BOOST_CHECK( (R1L == TmpL) != (R1L < TmpL)); BOOST_CHECK( (TmpL == R1L) || !( R1L >= TmpL));\n        BOOST_CHECK(! (TmpL < R1L)); BOOST_CHECK(! (R1L > TmpL));\n    }\n    uint160 TmpS;\n    for (unsigned int i = 0; i < 160; ++i) {\n        TmpS= OneS<< i;\n        BOOST_CHECK( TmpS >= ZeroS && TmpS > ZeroS && ZeroS < TmpS && ZeroS <= TmpS);\n        BOOST_CHECK( TmpS >= 0 && TmpS > 0 && 0 < TmpS && 0 <= TmpS);\n        TmpS |= R1S;\n        BOOST_CHECK( TmpS >= R1S ); BOOST_CHECK( (TmpS == R1S) != (TmpS > R1S)); BOOST_CHECK( (TmpS == R1S) || !( TmpS <= R1S));\n        BOOST_CHECK( R1S <= TmpS ); BOOST_CHECK( (R1S == TmpS) != (R1S < TmpS)); BOOST_CHECK( (TmpS == R1S) || !( R1S >= TmpS));\n        BOOST_CHECK(! (TmpS < R1S)); BOOST_CHECK(! (R1S > TmpS));\n    }\n}\n\nBOOST_AUTO_TEST_CASE( plusMinus ) \n{\n    uint256 TmpL = 0;\n    BOOST_CHECK(R1L+R2L == uint256(R1LplusR2L));\n    TmpL += R1L;\n    BOOST_CHECK(TmpL == R1L);\n    TmpL += R2L;\n    BOOST_CHECK(TmpL == R1L + R2L);\n    BOOST_CHECK(OneL+MaxL == ZeroL);\n    BOOST_CHECK(MaxL+OneL == ZeroL);\n    for (unsigned int i = 1; i < 256; ++i) {\n        BOOST_CHECK( (MaxL >> i) + OneL == (HalfL >> (i-1)) );\n        BOOST_CHECK( OneL + (MaxL >> i) == (HalfL >> (i-1)) );\n        TmpL = (MaxL>>i); TmpL += OneL;\n        BOOST_CHECK( TmpL == (HalfL >> (i-1)) );\n        TmpL = (MaxL>>i); TmpL += 1;\n        BOOST_CHECK( TmpL == (HalfL >> (i-1)) );\n        TmpL = (MaxL>>i); \n        BOOST_CHECK( TmpL++ == (MaxL>>i) );\n        BOOST_CHECK( TmpL == (HalfL >> (i-1)));\n    }\n    BOOST_CHECK(uint256(0xbedc77e27940a7ULL) + 0xee8d836fce66fbULL == uint256(0xbedc77e27940a7ULL + 0xee8d836fce66fbULL));\n    TmpL = uint256(0xbedc77e27940a7ULL); TmpL += 0xee8d836fce66fbULL;\n    BOOST_CHECK(TmpL == uint256(0xbedc77e27940a7ULL+0xee8d836fce66fbULL));\n    TmpL -= 0xee8d836fce66fbULL;  BOOST_CHECK(TmpL == 0xbedc77e27940a7ULL);\n    TmpL = R1L;\n    BOOST_CHECK(++TmpL == R1L+1);\n\n    BOOST_CHECK(R1L -(-R2L) == R1L+R2L);\n    BOOST_CHECK(R1L -(-OneL) == R1L+OneL);\n    BOOST_CHECK(R1L - OneL == R1L+(-OneL));\n    for (unsigned int i = 1; i < 256; ++i) {\n        BOOST_CHECK((MaxL>>i) - (-OneL)  == (HalfL >> (i-1)));\n        BOOST_CHECK((HalfL >> (i-1)) - OneL == (MaxL>>i));\n        TmpL = (HalfL >> (i-1));\n        BOOST_CHECK(TmpL-- == (HalfL >> (i-1)));\n        BOOST_CHECK(TmpL == (MaxL >> i));\n        TmpL = (HalfL >> (i-1));\n        BOOST_CHECK(--TmpL == (MaxL >> i));\n    }\n    TmpL = R1L;\n    BOOST_CHECK(--TmpL == R1L-1);\n\n    \/\/ 160-bit; copy-pasted\n    uint160 TmpS = 0;\n    BOOST_CHECK(R1S+R2S == uint160(R1LplusR2L));\n    TmpS += R1S;\n    BOOST_CHECK(TmpS == R1S);\n    TmpS += R2S;\n    BOOST_CHECK(TmpS == R1S + R2S);\n    BOOST_CHECK(OneS+MaxS == ZeroS);\n    BOOST_CHECK(MaxS+OneS == ZeroS);\n    for (unsigned int i = 1; i < 160; ++i) {\n        BOOST_CHECK( (MaxS >> i) + OneS == (HalfS >> (i-1)) );\n        BOOST_CHECK( OneS + (MaxS >> i) == (HalfS >> (i-1)) );\n        TmpS = (MaxS>>i); TmpS += OneS;\n        BOOST_CHECK( TmpS == (HalfS >> (i-1)) );\n        TmpS = (MaxS>>i); TmpS += 1;\n        BOOST_CHECK( TmpS == (HalfS >> (i-1)) );\n        TmpS = (MaxS>>i); \n        BOOST_CHECK( TmpS++ == (MaxS>>i) );\n        BOOST_CHECK( TmpS == (HalfS >> (i-1)));\n    }\n    BOOST_CHECK(uint160(0xbedc77e27940a7ULL) + 0xee8d836fce66fbULL == uint160(0xbedc77e27940a7ULL + 0xee8d836fce66fbULL));\n    TmpS = uint160(0xbedc77e27940a7ULL); TmpS += 0xee8d836fce66fbULL;\n    BOOST_CHECK(TmpS == uint160(0xbedc77e27940a7ULL+0xee8d836fce66fbULL));\n    TmpS -= 0xee8d836fce66fbULL;  BOOST_CHECK(TmpS == 0xbedc77e27940a7ULL);\n    TmpS = R1S;\n    BOOST_CHECK(++TmpS == R1S+1);\n\n    BOOST_CHECK(R1S -(-R2S) == R1S+R2S);\n    BOOST_CHECK(R1S -(-OneS) == R1S+OneS);\n    BOOST_CHECK(R1S - OneS == R1S+(-OneS));\n    for (unsigned int i = 1; i < 160; ++i) {\n        BOOST_CHECK((MaxS>>i) - (-OneS)  == (HalfS >> (i-1)));\n        BOOST_CHECK((HalfS >> (i-1)) - OneS == (MaxS>>i));\n        TmpS = (HalfS >> (i-1));\n        BOOST_CHECK(TmpS-- == (HalfS >> (i-1)));\n        BOOST_CHECK(TmpS == (MaxS >> i));\n        TmpS = (HalfS >> (i-1));\n        BOOST_CHECK(--TmpS == (MaxS >> i));\n    }\n    TmpS = R1S;\n    BOOST_CHECK(--TmpS == R1S-1);\n\n}\n\nBOOST_AUTO_TEST_CASE( multiply )\n{\n    BOOST_CHECK((R1L * R1L).ToString() == \"62a38c0486f01e45879d7910a7761bf30d5237e9873f9bff3642a732c4d84f10\");\n    BOOST_CHECK((R1L * R2L).ToString() == \"de37805e9986996cfba76ff6ba51c008df851987d9dd323f0e5de07760529c40\");\n    BOOST_CHECK((R1L * ZeroL) == ZeroL);\n    BOOST_CHECK((R1L * OneL) == R1L);\n    BOOST_CHECK((R1L * MaxL) == -R1L);\n    BOOST_CHECK((R2L * R1L) == (R1L * R2L));\n    BOOST_CHECK((R2L * R2L).ToString() == \"ac8c010096767d3cae5005dec28bb2b45a1d85ab7996ccd3e102a650f74ff100\");\n    BOOST_CHECK((R2L * ZeroL) == ZeroL);\n    BOOST_CHECK((R2L * OneL) == R2L);\n    BOOST_CHECK((R2L * MaxL) == -R2L);\n\n    BOOST_CHECK((R1S * R1S).ToString() == \"a7761bf30d5237e9873f9bff3642a732c4d84f10\");\n    BOOST_CHECK((R1S * R2S).ToString() == \"ba51c008df851987d9dd323f0e5de07760529c40\");\n    BOOST_CHECK((R1S * ZeroS) == ZeroS);\n    BOOST_CHECK((R1S * OneS) == R1S);\n    BOOST_CHECK((R1S * MaxS) == -R1S);\n    BOOST_CHECK((R2S * R1S) == (R1S * R2S));\n    BOOST_CHECK((R2S * R2S).ToString() == \"c28bb2b45a1d85ab7996ccd3e102a650f74ff100\");\n    BOOST_CHECK((R2S * ZeroS) == ZeroS);\n    BOOST_CHECK((R2S * OneS) == R2S);\n    BOOST_CHECK((R2S * MaxS) == -R2S);\n\n    BOOST_CHECK(MaxL * MaxL == OneL);\n    BOOST_CHECK(MaxS * MaxS == OneS);\n\n    BOOST_CHECK((R1L * 0) == 0);\n    BOOST_CHECK((R1L * 1) == R1L);\n    BOOST_CHECK((R1L * 3).ToString() == \"7759b1c0ed14047f961ad09b20ff83687876a0181a367b813634046f91def7d4\");\n    BOOST_CHECK((R2L * 0x97654321UL).ToString() == \"23f7816e30c4ae2017257b7a0fa64d60402f5234d46e746b61c960d09a26d070\");\n    BOOST_CHECK((R1S * 0) == 0);\n    BOOST_CHECK((R1S * 1) == R1S);\n    BOOST_CHECK((R1S * 7).ToString() == \"f7a987f3c3bf758d927f202d7e795faeff084244\");\n    BOOST_CHECK((R2S * 0xFFFFFFFFUL).ToString() == \"1c6f6c930353e17f7d6127213bb18d2883e2cd90\");\n}\n\nBOOST_AUTO_TEST_CASE( divide )\n{\n    uint256 D1L(\"AD7133AC1977FA2B7\");\n    uint256 D2L(\"ECD751716\");\n    BOOST_CHECK((R1L \/ D1L).ToString() == \"00000000000000000b8ac01106981635d9ed112290f8895545a7654dde28fb3a\");\n    BOOST_CHECK((R1L \/ D2L).ToString() == \"000000000873ce8efec5b67150bad3aa8c5fcb70e947586153bf2cec7c37c57a\");\n    BOOST_CHECK(R1L \/ OneL == R1L);\n    BOOST_CHECK(R1L \/ MaxL == ZeroL);\n    BOOST_CHECK(MaxL \/ R1L == 2);\n    BOOST_CHECK_THROW(R1L \/ ZeroL, uint_error);\n    BOOST_CHECK((R2L \/ D1L).ToString() == \"000000000000000013e1665895a1cc981de6d93670105a6b3ec3b73141b3a3c5\");\n    BOOST_CHECK((R2L \/ D2L).ToString() == \"000000000e8f0abe753bb0afe2e9437ee85d280be60882cf0bd1aaf7fa3cc2c4\");\n    BOOST_CHECK(R2L \/ OneL == R2L);\n    BOOST_CHECK(R2L \/ MaxL == ZeroL);\n    BOOST_CHECK(MaxL \/ R2L == 1);\n    BOOST_CHECK_THROW(R2L \/ ZeroL, uint_error);\n\n    uint160 D1S(\"D3C5EDCDEA54EB92679F0A4B4\");\n    uint160 D2S(\"13037\");\n    BOOST_CHECK((R1S \/ D1S).ToString() == \"0000000000000000000000000db9af3beade6c02\");\n    BOOST_CHECK((R1S \/ D2S).ToString() == \"000098dfb6cc40ca592bf74366794f298ada205c\");\n    BOOST_CHECK(R1S \/ OneS == R1S);\n    BOOST_CHECK(R1S \/ MaxS == ZeroS);\n    BOOST_CHECK(MaxS \/ R1S == 1);\n    BOOST_CHECK_THROW(R1S \/ ZeroS, uint_error);\n    BOOST_CHECK((R2S \/ D1S).ToString() == \"0000000000000000000000000c5608e781182047\");\n    BOOST_CHECK((R2S \/ D2S).ToString() == \"00008966751b7187c3c67c1fda5cea7db2c1c069\");\n    BOOST_CHECK(R2S \/ OneS == R2S);\n    BOOST_CHECK(R2S \/ MaxS == ZeroS);\n    BOOST_CHECK(MaxS \/ R2S == 1);\n    BOOST_CHECK_THROW(R2S \/ ZeroS, uint_error);\n}\n\n\nbool almostEqual(double d1, double d2) \n{\n    return fabs(d1-d2) <= 4*fabs(d1)*std::numeric_limits<double>::epsilon();\n}\n\nBOOST_AUTO_TEST_CASE( methods ) \/\/ GetHex SetHex begin() end() size() GetLow64 GetSerializeSize, Serialize, Unserialize\n{\n    BOOST_CHECK(R1L.GetHex() == R1L.ToString());\n    BOOST_CHECK(R2L.GetHex() == R2L.ToString());\n    BOOST_CHECK(OneL.GetHex() == OneL.ToString());\n    BOOST_CHECK(MaxL.GetHex() == MaxL.ToString());\n    uint256 TmpL(R1L);\n    BOOST_CHECK(TmpL == R1L);\n    TmpL.SetHex(R2L.ToString());   BOOST_CHECK(TmpL == R2L);\n    TmpL.SetHex(ZeroL.ToString()); BOOST_CHECK(TmpL == 0);\n    TmpL.SetHex(HalfL.ToString()); BOOST_CHECK(TmpL == HalfL);\n\n    TmpL.SetHex(R1L.ToString());\n    BOOST_CHECK(memcmp(R1L.begin(), R1Array, 32)==0);\n    BOOST_CHECK(memcmp(TmpL.begin(), R1Array, 32)==0);\n    BOOST_CHECK(memcmp(R2L.begin(), R2Array, 32)==0);\n    BOOST_CHECK(memcmp(ZeroL.begin(), ZeroArray, 32)==0);\n    BOOST_CHECK(memcmp(OneL.begin(), OneArray, 32)==0);\n    BOOST_CHECK(R1L.size() == 32);\n    BOOST_CHECK(R2L.size() == 32);\n    BOOST_CHECK(ZeroL.size() == 32);\n    BOOST_CHECK(MaxL.size() == 32);\n    BOOST_CHECK(R1L.begin() + 32 == R1L.end());\n    BOOST_CHECK(R2L.begin() + 32 == R2L.end());\n    BOOST_CHECK(OneL.begin() + 32 == OneL.end());\n    BOOST_CHECK(MaxL.begin() + 32 == MaxL.end());\n    BOOST_CHECK(TmpL.begin() + 32 == TmpL.end());\n    BOOST_CHECK(R1L.GetLow64()  == R1LLow64);\n    BOOST_CHECK(HalfL.GetLow64() ==0x0000000000000000ULL);\n    BOOST_CHECK(OneL.GetLow64() ==0x0000000000000001ULL);\n    BOOST_CHECK(R1L.GetSerializeSize(0,PROTOCOL_VERSION) == 32);\n    BOOST_CHECK(ZeroL.GetSerializeSize(0,PROTOCOL_VERSION) == 32);\n\n    std::stringstream ss;\n    R1L.Serialize(ss,0,PROTOCOL_VERSION);\n    BOOST_CHECK(ss.str() == std::string(R1Array,R1Array+32));\n    TmpL.Unserialize(ss,0,PROTOCOL_VERSION);\n    BOOST_CHECK(R1L == TmpL);\n    ss.str(\"\");\n    ZeroL.Serialize(ss,0,PROTOCOL_VERSION);\n    BOOST_CHECK(ss.str() == std::string(ZeroArray,ZeroArray+32));\n    TmpL.Unserialize(ss,0,PROTOCOL_VERSION);\n    BOOST_CHECK(ZeroL == TmpL);\n    ss.str(\"\");\n    MaxL.Serialize(ss,0,PROTOCOL_VERSION);\n    BOOST_CHECK(ss.str() == std::string(MaxArray,MaxArray+32));\n    TmpL.Unserialize(ss,0,PROTOCOL_VERSION);\n    BOOST_CHECK(MaxL == TmpL);\n    ss.str(\"\");\n\n    BOOST_CHECK(R1S.GetHex() == R1S.ToString());\n    BOOST_CHECK(R2S.GetHex() == R2S.ToString());\n    BOOST_CHECK(OneS.GetHex() == OneS.ToString());\n    BOOST_CHECK(MaxS.GetHex() == MaxS.ToString());\n    uint160 TmpS(R1S);\n    BOOST_CHECK(TmpS == R1S);\n    TmpS.SetHex(R2S.ToString());   BOOST_CHECK(TmpS == R2S);\n    TmpS.SetHex(ZeroS.ToString()); BOOST_CHECK(TmpS == 0);\n    TmpS.SetHex(HalfS.ToString()); BOOST_CHECK(TmpS == HalfS);\n\n    TmpS.SetHex(R1S.ToString());\n    BOOST_CHECK(memcmp(R1S.begin(), R1Array, 20)==0);\n    BOOST_CHECK(memcmp(TmpS.begin(), R1Array, 20)==0);\n    BOOST_CHECK(memcmp(R2S.begin(), R2Array, 20)==0);\n    BOOST_CHECK(memcmp(ZeroS.begin(), ZeroArray, 20)==0);\n    BOOST_CHECK(memcmp(OneS.begin(), OneArray, 20)==0);\n    BOOST_CHECK(R1S.size() == 20);\n    BOOST_CHECK(R2S.size() == 20);\n    BOOST_CHECK(ZeroS.size() == 20);\n    BOOST_CHECK(MaxS.size() == 20);\n    BOOST_CHECK(R1S.begin() + 20 == R1S.end());\n    BOOST_CHECK(R2S.begin() + 20 == R2S.end());\n    BOOST_CHECK(OneS.begin() + 20 == OneS.end());\n    BOOST_CHECK(MaxS.begin() + 20 == MaxS.end());\n    BOOST_CHECK(TmpS.begin() + 20 == TmpS.end());\n    BOOST_CHECK(R1S.GetLow64()  == R1LLow64);\n    BOOST_CHECK(HalfS.GetLow64() ==0x0000000000000000ULL); \n    BOOST_CHECK(OneS.GetLow64() ==0x0000000000000001ULL);\n    BOOST_CHECK(R1S.GetSerializeSize(0,PROTOCOL_VERSION) == 20);\n    BOOST_CHECK(ZeroS.GetSerializeSize(0,PROTOCOL_VERSION) == 20);\n\n    R1S.Serialize(ss,0,PROTOCOL_VERSION);\n    BOOST_CHECK(ss.str() == std::string(R1Array,R1Array+20));\n    TmpS.Unserialize(ss,0,PROTOCOL_VERSION);\n    BOOST_CHECK(R1S == TmpS);\n    ss.str(\"\");\n    ZeroS.Serialize(ss,0,PROTOCOL_VERSION);\n    BOOST_CHECK(ss.str() == std::string(ZeroArray,ZeroArray+20));\n    TmpS.Unserialize(ss,0,PROTOCOL_VERSION);\n    BOOST_CHECK(ZeroS == TmpS);\n    ss.str(\"\");\n    MaxS.Serialize(ss,0,PROTOCOL_VERSION);\n    BOOST_CHECK(ss.str() == std::string(MaxArray,MaxArray+20));\n    TmpS.Unserialize(ss,0,PROTOCOL_VERSION);\n    BOOST_CHECK(MaxS == TmpS);\n    ss.str(\"\");\n    \n    for (unsigned int i = 0; i < 255; ++i) \n    {\n        BOOST_CHECK((OneL << i).getdouble() == ldexp(1.0,i));\n        if (i < 160) BOOST_CHECK((OneS << i).getdouble() == ldexp(1.0,i));\n    }\n    BOOST_CHECK(ZeroL.getdouble() == 0.0);\n    BOOST_CHECK(ZeroS.getdouble() == 0.0);\n    for (int i = 256; i > 53; --i) \n        BOOST_CHECK(almostEqual((R1L>>(256-i)).getdouble(), ldexp(R1Ldouble,i)));\n    for (int i = 160; i > 53; --i) \n        BOOST_CHECK(almostEqual((R1S>>(160-i)).getdouble(), ldexp(R1Sdouble,i)));\n    uint64_t R1L64part = (R1L>>192).GetLow64();\n    uint64_t R1S64part = (R1S>>96).GetLow64();\n    for (int i = 53; i > 0; --i) \/\/ doubles can store all integers in {0,...,2^54-1} exactly\n    {\n        BOOST_CHECK((R1L>>(256-i)).getdouble() == (double)(R1L64part >> (64-i)));\n        BOOST_CHECK((R1S>>(160-i)).getdouble() == (double)(R1S64part >> (64-i)));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(bignum_SetCompact)\n{\n    uint256 num;\n    bool fNegative;\n    bool fOverflow;\n    num.SetCompact(0, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000000000\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x00123456, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000000000\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x01003456, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000000000\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x02000056, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000000000\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x03000000, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000000000\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x04000000, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000000000\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x00923456, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000000000\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x01803456, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000000000\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x02800056, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000000000\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x03800000, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000000000\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x04800000, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000000000\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x01123456, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000000012\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0x01120000U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    \/\/ Make sure that we don't generate compacts with the 0x00800000 bit set\n    num = 0x80;\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0x02008000U);\n\n    num.SetCompact(0x01fedcba, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"000000000000000000000000000000000000000000000000000000000000007e\");\n    BOOST_CHECK_EQUAL(num.GetCompact(true), 0x01fe0000U);\n    BOOST_CHECK_EQUAL(fNegative, true);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x02123456, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000001234\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0x02123400U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x03123456, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000000123456\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0x03123456U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x04123456, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000012345600\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0x04123456U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x04923456, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000012345600\");\n    BOOST_CHECK_EQUAL(num.GetCompact(true), 0x04923456U);\n    BOOST_CHECK_EQUAL(fNegative, true);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x05009234, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"0000000000000000000000000000000000000000000000000000000092340000\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0x05009234U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0x20123456, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(num.GetHex(), \"1234560000000000000000000000000000000000000000000000000000000000\");\n    BOOST_CHECK_EQUAL(num.GetCompact(), 0x20123456U);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, false);\n\n    num.SetCompact(0xff123456, &fNegative, &fOverflow);\n    BOOST_CHECK_EQUAL(fNegative, false);\n    BOOST_CHECK_EQUAL(fOverflow, true);\n}\n\n\nBOOST_AUTO_TEST_CASE( getmaxcoverage ) \/\/ some more tests just to get 100% coverage\n{\n    \/\/ ~R1L give a base_uint<256>\n    BOOST_CHECK((~~R1L >> 10) == (R1L >> 10)); BOOST_CHECK((~~R1S >> 10) == (R1S >> 10));\n    BOOST_CHECK((~~R1L << 10) == (R1L << 10)); BOOST_CHECK((~~R1S << 10) == (R1S << 10));\n    BOOST_CHECK(!(~~R1L < R1L)); BOOST_CHECK(!(~~R1S < R1S)); \n    BOOST_CHECK(~~R1L <= R1L); BOOST_CHECK(~~R1S <= R1S); \n    BOOST_CHECK(!(~~R1L > R1L)); BOOST_CHECK(!(~~R1S > R1S)); \n    BOOST_CHECK(~~R1L >= R1L); BOOST_CHECK(~~R1S >= R1S); \n    BOOST_CHECK(!(R1L < ~~R1L)); BOOST_CHECK(!(R1S < ~~R1S)); \n    BOOST_CHECK(R1L <= ~~R1L); BOOST_CHECK(R1S <= ~~R1S); \n    BOOST_CHECK(!(R1L > ~~R1L)); BOOST_CHECK(!(R1S > ~~R1S)); \n    BOOST_CHECK(R1L >= ~~R1L); BOOST_CHECK(R1S >= ~~R1S); \n    \n    BOOST_CHECK(~~R1L + R2L == R1L + ~~R2L);\n    BOOST_CHECK(~~R1S + R2S == R1S + ~~R2S);\n    BOOST_CHECK(~~R1L - R2L == R1L - ~~R2L);\n    BOOST_CHECK(~~R1S - R2S == R1S - ~~R2S);\n    BOOST_CHECK(~R1L != R1L); BOOST_CHECK(R1L != ~R1L); \n    BOOST_CHECK(~R1S != R1S); BOOST_CHECK(R1S != ~R1S); \n    unsigned char TmpArray[32];\n    CHECKBITWISEOPERATOR(~R1,R2,|)\n    CHECKBITWISEOPERATOR(~R1,R2,^)\n    CHECKBITWISEOPERATOR(~R1,R2,&)\n    CHECKBITWISEOPERATOR(R1,~R2,|)\n    CHECKBITWISEOPERATOR(R1,~R2,^)\n    CHECKBITWISEOPERATOR(R1,~R2,&)\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n","avg_line_length":43.1002386635,"max_line_length":128,"alphanum_fraction":0.6436679772,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":608,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/* Before this file begins, this is an experiment conducted to test #define macro magic.\n * I remember reading in a book that the access modifiers protect against stupidity and \n * not malice, and I thought about running this small experiment of corrupting the \n * definition of an access modifier right before I import a class, and see what happens.\n *\/\n\n#include <iostream>\n\n#define private public\n#include \"rect.h\"\n#undef private\n\nint\nmain ()\n{\n  Rectangle rect;\n  \n  \/\/ I shouldn't be able to do that\n  rect.width = 5;\n  \n  std::cout << \"Rectangle's width: \" << rect.width << std::endl;\n  return 0;  \n}\n\n","avg_line_length":24.32,"max_line_length":88,"alphanum_fraction":0.7088815789,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2840,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause-Clear","Apache-2.0","MIT"],"max_stars_count":376.0,"content":"\/\/ Copyright (C) 2017 J\u00e9r\u00f4me Leclercq\n\/\/ This file is part of the \"Nazara Engine - Graphics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Graphics\/Model.hpp>\n#include <Nazara\/Graphics\/GraphicalMesh.hpp>\n#include <Nazara\/Graphics\/Graphics.hpp>\n#include <Nazara\/Graphics\/Material.hpp>\n#include <Nazara\/Graphics\/RenderSubmesh.hpp>\n#include <Nazara\/Graphics\/WorldInstance.hpp>\n#include <Nazara\/Renderer\/CommandBufferBuilder.hpp>\n#include <Nazara\/Graphics\/Debug.hpp>\n\nnamespace Nz\n{\n\tModel::Model(std::shared_ptr<GraphicalMesh> graphicalMesh, const Boxf& aabb) :\n\tInstancedRenderable(aabb),\n\tm_graphicalMesh(std::move(graphicalMesh))\n\t{\n\t\tm_submeshes.reserve(m_graphicalMesh->GetSubMeshCount());\n\t\tfor (std::size_t i = 0; i < m_graphicalMesh->GetSubMeshCount(); ++i)\n\t\t{\n\t\t\tauto& subMeshData = m_submeshes.emplace_back();\n\t\t\t\/\/subMeshData.material = DefaultMaterial; \/\/< TODO\n\t\t\tsubMeshData.vertexBufferData = {\n\t\t\t\t{\n\t\t\t\t\t0,\n\t\t\t\t\tm_graphicalMesh->GetVertexDeclaration(i)\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n\n\tvoid Model::BuildElement(std::size_t passIndex, const WorldInstance& worldInstance, std::vector<std::unique_ptr<RenderElement>>& elements) const\n\t{\n\t\tfor (std::size_t i = 0; i < m_submeshes.size(); ++i)\n\t\t{\n\t\t\tconst auto& submeshData = m_submeshes[i];\n\n\t\t\tconst auto& materialPass = submeshData.material->GetPass(passIndex);\n\t\t\tif (!materialPass)\n\t\t\t\tcontinue;\n\n\t\t\tconst auto& indexBuffer = m_graphicalMesh->GetIndexBuffer(i);\n\t\t\tconst auto& vertexBuffer = m_graphicalMesh->GetVertexBuffer(i);\n\t\t\tconst auto& renderPipeline = materialPass->GetPipeline()->GetRenderPipeline(submeshData.vertexBufferData);\n\n\t\t\telements.emplace_back(std::make_unique<RenderSubmesh>(0, materialPass, renderPipeline, worldInstance, m_graphicalMesh->GetIndexCount(i), indexBuffer, vertexBuffer));\n\t\t}\n\t}\n\n\tconst std::shared_ptr<AbstractBuffer>& Model::GetIndexBuffer(std::size_t subMeshIndex) const\n\t{\n\t\treturn m_graphicalMesh->GetIndexBuffer(subMeshIndex);\n\t}\n\n\tstd::size_t Model::GetIndexCount(std::size_t subMeshIndex) const\n\t{\n\t\treturn m_graphicalMesh->GetIndexCount(subMeshIndex);\n\t}\n\n\tconst std::shared_ptr<Material>& Model::GetMaterial(std::size_t subMeshIndex) const\n\t{\n\t\tassert(subMeshIndex < m_submeshes.size());\n\t\tconst auto& subMeshData = m_submeshes[subMeshIndex];\n\t\treturn subMeshData.material;\n\t}\n\n\tstd::size_t Model::GetMaterialCount() const\n\t{\n\t\treturn m_submeshes.size();\n\t}\n\n\tconst std::vector<RenderPipelineInfo::VertexBufferData>& Model::GetVertexBufferData(std::size_t subMeshIndex) const\n\t{\n\t\tassert(subMeshIndex < m_submeshes.size());\n\t\tconst auto& subMeshData = m_submeshes[subMeshIndex];\n\t\treturn subMeshData.vertexBufferData;\n\t}\n\n\tconst std::shared_ptr<AbstractBuffer>& Model::GetVertexBuffer(std::size_t subMeshIndex) const\n\t{\n\t\treturn m_graphicalMesh->GetVertexBuffer(subMeshIndex);\n\t}\n}\n","avg_line_length":33.023255814,"max_line_length":168,"alphanum_fraction":0.7563380282,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3603,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":3.0,"content":"\/* Copyright 2013-2018 Polycraft Launcher Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"NewsChecker.h\"\n\n#include <QByteArray>\n#include <QDomDocument>\n\n#include <QDebug>\n\nNewsChecker::NewsChecker(const QString& feedUrl)\n{\n    m_feedUrl = feedUrl;\n}\n\nvoid NewsChecker::reloadNews()\n{\n    \/\/ Start a netjob to download the RSS feed and call rssDownloadFinished() when it's done.\n    if (isLoadingNews())\n    {\n        qDebug() << \"Ignored request to reload news. Currently reloading already.\";\n        return;\n    }\n\n    qDebug() << \"Reloading news.\";\n\n    NetJob* job = new NetJob(\"News RSS Feed\");\n    job->addNetAction(Net::Download::makeByteArray(m_feedUrl, &newsData));\n    QObject::connect(job, &NetJob::succeeded, this, &NewsChecker::rssDownloadFinished);\n    QObject::connect(job, &NetJob::failed, this, &NewsChecker::rssDownloadFailed);\n    m_newsNetJob.reset(job);\n    job->start();\n}\n\nvoid NewsChecker::rssDownloadFinished()\n{\n    \/\/ Parse the XML file and process the RSS feed entries.\n    qDebug() << \"Finished loading RSS feed.\";\n\n    m_newsNetJob.reset();\n    QDomDocument doc;\n    {\n        \/\/ Stuff to store error info in.\n        QString errorMsg = \"Unknown error.\";\n        int errorLine = -1;\n        int errorCol = -1;\n\n        \/\/ Parse the XML.\n        if (!doc.setContent(newsData, false, &errorMsg, &errorLine, &errorCol))\n        {\n            QString fullErrorMsg = QString(\"Error parsing RSS feed XML. %s at %d:%d.\").arg(errorMsg, errorLine, errorCol);\n            fail(fullErrorMsg);\n            newsData.clear();\n            return;\n        }\n        newsData.clear();\n    }\n\n    \/\/ If the parsing succeeded, read it.\n    QDomNodeList items = doc.elementsByTagName(\"item\");\n    m_newsEntries.clear();\n    for (int i = 0; i < items.length(); i++)\n    {\n        QDomElement element = items.at(i).toElement();\n        NewsEntryPtr entry;\n        entry.reset(new NewsEntry());\n        QString errorMsg = \"An unknown error occurred.\";\n        if (NewsEntry::fromXmlElement(element, entry.get(), &errorMsg))\n        {\n            qDebug() << \"Loaded news entry\" << entry->title;\n            m_newsEntries.append(entry);\n        }\n        else\n        {\n            qWarning() << \"Failed to load news entry at index\" << i << \":\" << errorMsg;\n        }\n    }\n\n    succeed();\n}\n\nvoid NewsChecker::rssDownloadFailed(QString reason)\n{\n    \/\/ Set an error message and fail.\n    fail(tr(\"Failed to load news RSS feed:\\n%1\").arg(reason));\n}\n\n\nQList<NewsEntryPtr> NewsChecker::getNewsEntries() const\n{\n    return m_newsEntries;\n}\n\nbool NewsChecker::isLoadingNews() const\n{\n    return m_newsNetJob.get() != nullptr;\n}\n\nQString NewsChecker::getLastLoadErrorMsg() const\n{\n    return m_lastLoadError;\n}\n\nvoid NewsChecker::succeed()\n{\n    m_lastLoadError = \"\";\n    qDebug() << \"News loading succeeded.\";\n    m_newsNetJob.reset();\n    emit newsLoaded();\n}\n\nvoid NewsChecker::fail(const QString& errorMsg)\n{\n    m_lastLoadError = errorMsg;\n    qDebug() << \"Failed to load news:\" << errorMsg;\n    m_newsNetJob.reset();\n    emit newsLoadingFailed(errorMsg);\n}\n\n","avg_line_length":27.2954545455,"max_line_length":122,"alphanum_fraction":0.6466833195,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2822,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":2.0,"content":"\/\/------------------------------------------------------------------------------\n\/*\n    This file is part of Beast: https:\/\/github.com\/vinniefalco\/Beast\n    Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>\n\n    Permission to use, copy, modify, and\/or distribute this software for any\n    purpose  with  or without fee is hereby granted, provided that the above\n    copyright notice and this permission notice appear in all copies.\n\n    THE  SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF\n    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN\n    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*\/\n\/\/==============================================================================\n\n#include <MUSO\/beast\/unit_test.h>\n#include <MUSO\/beast\/utility\/Journal.h>\n\nnamespace beast {\n\nclass Journal_test : public unit_test::suite\n{\npublic:\n    class TestSink : public Journal::Sink\n    {\n    private:\n        int m_count;\n\n    public:\n        TestSink() : Sink(severities::kWarning, false), m_count(0)\n        {\n        }\n\n        int\n        count() const\n        {\n            return m_count;\n        }\n\n        void\n        reset()\n        {\n            m_count = 0;\n        }\n\n        void\n        write(severities::Severity level, std::string const&) override\n        {\n            if (level >= threshold())\n                ++m_count;\n        }\n    };\n\n    void\n    run() override\n    {\n        TestSink sink;\n\n        using namespace beast::severities;\n        sink.threshold(kInfo);\n\n        Journal j(sink);\n\n        j.trace() << \" \";\n        BEAST_EXPECT(sink.count() == 0);\n        j.debug() << \" \";\n        BEAST_EXPECT(sink.count() == 0);\n        j.info() << \" \";\n        BEAST_EXPECT(sink.count() == 1);\n        j.warn() << \" \";\n        BEAST_EXPECT(sink.count() == 2);\n        j.error() << \" \";\n        BEAST_EXPECT(sink.count() == 3);\n        j.fatal() << \" \";\n        BEAST_EXPECT(sink.count() == 4);\n\n        sink.reset();\n\n        sink.threshold(kDebug);\n\n        j.trace() << \" \";\n        BEAST_EXPECT(sink.count() == 0);\n        j.debug() << \" \";\n        BEAST_EXPECT(sink.count() == 1);\n        j.info() << \" \";\n        BEAST_EXPECT(sink.count() == 2);\n        j.warn() << \" \";\n        BEAST_EXPECT(sink.count() == 3);\n        j.error() << \" \";\n        BEAST_EXPECT(sink.count() == 4);\n        j.fatal() << \" \";\n        BEAST_EXPECT(sink.count() == 5);\n    }\n};\n\nBEAST_DEFINE_TESTSUITE(Journal, utility, beast);\n\n}  \/\/ namespace beast\n","avg_line_length":27.3980582524,"max_line_length":80,"alphanum_fraction":0.5290574061,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":9582,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":120.0,"content":"\/*\nBullet Continuous Collision Detection and Physics Library\nCopyright (c) 2003-2006 Erwin Coumans  http:\/\/continuousphysics.com\/Bullet\/\n\nThis software is provided 'as-is', without any express or implied warranty.\nIn no event will the authors be held liable for any damages arising from the use of this software.\nPermission is granted to anyone to use this software for any purpose, \nincluding commercial applications, and to alter it and redistribute it freely, \nsubject to the following restrictions:\n\n1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.\n2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.\n3. This notice may not be removed or altered from any source distribution.\n*\/\n\n#include \"btSimpleBroadphase.h\"\n#include \"bullet\/BulletCollision\/\/BroadphaseCollision\/btDispatcher.h\"\n#include \"bullet\/BulletCollision\/\/BroadphaseCollision\/btCollisionAlgorithm.h\"\n\n#include \"bullet\/LinearMath\/btVector3.h\"\n#include \"bullet\/LinearMath\/btTransform.h\"\n#include \"bullet\/LinearMath\/btMatrix3x3.h\"\n#include \"bullet\/LinearMath\/btAabbUtil2.h\"\n\n#include <new>\n\nextern int gOverlappingPairs;\n\nvoid\tbtSimpleBroadphase::validate()\n{\n\tfor (int i=0;i<m_numHandles;i++)\n\t{\n\t\tfor (int j=i+1;j<m_numHandles;j++)\n\t\t{\n\t\t\tbtAssert(&m_pHandles[i] != &m_pHandles[j]);\n\t\t}\n\t}\n\t\n}\n\nbtSimpleBroadphase::btSimpleBroadphase(int maxProxies, btOverlappingPairCache* overlappingPairCache)\n\t:m_pairCache(overlappingPairCache),\n\tm_ownsPairCache(false),\n\tm_invalidPair(0)\n{\n\n\tif (!overlappingPairCache)\n\t{\n\t\tvoid* mem = btAlignedAlloc(sizeof(btHashedOverlappingPairCache),16);\n\t\tm_pairCache = new (mem)btHashedOverlappingPairCache();\n\t\tm_ownsPairCache = true;\n\t}\n\n\t\/\/ allocate handles buffer and put all handles on free list\n\tm_pHandlesRawPtr = btAlignedAlloc(sizeof(btSimpleBroadphaseProxy)*maxProxies,16);\n\tm_pHandles = new(m_pHandlesRawPtr) btSimpleBroadphaseProxy[maxProxies];\n\tm_maxHandles = maxProxies;\n\tm_numHandles = 0;\n\tm_firstFreeHandle = 0;\n\tm_LastHandleIndex = -1;\n\t\n\n\t{\n\t\tfor (int i = m_firstFreeHandle; i < maxProxies; i++)\n\t\t{\n\t\t\tm_pHandles[i].SetNextFree(i + 1);\n\t\t\tm_pHandles[i].m_uniqueId = i+2;\/\/any UID will do, we just avoid too trivial values (0,1) for debugging purposes\n\t\t}\n\t\tm_pHandles[maxProxies - 1].SetNextFree(0);\n\t\n\t}\n\n}\n\nbtSimpleBroadphase::~btSimpleBroadphase()\n{\n\tbtAlignedFree(m_pHandlesRawPtr);\n\n\tif (m_ownsPairCache)\n\t{\n\t\tm_pairCache->~btOverlappingPairCache();\n\t\tbtAlignedFree(m_pairCache);\n\t}\n}\n\n\nbtBroadphaseProxy*\tbtSimpleBroadphase::createProxy(  const btVector3& aabbMin,  const btVector3& aabbMax,int shapeType,void* userPtr ,short int collisionFilterGroup,short int collisionFilterMask, btDispatcher* \/*dispatcher*\/,void* multiSapProxy)\n{\n\tif (m_numHandles >= m_maxHandles)\n\t{\n\t\tbtAssert(0);\n\t\treturn 0; \/\/should never happen, but don't let the game crash ;-)\n\t}\n\tbtAssert(aabbMin[0]<= aabbMax[0] && aabbMin[1]<= aabbMax[1] && aabbMin[2]<= aabbMax[2]);\n\n\tint newHandleIndex = allocHandle();\n\tbtSimpleBroadphaseProxy* proxy = new (&m_pHandles[newHandleIndex])btSimpleBroadphaseProxy(aabbMin,aabbMax,shapeType,userPtr,collisionFilterGroup,collisionFilterMask,multiSapProxy);\n\n\treturn proxy;\n}\n\nclass\tRemovingOverlapCallback : public btOverlapCallback\n{\nprotected:\n\tvirtual bool\tprocessOverlap(btBroadphasePair& pair)\n\t{\n\t\t(void)pair;\n\t\tbtAssert(0);\n\t\treturn false;\n\t}\n};\n\nclass RemovePairContainingProxy\n{\n\n\tbtBroadphaseProxy*\tm_targetProxy;\n\tpublic:\n\tvirtual ~RemovePairContainingProxy()\n\t{\n\t}\nprotected:\n\tvirtual bool processOverlap(btBroadphasePair& pair)\n\t{\n\t\tbtSimpleBroadphaseProxy* proxy0 = static_cast<btSimpleBroadphaseProxy*>(pair.m_pProxy0);\n\t\tbtSimpleBroadphaseProxy* proxy1 = static_cast<btSimpleBroadphaseProxy*>(pair.m_pProxy1);\n\n\t\treturn ((m_targetProxy == proxy0 || m_targetProxy == proxy1));\n\t};\n};\n\nvoid\tbtSimpleBroadphase::destroyProxy(btBroadphaseProxy* proxyOrg,btDispatcher* dispatcher)\n{\n\t\t\n\t\tbtSimpleBroadphaseProxy* proxy0 = static_cast<btSimpleBroadphaseProxy*>(proxyOrg);\n\t\tfreeHandle(proxy0);\n\n\t\tm_pairCache->removeOverlappingPairsContainingProxy(proxyOrg,dispatcher);\n\n\t\t\/\/validate();\n\t\t\n}\n\nvoid\tbtSimpleBroadphase::getAabb(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const\n{\n\tconst btSimpleBroadphaseProxy* sbp = getSimpleProxyFromProxy(proxy);\n\taabbMin = sbp->m_aabbMin;\n\taabbMax = sbp->m_aabbMax;\n}\n\nvoid\tbtSimpleBroadphase::setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax, btDispatcher* \/*dispatcher*\/)\n{\n\tbtSimpleBroadphaseProxy* sbp = getSimpleProxyFromProxy(proxy);\n\tsbp->m_aabbMin = aabbMin;\n\tsbp->m_aabbMax = aabbMax;\n}\n\nvoid\tbtSimpleBroadphase::rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin,const btVector3& aabbMax)\n{\n\tfor (int i=0; i <= m_LastHandleIndex; i++)\n\t{\n\t\tbtSimpleBroadphaseProxy* proxy = &m_pHandles[i];\n\t\tif(!proxy->m_clientObject)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\trayCallback.process(proxy);\n\t}\n}\n\n\nvoid\tbtSimpleBroadphase::aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback)\n{\n\tfor (int i=0; i <= m_LastHandleIndex; i++)\n\t{\n\t\tbtSimpleBroadphaseProxy* proxy = &m_pHandles[i];\n\t\tif(!proxy->m_clientObject)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif (TestAabbAgainstAabb2(aabbMin,aabbMax,proxy->m_aabbMin,proxy->m_aabbMax))\n\t\t{\n\t\t\tcallback.process(proxy);\n\t\t}\n\t}\n}\n\n\n\n\t\n\n\n\nbool\tbtSimpleBroadphase::aabbOverlap(btSimpleBroadphaseProxy* proxy0,btSimpleBroadphaseProxy* proxy1)\n{\n\treturn proxy0->m_aabbMin[0] <= proxy1->m_aabbMax[0] && proxy1->m_aabbMin[0] <= proxy0->m_aabbMax[0] && \n\t\t   proxy0->m_aabbMin[1] <= proxy1->m_aabbMax[1] && proxy1->m_aabbMin[1] <= proxy0->m_aabbMax[1] &&\n\t\t   proxy0->m_aabbMin[2] <= proxy1->m_aabbMax[2] && proxy1->m_aabbMin[2] <= proxy0->m_aabbMax[2];\n\n}\n\n\n\n\/\/then remove non-overlapping ones\nclass CheckOverlapCallback : public btOverlapCallback\n{\npublic:\n\tvirtual bool processOverlap(btBroadphasePair& pair)\n\t{\n\t\treturn (!btSimpleBroadphase::aabbOverlap(static_cast<btSimpleBroadphaseProxy*>(pair.m_pProxy0),static_cast<btSimpleBroadphaseProxy*>(pair.m_pProxy1)));\n\t}\n};\n\nvoid\tbtSimpleBroadphase::calculateOverlappingPairs(btDispatcher* dispatcher)\n{\n\t\/\/first check for new overlapping pairs\n\tint i,j;\n\tif (m_numHandles >= 0)\n\t{\n\t\tint new_largest_index = -1;\n\t\tfor (i=0; i <= m_LastHandleIndex; i++)\n\t\t{\n\t\t\tbtSimpleBroadphaseProxy* proxy0 = &m_pHandles[i];\n\t\t\tif(!proxy0->m_clientObject)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tnew_largest_index = i;\n\t\t\tfor (j=i+1; j <= m_LastHandleIndex; j++)\n\t\t\t{\n\t\t\t\tbtSimpleBroadphaseProxy* proxy1 = &m_pHandles[j];\n\t\t\t\tbtAssert(proxy0 != proxy1);\n\t\t\t\tif(!proxy1->m_clientObject)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tbtSimpleBroadphaseProxy* p0 = getSimpleProxyFromProxy(proxy0);\n\t\t\t\tbtSimpleBroadphaseProxy* p1 = getSimpleProxyFromProxy(proxy1);\n\n\t\t\t\tif (aabbOverlap(p0,p1))\n\t\t\t\t{\n\t\t\t\t\tif ( !m_pairCache->findPair(proxy0,proxy1))\n\t\t\t\t\t{\n\t\t\t\t\t\tm_pairCache->addOverlappingPair(proxy0,proxy1);\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tif (!m_pairCache->hasDeferredRemoval())\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( m_pairCache->findPair(proxy0,proxy1))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_pairCache->removeOverlappingPair(proxy0,proxy1,dispatcher);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tm_LastHandleIndex = new_largest_index;\n\n\t\tif (m_ownsPairCache && m_pairCache->hasDeferredRemoval())\n\t\t{\n\n\t\t\tbtBroadphasePairArray&\toverlappingPairArray = m_pairCache->getOverlappingPairArray();\n\n\t\t\t\/\/perform a sort, to find duplicates and to sort 'invalid' pairs to the end\n\t\t\toverlappingPairArray.quickSort(btBroadphasePairSortPredicate());\n\n\t\t\toverlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair);\n\t\t\tm_invalidPair = 0;\n\n\n\t\t\tbtBroadphasePair previousPair;\n\t\t\tpreviousPair.m_pProxy0 = 0;\n\t\t\tpreviousPair.m_pProxy1 = 0;\n\t\t\tpreviousPair.m_algorithm = 0;\n\n\n\t\t\tfor (i=0;i<overlappingPairArray.size();i++)\n\t\t\t{\n\n\t\t\t\tbtBroadphasePair& pair = overlappingPairArray[i];\n\n\t\t\t\tbool isDuplicate = (pair == previousPair);\n\n\t\t\t\tpreviousPair = pair;\n\n\t\t\t\tbool needsRemoval = false;\n\n\t\t\t\tif (!isDuplicate)\n\t\t\t\t{\n\t\t\t\t\tbool hasOverlap = testAabbOverlap(pair.m_pProxy0,pair.m_pProxy1);\n\n\t\t\t\t\tif (hasOverlap)\n\t\t\t\t\t{\n\t\t\t\t\t\tneedsRemoval = false;\/\/callback->processOverlap(pair);\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tneedsRemoval = true;\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\t\/\/remove duplicate\n\t\t\t\t\tneedsRemoval = true;\n\t\t\t\t\t\/\/should have no algorithm\n\t\t\t\t\tbtAssert(!pair.m_algorithm);\n\t\t\t\t}\n\n\t\t\t\tif (needsRemoval)\n\t\t\t\t{\n\t\t\t\t\tm_pairCache->cleanOverlappingPair(pair,dispatcher);\n\n\t\t\t\t\t\/\/\t\tm_overlappingPairArray.swap(i,m_overlappingPairArray.size()-1);\n\t\t\t\t\t\/\/\t\tm_overlappingPairArray.pop_back();\n\t\t\t\t\tpair.m_pProxy0 = 0;\n\t\t\t\t\tpair.m_pProxy1 = 0;\n\t\t\t\t\tm_invalidPair++;\n\t\t\t\t\tgOverlappingPairs--;\n\t\t\t\t} \n\n\t\t\t}\n\n\t\t\t\/\/\/if you don't like to skip the invalid pairs in the array, execute following code:\n#define CLEAN_INVALID_PAIRS 1\n#ifdef CLEAN_INVALID_PAIRS\n\n\t\t\t\/\/perform a sort, to sort 'invalid' pairs to the end\n\t\t\toverlappingPairArray.quickSort(btBroadphasePairSortPredicate());\n\n\t\t\toverlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair);\n\t\t\tm_invalidPair = 0;\n#endif\/\/CLEAN_INVALID_PAIRS\n\n\t\t}\n\t}\n}\n\n\nbool btSimpleBroadphase::testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1)\n{\n\tbtSimpleBroadphaseProxy* p0 = getSimpleProxyFromProxy(proxy0);\n\tbtSimpleBroadphaseProxy* p1 = getSimpleProxyFromProxy(proxy1);\n\treturn aabbOverlap(p0,p1);\n}\n\nvoid\tbtSimpleBroadphase::resetPool(btDispatcher* dispatcher)\n{\n\t\/\/not yet\n}\n","avg_line_length":27.3771428571,"max_line_length":245,"alphanum_fraction":0.7396159466,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":208,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"int main() {\n\n\t\/\/ lvalue appears on LHS\n\tint a = 0;\n\t\n\t\/\/ address of lvalue can be stored in pointer\n\tint* a_ptr = &a;\n\n\t\/\/ lvalue can bind to lvalue references\n\tint& a_ref = a; \n\n\t\/\/ e.g. of lvalues\n\ta;\n\t\n}\n","avg_line_length":13.0,"max_line_length":46,"alphanum_fraction":0.6057692308,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11782,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"bincheck.h\"\n#include \"buttons.h\"\n#include <QToolButton>\n#include <QMessageBox>\n#include <QFileDialog>\n#include <QString>\n#include <QStringList>\n#include <QDir>\n#include <QDate>\n#include <QDataStream>\n#include <QVector>\n\nMainWindow::MainWindow(QWidget *parent) :\n\tQMainWindow(parent),\n\tui(new Ui::MainWindow)\n{\n\tui->setupUi(this);\n\tui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);\n\tui->tableWidget->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Stretch);\n\tui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);\n\tdelIcon=QIcon(\":\/pics\/delete.jpg\");\n\taddIcon=QIcon(\":\/pics\/add.jpg\");\n\tauto button=new QToolButton();\n\tbutton->setIcon(addIcon);\n\tui->tableWidget->setCellWidget(0,5,button);\n\tconnect(button,&QAbstractButton::clicked,this,&MainWindow::_addRow);\n\tcurPath=QDir::currentPath();\n\tui->curDir->setText(curPath);\n\tif(!readLog()){\n\t\taddRow(false,\"clk\");\n\t}\n}\n\nMainWindow::~MainWindow(){\n\tsaveLog();\n\tdelete ui;\n}\n\nvoid MainWindow::_addRow(){\n\taddRow();\n}\n\nint MainWindow::buttonStat(int row, int col){\n\treturn static_cast<BinCheck*>(ui->tableWidget->cellWidget(row,col))->get();\n}\n\nQTableWidget *MainWindow::table(){\n\treturn ui->tableWidget;\n}\n\nvoid MainWindow::addRow(bool useLast, const QString &name, int io, int wire, int sign, const QString &lenm1){\n\tint row=ui->tableWidget->rowCount()-1;\n\tui->tableWidget->insertRow(row);\n\n\tBinCheck* check;\n\tint stat;\n\tcheck=new BinCheck(\"in\",\"out\",true);\n\tui->tableWidget->setCellWidget(row,1,check);\n\tif(row>0&&useLast)\n\t\tstat=buttonStat(row-1,1);\n\telse\n\t\tstat=io;\n\n\tif(stat>=0)\n\t\tcheck->set(stat>0);\n\telse\n\t\tcheck->reset();\n\n\tcheck=new BinCheck(\"wire\",\"reg\");\n\tui->tableWidget->setCellWidget(row,2,check);\n\tstat=(row>0&&useLast)?buttonStat(row-1,2):wire;\n\tcheck->set(stat>0);\n\n\tcheck=new BinCheck(\"uns\",\"sign\");\n\tui->tableWidget->setCellWidget(row,3,check);\n\tstat=(row>0&&useLast)?buttonStat(row-1,3):sign;\n\tcheck->set(stat>0);\n\n\ttable()->setItem(row,0,new QTableWidgetItem(name));\n\ttable()->setItem(row,4,new QTableWidgetItem(lenm1));\n\n\tDelButton* button=new DelButton(delIcon,\n\t\t\t\t\t\t\t\t\ttable()->item(row,4),table());\n\tui->tableWidget->setCellWidget(row,5,button);\n\n\t\/\/ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);\n}\n\nvoid MainWindow::on_toolButton_clicked(){\n\tQString path=QDir::toNativeSeparators(\n\t\tQFileDialog::getExistingDirectory(this,tr(\"Directory to save\"),\n\t\tui->curDir->text()));\n\tui->curDir->setText(path);\n}\n\nbool MainWindow::openFile(const QString& fileName){\n\tf.setFileName(fileName);\n\tif(!f.open(QIODevice::WriteOnly|QIODevice::Text)){\n\t\tQString str=\"During opening of\\n\";\n\t\tstr+=fileName;\n\t\tstr+=\"\\nAn error occured:\\n\";\n\t\tstr+=f.errorString();\n\t\tstr+=\"\\nPlease try again.\";\n\t\tQMessageBox::critical(this,\"Error\",str);\n\t\treturn false;\n\t}\n\ts.setDevice(&f);\n\treturn true;\n}\n\nvoid MainWindow::closeFile(){\n\ts.setDevice(nullptr);\n\tf.close();\n}\n\nvoid MainWindow::printIO(bool &p, const QString &name, const QString &pad){\n\tif(p){\n\t\ts<<','<<endl<<pad<<name;\n\t}else{\n\t\tp=true;\n\t\ts<<name;\n\t}\n\n}\n\nbool MainWindow::readLog(){\n\tQDir::setCurrent(curPath);\n\tf.setFileName(\"log.dat\");\n\tif(!f.open(QIODevice::ReadOnly))\n\t\treturn false;\n\tQDataStream d(&f);\n\tint j;\n\tQStringList l;\n\tQVector<myPair> ll;\n\td>>j>>l>>ll;\n\tif(d.status()!=QDataStream::Ok)\n\t\treturn false;\n\tif(l.length()!=7)\n\t\treturn false;\n\tif(j>=8||j<0)\n\t\treturn false;\n\tfor(auto it:ll){\n\t\tif(it.first.second<-1||it.first.second>1)\n\t\t\treturn false;\n\t\tif(it.second.first<0||it.second.first>3)\n\t\t\treturn  false;\n\t}\n\tui->fileName->setText(l[0]);\n\tui->moduleName->setText(l[1]);\n\tui->curDir->setText(l[2]);\n\tui->function->setText(l[3]);\n\tui->func_tb->setText(l[4]);\n\tui->version->setText(l[5]);\n\tui->author->setText(l[6]);\n\tui->createFolder->setChecked(j&1);\n\tj>>=1;\n\tui->doFile->setChecked(j&1);\n\tj>>=1;\n\tui->testbench->setCurrentIndex(j);\n\tfor(auto it:ll){\n\t\taddRow(false,\n\t\t\t   it.first.first,\n\t\t\t   it.first.second,\n\t\t\t   it.second.first>>1,\n\t\t\t   it.second.first&1,\n\t\t\t   it.second.second);\n\t}\n\td.setDevice(nullptr);\n\tf.close();\n\treturn true;\n}\n\nvoid MainWindow::saveLog(){\n\tQDir::setCurrent(curPath);\n\tf.setFileName(\"log.dat\");\n\tif(!f.open(QIODevice::WriteOnly)){\n\t\tfprintf(stderr,\"Error: can't write to log\\n\");\n\t\tfprintf(stderr,f.errorString().toStdString().c_str());\n\t\tfflush(stderr);\n\t\treturn;\n\t}\n\tQDataStream d(&f);\n\tQStringList l;\n\tl.append(ui->fileName->text());\n\tl.append(ui->moduleName->text());\n\tl.append(ui->curDir->text());\n\tl.append(ui->function->text());\n\tl.append(ui->func_tb->text());\n\tl.append(ui->version->text());\n\tl.append(ui->author->text());\n\tint j=ui->testbench->currentIndex()*4;\n\tj+=ui->doFile->isChecked()*2;\n\tj+=ui->createFolder->isChecked();\n\tQVector<myPair> ll;\n\tfor(int i=0;i<table()->rowCount()-1;++i){\n\t\tll.append(myPair(\n\t\t\tpair1(\n\t\t\t\ttable()->item(i,0)->text(),\n\t\t\t\tbuttonStat(i,1)),\n\t\t\tpair2(\n\t\t\t\tbuttonStat(i,2)*2+buttonStat(i,3),\n\t\t\t\ttable()->item(i,4)->text())));\n\t}\n\td<<j<<l<<ll;\n\td.setDevice(nullptr);\n\tf.close();\n}\n\nvoid MainWindow::on_pushButton_clicked(){\n\tQString prefix=ui->curDir->text(),file,tbFile,doFile;\n\tQString module,module_tb,date,func,str;\n\tQDir dir(prefix);\n\tQStringList list,input,ouput,intra;\n\tQStringList inpre,oupre,intpre;\n\n\tint maxl=29,maxn=0;\n\tbool p=false;\n\n\tfile=ui->fileName->text();\n\tmodule=ui->moduleName->text();\n\tif(file.isEmpty()){\n\t\tstr=\"File name can't be empty!\";\n\t\tQMessageBox::critical(this,\"Error\",str);\n\t\treturn;\n\t}\n\tif(module.isEmpty()){\n\t\tstr=\"Module name can't be empty!\";\n\t\tQMessageBox::critical(this,\"Error\",str);\n\t\treturn;\n\t}\n\tif(ui->createFolder->isChecked()){\n\t\tdir.setPath(dir.filePath(file));\n\t\tif(!dir.exists()){\n\t\t\tdir.setPath(prefix);\n\t\t\tif(!(dir.mkdir(file)&&dir.cd(file))){\n\t\t\t\tstr=\"Can't create the directory!\";\n\t\t\t\tQMessageBox::critical(this,\"Error\",str);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\tfile+=\".v\";\n\n\tif(ui->testbench->currentText()==\"tb_*\"){\n\t\ttbFile=\"tb_\"+ui->fileName->text()+\".v\";\n\t\tmodule_tb=\"tb_\"+module;\n\t}else{\n\t\ttbFile=ui->fileName->text()+\"_tb.v\";\n\t\tmodule_tb=module+\"_tb\";\n\t}\n\n\tif(dir.exists(file)){\n\t\tlist.append(file);\n\t}\n\tif(dir.exists(tbFile)){\n\t\tlist.append(tbFile);\n\t}\n\n\tif(ui->doFile->isChecked()){\n\t\tdoFile=ui->fileName->text()+\".do\";\n\t\tif(dir.exists(doFile)){\n\t\t\tlist.append(doFile);\n\t\t}\n\t}\n\tif(!list.empty()){\n\t\tstr=\"The following files:\\n\";\n\t\tstr+=list.join('\\n');\n\t\tstr+=\"\\nwill be overwritten. Continue?\";\n\t\tswitch(QMessageBox::question(this,\"Overwrite\",str)){\n\t\tcase QMessageBox::Yes:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif(!QDir::setCurrent(dir.path())){\n\t\tstr=\"Can't change to directory\\n\";\n\t\tstr+=dir.path();\n\t\tstr+=\"\\nPlease try again or reselect the dir.\";\n\t\tQMessageBox::critical(this,\"Error\",str);\n\t\treturn;\n\t}\n\n\tif(!openFile(file)){\n\t\tcloseFile();\n\t\treturn;\n\t}\n\n\tdate=QDate::currentDate().toString(\"yyyy-MM-dd\");\n\ts<<\"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\"<<endl;\n\ts<<\"\/\/module name: \"<<module<<endl;\n\tfunc=ui->function->text();\n\tstr=(func.isEmpty())?\"Implementation of module \"+module:func;\n\ts<<\"\/\/function: \"<<str<<endl;\n\ts<<\"\/\/time: \"<<date<<endl;\n\ts<<\"\/\/author: \"<<ui->author->text()<<endl;\n\ts<<\"\/\/version: \"<<ui->version->text()<<endl;\n\ts<<\"\/\/mark of revision:\"<<endl;\n\ts<<\"\/\/build-\"<<date<<endl;\n\ts<<\"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\"<<endl;\n\ts<<endl;\n\n\/\/ Process table here.......................\n\n\tfor(int i=0;i<table()->rowCount()-1;++i){\n\t\t\/\/ prefix not used\n\t\tprefix=\"\";\n\t\tQString name;\n\t\tswitch(buttonStat(i,1)){\n\t\tcase 1:\n\t\t\tprefix+=\"output \";\n\t\t\tname=module+\"_ouput_\";\n\t\t\tbreak;\n\t\tcase 0:\n\t\t\tprefix+=\"input  \";\n\t\t\tname=module+\"_input_\";\n\t\t\tbreak;\n\t\t\/\/case -1:\n\t\tdefault:\n\t\t\tprefix+=\"       \";\n\t\t\tname=\"\";\n\t\t\tbreak;\n\t\t}\n\t\tstr=table()->item(i,0)->text();\n\t\tif(str.isEmpty())\n\t\t\tname+=QString::number(i);\n\t\telse\n\t\t\tname+=str;\n\n\t\tswitch(buttonStat(i,2)){\n\t\tcase 1:\n\t\t\tprefix+=\"reg  \";\n\t\t\tbreak;\n\t\t\/\/case 0:\n\t\tdefault:\n\t\t\tprefix+=(buttonStat(i,1)>=0)?\"     \"\n\t\t\t\t\t\t\t\t\t\t:\"wire \";\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch(buttonStat(i,3)){\n\t\tcase 1:\n\t\t\tprefix+=\"signed \";\n\t\t\tbreak;\n\t\t\/\/case 0:\n\t\tdefault:\n\t\t\tprefix+=\"       \";\n\t\t\tbreak;\n\t\t}\n\n\t\tstr=table()->item(i,4)->text();\n\t\tif(str.isEmpty()){\n\t\t\t\/\/prefix+=\"\";\n\t\t}else{\n\t\t\tprefix+='['+str+\":0] \";\n\t\t}\n\n\t\tif(prefix.length()>maxl)\n\t\t\tmaxl=prefix.length();\n\n\t\tswitch(buttonStat(i,1)){\n\t\tcase 1:\n\t\t\touput.append(name);\n\t\t\toupre.append(prefix);\n\t\t\tif(name.length()>maxn)\n\t\t\t\tmaxn=name.length();\n\t\t\tbreak;\n\t\tcase 0:\n\t\t\tinput.append(name);\n\t\t\tinpre.append(prefix);\n\t\t\tif(name.length()>maxn)\n\t\t\t\tmaxn=name.length();\n\t\t\tbreak;\n\t\t\/\/case -1:\n\t\tdefault:\n\t\t\tintra.append(name);\n\t\t\tintpre.append(prefix);\n\t\t\tbreak;\n\t\t}\n\t}\n\t++maxn;\n\tfor(QString& st: inpre){\n\t\tint diff=maxl-st.length();\n\t\tif(diff>0)\n\t\t\tst+=QString(diff,' ');\n\t}\n\tfor(QString& st: oupre){\n\t\tint diff=maxl-st.length();\n\t\tif(diff>0)\n\t\t\tst+=QString(diff,' ');\n\t}\n\n\tfor(QString& st: intpre){\n\t\tint diff=maxl-st.length();\n\t\tif(diff>0)\n\t\t\tst+=QString(diff,' ');\n\t}\n\n\/\/ Continue.......................\n\n\tstr=\"module \"+module+\" (\";\n\ts<<str;\n\tstr=QString(str.length(),' ');\n\tfor(QString& st: input){\n\t\tprintIO(p,st,str);\n\t}\n\tfor(QString& st: ouput){\n\t\tprintIO(p,st,str);\n\t}\n\ts<<\");\"<<endl;\n\ts<<'\\t'<<endl;\n\n\tfor(int i=0;i<input.length();++i){\n\t\ts<<'\\t'<<inpre[i]<<input[i]<<';'<<endl;\n\t}\n\tfor(int i=0;i<ouput.length();++i){\n\t\ts<<'\\t'<<oupre[i]<<ouput[i]<<';'<<endl;\n\t}\n\ts<<'\\t'<<endl;\n\tfor(int i=0;i<intra.length();++i){\n\t\ts<<'\\t'<<intpre[i]<<intra[i]<<';'<<endl;\n\t}\n\tintra.clear();\n\tintpre.clear();\n\ts<<'\\t'<<endl;\n\ts<<'\\t'<<\"\/\/Module starts here...\"<<endl;\n\ts<<'\\t'<<endl;\n\ts<<\"endmodule\"<<endl;\n\tcloseFile();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tif(!openFile(tbFile)){\n\t\tcloseFile();\n\t\treturn;\n\t}\n\ts<<\"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\"<<endl;\n\ts<<\"\/\/module name: \"<<module_tb<<endl;\n\tfunc=ui->func_tb->text();\n\tstr=(func.isEmpty())?\"Testbench of module \"+module:func;\n\ts<<\"\/\/function: \"<<str<<endl;\n\ts<<\"\/\/time: \"<<date<<endl;\n\ts<<\"\/\/author: \"<<ui->author->text()<<endl;\n\ts<<\"\/\/version: \"<<ui->version->text()<<endl;\n\ts<<\"\/\/mark of revision:\"<<endl;\n\ts<<\"\/\/build-\"<<date<<endl;\n\ts<<\"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\"<<endl;\n\ts<<endl;\n\ts<<\"`timescale 1ps\/1ps\"<<endl;\n\ts<<endl;\n\ts<<\"module \"<<module_tb<<\"();\"<<endl;\n\ts<<'\\t'<<endl;\n\tfor(int i=0;i<input.length();++i){\n\t\ts<<\"\\treg  \"<<inpre[i].remove(0,12);\n\t\tinpre[i]=input[i];\n\t\tinput[i].remove(0,module.length()+1);\n\t\ts<<input[i].remove(2,3)<<';'<<endl;\n\t}\n\tfor(int i=0;i<ouput.length();++i){\n\t\ts<<\"\\twire \"<<oupre[i].remove(0,12);\n\t\toupre[i]=ouput[i];\n\t\touput[i].remove(0,module.length()+1);\n\t\ts<<ouput[i].remove(2,3)<<';'<<endl;\n\t}\n\ts<<'\\t'<<endl;\n\n\tinpre+=oupre;\n\toupre.clear();\n\tinput+=ouput;\n\touput.clear();\n\tp=false;\n\n\ts<<'\\t'<<module<<' '<<module<<\"0(\";\n\tfor(int i=0;i<input.length();++i){\n\t\tif(p)\n\t\t\ts<<',';\n\t\telse\n\t\t\tp=true;\n\t\ts<<endl<<\"\\t\\t.\"<<inpre[i]\n\t\t <<QString(maxn-inpre[i].length(),' ')\n\t\t <<'('<<input[i]<<')';\n\t}\n\ts<<\");\"<<endl;\n\ts<<'\\t'<<endl;\n\ts<<'\\t'<<\"\/\/Module starts here... example below:\"<<endl;\n\ts<<'\\t'<<\"initial begin\"<<endl;\n\ts<<\"\\t\\t\"<<\"in_clk<=1'b0;\"<<endl;\n\ts<<\"\\t\\t\"<<\"in_rst<=1'b0;\"<<endl;\n\ts<<\"\\t\\t\"<<\"#10;\"<<endl;\n\ts<<\"\\t\\t\"<<\"in_rst<=1'b1;\"<<endl;\n\ts<<\"\\t\\t\"<<\"forever begin\"<<endl;\n\ts<<\"\\t\\t\\t\"<<\"#10; in_clk<=~in_clk;\"<<endl;\n\ts<<\"\\t\\t\"<<\"end\"<<endl;\n\ts<<'\\t'<<\"end\"<<endl;\n\ts<<'\\t'<<endl;\n\ts<<\"endmodule\"<<endl;\n\tcloseFile();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tif(!doFile.isEmpty()){\n\t\tif(!openFile(doFile)){\n\t\t\tcloseFile();\n\t\t\treturn;\n\t\t}\n\t\ts<<\"vlog -work work -stats=none \"<<file<<endl;\n\t\ts<<\"vlog -work work -stats=none \"<<tbFile<<endl;\n\t\ts<<\"vsim -gui work.\"<<module_tb<<endl;\n\t\ts<<\"add wave sim:\/\"<<module_tb<<\"\/*\"<<endl;\n\t\ts<<\"run -all\"<<endl;\n\t\tcloseFile();\n\t}\n\tsaveLog();\n\tstr=\"Successfully generated the following files:\";\n\tstr+='\\n'+file;\n\tstr+='\\n'+tbFile;\n\tif(!doFile.isEmpty())\n\t\tstr+='\\n'+doFile;\n\tQMessageBox::information(this,\"Success\",str);\n}\n","avg_line_length":22.4847328244,"max_line_length":109,"alphanum_fraction":0.6052452894,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4430,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":3680.0,"content":"\/\/\n\/\/ Copyright 2016 Pixar\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"Apache License\")\n\/\/ with the following modification; you may not use this file except in\n\/\/ compliance with the Apache License and the following modification to it:\n\/\/ Section 6. Trademarks. is deleted and replaced with:\n\/\/\n\/\/ 6. Trademarks. This License does not grant permission to use the trade\n\/\/    names, trademarks, service marks, or product names of the Licensor\n\/\/    and its affiliates, except as required to comply with Section 4(c) of\n\/\/    the License and to reproduce the content of the NOTICE file.\n\/\/\n\/\/ You may obtain a copy of the Apache License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the Apache License with the above modification is\n\/\/ distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the Apache License for the specific\n\/\/ language governing permissions and limitations under the Apache License.\n\/\/\n\n#include \"pxr\/pxr.h\"\n#include \"pxr\/usd\/sdf\/reference.h\"\n#include \"pxr\/base\/tf\/pyContainerConversions.h\"\n#include \"pxr\/base\/tf\/pyUtils.h\"\n\n#include <boost\/python.hpp>\n#include <boost\/function.hpp>\n\n#include <string>\n\nusing namespace boost::python;\nusing std::string;\n\nPXR_NAMESPACE_USING_DIRECTIVE\n\nnamespace {\n\nstatic string\n_Repr(const SdfReference &self)\n{\n    string args;\n    bool useKeywordArgs = false;\n\n    if (!self.GetAssetPath().empty()) {\n        args += TfPyRepr(self.GetAssetPath());\n    } else {\n        useKeywordArgs = true;\n    }\n    if (!self.GetPrimPath().IsEmpty()) {\n        args += (args.empty() ? \"\": \", \");\n        args += (useKeywordArgs ? \"primPath=\" : \"\") +\n            TfPyRepr(self.GetPrimPath());\n    } else {\n        useKeywordArgs = true;\n    }\n    if (!self.GetLayerOffset().IsIdentity()) {\n        args += (args.empty() ? \"\": \", \");\n        args += (useKeywordArgs ? \"layerOffset=\" : \"\") +\n            TfPyRepr(self.GetLayerOffset());\n    } else {\n        useKeywordArgs = true;\n    }\n    \/\/ Always use keyword args for custom data (for readability).\n    if (!self.GetCustomData().empty()) {\n        args += (args.empty() ? \"\": \", \");\n        args += \"customData=\" + TfPyRepr(self.GetCustomData());\n    }\n\n    return TF_PY_REPR_PREFIX + \"Reference(\" + args + \")\";\n}\n\n} \/\/ anonymous namespace \n\nvoid wrapReference()\n{    \n    using This = SdfReference;\n\n    \/\/ Register conversion for python list <-> vector<SdfReference>\n    to_python_converter<\n        SdfReferenceVector,\n        TfPySequenceToPython<SdfReferenceVector> >();\n    TfPyContainerConversions::from_python_sequence<\n        SdfReferenceVector,\n        TfPyContainerConversions::variable_capacity_policy >();\n\n    \/\/ Note: Since we have no proxy for Sdf.Reference we wrap it as an\n    \/\/       immutable type to avoid confusion about code like this\n    \/\/       prim.referenceList.explicitItems[0].assetPath = '\/\/menv30\/test.menva'\n    \/\/       This looks like it's updating the assetPath for the prim's\n    \/\/       first explicit reference, but would instead modify a temporary\n    \/\/       Sdf.Reference object.\n\n    class_<This>( \"Reference\" )\n        .def(init<const string &,\n                  const SdfPath &,\n                  const SdfLayerOffset &,\n                  const VtDictionary &>(\n            ( arg(\"assetPath\") = string(),\n              arg(\"primPath\") = SdfPath(),\n              arg(\"layerOffset\") = SdfLayerOffset(),\n              arg(\"customData\") = VtDictionary(0) ) ) )\n        .def(init<const This &>())\n\n        .add_property(\"assetPath\",\n            make_function(\n                &This::GetAssetPath, return_value_policy<return_by_value>()))\n        .add_property(\"primPath\",\n            make_function(\n                &This::GetPrimPath, return_value_policy<return_by_value>()))\n        .add_property(\"layerOffset\",\n            make_function(\n                &This::GetLayerOffset, return_value_policy<return_by_value>()))\n        .add_property(\"customData\",\n            make_function(\n                &This::GetCustomData, return_value_policy<return_by_value>()))\n\n        .def(\"IsInternal\", &This::IsInternal)\n\n        .def(self == self)\n        .def(self != self)\n        .def(self < self)\n        .def(self > self)\n        .def(self <= self)\n        .def(self >= self)\n\n        .def(\"__repr__\", _Repr)\n\n        ;\n\n}\n","avg_line_length":32.8148148148,"max_line_length":82,"alphanum_fraction":0.6266365688,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3607,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/=================================================================================================\n\/*!\n\/\/  \\file src\/mathtest\/dmatdmatadd\/U3x3bU3x3b.cpp\n\/\/  \\brief Source file for the U3x3bU3x3b dense matrix\/dense matrix addition math test\n\/\/\n\/\/  Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved\n\/\/\n\/\/  This file is part of the Blaze library. You can redistribute it and\/or modify it under\n\/\/  the terms of the New (Revised) BSD License. Redistribution and use in source and binary\n\/\/  forms, with or without modification, are permitted provided that the following conditions\n\/\/  are met:\n\/\/\n\/\/  1. Redistributions of source code must retain the above copyright notice, this list of\n\/\/     conditions and the following disclaimer.\n\/\/  2. Redistributions in binary form must reproduce the above copyright notice, this list\n\/\/     of conditions and the following disclaimer in the documentation and\/or other materials\n\/\/     provided with the distribution.\n\/\/  3. Neither the names of the Blaze development group nor the names of its contributors\n\/\/     may be used to endorse or promote products derived from this software without specific\n\/\/     prior written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n\/\/  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\/\/  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\n\/\/  SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n\/\/  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n\/\/  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/  DAMAGE.\n*\/\n\/\/=================================================================================================\n\n\n\/\/*************************************************************************************************\n\/\/ Includes\n\/\/*************************************************************************************************\n\n#include <cstdlib>\n#include <iostream>\n#include <blaze\/math\/StaticMatrix.h>\n#include <blaze\/math\/UpperMatrix.h>\n#include <blazetest\/mathtest\/Creator.h>\n#include <blazetest\/mathtest\/dmatdmatadd\/OperationTest.h>\n#include <blazetest\/system\/MathTest.h>\n\n\n\/\/=================================================================================================\n\/\/\n\/\/  MAIN FUNCTION\n\/\/\n\/\/=================================================================================================\n\n\/\/*************************************************************************************************\nint main()\n{\n   std::cout << \"   Running 'U3x3bU3x3b'...\" << std::endl;\n\n   using blazetest::mathtest::TypeB;\n\n   try\n   {\n      \/\/ Matrix type definitions\n      typedef blaze::UpperMatrix< blaze::StaticMatrix<TypeB,3UL,3UL> >  U3x3b;\n\n      \/\/ Creator type definitions\n      typedef blazetest::Creator<U3x3b>  CU3x3b;\n\n      \/\/ Running the tests\n      RUN_DMATDMATADD_OPERATION_TEST( CU3x3b(), CU3x3b() );\n   }\n   catch( std::exception& ex ) {\n      std::cerr << \"\\n\\n ERROR DETECTED during dense matrix\/dense matrix addition:\\n\"\n                << ex.what() << \"\\n\";\n      return EXIT_FAILURE;\n   }\n\n   return EXIT_SUCCESS;\n}\n\/\/*************************************************************************************************\n","avg_line_length":43.987804878,"max_line_length":99,"alphanum_fraction":0.5636262822,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2592,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2015 The Stardust Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"walletmodeltransaction.h\"\n\n#include \"policy\/policy.h\"\n#include \"wallet\/wallet.h\"\n\nWalletModelTransaction::WalletModelTransaction(const QList<SendCoinsRecipient> &recipients) :\n    recipients(recipients),\n    walletTransaction(0),\n    keyChange(0),\n    fee(0)\n{\n    walletTransaction = new CWalletTx();\n}\n\nWalletModelTransaction::~WalletModelTransaction()\n{\n    delete keyChange;\n    delete walletTransaction;\n}\n\nQList<SendCoinsRecipient> WalletModelTransaction::getRecipients()\n{\n    return recipients;\n}\n\nCWalletTx *WalletModelTransaction::getTransaction()\n{\n    return walletTransaction;\n}\n\nunsigned int WalletModelTransaction::getTransactionSize()\n{\n    return (!walletTransaction ? 0 : ::GetVirtualTransactionSize(*walletTransaction));\n}\n\nCAmount WalletModelTransaction::getTransactionFee()\n{\n    return fee;\n}\n\nvoid WalletModelTransaction::setTransactionFee(const CAmount& newFee)\n{\n    fee = newFee;\n}\n\nvoid WalletModelTransaction::reassignAmounts(int nChangePosRet)\n{\n    int i = 0;\n    for (QList<SendCoinsRecipient>::iterator it = recipients.begin(); it != recipients.end(); ++it)\n    {\n        SendCoinsRecipient& rcp = (*it);\n\n        if (rcp.paymentRequest.IsInitialized())\n        {\n            CAmount subtotal = 0;\n            const payments::PaymentDetails& details = rcp.paymentRequest.getDetails();\n            for (int j = 0; j < details.outputs_size(); j++)\n            {\n                const payments::Output& out = details.outputs(j);\n                if (out.amount() <= 0) continue;\n                if (i == nChangePosRet)\n                    i++;\n                subtotal += walletTransaction->vout[i].nValue;\n                i++;\n            }\n            rcp.amount = subtotal;\n        }\n        else \/\/ normal recipient (no payment request)\n        {\n            if (i == nChangePosRet)\n                i++;\n            rcp.amount = walletTransaction->vout[i].nValue;\n            i++;\n        }\n    }\n}\n\nCAmount WalletModelTransaction::getTotalTransactionAmount()\n{\n    CAmount totalTransactionAmount = 0;\n    Q_FOREACH(const SendCoinsRecipient &rcp, recipients)\n    {\n        totalTransactionAmount += rcp.amount;\n    }\n    return totalTransactionAmount;\n}\n\nvoid WalletModelTransaction::newPossibleKeyChange(CWallet *wallet)\n{\n    keyChange = new CReserveKey(wallet);\n}\n\nCReserveKey *WalletModelTransaction::getPossibleKeyChange()\n{\n    return keyChange;\n}\n","avg_line_length":25.6633663366,"max_line_length":99,"alphanum_fraction":0.6574074074,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":12548,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0","Apache-2.0","Zlib"],"max_stars_count":null,"content":"\/\/ --------------------------------------------------------------------------\n\/\/                   OpenMS -- Open-Source Mass Spectrometry\n\/\/ --------------------------------------------------------------------------\n\/\/ Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n\/\/ ETH Zurich, and Freie Universitaet Berlin 2002-2017.\n\/\/\n\/\/ This software is released under a three-clause BSD license:\n\/\/  * Redistributions of source code must retain the above copyright\n\/\/    notice, this list of conditions and the following disclaimer.\n\/\/  * Redistributions in binary form must reproduce the above copyright\n\/\/    notice, this list of conditions and the following disclaimer in the\n\/\/    documentation and\/or other materials provided with the distribution.\n\/\/  * Neither the name of any author or any participating institution\n\/\/    may be used to endorse or promote products derived from this software\n\/\/    without specific prior written permission.\n\/\/ For a full list of authors, refer to the file AUTHORS.\n\/\/ --------------------------------------------------------------------------\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n\/\/ INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n\/\/ OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n\/\/ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n\/\/ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n\/\/ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ --------------------------------------------------------------------------\n\/\/ $Maintainer: Hannes Roest $\n\/\/ $Authors: Hannes Roest $\n\/\/ --------------------------------------------------------------------------\n\n#include <OpenMS\/FORMAT\/CachedMzML.h>\n\n#include <OpenMS\/KERNEL\/MSExperiment.h>\n#include <OpenMS\/FORMAT\/MzMLFile.h>\n\nnamespace OpenMS\n{\n\n  CachedmzML::CachedmzML()\n  {\n  }\n\n  CachedmzML::~CachedmzML()\n  {\n  }\n\n  CachedmzML& CachedmzML::operator=(const CachedmzML& rhs)\n  {\n    if (&rhs == this)\n      return *this;\n\n    spectra_index_ = rhs.spectra_index_;\n    chrom_index_ = rhs.chrom_index_;\n\n    return *this;\n  }\n\n  void CachedmzML::writeMemdump(MapType& exp, String out)\n  {\n    std::ofstream ofs(out.c_str(), std::ios::binary);\n    Size exp_size = exp.size();\n    Size chrom_size = exp.getChromatograms().size();\n    int file_identifier = CACHED_MZML_FILE_IDENTIFIER;\n    ofs.write((char*)&file_identifier, sizeof(file_identifier));\n\n    startProgress(0, exp.size() + exp.getChromatograms().size(), \"storing binary data\");\n    for (Size i = 0; i < exp.size(); i++)\n    {\n      setProgress(i);\n      writeSpectrum_(exp[i], ofs);\n    }\n\n    for (Size i = 0; i < exp.getChromatograms().size(); i++)\n    {\n      setProgress(i);\n      writeChromatogram_(exp.getChromatograms()[i], ofs);\n    }\n\n    ofs.write((char*)&exp_size, sizeof(exp_size));\n    ofs.write((char*)&chrom_size, sizeof(chrom_size));\n    ofs.close();\n    endProgress();\n  }\n\n  void CachedmzML::readMemdump(MapType& exp_reading, String filename) const\n  {\n    std::ifstream ifs(filename.c_str(), std::ios::binary);\n    if (ifs.fail())\n    {\n      throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);\n    }\n\n    Size exp_size, chrom_size;\n    Peak1D current_peak;\n\n    int file_identifier;\n    ifs.read((char*)&file_identifier, sizeof(file_identifier));\n    if (file_identifier != CACHED_MZML_FILE_IDENTIFIER)\n    {\n      throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, \n        \"File might not be a cached mzML file (wrong file magic number). Aborting!\", filename);\n    }\n\n    ifs.seekg(0, ifs.end); \/\/ set file pointer to end\n    ifs.seekg(ifs.tellg(), ifs.beg); \/\/ set file pointer to end, in forward direction\n    ifs.seekg(- static_cast<int>(sizeof(exp_size) + sizeof(chrom_size)), ifs.cur); \/\/ move two fields to the left, start reading\n    ifs.read((char*)&exp_size, sizeof(exp_size));\n    ifs.read((char*)&chrom_size, sizeof(chrom_size));\n    ifs.seekg(sizeof(file_identifier), ifs.beg); \/\/ set file pointer to beginning (after identifier), start reading\n\n    exp_reading.reserve(exp_size);\n    startProgress(0, exp_size + chrom_size, \"reading binary data\");\n    for (Size i = 0; i < exp_size; i++)\n    {\n      setProgress(i);\n      SpectrumType spectrum;\n      readSpectrum_(spectrum, ifs);\n      exp_reading.addSpectrum(spectrum);\n    }\n    std::vector<ChromatogramType> chromatograms;\n    for (Size i = 0; i < chrom_size; i++)\n    {\n      setProgress(i);\n      ChromatogramType chromatogram;\n      readChromatogram_(chromatogram, ifs);\n      chromatograms.push_back(chromatogram);\n    }\n    exp_reading.setChromatograms(chromatograms);\n\n    ifs.close();\n    endProgress();\n  }\n\n  const std::vector<std::streampos>& CachedmzML::getSpectraIndex() const\n  {\n    return spectra_index_;\n  }\n\n  const std::vector<std::streampos>& CachedmzML::getChromatogramIndex() const\n  {\n    return chrom_index_;\n  }\n\n  void CachedmzML::createMemdumpIndex(String filename)\n  {\n    std::ifstream ifs(filename.c_str(), std::ios::binary);\n    if (ifs.fail())\n    {\n      throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);\n    }\n\n    Size exp_size, chrom_size;\n    Peak1D current_peak;\n\n    ifs.seekg(0, ifs.beg); \/\/ set file pointer to beginning, start reading\n    spectra_index_.clear();\n    chrom_index_.clear();\n    int file_identifier;\n    int extra_offset = sizeof(dbl_field_) + sizeof(int_field_);\n    int chrom_offset = 0;\n\n    ifs.read((char*)&file_identifier, sizeof(file_identifier));\n    if (file_identifier != CACHED_MZML_FILE_IDENTIFIER)\n    {\n      throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, \n          \"File might not be a cached mzML file (wrong file magic number). Aborting!\", filename);\n    }\n\n    \/\/ For spectra and chromatograms go through file, read the size of the\n    \/\/ spectrum\/chromatogram and record the starting index of the element, then\n    \/\/ skip ahead to the next spectrum\/chromatogram.\n\n    ifs.seekg(0, ifs.end); \/\/ set file pointer to end\n    ifs.seekg(ifs.tellg(), ifs.beg); \/\/ set file pointer to end, in forward direction\n    ifs.seekg(- static_cast<int>(sizeof(exp_size) + sizeof(chrom_size)), ifs.cur); \/\/ move two fields to the left, start reading\n    ifs.read((char*)&exp_size, sizeof(exp_size));\n    ifs.read((char*)&chrom_size, sizeof(chrom_size));\n    ifs.seekg(sizeof(file_identifier), ifs.beg); \/\/ set file pointer to beginning (after identifier), start reading\n\n    startProgress(0, exp_size + chrom_size, \"Creating index for binary spectra\");\n    for (Size i = 0; i < exp_size; i++)\n    {\n      setProgress(i);\n\n      Size spec_size;\n      spectra_index_.push_back(ifs.tellg());\n      ifs.read((char*)&spec_size, sizeof(spec_size));\n      ifs.seekg(extra_offset + (sizeof(DatumSingleton)) * 2 * (spec_size), ifs.cur);\n    }\n\n    for (Size i = 0; i < chrom_size; i++)\n    {\n      setProgress(i);\n\n      Size ch_size;\n      chrom_index_.push_back(ifs.tellg());\n      ifs.read((char*)&ch_size, sizeof(ch_size));\n      ifs.seekg(chrom_offset + (sizeof(DatumSingleton)) * 2 * (ch_size), ifs.cur);\n    }\n\n    ifs.close();\n    endProgress();\n  }\n\n  void CachedmzML::writeMetadata(MapType exp, String out_meta, bool addCacheMetaValue)\n  {\n    \/\/ delete the actual data for all spectra and chromatograms, leave only metadata\n    \/\/ TODO : remove copy\n    std::vector<MSChromatogram > chromatograms = exp.getChromatograms(); \/\/ copy\n    for (Size i = 0; i < exp.size(); i++)\n    {\n      exp[i].clear(false);\n    }\n    for (Size i = 0; i < exp.getChromatograms().size(); i++)\n    {\n      chromatograms[i].clear(false);\n    }\n    exp.setChromatograms(chromatograms);\n\n    if (addCacheMetaValue)\n    {\n      \/\/ set dataprocessing on each spectrum\/chromatogram\n      boost::shared_ptr< DataProcessing > dp = boost::shared_ptr< DataProcessing >(new DataProcessing);\n      std::set<DataProcessing::ProcessingAction> actions;\n      actions.insert(DataProcessing::FORMAT_CONVERSION);\n      dp->setProcessingActions(actions);\n      dp->setMetaValue(\"cached_data\", \"true\");\n      for (Size i=0; i<exp.size(); ++i)\n      {\n        exp[i].getDataProcessing().push_back(dp);\n      }\n      std::vector<MSChromatogram > l_chromatograms = exp.getChromatograms();\n      for (Size i=0; i<l_chromatograms.size(); ++i)\n      {\n        l_chromatograms[i].getDataProcessing().push_back(dp);\n      }\n      exp.setChromatograms(l_chromatograms);\n    }\n\n    \/\/ store the meta data using the regular MzMLFile\n    MzMLFile().store(out_meta, exp);\n  }\n\n  void CachedmzML::readSpectrum_(Datavector& data1, Datavector& data2, std::ifstream& ifs, int& ms_level, double& rt) const\n  {\n    Size spec_size = -1;\n    ifs.read((char*)&spec_size, sizeof(spec_size));\n    ifs.read((char*)&ms_level, sizeof(ms_level));\n    ifs.read((char*)&rt, sizeof(rt));\n\n    data1.resize(spec_size);\n    data2.resize(spec_size);\n\n    if (spec_size > 0)\n    {\n      ifs.read((char*)&data1[0], spec_size * sizeof(DatumSingleton));\n      ifs.read((char*)&data2[0], spec_size * sizeof(DatumSingleton));\n    }\n  }\n\n  void CachedmzML::readChromatogram_(Datavector& data1, Datavector& data2, std::ifstream& ifs) const\n  {\n    Size spec_size = -1;\n    ifs.read((char*)&spec_size, sizeof(spec_size));\n    data1.resize(spec_size);\n    data2.resize(spec_size);\n\n    if (spec_size > 0)\n    {\n      ifs.read((char*)&data1[0], spec_size * sizeof(DatumSingleton));\n      ifs.read((char*)&data2[0], spec_size * sizeof(DatumSingleton));\n    }\n  }\n\n  void CachedmzML::readSpectrum_(SpectrumType& spectrum, std::ifstream& ifs) const\n  {\n    Datavector mz_data;\n    Datavector int_data;\n\n    int ms_level;\n    double rt;\n    readSpectrum_(mz_data, int_data, ifs, ms_level, rt);\n    spectrum.reserve(mz_data.size());\n    spectrum.setMSLevel(ms_level);\n    spectrum.setRT(rt);\n\n    for (Size j = 0; j < mz_data.size(); j++)\n    {\n      Peak1D p;\n      p.setMZ(mz_data[j]);\n      p.setIntensity(int_data[j]);\n      spectrum.push_back(p);\n    }\n\n  }\n\n  void CachedmzML::readChromatogram_(ChromatogramType& chromatogram, std::ifstream& ifs) const\n  {\n    Datavector rt_data;\n    Datavector int_data;\n    readChromatogram_(rt_data, int_data, ifs);\n    chromatogram.reserve(rt_data.size());\n\n    for (Size j = 0; j < rt_data.size(); j++)\n    {\n      ChromatogramPeak p;\n      p.setRT(rt_data[j]);\n      p.setIntensity(int_data[j]);\n      chromatogram.push_back(p);\n    }\n\n  }\n\n  void CachedmzML::writeSpectrum_(const SpectrumType& spectrum, std::ofstream& ofs)\n  {\n    Size exp_size = spectrum.size();\n    ofs.write((char*)&exp_size, sizeof(exp_size));\n    int_field_ = spectrum.getMSLevel();\n    ofs.write((char*)&int_field_, sizeof(int_field_));\n    dbl_field_ = spectrum.getRT();\n    ofs.write((char*)&dbl_field_, sizeof(dbl_field_));\n\n    \/\/ Catch empty spectrum: we do not write any data and since the \"size\" we\n    \/\/ just wrote is zero, no data will be read\n    if (spectrum.empty())\n    {\n      return;\n    }\n\n    Datavector mz_data;\n    Datavector int_data;\n    for (Size j = 0; j < spectrum.size(); j++)\n    {\n      mz_data.push_back(spectrum[j].getMZ());\n      int_data.push_back(static_cast<double>(spectrum[j].getIntensity()));\n    }\n\n    ofs.write((char*)&mz_data.front(), mz_data.size() * sizeof(mz_data.front()));\n    ofs.write((char*)&int_data.front(), int_data.size() * sizeof(int_data.front()));\n  }\n\n  void CachedmzML::writeChromatogram_(const ChromatogramType& chromatogram, std::ofstream& ofs)\n  {\n    Size exp_size = chromatogram.size();\n    ofs.write((char*)&exp_size, sizeof(exp_size));\n\n    \/\/ Catch empty chromatogram: we do not write any data and since the \"size\" we\n    \/\/ just wrote is zero, no data will be read\n    if (chromatogram.empty())\n    {\n      return;\n    }\n\n    Datavector rt_data;\n    Datavector int_data;\n    for (Size j = 0; j < chromatogram.size(); j++)\n    {\n      rt_data.push_back(chromatogram[j].getRT());\n      int_data.push_back(chromatogram[j].getIntensity());\n    }\n    ofs.write((char*)&rt_data.front(), rt_data.size() * sizeof(rt_data.front()));\n    ofs.write((char*)&int_data.front(), int_data.size() * sizeof(int_data.front()));\n  }\n\n}\n\n","avg_line_length":33.8221024259,"max_line_length":128,"alphanum_fraction":0.650781001,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1772,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.\n\n#include \"MovieSceneMediaTrack.h\"\n\n#include \"MovieSceneMediaSection.h\"\n#include \"MovieSceneMediaTemplate.h\"\n\n\n#define LOCTEXT_NAMESPACE \"MovieSceneMediaTrack\"\n\n\n\/* UMovieSceneMediaTrack interface\n *****************************************************************************\/\n\nUMovieSceneMediaTrack::UMovieSceneMediaTrack(const FObjectInitializer& ObjectInitializer)\n\t: Super(ObjectInitializer)\n{\n\tEvalOptions.bCanEvaluateNearestSection = false;\n\tEvalOptions.bEvalNearestSection = false;\n\tEvalOptions.bEvaluateInPreroll = true;\n\tEvalOptions.bEvaluateInPostroll = true;\n\n#if WITH_EDITORONLY_DATA\n\tTrackTint = FColor(0, 0, 0, 200);\n#endif\n}\n\n\n\/* UMovieScenePropertyTrack interface\n *****************************************************************************\/\n\nvoid UMovieSceneMediaTrack::AddSection(UMovieSceneSection& Section)\n{\n\tSections.AddUnique(&Section);\n}\n\n\nUMovieSceneSection* UMovieSceneMediaTrack::CreateNewSection()\n{\n\treturn NewObject<UMovieSceneMediaSection>(this, NAME_None, RF_Transactional);\n}\n\n\nconst TArray<UMovieSceneSection*>& UMovieSceneMediaTrack::GetAllSections() const\n{\n\treturn Sections;\n}\n\n\nvoid UMovieSceneMediaTrack::RemoveSection(UMovieSceneSection& Section)\n{\n\tSections.Remove(&Section);\n}\n\n\nFMovieSceneEvalTemplatePtr UMovieSceneMediaTrack::CreateTemplateForSection(const UMovieSceneSection& InSection) const\n{\n\treturn FMovieSceneMediaSectionTemplate(*CastChecked<const UMovieSceneMediaSection>(&InSection), *this);\n}\n\n\n#if WITH_EDITORONLY_DATA\n\nFText UMovieSceneMediaTrack::GetDefaultDisplayName() const\n{\n\treturn LOCTEXT(\"DefaultDisplayName\", \"Media Track\");\n}\n\n\nFName UMovieSceneMediaTrack::GetTrackName() const\n{\n\treturn UniqueTrackName;\n}\n\n#endif\n\n\n#undef LOCTEXT_NAMESPACE\n","avg_line_length":22.4303797468,"max_line_length":117,"alphanum_fraction":0.7409706546,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1416,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1963.0,"content":"\/*\n *******************************************************************************\n * Copyright (c) 2020-2021, STMicroelectronics\n * All rights reserved.\n *\n * This software component is licensed by ST under BSD 3-Clause license,\n * the \"License\"; You may not use this file except in compliance with the\n * License. You may obtain a copy of the License at:\n *                        opensource.org\/licenses\/BSD-3-Clause\n *\n *******************************************************************************\n *\/\n#if defined(ARDUINO_GENERIC_F103T8UX) || defined(ARDUINO_GENERIC_F103TBUX)\n#include \"pins_arduino.h\"\n\n\/\/ Digital PinName array\nconst PinName digitalPin[] = {\n  PA_0,   \/\/ D0\/A0\n  PA_1,   \/\/ D1\/A1\n  PA_2,   \/\/ D2\/A2\n  PA_3,   \/\/ D3\/A3\n  PA_4,   \/\/ D4\/A4\n  PA_5,   \/\/ D5\/A5\n  PA_6,   \/\/ D6\/A6\n  PA_7,   \/\/ D7\/A7\n  PA_8,   \/\/ D8\n  PA_9,   \/\/ D9\n  PA_10,  \/\/ D10\n  PA_11,  \/\/ D11\n  PA_12,  \/\/ D12\n  PA_13,  \/\/ D13\n  PA_14,  \/\/ D14\n  PA_15,  \/\/ D15\n  PB_0,   \/\/ D16\/A8\n  PB_1,   \/\/ D17\/A9\n  PB_2,   \/\/ D18\n  PB_3,   \/\/ D19\n  PB_4,   \/\/ D20\n  PB_5,   \/\/ D21\n  PB_6,   \/\/ D22\n  PB_7,   \/\/ D23\n  PD_0,   \/\/ D24\n  PD_1    \/\/ D25\n};\n\n\/\/ Analog (Ax) pin number array\nconst uint32_t analogInputPin[] = {\n  0,  \/\/ A0,  PA0\n  1,  \/\/ A1,  PA1\n  2,  \/\/ A2,  PA2\n  3,  \/\/ A3,  PA3\n  4,  \/\/ A4,  PA4\n  5,  \/\/ A5,  PA5\n  6,  \/\/ A6,  PA6\n  7,  \/\/ A7,  PA7\n  16, \/\/ A8,  PB0\n  17  \/\/ A9,  PB1\n};\n\n#endif \/* ARDUINO_GENERIC_* *\/\n","avg_line_length":23.2131147541,"max_line_length":80,"alphanum_fraction":0.4865819209,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":255,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/*\n * Copyright 2018, Jaroslaw Pelczar <jarek@jpelczar.com>\n * Distributed under the terms of the MIT License.\n *\/\n\n#include <commpage.h>\n\nstatus_t\narch_commpage_init(void)\n{\n\treturn B_OK;\n}\n\n\nstatus_t\narch_commpage_init_post_cpus(void)\n{\n\treturn B_OK;\n}\n","avg_line_length":12.75,"max_line_length":56,"alphanum_fraction":0.7411764706,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1648,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":3.0,"content":"\/*\n * Copyright (c) 2018, ARM Limited, All Rights Reserved\n * SPDX-License-Identifier: Apache-2.0\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"greentea-client\/test_env.h\"\n#include \"mbed.h\"\n#include \"udp_tests.h\"\n#include \"UDPSocket.h\"\n#include \"unity\/unity.h\"\n#include \"utest.h\"\n\nusing namespace utest::v1;\n\nvoid UDPSOCKET_BIND_PORT()\n{\n#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLED\n    int count = fetch_stats();\n    for (int j = 0; j < count; j++) {\n        TEST_ASSERT_EQUAL(SOCK_CLOSED,  udp_stats[j].state);\n    }\n#endif\n\n    UDPSocket *sock = new UDPSocket;\n    if (!sock) {\n        TEST_FAIL();\n    }\n    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->open(NetworkInterface::get_default_instance()));\n    nsapi_error_t bind_result = sock->bind(1024);\n    if (bind_result == NSAPI_ERROR_UNSUPPORTED) {\n        TEST_IGNORE_MESSAGE(\"bind() not supported\");\n    } else {\n        TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, bind_result);\n    }\n\n    delete sock;\n\n#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLED\n    count = fetch_stats();\n    for (int j = 0; j < count; j++) {\n        TEST_ASSERT_EQUAL(SOCK_CLOSED, udp_stats[j].state);\n    }\n#endif\n}\n","avg_line_length":28.9122807018,"max_line_length":92,"alphanum_fraction":0.6990291262,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":284,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/ REQUIRES: opencl-aot, cpu, linux\n\n\/\/ RUN: %clangxx -fsycl -fsycl-targets=spir64_x86_64-unknown-unknown-sycldevice %S\/assert.cpp -o %t.aot.out\n\/\/ RUN: %CPU_RUN_PLACEHOLDER %t.aot.out >%t.aot.msg\n\/\/ RUN: FileCheck %S\/assert.cpp --input-file %t.aot.msg --check-prefixes=CHECK-MESSAGE\n","avg_line_length":47.3333333333,"max_line_length":107,"alphanum_fraction":0.7253521127,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4634,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":15.0,"content":"\/*\n * Copyright (C) 2006, 2007 Apple Inc.  All rights reserved.\n * Copyright (C) 2008 Collabora Ltd. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \n *\/\n\n#include \"config.h\"\n#include \"PluginPackage.h\"\n\n#include \"CString.h\"\n#include \"MIMETypeRegistry.h\"\n#include \"npruntime_impl.h\"\n#include \"PluginDatabase.h\"\n#include \"PluginDebug.h\"\n\nnamespace WebCore {\n\nbool PluginPackage::fetchInfo()\n{\n    if (!load())\n        return false;\n\n    NPP_GetValueProcPtr gv = (NPP_GetValueProcPtr)m_module->resolve(\"NP_GetValue\");\n    typedef char *(*NPP_GetMIMEDescriptionProcPtr)();\n    NPP_GetMIMEDescriptionProcPtr gm =\n        (NPP_GetMIMEDescriptionProcPtr)m_module->resolve(\"NP_GetMIMEDescription\");\n    if (!gm || !gv)\n        return false;\n\n    char *buf = 0;\n    NPError err = gv(0, NPPVpluginNameString, (void*) &buf);\n    if (err != NPERR_NO_ERROR)\n        return false;\n\n    m_name = buf;\n    err = gv(0, NPPVpluginDescriptionString, (void*) &buf);\n    if (err != NPERR_NO_ERROR)\n        return false;\n\n    m_description = buf;\n    determineModuleVersionFromDescription();\n\n    String s = gm();\n    Vector<String> types;\n    s.split(UChar(';'), false, types);\n    for (unsigned i = 0; i < types.size(); ++i) {\n        Vector<String> mime;\n        types[i].split(UChar(':'), true, mime);\n        if (mime.size() > 0) {\n            Vector<String> exts;\n            if (mime.size() > 1)\n                mime[1].split(UChar(','), false, exts);\n            determineQuirks(mime[0]);\n            m_mimeToExtensions.add(mime[0], exts);\n            if (mime.size() > 2)\n                m_mimeToDescriptions.add(mime[0], mime[2]);\n        }\n    }\n\n    return true;\n}\n\nstatic NPError staticPluginQuirkRequiresGtkToolKit_NPN_GetValue(NPP instance, NPNVariable variable, void* value)\n{\n    if (variable == NPNVToolkit) {\n        *static_cast<uint32*>(value) = 2;\n        return NPERR_NO_ERROR;\n    }\n\n    return NPN_GetValue(instance, variable, value);\n}\n\nbool PluginPackage::load()\n{\n    if (m_isLoaded) {\n        m_loadCount++;\n        return true;\n    }\n\n    m_module = new QLibrary((QString)m_path);\n    m_module->setLoadHints(QLibrary::ResolveAllSymbolsHint);\n    if (!m_module->load()) {\n        LOG(Plugins, \"%s not loaded (%s)\", m_path.utf8().data(),\n                m_module->errorString().toLatin1().constData());\n        return false;\n    }\n\n    m_isLoaded = true;\n\n    NP_InitializeFuncPtr NP_Initialize;\n    NPError npErr;\n\n    NP_Initialize = (NP_InitializeFuncPtr)m_module->resolve(\"NP_Initialize\");\n    m_NPP_Shutdown = (NPP_ShutdownProcPtr)m_module->resolve(\"NP_Shutdown\");\n\n    if (!NP_Initialize || !m_NPP_Shutdown)\n        goto abort;\n\n    memset(&m_pluginFuncs, 0, sizeof(m_pluginFuncs));\n    m_pluginFuncs.size = sizeof(m_pluginFuncs);\n\n    initializeBrowserFuncs();\n\n    if (m_path.contains(\"npwrapper.\")) {\n        \/\/ nspluginwrapper relies on the toolkit value to know if glib is available\n        \/\/ It does so in NP_Initialize with a null instance, therefore it is done this way:\n        m_browserFuncs.getvalue = staticPluginQuirkRequiresGtkToolKit_NPN_GetValue;\n    }\n\n#if defined(XP_UNIX)\n    npErr = NP_Initialize(&m_browserFuncs, &m_pluginFuncs);\n#else\n    npErr = NP_Initialize(&m_browserFuncs);\n#endif\n    if (npErr != NPERR_NO_ERROR)\n        goto abort;\n\n    m_loadCount++;\n    return true;\n\nabort:\n    unloadWithoutShutdown();\n    return false;\n}\n\n}\n","avg_line_length":31.5238095238,"max_line_length":112,"alphanum_fraction":0.6771687527,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2693,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"network\/Server.h\"\n#include <iostream>\n#if defined(__WIN32__)\n#include <thread>\n#else\n#include <pthread.h>\n#endif\n#include <string.h>\n\nconst char* LOCALHOST = \"127.0.0.1\";\nconst char* DEFAULT_PORT = \"79977\";\n\nconst int CLIENT_LIMIT = 5;\n\n#ifdef __WIN32__\n#define ClearConsole() system(\"cls\")\n#else\n#define ClearConsole() system(\"clear\");\n#endif\n\n\nconst char* ip_address;\nconst char* port;\n\nServer* server;\n\nvoid ChooseIpAndPort();\nvoid _SetTitle(const char* title);\n\nstruct startargs {\n\tint limit;\n};\n\n#ifndef __WIN32__\nvoid *Start(void* args)\n{\n\tserver->Start(args);\n\treturn NULL;\n}\n#endif\n\nint main() {\n\n\tChooseIpAndPort();\n\n\t\/\/ Initialize server\n\tserver = new Server(ip_address, port);\n\n#ifdef __WIN32__\n\tstd::thread listener(&Server::Start, server, CLIENT_LIMIT); \/\/listen for joining users\n#else\n\tpthread_t listener;\n\tstartargs args;\n\targs.limit = 5;\n\t\n\tpthread_create(&listener, NULL, &Server, (void*) &args);\n#endif\n\twhile (!server->closed)\n\t{\n\t\t\n\t}\n#ifdef __WIN32__\n\tlistener.detach();\n#else\n\tpthread_cancel(listener);\n\t#endif\n}\n\nvoid ChooseIpAndPort()\n{\n\tchar* input1 = new char[14]; \/\/ 255.255.255.255 = 15 chars\n\tchar* input2 = new char[6];\n\tchar* inputyn = new char[0];\n\twhile (true)\n\t{\n\t\t_SetTitle(\"Server\");\n\t\tClearConsole();\n\t\tstd::cout << \"Please enter desired ip address.\" << std::endl;\n\t\tstd::cin >> input1;\n\n\t\tmemset(inputyn, 0, 1);\n\t\tif (!NetworkingUtils::isValidIpv4(input1))\n\t\t{\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tClearConsole();\n\t\t\t\tstd::cout << input1 << \" is not a valid ip address! Would you like to to use \" << LOCALHOST << \"? y\/n\" << std::endl;\n\t\t\t\tstd::cin >> inputyn;\n\t\t\t\tif (inputyn[0] == 'y') {\n\t\t\t\t\tip_address = LOCALHOST;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if (inputyn[0] == 'n')\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (inputyn[0] == 'n') {\n\t\t\tcontinue;\n\t\t}\n\t\telse if (inputyn[0] == 'y')\n\t\t\tbreak;\n\t\telse if (ip_address != LOCALHOST) {\n\t\t\tip_address = input1;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\twhile (true)\n\t{\n\t\tClearConsole();\n\t\tstd::cout << \"Please enter desired port.\" << std::endl;\n\t\tstd::cin >> input2;\n\n\t\tmemset(inputyn, 0, 1);\n\t\tif (!NetworkingUtils::isValidPort(input2))\n\t\t{\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tClearConsole();\n\t\t\t\tstd::cout << input2 << \" is not a valid port! Would you like to to use \" << DEFAULT_PORT << \"? y\/n\" << std::endl;\n\t\t\t\tstd::cin >> inputyn;\n\t\t\t\tif (inputyn[0] == 'y') {\n\t\t\t\t\tport = DEFAULT_PORT;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if (inputyn[0] == 'n')\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (inputyn[0] == 'n') {\n\t\t\tcontinue;\n\t\t}\n\t\telse if (inputyn[0] == 'y')\n\t\t\tbreak;\n\t\telse if (port != DEFAULT_PORT) {\n\t\t\tport = input2;\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\ninline void _SetTitle(const char* title)\n{\n\t#ifdef __WIN32__\n\tSetConsoleTitle(title);\n\t#else\n\tstd::cout << \"\\033]0;\" << title << \"\\007\";\n\t#endif\n}","avg_line_length":18.0738255034,"max_line_length":120,"alphanum_fraction":0.6171555886,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5324,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":5.0,"content":"#include \"video_writer_fmf.hpp\"\r\n#include \"basic_types.hpp\"\r\n#include \"exception.hpp\"\r\n#include <iostream>\r\n#include <stdint.h>\r\n#include <stdexcept>\r\n\r\nnamespace bias\r\n{\r\n    const unsigned int VideoWriter_fmf::DEFAULT_FRAME_SKIP = 1;\r\n    const unsigned int VideoWriter_fmf::FMF_VERSION = 1;\r\n    const QString DUMMY_FILENAME(\"dummy.fmf\");\r\n    const VideoWriterParams_fmf VideoWriter_fmf::DEFAULT_PARAMS =\r\n        VideoWriterParams_fmf();\r\n\r\n    VideoWriter_fmf::VideoWriter_fmf(QObject *parent) \r\n        : VideoWriter_fmf(DEFAULT_PARAMS, DUMMY_FILENAME, 0, parent) \r\n    {}\r\n\r\n    VideoWriter_fmf::VideoWriter_fmf(\r\n            VideoWriterParams_fmf params,\r\n            QString fileName, \r\n            unsigned int cameraNumber,\r\n            QObject *parent\r\n            ) : VideoWriter(fileName, cameraNumber, parent)\r\n    {\r\n        numWritten_ = 0;\r\n        isFirst_ = true;\r\n        setFrameSkip(params.frameSkip);\r\n    }\r\n\r\n    VideoWriter_fmf::~VideoWriter_fmf()\r\n    {\r\n        file_.close();\r\n    }\r\n\r\n    void VideoWriter_fmf::finish()\r\n    {\r\n        try\r\n        {\r\n            file_.seekp(20);\r\n            file_.write((char*) &numWritten_, sizeof(uint64_t));\r\n        }\r\n        catch (std::ifstream::failure &exc)\r\n        {\r\n            unsigned int errorId = ERROR_VIDEO_WRITER_FINISH;\r\n            std::string errorMsg(\"video writer finish - failed\");\r\n            errorMsg +=  \"to write number frames:\\n\\n\"; \r\n            errorMsg += exc.what();\r\n            throw RuntimeError(errorId, errorMsg); \r\n        }\r\n    }\r\n\r\n    void VideoWriter_fmf::addFrame(StampedImage stampedImg)\r\n    {\r\n        if (isFirst_)\r\n        {\r\n            setupOutput(stampedImg);\r\n            isFirst_ = false;\r\n        }\r\n        if (frameCount_%frameSkip_==0)\r\n        {\r\n            try\r\n            {\r\n                file_.write((char*) &stampedImg.timeStamp, sizeof(double));\r\n                file_.write((char*) stampedImg.image.data, size_.width*size_.height*sizeof(char)); \r\n            }\r\n            catch (std::ifstream::failure &exc)\r\n            {\r\n                unsigned int errorId = ERROR_VIDEO_WRITER_ADD_FRAME;\r\n                std::string errorMsg(\"video writer add frame failed:\\n\\n\"); \r\n                errorMsg += exc.what();\r\n                throw RuntimeError(errorId, errorMsg); \r\n            }\r\n            numWritten_++;\r\n        }\r\n        else \r\n        {\r\n            \/\/std::cout << \"skip\" << std::endl;\r\n        }\r\n        frameCount_++;\r\n    }\r\n\r\n    void VideoWriter_fmf::setupOutput(StampedImage stampedImg)\r\n    {\r\n        \/\/ Check image format - must be CV_8UC1\r\n        if (stampedImg.image.channels() != 1)\r\n        {\r\n            unsigned int errorId = ERROR_VIDEO_WRITER_INITIALIZE;\r\n            std::string errorMsg(\"video writer fmf setup failed:\\n\\n\"); \r\n            errorMsg += \"images must be single channel\";\r\n            throw RuntimeError(errorId,errorMsg);\r\n        }\r\n\r\n        if (stampedImg.image.depth() != CV_8U)\r\n        {\r\n            unsigned int errorId = ERROR_VIDEO_WRITER_INITIALIZE;\r\n            std::string errorMsg(\"video writer fmf setup failed:\\n\\n\"); \r\n            errorMsg += \"image depth must be CV_8U\";\r\n            throw RuntimeError(errorId,errorMsg);\r\n        }\r\n\r\n        \/\/ Set error control state, set exceptions mask\r\n        file_.clear();\r\n        file_.exceptions(std::ifstream::failbit | std::ifstream::badbit);\r\n       \r\n        \/\/ Get unique name for file and open for reading\r\n        QString incrFileName = getUniqueFileName();\r\n\r\n        try\r\n        {\r\n            file_.open(incrFileName.toStdString(), std::ios::binary | std::ios::out);\r\n        }\r\n        catch (std::ifstream::failure &exc)\r\n        {\r\n            unsigned int errorId = ERROR_VIDEO_WRITER_INITIALIZE;\r\n            std::string errorMsg(\"video writer unable to open file:\\n\\n\"); \r\n            errorMsg += exc.what();\r\n            throw RuntimeError(errorId, errorMsg); \r\n        }\r\n\r\n        if (!file_.is_open())\r\n        {\r\n            unsigned int errorId = ERROR_VIDEO_WRITER_INITIALIZE;\r\n            std::string errorMsg(\"video writer unable to open file:\\n\\n\"); \r\n            errorMsg += \"no exception thrown\";\r\n            throw RuntimeError(errorId, errorMsg); \r\n        }\r\n\r\n        setSize(stampedImg.image.size());\r\n\r\n        \/\/ Cast values to integers with specific widths\r\n        uint32_t fmfVersion = uint32_t(FMF_VERSION);\r\n        uint32_t width = uint32_t(size_.width);\r\n        uint32_t height = uint32_t(size_.height);\r\n        uint64_t bytesPerChunk = uint64_t(width)*uint64_t(height) + sizeof(double);\r\n\r\n        \/\/ Add fmf header to file\r\n        try \r\n        {\r\n            file_.write((char*) &fmfVersion, sizeof(uint32_t));\r\n            file_.write((char*) &height, sizeof(uint32_t));\r\n            file_.write((char*) &width, sizeof(uint32_t));\r\n            file_.write((char*) &bytesPerChunk, sizeof(uint64_t));\r\n            file_.write((char*) &numWritten_, sizeof(uint64_t));\r\n        }\r\n        catch (std::ifstream::failure &exc)\r\n        {\r\n            unsigned int errorId = ERROR_VIDEO_WRITER_INITIALIZE;\r\n            std::string errorMsg(\"video writer unable to write fmf header:\\n\\n\"); \r\n            errorMsg += exc.what();\r\n            throw RuntimeError(errorId, errorMsg); \r\n        }\r\n\r\n    }\r\n\r\n\r\n} \/\/ namespace bias\r\n","avg_line_length":33.4842767296,"max_line_length":100,"alphanum_fraction":0.5578512397,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6278,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/\/===--- AvailabilityMixin.cpp - Symbol Graph Symbol Availability ---------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AvailabilityMixin.h\"\n#include \"JSON.h\"\n\nusing namespace swift;\nusing namespace symbolgraphgen;\n\nnamespace {\nStringRef getDomain(const AvailableAttr &AvAttr) {\n  switch (AvAttr.getPlatformAgnosticAvailability()) {\n    \/\/ SPM- and Swift-specific availability.\n    case PlatformAgnosticAvailabilityKind::PackageDescriptionVersionSpecific:\n      return { \"SwiftPM\" };\n    case PlatformAgnosticAvailabilityKind::SwiftVersionSpecific:\n    case PlatformAgnosticAvailabilityKind::UnavailableInSwift:\n      return { \"Swift\" };\n    \/\/ Although these are in the agnostic kinds, they are actually a signal\n    \/\/ that there is either platform-specific or completely platform-agnostic.\n    \/\/ They'll be handled below.\n    case PlatformAgnosticAvailabilityKind::Deprecated:\n    case PlatformAgnosticAvailabilityKind::Unavailable:\n    case PlatformAgnosticAvailabilityKind::None:\n      break;\n  }\n\n  \/\/ Platform-specific availability.\n  switch (AvAttr.Platform) {\n    case swift::PlatformKind::iOS:\n      return { \"iOS\" };\n    case swift::PlatformKind::macCatalyst:\n      return { \"macCatalyst\" };\n    case swift::PlatformKind::OSX:\n      return { \"macOS\" };\n    case swift::PlatformKind::tvOS:\n      return { \"tvOS\" };\n    case swift::PlatformKind::watchOS:\n      return { \"watchOS\" };\n    case swift::PlatformKind::iOSApplicationExtension:\n      return { \"iOSAppExtension\" };\n    case swift::PlatformKind::macCatalystApplicationExtension:\n      return { \"macCatalystAppExtension\" };\n    case swift::PlatformKind::OSXApplicationExtension:\n      return { \"macOSAppExtension\" };\n    case swift::PlatformKind::tvOSApplicationExtension:\n      return { \"tvOSAppExtension\" };\n    case swift::PlatformKind::watchOSApplicationExtension:\n      return { \"watchOSAppExtension\" };\n    case swift::PlatformKind::none:\n      return { \"*\" };\n  }\n  llvm_unreachable(\"invalid platform kind\");\n}\n} \/\/ end anonymous namespace\n\nAvailability::Availability(const AvailableAttr &AvAttr)\n  : Domain(getDomain(AvAttr)),\n    Introduced(AvAttr.Introduced),\n    Deprecated(AvAttr.Deprecated),\n    Obsoleted(AvAttr.Obsoleted),\n    Message(AvAttr.Message),\n    Renamed(AvAttr.Rename),\n    IsUnconditionallyDeprecated(AvAttr.isUnconditionallyDeprecated()) {\n      assert(!Domain.empty());\n}\n\nvoid\nAvailability::updateFromDuplicate(const Availability &Other) {\n  assert(Domain == Other.Domain);\n\n  \/\/ The highest `introduced` version always wins\n  \/\/ regardless of the order in which they appeared in the source.\n  if (!Introduced) {\n    Introduced = Other.Introduced;\n  } else if (Other.Introduced && *Other.Introduced > *Introduced) {\n    Introduced = Other.Introduced;\n  }\n\n  \/\/ The `deprecated` version that appears last in the source always wins,\n  \/\/ allowing even to erase a previous deprecated.\n  Deprecated = Other.Deprecated;\n\n  \/\/ Same for `deprecated` with no version.\n  IsUnconditionallyDeprecated = Other.IsUnconditionallyDeprecated;\n\n  \/\/ Same for `obsoleted`.\n  Obsoleted = Other.Obsoleted;\n\n  \/\/ The `message` that appears last in the source always wins.\n  Message = Other.Message;\n\n  \/\/ Same for `renamed`.\n  Renamed = Other.Renamed;\n}\n\nvoid\nAvailability::updateFromParent(const Availability &Parent) {\n  assert(Domain == Parent.Domain);\n\n  \/\/ Allow filling, but never replace a child's existing `introduced`\n  \/\/ availability because it can never be less available than the parent anyway.\n  \/\/\n  \/\/ e.g. you cannot write this:\n  \/\/ @available(macos, introduced: 10.15)\n  \/\/ struct S {\n  \/\/   @available(macos, introduced: 10.14)\n  \/\/   func foo() {}\n  \/\/ }\n  \/\/\n  \/\/ So the child's `introduced` availability will always\n  \/\/ be >= the parent's.\n  if (!Introduced) {\n    Introduced = Parent.Introduced;\n  }\n\n  \/\/ Allow filling from the parent.\n  \/\/ For replacement, we will consider a parent's\n  \/\/ earlier deprecation to supercede a child's later deprecation.\n  if (!Deprecated) {\n    Deprecated = Parent.Deprecated;\n  } else if (Parent.Deprecated && *Parent.Deprecated < *Deprecated) {\n    Deprecated = Parent.Deprecated;\n  }\n\n  \/\/ The above regarding `deprecated` also will apply to `obsoleted`.\n  if (!Obsoleted) {\n    Obsoleted = Parent.Obsoleted;\n  } else if (Parent.Obsoleted && *Parent.Obsoleted < *Obsoleted) {\n    Obsoleted = Parent.Obsoleted;\n  }\n\n  \/\/ Never replace or fill a child's `message` with a parent's because\n  \/\/ there may be context at the parent that doesn't apply at the child,\n  \/\/ i.e. it might not always make sense.\n\n  \/\/ Never replace or fill a child's `renamed` field because it\n  \/\/ doesn't make sense. Just because a parent is renamed doesn't\n  \/\/ mean its child is renamed to the same thing.\n\n  \/\/ If a parent is unconditionally deprecated, then so are all\n  \/\/ of its children.\n  IsUnconditionallyDeprecated |= Parent.IsUnconditionallyDeprecated;\n}\n\nvoid Availability::serialize(llvm::json::OStream &OS) const {\n  OS.object([&](){\n    OS.attribute(\"domain\", Domain);\n    if (Introduced) {\n      AttributeRAII IntroducedAttribute(\"introduced\", OS);\n      symbolgraphgen::serialize(*Introduced, OS);\n    }\n    if (Deprecated) {\n      AttributeRAII DeprecatedAttribute(\"deprecated\", OS);\n      symbolgraphgen::serialize(*Deprecated, OS);\n    }\n    if (Obsoleted) {\n      AttributeRAII ObsoletedAttribute(\"obsoleted\", OS);\n      symbolgraphgen::serialize(*Obsoleted, OS);\n    }\n    if (!Message.empty()) {\n      OS.attribute(\"message\", Message);\n    }\n    if (!Renamed.empty()) {\n      OS.attribute(\"renamed\", Renamed);\n    }\n    if (IsUnconditionallyDeprecated) {\n      OS.attribute(\"isUnconditionallyDeprecated\", true);\n    }\n  }); \/\/ end availability object\n}\n\nbool Availability::empty() const {\n  return !Introduced.hasValue() &&\n         !Deprecated.hasValue() &&\n         !Obsoleted.hasValue() &&\n         !IsUnconditionallyDeprecated;\n}\n","avg_line_length":33.3936170213,"max_line_length":80,"alphanum_fraction":0.6898693852,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1829,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC0-1.0"],"max_stars_count":null,"content":"class Solution {\npublic:\n    int divide(int dividend, int divisor) {\n        \/\/ dividend is minimum\n        if (dividend == INT_MIN) {\n            if (divisor == 1) {\n                return INT_MIN;\n            }\n            if (divisor == -1) {\n                return INT_MAX;\n            }\n        }\n        \/\/ divisor is minimum\n        if (divisor == INT_MIN) {\n            return dividend == INT_MIN ? 1 : 0;\n        }\n        \n        if (dividend == 0) {\n            return 0;\n        }\n        \n        \/\/ Binary Search\n        bool rev = false;\n        if (dividend > 0) {\n            dividend = -dividend;\n            rev = !rev;\n        }\n        if (divisor > 0) {\n            divisor = -divisor;\n            rev = !rev;\n        }\n\n        \/\/ quick multiplication\n        auto quickAdd = [](int y, int z, int x) {\n            int result = 0, add = y;\n            while (z) {\n                if (z & 1) {\n                    if (result < x - add) {\n                        return false;\n                    }\n                    result += add;\n                }\n                if (z != 1) {\n                    if (add < x - add) {\n                        return false;\n                    }\n                    add += add;\n                }\n                z >>= 1;\n            }\n            return true;\n        };\n        \n        int left = 1, right = INT_MAX, ans = 0;\n        while (left <= right) {\n            int mid = left + ((right - left) >> 1);\n            bool check = quickAdd(divisor, mid, dividend);\n            if (check) {\n                ans = mid;\n                if (mid == INT_MAX) {\n                    break;\n                }\n                left = mid + 1;\n            }\n            else {\n                right = mid - 1;\n            }\n        }\n\n        return rev ? -ans : ans;\n    }\n};\n","avg_line_length":25.0547945205,"max_line_length":58,"alphanum_fraction":0.3220338983,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":343,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/\n\/\/  main.cpp\n\/\/  multi_target\n\/\/\n\/\/  Created by Jayanth Raman on 12\/12\/16.\n\/\/  Copyright \u00a9 2016 Jayanth Raman. All rights reserved.\n\/\/\n\n#include <iostream>\n#include \"shared_stuff.hpp\"\n\nint main(int argc, const char * argv[]) {\n    std::cout << \"multi_target says Hello!\\n\";\n    auto shared = Shared();\n    shared.action1();\n    return 0;\n}\n","avg_line_length":19.0555555556,"max_line_length":56,"alphanum_fraction":0.638483965,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3284,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\r\n    author : Keshav Sahu\r\n*\/\r\n\r\n#include \"..\/include\/TicTacToe.h\"\r\n#include <iostream>\r\n#include <limits>\r\n\r\n\/**\r\nto get X,O,space\r\n@params\r\nint x;\r\n*\/\r\nchar toChar(int x)\r\n{\r\n    if(x == 0)\r\n        return ' ';\r\n    else if(x == 1)\r\n        return 'O';\r\n    else\r\n        return 'X';\r\n}\r\n\r\n\r\n\/**\r\nget user input\r\n@params\r\nPlayer &player;\/\/to change player after every run used reference\r\nshort board[3][3];\/\/to change value and get value from board\r\n*\/\r\nvoid getInput(Player &player,short board[3][3])\r\n{\r\n    int x = 0;\r\n    std::cout<<\"Player \"<<((player == PlayerO)?('O'):('X'))<<\"'s term : \";\r\n    do{\r\n    std::cin>>x;\r\n\r\n    \/\/if user enters non-digit number\r\n    if(std::cin.fail())\r\n    {\r\n        std::cin.clear();\r\n        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\\n');\r\n        std::cout<<\"Entered non-digit value enter, input again  : \";\r\n    }\r\n\r\n    \/\/if input value out of range\r\n    else if(x < 0 || x > 10)\r\n        std::cout<<\"Input must be 1-9, input valid number again : \";\r\n\r\n    \/\/check if input is already used\r\n    else if(!check(x-1,board))\r\n        std::cout<<\"Input has been already used, input again    : \";\r\n\r\n    \/\/else user entered a valid input so break loop\r\n    else\r\n        break;\r\n    }while(true);\r\n\r\n    \/\/as user will enter 1 to 9 so decrease by one as array starts with 0\r\n    x--;\r\n\r\n    \/\/if x = 7 then x\/3 = 2 and x%3 = 1 board[2][3]\r\n    board[x\/3][x%3] = player;\r\n\r\n    \/\/swap value X-O of player\r\n    if(player == PlayerO)\r\n        player = PlayerX;\r\n    else\r\n        player = PlayerO;\r\n}\r\n\r\n\/**\r\nto display board\r\n@params\r\nshort board[3][3];\r\n*\/\r\nvoid display(short board[3][3])\r\n{\r\n        std::cout<<toChar(board[0][0])<<\" | \"<<toChar(board[0][1])<<\" | \"<<toChar(board[0][2])<<std::endl;\r\n        std::cout<<\"--|---|--\"<<std::endl;\r\n        std::cout<<toChar(board[1][0])<<\" | \"<<toChar(board[1][1])<<\" | \"<<toChar(board[1][2])<<std::endl;\r\n        std::cout<<\"--|---|--\"<<std::endl;\r\n        std::cout<<toChar(board[2][0])<<\" | \"<<toChar(board[2][1])<<\" | \"<<toChar(board[2][2])<<std::endl;\r\n}\r\n\r\n\/**\r\nto get winner\r\nit will return 1 for PlayerO and 2 for PlayerX\r\nand 0 for none\r\n@params\r\nshort board[3][3]; \/\/board containing data\r\n*\/\r\nPlayer getWinner(short board[3][3])\r\n{\r\n    \/\/check for rows\r\n    for(int i = 0; i < 3; i++)\r\n        if(board[i][0] != 0 && board[i][0] == board[i][1] && board[i][1] == board[i][2])\r\n            return board[i][1];\r\n\r\n    \/\/check for columns\r\n    for(int i = 0; i < 3; i++)\r\n        if(board[0][i] != 0 && board[0][i] == board[1][i] && board[1][i] == board[2][i])\r\n            return board[1][i];\r\n\r\n    \/\/check for corners top-left to bottom-right\r\n    if(board[0][0] != 0 && board[0][0] == board[1][1] && board[1][1] == board[2][2])\r\n        return board[1][1];\r\n\r\n    \/\/check for corners top-right to bottom-left\r\n    if(board[0][2] != 0 && board[0][2] == board[1][1] && board[1][1] == board[2][0])\r\n        return board[1][1];\r\n\r\n    \/\/if no winner return none\r\n    return 0;\r\n}\r\n\r\n\r\n\/**\r\nto check if place is already used\r\n@params\r\nint x;\/\/x should not be negative or greater than or equal to 9\r\nshort board[3][3];\/\/board containing data\r\n*\/\r\nbool check(int x,short board[][3])\r\n{\r\n    if(board[x\/3][x%3] == 0)\r\n        return true;\r\n    else return false;\r\n}\r\n\r\n","avg_line_length":25.0687022901,"max_line_length":107,"alphanum_fraction":0.5267965895,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2096,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":339.0,"content":"#include \"stdafx.h\"\r\n\r\n#include <shared\/AfxDetours.h>\r\n#include \"hl_addresses.h\"\r\n#include \"hooks\/HookHw.h\"\r\n#include \"hooks\/hw\/ClientFunctions.h\"\r\n\r\n#include \"cmdregister.h\"\r\n\r\n#include <hlsdk.h>\r\n#include <deps\/release\/halflife\/common\/ref_params.h>\r\n\r\ntypedef void (*HUD_PlayerMove_t)( struct playermove_s *ppmove, int server );\r\n\r\nHUD_PlayerMove_t g_Old_Hud_PlayerMove;\r\n\r\nstruct {\r\n\tfloat angles[3];\r\n\tfloat origin[3];\r\n\tbool setAngles;\r\n\tbool setOrigin;\r\n} g_Move;\r\n\r\n\r\nvoid New_Hud_PlayerMove( struct playermove_s *ppmove, int server )\r\n{\r\n\tg_Old_Hud_PlayerMove(ppmove, server);\r\n\r\n\tif(g_Move.setAngles)\r\n\t{\r\n\t\tg_Move.setAngles = false;\r\n\r\n\t\tppmove->angles[0] = g_Move.angles[0];\r\n\t\tppmove->angles[1] = g_Move.angles[1];\r\n\t\tppmove->angles[2] = g_Move.angles[2];\r\n\t}\r\n\r\n\tif(g_Move.setOrigin)\r\n\t{\r\n\t\tg_Move.setOrigin = false;\r\n\r\n\t\tppmove->origin[0] = g_Move.origin[0];\r\n\t\tppmove->origin[1] = g_Move.origin[1];\r\n\t\tppmove->origin[2] = g_Move.origin[2];\r\n\t}\r\n}\r\n\r\n\r\nvoid Hook_Hud_PalyerMove(void)\r\n{\r\n\tstatic bool firstRun=true;\r\n\tif(!firstRun) return;\r\n\tfirstRun = false;\r\n\r\n\tg_Move.setAngles = false;\r\n\tg_Move.setOrigin = false;\r\n\r\n\tg_Old_Hud_PlayerMove = (HUD_PlayerMove_t)GetClientFunction(CFTE_HUD_PlayerMove);\r\n\tReplaceClientFunction(CFTE_HUD_PlayerMove, (void *)&New_Hud_PlayerMove);\r\n}\r\n\r\n\r\nREGISTER_DEBUGCMD_FUNC(moveto)\r\n{\r\n\tbool showHelp = true;\r\n\tint argc = pEngfuncs->Cmd_Argc();\r\n\r\n\tHook_Hud_PalyerMove();\r\n\r\n\tif(4 == argc || 7 == argc)\r\n\t{\r\n\t\tshowHelp = false;\r\n\r\n\t\tg_Move.origin[0] = (float)atof(pEngfuncs->Cmd_Argv(1));\r\n\t\tg_Move.origin[1] = (float)atof(pEngfuncs->Cmd_Argv(2));\r\n\t\tg_Move.origin[2] = (float)atof(pEngfuncs->Cmd_Argv(3));\r\n\t\tg_Move.setOrigin = true;\r\n\r\n\t\tif(7 == argc)\r\n\t\t{\r\n\t\t\tg_Move.angles[0] = (float)atof(pEngfuncs->Cmd_Argv(4));\r\n\t\t\tg_Move.angles[1] = (float)atof(pEngfuncs->Cmd_Argv(5));\r\n\t\t\tg_Move.angles[2] = (float)atof(pEngfuncs->Cmd_Argv(6));\r\n\t\t\tg_Move.setAngles = true;\r\n\r\n\t\t\tpEngfuncs->SetViewAngles(g_Move.angles);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tif(showHelp)\r\n\t{\r\n\t\tpEngfuncs->Con_Printf(\"Usage: \" DEBUG_PREFIX \"simorg_set x y z [ang0 ang1 ang2]\\n\");\r\n\t}\r\n\r\n\r\n}\r\n","avg_line_length":21.387755102,"max_line_length":87,"alphanum_fraction":0.6736641221,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1240,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"cpx\/LinuxLibraryLoader.hpp\"\n#include \"cpx\/PluginFactory.hpp\"\n\n#include <dlfcn.h>\n\nnamespace cpx\n{\n\nLinuxLibraryLoader::LinuxLibraryLoader(PluginFactory* pluginFactory):\n    _pluginFactory(pluginFactory)\n{\n}\n\nvoid LinuxLibraryLoader::loadLibrary(std::string file)\n{\n    typedef void (*InitFct)(cpx::PluginFactory*);\n    if (_loadedLibHandles.find(file)==_loadedLibHandles.end())\n    {\n        void* lib_handle;\n        char *error;\n        lib_handle = dlopen(file.c_str(), RTLD_LAZY);\n        if (!lib_handle)\n        {\n            cpx_throw(\"Error while opening file: '\",file,\"': \",dlerror());\n        }\n        _loadedLibHandles[file]=lib_handle;\n        \n        \/\/hides object-to-function cast from the compiler\n        SharedMemory<void*,InitFct> smemory(dlsym(lib_handle, \"init\"));\n        InitFct initFct = smemory.get();\n        if ((error = dlerror()) != NULL)\n        {\n            cpx_throw(\"Error while initializing file: '\",file,\"': \",dlerror());\n        }\n        (*initFct)(_pluginFactory);\n    }\n    else\n    {\n        cpx_throw(\"Plugin file '\",file,\"' already loaded\");\n    }\n}\n\nLinuxLibraryLoader::~LinuxLibraryLoader()\n{\n    for (auto handle: _loadedLibHandles)\n    {\n        dlclose(handle.second);\n    }\n}\n\n}\n","avg_line_length":23.8461538462,"max_line_length":79,"alphanum_fraction":0.614516129,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1362,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/Copyright(c) 2021 Dmitry Yakimenko\n\n#include \"PingICMPObject.h\"\n#include \"Icmp.h\"\n\nUPingICMPObject::UPingICMPObject()\n{\n\n}\n\nUPingICMPObject::~UPingICMPObject()\n{\n\tIcmpEchoResult.Unbind();\n\tOnPingCompleted.Clear();\n}\n\nvoid UPingICMPObject::Ping(FString IP)\n{\n\tIcmpEchoResult.BindUObject(this, &UPingICMPObject::OnServerCheckFinished);\n\tFIcmp::IcmpEcho(IP, 1.f, IcmpEchoResult);\n}\n\nvoid UPingICMPObject::OnServerCheckFinished(FIcmpEchoResult Result)\n{\n\tIcmpEchoResult.Unbind();\n\n\tFString PingStatus = \"Failed\";\n\tswitch (Result.Status)\n\t{\n\tcase EIcmpResponseStatus::Success:\n\t\tPingStatus = \"Success\";\n\t\tbreak;\n\tcase EIcmpResponseStatus::Timeout:\n\t\tPingStatus = \"Timeout\";\n\t\tbreak;\n\tcase EIcmpResponseStatus::Unreachable:\n\t\tPingStatus = \"Unreachable\";\n\t\tbreak;\n\tcase EIcmpResponseStatus::Unresolvable:\n\t\tPingStatus = \"Unresolvable\";\n\t\tbreak;\n\tcase EIcmpResponseStatus::InternalError:\n\t\tPingStatus = \"Internal Error\";\n\t\tbreak;\n\tdefault:\n\t\tPingStatus = \"Unknown Error\";\n\t\tbreak;\n\t}\n\n\tif (OnPingCompleted.IsBound())\n\t{\n\t\tICMPResult.Status = PingStatus;\/\/ StaticEnum<EIcmpResponseStatus>()->GetValueAsString(Result.Status);\n\t\tICMPResult.ResolvedAddress = Result.ResolvedAddress;\n\t\tICMPResult.ReplyFrom = Result.ReplyFrom;\n\t\tICMPResult.Time = Result.Time;\n\t\tOnPingCompleted.Broadcast(ICMPResult);\n\t}\n\n\tUE_LOG(LogTemp, Display, TEXT(\"Ping Result is %s\"), *PingStatus);\n}","avg_line_length":22.7,"max_line_length":103,"alphanum_fraction":0.7555066079,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2235,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/******************************************************************\n *\n * Round for C++\n *\n * Copyright (C) Satoshi Konno 2015\n *\n * This is licensed under BSD-style license, see file COPYING.\n *\n ******************************************************************\/\n\n#include <round\/common\/Mutex.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/  Mutex\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nRound::Mutex::Mutex() {\n#if defined(WIN32) && !defined(ITRON)\n  mutexID = CreateMutex(NULL, FALSE, NULL);\n#elif defined(BTRON)\n  mutexID = cre_sem(1, SEM_EXCL);\n#elif defined(ITRON)\n  T_CSEM  csem;\n  csem.sematr = TA_TFIFO;\n  csem.isemcnt = 1;\n  csem.maxsem = 1;\n  csem.name = NULL;\n  mutexID = acre_sem(&csem);\n#elif defined(TENGINE) && !defined(PROCESS_BASE)\n  T_CSEM  csem;\n  csem.exinf = 0;\n  csem.sematr = TA_TFIFO | TA_FIRST;\n  csem.isemcnt = 0;\n  csem.maxsem = 1;\n  mutexID = tk_cre_sem(&csem);\n#elif defined(TENGINE) && defined(PROCESS_BASE)\n  mutexID = b_cre_sem(1, SEM_EXCL);\n#else\n  pthread_mutex_init(&mutexID, NULL);\n#endif\n}\n\nRound::Mutex::~Mutex() {\n#if defined(WIN32) && !defined(ITRON)\n  CloseHandle(mutexID);\n#elif defined(BTRON)\n  del_sem(mutexID);\n#elif defined(ITRON)\n  del_sem(mutexID);\n#elif defined(TENGINE) && !defined(PROCESS_BASE)\n  tk_del_sem(mutexID);\n#elif defined(TENGINE) && defined(PROCESS_BASE)\n  b_del_sem(mutexID);\n#else\n  pthread_mutex_destroy(&mutexID);\n#endif\n}\n\nbool Round::Mutex::lock() {\n#if defined(WIN32) && !defined(ITRON)\n  WaitForSingleObject(mutexID, INFINITE);\n#elif defined(BTRON)\n  wai_sem(mutexID, T_FOREVER);\n#elif defined(ITRON)\n  twai_sem(mutexID, TMO_FEVR);\n#elif defined(TENGINE) && !defined(PROCESS_BASE)\n  tk_wai_sem(mutexID, 1, TMO_FEVR);\n#elif defined(TENGINE) && defined(PROCESS_BASE)\n  b_wai_sem(mutexID, T_FOREVER);\n#else\n  pthread_mutex_lock(&mutexID);\n#endif\n  return true;\n}\n\nbool Round::Mutex::unlock() {\n#if defined(WIN32) && !defined(ITRON)\n  ReleaseMutex(mutexID);\n#elif defined(BTRON)\n  sig_sem(mutexID);\n#elif defined(ITRON)\n  sig_sem(mutexID);\n#elif defined(TENGINE) && !defined(PROCESS_BASE)\n  tk_sig_sem(mutexID, 1);\n#elif defined(TENGINE) && defined(PROCESS_BASE)\n  b_sig_sem(mutexID);\n#else\n  pthread_mutex_unlock(&mutexID);\n#endif\n  return true;\n}\n","avg_line_length":24.2934782609,"max_line_length":68,"alphanum_fraction":0.6331096197,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1261,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2.0,"content":"\ufeff\/*\n* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\").\n* You may not use this file except in compliance with the License.\n* A copy of the License is located at\n*\n*  http:\/\/aws.amazon.com\/apache2.0\n*\n* or in the \"license\" file accompanying this file. This file is distributed\n* on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n* express or implied. See the License for the specific language governing\n* permissions and limitations under the License.\n*\/\n\n#include <aws\/mq\/model\/UpdateConfigurationRequest.h>\n#include <aws\/core\/utils\/json\/JsonSerializer.h>\n\n#include <utility>\n\nusing namespace Aws::MQ::Model;\nusing namespace Aws::Utils::Json;\nusing namespace Aws::Utils;\n\nUpdateConfigurationRequest::UpdateConfigurationRequest() : \n    m_configurationIdHasBeenSet(false),\n    m_dataHasBeenSet(false),\n    m_descriptionHasBeenSet(false)\n{\n}\n\nAws::String UpdateConfigurationRequest::SerializePayload() const\n{\n  JsonValue payload;\n\n  if(m_dataHasBeenSet)\n  {\n   payload.WithString(\"data\", m_data);\n\n  }\n\n  if(m_descriptionHasBeenSet)\n  {\n   payload.WithString(\"description\", m_description);\n\n  }\n\n  return payload.View().WriteReadable();\n}\n\n\n\n\n","avg_line_length":23.3518518519,"max_line_length":78,"alphanum_fraction":0.7478191911,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":490,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <bits\/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    #ifndef ONLINE_JUDGE\n    freopen(\"files\/input.txt\", \"r\", stdin);\n    freopen(\"files\/output.txt\", \"w\", stdout);\n    #endif\n\n    int n;\n    cin >> n;\n\n    int val, odds = 0, evens = 0;\n    for (int i = 0; i < n; ++i) {\n        cin >> val;\n        if (val % 2 == 1) odds++;\n        else evens++;\n    }\n\n    if (odds % 2 == 1) cout << odds << endl;\n    else cout << evens << endl;\n    return 0;\n}\n","avg_line_length":19.6,"max_line_length":45,"alphanum_fraction":0.5020408163,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":14633,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/* Copyright 2013-2019 MultiMC Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"MultiMCPage.h\"\n#include \"ui_MultiMCPage.h\"\n\n#include <QFileDialog>\n#include <QMessageBox>\n#include <QDir>\n#include <QTextCharFormat>\n\n#include \"updater\/UpdateChecker.h\"\n\n#include \"settings\/SettingsObject.h\"\n#include <FileSystem.h>\n#include \"MultiMC.h\"\n#include \"BuildConfig.h\"\n#include \"themes\/ITheme.h\"\n\n\/\/ FIXME: possibly move elsewhere\nenum InstSortMode\n{\n    \/\/ Sort alphabetically by name.\n    Sort_Name,\n    \/\/ Sort by which instance was launched most recently.\n    Sort_LastLaunch\n};\n\nMultiMCPage::MultiMCPage(QWidget *parent) : QWidget(parent), ui(new Ui::MultiMCPage)\n{\n    ui->setupUi(this);\n    auto origForeground = ui->fontPreview->palette().color(ui->fontPreview->foregroundRole());\n    auto origBackground = ui->fontPreview->palette().color(ui->fontPreview->backgroundRole());\n    m_colors.reset(new LogColorCache(origForeground, origBackground));\n\n    ui->sortingModeGroup->setId(ui->sortByNameBtn, Sort_Name);\n    ui->sortingModeGroup->setId(ui->sortLastLaunchedBtn, Sort_LastLaunch);\n\n    defaultFormat = new QTextCharFormat(ui->fontPreview->currentCharFormat());\n\n    m_languageModel = MMC->translations();\n    loadSettings();\n\n    if(BuildConfig.UPDATER_ENABLED)\n    {\n        QObject::connect(MMC->updateChecker().get(), &UpdateChecker::channelListLoaded, this,\n                        &MultiMCPage::refreshUpdateChannelList);\n\n        if (MMC->updateChecker()->hasChannels())\n        {\n            refreshUpdateChannelList();\n        }\n        else\n        {\n            MMC->updateChecker()->updateChanList(false);\n        }\n    }\n    else\n    {\n        ui->updateSettingsBox->setHidden(true);\n    }\n    \/\/ Analytics\n    if(BuildConfig.ANALYTICS_ID.isEmpty())\n    {\n        ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->analyticsTab));\n    }\n    connect(ui->fontSizeBox, SIGNAL(valueChanged(int)), SLOT(refreshFontPreview()));\n    connect(ui->consoleFont, SIGNAL(currentFontChanged(QFont)), SLOT(refreshFontPreview()));\n}\n\nMultiMCPage::~MultiMCPage()\n{\n    delete ui;\n    delete defaultFormat;\n}\n\nbool MultiMCPage::apply()\n{\n    applySettings();\n    return true;\n}\n\nvoid MultiMCPage::on_instDirBrowseBtn_clicked()\n{\n    QString raw_dir = QFileDialog::getExistingDirectory(this, tr(\"Instance Folder\"), ui->instDirTextBox->text());\n\n    \/\/ do not allow current dir - it's dirty. Do not allow dirs that don't exist\n    if (!raw_dir.isEmpty() && QDir(raw_dir).exists())\n    {\n        QString cooked_dir = FS::NormalizePath(raw_dir);\n        if (FS::checkProblemticPathJava(QDir(cooked_dir)))\n        {\n            QMessageBox warning;\n            warning.setText(tr(\"You're trying to specify an instance folder which\\'s path \"\n                               \"contains at least one \\'!\\'. \"\n                               \"Java is known to cause problems if that is the case, your \"\n                               \"instances (probably) won't start!\"));\n            warning.setInformativeText(\n                tr(\"Do you really want to use this path? \"\n                   \"Selecting \\\"No\\\" will close this and not alter your instance path.\"));\n            warning.setStandardButtons(QMessageBox::Yes | QMessageBox::No);\n            int result = warning.exec();\n            if (result == QMessageBox::Yes)\n            {\n                ui->instDirTextBox->setText(cooked_dir);\n            }\n        }\n        else\n        {\n            ui->instDirTextBox->setText(cooked_dir);\n        }\n    }\n}\n\nvoid MultiMCPage::on_iconsDirBrowseBtn_clicked()\n{\n    QString raw_dir = QFileDialog::getExistingDirectory(this, tr(\"Icons Folder\"), ui->iconsDirTextBox->text());\n\n    \/\/ do not allow current dir - it's dirty. Do not allow dirs that don't exist\n    if (!raw_dir.isEmpty() && QDir(raw_dir).exists())\n    {\n        QString cooked_dir = FS::NormalizePath(raw_dir);\n        ui->iconsDirTextBox->setText(cooked_dir);\n    }\n}\nvoid MultiMCPage::on_modsDirBrowseBtn_clicked()\n{\n    QString raw_dir = QFileDialog::getExistingDirectory(this, tr(\"Mods Folder\"), ui->modsDirTextBox->text());\n\n    \/\/ do not allow current dir - it's dirty. Do not allow dirs that don't exist\n    if (!raw_dir.isEmpty() && QDir(raw_dir).exists())\n    {\n        QString cooked_dir = FS::NormalizePath(raw_dir);\n        ui->modsDirTextBox->setText(cooked_dir);\n    }\n}\n\nvoid MultiMCPage::refreshUpdateChannelList()\n{\n    \/\/ Stop listening for selection changes. It's going to change a lot while we update it and\n    \/\/ we don't need to update the\n    \/\/ description label constantly.\n    QObject::disconnect(ui->updateChannelComboBox, SIGNAL(currentIndexChanged(int)), this,\n                        SLOT(updateChannelSelectionChanged(int)));\n\n    QList<UpdateChecker::ChannelListEntry> channelList = MMC->updateChecker()->getChannelList();\n    ui->updateChannelComboBox->clear();\n    int selection = -1;\n    for (int i = 0; i < channelList.count(); i++)\n    {\n        UpdateChecker::ChannelListEntry entry = channelList.at(i);\n\n        \/\/ When it comes to selection, we'll rely on the indexes of a channel entry being the\n        \/\/ same in the\n        \/\/ combo box as it is in the update checker's channel list.\n        \/\/ This probably isn't very safe, but the channel list doesn't change often enough (or\n        \/\/ at all) for\n        \/\/ this to be a big deal. Hope it doesn't break...\n        ui->updateChannelComboBox->addItem(entry.name);\n\n        \/\/ If the update channel we just added was the selected one, set the current index in\n        \/\/ the combo box to it.\n        if (entry.id == m_currentUpdateChannel)\n        {\n            qDebug() << \"Selected index\" << i << \"channel id\" << m_currentUpdateChannel;\n            selection = i;\n        }\n    }\n\n    ui->updateChannelComboBox->setCurrentIndex(selection);\n\n    \/\/ Start listening for selection changes again and update the description label.\n    QObject::connect(ui->updateChannelComboBox, SIGNAL(currentIndexChanged(int)), this,\n                     SLOT(updateChannelSelectionChanged(int)));\n    refreshUpdateChannelDesc();\n\n    \/\/ Now that we've updated the channel list, we can enable the combo box.\n    \/\/ It starts off disabled so that if the channel list hasn't been loaded, it will be\n    \/\/ disabled.\n    ui->updateChannelComboBox->setEnabled(true);\n}\n\nvoid MultiMCPage::updateChannelSelectionChanged(int index)\n{\n    refreshUpdateChannelDesc();\n}\n\nvoid MultiMCPage::refreshUpdateChannelDesc()\n{\n    \/\/ Get the channel list.\n    QList<UpdateChecker::ChannelListEntry> channelList = MMC->updateChecker()->getChannelList();\n    int selectedIndex = ui->updateChannelComboBox->currentIndex();\n    if (selectedIndex < 0)\n    {\n        return;\n    }\n    if (selectedIndex < channelList.count())\n    {\n        \/\/ Find the channel list entry with the given index.\n        UpdateChecker::ChannelListEntry selected = channelList.at(selectedIndex);\n\n        \/\/ Set the description text.\n        ui->updateChannelDescLabel->setText(selected.description);\n\n        \/\/ Set the currently selected channel ID.\n        m_currentUpdateChannel = selected.id;\n    }\n}\n\nvoid MultiMCPage::applySettings()\n{\n    auto s = MMC->settings();\n\n    if (ui->resetNotificationsBtn->isChecked())\n    {\n        s->set(\"ShownNotifications\", QString());\n    }\n\n    \/\/ Updates\n    s->set(\"AutoUpdate\", ui->autoUpdateCheckBox->isChecked());\n    s->set(\"UpdateChannel\", m_currentUpdateChannel);\n    auto original = s->get(\"IconTheme\").toString();\n    \/\/FIXME: make generic\n    switch (ui->themeComboBox->currentIndex())\n    {\n    case 1:\n        s->set(\"IconTheme\", \"pe_dark\");\n        break;\n    case 2:\n        s->set(\"IconTheme\", \"pe_light\");\n        break;\n    case 3:\n        s->set(\"IconTheme\", \"pe_blue\");\n        break;\n    case 4:\n        s->set(\"IconTheme\", \"pe_colored\");\n        break;\n    case 5:\n        s->set(\"IconTheme\", \"OSX\");\n        break;\n    case 6:\n        s->set(\"IconTheme\", \"iOS\");\n        break;\n    case 7:\n        s->set(\"IconTheme\", \"flat\");\n        break;\n    case 8:\n        s->set(\"IconTheme\", \"custom\");\n        break;\n    case 0:\n    default:\n        s->set(\"IconTheme\", \"multimc\");\n        break;\n    }\n\n    if(original != s->get(\"IconTheme\"))\n    {\n        MMC->setIconTheme(s->get(\"IconTheme\").toString());\n    }\n\n    auto originalAppTheme = s->get(\"ApplicationTheme\").toString();\n    auto newAppTheme = ui->themeComboBoxColors->currentData().toString();\n    if(originalAppTheme != newAppTheme)\n    {\n        s->set(\"ApplicationTheme\", newAppTheme);\n        MMC->setApplicationTheme(newAppTheme, false);\n    }\n\n    \/\/ Console settings\n    s->set(\"ShowConsole\", ui->showConsoleCheck->isChecked());\n    s->set(\"AutoCloseConsole\", ui->autoCloseConsoleCheck->isChecked());\n    s->set(\"ShowConsoleOnError\", ui->showConsoleErrorCheck->isChecked());\n    QString consoleFontFamily = ui->consoleFont->currentFont().family();\n    s->set(\"ConsoleFont\", consoleFontFamily);\n    s->set(\"ConsoleFontSize\", ui->fontSizeBox->value());\n    s->set(\"ConsoleMaxLines\", ui->lineLimitSpinBox->value());\n    s->set(\"ConsoleOverflowStop\", ui->checkStopLogging->checkState() != Qt::Unchecked);\n\n    \/\/ Folders\n    \/\/ TODO: Offer to move instances to new instance folder.\n    s->set(\"InstanceDir\", ui->instDirTextBox->text());\n    s->set(\"CentralModsDir\", ui->modsDirTextBox->text());\n    s->set(\"IconsDir\", ui->iconsDirTextBox->text());\n\n    auto sortMode = (InstSortMode)ui->sortingModeGroup->checkedId();\n    switch (sortMode)\n    {\n    case Sort_LastLaunch:\n        s->set(\"InstSortMode\", \"LastLaunch\");\n        break;\n    case Sort_Name:\n    default:\n        s->set(\"InstSortMode\", \"Name\");\n        break;\n    }\n\n    \/\/ Analytics\n    if(!BuildConfig.ANALYTICS_ID.isEmpty())\n    {\n        s->set(\"Analytics\", ui->analyticsCheck->isChecked());\n    }\n}\nvoid MultiMCPage::loadSettings()\n{\n    auto s = MMC->settings();\n    \/\/ Updates\n    ui->autoUpdateCheckBox->setChecked(s->get(\"AutoUpdate\").toBool());\n    m_currentUpdateChannel = s->get(\"UpdateChannel\").toString();\n    \/\/FIXME: make generic\n    auto theme = s->get(\"IconTheme\").toString();\n    if (theme == \"pe_dark\")\n    {\n        ui->themeComboBox->setCurrentIndex(1);\n    }\n    else if (theme == \"pe_light\")\n    {\n        ui->themeComboBox->setCurrentIndex(2);\n    }\n    else if (theme == \"pe_blue\")\n    {\n        ui->themeComboBox->setCurrentIndex(3);\n    }\n    else if (theme == \"pe_colored\")\n    {\n        ui->themeComboBox->setCurrentIndex(4);\n    }\n    else if (theme == \"OSX\")\n    {\n        ui->themeComboBox->setCurrentIndex(5);\n    }\n    else if (theme == \"iOS\")\n    {\n        ui->themeComboBox->setCurrentIndex(6);\n    }\n    else if (theme == \"flat\")\n    {\n        ui->themeComboBox->setCurrentIndex(7);\n    }\n    else if (theme == \"custom\")\n    {\n        ui->themeComboBox->setCurrentIndex(8);\n    }\n    else\n    {\n        ui->themeComboBox->setCurrentIndex(0);\n    }\n\n    {\n        auto currentTheme = s->get(\"ApplicationTheme\").toString();\n        auto themes = MMC->getValidApplicationThemes();\n        int idx = 0;\n        for(auto &theme: themes)\n        {\n            ui->themeComboBoxColors->addItem(theme->name(), theme->id());\n            if(currentTheme == theme->id())\n            {\n                ui->themeComboBoxColors->setCurrentIndex(idx);\n            }\n            idx++;\n        }\n    }\n\n    \/\/ Console settings\n    ui->showConsoleCheck->setChecked(s->get(\"ShowConsole\").toBool());\n    ui->autoCloseConsoleCheck->setChecked(s->get(\"AutoCloseConsole\").toBool());\n    ui->showConsoleErrorCheck->setChecked(s->get(\"ShowConsoleOnError\").toBool());\n    QString fontFamily = MMC->settings()->get(\"ConsoleFont\").toString();\n    QFont consoleFont(fontFamily);\n    ui->consoleFont->setCurrentFont(consoleFont);\n\n    bool conversionOk = true;\n    int fontSize = MMC->settings()->get(\"ConsoleFontSize\").toInt(&conversionOk);\n    if(!conversionOk)\n    {\n        fontSize = 11;\n    }\n    ui->fontSizeBox->setValue(fontSize);\n    refreshFontPreview();\n    ui->lineLimitSpinBox->setValue(s->get(\"ConsoleMaxLines\").toInt());\n    ui->checkStopLogging->setChecked(s->get(\"ConsoleOverflowStop\").toBool());\n\n    \/\/ Folders\n    ui->instDirTextBox->setText(s->get(\"InstanceDir\").toString());\n    ui->modsDirTextBox->setText(s->get(\"CentralModsDir\").toString());\n    ui->iconsDirTextBox->setText(s->get(\"IconsDir\").toString());\n\n    QString sortMode = s->get(\"InstSortMode\").toString();\n\n    if (sortMode == \"LastLaunch\")\n    {\n        ui->sortLastLaunchedBtn->setChecked(true);\n    }\n    else\n    {\n        ui->sortByNameBtn->setChecked(true);\n    }\n\n    \/\/ Analytics\n    if(!BuildConfig.ANALYTICS_ID.isEmpty())\n    {\n        ui->analyticsCheck->setChecked(s->get(\"Analytics\").toBool());\n    }\n}\n\nvoid MultiMCPage::refreshFontPreview()\n{\n    int fontSize = ui->fontSizeBox->value();\n    QString fontFamily = ui->consoleFont->currentFont().family();\n    ui->fontPreview->clear();\n    defaultFormat->setFont(QFont(fontFamily, fontSize));\n    {\n        QTextCharFormat format(*defaultFormat);\n        format.setForeground(m_colors->getFront(MessageLevel::Error));\n        \/\/ append a paragraph\/line\n        auto workCursor = ui->fontPreview->textCursor();\n        workCursor.movePosition(QTextCursor::End);\n        workCursor.insertText(tr(\"[Something\/ERROR] A spooky error!\"), format);\n        workCursor.insertBlock();\n    }\n    {\n        QTextCharFormat format(*defaultFormat);\n        format.setForeground(m_colors->getFront(MessageLevel::Message));\n        \/\/ append a paragraph\/line\n        auto workCursor = ui->fontPreview->textCursor();\n        workCursor.movePosition(QTextCursor::End);\n        workCursor.insertText(tr(\"[Test\/INFO] A harmless message...\"), format);\n        workCursor.insertBlock();\n    }\n    {\n        QTextCharFormat format(*defaultFormat);\n        format.setForeground(m_colors->getFront(MessageLevel::Warning));\n        \/\/ append a paragraph\/line\n        auto workCursor = ui->fontPreview->textCursor();\n        workCursor.movePosition(QTextCursor::End);\n        workCursor.insertText(tr(\"[Something\/WARN] A not so spooky warning.\"), format);\n        workCursor.insertBlock();\n    }\n}\n","avg_line_length":32.4456762749,"max_line_length":113,"alphanum_fraction":0.6356181234,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5987,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":5964.0,"content":"\/*\n * Copyright (C) 2007, 2008, 2013 Apple Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1.  Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n * 2.  Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and\/or other materials provided with the distribution.\n * 3.  Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n *     its contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"modules\/webdatabase\/DatabaseThread.h\"\n\n#include \"modules\/webdatabase\/Database.h\"\n#include \"modules\/webdatabase\/DatabaseTask.h\"\n#include \"modules\/webdatabase\/SQLTransactionClient.h\"\n#include \"modules\/webdatabase\/SQLTransactionCoordinator.h\"\n#include \"platform\/Logging.h\"\n#include \"platform\/ThreadSafeFunctional.h\"\n#include \"platform\/heap\/glue\/MessageLoopInterruptor.h\"\n#include \"platform\/heap\/glue\/PendingGCRunner.h\"\n#include \"public\/platform\/Platform.h\"\n\nnamespace blink {\n\nDatabaseThread::DatabaseThread()\n    : m_transactionClient(adoptPtr(new SQLTransactionClient()))\n    , m_transactionCoordinator(new SQLTransactionCoordinator())\n    , m_cleanupSync(0)\n    , m_terminationRequested(false)\n{\n}\n\nDatabaseThread::~DatabaseThread()\n{\n    ASSERT(m_openDatabaseSet.isEmpty());\n    ASSERT(!m_thread);\n}\n\nDEFINE_TRACE(DatabaseThread)\n{\n    visitor->trace(m_openDatabaseSet);\n    visitor->trace(m_transactionCoordinator);\n}\n\nvoid DatabaseThread::start()\n{\n    if (m_thread)\n        return;\n    m_thread = WebThreadSupportingGC::create(\"WebCore: Database\");\n    m_thread->postTask(FROM_HERE, new Task(threadSafeBind(&DatabaseThread::setupDatabaseThread, this)));\n}\n\nvoid DatabaseThread::setupDatabaseThread()\n{\n    m_thread->initialize();\n}\n\nvoid DatabaseThread::terminate()\n{\n    TaskSynchronizer sync;\n    {\n        MutexLocker lock(m_terminationRequestedMutex);\n        ASSERT(!m_terminationRequested);\n        m_terminationRequested = true;\n        m_cleanupSync = &sync;\n        WTF_LOG(StorageAPI, \"DatabaseThread %p was asked to terminate\\n\", this);\n        m_thread->postTask(FROM_HERE, new Task(threadSafeBind(&DatabaseThread::cleanupDatabaseThread, this)));\n    }\n    sync.waitForTaskCompletion();\n    \/\/ The WebThread destructor blocks until all the tasks of the database\n    \/\/ thread are processed. However, it shouldn't block at all because\n    \/\/ the database thread has already finished processing the cleanup task.\n    m_thread.clear();\n}\n\nbool DatabaseThread::terminationRequested() const\n{\n    MutexLocker lock(m_terminationRequestedMutex);\n    return m_terminationRequested;\n}\n\nvoid DatabaseThread::cleanupDatabaseThread()\n{\n    WTF_LOG(StorageAPI, \"Cleaning up DatabaseThread %p\", this);\n\n    \/\/ Clean up the list of all pending transactions on this database thread\n    m_transactionCoordinator->shutdown();\n\n    \/\/ Close the databases that we ran transactions on. This ensures that if any transactions are still open, they are rolled back and we don't leave the database in an\n    \/\/ inconsistent or locked state.\n    if (m_openDatabaseSet.size() > 0) {\n        \/\/ As the call to close will modify the original set, we must take a copy to iterate over.\n        HeapHashSet<Member<Database>> openSetCopy;\n        openSetCopy.swap(m_openDatabaseSet);\n        HeapHashSet<Member<Database>>::iterator end = openSetCopy.end();\n        for (HeapHashSet<Member<Database>>::iterator it = openSetCopy.begin(); it != end; ++it)\n            (*it)->close();\n    }\n    m_openDatabaseSet.clear();\n\n    m_thread->postTask(FROM_HERE, new Task(WTF::bind(&DatabaseThread::cleanupDatabaseThreadCompleted, this)));\n}\n\nvoid DatabaseThread::cleanupDatabaseThreadCompleted()\n{\n    m_thread->shutdown();\n    if (m_cleanupSync) \/\/ Someone wanted to know when we were done cleaning up.\n        m_cleanupSync->taskCompleted();\n}\n\nvoid DatabaseThread::recordDatabaseOpen(Database* database)\n{\n    ASSERT(isDatabaseThread());\n    ASSERT(database);\n    ASSERT(!m_openDatabaseSet.contains(database));\n    MutexLocker lock(m_terminationRequestedMutex);\n    if (!m_terminationRequested)\n        m_openDatabaseSet.add(database);\n}\n\nvoid DatabaseThread::recordDatabaseClosed(Database* database)\n{\n    ASSERT(isDatabaseThread());\n    ASSERT(database);\n    ASSERT(m_terminationRequested || m_openDatabaseSet.contains(database));\n    m_openDatabaseSet.remove(database);\n}\n\nbool DatabaseThread::isDatabaseOpen(Database* database)\n{\n    ASSERT(isDatabaseThread());\n    ASSERT(database);\n    MutexLocker lock(m_terminationRequestedMutex);\n    return !m_terminationRequested && m_openDatabaseSet.contains(database);\n}\n\nvoid DatabaseThread::scheduleTask(PassOwnPtr<DatabaseTask> task)\n{\n    ASSERT(m_thread);\n    ASSERT(!terminationRequested());\n    \/\/ WebThread takes ownership of the task.\n    m_thread->postTask(FROM_HERE, new Task(threadSafeBind(&DatabaseTask::run, task)));\n}\n\n} \/\/ namespace blink\n","avg_line_length":36.2848484848,"max_line_length":168,"alphanum_fraction":0.7437781861,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":74938,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2009-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <chain.h>\n#include <core_io.h>\n#include <interfaces\/chain.h>\n#include <key_io.h>\n#include <merkleblock.h>\n#include <rpc\/server.h>\n#include <rpc\/util.h>\n#include <script\/descriptor.h>\n#include <script\/script.h>\n#include <script\/standard.h>\n#include <sync.h>\n#include <util\/bip32.h>\n#include <util\/system.h>\n#include <util\/time.h>\n#include <validation.h>\n#include <wallet\/wallet.h>\n#include <wallet\/rpcwallet.h>\n#include <wallet\/hdwallet.h>\n\n#include <stdint.h>\n#include <tuple>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\n#include <univalue.h>\n\n\nint64_t static DecodeDumpTime(const std::string &str) {\n    static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);\n    static const std::locale loc(std::locale::classic(),\n        new boost::posix_time::time_input_facet(\"%Y-%m-%dT%H:%M:%SZ\"));\n    std::istringstream iss(str);\n    iss.imbue(loc);\n    boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);\n    iss >> ptime;\n    if (ptime.is_not_a_date_time())\n        return 0;\n    return (ptime - epoch).total_seconds();\n}\n\nstd::string static EncodeDumpString(const std::string &str) {\n    std::stringstream ret;\n    for (const unsigned char c : str) {\n        if (c <= 32 || c >= 128 || c == '%') {\n            ret << '%' << HexStr(&c, &c + 1);\n        } else {\n            ret << c;\n        }\n    }\n    return ret.str();\n}\n\nstatic std::string DecodeDumpString(const std::string &str) {\n    std::stringstream ret;\n    for (unsigned int pos = 0; pos < str.length(); pos++) {\n        unsigned char c = str[pos];\n        if (c == '%' && pos+2 < str.length()) {\n            c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |\n                ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));\n            pos += 2;\n        }\n        ret << c;\n    }\n    return ret.str();\n}\n\nstatic bool GetWalletAddressesForKey(CWallet* const pwallet, const CKeyID& keyid, std::string& strAddr, std::string& strLabel) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)\n{\n    bool fLabelFound = false;\n    CKey key;\n    pwallet->GetKey(keyid, key);\n    for (const auto& dest : GetAllDestinationsForKey(key.GetPubKey())) {\n        if (pwallet->mapAddressBook.count(dest)) {\n            if (!strAddr.empty()) {\n                strAddr += \",\";\n            }\n            strAddr += EncodeDestination(dest);\n            strLabel = EncodeDumpString(pwallet->mapAddressBook[dest].name);\n            fLabelFound = true;\n        }\n    }\n    if (!fLabelFound) {\n        strAddr = EncodeDestination(GetDestinationForKey(key.GetPubKey(), pwallet->m_default_address_type));\n    }\n    return fLabelFound;\n}\n\nstatic const int64_t TIMESTAMP_MIN = 0;\n\nstatic void RescanWallet(CWallet& wallet, const WalletRescanReserver& reserver, int64_t time_begin = TIMESTAMP_MIN, bool update = true)\n{\n    int64_t scanned_time = wallet.RescanFromTime(time_begin, reserver, update);\n    if (wallet.IsAbortingRescan()) {\n        throw JSONRPCError(RPC_MISC_ERROR, \"Rescan aborted by user.\");\n    } else if (scanned_time > time_begin) {\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Rescan was unable to fully rescan the blockchain. Some transactions may be missing.\");\n    }\n}\n\nUniValue importprivkey(const JSONRPCRequest& request)\n{\n    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n    CWallet* const pwallet = wallet.get();\n    if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {\n        return NullUniValue;\n    }\n\n    if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)\n        throw std::runtime_error(\n            RPCHelpMan{\"importprivkey\",\n                \"\\nAdds a private key (as returned by dumpprivkey) to your wallet. Requires a new wallet backup.\\n\"\n                \"Hint: use importmulti to import more than one private key.\\n\"\n            \"\\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\\n\"\n            \"may report that the imported key exists but related transactions are still missing, leading to temporarily incorrect\/bogus balances and unspent outputs until rescan completes.\\n\"\n            \"Note: Use \\\"getwalletinfo\\\" to query the scanning progress.\\n\",\n                {\n                    {\"privkey\", RPCArg::Type::STR, RPCArg::Optional::NO, \"The private key (see dumpprivkey)\"},\n                    {\"label\", RPCArg::Type::STR, \/* default *\/ \"current label if address exists, otherwise \\\"\\\"\", \"An optional label\"},\n                    {\"rescan\", RPCArg::Type::BOOL, \/* default *\/ \"true\", \"Rescan the wallet for transactions\"},\n                },\n                RPCResults{},\n                RPCExamples{\n            \"\\nDump a private key\\n\"\n            + HelpExampleCli(\"dumpprivkey\", \"\\\"myaddress\\\"\") +\n            \"\\nImport the private key with rescan\\n\"\n            + HelpExampleCli(\"importprivkey\", \"\\\"mykey\\\"\") +\n            \"\\nImport using a label and without rescan\\n\"\n            + HelpExampleCli(\"importprivkey\", \"\\\"mykey\\\" \\\"testing\\\" false\") +\n            \"\\nImport using default blank label and without rescan\\n\"\n            + HelpExampleCli(\"importprivkey\", \"\\\"mykey\\\" \\\"\\\" false\") +\n            \"\\nAs a JSON-RPC call\\n\"\n            + HelpExampleRpc(\"importprivkey\", \"\\\"mykey\\\", \\\"testing\\\", false\")\n                },\n            }.ToString());\n\n    if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Cannot import private keys to a wallet with private keys disabled\");\n    }\n\n    WalletRescanReserver reserver(pwallet);\n    bool fRescan = true;\n    {\n        auto locked_chain = pwallet->chain().lock();\n        LOCK(pwallet->cs_wallet);\n\n        EnsureWalletIsUnlocked(pwallet);\n\n        std::string strSecret = request.params[0].get_str();\n        std::string strLabel = \"\";\n        if (!request.params[1].isNull())\n            strLabel = request.params[1].get_str();\n\n        \/\/ Whether to perform rescan after import\n        if (!request.params[2].isNull())\n            fRescan = request.params[2].get_bool();\n\n        if (fRescan && pwallet->chain().havePruned()) {\n            \/\/ Exit early and print an error.\n            \/\/ If a block is pruned after this check, we will import the key(s),\n            \/\/ but fail the rescan with a generic error.\n            throw JSONRPCError(RPC_WALLET_ERROR, \"Rescan is disabled when blocks are pruned\");\n        }\n\n        if (fRescan && !reserver.reserve()) {\n            throw JSONRPCError(RPC_WALLET_ERROR, \"Wallet is currently rescanning. Abort existing rescan or wait.\");\n        }\n\n        CKey key = DecodeSecret(strSecret);\n        if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid private key encoding\");\n\n        CPubKey pubkey = key.GetPubKey();\n        assert(key.VerifyPubKey(pubkey));\n        CKeyID vchAddress = pubkey.GetID();\n        {\n            pwallet->MarkDirty();\n\n            \/\/ We don't know which corresponding address will be used;\n            \/\/ label all new addresses, and label existing addresses if a\n            \/\/ label was passed.\n            for (const auto& dest : GetAllDestinationsForKey(pubkey)) {\n                if (!request.params[1].isNull() || pwallet->mapAddressBook.count(dest) == 0) {\n                    pwallet->SetAddressBook(dest, strLabel, \"receive\");\n                }\n            }\n\n            \/\/ Don't throw error in case a key is already there\n            if (pwallet->HaveKey(vchAddress)) {\n                return NullUniValue;\n            }\n\n            \/\/ whenever a key is imported, we need to scan the whole chain\n            pwallet->UpdateTimeFirstKey(1);\n            pwallet->mapKeyMetadata[vchAddress].nCreateTime = 1;\n\n            if (!pwallet->AddKeyPubKey(key, pubkey)) {\n                throw JSONRPCError(RPC_WALLET_ERROR, \"Error adding key to wallet\");\n            }\n            pwallet->LearnAllRelatedScripts(pubkey);\n        }\n    }\n    if (fRescan) {\n        RescanWallet(*pwallet, reserver);\n    }\n\n    return NullUniValue;\n}\n\nUniValue abortrescan(const JSONRPCRequest& request)\n{\n    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n    CWallet* const pwallet = wallet.get();\n    if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {\n        return NullUniValue;\n    }\n\n    if (request.fHelp || request.params.size() > 0)\n        throw std::runtime_error(\n            RPCHelpMan{\"abortrescan\",\n                \"\\nStops current wallet rescan triggered by an RPC call, e.g. by an importprivkey call.\\n\"\n                \"Note: Use \\\"getwalletinfo\\\" to query the scanning progress.\\n\",\n                {},\n                RPCResults{},\n                RPCExamples{\n            \"\\nImport a private key\\n\"\n            + HelpExampleCli(\"importprivkey\", \"\\\"mykey\\\"\") +\n            \"\\nAbort the running wallet rescan\\n\"\n            + HelpExampleCli(\"abortrescan\", \"\") +\n            \"\\nAs a JSON-RPC call\\n\"\n            + HelpExampleRpc(\"abortrescan\", \"\")\n                },\n            }.ToString());\n\n    if (!pwallet->IsScanning() || pwallet->IsAbortingRescan()) return false;\n    pwallet->AbortRescan();\n    return true;\n}\n\nstatic void ImportAddress(CWallet*, const CTxDestination& dest, const std::string& strLabel);\nstatic void ImportScript(CWallet* const pwallet, const CScript& script, const std::string& strLabel, bool isRedeemScript) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)\n{\n    if (!isRedeemScript && ::IsMine(*pwallet, script) == ISMINE_SPENDABLE) {\n        throw JSONRPCError(RPC_WALLET_ERROR, \"The wallet already contains the private key for this address or script\");\n    }\n\n    pwallet->MarkDirty();\n\n    if (!pwallet->HaveWatchOnly(script) && !pwallet->AddWatchOnly(script, 0 \/* nCreateTime *\/)) {\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Error adding address to wallet\");\n    }\n\n    if (isRedeemScript) {\n        const CScriptID id(script);\n        if (!pwallet->HaveCScript(id) && !pwallet->AddCScript(script)) {\n            throw JSONRPCError(RPC_WALLET_ERROR, \"Error adding p2sh redeemScript to wallet\");\n        }\n        ImportAddress(pwallet, ScriptHash(id), strLabel);\n    } else {\n        CTxDestination destination;\n        if (ExtractDestination(script, destination)) {\n            pwallet->SetAddressBook(destination, strLabel, \"receive\");\n        }\n    }\n}\n\nstatic void ImportAddress(CWallet* const pwallet, const CTxDestination& dest, const std::string& strLabel) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)\n{\n    CScript script = GetScriptForDestination(dest);\n    ImportScript(pwallet, script, strLabel, false);\n    \/\/ add to address book or update label\n    if (IsValidDestination(dest))\n        pwallet->SetAddressBook(dest, strLabel, \"receive\");\n}\n\nUniValue importaddress(const JSONRPCRequest& request)\n{\n    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n    CWallet* const pwallet = wallet.get();\n    if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {\n        return NullUniValue;\n    }\n\n    if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)\n        throw std::runtime_error(\n            RPCHelpMan{\"importaddress\",\n                \"\\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\\n\"\n            \"\\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\\n\"\n            \"may report that the imported address exists but related transactions are still missing, leading to temporarily incorrect\/bogus balances and unspent outputs until rescan completes.\\n\"\n            \"If you have the full public key, you should call importpubkey instead of this.\\n\"\n            \"Hint: use importmulti to import more than one address.\\n\"\n            \"\\nNote: If you import a non-standard raw script in hex form, outputs sending to it will be treated\\n\"\n            \"as change, and not show up in many RPCs.\\n\"\n            \"Note: Use \\\"getwalletinfo\\\" to query the scanning progress.\\n\",\n                {\n                    {\"address\", RPCArg::Type::STR, RPCArg::Optional::NO, \"The ProInvestCoin address (or hex-encoded script)\"},\n                    {\"label\", RPCArg::Type::STR, \/* default *\/ \"\\\"\\\"\", \"An optional label\"},\n                    {\"rescan\", RPCArg::Type::BOOL, \/* default *\/ \"true\", \"Rescan the wallet for transactions\"},\n                    {\"p2sh\", RPCArg::Type::BOOL, \/* default *\/ \"false\", \"Add the P2SH version of the script as well\"},\n                },\n                RPCResults{},\n                RPCExamples{\n            \"\\nImport an address with rescan\\n\"\n            + HelpExampleCli(\"importaddress\", \"\\\"myaddress\\\"\") +\n            \"\\nImport using a label without rescan\\n\"\n            + HelpExampleCli(\"importaddress\", \"\\\"myaddress\\\" \\\"testing\\\" false\") +\n            \"\\nAs a JSON-RPC call\\n\"\n            + HelpExampleRpc(\"importaddress\", \"\\\"myaddress\\\", \\\"testing\\\", false\")\n                },\n            }.ToString());\n\n\n    std::string strLabel;\n    if (!request.params[1].isNull())\n        strLabel = request.params[1].get_str();\n\n    \/\/ Whether to perform rescan after import\n    bool fRescan = true;\n    if (!request.params[2].isNull())\n        fRescan = request.params[2].get_bool();\n\n    if (fRescan && pwallet->chain().havePruned()) {\n        \/\/ Exit early and print an error.\n        \/\/ If a block is pruned after this check, we will import the key(s),\n        \/\/ but fail the rescan with a generic error.\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Rescan is disabled when blocks are pruned\");\n    }\n\n    WalletRescanReserver reserver(pwallet);\n    if (fRescan && !reserver.reserve()) {\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Wallet is currently rescanning. Abort existing rescan or wait.\");\n    }\n\n    \/\/ Whether to import a p2sh version, too\n    bool fP2SH = false;\n    if (!request.params[3].isNull())\n        fP2SH = request.params[3].get_bool();\n\n    {\n        auto locked_chain = pwallet->chain().lock();\n        LOCK(pwallet->cs_wallet);\n\n        CTxDestination dest = DecodeDestination(request.params[0].get_str());\n        if (IsValidDestination(dest)) {\n            if (fP2SH) {\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Cannot use the p2sh flag with an address - use a script instead\");\n            }\n            ImportAddress(pwallet, dest, strLabel);\n        } else if (IsHex(request.params[0].get_str())) {\n            std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));\n            ImportScript(pwallet, CScript(data.begin(), data.end()), strLabel, fP2SH);\n        } else {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid ProInvestCoin address or script\");\n        }\n    }\n    if (fRescan)\n    {\n        RescanWallet(*pwallet, reserver);\n        {\n            auto locked_chain = pwallet->chain().lock();\n            LOCK(pwallet->cs_wallet);\n            pwallet->ReacceptWalletTransactions(*locked_chain);\n        }\n    }\n\n    return NullUniValue;\n}\n\nUniValue importprunedfunds(const JSONRPCRequest& request)\n{\n    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n    CWallet* const pwallet = wallet.get();\n    if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {\n        return NullUniValue;\n    }\n\n    if (request.fHelp || request.params.size() != 2)\n        throw std::runtime_error(\n            RPCHelpMan{\"importprunedfunds\",\n                \"\\nImports funds without rescan. Corresponding address or script must previously be included in wallet. Aimed towards pruned wallets. The end-user is responsible to import additional transactions that subsequently spend the imported outputs or rescan after the point in the blockchain the transaction is included.\\n\",\n                {\n                    {\"rawtransaction\", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, \"A raw transaction in hex funding an already-existing address in wallet\"},\n                    {\"txoutproof\", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, \"The hex output from gettxoutproof that contains the transaction\"},\n                },\n                RPCResults{},\n                RPCExamples{\"\"},\n            }.ToString()\n        );\n\n    CMutableTransaction tx;\n    if (!DecodeHexTx(tx, request.params[0].get_str()))\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"TX decode failed\");\n    uint256 hashTx = tx.GetHash();\n    CWalletTx wtx(pwallet, MakeTransactionRef(std::move(tx)));\n\n    CDataStream ssMB(ParseHexV(request.params[1], \"proof\"), SER_NETWORK, PROTOCOL_VERSION);\n    CMerkleBlock merkleBlock;\n    ssMB >> merkleBlock;\n\n    \/\/Search partial merkle tree in proof for our transaction and index in valid block\n    std::vector<uint256> vMatch;\n    std::vector<unsigned int> vIndex;\n    unsigned int txnIndex = 0;\n    if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) == merkleBlock.header.hashMerkleRoot) {\n\n        auto locked_chain = pwallet->chain().lock();\n        if (locked_chain->getBlockHeight(merkleBlock.header.GetHash()) == nullopt) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Block not found in chain\");\n        }\n\n        std::vector<uint256>::const_iterator it;\n        if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx))==vMatch.end()) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Transaction given doesn't exist in proof\");\n        }\n\n        txnIndex = vIndex[it - vMatch.begin()];\n    }\n    else {\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Something wrong with merkleblock\");\n    }\n\n    wtx.nIndex = txnIndex;\n    wtx.hashBlock = merkleBlock.header.GetHash();\n\n    auto locked_chain = pwallet->chain().lock();\n    LOCK(pwallet->cs_wallet);\n\n    if (pwallet->IsMine(*wtx.tx)) {\n        pwallet->AddToWallet(wtx, false);\n        return NullUniValue;\n    }\n\n    throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"No addresses in wallet correspond to included transaction\");\n}\n\nUniValue removeprunedfunds(const JSONRPCRequest& request)\n{\n    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n    CWallet* const pwallet = wallet.get();\n    if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {\n        return NullUniValue;\n    }\n\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            RPCHelpMan{\"removeprunedfunds\",\n                \"\\nDeletes the specified transaction from the wallet. Meant for use with pruned wallets and as a companion to importprunedfunds. This will affect wallet balances.\\n\",\n                {\n                    {\"txid\", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, \"The hex-encoded id of the transaction you are deleting\"},\n                },\n                RPCResults{},\n                RPCExamples{\n                    HelpExampleCli(\"removeprunedfunds\", \"\\\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\\\"\") +\n            \"\\nAs a JSON-RPC call\\n\"\n            + HelpExampleRpc(\"removeprunedfunds\", \"\\\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\\\"\")\n                },\n            }.ToString());\n\n    auto locked_chain = pwallet->chain().lock();\n    LOCK(pwallet->cs_wallet);\n\n    uint256 hash(ParseHashV(request.params[0], \"txid\"));\n    std::vector<uint256> vHash;\n    vHash.push_back(hash);\n    std::vector<uint256> vHashOut;\n\n    if (pwallet->ZapSelectTx(vHash, vHashOut) != DBErrors::LOAD_OK) {\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Could not properly delete the transaction.\");\n    }\n\n    if(vHashOut.empty()) {\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"Transaction does not exist in wallet.\");\n    }\n\n    return NullUniValue;\n}\n\nUniValue importpubkey(const JSONRPCRequest& request)\n{\n    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n    CWallet* const pwallet = wallet.get();\n    if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {\n        return NullUniValue;\n    }\n\n    if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)\n        throw std::runtime_error(\n            RPCHelpMan{\"importpubkey\",\n                \"\\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\\n\"\n                \"Hint: use importmulti to import more than one public key.\\n\"\n            \"\\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\\n\"\n            \"may report that the imported pubkey exists but related transactions are still missing, leading to temporarily incorrect\/bogus balances and unspent outputs until rescan completes.\\n\"\n            \"Note: Use \\\"getwalletinfo\\\" to query the scanning progress.\\n\",\n                {\n                    {\"pubkey\", RPCArg::Type::STR, RPCArg::Optional::NO, \"The hex-encoded public key\"},\n                    {\"label\", RPCArg::Type::STR, \/* default *\/ \"\\\"\\\"\", \"An optional label\"},\n                    {\"rescan\", RPCArg::Type::BOOL, \/* default *\/ \"true\", \"Rescan the wallet for transactions\"},\n                },\n                RPCResults{},\n                RPCExamples{\n            \"\\nImport a public key with rescan\\n\"\n            + HelpExampleCli(\"importpubkey\", \"\\\"mypubkey\\\"\") +\n            \"\\nImport using a label without rescan\\n\"\n            + HelpExampleCli(\"importpubkey\", \"\\\"mypubkey\\\" \\\"testing\\\" false\") +\n            \"\\nAs a JSON-RPC call\\n\"\n            + HelpExampleRpc(\"importpubkey\", \"\\\"mypubkey\\\", \\\"testing\\\", false\")\n                },\n            }.ToString());\n\n    std::string strLabel;\n    if (!request.params[1].isNull())\n        strLabel = request.params[1].get_str();\n\n    \/\/ Whether to perform rescan after import\n    bool fRescan = true;\n    if (!request.params[2].isNull())\n        fRescan = request.params[2].get_bool();\n\n    if (fRescan && pwallet->chain().havePruned()) {\n        \/\/ Exit early and print an error.\n        \/\/ If a block is pruned after this check, we will import the key(s),\n        \/\/ but fail the rescan with a generic error.\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Rescan is disabled when blocks are pruned\");\n    }\n\n    WalletRescanReserver reserver(pwallet);\n    if (fRescan && !reserver.reserve()) {\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Wallet is currently rescanning. Abort existing rescan or wait.\");\n    }\n\n    if (!IsHex(request.params[0].get_str()))\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Pubkey must be a hex string\");\n    std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));\n    CPubKey pubKey(data.begin(), data.end());\n    if (!pubKey.IsFullyValid())\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Pubkey is not a valid public key\");\n\n    {\n        auto locked_chain = pwallet->chain().lock();\n        LOCK(pwallet->cs_wallet);\n\n        for (const auto& dest : GetAllDestinationsForKey(pubKey)) {\n            ImportAddress(pwallet, dest, strLabel);\n        }\n        ImportScript(pwallet, GetScriptForRawPubKey(pubKey), strLabel, false);\n        pwallet->LearnAllRelatedScripts(pubKey);\n    }\n    if (fRescan)\n    {\n        RescanWallet(*pwallet, reserver);\n        {\n            auto locked_chain = pwallet->chain().lock();\n            LOCK(pwallet->cs_wallet);\n            pwallet->ReacceptWalletTransactions(*locked_chain);\n        }\n    }\n\n    return NullUniValue;\n}\n\n\nUniValue importwallet(const JSONRPCRequest& request)\n{\n    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n    CWallet* const pwallet = wallet.get();\n    if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {\n        return NullUniValue;\n    }\n\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            RPCHelpMan{\"importwallet\",\n                \"\\nImports keys from a wallet dump file (see dumpwallet). Requires a new wallet backup to include imported keys.\\n\"\n                \"Note: Use \\\"getwalletinfo\\\" to query the scanning progress.\\n\",\n                {\n                    {\"filename\", RPCArg::Type::STR, RPCArg::Optional::NO, \"The wallet file\"},\n                },\n                RPCResults{},\n                RPCExamples{\n            \"\\nDump the wallet\\n\"\n            + HelpExampleCli(\"dumpwallet\", \"\\\"test\\\"\") +\n            \"\\nImport the wallet\\n\"\n            + HelpExampleCli(\"importwallet\", \"\\\"test\\\"\") +\n            \"\\nImport using the json rpc call\\n\"\n            + HelpExampleRpc(\"importwallet\", \"\\\"test\\\"\")\n                },\n            }.ToString());\n\n    if (pwallet->chain().havePruned()) {\n        \/\/ Exit early and print an error.\n        \/\/ If a block is pruned after this check, we will import the key(s),\n        \/\/ but fail the rescan with a generic error.\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Importing wallets is disabled when blocks are pruned\");\n    }\n\n    WalletRescanReserver reserver(pwallet);\n    if (!reserver.reserve()) {\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Wallet is currently rescanning. Abort existing rescan or wait.\");\n    }\n\n    int64_t nTimeBegin = 0;\n    bool fGood = true;\n    {\n        auto locked_chain = pwallet->chain().lock();\n        LOCK(pwallet->cs_wallet);\n\n        EnsureWalletIsUnlocked(pwallet);\n\n        fsbridge::ifstream file;\n        file.open(request.params[0].get_str(), std::ios::in | std::ios::ate);\n        if (!file.is_open()) {\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Cannot open wallet dump file\");\n        }\n        Optional<int> tip_height = locked_chain->getHeight();\n        nTimeBegin = tip_height ? locked_chain->getBlockTime(*tip_height) : 0;\n\n        int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());\n        file.seekg(0, file.beg);\n\n        std::string sJson;\n        bool fJson = false;\n        \/\/ Use uiInterface.ShowProgress instead of pwallet.ShowProgress because pwallet.ShowProgress has a cancel button tied to AbortRescan which\n        \/\/ we don't want for this progress bar showing the import progress. uiInterface.ShowProgress does not have a cancel button.\n        pwallet->chain().showProgress(strprintf(\"%s \" + _(\"Importing...\"), pwallet->GetDisplayName()), 0, false); \/\/ show progress dialog in GUI\n        std::vector<std::tuple<CKey, int64_t, bool, std::string>> keys;\n        std::vector<std::pair<CScript, int64_t>> scripts;\n        while (file.good()) {\n            pwallet->chain().showProgress(\"\", std::max(1, std::min(50, (int)(((double)file.tellg() \/ (double)nFilesize) * 100))), false);\n            std::string line;\n            std::getline(file, line);\n            if (line.empty() || line[0] == '#')\n                continue;\n\n            if (line.rfind(\"# --- Begin JSON ---\", 0) == 0) {\n                fJson = true;\n                continue;\n            }\n            if (line.rfind(\"# --- End JSON ---\", 0) == 0) {\n                fJson = false;\n\n                if (!sJson.empty()) {\n                    std::string sError;\n                    UniValue inj;\n                    inj.read(sJson);\n\n                    if (!IsProInvestCoinWallet(pwallet)) {\n                        throw JSONRPCError(RPC_INVALID_PARAMETER, \"Legacy wallet\");\n                    }\n                    if (!GetProInvestCoinWallet(pwallet)->LoadJson(inj, sError)) {\n                        throw JSONRPCError(RPC_WALLET_ERROR, \"LoadJson failed \" + sError);\n                    }\n                }\n\n                continue;\n            }\n            if (fJson) {\n                sJson += line;\n                continue;\n            }\n\n            std::vector<std::string> vstr;\n            boost::split(vstr, line, boost::is_any_of(\" \"));\n            if (vstr.size() < 2) {\n                continue;\n            }\n            CKey key = DecodeSecret(vstr[0]);\n            if (key.IsValid()) {\n                int64_t nTime = DecodeDumpTime(vstr[1]);\n                std::string strLabel;\n                bool fLabel = true;\n                for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {\n                    if (vstr[nStr].front() == '#')\n                        break;\n                    if (vstr[nStr] == \"change=1\")\n                        fLabel = false;\n                    if (vstr[nStr] == \"reserve=1\")\n                        fLabel = false;\n                    if (vstr[nStr].substr(0,6) == \"label=\") {\n                        strLabel = DecodeDumpString(vstr[nStr].substr(6));\n                        fLabel = true;\n                    }\n                }\n                keys.push_back(std::make_tuple(key, nTime, fLabel, strLabel));\n            } else if(IsHex(vstr[0])) {\n                std::vector<unsigned char> vData(ParseHex(vstr[0]));\n                CScript script = CScript(vData.begin(), vData.end());\n                int64_t birth_time = DecodeDumpTime(vstr[1]);\n                scripts.push_back(std::pair<CScript, int64_t>(script, birth_time));\n            }\n        }\n        file.close();\n        \/\/ We now know whether we are importing private keys, so we can error if private keys are disabled\n        if (keys.size() > 0 && pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {\n            pwallet->chain().showProgress(\"\", 100, false); \/\/ hide progress dialog in GUI\n            throw JSONRPCError(RPC_WALLET_ERROR, \"Importing wallets is disabled when private keys are disabled\");\n        }\n        double total = (double)(keys.size() + scripts.size());\n        double progress = 0;\n        for (const auto& key_tuple : keys) {\n            pwallet->chain().showProgress(\"\", std::max(50, std::min(75, (int)((progress \/ total) * 100) + 50)), false);\n            const CKey& key = std::get<0>(key_tuple);\n            int64_t time = std::get<1>(key_tuple);\n            bool has_label = std::get<2>(key_tuple);\n            std::string label = std::get<3>(key_tuple);\n\n            CPubKey pubkey = key.GetPubKey();\n            assert(key.VerifyPubKey(pubkey));\n            CKeyID keyid = pubkey.GetID();\n            if (pwallet->HaveKey(keyid)) {\n                pwallet->WalletLogPrintf(\"Skipping import of %s (key already present)\\n\", EncodeDestination(PKHash(keyid)));\n                continue;\n            }\n            pwallet->WalletLogPrintf(\"Importing %s...\\n\", EncodeDestination(PKHash(keyid)));\n            if (!pwallet->AddKeyPubKey(key, pubkey)) {\n                fGood = false;\n                continue;\n            }\n            pwallet->mapKeyMetadata[keyid].nCreateTime = time;\n            if (has_label)\n                pwallet->SetAddressBook(PKHash(keyid), label, \"receive\");\n            nTimeBegin = std::min(nTimeBegin, time);\n            progress++;\n        }\n        for (const auto& script_pair : scripts) {\n            pwallet->chain().showProgress(\"\", std::max(50, std::min(75, (int)((progress \/ total) * 100) + 50)), false);\n            const CScript& script = script_pair.first;\n            int64_t time = script_pair.second;\n            CScriptID id(script);\n            if (pwallet->HaveCScript(id)) {\n                pwallet->WalletLogPrintf(\"Skipping import of %s (script already present)\\n\", HexStr(script));\n                continue;\n            }\n            if(!pwallet->AddCScript(script)) {\n                pwallet->WalletLogPrintf(\"Error importing script %s\\n\", HexStr(script));\n                fGood = false;\n                continue;\n            }\n            if (time > 0) {\n                pwallet->m_script_metadata[id].nCreateTime = time;\n                nTimeBegin = std::min(nTimeBegin, time);\n            }\n            progress++;\n        }\n        pwallet->chain().showProgress(\"\", 100, false); \/\/ hide progress dialog in GUI\n        pwallet->UpdateTimeFirstKey(nTimeBegin);\n    }\n    pwallet->chain().showProgress(\"\", 100, false); \/\/ hide progress dialog in GUI\n    RescanWallet(*pwallet, reserver, nTimeBegin, false \/* update *\/);\n    pwallet->MarkDirty();\n\n    if (!fGood)\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Error adding some keys\/scripts to wallet\");\n\n    return NullUniValue;\n}\n\nUniValue dumpprivkey(const JSONRPCRequest& request)\n{\n    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n    CWallet* const pwallet = wallet.get();\n    if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {\n        return NullUniValue;\n    }\n\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            RPCHelpMan{\"dumpprivkey\",\n                \"\\nReveals the private key corresponding to 'address'.\\n\"\n                \"Then the importprivkey can be used with this output\\n\",\n                {\n                    {\"address\", RPCArg::Type::STR, RPCArg::Optional::NO, \"The proinvestcoin address for the private key\"},\n                },\n                RPCResult{\n            \"\\\"key\\\"                (string) The private key\\n\"\n                },\n                RPCExamples{\n                    HelpExampleCli(\"dumpprivkey\", \"\\\"myaddress\\\"\")\n            + HelpExampleCli(\"importprivkey\", \"\\\"mykey\\\"\")\n            + HelpExampleRpc(\"dumpprivkey\", \"\\\"myaddress\\\"\")\n                },\n            }.ToString());\n\n    auto locked_chain = pwallet->chain().lock();\n    LOCK(pwallet->cs_wallet);\n\n    EnsureWalletIsUnlocked(pwallet);\n\n    std::string strAddress = request.params[0].get_str();\n    CTxDestination dest = DecodeDestination(strAddress);\n    if (!IsValidDestination(dest)) {\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid ProInvestCoin address\");\n    }\n\n    if (IsProInvestCoinWallet(pwallet)) {\n        if (dest.type() == typeid(CExtKeyPair)) {\n            CHDWallet *phdw = GetProInvestCoinWallet(pwallet);\n            CExtKeyPair ek = boost::get<CExtKeyPair>(dest);\n            CKeyID id = ek.GetID();\n            CStoredExtKey sek;\n            if (!phdw->GetExtKey(id, sek)) {\n                throw JSONRPCError(RPC_WALLET_ERROR, \"Private key for extaddress \" + strAddress + \" is not known\");\n            }\n            CExtKey58 eKey58;\n\n            if (0 != phdw->ExtKeyUnlock(&sek)) {\n                throw JSONRPCError(RPC_WALLET_ERROR, \"Unlock extaddress \" + strAddress + \" failed\");\n            }\n            if (!sek.kp.IsValidV()) {\n                throw JSONRPCError(RPC_WALLET_ERROR, \"Private key for extaddress \" + strAddress + \" is not known\");\n            }\n\n            eKey58.SetKeyV(sek.kp);\n            return eKey58.ToString();\n        }\n    }\n\n    auto keyid = GetKeyForDestination(*pwallet, dest);\n    if (keyid.IsNull()) {\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Address does not refer to a key\");\n    }\n    CKey vchSecret;\n    if (!pwallet->GetKey(keyid, vchSecret)) {\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Private key for address \" + strAddress + \" is not known\");\n    }\n    return EncodeSecret(vchSecret);\n}\n\n\nUniValue dumpwallet(const JSONRPCRequest& request)\n{\n    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n    CWallet* const pwallet = wallet.get();\n    if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {\n        return NullUniValue;\n    }\n\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            RPCHelpMan{\"dumpwallet\",\n                \"\\nDumps all wallet keys in a human-readable format to a server-side file. This does not allow overwriting existing files.\\n\"\n                \"Imported scripts are included in the dumpfile, but corresponding BIP173 addresses, etc. may not be added automatically by importwallet.\\n\"\n                \"Note that if your wallet contains keys which are not derived from your HD seed (e.g. imported keys), these are not covered by\\n\"\n                \"only backing up the seed itself, and must be backed up too (e.g. ensure you back up the whole dumpfile).\\n\",\n                {\n                    {\"filename\", RPCArg::Type::STR, RPCArg::Optional::NO, \"The filename with path (either absolute or relative to proinvestcoind)\"},\n                },\n                RPCResult{\n            \"{                           (json object)\\n\"\n            \"  \\\"filename\\\" : {        (string) The filename with full absolute path\\n\"\n            \"}\\n\"\n                },\n                RPCExamples{\n                    HelpExampleCli(\"dumpwallet\", \"\\\"test\\\"\")\n            + HelpExampleRpc(\"dumpwallet\", \"\\\"test\\\"\")\n                },\n            }.ToString());\n\n    auto locked_chain = pwallet->chain().lock();\n    LOCK(pwallet->cs_wallet);\n\n    EnsureWalletIsUnlocked(pwallet);\n\n    fs::path filepath = request.params[0].get_str();\n    filepath = fs::absolute(filepath);\n\n    \/* Prevent arbitrary files from being overwritten. There have been reports\n     * that users have overwritten wallet files this way:\n     * https:\/\/github.com\/bitcoin\/bitcoin\/issues\/9934\n     * It may also avoid other security issues.\n     *\/\n    if (fs::exists(filepath)) {\n        throw JSONRPCError(RPC_INVALID_PARAMETER, filepath.string() + \" already exists. If you are sure this is what you want, move it out of the way first\");\n    }\n\n    fsbridge::ofstream file;\n    file.open(filepath);\n    if (!file.is_open())\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"Cannot open wallet dump file\");\n\n    std::map<CKeyID, int64_t> mapKeyBirth;\n    const std::map<CKeyID, int64_t>& mapKeyPool = pwallet->GetAllReserveKeys();\n    pwallet->GetKeyBirthTimes(*locked_chain, mapKeyBirth);\n\n    std::set<CScriptID> scripts = pwallet->GetCScripts();\n\n    \/\/ sort time\/key pairs\n    std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;\n    for (const auto& entry : mapKeyBirth) {\n        vKeyBirth.push_back(std::make_pair(entry.second, entry.first));\n    }\n    mapKeyBirth.clear();\n    std::sort(vKeyBirth.begin(), vKeyBirth.end());\n\n    \/\/ produce output\n    file << strprintf(\"# Wallet dump created by ProInvestCoin %s\\n\", CLIENT_BUILD);\n    file << strprintf(\"# * Created on %s\\n\", FormatISO8601DateTime(GetTime()));\n    const Optional<int> tip_height = locked_chain->getHeight();\n    file << strprintf(\"# * Best block at time of backup was %i (%s),\\n\", tip_height.get_value_or(-1), tip_height ? locked_chain->getBlockHash(*tip_height).ToString() : \"(missing block hash)\");\n    file << strprintf(\"#   mined on %s\\n\", tip_height ? FormatISO8601DateTime(locked_chain->getBlockTime(*tip_height)) : \"(missing block time)\");\n    file << \"\\n\";\n\n    \/\/ add the base58check encoded extended master if the wallet uses HD\n    CKeyID seed_id = pwallet->GetHDChain().seed_id;\n    if (!seed_id.IsNull())\n    {\n        CKey seed;\n        if (pwallet->GetKey(seed_id, seed)) {\n            CExtKey masterKey;\n            masterKey.SetSeed(seed.begin(), seed.size());\n\n            file << \"# extended private masterkey: \" << EncodeExtKey(masterKey) << \"\\n\\n\";\n        }\n    }\n    for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {\n        const CKeyID &keyid = it->second;\n        std::string strTime = FormatISO8601DateTime(it->first);\n        std::string strAddr;\n        std::string strLabel;\n        CKey key;\n        if (pwallet->GetKey(keyid, key)) {\n            file << strprintf(\"%s %s \", EncodeSecret(key), strTime);\n            if (GetWalletAddressesForKey(pwallet, keyid, strAddr, strLabel)) {\n               file << strprintf(\"label=%s\", strLabel);\n            } else if (keyid == seed_id) {\n                file << \"hdseed=1\";\n            } else if (mapKeyPool.count(keyid)) {\n                file << \"reserve=1\";\n            } else if (pwallet->mapKeyMetadata[keyid].hdKeypath == \"s\") {\n                file << \"inactivehdseed=1\";\n            } else {\n                file << \"change=1\";\n            }\n            file << strprintf(\" # addr=%s%s\\n\", strAddr, (pwallet->mapKeyMetadata[keyid].has_key_origin ? \" hdkeypath=\"+WriteHDKeypath(pwallet->mapKeyMetadata[keyid].key_origin.path) : \"\"));\n        }\n    }\n\n    if (IsProInvestCoinWallet(pwallet)) {\n        std::string sError;\n        file << \"\\n# --- Begin JSON --- \\n\";\n\n        UniValue rv(UniValue::VOBJ);\n        if (!GetProInvestCoinWallet(pwallet)->DumpJson(rv, sError)) {\n            throw JSONRPCError(RPC_WALLET_ERROR, \"DumpJson failed \" + sError);\n        }\n        file << rv.write(1);\n\n        file << \"\\n# --- End JSON --- \\n\";\n    }\n\n    file << \"\\n\";\n    for (const CScriptID &scriptid : scripts) {\n        CScript script;\n        std::string create_time = \"0\";\n        std::string address = EncodeDestination(ScriptHash(scriptid));\n        \/\/ get birth times for scripts with metadata\n        auto it = pwallet->m_script_metadata.find(scriptid);\n        if (it != pwallet->m_script_metadata.end()) {\n            create_time = FormatISO8601DateTime(it->second.nCreateTime);\n        }\n        if(pwallet->GetCScript(scriptid, script)) {\n            file << strprintf(\"%s %s script=1\", HexStr(script.begin(), script.end()), create_time);\n            file << strprintf(\" # addr=%s\\n\", address);\n        }\n    }\n    file << \"\\n\";\n    file << \"# End of dump\\n\";\n    file.close();\n\n    UniValue reply(UniValue::VOBJ);\n    reply.pushKV(\"filename\", filepath.string());\n\n    return reply;\n}\n\nstruct ImportData\n{\n    \/\/ Input data\n    std::unique_ptr<CScript> redeemscript; \/\/!< Provided redeemScript; will be moved to `import_scripts` if relevant.\n    std::unique_ptr<CScript> witnessscript; \/\/!< Provided witnessScript; will be moved to `import_scripts` if relevant.\n\n    \/\/ Output data\n    std::set<CScript> import_scripts;\n    std::map<CKeyID, bool> used_keys; \/\/!< Import these private keys if available (the value indicates whether if the key is required for solvability)\n    std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> key_origins;\n};\n\nenum class ScriptContext\n{\n    TOP, \/\/!< Top-level scriptPubKey\n    P2SH, \/\/!< P2SH redeemScript\n    WITNESS_V0, \/\/!< P2WSH witnessScript\n};\n\n\/\/ Analyse the provided scriptPubKey, determining which keys and which redeem scripts from the ImportData struct are needed to spend it, and mark them as used.\n\/\/ Returns an error string, or the empty string for success.\nstatic std::string RecurseImportData(const CScript& script, ImportData& import_data, const ScriptContext script_ctx)\n{\n    \/\/ Use Solver to obtain script type and parsed pubkeys or hashes:\n    std::vector<std::vector<unsigned char>> solverdata;\n    txnouttype script_type = Solver(script, solverdata);\n\n    switch (script_type) {\n    case TX_PUBKEY: {\n        CPubKey pubkey(solverdata[0].begin(), solverdata[0].end());\n        import_data.used_keys.emplace(pubkey.GetID(), false);\n        return \"\";\n    }\n    case TX_PUBKEYHASH: {\n        CKeyID id = CKeyID(uint160(solverdata[0]));\n        import_data.used_keys[id] = true;\n        return \"\";\n    }\n    case TX_SCRIPTHASH: {\n        if (script_ctx == ScriptContext::P2SH) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Trying to nest P2SH inside another P2SH\");\n        if (script_ctx == ScriptContext::WITNESS_V0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Trying to nest P2SH inside a P2WSH\");\n        assert(script_ctx == ScriptContext::TOP);\n        CScriptID id = CScriptID(uint160(solverdata[0]));\n        auto subscript = std::move(import_data.redeemscript); \/\/ Remove redeemscript from import_data to check for superfluous script later.\n        if (!subscript) return \"missing redeemscript\";\n        if (CScriptID(*subscript) != id) return \"redeemScript does not match the scriptPubKey\";\n        import_data.import_scripts.emplace(*subscript);\n        return RecurseImportData(*subscript, import_data, ScriptContext::P2SH);\n    }\n    case TX_MULTISIG: {\n        for (size_t i = 1; i + 1< solverdata.size(); ++i) {\n            CPubKey pubkey(solverdata[i].begin(), solverdata[i].end());\n            import_data.used_keys.emplace(pubkey.GetID(), false);\n        }\n        return \"\";\n    }\n    case TX_WITNESS_V0_SCRIPTHASH: {\n        if (script_ctx == ScriptContext::WITNESS_V0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Trying to nest P2WSH inside another P2WSH\");\n        uint256 fullid(solverdata[0]);\n        CScriptID id;\n        CRIPEMD160().Write(fullid.begin(), fullid.size()).Finalize(id.begin());\n        auto subscript = std::move(import_data.witnessscript); \/\/ Remove redeemscript from import_data to check for superfluous script later.\n        if (!subscript) return \"missing witnessscript\";\n        if (CScriptID(*subscript) != id) return \"witnessScript does not match the scriptPubKey or redeemScript\";\n        if (script_ctx == ScriptContext::TOP) {\n            import_data.import_scripts.emplace(script); \/\/ Special rule for IsMine: native P2WSH requires the TOP script imported (see script\/ismine.cpp)\n        }\n        import_data.import_scripts.emplace(*subscript);\n        return RecurseImportData(*subscript, import_data, ScriptContext::WITNESS_V0);\n    }\n    case TX_WITNESS_V0_KEYHASH: {\n        if (script_ctx == ScriptContext::WITNESS_V0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Trying to nest P2WPKH inside P2WSH\");\n        CKeyID id = CKeyID(uint160(solverdata[0]));\n        import_data.used_keys[id] = true;\n        if (script_ctx == ScriptContext::TOP) {\n            import_data.import_scripts.emplace(script); \/\/ Special rule for IsMine: native P2WPKH requires the TOP script imported (see script\/ismine.cpp)\n        }\n        return \"\";\n    }\n    case TX_NULL_DATA:\n        return \"unspendable script\";\n    case TX_NONSTANDARD:\n    case TX_WITNESS_UNKNOWN:\n    default:\n        return \"unrecognized script\";\n    }\n}\n\nstatic UniValue ProcessImportLegacy(ImportData& import_data, std::map<CKeyID, CPubKey>& pubkey_map, std::map<CKeyID, CKey>& privkey_map, std::set<CScript>& script_pub_keys, bool& have_solving_data, const UniValue& data, std::vector<CKeyID>& ordered_pubkeys)\n{\n    UniValue warnings(UniValue::VARR);\n\n    \/\/ First ensure scriptPubKey has either a script or JSON with \"address\" string\n    const UniValue& scriptPubKey = data[\"scriptPubKey\"];\n    bool isScript = scriptPubKey.getType() == UniValue::VSTR;\n    if (!isScript && !(scriptPubKey.getType() == UniValue::VOBJ && scriptPubKey.exists(\"address\"))) {\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"scriptPubKey must be string with script or JSON with address string\");\n    }\n    const std::string& output = isScript ? scriptPubKey.get_str() : scriptPubKey[\"address\"].get_str();\n\n    \/\/ Optional fields.\n    const std::string& strRedeemScript = data.exists(\"redeemscript\") ? data[\"redeemscript\"].get_str() : \"\";\n    const std::string& witness_script_hex = data.exists(\"witnessscript\") ? data[\"witnessscript\"].get_str() : \"\";\n    const UniValue& pubKeys = data.exists(\"pubkeys\") ? data[\"pubkeys\"].get_array() : UniValue();\n    const UniValue& keys = data.exists(\"keys\") ? data[\"keys\"].get_array() : UniValue();\n    const bool internal = data.exists(\"internal\") ? data[\"internal\"].get_bool() : false;\n    const bool watchOnly = data.exists(\"watchonly\") ? data[\"watchonly\"].get_bool() : false;\n\n    if (data.exists(\"range\")) {\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"Range should not be specified for a non-descriptor import\");\n    }\n\n    \/\/ Generate the script and destination for the scriptPubKey provided\n    CScript script;\n    if (!isScript) {\n        CTxDestination dest = DecodeDestination(output);\n        if (!IsValidDestination(dest)) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid address \\\"\" + output + \"\\\"\");\n        }\n        script = GetScriptForDestination(dest);\n    } else {\n        if (!IsHex(output)) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid scriptPubKey \\\"\" + output + \"\\\"\");\n        }\n        std::vector<unsigned char> vData(ParseHex(output));\n        script = CScript(vData.begin(), vData.end());\n        CTxDestination dest;\n        if (!ExtractDestination(script, dest) && !internal) {\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Internal must be set to true for nonstandard scriptPubKey imports.\");\n        }\n    }\n    script_pub_keys.emplace(script);\n\n    \/\/ Parse all arguments\n    if (strRedeemScript.size()) {\n        if (!IsHex(strRedeemScript)) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid redeem script \\\"\" + strRedeemScript + \"\\\": must be hex string\");\n        }\n        auto parsed_redeemscript = ParseHex(strRedeemScript);\n        import_data.redeemscript = MakeUnique<CScript>(parsed_redeemscript.begin(), parsed_redeemscript.end());\n    }\n    if (witness_script_hex.size()) {\n        if (!IsHex(witness_script_hex)) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid witness script \\\"\" + witness_script_hex + \"\\\": must be hex string\");\n        }\n        auto parsed_witnessscript = ParseHex(witness_script_hex);\n        import_data.witnessscript = MakeUnique<CScript>(parsed_witnessscript.begin(), parsed_witnessscript.end());\n    }\n    for (size_t i = 0; i < pubKeys.size(); ++i) {\n        const auto& str = pubKeys[i].get_str();\n        if (!IsHex(str)) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Pubkey \\\"\" + str + \"\\\" must be a hex string\");\n        }\n        auto parsed_pubkey = ParseHex(str);\n        CPubKey pubkey(parsed_pubkey.begin(), parsed_pubkey.end());\n        if (!pubkey.IsFullyValid()) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Pubkey \\\"\" + str + \"\\\" is not a valid public key\");\n        }\n        pubkey_map.emplace(pubkey.GetID(), pubkey);\n        ordered_pubkeys.push_back(pubkey.GetID());\n    }\n    for (size_t i = 0; i < keys.size(); ++i) {\n        const auto& str = keys[i].get_str();\n        CKey key = DecodeSecret(str);\n        if (!key.IsValid()) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid private key encoding\");\n        }\n        CPubKey pubkey = key.GetPubKey();\n        CKeyID id = pubkey.GetID();\n        if (pubkey_map.count(id)) {\n            pubkey_map.erase(id);\n        }\n        privkey_map.emplace(id, key);\n    }\n\n\n    \/\/ Verify and process input data\n    have_solving_data = import_data.redeemscript || import_data.witnessscript || pubkey_map.size() || privkey_map.size();\n    if (have_solving_data) {\n        \/\/ Match up data in import_data with the scriptPubKey in script.\n        auto error = RecurseImportData(script, import_data, ScriptContext::TOP);\n\n        \/\/ Verify whether the watchonly option corresponds to the availability of private keys.\n        bool spendable = std::all_of(import_data.used_keys.begin(), import_data.used_keys.end(), [&](const std::pair<CKeyID, bool>& used_key){ return privkey_map.count(used_key.first) > 0; });\n        if (!watchOnly && !spendable) {\n            warnings.push_back(\"Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag.\");\n        }\n        if (watchOnly && spendable) {\n            warnings.push_back(\"All private keys are provided, outputs will be considered spendable. If this is intentional, do not specify the watchonly flag.\");\n        }\n\n        \/\/ Check that all required keys for solvability are provided.\n        if (error.empty()) {\n            for (const auto& require_key : import_data.used_keys) {\n                if (!require_key.second) continue; \/\/ Not a required key\n                if (pubkey_map.count(require_key.first) == 0 && privkey_map.count(require_key.first) == 0) {\n                    error = \"some required keys are missing\";\n                }\n            }\n        }\n\n        if (!error.empty()) {\n            warnings.push_back(\"Importing as non-solvable: \" + error + \". If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.\");\n            import_data = ImportData();\n            pubkey_map.clear();\n            privkey_map.clear();\n            have_solving_data = false;\n        } else {\n            \/\/ RecurseImportData() removes any relevant redeemscript\/witnessscript from import_data, so we can use that to discover if a superfluous one was provided.\n            if (import_data.redeemscript) warnings.push_back(\"Ignoring redeemscript as this is not a P2SH script.\");\n            if (import_data.witnessscript) warnings.push_back(\"Ignoring witnessscript as this is not a (P2SH-)P2WSH script.\");\n            for (auto it = privkey_map.begin(); it != privkey_map.end(); ) {\n                auto oldit = it++;\n                if (import_data.used_keys.count(oldit->first) == 0) {\n                    warnings.push_back(\"Ignoring irrelevant private key.\");\n                    privkey_map.erase(oldit);\n                }\n            }\n            for (auto it = pubkey_map.begin(); it != pubkey_map.end(); ) {\n                auto oldit = it++;\n                auto key_data_it = import_data.used_keys.find(oldit->first);\n                if (key_data_it == import_data.used_keys.end() || !key_data_it->second) {\n                    warnings.push_back(\"Ignoring public key \\\"\" + HexStr(oldit->first) + \"\\\" as it doesn't appear inside P2PKH or P2WPKH.\");\n                    pubkey_map.erase(oldit);\n                }\n            }\n        }\n    }\n\n    return warnings;\n}\n\nstatic UniValue ProcessImportDescriptor(ImportData& import_data, std::map<CKeyID, CPubKey>& pubkey_map, std::map<CKeyID, CKey>& privkey_map, std::set<CScript>& script_pub_keys, bool& have_solving_data, const UniValue& data, std::vector<CKeyID>& ordered_pubkeys)\n{\n    UniValue warnings(UniValue::VARR);\n\n    const std::string& descriptor = data[\"desc\"].get_str();\n    FlatSigningProvider keys;\n    auto parsed_desc = Parse(descriptor, keys, \/* require_checksum = *\/ true);\n    if (!parsed_desc) {\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Descriptor is invalid\");\n    }\n\n    have_solving_data = parsed_desc->IsSolvable();\n    const bool watch_only = data.exists(\"watchonly\") ? data[\"watchonly\"].get_bool() : false;\n\n    int64_t range_start = 0, range_end = 0;\n    if (!parsed_desc->IsRange() && data.exists(\"range\")) {\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"Range should not be specified for an un-ranged descriptor\");\n    } else if (parsed_desc->IsRange()) {\n        if (!data.exists(\"range\")) {\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Descriptor is ranged, please specify the range\");\n        }\n        std::tie(range_start, range_end) = ParseDescriptorRange(data[\"range\"]);\n    }\n\n    const UniValue& priv_keys = data.exists(\"keys\") ? data[\"keys\"].get_array() : UniValue();\n\n    \/\/ Expand all descriptors to get public keys and scripts.\n    \/\/ TODO: get private keys from descriptors too\n    for (int i = range_start; i <= range_end; ++i) {\n        FlatSigningProvider out_keys;\n        std::vector<CScript> scripts_temp;\n        parsed_desc->Expand(i, keys, scripts_temp, out_keys);\n        std::copy(scripts_temp.begin(), scripts_temp.end(), std::inserter(script_pub_keys, script_pub_keys.end()));\n        for (const auto& key_pair : out_keys.pubkeys) {\n            ordered_pubkeys.push_back(key_pair.first);\n        }\n\n        for (const auto& x : out_keys.scripts) {\n            import_data.import_scripts.emplace(x.second);\n        }\n\n        std::copy(out_keys.pubkeys.begin(), out_keys.pubkeys.end(), std::inserter(pubkey_map, pubkey_map.end()));\n        import_data.key_origins.insert(out_keys.origins.begin(), out_keys.origins.end());\n    }\n\n    for (size_t i = 0; i < priv_keys.size(); ++i) {\n        const auto& str = priv_keys[i].get_str();\n        CKey key = DecodeSecret(str);\n        if (!key.IsValid()) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid private key encoding\");\n        }\n        CPubKey pubkey = key.GetPubKey();\n        CKeyID id = pubkey.GetID();\n\n        \/\/ Check if this private key corresponds to a public key from the descriptor\n        if (!pubkey_map.count(id)) {\n            warnings.push_back(\"Ignoring irrelevant private key.\");\n        } else {\n            privkey_map.emplace(id, key);\n        }\n    }\n\n    \/\/ Check if all the public keys have corresponding private keys in the import for spendability.\n    \/\/ This does not take into account threshold multisigs which could be spendable without all keys.\n    \/\/ Thus, threshold multisigs without all keys will be considered not spendable here, even if they are,\n    \/\/ perhaps triggering a false warning message. This is consistent with the current wallet IsMine check.\n    bool spendable = std::all_of(pubkey_map.begin(), pubkey_map.end(),\n        [&](const std::pair<CKeyID, CPubKey>& used_key) {\n            return privkey_map.count(used_key.first) > 0;\n        }) && std::all_of(import_data.key_origins.begin(), import_data.key_origins.end(),\n        [&](const std::pair<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& entry) {\n            return privkey_map.count(entry.first) > 0;\n        });\n    if (!watch_only && !spendable) {\n        warnings.push_back(\"Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag.\");\n    }\n    if (watch_only && spendable) {\n        warnings.push_back(\"All private keys are provided, outputs will be considered spendable. If this is intentional, do not specify the watchonly flag.\");\n    }\n\n    return warnings;\n}\n\nstatic UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)\n{\n    UniValue warnings(UniValue::VARR);\n    UniValue result(UniValue::VOBJ);\n\n    try {\n        const bool internal = data.exists(\"internal\") ? data[\"internal\"].get_bool() : false;\n        \/\/ Internal addresses should not have a label\n        if (internal && data.exists(\"label\")) {\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Internal addresses should not have a label\");\n        }\n        const std::string& label = data.exists(\"label\") ? data[\"label\"].get_str() : \"\";\n        const bool add_keypool = data.exists(\"keypool\") ? data[\"keypool\"].get_bool() : false;\n\n        \/\/ Add to keypool only works with privkeys disabled\n        if (add_keypool && !pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Keys can only be imported to the keypool when private keys are disabled\");\n        }\n\n        ImportData import_data;\n        std::map<CKeyID, CPubKey> pubkey_map;\n        std::map<CKeyID, CKey> privkey_map;\n        std::set<CScript> script_pub_keys;\n        std::vector<CKeyID> ordered_pubkeys;\n        bool have_solving_data;\n\n        if (data.exists(\"scriptPubKey\") && data.exists(\"desc\")) {\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Both a descriptor and a scriptPubKey should not be provided.\");\n        } else if (data.exists(\"scriptPubKey\")) {\n            warnings = ProcessImportLegacy(import_data, pubkey_map, privkey_map, script_pub_keys, have_solving_data, data, ordered_pubkeys);\n        } else if (data.exists(\"desc\")) {\n            warnings = ProcessImportDescriptor(import_data, pubkey_map, privkey_map, script_pub_keys, have_solving_data, data, ordered_pubkeys);\n        } else {\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Either a descriptor or scriptPubKey must be provided.\");\n        }\n\n        \/\/ If private keys are disabled, abort if private keys are being imported\n        if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !privkey_map.empty()) {\n            throw JSONRPCError(RPC_WALLET_ERROR, \"Cannot import private keys to a wallet with private keys disabled\");\n        }\n\n        \/\/ Check whether we have any work to do\n        for (const CScript& script : script_pub_keys) {\n            if (::IsMine(*pwallet, script) & ISMINE_SPENDABLE) {\n                throw JSONRPCError(RPC_WALLET_ERROR, \"The wallet already contains the private key for this address or script (\\\"\" + HexStr(script.begin(), script.end()) + \"\\\")\");\n            }\n        }\n\n        \/\/ All good, time to import\n        pwallet->MarkDirty();\n        for (const auto& entry : import_data.import_scripts) {\n            if (!pwallet->HaveCScript(CScriptID(entry)) && !pwallet->AddCScript(entry)) {\n                throw JSONRPCError(RPC_WALLET_ERROR, \"Error adding script to wallet\");\n             }\n         }\n         for (const auto& entry : privkey_map) {\n             const CKey& key = entry.second;\n             CPubKey pubkey = key.GetPubKey();\n             const CKeyID& id = entry.first;\n             assert(key.VerifyPubKey(pubkey));\n             pwallet->mapKeyMetadata[id].nCreateTime = timestamp;\n             \/\/ If the private key is not present in the wallet, insert it.\n             if (!pwallet->HaveKey(id) && !pwallet->AddKeyPubKey(key, pubkey)) {\n                 throw JSONRPCError(RPC_WALLET_ERROR, \"Error adding key to wallet\");\n             }\n             pwallet->UpdateTimeFirstKey(timestamp);\n        }\n        for (const auto& entry : import_data.key_origins) {\n            pwallet->AddKeyOrigin(entry.second.first, entry.second.second);\n        }\n        for (const CKeyID& id : ordered_pubkeys) {\n            auto entry = pubkey_map.find(id);\n            if (entry == pubkey_map.end()) {\n                continue;\n            }\n             const CPubKey& pubkey = entry->second;\n             CPubKey temp;\n             if (!pwallet->GetPubKey(id, temp) && !pwallet->AddWatchOnly(GetScriptForRawPubKey(pubkey), timestamp)) {\n                throw JSONRPCError(RPC_WALLET_ERROR, \"Error adding address to wallet\");\n            }\n            pwallet->mapKeyMetadata[id].nCreateTime = timestamp;\n\n            \/\/ Add to keypool only works with pubkeys\n            if (add_keypool) {\n                pwallet->AddKeypoolPubkey(pubkey, internal);\n            }\n        }\n\n        for (const CScript& script : script_pub_keys) {\n            if (!have_solving_data || !(::IsMine(*pwallet, script) & ISMINE_SPENDABLE)) { \/\/ Always call AddWatchOnly for non-solvable watch-only, so that watch timestamp gets updated\n                if (!pwallet->AddWatchOnly(script, timestamp)) {\n                    throw JSONRPCError(RPC_WALLET_ERROR, \"Error adding address to wallet\");\n                }\n            }\n            CTxDestination dest;\n            ExtractDestination(script, dest);\n            if (!internal && IsValidDestination(dest)) {\n                pwallet->SetAddressBook(dest, label, \"receive\");\n            }\n        }\n\n        result.pushKV(\"success\", UniValue(true));\n    } catch (const UniValue& e) {\n        result.pushKV(\"success\", UniValue(false));\n        result.pushKV(\"error\", e);\n    } catch (...) {\n        result.pushKV(\"success\", UniValue(false));\n\n        result.pushKV(\"error\", JSONRPCError(RPC_MISC_ERROR, \"Missing required fields\"));\n    }\n    if (warnings.size()) result.pushKV(\"warnings\", warnings);\n    return result;\n}\n\nstatic int64_t GetImportTimestamp(const UniValue& data, int64_t now)\n{\n    if (data.exists(\"timestamp\")) {\n        const UniValue& timestamp = data[\"timestamp\"];\n        if (timestamp.isNum()) {\n            return timestamp.get_int64();\n        } else if (timestamp.isStr() && timestamp.get_str() == \"now\") {\n            return now;\n        }\n        throw JSONRPCError(RPC_TYPE_ERROR, strprintf(\"Expected number or \\\"now\\\" timestamp value for key. got type %s\", uvTypeName(timestamp.type())));\n    }\n    throw JSONRPCError(RPC_TYPE_ERROR, \"Missing required timestamp field for key\");\n}\n\nUniValue importmulti(const JSONRPCRequest& mainRequest)\n{\n    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(mainRequest);\n    CWallet* const pwallet = wallet.get();\n    if (!EnsureWalletIsAvailable(pwallet, mainRequest.fHelp)) {\n        return NullUniValue;\n    }\n\n    if (mainRequest.fHelp || mainRequest.params.size() < 1 || mainRequest.params.size() > 2)\n        throw std::runtime_error(\n            RPCHelpMan{\"importmulti\",\n                \"\\nImport addresses\/scripts (with private or public keys, redeem script (P2SH)), optionally rescanning the blockchain from the earliest creation time of the imported scripts. Requires a new wallet backup.\\n\"\n                \"If an address\/script is imported without all of the private keys required to spend from that address, it will be watchonly. The 'watchonly' option must be set to true in this case or a warning will be returned.\\n\"\n                \"Conversely, if all the private keys are provided and the address\/script is spendable, the watchonly option must be set to false, or a warning will be returned.\\n\"\n            \"\\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\\n\"\n            \"may report that the imported keys, addresses or scripts exist but related transactions are still missing.\\n\"\n            \"Note: Use \\\"getwalletinfo\\\" to query the scanning progress.\\n\",\n                {\n                    {\"requests\", RPCArg::Type::ARR, RPCArg::Optional::NO, \"Data to be imported\",\n                        {\n                            {\"\", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, \"\",\n                                {\n                                    {\"desc\", RPCArg::Type::STR, RPCArg::Optional::OMITTED, \"Descriptor to import. If using descriptor, do not also provide address\/scriptPubKey, scripts, or pubkeys\"},\n                                    {\"scriptPubKey\", RPCArg::Type::STR, RPCArg::Optional::NO, \"Type of scriptPubKey (string for script, json for address). Should not be provided if using a descriptor\",\n                                        \/* oneline_description *\/ \"\", {\"\\\"<script>\\\" | { \\\"address\\\":\\\"<address>\\\" }\", \"string \/ json\"}\n                                    },\n                                    {\"timestamp\", RPCArg::Type::NUM, RPCArg::Optional::NO, \"Creation time of the key in seconds since epoch (Jan 1 1970 GMT),\\n\"\n        \"                                                              or the string \\\"now\\\" to substitute the current synced blockchain time. The timestamp of the oldest\\n\"\n        \"                                                              key will determine how far back blockchain rescans need to begin for missing wallet transactions.\\n\"\n        \"                                                              \\\"now\\\" can be specified to bypass scanning, for keys which are known to never have been used, and\\n\"\n        \"                                                              0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest key\\n\"\n        \"                                                              creation time of all keys being imported by the importmulti call will be scanned.\",\n                                        \/* oneline_description *\/ \"\", {\"timestamp | \\\"now\\\"\", \"integer \/ string\"}\n                                    },\n                                    {\"redeemscript\", RPCArg::Type::STR, RPCArg::Optional::OMITTED, \"Allowed only if the scriptPubKey is a P2SH or P2SH-P2WSH address\/scriptPubKey\"},\n                                    {\"witnessscript\", RPCArg::Type::STR, RPCArg::Optional::OMITTED, \"Allowed only if the scriptPubKey is a P2SH-P2WSH or P2WSH address\/scriptPubKey\"},\n                                    {\"pubkeys\", RPCArg::Type::ARR, \/* default *\/ \"empty array\", \"Array of strings giving pubkeys to import. They must occur in P2PKH or P2WPKH scripts. They are not required when the private key is also provided (see the \\\"keys\\\" argument).\",\n                                        {\n                                            {\"pubKey\", RPCArg::Type::STR, RPCArg::Optional::OMITTED, \"\"},\n                                        }\n                                    },\n                                    {\"keys\", RPCArg::Type::ARR, \/* default *\/ \"empty array\", \"Array of strings giving private keys to import. The corresponding public keys must occur in the output or redeemscript.\",\n                                        {\n                                            {\"key\", RPCArg::Type::STR, RPCArg::Optional::OMITTED, \"\"},\n                                        }\n                                    },\n                                    {\"range\", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED, \"If a ranged descriptor is used, this specifies the end or the range (in the form [begin,end]) to import\"},\n                                    {\"internal\", RPCArg::Type::BOOL, \/* default *\/ \"false\", \"Stating whether matching outputs should be treated as not incoming payments (also known as change)\"},\n                                    {\"watchonly\", RPCArg::Type::BOOL, \/* default *\/ \"false\", \"Stating whether matching outputs should be considered watchonly.\"},\n                                    {\"label\", RPCArg::Type::STR, \/* default *\/ \"''\", \"Label to assign to the address, only allowed with internal=false\"},\n                                    {\"keypool\", RPCArg::Type::BOOL, \/* default *\/ \"false\", \"Stating whether imported public keys should be added to the keypool for when users request new addresses. Only allowed when wallet private keys are disabled\"},\n                                },\n                            },\n                        },\n                        \"\\\"requests\\\"\"},\n                    {\"options\", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED_NAMED_ARG, \"\",\n                        {\n                            {\"rescan\", RPCArg::Type::BOOL, \/* default *\/ \"true\", \"Stating if should rescan the blockchain after all imports\"},\n                        },\n                        \"\\\"options\\\"\"},\n                },\n                RPCResult{\n            \"\\nResponse is an array with the same size as the input that has the execution result :\\n\"\n            \"  [{\\\"success\\\": true}, {\\\"success\\\": true, \\\"warnings\\\": [\\\"Ignoring irrelevant private key\\\"]}, {\\\"success\\\": false, \\\"error\\\": {\\\"code\\\": -1, \\\"message\\\": \\\"Internal Server Error\\\"}}, ...]\\n\"\n                },\n                RPCExamples{\n                    HelpExampleCli(\"importmulti\", \"'[{ \\\"scriptPubKey\\\": { \\\"address\\\": \\\"<my address>\\\" }, \\\"timestamp\\\":1455191478 }, \"\n                                          \"{ \\\"scriptPubKey\\\": { \\\"address\\\": \\\"<my 2nd address>\\\" }, \\\"label\\\": \\\"example 2\\\", \\\"timestamp\\\": 1455191480 }]'\") +\n                    HelpExampleCli(\"importmulti\", \"'[{ \\\"scriptPubKey\\\": { \\\"address\\\": \\\"<my address>\\\" }, \\\"timestamp\\\":1455191478 }]' '{ \\\"rescan\\\": false}'\")\n                },\n            }.ToString()\n        );\n\n\n    RPCTypeCheck(mainRequest.params, {UniValue::VARR, UniValue::VOBJ});\n\n    const UniValue& requests = mainRequest.params[0];\n\n    \/\/Default options\n    bool fRescan = true;\n\n    if (!mainRequest.params[1].isNull()) {\n        const UniValue& options = mainRequest.params[1];\n\n        if (options.exists(\"rescan\")) {\n            fRescan = options[\"rescan\"].get_bool();\n        }\n    }\n\n    WalletRescanReserver reserver(pwallet);\n    if (fRescan && !reserver.reserve()) {\n        throw JSONRPCError(RPC_WALLET_ERROR, \"Wallet is currently rescanning. Abort existing rescan or wait.\");\n    }\n\n    int64_t now = 0;\n    bool fRunScan = false;\n    int64_t nLowestTimestamp = 0;\n    UniValue response(UniValue::VARR);\n    {\n        auto locked_chain = pwallet->chain().lock();\n        LOCK(pwallet->cs_wallet);\n        EnsureWalletIsUnlocked(pwallet);\n\n        \/\/ Verify all timestamps are present before importing any keys.\n        const Optional<int> tip_height = locked_chain->getHeight();\n        now = tip_height ? locked_chain->getBlockMedianTimePast(*tip_height) : 0;\n        for (const UniValue& data : requests.getValues()) {\n            GetImportTimestamp(data, now);\n        }\n\n        const int64_t minimumTimestamp = 1;\n\n        if (fRescan && tip_height) {\n            nLowestTimestamp = locked_chain->getBlockTime(*tip_height);\n        } else {\n            fRescan = false;\n        }\n\n        for (const UniValue& data : requests.getValues()) {\n            const int64_t timestamp = std::max(GetImportTimestamp(data, now), minimumTimestamp);\n            const UniValue result = ProcessImport(pwallet, data, timestamp);\n            response.push_back(result);\n\n            if (!fRescan) {\n                continue;\n            }\n\n            \/\/ If at least one request was successful then allow rescan.\n            if (result[\"success\"].get_bool()) {\n                fRunScan = true;\n            }\n\n            \/\/ Get the lowest timestamp.\n            if (timestamp < nLowestTimestamp) {\n                nLowestTimestamp = timestamp;\n            }\n        }\n    }\n    if (fRescan && fRunScan && requests.size()) {\n        int64_t scannedTime = pwallet->RescanFromTime(nLowestTimestamp, reserver, true \/* update *\/);\n        {\n            auto locked_chain = pwallet->chain().lock();\n            LOCK(pwallet->cs_wallet);\n            pwallet->ReacceptWalletTransactions(*locked_chain);\n        }\n\n        if (pwallet->IsAbortingRescan()) {\n            throw JSONRPCError(RPC_MISC_ERROR, \"Rescan aborted by user.\");\n        }\n        if (scannedTime > nLowestTimestamp) {\n            std::vector<UniValue> results = response.getValues();\n            response.clear();\n            response.setArray();\n            size_t i = 0;\n            for (const UniValue& request : requests.getValues()) {\n                \/\/ If key creation date is within the successfully scanned\n                \/\/ range, or if the import result already has an error set, let\n                \/\/ the result stand unmodified. Otherwise replace the result\n                \/\/ with an error message.\n                if (scannedTime <= GetImportTimestamp(request, now) || results.at(i).exists(\"error\")) {\n                    response.push_back(results.at(i));\n                } else {\n                    UniValue result = UniValue(UniValue::VOBJ);\n                    result.pushKV(\"success\", UniValue(false));\n                    result.pushKV(\n                        \"error\",\n                        JSONRPCError(\n                            RPC_MISC_ERROR,\n                            strprintf(\"Rescan failed for key with creation timestamp %d. There was an error reading a \"\n                                      \"block from time %d, which is after or within %d seconds of key creation, and \"\n                                      \"could contain transactions pertaining to the key. As a result, transactions \"\n                                      \"and coins using this key may not appear in the wallet. This error could be \"\n                                      \"caused by pruning or data corruption (see proinvestcoind log for details) and could \"\n                                      \"be dealt with by downloading and rescanning the relevant blocks (see -reindex \"\n                                      \"and -rescan options).\",\n                                GetImportTimestamp(request, now), scannedTime - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW)));\n                    response.push_back(std::move(result));\n                }\n                ++i;\n            }\n        }\n    }\n\n    return response;\n}\n","avg_line_length":46.6612702366,"max_line_length":333,"alphanum_fraction":0.6036590248,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3436,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/--------------------------------------------------------------------------------\n\/\/ \u30ec\u30a4\u30a2\u30a6\u30c8\u7528\u9244\u6a4b\u30b8\u30e7\u30a4\u30f3\u30c8\u97f3\u30b8\u30a7\u30cd\u30ec\u30fc\u30bf\n\/\/ [RailwayBridgeJoint.cpp]\n\/\/ Copyright (c) 2020 Ayanosuke(Maison de DCC)\n\/\/ https:\/\/desktopstation.net\/bb\/index.php\n\/\/\n\/\/ This software is released under the MIT License.\n\/\/ http:\/\/opensource.org\/licenses\/mit-license.php\n\/\/--------------------------------------------------------------------------------\n#include \"RailwayBridge.h\"\n#include \"jointini.h\"\n#include \"cds.h\"\n\nvoid RailWayBridgeState( JOINT ad ){\n  static Cds TrainSensor(0,1,2,200,500);    \/\/ CDS\u30bb\u30f3\u30b5\u306e\u30bb\u30c3\u30c8\u30a2\u30c3\u30d7\n  static int state = ST_INIT;\n  static int TrainVal = 0;\n  static int wait = 0;\n  int re;\n  \n  switch(state){\n    case ST_INIT:\nSerial.println(\"Railway:ST_INIT\");\n                  TrainVal = ad.RollingStock[0];\n                  digitalWrite(LED_BUILTIN,LOW);\n                  state = ST_TRSENSING;\n                  break;\n    case ST_TRSENSING:      \/\/ \u8eca\u4e21\u4fb5\u5165\u30c1\u30a7\u30c3\u30af\n                   re = TrainSensor.statechk(LOW); \/\/ \u660e\u308b\u3055\u95be\u5024LOW\u3067\u30c1\u30a7\u30c3\u30af\n                  if( re == 0 )\n                    break;\n                  else {        \n                    TrainSensor.Reset();\n                    gSound_played = re;\n                    wait = ad.TrainWait;\n                    state = ST_STTRAINWAIT;\n                  }\n                  break;\n    case ST_STTRAINWAIT:\n                  digitalWrite(LED_BUILTIN,HIGH);           \/\/ \u518d\u751f\u4e2d\n                  wait--;\n                  if(wait<=0)\n                    state = ST_TRAIN;\n                  break;   \n    case ST_TRAIN:\n                  if(TrainVal < 1){\n                    state  = ST_INIT;\n                    break;  \n                  } \n                  TrainVal--;\n                  state = ST_WHEELBASE1;\n                  break;                  \n    case ST_WHEELBASE1:             \/\/ \u6700\u521d\u306e\u53f0\u8eca\u306e\u30ac\u30bf\u30f3\u30ac\u30bf\u30f3\n                  ImaAdpcmPlay();   \/\/ \u30b8\u30e7\u30a4\u30f3\u30c8\u97f3\u767a\u751f\u4f9d\u983c\n                  wait = ad.ChassisWheelbase[0][gSound_played];  \/\/\u53f0\u8eca\u9593\u9694\u6642\u9593\u3092\u7b97\u51fa\nSerial.println(gSound_played);\nSerial.println(wait);\n                  state = ST_CHASSILENWAIT;\n                  break;  \n    case  ST_CHASSILENWAIT:\n                  wait--;\n                  if(wait<=0)\n                    state = ST_WHEELBASE2;\n                  break;                      \n    case ST_WHEELBASE2:             \/\/ 2\u756a\u76ee\u306e\u53f0\u8eca\u306e\u30ac\u30bf\u30f3\u30ac\u30bf\u30f3\n                  ImaAdpcmPlay();   \/\/ \u30b8\u30e7\u30a4\u30f3\u30c8\u97f3\u767a\u751f\u4f9d\u983c\n                  if( ad.BogieWheelbaseNum[0] == 3){          \/\/ \u53f0\u8eca\u304c3\u53f0\u3042\u308b\uff1f\n                    wait = ad.ChassisWheelbase[0][gSound_played];  \/\/\u53f0\u8eca\u9593\u9694\u6642\u9593\u3092\u7b97\u51fa\n Serial.println(wait);\n                    state = ST_CHASSILENWAIT2;\n                    break;\n                  }\n                  wait = ad.VehicleSpace[0][gSound_played];  \/\/\u8eca\u4e21\u9593\u9694\u6642\u9593\u3092\u7b97\u51fa\n\n                  state = ST_TRAINWAIT;                       \n                  break;  \n\n    case  ST_CHASSILENWAIT2:\n                  wait--;\n                  if(wait<=0)\n                    state = ST_WHEELBASE3;\n                  break;    \n\n    case ST_WHEELBASE3:             \/\/ 3\u756a\u76ee\u306e\u53f0\u8eca\u306e\u30ac\u30bf\u30f3\u30ac\u30bf\u30f3\n                  ImaAdpcmPlay();   \/\/ \u30b8\u30e7\u30a4\u30f3\u30c8\u97f3\u767a\u751f\u4f9d\u983c\n                  wait = ad.VehicleSpace[0][gSound_played];  \/\/\u8eca\u4e21\u611f\u899a\u6642\u9593\u3092\u7b97\u51fa\n                  state = ST_TRAINWAIT;                       \n                  break;  \n    case ST_TRAINWAIT:\n                  wait--;\n                  if(wait<=0)\n                    state = ST_TRAIN;\n                  break;                         \n    default:\n                  break;\n  }\n}\n","avg_line_length":35.0612244898,"max_line_length":82,"alphanum_fraction":0.4234575087,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":659,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"lib\/mainwindow.h\"\r\n#include <QApplication>\r\n#include <time.h>\r\n\r\nMainWindow* w = nullptr;\r\n\r\nint isMandelbrot(QVector2D z, int n, QVector2D point) {\r\n    if (n >= 0) {\r\n        if (z.length() <= 2) {\r\n            float x = z.x() * z.x() - z.y() * z.y() + point.x();\r\n            float y = 2 * z.x() * z.y() + point.y();\r\n            z.setX(x);\r\n            z.setY(y);\r\n            return isMandelbrot(z, n - 1, point);\r\n        } else {\r\n            return n;\r\n        }\r\n    }\r\n    return n;\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n    QApplication a(argc, argv);\r\n    w = new MandelbrotWindow(isMandelbrot);\r\n    w->show();\r\n\r\n    a.exec();\r\n}\r\n","avg_line_length":22.724137931,"max_line_length":65,"alphanum_fraction":0.4628224583,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3302,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":158.0,"content":"\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2016 Torus Knot Software Ltd\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreShaderProgramWriter.h\"\n#include \"OgreShaderProgram.h\"\n\nnamespace Ogre {\nnamespace RTShader {\n\n\/\/-----------------------------------------------------------------------\nvoid ProgramWriter::writeProgramTitle(std::ostream& os, Program* program)\n{\n    os << \"\/\/-----------------------------------------------------------------------------\" << std::endl;\n    os << \"\/\/ Program Type: \";\n    switch(program->getType())\n    {\n    case GPT_VERTEX_PROGRAM:\n        os << \"Vertex shader\";\n        break;\n    case GPT_FRAGMENT_PROGRAM:\n        os << \"Fragment shader\";\n        break;\n    case GPT_GEOMETRY_PROGRAM:\n        os << \"Geometry shader\";\n        break;  \n    default:\n        break;\n    }\n    os << std::endl;\n    os << \"\/\/ Language: \" <<  getTargetLanguage() << std::endl;\n    os << \"\/\/ Created by Ogre RT Shader Generator. All rights reserved.\" << std::endl;\n    os << \"\/\/-----------------------------------------------------------------------------\" << std::endl;\n}\n\n\/\/-----------------------------------------------------------------------\nvoid ProgramWriter::writeUniformParametersTitle(std::ostream& os, Program* program)\n{\n    os << \"\/\/-----------------------------------------------------------------------------\" << std::endl;\n    os << \"\/\/                         GLOBAL PARAMETERS\" << std::endl;\n    os << \"\/\/-----------------------------------------------------------------------------\" << std::endl;\n}\n\/\/-----------------------------------------------------------------------\nvoid ProgramWriter::writeFunctionTitle(std::ostream& os, Function* function)\n{\n    os << \"\/\/-----------------------------------------------------------------------------\" << std::endl;\n    os << \"\/\/ Function Name: \" <<  function->getName() << std::endl;\n    os << \"\/\/ Function Desc: \" <<  function->getDescription() << std::endl;\n    os << \"\/\/-----------------------------------------------------------------------------\" << std::endl;\n}\n\n}\n}\n","avg_line_length":43.4473684211,"max_line_length":105,"alphanum_fraction":0.5069654755,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":56,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\r\nint main(int argc, char ** argv)\r\n{\r\n\treturn 0;\r\n}\r\n\r\n","avg_line_length":8.0,"max_line_length":33,"alphanum_fraction":0.5178571429,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7273,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":2.0,"content":"\/\/\n\/\/ PatternFormatter.cpp\n\/\/\n\/\/ Library: Foundation\n\/\/ Package: Logging\n\/\/ Module:  PatternFormatter\n\/\/\n\/\/ Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.\n\/\/ and Contributors.\n\/\/\n\/\/ SPDX-License-Identifier:\tBSL-1.0\n\/\/\n\n\n#include \"Poco\/PatternFormatter.h\"\n#include \"Poco\/Message.h\"\n#include \"Poco\/NumberFormatter.h\"\n#include \"Poco\/DateTimeFormat.h\"\n#include \"Poco\/DateTimeFormatter.h\"\n#include \"Poco\/DateTime.h\"\n#include \"Poco\/Timestamp.h\"\n#include \"Poco\/Timezone.h\"\n#include \"Poco\/Environment.h\"\n#include \"Poco\/NumberParser.h\"\n#include \"Poco\/StringTokenizer.h\"\n\n\nnamespace Poco {\n\n\nconst std::string PatternFormatter::PROP_PATTERN = \"pattern\";\nconst std::string PatternFormatter::PROP_TIMES   = \"times\";\nconst std::string PatternFormatter::PROP_PRIORITY_NAMES = \"priorityNames\";\n\n\nPatternFormatter::PatternFormatter():\n\t_localTime(false)\n{\n\tparsePriorityNames();\n}\n\n\nPatternFormatter::PatternFormatter(const std::string& format):\n\t_localTime(false),\n\t_pattern(format)\n{\n\tparsePriorityNames();\n\tparsePattern();\n}\n\n\nPatternFormatter::~PatternFormatter()\n{\n}\n\n\nvoid PatternFormatter::format(const Message& msg, std::string& text)\n{\n\tTimestamp timestamp = msg.getTime();\n\tbool localTime = _localTime;\n\tif (localTime)\n\t{\n\t\ttimestamp += Timezone::utcOffset()*Timestamp::resolution();\n\t\ttimestamp += Timezone::dst()*Timestamp::resolution();\n\t}\n\tDateTime dateTime = timestamp;\n\tfor (auto& pa:_patternActions)\n\t{\n\t\ttext.append(pa.prepend);\n\t\tswitch (pa.key)\n\t\t{\n\t\tcase 's': text.append(msg.getSource()); break;\n\t\tcase 't': text.append(msg.getText()); break;\n\t\tcase 'l': NumberFormatter::append(text, (int) msg.getPriority()); break;\n\t\tcase 'p': text.append(getPriorityName((int) msg.getPriority())); break;\n\t\tcase 'q': text += getPriorityName((int) msg.getPriority()).at(0); break;\n\t\tcase 'P': NumberFormatter::append(text, msg.getPid()); break;\n\t\tcase 'T': text.append(msg.getThread()); break;\n\t\tcase 'I': NumberFormatter::append(text, msg.getTid()); break;\n\t\tcase 'N': text.append(Environment::nodeName()); break;\n\t\tcase 'U': text.append(msg.getSourceFile() ? msg.getSourceFile() : \"\"); break;\n\t\tcase 'u': NumberFormatter::append(text, msg.getSourceLine()); break;\n\t\tcase 'w': text.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()], 0, 3); break;\n\t\tcase 'W': text.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()]); break;\n\t\tcase 'b': text.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1], 0, 3); break;\n\t\tcase 'B': text.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1]); break;\n\t\tcase 'd': NumberFormatter::append0(text, dateTime.day(), 2); break;\n\t\tcase 'e': NumberFormatter::append(text, dateTime.day()); break;\n\t\tcase 'f': NumberFormatter::append(text, dateTime.day(), 2); break;\n\t\tcase 'm': NumberFormatter::append0(text, dateTime.month(), 2); break;\n\t\tcase 'n': NumberFormatter::append(text, dateTime.month()); break;\n\t\tcase 'o': NumberFormatter::append(text, dateTime.month(), 2); break;\n\t\tcase 'y': NumberFormatter::append0(text, dateTime.year() % 100, 2); break;\n\t\tcase 'Y': NumberFormatter::append0(text, dateTime.year(), 4); break;\n\t\tcase 'H': NumberFormatter::append0(text, dateTime.hour(), 2); break;\n\t\tcase 'h': NumberFormatter::append0(text, dateTime.hourAMPM(), 2); break;\n\t\tcase 'a': text.append(dateTime.isAM() ? \"am\" : \"pm\"); break;\n\t\tcase 'A': text.append(dateTime.isAM() ? \"AM\" : \"PM\"); break;\n\t\tcase 'M': NumberFormatter::append0(text, dateTime.minute(), 2); break;\n\t\tcase 'S': NumberFormatter::append0(text, dateTime.second(), 2); break;\n\t\tcase 'i': NumberFormatter::append0(text, dateTime.millisecond(), 3); break;\n\t\tcase 'c': NumberFormatter::append(text, dateTime.millisecond()\/100); break;\n\t\tcase 'F': NumberFormatter::append0(text, dateTime.millisecond()*1000 + dateTime.microsecond(), 6); break;\n\t\tcase 'z': text.append(DateTimeFormatter::tzdISO(localTime ? Timezone::tzd() : DateTimeFormatter::UTC)); break;\n\t\tcase 'Z': text.append(DateTimeFormatter::tzdRFC(localTime ? Timezone::tzd() : DateTimeFormatter::UTC)); break;\n\t\tcase 'E': NumberFormatter::append(text, msg.getTime().epochTime()); break;\n\t\tcase 'v':\n\t\t\tif (pa.length > msg.getSource().length())\t\/\/append spaces\n\t\t\t\ttext.append(msg.getSource()).append(pa.length - msg.getSource().length(), ' ');\n\t\t\telse if (pa.length && pa.length < msg.getSource().length()) \/\/ crop\n\t\t\t\ttext.append(msg.getSource(), msg.getSource().length()-pa.length, pa.length);\n\t\t\telse\n\t\t\t\ttext.append(msg.getSource());\n\t\t\tbreak;\n\t\tcase 'x':\n\t\t\ttry\n\t\t\t{\n\t\t\t\ttext.append(msg[pa.property]);\n\t\t\t}\n\t\t\tcatch (...)\n\t\t\t{\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tif (!localTime)\n\t\t\t{\n\t\t\t\tlocalTime = true;\n\t\t\t\ttimestamp += Timezone::utcOffset()*Timestamp::resolution();\n\t\t\t\ttimestamp += Timezone::dst()*Timestamp::resolution();\n\t\t\t\tdateTime = timestamp;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\nvoid PatternFormatter::parsePattern()\n{\n\t_patternActions.clear();\n\tstd::string::const_iterator it  = _pattern.begin();\n\tstd::string::const_iterator end = _pattern.end();\n\tPatternAction endAct;\n\twhile (it != end)\n\t{\n\t\tif (*it == '%')\n\t\t{\n\t\t\tif (++it != end)\n\t\t\t{\n\t\t\t\tPatternAction act;\n\t\t\t\tact.prepend = endAct.prepend;\n\t\t\t\tendAct.prepend.clear();\n\n\t\t\t\tif (*it == '[')\n\t\t\t\t{\n\t\t\t\t\tact.key = 'x';\n\t\t\t\t\t++it;\n\t\t\t\t\tstd::string prop;\n\t\t\t\t\twhile (it != end && *it != ']') prop += *it++;\n\t\t\t\t\tif (it == end) --it;\n\t\t\t\t\tact.property = prop;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tact.key = *it;\n\t\t\t\t\tif ((it + 1) != end && *(it + 1) == '[')\n\t\t\t\t\t{\n\t\t\t\t\t\tit += 2;\n\t\t\t\t\t\tstd::string number;\n\t\t\t\t\t\twhile (it != end && *it != ']') number += *it++;\n\t\t\t\t\t\tif (it == end) --it;\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tact.length = NumberParser::parse(number);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (...)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t_patternActions.push_back(act);\n\t\t\t\t++it;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tendAct.prepend += *it++;\n\t\t}\n\t}\n\tif (endAct.prepend.size())\n\t{\n\t\t_patternActions.push_back(endAct);\n\t}\n}\n\n\t\nvoid PatternFormatter::setProperty(const std::string& name, const std::string& value)\n{\n\tif (name == PROP_PATTERN)\n\t{\n\t\t_pattern = value;\n\t\tparsePattern();\n\t}\n\telse if (name == PROP_TIMES)\n\t{\n\t\t_localTime = (value == \"local\");\n\t}\n\telse if (name == PROP_PRIORITY_NAMES)\n\t{\n\t\t_priorityNames = value;\n\t\tparsePriorityNames();\n\t}\n\telse \n\t{\n\t\tFormatter::setProperty(name, value);\n\t}\n}\n\n\nstd::string PatternFormatter::getProperty(const std::string& name) const\n{\n\tif (name == PROP_PATTERN)\n\t\treturn _pattern;\n\telse if (name == PROP_TIMES)\n\t\treturn _localTime ? \"local\" : \"UTC\";\n\telse if (name == PROP_PRIORITY_NAMES)\n\t\treturn _priorityNames;\n\telse\n\t\treturn Formatter::getProperty(name);\n}\n\n\nnamespace\n{\n\tstatic std::string priorities[] = \n\t{\n\t\t\"\",\n\t\t\"Fatal\",\n\t\t\"Critical\",\n\t\t\"Error\",\n\t\t\"Warning\",\n\t\t\"Notice\",\n\t\t\"Information\",\n\t\t\"Debug\",\n\t\t\"Trace\"\n\t};\n}\n\n\nvoid PatternFormatter::parsePriorityNames()\n{\n\tfor (int i = 0; i <= 8; i++)\n\t{\n\t\t_priorities[i] = priorities[i];\n\t}\n\tif (!_priorityNames.empty())\n\t{\n\t\tStringTokenizer st(_priorityNames, \",;\", StringTokenizer::TOK_TRIM);\n\t\tif (st.count() == 8)\n\t\t{\n\t\t\tfor (int i = 1; i <= 8; i++)\n\t\t\t{\n\t\t\t\t_priorities[i] = st[i - 1];\n\t\t\t}\n\t\t}\n\t\telse throw Poco::SyntaxException(\"priorityNames property must specify a comma-separated list of 8 property names\");\n\t}\n}\n\n\nconst std::string& PatternFormatter::getPriorityName(int prio)\n{\n\tpoco_assert (1 <= prio && prio <= 8);\t\n\treturn priorities[prio];\n}\n\n\n} \/\/ namespace Poco\n","avg_line_length":26.0681003584,"max_line_length":117,"alphanum_fraction":0.6517255603,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2743,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/* TEMPLATE GENERATED TESTCASE FILE\r\nFilename: CWE401_Memory_Leak__new_array_char_53a.cpp\r\nLabel Definition File: CWE401_Memory_Leak__new_array.label.xml\r\nTemplate File: sources-sinks-53a.tmpl.cpp\r\n*\/\r\n\/*\r\n * @description\r\n * CWE: 401 Memory Leak\r\n * BadSource:  Allocate data using new[]\r\n * GoodSource: Point data to a stack buffer\r\n * Sinks:\r\n *    GoodSink: call delete[] on data\r\n *    BadSink : no deallocation of data\r\n * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files\r\n *\r\n * *\/\r\n\r\n#include \"std_testcase.h\"\r\n\r\nnamespace CWE401_Memory_Leak__new_array_char_53\r\n{\r\n\r\n#ifndef OMITBAD\r\n\r\n\/* bad function declaration *\/\r\nvoid bad_sink_b(char * data);\r\n\r\nvoid bad()\r\n{\r\n    char * data;\r\n    data = NULL;\r\n    \/* POTENTIAL FLAW: Allocate memory on the heap *\/\r\n    data = new char[100];\r\n    \/* Initialize and make use of data *\/\r\n    strcpy(data, \"A String\");\r\n    printLine(data);\r\n    bad_sink_b(data);\r\n}\r\n\r\n#endif \/* OMITBAD *\/\r\n\r\n#ifndef OMITGOOD\r\n\r\n\/* goodG2B uses the GoodSource with the BadSink *\/\r\nvoid goodG2B_sink_b(char * data);\r\n\r\nstatic void goodG2B()\r\n{\r\n    char * data;\r\n    data = NULL;\r\n    {\r\n        \/* FIX: Use memory allocated on the stack *\/\r\n        char data_goodbuf[100];\r\n        data = data_goodbuf;\r\n        \/* Initialize and make use of data *\/\r\n        strcpy(data, \"A String\");\r\n        printLine(data);\r\n    }\r\n    goodG2B_sink_b(data);\r\n}\r\n\r\n\/* goodB2G uses the BadSource with the GoodSink *\/\r\nvoid goodB2G_sink_b(char * data);\r\n\r\nstatic void goodB2G()\r\n{\r\n    char * data;\r\n    data = NULL;\r\n    \/* POTENTIAL FLAW: Allocate memory on the heap *\/\r\n    data = new char[100];\r\n    \/* Initialize and make use of data *\/\r\n    strcpy(data, \"A String\");\r\n    printLine(data);\r\n    goodB2G_sink_b(data);\r\n}\r\n\r\nvoid good()\r\n{\r\n    goodG2B();\r\n    goodB2G();\r\n}\r\n\r\n#endif \/* OMITGOOD *\/\r\n\r\n} \/\/ close namespace\r\n\r\n\/* Below is the main(). It is only used when building this testcase on\r\n   its own for testing or for building a binary to use in testing binary\r\n   analysis tools. It is not used when compiling all the testcases as one\r\n   application, which is how source code analysis tools are tested. *\/\r\n\r\n#ifdef INCLUDEMAIN\r\n\r\nusing namespace CWE401_Memory_Leak__new_array_char_53; \/\/ so that we can use good and bad easily\r\n\r\nint main(int argc, char * argv[])\r\n{\r\n    \/* seed randomness *\/\r\n    srand( (unsigned)time(NULL) );\r\n#ifndef OMITGOOD\r\n    printLine(\"Calling good()...\");\r\n    good();\r\n    printLine(\"Finished good()\");\r\n#endif \/* OMITGOOD *\/\r\n#ifndef OMITBAD\r\n    printLine(\"Calling bad()...\");\r\n    bad();\r\n    printLine(\"Finished bad()\");\r\n#endif \/* OMITBAD *\/\r\n    return 0;\r\n}\r\n\r\n#endif\r\n","avg_line_length":24.0614035088,"max_line_length":157,"alphanum_fraction":0.6412686839,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1188,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n* Problema: Preenchimento de Vetor I\n* https:\/\/www.urionlinejudge.com.br\/judge\/pt\/problems\/view\/1173\n*\/\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cstdlib>\n#include <numeric>\n#include <string>\n#include <sstream>\n#include <iomanip>\n#include <locale>\n#include <bitset>\n#include <map>\n#include <vector>\n#include <queue>\n#include <stack>\n#include <algorithm>\n#include <cmath>\n\n#define INF 0x3F3F3F3F\n#define PI 3.14159265358979323846\n#define EPS 1e-10\n\n#define file_in(file) freopen(file\".in\", \"r\", stdin)\n#define file_out(file) freopen(file\".out\", \"w+\", stdout)\n#define vet_i(var, tipo, lin, col, inic) vector< vector< tipo > > var (lin, vector< tipo > (col, inic))\n#define vet_d(tipo) vector< vector< tipo > >\n#define lli long long int\n#define llu unsigned long long int\n#define fore(var, inicio, final) for(int var=inicio; var<final; var++)\n#define forec(var, inicio, final, incremento) for(int var=inicio; var<final; incremento)\n#define forit(it, var) for( it = var.begin(); it != var.end(); it++ )\n\nusing namespace std;\n\nint main(){\n\n    int v;\n    cin>>v;\n\n    fore(i, 0, 10){\n        cout<<\"N[\"<<i<<\"] = \"<<v<<endl;\n        v = v * 2;\n    }\n\n    return 0;\n}\n","avg_line_length":23.76,"max_line_length":103,"alphanum_fraction":0.6658249158,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":346,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include \"GXCullState.h\"\n\nGXCullState::GXCullState(const GXCullMode &cullMode_)\n{\n\tset(cullMode_);\n}\n\nvoid GXCullState::set(const GXCullMode &cullMode_)\n{\n\tthis->cullMode\t\t= cullMode_;\n}\n\nvoid GXCullState::setMode(const GXCullMode &cullMode_)\n{\n\tthis->cullMode\t\t= cullMode_;\n}\n\nconst GXCullMode &GXCullState::getMode() const\n{\n\treturn cullMode;\n}","avg_line_length":16.4761904762,"max_line_length":54,"alphanum_fraction":0.7485549133,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":297,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":10.0,"content":"\/\/ stdafx.cpp : source file that includes just the standard includes\r\n\/\/ HelloWorld.pch will be the pre-compiled header\r\n\/\/ stdafx.obj will contain the pre-compiled type information\r\n\r\n#include \"stdafx.h\"\r\n\r\n\/\/ TODO: reference any additional headers you need in STDAFX.H\r\n\/\/ and not in this file\r\n","avg_line_length":33.0,"max_line_length":69,"alphanum_fraction":0.7441077441,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2379,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC0-1.0"],"max_stars_count":81.0,"content":"#include <bits\/stdc++.h>\nusing namespace std;\nconst int NUM_OF_ALPHABETS = 26;\n\/\/ Construction the Trie node structure\nstruct TrieNodeDS\n{\nstruct TrieNodeDS *childNode[NUM_OF_ALPHABETS];\n\/\/ nodeEnd is true if the node represents\n\/\/ the ending of a word\nbool nodeEnd;\n};\n\/\/ New NULL Trie node is returned\nstruct TrieNodeDS *getNode(void)\n{\nstruct TrieNodeDS *nodePointer = new TrieNodeDS;\nnodePointer->nodeEnd = false;\nfor (int i = 0; i < NUM_OF_ALPHABETS; i++)\nnodePointer->childNode[i] = NULL;\nreturn nodePointer;\n}\n\/\/Insert Algorithm in Trie\nvoid insertFunc(struct TrieNodeDS *headRoot, string searchKey)\n{\nstruct TrieNodeDS *crawlPointer = headRoot;\nfor (int i = 0; i < searchKey.length(); i++)\n{\nint head = searchKey[i] - 'a';\nif (!crawlPointer->childNode[head])\ncrawlPointer->childNode[head] = getNode();\ncrawlPointer = crawlPointer->childNode[head];\n}\n\/\/ End of node is marked as true; to point that the search will end here\ncrawlPointer->nodeEnd = true;\n}\n\/\/Search Algorithm in Trie\nbool searchFunc(struct TrieNodeDS * headRoot, string searchKey)\n{\nstruct TrieNodeDS *crawlPointer = headRoot;\nfor (int i = 0; i < searchKey.length(); i++)\n{\nint head = searchKey[i] - 'a';\nif (!crawlPointer->childNode[head])\nreturn false;\ncrawlPointer = crawlPointer->childNode[head];\n}\nreturn (crawlPointer != NULL && crawlPointer->nodeEnd);\n}\n\/\/ Main Function for execution\nint main()\n{\n\/\/ we will use only lowercase characters to keep consistency\nstring arrayWords[] = {\"educba\", \"provides\", \"best\",\n\"online\", \"education\", \"proven\",\n\"by\", \"quality\" };\nint n = sizeof(arrayWords)\/sizeof(arrayWords[0]);\nstruct TrieNodeDS * headRoot = getNode();\n\/\/ Construct trie\nfor (int i = 0; i < n; i++)\ninsertFunc(headRoot, arrayWords[i]);\ncout<< \"---------List of words:-----------\\n\";\nfor (int i = 0; i < n; i++)\ncout<< arrayWords[i] << \"\\n\";\n\/\/ Search for different words\ncout<< \"---------Search starts:-----------\\n\";\ncout<< \"Since 'edu' is not present as a word, but only present by sub-characters and 'u' in 'edu' doesn't represent end of node, the output will be No\\n\";\nsearchFunc(headRoot, \"edu\")? cout << \"edu Found: Yes\\n\" :\ncout << \"edu Found: No\\n\";\ncout<< \"Since 'education' is present as a word, 'n' in 'education' represents the end of node, the output will be Yes \\n\";\nsearchFunc(headRoot, \"education\")? cout << \"education Found: Yes\\n\" :\ncout << \"education Found: No\\n\";\nreturn 0;\n}\n","avg_line_length":32.5890410959,"max_line_length":154,"alphanum_fraction":0.6977721732,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2053,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":35.0,"content":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ UNSUPPORTED: c++98, c++03\n\n#include <cstddef>\n#include <type_traits>\n\n\/\/ max_align_t is a trivial standard-layout type whose alignment requirement\n\/\/   is at least as great as that of every scalar type\n\n#include <stdio.h>\n#include \"test_macros.h\"\n\nint main(int, char**)\n{\n\n#if TEST_STD_VER > 17\n\/\/  P0767\n    static_assert(std::is_trivial<std::max_align_t>::value,\n                  \"std::is_trivial<std::max_align_t>::value\");\n    static_assert(std::is_standard_layout<std::max_align_t>::value,\n                  \"std::is_standard_layout<std::max_align_t>::value\");\n#else\n    static_assert(std::is_pod<std::max_align_t>::value,\n                  \"std::is_pod<std::max_align_t>::value\");\n#endif\n    static_assert((std::alignment_of<std::max_align_t>::value >=\n                  std::alignment_of<long long>::value),\n                  \"std::alignment_of<std::max_align_t>::value >= \"\n                  \"std::alignment_of<long long>::value\");\n    static_assert(std::alignment_of<std::max_align_t>::value >=\n                  std::alignment_of<long double>::value,\n                  \"std::alignment_of<std::max_align_t>::value >= \"\n                  \"std::alignment_of<long double>::value\");\n    static_assert(std::alignment_of<std::max_align_t>::value >=\n                  std::alignment_of<void*>::value,\n                  \"std::alignment_of<std::max_align_t>::value >= \"\n                  \"std::alignment_of<void*>::value\");\n\n#ifdef __STDCPP_DEFAULT_NEW_ALIGNMENT__\n    static_assert(std::alignment_of<std::max_align_t>::value <=\n                  __STDCPP_DEFAULT_NEW_ALIGNMENT__,\n                  \"max_align_t alignment is no larger than new alignment\");\n#endif\n\n  return 0;\n}\n","avg_line_length":38.0185185185,"max_line_length":80,"alphanum_fraction":0.5854846566,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10514,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":27.0,"content":"#include <Python.h>\n#include \"numpy\/ndarrayobject.h\"\n#include \"opencv2\/core\/core.hpp\"\n\nstatic PyObject* opencv_error = 0;\n\n\/\/ === FAIL MESSAGE ====================================================================================================\n\nstatic int failmsg(const char *fmt, ...)\n{\n    char str[1000];\n\n    va_list ap;\n    va_start(ap, fmt);\n    vsnprintf(str, sizeof(str), fmt, ap);\n    va_end(ap);\n\n    PyErr_SetString(PyExc_TypeError, str);\n    return 0;\n}\n\nstruct ArgInfo\n{\n    const char * name;\n    bool outputarg;\n    \/\/ more fields may be added if necessary\n\n    ArgInfo(const char * name_, bool outputarg_)\n        : name(name_)\n        , outputarg(outputarg_) {}\n\n    \/\/ to match with older pyopencv_to function signature\n    operator const char *() const { return name; }\n};\n\n\/\/ === THREADING =======================================================================================================\n\nclass PyAllowThreads\n{\npublic:\n    PyAllowThreads() : _state(PyEval_SaveThread()) {}\n    ~PyAllowThreads()\n    {\n        PyEval_RestoreThread(_state);\n    }\nprivate:\n    PyThreadState* _state;\n};\n\nclass PyEnsureGIL\n{\npublic:\n    PyEnsureGIL() : _state(PyGILState_Ensure()) {}\n    ~PyEnsureGIL()\n    {\n        PyGILState_Release(_state);\n    }\nprivate:\n    PyGILState_STATE _state;\n};\n\n\/\/ === ERROR HANDLING ==================================================================================================\n\n#define ERRWRAP2(expr) \\\ntry \\\n{ \\\n    PyAllowThreads allowThreads; \\\n    expr; \\\n} \\\ncatch (const cv::Exception &e) \\\n{ \\\n    PyErr_SetString(opencv_error, e.what()); \\\n    return 0; \\\n}\n\n\/\/ === USING NAMESPACE CV ==============================================================================================\n\nusing namespace cv;\n\n\/\/ === NUMPY ALLOCATOR =================================================================================================\n\nclass NumpyAllocator : public MatAllocator\n{\npublic:\n    NumpyAllocator() { stdAllocator = Mat::getStdAllocator(); }\n    ~NumpyAllocator() {}\n\n    UMatData* allocate(PyObject* o, int dims, const int* sizes, int type, size_t* step) const\n    {\n        UMatData* u = new UMatData(this);\n        u->data = u->origdata = (uchar*)PyArray_DATA((PyArrayObject*) o);\n        npy_intp* _strides = PyArray_STRIDES((PyArrayObject*) o);\n        for( int i = 0; i < dims - 1; i++ )\n            step[i] = (size_t)_strides[i];\n        step[dims-1] = CV_ELEM_SIZE(type);\n        u->size = sizes[0]*step[0];\n        u->userdata = o;\n        return u;\n    }\n\n    UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const\n    {\n        if( data != 0 )\n        {\n            CV_Error(Error::StsAssert, \"The data should normally be NULL!\");\n            \/\/ probably this is safe to do in such extreme case\n            return stdAllocator->allocate(dims0, sizes, type, data, step, flags, usageFlags);\n        }\n        PyEnsureGIL gil;\n\n        int depth = CV_MAT_DEPTH(type);\n        int cn = CV_MAT_CN(type);\n        const int f = (int)(sizeof(size_t)\/8);\n        int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE :\n                      depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT :\n                      depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :\n                      depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT;\n        int i, dims = dims0;\n        cv::AutoBuffer<npy_intp> _sizes(dims + 1);\n        for( i = 0; i < dims; i++ )\n            _sizes[i] = sizes[i];\n        if( cn > 1 )\n            _sizes[dims++] = cn;\n        PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum);\n        if(!o)\n            CV_Error_(Error::StsError, (\"The numpy array of typenum=%d, ndims=%d can not be created\", typenum, dims));\n        return allocate(o, dims0, sizes, type, step);\n    }\n\n    bool allocate(UMatData* u, int accessFlags, UMatUsageFlags usageFlags) const\n    {\n        return stdAllocator->allocate(u, accessFlags, usageFlags);\n    }\n\n    void deallocate(UMatData* u) const\n    {\n        if(!u)\n            return;\n        PyEnsureGIL gil;\n        CV_Assert(u->urefcount >= 0);\n        CV_Assert(u->refcount >= 0);\n        if(u->refcount == 0)\n        {\n            PyObject* o = (PyObject*)u->userdata;\n            Py_XDECREF(o);\n            delete u;\n        }\n    }\n\n    const MatAllocator* stdAllocator;\n};\n\n\/\/ === ALLOCATOR INITIALIZATION ========================================================================================\n\nNumpyAllocator g_numpyAllocator;\n\n\/\/ === CONVERTOR FUNCTIONS =============================================================================================\n\ntemplate<typename T> static\nbool pyopencv_to(PyObject* obj, T& p, const char* name = \"<unknown>\");\n\ntemplate<typename T> static\nPyObject* pyopencv_from(const T& src);\n\nenum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 };\n\n\/\/ special case, when the convertor needs full ArgInfo structure\nstatic bool pyopencv_to(PyObject* o, Mat& m, const ArgInfo info)\n{\n    bool allowND = true;\n    if(!o || o == Py_None)\n    {\n        if( !m.data )\n            m.allocator = &g_numpyAllocator;\n        return true;\n    }\n\n    if( PyInt_Check(o) )\n    {\n        double v[] = {static_cast<double>(PyInt_AsLong((PyObject*)o)), 0., 0., 0.};\n        m = Mat(4, 1, CV_64F, v).clone();\n        return true;\n    }\n    if( PyFloat_Check(o) )\n    {\n        double v[] = {PyFloat_AsDouble((PyObject*)o), 0., 0., 0.};\n        m = Mat(4, 1, CV_64F, v).clone();\n        return true;\n    }\n    if( PyTuple_Check(o) )\n    {\n        int i, sz = (int)PyTuple_Size((PyObject*)o);\n        m = Mat(sz, 1, CV_64F);\n        for( i = 0; i < sz; i++ )\n        {\n            PyObject* oi = PyTuple_GET_ITEM(o, i);\n            if( PyInt_Check(oi) )\n                m.at<double>(i) = (double)PyInt_AsLong(oi);\n            else if( PyFloat_Check(oi) )\n                m.at<double>(i) = (double)PyFloat_AsDouble(oi);\n            else\n            {\n                failmsg(\"%s is not a numerical tuple\", info.name);\n                m.release();\n                return false;\n            }\n        }\n        return true;\n    }\n\n    if( !PyArray_Check(o) )\n    {\n        failmsg(\"%s is not a numpy array, neither a scalar\", info.name);\n        return false;\n    }\n\n    PyArrayObject* oarr = (PyArrayObject*) o;\n\n    bool needcopy = false, needcast = false;\n    int typenum = PyArray_TYPE(oarr), new_typenum = typenum;\n    int type = typenum == NPY_UBYTE ? CV_8U :\n               typenum == NPY_BYTE ? CV_8S :\n               typenum == NPY_USHORT ? CV_16U :\n               typenum == NPY_SHORT ? CV_16S :\n               typenum == NPY_INT ? CV_32S :\n               typenum == NPY_INT32 ? CV_32S :\n               typenum == NPY_FLOAT ? CV_32F :\n               typenum == NPY_DOUBLE ? CV_64F : -1;\n\n    if( type < 0 )\n    {\n        if( typenum == NPY_INT64 || typenum == NPY_UINT64 || typenum == NPY_LONG )\n        {\n            needcopy = needcast = true;\n            new_typenum = NPY_INT;\n            type = CV_32S;\n        }\n        else\n        {\n            failmsg(\"%s data type = %d is not supported\", info.name, typenum);\n            return false;\n        }\n    }\n\n#ifndef CV_MAX_DIM\n    const int CV_MAX_DIM = 32;\n#endif\n\n    int ndims = PyArray_NDIM(oarr);\n    if(ndims >= CV_MAX_DIM)\n    {\n        failmsg(\"%s dimensionality (=%d) is too high\", info.name, ndims);\n        return false;\n    }\n\n    int size[CV_MAX_DIM+1];\n    size_t step[CV_MAX_DIM+1];\n    size_t elemsize = CV_ELEM_SIZE1(type);\n    const npy_intp* _sizes = PyArray_DIMS(oarr);\n    const npy_intp* _strides = PyArray_STRIDES(oarr);\n    bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;\n\n    for( int i = ndims-1; i >= 0 && !needcopy; i-- )\n    {\n        \/\/ these checks handle cases of\n        \/\/  a) multi-dimensional (ndims > 2) arrays, as well as simpler 1- and 2-dimensional cases\n        \/\/  b) transposed arrays, where _strides[] elements go in non-descending order\n        \/\/  c) flipped arrays, where some of _strides[] elements are negative\n        \/\/ the _sizes[i] > 1 is needed to avoid spurious copies when NPY_RELAXED_STRIDES is set\n        if( (i == ndims-1 && _sizes[i] > 1 && (size_t)_strides[i] != elemsize) ||\n            (i < ndims-1 && _sizes[i] > 1 && _strides[i] < _strides[i+1]) )\n            needcopy = true;\n    }\n\n    if( ismultichannel && _strides[1] != (npy_intp)elemsize*_sizes[2] )\n        needcopy = true;\n\n    if (needcopy)\n    {\n        if (info.outputarg)\n        {\n            failmsg(\"Layout of the output array %s is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)\", info.name);\n            return false;\n        }\n\n        if( needcast ) {\n            o = PyArray_Cast(oarr, new_typenum);\n            oarr = (PyArrayObject*) o;\n        }\n        else {\n            oarr = PyArray_GETCONTIGUOUS(oarr);\n            o = (PyObject*) oarr;\n        }\n\n        _strides = PyArray_STRIDES(oarr);\n    }\n\n    \/\/ Normalize strides in case NPY_RELAXED_STRIDES is set\n    size_t default_step = elemsize;\n    for ( int i = ndims - 1; i >= 0; --i )\n    {\n        size[i] = (int)_sizes[i];\n        if ( size[i] > 1 )\n        {\n            step[i] = (size_t)_strides[i];\n            default_step = step[i] * size[i];\n        }\n        else\n        {\n            step[i] = default_step;\n            default_step *= size[i];\n        }\n    }\n\n    \/\/ handle degenerate case\n    if( ndims == 0) {\n        size[ndims] = 1;\n        step[ndims] = elemsize;\n        ndims++;\n    }\n\n    if( ismultichannel )\n    {\n        ndims--;\n        type |= CV_MAKETYPE(0, size[2]);\n    }\n\n    if( ndims > 2 && !allowND )\n    {\n        failmsg(\"%s has more than 2 dimensions\", info.name);\n        return false;\n    }\n\n    m = Mat(ndims, size, type, PyArray_DATA(oarr), step);\n    m.u = g_numpyAllocator.allocate(o, ndims, size, type, step);\n    m.addref();\n\n    if( !needcopy )\n    {\n        Py_INCREF(o);\n    }\n    m.allocator = &g_numpyAllocator;\n\n    return true;\n}\n\ntemplate<>\nbool pyopencv_to(PyObject* o, Mat& m, const char* name)\n{\n    return pyopencv_to(o, m, ArgInfo(name, 0));\n}\n\ntemplate<>\nPyObject* pyopencv_from(const Mat& m)\n{\n    if( !m.data )\n        Py_RETURN_NONE;\n    Mat temp, *p = (Mat*)&m;\n    if(!p->u || p->allocator != &g_numpyAllocator)\n    {\n        temp.allocator = &g_numpyAllocator;\n        ERRWRAP2(m.copyTo(temp));\n        p = &temp;\n    }\n    PyObject* o = (PyObject*)p->u->userdata;\n    Py_INCREF(o);\n    return o;\n}","avg_line_length":28.5706521739,"max_line_length":154,"alphanum_fraction":0.5186418109,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":17572,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1615.0,"content":"\/***************************************************************************\n # Copyright (c) 2015-21, NVIDIA CORPORATION. All rights reserved.\n #\n # Redistribution and use in source and binary forms, with or without\n # modification, are permitted provided that the following conditions\n # are met:\n #  * Redistributions of source code must retain the above copyright\n #    notice, this list of conditions and the following disclaimer.\n #  * Redistributions in binary form must reproduce the above copyright\n #    notice, this list of conditions and the following disclaimer in the\n #    documentation and\/or other materials provided with the distribution.\n #  * Neither the name of NVIDIA CORPORATION nor the names of its\n #    contributors may be used to endorse or promote products derived\n #    from this software without specific prior written permission.\n #\n # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS \"AS IS\" AND ANY\n # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n # PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **************************************************************************\/\n#include \"stdafx.h\"\n#include \"Core\/API\/ParameterBlock.h\"\nnamespace Falcor\n{\n    namespace\n    {\n        gfx::ShaderOffset getGFXShaderOffset(const UniformShaderVarOffset& offset)\n        {\n            gfx::ShaderOffset result;\n            result.bindingArrayIndex = 0;\n            result.bindingRangeIndex = 0;\n            result.uniformOffset = offset.getByteOffset();\n            return result;\n        }\n\n        gfx::ShaderOffset getGFXShaderOffset(const ParameterBlock::BindLocation& bindLoc)\n        {\n            gfx::ShaderOffset gfxOffset = {};\n            gfxOffset.bindingArrayIndex = bindLoc.getResourceArrayIndex();\n            gfxOffset.bindingRangeIndex = bindLoc.getResourceRangeIndex();\n            gfxOffset.uniformOffset = bindLoc.getUniform().getByteOffset();\n            return gfxOffset;\n        }\n\n        bool isSrvType(const ReflectionType::SharedConstPtr& pType)\n        {\n            auto resourceType = pType->unwrapArray()->asResourceType();\n            if (resourceType->getType() == ReflectionResourceType::Type::Sampler ||\n                resourceType->getType() == ReflectionResourceType::Type::ConstantBuffer) return false;\n\n            switch (resourceType->getShaderAccess())\n            {\n            case ReflectionResourceType::ShaderAccess::Read:\n                return true;\n            case ReflectionResourceType::ShaderAccess::ReadWrite:\n                return false;\n            default:\n                should_not_get_here();\n                return false;\n            }\n        }\n\n        bool isUavType(const ReflectionType::SharedConstPtr& pType)\n        {\n            auto resourceType = pType->unwrapArray()->asResourceType();\n            if (resourceType->getType() == ReflectionResourceType::Type::Sampler ||\n                resourceType->getType() == ReflectionResourceType::Type::ConstantBuffer) return false;\n\n            switch (resourceType->getShaderAccess())\n            {\n            case ReflectionResourceType::ShaderAccess::Read:\n                return false;\n            case ReflectionResourceType::ShaderAccess::ReadWrite:\n                return true;\n            default:\n                should_not_get_here();\n                return false;\n            }\n        }\n\n        bool isCbvType(const ReflectionType::SharedConstPtr& pType)\n        {\n            auto resourceType = pType->unwrapArray()->asResourceType();\n            if (resourceType->getType() == ReflectionResourceType::Type::ConstantBuffer)\n            {\n                assert(resourceType->getShaderAccess() == ReflectionResourceType::ShaderAccess::Read);\n                return true;\n            }\n            return false;\n        }\n    }\n\n    ParameterBlock::~ParameterBlock() {}\n\n    ParameterBlock::ParameterBlock(const ProgramReflection::SharedConstPtr& pReflector)\n        : mpReflector(pReflector->getDefaultParameterBlock())\n        , mpProgramVersion(pReflector->getProgramVersion())\n    {\n        gfx_call(gpDevice->getApiHandle()->createMutableRootShaderObject(\n            pReflector->getProgramVersion()->getKernels(nullptr)->getApiHandle(),\n            mpShaderObject.writeRef()));\n    }\n\n    ParameterBlock::ParameterBlock(\n        const std::shared_ptr<const ProgramVersion>& pProgramVersion,\n        const ParameterBlockReflection::SharedConstPtr& pReflection)\n        : mpReflector(pReflection)\n        , mpProgramVersion(pProgramVersion)\n    {\n        gfx_call(gpDevice->getApiHandle()->createMutableShaderObject(\n            pReflection->getElementType()->getSlangTypeLayout()->getType(),\n            gfx::ShaderObjectContainerType::None,\n            mpShaderObject.writeRef()));\n    }\n\n    bool ParameterBlock::setBlob(const void* pSrc, UniformShaderVarOffset offset, size_t size)\n    {\n        gfx::ShaderOffset gfxOffset = getGFXShaderOffset(offset);\n        return SLANG_SUCCEEDED(mpShaderObject->setData(gfxOffset, pSrc, size));\n    }\n\n    bool ParameterBlock::setBlob(const void* pSrc, size_t offset, size_t size)\n    {\n        gfx::ShaderOffset gfxOffset = {};\n        gfxOffset.uniformOffset = offset;\n        return SLANG_SUCCEEDED(mpShaderObject->setData(gfxOffset, pSrc, size));\n    }\n\n    bool ParameterBlock::setBuffer(const std::string& name, const Buffer::SharedPtr& pBuffer)\n    {\n        auto var = getRootVar()[name];\n        return var.setBuffer(pBuffer);\n    }\n\n    bool ParameterBlock::setBuffer(const BindLocation& bindLoc, const Buffer::SharedPtr& pResource)\n    {\n        gfx::ShaderOffset gfxOffset = getGFXShaderOffset(bindLoc);\n        if (isUavType(bindLoc.getType()))\n        {\n            auto pUAV = pResource ? pResource->getUAV() : UnorderedAccessView::getNullView(ReflectionResourceType::Dimensions::Buffer);\n            mpShaderObject->setResource(gfxOffset, pUAV->getApiHandle());\n            mUAVs[gfxOffset] = pUAV;\n        }\n        else if (isSrvType(bindLoc.getType()))\n        {\n            auto pSRV = pResource ? pResource->getSRV() : ShaderResourceView::getNullView(ReflectionResourceType::Dimensions::Buffer);\n            mpShaderObject->setResource(gfxOffset, pSRV->getApiHandle());\n            mSRVs[gfxOffset] = pSRV;\n        }\n        else\n        {\n            logError(\"Error trying to bind resource to non SRV\/UAV variable. Ignoring call.\");\n            return false;\n        }\n        return true;\n    }\n\n    Buffer::SharedPtr ParameterBlock::getBuffer(const std::string& name) const\n    {\n        auto var = getRootVar()[name];\n        return var.getBuffer();\n    }\n\n    Buffer::SharedPtr ParameterBlock::getBuffer(const BindLocation& bindLoc) const\n    {\n        gfx::ShaderOffset gfxOffset = getGFXShaderOffset(bindLoc);\n        if (isUavType(bindLoc.getType()))\n        {\n            auto iter = mUAVs.find(gfxOffset);\n            if (iter == mUAVs.end()) return nullptr;\n            return iter->second->getResource()->asBuffer();\n        }\n        else if (isSrvType(bindLoc.getType()))\n        {\n            auto iter = mSRVs.find(gfxOffset);\n            if (iter == mSRVs.end()) return nullptr;\n            return iter->second->getResource()->asBuffer();\n        }\n        else\n        {\n            logError(\"Error trying to bind resource to non SRV\/UAV variable. Ignoring call.\");\n            return nullptr;\n        }\n    }\n\n    bool ParameterBlock::setParameterBlock(const std::string& name, const ParameterBlock::SharedPtr& pBlock)\n    {\n        auto var = getRootVar()[name];\n        return var.setParameterBlock(pBlock);\n    }\n\n    bool ParameterBlock::setParameterBlock(const BindLocation& bindLocation, const ParameterBlock::SharedPtr& pBlock)\n    {\n        auto gfxOffset = getGFXShaderOffset(bindLocation);\n        mParameterBlocks[gfxOffset] = pBlock;\n        return SLANG_SUCCEEDED(mpShaderObject->setObject(gfxOffset, pBlock->mpShaderObject));\n    }\n\n    ParameterBlock::SharedPtr ParameterBlock::getParameterBlock(const std::string& name) const\n    {\n        auto var = getRootVar()[name];\n        return var.getParameterBlock();\n    }\n\n    ParameterBlock::SharedPtr ParameterBlock::getParameterBlock(const BindLocation& bindLocation) const\n    {\n        auto gfxOffset = getGFXShaderOffset(bindLocation);\n        auto iter = mParameterBlocks.find(gfxOffset);\n        if (iter == mParameterBlocks.end()) return nullptr;\n        return iter->second;\n    }\n\n    template<typename VarType>\n    bool ParameterBlock::setVariable(UniformShaderVarOffset offset, const VarType& value)\n    {\n        auto gfxOffset = getGFXShaderOffset(offset);\n        return SLANG_SUCCEEDED(mpShaderObject->setData(gfxOffset, &value, sizeof(VarType)));\n    }\n\n#define set_constant_by_offset(_t) template FALCOR_API bool ParameterBlock::setVariable(UniformShaderVarOffset offset, const _t& value)\n\n    set_constant_by_offset(bool);\n    set_constant_by_offset(bool2);\n    set_constant_by_offset(bool3);\n    set_constant_by_offset(bool4);\n\n    set_constant_by_offset(uint32_t);\n    set_constant_by_offset(uint2);\n    set_constant_by_offset(uint3);\n    set_constant_by_offset(uint4);\n\n    set_constant_by_offset(int32_t);\n    set_constant_by_offset(int2);\n    set_constant_by_offset(int3);\n    set_constant_by_offset(int4);\n\n    set_constant_by_offset(float);\n    set_constant_by_offset(float2);\n    set_constant_by_offset(float3);\n    set_constant_by_offset(float4);\n\n    set_constant_by_offset(glm::mat2);\n    set_constant_by_offset(glm::mat2x3);\n    set_constant_by_offset(glm::mat2x4);\n\n    set_constant_by_offset(glm::mat3);\n    set_constant_by_offset(glm::mat3x2);\n    set_constant_by_offset(glm::mat3x4);\n\n    set_constant_by_offset(glm::mat4);\n    set_constant_by_offset(glm::mat4x2);\n    set_constant_by_offset(glm::mat4x3);\n\n    set_constant_by_offset(uint64_t);\n\n#undef set_constant_by_offset\n\n    bool ParameterBlock::setTexture(const std::string& name, const Texture::SharedPtr& pTexture)\n    {\n        auto var = getRootVar()[name];\n        return var.setTexture(pTexture);\n    }\n\n    bool ParameterBlock::setTexture(const BindLocation& bindLocation, const Texture::SharedPtr& pTexture)\n    {\n        const auto& bindingInfo = mpReflector->getResourceRangeBindingInfo(bindLocation.getResourceRangeIndex());\n        gfx::ShaderOffset gfxOffset = getGFXShaderOffset(bindLocation);\n        if (isUavType(bindLocation.getType()))\n        {\n            auto pUAV = pTexture ? pTexture->getUAV() : UnorderedAccessView::getNullView(bindingInfo.dimension);\n            mpShaderObject->setResource(gfxOffset, pUAV->getApiHandle());\n            mUAVs[gfxOffset] = pUAV;\n        }\n        else if (isSrvType(bindLocation.getType()))\n        {\n            auto pSRV = pTexture ? pTexture->getSRV() : ShaderResourceView::getNullView(bindingInfo.dimension);\n            mpShaderObject->setResource(gfxOffset, pSRV->getApiHandle());\n            mSRVs[gfxOffset] = pSRV;\n        }\n        else\n        {\n            logError(\"Error trying to bind resource to non SRV\/UAV variable. Ignoring call.\");\n            return false;\n        }\n        return true;\n    }\n\n    Texture::SharedPtr ParameterBlock::getTexture(const std::string& name) const\n    {\n        auto var = getRootVar()[name];\n        return var.getTexture();\n    }\n\n    Texture::SharedPtr ParameterBlock::getTexture(const BindLocation& bindLocation) const\n    {\n        gfx::ShaderOffset gfxOffset = getGFXShaderOffset(bindLocation);\n        if (isUavType(bindLocation.getType()))\n        {\n            auto iter = mUAVs.find(gfxOffset);\n            if (iter == mUAVs.end()) return nullptr;\n            return iter->second->getResource()->asTexture();\n        }\n        else if (isSrvType(bindLocation.getType()))\n        {\n            auto iter = mSRVs.find(gfxOffset);\n            if (iter == mSRVs.end()) return nullptr;\n            return iter->second->getResource()->asTexture();\n        }\n        else\n        {\n            logError(\"Error trying to bind resource to non SRV\/UAV variable. Ignoring call.\");\n            return nullptr;\n        }\n    }\n\n    bool ParameterBlock::setSrv(const BindLocation& bindLocation, const ShaderResourceView::SharedPtr& pSrv)\n    {\n        gfx::ShaderOffset gfxOffset = getGFXShaderOffset(bindLocation);\n        if (isSrvType(bindLocation.getType()))\n        {\n            mpShaderObject->setResource(gfxOffset, pSrv->getApiHandle());\n            mSRVs[gfxOffset] = pSrv;\n        }\n        else\n        {\n            logError(\"Error trying to bind SRV to a non SRV variable. Ignoring call.\");\n            return false;\n        }\n        return true;\n    }\n\n    bool ParameterBlock::setUav(const BindLocation& bindLocation, const UnorderedAccessView::SharedPtr& pUav)\n    {\n        gfx::ShaderOffset gfxOffset = getGFXShaderOffset(bindLocation);\n        if (isUavType(bindLocation.getType()))\n        {\n            mpShaderObject->setResource(gfxOffset, pUav->getApiHandle());\n            mUAVs[gfxOffset] = pUav;\n        }\n        else\n        {\n            logError(\"Error trying to bind UAV to a non UAV variable. Ignoring call.\");\n            return false;\n        }\n        return true;\n    }\n\n    bool ParameterBlock::setAccelerationStructure(const BindLocation& bindLocation, const RtAccelerationStructure::SharedPtr& pAccl)\n    {\n        gfx::ShaderOffset gfxOffset = getGFXShaderOffset(bindLocation);\n        mAccelerationStructures[gfxOffset] = pAccl;\n        return SLANG_SUCCEEDED(mpShaderObject->setResource(gfxOffset, pAccl->getApiHandle()));\n    }\n\n    ShaderResourceView::SharedPtr ParameterBlock::getSrv(const BindLocation& bindLocation) const\n    {\n        gfx::ShaderOffset gfxOffset = getGFXShaderOffset(bindLocation);\n        auto iter = mSRVs.find(gfxOffset);\n        if (iter == mSRVs.end()) return nullptr;\n        return iter->second;\n    }\n\n    UnorderedAccessView::SharedPtr ParameterBlock::getUav(const BindLocation& bindLocation) const\n    {\n        gfx::ShaderOffset gfxOffset = getGFXShaderOffset(bindLocation);\n        auto iter = mUAVs.find(gfxOffset);\n        if (iter == mUAVs.end()) return nullptr;\n        return iter->second;\n    }\n\n    RtAccelerationStructure::SharedPtr ParameterBlock::getAccelerationStructure(const BindLocation& bindLocation) const\n    {\n        gfx::ShaderOffset gfxOffset = getGFXShaderOffset(bindLocation);\n        auto iter = mAccelerationStructures.find(gfxOffset);\n        if (iter == mAccelerationStructures.end()) return nullptr;\n        return iter->second;\n    }\n\n    bool ParameterBlock::setSampler(const std::string& name, const Sampler::SharedPtr& pSampler)\n    {\n        auto var = getRootVar()[name];\n        return var.setSampler(pSampler);\n    }\n\n    bool ParameterBlock::setSampler(const BindLocation& bindLocation, const Sampler::SharedPtr& pSampler)\n    {\n        gfx::ShaderOffset gfxOffset = getGFXShaderOffset(bindLocation);\n        mSamplers[gfxOffset] = pSampler;\n        return SLANG_SUCCEEDED(mpShaderObject->setSampler(gfxOffset, pSampler->getApiHandle()));\n    }\n\n    const Sampler::SharedPtr& ParameterBlock::getSampler(const BindLocation& bindLocation) const\n    {\n        static Sampler::SharedPtr pNull = nullptr;\n\n        gfx::ShaderOffset gfxOffset = getGFXShaderOffset(bindLocation);\n        auto iter = mSamplers.find(gfxOffset);\n        if (iter == mSamplers.end())\n        {\n            return pNull;\n        }\n        return iter->second;\n    }\n\n    Sampler::SharedPtr ParameterBlock::getSampler(const std::string& name) const\n    {\n        auto var = getRootVar()[name];\n        return var.getSampler();\n    }\n\n    size_t ParameterBlock::getSize() const\n    {\n        return mpShaderObject->getSize();\n    }\n\n    bool ParameterBlock::updateSpecialization() const\n    {\n        return true;\n    }\n\n    bool ParameterBlock::prepareDescriptorSets(CopyContext* pCopyContext)\n    {\n        return true;\n    }\n\n    const ParameterBlock::SharedPtr& ParameterBlock::getParameterBlock(uint32_t resourceRangeIndex, uint32_t arrayIndex) const\n    {\n        static ParameterBlock::SharedPtr pNull = nullptr;\n\n        gfx::ShaderOffset gfxOffset = {};\n        gfxOffset.bindingRangeIndex = resourceRangeIndex;\n        gfxOffset.bindingArrayIndex = arrayIndex;\n        auto iter = mParameterBlocks.find(gfxOffset);\n        if (iter == mParameterBlocks.end())\n        {\n            return pNull;\n        }\n        return iter->second;\n    }\n\n    void ParameterBlock::collectSpecializationArgs(SpecializationArgs& ioArgs) const\n    {\n    }\n\n    void ParameterBlock::markUniformDataDirty() const\n    {\n    }\n\n    void const* ParameterBlock::getRawData() const\n    {\n        return mpShaderObject->getRawData();\n    }\n\n    const Buffer::SharedPtr& ParameterBlock::getUnderlyingConstantBuffer() const\n    {\n        throw \"unimplemented\";\n    }\n\n#if FALCOR_ENABLE_CUDA\n    void* ParameterBlock::getCUDAHostBuffer(size_t& outSize)\n    {\n        return nullptr;\n    }\n\n    void* ParameterBlock::getCUDADeviceBuffer(size_t& outSize)\n    {\n        return nullptr;\n    }\n#endif\n}\n","avg_line_length":36.7615062762,"max_line_length":135,"alphanum_fraction":0.6525722741,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2873,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":7.0,"content":"\/*\n * OpenGLRenderImpl.cpp\n *\n *  Created on: 20.04.2019\n *      Author: florian\n *\/\n\n#include \"OpenGLRenderImpl.h\"\n\n#include \"..\/..\/zoe\/render\/GraphicsContext.h\"\n#include \"..\/..\/zoe\/core\/Application.h\"\n\n#include \"..\/..\/zoe\/render\/api\/RenderTarget.h\"\n\n#include \"OpenGLVertexArrayImpl.h\"\n#include \"OpenGLIndexBufferImpl.h\"\n\nnamespace Zoe {\n\nOpenGLRenderImpl::OpenGLRenderImpl(GraphicsContext *context) :\n        RenderImpl(context, 0, 0, 1280, 720) {\n    settings.width = Application::get().getWindow().getWidth();\n    settings.height = Application::get().getWindow().getHeight();\n}\n\nOpenGLRenderImpl::~OpenGLRenderImpl() = default;\n\nvoid OpenGLRenderImpl::draw(VertexArray &va, Shader &shader) {\n    loadSettings();\n    va.bind();\n    shader.bind();\n    glDrawElements(GL_TRIANGLES, va.getImpl()->getIndexBuffer()->getCount(), GL_UNSIGNED_INT, nullptr);\n    va.unbind();\n    shader.unbind();\n}\n\nvoid OpenGLRenderImpl::clear() {\n    loadSettings();\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n}\n\nvoid OpenGLRenderImpl::setClearColor(float r, float g, float b, float a) {\n    settings.clearColor = {r, g, b, a};\n}\n\nvoid OpenGLRenderImpl::setViewport(unsigned int x, unsigned int y,\n                                   unsigned int width, unsigned int height) {\n    this->settings.x = x;\n    this->settings.y = y;\n    this->settings.width = width;\n    this->settings.height = height;\n}\n\nvoid OpenGLRenderImpl::setAlphaEnabled(bool enabled) {\n    settings.flag.alpha = enabled;\n}\n\nvoid OpenGLRenderImpl::loadSettings() {\n    if (auto target = renderTarget.lock()) {\n        target->bind();\n    } else {\n        Application::getContext().getDefaultRenderTarget()->bind();\n    }\n    RenderSettings &bound = context->boundRenderSettings;\n\n    \/\/Update viewport\n    if (bound.x != settings.x || bound.y != settings.y || bound.width != settings.width ||\n        bound.height != settings.height) {\n        glViewport(settings.x, settings.y, settings.width, settings.height);\n    }\n\n    \/\/Update clearColor\n    if (bound.clearColor != settings.clearColor) {\n        glClearColor(settings.clearColor.x, settings.clearColor.y, settings.clearColor.z, settings.clearColor.w);\n    }\n\n    \/\/Check alpha enabled\n    if (bound.flag.alpha != settings.flag.alpha) {\n        if (settings.flag.alpha) {\n            glEnable(GL_BLEND);\n            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n            glBlendEquation(GL_FUNC_ADD);\n        } else {\n            glDisable(GL_BLEND);\n        }\n    }\n    bound = settings;\n}\n\nvoid OpenGLRenderImpl::setRenderTarget(std::shared_ptr<RenderTarget> target) {\n    this->renderTarget = target;\n}\n\nvoid OpenGLRenderImpl::push() {\n    stack.push({settings, renderTarget});\n}\n\nvoid OpenGLRenderImpl::pop() {\n    const StackElement &top = stack.top();\n    settings = top.settings;\n    renderTarget = top.renderTarget;\n    stack.pop();\n}\n\n}\n","avg_line_length":27.1037735849,"max_line_length":113,"alphanum_fraction":0.6616776888,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5122,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2.0,"content":"\/\/\n\/\/ BundleActivator.cpp\n\/\/\n\/\/ Copyright (c) 2015, Applied Informatics Software Engineering GmbH.\n\/\/ All rights reserved.\n\/\/\n\/\/ SPDX-License-Identifier: Apache-2.0\n\/\/\n\n\n#include \"Poco\/OSP\/BundleActivator.h\"\n#include \"Poco\/OSP\/BundleContext.h\"\n#include \"Poco\/OSP\/Bundle.h\"\n#include \"Poco\/OSP\/ServiceRegistry.h\"\n#include \"Poco\/OSP\/ServiceRef.h\"\n#include \"Poco\/OSP\/ServiceFinder.h\"\n#include \"Poco\/OSP\/PreferencesService.h\"\n#include \"Poco\/RemotingNG\/ORB.h\"\n#include \"RTUPort.h\"\n#include \"IoT\/Modbus\/ModbusMasterImpl.h\"\n#include \"IoT\/Modbus\/ModbusMasterServerHelper.h\"\n#include \"Poco\/Serial\/SerialPort.h\"\n#include \"Poco\/ClassLibrary.h\"\n#include \"Poco\/Format.h\"\n#include \"Poco\/NumberFormatter.h\"\n#include <vector>\n\n\nusing Poco::OSP::BundleContext;\nusing Poco::OSP::ServiceRegistry;\nusing Poco::OSP::ServiceRef;\nusing Poco::OSP::ServiceFinder;\nusing Poco::OSP::Properties;\nusing Poco::OSP::PreferencesService;\n\n\nnamespace IoT {\nnamespace Modbus {\nnamespace RTU {\n\n\nclass BundleActivator: public Poco::OSP::BundleActivator\n{\npublic:\n\ttypedef Poco::RemotingNG::ServerHelper<IoT::Modbus::ModbusMaster> ServerHelper;\n\n\tBundleActivator()\n\t{\n\t}\n\t\n\t~BundleActivator()\n\t{\n\t}\n\t\n\tvoid createModbusRTUMaster(const std::string& uid, Poco::SharedPtr<Poco::Serial::SerialPort> pSerialPort, Poco::Timespan timeout, Poco::Timespan frameTimeout)\n\t{\t\t\n\t\tPoco::SharedPtr<ModbusMaster> pModbusMaster = new ModbusMasterImpl<RTUPort>(new RTUPort(pSerialPort, frameTimeout), timeout);\n\t\tstd::string symbolicName = \"io.macchina.modbus.rtu\";\n\t\tPoco::RemotingNG::Identifiable::ObjectId oid = symbolicName;\n\t\toid += '#';\n\t\toid += uid;\n\t\tServerHelper::RemoteObjectPtr pModbusMasterRemoteObject = ServerHelper::createRemoteObject(pModbusMaster, oid);\n\t\t\n\t\tProperties props;\n\t\tprops.set(\"io.macchina.protocol\", symbolicName);\n\t\tprops.set(\"io.macchina.modbus.rtu.device\", pSerialPort->device());\n\t\t\n\t\tServiceRef::Ptr pServiceRef = _pContext->registry().registerService(oid, pModbusMasterRemoteObject, props);\n\t\t_serviceRefs.push_back(pServiceRef);\n\t}\n\n\tvoid start(BundleContext::Ptr pContext)\n\t{\n\t\t_pContext = pContext;\n\t\t_pPrefs = ServiceFinder::find<PreferencesService>(pContext);\n\t\t\n\t\tPoco::Util::AbstractConfiguration::Keys keys;\n\t\t_pPrefs->configuration()->keys(\"modbus.rtu.ports\", keys);\n\t\tint index = 0;\n\t\tfor (std::vector<std::string>::const_iterator it = keys.begin(); it != keys.end(); ++it)\n\t\t{\n\t\t\tstd::string baseKey = \"modbus.rtu.ports.\";\n\t\t\tbaseKey += *it;\n\n\t\t\tstd::string device = _pPrefs->configuration()->getString(baseKey + \".device\", \"\");\n\t\t\tstd::string params = _pPrefs->configuration()->getString(baseKey + \".params\", \"8N1\");\n\t\t\tint speed = _pPrefs->configuration()->getInt(baseKey + \".speed\", 9600);\n\t\t\tPoco::Timespan timeout = 1000*_pPrefs->configuration()->getInt(baseKey + \".timeout\", 2000);\n\t\t\tPoco::Timespan frameTimeout = _pPrefs->configuration()->getInt(baseKey + \".frameTimeout\", 10000);\n\t\t\n\t\t\ttry\n\t\t\t{\n\t\t\t\tpContext->logger().information(Poco::format(\"Creating serial port for Modbus RTU device '%s'.\", device));\n\n\t\t\t\tPoco::SharedPtr<Poco::Serial::SerialPort> pSerialPort = new Poco::Serial::SerialPort(device, speed, params);\n\t\t\t\n\t\t\t\tif (_pPrefs->configuration()->getBool(baseKey + \".rs485.enable\", false))\n\t\t\t\t{\n\t\t\t\t\tPoco::Serial::SerialPort::RS485Params rs485Params;\n\t\t\t\t\trs485Params.flags = Poco::Serial::SerialPort::RS485Params::RS485_ENABLED;\n\t\t\t\t\tif (_pPrefs->configuration()->getBool(baseKey + \".rs485.rtsOnSend\", false))\n\t\t\t\t\t\trs485Params.flags |= Poco::Serial::SerialPort::RS485Params::RS485_RTS_ON_SEND;\n\t\t\t\t\tif (_pPrefs->configuration()->getBool(baseKey + \".rs485.rtsAfterSend\", false))\n\t\t\t\t\t\trs485Params.flags |= Poco::Serial::SerialPort::RS485Params::RS485_RTS_AFTER_SEND;\n\t\t\t\t\tif (_pPrefs->configuration()->getBool(baseKey + \".rs485.useGPIO\", false))\n\t\t\t\t\t\trs485Params.flags |= Poco::Serial::SerialPort::RS485Params::RS485_USE_GPIO;\n\t\t\t\t\t\n\t\t\t\t\trs485Params.delayRTSBeforeSend = _pPrefs->configuration()->getInt(baseKey + \".rs485.delayRTSBeforeSend\", 0);\n\t\t\t\t\trs485Params.delayRTSAfterSend  = _pPrefs->configuration()->getInt(baseKey + \".rs485.delayRTSAfterSend\", 0);\n\t\t\t\t\trs485Params.gpioPin            = _pPrefs->configuration()->getInt(baseKey + \".rs485.gpioPin\", 0);\n\t\t\t\t\n\t\t\t\t\tpSerialPort->configureRS485(rs485Params);\n\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\tcreateModbusRTUMaster(Poco::NumberFormatter::format(index), pSerialPort, timeout, frameTimeout);\n\t\t\t}\n\t\t\tcatch (Poco::Exception& exc)\n\t\t\t{\n\t\t\t\tpContext->logger().error(Poco::format(\"Cannot create serial port for Modbus RTU device '%s': %s\", device, exc.displayText())); \n\t\t\t}\n\t\t\tindex++;\n\t\t}\n\t}\n\t\t\n\tvoid stop(BundleContext::Ptr pContext)\n\t{\n\t\tfor (std::vector<ServiceRef::Ptr>::iterator it = _serviceRefs.begin(); it != _serviceRefs.end(); ++it)\n\t\t{\n\t\t\t_pContext->registry().unregisterService(*it);\n\t\t}\n\t\t_serviceRefs.clear();\n\t\t_pPrefs = 0;\n\t\t_pContext = 0;\n\t\t\n\t\tServerHelper::shutdown();\n\t}\n\nprivate:\n\tBundleContext::Ptr _pContext;\n\tPreferencesService::Ptr _pPrefs;\n\tstd::vector<ServiceRef::Ptr> _serviceRefs;\n};\n\n\n} } } \/\/ namespace IoT::Modbus::RTU\n\n\nPOCO_BEGIN_MANIFEST(Poco::OSP::BundleActivator)\n\tPOCO_EXPORT_CLASS(IoT::Modbus::RTU::BundleActivator)\nPOCO_END_MANIFEST\n","avg_line_length":33.9205298013,"max_line_length":159,"alphanum_fraction":0.7182741117,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":146331,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-3.0"],"max_stars_count":null,"content":"#include \"Console.h\"\n\n#include \"modules\/Gui.h\"\n\n#include \"Core.h\"\n#include \"DataDefs.h\"\n#include \"df\/biome_type.h\"\n#include \"df\/inorganic_raw.h\"\n#include \"df\/region_map_entry.h\"\n#include \"df\/viewscreen.h\"\n#include \"df\/viewscreen_choose_start_sitest.h\"\n#include \"df\/world.h\"\n#include \"df\/world_data.h\"\n#include \"df\/world_raws.h\"\n#include \"df\/world_region.h\"\n#include \"df\/world_region_details.h\"\n#include \"df\/world_region_type.h\"\n\n#include \"matcher.h\"\n#include \"survey.h\"\n\nusing df::global::world;\n\nnamespace embark_assist {\n    namespace matcher {\n\n        \/\/=======================================================================================\n\n        struct matcher_info {\n            matcher_info() {\n                for (uint8 i = 0; i < 3; ++i)\n                {\n                    savagery_found[i] = false;\n                    evilness_found[i] = false;\n                }\n                aquifer = embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NA;\n                river_found = false;\n                max_waterfall = 0;\n                elevation = 0;\n                clay_found = false;\n                sand_found = false;\n                flux_found = false;\n                coal_found = false;\n                max_soil = 0;\n                uneven = false;\n                min_temperature = 0;\n                max_temperature = 0;\n                min_trees_found = embark_assist::defs::tree_levels::TREE_LEVEL_HEAVILY_FORESTED;\n                max_trees_found = embark_assist::defs::tree_levels::TREE_LEVEL_NONE;\n                blood_rain_found = false;\n                permanent_syndrome_rain_found = false;\n                temporary_syndrome_rain_found = false;\n                reanimation_found = false;\n                thralling_found = false;\n                spire_count = 0;\n                magma_level = -1;\n                biome_count = 0;\n                metal_1 = false;\n                metal_2 = false;\n                metal_3 = false;\n                economic_1 = false;\n                economic_2 = false;\n                economic_3 = false;\n                mineral_1 = false;\n                mineral_2 = false;\n                mineral_3 = false;\n                for (uint8 i = 0; i < ENUM_LAST_ITEM(biome_type) + 1; ++i)\n                    biomes[i] = false;\n                for (uint8 i = 0; i < ENUM_LAST_ITEM(world_region_type) + 1; ++i)\n                    region_types[i] = false;\n            }\n            bool savagery_found[3];\n            bool evilness_found[3];\n            embark_assist::defs::aquifer_sizes aquifer;\n            bool river_found;\n            uint8_t max_waterfall;\n            uint16_t elevation;\n            bool clay_found;\n            bool sand_found;\n            bool flux_found;\n            bool coal_found;\n            uint8_t max_soil;\n            bool uneven;\n            int16_t min_temperature;\n            int16_t max_temperature;\n            embark_assist::defs::tree_levels min_trees_found;\n            embark_assist::defs::tree_levels max_trees_found;\n            bool blood_rain_found;\n            bool permanent_syndrome_rain_found;\n            bool temporary_syndrome_rain_found;\n            bool reanimation_found;\n            bool thralling_found;\n            uint8_t spire_count;\n            int8_t magma_level;\n            bool biomes[ENUM_LAST_ITEM(biome_type) + 1];\n            bool region_types[ENUM_LAST_ITEM(world_region_type) + 1];\n            uint8_t biome_count;\n            bool metal_1;\n            bool metal_2;\n            bool metal_3;\n            bool economic_1;\n            bool economic_2;\n            bool economic_3;\n            bool mineral_1;\n            bool mineral_2;\n            bool mineral_3;\n        };\n\n        \/\/=======================================================================================\n\n        void process_embark_incursion(matcher_info *result,\n            embark_assist::defs::world_tile_data *survey_results,\n            embark_assist::defs::mid_level_tile *mlt,  \/\/ Note this is a single tile, as opposed to most usages of this variable name.\n            embark_assist::defs::finders *finder,\n            int16_t elevation,\n            uint16_t x,\n            uint16_t y,\n            bool *failed_match) {\n\n            df::world_data *world_data = world->world_data;\n\n            \/\/ Savagery & Evilness\n                {\n                    result->savagery_found[mlt->savagery_level] = true;\n                    result->evilness_found[mlt->evilness_level] = true;\n\n                    embark_assist::defs::evil_savagery_ranges l = embark_assist::defs::evil_savagery_ranges::EVIL_SAVAGERY_LOW;\n                    while (true) {\n                        if (mlt->savagery_level == static_cast<uint8_t>(l)) {\n                            if (finder->savagery[static_cast <int>(l)] ==\n                                embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ABSENT) {\n                                *failed_match = true;\n                                return;\n                            }\n                        }\n                        else {\n                            if (finder->savagery[static_cast <int>(l)] ==\n                                embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ALL) {\n                                *failed_match = true;\n                                return;\n                            }\n                        }\n\n                        if (mlt->evilness_level == static_cast<uint8_t>(l)) {\n                            if (finder->evilness[static_cast <int>(l)] ==\n                                embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ABSENT) {\n                                *failed_match = true;\n                                return;\n                            }\n                        }\n                        else {\n                            if (finder->evilness[static_cast <int>(l)] ==\n                                embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ALL) {\n                                *failed_match = true;\n                                return;\n                            }\n                        }\n\n                        if (l == embark_assist::defs::evil_savagery_ranges::EVIL_SAVAGERY_HIGH) break;\n                        l = static_cast <embark_assist::defs::evil_savagery_ranges>(static_cast<int8_t>(l) + 1);\n                    }\n                }\n\n                \/\/  Aquifer\n                result->aquifer = static_cast<embark_assist::defs::aquifer_sizes>(static_cast<int8_t>(result->aquifer) | static_cast<int8_t>(mlt->aquifer));\n\n                switch (finder->aquifer) {\n                case embark_assist::defs::aquifer_ranges::AQUIFER_NA:\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_NONE:\n                    if (result->aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE) {\n                        *failed_match = true;\n                        return;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_AT_MOST_LIGHT:\n                case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_PLUS_LIGHT:\n                    if (static_cast<int8_t>(result->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_HEAVY)) {\n                        *failed_match = true;\n                        return;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_LIGHT:\n                    if (result->aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_LIGHT) {\n                        *failed_match = true;\n                        return;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_AT_LEAST_LIGHT:\n                case embark_assist::defs::aquifer_ranges::AQUIFER_LIGHT_PLUS_HEAVY:\n                    if (static_cast<int8_t>(result->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE)) {\n                        *failed_match = true;\n                        return;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_PLUS_HEAVY:\n                    if (static_cast<int8_t>(result->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_LIGHT)) {\n                        *failed_match = true;\n                        return;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_PLUS_AT_LEAST_LIGHT:\n                case embark_assist::defs::aquifer_ranges::AQUIFER_AT_MOST_LIGHT_PLUS_HEAVY:\n                case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_LIGHT_HEAVY:\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_HEAVY:\n                    if (result->aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_HEAVY) {\n                        *failed_match = true;\n                        return;\n                    }\n                    break;\n                }\n\n                \/\/  River & Waterfall. N\/A for incursions.\n\n                \/\/  Flat\n                if (finder->flat == embark_assist::defs::yes_no_ranges::YES_NO_YES &&\n                    result->elevation != mlt->elevation) {\n                    *failed_match = true;\n                    return;\n                }\n\n                \/\/ Clay\n                if (mlt->clay) {\n                    if (finder->clay == embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT) {\n                        *failed_match = true;\n                        return;\n                    }\n                    result->clay_found = true;\n                }\n\n                \/\/ Sand\n                if (mlt->sand) {\n                    if (finder->sand == embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT) {\n                        *failed_match = true;\n                        return;\n                    }\n                    result->sand_found = true;\n                }\n\n                \/\/ Flux. N\/A for incursions.\n                \/\/ Coal. N\/A for incursions\n\n                \/\/  Min Soil\n                if (finder->soil_min != embark_assist::defs::soil_ranges::SOIL_NA &&\n                    mlt->soil_depth < static_cast<uint16_t>(finder->soil_min) &&\n                    finder->soil_min_everywhere == embark_assist::defs::all_present_ranges::ALL_PRESENT_ALL) {\n                    *failed_match = true;\n                    return;\n                }\n\n                if (result->max_soil < mlt->soil_depth) {\n                    result->max_soil = mlt->soil_depth;\n                }\n\n                \/\/  Max Soil\n                if (finder->soil_max != embark_assist::defs::soil_ranges::SOIL_NA &&\n                    mlt->soil_depth > static_cast<uint16_t>(finder->soil_max)) {\n                    *failed_match = true;\n                    return;\n                }\n\n                \/\/  Freezing\n                if (result->min_temperature > survey_results->at(x).at(y).min_temperature[mlt->biome_offset]) {\n                    result->min_temperature = survey_results->at(x).at(y).min_temperature[mlt->biome_offset];\n                }\n\n                if (result->max_temperature < survey_results->at(x).at(y).max_temperature[mlt->biome_offset]) {\n                    result->max_temperature = survey_results->at(x).at(y).max_temperature[mlt->biome_offset];\n                }\n\n                if (result->min_temperature <= 0 &&\n                    finder->freezing == embark_assist::defs::freezing_ranges::FREEZING_NEVER) {\n                    *failed_match = true;\n                    return;\n                }\n\n                if (result->max_temperature > 0 &&\n                    finder->freezing == embark_assist::defs::freezing_ranges::FREEZING_PERMANENT) {\n                    *failed_match = true;\n                    return;\n                }\n\n                \/\/ Trees\n                if (result->min_trees_found > mlt->trees) {\n                    result->min_trees_found = mlt->trees;\n\n                    switch (finder->min_trees) {\n                    case embark_assist::defs::tree_ranges::TREE_NA:\n                    case embark_assist::defs::tree_ranges::TREE_NONE:\n                        break;\n\n                    case embark_assist::defs::tree_ranges::TREE_VERY_SCARCE:\n                        if (result->min_trees_found < embark_assist::defs::tree_levels::TREE_LEVEL_VERY_SCARCE) {\n                            *failed_match = true;\n                            return;\n                        }\n                        break;\n\n                    case embark_assist::defs::tree_ranges::TREE_SCARCE:\n                        if (result->min_trees_found < embark_assist::defs::tree_levels::TREE_LEVEL_SCARCE) {\n                            *failed_match = true;\n                            return;\n                        }\n\n                    case embark_assist::defs::tree_ranges::TREE_WOODLAND:\n                        if (result->min_trees_found < embark_assist::defs::tree_levels::TREE_LEVEL_WOODLAND) {\n                            *failed_match = true;\n                            return;\n                        }\n                        break;\n\n                    case embark_assist::defs::tree_ranges::TREE_HEAVILY_FORESTED:\n                        if (result->min_trees_found < embark_assist::defs::tree_levels::TREE_LEVEL_HEAVILY_FORESTED) {\n                            *failed_match = true;\n                            return;\n                        }\n                        break;\n                    }\n                }\n\n                if (result->max_trees_found < mlt->trees) {\n                    result->max_trees_found = mlt->trees;\n\n                    switch (finder->max_trees) {\n                    case embark_assist::defs::tree_ranges::TREE_NA:\n                    case embark_assist::defs::tree_ranges::TREE_HEAVILY_FORESTED:\n                        break;\n\n                    case embark_assist::defs::tree_ranges::TREE_NONE:\n                        if (result->max_trees_found > embark_assist::defs::tree_levels::TREE_LEVEL_NONE) {\n                            *failed_match = true;\n                            return;\n                        }\n                        break;\n\n                    case embark_assist::defs::tree_ranges::TREE_VERY_SCARCE:\n                        if (result->max_trees_found > embark_assist::defs::tree_levels::TREE_LEVEL_VERY_SCARCE) {\n                            *failed_match = true;\n                            return;\n                        }\n                        break;\n\n                    case embark_assist::defs::tree_ranges::TREE_SCARCE:\n                        if (result->max_trees_found > embark_assist::defs::tree_levels::TREE_LEVEL_SCARCE) {\n                            *failed_match = true;\n                            return;\n                        }\n                        break;\n\n                    case embark_assist::defs::tree_ranges::TREE_WOODLAND:\n                        if (result->max_trees_found > embark_assist::defs::tree_levels::TREE_LEVEL_WOODLAND) {\n                            *failed_match = true;\n                            return;\n                        }\n                        break;\n                    }\n                }\n\n                \/\/  Blood Rain\n                if (survey_results->at(x).at(y).blood_rain[mlt->biome_offset]) {\n                    if (finder->blood_rain == embark_assist::defs::yes_no_ranges::YES_NO_NO) {\n                        *failed_match = true;\n                        return;\n                    }\n                    result->blood_rain_found = true;\n                }\n\n                \/\/ Syndrome Rain, Permanent\n                if (survey_results->at(x).at(y).permanent_syndrome_rain[mlt->biome_offset]) {\n                    if (finder->syndrome_rain == embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_TEMPORARY ||\n                        finder->syndrome_rain == embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_NOT_PERMANENT ||\n                        finder->syndrome_rain == embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_NONE) {\n                        *failed_match = true;\n                        return;\n                    }\n                    result->permanent_syndrome_rain_found = true;\n                }\n\n                \/\/ Syndrome Rain, Temporary\n                if (survey_results->at(x).at(y).temporary_syndrome_rain[mlt->biome_offset]) {\n                    if (finder->syndrome_rain == embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_PERMANENT ||\n                        finder->syndrome_rain == embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_NONE) {\n                        *failed_match = true;\n                        return;\n                    }\n                    result->temporary_syndrome_rain_found = true;\n                }\n\n                \/\/  Reanmation\n                if (survey_results->at(x).at(y).reanimating[mlt->biome_offset]) {\n                    if (finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_THRALLING ||\n                        finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_NONE) {\n                        *failed_match = true;\n                        return;\n                    }\n                    result->reanimation_found = true;\n                }\n\n                \/\/  Thralling\n                if (survey_results->at(x).at(y).thralling[mlt->biome_offset]) {\n                    if (finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_REANIMATION ||\n                        finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_NOT_THRALLING ||\n                        finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_NONE) {\n                        *failed_match = true;\n                        return;\n                    }\n                    result->thralling_found = true;\n                }\n\n                \/\/  Spires. N\/A for incursions\n                \/\/  Magma. N\/A for incursions\n                \/\/  Biomes\n\n                result->biomes[survey_results->at(x).at(y).biome[mlt->biome_offset]] = true;\n\n                \/\/  Region Type\n                result->region_types[world_data->regions[survey_results->at(x).at(y).biome_index[mlt->biome_offset]]->type] = true;\n\n                \/\/  Metals. N\/A for incursions\n                \/\/  Economics. N\/A for incursions\n                \/\/  Neighbors. N\/A for incursions\n        }\n\n        \/\/=======================================================================================\n\n\n        void process_embark_incursion_mid_level_tile(uint8_t from_direction,\n            matcher_info *result,\n            embark_assist::defs::world_tile_data *survey_results,\n            embark_assist::defs::mid_level_tiles *mlt,\n            embark_assist::defs::finders *finder,\n            uint16_t x,\n            uint16_t y,\n            uint8_t i,\n            uint8_t k,\n            bool *failed_match) {\n            int8_t fetch_i = i;\n            int8_t fetch_k = k;\n            int16_t fetch_x = x;\n            int16_t fetch_y = y;\n            df::world_data *world_data = world->world_data;\n\n            \/\/  Logic can be implemented with modulo and division, but that's harder to read.\n            switch (from_direction) {\n            case 0:\n                fetch_i = i - 1;\n                fetch_k = k - 1;\n                break;\n\n            case 1:\n                fetch_k = k - 1;\n                break;\n\n            case 2:\n                fetch_i = i + 1;\n                fetch_k = k - 1;\n                break;\n\n            case 3:\n                fetch_i = i - 1;\n                break;\n\n            case 4:\n                return;   \/\/  Own tile provides the data, so there's no incursion.\n                break;\n\n            case 5:\n                fetch_i = i + 1;\n                break;\n\n            case 6:\n                fetch_i = i - 1;\n                fetch_k = k + 1;\n                break;\n\n            case 7:\n                fetch_k = k + 1;\n                break;\n\n            case 8:\n                fetch_i = i + 1;\n                fetch_k = k + 1;\n            }\n\n            if (fetch_i < 0) {\n                fetch_x = x - 1;\n            }\n            else if (fetch_i > 15) {\n                fetch_x = x + 1;\n            }\n\n            if (fetch_k < 0) {\n                fetch_y = y - 1;\n            }\n            else if (fetch_k > 15) {\n                fetch_y = y + 1;\n            }\n\n            if (fetch_x < 0 ||\n                fetch_x == world_data->world_width ||\n                fetch_y < 0 ||\n                fetch_y == world_data->world_height) {\n                return;  \/\/  We're at the world edge, so no incursions from the outside.\n            }\n\n            if (!&survey_results->at(fetch_x).at(fetch_y).surveyed) {\n                *failed_match = true;\n                return;\n            }\n\n            if (fetch_k < 0) {\n                if (fetch_i < 0) {\n                    process_embark_incursion(result,\n                        survey_results,\n                        &survey_results->at(fetch_x).at(fetch_y).south_row[15],\n                        finder,\n                        mlt->at(i).at(k).elevation,\n                        fetch_x,\n                        fetch_y,\n                        failed_match);\n                }\n                else if (fetch_i > 15) {\n                    process_embark_incursion(result,\n                        survey_results,\n                        &survey_results->at(fetch_x).at(fetch_y).south_row[0],\n                        finder,\n                        mlt->at(i).at(k).elevation,\n                        fetch_x,\n                        fetch_y,\n                        failed_match);\n                }\n                else {\n                    process_embark_incursion(result,\n                        survey_results,\n                        &survey_results->at(fetch_x).at(fetch_y).south_row[i],\n                        finder,\n                        mlt->at(i).at(k).elevation,\n                        fetch_x,\n                        fetch_y,\n                        failed_match);\n                }\n            }\n            else if (fetch_k > 15) {\n                if (fetch_i < 0) {\n                    process_embark_incursion(result,\n                        survey_results,\n                        &survey_results->at(fetch_x).at(fetch_y).north_row[15],\n                        finder,\n                        mlt->at(i).at(k).elevation,\n                        fetch_x,\n                        fetch_y,\n                        failed_match);\n                }\n                else if (fetch_i > 15) {\n                    process_embark_incursion(result,\n                        survey_results,\n                        &survey_results->at(fetch_x).at(fetch_y).north_row[0],\n                        finder,\n                        mlt->at(i).at(k).elevation,\n                        fetch_x,\n                        fetch_y,\n                        failed_match);\n                }\n                else {\n                    process_embark_incursion(result,\n                        survey_results,\n                        &survey_results->at(fetch_x).at(fetch_y).north_row[i],\n                        finder,\n                        mlt->at(i).at(k).elevation,\n                        fetch_x,\n                        fetch_y,\n                        failed_match);\n                }\n            }\n            else {\n                if (fetch_i < 0) {\n                    process_embark_incursion(result,\n                        survey_results,\n                        &survey_results->at(fetch_x).at(fetch_y).east_column[k],\n                        finder,\n                        mlt->at(i).at(k).elevation,\n                        fetch_x,\n                        fetch_y,\n                        failed_match);\n                }\n                else if (fetch_i > 15) {\n                    process_embark_incursion(result,\n                        survey_results,\n                        &survey_results->at(fetch_x).at(fetch_y).west_column[k],\n                        finder,\n                        mlt->at(i).at(k).elevation,\n                        fetch_x,\n                        fetch_y,\n                        failed_match);\n                }\n                else {\n                    process_embark_incursion(result,\n                        survey_results,\n                        &mlt->at(fetch_i).at(fetch_k),\n                        finder,\n                        mlt->at(i).at(k).elevation,\n                        fetch_x,\n                        fetch_y,\n                        failed_match);\n                }\n            }\n        }\n\n        \/\/=======================================================================================\n\n        bool embark_match(embark_assist::defs::world_tile_data *survey_results,\n            embark_assist::defs::mid_level_tiles *mlt,\n            uint16_t x,\n            uint16_t y,\n            uint16_t start_x,\n            uint16_t start_y,\n            embark_assist::defs::finders *finder) {\n\n\/\/            color_ostream_proxy out(Core::getInstance().getConsole());\n            df::world_data *world_data = world->world_data;\n            matcher_info result;\n            result.elevation = mlt->at(start_x).at(start_y).elevation;\n            result.min_temperature = survey_results->at(x).at(y).min_temperature[mlt->at(start_x).at(start_y).biome_offset];\n            result.max_temperature = survey_results->at(x).at(y).max_temperature[mlt->at(start_x).at(start_y).biome_offset];\n            result.metal_1 = finder->metal_1 == -1;\n            result.metal_2 = finder->metal_2 == -1;\n            result.metal_3 = finder->metal_3 == -1;\n            result.economic_1 = finder->economic_1 == -1;\n            result.economic_2 = finder->economic_2 == -1;\n            result.economic_3 = finder->economic_3 == -1;\n            result.mineral_1 = finder->mineral_1 == -1;\n            result.mineral_2 = finder->mineral_2 == -1;\n            result.mineral_3 = finder->mineral_3 == -1;\n            bool failed_match = false;\n\n            const uint16_t embark_size = finder->x_dim * finder->y_dim;\n\n            if (finder->biome_count_min != -1 ||\n                finder->biome_count_max != -1 ||\n                finder->biome_1 != -1 ||\n                finder->biome_2 != -1 ||\n                finder->biome_3 != -1) {\n                for (uint8_t i = 0; i <= ENUM_LAST_ITEM(biome_type); i++) result.biomes[i] = false;\n            }\n\n            for (uint8_t i = 0; i <= ENUM_LAST_ITEM(world_region_type); i++) result.region_types[i] = false;\n\n            for (uint16_t i = start_x; i < start_x + finder->x_dim; i++) {\n                for (uint16_t k = start_y; k < start_y + finder->y_dim; k++) {\n\n                    \/\/ Savagery & Evilness\n                    {\n                        result.savagery_found[mlt->at(i).at(k).savagery_level] = true;\n                        result.evilness_found[mlt->at(i).at(k).evilness_level] = true;\n\n                        embark_assist::defs::evil_savagery_ranges l = embark_assist::defs::evil_savagery_ranges::EVIL_SAVAGERY_LOW;\n                        while (true) {\n                            if (mlt->at(i).at(k).savagery_level == static_cast<uint8_t>(l)) {\n                                if (finder->savagery[static_cast <int>(l)] ==\n                                    embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ABSENT) return false;\n                            }\n                            else {\n                                if (finder->savagery[static_cast <int>(l)] ==\n                                    embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ALL) return false;\n                            }\n\n                            if (mlt->at(i).at(k).evilness_level == static_cast<uint8_t>(l)) {\n                                if (finder->evilness[static_cast <int>(l)] ==\n                                    embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ABSENT) return false;\n                            }\n                            else {\n                                if (finder->evilness[static_cast <int>(l)] ==\n                                    embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ALL) return false;\n                            }\n\n                            if (l == embark_assist::defs::evil_savagery_ranges::EVIL_SAVAGERY_HIGH) break;\n                            l = static_cast <embark_assist::defs::evil_savagery_ranges>(static_cast<int8_t>(l) + 1);\n                        }\n                    }\n\n                    \/\/  Aquifer\n                    result.aquifer = static_cast<embark_assist::defs::aquifer_sizes>(static_cast<int8_t>(result.aquifer) | static_cast<int8_t>(mlt->at(i).at(k).aquifer));\n\n                    switch (finder->aquifer) {\n                    case embark_assist::defs::aquifer_ranges::AQUIFER_NA:\n                        break;\n\n                    case embark_assist::defs::aquifer_ranges::AQUIFER_NONE:\n                        if (result.aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE) return false;\n                        break;\n\n                    case embark_assist::defs::aquifer_ranges::AQUIFER_AT_MOST_LIGHT:\n                    case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_PLUS_LIGHT:\n                        if (static_cast<int8_t>(result.aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_HEAVY)) return false;\n                        break;\n\n                    case embark_assist::defs::aquifer_ranges::AQUIFER_LIGHT:\n                        if (result.aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_LIGHT) return false;\n                        break;\n\n                    case embark_assist::defs::aquifer_ranges::AQUIFER_AT_LEAST_LIGHT:\n                    case embark_assist::defs::aquifer_ranges::AQUIFER_LIGHT_PLUS_HEAVY:\n                        if (static_cast<int8_t>(result.aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE)) return false;\n                        break;\n\n                    case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_PLUS_HEAVY:\n                        if (static_cast<int8_t>(result.aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_LIGHT)) return false;\n                        break;\n\n                    case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_PLUS_AT_LEAST_LIGHT:\n                    case embark_assist::defs::aquifer_ranges::AQUIFER_AT_MOST_LIGHT_PLUS_HEAVY:\n                    case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_LIGHT_HEAVY:\n                        break;\n\n                    case embark_assist::defs::aquifer_ranges::AQUIFER_HEAVY:\n                        if (result.aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_HEAVY) return false;\n                        break;\n                    }\n\n                    \/\/  River & Waterfall\n                    if (mlt->at(i).at(k).river_present) {\n                        \/\/  Actual size values were checked on the world tile level for min rivers\n                        if (finder->max_river != embark_assist::defs::river_ranges::RIVER_NA &&\n                            finder->max_river < static_cast<embark_assist::defs::river_ranges>(survey_results->at(x).at(y).river_size)) return false;\n\n                        if (i < start_x + finder->x_dim - 2 &&\n                            mlt->at(i + 1).at(k).river_present &&\n                            abs(mlt->at(i).at(k).river_elevation - mlt->at(i + 1).at(k).river_elevation) > result.max_waterfall) {\n                            if (finder->min_waterfall == 0) return false;  \/\/ 0 = Absent\n                            result.max_waterfall =\n                                abs(mlt->at(i).at(k).river_elevation - mlt->at(i + 1).at(k).river_elevation);\n                        }\n\n                        if (k < start_y + finder->y_dim - 2 &&\n                            mlt->at(i).at(k + 1).river_present &&\n                            abs(mlt->at(i).at(k).river_elevation - mlt->at(i).at(k + 1).river_elevation) > result.max_waterfall) {\n                            if (finder->min_waterfall == 0) return false;  \/\/ 0 = Absent\n                            result.max_waterfall =\n                                abs(mlt->at(i).at(k).river_elevation - mlt->at(i).at(k + 1).river_elevation);\n                        }\n\n                        result.river_found = true;\n                    }\n\n                    \/\/  Flat\n                    if (finder->flat == embark_assist::defs::yes_no_ranges::YES_NO_YES &&\n                        result.elevation != mlt->at(i).at(k).elevation) return false;\n\n                    if (result.elevation != mlt->at(i).at(k).elevation) result.uneven = true;\n\n                    \/\/ Clay\n                    if (mlt->at(i).at(k).clay) {\n                        if (finder->clay == embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT) return false;\n                        result.clay_found = true;\n                    }\n\n                    \/\/ Sand\n                    if (mlt->at(i).at(k).sand) {\n                        if (finder->sand == embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT) return false;\n                        result.sand_found = true;\n                    }\n\n                    \/\/ Flux\n                    if (mlt->at(i).at(k).flux) {\n                        if (finder->flux == embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT) return false;\n                        result.flux_found = true;\n                    }\n\n                    \/\/ Coal\n                    if (mlt->at(i).at(k).coal) {\n                        if (finder->coal == embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT) return false;\n                        result.coal_found = true;\n                    }\n\n                    \/\/  Min Soil\n                    if (finder->soil_min != embark_assist::defs::soil_ranges::SOIL_NA &&\n                        mlt->at(i).at(k).soil_depth < static_cast<uint16_t>(finder->soil_min) &&\n                        finder->soil_min_everywhere == embark_assist::defs::all_present_ranges::ALL_PRESENT_ALL) return false;\n\n                    if (result.max_soil < mlt->at(i).at(k).soil_depth) {\n                        result.max_soil = mlt->at(i).at(k).soil_depth;\n                    }\n\n                    \/\/  Max Soil\n                    if (finder->soil_max != embark_assist::defs::soil_ranges::SOIL_NA &&\n                        mlt->at(i).at(k).soil_depth > static_cast<uint16_t>(finder->soil_max)) return false;\n\n                    \/\/  Freezing\n                    if (result.min_temperature > survey_results->at(x).at(y).min_temperature[mlt->at(i).at(k).biome_offset]) {\n                        result.min_temperature = survey_results->at(x).at(y).min_temperature[mlt->at(i).at(k).biome_offset];\n                    }\n\n                    if (result.max_temperature < survey_results->at(x).at(y).max_temperature[mlt->at(i).at(k).biome_offset]) {\n                        result.max_temperature = survey_results->at(x).at(y).max_temperature[mlt->at(i).at(k).biome_offset];\n                    }\n\n                    if (result.min_temperature <= 0 &&\n                        finder->freezing == embark_assist::defs::freezing_ranges::FREEZING_NEVER) return false;\n\n                    if (result.max_temperature > 0 &&\n                        finder->freezing == embark_assist::defs::freezing_ranges::FREEZING_PERMANENT) return false;\n\n\n                    \/\/ Trees\n                    if (result.min_trees_found > mlt->at(i).at(k).trees) {\n                        result.min_trees_found = mlt->at(i).at(k).trees;\n\n                        switch (finder->min_trees) {\n                        case embark_assist::defs::tree_ranges::TREE_NA:\n                        case embark_assist::defs::tree_ranges::TREE_NONE:\n                            break;\n\n                        case embark_assist::defs::tree_ranges::TREE_VERY_SCARCE:\n                            if (result.min_trees_found < embark_assist::defs::tree_levels::TREE_LEVEL_VERY_SCARCE) return false;\n                            break;\n\n                        case embark_assist::defs::tree_ranges::TREE_SCARCE:\n                            if (result.min_trees_found < embark_assist::defs::tree_levels::TREE_LEVEL_SCARCE) return false;\n                            break;\n\n                        case embark_assist::defs::tree_ranges::TREE_WOODLAND:\n                            if (result.min_trees_found < embark_assist::defs::tree_levels::TREE_LEVEL_WOODLAND) return false;\n                            break;\n\n                        case embark_assist::defs::tree_ranges::TREE_HEAVILY_FORESTED:\n                            if (result.min_trees_found < embark_assist::defs::tree_levels::TREE_LEVEL_HEAVILY_FORESTED) return false;\n                            break;\n                        }\n                    }\n\n                    if (result.max_trees_found < mlt->at(i).at(k).trees) {\n                        result.max_trees_found = mlt->at(i).at(k).trees;\n\n                        switch (finder->max_trees) {\n                        case embark_assist::defs::tree_ranges::TREE_NA:\n                        case embark_assist::defs::tree_ranges::TREE_HEAVILY_FORESTED:\n                            break;\n\n                        case embark_assist::defs::tree_ranges::TREE_NONE:\n                            if (result.max_trees_found > embark_assist::defs::tree_levels::TREE_LEVEL_NONE) return false;\n                            break;\n\n                        case embark_assist::defs::tree_ranges::TREE_VERY_SCARCE:\n                            if (result.max_trees_found > embark_assist::defs::tree_levels::TREE_LEVEL_VERY_SCARCE) return false;\n                            break;\n\n                        case embark_assist::defs::tree_ranges::TREE_SCARCE:\n                            if (result.max_trees_found > embark_assist::defs::tree_levels::TREE_LEVEL_SCARCE) return false;\n                            break;\n\n                        case embark_assist::defs::tree_ranges::TREE_WOODLAND:\n                            if (result.max_trees_found > embark_assist::defs::tree_levels::TREE_LEVEL_WOODLAND) return false;\n                            break;\n                        }\n                    }\n\n                    \/\/  Blood Rain\n                    if (survey_results->at(x).at(y).blood_rain[mlt->at(i).at(k).biome_offset]) {\n                        if (finder->blood_rain == embark_assist::defs::yes_no_ranges::YES_NO_NO) return false;\n                        result.blood_rain_found = true;\n                    }\n\n                    \/\/ Syndrome Rain, Permanent\n                    if (survey_results->at(x).at(y).permanent_syndrome_rain[mlt->at(i).at(k).biome_offset]) {\n                        if (finder->syndrome_rain == embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_TEMPORARY ||\n                            finder->syndrome_rain == embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_NOT_PERMANENT ||\n                            finder->syndrome_rain == embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_NONE) return false;\n                        result.permanent_syndrome_rain_found = true;\n                    }\n\n                    \/\/ Syndrome Rain, Temporary\n                    if (survey_results->at(x).at(y).temporary_syndrome_rain[mlt->at(i).at(k).biome_offset]) {\n                        if (finder->syndrome_rain == embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_PERMANENT ||\n                            finder->syndrome_rain == embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_NONE) return false;\n                        result.temporary_syndrome_rain_found = true;\n                    }\n\n                    \/\/  Reanmation\n                    if (survey_results->at(x).at(y).reanimating[mlt->at(i).at(k).biome_offset]) {\n                        if (finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_THRALLING ||\n                            finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_NONE) return false;\n                        result.reanimation_found = true;\n                    }\n\n                    \/\/  Thralling\n                    if (survey_results->at(x).at(y).thralling[mlt->at(i).at(k).biome_offset]) {\n                        if (finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_REANIMATION ||\n                            finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_NOT_THRALLING ||\n                            finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_NONE) return false;\n                        result.thralling_found = true;\n                    }\n\n                    \/\/  Spires\n                    if (mlt->at(i).at(k).adamantine_level != -1) {\n                        result.spire_count++;\n\n                        if (finder->spire_count_max != -1 &&\n                            finder->spire_count_max < result.spire_count) return false;\n                    }\n\n                    \/\/  Magma\n                    if (mlt->at(i).at(k).magma_level != -1) {\n                        if (mlt->at(i).at(k).magma_level > result.magma_level)\n                        {\n                            result.magma_level = mlt->at(i).at(k).magma_level;\n                            if (finder->magma_max != embark_assist::defs::magma_ranges::MAGMA_NA &&\n                                static_cast<int8_t>(finder->magma_max) < result.magma_level) return false;\n                        }\n                    }\n\n                    \/\/  Biomes\n                    result.biomes[survey_results->at(x).at(y).biome[mlt->at(i).at(k).biome_offset]] = true;\n\n                    \/\/  Region Type\n                    result.region_types[world_data->regions[survey_results->at(x).at(y).biome_index[mlt->at(i).at(k).biome_offset]]->type] = true;\n                \n                    \/\/  Metals\n                    result.metal_1 = result.metal_1 || mlt->at(i).at(k).metals[finder->metal_1];\n                    result.metal_2 = result.metal_2 || mlt->at(i).at(k).metals[finder->metal_2];\n                    result.metal_3 = result.metal_3 || mlt->at(i).at(k).metals[finder->metal_3];\n\n                    \/\/  Economics\n                    result.economic_1 = result.economic_1 || mlt->at(i).at(k).economics[finder->economic_1];\n                    result.economic_2 = result.economic_2 || mlt->at(i).at(k).economics[finder->economic_2];\n                    result.economic_3 = result.economic_3 || mlt->at(i).at(k).economics[finder->economic_3];\n\n                    \/\/  Minerals\n                    result.mineral_1 = result.mineral_1 || mlt->at(i).at(k).minerals[finder->mineral_1];\n                    result.mineral_2 = result.mineral_2 || mlt->at(i).at(k).minerals[finder->mineral_2];\n                    result.mineral_3 = result.mineral_3 || mlt->at(i).at(k).minerals[finder->mineral_3];\n                }\n            }\n\n            \/\/  Take incursions into account.\n\n            for (int8_t i = start_x; i < start_x + finder->x_dim; i++) {\n\n                \/\/  NW corner, north row\n                if ((i == 0 && start_y == 0 && x - 1 >= 0 && y - 1 >= 0 && !survey_results->at(x - 1).at(y - 1).surveyed) ||\n                    (i == 0 && x - 1 >= 0 && !survey_results->at(x - 1).at(y).surveyed) ||\n                    (start_y == 0 && y - 1 >= 0 && !survey_results->at(x).at(y - 1).surveyed)) {\n                    failed_match = true;\n                }\n                else {\n                    process_embark_incursion_mid_level_tile\n                    (embark_assist::survey::translate_corner(survey_results,\n                        4,\n                        x,\n                        y,\n                        i,\n                        start_y),\n                        &result,\n                        survey_results,\n                        mlt,\n                        finder,\n                        x,\n                        y,\n                        i,\n                        start_y,\n                        &failed_match);\n                }\n\n                \/\/  N edge, north row\n                if (start_y == 0 && y - 1 >= 0 && !survey_results->at(x).at(y - 1).surveyed) {\n                    failed_match = true;\n                }\n                else {\n                    process_embark_incursion_mid_level_tile\n                    (embark_assist::survey::translate_ns_edge(survey_results,\n                        true,\n                        x,\n                        y,\n                        i,\n                        start_y),\n                        &result,\n                        survey_results,\n                        mlt,\n                        finder,\n                        x,\n                        y,\n                        i,\n                        start_y,\n                        &failed_match);\n                }\n\n                \/\/  NE corner, north row\n                if ((i == 15 && start_y == 0 && x + 1 < world_data->world_width && y - 1 >= 0 && !survey_results->at(x + 1).at(y - 1).surveyed) ||\n                    (i == 15 && x + 1 < world_data->world_width && !survey_results->at(x + 1).at(y).surveyed) ||\n                    (start_y == 0 && y - 1 >= 0 && !survey_results->at(x).at(y - 1).surveyed)) {\n                    failed_match = true;\n                }\n                else {\n                    process_embark_incursion_mid_level_tile\n                    (embark_assist::survey::translate_corner(survey_results,\n                        5,\n                        x,\n                        y,\n                        i,\n                        start_y),\n                        &result,\n                        survey_results,\n                        mlt,\n                        finder,\n                        x,\n                        y,\n                        i,\n                        start_y,\n                        &failed_match);\n                }\n\n                \/\/  SW corner, south row\n                if ((i == 0 && start_y + finder->y_dim == 16 && x - 1 >= 0 && y + 1 < world_data->world_height && !survey_results->at(x - 1).at(y + 1).surveyed) ||\n                    (i == 0 && x - 1 >= 0 && !survey_results->at(x - 1).at(y).surveyed) ||\n                    (start_y + finder->y_dim == 16 && y + 1 < world_data->world_height && !survey_results->at(x).at(y + 1).surveyed)) {\n                    failed_match = true;\n                }\n                else {\n                    process_embark_incursion_mid_level_tile\n                    (embark_assist::survey::translate_corner(survey_results,\n                        7,\n                        x,\n                        y,\n                        i,\n                        start_y + finder->y_dim - 1),\n                        &result,\n                        survey_results,\n                        mlt,\n                        finder,\n                        x,\n                        y,\n                        i,\n                        start_y + finder->y_dim - 1,\n                        &failed_match);\n                }\n\n                \/\/  S edge, south row\n                if (start_y + finder->y_dim == 16 && y + 1 < world_data->world_height && !survey_results->at(x).at(y + 1).surveyed) {\n                    failed_match = true;\n                }\n                else {\n                    process_embark_incursion_mid_level_tile\n                    (embark_assist::survey::translate_ns_edge(survey_results,\n                        false,\n                        x,\n                        y,\n                        i,\n                        start_y + finder->y_dim - 1),\n                        &result,\n                        survey_results,\n                        mlt,\n                        finder,\n                        x,\n                        y,\n                        i,\n                        start_y + finder->y_dim - 1,\n                        &failed_match);\n                }\n\n                \/\/  SE corner south row\n                if ((i == 15 && start_y + finder->y_dim == 16 && x + 1 < world_data->world_width && y + 1 < world_data->world_height && !survey_results->at(x + 1).at(y + 1).surveyed) ||\n                    (i == 15 && x + 1 < world_data->world_width && !survey_results->at(x + 1).at(y).surveyed) ||\n                    (start_y + finder->y_dim == 16 && y + 1 < world_data->world_height && !survey_results->at(x).at(y + 1).surveyed)) {\n                    failed_match = true;\n                }\n                else {\n                    process_embark_incursion_mid_level_tile\n                    (embark_assist::survey::translate_corner(survey_results,\n                        8,\n                        x,\n                        y,\n                        i,\n                        start_y + finder->y_dim - 1),\n                        &result,\n                        survey_results,\n                        mlt,\n                        finder,\n                        x,\n                        y,\n                        i,\n                        start_y + finder->y_dim - 1,\n                        &failed_match);\n                }\n\n                if (failed_match) return false;\n           }\n\n           for (int8_t k = start_y; k < start_y + finder->y_dim; k++) {\n                \/\/ NW corner, west side\n               if ((start_x == 0 && x - 1 >= 0 && !survey_results->at(x - 1).at(y).surveyed)) {\n                   failed_match = true;\n               }\n               else if (k > start_y) { \/\/    We've already covered the NW corner of the NW, with its complications.\n                   process_embark_incursion_mid_level_tile\n                   (embark_assist::survey::translate_corner(survey_results,\n                       4,\n                       x,\n                       y,\n                       start_x,\n                       k),\n                       &result,\n                       survey_results,\n                       mlt,\n                       finder,\n                       x,\n                       y,\n                       start_x,\n                       k,\n                       &failed_match);\n               }\n\n               \/\/ W edge, west side\n               if (start_x == 0 && x - 1 >= 0 && !survey_results->at(x - 1).at(y).surveyed) {\n                   failed_match = true;\n               }\n               else {\n                   process_embark_incursion_mid_level_tile\n                   (embark_assist::survey::translate_ew_edge(survey_results,\n                       true,\n                       x,\n                       y,\n                       start_x,\n                       k),\n                       &result,\n                       survey_results,\n                       mlt,\n                       finder,\n                       x,\n                       y,\n                       start_x,\n                       k,\n                       &failed_match);\n               }\n\n                \/\/ SW corner, west side\n               if (start_x == 0 && x - 1 >= 0 && !survey_results->at(x - 1).at(y).surveyed) {\n                   failed_match = true;\n               }\n               else if (k < start_y + finder->y_dim - 1) { \/\/  We've already covered the SW corner of the SW tile, with its complicatinons.\n                   process_embark_incursion_mid_level_tile\n                   (embark_assist::survey::translate_corner(survey_results,\n                       7,\n                       x,\n                       y,\n                       start_x,\n                       k),\n                       &result,\n                       survey_results,\n                       mlt,\n                       finder,\n                       x,\n                       y,\n                       start_x,\n                       k,\n                       &failed_match);\n               }\n\n                \/\/ NE corner, east side\n               if ((start_x + finder->x_dim == 16 && x + 1 < world_data->world_width && !survey_results->at(x + 1).at(y).surveyed)) {\n                   failed_match = true;\n               }\n               else if (k > start_y) { \/\/  We've already covered the NE tile's NE corner, with its complications.\n                   process_embark_incursion_mid_level_tile\n                   (embark_assist::survey::translate_corner(survey_results,\n                       5,\n                       x,\n                       y,\n                       start_x + finder->x_dim - 1,\n                       k),\n                       &result,\n                       survey_results,\n                       mlt,\n                       finder,\n                       x,\n                       y,\n                       start_x + finder->x_dim - 1,\n                       k,\n                       &failed_match);\n               }\n\n               \/\/ E edge, east side\n               if (start_x + finder->y_dim == 16 && x + 1 < world_data->world_width && !survey_results->at(x + 1).at(y).surveyed) {\n                   failed_match = true;\n               }\n               else {\n                   process_embark_incursion_mid_level_tile\n                   (embark_assist::survey::translate_ew_edge(survey_results,\n                       false,\n                       x,\n                       y,\n                       start_x + finder->x_dim - 1,\n                       k),\n                       &result,\n                       survey_results,\n                       mlt,\n                       finder,\n                       x,\n                       y,\n                       start_x + finder->x_dim - 1,\n                       k,\n                       &failed_match);\n               }\n\n                \/\/ SE corner, east side\n               if (start_x + finder->x_dim == 16 && x + 1 < world_data->world_width && !survey_results->at(x + 1).at(y).surveyed) {\n                   failed_match = true;\n               }\n               else if (k < start_y + finder->y_dim - 1) { \/\/  We've already covered the SE tile's SE corner, with its complications.\n                   process_embark_incursion_mid_level_tile\n                   (embark_assist::survey::translate_corner(survey_results,\n                       8,\n                       x,\n                       y,\n                       start_x + finder->x_dim - 1,\n                       k),\n                       &result,\n                       survey_results,\n                       mlt,\n                       finder,\n                       x,\n                       y,\n                       start_x + finder->x_dim - 1,\n                       k,\n                       &failed_match);\n               }\n \n                if (failed_match) return false;\n           }\n\n            \/\/  Summary section, for all the stuff that require the complete picture\n            \/\/\n            \/\/ Savagery & Evilness\n            {\n                embark_assist::defs::evil_savagery_ranges l = embark_assist::defs::evil_savagery_ranges::EVIL_SAVAGERY_LOW;\n\n                while (true) {\n                    if (finder->savagery[static_cast <int>(l)] ==\n                        embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_PRESENT &&\n                        !result.savagery_found[static_cast<int>(l)]) return false;\n\n                    if (finder->evilness[static_cast <int>(l)] ==\n                        embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_PRESENT &&\n                        !result.evilness_found[static_cast<int>(l)]) return false;\n\n                    if (l == embark_assist::defs::evil_savagery_ranges::EVIL_SAVAGERY_HIGH) break;\n                    l = static_cast <embark_assist::defs::evil_savagery_ranges>(static_cast<int8_t>(l) + 1);\n                }\n            }\n\n            \/\/  Aquifer\n            switch (finder->aquifer) {\n            case embark_assist::defs::aquifer_ranges::AQUIFER_NA:\n            case embark_assist::defs::aquifer_ranges::AQUIFER_NONE:          \/\/  Checked above\n            case embark_assist::defs::aquifer_ranges::AQUIFER_LIGHT:         \/\/  Ditto\n            case embark_assist::defs::aquifer_ranges::AQUIFER_HEAVY:         \/\/  Ditto\n            case embark_assist::defs::aquifer_ranges::AQUIFER_AT_MOST_LIGHT: \/\/  Ditto\n            case embark_assist::defs::aquifer_ranges::AQUIFER_AT_LEAST_LIGHT:\/\/  Ditto\n                break;\n\n            case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_PLUS_LIGHT:\n                if (result.aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE_LIGHT) return false;\n                break;\n\n            case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_PLUS_AT_LEAST_LIGHT:\n                if (result.aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE_LIGHT &&\n                    result.aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE_HEAVY) return false;\n                break;\n\n            case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_PLUS_HEAVY:\n                if (result.aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE_HEAVY) return false;\n                break;\n\n            case embark_assist::defs::aquifer_ranges::AQUIFER_AT_MOST_LIGHT_PLUS_HEAVY:\n                if (result.aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE_HEAVY &&\n                    result.aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_LIGHT_HEAVY) return false;\n                break;\n\n            case embark_assist::defs::aquifer_ranges::AQUIFER_LIGHT_PLUS_HEAVY:\n                if (result.aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_LIGHT_HEAVY) return false;\n                break;\n\n            case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_LIGHT_HEAVY:\n                if (result.aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE_LIGHT_HEAVY) return false;\n                break;\n            }\n\n            \/\/  River & Waterfall\n            if (!result.river_found && finder->min_river > embark_assist::defs::river_ranges::RIVER_NONE) return false;\n            if (result.max_waterfall < finder->min_waterfall) return false;  \/\/ N\/A = -1 is always smaller, so no additional check needed.\n\n            \/\/  Flat\n            if (!result.uneven && finder->flat == embark_assist::defs::yes_no_ranges::YES_NO_NO) return false;\n\n            \/\/  Clay\n            if (finder->clay == embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT && !result.clay_found) return false;\n\n            \/\/  Sand\n            if (finder->sand == embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT && !result.sand_found) return false;\n\n            \/\/  Flux\n            if (finder->flux == embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT && !result.flux_found) return false;\n\n            \/\/  Coal\n            if (finder->coal == embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT && !result.coal_found) return false;\n\n            \/\/  Min Soil\n            if (finder->soil_min != embark_assist::defs::soil_ranges::SOIL_NA &&\n                finder->soil_min_everywhere == embark_assist::defs::all_present_ranges::ALL_PRESENT_PRESENT &&\n                result.max_soil < static_cast<uint8_t>(finder->soil_min)) return false;\n\n            \/\/  Freezing\n            if (finder->freezing == embark_assist::defs::freezing_ranges::FREEZING_AT_LEAST_PARTIAL &&\n                result.min_temperature > 0) return false;\n\n            if (finder->freezing == embark_assist::defs::freezing_ranges::FREEZING_PARTIAL &&\n                (result.min_temperature > 0 ||\n                    result.max_temperature <= 0)) return false;\n\n            if (finder->freezing == embark_assist::defs::freezing_ranges::FREEZING_AT_MOST_PARTIAL &&\n                result.max_temperature <= 0) return false;\n\n            \/\/  Trees. Mismatches already dealt with\n\n            \/\/  Blood Rain\n            if (finder->blood_rain == embark_assist::defs::yes_no_ranges::YES_NO_YES && !result.blood_rain_found) return false;\n\n            \/\/  Syndrome Rain\n            if (finder->syndrome_rain == embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_ANY && !result.permanent_syndrome_rain_found && !result.temporary_syndrome_rain_found) return false;\n            if (finder->syndrome_rain == embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_PERMANENT && !result.permanent_syndrome_rain_found) return false;\n            if (finder->syndrome_rain == embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_TEMPORARY && !result.temporary_syndrome_rain_found) return false;\n\n            \/\/  Reanimation\n            if (finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_BOTH && !(result.reanimation_found && result.thralling_found)) return false;\n            if (finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_ANY && !result.reanimation_found && !result.thralling_found) return false;\n            if (finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_THRALLING && !result.thralling_found) return false;\n            if (finder->reanimation == embark_assist::defs::reanimation_ranges::REANIMATION_REANIMATION && !result.reanimation_found) return false;\n\n            \/\/  Spires\n            if (finder->spire_count_min != -1 && finder->spire_count_min > result.spire_count) return false;\n            if (finder->spire_count_max != -1 && finder->spire_count_max < result.spire_count) return false;\n\n            \/\/  Magma\n            if (\/\/ finder->magma_min != embark_assist::defs::magma_ranges::MAGMA_NA &&  \/\/  This check is redundant.\n                finder->magma_min > static_cast<embark_assist::defs::magma_ranges>(result.magma_level)) return false;\n\n            \/\/  Biomes\n            if (finder->biome_count_min != -1 ||\n                finder->biome_count_max != -1) {\n                result.biome_count = 0;\n                for (uint8_t i = 0; i <= ENUM_LAST_ITEM(biome_type); i++) {\n                    if (result.biomes[i]) result.biome_count++;\n                }\n\n                if (result.biome_count < finder->biome_count_min ||\n                    (finder->biome_count_max != -1 &&\n                        finder->biome_count_max < result.biome_count)) return false;\n            }\n\n            if (finder->biome_1 != -1 && !result.biomes[finder->biome_1]) return false;\n            if (finder->biome_2 != -1 && !result.biomes[finder->biome_2]) return false;\n            if (finder->biome_3 != -1 && !result.biomes[finder->biome_3]) return false;\n\n            \/\/  Region Type\n            if (finder->region_type_1 != -1 && !result.region_types[finder->region_type_1]) return false;\n            if (finder->region_type_2 != -1 && !result.region_types[finder->region_type_2]) return false;\n            if (finder->region_type_3 != -1 && !result.region_types[finder->region_type_3]) return false;\n\n            \/\/  Metals, Economics, and Minerals\n            if (!result.metal_1 ||\n                !result.metal_2 ||\n                !result.metal_3 ||\n                !result.economic_1 ||\n                !result.economic_2 ||\n                !result.economic_3 ||\n                !result.mineral_1 ||\n                !result.mineral_2 ||\n                !result.mineral_3) return false;\n\n            \/\/  Necro neighbors  \/\/  Checked at the world tile level\n            \/\/  Civ neighbors\n            \/\/  Civs\n\n            return true;\n        }\n\n        \/\/=======================================================================================\n\n        void mid_level_tile_match(embark_assist::defs::world_tile_data *survey_results,\n            embark_assist::defs::mid_level_tiles *mlt,\n            uint16_t x,\n            uint16_t y,\n            embark_assist::defs::finders *finder,\n            embark_assist::defs::match_results *match_results) {\n\n\/\/            color_ostream_proxy out(Core::getInstance().getConsole());\n            bool match = false;\n            bool world_tile_match = true;\n            embark_assist::defs::region_tile_datum *world_tile = &survey_results->at(x).at(y);\n\n            \/\/  These world tile checks require that the MLTs have been surveyed to update the world tile data\n            \/\/  Necro Neighbors\n            if (finder->min_necro_neighbors > world_tile->necro_neighbors) world_tile_match = false;\n            if (finder->max_necro_neighbors != -1 && finder->max_necro_neighbors < world_tile->necro_neighbors) world_tile_match = false;\n\n            \/\/  Civ Neighbors\n            if (finder->min_civ_neighbors > (int16_t)world_tile->neighbors.size()) world_tile_match = false;\n            if (finder->max_civ_neighbors != -1 && finder->max_civ_neighbors < (int8_t)world_tile->neighbors.size()) world_tile_match = false;\n\n            \/\/  Specific Neighbors\n            for (uint16_t i = 0; i < finder->neighbors.size(); i++) {\n                switch (finder->neighbors[i].present) {\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_NA:\n                    break;\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT:\n                {\n                    bool found = false;\n\n                    for (uint16_t k = 0; k < world_tile->neighbors.size(); k++) {\n                        if (finder->neighbors[i].entity_raw == world_tile->neighbors[k]) {\n                            found = true;\n                            break;\n                        }\n                    }\n\n                    if (!found) world_tile_match = false;\n\n                    break;\n                }\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT:\n                    for (uint16_t k = 0; k < world_tile->neighbors.size(); k++) {\n                        if (finder->neighbors[i].entity_raw == world_tile->neighbors[k]) {\n                            world_tile_match = false;\n                            break;\n                        }\n                    }\n\n                    break;\n                }\n            }\n\n            for (uint16_t i = 0; i < 16; i++) {\n                for (uint16_t k = 0; k < 16; k++) {\n                    if (world_tile_match && i < 16 - finder->x_dim + 1 && k < 16 - finder->y_dim + 1) {\n                        match_results->at(x).at(y).mlt_match[i][k] = embark_match(survey_results, mlt, x, y, i, k, finder);\n                        match = match || match_results->at(x).at(y).mlt_match[i][k];\n                    }\n                    else {\n                        match_results->at(x).at(y).mlt_match[i][k] = false;\n                    }\n                }\n            }\n            match_results->at(x).at(y).contains_match = match;\n            match_results->at(x).at(y).preliminary_match = false;\n        }\n\n        \/\/=======================================================================================\n\n        bool world_tile_match(embark_assist::defs::world_tile_data *survey_results,\n            uint16_t x,\n            uint16_t y,\n            embark_assist::defs::finders *finder) {\n\n            bool trace = false;\n            color_ostream_proxy out(Core::getInstance().getConsole());\n            df::world_data *world_data = world->world_data;\n            embark_assist::defs::region_tile_datum *tile = &survey_results->at(x).at(y);\n            const uint16_t embark_size = finder->x_dim * finder->y_dim;\n            bool found;\n\n            if (tile->surveyed) {\n                \/\/  Savagery\n                for (uint8_t i = 0; i < 3; i++)\n                {\n                    switch (finder->savagery[i]) {\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_NA:\n                        break;  \/\/  No restriction\n\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ALL:\n                        if (tile->savagery_count[i] < embark_size) {\n                            if (trace) out.print(\"matcher::world_tile_match: Savagery All (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_PRESENT:\n                        if (tile->savagery_count[i] == 0) {\n                            if (trace) out.print(\"matcher::world_tile_match: Savagery Present (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ABSENT:\n                        if (tile->savagery_count[i] > 256 - embark_size) {\n                            if (trace) out.print(\"matcher::world_tile_match: Savagery Absent (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n                    }\n                }\n\n                \/\/ Evilness\n                for (uint8_t i = 0; i < 3; i++)\n                {\n                    switch (finder->evilness[i]) {\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_NA:\n                        break;  \/\/  No restriction\n\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ALL:\n                        if (tile->evilness_count[i] < embark_size) {\n                            if (trace) out.print(\"matcher::world_tile_match: Evil All (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_PRESENT:\n                        if (tile->evilness_count[i] == 0) {\n                            if (trace) out.print(\"matcher::world_tile_match: Evil Present (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ABSENT:\n                        if (tile->evilness_count[i] > 256 - embark_size) {\n                            if (trace) out.print(\"matcher::world_tile_match: Evil Absent (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n                    }\n                }\n\n                \/\/ Aquifer\n                switch (finder->aquifer) {\n                case embark_assist::defs::aquifer_ranges::AQUIFER_NA:\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_NONE:\n                    if (!(static_cast<int8_t>(tile->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE))) {\n                        if (trace) out.print(\"matcher::world_tile_match: Aquifer None (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_AT_MOST_LIGHT:\n                    if (tile->aquifer == embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_HEAVY) {\n                        if (trace) out.print(\"matcher::world_tile_match: Aquifer Heavy (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_PLUS_LIGHT:\n                    if (!(static_cast<int8_t>(tile->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE)) ||\n                        !(static_cast<int8_t>(tile->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_LIGHT))) {\n                        if (trace) out.print(\"matcher::world_tile_match: Aquifer None_Plus_Light (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_PLUS_AT_LEAST_LIGHT:\n                    if (!(static_cast<int8_t>(tile->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE)) ||\n                        !(static_cast<int8_t>(tile->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_LIGHT_HEAVY))) {\n                        if (trace) out.print(\"matcher::world_tile_match: Aquifer None_Plus_At_Least_Light (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_LIGHT:\n                    if (!(static_cast<int8_t>(tile->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_LIGHT))) {\n                        if (trace) out.print(\"matcher::world_tile_match: Aquifer Light (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_AT_LEAST_LIGHT:\n                    if (tile->aquifer == embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE) {\n                        if (trace) out.print(\"matcher::world_tile_match: Aquifer At_Least_Light (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_PLUS_HEAVY:\n                    if (!(static_cast<int8_t>(tile->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE)) ||\n                        !(static_cast<int8_t>(tile->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_HEAVY))) {\n                        if (trace) out.print(\"matcher::world_tile_match: Aquifer None_Plus_Heavy (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_AT_MOST_LIGHT_PLUS_HEAVY:\n                    if (!(static_cast<int8_t>(tile->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_HEAVY)) ||\n                        !(static_cast<int8_t>(tile->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE_LIGHT))) {\n                        if (trace) out.print(\"matcher::world_tile_match: Aquifer At_Most_Light_Plus_Heavy (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_LIGHT_PLUS_HEAVY:\n                    if (!(static_cast<int8_t>(tile->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_LIGHT)) ||\n                        !(static_cast<int8_t>(tile->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_HEAVY))) {\n                        if (trace) out.print(\"matcher::world_tile_match: Aquifer Light_Plus_Heavy (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_NONE_LIGHT_HEAVY:\n                    if (tile->aquifer != embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_NONE_LIGHT_HEAVY) {\n                        if (trace) out.print(\"matcher::world_tile_match: Aquifer None_Light_Heavy (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::aquifer_ranges::AQUIFER_HEAVY:\n                    if (!(static_cast<int8_t>(tile->aquifer) & static_cast<int8_t>(embark_assist::defs::aquifer_sizes::AQUIFER_SIZE_HEAVY))) {\n                        if (trace) out.print(\"matcher::world_tile_match: Aquifer Heavy (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/ River size. Every tile has riverless tiles, so max rivers has to be checked on the detailed level.\n                switch (tile->river_size) {\n                case embark_assist::defs::river_sizes::RIVER_SIZE_NONE:\n                    if (finder->min_river > embark_assist::defs::river_ranges::RIVER_NONE) {\n                        if (trace) out.print(\"matcher::world_tile_match: River_Size None (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::river_sizes::RIVER_SIZE_BROOK:\n                    if (finder->min_river > embark_assist::defs::river_ranges::RIVER_BROOK) {\n                        if (trace) out.print(\"matcher::world_tile_match: River_Size Brook (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::river_sizes::RIVER_SIZE_STREAM:\n                    if (finder->min_river > embark_assist::defs::river_ranges::RIVER_STREAM) {\n                        if (trace) out.print(\"matcher::world_tile_match: River_Size Stream (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::river_sizes::RIVER_SIZE_MINOR:\n                    if (finder->min_river > embark_assist::defs::river_ranges::RIVER_MINOR) {\n                        if (trace) out.print(\"matcher::world_tile_match: River_Size Mino (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::river_sizes::RIVER_SIZE_MEDIUM:\n                    if (finder->min_river > embark_assist::defs::river_ranges::RIVER_MEDIUM) {\n                        if (trace) out.print(\"matcher::world_tile_match: River_Size Medium (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::river_sizes::RIVER_SIZE_MAJOR:\n                    if (finder->max_river != embark_assist::defs::river_ranges::RIVER_NA) {\n                        if (trace) out.print(\"matcher::world_tile_match: River_Size Major (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Waterfall\n                if (finder->min_waterfall > tile->max_waterfall) {  \/\/  N\/A = -1 is always smaller\n                    if (trace) out.print(\"matcher::world_tile_match: Waterfall (%i, %i)\\n\", x, y);\n                    return false;\n                }\n                if (finder->min_waterfall == 0 &&  \/\/ Absent\n                    embark_size == 256 &&\n                    tile->max_waterfall > 0) {\n                    if (trace) out.print(\"matcher::world_tile_match: Waterfall 2 (%i, %i)\\n\", x, y);\n                    return false;\n                }\n\n                \/\/  Flat. No world tile checks. Need to look at the details\n\n                \/\/  Clay\n                switch (finder->clay) {\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT:\n                    if (tile->clay_count == 0) {\n                        if (trace) out.print(\"matcher::world_tile_match: Clay Present (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT:\n                    if (tile->clay_count > 256 - embark_size) {\n                        if (trace) out.print(\"matcher::world_tile_match: Clay Absent (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Sand\n                switch (finder->sand) {\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT:\n                    if (tile->sand_count == 0) {\n                        if (trace) out.print(\"matcher::world_tile_match: Sand Present (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT:\n                    if (tile->sand_count > 256 - embark_size) {\n                        if (trace) out.print(\"matcher::world_tile_match: Sand Absent (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Flux\n                switch (finder->flux) {\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT:\n                    if (tile->flux_count == 0) {\n                        if (trace) out.print(\"matcher::world_tile_match: Flux Present (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT:\n                    if (tile->flux_count > 256 - embark_size) {\n                        if (trace) out.print(\"matcher::world_tile_match: Flux Absent (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Coal\n                switch (finder->coal) {\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT:\n                    if (tile->coal_count == 0) {\n                        if (trace) out.print(\"matcher::world_tile_match: Coal Present (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT:\n                    if (tile->coal_count > 256 - embark_size) {\n                        if (trace) out.print(\"matcher::world_tile_match: Coal Absent (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Soil Min\n                switch (finder->soil_min) {\n                case embark_assist::defs::soil_ranges::SOIL_NA:\n                case embark_assist::defs::soil_ranges::SOIL_NONE:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::soil_ranges::SOIL_VERY_SHALLOW:\n                    if (tile->max_region_soil < 1) {\n                        if (trace) out.print(\"matcher::world_tile_match: Soil Min Very Shallow (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::soil_ranges::SOIL_SHALLOW:\n                    if (tile->max_region_soil < 2) {\n                        if (trace) out.print(\"matcher::world_tile_match: Soil Min Shallow (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::soil_ranges::SOIL_DEEP:\n                    if (tile->max_region_soil < 3) {\n                        if (trace) out.print(\"matcher::world_tile_match: Soil Min Deep (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::soil_ranges::SOIL_VERY_DEEP:\n                    if (tile->max_region_soil < 4) {\n                        if (trace) out.print(\"matcher::world_tile_match: Soil Min Very Deep (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  soil_min_everywhere only applies on the detailed level\n\n                \/\/  Soil Max\n                switch (finder->soil_max) {\n                case embark_assist::defs::soil_ranges::SOIL_NA:\n                case embark_assist::defs::soil_ranges::SOIL_VERY_DEEP:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::soil_ranges::SOIL_NONE:\n                    if (tile->min_region_soil > 0) {\n                        if (trace) out.print(\"matcher::world_tile_match: Soil_Max None (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::soil_ranges::SOIL_VERY_SHALLOW:\n                    if (tile->min_region_soil > 1) {\n                        if (trace) out.print(\"matcher::world_tile_match: Soil_Max Very_Shallow (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::soil_ranges::SOIL_SHALLOW:\n                    if (tile->min_region_soil > 2) {\n                        if (trace) out.print(\"matcher::world_tile_match: Soil_Max Shallow (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::soil_ranges::SOIL_DEEP:\n                    if (tile->min_region_soil > 3) {\n                        if (trace) out.print(\"matcher::world_tile_match: Soil_Max Deep (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Freezing\n                if (finder->freezing != embark_assist::defs::freezing_ranges::FREEZING_NA)\n                {\n                    int16_t max_max_temperature = tile->max_temperature[5];\n                    int16_t min_max_temperature = tile->max_temperature[5];\n                    int16_t max_min_temperature = tile->min_temperature[5];\n                    int16_t min_min_temperature = tile->min_temperature[5];\n\n                    for (uint8_t i = 1; i < 10; i++) {\n                        if (tile->max_temperature[i] > max_max_temperature) {\n                            max_max_temperature = tile->max_temperature[i];\n                        }\n\n                        if (tile->max_temperature[i] != - 30000 &&\n                            tile->max_temperature[i] < min_max_temperature) {\n                            min_max_temperature = tile->max_temperature[i];\n                        }\n\n                        if (tile->min_temperature[i] != -30000 &&\n                            tile->min_temperature[i] < min_min_temperature) {\n                            min_min_temperature = tile->min_temperature[i];\n                        }\n\n                        if (tile->min_temperature[i] > max_min_temperature) {\n                            max_min_temperature = tile->min_temperature[i];\n                        }\n                    }\n\n                    switch (finder->freezing) {\n                    case embark_assist::defs::freezing_ranges::FREEZING_NA:\n                        break;  \/\/  Excluded above, but the Travis complains if it's not here.\n\n                    case embark_assist::defs::freezing_ranges::FREEZING_PERMANENT:\n                        if (min_max_temperature > 0) {\n                            if (trace) out.print(\"matcher::world_tile_match: Freezing Permanent (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n\n                    case embark_assist::defs::freezing_ranges::FREEZING_AT_LEAST_PARTIAL:\n                        if (min_min_temperature > 0) {\n                            if (trace) out.print(\"matcher::world_tile_match: Freezing At_Lest_Partial (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n\n                    case embark_assist::defs::freezing_ranges::FREEZING_PARTIAL:\n                        if (min_min_temperature > 0 ||\n                            max_max_temperature <= 0) {\n                            if (trace) out.print(\"matcher::world_tile_match: Freezing Partial (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n\n                    case embark_assist::defs::freezing_ranges::FREEZING_AT_MOST_PARTIAL:\n                        if (max_max_temperature <= 0) {\n                            if (trace) out.print(\"matcher::world_tile_match: Freezing At Most_Partial (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n\n                    case embark_assist::defs::freezing_ranges::FREEZING_NEVER:\n                        if (max_min_temperature <= 0) {\n                            if (trace) out.print(\"matcher::world_tile_match: Freezing Never (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n                    }\n                }\n\n                \/\/  Trees\n                switch (finder->min_trees) {\n                case embark_assist::defs::tree_ranges::TREE_NA:\n                case embark_assist::defs::tree_ranges::TREE_NONE:\n                    break;\n \n                case embark_assist::defs::tree_ranges::TREE_VERY_SCARCE:\n                    if (tile->max_tree_level < embark_assist::defs::tree_levels::TREE_LEVEL_VERY_SCARCE) {\n                        if (trace) out.print(\"matcher::world_tile_match: Min_Trees Very_Scarce (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::tree_ranges::TREE_SCARCE:\n                    if (tile->max_tree_level < embark_assist::defs::tree_levels::TREE_LEVEL_SCARCE) {\n                        if (trace) out.print(\"matcher::world_tile_match: Min_Trees Scarce (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::tree_ranges::TREE_WOODLAND:\n                    if (tile->max_tree_level < embark_assist::defs::tree_levels::TREE_LEVEL_WOODLAND) {\n                        if (trace) out.print(\"matcher::world_tile_match: Min_Trees Woodland (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::tree_ranges::TREE_HEAVILY_FORESTED:\n                    if (tile->max_tree_level < embark_assist::defs::tree_levels::TREE_LEVEL_HEAVILY_FORESTED) {\n                        if (trace) out.print(\"matcher::world_tile_match: Min_Trees Heavily_Forested (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                switch (finder->max_trees) {\n                case embark_assist::defs::tree_ranges::TREE_NA:\n                case embark_assist::defs::tree_ranges::TREE_HEAVILY_FORESTED:\n                    break;\n\n                case embark_assist::defs::tree_ranges::TREE_NONE:\n                    if (tile->min_tree_level > embark_assist::defs::tree_levels::TREE_LEVEL_NONE) {\n                        if (trace) out.print(\"matcher::world_tile_match: Max_Trees None (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n\n                case embark_assist::defs::tree_ranges::TREE_VERY_SCARCE:\n                    if (tile->min_tree_level > embark_assist::defs::tree_levels::TREE_LEVEL_VERY_SCARCE) {\n                        if (trace) out.print(\"matcher::world_tile_match: Max_Trees Very_Scarce (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::tree_ranges::TREE_SCARCE:\n                    if (tile->min_tree_level > embark_assist::defs::tree_levels::TREE_LEVEL_SCARCE) {\n                        if (trace) out.print(\"matcher::world_tile_match: Max_Trees Scarce (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::tree_ranges::TREE_WOODLAND:\n                    if (tile->min_tree_level > embark_assist::defs::tree_levels::TREE_LEVEL_WOODLAND) {\n                        if (trace) out.print(\"matcher::world_tile_match: Max_Trees Woodland (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Blood Rain\n                switch (finder->blood_rain) {\n                case embark_assist::defs::yes_no_ranges::YES_NO_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::yes_no_ranges::YES_NO_YES:\n                    if (!tile->blood_rain_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: Blood_Rain Yes (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::yes_no_ranges::YES_NO_NO:\n                    if (tile->blood_rain_full) {\n                        if (trace) out.print(\"matcher::world_tile_match: Blood_Rain No (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Syndrome Rain\n                switch (finder->syndrome_rain) {\n                case embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_ANY:\n                    if (!tile->permanent_syndrome_rain_possible && !tile->temporary_syndrome_rain_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: Syndrome_Rain Any (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_PERMANENT:\n                    if (!tile->permanent_syndrome_rain_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: Syndrome_Rain Permanent (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_TEMPORARY:\n                    if (!tile->temporary_syndrome_rain_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: Syndrome_Rain Temporary (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_NOT_PERMANENT:\n                    if (tile->permanent_syndrome_rain_full) {\n                        if (trace) out.print(\"matcher::world_tile_match: Syndrome_Rain Not_Permanent (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_NONE:\n                    if (tile->permanent_syndrome_rain_full || tile->temporary_syndrome_rain_full) {\n                        if (trace) out.print(\"matcher::world_tile_match: Syndrome_Rain None (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Reanimating\n                switch (finder->reanimation) {\n                case embark_assist::defs::reanimation_ranges::REANIMATION_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::reanimation_ranges::REANIMATION_BOTH:\n                    if (!tile->reanimating_possible || !tile->thralling_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: Reanimation Both (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::reanimation_ranges::REANIMATION_ANY:\n                    if (!tile->reanimating_possible && !tile->thralling_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: Reanimation Any (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::reanimation_ranges::REANIMATION_THRALLING:\n                    if (!tile->thralling_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: Reanimation Thralling (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::reanimation_ranges::REANIMATION_REANIMATION:\n                    if (!tile->reanimating_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: Reanimation Reanimation (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::reanimation_ranges::REANIMATION_NOT_THRALLING:\n                    if (tile->thralling_full) {\n                        if (trace) out.print(\"matcher::world_tile_match: Reanimation Not_Thralling (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::reanimation_ranges::REANIMATION_NONE:\n                    if (tile->reanimating_full || tile->thralling_full) {\n                        if (trace) out.print(\"matcher::world_tile_match: Reanimation None (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Spire Count Min\/Max\n                \/\/  Magma Min\/Max\n                \/\/  Biome Count Min (Can't do anything with Max at this level)\n                if (finder->biome_count_min > tile->biome_count) return false;\n\n                \/\/  Region Type 1\n                if (finder->region_type_1 != -1) {\n                    found = false;\n\n                    for (uint8_t k = 1; k < 10; k++) {\n                        if (tile->biome_index[k] != -1) {\n                            if (world_data->regions[tile->biome_index[k]]->type == finder->region_type_1) {\n                                found = true;\n                                break;\n                            }\n                        }\n\n                        if (found) break;\n                    }\n\n                    if (!found) {\n                        if (trace) out.print(\"matcher::world_tile_match: Region_Type_1 (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                \/\/  Region Type 2\n                if (finder->region_type_2 != -1) {\n                    found = false;\n\n                    for (uint8_t k = 1; k < 10; k++) {\n                        if (tile->biome_index[k] != -1) {\n                            if (world_data->regions[tile->biome_index[k]]->type == finder->region_type_2) {\n                                found = true;\n                                break;\n                            }\n                        }\n\n                        if (found) break;\n                    }\n\n                    if (!found) {\n                        if (trace) out.print(\"matcher::world_tile_match: Region_Type_2 (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                \/\/  Region Type 3\n                if (finder->region_type_3 != -1) {\n                    found = false;\n\n                    for (uint8_t k = 1; k < 10; k++) {\n                        if (tile->biome_index[k] != -1) {\n                            if (world_data->regions[tile->biome_index[k]]->type == finder->region_type_3) {\n                                found = true;\n                                break;\n                            }\n                        }\n\n                        if (found) break;\n                    }\n\n                    if (!found) {\n                        if (trace) out.print(\"matcher::world_tile_match: Region_Type_3 (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                \/\/  Biome 1\n                if (finder->biome_1 != -1) {\n                    found = false;\n\n                    for (uint8_t i = 1; i < 10; i++) {\n                        if (tile->biome[i] == finder->biome_1) {\n                            found = true;\n                            break;\n                        }\n                    }\n\n                    if (!found) {\n                        if (trace) out.print(\"matcher::world_tile_match: Biome_1 (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                \/\/  Biome 2\n                if (finder->biome_2 != -1) {\n                    found = false;\n\n                    for (uint8_t i = 1; i < 10; i++) {\n                        if (tile->biome[i] == finder->biome_2) {\n                            found = true;\n                            break;\n                        }\n                    }\n\n                    if (!found) {\n                        if (trace) out.print(\"matcher::world_tile_match: Biome_2 (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                \/\/  Biome 3\n                if (finder->biome_3 != -1) {\n                    found = false;\n\n                    for (uint8_t i = 1; i < 10; i++) {\n                        if (tile->biome[i] == finder->biome_3) {\n                            found = true;\n                            break;\n                        }\n                    }\n\n                    if (!found) {\n                        if (trace) out.print(\"matcher::world_tile_match: Biome_3 (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                if (finder->metal_1 != -1 ||\n                    finder->metal_2 != -1 ||\n                    finder->metal_3 != -1 ||\n                    finder->economic_1 != -1 ||\n                    finder->economic_2 != -1 ||\n                    finder->economic_3 != -1 ||\n                    finder->mineral_1 != -1 ||\n                    finder->mineral_2 != -1 ||\n                    finder->mineral_3 != -1) {\n                    bool metal_1 = finder->metal_1 == -1;\n                    bool metal_2 = finder->metal_2 == -1;\n                    bool metal_3 = finder->metal_3 == -1;\n                    bool economic_1 = finder->economic_1 == -1;\n                    bool economic_2 = finder->economic_2 == -1;\n                    bool economic_3 = finder->economic_3 == -1;\n                    bool mineral_1 = finder->mineral_1 == -1;\n                    bool mineral_2 = finder->mineral_2 == -1;\n                    bool mineral_3 = finder->mineral_3 == -1;\n\n                    metal_1 = metal_1 || tile->metals[finder->metal_1];\n                    metal_2 = metal_2 || tile->metals[finder->metal_2];\n                    metal_3 = metal_3 || tile->metals[finder->metal_3];\n                    economic_1 = economic_1 || tile->economics[finder->economic_1];\n                    economic_2 = economic_2 || tile->economics[finder->economic_2];\n                    economic_3 = economic_3 || tile->economics[finder->economic_3];\n                    mineral_1 = mineral_1 || tile->minerals[finder->mineral_1];\n                    mineral_2 = mineral_2 || tile->minerals[finder->mineral_2];\n                    mineral_3 = mineral_3 || tile->minerals[finder->mineral_3];\n\n                    if (!metal_1 ||\n                        !metal_2 ||\n                        !metal_3 ||\n                        !economic_1 ||\n                        !economic_2 ||\n                        !economic_3 ||\n                        !mineral_1 ||\n                        !mineral_2 ||\n                        !mineral_3) {\n                        if (trace) out.print(\"matcher::world_tile_match: Metal\/Economic\/Mineral (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                \/\/  Necro Neighbors\n                if (finder->min_necro_neighbors > tile->necro_neighbors) {\n                    if (trace) out.print(\"matcher::world_tile_match: Necro_Neighbors 1 (%i, %i)\\n\", x, y);\n                    return false;\n                }\n                if (finder->max_necro_neighbors < tile->necro_neighbors &&\n                    finder->max_necro_neighbors != -1) {\n                    if (trace) out.print(\"matcher::world_tile_match: Necro_Neighbors 2 (%i, %i)\\n\", x, y);\n                    return false;\n                }\n\n                \/\/  Civ Neighbors\n                if (finder->min_civ_neighbors > (int16_t)tile->neighbors.size()) {\n                    if (trace) out.print(\"matcher::world_tile_match: Civ_Neighbors 1 (%i, %i), %i, %i\\n\", x, y, finder->min_civ_neighbors, (int)tile->neighbors.size());\n                    return false;\n                }\n                if (finder->max_civ_neighbors < (int8_t)tile->neighbors.size() &&\n                    finder->max_civ_neighbors != -1) {\n                    if (trace) out.print(\"matcher::world_tile_match: Civ_Neighbors 2 (%i, %i)\\n\", x, y);\n                    return false;\n                }\n\n                \/\/  Specific Neighbors\n                for (uint16_t i = 0; i < finder->neighbors.size(); i++) {\n                    switch (finder->neighbors[i].present) {\n                    case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_NA:\n                        break;\n\n                    case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT:\n                    {\n                        bool found = false;\n\n                        for (uint16_t k = 0; k < tile->neighbors.size(); k++) {\n                            if (finder->neighbors[i].entity_raw == tile->neighbors[k]) {\n                                found = true;\n                                break;\n                            }\n                        }\n\n                        if (!found) {\n                            if (trace) out.print(\"matcher::world_tile_match: Specific Neighbors Present (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n\n                        break;\n                    }\n\n                    case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT:\n                        for (uint16_t k = 0; k < tile->neighbors.size(); k++) {\n                            if (finder->neighbors[i].entity_raw == tile->neighbors[k]) {\n                                if (trace) out.print(\"matcher::world_tile_match: Specific Neighbors Absent (%i, %i)\\n\", x, y);\n                                return false;\n                            }\n                        }\n\n                        break;\n                    }\n                }\n            }\n            else {  \/\/  Not surveyed\n                    \/\/  Savagery\n                for (uint8_t i = 0; i < 3; i++)\n                {\n                    switch (finder->savagery[i]) {\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_NA:\n                        break;  \/\/  No restriction\n\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ALL:\n                        if (tile->savagery_count[i] == 0) {\n                            if (trace) out.print(\"matcher::world_tile_match: NS Savagery All (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_PRESENT:\n                        if (tile->savagery_count[i] == 0) {\n                            if (trace) out.print(\"matcher::world_tile_match: NS Savagery Present (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ABSENT:\n                        if (tile->savagery_count[i] == 256) {\n                            if (trace) out.print(\"matcher::world_tile_match: NS Savagery Absent (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n                    }\n                }\n\n                \/\/ Evilness\n                for (uint8_t i = 0; i < 3; i++)\n                {\n                    switch (finder->evilness[i]) {\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_NA:\n                        break;  \/\/  No restriction\n\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ALL:\n                        if (tile->evilness_count[i] == 0) {\n                            if (trace) out.print(\"matcher::world_tile_match: NS Evil All (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_PRESENT:\n                        if (tile->evilness_count[i] == 0) {\n                            if (trace) out.print(\"matcher::world_tile_match: NS Evil Present (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n\n                    case embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ABSENT:\n                        if (tile->evilness_count[i] == 256) {\n                            if (trace) out.print(\"matcher::world_tile_match: NS Evil Absent (%i, %i)\\n\", x, y);\n                            return false;\n                        }\n                        break;\n                    }\n                }\n\n                \/\/ Aquifer  \/\/  Requires survey\n\n                \/\/ River size\n                switch (tile->river_size) {\n                case embark_assist::defs::river_sizes::RIVER_SIZE_NONE:\n                    if (finder->min_river > embark_assist::defs::river_ranges::RIVER_NONE) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS River None (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::river_sizes::RIVER_SIZE_BROOK:\n                    if (finder->min_river > embark_assist::defs::river_ranges::RIVER_BROOK) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS River Brook (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::river_sizes::RIVER_SIZE_STREAM:\n                    if (finder->min_river > embark_assist::defs::river_ranges::RIVER_STREAM) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS River Stream (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::river_sizes::RIVER_SIZE_MINOR:\n                    if (finder->min_river > embark_assist::defs::river_ranges::RIVER_MINOR) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS River Minor (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::river_sizes::RIVER_SIZE_MEDIUM:\n                    if (finder->min_river > embark_assist::defs::river_ranges::RIVER_MEDIUM) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS River Medium (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::river_sizes::RIVER_SIZE_MAJOR:\n                    if (finder->max_river != embark_assist::defs::river_ranges::RIVER_NA) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS River Major (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Waterfall\n                if (finder->min_waterfall > 0 &&\n                    tile->river_size == embark_assist::defs::river_sizes::RIVER_SIZE_NONE) {\n                    if (trace) out.print(\"matcher::world_tile_match: NS Waterfall (%i, %i)\\n\", x, y);\n                    return false;\n                }\n\n                \/\/  Flat. No world tile checks. Need to look at the details\n\n                \/\/  Clay\n                switch (finder->clay) {\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT:\n                    if (tile->clay_count == 0) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Clay Present (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT:\n                    if (tile->clay_count == 256) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Clay Absent (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Sand\n                switch (finder->sand) {\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT:\n                    if (tile->sand_count == 0) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Sand Present (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT:\n                    if (tile->sand_count == 256) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Sand Absent (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Flux\n                switch (finder->flux) {\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT:\n                    if (tile->flux_count == 0) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Flux Present (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT:\n                    if (tile->flux_count == 256) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Flux Absent (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Coal\n                switch (finder->coal) {\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT:\n                    if (tile->coal_count == 0) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Coal Present (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT:\n                    if (tile->coal_count == 256) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Coal Absent (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Soil Min\n                switch (finder->soil_min) {\n                case embark_assist::defs::soil_ranges::SOIL_NA:\n                case embark_assist::defs::soil_ranges::SOIL_NONE:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::soil_ranges::SOIL_VERY_SHALLOW:\n                    if (tile->max_region_soil < 1) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Soil_Min Very_Shallow (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::soil_ranges::SOIL_SHALLOW:\n                    if (tile->max_region_soil < 2) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Soil_Min Shallow (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::soil_ranges::SOIL_DEEP:\n                    if (tile->max_region_soil < 3) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Soil_Min Deep (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::soil_ranges::SOIL_VERY_DEEP:\n                    if (tile->max_region_soil < 4) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Soil_Min Very_Deep (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  soil_min_everywhere only applies on the detailed level\n\n                \/\/  Soil Max\n                \/\/  Can't say anything as the preliminary data isn't reliable\n\n                \/\/  Blood Rain\n                switch (finder->blood_rain) {\n                case embark_assist::defs::yes_no_ranges::YES_NO_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::yes_no_ranges::YES_NO_YES:\n                    if (!tile->blood_rain_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Blood_Rain Yes (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::yes_no_ranges::YES_NO_NO:\n                    if (tile->blood_rain_full) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Blood_Rain No (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Trees  \/\/  Requires survey\n\n                \/\/  Syndrome Rain\n                switch (finder->syndrome_rain) {\n                case embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_ANY:\n                    if (!tile->permanent_syndrome_rain_possible && !tile->temporary_syndrome_rain_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Syndrome_Rain Any (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_PERMANENT:\n                    if (!tile->permanent_syndrome_rain_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Syndrome_Rain Permanent (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_TEMPORARY:\n                    if (!tile->temporary_syndrome_rain_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Syndrome_Rain Temporary (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_NOT_PERMANENT:\n                    if (tile->permanent_syndrome_rain_full) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Syndrome_Rain Not_Permanent (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::syndrome_rain_ranges::SYNDROME_RAIN_NONE:\n                    if (tile->permanent_syndrome_rain_full || tile->temporary_syndrome_rain_full) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Syndrome_Rain None (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Reanimating\n                switch (finder->reanimation) {\n                case embark_assist::defs::reanimation_ranges::REANIMATION_NA:\n                    break;  \/\/  No restriction\n\n                case embark_assist::defs::reanimation_ranges::REANIMATION_BOTH:\n                    if (!tile->reanimating_possible || !tile->thralling_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Reanimating Both (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::reanimation_ranges::REANIMATION_ANY:\n                    if (!tile->reanimating_possible && !tile->thralling_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Reanimating Any (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::reanimation_ranges::REANIMATION_THRALLING:\n                    if (!tile->thralling_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Reanimating Thralling (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::reanimation_ranges::REANIMATION_REANIMATION:\n                    if (!tile->reanimating_possible) {\n                        if (trace) out.print(\"matcher::world_tile_match:NS Reanimating Reanimating (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::reanimation_ranges::REANIMATION_NOT_THRALLING:\n                    if (tile->thralling_full) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Reanimating Not_Thralling (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n\n                case embark_assist::defs::reanimation_ranges::REANIMATION_NONE:\n                    if (tile->reanimating_full || tile->thralling_full) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Reanimating None (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                    break;\n                }\n\n                \/\/  Spire Count Min\/Max\n                \/\/  Magma Min\/Max\n                \/\/  Biome Count Min (Can't do anything with Max at this level)\n                if (finder->biome_count_min > tile->biome_count) {\n                    if (trace) out.print(\"matcher::world_tile_match: NS Biome_Count (%i, %i)\\n\", x, y);\n                    return false;\n                }\n\n                \/\/  Region Type 1\n                if (finder->region_type_1 != -1) {\n                    found = false;\n\n                    for (uint8_t k = 1; k < 10; k++) {\n                        if (tile->biome_index[k] != -1) {\n                            if (world_data->regions[tile->biome_index[k]]->type == finder->region_type_1) {\n                                found = true;\n                                break;\n                            }\n                        }\n\n                        if (found) break;\n                    }\n\n                    if (!found) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Region_Type_1 (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                \/\/  Region Type 2\n                if (finder->region_type_2 != -1) {\n                    found = false;\n\n                    for (uint8_t k = 1; k < 10; k++) {\n                        if (tile->biome_index[k] != -1) {\n                            if (world_data->regions[tile->biome_index[k]]->type == finder->region_type_2) {\n                                found = true;\n                                break;\n                            }\n                        }\n\n                        if (found) break;\n                    }\n\n                    if (!found) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Region_Type_2 (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                \/\/  Region Type 3\n                if (finder->region_type_3 != -1) {\n                    found = false;\n\n                    for (uint8_t k = 1; k < 10; k++) {\n                        if (tile->biome_index[k] != -1) {\n                            if (world_data->regions[tile->biome_index[k]]->type == finder->region_type_3) {\n                                found = true;\n                                break;\n                            }\n                        }\n\n                        if (found) break;\n                    }\n\n                    if (!found) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Region_Type_3 (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                \/\/  Biome 1\n                if (finder->biome_1 != -1) {\n                    found = false;\n\n                    for (uint8_t i = 1; i < 10; i++) {\n                        if (tile->biome[i] == finder->biome_1) {\n                            found = true;\n                            break;\n                        }\n                    }\n\n                    if (!found) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Biome_1 (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                \/\/  Biome 2\n                if (finder->biome_2 != -1) {\n                    found = false;\n\n                    for (uint8_t i = 1; i < 10; i++) {\n                        if (tile->biome[i] == finder->biome_2) {\n                            found = true;\n                            break;\n                        }\n                    }\n\n                    if (!found) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Biome_2 (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                \/\/  Biome 3\n                if (finder->biome_3 != -1) {\n                    found = false;\n\n                    for (uint8_t i = 1; i < 10; i++) {\n                        if (tile->biome[i] == finder->biome_3) {\n                            found = true;\n                            break;\n                        }\n                    }\n\n                    if (!found) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Biome_3 (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                if (finder->metal_1 != -1 ||\n                    finder->metal_2 != -1 ||\n                    finder->metal_3 != -1 ||\n                    finder->economic_1 != -1 ||\n                    finder->economic_2 != -1 ||\n                    finder->economic_3 != -1 ||\n                    finder->mineral_1 != -1 ||\n                    finder->mineral_2 != -1 ||\n                    finder->mineral_3 != -1) {\n                    bool metal_1 = finder->metal_1 == -1;\n                    bool metal_2 = finder->metal_2 == -1;\n                    bool metal_3 = finder->metal_3 == -1;\n                    bool economic_1 = finder->economic_1 == -1;\n                    bool economic_2 = finder->economic_2 == -1;\n                    bool economic_3 = finder->economic_3 == -1;\n                    bool mineral_1 = finder->mineral_1 == -1;\n                    bool mineral_2 = finder->mineral_2 == -1;\n                    bool mineral_3 = finder->mineral_3 == -1;\n\n                    metal_1 = metal_1 || tile->metals[finder->metal_1];\n                    metal_2 = metal_2 || tile->metals[finder->metal_2];\n                    metal_3 = metal_3 || tile->metals[finder->metal_3];\n                    economic_1 = economic_1 || tile->economics[finder->economic_1];\n                    economic_2 = economic_2 || tile->economics[finder->economic_2];\n                    economic_3 = economic_3 || tile->economics[finder->economic_3];\n                    mineral_1 = mineral_1 || tile->minerals[finder->mineral_1];\n                    mineral_2 = mineral_2 || tile->minerals[finder->mineral_2];\n                    mineral_3 = mineral_3 || tile->minerals[finder->mineral_3];\n\n                    if (!metal_1 ||\n                        !metal_2 ||\n                        !metal_3 ||\n                        !economic_1 ||\n                        !economic_2 ||\n                        !economic_3 ||\n                        !mineral_1 ||\n                        !mineral_2 ||\n                        !mineral_3) {\n                        if (trace) out.print(\"matcher::world_tile_match: NS Metal\/Economic\/Mineral (%i, %i)\\n\", x, y);\n                        return false;\n                    }\n                }\n\n                \/\/  Necro Neighbors  \/\/  Can't evaluate these without having collected the info.\n                \/\/  Civ Neighbors\n                \/\/  Specific Neighbors\n            }\n            return true;\n        }\n\n        \/\/=======================================================================================\n\n        uint32_t preliminary_world_match(embark_assist::defs::world_tile_data *survey_results,\n            embark_assist::defs::finders *finder,\n            embark_assist::defs::match_results *match_results) {\n\/\/                        color_ostream_proxy out(Core::getInstance().getConsole());\n            uint32_t count = 0;\n            for (uint16_t i = 0; i < world->worldgen.worldgen_parms.dim_x; i++) {\n                for (uint16_t k = 0; k < world->worldgen.worldgen_parms.dim_y; k++) {\n                    match_results->at(i).at(k).preliminary_match =\n                        world_tile_match(survey_results, i, k, finder);\n                    if (match_results->at(i).at(k).preliminary_match) count++;\n                    match_results->at(i).at(k).contains_match = false;\n                }\n            }\n\n            return count;\n        }\n\n        \/\/=======================================================================================\n\n        void match_world_tile(embark_assist::defs::geo_data *geo_summary,\n            embark_assist::defs::world_tile_data *survey_results,\n            embark_assist::defs::finders *finder,\n            embark_assist::defs::match_results *match_results,\n            uint16_t x,\n            uint16_t y) {\n\n\/\/            color_ostream_proxy out(Core::getInstance().getConsole());\n            embark_assist::defs::mid_level_tiles mlt;\n\n            embark_assist::survey::survey_mid_level_tile(geo_summary,\n                survey_results,\n                &mlt);\n\n            mid_level_tile_match(survey_results,\n                &mlt,\n                x,\n                y,\n                finder,\n                match_results);\n        }\n    }\n}\n\n\/\/=======================================================================================\n\/\/  Visible operations\n\/\/=======================================================================================\n\nvoid embark_assist::matcher::move_cursor(uint16_t x, uint16_t y) {\n    \/\/            color_ostream_proxy out(Core::getInstance().getConsole());\n    df::viewscreen_choose_start_sitest* screen = Gui::getViewscreenByType<df::viewscreen_choose_start_sitest>(0);\n    uint16_t original_x = screen->location.region_pos.x;\n    uint16_t original_y = screen->location.region_pos.y;\n\n    uint16_t large_x = std::abs(original_x - x) \/ 10;\n    uint16_t small_x = std::abs(original_x - x) % 10;\n    uint16_t large_y = std::abs(original_y - y) \/ 10;\n    uint16_t small_y = std::abs(original_y - y) % 10;\n\n    while (large_x > 0 || large_y > 0) {\n        if (large_x > 0 && large_y > 0) {\n            if (original_x - x > 0 && original_y - y > 0) {\n                screen->feed_key(df::interface_key::CURSOR_UPLEFT_FAST);\n            }\n            else if (original_x - x > 0 && original_y - y < 0) {\n                screen->feed_key(df::interface_key::CURSOR_DOWNLEFT_FAST);\n            }\n            else if (original_y - y > 0) {\n                screen->feed_key(df::interface_key::CURSOR_UPRIGHT_FAST);\n            }\n            else {\n                screen->feed_key(df::interface_key::CURSOR_DOWNRIGHT_FAST);\n            }\n            large_x--;\n            large_y--;\n        }\n        else if (large_x > 0) {\n            if (original_x - x > 0) {\n                screen->feed_key(df::interface_key::CURSOR_LEFT_FAST);\n            }\n            else {\n                screen->feed_key(df::interface_key::CURSOR_RIGHT_FAST);\n            }\n            large_x--;\n        }\n        else {\n            if (original_y - y > 0) {\n                screen->feed_key(df::interface_key::CURSOR_UP_FAST);\n            }\n            else {\n                screen->feed_key(df::interface_key::CURSOR_DOWN_FAST);\n            }\n            large_y--;\n        }\n    }\n\n    while (small_x > 0 || small_y > 0) {\n        if (small_x > 0 && small_y > 0) {\n            if (original_x - x > 0 && original_y - y > 0) {\n                screen->feed_key(df::interface_key::CURSOR_UPLEFT);\n            }\n            else if (original_x - x > 0 && original_y - y < 0) {\n                screen->feed_key(df::interface_key::CURSOR_DOWNLEFT);\n            }\n            else if (original_y - y > 0) {\n                screen->feed_key(df::interface_key::CURSOR_UPRIGHT);\n            }\n            else {\n                screen->feed_key(df::interface_key::CURSOR_DOWNRIGHT);\n            }\n            small_x--;\n            small_y--;\n        }\n        else if (small_x > 0) {\n            if (original_x - x > 0) {\n                screen->feed_key(df::interface_key::CURSOR_LEFT);\n            }\n            else {\n                screen->feed_key(df::interface_key::CURSOR_RIGHT);\n            }\n            small_x--;\n        }\n        else {\n            if (original_y - y > 0) {\n                screen->feed_key(df::interface_key::CURSOR_UP);\n            }\n            else {\n                screen->feed_key(df::interface_key::CURSOR_DOWN);\n            }\n            small_y--;\n        }\n    }\n}\n\n\/\/=======================================================================================\n\nuint16_t embark_assist::matcher::find(embark_assist::defs::match_iterators *iterator,\n    embark_assist::defs::geo_data *geo_summary,\n    embark_assist::defs::world_tile_data *survey_results,\n    embark_assist::defs::match_results *match_results) {\n\n    color_ostream_proxy out(Core::getInstance().getConsole());\n    df::viewscreen_choose_start_sitest* screen = Gui::getViewscreenByType<df::viewscreen_choose_start_sitest>(0);\n    uint16_t x_end;\n    uint16_t y_end;\n    bool turn = false;\n    uint16_t count;\n    uint16_t preliminary_matches;\n\n    if (!iterator->active) {\n        embark_assist::survey::clear_results(match_results);\n\n        \/\/  Static check for impossible requirements\n        \/\/\n        count = 0;\n        for (uint8_t i = 0; i < 3; i++) {\n            if (iterator->finder.evilness[i] == embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ALL) {\n                count++;\n            }\n        }\n\n        if (count > 1) {\n            out.printerr(\"matcher::find: Will never find any due to multiple All evilness requirements\\n\");\n            return 0;\n        }\n\n        count = 0;\n        for (uint8_t i = 0; i < 3; i++) {\n            if (iterator->finder.savagery[i] == embark_assist::defs::evil_savagery_values::EVIL_SAVAGERY_ALL) {\n                count++;\n            }\n        }\n\n        if (count > 1) {\n            out.printerr(\"matcher::find: Will never find any due to multiple All savagery requirements\\n\");\n            return 0;\n        }\n\n        if (iterator->finder.max_river < iterator->finder.min_river &&\n            iterator->finder.max_river != embark_assist::defs::river_ranges::RIVER_NA) {\n            out.printerr(\"matcher::find: Will never find any due to max river < min river\\n\");\n            return 0;\n        }\n\n        if (iterator->finder.min_waterfall > 0 &&\n            iterator->finder.max_river == embark_assist::defs::river_ranges::RIVER_NONE) {\n            out.printerr(\"matcher::find: Will never find any waterfalls with None as max river\\n\");\n            return 0;\n        }\n\n        if (iterator->finder.soil_max < iterator->finder.soil_min &&\n            iterator->finder.soil_max != embark_assist::defs::soil_ranges::SOIL_NA) {\n            out.printerr(\"matcher::find: Will never find any matches with max soil < min soil\\n\");\n            return 0;\n        }\n\n        if (iterator->finder.spire_count_max < iterator->finder.spire_count_min &&\n            iterator->finder.spire_count_max != -1) {\n            out.printerr(\"matcher::find: Will never find any matches with max spires < min spires\\n\");\n            return 0;\n        }\n\n        if (iterator->finder.magma_max < iterator->finder.magma_min &&\n            iterator->finder.magma_max != embark_assist::defs::magma_ranges::MAGMA_NA) {\n            out.printerr(\"matcher::find: Will never find any matches with max magma < min magma\\n\");\n            return 0;\n        }\n\n        if (iterator->finder.biome_count_max < iterator->finder.biome_count_min &&\n            iterator->finder.biome_count_max != -1) {\n            out.printerr(\"matcher::find: Will never find any matches with max biomes < min biomes\\n\");\n            return 0;\n        }\n\n        if (iterator->finder.min_trees > iterator->finder.max_trees &&\n            iterator->finder.max_trees != embark_assist::defs::tree_ranges::TREE_NA) {\n            out.printerr(\"matcher::find: Will never find any matches with max trees < min trees\\n\");\n            return 0;\n        }\n\n        if (iterator->finder.min_necro_neighbors > iterator->finder.max_necro_neighbors &&\n            iterator->finder.max_necro_neighbors != -1) {\n            out.printerr(\"matcher::find: Will never find any matches with max necro neighbors < min necro neighbors\\n\");\n            return 0;\n        }\n\n        if (iterator->finder.min_civ_neighbors > iterator->finder.max_civ_neighbors &&\n            iterator->finder.max_civ_neighbors != -1) {\n            out.printerr(\"matcher::find: Will never find any matches with max civ neighbors < min civ neighbors\\n\");\n            return 0;\n        }\n\n        if (iterator->finder.min_civ_neighbors != -1 ||\n            iterator->finder.max_civ_neighbors != -1) {\n            int16_t present_count = 0;\n            int16_t absent_count = 0;\n\n            for (size_t i = 0; i < iterator->finder.neighbors.size(); i++) {\n                switch (iterator->finder.neighbors[i].present) {\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_NA:\n                    break;\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_PRESENT:\n                    present_count++;\n                    break;\n\n                case embark_assist::defs::present_absent_ranges::PRESENT_ABSENT_ABSENT:\n                    absent_count++;\n                    break;\n                }\n            }\n\n            if (iterator->finder.max_civ_neighbors != -1 && present_count > iterator->finder.max_civ_neighbors) {\n                out.printerr(\"matcher::find: Will never find any matches with specified neighbors > max civ neighbors\\n\");\n                return 0;\n            }\n\n            if (iterator->finder.min_civ_neighbors != -1 && (int8_t)iterator->finder.neighbors.size() - absent_count < iterator->finder.min_civ_neighbors) {\n                out.printerr(\"matcher::find: Will never find any matches with total possible neighbors - excluded neighbors < min civ neighbors\\n\");\n                return 0;\n            }\n        }\n\n        preliminary_matches = preliminary_world_match(survey_results, &iterator->finder, match_results);\n\n        if (preliminary_matches == 0) {\n            out.printerr(\"matcher::find: Preliminarily matching World Tiles: %i\\n\", preliminary_matches);\n            return 0;\n        }\n        else {\n            out.print(\"matcher::find: Preliminarily matching World Tiles: %i\\n\", preliminary_matches);\n        }\n\n        while (screen->location.region_pos.x != 0 || screen->location.region_pos.y != 0) {\n            screen->feed_key(df::interface_key::CURSOR_UPLEFT_FAST);\n        }\n        iterator->target_location_x = 0;\n        iterator->target_location_y = 0;\n        iterator->active = true;\n        iterator->i = 0;\n        iterator->k = 0;\n        iterator->x_right = true;\n        iterator->y_down = true;\n        iterator->inhibit_x_turn = false;\n        iterator->inhibit_y_turn = false;\n        iterator->count = 0;\n    }\n\n    if ((iterator->k == world->worldgen.worldgen_parms.dim_x \/ 16 && iterator->x_right) ||\n        (iterator->k == 0 && !iterator->x_right)) {\n        x_end = 0;\n    }\n    else {\n        x_end = 15;\n    }\n\n    if (iterator->i == world->worldgen.worldgen_parms.dim_y \/ 16) {\n        y_end = 0;\n    }\n    else {\n        y_end = 15;\n    }\n\n    for (uint16_t l = 0; l <= x_end; l++) {\n        for (uint16_t m = 0; m <= y_end; m++) {\n            \/\/  This is where the payload goes\n            if (!survey_results->at(iterator->target_location_x).at(iterator->target_location_y).surveyed ||\n                match_results->at(iterator->target_location_x).at(iterator->target_location_y).preliminary_match) {\n                move_cursor(iterator->target_location_x, iterator->target_location_y);\n\n                match_world_tile(geo_summary,\n                    survey_results,\n                    &iterator->finder,\n                    match_results,\n                    iterator->target_location_x,\n                    iterator->target_location_y);\n                if (match_results->at(iterator->target_location_x).at(iterator->target_location_y).contains_match) {\n                    iterator->count++;\n                }\n            }\n            else {\n                for (uint16_t n = 0; n < 16; n++) {\n                    for (uint16_t p = 0; p < 16; p++) {\n                        match_results->at(iterator->target_location_x).at(iterator->target_location_y).mlt_match[n][p] = false;\n                    }\n                }\n            }\n            \/\/  End of payload section\n\n            if (m != y_end) {\n                if (iterator->y_down) {\n                    if (iterator->target_location_y < world->worldgen.worldgen_parms.dim_y - 1) iterator->target_location_y++;\n                }\n                else {\n                    if (iterator->target_location_y > 0) iterator->target_location_y--;\n                }\n            }\n            else {\n                if (iterator->target_location_x != 0 &&\n                    iterator->target_location_x != world->worldgen.worldgen_parms.dim_x - 1) {\n                    turn = true;\n                }\n                else {\n                    iterator->inhibit_y_turn = !iterator->inhibit_y_turn;\n                    turn = iterator->inhibit_y_turn;\n                }\n\n                if (turn) {\n                    iterator->y_down = !iterator->y_down;\n                }\n                else {\n                    if (iterator->y_down) {\n                        if (iterator->target_location_y < world->worldgen.worldgen_parms.dim_y - 1) iterator->target_location_y++;\n                    }\n                    else {\n                        if (iterator->target_location_y > 0) iterator->target_location_y--;\n                    }\n                }\n            }\n        }\n\n        if (iterator->x_right) {  \/\/  Won't do anything at the edge, so we don't bother filter those cases.\n            if (iterator->target_location_x < world->worldgen.worldgen_parms.dim_x - 1) iterator->target_location_x++;\n        }\n        else {\n            if (iterator->target_location_x > 0) iterator->target_location_x--;\n        }\n\n        if (!iterator->x_right &&\n            iterator->target_location_x == 0) {\n            turn = !turn;\n\n            if (turn) {\n                iterator->x_right = true;\n            }\n        }\n        else if (iterator->x_right &&\n            iterator->target_location_x == world->worldgen.worldgen_parms.dim_x - 1) {\n            turn = !turn;\n\n            if (turn) {\n                iterator->x_right = false;\n            }\n        }\n    }\n    \/\/        }\n\n    iterator->k++;\n    if (iterator->k > world->worldgen.worldgen_parms.dim_x \/ 16)\n    {\n        iterator->k = 0;\n        iterator->i++;\n        iterator->active = !(iterator->i > world->worldgen.worldgen_parms.dim_y \/ 16);\n\n        if (!iterator->active) {\n            embark_assist::matcher::move_cursor(iterator->x, iterator->y);\n        }\n    }\n\n    return iterator->count;\n}\n","avg_line_length":45.2896935933,"max_line_length":198,"alphanum_fraction":0.4668867157,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4945,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":39.0,"content":"#include \"DX9RenderVertexAttribute.h\"\n\n#include \"Kernel\/Logger.h\"\n#include \"Kernel\/ConstStringHelper.h\"\n#include \"Kernel\/Assertion.h\"\n\n#include \"DX9RenderEnum.h\"\n#include \"DX9RenderErrorHelper.h\"\n\nnamespace Mengine\n{\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    DX9RenderVertexAttribute::DX9RenderVertexAttribute()\n        : m_elementSize( 0 )\n        , m_compileReferenceCount( 0 )\n        , m_pD3DVertexDeclaration( nullptr )\n    {\n    }\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    DX9RenderVertexAttribute::~DX9RenderVertexAttribute()\n    {\n        MENGINE_ASSERTION_FATAL( m_pD3DVertexDeclaration == nullptr );\n    }\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    bool DX9RenderVertexAttribute::initialize( const ConstString & _name, uint32_t _elementSize )\n    {\n        m_name = _name;\n        m_elementSize = _elementSize;\n\n        return true;\n    }\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    void DX9RenderVertexAttribute::finalize()\n    {\n        MENGINE_ASSERTION_FATAL( m_pD3DVertexDeclaration == nullptr );\n\n        \/\/Empty\n    }\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    bool DX9RenderVertexAttribute::compile( IDirect3DDevice9 * _pD3DDevice )\n    {\n        if( m_compileReferenceCount == 0 )\n        {\n            MENGINE_ASSERTION_FATAL( m_pD3DVertexDeclaration == nullptr );\n\n            D3DVERTEXELEMENT9 declaration[64];\n\n            DWORD declaration_iterator = 0;\n\n            for( const AttributeDesc & desc : m_attributes )\n            {\n                if( desc.uniform == STRINGIZE_STRING_LOCAL( \"inVert\" ) )\n                {\n                    declaration[declaration_iterator++] = {0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0};\n                }\n                else if( desc.uniform == STRINGIZE_STRING_LOCAL( \"inCol\" ) )\n                {\n                    declaration[declaration_iterator++] = {0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0};\n                }\n                else if( desc.uniform == STRINGIZE_STRING_LOCAL( \"inUV0\" ) )\n                {\n                    declaration[declaration_iterator++] = {0, 16, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0};\n                }\n                else if( desc.uniform == STRINGIZE_STRING_LOCAL( \"inUV1\" ) )\n                {\n                    declaration[declaration_iterator++] = {0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1};\n                }\n            }\n\n            declaration[declaration_iterator] = D3DDECL_END();\n\n            LOGGER_INFO( \"render\", \"create vertex declaration '%s'\"\n                , m_name.c_str()\n            );\n\n            IDirect3DVertexDeclaration9 * pD3DVertexDeclaration;\n            IF_DXCALL( _pD3DDevice, CreateVertexDeclaration, (declaration, &pD3DVertexDeclaration) )\n            {\n                return false;\n            }\n\n            m_pD3DVertexDeclaration = pD3DVertexDeclaration;\n        }\n\n        ++m_compileReferenceCount;\n\n        return true;\n    }\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    void DX9RenderVertexAttribute::release()\n    {\n        DXRELEASE( m_pD3DVertexDeclaration );\n    }\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    const ConstString & DX9RenderVertexAttribute::getName() const\n    {\n        return m_name;\n    }\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    uint32_t DX9RenderVertexAttribute::getElementSize() const\n    {\n        return m_elementSize;\n    }\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    void DX9RenderVertexAttribute::enable( IDirect3DDevice9 * _pD3DDevice )\n    {\n        DXCALL( _pD3DDevice, SetVertexDeclaration, (m_pD3DVertexDeclaration) );\n    }\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    void DX9RenderVertexAttribute::disable( IDirect3DDevice9 * _pD3DDevice )\n    {\n        DXCALL( _pD3DDevice, SetVertexDeclaration, (NULL) );\n    }\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    void DX9RenderVertexAttribute::addAttribute( const ConstString & _uniform, uint32_t _index, uint32_t _size, EVertexAttributeType _type, bool _normalized, uint32_t _stride, uint32_t _offset )\n    {\n        MENGINE_UNUSED( _index );\n\n        AttributeDesc desc;\n        desc.uniform = _uniform;\n        desc.size = _size;\n        desc.type = _type;\n        desc.normalized = _normalized;\n        desc.stride = _stride;\n        desc.offset = _offset;\n\n        m_attributes.emplace_back( desc );\n\n        MENGINE_ASSERTION_FATAL( m_attributes.size() < 64 );\n    }\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n}","avg_line_length":37.4621212121,"max_line_length":194,"alphanum_fraction":0.5041456016,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2015,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <obs-module.h>\n\n#include \"xcompcap-main.hpp\"\n\nstatic void *xcompcap_create(obs_data_t *settings, obs_source_t *source)\n{\n\treturn new XCompcapMain(settings, source);\n}\n\nstatic void xcompcap_destroy(void *data)\n{\n\tXCompcapMain *cc = (XCompcapMain *)data;\n\tdelete cc;\n}\n\nstatic void xcompcap_video_tick(void *data, float seconds)\n{\n\tXCompcapMain *cc = (XCompcapMain *)data;\n\tcc->tick(seconds);\n}\n\nstatic void xcompcap_video_render(void *data, gs_effect_t *effect)\n{\n\tXCompcapMain *cc = (XCompcapMain *)data;\n\tcc->render(effect);\n}\n\nstatic uint32_t xcompcap_getwidth(void *data)\n{\n\tXCompcapMain *cc = (XCompcapMain *)data;\n\treturn cc->width();\n}\n\nstatic uint32_t xcompcap_getheight(void *data)\n{\n\tXCompcapMain *cc = (XCompcapMain *)data;\n\treturn cc->height();\n}\n\nstatic obs_properties_t *xcompcap_props(void *unused)\n{\n\tUNUSED_PARAMETER(unused);\n\n\treturn XCompcapMain::properties();\n}\n\nvoid xcompcap_defaults(obs_data_t *settings)\n{\n\tXCompcapMain::defaults(settings);\n}\n\nvoid xcompcap_update(void *data, obs_data_t *settings)\n{\n\tXCompcapMain *cc = (XCompcapMain *)data;\n\tcc->updateSettings(settings);\n}\n\nstatic const char *xcompcap_getname(void *)\n{\n\treturn obs_module_text(\"XCCapture\");\n}\n\nextern \"C\" void xcomposite_load(void)\n{\n\tif (!XCompcapMain::init())\n\t\treturn;\n\n\tobs_source_info sinfo;\n\tmemset(&sinfo, 0, sizeof(obs_source_info));\n\n\tsinfo.id = \"xcomposite_input\";\n\tsinfo.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW |\n\t\t\t     OBS_SOURCE_DO_NOT_DUPLICATE;\n\n\tsinfo.get_name = xcompcap_getname;\n\tsinfo.create = xcompcap_create;\n\tsinfo.destroy = xcompcap_destroy;\n\tsinfo.get_properties = xcompcap_props;\n\tsinfo.get_defaults = xcompcap_defaults;\n\tsinfo.update = xcompcap_update;\n\tsinfo.video_tick = xcompcap_video_tick;\n\tsinfo.video_render = xcompcap_video_render;\n\tsinfo.get_width = xcompcap_getwidth;\n\tsinfo.get_height = xcompcap_getheight;\n\tsinfo.icon_type = OBS_ICON_TYPE_WINDOW_CAPTURE,\n\n\tobs_register_source(&sinfo);\n}\n\nextern \"C\" void xcomposite_unload(void)\n{\n\tXCompcapMain::deinit();\n}\n","avg_line_length":21.4361702128,"max_line_length":72,"alphanum_fraction":0.7602977667,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":893,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2014 The Bitcoin Core developers\n\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/ Copyright (c) 2015-2017 The PIVX developers\n\/\/ Copyright (c) 2017-2018 The TittieCoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"primitives\/transaction.h\"\n#include \"main.h\"\n\n#include <boost\/test\/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(main_tests)\n\nBOOST_AUTO_TEST_CASE(subsidy_limit_test)\n{\n    CAmount nSum = 0;\n    for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) {\n        \/* @TODO fix subsidity, add nBits *\/\n        CAmount nSubsidy = GetBlockValue(nHeight);\n        BOOST_CHECK(nSubsidy <= 50 * COIN);\n        nSum += nSubsidy * 1000;\n        BOOST_CHECK(MoneyRange(nSum));\n    }\n    BOOST_CHECK(nSum == 2099999997690000ULL);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":30.7931034483,"max_line_length":71,"alphanum_fraction":0.7110862262,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2776,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":6.0,"content":"#include \"infinispan\/hotrod\/RemoteCacheManager.h\"\n#include \"hotrod\/impl\/RemoteCacheManagerImpl.h\"\n#include \"hotrod\/impl\/protocol\/CodecFactory.h\"\n#include \"hotrod\/impl\/operations\/OperationsFactory.h\"\n\nnamespace infinispan {\nnamespace hotrod {\n\n\nusing namespace protocol;\nusing namespace transport;\nusing namespace operations;\n\n#define IMPL ((RemoteCacheManagerImpl *) impl)\n\nvoid removeFromMap(std::map<std::string, std::unique_ptr<RemoteCacheBase> >& map, std::string& name) {\n    map.erase(name+\"\/false\");\n    map.erase(name+\"\/true\");\n}\n\nRemoteCacheManager::RemoteCacheManager(bool start_)\n  : impl(new RemoteCacheManagerImpl(start_)), transactionManager(TransactionManagerLookup::lookup()) {\n    cacheRemover = std::bind(removeFromMap, std::ref(remoteCacheMap), std::placeholders::_1);\n}\n\nRemoteCacheManager::RemoteCacheManager(const Configuration& configuration, bool start_)\n  : impl(new RemoteCacheManagerImpl(configuration, start_)), transactionManager(TransactionManagerLookup::lookup()) {\n    cacheRemover = std::bind(removeFromMap, std::ref(remoteCacheMap), std::placeholders::_1);\n}\n\nvoid RemoteCacheManager::init(const std::map<std::string, std::string> &properties, bool start_) {\n    cacheRemover = std::bind(removeFromMap, std::ref(remoteCacheMap), std::placeholders::_1);\n    impl = new RemoteCacheManagerImpl(properties, start_);\n}\n\nRemoteCounterManager& RemoteCacheManager::getCounterManager() {\n    return IMPL->getRemoteCounterManager();\n}\n\nRemoteCacheManager::~RemoteCacheManager() {\n\tif (IMPL)\n\t\tdelete IMPL;\n\timpl=nullptr;\n}\n\nvoid RemoteCacheManager::initCache(\n    RemoteCacheBase& cache, bool forceReturnValue, NearCacheConfiguration nc)\n{\n    cache.impl = IMPL->createRemoteCache(forceReturnValue, nc);\n}\n\nvoid RemoteCacheManager::initCache(\n    RemoteCacheBase& cache, const char *name, bool forceReturnValue, NearCacheConfiguration nc)\n{\n    cache.impl = IMPL->createRemoteCache(std::string(name), forceReturnValue, nc);\n}\n\nvoid RemoteCacheManager::start() {\n    IMPL->start();\n}\n\nvoid RemoteCacheManager::stop() {\n    IMPL->stop();\n}\n\nbool RemoteCacheManager::isStarted() {\n    return IMPL->isStarted();\n}\n\nconst Configuration& RemoteCacheManager::getConfiguration() {\n    return IMPL->getConfiguration();\n}\n\nbool RemoteCacheManager::switchToDefaultCluster()\n{\n  return IMPL->clusterSwitch(Configuration::DEFAULT_CLUSTER_NAME);\n}\nbool RemoteCacheManager::switchToCluster(std::string clusterName)\n{\n\treturn IMPL->clusterSwitch(clusterName);\n}\n\nstd::shared_ptr<RemoteCacheManagerAdmin> RemoteCacheManager::newRemoteCacheManagerAdmin() {\n    return IMPL->newRemoteCacheManagerAdmin(*this, cacheRemover);\n}\n\nstd::set<std::string> RemoteCacheManager::getCacheNames() {\n    return administration()->getCacheNames();\n}\n\n}} \/\/ namespace infinispan::hotrod\n","avg_line_length":30.1739130435,"max_line_length":117,"alphanum_fraction":0.7672910663,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":98,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":null,"content":"#include\"Shape.h\"\n#include <iostream>\n\nShape::Shape(float x,float y,float z):Field_Object(x,y,z){}","avg_line_length":24.5,"max_line_length":59,"alphanum_fraction":0.7244897959,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2958,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"StolenVehicleInfo.h\"\n\n#include <cpprest\/json.h>\nusing namespace web;\n\nStolenVehicleInfo::StolenVehicleInfo()\n{\n}\n\nStolenVehicleInfo::~StolenVehicleInfo()\n{\n}\n\nconst TSTRING& StolenVehicleInfo::getVehicleRegistration() const {\n\treturn _vehicleRegistration;\n}\n\nvoid StolenVehicleInfo::setVehicleRegistration(const TSTRING& vehicleRegistration) {\n\t_vehicleRegistration = vehicleRegistration;\n}\n\nconst TSTRING& StolenVehicleInfo::getVehicleMake() const {\n\treturn _vehicleMake;\n}\n\nvoid StolenVehicleInfo::setVehicleMake(const TSTRING& vehicleMake) {\n\t_vehicleMake = vehicleMake;\n}\n\nconst TSTRING& StolenVehicleInfo::getVehicleModel() const {\n\treturn _vehicleModel;\n}\n\nvoid StolenVehicleInfo::setVehicleModel(const TSTRING& vehicleModel) {\n\t_vehicleModel = vehicleModel;\n}\n\nconst VehicleOwnerRef& StolenVehicleInfo::getVehicleOwner() const {\n\treturn _vehicleOwner;\n}\nvoid StolenVehicleInfo::setVehicleOwner(const VehicleOwnerRef& vehicleOwner) {\n\t_vehicleOwner = vehicleOwner;\n}\n\nvoid StolenVehicleInfo::fromJsonObject(const JSON_T& value) {\n\tif (value.has_field(JSON_FILED_REGISTRATION)) {\n\t\t_vehicleRegistration = value.at(JSON_FILED_REGISTRATION).as_string();\n\t}\n\telse {\n\t\t_vehicleRegistration.clear();\n\t}\n\tif (value.has_field(JSON_FILED_MAKE)) {\n\t\t_vehicleMake = value.at(JSON_FILED_MAKE).as_string();\n\t}\n\telse {\n\t\t_vehicleMake.clear();\n\t}\n\tif (value.has_field(JSON_FILED_MODEL)) {\n\t\t_vehicleModel = value.at(JSON_FILED_MODEL).as_string();\n\t}\n\telse {\n\t\t_vehicleModel.clear();\n\t}\n\tif (value.has_field(JSON_FILED_OWNER)) {\n\t\t_vehicleOwner = std::make_shared<VehicleOwner>();\n\t\t_vehicleOwner->fromJsonObject(value.at(JSON_FILED_OWNER));\n\t}\n\telse {\n\t\t_vehicleOwner.reset();\n\t}\n}\n\n\nvoid StolenVehicleInfo::toJsonObject(JSON_T& obj) const {\n\tobj[JSON_FILED_REGISTRATION] = json::value::string(_vehicleRegistration);\n\tobj[JSON_FILED_MAKE] = json::value::string(_vehicleMake);\n\tobj[JSON_FILED_MODEL] = json::value::string(_vehicleModel);\n\tif (_vehicleOwner) {\n\t\tjson::value ownerObject;\n\t\t_vehicleOwner->toJsonObject(ownerObject);\n\t\tobj[JSON_FILED_OWNER] = ownerObject;\n\t}\n}\n\nstd::shared_ptr<std::list<StolenVehicleInfo>> StolenVehicleInfo::parseFromJsonArray(const TSTRING& s) {\n\tstd::shared_ptr<std::list<StolenVehicleInfo>> objs;\n\tjson::value arrayObj = json::value::parse(s);\n\tif (arrayObj.is_array() == false) {\n\t\treturn objs;\n\t}\n\n\tobjs = std::make_shared<std::list<StolenVehicleInfo>>();\n\tauto& jsArray = arrayObj.as_array();\n\tfor (auto it = jsArray.begin(); it != jsArray.end(); it++) {\n\t\tif (it->is_object()) {\n\t\t\tStolenVehicleInfo dummy;\n\t\t\tobjs->push_back(dummy);\n\t\t\tauto& obj = objs->back();\n\t\t\tobj.fromJsonObject(*it);\n\t\t}\n\t}\n\n\treturn objs;\n}\n\nTSTRING StolenVehicleInfo::convertToJsonArray(const std::list<StolenVehicleInfo>& vehicles) {\n\tjson::value arrayVal;\t\n\tint idx = 0;\n\tfor (const StolenVehicleInfo& vehicle : vehicles) {\n\t\tjson::value object;\n\t\tvehicle.toJsonObject(object);\n\t\tarrayVal[idx++] = object;\n\t}\n\n\treturn arrayVal.to_string();\n}","avg_line_length":25.5,"max_line_length":103,"alphanum_fraction":0.7518593644,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":17201,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include \"testing\/testing.hpp\"\n\n#include \"coding\/compressed_bit_vector.hpp\"\n#include \"coding\/writer.hpp\"\n\n#include \"std\/algorithm.hpp\"\n#include \"std\/iterator.hpp\"\n#include \"std\/set.hpp\"\n\nnamespace\n{\nvoid Intersect(vector<uint64_t> & setBits1, vector<uint64_t> & setBits2, vector<uint64_t> & result)\n{\n  sort(setBits1.begin(), setBits1.end());\n  sort(setBits2.begin(), setBits2.end());\n  set_intersection(setBits1.begin(), setBits1.end(), setBits2.begin(), setBits2.end(),\n                   back_inserter(result));\n}\n\nvoid Subtract(vector<uint64_t> & setBits1, vector<uint64_t> & setBits2, vector<uint64_t> & result)\n{\n  sort(setBits1.begin(), setBits1.end());\n  sort(setBits2.begin(), setBits2.end());\n  set_difference(setBits1.begin(), setBits1.end(), setBits2.begin(), setBits2.end(),\n                 back_inserter(result));\n}\n\nvoid Union(vector<uint64_t> & setBits1, vector<uint64_t> & setBits2, vector<uint64_t> & result)\n{\n  sort(setBits1.begin(), setBits1.end());\n  sort(setBits2.begin(), setBits2.end());\n  set_union(setBits1.begin(), setBits1.end(), setBits2.begin(), setBits2.end(),\n            back_inserter(result));\n}\n\ntemplate <typename TBinaryOp>\nvoid CheckBinaryOp(TBinaryOp op, vector<uint64_t> & setBits1, vector<uint64_t> & setBits2,\n                   coding::CompressedBitVector const & cbv)\n{\n  vector<uint64_t> expected;\n  op(setBits1, setBits2, expected);\n  TEST_EQUAL(expected.size(), cbv.PopCount(), ());\n\n  for (size_t i = 0; i < expected.size(); ++i)\n    TEST(cbv.GetBit(expected[i]), ());\n}\n\nvoid CheckIntersection(vector<uint64_t> & setBits1, vector<uint64_t> & setBits2,\n                       coding::CompressedBitVector const & cbv)\n{\n  CheckBinaryOp(&Intersect, setBits1, setBits2, cbv);\n}\n\nvoid CheckSubtraction(vector<uint64_t> & setBits1, vector<uint64_t> & setBits2,\n                      coding::CompressedBitVector const & cbv)\n{\n  CheckBinaryOp(&Subtract, setBits1, setBits2, cbv);\n}\n\nvoid CheckUnion(vector<uint64_t> & setBits1, vector<uint64_t> & setBits2,\n                coding::CompressedBitVector const & cbv)\n{\n  CheckBinaryOp(&Union, setBits1, setBits2, cbv);\n}\n\nvoid CheckUnion(vector<uint64_t> & setBits1, coding::CompressedBitVector::StorageStrategy strategy1,\n                vector<uint64_t> & setBits2, coding::CompressedBitVector::StorageStrategy strategy2,\n                coding::CompressedBitVector::StorageStrategy resultStrategy)\n{\n  auto cbv1 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits1);\n  auto cbv2 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits2);\n  TEST(cbv1.get(), ());\n  TEST(cbv2.get(), ());\n  TEST_EQUAL(strategy1, cbv1->GetStorageStrategy(), ());\n  TEST_EQUAL(strategy2, cbv2->GetStorageStrategy(), ());\n\n  auto cbv3 = coding::CompressedBitVector::Union(*cbv1, *cbv2);\n  TEST(cbv3.get(), ());\n  TEST_EQUAL(resultStrategy, cbv3->GetStorageStrategy(), ());\n  CheckUnion(setBits1, setBits2, *cbv3);\n}\n}  \/\/ namespace\n\nUNIT_TEST(CompressedBitVector_Intersect1)\n{\n  size_t const kNumBits = 100;\n  vector<uint64_t> setBits1;\n  vector<uint64_t> setBits2;\n  for (size_t i = 0; i < kNumBits; ++i)\n  {\n    if (i > 0)\n      setBits1.push_back(i);\n    if (i + 1 < kNumBits)\n      setBits2.push_back(i);\n  }\n  auto cbv1 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits1);\n  auto cbv2 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits2);\n  TEST(cbv1.get(), ());\n  TEST(cbv2.get(), ());\n\n  auto cbv3 = coding::CompressedBitVector::Intersect(*cbv1, *cbv2);\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Dense, cbv3->GetStorageStrategy(), ());\n  CheckIntersection(setBits1, setBits2, *cbv3);\n}\n\nUNIT_TEST(CompressedBitVector_Intersect2)\n{\n  size_t const kNumBits = 100;\n  vector<uint64_t> setBits1;\n  vector<uint64_t> setBits2;\n  for (size_t i = 0; i < kNumBits; ++i)\n  {\n    if (i <= kNumBits \/ 2)\n      setBits1.push_back(i);\n    if (i >= kNumBits \/ 2)\n      setBits2.push_back(i);\n  }\n  auto cbv1 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits1);\n  auto cbv2 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits2);\n  TEST(cbv1.get(), ());\n  TEST(cbv2.get(), ());\n\n  auto cbv3 = coding::CompressedBitVector::Intersect(*cbv1, *cbv2);\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Sparse, cbv3->GetStorageStrategy(), ());\n  CheckIntersection(setBits1, setBits2, *cbv3);\n}\n\nUNIT_TEST(CompressedBitVector_Intersect3)\n{\n  size_t const kNumBits = 100;\n  vector<uint64_t> setBits1;\n  vector<uint64_t> setBits2;\n  for (size_t i = 0; i < kNumBits; ++i)\n  {\n    if (i % 2 == 0)\n      setBits1.push_back(i);\n    if (i % 3 == 0)\n      setBits2.push_back(i);\n  }\n  auto cbv1 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits1);\n  auto cbv2 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits2);\n  TEST(cbv1.get(), ());\n  TEST(cbv2.get(), ());\n  auto cbv3 = coding::CompressedBitVector::Intersect(*cbv1, *cbv2);\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Sparse, cbv3->GetStorageStrategy(), ());\n  CheckIntersection(setBits1, setBits2, *cbv3);\n}\n\nUNIT_TEST(CompressedBitVector_Intersect4)\n{\n  size_t const kNumBits = 1000;\n  vector<uint64_t> setBits1;\n  vector<uint64_t> setBits2;\n  for (size_t i = 0; i < kNumBits; ++i)\n  {\n    if (i % 100 == 0)\n      setBits1.push_back(i);\n    if (i % 150 == 0)\n      setBits2.push_back(i);\n  }\n  auto cbv1 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits1);\n  auto cbv2 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits2);\n  TEST(cbv1.get(), ());\n  TEST(cbv2.get(), ());\n  auto cbv3 = coding::CompressedBitVector::Intersect(*cbv1, *cbv2);\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Sparse, cbv3->GetStorageStrategy(), ());\n  CheckIntersection(setBits1, setBits2, *cbv3);\n}\n\nUNIT_TEST(CompressedBitVector_Subtract1)\n{\n  vector<uint64_t> setBits1 = {0, 1, 2, 3, 4, 5, 6};\n  vector<uint64_t> setBits2 = {1, 2, 3, 4, 5, 6, 7};\n\n  auto cbv1 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits1);\n  auto cbv2 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits2);\n  TEST(cbv1.get(), ());\n  TEST(cbv2.get(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Dense, cbv1->GetStorageStrategy(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Dense, cbv2->GetStorageStrategy(), ());\n\n  auto cbv3 = coding::CompressedBitVector::Subtract(*cbv1, *cbv2);\n  TEST(cbv3.get(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Dense, cbv3->GetStorageStrategy(), ());\n  CheckSubtraction(setBits1, setBits2, *cbv3);\n}\n\nUNIT_TEST(CompressedBitVector_Subtract2)\n{\n  vector<uint64_t> setBits1;\n  for (size_t i = 0; i < 100; ++i)\n    setBits1.push_back(i);\n\n  vector<uint64_t> setBits2 = {9, 14};\n  auto cbv1 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits1);\n  auto cbv2 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits2);\n  TEST(cbv1.get(), ());\n  TEST(cbv2.get(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Dense, cbv1->GetStorageStrategy(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Sparse, cbv2->GetStorageStrategy(), ());\n\n  auto cbv3 = coding::CompressedBitVector::Subtract(*cbv1, *cbv2);\n  TEST(cbv3.get(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Dense, cbv3->GetStorageStrategy(), ());\n  CheckSubtraction(setBits1, setBits2, *cbv3);\n}\n\nUNIT_TEST(CompressedBitVector_Subtract3)\n{\n  vector<uint64_t> setBits1 = {0, 9};\n  vector<uint64_t> setBits2 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n  auto cbv1 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits1);\n  auto cbv2 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits2);\n  TEST(cbv1.get(), ());\n  TEST(cbv2.get(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Sparse, cbv1->GetStorageStrategy(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Dense, cbv2->GetStorageStrategy(), ());\n\n  auto cbv3 = coding::CompressedBitVector::Subtract(*cbv1, *cbv2);\n  TEST(cbv3.get(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Sparse, cbv3->GetStorageStrategy(), ());\n  CheckSubtraction(setBits1, setBits2, *cbv3);\n}\n\nUNIT_TEST(CompressedBitVector_Subtract4)\n{\n  vector<uint64_t> setBits1 = {0, 5, 15};\n  vector<uint64_t> setBits2 = {0, 10};\n  auto cbv1 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits1);\n  auto cbv2 = coding::CompressedBitVectorBuilder::FromBitPositions(setBits2);\n  TEST(cbv1.get(), ());\n  TEST(cbv2.get(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Sparse, cbv1->GetStorageStrategy(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Sparse, cbv2->GetStorageStrategy(), ());\n\n  auto cbv3 = coding::CompressedBitVector::Subtract(*cbv1, *cbv2);\n  TEST(cbv3.get(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Sparse, cbv3->GetStorageStrategy(), ());\n  CheckSubtraction(setBits1, setBits2, *cbv3);\n}\n\nUNIT_TEST(CompressedBitVector_Union_Smoke)\n{\n  vector<uint64_t> setBits1 = {};\n  vector<uint64_t> setBits2 = {};\n\n  CheckUnion(setBits1, coding::CompressedBitVector::StorageStrategy::Sparse \/* strategy1 *\/,\n             setBits2, coding::CompressedBitVector::StorageStrategy::Sparse \/* strategy2 *\/,\n             coding::CompressedBitVector::StorageStrategy::Sparse \/* resultStrategy *\/);\n}\n\nUNIT_TEST(CompressedBitVector_Union1)\n{\n  vector<uint64_t> setBits1 = {};\n  vector<uint64_t> setBits2 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n\n  CheckUnion(setBits1, coding::CompressedBitVector::StorageStrategy::Sparse \/* strategy1 *\/,\n             setBits2, coding::CompressedBitVector::StorageStrategy::Dense \/* strategy2 *\/,\n             coding::CompressedBitVector::StorageStrategy::Dense \/* resultStrategy *\/);\n}\n\nUNIT_TEST(CompressedBitVector_Union2)\n{\n  vector<uint64_t> setBits1 = {256, 1024};\n  vector<uint64_t> setBits2 = {0, 32, 64};\n\n  CheckUnion(setBits1, coding::CompressedBitVector::StorageStrategy::Sparse \/* strategy1 *\/,\n             setBits2, coding::CompressedBitVector::StorageStrategy::Sparse \/* strategy2 *\/,\n             coding::CompressedBitVector::StorageStrategy::Sparse \/* resultStrategy *\/);\n}\n\nUNIT_TEST(CompressedBitVector_Union3)\n{\n  vector<uint64_t> setBits1 = {0, 1, 2, 3, 4, 5, 6};\n\n  vector<uint64_t> setBits2;\n  for (int i = 0; i < 256; ++i)\n    setBits2.push_back(i);\n\n  CheckUnion(setBits1, coding::CompressedBitVector::StorageStrategy::Dense \/* strategy1 *\/,\n             setBits2, coding::CompressedBitVector::StorageStrategy::Dense \/* strategy2 *\/,\n             coding::CompressedBitVector::StorageStrategy::Dense \/* resultStrategy *\/);\n}\n\nUNIT_TEST(CompressedBitVector_Union4)\n{\n  vector<uint64_t> setBits1;\n  for (int i = 0; i < coding::DenseCBV::kBlockSize; ++i)\n    setBits1.push_back(i);\n\n  vector<uint64_t> setBits2 = {1000000000};\n\n  CheckUnion(setBits1, coding::CompressedBitVector::StorageStrategy::Dense \/* strategy1 *\/,\n             setBits2, coding::CompressedBitVector::StorageStrategy::Sparse \/* strategy2 *\/,\n             coding::CompressedBitVector::StorageStrategy::Sparse \/* resultStrategy *\/);\n}\n\nUNIT_TEST(CompressedBitVector_SerializationDense)\n{\n  int const kNumBits = 100;\n  vector<uint64_t> setBits;\n  for (size_t i = 0; i < kNumBits; ++i)\n    setBits.push_back(i);\n  vector<uint8_t> buf;\n  {\n    MemWriter<vector<uint8_t>> writer(buf);\n    auto cbv = coding::CompressedBitVectorBuilder::FromBitPositions(setBits);\n    TEST_EQUAL(setBits.size(), cbv->PopCount(), ());\n    TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Dense, cbv->GetStorageStrategy(), ());\n    cbv->Serialize(writer);\n  }\n  MemReader reader(buf.data(), buf.size());\n  auto cbv = coding::CompressedBitVectorBuilder::DeserializeFromReader(reader);\n  TEST(cbv.get(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Dense, cbv->GetStorageStrategy(), ());\n  TEST_EQUAL(setBits.size(), cbv->PopCount(), ());\n  for (size_t i = 0; i < setBits.size(); ++i)\n    TEST(cbv->GetBit(setBits[i]), ());\n}\n\nUNIT_TEST(CompressedBitVector_SerializationSparse)\n{\n  int const kNumBits = 100;\n  vector<uint64_t> setBits;\n  for (size_t i = 0; i < kNumBits; ++i)\n  {\n    if (i % 10 == 0)\n      setBits.push_back(i);\n  }\n  vector<uint8_t> buf;\n  {\n    MemWriter<vector<uint8_t>> writer(buf);\n    auto cbv = coding::CompressedBitVectorBuilder::FromBitPositions(setBits);\n    TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Sparse, cbv->GetStorageStrategy(), ());\n    cbv->Serialize(writer);\n  }\n  MemReader reader(buf.data(), buf.size());\n  auto cbv = coding::CompressedBitVectorBuilder::DeserializeFromReader(reader);\n  TEST(cbv.get(), ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Sparse, cbv->GetStorageStrategy(), ());\n  TEST_EQUAL(setBits.size(), cbv->PopCount(), ());\n  for (size_t i = 0; i < setBits.size(); ++i)\n    TEST(cbv->GetBit(setBits[i]), ());\n}\n\nUNIT_TEST(CompressedBitVector_ForEach)\n{\n  int const kNumBits = 150;\n  vector<uint64_t> denseBits;\n  vector<uint64_t> sparseBits;\n  for (size_t i = 0; i < kNumBits; ++i)\n  {\n    denseBits.push_back(i);\n    if (i % 15 == 0)\n      sparseBits.push_back(i);\n  }\n  auto denseCBV = coding::CompressedBitVectorBuilder::FromBitPositions(denseBits);\n  auto sparseCBV = coding::CompressedBitVectorBuilder::FromBitPositions(sparseBits);\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Dense, denseCBV->GetStorageStrategy(),\n             ());\n  TEST_EQUAL(coding::CompressedBitVector::StorageStrategy::Sparse, sparseCBV->GetStorageStrategy(),\n             ());\n\n  set<uint64_t> denseSet;\n  uint64_t maxPos = 0;\n  coding::CompressedBitVectorEnumerator::ForEach(*denseCBV, [&](uint64_t pos)\n                                                 {\n                                                   denseSet.insert(pos);\n                                                   maxPos = max(maxPos, pos);\n                                                 });\n  TEST_EQUAL(denseSet.size(), kNumBits, ());\n  TEST_EQUAL(maxPos, kNumBits - 1, ());\n\n  coding::CompressedBitVectorEnumerator::ForEach(*sparseCBV, [](uint64_t pos)\n                                                 {\n                                                   TEST_EQUAL(pos % 15, 0, ());\n                                                 });\n}\n\nUNIT_TEST(CompressedBitVector_DenseOneBit)\n{\n  vector<uint64_t> setBits = {0};\n  unique_ptr<coding::DenseCBV> cbv(new coding::DenseCBV(setBits));\n  TEST_EQUAL(cbv->PopCount(), 1, ());\n  coding::CompressedBitVectorEnumerator::ForEach(*cbv, [&](uint64_t pos)\n                                                 {\n                                                   TEST_EQUAL(pos, 0, ());\n                                                 });\n}\n\nUNIT_TEST(CompressedBitVector_LeaveFirstNBitsSmoke)\n{\n  auto cbv = coding::CompressedBitVectorBuilder::FromBitPositions(vector<uint64_t>{});\n  TEST_EQUAL(cbv->PopCount(), 0, ());\n\n  cbv = cbv->LeaveFirstSetNBits(0);\n  TEST_EQUAL(cbv->PopCount(), 0, ());\n\n  cbv = cbv->LeaveFirstSetNBits(200);\n  TEST_EQUAL(cbv->PopCount(), 0, ());\n}\n\nUNIT_TEST(CompressedBitVector_DenseLeaveFirstNBits)\n{\n  {\n    vector<uint64_t> setBits;\n    setBits.assign(coding::DenseCBV::kBlockSize * 4, 1);\n    auto cbv = coding::CompressedBitVectorBuilder::FromBitPositions(setBits);\n    TEST_EQUAL(cbv->PopCount(), coding::DenseCBV::kBlockSize * 4, ());\n    TEST_EQUAL(cbv->GetStorageStrategy(), coding::CompressedBitVector::StorageStrategy::Dense, ());\n\n    cbv = cbv->LeaveFirstSetNBits(0);\n    TEST_EQUAL(cbv->PopCount(), 0, ());\n  }\n\n  {\n    vector<uint64_t> setBits;\n    for (uint64_t i = 0; i < 100; ++i)\n      setBits.push_back(2 * i);\n    auto cbv = coding::CompressedBitVectorBuilder::FromBitPositions(setBits);\n    TEST_EQUAL(cbv->PopCount(), 100, ());\n    TEST_EQUAL(cbv->GetStorageStrategy(), coding::CompressedBitVector::StorageStrategy::Dense, ());\n\n    cbv = cbv->LeaveFirstSetNBits(50);\n    TEST_EQUAL(cbv->PopCount(), 50, ());\n    TEST_EQUAL(cbv->GetStorageStrategy(), coding::CompressedBitVector::StorageStrategy::Dense, ());\n\n    for (uint64_t i = 0; i < 50; ++i)\n    {\n      TEST(cbv->GetBit(2 * i), ());\n      TEST(!cbv->GetBit(2 * i + 1), ());\n    }\n  }\n}\n\nUNIT_TEST(CompressedBitVector_SparseLeaveFirstNBits)\n{\n  vector<uint64_t> setBits;\n  for (int p = 0; p < 10; ++p)\n    setBits.push_back(static_cast<uint64_t>(1) << p);\n  auto cbv = coding::CompressedBitVectorBuilder::FromBitPositions(setBits);\n  TEST_EQUAL(cbv->PopCount(), 10, ());\n  TEST_EQUAL(cbv->GetStorageStrategy(), coding::CompressedBitVector::StorageStrategy::Sparse, ());\n\n  cbv = cbv->LeaveFirstSetNBits(100);\n  TEST_EQUAL(cbv->PopCount(), 10, ());\n  for (uint64_t bit = 0; bit < (1 << 10); ++bit)\n  {\n    if (bit != 0 && (bit & (bit - 1)) == 0)\n      TEST(cbv->GetBit(bit), (bit));\n    else\n      TEST(!cbv->GetBit(bit), (bit));\n  }\n\n  cbv = cbv->LeaveFirstSetNBits(8);\n  TEST_EQUAL(cbv->PopCount(), 8, ());\n  for (uint64_t bit = 0; bit < (1 << 10); ++bit)\n  {\n    if (bit != 0 && (bit & (bit - 1)) == 0 && bit < (1 << 8))\n      TEST(cbv->GetBit(bit), (bit));\n    else\n      TEST(!cbv->GetBit(bit), (bit));\n  }\n\n  cbv = cbv->LeaveFirstSetNBits(0);\n  TEST_EQUAL(cbv->PopCount(), 0, ());\n  for (uint64_t bit = 0; bit < (1 << 10); ++bit)\n    TEST(!cbv->GetBit(bit), (bit));\n}\n","avg_line_length":36.5978723404,"max_line_length":100,"alphanum_fraction":0.6724027673,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4280,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":2171.0,"content":"#include <stan\/mcmc\/hmc\/integrators\/expl_leapfrog.hpp>\n#include <gtest\/gtest.h>\n\n#include <sstream>\n#include <stan\/callbacks\/stream_logger.hpp>\n#include <test\/test-models\/good\/mcmc\/hmc\/integrators\/gauss.hpp>\n#include <stan\/io\/dump.hpp>\n#include <stan\/mcmc\/hmc\/hamiltonians\/unit_e_metric.hpp>\n#include <stan\/mcmc\/hmc\/hamiltonians\/diag_e_metric.hpp>\n#include <boost\/random\/additive_combine.hpp>  \/\/ L'Ecuyer RNG\n\ntypedef boost::ecuyer1988 rng_t;\n\nTEST(McmcHmcIntegratorsExplLeapfrog, energy_conservation) {\n  rng_t base_rng(0);\n\n  std::fstream data_stream(std::string(\"\").c_str(), std::fstream::in);\n  stan::io::dump data_var_context(data_stream);\n  data_stream.close();\n\n  std::stringstream model_output;\n  std::stringstream debug, info, warn, error, fatal;\n  stan::callbacks::stream_logger logger(debug, info, warn, error, fatal);\n\n  gauss_model_namespace::gauss_model model(data_var_context, 0, &model_output);\n\n  stan::mcmc::expl_leapfrog<\n      stan::mcmc::unit_e_metric<gauss_model_namespace::gauss_model, rng_t> >\n      integrator;\n\n  stan::mcmc::unit_e_metric<gauss_model_namespace::gauss_model, rng_t> metric(\n      model);\n\n  stan::mcmc::unit_e_point z(1);\n  z.q(0) = 1;\n  z.p(0) = 1;\n\n  metric.init(z, logger);\n  double H0 = metric.H(z);\n  double aveDeltaH = 0;\n\n  double epsilon = 1e-3;\n  double tau = 6.28318530717959;\n  size_t L = tau \/ epsilon;\n\n  for (size_t n = 0; n < L; ++n) {\n    integrator.evolve(z, metric, epsilon, logger);\n\n    double deltaH = metric.H(z) - H0;\n    aveDeltaH += (deltaH - aveDeltaH) \/ double(n + 1);\n  }\n\n  \/\/ Average error in Hamiltonian should be O(epsilon^{2})\n  \/\/ in general, smaller for the gauss_modelian case due to cancellations\n  EXPECT_NEAR(aveDeltaH, 0, epsilon * epsilon);\n\n  EXPECT_EQ(\"\", model_output.str());\n  EXPECT_EQ(\"\", debug.str());\n  EXPECT_EQ(\"\", info.str());\n  EXPECT_EQ(\"\", warn.str());\n  EXPECT_EQ(\"\", error.str());\n  EXPECT_EQ(\"\", fatal.str());\n}\n\nTEST(McmcHmcIntegratorsExplLeapfrog, symplecticness) {\n  rng_t base_rng(0);\n\n  std::fstream data_stream(std::string(\"\").c_str(), std::fstream::in);\n  stan::io::dump data_var_context(data_stream);\n  data_stream.close();\n\n  std::stringstream model_output;\n  std::stringstream debug, info, warn, error, fatal;\n  stan::callbacks::stream_logger logger(debug, info, warn, error, fatal);\n\n  gauss_model_namespace::gauss_model model(data_var_context, 0, &model_output);\n\n  stan::mcmc::expl_leapfrog<\n      stan::mcmc::unit_e_metric<gauss_model_namespace::gauss_model, rng_t> >\n      integrator;\n\n  stan::mcmc::unit_e_metric<gauss_model_namespace::gauss_model, rng_t> metric(\n      model);\n\n  \/\/ Create a circle of points\n  const int n_points = 1000;\n\n  double pi = 3.141592653589793;\n  double r = 1.5;\n  double q0 = 1;\n  double p0 = 0;\n\n  std::vector<stan::mcmc::unit_e_point> z;\n\n  for (int i = 0; i < n_points; ++i) {\n    z.push_back(stan::mcmc::unit_e_point(1));\n\n    double theta = 2 * pi * (double)i \/ (double)n_points;\n    z.back().q(0) = r * cos(theta) + q0;\n    z.back().p(0) = r * sin(theta) + p0;\n  }\n\n  \/\/ Evolve circle\n  double epsilon = 1e-3;\n  size_t L = pi \/ epsilon;\n\n  for (int i = 0; i < n_points; ++i)\n    metric.init(z.at(i), logger);\n\n  for (size_t n = 0; n < L; ++n)\n    for (int i = 0; i < n_points; ++i)\n      integrator.evolve(z.at(i), metric, epsilon, logger);\n\n  \/\/ Compute area of evolved shape using divergence theorem in 2D\n  double area = 0;\n\n  for (int i = 0; i < n_points; ++i) {\n    double x1 = z[i].q(0);\n    double y1 = z[i].p(0);\n    double x2 = z[(i + 1) % n_points].q(0);\n    double y2 = z[(i + 1) % n_points].p(0);\n\n    double x_bary = 0.5 * (x1 + x2);\n    double y_bary = 0.5 * (y1 + y2);\n\n    double x_delta = x2 - x1;\n    double y_delta = y2 - y1;\n\n    double a = sqrt(x_delta * x_delta + y_delta * y_delta);\n\n    double x_norm = 1;\n    double y_norm = -x_delta \/ y_delta;\n    double norm = sqrt(x_norm * x_norm + y_norm * y_norm);\n\n    a *= (x_bary * x_norm + y_bary * y_norm) \/ norm;\n    a = a < 0 ? -a : a;\n\n    area += a;\n  }\n\n  area *= 0.5;\n\n  \/\/ Symplectic integrators preserve volume (area in 2D)\n  EXPECT_NEAR(area, pi * r * r, 1e-2);\n\n  EXPECT_EQ(\"\", model_output.str());\n  EXPECT_EQ(\"\", debug.str());\n  EXPECT_EQ(\"\", info.str());\n  EXPECT_EQ(\"\", warn.str());\n  EXPECT_EQ(\"\", error.str());\n  EXPECT_EQ(\"\", fatal.str());\n}\n","avg_line_length":27.9738562092,"max_line_length":79,"alphanum_fraction":0.6525700935,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3114,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#define WIN32_LEAN_AND_MEAN\n#define NOMINMAX\n#include \"Windows.h\"\n#include \"WinSock2.h\"\n#include \"Ws2tcpip.h\"\n\n#include <iostream>\n#include <cstdlib>\n#include <string>\n\n#pragma comment(lib, \"ws2_32.lib\")\n\n#define LISTEN_PORT 8888\n\nvoid printWSErrorAndExit(const char* msg)\n{\n\twchar_t* s = NULL;\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t\tNULL, WSAGetLastError(),\n\t\tMAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n\t\t(LPWSTR)&s, 0, NULL);\n\tfprintf(stderr, \"%s: %S\\n\", msg, s);\n\tLocalFree(s);\n\tsystem(\"pause\");\n\texit(-1);\n}\n\nvoid server(int port)\n{\n\t\/\/ Init Winsock\n\tWSADATA wsaData;\n\tint iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);\n\tif (iResult == SOCKET_ERROR)\n\t{\n\t\t\/\/ Log and handle error\n\t\tprintWSErrorAndExit(\"WSAStartup\");\n\t\treturn;\n\t}\n\n\t\/\/ Create socket\n\tSOCKET s = socket(AF_INET, SOCK_STREAM, 0); \/\/ TCP socket\n\tif (s == INVALID_SOCKET)\n\t{\n\t\tprintWSErrorAndExit(\"socket\");\n\t\treturn;\n\t}\n\n\t\/\/ Configure socket fro address reuse\n\tint enable = 1;\n\tiResult = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char*)&enable, sizeof(enable));\n\tif (iResult == SOCKET_ERROR) {\n\t\tprintWSErrorAndExit(\"setsockopt\");\n\t\treturn;\n\t}\n\n\t\/\/ Associate socket to adress object and bind it to local address\n\tsockaddr_in localAddr;\n\tlocalAddr.sin_family = AF_INET; \/\/ IPv4\n\tlocalAddr.sin_port = htons(port); \/\/ Port\n\tlocalAddr.sin_addr.S_un.S_addr = INADDR_ANY; \/\/ Any local IP address\n\tiResult = bind(s, (sockaddr*)&localAddr, sizeof(localAddr));\n\tif (iResult == SOCKET_ERROR) {\n\t\tprintWSErrorAndExit(\"bind\");\n\t\treturn;\n\t}\n\n\t\/\/ Make it listen socket\n\tint simultaneousConnections = 1;\n\tiResult = listen(s, simultaneousConnections);\n\tif (iResult == SOCKET_ERROR) {\n\t\tprintWSErrorAndExit(\"listen\");\n\t\treturn;\n\t}\n\n\t\/\/ Accept new incoming connection from a remote host\n\tsockaddr_in remoteAddr;\n\tint remoteAddrSize = sizeof(remoteAddr);\n\tSOCKET connectedSocket = accept(s, (sockaddr*)&remoteAddr, &remoteAddrSize);\n\tif (connectedSocket == INVALID_SOCKET) {\n\t\tprintWSErrorAndExit(\"accept\");\n\t\treturn;\n\t}\n\n\tchar pingStr[5];\n\t\n\twhile (true) {\n\t\t\n\t\tiResult = recv(connectedSocket, pingStr, sizeof(pingStr), 0);\n\t\tif (iResult == SOCKET_ERROR) {\n\t\t\tprintWSErrorAndExit(\"recv\");\n\t\t\tbreak;\n\t\t}\n\t\telse if (iResult == 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tstd::cout << pingStr << std::endl;\n\n\t\t\n\t\tstd::string pongStr = \"Pong\"; \/\/Testing Api with STL string\n\n\t\tiResult = send(connectedSocket, pongStr.c_str(), pongStr.length()+1, 0);\n\t\tif (iResult == SOCKET_ERROR) {\n\t\t\tprintWSErrorAndExit(\"send\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\n\t\/\/ Delete socket\n\tiResult = closesocket(s);\n\tstd::cout << \"server socket has closed \" << std::endl;\n\tif (iResult == SOCKET_ERROR)\n\t{\n\t\tprintWSErrorAndExit(\"closesocket\");\n\t\treturn;\n\t}\n\t\/\/ CleanUp Winsock\n\tiResult = WSACleanup();\n\tstd::cout << \"server winsock has closed \" << std::endl;\n\tif (iResult == SOCKET_ERROR)\n\t{\n\t\tprintWSErrorAndExit(\"WSACleanup\");\n\t\treturn;\n\t}\n}\n\n\nint main(int argc, char* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\tstd::cout << \"[ERROR]: No Input Arguments (Server Port) entered\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tserver(atoi(argv[1]));\n\n\tsystem(\"pause\");\n\treturn 0;\n}","avg_line_length":22.085106383,"max_line_length":108,"alphanum_fraction":0.6907514451,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1923,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":91.0,"content":"\/*\n * Copyright (c) 2013, Peter Thorson. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and\/or other materials provided with the distribution.\n *     * Neither the name of the WebSocket++ Project nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\/\/#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE random_none\n#include <boost\/test\/unit_test.hpp>\n\n#include <websocketpp\/common\/stdint.hpp>\n#include <websocketpp\/random\/none.hpp>\n\nBOOST_AUTO_TEST_CASE( does_it_compile ) {\n    websocketpp::random::none::int_generator<int32_t> rng;\n\n    int32_t foo = rng();\n\n    BOOST_CHECK( foo == 0 );\n}\n","avg_line_length":46.9024390244,"max_line_length":80,"alphanum_fraction":0.7535101404,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":469,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include \"bignumber.h\"\n#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n\tbigNum n,n2;\n\twhile(1)\n\t{\n\t\tcout << \"1. sayi\" << endl;\n\t\tstring s1;\n\t\tgetline(cin, s1);\n\t\tn.set(s1);\n\t\tcout << \"2. sayi\" << endl;\n\t\tstring s2;\n\t\tgetline(cin, s2);\n\t\tn2.set(s2);\n\t\tcout << \"sonuc\" << endl;\n\t\tcout << (n + n2) << endl;\n\t\tcout << \"beklenen sonuc\" << endl;\n\t\tstring s3;\n\t\tgetline(cin, s3);\n\t\tcout <<\"Esit Mi -> \"<<((n+n2).get()==s3?\"EVET\":\"HAYIR\")<<endl;\t\n\n\t}\n}","avg_line_length":18.0384615385,"max_line_length":65,"alphanum_fraction":0.552238806,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":20777,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":2.0,"content":"\/\/=============================================================================================================\n\/**\n * @file     hpisettingsview.cpp\n * @author   Lorenz Esch <lesch@mgh.harvard.edu>\n *           Ruben D\u00f6rfel <ruben.doerfel@tu-ilmenau.de>\n * @since    0.1.0\n * @date     March, 2020\n *\n * @section  LICENSE\n *\n * Copyright (C) 2020, Lorenz Esch, Ruben D\u00f6rfel. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n *       following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n *       the following disclaimer in the documentation and\/or other materials provided with the distribution.\n *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n *       to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief    HpiSettingsView class definition.\n *\n *\/\n\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"hpisettingsview.h\"\n\n#include \"ui_hpisettingsview.h\"\n\n#include <fiff\/fiff_dig_point_set.h>\n#include <fiff\/fiff_dig_point.h>\n\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include <QFileInfo>\n#include <QFileDialog>\n#include <QMessageBox>\n#include <QSettings>\n\n\/\/=============================================================================================================\n\/\/ EIGEN INCLUDES\n\/\/=============================================================================================================\n\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace DISPLIB;\nusing namespace FIFFLIB;\n\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nHpiSettingsView::HpiSettingsView(const QString& sSettingsPath,\n                                 QWidget *parent,\n                                 Qt::WindowFlags f)\n: AbstractView(parent, f)\n, m_pUi(new Ui::HpiSettingsViewWidget)\n{\n    m_sSettingsPath = sSettingsPath;\n    m_pUi->setupUi(this);\n\n    connect(m_pUi->m_pushButton_loadDigitizers, &QPushButton::released,\n            this, &HpiSettingsView::onLoadDigitizers);\n    connect(m_pUi->m_pushButton_doFreqOrder, &QPushButton::clicked,\n            this, &HpiSettingsView::doFreqOrder);\n    connect(m_pUi->m_pushButton_doSingleFit, &QPushButton::clicked,\n            this, &HpiSettingsView::doSingleHpiFit);\n    connect(m_pUi->m_tableWidget_Frequencies, &QTableWidget::cellChanged,\n            this, &HpiSettingsView::onFrequencyCellChanged);\n    connect(m_pUi->m_pushButton_addCoil, &QPushButton::clicked,\n            this, &HpiSettingsView::onAddCoil);\n    connect(m_pUi->m_pushButton_removeCoil, &QPushButton::clicked,\n            this, &HpiSettingsView::onRemoveCoil);\n    connect(m_pUi->m_checkBox_useSSP, &QCheckBox::clicked,\n            this, &HpiSettingsView::sspStatusChanged);\n    connect(m_pUi->m_checkBox_useComp, &QCheckBox::clicked,\n            this, &HpiSettingsView::compStatusChanged);\n    connect(m_pUi->m_checkBox_continousHPI, &QCheckBox::clicked,\n            this, &HpiSettingsView::contHpiStatusChanged);\n    connect(m_pUi->m_doubleSpinBox_maxHPIContinousDist, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),\n            this, &HpiSettingsView::allowedMeanErrorDistChanged);\n    connect(m_pUi->m_doubleSpinBox_moveThreshold, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),\n            this, &HpiSettingsView::allowedMovementChanged);\n    connect(m_pUi->m_doubleSpinBox_rotThreshold, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),\n            this, &HpiSettingsView::allowedRotationChanged);\n    \/\/Init coil freqs\n    m_vCoilFreqs << 155 << 165 << 190 << 200;\n    qRegisterMetaTypeStreamOperators<QVector<int> >(\"QVector<int>\");\n\n    loadSettings();\n}\n\n\/\/=============================================================================================================\n\nHpiSettingsView::~HpiSettingsView()\n{\n    saveSettings();\n\n    delete m_pUi;\n}\n\n\/\/=============================================================================================================\n\nvoid HpiSettingsView::setErrorLabels(const QVector<double>& vError,\n                                     double dMeanErrorDist)\n{\n    \/\/Update eror labels and change from m to mm\n    QString sGof(\"0mm\");\n\n    for(int i = 0; i < vError.size(); ++i) {\n        if(i < m_pUi->m_tableWidget_errors->rowCount()) {\n            sGof = QString::number(vError[i]*1000,'f',2)+QString(\" mm\");\n            m_pUi->m_tableWidget_errors->item(i, 1)->setText(sGof);\n        }\n    }\n\n    m_pUi->m_label_averagedFitError->setText(QString::number(dMeanErrorDist*1000,'f',2)+QString(\" mm\"));\n\n    \/\/Update good\/bad fit label\n    if(dMeanErrorDist*1000 > m_pUi->m_doubleSpinBox_maxHPIContinousDist->value()) {\n        m_pUi->m_label_fitFeedback->setText(\"Last fit: Bad\");\n        m_pUi->m_label_fitFeedback->setStyleSheet(\"QLabel { background-color : red;}\");\n    } else {\n        m_pUi->m_label_fitFeedback->setText(\"Last fit: Good\");\n        m_pUi->m_label_fitFeedback->setStyleSheet(\"QLabel { background-color : green;}\");\n    }\n}\n\n\/\/=========================================================================================================\n\nvoid HpiSettingsView::setMovementResults(double dMovement,\n                                         double dRotation)\n{\n    m_pUi->m_qLineEdit_moveResult->setText(QString::number(dMovement*1000,'f',2) + QString(\" mm\"));\n    m_pUi->m_qLineEdit_rotResult->setText(QString::number(dRotation,'f',2) + QString(\" \u00b0\"));\n\n    if(dMovement*1000 > m_pUi->m_doubleSpinBox_moveThreshold->value() || dRotation > m_pUi->m_doubleSpinBox_rotThreshold->value()) {\n        m_pUi->m_label_movementFeedback->setText(\"Big\");\n        m_pUi->m_label_movementFeedback->setStyleSheet(\"QLabel { background-color : red;}\");\n    } else {\n        m_pUi->m_label_movementFeedback->setText(\"Small\");\n        m_pUi->m_label_movementFeedback->setStyleSheet(\"QLabel { background-color : green;}\");\n    }\n}\n\n\/\/=============================================================================================================\n\nbool HpiSettingsView::getSspStatusChanged()\n{\n    return m_pUi->m_checkBox_useSSP->isChecked();\n}\n\n\/\/=============================================================================================================\n\nbool HpiSettingsView::getCompStatusChanged()\n{\n    return m_pUi->m_checkBox_useComp->isChecked();\n}\n\n\/\/=============================================================================================================\n\ndouble HpiSettingsView::getAllowedMeanErrorDistChanged()\n{\n    return m_pUi->m_doubleSpinBox_maxHPIContinousDist->value();\n}\n\n\/\/=============================================================================================================\n\ndouble HpiSettingsView::getAllowedMovementChanged()\n{\n    return m_pUi->m_doubleSpinBox_moveThreshold->value();\n}\n\n\/\/=============================================================================================================\n\ndouble HpiSettingsView::getAllowedRotationChanged()\n{\n    return m_pUi->m_doubleSpinBox_rotThreshold->value();\n}\n\n\/\/=============================================================================================================\n\nvoid HpiSettingsView::saveSettings()\n{\n    if(m_sSettingsPath.isEmpty()) {\n        return;\n    }\n\n    QSettings settings(\"MNECPP\");\n    QVariant data;\n\n    data.setValue(m_vCoilFreqs);\n    settings.setValue(m_sSettingsPath + QString(\"\/HpiSettingsView\/coilFreqs\"), data);\n\n    data.setValue(m_pUi->m_checkBox_useSSP->isChecked());\n    settings.setValue(m_sSettingsPath + QString(\"\/HpiSettingsView\/useSSP\"), data);\n\n    data.setValue(m_pUi->m_checkBox_useComp->isChecked());\n    settings.setValue(m_sSettingsPath + QString(\"\/HpiSettingsView\/useCOMP\"), data);\n\n    data.setValue(m_pUi->m_checkBox_continousHPI->isChecked());\n    settings.setValue(m_sSettingsPath + QString(\"\/HpiSettingsView\/continousHPI\"), data);\n\n    data.setValue(m_pUi->m_doubleSpinBox_maxHPIContinousDist->value());\n    settings.setValue(m_sSettingsPath + QString(\"\/HpiSettingsView\/maxError\"), data);\n}\n\n\/\/=============================================================================================================\n\nvoid HpiSettingsView::loadSettings()\n{\n    if(m_sSettingsPath.isEmpty()) {\n        return;\n    }\n\n    QSettings settings(\"MNECPP\");\n    QVariant defaultData;\n\n    defaultData.setValue(m_vCoilFreqs);\n    m_vCoilFreqs = settings.value(m_sSettingsPath + QString(\"\/HpiSettingsView\/coilFreqs\"), defaultData).value<QVector<int> >();\n    emit coilFrequenciesChanged(m_vCoilFreqs);\n\n    m_pUi->m_checkBox_useSSP->setChecked(settings.value(m_sSettingsPath + QString(\"\/HpiSettingsView\/useSSP\"), false).toBool());\n    m_pUi->m_checkBox_useComp->setChecked(settings.value(m_sSettingsPath + QString(\"\/HpiSettingsView\/useCOMP\"), false).toBool());\n    m_pUi->m_checkBox_continousHPI->setChecked(settings.value(m_sSettingsPath + QString(\"\/HpiSettingsView\/continousHPI\"), false).toBool());\n    m_pUi->m_doubleSpinBox_maxHPIContinousDist->setValue(settings.value(m_sSettingsPath + QString(\"\/HpiSettingsView\/maxError\"), 10.0).toDouble());\n}\n\n\/\/=============================================================================================================\n\nvoid HpiSettingsView::updateGuiMode(GuiMode mode)\n{\n    switch(mode) {\n        case GuiMode::Clinical:\n            break;\n        default: \/\/ default is research mode\n            break;\n    }\n}\n\n\/\/=============================================================================================================\n\nvoid HpiSettingsView::updateProcessingMode(ProcessingMode mode)\n{\n    switch(mode) {\n        case ProcessingMode::Offline:\n            break;\n        default: \/\/ default is realtime mode\n            break;\n    }\n}\n\n\/\/=============================================================================================================\n\nvoid HpiSettingsView::onLoadDigitizers()\n{\n    \/\/Get file location\n    QString fileName_HPI = QFileDialog::getOpenFileName(this,\n                                                        tr(\"Open digitizer file\"),\n                                                        \"\",\n                                                        tr(\"Fiff file (*.fif)\"));\n\n    if(!fileName_HPI.isEmpty()) {\n        m_pUi->m_lineEdit_filePath->setText(fileName_HPI);\n    }\n\n    \/\/Load Polhemus file\n    if (!fileName_HPI.isEmpty()) {\n        fileName_HPI = fileName_HPI.trimmed();\n        QFileInfo checkFile(fileName_HPI);\n\n        if (checkFile.exists() && checkFile.isFile()) {\n            \/\/ Stop cont HPI first\n            m_pUi->m_checkBox_continousHPI->setChecked(false);\n            emit digitizersChanged(readPolhemusDig(fileName_HPI), fileName_HPI);\n        } else {\n            QMessageBox msgBox;\n            msgBox.setText(\"File could not be loaded!\");\n            msgBox.exec();\n            return;\n        }\n    }\n}\n\n\/\/=============================================================================================================\n\nvoid HpiSettingsView::onFrequencyCellChanged(int row,\n                                             int col)\n{\n    if(col != 1 || row >= m_vCoilFreqs.size()) {\n        return;\n    }\n\n    if(QTableWidgetItem *pItem = m_pUi->m_tableWidget_Frequencies->item(row, col)) {\n        if(pItem->text() == \"none\") {\n            m_vCoilFreqs[row] = -1;\n        } else {\n            m_vCoilFreqs[row] = pItem->text().toInt();\n        }\n\n        emit coilFrequenciesChanged(m_vCoilFreqs);\n    }\n}\n\n\/\/=============================================================================================================\n\nvoid HpiSettingsView::onAddCoil()\n{\n    if(m_pUi->m_tableWidget_Frequencies->rowCount() + 1 > m_pUi->m_label_numberLoadedCoils->text().toInt()) {\n        QMessageBox msgBox;\n        msgBox.setText(\"Cannot add more HPI coils. Not enough digitzed HPI coils loaded.\");\n        msgBox.exec();\n        return;\n    }\n\n    \/\/ Add column 0 in freq table widget\n    m_pUi->m_tableWidget_Frequencies->insertRow(m_pUi->m_tableWidget_Frequencies->rowCount());\n    QTableWidgetItem* pTableItemA = new QTableWidgetItem(QString::number(m_pUi->m_tableWidget_Frequencies->rowCount()));\n    pTableItemA->setFlags(Qt::ItemIsEnabled);\n    m_pUi->m_tableWidget_Frequencies->setItem(m_pUi->m_tableWidget_Frequencies->rowCount()-1,\n                                             0,\n                                             pTableItemA);\n\n    \/\/ Add column 1 in freq table widget\n    if(m_vCoilFreqs.size() >= m_pUi->m_tableWidget_Frequencies->rowCount()) {\n        m_pUi->m_tableWidget_Frequencies->setItem(m_pUi->m_tableWidget_Frequencies->rowCount()-1,\n                                                 1,\n                                                 new QTableWidgetItem(QString::number(m_vCoilFreqs.at(m_pUi->m_tableWidget_Frequencies->rowCount()-1))));\n    } else {\n        m_pUi->m_tableWidget_Frequencies->setItem(m_pUi->m_tableWidget_Frequencies->rowCount()-1,\n                                                 1,\n                                                 new QTableWidgetItem(\"none\"));\n        m_vCoilFreqs.append(-1);\n    }\n\n    \/\/ Add column 0 in error table widget\n    m_pUi->m_tableWidget_errors->insertRow(m_pUi->m_tableWidget_errors->rowCount());\n    QTableWidgetItem* pTableItemB = new QTableWidgetItem(QString::number(m_pUi->m_tableWidget_Frequencies->rowCount()));\n    pTableItemB->setFlags(Qt::ItemIsEnabled);\n    m_pUi->m_tableWidget_errors->setItem(m_pUi->m_tableWidget_errors->rowCount()-1,\n                                        0,\n                                        pTableItemB);\n\n    \/\/ Add column 1 in error table widget\n    QTableWidgetItem* pTableItemC = new QTableWidgetItem(\"0mm\");\n    pTableItemC->setFlags(Qt::ItemIsEnabled);\n    m_pUi->m_tableWidget_errors->setItem(m_pUi->m_tableWidget_errors->rowCount()-1,\n                                        1,\n                                        pTableItemC);\n\n    emit coilFrequenciesChanged(m_vCoilFreqs);\n}\n\n\/\/=============================================================================================================\n\nvoid HpiSettingsView::onRemoveCoil()\n{\n    int row = m_pUi->m_tableWidget_Frequencies->currentRow();\n\n    if(row >= 0 && row < m_vCoilFreqs.size()) {\n        m_vCoilFreqs.remove(row);\n        m_pUi->m_tableWidget_Frequencies->removeRow(row);\n\n        for (int i = 0; i < m_pUi->m_tableWidget_Frequencies->rowCount(); ++i) {\n            m_pUi->m_tableWidget_Frequencies->item(i, 0)->setText(QString::number(i+1));\n        }\n\n        m_pUi->m_tableWidget_errors->removeRow(row);\n\n        for (int i = 0; i < m_pUi->m_tableWidget_errors->rowCount(); ++i) {\n            m_pUi->m_tableWidget_errors->item(i, 0)->setText(QString::number(i+1));\n        }\n\n        emit coilFrequenciesChanged(m_vCoilFreqs);\n    }\n}\n\n\/\/=============================================================================================================\n\nQList<FiffDigPoint> HpiSettingsView::readPolhemusDig(const QString& fileName)\n{\n    m_pUi->m_tableWidget_Frequencies->clear();\n    m_pUi->m_tableWidget_Frequencies->setRowCount(0);\n    m_pUi->m_tableWidget_Frequencies->setHorizontalHeaderItem(0, new QTableWidgetItem(\"#Coil\"));\n    m_pUi->m_tableWidget_Frequencies->setHorizontalHeaderItem(1, new QTableWidgetItem(\"Frequency (Hz)\"));\n\n    m_pUi->m_tableWidget_errors->clear();\n    m_pUi->m_tableWidget_errors->setRowCount(0);\n    m_pUi->m_tableWidget_errors->setHorizontalHeaderItem(0, new QTableWidgetItem(\"#Coil\"));\n    m_pUi->m_tableWidget_errors->setHorizontalHeaderItem(1, new QTableWidgetItem(\"Error\"));\n\n    QFile t_fileDig(fileName);\n    FiffDigPointSet t_digSet(t_fileDig);\n\n    QList<FiffDigPoint> lDigPoints;\n\n    qint16 numHPI = 0;\n    qint16 numFiducials = 0;\n    qint16 numEEG = 0;\n\n    for(int i = 0; i < t_digSet.size(); ++i) {\n        switch(t_digSet[i].kind) {\n            case FIFFV_POINT_HPI: {\n                \/\/ Add column 0 in freq table widget\n                m_pUi->m_tableWidget_Frequencies->insertRow(m_pUi->m_tableWidget_Frequencies->rowCount());\n                QTableWidgetItem* pTableItemA = new QTableWidgetItem(QString::number(m_pUi->m_tableWidget_Frequencies->rowCount()));\n                pTableItemA->setFlags(Qt::ItemIsEnabled);\n                m_pUi->m_tableWidget_Frequencies->setItem(m_pUi->m_tableWidget_Frequencies->rowCount()-1,\n                                                         0,\n                                                         pTableItemA);\n\n                \/\/ Add column 1 in freq table widget\n                if(m_vCoilFreqs.size() > numHPI) {\n                    m_pUi->m_tableWidget_Frequencies->setItem(m_pUi->m_tableWidget_Frequencies->rowCount()-1,\n                                                             1,\n                                                             new QTableWidgetItem(QString::number(m_vCoilFreqs.at(numHPI))));\n                } else {\n                    m_pUi->m_tableWidget_Frequencies->setItem(m_pUi->m_tableWidget_Frequencies->rowCount()-1,\n                                                             1,\n                                                             new QTableWidgetItem(\"none\"));\n                    m_vCoilFreqs.append(-1);\n                }\n\n                \/\/ Add column 0 in error table widget\n                m_pUi->m_tableWidget_errors->insertRow(m_pUi->m_tableWidget_errors->rowCount());\n                QTableWidgetItem* pTableItemB = new QTableWidgetItem(QString::number(m_pUi->m_tableWidget_Frequencies->rowCount()));\n                pTableItemB->setFlags(Qt::ItemIsEnabled);\n                m_pUi->m_tableWidget_errors->setItem(m_pUi->m_tableWidget_errors->rowCount()-1,\n                                                    0,\n                                                    pTableItemB);\n\n                \/\/ Add column 1 in error table widget\n                QTableWidgetItem* pTableItemC = new QTableWidgetItem(\"0mm\");\n                pTableItemC->setFlags(Qt::ItemIsEnabled);\n                m_pUi->m_tableWidget_errors->setItem(m_pUi->m_tableWidget_errors->rowCount()-1,\n                                                    1,\n                                                    pTableItemC);\n\n                lDigPoints.append(t_digSet[i]);\n                numHPI++;\n                break;\n            }\n\n            case FIFFV_POINT_CARDINAL:\n                lDigPoints.append(t_digSet[i]);\n                numFiducials++;\n                break;\n\n            case FIFFV_POINT_EEG:\n                lDigPoints.append(t_digSet[i]);\n                numEEG++;\n                break;\n        }\n    }\n\n    \/\/Set loaded number of digitizers\n    m_pUi->m_label_numberLoadedCoils->setNum(numHPI);\n    m_pUi->m_label_numberLoadedFiducials->setNum(numFiducials);\n    m_pUi->m_label_numberLoadedEEG->setNum(numEEG);\n\n    \/\/ Make sure that the stored coil freqs always match the number of loaded ones\n    m_vCoilFreqs.resize(numHPI);\n    emit coilFrequenciesChanged(m_vCoilFreqs);\n\n    return lDigPoints;\n}\n","avg_line_length":42.8391752577,"max_line_length":153,"alphanum_fraction":0.5430524137,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8281,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/**\n * Copyright (c) 2017-present, Facebook, Inc. and its affiliates.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n#include \"SyncSequencerRequest.h\"\n\n#include \"logdevice\/common\/MetaDataLog.h\"\n#include \"logdevice\/common\/Processor.h\"\n#include \"logdevice\/common\/Worker.h\"\n\n#include <folly\/Optional.h>\n\nnamespace facebook { namespace logdevice {\n\nconst SyncSequencerRequest::flags_t SyncSequencerRequest::WAIT_RELEASED;\nconst SyncSequencerRequest::flags_t\n    SyncSequencerRequest::INCLUDE_TAIL_ATTRIBUTES;\nconst SyncSequencerRequest::flags_t\n    SyncSequencerRequest::INCLUDE_HISTORICAL_METADATA;\nconst SyncSequencerRequest::flags_t SyncSequencerRequest::INCLUDE_TAIL_RECORD;\n\nSyncSequencerRequest::SyncSequencerRequest(\n    logid_t logid,\n    flags_t flags,\n    Callback cb,\n    GetSeqStateRequest::Context ctx,\n    std::chrono::milliseconds timeout,\n    GetSeqStateRequest::MergeType merge_type,\n    folly::Optional<epoch_t> min_epoch)\n    : Request(RequestType::SYNC_SEQUENCER),\n      logid_(logid),\n      flags_(flags),\n      cb_(std::move(cb)),\n      ctx_(ctx),\n      callbackHelper_(this),\n      timeout_(timeout),\n      merge_type_(merge_type),\n      min_epoch_(min_epoch) {}\n\nRequest::Execution SyncSequencerRequest::execute() {\n  Worker::onThisThread()->runningSyncSequencerRequests().getList().push_back(\n      *this);\n\n  retry_timer_ = std::make_unique<ExponentialBackoffTimer>(\n      Worker::onThisThread()->getEventBase(),\n      [this]() { tryAgain(); },\n      Worker::settings().seq_state_backoff_time);\n\n  if (timeout_.count() > 0) {\n    timeout_timer_ = std::make_unique<LibeventTimer>(\n        Worker::onThisThread()->getEventBase(), [this] { this->onTimeout(); });\n    timeout_timer_->activate(timeout_);\n  }\n\n  tryAgain();\n\n  return Execution::CONTINUE;\n}\n\nvoid SyncSequencerRequest::tryAgain() {\n  if (isCanceled()) {\n    complete(E::CANCELLED);\n    return;\n  }\n\n  ld_check(!shouldComplete());\n\n  \/\/ The reply should be passed back to this worker and to onGotSeqState().\n  auto callback_ticket = callbackHelper_.ticket();\n  GetSeqStateRequest::Options opts;\n  opts.merge_type = merge_type_;\n  opts.wait_for_recovery = false;\n  opts.min_epoch = min_epoch_;\n\n  if (flags_ & INCLUDE_TAIL_ATTRIBUTES) {\n    opts.include_tail_attributes = true;\n  }\n\n  if (flags_ & INCLUDE_HISTORICAL_METADATA) {\n    opts.include_historical_metadata = true;\n  }\n\n  if (flags_ & INCLUDE_TAIL_RECORD) {\n    opts.include_tail_record = true;\n  }\n\n  opts.on_complete = [=](GetSeqStateRequest::Result res) {\n    ld_debug(\"GetSeqStateRequest callback called for log:%lu,\"\n             \" id:%lu, status:%s\",\n             res.log_id.val_,\n             res.rqid.val(),\n             error_description(res.status));\n    callback_ticket.postCallbackRequest([=](SyncSequencerRequest* rq) {\n      if (!rq) {\n        RATELIMIT_INFO(std::chrono::seconds(10),\n                       1,\n                       \"GetSeqStateRequest finished after \"\n                       \"SyncSequencerRequest was destroyed. log:%lu, rqid:%lu\",\n                       res.log_id.val(),\n                       res.rqid.val());\n        return;\n      }\n      rq->onGotSeqState(res);\n    });\n  };\n\n  std::unique_ptr<Request> rq =\n      std::make_unique<GetSeqStateRequest>(logid_, ctx_, opts);\n  ld_debug(\"Posting a new GetSeqStateRequest(id:%\" PRIu64 \") for log:%lu\",\n           (uint64_t)rq->id_,\n           logid_.val_);\n  auto rv = Worker::onThisThread()->processor_->postRequest(rq);\n  if (rv != 0) {\n    RATELIMIT_ERROR(\n        std::chrono::seconds(1),\n        1,\n        \"Failed to post GetSeqStateRequest for log:%lu with error:%s\",\n        logid_.val_,\n        error_description(err));\n    complete(E::FAILED);\n    return;\n  }\n}\n\nvoid SyncSequencerRequest::onGotSeqState(GetSeqStateRequest::Result res) {\n  if (isCanceled()) {\n    complete(E::CANCELLED);\n    return;\n  }\n\n  ld_check(!shouldComplete());\n\n  lastGetSeqStateStatus_ = res.status;\n\n  const dbg::Level level =\n      res.status == E::OK ? dbg::Level::DEBUG : dbg::Level::ERROR;\n  RATELIMIT_LEVEL(level,\n                  std::chrono::seconds(1),\n                  5,\n                  \"Got sequencer state (id:%\" PRIu64 \") for log:%lu, status:%s,\"\n                  \"sequencer:%s, last_released_lsn:%s, next_lsn:%s\",\n                  (uint64_t)res.rqid,\n                  res.log_id.val_,\n                  error_description(res.status),\n                  res.last_seq.toString().c_str(),\n                  lsn_to_string(res.last_released_lsn).c_str(),\n                  lsn_to_string(res.next_lsn).c_str());\n\n  if (res.status == E::NOTFOUND && complete_if_log_not_found_) {\n    complete(E::NOTFOUND);\n    return;\n  }\n\n  if (res.status == E::ACCESS) {\n    complete(E::ACCESS);\n    return;\n  }\n\n  folly::Optional<lsn_t> next_lsn;\n  if (MetaDataLog::isMetaDataLog(res.log_id)) {\n    \/\/ LSN_INVALID means recovery is not complete.\n    if (res.last_released_lsn != LSN_INVALID) {\n      \/\/ Metadata logs don't have their own next_lsns. Using last_released_lsn\n      \/\/ instead.\n      \/\/ TODO(#9523145): If there's a metadata log Appender running for LSN x,\n      \/\/ this will set next_lsn=x instead of x+1. This may cause rebuilding to\n      \/\/ miss record x in this very unlikely situation: the running Appender has\n      \/\/ stored a copy on a node from rebuilding set before the node lost its\n      \/\/ data, then rebuilding got next_lsn=x, then the Appender succeeded\n      \/\/ without sending more waves.\n      next_lsn = res.last_released_lsn + 1;\n    }\n  } else {\n    next_lsn = res.next_lsn;\n  }\n\n  if (res.status == E::OK) {\n    if (!nextLsn_.hasValue() && next_lsn.hasValue()) {\n      nextLsn_ = next_lsn.value();\n    }\n    lastReleased_ = res.last_released_lsn;\n    last_seq_ = res.last_seq;\n    if (res.attributes.hasValue()) {\n      log_tail_attributes_ =\n          std::make_unique<LogTailAttributes>(res.attributes.value());\n    } else {\n      log_tail_attributes_.reset();\n    }\n\n    metadata_map_ = res.metadata_map;\n\n    tail_record_ = res.tail_record;\n  }\n\n  if (shouldComplete()) {\n    complete(E::OK);\n  } else {\n    \/\/ When the timer triggers we will retry GetSeqStateRequest.\n    retry_timer_->activate();\n  }\n}\n\nbool SyncSequencerRequest::gotReleasedUntilLSN() const {\n  if (flags_ & WAIT_RELEASED) {\n    \/\/ Need to keep pinging sequencer until it releases all records that we're\n    \/\/ going to rebuild.\n    return nextLsn_.hasValue() && lastReleased_.hasValue() &&\n        lastReleased_.value() + 1 >= nextLsn_.value();\n  } else {\n    return nextLsn_.hasValue();\n  }\n}\n\nbool SyncSequencerRequest::gotHistoricalMetaData() const {\n  return metadata_map_ != nullptr;\n}\n\nbool SyncSequencerRequest::gotTailRecord() const {\n  return tail_record_ != nullptr;\n}\n\nbool SyncSequencerRequest::shouldComplete() const {\n  return gotReleasedUntilLSN() &&\n      (!(flags_ & INCLUDE_HISTORICAL_METADATA) || gotHistoricalMetaData()) &&\n      (!(flags_ & INCLUDE_TAIL_RECORD) || gotTailRecord());\n}\n\nvoid SyncSequencerRequest::onTimeout() {\n  if (!lastGetSeqStateStatus_.hasValue()) {\n    complete(E::TIMEDOUT);\n    return;\n  }\n\n  Status res = lastGetSeqStateStatus_.value();\n  switch (res) {\n    case E::FAILED:\n    case E::CONNFAILED:\n    case E::NOSEQUENCER:\n      break;\n    case E::UNROUTABLE:\n    case E::PROTONOSUPPORT:\n    case E::DESTINATION_MISMATCH:\n    case E::INVALID_CLUSTER:\n      \/\/ These connection-related errors are reported as CONNFAILED.\n      res = E::CONNFAILED;\n      break;\n    case E::NOTINCONFIG:\n    case E::NOTREADY:\n    case E::REBUILDING:\n      \/\/ If these ever make it to the client, return NOSEQUENCER instead.\n      res = E::NOSEQUENCER;\n      break;\n    case E::OK:\n    default:\n      \/\/ If res==E::OK, it means we timed out waiting for lastReleased_ + 1 >=\n      \/\/ untilLsn_.\n      res = E::TIMEDOUT;\n      break;\n  }\n\n  complete(res);\n}\n\nvoid SyncSequencerRequest::complete(Status status) {\n  ld_check(cb_);\n  ld_check(status != E::INTERNAL);\n  cb_(status,\n      getLastSequencer(),\n      nextLsn_.hasValue() ? nextLsn_.value() : LSN_INVALID,\n      std::move(log_tail_attributes_),\n      std::move(metadata_map_),\n      std::move(tail_record_));\n  delete this;\n}\n\n}} \/\/ namespace facebook::logdevice\n","avg_line_length":29.575,"max_line_length":80,"alphanum_fraction":0.652578191,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3485,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":3.0,"content":"\/\/$Id: dfb_adj2.cpp 2754 2011-01-02 20:57:07Z jsibert $\n#include \"coff_t.h\"\n\nextern ofstream clogf;\n\ntemplate <typename D3_ARRAY, typename MATRIX, typename VECTOR, typename DOUBLE>\nvoid coff_t<D3_ARRAY,MATRIX,VECTOR,DOUBLE>::dfb_adjust(coff_t<D3_ARRAY,MATRIX,VECTOR,DOUBLE>& coff, par_t<D3_ARRAY,MATRIX,VECTOR,DOUBLE>& param, par_t<d3_array,dmatrix,dvector,double>& dfparam, dmatrix& dfz)\n{\n  dmatrix& acoff = coff.get_a();\n  dmatrix& bcoff = coff.get_b();\n  dmatrix& ccoff = coff.get_c();\n  dmatrix& xbet_c = coff.get_xbet();\n  dmatrix& xgam_c = coff.get_xgam();\n\n  dmatrix& dfacoff = get_a();\n  dmatrix& dfraw_bcoff = get_raw_b();\n  dmatrix& dfbcoff = get_b();\n  dmatrix& dfccoff = get_c();\n  dmatrix& dfxbet_c = get_xbet();\n  dmatrix& dfxgam_c = get_xgam();\n\n\tdfb_adjust(\n\tparam,\n\tdfz,\n\tacoff,\n\tbcoff,\n\tccoff,\n\txbet_c,\n\txgam_c,\n\tdfacoff,\n\tdfraw_bcoff,\n\tdfbcoff,\n\tdfccoff,\n\tdfxbet_c,\n\tdfxgam_c);\n}\ntemplate void coff_t<d3_array,dmatrix,dvector,double>::dfb_adjust(coff_t<d3_array,dmatrix,dvector,double>& coff, par_t<d3_array,dmatrix,dvector,double>& param, par_t<d3_array,dmatrix,dvector,double>& dfparam, dmatrix& dfz);\ntemplate<> void coff_t<dvar3_array,dvar_matrix,dvar_vector,dvariable>::dfb_adjust(coff_t<dvar3_array,dvar_matrix,dvar_vector,dvariable>& coff, par_t<dvar3_array,dvar_matrix,dvar_vector,dvariable>& param, par_t<d3_array,dmatrix,dvector,double>& dfparam, dmatrix& dfz) {}\n\ntemplate <typename D3_ARRAY, typename MATRIX, typename VECTOR, typename DOUBLE>\nvoid coff_t<D3_ARRAY,MATRIX,VECTOR,DOUBLE>::dfb_adjust(par_t<D3_ARRAY,MATRIX,VECTOR,DOUBLE>& param, dmatrix& dfz, dmatrix& acoff, dmatrix& bcoff, dmatrix& ccoff, dmatrix& xbet_c, dmatrix& xgam_c, dmatrix& dfacoff, dmatrix& dfraw_bcoff, dmatrix& dfbcoff, dmatrix& dfccoff, dmatrix& dfxbet_c, dmatrix& dfxgam_c)\n{\n  int n     = param.get_n();\n\n  for (int j = n; j >= 1; j--)\n  {\n      int i1 = bcoff(j).indexmin()+1;\n      int i2 = bcoff(j).indexmax();\n      for (int i = i2; i >= i1; i--)\n      {\n          double tmp = bcoff[j][i] - acoff[j][i] * xgam_c[j][i];\n          tmp = -dfxbet_c[j][i]\/(tmp*tmp);\n          dfbcoff(j,i) += tmp;\n          dfacoff(j,i) -= tmp*xgam_c[j][i];\n          dfxgam_c(j,i) -= tmp*acoff[j][i];\n          dfxbet_c(j,i) = 0.0;\n\n          dfccoff(j,i-1) += xbet_c[j][i-1]*dfxgam_c[j][i];\n          dfxbet_c(j,i-1) += ccoff[j][i-1]*dfxgam_c[j][i];\n          dfxgam_c(j,i) = 0.0;\n      }\n      i1--;\n      dfbcoff(j,i1) -= dfxbet_c[j][i1]\/(bcoff[j][i1]*bcoff[j][i1]);\n\n      dfxbet_c(j,i1) = 0.0;\n      dfxgam_c(j,i1) = 0.0;\n  }\n\n  for (int j = n; j >= 1; j--)\n  {\n      int i1 = bcoff(j).indexmin();\n      int i2 = bcoff(j).indexmax();\n      for (int i = i2; i >= i1; i--)\n      {\n          dfraw_bcoff(j,i) += dfbcoff(j,i);\n          dfz(i,j) += dfbcoff(j,i);\n          dfbcoff(j,i) = 0.0;\n      }\n  }\n}\ntemplate void coff_t<d3_array,dmatrix,dvector,double>::dfb_adjust(par_t<d3_array,dmatrix,dvector,double>& param, dmatrix& dfz, dmatrix& acoff, dmatrix& bcoff, dmatrix& ccoff, dmatrix& xbet_c, dmatrix& xgam_c, dmatrix& dfacoff, dmatrix& dfraw_bcoff, dmatrix& dfbcoff, dmatrix& dfccoff, dmatrix& dfxbet_c, dmatrix& dfxgam_c);\ntemplate<> void coff_t<dvar3_array,dvar_matrix,dvar_vector,dvariable>::dfb_adjust(par_t<dvar3_array,dvar_matrix,dvar_vector,dvariable>& param, dmatrix& dfz, dmatrix& acoff, dmatrix& bcoff, dmatrix& ccoff, dmatrix& xbet_c, dmatrix& xgam_c, dmatrix& dfacoff, dmatrix& dfraw_bcoff, dmatrix& dfbcoff, dmatrix& dfccoff, dmatrix& dfxbet_c, dmatrix& dfxgam_c) {}\n","avg_line_length":41.9879518072,"max_line_length":355,"alphanum_fraction":0.6694404591,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11117,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":109.0,"content":"\/*\n * Copyright (C) 2020 Open Source Robotics Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*\/\n\n#include <rmf_utils\/math.hpp>\n\n#include \"DifferentialDriveMap.hpp\"\n\n#include \"..\/internal_Interpolate.hpp\"\n\nnamespace rmf_traffic {\nnamespace agv {\nnamespace planning {\n\n\/\/==============================================================================\nDifferentialDriveMapTypes::RouteInfo::RouteInfo(\n  rmf_traffic::Time finish_time_,\n  double finish_yaw_,\n  std::vector<Route> routes_)\n: finish_time(finish_time_),\n  finish_yaw(finish_yaw_),\n  routes(std::move(routes_))\n{\n  \/\/ Do nothing\n}\n\n\/\/==============================================================================\nFactoryInfo make_differential_drive_translate_factory(\n    Eigen::Vector3d start,\n    Eigen::Vector3d finish,\n    KinematicLimits limits,\n    double translation_thresh,\n    double rotation_thresh,\n    std::vector<std::string> maps)\n{\n  const auto dummy_start_time = rmf_traffic::Time(rmf_traffic::Duration(0));\n  Trajectory trajectory;\n  trajectory.insert(dummy_start_time, start, Eigen::Vector3d::Zero());\n  internal::interpolate_translation(\n        trajectory, limits.linear.velocity, limits.linear.acceleration,\n        dummy_start_time, start, finish, translation_thresh);\n\n  const double minimal_cost =\n      rmf_traffic::time::to_seconds(trajectory.duration());\n\n  auto factory =\n      [start,\n       finish,\n       limits,\n       translation_thresh,\n       rotation_thresh,\n       maps = std::move(maps)](\n      rmf_traffic::Time start_time,\n      double initial_yaw)\n      -> DifferentialDriveMapTypes::RouteInfo\n  {\n    Trajectory trajectory;\n    const Eigen::Vector3d pre_start{start.x(), start.y(), initial_yaw};\n    trajectory.insert(start_time, pre_start, Eigen::Vector3d::Zero());\n\n    internal::interpolate_rotation(\n          trajectory, limits.angular.velocity, limits.angular.acceleration,\n          start_time, pre_start, start, rotation_thresh);\n\n    internal::interpolate_translation(\n          trajectory, limits.linear.velocity, limits.linear.acceleration,\n          trajectory.back().time(), start, finish, translation_thresh);\n\n    std::vector<Route> routes;\n    routes.reserve(maps.size());\n    for (const auto& map : maps)\n      routes.push_back({map, trajectory});\n\n    return {*trajectory.finish_time(), finish[2], routes};\n  };\n\n  auto factory_factory = [factory = std::move(factory)](\n      std::optional<double>)\n      -> DifferentialDriveMapTypes::RouteFactory\n  {\n    return [factory](\n        const rmf_traffic::Time start_time,\n        const double initial_yaw) -> DifferentialDriveMapTypes::RouteInfo\n    {\n      return factory(start_time, initial_yaw);\n    };\n  };\n\n  return {minimal_cost, std::move(factory_factory)};\n}\n\n\/\/==============================================================================\nstd::optional<FactoryInfo> make_rotate_factory(\n    Eigen::Vector2d position,\n    std::optional<double> start_yaw,\n    std::optional<double> finish_yaw,\n    KinematicLimits limits,\n    double rotation_thresh,\n    std::string map)\n{\n  double minimum_cost = 0.0;\n  if (start_yaw.has_value() && finish_yaw.has_value())\n  {\n    const double yaw_dist =\n        std::abs(rmf_utils::wrap_to_pi(*start_yaw - *finish_yaw));\n\n    \/\/ If both yaws are known and they are within the rotation threshold of each\n    \/\/ other, then no rotation will be needed.\n    if (yaw_dist <= rotation_thresh)\n      return std::nullopt;\n\n    \/\/ If both yaws are known and a rotation is needed, then let's calculate the\n    \/\/ time required for it.\n    const auto dummy_start_time = rmf_traffic::Time(rmf_traffic::Duration(0));\n    Trajectory trajectory;\n\n    const Eigen::Vector3d start_p{position.x(), position.y(), *start_yaw};\n    trajectory.insert(dummy_start_time, start_p, Eigen::Vector3d::Zero());\n\n    const Eigen::Vector3d finish_p{position.x(), position.y(), *finish_yaw};\n    internal::interpolate_rotation(\n          trajectory, limits.angular.velocity, limits.angular.acceleration,\n          dummy_start_time, start_p, finish_p, rotation_thresh);\n\n    minimum_cost = rmf_traffic::time::to_seconds(trajectory.duration());\n  }\n\n  auto factory =\n      [p = position,\n       finish_yaw,\n       limits = limits.angular,\n       rotation_thresh,\n       map = std::move(map)](\n      rmf_traffic::Time start_time,\n      double initial_yaw,\n      std::optional<double> child_yaw)\n      -> DifferentialDriveMapTypes::RouteInfo\n  {\n    Trajectory trajectory;\n    const Eigen::Vector3d start_p = {p.x(), p.y(), initial_yaw};\n    trajectory.insert(start_time, start_p, Eigen::Vector3d::Zero());\n\n    if (finish_yaw.has_value())\n    {\n      const Eigen::Vector3d finish_p = {p.x(), p.y(), *finish_yaw};\n      internal::interpolate_rotation(\n            trajectory, limits.velocity, limits.acceleration, start_time,\n            start_p, finish_p, rotation_thresh);\n    }\n    else if (child_yaw.has_value())\n    {\n      const Eigen::Vector3d finish_p = {p.x(), p.y(), *child_yaw};\n      internal::interpolate_rotation(\n            trajectory, limits.velocity, limits.acceleration, start_time,\n            start_p, finish_p, rotation_thresh);\n    }\n\n    const auto finish_time = *trajectory.finish_time();\n    const auto finish_yaw = trajectory.back().position()[2];\n    return {finish_time, finish_yaw, {{map, std::move(trajectory)}}};\n  };\n\n  auto factory_factory = [factory = std::move(factory)](\n      std::optional<double> child_yaw)\n      -> DifferentialDriveMapTypes::RouteFactory\n  {\n    return [factory, child_yaw](\n        const rmf_traffic::Time start_time,\n        const double initial_yaw) -> DifferentialDriveMapTypes::RouteInfo\n    {\n      return factory(start_time, initial_yaw, child_yaw);\n    };\n  };\n\n  return std::optional<FactoryInfo>({minimum_cost, std::move(factory_factory)});\n}\n\n\/\/==============================================================================\nDifferentialDriveMapTypes::RouteFactoryFactory\nmake_hold_factory(\n    Eigen::Vector2d position,\n    std::optional<double> yaw_opt,\n    rmf_traffic::Duration duration,\n    KinematicLimits limits,\n    double rotation_thresh,\n    std::vector<std::string> maps)\n{\n  auto factory =\n      [p = position,\n       yaw_opt,\n       duration,\n       limits = limits.angular,\n       rotation_thresh,\n       maps = std::move(maps)](\n      rmf_traffic::Time start_time,\n      double initial_yaw,\n      std::optional<double> child_yaw)\n      -> DifferentialDriveMapTypes::RouteInfo\n  {\n    rmf_traffic::Trajectory trajectory;\n    const Eigen::Vector3d start_position{p.x(), p.y(), initial_yaw};\n    trajectory.insert(start_time, start_position, Eigen::Vector3d::Zero());\n\n    Eigen::Vector3d yawed_position = start_position;\n    if (yaw_opt.has_value())\n    {\n      yawed_position = {p.x(), p.y(), *yaw_opt};\n      internal::interpolate_rotation(\n            trajectory, limits.velocity, limits.acceleration,\n            trajectory.back().time(), start_position, yawed_position,\n            rotation_thresh);\n    }\n    else if (child_yaw.has_value())\n    {\n      yawed_position = {p.x(), p.y(), *child_yaw};\n      internal::interpolate_rotation(\n            trajectory, limits.velocity, limits.acceleration,\n            trajectory.back().time(), yawed_position, yawed_position,\n            rotation_thresh);\n    }\n\n    const auto desired_finish_time = start_time + duration;\n    const auto remaining_duration =\n        desired_finish_time - *trajectory.finish_time();\n\n    if (remaining_duration > std::chrono::nanoseconds(0))\n    {\n      trajectory.insert(\n        desired_finish_time,\n        yawed_position,\n        Eigen::Vector3d::Zero());\n    }\n\n    std::vector<Route> routes;\n    routes.reserve(maps.size());\n    for (const auto& map : maps)\n      routes.push_back({map, trajectory});\n\n    const auto finish_time = *trajectory.finish_time();\n    const auto finish_yaw = trajectory.back().position()[2];\n    return {finish_time, finish_yaw, std::move(routes)};\n  };\n\n  return [factory = std::move(factory)](std::optional<double> child_yaw)\n      -> DifferentialDriveMapTypes::RouteFactory\n  {\n    return [factory, child_yaw](\n        rmf_traffic::Time start_time,\n        double initial_yaw) -> DifferentialDriveMapTypes::RouteInfo\n    {\n      return factory(start_time, initial_yaw, child_yaw);\n    };\n  };\n}\n\n\/\/==============================================================================\nDifferentialDriveMapTypes::RouteFactoryFactory\nmake_start_factory(\n  Eigen::Vector2d position,\n  std::optional<double> target_yaw,\n  KinematicLimits limits,\n  double rotation_thresh,\n  std::vector<std::string> maps)\n{\n  auto factory =\n      [p = position,\n       target_yaw,\n       maps = std::move(maps),\n       limits = limits.angular,\n       rotation_thresh](\n      Time start_time,\n      double initial_yaw,\n      std::optional<double> child_yaw)\n      -> DifferentialDriveMapTypes::RouteInfo\n  {\n    Trajectory trajectory;\n    const Eigen::Vector3d start_p = {p.x(), p.y(), initial_yaw};\n    trajectory.insert(start_time, start_p, Eigen::Vector3d::Zero());\n\n    if (target_yaw.has_value())\n    {\n      const Eigen::Vector3d finish_p = {p.x(), p.y(), *target_yaw};\n      internal::interpolate_rotation(\n        trajectory, limits.velocity, limits.acceleration,\n        start_time, start_p, finish_p, rotation_thresh);\n    }\n    else if (child_yaw.has_value())\n    {\n      const Eigen::Vector3d finish_p = {p.x(), p.y(), *child_yaw};\n      internal::interpolate_rotation(\n        trajectory, limits.velocity, limits.acceleration,\n        start_time, start_p, finish_p, rotation_thresh);\n    }\n\n    std::vector<Route> routes;\n    routes.reserve(maps.size());\n    for (const auto& map : maps)\n      routes.push_back({map, trajectory});\n\n    const auto finish_time = *trajectory.finish_time();\n    const auto finish_yaw = trajectory.back().position()[2];\n    return {finish_time, finish_yaw, std::move(routes)};\n  };\n\n  return [factory = std::move(factory)](\n      std::optional<double> child_yaw)\n      -> DifferentialDriveMapTypes::RouteFactory\n  {\n    return [factory, child_yaw](\n        const rmf_traffic::Time start_time,\n        const double initial_yaw) -> DifferentialDriveMapTypes::RouteInfo\n    {\n      return factory(start_time, initial_yaw, child_yaw);\n    };\n  };\n}\n\n\/\/==============================================================================\nDifferentialDriveMapTypes::RouteFactoryFactory\nmake_recycling_factory(DifferentialDriveMapTypes::RouteFactory old_factory)\n{\n  return [old_factory = std::move(old_factory)](auto)\n  {\n    return old_factory;\n  };\n}\n\n} \/\/ namespace planning\n} \/\/ namespace agv\n} \/\/ namespace rmf_traffic\n","avg_line_length":32.3168604651,"max_line_length":80,"alphanum_fraction":0.6523342628,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11158,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <map>\n#include <string>\n#include <boost\/test\/unit_test.hpp>\n#include \"json\/json_spirit_writer_template.h\"\n\n#include \"main.h\"\n#include \"wallet.h\"\n\nusing namespace std;\nusing namespace json_spirit;\n\n\/\/ In script_tests.cpp\nextern Array read_json(const std::string& filename);\nextern CScript ParseScript(string s);\n\nBOOST_AUTO_TEST_SUITE(transaction_tests)\n\nBOOST_AUTO_TEST_CASE(tx_valid)\n{\n    \/\/ Read tests from test\/data\/tx_valid.json\n    \/\/ Format is an array of arrays\n    \/\/ Inner arrays are either [ \"comment\" ]\n    \/\/ or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...],\"], serializedTransaction, enforceP2SH\n    \/\/ ... where all scripts are stringified scripts.\n    Array tests = read_json(\"tx_valid.json\");\n\n    BOOST_FOREACH(Value& tv, tests)\n    {\n        Array test = tv.get_array();\n        string strTest = write_string(tv, false);\n        if (test[0].type() == array_type)\n        {\n            if (test.size() != 3 || test[1].type() != str_type || test[2].type() != bool_type)\n            {\n                BOOST_ERROR(\"Bad test: \" << strTest);\n                continue;\n            }\n\n            map<COutPoint, CScript> mapprevOutScriptPubKeys;\n            Array inputs = test[0].get_array();\n            bool fValid = true;\n            BOOST_FOREACH(Value& input, inputs)\n            {\n                if (input.type() != array_type)\n                {\n                    fValid = false;\n                    break;\n                }\n                Array vinput = input.get_array();\n                if (vinput.size() != 3)\n                {\n                    fValid = false;\n                    break;\n                }\n\n                mapprevOutScriptPubKeys[COutPoint(uint256(vinput[0].get_str()), vinput[1].get_int())] = ParseScript(vinput[2].get_str());\n            }\n            if (!fValid)\n            {\n                BOOST_ERROR(\"Bad test: \" << strTest);\n                continue;\n            }\n\n            string transaction = test[1].get_str();\n            CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION);\n            CTransaction tx;\n            stream >> tx;\n\n            CValidationState state;\n            BOOST_CHECK_MESSAGE(tx.CheckTransaction(state), strTest);\n            BOOST_CHECK(state.IsValid());\n\n            for (unsigned int i = 0; i < tx.vin.size(); i++)\n            {\n                if (!mapprevOutScriptPubKeys.count(tx.vin[i].prevout))\n                {\n                    BOOST_ERROR(\"Bad test: \" << strTest);\n                    break;\n                }\n\n                BOOST_CHECK_MESSAGE(VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout], tx, i, test[2].get_bool() ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE, 0), strTest);\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(tx_invalid)\n{\n    \/\/ Read tests from test\/data\/tx_invalid.json\n    \/\/ Format is an array of arrays\n    \/\/ Inner arrays are either [ \"comment\" ]\n    \/\/ or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...],\"], serializedTransaction, enforceP2SH\n    \/\/ ... where all scripts are stringified scripts.\n    Array tests = read_json(\"tx_invalid.json\");\n\n    BOOST_FOREACH(Value& tv, tests)\n    {\n        Array test = tv.get_array();\n        string strTest = write_string(tv, false);\n        if (test[0].type() == array_type)\n        {\n            if (test.size() != 3 || test[1].type() != str_type || test[2].type() != bool_type)\n            {\n                BOOST_ERROR(\"Bad test: \" << strTest);\n                continue;\n            }\n\n            map<COutPoint, CScript> mapprevOutScriptPubKeys;\n            Array inputs = test[0].get_array();\n            bool fValid = true;\n            BOOST_FOREACH(Value& input, inputs)\n            {\n                if (input.type() != array_type)\n                {\n                    fValid = false;\n                    break;\n                }\n                Array vinput = input.get_array();\n                if (vinput.size() != 3)\n                {\n                    fValid = false;\n                    break;\n                }\n\n                mapprevOutScriptPubKeys[COutPoint(uint256(vinput[0].get_str()), vinput[1].get_int())] = ParseScript(vinput[2].get_str());\n            }\n            if (!fValid)\n            {\n                BOOST_ERROR(\"Bad test: \" << strTest);\n                continue;\n            }\n\n            string transaction = test[1].get_str();\n            CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION);\n            CTransaction tx;\n            stream >> tx;\n\n            CValidationState state;\n            fValid = tx.CheckTransaction(state) && state.IsValid();\n\n            for (unsigned int i = 0; i < tx.vin.size() && fValid; i++)\n            {\n                if (!mapprevOutScriptPubKeys.count(tx.vin[i].prevout))\n                {\n                    BOOST_ERROR(\"Bad test: \" << strTest);\n                    break;\n                }\n\n                fValid = VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout], tx, i, test[2].get_bool() ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE, 0);\n            }\n\n            BOOST_CHECK_MESSAGE(!fValid, strTest);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(basic_transaction_tests)\n{\n    \/\/ Random real transaction (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436)\n    unsigned char ch[] = {0x01, 0x00, 0x00, 0x00, 0x01, 0x6b, 0xff, 0x7f, 0xcd, 0x4f, 0x85, 0x65, 0xef, 0x40, 0x6d, 0xd5, 0xd6, 0x3d, 0x4f, 0xf9, 0x4f, 0x31, 0x8f, 0xe8, 0x20, 0x27, 0xfd, 0x4d, 0xc4, 0x51, 0xb0, 0x44, 0x74, 0x01, 0x9f, 0x74, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xda, 0x0d, 0xc6, 0xae, 0xce, 0xfe, 0x1e, 0x06, 0xef, 0xdf, 0x05, 0x77, 0x37, 0x57, 0xde, 0xb1, 0x68, 0x82, 0x09, 0x30, 0xe3, 0xb0, 0xd0, 0x3f, 0x46, 0xf5, 0xfc, 0xf1, 0x50, 0xbf, 0x99, 0x0c, 0x02, 0x21, 0x00, 0xd2, 0x5b, 0x5c, 0x87, 0x04, 0x00, 0x76, 0xe4, 0xf2, 0x53, 0xf8, 0x26, 0x2e, 0x76, 0x3e, 0x2d, 0xd5, 0x1e, 0x7f, 0xf0, 0xbe, 0x15, 0x77, 0x27, 0xc4, 0xbc, 0x42, 0x80, 0x7f, 0x17, 0xbd, 0x39, 0x01, 0x41, 0x04, 0xe6, 0xc2, 0x6e, 0xf6, 0x7d, 0xc6, 0x10, 0xd2, 0xcd, 0x19, 0x24, 0x84, 0x78, 0x9a, 0x6c, 0xf9, 0xae, 0xa9, 0x93, 0x0b, 0x94, 0x4b, 0x7e, 0x2d, 0xb5, 0x34, 0x2b, 0x9d, 0x9e, 0x5b, 0x9f, 0xf7, 0x9a, 0xff, 0x9a, 0x2e, 0xe1, 0x97, 0x8d, 0xd7, 0xfd, 0x01, 0xdf, 0xc5, 0x22, 0xee, 0x02, 0x28, 0x3d, 0x3b, 0x06, 0xa9, 0xd0, 0x3a, 0xcf, 0x80, 0x96, 0x96, 0x8d, 0x7d, 0xbb, 0x0f, 0x91, 0x78, 0xff, 0xff, 0xff, 0xff, 0x02, 0x8b, 0xa7, 0x94, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xba, 0xde, 0xec, 0xfd, 0xef, 0x05, 0x07, 0x24, 0x7f, 0xc8, 0xf7, 0x42, 0x41, 0xd7, 0x3b, 0xc0, 0x39, 0x97, 0x2d, 0x7b, 0x88, 0xac, 0x40, 0x94, 0xa8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xc1, 0x09, 0x32, 0x48, 0x3f, 0xec, 0x93, 0xed, 0x51, 0xf5, 0xfe, 0x95, 0xe7, 0x25, 0x59, 0xf2, 0xcc, 0x70, 0x43, 0xf9, 0x88, 0xac, 0x00, 0x00, 0x00, 0x00, 0x00};\n    vector<unsigned char> vch(ch, ch + sizeof(ch) -1);\n    CDataStream stream(vch, SER_DISK, CLIENT_VERSION);\n    CTransaction tx;\n    stream >> tx;\n    CValidationState state;\n    BOOST_CHECK_MESSAGE(tx.CheckTransaction(state) && state.IsValid(), \"Simple deserialized transaction should be valid.\");\n\n    \/\/ Check that duplicate txins fail\n    tx.vin.push_back(tx.vin[0]);\n    BOOST_CHECK_MESSAGE(!tx.CheckTransaction(state) || !state.IsValid(), \"Transaction with duplicate txins should be invalid.\");\n}\n\n\/\/\n\/\/ Helper: create two dummy transactions, each with\n\/\/ two outputs.  The first has 11 and 50 CENT outputs\n\/\/ paid to a TX_PUBKEY, the second 21 and 22 CENT outputs\n\/\/ paid to a TX_PUBKEYHASH.\n\/\/\nstatic std::vector<CTransaction>\nSetupDummyInputs(CBasicKeyStore& keystoreRet, CCoinsView & coinsRet)\n{\n    std::vector<CTransaction> dummyTransactions;\n    dummyTransactions.resize(2);\n\n    \/\/ Add some keys to the keystore:\n    CKey key[4];\n    for (int i = 0; i < 4; i++)\n    {\n        key[i].MakeNewKey(i % 2);\n        keystoreRet.AddKey(key[i]);\n    }\n\n    \/\/ Create some dummy input transactions\n    dummyTransactions[0].vout.resize(2);\n    dummyTransactions[0].vout[0].nValue = 11*CENT;\n    dummyTransactions[0].vout[0].scriptPubKey << key[0].GetPubKey() << OP_CHECKSIG;\n    dummyTransactions[0].vout[1].nValue = 50*CENT;\n    dummyTransactions[0].vout[1].scriptPubKey << key[1].GetPubKey() << OP_CHECKSIG;\n    coinsRet.SetCoins(dummyTransactions[0].GetHash(), CCoins(dummyTransactions[0], 0));\n\n    dummyTransactions[1].vout.resize(2);\n    dummyTransactions[1].vout[0].nValue = 21*CENT;\n    dummyTransactions[1].vout[0].scriptPubKey.SetDestination(key[2].GetPubKey().GetID());\n    dummyTransactions[1].vout[1].nValue = 22*CENT;\n    dummyTransactions[1].vout[1].scriptPubKey.SetDestination(key[3].GetPubKey().GetID());\n    coinsRet.SetCoins(dummyTransactions[1].GetHash(), CCoins(dummyTransactions[1], 0));\n\n    return dummyTransactions;\n}\n\nBOOST_AUTO_TEST_CASE(test_Get)\n{\n    CBasicKeyStore keystore;\n    CCoinsView coinsDummy;\n    CCoinsViewCache coins(coinsDummy);\n    std::vector<CTransaction> dummyTransactions = SetupDummyInputs(keystore, coins);\n\n    CTransaction t1;\n    t1.vin.resize(3);\n    t1.vin[0].prevout.hash = dummyTransactions[0].GetHash();\n    t1.vin[0].prevout.n = 1;\n    t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0);\n    t1.vin[1].prevout.hash = dummyTransactions[1].GetHash();\n    t1.vin[1].prevout.n = 0;\n    t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);\n    t1.vin[2].prevout.hash = dummyTransactions[1].GetHash();\n    t1.vin[2].prevout.n = 1;\n    t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);\n    t1.vout.resize(2);\n    t1.vout[0].nValue = 90*CENT;\n    t1.vout[0].scriptPubKey << OP_1;\n\n    BOOST_CHECK(t1.AreInputsStandard(coins));\n    BOOST_CHECK_EQUAL(t1.GetValueIn(coins), (50+21+22)*CENT);\n\n    \/\/ Adding extra junk to the scriptSig should make it non-standard:\n    t1.vin[0].scriptSig << OP_11;\n    BOOST_CHECK(!t1.AreInputsStandard(coins));\n\n    \/\/ ... as should not having enough:\n    t1.vin[0].scriptSig = CScript();\n    BOOST_CHECK(!t1.AreInputsStandard(coins));\n}\n\nBOOST_AUTO_TEST_CASE(test_IsStandard)\n{\n    CBasicKeyStore keystore;\n    CCoinsView coinsDummy;\n    CCoinsViewCache coins(coinsDummy);\n    std::vector<CTransaction> dummyTransactions = SetupDummyInputs(keystore, coins);\n\n    CTransaction t;\n    t.vin.resize(1);\n    t.vin[0].prevout.hash = dummyTransactions[0].GetHash();\n    t.vin[0].prevout.n = 1;\n    t.vin[0].scriptSig << std::vector<unsigned char>(65, 0);\n    t.vout.resize(1);\n    t.vout[0].nValue = 90*CENT;\n    CKey key;\n    key.MakeNewKey(true);\n    t.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID());\n\n    BOOST_CHECK(t.IsStandard());\n\n    t.vout[0].nValue = 5011; \/\/ dust\n    \/\/ Hectorcoin does not enforce isDust().  Per dust fees are considered sufficient as deterrant.\n    \/\/ BOOST_CHECK(!t.IsStandard());\n\n    t.vout[0].nValue = 6011; \/\/ not dust\n    BOOST_CHECK(t.IsStandard());\n\n    t.vout[0].scriptPubKey = CScript() << OP_1;\n    BOOST_CHECK(!t.IsStandard());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":40.2815884477,"max_line_length":1586,"alphanum_fraction":0.6069188027,"low_alphanum":false,"long_lines":true,"lexable":true}
{"size":51934,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/*\n * Copyright (c) 2021 dresden elektronik ingenieurtechnik gmbh.\n * All rights reserved.\n *\n * The software in this package is published under the terms of the BSD\n * style license a copy of which has been included with this distribution in\n * the LICENSE.txt file.\n *\n *\/\n\n#include <QDirIterator>\n#include <QFile>\n#include <QJsonArray>\n#include <QJsonDocument>\n#include <QJsonObject>\n#include <QJsonValue>\n#include <QSettings>\n#include <deconz\/dbg_trace.h>\n#include \"device_ddf_init.h\"\n#include \"device_descriptions.h\"\n#include \"event.h\"\n#include \"resource.h\"\n\n#define HND_MIN_LOAD_COUNTER 1\n#define HND_MAX_LOAD_COUNTER 15\n#define HND_MAX_DESCRIPTIONS 16383\n#define HND_MAX_ITEMS        1023\n#define HND_MAX_SUB_DEVS     15\n\n\/*! \\union ItemHandlePack\n\n    Packs location to an DDF item into a opaque 32-bit unsigned int handle.\n    The DDF item lookup complexity is O(1) via DDF_GetItem() function.\n *\/\nunion ItemHandlePack\n{\n    \/\/ 32-bit memory layout\n    \/\/ llll dddd dddd dddd ddss ssii iiii iiii\n    struct {\n        \/\/! Max: 15, check for valid handle, for each DDF reload the counter is incremented (wraps to 0).\n        unsigned int loadCounter : 4;\n        unsigned int description : 14; \/\/! Max: 16383, index into descriptions[].\n        unsigned int subDevice: 4;     \/\/! Max: 15, index into description -> subdevices[]\n        unsigned int item : 10;        \/\/! Max: 1023, index into subdevice -> items[]\n    };\n    quint32 handle;\n};\n\nstatic DeviceDescriptions *_instance = nullptr;\nstatic DeviceDescriptionsPrivate *_priv = nullptr;\n\nclass DeviceDescriptionsPrivate\n{\npublic:\n    uint loadCounter = HND_MIN_LOAD_COUNTER;\n    std::map<QString,QString> constants;\n    std::vector<DeviceDescription::Item> genericItems;\n    std::vector<DeviceDescription> descriptions;\n\n    DeviceDescription invalidDescription;\n    DeviceDescription::Item invalidItem;\n\n    QStringList enabledStatusFilter;\n\n    std::vector<DDF_SubDeviceDescriptor> subDevices;\n\n    std::vector<DDF_FunctionDescriptor> readFunctions;\n    std::vector<DDF_FunctionDescriptor> writeFunctions;\n    std::vector<DDF_FunctionDescriptor> parseFunctions;\n};\n\nstatic bool DDF_ReadConstantsJson(const QString &path, std::map<QString,QString> *constants);\nstatic DeviceDescription::Item DDF_ReadItemFile(const QString &path);\nstatic std::vector<DeviceDescription> DDF_ReadDeviceFile(const QString &path);\nstatic DDF_SubDeviceDescriptor DDF_ReadSubDeviceFile(const QString &path);\nstatic DeviceDescription DDF_MergeGenericItems(const std::vector<DeviceDescription::Item> &genericItems, const DeviceDescription &ddf);\nstatic DeviceDescription::Item *DDF_GetItemMutable(const ResourceItem *item);\nstatic void DDF_UpdateItemHandles(std::vector<DeviceDescription> &descriptions, uint loadCounter);\nDeviceDescription DDF_LoadScripts(const DeviceDescription &ddf);\n\n\/*! Constructor. *\/\nDeviceDescriptions::DeviceDescriptions(QObject *parent) :\n    QObject(parent),\n    d_ptr2(new DeviceDescriptionsPrivate)\n{\n    _instance = this;\n    _priv = d_ptr2;\n\n    d_ptr2->enabledStatusFilter;\n\n    {  \/\/ Parse function as shown in the DDF editor.\n        DDF_FunctionDescriptor fn;\n        fn.name = \"zcl\";\n        fn.description = \"Generic function to parse ZCL attributes and commands.\";\n\n        DDF_FunctionDescriptor::Parameter param;\n\n        param.name = \"Endpoint\";\n        param.key = \"ep\";\n        param.description = \"255 means any endpoint, 0 means auto selected from subdevice.\";\n        param.dataType = DataTypeUInt8;\n        param.defaultValue = 0;\n        param.isOptional = 1;\n        param.isHexString = 0;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        param.name = \"Cluster ID\";\n        param.key = \"cl\";\n        param.description = \"As string hex value\";\n        param.dataType = DataTypeUInt16;\n        param.defaultValue = 0;\n        param.isOptional = 0;\n        param.isHexString = 1;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        param.name = \"Attribute ID\";\n        param.key = \"at\";\n        param.description = \"As string hex value\";\n        param.dataType = DataTypeUInt16;\n        param.defaultValue = 0;\n        param.isOptional = 0;\n        param.isHexString = 1;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        param.name = \"Manufacturer code\";\n        param.key = \"mf\";\n        param.description = \"As string hex value.\";\n        param.dataType = DataTypeUInt16;\n        param.defaultValue = 0;\n        param.isOptional = 1;\n        param.isHexString = 1;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        param.name = \"Javascript file\";\n        param.key = \"script\";\n        param.description = \"Relative path of a Javascript .js file.\";\n        param.dataType = DataTypeString;\n        param.defaultValue = {};\n        param.isOptional = 1;\n        param.isHexString = 0;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        param.name = \"Expression\";\n        param.key = \"eval\";\n        param.description = \"Javascript expression to transform the raw value.\";\n        param.dataType = DataTypeString;\n        param.defaultValue = QLatin1String(\"Item.val = Attr.val\");\n        param.isOptional = 1;\n        param.isHexString = 0;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        d_ptr2->parseFunctions.push_back(fn);\n    }\n\n    {  \/\/ Read function as shown in the DDF editor.\n        DDF_FunctionDescriptor fn;\n        fn.name = \"zcl\";\n        fn.description = \"Generic function to read ZCL attributes.\";\n\n        DDF_FunctionDescriptor::Parameter param;\n\n        param.name = \"Endpoint\";\n        param.key = \"ep\";\n        param.description = \"255 means any endpoint, 0 means auto selected from subdevice.\";\n        param.dataType = DataTypeUInt8;\n        param.defaultValue = 255;\n        param.isOptional = 0;\n        param.isHexString = 0;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        param.name = \"Cluster ID\";\n        param.key = \"cl\";\n        param.description = \"As string hex value\";\n        param.dataType = DataTypeUInt16;\n        param.defaultValue = 0;\n        param.isOptional = 0;\n        param.isHexString = 1;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        param.name = \"Attribute ID\";\n        param.key = \"at\";\n        param.description = \"As string hex value\";\n        param.dataType = DataTypeUInt16;\n        param.defaultValue = 0;\n        param.isOptional = 0;\n        param.isHexString = 1;\n        param.supportsArray = 1;\n        fn.parameters.push_back(param);\n\n        param.name = \"Manufacturer code\";\n        param.key = \"mf\";\n        param.description = \"As string hex value.\";\n        param.dataType = DataTypeUInt16;\n        param.defaultValue = 0;\n        param.isOptional = 1;\n        param.isHexString = 1;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        d_ptr2->readFunctions.push_back(fn);\n    }\n\n    {\n        DDF_FunctionDescriptor fn;\n        fn.name = \"ias:zonestatus\";\n        fn.description = \"Generic function to parse IAS ZONE status change notifications or zone status from read\/report command.\";\n\n        DDF_FunctionDescriptor::Parameter param;\n\n        param.name = \"IAS Zone status mask\";\n        param.key = \"mask\";\n        param.description = \"Sets the bitmask for Alert1 and Alert2 item of the IAS Zone status.\";\n        param.dataType = DataTypeString;\n        param.defaultValue = QLatin1String(\"alarm1,alarm2\");\n        param.isOptional = 1;\n        param.isHexString = 0;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        d_ptr2->parseFunctions.push_back(fn);\n    }\n\n    {\n        DDF_FunctionDescriptor fn;\n        fn.name = \"numtostr\";\n        fn.description = \"Generic function to to convert number to string.\";\n\n        DDF_FunctionDescriptor::Parameter param;\n\n        param.name = \"Source item\";\n        param.key = \"srcitem\";\n        param.description = \"The source item holding the number.\";\n        param.dataType = DataTypeString;\n        param.defaultValue = 0;\n        param.isOptional = 0;\n        param.isHexString = 0;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        param.name = \"Operator\";\n        param.key = \"op\";\n        param.description = \"Comparison operator (lt | le | eq | gt | ge)\";\n        param.dataType = DataTypeString;\n        param.defaultValue = 0;\n        param.isOptional = 0;\n        param.isHexString = 0;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        param.name = \"Mapping\";\n        param.key = \"to\";\n        param.description = \"Array of (num, string) mappings\";\n        param.dataType = DataTypeString;\n        param.defaultValue = 0;\n        param.isOptional = 0;\n        param.isHexString = 0;\n        param.supportsArray = 1;\n        fn.parameters.push_back(param);\n\n        d_ptr2->parseFunctions.push_back(fn);\n    }\n\n    {\n        DDF_FunctionDescriptor fn;\n        fn.name = \"xiaomi:special\";\n        fn.description = \"Generic function to parse custom Xiaomi attributes and commands.\";\n\n        DDF_FunctionDescriptor::Parameter param;\n\n        param.name = \"Endpoint\";\n        param.key = \"ep\";\n        param.description = \"Source endpoint of the incoming command, default value 255 means any endpoint.\";\n        param.dataType = DataTypeUInt8;\n        param.defaultValue = 255;\n        param.isOptional = 1;\n        param.isHexString = 0;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        param.name = \"Attribute ID\";\n        param.key = \"at\";\n        param.description = \"The attribute to parse, shall be 0xff01, 0xff02 or 0x00f7\";\n        param.dataType = DataTypeUInt16;\n        param.defaultValue = 0;\n        param.isOptional = 0;\n        param.isHexString = 1;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        param.name = \"Index\";\n        param.key = \"idx\";\n        param.description = \"A 8-bit string hex value.\";\n        param.dataType = DataTypeUInt8;\n        param.defaultValue = 0;\n        param.isOptional = 0;\n        param.isHexString = 1;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        param.name = \"Expression\";\n        param.key = \"eval\";\n        param.description = \"Javascript expression to transform the raw value.\";\n        param.dataType = DataTypeString;\n        param.defaultValue = {};\n        param.isOptional = 0;\n        param.isHexString = 0;\n        param.supportsArray = 0;\n        fn.parameters.push_back(param);\n\n        d_ptr2->parseFunctions.push_back(fn);\n    }\n}\n\n\/*! Destructor. *\/\nDeviceDescriptions::~DeviceDescriptions()\n{\n    Q_ASSERT(_instance == this);\n    _instance = nullptr;\n    _priv = nullptr;\n    Q_ASSERT(d_ptr2);\n    delete d_ptr2;\n    d_ptr2 = nullptr;\n}\n\nvoid DeviceDescriptions::setEnabledStatusFilter(const QStringList &filter)\n{\n    d_ptr2->enabledStatusFilter = filter;\n}\n\nconst QStringList &DeviceDescriptions::enabledStatusFilter() const\n{\n    return d_ptr2->enabledStatusFilter;\n}\n\n\/*! Returns the DeviceDescriptions singleton instance.\n *\/\nDeviceDescriptions *DeviceDescriptions::instance()\n{\n    Q_ASSERT(_instance);\n    return _instance;\n}\n\n\/*! Helper to transform hard C++ coded parse functions to DDF.\n *\/\nvoid DDF_AnnoteZclParse1(int line, const char *file, const Resource *resource, ResourceItem *item, quint8 ep, quint16 clusterId, quint16 attributeId, const char *eval)\n{\n    DBG_Assert(resource);\n    DBG_Assert(item);\n    DBG_Assert(eval);\n\n    if (!_instance || !resource || !item || !eval)\n    {\n        return;\n    }\n\n    if (item->ddfItemHandle() == DeviceDescription::Item::InvalidItemHandle)\n    {\n        const Device *device = nullptr;\n        if (resource->parentResource())\n        {\n            device = static_cast<const Device*>(resource->parentResource());\n        }\n\n        if (!device)\n        {\n            return;\n        }\n\n        const auto *uniqueId = resource->item(RAttrUniqueId);\n        if (!uniqueId)\n        {\n            return;\n        }\n\n        auto &ddf = _instance->get(device);\n        if (!ddf.isValid())\n        {\n            return;\n        }\n\n        \/\/ this is pretty heavy but will be removed later\n        const QStringList u = uniqueId->toString().split(QLatin1Char('-'), SKIP_EMPTY_PARTS);\n\n        for (const auto &sub : ddf.subDevices)\n        {\n            if (u.size() != sub.uniqueId.size())\n            {\n                continue;\n            }\n\n            bool ok = true;\n            for (int i = 1; i < qMin(u.size(), sub.uniqueId.size()); i++)\n            {\n                if (u[i].toUInt(0, 16) != sub.uniqueId[i].toUInt(0, 16))\n                {\n                    ok = false;\n                }\n            }\n\n            if (!ok)\n            {\n                continue;\n            }\n\n            for (const auto &ddfItem : sub.items)\n            {\n                if (ddfItem.name == item->descriptor().suffix)\n                {\n                    item->setDdfItemHandle(ddfItem.handle);\n                    break;\n                }\n            }\n\n            break;\n        }\n    }\n\n    if (item->ddfItemHandle() != DeviceDescription::Item::InvalidItemHandle)\n    {\n        DeviceDescription::Item *ddfItem = DDF_GetItemMutable(item);\n\n        if (ddfItem && ddfItem->isValid())\n        {\n            if (ddfItem->parseParameters.isNull())\n            {\n                char buf[255];\n\n                QVariantMap param;\n                param[QLatin1String(\"ep\")] = int(ep);\n                snprintf(buf, sizeof(buf), \"0x%04X\", clusterId);\n                param[QLatin1String(\"cl\")] = QLatin1String(buf);\n                snprintf(buf, sizeof(buf), \"0x%04X\", attributeId);\n                param[QLatin1String(\"at\")] = QLatin1String(buf);\n                param[QLatin1String(\"eval\")] = QLatin1String(eval);\n\n                size_t fileLen = strlen(file);\n                const char *fileName = file + fileLen;\n\n                for (size_t i = fileLen; i > 0; i--, fileName--)\n                {\n                    if (*fileName == '\/')\n                    {\n                        fileName++;\n                        break;\n                    }\n                }\n\n                snprintf(buf, sizeof(buf), \"%s:%d\", fileName, line);\n                param[QLatin1String(\"cppsrc\")] = QLatin1String(buf);\n\n                ddfItem->parseParameters = param;\n\n                DBG_Printf(DBG_DDF, \"DDF %s:%d: %s updated ZCL function cl: 0x%04X, at: 0x%04X, eval: %s\\n\", fileName, line, qPrintable(resource->item(RAttrUniqueId)->toString()), clusterId, attributeId, eval);\n            }\n        }\n    }\n}\n\nvoid DeviceDescriptions::handleEvent(const Event &event)\n{\n    if (event.what() == REventDDFInitRequest)\n    {\n        handleDDFInitRequest(event);\n    }\n    else if (event.what() == REventDDFReload)\n    {\n        readAll(); \/\/ todo read only device specific files?\n    }\n}\n\n\/*! Get the DDF object for a \\p resource.\n    \\returns The DDF object, DeviceDescription::isValid() to check for success.\n *\/\nconst DeviceDescription &DeviceDescriptions::get(const Resource *resource) const\n{\n    Q_ASSERT(resource);\n    Q_ASSERT(resource->item(RAttrModelId));\n\n    Q_D(const DeviceDescriptions);\n\n    const auto modelId = resource->item(RAttrModelId)->toString();\n\n    const auto i = std::find_if(d->descriptions.begin(), d->descriptions.end(), [&modelId](const DeviceDescription &ddf)\n    {\n        return ddf.modelIds.contains(modelId);\n    });\n\n    if (i != d->descriptions.end())\n    {\n        return *i;\n    }\n\n    return d->invalidDescription;\n}\n\nvoid DeviceDescriptions::put(const DeviceDescription &ddf)\n{\n    if (!ddf.isValid())\n    {\n        return;\n    }\n\n    Q_D(DeviceDescriptions);\n\n    if (ddf.handle >= 0 && ddf.handle <= int(d->descriptions.size()))\n    {\n        DeviceDescription &ddf0 = d->descriptions[ddf.handle];\n\n        DBG_Assert(ddf0.handle == ddf.handle);\n        if (ddf.handle == ddf0.handle)\n        {\n            DBG_Printf(DBG_DDF, \"update ddf %s index %d\\n\", qPrintable(ddf0.modelIds.front()), ddf.handle);\n            ddf0 = ddf;\n            DDF_UpdateItemHandles(d->descriptions, d->loadCounter);\n            return;\n        }\n    }\n}\n\nconst DeviceDescription &DeviceDescriptions::load(const QString &path)\n{\n    Q_D(DeviceDescriptions);\n\n    auto i = std::find_if(d->descriptions.begin(), d->descriptions.end(), [&path](const auto &ddf){ return ddf.path == path; });\n    if (i != d->descriptions.end())\n    {\n        return *i;\n    }\n\n    auto result = DDF_ReadDeviceFile(path);\n\n    if (!result.empty())\n    {\n        for (auto &ddf : result)\n        {\n            ddf = DDF_MergeGenericItems(d->genericItems, ddf);\n            ddf = DDF_LoadScripts(ddf);\n\n            i = std::find_if(d->descriptions.begin(), d->descriptions.end(), [&ddf](const DeviceDescription &b)\n            {\n                return ddf.modelIds == b.modelIds && ddf.manufacturerNames == b.manufacturerNames;\n            });\n\n            if (i != d->descriptions.end())\n            {\n                *i = ddf; \/\/ update\n            }\n            else\n            {\n                d->descriptions.push_back(ddf);\n            }\n        }\n\n        DDF_UpdateItemHandles(d->descriptions, d->loadCounter);\n\n        i = std::find_if(d->descriptions.begin(), d->descriptions.end(), [&path](const auto &ddf){ return ddf.path == path; });\n        if (i != d->descriptions.end())\n        {\n            return *i;\n        }\n    }\n\n    return d->invalidDescription;\n}\n\n\/*! Turns a string constant into it's value.\n    \\returns The constant value on success, or the constant itself on error.\n *\/\nQString DeviceDescriptions::constantToString(const QString &constant) const\n{\n    Q_D(const DeviceDescriptions);\n\n    if (constant.startsWith('$'))\n    {\n        const auto i = d->constants.find(constant);\n\n        if (i != d->constants.end())\n        {\n            return i->second;\n        }\n    }\n\n    return constant;\n}\n\nQString DeviceDescriptions::stringToConstant(const QString &str) const\n{\n    Q_D(const DeviceDescriptions);\n\n    if (str.startsWith('$'))\n    {\n        return str;\n    }\n\n    const auto end = d->constants.cend();\n    for (auto p = d->constants.begin(); p != end; ++p)\n    {\n        if (p->second == str)\n        {\n            return p->first;\n        }\n    }\n\n    return str;\n}\n\nQStringList DeviceDescriptions::constants(const QString &prefix) const\n{\n    Q_D(const DeviceDescriptions);\n    QStringList result;\n\n    const auto end = d->constants.cend();\n    for (auto p = d->constants.begin(); p != end; ++p)\n    {\n        if (prefix.isEmpty() || p->first.startsWith(prefix))\n        {\n            result.push_back(p->first);\n        }\n    }\n\n    return result;\n}\n\nstatic DeviceDescription::Item *DDF_GetItemMutable(const ResourceItem *item)\n{\n    if (!_priv || !item)\n    {\n        return nullptr;\n    }\n\n    DeviceDescriptionsPrivate *d = _priv;\n\n    ItemHandlePack h;\n    h.handle = item->ddfItemHandle(); \/\/ unpack\n\n    if (h.handle == DeviceDescription::Item::InvalidItemHandle)\n    {\n        return nullptr;\n    }\n\n    if (h.loadCounter != d->loadCounter)\n    {\n        return nullptr;\n    }\n\n    DBG_Assert(h.description < d->descriptions.size());\n    if (h.description >= d->descriptions.size())\n    {\n        return nullptr;\n    }\n\n    auto &ddf = d->descriptions[h.description];\n\n    DBG_Assert(h.subDevice < ddf.subDevices.size());\n    if (h.subDevice >= ddf.subDevices.size())\n    {\n        return nullptr;\n    }\n\n    auto &sub = ddf.subDevices[h.subDevice];\n\n    DBG_Assert(h.item < sub.items.size());\n\n    if (h.item < sub.items.size())\n    {\n        return &sub.items[h.item];\n    }\n\n    return nullptr;\n}\n\n\/*! Retrieves the DDF item for the given \\p item.\n\n    If \\p item has a valid DDF item handle the respective entry is returned.\n    Otherwise the generic item list is searched based on the item.suffix.\n\n    The returned entry can be check with DeviceDescription::Item::isValid().\n *\/\nconst DeviceDescription::Item &DDF_GetItem(const ResourceItem *item)\n{\n    Q_ASSERT(_instance);\n    return _instance->getItem(item);\n}\n\n\/*! \\see DDF_GetItem() description.\n *\/\nconst DeviceDescription::Item &DeviceDescriptions::getItem(const ResourceItem *item) const\n{\n    Q_D(const DeviceDescriptions);\n\n    ItemHandlePack h;\n    h.handle = item->ddfItemHandle(); \/\/ unpack\n\n    if (h.handle == DeviceDescription::Item::InvalidItemHandle)\n    {\n        return getGenericItem(item->descriptor().suffix);\n    }\n\n    if (h.loadCounter != d->loadCounter)\n    {\n        return d->invalidItem;\n    }\n\n    \/\/ Note: There are no further if conditions since at this point it's certain that a handle must be valid.\n\n    Q_ASSERT(h.description < d->descriptions.size());\n\n    const auto &ddf = d->descriptions[h.description];\n\n    Q_ASSERT(h.subDevice < ddf.subDevices.size());\n\n    const auto &sub = ddf.subDevices[h.subDevice];\n\n    Q_ASSERT(h.item < sub.items.size());\n\n    return sub.items[h.item];\n}\n\nconst DDF_Items &DeviceDescriptions::genericItems() const\n{\n    return d_ptr2->genericItems;\n}\n\nconst DeviceDescription::Item &DeviceDescriptions::getGenericItem(const char *suffix) const\n{\n    Q_D(const DeviceDescriptions);\n\n    for (const auto &item : d->genericItems)\n    {\n        if (item.name == QLatin1String(suffix))\n        {\n            return item;\n        }\n    }\n\n    return d->invalidItem;\n}\n\nconst std::vector<DDF_FunctionDescriptor> &DeviceDescriptions::getParseFunctions() const\n{\n    return d_ptr2->parseFunctions;\n}\n\nconst std::vector<DDF_FunctionDescriptor> &DeviceDescriptions::getReadFunctions() const\n{\n    return d_ptr2->readFunctions;\n}\n\nconst std::vector<DDF_SubDeviceDescriptor> &DeviceDescriptions::getSubDevices() const\n{\n    return d_ptr2->subDevices;\n}\n\n\/*! Updates all DDF item handles to point to correct location.\n    \\p loadCounter - the current load counter.\n *\/\nstatic void DDF_UpdateItemHandles(std::vector<DeviceDescription> &descriptions, uint loadCounter)\n{\n    int index = 0;\n    Q_ASSERT(loadCounter >= HND_MIN_LOAD_COUNTER);\n    Q_ASSERT(loadCounter <= HND_MAX_LOAD_COUNTER);\n\n    ItemHandlePack handle;\n    handle.description = 0;\n    handle.loadCounter = loadCounter;\n\n    for (auto &ddf : descriptions)\n    {\n        ddf.handle = index++;\n        handle.subDevice = 0;\n        for (auto &sub : ddf.subDevices)\n        {\n            handle.item = 0;\n\n            for (auto &item : sub.items)\n            {\n                item.handle = handle.handle;\n                Q_ASSERT(handle.item < HND_MAX_ITEMS);\n                handle.item++;\n            }\n\n            Q_ASSERT(handle.subDevice < HND_MAX_SUB_DEVS);\n            handle.subDevice++;\n        }\n\n        Q_ASSERT(handle.description < HND_MAX_DESCRIPTIONS);\n        handle.description++;\n    }\n}\n\n\/*! Reads all DDF related files.\n *\/\nvoid DeviceDescriptions::readAll()\n{\n    Q_D(DeviceDescriptions);\n\n    d->loadCounter = (d->loadCounter + 1) % HND_MAX_LOAD_COUNTER;\n    if (d->loadCounter <= HND_MIN_LOAD_COUNTER)\n    {\n        d->loadCounter = HND_MIN_LOAD_COUNTER;\n    }\n\n    DBG_MEASURE_START(DDF_ReadAllFiles);\n\n    std::vector<DeviceDescription> descriptions;\n    std::vector<DeviceDescription::Item> genericItems;\n    std::vector<DDF_SubDeviceDescriptor> subDevices;\n\n    QStringList dirs;\n    dirs.push_back(deCONZ::getStorageLocation(deCONZ::DdfUserLocation));\n    dirs.push_back(deCONZ::getStorageLocation(deCONZ::DdfLocation));\n\n    while (!dirs.isEmpty())\n    {\n        QDirIterator it(dirs.takeFirst(), QDirIterator::Subdirectories | QDirIterator::FollowSymlinks);\n\n        while (it.hasNext())\n        {\n            it.next();\n\n            if (it.filePath().endsWith(QLatin1String(\"generic\/constants.json\")))\n            {\n                std::map<QString,QString> constants;\n                if (DDF_ReadConstantsJson(it.filePath(), &constants))\n                {\n                    d->constants = constants;\n                }\n            }\n            else if (it.fileName() == QLatin1String(\"button_maps.json\"))\n            {  }\n            else if (it.fileName().endsWith(QLatin1String(\".json\")))\n            {\n                if (it.filePath().contains(QLatin1String(\"generic\/items\/\")))\n                {\n                    auto result = DDF_ReadItemFile(it.filePath());\n                    if (result.isValid())\n                    {\n                        result.isGenericRead = !result.readParameters.isNull() ? 1 : 0;\n                        result.isGenericWrite = !result.writeParameters.isNull() ? 1 : 0;\n                        result.isGenericParse = !result.parseParameters.isNull() ? 1 : 0;\n                        genericItems.push_back(std::move(result));\n                    }\n                }\n                else if (it.filePath().contains(QLatin1String(\"generic\/subdevices\/\")))\n                {\n                    auto sub = DDF_ReadSubDeviceFile(it.filePath());\n                    if (isValid(sub))\n                    {\n                        subDevices.push_back(sub);\n                    }\n                }\n                else\n                {\n                    DBG_Printf(DBG_DDF, \"read %s\\n\", qPrintable(it.fileName()));\n                    std::vector<DeviceDescription> result = DDF_ReadDeviceFile(it.filePath());\n                    std::move(result.begin(), result.end(), std::back_inserter(descriptions));\n                }\n            }\n        }\n    }\n\n    if (!genericItems.empty())\n    {\n        d->genericItems = std::move(genericItems);\n    }\n\n    if (!subDevices.empty())\n    {\n        std::sort(subDevices.begin(), subDevices.end(), [](const auto &a, const auto &b){\n            return a.name < b.name;\n        });\n\n        d->subDevices = std::move(subDevices);\n    }\n\n    if (!descriptions.empty())\n    {\n        d->descriptions = std::move(descriptions);\n        DDF_UpdateItemHandles(d->descriptions, d->loadCounter);\n\n        for (auto &ddf : d->descriptions)\n        {\n            ddf = DDF_MergeGenericItems(d->genericItems, ddf);\n            ddf = DDF_LoadScripts(ddf);\n        }\n    }\n\n    DBG_MEASURE_END(DDF_ReadAllFiles);\n}\n\n\/*! Tries to init a Device from an DDF file.\n\n    Currently this is done syncronously later on it will be async to not block\n    the main thread while loading DDF files.\n *\/\nvoid DeviceDescriptions::handleDDFInitRequest(const Event &event)\n{\n    Q_D(DeviceDescriptions);\n\n    auto *resource = DEV_GetResource(RDevices, QString::number(event.deviceKey()));\n\n    int result = -1; \/\/ error\n\n    if (resource)\n    {\n        const auto ddf = get(resource);\n\n        if (ddf.isValid())\n        {\n            result = 0;\n\n            if (!DEV_TestManaged() && !d->enabledStatusFilter.contains(ddf.status))\n            {\n                result = 2;\n            }\n            else if (DEV_InitDeviceFromDescription(static_cast<Device*>(resource), ddf))\n            {\n                result = 1; \/\/ ok\n\n                if (ddf.status == QLatin1String(\"Draft\"))\n                {\n                    result = 2;\n                }\n            }\n        }\n\n        if (result >= 0)\n        {\n            DBG_Printf(DBG_INFO, \"DEV found DDF for 0x%016llX, path: %s\\n\", event.deviceKey(), qPrintable(ddf.path));\n        }\n\n        if (result == 0)\n        {\n            DBG_Printf(DBG_INFO, \"DEV init Device from DDF for 0x%016llX failed\\n\", event.deviceKey());\n        }\n        else if (result == -1)\n        {\n            DBG_Printf(DBG_INFO, \"DEV no DDF for 0x%016llX, modelId: %s\\n\", event.deviceKey(), qPrintable(resource->item(RAttrModelId)->toString()));\n            DBG_Printf(DBG_INFO, \"DEV create on-the-fly DDF for 0x%016llX\\n\", event.deviceKey());\n\n            DeviceDescription ddf1;\n\n            Device *device = static_cast<Device*>(resource);\n\n            if (DEV_InitBaseDescriptionForDevice(device, ddf1))\n            {\n                d->descriptions.push_back(ddf1);\n                DDF_UpdateItemHandles(d->descriptions, d->loadCounter);\n            }\n        }\n    }\n\n    emit eventNotify(Event(RDevices, REventDDFInitResponse, result, event.deviceKey()));\n}\n\n\/*! Reads constants.json file and places them into \\p constants map.\n *\/\nstatic bool DDF_ReadConstantsJson(const QString &path, std::map<QString,QString> *constants)\n{\n    Q_ASSERT(constants);\n\n    QFile file(path);\n\n    if (!file.exists())\n    {\n        return false;\n    }\n\n    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))\n    {\n        return false;\n    }\n\n    QJsonParseError error;\n    QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &error);\n    file.close();\n\n    if (!doc.isObject())\n    {\n        DBG_Printf(DBG_INFO, \"failed to read device constants: %s, err: %s, offset: %d\\n\", qPrintable(path), qPrintable(error.errorString()), error.offset);\n        return false;\n    }\n\n    const auto obj = doc.object();\n    const QStringList categories {\"manufacturers\", \"device-types\"};\n\n    for (const auto &cat : categories)\n    {\n        if (obj.contains(cat))\n        {\n            const auto catobj = obj.value(cat).toObject();\n            for (auto &key : catobj.keys())\n            {\n                (*constants)[key] = catobj.value(key).toString();\n            }\n        }\n    }\n\n    return !constants->empty();\n}\n\n\/*! Parses an item object.\n    \\returns A parsed item, use DeviceDescription::Item::isValid() to check for success.\n *\/\nstatic DeviceDescription::Item DDF_ParseItem(const QJsonObject &obj)\n{\n    DeviceDescription::Item result;\n\n    if (obj.contains(QLatin1String(\"name\")))\n    {\n        result.name = obj.value(QLatin1String(\"name\")).toString().toUtf8().constData();\n    }\n    else if (obj.contains(QLatin1String(\"id\"))) \/\/ generic\/item TODO align name\/id?\n    {\n        result.name = obj.value(QLatin1String(\"id\")).toString().toUtf8().constData();\n    }\n\n    if (obj.contains(QLatin1String(\"description\")))\n    {\n        result.description = obj.value(QLatin1String(\"description\")).toString();\n    }\n\n    if (result.name.empty())\n    {\n\n    }\n    else if (getResourceItemDescriptor(result.name, result.descriptor))\n    {\n        DBG_Printf(DBG_INFO, \"DDF: loaded resource item descriptor: %s\\n\", result.descriptor.suffix);\n\n        if (obj.contains(QLatin1String(\"access\")))\n        {\n            const auto access = obj.value(QLatin1String(\"access\")).toString();\n            if (access == \"R\")\n            {\n                result.descriptor.access = ResourceItemDescriptor::Access::ReadOnly;\n            }\n            else if (access == \"RW\")\n            {\n                result.descriptor.access = ResourceItemDescriptor::Access::ReadWrite;\n            }\n        }\n\n        if (obj.contains(QLatin1String(\"public\")))\n        {\n            result.isPublic = obj.value(QLatin1String(\"public\")).toBool() ? 1 : 0;\n        }\n\n        if (obj.contains(QLatin1String(\"implicit\")))\n        {\n            result.isImplicit = obj.value(QLatin1String(\"implicit\")).toBool() ? 1 : 0;\n        }\n\n        if (obj.contains(QLatin1String(\"awake\")))\n        {\n            result.awake = obj.value(QLatin1String(\"awake\")).toBool() ? 1 : 0;\n        }\n\n        if (obj.contains(QLatin1String(\"managed\")))\n        {\n            result.isManaged = obj.value(QLatin1String(\"managed\")).toBool() ? 1 : 0;\n        }\n\n        if (obj.contains(QLatin1String(\"refresh.interval\")))\n        {\n            result.refreshInterval = obj.value(QLatin1String(\"refresh.interval\")).toInt(0);\n        }\n\n        const auto parse = obj.value(QLatin1String(\"parse\"));\n        if (parse.isObject())\n        {\n            result.parseParameters = parse.toVariant();\n        }\n\n        const auto read = obj.value(QLatin1String(\"read\"));\n        if (read.isObject())\n        {\n            result.readParameters = read.toVariant();\n        }\n\n        const auto write = obj.value(QLatin1String(\"write\"));\n        if (write.isObject())\n        {\n            result.writeParameters = write.toVariant();\n        }\n\n        if (obj.contains(QLatin1String(\"static\")))\n        {\n            result.isStatic = 1;\n            result.defaultValue = obj.value(QLatin1String(\"static\")).toVariant();\n        }\n\n        if (obj.contains(QLatin1String(\"default\")))\n        {\n            result.defaultValue = obj.value(QLatin1String(\"default\")).toVariant();\n        }\n    }\n    else\n    {\n        DBG_Printf(DBG_INFO, \"DDF: failed to load resource item descriptor: %s\\n\", result.name.c_str());\n    }\n\n    return result;\n}\n\n\/*! Parses a sub device in a DDF object \"subdevices\" array.\n    \\returns The sub device object, use DeviceDescription::SubDevice::isValid() to check for success.\n *\/\nstatic DeviceDescription::SubDevice DDF_ParseSubDevice(const QJsonObject &obj)\n{\n    DeviceDescription::SubDevice result;\n\n    result.type = obj.value(QLatin1String(\"type\")).toString();\n    if (result.type.isEmpty())\n    {\n        return result;\n    }\n\n    result.restApi = obj.value(QLatin1String(\"restapi\")).toString();\n    if (result.restApi.isEmpty())\n    {\n        return result;\n    }\n\n    const auto uniqueId = obj.value(QLatin1String(\"uuid\"));\n    if (uniqueId.isArray())\n    {\n        const auto arr = uniqueId.toArray();\n        for (const auto &i : arr)\n        {\n            result.uniqueId.push_back(i.toString());\n        }\n    }\n\n    const auto fingerPrint = obj.value(QLatin1String(\"fingerprint\"));\n    if (fingerPrint.isObject())\n    {\n        bool ok;\n        const auto fp = fingerPrint.toObject();\n        result.fingerPrint.endpoint = fp.value(QLatin1String(\"endpoint\")).toString().toUInt(&ok, 0);\n        result.fingerPrint.profileId = ok ? fp.value(QLatin1String(\"profile\")).toString().toUInt(&ok, 0) : 0;\n        result.fingerPrint.deviceId = ok ? fp.value(QLatin1String(\"device\")).toString().toUInt(&ok, 0) : 0;\n\n        if (fp.value(QLatin1String(\"in\")).isArray())\n        {\n            const auto arr = fp.value(QLatin1String(\"in\")).toArray();\n            for (const auto &cl : arr)\n            {\n                const auto clusterId = ok ? cl.toString().toUInt(&ok, 0) : 0;\n                if (ok)\n                {\n                    result.fingerPrint.inClusters.push_back(clusterId);\n                }\n            }\n        }\n\n        if (fp.value(QLatin1String(\"out\")).isArray())\n        {\n            const auto arr = fp.value(QLatin1String(\"out\")).toArray();\n            for (const auto &cl : arr)\n            {\n                const auto clusterId = ok ? cl.toString().toUInt(&ok, 0) : 0;\n                if (ok)\n                {\n                    result.fingerPrint.outClusters.push_back(clusterId);\n                }\n            }\n        }\n\n        if (!ok)\n        {\n            result.fingerPrint = { };\n        }\n    }\n\n    const auto items = obj.value(QLatin1String(\"items\"));\n    if (!items.isArray())\n    {\n        return result;\n    }\n\n    {\n        const auto arr = items.toArray();\n        for (const auto &i : arr)\n        {\n            if (i.isObject())\n            {\n                const auto item = DDF_ParseItem(i.toObject());\n\n                if (item.isValid())\n                {\n                    result.items.push_back(item);\n                }\n                else\n                {\n\n                }\n            }\n        }\n    }\n\n    return result;\n}\n\n\/\/ {\"at\": \"0x0021\", \"dt\": \"u8\", \"min\": 5, \"max\": 3600, \"change\": 1 },\n\n\/*! Parses a ZCL report in a DDF_Binding object \"report\" array.\n    \\returns The ZCL report, use DDF_ZclReport::isValid() to check for success.\n *\/\nstatic DDF_ZclReport DDF_ParseZclReport(const QJsonObject &obj)\n{\n    DDF_ZclReport result{};\n\n    \/\/ check required fields\n    if (!obj.contains(QLatin1String(\"at\")) ||\n        !obj.contains(QLatin1String(\"dt\")) ||\n        !obj.contains(QLatin1String(\"min\")) ||\n        !obj.contains(QLatin1String(\"max\")))\n    {\n        return {};\n    }\n\n    bool ok = false;\n    result.attributeId = obj.value(QLatin1String(\"at\")).toString().toUShort(&ok, 0);\n\n    if (!ok)\n    {\n        return {};\n    }\n\n    {\n        auto dataType = obj.value(QLatin1String(\"dt\")).toString().toUShort(&ok, 0);\n        if (!ok || dataType > 0xFF)\n        {\n            return {};\n        }\n        result.dataType = dataType;\n    }\n\n    {\n        const auto minInterval = obj.value(QLatin1String(\"min\")).toInt(-1);\n\n        if (minInterval < 0 || minInterval > UINT16_MAX)\n        {\n            return {};\n        }\n\n        result.minInterval = minInterval;\n    }\n\n    {\n        const auto maxInterval = obj.value(QLatin1String(\"max\")).toInt(-1);\n\n        if (maxInterval < 0 || maxInterval > UINT16_MAX)\n        {\n            return {};\n        }\n\n        result.maxInterval = maxInterval;\n    }\n\n    if (obj.contains(QLatin1String(\"change\")))\n    {\n        result.reportableChange = obj.value(QLatin1String(\"change\")).toString().toUInt(&ok, 0);\n\n        if (!ok)\n        {\n            return {};\n        }\n    }\n\n    if (obj.contains(QLatin1String(\"mf\")))\n    {\n        result.manufacturerCode = obj.value(QLatin1String(\"mf\")).toString().toUShort(&ok, 0);\n\n        if (!ok)\n        {\n            return {};\n        }\n    }\n\n    result.valid = true;\n\n    return result;\n}\n\n\/*! Parses a binding in a DDF object \"bindings\" array.\n    \\returns The binding, use DDF_Binding::isValid() to check for success.\n *\/\nstatic DDF_Binding DDF_ParseBinding(const QJsonObject &obj)\n{\n    DDF_Binding result{};\n\n    \/\/ check required fields\n    if (!obj.contains(QLatin1String(\"bind\")) ||\n        !obj.contains(QLatin1String(\"src.ep\")) ||\n        !obj.contains(QLatin1String(\"cl\")))\n    {\n        return {};\n    }\n\n    const auto type = obj.value(QLatin1String(\"bind\")).toString();\n\n    if (type == QLatin1String(\"unicast\"))\n    {\n        result.isUnicastBinding = 1;\n    }\n    else if (type == QLatin1String(\"groupcast\"))\n    {\n        result.isGroupBinding = 1;\n    }\n    else\n    {\n        return {};\n    }\n\n    bool ok = false;\n    {\n        const auto srcEndpoint = obj.value(QLatin1String(\"src.ep\")).toInt(-1);\n\n        if (srcEndpoint < 0 || srcEndpoint > UINT8_MAX)\n        {\n            return {};\n        }\n        result.srcEndpoint = srcEndpoint;\n    }\n\n    {\n        result.clusterId = obj.value(QLatin1String(\"cl\")).toString().toUShort(&ok, 0);\n\n        if (!ok)\n        {\n            return {};\n        }\n    }\n\n    if (obj.contains(QLatin1String(\"dst.ep\")))\n    {\n        const auto dstEndpoint = obj.value(QLatin1String(\"dst.ep\")).toInt(-1);\n        if (dstEndpoint < 0 || dstEndpoint >= 255)\n        {\n            return {};\n        }\n        result.dstEndpoint = dstEndpoint;\n    }\n    else\n    {\n        result.dstEndpoint = 0;\n    }\n\n    if (result.isGroupBinding && obj.contains(QLatin1String(\"config.group\")))\n    {\n        const auto configGroup = obj.value(QLatin1String(\"config.group\")).toInt(-1);\n        if (configGroup < 0 || configGroup >= 255)\n        {\n            return {};\n        }\n        result.configGroup = configGroup;\n    }\n    else\n    {\n        result.configGroup = 0;\n    }\n\n    const auto report = obj.value(QLatin1String(\"report\"));\n    if (report.isArray())\n    {\n        const auto reportArr = report.toArray();\n        for (const auto &i : reportArr)\n        {\n            if (i.isObject())\n            {\n                const auto rep = DDF_ParseZclReport(i.toObject());\n                if (isValid(rep))\n                {\n                    result.reporting.push_back(rep);\n                }\n            }\n        }\n    }\n\n    return result;\n}\n\n\/*! Parses a single string or array of strings in DDF JSON object.\n    The obj[key] value can be a string or array of strings.\n    \\returns List of parsed strings.\n *\/\nstatic QStringList DDF_ParseStringOrList(const QJsonObject &obj, QLatin1String key)\n{\n    QStringList result;\n    const auto val = obj.value(key);\n\n    if (val.isString()) \/\/ \"key\": \"alpha.sensor\"\n    {\n        result.push_back(val.toString());\n    }\n    else if (val.isArray()) \/\/ \"key\": [ \"alpha.sensor\", \"beta.sensor\" ]\n    {\n        const auto arr = val.toArray();\n        for (const auto &i : arr)\n        {\n            if (i.isString())\n            {\n                result.push_back(i.toString());\n            }\n        }\n    }\n\n    return result;\n}\n\n\/*! Parses an DDF JSON object.\n    \\returns DDF object, use DeviceDescription::isValid() to check for success.\n *\/\nstatic DeviceDescription DDF_ParseDeviceObject(const QJsonObject &obj, const QString &path)\n{\n    DeviceDescription result;\n\n    const auto schema = obj.value(QLatin1String(\"schema\")).toString();\n\n    if (schema != QLatin1String(\"devcap1.schema.json\"))\n    {\n        return result;\n    }\n\n    const auto subDevices = obj.value(QLatin1String(\"subdevices\"));\n    if (!subDevices.isArray())\n    {\n        return result;\n    }\n\n    result.path = path;\n    result.manufacturerNames = DDF_ParseStringOrList(obj, QLatin1String(\"manufacturername\"));\n    result.modelIds = DDF_ParseStringOrList(obj, QLatin1String(\"modelid\"));\n    result.product = obj.value(QLatin1String(\"product\")).toString();\n\n    if (obj.contains(QLatin1String(\"status\")))\n    {\n        result.status = obj.value(QLatin1String(\"status\")).toString();\n    }\n\n    if (obj.contains(QLatin1String(\"vendor\")))\n    {\n        result.vendor = obj.value(QLatin1String(\"vendor\")).toString();\n    }\n\n    if (obj.contains(QLatin1String(\"sleeper\")))\n    {\n        result.sleeper = obj.value(QLatin1String(\"sleeper\")).toBool() ? 1 : 0;\n    }\n\n    const auto keys = obj.keys();\n    for (const auto &key : keys)\n    {\n        DBG_Printf(DBG_INFO, \"DDF: %s: %s\\n\", qPrintable(key), qPrintable(obj.value(key).toString()));\n    }\n\n    const auto subDevicesArr = subDevices.toArray();\n    for (const auto &i : subDevicesArr)\n    {\n        if (i.isObject())\n        {\n            const auto sub = DDF_ParseSubDevice(i.toObject());\n            if (sub.isValid())\n            {\n                result.subDevices.push_back(sub);\n            }\n        }\n    }\n\n    const auto bindings = obj.value(QLatin1String(\"bindings\"));\n    if (bindings.isArray())\n    {\n        const auto bindingsArr = bindings.toArray();\n        for (const auto &i : bindingsArr)\n        {\n            if (i.isObject())\n            {\n                const auto bnd = DDF_ParseBinding(i.toObject());\n                if (isValid(bnd))\n                {\n                    result.bindings.push_back(bnd);\n                }\n            }\n        }\n    }\n\n    return result;\n}\n\n\/*! Reads an item file under (generic\/items\/).\n    \\returns A parsed item, use DeviceDescription::Item::isValid() to check for success.\n *\/\nstatic DeviceDescription::Item DDF_ReadItemFile(const QString &path)\n{\n    QFile file(path);\n    if (!file.exists())\n    {\n        return { };\n    }\n\n    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))\n    {\n        return { };\n    }\n\n    QJsonParseError error;\n    QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &error);\n    file.close();\n\n    if (error.error != QJsonParseError::NoError)\n    {\n        DBG_Printf(DBG_INFO, \"DDF: failed to read %s, err: %s, offset: %d\\n\", qPrintable(path), qPrintable(error.errorString()), error.offset);\n        return { };\n    }\n\n    if (doc.isObject())\n    {\n        return DDF_ParseItem(doc.object());\n    }\n\n    return { };\n}\n\n\/*! Reads an subdevice file under (generic\/subdevices\/).\n    \\returns A parsed subdevice, use isValid(DDF_SubDeviceDescriptor) to check for success.\n *\/\nstatic DDF_SubDeviceDescriptor DDF_ReadSubDeviceFile(const QString &path)\n{\n    DDF_SubDeviceDescriptor result;\n\n    QFile file(path);\n    if (!file.exists())\n    {\n        return result;\n    }\n\n    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))\n    {\n        return result;\n    }\n\n    QJsonParseError error;\n    QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &error);\n    file.close();\n\n    if (error.error != QJsonParseError::NoError)\n    {\n        DBG_Printf(DBG_INFO, \"DDF: failed to read %s, err: %s, offset: %d\\n\", qPrintable(path), qPrintable(error.errorString()), error.offset);\n        return result;\n    }\n\n    if (doc.isObject())\n    {\n        const auto obj = doc.object();\n        QString schema;\n        if (obj.contains(QLatin1String(\"schema\")))\n        {\n            schema = obj.value(QLatin1String(\"schema\")).toString();\n        }\n\n        if (schema != QLatin1String(\"subdevice1.schema.json\"))\n        {\n            return result;\n        }\n\n        if (obj.contains(QLatin1String(\"name\")))\n        {\n            result.name = obj.value(QLatin1String(\"name\")).toString();\n        }\n        if (obj.contains(QLatin1String(\"type\")))\n        {\n            result.type = obj.value(QLatin1String(\"type\")).toString();\n        }\n        if (obj.contains(QLatin1String(\"restapi\")))\n        {\n            result.restApi = obj.value(QLatin1String(\"restapi\")).toString();\n        }\n\n        result.order = obj.value(QLatin1String(\"order\")).toInt(SUBDEVICE_DEFAULT_ORDER);\n\n        if (obj.contains(QLatin1String(\"uuid\")))\n        {\n            const auto uniqueId = obj.value(QLatin1String(\"uuid\"));\n            if (uniqueId.isArray())\n            {\n                const auto arr = uniqueId.toArray();\n                for (const auto &i : arr)\n                {\n                    DBG_Assert(i.isString());\n                    result.uniqueId.push_back(i.toString());\n                }\n            }\n        }\n        if (obj.contains(QLatin1String(\"items\")))\n        {\n            const auto items = obj.value(QLatin1String(\"items\"));\n            if (items.isArray())\n            {\n                const auto arr = items.toArray();\n                for (const auto &i : arr)\n                {\n                    DBG_Assert(i.isString());\n                    ResourceItemDescriptor rid;\n                    if (getResourceItemDescriptor(i.toString(), rid))\n                    {\n                        result.items.push_back(rid.suffix);\n                    }\n                }\n            }\n        }\n    }\n\n    return result;\n}\n\nQVariant DDF_ResolveParamScript(const QVariant &param, const QString &path)\n{\n    auto result = param;\n\n    if (param.type() != QVariant::Map)\n    {\n        return result;\n    }\n\n    auto map = param.toMap();\n\n    if (map.contains(\"script\"))\n    {\n        const auto script = map[\"script\"].toString();\n\n        const QFileInfo fi(path);\n        QFile f(fi.canonicalPath() + \"\/\" + script);\n\n        if (f.exists() && f.open(QFile::ReadOnly))\n        {\n            const auto content = f.readAll();\n            if (!content.isEmpty())\n            {\n                map[\"eval\"] = content;\n                result = std::move(map);\n            }\n        }\n    }\n\n    return result;\n}\n\nDeviceDescription DDF_LoadScripts(const DeviceDescription &ddf)\n{\n    auto result = ddf;\n\n    for (auto &sub : result.subDevices)\n    {\n        for (auto &item : sub.items)\n        {\n            item.parseParameters = DDF_ResolveParamScript(item.parseParameters, ddf.path);\n            item.readParameters = DDF_ResolveParamScript(item.readParameters, ddf.path);\n            item.writeParameters = DDF_ResolveParamScript(item.writeParameters, ddf.path);\n        }\n    }\n\n    return result;\n}\n\n\/*! Reads a DDF file which may contain one or more device descriptions.\n    \\returns Vector of parsed DDF objects.\n *\/\nstatic std::vector<DeviceDescription> DDF_ReadDeviceFile(const QString &path)\n{\n    std::vector<DeviceDescription> result;\n\n    QFile file(path);\n    if (!file.exists())\n    {\n        return result;\n    }\n\n    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))\n    {\n        return result;\n    }\n\n    QJsonParseError error;\n    QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &error);\n    file.close();\n\n    if (error.error != QJsonParseError::NoError)\n    {\n        DBG_Printf(DBG_INFO, \"DDF: failed to read %s, err: %s, offset: %d\\n\", qPrintable(path), qPrintable(error.errorString()), error.offset);\n        return result;\n    }\n\n    if (doc.isObject())\n    {\n        const auto ddf = DDF_ParseDeviceObject(doc.object(), path);\n        if (ddf.isValid())\n        {\n            result.push_back(ddf);\n        }\n    }\n    else if (doc.isArray())\n    {\n        const auto arr = doc.array();\n        for (const auto &i : arr)\n        {\n            if (i.isObject())\n            {\n                const auto ddf = DDF_ParseDeviceObject(i.toObject(), path);\n                if (ddf.isValid())\n                {\n                    result.push_back(ddf);\n                }\n            }\n        }\n    }\n\n    return result;\n}\n\n\/*! Merge common properties like \"read\", \"parse\" and \"write\" functions from generic items into DDF items.\n    Only properties which are already defined in the DDF file won't be overwritten.\n\n    \\param genericItems - generic items used as source\n    \\param ddf - DDF object with unmerged items\n    \\returns The merged DDF object.\n *\/\nstatic DeviceDescription DDF_MergeGenericItems(const std::vector<DeviceDescription::Item> &genericItems, const DeviceDescription &ddf)\n{\n    auto result = ddf;\n\n    for (auto &sub : result.subDevices)\n    {\n        for (auto &item : sub.items)\n        {\n            const auto genItem = std::find_if(genericItems.cbegin(), genericItems.cend(),\n                                              [&item](const DeviceDescription::Item &i){ return i.descriptor.suffix == item.descriptor.suffix; });\n            if (genItem == genericItems.cend())\n            {\n                continue;\n            }\n\n            item.isImplicit = genItem->isImplicit;\n            item.isManaged = genItem->isManaged;\n            item.isGenericRead = 0;\n            item.isGenericWrite = 0;\n            item.isGenericParse = 0;\n\n            if (item.readParameters.isNull()) { item.readParameters = genItem->readParameters; item.isGenericRead = 1; }\n            if (item.writeParameters.isNull()) { item.writeParameters = genItem->writeParameters; item.isGenericWrite = 1; }\n            if (item.parseParameters.isNull()) { item.parseParameters = genItem->parseParameters; item.isGenericParse = 1; }\n            if (item.descriptor.access == ResourceItemDescriptor::Access::Unknown)\n            {\n                item.descriptor.access = genItem->descriptor.access;\n            }\n            item.isPublic = genItem->isPublic;\n            if (item.refreshInterval == DeviceDescription::Item::NoRefreshInterval && genItem->refreshInterval != item.refreshInterval)\n            {\n                item.refreshInterval = genItem->refreshInterval;\n            }\n\n            if (!item.defaultValue.isValid() && genItem->defaultValue.isValid())\n            {\n                item.defaultValue = genItem->defaultValue;\n            }\n        }\n    }\n\n    return result;\n}\n\nuint8_t DDF_GetSubDeviceOrder(const QString &type)\n{\n    if (type.isEmpty() || type.startsWith(QLatin1String(\"CLIP\")))\n    {\n        return SUBDEVICE_DEFAULT_ORDER;\n    }\n\n    if (_priv)\n    {\n        auto i = std::find_if(_priv->subDevices.cbegin(), _priv->subDevices.cend(), [&](const auto &sub)\n        { return sub.name == type; });\n\n        if (i != _priv->subDevices.cend())\n        {\n            return i->order;\n        }\n    }\n\n#ifdef QT_DEBUG\n    DBG_Printf(DBG_DDF, \"DDF: No subdevice for type: %s\\n\", qPrintable(type));\n#endif\n\n    return SUBDEVICE_DEFAULT_ORDER;\n}\n\n\/*! Creates a unique Resource handle.\n *\/\nResource::Handle R_CreateResourceHandle(const Resource *r, size_t containerIndex)\n{\n    Q_ASSERT(r->prefix() != nullptr);\n    Q_ASSERT(!r->item(RAttrUniqueId)->toString().isEmpty());\n\n    Resource::Handle result;\n    result.hash = qHash(r->item(RAttrUniqueId)->toString());\n    result.index = containerIndex;\n    result.type = r->prefix()[1];\n    result.order = 0;\n\n    Q_ASSERT(result.type == 's' || result.type == 'l' || result.type == 'd' || result.type == 'g');\n    Q_ASSERT(isValid(result));\n\n    if (result.type == 's' || result.type == 'l')\n    {\n        const ResourceItem *type = r->item(RAttrType);\n        if (type)\n        {\n            result.order = DDF_GetSubDeviceOrder(type->toString());\n        }\n    }\n\n    return result;\n}\n","avg_line_length":28.3327877796,"max_line_length":210,"alphanum_fraction":0.5779258289,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2302,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*===================== begin_copyright_notice ==================================\n\nCopyright (c) 2017 Intel Corporation\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and\/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n======================= end_copyright_notice ==================================*\/\n\n#include \"Arena.h\"\n\n#ifdef COLLECT_ALLOCATION_STATS\nint numAllocations = 0;\nint numMallocCalls = 0;\nint totalAllocSize = 0;\nint totalMallocSize = 0;\nint numMemManagers = 0;\nint maxArenaLength = 0;\nint currentMallocSize = 0;\n#endif\nusing namespace vISA;\n\nvoid*\nArenaHeader::AllocSpace(size_t size, size_t al)\n{\n    assert(DefaultAlign(size_t(_nextByte)) == size_t(_nextByte));\n\n    void* allocSpace = (void*) AlignAddr((size_t) _nextByte, al);\n\n    if (size)\n    {\n        size = DefaultAlign(size);  \/\/ round up size so that next address is at least max aligned\n\n        if (_nextByte + size <= _lastByte) {\n            _nextByte += size;\n        }\n        else {\n            allocSpace = 0;\n        }\n    }\n    else\n    {\n        allocSpace = 0;\n    }\n\n    return allocSpace;\n}\n\n\nvoid\nArenaManager::FreeArenas()\n{\n    while (_arenas)\n    {\n#ifdef COLLECT_ALLOCATION_STATS\n        currentMallocSize -= _arenas->size;\n#endif\n        unsigned char* killed = (unsigned char*) _arenas;\n        _arenas = _arenas->_nextArena;\n        delete [] killed;\n    }\n\n    _arenas = 0;\n}\n","avg_line_length":28.0731707317,"max_line_length":97,"alphanum_fraction":0.6798436142,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1976,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include \"analog_bend.h\"\n#include <ArduinoLog.h>\n\n\/\/ variables:\nunsigned int m_bendSensorValue = 0;         \/\/ the sensor value\nunsigned int m_bendSensorMin = 1023;        \/\/ minimum sensor value\nunsigned int m_bendSensorMax = 0;           \/\/ maximum sensor value\n\nAnalogSmooth m_bendSensorAverage = AnalogSmooth(15); \/\/averaging filter\nunsigned char m_bendSensorOutputValue = 0;        \/\/the scaled & smoothed result: 0 - 255\n\nunsigned char m_ledStatus = HIGH;        \/\/for doing the calibration blink, 1 = off\n\nbool analog_bend_calibrateSensor(unsigned int &min, unsigned int &max){\n  \/\/calibration\n  Log.notice(\"Calibrating...\" CR );\n  unsigned int now = millis();\n  while ( (millis() - now) < 7000) { \/\/calibrate\n    m_bendSensorValue = analogRead(BEND_SENSOR_PIN);\n\n    \/\/ record the maximum sensor value\n    if (m_bendSensorValue > m_bendSensorMax) {\n      m_bendSensorMax = m_bendSensorValue;\n    }\n\n    \/\/ record the minimum sensor value\n    if (m_bendSensorValue < m_bendSensorMin) {\n      m_bendSensorMin = m_bendSensorValue;\n    }\n    m_ledStatus = !m_ledStatus;\n    delay(50);\n    digitalWrite(LED_PIN, m_ledStatus);\n  }\n  m_ledStatus = HIGH;\n  digitalWrite(LED_PIN, m_ledStatus); \/\/off!\n\n  min = m_bendSensorMin;\n  max = m_bendSensorMax;\n}\n\nunsigned char analog_bend_getLastKnownAdcRead(){\n  return m_bendSensorOutputValue;\n}\n\nunsigned char analog_bend_readAdc(){\n  \/\/ read the analog in value:\n    m_bendSensorValue = analogRead(BEND_SENSOR_PIN);\n\n    \/\/ apply the calibration to the sensor reading\n    m_bendSensorValue = map(m_bendSensorValue, m_bendSensorMin, m_bendSensorMax, 0, 255);\n\n    \/\/ in case the sensor value is outside the range seen during calibration\n    m_bendSensorValue = constrain(m_bendSensorValue, 0, 255);\n    m_bendSensorOutputValue = m_bendSensorAverage.smooth(m_bendSensorValue);\n\n    return m_bendSensorOutputValue;\n}\n\nvoid analog_bend_setMinMax(unsigned int min, unsigned int max){\n  m_bendSensorMin = min;\n  m_bendSensorMax = max;\n}\n","avg_line_length":31.3650793651,"max_line_length":89,"alphanum_fraction":0.725708502,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1560,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <string>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\n\r\nint calc_rows()   \/\/function to calculate total number of rows\r\n{\r\n    int rows=0;\r\n    ifstream file(\"mempool.csv\");   \/\/input file stream to read input from mempool file.\r\n    string line;\r\n    while (getline(file,line))      \/\/rows++ on every encounter of newline after a string \r\n    rows++;\r\n\r\n    return rows;          \/\/function returns total rows \r\n}\r\n\r\nint main()\r\n{\r\n  \r\n  fstream fin,fout;      \/\/ file pointer each for input and output\r\n  fin.open(\"sortedmempool.csv\");      \/\/mempool file sorted in descending order according to fee\r\n  fout.open(\"block.txt\", ios::out | ios::app);    \/\/ opens an existing file or creates a new file.\r\n\r\n  string taxid;\r\n  string fee;\r\n  string weight;\r\n  string parent_txids;\r\n\r\n  int rows=calc_rows();  \/\/calling function calc_rows();\r\n  cout<<rows<<endl;\r\n\r\n  int max_wt=4000000;     \/\/maximum weight which is used\r\n  int calculate=0;\r\n\r\n  while(fin.good())  \/\/The good() method used to check if the stream is good enough to work.\r\n {\r\n     getline(fin,taxid,',');  \/\/ read every column data of a row and store it in a string variable\r\n     getline(fin,fee,',');\r\n     getline(fin,weight,',');\r\n     getline(fin,parent_txids,'\\n');\r\n\r\n     int second=stoi(weight);    \/\/ convert string to integer for comparision\r\n\r\n     if((calculate+second)<=max_wt)\r\n     {\r\n       fout<<taxid<<'\\n';\r\n       calculate=calculate+second;\r\n     }\r\n\r\n }\r\n\r\n  \r\n fin.close();\r\n fout.close();\r\n\r\n}\r\n\r\n","avg_line_length":25.1612903226,"max_line_length":99,"alphanum_fraction":0.6237179487,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1022,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <bits\/stdc++.h>\nusing namespace std;\n\nclass WordFilter {\n   private:\n    unordered_map<string, int> mp;\n\n   public:\n    WordFilter(vector<string>& words) {\n        for (int i = 0; i < words.size(); ++i) {\n            string word = words[i];\n            vector<string> prefix, suffix;\n            for (int j = 0; j <= word.size(); ++j) {\n                prefix.push_back(word.substr(0, j));\n                suffix.push_back(word.substr(j));\n            }\n            for (const auto& p : prefix) {\n                for (const auto& s : suffix) {\n                    mp[p + \"$\" + s] = max(mp[p + \"$\" + s], i);\n                }\n            }\n        }\n    }\n\n    int f(string prefix, string suffix) {\n        if (mp.count(prefix + \"$\" + suffix) > 0) {\n            return mp[prefix + \"$\" + suffix];\n        } else {\n            return -1;\n        }\n    }\n};\n\n\/**\n * Your WordFilter object will be instantiated and called as such:\n * WordFilter* obj = new WordFilter(words);\n * int param_1 = obj->f(prefix,suffix);\n *\/","avg_line_length":26.8947368421,"max_line_length":66,"alphanum_fraction":0.4726027397,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4706,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"M5StickCPlus.h\"\n#include \"CanonBLE.h\"\n#include \"Display.h\"\n#include \"TimeLapse_Management.h\"\n#include <Arduino.h>\n\n#define LOG_LOCAL_LEVEL ESP_LOG_INFO\n#include \"esp_log.h\"\n#include <esp32-hal-log.h>\n\nString name_remote = \"BR-M5\";\nDisplay M5_display(&M5.Lcd, name_remote);\nCanonBLE canon_ble(name_remote);\nTimeLapse timelapse(400);\n\nenum RemoteMode {Settings, Shooting}current_mode;\n\nvoid update_shooting()\n{\n    \/\/ Update timelapse\n    if (timelapse.TimeLapse_Trigger())\n    {\n        canon_ble.trigger();\n        Serial.println(\"Trigger tl\");\n    }\n\n    \/\/ Remote control\n    if (timelapse.get_interval() == 0) \/\/Single shots\n    {\n        if (M5.BtnA.wasReleased() && !M5.BtnB.wasReleased())\n        {\n            canon_ble.trigger();\n            Serial.println(\"Single shot\");\n        }\n    }\n    else \/\/ Timelapses\n    {\n        \/\/ Stop or start timelapse\n        if (M5.BtnA.wasReleased())\n        {\n            if (timelapse.Recording_OnOFF())\n            {\n                Serial.println(\"Start timelapse\");\n                M5_display.set_main_menu_screen(timelapse.get_interval(), \"Shooting timelapse\");\n            }\n            else\n            {\n                Serial.println(\"Stop timelapse\");\n                M5_display.set_main_menu_screen(timelapse.get_interval(), \"Ready for timelapse\");\n            }\n        }\n    }\n}\n\nvoid update_settings()\n{\n    if (M5.BtnA.wasReleased())\n    {\n        timelapse.TimeLapse_decDelay();\n        M5_display.set_main_menu_screen(timelapse.get_interval(), \"Setting interval\");\n    }\n    if (M5.BtnB.wasReleased())\n    {\n        timelapse.TimeLapse_incDelay();\n        M5_display.set_main_menu_screen(timelapse.get_interval(), \"Setting interval\");\n    }\n}\n\nvoid connect_loop(){\n    while (! canon_ble.is_ready_to_connect())\n    {\n        log_i(\"Scanning.\");\n        canon_ble.scan(5);\n    }\n\n\n    log_i(\"Canon device found: \");\n    Serial.println(canon_ble.get_device_address().toString().c_str());\n    log_i(\"Trying to connect.\");\n    if (canon_ble.connect_to_device())\n    {\n        log_i(\"Connected successfully\");\n        M5_display.set_address(canon_ble.get_device_address().toString().c_str());\n        M5_display.set_main_menu_screen(timelapse.get_interval(), \"Ready for single shot\");\n    }\n    else { \n        log_e(\"failed to connect\");\n    }\n}\n\nvoid trigger_loop(){\n    switch (current_mode)\n    {\n    case Settings:\n        if (M5.BtnB.pressedFor(700))\n        {\n            M5.BtnB.reset();\n            current_mode = Shooting;\n            String status = (timelapse.get_interval()==0)?\"Ready for single shot\":\"Ready for timelapse\";\n            M5_display.set_main_menu_screen(timelapse.get_interval(), status);\n        }\n        else\n        {\n            update_settings();\n        }\n        break;\n    \n    case Shooting:\n        if (M5.BtnB.pressedFor(700))\n        {\n            M5.BtnB.reset();\n            current_mode = Settings;\n            M5_display.set_main_menu_screen(timelapse.get_interval(), \"Setting interval\");\n        }\n        else\n        {\n            update_shooting();\n        }\n        break;\n\n    default:\n        break;\n    }\n}\n\nvoid try_connect() {\n    bool connected = false;\n    while (!connected) {\n        Serial.println(\"Trying to connect.\");\n        if (canon_ble.connect_to_device())\n        {\n            Serial.println(\"Connected successfully\");\n            connected = true; \n        }\n        else { \n            Serial.println(\"Failed to connect.\");\n        }\n    }\n}\n\nvoid test_reconnect() {\n    while (! canon_ble.is_ready_to_connect())\n    {\n        log_i(\"Scanning.\");\n        canon_ble.scan(5);\n    }\n\n    Serial.println(canon_ble.get_device_address().toString().c_str());\n\n    for (int i = 0; i < 100; i++) {\n        try_connect();\n        delay(200);\n        if (canon_ble.is_connected()) {\n            log_i(\"connection successful\");\n        } else {\n            log_e(\"connection failed\");\n        }\n\n        delay(500);\n\n        canon_ble.disconnect();\n        delay(200);\n        if (!canon_ble.is_connected()) {\n            log_i(\"disconnection successful\");\n        } else {\n            log_e(\"disconnection failed\");\n        }\n\n        delay(500);\n    }\n}\n\nvoid loop()\n{\n    \/\/ Update buttons state\n    M5.update();\n\n    \/\/ Check connection state\n    \/\/ If disconnected, bump back to connecting\n    if (canon_ble.is_connected()) {\n        trigger_loop();\n    }\n    else {\n        M5_display.set_init_screen();\n        connect_loop();\n    }\n\n    \n    delay(10);\n}\n\nvoid setup()\n{\n    esp_log_level_set(\"*\", ESP_LOG_INFO); \n\n    M5.begin();\n    current_mode = Shooting;\n    M5.Axp.ScreenBreath(9);\n    M5.Lcd.setRotation(1);\n    M5_display.set_init_screen();\n\n    connect_loop();\n}","avg_line_length":23.1822660099,"max_line_length":104,"alphanum_fraction":0.5703357416,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7187,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Linux-OpenIB"],"max_stars_count":3.0,"content":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\tCreated\t\t: 28.12.2009\r\n\/\/\tAuthor\t\t: Sergey Chechin\r\n\/\/\tCopyright (C) GSC Game World - 2009\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n#include \"pch.h\"\r\n#include <xray\/resources_query_result.h>\r\n#include \"resources_manager.h\"\r\n\r\nnamespace xray {\r\nnamespace resources {\r\n\r\nusing namespace fs;\r\n\r\nbool   query_result::is_translate_query () const\r\n{\r\n\treturn\t\t\t\t\t\t\t\t!!cook_base::find_translate_query_cook(m_class_id);\r\n}\r\n\r\nvoid   query_result::translate_request_path ()\r\n{\r\n\tcook_base * const\tcook\t\t=\tg_resources_manager->find_cook(m_class_id);\r\n\tif ( !cook )\r\n\t\treturn;\r\n\r\n\tfs::path_string\t\tnew_path;\r\n\tcook->translate_request_path\t\t(get_requested_path(), new_path);\r\n\tR_ASSERT\t\t\t\t\t\t\t(new_path.length());\r\n\r\n\tif ( new_path != get_requested_path() )\r\n\t{\r\n\t\tm_request_path\t\t\t\t=\t(pstr)XRAY_ALLOC_IMPL(* m_user_allocator, char, new_path.length()+1);\r\n\t\tstrings::copy\t\t\t\t\t(m_request_path, new_path.length()+1, new_path.c_str());\r\n\t\tset_flag\t\t\t\t\t\t(flag_should_free_request_path);\r\n\t}\r\n}\r\n\r\nvoid   query_result_for_cook::set_request_path (pcstr path)\r\n{\r\n\tstrings::copy\t\t\t\t\t\t(m_request_path, m_request_path_max_size, path);\r\n}\r\n\r\nfs::path_string   query_result_for_user::get_full_path () const \r\n{\r\n\tfs::path_string path;\r\n\tfat_iterator\tfat_it\t\t\t=\twrapper_to_fat_it(m_fat_it);\r\n\treturn\t\t\t\t\t\t\t\tfat_it.get_full_path();\r\n}\r\n\r\nbool   query_result::next_item_in_request_path (request_path_iterator & out_it) const\r\n{\r\n\tif ( !get_requested_path() )\r\n\t\treturn\t\t\t\t\t\t\tfalse;\r\n\r\n\tif ( !out_it.iterator )\r\n\t\tout_it.iterator\t\t\t\t=\tget_requested_path();\r\n\r\n\tif ( ! * out_it.iterator )\r\n\t\treturn\t\t\t\t\t\t\tfalse;\r\n\r\n\tpcstr const next_item_separator\t=\tstrchr(out_it.iterator, request::path_separator);\r\n\tif ( next_item_separator )\r\n\t{\r\n\t\tout_it.item.assign\t\t\t\t(out_it.iterator, next_item_separator);\r\n\t\tout_it.iterator\t\t\t\t=\tnext_item_separator + 1;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tout_it.item\t\t\t\t\t=\tout_it.iterator;\r\n\t\tout_it.iterator\t\t\t\t=\tout_it.iterator + strings::length(out_it.iterator);\r\n\t}\r\n\r\n\treturn\t\t\t\t\t\t\t\ttrue;\r\n}\r\n\r\nbool   query_result::has_same_item_in_request_path (query_result const & other_request_path) const\r\n{\r\n\trequest_path_iterator\t\t\t\tit;\r\n\twhile ( next_item_in_request_path(it) )\r\n\t{\r\n\t\trequest_path_iterator\t\t\tother_it;\r\n\t\twhile ( other_request_path.next_item_in_request_path(other_it) )\r\n\t\t{\r\n\t\t\tif ( it.item == other_it.item )\r\n\t\t\t\treturn\t\t\t\t\ttrue;\r\n\t\t}\r\n\t}\r\n\r\n\treturn\t\t\t\t\t\t\t\tfalse;\r\n}\r\n\r\nsignalling_bool   query_result::select_disk_path_from_request_path (buffer_string * out_disk_path) const\r\n{\r\n\trequest_path_iterator\t\t\t\tit;\r\n\twhile ( next_item_in_request_path(it) )\r\n\t{\r\n\t\tif ( fs::g_fat->get_disk_path_to_store_file(it.item.c_str(), out_disk_path) )\r\n\t\t{\r\n\t\t\tstrings::copy\t\t\t\t(m_request_path, m_request_path_max_size, it.item.c_str());\r\n\t\t\treturn\t\t\t\t\t\ttrue;\r\n\t\t}\r\n\t}\r\n\r\n\tFATAL\t\t\t\t\t\t\t\t(\"omg! none of request_path items '%s' are mounted to disk - cannot select disk path!\", \r\n\t\t\t\t\t\t\t\t\t\t get_requested_path());\r\n\r\n\treturn\t\t\t\t\t\t\t\tfalse;\r\n}\r\n\r\n\r\n\/\/-----------------------------------------------\r\n\/\/ misc code\r\n\/\/-----------------------------------------------\r\n\r\nfs::path_string   get_native_file_path (query_result const * query, bool assert_on_fail) \r\n{\r\n\tXRAY_UNREFERENCED_PARAMETER\t\t\t( assert_on_fail );\r\n\r\n\tif ( query->is_save_type() )\r\n\t{\r\n\t\tfs::path_string\tdisk_path;\r\n\t\tbool const result\t\t\t=\tquery->select_disk_path_from_request_path(& disk_path);\r\n\t\tXRAY_UNREFERENCED_PARAMETER\t\t( result );\r\n\t\tR_ASSERT\t\t\t\t\t\t(result);\r\n\t\treturn\t\t\t\t\t\t\tconvert_to_native(disk_path.c_str());\r\n\t}\r\n\r\n\tusing namespace\t\t\t\t\t\tfs;\r\n\tfat_iterator const it\t\t\t=\twrapper_to_fat_it(query->get_fat_it());\r\n\tpath_string\t\t\t\t\t\t\tpath;\r\n\tg_fat->get_disk_path\t\t\t\t(it, path);\r\n\r\n\tR_ASSERT\t\t\t\t\t\t\t(path.length() || !assert_on_fail);\r\n\r\n\tif ( query->is_replication_type() )\r\n\t{\r\n\t\tpath_string\t\t\t\t\t\treplicated_path;\r\n\t\tg_fat->replicate_path\t\t\t(path.c_str(), replicated_path);\r\n\t\treturn\t\t\t\t\t\t\tconvert_to_native(replicated_path.c_str());\r\n\t}\r\n\r\n\treturn\t\t\t\t\t\t\t\tpath.length() ? convert_to_native(path.c_str()) : \"\";\r\n}\r\n\r\nvoid   query_result::process_request_path ()\r\n{\r\n\tif ( has_flag(flag_processed_request_path) )\r\n\t\treturn;\r\n\r\n\tunlock_fat_it\t\t\t\t\t\t();\r\n\r\n\tset_flag\t\t\t\t\t\t\t(flag_processed_request_path);\r\n\tpstr\tcur_path\t\t\t\t=\tm_request_path;\r\n\tfile_system::iterator\tfat_it;\r\n\tfat_it.set_end\t\t\t\t\t\t();\r\n\r\n\twhile ( cur_path )\r\n\t{\r\n\t\tpstr const separator_pos\t=\tstrchr(cur_path, request::path_separator);\r\n\t\tif ( separator_pos )\r\n\t\t\t*separator_pos\t\t\t=\tNULL;\r\n\r\n\t\tif ( *cur_path == physical_path_char )\r\n\t\t{\r\n\t\t\tif ( threading::current_thread_id() == m_user_thread_id )\r\n\t\t\t\tm_temp_disk_fat_it_allocator\t=\tm_user_allocator;\r\n\t\t\telse\r\n\t\t\t\tm_temp_disk_fat_it_allocator\t=\t& memory::g_mt_allocator;\r\n\r\n\t\t\tfat_it\t\t\t\t\t=\tg_fat->create_temp_disk_it(m_temp_disk_fat_it_allocator, cur_path+1);\r\n\t\t\tif ( fat_it != g_fat->end() )\r\n\t\t\t\tset_flag\t\t\t\t(flag_uses_physical_path);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif ( get_create_resource_result() == cook_base::result_requery )\r\n\t\t\t\tg_fat->mount_disk_node_by_logical_path\t(cur_path);\r\n\r\n\t\t\tfat_it\t\t\t\t\t=\tg_fat->find(cur_path);\r\n\t\t}\r\n\r\n\t\tif ( fat_it != g_fat->end() && !fat_it.is_folder() )\r\n\t\t{\r\n\t\t\tif ( cur_path != m_request_path )\r\n\t\t\t{\r\n\t\t\t\tpstr\t\t\t\t\tpath\t=\tNULL;\r\n\t\t\t\tSTR_JOINA\t\t\t\t(path, cur_path);\r\n\t\t\t\t\/\/ we're sure buffer is ok\r\n\t\t\t\tstrings::copy\t\t\t(m_request_path, strings::length(path)+1, path);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\tif ( separator_pos )\r\n\t\t{\r\n\t\t\t*separator_pos\t\t\t=\trequest::path_separator;\r\n\t\t\tcur_path\t\t\t\t=\tseparator_pos + 1;\r\n\t\t}\r\n\t\telse\r\n\t\t\tbreak;\r\n\t}\r\n\r\n\tm_fat_it\t\t\t\t\t\t=\tfat_it_to_wrapper(fat_it);\r\n\r\n\tlock_fat_it\t\t\t\t\t\t\t();\r\n}\r\n\r\nvoid   query_result::lock_fat_it ()\r\n{\r\n\tfile_system::iterator\tfat_it\t=\twrapper_to_fat_it(m_fat_it);\r\n\tif ( fat_it.is_end() )\r\n\t\treturn;\r\n\r\n\tR_ASSERT\t\t\t\t\t\t\t(!has_flag(flag_locked_fat_iterator));\r\n\tset_flag\t\t\t\t\t\t\t(flag_locked_fat_iterator);\r\n\tg_resources_manager->change_count_of_pending_query_with_fat_it (+1);\r\n\tfat_it.set_is_locked\t\t\t\t(true);\r\n}\r\n\r\nvoid   query_result::unlock_fat_it ()\r\n{\r\n\tfile_system::iterator\tfat_it\t=\twrapper_to_fat_it(m_fat_it);\r\n\tif ( fat_it.is_end() )\r\n\t{\r\n\t\tR_ASSERT\t\t\t\t\t\t(!has_flag(flag_locked_fat_iterator));\r\n\t\treturn;\r\n\t}\r\n\r\n\tR_ASSERT\t\t\t\t\t\t\t(has_flag(flag_locked_fat_iterator));\r\n\tunset_flag\t\t\t\t\t\t\t(flag_locked_fat_iterator);\r\n\tg_resources_manager->change_count_of_pending_query_with_fat_it (-1);\r\n\tfat_it.set_is_locked\t\t\t\t(false);\r\n}\r\n\r\nvoid   query_result::late_set_fat_it (fat_it_wrapper const it)\r\n{\r\n\tfat_iterator const previous_it\t=\twrapper_to_fat_it(m_fat_it);\r\n\tfat_iterator new_it\t\t\t\t=\twrapper_to_fat_it(it);\r\n\tif ( previous_it == new_it )\r\n\t\treturn;\r\n\r\n\tR_ASSERT\t\t\t\t\t\t\t(previous_it.is_end());\r\n\tR_ASSERT\t\t\t\t\t\t\t(!has_flag(flag_locked_fat_iterator));\r\n\tm_fat_it\t\t\t\t\t\t=\tit;\r\n\r\n\tset_flag\t\t\t\t\t\t\t(flag_locked_fat_iterator);\r\n\tg_resources_manager->change_count_of_pending_query_with_fat_it (+1);\r\n\tnew_it.set_is_locked\t\t\t\t(true);\r\n\r\n\tif ( m_raw_managed_resource )\r\n\t\tm_raw_managed_resource->late_set_fat_it\t\t(it);\r\n\r\n\tif ( m_managed_resource )\r\n\t\tm_managed_resource->late_set_fat_it\t\t\t(it);\r\n\r\n\tif ( m_unmanaged_resource )\r\n\t\tm_unmanaged_resource->late_set_fat_it\t\t(it);\r\n}\r\n\r\n} \/\/ namespace resources\r\n} \/\/ namespace xray\r\n\r\n","avg_line_length":27.2234848485,"max_line_length":105,"alphanum_fraction":0.6538193961,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6958,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0","MIT"],"max_stars_count":1.0,"content":"\/*\n * Copyright (c) Contributors to the Open 3D Engine Project.\n * For complete copyright and license terms please see the LICENSE at the root of this distribution.\n *\n * SPDX-License-Identifier: Apache-2.0 OR MIT\n *\n *\/\n\n#include \"UserTypes.h\"\n\n#include <AzCore\/std\/parallel\/thread.h>\n#include <AzCore\/std\/parallel\/containers\/lock_free_queue.h>\n#include <AzCore\/std\/parallel\/containers\/lock_free_stamped_queue.h>\n#include <AzCore\/std\/functional.h>\n#include <AzCore\/std\/smart_ptr\/shared_ptr.h>\n\n\nnamespace UnitTest\n{\n    using namespace AZStd;\n    using namespace UnitTestInternal;\n\n    class LockFreeQueue\n        : public AllocatorsFixture\n    {\n    public:\n        LockFreeQueue() : AllocatorsFixture() {}\n\n    protected:\n#ifdef _DEBUG\n        static const int NUM_ITERATIONS = 5000;\n#else\n        static const int NUM_ITERATIONS = 100000;\n#endif\n    public:\n        template <class Q>\n        void Push(Q* queue)\n        {\n            for (int i = 0; i < NUM_ITERATIONS; ++i)\n            {\n                queue->push(i);\n            }\n        }\n\n        template <class Q>\n        void Pop(Q* queue)\n        {\n            int expected = 0;\n            while (expected < NUM_ITERATIONS)\n            {\n                typename Q::value_type value = NUM_ITERATIONS;\n                if (queue->pop(&value))\n                {\n                    if (value == expected)\n                    {\n                        ++m_counter;\n                    }\n                    ++expected;\n                }\n            }\n        }\n\n        atomic<int> m_counter;\n    };\n\n    TEST_F(LockFreeQueue, LockFreeQueue)\n    {\n        lock_free_queue<int, MyLockFreeAllocator> queue;\n        int result;\n        AZ_TEST_ASSERT(queue.empty());\n        AZ_TEST_ASSERT(!queue.pop(&result));\n\n        queue.push(20);\n        AZ_TEST_ASSERT(!queue.empty());\n        AZ_TEST_ASSERT(queue.pop(&result));\n        AZ_TEST_ASSERT(result == 20);\n        AZ_TEST_ASSERT(queue.empty());\n        AZ_TEST_ASSERT(!queue.pop(&result));\n\n        queue.push(20);\n        queue.push(30);\n        AZ_TEST_ASSERT(!queue.empty());\n        AZ_TEST_ASSERT(queue.pop(&result));\n        AZ_TEST_ASSERT(result == 20);\n        AZ_TEST_ASSERT(!queue.empty());\n        AZ_TEST_ASSERT(queue.pop(&result));\n        AZ_TEST_ASSERT(result == 30);\n        AZ_TEST_ASSERT(queue.empty());\n        AZ_TEST_ASSERT(!queue.pop(&result));\n\n        {\n            m_counter = 0;\n            AZStd::thread thread0(AZStd::bind(&LockFreeQueue::Push<decltype(queue)>, this, &queue));\n            AZStd::thread thread1(AZStd::bind(&LockFreeQueue::Pop<decltype(queue)>, this, &queue));\n            thread0.join();\n            thread1.join();\n            AZ_TEST_ASSERT(m_counter == NUM_ITERATIONS);\n            AZ_TEST_ASSERT(queue.empty());\n        }\n    }\n\n\n    struct SharedInt {\n        SharedInt() : m_ptr(nullptr) {}\n        SharedInt(int i) : m_ptr(new int(i)) {}\n        bool operator==(const SharedInt& other) \n        {\n            if (!m_ptr || !other.m_ptr) \n            { \n                return false; \n            }\n            return *m_ptr == *other.m_ptr;\n        }\n    private:\n        AZStd::shared_ptr<int> m_ptr;\n    };\n\n    TEST_F(LockFreeQueue, LockFreeQueueNonTrivialDestructor)\n    {\n        lock_free_queue<SharedInt, MyLockFreeAllocator> queue;\n        SharedInt result;\n        AZ_TEST_ASSERT(queue.empty());\n        AZ_TEST_ASSERT(!queue.pop(&result));\n\n        queue.push(20);\n        AZ_TEST_ASSERT(!queue.empty());\n        AZ_TEST_ASSERT(queue.pop(&result));\n        AZ_TEST_ASSERT(result == 20);\n        AZ_TEST_ASSERT(queue.empty());\n        AZ_TEST_ASSERT(!queue.pop(&result));\n\n        queue.push(20);\n        queue.push(30);\n        AZ_TEST_ASSERT(!queue.empty());\n        AZ_TEST_ASSERT(queue.pop(&result));\n        AZ_TEST_ASSERT(result == 20);\n        AZ_TEST_ASSERT(!queue.empty());\n        AZ_TEST_ASSERT(queue.pop(&result));\n        AZ_TEST_ASSERT(result == 30);\n        AZ_TEST_ASSERT(queue.empty());\n        AZ_TEST_ASSERT(!queue.pop(&result));\n\n        {\n            m_counter = 0;\n            AZStd::thread thread0(AZStd::bind(&LockFreeQueue::Push<decltype(queue)>, this, &queue));\n            AZStd::thread thread1(AZStd::bind(&LockFreeQueue::Pop<decltype(queue)>, this, &queue));\n            thread0.join();\n            thread1.join();\n            AZ_TEST_ASSERT(m_counter == NUM_ITERATIONS);\n            AZ_TEST_ASSERT(queue.empty());\n        }\n    }\n\n    TEST_F(LockFreeQueue, LockFreeStampedQueue)\n    {\n        lock_free_stamped_queue<int, MyLockFreeAllocator> queue;\n\n        int result;\n        AZ_TEST_ASSERT(queue.empty());\n        AZ_TEST_ASSERT(!queue.pop(&result));\n\n        queue.push(20);\n        AZ_TEST_ASSERT(!queue.empty());\n        AZ_TEST_ASSERT(queue.pop(&result));\n        AZ_TEST_ASSERT(result == 20);\n        AZ_TEST_ASSERT(queue.empty());\n        AZ_TEST_ASSERT(!queue.pop(&result));\n\n        queue.push(20);\n        queue.push(30);\n        AZ_TEST_ASSERT(!queue.empty());\n        AZ_TEST_ASSERT(queue.pop(&result));\n        AZ_TEST_ASSERT(result == 20);\n        AZ_TEST_ASSERT(!queue.empty());\n        AZ_TEST_ASSERT(queue.pop(&result));\n        AZ_TEST_ASSERT(result == 30);\n        AZ_TEST_ASSERT(queue.empty());\n        AZ_TEST_ASSERT(!queue.pop(&result));\n\n        {\n            m_counter = 0;\n            AZStd::thread thread0(AZStd::bind(&LockFreeQueue::Push<decltype(queue)>, this, &queue));\n            AZStd::thread thread1(AZStd::bind(&LockFreeQueue::Pop<decltype(queue)>, this, &queue));\n            thread0.join();\n            thread1.join();\n            AZ_TEST_ASSERT(m_counter == NUM_ITERATIONS);\n            AZ_TEST_ASSERT(queue.empty());\n        }\n    }\n\n    TEST_F(LockFreeQueue, LockFreeStampedQueueNonTrivialDestructor)\n    {\n        lock_free_stamped_queue<SharedInt, MyLockFreeAllocator> queue;\n\n        SharedInt result;\n        AZ_TEST_ASSERT(queue.empty());\n        AZ_TEST_ASSERT(!queue.pop(&result));\n\n        queue.push(20);\n        AZ_TEST_ASSERT(!queue.empty());\n        AZ_TEST_ASSERT(queue.pop(&result));\n        AZ_TEST_ASSERT(result == 20);\n        AZ_TEST_ASSERT(queue.empty());\n        AZ_TEST_ASSERT(!queue.pop(&result));\n\n        queue.push(20);\n        queue.push(30);\n        AZ_TEST_ASSERT(!queue.empty());\n        AZ_TEST_ASSERT(queue.pop(&result));\n        AZ_TEST_ASSERT(result == 20);\n        AZ_TEST_ASSERT(!queue.empty());\n        AZ_TEST_ASSERT(queue.pop(&result));\n        AZ_TEST_ASSERT(result == 30);\n        AZ_TEST_ASSERT(queue.empty());\n        AZ_TEST_ASSERT(!queue.pop(&result));\n\n        {\n            m_counter = 0;\n            AZStd::thread thread0(AZStd::bind(&LockFreeQueue::Push<decltype(queue)>, this, &queue));\n            AZStd::thread thread1(AZStd::bind(&LockFreeQueue::Pop<decltype(queue)>, this, &queue));\n            thread0.join();\n            thread1.join();\n\n            AZ_TEST_ASSERT(m_counter == NUM_ITERATIONS);\n            AZ_TEST_ASSERT(queue.empty());\n        }\n    }\n}\n","avg_line_length":30.384279476,"max_line_length":100,"alphanum_fraction":0.5737280828,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":458079,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/-------------------------------------------------------------------------------------------------------\n\/\/ Copyright (C) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n\/\/-------------------------------------------------------------------------------------------------------\n#include \"ParserPch.h\"\n#include \"FormalsUtil.h\"\n#include \"..\/Runtime\/Language\/SourceDynamicProfileManager.h\"\n\n#if DBG_DUMP\nvoid PrintPnodeWIndent(ParseNode *pnode,int indentAmt);\n#endif\n\nconst char* const nopNames[knopLim]= {\n#define PTNODE(nop,sn,pc,nk,grfnop,json) sn,\n#include \"ptlist.h\"\n};\nvoid printNop(int nop) {\n  printf(\"%s\\n\",nopNames[nop]);\n}\n\nconst uint ParseNode::mpnopgrfnop[knopLim] =\n{\n#define PTNODE(nop,sn,pc,nk,grfnop,json) grfnop,\n#include \"ptlist.h\"\n};\n\nbool Parser::IsES6DestructuringEnabled() const\n{\n    return m_scriptContext->GetConfig()->IsES6DestructuringEnabled();\n}\n\nstruct DeferredFunctionStub\n{\n    RestorePoint restorePoint;\n    uint fncFlags;\n    uint nestedCount;\n    DeferredFunctionStub *deferredStubs;\n    charcount_t ichMin;\n};\n\nstruct StmtNest\n{\n    union\n    {\n        struct\n        {\n            ParseNodePtr pnodeStmt; \/\/ This statement node.\n            ParseNodePtr pnodeLab;  \/\/ Labels for this statement.\n        };\n        struct\n        {\n            bool isDeferred : 1;\n            OpCode op;              \/\/ This statement operation.\n            LabelId* pLabelId;      \/\/ Labels for this statement.\n        };\n    };\n    StmtNest *pstmtOuter;           \/\/ Enclosing statement.\n};\n\nstruct BlockInfoStack\n{\n    StmtNest pstmt;\n    ParseNode *pnodeBlock;\n    ParseNodePtr *m_ppnodeLex;              \/\/ lexical variable list tail\n    BlockInfoStack *pBlockInfoOuter;        \/\/ containing block's BlockInfoStack\n    BlockInfoStack *pBlockInfoFunction;     \/\/ nearest function's BlockInfoStack (if pnodeBlock is a function, this points to itself)\n};\n\n#if DEBUG\nParser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground, size_t size)\n#else\nParser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground)\n#endif\n    : m_nodeAllocator(_u(\"Parser\"), alloc ? alloc : scriptContext->GetThreadContext()->GetPageAllocator(), Parser::OutOfMemory),\n    \/\/ use the GuestArena directly for keeping the RegexPattern* alive during byte code generation\n    m_registeredRegexPatterns(scriptContext->GetGuestArena())\n{\n    AssertMsg(size == sizeof(Parser), \"verify conditionals affecting the size of Parser agree\");\n    Assert(scriptContext != nullptr);\n    m_isInBackground = isBackground;\n    m_phtbl = nullptr;\n    m_pscan = nullptr;\n    m_deferringAST = FALSE;\n    m_stoppedDeferredParse = FALSE;\n    m_hasParallelJob = false;\n    m_doingFastScan = false;\n    m_scriptContext = scriptContext;\n    m_pCurrentAstSize = nullptr;\n    m_arrayDepth = 0;\n    m_funcInArrayDepth = 0;\n    m_parenDepth = 0;\n    m_funcInArray = 0;\n    m_tryCatchOrFinallyDepth = 0;\n    m_UsesArgumentsAtGlobal = false;\n    m_currentNodeFunc = nullptr;\n    m_currentNodeDeferredFunc = nullptr;\n    m_currentNodeNonLambdaFunc = nullptr;\n    m_currentNodeNonLambdaDeferredFunc = nullptr;\n    m_currentNodeProg = nullptr;\n    m_currDeferredStub = nullptr;\n    m_prevSiblingDeferredStub = nullptr;\n    m_pstmtCur = nullptr;\n    m_currentBlockInfo = nullptr;\n    m_currentScope = nullptr;\n    m_currentDynamicBlock = nullptr;\n    m_grfscr = fscrNil;\n    m_length = 0;\n    m_originalLength = 0;\n    m_nextFunctionId = nullptr;\n    m_errorCallback = nullptr;\n    m_uncertainStructure = FALSE;\n    currBackgroundParseItem = nullptr;\n    backgroundParseItems = nullptr;\n    fastScannedRegExpNodes = nullptr;\n\n    m_fUseStrictMode = strictMode;\n    m_InAsmMode = false;\n    m_deferAsmJs = true;\n    m_scopeCountNoAst = 0;\n    m_fExpectExternalSource = 0;\n\n    m_parseType = ParseType_Upfront;\n\n    m_deferEllipsisError = false;\n    m_hasDeferredShorthandInitError = false;\n    m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperDisallowed;\n}\n\nParser::~Parser(void)\n{\n    if (m_scriptContext == nullptr || m_scriptContext->GetGuestArena() == nullptr)\n    {\n        \/\/ If the scriptContext or guestArena have gone away, there is no point clearing each item of this list.\n        \/\/ Just reset it so that destructor of the SList will be no-op\n        m_registeredRegexPatterns.Reset();\n    }\n\n    if (this->m_hasParallelJob)\n    {\n#if ENABLE_BACKGROUND_PARSING\n        \/\/ Let the background threads know that they can decommit their arena pages.\n        BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();\n        Assert(bgp);\n        if (bgp->Processor()->ProcessesInBackground())\n        {\n            JsUtil::BackgroundJobProcessor *processor = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor());\n\n            bool result = processor->IterateBackgroundThreads([&](JsUtil::ParallelThreadData *threadData)->bool {\n                threadData->canDecommit = true;\n                return false;\n            });\n            Assert(result);\n        }\n#endif\n    }\n\n    Release();\n\n}\n\nvoid Parser::OutOfMemory()\n{\n    throw ParseExceptionObject(ERRnoMemory);\n}\n\nvoid Parser::Error(HRESULT hr)\n{\n    Assert(FAILED(hr));\n    m_err.Throw(hr);\n}\n\nvoid Parser::Error(HRESULT hr, ParseNodePtr pnode)\n{\n    if (pnode && pnode->ichLim)\n    {\n        Error(hr, pnode->ichMin, pnode->ichLim);\n    }\n    else\n    {\n        Error(hr);\n    }\n}\n\nvoid Parser::Error(HRESULT hr, charcount_t ichMin, charcount_t ichLim)\n{\n    m_pscan->SetErrorPosition(ichMin, ichLim);\n    Error(hr);\n}\n\nvoid Parser::IdentifierExpectedError(const Token& token)\n{\n    Assert(token.tk != tkID);\n\n    HRESULT hr;\n    if (token.IsReservedWord())\n    {\n        if (token.IsKeyword())\n        {\n            hr = ERRKeywordNotId;\n        }\n        else\n        {\n            Assert(token.IsFutureReservedWord(true));\n            if (token.IsFutureReservedWord(false))\n            {\n                \/\/ Future reserved word in strict and non-strict modes\n                hr = ERRFutureReservedWordNotId;\n            }\n            else\n            {\n                \/\/ Future reserved word only in strict mode. The token would have been converted to tkID by the scanner if not\n                \/\/ in strict mode.\n                Assert(IsStrictMode());\n                hr = ERRFutureReservedWordInStrictModeNotId;\n            }\n        }\n    }\n    else\n    {\n        hr = ERRnoIdent;\n    }\n\n    Error(hr);\n}\n\nHRESULT Parser::ValidateSyntax(LPCUTF8 pszSrc, size_t encodedCharCount, bool isGenerator, bool isAsync, CompileScriptException *pse, void (Parser::*validateFunction)())\n{\n    AssertPsz(pszSrc);\n    AssertMemN(pse);\n\n    if (this->IsBackgroundParser())\n    {\n        PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);\n    }\n    else\n    {\n        PROBE_STACK(m_scriptContext, Js::Constants::MinStackDefault);\n    }\n\n    HRESULT hr;\n    SmartFPUControl smartFpuControl;\n\n    DebugOnly( m_err.fInited = TRUE; )\n    BOOL fDeferSave = m_deferringAST;\n    try\n    {\n        hr = NOERROR;\n\n        this->PrepareScanner(false);\n\n        m_length = encodedCharCount;\n        m_originalLength = encodedCharCount;\n\n        \/\/ make sure deferred parsing is turned off\n        ULONG grfscr = fscrNil;\n\n        \/\/ Give the scanner the source and get the first token\n        m_pscan->SetText(pszSrc, 0, encodedCharCount, 0, grfscr);\n        m_pscan->SetYieldIsKeyword(isGenerator);\n        m_pscan->SetAwaitIsKeyword(isAsync);\n        m_pscan->Scan();\n\n        uint nestedCount = 0;\n        m_pnestedCount = &nestedCount;\n\n        ParseNodePtr pnodeScope = nullptr;\n        m_ppnodeScope = &pnodeScope;\n        m_ppnodeExprScope = nullptr;\n\n        uint nextFunctionId = 0;\n        m_nextFunctionId = &nextFunctionId;\n\n        m_inDeferredNestedFunc = false;\n        m_deferringAST = true;\n\n\n\n        m_nextBlockId = 0;\n\n        ParseNode *pnodeFnc = CreateNode(knopFncDecl);\n        pnodeFnc->sxFnc.ClearFlags();\n        pnodeFnc->sxFnc.SetDeclaration(false);\n        pnodeFnc->sxFnc.functionId   = 0;\n        pnodeFnc->sxFnc.astSize      = 0;\n        pnodeFnc->sxFnc.pnodeVars    = nullptr;\n        pnodeFnc->sxFnc.pnodeParams  = nullptr;\n        pnodeFnc->sxFnc.pnodeBody    = nullptr;\n        pnodeFnc->sxFnc.pnodeName    = nullptr;\n        pnodeFnc->sxFnc.pnodeRest    = nullptr;\n        pnodeFnc->sxFnc.deferredStub = nullptr;\n        pnodeFnc->sxFnc.SetIsGenerator(isGenerator);\n        pnodeFnc->sxFnc.SetIsAsync(isAsync);\n        m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;\n        m_currentNodeFunc = pnodeFnc;\n        m_currentNodeDeferredFunc = NULL;\n        m_sourceContextInfo = nullptr;\n        AssertMsg(m_pstmtCur == NULL, \"Statement stack should be empty when we start parse function body\");\n\n        ParseNodePtr block = StartParseBlock<false>(PnodeBlockType::Function, ScopeType_FunctionBody);\n        (this->*validateFunction)();\n        FinishParseBlock(block);\n\n        pnodeFnc->ichLim = m_pscan->IchLimTok();\n        pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();\n        pnodeFnc->sxFnc.pnodeVars = nullptr;\n\n        \/\/ there should be nothing after successful parsing for a given construct\n        if (m_token.tk != tkEOF)\n            Error(ERRsyntax);\n\n        RELEASEPTR(m_pscan);\n        m_deferringAST = fDeferSave;\n    }\n    catch(ParseExceptionObject& e)\n    {\n        m_deferringAST = fDeferSave;\n        m_err.m_hr = e.GetError();\n        hr = pse->ProcessError( m_pscan,  m_err.m_hr, \/* pnodeBase *\/ NULL);\n    }\n\n    return hr;\n}\n\nHRESULT Parser::ParseSourceInternal(\n    __out ParseNodePtr* parseTree, LPCUTF8 pszSrc, size_t offsetInBytes, size_t encodedCharCount, charcount_t offsetInChars,\n    bool fromExternal, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo)\n{\n    AssertMem(parseTree);\n    AssertPsz(pszSrc);\n    AssertMemN(pse);\n   \n    if (this->IsBackgroundParser())\n    {\n        PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);\n    }\n    else\n    {\n        PROBE_STACK(m_scriptContext, Js::Constants::MinStackDefault);\n    }\n\n#ifdef PROFILE_EXEC\n    m_scriptContext->ProfileBegin(Js::ParsePhase);\n#endif\n    JS_ETW(EventWriteJSCRIPT_PARSE_START(m_scriptContext,0));\n\n    *parseTree = NULL;\n    m_sourceLim = 0;\n\n    m_grfscr = grfscr;\n    m_sourceContextInfo = sourceContextInfo;\n\n    ParseNodePtr pnodeBase = NULL;\n    HRESULT hr;\n    SmartFPUControl smartFpuControl;\n\n    DebugOnly( m_err.fInited = TRUE; )\n\n    try\n    {\n        this->PrepareScanner(fromExternal);\n\n        if ((grfscr & fscrEvalCode) != 0)\n        {\n            \/\/ This makes the parser to believe when eval() is called, it accept any super access in global scope.\n            this->m_parsingSuperRestrictionState = Parser::ParsingSuperRestrictionState_SuperCallAndPropertyAllowed;\n        }\n\n        if ((grfscr & fscrIsModuleCode) != 0)\n        {\n            \/\/ Module source flag should not be enabled unless module is enabled\n            Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());\n\n            \/\/ Module code is always strict mode code.\n            this->m_fUseStrictMode = TRUE;\n        }\n\n        \/\/ parse the source\n        pnodeBase = Parse(pszSrc, offsetInBytes, encodedCharCount, offsetInChars, grfscr, lineNumber, nextFunctionId, pse);\n\n        AssertNodeMem(pnodeBase);\n\n        \/\/ Record the actual number of words parsed.\n        m_sourceLim = pnodeBase->ichLim - offsetInChars;\n\n        \/\/ TODO: The assert can be false positive in some scenarios and chuckj to fix it later\n        \/\/ Assert(utf8::ByteIndexIntoCharacterIndex(pszSrc + offsetInBytes, encodedCharCount, fromExternal ? utf8::doDefault : utf8::doAllowThreeByteSurrogates) == m_sourceLim);\n\n#if DBG_DUMP\n        if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::ParsePhase))\n        {\n            PrintPnodeWIndent(pnodeBase,4);\n            fflush(stdout);\n        }\n#endif\n\n        *parseTree = pnodeBase;\n\n        hr = NOERROR;\n    }\n    catch(ParseExceptionObject& e)\n    {\n        m_err.m_hr = e.GetError();\n        hr = pse->ProcessError( m_pscan, m_err.m_hr, pnodeBase);\n    }\n\n    if (this->m_hasParallelJob)\n    {\n#if ENABLE_BACKGROUND_PARSING\n        \/\/\/\/\/ Wait here for remaining jobs to finish. Then look for errors, do final const bindings.\n        \/\/ pleath TODO: If there are remaining jobs, let the main thread help finish them.\n        BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();\n        Assert(bgp);\n\n        CompileScriptException se;\n        this->WaitForBackgroundJobs(bgp, &se);\n\n        BackgroundParseItem *failedItem = bgp->GetFailedBackgroundParseItem();\n        if (failedItem)\n        {\n            CompileScriptException *bgPse = failedItem->GetPSE();\n            Assert(bgPse);\n            *pse = *bgPse;\n            hr = failedItem->GetHR();\n            bgp->SetFailedBackgroundParseItem(nullptr);\n        }\n\n        if (this->fastScannedRegExpNodes != nullptr)\n        {\n            this->FinishBackgroundRegExpNodes();\n        }\n\n        for (BackgroundParseItem *item = this->backgroundParseItems; item; item = item->GetNext())\n        {\n            Parser *parser = item->GetParser();\n            parser->FinishBackgroundPidRefs(item, this != parser);\n        }\n#endif\n    }\n\n    \/\/ done with the scanner\n    RELEASEPTR(m_pscan);\n\n#ifdef PROFILE_EXEC\n    m_scriptContext->ProfileEnd(Js::ParsePhase);\n#endif\n    JS_ETW(EventWriteJSCRIPT_PARSE_STOP(m_scriptContext, 0));\n    \n    return hr;\n}\n\n#if ENABLE_BACKGROUND_PARSING\nvoid Parser::WaitForBackgroundJobs(BackgroundParser *bgp, CompileScriptException *pse)\n{\n    \/\/ The scan of the script is done, but there may be unfinished background jobs in the queue.\n    \/\/ Enlist the main thread to help with those.\n    BackgroundParseItem *item;\n    if (!*bgp->GetPendingBackgroundItemsPtr())\n    {\n        \/\/ We're done.\n        return;\n    }\n\n    \/\/ Save parser state, since we'll need to restore it in order to bind references correctly later.\n    this->m_isInBackground = true;\n    this->SetCurrBackgroundParseItem(nullptr);\n    uint blockIdSave = this->m_nextBlockId;\n    uint functionIdSave = *this->m_nextFunctionId;\n    StmtNest *pstmtSave = this->m_pstmtCur;\n\n    if (!bgp->Processor()->ProcessesInBackground())\n    {\n        \/\/ No background thread. Just walk the jobs with no locking and process them.\n        for (item = bgp->GetNextUnprocessedItem(); item; item = bgp->GetNextUnprocessedItem())\n        {\n            bgp->Processor()->RemoveJob(item);\n            bool succeeded = bgp->Process(item, this, pse);\n            bgp->JobProcessed(item, succeeded);\n        }\n        Assert(!*bgp->GetPendingBackgroundItemsPtr());\n    }\n    else\n    {\n        \/\/ Background threads. We need to have the critical section in order to:\n        \/\/ - Check for unprocessed jobs;\n        \/\/ - Remove jobs from the processor queue;\n        \/\/ - Do JobsProcessed work (such as removing jobs from the BackgroundParser's unprocessed list).\n        CriticalSection *pcs = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor())->GetCriticalSection();\n        pcs->Enter();\n        for (;;)\n        {\n            \/\/ Grab a job (in lock)\n            item = bgp->GetNextUnprocessedItem();\n            if (item == nullptr)\n            {\n                break;\n            }\n            bgp->Processor()->RemoveJob(item);\n            pcs->Leave();\n\n            \/\/ Process job (if there is one) (outside lock)\n            bool succeeded = bgp->Process(item, this, pse);\n\n            pcs->Enter();\n            bgp->JobProcessed(item, succeeded);\n        }\n        pcs->Leave();\n\n        \/\/ Wait for the background threads to finish jobs they're already processing (if any).\n        \/\/ TODO: Replace with a proper semaphore.\n        while(*bgp->GetPendingBackgroundItemsPtr());\n    }\n\n    Assert(!*bgp->GetPendingBackgroundItemsPtr());\n\n    \/\/ Restore parser state.\n    this->m_pstmtCur = pstmtSave;\n    this->m_isInBackground = false;\n    this->m_nextBlockId = blockIdSave;\n    *this->m_nextFunctionId = functionIdSave;\n}\n\nvoid Parser::FinishBackgroundPidRefs(BackgroundParseItem *item, bool isOtherParser)\n{\n    for (BlockInfoStack *blockInfo = item->GetParseContext()->currentBlockInfo; blockInfo; blockInfo = blockInfo->pBlockInfoOuter)\n    {\n        if (isOtherParser)\n        {\n            this->BindPidRefs<true>(blockInfo, item->GetMaxBlockId());\n        }\n        else\n        {\n            this->BindPidRefs<false>(blockInfo, item->GetMaxBlockId());\n        }\n    }\n}\n\nvoid Parser::FinishBackgroundRegExpNodes()\n{\n    \/\/ We have a list of RegExp nodes that we saw on the UI thread in functions we're parallel parsing,\n    \/\/ and for each background job we have a list of RegExp nodes for which we couldn't allocate patterns.\n    \/\/ We need to copy the pattern pointers from the UI thread nodes to the corresponding nodes on the\n    \/\/ background nodes.\n    \/\/ There may be UI thread nodes for which there are no background thread equivalents, because the UI thread\n    \/\/ has to assume that the background thread won't defer anything.\n\n    \/\/ Note that because these lists (and the list of background jobs) are SList's built by prepending, they are\n    \/\/ all in reverse lexical order.\n\n    Assert(!this->IsBackgroundParser());\n    Assert(this->fastScannedRegExpNodes);\n    Assert(this->backgroundParseItems != nullptr);\n\n    BackgroundParseItem *currBackgroundItem;\n\n#if DBG\n    for (currBackgroundItem = this->backgroundParseItems;\n         currBackgroundItem;\n         currBackgroundItem = currBackgroundItem->GetNext())\n    {\n        if (currBackgroundItem->RegExpNodeList())\n        {\n            FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())\n            {\n                Assert(pnode->sxPid.regexPattern == nullptr);\n            }\n            NEXT_DLIST_ENTRY;\n        }\n    }\n#endif\n\n    \/\/ Hook up the patterns allocated on the main thread to the nodes created on the background thread.\n    \/\/ Walk the list of foreground nodes, advancing through the work items and looking up each item.\n    \/\/ Note that the background thread may have chosen to defer a given RegEx literal, so not every foreground\n    \/\/ node will have a matching background node. Doesn't matter for correctness.\n    \/\/ (It's inefficient, of course, to have to restart the inner loop from the beginning of the work item's\n    \/\/ list, but it should be unusual to have many RegExes in a single work item's chunk of code. Figure out how\n    \/\/ to start the inner loop from a known internal node within the list if that turns out to be important.)\n    currBackgroundItem = this->backgroundParseItems;\n    FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeFgnd, this->fastScannedRegExpNodes)\n    {\n        Assert(pnodeFgnd->nop == knopRegExp);\n        Assert(pnodeFgnd->sxPid.regexPattern != nullptr);\n        bool quit = false;\n\n        while (!quit)\n        {\n            \/\/ Find the next work item with a RegEx in it.\n            while (currBackgroundItem && currBackgroundItem->RegExpNodeList() == nullptr)\n            {\n                currBackgroundItem = currBackgroundItem->GetNext();\n            }\n            if (!currBackgroundItem)\n            {\n                break;\n            }\n\n            \/\/ Walk the RegExps in the work item.\n            FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeBgnd, currBackgroundItem->RegExpNodeList())\n            {\n                Assert(pnodeBgnd->nop == knopRegExp);\n\n                if (pnodeFgnd->ichMin <= pnodeBgnd->ichMin)\n                {\n                    \/\/ Either we found a match, or the next background node is past the foreground node.\n                    \/\/ In any case, we can stop searching.\n                    if (pnodeFgnd->ichMin == pnodeBgnd->ichMin)\n                    {\n                        Assert(pnodeFgnd->ichLim == pnodeBgnd->ichLim);\n                        pnodeBgnd->sxPid.regexPattern = pnodeFgnd->sxPid.regexPattern;\n                    }\n                    quit = true;\n                    break;\n                }\n            }\n            NEXT_DLIST_ENTRY;\n\n            if (!quit)\n            {\n                \/\/ Need to advance to the next work item.\n                currBackgroundItem = currBackgroundItem->GetNext();\n            }\n        }\n    }\n    NEXT_DLIST_ENTRY;\n\n#if DBG\n    for (currBackgroundItem = this->backgroundParseItems;\n         currBackgroundItem;\n         currBackgroundItem = currBackgroundItem->GetNext())\n    {\n        if (currBackgroundItem->RegExpNodeList())\n        {\n            FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())\n            {\n                Assert(pnode->sxPid.regexPattern != nullptr);\n            }\n            NEXT_DLIST_ENTRY;\n        }\n    }\n#endif\n}\n#endif\n\nLabelId* Parser::CreateLabelId(IdentToken* pToken)\n{\n    LabelId* pLabelId;\n\n    pLabelId = (LabelId*)m_nodeAllocator.Alloc(sizeof(LabelId));\n    if (NULL == pLabelId)\n        Error(ERRnoMemory);\n    pLabelId->pid = pToken->pid;\n    pLabelId->next = NULL;\n\n    return pLabelId;\n}\n\n\/*****************************************************************************\nThe following set of routines allocate parse tree nodes of various kinds.\nThey catch an exception on out of memory.\n*****************************************************************************\/\nstatic const int g_mpnopcbNode[] =\n{\n#define PTNODE(nop,sn,pc,nk,ok,json) kcbPn##nk,\n#include \"ptlist.h\"\n};\n\nconst Js::RegSlot NoRegister = (Js::RegSlot)-1;\nconst Js::RegSlot OneByteRegister = (Js::RegSlot_OneByte)-1;\n\nvoid Parser::InitNode(OpCode nop,ParseNodePtr pnode) {\n    pnode->nop = nop;\n    pnode->grfpn = PNodeFlags::fpnNone;\n    pnode->location = NoRegister;\n    pnode->emitLabels = false;\n    pnode->isUsed = true;\n    pnode->notEscapedUse = false;\n    pnode->isInList = false;\n    pnode->isCallApplyTargetLoad = false;\n}\n\n\/\/ Create nodes using Arena\nParseNodePtr\nParser::StaticCreateBlockNode(ArenaAllocator* alloc, charcount_t ichMin , charcount_t ichLim, int blockId, PnodeBlockType blockType)\n{\n    ParseNodePtr pnode = StaticCreateNodeT<knopBlock>(alloc, ichMin, ichLim);\n    InitBlockNode(pnode, blockId, blockType);\n    return pnode;\n}\n\nvoid Parser::InitBlockNode(ParseNodePtr pnode, int blockId, PnodeBlockType blockType)\n{\n    Assert(pnode->nop == knopBlock);\n    pnode->sxBlock.pnodeScopes = nullptr;\n    pnode->sxBlock.pnodeNext = nullptr;\n    pnode->sxBlock.scope = nullptr;\n    pnode->sxBlock.enclosingBlock = nullptr;\n    pnode->sxBlock.pnodeLexVars = nullptr;\n    pnode->sxBlock.pnodeStmt = nullptr;\n    pnode->sxBlock.pnodeLastValStmt = nullptr;\n\n    pnode->sxBlock.callsEval = false;\n    pnode->sxBlock.childCallsEval = false;\n    pnode->sxBlock.blockType = blockType;\n    pnode->sxBlock.blockId = blockId;\n\n    if (blockType != PnodeBlockType::Regular)\n    {\n        pnode->grfpn |= PNodeFlags::fpnSyntheticNode;\n    }\n}\n\n\/\/ Create Node with limit\ntemplate <OpCode nop>\nParseNodePtr Parser::CreateNodeT(charcount_t ichMin,charcount_t ichLim)\n{\n    Assert(!this->m_deferringAST);\n    ParseNodePtr pnode = StaticCreateNodeT<nop>(&m_nodeAllocator, ichMin, ichLim);\n\n    Assert(m_pCurrentAstSize != NULL);\n    *m_pCurrentAstSize += GetNodeSize<nop>();\n\n    return pnode;\n}\n\nParseNodePtr Parser::CreateDeclNode(OpCode nop, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)\n{\n    ParseNodePtr pnode = CreateNode(nop);\n\n    pnode->sxVar.InitDeclNode(pid, NULL);\n\n    if (symbolType != STUnknown)\n    {\n        pnode->sxVar.sym = AddDeclForPid(pnode, pid, symbolType, errorOnRedecl);\n    }\n\n    return pnode;\n}\n\nSymbol* Parser::AddDeclForPid(ParseNodePtr pnode, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)\n{\n    Assert(pnode->IsVarLetOrConst());\n\n    PidRefStack *refForUse = nullptr, *refForDecl = nullptr;\n\n    BlockInfoStack *blockInfo;\n    bool fBlockScope = false;\n    if (pnode->nop != knopVarDecl || symbolType == STFunction)\n    {\n        Assert(m_pstmtCur);\n        if (m_pstmtCur->isDeferred)\n        {\n            \/\/ Deferred parsing: there's no pnodeStmt node, only an opcode on the Stmt struct.\n            if (m_pstmtCur->op != knopBlock)\n            {\n                \/\/ Let\/const declared in a bare statement context.\n                Error(ERRDeclOutOfStmt);\n            }\n\n            if (m_pstmtCur->pstmtOuter && m_pstmtCur->pstmtOuter->op == knopSwitch)\n            {\n                \/\/ Let\/const declared inside a switch block (requiring conservative use-before-decl check).\n                pnode->sxVar.isSwitchStmtDecl = true;\n            }\n        }\n        else\n        {\n            if (m_pstmtCur->pnodeStmt->nop != knopBlock)\n            {\n                \/\/ Let\/const declared in a bare statement context.\n                Error(ERRDeclOutOfStmt);\n            }\n\n            if (m_pstmtCur->pstmtOuter && m_pstmtCur->pstmtOuter->pnodeStmt->nop == knopSwitch)\n            {\n                \/\/ Let\/const declared inside a switch block (requiring conservative use-before-decl check).\n                pnode->sxVar.isSwitchStmtDecl = true;\n            }\n        }\n\n        fBlockScope = pnode->nop != knopVarDecl ||\n            (\n                !GetCurrentBlockInfo()->pnodeBlock->sxBlock.scope ||\n                GetCurrentBlockInfo()->pnodeBlock->sxBlock.scope->GetScopeType() != ScopeType_GlobalEvalBlock\n                );\n    }\n    if (fBlockScope)\n    {\n        blockInfo = GetCurrentBlockInfo();\n    }\n    else\n    {\n        blockInfo = GetCurrentFunctionBlockInfo();\n    }\n\n    \/\/ If we are creating an 'arguments' Sym at function block scope, create it in\n    \/\/ the parameter scope instead. That way, if we need to reuse the Sym for the\n    \/\/ actual arguments object at the end of the function, we don't need to move it\n    \/\/ into the parameter scope.\n    if (pid == wellKnownPropertyPids.arguments\n        && pnode->nop == knopVarDecl\n        && blockInfo->pnodeBlock->sxBlock.blockType == PnodeBlockType::Function\n        && blockInfo->pBlockInfoOuter != nullptr\n        && blockInfo->pBlockInfoOuter->pnodeBlock->sxBlock.blockType == PnodeBlockType::Parameter\n        && blockInfo->pnodeBlock->sxBlock.scope->GetScopeType() != ScopeType_FuncExpr\n        && blockInfo->pBlockInfoOuter->pnodeBlock->sxBlock.scope->GetCanMergeWithBodyScope())\n    {\n        blockInfo = blockInfo->pBlockInfoOuter;\n    }\n\n    refForDecl = this->FindOrAddPidRef(pid, blockInfo->pnodeBlock->sxBlock.blockId, GetCurrentFunctionNode()->sxFnc.functionId);\n\n    if (refForDecl == nullptr)\n    {\n        Error(ERRnoMemory);\n    }\n    if (blockInfo == GetCurrentBlockInfo())\n    {\n        refForUse = refForDecl;\n    }\n    else\n    {\n        refForUse = this->PushPidRef(pid);\n    }\n    pnode->sxVar.symRef = refForUse->GetSymRef();\n    Symbol *sym = refForDecl->GetSym();\n    if (sym != nullptr)\n    {\n        \/\/ Multiple declarations in the same scope. 3 possibilities: error, existing one wins, new one wins.\n        switch (pnode->nop)\n        {\n        case knopLetDecl:\n        case knopConstDecl:\n            if (!sym->GetDecl()->sxVar.isBlockScopeFncDeclVar)\n            {\n                Assert(errorOnRedecl);\n                \/\/ Redeclaration error.\n                Error(ERRRedeclaration);\n            }\n            else\n            {\n                \/\/ (New) let\/const hides the (old) var\n                sym->SetSymbolType(symbolType);\n                sym->SetDecl(pnode);\n            }\n            break;\n        case knopVarDecl:\n            if (m_currentScope->GetScopeType() == ScopeType_Parameter)\n            {\n                \/\/ If this is a parameter list, mark the scope to indicate that it has duplicate definition.\n                \/\/ If later this turns out to be a non-simple param list (like function f(a, a, c = 1) {}) then it is a SyntaxError to have duplicate formals.\n                m_currentScope->SetHasDuplicateFormals();\n            }\n\n            if (sym->GetDecl() == nullptr)\n            {\n                Assert(symbolType == STFunction);\n                sym->SetDecl(pnode);\n                break;\n            }\n            switch (sym->GetDecl()->nop)\n            {\n            case knopLetDecl:\n            case knopConstDecl:\n                \/\/ Destructuring made possible to have the formals to be the let bind. But that shouldn't throw the error.\n                if (errorOnRedecl && (!IsES6DestructuringEnabled() || sym->GetSymbolType() != STFormal))\n                {\n                    Error(ERRRedeclaration);\n                }\n                \/\/ If !errorOnRedecl, (old) let\/const hides the (new) var, so do nothing.\n                break;\n            case knopVarDecl:\n                \/\/ Legal redeclaration. Who wins?\n                if (errorOnRedecl || sym->GetDecl()->sxVar.isBlockScopeFncDeclVar)\n                {\n                    if (symbolType == STFormal ||\n                        (symbolType == STFunction && sym->GetSymbolType() != STFormal) ||\n                        sym->GetSymbolType() == STVariable)\n                    {\n                        \/\/ New decl wins.\n                        sym->SetSymbolType(symbolType);\n                        sym->SetDecl(pnode);\n                    }\n                }\n                break;\n            }\n            break;\n        }\n    }\n    else\n    {\n        Scope *scope = blockInfo->pnodeBlock->sxBlock.scope;\n        if (scope == nullptr)\n        {\n            Assert(blockInfo->pnodeBlock->sxBlock.blockType == PnodeBlockType::Regular);\n            scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, ScopeType_Block);\n            blockInfo->pnodeBlock->sxBlock.scope = scope;\n            PushScope(scope);\n        }\n\n        if (scope->GetScopeType() == ScopeType_GlobalEvalBlock)\n        {\n            Assert(fBlockScope);\n            Assert(scope->GetEnclosingScope() == m_currentNodeProg->sxProg.scope);\n            \/\/ Check for same-named decl in Global scope.\n            PidRefStack *pidRefOld = pid->GetPidRefForScopeId(0);\n            if (pidRefOld && pidRefOld->GetSym())\n            {\n                Error(ERRRedeclaration);\n            }\n        }\n        else if (scope->GetScopeType() == ScopeType_Global && (this->m_grfscr & fscrEvalCode) &&\n                 !(m_functionBody && m_functionBody->GetScopeInfo()))\n        {\n            \/\/ Check for same-named decl in GlobalEvalBlock scope. Note that this is not necessary\n            \/\/ if we're compiling a deferred nested function and the global scope was restored from cached info,\n            \/\/ because in that case we don't need a GlobalEvalScope.\n            Assert(!fBlockScope || (this->m_grfscr & fscrConsoleScopeEval) == fscrConsoleScopeEval);\n            PidRefStack *pidRefOld = pid->GetPidRefForScopeId(1);\n            if (pidRefOld && pidRefOld->GetSym())\n            {\n                Error(ERRRedeclaration);\n            }\n        }\n\n        if ((scope->GetScopeType() == ScopeType_FunctionBody || scope->GetScopeType() == ScopeType_Parameter) && symbolType != STFunction)\n        {\n            ParseNodePtr pnodeFnc = GetCurrentFunctionNode();\n            AnalysisAssert(pnodeFnc);\n            if (pnodeFnc->sxFnc.pnodeName &&\n                pnodeFnc->sxFnc.pnodeName->nop == knopVarDecl &&\n                pnodeFnc->sxFnc.pnodeName->sxVar.pid == pid)\n            {\n                \/\/ Named function expression has its name hidden by a local declaration.\n                \/\/ This is important to know if we don't know whether nested deferred functions refer to it,\n                \/\/ because if the name has a non-local reference then we have to create a scope object.\n                m_currentNodeFunc->sxFnc.SetNameIsHidden();\n            }\n        }\n\n        if (!sym)\n        {\n            const char16 *name = reinterpret_cast<const char16*>(pid->Psz());\n            int nameLength = pid->Cch();\n            SymbolName const symName(name, nameLength);\n\n            Assert(!scope->FindLocalSymbol(symName));\n            sym = Anew(&m_nodeAllocator, Symbol, symName, pnode, symbolType);\n            scope->AddNewSymbol(sym);\n            sym->SetPid(pid);\n        }\n        refForDecl->SetSym(sym);\n    }\n    return sym;\n}\n\nvoid Parser::RestorePidRefForSym(Symbol *sym)\n{\n    IdentPtr pid = m_pscan->m_phtbl->PidHashNameLen(sym->GetName().GetBuffer(), sym->GetName().GetLength());\n    Assert(pid);\n    sym->SetPid(pid);\n    PidRefStack *ref = this->PushPidRef(pid);\n    ref->SetSym(sym);\n}\n\nIdentPtr Parser::PidFromNode(ParseNodePtr pnode)\n{\n    for (;;)\n    {\n        switch (pnode->nop)\n        {\n        case knopName:\n            return pnode->sxPid.pid;\n\n        case knopVarDecl:\n            return pnode->sxVar.pid;\n\n        case knopDot:\n            Assert(pnode->sxBin.pnode2->nop == knopName);\n            return pnode->sxBin.pnode2->sxPid.pid;\n\n        case knopComma:\n            \/\/ Advance to the RHS and iterate.\n            pnode = pnode->sxBin.pnode2;\n            break;\n\n        default:\n            return nullptr;\n        }\n    }\n}\n\n#if DBG\nvoid VerifyNodeSize(OpCode nop, int size)\n{\n    Assert(nop >= 0 && nop < knopLim);\n    __analysis_assume(nop < knopLim);\n    Assert(g_mpnopcbNode[nop] == size);\n}\n#endif\n\nParseNodePtr Parser::StaticCreateBinNode(OpCode nop, ParseNodePtr pnode1,\n                                   ParseNodePtr pnode2,ArenaAllocator* alloc)\n{\n    DebugOnly(VerifyNodeSize(nop, kcbPnBin));\n    ParseNodePtr pnode = (ParseNodePtr)alloc->Alloc(kcbPnBin);\n    InitNode(nop, pnode);\n\n    pnode->sxBin.pnodeNext = nullptr;\n    pnode->sxBin.pnode1 = pnode1;\n    pnode->sxBin.pnode2 = pnode2;\n\n    \/\/ Statically detect if the add is a concat\n    if (!PHASE_OFF1(Js::ByteCodeConcatExprOptPhase))\n    {\n        \/\/ We can't flatten the concat expression if the LHS is not a flatten concat already\n        \/\/ e.g.  a + (<str> + b)\n        \/\/      Side effect of ToStr(b) need to happen first before ToStr(a)\n        \/\/      If we flatten the concat expression, we will do ToStr(a) before ToStr(b)\n        if ((nop == knopAdd) && (pnode1->CanFlattenConcatExpr() || pnode2->nop == knopStr))\n        {\n            pnode->grfpn |= fpnCanFlattenConcatExpr;\n        }\n    }\n\n    return pnode;\n}\n\n\/\/ Create nodes using parser allocator\n\nParseNodePtr Parser::CreateNode(OpCode nop, charcount_t ichMin)\n{\n    bool nodeAllowed = IsNodeAllowedInCurrentDeferralState(nop);\n    Assert(nodeAllowed);\n\n    Assert(nop >= 0 && nop < knopLim);\n    ParseNodePtr pnode;\n    int cb = (nop >= knopNone && nop < knopLim) ? g_mpnopcbNode[nop] : g_mpnopcbNode[knopEmpty];\n\n    pnode = (ParseNodePtr)m_nodeAllocator.Alloc(cb);\n    Assert(pnode != nullptr);\n\n    if (!m_deferringAST)\n    {\n        Assert(m_pCurrentAstSize != nullptr);\n        *m_pCurrentAstSize += cb;\n    }\n\n    InitNode(nop,pnode);\n\n    \/\/ default - may be changed\n    pnode->ichMin = ichMin;\n    if (m_pscan!= nullptr) {\n      pnode->ichLim = m_pscan->IchLimTok();\n    }\n    else pnode->ichLim=0;\n\n    return pnode;\n}\n\nParseNodePtr Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1)\n{\n    Assert(!this->m_deferringAST);\n    DebugOnly(VerifyNodeSize(nop, kcbPnUni));\n    ParseNodePtr pnode = (ParseNodePtr)m_nodeAllocator.Alloc(kcbPnUni);\n\n    Assert(m_pCurrentAstSize != nullptr);\n    *m_pCurrentAstSize += kcbPnUni;\n\n    InitNode(nop, pnode);\n\n    pnode->sxUni.pnode1 = pnode1;\n    if (nullptr == pnode1)\n    {\n        \/\/ no ops\n        pnode->ichMin = m_pscan->IchMinTok();\n        pnode->ichLim = m_pscan->IchLimTok();\n    }\n    else\n    {\n        \/\/ 1 op\n        pnode->ichMin = pnode1->ichMin;\n        pnode->ichLim = pnode1->ichLim;\n        this->CheckArguments(pnode);\n    }\n    return pnode;\n}\n\nParseNodePtr Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)\n{\n    Assert(!this->m_deferringAST);\n    charcount_t ichMin;\n    charcount_t ichLim;\n\n    if (nullptr == pnode1)\n    {\n        \/\/ no ops\n        Assert(nullptr == pnode2);\n        ichMin = m_pscan->IchMinTok();\n        ichLim = m_pscan->IchLimTok();\n    }\n    else\n    {\n        if (nullptr == pnode2)\n        {\n            \/\/ 1 op\n            ichMin = pnode1->ichMin;\n            ichLim = pnode1->ichLim;\n        }\n        else\n        {\n            \/\/ 2 ops\n            ichMin = pnode1->ichMin;\n            ichLim = pnode2->ichLim;\n            if (nop != knopDot && nop != knopIndex)\n            {\n                this->CheckArguments(pnode2);\n            }\n        }\n        if (nop != knopDot && nop != knopIndex)\n        {\n            this->CheckArguments(pnode1);\n        }\n    }\n\n    return CreateBinNode(nop, pnode1, pnode2, ichMin, ichLim);\n}\n\nParseNodePtr Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,\n                                   ParseNodePtr pnode2, ParseNodePtr pnode3)\n{\n    charcount_t ichMin;\n    charcount_t ichLim;\n\n    if (nullptr == pnode1)\n    {\n        \/\/ no ops\n        Assert(nullptr == pnode2);\n        Assert(nullptr == pnode3);\n        ichMin = m_pscan->IchMinTok();\n        ichLim = m_pscan->IchLimTok();\n    }\n    else if (nullptr == pnode2)\n    {\n        \/\/ 1 op\n        Assert(nullptr == pnode3);\n        ichMin = pnode1->ichMin;\n        ichLim = pnode1->ichLim;\n    }\n    else if (nullptr == pnode3)\n    {\n        \/\/ 2 op\n        ichMin = pnode1->ichMin;\n        ichLim = pnode2->ichLim;\n    }\n    else\n    {\n        \/\/ 3 ops\n        ichMin = pnode1->ichMin;\n        ichLim = pnode3->ichLim;\n    }\n\n    return CreateTriNode(nop, pnode1, pnode2, pnode3, ichMin, ichLim);\n}\n\nParseNodePtr Parser::CreateBlockNode(charcount_t ichMin,charcount_t ichLim, PnodeBlockType blockType)\n{\n    return StaticCreateBlockNode(&m_nodeAllocator, ichMin, ichLim, this->m_nextBlockId++, blockType);\n}\n\nParseNodePtr\nParser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2,charcount_t ichMin,charcount_t ichLim)\n{\n    Assert(!this->m_deferringAST);\n    DebugOnly(VerifyNodeSize(nop, kcbPnCall));\n    ParseNodePtr pnode = (ParseNodePtr)m_nodeAllocator.Alloc(kcbPnCall);\n\n    Assert(m_pCurrentAstSize != nullptr);\n    *m_pCurrentAstSize += kcbPnCall;\n\n    InitNode(nop, pnode);\n\n    pnode->sxCall.pnodeTarget = pnode1;\n    pnode->sxCall.pnodeArgs = pnode2;\n    pnode->sxCall.argCount = 0;\n    pnode->sxCall.spreadArgCount = 0;\n    pnode->sxCall.callOfConstants = false;\n    pnode->sxCall.isApplyCall = false;\n    pnode->sxCall.isEvalCall = false;\n\n    pnode->ichMin = ichMin;\n    pnode->ichLim = ichLim;\n\n    return pnode;\n}\n\nParseNodePtr Parser::CreateStrNode(IdentPtr pid)\n{\n    Assert(!this->m_deferringAST);\n\n    ParseNodePtr pnode = CreateNode(knopStr);\n    pnode->sxPid.pid=pid;\n    pnode->grfpn |= PNodeFlags::fpnCanFlattenConcatExpr;\n    return pnode;\n}\n\nParseNodePtr Parser::CreateIntNode(int32 lw)\n{\n    ParseNodePtr pnode = CreateNode(knopInt);\n    pnode->sxInt.lw = lw;\n    return pnode;\n}\n\n\/\/ Create Node with scanner limit\ntemplate <OpCode nop>\nParseNodePtr Parser::CreateNodeWithScanner()\n{\n    Assert(m_pscan != nullptr);\n    return CreateNodeWithScanner<nop>(m_pscan->IchMinTok());\n}\n\ntemplate <OpCode nop>\nParseNodePtr Parser::CreateNodeWithScanner(charcount_t ichMin)\n{\n    Assert(m_pscan != nullptr);\n    return CreateNodeT<nop>(ichMin, m_pscan->IchLimTok());\n}\n\nParseNodePtr Parser::CreateProgNodeWithScanner(bool isModuleSource)\n{\n    ParseNodePtr pnodeProg;\n\n    if (isModuleSource)\n    {\n        pnodeProg = CreateNodeWithScanner<knopModule>();\n\n        \/\/ knopModule is not actually handled anywhere since we would need to handle it everywhere we could\n        \/\/ have knopProg and it would be treated exactly the same except for import\/export statements.\n        \/\/ We are only using it as a way to get the correct size for PnModule.\n        \/\/ Consider: Should we add a flag to PnProg which is false but set to true in PnModule?\n        \/\/           If we do, it can't be a virtual method since the parse nodes are all in a union.\n        pnodeProg->nop = knopProg;\n    }\n    else\n    {\n        pnodeProg = CreateNodeWithScanner<knopProg>();\n    }\n\n    return pnodeProg;\n}\n\nParseNodePtr Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)\n{\n    charcount_t ichMin;\n    charcount_t ichLim;\n\n    if (nullptr == pnode1)\n    {\n        Assert(nullptr == pnode2);\n        ichMin = m_pscan->IchMinTok();\n        ichLim = m_pscan->IchLimTok();\n    }\n    else\n    {\n        if (nullptr == pnode2)\n        {\n            ichMin = pnode1->ichMin;\n            ichLim = pnode1->ichLim;\n        }\n        else\n        {\n            ichMin = pnode1->ichMin;\n            ichLim = pnode2->ichLim;\n        }\n        if (pnode1->nop == knopDot || pnode1->nop == knopIndex)\n        {\n            this->CheckArguments(pnode1->sxBin.pnode1);\n        }\n    }\n    return CreateCallNode(nop, pnode1, pnode2, ichMin, ichLim);\n}\n\nParseNodePtr Parser::CreateStrNodeWithScanner(IdentPtr pid)\n{\n    Assert(!this->m_deferringAST);\n\n    ParseNodePtr pnode = CreateNodeWithScanner<knopStr>();\n    pnode->sxPid.pid=pid;\n    pnode->grfpn |= PNodeFlags::fpnCanFlattenConcatExpr;\n    return pnode;\n}\n\nParseNodePtr Parser::CreateIntNodeWithScanner(int32 lw)\n{\n    Assert(!this->m_deferringAST);\n    ParseNodePtr pnode = CreateNodeWithScanner<knopInt>();\n    pnode->sxInt.lw = lw;\n    return pnode;\n}\n\nParseNodePtr Parser::CreateTempNode(ParseNode* initExpr)\n{\n    ParseNodePtr pnode = CreateNode(knopTemp, (charcount_t)0);\n    pnode->sxVar.pnodeInit =initExpr;\n    pnode->sxVar.pnodeNext = nullptr;\n    return pnode;\n}\n\nParseNodePtr Parser::CreateTempRef(ParseNode* tempNode)\n{\n    ParseNodePtr pnode = CreateUniNode(knopTempRef, tempNode);\n    return pnode;\n}\n\nvoid Parser::CheckPidIsValid(IdentPtr pid, bool autoArgumentsObject)\n{\n    if (IsStrictMode())\n    {\n        \/\/ in strict mode, variable named 'eval' cannot be created\n        if (pid == wellKnownPropertyPids.eval)\n        {\n            Error(ERREvalUsage);\n        }\n        else if (pid == wellKnownPropertyPids.arguments && !autoArgumentsObject)\n        {\n            Error(ERRArgsUsage);\n        }\n    }\n}\n\n\/\/ CreateVarDecl needs m_ppnodeVar to be pointing to the right function.\n\/\/ Post-parsing rewriting during bytecode gen may have m_ppnodeVar pointing to the last parsed function.\n\/\/ This function sets up m_ppnodeVar to point to the given pnodeFnc and creates the new var declaration.\n\/\/ This prevents accidentally adding var declarations to the last parsed function.\nParseNodePtr Parser::AddVarDeclNode(IdentPtr pid, ParseNodePtr pnodeFnc)\n{\n    AnalysisAssert(pnodeFnc);\n\n    ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;\n\n    m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;\n    while (*m_ppnodeVar != nullptr)\n    {\n        m_ppnodeVar = &(*m_ppnodeVar)->sxVar.pnodeNext;\n    }\n\n    ParseNodePtr pnode = CreateVarDeclNode(pid, STUnknown, false, 0, \/* checkReDecl = *\/ false);\n\n    m_ppnodeVar = ppnodeVarSave;\n\n    return pnode;\n}\n\nParseNodePtr Parser::CreateModuleImportDeclNode(IdentPtr localName)\n{\n    ParseNodePtr declNode = CreateBlockScopedDeclNode(localName, knopConstDecl);\n    Symbol* sym = declNode->sxVar.sym;\n\n    sym->SetIsModuleExportStorage(true);\n    sym->SetIsModuleImport(true);\n\n    return declNode;\n}\n\nParseNodePtr Parser::CreateVarDeclNode(IdentPtr pid, SymbolType symbolType, bool autoArgumentsObject, ParseNodePtr pnodeFnc, bool errorOnRedecl)\n{\n    ParseNodePtr pnode = CreateDeclNode(knopVarDecl, pid, symbolType, errorOnRedecl);\n\n    \/\/ Append the variable to the end of the current variable list.\n    AssertMem(m_ppnodeVar);\n    pnode->sxVar.pnodeNext = *m_ppnodeVar;\n    *m_ppnodeVar = pnode;\n    if (nullptr != pid)\n    {\n        \/\/ this is not a temp - make sure temps go after this node\n        AssertMem(pid);\n        m_ppnodeVar = &pnode->sxVar.pnodeNext;\n        CheckPidIsValid(pid, autoArgumentsObject);\n    }\n\n    return pnode;\n}\n\nParseNodePtr Parser::CreateBlockScopedDeclNode(IdentPtr pid, OpCode nodeType)\n{\n    Assert(nodeType == knopConstDecl || nodeType == knopLetDecl);\n\n    ParseNodePtr pnode = CreateDeclNode(nodeType, pid, STVariable, true);\n\n    if (nullptr != pid)\n    {\n        AssertMem(pid);\n        pid->SetIsLetOrConst();\n        AddVarDeclToBlock(pnode);\n        CheckPidIsValid(pid);\n    }\n\n    return pnode;\n}\n\nvoid Parser::AddVarDeclToBlock(ParseNode *pnode)\n{\n    Assert(pnode->nop == knopConstDecl || pnode->nop == knopLetDecl);\n\n    \/\/ Maintain a combined list of let and const declarations to keep\n    \/\/ track of declaration order.\n\n    AssertMem(m_currentBlockInfo->m_ppnodeLex);\n    *m_currentBlockInfo->m_ppnodeLex = pnode;\n    m_currentBlockInfo->m_ppnodeLex = &pnode->sxVar.pnodeNext;\n    pnode->sxVar.pnodeNext = nullptr;\n}\n\nvoid Parser::SetCurrentStatement(StmtNest *stmt)\n{\n    m_pstmtCur = stmt;\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::StartParseBlockWithCapacity(PnodeBlockType blockType, ScopeType scopeType, int capacity)\n{\n    Scope *scope = nullptr;\n    \/\/ Block scopes are created lazily when we discover block-scoped content.\n    if (scopeType != ScopeType_Unknown && scopeType != ScopeType_Block)\n    {\n        scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType, capacity);\n        PushScope(scope);\n    }\n\n    return StartParseBlockHelper<buildAST>(blockType, scope, nullptr, nullptr);\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::StartParseBlock(PnodeBlockType blockType, ScopeType scopeType, ParseNodePtr pnodeLabel, LabelId* pLabelId)\n{\n    Scope *scope = nullptr;\n    \/\/ Block scopes are created lazily when we discover block-scoped content.\n    if (scopeType != ScopeType_Unknown && scopeType != ScopeType_Block)\n    {\n        scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType);\n        PushScope(scope);\n    }\n\n    return StartParseBlockHelper<buildAST>(blockType, scope, pnodeLabel, pLabelId);\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::StartParseBlockHelper(PnodeBlockType blockType, Scope *scope, ParseNodePtr pnodeLabel, LabelId* pLabelId)\n{\n    ParseNodePtr pnodeBlock = CreateBlockNode(blockType);\n    pnodeBlock->sxBlock.scope = scope;\n    BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeBlock);\n\n    PushStmt<buildAST>(&newBlockInfo->pstmt, pnodeBlock, knopBlock, pnodeLabel, pLabelId);\n\n    return pnodeBlock;\n}\n\nvoid Parser::PushScope(Scope *scope)\n{\n    Assert(scope);\n    scope->SetEnclosingScope(m_currentScope);\n    m_currentScope = scope;\n}\n\nvoid Parser::PopScope(Scope *scope)\n{\n    Assert(scope == m_currentScope);\n    m_currentScope = scope->GetEnclosingScope();\n    scope->SetEnclosingScope(nullptr);\n}\n\nvoid Parser::PushFuncBlockScope(ParseNodePtr pnodeBlock, ParseNodePtr **ppnodeScopeSave, ParseNodePtr **ppnodeExprScopeSave)\n{\n    \/\/ Maintain the scope tree.\n\n    pnodeBlock->sxBlock.pnodeScopes = nullptr;\n    pnodeBlock->sxBlock.pnodeNext = nullptr;\n\n    \/\/ Insert this block into the active list of scopes (m_ppnodeExprScope or m_ppnodeScope).\n    \/\/ Save the current block's \"next\" pointer as the new endpoint of that list.\n    if (m_ppnodeExprScope)\n    {\n        *ppnodeScopeSave = m_ppnodeScope;\n\n        Assert(*m_ppnodeExprScope == nullptr);\n        *m_ppnodeExprScope = pnodeBlock;\n        *ppnodeExprScopeSave = &pnodeBlock->sxBlock.pnodeNext;\n    }\n    else\n    {\n        Assert(m_ppnodeScope);\n        Assert(*m_ppnodeScope == nullptr);\n        *m_ppnodeScope = pnodeBlock;\n        *ppnodeScopeSave = &pnodeBlock->sxBlock.pnodeNext;\n\n        *ppnodeExprScopeSave = m_ppnodeExprScope;\n    }\n\n    \/\/ Advance the global scope list pointer to the new block's child list.\n    m_ppnodeScope = &pnodeBlock->sxBlock.pnodeScopes;\n    \/\/ Set m_ppnodeExprScope to NULL to make that list inactive.\n    m_ppnodeExprScope = nullptr;\n}\n\nvoid Parser::PopFuncBlockScope(ParseNodePtr *ppnodeScopeSave, ParseNodePtr *ppnodeExprScopeSave)\n{\n    Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);\n    m_ppnodeExprScope = ppnodeExprScopeSave;\n\n    AssertMem(m_ppnodeScope);\n    Assert(nullptr == *m_ppnodeScope);\n    m_ppnodeScope = ppnodeScopeSave;\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseBlock(ParseNodePtr pnodeLabel, LabelId* pLabelId)\n{\n    ParseNodePtr pnodeBlock = nullptr;\n    ParseNodePtr *ppnodeScopeSave = nullptr;\n    ParseNodePtr *ppnodeExprScopeSave = nullptr;\n\n    pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block, pnodeLabel, pLabelId);\n\n    BlockInfoStack* outerBlockInfo = m_currentBlockInfo->pBlockInfoOuter;\n    if (outerBlockInfo != nullptr && outerBlockInfo->pnodeBlock != nullptr\n        && outerBlockInfo->pnodeBlock->sxBlock.scope != nullptr\n        && outerBlockInfo->pnodeBlock->sxBlock.scope->GetScopeType() == ScopeType_CatchParamPattern)\n    {\n        \/\/ If we are parsing the catch block then destructured params can have let declrations. Let's add them to the new block.\n        for (ParseNodePtr pnode = m_currentBlockInfo->pBlockInfoOuter->pnodeBlock->sxBlock.pnodeLexVars; pnode; pnode = pnode->sxVar.pnodeNext)\n        {\n            PidRefStack* ref = PushPidRef(pnode->sxVar.sym->GetPid());\n            ref->SetSym(pnode->sxVar.sym);\n        }\n    }\n\n    ChkCurTok(tkLCurly, ERRnoLcurly);\n    ParseNodePtr * ppnodeList = nullptr;\n    if (buildAST)\n    {\n        PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);\n        ppnodeList = &pnodeBlock->sxBlock.pnodeStmt;\n    }\n\n    ParseStmtList<buildAST>(ppnodeList);\n\n    if (buildAST)\n    {\n        PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);\n    }\n\n    FinishParseBlock(pnodeBlock);\n\n    ChkCurTok(tkRCurly, ERRnoRcurly);\n\n\n    return pnodeBlock;\n}\n\nvoid Parser::FinishParseBlock(ParseNode *pnodeBlock, bool needScanRCurly)\n{\n    Assert(m_currentBlockInfo != nullptr && pnodeBlock == m_currentBlockInfo->pnodeBlock);\n\n    if (needScanRCurly)\n    {\n        \/\/ Only update the ichLim if we were expecting an RCurly. If there is an\n        \/\/ expression body without a necessary RCurly, the correct ichLim will\n        \/\/ have been set already.\n        pnodeBlock->ichLim = m_pscan->IchLimTok();\n    }\n\n    BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);\n\n    PopStmt(&m_currentBlockInfo->pstmt);\n\n    PopBlockInfo();\n\n    Scope *scope = pnodeBlock->sxBlock.scope;\n    if (scope)\n    {\n        PopScope(scope);\n    }\n}\n\nvoid Parser::FinishParseFncExprScope(ParseNodePtr pnodeFnc, ParseNodePtr pnodeFncExprScope)\n{\n    int fncExprScopeId = pnodeFncExprScope->sxBlock.blockId;\n    ParseNodePtr pnodeName = pnodeFnc->sxFnc.pnodeName;\n    if (pnodeName)\n    {\n        Assert(pnodeName->nop == knopVarDecl);\n        BindPidRefsInScope(pnodeName->sxVar.pid, pnodeName->sxVar.sym, fncExprScopeId);\n    }\n    FinishParseBlock(pnodeFncExprScope);\n}\n\ntemplate <const bool backgroundPidRef>\nvoid Parser::BindPidRefs(BlockInfoStack *blockInfo, uint maxBlockId)\n{\n    \/\/ We need to bind all assignments in order to emit assignment to 'const' error\n    int blockId = blockInfo->pnodeBlock->sxBlock.blockId;\n\n    Scope *scope = blockInfo->pnodeBlock->sxBlock.scope;\n    if (scope)\n    {\n        auto bindPidRefs = [blockId, maxBlockId, this](Symbol *sym)\n        {\n            ParseNodePtr pnode = sym->GetDecl();\n            IdentPtr pid;\n#if PROFILE_DICTIONARY\n            int depth = 0;\n#endif\n            Assert(pnode);\n            switch (pnode->nop)\n            {\n            case knopVarDecl:\n            case knopLetDecl:\n            case knopConstDecl:\n                pid = pnode->sxVar.pid;\n                if (backgroundPidRef)\n                {\n                    pid = this->m_pscan->m_phtbl->FindExistingPid(pid->Psz(), pid->Cch(), pid->Hash(), nullptr, nullptr\n#if PROFILE_DICTIONARY\n                                                                  , depth\n#endif\n                        );\n                    if (pid == nullptr)\n                    {\n                        break;\n                    }\n                }\n                this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);\n                break;\n            case knopName:\n                pid = pnode->sxPid.pid;\n                if (backgroundPidRef)\n                {\n                    pid = this->m_pscan->m_phtbl->FindExistingPid(pid->Psz(), pid->Cch(), pid->Hash(), nullptr, nullptr\n#if PROFILE_DICTIONARY\n                                                                  , depth\n#endif\n                        );\n                    if (pid == nullptr)\n                    {\n                        break;\n                    }\n                }\n                this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);\n                break;\n            default:\n                Assert(0);\n                break;\n            }\n        };\n\n        scope->ForEachSymbol(bindPidRefs);\n    }\n}\n\nvoid Parser::BindPidRefsInScope(IdentPtr pid, Symbol *sym, int blockId, uint maxBlockId)\n{\n    PidRefStack *ref, *nextRef, *lastRef = nullptr;\n    Js::LocalFunctionId funcId = GetCurrentFunctionNode()->sxFnc.functionId;\n    Assert(sym);\n\n    if (pid->GetIsModuleExport())\n    {\n        sym->SetIsModuleExportStorage(true);\n    }\n\n    for (ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = nextRef)\n    {\n        \/\/ Fix up sym* on PID ref.\n        Assert(!ref->GetSym() || ref->GetSym() == sym);\n        nextRef = ref->prev;\n        Assert(ref->GetScopeId() >= 0);\n        if ((uint)ref->GetScopeId() > maxBlockId)\n        {\n            lastRef = ref;\n            continue;\n        }\n        ref->SetSym(sym);\n        this->RemovePrevPidRef(pid, lastRef);\n\n        if (ref->IsAssignment())\n        {\n            sym->PromoteAssignmentState();\n            if (m_currentNodeFunc && sym->GetIsFormal())\n            {\n                m_currentNodeFunc->sxFnc.SetHasAnyWriteToFormals(true);                \n            }\n        }\n\n        if (ref->GetFuncScopeId() != funcId && !sym->GetIsGlobal() && !sym->GetIsModuleExportStorage())\n        {\n            Assert(ref->GetFuncScopeId() > funcId);\n            sym->SetHasNonLocalReference();\n        }\n\n        if (ref->GetScopeId() == blockId)\n        {\n            break;\n        }\n\n        if (m_currentNodeFunc && ref->isEscape && sym->GetSymbolType() == STFunction)\n        {\n            if (m_sourceContextInfo ? \n                    !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->sxFnc.functionId) :\n                    !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))\n            {\n                m_currentNodeFunc->sxFnc.SetNestedFuncEscapes();\n            }\n        }\n    }\n}\n\nvoid Parser::MarkEscapingRef(ParseNodePtr pnode, IdentToken *pToken)\n{\n    if (m_currentNodeFunc == nullptr)\n    {\n        return;\n    }\n    if (pnode && pnode->nop == knopFncDecl)\n    {\n        this->SetNestedFuncEscapes();\n    }\n    else if (pToken->pid)\n    {\n        PidRefStack *pidRef = pToken->pid->GetTopRef();\n        if (pidRef->sym)\n        {\n            if (pidRef->sym->GetSymbolType() == STFunction)\n            {\n                this->SetNestedFuncEscapes();\n            }\n        }\n        else\n        {\n            pidRef->isEscape = true;\n        }\n    }\n}\n\nvoid Parser::SetNestedFuncEscapes() const\n{\n    if (m_sourceContextInfo ? \n            !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->sxFnc.functionId) :\n            !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))\n    {\n        m_currentNodeFunc->sxFnc.SetNestedFuncEscapes();\n    }\n}\n\nvoid Parser::PopStmt(StmtNest *pStmt)\n{\n    Assert(pStmt == m_pstmtCur);\n    SetCurrentStatement(m_pstmtCur->pstmtOuter);\n}\n\nBlockInfoStack *Parser::PushBlockInfo(ParseNodePtr pnodeBlock)\n{\n    BlockInfoStack *newBlockInfo = (BlockInfoStack *)m_nodeAllocator.Alloc(sizeof(BlockInfoStack));\n    Assert(nullptr != newBlockInfo);\n\n    newBlockInfo->pnodeBlock = pnodeBlock;\n    newBlockInfo->pBlockInfoOuter = m_currentBlockInfo;\n    newBlockInfo->m_ppnodeLex = &pnodeBlock->sxBlock.pnodeLexVars;\n\n    if (pnodeBlock->sxBlock.blockType != PnodeBlockType::Regular)\n    {\n        newBlockInfo->pBlockInfoFunction = newBlockInfo;\n    }\n    else\n    {\n        Assert(m_currentBlockInfo);\n        newBlockInfo->pBlockInfoFunction = m_currentBlockInfo->pBlockInfoFunction;\n    }\n\n    m_currentBlockInfo = newBlockInfo;\n    return newBlockInfo;\n}\n\nvoid Parser::PopBlockInfo()\n{\n    Assert(m_currentBlockInfo);\n    PopDynamicBlock();\n    m_currentBlockInfo = m_currentBlockInfo->pBlockInfoOuter;\n}\n\nvoid Parser::PushDynamicBlock()\n{\n    Assert(GetCurrentBlock());\n    int blockId = GetCurrentBlock()->sxBlock.blockId;\n    if (m_currentDynamicBlock && m_currentDynamicBlock->id == blockId)\n    {\n        return;\n    }\n    BlockIdsStack *info = (BlockIdsStack *)m_nodeAllocator.Alloc(sizeof(BlockIdsStack));\n    if (nullptr == info)\n    {\n        Error(ERRnoMemory);\n    }\n\n    info->id = blockId;\n    info->prev = m_currentDynamicBlock;\n    m_currentDynamicBlock = info;\n}\n\nvoid Parser::PopDynamicBlock()\n{\n    int blockId = GetCurrentDynamicBlockId();\n    if (GetCurrentBlock()->sxBlock.blockId != blockId || blockId == -1)\n    {\n        return;\n    }\n    Assert(m_currentDynamicBlock);\n    for (BlockInfoStack *blockInfo = m_currentBlockInfo; blockInfo; blockInfo = blockInfo->pBlockInfoOuter)\n    {\n        for (ParseNodePtr pnodeDecl = blockInfo->pnodeBlock->sxBlock.pnodeLexVars;\n             pnodeDecl;\n             pnodeDecl = pnodeDecl->sxVar.pnodeNext)\n        {\n            this->SetPidRefsInScopeDynamic(pnodeDecl->sxVar.pid, blockId);\n        }\n    }\n\n    m_currentDynamicBlock = m_currentDynamicBlock->prev;\n}\n\nint Parser::GetCurrentDynamicBlockId() const\n{\n    return m_currentDynamicBlock ? m_currentDynamicBlock->id : -1;\n}\n\nParseNode *Parser::GetCurrentFunctionNode()\n{\n    if (m_currentNodeDeferredFunc != nullptr)\n    {\n        return m_currentNodeDeferredFunc;\n    }\n    else if (m_currentNodeFunc != nullptr)\n    {\n        return m_currentNodeFunc;\n    }\n    else\n    {\n        AssertMsg(GetFunctionBlock()->sxBlock.blockType == PnodeBlockType::Global,\n            \"Most likely we are trying to find a syntax error, related to 'let' or 'const' in deferred parsing mode with disabled support of 'let' and 'const'\");\n        return m_currentNodeProg;\n    }\n}\n\nParseNode *Parser::GetCurrentNonLambdaFunctionNode()\n{\n    if (m_currentNodeNonLambdaDeferredFunc != nullptr)\n    {\n        return m_currentNodeNonLambdaDeferredFunc;\n    }\n    return m_currentNodeNonLambdaFunc;\n\n}\nvoid Parser::RegisterRegexPattern(UnifiedRegex::RegexPattern *const regexPattern)\n{\n    Assert(regexPattern);\n\n    \/\/ ensure a no-throw add behavior here, to catch out of memory exceptions, using the guest arena allocator\n    if (!m_registeredRegexPatterns.PrependNoThrow(m_scriptContext->GetGuestArena(), regexPattern))\n    {\n        Parser::Error(ERRnoMemory);\n    }\n}\n\nvoid Parser::CaptureState(ParserState *state)\n{\n    Assert(state != nullptr);\n\n    state->m_funcInArraySave = m_funcInArray;\n    state->m_funcInArrayDepthSave = m_funcInArrayDepth;\n    state->m_nestedCountSave = *m_pnestedCount;\n    state->m_ppnodeScopeSave = m_ppnodeScope;\n    state->m_ppnodeExprScopeSave = m_ppnodeExprScope;\n    state->m_pCurrentAstSizeSave = m_pCurrentAstSize;\n\n    Assert(state->m_ppnodeScopeSave == nullptr || *state->m_ppnodeScopeSave == nullptr);\n    Assert(state->m_ppnodeExprScopeSave == nullptr || *state->m_ppnodeExprScopeSave == nullptr);\n\n#if DEBUG\n    state->m_currentBlockInfo = m_currentBlockInfo;\n#endif\n}\n\nvoid Parser::RestoreStateFrom(ParserState *state)\n{\n    Assert(state != nullptr);\n    Assert(state->m_currentBlockInfo == m_currentBlockInfo);\n\n    m_funcInArray = state->m_funcInArraySave;\n    m_funcInArrayDepth = state->m_funcInArrayDepthSave;\n    *m_pnestedCount = state->m_nestedCountSave;\n    m_pCurrentAstSize = state->m_pCurrentAstSizeSave;\n\n    if (state->m_ppnodeScopeSave != nullptr)\n    {\n        *state->m_ppnodeScopeSave = nullptr;\n    }\n\n    if (state->m_ppnodeExprScopeSave != nullptr)\n    {\n        *state->m_ppnodeExprScopeSave = nullptr;\n    }\n\n    m_ppnodeScope = state->m_ppnodeScopeSave;\n    m_ppnodeExprScope = state->m_ppnodeExprScopeSave;\n}\n\nvoid Parser::AddToNodeListEscapedUse(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,\n                           ParseNode * pnodeAdd)\n{\n    AddToNodeList(ppnodeList, pppnodeLast, pnodeAdd);\n    pnodeAdd->SetIsInList();\n}\n\nvoid Parser::AddToNodeList(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,\n                           ParseNode * pnodeAdd)\n{\n    Assert(!this->m_deferringAST);\n    if (nullptr == *pppnodeLast)\n    {\n        \/\/ should be an empty list\n        Assert(nullptr == *ppnodeList);\n\n        *ppnodeList = pnodeAdd;\n        *pppnodeLast = ppnodeList;\n    }\n    else\n    {\n        \/\/\n        AssertNodeMem(*ppnodeList);\n        AssertNodeMem(**pppnodeLast);\n\n        ParseNode *pnodeT = CreateBinNode(knopList, **pppnodeLast, pnodeAdd);\n        **pppnodeLast = pnodeT;\n        *pppnodeLast = &pnodeT->sxBin.pnode2;\n    }\n}\n\n\/\/ Check reference to \"arguments\" that indicates the object may escape.\nvoid Parser::CheckArguments(ParseNodePtr pnode)\n{\n    if (m_currentNodeFunc && this->NodeIsIdent(pnode, wellKnownPropertyPids.arguments))\n    {\n        m_currentNodeFunc->sxFnc.SetHasHeapArguments();\n    }\n}\n\n\/\/ Check use of \"arguments\" that requires instantiation of the object.\nvoid Parser::CheckArgumentsUse(IdentPtr pid, ParseNodePtr pnodeFnc)\n{\n    if (pid == wellKnownPropertyPids.arguments)\n    {\n        if (pnodeFnc != nullptr && pnodeFnc != m_currentNodeProg)\n        {\n            pnodeFnc->sxFnc.SetUsesArguments(TRUE);\n        }\n        else\n        {\n            m_UsesArgumentsAtGlobal = true;\n        }\n    }\n}\n\nvoid Parser::CheckStrictModeEvalArgumentsUsage(IdentPtr pid, ParseNodePtr pnode)\n{\n    if (pid != nullptr)\n    {\n        \/\/ In strict mode, 'eval' \/ 'arguments' cannot be assigned to.\n        if ( pid == wellKnownPropertyPids.eval)\n        {\n            Error(ERREvalUsage, pnode);\n        }\n\n        if (pid == wellKnownPropertyPids.arguments)\n        {\n            Error(ERRArgsUsage, pnode);\n        }\n    }\n}\n\nvoid Parser::ReduceDeferredScriptLength(size_t chars)\n{\n    \/\/ If we're in deferred mode, subtract the given char count from the total length,\n    \/\/ and see if this puts us under the deferral threshold.\n    if ((m_grfscr & fscrDeferFncParse) &&\n        (\n            PHASE_OFF1(Js::DeferEventHandlersPhase) ||\n            (m_grfscr & fscrGlobalCode)\n        )\n    )\n    {\n        if (m_length > chars)\n        {\n            m_length -= chars;\n        }\n        else\n        {\n            m_length = 0;\n        }\n        if (m_length < Parser::GetDeferralThreshold(this->m_sourceContextInfo->IsSourceProfileLoaded()))\n        {\n            \/\/ Stop deferring.\n            m_grfscr &= ~fscrDeferFncParse;\n            m_stoppedDeferredParse = TRUE;\n        }\n    }\n}\n\n\/***************************************************************************\nLook for an existing label with the given name.\n***************************************************************************\/\nBOOL Parser::PnodeLabelNoAST(IdentToken* pToken, LabelId* pLabelIdList)\n{\n    StmtNest* pStmt;\n    LabelId* pLabelId;\n\n    \/\/ Look in the label stack.\n    for (pStmt = m_pstmtCur; pStmt != nullptr; pStmt = pStmt->pstmtOuter)\n    {\n        for (pLabelId = pStmt->pLabelId; pLabelId != nullptr; pLabelId = pLabelId->next)\n        {\n            if (pLabelId->pid == pToken->pid)\n                return TRUE;\n        }\n    }\n\n    \/\/ Also look in the pnodeLabels list.\n    for (pLabelId = pLabelIdList; pLabelId != nullptr; pLabelId = pLabelId->next)\n    {\n        if (pLabelId->pid == pToken->pid)\n            return TRUE;\n    }\n\n    return FALSE;\n}\n\nvoid Parser::EnsureStackAvailable()\n{\n    if (!m_scriptContext->GetThreadContext()->IsStackAvailable(Js::Constants::MinStackCompile))\n    {\n        Error(ERRnoMemory);\n    }\n}\n\nvoid Parser::ThrowNewTargetSyntaxErrForGlobalScope()\n{\n    if (GetCurrentNonLambdaFunctionNode() != nullptr)\n    {\n        return;\n    }\n\n    if ((this->m_grfscr & fscrEval) != 0)\n    {\n        Js::JavascriptFunction * caller = nullptr;\n        if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))\n        {\n            Js::FunctionBody * callerBody = caller->GetFunctionBody();\n            Assert(callerBody);\n            if (!callerBody->GetIsGlobalFunc() && !(callerBody->IsLambda() && callerBody->GetEnclosedByGlobalFunc()))\n            {\n                return;\n            }\n        }\n    }\n\n    Error(ERRInvalidNewTarget);\n }\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseMetaProperty(tokens metaParentKeyword, charcount_t ichMin, _Out_opt_ BOOL* pfCanAssign)\n{\n    AssertMsg(metaParentKeyword == tkNEW, \"Only supported for tkNEW parent keywords\");\n    AssertMsg(this->m_token.tk == tkDot, \"We must be currently sitting on the dot after the parent keyword\");\n\n    m_pscan->Scan();\n\n    if (this->m_token.tk == tkID && this->m_token.GetIdentifier(m_phtbl) == this->GetTargetPid())\n    {\n        ThrowNewTargetSyntaxErrForGlobalScope();\n        if (pfCanAssign)\n        {\n            *pfCanAssign = FALSE;\n        }\n        if (buildAST)\n        {\n            return CreateNodeWithScanner<knopNewTarget>(ichMin);\n        }\n    }\n    else\n    {\n        Error(ERRsyntax);\n    }\n\n    return nullptr;\n}\n\ntemplate<bool buildAST> \nvoid Parser::ParseNamedImportOrExportClause(ModuleImportOrExportEntryList* importOrExportEntryList, bool isExportClause)\n{\n    Assert(m_token.tk == tkLCurly);\n    Assert(importOrExportEntryList != nullptr);\n\n    m_pscan->Scan();\n\n    while (m_token.tk != tkRCurly && m_token.tk != tkEOF)\n    {\n        tokens firstToken = m_token.tk;\n\n        if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))\n        {\n            Error(ERRsyntax);\n        }\n\n        IdentPtr identifierName = m_token.GetIdentifier(m_phtbl);\n        IdentPtr identifierAs = identifierName;\n\n        m_pscan->Scan();\n\n        if (m_token.tk == tkID)\n        {\n            \/\/ We have the pattern \"IdentifierName as\"\n            if (wellKnownPropertyPids.as != m_token.GetIdentifier(m_phtbl))\n            {\n                Error(ERRsyntax);\n            }\n\n            m_pscan->Scan();\n\n            \/\/ If we are parsing an import statement, the token after 'as' must be a BindingIdentifier.\n            if (!isExportClause)\n            {\n                ChkCurTokNoScan(tkID, ERRsyntax);\n            }\n\n            if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))\n            {\n                Error(ERRsyntax);\n            }\n\n            identifierAs = m_token.GetIdentifier(m_phtbl);\n\n            \/\/ Scan to the next token.\n            m_pscan->Scan();\n        }\n        else if (!isExportClause && firstToken != tkID)\n        {\n            \/\/ If we are parsing an import statement and this ImportSpecifier clause did not have\n            \/\/ 'as ImportedBinding' at the end of it, identifierName must be a BindingIdentifier.\n            Error(ERRsyntax);\n        }\n\n        if (m_token.tk == tkComma)\n        {\n            \/\/ Consume a trailing comma\n            m_pscan->Scan();\n        }\n\n        if (buildAST)\n        {\n            \/\/ The name we will use 'as' this import\/export is a binding identifier in import statements.\n            if (!isExportClause)\n            {\n                CreateModuleImportDeclNode(identifierAs);\n                AddModuleImportOrExportEntry(importOrExportEntryList, identifierName, identifierAs, nullptr, nullptr);\n            }\n            else\n            {\n                identifierName->SetIsModuleExport();\n                AddModuleImportOrExportEntry(importOrExportEntryList, nullptr, identifierName, identifierAs, nullptr);\n            }\n        }\n    }\n\n    \/\/ Final token in a named import or export clause must be a '}'\n    ChkCurTokNoScan(tkRCurly, ERRsyntax);\n}\n\nIdentPtrList* Parser::GetRequestedModulesList()\n{\n    return m_currentNodeProg->sxModule.requestedModules;\n}\n\nModuleImportOrExportEntryList* Parser::GetModuleImportEntryList()\n{\n    return m_currentNodeProg->sxModule.importEntries;\n}\n\nModuleImportOrExportEntryList* Parser::GetModuleLocalExportEntryList()\n{\n    return m_currentNodeProg->sxModule.localExportEntries;\n}\n\nModuleImportOrExportEntryList* Parser::GetModuleIndirectExportEntryList()\n{\n    return m_currentNodeProg->sxModule.indirectExportEntries;\n}\n\nModuleImportOrExportEntryList* Parser::GetModuleStarExportEntryList()\n{\n    return m_currentNodeProg->sxModule.starExportEntries;\n}\n\nIdentPtrList* Parser::EnsureRequestedModulesList()\n{\n    if (m_currentNodeProg->sxModule.requestedModules == nullptr)\n    {\n        m_currentNodeProg->sxModule.requestedModules = Anew(&m_nodeAllocator, IdentPtrList, &m_nodeAllocator);\n    }\n    return m_currentNodeProg->sxModule.requestedModules;\n}\n\nModuleImportOrExportEntryList* Parser::EnsureModuleImportEntryList()\n{\n    if (m_currentNodeProg->sxModule.importEntries == nullptr)\n    {\n        m_currentNodeProg->sxModule.importEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);\n    }\n    return m_currentNodeProg->sxModule.importEntries;\n}\n\nModuleImportOrExportEntryList* Parser::EnsureModuleLocalExportEntryList()\n{\n    if (m_currentNodeProg->sxModule.localExportEntries == nullptr)\n    {\n        m_currentNodeProg->sxModule.localExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);\n    }\n    return m_currentNodeProg->sxModule.localExportEntries;\n}\n\nModuleImportOrExportEntryList* Parser::EnsureModuleIndirectExportEntryList()\n{\n    if (m_currentNodeProg->sxModule.indirectExportEntries == nullptr)\n    {\n        m_currentNodeProg->sxModule.indirectExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);\n    }\n    return m_currentNodeProg->sxModule.indirectExportEntries;\n}\n\nModuleImportOrExportEntryList* Parser::EnsureModuleStarExportEntryList()\n{\n    if (m_currentNodeProg->sxModule.starExportEntries == nullptr)\n    {\n        m_currentNodeProg->sxModule.starExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);\n    }\n    return m_currentNodeProg->sxModule.starExportEntries;\n}\n\nvoid Parser::AddModuleSpecifier(IdentPtr moduleRequest)\n{\n    IdentPtrList* requestedModulesList = EnsureRequestedModulesList();\n\n    if (!requestedModulesList->Has(moduleRequest))\n    {\n        requestedModulesList->Prepend(moduleRequest);\n    }\n}\n\nModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, ModuleImportOrExportEntry* importOrExportEntry)\n{\n    if (importOrExportEntry->exportName != nullptr)\n    {\n        CheckForDuplicateExportEntry(importOrExportEntryList, importOrExportEntry->exportName);\n    }\n\n    importOrExportEntryList->Prepend(*importOrExportEntry);\n\n    return importOrExportEntry;\n}\n\nModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, IdentPtr importName, IdentPtr localName, IdentPtr exportName, IdentPtr moduleRequest)\n{\n    ModuleImportOrExportEntry* importOrExportEntry = Anew(&m_nodeAllocator, ModuleImportOrExportEntry);\n\n    importOrExportEntry->importName = importName;\n    importOrExportEntry->localName = localName;\n    importOrExportEntry->exportName = exportName;\n    importOrExportEntry->moduleRequest = moduleRequest;\n\n    return AddModuleImportOrExportEntry(importOrExportEntryList, importOrExportEntry);\n}\n\nvoid Parser::AddModuleLocalExportEntry(ParseNodePtr varDeclNode)\n{\n    Assert(varDeclNode->nop == knopVarDecl || varDeclNode->nop == knopLetDecl || varDeclNode->nop == knopConstDecl);\n\n    IdentPtr localName = varDeclNode->sxVar.pid;\n    varDeclNode->sxVar.sym->SetIsModuleExportStorage(true);\n\n    AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);\n}\n\nvoid Parser::CheckForDuplicateExportEntry(ModuleImportOrExportEntryList* exportEntryList, IdentPtr exportName)\n{\n    ModuleImportOrExportEntry* findResult = exportEntryList->Find([&](ModuleImportOrExportEntry exportEntry)\n    {\n        if (exportName == exportEntry.exportName)\n        {\n            return true;\n        }\n        return false;\n    });\n\n    if (findResult != nullptr)\n    {\n        Error(ERRsyntax);\n    }\n}\n\ntemplate<bool buildAST>\nvoid Parser::ParseImportClause(ModuleImportOrExportEntryList* importEntryList, bool parsingAfterComma)\n{\n    bool parsedNamespaceOrNamedImport = false;\n\n    switch (m_token.tk)\n    {\n    case tkID:\n        \/\/ This is the default binding identifier.\n\n        \/\/ If we already saw a comma in the import clause, this is a syntax error.\n        if (parsingAfterComma)\n        {\n            Error(ERRsyntax);\n        }\n\n        if (buildAST)\n        {\n            IdentPtr localName = m_token.GetIdentifier(m_phtbl);\n            IdentPtr importName = wellKnownPropertyPids._default;\n\n            CreateModuleImportDeclNode(localName);\n            AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);\n        }\n\n        break;\n\n    case tkLCurly:\n        \/\/ This begins a list of named imports.\n        ParseNamedImportOrExportClause<buildAST>(importEntryList, false);\n\n        parsedNamespaceOrNamedImport = true;\n        break;\n\n    case tkStar:\n        \/\/ This begins a namespace import clause.\n        \/\/ \"* as ImportedBinding\"\n\n        \/\/ Token following * must be the identifier 'as'\n        m_pscan->Scan();\n        if (m_token.tk != tkID || wellKnownPropertyPids.as != m_token.GetIdentifier(m_phtbl))\n        {\n            Error(ERRsyntax);\n        }\n\n        \/\/ Token following 'as' must be a binding identifier.\n        m_pscan->Scan();\n        ChkCurTokNoScan(tkID, ERRsyntax);\n\n        if (buildAST)\n        {\n            IdentPtr localName = m_token.GetIdentifier(m_phtbl);\n            IdentPtr importName = wellKnownPropertyPids._star;\n\n            CreateModuleImportDeclNode(localName);\n            AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);\n        }\n\n        parsedNamespaceOrNamedImport = true;\n        break;\n\n    default:\n        Error(ERRsyntax);\n    }\n\n    m_pscan->Scan();\n\n    if (m_token.tk == tkComma)\n    {\n        \/\/ There cannot be more than one comma in a module import clause.\n        \/\/ There cannot be a namespace import or named imports list on the left of the comma in a module import clause.\n        if (parsingAfterComma || parsedNamespaceOrNamedImport)\n        {\n            Error(ERRsyntax);\n        }\n\n        m_pscan->Scan();\n\n        ParseImportClause<buildAST>(importEntryList, true);\n    }\n}\n\nbool Parser::IsImportOrExportStatementValidHere()\n{\n    ParseNodePtr curFunc = GetCurrentFunctionNode();\n\n    \/\/ Import must be located in the top scope of the module body.\n    return curFunc->nop == knopFncDecl\n        && curFunc->sxFnc.IsModule()\n        && this->m_currentBlockInfo->pnodeBlock == curFunc->sxFnc.pnodeBodyScope\n        && (this->m_grfscr & fscrEvalCode) != fscrEvalCode\n        && this->m_tryCatchOrFinallyDepth == 0;\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseImportDeclaration()\n{\n    Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());\n    Assert(m_token.tk == tkIMPORT);\n\n    if (!IsImportOrExportStatementValidHere())\n    {\n        Error(ERRInvalidModuleImportOrExport);\n    }\n\n    \/\/ We just parsed an import token. Next valid token is *, {, string constant, or binding identifier.\n    m_pscan->Scan();\n\n    if (m_token.tk == tkStrCon)\n    {\n        \/\/ This import declaration has no import clause.\n        \/\/ \"import ModuleSpecifier;\"\n        if (buildAST)\n        {\n            AddModuleSpecifier(m_token.GetStr());\n        }\n\n        \/\/ Scan past the module identifier.\n        m_pscan->Scan();\n    }\n    else\n    {\n        ModuleImportOrExportEntryList importEntryList(&m_nodeAllocator);\n\n        \/\/ Parse the import clause (default binding can only exist before the comma).\n        ParseImportClause<buildAST>(&importEntryList);\n\n        \/\/ Token following import clause must be the identifier 'from'\n        IdentPtr moduleSpecifier = ParseImportOrExportFromClause<buildAST>(true);\n\n        if (buildAST)\n        {\n            Assert(moduleSpecifier != nullptr);\n\n            AddModuleSpecifier(moduleSpecifier);\n\n            importEntryList.Map([this, moduleSpecifier](ModuleImportOrExportEntry& importEntry) {\n                importEntry.moduleRequest = moduleSpecifier;\n                AddModuleImportOrExportEntry(EnsureModuleImportEntryList(), &importEntry);\n            });\n        }\n\n        importEntryList.Clear();\n    }\n\n    \/\/ Import statement is actually a nop, we hoist all the imported bindings to the top of the module.\n    return nullptr;\n}\n\ntemplate<bool buildAST>\nIdentPtr Parser::ParseImportOrExportFromClause(bool throwIfNotFound)\n{\n    IdentPtr moduleSpecifier = nullptr;\n\n    if (m_token.tk == tkID && wellKnownPropertyPids.from == m_token.GetIdentifier(m_phtbl))\n    {\n        m_pscan->Scan();\n\n        \/\/ Token following the 'from' token must be a string constant - the module specifier.\n        ChkCurTokNoScan(tkStrCon, ERRsyntax);\n\n        if (buildAST)\n        {\n            moduleSpecifier = m_token.GetStr();\n        }\n\n        m_pscan->Scan();\n    }\n    else if (throwIfNotFound)\n    {\n        Error(ERRsyntax);\n    }\n\n    return moduleSpecifier;\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseDefaultExportClause()\n{\n    Assert(m_token.tk == tkDEFAULT);\n\n    m_pscan->Scan();\n    ParseNodePtr pnode = nullptr;\n    ushort flags = fFncNoFlgs;\n\n    switch (m_token.tk)\n    {\n    case tkCLASS:\n        {\n            if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())\n            {\n                goto LDefault;\n            }\n\n            \/\/ Before we parse the class itself we need to know if the class has an identifier name.\n            \/\/ If it does, we'll treat this class as an ordinary class declaration which will bind\n            \/\/ it to that name. Otherwise the class should parse as a nameless class expression and\n            \/\/ bind only to the export binding.\n            BOOL classHasName = false;\n            RestorePoint parsedClass;\n            m_pscan->Capture(&parsedClass);\n            m_pscan->Scan();\n\n            if (m_token.tk == tkID)\n            {\n                classHasName = true;\n            }\n\n            m_pscan->SeekTo(parsedClass);\n            pnode = ParseClassDecl<buildAST>(classHasName, nullptr, nullptr, nullptr);\n\n            if (buildAST)\n            {\n                AnalysisAssert(pnode != nullptr);\n                Assert(pnode->nop == knopClassDecl);\n\n                pnode->sxClass.SetIsDefaultModuleExport(true);\n            }\n\n            break;\n        }\n    case tkID:\n        \/\/ If we parsed an async token, it could either modify the next token (if it is a\n        \/\/ function token) or it could be an identifier (let async = 0; export default async;).\n        \/\/ To handle both cases, when we parse an async token we need to keep the parser state\n        \/\/ and rewind if the next token is not function.\n        if (wellKnownPropertyPids.async == m_token.GetIdentifier(m_phtbl))\n        {\n            RestorePoint parsedAsync;\n            m_pscan->Capture(&parsedAsync);\n            m_pscan->Scan();\n            if (m_token.tk == tkFUNCTION)\n            {\n                \/\/ Token after async is function, consume the async token and continue to parse the\n                \/\/ function as an async function.\n                flags |= fFncAsync;\n                goto LFunction;\n            }\n            \/\/ Token after async is not function, no idea what the async token is supposed to mean\n            \/\/ so rewind and let the default case handle it.\n            m_pscan->SeekTo(parsedAsync);\n        }\n        goto LDefault;\n        break;\n    case tkFUNCTION:\n        {\nLFunction:\n            \/\/ We just parsed a function token but we need to figure out if the function\n            \/\/ has an identifier name or not before we call the helper.\n            RestorePoint parsedFunction;\n            m_pscan->Capture(&parsedFunction);\n            m_pscan->Scan();\n\n            if (m_token.tk == tkStar)\n            {\n                \/\/ If we saw 'function*' that indicates we are going to parse a generator,\n                \/\/ but doesn't tell us if the generator has an identifier or not.\n                \/\/ Skip the '*' token for now as it doesn't matter yet.\n                m_pscan->Scan();\n            }\n\n            \/\/ We say that if the function has an identifier name, it is a 'normal' declaration\n            \/\/ and should create a binding to that identifier as well as one for our default export.\n            if (m_token.tk == tkID)\n            {\n                flags |= fFncDeclaration;\n            }\n            else\n            {\n                flags |= fFncNoName;\n            }\n\n            \/\/ Rewind back to the function token and let the helper handle the parsing.\n            m_pscan->SeekTo(parsedFunction);\n            pnode = ParseFncDecl<buildAST>(flags);\n            \n            if (buildAST)\n            {\n                AnalysisAssert(pnode != nullptr);\n                Assert(pnode->nop == knopFncDecl);\n\n                pnode->sxFnc.SetIsDefaultModuleExport(true);\n            }\n            break;\n        }\n    default:\nLDefault:\n        {\n            ParseNodePtr pnodeExpression = ParseExpr<buildAST>();\n\n            \/\/ Consider: Can we detect this syntax error earlier?\n            if (pnodeExpression && pnodeExpression->nop == knopComma)\n            {\n                Error(ERRsyntax);\n            }\n\n            if (buildAST)\n            {\n                AnalysisAssert(pnodeExpression != nullptr);\n\n                \/\/ Mark this node as the default module export. We need to make sure it is put into the correct\n                \/\/ module export slot when we emit the node.\n                pnode = CreateNode(knopExportDefault);\n                pnode->sxExportDefault.pnodeExpr = pnodeExpression;\n            }\n            break;\n        }\n    }\n\n    IdentPtr exportName = wellKnownPropertyPids._default;\n    IdentPtr localName = wellKnownPropertyPids._starDefaultStar;\n    AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, exportName, nullptr);\n\n    return pnode;\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseExportDeclaration()\n{\n    Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());\n    Assert(m_token.tk == tkEXPORT);\n\n    if (!IsImportOrExportStatementValidHere())\n    {\n        Error(ERRInvalidModuleImportOrExport);\n    }\n\n    ParseNodePtr pnode = nullptr;\n    IdentPtr moduleIdentifier = nullptr;\n    tokens declarationType;\n\n    \/\/ We just parsed an export token. Next valid tokens are *, {, var, let, const, async, function, class, default.\n    m_pscan->Scan();\n\n    switch (m_token.tk)\n    {\n    case tkStar:\n        m_pscan->Scan();\n\n        \/\/ A star token in an export declaration must be followed by a from clause which begins with a token 'from'.\n        moduleIdentifier = ParseImportOrExportFromClause<buildAST>(true);\n\n        if (buildAST)\n        {\n            Assert(moduleIdentifier != nullptr);\n\n            AddModuleSpecifier(moduleIdentifier);\n            IdentPtr importName = wellKnownPropertyPids._star;\n\n            AddModuleImportOrExportEntry(EnsureModuleStarExportEntryList(), importName, nullptr, nullptr, moduleIdentifier);\n        }\n\n        break;\n\n    case tkLCurly:\n        {\n            ModuleImportOrExportEntryList exportEntryList(&m_nodeAllocator);\n\n            ParseNamedImportOrExportClause<buildAST>(&exportEntryList, true);\n\n            m_pscan->Scan();\n\n            \/\/ Export clause may be followed by a from clause.\n            moduleIdentifier = ParseImportOrExportFromClause<buildAST>(false);\n\n            if (buildAST)\n            {\n                if (moduleIdentifier != nullptr)\n                {\n                    AddModuleSpecifier(moduleIdentifier);\n                }\n\n                exportEntryList.Map([this, moduleIdentifier](ModuleImportOrExportEntry& exportEntry) {\n                    if (moduleIdentifier != nullptr)\n                    {\n                        exportEntry.moduleRequest = moduleIdentifier;\n\n                        \/\/ We need to swap localname and importname when this is a re-export.\n                        exportEntry.importName = exportEntry.localName;\n                        exportEntry.localName = nullptr;\n\n                        AddModuleImportOrExportEntry(EnsureModuleIndirectExportEntryList(), &exportEntry);\n                    }\n                    else\n                    {\n                        AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), &exportEntry);\n                    }\n                });\n\n                exportEntryList.Clear();\n            }\n        }\n        break;\n\n    case tkID:\n        {\n            IdentPtr pid = m_token.GetIdentifier(m_phtbl);\n\n            if (wellKnownPropertyPids.let == pid)\n            {\n                declarationType = tkLET;\n                goto ParseVarDecl;\n            }\n            if (wellKnownPropertyPids.async == pid && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())\n            {\n                \/\/ In module export statements, async token is only valid if it's followed by function.\n                \/\/ We need to check here because ParseStatement would think 'async = 20' is a var decl.\n                RestorePoint parsedAsync;\n                m_pscan->Capture(&parsedAsync);\n                m_pscan->Scan();\n                if (m_token.tk == tkFUNCTION)\n                {\n                    \/\/ Token after async is function, rewind to the async token and let ParseStatement handle it.\n                    m_pscan->SeekTo(parsedAsync);\n                    goto ParseFunctionDecl;\n                }\n                \/\/ Token after async is not function, it's a syntax error.\n            }\n            goto ErrorToken;\n        }\n    case tkVAR:\n    case tkLET:\n    case tkCONST:\n        {\n            declarationType = m_token.tk;\n\nParseVarDecl:\n            m_pscan->Scan();\n\n            pnode = ParseVariableDeclaration<buildAST>(declarationType, m_pscan->IchMinTok());\n\n            if (buildAST)\n            {\n                ParseNodePtr temp = pnode;\n                while (temp->nop == knopList)\n                {\n                    ParseNodePtr varDeclNode = temp->sxBin.pnode1;\n                    temp = temp->sxBin.pnode2;\n\n                    AddModuleLocalExportEntry(varDeclNode);\n                }\n                AddModuleLocalExportEntry(temp);\n            }\n        }\n        break;\n\n    case tkFUNCTION:\n    case tkCLASS:\n        {\nParseFunctionDecl:\n            pnode = ParseStatement<buildAST>();\n\n            if (buildAST)\n            {\n                IdentPtr localName;\n                if (pnode->nop == knopClassDecl)\n                {\n                    pnode->sxClass.pnodeName->sxVar.sym->SetIsModuleExportStorage(true);\n                    pnode->sxClass.pnodeDeclName->sxVar.sym->SetIsModuleExportStorage(true);\n                    localName = pnode->sxClass.pnodeName->sxVar.pid;\n                }\n                else\n                {\n                    Assert(pnode->nop == knopFncDecl);\n\n                    pnode->sxFnc.GetFuncSymbol()->SetIsModuleExportStorage(true);\n                    localName = pnode->sxFnc.pid;\n                }\n                Assert(localName != nullptr);\n\n                AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);\n            }\n        }\n        break;\n\n    case tkDEFAULT:\n        {\n            pnode = ParseDefaultExportClause<buildAST>();\n        }\n        break;\n\n    default:\n        {\nErrorToken:\n            Error(ERRsyntax);\n        }\n    }\n\n    return pnode;\n}\n\n\/***************************************************************************\nParse an expression term.\n***************************************************************************\/\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseTerm(BOOL fAllowCall,\n    LPCOLESTR pNameHint,\n    uint32 *pHintLength,\n    uint32 *pShortNameOffset,\n    _Inout_opt_ IdentToken* pToken \/*= nullptr*\/,\n    bool fUnaryOrParen \/*= false*\/,\n    _Out_opt_ BOOL* pfCanAssign \/*= nullptr*\/,\n    _Inout_opt_ BOOL* pfLikelyPattern \/*= nullptr*\/,\n    _Out_opt_ bool* pfIsDotOrIndex \/*= nullptr*\/)\n{\n    ParseNodePtr pnode = nullptr;\n    charcount_t ichMin = 0;\n    size_t iecpMin = 0;\n    size_t iuMin;\n    IdentToken term;\n    BOOL fInNew = FALSE;\n    BOOL fCanAssign = TRUE;\n    bool isAsyncExpr = false;\n    bool isLambdaExpr = false;\n    Assert(pToken == nullptr || pToken->tk == tkNone); \/\/ Must be empty initially\n\n    if (this->IsBackgroundParser())\n    {\n        PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackParseOneTerm);\n    }\n    else\n    {\n        PROBE_STACK(m_scriptContext, Js::Constants::MinStackParseOneTerm);\n    }\n\n    switch (m_token.tk)\n    {\n    case tkID:\n    {\n        PidRefStack *ref = nullptr;\n        IdentPtr pid = m_token.GetIdentifier(m_phtbl);\n        charcount_t ichLim = m_pscan->IchLimTok();\n        size_t iecpLim = m_pscan->IecpLimTok();\n        ichMin = m_pscan->IchMinTok();\n        iecpMin  = m_pscan->IecpMinTok();\n\n        if (pid == wellKnownPropertyPids.async &&\n            m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())\n        {\n            isAsyncExpr = true;\n        }\n\n        bool previousAwaitIsKeyword = m_pscan->SetAwaitIsKeyword(isAsyncExpr);\n        m_pscan->Scan();\n        m_pscan->SetAwaitIsKeyword(previousAwaitIsKeyword);\n\n        \/\/ We search for an Async expression (a function declaration or an async lambda expression)\n        if (isAsyncExpr && !m_pscan->FHadNewLine())\n        {\n            if (m_token.tk == tkFUNCTION)\n            {\n                goto LFunction;\n            }\n            else if (m_token.tk == tkID || m_token.tk == tkAWAIT)\n            {\n                isLambdaExpr = true;\n                goto LFunction;\n            }\n        }\n\n        ref = this->PushPidRef(pid);\n\n        if (buildAST)\n        {\n            pnode = CreateNameNode(pid);\n            pnode->ichMin = ichMin;\n            pnode->ichLim = ichLim;\n            pnode->sxPid.SetSymRef(ref);\n        }\n        else\n        {\n            \/\/ Remember the identifier start and end in case it turns out to be a statement label.\n            term.tk = tkID;\n            term.pid = pid; \/\/ Record the identifier for detection of eval\n            term.ichMin = static_cast<charcount_t>(iecpMin);\n            term.ichLim = static_cast<charcount_t>(iecpLim);\n        }\n        CheckArgumentsUse(pid, GetCurrentFunctionNode());\n        break;\n    }\n\n    case tkTHIS:\n        if (buildAST)\n        {\n            pnode = CreateNodeWithScanner<knopThis>();\n        }\n        fCanAssign = FALSE;\n        m_pscan->Scan();\n        break;\n\n    case tkLParen:\n        ichMin = m_pscan->IchMinTok();\n        iuMin = m_pscan->IecpMinTok();\n        m_pscan->Scan();\n        if (m_token.tk == tkRParen)\n        {\n            \/\/ Empty parens can only be legal as an empty parameter list to a lambda declaration.\n            \/\/ We're in a lambda if the next token is =>.\n            fAllowCall = FALSE;\n            m_pscan->Scan();\n\n            \/\/ If the token after the right paren is not => or if there was a newline between () and => this is a syntax error\n            if (!m_doingFastScan && (m_token.tk != tkDArrow || m_pscan->FHadNewLine()))\n            {\n                Error(ERRsyntax);\n            }\n\n            if (buildAST)\n            {\n                pnode = CreateNodeWithScanner<knopEmpty>();\n            }\n            break;\n        }\n\n        this->m_parenDepth++;\n        pnode = ParseExpr<buildAST>(koplNo, &fCanAssign, TRUE, FALSE, nullptr, nullptr \/*nameLength*\/, nullptr  \/*pShortNameOffset*\/, &term, true);\n        this->m_parenDepth--;\n\n        ChkCurTok(tkRParen, ERRnoRparen);\n        \/\/ Emit a deferred ... error if one was parsed.\n        if (m_deferEllipsisError && m_token.tk != tkDArrow)\n        {\n            m_pscan->SeekTo(m_EllipsisErrLoc);\n            Error(ERRInvalidSpreadUse);\n        }\n        else\n        {\n            m_deferEllipsisError = false;\n        }\n        break;\n\n    case tkIntCon:\n        if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())\n        {\n            Error(ERRES5NoOctal);\n        }\n\n        if (buildAST)\n        {\n            pnode = CreateIntNodeWithScanner(m_token.GetLong());\n        }\n        fCanAssign = FALSE;\n        m_pscan->Scan();\n        break;\n\n    case tkFltCon:\n        if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())\n        {\n            Error(ERRES5NoOctal);\n        }\n\n        if (buildAST)\n        {\n            pnode = CreateNodeWithScanner<knopFlt>();\n            pnode->sxFlt.dbl = m_token.GetDouble();\n            pnode->sxFlt.maybeInt = m_token.GetDoubleMayBeInt();\n        }\n        fCanAssign = FALSE;\n        m_pscan->Scan();\n        break;\n\n    case tkStrCon:\n        if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())\n        {\n            Error(ERRES5NoOctal);\n        }\n\n        if (buildAST)\n        {\n            pnode = CreateStrNodeWithScanner(m_token.GetStr());\n        }\n        else\n        {\n            \/\/ Subtract the string literal length from the total char count for the purpose\n            \/\/ of deciding whether to defer parsing and byte code generation.\n            this->ReduceDeferredScriptLength(m_pscan->IchLimTok() - m_pscan->IchMinTok());\n        }\n        fCanAssign = FALSE;\n        m_pscan->Scan();\n        break;\n\n    case tkTRUE:\n        if (buildAST)\n        {\n            pnode = CreateNodeWithScanner<knopTrue>();\n        }\n        fCanAssign = FALSE;\n        m_pscan->Scan();\n        break;\n\n    case tkFALSE:\n        if (buildAST)\n        {\n            pnode = CreateNodeWithScanner<knopFalse>();\n        }\n        fCanAssign = FALSE;\n        m_pscan->Scan();\n        break;\n\n    case tkNULL:\n        if (buildAST)\n        {\n            pnode = CreateNodeWithScanner<knopNull>();\n        }\n        fCanAssign = FALSE;\n        m_pscan->Scan();\n        break;\n\n    case tkDiv:\n    case tkAsgDiv:\n        pnode = ParseRegExp<buildAST>();\n        fCanAssign = FALSE;\n        m_pscan->Scan();\n        break;\n\n    case tkNEW:\n    {\n        ichMin = m_pscan->IchMinTok();\n        m_pscan->Scan();\n\n        if (m_token.tk == tkDot && m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())\n        {\n            pnode = ParseMetaProperty<buildAST>(tkNEW, ichMin, &fCanAssign);\n\n            m_pscan->Scan();\n        }\n        else\n        {\n            ParseNodePtr pnodeExpr = ParseTerm<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset);\n            if (buildAST)\n            {\n                pnode = CreateCallNode(knopNew, pnodeExpr, nullptr);\n                pnode->ichMin = ichMin;\n            }\n            fInNew = TRUE;\n            fCanAssign = FALSE;\n        }\n        break;\n    }\n\n    case tkLBrack:\n    {\n        ichMin = m_pscan->IchMinTok();\n        m_pscan->Scan();\n        pnode = ParseArrayLiteral<buildAST>();\n        if (buildAST)\n        {\n            pnode->ichMin = ichMin;\n            pnode->ichLim = m_pscan->IchLimTok();\n        }\n\n        if (this->m_arrayDepth == 0)\n        {\n            Assert(m_pscan->IchLimTok() - ichMin > m_funcInArray);\n            this->ReduceDeferredScriptLength(m_pscan->IchLimTok() - ichMin - this->m_funcInArray);\n            this->m_funcInArray = 0;\n            this->m_funcInArrayDepth = 0;\n        }\n        ChkCurTok(tkRBrack, ERRnoRbrack);\n        if (!IsES6DestructuringEnabled())\n        {\n            fCanAssign = FALSE;\n        }\n        else if (pfLikelyPattern != nullptr && !IsPostFixOperators())\n        {\n            *pfLikelyPattern = TRUE;\n        }\n        break;\n    }\n\n    case tkLCurly:\n    {\n        ichMin = m_pscan->IchMinTok();\n        m_pscan->ScanForcingPid();\n        ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(pNameHint, pHintLength);\n        if (buildAST)\n        {\n            pnode = CreateUniNode(knopObject, pnodeMemberList);\n            pnode->ichMin = ichMin;\n            pnode->ichLim = m_pscan->IchLimTok();\n        }\n        ChkCurTok(tkRCurly, ERRnoRcurly);\n        if (!IsES6DestructuringEnabled())\n        {\n            fCanAssign = FALSE;\n        }\n        else if (pfLikelyPattern != nullptr && !IsPostFixOperators())\n        {\n            *pfLikelyPattern = TRUE;\n        }\n        break;\n    }\n\n    case tkFUNCTION:\n    {\nLFunction :\n        if (m_grfscr & fscrDeferredFncExpression)\n        {\n            \/\/ The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now\n            \/\/ parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the\n            \/\/ first time we see it.\n            \/\/\n            \/\/ Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first\n            \/\/ token of the source code of the function may not a 'function' token though, so we still need to reset this flag\n            \/\/ for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed\n            \/\/ in parentheses, where the legacy behavior was to include the parentheses in the function's source code.\n            m_grfscr &= ~fscrDeferredFncExpression;\n        }\n        ushort flags = fFncNoFlgs;\n        if (isLambdaExpr)\n        {\n            flags |= fFncLambda;\n        }\n        if (isAsyncExpr)\n        {\n            flags |= fFncAsync;\n        }\n        pnode = ParseFncDecl<buildAST>(flags, pNameHint, false, true, fUnaryOrParen);\n        if (isAsyncExpr)\n        {\n            pnode->sxFnc.cbMin = iecpMin;\n            pnode->ichMin = ichMin;\n        }\n        fCanAssign = FALSE;\n        break;\n    }\n\n    case tkCLASS:\n        if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())\n        {\n            pnode = ParseClassDecl<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset);\n        }\n        else\n        {\n            goto LUnknown;\n        }\n        fCanAssign = FALSE;\n        break;\n\n    case tkStrTmplBasic:\n    case tkStrTmplBegin:\n        pnode = ParseStringTemplateDecl<buildAST>(nullptr);\n        fCanAssign = FALSE;\n        break;\n\n    case tkSUPER:\n        if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())\n        {\n            pnode = ParseSuper<buildAST>(pnode, !!fAllowCall);\n        }\n        else\n        {\n            goto LUnknown;\n        }\n        break;\n\n    case tkCASE:\n    {\n        if (!m_doingFastScan)\n        {\n            goto LUnknown;\n        }\n        ParseNodePtr pnodeUnused;\n        pnode = ParseCase<buildAST>(&pnodeUnused);\n        break;\n    }\n\n    case tkELSE:\n        if (!m_doingFastScan)\n        {\n            goto LUnknown;\n        }\n        m_pscan->Scan();\n        ParseStatement<buildAST>();\n        break;\n\n    default:\n    LUnknown :\n        Error(ERRsyntax);\n        break;\n    }\n\n    pnode = ParsePostfixOperators<buildAST>(pnode, fAllowCall, fInNew, &fCanAssign, &term, pfIsDotOrIndex);\n\n    \/\/ Pass back identifier if requested\n    if (pToken && term.tk == tkID)\n    {\n        *pToken = term;\n    }\n\n    if (pfCanAssign)\n    {\n        *pfCanAssign = fCanAssign;\n    }\n\n    return pnode;\n}\n\ntemplate <bool buildAST>\nParseNodePtr Parser::ParseRegExp()\n{\n    ParseNodePtr pnode = nullptr;\n\n    if (buildAST || m_doingFastScan)\n    {\n        m_pscan->RescanRegExp();\n\n        BOOL saveDeferringAST = this->m_deferringAST;\n        if (m_doingFastScan)\n        {\n            this->m_deferringAST = false;\n        }\n        pnode = CreateNodeWithScanner<knopRegExp>();\n        pnode->sxPid.regexPattern = m_token.GetRegex();\n        if (m_doingFastScan)\n        {\n            this->m_deferringAST = saveDeferringAST;\n            this->AddFastScannedRegExpNode(pnode);\n            if (!buildAST)\n            {\n                pnode = nullptr;\n            }\n        }\n#if ENABLE_BACKGROUND_PARSING\n        else if (this->IsBackgroundParser())\n        {\n            Assert(pnode->sxPid.regexPattern == nullptr);\n            this->AddBackgroundRegExpNode(pnode);\n        }\n#endif\n    }\n    else\n    {\n        m_pscan->RescanRegExpNoAST();\n    }\n    Assert(m_token.tk == tkRegExp);\n\n    return pnode;\n}\n\nBOOL Parser::NodeIsEvalName(ParseNodePtr pnode)\n{\n    \/\/WOOB 1107758 Special case of indirect eval binds to local scope in standards mode\n    return pnode->nop == knopName && (pnode->sxPid.pid == wellKnownPropertyPids.eval);\n}\n\nBOOL Parser::NodeEqualsName(ParseNodePtr pnode, LPCOLESTR sz, uint32 cch)\n{\n    return pnode->nop == knopName &&\n        pnode->sxPid.pid->Cch() == cch &&\n        !wmemcmp(pnode->sxPid.pid->Psz(), sz, cch);\n}\n\nBOOL Parser::NodeIsIdent(ParseNodePtr pnode, IdentPtr pid)\n{\n    for (;;)\n    {\n        switch (pnode->nop)\n        {\n        case knopName:\n            return (pnode->sxPid.pid == pid);\n\n        case knopComma:\n            pnode = pnode->sxBin.pnode2;\n            break;\n\n        default:\n            return FALSE;\n        }\n    }\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParsePostfixOperators(\n    ParseNodePtr pnode,\n    BOOL fAllowCall,\n    BOOL fInNew,\n    BOOL *pfCanAssign,\n    _Inout_ IdentToken* pToken,\n    _Out_opt_ bool* pfIsDotOrIndex \/*= nullptr *\/)\n{\n    uint16 count = 0;\n    bool callOfConstants = false;\n    if (pfIsDotOrIndex)\n    {\n        *pfIsDotOrIndex = false;\n    }\n\n    for (;;)\n    {\n        uint16 spreadArgCount = 0;\n        switch (m_token.tk)\n        {\n        case tkLParen:\n            {\n                if (fInNew)\n                {\n                    ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);\n                    if (buildAST)\n                    {\n                        Assert(pnode->nop == knopNew);\n                        Assert(pnode->sxCall.pnodeArgs == nullptr);\n                        pnode->sxCall.pnodeArgs = pnodeArgs;\n                        pnode->sxCall.callOfConstants = callOfConstants;\n                        pnode->sxCall.isApplyCall = false;\n                        pnode->sxCall.isEvalCall = false;\n                        pnode->sxCall.argCount = count;\n                        pnode->sxCall.spreadArgCount = spreadArgCount;\n                        pnode->ichLim = m_pscan->IchLimTok();\n                    }\n                    else\n                    {\n                        pnode = nullptr;\n                        pToken->tk = tkNone; \/\/ This is no longer an identifier\n                    }\n                    fInNew = FALSE;\n                }\n                else\n                {\n                    bool fCallIsEval = false;\n                    if (!fAllowCall)\n                    {\n                        return pnode;\n                    }\n\n                    ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);\n                    \/\/ We used to un-defer a deferred function body here if it was called as part of the expression that declared it.\n                    \/\/ We now detect this case up front in ParseFncDecl, which is cheaper and simpler.\n                    if (buildAST)\n                    {\n                        pnode = CreateCallNode(knopCall, pnode, pnodeArgs);\n                        Assert(pnode);\n\n                        \/\/ Detect call to \"eval\" and record it on the function.\n                        \/\/ Note: we used to leave it up to the byte code generator to detect eval calls\n                        \/\/ at global scope, but now it relies on the flag the parser sets, so set it here.\n\n                        if (count > 0 && this->NodeIsEvalName(pnode->sxCall.pnodeTarget))\n                        {\n                            this->MarkEvalCaller();\n                            fCallIsEval = true;\n                        }\n\n                        pnode->sxCall.callOfConstants = callOfConstants;\n                        pnode->sxCall.spreadArgCount = spreadArgCount;\n                        pnode->sxCall.isApplyCall = false;\n                        pnode->sxCall.isEvalCall = fCallIsEval;\n                        pnode->sxCall.argCount = count;\n                        pnode->ichLim = m_pscan->IchLimTok();\n                    }\n                    else\n                    {\n                        pnode = nullptr;\n                        if (pToken->tk == tkID && pToken->pid == wellKnownPropertyPids.eval && count > 0) \/\/ Detect eval\n                        {\n                            this->MarkEvalCaller();\n                        }\n                        pToken->tk = tkNone; \/\/ This is no longer an identifier\n                    }\n                }\n                ChkCurTok(tkRParen, ERRnoRparen);\n                if (pfCanAssign)\n                {\n                    *pfCanAssign = FALSE;\n                }\n                if (pfIsDotOrIndex)\n                {\n                    *pfIsDotOrIndex = false;\n                }\n                break;\n            }\n        case tkLBrack:\n            {\n                m_pscan->Scan();\n                ParseNodePtr pnodeExpr = ParseExpr<buildAST>();\n                if (buildAST)\n                {\n                    pnode = CreateBinNode(knopIndex, pnode, pnodeExpr);\n                    pnode->ichLim = m_pscan->IchLimTok();\n                }\n                else\n                {\n                    pnode = nullptr;\n                    pToken->tk = tkNone; \/\/ This is no longer an identifier\n                }\n                ChkCurTok(tkRBrack, ERRnoRbrack);\n                if (pfCanAssign)\n                {\n                    *pfCanAssign = TRUE;\n                }\n                if (pfIsDotOrIndex)\n                {\n                    *pfIsDotOrIndex = true;\n                }\n\n                if (!buildAST)\n                {\n                    break;\n                }\n\n                bool shouldConvertToDot = false;\n                if (pnode->sxBin.pnode2->nop == knopStr)\n                {\n                    \/\/ if the string is empty or contains escape character, we will not convert them to dot node\n                    shouldConvertToDot = pnode->sxBin.pnode2->sxPid.pid->Cch() > 0 && !m_pscan->IsEscapeOnLastTkStrCon();\n                }\n\n                if (shouldConvertToDot)\n                {\n                    LPCOLESTR str = pnode->sxBin.pnode2->sxPid.pid->Psz();\n                    \/\/ See if we can convert o[\"p\"] into o.p and o[\"0\"] into o[0] since they're equivalent and the latter forms\n                    \/\/ are faster\n                    uint32 uintValue;\n                    if(Js::JavascriptOperators::TryConvertToUInt32(\n                           str,\n                           pnode->sxBin.pnode2->sxPid.pid->Cch(),\n                           &uintValue) &&\n                       !Js::TaggedInt::IsOverflow(uintValue)) \/\/ the optimization is not very useful if the number can't be represented as a TaggedInt\n                    {\n                        \/\/ No need to verify that uintValue != JavascriptArray::InvalidIndex since all nonnegative TaggedInts are valid indexes\n                        auto intNode = CreateIntNodeWithScanner(uintValue); \/\/ implicit conversion from uint32 to int32\n                        pnode->sxBin.pnode2 = intNode;\n                    }\n                    \/\/ Field optimization (see GlobOpt::KillLiveElems) checks for value being a Number,\n                    \/\/ and since NaN\/Infinity is a number it won't kill o.NaN\/o.Infinity which would cause a problem\n                    \/\/ if we decide to hoist o.NaN\/o.Infinity.\n                    \/\/ We need to keep o[\"NaN\"] and o[\"+\/-Infinity\"] as array element access (we don't hoist that but we may hoist field access),\n                    \/\/ so no matter if it's killed by o[x] inside a loop, we make sure that we never hoist these.\n                    \/\/ We need to follow same logic for strings that convert to a floating point number.\n                    else\n                    {\n                        bool doConvertToProperty = false;    \/\/ Convert a[\"x\"] -> a.x.\n                        if (!Parser::IsNaNOrInfinityLiteral<true>(str))\n                        {\n                            const OLECHAR* terminalChar;\n                            double dbl = Js::NumberUtilities::StrToDbl(str, &terminalChar, m_scriptContext);\n                            bool convertsToFloat = !Js::NumberUtilities::IsNan(dbl);\n                            doConvertToProperty = !convertsToFloat;\n                        }\n\n                        if (doConvertToProperty)\n                        {\n                            pnode->sxBin.pnode2->nop = knopName;\n                            pnode->nop = knopDot;\n                            pnode->grfpn |= PNodeFlags::fpnIndexOperator;\n                        }\n                    }\n                }\n            }\n            break;\n\n        case tkDot:\n            {\n            ParseNodePtr name = nullptr;\n            OpCode opCode = knopDot;\n\n            m_pscan->Scan();\n            if (!m_token.IsIdentifier())\n            {\n                \/\/allow reserved words in ES5 mode\n                if (!(m_token.IsReservedWord()))\n                {\n                    IdentifierExpectedError(m_token);\n                }\n            }\n            \/\/ Note: see comment above about field optimization WRT NaN\/Infinity\/-Infinity.\n            \/\/ Convert a.Nan, a.Infinity into a[\"NaN\"], a[\"Infinity\"].\n            \/\/ We don't care about -Infinity case here because x.-Infinity is invalid in JavaScript.\n            \/\/ Both NaN and Infinity are identifiers.\n            else if (buildAST && Parser::IsNaNOrInfinityLiteral<false>(m_token.GetIdentifier(m_phtbl)->Psz()))\n            {\n                opCode = knopIndex;\n            }\n\n            if (buildAST)\n            {\n                if (opCode == knopDot)\n                {\n                    name = CreateNameNode(m_token.GetIdentifier(m_phtbl));\n                }\n                else\n                {\n                    Assert(opCode == knopIndex);\n                    name = CreateStrNodeWithScanner(m_token.GetIdentifier(m_phtbl));\n                }\n                pnode = CreateBinNode(opCode, pnode, name);\n            }\n            else\n            {\n                pnode = nullptr;\n                pToken->tk = tkNone;\n            }\n\n            if (pfCanAssign)\n            {\n                *pfCanAssign = TRUE;\n            }\n            if (pfIsDotOrIndex)\n            {\n                *pfIsDotOrIndex = true;\n            }\n            m_pscan->Scan();\n\n            break;\n            }\n\n        case tkStrTmplBasic:\n        case tkStrTmplBegin:\n            {\n                ParseNode* templateNode = ParseStringTemplateDecl<buildAST>(pnode);\n\n                if (!buildAST)\n                {\n                    pToken->tk = tkNone; \/\/ This is no longer an identifier\n                }\n\n                pnode = templateNode;\n                if (pfCanAssign)\n                {\n                    *pfCanAssign = FALSE;\n                }\n                if (pfIsDotOrIndex)\n                {\n                    *pfIsDotOrIndex = false;\n                }\n                break;\n            }\n        default:\n            return pnode;\n        }\n    }\n}\n\n\/***************************************************************************\nLook for an existing label with the given name.\n***************************************************************************\/\nParseNodePtr Parser::PnodeLabel(IdentPtr pid, ParseNodePtr pnodeLabels)\n{\n    AssertMem(pid);\n    AssertNodeMemN(pnodeLabels);\n\n    StmtNest *pstmt;\n    ParseNodePtr pnodeT;\n\n    \/\/ Look in the statement stack.\n    for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)\n    {\n        AssertNodeMem(pstmt->pnodeStmt);\n        AssertNodeMemN(pstmt->pnodeLab);\n\n        for (pnodeT = pstmt->pnodeLab; nullptr != pnodeT;\n            pnodeT = pnodeT->sxLabel.pnodeNext)\n        {\n            Assert(knopLabel == pnodeT->nop);\n            if (pid == pnodeT->sxLabel.pid)\n                return pnodeT;\n        }\n    }\n\n    \/\/ Also look in the pnodeLabels list.\n    for (pnodeT = pnodeLabels; nullptr != pnodeT;\n        pnodeT = pnodeT->sxLabel.pnodeNext)\n    {\n        Assert(knopLabel == pnodeT->nop);\n        if (pid == pnodeT->sxLabel.pid)\n            return pnodeT;\n    }\n\n    return nullptr;\n}\n\n\/\/ Currently only ints and floats are treated as constants in function call\n\/\/ TODO: Check if we need for other constants as well\nBOOL Parser::IsConstantInFunctionCall(ParseNodePtr pnode)\n{\n    if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->sxInt.lw))\n    {\n        return TRUE;\n    }\n\n    if (pnode->nop == knopFlt)\n    {\n        return TRUE;\n    }\n\n    return FALSE;\n}\n\n\/***************************************************************************\nParse a list of arguments.\n***************************************************************************\/\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseArgList( bool *pCallOfConstants, uint16 *pSpreadArgCount, uint16 * pCount)\n{\n    ParseNodePtr pnodeArg;\n    ParseNodePtr pnodeList = nullptr;\n    ParseNodePtr *lastNodeRef = nullptr;\n\n    \/\/ Check for an empty list\n    Assert(m_token.tk == tkLParen);\n\n    if (m_pscan->Scan() == tkRParen)\n    {\n        return nullptr;\n    }\n\n    *pCallOfConstants = true;\n    *pSpreadArgCount = 0;\n\n    int count=0;\n    while (true)\n    {\n        \/\/ the count of arguments has to fit in an unsigned short\n        if (count > 0xffffU)\n            Error(ERRnoMemory);\n        \/\/ Allow spread in argument lists.\n        IdentToken token;\n        pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, \/* fAllowEllipsis *\/TRUE, NULL, nullptr, nullptr, &token);\n        ++count;\n        this->MarkEscapingRef(pnodeArg, &token);\n\n        if (buildAST)\n        {\n            this->CheckArguments(pnodeArg);\n\n            if (*pCallOfConstants && !IsConstantInFunctionCall(pnodeArg))\n            {\n                *pCallOfConstants = false;\n            }\n\n            if (pnodeArg->nop == knopEllipsis)\n            {\n                (*pSpreadArgCount)++;\n            }\n\n            AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);\n        }\n        if (m_token.tk != tkComma)\n        {\n            break;\n        }\n        m_pscan->Scan();\n\n        if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())\n        {\n            break;\n        }\n    }\n\n    if (pSpreadArgCount!=nullptr && (*pSpreadArgCount) > 0){\n        CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(SpreadFeatureCount, m_scriptContext);\n    }\n\n    *pCount = static_cast<uint16>(count);\n    if (buildAST)\n    {\n        AssertMem(lastNodeRef);\n        AssertNodeMem(*lastNodeRef);\n        pnodeList->ichLim = (*lastNodeRef)->ichLim;\n    }\n\n    return pnodeList;\n}\n\n\/\/ Currently only ints are treated as constants in ArrayLiterals\nBOOL Parser::IsConstantInArrayLiteral(ParseNodePtr pnode)\n{\n    if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->sxInt.lw))\n    {\n        return TRUE;\n    }\n    return FALSE;\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseArrayLiteral()\n{\n    ParseNodePtr pnode = nullptr;\n    bool arrayOfTaggedInts = false;\n    bool arrayOfInts = false;\n    bool arrayOfNumbers = false;\n    bool hasMissingValues = false;\n    uint count = 0;\n    uint spreadCount = 0;\n\n    ParseNodePtr pnode1 = ParseArrayList<buildAST>(&arrayOfTaggedInts, &arrayOfInts, &arrayOfNumbers, &hasMissingValues, &count, &spreadCount);\n\n    if (buildAST)\n    {\n        pnode = CreateNodeWithScanner<knopArray>();\n        pnode->sxArrLit.pnode1 = pnode1;\n        pnode->sxArrLit.arrayOfTaggedInts = arrayOfTaggedInts;\n        pnode->sxArrLit.arrayOfInts = arrayOfInts;\n        pnode->sxArrLit.arrayOfNumbers = arrayOfNumbers;\n        pnode->sxArrLit.hasMissingValues = hasMissingValues;\n        pnode->sxArrLit.count = count;\n        pnode->sxArrLit.spreadCount = spreadCount;\n\n        if (pnode->sxArrLit.pnode1)\n        {\n            this->CheckArguments(pnode->sxArrLit.pnode1);\n        }\n    }\n\n    return pnode;\n}\n\n\/***************************************************************************\nCreate an ArrayLiteral node\nParse a list of array elements. [ a, b, , c, ]\n***************************************************************************\/\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseArrayList(bool *pArrayOfTaggedInts, bool *pArrayOfInts, bool *pArrayOfNumbers, bool *pHasMissingValues, uint *count, uint *spreadCount)\n{\n    ParseNodePtr pnodeArg = nullptr;\n    ParseNodePtr pnodeList = nullptr;\n    ParseNodePtr *lastNodeRef = nullptr;\n\n    *count = 0;\n\n    \/\/ Check for an empty list\n    if (tkRBrack == m_token.tk)\n    {\n        return nullptr;\n    }\n\n    this->m_arrayDepth++;\n    bool arrayOfTaggedInts = buildAST;\n    bool arrayOfInts = buildAST;\n    bool arrayOfNumbers = buildAST;\n    bool arrayOfVarInts = false;\n    bool hasMissingValues = false;\n\n    for (;;)\n    {\n        (*count)++;\n        if (tkComma == m_token.tk || tkRBrack == m_token.tk)\n        {\n            hasMissingValues = true;\n            arrayOfTaggedInts = false;\n            arrayOfInts = false;\n            arrayOfNumbers = false;\n            if (buildAST)\n            {\n                pnodeArg = CreateNodeWithScanner<knopEmpty>();\n            }\n        }\n        else\n        {\n            \/\/ Allow Spread in array literals.\n            pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, \/* fAllowEllipsis *\/ TRUE);\n            if (buildAST)\n            {\n                if (pnodeArg->nop == knopEllipsis)\n                {\n                    (*spreadCount)++;\n                }\n                this->CheckArguments(pnodeArg);\n            }\n        }\n\n#if DEBUG\n        if(m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeArg))\n        {\n            Error(ERRsyntax);\n        }\n#endif\n\n        if (buildAST)\n        {\n            if (arrayOfNumbers)\n            {\n                if (pnodeArg->nop != knopInt)\n                {\n                    arrayOfTaggedInts = false;\n                    if (pnodeArg->nop != knopFlt)\n                    {\n                        \/\/ Not an array of constants.\n                        arrayOfInts = false;\n                        arrayOfNumbers = false;\n                    }\n                    else if (arrayOfInts && Js::JavascriptNumber::IsInt32OrUInt32(pnodeArg->sxFlt.dbl) && (!Js::JavascriptNumber::IsInt32(pnodeArg->sxFlt.dbl) || pnodeArg->sxFlt.dbl == -2147483648.0))\n                    {\n                        \/\/ We've seen nothing but ints, and this is a uint32 but not an int32.\n                        \/\/ Unless we see an actual float at some point, we want an array of vars\n                        \/\/ so we can work with tagged ints.\n                        arrayOfVarInts = true;\n                    }\n                    else\n                    {\n                        \/\/ Not an int array, but it may still be a float array.\n                        arrayOfInts = false;\n                    }\n                }\n                else\n                {\n                    if (Js::SparseArraySegment<int32>::IsMissingItem((int32*)&pnodeArg->sxInt.lw))\n                    {\n                        arrayOfInts = false;\n                    }\n                    if (Js::TaggedInt::IsOverflow(pnodeArg->sxInt.lw))\n                    {\n                        arrayOfTaggedInts = false;\n                    }\n                }\n            }\n            AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);\n        }\n\n        if (tkComma != m_token.tk)\n        {\n            break;\n        }\n        m_pscan->Scan();\n\n        if (tkRBrack == m_token.tk)\n        {\n            break;\n        }\n    }\n\n    if (spreadCount != nullptr && *spreadCount > 0){\n        CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(SpreadFeatureCount, m_scriptContext);\n    }\n\n    if (buildAST)\n    {\n        AssertMem(lastNodeRef);\n        AssertNodeMem(*lastNodeRef);\n        pnodeList->ichLim = (*lastNodeRef)->ichLim;\n\n        if (arrayOfVarInts && arrayOfInts)\n        {\n            arrayOfInts = false;\n            arrayOfNumbers = false;\n        }\n        *pArrayOfTaggedInts = arrayOfTaggedInts;\n        *pArrayOfInts = arrayOfInts;\n        *pArrayOfNumbers = arrayOfNumbers;\n        *pHasMissingValues = hasMissingValues;\n    }\n    this->m_arrayDepth--;\n    return pnodeList;\n}\n\nParser::MemberNameToTypeMap* Parser::CreateMemberNameMap(ArenaAllocator* pAllocator)\n{\n    Assert(pAllocator);\n    return Anew(pAllocator, MemberNameToTypeMap, pAllocator, 5);\n}\n\ntemplate<bool buildAST> void Parser::ParseComputedName(ParseNodePtr* ppnodeName, LPCOLESTR* ppNameHint, LPCOLESTR* ppFullNameHint, uint32 *pNameLength, uint32 *pShortNameOffset)\n{\n    m_pscan->Scan();\n    ParseNodePtr pnodeNameExpr = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, *ppNameHint, pNameLength, pShortNameOffset);\n    if (buildAST)\n    {\n        *ppnodeName = CreateNodeT<knopComputedName>(pnodeNameExpr->ichMin, pnodeNameExpr->ichLim);\n        (*ppnodeName)->sxUni.pnode1 = pnodeNameExpr;\n    }\n\n    if (ppFullNameHint && buildAST && CONFIG_FLAG(UseFullName))\n    {\n        *ppFullNameHint = FormatPropertyString(*ppNameHint, pnodeNameExpr, pNameLength, pShortNameOffset);\n    }\n\n    ChkCurTokNoScan(tkRBrack, ERRnoRbrack);\n}\n\n\/***************************************************************************\n    Parse a list of object set\/get members, e.g.:\n    { get foo(){ ... }, set bar(arg) { ... } }\n***************************************************************************\/\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseMemberGetSet(OpCode nop, LPCOLESTR* ppNameHint)\n{\n    ParseNodePtr pnodeName = nullptr;\n    Assert(nop == knopGetMember || nop == knopSetMember);\n    AssertMem(ppNameHint);\n    IdentPtr pid = nullptr;\n    bool isComputedName = false;\n\n    *ppNameHint=nullptr;\n\n    switch(m_token.tk)\n    {\n    default:\n        if (!m_token.IsReservedWord())\n        {\n            Error(ERRnoMemberIdent);\n        }\n        \/\/ fall through\n    case tkID:\n        pid = m_token.GetIdentifier(m_phtbl);\n        *ppNameHint = pid->Psz();\n        if (buildAST)\n        {\n            pnodeName = CreateStrNodeWithScanner(pid);\n        }\n        break;\n    case tkStrCon:\n        if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())\n        {\n            Error(ERRES5NoOctal);\n        }\n        pid = m_token.GetStr();\n        *ppNameHint = pid->Psz();\n        if (buildAST)\n        {\n            pnodeName = CreateStrNodeWithScanner(pid);\n        }\n        break;\n\n    case tkIntCon:\n        if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())\n        {\n            Error(ERRES5NoOctal);\n        }\n\n        pid = m_pscan->PidFromLong(m_token.GetLong());\n        if (buildAST)\n        {\n            pnodeName = CreateStrNodeWithScanner(pid);\n        }\n        break;\n\n    case tkFltCon:\n        if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())\n        {\n            Error(ERRES5NoOctal);\n        }\n\n        pid = m_pscan->PidFromDbl(m_token.GetDouble());\n        if (buildAST)\n        {\n            pnodeName = CreateStrNodeWithScanner(pid);\n        }\n        break;\n\n    case tkLBrack:\n        \/\/ Computed property name: get|set [expr] () {  }\n        if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())\n        {\n            Error(ERRnoMemberIdent);\n        }\n        LPCOLESTR emptyHint = nullptr;\n        uint32 offset = 0;\n        ParseComputedName<buildAST>(&pnodeName, &emptyHint, ppNameHint, &offset);\n\n        isComputedName = true;\n        break;\n    }\n\n    MemberType memberType;\n    ushort flags = fFncMethod | fFncNoName;\n    if (nop == knopGetMember)\n    {\n        memberType = MemberTypeGetter;\n        flags |= fFncNoArg;\n    }\n    else\n    {\n        Assert(nop == knopSetMember);\n        memberType = MemberTypeSetter;\n        flags |= fFncOneArg;\n    }\n\n    this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;\n    ParseNodePtr pnodeFnc = ParseFncDecl<buildAST>(flags, *ppNameHint,\n        \/*needsPIDOnRCurlyScan*\/ false, \/*resetParsingSuperRestrictionState*\/ false);\n\n    if (buildAST)\n    {\n        pnodeFnc->sxFnc.SetIsAccessor();\n        return CreateBinNode(nop, pnodeName, pnodeFnc);\n    }\n    else\n    {\n        return nullptr;\n    }\n}\n\n\/***************************************************************************\nParse a list of object members. e.g. { x:foo, 'y me':bar }\n***************************************************************************\/\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseMemberList(LPCOLESTR pNameHint, uint32* pNameHintLength, tokens declarationType)\n{\n    ParseNodePtr pnodeArg = nullptr;\n    ParseNodePtr pnodeName = nullptr;\n    ParseNodePtr pnodeList = nullptr;\n    ParseNodePtr *lastNodeRef = nullptr;\n    LPCOLESTR pFullNameHint = nullptr;       \/\/ A calculated full name\n    uint32 fullNameHintLength = pNameHintLength ? *pNameHintLength : 0;\n    uint32 shortNameOffset = 0;\n    bool isProtoDeclared = false;\n\n    \/\/ we get declaration tkLCurly - when the possible object pattern found under the expression.\n    bool isObjectPattern = (declarationType == tkVAR || declarationType == tkLET || declarationType == tkCONST || declarationType == tkLCurly) && IsES6DestructuringEnabled();\n\n    \/\/ Check for an empty list\n    if (tkRCurly == m_token.tk)\n    {\n        return nullptr;\n    }\n\n    ArenaAllocator tempAllocator(_u(\"MemberNames\"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);\n\n    bool hasDeferredInitError = false;\n\n    for (;;)\n    {\n        bool isComputedName = false;\n#if DEBUG\n        if((m_grfscr & fscrEnforceJSON) && (tkStrCon != m_token.tk || !(m_pscan->IsDoubleQuoteOnLastTkStrCon())))\n        {\n            Error(ERRsyntax);\n        }\n#endif\n        bool isAsyncMethod = false;\n        charcount_t ichMin = 0;\n        size_t iecpMin = 0;\n        if (m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())\n        {\n            RestorePoint parsedAsync;\n            m_pscan->Capture(&parsedAsync);\n            ichMin = m_pscan->IchMinTok();\n            iecpMin = m_pscan->IecpMinTok();\n\n            m_pscan->ScanForcingPid();\n            if (m_token.tk == tkLParen || m_token.tk == tkColon || m_token.tk == tkRCurly || m_pscan->FHadNewLine())\n            {\n                m_pscan->SeekTo(parsedAsync);\n            }\n            else\n            {\n                isAsyncMethod = true;\n            }\n        }\n\n        bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&\n                           m_token.tk == tkStar;\n        ushort fncDeclFlags = fFncNoName | fFncMethod;\n        if (isGenerator)\n        {\n            if (isAsyncMethod)\n            {\n                Error(ERRsyntax);\n            }\n            m_pscan->ScanForcingPid();\n            fncDeclFlags |= fFncGenerator;\n        }\n\n        IdentPtr pidHint = nullptr;              \/\/ A name scoped to current expression\n        Token tkHint = m_token;\n        charcount_t idHintIchMin = static_cast<charcount_t>(m_pscan->IecpMinTok());\n        charcount_t idHintIchLim = static_cast< charcount_t >(m_pscan->IecpLimTok());\n        bool wrapInBrackets = false;\n        switch (m_token.tk)\n        {\n        default:\n            if (!m_token.IsReservedWord())\n            {\n                Error(ERRnoMemberIdent);\n            }\n            \/\/ allow reserved words\n            wrapInBrackets = true;\n            \/\/ fall-through\n        case tkID:\n            pidHint = m_token.GetIdentifier(m_phtbl);\n            if (buildAST)\n            {\n                pnodeName = CreateStrNodeWithScanner(pidHint);\n            }\n            break;\n\n        case tkStrCon:\n            if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())\n            {\n                Error(ERRES5NoOctal);\n            }\n            wrapInBrackets = true;\n            pidHint = m_token.GetStr();\n            if (buildAST)\n            {\n                pnodeName = CreateStrNodeWithScanner(pidHint);\n            }\n            break;\n\n        case tkIntCon:\n            \/\/ Object initializers with numeric labels allowed in JS6\n            if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())\n            {\n                Error(ERRES5NoOctal);\n            }\n\n            pidHint = m_pscan->PidFromLong(m_token.GetLong());\n            if (buildAST)\n            {\n                pnodeName = CreateStrNodeWithScanner(pidHint);\n            }\n            break;\n\n        case tkFltCon:\n            if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())\n            {\n                Error(ERRES5NoOctal);\n            }\n\n            pidHint = m_pscan->PidFromDbl(m_token.GetDouble());\n            if (buildAST)\n            {\n                pnodeName = CreateStrNodeWithScanner(pidHint);\n            }\n            wrapInBrackets = true;\n            break;\n\n        case tkLBrack:\n            \/\/ Computed property name: [expr] : value\n            if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())\n            {\n                Error(ERRnoMemberIdent);\n            }\n\n            ParseComputedName<buildAST>(&pnodeName, &pNameHint, &pFullNameHint, &fullNameHintLength, &shortNameOffset);\n\n            isComputedName = true;\n            break;\n        }\n\n        if (pFullNameHint == nullptr)\n        {\n            if (CONFIG_FLAG(UseFullName))\n            {\n                pFullNameHint = AppendNameHints(pNameHint, pidHint, &fullNameHintLength, &shortNameOffset, false, wrapInBrackets);\n            }\n            else\n            {\n                pFullNameHint = pidHint? pidHint->Psz() : nullptr;\n                fullNameHintLength = pidHint ? pidHint->Cch() : 0;\n                shortNameOffset = 0;\n            }\n        }\n\n        RestorePoint atPid;\n        m_pscan->Capture(&atPid);\n\n        m_pscan->ScanForcingPid();\n\n        if (isGenerator && m_token.tk != tkLParen)\n        {\n            Error(ERRnoLparen);\n        }\n\n        if (tkColon == m_token.tk)\n        {\n            \/\/ It is a syntax error is the production of the form __proto__ : <> occurs more than once. From B.3.1 in spec.\n            \/\/ Note that previous scan is important because only after that we can determine we have a variable.\n            if (!isComputedName && pidHint == wellKnownPropertyPids.__proto__)\n            {\n                if (isProtoDeclared)\n                {\n                    Error(ERRsyntax);\n                }\n                else\n                {\n                    isProtoDeclared = true;\n                }\n            }\n\n            m_pscan->Scan();\n            ParseNodePtr pnodeExpr = nullptr;\n            if (isObjectPattern)\n            {\n                if (m_token.tk == tkEllipsis)\n                {\n                    Error(ERRUnexpectedEllipsis);\n                }\n                pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr\/* *hasSeenRest*\/, false \/*topLevel*\/, false \/*allowEmptyExpression*\/);\n\n                if (m_token.tk != tkComma && m_token.tk != tkRCurly)\n                {\n                    if (m_token.IsOperator())\n                    {\n                        Error(ERRDestructNoOper);\n                    }\n                    Error(ERRsyntax);\n                }\n            }\n            else\n            {\n                pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, pFullNameHint, &fullNameHintLength, &shortNameOffset);\n            }\n#if DEBUG\n            if((m_grfscr & fscrEnforceJSON) && !IsJSONValid(pnodeExpr))\n            {\n                Error(ERRsyntax);\n            }\n#endif\n            if (buildAST)\n            {\n                pnodeArg = CreateBinNode(isObjectPattern ? knopObjectPatternMember : knopMember, pnodeName, pnodeExpr);\n                if (pnodeArg->sxBin.pnode1->nop == knopStr)\n                {\n                    pnodeArg->sxBin.pnode1->sxPid.pid->PromoteAssignmentState();\n                }\n            }\n        }\n        else if (m_token.tk == tkLParen && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())\n        {\n            if (isObjectPattern)\n            {\n                Error(ERRInvalidAssignmentTarget);\n            }\n            \/\/ Shorthand syntax: foo() {} -> foo: function() {}\n\n            \/\/ Rewind to the PID and parse a function expression.\n            m_pscan->SeekTo(atPid);\n            this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;\n            ParseNodePtr pnodeFunc = ParseFncDecl<buildAST>(fncDeclFlags | (isAsyncMethod ? fFncAsync : fFncNoFlgs), pFullNameHint,\n                \/*needsPIDOnRCurlyScan*\/ false, \/*resetParsingSuperRestrictionState*\/ false);\n\n            if (isAsyncMethod)\n            {\n                pnodeFunc->sxFnc.cbMin = iecpMin;\n                pnodeFunc->ichMin = ichMin;\n            }\n            if (buildAST)\n            {\n                pnodeArg = CreateBinNode(knopMember, pnodeName, pnodeFunc);\n            }\n        }\n        else if (nullptr != pidHint) \/\/Its either tkID\/tkStrCon\/tkFloatCon\/tkIntCon\n        {\n            Assert(pidHint->Psz() != nullptr);\n\n            if ((pidHint == wellKnownPropertyPids.get || pidHint == wellKnownPropertyPids.set) &&\n                \/\/ get\/set are only pseudo keywords when they are identifiers (i.e. not strings)\n                tkHint.tk == tkID && NextTokenIsPropertyNameStart())\n            {\n                if (isObjectPattern)\n                {\n                    Error(ERRInvalidAssignmentTarget);\n                }\n\n                LPCOLESTR pNameGetOrSet = nullptr;\n                OpCode op = pidHint == wellKnownPropertyPids.get ? knopGetMember : knopSetMember;\n\n                pnodeArg = ParseMemberGetSet<buildAST>(op, &pNameGetOrSet);\n\n                if (CONFIG_FLAG(UseFullName) && buildAST && pnodeArg->sxBin.pnode2->nop == knopFncDecl)\n                {\n                    if (m_scriptContext->GetConfig()->IsES6FunctionNameEnabled())\n                    {\n                        \/\/ displays as \"get object.funcname\" or \"set object.funcname\"\n                        uint32 getOrSetOffset = 0;\n                        LPCOLESTR intermediateHint = AppendNameHints(pNameHint, pNameGetOrSet, &fullNameHintLength, &shortNameOffset);\n                        pFullNameHint = AppendNameHints(pidHint, intermediateHint, &fullNameHintLength, &getOrSetOffset, true);\n                        shortNameOffset += getOrSetOffset;\n                    }\n                    else\n                    {\n                        \/\/ displays as \"object.funcname.get\" or \"object.funcname.set\"\n                        LPCOLESTR intermediateHint = AppendNameHints(pNameGetOrSet, pidHint, &fullNameHintLength, &shortNameOffset);\n                        pFullNameHint = AppendNameHints(pNameHint, intermediateHint, &fullNameHintLength, &shortNameOffset);\n                    }\n                }\n            }\n            else if ((m_token.tk == tkRCurly || m_token.tk == tkComma || m_token.tk == tkAsg) && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())\n            {\n                \/\/ Shorthand {foo} -> {foo:foo} syntax.\n                \/\/ {foo = <initializer>} supported only when on object pattern rules are being applied\n                if (tkHint.tk != tkID)\n                {\n                    Assert(tkHint.IsReservedWord()\n                        || tkHint.tk == tkIntCon || tkHint.tk == tkFltCon || tkHint.tk == tkStrCon);\n                    \/\/ All keywords are banned in non-strict mode.\n                    \/\/ Future reserved words are banned in strict mode.\n                    if (IsStrictMode() || !tkHint.IsFutureReservedWord(true))\n                    {\n                        IdentifierExpectedError(tkHint);\n                    }\n                }\n\n                if (buildAST)\n                {\n                    CheckArgumentsUse(pidHint, GetCurrentFunctionNode());\n                }\n\n                bool couldBeObjectPattern = !isObjectPattern && m_token.tk == tkAsg;\n\n                if (couldBeObjectPattern)\n                {\n                    declarationType = tkLCurly;\n                    isObjectPattern = true;\n\n                    \/\/ This may be an error but we are deferring for favouring destructuring.\n                    hasDeferredInitError = true;\n                }\n\n                ParseNodePtr pnodeIdent = nullptr;\n                if (isObjectPattern)\n                {\n                    m_pscan->SeekTo(atPid);\n                    pnodeIdent = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr\/* *hasSeenRest*\/, false \/*topLevel*\/, false \/*allowEmptyExpression*\/);\n\n                    if (m_token.tk != tkComma && m_token.tk != tkRCurly)\n                    {\n                        if (m_token.IsOperator())\n                        {\n                            Error(ERRDestructNoOper);\n                        }\n                        Error(ERRsyntax);\n                    }\n                }\n                else\n                {\n                    \/\/ Add a reference to the hinted name so we can bind it properly.\n                    PidRefStack *ref = PushPidRef(pidHint);\n\n                    if (buildAST)\n                    {\n                        pnodeIdent = CreateNameNode(pidHint, idHintIchMin, idHintIchLim);\n                        pnodeIdent->sxPid.SetSymRef(ref);\n                    }\n                }\n\n                if (buildAST)\n                {\n                    pnodeArg = CreateBinNode(isObjectPattern && !couldBeObjectPattern ? knopObjectPatternMember : knopMemberShort, pnodeName, pnodeIdent);\n                }\n            }\n            else\n            {\n                Error(ERRnoColon);\n            }\n        }\n        else\n        {\n            Error(ERRnoColon);\n        }\n\n        if (buildAST)\n        {\n            Assert(pnodeArg->sxBin.pnode2 != nullptr);\n            if (pnodeArg->sxBin.pnode2->nop == knopFncDecl)\n            {\n                Assert(fullNameHintLength >= shortNameOffset);\n                pnodeArg->sxBin.pnode2->sxFnc.hint = pFullNameHint;\n                pnodeArg->sxBin.pnode2->sxFnc.hintLength =  fullNameHintLength;\n                pnodeArg->sxBin.pnode2->sxFnc.hintOffset  = shortNameOffset;\n            }\n            AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);\n        }\n        pidHint = nullptr;\n        pFullNameHint = nullptr;\n        if (tkComma != m_token.tk)\n        {\n            break;\n        }\n        m_pscan->ScanForcingPid();\n        if (tkRCurly == m_token.tk)\n        {\n            break;\n        }\n    }\n\n    m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || hasDeferredInitError;\n\n    if (buildAST)\n    {\n        AssertMem(lastNodeRef);\n        AssertNodeMem(*lastNodeRef);\n        pnodeList->ichLim = (*lastNodeRef)->ichLim;\n    }\n\n    return pnodeList;\n}\n\nBOOL Parser::DeferredParse(Js::LocalFunctionId functionId)\n{\n    if ((m_grfscr & fscrDeferFncParse) != 0)\n    {\n        if (m_stoppedDeferredParse)\n        {\n            return false;\n        }\n        if (PHASE_OFF_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId))\n        {\n            return false;\n        }\n        if (PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId))\n        {\n            return true;\n        }\n#if ENABLE_PROFILE_INFO\n#ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE\n        if (m_sourceContextInfo->sourceDynamicProfileManager != nullptr)\n        {\n            Js::ExecutionFlags flags = m_sourceContextInfo->sourceDynamicProfileManager->IsFunctionExecuted(functionId);\n            return flags != Js::ExecutionFlags_Executed;\n        }\n#endif\n#endif\n        return true;\n    }\n\n    return false;\n}\n\n\/\/\n\/\/ Call this in ParseFncDecl only to check (and reset) if ParseFncDecl is re-parsing a deferred\n\/\/ function body. If a deferred function is called and being re-parsed, it shouldn't be deferred again.\n\/\/\nBOOL Parser::IsDeferredFnc()\n{\n    if (m_grfscr & fscrDeferredFnc)\n    {\n        m_grfscr &= ~fscrDeferredFnc;\n        return true;\n    }\n\n    return false;\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseFncDecl(ushort flags, LPCOLESTR pNameHint, const bool needsPIDOnRCurlyScan, bool resetParsingSuperRestrictionState, bool fUnaryOrParen)\n{\n    AutoParsingSuperRestrictionStateRestorer restorer(this);\n    if (resetParsingSuperRestrictionState)\n    {\n        \/\/  ParseFncDecl will always reset m_parsingSuperRestrictionState to super disallowed unless explicitly disabled\n        this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperDisallowed;\n    }\n\n    ParseNodePtr pnodeFnc = nullptr;\n    ParseNodePtr *ppnodeVarSave = nullptr;\n    ParseNodePtr pnodeFncBlockScope = nullptr;\n    ParseNodePtr *ppnodeScopeSave = nullptr;\n    ParseNodePtr *ppnodeExprScopeSave = nullptr;\n    bool funcHasName = false;\n    bool fDeclaration = flags & fFncDeclaration;\n    bool fModule = (flags & fFncModule) != 0;\n    bool fLambda = (flags & fFncLambda) != 0;\n    charcount_t ichMin = this->m_pscan->IchMinTok();\n    bool wasInDeferredNestedFunc = false;\n\n    uint tryCatchOrFinallyDepthSave = this->m_tryCatchOrFinallyDepth;\n    this->m_tryCatchOrFinallyDepth = 0;\n\n    if (this->m_arrayDepth)\n    {\n        this->m_funcInArrayDepth++; \/\/ Count function depth within array literal\n    }\n\n    \/\/ Update the count of functions nested in the current parent.\n    Assert(m_pnestedCount || !buildAST);\n    uint *pnestedCountSave = m_pnestedCount;\n    if (buildAST || m_pnestedCount)\n    {\n        (*m_pnestedCount)++;\n    }\n\n    uint scopeCountNoAstSave = m_scopeCountNoAst;\n    m_scopeCountNoAst = 0;\n\n    bool noStmtContext = false;\n\n    if (fDeclaration)\n    {\n        AnalysisAssert(m_pstmtCur->isDeferred || m_pstmtCur->pnodeStmt != nullptr);\n        noStmtContext =\n            (m_pstmtCur->isDeferred && m_pstmtCur->op != knopBlock) ||\n            (!m_pstmtCur->isDeferred && m_pstmtCur->pnodeStmt->nop != knopBlock);\n\n        if (noStmtContext)\n        {\n            \/\/ We have a function declaration like \"if (a) function f() {}\". We didn't see\n            \/\/ a block scope on the way in, so we need to pretend we did. Note that this is a syntax error\n            \/\/ in strict mode.\n            if (!this->FncDeclAllowedWithoutContext(flags))\n            {\n                Error(ERRsyntax);\n            }\n            pnodeFncBlockScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);\n            if (buildAST)\n            {\n                PushFuncBlockScope(pnodeFncBlockScope, &ppnodeScopeSave, &ppnodeExprScopeSave);\n            }\n        }\n    }\n\n    \/\/ Create the node.\n    pnodeFnc = CreateNode(knopFncDecl);\n    pnodeFnc->sxFnc.ClearFlags();\n    pnodeFnc->sxFnc.SetDeclaration(fDeclaration);\n    pnodeFnc->sxFnc.astSize             = 0;\n    pnodeFnc->sxFnc.pnodeName           = nullptr;\n    pnodeFnc->sxFnc.pnodeScopes         = nullptr;\n    pnodeFnc->sxFnc.pnodeRest           = nullptr;\n    pnodeFnc->sxFnc.pid                 = nullptr;\n    pnodeFnc->sxFnc.hint                = nullptr;\n    pnodeFnc->sxFnc.hintOffset          = 0;\n    pnodeFnc->sxFnc.hintLength          = 0;\n    pnodeFnc->sxFnc.isNameIdentifierRef = true;\n    pnodeFnc->sxFnc.nestedFuncEscapes   = false;\n    pnodeFnc->sxFnc.pnodeNext           = nullptr;\n    pnodeFnc->sxFnc.pnodeParams         = nullptr;\n    pnodeFnc->sxFnc.pnodeVars           = nullptr;\n    pnodeFnc->sxFnc.funcInfo            = nullptr;\n    pnodeFnc->sxFnc.deferredStub        = nullptr;\n    pnodeFnc->sxFnc.nestedCount         = 0;\n    pnodeFnc->sxFnc.cbMin = m_pscan->IecpMinTok();\n    pnodeFnc->sxFnc.functionId = (*m_nextFunctionId)++;\n\n    \/\/ Push new parser state with this new function node\n\n    AppendFunctionToScopeList(fDeclaration, pnodeFnc);\n\n    \/\/ Start the argument list.\n    ppnodeVarSave = m_ppnodeVar;\n\n    if (buildAST)\n    {\n        pnodeFnc->sxFnc.lineNumber = m_pscan->LineCur();\n        pnodeFnc->sxFnc.columnNumber = CalculateFunctionColumnNumber();\n        pnodeFnc->sxFnc.SetNested(m_currentNodeFunc != nullptr); \/\/ If there is a current function, then we're a nested function.\n        pnodeFnc->sxFnc.SetStrictMode(IsStrictMode()); \/\/ Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.\n        pnodeFnc->sxFnc.firstDefaultArg = 0;\n\n        m_pCurrentAstSize = &pnodeFnc->sxFnc.astSize;\n    }\n    else \/\/ if !buildAST\n    {\n        wasInDeferredNestedFunc = m_inDeferredNestedFunc;\n        m_inDeferredNestedFunc = true;\n    }\n\n    m_pnestedCount = &pnodeFnc->sxFnc.nestedCount;\n\n    AnalysisAssert(pnodeFnc);\n    pnodeFnc->sxFnc.SetIsAsync((flags & fFncAsync) != 0);\n    pnodeFnc->sxFnc.SetIsLambda(fLambda);\n    pnodeFnc->sxFnc.SetIsMethod((flags & fFncMethod) != 0);\n    pnodeFnc->sxFnc.SetIsClassMember((flags & fFncClassMember) != 0);\n    pnodeFnc->sxFnc.SetIsModule(fModule);\n\n    bool needScanRCurly = true;\n    bool result = ParseFncDeclHelper<buildAST>(pnodeFnc, pNameHint, flags, &funcHasName, fUnaryOrParen, noStmtContext, &needScanRCurly, fModule);\n    if (!result)\n    {\n        Assert(!pnodeFncBlockScope);\n\n        return pnodeFnc;\n    }\n\n    AnalysisAssert(pnodeFnc);\n\n    *m_ppnodeVar = nullptr;\n    m_ppnodeVar = ppnodeVarSave;\n\n    if (m_currentNodeFunc && (pnodeFnc->sxFnc.CallsEval() || pnodeFnc->sxFnc.ChildCallsEval()))\n    {\n        GetCurrentFunctionNode()->sxFnc.SetChildCallsEval(true);\n    }\n\n    ParseNodePtr pnodeFncParent = buildAST ? m_currentNodeFunc : m_currentNodeDeferredFunc;\n\n    \/\/ Lambdas do not have \"arguments\" and instead capture their parent's\n    \/\/ binding of \"arguments.  To ensure the arguments object of the enclosing\n    \/\/ non-lambda function is loaded propagate the UsesArguments flag up to\n    \/\/ the parent function\n    if ((flags & fFncLambda) != 0 && pnodeFnc->sxFnc.UsesArguments())\n    {\n        if (pnodeFncParent != nullptr)\n        {\n            pnodeFncParent->sxFnc.SetUsesArguments();\n        }\n        else\n        {\n            m_UsesArgumentsAtGlobal = true;\n        }\n    }\n\n    if (needScanRCurly && !fModule)\n    {\n        \/\/ Consume the next token now that we're back in the enclosing function (whose strictness may be\n        \/\/ different from the function we just finished).\n#if DBG\n        bool expectedTokenValid = m_token.tk == tkRCurly;\n        AssertMsg(expectedTokenValid, \"Invalid token expected for RCurly match\");\n#endif\n        \/\/ The next token may need to have a PID created in !buildAST mode, as we may be parsing a method with a string name.\n        if (needsPIDOnRCurlyScan)\n        {\n            m_pscan->ScanForcingPid();\n        }\n        else\n        {\n            m_pscan->Scan();\n        }\n    }\n\n    m_pnestedCount = pnestedCountSave;\n    Assert(!buildAST || !wasInDeferredNestedFunc);\n    m_inDeferredNestedFunc = wasInDeferredNestedFunc;\n\n    if (this->m_arrayDepth)\n    {\n        this->m_funcInArrayDepth--;\n        if (this->m_funcInArrayDepth == 0)\n        {\n            \/\/ We disable deferred parsing if array literals dominate.\n            \/\/ But don't do this if the array literal is dominated by function bodies.\n            if (flags & (fFncMethod | fFncClassMember) && m_token.tk != tkSColon)\n            {\n                \/\/ Class member methods have optional separators. We need to check whether we are\n                \/\/ getting the IchLim of the correct token.\n                Assert(m_pscan->m_tkPrevious == tkRCurly && needScanRCurly);\n\n                this->m_funcInArray += m_pscan->IchMinTok() - \/*tkRCurly*\/ 1 - ichMin;\n            }\n            else\n            {\n                this->m_funcInArray += m_pscan->IchLimTok() - ichMin;\n            }\n        }\n    }\n\n    m_scopeCountNoAst = scopeCountNoAstSave;\n\n    if (buildAST && fDeclaration && !IsStrictMode())\n    {\n        if (pnodeFnc->sxFnc.pnodeName != nullptr && pnodeFnc->sxFnc.pnodeName->nop == knopVarDecl &&\n            GetCurrentBlock()->sxBlock.blockType == PnodeBlockType::Regular)\n        {\n            \/\/ Add a function-scoped VarDecl with the same name as the function for\n            \/\/ back compat with pre-ES6 code that declares functions in blocks. The\n            \/\/ idea is that the last executed declaration wins at the function scope\n            \/\/ level and we accomplish this by having each block scoped function\n            \/\/ declaration assign to both the block scoped \"let\" binding, as well\n            \/\/ as the function scoped \"var\" binding.\n            ParseNodePtr vardecl = CreateVarDeclNode(pnodeFnc->sxFnc.pnodeName->sxVar.pid, STVariable, false, nullptr, false);\n            vardecl->sxVar.isBlockScopeFncDeclVar = true;\n        }\n    }\n\n    if (pnodeFncBlockScope)\n    {\n        Assert(pnodeFncBlockScope->sxBlock.pnodeStmt == nullptr);\n        pnodeFncBlockScope->sxBlock.pnodeStmt = pnodeFnc;\n        if (buildAST)\n        {\n            PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);\n        }\n        FinishParseBlock(pnodeFncBlockScope);\n        return pnodeFncBlockScope;\n    }\n\n    this->m_tryCatchOrFinallyDepth = tryCatchOrFinallyDepthSave;\n\n    return pnodeFnc;\n}\n\nbool Parser::FncDeclAllowedWithoutContext(ushort flags)\n{\n    \/\/ Statement context required for strict mode, async functions, and generators.\n    \/\/ Note that generators aren't detected yet when this method is called; they're checked elsewhere.\n    return !IsStrictMode() && !(flags & fFncAsync);\n}\n\nuint Parser::CalculateFunctionColumnNumber()\n{\n    uint columnNumber;\n\n    if (m_pscan->IchMinTok() >= m_pscan->IchMinLine())\n    {\n        \/\/ In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse\n        columnNumber = m_pscan->IchMinTok() - m_pscan->IchMinLine();\n        if (m_functionBody != nullptr && m_functionBody->GetRelativeLineNumber() == m_pscan->LineCur())\n        {\n            \/\/ Adjust the column if it falls on the first line, where the re-parse is happening.\n            columnNumber += m_functionBody->GetRelativeColumnNumber();\n        }\n    }\n    else if (m_currentNodeFunc)\n    {\n        \/\/ For the first line after defer parse, compute the column relative to the column number\n        \/\/ of the lexically parent function.\n        ULONG offsetFromCurrentFunction = m_pscan->IchMinTok() - m_currentNodeFunc->ichMin;\n        columnNumber = m_currentNodeFunc->sxFnc.columnNumber + offsetFromCurrentFunction ;\n    }\n    else\n    {\n        \/\/ if there is no current function, lets give a default of 0.\n        columnNumber = 0;\n    }\n\n    return columnNumber;\n}\n\nvoid Parser::AppendFunctionToScopeList(bool fDeclaration, ParseNodePtr pnodeFnc)\n{\n    if (!fDeclaration && m_ppnodeExprScope)\n    {\n        \/\/ We're tracking function expressions separately from declarations in this scope\n        \/\/ (e.g., inside a catch scope in standards mode).\n        Assert(*m_ppnodeExprScope == nullptr);\n        *m_ppnodeExprScope = pnodeFnc;\n        m_ppnodeExprScope = &pnodeFnc->sxFnc.pnodeNext;\n    }\n    else\n    {\n        Assert(*m_ppnodeScope == nullptr);\n        *m_ppnodeScope = pnodeFnc;\n        m_ppnodeScope = &pnodeFnc->sxFnc.pnodeNext;\n    }\n}\n\n\/***************************************************************************\nParse a function definition.\n***************************************************************************\/\ntemplate<bool buildAST>\nbool Parser::ParseFncDeclHelper(ParseNodePtr pnodeFnc, LPCOLESTR pNameHint, ushort flags, bool *pHasName, bool fUnaryOrParen, bool noStmtContext, bool *pNeedScanRCurly, bool skipFormals)\n{\n    ParseNodePtr pnodeFncParent = GetCurrentFunctionNode();\n    \/\/ is the following correct? When buildAST is false, m_currentNodeDeferredFunc can be nullptr on transition to deferred parse from non-deferred\n    ParseNodePtr pnodeFncSave = buildAST ? m_currentNodeFunc : m_currentNodeDeferredFunc;\n    ParseNodePtr pnodeFncSaveNonLambda = buildAST ? m_currentNodeNonLambdaFunc : m_currentNodeNonLambdaDeferredFunc;\n    int32* pAstSizeSave = m_pCurrentAstSize;\n\n    bool fDeclaration = (flags & fFncDeclaration) != 0;\n    bool fLambda = (flags & fFncLambda) != 0;\n    bool fAsync = (flags & fFncAsync) != 0;\n    bool fModule = (flags & fFncModule) != 0;\n    bool fDeferred = false;\n    StmtNest *pstmtSave;\n    ParseNodePtr *lastNodeRef = nullptr;\n    bool fFunctionInBlock = false;\n    if (buildAST)\n    {\n        fFunctionInBlock = GetCurrentBlockInfo() != GetCurrentFunctionBlockInfo() &&\n            (GetCurrentBlockInfo()->pnodeBlock->sxBlock.scope == nullptr ||\n             GetCurrentBlockInfo()->pnodeBlock->sxBlock.scope->GetScopeType() != ScopeType_GlobalEvalBlock);\n    }\n\n    \/\/ Save the position of the scanner in case we need to inspect the name hint later\n    RestorePoint beginNameHint;\n    m_pscan->Capture(&beginNameHint);\n\n    ParseNodePtr pnodeFncExprScope = nullptr;    \n    Scope *fncExprScope = nullptr;\n    if (!fDeclaration)\n    {\n        pnodeFncExprScope = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FuncExpr);\n        fncExprScope = pnodeFncExprScope->sxBlock.scope;\n\n        \/\/ Function expression: push the new function onto the stack now so that the name (if any) will be\n        \/\/ local to the new function.\n\n        this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);\n    }\n\n    *pHasName = !fLambda && !fModule && this->ParseFncNames<buildAST>(pnodeFnc, pnodeFncSave, flags, &lastNodeRef);\n\n    if (fDeclaration)\n    {\n        \/\/ Declaration statement: push the new function now, after parsing the name, so the name is local to the\n        \/\/ enclosing function.\n\n        this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);\n    }\n\n    if (noStmtContext && pnodeFnc->sxFnc.IsGenerator())\n    {\n        \/\/ Generator decl not allowed outside stmt context. (We have to wait until we've parsed the '*' to\n        \/\/ detect generator.)\n        Error(ERRsyntax, pnodeFnc);\n    }\n\n    \/\/ switch scanner to treat 'yield' as keyword in generator functions\n    \/\/ or as an identifier in non-generator functions\n    bool fPreviousYieldIsKeyword = m_pscan->SetYieldIsKeyword(pnodeFnc && pnodeFnc->sxFnc.IsGenerator());\n\n    bool fPreviousAwaitIsKeyword = m_pscan->SetAwaitIsKeyword(fAsync);\n\n    if (pnodeFnc && pnodeFnc->sxFnc.IsGenerator())\n    {\n        CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(GeneratorCount, m_scriptContext);\n    }\n\n    if (fncExprScope && !*pHasName)\n    {\n        FinishParseBlock(pnodeFncExprScope);\n        m_nextBlockId--;\n        Adelete(&m_nodeAllocator, fncExprScope);\n        fncExprScope = nullptr;\n        pnodeFncExprScope = nullptr;\n    }\n    if (pnodeFnc)\n    {\n        pnodeFnc->sxFnc.scope = fncExprScope;\n    }\n\n    \/\/ Start a new statement stack.\n    bool topLevelStmt =\n        buildAST &&\n        !fFunctionInBlock &&\n        (this->m_pstmtCur == nullptr || this->m_pstmtCur->pnodeStmt->nop == knopBlock);\n\n    pstmtSave = m_pstmtCur;\n    SetCurrentStatement(nullptr);\n\n    \/\/ Function definition is inside the parent function's parameter scope\n    bool isEnclosedInParamScope = this->m_currentScope->GetScopeType() == ScopeType_Parameter;\n\n    if (this->m_currentScope->GetScopeType() == ScopeType_FuncExpr || this->m_currentScope->GetScopeType() == ScopeType_Block)\n    {\n        \/\/ Or this is a function expression or class enclosed in a parameter scope\n        isEnclosedInParamScope = this->m_currentScope->GetEnclosingScope() && this->m_currentScope->GetEnclosingScope()->GetScopeType() == ScopeType_Parameter;\n    }\n\n    Assert(!isEnclosedInParamScope || pnodeFncSave->sxFnc.HasNonSimpleParameterList());\n\n    RestorePoint beginFormals;\n    m_pscan->Capture(&beginFormals);\n    BOOL fWasAlreadyStrictMode = IsStrictMode();\n    BOOL oldStrictMode = this->m_fUseStrictMode;\n\n    if (fLambda)\n    {\n        CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(LambdaCount, m_scriptContext);\n    }\n\n    uint uDeferSave = m_grfscr & fscrDeferFncParse;\n    if ((!fDeclaration && m_ppnodeExprScope) ||\n        fFunctionInBlock ||\n        isEnclosedInParamScope ||\n        (flags & (fFncNoName | fFncLambda)))\n    {\n        \/\/ NOTE: Don't defer if this is a function expression inside a construct that induces\n        \/\/ a scope nested within the current function (like a with, or a catch in ES5 mode, or\n        \/\/ any function declared inside a nested lexical block or param scope in ES6 mode).\n        \/\/ We won't be able to reconstruct the scope chain properly when we come back and\n        \/\/ try to compile just the function expression.\n        \/\/ Also shut off deferring on getter\/setter or other construct with unusual text bounds\n        \/\/ (fFncNoName|fFncLambda) as these are usually trivial, and re-parsing is problematic.\n        m_grfscr &= ~fscrDeferFncParse;\n    }\n\n\n    bool isTopLevelDeferredFunc = false;\n\n    struct AutoFastScanFlag {\n        bool savedDoingFastScan;\n        AutoFastScanFlag(Parser *parser) : m_parser(parser) { savedDoingFastScan = m_parser->m_doingFastScan; }\n        ~AutoFastScanFlag() { m_parser->m_doingFastScan = savedDoingFastScan; }\n        Parser *m_parser;\n    } flag(this);\n\n    bool doParallel = false;\n    bool parallelJobStarted = false;\n    if (buildAST)\n    {\n        bool isLikelyIIFE = !fDeclaration && pnodeFnc && fUnaryOrParen;\n\n        BOOL isDeferredFnc = IsDeferredFnc();\n        AnalysisAssert(isDeferredFnc || pnodeFnc);\n        isTopLevelDeferredFunc =\n            (!isDeferredFnc\n             && DeferredParse(pnodeFnc->sxFnc.functionId)\n             && (!pnodeFnc->sxFnc.IsNested() || CONFIG_FLAG(DeferNested))\n            \/\/ Don't defer if this is a function expression not contained in a statement or other expression.\n            \/\/ Assume it will be called as part of this expression.\n             && (!isLikelyIIFE || !topLevelStmt || PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->sxFnc.functionId))\n             && !m_InAsmMode\n            \/\/ Don't defer a module function wrapper because we need to do export resolution at parse time\n             && !fModule\n            );\n\n        if (!fLambda &&\n            !isDeferredFnc &&\n            !isLikelyIIFE &&\n            !this->IsBackgroundParser() &&\n            !this->m_doingFastScan &&\n            !(pnodeFncSave && m_currDeferredStub) &&\n            !(this->m_parseType == ParseType_Deferred && this->m_functionBody && this->m_functionBody->GetScopeInfo() && !isTopLevelDeferredFunc))\n        {\n            doParallel = DoParallelParse(pnodeFnc);\n#if ENABLE_BACKGROUND_PARSING\n            if (doParallel)\n            {\n                BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();\n                Assert(bgp);\n                if (bgp->HasFailedBackgroundParseItem())\n                {\n                    Error(ERRsyntax);\n                }\n                doParallel = bgp->ParseBackgroundItem(this, pnodeFnc, isTopLevelDeferredFunc);\n                if (doParallel)\n                {\n                    parallelJobStarted = true;\n                    this->m_hasParallelJob = true;\n                    this->m_doingFastScan = true;\n                    doParallel = FastScanFormalsAndBody();\n                    if (doParallel)\n                    {\n                        \/\/ Let the foreground thread take care of marking the limit on the function node,\n                        \/\/ because in some cases this function's caller will want to change that limit,\n                        \/\/ so we don't want the background thread to try and touch it.\n                        pnodeFnc->ichLim = m_pscan->IchLimTok();\n                        pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();\n                    }\n                }\n            }\n#endif\n        }\n    }\n\n    if (!doParallel)\n    {\n        \/\/ We don't want to, or couldn't, let the main thread scan past this function body, so parse\n        \/\/ it for real.\n        ParseNodePtr pnodeRealFnc = pnodeFnc;\n        if (parallelJobStarted)\n        {\n            \/\/ We have to deal with a failure to fast-scan the function (due to syntax error? \"\/\"?) when\n            \/\/ a background thread may already have begun to work on the job. Both threads can't be allowed to\n            \/\/ operate on the same node.\n            pnodeFnc = CreateDummyFuncNode(fDeclaration);\n        }\n\n        AnalysisAssert(pnodeFnc);\n        ParseNodePtr pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);\n        AnalysisAssert(pnodeBlock != nullptr);\n        pnodeFnc->sxFnc.pnodeScopes = pnodeBlock;\n        m_ppnodeVar = &pnodeFnc->sxFnc.pnodeParams;\n\n        ParseNodePtr *ppnodeScopeSave = nullptr;\n        ParseNodePtr *ppnodeExprScopeSave = nullptr;\n\n        ppnodeScopeSave = m_ppnodeScope;\n        if (pnodeBlock)\n        {\n            \/\/ This synthetic block scope will contain all the nested scopes.\n            m_ppnodeScope = &pnodeBlock->sxBlock.pnodeScopes;\n            pnodeBlock->sxBlock.pnodeStmt = pnodeFnc;\n        }\n\n        \/\/ Keep nested function declarations and expressions in the same list at function scope.\n        \/\/ (Indicate this by nulling out the current function expressions list.)\n        ppnodeExprScopeSave = m_ppnodeExprScope;\n        m_ppnodeExprScope = nullptr;\n\n        if (!skipFormals)\n        {\n            this->ParseFncFormals<buildAST>(pnodeFnc, pnodeFncParent, flags);\n        }\n\n        \/\/ Create function body scope\n        ParseNodePtr pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);\n        \/\/ Set the parameter block's child to the function body block.\n        \/\/ The pnodeFnc->sxFnc.pnodeScopes list is constructed in such a way that it includes all the scopes in this list.\n        \/\/ For example if the param scope has one function and body scope has one function then the list will look like below,\n        \/\/ param scope block -> function decl from param scope -> body socpe block -> function decl from body scope.\n        *m_ppnodeScope = pnodeInnerBlock;\n        pnodeFnc->sxFnc.pnodeBodyScope = pnodeInnerBlock;\n\n        \/\/ This synthetic block scope will contain all the nested scopes.\n        m_ppnodeScope = &pnodeInnerBlock->sxBlock.pnodeScopes;\n        pnodeInnerBlock->sxBlock.pnodeStmt = pnodeFnc;\n\n        \/\/ DEFER: Begin deferral here (after names are parsed and name nodes created).\n        \/\/ Create no more AST nodes until we're done.\n\n        \/\/ Try to defer this func if all these are true:\n        \/\/  0. We are not already in deferred parsing (i.e. buildAST is true)\n        \/\/  1. We are not re-parsing a deferred func which is being invoked.\n        \/\/  2. Dynamic profile suggests this func can be deferred (and deferred parse is on).\n        \/\/  3. This func is top level or defer nested func is on.\n        \/\/  4. Optionally, the function is non-nested and not in eval, or the deferral decision was based on cached profile info,\n        \/\/     or the function is sufficiently long. (I.e., don't defer little nested functions unless we're\n        \/\/     confident they'll never be executed, because un-deferring nested functions is more expensive.)\n        \/\/     NOTE: I'm disabling #4 by default, because we've found other ways to reduce the cost of un-deferral,\n        \/\/           and we don't want to create function bodies aggressively for little functions.\n\n        \/\/ We will also temporarily defer all asm.js functions, except for the asm.js\n        \/\/ module itself, which we will never defer\n        bool strictModeTurnedOn = false;\n\n        if (isTopLevelDeferredFunc &&\n            !(this->m_grfscr & fscrEvalCode) &&\n            pnodeFnc->sxFnc.IsNested() &&\n#ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE\n            m_sourceContextInfo->sourceDynamicProfileManager == nullptr &&\n#endif\n            PHASE_ON_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->sxFnc.functionId) &&\n            (\n                !PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->sxFnc.functionId) ||\n                PHASE_FORCE_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->sxFnc.functionId)\n            ))\n        {\n            \/\/ Try to scan ahead to the end of the function. If we get there before we've scanned a minimum\n            \/\/ number of tokens, don't bother deferring, because it's too small.\n            if (this->ScanAheadToFunctionEnd(CONFIG_FLAG(MinDeferredFuncTokenCount)))\n            {\n                isTopLevelDeferredFunc = false;\n            }\n        }\n\n        Scope* paramScope = pnodeFnc->sxFnc.pnodeScopes ? pnodeFnc->sxFnc.pnodeScopes->sxBlock.scope : nullptr;\n        if (paramScope != nullptr)\n        {\n            if (CONFIG_FLAG(ForceSplitScope))\n            {\n                paramScope->SetCannotMergeWithBodyScope();\n            }\n            else if (pnodeFnc->sxFnc.HasNonSimpleParameterList())\n            {\n                if (paramScope->GetCanMergeWithBodyScope())\n                {\n                    paramScope->ForEachSymbolUntil([this, paramScope](Symbol* sym) {\n                        if (sym->GetPid()->GetTopRef()->sym == nullptr)\n                        {\n                            \/\/ One of the symbol has non local reference. Mark the param scope as we can't merge it with body scope.\n                            paramScope->SetCannotMergeWithBodyScope();\n                            return true;\n                        }\n                        else\n                        {\n                            \/\/ If no non-local references are there then the top of the ref stack should point to the same symbol.\n                            Assert(sym->GetPid()->GetTopRef()->sym == sym);\n                        }\n                        return false;\n                    });\n\n                    if (wellKnownPropertyPids.arguments->GetTopRef() && wellKnownPropertyPids.arguments->GetTopRef()->GetScopeId() > pnodeFnc->sxFnc.pnodeScopes->sxBlock.blockId)\n                    {\n                        Assert(pnodeFnc->sxFnc.UsesArguments());\n                        \/\/ Arguments symbol is captured in the param scope\n                        paramScope->SetCannotMergeWithBodyScope();\n                    }\n                }\n            }\n        }\n\n        if (!fLambda && paramScope != nullptr && !paramScope->GetCanMergeWithBodyScope()\n            && (pnodeFnc->sxFnc.UsesArguments() || pnodeFnc->grfpn & fpnArguments_overriddenByDecl))\n        {\n            Error(ERRNonSimpleParamListArgumentsUse);\n        }\n\n        \/\/ If the param scope is merged with the body scope we want to use the param scope symbols in the body scope.\n        \/\/ So add a pid ref for the body using the param scope symbol. Note that in this case the same symbol will occur twice\n        \/\/ in the same pid ref stack.\n        if (paramScope != nullptr && paramScope->GetCanMergeWithBodyScope())\n        {\n            paramScope->ForEachSymbol([this](Symbol* paramSym)\n            {\n                PidRefStack* ref = PushPidRef(paramSym->GetPid());\n                ref->SetSym(paramSym);\n            });\n        }\n\n        if (isTopLevelDeferredFunc || (m_InAsmMode && m_deferAsmJs))\n        {\n            AssertMsg(!fLambda, \"Deferring function parsing of a function does not handle lambda syntax\");\n            fDeferred = true;\n\n            this->ParseTopLevelDeferredFunc(pnodeFnc, pnodeFncSave, pNameHint);\n        }\n        else\n        {\n            if (m_token.tk == tkRParen) \/\/ This might be false due to error recovery or lambda.\n            {\n                m_pscan->Scan();\n            }\n\n            if (fLambda)\n            {\n                BOOL hadNewLine = m_pscan->FHadNewLine();\n\n                \/\/ it can be the case we do not have a fat arrow here if there is a valid expression on the left hand side\n                \/\/ of the fat arrow, but that expression does not parse as a parameter list.  E.g.\n                \/\/    a.x => { }\n                \/\/ Therefore check for it and error if not found.\n                \/\/ LS Mode : since this is a lambda we supposed to get the fat arrow, if not we will skip till we get that fat arrow.\n                ChkCurTok(tkDArrow, ERRnoDArrow);\n\n                \/\/ Newline character between arrow parameters and fat arrow is a syntax error but we want to check for\n                \/\/ this after verifying there was a => token. Otherwise we would throw the wrong error.\n                if (hadNewLine)\n                {\n                    Error(ERRsyntax);\n                }\n            }\n\n            AnalysisAssert(pnodeFnc);\n\n            \/\/ Shouldn't be any temps in the arg list.\n            Assert(*m_ppnodeVar == nullptr);\n\n            \/\/ Start the var list.\n            pnodeFnc->sxFnc.pnodeVars = nullptr;\n            m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;\n\n            if (paramScope != nullptr && !paramScope->GetCanMergeWithBodyScope())\n            {\n                OUTPUT_TRACE_DEBUGONLY(Js::ParsePhase, _u(\"The param and body scope of the function %s cannot be merged\\n\"), pnodeFnc->sxFnc.pnodeName ? pnodeFnc->sxFnc.pnodeName->sxVar.pid->Psz() : _u(\"Anonymous function\"));\n                \/\/ Add a new symbol reference for each formal in the param scope to the body scope.\n                \/\/ While inserting symbols into the symbol list we always insert at the front, so while traversing the list we will be visiting the last added\n                \/\/ formals first. Normal insertion of those into the body will reverse the order of symbols, which will eventually result in different order\n                \/\/ for scope slots allocation for the corresponding symbol in both param and body scope. Inserting them in the opposite order will help us\n                \/\/ have the same sequence for scope slots allocation in both scopes. This makes it easy to read the bytecode and may help in some optimization\n                \/\/ later.\n                paramScope->ForEachSymbol([this, pnodeFnc](Symbol* param) {\n                    OUTPUT_TRACE_DEBUGONLY(Js::ParsePhase, _u(\"Creating a duplicate symbol for the parameter %s in the body scope\\n\"), param->GetPid()->Psz());\n\n                    ParseNodePtr paramNode = nullptr;\n                    if (this->m_ppnodeVar != &pnodeFnc->sxFnc.pnodeVars)\n                    {\n                        ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;\n                        m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;\n                        paramNode = this->CreateVarDeclNode(param->GetPid(), STVariable, false, nullptr, false);\n                        m_ppnodeVar = ppnodeVarSave;\n                    }\n                    else\n                    {\n                        paramNode = this->CreateVarDeclNode(param->GetPid(), STVariable, false, nullptr, false);\n                    }\n\n                    Assert(paramNode && paramNode->sxVar.sym->GetScope()->GetScopeType() == ScopeType_FunctionBody);\n                    paramNode->sxVar.sym->SetHasInit(true);\n                });\n\n                if (!fLambda)\n                {\n                    \/\/ In split scope case ideally the arguments object should be in the param scope.\n                    \/\/ Right now referring to arguments in the param scope is a SyntaxError, so we have to\n                    \/\/ add a duplicate symbol in the body scope and copy over the value in BeginBodySope.\n                    ParseNodePtr argumentsNode = this->CreateVarDeclNode(wellKnownPropertyPids.arguments, STVariable, true, nullptr, false);\n                    Assert(argumentsNode && argumentsNode->sxVar.sym->GetScope()->GetScopeType() == ScopeType_FunctionBody);\n                }\n            }\n\n            \/\/ Keep nested function declarations and expressions in the same list at function scope.\n            \/\/ (Indicate this by nulling out the current function expressions list.)\n            m_ppnodeExprScope = nullptr;\n\n            if (buildAST)\n            {\n                DeferredFunctionStub *saveCurrentStub = m_currDeferredStub;\n                if (isEnclosedInParamScope)\n                {\n                    \/\/ if the enclosed scope is the param scope we would not have created the deferred stub.\n                    m_currDeferredStub = nullptr;\n                }\n                else if (pnodeFncSave && m_currDeferredStub)\n                {\n                    \/\/ the Deferred stub will not match for the function which are defined on lambda formals.\n                    \/\/ Since this is not determined upfront that the current function is a part of outer function or part of lambda formal until we have seen the Arrow token.\n                    \/\/ Due to that the current function may be fetching stubs from the outer function (outer of the lambda) - rather then the lambda function. The way to fix is to match\n                    \/\/ the function start with the stub. Because they should match. We need to have previous sibling concept as the lambda formals can have more than one\n                    \/\/ functions and we want to avoid getting wrong stub.\n\n                    if (pnodeFncSave->sxFnc.nestedCount == 1)\n                    {\n                        m_prevSiblingDeferredStub = nullptr;\n                    }\n\n                    if (m_prevSiblingDeferredStub == nullptr)\n                    {\n                        m_prevSiblingDeferredStub = (m_currDeferredStub + (pnodeFncSave->sxFnc.nestedCount - 1));\n                    }\n\n                    if (m_prevSiblingDeferredStub->ichMin == pnodeFnc->ichMin)\n                    {\n                        m_currDeferredStub = m_prevSiblingDeferredStub->deferredStubs;\n                        m_prevSiblingDeferredStub = nullptr;\n                    }\n                    else\n                    {\n                        m_currDeferredStub = nullptr;\n                    }\n                }\n\n                if (m_token.tk != tkLCurly && fLambda)\n                {\n                    ParseExpressionLambdaBody<true>(pnodeFnc);\n                    *pNeedScanRCurly = false;\n                }\n                else\n                {\n                    this->FinishFncDecl(pnodeFnc, pNameHint, lastNodeRef, skipFormals);\n                }\n                m_currDeferredStub = saveCurrentStub;\n            }\n            else\n            {\n                this->ParseNestedDeferredFunc(pnodeFnc, fLambda, pNeedScanRCurly, &strictModeTurnedOn);\n            }\n        }\n\n        if (pnodeInnerBlock)\n        {\n            FinishParseBlock(pnodeInnerBlock, *pNeedScanRCurly);\n        }\n\n        if (!fModule && (m_token.tk == tkLCurly || !fLambda))\n        {\n            this->AddArgumentsNodeToVars(pnodeFnc);\n        }\n\n        \/\/ Restore the lists of scopes that contain function expressions.\n\n        Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);\n        m_ppnodeExprScope = ppnodeExprScopeSave;\n\n        AssertMem(m_ppnodeScope);\n        Assert(nullptr == *m_ppnodeScope);\n        m_ppnodeScope = ppnodeScopeSave;\n\n        if (pnodeBlock)\n        {\n            FinishParseBlock(pnodeBlock, *pNeedScanRCurly);\n        }\n\n        if (IsStrictMode() || strictModeTurnedOn)\n        {\n            this->m_fUseStrictMode = TRUE; \/\/ Now we know this function is in strict mode\n\n            if (!fWasAlreadyStrictMode)\n            {\n                \/\/ If this function turned on strict mode then we didn't check the formal\n                \/\/ parameters or function name hint for future reserved word usage. So do that now.\n                RestorePoint afterFnc;\n                m_pscan->Capture(&afterFnc);\n\n                if (*pHasName)\n                {\n                    \/\/ Rewind to the function name hint and check if the token is a reserved word.\n                    m_pscan->SeekTo(beginNameHint);\n                    m_pscan->Scan();\n                    if (pnodeFnc->sxFnc.IsGenerator())\n                    {\n                        Assert(m_token.tk == tkStar);\n                        Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());\n                        Assert(!(flags & fFncClassMember));\n                        m_pscan->Scan();\n                    }\n                    if (m_token.IsReservedWord())\n                    {\n                        IdentifierExpectedError(m_token);\n                    }\n                    CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(m_phtbl));\n                }\n\n                \/\/ Fast forward to formal parameter list, check for future reserved words,\n                \/\/ then restore scanner as it was.\n                m_pscan->SeekToForcingPid(beginFormals);\n                CheckStrictFormalParameters();\n                m_pscan->SeekTo(afterFnc);\n            }\n\n            if (buildAST)\n            {\n                if (pnodeFnc->sxFnc.pnodeName != nullptr && knopVarDecl == pnodeFnc->sxFnc.pnodeName->nop)\n                {\n                    CheckStrictModeEvalArgumentsUsage(pnodeFnc->sxFnc.pnodeName->sxVar.pid, pnodeFnc->sxFnc.pnodeName);\n                }\n            }\n\n            this->m_fUseStrictMode = oldStrictMode;\n            CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(StrictModeFunctionCount, m_scriptContext);\n        }\n\n        if (fDeferred)\n        {\n            AnalysisAssert(pnodeFnc);\n            pnodeFnc->sxFnc.pnodeVars = nullptr;\n        }\n\n        if (parallelJobStarted)\n        {\n            pnodeFnc = pnodeRealFnc;\n            m_currentNodeFunc = pnodeRealFnc;\n\n            \/\/ Let the foreground thread take care of marking the limit on the function node,\n            \/\/ because in some cases this function's caller will want to change that limit,\n            \/\/ so we don't want the background thread to try and touch it.\n            pnodeFnc->ichLim = m_pscan->IchLimTok();\n            pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();\n        }\n    }\n\n    \/\/ after parsing asm.js module, we want to reset asm.js state before continuing\n    AnalysisAssert(pnodeFnc);\n    if (pnodeFnc->sxFnc.GetAsmjsMode())\n    {\n        m_InAsmMode = false;\n    }\n\n    \/\/ Restore the statement stack.\n    Assert(nullptr == m_pstmtCur);\n    SetCurrentStatement(pstmtSave);\n\n    if (pnodeFncExprScope)\n    {\n        FinishParseFncExprScope(pnodeFnc, pnodeFncExprScope);\n    }\n    if (!m_stoppedDeferredParse)\n    {\n        m_grfscr |= uDeferSave;\n    }\n\n\n    m_pscan->SetYieldIsKeyword(fPreviousYieldIsKeyword);\n    m_pscan->SetAwaitIsKeyword(fPreviousAwaitIsKeyword);\n\n    \/\/ Restore the current function.\n    if (buildAST)\n    {\n        Assert(pnodeFnc == m_currentNodeFunc);\n\n        m_currentNodeFunc = pnodeFncSave;\n        m_pCurrentAstSize = pAstSizeSave;\n\n        if (!fLambda)\n        {\n            Assert(pnodeFnc == m_currentNodeNonLambdaFunc);\n            m_currentNodeNonLambdaFunc = pnodeFncSaveNonLambda;\n        }\n    }\n    else\n    {\n        Assert(pnodeFnc == m_currentNodeDeferredFunc);\n        if (!fLambda)\n        {\n            Assert(pnodeFnc == m_currentNodeNonLambdaDeferredFunc);\n            m_currentNodeNonLambdaDeferredFunc = pnodeFncSaveNonLambda;\n        }\n        m_currentNodeDeferredFunc = pnodeFncSave;\n    }\n\n    if (m_currentNodeFunc && pnodeFnc->sxFnc.HasWithStmt())\n    {\n        GetCurrentFunctionNode()->sxFnc.SetHasWithStmt(true);\n    }\n\n    return true;\n}\n\ntemplate<bool buildAST>\nvoid Parser::UpdateCurrentNodeFunc(ParseNodePtr pnodeFnc, bool fLambda)\n{\n    if (buildAST)\n    {\n        \/\/ Make this the current function and start its sub-function list.\n        m_currentNodeFunc = pnodeFnc;\n\n        Assert(m_currentNodeDeferredFunc == nullptr);\n\n        if (!fLambda)\n        {\n            m_currentNodeNonLambdaFunc = pnodeFnc;\n        }\n    }\n    else \/\/ if !buildAST\n    {\n        AnalysisAssert(pnodeFnc);\n\n        if (!fLambda)\n        {\n            m_currentNodeNonLambdaDeferredFunc = pnodeFnc;\n        }\n\n        m_currentNodeDeferredFunc = pnodeFnc;\n    }\n}\n\nvoid Parser::ParseTopLevelDeferredFunc(ParseNodePtr pnodeFnc, ParseNodePtr pnodeFncParent, LPCOLESTR pNameHint)\n{\n    \/\/ Parse a function body that is a transition point from building AST to doing fast syntax check.\n\n    pnodeFnc->sxFnc.pnodeVars = nullptr;\n    pnodeFnc->sxFnc.pnodeBody = nullptr;\n\n    this->m_deferringAST = TRUE;\n\n    \/\/ Put the scanner into \"no hashing\" mode.\n    BYTE deferFlags = m_pscan->SetDeferredParse(TRUE);\n\n    m_pscan->Scan();\n\n    ChkCurTok(tkLCurly, ERRnoLcurly);\n\n    ParseNodePtr *ppnodeVarSave = m_ppnodeVar;\n\n    m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;\n\n    if (pnodeFncParent != nullptr\n        && m_currDeferredStub != nullptr\n        \/\/ We don't create stubs for function bodies in parameter scope.\n        && pnodeFnc->sxFnc.pnodeScopes->sxBlock.blockType != PnodeBlockType::Parameter)\n    {\n        \/\/ We've already parsed this function body for syntax errors on the initial parse of the script.\n        \/\/ We have information that allows us to skip it, so do so.\n\n        DeferredFunctionStub *stub = m_currDeferredStub + (pnodeFncParent->sxFnc.nestedCount - 1);\n        Assert(pnodeFnc->ichMin == stub->ichMin);\n        if (stub->fncFlags & kFunctionCallsEval)\n        {\n            this->MarkEvalCaller();\n        }\n        if (stub->fncFlags & kFunctionChildCallsEval)\n        {\n            pnodeFnc->sxFnc.SetChildCallsEval(true);\n        }\n        if (stub->fncFlags & kFunctionHasWithStmt)\n        {\n            pnodeFnc->sxFnc.SetHasWithStmt(true);\n        }\n\n        PHASE_PRINT_TRACE1(\n            Js::SkipNestedDeferredPhase,\n            _u(\"Skipping nested deferred function %d. %s: %d...%d\\n\"),\n            pnodeFnc->sxFnc.functionId, GetFunctionName(pnodeFnc, pNameHint), pnodeFnc->ichMin, stub->restorePoint.m_ichMinTok);\n\n        m_pscan->SeekTo(stub->restorePoint, m_nextFunctionId);\n        pnodeFnc->sxFnc.nestedCount = stub->nestedCount;\n        pnodeFnc->sxFnc.deferredStub = stub->deferredStubs;\n        if (stub->fncFlags & kFunctionStrictMode)\n        {\n            pnodeFnc->sxFnc.SetStrictMode(true);\n        }\n    }\n    else\n    {\n        ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true \/* isSourceElementList *\/);\n    }\n\n    pnodeFnc->ichLim = m_pscan->IchLimTok();\n    pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();\n\n    m_ppnodeVar = ppnodeVarSave;\n\n    \/\/ Restore the scanner's default hashing mode.\n    \/\/ Do this before we consume the next token.\n    m_pscan->SetDeferredParseFlags(deferFlags);\n\n    ChkCurTokNoScan(tkRCurly, ERRnoRcurly);\n\n#if DBG\n    pnodeFnc->sxFnc.deferredParseNextFunctionId = *this->m_nextFunctionId;\n#endif\n    this->m_deferringAST = FALSE;\n}\n\nbool Parser::DoParallelParse(ParseNodePtr pnodeFnc) const\n{\n#if ENABLE_BACKGROUND_PARSING\n    if (!PHASE_ON_RAW(Js::ParallelParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->sxFnc.functionId))\n    {\n        return false;\n    }\n\n    BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();\n    return bgp != nullptr;\n#else\n    return false;\n#endif\n}\n\nbool Parser::ScanAheadToFunctionEnd(uint count)\n{\n    bool found = false;\n    uint curlyDepth = 0;\n\n    RestorePoint funcStart;\n    m_pscan->Capture(&funcStart);\n\n    for (uint i = 0; i < count; i++)\n    {\n        switch (m_token.tk)\n        {\n            case tkStrTmplBegin:\n            case tkStrTmplMid:\n            case tkStrTmplEnd:\n            case tkDiv:\n            case tkAsgDiv:\n            case tkScanError:\n            case tkEOF:\n                goto LEnd;\n\n            case tkLCurly:\n                UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);\n                break;\n\n            case tkRCurly:\n                if (curlyDepth == 1)\n                {\n                    found = true;\n                    goto LEnd;\n                }\n                if (curlyDepth == 0)\n                {\n                    goto LEnd;\n                }\n                curlyDepth--;\n                break;\n        }\n\n        m_pscan->ScanAhead();\n    }\n\n LEnd:\n    m_pscan->SeekTo(funcStart);\n    return found;\n}\n\nbool Parser::FastScanFormalsAndBody()\n{\n    \/\/ The scanner is currently pointing just past the name of a function.\n    \/\/ The idea here is to find the end of the function body as quickly as possible,\n    \/\/ by tokenizing and tracking {}'s if possible.\n    \/\/ String templates require some extra logic but can be handled.\n\n    \/\/ The real wrinkle is \"\/\" and \"\/=\", which may indicate either a RegExp literal or a division, depending\n    \/\/ on the context.\n    \/\/ To handle this with minimal work, keep track of the last \";\" seen at each {} depth. If we see one of the\n    \/\/ difficult tokens, rewind to the last \";\" at the current {} depth and parse statements until we pass the\n    \/\/ point where we had to rewind. This will process the \"\/\" as required.\n\n    RestorePoint funcStart;\n    m_pscan->Capture(&funcStart);\n\n    const int maxRestorePointDepth = 16;\n    struct FastScanRestorePoint\n    {\n        RestorePoint restorePoint;\n        uint parenDepth;\n        Js::LocalFunctionId functionId;\n        int blockId;\n\n        FastScanRestorePoint() : restorePoint(), parenDepth(0) {};\n    };\n    FastScanRestorePoint lastSColonAtCurlyDepth[maxRestorePointDepth];\n\n    charcount_t ichStart = m_pscan->IchMinTok();\n    uint blockIdSave = m_nextBlockId;\n    uint functionIdSave = *m_nextFunctionId;\n    uint curlyDepth = 0;\n    uint strTmplDepth = 0;\n    for (;;)\n    {\n        switch (m_token.tk)\n        {\n            case tkStrTmplBegin:\n                UInt32Math::Inc(strTmplDepth, Parser::OutOfMemory);\n                \/\/ Fall through\n\n            case tkStrTmplMid:\n            case tkLCurly:\n                UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);\n                Int32Math::Inc(m_nextBlockId, &m_nextBlockId);\n                break;\n\n            case tkStrTmplEnd:\n                \/\/ We can assert here, because the scanner will only return this token if we've told it we're\n                \/\/ in a string template.\n                Assert(strTmplDepth > 0);\n                strTmplDepth--;\n                break;\n\n            case tkRCurly:\n                if (curlyDepth == 1)\n                {\n                    Assert(strTmplDepth == 0);\n                    if (PHASE_TRACE1(Js::ParallelParsePhase))\n                    {\n                        Output::Print(_u(\"Finished fast seek: %d. %s -- %d...%d\\n\"),\n                                      m_currentNodeFunc->sxFnc.functionId,\n                                      GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->sxFnc.hint),\n                                      ichStart, m_pscan->IchLimTok());\n                    }\n                    return true;\n                }\n                if (curlyDepth < maxRestorePointDepth)\n                {\n                    lastSColonAtCurlyDepth[curlyDepth].restorePoint.m_ichMinTok = (uint)-1;\n                }\n                curlyDepth--;\n                if (strTmplDepth > 0)\n                {\n                    m_pscan->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);\n                }\n                break;\n\n            case tkSColon:\n                \/\/ Track the location of the \";\" (if it's outside parens, as we don't, for instance, want\n                \/\/ to track the \";\"'s in a for-loop header. If we find it's important to rewind within a paren\n                \/\/ expression, we can do something more sophisticated.)\n                if (curlyDepth < maxRestorePointDepth && lastSColonAtCurlyDepth[curlyDepth].parenDepth == 0)\n                {\n                    m_pscan->Capture(&lastSColonAtCurlyDepth[curlyDepth].restorePoint);\n                    lastSColonAtCurlyDepth[curlyDepth].functionId = *this->m_nextFunctionId;\n                    lastSColonAtCurlyDepth[curlyDepth].blockId = m_nextBlockId;\n                }\n                break;\n\n            case tkLParen:\n                if (curlyDepth < maxRestorePointDepth)\n                {\n                    UInt32Math::Inc(lastSColonAtCurlyDepth[curlyDepth].parenDepth);\n                }\n                break;\n\n            case tkRParen:\n                if (curlyDepth < maxRestorePointDepth)\n                {\n                    Assert(lastSColonAtCurlyDepth[curlyDepth].parenDepth != 0);\n                    lastSColonAtCurlyDepth[curlyDepth].parenDepth--;\n                }\n                break;\n\n            case tkID:\n            {\n                charcount_t tokLength = m_pscan->IchLimTok() - m_pscan->IchMinTok();\n                \/\/ Detect the function and class keywords so we can track function ID's.\n                \/\/ (In fast mode, the scanner doesn't distinguish keywords and doesn't point the token\n                \/\/ to a PID.)\n                \/\/ Detect try\/catch\/for to increment block count for them.\n                switch (tokLength)\n                {\n                case 3:\n                    if (!memcmp(m_pscan->PchMinTok(), \"try\", 3) || !memcmp(m_pscan->PchMinTok(), \"for\", 3))\n                    {\n                        Int32Math::Inc(m_nextBlockId, &m_nextBlockId);\n                    }\n                    break;\n                case 5:\n                    if (!memcmp(m_pscan->PchMinTok(), \"catch\", 5))\n                    {\n                        Int32Math::Inc(m_nextBlockId, &m_nextBlockId);\n                    }\n                    else if (!memcmp(m_pscan->PchMinTok(), \"class\", 5))\n                    {\n                        Int32Math::Inc(m_nextBlockId, &m_nextBlockId);\n                        Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);\n                    }\n                    break;\n                case 8:\n                    if (!memcmp(m_pscan->PchMinTok(), \"function\", 8))\n                    {\n                        \/\/ Account for the possible func expr scope or dummy block for missing {}'s around a declaration\n                        Int32Math::Inc(m_nextBlockId, &m_nextBlockId);\n                        Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);\n                    }\n                    break;\n                }\n                break;\n            }\n\n            case tkDArrow:\n                Int32Math::Inc(m_nextBlockId, &m_nextBlockId);\n                Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);\n                break;\n\n            case tkDiv:\n            case tkAsgDiv:\n            {\n                int opl;\n                OpCode nop;\n                tokens tkPrev = m_pscan->m_tkPrevious;\n                if ((m_pscan->m_phtbl->TokIsBinop(tkPrev, &opl, &nop) && nop != knopNone) ||\n                    (m_pscan->m_phtbl->TokIsUnop(tkPrev, &opl, &nop) &&\n                     nop != knopNone &&\n                     tkPrev != tkInc &&\n                     tkPrev != tkDec) ||\n                    tkPrev == tkColon ||\n                    tkPrev == tkLParen ||\n                    tkPrev == tkLBrack ||\n                    tkPrev == tkRETURN)\n                {\n                    \/\/ Previous token indicates that we're starting an expression here and can't have a\n                    \/\/ binary operator now.\n                    \/\/ Assume this is a RegExp.\n                    ParseRegExp<false>();\n                    break;\n                }\n                uint tempCurlyDepth = curlyDepth < maxRestorePointDepth ? curlyDepth : maxRestorePointDepth - 1;\n                for (; tempCurlyDepth != (uint)-1; tempCurlyDepth--)\n                {\n                    \/\/ We don't know whether we've got a RegExp or a divide. Rewind to the last safe \";\"\n                    \/\/ if we can and parse statements until we pass this point.\n                    if (lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint.m_ichMinTok != -1)\n                    {\n                        break;\n                    }\n                }\n                if (tempCurlyDepth != (uint)-1)\n                {\n                    ParseNodePtr pnodeFncSave = m_currentNodeFunc;\n                    int32 *pastSizeSave = m_pCurrentAstSize;\n                    uint *pnestedCountSave = m_pnestedCount;\n                    ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;\n                    ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;\n\n                    ParseNodePtr pnodeFnc = CreateDummyFuncNode(true);\n                    m_ppnodeScope = &pnodeFnc->sxFnc.pnodeScopes;\n                    m_ppnodeExprScope = nullptr;\n\n                    charcount_t ichStop = m_pscan->IchLimTok();\n                    curlyDepth = tempCurlyDepth;\n                    m_pscan->SeekTo(lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint);\n                    m_nextBlockId = lastSColonAtCurlyDepth[tempCurlyDepth].blockId;\n                    *this->m_nextFunctionId = lastSColonAtCurlyDepth[tempCurlyDepth].functionId;\n\n                    ParseNodePtr pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);\n\n                    m_pscan->Scan();\n                    do\n                    {\n                        ParseStatement<false>();\n                    }\n                    while(m_pscan->IchMinTok() < ichStop);\n\n                    FinishParseBlock(pnodeBlock);\n\n                    m_currentNodeFunc = pnodeFncSave;\n                    m_pCurrentAstSize = pastSizeSave;\n                    m_pnestedCount = pnestedCountSave;\n                    m_ppnodeScope = ppnodeScopeSave;\n                    m_ppnodeExprScope = ppnodeExprScopeSave;\n\n                    \/\/ We've already consumed the first token of the next statement, so just continue\n                    \/\/ without a further scan.\n                    continue;\n                }\n            }\n\n                \/\/ fall through to rewind to function start\n            case tkScanError:\n            case tkEOF:\n                \/\/ Unexpected token.\n                if (PHASE_TRACE1(Js::ParallelParsePhase))\n                {\n                    Output::Print(_u(\"Failed fast seek: %d. %s -- %d...%d\\n\"),\n                                  m_currentNodeFunc->sxFnc.functionId,\n                                  GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->sxFnc.hint),\n                                  ichStart, m_pscan->IchLimTok());\n                }\n                m_nextBlockId = blockIdSave;\n                *m_nextFunctionId = functionIdSave;\n                m_pscan->SeekTo(funcStart);\n                return false;\n        }\n\n        m_pscan->ScanNoKeywords();\n    }\n}\n\nParseNodePtr Parser::CreateDummyFuncNode(bool fDeclaration)\n{\n    \/\/ Create a dummy node and make it look like the current function declaration.\n    \/\/ Do this in situations where we want to parse statements without impacting\n    \/\/ the state of the \"real\" AST.\n\n    ParseNodePtr pnodeFnc = CreateNode(knopFncDecl);\n    pnodeFnc->sxFnc.ClearFlags();\n    pnodeFnc->sxFnc.SetDeclaration(fDeclaration);\n    pnodeFnc->sxFnc.astSize             = 0;\n    pnodeFnc->sxFnc.pnodeName           = nullptr;\n    pnodeFnc->sxFnc.pnodeScopes         = nullptr;\n    pnodeFnc->sxFnc.pnodeRest           = nullptr;\n    pnodeFnc->sxFnc.pid                 = nullptr;\n    pnodeFnc->sxFnc.hint                = nullptr;\n    pnodeFnc->sxFnc.hintOffset          = 0;\n    pnodeFnc->sxFnc.hintLength          = 0;\n    pnodeFnc->sxFnc.isNameIdentifierRef = true;\n    pnodeFnc->sxFnc.nestedFuncEscapes   = false;\n    pnodeFnc->sxFnc.pnodeNext           = nullptr;\n    pnodeFnc->sxFnc.pnodeParams         = nullptr;\n    pnodeFnc->sxFnc.pnodeVars           = nullptr;\n    pnodeFnc->sxFnc.funcInfo            = nullptr;\n    pnodeFnc->sxFnc.deferredStub        = nullptr;\n    pnodeFnc->sxFnc.nestedCount         = 0;\n    pnodeFnc->sxFnc.SetNested(m_currentNodeFunc != nullptr); \/\/ If there is a current function, then we're a nested function.\n    pnodeFnc->sxFnc.SetStrictMode(IsStrictMode()); \/\/ Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.\n    pnodeFnc->sxFnc.firstDefaultArg = 0;\n\n    m_pCurrentAstSize = &pnodeFnc->sxFnc.astSize;\n    m_currentNodeFunc = pnodeFnc;\n    m_pnestedCount = &pnodeFnc->sxFnc.nestedCount;\n\n    return pnodeFnc;\n}\n\nvoid Parser::ParseNestedDeferredFunc(ParseNodePtr pnodeFnc, bool fLambda, bool *pNeedScanRCurly, bool *pStrictModeTurnedOn)\n{\n    \/\/ Parse a function nested inside another deferred function.\n\n    size_t lengthBeforeBody = this->GetSourceLength();\n\n    if (m_token.tk != tkLCurly && fLambda)\n    {\n        ParseExpressionLambdaBody<false>(pnodeFnc);\n        *pNeedScanRCurly = false;\n    }\n    else\n    {\n        ChkCurTok(tkLCurly, ERRnoLcurly);\n\n        bool* detectStrictModeOn = IsStrictMode() ? nullptr : pStrictModeTurnedOn;\n        m_ppnodeVar = &m_currentNodeDeferredFunc->sxFnc.pnodeVars;\n\n        ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true \/* isSourceElementList *\/, detectStrictModeOn);\n\n        ChkCurTokNoScan(tkRCurly, ERRnoRcurly);\n    }\n\n    pnodeFnc->ichLim = m_pscan->IchLimTok();\n    pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();\n    if (*pStrictModeTurnedOn)\n    {\n        pnodeFnc->sxFnc.SetStrictMode(true);\n    }\n\n    if (!PHASE_OFF1(Js::SkipNestedDeferredPhase))\n    {\n        \/\/ Record the end of the function and the function ID increment that happens inside the function.\n        \/\/ Byte code gen will use this to build stub information to allow us to skip this function when the\n        \/\/ enclosing function is fully parsed.\n        RestorePoint *restorePoint = Anew(&m_nodeAllocator, RestorePoint);\n        m_pscan->Capture(restorePoint,\n                         *m_nextFunctionId - pnodeFnc->sxFnc.functionId - 1,\n                         lengthBeforeBody - this->GetSourceLength());\n        pnodeFnc->sxFnc.pRestorePoint = restorePoint;\n    }\n}\n\ntemplate<bool buildAST>\nbool Parser::ParseFncNames(ParseNodePtr pnodeFnc, ParseNodePtr pnodeFncParent, ushort flags, ParseNodePtr **pLastNodeRef)\n{\n    BOOL fDeclaration = flags & fFncDeclaration;\n    BOOL fIsAsync = flags & fFncAsync;\n    ParseNodePtr pnodeT;\n    charcount_t ichMinNames, ichLimNames;\n\n    \/\/ Get the names to bind to.\n    \/*\n    * KaushiS [5\/15\/08]:\n    * ECMAScript defines a FunctionExpression as follows:\n    *\n    * \"function\" [Identifier] ( [FormalParameterList] ) { FunctionBody }\n    *\n    * The function name being optional is omitted by most real world\n    * code that uses a FunctionExpression to define a function. This however\n    * is problematic for tools because there isn't a function name that\n    * the runtime can provide.\n    *\n    * To fix this (primarily for the profiler), I'm adding simple, static\n    * name inferencing logic to the parser. When it encounters the following\n    * productions\n    *\n    *   \"var\" Identifier \"=\" FunctionExpression\n    *   \"var\" IdentifierA.IdentifierB...Identifier \"=\" FunctionExpression\n    *   Identifier = FunctionExpression\n    *   \"{\" Identifier: FunctionExpression \"}\"\n    *\n    * it associates Identifier with the function created by the\n    * FunctionExpression. This identifier is *not* the function's name. It\n    * is ignored by the runtime and is only an additional piece of information\n    * about the function (function name hint) that tools could opt to\n    * surface.\n    *\/\n\n    m_pscan->Scan();\n\n    \/\/ If generators are enabled then we are in a recent enough version\n    \/\/ that deferred parsing will create a parse node for pnodeFnc and\n    \/\/ it is safe to assume it is not null.\n    if (flags & fFncGenerator)\n    {\n        Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());\n        pnodeFnc->sxFnc.SetIsGenerator();\n    }\n    else if (m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&\n        m_token.tk == tkStar &&\n        !(flags & fFncClassMember))\n    {\n        if (!fDeclaration)\n        {\n            bool fPreviousYieldIsKeyword = m_pscan->SetYieldIsKeyword(!fDeclaration);\n            m_pscan->Scan();\n            m_pscan->SetYieldIsKeyword(fPreviousYieldIsKeyword);\n        }\n        else\n        {\n            m_pscan->Scan();\n        }\n\n        pnodeFnc->sxFnc.SetIsGenerator();\n    }\n\n    if (fIsAsync)\n    {\n        if (pnodeFnc->sxFnc.IsGenerator())\n        {\n            Error(ERRsyntax);\n        }\n        pnodeFnc->sxFnc.SetIsAsync();\n    }\n\n    if (pnodeFnc)\n    {\n        pnodeFnc->sxFnc.pnodeName = nullptr;\n    }\n\n    if ((m_token.tk != tkID || flags & fFncNoName)\n        && (IsStrictMode() || (pnodeFnc && pnodeFnc->sxFnc.IsGenerator()) || m_token.tk != tkYIELD || fDeclaration)) \/\/ Function expressions can have the name yield even inside generator functions\n    {\n        if (fDeclaration  ||\n            m_token.IsReservedWord())  \/\/ For example:  var x = (function break(){});\n        {\n            IdentifierExpectedError(m_token);\n        }\n        return false;\n    }\n\n    ichMinNames = m_pscan->IchMinTok();\n\n\n    Assert(m_token.tk == tkID || (m_token.tk == tkYIELD && !fDeclaration));\n\n    if (IsStrictMode())\n    {\n        CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(m_phtbl));\n    }\n    Token tokenBase = m_token;\n    charcount_t ichMinBase = m_pscan->IchMinTok();\n    charcount_t ichLimBase = m_pscan->IchLimTok();\n\n    m_pscan->Scan();\n\n    IdentPtr pidBase = tokenBase.GetIdentifier(m_phtbl);\n    pnodeT = CreateDeclNode(knopVarDecl, pidBase, STFunction);\n    pnodeT->ichMin = ichMinBase;\n    pnodeT->ichLim = ichLimBase;\n\n    if (fDeclaration &&\n        pnodeFncParent &&\n        pnodeFncParent->sxFnc.pnodeName &&\n        pnodeFncParent->sxFnc.pnodeName->nop == knopVarDecl &&\n        pnodeFncParent->sxFnc.pnodeName->sxVar.pid == pidBase)\n    {\n        pnodeFncParent->sxFnc.SetNameIsHidden();\n    }\n\n    if (buildAST)\n    {\n        AnalysisAssert(pnodeFnc);\n        ichLimNames = pnodeT->ichLim;\n        AddToNodeList(&pnodeFnc->sxFnc.pnodeName, pLastNodeRef, pnodeT);\n\n        pnodeFnc->sxFnc.pnodeName->ichMin = ichMinNames;\n        pnodeFnc->sxFnc.pnodeName->ichLim = ichLimNames;\n        if (knopVarDecl == pnodeFnc->sxFnc.pnodeName->nop)\n        {\n            \/\/ Only one name (the common case).\n            pnodeFnc->sxFnc.pid = pnodeFnc->sxFnc.pnodeName->sxVar.pid;\n        }\n        else\n        {\n            \/\/ Multiple names. Turn the source into an IdentPtr.\n            pnodeFnc->sxFnc.pid = m_phtbl->PidHashNameLen(\n                m_pscan->PchBase() + ichMinNames, ichLimNames - ichMinNames);\n        }\n    }\n\n    return true;\n}\n\nvoid Parser::ValidateFormals()\n{\n    ParseFncFormals<false>(nullptr, nullptr, fFncNoFlgs);\n    \/\/ Eat the tkRParen. The ParseFncDeclHelper caller expects to see it.\n    m_pscan->Scan();\n}\n\nvoid Parser::ValidateSourceElementList()\n{\n    ParseStmtList<false>(nullptr, nullptr, SM_NotUsed, true);\n}\n\nvoid Parser::UpdateOrCheckForDuplicateInFormals(IdentPtr pid, SList<IdentPtr> *formals)\n{\n    bool isStrictMode = IsStrictMode();\n    if (isStrictMode)\n    {\n        CheckStrictModeEvalArgumentsUsage(pid);\n    }\n\n    if (formals->Has(pid))\n    {\n        if (isStrictMode)\n        {\n            Error(ERRES5ArgSame);\n        }\n        else\n        {\n            Error(ERRFormalSame);\n        }\n    }\n    else\n    {\n        formals->Prepend(pid);\n    }\n}\n\ntemplate<bool buildAST>\nvoid Parser::ParseFncFormals(ParseNodePtr pnodeFnc, ParseNodePtr pnodeParentFnc, ushort flags)\n{\n    bool fLambda = (flags & fFncLambda) != 0;\n    bool fMethod = (flags & fFncMethod) != 0;\n    bool fNoArg = (flags & fFncNoArg) != 0;\n    bool fOneArg = (flags & fFncOneArg) != 0;\n    bool fAsync = (flags & fFncAsync) != 0;\n\n    bool fPreviousYieldIsKeyword = false;\n    bool fPreviousAwaitIsKeyword = false;\n\n    if (fLambda)\n    {\n        fPreviousYieldIsKeyword = m_pscan->SetYieldIsKeyword(pnodeParentFnc != nullptr && pnodeParentFnc->sxFnc.IsGenerator());\n        fPreviousAwaitIsKeyword = m_pscan->SetAwaitIsKeyword(fAsync || (pnodeParentFnc != nullptr && pnodeParentFnc->sxFnc.IsAsync()));\n    }\n\n    Assert(!fNoArg || !fOneArg); \/\/ fNoArg and fOneArg can never be true at the same time.\n\n    \/\/ strictFormals corresponds to the StrictFormalParameters grammar production\n    \/\/ in the ES spec which just means duplicate names are not allowed\n    bool fStrictFormals = IsStrictMode() || fLambda || fMethod;\n\n    \/\/ When detecting duplicated formals pids are needed so force PID creation (unless the function should take 0 or 1 arg).\n    bool forcePid = fStrictFormals && !fNoArg && !fOneArg;\n    AutoTempForcePid autoForcePid(m_pscan, forcePid);\n\n    \/\/ Lambda's allow single formal specified by a single binding identifier without parentheses, special case it.\n    if (fLambda && m_token.tk == tkID)\n    {\n        IdentPtr pid = m_token.GetIdentifier(m_phtbl);\n\n        CreateVarDeclNode(pid, STFormal, false, nullptr, false);\n        CheckPidIsValid(pid);\n\n        m_pscan->Scan();\n\n        if (m_token.tk != tkDArrow)\n        {\n            Error(ERRsyntax, m_pscan->IchMinTok(), m_pscan->IchLimTok());\n        }\n\n        if (fLambda)\n        {\n            m_pscan->SetYieldIsKeyword(fPreviousYieldIsKeyword);\n            m_pscan->SetAwaitIsKeyword(fPreviousAwaitIsKeyword);\n        }\n\n        return;\n    }\n    else if (fLambda && m_token.tk == tkAWAIT)\n    {\n        \/\/ async await => {}\n        IdentifierExpectedError(m_token);\n    }\n\n    \/\/ Otherwise, must have a parameter list within parens.\n    ChkCurTok(tkLParen, ERRnoLparen);\n\n    \/\/ Now parse the list of arguments, if present\n    if (m_token.tk == tkRParen)\n    {\n        if (fOneArg)\n        {\n            Error(ERRSetterMustHaveOneParameter);\n        }\n    }\n    else\n    {\n        if (fNoArg)\n        {\n            Error(ERRGetterMustHaveNoParameters);\n        }\n        SList<IdentPtr> formals(&m_nodeAllocator);\n        ParseNodePtr pnodeT = nullptr;\n        bool seenRestParameter = false;\n        bool isNonSimpleParameterList = false;\n        for (Js::ArgSlot argPos = 0; ; ++argPos)\n        {\n            bool isBindingPattern = false;\n            if (m_scriptContext->GetConfig()->IsES6RestEnabled() && m_token.tk == tkEllipsis)\n            {\n                \/\/ Possible rest parameter\n                m_pscan->Scan();\n                seenRestParameter = true;\n            }\n            if (m_token.tk != tkID)\n            {\n                if (IsES6DestructuringEnabled() && IsPossiblePatternStart())\n                {\n                    \/\/ Mark that the function has a non simple parameter list before parsing the pattern since the pattern can have function definitions.\n                    this->GetCurrentFunctionNode()->sxFnc.SetHasNonSimpleParameterList();\n\n                    ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;\n                    m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;\n\n                    ParseNodePtr * ppNodeLex = m_currentBlockInfo->m_ppnodeLex;\n                    Assert(ppNodeLex != nullptr);\n\n                    ParseNodePtr paramPattern = nullptr;\n                    ParseNodePtr pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true \/*isDecl*\/, false \/*topLevel*\/);\n\n                    \/\/ Instead of passing the STFormal all the way on many methods, it seems it is better to change the symbol type afterward.\n                    for (ParseNodePtr lexNode = *ppNodeLex; lexNode != nullptr; lexNode = lexNode->sxVar.pnodeNext)\n                    {\n                        Assert(lexNode->IsVarLetOrConst());\n                        UpdateOrCheckForDuplicateInFormals(lexNode->sxVar.pid, &formals);\n                        lexNode->sxVar.sym->SetSymbolType(STFormal);\n                        if (m_currentNodeFunc != nullptr && lexNode->sxVar.pid == wellKnownPropertyPids.arguments)\n                        {\n                            m_currentNodeFunc->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;\n                        }\n                    }\n\n                    m_ppnodeVar = ppnodeVarSave;\n                    if (buildAST)\n                    {\n                        paramPattern = CreateParamPatternNode(pnodePattern);\n\n                        \/\/ Linking the current formal parameter (which is pattern parameter) with other formals.\n                        *m_ppnodeVar = paramPattern;\n                        paramPattern->sxParamPattern.pnodeNext = nullptr;\n                        m_ppnodeVar = &paramPattern->sxParamPattern.pnodeNext;\n                    }\n\n                    isBindingPattern = true;\n                    isNonSimpleParameterList = true;\n                }\n                else\n                {\n                    IdentifierExpectedError(m_token);\n                }\n            }\n\n            if (!isBindingPattern)\n            {\n                IdentPtr pid = m_token.GetIdentifier(m_phtbl);\n                LPCOLESTR pNameHint = pid->Psz();\n                uint32 nameHintLength = pid->Cch();\n                uint32 nameHintOffset = 0;\n\n                if (seenRestParameter)\n                {\n                    this->GetCurrentFunctionNode()->sxFnc.SetHasNonSimpleParameterList();\n                    if (flags & fFncOneArg)\n                    {\n                        \/\/ The parameter of a setter cannot be a rest parameter.\n                        Error(ERRUnexpectedEllipsis);\n                    }\n                    pnodeT = CreateDeclNode(knopVarDecl, pid, STFormal, false);\n                    pnodeT->sxVar.sym->SetIsNonSimpleParameter(true);\n                    if (buildAST)\n                    {\n                        \/\/ When only validating formals, we won't have a function node.\n                        pnodeFnc->sxFnc.pnodeRest = pnodeT;\n                        if (!isNonSimpleParameterList)\n                        {\n                            \/\/ This is the first non-simple parameter we've seen. We need to go back\n                            \/\/ and set the Symbols of all previous parameters.\n                            MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->sxVar.sym->SetIsNonSimpleParameter(true); });\n                        }\n                    }\n\n                    isNonSimpleParameterList = true;\n                }\n                else\n                {\n                    pnodeT = CreateVarDeclNode(pid, STFormal, false, nullptr, false);\n                    if (isNonSimpleParameterList)\n                    {\n                        pnodeT->sxVar.sym->SetIsNonSimpleParameter(true);\n                    }\n                }\n\n                if (buildAST && pid == wellKnownPropertyPids.arguments)\n                {\n                    \/\/ This formal parameter overrides the built-in 'arguments' object\n                    m_currentNodeFunc->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;\n                }\n\n                if (fStrictFormals)\n                {\n                    UpdateOrCheckForDuplicateInFormals(pid, &formals);\n                }\n\n                m_pscan->Scan();\n\n                if (seenRestParameter && m_token.tk != tkRParen && m_token.tk != tkAsg)\n                {\n                    Error(ERRRestLastArg);\n                }\n\n                if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())\n                {\n                    if (seenRestParameter && m_scriptContext->GetConfig()->IsES6RestEnabled())\n                    {\n                        Error(ERRRestWithDefault);\n                    }\n\n                    \/\/ In defer parse mode we have to flag the function node to indicate that it has default arguments\n                    \/\/ so that it will be considered for any syntax error scenario.\n                    \/\/ Also mark it before parsing the expression as it may contain functions.\n                    ParseNode* currentFncNode = GetCurrentFunctionNode();\n                    if (!currentFncNode->sxFnc.HasDefaultArguments())\n                    {\n                        currentFncNode->sxFnc.SetHasDefaultArguments();\n                        currentFncNode->sxFnc.SetHasNonSimpleParameterList();\n                        currentFncNode->sxFnc.firstDefaultArg = argPos;\n                    }\n\n                    m_pscan->Scan();\n                    ParseNodePtr pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);\n\n                    if (buildAST && pnodeInit->nop == knopFncDecl)\n                    {\n                        Assert(nameHintLength >= nameHintOffset);\n                        pnodeInit->sxFnc.hint = pNameHint;\n                        pnodeInit->sxFnc.hintLength = nameHintLength;\n                        pnodeInit->sxFnc.hintOffset = nameHintOffset;\n                    }\n\n                    AnalysisAssert(pnodeT);\n                    pnodeT->sxVar.sym->SetIsNonSimpleParameter(true);\n                    if (!isNonSimpleParameterList)\n                    {\n                        if (buildAST)\n                        {\n                            \/\/ This is the first non-simple parameter we've seen. We need to go back\n                            \/\/ and set the Symbols of all previous parameters.\n                            MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->sxVar.sym->SetIsNonSimpleParameter(true); });\n                        }\n\n                        \/\/ There may be previous parameters that need to be checked for duplicates.\n                        isNonSimpleParameterList = true;\n                    }\n\n                    if (buildAST)\n                    {\n                        if (!m_currentNodeFunc->sxFnc.HasDefaultArguments())\n                        {\n                            CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(DefaultArgFunctionCount, m_scriptContext);\n                        }\n                        pnodeT->sxVar.pnodeInit = pnodeInit;\n                        pnodeT->ichLim = m_pscan->IchLimTok();\n                    }\n                }\n            }\n\n            if (isNonSimpleParameterList && m_currentScope->GetHasDuplicateFormals())\n            {\n                Error(ERRFormalSame);\n            }\n\n            if (flags & fFncOneArg)\n            {\n                if (m_token.tk != tkRParen)\n                {\n                    Error(ERRSetterMustHaveOneParameter);\n                }\n                break; \/\/enforce only one arg\n            }\n\n            if (m_token.tk != tkComma)\n            {\n                break;\n            }\n\n            m_pscan->Scan();\n\n            if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())\n            {\n                break;\n            }\n        }\n\n        if (seenRestParameter)\n        {\n            CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(RestCount, m_scriptContext);\n        }\n\n        if (m_token.tk != tkRParen)\n        {\n            Error(ERRnoRparen);\n        }\n\n        if (this->GetCurrentFunctionNode()->sxFnc.CallsEval() || this->GetCurrentFunctionNode()->sxFnc.ChildCallsEval())\n        {\n            if (!m_scriptContext->GetConfig()->IsES6DefaultArgsSplitScopeEnabled())\n            {\n                Error(ERREvalNotSupportedInParamScope);\n            }\n            else\n            {\n                Assert(pnodeFnc->sxFnc.HasNonSimpleParameterList());\n                pnodeFnc->sxFnc.pnodeScopes->sxBlock.scope->SetCannotMergeWithBodyScope();\n            }\n        }\n    }\n    Assert(m_token.tk == tkRParen);\n\n    if (fLambda)\n    {\n        m_pscan->SetYieldIsKeyword(fPreviousYieldIsKeyword);\n        m_pscan->SetAwaitIsKeyword(fPreviousAwaitIsKeyword);\n    }\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::GenerateModuleFunctionWrapper()\n{\n    ParseNodePtr pnodeFnc = ParseFncDecl<buildAST>(fFncModule, nullptr, false, true, true);\n    ParseNodePtr callNode = CreateCallNode(knopCall, pnodeFnc, nullptr);\n\n    return callNode;\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::GenerateEmptyConstructor(bool extends)\n{\n    ParseNodePtr pnodeFnc;\n\n    \/\/ Create the node.\n    pnodeFnc = CreateNode(knopFncDecl);\n    pnodeFnc->sxFnc.ClearFlags();\n    pnodeFnc->sxFnc.SetNested(NULL != m_currentNodeFunc);\n    pnodeFnc->sxFnc.SetStrictMode();\n    pnodeFnc->sxFnc.SetDeclaration(TRUE);\n    pnodeFnc->sxFnc.SetIsMethod(TRUE);\n    pnodeFnc->sxFnc.SetIsClassMember(TRUE);\n    pnodeFnc->sxFnc.SetIsClassConstructor(TRUE);\n    pnodeFnc->sxFnc.SetIsBaseClassConstructor(!extends);\n    pnodeFnc->sxFnc.SetHasNonThisStmt();\n    pnodeFnc->sxFnc.SetIsGeneratedDefault(TRUE);\n\n    pnodeFnc->ichLim = m_pscan->IchLimTok();\n    pnodeFnc->ichMin = m_pscan->IchMinTok();\n    pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();\n    pnodeFnc->sxFnc.cbMin = m_pscan->IecpMinTok();\n    pnodeFnc->sxFnc.astSize = 0;\n    pnodeFnc->sxFnc.lineNumber = m_pscan->LineCur();\n\n    pnodeFnc->sxFnc.functionId          = (*m_nextFunctionId);\n    pnodeFnc->sxFnc.pid                 = nullptr;\n    pnodeFnc->sxFnc.hint                = nullptr;\n    pnodeFnc->sxFnc.hintOffset          = 0;\n    pnodeFnc->sxFnc.hintLength          = 0;\n    pnodeFnc->sxFnc.isNameIdentifierRef = true;\n    pnodeFnc->sxFnc.nestedFuncEscapes   = false;\n    pnodeFnc->sxFnc.pnodeName           = nullptr;\n    pnodeFnc->sxFnc.pnodeScopes         = nullptr;\n    pnodeFnc->sxFnc.pnodeParams         = nullptr;\n    pnodeFnc->sxFnc.pnodeVars           = nullptr;\n    pnodeFnc->sxFnc.pnodeBody           = nullptr;\n    pnodeFnc->sxFnc.nestedCount         = 0;\n    pnodeFnc->sxFnc.pnodeNext           = nullptr;\n    pnodeFnc->sxFnc.pnodeRest           = nullptr;\n    pnodeFnc->sxFnc.deferredStub        = nullptr;\n    pnodeFnc->sxFnc.funcInfo            = nullptr;\n\n#ifdef DBG\n    pnodeFnc->sxFnc.deferredParseNextFunctionId = *(this->m_nextFunctionId);\n#endif\n\n    AppendFunctionToScopeList(true, pnodeFnc);\n\n    if (m_nextFunctionId)\n    {\n        (*m_nextFunctionId)++;\n    }\n\n    \/\/ Update the count of functions nested in the current parent.\n    if (m_pnestedCount)\n    {\n        (*m_pnestedCount)++;\n    }\n\n    if (!buildAST)\n    {\n        return NULL;\n    }\n\n    if (m_pscan->IchMinTok() >= m_pscan->IchMinLine())\n    {\n        \/\/ In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse\n        pnodeFnc->sxFnc.columnNumber = m_pscan->IchMinTok() - m_pscan->IchMinLine();\n    }\n    else if (m_currentNodeFunc)\n    {\n        \/\/ For the first line after defer parse, compute the column relative to the column number\n        \/\/ of the lexically parent function.\n        ULONG offsetFromCurrentFunction = m_pscan->IchMinTok() - m_currentNodeFunc->ichMin;\n        pnodeFnc->sxFnc.columnNumber = m_currentNodeFunc->sxFnc.columnNumber + offsetFromCurrentFunction;\n    }\n    else\n    {\n        \/\/ if there is no current function, lets give a default of 0.\n        pnodeFnc->sxFnc.columnNumber = 0;\n    }\n\n    int32 * pAstSizeSave = m_pCurrentAstSize;\n    m_pCurrentAstSize = &(pnodeFnc->sxFnc.astSize);\n\n    \/\/ Make this the current function.\n    ParseNodePtr pnodeFncSave = m_currentNodeFunc;\n    m_currentNodeFunc = pnodeFnc;\n\n    ParseNodePtr argsId = nullptr;\n    ParseNodePtr *lastNodeRef = nullptr;\n    ParseNodePtr pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);\n\n    if (extends)\n    {\n        \/\/ constructor(...args) { super(...args); }\n        \/\/             ^^^^^^^\n        ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;\n        m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;\n\n        IdentPtr pidargs = m_phtbl->PidHashNameLen(_u(\"args\"), sizeof(\"args\") - 1);\n        ParseNodePtr pnodeT = CreateVarDeclNode(pidargs, STFormal);\n        pnodeT->sxVar.sym->SetIsNonSimpleParameter(true);\n        pnodeFnc->sxFnc.pnodeRest = pnodeT;\n        PidRefStack *ref = this->PushPidRef(pidargs);\n\n        argsId = CreateNameNode(pidargs, pnodeFnc->ichMin, pnodeFnc->ichLim);\n\n        argsId->sxPid.symRef = ref->GetSymRef();\n        m_ppnodeVar = ppnodeVarSave;\n    }\n\n    ParseNodePtr pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);\n    pnodeBlock->sxBlock.pnodeScopes = pnodeInnerBlock;\n    pnodeFnc->sxFnc.pnodeBodyScope = pnodeInnerBlock;\n    pnodeFnc->sxFnc.pnodeScopes = pnodeBlock;\n\n    if (extends)\n    {\n        \/\/ constructor(...args) { super(...args); }\n        \/\/                        ^^^^^^^^^^^^^^^\n        Assert(argsId);\n        ParseNodePtr spreadArg = CreateUniNode(knopEllipsis, argsId, pnodeFnc->ichMin, pnodeFnc->ichLim);\n\n        ParseNodePtr superRef = CreateNodeWithScanner<knopSuper>();\n        pnodeFnc->sxFnc.SetHasSuperReference(TRUE);\n\n        ParseNodePtr callNode = CreateCallNode(knopCall, superRef, spreadArg);\n        callNode->sxCall.spreadArgCount = 1;\n        AddToNodeList(&pnodeFnc->sxFnc.pnodeBody, &lastNodeRef, callNode);\n    }\n\n    AddToNodeList(&pnodeFnc->sxFnc.pnodeBody, &lastNodeRef, CreateNodeWithScanner<knopEndCode>());\n\n    FinishParseBlock(pnodeInnerBlock);\n    FinishParseBlock(pnodeBlock);\n\n    m_currentNodeFunc = pnodeFncSave;\n    m_pCurrentAstSize = pAstSizeSave;\n\n    return pnodeFnc;\n}\n\ntemplate<bool buildAST>\nvoid Parser::ParseExpressionLambdaBody(ParseNodePtr pnodeLambda)\n{\n    ParseNodePtr *lastNodeRef = nullptr;\n\n    \/\/ The lambda body is a single expression, the result of which is the return value.\n    ParseNodePtr pnodeRet = nullptr;\n\n    if (buildAST)\n    {\n        pnodeRet = CreateNodeWithScanner<knopReturn>();\n        pnodeRet->grfpn |= PNodeFlags::fpnSyntheticNode;\n        pnodeLambda->sxFnc.pnodeScopes->sxBlock.pnodeStmt = pnodeRet;\n    }\n\n    ParseNodePtr result = ParseExpr<buildAST>(koplAsg, nullptr, TRUE, FALSE, nullptr);\n\n    if (buildAST)\n    {\n        pnodeRet->sxReturn.pnodeExpr = result;\n\n        pnodeRet->ichMin = pnodeRet->sxReturn.pnodeExpr->ichMin;\n        pnodeRet->ichLim = pnodeRet->sxReturn.pnodeExpr->ichLim;\n\n        \/\/ Pushing a statement node with PushStmt<>() normally does this initialization\n        \/\/ but do it here manually since we know there is no outer statement node.\n        pnodeRet->sxStmt.grfnop = 0;\n        pnodeRet->sxStmt.pnodeOuter = nullptr;\n\n        pnodeLambda->ichLim = pnodeRet->ichLim;\n        pnodeLambda->sxFnc.cbLim = m_pscan->IecpLimTokPrevious();\n        pnodeLambda->sxFnc.pnodeScopes->ichLim = pnodeRet->ichLim;\n\n        pnodeLambda->sxFnc.pnodeBody = nullptr;\n        AddToNodeList(&pnodeLambda->sxFnc.pnodeBody, &lastNodeRef, pnodeLambda->sxFnc.pnodeScopes);\n\n        \/\/ Append an EndCode node.\n        ParseNodePtr end = CreateNodeWithScanner<knopEndCode>(pnodeRet->ichLim);\n        end->ichLim = end->ichMin; \/\/ make end code zero width at the immediate end of lambda body\n        AddToNodeList(&pnodeLambda->sxFnc.pnodeBody, &lastNodeRef, end);\n\n        \/\/ Lambda's do not have arguments binding\n        pnodeLambda->sxFnc.SetHasReferenceableBuiltInArguments(false);\n    }\n}\n\nvoid Parser::CheckStrictFormalParameters()\n{\n    if (m_token.tk == tkID)\n    {\n        \/\/ single parameter arrow function case\n        IdentPtr pid = m_token.GetIdentifier(m_phtbl);\n        CheckStrictModeEvalArgumentsUsage(pid);\n        return;\n    }\n\n    Assert(m_token.tk == tkLParen);\n    m_pscan->ScanForcingPid();\n\n    if (m_token.tk != tkRParen)\n    {\n        SList<IdentPtr> formals(&m_nodeAllocator);\n        for (;;)\n        {\n            if (m_token.tk != tkID)\n            {\n                IdentifierExpectedError(m_token);\n            }\n\n            IdentPtr pid = m_token.GetIdentifier(m_phtbl);\n            CheckStrictModeEvalArgumentsUsage(pid);\n            if (formals.Has(pid))\n            {\n                Error(ERRES5ArgSame, m_pscan->IchMinTok(), m_pscan->IchLimTok());\n            }\n            else\n            {\n                formals.Prepend(pid);\n            }\n\n            m_pscan->Scan();\n\n            if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())\n            {\n                m_pscan->Scan();\n                \/\/ We can avoid building the AST since we are just checking the default expression.\n                ParseNodePtr pnodeInit = ParseExpr<false>(koplCma);\n                Assert(pnodeInit == nullptr);\n            }\n\n            if (m_token.tk != tkComma)\n            {\n                break;\n            }\n            m_pscan->ScanForcingPid();\n\n            if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())\n            {\n                break;\n            }\n        }\n    }\n    Assert(m_token.tk == tkRParen);\n}\n\nvoid Parser::FinishFncNode(ParseNodePtr pnodeFnc)\n{\n    AnalysisAssert(pnodeFnc);\n\n    \/\/ Finish the AST for a function that was deferred earlier, but which we decided\n    \/\/ to finish after the fact.\n    \/\/ We assume that the name(s) and arg(s) have already got parse nodes, so\n    \/\/ we just have to do the function body.\n\n    \/\/ Save the current next function Id, and resume from the old one.\n    Js::LocalFunctionId * nextFunctionIdSave = m_nextFunctionId;\n    Js::LocalFunctionId tempNextFunctionId = pnodeFnc->sxFnc.functionId + 1;\n    this->m_nextFunctionId = &tempNextFunctionId;\n\n    ParseNodePtr pnodeFncSave = m_currentNodeFunc;\n    uint *pnestedCountSave = m_pnestedCount;\n    int32* pAstSizeSave = m_pCurrentAstSize;\n\n    m_currentNodeFunc = pnodeFnc;\n    m_pCurrentAstSize = & (pnodeFnc->sxFnc.astSize);\n\n    pnodeFnc->sxFnc.nestedCount = 0;\n    m_pnestedCount = &pnodeFnc->sxFnc.nestedCount;\n\n    \/\/ Cue up the parser to the start of the function body.\n    if (pnodeFnc->sxFnc.pnodeName)\n    {\n        \/\/ Skip the name(s).\n        m_pscan->SetCurrentCharacter(pnodeFnc->sxFnc.pnodeName->ichLim, pnodeFnc->sxFnc.lineNumber);\n    }\n    else\n    {\n        m_pscan->SetCurrentCharacter(pnodeFnc->ichMin, pnodeFnc->sxFnc.lineNumber);\n        if (pnodeFnc->sxFnc.IsAccessor())\n        {\n            \/\/ Getter\/setter. The node text starts with the name, so eat that.\n            m_pscan->ScanNoKeywords();\n        }\n        else\n        {\n            \/\/ Anonymous function. Skip any leading \"(\"'s and \"function\".\n            for (;;)\n            {\n                m_pscan->Scan();\n                if (m_token.tk == tkFUNCTION)\n                {\n                    break;\n                }\n                Assert(m_token.tk == tkLParen || m_token.tk == tkStar);\n            }\n        }\n    }\n\n    \/\/ switch scanner to treat 'yield' as keyword in generator functions\n    \/\/ or as an identifier in non-generator functions\n    bool fPreviousYieldIsKeyword = m_pscan->SetYieldIsKeyword(pnodeFnc && pnodeFnc->sxFnc.IsGenerator());\n\n    bool fPreviousAwaitIsKeyword = m_pscan->SetAwaitIsKeyword(pnodeFnc && pnodeFnc->sxFnc.IsAsync());\n\n    \/\/ Skip the arg list.\n    m_pscan->ScanNoKeywords();\n    if (m_token.tk == tkStar)\n    {\n        Assert(pnodeFnc->sxFnc.IsGenerator());\n        m_pscan->ScanNoKeywords();\n    }\n    Assert(m_token.tk == tkLParen);\n    m_pscan->ScanNoKeywords();\n\n    if (m_token.tk != tkRParen)\n    {\n        for (;;)\n        {\n            if (m_token.tk == tkEllipsis)\n            {\n                m_pscan->ScanNoKeywords();\n            }\n\n            if (m_token.tk == tkID)\n            {\n                m_pscan->ScanNoKeywords();\n\n                if (m_token.tk == tkAsg)\n                {\n                    \/\/ Eat the default expression\n                    m_pscan->Scan();\n                    ParseExpr<false>(koplCma);\n                }\n            }\n            else if (IsPossiblePatternStart())\n            {\n                ParseDestructuredLiteralWithScopeSave(tkLET, false\/*isDecl*\/, false \/*topLevel*\/);\n            }\n            else\n            {\n                AssertMsg(false, \"Unexpected identifier prefix while fast-scanning formals\");\n            }\n\n            if (m_token.tk != tkComma)\n            {\n                break;\n            }\n            m_pscan->ScanNoKeywords();\n\n            if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())\n            {\n                break;\n            }\n        }\n    }\n\n    if (m_token.tk == tkRParen) \/\/ This might be false due to a lambda => token.\n    {\n        m_pscan->Scan();\n    }\n\n    \/\/ Finish the function body.\n    {\n        \/\/ Note that in IE8- modes, surrounding parentheses are considered part of function body. e.g. \"( function x(){} )\".\n        \/\/ We lose that context here since we start from middle of function body. So save and restore source range info.\n        ParseNodePtr* lastNodeRef = NULL;\n        const charcount_t ichLim = pnodeFnc->ichLim;\n        const size_t cbLim = pnodeFnc->sxFnc.cbLim;\n        this->FinishFncDecl(pnodeFnc, NULL, lastNodeRef);\n\n#if DBG\n        \/\/ The pnode extent may not match the original extent.\n        \/\/ We expect this to happen only when there are trailing \")\"'s.\n        \/\/ Consume them and make sure that's all we've got.\n        if (pnodeFnc->ichLim != ichLim)\n        {\n            Assert(pnodeFnc->ichLim < ichLim);\n            m_pscan->SetCurrentCharacter(pnodeFnc->ichLim);\n            while (m_pscan->IchLimTok() != ichLim)\n            {\n                m_pscan->ScanNoKeywords();\n                Assert(m_token.tk == tkRParen);\n            }\n        }\n#endif\n        pnodeFnc->ichLim = ichLim;\n        pnodeFnc->sxFnc.cbLim = cbLim;\n    }\n\n    m_currentNodeFunc = pnodeFncSave;\n    m_pCurrentAstSize = pAstSizeSave;\n    m_pnestedCount = pnestedCountSave;\n    Assert(m_pnestedCount);\n\n    Assert(tempNextFunctionId == pnodeFnc->sxFnc.deferredParseNextFunctionId);\n    this->m_nextFunctionId = nextFunctionIdSave;\n\n    m_pscan->SetYieldIsKeyword(fPreviousYieldIsKeyword);\n    m_pscan->SetAwaitIsKeyword(fPreviousAwaitIsKeyword);\n}\n\nvoid Parser::FinishFncDecl(ParseNodePtr pnodeFnc, LPCOLESTR pNameHint, ParseNodePtr *lastNodeRef, bool skipCurlyBraces)\n{\n    LPCOLESTR name = NULL;\n    JS_ETW(int32 startAstSize = *m_pCurrentAstSize);\n    if (IS_JS_ETW(EventEnabledJSCRIPT_PARSE_METHOD_START()) || PHASE_TRACE1(Js::DeferParsePhase))\n    {\n        name = GetFunctionName(pnodeFnc, pNameHint);\n        m_functionBody = NULL;  \/\/ for nested functions we do not want to get the name of the top deferred function return name;\n        JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->sxFnc.functionId, 0, m_parseType, name));\n        OUTPUT_TRACE(Js::DeferParsePhase, _u(\"Parsing function (%s) : %s (%d)\\n\"), GetParseType(), name, pnodeFnc->sxFnc.functionId);\n    }\n\n    JS_ETW(EventWriteJSCRIPT_PARSE_FUNC(GetScriptContext(), pnodeFnc->sxFnc.functionId, \/*Undefer*\/FALSE));\n\n\n    \/\/ Do the work of creating an AST for a function body.\n    \/\/ This is common to the un-deferred case and the case in which we un-defer late in the game.\n\n    Assert(pnodeFnc->nop == knopFncDecl);\n\n    if (!skipCurlyBraces)\n    {\n        ChkCurTok(tkLCurly, ERRnoLcurly);\n    }\n\n    ParseStmtList<true>(&pnodeFnc->sxFnc.pnodeBody, &lastNodeRef, SM_OnFunctionCode, true \/* isSourceElementList *\/);\n    \/\/ Append an EndCode node.\n    AddToNodeList(&pnodeFnc->sxFnc.pnodeBody, &lastNodeRef, CreateNodeWithScanner<knopEndCode>());\n\n    if (!skipCurlyBraces)\n    {\n        ChkCurTokNoScan(tkRCurly, ERRnoRcurly);\n    }\n\n    pnodeFnc->ichLim = m_pscan->IchLimTok();\n    pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();\n\n#ifdef ENABLE_JS_ETW\n    int32 astSize = *m_pCurrentAstSize - startAstSize;\n    EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->sxFnc.functionId, astSize, m_parseType, name);\n#endif\n}\n\nvoid Parser::AddArgumentsNodeToVars(ParseNodePtr pnodeFnc)\n{\n    if((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenByDecl) || pnodeFnc->sxFnc.IsLambda())\n    {\n        \/\/ In any of the following cases, there is no way to reference the built-in 'arguments' variable (in the order of checks\n        \/\/ above):\n        \/\/     - A function parameter is named 'arguments'\n        \/\/     - There is a nested function declaration (or named function expression in compat modes) named 'arguments'\n        \/\/     - In compat modes, the function is named arguments, does not have a var declaration named 'arguments', and does\n        \/\/       not call 'eval'\n        pnodeFnc->sxFnc.SetHasReferenceableBuiltInArguments(false);\n    }\n    else\n    {\n        ParseNodePtr argNode = nullptr;\n        if(m_ppnodeVar == &pnodeFnc->sxFnc.pnodeVars)\n        {\n            \/\/ There were no var declarations in the function\n            argNode = CreateVarDeclNode(wellKnownPropertyPids.arguments, STVariable, true, pnodeFnc);\n        }\n        else\n        {\n            \/\/ There were var declarations in the function, so insert an 'arguments' local at the beginning of the var list.\n            \/\/ This is done because the built-in 'arguments' variable overrides an 'arguments' var declaration until the\n            \/\/ 'arguments' variable is assigned. By putting our built-in var declaration at the beginning, an 'arguments'\n            \/\/ identifier will resolve to this symbol, which has the fpnArguments flag set, and will be the built-in arguments\n            \/\/ object until it is replaced with something else.\n            ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;\n            m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;\n            argNode = CreateVarDeclNode(wellKnownPropertyPids.arguments, STVariable, true, pnodeFnc);\n            m_ppnodeVar = ppnodeVarSave;\n        }\n\n        Assert(argNode);\n        argNode->grfpn |= PNodeFlags::fpnArguments;\n\n        \/\/ When a function definition with the name arguments occurs in the body the declaration of the arguments symbol will\n        \/\/ be set to that function declaration. We should change it to arguments declaration from the param scope as it may be\n        \/\/ used in the param scope and we have to load the arguments.\n        argNode->sxVar.sym->SetDecl(argNode);\n\n        pnodeFnc->sxFnc.SetHasReferenceableBuiltInArguments(true);\n    }\n}\n\nLPCOLESTR Parser::GetFunctionName(ParseNodePtr pnodeFnc, LPCOLESTR pNameHint)\n{\n    LPCOLESTR name = nullptr;\n    if(pnodeFnc->sxFnc.pnodeName != nullptr && knopVarDecl == pnodeFnc->sxFnc.pnodeName->nop)\n    {\n        name = pnodeFnc->sxFnc.pnodeName->sxVar.pid->Psz();\n    }\n    if(name == nullptr && pNameHint != nullptr)\n    {\n        name = pNameHint;\n    }\n    if(name == nullptr && m_functionBody != nullptr)\n    {\n        name = m_functionBody->GetExternalDisplayName();\n    }\n    else if(name == nullptr)\n    {\n        name = Js::Constants::AnonymousFunction;\n    }\n    return name;\n}\n\nIdentPtr Parser::ParseClassPropertyName(IdentPtr * pidHint)\n{\n    if (m_token.tk == tkID || m_token.tk == tkStrCon || m_token.IsReservedWord())\n    {\n        IdentPtr pid;\n        if (m_token.tk == tkStrCon)\n        {\n            if (m_pscan->IsOctOrLeadingZeroOnLastTKNumber())\n            {\n                Error(ERRES5NoOctal);\n            }\n\n            pid = m_token.GetStr();\n        }\n        else\n        {\n            pid = m_token.GetIdentifier(m_phtbl);\n        }\n        *pidHint = pid;\n        return pid;\n    }\n    else if (m_token.tk == tkIntCon)\n    {\n        if (m_pscan->IsOctOrLeadingZeroOnLastTKNumber())\n        {\n            Error(ERRES5NoOctal);\n        }\n\n        return m_pscan->PidFromLong(m_token.GetLong());\n    }\n    else if (m_token.tk == tkFltCon)\n    {\n        if (m_pscan->IsOctOrLeadingZeroOnLastTKNumber())\n        {\n            Error(ERRES5NoOctal);\n        }\n\n        return m_pscan->PidFromDbl(m_token.GetDouble());\n    }\n\n    Error(ERRnoMemberIdent);\n}\n\nLPCOLESTR Parser::ConstructFinalHintNode(IdentPtr pClassName, IdentPtr pMemberName, IdentPtr pGetSet, bool isStatic, uint32* nameLength, uint32* pShortNameOffset, bool isComputedName, LPCOLESTR pMemberNameHint)\n{\n    if ((pMemberName == nullptr && !isComputedName) ||\n        (pMemberNameHint == nullptr && isComputedName) ||\n        !CONFIG_FLAG(UseFullName))\n    {\n        return nullptr;\n    }\n\n    LPCOLESTR pFinalName = isComputedName? pMemberNameHint : pMemberName->Psz();\n    uint32 fullNameHintLength = 0;\n    uint32 shortNameOffset = 0;\n    if (!isStatic)\n    {\n        \/\/ Add prototype.\n        pFinalName = AppendNameHints(wellKnownPropertyPids.prototype, pFinalName, &fullNameHintLength, &shortNameOffset);\n    }\n\n    if (pClassName)\n    {\n        uint32 classNameOffset = 0;\n        pFinalName = AppendNameHints(pClassName, pFinalName, &fullNameHintLength, &classNameOffset);\n        shortNameOffset += classNameOffset;\n    }\n\n    if (pGetSet)\n    {\n        if (m_scriptContext->GetConfig()->IsES6FunctionNameEnabled())\n        {\n            \/\/ displays as get\/set prototype.funcname\n            uint32 getSetOffset = 0;\n            pFinalName = AppendNameHints(pGetSet, pFinalName, &fullNameHintLength, &getSetOffset, true);\n            shortNameOffset += getSetOffset;\n        }\n        else\n        {\n            pFinalName = AppendNameHints(pFinalName, pGetSet, &fullNameHintLength, &shortNameOffset);\n        }\n\n    }\n    if (fullNameHintLength > *nameLength)\n    {\n        *nameLength = fullNameHintLength;\n    }\n\n    if (shortNameOffset > *pShortNameOffset)\n    {\n        *pShortNameOffset = shortNameOffset;\n    }\n\n    return pFinalName;\n}\n\nclass AutoParsingSuperRestrictionStateRestorer\n{\npublic:\n    AutoParsingSuperRestrictionStateRestorer(Parser* parser) : m_parser(parser)\n    {\n        AssertMsg(this->m_parser != nullptr, \"This just should not happen\");\n        this->m_originalParsingSuperRestrictionState = this->m_parser->m_parsingSuperRestrictionState;\n    }\n    ~AutoParsingSuperRestrictionStateRestorer()\n    {\n        AssertMsg(this->m_parser != nullptr, \"This just should not happen\");\n        this->m_parser->m_parsingSuperRestrictionState = m_originalParsingSuperRestrictionState;\n    }\nprivate:\n    Parser* m_parser;\n    int m_originalParsingSuperRestrictionState;\n};\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseClassDecl(BOOL isDeclaration, LPCOLESTR pNameHint, uint32 *pHintLength, uint32 *pShortNameOffset)\n{\n    bool hasConstructor = false;\n    bool hasExtends = false;\n    IdentPtr name = nullptr;\n    ParseNodePtr pnodeName = nullptr;\n    ParseNodePtr pnodeConstructor = nullptr;\n    ParseNodePtr pnodeExtends = nullptr;\n    ParseNodePtr pnodeMembers = nullptr;\n    ParseNodePtr *lastMemberNodeRef = nullptr;\n    ParseNodePtr pnodeStaticMembers = nullptr;\n    ParseNodePtr *lastStaticMemberNodeRef = nullptr;\n    uint32 nameHintLength = pHintLength ? *pHintLength : 0;\n    uint32 nameHintOffset = pShortNameOffset ? *pShortNameOffset : 0;\n\n    ArenaAllocator tempAllocator(_u(\"ClassMemberNames\"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);\n\n    ParseNodePtr pnodeClass = nullptr;\n    if (buildAST)\n    {\n        pnodeClass = CreateNode(knopClassDecl);\n\n        CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ClassCount, m_scriptContext);\n    }\n\n    m_pscan->Scan();\n    if (m_token.tk == tkID)\n    {\n        name = m_token.GetIdentifier(m_phtbl);\n        m_pscan->Scan();\n    }\n    else if (isDeclaration)\n    {\n        IdentifierExpectedError(m_token);\n    }\n\n    if (isDeclaration && name == wellKnownPropertyPids.arguments && GetCurrentBlockInfo()->pnodeBlock->sxBlock.blockType == Function)\n    {\n        GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;\n    }\n\n    BOOL strictSave = m_fUseStrictMode;\n    m_fUseStrictMode = TRUE;\n\n    ParseNodePtr pnodeDeclName = nullptr;\n    if (isDeclaration)\n    {\n        pnodeDeclName = CreateBlockScopedDeclNode(name, knopLetDecl);\n    }\n\n    ParseNodePtr *ppnodeScopeSave = nullptr;\n    ParseNodePtr *ppnodeExprScopeSave = nullptr;\n\n    ParseNodePtr pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);\n    if (buildAST)\n    {\n        PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);\n        pnodeClass->sxClass.pnodeBlock = pnodeBlock;\n    }\n\n    if (name)\n    {\n        pnodeName = CreateBlockScopedDeclNode(name, knopConstDecl);\n    }\n\n    if (m_token.tk == tkEXTENDS)\n    {\n        m_pscan->Scan();\n        pnodeExtends = ParseExpr<buildAST>();\n        hasExtends = true;\n    }\n\n    if (m_token.tk != tkLCurly)\n    {\n        Error(ERRnoLcurly);\n    }\n\n    OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u(\"Parsing class (%s) : %s\\n\"), GetParseType(), name ? name->Psz() : _u(\"anonymous class\"));\n\n    RestorePoint beginClass;\n    m_pscan->Capture(&beginClass);\n\n    m_pscan->ScanForcingPid();\n\n    IdentPtr pClassNamePid = pnodeName ? pnodeName->sxVar.pid : nullptr;\n\n    for (;;)\n    {\n        if (m_token.tk == tkSColon)\n        {\n            m_pscan->ScanForcingPid();\n            continue;\n        }\n        if (m_token.tk == tkRCurly)\n        {\n            break;\n        }\n\n        bool isStatic = m_token.tk == tkSTATIC;\n        if (isStatic)\n        {\n            m_pscan->ScanForcingPid();\n        }\n\n        ushort fncDeclFlags = fFncNoName | fFncMethod | fFncClassMember;\n        charcount_t ichMin = 0;\n        size_t iecpMin = 0;\n        ParseNodePtr pnodeMemberName = nullptr;\n        IdentPtr pidHint = nullptr;\n        IdentPtr memberPid = nullptr;\n        LPCOLESTR pMemberNameHint = nullptr;\n        uint32     memberNameHintLength = 0;\n        uint32     memberNameOffset = 0;\n        bool isComputedName = false;\n        bool isAsyncMethod = false;\n\n        if (m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())\n        {\n            RestorePoint parsedAsync;\n            m_pscan->Capture(&parsedAsync);\n            ichMin = m_pscan->IchMinTok();\n            iecpMin = m_pscan->IecpMinTok();\n\n            m_pscan->Scan();\n            if (m_token.tk == tkLParen || m_pscan->FHadNewLine())\n            {\n                m_pscan->SeekTo(parsedAsync);\n            }\n            else\n            {\n                isAsyncMethod = true;\n            }\n        }\n\n        bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&\n                           m_token.tk == tkStar;\n        if (isGenerator)\n        {\n            fncDeclFlags |= fFncGenerator;\n            m_pscan->ScanForcingPid();\n        }\n\n\n        if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())\n        {\n            \/\/ Computed member name: [expr] () { }\n            LPCOLESTR emptyHint = nullptr;\n            ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);\n            isComputedName = true;\n        }\n        else \/\/ not computed name\n        {\n            memberPid = this->ParseClassPropertyName(&pidHint);\n            if (pidHint)\n            {\n                pMemberNameHint = pidHint->Psz();\n                memberNameHintLength = pidHint->Cch();\n            }\n        }\n\n        if (buildAST && memberPid)\n        {\n            pnodeMemberName = CreateStrNodeWithScanner(memberPid);\n        }\n\n        if (!isStatic && memberPid == wellKnownPropertyPids.constructor)\n        {\n            if (hasConstructor || isAsyncMethod)\n            {\n                Error(ERRsyntax);\n            }\n            hasConstructor = true;\n            LPCOLESTR pConstructorName = nullptr;\n            uint32  constructorNameLength = 0;\n            uint32  constructorShortNameHintOffset = 0;\n            if (pnodeName && pnodeName->sxVar.pid)\n            {\n                pConstructorName = pnodeName->sxVar.pid->Psz();\n                constructorNameLength = pnodeName->sxVar.pid->Cch();\n            }\n            else\n            {\n                pConstructorName = pNameHint;\n                constructorNameLength = nameHintLength;\n                constructorShortNameHintOffset = nameHintOffset;\n            }\n\n            {\n                AutoParsingSuperRestrictionStateRestorer restorer(this);\n                this->m_parsingSuperRestrictionState = hasExtends ? ParsingSuperRestrictionState_SuperCallAndPropertyAllowed : ParsingSuperRestrictionState_SuperPropertyAllowed;\n                pnodeConstructor = ParseFncDecl<buildAST>(fncDeclFlags, pConstructorName, \/* needsPIDOnRCurlyScan *\/ true, \/* resetParsingSuperRestrictionState = *\/false);\n            }\n\n            if (pnodeConstructor->sxFnc.IsGenerator())\n            {\n                Error(ERRConstructorCannotBeGenerator);\n            }\n\n            Assert(constructorNameLength >= constructorShortNameHintOffset);\n            \/\/ The constructor function will get the same name as class.\n            pnodeConstructor->sxFnc.hint = pConstructorName;\n            pnodeConstructor->sxFnc.hintLength = constructorNameLength;\n            pnodeConstructor->sxFnc.hintOffset = constructorShortNameHintOffset;\n            pnodeConstructor->sxFnc.pid = pnodeName && pnodeName->sxVar.pid ? pnodeName->sxVar.pid : wellKnownPropertyPids.constructor;\n            pnodeConstructor->sxFnc.SetIsClassConstructor(TRUE);\n            pnodeConstructor->sxFnc.SetHasNonThisStmt();\n            pnodeConstructor->sxFnc.SetIsBaseClassConstructor(pnodeExtends == nullptr);\n        }\n        else\n        {\n            ParseNodePtr pnodeMember = nullptr;\n\n            bool isMemberNamedGetOrSet = false;\n            RestorePoint beginMethodName;\n            m_pscan->Capture(&beginMethodName);\n            if (memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set)\n            {\n                m_pscan->ScanForcingPid();\n            }\n            if (m_token.tk == tkLParen)\n            {\n                m_pscan->SeekTo(beginMethodName);\n                isMemberNamedGetOrSet = true;\n            }\n\n            if ((memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set) && !isMemberNamedGetOrSet)\n            {\n                bool isGetter = (memberPid == wellKnownPropertyPids.get);\n\n                if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())\n                {\n                    \/\/ Computed get\/set member name: get|set [expr] () { }\n                    LPCOLESTR emptyHint = nullptr;\n                    ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);\n                    isComputedName = true;\n                }\n                else \/\/ not computed name\n                {\n                    memberPid = this->ParseClassPropertyName(&pidHint);\n                }\n\n                if ((isStatic ? (memberPid == wellKnownPropertyPids.prototype) : (memberPid == wellKnownPropertyPids.constructor)) || isAsyncMethod)\n                {\n                    Error(ERRsyntax);\n                }\n                if (buildAST && memberPid && !isComputedName)\n                {\n                    pnodeMemberName = CreateStrNodeWithScanner(memberPid);\n                }\n\n                ParseNodePtr pnodeFnc = nullptr;\n                {\n                    AutoParsingSuperRestrictionStateRestorer restorer(this);\n                    this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;\n                    pnodeFnc = ParseFncDecl<buildAST>(fncDeclFlags | (isGetter ? fFncNoArg : fFncOneArg),\n                        pidHint ? pidHint->Psz() : nullptr, \/* needsPIDOnRCurlyScan *\/ true,\n                        \/* resetParsingSuperRestrictionState *\/false);\n                }\n\n                pnodeFnc->sxFnc.SetIsStaticMember(isStatic);\n\n                if (buildAST)\n                {\n                    pnodeFnc->sxFnc.SetIsAccessor();\n                    pnodeMember = CreateBinNode(isGetter ? knopGetMember : knopSetMember, pnodeMemberName, pnodeFnc);\n                    pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint,\n                        isGetter ? wellKnownPropertyPids.get : wellKnownPropertyPids.set, isStatic,\n                        &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);\n                }\n            }\n            else\n            {\n                if (isStatic && (memberPid == wellKnownPropertyPids.prototype))\n                {\n                    Error(ERRsyntax);\n                }\n\n                ParseNodePtr pnodeFnc = nullptr;\n                {\n                    AutoParsingSuperRestrictionStateRestorer restorer(this);\n                    this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;\n\n                    if (isAsyncMethod)\n                    {\n                        fncDeclFlags |= fFncAsync;\n                    }\n                    pnodeFnc = ParseFncDecl<buildAST>(fncDeclFlags, pidHint ? pidHint->Psz() : nullptr, \/* needsPIDOnRCurlyScan *\/ true, \/* resetParsingSuperRestrictionState *\/false);\n                    if (isAsyncMethod)\n                    {\n                        pnodeFnc->sxFnc.cbMin = iecpMin;\n                        pnodeFnc->ichMin = ichMin;\n                    }\n                }\n                pnodeFnc->sxFnc.SetIsStaticMember(isStatic);\n\n                if (buildAST)\n                {\n                    pnodeMember = CreateBinNode(knopMember, pnodeMemberName, pnodeFnc);\n                    pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint, nullptr \/*pgetset*\/, isStatic, &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);\n                }\n            }\n\n            if (buildAST)\n            {\n                Assert(memberNameHintLength >= memberNameOffset);\n                pnodeMember->sxBin.pnode2->sxFnc.hint = pMemberNameHint; \/\/ Fully qualified name\n                pnodeMember->sxBin.pnode2->sxFnc.hintLength = memberNameHintLength;\n                pnodeMember->sxBin.pnode2->sxFnc.hintOffset = memberNameOffset;\n                pnodeMember->sxBin.pnode2->sxFnc.pid = memberPid; \/\/ Short name\n\n                AddToNodeList(isStatic ? &pnodeStaticMembers : &pnodeMembers, isStatic ? &lastStaticMemberNodeRef : &lastMemberNodeRef, pnodeMember);\n            }\n        }\n    }\n\n    if (buildAST)\n    {\n        pnodeClass->ichLim = m_pscan->IchLimTok();\n    }\n\n    if (!hasConstructor)\n    {\n        OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u(\"Generating constructor (%s) : %s\\n\"), GetParseType(), name ? name->Psz() : _u(\"anonymous class\"));\n\n        RestorePoint endClass;\n        m_pscan->Capture(&endClass);\n        m_pscan->SeekTo(beginClass);\n\n        pnodeConstructor = GenerateEmptyConstructor<buildAST>(pnodeExtends != nullptr);\n        if (buildAST)\n        {\n            if (pClassNamePid)\n            {\n                pnodeConstructor->sxFnc.hint = pClassNamePid->Psz();\n                pnodeConstructor->sxFnc.hintLength = pClassNamePid->Cch();\n                pnodeConstructor->sxFnc.hintOffset = 0;\n            }\n            else\n            {\n                Assert(nameHintLength >= nameHintOffset);\n                pnodeConstructor->sxFnc.hint = pNameHint;\n                pnodeConstructor->sxFnc.hintLength = nameHintLength;\n                pnodeConstructor->sxFnc.hintOffset = nameHintOffset;\n            }\n            pnodeConstructor->sxFnc.pid = pClassNamePid;\n        }\n\n        m_pscan->SeekTo(endClass);\n    }\n\n    if (buildAST)\n    {\n        pnodeConstructor->sxFnc.cbMin = pnodeClass->ichMin;\n        pnodeConstructor->sxFnc.cbLim = pnodeClass->ichLim;\n        pnodeConstructor->ichMin = pnodeClass->ichMin;\n        pnodeConstructor->ichLim = pnodeClass->ichLim;\n\n        PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);\n\n        pnodeClass->sxClass.pnodeDeclName = pnodeDeclName;\n        pnodeClass->sxClass.pnodeName = pnodeName;\n        pnodeClass->sxClass.pnodeConstructor = pnodeConstructor;\n        pnodeClass->sxClass.pnodeExtends = pnodeExtends;\n        pnodeClass->sxClass.pnodeMembers = pnodeMembers;\n        pnodeClass->sxClass.pnodeStaticMembers = pnodeStaticMembers;\n        pnodeClass->sxClass.isDefaultModuleExport = false;\n    }\n    FinishParseBlock(pnodeBlock);\n\n    m_fUseStrictMode = strictSave;\n\n    m_pscan->Scan();\n\n    return pnodeClass;\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseStringTemplateDecl(ParseNodePtr pnodeTagFnc)\n{\n    ParseNodePtr pnodeStringLiterals = nullptr;\n    ParseNodePtr* lastStringLiteralNodeRef = nullptr;\n    ParseNodePtr pnodeRawStringLiterals = nullptr;\n    ParseNodePtr* lastRawStringLiteralNodeRef = nullptr;\n    ParseNodePtr pnodeSubstitutionExpressions = nullptr;\n    ParseNodePtr* lastSubstitutionExpressionNodeRef = nullptr;\n    ParseNodePtr pnodeTagFncArgs = nullptr;\n    ParseNodePtr* lastTagFncArgNodeRef = nullptr;\n    ParseNodePtr stringLiteral = nullptr;\n    ParseNodePtr stringLiteralRaw = nullptr;\n    ParseNodePtr pnodeStringTemplate = nullptr;\n    bool templateClosed = false;\n    const bool isTagged = pnodeTagFnc != nullptr;\n    uint16 stringConstantCount = 0;\n    charcount_t ichMin = 0;\n\n    Assert(m_token.tk == tkStrTmplBasic || m_token.tk == tkStrTmplBegin);\n\n    if (buildAST)\n    {\n        pnodeStringTemplate = CreateNode(knopStrTemplate);\n        pnodeStringTemplate->sxStrTemplate.countStringLiterals = 0;\n        pnodeStringTemplate->sxStrTemplate.isTaggedTemplate = isTagged ? TRUE : FALSE;\n\n        \/\/ If this is a tagged string template, we need to start building the arg list for the call\n        if (isTagged)\n        {\n            ichMin = pnodeTagFnc->ichMin;\n            AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, pnodeStringTemplate);\n        }\n\n    }\n    CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(StringTemplatesCount, m_scriptContext);\n\n    OUTPUT_TRACE_DEBUGONLY(\n        Js::StringTemplateParsePhase,\n        _u(\"Starting to parse a string template (%s)...\\n\\tis tagged = %s\\n\"),\n        GetParseType(),\n        isTagged ? _u(\"true\") : _u(\"false (Raw and cooked strings will not differ!)\"));\n\n    \/\/ String template grammar\n    \/\/ `...`   Simple string template\n    \/\/ `...${  String template beginning\n    \/\/ }...${  String template middle\n    \/\/ }...`   String template end\n    while (!templateClosed)\n    {\n        \/\/ First, extract the string constant part - we always have one\n        if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())\n        {\n            Error(ERRES5NoOctal);\n        }\n\n        \/\/ We are not able to pass more than a ushort worth of arguments to the tag\n        \/\/ so use that as a logical limit on the number of string constant pieces.\n        if (stringConstantCount >= USHRT_MAX)\n        {\n            Error(ERRnoMemory);\n        }\n\n        \/\/ Keep track of the string literal count (must be the same for raw strings)\n        \/\/ We use this in code gen so we don't need to count the string literals list\n        stringConstantCount++;\n\n        \/\/ If we are not creating parse nodes, there is no need to create strings\n        if (buildAST)\n        {\n            stringLiteral = CreateStrNodeWithScanner(m_token.GetStr());\n\n            AddToNodeList(&pnodeStringLiterals, &lastStringLiteralNodeRef, stringLiteral);\n\n            \/\/ We only need to collect a raw string when we are going to pass the string template to a tag\n            if (isTagged)\n            {\n                \/\/ Make the scanner create a PID for the raw string constant for the preceding scan\n                IdentPtr pid = m_pscan->GetSecondaryBufferAsPid();\n\n                stringLiteralRaw = CreateStrNodeWithScanner(pid);\n\n                \/\/ Should have gotten a raw string literal above\n                AddToNodeList(&pnodeRawStringLiterals, &lastRawStringLiteralNodeRef, stringLiteralRaw);\n            }\n            else\n            {\n#if DBG\n                \/\/ Assign the raw string for debug tracing below\n                stringLiteralRaw = stringLiteral;\n#endif\n            }\n\n            OUTPUT_TRACE_DEBUGONLY(\n                Js::StringTemplateParsePhase,\n                _u(\"Parsed string constant: \\n\\tcooked = \\\"%s\\\" \\n\\traw = \\\"%s\\\" \\n\\tdiffer = %d\\n\"),\n                stringLiteral->sxPid.pid->Psz(),\n                stringLiteralRaw->sxPid.pid->Psz(),\n                stringLiteral->sxPid.pid->Psz() == stringLiteralRaw->sxPid.pid->Psz() ? 0 : 1);\n        }\n\n        switch (m_token.tk)\n        {\n        case tkStrTmplEnd:\n        case tkStrTmplBasic:\n            \/\/ We do not need to parse an expression for either the end or basic string template tokens\n            templateClosed = true;\n            break;\n        case tkStrTmplBegin:\n        case tkStrTmplMid:\n            {\n            \/\/ In the middle or begin string template token case, we need to parse an expression next\n            m_pscan->Scan();\n\n            \/\/ Parse the contents of the curly braces as an expression\n            ParseNodePtr expression = ParseExpr<buildAST>(0);\n\n            \/\/ After parsing expression, scan should leave us with an RCurly token.\n            \/\/ Use the NoScan version so we do not automatically perform a scan - we need to\n            \/\/ set the scan state before next scan but we don't want to set that state if\n            \/\/ the token is not as expected since we'll error in that case.\n            ChkCurTokNoScan(tkRCurly, ERRnoRcurly);\n\n            \/\/ Notify the scanner that it should scan for a middle or end string template token\n            m_pscan->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);\n            m_pscan->Scan();\n\n            if (buildAST)\n            {\n                \/\/ If we are going to call the tag function, add this expression into the list of args\n                if (isTagged)\n                {\n                    AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, expression);\n                }\n                else\n                {\n                    \/\/ Otherwise add it to the substitution expression list\n                    \/\/ TODO: Store the arguments and substitution expressions in a single list?\n                    AddToNodeList(&pnodeSubstitutionExpressions, &lastSubstitutionExpressionNodeRef, expression);\n                }\n            }\n\n            if (!(m_token.tk == tkStrTmplMid || m_token.tk == tkStrTmplEnd))\n            {\n                \/\/ Scan with ScanState ScanStateStringTemplateMiddleOrEnd should only return\n                \/\/ tkStrTmpMid\/End unless it is EOF or tkScanError\n                Assert(m_token.tk == tkEOF || m_token.tk == tkScanError);\n                Error(ERRsyntax);\n            }\n\n            OUTPUT_TRACE_DEBUGONLY(Js::StringTemplateParsePhase, _u(\"Parsed expression\\n\"));\n            }\n            break;\n        default:\n            Assert(false);\n            break;\n        }\n    }\n\n    if (buildAST)\n    {\n        pnodeStringTemplate->sxStrTemplate.pnodeStringLiterals = pnodeStringLiterals;\n        pnodeStringTemplate->sxStrTemplate.pnodeStringRawLiterals = pnodeRawStringLiterals;\n        pnodeStringTemplate->sxStrTemplate.pnodeSubstitutionExpressions = pnodeSubstitutionExpressions;\n        pnodeStringTemplate->sxStrTemplate.countStringLiterals = stringConstantCount;\n\n        \/\/ We should still have the last string literal.\n        \/\/ Use the char offset of the end of that constant as the end of the string template.\n        pnodeStringTemplate->ichLim = stringLiteral->ichLim;\n\n        \/\/ If this is a tagged template, we now have the argument list and can construct a call node\n        if (isTagged)\n        {\n            \/\/ Return the call node here and let the byte code generator Emit the string template automagically\n            pnodeStringTemplate = CreateCallNode(knopCall, pnodeTagFnc, pnodeTagFncArgs, ichMin, pnodeStringTemplate->ichLim);\n\n            \/\/ We need to set the arg count explicitly\n            pnodeStringTemplate->sxCall.argCount = stringConstantCount;\n        }\n    }\n\n    m_pscan->Scan();\n\n    return pnodeStringTemplate;\n}\n\nParseNodePtr Parser::CreateAsyncSpawnGenerator()\n{\n    ParseNodePtr pnodeFncGenerator = nullptr;\n\n    pnodeFncGenerator = CreateDummyFuncNode(false);\n    pnodeFncGenerator->sxFnc.functionId = (*m_nextFunctionId)++;\n\n    pnodeFncGenerator->sxFnc.cbMin = m_pscan->IecpMinTok();\n    pnodeFncGenerator->sxFnc.cbLim = m_pscan->IecpLimTok();\n    pnodeFncGenerator->sxFnc.lineNumber = m_pscan->LineCur();\n    pnodeFncGenerator->sxFnc.columnNumber = CalculateFunctionColumnNumber();\n    pnodeFncGenerator->sxFnc.SetNested(m_currentNodeFunc != nullptr);\n    pnodeFncGenerator->sxFnc.SetStrictMode(IsStrictMode());\n\n    pnodeFncGenerator->sxFnc.SetIsGenerator();\n    pnodeFncGenerator->sxFnc.SetIsLambda();\n    pnodeFncGenerator->sxFnc.scope = nullptr;\n\n    AppendFunctionToScopeList(false, pnodeFncGenerator);\n\n    return pnodeFncGenerator;\n}\n\nLPCOLESTR Parser::FormatPropertyString(LPCOLESTR propertyString, ParseNodePtr pNode, uint32 *fullNameHintLength, uint32 *pShortNameOffset)\n{\n    \/\/ propertyString could be null, such as 'this.foo' =\n    \/\/ propertyString could be empty, found in pattern as in (-1)[\"\"][(x = z)]\n\n    OpCode op = pNode->nop;\n    LPCOLESTR rightNode = nullptr;\n    if (propertyString == nullptr)\n    {\n        propertyString = _u(\"\");\n    }\n\n    if (op != knopInt && op != knopFlt && op != knopName && op != knopStr)\n    {\n        rightNode = _u(\"\");\n    }\n    else if (op == knopStr)\n    {\n        return AppendNameHints(propertyString, pNode->sxPid.pid, fullNameHintLength, pShortNameOffset, false, true\/*add brackets*\/);\n    }\n    else if(op == knopFlt)\n    {\n        rightNode = m_pscan->StringFromDbl(pNode->sxFlt.dbl);\n    }\n    else\n    {\n        rightNode = op == knopInt ? m_pscan->StringFromLong(pNode->sxInt.lw)\n            : pNode->sxPid.pid->Psz();\n    }\n\n    return AppendNameHints(propertyString, rightNode, fullNameHintLength, pShortNameOffset, false, true\/*add brackets*\/);\n}\n\nLPCOLESTR Parser::ConstructNameHint(ParseNodePtr pNode, uint32* fullNameHintLength, uint32 *pShortNameOffset)\n{\n    Assert(pNode != nullptr);\n    Assert(pNode->nop == knopDot || pNode->nop == knopIndex);\n    LPCOLESTR leftNode = nullptr;\n    if (pNode->sxBin.pnode1->nop == knopDot || pNode->sxBin.pnode1->nop == knopIndex)\n    {\n        leftNode = ConstructNameHint(pNode->sxBin.pnode1, fullNameHintLength, pShortNameOffset);\n    }\n    else if (pNode->sxBin.pnode1->nop == knopName)\n    {\n        leftNode = pNode->sxBin.pnode1->sxPid.pid->Psz();\n        *fullNameHintLength = pNode->sxBin.pnode1->sxPid.pid->Cch();\n        *pShortNameOffset = 0;\n    }\n\n    if (pNode->nop == knopIndex)\n    {\n        return FormatPropertyString(\n            leftNode ? leftNode : Js::Constants::AnonymousFunction, \/\/ e.g. f()[0] = function () {}\n            pNode->sxBin.pnode2, fullNameHintLength, pShortNameOffset);\n    }\n\n    Assert(pNode->sxBin.pnode2->nop == knopDot || pNode->sxBin.pnode2->nop == knopName);\n\n    LPCOLESTR rightNode = nullptr;\n    bool wrapWithBrackets = false;\n    if (pNode->sxBin.pnode2->nop == knopDot)\n    {\n        rightNode = ConstructNameHint(pNode->sxBin.pnode2, fullNameHintLength, pShortNameOffset);\n    }\n    else\n    {\n        rightNode = pNode->sxBin.pnode2->sxPid.pid->Psz();\n        wrapWithBrackets = PNodeFlags::fpnIndexOperator == (pNode->grfpn & PNodeFlags::fpnIndexOperator);\n    }\n    Assert(rightNode != nullptr);\n    return AppendNameHints(leftNode, rightNode, fullNameHintLength, pShortNameOffset, false, wrapWithBrackets);\n}\n\nLPCOLESTR Parser::AppendNameHints(LPCOLESTR leftStr, uint32 leftLen, LPCOLESTR rightStr, uint32 rightLen, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)\n{\n    Assert(rightStr != nullptr);\n    Assert(leftLen  != 0 || wrapInBrackets);\n    Assert(rightLen != 0 || wrapInBrackets);\n\n    bool ignoreDot = rightStr[0] == _u('[') && !wrapInBrackets;\/\/if we wrap in brackets it can be a string literal which can have brackets at the first char\n    uint32 totalLength = leftLen + rightLen + ((ignoreDot) ? 1 : 2); \/\/ 1 (for dot or [) + 1 (for null termination)\n\n    if (wrapInBrackets)\n    {\n        totalLength++; \/\/1 for ']';\n    }\n    WCHAR * finalName = AllocateStringOfLength(totalLength);\n\n    if (leftStr != nullptr && leftLen != 0)\n    {\n        wcscpy_s(finalName, leftLen + 1, leftStr);\n    }\n\n    if (ignoreAddDotWithSpace)\n    {\n        finalName[leftLen++] = (OLECHAR)_u(' ');\n    }\n    \/\/ mutually exclusive from ignoreAddDotWithSpace which is used for getters\/setters\n\n    else if (wrapInBrackets)\n    {\n        finalName[leftLen++] = (OLECHAR)_u('[');\n        finalName[totalLength-2] = (OLECHAR)_u(']');\n    }\n    else if (!ignoreDot)\n    {\n        finalName[leftLen++] = (OLECHAR)_u('.');\n    }\n    \/\/ignore case falls through\n    js_wmemcpy_s(finalName + leftLen, rightLen, rightStr, rightLen);\n    finalName[totalLength-1] = (OLECHAR)_u('\\0');\n\n    if (pNameLength != nullptr)\n    {\n        *pNameLength = totalLength - 1;\n    }\n    if (pShortNameOffset != nullptr)\n    {\n        *pShortNameOffset = leftLen;\n    }\n\n    return finalName;\n}\n\nWCHAR * Parser::AllocateStringOfLength(ULONG length)\n{\n    Assert(length > 0);\n    ULONG totalBytes;\n    if (ULongMult(length, sizeof(OLECHAR), &totalBytes) != S_OK)\n    {\n        Error(ERRnoMemory);\n    }\n    WCHAR* finalName = (WCHAR*)m_phtbl->GetAllocator()->Alloc(totalBytes);\n    if (finalName == nullptr)\n    {\n        Error(ERRnoMemory);\n    }\n    return finalName;\n}\n\nLPCOLESTR Parser::AppendNameHints(IdentPtr left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)\n{\n    if (pShortNameOffset != nullptr)\n    {\n        *pShortNameOffset = 0;\n    }\n\n    if (left == nullptr && !wrapInBrackets)\n    {\n        if (right)\n        {\n            *pNameLength = right->Cch();\n            return right->Psz();\n        }\n        return nullptr;\n    }\n\n    uint32 leftLen = 0;\n    LPCOLESTR leftStr = _u(\"\");\n\n    if (left != nullptr) \/\/ if wrapInBrackets is true\n    {\n        leftStr = left->Psz();\n        leftLen = left->Cch();\n    }\n\n    if (right == nullptr)\n    {\n        *pNameLength = leftLen;\n        return left->Psz();\n    }\n    uint32 rightLen = right->Cch();\n\n    return AppendNameHints(leftStr, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);\n}\n\nLPCOLESTR Parser::AppendNameHints(IdentPtr left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)\n{\n    uint32 rightLen = (right == nullptr) ? 0 : (uint32) wcslen(right);\n\n    if (pShortNameOffset != nullptr)\n    {\n        *pShortNameOffset = 0;\n    }\n\n    Assert(rightLen <= ULONG_MAX); \/\/ name hints should not exceed ULONG_MAX characters\n\n    if (left == nullptr && !wrapInBrackets)\n    {\n        *pNameLength = rightLen;\n        return right;\n    }\n\n    LPCOLESTR leftStr = _u(\"\");\n    uint32 leftLen = 0;\n\n    if (left != nullptr) \/\/ if wrapInBrackets is true\n    {\n        leftStr = left->Psz();\n        leftLen = left->Cch();\n    }\n\n    if (rightLen == 0 && !wrapInBrackets)\n    {\n        *pNameLength = leftLen;\n        return left->Psz();\n    }\n\n    return AppendNameHints(leftStr, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);\n}\n\nLPCOLESTR Parser::AppendNameHints(LPCOLESTR left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)\n{\n    uint32 leftLen = (left == nullptr) ? 0 : (uint32) wcslen(left);\n\n    if (pShortNameOffset != nullptr)\n    {\n        *pShortNameOffset = 0;\n    }\n\n    Assert(leftLen <= ULONG_MAX); \/\/ name hints should not exceed ULONG_MAX characters\n\n    if (left == nullptr || (leftLen == 0 && !wrapInBrackets))\n    {\n        if (right != nullptr)\n        {\n            *pNameLength = right->Cch();\n            return right->Psz();\n        }\n        return nullptr;\n    }\n\n    if (right == nullptr)\n    {\n        *pNameLength = leftLen;\n        return left;\n    }\n    uint32 rightLen = right->Cch();\n\n    return AppendNameHints(left, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);\n}\n\n\nLPCOLESTR Parser::AppendNameHints(LPCOLESTR left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)\n{\n    uint32 leftLen = (left == nullptr) ? 0 : (uint32) wcslen(left);\n    uint32 rightLen = (right == nullptr) ? 0 : (uint32) wcslen(right);\n    if (pShortNameOffset != nullptr)\n    {\n        *pShortNameOffset = 0;\n    }\n    Assert(rightLen <= ULONG_MAX && leftLen <= ULONG_MAX); \/\/ name hints should not exceed ULONG_MAX characters\n\n    if (leftLen == 0 && !wrapInBrackets)\n    {\n        *pNameLength = right ? rightLen : 0;\n        return right;\n    }\n\n    if (rightLen == 0 && !wrapInBrackets)\n    {\n        *pNameLength = leftLen;\n        return left;\n    }\n\n    return AppendNameHints(left, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);\n}\n\n\/**\n * Emits a spread error if there is no ambiguity, or marks defers the error for\n * when we can determine if it is a rest error or a spread error.\n *\n * The ambiguity arises when we are parsing a lambda parameter list but we have\n * not seen the => token. At this point, we are either in a parenthesized\n * expression or a parameter list, and cannot issue an error until the matching\n * RParen has been scanned.\n *\n * The actual emission of the error happens in ParseExpr, when we first know if\n * the expression is a lambda parameter list or not.\n *\n *\/\nvoid Parser::DeferOrEmitPotentialSpreadError(ParseNodePtr pnodeT)\n{\n    if (m_parenDepth > 0)\n    {\n        if (m_token.tk == tkRParen)\n        {\n           if (!m_deferEllipsisError)\n            {\n                \/\/ Capture only the first error instance.\n                m_pscan->Capture(&m_EllipsisErrLoc);\n                m_deferEllipsisError = true;\n            }\n        }\n        else\n        {\n            Error(ERRUnexpectedEllipsis);\n        }\n    }\n    else\n    {\n        Error(ERRInvalidSpreadUse);\n    }\n}\n\n\/***************************************************************************\nParse an optional sub expression returning null if there was no expression.\nChecks for no expression by looking for a token that can follow an\nExpression grammar production.\n***************************************************************************\/\ntemplate<bool buildAST>\nbool Parser::ParseOptionalExpr(ParseNodePtr* pnode, bool fUnaryOrParen, int oplMin, BOOL *pfCanAssign, BOOL fAllowIn, BOOL fAllowEllipsis, _Inout_opt_ IdentToken* pToken)\n{\n    *pnode = nullptr;\n    if (m_token.tk == tkRCurly ||\n        m_token.tk == tkRBrack ||\n        m_token.tk == tkRParen ||\n        m_token.tk == tkSColon ||\n        m_token.tk == tkColon ||\n        m_token.tk == tkComma ||\n        m_token.tk == tkLimKwd ||\n        m_pscan->FHadNewLine())\n    {\n        return false;\n    }\n\n    IdentToken token;\n    ParseNodePtr pnodeT = ParseExpr<buildAST>(oplMin, pfCanAssign, fAllowIn, fAllowEllipsis, nullptr \/*pNameHint*\/, nullptr \/*pHintLength*\/, nullptr \/*pShortNameOffset*\/, &token, fUnaryOrParen);\n    \/\/ Detect nested function escapes of the pattern \"return function(){...}\" or \"yield function(){...}\".\n    \/\/ Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape\n    \/\/ is not detected at byte code gen time because of deferred parsing.\n    this->MarkEscapingRef(pnodeT, &token);\n    if (pToken)\n    {\n        *pToken = token;\n    }\n    *pnode = pnodeT;\n    return true;\n}\n\n\/***************************************************************************\nParse a sub expression.\n'fAllowIn' indicates if the 'in' operator should be allowed in the initializing\nexpression ( it is not allowed in the context of the first expression in a  'for' loop).\n***************************************************************************\/\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseExpr(int oplMin,\n    BOOL *pfCanAssign,\n    BOOL fAllowIn,\n    BOOL fAllowEllipsis,\n    LPCOLESTR pNameHint,\n    uint32 *pHintLength,\n    uint32 *pShortNameOffset,\n    _Inout_opt_ IdentToken* pToken,\n    bool fUnaryOrParen,\n    _Inout_opt_ bool* pfLikelyPattern)\n{\n    Assert(pToken == nullptr || pToken->tk == tkNone); \/\/ Must be empty initially\n    int opl;\n    OpCode nop;\n    charcount_t ichMin;\n    ParseNodePtr pnode = nullptr;\n    ParseNodePtr pnodeT = nullptr;\n    BOOL fCanAssign = TRUE;\n    bool assignmentStmt = false;\n    bool fIsDotOrIndex = false;\n    IdentToken term;\n    RestorePoint termStart;\n    uint32 hintLength = 0;\n    uint32 hintOffset = 0;\n\n    ParserState parserState;\n\n    if (pHintLength != nullptr)\n    {\n        hintLength = *pHintLength;\n    }\n\n    if (pShortNameOffset != nullptr)\n    {\n        hintOffset = *pShortNameOffset;\n    }\n\n    EnsureStackAvailable();\n\n    \/\/ Storing the state here as we need to restore this state back when we need to reparse the grammar under lambda syntax.\n    CaptureState(&parserState);\n\n    m_pscan->Capture(&termStart);\n\n    bool deferredErrorFoundOnLeftSide = false;\n    bool savedDeferredInitError = m_hasDeferredShorthandInitError;\n    m_hasDeferredShorthandInitError = false;\n\n    \/\/ Is the current token a unary operator?\n    if (m_phtbl->TokIsUnop(m_token.tk, &opl, &nop) && nop != knopNone)\n    {\n        IdentToken operandToken;\n        ichMin = m_pscan->IchMinTok();\n\n        if (nop == knopYield)\n        {\n            if (!m_pscan->YieldIsKeyword() || oplMin > opl)\n            {\n                \/\/ The case where 'yield' is scanned as a keyword (tkYIELD) but the scanner\n                \/\/ is not treating yield as a keyword (!m_pscan->YieldIsKeyword()) occurs\n                \/\/ in strict mode non-generator function contexts.\n                \/\/\n                \/\/ That is, 'yield' is a keyword because of strict mode, but YieldExpression\n                \/\/ is not a grammar production outside of generator functions.\n                \/\/\n                \/\/ Otherwise it is an error for a yield to appear in the context of a higher level\n                \/\/ binding operator, be it unary or binary.\n                Error(ERRsyntax);\n            }\n            if (m_currentBlockInfo->pnodeBlock->sxBlock.blockType == PnodeBlockType::Parameter)\n            {\n                \/\/ 'yield' can appear (as a keyword) in parameter scope as formal name or as\n                \/\/ expression within a default parameter expression, in either a generator\n                \/\/ function or an arrow function contained within a generator function.\n                \/\/ In all cases it is an error.\n                Error(ERRsyntax);\n            }\n        }\n        else if (nop == knopAwait)\n        {\n            if (!m_pscan->AwaitIsKeyword() ||\n                m_currentScope->GetScopeType() == ScopeType_Parameter)\n            {\n                \/\/ As with the 'yield' keyword, the case where 'await' is scanned as a keyword (tkAWAIT)\n                \/\/ but the scanner is not treating await as a keyword (!m_pscan->AwaitIsKeyword())\n                \/\/ occurs in strict mode non-async function contexts.\n                \/\/\n                \/\/ That is, 'await' is a keyword because of strict mode, but AwaitExpression\n                \/\/ is not a grammar production outside of async functions.\n                \/\/\n                \/\/ Further, await expressions are disallowed within parameter scopes.\n                Error(ERRBadAwait);\n            }\n        }\n\n        m_pscan->Scan();\n\n        if (m_token.tk == tkEllipsis) {\n            \/\/ ... cannot have a unary prefix.\n            Error(ERRUnexpectedEllipsis);\n        }\n\n        if (nop == knopYield && !m_pscan->FHadNewLine() && m_token.tk == tkStar)\n        {\n            m_pscan->Scan();\n            nop = knopYieldStar;\n        }\n\n        if (nop == knopYield)\n        {\n            if (!ParseOptionalExpr<buildAST>(&pnodeT, false, opl, NULL, TRUE, fAllowEllipsis))\n            {\n                nop = knopYieldLeaf;\n                if (buildAST)\n                {\n                    pnode = CreateNodeT<knopYieldLeaf>(ichMin, m_pscan->IchLimTok());\n                }\n            }\n        }\n        else\n        {\n            \/\/ Disallow spread after a unary operator.\n            pnodeT = ParseExpr<buildAST>(opl, &fCanAssign, TRUE, FALSE, nullptr \/*hint*\/, nullptr \/*hintLength*\/, nullptr \/*hintOffset*\/, &operandToken, true);\n        }\n\n        if (nop != knopYieldLeaf)\n        {\n            if (nop == knopIncPre || nop == knopDecPre)\n            {\n                if (!fCanAssign && PHASE_ON1(Js::EarlyReferenceErrorsPhase))\n                {\n                    Error(JSERR_CantAssignTo);\n                }\n                TrackAssignment<buildAST>(pnodeT, &operandToken);\n                if (buildAST)\n                {\n                    if (IsStrictMode() && pnodeT->nop == knopName)\n                    {\n                        CheckStrictModeEvalArgumentsUsage(pnodeT->sxPid.pid);\n                    }\n                }\n                else\n                {\n                    if (IsStrictMode() && operandToken.tk == tkID)\n                    {\n                        CheckStrictModeEvalArgumentsUsage(operandToken.pid);\n                    }\n                }\n            }\n            else if (nop == knopEllipsis)\n            {\n                if (!fAllowEllipsis)\n                {\n                    DeferOrEmitPotentialSpreadError(pnodeT);\n                }\n            }\n            else if (m_token.tk == tkExpo)\n            {\n                \/\/Unary operator on the left hand-side of ** is unexpected, except ++, -- or ...\n                Error(ERRInvalidUseofExponentiationOperator);\n            }\n\n            if (buildAST)\n            {\n                \/\/Do not do the folding for Asm in case of KnopPos as we need this to determine the type\n                if (nop == knopPos && (pnodeT->nop == knopInt || pnodeT->nop == knopFlt) && !this->m_InAsmMode)\n                {\n                    \/\/ Fold away a unary '+' on a number.\n                    pnode = pnodeT;\n                }\n                else if (nop == knopNeg &&\n                    ((pnodeT->nop == knopInt && pnodeT->sxInt.lw != 0) ||\n                    (pnodeT->nop == knopFlt && (pnodeT->sxFlt.dbl != 0 || this->m_InAsmMode))))\n                {\n                    \/\/ Fold a unary '-' on a number into the value of the number itself.\n                    pnode = pnodeT;\n                    if (pnode->nop == knopInt)\n                    {\n                        pnode->sxInt.lw = -pnode->sxInt.lw;\n                    }\n                    else\n                    {\n                        pnode->sxFlt.dbl = -pnode->sxFlt.dbl;\n                    }\n                }\n                else\n                {\n                    pnode = CreateUniNode(nop, pnodeT);\n                    this->CheckArguments(pnode->sxUni.pnode1);\n                }\n                pnode->ichMin = ichMin;\n            }\n\n            if (nop == knopDelete)\n            {\n                if (IsStrictMode())\n                {\n                    if ((buildAST && pnode->sxUni.pnode1->nop == knopName) ||\n                        (!buildAST && operandToken.tk == tkID))\n                    {\n                        Error(ERRInvalidDelete);\n                    }\n                }\n\n                if (buildAST)\n                {\n                    ParseNodePtr pnode1 = pnode->sxUni.pnode1;\n                    if (m_currentNodeFunc)\n                    {\n                        if (pnode1->nop == knopDot || pnode1->nop == knopIndex)\n                        {\n                            \/\/ If we delete an arguments property, use the conservative,\n                            \/\/ heap-allocated arguments object.\n                            this->CheckArguments(pnode1->sxBin.pnode1);\n                        }\n                    }\n                }\n            }\n        }\n\n        fCanAssign = FALSE;\n    }\n    else\n    {\n        ichMin = m_pscan->IchMinTok();\n        BOOL fLikelyPattern = FALSE;\n        pnode = ParseTerm<buildAST>(TRUE, pNameHint, &hintLength, &hintOffset, &term, fUnaryOrParen, &fCanAssign, IsES6DestructuringEnabled() ? &fLikelyPattern : nullptr, &fIsDotOrIndex);\n        if (pfLikelyPattern != nullptr)\n        {\n            *pfLikelyPattern = !!fLikelyPattern;\n        }\n\n        if (m_token.tk == tkDArrow)\n        {\n            m_hasDeferredShorthandInitError = false;\n        }\n\n        if (m_token.tk == tkAsg && oplMin <= koplAsg && fLikelyPattern)\n        {\n            m_pscan->SeekTo(termStart);\n\n            ParseDestructuredLiteralWithScopeSave(tkLCurly, false\/*isDecl*\/, false \/*topLevel*\/, DIC_ShouldNotParseInitializer);\n\n            if (buildAST)\n            {\n                pnode = ConvertToPattern(pnode);\n            }\n\n            \/\/ The left-hand side is found to be destructuring pattern - so the shorthand can have initializer.\n            m_hasDeferredShorthandInitError = false;\n        }\n\n        if (buildAST)\n        {\n            pNameHint = NULL;\n            if (pnode->nop == knopName)\n            {\n                pNameHint = pnode->sxPid.pid->Psz();\n                hintLength = pnode->sxPid.pid->Cch();\n                hintOffset = 0;\n            }\n            else if (pnode->nop == knopDot || pnode->nop == knopIndex)\n            {\n                if (CONFIG_FLAG(UseFullName))\n                {\n                    pNameHint = ConstructNameHint(pnode, &hintLength, &hintOffset);\n                }\n                else\n                {\n                    ParseNodePtr pnodeName = pnode;\n                    while (pnodeName->nop == knopDot)\n                    {\n                        pnodeName = pnodeName->sxBin.pnode2;\n                    }\n\n                    if (pnodeName->nop == knopName)\n                    {\n                        pNameHint = pnodeName->sxPid.pid->Psz();\n                        hintLength = pnodeName->sxPid.pid->Cch();\n                        hintOffset = 0;\n                    }\n                }\n            }\n        }\n\n        \/\/ Check for postfix unary operators.\n        if (!m_pscan->FHadNewLine() &&\n            (tkInc == m_token.tk || tkDec == m_token.tk))\n        {\n            if (!fCanAssign && PHASE_ON1(Js::EarlyReferenceErrorsPhase))\n            {\n                Error(JSERR_CantAssignTo);\n            }\n            TrackAssignment<buildAST>(pnode, &term);\n            fCanAssign = FALSE;\n            if (buildAST)\n            {\n                if (IsStrictMode() && pnode->nop == knopName)\n                {\n                    CheckStrictModeEvalArgumentsUsage(pnode->sxPid.pid);\n                }\n                this->CheckArguments(pnode);\n                pnode = CreateUniNode(tkInc == m_token.tk ? knopIncPost : knopDecPost, pnode);\n                pnode->ichLim = m_pscan->IchLimTok();\n            }\n            else\n            {\n                if (IsStrictMode() && term.tk == tkID)\n                {\n                    CheckStrictModeEvalArgumentsUsage(term.pid);\n                }\n                \/\/ This expression is not an identifier\n                term.tk = tkNone;\n            }\n            m_pscan->Scan();\n        }\n    }\n\n    deferredErrorFoundOnLeftSide = m_hasDeferredShorthandInitError;\n\n    \/\/ Process a sequence of operators and operands.\n    for (;;)\n    {\n        if (!m_phtbl->TokIsBinop(m_token.tk, &opl, &nop) || nop == knopNone)\n        {\n            break;\n        }\n        if ( ! fAllowIn && nop == knopIn )\n        {\n            break;\n        }\n        Assert(opl != koplNo);\n\n        if (opl == koplAsg)\n        {\n            if (m_token.tk != tkDArrow)\n            {\n                \/\/ Assignment operator. These are the only right associative\n                \/\/ binary operators. We also need to special case the left\n                \/\/ operand - it should only be a LeftHandSideExpression.\n                Assert(ParseNode::Grfnop(nop) & fnopAsg || nop == knopFncDecl);\n                TrackAssignment<buildAST>(pnode, &term);\n                if (buildAST)\n                {\n                    if (IsStrictMode() && pnode->nop == knopName)\n                    {\n                        CheckStrictModeEvalArgumentsUsage(pnode->sxPid.pid);\n                    }\n\n                    \/\/ Assignment stmt of the form \"this.<id> = <expr>\"\n                    if (nop == knopAsg && pnode->nop == knopDot && pnode->sxBin.pnode1->nop == knopThis && pnode->sxBin.pnode2->nop == knopName)\n                    {\n                        if (pnode->sxBin.pnode2->sxPid.pid != wellKnownPropertyPids.__proto__)\n                        {\n                            assignmentStmt = true;\n                        }\n                    }\n                }\n                else\n                {\n                    if (IsStrictMode() && term.tk == tkID)\n                    {\n                        CheckStrictModeEvalArgumentsUsage(term.pid);\n                    }\n                }\n            }\n\n            if (opl < oplMin)\n            {\n                break;\n            }\n            if (m_token.tk != tkDArrow && !fCanAssign && PHASE_ON1(Js::EarlyReferenceErrorsPhase))\n            {\n                Error(JSERR_CantAssignTo);\n                \/\/ No recovery necessary since this is a semantic, not structural, error.\n            }\n        }\n        else if (opl == koplExpo)\n        {\n            \/\/ ** operator is right associative\n            if (opl < oplMin)\n            {\n                break;\n            }\n\n        }\n        else if (opl <= oplMin)\n        {\n            break;\n        }\n\n        \/\/ This expression is not an identifier\n        term.tk = tkNone;\n\n        \/\/ Precedence is high enough. Consume the operator token.\n        m_pscan->Scan();\n        fCanAssign = FALSE;\n\n        \/\/ Special case the \"?:\" operator\n        if (nop == knopQmark)\n        {\n            pnodeT = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn);\n            ChkCurTok(tkColon, ERRnoColon);\n            ParseNodePtr pnodeT2 = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn);\n            if (buildAST)\n            {\n                pnode = CreateTriNode(nop, pnode, pnodeT, pnodeT2);\n                this->CheckArguments(pnode->sxTri.pnode2);\n                this->CheckArguments(pnode->sxTri.pnode3);\n            }\n        }\n        else if (nop == knopFncDecl)\n        {\n            ushort flags = fFncLambda;\n            size_t iecpMin = 0;\n            bool isAsyncMethod = false;\n\n            RestoreStateFrom(&parserState);\n\n            m_pscan->SeekTo(termStart);\n            if (m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())\n            {\n                ichMin = m_pscan->IchMinTok();\n                iecpMin = m_pscan->IecpMinTok();\n\n                m_pscan->Scan();\n                if ((m_token.tk == tkID || m_token.tk == tkLParen) && !m_pscan->FHadNewLine())\n                {\n                    flags |= fFncAsync;\n                    isAsyncMethod = true;\n                }\n                else\n                {\n                    m_pscan->SeekTo(termStart);\n                }\n            }\n            pnode = ParseFncDecl<buildAST>(flags, nullptr, \/* needsPIDOnRCurlyScan = *\/false, \/* resetParsingSuperRestrictionState = *\/false);\n            if (isAsyncMethod)\n            {\n                pnode->sxFnc.cbMin = iecpMin;\n                pnode->ichMin = ichMin;\n            }\n        }\n        else\n        {\n            \/\/ Parse the operand, make a new node, and look for more\n            IdentToken token;\n            pnodeT = ParseExpr<buildAST>(opl, NULL, fAllowIn, FALSE, pNameHint, &hintLength, &hintOffset, &token);\n\n            \/\/ Detect nested function escapes of the pattern \"o.f = function(){...}\" or \"o[s] = function(){...}\".\n            \/\/ Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape\n            \/\/ is not detected at byte code gen time because of deferred parsing.\n            if (fIsDotOrIndex && nop == knopAsg)\n            {\n                this->MarkEscapingRef(pnodeT, &token);\n            }\n\n            if (buildAST)\n            {\n                pnode = CreateBinNode(nop, pnode, pnodeT);\n                Assert(pnode->sxBin.pnode2 != NULL);\n                if (pnode->sxBin.pnode2->nop == knopFncDecl)\n                {\n                    Assert(hintLength >= hintOffset);\n                    pnode->sxBin.pnode2->sxFnc.hint = pNameHint;\n                    pnode->sxBin.pnode2->sxFnc.hintLength = hintLength;\n                    pnode->sxBin.pnode2->sxFnc.hintOffset = hintOffset;\n\n                    if (pnode->sxBin.pnode1->nop == knopDot)\n                    {\n                        pnode->sxBin.pnode2->sxFnc.isNameIdentifierRef  = false;\n                    }\n                }\n                if (pnode->sxBin.pnode2->nop == knopClassDecl && pnode->sxBin.pnode1->nop == knopDot)\n                {\n                    Assert(pnode->sxBin.pnode2->sxClass.pnodeConstructor);\n                    pnode->sxBin.pnode2->sxClass.pnodeConstructor->sxFnc.isNameIdentifierRef  = false;\n                }\n            }\n            pNameHint = NULL;\n        }\n    }\n\n    if (buildAST)\n    {\n        if (!assignmentStmt)\n        {\n            \/\/ Don't set the flag for following nodes\n            switch (pnode->nop)\n            {\n            case knopName:\n            case knopInt:\n            case knopFlt:\n            case knopStr:\n            case knopRegExp:\n            case knopNull:\n            case knopFalse:\n            case knopTrue:\n                break;\n            default:\n                if (m_currentNodeFunc)\n                {\n                    m_currentNodeFunc->sxFnc.SetHasNonThisStmt();\n                }\n                else if (m_currentNodeProg)\n                {\n                    m_currentNodeProg->sxFnc.SetHasNonThisStmt();\n                }\n            }\n        }\n    }\n\n    if (m_hasDeferredShorthandInitError && !deferredErrorFoundOnLeftSide)\n    {\n        \/\/ Raise error only if it is found not on the right side of the expression.\n        \/\/ such as  <expr> = {x = 1}\n        Error(ERRnoColon);\n    }\n\n    m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || savedDeferredInitError;\n\n    if (NULL != pfCanAssign)\n    {\n        *pfCanAssign = fCanAssign;\n    }\n\n    \/\/ Pass back identifier if requested\n    if (pToken && term.tk == tkID)\n    {\n        *pToken = term;\n    }\n\n    \/\/Track \"obj.a\" assignment patterns here - Promote the Assignment state for the property's PID.\n    \/\/ This includes =, += etc.\n    if (pnode != NULL)\n    {\n        uint nodeType = ParseNode::Grfnop(pnode->nop);\n        if (nodeType & fnopAsg)\n        {\n            if (nodeType & fnopBin)\n            {\n                ParseNodePtr lhs = pnode->sxBin.pnode1;\n\n                Assert(lhs);\n                if (lhs->nop == knopDot)\n                {\n                    ParseNodePtr propertyNode = lhs->sxBin.pnode2;\n                    if (propertyNode->nop == knopName)\n                    {\n                        propertyNode->sxPid.pid->PromoteAssignmentState();\n                    }\n                }\n            }\n            else if (nodeType & fnopUni)\n            {\n                \/\/ cases like obj.a++, ++obj.a\n                ParseNodePtr lhs = pnode->sxUni.pnode1;\n                if (lhs->nop == knopDot)\n                {\n                    ParseNodePtr propertyNode = lhs->sxBin.pnode2;\n                    if (propertyNode->nop == knopName)\n                    {\n                        propertyNode->sxPid.pid->PromoteAssignmentState();\n                    }\n                }\n            }\n        }\n    }\n    return pnode;\n}\n\ntemplate<bool buildAST>\nvoid Parser::TrackAssignment(ParseNodePtr pnodeT, IdentToken* pToken)\n{\n    if (buildAST)\n    {\n        Assert(pnodeT != nullptr);\n        if (pnodeT->nop == knopName)\n        {\n            PidRefStack *ref = pnodeT->sxPid.pid->GetTopRef();\n            Assert(ref);\n            ref->isAsg = true;\n        }\n    }\n    else\n    {\n        Assert(pToken != nullptr);\n        if (pToken->tk == tkID)\n        {\n            PidRefStack *ref = pToken->pid->GetTopRef();\n            Assert(ref);\n            ref->isAsg = true;\n        }\n    }\n}\n\nvoid PnPid::SetSymRef(PidRefStack *ref)\n{\n    Assert(symRef == nullptr);\n    this->symRef = ref->GetSymRef();\n}\n\nJs::PropertyId PnPid::PropertyIdFromNameNode() const\n{\n    Js::PropertyId propertyId;\n    Symbol *sym = this->sym;\n    if (sym)\n    {\n        propertyId = sym->GetPosition();\n    }\n    else\n    {\n        propertyId = this->pid->GetPropertyId();\n    }\n    return propertyId;\n}\n\nPidRefStack* Parser::PushPidRef(IdentPtr pid)\n{\n    if (PHASE_ON1(Js::ParallelParsePhase))\n    {\n        \/\/ NOTE: the phase check is here to protect perf. See OSG 1020424.\n        \/\/ In some LS AST-rewrite cases we lose a lot of perf searching the PID ref stack rather\n        \/\/ than just pushing on the top. This hasn't shown up as a perf issue in non-LS benchmarks.\n        return pid->FindOrAddPidRef(&m_nodeAllocator, GetCurrentBlock()->sxBlock.blockId, GetCurrentFunctionNode()->sxFnc.functionId);\n    }\n\n    Assert(GetCurrentBlock() != nullptr);\n    AssertMsg(pid != nullptr, \"PID should be created\");\n    PidRefStack *ref = pid->GetTopRef();\n    int blockId = GetCurrentBlock()->sxBlock.blockId;\n    int funcId = GetCurrentFunctionNode()->sxFnc.functionId;\n    if (!ref || (ref->GetScopeId() < blockId))\n    {\n        ref = Anew(&m_nodeAllocator, PidRefStack);\n        if (ref == nullptr)\n        {\n            Error(ERRnoMemory);\n        }\n        pid->PushPidRef(blockId, funcId, ref);\n    }\n\n    return ref;\n}\n\nPidRefStack* Parser::FindOrAddPidRef(IdentPtr pid, int scopeId, Js::LocalFunctionId funcId)\n{\n    PidRefStack *ref = pid->FindOrAddPidRef(&m_nodeAllocator, scopeId, funcId);\n    if (ref == NULL)\n    {\n        Error(ERRnoMemory);\n    }\n    return ref;\n}\n\nvoid Parser::RemovePrevPidRef(IdentPtr pid, PidRefStack *ref)\n{\n    PidRefStack *prevRef = pid->RemovePrevPidRef(ref);\n    Assert(prevRef);\n    if (prevRef->GetSym() == nullptr)\n    {\n        AllocatorDelete(ArenaAllocator, &m_nodeAllocator, prevRef);\n    }\n}\n\nvoid Parser::SetPidRefsInScopeDynamic(IdentPtr pid, int blockId)\n{\n    PidRefStack *ref = pid->GetTopRef();\n    while (ref && ref->GetScopeId() >= blockId)\n    {\n        ref->SetDynamicBinding();\n        ref = ref->prev;\n    }\n}\n\nParseNode* Parser::GetFunctionBlock()\n{\n    Assert(m_currentBlockInfo != nullptr);\n    return m_currentBlockInfo->pBlockInfoFunction->pnodeBlock;\n}\n\n\nParseNode* Parser::GetCurrentBlock()\n{\n    return m_currentBlockInfo != nullptr ? m_currentBlockInfo->pnodeBlock : nullptr;\n}\n\nBlockInfoStack* Parser::GetCurrentBlockInfo()\n{\n    return m_currentBlockInfo;\n}\n\nBlockInfoStack* Parser::GetCurrentFunctionBlockInfo()\n{\n    return m_currentBlockInfo->pBlockInfoFunction;\n}\n\n\/***************************************************************************\nParse a variable declaration.\n'fAllowIn' indicates if the 'in' operator should be allowed in the initializing\nexpression ( it is not allowed in the context of the first expression in a  'for' loop).\n***************************************************************************\/\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseVariableDeclaration(\n    tokens declarationType, charcount_t ichMin,\n    BOOL fAllowIn\/* = TRUE*\/,\n    BOOL* pfForInOk\/* = nullptr*\/,\n    BOOL singleDefOnly\/* = FALSE*\/,\n    BOOL allowInit\/* = TRUE*\/,\n    BOOL isTopVarParse\/* = TRUE*\/,\n    BOOL isFor\/* = FALSE*\/,\n    BOOL* nativeForOk \/*= nullptr*\/)\n{\n    ParseNodePtr pnodeThis = nullptr;\n    ParseNodePtr pnodeInit;\n    ParseNodePtr pnodeList = nullptr;\n    ParseNodePtr *lastNodeRef = nullptr;\n    LPCOLESTR pNameHint = nullptr;\n    uint32     nameHintLength = 0;\n    uint32     nameHintOffset = 0;\n    Assert(declarationType == tkVAR || declarationType == tkCONST || declarationType == tkLET);\n\n    for (;;)\n    {\n        if (IsES6DestructuringEnabled() && IsPossiblePatternStart())\n        {\n            pnodeThis = ParseDestructuredLiteral<buildAST>(declarationType, true, !!isTopVarParse, DIC_None, !!fAllowIn, pfForInOk, nativeForOk);\n            if (pnodeThis != nullptr)\n            {\n                pnodeThis->ichMin = ichMin;\n            }\n        }\n        else\n        {\n            if (m_token.tk != tkID)\n            {\n                IdentifierExpectedError(m_token);\n            }\n\n            IdentPtr pid = m_token.GetIdentifier(m_phtbl);\n            Assert(pid);\n            pNameHint = pid->Psz();\n            nameHintLength = pid->Cch();\n            nameHintOffset = 0;\n\n            if (pid == wellKnownPropertyPids.let && (declarationType == tkCONST || declarationType == tkLET))\n            {\n                Error(ERRLetIDInLexicalDecl, pnodeThis);\n            }\n\n            if (declarationType == tkVAR)\n            {\n                pnodeThis = CreateVarDeclNode(pid, STVariable);\n            }\n            else if (declarationType == tkCONST)\n            {\n                pnodeThis = CreateBlockScopedDeclNode(pid, knopConstDecl);\n                CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ConstCount, m_scriptContext);\n            }\n            else\n            {\n                pnodeThis = CreateBlockScopedDeclNode(pid, knopLetDecl);\n                CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(LetCount, m_scriptContext);\n            }\n\n            if (pid == wellKnownPropertyPids.arguments && m_currentNodeFunc)\n            {\n                \/\/ This var declaration may change the way an 'arguments' identifier in the function is resolved\n                if (declarationType == tkVAR)\n                {\n                    m_currentNodeFunc->grfpn |= PNodeFlags::fpnArguments_varDeclaration;\n                }\n                else\n                {\n                    if (GetCurrentBlockInfo()->pnodeBlock->sxBlock.blockType == Function)\n                    {\n                        \/\/ Only override arguments if we are at the function block level.\n                        m_currentNodeFunc->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;\n                    }\n                }\n            }\n\n            if (pnodeThis)\n            {\n                pnodeThis->ichMin = ichMin;\n            }\n\n            m_pscan->Scan();\n\n            if (m_token.tk == tkAsg)\n            {\n                if (!allowInit)\n                {\n                    Error(ERRUnexpectedDefault);\n                }\n                if (pfForInOk && (declarationType == tkLET || declarationType == tkCONST || IsStrictMode()))\n                {\n                    *pfForInOk = FALSE;\n                }\n\n                m_pscan->Scan();\n                pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, fAllowIn, FALSE, pNameHint, &nameHintLength, &nameHintOffset);\n                if (buildAST)\n                {\n                    AnalysisAssert(pnodeThis);\n                    pnodeThis->sxVar.pnodeInit = pnodeInit;\n                    pnodeThis->ichLim = pnodeInit->ichLim;\n\n                    if (pnodeInit->nop == knopFncDecl)\n                    {\n                        Assert(nameHintLength >= nameHintOffset);\n                        pnodeInit->sxFnc.hint = pNameHint;\n                        pnodeInit->sxFnc.hintLength = nameHintLength;\n                        pnodeInit->sxFnc.hintOffset = nameHintOffset;\n\n                    }\n                    else\n                    {\n                        this->CheckArguments(pnodeInit);\n                    }\n                    pNameHint = nullptr;\n                }\n\n                \/\/Track var a =, let a= , const a =\n                \/\/ This is for FixedFields Constant Heuristics\n                if (pnodeThis && pnodeThis->sxVar.pnodeInit != nullptr)\n                {\n                    pnodeThis->sxVar.sym->PromoteAssignmentState();\n                    if (m_currentNodeFunc && pnodeThis->sxVar.sym->GetIsFormal())\n                    {\n                        m_currentNodeFunc->sxFnc.SetHasAnyWriteToFormals(true);\n                    }\n                }\n            }\n            else if (declarationType == tkCONST \/*pnodeThis->nop == knopConstDecl*\/\n                     && !singleDefOnly\n                     && !(isFor && TokIsForInOrForOf()))\n            {\n                Error(ERRUninitializedConst);\n            }\n        }\n\n        if (singleDefOnly)\n        {\n            return pnodeThis;\n        }\n\n        if (buildAST)\n        {\n            AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeThis);\n        }\n\n        if (m_token.tk != tkComma)\n        {\n            return pnodeList;\n        }\n\n        if (pfForInOk)\n        {\n            \/\/ don't allow \"for (var a, b in c)\"\n            *pfForInOk = FALSE;\n        }\n        m_pscan->Scan();\n        ichMin = m_pscan->IchMinTok();\n    }\n}\n\n\/***************************************************************************\nParse try-catch-finally statement\n***************************************************************************\/\n\n\/\/ The try-catch-finally tree nests the try-catch within a try-finally.\n\/\/ This matches the new runtime implementation.\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseTryCatchFinally()\n{\n    this->m_tryCatchOrFinallyDepth++;\n\n    ParseNodePtr pnodeT = ParseTry<buildAST>();\n    ParseNodePtr pnodeTC = nullptr;\n    StmtNest stmt;\n    bool hasCatch = false;\n\n    if (tkCATCH == m_token.tk)\n    {\n        hasCatch = true;\n        if (buildAST)\n        {\n            pnodeTC = CreateNodeWithScanner<knopTryCatch>();\n            pnodeT->sxStmt.pnodeOuter = pnodeTC;\n            pnodeTC->sxTryCatch.pnodeTry = pnodeT;\n        }\n        PushStmt<buildAST>(&stmt, pnodeTC, knopTryCatch, nullptr, nullptr);\n\n        ParseNodePtr pnodeCatch = ParseCatch<buildAST>();\n        if (buildAST)\n        {\n            pnodeTC->sxTryCatch.pnodeCatch = pnodeCatch;\n        }\n        PopStmt(&stmt);\n    }\n    if (tkFINALLY != m_token.tk)\n    {\n        if (!hasCatch)\n        {\n            Error(ERRnoCatch);\n        }\n        Assert(!buildAST || pnodeTC);\n        return pnodeTC;\n    }\n\n    ParseNodePtr pnodeTF = nullptr;\n    if (buildAST)\n    {\n        pnodeTF = CreateNode(knopTryFinally);\n    }\n    PushStmt<buildAST>(&stmt, pnodeTF, knopTryFinally, nullptr, nullptr);\n    ParseNodePtr pnodeFinally = ParseFinally<buildAST>();\n    if (buildAST)\n    {\n        if (!hasCatch)\n        {\n            pnodeTF->sxTryFinally.pnodeTry = pnodeT;\n            pnodeT->sxStmt.pnodeOuter = pnodeTF;\n        }\n        else\n        {\n            pnodeTF->sxTryFinally.pnodeTry = CreateNode(knopTry);\n            pnodeTF->sxTryFinally.pnodeTry->sxStmt.pnodeOuter = pnodeTF;\n            pnodeTF->sxTryFinally.pnodeTry->sxTry.pnodeBody = pnodeTC;\n            pnodeTC->sxStmt.pnodeOuter = pnodeTF->sxTryFinally.pnodeTry;\n        }\n        pnodeTF->sxTryFinally.pnodeFinally = pnodeFinally;\n    }\n    PopStmt(&stmt);\n    this->m_tryCatchOrFinallyDepth--;\n    return pnodeTF;\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseTry()\n{\n    ParseNodePtr pnode = nullptr;\n    StmtNest stmt;\n    Assert(tkTRY == m_token.tk);\n    if (buildAST)\n    {\n        pnode = CreateNode(knopTry);\n    }\n    m_pscan->Scan();\n    if (tkLCurly != m_token.tk)\n    {\n        Error(ERRnoLcurly);\n    }\n\n    PushStmt<buildAST>(&stmt, pnode, knopTry, nullptr, nullptr);\n    ParseNodePtr pnodeBody = ParseStatement<buildAST>();\n    if (buildAST)\n    {\n        pnode->sxTry.pnodeBody = pnodeBody;\n        if (pnode->sxTry.pnodeBody)\n            pnode->ichLim = pnode->sxTry.pnodeBody->ichLim;\n    }\n    PopStmt(&stmt);\n    return pnode;\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseFinally()\n{\n    ParseNodePtr pnode = nullptr;\n    StmtNest stmt;\n    Assert(tkFINALLY == m_token.tk);\n    if (buildAST)\n    {\n        pnode = CreateNode(knopFinally);\n    }\n    m_pscan->Scan();\n    if (tkLCurly != m_token.tk)\n    {\n        Error(ERRnoLcurly);\n    }\n\n    PushStmt<buildAST>(&stmt, pnode, knopFinally, nullptr, nullptr);\n    ParseNodePtr pnodeBody = ParseStatement<buildAST>();\n    if (buildAST)\n    {\n        pnode->sxFinally.pnodeBody = pnodeBody;\n        if (!pnode->sxFinally.pnodeBody)\n            \/\/ Will only occur due to error correction.\n            pnode->sxFinally.pnodeBody = CreateNodeWithScanner<knopEmpty>();\n        else\n            pnode->ichLim = pnode->sxFinally.pnodeBody->ichLim;\n    }\n    PopStmt(&stmt);\n\n    return pnode;\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseCatch()\n{\n    ParseNodePtr rootNode = nullptr;\n    ParseNodePtr* ppnode = &rootNode;\n    ParseNodePtr *ppnodeExprScopeSave = nullptr;\n    ParseNodePtr pnode = nullptr;\n    ParseNodePtr pnodeCatchScope = nullptr;\n    StmtNest stmt;\n    IdentPtr pidCatch = nullptr;\n    \/\/while (tkCATCH == m_token.tk)\n    if (tkCATCH == m_token.tk)\n    {\n        charcount_t ichMin;\n        if (buildAST)\n        {\n            ichMin = m_pscan->IchMinTok();\n        }\n        m_pscan->Scan(); \/\/catch\n        ChkCurTok(tkLParen, ERRnoLparen); \/\/catch(\n\n        bool isPattern = false;\n        if (tkID != m_token.tk)\n        {\n            isPattern = IsES6DestructuringEnabled() && IsPossiblePatternStart();\n            if (!isPattern)\n            {\n                IdentifierExpectedError(m_token);\n            }\n        }\n\n        if (buildAST)\n        {\n            pnode = CreateNodeWithScanner<knopCatch>(ichMin);\n            PushStmt<buildAST>(&stmt, pnode, knopCatch, nullptr, nullptr);\n            *ppnode = pnode;\n            ppnode = &pnode->sxCatch.pnodeNext;\n            *ppnode = nullptr;\n        }\n\n        pnodeCatchScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, isPattern ? ScopeType_CatchParamPattern : ScopeType_Catch);\n\n        if (buildAST)\n        {\n            \/\/ Add this catch to the current scope list.\n\n            if (m_ppnodeExprScope)\n            {\n                Assert(*m_ppnodeExprScope == nullptr);\n                *m_ppnodeExprScope = pnode;\n                m_ppnodeExprScope = &pnode->sxCatch.pnodeNext;\n            }\n            else\n            {\n                Assert(m_ppnodeScope);\n                Assert(*m_ppnodeScope == nullptr);\n                *m_ppnodeScope = pnode;\n                m_ppnodeScope = &pnode->sxCatch.pnodeNext;\n            }\n\n            \/\/ Keep a list of function expressions (not declarations) at this scope.\n\n            ppnodeExprScopeSave = m_ppnodeExprScope;\n            m_ppnodeExprScope = &pnode->sxCatch.pnodeScopes;\n            pnode->sxCatch.pnodeScopes = nullptr;\n        }\n\n        if (isPattern)\n        {\n            ParseNodePtr pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true \/*isDecl*\/, true \/*topLevel*\/, DIC_ForceErrorOnInitializer);\n            if (buildAST)\n            {\n                pnode->sxCatch.pnodeParam = CreateParamPatternNode(pnodePattern);\n                Scope *scope = pnodeCatchScope->sxBlock.scope;\n                pnode->sxCatch.scope = scope;\n            }\n        }\n        else\n        {\n            if (IsStrictMode())\n            {\n                IdentPtr pid = m_token.GetIdentifier(m_phtbl);\n                if (pid == wellKnownPropertyPids.eval)\n                {\n                    Error(ERREvalUsage);\n                }\n                else if (pid == wellKnownPropertyPids.arguments)\n                {\n                    Error(ERRArgsUsage);\n                }\n            }\n\n            pidCatch = m_token.GetIdentifier(m_phtbl);\n            PidRefStack *ref = this->PushPidRef(pidCatch);\n\n            ParseNodePtr pnodeParam = CreateNameNode(pidCatch);\n            pnodeParam->sxPid.symRef = ref->GetSymRef();\n\n            const char16 *name = reinterpret_cast<const char16*>(pidCatch->Psz());\n            int nameLength = pidCatch->Cch();\n            SymbolName const symName(name, nameLength);\n            Symbol *sym = Anew(&m_nodeAllocator, Symbol, symName, pnodeParam, STVariable);\n            sym->SetPid(pidCatch);\n            if (sym == nullptr)\n            {\n                Error(ERRnoMemory);\n            }\n            Assert(ref->GetSym() == nullptr);\n            ref->SetSym(sym);\n\n            Scope *scope = pnodeCatchScope->sxBlock.scope;\n            scope->AddNewSymbol(sym);\n\n            if (buildAST)\n            {\n                pnode->sxCatch.pnodeParam = pnodeParam;\n                pnode->sxCatch.scope = scope;\n            }\n\n            m_pscan->Scan();\n        }\n\n        charcount_t ichLim;\n        if (buildAST)\n        {\n            ichLim = m_pscan->IchLimTok();\n        }\n        ChkCurTok(tkRParen, ERRnoRparen); \/\/catch(id[:expr])\n\n        if (tkLCurly != m_token.tk)\n        {\n            Error(ERRnoLcurly);\n        }\n\n        ParseNodePtr pnodeBody = ParseStatement<buildAST>();  \/\/catch(id[:expr]) {block}\n        if (buildAST)\n        {\n            pnode->sxCatch.pnodeBody = pnodeBody;\n            pnode->ichLim = ichLim;\n        }\n\n        if (pnodeCatchScope != nullptr)\n        {\n            FinishParseBlock(pnodeCatchScope);\n        }\n\n        if (buildAST)\n        {\n            PopStmt(&stmt);\n\n            \/\/ Restore the lists of function expression scopes.\n\n            AssertMem(m_ppnodeExprScope);\n            Assert(*m_ppnodeExprScope == nullptr);\n            m_ppnodeExprScope = ppnodeExprScopeSave;\n        }\n    }\n    return rootNode;\n}\n\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseCase(ParseNodePtr *ppnodeBody)\n{\n    ParseNodePtr pnodeT = nullptr;\n\n    charcount_t ichMinT = m_pscan->IchMinTok();\n    m_pscan->Scan();\n    ParseNodePtr pnodeExpr = ParseExpr<buildAST>();\n    charcount_t ichLim = m_pscan->IchLimTok();\n\n    ChkCurTok(tkColon, ERRnoColon);\n\n    if (buildAST)\n    {\n        pnodeT = CreateNodeWithScanner<knopCase>(ichMinT);\n        pnodeT->sxCase.pnodeExpr = pnodeExpr;\n        pnodeT->ichLim = ichLim;\n    }\n    ParseStmtList<buildAST>(ppnodeBody);\n\n    return pnodeT;\n}\n\n\/***************************************************************************\nParse a single statement. Digest a trailing semicolon.\n***************************************************************************\/\ntemplate<bool buildAST>\nParseNodePtr Parser::ParseStatement()\n{\n    ParseNodePtr *ppnodeT;\n    ParseNodePtr pnodeT;\n    ParseNodePtr pnode = nullptr;\n    LabelId* pLabelIdList = nullptr;\n    charcount_t ichMin = 0;\n    size_t iecpMin = 0;\n    StmtNest stmt;\n    StmtNest *pstmt;\n    BOOL fForInOrOfOkay;\n    BOOL fCanAssign;\n    IdentPtr pid;\n    uint fnop;\n    ParseNodePtr pnodeLabel = nullptr;\n    bool expressionStmt = false;\n    bool isAsyncMethod = false;\n    tokens tok;\n#if EXCEPTION_RECOVERY\n    ParseNodePtr pParentTryCatch = nullptr;\n    ParseNodePtr pTryBlock = nullptr;\n    ParseNodePtr pTry = nullptr;\n    ParseNodePtr pParentTryCatchBlock = nullptr;\n\n    StmtNest stmtTryCatchBlock;\n    StmtNest stmtTryCatch;\n    StmtNest stmtTry;\n    StmtNest stmtTryBlock;\n#endif\n\n    if (buildAST)\n    {\n#if EXCEPTION_RECOVERY\n        if(Js::Configuration::Global.flags.SwallowExceptions)\n        {\n            \/\/ If we're swallowing exceptions, surround this statement with a try\/catch block:\n            \/\/\n            \/\/   Before: x.y = 3;\n            \/\/   After:  try { x.y = 3; } catch(__ehobj) { }\n            \/\/\n            \/\/ This is done to force the runtime to recover from exceptions at the most granular\n            \/\/ possible point.  Recovering from EH dramatically improves coverage of testing via\n            \/\/ fault injection.\n\n\n            \/\/ create and push the try-catch node\n            pParentTryCatchBlock = CreateBlockNode();\n            PushStmt<buildAST>(&stmtTryCatchBlock, pParentTryCatchBlock, knopBlock, nullptr, nullptr);\n            pParentTryCatch = CreateNodeWithScanner<knopTryCatch>();\n            PushStmt<buildAST>(&stmtTryCatch, pParentTryCatch, knopTryCatch, nullptr, nullptr);\n\n            \/\/ create and push a try node\n            pTry = CreateNodeWithScanner<knopTry>();\n            PushStmt<buildAST>(&stmtTry, pTry, knopTry, nullptr, nullptr);\n            pTryBlock = CreateBlockNode();\n            PushStmt<buildAST>(&stmtTryBlock, pTryBlock, knopBlock, nullptr, nullptr);\n            \/\/ these nodes will be closed after the statement is parsed.\n        }\n#endif \/\/ EXCEPTION_RECOVERY\n    }\n\n    EnsureStackAvailable();\n\nLRestart:\n    tok = m_token.tk;\n\n    switch (tok)\n    {\n    case tkEOF:\n        if (buildAST)\n        {\n            pnode = nullptr;\n        }\n        break;\n\n    case tkFUNCTION:\n    {\nLFunctionStatement:\n        if (m_grfscr & fscrDeferredFncExpression)\n        {\n            \/\/ The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now\n            \/\/ parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the\n            \/\/ first time we see it.\n            m_grfscr &= ~fscrDeferredFncExpression;\n            pnode = ParseFncDecl<buildAST>(isAsyncMethod ? fFncAsync : fFncNoFlgs, nullptr);\n        }\n        else\n        {\n            pnode = ParseFncDecl<buildAST>(fFncDeclaration | (isAsyncMethod ? fFncAsync : fFncNoFlgs), nullptr);\n        }\n        if (isAsyncMethod)\n        {\n            pnode->sxFnc.cbMin = iecpMin;\n            pnode->ichMin = ichMin;\n        }\n        break;\n    }\n\n    case tkCLASS:\n        if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())\n        {\n            pnode = ParseClassDecl<buildAST>(TRUE, nullptr, nullptr, nullptr);\n        }\n        else\n        {\n            goto LDefaultToken;\n        }\n        break;\n\n    case tkID:\n        if (m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.let)\n        {\n            \/\/ We see \"let\" at the start of a statement. This could either be a declaration or an identifier\n            \/\/ reference. The next token determines which.\n            RestorePoint parsedLet;\n            m_pscan->Capture(&parsedLet);\n            ichMin = m_pscan->IchMinTok();\n\n            m_pscan->Scan();\n            if (this->NextTokenConfirmsLetDecl())\n            {\n                pnode = ParseVariableDeclaration<buildAST>(tkLET, ichMin);\n                goto LNeedTerminator;\n            }\n            m_pscan->SeekTo(parsedLet);\n        }\n        else if (m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())\n        {\n            RestorePoint parsedAsync;\n            m_pscan->Capture(&parsedAsync);\n            ichMin = m_pscan->IchMinTok();\n            iecpMin = m_pscan->IecpMinTok();\n\n            m_pscan->Scan();\n            if (m_token.tk == tkFUNCTION && !m_pscan->FHadNewLine())\n            {\n                isAsyncMethod = true;\n                goto LFunctionStatement;\n            }\n            m_pscan->SeekTo(parsedAsync);\n        }\n        goto LDefaultToken;\n\n    case tkCONST:\n    case tkLET:\n        ichMin = m_pscan->IchMinTok();\n\n        m_pscan->Scan();\n        pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);\n        goto LNeedTerminator;\n\n    case tkVAR:\n        ichMin = m_pscan->IchMinTok();\n\n        m_pscan->Scan();\n        pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);\n        goto LNeedTerminator;\n\n    case tkFOR:\n    {\n        ParseNodePtr pnodeBlock = nullptr;\n        ParseNodePtr *ppnodeScopeSave = nullptr;\n        ParseNodePtr *ppnodeExprScopeSave = nullptr;\n\n        ichMin = m_pscan->IchMinTok();\n        ChkNxtTok(tkLParen, ERRnoLparen);\n        pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);\n        if (buildAST)\n        {\n            PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);\n        }\n\n        RestorePoint startExprOrIdentifier;\n        fForInOrOfOkay = TRUE;\n        fCanAssign = TRUE;\n        tok = m_token.tk;\n        BOOL nativeForOkay = TRUE;\n\n        switch (tok)\n        {\n        case tkID:\n            if (m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.let)\n            {\n                \/\/ We see \"let\" in the init part of a for loop. This could either be a declaration or an identifier\n                \/\/ reference. The next token determines which.\n                RestorePoint parsedLet;\n                m_pscan->Capture(&parsedLet);\n                auto ichMinInner = m_pscan->IchMinTok();\n\n                m_pscan->Scan();\n                if (IsPossiblePatternStart())\n                {\n                    m_pscan->Capture(&startExprOrIdentifier);\n                }\n                if (this->NextTokenConfirmsLetDecl() && m_token.tk != tkIN)\n                {\n                    pnodeT = ParseVariableDeclaration<buildAST>(tkLET, ichMinInner\n                                                                , \/*fAllowIn = *\/FALSE\n                                                                , \/*pfForInOk = *\/&fForInOrOfOkay\n                                                                , \/*singleDefOnly*\/FALSE\n                                                                , \/*allowInit*\/TRUE\n                                                                , \/*isTopVarParse*\/TRUE\n                                                                , \/*isFor*\/TRUE\n                                                                , &nativeForOkay);\n                    break;\n                }\n                m_pscan->SeekTo(parsedLet);\n            }\n            goto LDefaultTokenFor;\n        case tkLET:\n        case tkCONST:\n        case tkVAR:\n            {\n                auto ichMinInner = m_pscan->IchMinTok();\n\n                m_pscan->Scan();\n                if (IsPossiblePatternStart())\n                {\n                    m_pscan->Capture(&startExprOrIdentifier);\n                }\n                pnodeT = ParseVariableDeclaration<buildAST>(tok, ichMinInner\n                                                            , \/*fAllowIn = *\/FALSE\n                                                            , \/*pfForInOk = *\/&fForInOrOfOkay\n                                                            , \/*singleDefOnly*\/FALSE\n                                                            , \/*allowInit*\/TRUE\n                                                            , \/*isTopVarParse*\/TRUE\n                                                            , \/*isFor*\/TRUE\n                                                            , &nativeForOkay);\n            }\n            break;\n        case tkSColon:\n            pnodeT = nullptr;\n            fForInOrOfOkay = FALSE;\n            break;\n        default:\n            {\nLDefaultTokenFor:\n               RestorePoint exprStart;\n                tokens beforeToken = tok;\n                m_pscan->Capture(&exprStart);\n                if (IsPossiblePatternStart())\n                {\n                    m_pscan->Capture(&startExprOrIdentifier);\n                }\n                bool fLikelyPattern = false;\n                if (IsES6DestructuringEnabled() && (beforeToken == tkLBrack || beforeToken == tkLCurly))\n                {\n                    pnodeT = ParseExpr<buildAST>(koplNo,\n                        &fCanAssign,\n                        \/*fAllowIn = *\/FALSE,\n                        \/*fAllowEllipsis*\/FALSE,\n                        \/*pHint*\/nullptr,\n                        \/*pHintLength*\/nullptr,\n                        \/*pShortNameOffset*\/nullptr,\n                        \/*pToken*\/nullptr,\n                        \/**fUnaryOrParen*\/false,\n                        &fLikelyPattern);\n                }\n                else\n                {\n                    pnodeT = ParseExpr<buildAST>(koplNo, &fCanAssign, \/*fAllowIn = *\/FALSE);\n                }\n\n                \/\/ We would veryfiy the grammar as destructuring grammar only when  for..in\/of case. As in the native for loop case the above ParseExpr call\n                \/\/ has already converted them appropriately.\n                if (fLikelyPattern && TokIsForInOrForOf())\n                {\n                    m_pscan->SeekTo(exprStart);\n                    ParseDestructuredLiteralWithScopeSave(tkNone, false\/*isDecl*\/, false \/*topLevel*\/, DIC_None, false \/*allowIn*\/);\n\n                    if (buildAST)\n                    {\n                        pnodeT = ConvertToPattern(pnodeT);\n                    }\n                }\n                if (buildAST)\n                {\n                    Assert(pnodeT);\n                    pnodeT->isUsed = false;\n                }\n            }\n            break;\n        }\n\n        if (TokIsForInOrForOf())\n        {\n            bool isForOf = (m_token.tk != tkIN);\n            Assert(!isForOf || (m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.of));\n\n            if ((buildAST && nullptr == pnodeT) || !fForInOrOfOkay)\n            {\n                if (isForOf)\n                {\n                    Error(ERRForOfNoInitAllowed);\n                }\n                else\n                {\n                    Error(ERRForInNoInitAllowed);\n                }\n            }\n            if (!fCanAssign && PHASE_ON1(Js::EarlyReferenceErrorsPhase))\n            {\n                Error(JSERR_CantAssignTo);\n            }\n\n            m_pscan->Scan();\n            ParseNodePtr pnodeObj = ParseExpr<buildAST>(isForOf ? koplCma : koplNo);\n            charcount_t ichLim = m_pscan->IchLimTok();\n            ChkCurTok(tkRParen, ERRnoRparen);\n\n            if (buildAST)\n            {\n                if (isForOf)\n                {\n                    pnode = CreateNodeWithScanner<knopForOf>(ichMin);\n                }\n                else\n                {\n                    pnode = CreateNodeWithScanner<knopForIn>(ichMin);\n                }\n                pnode->sxForInOrForOf.pnodeBlock = pnodeBlock;\n                pnode->sxForInOrForOf.pnodeLval = pnodeT;\n                pnode->sxForInOrForOf.pnodeObj = pnodeObj;\n                pnode->ichLim = ichLim;\n                \n                TrackAssignment<true>(pnodeT, nullptr);\n            }\n            PushStmt<buildAST>(&stmt, pnode, isForOf ? knopForOf : knopForIn, pnodeLabel, pLabelIdList);\n            ParseNodePtr pnodeBody = ParseStatement<buildAST>();\n\n            if (buildAST)\n            {\n                pnode->sxForInOrForOf.pnodeBody = pnodeBody;\n            }\n            PopStmt(&stmt);\n        }\n        else\n        {\n            if (!nativeForOkay)\n            {\n                Error(ERRDestructInit);\n            }\n\n            ChkCurTok(tkSColon, ERRnoSemic);\n            ParseNodePtr pnodeCond = nullptr;\n            if (m_token.tk != tkSColon)\n            {\n                pnodeCond = ParseExpr<buildAST>();\n                if (m_token.tk != tkSColon)\n                {\n                    Error(ERRnoSemic);\n                }\n            }\n\n            tokens tk;\n            tk = m_pscan->Scan();\n\n            ParseNodePtr pnodeIncr = nullptr;\n            if (tk != tkRParen)\n            {\n                pnodeIncr = ParseExpr<buildAST>();\n                if(pnodeIncr)\n                {\n                    pnodeIncr->isUsed = false;\n                }\n            }\n\n            charcount_t ichLim = m_pscan->IchLimTok();\n\n            ChkCurTok(tkRParen, ERRnoRparen);\n\n            if (buildAST)\n            {\n                pnode = CreateNodeWithScanner<knopFor>(ichMin);\n                pnode->sxFor.pnodeBlock = pnodeBlock;\n                pnode->sxFor.pnodeInverted= nullptr;\n                pnode->sxFor.pnodeInit = pnodeT;\n                pnode->sxFor.pnodeCond = pnodeCond;\n                pnode->sxFor.pnodeIncr = pnodeIncr;\n                pnode->ichLim = ichLim;\n            }\n            PushStmt<buildAST>(&stmt, pnode, knopFor, pnodeLabel, pLabelIdList);\n            ParseNodePtr pnodeBody = ParseStatement<buildAST>();\n            if (buildAST)\n            {\n                pnode->sxFor.pnodeBody = pnodeBody;\n            }\n            PopStmt(&stmt);\n        }\n\n        if (buildAST)\n        {\n            PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);\n        }\n\n        FinishParseBlock(pnodeBlock);\n\n        break;\n    }\n\n    case tkSWITCH:\n    {\n        BOOL fSeenDefault = FALSE;\n        ParseNodePtr pnodeBlock = nullptr;\n        ParseNodePtr *ppnodeScopeSave = nullptr;\n        ParseNodePtr *ppnodeExprScopeSave = nullptr;\n\n        ichMin = m_pscan->IchMinTok();\n        ChkNxtTok(tkLParen, ERRnoLparen);\n        ParseNodePtr pnodeVal = ParseExpr<buildAST>();\n        charcount_t ichLim = m_pscan->IchLimTok();\n\n        ChkCurTok(tkRParen, ERRnoRparen);\n        ChkCurTok(tkLCurly, ERRnoLcurly);\n\n        if (buildAST)\n        {\n            pnode = CreateNodeWithScanner<knopSwitch>(ichMin);\n        }\n        PushStmt<buildAST>(&stmt, pnode, knopSwitch, pnodeLabel, pLabelIdList);\n        pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block, nullptr, pLabelIdList);\n\n        if (buildAST)\n        {\n            pnode->sxSwitch.pnodeVal = pnodeVal;\n            pnode->sxSwitch.pnodeBlock = pnodeBlock;\n            pnode->ichLim = ichLim;\n            PushFuncBlockScope(pnode->sxSwitch.pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);\n\n            pnode->sxSwitch.pnodeDefault = nullptr;\n            ppnodeT = &pnode->sxSwitch.pnodeCases;\n        }\n\n        for (;;)\n        {\n            ParseNodePtr pnodeBody = nullptr;\n            switch (m_token.tk)\n            {\n            default:\n                goto LEndSwitch;\n            case tkCASE:\n            {\n                pnodeT = this->ParseCase<buildAST>(&pnodeBody);\n                break;\n            }\n            case tkDEFAULT:\n                if (fSeenDefault)\n                {\n                    Error(ERRdupDefault);\n                    \/\/ No recovery necessary since this is a semantic, not structural, error\n                }\n                fSeenDefault = TRUE;\n                charcount_t ichMinT = m_pscan->IchMinTok();\n                m_pscan->Scan();\n                charcount_t ichMinInner = m_pscan->IchLimTok();\n                ChkCurTok(tkColon, ERRnoColon);\n                if (buildAST)\n                {\n                    pnodeT = CreateNodeWithScanner<knopCase>(ichMinT);\n                    pnode->sxSwitch.pnodeDefault = pnodeT;\n                    pnodeT->ichLim = ichMinInner;\n                    pnodeT->sxCase.pnodeExpr = nullptr;\n                }\n                ParseStmtList<buildAST>(&pnodeBody);\n                break;\n            }\n            if (buildAST)\n            {\n                if (pnodeBody)\n                {\n                    \/\/ Create a block node to contain the statement list for this case.\n                    \/\/ This helps us insert byte code to return the right value from\n                    \/\/ global\/eval code.\n                    pnodeT->sxCase.pnodeBody = CreateBlockNode(pnodeT->ichMin, pnodeT->ichLim);\n                    pnodeT->sxCase.pnodeBody->grfpn |= PNodeFlags::fpnSyntheticNode; \/\/ block is not a user specifier block\n                    pnodeT->sxCase.pnodeBody->sxBlock.pnodeStmt = pnodeBody;\n                }\n                else\n                {\n                    pnodeT->sxCase.pnodeBody = nullptr;\n                }\n                *ppnodeT = pnodeT;\n                ppnodeT = &pnodeT->sxCase.pnodeNext;\n            }\n        }\nLEndSwitch:\n        ChkCurTok(tkRCurly, ERRnoRcurly);\n        if (buildAST)\n        {\n            *ppnodeT = nullptr;\n            PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);\n            FinishParseBlock(pnode->sxSwitch.pnodeBlock);\n        }\n        else\n        {\n            FinishParseBlock(pnodeBlock);\n        }\n        PopStmt(&stmt);\n\n        break;\n    }\n\n    case tkWHILE:\n    {\n        ichMin = m_pscan->IchMinTok();\n        ChkNxtTok(tkLParen, ERRnoLparen);\n        ParseNodePtr pnodeCond = ParseExpr<buildAST>();\n        charcount_t ichLim = m_pscan->IchLimTok();\n        ChkCurTok(tkRParen, ERRnoRparen);\n\n        if (buildAST)\n        {\n            pnode = CreateNodeWithScanner<knopWhile>(ichMin);\n            pnode->sxWhile.pnodeCond = pnodeCond;\n            pnode->ichLim = ichLim;\n        }\n        PushStmt<buildAST>(&stmt, pnode, knopWhile, pnodeLabel, pLabelIdList);\n        ParseNodePtr pnodeBody = ParseStatement<buildAST>();\n        PopStmt(&stmt);\n\n        if (buildAST)\n        {\n            pnode->sxWhile.pnodeBody = pnodeBody;\n        }\n        break;\n    }\n\n    case tkDO:\n    {\n        if (buildAST)\n        {\n            pnode = CreateNodeWithScanner<knopDoWhile>();\n        }\n        PushStmt<buildAST>(&stmt, pnode, knopDoWhile, pnodeLabel, pLabelIdList);\n        m_pscan->Scan();\n        ParseNodePtr pnodeBody = ParseStatement<buildAST>();\n        PopStmt(&stmt);\n        charcount_t ichMinT = m_pscan->IchMinTok();\n\n        ChkCurTok(tkWHILE, ERRnoWhile);\n        ChkCurTok(tkLParen, ERRnoLparen);\n\n        ParseNodePtr pnodeCond = ParseExpr<buildAST>();\n        charcount_t ichLim = m_pscan->IchLimTok();\n        ChkCurTok(tkRParen, ERRnoRparen);\n\n        if (buildAST)\n        {\n            pnode->sxWhile.pnodeBody = pnodeBody;\n            pnode->sxWhile.pnodeCond = pnodeCond;\n            pnode->ichLim = ichLim;\n            pnode->ichMin = ichMinT;\n        }\n\n        \/\/ REVIEW: Allow do...while statements to be embedded in other compound statements like if..else, or do..while?\n        \/\/      goto LNeedTerminator;\n\n        \/\/ For now just eat the trailing semicolon if present.\n        if (m_token.tk == tkSColon)\n        {\n            if (pnode)\n            {\n                pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;\n            }\n            m_pscan->Scan();\n        }\n        else if (pnode)\n        {\n            pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;\n        }\n\n        break;\n    }\n\n    case tkIF:\n    {\n        ichMin = m_pscan->IchMinTok();\n        ChkNxtTok(tkLParen, ERRnoLparen);\n        ParseNodePtr pnodeCond = ParseExpr<buildAST>();\n        if (buildAST)\n        {\n            pnode = CreateNodeWithScanner<knopIf>(ichMin);\n            pnode->ichLim = m_pscan->IchLimTok();\n            pnode->sxIf.pnodeCond = pnodeCond;\n        }\n        ChkCurTok(tkRParen, ERRnoRparen);\n\n        PushStmt<buildAST>(&stmt, pnode, knopIf, pnodeLabel, pLabelIdList);\n        ParseNodePtr pnodeTrue = ParseStatement<buildAST>();\n        ParseNodePtr pnodeFalse = nullptr;\n        if (m_token.tk == tkELSE)\n        {\n            m_pscan->Scan();\n            pnodeFalse = ParseStatement<buildAST>();\n        }\n        if (buildAST)\n        {\n            pnode->sxIf.pnodeTrue = pnodeTrue;\n            pnode->sxIf.pnodeFalse = pnodeFalse;\n        }\n        PopStmt(&stmt);\n        break;\n    }\n\n    case tkTRY:\n    {\n        if (buildAST)\n        {\n            pnode = CreateBlockNode();\n            pnode->grfpn |= PNodeFlags::fpnSyntheticNode; \/\/ block is not a user specifier block\n        }\n        PushStmt<buildAST>(&stmt, pnode, knopBlock, pnodeLabel, pLabelIdList);\n        ParseNodePtr pnodeStmt = ParseTryCatchFinally<buildAST>();\n        if (buildAST)\n        {\n            pnode->sxBlock.pnodeStmt = pnodeStmt;\n        }\n        PopStmt(&stmt);\n        break;\n    }\n\n    case tkWITH:\n    {\n        if ( IsStrictMode() )\n        {\n            Error(ERRES5NoWith);\n        }\n        if (m_currentNodeFunc)\n        {\n            GetCurrentFunctionNode()->sxFnc.SetHasWithStmt(); \/\/ Used by DeferNested\n        }\n\n        ichMin = m_pscan->IchMinTok();\n        ChkNxtTok(tkLParen, ERRnoLparen);\n        ParseNodePtr pnodeObj = ParseExpr<buildAST>();\n        if (!buildAST)\n        {\n            m_scopeCountNoAst++;\n        }\n        charcount_t ichLim = m_pscan->IchLimTok();\n        ChkCurTok(tkRParen, ERRnoRparen);\n\n        if (buildAST)\n        {\n            pnode = CreateNodeWithScanner<knopWith>(ichMin);\n        }\n        PushStmt<buildAST>(&stmt, pnode, knopWith, pnodeLabel, pLabelIdList);\n\n        ParseNodePtr *ppnodeExprScopeSave = nullptr;\n        if (buildAST)\n        {\n            pnode->sxWith.pnodeObj = pnodeObj;\n            this->CheckArguments(pnode->sxWith.pnodeObj);\n\n            if (m_ppnodeExprScope)\n            {\n                Assert(*m_ppnodeExprScope == nullptr);\n                *m_ppnodeExprScope = pnode;\n                m_ppnodeExprScope = &pnode->sxWith.pnodeNext;\n            }\n            else\n            {\n                Assert(m_ppnodeScope);\n                Assert(*m_ppnodeScope == nullptr);\n                *m_ppnodeScope = pnode;\n                m_ppnodeScope = &pnode->sxWith.pnodeNext;\n            }\n            pnode->sxWith.pnodeNext = nullptr;\n            pnode->sxWith.scope = nullptr;\n\n            ppnodeExprScopeSave = m_ppnodeExprScope;\n            m_ppnodeExprScope = &pnode->sxWith.pnodeScopes;\n            pnode->sxWith.pnodeScopes = nullptr;\n\n            pnode->ichLim = ichLim;\n        }\n\n        PushBlockInfo(CreateBlockNode());\n        PushDynamicBlock();\n\n        ParseNodePtr pnodeBody = ParseStatement<buildAST>();\n        if (buildAST)\n        {\n            pnode->sxWith.pnodeBody = pnodeBody;\n            m_ppnodeExprScope = ppnodeExprScopeSave;\n        }\n        else\n        {\n            m_scopeCountNoAst--;\n        }\n\n        \/\/ The dynamic block is not stored in the actual parse tree and so will not\n        \/\/ be visited by the byte code generator.  Grab the callsEval flag off it and\n        \/\/ pass on to outer block in case of:\n        \/\/ with (...) eval(...); \/\/ i.e. blockless form of with\n        bool callsEval = GetCurrentBlock()->sxBlock.GetCallsEval();\n        PopBlockInfo();\n        if (callsEval)\n        {\n            \/\/ be careful not to overwrite an existing true with false\n            GetCurrentBlock()->sxBlock.SetCallsEval(true);\n        }\n\n        PopStmt(&stmt);\n        break;\n    }\n\n    case tkLCurly:\n        pnode = ParseBlock<buildAST>(pnodeLabel, pLabelIdList);\n        break;\n\n    case tkSColon:\n        pnode = nullptr;\n        m_pscan->Scan();\n        break;\n\n    case tkBREAK:\n        if (buildAST)\n        {\n            pnode = CreateNodeWithScanner<knopBreak>();\n        }\n        fnop = fnopBreak;\n        goto LGetJumpStatement;\n\n    case tkCONTINUE:\n        if (buildAST)\n        {\n            pnode = CreateNode(knopContinue);\n        }\n        fnop = fnopContinue;\n\nLGetJumpStatement:\n        m_pscan->ScanForcingPid();\n        if (tkID == m_token.tk && !m_pscan->FHadNewLine())\n        {\n            \/\/ Labeled break or continue.\n            pid = m_token.GetIdentifier(m_phtbl);\n            AssertMem(pid);\n            if (buildAST)\n            {\n                pnode->sxJump.hasExplicitTarget=true;\n                pnode->ichLim = m_pscan->IchLimTok();\n\n                m_pscan->Scan();\n                PushStmt<buildAST>(&stmt, pnode, pnode->nop, pnodeLabel, nullptr);\n                Assert(pnode->sxStmt.grfnop == 0);\n                for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)\n                {\n                    AssertNodeMem(pstmt->pnodeStmt);\n                    AssertNodeMemN(pstmt->pnodeLab);\n                    for (pnodeT = pstmt->pnodeLab; nullptr != pnodeT;\n                         pnodeT = pnodeT->sxLabel.pnodeNext)\n                    {\n                        Assert(knopLabel == pnodeT->nop);\n                        if (pid == pnodeT->sxLabel.pid)\n                        {\n                            \/\/ Found the label. Make sure we can use it. We can\n                            \/\/ break out of any statement, but we can only\n                            \/\/ continue loops.\n                            if (fnop == fnopContinue &&\n                                !(pstmt->pnodeStmt->Grfnop() & fnop))\n                            {\n                                Error(ERRbadContinue);\n                            }\n                            else\n                            {\n                                pstmt->pnodeStmt->sxStmt.grfnop |= fnop;\n                                pnode->sxJump.pnodeTarget = pstmt->pnodeStmt;\n                            }\n                            PopStmt(&stmt);\n                            goto LNeedTerminator;\n                        }\n                    }\n                    pnode->sxStmt.grfnop |=\n                        (pstmt->pnodeStmt->Grfnop() & fnopCleanup);\n                }\n            }\n            else\n            {\n                m_pscan->Scan();\n                for (pstmt = m_pstmtCur; pstmt; pstmt = pstmt->pstmtOuter)\n                {\n                    LabelId* pLabelId;\n                    for (pLabelId = pstmt->pLabelId; pLabelId; pLabelId = pLabelId->next)\n                    {\n\n                        if (pid == pLabelId->pid)\n                        {\n                            \/\/ Found the label. Make sure we can use it. We can\n                            \/\/ break out of any statement, but we can only\n                            \/\/ continue loops.\n                            if (fnop == fnopContinue &&\n                                !(ParseNode::Grfnop(pstmt->op) & fnop))\n                            {\n                                Error(ERRbadContinue);\n                            }\n                            goto LNeedTerminator;\n                        }\n                    }\n                }\n            }\n            Error(ERRnoLabel);\n        }\n        else\n        {\n            \/\/ If we're doing a fast scan, we're not tracking labels, so we can't accurately do this analysis.\n            \/\/ Let the thread that's doing the full parse detect the error, if there is one.\n            if (!this->m_doingFastScan)\n            {\n                \/\/ Unlabeled break or continue.\n                if (buildAST)\n                {\n                    pnode->sxJump.hasExplicitTarget=false;\n                    PushStmt<buildAST>(&stmt, pnode, pnode->nop, pnodeLabel, nullptr);\n                    Assert(pnode->sxStmt.grfnop == 0);\n                }\n\n                for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)\n                {\n                    if (buildAST)\n                    {\n                        AnalysisAssert(pstmt->pnodeStmt);\n                        if (pstmt->pnodeStmt->Grfnop() & fnop)\n                        {\n                            pstmt->pnodeStmt->sxStmt.grfnop |= fnop;\n                            pnode->sxJump.pnodeTarget = pstmt->pnodeStmt;\n                            PopStmt(&stmt);\n                            goto LNeedTerminator;\n                        }\n                        pnode->sxStmt.grfnop |=\n                            (pstmt->pnodeStmt->Grfnop() & fnopCleanup);\n                    }\n                    else\n                    {\n                        if (pstmt->isDeferred)\n                        {\n                            if (ParseNode::Grfnop(pstmt->op) & fnop)\n                            {\n                                goto LNeedTerminator;\n                            }\n                        }\n                        else\n                        {\n                            AnalysisAssert(pstmt->pnodeStmt);\n                            if (pstmt->pnodeStmt->Grfnop() & fnop)\n                            {\n                                pstmt->pnodeStmt->sxStmt.grfnop |= fnop;\n                                goto LNeedTerminator;\n                            }\n                        }\n                    }\n                }\n                Error(fnop == fnopBreak ? ERRbadBreak : ERRbadContinue);\n            }\n            goto LNeedTerminator;\n        }\n\n    case tkRETURN:\n    {\n        if (buildAST)\n        {\n            if (nullptr == m_currentNodeFunc)\n            {\n                Error(ERRbadReturn);\n            }\n            pnode = CreateNodeWithScanner<knopReturn>();\n        }\n        m_pscan->Scan();\n        ParseNodePtr pnodeExpr = nullptr;\n        ParseOptionalExpr<buildAST>(&pnodeExpr, true);\n        if (buildAST)\n        {\n            pnode->sxReturn.pnodeExpr = pnodeExpr;\n            if (pnodeExpr)\n            {\n                this->CheckArguments(pnode->sxReturn.pnodeExpr);\n                pnode->ichLim = pnode->sxReturn.pnodeExpr->ichLim;\n            }\n            \/\/ See if return should call finally\n            PushStmt<buildAST>(&stmt, pnode, knopReturn, pnodeLabel, nullptr);\n            Assert(pnode->sxStmt.grfnop == 0);\n            for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)\n            {\n                AssertNodeMem(pstmt->pnodeStmt);\n                AssertNodeMemN(pstmt->pnodeLab);\n                if (pstmt->pnodeStmt->Grfnop() & fnopCleanup)\n                {\n                    pnode->sxStmt.grfnop |= fnopCleanup;\n                    break;\n                }\n            }\n            PopStmt(&stmt);\n        }\n        goto LNeedTerminator;\n    }\n\n    case tkTHROW:\n    {\n        if (buildAST)\n        {\n            pnode = CreateUniNode(knopThrow, nullptr);\n        }\n        m_pscan->Scan();\n        ParseNodePtr pnode1 = nullptr;\n        if (m_token.tk != tkSColon &&\n            m_token.tk != tkRCurly &&\n            !m_pscan->FHadNewLine())\n        {\n            pnode1 = ParseExpr<buildAST>();\n        }\n        else\n        {\n            Error(ERRdanglingThrow);\n        }\n\n        if (buildAST)\n        {\n            pnode->sxUni.pnode1 = pnode1;\n            if (pnode1)\n            {\n                this->CheckArguments(pnode->sxUni.pnode1);\n                pnode->ichLim = pnode->sxUni.pnode1->ichLim;\n            }\n        }\n        goto LNeedTerminator;\n    }\n\n    case tkDEBUGGER:\n        if (buildAST)\n        {\n            pnode = CreateNodeWithScanner<knopDebugger>();\n        }\n        m_pscan->Scan();\n        goto LNeedTerminator;\n\n    case tkIMPORT:\n        if (!(m_grfscr & fscrIsModuleCode))\n        {\n            goto LDefaultToken;\n        }\n\n        pnode = ParseImportDeclaration<buildAST>();\n\n        goto LNeedTerminator;\n\n    case tkEXPORT:\n        if (!(m_grfscr & fscrIsModuleCode))\n        {\n            goto LDefaultToken;\n        }\n\n        pnode = ParseExportDeclaration<buildAST>();\n\n        goto LNeedTerminator;\n\nLDefaultToken:\n    default:\n    {\n        \/\/ An expression statement or a label.\n        IdentToken tokInner;\n        pnode = ParseExpr<buildAST>(koplNo, nullptr, TRUE, FALSE, nullptr, nullptr \/*hintLength*\/, nullptr \/*hintOffset*\/, &tokInner);\n\n        if (m_hasDeferredShorthandInitError)\n        {\n            Error(ERRnoColon);\n        }\n\n        if (buildAST)\n        {\n            \/\/ Check for a label.\n            if (tkColon == m_token.tk &&\n                nullptr != pnode && knopName == pnode->nop)\n            {\n                \/\/ We have a label. See if it is already defined.\n                if (nullptr != PnodeLabel(pnode->sxPid.pid, pnodeLabel))\n                {\n                    Error(ERRbadLabel);\n                    \/\/ No recovery is necessary since this is a semantic, not structural, error\n                }\n                pnodeT = CreateNodeWithScanner<knopLabel>();\n                pnodeT->sxLabel.pid = pnode->sxPid.pid;\n                pnodeT->sxLabel.pnodeNext = pnodeLabel;\n                pnodeLabel = pnodeT;\n                m_pscan->Scan();\n                goto LRestart;\n            }\n\n            expressionStmt = true;\n\n            AnalysisAssert(pnode);\n            pnode->isUsed = false;\n        }\n        else\n        {\n            \/\/ Check for a label.\n            if (tkColon == m_token.tk && tokInner.tk == tkID)\n            {\n                tokInner.pid = m_pscan->PidAt(tokInner.ichMin, tokInner.ichLim);\n                if (PnodeLabelNoAST(&tokInner, pLabelIdList))\n                {\n                    Error(ERRbadLabel);\n                }\n                LabelId* pLabelId = CreateLabelId(&tokInner);\n                pLabelId->next = pLabelIdList;\n                pLabelIdList = pLabelId;\n                m_pscan->Scan();\n                goto LRestart;\n            }\n        }\n    }\n\nLNeedTerminator:\n        \/\/ Need a semicolon, new-line, } or end-of-file.\n        \/\/ We digest a semicolon if it's there.\n        switch (m_token.tk)\n        {\n        case tkSColon:\n            m_pscan->Scan();\n            if (pnode!= nullptr) pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;\n            break;\n        case tkEOF:\n        case tkRCurly:\n            if (pnode!= nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;\n            break;\n        default:\n            if (!m_pscan->FHadNewLine())\n            {\n                Error(ERRnoSemic);\n            }\n            else\n            {\n                if (pnode!= nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;\n            }\n            break;\n        }\n        break;\n    }\n\n    if (m_hasDeferredShorthandInitError)\n    {\n        Error(ERRnoColon);\n    }\n\n    if (buildAST)\n    {\n        \/\/ All non expression statements excluded from the \"this.x\" optimization\n        \/\/ Another check while parsing expressions\n        if (!expressionStmt)\n        {\n            if (m_currentNodeFunc)\n            {\n                m_currentNodeFunc->sxFnc.SetHasNonThisStmt();\n            }\n            else if (m_currentNodeProg)\n            {\n                m_currentNodeProg->sxFnc.SetHasNonThisStmt();\n            }\n        }\n\n#if EXCEPTION_RECOVERY\n        \/\/ close the try\/catch block\n        if(Js::Configuration::Global.flags.SwallowExceptions)\n        {\n            \/\/ pop the try block and fill in the body\n            PopStmt(&stmtTryBlock);\n            pTryBlock->sxBlock.pnodeStmt = pnode;\n            PopStmt(&stmtTry);\n            if(pnode != nullptr)\n            {\n                pTry->ichLim = pnode->ichLim;\n            }\n            pTry->sxTry.pnodeBody = pTryBlock;\n\n\n            \/\/ create a catch block with an empty body\n            StmtNest stmtCatch;\n            ParseNodePtr pCatch;\n            pCatch = CreateNodeWithScanner<knopCatch>();\n            PushStmt<buildAST>(&stmtCatch, pCatch, knopCatch, nullptr, nullptr);\n            pCatch->sxCatch.pnodeBody = nullptr;\n            if(pnode != nullptr)\n            {\n                pCatch->ichLim = pnode->ichLim;\n            }\n            pCatch->sxCatch.grfnop = 0;\n            pCatch->sxCatch.pnodeNext = nullptr;\n\n            \/\/ create a fake name for the catch var.\n            const WCHAR *uniqueNameStr = _u(\"__ehobj\");\n            IdentPtr uniqueName = m_phtbl->PidHashNameLen(uniqueNameStr, static_cast<int32>(wcslen(uniqueNameStr)));\n\n            pCatch->sxCatch.pnodeParam = CreateNameNode(uniqueName);\n\n            \/\/ Add this catch to the current list. We don't bother adjusting the catch and function expression\n            \/\/ lists here because the catch is just an empty statement.\n\n            if (m_ppnodeExprScope)\n            {\n                Assert(*m_ppnodeExprScope == nullptr);\n                *m_ppnodeExprScope = pCatch;\n                m_ppnodeExprScope = &pCatch->sxCatch.pnodeNext;\n            }\n            else\n            {\n                Assert(m_ppnodeScope);\n                Assert(*m_ppnodeScope == nullptr);\n                *m_ppnodeScope = pCatch;\n                m_ppnodeScope = &pCatch->sxCatch.pnodeNext;\n            }\n\n            pCatch->sxCatch.pnodeScopes = nullptr;\n\n            PopStmt(&stmtCatch);\n\n            \/\/ fill in and pop the try-catch\n            pParentTryCatch->sxTryCatch.pnodeTry = pTry;\n            pParentTryCatch->sxTryCatch.pnodeCatch = pCatch;\n            PopStmt(&stmtTryCatch);\n            PopStmt(&stmtTryCatchBlock);\n\n            \/\/ replace the node that's being returned\n            pParentTryCatchBlock->sxBlock.pnodeStmt = pParentTryCatch;\n            pnode = pParentTryCatchBlock;\n        }\n#endif \/\/ EXCEPTION_RECOVERY\n\n    }\n\n    return pnode;\n}\n\nBOOL\nParser::TokIsForInOrForOf()\n{\n    return m_token.tk == tkIN ||\n        (m_token.tk == tkID &&\n         m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.of);\n}\n\n\/***************************************************************************\nParse a sequence of statements.\n***************************************************************************\/\ntemplate<bool buildAST>\nvoid Parser::ParseStmtList(ParseNodePtr *ppnodeList, ParseNodePtr **pppnodeLast, StrictModeEnvironment smEnvironment, const bool isSourceElementList, bool* strictModeOn)\n{\n    BOOL doneDirectives = !isSourceElementList; \/\/ directives may only exist in a SourceElementList, not a StatementList\n    BOOL seenDirectiveContainingOctal = false; \/\/ Have we seen an octal directive before a use strict directive?\n\n    BOOL old_UseStrictMode = m_fUseStrictMode;\n\n    ParseNodePtr pnodeStmt;\n    ParseNodePtr *lastNodeRef = nullptr;\n\n    if (buildAST)\n    {\n        AssertMem(ppnodeList);\n        AssertMemN(pppnodeLast);\n        *ppnodeList = nullptr;\n    }\n\n    if(CONFIG_FLAG(ForceStrictMode))\n    {\n        m_fUseStrictMode = TRUE;\n    }\n\n    for (;;)\n    {\n        switch (m_token.tk)\n        {\n        case tkCASE:\n        case tkDEFAULT:\n        case tkRCurly:\n        case tkEOF:\n            if (buildAST && nullptr != pppnodeLast)\n            {\n                *pppnodeLast = lastNodeRef;\n            }\n            if (!buildAST)\n            {\n                m_fUseStrictMode = old_UseStrictMode;\n            }\n            return;\n        }\n\n        if (doneDirectives == FALSE)\n        {\n            bool isOctalInString = false;\n            bool isUseStrictDirective = false;\n            bool isUseAsmDirective = false;\n            if (smEnvironment != SM_NotUsed && CheckForDirective(&isUseStrictDirective, &isUseAsmDirective, &isOctalInString))\n            {\n                \/\/ Ignore \"use asm\" statement when not building the AST\n                isUseAsmDirective &= buildAST;\n\n                if (isUseStrictDirective)\n                {\n                    \/\/ Functions with non-simple parameter list cannot be made strict mode\n                    if (GetCurrentFunctionNode()->sxFnc.HasNonSimpleParameterList())\n                    {\n                        Error(ERRNonSimpleParamListInStrictMode);\n                    }\n\n                    if (seenDirectiveContainingOctal)\n                    {\n                        \/\/ Directives seen before a \"use strict\" cannot contain an octal.\n                        Error(ERRES5NoOctal);\n                    }\n                    if (!buildAST)\n                    {\n                        \/\/ Turning on strict mode in deferred code.\n                        m_fUseStrictMode = TRUE;\n                        if (!m_inDeferredNestedFunc)\n                        {\n                            \/\/ Top-level deferred function, so there's a parse node\n                            Assert(m_currentNodeFunc != nullptr);\n                            m_currentNodeFunc->sxFnc.SetStrictMode();\n                        }\n                        else if (strictModeOn)\n                        {\n                            \/\/ This turns on strict mode in a deferred function, we need to go back\n                            \/\/ and re-check duplicated formals.\n                            *strictModeOn = true;\n                        }\n                    }\n                    else\n                    {\n                        if (smEnvironment == SM_OnGlobalCode)\n                        {\n                            \/\/ Turning on strict mode at the top level\n                            m_fUseStrictMode = TRUE;\n                        }\n                        else\n                        {\n                            \/\/ i.e. smEnvironment == SM_OnFunctionCode\n                            Assert(m_currentNodeFunc != nullptr);\n                            m_currentNodeFunc->sxFnc.SetStrictMode();\n                        }\n                    }\n                }\n                else if (isUseAsmDirective)\n                {\n                    if (smEnvironment != SM_OnGlobalCode) \/\/Top level use asm doesn't mean anything.\n                    {\n                        \/\/ i.e. smEnvironment == SM_OnFunctionCode\n                        Assert(m_currentNodeFunc != nullptr);\n                        m_currentNodeFunc->sxFnc.SetAsmjsMode();\n                        m_InAsmMode = true;\n\n                        CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(AsmJSFunctionCount, m_scriptContext);\n                    }\n                }\n                else if (isOctalInString)\n                {\n                    seenDirectiveContainingOctal = TRUE;\n                }\n            }\n            else\n            {\n                \/\/ The first time we see anything other than a directive we can have no more directives.\n                doneDirectives = TRUE;\n            }\n        }\n\n        if (nullptr != (pnodeStmt = ParseStatement<buildAST>()))\n        {\n            if (buildAST)\n            {\n                AddToNodeList(ppnodeList, &lastNodeRef, pnodeStmt);\n            }\n        }\n    }\n}\n\ntemplate <class Fn>\nvoid Parser::VisitFunctionsInScope(ParseNodePtr pnodeScopeList, Fn fn)\n{\n    ParseNodePtr pnodeScope;\n    for (pnodeScope = pnodeScopeList; pnodeScope;)\n    {\n        switch (pnodeScope->nop)\n        {\n        case knopBlock:\n            VisitFunctionsInScope(pnodeScope->sxBlock.pnodeScopes, fn);\n            pnodeScope = pnodeScope->sxBlock.pnodeNext;\n            break;\n\n        case knopFncDecl:\n            fn(pnodeScope);\n            pnodeScope = pnodeScope->sxFnc.pnodeNext;\n            break;\n\n        case knopCatch:\n            VisitFunctionsInScope(pnodeScope->sxCatch.pnodeScopes, fn);\n            pnodeScope = pnodeScope->sxCatch.pnodeNext;\n            break;\n\n        case knopWith:\n            VisitFunctionsInScope(pnodeScope->sxWith.pnodeScopes, fn);\n            pnodeScope = pnodeScope->sxWith.pnodeNext;\n            break;\n\n        default:\n            AssertMsg(false, \"Unexpected node with scope list\");\n            return;\n        }\n    }\n}\n\n\/\/ Scripts above this size (minus string literals and comments) will have parsing of\n\/\/ function bodies deferred.\nULONG Parser::GetDeferralThreshold(bool isProfileLoaded)\n{\n#ifdef ENABLE_DEBUG_CONFIG_OPTIONS\n    if (CONFIG_FLAG(ForceDeferParse) ||\n        PHASE_FORCE1(Js::DeferParsePhase) ||\n        Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))\n    {\n        return 0;\n    }\n    else if (Js::Configuration::Global.flags.IsEnabled(Js::DeferParseFlag))\n    {\n        return Js::Configuration::Global.flags.DeferParse;\n    }\n    else\n#endif\n    {\n        if (isProfileLoaded)\n        {\n            return DEFAULT_CONFIG_ProfileBasedDeferParseThreshold;\n        }\n        return DEFAULT_CONFIG_DeferParseThreshold;\n    }\n}\n\nvoid Parser::FinishDeferredFunction(ParseNodePtr pnodeScopeList)\n{\n    VisitFunctionsInScope(pnodeScopeList,\n        [this](ParseNodePtr pnodeFnc)\n    {\n        Assert(pnodeFnc->nop == knopFncDecl);\n\n        \/\/ Non-simple params (such as default) require a good amount of logic to put vars on appriopriate scopes. ParseFncDecl handles it\n        \/\/ properly (both on defer and non-defer case). This is to avoid write duplicated logic here as well. Function with non-simple-param\n        \/\/ will remain deferred untill they are called.\n        if (pnodeFnc->sxFnc.pnodeBody == nullptr && !pnodeFnc->sxFnc.HasNonSimpleParameterList())\n        {\n            \/\/ Go back and generate an AST for this function.\n            JS_ETW(EventWriteJSCRIPT_PARSE_FUNC(this->GetScriptContext(), pnodeFnc->sxFnc.functionId, \/*Undefer*\/TRUE));\n\n            ParseNodePtr pnodeFncSave = this->m_currentNodeFunc;\n            this->m_currentNodeFunc = pnodeFnc;\n\n            ParseNodePtr pnodeFncExprBlock = nullptr;\n            if (pnodeFnc->sxFnc.pnodeName &&\n                !pnodeFnc->sxFnc.IsDeclaration())\n            {\n                \/\/ Set up the named function expression symbol so references inside the function can be bound.\n                ParseNodePtr pnodeName = pnodeFnc->sxFnc.pnodeName;\n                Assert(pnodeName->nop == knopVarDecl);\n                Assert(pnodeName->sxVar.pnodeNext == nullptr);\n\n                pnodeFncExprBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FuncExpr);\n                PidRefStack *ref = this->PushPidRef(pnodeName->sxVar.pid);\n                pnodeName->sxVar.symRef = ref->GetSymRef();\n                ref->SetSym(pnodeName->sxVar.sym);\n\n                Scope *fncExprScope = pnodeFncExprBlock->sxBlock.scope;\n                fncExprScope->AddNewSymbol(pnodeName->sxVar.sym);\n                pnodeFnc->sxFnc.scope = fncExprScope;\n            }\n\n            ParseNodePtr pnodeBlock = this->StartParseBlock<true>(PnodeBlockType::Parameter, ScopeType_Parameter);\n            pnodeFnc->sxFnc.pnodeScopes = pnodeBlock;\n            m_ppnodeScope = &pnodeBlock->sxBlock.pnodeScopes;\n            pnodeBlock->sxBlock.pnodeStmt = pnodeFnc;\n\n            \/\/ Add the args to the scope, since we won't re-parse those.\n            Scope *scope = pnodeBlock->sxBlock.scope;\n            auto addArgsToScope = [&](ParseNodePtr pnodeArg) {\n                if (pnodeArg->IsVarLetOrConst())\n                {\n                    PidRefStack *ref = this->PushPidRef(pnodeArg->sxVar.pid);\n                    pnodeArg->sxVar.symRef = ref->GetSymRef();\n                    if (ref->GetSym() != nullptr)\n                    {\n                        \/\/ Duplicate parameter in a configuration that allows them.\n                        \/\/ The symbol is already in the scope, just point it to the right declaration.\n                        Assert(ref->GetSym() == pnodeArg->sxVar.sym);\n                        ref->GetSym()->SetDecl(pnodeArg);\n                    }\n                    else\n                    {\n                        ref->SetSym(pnodeArg->sxVar.sym);\n                        scope->AddNewSymbol(pnodeArg->sxVar.sym);\n                    }\n                }\n            };\n            MapFormals(pnodeFnc, addArgsToScope);\n            MapFormalsFromPattern(pnodeFnc, addArgsToScope);\n\n            ParseNodePtr pnodeInnerBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);\n            pnodeFnc->sxFnc.pnodeBodyScope = pnodeInnerBlock;\n\n            \/\/ Set the parameter block's child to the function body block.\n            *m_ppnodeScope = pnodeInnerBlock;\n\n            ParseNodePtr *ppnodeScopeSave = nullptr;\n            ParseNodePtr *ppnodeExprScopeSave = nullptr;\n\n            ppnodeScopeSave = m_ppnodeScope;\n\n            \/\/ This synthetic block scope will contain all the nested scopes.\n            m_ppnodeScope = &pnodeInnerBlock->sxBlock.pnodeScopes;\n            pnodeInnerBlock->sxBlock.pnodeStmt = pnodeFnc;\n\n            \/\/ Keep nested function declarations and expressions in the same list at function scope.\n            \/\/ (Indicate this by nulling out the current function expressions list.)\n            ppnodeExprScopeSave = m_ppnodeExprScope;\n            m_ppnodeExprScope = nullptr;\n\n            \/\/ Shouldn't be any temps in the arg list.\n            Assert(*m_ppnodeVar == nullptr);\n\n            \/\/ Start the var list.\n            pnodeFnc->sxFnc.pnodeVars = nullptr;\n            m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;\n\n            if (scope != nullptr && !pnodeFnc->sxFnc.IsAsync())\n            {\n                if (scope->GetCanMergeWithBodyScope())\n                {\n                    scope->ForEachSymbol([this](Symbol* paramSym)\n                    {\n                        PidRefStack* ref = PushPidRef(paramSym->GetPid());\n                        ref->SetSym(paramSym);\n                    });\n                }\n                else\n                {\n                    OUTPUT_TRACE_DEBUGONLY(Js::ParsePhase, _u(\"The param and body scope of the function %s cannot be merged\\n\"), pnodeFnc->sxFnc.pnodeName ? pnodeFnc->sxFnc.pnodeName->sxVar.pid->Psz() : _u(\"Anonymous function\"));\n                    \/\/ Add a new symbol reference for each formal in the param scope to the body scope.\n                    scope->ForEachSymbol([this](Symbol* param) {\n                        OUTPUT_TRACE_DEBUGONLY(Js::ParsePhase, _u(\"Creating a duplicate symbol for the parameter %s in the body scope\\n\"), param->GetPid()->Psz());\n                        ParseNodePtr paramNode = this->CreateVarDeclNode(param->GetPid(), STVariable, false, nullptr, false);\n                        Assert(paramNode && paramNode->sxVar.sym->GetScope()->GetScopeType() == ScopeType_FunctionBody);\n                        paramNode->sxVar.sym->SetHasInit(true);\n                    });\n                }\n            }\n\n            Assert(m_currentNodeNonLambdaFunc == nullptr);\n            m_currentNodeNonLambdaFunc = pnodeFnc;\n\n            this->FinishFncNode(pnodeFnc);\n\n            Assert(pnodeFnc == m_currentNodeNonLambdaFunc);\n            m_currentNodeNonLambdaFunc = nullptr;\n\n            m_ppnodeExprScope = ppnodeExprScopeSave;\n\n            AssertMem(m_ppnodeScope);\n            Assert(nullptr == *m_ppnodeScope);\n            m_ppnodeScope = ppnodeScopeSave;\n\n            this->FinishParseBlock(pnodeInnerBlock);\n\n            this->AddArgumentsNodeToVars(pnodeFnc);\n\n            this->FinishParseBlock(pnodeBlock);\n            if (pnodeFncExprBlock)\n            {\n                this->FinishParseBlock(pnodeFncExprBlock);\n            }\n\n            this->m_currentNodeFunc = pnodeFncSave;\n        }\n    });\n}\n\nvoid Parser::InitPids()\n{\n    AssertMemN(m_phtbl);\n    wellKnownPropertyPids.arguments = m_phtbl->PidHashNameLen(g_ssym_arguments.sz, g_ssym_arguments.cch);\n    wellKnownPropertyPids.async = m_phtbl->PidHashNameLen(g_ssym_async.sz, g_ssym_async.cch);\n    wellKnownPropertyPids.eval = m_phtbl->PidHashNameLen(g_ssym_eval.sz, g_ssym_eval.cch);\n    wellKnownPropertyPids.get = m_phtbl->PidHashNameLen(g_ssym_get.sz, g_ssym_get.cch);\n    wellKnownPropertyPids.set = m_phtbl->PidHashNameLen(g_ssym_set.sz, g_ssym_set.cch);\n    wellKnownPropertyPids.let = m_phtbl->PidHashNameLen(g_ssym_let.sz, g_ssym_let.cch);\n    wellKnownPropertyPids.constructor = m_phtbl->PidHashNameLen(g_ssym_constructor.sz, g_ssym_constructor.cch);\n    wellKnownPropertyPids.prototype = m_phtbl->PidHashNameLen(g_ssym_prototype.sz, g_ssym_prototype.cch);\n    wellKnownPropertyPids.__proto__ = m_phtbl->PidHashNameLen(_u(\"__proto__\"), sizeof(\"__proto__\") - 1);\n    wellKnownPropertyPids.of = m_phtbl->PidHashNameLen(_u(\"of\"), sizeof(\"of\") - 1);\n    wellKnownPropertyPids.target = m_phtbl->PidHashNameLen(_u(\"target\"), sizeof(\"target\") - 1);\n    wellKnownPropertyPids.as = m_phtbl->PidHashNameLen(_u(\"as\"), sizeof(\"as\") - 1);\n    wellKnownPropertyPids.from = m_phtbl->PidHashNameLen(_u(\"from\"), sizeof(\"from\") - 1);\n    wellKnownPropertyPids._default = m_phtbl->PidHashNameLen(_u(\"default\"), sizeof(\"default\") - 1);\n    wellKnownPropertyPids._starDefaultStar = m_phtbl->PidHashNameLen(_u(\"*default*\"), sizeof(\"*default*\") - 1);\n    wellKnownPropertyPids._star = m_phtbl->PidHashNameLen(_u(\"*\"), sizeof(\"*\") - 1);\n}\n\nvoid Parser::RestoreScopeInfo(Js::FunctionBody* functionBody)\n{\n    if (!functionBody)\n    {\n        return;\n    }\n\n    Js::ScopeInfo* scopeInfo = functionBody->GetScopeInfo();\n    if (!scopeInfo)\n    {\n        return;\n    }\n\n    if (this->IsBackgroundParser())\n    {\n        PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);\n    }\n    else\n    {\n        PROBE_STACK(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);\n    }\n\n    RestoreScopeInfo(scopeInfo->GetParent()); \/\/ Recursively restore outer func scope info\n\n    Js::ScopeInfo* funcExprScopeInfo = scopeInfo->GetFuncExprScopeInfo();\n    if (funcExprScopeInfo)\n    {\n        funcExprScopeInfo->SetScopeId(m_nextBlockId);\n        ParseNodePtr pnodeFncExprScope = StartParseBlockWithCapacity<true>(PnodeBlockType::Function, ScopeType_FuncExpr, funcExprScopeInfo->GetSymbolCount());\n        Scope *scope = pnodeFncExprScope->sxBlock.scope;\n        funcExprScopeInfo->GetScopeInfo(this, nullptr, nullptr, scope);\n    }\n\n    Js::ScopeInfo* paramScopeInfo = scopeInfo->GetParamScopeInfo();\n    if (paramScopeInfo)\n    {\n        paramScopeInfo->SetScopeId(m_nextBlockId);\n        ParseNodePtr pnodeFncExprScope = StartParseBlockWithCapacity<true>(PnodeBlockType::Parameter, ScopeType_Parameter, paramScopeInfo->GetSymbolCount());\n        Scope *scope = pnodeFncExprScope->sxBlock.scope;\n        paramScopeInfo->GetScopeInfo(this, nullptr, nullptr, scope);\n    }\n\n    scopeInfo->SetScopeId(m_nextBlockId);\n    ParseNodePtr pnodeFncScope = nullptr;\n    if (scopeInfo->IsGlobalEval())\n    {\n        pnodeFncScope = StartParseBlockWithCapacity<true>(PnodeBlockType::Regular, ScopeType_GlobalEvalBlock, scopeInfo->GetSymbolCount());\n    }\n    else\n    {\n        pnodeFncScope = StartParseBlockWithCapacity<true>(PnodeBlockType::Function, ScopeType_FunctionBody, scopeInfo->GetSymbolCount());\n    }\n    Scope *scope = pnodeFncScope->sxBlock.scope;\n    scopeInfo->GetScopeInfo(this, nullptr, nullptr, scope);\n}\n\nvoid Parser::FinishScopeInfo(Js::FunctionBody *functionBody)\n{\n    if (!functionBody)\n    {\n        return;\n    }\n\n    Js::ScopeInfo* scopeInfo = functionBody->GetScopeInfo();\n    if (!scopeInfo)\n    {\n        return;\n    }\n\n    if (this->IsBackgroundParser())\n    {\n        PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);\n    }\n    else\n    {\n        PROBE_STACK(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);\n    }\n\n    int scopeId = scopeInfo->GetScopeId();\n\n    scopeInfo->GetScope()->ForEachSymbol([this, scopeId](Symbol *sym)\n    {\n        this->BindPidRefsInScope(sym->GetPid(), sym, scopeId);\n    });\n    PopScope(scopeInfo->GetScope());\n    PopStmt(&m_currentBlockInfo->pstmt);\n    PopBlockInfo();\n\n    Js::ScopeInfo *paramScopeInfo = scopeInfo->GetParamScopeInfo();\n    if (paramScopeInfo)\n    {\n        scopeId = paramScopeInfo->GetScopeId();\n        paramScopeInfo->GetScope()->ForEachSymbol([this, scopeId](Symbol *sym)\n        {\n            this->BindPidRefsInScope(sym->GetPid(), sym, scopeId);\n        });\n        PopScope(paramScopeInfo->GetScope());\n        PopStmt(&m_currentBlockInfo->pstmt);\n        PopBlockInfo();\n    }\n\n    Js::ScopeInfo *funcExprScopeInfo = scopeInfo->GetFuncExprScopeInfo();\n    if (funcExprScopeInfo)\n    {\n        scopeId = funcExprScopeInfo->GetScopeId();\n        funcExprScopeInfo->GetScope()->ForEachSymbol([this, scopeId](Symbol *sym)\n        {\n            this->BindPidRefsInScope(sym->GetPid(), sym, scopeId);\n        });\n        PopScope(funcExprScopeInfo->GetScope());\n        PopStmt(&m_currentBlockInfo->pstmt);\n        PopBlockInfo();\n    }\n\n    FinishScopeInfo(scopeInfo->GetParent());\n}\n\n\/***************************************************************************\nParse the code.\n***************************************************************************\/\nParseNodePtr Parser::Parse(LPCUTF8 pszSrc, size_t offset, size_t length, charcount_t charOffset, ULONG grfscr, ULONG lineNumber, Js::LocalFunctionId * nextFunctionId, CompileScriptException *pse)\n{\n    ParseNodePtr pnodeProg;\n    ParseNodePtr *lastNodeRef = nullptr;\n\n    m_nextBlockId = 0;\n\n    \/\/ Scanner should run in Running mode and not syntax coloring mode\n    grfscr &= ~fscrSyntaxColor;\n\n    if (this->m_scriptContext->IsScriptContextInDebugMode()\n#ifdef ENABLE_PREJIT\n         || Js::Configuration::Global.flags.Prejit\n#endif\n         || ((grfscr & fscrNoDeferParse) != 0)\n        )\n    {\n        \/\/ Don't do deferred parsing if debugger is attached or feature is disabled\n        \/\/ by command-line switch.\n        grfscr &= ~fscrDeferFncParse;\n    }\n    else if (!(grfscr & fscrGlobalCode) &&\n             (\n                 PHASE_OFF1(Js::Phase::DeferEventHandlersPhase) ||\n                 this->m_scriptContext->IsScriptContextInSourceRundownOrDebugMode()\n             )\n        )\n    {\n        \/\/ Don't defer event handlers in debug\/rundown mode, because we need to register the document,\n        \/\/ so we need to create a full FunctionBody for the script body.\n        grfscr &= ~fscrDeferFncParse;\n    }\n\n    bool isDeferred = (grfscr & fscrDeferredFnc) != 0;\n    bool isModuleSource = (grfscr & fscrIsModuleCode) != 0;\n\n    m_grfscr = grfscr;\n    m_length = length;\n    m_originalLength = length;\n    m_nextFunctionId = nextFunctionId;\n\n    if(m_parseType != ParseType_Deferred)\n    {\n        JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), *m_nextFunctionId, 0, m_parseType, Js::Constants::GlobalFunction));\n        OUTPUT_TRACE(Js::DeferParsePhase, _u(\"Parsing function (%s) : %s (%d)\\n\"), GetParseType(), Js::Constants::GlobalFunction, *m_nextFunctionId);\n    }\n\n    \/\/ Give the scanner the source and get the first token\n    m_pscan->SetText(pszSrc, offset, length, charOffset, grfscr, lineNumber);\n    m_pscan->Scan();\n\n    \/\/ Make the main 'knopProg' node\n    int32 initSize = 0;\n    m_pCurrentAstSize = &initSize;\n    pnodeProg = CreateProgNodeWithScanner(isModuleSource);\n    pnodeProg->grfpn = PNodeFlags::fpnNone;\n    pnodeProg->sxFnc.pid = nullptr;\n    pnodeProg->sxFnc.pnodeName = nullptr;\n    pnodeProg->sxFnc.pnodeRest = nullptr;\n    pnodeProg->sxFnc.ClearFlags();\n    pnodeProg->sxFnc.SetNested(FALSE);\n    pnodeProg->sxFnc.astSize = 0;\n    pnodeProg->sxFnc.cbMin = m_pscan->IecpMinTok();\n    pnodeProg->sxFnc.lineNumber = lineNumber;\n    pnodeProg->sxFnc.columnNumber = 0;\n\n    if (!isDeferred || (isDeferred && grfscr & fscrGlobalCode))\n    {\n        \/\/ In the deferred case, if the global function is deferred parse (which is in no-refresh case),\n        \/\/ we will re-use the same function body, so start with the correct functionId.\n        pnodeProg->sxFnc.functionId = (*m_nextFunctionId)++;\n    }\n    else\n    {\n        pnodeProg->sxFnc.functionId = Js::Constants::NoFunctionId;\n    }\n\n    if (isModuleSource)\n    {\n        Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());\n\n        pnodeProg->sxModule.localExportEntries = nullptr;\n        pnodeProg->sxModule.indirectExportEntries = nullptr;\n        pnodeProg->sxModule.starExportEntries = nullptr;\n        pnodeProg->sxModule.importEntries = nullptr;\n        pnodeProg->sxModule.requestedModules = nullptr;\n    }\n\n    m_pCurrentAstSize = & (pnodeProg->sxFnc.astSize);\n\n    pnodeProg->sxFnc.hint = nullptr;\n    pnodeProg->sxFnc.hintLength = 0;\n    pnodeProg->sxFnc.hintOffset = 0;\n    pnodeProg->sxFnc.isNameIdentifierRef = true;\n    pnodeProg->sxFnc.nestedFuncEscapes = false;\n\n    \/\/ initialize parsing variables\n    pnodeProg->sxFnc.pnodeNext = nullptr;\n\n    m_currentNodeFunc = nullptr;\n    m_currentNodeDeferredFunc = nullptr;\n    m_currentNodeProg = pnodeProg;\n    m_cactIdentToNodeLookup = 1;\n\n    pnodeProg->sxFnc.nestedCount = 0;\n    m_pnestedCount = &pnodeProg->sxFnc.nestedCount;\n    m_inDeferredNestedFunc = false;\n\n    pnodeProg->sxFnc.pnodeParams = nullptr;\n    pnodeProg->sxFnc.pnodeVars = nullptr;\n    pnodeProg->sxFnc.pnodeRest = nullptr;\n    m_ppnodeVar = &pnodeProg->sxFnc.pnodeVars;\n    SetCurrentStatement(nullptr);\n    AssertMsg(m_pstmtCur == nullptr, \"Statement stack should be empty when we start parse global code\");\n\n    \/\/ Create block for const's and let's\n    ParseNodePtr pnodeGlobalBlock = StartParseBlock<true>(PnodeBlockType::Global, ScopeType_Global);\n    pnodeProg->sxProg.scope = pnodeGlobalBlock->sxBlock.scope;\n    ParseNodePtr pnodeGlobalEvalBlock = nullptr;\n\n    \/\/ Don't track function expressions separately from declarations at global scope.\n    m_ppnodeExprScope = nullptr;\n\n    \/\/ This synthetic block scope will contain all the nested scopes.\n    pnodeProg->sxFnc.pnodeBodyScope = nullptr;\n    pnodeProg->sxFnc.pnodeScopes = pnodeGlobalBlock;\n    m_ppnodeScope = &pnodeGlobalBlock->sxBlock.pnodeScopes;\n\n    if ((this->m_grfscr & fscrEvalCode) &&\n        !(this->m_functionBody && this->m_functionBody->GetScopeInfo()))\n    {\n        pnodeGlobalEvalBlock = StartParseBlock<true>(PnodeBlockType::Regular, ScopeType_GlobalEvalBlock);\n        pnodeProg->sxFnc.pnodeScopes = pnodeGlobalEvalBlock;\n        m_ppnodeScope = &pnodeGlobalEvalBlock->sxBlock.pnodeScopes;\n    }\n\n    Js::ScopeInfo *scopeInfo = nullptr;\n    if (m_parseType == ParseType_Deferred && m_functionBody)\n    {\n        \/\/ this->m_functionBody can be cleared during parsing, but we need access to the scope info later.\n        scopeInfo = m_functionBody->GetScopeInfo();\n        if (scopeInfo)\n        {\n            \/\/ Create an enclosing function context.\n            m_currentNodeFunc = CreateNode(knopFncDecl);\n            m_currentNodeFunc->sxFnc.pnodeName = nullptr;\n            m_currentNodeFunc->sxFnc.functionId = m_functionBody->GetLocalFunctionId();\n            m_currentNodeFunc->sxFnc.nestedCount = m_functionBody->GetNestedCount();\n            m_currentNodeFunc->sxFnc.SetStrictMode(!!this->m_fUseStrictMode);\n\n            this->RestoreScopeInfo(scopeInfo->GetParent());\n        }\n    }\n\n    \/\/ It's possible for the module global to be defer-parsed in debug scenarios.\n    if (isModuleSource && (!isDeferred || (isDeferred && grfscr & fscrGlobalCode)))\n    {\n        ParseNodePtr moduleFunction = GenerateModuleFunctionWrapper<true>();\n        pnodeProg->sxFnc.pnodeBody = nullptr;\n        AddToNodeList(&pnodeProg->sxFnc.pnodeBody, &lastNodeRef, moduleFunction);\n    }\n    else\n    {\n        \/\/ Process a sequence of statements\/declarations\n        ParseStmtList<true>(\n            &pnodeProg->sxFnc.pnodeBody,\n            &lastNodeRef,\n            SM_OnGlobalCode,\n            !(m_grfscr & fscrDeferredFncExpression) \/* isSourceElementList *\/);\n    }\n\n    if (m_parseType == ParseType_Deferred)\n    {\n        if (scopeInfo)\n        {\n            this->FinishScopeInfo(scopeInfo->GetParent());\n        }\n    }\n\n    pnodeProg->sxProg.m_UsesArgumentsAtGlobal = m_UsesArgumentsAtGlobal;\n\n    if (IsStrictMode())\n    {\n        pnodeProg->sxFnc.SetStrictMode();\n    }\n\n#if DEBUG\n    if(m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeProg->sxFnc.pnodeBody))\n    {\n        Error(ERRsyntax);\n    }\n#endif\n\n    if (tkEOF != m_token.tk)\n        Error(ERRsyntax);\n\n    \/\/ Append an EndCode node.\n    AddToNodeList(&pnodeProg->sxFnc.pnodeBody, &lastNodeRef,\n        CreateNodeWithScanner<knopEndCode>());\n    AssertMem(lastNodeRef);\n    AssertNodeMem(*lastNodeRef);\n    Assert((*lastNodeRef)->nop == knopEndCode);\n    (*lastNodeRef)->ichMin = 0;\n    (*lastNodeRef)->ichLim = 0;\n\n    \/\/ Get the extent of the code.\n    pnodeProg->ichLim = m_pscan->IchLimTok();\n    pnodeProg->sxFnc.cbLim = m_pscan->IecpLimTok();\n\n    \/\/ Terminate the local list\n    *m_ppnodeVar = nullptr;\n\n    Assert(nullptr == *m_ppnodeScope);\n    Assert(nullptr == pnodeProg->sxFnc.pnodeNext);\n\n#ifdef ENABLE_DEBUG_CONFIG_OPTIONS\n    if (Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))\n    {\n        m_stoppedDeferredParse = true;\n    }\n#endif\n\n    if (m_stoppedDeferredParse)\n    {\n        if (this->m_hasParallelJob)\n        {\n#if ENABLE_BACKGROUND_PARSING\n            BackgroundParser *bgp = static_cast<BackgroundParser*>(m_scriptContext->GetBackgroundParser());\n            Assert(bgp);\n            this->WaitForBackgroundJobs(bgp, pse);\n#endif\n        }\n\n        \/\/ Finally, see if there are any function bodies we now want to generate because we\n        \/\/ decided to stop deferring.\n        FinishDeferredFunction(pnodeProg->sxFnc.pnodeScopes);\n    }\n\n    if (pnodeGlobalEvalBlock)\n    {\n        FinishParseBlock(pnodeGlobalEvalBlock);\n    }\n    \/\/ Append block as body of pnodeProg\n    FinishParseBlock(pnodeGlobalBlock);\n\n    m_scriptContext->AddSourceSize(m_length);\n\n    if (m_parseType != ParseType_Deferred)\n    {\n        JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeProg->sxFnc.functionId, *m_pCurrentAstSize, false, Js::Constants::GlobalFunction));\n    }\n    return pnodeProg;\n}\n\n\nbool Parser::CheckForDirective(bool* pIsUseStrict, bool *pIsUseAsm, bool* pIsOctalInString)\n{\n    \/\/ A directive is a string constant followed by a statement terminating token\n    if (m_token.tk != tkStrCon)\n        return false;\n\n    \/\/ Careful, need to check for octal before calling m_pscan->Scan()\n    \/\/ because Scan() clears the \"had octal\" flag on the scanner and\n    \/\/ m_pscan->Restore() does not restore this flag.\n    if (pIsOctalInString != nullptr)\n    {\n        *pIsOctalInString = m_pscan->IsOctOrLeadingZeroOnLastTKNumber();\n    }\n\n    Ident* pidDirective = m_token.GetStr();\n    RestorePoint start;\n    m_pscan->Capture(&start);\n    m_pscan->Scan();\n\n    bool isDirective = true;\n\n    switch (m_token.tk)\n    {\n    case tkSColon:\n    case tkEOF:\n    case tkLCurly:\n    case tkRCurly:\n        break;\n    default:\n        if (!m_pscan->FHadNewLine())\n        {\n            isDirective = false;\n        }\n        break;\n    }\n\n    if (isDirective)\n    {\n        if (pIsUseStrict != nullptr)\n        {\n            *pIsUseStrict = CheckStrictModeStrPid(pidDirective);\n        }\n        if (pIsUseAsm != nullptr)\n        {\n            *pIsUseAsm = CheckAsmjsModeStrPid(pidDirective);\n        }\n    }\n\n    m_pscan->SeekTo(start);\n    return isDirective;\n}\n\nbool Parser::CheckStrictModeStrPid(IdentPtr pid)\n{\n#ifdef ENABLE_DEBUG_CONFIG_OPTIONS\n    if (Js::Configuration::Global.flags.NoStrictMode)\n        return false;\n#endif\n\n    return pid != nullptr &&\n        pid->Cch() == 10 &&\n        !m_pscan->IsEscapeOnLastTkStrCon() &&\n        wcsncmp(pid->Psz(), _u(\"use strict\"), 10) == 0;\n}\n\nbool Parser::CheckAsmjsModeStrPid(IdentPtr pid)\n{\n#ifdef ASMJS_PLAT\n    if (!CONFIG_FLAG_RELEASE(Asmjs))\n    {\n        return false;\n    }\n\n    bool isAsmCandidate = (pid != nullptr &&\n        AutoSystemInfo::Data.SSE2Available() &&\n        pid->Cch() == 7 &&\n        !m_pscan->IsEscapeOnLastTkStrCon() &&\n        wcsncmp(pid->Psz(), _u(\"use asm\"), 10) == 0);\n\n    if (isAsmCandidate && m_scriptContext->IsScriptContextInDebugMode())\n    {\n        \/\/ We would like to report this to debugger - they may choose to disable debugging.\n        \/\/ TODO : localization of the string?\n        m_scriptContext->RaiseMessageToDebugger(DEIT_ASMJS_IN_DEBUGGING, _u(\"AsmJs initialization error - AsmJs disabled due to script debugger\"), !m_sourceContextInfo->IsDynamic() ? m_sourceContextInfo->url : nullptr);\n        return false;\n    }\n\n    return isAsmCandidate && !(m_grfscr & fscrNoAsmJs);\n#else\n    return false;\n#endif\n}\n\nHRESULT Parser::ParseUtf8Source(__out ParseNodePtr* parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,\n    Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)\n{\n    m_functionBody = nullptr;\n    m_parseType = ParseType_Upfront;\n    return ParseSourceInternal( parseTree, pSrc, 0, length, 0, true, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);\n}\n\nHRESULT Parser::ParseCesu8Source(__out ParseNodePtr* parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,\n    Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)\n{\n    m_functionBody = nullptr;\n    m_parseType = ParseType_Upfront;\n    return ParseSourceInternal( parseTree, pSrc, 0, length, 0, false, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);\n}\n\nvoid Parser::PrepareScanner(bool fromExternal)\n{\n    \/\/ NOTE: HashTbl and Scanner are currently allocated from the CRT heap. If we want to allocate them from the\n    \/\/ parser arena, then we also need to change the way the HashTbl allocates PID's from its underlying\n    \/\/ allocator (which also currently uses the CRT heap). This is not trivial, because we still need to support\n    \/\/ heap allocation for the colorizer interface.\n\n    \/\/ create the hash table and init PID members\n    if (nullptr == (m_phtbl = HashTbl::Create(HASH_TABLE_SIZE, &m_err)))\n        Error(ERRnoMemory);\n    InitPids();\n\n    \/\/ create the scanner\n    if (nullptr == (m_pscan = Scanner_t::Create(this, m_phtbl, &m_token, &m_err, m_scriptContext)))\n        Error(ERRnoMemory);\n\n    if (fromExternal)\n        m_pscan->FromExternalSource();\n}\n\n#if ENABLE_BACKGROUND_PARSING\nvoid Parser::PrepareForBackgroundParse()\n{\n    m_pscan->PrepareForBackgroundParse(m_scriptContext);\n}\n\nvoid Parser::AddBackgroundParseItem(BackgroundParseItem *const item)\n{\n    if (currBackgroundParseItem == nullptr)\n    {\n        backgroundParseItems = item;\n    }\n    else\n    {\n        currBackgroundParseItem->SetNext(item);\n    }\n    currBackgroundParseItem = item;\n}\n#endif\n\nvoid Parser::AddFastScannedRegExpNode(ParseNodePtr const pnode)\n{\n    Assert(!IsBackgroundParser());\n    Assert(m_doingFastScan);\n\n    if (fastScannedRegExpNodes == nullptr)\n    {\n        fastScannedRegExpNodes = Anew(&m_nodeAllocator, NodeDList, &m_nodeAllocator);\n    }\n    fastScannedRegExpNodes->Append(pnode);\n}\n\n#if ENABLE_BACKGROUND_PARSING\nvoid Parser::AddBackgroundRegExpNode(ParseNodePtr const pnode)\n{\n    Assert(IsBackgroundParser());\n    Assert(currBackgroundParseItem != nullptr);\n\n    currBackgroundParseItem->AddRegExpNode(pnode, &m_nodeAllocator);\n}\n#endif\n\nHRESULT Parser::ParseFunctionInBackground(ParseNodePtr pnodeFnc, ParseContext *parseContext, bool topLevelDeferred, CompileScriptException *pse)\n{\n    m_functionBody = nullptr;\n    m_parseType = ParseType_Upfront;\n    HRESULT hr = S_OK;\n    SmartFPUControl smartFpuControl;\n    uint nextFunctionId = pnodeFnc->sxFnc.functionId + 1;\n\n    this->RestoreContext(parseContext);\n    DebugOnly( m_err.fInited = TRUE; )\n    m_nextFunctionId = &nextFunctionId;\n    m_deferringAST = topLevelDeferred;\n    m_inDeferredNestedFunc = false;\n    m_scopeCountNoAst = 0;\n\n    SetCurrentStatement(nullptr);\n\n    pnodeFnc->sxFnc.pnodeVars = nullptr;\n    pnodeFnc->sxFnc.pnodeParams = nullptr;\n    pnodeFnc->sxFnc.pnodeBody = nullptr;\n    pnodeFnc->sxFnc.nestedCount = 0;\n\n    ParseNodePtr pnodeParentFnc = GetCurrentFunctionNode();\n    m_currentNodeFunc = pnodeFnc;\n    m_currentNodeDeferredFunc = nullptr;\n    m_ppnodeScope = nullptr;\n    m_ppnodeExprScope = nullptr;\n\n    m_pnestedCount = &pnodeFnc->sxFnc.nestedCount;\n    m_pCurrentAstSize = &pnodeFnc->sxFnc.astSize;\n\n    ParseNodePtr pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);\n    pnodeFnc->sxFnc.pnodeScopes = pnodeBlock;\n    m_ppnodeScope = &pnodeBlock->sxBlock.pnodeScopes;\n\n    uint uDeferSave = m_grfscr & fscrDeferFncParse;\n\n    try\n    {\n        m_pscan->Scan();\n\n        m_ppnodeVar = &pnodeFnc->sxFnc.pnodeParams;\n        this->ParseFncFormals<true>(pnodeFnc, pnodeParentFnc, fFncNoFlgs);\n\n        if (m_token.tk == tkRParen)\n        {\n            m_pscan->Scan();\n        }\n\n        ChkCurTok(tkLCurly, ERRnoLcurly);\n\n        m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;\n\n        \/\/ Put the scanner into \"no hashing\" mode.\n        BYTE deferFlags = m_pscan->SetDeferredParse(topLevelDeferred);\n\n        \/\/ Process a sequence of statements\/declarations\n        if (topLevelDeferred)\n        {\n            ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true);\n        }\n        else\n        {\n            ParseNodePtr *lastNodeRef = nullptr;\n            ParseStmtList<true>(&pnodeFnc->sxFnc.pnodeBody, &lastNodeRef, SM_OnFunctionCode, true);\n            AddArgumentsNodeToVars(pnodeFnc);\n            \/\/ Append an EndCode node.\n            AddToNodeList(&pnodeFnc->sxFnc.pnodeBody, &lastNodeRef, CreateNodeWithScanner<knopEndCode>());\n        }\n\n        \/\/ Restore the scanner's default hashing mode.\n        m_pscan->SetDeferredParseFlags(deferFlags);\n\n#if DBG\n        pnodeFnc->sxFnc.deferredParseNextFunctionId = *this->m_nextFunctionId;\n#endif\n        this->m_deferringAST = FALSE;\n\n        \/\/ Append block as body of pnodeProg\n        FinishParseBlock(pnodeBlock);\n    }\n    catch(ParseExceptionObject& e)\n    {\n        m_err.m_hr = e.GetError();\n        hr = pse->ProcessError( m_pscan, m_err.m_hr, nullptr);\n    }\n\n    if (IsStrictMode())\n    {\n        pnodeFnc->sxFnc.SetStrictMode();\n    }\n\n    if (topLevelDeferred)\n    {\n        pnodeFnc->sxFnc.pnodeVars = nullptr;\n    }\n\n    m_grfscr |= uDeferSave;\n\n    Assert(nullptr == *m_ppnodeScope);\n\n    return hr;\n}\n\nHRESULT Parser::ParseSourceWithOffset(__out ParseNodePtr* parseTree, LPCUTF8 pSrc, size_t offset, size_t cbLength, charcount_t cchOffset,\n        bool isCesu8, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo,\n        Js::ParseableFunctionInfo* functionInfo)\n{\n    m_functionBody = functionInfo;\n    if (m_functionBody)\n    {\n        m_currDeferredStub = m_functionBody->GetDeferredStubs();\n        m_InAsmMode = grfscr & fscrNoAsmJs ? false : m_functionBody->GetIsAsmjsMode();\n    }\n    m_deferAsmJs = !m_InAsmMode;\n    m_parseType = ParseType_Deferred;\n    return ParseSourceInternal( parseTree, pSrc, offset, cbLength, cchOffset, !isCesu8, grfscr, pse, nextFunctionId, lineNumber, sourceContextInfo);\n}\n\nbool Parser::IsStrictMode() const\n{\n    return (m_fUseStrictMode ||\n           (m_currentNodeFunc != nullptr && m_currentNodeFunc->sxFnc.GetStrictMode()));\n}\n\nBOOL Parser::ExpectingExternalSource()\n{\n    return m_fExpectExternalSource;\n}\n\nSymbol *PnFnc::GetFuncSymbol()\n{\n    if (pnodeName &&\n        pnodeName->nop == knopVarDecl)\n    {\n        return pnodeName->sxVar.sym;\n    }\n    return nullptr;\n}\n\nvoid PnFnc::SetFuncSymbol(Symbol *sym)\n{\n    Assert(pnodeName &&\n           pnodeName->nop == knopVarDecl);\n    pnodeName->sxVar.sym = sym;\n}\n\nParseNodePtr PnFnc::GetParamScope() const\n{\n    if (this->pnodeScopes == nullptr)\n    {\n        return nullptr;\n    }\n    Assert(this->pnodeScopes->nop == knopBlock &&\n           this->pnodeScopes->sxBlock.pnodeNext == nullptr);\n    return this->pnodeScopes->sxBlock.pnodeScopes;\n}\n\nParseNodePtr PnFnc::GetBodyScope() const\n{\n    if (this->pnodeBodyScope == nullptr)\n    {\n        return nullptr;\n    }\n    Assert(this->pnodeBodyScope->nop == knopBlock &&\n           this->pnodeBodyScope->sxBlock.pnodeNext == nullptr);\n    return this->pnodeBodyScope->sxBlock.pnodeScopes;\n}\n\n\/\/ Create node versions with explicit token limits\nParseNodePtr Parser::CreateNode(OpCode nop, charcount_t ichMin, charcount_t ichLim)\n{\n    Assert(!this->m_deferringAST);\n    Assert(nop >= 0 && nop < knopLim);\n    ParseNodePtr pnode;\n    __analysis_assume(nop < knopLim);\n    int cb = nop >= 0 && nop < knopLim ? g_mpnopcbNode[nop] : kcbPnNone;\n\n    pnode = (ParseNodePtr)m_nodeAllocator.Alloc(cb);\n    Assert(pnode);\n\n    Assert(m_pCurrentAstSize != NULL);\n    *m_pCurrentAstSize += cb;\n\n    InitNode(nop,pnode);\n\n    pnode->ichMin = ichMin;\n    pnode->ichLim = ichLim;\n\n    return pnode;\n}\n\nParseNodePtr Parser::CreateNameNode(IdentPtr pid,charcount_t ichMin,charcount_t ichLim) {\n  ParseNodePtr pnode = CreateNodeT<knopName>(ichMin,ichLim);\n  pnode->sxPid.pid = pid;\n  pnode->sxPid.sym=NULL;\n  pnode->sxPid.symRef=NULL;\n  return pnode;\n}\n\nParseNodePtr Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1, charcount_t ichMin,charcount_t ichLim)\n{\n    Assert(!this->m_deferringAST);\n    DebugOnly(VerifyNodeSize(nop, kcbPnUni));\n\n    ParseNodePtr pnode = (ParseNodePtr)m_nodeAllocator.Alloc(kcbPnUni);\n\n    Assert(m_pCurrentAstSize != NULL);\n    *m_pCurrentAstSize += kcbPnUni;\n\n    InitNode(nop, pnode);\n\n    pnode->sxUni.pnode1 = pnode1;\n\n    pnode->ichMin = ichMin;\n    pnode->ichLim = ichLim;\n\n    return pnode;\n}\n\nParseNodePtr Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1,\n                                   ParseNodePtr pnode2,charcount_t ichMin,charcount_t ichLim)\n{\n    Assert(!this->m_deferringAST);\n    ParseNodePtr pnode = StaticCreateBinNode(nop, pnode1, pnode2, &m_nodeAllocator);\n\n    Assert(m_pCurrentAstSize != NULL);\n    *m_pCurrentAstSize += kcbPnBin;\n\n    pnode->ichMin = ichMin;\n    pnode->ichLim = ichLim;\n\n    return pnode;\n}\n\nParseNodePtr Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,\n                                   ParseNodePtr pnode2, ParseNodePtr pnode3,\n                                   charcount_t ichMin,charcount_t ichLim)\n{\n    Assert(!this->m_deferringAST);\n    DebugOnly(VerifyNodeSize(nop, kcbPnTri));\n    ParseNodePtr pnode = (ParseNodePtr)m_nodeAllocator.Alloc(kcbPnTri);\n\n    Assert(m_pCurrentAstSize != NULL);\n    *m_pCurrentAstSize += kcbPnTri;\n\n    InitNode(nop, pnode);\n\n    pnode->sxTri.pnodeNext = NULL;\n    pnode->sxTri.pnode1 = pnode1;\n    pnode->sxTri.pnode2 = pnode2;\n    pnode->sxTri.pnode3 = pnode3;\n\n    pnode->ichMin = ichMin;\n    pnode->ichLim = ichLim;\n\n    return pnode;\n}\n\nbool PnBlock::HasBlockScopedContent() const\n{\n    \/\/ A block has its own content if a let, const, or function is declared there.\n\n    if (this->pnodeLexVars != nullptr || this->blockType == Parameter)\n    {\n        return true;\n    }\n\n    \/\/ The enclosing scopes can contain functions and other things, so walk the list\n    \/\/ looking specifically for functions.\n\n    for (ParseNodePtr pnode = this->pnodeScopes; pnode;)\n    {\n        switch (pnode->nop) {\n\n        case knopFncDecl:\n            return true;\n\n        case knopBlock:\n            pnode = pnode->sxBlock.pnodeNext;\n            break;\n\n        case knopCatch:\n            pnode = pnode->sxCatch.pnodeNext;\n            break;\n\n        case knopWith:\n            pnode = pnode->sxWith.pnodeNext;\n            break;\n\n        default:\n            Assert(UNREACHED);\n            return true;\n        }\n    }\n\n    return false;\n}\n\nclass ByteCodeGenerator;\n\n\/\/ Copy AST; this works mostly on expressions for now\nParseNode* Parser::CopyPnode(ParseNode *pnode) {\n    if (pnode==NULL)\n        return NULL;\n    switch (pnode->nop) {\n        \/\/PTNODE(knopName       , \"name\"        ,None    ,Pid  ,fnopLeaf)\n    case knopName: {\n      ParseNode* nameNode=CreateNameNode(pnode->sxPid.pid,pnode->ichMin,pnode->ichLim);\n      nameNode->sxPid.sym=pnode->sxPid.sym;\n      return nameNode;\n    }\n      \/\/PTNODE(knopInt        , \"int const\"    ,None    ,Int  ,fnopLeaf|fnopConst)\n  case knopInt:\n    return pnode;\n      \/\/PTNODE(knopFlt        , \"flt const\"    ,None    ,Flt  ,fnopLeaf|fnopConst)\n  case knopFlt:\n    return pnode;\n      \/\/PTNODE(knopStr        , \"str const\"    ,None    ,Pid  ,fnopLeaf|fnopConst)\n  case knopStr:\n    return pnode;\n      \/\/PTNODE(knopRegExp     , \"reg expr\"    ,None    ,Pid  ,fnopLeaf|fnopConst)\n  case knopRegExp:\n    return pnode;\n    break;\n      \/\/PTNODE(knopThis       , \"this\"        ,None    ,None ,fnopLeaf)\n  case knopThis:\n    return CreateNodeT<knopThis>(pnode->ichMin,pnode->ichLim);\n      \/\/PTNODE(knopNull       , \"null\"        ,Null    ,None ,fnopLeaf)\n  case knopNull:\n    return pnode;\n      \/\/PTNODE(knopFalse      , \"false\"        ,False   ,None ,fnopLeaf)\n  case knopFalse:\n    {\n      ParseNode* ret = CreateNodeT<knopFalse>(pnode->ichMin, pnode->ichLim);\n      ret->location = pnode->location;\n      return ret;\n    }\n      \/\/PTNODE(knopTrue       , \"true\"        ,True    ,None ,fnopLeaf)\n  case knopTrue:\n    {\n        ParseNode* ret = CreateNodeT<knopTrue>(pnode->ichMin, pnode->ichLim);\n        ret->location = pnode->location;\n        return ret;\n    }\n      \/\/PTNODE(knopEmpty      , \"empty\"        ,Empty   ,None ,fnopLeaf)\n  case knopEmpty:\n    return CreateNodeT<knopEmpty>(pnode->ichMin,pnode->ichLim);\n      \/\/ Unary operators.\n      \/\/PTNODE(knopNot        , \"~\"            ,BitNot  ,Uni  ,fnopUni)\n      \/\/PTNODE(knopNeg        , \"unary -\"    ,Neg     ,Uni  ,fnopUni)\n      \/\/PTNODE(knopPos        , \"unary +\"    ,Pos     ,Uni  ,fnopUni)\n      \/\/PTNODE(knopLogNot     , \"!\"            ,LogNot  ,Uni  ,fnopUni)\n      \/\/PTNODE(knopEllipsis     , \"...\"       ,Spread  ,Uni    , fnopUni)\n      \/\/PTNODE(knopDecPost    , \"-- post\"    ,Dec     ,Uni  ,fnopUni|fnopAsg)\n      \/\/PTNODE(knopIncPre     , \"++ pre\"    ,Inc     ,Uni  ,fnopUni|fnopAsg)\n      \/\/PTNODE(knopDecPre     , \"-- pre\"    ,Dec     ,Uni  ,fnopUni|fnopAsg)\n      \/\/PTNODE(knopTypeof     , \"typeof\"    ,None    ,Uni  ,fnopUni)\n      \/\/PTNODE(knopVoid       , \"void\"        ,Void    ,Uni  ,fnopUni)\n      \/\/PTNODE(knopDelete     , \"delete\"    ,None    ,Uni  ,fnopUni)\n  case knopNot:\n  case knopNeg:\n  case knopPos:\n  case knopLogNot:\n  case knopEllipsis:\n  case knopIncPost:\n  case knopDecPost:\n  case knopIncPre:\n  case knopDecPre:\n  case knopTypeof:\n  case knopVoid:\n  case knopDelete:\n    return CreateUniNode(pnode->nop,CopyPnode(pnode->sxUni.pnode1),pnode->ichMin,pnode->ichLim);\n      \/\/PTNODE(knopArray      , \"arr cnst\"    ,None    ,Uni  ,fnopUni)\n      \/\/PTNODE(knopObject     , \"obj cnst\"    ,None    ,Uni  ,fnopUni)\n  case knopArray:\n  case knopObject:\n    \/\/ TODO: need to copy arr\n    Assert(false);\n    break;\n      \/\/ Binary operators\n      \/\/PTNODE(knopAdd        , \"+\"            ,Add     ,Bin  ,fnopBin)\n      \/\/PTNODE(knopSub        , \"-\"            ,Sub     ,Bin  ,fnopBin)\n      \/\/PTNODE(knopMul        , \"*\"            ,Mul     ,Bin  ,fnopBin)\n      \/\/PTNODE(knopExpo       , \"**\"           ,Expo     ,Bin  ,fnopBin)\n      \/\/PTNODE(knopDiv        , \"\/\"            ,Div     ,Bin  ,fnopBin)\n      \/\/PTNODE(knopMod        , \"%\"            ,Mod     ,Bin  ,fnopBin)\n      \/\/PTNODE(knopOr         , \"|\"            ,BitOr   ,Bin  ,fnopBin)\n      \/\/PTNODE(knopXor        , \"^\"            ,BitXor  ,Bin  ,fnopBin)\n      \/\/PTNODE(knopAnd        , \"&\"            ,BitAnd  ,Bin  ,fnopBin)\n      \/\/PTNODE(knopEq         , \"==\"        ,EQ      ,Bin  ,fnopBin|fnopRel)\n      \/\/PTNODE(knopNe         , \"!=\"        ,NE      ,Bin  ,fnopBin|fnopRel)\n      \/\/PTNODE(knopLt         , \"<\"            ,LT      ,Bin  ,fnopBin|fnopRel)\n      \/\/PTNODE(knopLe         , \"<=\"        ,LE      ,Bin  ,fnopBin|fnopRel)\n      \/\/PTNODE(knopGe         , \">=\"        ,GE      ,Bin  ,fnopBin|fnopRel)\n      \/\/PTNODE(knopGt         , \">\"            ,GT      ,Bin  ,fnopBin|fnopRel)\n      \/\/PTNODE(knopEqv        , \"===\"        ,Eqv     ,Bin  ,fnopBin|fnopRel)\n      \/\/PTNODE(knopIn         , \"in\"        ,In      ,Bin  ,fnopBin|fnopRel)\n      \/\/PTNODE(knopInstOf     , \"instanceof\",InstOf  ,Bin  ,fnopBin|fnopRel)\n      \/\/PTNODE(knopNEqv       , \"!==\"        ,NEqv    ,Bin  ,fnopBin|fnopRel)\n      \/\/PTNODE(knopComma      , \",\"            ,None    ,Bin  ,fnopBin)\n      \/\/PTNODE(knopLogOr      , \"||\"        ,None    ,Bin  ,fnopBin)\n      \/\/PTNODE(knopLogAnd     , \"&&\"        ,None    ,Bin  ,fnopBin)\n      \/\/PTNODE(knopLsh        , \"<<\"        ,Lsh     ,Bin  ,fnopBin)\n      \/\/PTNODE(knopRsh        , \">>\"        ,Rsh     ,Bin  ,fnopBin)\n      \/\/PTNODE(knopRs2        , \">>>\"        ,Rs2     ,Bin  ,fnopBin)\n  case knopAdd:\n  case knopSub:\n  case knopMul:\n  case knopExpo:\n  case knopDiv:\n  case knopMod:\n  case knopOr:\n  case knopXor:\n  case knopAnd:\n  case knopEq:\n  case knopNe:\n  case knopLt:\n  case knopLe:\n  case knopGe:\n  case knopGt:\n  case knopEqv:\n  case knopIn:\n  case knopInstOf:\n  case knopNEqv:\n  case knopComma:\n  case knopLogOr:\n  case knopLogAnd:\n  case knopLsh:\n  case knopRsh:\n  case knopRs2:\n      \/\/PTNODE(knopAsg        , \"=\"            ,None    ,Bin  ,fnopBin|fnopAsg)\n  case knopAsg:\n      \/\/PTNODE(knopDot        , \".\"            ,None    ,Bin  ,fnopBin)\n  case knopDot:\n      \/\/PTNODE(knopAsgAdd     , \"+=\"        ,Add     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgAdd:\n      \/\/PTNODE(knopAsgSub     , \"-=\"        ,Sub     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgSub:\n      \/\/PTNODE(knopAsgMul     , \"*=\"        ,Mul     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgMul:\n      \/\/PTNODE(knopAsgDiv     , \"\/=\"        ,Div     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgExpo:\n      \/\/PTNODE(knopAsgExpo    , \"**=\"       ,Expo    ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgDiv:\n      \/\/PTNODE(knopAsgMod     , \"%=\"        ,Mod     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgMod:\n      \/\/PTNODE(knopAsgAnd     , \"&=\"        ,BitAnd  ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgAnd:\n      \/\/PTNODE(knopAsgXor     , \"^=\"        ,BitXor  ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgXor:\n      \/\/PTNODE(knopAsgOr      , \"|=\"        ,BitOr   ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgOr:\n      \/\/PTNODE(knopAsgLsh     , \"<<=\"        ,Lsh     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgLsh:\n      \/\/PTNODE(knopAsgRsh     , \">>=\"        ,Rsh     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgRsh:\n      \/\/PTNODE(knopAsgRs2     , \">>>=\"        ,Rs2     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgRs2:\n      \/\/PTNODE(knopMember     , \":\"            ,None    ,Bin  ,fnopBin)\n  case knopMember:\n  case knopMemberShort:\n      \/\/PTNODE(knopIndex      , \"[]\"        ,None    ,Bin  ,fnopBin)\n      \/\/PTNODE(knopList       , \"<list>\"    ,None    ,Bin  ,fnopNone)\n\n  case knopIndex:\n  case knopList:\n    return CreateBinNode(pnode->nop,CopyPnode(pnode->sxBin.pnode1),\n                         CopyPnode(pnode->sxBin.pnode2),pnode->ichMin,pnode->ichLim);\n\n      \/\/PTNODE(knopCall       , \"()\"        ,None    ,Bin  ,fnopBin)\n      \/\/PTNODE(knopNew        , \"new\"        ,None    ,Bin  ,fnopBin)\n  case knopNew:\n  case knopCall:\n    return CreateCallNode(pnode->nop,CopyPnode(pnode->sxCall.pnodeTarget),\n                         CopyPnode(pnode->sxCall.pnodeArgs),pnode->ichMin,pnode->ichLim);\n      \/\/PTNODE(knopQmark      , \"?\"            ,None    ,Tri  ,fnopBin)\n  case knopQmark:\n    return CreateTriNode(pnode->nop,CopyPnode(pnode->sxTri.pnode1),\n                         CopyPnode(pnode->sxTri.pnode2),CopyPnode(pnode->sxTri.pnode3),\n                         pnode->ichMin,pnode->ichLim);\n      \/\/ General nodes.\n      \/\/PTNODE(knopVarDecl    , \"varDcl\"    ,None    ,Var  ,fnopNone)\n    case knopVarDecl: {\n      ParseNode* copyNode=CreateNodeT<knopVarDecl>(pnode->ichMin,pnode->ichLim);\n      copyNode->sxVar.pnodeInit=CopyPnode(pnode->sxVar.pnodeInit);\n      copyNode->sxVar.sym=pnode->sxVar.sym;\n      \/\/ TODO: mult-decl\n      Assert(pnode->sxVar.pnodeNext==NULL);\n      copyNode->sxVar.pnodeNext=NULL;\n      return copyNode;\n    }\n      \/\/PTNODE(knopFncDecl    , \"fncDcl\"    ,None    ,Fnc  ,fnopLeaf)\n      \/\/PTNODE(knopProg       , \"program\"    ,None    ,Fnc  ,fnopNone)\n  case knopFncDecl:\n  case knopProg:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopEndCode    , \"<endcode>\"    ,None    ,None ,fnopNone)\n  case knopEndCode:\n    break;\n      \/\/PTNODE(knopDebugger   , \"debugger\"    ,None    ,None ,fnopNone)\n  case knopDebugger:\n    break;\n      \/\/PTNODE(knopFor        , \"for\"        ,None    ,For  ,fnopBreak|fnopContinue)\n    case knopFor: {\n      ParseNode* copyNode=CreateNodeT<knopFor>(pnode->ichMin,pnode->ichLim);\n      copyNode->sxFor.pnodeInverted=NULL;\n      copyNode->sxFor.pnodeInit=CopyPnode(pnode->sxFor.pnodeInit);\n      copyNode->sxFor.pnodeCond=CopyPnode(pnode->sxFor.pnodeCond);\n      copyNode->sxFor.pnodeIncr=CopyPnode(pnode->sxFor.pnodeIncr);\n      copyNode->sxFor.pnodeBody=CopyPnode(pnode->sxFor.pnodeBody);\n      return copyNode;\n    }\n      \/\/PTNODE(knopIf         , \"if\"        ,None    ,If   ,fnopNone)\n  case knopIf:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopWhile      , \"while\"        ,None    ,While,fnopBreak|fnopContinue)\n  case knopWhile:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopDoWhile    , \"do-while\"    ,None    ,While,fnopBreak|fnopContinue)\n  case knopDoWhile:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopForIn      , \"for in\"    ,None    ,ForIn,fnopBreak|fnopContinue|fnopCleanup)\n  case knopForIn:\n    Assert(false);\n    break;\n  case knopForOf:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopReturn     , \"return\"    ,None    ,Uni  ,fnopNone)\n  case knopReturn: {\n    ParseNode* copyNode=CreateNodeT<knopReturn>(pnode->ichMin,pnode->ichLim);\n    copyNode->sxReturn.pnodeExpr=CopyPnode(pnode->sxReturn.pnodeExpr);\n    return copyNode;\n  }\n      \/\/PTNODE(knopBlock      , \"{}\"        ,None    ,Block,fnopNone)\n  case knopBlock: {\n    ParseNode* copyNode=CreateBlockNode(pnode->ichMin,pnode->ichLim,pnode->sxBlock.blockType);\n    if (pnode->grfpn & PNodeFlags::fpnSyntheticNode) {\n        \/\/ fpnSyntheticNode is sometimes set on PnodeBlockType::Regular blocks which\n        \/\/ CreateBlockNode() will not automatically set for us, so set it here if it's\n        \/\/ specified on the source node.\n        copyNode->grfpn |= PNodeFlags::fpnSyntheticNode;\n    }\n    copyNode->sxBlock.pnodeStmt=CopyPnode(pnode->sxBlock.pnodeStmt);\n    return copyNode;\n  }\n      \/\/PTNODE(knopWith       , \"with\"        ,None    ,With ,fnopCleanup)\n  case knopWith:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopBreak      , \"break\"        ,None    ,Jump ,fnopNone)\n  case knopBreak:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopContinue   , \"continue\"    ,None    ,Jump ,fnopNone)\n  case knopContinue:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopLabel      , \"label\"        ,None    ,Label,fnopNone)\n  case knopLabel:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopSwitch     , \"switch\"    ,None    ,Switch,fnopBreak)\n  case knopSwitch:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopCase       , \"case\"        ,None    ,Case ,fnopNone)\n  case knopCase:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopTryFinally,\"try-finally\",None,TryFinally,fnopCleanup)\n  case knopTryFinally:\n    Assert(false);\n    break;\n  case knopFinally:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopCatch      , \"catch\"     ,None    ,Catch,fnopNone)\n  case knopCatch:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopTryCatch      , \"try-catch\" ,None    ,TryCatch  ,fnopCleanup)\n  case knopTryCatch:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopTry        , \"try\"       ,None    ,Try  ,fnopCleanup)\n  case knopTry:\n    Assert(false);\n    break;\n      \/\/PTNODE(knopThrow      , \"throw\"     ,None    ,Uni  ,fnopNone)\n  case knopThrow:\n    Assert(false);\n    break;\n  default:\n    Assert(false);\n    break;\n    }\n    return NULL;\n}\n\n\/\/ Returns true when str is string for Nan, Infinity or -Infinity.\n\/\/ Does not check for double number value being in NaN\/Infinity range.\n\/\/ static\ntemplate<bool CheckForNegativeInfinity>\ninline bool Parser::IsNaNOrInfinityLiteral(LPCOLESTR str)\n{\n    \/\/ Note: wcscmp crashes when one of the parameters is NULL.\n    return str &&\n           (wcscmp(_u(\"NaN\"), str) == 0 ||\n           wcscmp(_u(\"Infinity\"), str) == 0 ||\n               (CheckForNegativeInfinity && wcscmp(_u(\"-Infinity\"), str) == 0));\n}\n\ntemplate <bool buildAST>\nParseNodePtr Parser::ParseSuper(ParseNodePtr pnode, bool fAllowCall)\n{\n    ParseNodePtr currentNodeFunc = GetCurrentFunctionNode();\n\n    if (buildAST) {\n        pnode = CreateNodeWithScanner<knopSuper>();\n    }\n\n    m_pscan->ScanForcingPid();\n\n    switch (m_token.tk)\n    {\n    case tkDot:     \/\/ super.prop\n    case tkLBrack:  \/\/ super[foo]\n    case tkLParen:  \/\/ super(args)\n        break;\n\n    default:\n        Error(ERRInvalidSuper);\n        break;\n    }\n\n    if (!fAllowCall && (m_token.tk == tkLParen))\n    {\n        Error(ERRInvalidSuper); \/\/ new super() is not allowed\n    }\n    else if (this->m_parsingSuperRestrictionState == ParsingSuperRestrictionState_SuperCallAndPropertyAllowed)\n    {\n        \/\/ Any super access is good within a class constructor\n    }\n    else if (this->m_parsingSuperRestrictionState == ParsingSuperRestrictionState_SuperPropertyAllowed)\n    {\n        \/\/ Cannot call super within a class member\n        if (m_token.tk == tkLParen)\n        {\n            Error(ERRInvalidSuper);\n        }\n    }\n    else\n    {\n        \/\/ Anything else is an error\n        Error(ERRInvalidSuper);\n    }\n\n    currentNodeFunc->sxFnc.SetHasSuperReference(TRUE);\n    CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(SuperCount, m_scriptContext);\n    return pnode;\n}\n\nvoid Parser::AppendToList(ParseNodePtr *node, ParseNodePtr nodeToAppend)\n{\n    Assert(nodeToAppend);\n    ParseNodePtr* lastPtr = node;\n    while ((*lastPtr) && (*lastPtr)->nop == knopList)\n    {\n        lastPtr = &(*lastPtr)->sxBin.pnode2;\n    }\n    auto last = (*lastPtr);\n    if (last)\n    {\n        *lastPtr = CreateBinNode(knopList, last, nodeToAppend, last->ichMin, nodeToAppend->ichLim);\n    }\n    else\n    {\n        *lastPtr = nodeToAppend;\n    }\n}\n\nParseNodePtr Parser::ConvertArrayToArrayPattern(ParseNodePtr pnode)\n{\n    Assert(pnode->nop == knopArray);\n    pnode->nop = knopArrayPattern;\n\n    ForEachItemRefInList(&pnode->sxArrLit.pnode1, [&](ParseNodePtr *itemRef) {\n        ParseNodePtr item = *itemRef;\n        if (item->nop == knopEllipsis)\n        {\n            itemRef = &item->sxUni.pnode1;\n            item = *itemRef;\n            if (!(item->nop == knopName\n                  || item->nop == knopDot\n                  || item->nop == knopIndex\n                  || item->nop == knopArray\n                  || item->nop == knopObject))\n            {\n                Error(ERRInvalidAssignmentTarget);\n            }\n        }\n        else if (item->nop == knopAsg)\n        {\n            itemRef = &item->sxBin.pnode1;\n            item = *itemRef;\n        }\n\n        if (item->nop == knopArray)\n        {\n            ConvertArrayToArrayPattern(item);\n        }\n        else if (item->nop == knopObject)\n        {\n            *itemRef = ConvertObjectToObjectPattern(item);\n        }\n        else if (item->nop == knopName)\n        {\n            TrackAssignment<true>(item, nullptr);\n        }\n    });\n\n    return pnode;\n}\n\nParseNodePtr Parser::CreateParamPatternNode(ParseNodePtr pnode1)\n{\n    ParseNodePtr paramPatternNode = CreateNode(knopParamPattern, pnode1->ichMin, pnode1->ichLim);\n    paramPatternNode->sxParamPattern.pnode1 = pnode1;\n    paramPatternNode->sxParamPattern.pnodeNext = nullptr;\n    paramPatternNode->sxParamPattern.location = Js::Constants::NoRegister;\n    return paramPatternNode;\n}\n\nParseNodePtr Parser::ConvertObjectToObjectPattern(ParseNodePtr pnodeMemberList)\n{\n    charcount_t ichMin = m_pscan->IchMinTok();\n    charcount_t ichLim = m_pscan->IchLimTok();\n    ParseNodePtr pnodeMemberNodeList = nullptr;\n    if (pnodeMemberList != nullptr && pnodeMemberList->nop == knopObject)\n    {\n        ichMin = pnodeMemberList->ichMin;\n        ichLim = pnodeMemberList->ichLim;\n        pnodeMemberList = pnodeMemberList->sxUni.pnode1;\n    }\n\n    ForEachItemInList(pnodeMemberList, [&](ParseNodePtr item) {\n        ParseNodePtr memberNode = ConvertMemberToMemberPattern(item);\n        AppendToList(&pnodeMemberNodeList, memberNode);\n    });\n\n    return CreateUniNode(knopObjectPattern, pnodeMemberNodeList, ichMin, ichLim);\n}\n\nParseNodePtr Parser::GetRightSideNodeFromPattern(ParseNodePtr pnode)\n{\n    Assert(pnode != nullptr);\n    ParseNodePtr rightNode = nullptr;\n    OpCode op = pnode->nop;\n    if (op == knopObject)\n    {\n        rightNode = ConvertObjectToObjectPattern(pnode);\n    }\n    else if (op == knopArray)\n    {\n        rightNode = ConvertArrayToArrayPattern(pnode);\n    }\n    else\n    {\n        rightNode = pnode;\n        if (op == knopName)\n        {\n            TrackAssignment<true>(pnode, nullptr);\n        }\n    }\n\n    return rightNode;\n}\n\nParseNodePtr Parser::ConvertMemberToMemberPattern(ParseNodePtr pnodeMember)\n{\n    if (pnodeMember->nop == knopObjectPatternMember)\n    {\n        return pnodeMember;\n    }\n\n    Assert(pnodeMember->nop == knopMember || pnodeMember->nop == knopMemberShort);\n\n    ParseNodePtr rightNode = GetRightSideNodeFromPattern(pnodeMember->sxBin.pnode2);\n    ParseNodePtr resultNode = CreateBinNode(knopObjectPatternMember, pnodeMember->sxBin.pnode1, rightNode);\n    resultNode->ichMin = pnodeMember->ichMin;\n    resultNode->ichLim = pnodeMember->ichLim;\n    return resultNode;\n}\n\nParseNodePtr Parser::ConvertToPattern(ParseNodePtr pnode)\n{\n    if (pnode != nullptr)\n    {\n        if (pnode->nop == knopArray)\n        {\n            ConvertArrayToArrayPattern(pnode);\n        }\n        else if (pnode->nop == knopObject)\n        {\n            pnode = ConvertObjectToObjectPattern(pnode);\n        }\n    }\n    return pnode;\n}\n\n\/\/ This essentially be called for verifying the structure of the current tree with satisfying the destructuring grammar.\nvoid Parser::ParseDestructuredLiteralWithScopeSave(tokens declarationType,\n    bool isDecl,\n    bool topLevel,\n    DestructuringInitializerContext initializerContext\/* = DIC_None*\/,\n    bool allowIn \/*= true*\/)\n{\n    \/\/ We are going to parse the text again to validate the current grammar as Destructuring. Saving some scopes and\n    \/\/ AST related information before the validation parsing and later they will be restored.\n\n    ParseNodePtr pnodeFncSave = m_currentNodeFunc;\n    ParseNodePtr pnodeDeferredFncSave = m_currentNodeDeferredFunc;\n    if (m_currentNodeDeferredFunc == nullptr)\n    {\n        m_currentNodeDeferredFunc = m_currentNodeFunc;\n    }\n    int32 *pAstSizeSave = m_pCurrentAstSize;\n    uint *pNestedCountSave = m_pnestedCount;\n    ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;\n    ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;\n\n    ParseNodePtr newTempScope = nullptr;\n    m_ppnodeScope = &newTempScope;\n\n    int32 newTempAstSize = 0;\n    m_pCurrentAstSize = &newTempAstSize;\n\n    uint newTempNestedCount = 0;\n    m_pnestedCount = &newTempNestedCount;\n\n    m_ppnodeExprScope = nullptr;\n\n    charcount_t funcInArraySave = m_funcInArray;\n    uint funcInArrayDepthSave = m_funcInArrayDepth;\n\n    \/\/ we need to reset this as we are going to parse the grammar again.\n    m_hasDeferredShorthandInitError = false;\n\n    ParseDestructuredLiteral<false>(declarationType, isDecl, topLevel, initializerContext, allowIn);\n\n    m_currentNodeFunc = pnodeFncSave;\n    m_currentNodeDeferredFunc = pnodeDeferredFncSave;\n    m_pCurrentAstSize = pAstSizeSave;\n    m_pnestedCount = pNestedCountSave;\n    m_ppnodeScope = ppnodeScopeSave;\n    m_ppnodeExprScope = ppnodeExprScopeSave;\n    m_funcInArray = funcInArraySave;\n    m_funcInArrayDepth = funcInArrayDepthSave;\n}\n\ntemplate <bool buildAST>\nParseNodePtr Parser::ParseDestructuredLiteral(tokens declarationType,\n    bool isDecl,\n    bool topLevel\/* = true*\/,\n    DestructuringInitializerContext initializerContext\/* = DIC_None*\/,\n    bool allowIn\/* = true*\/,\n    BOOL *forInOfOkay\/* = nullptr*\/,\n    BOOL *nativeForOkay\/* = nullptr*\/)\n{\n    ParseNodePtr pnode = nullptr;\n    Assert(IsPossiblePatternStart());\n    if (m_token.tk == tkLCurly)\n    {\n        pnode = ParseDestructuredObjectLiteral<buildAST>(declarationType, isDecl, topLevel);\n    }\n    else\n    {\n        pnode = ParseDestructuredArrayLiteral<buildAST>(declarationType, isDecl, topLevel);\n    }\n\n    return ParseDestructuredInitializer<buildAST>(pnode, isDecl, topLevel, initializerContext, allowIn, forInOfOkay, nativeForOkay);\n}\n\ntemplate <bool buildAST>\nParseNodePtr Parser::ParseDestructuredInitializer(ParseNodePtr lhsNode,\n    bool isDecl,\n    bool topLevel,\n    DestructuringInitializerContext initializerContext,\n    bool allowIn,\n    BOOL *forInOfOkay,\n    BOOL *nativeForOkay)\n{\n    m_pscan->Scan();\n    if (topLevel && nativeForOkay == nullptr)\n    {\n        if (initializerContext != DIC_ForceErrorOnInitializer && m_token.tk != tkAsg)\n        {\n            \/\/ e.g. var {x};\n            Error(ERRDestructInit);\n        }\n        else if (initializerContext == DIC_ForceErrorOnInitializer && m_token.tk == tkAsg)\n        {\n            \/\/ e.g. catch([x] = [0])\n            Error(ERRDestructNotInit);\n        }\n    }\n\n    if (m_token.tk != tkAsg || initializerContext == DIC_ShouldNotParseInitializer)\n    {\n        if (topLevel && nativeForOkay != nullptr)\n        {\n            \/\/ Native loop should have destructuring initializer\n            *nativeForOkay = FALSE;\n        }\n\n        return lhsNode;\n    }\n\n    if (forInOfOkay)\n    {\n        *forInOfOkay = FALSE;\n    }\n\n    m_pscan->Scan();\n\n\n    bool alreadyHasInitError = m_hasDeferredShorthandInitError;\n\n    ParseNodePtr pnodeDefault = ParseExpr<buildAST>(koplCma, nullptr, allowIn);\n\n    if (m_hasDeferredShorthandInitError && !alreadyHasInitError)\n    {\n        Error(ERRnoColon);\n    }\n\n    ParseNodePtr pnodeDestructAsg = nullptr;\n    if (buildAST)\n    {\n        Assert(lhsNode != nullptr);\n\n        pnodeDestructAsg = CreateNodeWithScanner<knopAsg>();\n        pnodeDestructAsg->sxBin.pnode1 = lhsNode;\n        pnodeDestructAsg->sxBin.pnode2 = pnodeDefault;\n        pnodeDestructAsg->ichMin = lhsNode->ichMin;\n        pnodeDestructAsg->ichLim = pnodeDefault->ichLim;\n    }\n    return pnodeDestructAsg;\n}\n\ntemplate <bool buildAST>\nParseNodePtr Parser::ParseDestructuredObjectLiteral(tokens declarationType, bool isDecl, bool topLevel\/* = true*\/)\n{\n    Assert(m_token.tk == tkLCurly);\n    charcount_t ichMin = m_pscan->IchMinTok();\n    m_pscan->Scan();\n\n    if (!isDecl)\n    {\n        declarationType = tkLCurly;\n    }\n    ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(nullptr\/*pNameHint*\/, nullptr\/*pHintLength*\/, declarationType);\n    Assert(m_token.tk == tkRCurly);\n\n    ParseNodePtr objectPatternNode = nullptr;\n    if (buildAST)\n    {\n        charcount_t ichLim = m_pscan->IchLimTok();\n        objectPatternNode = CreateUniNode(knopObjectPattern, pnodeMemberList, ichMin, ichLim);\n    }\n    return objectPatternNode;\n}\n\ntemplate <bool buildAST>\nParseNodePtr Parser::ParseDestructuredVarDecl(tokens declarationType, bool isDecl, bool *hasSeenRest, bool topLevel\/* = true*\/, bool allowEmptyExpression\/* = true*\/)\n{\n    ParseNodePtr pnodeElem = nullptr;\n    int parenCount = 0;\n    bool seenRest = false;\n\n    while (m_token.tk == tkLParen)\n    {\n        m_pscan->Scan();\n        ++parenCount;\n    }\n\n    if (m_token.tk == tkEllipsis)\n    {\n        \/\/ As per ES 2015 : Rest can have left-hand-side-expression when on assignment expression, but under declaration only binding identifier is allowed\n        \/\/ But spec is going to change for this one to allow LHS-expression both on expression and declaration - so making that happen early.\n\n        seenRest = true;\n        m_pscan->Scan();\n\n        while (m_token.tk == tkLParen)\n        {\n            m_pscan->Scan();\n            ++parenCount;\n        }\n\n        if (m_token.tk != tkID && m_token.tk != tkSUPER && m_token.tk != tkLCurly && m_token.tk != tkLBrack)\n        {\n            if (isDecl)\n            {\n                Error(ERRnoIdent);\n            }\n            else\n            {\n                Error(ERRInvalidAssignmentTarget);\n            }\n        }\n    }\n\n    if (IsPossiblePatternStart())\n    {\n        \/\/ Go recursively\n        pnodeElem = ParseDestructuredLiteral<buildAST>(declarationType, isDecl, false \/*topLevel*\/, seenRest ? DIC_ShouldNotParseInitializer : DIC_None);\n        if (!isDecl)\n        {\n            BOOL fCanAssign;\n            IdentToken token;\n            \/\/ Look for postfix operator\n            pnodeElem = ParsePostfixOperators<buildAST>(pnodeElem, TRUE, FALSE, &fCanAssign, &token);\n        }\n    }\n    else if (m_token.tk == tkSUPER || m_token.tk == tkID)\n    {\n        if (isDecl)\n        {\n            charcount_t ichMin = m_pscan->IchMinTok();\n            pnodeElem = ParseVariableDeclaration<buildAST>(declarationType, ichMin\n                ,\/* fAllowIn *\/false, \/* pfForInOk *\/nullptr, \/* singleDefOnly *\/true, \/* allowInit *\/!seenRest, false \/*topLevelParse*\/);\n\n        }\n        else\n        {\n            BOOL fCanAssign;\n            IdentToken token;\n            \/\/ We aren't declaring anything, so scan the ID reference manually.\n            pnodeElem = ParseTerm<buildAST>(\/* fAllowCall *\/ m_token.tk != tkSUPER, nullptr \/*pNameHint*\/, nullptr \/*pHintLength*\/, nullptr \/*pShortNameOffset*\/, &token, false,\n                                                             &fCanAssign);\n\n            \/\/ In this destructuring case we can force error here as we cannot assign.\n\n            if (!fCanAssign)\n            {\n                Error(ERRInvalidAssignmentTarget);\n            }\n\n            if (buildAST)\n            {\n                if (IsStrictMode() && pnodeElem != nullptr && pnodeElem->nop == knopName)\n                {\n                    CheckStrictModeEvalArgumentsUsage(pnodeElem->sxPid.pid);\n                }\n            }\n            else\n            {\n                if (IsStrictMode() && token.tk == tkID)\n                {\n                    CheckStrictModeEvalArgumentsUsage(token.pid);\n                }\n                token.tk = tkNone;\n            }\n        }\n    }\n    else if (!((m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly) && allowEmptyExpression))\n    {\n        if (m_token.IsOperator())\n        {\n            Error(ERRDestructNoOper);\n        }\n        Error(ERRDestructIDRef);\n    }\n\n    \/\/ Swallow RParens before a default expression, if any.\n    while (m_token.tk == tkRParen)\n    {\n        m_pscan->Scan();\n        --parenCount;\n    }\n\n    if (hasSeenRest != nullptr)\n    {\n        *hasSeenRest = seenRest;\n    }\n\n    if (m_token.tk == tkAsg)\n    {\n        \/\/ Parse the initializer.\n        if (seenRest)\n        {\n            Error(ERRRestWithDefault);\n        }\n        m_pscan->Scan();\n\n        bool alreadyHasInitError = m_hasDeferredShorthandInitError;\n        ParseNodePtr pnodeInit = ParseExpr<buildAST>(koplCma);\n\n        if (m_hasDeferredShorthandInitError && !alreadyHasInitError)\n        {\n            Error(ERRnoColon);\n        }\n\n        if (buildAST)\n        {\n            pnodeElem = CreateBinNode(knopAsg, pnodeElem, pnodeInit);\n        }\n    }\n\n    if (buildAST && seenRest)\n    {\n        ParseNodePtr pnodeRest = CreateNodeWithScanner<knopEllipsis>();\n        pnodeRest->sxUni.pnode1 = pnodeElem;\n        pnodeElem = pnodeRest;\n    }\n\n    while (m_token.tk == tkRParen)\n    {\n        m_pscan->Scan();\n        --parenCount;\n    }\n\n    if (!(m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly))\n    {\n        if (m_token.IsOperator())\n        {\n            Error(ERRDestructNoOper);\n        }\n        Error(ERRsyntax);\n    }\n\n    if (parenCount != 0)\n    {\n        Error(ERRnoRparen);\n    }\n    return pnodeElem;\n}\n\ntemplate <bool buildAST>\nParseNodePtr Parser::ParseDestructuredArrayLiteral(tokens declarationType, bool isDecl, bool topLevel)\n{\n    Assert(m_token.tk == tkLBrack);\n    charcount_t ichMin = m_pscan->IchMinTok();\n\n    m_pscan->Scan();\n\n    ParseNodePtr pnodeDestructArr = nullptr;\n    ParseNodePtr pnodeList = nullptr;\n    ParseNodePtr *lastNodeRef = nullptr;\n    uint count = 0;\n    bool hasMissingValues = false;\n    bool seenRest = false;\n\n    if (m_token.tk != tkRBrack)\n    {\n        while (true)\n        {\n            ParseNodePtr pnodeElem = ParseDestructuredVarDecl<buildAST>(declarationType, isDecl, &seenRest, topLevel);\n            if (buildAST)\n            {\n                if (pnodeElem == nullptr && buildAST)\n                {\n                    pnodeElem = CreateNodeWithScanner<knopEmpty>();\n                    hasMissingValues = true;\n                }\n                AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeElem);\n            }\n            count++;\n\n            if (m_token.tk == tkRBrack)\n            {\n                break;\n            }\n\n            if (m_token.tk != tkComma)\n            {\n                Error(ERRDestructNoOper);\n            }\n\n            if (seenRest) \/\/ Rest must be in the last position.\n            {\n                Error(ERRDestructRestLast);\n            }\n\n            m_pscan->Scan();\n\n            \/\/ break if we have the trailing comma as well, eg. [a,]\n            if (m_token.tk == tkRBrack)\n            {\n                break;\n            }\n        }\n    }\n\n    if (buildAST)\n    {\n        pnodeDestructArr = CreateNodeWithScanner<knopArrayPattern>();\n        pnodeDestructArr->sxArrLit.pnode1 = pnodeList;\n        pnodeDestructArr->sxArrLit.arrayOfTaggedInts = false;\n        pnodeDestructArr->sxArrLit.arrayOfInts = false;\n        pnodeDestructArr->sxArrLit.arrayOfNumbers = false;\n        pnodeDestructArr->sxArrLit.hasMissingValues = hasMissingValues;\n        pnodeDestructArr->sxArrLit.count = count;\n        pnodeDestructArr->sxArrLit.spreadCount = seenRest ? 1 : 0;\n        pnodeDestructArr->ichMin = ichMin;\n        pnodeDestructArr->ichLim = m_pscan->IchLimTok();\n\n        if (pnodeDestructArr->sxArrLit.pnode1)\n        {\n            this->CheckArguments(pnodeDestructArr->sxArrLit.pnode1);\n        }\n    }\n\n    return pnodeDestructArr;\n}\n\nvoid Parser::CaptureContext(ParseContext *parseContext) const\n{\n    parseContext->pszSrc = m_pscan->PchBase();\n    parseContext->length = this->m_originalLength;\n    parseContext->characterOffset = m_pscan->IchMinTok();\n    parseContext->offset = parseContext->characterOffset + m_pscan->m_cMultiUnits;\n    parseContext->grfscr = this->m_grfscr;\n    parseContext->lineNumber = m_pscan->LineCur();\n\n    parseContext->pnodeProg = this->m_currentNodeProg;\n    parseContext->fromExternal = m_pscan->IsFromExternalSource();\n    parseContext->strictMode = this->IsStrictMode();\n    parseContext->sourceContextInfo = this->m_sourceContextInfo;\n    parseContext->currentBlockInfo = this->m_currentBlockInfo;\n    parseContext->nextBlockId = this->m_nextBlockId;\n}\n\nvoid Parser::RestoreContext(ParseContext *const parseContext)\n{\n    m_sourceContextInfo = parseContext->sourceContextInfo;\n    m_currentBlockInfo = parseContext->currentBlockInfo;\n    m_nextBlockId = parseContext->nextBlockId;\n    m_grfscr = parseContext->grfscr;\n    m_length = parseContext->length;\n    m_pscan->SetText(parseContext->pszSrc, parseContext->offset, parseContext->length, parseContext->characterOffset, parseContext->grfscr, parseContext->lineNumber);\n    m_currentNodeProg = parseContext->pnodeProg;\n    m_fUseStrictMode = parseContext->strictMode;\n}\n\nclass ByteCodeGenerator;\n#if DBG_DUMP\n\n#define INDENT_SIZE 2\n\nvoid PrintPnodeListWIndent(ParseNode *pnode,int indentAmt);\nvoid PrintFormalsWIndent(ParseNode *pnode, int indentAmt);\n\n\nvoid Indent(int indentAmt) {\n    for (int i=0;i<indentAmt;i++) {\n        Output::Print(_u(\" \"));\n    }\n}\n\nvoid PrintBlockType(PnodeBlockType type)\n{\n    switch (type)\n    {\n    case Global:\n        Output::Print(_u(\"(Global)\"));\n        break;\n    case Function:\n        Output::Print(_u(\"(Function)\"));\n        break;\n    case Regular:\n        Output::Print(_u(\"(Regular)\"));\n        break;\n    case Parameter:\n        Output::Print(_u(\"(Parameter)\"));\n        break;\n    default:\n        Output::Print(_u(\"(unknown blocktype)\"));\n        break;\n    }\n}\n\nvoid PrintScopesWIndent(ParseNode *pnode,int indentAmt) {\n    ParseNode *scope = nullptr;\n    bool firstOnly = false;\n    switch(pnode->nop)\n    {\n    case knopProg:\n    case knopFncDecl: scope = pnode->sxFnc.pnodeScopes; break;\n    case knopBlock: scope = pnode->sxBlock.pnodeScopes; break;\n    case knopCatch: scope = pnode->sxCatch.pnodeScopes; break;\n    case knopWith: scope = pnode->sxWith.pnodeScopes; break;\n    case knopSwitch: scope = pnode->sxSwitch.pnodeBlock; firstOnly = true; break;\n    case knopFor: scope = pnode->sxFor.pnodeBlock; firstOnly = true; break;\n    case knopForIn: scope = pnode->sxForInOrForOf.pnodeBlock; firstOnly = true; break;\n    case knopForOf: scope = pnode->sxForInOrForOf.pnodeBlock; firstOnly = true; break;\n    }\n    if (scope) {\n        Output::Print(_u(\"[%4d, %4d): \"), scope->ichMin, scope->ichLim);\n        Indent(indentAmt);\n        Output::Print(_u(\"Scopes: \"));\n        ParseNode *next = nullptr;\n        ParseNode *syntheticBlock = nullptr;\n        while (scope) {\n            switch (scope->nop) {\n            case knopFncDecl: Output::Print(_u(\"knopFncDecl\")); next = scope->sxFnc.pnodeNext; break;\n            case knopBlock: Output::Print(_u(\"knopBlock\")); PrintBlockType(scope->sxBlock.blockType); next = scope->sxBlock.pnodeNext; break;\n            case knopCatch: Output::Print(_u(\"knopCatch\")); next = scope->sxCatch.pnodeNext; break;\n            case knopWith: Output::Print(_u(\"knopWith\")); next = scope->sxWith.pnodeNext; break;\n            default: Output::Print(_u(\"unknown\")); break;\n            }\n            if (firstOnly) {\n                next = nullptr;\n                syntheticBlock = scope;\n            }\n            if (scope->grfpn & fpnSyntheticNode) {\n                Output::Print(_u(\" synthetic\"));\n                if (scope->nop == knopBlock)\n                    syntheticBlock = scope;\n            }\n            Output::Print(_u(\" (%d-%d)\"), scope->ichMin, scope->ichLim);\n            if (next) Output::Print(_u(\", \"));\n            scope = next;\n        }\n        Output::Print(_u(\"\\n\"));\n        if (syntheticBlock || firstOnly) {\n            PrintScopesWIndent(syntheticBlock, indentAmt + INDENT_SIZE);\n        }\n    }\n}\n\nvoid PrintPnodeWIndent(ParseNode *pnode,int indentAmt) {\n    if (pnode==NULL)\n        return;\n\n    Output::Print(_u(\"[%4d, %4d): \"), pnode->ichMin, pnode->ichLim);\n    switch (pnode->nop) {\n        \/\/PTNODE(knopName       , \"name\"        ,None    ,Pid  ,fnopLeaf)\n  case knopName:\n      Indent(indentAmt);\n      if (pnode->sxPid.pid!=NULL) {\n        Output::Print(_u(\"id: %s\\n\"),pnode->sxPid.pid->Psz());\n      }\n      else {\n        Output::Print(_u(\"name node\\n\"));\n      }\n      break;\n      \/\/PTNODE(knopInt        , \"int const\"    ,None    ,Int  ,fnopLeaf|fnopConst)\n  case knopInt:\n      Indent(indentAmt);\n      Output::Print(_u(\"%d\\n\"),pnode->sxInt.lw);\n      break;\n      \/\/PTNODE(knopFlt        , \"flt const\"    ,None    ,Flt  ,fnopLeaf|fnopConst)\n  case knopFlt:\n      Indent(indentAmt);\n      Output::Print(_u(\"%lf\\n\"),pnode->sxFlt.dbl);\n      break;\n      \/\/PTNODE(knopStr        , \"str const\"    ,None    ,Pid  ,fnopLeaf|fnopConst)\n  case knopStr:\n      Indent(indentAmt);\n      Output::Print(_u(\"\\\"%s\\\"\\n\"),pnode->sxPid.pid->Psz());\n      break;\n      \/\/PTNODE(knopRegExp     , \"reg expr\"    ,None    ,Pid  ,fnopLeaf|fnopConst)\n  case knopRegExp:\n      Indent(indentAmt);\n      Output::Print(_u(\"\/%x\/\\n\"),pnode->sxPid.regexPattern);\n      break;\n      \/\/PTNODE(knopThis       , \"this\"        ,None    ,None ,fnopLeaf)\n  case knopThis:\n      Indent(indentAmt);\n      Output::Print(_u(\"this\\n\"));\n      break;\n      \/\/PTNODE(knopSuper      , \"super\"       ,None    ,None ,fnopLeaf)\n  case knopSuper:\n      Indent(indentAmt);\n      Output::Print(_u(\"super\\n\"));\n      break;\n      \/\/PTNODE(knopNewTarget  , \"new.target\"  ,None    ,None ,fnopLeaf)\n  case knopNewTarget:\n      Indent(indentAmt);\n      Output::Print(_u(\"new.target\\n\"));\n      break;\n      \/\/PTNODE(knopNull       , \"null\"        ,Null    ,None ,fnopLeaf)\n  case knopNull:\n      Indent(indentAmt);\n      Output::Print(_u(\"null\\n\"));\n      break;\n      \/\/PTNODE(knopFalse      , \"false\"        ,False   ,None ,fnopLeaf)\n  case knopFalse:\n      Indent(indentAmt);\n      Output::Print(_u(\"false\\n\"));\n      break;\n      \/\/PTNODE(knopTrue       , \"true\"        ,True    ,None ,fnopLeaf)\n  case knopTrue:\n      Indent(indentAmt);\n      Output::Print(_u(\"true\\n\"));\n      break;\n      \/\/PTNODE(knopEmpty      , \"empty\"        ,Empty   ,None ,fnopLeaf)\n  case knopEmpty:\n      Indent(indentAmt);\n      Output::Print(_u(\"empty\\n\"));\n      break;\n      \/\/ Unary operators.\n      \/\/PTNODE(knopNot        , \"~\"            ,BitNot  ,Uni  ,fnopUni)\n  case knopNot:\n      Indent(indentAmt);\n      Output::Print(_u(\"~\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopNeg        , \"unary -\"    ,Neg     ,Uni  ,fnopUni)\n  case knopNeg:\n      Indent(indentAmt);\n      Output::Print(_u(\"U-\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopPos        , \"unary +\"    ,Pos     ,Uni  ,fnopUni)\n  case knopPos:\n      Indent(indentAmt);\n      Output::Print(_u(\"U+\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopLogNot     , \"!\"            ,LogNot  ,Uni  ,fnopUni)\n  case knopLogNot:\n      Indent(indentAmt);\n      Output::Print(_u(\"!\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopEllipsis     , \"...\"       ,Spread  ,Uni    , fnopUni)\n  case knopEllipsis:\n      Indent(indentAmt);\n      Output::Print(_u(\"...<expr>\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopIncPost    , \"++ post\"    ,Inc     ,Uni  ,fnopUni|fnopAsg)\n  case knopIncPost:\n      Indent(indentAmt);\n      Output::Print(_u(\"<expr>++\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopDecPost    , \"-- post\"    ,Dec     ,Uni  ,fnopUni|fnopAsg)\n  case knopDecPost:\n      Indent(indentAmt);\n      Output::Print(_u(\"<expr>--\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopIncPre     , \"++ pre\"    ,Inc     ,Uni  ,fnopUni|fnopAsg)\n  case knopIncPre:\n      Indent(indentAmt);\n      Output::Print(_u(\"++<expr>\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopDecPre     , \"-- pre\"    ,Dec     ,Uni  ,fnopUni|fnopAsg)\n  case knopDecPre:\n      Indent(indentAmt);\n      Output::Print(_u(\"--<expr>\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopTypeof     , \"typeof\"    ,None    ,Uni  ,fnopUni)\n  case knopTypeof:\n      Indent(indentAmt);\n      Output::Print(_u(\"typeof\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopVoid       , \"void\"        ,Void    ,Uni  ,fnopUni)\n  case knopVoid:\n      Indent(indentAmt);\n      Output::Print(_u(\"void\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopDelete     , \"delete\"    ,None    ,Uni  ,fnopUni)\n  case knopDelete:\n      Indent(indentAmt);\n      Output::Print(_u(\"delete\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopArray      , \"arr cnst\"    ,None    ,Uni  ,fnopUni)\n\n  case knopArrayPattern:\n      Indent(indentAmt);\n      Output::Print(_u(\"Array Pattern\\n\"));\n      PrintPnodeListWIndent(pnode->sxUni.pnode1, indentAmt + INDENT_SIZE);\n      break;\n\n  case knopObjectPattern:\n      Indent(indentAmt);\n      Output::Print(_u(\"Object Pattern\\n\"));\n      PrintPnodeListWIndent(pnode->sxUni.pnode1, indentAmt + INDENT_SIZE);\n      break;\n\n  case knopArray:\n      Indent(indentAmt);\n      Output::Print(_u(\"Array Literal\\n\"));\n      PrintPnodeListWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopObject     , \"obj cnst\"    ,None    ,Uni  ,fnopUni)\n  case knopObject:\n      Indent(indentAmt);\n      Output::Print(_u(\"Object Literal\\n\"));\n      PrintPnodeListWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/ Binary and Ternary Operators\n      \/\/PTNODE(knopAdd        , \"+\"            ,Add     ,Bin  ,fnopBin)\n  case knopAdd:\n      Indent(indentAmt);\n      Output::Print(_u(\"+\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopSub        , \"-\"            ,Sub     ,Bin  ,fnopBin)\n  case knopSub:\n      Indent(indentAmt);\n      Output::Print(_u(\"-\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopMul        , \"*\"            ,Mul     ,Bin  ,fnopBin)\n  case knopMul:\n      Indent(indentAmt);\n      Output::Print(_u(\"*\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopDiv        , \"\/\"            ,Div     ,Bin  ,fnopBin)\n  case knopExpo:\n      Indent(indentAmt);\n      Output::Print(_u(\"**\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1, indentAmt + INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2, indentAmt + INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopExpo        , \"**\"            ,Expo     ,Bin  ,fnopBin)\n\n  case knopDiv:\n      Indent(indentAmt);\n      Output::Print(_u(\"\/\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopMod        , \"%\"            ,Mod     ,Bin  ,fnopBin)\n  case knopMod:\n      Indent(indentAmt);\n      Output::Print(_u(\"%\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopOr         , \"|\"            ,BitOr   ,Bin  ,fnopBin)\n  case knopOr:\n      Indent(indentAmt);\n      Output::Print(_u(\"|\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopXor        , \"^\"            ,BitXor  ,Bin  ,fnopBin)\n  case knopXor:\n      Indent(indentAmt);\n      Output::Print(_u(\"^\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAnd        , \"&\"            ,BitAnd  ,Bin  ,fnopBin)\n  case knopAnd:\n      Indent(indentAmt);\n      Output::Print(_u(\"&\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopEq         , \"==\"        ,EQ      ,Bin  ,fnopBin|fnopRel)\n  case knopEq:\n      Indent(indentAmt);\n      Output::Print(_u(\"==\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopNe         , \"!=\"        ,NE      ,Bin  ,fnopBin|fnopRel)\n  case knopNe:\n      Indent(indentAmt);\n      Output::Print(_u(\"!=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopLt         , \"<\"            ,LT      ,Bin  ,fnopBin|fnopRel)\n  case knopLt:\n      Indent(indentAmt);\n      Output::Print(_u(\"<\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopLe         , \"<=\"        ,LE      ,Bin  ,fnopBin|fnopRel)\n  case knopLe:\n      Indent(indentAmt);\n      Output::Print(_u(\"<=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopGe         , \">=\"        ,GE      ,Bin  ,fnopBin|fnopRel)\n  case knopGe:\n      Indent(indentAmt);\n      Output::Print(_u(\">=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopGt         , \">\"            ,GT      ,Bin  ,fnopBin|fnopRel)\n  case knopGt:\n      Indent(indentAmt);\n      Output::Print(_u(\">\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopCall       , \"()\"        ,None    ,Bin  ,fnopBin)\n  case knopCall:\n      Indent(indentAmt);\n      Output::Print(_u(\"Call\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeListWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopDot        , \".\"            ,None    ,Bin  ,fnopBin)\n  case knopDot:\n      Indent(indentAmt);\n      Output::Print(_u(\".\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAsg        , \"=\"            ,None    ,Bin  ,fnopBin|fnopAsg)\n  case knopAsg:\n      Indent(indentAmt);\n      Output::Print(_u(\"=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopInstOf     , \"instanceof\",InstOf  ,Bin  ,fnopBin|fnopRel)\n  case knopInstOf:\n      Indent(indentAmt);\n      Output::Print(_u(\"instanceof\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopIn         , \"in\"        ,In      ,Bin  ,fnopBin|fnopRel)\n  case knopIn:\n      Indent(indentAmt);\n      Output::Print(_u(\"in\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopEqv        , \"===\"        ,Eqv     ,Bin  ,fnopBin|fnopRel)\n  case knopEqv:\n      Indent(indentAmt);\n      Output::Print(_u(\"===\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopNEqv       , \"!==\"        ,NEqv    ,Bin  ,fnopBin|fnopRel)\n  case knopNEqv:\n      Indent(indentAmt);\n      Output::Print(_u(\"!==\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopComma      , \",\"            ,None    ,Bin  ,fnopBin)\n  case knopComma:\n      Indent(indentAmt);\n      Output::Print(_u(\",\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopLogOr      , \"||\"        ,None    ,Bin  ,fnopBin)\n  case knopLogOr:\n      Indent(indentAmt);\n      Output::Print(_u(\"||\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopLogAnd     , \"&&\"        ,None    ,Bin  ,fnopBin)\n  case knopLogAnd:\n      Indent(indentAmt);\n      Output::Print(_u(\"&&\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopLsh        , \"<<\"        ,Lsh     ,Bin  ,fnopBin)\n  case knopLsh:\n      Indent(indentAmt);\n      Output::Print(_u(\"<<\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopRsh        , \">>\"        ,Rsh     ,Bin  ,fnopBin)\n  case knopRsh:\n      Indent(indentAmt);\n      Output::Print(_u(\">>\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopRs2        , \">>>\"        ,Rs2     ,Bin  ,fnopBin)\n  case knopRs2:\n      Indent(indentAmt);\n      Output::Print(_u(\">>>\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopNew        , \"new\"        ,None    ,Bin  ,fnopBin)\n  case knopNew:\n      Indent(indentAmt);\n      Output::Print(_u(\"new\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeListWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopIndex      , \"[]\"        ,None    ,Bin  ,fnopBin)\n  case knopIndex:\n      Indent(indentAmt);\n      Output::Print(_u(\"[]\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeListWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopQmark      , \"?\"            ,None    ,Tri  ,fnopBin)\n  case knopQmark:\n      Indent(indentAmt);\n      Output::Print(_u(\"?:\\n\"));\n      PrintPnodeWIndent(pnode->sxTri.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxTri.pnode2,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxTri.pnode3,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAsgAdd     , \"+=\"        ,Add     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgAdd:\n      Indent(indentAmt);\n      Output::Print(_u(\"+=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAsgSub     , \"-=\"        ,Sub     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgSub:\n      Indent(indentAmt);\n      Output::Print(_u(\"-=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAsgMul     , \"*=\"        ,Mul     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgMul:\n      Indent(indentAmt);\n      Output::Print(_u(\"*=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAsgDiv     , \"\/=\"        ,Div     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgExpo:\n      Indent(indentAmt);\n      Output::Print(_u(\"**=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1, indentAmt + INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2, indentAmt + INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAsgExpo     , \"**=\"       ,Expo     ,Bin  ,fnopBin|fnopAsg)\n\n  case knopAsgDiv:\n      Indent(indentAmt);\n      Output::Print(_u(\"\/=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAsgMod     , \"%=\"        ,Mod     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgMod:\n      Indent(indentAmt);\n      Output::Print(_u(\"%=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAsgAnd     , \"&=\"        ,BitAnd  ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgAnd:\n      Indent(indentAmt);\n      Output::Print(_u(\"&=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAsgXor     , \"^=\"        ,BitXor  ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgXor:\n      Indent(indentAmt);\n      Output::Print(_u(\"^=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAsgOr      , \"|=\"        ,BitOr   ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgOr:\n      Indent(indentAmt);\n      Output::Print(_u(\"|=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAsgLsh     , \"<<=\"        ,Lsh     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgLsh:\n      Indent(indentAmt);\n      Output::Print(_u(\"<<=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAsgRsh     , \">>=\"        ,Rsh     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgRsh:\n      Indent(indentAmt);\n      Output::Print(_u(\">>=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopAsgRs2     , \">>>=\"        ,Rs2     ,Bin  ,fnopBin|fnopAsg)\n  case knopAsgRs2:\n      Indent(indentAmt);\n      Output::Print(_u(\">>>=\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n\n  case knopComputedName:\n      Indent(indentAmt);\n      Output::Print(_u(\"ComputedProperty\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1, indentAmt + INDENT_SIZE);\n      break;\n\n      \/\/PTNODE(knopMember     , \":\"            ,None    ,Bin  ,fnopBin)\n  case knopMember:\n  case knopMemberShort:\n  case knopObjectPatternMember:\n      Indent(indentAmt);\n      Output::Print(_u(\":\\n\"));\n      PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);\n      break;\n      \/\/ General nodes.\n      \/\/PTNODE(knopList       , \"<list>\"    ,None    ,Bin  ,fnopNone)\n  case knopList:\n      Indent(indentAmt);\n      Output::Print(_u(\"List\\n\"));\n      PrintPnodeListWIndent(pnode,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopVarDecl    , \"varDcl\"    ,None    ,Var  ,fnopNone)\n  case knopVarDecl:\n      Indent(indentAmt);\n      Output::Print(_u(\"var %s\\n\"),pnode->sxVar.pid->Psz());\n      if (pnode->sxVar.pnodeInit!=NULL)\n          PrintPnodeWIndent(pnode->sxVar.pnodeInit,indentAmt+INDENT_SIZE);\n      break;\n  case knopConstDecl:\n      Indent(indentAmt);\n      Output::Print(_u(\"const %s\\n\"),pnode->sxVar.pid->Psz());\n      if (pnode->sxVar.pnodeInit!=NULL)\n          PrintPnodeWIndent(pnode->sxVar.pnodeInit,indentAmt+INDENT_SIZE);\n      break;\n  case knopLetDecl:\n      Indent(indentAmt);\n      Output::Print(_u(\"let %s\\n\"),pnode->sxVar.pid->Psz());\n      if (pnode->sxVar.pnodeInit!=NULL)\n          PrintPnodeWIndent(pnode->sxVar.pnodeInit,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopFncDecl    , \"fncDcl\"    ,None    ,Fnc  ,fnopLeaf)\n  case knopFncDecl:\n      Indent(indentAmt);\n      if (pnode->sxFnc.pid!=NULL)\n      {\n          Output::Print(_u(\"fn decl %d nested %d name %s (%d-%d)\\n\"),pnode->sxFnc.IsDeclaration(),pnode->sxFnc.IsNested(),\n              pnode->sxFnc.pid->Psz(), pnode->ichMin, pnode->ichLim);\n      }\n      else\n      {\n          Output::Print(_u(\"fn decl %d nested %d anonymous (%d-%d)\\n\"),pnode->sxFnc.IsDeclaration(),pnode->sxFnc.IsNested(),pnode->ichMin,pnode->ichLim);\n      }\n      PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);\n      PrintFormalsWIndent(pnode->sxFnc.pnodeParams, indentAmt + INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxFnc.pnodeRest, indentAmt + INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxFnc.pnodeBody, indentAmt + INDENT_SIZE);\n      if (pnode->sxFnc.pnodeBody == nullptr)\n      {\n          Output::Print(_u(\"[%4d, %4d): \"), pnode->ichMin, pnode->ichLim);\n          Indent(indentAmt + INDENT_SIZE);\n          Output::Print(_u(\"<parse deferred body>\\n\"));\n      }\n      break;\n      \/\/PTNODE(knopProg       , \"program\"    ,None    ,Fnc  ,fnopNone)\n  case knopProg:\n      Indent(indentAmt);\n      Output::Print(_u(\"program\\n\"));\n      PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);\n      PrintPnodeListWIndent(pnode->sxFnc.pnodeBody,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopEndCode    , \"<endcode>\"    ,None    ,None ,fnopNone)\n  case knopEndCode:\n      Indent(indentAmt);\n      Output::Print(_u(\"<endcode>\\n\"));\n      break;\n      \/\/PTNODE(knopDebugger   , \"debugger\"    ,None    ,None ,fnopNone)\n  case knopDebugger:\n      Indent(indentAmt);\n      Output::Print(_u(\"<debugger>\\n\"));\n      break;\n      \/\/PTNODE(knopFor        , \"for\"        ,None    ,For  ,fnopBreak|fnopContinue)\n  case knopFor:\n      Indent(indentAmt);\n      Output::Print(_u(\"for\\n\"));\n      PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxFor.pnodeInit,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxFor.pnodeCond,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxFor.pnodeIncr,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxFor.pnodeBody,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopIf         , \"if\"        ,None    ,If   ,fnopNone)\n  case knopIf:\n      Indent(indentAmt);\n      Output::Print(_u(\"if\\n\"));\n      PrintPnodeWIndent(pnode->sxIf.pnodeCond,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxIf.pnodeTrue,indentAmt+INDENT_SIZE);\n      if (pnode->sxIf.pnodeFalse!=NULL)\n          PrintPnodeWIndent(pnode->sxIf.pnodeFalse,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopWhile      , \"while\"        ,None    ,While,fnopBreak|fnopContinue)\n  case knopWhile:\n      Indent(indentAmt);\n      Output::Print(_u(\"while\\n\"));\n      PrintPnodeWIndent(pnode->sxWhile.pnodeCond,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxWhile.pnodeBody,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopDoWhile    , \"do-while\"    ,None    ,While,fnopBreak|fnopContinue)\n  case knopDoWhile:\n      Indent(indentAmt);\n      Output::Print(_u(\"do\\n\"));\n      PrintPnodeWIndent(pnode->sxWhile.pnodeCond,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxWhile.pnodeBody,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopForIn      , \"for in\"    ,None    ,ForIn,fnopBreak|fnopContinue|fnopCleanup)\n  case knopForIn:\n      Indent(indentAmt);\n      Output::Print(_u(\"forIn\\n\"));\n      PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxForInOrForOf.pnodeLval,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxForInOrForOf.pnodeObj,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxForInOrForOf.pnodeBody,indentAmt+INDENT_SIZE);\n      break;\n  case knopForOf:\n      Indent(indentAmt);\n      Output::Print(_u(\"forOf\\n\"));\n      PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxForInOrForOf.pnodeLval,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxForInOrForOf.pnodeObj,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxForInOrForOf.pnodeBody,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopReturn     , \"return\"    ,None    ,Uni  ,fnopNone)\n  case knopReturn:\n      Indent(indentAmt);\n      Output::Print(_u(\"return\\n\"));\n      if (pnode->sxReturn.pnodeExpr!=NULL)\n          PrintPnodeWIndent(pnode->sxReturn.pnodeExpr,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopBlock      , \"{}\"        ,None    ,Block,fnopNone)\n  case knopBlock:\n      Indent(indentAmt);\n      Output::Print(_u(\"block \"));\n      if (pnode->grfpn & fpnSyntheticNode)\n          Output::Print(_u(\"synthetic \"));\n      PrintBlockType(pnode->sxBlock.blockType);\n      Output::Print(_u(\"(%d-%d)\\n\"),pnode->ichMin,pnode->ichLim);\n      PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);\n      if (pnode->sxBlock.pnodeStmt!=NULL)\n          PrintPnodeWIndent(pnode->sxBlock.pnodeStmt,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopWith       , \"with\"        ,None    ,With ,fnopCleanup)\n  case knopWith:\n      Indent(indentAmt);\n      Output::Print(_u(\"with (%d-%d)\\n\"), pnode->ichMin,pnode->ichLim);\n      PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxWith.pnodeObj,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxWith.pnodeBody,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopBreak      , \"break\"        ,None    ,Jump ,fnopNone)\n  case knopBreak:\n      Indent(indentAmt);\n      Output::Print(_u(\"break\\n\"));\n      \/\/ TODO: some representation of target\n      break;\n      \/\/PTNODE(knopContinue   , \"continue\"    ,None    ,Jump ,fnopNone)\n  case knopContinue:\n      Indent(indentAmt);\n      Output::Print(_u(\"continue\\n\"));\n      \/\/ TODO: some representation of target\n      break;\n      \/\/PTNODE(knopLabel      , \"label\"        ,None    ,Label,fnopNone)\n  case knopLabel:\n      Indent(indentAmt);\n      Output::Print(_u(\"label %s\"),pnode->sxLabel.pid->Psz());\n      \/\/ TODO: print labeled statement\n      break;\n      \/\/PTNODE(knopSwitch     , \"switch\"    ,None    ,Switch,fnopBreak)\n  case knopSwitch:\n      Indent(indentAmt);\n      Output::Print(_u(\"switch\\n\"));\n      PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);\n      for (ParseNode *pnodeT = pnode->sxSwitch.pnodeCases; NULL != pnodeT;pnodeT = pnodeT->sxCase.pnodeNext) {\n          PrintPnodeWIndent(pnodeT,indentAmt+2);\n      }\n      break;\n      \/\/PTNODE(knopCase       , \"case\"        ,None    ,Case ,fnopNone)\n  case knopCase:\n      Indent(indentAmt);\n      Output::Print(_u(\"case\\n\"));\n      PrintPnodeWIndent(pnode->sxCase.pnodeExpr,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxCase.pnodeBody,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopTryFinally,\"try-finally\",None,TryFinally,fnopCleanup)\n  case knopTryFinally:\n      PrintPnodeWIndent(pnode->sxTryFinally.pnodeTry,indentAmt);\n      PrintPnodeWIndent(pnode->sxTryFinally.pnodeFinally,indentAmt);\n      break;\n  case knopFinally:\n      Indent(indentAmt);\n      Output::Print(_u(\"finally\\n\"));\n      PrintPnodeWIndent(pnode->sxFinally.pnodeBody,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopCatch      , \"catch\"     ,None    ,Catch,fnopNone)\n  case knopCatch:\n      Indent(indentAmt);\n      Output::Print(_u(\"catch (%d-%d)\\n\"), pnode->ichMin,pnode->ichLim);\n      PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxCatch.pnodeParam,indentAmt+INDENT_SIZE);\n\/\/      if (pnode->sxCatch.pnodeGuard!=NULL)\n\/\/          PrintPnodeWIndent(pnode->sxCatch.pnodeGuard,indentAmt+INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxCatch.pnodeBody,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopTryCatch      , \"try-catch\" ,None    ,TryCatch  ,fnopCleanup)\n  case knopTryCatch:\n      PrintPnodeWIndent(pnode->sxTryCatch.pnodeTry,indentAmt);\n      PrintPnodeWIndent(pnode->sxTryCatch.pnodeCatch,indentAmt);\n      break;\n      \/\/PTNODE(knopTry        , \"try\"       ,None    ,Try  ,fnopCleanup)\n  case knopTry:\n      Indent(indentAmt);\n      Output::Print(_u(\"try\\n\"));\n      PrintPnodeWIndent(pnode->sxTry.pnodeBody,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopThrow      , \"throw\"     ,None    ,Uni  ,fnopNone)\n  case knopThrow:\n      Indent(indentAmt);\n      Output::Print(_u(\"throw\\n\"));\n      PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);\n      break;\n      \/\/PTNODE(knopClassDecl, \"classDecl\", None , Class, fnopLeaf)\n  case knopClassDecl:\n      Indent(indentAmt);\n      Output::Print(_u(\"class %s\"), pnode->sxClass.pnodeName->sxVar.pid->Psz());\n      if (pnode->sxClass.pnodeExtends != nullptr)\n      {\n          Output::Print(_u(\" extends \"));\n          PrintPnodeWIndent(pnode->sxClass.pnodeExtends, 0);\n      }\n      else {\n          Output::Print(_u(\"\\n\"));\n      }\n\n      PrintPnodeWIndent(pnode->sxClass.pnodeConstructor,   indentAmt + INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxClass.pnodeMembers,       indentAmt + INDENT_SIZE);\n      PrintPnodeWIndent(pnode->sxClass.pnodeStaticMembers, indentAmt + INDENT_SIZE);\n      break;\n  case knopStrTemplate:\n      Indent(indentAmt);\n      Output::Print(_u(\"string template\\n\"));\n      PrintPnodeListWIndent(pnode->sxStrTemplate.pnodeSubstitutionExpressions, indentAmt + INDENT_SIZE);\n      break;\n  case knopYieldStar:\n      Indent(indentAmt);\n      Output::Print(_u(\"yield*\\n\"));\n      PrintPnodeListWIndent(pnode->sxUni.pnode1, indentAmt + INDENT_SIZE);\n      break;\n  case knopYield:\n  case knopYieldLeaf:\n      Indent(indentAmt);\n      Output::Print(_u(\"yield\\n\"));\n      PrintPnodeListWIndent(pnode->sxUni.pnode1, indentAmt + INDENT_SIZE);\n      break;\n  case knopAwait:\n      Indent(indentAmt);\n      Output::Print(_u(\"await\\n\"));\n      PrintPnodeListWIndent(pnode->sxUni.pnode1, indentAmt + INDENT_SIZE);\n      break;\n  case knopExportDefault:\n      Indent(indentAmt);\n      Output::Print(_u(\"export default\\n\"));\n      PrintPnodeListWIndent(pnode->sxExportDefault.pnodeExpr, indentAmt + INDENT_SIZE);\n      break;\n  default:\n      Output::Print(_u(\"unhandled pnode op %d\\n\"),pnode->nop);\n      break;\n    }\n}\n\nvoid PrintPnodeListWIndent(ParseNode *pnode,int indentAmt) {\n    if (pnode!=NULL) {\n        while(pnode->nop==knopList) {\n            PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt);\n            pnode = pnode->sxBin.pnode2;\n        }\n        PrintPnodeWIndent(pnode,indentAmt);\n    }\n}\n\nvoid PrintFormalsWIndent(ParseNode *pnodeArgs, int indentAmt)\n{\n    for (ParseNode *pnode = pnodeArgs; pnode != nullptr; pnode = pnode->GetFormalNext())\n    {\n        PrintPnodeWIndent(pnode->nop == knopParamPattern ? pnode->sxParamPattern.pnode1 : pnode, indentAmt);\n    }\n}\n\nvoid PrintPnode(ParseNode *pnode) {\n    PrintPnodeWIndent(pnode,0);\n}\n\nvoid ParseNode::Dump()\n{\n    switch(nop)\n    {\n    case knopFncDecl:\n    case knopProg:\n        LPCOLESTR name = Js::Constants::AnonymousFunction;\n        if(this->sxFnc.pnodeName)\n        {\n            name = this->sxFnc.pnodeName->sxVar.pid->Psz();\n        }\n\n        Output::Print(_u(\"%s (%d) [%d, %d]:\\n\"), name, this->sxFnc.functionId, this->sxFnc.lineNumber, this->sxFnc.columnNumber);\n        Output::Print(_u(\"hasArguments: %s callsEval:%s childCallsEval:%s HasReferenceableBuiltInArguments:%s ArgumentsObjectEscapes:%s HasWith:%s HasThis:%s HasOnlyThis:%s \\n\"),\n            IsTrueOrFalse(this->sxFnc.HasHeapArguments()),\n            IsTrueOrFalse(this->sxFnc.CallsEval()),\n            IsTrueOrFalse(this->sxFnc.ChildCallsEval()),\n            IsTrueOrFalse(this->sxFnc.HasReferenceableBuiltInArguments()),\n            IsTrueOrFalse(this->sxFnc.GetArgumentsObjectEscapes()),\n            IsTrueOrFalse(this->sxFnc.HasWithStmt()),\n            IsTrueOrFalse(this->sxFnc.HasThisStmt()),\n            IsTrueOrFalse(this->sxFnc.HasOnlyThisStmts()));\n        if(this->sxFnc.funcInfo)\n        {\n            this->sxFnc.funcInfo->Dump();\n        }\n        break;\n    }\n}\n#endif\n\nDeferredFunctionStub * BuildDeferredStubTree(ParseNode *pnodeFnc, Recycler *recycler)\n{\n    Assert(pnodeFnc->nop == knopFncDecl);\n\n    uint nestedCount = pnodeFnc->sxFnc.nestedCount;\n    if (nestedCount == 0)\n    {\n        return nullptr;\n    }\n\n    if (pnodeFnc->sxFnc.deferredStub)\n    {\n        return pnodeFnc->sxFnc.deferredStub;\n    }\n\n    DeferredFunctionStub *deferredStubs = RecyclerNewArray(recycler, DeferredFunctionStub, nestedCount);\n    uint i = 0;\n\n    ParseNode *pnodeBlock = pnodeFnc->sxFnc.pnodeBodyScope;\n    Assert(pnodeBlock != nullptr\n        && pnodeBlock->nop == knopBlock\n        && (pnodeBlock->sxBlock.blockType == PnodeBlockType::Function\n            || pnodeBlock->sxBlock.blockType == PnodeBlockType::Parameter));\n\n    for (ParseNode *pnodeChild = pnodeBlock->sxBlock.pnodeScopes; pnodeChild != nullptr;)\n    {\n\n        if (pnodeChild->nop != knopFncDecl)\n        {\n            \/\/ We only expect to find a function body block in a parameter scope block.\n            Assert(pnodeChild->nop == knopBlock\n                && (pnodeBlock->sxBlock.blockType == PnodeBlockType::Parameter\n                    || pnodeChild->sxBlock.blockType == PnodeBlockType::Function));\n            pnodeChild = pnodeChild->sxBlock.pnodeNext;\n            continue;\n        }\n        Assert(i < nestedCount);\n\n        if (pnodeChild->sxFnc.IsGeneratedDefault())\n        {\n            ++i;\n            pnodeChild = pnodeChild->sxFnc.pnodeNext;\n            continue;\n        }\n\n        __analysis_assume(i < nestedCount);\n\n        deferredStubs[i].fncFlags = pnodeChild->sxFnc.fncFlags;\n        deferredStubs[i].nestedCount = pnodeChild->sxFnc.nestedCount;\n        deferredStubs[i].restorePoint = *pnodeChild->sxFnc.pRestorePoint;\n        deferredStubs[i].deferredStubs = BuildDeferredStubTree(pnodeChild, recycler);\n        deferredStubs[i].ichMin = pnodeChild->ichMin;\n        ++i;\n        pnodeChild = pnodeChild->sxFnc.pnodeNext;\n    }\n\n    return deferredStubs;\n}\n","avg_line_length":34.3181750075,"max_line_length":229,"alphanum_fraction":0.5845039829,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":454,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\n#include <memory>\nusing namespace std;\n\nclass Sample {\npublic:\n  Sample() {\n    cout << \"Sample Constructor\" << endl;\n  }\n\n  ~Sample() {\n    cout << \"Sample Destructor\" << endl;\n  }\n\n  void publicFn() {\n    cout << \"This is public function of class.\" << endl;\n  }\n};\n\nvoid TestUniquePtr_ReleaseMemory() {\n  unique_ptr<Sample> up(new Sample{});\n  up->publicFn();\n  return;\n}\n\nint main() {\n  TestUniquePtr_ReleaseMemory();\n  return 0;\n}","avg_line_length":15.6551724138,"max_line_length":56,"alphanum_fraction":0.627753304,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":22839,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["OML"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Copyright (c) 2019 Bitcoin Association\n\/\/ Copyright (c) 2020* Jimmy N. Lose\n\/\/ * Gregorian calendar years\n\/\/ Distributed under the Open BSV software license, see the accompanying file\n\/\/ LICENSE.\n\n#include \"config.h\"\n#include \"consensus\/validation.h\"\n#include \"key.h\"\n#include \"keystore.h\"\n#include \"mining\/legacy.h\"\n#include \"pubkey.h\"\n#include \"random.h\"\n#include \"script\/scriptcache.h\"\n#include \"script\/sighashtype.h\"\n#include \"script\/sign.h\"\n#include \"script\/standard.h\"\n#include \"test\/sigutil.h\"\n#include \"test\/test_bitcoin.h\"\n#include \"txmempool.h\"\n#include \"txn_validator.h\"\n#include \"utiltime.h\"\n\n#include <boost\/test\/unit_test.hpp>\n\nnamespace {\n    struct TestChain100Setup2 : TestChain100Setup {\n        \/**\n         * Check if txn is valid and accepted by the mempool.\n         *\n         *\/\n        \/\/ TxnValidator\n        bool ToMemPool(CMutableTransaction &tx) {\n            \/\/ Mock rpc txn\n            auto pTxInputData {\n                std::make_shared<CTxInputData>(\n                                    TxSource::rpc,            \/\/ tx source\n                                    TxValidationPriority::normal,   \/\/ tx validation priority\n                                    MakeTransactionRef(tx),   \/\/ a pointer to the tx\n                                    GetTime(),                \/\/ nAcceptTime\n                                    false)                    \/\/ fLimitFree\n            };\n            \/\/ Mempool Journal ChangeSet\n            mining::CJournalChangeSetPtr changeSet {nullptr};\n            \/\/ Execute validation via synchronous interface\n            const auto& status {\n                txnValidator->processValidation(pTxInputData, changeSet)\n            };\n            return status.IsValid();\n        }\n        \/\/ A default double spend detector\n        TxnDoubleSpendDetectorSPtr dsDetector {\n            std::make_shared<CTxnDoubleSpendDetector>()\n        };\n        \/\/ Create txn validator\n        std::shared_ptr<CTxnValidator> txnValidator {\n            std::make_shared<CTxnValidator>(\n                    GlobalConfig::GetConfig(),\n                    mempool,\n                    dsDetector)\n        };\n    };\n\n    \/\/ Run CheckInputs (using pcoinsTip) on the given transaction, for all script\n    \/\/ flags. Test that CheckInputs passes for all flags that don't overlap with the\n    \/\/ failing_flags argument, but otherwise fails.\n    \/\/ CHECKLOCKTIMEVERIFY and CHECKSEQUENCEVERIFY (and future NOP codes that may\n    \/\/ get reassigned) have an interaction with DISCOURAGE_UPGRADABLE_NOPS: if the\n    \/\/ script flags used contain DISCOURAGE_UPGRADABLE_NOPS but don't contain\n    \/\/ CHECKLOCKTIMEVERIFY (or CHECKSEQUENCEVERIFY), but the script does contain\n    \/\/ OP_CHECKLOCKTIMEVERIFY (or OP_CHECKSEQUENCEVERIFY), then script execution\n    \/\/ should fail.\n    \/\/ Capture this interaction with the upgraded_nop argument: set it when\n    \/\/ evaluating any script flag that is implemented as an upgraded NOP code.\n    void ValidateCheckInputsForAllFlags(const CMutableTransaction &mutableTx,\n                                        std::function<bool(uint32_t)> expectedResultBasedOnFlags,\n                                        bool add_to_cache,\n                                        bool upgraded_nop) {\n        \/\/DummyConfig config(CBaseChainParams::MAIN);\n        auto& config = GlobalConfig::GetConfig();\n        auto genesisActivationHeight = config.GetGenesisActivationHeight();\n        const CTransaction tx(mutableTx);\n        PrecomputedTransactionData txdata(tx);\n        auto source = task::CCancellationSource::Make();\n        \/\/ If we add many more flags, this loop can get too expensive, but we can\n        \/\/ rewrite in the future to randomly pick a set of flags to evaluate.\n        for (size_t test_flags = 0; test_flags < SCRIPT_FLAG_LAST; test_flags += 1) {\n\n            \/\/ skipping impossible combination\n            if ((test_flags & SCRIPT_UTXO_AFTER_GENESIS) && !(test_flags & SCRIPT_GENESIS)){\n                continue; \n            }\n\n            \/\/ If all mandatory flags are not set no point to test.\n            if((test_flags & MANDATORY_SCRIPT_VERIFY_FLAGS) != MANDATORY_SCRIPT_VERIFY_FLAGS) {\n                continue;\n            }\n\n            if (test_flags & SCRIPT_UTXO_AFTER_GENESIS) {\n                config.SetGenesisActivationHeight(1); \/\/ put genesis activation low to be sure that every utxo is before genesis\n            } else {\n                config.SetGenesisActivationHeight(chainActive.Height() + 2); \/\/ put genesis activation one block above mempool height\n            }\n\n            CValidationState state;\n\n            bool ret =\n                CheckInputs(\n                    source->GetToken(),\n                    config,\n                    true,\n                    tx,\n                    state,\n                    pcoinsTip,\n                    true,\n                    test_flags,\n                    true,\n                    add_to_cache,\n                    txdata,\n                    nullptr).value();\n\n            \/\/ find out if we should pass or fail based on flags.\n            bool expected_return_value = expectedResultBasedOnFlags(test_flags);\n            if (expected_return_value && upgraded_nop) {\n                \/\/ If the script flag being tested corresponds to an upgraded NOP,\n                \/\/ then script execution should fail if DISCOURAGE_UPGRADABLE_NOPS\n                \/\/ is set.\n                expected_return_value =\n                    !(test_flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS);\n            }\n\n            BOOST_CHECK_EQUAL(ret, expected_return_value);\n\n            \/\/ Test the caching\n            if (ret && add_to_cache) {\n                \/\/ Check that we get a cache hit if the tx was valid\n                std::vector<CScriptCheck> scriptchecks;\n                BOOST_CHECK(\n                    CheckInputs(\n                        source->GetToken(),\n                        config,\n                        true,\n                        tx,\n                        state,\n                        pcoinsTip,\n                        true,\n                        test_flags,\n                        true,\n                        add_to_cache,\n                        txdata,\n                        &scriptchecks).value());\n                BOOST_CHECK(scriptchecks.empty());\n            } else {\n                \/\/ Check that we get script executions to check, if the transaction\n                \/\/ was invalid, or we didn't add to cache.\n                std::vector<CScriptCheck> scriptchecks;\n                BOOST_CHECK(\n                    CheckInputs(\n                        source->GetToken(),\n                        config,\n                        true,\n                        tx,\n                        state,\n                        pcoinsTip,\n                        true,\n                        test_flags,\n                        true,\n                        add_to_cache,\n                        txdata,\n                        &scriptchecks).value());\n                BOOST_CHECK_EQUAL(scriptchecks.size(), tx.vin.size());\n            }\n        }\n        config.SetGenesisActivationHeight(genesisActivationHeight);\n    }\n}\n\nBOOST_FIXTURE_TEST_SUITE(txvalidationcache_tests, TestChain100Setup2)\n\nBOOST_AUTO_TEST_CASE(tx_mempool_block_doublespend) {\n    \/\/ Make sure skipping validation of transctions that were validated going\n    \/\/ into the memory pool does not allow double-spends in blocks to pass\n    \/\/ validation when they should not.\n    CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey())\n                                     << OP_CHECKSIG;\n\n    \/\/ Create a double-spend of mature coinbase txn:\n    std::vector<CMutableTransaction> spends;\n    spends.resize(2);\n    for (int i = 0; i < 2; i++) {\n        spends[i].nVersion = 1;\n        spends[i].vin.resize(1);\n        spends[i].vin[0].prevout = COutPoint(coinbaseTxns[0].GetId(), 0);\n        spends[i].vout.resize(1);\n        spends[i].vout[0].nValue = 11 * CENT;\n        spends[i].vout[0].scriptPubKey = scriptPubKey;\n\n        \/\/ Sign:\n        std::vector<uint8_t> vchSig;\n        uint256 hash = SignatureHash(scriptPubKey, CTransaction(spends[i]), 0,\n                                     SigHashType().withForkId(),\n                                     coinbaseTxns[0].vout[0].nValue);\n        BOOST_CHECK(coinbaseKey.Sign(hash, vchSig));\n        vchSig.push_back(uint8_t(SIGHASH_ALL | SIGHASH_FORKID));\n        spends[i].vin[0].scriptSig << vchSig;\n    }\n\n    CBlock block;\n\n    \/\/ Test 1: block with both of those transactions should be rejected.\n    block = CreateAndProcessBlock(spends, scriptPubKey);\n    BOOST_CHECK(chainActive.Tip()->GetBlockHash() != block.GetHash());\n\n    \/\/ Test 2: ... and should be rejected if spend1 is in the memory pool\n    BOOST_CHECK(ToMemPool(spends[0]));\n    block = CreateAndProcessBlock(spends, scriptPubKey);\n    BOOST_CHECK(chainActive.Tip()->GetBlockHash() != block.GetHash());\n    mempool.Clear();\n\n    \/\/ Test 3: ... and should be rejected if spend2 is in the memory pool\n    BOOST_CHECK(ToMemPool(spends[1]));\n    block = CreateAndProcessBlock(spends, scriptPubKey);\n    BOOST_CHECK(chainActive.Tip()->GetBlockHash() != block.GetHash());\n    mempool.Clear();\n\n    \/\/ Final sanity test: first spend in mempool, second in block, that's OK:\n    std::vector<CMutableTransaction> oneSpend;\n    oneSpend.push_back(spends[0]);\n    BOOST_CHECK(ToMemPool(spends[1]));\n    block = CreateAndProcessBlock(oneSpend, scriptPubKey);\n    BOOST_CHECK(chainActive.Tip()->GetBlockHash() == block.GetHash());\n    \/\/ spends[1] should have been removed from the mempool when the block with\n    \/\/ spends[0] is accepted:\n    BOOST_CHECK_EQUAL(mempool.Size(), 0);\n}\n\n\nBOOST_AUTO_TEST_CASE(checkinputs_test) {\n    \/\/ Test that passing CheckInputs with one set of script flags doesn't imply\n    \/\/ that we would pass again with a different set of flags.\n    InitScriptExecutionCache();\n\n    CScript p2pk_scriptPubKey =\n        CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;\n    CScript p2sh_scriptPubKey =\n        GetScriptForDestination(CScriptID(p2pk_scriptPubKey));\n    CScript p2pkh_scriptPubKey =\n        GetScriptForDestination(coinbaseKey.GetPubKey().GetID());\n\n    CBasicKeyStore keystore;\n    keystore.AddKey(coinbaseKey);\n    keystore.AddCScript(p2pk_scriptPubKey);\n\n    \/\/ flags to test: SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY,\n    \/\/ SCRIPT_VERIFY_CHECKSEQUENCE_VERIFY, SCRIPT_VERIFY_NULLDUMMY, uncompressed\n    \/\/ pubkey thing\n\n    \/\/ Create 2 outputs that match the three scripts above, spending the first\n    \/\/ coinbase tx.\n    CMutableTransaction mutableSpend_tx;\n\n    mutableSpend_tx.nVersion = 1;\n    mutableSpend_tx.vin.resize(1);\n    mutableSpend_tx.vin[0].prevout = COutPoint(coinbaseTxns[0].GetId(), 0);\n    mutableSpend_tx.vout.resize(4);\n    mutableSpend_tx.vout[0].nValue = 11 * CENT;\n    mutableSpend_tx.vout[0].scriptPubKey = p2sh_scriptPubKey;\n    mutableSpend_tx.vout[1].nValue = 11 * CENT;\n    mutableSpend_tx.vout[1].scriptPubKey =\n        CScript() << OP_CHECKLOCKTIMEVERIFY << OP_DROP\n                  << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;\n    mutableSpend_tx.vout[2].nValue = 11 * CENT;\n    mutableSpend_tx.vout[2].scriptPubKey =\n        CScript() << OP_CHECKSEQUENCEVERIFY << OP_DROP\n                  << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;\n    mutableSpend_tx.vout[3].nValue = 11 * CENT;\n    mutableSpend_tx.vout[3].scriptPubKey = p2sh_scriptPubKey;\n\n    \/\/ Sign, and push an extra element on the stack.\n    {\n        std::vector<uint8_t> vchSig;\n        uint256 hash = SignatureHash(\n            p2pk_scriptPubKey, CTransaction(mutableSpend_tx), 0,\n            SigHashType().withForkId(), coinbaseTxns[0].vout[0].nValue);\n        BOOST_CHECK(coinbaseKey.Sign(hash, vchSig));\n        vchSig.push_back(uint8_t(SIGHASH_ALL | SIGHASH_FORKID));\n        mutableSpend_tx.vin[0].scriptSig << OP_TRUE << vchSig;\n    }\n\n    const CTransaction spend_tx(mutableSpend_tx);\n\n    LOCK(cs_main);\n    auto& config = GlobalConfig::GetConfig();\n    config.SetGenesisActivationHeight(102);\n\n    \/\/ Test that invalidity under a set of flags doesn't preclude validity under\n    \/\/ other (eg consensus) flags.\n    \/\/ spend_tx is invalid according to DERSIG\n    CValidationState state;\n    auto source = task::CCancellationSource::Make();\n    {\n        PrecomputedTransactionData ptd_spend_tx(spend_tx);\n\n        BOOST_CHECK(\n            !CheckInputs(\n                source->GetToken(),\n                config,\n                true,\n                spend_tx,\n                state,\n                pcoinsTip,\n                true,\n                MANDATORY_SCRIPT_VERIFY_FLAGS |\n                    SCRIPT_VERIFY_CLEANSTACK | SCRIPT_GENESIS,\n                true,\n                true,\n                ptd_spend_tx,\n                nullptr).value());\n\n        \/\/ If we call again asking for scriptchecks (as happens in\n        \/\/ ConnectBlock), we should add a script check object for this -- we're\n        \/\/ not caching invalidity (if that changes, delete this test case).\n        std::vector<CScriptCheck> scriptchecks;\n        BOOST_CHECK(\n            CheckInputs(\n                source->GetToken(),\n                config,\n                true,\n                spend_tx,\n                state,\n                pcoinsTip,\n                true,\n                MANDATORY_SCRIPT_VERIFY_FLAGS |\n                    SCRIPT_VERIFY_CLEANSTACK | SCRIPT_GENESIS,\n                true,\n                true,\n                ptd_spend_tx,\n                &scriptchecks).value());\n        BOOST_CHECK_EQUAL(scriptchecks.size(), 1);\n\n        \/\/ Test that CheckInputs returns true iff cleanstack-enforcing flags are\n        \/\/ not present. Don't add these checks to the cache, so that we can test\n        \/\/ later that block validation works fine in the absence of cached\n        \/\/ successes.\n        ValidateCheckInputsForAllFlags(spend_tx, \n                                       [](uint32_t flags) -> bool { return !(flags & SCRIPT_VERIFY_CLEANSTACK); },\n                                       false, false);\n        \n        \/\/ And if we produce a block with this tx, it should be valid (LOW_S not\n        \/\/ enabled yet), even though there's no cache entry.\n        CBlock block;\n\n        block = CreateAndProcessBlock({spend_tx}, p2pk_scriptPubKey);\n        BOOST_CHECK(chainActive.Tip()->GetBlockHash() == block.GetHash());\n        BOOST_CHECK(pcoinsTip->GetBestBlock() == block.GetHash());\n    }\n\n    \/\/ Test P2SH: construct a transaction that is valid without P2SH, redeem script hash is correct but redeem script is invalid. \n    \/\/ Redeem script is not executed after genesis so it passes.\n    {\n        CMutableTransaction invalid_under_p2sh_tx;\n        invalid_under_p2sh_tx.nVersion = 1;\n        invalid_under_p2sh_tx.vin.resize(1);\n        invalid_under_p2sh_tx.vin[0].prevout = COutPoint(spend_tx.GetId(), 0);\n        invalid_under_p2sh_tx.vout.resize(1);\n        invalid_under_p2sh_tx.vout[0].nValue = 11 * CENT;\n        invalid_under_p2sh_tx.vout[0].scriptPubKey = p2pk_scriptPubKey;\n        std::vector<uint8_t> vchSig2(p2pk_scriptPubKey.begin(),\n                                     p2pk_scriptPubKey.end());\n        invalid_under_p2sh_tx.vin[0].scriptSig << vchSig2;\n\n\n        ValidateCheckInputsForAllFlags(invalid_under_p2sh_tx,\n                                       [](uint32_t flags) -> bool { return (flags & SCRIPT_UTXO_AFTER_GENESIS); },\n                                       true, false);\n    }\n\n    \/\/ Test CHECKLOCKTIMEVERIFY\n    {\n        CMutableTransaction invalid_with_cltv_tx;\n        invalid_with_cltv_tx.nVersion = 1;\n        invalid_with_cltv_tx.nLockTime = 100;\n        invalid_with_cltv_tx.vin.resize(1);\n        invalid_with_cltv_tx.vin[0].prevout = COutPoint(spend_tx.GetId(), 1);\n        invalid_with_cltv_tx.vin[0].nSequence = 0;\n        invalid_with_cltv_tx.vout.resize(1);\n        invalid_with_cltv_tx.vout[0].nValue = 11 * CENT;\n        invalid_with_cltv_tx.vout[0].scriptPubKey = p2pk_scriptPubKey;\n\n        \/\/ Sign\n        std::vector<uint8_t> vchSig;\n        uint256 hash = SignatureHash(\n            spend_tx.vout[1].scriptPubKey, CTransaction(invalid_with_cltv_tx),\n            0, SigHashType().withForkId(), spend_tx.vout[1].nValue);\n        BOOST_CHECK(coinbaseKey.Sign(hash, vchSig));\n        vchSig.push_back(uint8_t(SIGHASH_ALL | SIGHASH_FORKID));\n        invalid_with_cltv_tx.vin[0].scriptSig = CScript() << vchSig << 101;\n\n        \/\/ Since Genesis CLV operator is treated as NOP.\n        ValidateCheckInputsForAllFlags(invalid_with_cltv_tx,\n                                       [](uint32_t flags) -> bool { return !(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)\n                                                                            || (flags & SCRIPT_UTXO_AFTER_GENESIS); },\n                                       true, true);\n        \n        \/\/ Make it valid, and check again\n        invalid_with_cltv_tx.vin[0].scriptSig = CScript() << vchSig << 100;\n        CValidationState state;\n\n        CTransaction transaction(invalid_with_cltv_tx);\n        PrecomputedTransactionData txdata(transaction);\n\n        BOOST_CHECK(\n            CheckInputs(\n                source->GetToken(),\n                config,\n                true,\n                transaction,\n                state,\n                pcoinsTip,\n                true,\n                MANDATORY_SCRIPT_VERIFY_FLAGS |\n                    SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY | SCRIPT_GENESIS,\n                true,\n                true,\n                txdata,\n                nullptr).value());\n    }\n\n    \/\/ TEST CHECKSEQUENCEVERIFY\n    {\n        CMutableTransaction invalid_with_csv_tx;\n        invalid_with_csv_tx.nVersion = 2;\n        invalid_with_csv_tx.vin.resize(1);\n        invalid_with_csv_tx.vin[0].prevout = COutPoint(spend_tx.GetId(), 2);\n        invalid_with_csv_tx.vin[0].nSequence = 100;\n        invalid_with_csv_tx.vout.resize(1);\n        invalid_with_csv_tx.vout[0].nValue = 11 * CENT;\n        invalid_with_csv_tx.vout[0].scriptPubKey = p2pk_scriptPubKey;\n\n        \/\/ Sign\n        std::vector<uint8_t> vchSig;\n        uint256 hash = SignatureHash(\n            spend_tx.vout[2].scriptPubKey, CTransaction(invalid_with_csv_tx), 0,\n            SigHashType().withForkId(), spend_tx.vout[2].nValue);\n        BOOST_CHECK(coinbaseKey.Sign(hash, vchSig));\n        vchSig.push_back(uint8_t(SIGHASH_ALL | SIGHASH_FORKID));\n        invalid_with_csv_tx.vin[0].scriptSig = CScript() << vchSig << 101;\n\n        \/\/ Since Genesis CSV operator is treated as NOP.\n        ValidateCheckInputsForAllFlags(invalid_with_csv_tx,\n                                       [](uint32_t flags) -> bool { return !(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)\n                                                                            || (flags & SCRIPT_UTXO_AFTER_GENESIS); },\n                                       true, true);\n        \/\/ Make it valid, and check again\n        invalid_with_csv_tx.vin[0].scriptSig = CScript() << vchSig << 100;\n        CValidationState state;\n\n        CTransaction transaction(invalid_with_csv_tx);\n        PrecomputedTransactionData txdata(transaction);\n\n        BOOST_CHECK(\n            CheckInputs(\n                source->GetToken(),\n                config,\n                true,\n                transaction,\n                state,\n                pcoinsTip,\n                true,\n                MANDATORY_SCRIPT_VERIFY_FLAGS |\n                    SCRIPT_VERIFY_CHECKSEQUENCEVERIFY | SCRIPT_GENESIS,\n                true,\n                true,\n                txdata,\n                nullptr).value());\n    }\n\n    \/\/ TODO: add tests for remaining script flags\n\n    {\n        \/\/ Test a transaction with multiple inputs.\n        CMutableTransaction tx;\n\n        tx.nVersion = 1;\n        tx.vin.resize(2);\n        tx.vin[0].prevout = COutPoint(spend_tx.GetId(), 0);\n        tx.vin[1].prevout = COutPoint(spend_tx.GetId(), 3);\n        tx.vout.resize(1);\n        tx.vout[0].nValue = 22 * CENT;\n        tx.vout[0].scriptPubKey = p2pk_scriptPubKey;\n\n        \/\/ Sign\n        SignatureData sigdata;\n        ProduceSignature(config, true,\n            MutableTransactionSignatureCreator(&keystore, &tx, 0, 11 * CENT,\n                                               SigHashType().withForkId()),\n            true, false, spend_tx.vout[0].scriptPubKey, sigdata);\n\n        UpdateTransaction(tx, 0, sigdata);\n        ProduceSignature(config, true,\n            MutableTransactionSignatureCreator(&keystore, &tx, 1, 11 * CENT,\n                                               SigHashType().withForkId()),\n            true, false, spend_tx.vout[3].scriptPubKey, sigdata);\n        UpdateTransaction(tx, 1, sigdata);\n\n        auto shouldPass = [](uint32_t flags) -> bool {\n            bool isUtxoAfterGenesis = flags & SCRIPT_UTXO_AFTER_GENESIS;\n            bool isCleanStackEnforced = flags & SCRIPT_VERIFY_CLEANSTACK;\n            return !(isUtxoAfterGenesis && isCleanStackEnforced); \n        };\n\n        \/\/ This spends p2sh so after genesis it should fail if cleans stack rule is enforced\n        ValidateCheckInputsForAllFlags(tx, shouldPass,  true, false);\n\n        \/\/ Check that if the second input is invalid, but the first input is\n        \/\/ valid, the transaction is not cached.\n        \/\/ Invalidate vin[1]\n        tx.vin[1].scriptSig = CScript();\n\n        CValidationState state;\n        CTransaction transaction(tx);\n        PrecomputedTransactionData txdata(transaction);\n\n        \/\/ This transaction is now invalid because the second signature is\n        \/\/ missing.\n        BOOST_CHECK(\n            !CheckInputs(\n                source->GetToken(),\n                config,\n                true,\n                transaction,\n                state,\n                pcoinsTip,\n                true,\n                MANDATORY_SCRIPT_VERIFY_FLAGS | SCRIPT_GENESIS,\n                true,\n                true,\n                txdata,\n                nullptr).value());\n\n        \/\/ Make sure this transaction was not cached (ie becausethe first input\n        \/\/ was valid)\n        std::vector<CScriptCheck> scriptchecks;\n        BOOST_CHECK(\n            CheckInputs(\n                source->GetToken(),\n                config,\n                true,\n                transaction,\n                state,\n                pcoinsTip,\n                true,\n                MANDATORY_SCRIPT_VERIFY_FLAGS | SCRIPT_GENESIS,\n                true,\n                true,\n                txdata,\n                &scriptchecks).value());\n        \/\/ Should get 2 script checks back -- caching is on a whole-transaction\n        \/\/ basis.\n        BOOST_CHECK_EQUAL(scriptchecks.size(), 2);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":40.351590106,"max_line_length":133,"alphanum_fraction":0.5790971584,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3633,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"file.hpp\"\n\nnamespace calc_greenwich {\n\n\/\/ \u5b9a\u6570\nstatic constexpr char kFLeapSec[13] = \"LEAP_SEC.txt\";\nstatic constexpr char kFDut1[9]     = \"DUT1.txt\";\nstatic constexpr char kFNutLs[11]   = \"NUT_LS.txt\";\nstatic constexpr char kFNutPl[11]   = \"NUT_PL.txt\";\n\n\/*\n * @brief       UTC - TAI (\u5354\u5b9a\u4e16\u754c\u6642\u3068\u56fd\u969b\u539f\u5b50\u6642\u306e\u5dee = \u3046\u308b\u3046\u79d2\u306e\u7dcf\u548c) \u4e00\u89a7\u53d6\u5f97\n *\n * @param[ref]  UTC - TAI \u4e00\u89a7(vector<vector<string>>)\n * @return      true|false\n *\/\nbool File::get_leap_sec_list(std::vector<std::vector<std::string>>& data) {\n  std::string f(kFLeapSec);  \/\/ \u30d5\u30a1\u30a4\u30eb\u540d\n  std::string buf;           \/\/ 1\u884c\u5206\u30d0\u30c3\u30d5\u30a1\n\n  try {\n    \/\/ \u30d5\u30a1\u30a4\u30eb OPEN\n    std::ifstream ifs(f);\n    if (!ifs) return 0;  \/\/ \u8aad\u307f\u8fbc\u307f\u5931\u6557\n\n    \/\/ \u30d5\u30a1\u30a4\u30eb READ\n    while (getline(ifs, buf)) {\n      std::vector<std::string> rec;  \/\/ 1\u884c\u5206\u30d9\u30af\u30bf\n      std::istringstream iss(buf);   \/\/ \u6587\u5b57\u5217\u30b9\u30c8\u30ea\u30fc\u30e0\n      \/\/ 1\u884c\u5206\u6587\u5b57\u5217\u30921\u884c\u5206\u30d9\u30af\u30bf\u306b\u8ffd\u52a0\n      std::string s;\n      while (iss >> s) rec.push_back(s);\n      \/\/ 1\u884c\u5206\u30d9\u30af\u30bf\u3092 data \u30d9\u30af\u30bf\u306b\u8ffd\u52a0\n      if (rec.size() != 0) data.push_back(rec);\n    }\n  } catch (...) {\n    return false;\n  }\n\n  return true;\n}\n\n\/*\n * @brief       DUT1 (UT1(\u4e16\u754c\u66421) \u3068 UTC(\u5354\u5b9a\u4e16\u754c\u6642)\u306e\u5dee) \u4e00\u89a7\u53d6\u5f97\n *\n * @param[ref]  DUT1 \u4e00\u89a7(vector<vector<string>>)\n * @return      true|false\n *\/\nbool File::get_dut1_list(std::vector<std::vector<std::string>>& data) {\n  std::string f(kFDut1);  \/\/ \u30d5\u30a1\u30a4\u30eb\u540d\n  std::string buf;        \/\/ 1\u884c\u5206\u30d0\u30c3\u30d5\u30a1\n\n  try {\n    \/\/ \u30d5\u30a1\u30a4\u30eb OPEN\n    std::ifstream ifs(f);\n    if (!ifs) return 0;  \/\/ \u8aad\u307f\u8fbc\u307f\u5931\u6557\n\n    \/\/ \u30d5\u30a1\u30a4\u30eb READ\n    while (getline(ifs, buf)) {\n      std::vector<std::string> rec;  \/\/ 1\u884c\u5206\u30d9\u30af\u30bf\n      std::istringstream iss(buf);   \/\/ \u6587\u5b57\u5217\u30b9\u30c8\u30ea\u30fc\u30e0\n      \/\/ 1\u884c\u5206\u6587\u5b57\u5217\u30921\u884c\u5206\u30d9\u30af\u30bf\u306b\u8ffd\u52a0\n      std::string s;\n      while (iss >> s) rec.push_back(s);\n      \/\/ 1\u884c\u5206\u30d9\u30af\u30bf\u3092 data \u30d9\u30af\u30bf\u306b\u8ffd\u52a0\n      if (rec.size() != 0) data.push_back(rec);\n    }\n  } catch (...) {\n    return false;\n  }\n\n  return true;\n}\n\n\/*\n * @brief       \u53d6\u5f97: lunisolar parameters\n *              \uff08\u7b2c6\u5217\u4ee5\u5f8c\u306f 10,000 \u500d\u306b\u3059\u308b\uff09\n *\n * @param[ref]  lunisolar \u30d1\u30e9\u30e1\u30fc\u30bf\u4e00\u89a7(vector<vector<double>>)\n * @return      true|false\n *\/\nbool File::get_param_ls(std::vector<std::vector<double>>& data) {\n  std::string f(kFNutLs);  \/\/ \u30d5\u30a1\u30a4\u30eb\u540d\n  std::string buf;         \/\/ 1\u884c\u5206\u30d0\u30c3\u30d5\u30a1\n  unsigned int c;          \/\/ \u30eb\u30fc\u30d7\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\uff08\u5217\u51e6\u7406\u7528\n\n  try {\n    \/\/ \u30d5\u30a1\u30a4\u30eb OPEN\n    std::ifstream ifs(f);\n    if (!ifs) return 0;  \/\/ \u8aad\u307f\u8fbc\u307f\u5931\u6557\n\n    \/\/ \u30d5\u30a1\u30a4\u30eb READ\n    while (getline(ifs, buf)) {\n      std::vector<double> rec;      \/\/ 1\u884c\u5206\u30d9\u30af\u30bf\n      std::istringstream iss(buf);  \/\/ \u6587\u5b57\u5217\u30b9\u30c8\u30ea\u30fc\u30e0\n      \/\/ 1\u884c\u5206\u6587\u5b57\u5217\u30921\u884c\u5206\u30d9\u30af\u30bf\u306b\u8ffd\u52a0\n      double s;\n      c = 0;\n      while (iss >> s) {\n        if (c > 4) s *= 10000;\n        rec.push_back(s);\n        ++c;\n      }\n      \/\/ 1\u884c\u5206\u30d9\u30af\u30bf\u3092 data \u30d9\u30af\u30bf\u306b\u8ffd\u52a0\n      if (rec.size() != 0) data.push_back(rec);\n    }\n    return data.size();\n  } catch (...) {\n    return false;\n  }\n\n  return true;\n}\n\n\/*\n * @brief       \u53d6\u5f97: planetary parameters\n *              \uff08\u7b2c15\u5217\u4ee5\u5f8c\u306f 10,000 \u500d\u306b\u3059\u308b\uff09\n *\n * @param[ref]  planetary \u30d1\u30e9\u30e1\u30fc\u30bf\u4e00\u89a7(vector<vector<double>>)\n * @return      true|false\n *\/\nbool File::get_param_pl(std::vector<std::vector<double>>& data) {\n  std::string f(kFNutPl);  \/\/ \u30d5\u30a1\u30a4\u30eb\u540d\n  std::string buf;         \/\/ 1\u884c\u5206\u30d0\u30c3\u30d5\u30a1\n  unsigned int c;          \/\/ \u30eb\u30fc\u30d7\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\uff08\u5217\u51e6\u7406\u7528\n\n  try {\n    \/\/ \u30d5\u30a1\u30a4\u30eb OPEN\n    std::ifstream ifs(f);\n    if (!ifs) return 0;  \/\/ \u8aad\u307f\u8fbc\u307f\u5931\u6557\n\n    \/\/ \u30d5\u30a1\u30a4\u30eb READ\n    while (getline(ifs, buf)) {\n      std::vector<double> rec;      \/\/ 1\u884c\u5206\u30d9\u30af\u30bf\n      std::istringstream iss(buf);  \/\/ \u6587\u5b57\u5217\u30b9\u30c8\u30ea\u30fc\u30e0\n      \/\/ 1\u884c\u5206\u6587\u5b57\u5217\u30921\u884c\u5206\u30d9\u30af\u30bf\u306b\u8ffd\u52a0\n      double s;\n      c = 0;\n      while (iss >> s) {\n        if (c > 13) s *= 10000;\n        rec.push_back(s);\n        ++c;\n      }\n      \/\/ 1\u884c\u5206\u30d9\u30af\u30bf\u3092 data \u30d9\u30af\u30bf\u306b\u8ffd\u52a0\n      if (rec.size() != 0) data.push_back(rec);\n    }\n    return data.size();\n  } catch (...) {\n    return false;\n  }\n\n  return true;\n}\n\n}  \/\/ namespace calc_greenwich\n\n","avg_line_length":23.1401273885,"max_line_length":75,"alphanum_fraction":0.5524360033,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13022,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/\/ Copyright 2017 Proyectos y Sistemas de Mantenimiento SL (eProsima).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <gtest\/gtest.h>\n#include <microcdr\/microcdr.h>\n\n#define BUFFER_LENGTH_KO 0\n#define ARRAY_LENGTH 4\n#define PI 3.1415926535897932384626433832795028\n\nstatic Endianness endianness = BIG_ENDIANNESS;\n\nTEST(buffer_error, BoolKO)\n{\n    bool input = true;\n    bool output;\n    uint8_t *buffer = NULL;\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, BUFFER_LENGTH_KO);\n    init_micro_buffer(&reader, buffer, BUFFER_LENGTH_KO);\n\n    EXPECT_FALSE(serialize_bool(&writer, input));\n    EXPECT_FALSE(deserialize_bool(&reader, &output));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, CharKO)\n{\n    char input = 'A';\n    char output;\n    uint8_t *buffer = NULL;\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, BUFFER_LENGTH_KO);\n    init_micro_buffer(&reader, buffer, BUFFER_LENGTH_KO);\n\n    EXPECT_FALSE(serialize_char(&writer, input));\n    EXPECT_FALSE(deserialize_char(&reader, &output));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, Uint8KO)\n{\n    uint8_t input = 0x09;\n    uint8_t output;\n    uint8_t *buffer = NULL;\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, BUFFER_LENGTH_KO);\n    init_micro_buffer(&reader, buffer, BUFFER_LENGTH_KO);\n\n    EXPECT_FALSE(serialize_uint8_t(&writer, input));\n    EXPECT_FALSE(deserialize_uint8_t(&reader, &output));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, Int16KO)\n{\n    int16_t input = 0x0A0B;\n    int16_t output;\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_int16_t(&writer, endianness, input));\n    EXPECT_FALSE(deserialize_endian_int16_t(&reader, endianness, &output));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, Uint16KO)\n{\n    uint16_t input = 0x0A0B;\n    uint16_t output;\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_uint16_t(&writer, endianness, input));\n    EXPECT_FALSE(deserialize_endian_uint16_t(&reader, endianness, &output));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, Int32KO)\n{\n    int32_t input = 0x0C0D0E0F;\n    int32_t output;\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_int32_t(&writer, endianness, input));\n    EXPECT_FALSE(deserialize_endian_int32_t(&reader, endianness, &output));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, Uint32KO)\n{\n    uint32_t input = 0x0C0D0E0F;\n    uint32_t output;\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_uint32_t(&writer, endianness, input));\n    EXPECT_FALSE(deserialize_endian_uint32_t(&reader, endianness, &output));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, Int64KO)\n{\n    int64_t input = 0x0102030405060708;\n    int64_t output;\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_int64_t(&writer, endianness, input));\n    EXPECT_FALSE(deserialize_endian_int64_t(&reader, endianness, &output));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, Uint64KO)\n{\n    uint64_t input = 0x0102030405060708;\n    uint64_t output;\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_uint64_t(&writer, endianness, input));\n    EXPECT_FALSE(deserialize_endian_uint64_t(&reader, endianness, &output));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, FloatKO)\n{\n    float input = static_cast<float>(PI);\n    float output;\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_float(&writer, endianness, input));\n    EXPECT_FALSE(deserialize_endian_float(&reader, endianness, &output));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, DoubleKO)\n{\n    double input = PI;\n    double output;\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_double(&writer, endianness, input));\n    EXPECT_FALSE(deserialize_endian_double(&reader, endianness, &output));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, ArrayBoolKO)\n{\n    bool input[ARRAY_LENGTH] = {true};\n    bool output[ARRAY_LENGTH];\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_array_bool(&writer, input, ARRAY_LENGTH));\n    EXPECT_FALSE(deserialize_array_bool(&reader, output, ARRAY_LENGTH));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, ArrayCharKO)\n{\n    char input[ARRAY_LENGTH] = {'A'};\n    char output[ARRAY_LENGTH];\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_array_char(&writer, input, ARRAY_LENGTH));\n    EXPECT_FALSE(deserialize_array_char(&reader, output, ARRAY_LENGTH));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, ArrayUint8KO)\n{\n    uint8_t input[ARRAY_LENGTH] = {0x09};\n    uint8_t output[ARRAY_LENGTH];\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_array_uint8_t(&writer, input, ARRAY_LENGTH));\n    EXPECT_FALSE(deserialize_array_uint8_t(&reader, output, ARRAY_LENGTH));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, ArrayInt16KO)\n{\n    int16_t input[ARRAY_LENGTH] = {0x0A0B};\n    int16_t output[ARRAY_LENGTH];\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_array_int16_t(&writer, endianness, input, ARRAY_LENGTH));\n    EXPECT_FALSE(deserialize_endian_array_int16_t(&reader, endianness, output, ARRAY_LENGTH));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, ArrayUint16KO)\n{\n    uint16_t input[ARRAY_LENGTH] = {0x0A0B};\n    uint16_t output[ARRAY_LENGTH];\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_array_uint16_t(&writer, endianness, input, ARRAY_LENGTH));\n    EXPECT_FALSE(deserialize_endian_array_uint16_t(&reader, endianness, output, ARRAY_LENGTH));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, ArrayInt32KO)\n{\n    int32_t input[ARRAY_LENGTH] = {0x0C0D0E0F};\n    int32_t output[ARRAY_LENGTH];\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_array_int32_t(&writer, endianness, input, ARRAY_LENGTH));\n    EXPECT_FALSE(deserialize_endian_array_int32_t(&reader, endianness, output, ARRAY_LENGTH));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, ArrayUint32KO)\n{\n    uint32_t input[ARRAY_LENGTH] = {0x0C0D0E0F};\n    uint32_t output[ARRAY_LENGTH];\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_array_uint32_t(&writer, endianness, input, ARRAY_LENGTH));\n    EXPECT_FALSE(deserialize_endian_array_uint32_t(&reader, endianness, output, ARRAY_LENGTH));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, ArrayInt64KO)\n{\n    int64_t input[ARRAY_LENGTH] = {0x0102030405060708};\n    int64_t output[ARRAY_LENGTH];\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_array_int64_t(&writer, endianness, input, ARRAY_LENGTH));\n    EXPECT_FALSE(deserialize_endian_array_int64_t(&reader, endianness, output, ARRAY_LENGTH));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, ArrayUint64KO)\n{\n    uint64_t input[ARRAY_LENGTH] = {0x0102030405060708};\n    uint64_t output[ARRAY_LENGTH];\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_array_uint64_t(&writer, endianness, input, ARRAY_LENGTH));\n    EXPECT_FALSE(deserialize_endian_array_uint64_t(&reader, endianness, output, ARRAY_LENGTH));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, ArrayFloatKO)\n{\n    float input[ARRAY_LENGTH] = {static_cast<float>(PI)};\n    float output[ARRAY_LENGTH];\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_array_float(&writer, endianness, input, ARRAY_LENGTH));\n    EXPECT_FALSE(deserialize_endian_array_float(&reader, endianness, output, ARRAY_LENGTH));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\nTEST(buffer_error, ArrayDoubleKO)\n{\n    double input[ARRAY_LENGTH] = {PI};\n    double output[ARRAY_LENGTH];\n    uint8_t buffer[sizeof(output) \/ 2] = {0};\n\n    MicroBuffer writer;\n    MicroBuffer reader;\n\n    init_micro_buffer(&writer, buffer, sizeof(output) \/ 2);\n    init_micro_buffer(&reader, buffer, sizeof(output) \/ 2);\n\n    EXPECT_FALSE(serialize_endian_array_double(&writer, endianness, input, ARRAY_LENGTH));\n    EXPECT_FALSE(deserialize_endian_array_double(&reader, endianness, output, ARRAY_LENGTH));\n\n    EXPECT_EQ(writer.error, BUFFER_NOK);\n    EXPECT_EQ(reader.error, BUFFER_NOK);\n}\n\n","avg_line_length":29.4615384615,"max_line_length":95,"alphanum_fraction":0.7240055291,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6837,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":7.0,"content":"#define DEBUG 1\n\/**\n * File    : F.cpp\n * Author  : Kazune Takahashi\n * Created : 6\/22\/2020, 1:47:53 AM\n * Powered by Visual Studio Code\n *\/\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\/\/ ----- boost -----\n#include <boost\/integer\/common_factor_rt.hpp>\n#include <boost\/multiprecision\/cpp_int.hpp>\n#include <boost\/rational.hpp>\n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::integer::gcd; \/\/ for C++14 or for cpp_int\nusing boost::integer::lcm; \/\/ for C++14 or for cpp_int\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n\/\/ constexpr ll MOD{998'244'353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n\/\/ constexpr ll MAX_SIZE{30'000'010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nbool ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\ntemplate <typename T>\nbool ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(Mint const &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(Mint const &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(Mint const &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator\/=(Mint const &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n  Mint operator\/(Mint const &a) const { return Mint(*this) \/= a; }\n  bool operator<(Mint const &a) const { return x < a.x; }\n  bool operator<=(Mint const &a) const { return x <= a.x; }\n  bool operator>(Mint const &a) const { return x > a.x; }\n  bool operator>=(Mint const &a) const { return x >= a.x; }\n  bool operator==(Mint const &a) const { return x == a.x; }\n  bool operator!=(Mint const &a) const { return !(*this == a); }\n  Mint power(ll N) const\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N \/ 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} \/ rhs; }\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i{2LL}; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i{1LL}; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\n\/\/ ----- for C++17 -----\ntemplate <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>\nsize_t popcount(T x) { return bitset<64>(x).count(); }\nsize_t popcount(string const &S) { return bitset<200010>{S}.count(); }\n\/\/ ----- Infty -----\ntemplate <typename T>\nconstexpr T Infty() { return numeric_limits<T>::max(); }\ntemplate <typename T>\nconstexpr T mInfty() { return numeric_limits<T>::min(); }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1'000'000'000'000'010LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\n\/\/ ----- Solve -----\n\nconstexpr ll M{1'000'010};\n\nclass Solve\n{\n  ll N;\n\npublic:\n  Solve(ll N) : N{N}\n  {\n  }\n\n  void flush()\n  {\n    ll ans{0};\n    for (auto K{2LL}; K <= min(N, M); ++K)\n    {\n      if (g(N, K) == 1)\n      {\n        ++ans;\n      }\n    }\n    ll X{N - 1};\n    for (auto i{1LL}; i <= M; ++i)\n    {\n      if (X % i == 0)\n      {\n        auto K{X \/ i};\n#if DEBUG == 1\n        cerr << \"K = \" << K << endl;\n#endif\n        if (M < K && K <= N)\n        {\n          ++ans;\n        }\n      }\n    }\n    if (N > M)\n    {\n      ++ans;\n    }\n    cout << ans << endl;\n  }\n\nprivate:\n  ll g(ll N, ll K)\n  {\n    while (N % K == 0)\n    {\n      N \/= K;\n    }\n    return N % K;\n  }\n\n  ll g_info(ll N, ll K)\n  {\n#if DEBUG == 1\n    cerr << \"K = \" << K << \" : \" << N << \" \";\n#endif\n    while (N >= K)\n    {\n      N = f_info(N, K);\n#if DEBUG == 1\n      cerr << N << \" \";\n#endif\n    }\n#if DEBUG == 1\n    cerr << endl;\n#endif\n    return N;\n  }\n\n  ll f_info(ll N, ll K)\n  {\n    if (N % K == 0)\n    {\n#if DEBUG == 1\n      cerr << \"(div) \";\n#endif\n      return N \/ K;\n    }\n    else\n    {\n#if DEBUG == 1\n      cerr << \"(sub) \";\n#endif\n      return N - K;\n    }\n  }\n};\n\n\/\/ ----- main() -----\n\nint main()\n{\n  ll N;\n  cin >> N;\n  Solve solve(N);\n  solve.flush();\n}\n","avg_line_length":21.365625,"max_line_length":82,"alphanum_fraction":0.5461459705,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3094,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":null,"content":"\/*\n * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>\n *\n * SPDX-License-Identifier: BSD-2-Clause\n *\/\n\n#include \"PenTool.h\"\n#include \"ImageEditor.h\"\n#include \"Layer.h\"\n#include <LibGUI\/Action.h>\n#include <LibGUI\/BoxLayout.h>\n#include <LibGUI\/Label.h>\n#include <LibGUI\/Menu.h>\n#include <LibGUI\/Painter.h>\n#include <LibGUI\/ValueSlider.h>\n\nnamespace PixelPaint {\n\nPenTool::PenTool()\n{\n}\n\nPenTool::~PenTool()\n{\n}\n\nvoid PenTool::on_mousedown(Layer& layer, GUI::MouseEvent& event, GUI::MouseEvent&)\n{\n    if (event.button() != GUI::MouseButton::Left && event.button() != GUI::MouseButton::Right)\n        return;\n\n    GUI::Painter painter(layer.bitmap());\n    painter.draw_line(event.position(), event.position(), m_editor->color_for(event), m_thickness);\n    layer.did_modify_bitmap(Gfx::IntRect::centered_on(event.position(), Gfx::IntSize { m_thickness, m_thickness }));\n    m_last_drawing_event_position = event.position();\n}\n\nvoid PenTool::on_mouseup(Layer&, GUI::MouseEvent& event, GUI::MouseEvent&)\n{\n    if (event.button() == GUI::MouseButton::Left || event.button() == GUI::MouseButton::Right) {\n        m_last_drawing_event_position = { -1, -1 };\n        m_editor->did_complete_action();\n    }\n}\n\nvoid PenTool::on_mousemove(Layer& layer, GUI::MouseEvent& event, GUI::MouseEvent&)\n{\n    if (!(event.buttons() & GUI::MouseButton::Left || event.buttons() & GUI::MouseButton::Right))\n        return;\n    GUI::Painter painter(layer.bitmap());\n\n    Gfx::IntRect changed_rect;\n    if (m_last_drawing_event_position != Gfx::IntPoint(-1, -1)) {\n        painter.draw_line(m_last_drawing_event_position, event.position(), m_editor->color_for(event), m_thickness);\n        changed_rect = Gfx::IntRect::from_two_points(m_last_drawing_event_position, event.position());\n    } else {\n        painter.draw_line(event.position(), event.position(), m_editor->color_for(event), m_thickness);\n        changed_rect = Gfx::IntRect::from_two_points(event.position(), event.position());\n    }\n    changed_rect.inflate(m_thickness, m_thickness);\n    layer.did_modify_bitmap(changed_rect);\n\n    m_last_drawing_event_position = event.position();\n}\n\nGUI::Widget* PenTool::get_properties_widget()\n{\n    if (!m_properties_widget) {\n        m_properties_widget = GUI::Widget::construct();\n        m_properties_widget->set_layout<GUI::VerticalBoxLayout>();\n\n        auto& thickness_container = m_properties_widget->add<GUI::Widget>();\n        thickness_container.set_fixed_height(20);\n        thickness_container.set_layout<GUI::HorizontalBoxLayout>();\n\n        auto& thickness_label = thickness_container.add<GUI::Label>(\"Thickness:\");\n        thickness_label.set_text_alignment(Gfx::TextAlignment::CenterLeft);\n        thickness_label.set_fixed_size(80, 20);\n\n        auto& thickness_slider = thickness_container.add<GUI::ValueSlider>(Orientation::Horizontal, \"px\");\n        thickness_slider.set_range(1, 20);\n        thickness_slider.set_value(m_thickness);\n\n        thickness_slider.on_change = [&](int value) {\n            m_thickness = value;\n        };\n    }\n\n    return m_properties_widget.ptr();\n}\n\n}\n","avg_line_length":33.2688172043,"max_line_length":116,"alphanum_fraction":0.6952165482,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8250,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["FTL"],"max_stars_count":null,"content":"\/\/#include \"rojue_ImageSavingDialog.h\"\n\/\/using namespace rojue;\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ construction\/destruction:\n\nImageSavingDialog::ImageSavingDialog(rsPlot *owner, int defaultWidth, int defaultHeight, \n                                     const String &defaultFormat, const File &defaultTargetFile)\n{\n  setSize(384, 52);\n  ownerSystem = owner;\n\n  int x, y, w, h;\n  x = 0;\n  y = 0;\n  w = getWidth();\n  h = getHeight();\n\n  targetFileLabel = new Label(String((\"Target File\")), String((\"File:\")) );\n  targetFileLabel->setBounds(4, 4, 32, 20);\n  addAndMakeVisible(targetFileLabel);\n\n  browseButton = new TextButton(String((\"Browse\")));\n  browseButton->setBounds(w-48-4, 4, 48, 20);\n  browseButton->addListener(this);\n  addAndMakeVisible(browseButton);\n\n  x = targetFileLabel->getRight();\n  w = browseButton->getX() - targetFileLabel->getRight();\n  \/\/targetFileEditLabel = new Label(String((\"Target File\")), String() );\n  targetFileEditLabel = new Label(String((\"Target File\")), defaultTargetFile.getFullPathName() );\n  targetFileEditLabel->setColour(Label::backgroundColourId, Colours::white);\n  targetFileEditLabel->setColour(Label::outlineColourId, Colours::black);\n  targetFileEditLabel->setEditable(true);\n  targetFileEditLabel->setBounds(x+4, 4, w-8, 20);\n  addAndMakeVisible(targetFileEditLabel);\n\n  x = 0;\n  y = targetFileEditLabel->getBottom();\n  pixelWidthLabel = new Label(String((\"Pixel width\")), String((\"Width:\")) );\n  pixelWidthLabel->setBounds(x+4, y+4, 48, 20);\n  addAndMakeVisible(pixelWidthLabel);\n\n  x = pixelWidthLabel->getRight();\n  \/\/pixelWidthEditLabel = new Label(String((\"Pixel width\")), String(owner->getWidth()) );\n  pixelWidthEditLabel = new Label(String((\"Pixel width\")), String(defaultWidth) );\n  pixelWidthEditLabel->setBounds(x+4, y+4, 48, 20);\n  pixelWidthEditLabel->setColour(Label::backgroundColourId, Colours::white);\n  pixelWidthEditLabel->setColour(Label::outlineColourId, Colours::black);\n  pixelWidthEditLabel->setEditable(true);\n  pixelWidthEditLabel->addListener(this);\n  addAndMakeVisible(pixelWidthEditLabel);\n\n  x = pixelWidthEditLabel->getRight();\n  pixelHeightLabel = new Label(String((\"Pixel height\")), String((\"Height:\")) );\n  pixelHeightLabel->setBounds(x+4, y+4, 52, 20);\n  addAndMakeVisible(pixelHeightLabel);\n\n  x = pixelHeightLabel->getRight();\n  \/\/pixelHeightEditLabel = new Label(String((\"Pixel height\")), String(owner->getHeight()) );\n  pixelHeightEditLabel = new Label(String((\"Pixel height\")), String(defaultHeight) );\n  pixelHeightEditLabel->setBounds(x+4, y+4, 48, 20);\n  pixelHeightEditLabel->setColour(Label::backgroundColourId, Colours::white);\n  pixelHeightEditLabel->setColour(Label::outlineColourId, Colours::black);\n  pixelHeightEditLabel->setEditable(true);\n  pixelHeightEditLabel->addListener(this);\n  addAndMakeVisible(pixelHeightEditLabel);\n\n  x = pixelHeightEditLabel->getRight();\n  formatLabel = new Label(String((\"Format\")), String((\"Format:\")) );\n  formatLabel->setBounds(x+4, y+4, 52, 20);\n  addAndMakeVisible(formatLabel);\n\n  x = formatLabel->getRight();\n  w = browseButton->getX() - x;\n  formatComboBox = new ComboBox(String((\"formatComboBox\")));\n  formatComboBox->setBounds(x+4, y+4, w-8, 20);\n  formatComboBox->addItem(String((\"svg\")),        1);\n  formatComboBox->addItem(String((\"png\")),        2);\n  \/\/formatComboBox->setSelectedId(2, true);\n  if( defaultFormat == String((\"svg\")) )\n    formatComboBox->setSelectedId(1);\n  else if( defaultFormat == String((\"png\")) )\n    formatComboBox->setSelectedId(2);\n  else\n    formatComboBox->setSelectedId(2);\n  addAndMakeVisible(formatComboBox);\n\n  saveButton = new TextButton(String((\"Save\")));\n  saveButton->setBounds(browseButton->getX(), browseButton->getY()+24, 48, 20);\n  saveButton->addListener(this);\n  addAndMakeVisible(saveButton);\n\n  \/\/ initialize the target file field:\n  File   thisExeAsFile         = File::getSpecialLocation(File::currentExecutableFile);\n  File   thisDirectoryAsFile   = thisExeAsFile.getParentDirectory();\n  String thisDirectoryAsString = thisDirectoryAsFile.getFullPathName();\n  File   targetFile            = File(thisDirectoryAsString + String((\"\/ExportedImage\")) );\n  if( defaultTargetFile != File() )\n    targetFile = defaultTargetFile;\n  targetFileEditLabel->setText(targetFile.getFullPathName(), juce::NotificationType::dontSendNotification);\n}\n\nImageSavingDialog::~ImageSavingDialog()\n{\n  deleteAllChildren();\n}\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ inquiry:\n\nint ImageSavingDialog::getSelectedPixelWidth()\n{\n  int w = pixelWidthEditLabel->getText().getIntValue();\n  if( w > 1 )\n    return w;\n  else\n    return 1;\n}\n\nint ImageSavingDialog::getSelectedPixelHeight()\n{\n  int h = pixelHeightEditLabel->getText().getIntValue();\n  if( h > 1 )\n    return h;\n  else\n    return 1;\n}\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ callbacks:\n\nvoid ImageSavingDialog::buttonClicked(juce::Button *buttonThatWasClicked)\n{\n  if( buttonThatWasClicked == browseButton )\n  {\n    FileChooser chooser(String((\"Select target file\")), \n      File(targetFileEditLabel->getText()), String(), false);\n    if(chooser.browseForFileToSave(false))\n    {\n      File newTargetFile = chooser.getResult();\n      targetFileEditLabel->setText(newTargetFile.getFullPathName(), \n        NotificationType::dontSendNotification);\n      saveNow();\n    }\n  }\n  else if( buttonThatWasClicked == saveButton )\n  {\n    saveNow();\n  }\n}\n\nvoid ImageSavingDialog::comboBoxChanged(juce::ComboBox *comboBoxThatHasChanged)\n{\n\n}\n\nvoid ImageSavingDialog::labelTextChanged(juce::Label *labelThatHasChanged)\n{\n\n}\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ saving:\n\nvoid ImageSavingDialog::saveNow()\n{\n  int w = getSelectedPixelWidth();\n  int h = getSelectedPixelHeight();\n  File fileToSaveTo = File(targetFileEditLabel->getText());\n\n  if( formatComboBox->getText() == String((\"png\")) )\n  {\n    \/\/ append the proper extension, if not already there:\n    if( !fileToSaveTo.hasFileExtension(String((\"png\"))) )\n      fileToSaveTo = fileToSaveTo.withFileExtension(String((\"png\")));\n\n    \/\/ ask user for overwriting when the file already exists:\n    if( fileToSaveTo.existsAsFile() )\n    {\n      bool overwrite = AlertWindow::showOkCancelBox(\n        AlertWindow::WarningIcon, \n        String((\"Overwrite Warning\")),                        \n        String((\"File already exists. Overwrite?\")),\n        String((\"yes\")),\n        String((\"no\"))  );\n\n      if( overwrite )\n        fileToSaveTo.deleteFile();\n      else\n        return;\n    }\n\n    Image* im = ownerSystem->getPlotAsImage(w, h);\n\n    \/\/ create a PNGImagefileFormat object:\n    PNGImageFormat pngFormat;\n\n    \/\/ create the file output stream:\n    FileOutputStream fileStream(fileToSaveTo);\n\n    bool success = false;\n    success = pngFormat.writeImageToStream(*im, fileStream);\n\n    delete im;\n  }\n  else if( formatComboBox->getText() == String((\"svg\")) )\n  {\n    \/\/ append the proper extension, if not already there:\n    if( !fileToSaveTo.hasFileExtension(String((\"svg\"))) )\n      fileToSaveTo = fileToSaveTo.withFileExtension(String((\"svg\")));\n\n    \/\/ ask user for overwriting when the file already exists:\n    if( fileToSaveTo.existsAsFile() )\n    {\n      bool overwrite = AlertWindow::showOkCancelBox(\n        AlertWindow::WarningIcon, \n        String((\"Overwrite Warning\")),                        \n        String((\"File already exists. Overwrite?\")),\n        String((\"yes\")),\n        String((\"no\"))  );\n\n      if( overwrite )\n        fileToSaveTo.deleteFile();\n      else\n        return;\n    }\n\n    \/\/ create a dummy-image - this has the side-effect to make the svg-drawing inside the \n    \/\/ CoordinatSystem to have the right dimensions - elegantize this someday...\n    \/\/const Image* dummyImage = ownerSystem->getPlotAsImage(w, h);\n    \/\/delete dummyImage;\n\n    XmlElement* theSVG = ownerSystem->getPlotAsSVG(w, h);\n\n    \/*String myXmlDoc = theSVG->createDocument(String());*\/\n    String myXmlDoc = theSVG->toString();\n    fileToSaveTo.create();\n    fileToSaveTo.appendText(myXmlDoc);\n\n    delete theSVG;\n  }\n}\n\n\n\n\n","avg_line_length":33.2661290323,"max_line_length":107,"alphanum_fraction":0.6561212121,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":14727,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/\/===--- Errors.cpp - Error reporting utilities ---------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Utilities for reporting errors to stderr, system console, and crash logs.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#if defined(_WIN32)\n#include <mutex>\n#endif\n\n#include <inttypes.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#if defined(_WIN32)\n#include <io.h>\n#endif\n#include <stdarg.h>\n\n#include \"ImageInspection.h\"\n#include \"swift\/Runtime\/Debug.h\"\n#include \"swift\/Runtime\/Mutex.h\"\n#include \"swift\/Runtime\/Portability.h\"\n#include \"swift\/Demangling\/Demangle.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n\n#if defined(_MSC_VER)\n#include <DbgHelp.h>\n#else\n#include <cxxabi.h>\n#endif\n\n#if __has_include(<execinfo.h>)\n#include <execinfo.h>\n#endif\n\n#if SWIFT_STDLIB_HAS_ASL\n#include <asl.h>\n#elif defined(__ANDROID__)\n#include <android\/log.h>\n#endif\n\n#if defined(__ELF__)\n#include <unwind.h>\n#endif\n\n#include <inttypes.h>\n\nnamespace FatalErrorFlags {\nenum: uint32_t {\n  ReportBacktrace = 1 << 0\n};\n} \/\/ end namespace FatalErrorFlags\n\nusing namespace swift;\n\n#if SWIFT_STDLIB_SUPPORTS_BACKTRACE_REPORTING && SWIFT_STDLIB_HAS_DLADDR\nstatic bool getSymbolNameAddr(llvm::StringRef libraryName,\n                              const SymbolInfo &syminfo,\n                              std::string &symbolName, uintptr_t &addrOut) {\n  \/\/ If we failed to find a symbol and thus dlinfo->dli_sname is nullptr, we\n  \/\/ need to use the hex address.\n  bool hasUnavailableAddress = syminfo.symbolName == nullptr;\n\n  if (hasUnavailableAddress) {\n    return false;\n  }\n\n  \/\/ Ok, now we know that we have some sort of \"real\" name. Set the outAddr.\n  addrOut = uintptr_t(syminfo.symbolAddress);\n\n  \/\/ First lets try to demangle using cxxabi. If this fails, we will try to\n  \/\/ demangle with swift. We are taking advantage of __cxa_demangle actually\n  \/\/ providing failure status instead of just returning the original string like\n  \/\/ swift demangle.\n#if defined(_WIN32)\n  char szUndName[1024];\n  DWORD dwResult;\n  dwResult = _swift_withWin32DbgHelpLibrary([&] (bool isInitialized) -> DWORD {\n    if (!isInitialized) {\n      return 0;\n    }\n\n    DWORD dwFlags = UNDNAME_COMPLETE;\n#if !defined(_WIN64)\n    dwFlags |= UNDNAME_32_BIT_DECODE;\n#endif\n\n    return UnDecorateSymbolName(syminfo.symbolName.get(), szUndName,\n                                sizeof(szUndName), dwFlags);\n  });\n\n  if (dwResult) {\n    symbolName += szUndName;\n    return true;\n  }\n#else\n  int status;\n  char *demangled =\n      abi::__cxa_demangle(syminfo.symbolName.get(), 0, 0, &status);\n  if (status == 0) {\n    assert(demangled != nullptr &&\n           \"If __cxa_demangle succeeds, demangled should never be nullptr\");\n    symbolName += demangled;\n    free(demangled);\n    return true;\n  }\n  assert(demangled == nullptr &&\n         \"If __cxa_demangle fails, demangled should be a nullptr\");\n#endif\n\n  \/\/ Otherwise, try to demangle with swift. If swift fails to demangle, it will\n  \/\/ just pass through the original output.\n  symbolName = demangleSymbolAsString(\n      syminfo.symbolName.get(), strlen(syminfo.symbolName.get()),\n      Demangle::DemangleOptions::SimplifiedUIDemangleOptions());\n  return true;\n}\n#endif\n\nvoid swift::dumpStackTraceEntry(unsigned index, void *framePC,\n                                bool shortOutput) {\n#if SWIFT_STDLIB_SUPPORTS_BACKTRACE_REPORTING && SWIFT_STDLIB_HAS_DLADDR\n  SymbolInfo syminfo;\n\n  \/\/ 0 is failure for lookupSymbol\n  if (0 == lookupSymbol(framePC, &syminfo)) {\n    return;\n  }\n\n  \/\/ If lookupSymbol succeeded then fileName is non-null. Thus, we find the\n  \/\/ library name here. Avoid using StringRef::rsplit because its definition\n  \/\/ is not provided in the header so that it requires linking with\n  \/\/ libSupport.a.\n  llvm::StringRef libraryName{syminfo.fileName};\n  libraryName = libraryName.substr(libraryName.rfind('\/')).substr(1);\n\n  \/\/ Next we get the symbol name that we are going to use in our backtrace.\n  std::string symbolName;\n  \/\/ We initialize symbolAddr to framePC so that if we succeed in finding the\n  \/\/ symbol, we get the offset in the function and if we fail to find the symbol\n  \/\/ we just get HexAddr + 0.\n  uintptr_t symbolAddr = uintptr_t(framePC);\n  bool foundSymbol =\n      getSymbolNameAddr(libraryName, syminfo, symbolName, symbolAddr);\n  ptrdiff_t offset = 0;\n  if (foundSymbol) {\n    offset = ptrdiff_t(uintptr_t(framePC) - symbolAddr);\n  } else {\n    offset = ptrdiff_t(uintptr_t(framePC) - uintptr_t(syminfo.baseAddress));\n    symbolAddr = uintptr_t(framePC);\n    symbolName = \"<unavailable>\";\n  }\n\n  \/\/ We do not use %p here for our pointers since the format is implementation\n  \/\/ defined. This makes it logically impossible to check the output. Forcing\n  \/\/ hexadecimal solves this issue.\n  \/\/ If the symbol is not available, we print out <unavailable> + offset\n  \/\/ from the base address of where the image containing framePC is mapped.\n  \/\/ This gives enough info to reconstruct identical debugging target after\n  \/\/ this process terminates.\n  if (shortOutput) {\n    fprintf(stderr, \"%s`%s + %td\", libraryName.data(), symbolName.c_str(),\n            offset);\n  } else {\n    constexpr const char *format = \"%-4u %-34s 0x%0.16\" PRIxPTR \" %s + %td\\n\";\n    fprintf(stderr, format, index, libraryName.data(), symbolAddr,\n            symbolName.c_str(), offset);\n  }\n#else\n  if (shortOutput) {\n    fprintf(stderr, \"<unavailable>\");\n  } else {\n    constexpr const char *format = \"%-4u 0x%0.16tx\\n\";\n    fprintf(stderr, format, index, reinterpret_cast<uintptr_t>(framePC));\n  }\n#endif\n}\n\n#if defined(__ELF__)\nstruct UnwindState {\n  void **current;\n  void **end;\n};\n\nstatic _Unwind_Reason_Code SwiftUnwindFrame(struct _Unwind_Context *context, void *arg) {\n  struct UnwindState *state = static_cast<struct UnwindState *>(arg);\n  if (state->current == state->end) {\n    return _URC_END_OF_STACK;\n  }\n\n  uintptr_t pc;\n#if defined(__arm__)\n  \/\/ ARM r15 is PC.  UNW_REG_PC is *not* the same value, and using that will\n  \/\/ result in abnormal behaviour.\n  _Unwind_VRS_Get(context, _UVRSC_CORE, 15, _UVRSD_UINT32, &pc);\n  \/\/ Clear the ISA bit during the reporting.\n  pc &= ~(uintptr_t)0x1;\n#else\n  pc = _Unwind_GetIP(context);\n#endif\n  if (pc) {\n    *state->current++ = reinterpret_cast<void *>(pc);\n  }\n  return _URC_NO_REASON;\n}\n#endif\n\nSWIFT_ALWAYS_INLINE\nstatic bool withCurrentBacktraceImpl(std::function<void(void **, int)> call) {\n#if SWIFT_STDLIB_SUPPORTS_BACKTRACE_REPORTING\n  constexpr unsigned maxSupportedStackDepth = 128;\n  void *addrs[maxSupportedStackDepth];\n#if defined(_WIN32)\n  int symbolCount = CaptureStackBackTrace(0, maxSupportedStackDepth, addrs, NULL);\n#elif defined(__ELF__)\n  struct UnwindState state = {&addrs[0], &addrs[maxSupportedStackDepth]};\n  _Unwind_Backtrace(SwiftUnwindFrame, &state);\n  int symbolCount = state.current - addrs;\n#else\n  int symbolCount = backtrace(addrs, maxSupportedStackDepth);\n#endif\n  call(addrs, symbolCount);\n  return true;\n#else\n  return false;\n#endif\n}\n\nSWIFT_NOINLINE\nbool swift::withCurrentBacktrace(std::function<void(void **, int)> call) {\n  return withCurrentBacktraceImpl(call);\n}\n\nSWIFT_NOINLINE\nvoid swift::printCurrentBacktrace(unsigned framesToSkip) {\n  bool success = withCurrentBacktraceImpl([&](void **addrs, int symbolCount) {\n    for (int i = framesToSkip; i < symbolCount; ++i) {\n      dumpStackTraceEntry(i - framesToSkip, addrs[i]);\n    }\n  });\n  if (!success)\n    fprintf(stderr, \"<backtrace unavailable>\\n\");\n}\n\n#ifdef SWIFT_HAVE_CRASHREPORTERCLIENT\n#include <malloc\/malloc.h>\n\n\/\/ Instead of linking to CrashReporterClient.a (because it complicates the\n\/\/ build system), define the only symbol from that static archive ourselves.\n\/\/\n\/\/ The layout of this struct is CrashReporter ABI, so there are no ABI concerns\n\/\/ here.\nextern \"C\" {\nSWIFT_LIBRARY_VISIBILITY\nstruct crashreporter_annotations_t gCRAnnotations\n__attribute__((__section__(\"__DATA,\" CRASHREPORTER_ANNOTATIONS_SECTION))) = {\n    CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0, 0};\n}\n\n\/\/ Report a message to any forthcoming crash log.\nstatic void\nreportOnCrash(uint32_t flags, const char *message)\n{\n  \/\/ We must use an \"unsafe\" mutex in this pathway since the normal \"safe\"\n  \/\/ mutex calls fatalError when an error is detected and fatalError ends up\n  \/\/ calling us. In other words we could get infinite recursion if the\n  \/\/ mutex errors.\n  static swift::StaticUnsafeMutex crashlogLock;\n\n  crashlogLock.lock();\n\n  char *oldMessage = (char *)CRGetCrashLogMessage();\n  char *newMessage;\n  if (oldMessage) {\n    swift_asprintf(&newMessage, \"%s%s\", oldMessage, message);\n    if (malloc_size(oldMessage)) free(oldMessage);\n  } else {\n    newMessage = strdup(message);\n  }\n  \n  CRSetCrashLogMessage(newMessage);\n\n  crashlogLock.unlock();\n}\n\n#else\n\nstatic void\nreportOnCrash(uint32_t flags, const char *message)\n{\n  \/\/ empty\n}\n\n#endif\n\n\/\/ Report a message to system console and stderr.\nstatic void\nreportNow(uint32_t flags, const char *message)\n{\n#if defined(_WIN32)\n#define STDERR_FILENO 2\n  _write(STDERR_FILENO, message, strlen(message));\n#else\n  fputs(message, stderr);\n  fflush(stderr);\n#endif\n#if SWIFT_STDLIB_HAS_ASL\n  asl_log(nullptr, nullptr, ASL_LEVEL_ERR, \"%s\", message);\n#elif defined(__ANDROID__)\n  __android_log_print(ANDROID_LOG_FATAL, \"SwiftRuntime\", \"%s\", message);\n#endif\n#if SWIFT_STDLIB_SUPPORTS_BACKTRACE_REPORTING\n  if (flags & FatalErrorFlags::ReportBacktrace) {\n    fputs(\"Current stack trace:\\n\", stderr);\n    printCurrentBacktrace();\n  }\n#endif\n}\n\nSWIFT_NOINLINE SWIFT_RUNTIME_EXPORT void\n_swift_runtime_on_report(uintptr_t flags, const char *message,\n                         RuntimeErrorDetails *details) {\n  \/\/ Do nothing. This function is meant to be used by the debugger.\n\n  \/\/ The following is necessary to avoid calls from being optimized out.\n  asm volatile(\"\" \/\/ Do nothing.\n               : \/\/ Output list, empty.\n               : \"r\" (flags), \"r\" (message), \"r\" (details) \/\/ Input list.\n               : \/\/ Clobber list, empty.\n               );\n}\n\nvoid swift::_swift_reportToDebugger(uintptr_t flags, const char *message,\n                                    RuntimeErrorDetails *details) {\n  _swift_runtime_on_report(flags, message, details);\n}\n\nbool swift::_swift_reportFatalErrorsToDebugger = true;\n\nbool swift::_swift_shouldReportFatalErrorsToDebugger() {\n  return _swift_reportFatalErrorsToDebugger;\n}\n\n\/\/\/ Report a fatal error to system console, stderr, and crash logs.\n\/\/\/ Does not crash by itself.\nvoid swift::swift_reportError(uint32_t flags,\n                              const char *message) {\n#if defined(__APPLE__) && NDEBUG\n  flags &= ~FatalErrorFlags::ReportBacktrace;\n#endif\n  reportNow(flags, message);\n  reportOnCrash(flags, message);\n}\n\n\/\/ Report a fatal error to system console, stderr, and crash logs, then abort.\nSWIFT_NORETURN void swift::fatalError(uint32_t flags, const char *format, ...) {\n  va_list args;\n  va_start(args, format);\n\n  char *log;\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wuninitialized\"\n  swift_vasprintf(&log, format, args);\n#pragma GCC diagnostic pop\n\n  swift_reportError(flags, log);\n  abort();\n}\n\n\/\/ Report a warning to system console and stderr.\nvoid\nswift::warningv(uint32_t flags, const char *format, va_list args)\n{\n  char *log;\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wuninitialized\"\n  swift_vasprintf(&log, format, args);\n#pragma GCC diagnostic pop\n  \n  reportNow(flags, log);\n  \n  free(log);\n}\n\n\/\/ Report a warning to system console and stderr.\nvoid\nswift::warning(uint32_t flags, const char *format, ...)\n{\n  va_list args;\n  va_start(args, format);\n\n  warningv(flags, format, args);\n}\n\n\/\/ Crash when a deleted method is called by accident.\nSWIFT_RUNTIME_EXPORT SWIFT_NORETURN void swift_deletedMethodError() {\n  swift::fatalError(\/* flags = *\/ 0,\n                    \"Fatal error: Call of deleted method\\n\");\n}\n\n\/\/ Crash due to a retain count overflow.\n\/\/ FIXME: can't pass the object's address from InlineRefCounts without hacks\nvoid swift::swift_abortRetainOverflow() {\n  swift::fatalError(FatalErrorFlags::ReportBacktrace,\n                    \"Fatal error: Object was retained too many times\");\n}\n\n\/\/ Crash due to an unowned retain count overflow.\n\/\/ FIXME: can't pass the object's address from InlineRefCounts without hacks\nvoid swift::swift_abortUnownedRetainOverflow() {\n  swift::fatalError(FatalErrorFlags::ReportBacktrace,\n                    \"Fatal error: Object's unowned reference was retained too many times\");\n}\n\n\/\/ Crash due to a weak retain count overflow.\n\/\/ FIXME: can't pass the object's address from InlineRefCounts without hacks\nvoid swift::swift_abortWeakRetainOverflow() {\n  swift::fatalError(FatalErrorFlags::ReportBacktrace,\n                    \"Fatal error: Object's weak reference was retained too many times\");\n}\n\n\/\/ Crash due to retain of a dead unowned reference.\n\/\/ FIXME: can't pass the object's address from InlineRefCounts without hacks\nvoid swift::swift_abortRetainUnowned(const void *object) {\n  if (object) {\n    swift::fatalError(FatalErrorFlags::ReportBacktrace,\n                      \"Fatal error: Attempted to read an unowned reference but \"\n                      \"object %p was already deallocated\", object);\n  } else {\n    swift::fatalError(FatalErrorFlags::ReportBacktrace,\n                      \"Fatal error: Attempted to read an unowned reference but \"\n                      \"the object was already deallocated\");\n  }\n}\n\n\/\/\/ Halt due to enabling an already enabled dynamic replacement().\nvoid swift::swift_abortDynamicReplacementEnabling() {\n  swift::fatalError(FatalErrorFlags::ReportBacktrace,\n                    \"Fatal error: trying to enable a dynamic replacement \"\n                    \"that is already enabled\");\n}\n\n\/\/\/ Halt due to disabling an already disabled dynamic replacement().\nvoid swift::swift_abortDynamicReplacementDisabling() {\n  swift::fatalError(FatalErrorFlags::ReportBacktrace,\n                    \"Fatal error: trying to disable a dynamic replacement \"\n                    \"that is already disabled\");\n}\n\n\/\/\/ Halt due to trying to use unicode data on platforms that don't have it.\nvoid swift::swift_abortDisabledUnicodeSupport() {\n  swift::fatalError(FatalErrorFlags::ReportBacktrace,\n                    \"Unicode normalization data is disabled on this platform\");\n\n}\n","avg_line_length":31.4679487179,"max_line_length":91,"alphanum_fraction":0.6987166429,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5533,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":71.0,"content":"#include <gtest\/gtest.h>\n#include <futures\/Stream.h>\n#include <futures\/Timer.h>\n#include <futures\/TcpStream.h>\n#include <futures\/http\/HttpCodec.h>\n#include <futures\/service\/RpcFuture.h>\n#include <futures\/CpuPoolExecutor.h>\n#include <futures\/io\/AsyncSocket.h>\n#include <futures\/io\/AsyncServerSocket.h>\n\nusing namespace futures;\n\nTEST(Stream, Empty) {\n    EmptyStream<int> e;\n    EXPECT_EQ(e.poll()->value(), Optional<int>());\n}\n\nTEST(Stream, Iter) {\n    std::vector<std::string> v{\"AAA\", \"BBB\", \"CCC\"};\n    auto v_old = v;\n    auto s = makeIterStream(std::make_move_iterator(v.begin()),\n            std::make_move_iterator(v.end()));\n    auto f = s.collect();\n    std::vector<std::string> v1 = f.value();\n    EXPECT_EQ(v_old, v1);\n}\n\nTEST(Stream, Filter) {\n    std::vector<std::string> v{\"AAA\", \"BBB1\", \"CCC\"};\n    auto s = makeIterStream(std::make_move_iterator(v.begin()),\n            std::make_move_iterator(v.end()))\n        .filter([] (const std::string &s) {\n            return s.size() == 3;\n        });\n\n    auto f = s.collect();\n    std::vector<std::string> v1 = f.value();\n    const std::vector<std::string> kResult{\"AAA\", \"CCC\"};\n    EXPECT_EQ(v1, kResult);\n}\n\nTEST(Stream, Map) {\n    std::vector<std::string> v{\"AAA\", \"BBB1\", \"CCC\"};\n    auto s = makeIterStream(std::make_move_iterator(v.begin()),\n            std::make_move_iterator(v.end()))\n        .map([] (const std::string &s) {\n            return s.length();\n        });\n\n    auto f = s.collect();\n    std::vector<size_t> v1 = f.value();\n    const std::vector<size_t> kResult{3, 4, 3};\n    EXPECT_EQ(v1, kResult);\n}\n\nTEST(Stream, AndThen) {\n    std::vector<std::string> v{\"AAA\", \"BBB1\", \"CCC\"};\n    auto s = makeIterStream(std::make_move_iterator(v.begin()),\n            std::make_move_iterator(v.end()))\n        .andThen([] (const std::string &s) {\n            return makeOk(s.length());\n        });\n\n    auto f = s.collect();\n    std::vector<size_t> v1 = f.value();\n    const std::vector<size_t> kResult{3, 4, 3};\n    EXPECT_EQ(v1, kResult);\n}\n\nTEST(Stream, Take) {\n    const std::vector<int> v{0, 1, 2};\n    auto s = makeIterStream(v.begin(), v.end()).take(2);\n    const std::vector<int> kResult{0,1};\n    EXPECT_EQ(s.collect().value(), kResult);\n\n    auto s1 = makeIterStream(v.begin(), v.end()).take(10);\n    EXPECT_EQ(s1.collect().value(), v);\n}\n\nTEST(Stream, Iterator) {\n    std::vector<int> v{0, 1, 2};\n    auto s = makeIterStream(v.begin(), v.end());\n    int i = 0;\n    for (auto &e: s) {\n        EXPECT_EQ(e, i);\n        i++;\n    }\n}\n\nTEST(StreamIO, NewSocket) {\n    EventExecutor ev;\n\n    auto f = io::SocketChannel::connect(&ev, folly::SocketAddress(\"127.0.0.1\", 8011))\n        .andThen([] (io::SocketChannel::Ptr sock) {\n            return sock->readStream()\n            .forEach([sock] (std::unique_ptr<folly::IOBuf> buf) {\n                    std::cerr << \"READ: \" << buf->computeChainDataLength() << std::endl;\n                    EventExecutor::current()->spawn(\n                            sock->write(std::move(buf))\n                                .error([] (folly::exception_wrapper w) {\n                                    std::cerr << \"ERR: \" << w.what() << std::endl;\n                                })\n                    );\n            });\n        })\n        .then([] (Try<folly::Unit> err) {\n            if (err.hasException())\n                std::cerr << err.exception().what() << std::endl;\n            return makeOk();\n        });\n    ev.spawn(std::move(f));\n    ev.run();\n}\n\nstatic BoxedFuture<folly::Unit> doEcho(io::SocketChannel::Ptr sock) {\n    return io::WriteFuture(sock, folly::IOBuf::copyBuffer(\"XXX\", 3))\n        .error([] (folly::exception_wrapper w) {\n            std::cerr << \"WRITE_ERR: \" << w.what() << std::endl;\n        }).boxed();\n}\n\nTEST(StreamIO, Accept) {\n    EventExecutor ev;\n    folly::SocketAddress addr(\"127.0.0.1\", 8033);\n    auto p = std::make_shared<io::AsyncServerSocket>(&ev, addr);\n\n    int cnt = 0;\n    auto f = p->accept()\n        .forEach2([&cnt] (tcp::Socket sock, folly::SocketAddress peer) mutable {\n            std::cerr << \"accept from: \" << peer.getAddressStr();\n            auto ev = EventExecutor::current();\n            auto new_sock = std::make_shared<io::SocketChannel>(ev, std::move(sock), peer);\n            ev->spawn(doEcho(new_sock));\n            cnt ++;\n            if (cnt > 1)\n                ev->stop();\n    }).error([] (folly::exception_wrapper err) {\n        std::cerr << err.what() << std::endl;\n    });\n    for (size_t i = 0; i < 2; i++) {\n        auto f = io::SocketChannel::connect(&ev, addr)\n            .andThen([] (io::SocketChannel::Ptr sock) {\n                    return sock->readStream()\n                    .forEach([sock] (std::unique_ptr<folly::IOBuf> buf) {\n                            std::cerr << \"READ: \" << buf->computeChainDataLength() << std::endl;\n                            EventExecutor::current()->spawn(\n                                    sock->write(std::move(buf))\n                                        .error([] (folly::exception_wrapper w) {\n                                            std::cerr << \"ERR: \" << w.what() << std::endl;\n                                        })\n                                     );\n                            });\n            })\n\t    .then([] (Try<folly::Unit> err) {\n                if (err.hasException())\n                    std::cerr << err.exception().what() << std::endl;\n                return makeOk();\n            });\n        ev.spawn(std::move(f));\n    }\n    ev.spawn(std::move(f));\n    ev.run();\n}\n\n","avg_line_length":33.5333333333,"max_line_length":96,"alphanum_fraction":0.5102114585,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4394,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":27.0,"content":"\/*\r\n-----------------------------------------------------------------------------------------------\r\nCopyright (C) 2013 Henry van Merode. All rights reserved.\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of\r\nthis software and associated documentation files (the \"Software\"), to deal in\r\nthe Software without restriction, including without limitation the rights to\r\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\r\nthe Software, and to permit persons to whom the Software is furnished to do so,\r\nsubject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n-----------------------------------------------------------------------------------------------\r\n*\/\r\n\r\n#include \"ParticleUniversePCH.h\"\r\n\r\n#ifndef PARTICLE_UNIVERSE_EXPORTS\r\n#define PARTICLE_UNIVERSE_EXPORTS\r\n#endif\r\n\r\n#include \"Externs\/ParticleUniverseGravityExtern.h\"\r\n#include \"Externs\/ParticleUniverseGravityExternTokens.h\"\r\n#include \"ParticleUniverseScriptDeserializerTokens.h\"\r\n\r\nnamespace ParticleUniverse\r\n{\r\n\t\/\/-----------------------------------------------------------------------\r\n\tbool GravityExternTranslator::translateChildProperty(ScriptCompiler* compiler, const AbstractNodePtr &node)\r\n\t{\r\n\t\tPropertyAbstractNode* prop = reinterpret_cast<PropertyAbstractNode*>(node.get());\r\n\t\tExtern* ex = any_cast<Extern*>(prop->parent->context);\r\n\t\tGravityExtern* externObject = static_cast<GravityExtern*>(ex);\r\n\r\n\t\tif (prop->name == token[TOKEN_GRAVITY])\r\n\t\t{\r\n\t\t\tif (passValidateProperty(compiler, prop, token[TOKEN_GRAVITY], VAL_REAL))\r\n\t\t\t{\r\n\t\t\t\tReal val = 0.0f;\r\n\t\t\t\tif(getReal(prop->values.front(), &val))\r\n\t\t\t\t{\r\n\t\t\t\t\texternObject->setGravity(val);\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (prop->name == token[TOKEN_DISTANCE_THRESHOLD])\r\n\t\t{\r\n\t\t\t\/\/ Property: distance_threshold\r\n\t\t\tif (passValidateProperty(compiler, prop, token[TOKEN_DISTANCE_THRESHOLD], VAL_REAL))\r\n\t\t\t{\r\n\t\t\t\tReal val;\r\n\t\t\t\tif(getReal(prop->values.front(), &val))\r\n\t\t\t\t{\r\n\t\t\t\t\texternObject->setDistanceThreshold(val);\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (prop->name == token[TOKEN_EXTERN_DISTANCE_THRESHOLD])\r\n\t\t{\r\n\t\t\t\/\/ Property: attachable_distance_threshold (deprecated and replaced by 'distance_threshold')\r\n\t\t\tif (passValidateProperty(compiler, prop, token[TOKEN_EXTERN_DISTANCE_THRESHOLD], VAL_REAL))\r\n\t\t\t{\r\n\t\t\t\tReal val;\r\n\t\t\t\tif(getReal(prop->values.front(), &val))\r\n\t\t\t\t{\r\n\t\t\t\t\texternObject->setDistanceThreshold(val);\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn false;\r\n\t}\r\n\t\/\/-----------------------------------------------------------------------\r\n\tbool GravityExternTranslator::translateChildObject(ScriptCompiler* compiler, const AbstractNodePtr &node)\r\n\t{\r\n\t\t\/\/ No objects\r\n\t\treturn false;\r\n\t}\r\n\t\/\/-----------------------------------------------------------------------\r\n\t\/\/-----------------------------------------------------------------------\r\n\t\/\/-----------------------------------------------------------------------\r\n\tvoid GravityExternWriter::write(ParticleScriptSerializer* serializer, const IElement* element)\r\n\t{\r\n\t\t\/\/ Cast the element to a GravityExtern\r\n\t\tconst Extern* externObject = static_cast<const Extern*>(element);\r\n\t\tconst GravityExtern* gravityExtern = static_cast<const GravityExtern*>(externObject);\r\n\t\tserializer->writeLine(token[TOKEN_EXTERN], externObject->getExternType(), externObject->getName(), 8);\r\n\t\tserializer->writeLine(\"{\", 8);\r\n\r\n\t\t\/\/ Write base attributes\r\n\t\tExternWriter::write(serializer, element);\r\n\t\tAttachableWriter::write(serializer, element);\r\n\r\n\t\t\/\/ Write own attributes\r\n\t\tif (gravityExtern->getGravity() != GravityAffector::DEFAULT_GRAVITY) serializer->writeLine(\r\n\t\t\ttoken[TOKEN_GRAVITY], StringConverter::toString(gravityExtern->getGravity()), 12);\r\n\r\n\t\t\/\/ Write the close bracket\r\n\t\tserializer->writeLine(\"}\", 8);\r\n\t}\r\n\r\n}\r\n","avg_line_length":38.5438596491,"max_line_length":109,"alphanum_fraction":0.6367774238,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3030,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Copyright (c) 2021 Huawei Device Co., Ltd.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"shell_command.h\"\n\n#include <getopt.h>\n#include \"hilog_wrapper.h\"\n\nnamespace OHOS {\nnamespace AAFwk {\n\nShellCommand::ShellCommand(int argc, char *argv[], std::string name)\n{\n    opterr = 0;\n    argc_ = argc;\n    argv_ = argv;\n    name_ = name;\n\n    if (argc < MIN_ARGUMENT_NUMBER) {\n        cmd_ = \"help\";\n        return;\n    }\n    cmd_ = argv[1];\n    for (int i = 2; i < argc; i++) {\n        argList_.push_back(argv[i]);\n    }\n}\n\nShellCommand::~ShellCommand()\n{}\n\nErrCode ShellCommand::OnCommand()\n{\n    int result = OHOS::ERR_OK;\n\n    auto respond = commandMap_[cmd_];\n    if (respond == nullptr) {\n        resultReceiver_.append(GetCommandErrorMsg());\n        respond = commandMap_[\"help\"];\n    }\n\n    if (init() == OHOS::ERR_OK) {\n        respond();\n    } else {\n        result = OHOS::ERR_INVALID_VALUE;\n    }\n\n    return result;\n}\n\nstd::string ShellCommand::ExecCommand()\n{\n    int result = CreateCommandMap();\n    if (result != OHOS::ERR_OK) {\n        HILOG_ERROR(\"failed to create command map.\\n\");\n    }\n\n    result = CreateMessageMap();\n    if (result != OHOS::ERR_OK) {\n        HILOG_ERROR(\"failed to create message map.\\n\");\n    }\n\n    result = OnCommand();\n    if (result != OHOS::ERR_OK) {\n        HILOG_ERROR(\"failed to execute your command.\\n\");\n\n        resultReceiver_ = \"error: failed to execute your command.\\n\";\n    }\n\n    return resultReceiver_;\n}\n\nstd::string ShellCommand::GetCommandErrorMsg() const\n{\n    std::string commandErrorMsg =\n        name_ + \": '\" + cmd_ + \"' is not a valid \" + name_ + \" command. See '\" + name_ + \" help'.\\n\";\n\n    return commandErrorMsg;\n}\n\nstd::string ShellCommand::GetUnknownOptionMsg(std::string &unknownOption) const\n{\n    std::string result = \"\";\n\n    if (optind < 0 || optind > argc_) {\n        return result;\n    }\n\n    result.append(\"error: unknown option\");\n    result.append(\".\\n\");\n\n    return result;\n}\n\nstd::string ShellCommand::GetMessageFromCode(const int32_t code) const\n{\n    HILOG_INFO(\"[%{public}s(%{public}s)] enter\", __FILE__, __FUNCTION__);\n    HILOG_INFO(\"code = %{public}d\", code);\n\n    std::string result = \"\";\n    if (messageMap_.find(code) != messageMap_.end()) {\n        std::string message = messageMap_.at(code);\n\n        if (message.size() != 0) {\n            result.append(message + \"\\n\");\n        }\n    }\n\n    HILOG_INFO(\"result = %{public}s\", result.c_str());\n\n    return result;\n}\n\n}  \/\/ namespace AAFwk\n}  \/\/ namespace OHOS","avg_line_length":23.8582677165,"max_line_length":101,"alphanum_fraction":0.6247524752,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":261,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":7.0,"content":"#include <iostream>\nusing namespace std;\n\nint f(int m, int n) {\n    if (m == 0 || n == 0) return 0;\n    if (m == 1 && n == 1) return 1;\n    return f(m-1, n) + f(m, n-1);\n}\n\nint main()\n{\n    int m, n;\n    cin >> m >> n;\n\n    cout << f(m, n);\n    \n    return 0;\n}","avg_line_length":14.5,"max_line_length":35,"alphanum_fraction":0.4406130268,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2273,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/**\r\n * base64.cpp\r\n *\r\n * Created on: 09.12.2015\r\n *\r\n * Copyright (c) 2015 Markus Sattler. All rights reserved.\r\n * This file is part of the ESP8266 core for Arduino.\r\n *\r\n * This library is free software; you can redistribute it and\/or\r\n * modify it under the terms of the GNU Lesser General Public\r\n * License as published by the Free Software Foundation; either\r\n * version 2.1 of the License, or (at your option) any later version.\r\n *\r\n * This library is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * Lesser General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Lesser General Public\r\n * License along with this library; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\r\n *\r\n *\/\r\n\r\n#include \"Arduino.h\"\r\nextern \"C\" {\r\n#include \"libb64\/cdecode.h\"\r\n#include \"libb64\/cencode.h\"\r\n}\r\n#include \"base64.h\"\r\n\r\n\/**\r\n * convert input data to base64\r\n * @param data uint8_t *\r\n * @param length size_t\r\n * @return String\r\n *\/\r\nString base64::encode(uint8_t * data, size_t length, bool doNewLines) {\r\n    \/\/ base64 needs more size then the source data, use cencode.h macros\r\n    size_t size = ((doNewLines ? base64_encode_expected_len(length)\r\n                               : base64_encode_expected_len_nonewlines(length)) + 1);\r\n    char * buffer = (char *) malloc(size);\r\n    if(buffer) {\r\n        base64_encodestate _state;\r\n        if(doNewLines)\r\n        {\r\n            base64_init_encodestate(&_state);\r\n        }\r\n        else \r\n        {\r\n            base64_init_encodestate_nonewlines(&_state);\r\n        }\r\n        int len = base64_encode_block((const char *) &data[0], length, &buffer[0], &_state);\r\n        len = base64_encode_blockend((buffer + len), &_state);\r\n\r\n        String base64 = String(buffer);\r\n        free(buffer);\r\n        return base64;\r\n    }\r\n    return String(\"-FAIL-\");\r\n}\r\n\r\n\/**\r\n * convert input data to base64\r\n * @param text String\r\n * @return String\r\n *\/\r\nString base64::encode(String text, bool doNewLines) {\r\n    return base64::encode((uint8_t *) text.c_str(), text.length(), doNewLines);\r\n}\r\n\r\n","avg_line_length":31.5694444444,"max_line_length":93,"alphanum_fraction":0.6454025517,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":689,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include \"cbpch.h\"\n#include \"File.h\"\n\n#include <fstream>\n\nnamespace CherryBell {\n\tstd::string IO::ReadFile(std::string_view filepath)\n\t{\n\t\tCB_PROFILE_FUNCTION();\n\t\tstd::string fileContents;\n\t\tstd::ifstream in(filepath.data(), std::ios::in | std::ios::binary);\n\t\tif (in)\n\t\t{\n\t\t\tin.seekg(0, std::ios::end);\n\t\t\tsize_t size = in.tellg();\n\t\t\tif (size != -1)\n\t\t\t{\n\t\t\t\tfileContents.resize(in.tellg());\n\t\t\t\tin.seekg(0, std::ios::beg);\n\t\t\t\tin.read(&fileContents[0], fileContents.size());\n\t\t\t\tin.close();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCB_CORE_ERROR(\"Could not read from file \\\"{0}\\\"\", filepath);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCB_CORE_ERROR(\"Could not open file \\\"{0}\\\"\", filepath);\n\t\t}\n\t\treturn fileContents;\n\t}\n}\n","avg_line_length":19.6857142857,"max_line_length":69,"alphanum_fraction":0.6081277213,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13644,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC0-1.0","CC-BY-4.0"],"max_stars_count":null,"content":"\/\/ -----------------------------------------------------------------------------------------------------\n\/\/ Copyright (c) 2006-2019, Knut Reinert & Freie Universit\u00e4t Berlin\n\/\/ Copyright (c) 2016-2019, Knut Reinert & MPI f\u00fcr molekulare Genetik\n\/\/ This file may be used, modified and\/or redistributed under the terms of the 3-clause BSD-License\n\/\/ shipped with this file and also available at: https:\/\/github.com\/seqan\/seqan3\/blob\/master\/LICENSE.md\n\/\/ -----------------------------------------------------------------------------------------------------\n\n#include <list>\n#include <vector>\n\n#include <gtest\/gtest.h>\n\n#include <meta\/meta.hpp>\n\n\n#include <seqan3\/core\/type_traits\/all.hpp>\n#include <seqan3\/core\/detail\/reflection.hpp>\n#include <seqan3\/range\/shortcuts.hpp>\n#include <seqan3\/range\/detail\/random_access_iterator.hpp>\n#include <seqan3\/range\/views\/take_exactly.hpp>\n#include <seqan3\/std\/ranges>\n\nusing namespace seqan3;\n\nTEST(range_and_iterator, iterator_)\n{\n    EXPECT_TRUE((std::is_same_v<std::ranges::iterator_t<std::vector<int>>,\n                                typename std::vector<int>::iterator>));\n    EXPECT_TRUE((std::is_same_v<std::ranges::iterator_t<std::vector<int> const>,\n                                typename std::vector<int>::const_iterator>));\n\n    auto v = std::views::iota(1);\n    EXPECT_TRUE((std::is_same_v<std::ranges::iterator_t<decltype(v)>,\n                                decltype(begin(v))>));\n    EXPECT_FALSE((std::is_same_v<std::ranges::iterator_t<decltype(v)>,\n                                 decltype(end(v))>));\n}\n\nTEST(range_and_iterator, sentinel_)\n{\n    EXPECT_TRUE((std::is_same_v<std::ranges::sentinel_t<std::vector<int>>,\n                                typename std::vector<int>::iterator>));\n    EXPECT_TRUE((std::is_same_v<std::ranges::sentinel_t<std::vector<int> const>,\n                                typename std::vector<int>::const_iterator>));\n    EXPECT_TRUE((std::is_same_v<std::ranges::sentinel_t<std::vector<int>>,\n                                std::ranges::iterator_t<std::vector<int>>>));\n\n    auto v = std::views::iota(1);\n    EXPECT_FALSE((std::is_same_v<std::ranges::sentinel_t<decltype(v)>,\n                                decltype(begin(v))>));\n    EXPECT_TRUE((std::is_same_v<std::ranges::sentinel_t<decltype(v)>,\n                                decltype(end(v))>));\n}\n\ntemplate <typename list1, typename list2, size_t pos = 0>\nvoid expect_same_types()\n{\n    constexpr bool val = std::is_same_v<meta::at_c<list1, pos>, meta::at_c<list2, pos>>;\n    if constexpr (!val)\n    {\n        std::cerr << \"pos: \" << pos << \" \\'\" << detail::get_display_name_v<meta::at_c<list1, pos>>\n                  << \"\\' not equal to \\'\" << detail::get_display_name_v<meta::at_c<list2, pos>> << \"\\' \\n\";\n    }\n    EXPECT_TRUE(val);\n\n    if constexpr (pos < list1::size() - 1)\n        expect_same_types<list1, list2, pos + 1>();\n}\n\nTEST(range_and_iterator, value_type_)\n{\n    using foreign_iterator = detail::random_access_iterator<std::vector<int>>;\n    auto v = std::views::iota(1);\n    using type_list = meta::list<value_type_t<std::vector<int>>,                    \/\/ short\n                                 typename value_type<std::vector<int>>::type,       \/\/ long\n                                 typename std::vector<int>::value_type,             \/\/ member type\n                                 value_type_t<std::vector<int> const>,              \/\/ const container\n                                 value_type_t<std::ranges::iterator_t<std::vector<int>>>,        \/\/ iterator\n                                 value_type_t<foreign_iterator>,                    \/\/ iterator2\n                                 value_type_t<decltype(v)>>;                        \/\/ range, no member\n    using comp_list = meta::list<int,\n                                 int,\n                                 int,\n                                 int,\n                                 int,\n                                 int,\n                                 int>;\n\n    expect_same_types<type_list, comp_list>();\n}\n\nTEST(range_and_iterator, reference_)\n{\n    using foreign_iterator = detail::random_access_iterator<std::vector<int>>;\n    auto v = std::views::iota(1);\n    using type_list = meta::list<reference_t<std::vector<int>>,                    \/\/ short\n                                 typename reference<std::vector<int>>::type,       \/\/ long\n                                 typename std::vector<int>::reference,             \/\/ member type\n                                 reference_t<std::vector<int> const>,              \/\/ const container\n                                 reference_t<std::ranges::iterator_t<std::vector<int>>>,        \/\/ iterator\n                                 reference_t<foreign_iterator>,                    \/\/ iterator2\n                                 reference_t<decltype(v)>>;                        \/\/ range, no member\n\n    using comp_list = meta::list<int &,\n                                 int &,\n                                 int &,\n                                 int const &,   \/\/ container is const\n                                 int &,\n                                 int &,\n                                 int>;          \/\/ view creates values\n\n    expect_same_types<type_list, comp_list>();\n}\n\nTEST(range_and_iterator, rvalue_reference_)\n{\n    using foreign_iterator = detail::random_access_iterator<std::vector<int>>;\n    auto v = std::views::iota(1);\n    using type_list = meta::list<rvalue_reference_t<std::vector<int>>,                    \/\/ short\n                                 typename rvalue_reference<std::vector<int>>::type,       \/\/ long\n\/\/ No types have member,yet:\n\/\/                                  typename std::vector<int>::rvalue_reference,             \/\/ member type\n                                 rvalue_reference_t<std::vector<int> const>,              \/\/ const container\n                                 rvalue_reference_t<std::ranges::iterator_t<std::vector<int>>>,        \/\/ iterator\n                                 rvalue_reference_t<foreign_iterator>,                    \/\/ iterator2\n                                 rvalue_reference_t<decltype(v)>>;                        \/\/ range, no member\n\n    using comp_list = meta::list<int &&,\n                                 int &&,\n\/\/                                  int &&,\n                                 int const &&,  \/\/ container is const\n                                 int &&,\n                                 int &&,\n                                 int>;          \/\/ view creates values\n\n    expect_same_types<type_list, comp_list>();\n}\n\nTEST(range_and_iterator, const_reference_)\n{\n\/\/     using foreign_iterator = detail::random_access_iterator<std::vector<int>>;\n    auto v = std::views::iota(1);\n    using type_list = meta::list<const_reference_t<std::vector<int>>,                    \/\/ short\n                                 typename const_reference<std::vector<int>>::type,       \/\/ long\n                                 typename std::vector<int>::const_reference,             \/\/ member type\n                                 const_reference_t<std::vector<int> const>,              \/\/ const container\n\/\/ not defined on iterators\n\/\/                                  const_reference_t<std::ranges::iterator_t<std::vector<int>>>,        \/\/ iterator\n\/\/                                  const_reference_t<foreign_iterator>,                    \/\/ iterator2\n                                 const_reference_t<decltype(v)>>;                        \/\/ range, no member\n\n    using comp_list = meta::list<int const &,\n                                 int const &,\n                                 int const &,\n                                 int const &,  \/\/ container is const\n\/\/                                  int const &,\n\/\/                                  int const &,\n                                 int>;          \/\/ view creates values\n\n    expect_same_types<type_list, comp_list>();\n}\n\nTEST(range_and_iterator, difference_type_)\n{\n    \/\/TODO(h-2): add something that actually has a different difference_type\n    using foreign_iterator = detail::random_access_iterator<std::vector<int>>;\n    auto v = std::views::iota(1);\n    using type_list = meta::list<difference_type_t<std::vector<int>>,                    \/\/ short\n                                 typename difference_type<std::vector<int>>::type,       \/\/ long\n                                 typename std::vector<int>::difference_type,             \/\/ member type\n                                 difference_type_t<std::vector<int> const>,              \/\/ const container\n                                 difference_type_t<std::ranges::iterator_t<std::vector<int>>>,        \/\/ iterator\n                                 difference_type_t<foreign_iterator>,                    \/\/ iterator2\n                                 difference_type_t<decltype(v)>>;                        \/\/ range, no member\n\n    \/\/ views::ints' difference_type is not std::ptrdiff_t, but depends on the size.\n    \/\/ For infinite views, like in our case, it's std::int_fast64_t (or std::int_fast32_t on 32bit).\n    \/\/ On most platforms this is the same as std::size_t (`long int` on Linux and FreeBSD;\n    \/\/ `long long int` on macOS and MSVC) BUT on some platforms like OpenBSD std::ptrdiff_t is\n    \/\/ `long int`, but std::int64_t and std::int_fast64_t are `long long int`.\n    \/\/ This detects word-size and selects the corresponding int_fast*_t which is always correct\n    using view_int_diff_t = std::conditional_t<sizeof(std::ptrdiff_t) == 8,\n                                               std::int_fast64_t,\n                                               std::int_fast32_t>;\n\n    using comp_list = meta::list<std::ptrdiff_t,\n                                 std::ptrdiff_t,\n                                 std::ptrdiff_t,\n                                 std::ptrdiff_t,\n                                 std::ptrdiff_t,\n                                 std::ptrdiff_t,\n                                 view_int_diff_t>;\n\n    expect_same_types<type_list, comp_list>();\n}\n\nTEST(range_and_iterator, size_type_)\n{\n    \/\/TODO(h-2): add something that actually has a different size_type\n    using foreign_iterator = detail::random_access_iterator<std::vector<int>>;\n\/\/ iota is not a sized range, but take_exactly is\n    auto v = std::views::iota(0) | views::take_exactly(2);\n    using type_list = meta::list<size_type_t<std::vector<int>>,                    \/\/ short\n                                 typename size_type<std::vector<int>>::type,       \/\/ long\n                                 typename std::vector<int>::size_type,             \/\/ member type\n                                 size_type_t<std::vector<int> const>,              \/\/ const container\n                                 size_type_t<std::ranges::iterator_t<std::vector<int>>>,        \/\/ iterator\n                                 size_type_t<foreign_iterator>,                    \/\/ iterator2\n                                 size_type_t<decltype(v)>>;                        \/\/ range, no member\n\n    using comp_list = meta::list<size_t,\n                                 size_t,\n                                 size_t,\n                                 size_t,\n                                 size_t,\n                                 size_t,\n                                 size_t>;\n\n    expect_same_types<type_list, comp_list>();\n}\n\nTEST(range_and_iterator, innermost_value_type_)\n{\n    using type_list = meta::list<typename innermost_value_type<std::vector<int>>::type,         \/\/ long\n                                 innermost_value_type_t<std::vector<int>>,                      \/\/ short\n                                 innermost_value_type_t<std::vector<std::vector<int>>>,         \/\/ two-level\n                                 innermost_value_type_t<std::ranges::iterator_t<std::vector<int>>>,          \/\/ iterator\n                                 innermost_value_type_t<std::ranges::iterator_t<std::vector<int> const>>>;   \/\/ const_iterator\n\n    using comp_list = meta::list<int,\n                                 int,\n                                 int,\n                                 int,\n                                 int>;\n\n    expect_same_types<type_list, comp_list>();\n}\n\nTEST(range_and_iterator, dimension)\n{\n    EXPECT_EQ(dimension_v<std::vector<int>>,                            1u);\n    EXPECT_EQ(dimension_v<std::ranges::iterator_t<std::vector<int>>>,                1u);\n    EXPECT_EQ(dimension_v<std::vector<std::vector<int>>>,               2u);\n    EXPECT_EQ(dimension_v<std::ranges::iterator_t<std::vector<std::vector<int>>>>,   2u);\n}\n\nTEST(range_and_iterator, compatible)\n{\n    EXPECT_TRUE((compatible<std::vector<int>,\n                                    std::list<int>>));\n    EXPECT_TRUE((compatible<std::vector<int>,\n                                    std::ranges::iterator_t<std::vector<int>>>));\n    EXPECT_TRUE((compatible<std::vector<int>,\n                                    std::ranges::iterator_t<std::vector<int> const>>));\n    EXPECT_TRUE((compatible<std::list<std::vector<char>>,\n                                    std::ranges::iterator_t<std::vector<std::string>>>));\n\n    EXPECT_FALSE((compatible<std::list<std::vector<char>>,\n                                     std::string>));\n    EXPECT_FALSE((compatible<std::list<std::vector<char>>,\n                                     std::ranges::iterator_t<std::string>>));\n    EXPECT_FALSE((compatible<std::list<int>,\n                                     int>));\n    EXPECT_FALSE((compatible<std::vector<int>,\n                                     std::string>));\n}\n","avg_line_length":51.1011235955,"max_line_length":126,"alphanum_fraction":0.4904720023,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6899,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/$Id$\n\/\/------------------------------------------------------------------------------\n\/\/                                EndOptimize \n\/\/------------------------------------------------------------------------------\n\/\/ GMAT: General Mission Analysis Tool.\n\/\/\n\/\/ Copyright (c) 2002 - 2018 United States Government as represented by the\n\/\/ Administrator of the National Aeronautics and Space Administration.\n\/\/ All Other Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \n\/\/ You may not use this file except in compliance with the License. \n\/\/ You may obtain a copy of the License at:\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0. \n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either \n\/\/ express or implied.   See the License for the specific language\n\/\/ governing permissions and limitations under the License.\n\/\/\n\/\/ Developed jointly by NASA\/GSFC and Thinking Systems, Inc. under contract\n\/\/ number NNG04CC06P\n\/\/\n\/\/ Author:  Daniel Hunter\/GSFC\/MAB (CoOp)\n\/\/ Created: 2006.07.20\n\/\/\n\/**\n * Implementation for the EndOptimize command class\n *\/\n\/\/------------------------------------------------------------------------------\n\n#include \"EndOptimize.hpp\"\n#include \"BranchCommand.hpp\"\n#include \"MessageInterface.hpp\"\n\n\/\/#define DEBUG_OPTIMIZER_COMMANDS\n\n\/\/------------------------------------------------------------------------------\n\/\/ static data\n\/\/------------------------------------------------------------------------------\n\n\/\/VC++ error C2466: cannot allocate an array of constant size 0\n\/\/ so commented out for possible later use\n\/\/const std::string\n\/\/EndOptimize::PARAMETER_TEXT[EndOptimizeParamCount - GmatCommandParamCount] = {};\n\/\/const Gmat::ParameterType\n\/\/EndOptimize::PARAMETER_TYPE[EndOptimizeParamCount - GmatCommandParamCount] = {};\n\n\/\/------------------------------------------------------------------------------\n\/\/ public methods\n\/\/------------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------------------\n\/\/ constructor\n\/\/------------------------------------------------------------------------------\nEndOptimize::EndOptimize() :\n   GmatCommand         (\"EndOptimize\")\n{\n   objectTypeNames.push_back(\"BranchEnd\");\n   depthChange = -1;\n   parameterCount = EndOptimizeParamCount;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ copy constructor\n\/\/------------------------------------------------------------------------------\nEndOptimize::EndOptimize(const EndOptimize& eo) :\n   GmatCommand         (eo)\n{\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ operator =\n\/\/------------------------------------------------------------------------------\nEndOptimize& EndOptimize::operator=(const EndOptimize& eo)\n{\n   if (this == &eo)\n      return *this;\n    \n   return *this;\n}\n    \n\n\/\/------------------------------------------------------------------------------\n\/\/ destructor\n\/\/------------------------------------------------------------------------------\nEndOptimize::~EndOptimize()\n{\n   \/\/ nothing to do here at the moment ...... la de da de da\n}\n    \n\/\/------------------------------------------------------------------------------\n\/\/ Initialize\n\/\/------------------------------------------------------------------------------\nbool EndOptimize::Initialize()\n{\n   GmatCommand::Initialize();\n   \n   \/\/ Validate that next points to the owning Optimize command\n   if (!next)\n      throw CommandException(\"EndOptimize Command not properly reconnected\");\n    \n   if (next->GetTypeName() != \"Optimize\")\n      throw CommandException(\"EndOptimize Command not connected to Optimize Command\");\n    \n   return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Execute\n\/\/------------------------------------------------------------------------------\nbool EndOptimize::Execute()\n{\n   #ifdef DEBUG_OPTIMIZER_COMMANDS\n      if (next)\n         MessageInterface::ShowMessage(\n            \"End Optimize points to a %s command\\n\", next->GetTypeName().c_str());\n      else\n         MessageInterface::ShowMessage(\n            \"EndOptimize does not reconnect to Optimize comamnd\\n\");\n   #endif\n   \n   BuildCommandSummary(true);\n   return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Insert\n\/\/------------------------------------------------------------------------------\nbool EndOptimize::Insert(GmatCommand *cmd, GmatCommand *prev)\n{\n   \/\/ if inserting after End statement for branch command, we want to \n   \/\/ insert right after the entire Optimize command\n   if (this == prev)\n      return ((BranchCommand*)next)->InsertRightAfter(cmd);\n   return false;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Clone\n\/\/------------------------------------------------------------------------------\nGmatBase* EndOptimize::Clone() const\n{\n   return (new EndOptimize(*this));\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ GetGeneratingString\n\/\/------------------------------------------------------------------------------\nconst std::string& EndOptimize::GetGeneratingString(Gmat::WriteMode mode,\n                                                    const std::string &prefix,\n                                                    const std::string &useName)\n{\n   generatingString = prefix + \"EndOptimize;\";\n   if (mode == Gmat::NO_COMMENTS)\n   {\n\t  InsertCommandName(generatingString);\n      return generatingString;\n   }\n   \n   if ((next) && (next->GetTypeName() == \"Optimize\"))\n   {\n      if (showInlineComment)\n      {\n         \/\/ To avoid keep appending, check for empty inline comment\n         if (GetInlineComment() == \"\")\n         {\n            generatingString += \"  % For optimizer \";\n            generatingString += next->GetRefObjectName(Gmat::SOLVER);\n         }\n      }\n   }\n   return GmatCommand::GetGeneratingString(mode, prefix, useName);\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ bool RenameRefObject()\n\/\/------------------------------------------------------------------------------\n\/**\n * @see GmatBase\n *\/\n\/\/------------------------------------------------------------------------------\nbool EndOptimize::RenameRefObject(const UnsignedInt type,\n                                  const std::string &oldName,\n                                  const std::string &newName)\n{\n   \/\/ There are no renamealbe objects\n   return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ protected methods\n\/\/------------------------------------------------------------------------------\n\/\/ none at this time\n\n","avg_line_length":35.0203045685,"max_line_length":86,"alphanum_fraction":0.4268734599,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4643,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["PostgreSQL","Apache-2.0"],"max_stars_count":null,"content":"\/\/---------------------------------------------------------------------------\n\/\/\tGreenplum Database\n\/\/\tCopyright (C) 2012 EMC Corp.\n\/\/\n\/\/\t@filename:\n\/\/\t\tCParseHandlerWindowKey.cpp\n\/\/\n\/\/\t@doc:\n\/\/\t\tImplementation of the SAX parse handler class for parsing the window key\n\/\/---------------------------------------------------------------------------\n\n#include \"naucrates\/dxl\/parser\/CParseHandlerWindowKey.h\"\n#include \"naucrates\/dxl\/parser\/CParseHandlerScalarOp.h\"\n#include \"naucrates\/dxl\/parser\/CParseHandlerWindowFrame.h\"\n#include \"naucrates\/dxl\/parser\/CParseHandlerSortColList.h\"\n#include \"naucrates\/dxl\/operators\/CDXLOperatorFactory.h\"\n#include \"naucrates\/dxl\/parser\/CParseHandlerFactory.h\"\n\nusing namespace gpdxl;\n\nXERCES_CPP_NAMESPACE_USE\n\n\/\/---------------------------------------------------------------------------\n\/\/\t@function:\n\/\/\t\tCParseHandlerWindowKey::CParseHandlerWindowKey\n\/\/\n\/\/\t@doc:\n\/\/\t\tCtor\n\/\/\n\/\/---------------------------------------------------------------------------\nCParseHandlerWindowKey::CParseHandlerWindowKey\n\t(\n\tIMemoryPool *mp,\n\tCParseHandlerManager *parse_handler_mgr,\n\tCParseHandlerBase *parse_handler_root\n\t)\n\t:\n\tCParseHandlerBase(mp, parse_handler_mgr, parse_handler_root),\n\tm_dxl_window_key_gen(NULL)\n{\n}\n\n\/\/---------------------------------------------------------------------------\n\/\/\t@function:\n\/\/\t\tCParseHandlerWindowKey::StartElement\n\/\/\n\/\/\t@doc:\n\/\/\t\tInvoked by Xerces to process an opening tag\n\/\/\n\/\/---------------------------------------------------------------------------\nvoid\nCParseHandlerWindowKey::StartElement\n\t(\n\tconst XMLCh* const element_uri,\n\tconst XMLCh* const element_local_name,\n\tconst XMLCh* const element_qname,\n\tconst Attributes& attrs\n\t)\n{\n\tif (0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenWindowKey), element_local_name))\n\t{\n\t\tGPOS_ASSERT(NULL == m_dxl_window_key_gen);\n\t\tm_dxl_window_key_gen = GPOS_NEW(m_mp) CDXLWindowKey(m_mp);\n\n\t\t\/\/ parse handler for the sorting column list\n\t\tCParseHandlerBase *sort_col_list_parse_handler =\n\t\t\t\tCParseHandlerFactory::GetParseHandler(m_mp, CDXLTokens::XmlstrToken(EdxltokenScalarSortColList), m_parse_handler_mgr, this);\n\t\tm_parse_handler_mgr->ActivateParseHandler(sort_col_list_parse_handler);\n\n\t\t\/\/ store parse handler\n\t\tthis->Append(sort_col_list_parse_handler);\n\t}\n\telse if (0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenWindowFrame), element_local_name))\n\t{\n\t\tGPOS_ASSERT(1 == this->Length());\n\n\t\t\/\/ parse handler for the leading and trailing scalar values\n\t\tCParseHandlerBase *window_frame_parse_handler_base =\n\t\t\t\tCParseHandlerFactory::GetParseHandler(m_mp, CDXLTokens::XmlstrToken(EdxltokenWindowFrame), m_parse_handler_mgr, this);\n\t\tm_parse_handler_mgr->ActivateParseHandler(window_frame_parse_handler_base);\n\n\t\t\/\/ store parse handler\n\t\tthis->Append(window_frame_parse_handler_base);\n\t\twindow_frame_parse_handler_base->startElement(element_uri, element_local_name, element_qname, attrs);\n\t}\n\telse\n\t{\n\t\t\tCWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray(m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name);\n\t\t\tGPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, str->GetBuffer());\n\t}\n}\n\n\/\/---------------------------------------------------------------------------\n\/\/\t@function:\n\/\/\t\tCParseHandlerWindowKey::EndElement\n\/\/\n\/\/\t@doc:\n\/\/\t\tInvoked by Xerces to process a closing tag\n\/\/\n\/\/---------------------------------------------------------------------------\nvoid\nCParseHandlerWindowKey::EndElement\n\t(\n\tconst XMLCh* const, \/\/ element_uri,\n\tconst XMLCh* const element_local_name,\n\tconst XMLCh* const \/\/ element_qname\n\t)\n{\n\tif (0 != XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenWindowKey), element_local_name))\n\t{\n\t\tCWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray(m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name);\n\t\tGPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, str->GetBuffer());\n\t}\n\tGPOS_ASSERT(NULL != m_dxl_window_key_gen);\n\tGPOS_ASSERT(1 <= this->Length());\n\n\tCParseHandlerSortColList *sort_col_list_parse_handler = dynamic_cast<CParseHandlerSortColList *>((*this)[0]);\n\tCDXLNode *sort_col_list_dxlnode = sort_col_list_parse_handler->CreateDXLNode();\n\tsort_col_list_dxlnode->AddRef();\n\tm_dxl_window_key_gen->SetSortColList(sort_col_list_dxlnode);\n\n\tif (2 == this->Length())\n\t{\n\t\tCParseHandlerWindowFrame *window_frame_parse_handler_base = dynamic_cast<CParseHandlerWindowFrame *>((*this)[1]);\n\t\tCDXLWindowFrame *window_frame = window_frame_parse_handler_base->GetWindowFrame();\n\t\tm_dxl_window_key_gen->SetWindowFrame(window_frame);\n\t}\n\n\t\/\/ deactivate handler\n\tm_parse_handler_mgr->DeactivateHandler();\n}\n\n\/\/ EOF\n","avg_line_length":34.6492537313,"max_line_length":135,"alphanum_fraction":0.684902003,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2193,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":86.0,"content":"\/*\r\n\r\nCHELLO.CPP - A Class for Hello\r\n\r\nThis class, which is derived from the Logic Server class,\r\nCLogicServer, calls the compiled Prolog file, HELLO.XPL and\r\nqueries its only predicate, hello\/2.  The arguments are:\r\n\r\n\t1- A string with the callers name, and\r\n\t2- A returned string with a greeting.\r\n\r\nTo use it you need HELLO.XPL which is the compiled\r\nversion of HELLO.PRO.  It is already in the \\AMZI directory,\r\nso, assuming \\AMZI is on your path, the program will find\r\nit without problem.\r\n\r\nIf you do have load errors on HELLO.XPL, check the path and\r\nmake sure HELLO.XPL is somewhere on it.\r\n\r\n*\/\r\n\r\n#include \"chello.h\"\r\n#include \"stdio.h\"\r\n#include <string>\r\n#ifdef _CONSOLE\r\n#include <iostream>\r\n#include <cstdio>\r\n#endif\r\n\r\nusing namespace std;\r\n\r\nTF CHello::init()\r\n{\r\n\ttry\r\n\t{\r\n\t\t\/\/ Initialize the Logic Server engine\r\n\t\tls.Init(\"\");\r\n\t\tmsg_out(\"Logic Server initialized\");\r\n\r\n\t\t\/\/ Load the compiled Prolog program, hello.xpl\r\n\t\tls.Load(\"hello\");\r\n\t\tmsg_out(\"HELLO.XPL loaded\");\r\n\t\treturn TRUE;\r\n\t}\r\n\tcatch(LS_EXCEPTION)\r\n\t{\r\n\t\terror(E);\r\n\t\treturn FALSE;\r\n\t}\r\n}\r\n\r\nCHello::~CHello()\r\n{\r\n\t\/\/ Close the Logic Server engine\r\n\r\n\ttry { ls.Close(); }\r\n\tcatch(LS_EXCEPTION) { error(E); }\r\n\r\n\tmsg_out(\"Logic Server successfully closed\");\r\n}\r\n\r\nvoid CHello::run()\r\n{\r\n\tTERM   t;\r\n\tstring   buf;\r\n\r\n\ttry\r\n\t{\r\n\t\t\/\/ Build a query term and call it\r\n\t\tt = ls.ExecStr(\"hello($Windows C++ Programmer$, X)\");\r\n\r\n\t\t\/\/ If the query succeeded print up the results\r\n\t\tif (t != 0)\r\n\t\t{\r\n\t\t\tbuf = ls.TermToStr(t);\r\n\t\t   \/\/buf = ls.GetStrArg(t, 2);\r\n\t\t\tmsg_out(buf);\r\n\t\t}\r\n\t\telse\r\n\t\t\tmsg_out(\"Hello failed\");\r\n\t}\r\n\tcatch(LS_EXCEPTION) { error(E); }\r\n}\r\n\r\nvoid CHello::error(LS_EXCEPTION)\r\n{\r\n\tstring buf;\r\n\tstring msg;\r\n   char num[100];\r\n   int  rc;\r\n\r\n\t\/\/ Get Logic Server error number and message\r\n#ifdef GNU\r\n   rc = E->GetRC();\r\n\tmsg = E->GetMsg();\r\n#else\r\n   rc = E.GetRC();\r\n\tmsg = E.GetMsg();\r\n#endif\r\n\r\n   sprintf(num, \"%d\", rc);\r\n\tbuf = \"Logic Server Exception: \" + string(num) + \"\\n\" + msg;\r\n\tmsg_out(buf);\r\n}\r\n\r\nvoid CHello::msg_out(string msg)\r\n{\r\n#ifdef _CONSOLE\r\n\tcout << msg << '\\n';\r\n\t\/\/printf(\"%s\\n\", msg);\r\n#else\r\n   MessageBox(NULL, msg.c_str(), \"Hello Message\", MB_OK);\r\n#endif\r\n}\r\n","avg_line_length":19.0695652174,"max_line_length":62,"alphanum_fraction":0.6251709986,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6882,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\r\n * NavRendererAxial.cpp\r\n *\r\n * Created on: 09.05.2012\r\n * @author Ralph Schurade\r\n *\/\r\n#include \"navrendereraxial.h\"\r\n#include \"glfunctions.h\"\r\n#include \"..\/..\/data\/enums.h\"\r\n\r\n#include <QDebug>\r\n#include <QtOpenGL\/QGLShaderProgram>\r\n#include <QVector3D>\r\n#include <QMatrix4x4>\r\n\r\nNavRendererAxial::NavRendererAxial( QString name ) :\r\n    NavRenderer( name )\r\n{\r\n}\r\n\r\nNavRendererAxial::~NavRendererAxial()\r\n{\r\n    glDeleteBuffers( 4, vboIds );\r\n    delete[] vboIds;\r\n}\r\n\r\nvoid NavRendererAxial::adjustRatios()\r\n{\r\n    glViewport( 0, 0, m_width, m_height );\r\n\r\n    m_ratio = static_cast< float >( m_width ) \/ static_cast< float >( m_height );\r\n\r\n    \/\/ Reset projection\r\n    QMatrix4x4 pMatrix;\r\n    pMatrix.setToIdentity();\r\n\r\n    int boundingbox = qMax ( m_nx * m_dx, qMax( m_ny * m_dy, m_nz * m_dz ) );\r\n\r\n    pMatrix.ortho( 0, boundingbox, 0, boundingbox, -3000, 3000 );\r\n\r\n    pMatrix.translate( static_cast<float>( m_moveX ) \/ ( static_cast<float>( m_width ) \/ boundingbox ),\r\n                       static_cast<float>( m_moveY ) \/ ( static_cast<float>( m_height ) \/ boundingbox ), 0 );\r\n\r\n    pMatrix.translate( boundingbox \/ 2, boundingbox \/ 2, 0 );\r\n\r\n    pMatrix.scale( m_zoom );\r\n\r\n    if ( m_ratio >= 1.0 )\r\n    {\r\n        pMatrix.scale( 1.0 \/ m_ratio, 1.0, 1.0 );\r\n    }\r\n    else\r\n    {\r\n        pMatrix.scale( 1.0, m_ratio, 1.0 );\r\n    }\r\n\r\n    pMatrix.translate( m_nx * m_dx \/ -2, m_ny * m_dy \/ -2, 0 );\r\n    m_mvpMatrix = pMatrix;\r\n}\r\n\r\nvoid NavRendererAxial::leftMouseDown( int x, int y )\r\n{\r\n    float xf = static_cast<float>( x );\r\n    float yf = static_cast<float>( m_height - y );\r\n\r\n    QVector4D test;\r\n    test.setX( ( 2 * xf ) \/ m_width - 1 );\r\n    test.setY( ( 2 * yf ) \/ m_height - 1 );\r\n    test.setZ( 1 );\r\n    test.setW( 1 );\r\n\r\n    QVector4D out = m_mvpMatrix.inverted() * test;\r\n\r\n    int xout = out.x() \/ m_dx;\r\n    int yout = out.y() \/ m_dy;\r\n\r\n    xout = qMax( 0, qMin( xout, static_cast<int>( m_nx - 1.0 ) ) );\r\n    yout = qMax( 0, qMin( yout, static_cast<int>( m_ny - 1.0 ) ) );\r\n\r\n    QModelIndex mi;\r\n    QPoint p( xout, yout );\r\n    mi = model()->index( (int)Fn::Global::SAGITTAL_CORONAL, 0 );\r\n    if ( mi.isValid() )\r\n    {\r\n        model()->setData( mi, p );\r\n        model()->submit();\r\n    }\r\n}\r\n\r\nvoid NavRendererAxial::initGeometry()\r\n{\r\n    m_x = model()->data( model()->index( (int)Fn::Global::SAGITTAL, 0 ) ).toInt();\r\n    m_y = model()->data( model()->index( (int)Fn::Global::CORONAL, 0 ) ).toInt();\r\n    m_z = model()->data( model()->index( (int)Fn::Global::AXIAL, 0 ) ).toInt();\r\n\r\n    if ( m_xOld != m_x || m_yOld != m_y || m_zOld != m_z )\r\n    {\r\n        m_nx = model()->data( model()->index( (int)Fn::Global::MAX_SAGITTAL, 0 ) ).toInt();\r\n        m_ny = model()->data( model()->index( (int)Fn::Global::MAX_CORONAL, 0 ) ).toInt();\r\n        m_nz = model()->data( model()->index( (int)Fn::Global::MAX_AXIAL, 0 ) ).toInt();\r\n\r\n        m_dx = model()->data( model()->index( (int)Fn::Global::SLICE_DX, 0 ) ).toFloat();\r\n        m_dy = model()->data( model()->index( (int)Fn::Global::SLICE_DY, 0 ) ).toFloat();\r\n        m_dz = model()->data( model()->index( (int)Fn::Global::SLICE_DZ, 0 ) ).toFloat();\r\n\r\n        float x = m_x * m_dx + m_dx \/ 2.0;\r\n        float y = m_y * m_dy + m_dy \/ 2.0;\r\n        float z = m_z * m_dz + m_dz \/ 2.0;\r\n        float xb = m_nx * m_dx;\r\n        float yb = m_ny * m_dy;\r\n        \/\/float zb = m_nz * m_dz;\r\n\r\n        VertexData vertices[] =\r\n        {\r\n            { QVector3D( 0.0, 0.0, z ), QVector3D( 0.0, 0.0, ( m_z ) \/ ( m_nz - 1 ) ) },\r\n            { QVector3D( xb,  0.0, z ), QVector3D( 1.0, 0.0, ( m_z ) \/ ( m_nz - 1 ) ) },\r\n            { QVector3D( xb,  yb,  z ), QVector3D( 1.0, 1.0, ( m_z ) \/ ( m_nz - 1 ) ) },\r\n            { QVector3D( 0.0, yb,  z ), QVector3D( 0.0, 1.0, ( m_z ) \/ ( m_nz - 1 ) ) }\r\n        };\r\n\r\n        VertexData verticesCrosshair[] =\r\n        {\r\n            { QVector3D( x,   0.0, z + 1.0 ), QVector3D( 0.0, 0.0, 0.0 ) },\r\n            { QVector3D( x,   yb,  z + 1.0 ), QVector3D( 0.0, 0.0, 0.0 ) },\r\n            { QVector3D( 0.0, y,   z + 1.0 ), QVector3D( 0.0, 0.0, 0.0 ) },\r\n            { QVector3D( xb,  y,   z + 1.0 ), QVector3D( 0.0, 0.0, 0.0 ) }\r\n        };\r\n\r\n        \/\/ Transfer vertex data to VBO 1\r\n        glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );\r\n        glBufferData( GL_ARRAY_BUFFER, 4 * sizeof(VertexData), vertices, GL_STATIC_DRAW );\r\n\r\n        \/\/ Transfer vertex data to VBO 2\r\n        glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 2 ] );\r\n        glBufferData( GL_ARRAY_BUFFER, 4 * sizeof(VertexData), verticesCrosshair, GL_STATIC_DRAW );\r\n\r\n        m_xOld = m_x;\r\n        m_yOld = m_y;\r\n        m_zOld = m_z;\r\n    }\r\n}\r\n\r\nvoid NavRendererAxial::draw()\r\n{\r\n    QColor color = model()->data( model()->index( (int)Fn::Global::BACKGROUND_COLOR_NAV1, 0 ) ).value<QColor>();\r\n    glClearColor( color.redF(), color.greenF(), color.blueF(), 1.0 );\r\n\r\n    \/\/qDebug() << \"nav draw\";\r\n    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\r\n\r\n    setupTextures();\r\n\r\n    adjustRatios();\r\n\r\n    GLFunctions::getShader( \"slice\" )->bind();\r\n    \/\/ Set modelview-projection matrix\r\n    GLFunctions::getShader( \"slice\" )->setUniformValue( \"mvp_matrix\", m_mvpMatrix );\r\n    GLFunctions::getShader( \"slice\" )->setUniformValue( \"u_renderMode\", 0 );\r\n\r\n    initGeometry();\r\n\r\n    \/\/ Tell OpenGL which VBOs to use\r\n    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );\r\n    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );\r\n    setShaderVars();\r\n    \/\/ Draw cube geometry using indices from VBO 0\r\n    glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0 );\r\n\r\n    bool renderCrosshirs = model()->data( model()->index( (int)Fn::Global::RENDER_CROSSHAIRS, 0 ) ).toBool();\r\n\r\n    if ( renderCrosshirs )\r\n    {\r\n        GLFunctions::getShader( \"crosshair\" )->bind();\r\n        GLFunctions::getShader( \"crosshair\" )->setUniformValue( \"mvp_matrix\", m_mvpMatrix );\r\n        QColor ccolor = model()->data( model()->index( (int)Fn::Global::CROSSHAIR_COLOR, 0 ) ).value<QColor>();\r\n        GLFunctions::getShader( \"crosshair\" )->setUniformValue( \"u_color\", ccolor.redF(), ccolor.greenF(), ccolor.blueF(), 1.0f );\r\n        \/\/ Tell OpenGL which VBOs to use\r\n        glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 3 ] );\r\n        glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 2 ] );\r\n\r\n        \/\/ Tell OpenGL programmable pipeline how to locate vertex position data\r\n        int vertexLocation = GLFunctions::getShader( \"crosshair\" )->attributeLocation( \"a_position\" );\r\n        GLFunctions::getShader( \"crosshair\" )->enableAttributeArray( vertexLocation );\r\n        glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof( VertexData ), 0 );\r\n        \/\/ Draw cube geometry using indices from VBO 0\r\n        glDrawElements( GL_LINES, 4, GL_UNSIGNED_SHORT, 0 );\r\n        glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );\r\n        glBindBuffer( GL_ARRAY_BUFFER, 0 );\r\n    }\r\n}\r\n","avg_line_length":36.0314136126,"max_line_length":131,"alphanum_fraction":0.5712002325,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":517,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\r\n\r\n\r\n#include <boost\/lambda\/lambda.hpp>\r\n#include <boost\/lambda\/bind.hpp>\r\n#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n\r\nstruct Test {\r\n\tTest(int i) : integer_(i) {}\r\n\tint integer_;\r\n};\r\n\r\nvoid print(const Test& test) {\r\n\tstd::cout << test.integer_ << std::endl;\r\n}\r\n\r\n\r\nint main() {\r\n\tusing namespace boost::lambda;\r\n\r\n\tstd::vector<Test> container;\r\n\r\n\tfor (int i = 0; i < 10; ++i) {\r\n\t\tcontainer.push_back(i);\r\n\t}\r\n\r\n\tstd::for_each(container.begin(), container.end(), bind(print, _1));\r\n}\r\n\r\n\r\n","avg_line_length":15.2058823529,"max_line_length":69,"alphanum_fraction":0.6092843327,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":46185,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include \"storagehandler.hpp\"\n\n#include \"fruread.hpp\"\n#include \"read_fru_data.hpp\"\n#include \"selutility.hpp\"\n#include \"sensorhandler.hpp\"\n#include \"storageaddsel.hpp\"\n\n#include <arpa\/inet.h>\n#include <mapper.h>\n#include <systemd\/sd-bus.h>\n\n#include <algorithm>\n#include <boost\/beast\/core\/span.hpp>\n#include <boost\/process.hpp>\n#include <chrono>\n#include <cstdio>\n#include <cstring>\n#include <filesystem>\n#include <ipmid\/api.hpp>\n#include <ipmid\/utils.hpp>\n#include <phosphor-logging\/elog-errors.hpp>\n#include <phosphor-logging\/log.hpp>\n#include <sdbusplus\/server.hpp>\n#include <sdrutils.hpp>\n#include <string>\n#include <string_view>\n#include <variant>\n#include <xyz\/openbmc_project\/Common\/error.hpp>\n\nvoid register_netfn_storage_functions() __attribute__((constructor));\n\nunsigned int g_sel_time = 0xFFFFFFFF;\nnamespace ipmi\n{\nnamespace sensor\n{\nextern const IdInfoMap sensors;\n} \/\/ namespace sensor\n} \/\/ namespace ipmi\n\nextern const FruMap frus;\nconstexpr uint8_t eventDataSize = 3;\nnamespace\n{\nconstexpr auto TIME_INTERFACE = \"xyz.openbmc_project.Time.EpochTime\";\nconstexpr auto BMC_TIME_PATH = \"\/xyz\/openbmc_project\/time\/bmc\";\nconstexpr auto DBUS_PROPERTIES = \"org.freedesktop.DBus.Properties\";\nconstexpr auto PROPERTY_ELAPSED = \"Elapsed\";\n\n} \/\/ namespace\n\n\n#ifndef JOURNAL_SEL\nnamespace cache\n{\n\/*\n * This cache contains the object paths of the logging entries sorted in the\n * order of the filename(numeric order). The cache is initialized by\n * invoking readLoggingObjectPaths with the cache as the parameter. The\n * cache is invoked in the execution of the Get SEL info and Delete SEL\n * entry command. The Get SEL Info command is typically invoked before the\n * Get SEL entry command, so the cache is utilized for responding to Get SEL\n * entry command. The cache is invalidated by clearing after Delete SEL\n * entry and Clear SEL command.\n *\/\nipmi::sel::ObjectPaths paths;\n\n} \/\/ namespace cache\n#endif\n\nusing InternalFailure =\n    sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;\nusing namespace phosphor::logging;\nusing namespace ipmi::fru;\n\n\/**\n * @enum Device access mode\n *\/\nenum class AccessMode\n{\n    bytes, \/\/\/< Device is accessed by bytes\n    words  \/\/\/< Device is accessed by words\n};\n\n#ifdef JOURNAL_SEL\nnamespace ipmi::sel::erase_time\n{\nstatic constexpr const char* selEraseTimestamp = \"\/var\/lib\/ipmi\/sel_erase_time\";\n\nvoid save()\n{\n    \/\/ open the file, creating it if necessary\n    int fd = open(selEraseTimestamp, O_WRONLY | O_CREAT | O_CLOEXEC, 0644);\n    if (fd < 0)\n    {\n        std::cerr << \"Failed to open file\\n\";\n        return;\n    }\n\n    \/\/ update the file timestamp to the current time\n    if (futimens(fd, NULL) < 0)\n    {\n        std::cerr << \"Failed to update timestamp: \"\n                  << std::string(strerror(errno));\n    }\n    close(fd);\n}\n\nint get()\n{\n    struct stat st;\n    \/\/ default to an invalid timestamp\n    int timestamp = ::ipmi::sel::invalidTimeStamp;\n\n    int fd = open(selEraseTimestamp, O_RDWR | O_CLOEXEC, 0644);\n    if (fd < 0)\n    {\n        return timestamp;\n    }\n\n    if (fstat(fd, &st) >= 0)\n    {\n        timestamp = st.st_mtime;\n    }\n\n    return timestamp;\n}\n} \/\/ namespace ipmi::sel::erase_time\n\nstatic int fromHexStr(const std::string hexStr, std::vector<uint8_t>& data)\n{\n    for (unsigned int i = 0; i < hexStr.size(); i += 2)\n    {\n        try\n        {\n            data.push_back(static_cast<uint8_t>(\n                std::stoul(hexStr.substr(i, 2), nullptr, 16)));\n        }\n        catch (std::invalid_argument& e)\n        {\n            phosphor::logging::log<phosphor::logging::level::ERR>(e.what());\n            return -1;\n        }\n        catch (std::out_of_range& e)\n        {\n            phosphor::logging::log<phosphor::logging::level::ERR>(e.what());\n            return -1;\n        }\n    }\n    return 0;\n}\n\nstatic const std::filesystem::path selLogDir = \"\/var\/log\";\nstatic const std::string selLogFilename = \"ipmi_sel\";\n\nstatic bool getSELLogFiles(std::vector<std::filesystem::path>& selLogFiles)\n{\n    \/\/ Loop through the directory looking for ipmi_sel log files\n    for (const std::filesystem::directory_entry& dirEnt :\n         std::filesystem::directory_iterator(selLogDir))\n    {\n        std::string filename = dirEnt.path().filename();\n        if (boost::starts_with(filename, selLogFilename))\n        {\n            \/\/ If we find an ipmi_sel log file, save the path\n            selLogFiles.emplace_back(selLogDir \/\n                                     filename);\n        }\n    }\n    \/\/ As the log files rotate, they are appended with a \".#\" that is higher for\n    \/\/ the older logs. Since we don't expect more than 10 log files, we\n    \/\/ can just sort the list to get them in order from newest to oldest\n    std::sort(selLogFiles.begin(), selLogFiles.end());\n\n    return !selLogFiles.empty();\n}\n\nstatic int countSELEntries()\n{\n    \/\/ Get the list of ipmi_sel log files\n    std::vector<std::filesystem::path> selLogFiles;\n    if (!getSELLogFiles(selLogFiles))\n    {\n        return 0;\n    }\n    int numSELEntries = 0;\n    \/\/ Loop through each log file and count the number of logs\n    for (const std::filesystem::path& file : selLogFiles)\n    {\n        std::ifstream logStream(file);\n        if (!logStream.is_open())\n        {\n            continue;\n        }\n\n        std::string line;\n        while (std::getline(logStream, line))\n        {\n            numSELEntries++;\n        }\n    }\n    return numSELEntries;\n}\n\nstatic bool findSELEntry(const int recordID,\n                         const std::vector<std::filesystem::path>& selLogFiles,\n                         std::string& entry)\n{\n    \/\/ Record ID is the first entry field following the timestamp. It is\n    \/\/ preceded by a space and followed by a comma\n    std::string search = \" \" + std::to_string(recordID) + \",\";\n\n    \/\/ Loop through the ipmi_sel log entries\n    for (const std::filesystem::path& file : selLogFiles)\n    {\n        std::ifstream logStream(file);\n        if (!logStream.is_open())\n        {\n            continue;\n        }\n\n        while (std::getline(logStream, entry))\n        {\n            \/\/ Check if the record ID matches\n            if (entry.find(search) != std::string::npos)\n            {\n                return true;\n            }\n        }\n    }\n    return false;\n}\n\nstatic uint16_t\n    getNextRecordID(const uint16_t recordID,\n                    const std::vector<std::filesystem::path>& selLogFiles)\n{\n    uint16_t nextRecordID = recordID + 1;\n    std::string entry;\n    if (findSELEntry(nextRecordID, selLogFiles, entry))\n    {\n        return nextRecordID;\n    }\n    else\n    {\n        return ipmi::sel::lastEntry;\n    }\n}\n\nstatic int getFileTimestamp(const std::filesystem::path& file)\n{\n    struct stat st;\n\n    if (stat(file.c_str(), &st) >= 0)\n    {\n        return st.st_mtime;\n    }\n    return ::ipmi::sel::invalidTimeStamp;\n}\n\nusing systemEventType = std::tuple<\n    uint32_t, \/\/ Timestamp\n    uint16_t, \/\/ Generator ID\n    uint8_t,  \/\/ EvM Rev\n    uint8_t,  \/\/ Sensor Type\n    uint8_t,  \/\/ Sensor Number\n    uint7_t,  \/\/ Event Type\n    bool,     \/\/ Event Direction\n    std::array<uint8_t, ipmi::sel::systemEventSize>>; \/\/ Event Data\nusing oemTsEventType = std::tuple<\n    uint32_t,                                                   \/\/ Timestamp\n    std::array<uint8_t, ipmi::sel::oemTsEventSize>>; \/\/ Event Data\nusing oemEventType =\n    std::array<uint8_t, ipmi::sel::oemEventSize>; \/\/ Event Data\n\nipmi::RspType<uint16_t, \/\/ Next Record ID\n              uint16_t, \/\/ Record ID\n              uint8_t,  \/\/ Record Type\n              std::variant<systemEventType, oemTsEventType,\n                           oemEventType>> \/\/ Record Content\n    ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID,\n                           uint8_t offset, uint8_t size)\n{\n    \/\/ Only support getting the entire SEL record. If a partial size or non-zero\n    \/\/ offset is requested, return an error\n    if (offset != 0 || size != ipmi::sel::entireRecord)\n    {\n        return ipmi::responseRetBytesUnavailable();\n    }\n\n    \/\/ Check the reservation ID if one is provided or required (only if the\n    \/\/ offset is non-zero)\n    if (reservationID != 0 || offset != 0)\n    {\n        if (!checkSELReservation(reservationID))\n        {\n            return ipmi::responseInvalidReservationId();\n        }\n    }\n\n    \/\/ Get the ipmi_sel log files\n    std::vector<std::filesystem::path> selLogFiles;\n    if (!getSELLogFiles(selLogFiles))\n    {\n        return ipmi::responseSensorInvalid();\n    }\n\n    std::string targetEntry;\n\n    if (targetID == ipmi::sel::firstEntry)\n    {\n        \/\/ The first entry will be at the top of the oldest log file\n        std::ifstream logStream(selLogFiles.back());\n        if (!logStream.is_open())\n        {\n            return ipmi::responseUnspecifiedError();\n        }\n\n        if (!std::getline(logStream, targetEntry))\n        {\n            return ipmi::responseUnspecifiedError();\n        }\n    }\n    else if (targetID == ipmi::sel::lastEntry)\n    {\n        \/\/ The last entry will be at the bottom of the newest log file\n        std::ifstream logStream(selLogFiles.front());\n        if (!logStream.is_open())\n        {\n            return ipmi::responseUnspecifiedError();\n        }\n\n        std::string line;\n        while (std::getline(logStream, line))\n        {\n            targetEntry = line;\n        }\n    }\n    else\n    {\n        if (!findSELEntry(targetID, selLogFiles, targetEntry))\n        {\n            return ipmi::responseSensorInvalid();\n        }\n    }\n\n    \/\/ The format of the ipmi_sel message is \"<Timestamp>\n    \/\/ <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]\".\n    \/\/ First get the Timestamp\n    size_t space = targetEntry.find_first_of(\" \");\n    if (space == std::string::npos)\n    {\n        return ipmi::responseUnspecifiedError();\n    }\n    std::string entryTimestamp = targetEntry.substr(0, space);\n    \/\/ Then get the log contents\n    size_t entryStart = targetEntry.find_first_not_of(\" \", space);\n    if (entryStart == std::string::npos)\n    {\n        return ipmi::responseUnspecifiedError();\n    }\n    std::string_view entry(targetEntry);\n    entry.remove_prefix(entryStart);\n    \/\/ Use split to separate the entry into its fields\n    std::vector<std::string> targetEntryFields;\n    boost::split(targetEntryFields, entry, boost::is_any_of(\",\"),\n                 boost::token_compress_on);\n    if (targetEntryFields.size() < 3)\n    {\n        return ipmi::responseUnspecifiedError();\n    }\n    std::string& recordIDStr = targetEntryFields[0];\n    std::string& recordTypeStr = targetEntryFields[1];\n    std::string& eventDataStr = targetEntryFields[2];\n\n    uint16_t recordID;\n    uint8_t recordType;\n    try\n    {\n        recordID = std::stoul(recordIDStr);\n        recordType = std::stoul(recordTypeStr, nullptr, 16);\n    }\n    catch (const std::invalid_argument&)\n    {\n        return ipmi::responseUnspecifiedError();\n    }\n    uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles);\n    std::vector<uint8_t> eventDataBytes;\n    if (fromHexStr(eventDataStr, eventDataBytes) < 0)\n    {\n        return ipmi::responseUnspecifiedError();\n    }\n\n    if (recordType == ipmi::sel::systemEvent)\n    {\n        \/\/ Get the timestamp\n        std::tm timeStruct = {};\n        std::istringstream entryStream(entryTimestamp);\n\n        uint32_t timestamp = ipmi::sel::invalidTimeStamp;\n        if (entryStream >> std::get_time(&timeStruct, \"%Y-%m-%dT%H:%M:%S\"))\n        {\n            timestamp = std::mktime(&timeStruct);\n        }\n\n        \/\/ Set the event message revision\n        uint8_t evmRev = ipmi::sel::eventMsgRev;\n\n        uint16_t generatorID = 0;\n        uint8_t sensorType = 0;\n        uint16_t sensorAndLun = 0;\n        uint8_t sensorNum = 0xFF;\n        uint7_t eventType = 0;\n        bool eventDir = 0;\n        \/\/ System type events should have six fields\n        if (targetEntryFields.size() >= 6)\n        {\n            std::string& generatorIDStr = targetEntryFields[3];\n            std::string& sensorPath = targetEntryFields[4];\n            std::string& eventDirStr = targetEntryFields[5];\n\n            \/\/ Get the generator ID\n            try\n            {\n                generatorID = std::stoul(generatorIDStr, nullptr, 16);\n            }\n            catch (const std::invalid_argument&)\n            {\n                std::cerr << \"Invalid Generator ID\\n\";\n            }\n\n            \/\/ Get the sensor type, sensor number, and event type for the sensor\n            sensorType = getSensorTypeFromPath(sensorPath);\n            sensorAndLun = getSensorNumberFromPath(sensorPath);\n            sensorNum = static_cast<uint8_t>(sensorAndLun);\n            generatorID |= sensorAndLun >> 8;\n            eventType = getSensorEventTypeFromPath(sensorPath);\n\n            \/\/ Get the event direction\n            try\n            {\n                eventDir = std::stoul(eventDirStr) ? 0 : 1;\n            }\n            catch (const std::invalid_argument&)\n            {\n                std::cerr << \"Invalid Event Direction\\n\";\n            }\n        }\n\n        \/\/ Only keep the eventData bytes that fit in the record\n        std::array<uint8_t, ipmi::sel::systemEventSize> eventData{};\n        std::copy_n(eventDataBytes.begin(),\n                    std::min(eventDataBytes.size(), eventData.size()),\n                    eventData.begin());\n\n        return ipmi::responseSuccess(\n            nextRecordID, recordID, recordType,\n            systemEventType{timestamp, generatorID, evmRev, sensorType,\n                            sensorNum, eventType, eventDir, eventData});\n    }\n    else if (recordType >= ipmi::sel::oemTsEventFirst &&\n             recordType <= ipmi::sel::oemTsEventLast)\n    {\n        \/\/ Get the timestamp\n        std::tm timeStruct = {};\n        std::istringstream entryStream(entryTimestamp);\n\n        uint32_t timestamp = ipmi::sel::invalidTimeStamp;\n        if (entryStream >> std::get_time(&timeStruct, \"%Y-%m-%dT%H:%M:%S\"))\n        {\n            timestamp = std::mktime(&timeStruct);\n        }\n\n        \/\/ Only keep the bytes that fit in the record\n        std::array<uint8_t, ipmi::sel::oemTsEventSize> eventData{};\n        std::copy_n(eventDataBytes.begin(),\n                    std::min(eventDataBytes.size(), eventData.size()),\n                    eventData.begin());\n\n        return ipmi::responseSuccess(nextRecordID, recordID, recordType,\n                                     oemTsEventType{timestamp, eventData});\n    }\n    else if (recordType >= ipmi::sel::oemEventFirst)\n    {\n        \/\/ Only keep the bytes that fit in the record\n        std::array<uint8_t, ipmi::sel::oemEventSize> eventData{};\n        std::copy_n(eventDataBytes.begin(),\n                    std::min(eventDataBytes.size(), eventData.size()),\n                    eventData.begin());\n\n        return ipmi::responseSuccess(nextRecordID, recordID, recordType,\n                                     eventData);\n    }\n\n    return ipmi::responseUnspecifiedError();\n}\n\n\nipmi::RspType<uint8_t> ipmiStorageClearSEL(ipmi::Context::ptr ctx,\n                                           uint16_t reservationID,\n                                           const std::array<uint8_t, 3>& clr,\n                                           uint8_t eraseOperation)\n{\n    if (!checkSELReservation(reservationID))\n    {\n        return ipmi::responseInvalidReservationId();\n    }\n\n    static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};\n    if (clr != clrExpected)\n    {\n        return ipmi::responseInvalidFieldRequest();\n    }\n\n    \/\/ Erasure status cannot be fetched, so always return erasure status as\n    \/\/ `erase completed`.\n    if (eraseOperation == ipmi::sel::getEraseStatus)\n    {\n        return ipmi::responseSuccess(ipmi::sel::eraseComplete);\n    }\n\n    \/\/ Check that initiate erase is correct\n    if (eraseOperation != ipmi::sel::initiateErase)\n    {\n        return ipmi::responseInvalidFieldRequest();\n    }\n\n    \/\/ Per the IPMI spec, need to cancel any reservation when the SEL is\n    \/\/ cleared\n    cancelSELReservation();\n\n    \/\/ Save the erase time\n    ipmi::sel::erase_time::save();\n\n    \/\/ Clear the SEL by deleting the log files\n    std::vector<std::filesystem::path> selLogFiles;\n    if (getSELLogFiles(selLogFiles))\n    {\n        for (const std::filesystem::path& file : selLogFiles)\n        {\n            std::error_code ec;\n            std::filesystem::remove(file, ec);\n        }\n    }\n\n    \/\/ Reload rsyslog so it knows to start new log files\n    std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();\n    sdbusplus::message::message rsyslogReload = dbus->new_method_call(\n        \"org.freedesktop.systemd1\", \"\/org\/freedesktop\/systemd1\",\n        \"org.freedesktop.systemd1.Manager\", \"ReloadUnit\");\n    rsyslogReload.append(\"rsyslog.service\", \"replace\");\n    try\n    {\n        sdbusplus::message::message reloadResponse = dbus->call(rsyslogReload);\n    }\n    catch (sdbusplus::exception_t& e)\n    {\n        phosphor::logging::log<phosphor::logging::level::ERR>(e.what());\n    }\n\n    return ipmi::responseSuccess(ipmi::sel::eraseComplete);\n}\n\n\n\nipmi::RspType<uint8_t,  \/\/ SEL version\n              uint16_t, \/\/ SEL entry count\n              uint16_t, \/\/ free space\n              uint32_t, \/\/ last add timestamp\n              uint32_t, \/\/ last erase timestamp\n              uint8_t>  \/\/ operation support\n    ipmiStorageGetSelInfo()\n{\n    constexpr uint8_t selVersion = ipmi::sel::selVersion;\n    uint16_t entries = countSELEntries();\n    uint32_t addTimeStamp = getFileTimestamp(\n        selLogDir \/ selLogFilename);\n    uint32_t eraseTimeStamp = ipmi::sel::erase_time::get();\n    constexpr uint8_t operationSupport =\n        ipmi::sel::selOperationSupport;\n    constexpr uint16_t freeSpace =\n        0xffff; \/\/ Spec indicates that more than 64kB is free\n\n    return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp,\n                                 eraseTimeStamp, operationSupport);\n}\n#else \/\/ JOURNAL_SEL not used\n\/** @brief implements the get SEL Info command\n *  @returns IPMI completion code plus response data\n *   - selVersion - SEL revision\n *   - entries    - Number of log entries in SEL.\n *   - freeSpace  - Free Space in bytes.\n *   - addTimeStamp - Most recent addition timestamp\n *   - eraseTimeStamp - Most recent erase timestamp\n *   - operationSupport - Reserve & Delete SEL operations supported\n *\/\n\nipmi::RspType<uint8_t,  \/\/ SEL revision.\n              uint16_t, \/\/ number of log entries in SEL.\n              uint16_t, \/\/ free Space in bytes.\n              uint32_t, \/\/ most recent addition timestamp\n              uint32_t, \/\/ most recent erase timestamp.\n\n              bool,    \/\/ SEL allocation info supported\n              bool,    \/\/ reserve SEL supported\n              bool,    \/\/ partial Add SEL Entry supported\n              bool,    \/\/ delete SEL supported\n              uint3_t, \/\/ reserved\n              bool     \/\/ overflow flag\n              >\n    ipmiStorageGetSelInfo()\n{\n    uint16_t entries = 0;\n    \/\/ Most recent addition timestamp.\n    uint32_t addTimeStamp = ipmi::sel::invalidTimeStamp;\n\n    try\n    {\n        ipmi::sel::readLoggingObjectPaths(cache::paths);\n    }\n    catch (const sdbusplus::exception::SdBusError& e)\n    {\n        \/\/ No action if reading log objects have failed for this command.\n        \/\/ readLoggingObjectPaths will throw exception if there are no log\n        \/\/ entries. The command will be responded with number of SEL entries\n        \/\/ as 0.\n    }\n\n    if (!cache::paths.empty())\n    {\n        entries = static_cast<uint16_t>(cache::paths.size());\n\n        try\n        {\n            addTimeStamp = static_cast<uint32_t>(\n                (ipmi::sel::getEntryTimeStamp(cache::paths.back()).count()));\n        }\n        catch (InternalFailure& e)\n        {\n        }\n        catch (const std::runtime_error& e)\n        {\n            log<level::ERR>(e.what());\n        }\n    }\n\n    constexpr uint8_t selVersion = ipmi::sel::selVersion;\n    constexpr uint16_t freeSpace = 0xFFFF;\n    constexpr uint32_t eraseTimeStamp = ipmi::sel::invalidTimeStamp;\n    constexpr uint3_t reserved{0};\n\n    return ipmi::responseSuccess(\n        selVersion, entries, freeSpace, addTimeStamp, eraseTimeStamp,\n        ipmi::sel::operationSupport::getSelAllocationInfo,\n        ipmi::sel::operationSupport::reserveSel,\n        ipmi::sel::operationSupport::partialAddSelEntry,\n        ipmi::sel::operationSupport::deleteSel, reserved,\n        ipmi::sel::operationSupport::overflow);\n}\n\nipmi_ret_t getSELEntry(ipmi_netfn_t netfn, ipmi_cmd_t cmd,\n                       ipmi_request_t request, ipmi_response_t response,\n                       ipmi_data_len_t data_len, ipmi_context_t context)\n{\n    if (*data_len != sizeof(ipmi::sel::GetSELEntryRequest))\n    {\n        *data_len = 0;\n        return IPMI_CC_REQ_DATA_LEN_INVALID;\n    }\n\n    auto requestData =\n        reinterpret_cast<const ipmi::sel::GetSELEntryRequest*>(request);\n\n    if (requestData->reservationID != 0)\n    {\n        if (!checkSELReservation(requestData->reservationID))\n        {\n            *data_len = 0;\n            return IPMI_CC_INVALID_RESERVATION_ID;\n        }\n    }\n\n    if (cache::paths.empty())\n    {\n        *data_len = 0;\n        return IPMI_CC_SENSOR_INVALID;\n    }\n\n    ipmi::sel::ObjectPaths::const_iterator iter;\n\n    \/\/ Check for the requested SEL Entry.\n    if (requestData->selRecordID == ipmi::sel::firstEntry)\n    {\n        iter = cache::paths.begin();\n    }\n    else if (requestData->selRecordID == ipmi::sel::lastEntry)\n    {\n        iter = cache::paths.end();\n    }\n    else\n    {\n        std::string objPath = std::string(ipmi::sel::logBasePath) + \"\/\" +\n                              std::to_string(requestData->selRecordID);\n\n        iter = std::find(cache::paths.begin(), cache::paths.end(), objPath);\n        if (iter == cache::paths.end())\n        {\n            *data_len = 0;\n            return IPMI_CC_SENSOR_INVALID;\n        }\n    }\n\n    ipmi::sel::GetSELEntryResponse record{};\n\n    \/\/ Convert the log entry into SEL record.\n    try\n    {\n        record = ipmi::sel::convertLogEntrytoSEL(*iter);\n    }\n    catch (InternalFailure& e)\n    {\n        *data_len = 0;\n        return IPMI_CC_UNSPECIFIED_ERROR;\n    }\n    catch (const std::runtime_error& e)\n    {\n        log<level::ERR>(e.what());\n        *data_len = 0;\n        return IPMI_CC_UNSPECIFIED_ERROR;\n    }\n\n    \/\/ Identify the next SEL record ID\n    if (iter != cache::paths.end())\n    {\n        ++iter;\n        if (iter == cache::paths.end())\n        {\n            record.nextRecordID = ipmi::sel::lastEntry;\n        }\n        else\n        {\n            namespace fs = std::filesystem;\n            fs::path path(*iter);\n            record.nextRecordID = static_cast<uint16_t>(\n                std::stoul(std::string(path.filename().c_str())));\n        }\n    }\n    else\n    {\n        record.nextRecordID = ipmi::sel::lastEntry;\n    }\n\n    if (requestData->readLength == ipmi::sel::entireRecord)\n    {\n        std::memcpy(response, &record, sizeof(record));\n        *data_len = sizeof(record);\n    }\n    else\n    {\n        if (requestData->offset >= ipmi::sel::selRecordSize ||\n            requestData->readLength > ipmi::sel::selRecordSize)\n        {\n            *data_len = 0;\n            return IPMI_CC_INVALID_FIELD_REQUEST;\n        }\n\n        auto diff = ipmi::sel::selRecordSize - requestData->offset;\n        auto readLength =\n            std::min(diff, static_cast<int>(requestData->readLength));\n\n        std::memcpy(response, &record.nextRecordID,\n                    sizeof(record.nextRecordID));\n        std::memcpy(static_cast<uint8_t*>(response) +\n                        sizeof(record.nextRecordID),\n                    &record.event.eventRecord.recordID + requestData->offset,\n                    readLength);\n        *data_len = sizeof(record.nextRecordID) + readLength;\n    }\n\n    return IPMI_CC_OK;\n}\n\n\/** @brief implements the delete SEL entry command\n * @request\n *   - reservationID; \/\/ reservation ID.\n *   - selRecordID;   \/\/ SEL record ID.\n *\n *  @returns ipmi completion code plus response data\n *   - Record ID of the deleted record\n *\/\nipmi::RspType<uint16_t \/\/ deleted record ID\n              >\n    deleteSELEntry(uint16_t reservationID, uint16_t selRecordID)\n{\n\n    namespace fs = std::filesystem;\n\n    if (!checkSELReservation(reservationID))\n    {\n        return ipmi::responseInvalidReservationId();\n    }\n\n    \/\/ Per the IPMI spec, need to cancel the reservation when a SEL entry is\n    \/\/ deleted\n    cancelSELReservation();\n\n    try\n    {\n        ipmi::sel::readLoggingObjectPaths(cache::paths);\n    }\n    catch (const sdbusplus::exception::SdBusError& e)\n    {\n        \/\/ readLoggingObjectPaths will throw exception if there are no error\n        \/\/ log entries.\n        return ipmi::responseSensorInvalid();\n    }\n\n    if (cache::paths.empty())\n    {\n        return ipmi::responseSensorInvalid();\n    }\n\n    ipmi::sel::ObjectPaths::const_iterator iter;\n    uint16_t delRecordID = 0;\n\n    if (selRecordID == ipmi::sel::firstEntry)\n    {\n        iter = cache::paths.begin();\n        fs::path path(*iter);\n        delRecordID = static_cast<uint16_t>(\n            std::stoul(std::string(path.filename().c_str())));\n    }\n    else if (selRecordID == ipmi::sel::lastEntry)\n    {\n        iter = cache::paths.end();\n        fs::path path(*iter);\n        delRecordID = static_cast<uint16_t>(\n            std::stoul(std::string(path.filename().c_str())));\n    }\n    else\n    {\n        std::string objPath = std::string(ipmi::sel::logBasePath) + \"\/\" +\n                              std::to_string(selRecordID);\n\n        iter = std::find(cache::paths.begin(), cache::paths.end(), objPath);\n        if (iter == cache::paths.end())\n        {\n            return ipmi::responseSensorInvalid();\n        }\n        delRecordID = selRecordID;\n    }\n\n    sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};\n    std::string service;\n\n    try\n    {\n        service = ipmi::getService(bus, ipmi::sel::logDeleteIntf, *iter);\n    }\n    catch (const std::runtime_error& e)\n    {\n        log<level::ERR>(e.what());\n        return ipmi::responseUnspecifiedError();\n    }\n\n    auto methodCall = bus.new_method_call(service.c_str(), (*iter).c_str(),\n                                          ipmi::sel::logDeleteIntf, \"Delete\");\n    auto reply = bus.call(methodCall);\n    if (reply.is_method_error())\n    {\n        return ipmi::responseUnspecifiedError();\n    }\n\n    \/\/ Invalidate the cache of dbus entry objects.\n    cache::paths.clear();\n\n    return ipmi::responseSuccess(delRecordID);\n}\n\n\/** @brief implements the Clear SEL command\n * @request\n *   - reservationID   \/\/ Reservation ID.\n *   - clr             \/\/ char array { 'C'(0x43h), 'L'(0x4Ch), 'R'(0x52h) }\n *   - eraseOperation; \/\/ requested operation.\n *\n *  @returns ipmi completion code plus response data\n *   - erase status\n *\/\n\nipmi::RspType<uint8_t \/\/ erase status\n              >\n    clearSEL(uint16_t reservationID, const std::array<char, 3>& clr,\n             uint8_t eraseOperation)\n{\n    static constexpr std::array<char, 3> clrOk = {'C', 'L', 'R'};\n    if (clr != clrOk)\n    {\n        return ipmi::responseInvalidFieldRequest();\n    }\n\n    if (!checkSELReservation(reservationID))\n    {\n        return ipmi::responseInvalidReservationId();\n    }\n\n    \/*\n     * Erasure status cannot be fetched from DBUS, so always return erasure\n     * status as `erase completed`.\n     *\/\n    if (eraseOperation == ipmi::sel::getEraseStatus)\n    {\n        return ipmi::responseSuccess(\n            static_cast<uint8_t>(ipmi::sel::eraseComplete));\n    }\n\n    \/\/ Per the IPMI spec, need to cancel any reservation when the SEL is cleared\n    cancelSELReservation();\n\n    sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};\n    ipmi::sel::ObjectPaths objectPaths;\n    auto depth = 0;\n\n    auto mapperCall =\n        bus.new_method_call(ipmi::sel::mapperBusName, ipmi::sel::mapperObjPath,\n                            ipmi::sel::mapperIntf, \"GetSubTreePaths\");\n    mapperCall.append(ipmi::sel::logBasePath);\n    mapperCall.append(depth);\n    mapperCall.append(ipmi::sel::ObjectPaths({ipmi::sel::logEntryIntf}));\n\n    try\n    {\n        auto reply = bus.call(mapperCall);\n        if (reply.is_method_error())\n        {\n            return ipmi::responseSuccess(\n                static_cast<uint8_t>(ipmi::sel::eraseComplete));\n        }\n\n        reply.read(objectPaths);\n        if (objectPaths.empty())\n        {\n            return ipmi::responseSuccess(\n                static_cast<uint8_t>(ipmi::sel::eraseComplete));\n        }\n    }\n    catch (const sdbusplus::exception::SdBusError& e)\n    {\n        return ipmi::responseSuccess(\n            static_cast<uint8_t>(ipmi::sel::eraseComplete));\n    }\n\n    std::string service;\n\n    try\n    {\n        service = ipmi::getService(bus, ipmi::sel::logDeleteIntf,\n                                   objectPaths.front());\n    }\n    catch (const std::runtime_error& e)\n    {\n        log<level::ERR>(e.what());\n        return ipmi::responseUnspecifiedError();\n    }\n\n    for (const auto& iter : objectPaths)\n    {\n        auto methodCall = bus.new_method_call(\n            service.c_str(), iter.c_str(), ipmi::sel::logDeleteIntf, \"Delete\");\n\n        auto reply = bus.call(methodCall);\n        if (reply.is_method_error())\n        {\n            return ipmi::responseUnspecifiedError();\n        }\n    }\n\n    \/\/ Invalidate the cache of dbus entry objects.\n    cache::paths.clear();\n    return ipmi::responseSuccess(\n        static_cast<uint8_t>(ipmi::sel::eraseComplete));\n}\n#endif\n\n\/** @brief implements the get SEL time command\n *  @returns IPMI completion code plus response data\n *   -current time\n *\/\nipmi::RspType<uint32_t> \/\/ current time\n    ipmiStorageGetSelTime()\n{\n    using namespace std::chrono;\n    uint64_t bmc_time_usec = 0;\n    std::stringstream bmcTime;\n\n    try\n    {\n        sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};\n        auto service = ipmi::getService(bus, TIME_INTERFACE, BMC_TIME_PATH);\n        std::variant<uint64_t> value;\n\n        \/\/ Get bmc time\n        auto method = bus.new_method_call(service.c_str(), BMC_TIME_PATH,\n                                          DBUS_PROPERTIES, \"Get\");\n\n        method.append(TIME_INTERFACE, PROPERTY_ELAPSED);\n        auto reply = bus.call(method);\n        if (reply.is_method_error())\n        {\n            log<level::ERR>(\"Error getting time\",\n                            entry(\"SERVICE=%s\", service.c_str()),\n                            entry(\"PATH=%s\", BMC_TIME_PATH));\n            return ipmi::responseUnspecifiedError();\n        }\n        reply.read(value);\n        bmc_time_usec = std::get<uint64_t>(value);\n    }\n    catch (InternalFailure& e)\n    {\n        log<level::ERR>(e.what());\n        return ipmi::responseUnspecifiedError();\n    }\n    catch (const std::exception& e)\n    {\n        log<level::ERR>(e.what());\n        return ipmi::responseUnspecifiedError();\n    }\n\n    bmcTime << \"BMC time:\"\n            << duration_cast<seconds>(microseconds(bmc_time_usec)).count();\n    log<level::DEBUG>(bmcTime.str().c_str());\n\n    \/\/ Time is really long int but IPMI wants just uint32. This works okay until\n    \/\/ the number of seconds since 1970 overflows uint32 size.. Still a whole\n    \/\/ lot of time here to even think about that.\n    return ipmi::responseSuccess(\n        duration_cast<seconds>(microseconds(bmc_time_usec)).count());\n}\n\n\/** @brief implements the set SEL time command\n *  @param selDeviceTime - epoch time\n *        -local time as the number of seconds from 00:00:00, January 1, 1970\n *  @returns IPMI completion code\n *\/\nipmi::RspType<> ipmiStorageSetSelTime(uint32_t selDeviceTime)\n{\n    using namespace std::chrono;\n    microseconds usec{seconds(selDeviceTime)};\n\n    try\n    {\n        sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};\n        auto service = ipmi::getService(bus, TIME_INTERFACE, BMC_TIME_PATH);\n        std::variant<uint64_t> value{(uint64_t)usec.count()};\n\n        \/\/ Set bmc time\n        auto method = bus.new_method_call(service.c_str(), BMC_TIME_PATH,\n                                          DBUS_PROPERTIES, \"Set\");\n\n        method.append(TIME_INTERFACE, PROPERTY_ELAPSED, value);\n        auto reply = bus.call(method);\n        if (reply.is_method_error())\n        {\n            log<level::ERR>(\"Error setting time\",\n                            entry(\"SERVICE=%s\", service.c_str()),\n                            entry(\"PATH=%s\", BMC_TIME_PATH));\n            return ipmi::responseUnspecifiedError();\n        }\n    }\n    catch (InternalFailure& e)\n    {\n        log<level::ERR>(e.what());\n        return ipmi::responseUnspecifiedError();\n    }\n    catch (const std::exception& e)\n    {\n        log<level::ERR>(e.what());\n        return ipmi::responseUnspecifiedError();\n    }\n\n    return ipmi::responseSuccess();\n}\n\n\/** @brief implements the reserve SEL command\n *  @returns IPMI completion code plus response data\n *   - SEL reservation ID.\n *\/\nipmi::RspType<uint16_t> ipmiStorageReserveSel()\n{\n    return ipmi::responseSuccess(reserveSel());\n}\n\n#ifdef JOURNAL_SEL\n#if 0\nstatic void toHexStr(const boost::beast::span<uint8_t> bytes,\n                     std::string& hexStr)\n{\n    std::stringstream stream;\n    stream << std::hex << std::uppercase << std::setfill('0');\n    for (const uint8_t& byte : bytes)\n    {\n        stream << std::setw(2) << static_cast<int>(byte);\n    }\n    hexStr = stream.str();\n}\n\nstatic inline bool defaultMessageHook(uint16_t recordID, uint8_t recordType,\n                       uint32_t timestamp, uint16_t generatorID, uint8_t evmRev,\n                       uint8_t sensorType, uint8_t sensorNum, uint8_t eventType,\n                       std::array<uint8_t, eventDataSize> eventData)\n{\n    \/\/ Log the record as a default Redfish message instead of a SEL record\n\n    \/\/ Save the raw IPMI string of the request\n    std::string ipmiRaw;\n    std::array selBytes = {static_cast<uint8_t>(recordID),\n                           static_cast<uint8_t>(recordID >> 8),\n                           recordType,\n                           static_cast<uint8_t>(timestamp),\n                           static_cast<uint8_t>(timestamp >> 8),\n                           static_cast<uint8_t>(timestamp >> 16),\n                           static_cast<uint8_t>(timestamp >> 24),\n                           static_cast<uint8_t>(generatorID),\n                           static_cast<uint8_t>(generatorID >> 8),\n                           evmRev,\n                           sensorType,\n                           sensorNum,\n                           eventType,\n                           eventData[0],\n                           eventData[1],\n                           eventData[2]};\n\n    toHexStr(boost::beast::span<uint8_t>(selBytes), ipmiRaw);\n\n    static const std::string openBMCMessageRegistryVersion(\"0.1\");\n    std::string messageID =\n        \"OpenBMC.\" + openBMCMessageRegistryVersion + \".SELEntryAdded\";\n\n    std::vector<std::string> messageArgs;\n    messageArgs.push_back(ipmiRaw);\n\n    \/\/ Log the Redfish message to the journal with the appropriate metadata\n    std::string journalMsg = \"SEL Entry Added: \" + ipmiRaw;\n    std::string messageArgsString = boost::algorithm::join(messageArgs, \",\");\n    phosphor::logging::log<phosphor::logging::level::INFO>(\n        journalMsg.c_str(),\n        phosphor::logging::entry(\"REDFISH_MESSAGE_ID=%s\", messageID.c_str()),\n        phosphor::logging::entry(\"REDFISH_MESSAGE_ARGS=%s\",\n                                 messageArgsString.c_str()));\n\n    return true;\n}\n#endif\n\nipmi::RspType<uint16_t> ipmiStorageAddSEL(\n    uint16_t recordID, uint8_t recordType, uint32_t timestamp,\n    uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,\n    uint8_t eventType, std::array<uint8_t, eventDataSize> eventData)\n{\n    \/\/ Per the IPMI spec, need to cancel any reservation when a SEL entry is\n    \/\/ added\n    cancelSELReservation();\n#if 0\n    \/\/ Send this request to the Redfish hooks to log it as a Redfish message\n    \/\/ instead.  There is no need to add it to the SEL, so just return success.\n    defaultMessageHook(\n        recordID, recordType, timestamp, generatorID, evmRev, sensorType,\n        sensorNum, eventType, eventData);\n#endif\n    static constexpr char const* ipmiSELObject =\n        \"xyz.openbmc_project.Logging.IPMI\";\n    static constexpr char const* ipmiSELPath =\n        \"\/xyz\/openbmc_project\/Logging\/IPMI\";\n    static constexpr char const* ipmiSELAddInterface =\n        \"xyz.openbmc_project.Logging.IPMI\";\n    static const std::string ipmiSELAddMessage =\n        \"IPMI SEL entry logged using IPMI Add SEL Entry command.\";\n\n    sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};\n\n    if (recordType == ipmi::sel::systemEvent)\n    {\n        std::string sensorPath = getPathFromSensorNumber(sensorNum);\n        if(sensorPath.length() == 0){\n            return ipmi::responseSensorInvalid();\n        }\n\n        bool assert =\n            (eventType & ipmi::sel::deassertionEvent) ? false : true;\n        uint16_t genId = generatorID;\n        sdbusplus::message::message writeSEL = bus.new_method_call(\n            ipmiSELObject, ipmiSELPath, ipmiSELAddInterface, \"IpmiSelAdd\");\n        writeSEL.append(ipmiSELAddMessage, sensorPath, eventData, assert,\n                        genId);\n        try\n        {\n            sdbusplus::message::message writeSELResp = bus.call(writeSEL);\n            writeSELResp.read(recordID);\n        }\n        catch (sdbusplus::exception_t& e)\n        {\n            log<level::ERR>(e.what());\n            return ipmi::responseUnspecifiedError();\n        }\n    }\n    else if (recordType >= ipmi::sel::oemTsEventFirst &&\n             recordType <= ipmi::sel::oemEventLast)\n    {\n        sdbusplus::message::message writeSEL = bus.new_method_call(\n            ipmiSELObject, ipmiSELPath, ipmiSELAddInterface, \"IpmiSelAddOem\");\n        writeSEL.append(ipmiSELAddMessage, eventData, recordType);\n        try\n        {\n            sdbusplus::message::message writeSELResp = bus.call(writeSEL);\n            writeSELResp.read(recordID);\n        }\n        catch (sdbusplus::exception_t& e)\n        {\n            log<level::ERR>(e.what());\n            return ipmi::responseUnspecifiedError();\n        }\n    }\n    else\n    {\n        return ipmi::responseUnspecifiedError();\n    }\n\n   \/\/ uint16_t responseID = 0xFFFF;\n    return ipmi::responseSuccess(recordID);\n}\n#else  \/\/ JOURNAL_SEL not used\n\/** @brief implements the Add SEL entry command\n * @request\n *\n *   - recordID      ID used for SEL Record access\n *   - recordType    Record Type\n *   - timeStamp     Time when event was logged. LS byte first\n *   - generatorID   software ID if event was generated from\n *                   system software\n *   - evmRev        event message format version\n *   - sensorType    sensor type code for service that generated\n *                   the event\n *   - sensorNumber  number of sensors that generated the event\n *   - eventDir     event dir\n *   - eventData    event data field contents\n *\n *  @returns ipmi completion code plus response data\n *   - RecordID of the Added SEL entry\n *\/\nipmi::RspType<uint16_t \/\/ recordID of the Added SEL entry\n              >\n    ipmiStorageAddSEL(uint16_t recordID, uint8_t recordType, uint32_t timeStamp,\n                      uint16_t generatorID, uint8_t evmRev, uint8_t sensorType,\n                      uint8_t sensorNumber, uint8_t eventDir,\n                      std::array<uint8_t, eventDataSize> eventData)\n{\n    \/\/ Per the IPMI spec, need to cancel the reservation when a SEL entry is\n    \/\/ added\n    cancelSELReservation();\n    \/\/ Hostboot sends SEL with OEM record type 0xDE to indicate that there is\n    \/\/ a maintenance procedure associated with eSEL record.\n    static constexpr auto procedureType = 0xDE;\n    if (recordType == procedureType)\n    {\n        \/\/ In the OEM record type 0xDE, byte 11 in the SEL record indicate the\n        \/\/ procedure number.\n        createProcedureLogEntry(sensorType);\n    }\n\n    return ipmi::responseSuccess(recordID);\n}\n#endif \/\/ JOURNAL_SEL\n\n\/** @brief implements the get FRU Inventory Area Info command\n *\n *  @returns IPMI completion code plus response data\n *   - FRU Inventory area size in bytes,\n *   - access bit\n **\/\nipmi::RspType<uint16_t, \/\/ FRU Inventory area size in bytes,\n              uint8_t   \/\/ access size (bytes \/ words)\n              >\n    ipmiStorageGetFruInvAreaInfo(uint8_t fruID)\n{\n\n    auto iter = frus.find(fruID);\n    if (iter == frus.end())\n    {\n        return ipmi::responseSensorInvalid();\n    }\n\n    try\n    {\n        return ipmi::responseSuccess(\n            static_cast<uint16_t>(getFruAreaData(fruID).size()),\n            static_cast<uint8_t>(AccessMode::bytes));\n    }\n    catch (const InternalFailure& e)\n    {\n        log<level::ERR>(e.what());\n        return ipmi::responseUnspecifiedError();\n    }\n}\n\n\/**@brief implements the Read FRU Data command\n * @param fruDeviceId - FRU device ID. FFh = reserved\n * @param offset      - FRU inventory offset to read\n * @param readCount   - count to read\n *\n * @return IPMI completion code plus response data\n * - returnCount - response data count.\n * - data        -  response data\n *\/\nipmi::RspType<uint8_t,              \/\/ count returned\n              std::vector<uint8_t>> \/\/ FRU data\n    ipmiStorageReadFruData(uint8_t fruDeviceId, uint16_t offset,\n                           uint8_t readCount)\n{\n    if (fruDeviceId == 0xFF)\n    {\n        return ipmi::responseInvalidFieldRequest();\n    }\n\n    auto iter = frus.find(fruDeviceId);\n    if (iter == frus.end())\n    {\n        return ipmi::responseSensorInvalid();\n    }\n\n    try\n    {\n        const auto& fruArea = getFruAreaData(fruDeviceId);\n        auto size = fruArea.size();\n\n        if (offset >= size)\n        {\n            return ipmi::responseParmOutOfRange();\n        }\n\n        \/\/ Write the count of response data.\n        uint8_t returnCount;\n        if ((offset + readCount) <= size)\n        {\n            returnCount = readCount;\n        }\n        else\n        {\n            returnCount = size - offset;\n        }\n\n        std::vector<uint8_t> fruData((fruArea.begin() + offset),\n                                     (fruArea.begin() + offset + returnCount));\n\n        return ipmi::responseSuccess(returnCount, fruData);\n    }\n    catch (const InternalFailure& e)\n    {\n        log<level::ERR>(e.what());\n        return ipmi::responseUnspecifiedError();\n    }\n}\n\nipmi::RspType<uint8_t,  \/\/ SDR version\n              uint16_t, \/\/ record count LS first\n              uint16_t, \/\/ free space in bytes, LS first\n              uint32_t, \/\/ addition timestamp LS first\n              uint32_t, \/\/ deletion timestamp LS first\n              uint8_t>  \/\/ operation Support\n    ipmiGetRepositoryInfo()\n{\n\n    constexpr uint8_t sdrVersion = 0x51;\n    constexpr uint16_t freeSpace = 0xFFFF;\n    constexpr uint32_t additionTimestamp = 0x0;\n    constexpr uint32_t deletionTimestamp = 0x0;\n    constexpr uint8_t operationSupport = 0;\n\n    uint16_t records = frus.size() + ipmi::sensor::sensors.size();\n\n    return ipmi::responseSuccess(sdrVersion, records, freeSpace,\n                                 additionTimestamp, deletionTimestamp,\n                                 operationSupport);\n}\n\nvoid register_netfn_storage_functions()\n{\n\n    \/\/ <Get SEL Info>\n    ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,\n                          ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,\n                          ipmiStorageGetSelInfo);\n    \/\/ <Get SEL Time>\n    ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,\n                          ipmi::storage::cmdGetSelTime, ipmi::Privilege::User,\n                          ipmiStorageGetSelTime);\n\n    \/\/ <Set SEL Time>\n    ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,\n                          ipmi::storage::cmdSetSelTime,\n                          ipmi::Privilege::Operator, ipmiStorageSetSelTime);\n\n    \/\/ <Reserve SEL>\n    ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,\n                          ipmi::storage::cmdReserveSel, ipmi::Privilege::User,\n                          ipmiStorageReserveSel);\n    \/\/ <Get SEL Entry>\n    ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,\n                          ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User,\n                          ipmiStorageGetSELEntry);\n\n#ifndef JOURNAL_SEL\n    \/\/ <Delete SEL Entry>\n    ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,\n                          ipmi::storage::cmdDeleteSelEntry,\n                          ipmi::Privilege::Operator, deleteSELEntry);\n#endif\n    \/\/ <Add SEL Entry>\n    ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,\n                          ipmi::storage::cmdAddSelEntry,\n                          ipmi::Privilege::Operator, ipmiStorageAddSEL);\n\n    \/\/ <Clear SEL>\n    ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,\n                          ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,\n                          ipmiStorageClearSEL);\n\n    \/\/ <Get FRU Inventory Area Info>\n    ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,\n                          ipmi::storage::cmdGetFruInventoryAreaInfo,\n                          ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);\n\n    \/\/ <READ FRU Data>\n    ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,\n                          ipmi::storage::cmdReadFruData,\n                          ipmi::Privilege::Operator, ipmiStorageReadFruData);\n\n    \/\/ <Get Repository Info>\n    ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,\n                          ipmi::storage::cmdGetSdrRepositoryInfo,\n                          ipmi::Privilege::User, ipmiGetRepositoryInfo);\n\n    \/\/ <Reserve SDR Repository>\n    ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,\n                          ipmi::storage::cmdReserveSdrRepository,\n                          ipmi::Privilege::User, ipmiSensorReserveSdr);\n\n    \/\/ <Get SDR>\n    ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_GET_SDR, nullptr,\n                           ipmi_sen_get_sdr, PRIVILEGE_USER);\n\n    ipmi::fru::registerCallbackHandler();\n    return;\n}\n","avg_line_length":31.7640990371,"max_line_length":80,"alphanum_fraction":0.601667208,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3126,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ vect.cpp -- methods for the Vector class\n#include <cmath>\n#include \"vector.h\"\n\/\/ includes <iostream>\nusing std::sqrt;\nusing std::sin;\nusing std::cos;\nusing std::atan;\nusing std::atan2;\nusing std::cout;\n\nnamespace VECTOR\n{\n\t\/\/ compute degrees in one radian\n\tconst double Rad_to_deg = 45.0 \/ atan(1.0);\n\t\/\/ should be about 57.2957795130823\n\t\/\/ private methods\n\t\/\/ calculates magnitude from x and y\n\tvoid Vector::set_mag()\n\t{\n\t\tmag = sqrt(x * x + y * y);\n\t}\n\n\tvoid Vector::set_ang()\n\t{\n\t\tif (x == 0.0 && y == 0.0)\n\t\t\tang = 0.0;\n\t\telse\n\t\t\tang = atan2(y, x);\n\t}\n\n\t\/\/ set x from polar coordinate\n\tvoid Vector::set_x()\n\t{\n\t\tx = mag * cos(ang);\n\t}\n\n\t\/\/ set y from polar coordinate\n\tvoid Vector::set_y()\n\t{\n\t\ty = mag * sin(ang);\n\t}\n\n\t\/\/ public methods\n\tVector::Vector()\n\t\/\/ default constructor\n\t{\n\t\tx = y = mag = ang = 0.0;\n\t\tmode = RECT;\n\t}\n\n\t\/\/ construct vector from rectangular coordinates if form is r\n\t\/\/ (the default) or else from polar coordinates if form is p\n\tVector::Vector(double n1, double n2, Mode form)\n\t{\n\t\tmode = form;\n\t\tif (form == RECT)\n\t\t{\n\t\t\tx = n1;\n\t\t\ty = n2;\n\t\t\tset_mag();\n\t\t\tset_ang();\n\t\t}\n\t\telse if (form == POL)\n\t\t{\n\t\t\tmag = n1;\n\t\t\tang = n2 \/ Rad_to_deg;\n\t\t\tset_x();\n\t\t\tset_y();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcout << \"Incorrect 3rd argument to Vector() -- \";\n\t\t\tcout << \"vector set to 0\\n\";\n\t\t\tx = y = mag = ang = 0.0;\n\t\t\tmode = RECT;\n\t\t}\n\t}\n\t\/\/ reset vector from rectangular coordinates if form is\n\t\/\/ RECT (the default) or else from polar coordinates if\n\t\/\/ form is POL\n\tvoid Vector:: reset(double n1, double n2, Mode form)\n\t{\n\t\tmode = form;\n\t\tif (form == RECT)\n\t\t{\n\t\t\tx = n1;\n\t\t\ty = n2;\n\t\t\tset_mag();\n\t\t\tset_ang();\n\t\t}\n\t\telse if (form == POL)\n\t\t{\n\t\t\tmag = n1;\n\t\t\tang = n2 \/ Rad_to_deg;\n\t\t\tset_x();\n\t\t\tset_y();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcout << \"Incorrect 3rd argument to Vector() -- \";\n\t\t\tcout << \"vector set to 0\\n\";\n\t\t\tx = y = mag = ang = 0.0;\n\t\t\tmode = RECT;\n\t\t}\n\t}\n\tVector::~Vector(){}\n\t\/\/ destructor\n\tvoid Vector::polar_mode()\n\t{\n\t\tmode = POL;\n\t} \/\/ set to polar mode\n\tvoid Vector::rect_mode()\n\t{\n\t\tmode = RECT;\n\t} \/\/ set to rectangular mode\n\t\/\/ operator overloading\n\t\/\/ add two Vectors\n\tVector Vector::operator+(const Vector & b) const\n\t{\n\t\treturn Vector(x + b.x, y + b.y);\n\t}\n\t\/\/ subtract Vector b from a\n\tVector Vector::operator-(const Vector & b) const\n\t{\n\t\treturn Vector(x - b.x, y - b.y);\n\t}\n\t\/\/ reverse sign of Vector\n\tVector Vector::operator-() const\n\t{\n\t\treturn Vector(-x, -y);\n\t}\n\t\/\/ multiply vector by n\n\tVector Vector::operator*(double n) const\n\t{\n\t\treturn Vector(n * x, n * y);\n\t}\n\t\/\/ friend methods\n\t\/\/ multiply n by Vector a\n\tVector operator*(double n, const Vector & a)\n\t{\n\t\treturn a * n;\n\t}\n\t\/\/ display rectangular coordinates if mode is RECT,\n\t\/\/ else display polar coordinates if mode is POL\n\tstd::ostream & operator<<(std::ostream & os, const Vector & v)\n\t{\n\t\tif (v.mode == Vector::RECT)\n\t\t\tos << \"(x,y) = (\" << v.x << \", \" << v.y << \")\";\n\t\telse if (v.mode == Vector::POL)\n\t\t{\n\t\t\tos << \"(m,a) = (\" << v.mag << \", \"\n\t\t\t<< v.ang * Rad_to_deg << \")\";\n\t\t}\n\t\telse\n\t\t\tos << \"Vector object mode is invalid\";\n\t\t\n\t\treturn os;\n\t}\n\n\tVector::operator double() const\n\t{\n\t\treturn mag;\n\t}\n}\n\/\/ end namespace VECTOR","avg_line_length":18.8313253012,"max_line_length":63,"alphanum_fraction":0.5850927703,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5363,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"#include <string>\n#include <chrono>\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <stdexcept>\n\n#include \"deflate.h\"\n#include \"crc.h\"\n\nusing namespace deflate;\n\n#include <fstream>\nstd::vector<uint8_t> read_file(const std::string& filename)\n{\n    std::ifstream in(filename, std::ios_base::binary);\n    if (!in) throw std::runtime_error(filename + \" not found\");\n    in.seekg(0, std::ios_base::end);\n    const auto file_size = static_cast<int>(in.tellg());\n    in.seekg(0, std::ios_base::beg);\n    std::vector<uint8_t> input(file_size);\n    in.read(reinterpret_cast<char*>(&input[0]), input.size());\n    return input;\n}\n\nstd::vector<uint8_t> gunzip(const std::string& filename)\n{\n    const auto input     = read_file(filename);\n    const int  file_size = static_cast<int>(input.size());\n    if (file_size < 18) throw std::runtime_error(filename + \" is too small to be a gzip file\");\n\n\n    auto invalid = [&filename] () { throw std::runtime_error(filename + \" is not a valid gzip file\"); };\n\n    \/\/ +---+---+---+---+---+---+---+---+---+---+\n    \/\/ |ID1|ID2|CM |FLG|     MTIME      |XFL|OS|\n    \/\/ +---+---+---+---+---+---+---+---+---+---+\n    if (input[0] != 0x1f || \/\/ ID1\n        input[1] != 0x8b || \/\/ ID2\n        input[2] != 8) {    \/\/ CM\n        invalid();\n    }\n    enum { FTEXT=1, FHCRC=2, FEXTRA=4, FNAME=8, FCOMMENT=16 };\n    const auto flg = input[3];\n    int pos = 10;\n    if (flg & FEXTRA) {\n        const int xlen = input[pos] | (input[pos+1] << 8);\n        \/\/ TODO: Check whether it's valid to skip this many bytes\n        pos += 2 + xlen;\n    }\n    auto get_zero_terminated_string = [&] () -> std::string {\n        std::string res;\n        while (pos < file_size) {\n            const char c = input[pos++];\n            if (!c) return res;\n            res += c;\n        }\n        invalid();\n        return {};\n    };\n    if (flg & FNAME) {\n        get_zero_terminated_string(); \/\/ filename\n    }\n    if (flg & FCOMMENT) {\n        get_zero_terminated_string(); \/\/ comment\n    }\n    if (flg & FHCRC) {\n        pos += 2; \/\/ skip 16-bit header CRC\n    }\n    assert(file_size >= pos + 8);\n\n    int f = file_size - 8;\n    const auto crc32 = static_cast<uint32_t>(input[f + 0]) |\n        (static_cast<uint32_t>(input[f + 1]) << 8) |\n        (static_cast<uint32_t>(input[f + 2]) << 16) |\n        (static_cast<uint32_t>(input[f + 3]) << 24);\n\n    const auto isize = static_cast<uint32_t>(input[f + 4]) |\n        (static_cast<uint32_t>(input[f + 5]) << 8) |\n        (static_cast<uint32_t>(input[f + 6]) << 16) |\n        (static_cast<uint32_t>(input[f + 7]) << 24);\n\n    bit_stream bs(input.data() + pos, input.data() + file_size - 8);\n    const auto output = deflate::deflate(bs);\n    if (output.size() != isize) {\n        invalid();\n    }\n\n    if (update_crc32(0, output.data(), output.data() + output.size()) != crc32) {\n        invalid();\n    }\n\n    return output;\n}\n\ntemplate<typename F>\nvoid time_it(F f)\n{\n    constexpr int num_timings = 20;\n    double timings[num_timings];\n    double sum = 0.0;\n    for (int i = 0; i < num_timings; ++i) {\n        const auto start = std::chrono::high_resolution_clock::now();\n        f();\n        const auto end = std::chrono::high_resolution_clock::now();\n        timings[i] = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(end - start).count();\n        std::cout << timings[i] << \"\\n\";\n        sum += timings[i];\n    }\n    std::sort(timings, timings + num_timings);\n    std::cout << \"Min\/Avg\/Mean\/Max: \";\n    std::cout << timings[0] << \" \/ \";\n    std::cout << sum\/num_timings << \" \/ \";\n    std::cout << timings[num_timings\/2] << \" \/ \";\n    std::cout << timings[num_timings-1] << std::endl;\n}\n\nvoid timing()\n{\n    \/\/ Tests performned on bunny.tar.gz (4.894.286 B) and doing 2 \"warp up\" runs before sampling\n    \/\/\n    \/\/ Before optimizations                                 Min\/Avg\/Mean\/Max: 245.635 \/ 262.008 \/ 249.782 \/ 347.802\n    \/\/ Use tables:                                          Min\/Avg\/Mean\/Max: 164.282 \/ 170.603 \/ 168.520 \/ 204.303\n    \/\/ Remember tables, resize before main deflate loop     Min\/Avg\/Mean\/Max: 146.035 \/ 151.077 \/ 149.078 \/ 181.598\n    \/\/ Rrwrite copy_match to use pointers                   Min\/Avg\/Mean\/Max: 144.599 \/ 149.110 \/ 146.850 \/ 178.669\n    \/\/ Use memcpy in copy_match when possible               Min\/Avg\/Mean\/Max: 140.990 \/ 145.125 \/ 143.224 \/ 166.766\n    \/\/ Refactor to reduce memory usage\/copying              Min\/Avg\/Mean\/Max: 139.712 \/ 144.123 \/ 142.551 \/ 169.340\n    \/\/ Add output_buffer to reduce reallocations            Min\/Avg\/Mean\/Max: 126.260 \/ 130.980 \/ 128.099 \/ 166.442\n    \/\/ Make copy_match a member function of output_buffer   Min\/Avg\/Mean\/Max: 125.058 \/ 128.883 \/ 126.667 \/ 149.527\n    \/\/ Double buffer on enlarge() call                      Min\/Avg\/Mean\/Max: 120.193 \/ 123.590 \/ 121.619 \/ 145.353\n    \/\/ Use realloc()                                        Min\/Avg\/Mean\/Max: 116.515 \/ 121.193 \/ 118.694 \/ 145.324\n    auto data = read_file(\"..\/bunny.tar.gz\");\n    time_it([&data] {\n        bit_stream bs{data.data() + 20, data.data() + data.size() - 8};\n        deflate::deflate(bs);\n    });\n}\n\nint main()\n{\n    try {\n        gunzip(\"..\/CMakeLists.txt.gz\");\n        gunzip(\"..\/main.cpp.gz\");\n        timing();\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << \"\\n\";\n        return 1;\n    }\n}\n","avg_line_length":35.7533333333,"max_line_length":115,"alphanum_fraction":0.5521163528,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":428,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"PlayerContext.h\"\r\n\r\nusing namespace model;\r\nusing namespace std;\r\n\r\nPlayerContext::PlayerContext()\r\n        : cars(vector<Car> ()), world(World ()) { }\r\n\r\nPlayerContext::PlayerContext(const vector<Car>& cars, const World& world)\r\n        : cars(cars), world(world) { }\r\n\r\nconst vector<Car>& PlayerContext::getCars() const {\r\n    return cars;\r\n}\r\n\r\nconst World& PlayerContext::getWorld() const {\r\n    return world;\r\n}\r\n","avg_line_length":22.5263157895,"max_line_length":74,"alphanum_fraction":0.6518691589,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":64152,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include \"train_model.h\"\n#include \"options_helper.h\"\n#include \"cross_validation.h\"\n#include \"dir_helper.h\"\n\n#include <catboost\/private\/libs\/algo\/approx_dimension.h>\n#include <catboost\/private\/libs\/algo\/data.h>\n#include <catboost\/private\/libs\/algo\/full_model_saver.h>\n#include <catboost\/private\/libs\/algo\/helpers.h>\n#include <catboost\/private\/libs\/algo\/learn_context.h>\n#include <catboost\/private\/libs\/algo\/preprocess.h>\n#include <catboost\/private\/libs\/algo\/train.h>\n#include <catboost\/private\/libs\/algo\/tree_print.h>\n#include <catboost\/libs\/data\/feature_names_converter.h>\n#include <catboost\/libs\/data\/borders_io.h>\n#include <catboost\/libs\/data\/load_data.h>\n#include <catboost\/private\/libs\/data_util\/exists_checker.h>\n#include <catboost\/private\/libs\/distributed\/master.h>\n#include <catboost\/private\/libs\/distributed\/worker.h>\n#include <catboost\/libs\/fstr\/calc_fstr.h>\n#include <catboost\/libs\/fstr\/output_fstr.h>\n#include <catboost\/libs\/helpers\/int_cast.h>\n#include <catboost\/libs\/helpers\/mem_usage.h>\n#include <catboost\/libs\/helpers\/permutation.h>\n#include <catboost\/libs\/helpers\/query_info_helper.h>\n#include <catboost\/libs\/helpers\/vector_helpers.h>\n#include <catboost\/private\/libs\/labels\/external_label_helper.h>\n#include <catboost\/libs\/loggers\/catboost_logger_helpers.h>\n#include <catboost\/libs\/loggers\/logger.h>\n#include <catboost\/libs\/logging\/profile_info.h>\n#include <catboost\/libs\/metrics\/metric.h>\n#include <catboost\/libs\/metrics\/optimal_const_for_loss.h>\n#include <catboost\/libs\/model\/ctr_data.h>\n#include <catboost\/libs\/model\/model_build_helper.h>\n#include <catboost\/private\/libs\/options\/catboost_options.h>\n#include <catboost\/private\/libs\/options\/monotone_constraints.h>\n#include <catboost\/private\/libs\/options\/plain_options_helper.h>\n#include <catboost\/private\/libs\/options\/system_options.h>\n#include <catboost\/private\/libs\/pairs\/util.h>\n#include <catboost\/private\/libs\/target\/classification_target_helper.h>\n\n#include <library\/cpp\/grid_creator\/binarization.h>\n#include <library\/cpp\/json\/json_prettifier.h>\n\n#include <util\/generic\/cast.h>\n#include <util\/generic\/mapfindptr.h>\n#include <util\/generic\/scope.h>\n#include <util\/generic\/vector.h>\n#include <util\/generic\/xrange.h>\n#include <util\/generic\/ymath.h>\n#include <util\/random\/shuffle.h>\n#include <util\/system\/compiler.h>\n#include <util\/system\/hp_timer.h>\n\n#include <functional>\n\nusing namespace NCB;\n\n\nstatic void ShrinkModel(int itCount, const TCtrHelper& ctrsHelper, TLearnProgress* progress) {\n    itCount += SafeIntegerCast<int>(progress->InitTreesSize);\n    progress->LeafValues.resize(itCount);\n    progress->TreeStruct.resize(itCount);\n    progress->TreeStats.resize(itCount);\n    if (!progress->ModelShrinkHistory.empty()) {\n        Y_ASSERT(SafeIntegerCast<int>(progress->ModelShrinkHistory.size()) >= itCount);\n        progress->ModelShrinkHistory.resize(itCount);\n    }\n    progress->UsedCtrSplits.clear();\n    for (const auto& tree: progress->TreeStruct) {\n        for (const auto& ctr : GetUsedCtrs(tree)) {\n            TProjection projection = ctr.Projection;\n            ECtrType ctrType = ctrsHelper.GetCtrInfo(projection)[ctr.CtrIdx].Type;\n            progress->UsedCtrSplits.insert(std::make_pair(ctrType, projection));\n        }\n    }\n    progress->IsFoldsAndApproxDataValid = false;\n}\n\n\nstatic TDataProviders LoadPools(\n    const NCatboostOptions::TPoolLoadParams& loadOptions,\n    ETaskType taskType,\n    ui64 cpuRamLimit,\n    EObjectsOrder objectsOrder,\n    TDatasetSubset trainDatasetSubset,\n    TVector<NJson::TJsonValue>* classLabels,\n    NPar::TLocalExecutor* const executor,\n    TProfileInfo* profile\n) {\n    const auto& cvParams = loadOptions.CvParams;\n    const bool cvMode = cvParams.FoldCount != 0;\n    CB_ENSURE(\n        !cvMode || loadOptions.TestSetPaths.empty(),\n        \"Test files are not supported in cross-validation mode\"\n    );\n\n    auto pools = NCB::ReadTrainDatasets(taskType, loadOptions, objectsOrder, !cvMode, trainDatasetSubset, classLabels, executor, profile);\n\n    if (cvMode) {\n        if (cvParams.Shuffle && (pools.Learn->ObjectsData->GetOrder() != EObjectsOrder::RandomShuffled)) {\n            TRestorableFastRng64 rand(cvParams.PartitionRandSeed);\n\n            auto objectsGroupingSubset = NCB::Shuffle(pools.Learn->ObjectsGrouping, 1, &rand);\n            pools.Learn = pools.Learn->GetSubset(objectsGroupingSubset, cpuRamLimit, executor);\n        }\n\n        TVector<TDataProviders> foldPools = PrepareCvFolds<TDataProviders>(\n            std::move(pools.Learn),\n            cvParams,\n            cvParams.FoldIdx,\n            \/* oldCvStyleSplit *\/ true,\n            cpuRamLimit,\n            executor);\n        Y_VERIFY(foldPools.size() == 1);\n\n        profile->AddOperation(\"Build cv pools\");\n\n        return foldPools[0];\n    } else {\n        return pools;\n    }\n}\n\nstatic bool HasInvalidValues(const TVector<TVector<double>>& treeLeafValues) {\n    for (const auto& leafValuesDimension : treeLeafValues) {\n        for (double leafValueCoord : leafValuesDimension) {\n            if (!IsValidFloat(leafValueCoord)) {\n                return true;\n            }\n        }\n    }\n    return false;\n}\n\nnamespace {\nstruct TMetricsData {\n    TVector<THolder<IMetric>> Metrics;\n    bool CalcEvalMetricOnEveryIteration;\n    TMaybe<ui32> MetricPeriodOffset; \/\/ shift metric period calculations by this value if defined\n    TMaybe<TErrorTracker> ErrorTracker;\n    TMaybe<TErrorTracker> BestModelMinTreesTracker;\n    size_t ErrorTrackerMetricIdx;\n};\n}\n\nstatic void InitializeAndCheckMetricData(\n    const TTrainModelInternalOptions& internalOptions,\n    const TTrainingDataProviders& data,\n    const TLearnContext& ctx,\n    TMetricsData* metricsData) {\n\n    const int approxDimension = ctx.LearnProgress->ApproxDimension;\n    auto& metrics = metricsData->Metrics;\n    metrics = CreateMetrics(\n        ctx.Params.MetricOptions,\n        ctx.EvalMetricDescriptor,\n        approxDimension,\n        ctx.GetHasWeights()\n    );\n    CheckMetrics(metrics, ctx.Params.LossFunctionDescription.Get().GetLossFunction());\n    if (!ctx.Params.SystemOptions->IsSingleHost()) {\n        if (!AllOf(metrics, [](const auto& metric) { return metric->IsAdditiveMetric(); })) {\n            CATBOOST_WARNING_LOG << \"In distributed training, non-additive metrics are not evaluated on train dataset\" << Endl;\n        }\n    }\n    if (ctx.Params.LossFunctionDescription->GetLossFunction() == ELossFunction::MultiRMSE) {\n        CB_ENSURE(!ctx.Layout->GetCatFeatureCount(), \"Training with MultiRMSE loss function doesn't support categorical features\");\n    }\n\n    CB_ENSURE(!metrics.empty(), \"Eval metric is not defined\");\n\n    const bool lastTestDatasetHasTargetData = (data.Test.size() > 0) && data.Test.back()->MetaInfo.TargetCount > 0;\n\n    const bool hasTest = data.GetTestSampleCount() > 0;\n    if (hasTest && metrics[0]->NeedTarget() && !lastTestDatasetHasTargetData) {\n        CATBOOST_WARNING_LOG << \"Warning: Eval metric \" << metrics[0]->GetDescription() <<\n            \" needs Target data, but test dataset does not have it so it won't be calculated\" << Endl;\n    }\n    const bool canCalcEvalMetric = hasTest && (!metrics[0]->NeedTarget() || lastTestDatasetHasTargetData);\n\n    if (canCalcEvalMetric) {\n        EMetricBestValue bestValueType;\n        float bestPossibleValue;\n\n        metrics.front()->GetBestValue(&bestValueType, &bestPossibleValue);\n        metricsData->ErrorTracker = BuildErrorTracker(bestValueType, bestPossibleValue, hasTest, ctx);\n        metricsData->BestModelMinTreesTracker = BuildErrorTracker(bestValueType, bestPossibleValue, hasTest, ctx);\n    }\n\n    auto& errorTracker = metricsData->ErrorTracker;\n    metricsData->CalcEvalMetricOnEveryIteration\n        = canCalcEvalMetric && (internalOptions.ForceCalcEvalMetricOnEveryIteration || errorTracker->IsActive());\n\n    if (ctx.OutputOptions.GetMetricPeriod() > 1 && errorTracker && errorTracker->IsActive() && hasTest) {\n        CATBOOST_WARNING_LOG << \"Warning: Overfitting detector is active, thus evaluation metric is \" <<\n            \"calculated on every iteration. 'metric_period' is ignored for evaluation metric.\" << Endl;\n    }\n\n    \/\/ Use only (last_test, first_metric) for best iteration and overfitting detection\n    \/\/ In case of changing the order it should be changed in GPU mode also.\n    metricsData->ErrorTrackerMetricIdx = 0;\n\n    if (internalOptions.OffsetMetricPeriodByInitModelSize) {\n        metricsData->MetricPeriodOffset = ctx.LearnProgress->GetInitModelTreesSize();\n    } else {\n        metricsData->MetricPeriodOffset = Nothing();\n    }\n}\n\nnamespace {\nstruct TLoggingData {\n    TString LearnToken;\n    TVector<const TString> TestTokens;\n    TLogger Logger;\n};\n}\n\nstatic bool ShouldCalcAllMetrics(ui32 iter, const TMetricsData& metricsData, const TLearnContext& ctx) {\n    const ui32 iterWithOffset = iter + metricsData.MetricPeriodOffset.GetOrElse(0);\n    return ((iterWithOffset + 1) == ctx.Params.BoostingOptions->IterationCount) || \/\/ last iteration\n        !(iterWithOffset % SafeIntegerCast<ui32>(ctx.OutputOptions.GetMetricPeriod()));\n}\n\nstatic bool ShouldCalcErrorTrackerMetric(ui32 iter, const TMetricsData& metricsData, const TLearnContext& ctx) {\n    return ShouldCalcAllMetrics(iter, metricsData, ctx) || metricsData.CalcEvalMetricOnEveryIteration;\n}\n\n\/\/ Write history metrics to loggers, error trackers and get info from per iteration metric based callback.\nstatic void ProcessHistoryMetrics(\n    const TTrainingDataProviders& data,\n    const TLearnContext& ctx,\n    ITrainingCallbacks* trainingCallbacks,\n    TMetricsData* metricsData,\n    TLoggingData* loggingData,\n    bool* continueTraining) {\n\n    loggingData->LearnToken = GetTrainModelLearnToken();\n    loggingData->TestTokens = GetTrainModelTestTokens(data.Test.ysize());\n\n    if (ctx.OutputOptions.AllowWriteFiles()) {\n        InitializeFileLoggers(\n            ctx.Params,\n            ctx.Files,\n            GetConstPointers(metricsData->Metrics),\n            loggingData->LearnToken,\n            loggingData->TestTokens,\n            ctx.OutputOptions.GetMetricPeriod(),\n            &loggingData->Logger);\n    }\n\n    const TVector<TTimeInfo>& timeHistory = ctx.LearnProgress->MetricsAndTimeHistory.TimeHistory;\n    const TVector<TVector<THashMap<TString, double>>>& testMetricsHistory =\n        ctx.LearnProgress->MetricsAndTimeHistory.TestMetricsHistory;\n\n    const bool useBestModel = ctx.OutputOptions.ShrinkModelToBestIteration();\n    *continueTraining = true;\n    for (int iter : xrange(ctx.LearnProgress->GetCurrentTrainingIterationCount())) {\n        if (iter < testMetricsHistory.ysize() && ShouldCalcErrorTrackerMetric(iter, *metricsData, ctx) && metricsData->ErrorTracker) {\n            const TString& errorTrackerMetricDescription = metricsData->Metrics[metricsData->ErrorTrackerMetricIdx]->GetDescription();\n            const double error = testMetricsHistory[iter].back().at(errorTrackerMetricDescription);\n            metricsData->ErrorTracker->AddError(error, iter);\n            if (useBestModel && iter + 1 >= ctx.OutputOptions.BestModelMinTrees) {\n                metricsData->BestModelMinTreesTracker->AddError(error, iter);\n            }\n        }\n\n        Log(iter,\n            GetMetricsDescription(metricsData->Metrics),\n            ctx.LearnProgress->MetricsAndTimeHistory.LearnMetricsHistory,\n            testMetricsHistory,\n            metricsData->ErrorTracker ? TMaybe<double>(metricsData->ErrorTracker->GetBestError()) : Nothing(),\n            metricsData->ErrorTracker ? TMaybe<int>(metricsData->ErrorTracker->GetBestIteration()) : Nothing(),\n            TProfileResults(timeHistory[iter].PassedTime, timeHistory[iter].RemainingTime),\n            loggingData->LearnToken,\n            loggingData->TestTokens,\n            ShouldCalcAllMetrics(iter, *metricsData, ctx),\n            &loggingData->Logger\n        );\n\n        *continueTraining = trainingCallbacks->IsContinueTraining(ctx.LearnProgress->MetricsAndTimeHistory);\n    }\n\n    AddConsoleLogger(\n        loggingData->LearnToken,\n        loggingData->TestTokens,\n        \/*hasTrain=*\/true,\n        ctx.OutputOptions.GetVerbosePeriod(),\n        ctx.Params.BoostingOptions->IterationCount,\n        &loggingData->Logger\n    );\n}\n\nstatic void InitializeSamplingStructures(\n    const TTrainingDataProviders& data,\n    TLearnContext* ctx) {\n\n    const bool isPairwiseScoring = IsPairwiseScoring(ctx->Params.LossFunctionDescription->GetLossFunction());\n    const int defaultCalcStatsObjBlockSize = static_cast<int>(ctx->Params.ObliviousTreeOptions->DevScoreCalcObjBlockSize);\n\n    if (ctx->UseTreeLevelCaching()) {\n        ctx->SmallestSplitSideDocs.Create(\n            ctx->LearnProgress->Folds,\n            isPairwiseScoring,\n            data.EstimatedObjectsData.GetFeatureCount() != 0,\n            defaultCalcStatsObjBlockSize\n        );\n        ctx->PrevTreeLevelStats.Create(\n            ctx->LearnProgress->Folds,\n            CountNonCtrBuckets(\n                *data.Learn->ObjectsData->GetFeaturesLayout(),\n                *data.Learn->ObjectsData->GetQuantizedFeaturesInfo(),\n                ctx->Params.CatFeatureParams->OneHotMaxSize),\n            static_cast<int>(ctx->Params.ObliviousTreeOptions->MaxDepth)\n        );\n    }\n    ctx->SampledDocs.Create(\n        ctx->LearnProgress->Folds,\n        isPairwiseScoring,\n        data.EstimatedObjectsData.GetFeatureCount() != 0,\n        defaultCalcStatsObjBlockSize,\n        GetBernoulliSampleRate(ctx->Params.ObliviousTreeOptions->BootstrapConfig)\n    ); \/\/ TODO(espetrov): create only if sample rate < 1\n}\n\nstatic void LogThatStoppingOccured(const TErrorTracker& errorTracker) {\n    CATBOOST_NOTICE_LOG << \"Stopped by overfitting detector \"\n        << \" (\" << errorTracker.GetOverfittingDetectorIterationsWait() << \" iterations wait)\" << Endl;\n}\n\nstatic void CalcErrors(\n    const TTrainingDataProviders& data,\n    const TMetricsData& metricsData,\n    int iter,\n    TLearnContext* ctx) {\n\n    CalcErrors(data, metricsData.Metrics, ShouldCalcAllMetrics(iter, metricsData, *ctx), ShouldCalcErrorTrackerMetric(iter, metricsData, *ctx), ctx);\n}\n\nstatic void Train(\n    const TTrainModelInternalOptions& internalOptions,\n    const TTrainingDataProviders& data,\n    ITrainingCallbacks* trainingCallbacks,\n    TLearnContext* ctx,\n    TVector<TVector<TVector<double>>>* testMultiApprox \/\/ [test][dim][docIdx]\n) {\n    TProfileInfo& profile = ctx->Profile;\n\n    TMetricsData metricsData;\n    InitializeAndCheckMetricData(internalOptions, data, *ctx, &metricsData);\n\n    const auto onLoadSnapshotCallback = [&] (IInputStream* in) {\n        return trainingCallbacks->OnLoadSnapshot(in);\n    };\n\n    if (ctx->TryLoadProgress(onLoadSnapshotCallback) && ctx->Params.SystemOptions->IsMaster()) {\n        MapRestoreApproxFromTreeStruct(ctx);\n    }\n\n    TLoggingData loggingData;\n    bool continueTraining;\n    ProcessHistoryMetrics(data, *ctx, trainingCallbacks, &metricsData, &loggingData, &continueTraining);\n\n    if (continueTraining) {\n        InitializeSamplingStructures(data, ctx);\n    }\n\n    THPTimer timer;\n\n    const bool useBestModel = ctx->OutputOptions.ShrinkModelToBestIteration();\n    const bool hasTest = data.GetTestSampleCount() > 0;\n    const auto& metrics = metricsData.Metrics;\n    auto& errorTracker = metricsData.ErrorTracker;\n    const auto onSaveSnapshotCallback = [&] (IOutputStream* out) {\n        trainingCallbacks->OnSaveSnapshot(out);\n    };\n\n    for (ui32 iter = ctx->LearnProgress->GetCurrentTrainingIterationCount();\n         continueTraining && (iter < ctx->Params.BoostingOptions->IterationCount);\n         ++iter)\n\n    {\n        if (errorTracker && errorTracker->GetIsNeedStop()) {\n            LogThatStoppingOccured(*errorTracker);\n            break;\n        }\n\n        profile.StartNextIteration();\n\n        if (timer.Passed() > ctx->OutputOptions.GetSnapshotSaveInterval()) {\n            profile.AddOperation(\"Save snapshot\");\n            ctx->SaveProgress(onSaveSnapshotCallback);\n            timer.Reset();\n        }\n\n        TrainOneIteration(data, ctx);\n\n        CalcErrors(data, metricsData, iter, ctx);\n\n        profile.AddOperation(\"Calc errors\");\n\n        if (hasTest && ShouldCalcErrorTrackerMetric(iter, metricsData, *ctx) && errorTracker) {\n            const auto testErrors = ctx->LearnProgress->MetricsAndTimeHistory.TestMetricsHistory.back();\n            const TString& errorTrackerMetricDescription = metrics[metricsData.ErrorTrackerMetricIdx]->GetDescription();\n            \/\/ it is possible that metric has not been calculated because it requires target data\n            \/\/ that is absent\n            if (!testErrors.empty()) {\n                const double* error = MapFindPtr(testErrors.back(), errorTrackerMetricDescription);\n                if (error) {\n                    errorTracker->AddError(*error, iter);\n                    if (useBestModel && iter == static_cast<ui32>(errorTracker->GetBestIteration())) {\n                        ctx->LearnProgress->BestTestApprox = ctx->LearnProgress->TestApprox.back();\n                    }\n                    if (useBestModel && static_cast<int>(iter + 1) >= ctx->OutputOptions.BestModelMinTrees) {\n                        metricsData.BestModelMinTreesTracker->AddError(*error, iter);\n                    }\n                }\n            }\n        }\n\n        profile.FinishIteration();\n\n        const TProfileResults profileResults = profile.GetProfileResults();\n        ctx->LearnProgress->MetricsAndTimeHistory.TimeHistory.emplace_back(profileResults);\n\n        Log(\n            iter,\n            GetMetricsDescription(metrics),\n            ctx->LearnProgress->MetricsAndTimeHistory.LearnMetricsHistory,\n            ctx->LearnProgress->MetricsAndTimeHistory.TestMetricsHistory,\n            errorTracker ? TMaybe<double>(errorTracker->GetBestError()) : Nothing(),\n            errorTracker ? TMaybe<int>(errorTracker->GetBestIteration()) : Nothing(),\n            profileResults,\n            loggingData.LearnToken,\n            loggingData.TestTokens,\n            ShouldCalcAllMetrics(iter, metricsData, *ctx),\n            &loggingData.Logger\n        );\n\n        if (HasInvalidValues(ctx->LearnProgress->LeafValues.back())) {\n            ctx->LearnProgress->LeafValues.pop_back();\n            ctx->LearnProgress->TreeStruct.pop_back();\n            if (!ctx->LearnProgress->ModelShrinkHistory.empty()) {\n                ctx->LearnProgress->ModelShrinkHistory.pop_back();\n            }\n            CATBOOST_WARNING_LOG << \"Training has stopped (degenerate solution on iteration \"\n                << iter << \", probably too small l2-regularization, try to increase it)\" << Endl;\n            break;\n        }\n\n        continueTraining = trainingCallbacks->IsContinueTraining(ctx->LearnProgress->MetricsAndTimeHistory);\n    }\n\n    ctx->SaveProgress(onSaveSnapshotCallback);\n\n    if (hasTest) {\n        (*testMultiApprox) = ctx->LearnProgress->TestApprox;\n        if (useBestModel) {\n            (*testMultiApprox)[0] = ctx->LearnProgress->BestTestApprox;\n        }\n    }\n\n    if (hasTest && errorTracker) {\n        CATBOOST_NOTICE_LOG << \"\\n\";\n        CATBOOST_NOTICE_LOG << \"bestTest = \" << errorTracker->GetBestError() << \"\\n\";\n        CATBOOST_NOTICE_LOG << \"bestIteration = \" << errorTracker->GetBestIteration() << \"\\n\";\n        CATBOOST_NOTICE_LOG << \"\\n\";\n    }\n\n    if (useBestModel && metricsData.BestModelMinTreesTracker && ctx->Params.BoostingOptions->IterationCount > 0) {\n        const int bestModelIterations = metricsData.BestModelMinTreesTracker->GetBestIteration() + 1;\n        if (0 < bestModelIterations && bestModelIterations < static_cast<int>(ctx->Params.BoostingOptions->IterationCount)) {\n            CATBOOST_NOTICE_LOG << \"Shrink model to first \" << bestModelIterations << \" iterations.\";\n            if (errorTracker->GetBestIteration() + 1 < ctx->OutputOptions.BestModelMinTrees) {\n                CATBOOST_NOTICE_LOG << \" (min iterations for best model = \" << ctx->OutputOptions.BestModelMinTrees << \")\";\n            }\n            CATBOOST_NOTICE_LOG << Endl;\n            ShrinkModel(bestModelIterations, ctx->CtrsHelper, ctx->LearnProgress.Get());\n        }\n    }\n\n    if (!ctx->LearnProgress->ModelShrinkHistory.empty()) {\n        const int treeCount = ctx->LearnProgress->ModelShrinkHistory.size();\n        Y_ASSERT(SafeIntegerCast<int>(ctx->LearnProgress->LeafValues.size()) == treeCount);\n        double accumulatedTreeShrinkage = 1.0;\n        for (int treeIndex = treeCount - 1; treeIndex >= 0; --treeIndex) {\n            auto& treeLeafValues = ctx->LearnProgress->LeafValues[treeIndex];\n            treeLeafValues = ScaleElementwise(accumulatedTreeShrinkage, treeLeafValues);\n            accumulatedTreeShrinkage *= ctx->LearnProgress->ModelShrinkHistory[treeIndex];\n        }\n    }\n}\n\n\nstatic THolder<TNonSymmetricTreeNode> BuildTree(\n    int nodeIdx,\n    TConstArrayRef<TSplitNode> nodes,\n    TConstArrayRef<TVector<double>> leafValues,\n    TConstArrayRef<double> leafWeights,\n    std::function<TModelSplit(TSplit)> getModelSplit\n) {\n    auto finalNode = MakeHolder<TNonSymmetricTreeNode>();\n    if (nodeIdx < 0) {\n        int leafIdx = ~nodeIdx;\n        if (leafValues.size() == 1) {\n            finalNode->Value = leafValues[0][leafIdx];\n        } else {\n            TVector<double> value(leafValues.size());\n            for (auto dim : xrange(leafValues.size())) {\n                value[dim] = leafValues[dim][leafIdx];\n            }\n            finalNode->Value = std::move(value);\n        }\n        finalNode->NodeWeight = leafWeights[leafIdx];\n    } else {\n        const auto& node = nodes[nodeIdx];\n        finalNode->SplitCondition = getModelSplit(node.Split);\n        finalNode->Left = BuildTree(node.Left, nodes, leafValues, leafWeights, getModelSplit);\n        finalNode->Right = BuildTree(node.Right, nodes, leafValues, leafWeights, getModelSplit);\n    }\n    return finalNode;\n}\n\n\nstatic void SaveModel(\n    const TTrainingDataProviders& trainingDataForCpu,\n    const TLearnContext& ctx,\n    TMaybe<TFullModel*> initModel,\n    TMaybe<ui32> initLearnProgressLearnAndTestQuantizedFeaturesCheckSum,\n    TFullModel* dstModel\n) {\n    const auto& target = ctx.LearnProgress->AveragingFold.LearnTarget;\n    const TQuantizedFeaturesInfo& quantizedFeaturesInfo\n        = *(trainingDataForCpu.Learn->ObjectsData->GetQuantizedFeaturesInfo());\n\n    TPerfectHashedToHashedCatValuesMap perfectHashedToHashedCatValuesMap\n        = quantizedFeaturesInfo.CalcPerfectHashedToHashedCatValuesMap(ctx.LocalExecutor);\n    if (ctx.OutputOptions.AllowWriteFiles()) {\n        TString tmpDir;\n        NCB::NPrivate::CreateTrainDirWithTmpDirIfNotExist(ctx.OutputOptions.GetTrainDir(), &tmpDir);\n        quantizedFeaturesInfo.UnloadCatFeaturePerfectHashFromRam(tmpDir);\n    }\n\n    const TQuantizedEstimatedFeaturesInfo onlineQuantizedEstimatedFeaturesInfo\n        = ctx.LearnProgress->GetOnlineEstimatedFeaturesInfo();\n\n    TModelTrees modelTrees;\n    THashMap<TFeatureCombination, TProjection> featureCombinationToProjectionMap;\n    const std::function<TModelSplit(TSplit)> getModelSplit = [&] (const TSplit& split) {\n        auto modelSplit = split.GetModelSplit(\n            ctx,\n            perfectHashedToHashedCatValuesMap,\n            *trainingDataForCpu.FeatureEstimators,\n            trainingDataForCpu.EstimatedObjectsData.QuantizedEstimatedFeaturesInfo,\n            onlineQuantizedEstimatedFeaturesInfo\n        );\n        if (modelSplit.Type == ESplitType::OnlineCtr) {\n            featureCombinationToProjectionMap[modelSplit.OnlineCtr.Ctr.Base.Projection] = split.Ctr.Projection;\n        }\n        return modelSplit;\n    };\n    if (ctx.Params.ObliviousTreeOptions->GrowPolicy == EGrowPolicy::SymmetricTree) {\n        TObliviousTreeBuilder builder(\n            ctx.LearnProgress->FloatFeatures,\n            ctx.LearnProgress->CatFeatures,\n            ctx.LearnProgress->TextFeatures,\n            ctx.LearnProgress->ApproxDimension);\n        for (size_t treeId = 0; treeId < ctx.LearnProgress->TreeStruct.size(); ++treeId) {\n            TVector<TModelSplit> modelSplits;\n            Y_ASSERT(HoldsAlternative<TSplitTree>(ctx.LearnProgress->TreeStruct[treeId]));\n            TVector<TSplit> splits = Get<TSplitTree>(ctx.LearnProgress->TreeStruct[treeId]).Splits;\n            for (const auto& split : splits) {\n                modelSplits.push_back(getModelSplit(split));\n            }\n            builder.AddTree(modelSplits, ctx.LearnProgress->LeafValues[treeId], ctx.LearnProgress->TreeStats[treeId].LeafWeightsSum);\n        }\n        builder.Build(&modelTrees);\n    } else {\n        TNonSymmetricTreeModelBuilder builder(\n            ctx.LearnProgress->FloatFeatures,\n            ctx.LearnProgress->CatFeatures,\n            ctx.LearnProgress->TextFeatures,\n            ctx.LearnProgress->ApproxDimension);\n        for (size_t treeId = 0; treeId < ctx.LearnProgress->TreeStruct.size(); ++treeId) {\n            Y_ASSERT(HoldsAlternative<TNonSymmetricTreeStructure>(ctx.LearnProgress->TreeStruct[treeId]));\n            const auto& structure = Get<TNonSymmetricTreeStructure>(ctx.LearnProgress->TreeStruct[treeId]);\n            auto tree = BuildTree(\n                structure.GetRoot(),\n                structure.GetNodes(),\n                ctx.LearnProgress->LeafValues[treeId],\n                ctx.LearnProgress->TreeStats[treeId].LeafWeightsSum,\n                getModelSplit);\n            builder.AddTree(std::move(tree));\n        }\n        builder.Build(&modelTrees);\n    }\n\n\n\/\/    TODO(kirillovs,espetrov): return this code after fixing R and Python wrappers\n\/\/    for (auto& oheFeature : modelTrees.OneHotFeatures) {\n\/\/        for (const auto& value : oheFeature.Values) {\n\/\/            oheFeature.StringValues.push_back(pools.Learn->CatFeaturesHashToString.at(value));\n\/\/        }\n\/\/    }\n    TClassificationTargetHelper classificationTargetHelper(\n        ctx.LearnProgress->LabelConverter,\n        ctx.Params.DataProcessingOptions\n    );\n\n    TDatasetDataForFinalCtrs datasetDataForFinalCtrs;\n    datasetDataForFinalCtrs.Data = trainingDataForCpu;\n    datasetDataForFinalCtrs.LearnPermutation = &ctx.LearnProgress->AveragingFold.LearnPermutation->GetObjectsIndexing();\n    if (target.size() == 1) { \/\/ since counters are not implemented for multi-dimensional target\n        datasetDataForFinalCtrs.Targets = target[0];\n    }\n    datasetDataForFinalCtrs.LearnTargetClass = &ctx.LearnProgress->AveragingFold.LearnTargetClass;\n    datasetDataForFinalCtrs.TargetClassesCount = &ctx.LearnProgress->AveragingFold.TargetClassesCount;\n\n    {\n        const bool addResultModelToInitModel = ctx.LearnProgress->SeparateInitModelTreesSize != 0;\n\n        TMaybe<TFullModel> fullModel;\n        TFullModel* modelPtr = nullptr;\n        if (dstModel && !addResultModelToInitModel) {\n            modelPtr = dstModel;\n        } else {\n            fullModel.ConstructInPlace();\n            modelPtr = &*fullModel;\n        }\n\n        *modelPtr->ModelTrees.GetMutable() = std::move(modelTrees);\n        modelPtr->SetScaleAndBias({1, ctx.LearnProgress->StartingApprox.GetOrElse({})});\n        modelPtr->UpdateDynamicData();\n\n        EFinalFeatureCalcersComputationMode featureCalcerComputationMode\n            = ctx.OutputOptions.GetFinalFeatureCalcerComputationMode();\n        if (modelPtr->ModelTrees->GetTextFeatures().empty() ||\n            modelPtr->ModelTrees->GetEstimatedFeatures().empty()\n        ) {\n            featureCalcerComputationMode = EFinalFeatureCalcersComputationMode::Skip;\n        }\n\n        NCB::TCoreModelToFullModelConverter coreModelToFullModelConverter(\n            ctx.Params,\n            ctx.OutputOptions,\n            classificationTargetHelper,\n            ctx.Params.CatFeatureParams->CtrLeafCountLimit,\n            ctx.Params.CatFeatureParams->StoreAllSimpleCtrs,\n            ctx.OutputOptions.GetFinalCtrComputationMode(),\n            featureCalcerComputationMode\n        );\n\n        coreModelToFullModelConverter.WithBinarizedDataComputedFrom(\n            std::move(datasetDataForFinalCtrs),\n            std::move(featureCombinationToProjectionMap)\n        ).WithPerfectHashedToHashedCatValuesMap(\n            &perfectHashedToHashedCatValuesMap\n        ).WithCoreModelFrom(\n            modelPtr\n        ).WithObjectsDataFrom(\n            trainingDataForCpu.Learn->ObjectsData\n        ).WithFeatureEstimators(\n            trainingDataForCpu.FeatureEstimators\n        );\n\n        if (dstModel || addResultModelToInitModel) {\n            coreModelToFullModelConverter.Do(true, modelPtr, ctx.LocalExecutor);\n            if (addResultModelToInitModel) {\n                TVector<const TFullModel*> models = {*initModel, modelPtr};\n                TVector<double> weights = {1.0, 1.0};\n                (dstModel ? *dstModel : *modelPtr) = SumModels(models, weights);\n\n                if (!dstModel) {\n                    const bool allLearnObjectsDataIsAvailable\n                        = initLearnProgressLearnAndTestQuantizedFeaturesCheckSum &&\n                            (*initLearnProgressLearnAndTestQuantizedFeaturesCheckSum ==\n                             ctx.LearnProgress->LearnAndTestQuantizedFeaturesCheckSum);\n\n                    ExportFullModel(\n                        *modelPtr,\n                        ctx.OutputOptions.CreateResultModelFullPath(),\n                        allLearnObjectsDataIsAvailable ?\n                            TMaybe<TObjectsDataProvider*>(trainingDataForCpu.Learn->ObjectsData.Get()) :\n                            Nothing(),\n                        ctx.OutputOptions.GetModelFormats(),\n                        ctx.OutputOptions.AddFileFormatExtension()\n                    );\n                }\n            }\n        } else if (!dstModel) {\n            coreModelToFullModelConverter.Do(\n                ctx.OutputOptions.CreateResultModelFullPath(),\n                ctx.OutputOptions.GetModelFormats(),\n                ctx.OutputOptions.AddFileFormatExtension(),\n                ctx.LocalExecutor\n            );\n        }\n    }\n}\n\n\nnamespace {\n    class TCPUModelTrainer : public IModelTrainer {\n\n        void TrainModel(\n            const TTrainModelInternalOptions& internalOptions,\n            const NCatboostOptions::TCatBoostOptions& catboostOptions,\n            const NCatboostOptions::TOutputFilesOptions& outputOptions,\n            const TMaybe<TCustomObjectiveDescriptor>& objectiveDescriptor,\n            const TMaybe<TCustomMetricDescriptor>& evalMetricDescriptor,\n            TTrainingDataProviders trainingData,\n            const TLabelConverter& labelConverter,\n            ITrainingCallbacks* trainingCallbacks,\n            TMaybe<TFullModel*> initModel,\n            THolder<TLearnProgress> initLearnProgress,\n            TDataProviders initModelApplyCompatiblePools,\n            NPar::TLocalExecutor* localExecutor,\n            const TMaybe<TRestorableFastRng64*> rand,\n            TFullModel* dstModel,\n            const TVector<TEvalResult*>& evalResultPtrs,\n            TMetricsAndTimeLeftHistory* metricsAndTimeHistory,\n            THolder<TLearnProgress>* dstLearnProgress\n        ) const override {\n            if (!internalOptions.CalcMetricsOnly) {\n                if (dstModel != nullptr) {\n                    CB_ENSURE(\n                        !outputOptions.ResultModelPath.IsSet(),\n                        \"Both dstModel != nullptr and ResultModelPath is set\"\n                    );\n                } else {\n                    CB_ENSURE(\n                        !outputOptions.ResultModelPath.Get().empty(),\n                        \"Both dstModel == nullptr and ResultModelPath is empty\"\n                    );\n                }\n            }\n\n            trainingData.Learn->ObjectsData->CheckCPUTrainCompatibility();\n            for (auto& test : trainingData.Test) {\n                test->ObjectsData->CheckCPUTrainCompatibility();\n            }\n\n            const TString trainingOptionsFileName = outputOptions.CreateTrainingOptionsFullPath();\n            if (!trainingOptionsFileName.empty()) {\n                TOFStream trainingOptionsFile(trainingOptionsFileName);\n                trainingOptionsFile.Write(NJson::PrettifyJson(ToString(catboostOptions)));\n            }\n\n            \/\/ need to save it because initLearnProgress is moved to TLearnContext\n            TMaybe<ui32> initLearnProgressLearnAndTestQuantizedFeaturesCheckSum;\n            if (initLearnProgress) {\n                initLearnProgressLearnAndTestQuantizedFeaturesCheckSum = initLearnProgress->LearnAndTestQuantizedFeaturesCheckSum;\n            }\n\n            if (catboostOptions.BoostingOptions->BoostFromAverage.Get()) {\n                CB_ENSURE(!initModel, \"You can't use boost_from_average with initial model now.\");\n                CB_ENSURE(!trainingData.Learn->TargetData->GetBaseline(), \"You can't use boost_from_average with baseline now.\");\n                for (ui32 testIdx = 0; testIdx < trainingData.Test.size(); ++testIdx) {\n                    CB_ENSURE(!trainingData.Test[testIdx]->TargetData->GetBaseline(), \"You can't use boost_from_average with baseline now.\");\n                }\n            }\n\n            if (catboostOptions.BoostingOptions->ModelShrinkRate.Get() != 0.0f) {\n                CB_ENSURE(!initModel,\n                    \"Usage of model_shrink_rate option in combination with learning continuation is unimplemented yet.\"\n                );\n                auto errMessage = \"Usage of model_shrink_rate option in combination with baseline is unimplemented yet.\";\n                CB_ENSURE(!trainingData.Learn->TargetData->GetBaseline(), errMessage);\n                for (ui32 testIdx = 0; testIdx < trainingData.Test.size(); ++testIdx) {\n                    CB_ENSURE(!trainingData.Test[testIdx]->TargetData->GetBaseline(), errMessage);\n                }\n            }\n\n            TMaybe<TVector<double>> startingApprox;\n            if (catboostOptions.BoostingOptions->BoostFromAverage.Get()) {\n                \/\/ TODO(fedorlebed): add boost from average support for multiregression\n                CB_ENSURE(trainingData.Learn->TargetData->GetTargetDimension() != 0, \"Target is required for boosting from average\");\n                CB_ENSURE(trainingData.Learn->TargetData->GetTargetDimension() == 1, \"Multi-dimensional target boosting from average is unimplemented yet\");\n\n                startingApprox = CalcOptimumConstApprox(\n                    catboostOptions.LossFunctionDescription,\n                    *trainingData.Learn->TargetData->GetOneDimensionalTarget(),\n                    GetWeights(*trainingData.Learn->TargetData)\n                );\n            } else {\n                if (catboostOptions.LossFunctionDescription->GetLossFunction() == ELossFunction::RMSEWithUncertainty) {\n                    startingApprox = CalcOptimumConstApprox(\n                        catboostOptions.LossFunctionDescription,\n                        *trainingData.Learn->TargetData->GetOneDimensionalTarget(),\n                        GetWeights(*trainingData.Learn->TargetData)\n                    );\n                }\n            }\n            TLearnContext ctx(\n                catboostOptions,\n                objectiveDescriptor,\n                evalMetricDescriptor,\n                outputOptions,\n                trainingData,\n                labelConverter,\n                startingApprox,\n                rand,\n                std::move(initModel),\n                std::move(initLearnProgress),\n                std::move(initModelApplyCompatiblePools),\n                localExecutor\n            );\n\n            DumpMemUsage(\"Before start train\");\n\n            const auto& systemOptions = ctx.Params.SystemOptions;\n            if (!systemOptions->IsSingleHost()) { \/\/ send target, weights, baseline (if present), binarized features to workers and ask them to create plain folds\n                CB_ENSURE(IsPlainMode(ctx.Params.BoostingOptions->BoostingType), \"Distributed training requires plain boosting\");\n                CB_ENSURE(!ctx.Layout->GetCatFeatureCount(), \"Distributed training doesn't support categorical features\");\n                MapBuildPlainFold(&ctx);\n            }\n            TVector<TVector<double>> oneRawValues(ctx.LearnProgress->ApproxDimension);\n            TVector<TVector<TVector<double>>> rawValues(trainingData.Test.size(), oneRawValues);\n\n            Train(internalOptions, trainingData, trainingCallbacks, &ctx, &rawValues);\n\n            if (!dstLearnProgress) {\n                \/\/ Save memory as it is no longer needed\n                ctx.LearnProgress->Folds.clear();\n            }\n\n            for (int testIdx = 0; testIdx < trainingData.Test.ysize(); ++testIdx) {\n                evalResultPtrs[testIdx]->SetRawValuesByMove(rawValues[testIdx]);\n            }\n\n            if (metricsAndTimeHistory) {\n                *metricsAndTimeHistory = ctx.LearnProgress->MetricsAndTimeHistory;\n            }\n\n            if (!internalOptions.CalcMetricsOnly) {\n                SaveModel(\n                    trainingData,\n                    ctx,\n                    initModel,\n                    initLearnProgressLearnAndTestQuantizedFeaturesCheckSum,\n                    dstModel);\n            }\n            if (dstLearnProgress) {\n                ctx.LearnProgress->PrepareForContinuation();\n                *dstLearnProgress = std::move(ctx.LearnProgress);\n            }\n        }\n\n        void ModelBasedEval(\n            const NCatboostOptions::TCatBoostOptions& \/*catboostOptions*\/,\n            const NCatboostOptions::TOutputFilesOptions& \/*outputOptions*\/,\n            TTrainingDataProviders \/*trainingData*\/,\n            const TLabelConverter& \/*labelConverter*\/,\n            NPar::TLocalExecutor* \/*localExecutor*\/) const override {\n            CB_ENSURE(false, \"Model based eval is not implemented for CPU\");\n        }\n    };\n\n}\n\nTTrainerFactory::TRegistrator<TCPUModelTrainer> CPURegistrator(ETaskType::CPU);\n\nstatic bool HaveLearnFeaturesInMemory(\n    const NCatboostOptions::TPoolLoadParams* loadOptions,\n    const NCatboostOptions::TCatBoostOptions& catBoostOptions\n) {\n    #if defined(USE_MPI)\n    const bool isGpuDistributed = catBoostOptions.GetTaskType() == ETaskType::GPU;\n    #else\n    const bool isGpuDistributed = false;\n    #endif\n    const bool isCpuDistributed = catBoostOptions.SystemOptions->IsMaster();\n    if (!isCpuDistributed && !isGpuDistributed) {\n        return true;\n    }\n    if (loadOptions == nullptr) {\n        return true;\n    }\n    const auto& learnSetPath = loadOptions->LearnSetPath;\n    const bool isQuantized = learnSetPath.Scheme.find(\"quantized\") != std::string::npos;\n    return !IsSharedFs(learnSetPath) || !isQuantized;\n}\n\nstatic void TrainModel(\n    const NJson::TJsonValue& trainOptionsJson,\n    const NCatboostOptions::TOutputFilesOptions& outputOptions,\n    TQuantizedFeaturesInfoPtr quantizedFeaturesInfo,\n    const TMaybe<TCustomObjectiveDescriptor>& objectiveDescriptor,\n    const TMaybe<TCustomMetricDescriptor>& evalMetricDescriptor,\n    TDataProviders pools,\n    TMaybe<TFullModel*> initModel,\n    THolder<TLearnProgress> initLearnProgress,\n    const NCatboostOptions::TPoolLoadParams* poolLoadOptions,\n    const TString& outputModelPath,\n    TFullModel* dstModel,\n    const TVector<TEvalResult*>& evalResultPtrs,\n    TMetricsAndTimeLeftHistory* metricsAndTimeHistory,\n    THolder<TLearnProgress>* dstLearnProgress,\n    NPar::TLocalExecutor* const executor)\n{\n    CB_ENSURE(pools.Learn != nullptr, \"Train data must be provided\");\n    CB_ENSURE(pools.Test.size() == evalResultPtrs.size());\n\n    THolder<IModelTrainer> modelTrainerHolder;\n\n    const ETaskType taskType = NCatboostOptions::GetTaskType(trainOptionsJson);\n\n    CB_ENSURE(\n        (taskType == ETaskType::CPU) || (pools.Test.size() <= 1),\n        \"Multiple eval sets not supported for GPU\"\n    );\n\n    NCatboostOptions::TOutputFilesOptions updatedOutputOptions(outputOptions);\n    if (outputModelPath) {\n        updatedOutputOptions.ResultModelPath = outputModelPath;\n    }\n\n    NJson::TJsonValue updatedTrainOptionsJson = trainOptionsJson;\n\n    const bool isGpuDeviceType = taskType == ETaskType::GPU;\n    if (isGpuDeviceType && TTrainerFactory::Has(ETaskType::GPU)) {\n        modelTrainerHolder.Reset(TTrainerFactory::Construct(ETaskType::GPU));\n    } else {\n        CB_ENSURE(!isGpuDeviceType, \"Can't load GPU learning library. Module was not compiled or driver  is incompatible with package. Please install latest NVDIA driver and check again\");\n        modelTrainerHolder.Reset(TTrainerFactory::Construct(ETaskType::CPU));\n    }\n\n    if (outputOptions.SaveSnapshot()) {\n        UpdateUndefinedRandomSeed(taskType, updatedOutputOptions, &updatedTrainOptionsJson, [&](IInputStream* in, TString& params) {\n            ::Load(in, params);\n        });\n    }\n\n    const auto learnFeaturesLayout = pools.Learn->MetaInfo.FeaturesLayout;\n\n    NCatboostOptions::TCatBoostOptions catBoostOptions(taskType);\n    catBoostOptions.Load(updatedTrainOptionsJson);\n\n    if (!quantizedFeaturesInfo) {\n        quantizedFeaturesInfo = MakeIntrusive<TQuantizedFeaturesInfo>(\n            *learnFeaturesLayout,\n            catBoostOptions.DataProcessingOptions.Get().IgnoredFeatures.Get(),\n            catBoostOptions.DataProcessingOptions->FloatFeaturesBinarization.Get(),\n            catBoostOptions.DataProcessingOptions->PerFloatFeatureQuantization.Get(),\n            catBoostOptions.DataProcessingOptions->TextProcessingOptions.Get(),\n            catBoostOptions.DataProcessingOptions->EmbeddingProcessingOptions.Get(),\n            \/*allowNansInTestOnly*\/true\n        );\n        \/* TODO(akhropov): reuse float features quantization data from initLearnProgress if data quantization\n         * options and raw data is the same\n         *\/\n    }\n\n    for (auto testPoolIdx : xrange(pools.Test.size())) {\n        const auto& testPool = *pools.Test[testPoolIdx];\n        if (testPool.GetObjectCount() == 0) {\n            continue;\n        }\n        CheckCompatibleForApply(\n            *learnFeaturesLayout,\n            *testPool.MetaInfo.FeaturesLayout,\n            TStringBuilder() << \"test dataset #\" << testPoolIdx);\n    }\n\n    if (updatedOutputOptions.GetVerbosePeriod() == 0 && catBoostOptions.LoggingLevel.NotSet()) {\n        catBoostOptions.LoggingLevel.SetDefault(ELoggingLevel::Silent);\n    }\n\n    TSetLogging inThisScope(catBoostOptions.LoggingLevel);\n\n    auto learnDataOrder = pools.Learn->ObjectsData->GetOrder();\n    if (learnDataOrder == EObjectsOrder::Ordered) {\n        catBoostOptions.DataProcessingOptions->HasTimeFlag = true;\n    }\n\n    pools.Learn = ReorderByTimestampLearnDataIfNeeded(catBoostOptions, pools.Learn, executor);\n\n    TRestorableFastRng64 rand(catBoostOptions.RandomSeed.Get());\n\n    pools.Learn = ShuffleLearnDataIfNeeded(catBoostOptions, pools.Learn, executor, &rand);\n\n    TLabelConverter labelConverter;\n\n    const bool needInitModelApplyCompatiblePools = initModel.Defined();\n\n    TString tmpDir;\n    if (outputOptions.AllowWriteFiles()) {\n        NCB::NPrivate::CreateTrainDirWithTmpDirIfNotExist(outputOptions.GetTrainDir(), &tmpDir);\n    }\n\n    const bool haveLearnFeaturesInMemory = HaveLearnFeaturesInMemory(poolLoadOptions, catBoostOptions);\n    CB_ENSURE_INTERNAL(\n        haveLearnFeaturesInMemory || poolLoadOptions, \"Learn dataset is not loaded, and load options are not provided\");\n    TTrainingDataProviders trainingData = GetTrainingData(\n        needInitModelApplyCompatiblePools ? pools : std::move(pools),\n        \/* borders *\/ Nothing(), \/\/ borders are already loaded to quantizedFeaturesInfo\n        \/*ensureConsecutiveIfDenseLearnFeaturesDataForCpu*\/ haveLearnFeaturesInMemory,\n        outputOptions.AllowWriteFiles(),\n        tmpDir,\n        quantizedFeaturesInfo,\n        &catBoostOptions,\n        &labelConverter,\n        executor,\n        &rand,\n        initModel);\n    if (catBoostOptions.SystemOptions->IsMaster()) {\n        InitializeMaster(catBoostOptions.SystemOptions);\n        if (!haveLearnFeaturesInMemory) {\n            SetTrainDataFromQuantizedPool(\n                *poolLoadOptions,\n                catBoostOptions,\n                *trainingData.Learn->ObjectsGrouping,\n                *trainingData.Learn->MetaInfo.FeaturesLayout,\n                &rand\n            );\n        } else {\n            SetTrainDataFromMaster(\n                trainingData,\n                ParseMemorySizeDescription(catBoostOptions.SystemOptions->CpuUsedRamLimit.Get()),\n                executor\n            );\n        }\n    }\n\n    CheckConsistency(trainingData);\n\n    SetDataDependentDefaults(\n        trainingData.Learn->MetaInfo,\n        trainingData.Test.size() > 0 ?\n            TMaybe<NCB::TDataMetaInfo>(trainingData.Test[0]->MetaInfo) :\n            Nothing(),\n        initModel.Defined(),\n        !!initLearnProgress,\n        &updatedOutputOptions.UseBestModel,\n        &catBoostOptions\n    );\n\n    CB_ENSURE(\n        haveLearnFeaturesInMemory || catBoostOptions.BoostingOptions->BoostingType == EBoostingType::Plain,\n        \"Only plain boosting is supported in distributed training for schema \" << poolLoadOptions->LearnSetPath.Scheme);\n\n    \/\/ Eval metric may not be set. If that's the case, we assign it to objective metric\n    InitializeEvalMetricIfNotSet(catBoostOptions.MetricOptions->ObjectiveMetric, &catBoostOptions.MetricOptions->EvalMetric);\n\n    if (outputOptions.NeedSaveBorders()) {\n        SaveBordersAndNanModesToFileInMatrixnetFormat(\n            outputOptions.CreateOutputBordersFullPath(),\n            *trainingData.Learn->ObjectsData->GetQuantizedFeaturesInfo());\n    }\n\n    const auto defaultTrainingCallbacks = MakeHolder<ITrainingCallbacks>();\n    modelTrainerHolder->TrainModel(\n        TTrainModelInternalOptions(),\n        catBoostOptions,\n        updatedOutputOptions,\n        objectiveDescriptor,\n        evalMetricDescriptor,\n        std::move(trainingData),\n        labelConverter,\n        defaultTrainingCallbacks.Get(),\n        std::move(initModel),\n        std::move(initLearnProgress),\n        needInitModelApplyCompatiblePools ? std::move(pools) : TDataProviders(),\n        executor,\n        &rand,\n        dstModel,\n        evalResultPtrs,\n        metricsAndTimeHistory,\n        dstLearnProgress);\n}\n\n\nvoid TrainModel(\n    const NCatboostOptions::TPoolLoadParams& loadOptions,\n    const NCatboostOptions::TOutputFilesOptions& outputOptions,\n    const NJson::TJsonValue& trainJson\n) {\n    THPTimer runTimer;\n    auto catBoostOptions = NCatboostOptions::LoadOptions(trainJson);\n\n    TSetLogging inThisScope(catBoostOptions.LoggingLevel);\n\n    TProfileInfo profile;\n\n    CB_ENSURE(\n        (catBoostOptions.GetTaskType() == ETaskType::CPU) || (loadOptions.TestSetPaths.size() <= 1),\n        \"Multiple eval sets not supported for GPU\"\n    );\n\n    CB_ENSURE(\n        !(loadOptions.CvParams.FoldCount != 0 && catBoostOptions.GetTaskType() == ETaskType::CPU && catBoostOptions.SystemOptions->IsMaster()),\n        \"Distributed training on CPU does not support test and train datasests specified by cross validation options\"\n    );\n\n    const auto evalOutputFileName = outputOptions.CreateEvalFullPath();\n\n    const auto fstrRegularFileName = outputOptions.CreateFstrRegularFullPath();\n    const auto fstrInternalFileName = outputOptions.CreateFstrIternalFullPath();\n    bool needFstr = !fstrInternalFileName.empty() || !fstrRegularFileName.empty();\n\n    auto modelFormat = outputOptions.GetModelFormats()[0];\n    for (int formatIdx = 1; !IsDeserializableModelFormat(modelFormat) && formatIdx < outputOptions.GetModelFormats().ysize(); ++formatIdx) {\n        modelFormat = outputOptions.GetModelFormats()[formatIdx];\n    }\n    if (!evalOutputFileName.empty()) {\n        CB_ENSURE(\n            IsDeserializableModelFormat(modelFormat),\n            \"All chosen model formats not supported deserialization. Add CatboostBinary model-format to save eval-file.\"\n        );\n    }\n    if (needFstr) {\n        CB_ENSURE(\n            IsDeserializableModelFormat(modelFormat),\n            \"All chosen model formats not supported deserialization. Add CatboostBinary model-format to calc fstr.\"\n        );\n    }\n\n\n    NPar::TLocalExecutor executor;\n    executor.RunAdditionalThreads(catBoostOptions.SystemOptions.Get().NumThreads.Get() - 1);\n\n    TVector<NJson::TJsonValue> classLabels = catBoostOptions.DataProcessingOptions->ClassLabels;\n    const auto objectsOrder = catBoostOptions.DataProcessingOptions->HasTimeFlag.Get() ?\n        EObjectsOrder::Ordered : EObjectsOrder::Undefined;\n\n    auto lossFunction = catBoostOptions.LossFunctionDescription->GetLossFunction();\n    auto fstrType = AdjustFeatureImportanceType(outputOptions.GetFstrType(), lossFunction);\n    const bool isLossFunctionChangeFstr = needFstr && fstrType == EFstrType::LossFunctionChange;\n\n    const bool haveLearnFeaturesInMemory = HaveLearnFeaturesInMemory(&loadOptions, catBoostOptions);\n    if (needFstr && !haveLearnFeaturesInMemory && fstrType != EFstrType::PredictionValuesChange) {\n        const auto& pathScheme = loadOptions.LearnSetPath.Scheme;\n        CB_ENSURE(\n            !outputOptions.IsFstrTypeSet(),\n            \"Only fstr type \" << EFstrType::PredictionValuesChange << \" is supported in distributed training for schema \" << pathScheme);\n        CATBOOST_WARNING_LOG << \"Recommended fstr type \" << fstrType << \" is not supported in distributed training for schema \"\n            << pathScheme << \";\" << \" fstr type is set to \" << EFstrType::PredictionValuesChange << Endl;\n        fstrType = EFstrType::PredictionValuesChange;\n    }\n\n    TDataProviders pools = LoadPools(\n        loadOptions,\n        catBoostOptions.GetTaskType(),\n        ParseMemorySizeDescription(catBoostOptions.SystemOptions->CpuUsedRamLimit.Get()),\n        objectsOrder,\n        TDatasetSubset::MakeColumns(haveLearnFeaturesInMemory),\n        &classLabels,\n        &executor,\n        &profile);\n\n    const bool hasTextFeatures = pools.Learn->MetaInfo.FeaturesLayout->GetTextFeatureCount() > 0;\n    if (hasTextFeatures) {\n        needFstr = false;\n    }\n\n    TVector<TString> outputColumns;\n    if (!evalOutputFileName.empty() && !pools.Test.empty()) {\n        outputColumns = outputOptions.GetOutputColumns(pools.Test[0]->MetaInfo.TargetCount);\n        for (int testIdx = 0; testIdx < pools.Test.ysize(); ++testIdx) {\n            const TDataProvider& testPool = *pools.Test[testIdx];\n\n            CB_ENSURE(\n                outputColumns == outputOptions.GetOutputColumns(testPool.MetaInfo.TargetCount),\n                \"Inconsistent output columns between test sets\"\n            );\n\n            ValidateColumnOutput(\n                outputColumns,\n                testPool,\n                loadOptions.CvParams.FoldCount > 0\n            );\n        }\n    }\n    TVector<TEvalResult> evalResults(pools.Test.ysize());\n\n    NJson::TJsonValue updatedTrainJson = trainJson;\n    UpdateUndefinedClassLabels(classLabels, &updatedTrainJson);\n\n    \/\/ create here to possibly load borders\n    auto quantizedFeaturesInfo = MakeIntrusive<TQuantizedFeaturesInfo>(\n        *pools.Learn->MetaInfo.FeaturesLayout,\n        catBoostOptions.DataProcessingOptions->IgnoredFeatures.Get(),\n        catBoostOptions.DataProcessingOptions->FloatFeaturesBinarization.Get(),\n        catBoostOptions.DataProcessingOptions->PerFloatFeatureQuantization.Get(),\n        catBoostOptions.DataProcessingOptions->TextProcessingOptions.Get(),\n        catBoostOptions.DataProcessingOptions->EmbeddingProcessingOptions.Get(),\n        \/*allowNansInTestOnly*\/true\n    );\n    if (loadOptions.BordersFile) {\n        LoadBordersAndNanModesFromFromFileInMatrixnetFormat(\n            loadOptions.BordersFile,\n            quantizedFeaturesInfo.Get());\n    }\n\n    bool needPoolAfterTrain = !evalOutputFileName.empty() || isLossFunctionChangeFstr;\n    TrainModel(\n        updatedTrainJson,\n        outputOptions,\n        quantizedFeaturesInfo,\n        \/*objectiveDescriptor*\/ Nothing(),\n        \/*evalMetricDescriptor*\/ Nothing(),\n        needPoolAfterTrain ? pools : std::move(pools),\n        \/*initModel*\/ Nothing(),\n        \/*initLearnProgress*\/ nullptr,\n        &loadOptions,\n        \/*outputModelPath*\/ \"\",\n        \/*dstModel*\/ nullptr,\n        GetMutablePointers(evalResults),\n        \/*metricsAndTimeHistory*\/ nullptr,\n        \/*dstLearnProgress*\/ nullptr,\n        &executor\n    );\n\n    const auto fullModelPath = NCatboostOptions::AddExtension(\n        modelFormat,\n        outputOptions.CreateResultModelFullPath(),\n        outputOptions.AddFileFormatExtension());\n\n    TSetLoggingVerbose inThisScope2;\n    if (!evalOutputFileName.empty()) {\n        TFullModel model = ReadModel(fullModelPath, modelFormat);\n        const TExternalLabelsHelper visibleLabelsHelper(model);\n        if (!loadOptions.CvParams.FoldCount && loadOptions.TestSetPaths.empty() && !outputColumns.empty()) {\n            CATBOOST_WARNING_LOG << \"No test files, can't output columns\\n\";\n        }\n        CATBOOST_INFO_LOG << \"Writing test eval to: \" << evalOutputFileName << Endl;\n        TOFStream fileStream(evalOutputFileName);\n        for (int testIdx = 0; testIdx < pools.Test.ysize(); ++testIdx) {\n            const TDataProvider& testPool = *pools.Test[testIdx];\n            const NCB::TPathWithScheme& testSetPath = testIdx < loadOptions.TestSetPaths.ysize() ? loadOptions.TestSetPaths[testIdx] : NCB::TPathWithScheme();\n            OutputEvalResultToFile(\n                evalResults[testIdx],\n                &executor,\n                outputColumns,\n                model.GetLossFunctionName(),\n                visibleLabelsHelper,\n                testPool,\n                &fileStream,\n                testSetPath,\n                {testIdx, pools.Test.ysize()},\n                loadOptions.ColumnarPoolFormatParams.DsvFormat,\n                \/*writeHeader*\/ testIdx < 1);\n        }\n\n        if (pools.Test.empty()) {\n            CATBOOST_WARNING_LOG << \"can't evaluate model (--eval-file) without test set\" << Endl;\n        }\n    } else {\n        CATBOOST_INFO_LOG << \"Skipping test eval output\" << Endl;\n    }\n    profile.AddOperation(\"Train model\");\n\n    if (catBoostOptions.IsProfile || catBoostOptions.LoggingLevel == ELoggingLevel::Debug) {\n        TLogger logger;\n        logger.AddProfileBackend(TIntrusivePtr<ILoggingBackend>(new TConsoleLoggingBackend(true)));\n        TOneInterationLogger oneIterLogger(logger);\n        oneIterLogger.OutputProfile(profile.GetProfileResults());\n    }\n\n    if (needFstr) {\n        TFullModel model = ReadModel(fullModelPath, modelFormat);\n        const bool useLearnToCalcFstr = haveLearnFeaturesInMemory && isLossFunctionChangeFstr;\n        CalcAndOutputFstr(\n            model,\n            useLearnToCalcFstr ? pools.Learn : nullptr,\n            &executor,\n            &fstrRegularFileName,\n            &fstrInternalFileName,\n            fstrType);\n    }\n\n    CATBOOST_INFO_LOG << runTimer.Passed() \/ 60 << \" min passed\" << Endl;\n}\n\nstatic void ValidateFeaturesToEvaluate(const NJson::TJsonValue& trainOptionsJson, ui32 featureCount) {\n    const auto maxFeatureToEvaluateIdx = GetOptionFeaturesToEvaluate(trainOptionsJson).back();\n    CB_ENSURE(\n        maxFeatureToEvaluateIdx < featureCount,\n        \"Feature index \" << maxFeatureToEvaluateIdx << \" is too large; dataset has only \"\n        << featureCount << \" features\");\n}\n\nstatic void ModelBasedEval(\n    const NJson::TJsonValue& trainOptionsJson,\n    const NCatboostOptions::TOutputFilesOptions& outputOptions,\n    TQuantizedFeaturesInfoPtr quantizedFeaturesInfo,\n    TDataProviders pools,\n    NPar::TLocalExecutor* const executor)\n{\n    CB_ENSURE(pools.Learn != nullptr, \"Train data must be provided\");\n\n    const ETaskType taskType = NCatboostOptions::GetTaskType(trainOptionsJson);\n\n    CB_ENSURE(taskType == ETaskType::GPU, \"Model based eval is not implemented for CPU\");\n\n    CB_ENSURE(pools.Test.size() <= 1, \"Multiple eval sets not supported for GPU\");\n\n    NJson::TJsonValue updatedTrainOptionsJson = trainOptionsJson;\n\n    CB_ENSURE(TTrainerFactory::Has(ETaskType::GPU),\n        \"Can't load GPU learning library. Module was not compiled or driver is incompatible with package. Please install latest NVDIA driver and check again.\");\n\n    THolder<IModelTrainer> modelTrainerHolder(TTrainerFactory::Construct(ETaskType::GPU));\n    if (outputOptions.SaveSnapshot()) {\n        UpdateUndefinedRandomSeed(ETaskType::GPU, outputOptions, &updatedTrainOptionsJson, [&](IInputStream* in, TString& params) {\n            ::Load(in, params);\n        });\n    }\n\n    const auto learnFeaturesLayout = pools.Learn->MetaInfo.FeaturesLayout;\n    NCatboostOptions::TCatBoostOptions catBoostOptions(taskType);\n    catBoostOptions.Load(updatedTrainOptionsJson);\n\n    ValidateFeaturesToEvaluate(trainOptionsJson, pools.Learn->MetaInfo.GetFeatureCount());\n\n    if (!quantizedFeaturesInfo) {\n        quantizedFeaturesInfo = MakeIntrusive<TQuantizedFeaturesInfo>(\n            *learnFeaturesLayout,\n            catBoostOptions.DataProcessingOptions.Get().IgnoredFeatures.Get(),\n            catBoostOptions.DataProcessingOptions->FloatFeaturesBinarization.Get(),\n            catBoostOptions.DataProcessingOptions->PerFloatFeatureQuantization.Get(),\n            catBoostOptions.DataProcessingOptions->TextProcessingOptions.Get(),\n            catBoostOptions.DataProcessingOptions->EmbeddingProcessingOptions.Get(),\n            \/*allowNansInTestOnly*\/true\n        );\n    }\n\n    for (auto testPoolIdx : xrange(pools.Test.size())) {\n        const auto& testPool = *pools.Test[testPoolIdx];\n        if (testPool.GetObjectCount() == 0) {\n            continue;\n        }\n        CheckCompatibleForApply(\n            *learnFeaturesLayout,\n            *testPool.MetaInfo.FeaturesLayout,\n            TStringBuilder() << \"test dataset #\" << testPoolIdx);\n    }\n\n    TSetLogging inThisScope(catBoostOptions.LoggingLevel);\n\n    auto learnDataOrder = pools.Learn->ObjectsData->GetOrder();\n    if (learnDataOrder == EObjectsOrder::Ordered) {\n        catBoostOptions.DataProcessingOptions->HasTimeFlag = true;\n    }\n\n    pools.Learn = ReorderByTimestampLearnDataIfNeeded(catBoostOptions, pools.Learn, executor);\n\n    TRestorableFastRng64 rand(catBoostOptions.RandomSeed.Get());\n\n    pools.Learn = ShuffleLearnDataIfNeeded(catBoostOptions, pools.Learn, executor, &rand);\n\n    TLabelConverter labelConverter;\n\n    TString tmpDir;\n    if (outputOptions.AllowWriteFiles()) {\n        NCB::NPrivate::CreateTrainDirWithTmpDirIfNotExist(outputOptions.GetTrainDir(), &tmpDir);\n    }\n\n    TTrainingDataProviders trainingData = GetTrainingData(\n        std::move(pools),\n        \/* borders *\/ Nothing(), \/\/ borders are already loaded to quantizedFeaturesInfo\n        \/*ensureConsecutiveIfDenseLearnFeaturesDataForCpu*\/ true,\n        outputOptions.AllowWriteFiles(),\n        tmpDir,\n        quantizedFeaturesInfo,\n        &catBoostOptions,\n        &labelConverter,\n        executor,\n        &rand);\n\n    CheckConsistency(trainingData);\n\n    NCatboostOptions::TOutputFilesOptions updatedOutputOptions(outputOptions);\n    SetDataDependentDefaults(\n        trainingData.Learn->MetaInfo,\n        trainingData.Test.size() > 0 ?\n            TMaybe<NCB::TDataMetaInfo>(trainingData.Test[0]->MetaInfo) :\n            Nothing(),\n        \/*continueFromModel*\/ false,\n        \/*continueFromProgress*\/ false,\n        &updatedOutputOptions.UseBestModel,\n        &catBoostOptions\n    );\n    InitializeEvalMetricIfNotSet(catBoostOptions.MetricOptions->ObjectiveMetric, &catBoostOptions.MetricOptions->EvalMetric);\n\n    modelTrainerHolder->ModelBasedEval(\n        catBoostOptions,\n        updatedOutputOptions,\n        std::move(trainingData),\n        labelConverter,\n        executor);\n}\n\nvoid ModelBasedEval(\n    const NCatboostOptions::TPoolLoadParams& loadOptions,\n    const NCatboostOptions::TOutputFilesOptions& outputOptions,\n    const NJson::TJsonValue& trainJson\n) {\n    THPTimer runTimer;\n    auto catBoostOptions = NCatboostOptions::LoadOptions(trainJson);\n\n    TSetLogging inThisScope(catBoostOptions.LoggingLevel);\n\n    TProfileInfo profile;\n\n    CB_ENSURE(\n        (catBoostOptions.GetTaskType() == ETaskType::CPU) || (loadOptions.TestSetPaths.size() <= 1),\n        \"Multiple eval sets not supported for GPU\"\n    );\n\n    NPar::TLocalExecutor executor;\n    executor.RunAdditionalThreads(catBoostOptions.SystemOptions.Get().NumThreads.Get() - 1);\n\n    TVector<NJson::TJsonValue> classLabels = catBoostOptions.DataProcessingOptions->ClassLabels;\n\n    TDataProviders pools = LoadPools(\n        loadOptions,\n        catBoostOptions.GetTaskType(),\n        ParseMemorySizeDescription(catBoostOptions.SystemOptions->CpuUsedRamLimit.Get()),\n        catBoostOptions.DataProcessingOptions->HasTimeFlag.Get() ?\n            EObjectsOrder::Ordered : EObjectsOrder::Undefined,\n        TDatasetSubset::MakeColumns(),\n        &classLabels,\n        &executor,\n        &profile);\n\n    ValidateFeaturesToEvaluate(trainJson, pools.Learn->MetaInfo.GetFeatureCount());\n\n    \/\/ create here to possibly load borders\n    auto quantizedFeaturesInfo = MakeIntrusive<TQuantizedFeaturesInfo>(\n        *pools.Learn->MetaInfo.FeaturesLayout,\n        catBoostOptions.DataProcessingOptions->IgnoredFeatures.Get(),\n        catBoostOptions.DataProcessingOptions->FloatFeaturesBinarization.Get(),\n        catBoostOptions.DataProcessingOptions->PerFloatFeatureQuantization.Get(),\n        catBoostOptions.DataProcessingOptions->TextProcessingOptions.Get(),\n        catBoostOptions.DataProcessingOptions->EmbeddingProcessingOptions.Get(),\n        \/*allowNansInTestOnly*\/true\n    );\n    if (loadOptions.BordersFile) {\n        LoadBordersAndNanModesFromFromFileInMatrixnetFormat(\n            loadOptions.BordersFile,\n            quantizedFeaturesInfo.Get());\n    }\n\n    NJson::TJsonValue updatedTrainJson = trainJson;\n    UpdateUndefinedClassLabels(classLabels, &updatedTrainJson);\n\n    ModelBasedEval(\n        updatedTrainJson,\n        outputOptions,\n        quantizedFeaturesInfo,\n        std::move(pools),\n        &executor\n    );\n\n    profile.AddOperation(\"Model based eval\");\n\n    if (catBoostOptions.IsProfile || catBoostOptions.LoggingLevel == ELoggingLevel::Debug) {\n        TLogger logger;\n        logger.AddProfileBackend(TIntrusivePtr<ILoggingBackend>(new TConsoleLoggingBackend(true)));\n        TOneInterationLogger oneIterLogger(logger);\n        oneIterLogger.OutputProfile(profile.GetProfileResults());\n    }\n\n    CATBOOST_INFO_LOG << runTimer.Passed() \/ 60 << \" min passed\" << Endl;\n}\n\nvoid TrainModel(\n    NJson::TJsonValue plainJsonParams,\n    NCB::TQuantizedFeaturesInfoPtr quantizedFeaturesInfo, \/\/ can be nullptr\n    const TMaybe<TCustomObjectiveDescriptor>& objectiveDescriptor,\n    const TMaybe<TCustomMetricDescriptor>& evalMetricDescriptor,\n    NCB::TDataProviders pools, \/\/ not rvalue reference because Cython does not support them\n    TMaybe<TFullModel*> initModel,\n    THolder<TLearnProgress>* initLearnProgress,\n    const TString& outputModelPath,\n    TFullModel* dstModel,\n    const TVector<TEvalResult*>& evalResultPtrs,\n    TMetricsAndTimeLeftHistory* metricsAndTimeHistory,\n    THolder<TLearnProgress>* dstLearnProgress\n) {\n    NJson::TJsonValue trainOptionsJson;\n    NJson::TJsonValue outputFilesOptionsJson;\n    ConvertIgnoredFeaturesFromStringToIndices(pools.Learn.Get()->MetaInfo, &plainJsonParams);\n    NCatboostOptions::PlainJsonToOptions(plainJsonParams, &trainOptionsJson, &outputFilesOptionsJson);\n    ConvertParamsToCanonicalFormat(pools.Learn.Get()->MetaInfo, &trainOptionsJson);\n\n    CB_ENSURE(!plainJsonParams.Has(\"node_type\") || plainJsonParams[\"node_type\"] == \"SingleHost\", \"CatBoost Python module does not support distributed training\");\n\n    NCatboostOptions::TOutputFilesOptions outputOptions;\n    outputOptions.Load(outputFilesOptionsJson);\n\n    NPar::TLocalExecutor executor;\n    executor.RunAdditionalThreads(\n        NCatboostOptions::GetThreadCount(trainOptionsJson) - 1);\n\n    TrainModel(\n        trainOptionsJson,\n        outputOptions,\n        quantizedFeaturesInfo,\n        objectiveDescriptor,\n        evalMetricDescriptor,\n        std::move(pools),\n        std::move(initModel),\n        initLearnProgress ? std::move(*initLearnProgress) : THolder<TLearnProgress>(),\n        \/*poolLoadOptions*\/nullptr,\n        outputModelPath,\n        dstModel,\n        evalResultPtrs,\n        metricsAndTimeHistory,\n        dstLearnProgress,\n        &executor);\n}\n","avg_line_length":42.3725231176,"max_line_length":188,"alphanum_fraction":0.6787161741,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":705,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":12278.0,"content":"\/\/ Copyright 2014 Renato Tegon Forti, Antony Polukhin.\n\/\/ Copyright 2015-2019 Antony Polukhin.\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt\n\/\/ or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n\/\/[callplugcpp_tutorial8_static\n#include <boost\/dll\/runtime_symbol_info.hpp> \/\/ program_location()\n#include <iostream>\n#include \"refcounting_plugin.hpp\"\n\nint main() {\n    boost::shared_ptr<my_refcounting_api> plugin = get_plugin(\n        boost::dll::program_location(),\n        \"create_refc_plugin\"\n    );\n\n    std::cout << \"Plugin name: \" << plugin->name() \n              << \", \\nlocation: \" << plugin->location() \n              << std::endl;\n}\n\/\/]\n","avg_line_length":29.375,"max_line_length":66,"alphanum_fraction":0.6680851064,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1052,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":255.0,"content":"\/*\n * Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"DataLayoutConversion.h\"\n\n#include <gtest\/gtest.h>\n\nTEST(DataLayoutConversionTest, case_000)\n{\n  auto m = coco::Module::create();\n\n  \/\/ Create a \"free\" Load op\n  m->entity()->instr()->create<coco::Eval>();\n\n  enco::Code code{m.get(), nullptr};\n  ASSERT_EQ(m->entity()->instr()->size(), 1);\n\n  \/\/ \"conver_data_layout\" SHOULD NOT crash even if there is a \"free\" Load op\n  enco::convert_data_layout(&code);\n}\n","avg_line_length":30.9411764706,"max_line_length":76,"alphanum_fraction":0.711026616,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1697,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include \"DatabaseBuilder\/DatabaseBuilder.h\"\n\nint main()\n{\n    const string APP_NAME(\"database-test\");\n    const string APP_VERSION(\"1.0\");\n\n    const string LIB_PATH(\"..\\\\lib\\\\\");\n    const string DATABASE_PATH(\"..\\\\lib\\\\lib.sqlite3\");\n\n    const char* ARGS_INCLUDE_PREFIX = \"-I\";\n    const char* ARGS_INCLUDE_PATH   = \"..\\\\lib\\\\include\\\\\";\n    const char* COMPILATION_ARGS[2] = { ARGS_INCLUDE_PREFIX, ARGS_INCLUDE_PATH };\n\n    FolderBrowser folderBrowser;\n    folderBrowser.addIgnoreFilePath(\"..\\\\lib\\\\src\\\\TestPrimitives.cpp\");\n    folderBrowser.addIgnoreFilePath(\"..\\\\lib\\\\include\\\\TestPrimitives.h\");\n    folderBrowser.startFolderBrowse(LIB_PATH);\n\n    Database database;\n    DatabaseBuilder databaseBuilder(database, APP_NAME, APP_VERSION, folderBrowser, COMPILATION_ARGS, 2);\n    databaseBuilder.buildDatabase\n    (\n        [](const string& filePath, size_t fileIndex, size_t fileCount) -> void\n        {\n            cout << fileIndex + 1 << '\/' << fileCount << \" -> \" << filePath << endl;\n        }\n    );\n\n    QueryResults queryResults;\n    DatabaseQueryErrMsg queryErrMsg = database.recvQuery(\"SELECT * FROM [..\\\\file_list]\", queryResults);\n    if(database.isNotOK())\n        cout << \"Recv Error : \" << queryErrMsg << endl;\n\n    for(std::vector<string>& row : queryResults.rows)\n    {\n        string& idStr = row[0];\n        string& fileNameStr = row[1];\n\n        cout << fileNameStr << endl;\n    }\n\n    database.saveAsDatabase\n    (\n        DATABASE_PATH,\n        [](double currentPercent) -> void\n        {\n            cout << currentPercent << endl;\n        }\n    );\n\n    if(database.isNotOK())\n        cout << \"Database hasn't saved correctly.\" << endl;\n\n    return EXIT_SUCCESS;\n}\n\n","avg_line_length":29.2586206897,"max_line_length":105,"alphanum_fraction":0.6287566293,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":32263,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["PHP-3.01","Zend-2.0"],"max_stars_count":1.0,"content":"\/*\n   +----------------------------------------------------------------------+\n   | HipHop for PHP                                                       |\n   +----------------------------------------------------------------------+\n   | Copyright (c) 2010-2015 Facebook, Inc. (http:\/\/www.facebook.com)     |\n   +----------------------------------------------------------------------+\n   | This source file is subject to version 3.01 of the PHP license,      |\n   | that is bundled with this package in the file LICENSE, and is        |\n   | available through the world-wide-web at the following url:           |\n   | http:\/\/www.php.net\/license\/3_01.txt                                  |\n   | If you did not receive a copy of the PHP license and are unable to   |\n   | obtain it through the world-wide-web, please send a note to          |\n   | license@php.net so we can mail you a copy immediately.               |\n   +----------------------------------------------------------------------+\n*\/\n\n#include \"hphp\/compiler\/analysis\/analysis_result.h\"\n\n#include <boost\/format.hpp>\n#include <boost\/bind.hpp>\n\n#include <folly\/Conv.h>\n\n#include <algorithm>\n#include <atomic>\n#include <fstream>\n#include <iomanip>\n#include <map>\n#include <set>\n#include <sstream>\n#include <utility>\n#include <vector>\n\n#include \"hphp\/compiler\/analysis\/exceptions.h\"\n#include \"hphp\/compiler\/analysis\/file_scope.h\"\n#include \"hphp\/compiler\/analysis\/class_scope.h\"\n#include \"hphp\/compiler\/analysis\/code_error.h\"\n#include \"hphp\/compiler\/analysis\/depth_first_visitor.h\"\n#include \"hphp\/compiler\/statement\/statement_list.h\"\n#include \"hphp\/compiler\/statement\/if_branch_statement.h\"\n#include \"hphp\/compiler\/statement\/method_statement.h\"\n#include \"hphp\/compiler\/statement\/loop_statement.h\"\n#include \"hphp\/compiler\/statement\/class_variable.h\"\n#include \"hphp\/compiler\/statement\/use_trait_statement.h\"\n#include \"hphp\/compiler\/statement\/class_require_statement.h\"\n#include \"hphp\/compiler\/analysis\/symbol_table.h\"\n#include \"hphp\/compiler\/package.h\"\n#include \"hphp\/compiler\/parser\/parser.h\"\n#include \"hphp\/compiler\/option.h\"\n#include \"hphp\/compiler\/analysis\/function_scope.h\"\n#include \"hphp\/compiler\/builtin_symbols.h\"\n#include \"hphp\/compiler\/analysis\/constant_table.h\"\n#include \"hphp\/compiler\/analysis\/variable_table.h\"\n#include \"hphp\/compiler\/expression\/scalar_expression.h\"\n#include \"hphp\/compiler\/expression\/constant_expression.h\"\n#include \"hphp\/compiler\/expression\/expression_list.h\"\n#include \"hphp\/compiler\/expression\/array_pair_expression.h\"\n#include \"hphp\/compiler\/expression\/simple_function_call.h\"\n#include \"hphp\/runtime\/base\/zend-printf.h\"\n#include \"hphp\/runtime\/base\/program-functions.h\"\n#include \"hphp\/util\/atomic.h\"\n#include \"hphp\/util\/logger.h\"\n#include \"hphp\/util\/text-util.h\"\n#include \"hphp\/util\/hash.h\"\n#include \"hphp\/util\/process.h\"\n#include \"hphp\/util\/job-queue.h\"\n#include \"hphp\/util\/timer.h\"\n\nusing namespace HPHP;\nusing std::map;\nusing std::set;\nusing std::ostringstream;\nusing std::ofstream;\nusing std::ifstream;\nusing std::pair;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ initialization\n\nIMPLEMENT_THREAD_LOCAL(BlockScopeRawPtr,\n                       AnalysisResult::s_currentScopeThreadLocal);\n\nIMPLEMENT_THREAD_LOCAL(BlockScopeRawPtrFlagsHashMap,\n                       AnalysisResult::s_changedScopesMapThreadLocal);\n\nAnalysisResult::AnalysisResult()\n  : BlockScope(\"Root\", \"\", StatementPtr(), BlockScope::ProgramScope),\n    m_arrayLitstrKeyMaxSize(0), m_arrayIntegerKeyMaxSize(0),\n    m_package(nullptr), m_parseOnDemand(false), m_phase(ParseAllFiles) {\n}\n\nAnalysisResult::~AnalysisResult() {\n  always_assert(!m_finish);\n}\n\nvoid AnalysisResult::finish() {\n  if (m_finish) {\n    decltype(m_finish) f;\n    f.swap(m_finish);\n    f(shared_from_this());\n  }\n}\n\nvoid AnalysisResult::appendExtraCode(const std::string &key,\n                                     const std::string &code) {\n  auto& extraCode = m_extraCodes[key];\n\n  if (extraCode.empty()) {\n    extraCode = \"<?php\\n\";\n  }\n  extraCode += code + \"\\n\";\n}\n\nvoid AnalysisResult::appendExtraCode(const std::string &key,\n                                     const std::string &code) const {\n  lock()->appendExtraCode(key, code);\n}\n\nvoid AnalysisResult::parseExtraCode(const std::string &key) {\n  Lock lock(getMutex());\n  auto iter = m_extraCodes.find(key);\n  if (iter != m_extraCodes.end()) {\n    auto const code = iter->second;\n    auto const sfilename = iter->first + \".\" + Option::LambdaPrefix + \"lambda\";\n    m_extraCodes.erase(key);\n\n    const char *filename = m_extraCodeFileNames.add(sfilename.c_str());\n    Compiler::Parser::ParseString(code, shared_from_this(), filename, true);\n  }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ general functions\n\nvoid AnalysisResult::addFileScope(FileScopePtr fileScope) {\n  assert(fileScope);\n  FileScopePtr &res = m_files[fileScope->getName()];\n  assert(!res);\n  res = fileScope;\n  m_fileScopes.push_back(fileScope);\n}\n\nbool AnalysisResult::inParseOnDemandDirs(const std::string &filename) const {\n  for (size_t i = 0; i < m_parseOnDemandDirs.size(); i++) {\n    if (filename.find(m_parseOnDemandDirs[i]) == 0) return true;\n  }\n  return false;\n}\n\nvoid AnalysisResult::parseOnDemand(const std::string &name) const {\n  if (m_package) {\n    auto const& root = m_package->getRoot();\n    auto rname = name;\n    if (name.find(root) == 0) {\n      rname = name.substr(root.length());\n    }\n    if ((m_parseOnDemand || inParseOnDemandDirs(rname)) &&\n        Option::PackageExcludeFiles.find(rname) ==\n        Option::PackageExcludeFiles.end() &&\n        !Option::IsFileExcluded(rname, Option::PackageExcludePatterns)) {\n      {\n        Locker l(this);\n        if (m_files.find(rname) != m_files.end()) return;\n      }\n      m_package->addSourceFile(rname.c_str());\n    }\n  }\n}\n\ntemplate <class Map>\nvoid AnalysisResult::parseOnDemandBy(const std::string &name,\n                                     const Map &amap) const {\n  if (m_package) {\n    auto it = amap.find(name);\n    if (it != amap.end()) {\n      parseOnDemand(Option::AutoloadRoot + it->second);\n    }\n  }\n}\n\ntemplate void AnalysisResult::parseOnDemandBy(\n  const std::string &name, const std::map<std::string,std::string> &amap) const;\n\ntemplate void AnalysisResult::parseOnDemandBy(\n  const std::string &name,\n  const std::map<std::string,std::string,stdltistr> &amap) const;\n\nvoid AnalysisResult::addNSFallbackFunc(ConstructPtr c, FileScopePtr fs) {\n  m_nsFallbackFuncs.insert(std::make_pair(c, fs));\n}\n\nFileScopePtr AnalysisResult::findFileScope(const std::string &name) const {\n  auto iter = m_files.find(name);\n  if (iter != m_files.end()) {\n    return iter->second;\n  }\n  return FileScopePtr();\n}\n\nFunctionScopePtr AnalysisResult::findFunction(\n  const std::string &funcName) const {\n  auto bit = m_functions.find(funcName);\n  if (bit != m_functions.end() && !bit->second->allowOverride()) {\n    return bit->second;\n  }\n  auto iter = m_functionDecs.find(funcName);\n  if (iter != m_functionDecs.end()) {\n    return iter->second;\n  }\n  return bit != m_functions.end() ? bit->second : FunctionScopePtr();\n}\n\nBlockScopePtr AnalysisResult::findConstantDeclarer(\n  const std::string &name) {\n  if (getConstants()->isPresent(name)) return shared_from_this();\n  auto iter = m_constDecs.find(name);\n  if (iter != m_constDecs.end()) return iter->second;\n  return BlockScopePtr();\n}\n\nClassScopePtr AnalysisResult::findClass(const std::string &name) const {\n  AnalysisResultConstPtr ar = shared_from_this();\n  auto const lname = toLower(name);\n  auto const sysIter = m_systemClasses.find(lname);\n  if (sysIter != m_systemClasses.end()) return sysIter->second;\n\n  auto const iter = m_classDecs.find(lname);\n  if (iter != m_classDecs.end() && iter->second.size()) {\n    return iter->second.back();\n  }\n  return ClassScopePtr();\n}\n\nconst std::vector<ClassScopePtr>&\nAnalysisResult::findRedeclaredClasses(const std::string &name) const {\n  auto iter = m_classDecs.find(name);\n  if (iter == m_classDecs.end()) {\n    static std::vector<ClassScopePtr> empty;\n    empty.clear();\n    return empty;\n  }\n  return iter->second;\n}\n\nstd::vector<ClassScopePtr> AnalysisResult::findClasses(\n  const std::string &name\n) const {\n  auto const sysIter = m_systemClasses.find(name);\n  if (sysIter != m_systemClasses.end()) {\n    return {sysIter->second};\n  }\n\n  return findRedeclaredClasses(name);\n}\n\nClassScopePtr AnalysisResult::findExactClass(ConstructPtr cs,\n                                             const std::string &name) const {\n  ClassScopePtr cls = findClass(name);\n  if (!cls || !cls->isRedeclaring()) return cls;\n  if (ClassScopePtr currentCls = cs->getClassScope()) {\n    if (cls->isNamed(currentCls->getScopeName())) {\n      return currentCls;\n    }\n  }\n  return ClassScopePtr();\n}\n\nint AnalysisResult::getFunctionCount() const {\n  int total = 0;\n  for (auto& pair : m_files) {\n    total += pair.second->getFunctionCount();\n  }\n  return total;\n}\n\nint AnalysisResult::getClassCount() const {\n  int total = 0;\n  for (auto& pair : m_files) {\n    total += pair.second->getClassCount();\n  }\n  return total;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ static analysis functions\n\nbool AnalysisResult::declareFunction(FunctionScopePtr funcScope) const {\n  assert(m_phase < AnalyzeAll);\n\n  \/\/ System functions override\n  auto it = m_functions.find(funcScope->getScopeName());\n  if (it != m_functions.end()) {\n    if (!it->second->allowOverride()) {\n      \/\/ we need someone to hold on to a reference to it\n      \/\/ even though we're not going to do anything with it\n      this->lock()->m_ignoredScopes.push_back(funcScope);\n      return false;\n    }\n  }\n\n  return true;\n}\n\nbool AnalysisResult::declareClass(ClassScopePtr classScope) const {\n  assert(m_phase < AnalyzeAll);\n\n  \/\/ System classes override\n  if (m_systemClasses.count(classScope->getScopeName())) {\n    \/\/ we need someone to hold on to a reference to it\n    \/\/ even though we're not going to do anything with it\n    this->lock()->m_ignoredScopes.push_back(classScope);\n    return false;\n  }\n\n  return true;\n}\n\nvoid AnalysisResult::declareUnknownClass(const std::string &name) {\n  m_classDecs.operator[](name);\n}\n\nbool AnalysisResult::declareConst(FileScopePtr fs, const std::string &name) {\n  if (getConstants()->isPresent(name) ||\n      m_constDecs.find(name) != m_constDecs.end()) {\n    m_constRedeclared.insert(name);\n    return false;\n  } else {\n    m_constDecs[name] = fs;\n    return true;\n  }\n}\n\nstatic bool by_source(const BlockScopePtr &b1, const BlockScopePtr &b2) {\n  if (auto d = b1->getStmt()->getRange().compare(b2->getStmt()->getRange())) {\n    return d;\n  }\n  return b1->getContainingFile()->getName() <\n    b2->getContainingFile()->getName();\n}\n\nvoid AnalysisResult::canonicalizeSymbolOrder() {\n  getConstants()->canonicalizeSymbolOrder();\n  getVariables()->canonicalizeSymbolOrder();\n}\n\nvoid AnalysisResult::markRedeclaringClasses() {\n  AnalysisResultPtr ar = shared_from_this();\n  for (auto& pair : m_classDecs) {\n    auto& classes = pair.second;\n    if (classes.size() > 1) {\n      sort(classes.begin(), classes.end(), by_source);\n      for (size_t i = 0; i < classes.size(); i++) {\n        classes[i]->setRedeclaring(ar, i);\n      }\n    }\n  }\n\n  auto markRedeclaring = [&] (const std::string& name) {\n    auto it = m_classDecs.find(name);\n    if (it != m_classDecs.end()) {\n      auto& classes = it->second;\n      for (size_t i = 0; i < classes.size(); ++i) {\n        classes[i]->setRedeclaring(ar, i);\n      }\n    }\n  };\n\n  \/*\n   * In WholeProgram mode, during parse time we collected all\n   * class_alias calls so we can mark the targets of such calls\n   * redeclaring if necessary.\n   *\n   * Two cases here that definitely require this:\n   *\n   *  - If an alias name has the same name as another class, we need\n   *    to mark *that* class as redeclaring, since it may mean\n   *    different things in different requests now.\n   *\n   *  - If an alias name can refer to more than one class, each of\n   *    those classes must be marked redeclaring.\n   *\n   * In the simple case of a unique alias name and a unique target\n   * name, we might be able to get away with manipulating the target\n   * classes' volatility.\n   *\n   * Rather than work through the various cases here, though, we've\n   * just decided to just play it safe and mark all the names involved\n   * as redeclaring for now.\n   *\/\n  for (auto& kv : m_classAliases) {\n    assert(kv.first == toLower(kv.first));\n    assert(kv.second == toLower(kv.second));\n    markRedeclaring(kv.first);\n    markRedeclaring(kv.second);\n  }\n\n  \/*\n   * Similar to class_alias, when a type alias is declared with the\n   * same name as a class in the program, we need to make sure the\n   * class is marked redeclaring.  It is possible in some requests\n   * that things like 'instanceof Foo' will not mean the same thing.\n   *\/\n  for (auto& name : m_typeAliasNames) {\n    assert(toLower(name) == name);\n    markRedeclaring(name);\n  }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Dependencies\n\nbool AnalysisResult::isConstantDeclared(const std::string &constName) const {\n  if (m_constants->isPresent(constName)) return true;\n  auto const iter = m_constDecs.find(constName);\n  if (iter == m_constDecs.end()) return false;\n  FileScopePtr fileScope = iter->second;\n  ConstantTablePtr constants = fileScope->getConstants();\n  ConstructPtr decl = constants->getValue(constName);\n  if (decl) return true;\n  return false;\n}\n\nbool AnalysisResult::isConstantRedeclared(const std::string &constName) const {\n  return m_constRedeclared.find(constName) != m_constRedeclared.end();\n}\n\nbool AnalysisResult::isSystemConstant(const std::string &constName) const {\n  return m_constants->isSystem(constName);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Program\n\nvoid AnalysisResult::addSystemFunction(FunctionScopeRawPtr fs) {\n  FunctionScopePtr& entry = m_functions[fs->getScopeName()];\n  assert(!entry);\n  entry = fs;\n}\n\nvoid AnalysisResult::addSystemClass(ClassScopeRawPtr cs) {\n  ClassScopePtr& entry = m_systemClasses[cs->getScopeName()];\n  assert(!entry);\n  entry = cs;\n}\n\nvoid AnalysisResult::checkClassDerivations() {\n  AnalysisResultPtr ar = shared_from_this();\n  for (auto& pair : m_classDecs) {\n    for (ClassScopePtr cls : pair.second) {\n      if (Option::WholeProgram) {\n        try {\n          cls->importUsedTraits(ar);\n        } catch (const AnalysisTimeFatalException& e) {\n          cls->setFatal(e);\n        }\n      }\n      hphp_string_iset seen;\n      cls->checkDerivation(ar, seen);\n    }\n  }\n}\n\nvoid AnalysisResult::resolveNSFallbackFuncs() {\n  for (auto &pair : m_nsFallbackFuncs) {\n    auto sfc = static_pointer_cast<SimpleFunctionCall>(pair.first);\n    sfc->resolveNSFallbackFunc(\n      shared_from_this(),\n      pair.second\n    );\n  }\n}\n\nvoid AnalysisResult::collectFunctionsAndClasses(FileScopePtr fs) {\n  for (const auto& iter : fs->getFunctions()) {\n    FunctionScopePtr func = iter.second;\n    if (!func->inPseudoMain()) {\n      FunctionScopePtr &funcDec = m_functionDecs[iter.first];\n      if (funcDec) {\n        if (funcDec->isSystem()) {\n          assert(funcDec->allowOverride());\n          funcDec = func;\n        } else if (func->isSystem()) {\n          assert(func->allowOverride());\n        } else {\n          auto& funcVec = m_functionReDecs[iter.first];\n          int sz = funcVec.size();\n          if (!sz) {\n            funcDec->setRedeclaring(sz++);\n            funcVec.push_back(funcDec);\n          }\n          func->setRedeclaring(sz++);\n          funcVec.push_back(func);\n        }\n      } else {\n        funcDec = func;\n      }\n    }\n  }\n\n  if (const auto redec = fs->getRedecFunctions()) {\n    for (const auto &iter : *redec) {\n      auto i = iter.second.begin();\n      auto e = iter.second.end();\n      auto& funcDec = m_functionDecs[iter.first];\n      assert(funcDec); \/\/ because the first one was in funcs above\n      auto& funcVec = m_functionReDecs[iter.first];\n      int sz = funcVec.size();\n      if (!sz) {\n        funcDec->setRedeclaring(sz++);\n        funcVec.push_back(funcDec);\n      }\n      while (++i != e) { \/\/ we already added the first one\n        (*i)->setRedeclaring(sz++);\n        funcVec.push_back(*i);\n      }\n    }\n  }\n\n  for (const auto& iter : fs->getClasses()) {\n    auto& clsVec = m_classDecs[iter.first];\n    clsVec.insert(clsVec.end(), iter.second.begin(), iter.second.end());\n  }\n\n  m_classAliases.insert(fs->getClassAliases().begin(),\n                        fs->getClassAliases().end());\n  m_typeAliasNames.insert(fs->getTypeAliasNames().begin(),\n                          fs->getTypeAliasNames().end());\n}\n\nstatic bool by_filename(const FileScopePtr &f1, const FileScopePtr &f2) {\n  return f1->getName() < f2->getName();\n}\n\nvoid AnalysisResult::analyzeProgram(bool system \/* = false *\/) {\n  AnalysisResultPtr ar = shared_from_this();\n\n  getVariables()->setAttribute(VariableTable::ContainsLDynamicVariable);\n  getVariables()->setAttribute(VariableTable::ContainsExtract);\n  getVariables()->setAttribute(VariableTable::ForceGlobal);\n\n  \/\/ Analyze Includes\n  Logger::Verbose(\"Analyzing Includes\");\n  sort(m_fileScopes.begin(), m_fileScopes.end(), by_filename); \/\/ fixed order\n  unsigned int i = 0;\n  for (i = 0; i < m_fileScopes.size(); i++) {\n    collectFunctionsAndClasses(m_fileScopes[i]);\n  }\n\n  \/\/ Keep generated code identical without randomness\n  canonicalizeSymbolOrder();\n\n  markRedeclaringClasses();\n\n  \/\/ Analyze some special cases\n  for (auto& cls_name : Option::VolatileClasses) {\n    ClassScopePtr cls = findClass(toLower(cls_name));\n    if (cls && cls->isUserClass()) {\n      cls->setVolatile();\n    }\n  }\n\n  checkClassDerivations();\n  resolveNSFallbackFuncs();\n\n  \/\/ Analyze All\n  Logger::Verbose(\"Analyzing All\");\n  setPhase(AnalysisResult::AnalyzeAll);\n  for (i = 0; i < m_fileScopes.size(); i++) {\n    m_fileScopes[i]->analyzeProgram(ar);\n  }\n\n  \/*\n    Note that cls->collectMethods() can add entries to m_classDecs,\n    which can invalidate iterators. So we have to create an array\n    and then iterate over that.\n    The new entries added to m_classDecs are always empty, so it\n    doesnt matter that we dont include them in the iteration\n  *\/\n  std::vector<ClassScopePtr> classes;\n  classes.reserve(m_classDecs.size());\n  for (auto& pair : m_classDecs) {\n    for (auto cls : pair.second) {\n      classes.push_back(cls);\n    }\n  }\n\n  \/\/ Collect methods\n  for (auto cls : classes) {\n    StringToFunctionScopePtrMap methods;\n    cls->collectMethods(ar, methods, true \/* include privates *\/);\n    bool needAbstractMethodImpl =\n      (!cls->isAbstract() && !cls->isInterface() &&\n       cls->derivesFromRedeclaring() == Derivation::Normal &&\n       !cls->getAttribute(ClassScope::UsesUnknownTrait));\n    for (auto& pair : methods) {\n      auto func = pair.second;\n      if (Option::WholeProgram && !func->hasImpl() && needAbstractMethodImpl) {\n        auto tmpFunc = cls->findFunction(ar, func->getScopeName(), true, true);\n        always_assert(!tmpFunc || !tmpFunc->hasImpl());\n        Compiler::Error(Compiler::MissingAbstractMethodImpl,\n                        func->getStmt(), cls->getStmt());\n      }\n    }\n  }\n\n  for (auto& item : m_systemClasses) {\n    StringToFunctionScopePtrMap methods;\n    item.second->collectMethods(ar, methods, true \/* include privates *\/);\n  }\n}\n\nvoid AnalysisResult::analyzeProgramFinal() {\n  AnalysisResultPtr ar = shared_from_this();\n  setPhase(AnalysisResult::AnalyzeFinal);\n  for (size_t i = 0; i < m_fileScopes.size(); i++) {\n    m_fileScopes[i]->analyzeProgram(ar);\n  }\n\n  \/\/ Keep generated code identical without randomness\n  canonicalizeSymbolOrder();\n\n  \/\/ XXX: this is only here because canonicalizeSymbolOrder used to do\n  \/\/ it---is it necessary to repeat at this phase?  (Probably not ...)\n  markRedeclaringClasses();\n\n  setPhase(AnalysisResult::CodeGen);\n}\n\nstatic void dumpVisitor(AnalysisResultPtr ar, StatementPtr s, void *data) {\n  s->dump(0, ar);\n}\n\nvoid AnalysisResult::dump() {\n  visitFiles(dumpVisitor, 0);\n  fflush(0);\n}\n\nvoid AnalysisResult::visitFiles(void (*cb)(AnalysisResultPtr,\n                                           StatementPtr, void*), void *data) {\n  AnalysisResultPtr ar = shared_from_this();\n  for (auto& pair : m_files) {\n    pair.second->visit(ar, cb, data);\n  }\n}\n\nvoid AnalysisResult::getScopesSet(BlockScopeRawPtrQueue &v) {\n  for (auto& pair: m_files) {\n    pair.second->getScopesSet(v);\n  }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ optimization functions\n\nnamespace HPHP {\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate <typename When>\nstruct OptWorker;\n\ntemplate <typename When>\nstruct OptVisitor {\n  typedef OptVisitor<When> Visitor;\n\n  OptVisitor(AnalysisResultPtr ar, unsigned nscope) :\n      m_ar(ar), m_nscope(nscope), m_dispatcher(0) {\n  }\n  \/* implicit *\/ OptVisitor(const Visitor &po)\n    : m_ar(po.m_ar)\n    , m_nscope(po.m_nscope)\n    , m_dispatcher(po.m_dispatcher)\n  {\n    const_cast<Visitor&>(po).m_dispatcher = 0;\n  }\n  ~OptVisitor() {\n    delete m_dispatcher;\n  }\n\n  void start() {\n    m_dispatcher->start();\n  }\n\n  void wait() {\n    m_dispatcher->waitEmpty(false);\n  }\n\n  void stop() {\n    m_dispatcher->waitEmpty();\n  }\n\n  int getQueuedJobs() {\n    return m_dispatcher->getQueuedJobs();\n  }\n\n  int getActiveWorker() {\n    return m_dispatcher->getActiveWorker();\n  }\n\n  AnalysisResultPtr m_ar;\n  unsigned m_nscope;\n  JobQueueDispatcher<OptWorker<When>> *m_dispatcher;\n};\n\ntemplate <typename When>\nclass OptWorker : public JobQueueWorker<BlockScope*,\n                                        void*,\n                                        true,\n                                        true> {\npublic:\n  OptWorker() {}\n\n  void onThreadEnter() override {\n  }\n\n  void onThreadExit() override {\n  }\n\n  void doJob(BlockScope *scope) override {\n    try {\n      auto visitor =\n        (DepthFirstVisitor<When, OptVisitor>*) m_context;\n      {\n        Lock ldep(BlockScope::s_depsMutex);\n        Lock lstate(BlockScope::s_jobStateMutex);\n        always_assert(scope->getMark() == BlockScope::MarkReady);\n        if (scope->getNumDepsToWaitFor()) {\n          scope->setMark(BlockScope::MarkWaiting);\n          return;\n        }\n        scope->setMark(BlockScope::MarkProcessing);\n      }\n\n      scope->setForceRerun(false);\n\n      \/\/ creates on demand\n      AnalysisResult::s_changedScopesMapThreadLocal->clear();\n      int useKinds = visitor->visitScope(BlockScopeRawPtr(scope));\n      assert(useKinds >= 0);\n\n      {\n        Lock l2(BlockScope::s_depsMutex);\n        Lock l1(BlockScope::s_jobStateMutex);\n\n        assert(scope->getMark() == BlockScope::MarkProcessing);\n        assert(scope->getNumDepsToWaitFor() == 0);\n\n        \/\/ re-enqueue changed scopes, regardless of rescheduling exception.\n        \/\/ this is because we might have made changes to other scopes which we\n        \/\/ do not undo, so we need to announce their updates\n        for (const auto& local : *AnalysisResult::s_changedScopesMapThreadLocal) {\n          for (const auto& pf : local.first->getOrderedUsers()) {\n            if ((pf->second & GetPhaseInterestMask<When>()) &&\n                (pf->second & local.second)) {\n              int m = pf->first->getMark();\n              switch (m) {\n              case BlockScope::MarkWaiting:\n              case BlockScope::MarkReady:\n                ; \/\/ no-op\n                break;\n              case BlockScope::MarkProcessing:\n                pf->first->setForceRerun(true);\n                break;\n              case BlockScope::MarkProcessed:\n                if (visitor->activateScope(pf->first)) {\n                  visitor->enqueue(pf->first);\n                }\n                break;\n              default: assert(false);\n              }\n            }\n          }\n        }\n        AnalysisResult::s_changedScopesMapThreadLocal.destroy();\n\n        useKinds |= scope->rescheduleFlags();\n        scope->setRescheduleFlags(0);\n\n        for (const auto& pf : scope->getOrderedUsers()) {\n          if (pf->second & GetPhaseInterestMask<When>()) {\n            int m = pf->first->getMark();\n            if (pf->second & useKinds && m == BlockScope::MarkProcessed) {\n              bool ready = visitor->activateScope(pf->first);\n              always_assert(!ready);\n              m = BlockScope::MarkWaiting;\n            }\n\n            if (m == BlockScope::MarkWaiting || m == BlockScope::MarkReady) {\n              int nd = pf->first->getNumDepsToWaitFor();\n              always_assert(nd >= 1);\n              if (!pf->first->decNumDepsToWaitFor() &&\n                  m == BlockScope::MarkWaiting) {\n                pf->first->setMark(BlockScope::MarkReady);\n                visitor->enqueue(pf->first);\n              }\n            } else if (pf->second & useKinds &&\n                       m == BlockScope::MarkProcessing) {\n              \/\/ This is conservative: If we have a user who is currently\n              \/\/ processing (yes, this can potentially happen if we add a\n              \/\/ user *after* the initial dep graph has been formed), then we\n              \/\/ have no guarantee that the scope read this scope's updates\n              \/\/ in its entirety. Thus, we must force it to run again in\n              \/\/ order to be able to observe all the updates.\n              always_assert(pf->first->getNumDepsToWaitFor() == 0);\n              pf->first->setForceRerun(true);\n            }\n          }\n        }\n        scope->setMark(BlockScope::MarkProcessed);\n        if (scope->forceRerun()) {\n          if (visitor->activateScope(BlockScopeRawPtr(scope))) {\n            visitor->enqueue(BlockScopeRawPtr(scope));\n          }\n        } else {\n          for (const auto& p : scope->getDeps()) {\n            if (*p.second & GetPhaseInterestMask<When>()) {\n              if (p.first->getMark() == BlockScope::MarkProcessing) {\n                bool ready = visitor->activateScope(BlockScopeRawPtr(scope));\n                always_assert(!ready);\n                break;\n              }\n            }\n          }\n        }\n      }\n    } catch (Exception &e) {\n      Logger::Error(\"%s\", e.getMessage().c_str());\n    }\n  }\n};\n\n\/\/ Pre defined in depth_first_visitor.h\n\ntypedef   OptVisitor<Pre>          PreOptVisitor;\ntypedef   OptWorker<Pre>           PreOptWorker;\n\ntemplate<>\nvoid OptWorker<Pre>::onThreadEnter() {\n  hphp_session_init();\n  hphp_context_init();\n}\n\ntemplate<>\nvoid OptWorker<Pre>::onThreadExit() {\n  hphp_context_exit();\n  hphp_session_exit();\n}\n\n\/**\n * Unfortunately we cannot template specialize on something like this w\/o\n * complaints about incomplete class declarations:\n *\n *   template <class When>\n *   void DepthFirstVisitor<When, OptVisitor>::setup() { ... }\n *\n * And as such, this evil exists\n *\/\n\n#define IMPLEMENT_OPT_VISITOR_SETUP(worker) \\\n  do { \\\n    unsigned int threadCount = Option::ParserThreadCount; \\\n    if (threadCount > this->m_data.m_nscope) { \\\n      threadCount = this->m_data.m_nscope; \\\n    } \\\n    if (threadCount <= 0) threadCount = 1; \\\n    this->m_data.m_dispatcher = \\\n      new JobQueueDispatcher<worker>( \\\n        threadCount, true, 0, false, this); \\\n  } while (0)\n\n#define IMPLEMENT_OPT_VISITOR_ENQUEUE(scope) \\\n  do { \\\n    assert((scope)->getMark() == BlockScope::MarkReady); \\\n    this->m_data.m_dispatcher->enqueue((scope).get()); \\\n  } while (0)\n\ntemplate<>\nvoid DepthFirstVisitor<Pre, OptVisitor>::setup() {\n  IMPLEMENT_OPT_VISITOR_SETUP(PreOptWorker);\n}\n\ntemplate<>\nvoid DepthFirstVisitor<Pre, OptVisitor>::enqueue(BlockScopeRawPtr scope) {\n  IMPLEMENT_OPT_VISITOR_ENQUEUE(scope);\n}\n\ntemplate <typename When>\nvoid\nAnalysisResult::preWaitCallback(bool first,\n                                const BlockScopeRawPtrQueue &scopes,\n                                void *context) {\n  \/\/ default is no-op\n}\n\ntemplate <typename When>\nbool\nAnalysisResult::postWaitCallback(bool first,\n                                 bool again,\n                                 const BlockScopeRawPtrQueue &scopes,\n                                 void *context) {\n  \/\/ default is no-op\n  return again;\n}\n\ntemplate <typename When>\nvoid\nAnalysisResult::processScopesParallel(const char *id,\n                                      void *context \/* = NULL *\/) {\n  BlockScopeRawPtrQueue scopes;\n  getScopesSet(scopes);\n\n  DepthFirstVisitor<When, OptVisitor> dfv(\n    OptVisitor<When>(shared_from_this(), scopes.size()));\n\n  bool first = true;\n  bool again;\n  dfv.data().start();\n  do {\n    BlockScopeRawPtrQueue enqueued;\n    again = dfv.visitParallel(scopes, first, enqueued);\n    preWaitCallback<When>(first, scopes, context);\n\n    dfv.data().wait();\n\n    assert(!dfv.data().getQueuedJobs());\n    assert(!dfv.data().getActiveWorker());\n\n    again = postWaitCallback<When>(first, again, scopes, context);\n    first = false;\n  } while (again);\n  dfv.data().stop();\n\n  for (BlockScopeRawPtrQueue::iterator\n       it = scopes.begin(), end = scopes.end();\n       it != end; ++it) {\n    assert((*it)->getMark() == BlockScope::MarkProcessed);\n    assert((*it)->getNumDepsToWaitFor() == 0);\n    assert((*it)->rescheduleFlags() == 0);\n  }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ pre-opt\n\ntemplate<>\nint DepthFirstVisitor<Pre, OptVisitor>::visitScope(BlockScopeRawPtr scope) {\n  int updates, all_updates = 0;\n  StatementPtr stmt = scope->getStmt();\n  if (auto m = dynamic_pointer_cast<MethodStatement>(stmt)) {\n    do {\n      scope->clearUpdated();\n      StatementPtr rep = this->visitStmtRecur(stmt);\n      always_assert(!rep);\n      updates = scope->getUpdated();\n      all_updates |= updates;\n    } while (updates);\n    if (all_updates & BlockScope::UseKindCaller) {\n      all_updates &= ~BlockScope::UseKindCaller;\n    }\n    return all_updates;\n  }\n\n  do {\n    scope->clearUpdated();\n    StatementPtr rep = this->visitStmtRecur(stmt);\n    always_assert(!rep);\n    updates = scope->getUpdated();\n    all_updates |= updates;\n  } while (updates);\n\n  return all_updates;\n}\n\ntemplate<>\nExpressionPtr DepthFirstVisitor<Pre, OptVisitor>::visit(ExpressionPtr e) {\n  return e->preOptimize(this->m_data.m_ar);\n}\n\ntemplate<>\nStatementPtr DepthFirstVisitor<Pre, OptVisitor>::visit(StatementPtr stmt) {\n  return stmt->preOptimize(this->m_data.m_ar);\n}\n\nvoid AnalysisResult::preOptimize() {\n  setPhase(FirstPreOptimize);\n  processScopesParallel<Pre>(\"PreOptimize\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace HPHP\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ code generation functions\n\nstd::string AnalysisResult::prepareFile(const char *root,\n                                        const std::string &fileName,\n                                        bool chop,\n                                        bool stripPath \/* = true *\/) {\n  std::string fullPath = root;\n  if (!fullPath.empty() && fullPath[fullPath.size() - 1] != '\/') {\n    fullPath += \"\/\";\n  }\n\n  auto file = fileName;\n  if (stripPath) {\n    size_t npos = file.rfind('\/');\n    if (npos != std::string::npos) {\n      file = file.substr(npos + 1);\n    }\n  }\n\n  if (chop && file.size() > 4 && file.substr(file.length() - 4) == \".php\") {\n    fullPath += file.substr(0, file.length() - 4);\n  } else {\n    fullPath += file;\n  }\n  for (size_t pos = strlen(root); pos < fullPath.size(); pos++) {\n    if (fullPath[pos] == '\/') {\n      mkdir(fullPath.substr(0, pos).c_str(), 0777);\n    }\n  }\n  return fullPath;\n}\n\nbool AnalysisResult::outputAllPHP(CodeGenerator::Output output) {\n  AnalysisResultPtr ar = shared_from_this();\n  switch (output) {\n  case CodeGenerator::PickledPHP:\n    for (auto& pair : m_files) {\n      auto fullPath = prepareFile(m_outputPath.c_str(), pair.first, false);\n      std::ofstream f(fullPath.c_str());\n      if (f) {\n        CodeGenerator cg(&f, output);\n        cg_printf(\"<?php\\n\");\n        Logger::Info(\"Generating %s...\", fullPath.c_str());\n        pair.second->getStmt()->outputPHP(cg, ar);\n        f.close();\n      } else {\n        Logger::Error(\"Unable to open %s for write\", fullPath.c_str());\n      }\n    }\n    return true; \/\/ we are done\n  default:\n    assert(false);\n  }\n\n  return true;\n}\n","avg_line_length":30.7559580553,"max_line_length":82,"alphanum_fraction":0.6206180454,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6483,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":4.0,"content":"\/*******************************************************************************\n* Copyright 2020-2021 Intel Corporation\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*******************************************************************************\/\n\n#include <math.h>\n\n#include \"common\/primitive_exec_types.hpp\"\n\n#include \"gpu\/ocl\/ocl_utils.hpp\"\n#include \"gpu\/ocl\/ref_reduction.hpp\"\n\nnamespace dnnl {\nnamespace impl {\nnamespace gpu {\nnamespace ocl {\n\nstatus_t ref_reduction_t::pd_t::init_conf(engine_t *engine) {\n    const reduction_pd_t *pd = this;\n\n    const memory_desc_wrapper src_mdw(pd->src_md());\n    const memory_desc_wrapper dst_mdw(pd->dst_md());\n\n    const int ndims = src_mdw.ndims();\n    const auto src_dims = src_mdw.md_->dims;\n    const auto dst_dims = dst_mdw.md_->dims;\n    const auto *compute_engine\n            = utils::downcast<compute::compute_engine_t *>(engine);\n\n    conf.alg = pd->desc()->alg_kind;\n    conf.src_md_info = memory_desc_info_t::create(src_mdw);\n    conf.dst_md_info = memory_desc_info_t::create(dst_mdw);\n    conf.dst_type = dst_mdw.data_type();\n    conf.src_type = src_mdw.data_type();\n    conf.ndims = ndims;\n    conf.power = pd->desc()->p;\n    conf.eps = pd->desc()->eps;\n    conf.dispatch = compute_engine->create_dispatch(src_mdw.md_);\n    conf.div = 1;\n\n    for (int d = 0; d < ndims; d++) {\n        conf.reduce_dims[d] = conf.dst_dims[d] = dim_t {1};\n        const bool is_reduction_dim = src_dims[d] != dst_dims[d];\n        conf.is_reduction_dim[d] = is_reduction_dim;\n\n        if (is_reduction_dim) {\n            conf.reduce_dims[d] = src_dims[d];\n            conf.div *= conf.reduce_dims[d];\n        }\n        conf.dst_dims[d] = dst_mdw.md_->padded_dims[d];\n    }\n\n    conf.dispatch.define_dim(\"D0\", 0, conf.dst_dims[0]);\n    conf.dispatch.define_dim(\"D1\", 0, ndims >= 2 ? conf.dst_dims[1] : 1);\n    conf.dispatch.define_dim(\n            \"D2\", 0, ndims >= 6 ? conf.dst_dims[ndims - 4] : 1);\n    conf.dispatch.define_dim(\n            \"D3\", 0, ndims >= 5 ? conf.dst_dims[ndims - 3] : 1);\n    conf.dispatch.define_dim(\n            \"D4\", 0, ndims >= 4 ? conf.dst_dims[ndims - 2] : 1);\n    conf.dispatch.define_dim(\n            \"D5\", 0, ndims >= 3 ? conf.dst_dims[ndims - 1] : 1);\n    conf.dispatch.generate(false);\n\n    conf.attr_info = attr_info_t::create(pd->attr());\n    set_offsets(src_mdw, conf.off.src_off);\n    set_offsets(dst_mdw, conf.off.dst_off);\n\n    return status::success;\n}\n\nstatic status_t init_kernel_ctx_common(\n        compute::kernel_ctx_t &kernel_ctx, const reduction_conf_t &conf) {\n    using namespace alg_kind;\n\n    kernel_ctx.set_data_type(conf.src_type);\n\n    kernel_ctx.define_int(\"D0\", conf.dst_dims[0]);\n    kernel_ctx.define_int(\"D1\", conf.ndims >= 2 ? conf.dst_dims[1] : 1);\n    kernel_ctx.define_int(\n            \"D2\", conf.ndims >= 6 ? conf.dst_dims[conf.ndims - 4] : 1);\n    kernel_ctx.define_int(\n            \"D3\", conf.ndims >= 5 ? conf.dst_dims[conf.ndims - 3] : 1);\n    kernel_ctx.define_int(\n            \"D4\", conf.ndims >= 4 ? conf.dst_dims[conf.ndims - 2] : 1);\n    kernel_ctx.define_int(\n            \"D5\", conf.ndims >= 3 ? conf.dst_dims[conf.ndims - 1] : 1);\n\n    kernel_ctx.define_int(\"REDUCTION_D0\", conf.reduce_dims[0]);\n    kernel_ctx.define_int(\n            \"REDUCTION_D1\", conf.ndims >= 2 ? conf.reduce_dims[1] : 1);\n    kernel_ctx.define_int(\"REDUCTION_D2\",\n            conf.ndims >= 6 ? conf.reduce_dims[conf.ndims - 4] : 1);\n    kernel_ctx.define_int(\"REDUCTION_D3\",\n            conf.ndims >= 5 ? conf.reduce_dims[conf.ndims - 3] : 1);\n    kernel_ctx.define_int(\"REDUCTION_D4\",\n            conf.ndims >= 4 ? conf.reduce_dims[conf.ndims - 2] : 1);\n    kernel_ctx.define_int(\"REDUCTION_D5\",\n            conf.ndims >= 3 ? conf.reduce_dims[conf.ndims - 1] : 1);\n\n    switch (conf.alg) {\n        case reduction_max: kernel_ctx.define_int(\"IS_MAX\", 1); break;\n        case reduction_min: kernel_ctx.define_int(\"IS_MIN\", 1); break;\n        case reduction_mean: kernel_ctx.define_int(\"IS_MEAN\", 1); break;\n        case reduction_sum: kernel_ctx.define_int(\"IS_SUM\", 1); break;\n        case reduction_mul: kernel_ctx.define_int(\"IS_MUL\", 1); break;\n        case reduction_norm_lp_max:\n            kernel_ctx.define_int(\"IS_LP_MAX\", 1);\n            break;\n        case reduction_norm_lp_sum:\n            kernel_ctx.define_int(\"IS_LP_SUM\", 1);\n            break;\n        case reduction_norm_lp_power_p_max:\n            kernel_ctx.define_int(\"IS_P_MAX\", 1);\n            break;\n        case reduction_norm_lp_power_p_sum:\n            kernel_ctx.define_int(\"IS_P_SUM\", 1);\n            break;\n        default: return status::invalid_arguments;\n    }\n\n    def_offsets(conf.off.src_off, kernel_ctx, \"SRC\", conf.ndims);\n    def_offsets(conf.off.dst_off, kernel_ctx, \"DST\", conf.ndims);\n\n    kernel_ctx.define_int(\"DIV\", conf.div);\n    kernel_ctx.define_int(\"NDIMS\", conf.ndims);\n    kernel_ctx.define_int(\"POWER\", conf.power);\n    kernel_ctx.define_float(\"EPS\", conf.eps);\n\n    def_memory_desc_info(kernel_ctx, conf.src_md_info, \"SRC\");\n    def_memory_desc_info(kernel_ctx, conf.dst_md_info, \"DST\");\n\n    def_attr_info(kernel_ctx, conf.attr_info);\n\n    def_dispatch(kernel_ctx, conf.dispatch);\n\n    return status::success;\n}\n\nstatus_t ref_reduction_t::pd_t::init_kernel_ctx(\n        compute::kernel_ctx_t &kernel_ctx) const {\n    return init_kernel_ctx_common(kernel_ctx, conf);\n}\n\nstatus_t ref_reduction_t::execute_ref(const exec_ctx_t &ctx) const {\n    auto &src = CTX_IN_STORAGE(DNNL_ARG_SRC);\n    auto &dst = CTX_OUT_STORAGE(DNNL_ARG_DST);\n\n    const auto &conf = pd()->conf;\n\n    compute::kernel_arg_list_t reduction_arg_list;\n\n    reduction_arg_list.set(0, src);\n    reduction_arg_list.set(1, dst);\n    append_post_ops_to_arg_list(\n            ctx, reduction_arg_list, 2, conf.attr_info.all_post_ops);\n\n    auto nd_range = conf.dispatch.nd_range();\n\n    return parallel_for(ctx, nd_range, kernel, reduction_arg_list);\n}\n\n} \/\/ namespace ocl\n} \/\/ namespace gpu\n} \/\/ namespace impl\n} \/\/ namespace dnnl\n","avg_line_length":36.4213483146,"max_line_length":80,"alphanum_fraction":0.6456887244,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7710,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/\/ Sequence methods\n\n#include <stdio.h>\n#include <string>\n#include <math.h>\r\n#include \"Sequence.h\"\n\n\nint atomC(const int& ch)\n{\n   static int carbons [] =\n  {\n      0, 3, 0, 3, 4, 5, 9, 2, 6, 6, 0, 6,\n      6, 5, 4, 0, 5, 5, 6, 3, 4, 0, 5, 11,\n      0, 9, 0\n  };\n\n \/\/   std::cout<<carbons[ch&31]<<std::endl;\n    return (isalpha(ch) ? carbons[ch & 31] : 0 );\n}\n\nint atomN(const int& ch)\n{\n     static int nitrogens [] =\n  {\n      0, 1, 1, 1, 1, 1, 1, 1, 3, 1, 0, 2,\n      1, 1, 2, 0, 1, 2, 4, 1, 1, 0, 1, 2,\n      0, 1, 0\n  };\n\n  return (isalpha(ch) ? nitrogens[ch & 31] : 0 );\n}\n\nint atomO(const int& ch)\n{\n     static int oxygens [] =\n  {\n      0, 1, 0, 1, 3, 3, 1, 1, 1, 1, 0, 1, 1,\n      1, 2, 0, 1, 2, 1, 2, 2, 0, 1, 1, 0, 2, 0\n  };\n\n  return (isalpha(ch) ? oxygens[ch & 31] : 0 );\n}\n\nint atomS(const int& ch)\n{\n     static int sulphurs [] =\n  {\n      0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,\n      0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n      0, 0, 0\n  };\n  return (isalpha(ch) ? sulphurs[ch & 31] : 0 );\n}\n\nint atomH(const int& ch)\n{\n     static int hydrogens [] =\n  {\n      0, 5, 0, 5, 5, 7, 9, 3, 7, 11, 0,\n      12, 11, 9, 6, 0, 7, 8, 12, 5, 7, 0, 9,\n      10, 0, 9, 0\n  };\n\n   return (isalpha(ch) ? hydrogens[ch & 31] : 0 );\n}\n\n\nint molExt(const int& ch)\n{\n   static int molEx [] =\n  {\n      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5690,\n      0, 1280, 0\n  };\n\n    return (isalpha(ch) ? molEx[ch & 31] : 0 );\n\n}\n\ndouble pI(const int& ch)\n{\n   static double pIcvs [] =\n  {\n      0.0, 6.01, 0.0, 5.07, 2.77, 3.22, 5.48, 5.97, 7.59, 6.02, 0.0, 9.74,\n      5.98, 5.74, 5.41, 0.0,  6.3, 5.65, 10.76, 5.68, 5.6, 0.0, 5.96, 5.89,\n      0.0, 5.66, 0.0\n  };\n\n    return (isalpha(ch) ? pIcvs[ch & 31] : 0.0);\n}\n\ndouble Kd(const int& ch)\n{\n   static double dissoc [] =\n  {\n      0.0, 0.0, 0.0, -8.5, -3.9, -4.1, 0.0, 0.0, -6.5, 0.0, 0.0, -10.8,\n      0.0, 0.0, 0.0, 0.0,  0.0, 0.0, -12.5, 0.0, 0.0, 0.0, 0.0, 0.0,\n      0.0, -10.1, 0.0\n  };\n\n  return (isalpha(ch) &&  dissoc[ch & 31] < 0.0 ? pow(10.0,dissoc[ch & 31]) : 0.0);\n}\ndouble pK(const int& ch)\n{\n  static double chargecvs [] =\n  {\n      0.0, 0.0, 0.0, 8.5, 3.9, 4.1, 0.0, 0.0, 6.5, 0.0, 0.0, 10.8,\n      0.0, 0.0, 0.0, 0.0,  0.0, 0.0, 12.5, 0.0, 0.0, 0.0, 0.0, 0.0,\n      0.0, 10.1, 0.0\n  };\n\n    return (isalpha(ch) ? chargecvs[ch & 31] : 0.0);\n\n}\n\nint area(const int& ch)\n{\n    static int areacvs[] =\n    {\n      999, 115, 999, 135, 160, 180, 210,  75, 195, 175, 999, 200, 170, 185, 150,\n      999, 145, 190, 225, 115, 140, 999, 140, 255, 999, 999, 999\n    };\n     \n    return (isalpha(ch) ? areacvs[ch & 31] : 0);\n}\n\ndouble mwt(const int& ch)\n{\n    static double mwtcvs[] =\n    {\n      0, 89.09, 132.61, 121.12, 133.10, 147.13, 165.19, 75.07, 155.16, 131.17,\n      0, 146.19, 131.17, 149.21, 132.12, 0, 115.13, 146.15, 174.2, 105.09,\n      119.12, 0, 117.15, 204.23, 0, 181.19, 146.64\n    };\n\n\n\n    return (isalpha(ch) ? mwtcvs[ch & 31] : 0);\n}\n\n  \n\n\n\ndouble kd_hydro(const int& ch)\n{\n  static double kd[] =\n  {\n      999.99, 1.8, 999.99, 2.5, -3.5, -3.5, 2.8, -0.4, -3.2, 4.5, 0.00, -3.9, 3.8, 1.9, -3.5,\n      0.00, -1.6, -3.5, -4.5, -0.8, -0.7, 0.00, 4.2, -0.9, 0.00, -1.3, 0.00\n  };\n\n    return (isalpha(ch) ? kd[ch & 31] : 0.00);\n}\n\ndouble vol(const int& ch)\n{\n    static double aavol[] =\n    {\n      0, 88.6, 999.99, 138.4, 114.1, 143.8, 189.9, 60.1, 153.2, 166.7, 999.99, 168.6, 166.7, 162.9, 111.1,\n      0, 112.7, 108.5, 173.4, 89.0, 116.1, 0.0, 140.0, 227.8, 999.99, 193.6, 999.99\n    };\n\n    return (isalpha(ch) ? aavol[ch & 31] : 0.00 );\n}\n\ndouble pHtoConc(const double& pH)\n{\n  return pow(10.0,-pH);\n}\n\nint aanum(const int& ch)\n{\n    static int aacvs[] =\n    {\n      999, 0, 20, 4, 3, 6, 13, 7, 8, 9, 22, 11, 10, 12, 2,\n      22, 14, 5, 1, 15, 16, 22, 19, 17, 22, 18, 21\n    };\n\n    return (isalpha(ch) ? aacvs[ch & 31] : 22 );\n}\n\nint atoms(const int& ch)\n{\n    static int atomcvs[] =\n    {\n      999, 0, 20, 4, 3, 6, 13, 7, 8, 9, 22, 11, 10, 12, 2,\n      22, 14, 5, 1, 15, 16, 22, 19, 17, 22, 18, 21\n    };\n\n    return (isalpha(ch) ? atomcvs[ch & 31] : 0);\n}\n\nvoid Sequence::calc_charge( double* p, double& c, double& h)\n{\n     double pamino   =  h\/(h+pow(10,-8.6));\n     double pcarboxy  =  h\/(h+pow(10,-3.6));\n\n     \n     \n     c = (p[1]+p[11]+p[8] + pamino) -\n             ((double)aa_comp[18]     -  p[18]  +\n              (double)aa_comp[4]      -  p[4]   +\n              (double)aa_comp[3]      -  p[3]   +\n              (double)aa_comp[6]      -  p[6]   +\n              1.0 - pcarboxy );\n    \n}\n\nvoid Sequence::calc_protons(double* p, const double& h)\n{\n  \/\/get proton scale for amino acids at pH h\n  std::string amino_acids = \"ARNDCQEGHILKMFPSTWYVBZX\";\n  \n  for(unsigned int i=0; i < amino_acids.length(); i++)\n  {\n    double kd = Kd(amino_acids[i]);\n    \/\/std::cout<<\"Kd:  \"<<kd<<std::endl;\n    if(kd != 0.0)\n    {\n     p[i] =  (h\/(h+Kd(amino_acids[i]))) * (double)aa_comp[aanum(amino_acids[i])];\n     \n    }\n    else {\n           p[i] = 0.0;\n         }\n  }\n}\n\nvoid Sequence::calc_IEP()\n{\n  double tpH = 1.0;\n  double bpH = 14.0;\n  \n  double H   = pHtoConc(tpH);\n  double* protons = new double[26];\n  double top,btm,ch;\n\n  calc_protons(protons,H);\n  calc_charge(protons,top,H);\n\n  H=pHtoConc(6.5);\n  calc_protons(protons,H);\n  calc_charge(protons,charge,H);\n\n  H=pHtoConc(bpH);\n  calc_protons(protons,H);\n  calc_charge(protons,btm,H);\n  \n\n  double mid = 0.0;\n  iso_point = tpH;\n  \n  while(bpH-tpH > 0.0001)\n  {\n     mid = ((bpH-tpH)\/2.0) + tpH;\n\n     H   = pHtoConc(mid);\n     calc_protons(protons,H);\n     calc_charge(protons,ch,H);\n\n     \n\n     if( ch > 0.0 )\n     {\n       tpH = mid;\n       continue;\n     }\n\n     if( ch < 0.0 )\n     {\n       bpH = mid;\n       continue;\n     }\n  }\n\n  iso_point = mid;\n   \n}\n\nvoid Sequence::set_composition()\n{\n   for(unsigned int i=0; i< aa.length(); i++)\n   {\n      \n      aa_comp[aanum(aa[i])]++;\n      \n      num_atoms+= atoms(aa[i]);\n      mol_ext  += molExt(aa[i]);\n      mol_wt   += mwt(aa[i]);\n      volume   += vol(aa[i]);\n      surfarea += area(aa[i]);\n      hydro    += kd_hydro(aa[i]);\n      iso_point+= pI(aa[i]);\n\n      atom_comp[0] += atomC(aa[i]);\n      atom_comp[1] += atomH(aa[i]);\n      atom_comp[2] += atomO(aa[i]);\n      atom_comp[3] += atomN(aa[i]);\n      atom_comp[4] += atomS(aa[i]);\n\n     \n\n   \n   }\n\n   \/\/add on N and C terminal atoms H and OH\n   atom_comp[1]+=2;\n   atom_comp[2]++;\n    \n   \/\/water correction to mol_wt\n   mol_wt -= (18.015*(aa.length()-1));\n   calc_IEP();\n\n   num_atoms = atom_comp[0] + atom_comp[1] +\n               atom_comp[2] + atom_comp[3] +\n               atom_comp[4] ;\n   double len= aa.length();   \n   aliphatic =  aa_comp[0]          +\n               ( 2.9 * aa_comp[19]) +\n               ( 3.9 * (aa_comp[10] + aa_comp[9] ) );\n   aliphatic *= 100\/len;\n\n   npos = aa_comp[1] + aa_comp[11];\n   nneg = aa_comp[3] + aa_comp[6];\n \n}\n\n\nvoid Sequence::set_properties()\n{\n  if( aa[0] == 'M')\n    met = true;\n    \n  set_composition();\n\n}       \n\nvoid Sequence::print()\n{\n  std::cout<<id<<\"\\t\"\n           <<met<<\"\\t\"\n           <<aa.length()<<\"\\t\"\n           <<mol_wt<<\"\\t\"\n           <<volume<<\"\\t\"\n           <<surfarea<<\"\\t\"\n           <<hydro<<\"\\t\"\n           <<hydro\/(double)aa.length()<<\"\\t\"\n           <<charge<<\"\\t\"\n           <<mol_ext<<\"\\t\"\n           <<iso_point<<\"\\t\"\n           <<aliphatic<<\"\\t\"\n           <<npos<<\"\\t\"\n           <<nneg<<\"\\t\"\n           <<npos\/(double)aa.length()<<\"\\t\"\n           <<nneg\/(double)aa.length()<<\"\\t\";\n\n  for(unsigned int i=0; i< 23; i++)\n  {\n    std::cout<<aa_comp[i]<<\"\\t\"<<aa_comp[i]\/double(aa.length())<<\"\\t\";\n  }\n\n  for(unsigned int i=0; i<5; i++)\n  {\n    std::cout<<atom_comp[i]<<\"\\t\"<<atom_comp[i]\/double(num_atoms)<<\"\\t\";\n  }\n  std::cout<<num_atoms<<std::endl;\n  \n}\n","avg_line_length":20.7258064516,"max_line_length":106,"alphanum_fraction":0.473151751,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5286,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/\r\n\/\/ (C) Copyright 2001 by Autodesk, Inc. \r\n\/\/\r\n\/\/ Permission to use, copy, modify, and distribute this software in\r\n\/\/ object code form for any purpose and without fee is hereby granted, \r\n\/\/ provided that the above copyright notice appears in all copies and \r\n\/\/ that both that copyright notice and the limited warranty and\r\n\/\/ restricted rights notice below appear in all supporting \r\n\/\/ documentation.\r\n\/\/\r\n\/\/ AUTODESK PROVIDES THIS PROGRAM \"AS IS\" AND WITH ALL FAULTS. \r\n\/\/ AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF\r\n\/\/ MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE.  AUTODESK, INC. \r\n\/\/ DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE\r\n\/\/ UNINTERRUPTED OR ERROR FREE.\r\n\/\/\r\n\/\/ Use, duplication, or disclosure by the U.S. Government is subject to \r\n\/\/ restrictions set forth in FAR 52.227-19 (Commercial Computer\r\n\/\/ Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)\r\n\/\/ (Rights in Technical Data and Computer Software), as applicable.\r\n\/\/\r\n\r\n\/\/ AddFileHandler.cpp : Implementation of CAddFileHandler\r\n#include \"stdafx.h\"\r\n#include \"ETransmitNotifier.h\"\r\n#include \"AddFileHandler.h\"\r\n#include \"string.h\"\r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ CAddFileHandler\r\n\r\nSTDMETHODIMP CAddFileHandler::addFileNotificationHandler(ITransmittalFile * pFile, ITransmittalOperation * pTransmit)\r\n{\r\n\t\/\/\tGet the pathname and filename\r\n\tCComBSTR SrcName;\r\n\t\/\/ sourcePath( [out, retval] BSTR* pVal );\r\n\tpFile->get_sourcePath(&SrcName);\r\n\t\r\n\t\/\/\tConvert BSTR to char * for text manipulation\r\n\tUSES_CONVERSION;\r\n    char * strFile = OLE2T(SrcName);\r\n\t\r\n\t\/\/\tOutput progress to command line\r\n\tacutPrintf(\"\\n***  Handling file : %s ***\", strFile);\r\n\t\r\n\t\/\/ We only want to respond once per transmittal. \r\n\t\/\/\tThe response should be to the main dwg file.\r\n\t\/\/\t(The main drawing file has FileType = eDwgFile).\r\n\tFileType type;\r\n\t\/\/ fileType( [out, retval] FileType* pVal );\r\n\tpFile->get_FileType(&type);\r\n    if (type != eDwgFile)\r\n\t{\r\n        return S_OK;\r\n\t}\t\r\n\t\r\n\t\/\/\tlocate last backslash in filename\r\n\tchar * temp = strrchr(strFile, '\\\\');\r\n\t\r\n\t\/\/\tTruncate string at that point to remove filename from pathname\r\n\t*temp = '\\0';\r\n\t\r\n\t\/\/\tStore path (without filename) in a BSTR for use by COM interface\r\n\tCComBSTR pathName;\r\n\tpathName.Append(strFile);\r\n\t\r\n\t\/\/\tSpecify pathname + filename of the files we want to add.\r\n\tCComBSTR filesToAdd[4];\r\n\tfilesToAdd[0] = pathName;\r\n\tfilesToAdd[0].Append(\"\\\\Test.xml\");\r\n\tfilesToAdd[1] = pathName;\r\n\tfilesToAdd[1].Append(\"\\\\TestSchema.xml\");\r\n\tfilesToAdd[2] = pathName;\r\n\tfilesToAdd[2].Append(\"\\\\testXmlProj.dvb\");\r\n\tfilesToAdd[3] = pathName;\r\n\tfilesToAdd[3].Append(\"\\\\XMLReadMe.doc\");\r\n\t\r\n\t\/\/\tAdd the library files to the transmittal\r\n\tAddFileReturnVal returnVal;\r\n\tITransmittalFile * pIAddedFile = NULL;\r\n\t\r\n\t\/\/\tTry to add all four files.\r\n\tAdesk::Boolean errFlag = Adesk::kFalse;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\t\/\/ addFile(\r\n\t\t\/\/\t\t\t[in] const BSTR bstrFullPath,\r\n\t\t\/\/\t\t\t[in] const BSTR bstrVersion,\r\n\t\t\/\/\t\t\t[in] const ITransmittalFile* pIParentFile,\r\n\t\t\/\/\t\t\t[in] BOOL bAddedBy3rdParty,\r\n\t\t\/\/\t\t\t[out] ITransmittalFile** ppIAddedFile,\r\n\t\t\/\/\t\t\t[out, retval] AddFileReturnVal* pRetVal );\r\n\t\tpTransmit->addFile(filesToAdd[i], NULL, pFile, TRUE, &pIAddedFile, &returnVal);\r\n\t\tif ((returnVal != eFileAdded) || (pIAddedFile == NULL))\r\n\t\t{\r\n\t\t\terrFlag = Adesk::kTrue;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t\/\/\tEven if addFile returns eFileAdded, we have to check that the new file\r\n\t\t\t\/\/\tdoes exist. If the pathname was wrong, then addFile can return eFileAdded, \r\n\t\t\t\/\/\teven if the file cannot be found.\r\n\t\t\tlong fileExists;\r\n\t\t\t\/\/ fileExists( [out, retval] BOOL* pVal );\r\n\t\t\tpIAddedFile->get_fileExists(&fileExists);\r\n\t\t\tif ( !fileExists )\r\n\t\t\t{\r\n\t\t\t\terrFlag = Adesk::kTrue;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t\/\/\tAdd text to transmittal report.\t\r\n\t\r\n\tlong reportStorageIndex = -1;\r\n\tCComBSTR ReportText;\r\n\t\r\n\tReportText = \"\\r\\n*** Notifier Sample Report ***\\r\\n\\r\\n\";\r\n\tReportText.Append(\"Demonstrated at iDevelop - 2nd November, 2000 \\r\\n\");\r\n\tReportText.Append(\"http:\/\/www.autodesk.com\/idevelop2000 \\r\\n\\r\\n\");\r\n\t\/\/ addToReport(\r\n\t\/\/\t\t\t\t[in] const BSTR bstrTextToAdd,\r\n\t\/\/\t\t\t\t[in] const long nIndex,\r\n\t\/\/\t\t\t\t[out, retval] long* pnIndex);\r\n\tpTransmit->addToReport(ReportText, -1, &reportStorageIndex);\r\n\t\r\n\tif (errFlag)\t\/\/\treport failure.\r\n\t{\r\n\t\tReportText = \"One or more files could not be included with the drawing '\";\r\n\t\tReportText.Append(SrcName);\r\n\t\tReportText.Append(\"'.\\r\\n\");\r\n\t\tReportText += \"Please contact the sender.\\r\\n\\r\\n\";\r\n\t\tpTransmit->addToReport(ReportText, reportStorageIndex, NULL);\r\n\t}\r\n\telse\t\t\/\/\treport success\r\n\t{\r\n\t\tReportText = \"The drawing '\";\r\n\t\tReportText.Append(SrcName);\r\n\t\tReportText.Append(\"' was created from an XML document using a VBA macro.\\r\\n\");\r\n\t\tReportText.Append(\"Please see the included Read Me file for more details.\\r\\n\\r\\n\") ;\r\n\t\tpTransmit->addToReport(ReportText, reportStorageIndex, NULL);\r\n\t}\r\n\treturn S_OK;\r\n}\r\n\r\n\r\nSTDMETHODIMP CAddFileHandler::beginFilesGraphCreation(ITransmittalOperation * pTransmit)\r\n{\r\n\tacedPrompt(\"\\n\\n*** Start of Files Graph Creation ***\\n\");\r\n\treturn S_OK;\r\n}\r\n\r\n\r\nSTDMETHODIMP CAddFileHandler::endFilesGraphCreation(ITransmittalOperation * pTransmit)\r\n{\r\n\tacedPrompt(\"\\n\\n*** End of Files Graph Creation ***\\n\");\r\n\treturn S_OK;\r\n}\r\n","avg_line_length":33.0375,"max_line_length":118,"alphanum_fraction":0.6727203935,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7239,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"vgelib\/vgelib.hpp\"\r\n\r\nvoid vge::Buffer::GetPtr(void*& boundMemory)\r\n{\r\n\tchar* memPtr = nullptr;\r\n\tif (_owner != nullptr) {\r\n\t\tmemPtr = static_cast<char*>(_owner->get_memPtr());\r\n\t}\r\n\tif (memPtr == nullptr) {\r\n\t\tthrow std::runtime_error(\"Buffer memory not bound\");\r\n\t}\r\n\tboundMemory = memPtr + _offset;\r\n}\r\n\r\nvoid vge::Buffer::NewView(vk::Format format, uint64_t offset, uint64_t size, BufferView*& view)\r\n{\r\n\tview = new BufferView(_dev, _buffer, format);\r\n\tview->init(size, offset);\r\n}\r\n\r\nvoid vge::Buffer::Dispose()\r\n{\r\n\tif (!!_buffer) {\r\n\t\t_dev->get_device().destroyBuffer(_buffer, allocator, _dev->get_dispatch());\r\n\t\t_buffer = nullptr;\r\n\t\t_owner = nullptr;\r\n\t}\r\n}\r\n\r\nvk::MemoryRequirements vge::Buffer::getMemoryRequirements(bool& hostMemory)\r\n{\r\n\thostMemory = _hostMemory;\r\n\treturn _dev->get_device().getBufferMemoryRequirements(_buffer, _dev->get_dispatch());\r\n}\r\n\r\nvoid vge::Buffer::bind()\r\n{\r\n\t_dev->get_device().bindBufferMemory(_buffer, _owner->get_mem(), _offset, _dev->get_dispatch());\r\n}\r\n\r\nvoid vge::Buffer::init()\r\n{\r\n\tvk::BufferCreateInfo bci;\r\n\tbci.size = _size;\r\n\tbci.usage = _usage;\r\n\t_buffer = _dev->get_device().createBuffer(bci, allocator, _dev->get_dispatch());\r\n}\r\n\r\n\r\nvoid vge::Image::Dispose()\r\n{\r\n\tif (_swapchainImage) {\r\n\t\treturn;\r\n\t}\r\n\tif (!!_image) {\r\n\t\t_dev->get_device().destroyImage(_image, allocator, _dev->get_dispatch());\r\n\t\t_image = nullptr;\r\n\t}\r\n}\r\n\r\nvk::MemoryRequirements vge::Image::getMemoryRequirements(bool& hostMemory)\r\n{\r\n\thostMemory = false;\r\n\treturn _dev->get_device().getImageMemoryRequirements(_image, _dev->get_dispatch());\r\n}\r\n\r\nvoid vge::Image::bind()\r\n{\r\n\t_dev->get_device().bindImageMemory(_image, _owner->get_mem(), _offset, _dev->get_dispatch());\r\n}\r\n\r\nvoid vge::Image::NewView(vge::ImageRange *range, ImageView*& view, bool cubeView)\r\n{\r\n\tauto ivci = cvInfo(0, 0);\r\n\tivci.subresourceRange.layerCount = range->LayerCount;\r\n\tivci.subresourceRange.baseArrayLayer = range->FirstLayer;\r\n\tivci.subresourceRange.levelCount = range->LevelCount;\r\n\tivci.subresourceRange.baseMipLevel = range->FirstMipLevel;\r\n\tif (cubeView) {\r\n\t\tif (ivci.viewType == vk::ImageViewType::e2D) {\r\n\t\t\tivci.viewType = vk::ImageViewType::eCube;\r\n\t\t}\r\n\t} else {\r\n\t\tif (range->LayerCount > 1 && ivci.viewType == vk::ImageViewType::e2D) {\r\n\t\t\tivci.viewType = vk::ImageViewType::e2DArray;\r\n\t\t}\r\n\t}\r\n\tauto vh = _dev->get_device().createImageView(ivci, allocator, _dev->get_dispatch());\r\n\tview = new ImageView(_dev, vh, this, *range);\r\n}\r\n\r\nvoid vge::Image::init()\r\n{\r\n\tvk::ImageCreateInfo ici;\r\n\tici.arrayLayers = _description.Layers;\r\n\tici.format = _description.Format;\r\n\tici.samples = vk::SampleCountFlagBits::e1;\r\n\tici.imageType = vk::ImageType::e2D;\r\n\tici.extent.width = _description.Width;\r\n\tici.extent.height = _description.Height;\r\n\tif (_description.Depth > 1) {\r\n\t\tici.imageType = vk::ImageType::e3D;\r\n\t\tici.extent.depth = _description.Depth;\r\n\t}\r\n\telse {\r\n\t\tici.extent.depth = 1;\r\n\t}\r\n\tici.mipLevels = _description.MipLevels;\r\n\tici.usage = _usage;\r\n\tici.sharingMode = vk::SharingMode::eExclusive;\r\n\tif (ici.arrayLayers == 6) {\r\n\t\tici.flags = vk::ImageCreateFlagBits::eCubeCompatible;\r\n\t}\r\n\t_image = _dev->get_device().createImage(ici, allocator, _dev->get_dispatch());\r\n}\r\n\r\nvk::ImageViewCreateInfo vge::Image::cvInfo(int32_t layer, int32_t mipLevel)\r\n{\r\n\tvk::ImageViewCreateInfo ivci;\r\n\tivci.image = _image;\r\n\tivci.format = _description.Format;\r\n\tivci.viewType = get_viewType();\r\n\tivci.components.a = vk::ComponentSwizzle::eA;\r\n\tivci.components.r = vk::ComponentSwizzle::eR;\r\n\tivci.components.g = vk::ComponentSwizzle::eG;\r\n\tivci.components.b = vk::ComponentSwizzle::eB;\r\n\tivci.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;\r\n\tif (ivci.format == vk::Format::eD32Sfloat || ivci.format == vk::Format::eD32SfloatS8Uint || ivci.format == vk::Format::eD16Unorm ||\r\n\t\tivci.format == vk::Format::eD16UnormS8Uint || ivci.format == vk::Format::eD24UnormS8Uint) {\r\n\t\tivci.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eDepth;\r\n\t}\r\n\tivci.subresourceRange.baseArrayLayer = layer;\r\n\tivci.subresourceRange.baseMipLevel = mipLevel;\r\n\treturn ivci;\r\n}\r\n\r\nvoid vge::MemoryBlock::Reserve(MemoryObject* obj, bool &ok)\r\n{\r\n\tbool hostMemory;\r\n\tauto mr = obj->getMemoryRequirements(hostMemory);\r\n\tauto mi = findMemIndex(mr, hostMemory);\r\n\tsize_t offset = 0;\r\n\tif (_objects.size() == 0) {\r\n\t\t_memIndex = mi;\r\n\t} else {\r\n\t\tif (_memIndex != mi) {\r\n\t\t\tok = 0;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\toffset = _objects[_objects.size() - 1]->_offset + _objects[_objects.size() - 1]->_allocSize;\r\n\t}\r\n\tok = 1;\r\n\t_hostMem |= hostMemory;\r\n\tsize_t rem = mr.size % mr.alignment;\r\n\tif (rem > 0) {\r\n\t\tobj->_allocSize = mr.size + (mr.alignment - rem);\r\n\t} else {\r\n\t\tobj->_allocSize = mr.size;\r\n\t}\r\n\trem = offset % mr.alignment;\r\n\tif (rem != 0) {\r\n\t\toffset += mr.alignment - rem;\r\n\t}\r\n\r\n\tobj->_offset = offset;\r\n\t_objects.push_back(obj);\r\n}\r\n\r\nvoid vge::MemoryBlock::Allocate()\r\n{\r\n\tif (_objects.size() == 0) {\r\n\t\tthrow std::runtime_error(\"Can't allocate empty memory block!\");\r\n\t}\r\n\tsize_t size = _objects[_objects.size() - 1]->_offset + _objects[_objects.size() - 1]->_allocSize;\r\n\tvk::MemoryAllocateInfo mai;\r\n\tmai.allocationSize = size;\r\n\tmai.memoryTypeIndex = _memIndex;\r\n\t_mem = _dev->get_device().allocateMemory(mai, allocator, _dev->get_dispatch());\r\n\tif (_hostMem) {\r\n\t\t_memPtr = _dev->get_device().mapMemory(_mem, 0, size, vk::MemoryMapFlagBits(), _dev->get_dispatch());\r\n\t}\r\n\r\n\tsize_t offset = 0;\r\n\tfor (auto obj : _objects) {\r\n\t\tobj->_owner = this;\r\n\t\tobj->bind();\r\n\t}\r\n}\r\n\r\nvoid vge::MemoryBlock::Dispose()\r\n{\r\n\tif (_memPtr != nullptr) {\r\n\t\t_dev->get_device().unmapMemory(_mem, _dev->get_dispatch());\r\n\t\t_memPtr = nullptr;\r\n\t}\r\n\tif (!!_mem) {\r\n\t\tfor (auto obj : _objects) {\r\n\t\t\tobj->Dispose();\r\n\t\t}\r\n\t\t_objects.clear();\r\n\t\t_dev->get_device().freeMemory(_mem, allocator, _dev->get_dispatch());\r\n\t\t_mem = nullptr;\r\n\t}\r\n}\r\n\r\nuint32_t vge::MemoryBlock::findMemIndex(vk::MemoryRequirements mr, bool hostMemory)\r\n{\r\n\tvk::MemoryPropertyFlags hmFlags = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;\r\n\tauto mps = _dev->get_memoryProps();\r\n\tfor (uint32_t memIndex = 0; memIndex < mps.memoryTypeCount; memIndex++) {\r\n\t\tif ((mr.memoryTypeBits & (1 << memIndex)) == 0) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (!hostMemory && (mps.memoryTypes[memIndex].propertyFlags & vk::MemoryPropertyFlagBits::eDeviceLocal) == vk::MemoryPropertyFlagBits::eDeviceLocal) {\r\n\t\t\treturn memIndex;\r\n\t\t}\r\n\t\tif (hostMemory && (mps.memoryTypes[memIndex].propertyFlags & hmFlags) == hmFlags) {\r\n\t\t\treturn memIndex;\r\n\t\t}\r\n\t}\r\n\tthrow std::runtime_error(\"No suitable memory found!\");\r\n}\r\n\r\nvoid vge::ImageView::Dispose()\r\n{\r\n\tif (!!_view) {\r\n\t\t\r\n\t\t_dev->get_device().destroyImageView(_view, allocator, _dev->get_dispatch());\r\n\t\t_view = nullptr;\r\n\t}\r\n}\r\n\r\nvoid vge::BufferView::init(size_t size, size_t offset)\r\n{\r\n\tvk::BufferViewCreateInfo bvci;\r\n\tbvci.buffer = _buffer;\r\n\tbvci.format = _format;\r\n\tbvci.offset = offset;\r\n\tif (size > 0) {\r\n\t\tbvci.range = size;\r\n\t} else {\r\n\t\tbvci.range = VK_WHOLE_SIZE;\r\n\t}\r\n\t_view = _dev->get_device().createBufferView(bvci, allocator, _dev->get_dispatch());\r\n}\r\n\r\nvoid vge::BufferView::Dispose()\r\n{\r\n\t_dev->get_device().destroyBufferView(_view, allocator, _dev->get_dispatch());\r\n\tdelete this;\r\n}\r\n","avg_line_length":28.7261904762,"max_line_length":153,"alphanum_fraction":0.6788230419,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":99398,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/**\n * Copyright (c) 2017-present, Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"glow\/LLVMIRCodeGen\/LLVMIRGen.h\"\n\n#include \"CommandLine.h\"\n#include \"glow\/LLVMIRCodeGen\/AllocationsInfo.h\"\n#include \"glow\/LLVMIRCodeGen\/LLVMBackend.h\"\n\n#include \"glow\/Graph\/Graph.h\"\n#include \"glow\/IR\/IRUtils.h\"\n#include \"glow\/IR\/Instrs.h\"\n#include \"glow\/Quantization\/Base\/Base.h\"\n\n#include \"llvm\/ExecutionEngine\/ExecutionEngine.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n\nusing namespace glow;\nusing llvm::cast;\nusing llvm::dyn_cast;\nusing llvm::isa;\n\nstatic llvm::cl::opt<bool>\n    dumpIR(\"dump-llvm-ir\",\n           llvm::cl::desc(\"Dump the LLVM-IR of the jitted code\"),\n           llvm::cl::init(false), llvm::cl::cat(getLLVMBackendCat()));\n\nstatic llvm::cl::opt<bool>\n    dumpJitAsm(\"dump-llvm-asm\",\n               llvm::cl::desc(\"Dump the textual assembly of the jitted code\"),\n               llvm::cl::init(false), llvm::cl::cat(getLLVMBackendCat()));\n\nllvm::cl::opt<bool>\n    emitDebugInfo(\"g\", llvm::cl::desc(\"Emit debug information for debuggers\"),\n                  llvm::cl::init(false), llvm::cl::cat(getLLVMBackendCat()));\n\nllvm::cl::opt<llvm::Reloc::Model> relocModel(\n    \"relocation-model\",\n    llvm::cl::desc(\n        \"Specify which relocation model to use on the target machine\"),\n    llvm::cl::values(\n        clEnumValN(llvm::Reloc::Static, \"static\", \"Non-relocatable code\"),\n        clEnumValN(llvm::Reloc::PIC_, \"pic\", \"Position independent code\")),\n    llvm::cl::init(llvm::Reloc::Static), llvm::cl::cat(getLLVMBackendCat()));\n\n\/\/\/ Limitation of number of arguments for `emitDataParallelKernel`.\nconstexpr static size_t kArgLimit = 64;\n\n\/\/\/ Generate the LLVM MAttr list of attributes.\nstatic llvm::SmallVector<std::string, 0> getMachineAttributes() {\n  llvm::SmallVector<std::string, 0> result;\n  llvm::StringMap<bool> hostFeatures;\n  if (llvm::sys::getHostCPUFeatures(hostFeatures)) {\n    for (auto &feature : hostFeatures) {\n      if (feature.second) {\n        llvm::StringRef fn = feature.first();\n        \/\/ Skip avx512 because LLVM does not support it well.\n        if (fn.startswith(\"avx512\")) {\n          continue;\n        }\n        result.push_back(fn);\n      }\n    }\n  }\n  return result;\n}\n\n\/\/\/ Returns the CPU hostname.\nstatic llvm::StringRef getHostCpuName() {\n  auto cpu_name = llvm::sys::getHostCPUName();\n  \/\/ Skip avx512 because LLVM does not support it well.\n  cpu_name.consume_back(\"-avx512\");\n  return cpu_name;\n}\n\n\/\/\/ Query the TargetMachine to get the pointer size in bits\nstatic unsigned getPointerNumBits(const llvm::TargetMachine &TM) {\n#if LLVM_VERSION_MAJOR >= 7\n  return TM.getPointerSize(0) * 8;\n#else\n  return TM.getPointerSize() * 8;\n#endif\n}\n\nLLVMIRGen::LLVMIRGen(const IRFunction *F, AllocationsInfo &allocationsInfo,\n                     std::string mainEntryName, llvm::StringRef libjitBC)\n    : F_(F), allocationsInfo_(allocationsInfo), mainEntryName_(mainEntryName),\n      libjitBC_(libjitBC) {}\n\nvoid LLVMIRGen::initTargetMachine(\n    llvm::StringRef target, llvm::StringRef arch, llvm::StringRef cpu,\n    const llvm::SmallVectorImpl<std::string> &targetFeatures,\n    llvm::CodeModel::Model codeModel) {\n  llvm::InitializeAllTargets();\n  llvm::InitializeAllTargetMCs();\n  llvm::InitializeAllAsmPrinters();\n\n  if (target.empty()) {\n    TM_.reset(llvm::EngineBuilder()\n                  .setCodeModel(codeModel)\n                  .setRelocationModel(relocModel)\n                  .selectTarget(llvm::Triple(), arch, getHostCpuName(),\n                                getMachineAttributes()));\n  } else {\n    TM_.reset(\n        llvm::EngineBuilder()\n            .setCodeModel(codeModel)\n            .setRelocationModel(relocModel)\n            .selectTarget(llvm::Triple(target), arch, cpu, targetFeatures));\n  }\n  assert(TM_ && \"Could not initialize the target machine\");\n}\n\nstd::string LLVMIRGen::getMainEntryName() const {\n  return mainEntryName_.empty() ? \"main\" : mainEntryName_;\n}\n\nvoid LLVMIRGen::setMainEntryName(std::string name) { mainEntryName_ = name; }\n\n\/\/\/ Load base addresses of different memory areas so that they can be easily\n\/\/\/ reused during codegen.\nvoid LLVMIRGen::loadBaseAddresses(llvm::IRBuilder<> &builder) {\n  auto *F = builder.GetInsertBlock()->getParent();\n\n  \/\/ Load the base addresses at the beginning of the entry function once they\n  \/\/ are set. They won't change after this point and all relative addressing\n  \/\/ computations will simply use them.\n  auto sizeTTy = builder.getIntNTy(getTargetSizeTWidth());\n  baseActivationsAddr_ = builder.CreatePtrToInt(F->args().begin() + 2, sizeTTy);\n  baseConstantWeightVarsAddr_ =\n      builder.CreatePtrToInt(F->args().begin(), sizeTTy);\n  baseMutableWeightVarsAddr_ =\n      builder.CreatePtrToInt(F->args().begin() + 1, sizeTTy);\n  offsetsArray_ = F->args().begin() + 3;\n}\n\n\/\/ Search for the standard library bitcode file on disk and load it into an\n\/\/ LLVM module. We search for the standard library around the current executable\n\/\/ and also in the current directory.\nstatic std::unique_ptr<llvm::Module>\nloadStandardLibrary(llvm::LLVMContext *ctx, llvm::StringRef filename,\n                    llvm::StringRef libjitBC) {\n  using llvm::sys::path::append;\n  using llvm::sys::path::parent_path;\n\n  llvm::SMDiagnostic error;\n\n  \/\/ Parse the compiled-in image of libjit and return the resulting Module.\n  return llvm::parseIR(\n      llvm::MemoryBufferRef(\n          llvm::StringRef(reinterpret_cast<const char *>(libjitBC.data()),\n                          libjitBC.size()),\n          \"libjit.bc\"),\n      error, *ctx);\n}\n\n\/\/\/ Register a diagnostics handler that prevents the compiler from printing to\n\/\/\/ stdout.\nstatic void registerEmptyDiagHandler(llvm::LLVMContext &ctx) {\n#if LLVM_VERSION_MAJOR >= 6\n  ctx.setDiagnosticHandlerCallBack(\n      [](const llvm::DiagnosticInfo &DI, void *Context) {\n        \/\/ Do not emit any warnings or diagnostics when JITting.\n      });\n#else\n  ctx.setDiagnosticHandler([](const llvm::DiagnosticInfo &DI, void *Context) {\n    \/\/ Do not emit any warnings or diagnostics when JITting.\n  });\n#endif\n}\n\nvoid LLVMIRGen::initCodeGen() {\n  instrNumbering_.reset(new InstructionNumbering(*F_));\n  \/\/ Load the jit library as a new module.\n  llmodule_ = loadStandardLibrary(&ctx_, \"libjit.bc\", libjitBC_);\n  GLOW_ASSERT(llmodule_.get() && \"Unable to load the JIT library.\");\n\n  \/\/ By default, LLVM would emit some diagnostics, remarks, etc. It is fine for\n  \/\/ a static compiler, but not necessary for a JIT. Let's disable it by\n  \/\/ providing a dummy diagnostics handler, that does not emit anything.\n  \/\/ In particular, this allows us to get rid of the annoying \"cannot vectorize\"\n  \/\/ warnings.\n  registerEmptyDiagHandler(ctx_);\n\n  \/\/ Assign the target information to the module.\n  llmodule_->setDataLayout(getTargetMachine().createDataLayout());\n\n  \/\/ Create the entry function into the LLVM module.\n  auto int8PtrTy = llvm::Type::getInt8PtrTy(ctx_);\n  auto sizeTPtrTy = llvm::Type::getIntNPtrTy(ctx_, getTargetSizeTWidth());\n  \/\/ The entry point has the following API:\n  \/\/ void entry(uint8_t *baseConstantWeightVars, uint8_t\n  \/\/ *baseInoutWeightVars, uint8_t *baseActivations, size_t *offsets);\n  llvm::Type *voidTy = llvm::Type::getVoidTy(ctx_);\n  llvm::FunctionType *jitFuncTy = llvm::FunctionType::get(\n      voidTy, {int8PtrTy, int8PtrTy, int8PtrTy, sizeTPtrTy}, false);\n  auto *func = llvm::Function::Create(\n      jitFuncTy, llvm::Function::ExternalLinkage, \"main\", llmodule_.get());\n\n  \/\/ Setup the entry basic block and initialize the IR builder.\n  llvm::BasicBlock *entry_bb = llvm::BasicBlock::Create(ctx_, \"entry\", func);\n  builder_ = llvm::make_unique<llvm::IRBuilder<>>(entry_bb);\n\n  \/\/ Initialize the debug information emission.\n  initDebugInfo();\n}\n\n\/\/\/ \\returns the LLVM type corresponding to the type of elements stored in \\p\n\/\/\/ val.\nllvm::Type *LLVMIRGen::getElementType(llvm::IRBuilder<> &builder,\n                                      const Value *val) {\n  switch (val->getElementType()) {\n  case ElemKind::Int64ITy:\n    return builder.getInt64Ty();\n  case ElemKind::FloatTy:\n    return builder.getFloatTy();\n  case ElemKind::Float16Ty:\n    llvm_unreachable(\"Not yet implemented\");\n  case ElemKind::Int8QTy:\n    return builder.getInt8Ty();\n  case ElemKind::Int16QTy:\n    return builder.getInt16Ty();\n  case ElemKind::Int32QTy:\n    return builder.getInt32Ty();\n  case ElemKind::Int32ITy:\n    return builder.getInt32Ty();\n  case ElemKind::UInt8FusedQTy:\n    return builder.getInt8Ty();\n  case ElemKind::BoolTy:\n    static_assert(sizeof(bool) == sizeof(int8_t),\n                  \"Bool is expected to be the same size as int8.\");\n    return builder.getInt8Ty();\n  }\n  return nullptr;\n}\n\nvoid LLVMIRGen::performCodeGen() {\n  auto *func = builder_->GetInsertBlock()->getParent();\n  loadBaseAddresses(*builder_);\n\n  generateLLVMIRForModule(*builder_);\n\n  \/\/ Terminate the function.\n  builder_->CreateRetVoid();\n\n  if (dumpIR) {\n    llvm::outs() << \"LLVM module before optimizations:\\n\";\n    llmodule_->print(llvm::outs(), nullptr);\n  }\n\n  \/\/ Perform verification if no debug info is being emitted.\n  \/\/ Otherwise, the verification is performed later by\n  \/\/ generateDebugInfo, once the debug info emission is finalized.\n  if (!emitDebugInfo) {\n    \/\/ Perform verification, but ignore any debug info errors for now.\n    \/\/ Debug info errors will be checked later by generateDebugInfo.\n    bool brokenDebugInfo = false;\n    (void)brokenDebugInfo;\n    assert(!llvm::verifyModule(getModule(), &llvm::errs(), &brokenDebugInfo) &&\n           \"LLVM module verification error\");\n  }\n\n  \/\/ Optimize the module.\n  optimizeLLVMModule(func, getTargetMachine());\n\n  \/\/ Generate debug information.\n  generateDebugInfo();\n\n  \/\/ And pass the ownership to the JIT.\n\n  if (dumpIR) {\n    llvm::outs() << \"LLVM module after optimizations:\\n\";\n    llmodule_->print(llvm::outs(), nullptr);\n  }\n\n  if (dumpJitAsm) {\n    llvm::SmallVector<char, 0> asmBuffer;\n    llvm::raw_svector_ostream asmStream(asmBuffer);\n    llvm::legacy::PassManager PM;\n#if FACEBOOK_INTERNAL && LLVM_VERSION_PATCH < 20181009\n    getTargetMachine().addPassesToEmitFile(\n        PM, asmStream, llvm::TargetMachine::CodeGenFileType::CGFT_AssemblyFile);\n#elif LLVM_VERSION_MAJOR > 6\n    getTargetMachine().addPassesToEmitFile(\n        PM, asmStream, nullptr,\n        llvm::TargetMachine::CodeGenFileType::CGFT_AssemblyFile);\n#else\n    getTargetMachine().addPassesToEmitFile(\n        PM, asmStream, llvm::TargetMachine::CodeGenFileType::CGFT_AssemblyFile);\n#endif\n\n    PM.run(*llmodule_);\n    llvm::outs() << asmStream.str();\n  }\n}\n\nllvm::Value *LLVMIRGen::emitValueAddress(llvm::IRBuilder<> &builder,\n                                         const glow::Value *val) {\n  assert(allocationsInfo_.allocatedAddress_.count(val) &&\n         \"Value address was not allocated\");\n  auto sizeTTy = builder.getIntNTy(getTargetSizeTWidth());\n  llvm::Type *T = nullptr;\n\n  switch (val->getElementType()) {\n  case ElemKind::FloatTy:\n    T = llvm::Type::getFloatPtrTy(ctx_);\n    break;\n  case ElemKind::Int8QTy:\n    T = llvm::Type::getInt8PtrTy(ctx_);\n    break;\n  case ElemKind::Int16QTy:\n    T = llvm::Type::getInt16PtrTy(ctx_);\n    break;\n  case ElemKind::Int32QTy:\n    T = llvm::Type::getInt32PtrTy(ctx_);\n    break;\n  case ElemKind::Int64ITy:\n    T = llvm::Type::getInt64PtrTy(ctx_);\n    break;\n  case ElemKind::Int32ITy:\n    T = llvm::Type::getInt32PtrTy(ctx_);\n    break;\n  case ElemKind::UInt8FusedQTy:\n    T = llvm::Type::getInt8PtrTy(ctx_);\n    break;\n  case ElemKind::BoolTy:\n    T = llvm::Type::getInt8PtrTy(ctx_);\n    break;\n  default:\n    llvm_unreachable(\"Unimplemented\");\n    break;\n  }\n\n  assert(allocationsInfo_.valueNumbers_.count(val));\n  auto &kindAndValue = allocationsInfo_.valueNumbers_[val];\n\n  \/\/ Get the required base address.\n  llvm::Value *baseAddrValue = nullptr;\n  switch (kindAndValue.first) {\n  case AllocationsInfo::ValueKind::Activation:\n    baseAddrValue = baseActivationsAddr_;\n    break;\n  case AllocationsInfo::ValueKind::ConstantWeight:\n    baseAddrValue = baseConstantWeightVarsAddr_;\n    break;\n  case AllocationsInfo::ValueKind::MutableWeight:\n    baseAddrValue = baseMutableWeightVarsAddr_;\n    break;\n  }\n\n  \/\/ Use relative addressing.\n  \/\/ Get offset.\n  auto valueIdx = llvm::ConstantInt::get(sizeTTy, kindAndValue.second);\n  auto offsetAddr = builder.CreateGEP(sizeTTy, offsetsArray_, valueIdx);\n  auto offsetValue = builder.CreateLoad(sizeTTy, offsetAddr);\n  \/\/ Add offset to the base address.\n  llvm::Value *addr = builder.CreateAdd(baseAddrValue, offsetValue);\n  return builder.CreateIntToPtr(addr, T);\n}\n\nllvm::Value *\nLLVMIRGen::emitConstOffsetsArray(llvm::IRBuilder<> &builder,\n                                 const AllocationsInfo &allocationsInfo) {\n  auto sizeTType = builder.getIntNTy(getTargetSizeTWidth());\n  std::vector<llvm::Constant *> elems(allocationsInfo.valueNumbers_.size());\n  for (auto &I : allocationsInfo.valueNumbers_) {\n    auto *V = I.first;\n    auto offset = I.second.second;\n    elems[offset] = llvm::ConstantInt::get(\n        sizeTType, allocationsInfo.allocatedAddress_.lookup(V));\n  }\n  auto *arr = llvm::ConstantArray::get(\n      llvm::ArrayType::get(sizeTType, elems.size()), elems);\n  \/\/ Ensure that the same casted global variable is used for the equivalent\n  \/\/ const arrays. This is important for the later function specialization pass.\n  \/\/ LLVM does not do it automatically for this code pattern involving global\n  \/\/ variables. It also reduces the number of variables.\n  auto &constArrayVar = constArrayPtrs_[arr];\n  if (constArrayVar && constArrayVar->getType() == sizeTType->getPointerTo())\n    return constArrayVar;\n\n  auto *M = builder.GetInsertBlock()->getModule();\n\n  auto *G = new llvm::GlobalVariable(*M, arr->getType(), true,\n                                     llvm::GlobalValue::InternalLinkage, arr);\n  constArrayVar = builder.CreateBitCast(G, sizeTType->getPointerTo());\n  return constArrayVar;\n}\n\ntemplate <typename T>\nllvm::Value *LLVMIRGen::emitConstSizeTArray(llvm::IRBuilder<> &builder,\n                                            llvm::ArrayRef<T> vals) {\n  assert(std::is_integral<T>() && \"Can only convert integral type to size_t.\");\n  auto SizeTType = builder.getIntNTy(getTargetSizeTWidth());\n  std::vector<llvm::Constant *> elems;\n  for (auto I : vals) {\n    assert(I >= 0 && \"Only allow casting positive values into size_t.\");\n    assert(I <= std::numeric_limits<size_t>::max() &&\n           \"Do not allow overflow of size_t.\");\n    elems.push_back(llvm::ConstantInt::get(SizeTType, (size_t)I));\n  }\n  return emitConstArray(builder, elems, SizeTType);\n}\n\nllvm::Value *LLVMIRGen::emitConstArray(llvm::IRBuilder<> &builder,\n                                       llvm::ArrayRef<llvm::Constant *> vals,\n                                       llvm::Type *elemTy) {\n  std::vector<llvm::Constant *> elems;\n  for (auto I : vals) {\n    elems.push_back(cast<llvm::Constant>(builder.CreateBitCast(I, elemTy)));\n  }\n  auto *arr = llvm::ConstantArray::get(\n      llvm::ArrayType::get(elemTy, elems.size()), elems);\n  \/\/ Ensure that the same casted global variable is used for the equivalent\n  \/\/ const arrays. This is important for the later function specialization pass.\n  \/\/ LLVM does not do it automatically for this code pattern involving global\n  \/\/ variables. It also reduces the number of variables.\n  auto &constArrayVar = constArrayPtrs_[arr];\n  if (constArrayVar && constArrayVar->getType() == elemTy->getPointerTo())\n    return constArrayVar;\n\n  auto *M = builder.GetInsertBlock()->getModule();\n\n  auto *G = new llvm::GlobalVariable(*M, arr->getType(), true,\n                                     llvm::GlobalValue::InternalLinkage, arr);\n  constArrayVar = builder.CreateBitCast(G, elemTy->getPointerTo());\n  return constArrayVar;\n}\n\nllvm::Value *LLVMIRGen::emitValueDims(llvm::IRBuilder<> &builder,\n                                      const glow::Value *val) {\n  auto dims = val->dims();\n  return emitConstSizeTArray(builder, dims);\n}\n\nllvm::Value *LLVMIRGen::emitValueSize(llvm::IRBuilder<> &builder,\n                                      const glow::Value *val) {\n  return builder.getIntN(getTargetSizeTWidth(), val->size());\n}\n\nllvm::Value *LLVMIRGen::emitConstF32(llvm::IRBuilder<> &builder, float val) {\n  return llvm::ConstantFP::get(llvm::Type::getFloatTy(ctx_), val);\n}\n\nllvm::Value *LLVMIRGen::emitConstI32(llvm::IRBuilder<> &builder, int32_t val) {\n  return builder.getInt32(val);\n}\n\nllvm::Value *LLVMIRGen::emitConstI8(llvm::IRBuilder<> &builder, int8_t val) {\n  return builder.getInt8(val);\n}\n\nllvm::Value *LLVMIRGen::emitConstSizeT(llvm::IRBuilder<> &builder, size_t val) {\n  return builder.getIntN(getTargetSizeTWidth(), val);\n}\n\nllvm::Value *LLVMIRGen::emitConst(llvm::IRBuilder<> &builder, float val,\n                                  glow::ElemKind kind) {\n  switch (kind) {\n  case ElemKind::FloatTy:\n    return llvm::ConstantFP::get(llvm::Type::getFloatTy(ctx_), val);\n  case ElemKind::Float16Ty:\n    llvm_unreachable(\"No yet implemented\");\n  case ElemKind::Int64ITy:\n    return builder.getInt64(static_cast<int64_t>(val));\n  case ElemKind::Int8QTy:\n    return builder.getInt8(static_cast<int8_t>(val));\n  case ElemKind::Int16QTy:\n    return builder.getInt16(static_cast<int16_t>(val));\n  case ElemKind::Int32QTy:\n    return builder.getInt32(static_cast<int32_t>(val));\n  case ElemKind::Int32ITy:\n    return builder.getInt32(static_cast<int32_t>(val));\n  case ElemKind::UInt8FusedQTy:\n    return builder.getInt8(static_cast<int8_t>(val));\n  case ElemKind::BoolTy:\n    return builder.getInt8(static_cast<int8_t>(val));\n  }\n  llvm_unreachable(\"Unknown element type\");\n}\n\nllvm::Value *LLVMIRGen::emitStringConst(llvm::IRBuilder<> &builder,\n                                        llvm::StringRef str) {\n  llvm::Constant *constStrArray =\n      llvm::ConstantDataArray::getString(ctx_, str, true);\n  llvm::GlobalVariable *gvarStr = new llvm::GlobalVariable(\n      *llmodule_, constStrArray->getType(), true,\n      llvm::GlobalValue::PrivateLinkage, constStrArray, \".str\");\n  gvarStr->setAlignment(1);\n  return builder.CreateBitCast(gvarStr, builder.getInt8PtrTy());\n}\n\nvoid LLVMIRGen::markArgAsUnspecialized(llvm::Value *val) {\n  dontSpecializeArgsSet_.insert(val);\n}\n\nllvm::Function *LLVMIRGen::getFunction(const std::string &name) {\n  auto *F = llmodule_->getFunction(\"libjit_\" + name);\n#ifndef NDEBUG\n  if (!F) {\n    llvm::errs() << \"Unable to load the function: libjit_\" << name << \"\\n\";\n  }\n#endif\n  GLOW_ASSERT(F && \"Unable to load the function\");\n  return F;\n}\n\nllvm::Function *LLVMIRGen::getFunction(const std::string &name,\n                                       ElemKind elemTy) {\n  auto get = [this](llvm::StringRef funcName) {\n    auto *F = llmodule_->getFunction(funcName);\n#ifndef NDEBUG\n    if (!F) {\n      llvm::errs() << \"Unable to load the function: \" << funcName << \"\\n\";\n    }\n#endif\n    GLOW_ASSERT(F && \"Unable to load the function\");\n    return F;\n  };\n  switch (elemTy) {\n  case ElemKind::FloatTy:\n    return get(\"libjit_\" + name + \"_f\");\n  case ElemKind::Int8QTy:\n    return get(\"libjit_\" + name + \"_i8\");\n  case ElemKind::Int32QTy:\n    return get(\"libjit_\" + name + \"_i32\");\n  case ElemKind::Int32ITy:\n    return get(\"libjit_\" + name + \"_i32\");\n  case ElemKind::Int64ITy:\n    return get(\"libjit_\" + name + \"_u\");\n  case ElemKind::BoolTy:\n    return get(\"libjit_\" + name + \"_b\");\n  default:\n    GLOW_UNREACHABLE(\"Unsupported element type\");\n  }\n}\n\nllvm::CallInst *LLVMIRGen::createCall(llvm::IRBuilder<> &builder,\n                                      llvm::Function *callee,\n                                      llvm::ArrayRef<llvm::Value *> args) {\n#ifndef NDEBUG\n  llvm::FunctionType *FTy = callee->getFunctionType();\n  assert((args.size() == FTy->getNumParams() ||\n          (FTy->isVarArg() && args.size() > FTy->getNumParams())) &&\n         \"Calling a function with bad signature: wrong number of arguments.\");\n\n  for (unsigned i = 0; i != args.size(); ++i) {\n    assert((i >= FTy->getNumParams() ||\n            FTy->getParamType(i) == args[i]->getType()) &&\n           \"Calling a function with a bad signature: argument type mismatch.\");\n  }\n#endif\n  return builder.CreateCall(callee, args);\n}\n\nstd::pair<llvm::BasicBlock *, llvm::BasicBlock *>\nLLVMIRGen::createLoop(llvm::IRBuilder<> &builder, llvm::LLVMContext &ctx,\n                      llvm::Value *numElements) const {\n  auto sizeTTy = builder.getIntNTy(getTargetSizeTWidth());\n  auto *initVal = llvm::ConstantInt::get(sizeTTy, 0);\n\n  \/\/ Make the new basic block for the loop header. Insert it after current\n  \/\/ block.\n  llvm::Function *func = builder.GetInsertBlock()->getParent();\n  auto *preheaderBB = builder.GetInsertBlock();\n  auto *loopBB = llvm::BasicBlock::Create(ctx, \"loop\", func);\n\n  \/\/ Insert a jump from the current block to the loopBB.\n  builder.CreateBr(loopBB);\n\n  \/\/ Start insertion in LoopBB.\n  builder.SetInsertPoint(loopBB);\n\n  \/\/ Create the PHI node with an entry for initial value.\n  llvm::PHINode *var = builder.CreatePHI(sizeTTy, 2);\n  var->addIncoming(initVal, preheaderBB);\n\n  \/\/ Emit the step value.\n  auto *stepVal = llvm::ConstantInt::get(sizeTTy, 1);\n  auto *nextVal = builder.CreateAdd(var, stepVal, \"nextvar\", \/* HasNUW *\/ true,\n                                    \/* HasNSW *\/ true);\n  \/\/ Compute the end condition.\n  auto *endCond = builder.CreateICmpULT(nextVal, numElements, \"loopcond\");\n\n  \/\/ Create the \"after loop\" block and insert it.\n  auto *afterBB = llvm::BasicBlock::Create(ctx, \"afterloop\", func);\n\n  \/\/ Insert the conditional branch at the end of the loopBB.\n  auto *backEdge = builder.CreateCondBr(endCond, loopBB, afterBB);\n  \/\/ Add explicit loop llvm.loop.vectorize.enable metadata to the generated\n  \/\/ loop to help the LLVM vectorizer. Without this metadata, LLVM loop\n  \/\/ vectorizer bails on long data-parallel loops with a lot of operations. This\n  \/\/ metadata forces it to vectorize them anyways.\n  llvm::SmallVector<llvm::Metadata *, 4> args;\n  \/\/ Reserve operand 0 for loop id self reference.\n  \/\/\n  \/\/ Initialize it with a special temporary metadata node, which is typically\n  \/\/ used to create cyclic metadata structures. tmpMD is a unique_ptr and thus\n  \/\/ will be freed automatically when it goes out of scope.\n  llvm::TempMDTuple tmpMD = llvm::MDNode::getTemporary(ctx, llvm::None);\n  args.push_back(tmpMD.get());\n  llvm::Metadata *Vals[] = {\n      \/\/ Reserve operand 0 for loop id self reference.\n      llvm::MDString::get(ctx, \"llvm.loop.vectorize.enable\"),\n      llvm::ConstantAsMetadata::get(\n          llvm::ConstantInt::get(llvm::Type::getInt1Ty(ctx), true))};\n  args.push_back(llvm::MDNode::get(ctx, Vals));\n  auto *loopMD = llvm::MDNode::get(ctx, args);\n  \/\/ Set the first operand to itself.\n  loopMD->replaceOperandWith(0, loopMD);\n  backEdge->setMetadata(llvm::LLVMContext::MD_loop, loopMD);\n  \/\/ Add a new entry to the PHI node for the backedge.\n  var->addIncoming(nextVal, loopBB);\n  builder.SetInsertPoint(afterBB);\n  return std::make_pair(loopBB, afterBB);\n}\n\n\/\/\/ Emit the address of the buffer \\p v inside a data-parallel kernel \\p kernel\n\/\/\/ using the mapping provided by \\p bufferToArgNum.\nllvm::Value *\nLLVMIRGen::emitBufferAddress(llvm::IRBuilder<> &builder, Value *val,\n                             llvm::Function *kernel,\n                             llvm::DenseMap<Value *, int> &bufferToArgNum) {\n  assert(bufferToArgNum.count(val) && \"Buffer should be in the map\");\n  return kernel->args().begin() + bufferToArgNum[val];\n}\n\n\/\/\/ Implementation of emitDataParallelKernel where we guarantee that the number\n\/\/\/ of arguments will be bound by 64.\nvoid LLVMIRGen::emitDataParallelKernelImpl(\n    llvm::IRBuilder<> &builder, llvm::ArrayRef<const Instruction *> bundle,\n    llvm::ArrayRef<llvm::Type *> argTypes,\n    llvm::DenseMap<Value *, int> &bufferToArgNum,\n    llvm::ArrayRef<llvm::Value *> buffers) {\n  if (bundle.empty()) {\n    return;\n  }\n  \/\/ Create stacked kernel function type.\n  llvm::Type *voidTy = llvm::Type::getVoidTy(ctx_);\n  llvm::FunctionType *kernelFuncTy =\n      llvm::FunctionType::get(voidTy, argTypes, false);\n  auto *kernelFunc =\n      llvm::Function::Create(kernelFuncTy, llvm::Function::InternalLinkage,\n                             \"libjit_stacked_kernel\", llmodule_.get());\n  \/\/ Mark all kernel function buffer parameters as no-alias, because above\n  \/\/ we ensured that they are uniqued.\n  for (unsigned paramIdx = 0; paramIdx < bufferToArgNum.size(); ++paramIdx) {\n    kernelFunc->addParamAttr(paramIdx, llvm::Attribute::AttrKind::NoAlias);\n  }\n\n  \/\/ Create the entry BB.\n  llvm::BasicBlock *entryBB =\n      llvm::BasicBlock::Create(ctx_, \"entry\", kernelFunc);\n  llvm::IRBuilder<> kernelBuilder(entryBB);\n  \/\/ Number of tensor elements.\n  auto *numElements =\n      emitValueSize(kernelBuilder, bundle[0]->getOperand(0).first);\n  \/\/ Create a loop inside the stacked kernel function being generated.\n  auto loopBBs = createLoop(kernelBuilder, ctx_, numElements);\n\n  \/\/ Get the index parameter of the loop.\n  \/\/ This is the PHI node of the BB.\n  auto *kernelLoopIdx = dyn_cast<llvm::PHINode>(loopBBs.first->begin());\n  assert(kernelLoopIdx && \"Could not find the loop index\");\n  \/\/ Insert the body of the loop right after the PHI node.\n  kernelBuilder.SetInsertPoint(loopBBs.first->getFirstNonPHIOrDbg());\n  \/\/ Iterate over stacked instructions and create a kernel invocations per\n  \/\/ instruction.\n  for (auto &BI : bundle) {\n    \/\/ Name of the stacked operation to be invoked.\n    assert(BI->isDataParallel() && \"Data parallel operation is expected\");\n    generateLLVMIRForDataParallelInstr(kernelBuilder, BI, kernelFunc,\n                                       bufferToArgNum, kernelLoopIdx);\n  }\n  kernelBuilder.SetInsertPoint(loopBBs.second);\n  \/\/ Add a return.\n  kernelBuilder.CreateRetVoid();\n\n  \/\/ Emit a call of the kernel.\n  createCall(builder, kernelFunc, buffers);\n}\n\n\/\/\/ Emit the function that implements a data-parallel kernel and calls it.\n\/\/\/\n\/\/\/ The generated kernel functions get buffers as their parameters. The buffers\n\/\/\/ are uniqued, so that any buffer is passed as argument to the kernel function\n\/\/\/ only once. This allows us to mark all parameters of the generated kernel as\n\/\/\/ noalias. As a result, the LLVM optimizer makes use of the noalias attributes\n\/\/\/ and produces nicely vectorized code for the generated data-parallel kernels.\n\/\/\/ Note that we will emit a kernel whenever the number of arguments (aka unique\n\/\/\/ buffers) exceeds `kArgLimit`.\nvoid LLVMIRGen::emitDataParallelKernel(\n    llvm::IRBuilder<> &builder, llvm::ArrayRef<const Instruction *> bundle) {\n  if (bundle.empty())\n    return;\n  \/\/ Types of arguments for the kernel function being generated.\n  llvm::SmallVector<llvm::Type *, 32> argTypes;\n  \/\/ Map each buffer used by the kernel to the argument number of the kernel\n  \/\/ function. This ensures that same buffer is always mapped to the same\n  \/\/ argument.\n  llvm::DenseMap<Value *, int> bufferToArgNum;\n  \/\/ Buffers to be passed to the kernel function as arguments.\n  llvm::SmallVector<llvm::Value *, 32> buffers;\n  \/\/ Hold a group of instructions whose unique buffer size is no more than\n  \/\/ `kArgLimit` and ship it for processing\n  llvm::SmallVector<const Instruction *, 32> batchedBundle;\n  \/\/ Collect unique buffers up to `kArgLimit` used by the instructions of the\n  \/\/ kernel.\n  for (const auto I : bundle) {\n    \/\/ If adding the buffers of current instruction might make the total number\n    \/\/ of unique buffer exceed `kArgLimit`, we need to emit the kernel and start\n    \/\/ over. Note the \"might\" as this method is pessimistic, because number of\n    \/\/ buffers from current instructure might not be unique. Trade-off here is\n    \/\/ that the algorithm is cleaner and in practice, if we over-estimate the\n    \/\/ argument size by several, it does not matter too much.\n    if (argTypes.size() + I->getOperands().size() > kArgLimit) {\n      emitDataParallelKernelImpl(builder, batchedBundle, argTypes,\n                                 bufferToArgNum, buffers);\n      batchedBundle.clear();\n      argTypes.clear();\n      bufferToArgNum.clear();\n      buffers.clear();\n    }\n\n    \/\/ Add the instruction to the current bundle and process its operands\n    batchedBundle.push_back(I);\n    for (const auto &Op : I->getOperands()) {\n      auto *buf = Op.first;\n      if (!bufferToArgNum.count(buf)) {\n        bufferToArgNum[buf] = argTypes.size();\n        buffers.push_back(emitValueAddress(builder, buf));\n        argTypes.push_back(getElementType(builder, buf)->getPointerTo());\n      }\n    }\n  }\n  emitDataParallelKernelImpl(builder, batchedBundle, argTypes, bufferToArgNum,\n                             buffers);\n}\n\n\/\/\/ Check if the provided operand overlaps with an operand of an instruction\n\/\/\/ already in the bundle, but is not exactly the same memory region.\n\/\/\/ Such memory regions cannot be considered data-parallel in the scope of the\n\/\/\/ same kernel.\n\/\/\/\n\/\/\/ \\param allocationsInfo information about allocations\n\/\/\/ \\param bundle current bundle of stacked instructions\n\/\/\/ \\param buf the buffer operand to be checked for overlaps with the \\p bundle.\nstatic bool isOverlappingWithAnyBundleBufferOperands(\n    AllocationsInfo &allocationsInfo,\n    llvm::SmallVectorImpl<const Instruction *> &bundle, Value *buf) {\n  auto addr1 = allocationsInfo.allocatedAddress_[buf];\n  auto size1 = buf->getSizeInBytes();\n  for (auto bi : bundle) {\n    for (auto bop : bi->getOperands()) {\n      auto buf2 = bop.first;\n      auto addr2 = allocationsInfo.allocatedAddress_[buf2];\n      auto size2 = buf2->getSizeInBytes();\n      \/\/ It is fine, if buffers of different data-parallel instructions are\n      \/\/ allocated exactly the same memory region.\n      if (addr1 == addr2 && size1 == size2) {\n        continue;\n      }\n      if ((addr1 >= addr2 && addr1 < addr2 + size2) ||\n          (addr2 >= addr1 && addr2 < addr1 + size1)) {\n        \/\/ Two intervals overlap, but are not the same.\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\nvoid LLVMIRGen::generateLLVMIRForModule(llvm::IRBuilder<> &builder) {\n  \/\/ Go over the instructions and try to group them into bundles.\n  auto &instrs = F_->getInstrs();\n\n  \/\/ Group instructions into bundles of shape compatible data parallel\n  \/\/ instructions and emit them.\n  llvm::SmallVector<const Instruction *, 32> bundle;\n  for (auto &I : instrs) {\n    if (!I.isDataParallel()) {\n      \/\/ Ignore memory management instructions as they are handled by the\n      \/\/ MemoryManager and are NOPs for a JIT.\n      if (isa<AllocActivationInst>(&I) || isa<DeallocActivationInst>(&I) ||\n          isa<TensorViewInst>(&I))\n        continue;\n      emitDataParallelKernel(builder, bundle);\n      bundle.clear();\n      generateLLVMIRForInstr(builder, &I);\n      continue;\n    }\n\n    \/\/ This is a data parallel instruction.\n\n    \/\/ Check if the current instruction is shape compatible with the bundle.\n    bool isBundleCompatible = true;\n    if (!bundle.empty()) {\n      auto val = I.getOperand(0).first;\n      auto bundleVal = bundle.back()->getOperand(0).first;\n      \/\/ Check if shapes have the same amount of elements.\n      isBundleCompatible = val->size() == bundleVal->size();\n    }\n\n    \/\/ Check all mutated operands of the current instruction. Their memory\n    \/\/ regions should not have a non-exact overlap with any operands of the\n    \/\/ bundled instructions. In case this condition does not hold, the current\n    \/\/ instruction cannot be included into the data-parallel bundle, because\n    \/\/ overlapping operand buffers are not data parallel.\n    for (auto op : I.getOperands()) {\n      \/\/ Skip non-mutated operands.\n      if (op.second == OperandKind::In)\n        continue;\n      \/\/ If the mutated operand buffer overlaps with any buffer already used by\n      \/\/ the bundle, the current instruction cannot become a part of the bundle.\n      if (isOverlappingWithAnyBundleBufferOperands(allocationsInfo_, bundle,\n                                                   op.first)) {\n        isBundleCompatible = false;\n        break;\n      }\n    }\n\n    \/\/ If the instruction cannot be added to the current bundle, emit the kernel\n    \/\/ for the current bundle and start a new bundle.\n    if (!isBundleCompatible) {\n      emitDataParallelKernel(builder, bundle);\n      bundle.clear();\n    }\n    \/\/ Add a data parallel instruction to the bundle.\n    bundle.push_back(&I);\n  }\n\n  emitDataParallelKernel(builder, bundle);\n}\n\nvoid LLVMIRGen::generateLLVMIRForDataParallelInstr(\n    llvm::IRBuilder<> &builder, const glow::Instruction *I,\n    llvm::Function *kernel, llvm::DenseMap<Value *, int> &bufferToArgNum,\n    llvm::Value *loopCount) {\n  setCurrentDebugLocation(builder, I);\n  assert(I->isDataParallel() && \"Expected a data parallel instruction\");\n  switch (I->getKind()) {\n\n#define ARITHMETIC_UNARY_OP_WITH_IMM_CASE(INST_NAME_, FUN_NAME_, VALUE_)       \\\n  case Kinded::Kind::INST_NAME_##InstKind: {                                   \\\n    auto *AN = cast<INST_NAME_##Inst>(I);                                      \\\n    auto *dest = AN->getDest();                                                \\\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);  \\\n    auto *elementTy = getElementType(builder, dest);                           \\\n    auto value = AN->get##VALUE_();                                            \\\n    auto *F = getFunction(FUN_NAME_ \"_kernel\", dest->getElementType());        \\\n    auto *pointerNull =                                                        \\\n        llvm::ConstantPointerNull::get(elementTy->getPointerTo());             \\\n    if (dest->getType()->isQuantizedType()) {                                  \\\n      auto *destTy = dest->getType();                                          \\\n      \/* Quantize value based on the output type. *\/                           \\\n      \/* Perform this early and let jit library to work *\/                     \\\n      \/* with quantized number. *\/                                             \\\n      TensorQuantizationParams TQP{destTy->getScale(), destTy->getOffset()};   \\\n      auto quantizedValue = quantization::quantize(value, TQP);                \\\n      auto *val = emitConstI8(builder, quantizedValue);                        \\\n      auto *stackedOpCall =                                                    \\\n          createCall(builder, F, {loopCount, val, pointerNull, pointerNull});  \\\n      auto *destAddr = builder.CreateGEP(elementTy, destPtr, loopCount,        \\\n                                         \"buffer.element.addr\");               \\\n      builder.CreateStore(stackedOpCall, destAddr);                            \\\n    } else {                                                                   \\\n      auto *val = emitConst(builder, value, dest->getElementType());           \\\n      auto *stackedOpCall =                                                    \\\n          createCall(builder, F, {loopCount, val, pointerNull, pointerNull});  \\\n      auto *destAddr = builder.CreateGEP(elementTy, destPtr, loopCount,        \\\n                                         \"buffer.element.addr\");               \\\n      builder.CreateStore(stackedOpCall, destAddr);                            \\\n    }                                                                          \\\n    break;                                                                     \\\n  }\n    ARITHMETIC_UNARY_OP_WITH_IMM_CASE(Splat, \"splat\", Value);\n#undef ARITHMETIC_UNARY_OP_WITH_IMM_CASE\n\n  case Kinded::Kind::ElementSelectInstKind: {\n    auto *ES = cast<ElementSelectInst>(I);\n    auto *dest = ES->getDest();\n    auto *cond = ES->getCond();\n    auto *lhs = ES->getLHS();\n    auto *rhs = ES->getRHS();\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);\n    auto *condPtr = emitBufferAddress(builder, cond, kernel, bufferToArgNum);\n    auto *lhsPtr = emitBufferAddress(builder, lhs, kernel, bufferToArgNum);\n    auto *rhsPtr = emitBufferAddress(builder, rhs, kernel, bufferToArgNum);\n\n    \/\/ Need _kernel suffix since these operations are implemented as\n    \/\/ \"data-parallel\" kernels in libjit.\n    auto *F = getFunction(\"elementselect_kernel\", lhs->getElementType());\n\n    if (lhs->getType()->isQuantizedType()) {\n      auto *destTy = dest->getType();\n      auto *lhsTy = lhs->getType();\n      auto *rhsTy = rhs->getType();\n\n      auto *destOffset = emitConstI32(builder, destTy->getOffset());\n      auto *lhsOffset = emitConstI32(builder, lhsTy->getOffset());\n      auto *rhsOffset = emitConstI32(builder, rhsTy->getOffset());\n\n      \/\/ The selected value will be either lhs = s_l * (i_l - o_l) or\n      \/\/ rhs = s_r * (i_r - o_r); the stored result that must be computed is\n      \/\/ therefore one of:\n      \/\/ (i)  i_d = (s_l \/ s_d) * (i_l - o_l) + o_d\n      \/\/ (ii) i_d = (s_r \/ s_d) * (i_r - o_r) + o_d\n      float destScale = destTy->getScale();\n      auto lhsScaleParams = quantization::quantizeScaleOffset32To8(\n          lhsTy->getScale() \/ destScale, lhsTy->getOffset());\n      auto rhsScaleParams = quantization::quantizeScaleOffset32To8(\n          rhsTy->getScale() \/ destScale, rhsTy->getOffset());\n\n      auto *lhsPre = emitConstI32(builder, lhsScaleParams.pre);\n      auto *lhsPost = emitConstI32(builder, lhsScaleParams.post);\n      auto *lhsScale = emitConstI32(builder, lhsScaleParams.scale);\n      auto *rhsPre = emitConstI32(builder, rhsScaleParams.pre);\n      auto *rhsPost = emitConstI32(builder, rhsScaleParams.post);\n      auto *rhsScale = emitConstI32(builder, rhsScaleParams.scale);\n\n      auto *stackedOpCall = createCall(\n          builder, F,\n          {loopCount, condPtr, lhsPtr, rhsPtr, destOffset, lhsOffset, rhsOffset,\n           lhsPre, lhsPost, lhsScale, rhsPre, rhsPost, rhsScale});\n      auto *destAddr = builder.CreateGEP(builder.getInt8Ty(), destPtr,\n                                         loopCount, \"buffer.element.addr\");\n      builder.CreateStore(stackedOpCall, destAddr);\n    } else {\n      auto *stackedOpCall =\n          createCall(builder, F, {loopCount, condPtr, lhsPtr, rhsPtr});\n      auto *destAddr = builder.CreateGEP(builder.getFloatTy(), destPtr,\n                                         loopCount, \"buffer.element.addr\");\n      builder.CreateStore(stackedOpCall, destAddr);\n    }\n    break;\n  }\n  case Kinded::Kind::IntLookupTableInstKind: {\n    auto *lookupTable = cast<IntLookupTableInst>(I);\n    auto *dest = lookupTable->getDest();\n    auto *src = lookupTable->getSrc();\n    auto *mapping = lookupTable->getMapping();\n\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);\n    auto *srcPtr = emitBufferAddress(builder, src, kernel, bufferToArgNum);\n    auto *mappingPtr =\n        emitBufferAddress(builder, mapping, kernel, bufferToArgNum);\n\n    auto *F = getFunction(\"intlookuptable_kernel\", dest->getElementType());\n    auto *stackedOpCall =\n        builder.CreateCall(F, {loopCount, srcPtr, mappingPtr});\n    auto *destAddr = builder.CreateGEP(builder.getInt8Ty(), destPtr, loopCount,\n                                       \"buffer.element.addr\");\n    builder.CreateStore(stackedOpCall, destAddr);\n\n    break;\n  }\n#define ARITHMETIC_UNARY_OP_CASE(INST_NAME_, FUN_NAME_)                        \\\n  case Kinded::Kind::INST_NAME_##InstKind: {                                   \\\n    auto *AN = cast<INST_NAME_##Inst>(I);                                      \\\n    auto *dest = AN->getDest();                                                \\\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);  \\\n    auto *srcPtr =                                                             \\\n        emitBufferAddress(builder, AN->getSrc(), kernel, bufferToArgNum);      \\\n    auto *F = getFunction(FUN_NAME_ \"_kernel\", dest->getElementType());        \\\n    auto *elementTy = getElementType(builder, dest);                           \\\n    auto *pointerNull =                                                        \\\n        llvm::ConstantPointerNull::get(elementTy->getPointerTo());             \\\n    auto *stackedOpCall =                                                      \\\n        createCall(builder, F, {loopCount, srcPtr, pointerNull, pointerNull}); \\\n    auto *destAddr = builder.CreateGEP(builder.getFloatTy(), destPtr,          \\\n                                       loopCount, \"buffer.element.addr\");      \\\n    builder.CreateStore(stackedOpCall, destAddr);                              \\\n    break;                                                                     \\\n  }\n\n    ARITHMETIC_UNARY_OP_CASE(Sigmoid, \"sigmoid\");\n    ARITHMETIC_UNARY_OP_CASE(Tanh, \"tanh\");\n    ARITHMETIC_UNARY_OP_CASE(ElementLog, \"element_log\");\n#undef ARITHMETIC_UNARY_OP_CASE\n\n  case Kinded::Kind::ElementIsNaNInstKind: {\n    auto *AN = cast<ElementIsNaNInst>(I);\n    auto *src = AN->getSrc();\n    auto *dest = AN->getDest();\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);\n    auto *srcPtr = emitBufferAddress(builder, src, kernel, bufferToArgNum);\n    auto *F = getFunction(\"element_is_nan_kernel\", src->getElementType());\n    auto *stackedOpCall = createCall(builder, F, {loopCount, srcPtr});\n    auto *elementTy = getElementType(builder, dest);\n    auto *destAddr =\n        builder.CreateGEP(elementTy, destPtr, loopCount, \"buffer.element.addr\");\n    builder.CreateStore(stackedOpCall, destAddr);\n    break;\n  }\n\n  case Kinded::Kind::QuantizeInstKind: {\n    auto *QI = cast<QuantizeInst>(I);\n    auto *src = QI->getSrc();\n    auto *dest = QI->getDest();\n    auto *srcPtr = emitBufferAddress(builder, src, kernel, bufferToArgNum);\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);\n    auto *destTy = dest->getType();\n    auto *destScale = emitConstF32(builder, destTy->getScale());\n    auto *destOffset = emitConstI32(builder, destTy->getOffset());\n    auto *F = getFunction(\"element_quantize_kernel\", dest->getElementType());\n\n    auto *stackedOpCall =\n        createCall(builder, F, {loopCount, srcPtr, destScale, destOffset});\n    llvm::Value *destAddr = nullptr;\n    if (dest->getElementType() == ElemKind::Int8QTy) {\n      destAddr = builder.CreateGEP(builder.getInt8Ty(), destPtr, loopCount,\n                                   \"buffer.element.addr\");\n    } else if (dest->getElementType() == ElemKind::Int32QTy) {\n      destAddr = builder.CreateGEP(builder.getInt32Ty(), destPtr, loopCount,\n                                   \"buffer.element.addr\");\n    } else {\n      GLOW_UNREACHABLE(\"Type is not supported.\");\n    }\n\n    builder.CreateStore(stackedOpCall, destAddr);\n    break;\n  }\n\n  case Kinded::Kind::DequantizeInstKind: {\n    auto *DI = cast<DequantizeInst>(I);\n    auto *src = DI->getSrc();\n    auto *dest = DI->getDest();\n    auto *srcPtr = emitBufferAddress(builder, src, kernel, bufferToArgNum);\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);\n    auto *srcTy = src->getType();\n    auto *srcScale = emitConstF32(builder, srcTy->getScale());\n    auto *srcOffset = emitConstI32(builder, srcTy->getOffset());\n    auto *F = getFunction(\"element_dequantize_kernel\", dest->getElementType());\n\n    auto *stackedOpCall =\n        createCall(builder, F, {loopCount, srcPtr, srcScale, srcOffset});\n    auto *destAddr = builder.CreateGEP(builder.getFloatTy(), destPtr, loopCount,\n                                       \"buffer.element.addr\");\n    builder.CreateStore(stackedOpCall, destAddr);\n    break;\n  }\n\n  case Kinded::Kind::RescaleQuantizedInstKind: {\n    auto *RQI = cast<RescaleQuantizedInst>(I);\n    auto *dest = RQI->getDest();\n    auto *src = RQI->getSrc();\n    auto *srcPtr = emitBufferAddress(builder, src, kernel, bufferToArgNum);\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);\n\n    auto *destType = dest->getType();\n    auto *srcType = src->getType();\n\n    auto rescaleParams = quantization::quantizeScaleOffset32To8(\n        srcType->getScale() \/ destType->getScale(), srcType->getOffset());\n\n    auto *destOffset = emitConstI32(builder, destType->getOffset());\n    auto *srcOffset = emitConstI32(builder, srcType->getOffset());\n    auto *preShift = emitConstI32(builder, rescaleParams.pre);\n    auto *postShift = emitConstI32(builder, rescaleParams.post);\n    auto *scale = emitConstI32(builder, rescaleParams.scale);\n    auto *F = getFunction(\"element_rescale_kernel\", dest->getElementType());\n\n    auto *stackedOpCall = createCall(\n        builder, F,\n        {loopCount, srcPtr, destOffset, srcOffset, preShift, postShift, scale});\n    auto *destAddr = builder.CreateGEP(builder.getInt8Ty(), destPtr, loopCount,\n                                       \"buffer.element.addr\");\n    builder.CreateStore(stackedOpCall, destAddr);\n    break;\n  }\n\n  case Kinded::Kind::CopyInstKind: {\n    auto *CI = cast<CopyInst>(I);\n    auto *dest = CI->getDest();\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);\n    auto *srcPtr =\n        emitBufferAddress(builder, CI->getSrc(), kernel, bufferToArgNum);\n    auto *F = getFunction(\"copy_kernel\", dest->getElementType());\n    auto *elementTy = getElementType(builder, dest);\n    auto *pointerNull =\n        llvm::ConstantPointerNull::get(elementTy->getPointerTo());\n    auto *stackedOpCall =\n        createCall(builder, F, {loopCount, srcPtr, pointerNull, pointerNull});\n    auto *destAddr = builder.CreateGEP(getElementType(builder, dest), destPtr,\n                                       loopCount, \"buffer.element.addr\");\n    builder.CreateStore(stackedOpCall, destAddr);\n    break;\n  }\n\n#define ARITHMETIC_BINARY_OP_CASE(INST_NAME_, FUN_NAME_)                       \\\n  case Kinded::Kind::INST_NAME_##InstKind: {                                   \\\n    auto *AN = cast<INST_NAME_##Inst>(I);                                      \\\n    auto *dest = AN->getDest();                                                \\\n    auto *lhs = AN->getLHS();                                                  \\\n    auto *rhs = AN->getRHS();                                                  \\\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);  \\\n    auto *lhsPtr = emitBufferAddress(builder, lhs, kernel, bufferToArgNum);    \\\n    auto *rhsPtr = emitBufferAddress(builder, rhs, kernel, bufferToArgNum);    \\\n                                                                               \\\n    auto *F = getFunction(FUN_NAME_ \"_kernel\", dest->getElementType());        \\\n    auto *elementTy = getElementType(builder, dest);                           \\\n    auto *pointerNull =                                                        \\\n        llvm::ConstantPointerNull::get(elementTy->getPointerTo());             \\\n                                                                               \\\n    if (lhs->getType()->isQuantizedType()) {                                   \\\n      auto *destTy = dest->getType();                                          \\\n      auto *lhsTy = lhs->getType();                                            \\\n      auto *rhsTy = rhs->getType();                                            \\\n                                                                               \\\n      auto *destOffset = emitConstI32(builder, destTy->getOffset());           \\\n      auto *lhsOffset = emitConstI32(builder, lhsTy->getOffset());             \\\n      auto *rhsOffset = emitConstI32(builder, rhsTy->getOffset());             \\\n                                                                               \\\n      float destScale = destTy->getScale();                                    \\\n                                                                               \\\n      auto lhsScaleParams = quantization::quantizeScaleOffset32To8(            \\\n          lhsTy->getScale() \/ destScale, lhsTy->getOffset());                  \\\n      auto rhsScaleParams = quantization::quantizeScaleOffset32To8(            \\\n          rhsTy->getScale() \/ destScale, rhsTy->getOffset());                  \\\n                                                                               \\\n      auto *lhsPre = emitConstI32(builder, lhsScaleParams.pre);                \\\n      auto *lhsPost = emitConstI32(builder, lhsScaleParams.post);              \\\n      auto *lhsScale = emitConstI32(builder, lhsScaleParams.scale);            \\\n      auto *rhsPre = emitConstI32(builder, rhsScaleParams.pre);                \\\n      auto *rhsPost = emitConstI32(builder, rhsScaleParams.post);              \\\n      auto *rhsScale = emitConstI32(builder, rhsScaleParams.scale);            \\\n                                                                               \\\n      auto *stackedOpCall = createCall(builder, F,                             \\\n                                       {loopCount, lhsPtr, rhsPtr, destOffset, \\\n                                        lhsOffset, rhsOffset, lhsPre, lhsPost, \\\n                                        lhsScale, rhsPre, rhsPost, rhsScale}); \\\n      auto *destAddr = builder.CreateGEP(builder.getInt8Ty(), destPtr,         \\\n                                         loopCount, \"buffer.element.addr\");    \\\n      builder.CreateStore(stackedOpCall, destAddr);                            \\\n    } else {                                                                   \\\n      auto *stackedOpCall =                                                    \\\n          createCall(builder, F, {loopCount, lhsPtr, rhsPtr, pointerNull});    \\\n      auto *destAddr = builder.CreateGEP(builder.getFloatTy(), destPtr,        \\\n                                         loopCount, \"buffer.element.addr\");    \\\n      builder.CreateStore(stackedOpCall, destAddr);                            \\\n    }                                                                          \\\n    break;                                                                     \\\n  }\n    ARITHMETIC_BINARY_OP_CASE(ElementAdd, \"element_add\");\n    ARITHMETIC_BINARY_OP_CASE(ElementSub, \"element_sub\");\n    ARITHMETIC_BINARY_OP_CASE(ElementMax, \"elementmax\");\n    ARITHMETIC_BINARY_OP_CASE(ElementMin, \"elementmin\");\n    ARITHMETIC_BINARY_OP_CASE(ElementPow, \"element_pow\");\n#undef ARITHMETIC_BINARY_OP_CASE\n\n  case Kinded::Kind::ElementCmpLTEInstKind: {\n    auto *CI = cast<ElementCmpLTEInst>(I);\n    auto *dest = CI->getDest();\n    auto *lhs = CI->getLHS();\n    auto *rhs = CI->getRHS();\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);\n    auto *lhsPtr = emitBufferAddress(builder, lhs, kernel, bufferToArgNum);\n    auto *rhsPtr = emitBufferAddress(builder, rhs, kernel, bufferToArgNum);\n\n    \/\/ Need _kernel suffix since these operations are implemented as\n    \/\/ \"data-parallel\" kernels in libjit.\n    auto *F = getFunction(\"element_cmp_lte_kernel\", lhs->getElementType());\n\n    if (lhs->getType()->isQuantizedType()) {\n      auto *lhsTy = lhs->getType();\n      auto *rhsTy = rhs->getType();\n\n      auto *lhsOffset = emitConstI32(builder, lhsTy->getOffset());\n      auto *rhsOffset = emitConstI32(builder, rhsTy->getOffset());\n\n      \/\/ We can divide both sides of the comparison by the rhs scale since it is\n      \/\/ strictly positive; this saves one rescale within the backend. The\n      \/\/ inequalities are:\n      \/\/     s_l * (i_l - o_l) <= s_r * (i_r - o_r)\n      \/\/ <=> (s_l \/ s_r) * (i_l - o_l) <= i_r - o_r\n      float scale = lhsTy->getScale() \/ rhsTy->getScale();\n      auto scaleParams = quantization::quantizeScaleOffset32To8(scale, 0);\n      auto *cmpPre = emitConstI32(builder, scaleParams.pre);\n      auto *cmpPost = emitConstI32(builder, scaleParams.post);\n      auto *cmpScale = emitConstI32(builder, scaleParams.scale);\n\n      auto *stackedOpCall = createCall(builder, F,\n                                       {loopCount, lhsPtr, rhsPtr, lhsOffset,\n                                        rhsOffset, cmpPre, cmpPost, cmpScale});\n      auto *destAddr = builder.CreateGEP(builder.getInt8Ty(), destPtr,\n                                         loopCount, \"buffer.element.addr\");\n      builder.CreateStore(stackedOpCall, destAddr);\n    } else {\n      auto *stackedOpCall = createCall(builder, F, {loopCount, lhsPtr, rhsPtr});\n      auto *elementTy = getElementType(builder, dest);\n      auto *destAddr = builder.CreateGEP(elementTy, destPtr, loopCount,\n                                         \"buffer.element.addr\");\n      builder.CreateStore(stackedOpCall, destAddr);\n    }\n    break;\n  }\n\n  case Kinded::Kind::ElementCmpEQInstKind: {\n    auto *CI = cast<ElementCmpEQInst>(I);\n    auto *dest = CI->getDest();\n\n    auto *lhs = CI->getLHS();\n    auto *rhs = CI->getRHS();\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);\n    auto *lhsPtr = emitBufferAddress(builder, lhs, kernel, bufferToArgNum);\n    auto *rhsPtr = emitBufferAddress(builder, rhs, kernel, bufferToArgNum);\n\n    \/\/ Need _kernel suffix since these operations are implemented as\n    \/\/ \"data-parallel\" kernels in libjit.\n    auto *F = getFunction(\"element_cmp_eq_kernel\", lhs->getElementType());\n    auto *elementTy = getElementType(builder, dest);\n    auto *stackedOpCall = createCall(builder, F, {loopCount, lhsPtr, rhsPtr});\n    auto *destAddr =\n        builder.CreateGEP(elementTy, destPtr, loopCount, \"buffer.element.addr\");\n    builder.CreateStore(stackedOpCall, destAddr);\n    break;\n  }\n\n  case Kinded::Kind::ElementMulInstKind: {\n    auto *MI = cast<ElementMulInst>(I);\n    auto *dest = MI->getDest();\n    auto *lhs = MI->getLHS();\n    auto *rhs = MI->getRHS();\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);\n    auto *lhsPtr = emitBufferAddress(builder, lhs, kernel, bufferToArgNum);\n    auto *rhsPtr = emitBufferAddress(builder, rhs, kernel, bufferToArgNum);\n\n    \/\/ Need _kernel suffix since these operations are implemented as\n    \/\/ \"data-parallel\" kernels in libjit.\n    auto *F = getFunction(\"element_mul_kernel\", dest->getElementType());\n    auto *elementTy = getElementType(builder, dest);\n    auto *pointerNull =\n        llvm::ConstantPointerNull::get(elementTy->getPointerTo());\n\n    if (lhs->getType()->isQuantizedType()) {\n      auto *destTy = dest->getType();\n      auto *lhsTy = lhs->getType();\n      auto *rhsTy = rhs->getType();\n\n      auto *destOffset = emitConstI32(builder, destTy->getOffset());\n      auto *lhsOffset = emitConstI32(builder, lhsTy->getOffset());\n      auto *rhsOffset = emitConstI32(builder, rhsTy->getOffset());\n\n      \/\/ The multiplicative scale factor is s_l * s_r \/ s_d due to the equation\n      \/\/    s_d * (i_d - o_d) = s_l * (i_l - o_l) * s_r * (i_r - o_r)\n      \/\/ => i_d = (s_l * s_r \/ s_d) * (i_l - o_l) * (i_r - o_r) + o_d\n      float scale = lhsTy->getScale() * rhsTy->getScale() \/ destTy->getScale();\n      auto scaleParams = quantization::quantizeScaleOffset32To8(scale, 0);\n      auto *mulPre = emitConstI32(builder, scaleParams.pre);\n      auto *mulPost = emitConstI32(builder, scaleParams.post);\n      auto *mulScale = emitConstI32(builder, scaleParams.scale);\n\n      auto *stackedOpCall =\n          createCall(builder, F,\n                     {loopCount, lhsPtr, rhsPtr, destOffset, lhsOffset,\n                      rhsOffset, mulPre, mulPost, mulScale});\n      auto *destAddr = builder.CreateGEP(builder.getInt8Ty(), destPtr,\n                                         loopCount, \"buffer.element.addr\");\n      builder.CreateStore(stackedOpCall, destAddr);\n    } else {\n      auto *stackedOpCall =\n          createCall(builder, F, {loopCount, lhsPtr, rhsPtr, pointerNull});\n      auto *destAddr = builder.CreateGEP(builder.getFloatTy(), destPtr,\n                                         loopCount, \"buffer.element.addr\");\n      builder.CreateStore(stackedOpCall, destAddr);\n    }\n    break;\n  }\n\n  case Kinded::Kind::ElementDivInstKind: {\n    auto *MI = cast<ElementDivInst>(I);\n    auto *dest = MI->getDest();\n    auto *lhs = MI->getLHS();\n    auto *rhs = MI->getRHS();\n    auto *destPtr = emitBufferAddress(builder, dest, kernel, bufferToArgNum);\n    auto *lhsPtr = emitBufferAddress(builder, lhs, kernel, bufferToArgNum);\n    auto *rhsPtr = emitBufferAddress(builder, rhs, kernel, bufferToArgNum);\n\n    \/\/ Need _kernel suffix since these operations are implemented as\n    \/\/ \"data-parallel\" kernels in libjit.\n    auto *F = getFunction(\"element_div_kernel\", dest->getElementType());\n    auto *elementTy = getElementType(builder, dest);\n    auto *pointerNull =\n        llvm::ConstantPointerNull::get(elementTy->getPointerTo());\n\n    if (lhs->getType()->isQuantizedType()) {\n      auto *destTy = dest->getType();\n      auto *lhsTy = lhs->getType();\n      auto *rhsTy = rhs->getType();\n\n      auto *destOffset = emitConstI32(builder, destTy->getOffset());\n      auto *lhsOffset = emitConstI32(builder, lhsTy->getOffset());\n      auto *rhsOffset = emitConstI32(builder, rhsTy->getOffset());\n\n      \/\/ The division scale factor is s_l \/ (s_r * s_d) due to the equation\n      \/\/    s_d * (i_d - o_d) = (s_l * (i_l - o_l)) \/ (s_r * (i_r - o_r))\n      \/\/ => i_d = (s_l \/ (s_r * s_d)) * ((i_l - o_l) \/ (i_r - o_r)) + o_d\n      float scale =\n          lhsTy->getScale() \/ (rhsTy->getScale() * destTy->getScale());\n      auto scaleParams = quantization::quantizeScaleOffset32To8(scale, 0);\n      auto *divPre = emitConstI32(builder, scaleParams.pre);\n      auto *divPost = emitConstI32(builder, scaleParams.post);\n      auto *divScale = emitConstI32(builder, scaleParams.scale);\n\n      auto *stackedOpCall =\n          createCall(builder, F,\n                     {loopCount, lhsPtr, rhsPtr, destOffset, lhsOffset,\n                      rhsOffset, divPre, divPost, divScale});\n      auto *destAddr = builder.CreateGEP(builder.getInt8Ty(), destPtr,\n                                         loopCount, \"buffer.element.addr\");\n      builder.CreateStore(stackedOpCall, destAddr);\n    } else {\n      auto *elementTy = getElementType(builder, dest);\n      auto *stackedOpCall =\n          createCall(builder, F, {loopCount, lhsPtr, rhsPtr, pointerNull});\n      auto *destAddr = builder.CreateGEP(elementTy, destPtr, loopCount,\n                                         \"buffer.element.addr\");\n      builder.CreateStore(stackedOpCall, destAddr);\n    }\n    break;\n  }\n\n  default:\n#ifndef NDEBUG\n    llvm::errs() << \"Cannot select the instruction:\\n\";\n    I->dump(llvm::errs());\n    llvm::errs() << \"\\n\";\n#endif\n    GLOW_UNREACHABLE(\"ERROR: Cannot select the instruction.\");\n  }\n}\n\nvoid LLVMIRGen::generateLLVMIRForInstr(llvm::IRBuilder<> &builder,\n                                       const glow::Instruction *I) {\n  setCurrentDebugLocation(builder, I);\n  assert(!I->isDataParallel() &&\n         \"data parallel instructions are not handled here\");\n  switch (I->getKind()) {\n  case Kinded::Kind::MatMulInstKind: {\n    auto *MM = cast<MatMulInst>(I);\n    auto *dest = MM->getDest();\n    auto *lhs = MM->getLHS();\n    auto *rhs = MM->getRHS();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *lhsPtr = emitValueAddress(builder, lhs);\n    auto *rhsPtr = emitValueAddress(builder, rhs);\n\n    auto *destDims = emitValueDims(builder, dest);\n    auto *lhsDims = emitValueDims(builder, lhs);\n    auto *rhsDims = emitValueDims(builder, rhs);\n\n    auto *F = getFunction(\"matmul\", dest->getElementType());\n\n    if (lhs->getType()->isQuantizedType()) {\n      auto *destTy = dest->getType();\n      auto *lhsTy = lhs->getType();\n      auto *rhsTy = rhs->getType();\n\n      auto *destOffset = emitConstI32(builder, destTy->getOffset());\n      auto *lhsOffset = emitConstI32(builder, lhsTy->getOffset());\n      auto *rhsOffset = emitConstI32(builder, rhsTy->getOffset());\n\n      auto outScaleParams = quantization::quantizeScaleOffset32To8(\n          lhsTy->getScale() * rhsTy->getScale() \/ destTy->getScale(), 0);\n\n      auto *outPre = emitConstI32(builder, outScaleParams.pre);\n      auto *outPost = emitConstI32(builder, outScaleParams.post);\n      auto *outScale = emitConstI32(builder, outScaleParams.scale);\n\n      createCall(builder, F,\n                 {destPtr, lhsPtr, rhsPtr, destDims, lhsDims, rhsDims,\n                  destOffset, lhsOffset, rhsOffset, outPre, outPost, outScale});\n    } else {\n      createCall(builder, F,\n                 {destPtr, lhsPtr, rhsPtr, destDims, lhsDims, rhsDims});\n    }\n    break;\n  }\n\n  case Kinded::Kind::QuantizationProfileInstKind: {\n    auto *QP = cast<QuantizationProfileInst>(I);\n    auto *hist = QP->getHistogram();\n    auto *compInfo = QP->getComputationInfo();\n    auto *inputTensor = QP->getInputTensor();\n\n    auto *histPtr = emitValueAddress(builder, hist);\n    auto *compInfoPtr = emitValueAddress(builder, compInfo);\n    auto *inputTensorInfoPtr = emitValueAddress(builder, inputTensor);\n\n    auto *histDims = emitValueDims(builder, hist);\n    assert(inputTensor->getElementType() == ElemKind::FloatTy &&\n           \"None float Tensor type for Quantization Profile Instruction.\");\n    auto *tensorSize = emitConstSizeT(builder, inputTensor->getType()->size());\n\n    auto *F = getFunction(\"quantization_profile\");\n    createCall(\n        builder, F,\n        {inputTensorInfoPtr, tensorSize, compInfoPtr, histPtr, histDims});\n    break;\n  }\n\n  case Kinded::Kind::RowwiseQuantizedFullyConnectedInstKind: {\n    auto *RWQFC = cast<RowwiseQuantizedFullyConnectedInst>(I);\n    \/\/ Since we can't get the variable from a glow::Value directly,\n    \/\/ we need to traverse the var list and find the one matching the given\n    \/\/ Value.\n    Tensor scalesT;\n    auto *F_ = getIRFunction();\n    for (auto &v : F_->findConstants()) {\n      assert(isa<WeightVar>(F_->getWeightForNode(v)));\n      auto *w = cast<glow::Value>(F_->getWeightForNode(v));\n      if (w == RWQFC->getScales()) {\n        scalesT.assign(&v->getPayload());\n        break;\n      }\n    }\n    GLOW_ASSERT(scalesT.getUnsafePtr() != nullptr &&\n                \"Can't find the variable.\");\n\n    auto scalesH = scalesT.getHandle();\n    size_t rowNum = scalesH.dims()[0];\n    float inputScale = RWQFC->getSrc()->getType()->getScale();\n\n    float bScale = RWQFC->getBias()->getType()->getScale();\n    int32_t bOffset = RWQFC->getBias()->getType()->getOffset();\n\n    float outputScale = RWQFC->getDest()->getType()->getScale();\n\n    std::vector<llvm::Constant *> biasPreV(rowNum);\n    std::vector<llvm::Constant *> biasPostV(rowNum);\n    std::vector<llvm::Constant *> biasScaleV(rowNum);\n    std::vector<llvm::Constant *> outputPreV(rowNum);\n    std::vector<llvm::Constant *> outputPostV(rowNum);\n    std::vector<llvm::Constant *> outputScaleV(rowNum);\n\n    for (size_t i = 0; i < rowNum; i++) {\n      \/\/ Calculate the scale of the values that come out of the matrix\n      \/\/ multiplication part of the calculation.\n      float matMulScale = inputScale * scalesH.raw(i);\n\n      \/\/ Calculate the scaling parameters for the bias and output.\n      auto biasScaleParam =\n          quantization::quantizeScaleOffset32To8(bScale \/ matMulScale, bOffset);\n      auto outScaleParam =\n          quantization::quantizeScaleOffset32To8(matMulScale \/ outputScale, 0);\n\n      \/\/ Pass the pre-shift, post-shift and integer scale parameters for the\n      \/\/ bias and output calculation.\n      biasPreV[i] = llvm::ConstantInt::get(builder.getInt32Ty(),\n                                           biasScaleParam.pre, true);\n      biasPostV[i] = llvm::ConstantInt::get(builder.getInt32Ty(),\n                                            biasScaleParam.post, true);\n      biasScaleV[i] = llvm::ConstantInt::get(builder.getInt32Ty(),\n                                             biasScaleParam.scale, true);\n      outputPreV[i] =\n          llvm::ConstantInt::get(builder.getInt32Ty(), outScaleParam.pre, true);\n      outputPostV[i] = llvm::ConstantInt::get(builder.getInt32Ty(),\n                                              outScaleParam.post, true);\n      outputScaleV[i] = llvm::ConstantInt::get(builder.getInt32Ty(),\n                                               outScaleParam.scale, true);\n    }\n\n    auto *dest = RWQFC->getDest();\n    auto *src = RWQFC->getSrc();\n    auto *weights = RWQFC->getWeights();\n    auto *bias = RWQFC->getBias();\n    auto *weightsOffsets = RWQFC->getOffsets();\n\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *srcPtr = emitValueAddress(builder, src);\n    auto *weightsPtr = emitValueAddress(builder, weights);\n    auto *biasPtr = emitValueAddress(builder, bias);\n    auto *weightsOffsetsPtr = emitValueAddress(builder, weightsOffsets);\n    auto *biasPrePtr = emitConstArray(builder, biasPreV, builder.getInt32Ty());\n    auto *biasPostPtr =\n        emitConstArray(builder, biasPostV, builder.getInt32Ty());\n    auto *biasScalePtr =\n        emitConstArray(builder, biasScaleV, builder.getInt32Ty());\n    auto *outputPrePtr =\n        emitConstArray(builder, outputPreV, builder.getInt32Ty());\n    auto *outputPostPtr =\n        emitConstArray(builder, outputPostV, builder.getInt32Ty());\n    auto *outputScalePtr =\n        emitConstArray(builder, outputScaleV, builder.getInt32Ty());\n\n    auto *srcDims = emitValueDims(builder, src);\n    auto *weightsDims = emitValueDims(builder, weights);\n    auto *destDims = emitValueDims(builder, dest);\n    auto *biasDims = emitValueDims(builder, bias);\n    auto *row = emitConstSizeT(builder, weightsOffsets->dims()[0]);\n\n    auto *destOffset = emitConstI32(builder, dest->getType()->getOffset());\n    auto *srcOffset = emitConstI32(builder, src->getType()->getOffset());\n    auto *biasOffset = emitConstI32(builder, bOffset);\n\n    auto *F = getFunction(\"rowwise_quantized_fc\", dest->getElementType());\n\n    createCall(builder, F,\n               {destPtr, srcPtr, weightsPtr, biasPtr, weightsOffsetsPtr,\n                biasPrePtr, biasPostPtr, biasScalePtr, outputPrePtr,\n                outputPostPtr, outputScalePtr, destDims, srcDims, weightsDims,\n                biasDims, row, destOffset, srcOffset, biasOffset});\n    break;\n  }\n\n  case Kinded::Kind::BatchedAddInstKind: {\n    auto *BA = cast<BatchedAddInst>(I);\n    auto *dest = BA->getDest();\n    auto *batch = BA->getBatch();\n    auto *slice = BA->getSlice();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *batchPtr = emitValueAddress(builder, batch);\n    auto *slicePtr = emitValueAddress(builder, slice);\n\n    auto bdim = flattenCdr(batch->dims());\n    auto *numSlice = emitConstSizeT(builder, bdim.first);\n    auto *sliceSize = emitConstSizeT(builder, bdim.second);\n\n    if (batch->getType()->isQuantizedType()) {\n      auto *destTy = dest->getType();\n      auto *batchTy = batch->getType();\n      auto *sliceTy = slice->getType();\n\n      auto *destOffset = emitConstI32(builder, destTy->getOffset());\n      auto *batchOffset = emitConstI32(builder, batchTy->getOffset());\n      auto *sliceOffset = emitConstI32(builder, sliceTy->getOffset());\n\n      float destScale = destTy->getScale();\n\n      \/\/ Here, we select parameters for scaling both summands to the\n      \/\/ destination scale.\n      auto batchScaleParams = quantization::quantizeScaleOffset32To8(\n          batchTy->getScale() \/ destScale, batchTy->getOffset());\n      auto sliceScaleParams = quantization::quantizeScaleOffset32To8(\n          sliceTy->getScale() \/ destScale, sliceTy->getOffset());\n\n      auto *batchPre = emitConstI32(builder, batchScaleParams.pre);\n      auto *batchPost = emitConstI32(builder, batchScaleParams.post);\n      auto *batchScale = emitConstI32(builder, batchScaleParams.scale);\n      auto *slicePre = emitConstI32(builder, sliceScaleParams.pre);\n      auto *slicePost = emitConstI32(builder, sliceScaleParams.post);\n      auto *sliceScale = emitConstI32(builder, sliceScaleParams.scale);\n\n      llvm::Function *F = nullptr;\n      if (sliceTy->getElementType() == ElemKind::Int8QTy) {\n        F = getFunction(\"batchedadd\", dest->getElementType());\n      } else if (sliceTy->getElementType() == ElemKind::Int32QTy) {\n        F = getFunction(\"batchedadd_i32\", dest->getElementType());\n      } else {\n        GLOW_UNREACHABLE(\"Type is not supported.\");\n      }\n      createCall(builder, F,\n                 {destPtr, batchPtr, slicePtr, numSlice, sliceSize, destOffset,\n                  batchOffset, sliceOffset, batchPre, batchPost, batchScale,\n                  slicePre, slicePost, sliceScale});\n    } else {\n      auto *F = getFunction(\"batchedadd\", dest->getElementType());\n      createCall(builder, F,\n                 {destPtr, batchPtr, slicePtr, numSlice, sliceSize});\n    }\n    break;\n  }\n\n  case Kinded::Kind::BatchedReduceAddInstKind: {\n    auto *BR = cast<BatchedReduceAddInst>(I);\n    auto *dest = BR->getDest();\n    auto *batch = BR->getBatch();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *batchPtr = emitValueAddress(builder, batch);\n    auto *axis = emitConstSizeT(builder, BR->getAxis());\n\n    ShapeVector eBatchDims = expandDimsToMax(batch->dims());\n    ShapeVector eDestDims = eBatchDims;\n    eDestDims[BR->getAxis()] = 1;\n\n    auto *batchDims =\n        emitConstSizeTArray(builder, llvm::makeArrayRef(eBatchDims));\n    auto *destDims =\n        emitConstSizeTArray(builder, llvm::makeArrayRef(eDestDims));\n\n    auto *F = getFunction(\"batchedreduceadd\", dest->getElementType());\n\n    if (batch->getType()->isQuantizedType()) {\n      auto *destTy = dest->getType();\n      auto *batchTy = batch->getType();\n\n      auto *destOffset = emitConstI32(builder, destTy->getOffset());\n      auto *batchOffset = emitConstI32(builder, batchTy->getOffset());\n\n      \/\/ BatchedReduceAdd is an accumulation operation, with equations\n      \/\/    s_d * (i_d - o_d) = \\sum s_b * (i_b - o_b)\n      \/\/ => i_d - o_d = \\sum (s_b \/ s_d) * (i_b - o_b)\n      \/\/ => i_d = (s_b \/ s_d ) * [\\sum (i_b - o_b)] + o_d\n      auto batchScaleParams = quantization::quantizeScaleOffset32To8(\n          batchTy->getScale() \/ destTy->getScale(), batchTy->getOffset());\n\n      auto *batchPre = emitConstI32(builder, batchScaleParams.pre);\n      auto *batchPost = emitConstI32(builder, batchScaleParams.post);\n      auto *batchScale = emitConstI32(builder, batchScaleParams.scale);\n\n      createCall(builder, F,\n                 {destPtr, batchPtr, destDims, batchDims, destOffset,\n                  batchOffset, batchPre, batchPost, batchScale, axis});\n    } else {\n      auto *destSize = emitConstSizeT(builder, dest->size());\n\n      createCall(builder, F,\n                 {destPtr, batchPtr, destSize, destDims, batchDims, axis});\n    }\n    break;\n  }\n\n  case Kinded::Kind::ConvolutionInstKind: {\n    auto *CI = cast<ConvolutionInst>(I);\n    auto *dest = CI->getDest();\n    auto *src = CI->getSrc();\n    auto *filter = CI->getFilter();\n    auto *bias = CI->getBias();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *srcPtr = emitValueAddress(builder, src);\n    auto *filterPtr = emitValueAddress(builder, filter);\n    auto *biasPtr = emitValueAddress(builder, bias);\n\n    auto *destDims = emitValueDims(builder, dest);\n    auto *srcDims = emitValueDims(builder, src);\n    auto *filterDims = emitValueDims(builder, filter);\n    auto *biasDims = emitValueDims(builder, bias);\n\n    auto *kernels = emitConstSizeTArray(builder, CI->getKernels());\n    auto *strides = emitConstSizeTArray(builder, CI->getStrides());\n    auto *pads = emitConstSizeTArray(builder, CI->getPads());\n    auto *group = emitConstSizeT(builder, CI->getGroup());\n\n    const char *kernelName = \"convolution\";\n\n    auto destDepth = dest->dims()[3];\n\n    \/\/ Try to 'block' the convolution on the 'depth' dimension. We will process\n    \/\/ this number output slices each iteration.\n    unsigned unrollDFactor = 1;\n\n    \/\/ In libjit_convolution_f function, 'unrollDFactor' output\n    \/\/ layers will be processed together. Therefore, the number of\n    \/\/ output layers in each group should be divisible by 'unrollDFactor'\n    bool groupDividedBy8 = ((destDepth \/ CI->getGroup()) % 8) == 0;\n    if (groupDividedBy8) {\n      unrollDFactor = 8;\n    }\n\n    auto *unrollD = emitConstI32(builder, unrollDFactor);\n\n    auto *F = getFunction(kernelName, dest->getElementType());\n\n    if (src->getType()->isQuantizedType()) {\n      auto *destTy = dest->getType();\n      auto *srcTy = src->getType();\n      auto *filterTy = filter->getType();\n      auto *biasTy = bias->getType();\n\n      auto *destOffset = emitConstI32(builder, destTy->getOffset());\n      auto *srcOffset = emitConstI32(builder, srcTy->getOffset());\n      auto *filterOffset = emitConstI32(builder, filterTy->getOffset());\n      auto *biasOffset = emitConstI32(builder, biasTy->getOffset());\n\n      \/\/ Calculate the scale of the values that come out of the matrix\n      \/\/ multiplication part of the calculation.\n      float matMulScale = srcTy->getScale() * filterTy->getScale();\n\n      \/\/ Calculate the sacling parameters for the bias and output.\n      auto biasScaleParam = quantization::quantizeScaleOffset32To8(\n          biasTy->getScale() \/ matMulScale, biasTy->getOffset());\n      auto outScaleParam = quantization::quantizeScaleOffset32To8(\n          matMulScale \/ destTy->getScale(), 0);\n\n      \/\/ Pass the pre-shift, post-shift and integer scale parameters for the\n      \/\/ bias and output calculation.\n      auto *biasPre = emitConstI32(builder, biasScaleParam.pre);\n      auto *biasPost = emitConstI32(builder, biasScaleParam.post);\n      auto *biasScale = emitConstI32(builder, biasScaleParam.scale);\n      auto *outPre = emitConstI32(builder, outScaleParam.pre);\n      auto *outPost = emitConstI32(builder, outScaleParam.post);\n      auto *outScale = emitConstI32(builder, outScaleParam.scale);\n\n      createCall(builder, F,\n                 {destPtr,    srcPtr,     filterPtr,  biasPtr,   destDims,\n                  srcDims,    filterDims, biasDims,   kernels,   strides,\n                  pads,       group,      destOffset, srcOffset, filterOffset,\n                  biasOffset, biasPre,    biasPost,   biasScale, outPre,\n                  outPost,    outScale,   unrollD});\n    } else {\n      createCall(builder, F,\n                 {destPtr, srcPtr, filterPtr, biasPtr, destDims, srcDims,\n                  filterDims, biasDims, kernels, strides, pads, group,\n                  unrollD});\n    }\n    break;\n  }\n\n  case Kinded::Kind::ConvolutionGradInstKind: {\n    auto *CG = cast<ConvolutionGradInst>(I);\n    auto *srcGrad = CG->getSrcGrad();\n    auto *destGrad = CG->getDestGrad();\n    auto *src = CG->getSrc();\n    auto *filterGrad = CG->getFilterGrad();\n    auto *srcGradPtr = emitValueAddress(builder, srcGrad);\n    auto *destGradPtr = emitValueAddress(builder, destGrad);\n    auto *srcPtr = emitValueAddress(builder, src);\n    auto *filterGradPtr = emitValueAddress(builder, filterGrad);\n    auto *biasGradPtr = emitValueAddress(builder, CG->getBiasGrad());\n    auto *filterPtr = emitValueAddress(builder, CG->getFilter());\n\n    auto *destGradDims = emitValueDims(builder, destGrad);\n    auto *srcDims = emitValueDims(builder, src);\n    auto *filterGradDims = emitValueDims(builder, filterGrad);\n\n    auto *kernels = emitConstSizeTArray(builder, CG->getKernels());\n    auto *strides = emitConstSizeTArray(builder, CG->getStrides());\n    auto *pads = emitConstSizeTArray(builder, CG->getPads());\n    auto *group = emitConstSizeT(builder, CG->getGroup());\n\n    auto *F = getFunction(\"convolution_grad\", srcGrad->getElementType());\n    createCall(builder, F,\n               {srcGradPtr, destGradPtr, srcPtr, filterGradPtr, biasGradPtr,\n                filterPtr, destGradDims, srcDims, filterGradDims, kernels,\n                strides, pads, group});\n    break;\n  }\n\n  case Kinded::Kind::CrossEntropyLossInstKind: {\n    auto *CI = cast<CrossEntropyLossInst>(I);\n    auto *P = CI->getP();\n    auto *labels = CI->getLabels();\n    auto *CE = CI->getCE();\n\n    auto *CEPtr = emitValueAddress(builder, CE);\n    auto *PPtr = emitValueAddress(builder, P);\n    auto *labelsPtr = emitValueAddress(builder, labels);\n    auto *dims = emitValueDims(builder, P);\n\n    auto *F = getFunction(\"cross_entropy_loss\", CE->getElementType());\n    createCall(builder, F, {CEPtr, PPtr, labelsPtr, dims});\n    break;\n  }\n\n  case Kinded::Kind::LengthsToRangesInstKind: {\n    auto *LTR = cast<LengthsToRangesInst>(I);\n    auto *dest = LTR->getDest();\n    auto *lengths = LTR->getLengths();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *lengthsPtr = emitValueAddress(builder, lengths);\n    auto *size = emitConstSizeT(builder, lengths->dims()[0]);\n    auto *F = getFunction(\"lengths_to_ranges\", dest->getElementType());\n    createCall(builder, F, {destPtr, lengthsPtr, size});\n    break;\n  }\n\n  case Kinded::Kind::LengthsSumInstKind: {\n    auto *LS = cast<LengthsSumInst>(I);\n    auto *dest = LS->getDest();\n    auto *data = LS->getData();\n    auto *lengths = LS->getLengths();\n\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *dataPtr = emitValueAddress(builder, data);\n    auto *lengthsPtr = emitValueAddress(builder, lengths);\n\n    auto *lengthsSize = emitConstSizeT(builder, lengths->size());\n    auto *dataType = data->getType();\n    auto *destSize = emitConstSizeT(builder, dest->size());\n    auto *sliceSize =\n        emitConstSizeT(builder, dataType->size() \/ dataType->dims()[0]);\n\n    auto *F = getFunction(\"lengths_sum\", data->getElementType());\n    createCall(\n        builder, F,\n        {destPtr, dataPtr, lengthsPtr, destSize, lengthsSize, sliceSize});\n    break;\n  }\n\n  case Kinded::Kind::LocalResponseNormalizationInstKind: {\n    auto *LRN = cast<LocalResponseNormalizationInst>(I);\n    auto *dest = LRN->getDest();\n    auto *src = LRN->getSrc();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *srcPtr = emitValueAddress(builder, src);\n    auto *scalePtr = emitValueAddress(builder, LRN->getScale());\n\n    auto *destDims = emitValueDims(builder, dest);\n    auto *srcDims = emitValueDims(builder, src);\n    auto *halfWindow = emitConstSizeT(builder, LRN->getHalfWindowSize());\n    auto *alpha = emitConstF32(builder, LRN->getAlpha());\n    auto *beta = emitConstF32(builder, LRN->getBeta());\n    auto *k = emitConstF32(builder, LRN->getK());\n\n    auto *F =\n        getFunction(\"local_response_normalization\", dest->getElementType());\n    createCall(builder, F,\n               {destPtr, srcPtr, scalePtr, destDims, srcDims, halfWindow, alpha,\n                beta, k});\n    break;\n  }\n\n  case Kinded::Kind::LocalResponseNormalizationGradInstKind: {\n    auto *LRNG = llvm::cast<LocalResponseNormalizationGradInst>(I);\n    auto *srcGrad = LRNG->getSrcGrad();\n    auto *dest = LRNG->getDest();\n    auto *srcGradPtr = emitValueAddress(builder, srcGrad);\n    auto *destGradPtr = emitValueAddress(builder, LRNG->getDestGrad());\n    auto *srcPtr = emitValueAddress(builder, LRNG->getSrc());\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *scalePtr = emitValueAddress(builder, LRNG->getScale());\n\n    auto *destDims = emitValueDims(builder, dest);\n\n    auto *halfWindow = emitConstSizeT(builder, LRNG->getHalfWindowSize());\n    auto *alpha = emitConstF32(builder, LRNG->getAlpha());\n    auto *beta = emitConstF32(builder, LRNG->getBeta());\n\n    auto *F = getFunction(\"local_response_normalization_grad\",\n                          srcGrad->getElementType());\n    createCall(builder, F,\n               {srcGradPtr, destGradPtr, srcPtr, destPtr, scalePtr, destDims,\n                halfWindow, alpha, beta});\n    break;\n  }\n\n  case Kinded::Kind::MaxPoolInstKind: {\n    auto *PM = cast<MaxPoolInst>(I);\n    auto *dest = PM->getDest();\n    auto *src = PM->getSrc();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *srcPtr = emitValueAddress(builder, src);\n\n    auto *destDims = emitValueDims(builder, dest);\n    auto *srcDims = emitValueDims(builder, src);\n\n    auto *kernels = emitConstSizeTArray(builder, PM->getKernels());\n    auto *strides = emitConstSizeTArray(builder, PM->getStrides());\n    auto *pads = emitConstSizeTArray(builder, PM->getPads());\n\n    auto *F = getFunction(\"max_pool\", dest->getElementType());\n    createCall(builder, F,\n               {srcPtr, destPtr, srcDims, destDims, kernels, strides, pads});\n    break;\n  }\n\n  case Kinded::Kind::MaxPoolWithXYInstKind: {\n    auto *PMXY = cast<MaxPoolWithXYInst>(I);\n    auto *dest = PMXY->getDest();\n    auto *src = PMXY->getSrc();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *srcPtr = emitValueAddress(builder, src);\n    auto *srcXYPtr = emitValueAddress(builder, PMXY->getSrcXY());\n\n    auto *destDims = emitValueDims(builder, dest);\n    auto *srcDims = emitValueDims(builder, src);\n\n    auto *kernels = emitConstSizeTArray(builder, PMXY->getKernels());\n    auto *strides = emitConstSizeTArray(builder, PMXY->getStrides());\n    auto *pads = emitConstSizeTArray(builder, PMXY->getPads());\n\n    auto *F = getFunction(\"max_pool_xy\", dest->getElementType());\n    createCall(\n        builder, F,\n        {srcPtr, destPtr, srcXYPtr, srcDims, destDims, kernels, strides, pads});\n    break;\n  }\n\n  case Kinded::Kind::MaxPoolWithXYGradInstKind: {\n    auto *PMG = cast<MaxPoolWithXYGradInst>(I);\n    auto *srcGrad = PMG->getSrcGrad();\n    auto *srcGradPtr = emitValueAddress(builder, srcGrad);\n    auto *destGradPtr = emitValueAddress(builder, PMG->getDestGrad());\n    auto *srcXYPtr = emitValueAddress(builder, PMG->getSrcXY());\n\n    auto *srcGradDims = emitValueDims(builder, srcGrad);\n    auto *destDims = emitValueDims(builder, PMG->getDest());\n\n    auto *F = getFunction(\"max_pool_xy_grad\", srcGrad->getElementType());\n    createCall(builder, F,\n               {srcGradPtr, destGradPtr, srcXYPtr, srcGradDims, destDims});\n    break;\n  }\n\n  case Kinded::Kind::AvgPoolInstKind: {\n    auto *PA = cast<AvgPoolInst>(I);\n    auto *dest = PA->getDest();\n    auto *src = PA->getSrc();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *srcPtr = emitValueAddress(builder, src);\n\n    auto *destDims = emitValueDims(builder, dest);\n    auto *srcDims = emitValueDims(builder, src);\n\n    auto *kernels = emitConstSizeTArray(builder, PA->getKernels());\n    auto *strides = emitConstSizeTArray(builder, PA->getStrides());\n    auto *pads = emitConstSizeTArray(builder, PA->getPads());\n\n    if (src->getType()->isQuantizedType()) {\n      auto *destTy = dest->getType();\n      auto *srcTy = src->getType();\n      auto *destOffset = emitConstI32(builder, destTy->getOffset());\n      auto *srcOffset = emitConstI32(builder, srcTy->getOffset());\n      \/\/ Reduce resulting scale by a factor of PA->getKernels()[0] *\n      \/\/ PA->getKernels()[1] since each subtensor value is divided by the area\n      \/\/ of kernel.\n      auto outScaleParam = quantization::quantizeScaleOffset32To8(\n          srcTy->getScale() \/ destTy->getScale() \/\n              (PA->getKernels()[0] * PA->getKernels()[1]),\n          destTy->getOffset());\n      auto *outPre = emitConstI32(builder, outScaleParam.pre);\n      auto *outPost = emitConstI32(builder, outScaleParam.post);\n      auto *outScale = emitConstI32(builder, outScaleParam.scale);\n\n      auto *F = getFunction(\"avg_pool\", dest->getElementType());\n      createCall(builder, F,\n                 {srcPtr, destPtr, srcDims, destDims, kernels, strides, pads,\n                  destOffset, srcOffset, outPre, outPost, outScale});\n      break;\n    } else {\n      auto *F = getFunction(\"avg_pool\", dest->getElementType());\n      createCall(builder, F,\n                 {srcPtr, destPtr, srcDims, destDims, kernels, strides, pads});\n      break;\n    }\n  }\n\n  case Kinded::Kind::AvgPoolGradInstKind: {\n    auto *PAG = cast<AvgPoolGradInst>(I);\n    auto *srcGrad = PAG->getSrcGrad();\n    auto *srcGradPtr = emitValueAddress(builder, srcGrad);\n    auto *destGradPtr = emitValueAddress(builder, PAG->getDestGrad());\n\n    auto *srcGradDims = emitValueDims(builder, srcGrad);\n    auto *destDims = emitValueDims(builder, PAG->getDest());\n\n    auto *kernels = emitConstSizeTArray(builder, PAG->getKernels());\n    auto *strides = emitConstSizeTArray(builder, PAG->getStrides());\n    auto *pads = emitConstSizeTArray(builder, PAG->getPads());\n\n    auto *F = getFunction(\"avg_pool_grad\", srcGrad->getElementType());\n    createCall(builder, F,\n               {srcGradPtr, destGradPtr, srcGradDims, destDims, kernels,\n                strides, pads});\n    break;\n  }\n\n  case Kinded::Kind::SoftMaxInstKind: {\n    auto *SM = cast<SoftMaxInst>(I);\n    auto *dest = SM->getDest();\n    auto *src = SM->getSrc();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *srcPtr = emitValueAddress(builder, src);\n\n    auto *destDims = emitValueDims(builder, dest);\n    auto *srcDims = emitValueDims(builder, src);\n\n    auto *F = getFunction(\"softmax\", dest->getElementType());\n    createCall(builder, F, {srcPtr, destPtr, srcDims, destDims});\n    break;\n  }\n\n  case Kinded::Kind::SoftMaxGradInstKind: {\n    auto *SMG = cast<SoftMaxGradInst>(I);\n    auto *srcGrad = SMG->getSrcGrad();\n    auto *selected = SMG->getSelected();\n    auto *srcGradPtr = emitValueAddress(builder, srcGrad);\n    auto *destPtr = emitValueAddress(builder, SMG->getOrigDest());\n    auto *selectedPtr = emitValueAddress(builder, selected);\n\n    auto *srcGradDims = emitValueDims(builder, srcGrad);\n    auto *selectedDims = emitValueDims(builder, selected);\n\n    auto *F = getFunction(\"softmax_grad\", srcGrad->getElementType());\n    createCall(builder, F,\n               {srcGradPtr, destPtr, selectedPtr, srcGradDims, selectedDims});\n    break;\n  }\n\n  case Kinded::Kind::TopKInstKind: {\n    auto *TI = cast<TopKInst>(I);\n    auto *input = TI->getInput();\n    auto *valuesPtr = emitValueAddress(builder, TI->getValues());\n    auto *indicesPtr = emitValueAddress(builder, TI->getIndices());\n    auto *inputPtr = emitValueAddress(builder, input);\n    auto *scratchPtr = emitValueAddress(builder, TI->getScratch());\n\n    auto *k = emitConstSizeT(builder, TI->getK());\n    auto *n = emitConstSizeT(builder, input->dims().back());\n    auto *size = emitConstSizeT(builder, input->size());\n\n    auto *F = getFunction(\"topk\", input->getElementType());\n    createCall(builder, F,\n               {valuesPtr, indicesPtr, inputPtr, scratchPtr, k, n, size});\n    break;\n  }\n\n  case Kinded::Kind::TransposeInstKind: {\n    auto *TI = cast<TransposeInst>(I);\n    auto *dest = TI->getDest();\n    auto *src = TI->getSrc();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *srcPtr = emitValueAddress(builder, src);\n\n    auto *destDims = emitValueDims(builder, dest);\n    auto *srcDims = emitValueDims(builder, src);\n\n    \/\/ Convert the mask to size_t type.\n    ShapeVector shuffSizeT;\n    for (auto D : TI->getShuffle()) {\n      shuffSizeT.push_back((size_t)D);\n    }\n\n    auto *shuffle =\n        emitConstSizeTArray(builder, llvm::makeArrayRef(shuffSizeT));\n    auto *len = emitConstSizeT(builder, TI->getShuffle().size());\n\n    auto *F = getFunction(\"transpose\", dest->getElementType());\n    createCall(builder, F, {srcPtr, destPtr, srcDims, destDims, shuffle, len});\n    break;\n  }\n\n    \/\/ Alloc and Dealloc instructions are handled by the memory allocator.\n  case Kinded::Kind::AllocActivationInstKind:\n  case Kinded::Kind::DeallocActivationInstKind:\n  case Kinded::Kind::TensorViewInstKind:\n    break;\n\n  case Kinded::Kind::InsertTensorInstKind: {\n    auto *ITI = llvm::cast<InsertTensorInst>(I);\n    auto *dest = ITI->getDest();\n    auto *src = ITI->getSrc();\n    auto offsets = ITI->getOffsets();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *srcPtr = emitValueAddress(builder, src);\n\n    auto *destDims = emitValueDims(builder, dest);\n    auto *srcDims = emitValueDims(builder, src);\n\n    auto *destDimsSize =\n        emitConstSizeT(builder, dest->getType()->dims().size());\n    auto *srcDimsSize = emitConstSizeT(builder, src->getType()->dims().size());\n    auto *offsetsPtr = emitConstSizeTArray(builder, offsets);\n    auto *offsetsArraySize = emitConstSizeT(builder, offsets.size());\n    auto *count = emitConstSizeT(builder, ITI->getCount());\n    auto *axis = emitConstSizeT(builder, ITI->getAxis());\n\n    \/\/ Don't specialize the offsetPtr because we typically generate lots of\n    \/\/ extracts from different offsets and specializing on this argument does\n    \/\/ not speed things up.\n    markArgAsUnspecialized(offsetsPtr);\n\n    auto *F = getFunction(\"insert_tensor\", dest->getElementType());\n    createCall(builder, F,\n               {destPtr, srcPtr, offsetsPtr, destDims, srcDims, destDimsSize,\n                srcDimsSize, offsetsArraySize, count, axis});\n    break;\n  }\n\n  case Kinded::Kind::ExtractTensorInstKind: {\n    auto *ITI = llvm::cast<ExtractTensorInst>(I);\n    auto *dest = ITI->getDest();\n    auto *src = ITI->getSrc();\n    auto offsets = ITI->getOffsets();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *srcPtr = emitValueAddress(builder, src);\n\n    auto *destDims = emitValueDims(builder, dest);\n    auto *srcDims = emitValueDims(builder, src);\n\n    auto *destDimsSize =\n        emitConstSizeT(builder, dest->getType()->dims().size());\n    auto *srcDimsSize = emitConstSizeT(builder, src->getType()->dims().size());\n    auto *offsetsPtr = emitConstSizeTArray(builder, offsets);\n    auto *offsetsArraySize = emitConstSizeT(builder, offsets.size());\n\n    \/\/ Don't specialize the offsetPtr because we typically generate lots of\n    \/\/ extracts from different offsets and specializing on this argument does\n    \/\/ not speed things up.\n    markArgAsUnspecialized(offsetsPtr);\n\n    auto *F = getFunction(\"extract_tensor\", dest->getElementType());\n    createCall(builder, F,\n               {srcPtr, destPtr, offsetsPtr, srcDims, destDims, srcDimsSize,\n                destDimsSize, offsetsArraySize});\n    break;\n  }\n\n  case Kinded::Kind::GatherInstKind: {\n    auto *GI = llvm::cast<GatherInst>(I);\n    auto *dest = GI->getDest();\n    auto *data = GI->getData();\n    auto *indices = GI->getIndices();\n    unsigned batchDims = GI->getBatchDims();\n\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *dataPtr = emitValueAddress(builder, data);\n    auto *indicesPtr = emitValueAddress(builder, indices);\n\n    auto *indicesSize = emitConstSizeT(builder, indices->size());\n\n    auto *dataType = data->getType();\n\n    \/\/ The size of the sample in the batch.\n    size_t sampleSize = dataType->getSliceSize(batchDims);\n    \/\/ The size of the slices that we gather.\n    size_t sliceSize = dataType->getSliceSize(batchDims + 1);\n    \/\/ The size of each sample in the batch.\n    size_t numSamples = dataType->size() \/ sampleSize;\n\n    auto *sliceSizeVal = emitConstSizeT(builder, sliceSize);\n    auto *numSamplesVal = emitConstSizeT(builder, numSamples);\n    auto *sampleSizeVal = emitConstSizeT(builder, sampleSize);\n\n    \/\/ Dispatching function depeending on the input type of Indices.\n    llvm::Function *F = nullptr;\n    if (indices->getElementType() == ElemKind::Int64ITy) {\n      F = getFunction(\"gather64\", dest->getElementType());\n    } else if (indices->getElementType() == ElemKind::Int32ITy) {\n      F = getFunction(\"gather32\", dest->getElementType());\n    }\n    if (!F) {\n      llvm_unreachable(\"Cannot get function for Gather. \"\n                       \"Indices input of Gather has to be int32 or int64\");\n    }\n    createCall(builder, F,\n               {destPtr, dataPtr, indicesPtr, indicesSize, sliceSizeVal,\n                numSamplesVal, sampleSizeVal});\n    break;\n  }\n\n  case Kinded::Kind::GatherRangesInstKind: {\n    auto *GRI = llvm::cast<GatherRangesInst>(I);\n    auto *output = GRI->getOutput();\n    auto *lengths = GRI->getLengths();\n    auto *data = GRI->getData();\n    auto *ranges = GRI->getRanges();\n\n    auto *outputPtr = emitValueAddress(builder, output);\n    auto *lengthsPtr = emitValueAddress(builder, lengths);\n    auto *dataPtr = emitValueAddress(builder, data);\n    auto *rangesPtr = emitValueAddress(builder, ranges);\n\n    auto rangesType = ranges->getType();\n\n    \/\/ The number of examples in ranges.\n    size_t numExamples = rangesType->dims()[0];\n    \/\/ The number of range pairs in each example.\n    size_t exampleSize = rangesType->dims()[1];\n\n    auto *numExamplesVal = emitConstSizeT(builder, numExamples);\n    auto *exampleSizeVal = emitConstSizeT(builder, exampleSize);\n\n    \/\/ Dispatching function depending on the input type of Ranges.\n    llvm::Function *F = nullptr;\n    if (ranges->getElementType() == ElemKind::Int64ITy) {\n      F = getFunction(\"gatherranges64\", output->getElementType());\n    } else if (ranges->getElementType() == ElemKind::Int32ITy) {\n      F = getFunction(\"gatherranges32\", output->getElementType());\n    }\n    if (!F) {\n      llvm_unreachable(\"Cannot get function for GatherRanges. \"\n                       \"Ranges input of GatherRanges has to be int32 or int64\");\n    }\n    createCall(builder, F,\n               {outputPtr, lengthsPtr, dataPtr, rangesPtr, numExamplesVal,\n                exampleSizeVal});\n    break;\n  }\n\n  case Kinded::Kind::ScatterAssignInstKind: {\n    auto *SAI = llvm::cast<ScatterAssignInst>(I);\n    auto *data = SAI->getData();\n    auto *indices = SAI->getIndices();\n    auto *slices = SAI->getSlices();\n\n    auto *dataPtr = emitValueAddress(builder, data);\n    auto *indicesPtr = emitValueAddress(builder, indices);\n    auto *slicesPtr = emitValueAddress(builder, slices);\n\n    auto *indicesSize = emitConstSizeT(builder, indices->size());\n\n    auto *dataType = data->getType();\n    auto *sliceSize =\n        emitConstSizeT(builder, dataType->size() \/ dataType->dims()[0]);\n\n    auto *F = getFunction(\"scatterassign\", data->getElementType());\n    createCall(builder, F,\n               {dataPtr, indicesPtr, slicesPtr, indicesSize, sliceSize});\n    break;\n  }\n\n  case Kinded::Kind::SparseLengthsWeightedSumInstKind: {\n    auto *SI = cast<SparseLengthsWeightedSumInst>(I);\n    auto *dest = SI->getDest();\n    auto *data = SI->getData();\n    auto *weights = SI->getWeights();\n    auto *indices = SI->getIndices();\n    auto *lengths = SI->getLengths();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *dataPtr = emitValueAddress(builder, data);\n    auto *weightsPtr = emitValueAddress(builder, weights);\n    auto *indicesPtr = emitValueAddress(builder, indices);\n    auto *lengthsPtr = emitValueAddress(builder, lengths);\n    auto *segments = emitConstSizeT(builder, lengths->dims()[0]);\n    auto *lineSize = emitConstSizeT(builder, data->size() \/ data->dims()[0]);\n    auto *F =\n        getFunction(\"sparse_lengths_weighted_sum\", dest->getElementType());\n    createCall(builder, F,\n               {destPtr, dataPtr, weightsPtr, indicesPtr, lengthsPtr, segments,\n                lineSize});\n    break;\n  }\n\n  case Kinded::Kind::RowwiseQuantizedSparseLengthsWeightedSumInstKind: {\n    auto *N = cast<RowwiseQuantizedSparseLengthsWeightedSumInst>(I);\n    auto *dest = N->getDest();\n    auto *data = N->getData();\n    auto *scales = N->getScales();\n    auto *offsets = N->getOffsets();\n    auto *weights = N->getWeights();\n    auto *indices = N->getIndices();\n    auto *lengths = N->getLengths();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *dataPtr = emitValueAddress(builder, data);\n    auto *scalesPtr = emitValueAddress(builder, scales);\n    auto *offsetsPtr = emitValueAddress(builder, offsets);\n    auto *weightsPtr = emitValueAddress(builder, weights);\n    auto *indicesPtr = emitValueAddress(builder, indices);\n    auto *lengthsPtr = emitValueAddress(builder, lengths);\n    auto *segments = emitConstSizeT(builder, lengths->dims()[0]);\n    auto *lineSize = emitConstSizeT(builder, data->size() \/ data->dims()[0]);\n    auto *F = getFunction(\"rowwise_quantized_sparse_lengths_weighted_sum\",\n                          dest->getElementType());\n    createCall(builder, F,\n               {destPtr, dataPtr, scalesPtr, offsetsPtr, weightsPtr, indicesPtr,\n                lengthsPtr, segments, lineSize});\n    break;\n  }\n\n  case Kinded::Kind::FusedRowwiseQuantizedSparseLengthsWeightedSumInstKind: {\n    auto *N = cast<FusedRowwiseQuantizedSparseLengthsWeightedSumInst>(I);\n    auto *dest = N->getDest();\n    auto *data = N->getData();\n    auto *weights = N->getWeights();\n    auto *indices = N->getIndices();\n    auto *lengths = N->getLengths();\n    auto *destPtr = emitValueAddress(builder, dest);\n    auto *dataPtr = emitValueAddress(builder, data);\n    auto *weightsPtr = emitValueAddress(builder, weights);\n    auto *indicesPtr = emitValueAddress(builder, indices);\n    auto *lengthsPtr = emitValueAddress(builder, lengths);\n    auto *segments = emitConstSizeT(builder, lengths->dims()[0]);\n    auto *inLineSize = emitConstSizeT(builder, data->size() \/ data->dims()[0]);\n    auto *outLineSize = emitConstSizeT(builder, dest->size() \/ dest->dims()[0]);\n    auto *F = getFunction(\"fused_rowwise_quantized_sparse_lengths_weighted_sum\",\n                          dest->getElementType());\n    createCall(builder, F,\n               {destPtr, dataPtr, weightsPtr, indicesPtr, lengthsPtr, segments,\n                inLineSize, outLineSize});\n    break;\n  }\n\n  case Kinded::Kind::SparseToDenseInstKind: {\n    auto *STDI = llvm::cast<SparseToDenseInst>(I);\n    auto *indices = STDI->getIndices();\n    auto *values = STDI->getValues();\n    auto *dest = STDI->getDest();\n\n    auto *indicesPtr = emitValueAddress(builder, indices);\n    auto *valuesPtr = emitValueAddress(builder, values);\n    auto *destPtr = emitValueAddress(builder, dest);\n\n    auto *indicesSize = emitConstSizeT(builder, indices->size());\n    auto *destSize = emitConstSizeT(builder, dest->size());\n\n    auto *valuesType = values->getType();\n    auto *valueSize =\n        emitConstSizeT(builder, valuesType->size() \/ valuesType->dims()[0]);\n\n    auto *F = getFunction(\"sparse_to_dense\", dest->getElementType());\n    createCall(\n        builder, F,\n        {destPtr, indicesPtr, valuesPtr, indicesSize, destSize, valueSize});\n    break;\n  }\n\n  case Kinded::Kind::DebugPrintInstKind: {\n    auto *DPI = llvm::cast<DebugPrintInst>(I);\n    auto *src = DPI->getSrc();\n    auto *srcPtr = emitValueAddress(builder, src);\n    srcPtr = builder.CreateBitCast(srcPtr, builder.getInt8PtrTy());\n    auto *srcDims = emitValueDims(builder, src);\n    auto *srcDimsSize = emitConstSizeT(builder, src->getType()->dims().size());\n    auto *srcElemKind =\n        emitConstSizeT(builder, static_cast<size_t>(src->getElementType()));\n    auto *name = emitStringConst(builder, I->getName());\n\n    auto *F = getFunction(\"dump_tensor\");\n    createCall(builder, F, {srcPtr, srcDims, srcDimsSize, srcElemKind, name});\n    break;\n  }\n\n  case Kinded::Kind::TraceEventInstKind: {\n    auto *TEI = llvm::cast<TraceEventInst>(I);\n    auto *data = TEI->getData();\n    auto *offset = emitConstSizeT(builder, TEI->getIndex());\n    auto *dataPtr = emitValueAddress(builder, data);\n    auto *F = getFunction(\"write_timestamp\");\n    createCall(builder, F, {dataPtr, offset});\n    break;\n  }\n\n  default:\n#ifndef NDEBUG\n    llvm::errs() << \"Cannot select the instruction:\\n\";\n    I->dump(llvm::errs());\n    llvm::errs() << \"\\n\";\n#endif\n    GLOW_UNREACHABLE(\"ERROR: Cannot select the instruction.\");\n  }\n}\n\nunsigned LLVMIRGen::getTargetSizeTWidth() const {\n  return getPointerNumBits(*TM_);\n}\n","avg_line_length":42.3510864934,"max_line_length":80,"alphanum_fraction":0.6439868005,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7131,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/**\n\t* \\file QryWzskShtRef1NFile.cpp\n\t* job handler for job QryWzskShtRef1NFile (implementation)\n\t* \\copyright (C) 2016-2020 MPSI Technologies GmbH\n\t* \\author Emily Johnson (auto-generation)\n\t* \\date created: 5 Dec 2020\n\t*\/\n\/\/ IP header --- ABOVE\n\n#ifdef WZSKCMBD\n\t#include <Wzskcmbd.h>\n#else\n\t#include <Wzskd.h>\n#endif\n\n#include \"QryWzskShtRef1NFile.h\"\n\n#include \"QryWzskShtRef1NFile_blks.cpp\"\n\nusing namespace std;\nusing namespace Sbecore;\nusing namespace Xmlio;\n\n\/\/ IP ns.cust --- INSERT\n\n\/******************************************************************************\n class QryWzskShtRef1NFile\n ******************************************************************************\/\n\nQryWzskShtRef1NFile::QryWzskShtRef1NFile(\n\t\t\tXchgWzsk* xchg\n\t\t\t, DbsWzsk* dbswzsk\n\t\t\t, const ubigint jrefSup\n\t\t\t, const uint ixWzskVLocale\n\t\t) :\n\t\t\tJobWzsk(xchg, VecWzskVJob::QRYWZSKSHTREF1NFILE, jrefSup, ixWzskVLocale)\n\t\t{\n\tjref = xchg->addJob(dbswzsk, this, jrefSup);\n\n\t\/\/ IP constructor.cust1 --- INSERT\n\n\txchg->addStmgr(jref, Stub::VecVNonetype::SHORT);\n\tixWzskVQrystate = VecWzskVQrystate::OOD;\n\n\t\/\/ IP constructor.cust2 --- INSERT\n\n\trerun(dbswzsk);\n\n\txchg->addClstn(VecWzskVCall::CALLWZSKSTUBCHG, jref, Clstn::VecVJobmask::SELF, 0, false, Arg(), 0, Clstn::VecVJactype::LOCK);\n\n\t\/\/ IP constructor.cust3 --- INSERT\n\n\t\/\/ IP constructor.spec3 --- INSERT\n};\n\nQryWzskShtRef1NFile::~QryWzskShtRef1NFile() {\n\t\/\/ IP destructor.spec --- INSERT\n\n\t\/\/ IP destructor.cust --- INSERT\n\n\txchg->removeJobByJref(jref);\n};\n\n\/\/ IP cust --- INSERT\n\nvoid QryWzskShtRef1NFile::refreshJnum() {\n\tubigint preRefSel = xchg->getRefPreset(VecWzskVPreset::PREWZSKREFSEL, jref);\n\n\tstgiac.jnum = getJnumByRef(preRefSel);\n};\n\nvoid QryWzskShtRef1NFile::rerun(\n\t\t\tDbsWzsk* dbswzsk\n\t\t\t, const bool call\n\t\t) {\n\tstring sqlstr;\n\n\tuint cnt;\n\n\tubigint preRefSht = xchg->getRefPreset(VecWzskVPreset::PREWZSKREFSHT, jref);\n\n\txchg->removeClstns(VecWzskVCall::CALLWZSKFILMOD_RETREUEQ, jref);\n\n\tdbswzsk->tblwzskqselect->removeRstByJref(jref);\n\tdbswzsk->tblwzskqshtref1nfile->removeRstByJref(jref);\n\n\tsqlstr = \"SELECT COUNT(TblWzskMFile.ref)\";\n\tsqlstr += \" FROM TblWzskMFile\";\n\tsqlstr += \" WHERE TblWzskMFile.refIxVTbl = \" + to_string(VecWzskVMFileRefTbl::SHT);\n\tsqlstr += \" AND TblWzskMFile.refUref = \" + to_string(preRefSht) + \"\";\n\tdbswzsk->loadUintBySQL(sqlstr, cnt);\n\n\tstatshr.ntot = cnt;\n\tstatshr.nload = 0;\n\n\tif (stgiac.jnumFirstload > cnt) {\n\t\tif (cnt >= stgiac.nload) stgiac.jnumFirstload = cnt-stgiac.nload+1;\n\t\telse stgiac.jnumFirstload = 1;\n\t};\n\n\tsqlstr = \"INSERT INTO TblWzskQShtRef1NFile(jref, jnum, ref)\";\n\tsqlstr += \" SELECT \" + to_string(jref) + \", 0, TblWzskMFile.ref\";\n\tsqlstr += \" FROM TblWzskMFile\";\n\tsqlstr += \" WHERE TblWzskMFile.refIxVTbl = \" + to_string(VecWzskVMFileRefTbl::SHT);\n\tsqlstr += \" AND TblWzskMFile.refUref = \" + to_string(preRefSht) + \"\";\n\tsqlstr += \" ORDER BY Filename ASC\";\n\tsqlstr += \" LIMIT \" + to_string(stgiac.nload) + \" OFFSET \" + to_string(stgiac.jnumFirstload-1);\n\tdbswzsk->executeQuery(sqlstr);\n\n\tsqlstr = \"UPDATE TblWzskQShtRef1NFile SET jnum = qref WHERE jref = \" + to_string(jref);\n\tdbswzsk->executeQuery(sqlstr);\n\n\tixWzskVQrystate = VecWzskVQrystate::UTD;\n\tstatshr.jnumFirstload = stgiac.jnumFirstload;\n\n\tfetch(dbswzsk);\n\n\tif (call) xchg->triggerCall(dbswzsk, VecWzskVCall::CALLWZSKSTATCHG, jref);\n\n\txchg->addIxRefClstn(VecWzskVCall::CALLWZSKFILMOD_RETREUEQ, jref, Clstn::VecVJobmask::ALL, 0, false, VecWzskVMFileRefTbl::SHT, preRefSht);\n};\n\nvoid QryWzskShtRef1NFile::fetch(\n\t\t\tDbsWzsk* dbswzsk\n\t\t) {\n\tstring sqlstr;\n\n\tStmgrWzsk* stmgr = NULL;\n\tStcch* stcch = NULL;\n\n\tWzskQShtRef1NFile* rec = NULL;\n\n\tdbswzsk->tblwzskqshtref1nfile->loadRstByJref(jref, false, rst);\n\tstatshr.nload = rst.nodes.size();\n\n\tstmgr = xchg->getStmgrByJref(jref);\n\n\tif (stmgr) {\n\t\tstmgr->begin();\n\n\t\tstcch = stmgr->stcch;\n\t\tstcch->clear();\n\n\t\tfor (unsigned int i = 0; i < rst.nodes.size(); i++) {\n\t\t\trec = rst.nodes[i];\n\n\t\t\trec->jnum = statshr.jnumFirstload + i;\n\t\t\trec->stubRef = StubWzsk::getStubFilStd(dbswzsk, rec->ref, ixWzskVLocale, Stub::VecVNonetype::SHORT, stcch);\n\t\t};\n\n\t\tstmgr->commit();\n\t\tstmgr->unlockAccess(\"QryWzskShtRef1NFile\", \"fetch\");\n\t};\n\n\trefreshJnum();\n};\n\nuint QryWzskShtRef1NFile::getJnumByRef(\n\t\t\tconst ubigint ref\n\t\t) {\n\tuint retval = 0;\n\n\tWzskQShtRef1NFile* rec = NULL;\n\n\tfor (unsigned int i = 0; i < rst.nodes.size(); i++) {\n\t\trec = rst.nodes[i];\n\n\t\tif (rec->ref == ref) {\n\t\t\tretval = rec->jnum;\n\t\t\tbreak;\n\t\t};\n\t};\n\n\treturn retval;\n};\n\nubigint QryWzskShtRef1NFile::getRefByJnum(\n\t\t\tconst uint jnum\n\t\t) {\n\tuint ref = 0;\n\n\tWzskQShtRef1NFile* rec = getRecByJnum(jnum);\n\tif (rec) ref = rec->ref;\n\treturn ref;\n};\n\nWzskQShtRef1NFile* QryWzskShtRef1NFile::getRecByJnum(\n\t\t\tconst uint jnum\n\t\t) {\n\tWzskQShtRef1NFile* rec = NULL;\n\n\tfor (unsigned int i = 0; i < rst.nodes.size(); i++) {\n\t\trec = rst.nodes[i];\n\t\tif (rec->jnum == jnum) break;\n\t};\n\n\tif (rec) if (rec->jnum != jnum) rec = NULL;\n\treturn rec;\n};\n\nvoid QryWzskShtRef1NFile::handleRequest(\n\t\t\tDbsWzsk* dbswzsk\n\t\t\t, ReqWzsk* req\n\t\t) {\n\tif (req->ixVBasetype == ReqWzsk::VecVBasetype::CMD) {\n\t\treqCmd = req;\n\n\t\tif (req->cmd == \"cmdset\") {\n\t\t\tcout << \"\\trerun\" << endl;\n\t\t\tcout << \"\\tshow\" << endl;\n\t\t} else if (req->cmd == \"rerun\") {\n\t\t\treq->retain = handleRerun(dbswzsk);\n\n\t\t} else if (req->cmd == \"show\") {\n\t\t\treq->retain = handleShow(dbswzsk);\n\n\t\t} else {\n\t\t\tcout << \"\\tinvalid command!\" << endl;\n\t\t};\n\n\t\tif (!req->retain) reqCmd = NULL;\n\n\t};\n};\n\nbool QryWzskShtRef1NFile::handleRerun(\n\t\t\tDbsWzsk* dbswzsk\n\t\t) {\n\tbool retval = false;\n\tstring input;\n\n\tcout << \"\\tjnumFirstload (\" << stgiac.jnumFirstload << \"): \";\n\tcin >> input;\n\tstgiac.jnumFirstload = atol(input.c_str());\n\tcout << \"\\tnload (\" << stgiac.nload << \"): \";\n\tcin >> input;\n\tstgiac.nload = atol(input.c_str());\n\n\trerun(dbswzsk);\n\treturn retval;\n};\n\nbool QryWzskShtRef1NFile::handleShow(\n\t\t\tDbsWzsk* dbswzsk\n\t\t) {\n\tbool retval = false;\n\tWzskQShtRef1NFile* rec = NULL;\n\n\t\/\/ header row\n\tcout << \"\\tqref\";\n\tcout << \"\\tjref\";\n\tcout << \"\\tjnum\";\n\tcout << \"\\tref\";\n\tcout << \"\\tstubRef\";\n\tcout << endl;\n\n\t\/\/ record rows\n\tfor (unsigned int i = 0; i < rst.nodes.size(); i++) {\n\t\trec = rst.nodes[i];\n\n\t\tcout << \"\\t\" << rec->qref;\n\t\tcout << \"\\t\" << rec->jref;\n\t\tcout << \"\\t\" << rec->jnum;\n\t\tcout << \"\\t\" << rec->ref;\n\t\tcout << \"\\t\" << rec->stubRef;\n\t\tcout << endl;\n\t};\n\treturn retval;\n};\n\nvoid QryWzskShtRef1NFile::handleCall(\n\t\t\tDbsWzsk* dbswzsk\n\t\t\t, Call* call\n\t\t) {\n\tif (call->ixVCall == VecWzskVCall::CALLWZSKFILMOD_RETREUEQ) {\n\t\tcall->abort = handleCallWzskFilMod_retReuEq(dbswzsk, call->jref);\n\t} else if ((call->ixVCall == VecWzskVCall::CALLWZSKSTUBCHG) && (call->jref == jref)) {\n\t\tcall->abort = handleCallWzskStubChgFromSelf(dbswzsk);\n\t};\n};\n\nbool QryWzskShtRef1NFile::handleCallWzskFilMod_retReuEq(\n\t\t\tDbsWzsk* dbswzsk\n\t\t\t, const ubigint jrefTrig\n\t\t) {\n\tbool retval = false;\n\n\tif (ixWzskVQrystate != VecWzskVQrystate::OOD) {\n\t\tixWzskVQrystate = VecWzskVQrystate::OOD;\n\t\txchg->triggerCall(dbswzsk, VecWzskVCall::CALLWZSKSTATCHG, jref);\n\t};\n\n\treturn retval;\n};\n\nbool QryWzskShtRef1NFile::handleCallWzskStubChgFromSelf(\n\t\t\tDbsWzsk* dbswzsk\n\t\t) {\n\tbool retval = false;\n\t\/\/ IP handleCallWzskStubChgFromSelf --- INSERT\n\treturn retval;\n};\n","avg_line_length":23.5346534653,"max_line_length":138,"alphanum_fraction":0.663160847,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11888,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1947.0,"content":"\/* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *  * Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  * Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *  * Neither the name of NVIDIA CORPORATION nor the names of its\n *    contributors may be used to endorse or promote products derived\n *    from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"render_particles.h\"\n\n#define HELPERGL_EXTERN_GL_FUNC_IMPLEMENTATION\n#include <helper_gl.h>\n\n#include <cuda_runtime.h>\n#include <cuda_gl_interop.h>\n\n#include <helper_cuda.h>\n\n#include <math.h>\n#include <assert.h>\n\n#define GL_POINT_SPRITE_ARB 0x8861\n#define GL_COORD_REPLACE_ARB 0x8862\n#define GL_VERTEX_PROGRAM_POINT_SIZE_NV 0x8642\n\nParticleRenderer::ParticleRenderer()\n    : m_pos(0),\n      m_numParticles(0),\n      m_pointSize(1.0f),\n      m_spriteSize(2.0f),\n      m_vertexShader(0),\n      m_vertexShaderPoints(0),\n      m_pixelShader(0),\n      m_programPoints(0),\n      m_programSprites(0),\n      m_texture(0),\n      m_pbo(0),\n      m_vboColor(0),\n      m_bFp64Positions(false) {\n  _initGL();\n}\n\nParticleRenderer::~ParticleRenderer() { m_pos = 0; }\n\nvoid ParticleRenderer::resetPBO() { glDeleteBuffers(1, (GLuint *)&m_pbo); }\n\nvoid ParticleRenderer::setPositions(float *pos, int numParticles) {\n  m_pos = pos;\n  m_numParticles = numParticles;\n\n  if (!m_pbo) {\n    glGenBuffers(1, (GLuint *)&m_pbo);\n  }\n\n  glBindBuffer(GL_ARRAY_BUFFER, m_pbo);\n  glBufferData(GL_ARRAY_BUFFER, numParticles * 4 * sizeof(float), pos,\n               GL_STATIC_DRAW);\n  glBindBuffer(GL_ARRAY_BUFFER, 0);\n  SDK_CHECK_ERROR_GL();\n}\n\nvoid ParticleRenderer::setPositions(double *pos, int numParticles) {\n  m_bFp64Positions = true;\n  m_pos_fp64 = pos;\n  m_numParticles = numParticles;\n\n  if (!m_pbo) {\n    glGenBuffers(1, (GLuint *)&m_pbo);\n  }\n\n  glBindBuffer(GL_ARRAY_BUFFER, m_pbo);\n  glBufferData(GL_ARRAY_BUFFER, numParticles * 4 * sizeof(double), pos,\n               GL_STATIC_DRAW);\n  glBindBuffer(GL_ARRAY_BUFFER, 0);\n  SDK_CHECK_ERROR_GL();\n}\n\nvoid ParticleRenderer::setColors(float *color, int numParticles) {\n  glBindBuffer(GL_ARRAY_BUFFER, m_vboColor);\n  glBufferData(GL_ARRAY_BUFFER, numParticles * 4 * sizeof(float), color,\n               GL_STATIC_DRAW);\n  glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n\nvoid ParticleRenderer::setBaseColor(float color[4]) {\n  for (int i = 0; i < 4; i++) m_baseColor[i] = color[i];\n}\n\nvoid ParticleRenderer::setPBO(unsigned int pbo, int numParticles, bool fp64) {\n  m_pbo = pbo;\n  m_numParticles = numParticles;\n\n  if (fp64) m_bFp64Positions = true;\n}\n\nvoid ParticleRenderer::_drawPoints(bool color) {\n  if (!m_pbo) {\n    glBegin(GL_POINTS);\n    {\n      int k = 0;\n\n      for (int i = 0; i < m_numParticles; ++i) {\n        if (m_bFp64Positions)\n          glVertex3dv(&m_pos_fp64[k]);\n        else {\n          glVertex3fv(&m_pos[k]);\n        }\n\n        k += 4;\n      }\n    }\n    glEnd();\n  } else {\n    glEnableClientState(GL_VERTEX_ARRAY);\n\n    glBindBuffer(GL_ARRAY_BUFFER, m_pbo);\n\n    if (m_bFp64Positions)\n      glVertexPointer(4, GL_DOUBLE, 0, 0);\n    else\n      glVertexPointer(4, GL_FLOAT, 0, 0);\n\n    if (color) {\n      glEnableClientState(GL_COLOR_ARRAY);\n      glBindBuffer(GL_ARRAY_BUFFER, m_vboColor);\n      \/\/ glActiveTexture(GL_TEXTURE1);\n      \/\/ glTexCoordPointer(4, GL_FLOAT, 0, 0);\n      glColorPointer(4, GL_FLOAT, 0, 0);\n    }\n\n    glDrawArrays(GL_POINTS, 0, m_numParticles);\n    glBindBuffer(GL_ARRAY_BUFFER, 0);\n    glDisableClientState(GL_VERTEX_ARRAY);\n    glDisableClientState(GL_COLOR_ARRAY);\n  }\n}\n\nvoid ParticleRenderer::display(DisplayMode mode \/* = PARTICLE_POINTS *\/) {\n  switch (mode) {\n    case PARTICLE_POINTS:\n      glColor3f(1, 1, 1);\n      glPointSize(m_pointSize);\n      glUseProgram(m_programPoints);\n      _drawPoints();\n      glUseProgram(0);\n      break;\n\n    case PARTICLE_SPRITES:\n    default: {\n      \/\/ setup point sprites\n      glEnable(GL_POINT_SPRITE_ARB);\n      glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);\n      glEnable(GL_VERTEX_PROGRAM_POINT_SIZE_NV);\n      glPointSize(m_spriteSize);\n      glBlendFunc(GL_SRC_ALPHA, GL_ONE);\n      glEnable(GL_BLEND);\n      glDepthMask(GL_FALSE);\n\n      glUseProgram(m_programSprites);\n      GLuint texLoc = glGetUniformLocation(m_programSprites, \"splatTexture\");\n      glUniform1i(texLoc, 0);\n\n      glActiveTexture(GL_TEXTURE0);\n      glBindTexture(GL_TEXTURE_2D, m_texture);\n\n      glColor3f(1, 1, 1);\n      glSecondaryColor3fv(m_baseColor);\n\n      _drawPoints();\n\n      glUseProgram(0);\n\n      glDisable(GL_POINT_SPRITE_ARB);\n      glDisable(GL_BLEND);\n      glDepthMask(GL_TRUE);\n    }\n\n    break;\n\n    case PARTICLE_SPRITES_COLOR: {\n      \/\/ setup point sprites\n      glEnable(GL_POINT_SPRITE_ARB);\n      glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);\n      glEnable(GL_VERTEX_PROGRAM_POINT_SIZE_NV);\n      glPointSize(m_spriteSize);\n      glBlendFunc(GL_SRC_ALPHA, GL_ONE);\n      glEnable(GL_BLEND);\n      glDepthMask(GL_FALSE);\n\n      glUseProgram(m_programSprites);\n      GLuint texLoc = glGetUniformLocation(m_programSprites, \"splatTexture\");\n      glUniform1i(texLoc, 0);\n\n      glActiveTexture(GL_TEXTURE0);\n      glBindTexture(GL_TEXTURE_2D, m_texture);\n\n      glColor3f(1, 1, 1);\n      glSecondaryColor3fv(m_baseColor);\n\n      _drawPoints(true);\n\n      glUseProgram(0);\n\n      glDisable(GL_POINT_SPRITE_ARB);\n      glDisable(GL_BLEND);\n      glDepthMask(GL_TRUE);\n    }\n\n    break;\n  }\n\n  SDK_CHECK_ERROR_GL();\n}\n\nconst char vertexShaderPoints[] = {\n    \"void main()                                                            \\n\"\n    \"{                                                                      \\n\"\n    \"    vec4 vert = vec4(gl_Vertex.xyz, 1.0);  \t\t\t       \"\n    \" \"\n    \"              \\n\"\n    \"    gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * vert;        \"\n    \"                   \\n\"\n    \"    gl_FrontColor = gl_Color;                                          \\n\"\n    \"}                                                                      \"\n    \"\\n\"};\n\nconst char vertexShader[] = {\n    \"void main()                                                            \\n\"\n    \"{                                                                      \\n\"\n    \"    float pointSize = 500.0 * gl_Point.size;                           \\n\"\n    \"    vec4 vert = gl_Vertex;\t\t\t\t\t\t\"\n    \"\t\t\t\t\t\t\\n\"\n    \"    vert.w = 1.0;\t\t\t\t\t\t\t\"\n    \"\t\"\n    \"\t\t\t\t\t\t\\n\"\n    \"    vec3 pos_eye = vec3 (gl_ModelViewMatrix * vert);                   \\n\"\n    \"    gl_PointSize = max(1.0, pointSize \/ (1.0 - pos_eye.z));            \\n\"\n    \"    gl_TexCoord[0] = gl_MultiTexCoord0;                                \\n\"\n    \/\/\"    gl_TexCoord[1] = gl_MultiTexCoord1; \\n\"\n    \"    gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * vert;     \\n\"\n    \"    gl_FrontColor = gl_Color;                                          \\n\"\n    \"    gl_FrontSecondaryColor = gl_SecondaryColor;                        \\n\"\n    \"}                                                                      \"\n    \"\\n\"};\n\nconst char pixelShader[] = {\n    \"uniform sampler2D splatTexture;                                        \\n\"\n\n    \"void main()                                                            \\n\"\n    \"{                                                                      \\n\"\n    \"    vec4 color2 = gl_SecondaryColor;                                   \\n\"\n    \"    vec4 color = (0.6 + 0.4 * gl_Color) * texture2D(splatTexture, \"\n    \"gl_TexCoord[0].st); \\n\"\n    \"    gl_FragColor =                                                     \\n\"\n    \"         color * color2;\\n\"  \/\/ mix(vec4(0.1, 0.0, 0.0, color.w), color2,\n                                  \/\/ color.w);\\n\"\n    \"}                                                                      \"\n    \"\\n\"};\n\nvoid ParticleRenderer::_initGL() {\n  m_vertexShader = glCreateShader(GL_VERTEX_SHADER);\n  m_vertexShaderPoints = glCreateShader(GL_VERTEX_SHADER);\n  m_pixelShader = glCreateShader(GL_FRAGMENT_SHADER);\n\n  const char *v = vertexShader;\n  const char *p = pixelShader;\n  glShaderSource(m_vertexShader, 1, &v, 0);\n  glShaderSource(m_pixelShader, 1, &p, 0);\n  const char *vp = vertexShaderPoints;\n  glShaderSource(m_vertexShaderPoints, 1, &vp, 0);\n\n  glCompileShader(m_vertexShader);\n  glCompileShader(m_vertexShaderPoints);\n  glCompileShader(m_pixelShader);\n\n  m_programSprites = glCreateProgram();\n  glAttachShader(m_programSprites, m_vertexShader);\n  glAttachShader(m_programSprites, m_pixelShader);\n  glLinkProgram(m_programSprites);\n\n  m_programPoints = glCreateProgram();\n  glAttachShader(m_programPoints, m_vertexShaderPoints);\n  glLinkProgram(m_programPoints);\n\n  _createTexture(32);\n\n  glGenBuffers(1, (GLuint *)&m_vboColor);\n  glBindBuffer(GL_ARRAY_BUFFER, m_vboColor);\n  glBufferData(GL_ARRAY_BUFFER, m_numParticles * 4 * sizeof(float), 0,\n               GL_STATIC_DRAW);\n  glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Function           : EvalHermite\n\/\/ Description      :\n\/\/------------------------------------------------------------------------------\n\/**\n* EvalHermite(float pA, float pB, float vA, float vB, float u)\n* @brief Evaluates Hermite basis functions for the specified coefficients.\n*\/\ninline float evalHermite(float pA, float pB, float vA, float vB, float u) {\n  float u2 = (u * u), u3 = u2 * u;\n  float B0 = 2 * u3 - 3 * u2 + 1;\n  float B1 = -2 * u3 + 3 * u2;\n  float B2 = u3 - 2 * u2 + u;\n  float B3 = u3 - u;\n  return (B0 * pA + B1 * pB + B2 * vA + B3 * vB);\n}\n\nunsigned char *createGaussianMap(int N) {\n  float *M = new float[2 * N * N];\n  unsigned char *B = new unsigned char[4 * N * N];\n  float X, Y, Y2, Dist;\n  float Incr = 2.0f \/ N;\n  int i = 0;\n  int j = 0;\n  Y = -1.0f;\n\n  \/\/ float mmax = 0;\n  for (int y = 0; y < N; y++, Y += Incr) {\n    Y2 = Y * Y;\n    X = -1.0f;\n\n    for (int x = 0; x < N; x++, X += Incr, i += 2, j += 4) {\n      Dist = (float)sqrtf(X * X + Y2);\n\n      if (Dist > 1) Dist = 1;\n\n      M[i + 1] = M[i] = evalHermite(1.0f, 0, 0, 0, Dist);\n      B[j + 3] = B[j + 2] = B[j + 1] = B[j] = (unsigned char)(M[i] * 255);\n    }\n  }\n\n  delete[] M;\n  return (B);\n}\n\nvoid ParticleRenderer::_createTexture(int resolution) {\n  unsigned char *data = createGaussianMap(resolution);\n  glGenTextures(1, (GLuint *)&m_texture);\n  glBindTexture(GL_TEXTURE_2D, m_texture);\n  glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);\n  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,\n                  GL_LINEAR_MIPMAP_LINEAR);\n  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, resolution, resolution, 0, GL_RGBA,\n               GL_UNSIGNED_BYTE, data);\n}\n","avg_line_length":32.216802168,"max_line_length":80,"alphanum_fraction":0.6012786003,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3112,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.\n\n#include \"DirectoryScanner.h\"\n#include \"GenericPlatform\/GenericPlatformFile.h\"\n#include \"Misc\/IQueuedWork.h\"\n#include \"Misc\/QueuedThreadPool.h\"\n\nTArray<FDirectoryScannerCommand*> FDirectoryScanner::CommandQueue;\n\nstruct FDirectoryResult\n{\n\tFDirectoryResult(const FString& InPathName, ECodeProjectItemType::Type InType)\n\t\t: PathName(InPathName)\n\t\t, Type(InType)\n\t{\n\t}\n\n\tFString PathName;\n\n\tECodeProjectItemType::Type Type;\n};\n\nstruct FDirectoryScannerCommand : public IQueuedWork\n{\n\tFDirectoryScannerCommand(const FString& InPathName, const FOnDirectoryScanned& InOnDirectoryScanned)\n\t\t: PathName(InPathName)\n\t\t, OnDirectoryScanned(InOnDirectoryScanned)\n\t\t, bExecuted(0)\n\t{\n\t}\n\n\t\/** Begin FQueuedWork interface *\/\n\tvirtual void Abandon() override\n\t{\n\t\tFPlatformAtomics::InterlockedExchange(&bExecuted, 1);\n\t}\n\n\tvirtual void DoThreadedWork() override\n\t{\n\t\tclass FDirectoryEnumerator : public IPlatformFile::FDirectoryVisitor\n\t\t{\n\t\tpublic:\n\t\t\tFDirectoryEnumerator(TLockFreePointerListUnordered<FDirectoryResult, PLATFORM_CACHE_LINE_SIZE>& InFoundFiles)\n\t\t\t\t: FoundFiles(InFoundFiles)\n\t\t\t{\n\t\t\t}\n\n\t\t\tvirtual bool Visit(const TCHAR* FilenameOrDirectory, bool bIsDirectory) override\n\t\t\t{\n\t\t\t\tif(bIsDirectory)\n\t\t\t\t{\n\t\t\t\t\tFoundFiles.Push(new FDirectoryResult(FilenameOrDirectory, ECodeProjectItemType::Folder));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tFoundFiles.Push(new FDirectoryResult(FilenameOrDirectory, ECodeProjectItemType::File));\n\t\t\t\t}\n\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tTLockFreePointerListUnordered<FDirectoryResult, PLATFORM_CACHE_LINE_SIZE>& FoundFiles;\n\t\t};\n\n\t\tFDirectoryEnumerator DirectoryEnumerator(FoundFiles);\n\t\tIPlatformFile& PlatformFile = IPlatformFile::GetPlatformPhysical();\n\t\tPlatformFile.IterateDirectory(*PathName, DirectoryEnumerator);\n\n\t\tFPlatformAtomics::InterlockedExchange(&bExecuted, 1);\n\t}\n\t\/** End FQueuedWork interface *\/\n\n\tFString PathName;\n\n\tFOnDirectoryScanned OnDirectoryScanned;\n\n\tTLockFreePointerListUnordered<FDirectoryResult, PLATFORM_CACHE_LINE_SIZE> FoundFiles;\n\n\tvolatile int32 bExecuted;\n};\n\n\nbool FDirectoryScanner::Tick()\n{\n\tbool bAddedData = false;\n\tfor (int32 CommandIndex = 0; CommandIndex < CommandQueue.Num(); ++CommandIndex)\n\t{\n\t\tFDirectoryScannerCommand& Command = *CommandQueue[CommandIndex];\n\t\tif (Command.bExecuted)\n\t\t{\n\t\t\twhile(!Command.FoundFiles.IsEmpty())\n\t\t\t{\n\t\t\t\tFDirectoryResult* DirectoryResult = Command.FoundFiles.Pop();\n\t\t\t\tCommand.OnDirectoryScanned.ExecuteIfBound(DirectoryResult->PathName, DirectoryResult->Type);\n\t\t\t\tdelete DirectoryResult;\n\t\t\t\tbAddedData = true;\n\t\t\t}\n\n\t\t\t\/\/ Remove command from the queue & delete it, we are done for this tick\n\t\t\tCommandQueue.RemoveAt(CommandIndex);\n\t\t\tdelete &Command;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn bAddedData;\n}\n\nvoid FDirectoryScanner::AddDirectory(const FString& PathName, const FOnDirectoryScanned& OnDirectoryScanned)\n{\n\tFDirectoryScannerCommand* NewCommand = new FDirectoryScannerCommand(PathName, OnDirectoryScanned);\n\tCommandQueue.Add(NewCommand);\n\tGThreadPool->AddQueuedWork(NewCommand);\n}\n\nbool FDirectoryScanner::IsScanning()\n{\n\treturn CommandQueue.Num() > 0;\n}\n","avg_line_length":25.9333333333,"max_line_length":112,"alphanum_fraction":0.7721722365,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":23786,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":21.0,"content":"\/\/ Test host codegen.\n\/\/ RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fomptargets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck %s\n\/\/ RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fomptargets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s\n\/\/ RUN: %clang_cc1 -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fomptargets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s\n\/\/ RUN: %clang_cc1 -verify -fopenmp -x c++ -triple i386-unknown-unknown -fomptargets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s\n\/\/ RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple i386-unknown-unknown -fomptargets=i386-pc-linux-gnu -emit-pch -o %t %s\n\/\/ RUN: %clang_cc1 -fopenmp -x c++ -triple i386-unknown-unknown -fomptargets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s\n\n\/\/ Test target codegen - host bc file has to be created first.\n\/\/ RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fomptargets=powerpc64le-ibm-linux-gnu -emit-llvm-bc %s -o %t-ppc-host.bc\n\/\/ RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fomptargets=powerpc64le-ibm-linux-gnu -emit-llvm %s -fopenmp-is-device -fomp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s -check-prefix=TCHECK\n\/\/ RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fomptargets=powerpc64le-ibm-linux-gnu -emit-pch -fopenmp-is-device -fomp-host-ir-file-path %t-ppc-host.bc -o %t %s\n\/\/ RUN: %clang_cc1 -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fomptargets=powerpc64le-ibm-linux-gnu -std=c++11 -fopenmp-is-device -fomp-host-ir-file-path %t-ppc-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s -check-prefix=TCHECK\n\/\/ RUN: %clang_cc1 -verify -fopenmp -x c++ -triple i386-unknown-unknown -fomptargets=i386-pc-linux-gnu -emit-llvm-bc %s -o %t-x86-host.bc\n\/\/ RUN: %clang_cc1 -verify -fopenmp -x c++ -triple i386-unknown-unknown -fomptargets=i386-pc-linux-gnu -emit-llvm %s -fopenmp-is-device -fomp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s -check-prefix=TCHECK\n\/\/ RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple i386-unknown-unknown -fomptargets=i386-pc-linux-gnu -emit-pch -fopenmp-is-device -fomp-host-ir-file-path %t-x86-host.bc -o %t %s\n\/\/ RUN: %clang_cc1 -fopenmp -x c++ -triple i386-unknown-unknown -fomptargets=i386-pc-linux-gnu -std=c++11 -fopenmp-is-device -fomp-host-ir-file-path %t-x86-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s -check-prefix=TCHECK\n\n\/\/ Check that no target code is emmitted if no omptests flag was provided.\n\/\/ RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK-NTARGET\n\n\/\/ expected-no-diagnostics\n#ifndef HEADER\n#define HEADER\n\n\/\/ CHECK-DAG: [[SA:%.+]] = type { [4 x i32] }\n\/\/ CHECK-DAG: [[SB:%.+]] = type { [8 x i32] }\n\/\/ CHECK-DAG: [[SC:%.+]] = type { [16 x i32] }\n\/\/ CHECK-DAG: [[SD:%.+]] = type { [32 x i32] }\n\/\/ CHECK-DAG: [[SE:%.+]] = type { [64 x i32] }\n\/\/ CHECK-DAG: [[ST1:%.+]] = type { [228 x i32] }\n\/\/ CHECK-DAG: [[ST2:%.+]] = type { [1128 x i32] }\n\/\/ CHECK-DAG: [[ENTTY:%.+]] = type { i8*, i8*, i[[SZ:32|64]] }\n\/\/ CHECK-DAG: [[DEVTY:%.+]] = type { i8*, i8*, [[ENTTY]]*, [[ENTTY]]* }\n\/\/ CHECK-DAG: [[DSCTY:%.+]] = type { i32, [[DEVTY]]*, [[ENTTY]]*, [[ENTTY]]* }\n\n\/\/ TCHECK:    [[ENTTY:%.+]] = type { i8*, i8*, i[[SZ:32|64]] }\n\n\/\/ CHECK-DAG: [[A1:@.+]] = internal global [[SA]]\n\/\/ CHECK-DAG: [[A2:@.+]] = global [[SA]]\n\/\/ CHECK-DAG: [[B1:@.+]] = global [[SB]]\n\/\/ CHECK-DAG: [[B2:@.+]] = global [[SB]]\n\/\/ CHECK-DAG: [[C1:@.+]] = internal global [[SC]]\n\/\/ CHECK-DAG: [[D1:@.+]] = global [[SD]]\n\/\/ CHECK-DAG: [[E1:@.+]] = global [[SE]]\n\/\/ CHECK-DAG: [[T1:@.+]] = global [[ST1]]\n\/\/ CHECK-DAG: [[T2:@.+]] = global [[ST2]]\n\n\/\/ CHECK-NTARGET-DAG: [[SA:%.+]] = type { [4 x i32] }\n\/\/ CHECK-NTARGET-DAG: [[SB:%.+]] = type { [8 x i32] }\n\/\/ CHECK-NTARGET-DAG: [[SC:%.+]] = type { [16 x i32] }\n\/\/ CHECK-NTARGET-DAG: [[SD:%.+]] = type { [32 x i32] }\n\/\/ CHECK-NTARGET-DAG: [[SE:%.+]] = type { [64 x i32] }\n\/\/ CHECK-NTARGET-DAG: [[ST1:%.+]] = type { [228 x i32] }\n\/\/ CHECK-NTARGET-DAG: [[ST2:%.+]] = type { [1128 x i32] }\n\/\/ CHECK-NTARGET-NOT: type { i8*,\n\/\/ CHECK-NTARGET-NOT: type { i32,\n\n\/\/ We have 7 target regions\n\n\/\/ CHECK-DAG: {{@.+}} = private constant i8 0\n\/\/ TCHECK-NOT: {{@.+}} = private constant i8 0\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 128]\n\/\/ CHECK-DAG: {{@.+}} = private constant i8 0\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 128]\n\/\/ CHECK-DAG: {{@.+}} = private constant i8 0\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 128]\n\/\/ CHECK-DAG: {{@.+}} = private constant i8 0\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 128]\n\/\/ CHECK-DAG: {{@.+}} = private constant i8 0\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 128]\n\/\/ CHECK-DAG: {{@.+}} = private constant i8 0\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 128]\n\/\/ CHECK-DAG: {{@.+}} = private constant i8 0\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 128]\n\/\/ CHECK-DAG: {{@.+}} = private constant i8 0\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 128]\n\/\/ CHECK-DAG: {{@.+}} = private constant i8 0\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 128]\n\/\/ CHECK-DAG: {{@.+}} = private constant i8 0\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 128]\n\/\/ CHECK-DAG: {{@.+}} = private constant i8 0\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 128]\n\/\/ CHECK-DAG: {{@.+}} = private constant i8 0\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]\n\/\/ CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 128]\n\n\/\/ CHECK-NTARGET-NOT: private constant i8 0\n\/\/ CHECK-NTARGET-NOT: private unnamed_addr constant [1 x i\n\n\/\/ CHECK-DAG: [[NAMEPTR1:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME1:__omp_offloading_[0-9a-f]+_[0-9a-f]+__Z.+_l[0-9]+]]\\00\"\n\/\/ CHECK-DAG: [[ENTRY1:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR1]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ CHECK-DAG: [[NAMEPTR2:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME2:.+]]\\00\"\n\/\/ CHECK-DAG: [[ENTRY2:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR2]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ CHECK-DAG: [[NAMEPTR3:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME3:.+]]\\00\"\n\/\/ CHECK-DAG: [[ENTRY3:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR3]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ CHECK-DAG: [[NAMEPTR4:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME4:.+]]\\00\"\n\/\/ CHECK-DAG: [[ENTRY4:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR4]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ CHECK-DAG: [[NAMEPTR5:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME5:.+]]\\00\"\n\/\/ CHECK-DAG: [[ENTRY5:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR5]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ CHECK-DAG: [[NAMEPTR6:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME6:.+]]\\00\"\n\/\/ CHECK-DAG: [[ENTRY6:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR6]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ CHECK-DAG: [[NAMEPTR7:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME7:.+]]\\00\"\n\/\/ CHECK-DAG: [[ENTRY7:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR7]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ CHECK-DAG: [[NAMEPTR8:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME8:.+]]\\00\"\n\/\/ CHECK-DAG: [[ENTRY8:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR8]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ CHECK-DAG: [[NAMEPTR9:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME9:.+]]\\00\"\n\/\/ CHECK-DAG: [[ENTRY9:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR9]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ CHECK-DAG: [[NAMEPTR10:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME10:.+]]\\00\"\n\/\/ CHECK-DAG: [[ENTRY10:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR10]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ CHECK-DAG: [[NAMEPTR11:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME11:.+]]\\00\"\n\/\/ CHECK-DAG: [[ENTRY11:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR11]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ CHECK-DAG: [[NAMEPTR12:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME12:.+]]\\00\"\n\/\/ CHECK-DAG: [[ENTRY12:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR12]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\n\/\/ TCHECK-DAG: [[NAMEPTR1:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME1:__omp_offloading_[0-9a-f]+_[0-9a-f]+__Z.+_l[0-9]+]]\\00\"\n\/\/ TCHECK-DAG: [[ENTRY1:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR1]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ TCHECK-DAG: [[NAMEPTR2:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME2:.+]]\\00\"\n\/\/ TCHECK-DAG: [[ENTRY2:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR2]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ TCHECK-DAG: [[NAMEPTR3:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME3:.+]]\\00\"\n\/\/ TCHECK-DAG: [[ENTRY3:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR3]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ TCHECK-DAG: [[NAMEPTR4:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME4:.+]]\\00\"\n\/\/ TCHECK-DAG: [[ENTRY4:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR4]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ TCHECK-DAG: [[NAMEPTR5:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME5:.+]]\\00\"\n\/\/ TCHECK-DAG: [[ENTRY5:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR5]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ TCHECK-DAG: [[NAMEPTR6:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME6:.+]]\\00\"\n\/\/ TCHECK-DAG: [[ENTRY6:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR6]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ TCHECK-DAG: [[NAMEPTR7:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME7:.+]]\\00\"\n\/\/ TCHECK-DAG: [[ENTRY7:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR7]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ TCHECK-DAG: [[NAMEPTR8:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME8:.+]]\\00\"\n\/\/ TCHECK-DAG: [[ENTRY8:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR8]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ TCHECK-DAG: [[NAMEPTR9:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME9:.+]]\\00\"\n\/\/ TCHECK-DAG: [[ENTRY9:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR9]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ TCHECK-DAG: [[NAMEPTR10:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME10:.+]]\\00\"\n\/\/ TCHECK-DAG: [[ENTRY10:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR10]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ TCHECK-DAG: [[NAMEPTR11:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME11:.+]]\\00\"\n\/\/ TCHECK-DAG: [[ENTRY11:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR11]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\/\/ TCHECK-DAG: [[NAMEPTR12:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c\"[[NAME12:.+]]\\00\"\n\/\/ TCHECK-DAG: [[ENTRY12:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR12]], i32 0, i32 0), i[[SZ]] 0 }, section \".omp_offloading.entries\", align 1\n\n\/\/ CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]]\n\/\/ CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]]\n\/\/ CHECK: [[DEVBEGIN:@.+]] = external constant i8\n\/\/ CHECK: [[DEVEND:@.+]] = external constant i8\n\/\/ CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }]\n\/\/ CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }\n\n\/\/ We have 4 initializers, one for the 500 priority, another one for 501, or more for the default priority, and the last one for the offloading registration function.\n\/\/ CHECK: @llvm.global_ctors = appending global [4 x { i32, void ()*, i8* }] [\n\/\/ CHECK-SAME: { i32, void ()*, i8* } { i32 500, void ()* [[P500:@[^,]+]], i8* null },\n\/\/ CHECK-SAME: { i32, void ()*, i8* } { i32 501, void ()* [[P501:@[^,]+]], i8* null },\n\/\/ CHECK-SAME: { i32, void ()*, i8* } { i32 65535, void ()* [[PMAX:@[^,]+]], i8* null },\n\/\/ CHECK-SAME: { i32, void ()*, i8* } { i32 0, void ()* bitcast (void (i8*)* [[REGFN:@.+]] to void ()*), i8* null }]\n\n\/\/ CHECK-NTARGET: @llvm.global_ctors = appending global [3   x { i32, void ()*, i8* }] [\n\nextern int *R;\n\nstruct SA {\n  int arr[4];\n  void foo() {\n    int a = *R;\n    a += 1;\n    *R = a;\n  }\n  SA() {\n    int a = *R;\n    a += 2;\n    *R = a;\n  }\n  ~SA() {\n    int a = *R;\n    a += 3;\n    *R = a;\n  }\n};\n\nstruct SB {\n  int arr[8];\n  void foo() {\n    int a = *R;\n    #pragma omp target\n    a += 4;\n    *R = a;\n  }\n  SB() {\n    int a = *R;\n    a += 5;\n    *R = a;\n  }\n  ~SB() {\n    int a = *R;\n    a += 6;\n    *R = a;\n  }\n};\n\nstruct SC {\n  int arr[16];\n  void foo() {\n    int a = *R;\n    a += 7;\n    *R = a;\n  }\n  SC() {\n    int a = *R;\n    #pragma omp target\n    a += 8;\n    *R = a;\n  }\n  ~SC() {\n    int a = *R;\n    a += 9;\n    *R = a;\n  }\n};\n\nstruct SD {\n  int arr[32];\n  void foo() {\n    int a = *R;\n    a += 10;\n    *R = a;\n  }\n  SD() {\n    int a = *R;\n    a += 11;\n    *R = a;\n  }\n  ~SD() {\n    int a = *R;\n    #pragma omp target\n    a += 12;\n    *R = a;\n  }\n};\n\nstruct SE {\n  int arr[64];\n  void foo() {\n    int a = *R;\n    #pragma omp target if(0)\n    a += 13;\n    *R = a;\n  }\n  SE() {\n    int a = *R;\n    #pragma omp target\n    a += 14;\n    *R = a;\n  }\n  ~SE() {\n    int a = *R;\n    #pragma omp target\n    a += 15;\n    *R = a;\n  }\n};\n\ntemplate <int x>\nstruct ST {\n  int arr[128 + x];\n  void foo() {\n    int a = *R;\n    #pragma omp target\n    a += 16 + x;\n    *R = a;\n  }\n  ST() {\n    int a = *R;\n    #pragma omp target\n    a += 17 + x;\n    *R = a;\n  }\n  ~ST() {\n    int a = *R;\n    #pragma omp target\n    a += 18 + x;\n    *R = a;\n  }\n};\n\n\/\/ We have to make sure we us all the target regions:\n\/\/CHECK-DAG: define internal void @[[NAME1]](\n\/\/CHECK-DAG: call void @[[NAME1]](\n\/\/CHECK-DAG: define internal void @[[NAME2]](\n\/\/CHECK-DAG: call void @[[NAME2]](\n\/\/CHECK-DAG: define internal void @[[NAME3]](\n\/\/CHECK-DAG: call void @[[NAME3]](\n\/\/CHECK-DAG: define internal void @[[NAME4]](\n\/\/CHECK-DAG: call void @[[NAME4]](\n\/\/CHECK-DAG: define internal void @[[NAME5]](\n\/\/CHECK-DAG: call void @[[NAME5]](\n\/\/CHECK-DAG: define internal void @[[NAME6]](\n\/\/CHECK-DAG: call void @[[NAME6]](\n\/\/CHECK-DAG: define internal void @[[NAME7]](\n\/\/CHECK-DAG: call void @[[NAME7]](\n\/\/CHECK-DAG: define internal void @[[NAME8]](\n\/\/CHECK-DAG: call void @[[NAME8]](\n\/\/CHECK-DAG: define internal void @[[NAME9]](\n\/\/CHECK-DAG: call void @[[NAME9]](\n\/\/CHECK-DAG: define internal void @[[NAME10]](\n\/\/CHECK-DAG: call void @[[NAME10]](\n\/\/CHECK-DAG: define internal void @[[NAME11]](\n\/\/CHECK-DAG: call void @[[NAME11]](\n\/\/CHECK-DAG: define internal void @[[NAME12]](\n\/\/CHECK-DAG: call void @[[NAME12]](\n\n\/\/TCHECK-DAG: define void @[[NAME1]](\n\/\/TCHECK-DAG: define void @[[NAME2]](\n\/\/TCHECK-DAG: define void @[[NAME3]](\n\/\/TCHECK-DAG: define void @[[NAME4]](\n\/\/TCHECK-DAG: define void @[[NAME5]](\n\/\/TCHECK-DAG: define void @[[NAME6]](\n\/\/TCHECK-DAG: define void @[[NAME7]](\n\/\/TCHECK-DAG: define void @[[NAME8]](\n\/\/TCHECK-DAG: define void @[[NAME9]](\n\/\/TCHECK-DAG: define void @[[NAME10]](\n\/\/TCHECK-DAG: define void @[[NAME11]](\n\/\/TCHECK-DAG: define void @[[NAME12]](\n\n\/\/ CHECK-NTARGET-NOT: __tgt_target\n\/\/ CHECK-NTARGET-NOT: __tgt_register_lib\n\/\/ CHECK-NTARGET-NOT: __tgt_unregister_lib\n\n\/\/ TCHECK-NOT: __tgt_target\n\/\/ TCHECK-NOT: __tgt_register_lib\n\/\/ TCHECK-NOT: __tgt_unregister_lib\n\n\/\/ We have 2 initializers with priority 500\n\/\/CHECK: define internal void [[P500]](\n\/\/CHECK:     call void @{{.+}}()\n\/\/CHECK:     call void @{{.+}}()\n\/\/CHECK-NOT: call void @{{.+}}()\n\/\/CHECK:     ret void\n\n\/\/ We have 1 initializers with priority 501\n\/\/CHECK: define internal void [[P501]](\n\/\/CHECK:     call void @{{.+}}()\n\/\/CHECK-NOT: call void @{{.+}}()\n\/\/CHECK:     ret void\n\n\/\/ We have 6 initializers with default priority\n\/\/CHECK: define internal void [[PMAX]](\n\/\/CHECK:     call void @{{.+}}()\n\/\/CHECK:     call void @{{.+}}()\n\/\/CHECK:     call void @{{.+}}()\n\/\/CHECK:     call void @{{.+}}()\n\/\/CHECK:     call void @{{.+}}()\n\/\/CHECK:     call void @{{.+}}()\n\/\/CHECK-NOT: call void @{{.+}}()\n\/\/CHECK:     ret void\n\n\/\/ Check registration and unregistration\n\n\/\/CHECK:     define internal void [[UNREGFN:@.+]](i8*)\n\/\/CHECK:     call i32 @__tgt_unregister_lib([[DSCTY]]* [[DESC]])\n\/\/CHECK:     ret void\n\/\/CHECK:     declare i32 @__tgt_unregister_lib([[DSCTY]]*)\n\n\/\/CHECK:     define internal void [[REGFN]](i8*)\n\/\/CHECK:     call i32 @__tgt_register_lib([[DSCTY]]* [[DESC]])\n\/\/CHECK:     call i32 @__cxa_atexit(void (i8*)* [[UNREGFN]], i8* bitcast ([[DSCTY]]* [[DESC]] to i8*),\n\/\/CHECK:     ret void\n\/\/CHECK:     declare i32 @__tgt_register_lib([[DSCTY]]*)\n\nstatic __attribute__((init_priority(500))) SA a1;\nSA a2;\nSB __attribute__((init_priority(500))) b1;\nSB __attribute__((init_priority(501))) b2;\nstatic SC c1;\nSD d1;\nSE e1;\nST<100> t1;\nST<1000> t2;\n\n\nint bar(int a){\n  int r = a;\n\n  a1.foo();\n  a2.foo();\n  b1.foo();\n  b2.foo();\n  c1.foo();\n  d1.foo();\n  e1.foo();\n  t1.foo();\n  t2.foo();\n\n  #pragma omp target\n  ++r;\n\n  return r + *R;\n}\n\n\/\/ Check metadata is properly generated:\n\/\/ CHECK:     !omp_offload.info = !{!{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}}\n\/\/ CHECK-DAG: = !{i32 0, i32 [[DEVID:-?[0-9]+]], i32 [[FILEID:-?[0-9]+]], !\"_ZN2SB3fooEv\", i32 193, i32 {{[0-9]+}}}\n\/\/ CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2SDD1Ev\", i32 243, i32 {{[0-9]+}}}\n\/\/ CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2SEC1Ev\", i32 259, i32 {{[0-9]+}}}\n\/\/ CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2SED1Ev\", i32 265, i32 {{[0-9]+}}}\n\/\/ CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2STILi1000EE3fooEv\", i32 276, i32 {{[0-9]+}}}\n\/\/ CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2STILi100EEC1Ev\", i32 282, i32 {{[0-9]+}}}\n\/\/ CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_Z3bari\", i32 402, i32 {{[0-9]+}}}\n\/\/ CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2STILi100EED1Ev\", i32 288, i32 {{[0-9]+}}}\n\/\/ CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2STILi1000EEC1Ev\", i32 282, i32 {{[0-9]+}}}\n\/\/ CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2STILi1000EED1Ev\", i32 288, i32 {{[0-9]+}}}\n\/\/ CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2STILi100EE3fooEv\", i32 276, i32 {{[0-9]+}}}\n\/\/ CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2SCC1Ev\", i32 218, i32 {{[0-9]+}}}\n\n\/\/ TCHECK:     !omp_offload.info = !{!{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}}\n\/\/ TCHECK-DAG: = !{i32 0, i32 [[DEVID:-?[0-9]+]], i32 [[FILEID:-?[0-9]+]], !\"_ZN2SB3fooEv\", i32 193, i32 {{[0-9]+}}}\n\/\/ TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2SDD1Ev\", i32 243, i32 {{[0-9]+}}}\n\/\/ TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2SEC1Ev\", i32 259, i32 {{[0-9]+}}}\n\/\/ TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2SED1Ev\", i32 265, i32 {{[0-9]+}}}\n\/\/ TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2STILi1000EE3fooEv\", i32 276, i32 {{[0-9]+}}}\n\/\/ TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2STILi100EEC1Ev\", i32 282, i32 {{[0-9]+}}}\n\/\/ TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_Z3bari\", i32 402, i32 {{[0-9]+}}}\n\/\/ TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2STILi100EED1Ev\", i32 288, i32 {{[0-9]+}}}\n\/\/ TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2STILi1000EEC1Ev\", i32 282, i32 {{[0-9]+}}}\n\/\/ TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2STILi1000EED1Ev\", i32 288, i32 {{[0-9]+}}}\n\/\/ TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2STILi100EE3fooEv\", i32 276, i32 {{[0-9]+}}}\n\/\/ TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !\"_ZN2SCC1Ev\", i32 218, i32 {{[0-9]+}}}\n\n#endif\n","avg_line_length":54.3059360731,"max_line_length":257,"alphanum_fraction":0.5620112671,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3650,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n * FMS1Frame.cpp\n *\n *  Created on: Mar 11, 2018\n *      Author: famez\n *\/\n\n#include <string>\n#include <sstream>\n#include <iostream>\n\n#include <Utils.h>\n\n#include <FMS\/TellTale\/FMS1Frame.h>\n\n#define FMS1_NAME\t\t\t\t\"FMS1\"\n\nnamespace J1939 {\n\nFMS1Frame::FMS1Frame() : J1939Frame(FMS1_PGN), mBlockID(0) {\n\tmName = FMS1_NAME;\n\n}\n\n\nFMS1Frame::FMS1Frame(u8 blockID) : J1939Frame(FMS1_PGN), mBlockID(blockID) {\n\tmName = FMS1_NAME;\n\n\tfor(u8 i = mBlockID * TTSS_PER_BLOCK + 1; i < (mBlockID + 1) * TTSS_PER_BLOCK + 1; ++i) {\n\t\tmTTSs[i] = TellTale(i, TellTale::TTS_STATUS_NOT_AVAILABLE);\n\t}\n}\n\nFMS1Frame::~FMS1Frame() {\n}\n\nvoid FMS1Frame::decodeData(const u8* buffer, size_t length) {\n\n\tif(length != FMS1_FRAME_LENGTH) {\t\t\/\/Check the length first\n\t\tthrow  J1939DecodeException(\"[FMS1Frame::decodeData] Buffer length does \"\n\t\t\t\t\"not match the expected length. Buffer length:\" + std::to_string(length) + \". Expected length: \" + std::to_string(FMS1_FRAME_LENGTH));\n\t}\n\n\n\tmBlockID = buffer[0] & BLOCKID_MASK;\n\n\tu8 tts1Number = TTSS_PER_BLOCK * mBlockID + 1;\n\tTellTale tts1(tts1Number, (buffer[0] >> TTS_HIGH_PART_SHIFT) & TTS_MASK);\n\tmTTSs[tts1Number] = tts1;\n\n\tfor(unsigned int i = 1; i < FMS1_FRAME_LENGTH; ++i) {\n\t\tu8 ttsLowPartNumber = TTSS_PER_BLOCK * mBlockID + 2*i;\n\t\tu8 ttsHighPartNumber = TTSS_PER_BLOCK * mBlockID + 2*i + 1;\n\n\t\tu8 ttsLowPartStatus = buffer[i] & TTS_MASK;\n\t\tu8 ttsHighPartStatus = (buffer[i] >> TTS_HIGH_PART_SHIFT) & TTS_MASK;\n\n\t\tmTTSs[ttsLowPartNumber] = TellTale(ttsLowPartNumber, ttsLowPartStatus);\n\t\tmTTSs[ttsHighPartNumber] = TellTale(ttsHighPartNumber, ttsHighPartStatus);\n\n\t}\n\n\n\n}\n\nvoid FMS1Frame::encodeData(u8* buffer, size_t length) const {\n\n\t\/\/Not necessary to check length if getDataLength() returns the proper value as the base class will already do the check\n\n\tif(mTTSs.size() != TTSS_PER_BLOCK) {\t\t\/\/Check if we have the right number of TTSs.\n\t\tthrow  J1939EncodeException(\"[FMS1Frame::encodeData] There are not \" + std::to_string(TTSS_PER_BLOCK) + \" defined\");\n\t}\n\n\t\/\/Check if the number for every TTS is the right one.\n\tif(mTTSs.begin()->first <= mBlockID * TTSS_PER_BLOCK || mTTSs.rbegin()->first > (mBlockID + 1) * TTSS_PER_BLOCK) {\n\t\tthrow  J1939EncodeException(\"[FMS1Frame::encodeData] TTS numbers are not the proper ones for this block\");\n\t}\n\n\tu8 tts1Number = TTSS_PER_BLOCK * mBlockID + 1;\n\n\tbuffer[0] = (mBlockID & BLOCKID_MASK) | ((mTTSs.at(tts1Number).getStatus() | TTS_ENCODING_MASK) << TTS_HIGH_PART_SHIFT);\n\n\tfor(unsigned int i = 1; i < FMS1_FRAME_LENGTH; ++i) {\n\t\tu8 ttsLowPartNumber = TTSS_PER_BLOCK * mBlockID + 2*i;\n\t\tu8 ttsHighPartNumber = TTSS_PER_BLOCK * mBlockID + 2*i + 1;\n\n\t\tbuffer[i] = (mTTSs.at(ttsLowPartNumber).getStatus() | TTS_ENCODING_MASK) |\n\t\t\t\t((mTTSs.at(ttsHighPartNumber).getStatus() | TTS_ENCODING_MASK) << TTS_HIGH_PART_SHIFT);\n\t}\n\n}\n\nstd::string FMS1Frame::toString() {\n\n\tstd::string retVal = J1939Frame::toString();\n\n\tstd::stringstream sstr;\n\n\tsstr << \"Block ID: \" << static_cast<int>(mBlockID) << std::endl;\n\n\tfor(auto tts = mTTSs.begin(); tts != mTTSs.end(); ++tts) {\n\t\tsstr << tts->second.toString();\n\t}\n\n\treturn retVal + sstr.str();\n\n}\n\nbool FMS1Frame::hasTTS(u8 number) {\n\n\treturn (mTTSs.find(number) != mTTSs.end());\n\n}\n\n\nTellTale FMS1Frame::getTTS(u8 number) {\n\n\tauto iter = mTTSs.find(number);\n\n\tif(iter != mTTSs.end()) {\n\t\treturn iter->second;\n\t}\n\n\treturn TellTale(number, TellTale::TTS_STATUS_NOT_AVAILABLE);\n\n}\n\nbool FMS1Frame::setTTS(u8 number, u8 status) {\n\n\tauto iter = mTTSs.find(number);\n\n\t\/\/If tts number does not belong to FMS1 frame, the tts is not set\n\tif(iter != mTTSs.end()) {\n\t\titer->second = TellTale(number, status);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n}\n","avg_line_length":25.5244755245,"max_line_length":138,"alphanum_fraction":0.6980821918,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":827,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <bits\/stdc++.h>\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\nusing namespace std;\ntypedef long long ll;\nconst int MOD = 1E9 + 7;\nconst int INF = 1 << 29;\n\nint main() {\n  ll n, k;\n  cin >> n >> k;\n  vector<int> a(n);\n  rep(i, n) cin >> a[i];\n  int t = 1;\n  vector<ll> memo(n, -1);\n  vector<bool> reach(n, false);\n  int cnt = 0;\n  int min;\n  rep(i, n) {\n    if (reach[t - 1]) {\n      \/\/   cout << cnt << \"\u56de\u76ee\u306b\u5230\u9054\u3057\u305f\" << t << \"\u306f\" << memo[t - 1]\n      \/\/        << \"\u56de\u76ee\u306b\u3082\u5230\u9054\u3057\u3066\u3044\u308b\u3002\" << endl;\n      cnt -= memo[t - 1];\n      min = memo[t - 1];\n      break;\n    };\n    reach[t - 1] = true;\n    \n    memo[t - 1] = cnt;\n    t = a[t - 1];\n    cnt++;\n  }\n  \/\/   cout << min << \"\u56de\u76ee\u304b\u3089\" << cnt << \"\u56de\u3067\u30eb\u30fc\u30d7\u3059\u308b\" << endl;\n  t = 1;\n  if (k >= (min + cnt)) k = min + ((k - min) % cnt);\n  rep(i, k) { t = a[t - 1]; }\n  cout << t << endl;\n}","avg_line_length":22.3513513514,"max_line_length":62,"alphanum_fraction":0.4340991536,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1384,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/\/ BaseGridCtrl.cpp : implementation file\n\/\/\n\n#include \"stdafx.h\"\n#include \"BaseGridCtrl.h\"\n#include \"afxdialogex.h\"\n\n\n\/\/ CBaseGridCtrl dialog\n\nIMPLEMENT_DYNAMIC(CBaseGridCtrl, CDialogEx)\n\nCBaseGridCtrl::CBaseGridCtrl(CWnd* pParent \/*=NULL*\/)\n  : CDialogEx(CBaseGridCtrl::IDD, pParent)\n{\n\n}\n\nCBaseGridCtrl::~CBaseGridCtrl()\n{\n}\n\nvoid CBaseGridCtrl::DoDataExchange(CDataExchange* pDX)\n{\n  DDX_Control(pDX, IDC_VIEW_DATA_GRID, m_view_data_grid);\n\tCDialogEx::DoDataExchange(pDX);\n}\n\n\nBEGIN_MESSAGE_MAP(CBaseGridCtrl, CDialogEx)\n  ON_WM_SIZE()\nEND_MESSAGE_MAP()\n\n\n\/\/ CBaseGridCtrl message handlers\n\n\nvoid CBaseGridCtrl::OnSize(UINT nType, int cx, int cy)\n{\n  CDialogEx::OnSize(nType, cx, cy);\n\n  CRect rect;\n  GetClientRect(&rect);\n  \/\/ScreenToClient(&rect);\n  int space = 0;\n  rect.left -= space;\n  rect.right -= space;\n  rect.top -= space;\n  rect.bottom -= space;\n\n  if (m_view_data_grid.GetSafeHwnd())\n    m_view_data_grid.MoveWindow(rect);\n}\n\n\nBOOL CBaseGridCtrl::OnInitDialog()\n{\n  CDialogEx::OnInitDialog();\n\n  \/*\n  m_view_data_grid.SetColumnCount(4);\n  m_view_data_grid.SetRowCount(16);\n  m_view_data_grid.SetFixedRowCount(1);\n  m_view_data_grid.SetFixedColumnCount(1);\n\n  m_view_data_grid.SetEditable(false);\n  *\/\n  m_view_data_grid.ShowWindow(SW_SHOW);\n  return TRUE;  \/\/ return TRUE unless you set the focus to a control\n  \/\/ EXCEPTION: OCX Property Pages should return FALSE\n}\n","avg_line_length":19.2222222222,"max_line_length":68,"alphanum_fraction":0.7398843931,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3546,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"dllmain.h\"\r\n\n#include \"rule_set\/rule_set.hpp\"\r\n\r\n#ifndef Q_MOC_RUN \/\/ A Qt workaround, for those of you who use Qt\r\n#   include \"SimpleJSON\/parse\/jsd.hpp\"\r\n#   include \"SimpleJSON\/parse\/jsd_convenience.hpp\"\r\n#   include \"SimpleJSON\/stringify\/jss.hpp\"\r\n#   include \"SimpleJSON\/stringify\/jss_fusion_adapted_struct.hpp\"\r\n#endif\r\n\r\n#include \"rule_set\/rule\/selector.hpp\"\r\n\r\n#include \"windebug.hpp\"\r\n\n#include <cstring>\r\n#include <string>\r\n\r\n\/\/#####################################################################################################################\r\nstd::string lastError;\r\n\/\/#####################################################################################################################\r\nchar* allocateCString(std::string const& str)\r\n{\r\n    char* cstr = new char[str.length() + 1];\r\n    std::memcpy(cstr, str.c_str(), str.length());\r\n    cstr[str.length()] = '\\0';\r\n    return cstr;\r\n}\r\n\/\/---------------------------------------------------------------------------------------------------------------------\nextern \"C\" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE \/* hinstDLL *\/, DWORD \/* fdwReason *\/, LPVOID \/* lpvReserved *\/)\n{\r\n    return TRUE; \/\/ succesful\r\n}\r\n\/\/---------------------------------------------------------------------------------------------------------------------\nC_LINKAGE DLL_EXPORT void json_to_css(const char* json, char** css)\r\n{\r\n    *css = nullptr;\r\n    try\r\n    {\r\n        WretchedCss::RuleSet rules;\r\n        rules.fromJson(json);\r\n        auto cssString = rules.toCss();\r\n        *css = allocateCString(cssString);\r\n    }\r\n    catch (std::exception const& exc)\r\n    {\r\n        lastError = exc.what();\r\n        WretchedCss::DisplayError(exc);\r\n    }\r\n}\r\n\/\/---------------------------------------------------------------------------------------------------------------------\r\nC_LINKAGE DLL_EXPORT void css_to_json(const char* css, char** json)\r\n{\r\n    *json = nullptr;\r\n    try\r\n    {\r\n        WretchedCss::RuleSet rules{{css}};\r\n        auto jsonString = rules.toJson();\r\n        *json = allocateCString(jsonString);\r\n    }\r\n    catch (std::exception const& exc)\r\n    {\r\n        lastError = exc.what();\r\n        WretchedCss::DisplayError(exc);\r\n    }\r\n}\r\n\/\/---------------------------------------------------------------------------------------------------------------------\r\nC_LINKAGE DLL_EXPORT result_type selector_to_json(const char* selector, char** json)\r\n{\r\n    *json = nullptr;\r\n    try\r\n    {\r\n        WretchedCss::Selector stor(selector);\r\n        std::stringstream sstr;\r\n        sstr << '{';\r\n        JSON::stringify(sstr, \"selector\", stor, JSON::ProduceNamedOutput);\r\n        sstr << '}';\r\n        *json = allocateCString(sstr.str());\r\n        return 0;\r\n    }\r\n    catch (std::exception const& exc)\r\n    {\r\n        lastError = exc.what();\r\n        WretchedCss::DisplayError(exc);\r\n        return 1;\r\n    }\r\n}\r\n\/\/---------------------------------------------------------------------------------------------------------------------\nC_LINKAGE DLL_EXPORT void free_buffer(char* buffer)\r\n{\r\n    if (buffer != nullptr)\r\n        delete buffer;\r\n}\r\n\/\/---------------------------------------------------------------------------------------------------------------------\r\nC_LINKAGE DLL_EXPORT void get_last_error(char** error_message)\r\n{\r\n    if (!lastError.empty())\r\n        *error_message = allocateCString(lastError);\r\n    else\r\n        *error_message = nullptr;\r\n}\n\/\/#####################################################################################################################\n","avg_line_length":34.427184466,"max_line_length":120,"alphanum_fraction":0.4235758601,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4496,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n *  Copyright (c) 2016, The OpenThread Authors.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions are met:\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and\/or other materials provided with the distribution.\n *  3. Neither the name of the copyright holder nor the\n *     names of its contributors may be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n *   This file implements the CLI interpreter Instance related functions.\n *\/\n\n#include \"openthread-core-config.h\"\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include \"utils\/wrap_string.h\"\n\n#include <openthread\/openthread.h>\n\n#include \"cli.hpp\"\n\nnamespace ot {\n\nnamespace Cli {\n\n#ifdef OTDLL\nvoid Interpreter::CacheInstances()\n{\n    if (mApiInstance)\n    {\n        otDeviceList *aDeviceList = otEnumerateDevices(mApiInstance);\n        assert(aDeviceList);\n\n        mInstancesLength = aDeviceList->aDevicesLength > MAX_CLI_OT_INSTANCES ?\n                            MAX_CLI_OT_INSTANCES :\n                            (uint8_t)aDeviceList->aDevicesLength;\n\n        for (uint8_t i = 0; i < mInstancesLength; i++)\n        {\n            mInstances[i].mInterpreter = this;\n            mInstances[i].mInstance = otInstanceInit(mApiInstance, &aDeviceList->aDevices[i]);\n            assert(mInstances[i].mInstance);\n            otSetStateChangedCallback(mInstances[i].mInstance, &Interpreter::s_HandleNetifStateChanged, &mInstances[i]);\n        }\n\n        otFreeMemory(aDeviceList);\n\n        if (mInstancesLength > 0) { mInstance = mInstances[0].mInstance; }\n    }\n}\n\n#define GUID_FORMAT \"{%08lX-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX}\"\n#define GUID_ARG(guid) guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]\n\nvoid Interpreter::ProcessInstanceList(int argc, char *argv[])\n{\n    mServer->OutputFormat(\"%d instances found:\\r\\n\", mInstancesLength);\n\n    for (uint8_t i = 0; i < mInstancesLength; i++)\n    {\n        GUID aDeviceGuid = otGetDeviceGuid(mInstances[i].mInstance);\n        uint32_t aCompartment = otGetCompartmentId(mInstances[i].mInstance);\n        mServer->OutputFormat(\"[%d] \" GUID_FORMAT \" (Compartment %u)\\r\\n\",\n                              i, GUID_ARG(aDeviceGuid), aCompartment);\n    }\n}\n\nvoid Interpreter::ProcessInstance(int argc, char *argv[])\n{\n    otError error = OT_ERROR_NONE;\n    long value;\n\n    if (argc == 0)\n    {\n        if (mInstance == NULL)\n        {\n            mServer->OutputFormat(\"No Instance Set\\r\\n\");\n        }\n        else\n        {\n            GUID aDeviceGuid = otGetDeviceGuid(mInstance);\n            uint32_t aCompartment = otGetCompartmentId(mInstance);\n            mServer->OutputFormat(\"[%d] \" GUID_FORMAT \" (Compartment %u)\\r\\n\",\n                                  mInstanceIndex, GUID_ARG(aDeviceGuid), aCompartment);\n        }\n    }\n    else\n    {\n        SuccessOrExit(error = ParseLong(argv[0], value));\n        VerifyOrExit(value >= 0 && value < mInstancesLength, error = OT_ERROR_INVALID_ARGS);\n\n        mInstanceIndex = (uint8_t)value;\n        mInstance = mInstances[mInstanceIndex].mInstance;\n    }\n\nexit:\n    AppendResult(error);\n}\n#endif\n\n}  \/\/ namespace Cli\n}  \/\/ namespace ot\n","avg_line_length":35.6825396825,"max_line_length":177,"alphanum_fraction":0.6754893238,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":12648,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["NASA-1.3"],"max_stars_count":88.0,"content":"\/\/ ===============================================================================\n\/\/ Authors: AFRL\/RQQA\n\/\/ Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division\n\/\/ \n\/\/ Copyright (c) 2017 Government of the United State of America, as represented by\n\/\/ the Secretary of the Air Force.  No copyright is claimed in the United States under\n\/\/ Title 17, U.S. Code.  All Other Rights Reserved.\n\/\/ ===============================================================================\n\n#include \"UxAS_Time.h\"\n\n#include \"UxAS_Log.h\"\n\n#include <ctime>\n#include <iostream>\n#include <ratio>\n\n#define TIME_LOCAL_LOG_MESSAGE(message) std::cout << message << std::endl; std::cout.flush();\n\nnamespace uxas\n{\nnamespace common\n{\n\nTime::TimeMode Time::m_currentMode{Time::REAL_TIME};\nTime::TimeMode Time::m_desiredMode{Time::REAL_TIME};\nstd::unique_ptr<Time> Time::s_instance = nullptr;\n\nTime&\nTime::getInstance()\n{\n    \/\/ first time\/one time creation\n    if ((Time::s_instance == nullptr) || (m_currentMode != m_desiredMode))\n    {\n        switch (m_desiredMode)\n        {\n            case Time::DISCRETE_TIME:\n                s_instance.reset(new DiscreteTime);\n                break;\n            default:\n            case Time::REAL_TIME:\n                s_instance.reset(new Time);\n                break;\n        } \/\/switch(m_desiredMode)\n        m_currentMode = m_desiredMode;\n\n        s_instance->m_cpuStartTimeSinceEpoch_hr\n                = std::chrono::duration_cast<std::chrono::hours>\n                (std::chrono::system_clock::now().time_since_epoch()).count();\n        s_instance->m_cpuStartTimeSinceEpoch_min\n                = std::chrono::duration_cast<std::chrono::minutes>\n                (std::chrono::system_clock::now().time_since_epoch()).count();\n        s_instance->m_cpuStartTimeSinceEpoch_s\n                = std::chrono::duration_cast<std::chrono::seconds>\n                (std::chrono::system_clock::now().time_since_epoch()).count();\n        s_instance->m_cpuStartTimeSinceEpoch_ms\n                = std::chrono::duration_cast<std::chrono::milliseconds>\n                (std::chrono::system_clock::now().time_since_epoch()).count();\n        s_instance->m_cpuStartTimeSinceEpoch_us\n                = std::chrono::duration_cast<std::chrono::microseconds>\n                (std::chrono::system_clock::now().time_since_epoch()).count();\n        s_instance->m_cpuStartTimeSinceEpoch_ns\n                = std::chrono::duration_cast<std::chrono::nanoseconds>\n                (std::chrono::system_clock::now().time_since_epoch()).count();\n    }\n    return *s_instance;\n};\n\nbool\nTime::calibrateWithReferenceUtcTime(int year, int month, int day, int hour, int minutes, int seconds, int milliseconds)\n{\n    UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTime y, M, d, h, m, s, ms[\", year, \",\", month, \",\", day, \",\", hour, \",\", minutes, \",\", seconds, \",\", milliseconds, \"]\");\n    if (year < m_minimumCalibrationYear)\n    {\n        UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTime invalid year [\", year, \"]\");\n        return (false);\n    }\n    return (calibrateWithReferenceUtcTimeImpl(year, month, day, -1, hour, minutes, seconds, milliseconds));\n};\n\nbool\nTime::calibrateWithReferenceUtcTime(int year, int month, int day, int weeks, int milliseconds)\n{\n    UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTime y, M, d, weeks, ms[\", year, \",\", month, \",\", day, \",\", weeks, \",\", milliseconds, \"]\");\n    if (weeks < 0)\n    {\n        UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTime invalid weeks [\", weeks, \"]\");\n        return (false);\n    }\n    return (calibrateWithReferenceUtcTimeImpl(year, month, day, weeks, 0, 0, 0, milliseconds));\n};\n\nbool\nTime::calibrateWithReferenceUtcTimeImpl(int year, int month, int day, int weeks, int hour, int minutes, int seconds, int milliseconds)\n{\n    UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl - START\");\n\n    int64_t nowTimeSinceEpoch_ms = std::chrono::duration_cast<std::chrono::milliseconds>\n            (std::chrono::system_clock::now().time_since_epoch()).count();\n    UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl nowTimeSinceEpoch_ms [\", nowTimeSinceEpoch_ms, \"]\");\n\n    std::tm dateTm = {0};\n    dateTm.tm_isdst = -1;\n\n    dateTm.tm_year = year - 1900; \/\/ year since 1900\n    std::time_t tmtNow = std::time(nullptr);\n#ifdef _WIN32\n    std::tm tmNow;\n    gmtime_s(&tmNow, &tmtNow);\n#else\n    std::tm* tmNow = gmtime(&tmtNow);\n#endif\n\n    UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl dateTm.tm_year [\", dateTm.tm_year, \"]\");\n\n    if (month > 0 && month < 13)\n    {\n        dateTm.tm_mon = month - 1; \/\/ 0-11\n        UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl dateTm.tm_mon [\", dateTm.tm_mon, \"]\");\n    }\n    else\n    {\n        UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl invalid month [\", month, \"]\");\n        return (false);\n    }\n\n    if (day > 0 && day < 32)\n    {\n        dateTm.tm_mday = day; \/\/ 1-31\n        UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl dateTm.tm_mday [\", dateTm.tm_mday, \"]\");\n    }\n    else\n    {\n        UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl invalid day [\", day, \"]\");\n        return (false);\n    }\n\n    if (weeks < 0) \/\/ ignore weeks; use hour, minutes, seconds\n    {\n        if (hour > -1 && hour < 24)\n        {\n            dateTm.tm_hour = hour; \/\/ 00-23\n            UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl dateTm.tm_hour [\", dateTm.tm_hour, \"]\");\n        }\n        else\n        {\n            UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl invalid hour [\", hour, \"]\");\n            return (false);\n        }\n\n        if (minutes > -1 && minutes < 60)\n        {\n            dateTm.tm_min = minutes; \/\/ 00-59\n            UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl dateTm.tm_min [\", dateTm.tm_min, \"]\");\n        }\n        else\n        {\n            UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl invalid minutes [\", minutes, \"]\");\n            return (false);\n        }\n\n        if (seconds > -1 && seconds < 61)\n        {\n            dateTm.tm_sec = seconds; \/\/ 00-60\n            UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl dateTm.tm_sec [\", dateTm.tm_sec, \"]\");\n        }\n        else\n        {\n            UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl invalid seconds [\", seconds, \"]\");\n            return (false);\n        }\n    }\n    else \/\/ use weeks (later); ignore hour, minutes, seconds; \n    {\n        UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl weeks [\", weeks, \"]; ignoring hour, minutes, seconds\");\n        dateTm.tm_hour = 0;\n        dateTm.tm_min = 0;\n        dateTm.tm_sec = 0;\n    }\n\n    \/\/ convert std::tm to std::time_t\n#ifdef _WIN32\n    std::time_t dateTime = _mkgmtime(&dateTm); \/\/ UTC time (not mktime - not local time)\n#else\n    std::time_t dateTime = timegm(&dateTm); \/\/ UTC time (not mktime - not local time)\n#endif\n\n    \/\/ convert std::time_t to std::chrono::system_clock::time_point\n    std::chrono::system_clock::time_point refTime\n            = std::chrono::system_clock::from_time_t(dateTime);\n\n    int64_t refTimeSinceEpoch_ms;\n    if (weeks < 0) \/\/ ignore weeks\n    {\n        UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl hour, minutes, seconds calculation\");\n        refTimeSinceEpoch_ms = std::chrono::duration_cast<std::chrono::milliseconds>\n                (refTime.time_since_epoch()).count() + milliseconds;\n    }\n    else \/\/ use weeks\n    {\n        UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl weeks calculation\");\n        uint64_t weeks_ms = static_cast<int64_t> (weeks) * 7 * 24 * 3600 * 1000;\n        refTimeSinceEpoch_ms = std::chrono::duration_cast<std::chrono::milliseconds>\n                (refTime.time_since_epoch()).count() + weeks_ms + milliseconds;\n    }\n    UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl refTimeSinceEpoch_ms [\", refTimeSinceEpoch_ms, \"]\");\n\n    uint64_t refTimeSinceEpoch_s = refTimeSinceEpoch_ms \/ 1000;\n    std::chrono::time_point<std::chrono::system_clock> epochTm;\n    std::chrono::time_point<std::chrono::system_clock> refCalChronoTmNoMs = epochTm + std::chrono::seconds(refTimeSinceEpoch_s);\n    std::time_t refCalTtNoMs = std::chrono::system_clock::to_time_t(refCalChronoTmNoMs);\n    std::tm* refCalTmNoMs = gmtime(&refCalTtNoMs);\n\n    if ((refCalTmNoMs->tm_year + 1900) < m_minimumCalibrationYear)\n    {\n        UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl invalid year [\", year, \"]\");\n        return (false);\n    }\n\n    m_calibrationMutex.lock();\n    bool isCalculateDeltaMs = true;\n#ifdef ICET_ARM \/\/ only change clock on gumstix or ODROID\n    if (m_setSwHdwDateTime.empty())\n    {\n        isCalculateDeltaMs = false;\n    }\n#endif\n    if (isCalculateDeltaMs)\n    {\n        m_timeExternalCalibrationDelta_ms = refTimeSinceEpoch_ms - nowTimeSinceEpoch_ms;\n        if (m_timeExternallyCalibrationCount < UINT64_MAX)\n        {\n            m_timeExternallyCalibrationCount++;\n        }\n        m_calibrationMutex.unlock();\n\n        \/\/36 times in one hour  100s == 100000ms  100000\/50 = 2000\n        \/\/50ms => 20Hz => 72000\/hour\n        \/\/72\/hour => 1000\n        if (m_timeExternalCalibrationLogCount < m_timeExternalCalibrationLogCountMax)\n        {\n            m_timeExternalCalibrationLogCount++;\n        }\n        else\n        {\n            UXAS_LOG_INFORM(\"Time::calibrateWithReferenceUtcTimeImpl m_timeExternalCalibrationDelta_ms [\", m_timeExternalCalibrationDelta_ms, \"]\");\n            m_timeExternalCalibrationLogCount = 0;\n        }\n        UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl - END (delta calculation)\");\n        return (true);\n    }\n\n    \/\/ set host system software and hardware clocks (*nix specific)\n#ifdef ICET_ARM \/\/ only change clock on gumstix or ODROID\n    if (m_setSwHdwDateTime.empty())\n    {\n#ifdef DEBUG_VERBOSE_LOGGING_ENABLED_TIME\n        TIME_LOCAL_LOG_MESSAGE(\"Time::calibrateWithReferenceUtcTimeImpl setting system software clock and hardware clock\");\n#endif\n\n        if (weeks < 0) \/\/ ignore weeks\n        {\n#ifdef DEBUG_VERBOSE_LOGGING_ENABLED_TIME\n            TIME_LOCAL_LOG_MESSAGE(\"Time::calibrateWithReferenceUtcTimeImpl setting system and hardware clock using hour, minutes, seconds parameters\");\n#endif\n            m_setSwHdwDateTime = std::to_string(year) + \"-\" + std::to_string(month) + \"-\" + std::to_string(day) + \" \" + std::to_string(hour) + \":\" + std::to_string(minutes) + \":\" + std::to_string(seconds) + \".\" + std::to_string(milliseconds);\n        }\n        else\n        {\n#ifdef DEBUG_VERBOSE_LOGGING_ENABLED_TIME\n            TIME_LOCAL_LOG_MESSAGE(\"Time::calibrateWithReferenceUtcTimeImpl setting system and hardware clock using weeks parameter\");\n#endif\n            uint64_t refTimeSinceEpochMsOnly_ms = refTimeSinceEpoch_ms - (refTimeSinceEpoch_s * 1000);\n            m_setSwHdwDateTime = std::to_string(refCalTmNoMs->tm_year + 1900) + \"-\" + std::to_string(refCalTmNoMs->tm_mon + 1) + \"-\" + std::to_string(refCalTmNoMs->tm_mday) + \" \" + std::to_string(refCalTmNoMs->tm_hour) + \":\" + std::to_string(refCalTmNoMs->tm_min) + \":\" + std::to_string(refCalTmNoMs->tm_sec) + \".\" + std::to_string(refTimeSinceEpochMsOnly_ms);\n        }\n\n#ifdef DEBUG_VERBOSE_LOGGING_ENABLED_TIME\n        TIME_LOCAL_LOG_MESSAGE(\"Time::calibrateWithReferenceUtcTimeImpl invoking system call with date time string [\" << m_setSwHdwDateTime << \"]\");\n#endif\n        \/\/m_setSwHdwDateTime=\"2016-06-22 01:02:03.456\"\n        std::string sysCmd = \"nohup $((date --set='\" + m_setSwHdwDateTime + \"' && date --rfc-3339=ns > \/dev\/null 2>&1) && (hwclock -w > \/dev\/null 2>&1) && (disown > \/dev\/null 2>&1)) > \/dev\/null 2>&1\";\n        std::system(sysCmd.c_str());\n\n        m_isSetSwHdwDateTime = true;\n        if (m_timeExternallyCalibrationCount < UINT64_MAX)\n        {\n            m_timeExternallyCalibrationCount++;\n        }\n    }\n#endif \/\/ only change clock on gumstix or ODROID\n\n    m_calibrationMutex.unlock();\n\n    if (m_isSetSwHdwDateTime && !m_isSetSwHdwDateTimeLogged)\n    {\n        UXAS_LOG_INFORM(\"Time::calibrateWithReferenceUtcTimeImpl invoked system call with date time string [\", m_setSwHdwDateTime, \"]\");\n        m_isSetSwHdwDateTimeLogged = true;\n    }\n\n    UXAS_LOG_DEBUG_VERBOSE_TIME(\"Time::calibrateWithReferenceUtcTimeImpl - END (update system)\");\n    return (true);\n};\n\n}; \/\/namespace common\n}; \/\/namespace uxas\n","avg_line_length":41.3333333333,"max_line_length":360,"alphanum_fraction":0.6516445288,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2121,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/\r\n\/\/ Created by:  Ehiremen Ekore on 11\/21\/2019.\r\n\/\/ File name:   BoardSixy.cpp\r\n\/\/\r\n\r\n#include \"BoardSixy.hpp\"\r\n#include \"Cluster.hpp\"\r\n\r\nSixyBoard:: SixyBoard(int numRows, ifstream& puzFile, int nClusters):\r\n                Board(numRows, puzFile, nClusters){\r\n    makeBoxClusters();\r\n}\r\n\/\/------------------------------------------------------------------------------\r\n\r\nCluster* SixyBoard:: createHBox(short j, short k){\r\n    clusterSqPtr = new Square*[sizeOfPuzzle];\r\n    int index=0;\r\n    short indexLimit = sizeOfPuzzle\/2;\r\n    \r\n    for(short m=0; m<indexLimit; m++){\r\n        for(short n=0; n<indexLimit-1; n++){\r\n            clusterSqPtr[index] = &sub(j+m, k+n);\r\n            index++;\r\n        }\r\n    }\r\n    \r\n    Cluster* cluster = new Cluster(hbox, clusterSqPtr, sizeOfPuzzle);\r\n    \r\n    for(int n=0; n<sizeOfPuzzle; n++){\r\n        clusterSqPtr[n]->addCluster(cluster);\r\n        cluster->shoop(clusterSqPtr[n]->getValue());\r\n    }\r\n    return cluster;\r\n}\r\n\/\/------------------------------------------------------------------------------\r\n\r\nCluster* SixyBoard:: createVBox(short j, short k){\r\n    clusterSqPtr = new Square*[sizeOfPuzzle];\r\n    int index=0;\r\n    short indexLimit = sizeOfPuzzle\/3;\r\n    for(short m=0; m<indexLimit; m++){\r\n        for(short n=0; n<indexLimit+1; n++){\r\n            clusterSqPtr[index] = &sub(j+m, k+n);\r\n            index++;\r\n        }\r\n    }\r\n    Cluster* cluster = new Cluster(vbox, clusterSqPtr, sizeOfPuzzle);\r\n    for(int n=0; n<sizeOfPuzzle; n++){\r\n        clusterSqPtr[n]->addCluster(cluster);\r\n        cluster->shoop(clusterSqPtr[n]->getValue());\r\n    }\r\n    return cluster;\r\n}\r\n\/\/------------------------------------------------------------------------------\r\n\r\nvoid SixyBoard:: makeBoxClusters(){\r\n    \/\/make h-boxes\r\n    for(short j=1; j<=sizeOfPuzzle; j+=3){\r\n        for(short k=1; k<=sizeOfPuzzle; k+=2){\r\n            bdCluster.push_back(createHBox(j, k));\r\n        }\r\n    }\r\n\r\n    \/\/make v-boxes\r\n    for(short j=1; j<=sizeOfPuzzle; j+=2){\r\n        for(short k=1; k<=sizeOfPuzzle; k+=3){\r\n            bdCluster.push_back(createVBox(j, k));\r\n        }\r\n    }\r\n}\r\n","avg_line_length":29.8732394366,"max_line_length":81,"alphanum_fraction":0.4988213107,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":22843,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/*\nCopyright (c) 2014, Intel Corporation\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n    * Redistributions of source code must retain the above copyright notice,\n      this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and\/or other materials provided with the distribution.\n    * Neither the name of Intel Corporation nor the names of its contributors\n      may be used to endorse or promote products derived from this software\n      without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"common\/nn_data_tools.h\"\n#include \"common\/time_control.h\"\n#include <fstream>\n#include <cstring>\n#include <nmmintrin.h>\n#include <algorithm>\n#include <chrono>\n#include <memory>\n\n#define CRC_INIT 0xbaba7007\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nuint32_t crc32( const void *buffer,size_t count,uint32_t crc_ini )\n{\n    uint32_t crc = crc_ini;\n    const uint8_t *ptr = static_cast<const uint8_t *>(buffer);\n    while ( count >= 4 ) {\n        crc = _mm_crc32_u32( crc,*reinterpret_cast<const uint32_t *>(ptr) );\n        ptr += 4;\n        count -= 4;\n    }\n    while ( count-- ) crc = _mm_crc32_u32( crc,*(ptr++) );\n    return crc;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool nn_data_save_to_file(                     \/\/ Storage of all data into a binary file\n    nn::data<float>      *in,\n    std::string           filename )\n{\n    try {\n        std::ofstream file;\n        file.exceptions(std::ios::failbit | std::ios::badbit);\n        file.open(filename, std::ios::out | std::ios::trunc | std::ios::binary);\n        const nn_data_file_head_t file_head = {\n            {'N', 'N', 'D'},    \/\/ magic[]\n            'F',                \/\/ data_type\n            1,                  \/\/ version\n            in->dimension,      \/\/ dimension\n            in->sizeof_value    \/\/ sizeof_value\n        };\n\n        auto write_crc = [&file](uint32_t crc) -> void {\n            file.write(reinterpret_cast<char *>(&crc), sizeof(uint32_t));\n        };\n\n        \/\/ write header with 32-bit crc\n        file.write(reinterpret_cast<const char *>(&file_head), sizeof(file_head));\n        write_crc(crc32(&file_head, sizeof(file_head), CRC_INIT));\n\n        \/\/ write size array with 32-bit crc\n        const char *array = reinterpret_cast<const char *>(in->nn_data_t::size);\n        const auto array_size = in->dimension*sizeof(*in->nn_data_t::size);\n        file.write( array, array_size);\n        write_crc(crc32(array, array_size, CRC_INIT));\n\n        \/\/ write data with 32-bit crc\n        size_t buffer_size = in->sizeof_value;\n        for(auto index=0u; index<in->dimension; ++index) buffer_size *= in->size[index];\n        file.write(static_cast<char *>(in->buffer), buffer_size);\n        write_crc(crc32(in->buffer, buffer_size, CRC_INIT));\n    }\n    catch(...) {\n        return false;\n    }\n    return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnn::data<float>*  nn_data_load_from_file( std::string  filename )     \/\/ Load of all data from a binary file (version 2)\n\/\/ Warning! This is not a generic but only for float data\n\/\/ TODO: More generic\n{\n    try {\n        std::ifstream file;\n        file.exceptions(std::ios::failbit | std::ios::badbit);\n        file.open(filename, std::ios::in | std::ios::binary);\n\n        auto read_crc = [&file]() -> uint32_t {\n            uint32_t result;\n            file.read(reinterpret_cast<char *>(&result), sizeof(uint32_t));\n            return result;\n        };\n\n        \/\/ load header, verify 32-bit crc\n        nn_data_file_head_t file_head;\n        file.read(reinterpret_cast<char *>(&file_head), sizeof(file_head));\n        if(read_crc()!=crc32(&file_head, sizeof(file_head), CRC_INIT)) throw std::runtime_error(\"nn_data_t header crc mismatch\");\n        if(   file_head.sizeof_value!=sizeof(float)\n           || file_head.data_type!='F' ) throw std::runtime_error(\"nn_data_t has invalid type\");\n\n        \/\/ load size array, verify 32-bit crc\n        auto array = std::unique_ptr<size_t>(new size_t[file_head.dimension]);\n        auto array_size = file_head.dimension*sizeof(size_t);\n        file.read(reinterpret_cast<char *>(array.get()), array_size);\n        if(read_crc()!=crc32(array.get(), array_size, CRC_INIT)) throw std::runtime_error(\"nn_data_t size array crc mismatch\");\n\n        \/\/ create target nn::data & load data into it\n        auto data = std::unique_ptr<nn::data<float>>(new nn::data<float>(array.get(), file_head.dimension));\n        auto data_size = data.get()->count()*sizeof(float);\n        file.read(static_cast<char *>(data.get()->buffer), data_size);\n        if(read_crc()!=crc32(data.get()->buffer, data_size, CRC_INIT)) throw std::runtime_error(\"nn_data_t data crc mismatch\");\n\n        \/\/ return result\n        auto result = data.get();\n        data.release();\n        return result;\n    }\n    catch(...) {\n        return nullptr;\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnn::data<float> *nn_data_load_from_file_time_measure(\n    std::string filename,\n    std::string note\n    )\n{\n    std::cout << \"Load file  \" << filename << \" \" << note;\n    C_time_control timer;\n    nn::data<float> *nn_temp= nn_data_load_from_file(filename);\n    timer.tock();\n    std::cout<< \" at \" << timer.time_diff_string() <<\" (\"<< timer.clocks_diff_string() <<\")\"  <<std::endl;\n\n    return nn_temp;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnn::data<float, 3>*  nn_data_load_from_image(std::string  filename, \/\/ Load of all data from a image filename\n                                             uint16_t std_size,     \/\/ size of image both: height and width\n                                             fi::prepare_image_t image_process, \/\/ pointer of function for image processing\n                                             bool RGB_order)        \/\/ if true - image have RGB order, otherwise BGR\n\/\/ supported formats: JPEG, J2K, JP2, PNG, BMP, WEBP, GIF, TIFF\n{\n\n    auto data = new nn::data<float,3>(3, std_size, std_size);\n    if(FIBITMAP *bitmap_raw = fi::load_image_from_file( filename )) {\n        FIBITMAP *bitmap;\n\n        if(FreeImage_GetBPP(bitmap_raw)!=24) {\n            bitmap = FreeImage_ConvertTo24Bits(bitmap_raw);\n            FreeImage_Unload(bitmap_raw);\n        } else bitmap = bitmap_raw;\n\n        bitmap = image_process(bitmap, std_size);\n\n        auto bytes_per_pixel = FreeImage_GetLine( bitmap )\/std_size;\n        if(RGB_order) {\n            for(uint32_t y=0u; y<std_size; ++y) {\n                uint8_t *pixel = FreeImage_GetScanLine(bitmap, std_size - y - 1);\n                for(uint32_t x=0u; x<std_size; ++x) {\n                    data->at(0, x, y) = pixel[FI_RGBA_RED];\n                    data->at(1, x, y) = pixel[FI_RGBA_GREEN];\n                    data->at(2, x, y) = pixel[FI_RGBA_BLUE];\n                    pixel += bytes_per_pixel;\n                }\n            }\n        }\n        else {\n            for(uint32_t y=0u; y<std_size; ++y) {\n                uint8_t *pixel = FreeImage_GetScanLine(bitmap, std_size - y - 1);\n                for(uint32_t x=0u; x<std_size; ++x) {\n                    data->at(0, x, y) = pixel[FI_RGBA_BLUE];\n                    data->at(1, x, y) = pixel[FI_RGBA_GREEN];\n                    data->at(2, x, y) = pixel[FI_RGBA_RED];\n                    pixel += bytes_per_pixel;\n                }\n            }\n\n        }\n\n        FreeImage_Unload(bitmap);\n        return data;\n    }\n    return nullptr;\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnn::data<float>* nn_data_extend_biases_by_padding( nn::data<float>* biases, uint32_t required_num_outputs)\n{\n    \/\/ Check if number of out FM (dim number 1)  is smaller than required (to be extended to) number of dimensions\n    if (biases->size[0] >= required_num_outputs) \n    {\n        assert(0);\n        return nullptr;   \n    }\n\n    \/\/ Make a new biases container with dimension corressponding to number of outputs (num filters)\n    size_t sizes[1] = {required_num_outputs};\n    nn::data<float>* extended_biases = new nn::data<float>(sizes,1);\n\n    for(uint32_t n = 0; n< extended_biases->size[0]; ++n)\n    {\n        if(n < biases->size[0])\n        {\n            extended_biases->at(n) = biases->at(n); \n        } else {\n            extended_biases->at(n) = 0.0f; \n        }\n    }\n\n    return extended_biases; \n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnn::data<float>* nn_data_extend_weights_by_padding( nn::data<float>* weights, uint32_t extended_num_input_feature_maps, uint32_t extended_num_output_feature_maps)\n{\n    \/\/ Check if number of out FM (dim number 3)  is smaller than required (to be extended to) number of dimensions\n    \/\/ TODO: Make it better validation of sizes\n    if(weights->size[3] > extended_num_output_feature_maps ) \n    {\n        assert(0);\n        return nullptr;   \n    }\n\n    if(weights->size[2] > extended_num_input_feature_maps ) \n    {\n        assert(0);\n        return nullptr;   \n    }\n\n    \/\/ Make a new weights container with dimension corressponding to number of outputs (num filters)\n    size_t sizes[4] = {weights->size[0],weights->size[1],extended_num_input_feature_maps, extended_num_output_feature_maps};\n    nn::data<float>* extended_weights = new nn::data<float>(sizes,4);\n \n    \/\/ Copy source weights into extended container and fill the remaining part woth zeros \n    for(uint32_t n = 0; n< extended_weights->size[3]; ++n)\n    {\n        if(n < weights->size[3])\n        {\n            for(uint32_t z = 0; z< extended_weights->size[2]; ++z)\n            {\n                if(z < weights->size[2])\n                {\n                    for(uint32_t y = 0; y< weights->size[1]; ++y)\n                    {\n                        for(uint32_t x = 0; x< weights->size[0]; ++x)\n                        {\n                            extended_weights->at(x,y,z,n) = weights->at(x,y,z,n); \n                        }\n                    }\n                } else {\n                    for(uint32_t y = 0; y< extended_weights->size[1]; ++y)\n                    {\n                        for(uint32_t x = 0; x< extended_weights->size[0]; ++x)\n                        {\n                             extended_weights->at(x,y,z,n) = 0.0f; \n                        }\n                    }\n                }\n            }\n        } else {\n            for(uint32_t z = 0; z< extended_weights->size[2]; ++z)\n            {\n                for(uint32_t y = 0; y< weights->size[1]; ++y)\n                {\n                    for(uint32_t x = 0; x< weights->size[0]; ++x)\n                    {\n                         extended_weights->at(x,y,z,n) = 0.0f; \n                    }\n                }\n            }\n        }\n    }\n   \n    return extended_weights; \n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnn::data<float>* nn_data_convert_weights_2D_to_4D(nn::data<float>*src, uint32_t size_x,uint32_t size_y, uint32_t size_z, uint32_t size_n)\n{\n    \/\/ TODO: make it more generic eg. size 1D upto 3D can be converted into 4D\n    if(src->dimension != 2)\n    {\n        assert(0);\n        throw std::runtime_error(\"conversion of fully connected weights did not succeed!\");\n        return nullptr;\n    }\n\n    size_t sizes[4] = {size_x,size_y,size_z,size_n};\n    nn::data<float>* converted_weights = new nn::data<float>(sizes,4);\n\n    \/\/ Out of first dimension of source nn::data we will make content to first three dimensions of destination container\n    for(uint32_t n = 0; n< size_n; ++n)\n    {\n        size_t idx = 0;\n        for(uint32_t z = 0; z< size_z; ++z)\n        {\n            for(uint32_t y = 0; y< size_y; ++y)\n            {\n                for(uint32_t x = 0; x< size_x; ++x)\n                {\n                    converted_weights->at(x,y,z,n) = src->at(idx++,n); \n                }\n            }\n        }\n    }\n\n    return converted_weights;\n} \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnn::data<float, 4>*  nn_data_load_from_image_list(          \/\/ Load of all data from a batch of image files\n    std::vector<std::string>*  filelist,                    \/\/ Pointer to vector contained a batch of filenames of images\n    uint16_t  std_size,                                     \/\/ All images will be converted to uniform size -> std_size\n    fi::prepare_image_t image_process,                      \/\/ Pointer of function for image processing\n    uint16_t batching_size,                                 \/\/ A portion of the images must have a specific size\n    bool RGB_order)                                         \/\/ If true, then images are load with RGB order, otherwise BGR\n    \/\/ supported formats: JPEG, J2K, JP2, PNG, BMP, WEBP, GIF, TIFF\n{\n    auto set_zero = [](nn::data<float, 3> &dst) {\n        for(auto z=0u; z<dst.size[2]; ++z)\n            for(auto y=0u; y<dst.size[1]; ++y)\n                for(auto x=0u; x<dst.size[0]; ++x)\n                    dst(x,y,z) = 0.0f;\n    };\n\n    auto result = new nn::data<float, 4>(3, std_size, std_size, batching_size);\n    auto it = filelist->begin();\n    auto image_stride = 3*std_size*std_size;\n    for(auto index=0u; index<batching_size; ++index) {\n        float *buffer = reinterpret_cast<float *>(result->buffer);\n        nn::data<float,3> view(buffer+index*image_stride, 3, std_size, std_size);\n        if(it!=filelist->end()) {\n            auto image = nn_data_load_from_image(*it, std_size, image_process, RGB_order);\n            if(image) memcpy(view.buffer, image->buffer, view.count()*sizeof(float));\n            else set_zero(view);\n            delete image;\n            ++it;\n        } else set_zero(view);\n    }\n    return result;\n\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Read all labels from given mnist labels file and all corressponding images from mnist images file\nvoid nn_data_load_images_and_labels_from_mnist_files( nn::data< float, 3 >* &images, nn::data< char, 1 >* &labels, std::string &mnist_images, std::string &mnist_labels)\n{\n    char int_read[sizeof(uint32_t)]; \n    const int mnist_labels_magic_number = 2049; \n    const int mnist_images_magic_number = 2051;\n\n    \/\/ Convert 4 chars in big endian order into 4bytes long integer\n    auto block_to_int = [](char *memblock)\n    {\n        uint32_t int_value = ((((((uint8_t)memblock[0] << 8) + (uint8_t)memblock[1]) << 8 )+ (uint8_t)memblock[2]) << 8)  + (uint8_t)memblock[3];\n        return int_value;\n    };\n\n    \/\/1. Read MNIST labels\n    std::ifstream lifs;\n    lifs.open(mnist_labels, std::ifstream::binary ); \n\n    if(lifs.good() == false) {\n        std::string err_msg(\"Error reading: \" + mnist_labels); \n        throw std::runtime_error(err_msg.c_str());\n    }\n\n    \/\/ 1.1 Get Magic number\n    lifs.read(int_read,sizeof(uint32_t));\n    uint32_t magic_number = block_to_int(int_read); \n    if( magic_number != mnist_labels_magic_number ) {\n        std::string err_msg(\"Error reading MNIST Labels eg. Wrong Magic number read: \"); \n        err_msg += std::to_string(magic_number );\n        throw std::runtime_error(err_msg);\n    }\n\n    \/\/ 1.2 Get Number of labels\n    lifs.read(int_read,sizeof(uint32_t));\n    uint32_t num_labels = block_to_int(int_read); \n\n    \/\/ 1.3 Get labels\n    labels = new nn::data<char, 1>(num_labels);\n    char* pbuf = (char*)labels->buffer;\n    for(unsigned int l=0 ; l< num_labels; ++l) \n    {\n        lifs.read(pbuf+l,sizeof(char));            \n    }\n\n    lifs.close();\n\n    \/\/2. Read MNIST images\n    std::ifstream ifs;\n    ifs.open(mnist_images, std::ifstream::binary ); \n\n    if(ifs.good() == false) {\n        std::string err_msg(\"Error reading: \" + mnist_images); \n        throw std::runtime_error(err_msg.c_str());\n    }\n\n    \/\/ 2.1 Get Magic number and number of images and width and height of each image\n    ifs.read(int_read,sizeof(uint32_t));\n    magic_number = block_to_int(int_read); \n    if( magic_number != mnist_images_magic_number ) {\n        std::string err_msg(\"Error reading MNIST Images eg. Wrong Magic number read: \"); \n        err_msg += std::to_string(magic_number);\n        throw std::runtime_error(err_msg);\n    }\n\n    \/\/ Get Number of images\n    ifs.read(int_read,sizeof(uint32_t));\n    uint32_t num_images = block_to_int(int_read); \n\n    \/\/ Get images' width\n    ifs.read(int_read,sizeof(uint32_t));\n    uint32_t images_width = block_to_int(int_read); \n\n    \/\/ Get images' height\n    ifs.read(int_read,sizeof(uint32_t));\n    uint32_t images_height = block_to_int(int_read); \n\n    \/\/ 2.2 Get all images\n    images = new nn::data<float, 3>(images_width, images_height, num_images);\n    std::unique_ptr<char[]> single_image(new char[images_height * images_width]);   \n    \n    \/\/ Read all images (all at one) , scale its values from: <0-255> to <0.0 - 1.0>\n    \/\/ as caffe training was processing data that way\n    for(unsigned int img=0; img < num_images; ++img)\n    {\n        ifs.read(single_image.get(),images_width*images_height*sizeof(char));    \n\n        float* pdata_image = (float*)images->buffer + img*images_width*images_height;   \/\/?? is it safe\n        for(unsigned int pix=0; pix < images_width*images_height; ++pix )\n        {\n             pdata_image[pix]= *((unsigned char*)single_image.get() + pix)*1.0f\/255.0f;\n        }\n\n    }\n\n    ifs.close();\n\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid nn_data_convert_float_to_int16_fixedpoint(nn::data<float> *in,\n                                                        nn::data<int16_t> *out,\n                                                        const float scale){\n    const size_t N = in->count();\n    auto  inbuffer = static_cast<float *>(in->buffer);\n    auto outbuffer = static_cast<int16_t *>(out->buffer);\n\n    for (size_t i = 0; i < N; ++i)\n        outbuffer[i] = inbuffer[i] * scale;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid nn_data_convert_float_to_int32_fixedpoint(nn::data<float> *in,\n                                                        nn::data<int32_t> *out,\n                                                        float scale){\n    const size_t N = in->count();\n    auto  inbuffer = static_cast<float *>(in->buffer);\n    auto outbuffer = static_cast<int32_t *>(out->buffer);\n\n    for(size_t i=0;i<N;++i)\n        outbuffer[i] = inbuffer[i] * scale;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnn::data<float, 4>*  nn_data_load_from_image_list_for_int16(    \/\/ Load of all data from a batch of image files\n    std::vector<std::string>*  filelist,                                 \/\/ Pointer to vector contained a batch of filenames of images\n    uint16_t  std_size,                                                  \/\/ All images will be converted to uniform size -> std_size\n    uint16_t batching_size)                                              \/\/ A portion of the images must have a specific size\n    \/\/ supported formats: JPEG, J2K, JP2, PNG, BMP, WEBP, GIF, TIFF\n{\n    auto data = new nn::data<float, 4>(3, std_size, std_size, batching_size);\n\n    auto filelist_count = filelist->size();\n\n    \/\/ Verifying that the images on the list is more than the size of batching\n    uint16_t  count = (filelist_count > batching_size) ? batching_size : filelist_count;\n\n    \/\/ Read images from filelist vector\n    uint16_t i = 0;\n    std::vector<std::string>::iterator files_itr = filelist->begin();\n    for (; i < count; ++i, ++files_itr) {\n        FIBITMAP *bitmap = fi::load_image_from_file(files_itr->data());\n        if (bitmap) {\n            if (FreeImage_GetBPP(bitmap) != 24) {\n                FIBITMAP *bmp_temp = FreeImage_ConvertTo24Bits(bitmap);\n                FreeImage_Unload(bitmap);\n                bitmap = bmp_temp;\n            }\n            bitmap = fi::crop_image_to_square_and_resize(bitmap, std_size);\n            uint8_t Bpp = FreeImage_GetLine(bitmap) \/ std_size; \/\/ And now Bpp means Bytes per pixel\n            for (int y = 0; y < std_size; ++y) {\n                uint8_t *pixel = FreeImage_GetScanLine(bitmap, std_size - y - 1);\n                for (int x = 0; x < std_size; ++x) {\n                    data->at(0, x, y, i) = pixel[FI_RGBA_RED];\n                    data->at(1, x, y, i) = pixel[FI_RGBA_GREEN];\n                    data->at(2, x, y, i) = pixel[FI_RGBA_BLUE];\n                    pixel += Bpp;\n                }\n            }\n            FreeImage_Unload(bitmap);\n        }\n        else {  \/\/ What, if reading bitmap failed? - Why not fill with zeros?\n            for (int y = 0; y < std_size; ++y) {\n                for (int x = 0; x < std_size; ++x) {\n                    for(int p = 0; p < 3; ++p) {\n                        data->at(p, x, y, i) = 0;\n                    }\n                }\n            }\n        }\n    }\n    \/\/ Fill with zero values, if number of  images are less than batching size\n    for (; i < batching_size; ++i) {\n        for (int y = 0; y < std_size; ++y) {\n            for (int x = 0; x < std_size; ++x) {\n              for (int p = 0; p < 3;++p)\n                data->at(i, x, y, p) = 0;\n            }\n        }\n    }\n    return data;\n}\n","avg_line_length":42.2236598891,"max_line_length":168,"alphanum_fraction":0.5381079543,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5518,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":43.0,"content":"\/*\n * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <tencentcloud\/yunjing\/v20180228\/model\/DescribeWeeklyReportsResponse.h>\n#include <tencentcloud\/core\/utils\/rapidjson\/document.h>\n#include <tencentcloud\/core\/utils\/rapidjson\/writer.h>\n#include <tencentcloud\/core\/utils\/rapidjson\/stringbuffer.h>\n\nusing TencentCloud::CoreInternalOutcome;\nusing namespace TencentCloud::Yunjing::V20180228::Model;\nusing namespace std;\n\nDescribeWeeklyReportsResponse::DescribeWeeklyReportsResponse() :\n    m_weeklyReportsHasBeenSet(false),\n    m_totalCountHasBeenSet(false)\n{\n}\n\nCoreInternalOutcome DescribeWeeklyReportsResponse::Deserialize(const string &payload)\n{\n    rapidjson::Document d;\n    d.Parse(payload.c_str());\n    if (d.HasParseError() || !d.IsObject())\n    {\n        return CoreInternalOutcome(Core::Error(\"response not json format\"));\n    }\n    if (!d.HasMember(\"Response\") || !d[\"Response\"].IsObject())\n    {\n        return CoreInternalOutcome(Core::Error(\"response `Response` is null or not object\"));\n    }\n    rapidjson::Value &rsp = d[\"Response\"];\n    if (!rsp.HasMember(\"RequestId\") || !rsp[\"RequestId\"].IsString())\n    {\n        return CoreInternalOutcome(Core::Error(\"response `Response.RequestId` is null or not string\"));\n    }\n    string requestId(rsp[\"RequestId\"].GetString());\n    SetRequestId(requestId);\n\n    if (rsp.HasMember(\"Error\"))\n    {\n        if (!rsp[\"Error\"].IsObject() ||\n            !rsp[\"Error\"].HasMember(\"Code\") || !rsp[\"Error\"][\"Code\"].IsString() ||\n            !rsp[\"Error\"].HasMember(\"Message\") || !rsp[\"Error\"][\"Message\"].IsString())\n        {\n            return CoreInternalOutcome(Core::Error(\"response `Response.Error` format error\").SetRequestId(requestId));\n        }\n        string errorCode(rsp[\"Error\"][\"Code\"].GetString());\n        string errorMsg(rsp[\"Error\"][\"Message\"].GetString());\n        return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));\n    }\n\n\n    if (rsp.HasMember(\"WeeklyReports\") && !rsp[\"WeeklyReports\"].IsNull())\n    {\n        if (!rsp[\"WeeklyReports\"].IsArray())\n            return CoreInternalOutcome(Core::Error(\"response `WeeklyReports` is not array type\"));\n\n        const rapidjson::Value &tmpValue = rsp[\"WeeklyReports\"];\n        for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)\n        {\n            WeeklyReport item;\n            CoreInternalOutcome outcome = item.Deserialize(*itr);\n            if (!outcome.IsSuccess())\n            {\n                outcome.GetError().SetRequestId(requestId);\n                return outcome;\n            }\n            m_weeklyReports.push_back(item);\n        }\n        m_weeklyReportsHasBeenSet = true;\n    }\n\n    if (rsp.HasMember(\"TotalCount\") && !rsp[\"TotalCount\"].IsNull())\n    {\n        if (!rsp[\"TotalCount\"].IsUint64())\n        {\n            return CoreInternalOutcome(Core::Error(\"response `TotalCount` IsUint64=false incorrectly\").SetRequestId(requestId));\n        }\n        m_totalCount = rsp[\"TotalCount\"].GetUint64();\n        m_totalCountHasBeenSet = true;\n    }\n\n\n    return CoreInternalOutcome(true);\n}\n\nstring DescribeWeeklyReportsResponse::ToJsonString() const\n{\n    rapidjson::Document value;\n    value.SetObject();\n    rapidjson::Document::AllocatorType& allocator = value.GetAllocator();\n\n    if (m_weeklyReportsHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"WeeklyReports\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);\n\n        int i=0;\n        for (auto itr = m_weeklyReports.begin(); itr != m_weeklyReports.end(); ++itr, ++i)\n        {\n            value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);\n            (*itr).ToJsonObject(value[key.c_str()][i], allocator);\n        }\n    }\n\n    if (m_totalCountHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"TotalCount\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, m_totalCount, allocator);\n    }\n\n    rapidjson::Value iKey(rapidjson::kStringType);\n    string key = \"RequestId\";\n    iKey.SetString(key.c_str(), allocator);\n    value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);\n    \n    rapidjson::StringBuffer buffer;\n    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n    value.Accept(writer);\n    return buffer.GetString();\n}\n\n\nvector<WeeklyReport> DescribeWeeklyReportsResponse::GetWeeklyReports() const\n{\n    return m_weeklyReports;\n}\n\nbool DescribeWeeklyReportsResponse::WeeklyReportsHasBeenSet() const\n{\n    return m_weeklyReportsHasBeenSet;\n}\n\nuint64_t DescribeWeeklyReportsResponse::GetTotalCount() const\n{\n    return m_totalCount;\n}\n\nbool DescribeWeeklyReportsResponse::TotalCountHasBeenSet() const\n{\n    return m_totalCountHasBeenSet;\n}\n\n\n","avg_line_length":34.0617283951,"max_line_length":128,"alphanum_fraction":0.6718013773,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2657,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"PCH.h\"\n\n#include \"Image.h\"\n\nImageView::ImageView(VkImage vkImage, VkFormat format, VkImageViewType viewType, VkComponentMapping mapping,\n\tVkImageSubresourceRange range, VkImageViewCreateFlags flags)\n{\n\tVkImageViewCreateInfo info{ .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,\n\t\t.pNext = nullptr,\n\t\t.flags = flags,\n\t\t.image = vkImage,\n\t\t.viewType = viewType,\n\t\t.format = format,\n\t\t.components = mapping,\n\t\t.subresourceRange = range };\n\n\tVkCall(vkCreateImageView(Instance::Device(), &info, nullptr, &m_View));\n}\n\nImageView::ImageView(const Image& image, VkFormat format, VkImageViewType viewType, VkComponentMapping mapping,\n\tVkImageSubresourceRange range, VkImageViewCreateFlags flags)\n{\n\tVkImageViewCreateInfo info{ .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,\n\t\t.pNext = nullptr,\n\t\t.flags = flags,\n\t\t.image = image.GetHandle(),\n\t\t.viewType = viewType,\n\t\t.format = format,\n\t\t.components = mapping,\n\t\t.subresourceRange = range };\n\n\tVkCall(vkCreateImageView(Instance::Device(), &info, nullptr, &m_View));\n}\n\nImageView::~ImageView() { vkDestroyImageView(Instance::Device(), m_View, nullptr); }\n\nImageView::ImageView(ImageView&& other)\n{\n\tm_View = other.m_View;\n\tother.m_View = VK_NULL_HANDLE;\n}\n\nImageView& ImageView::operator=(ImageView&& other)\n{\n\tthis->~ImageView();\n\n\tm_View = other.m_View;\n\tother.m_View = VK_NULL_HANDLE;\n\n\treturn *this;\n}\n\nImage::Image(VkImageType type, VkFormat format, glm::u32vec3 size, u32 mipLevels, u32 layers,\n\tVkSampleCountFlagBits samples, VkImageUsageFlags usage, VkImageLayout layout, VmaMemoryUsage memUsage,\n\tVkImageCreateFlags flags)\n{\n\tu32 index = Instance::GraphicsIndex();\n\n\tVkImageCreateInfo info{ .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,\n\t\t.flags = flags,\n\t\t.imageType = type,\n\t\t.format = format,\n\t\t.extent = { size.x, size.y, size.z },\n\t\t.mipLevels = mipLevels,\n\t\t.arrayLayers = layers,\n\t\t.samples = samples,\n\t\t.tiling = VK_IMAGE_TILING_OPTIMAL,\n\t\t.usage = usage,\n\t\t.sharingMode = VK_SHARING_MODE_EXCLUSIVE,\n\t\t.queueFamilyIndexCount = 1,\n\t\t.pQueueFamilyIndices = &index,\n\t\t.initialLayout = layout };\n\n\tVmaAllocationCreateInfo allocInfo{ .usage = memUsage };\n\n\tVkCall(vmaCreateImage(Instance::Allocator(), &info, &allocInfo, &m_Image, &m_Memory, nullptr));\n}\n\nImage::~Image() { vmaDestroyImage(Instance::Allocator(), m_Image, m_Memory); }\n\nImage::Image(Image&& other)\n{\n\tm_Image = other.m_Image;\n\tother.m_Image = VK_NULL_HANDLE;\n\tm_Memory = other.m_Memory;\n\tother.m_Memory = VK_NULL_HANDLE;\n}\n\nImage& Image::operator=(Image&& other)\n{\n\tthis->~Image();\n\n\tm_Image = other.m_Image;\n\tother.m_Image = VK_NULL_HANDLE;\n\tm_Memory = other.m_Memory;\n\tother.m_Memory = VK_NULL_HANDLE;\n\n\treturn *this;\n}\n","avg_line_length":26.57,"max_line_length":111,"alphanum_fraction":0.7414377117,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1238,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/* file: implicit_als_train_csr_default_distr_step3_fpt_dispatcher.cpp *\/\n\/*******************************************************************************\n* Copyright 2014-2019 Intel Corporation\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*******************************************************************************\/\n\n\/*\n\/\/++\n\/\/  Implementation of implicit ALS training algorithm container for distributed\n\/\/  computing mode.\n\/\/--\n*\/\n\n#include \"implicit_als_train_container.h\"\n\nnamespace daal\n{\nnamespace algorithms\n{\n__DAAL_INSTANTIATE_DISPATCH_CONTAINER(implicit_als::training::DistributedContainer, distributed, step3Local, DAAL_FPTYPE,\n                                      implicit_als::training::fastCSR)\n}\n} \/\/ namespace daal\n","avg_line_length":35.3714285714,"max_line_length":121,"alphanum_fraction":0.6542810985,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2609,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2.0,"content":"\ufeff\/*\n* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\").\n* You may not use this file except in compliance with the License.\n* A copy of the License is located at\n*\n*  http:\/\/aws.amazon.com\/apache2.0\n*\n* or in the \"license\" file accompanying this file. This file is distributed\n* on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n* express or implied. See the License for the specific language governing\n* permissions and limitations under the License.\n*\/\n\n#include <aws\/athena\/model\/StatementType.h>\n#include <aws\/core\/utils\/HashingUtils.h>\n#include <aws\/core\/Globals.h>\n#include <aws\/core\/utils\/EnumParseOverflowContainer.h>\n\nusing namespace Aws::Utils;\n\n\nnamespace Aws\n{\n  namespace Athena\n  {\n    namespace Model\n    {\n      namespace StatementTypeMapper\n      {\n\n        static const int DDL_HASH = HashingUtils::HashString(\"DDL\");\n        static const int DML_HASH = HashingUtils::HashString(\"DML\");\n        static const int UTILITY_HASH = HashingUtils::HashString(\"UTILITY\");\n\n\n        StatementType GetStatementTypeForName(const Aws::String& name)\n        {\n          int hashCode = HashingUtils::HashString(name.c_str());\n          if (hashCode == DDL_HASH)\n          {\n            return StatementType::DDL;\n          }\n          else if (hashCode == DML_HASH)\n          {\n            return StatementType::DML;\n          }\n          else if (hashCode == UTILITY_HASH)\n          {\n            return StatementType::UTILITY;\n          }\n          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();\n          if(overflowContainer)\n          {\n            overflowContainer->StoreOverflow(hashCode, name);\n            return static_cast<StatementType>(hashCode);\n          }\n\n          return StatementType::NOT_SET;\n        }\n\n        Aws::String GetNameForStatementType(StatementType enumValue)\n        {\n          switch(enumValue)\n          {\n          case StatementType::DDL:\n            return \"DDL\";\n          case StatementType::DML:\n            return \"DML\";\n          case StatementType::UTILITY:\n            return \"UTILITY\";\n          default:\n            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();\n            if(overflowContainer)\n            {\n              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));\n            }\n\n            return {};\n          }\n        }\n\n      } \/\/ namespace StatementTypeMapper\n    } \/\/ namespace Model\n  } \/\/ namespace Athena\n} \/\/ namespace Aws\n","avg_line_length":29.6477272727,"max_line_length":92,"alphanum_fraction":0.6239938674,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2106,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":10.0,"content":"\/*\n *\n *  Copyright (C) 2013  Anwar Mohamed <anwarelmakrahy[at]gmail.com>\n *\n *  This program is free software; you can redistribute it and\/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation; either version 2 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program; if not, write to Anwar Mohamed\n *  anwarelmakrahy[at]gmail.com\n *\n *\/\n\n#include \"Packetyzer.h\"\n\nusing namespace Packetyzer::Send;\n\ncWinpcapSend::cWinpcapSend()\n{\n\tisReady = InitializeAdapters();\n};\n\nBOOL cWinpcapSend::SendPacket(UINT AdapterIndex, cPacket* Packet)\n{\n\tUINT i=0;\n\tif (AdapterIndex< 1 || AdapterIndex > nAdapters) return FALSE;\n\tfor (d=alldevs, i=0; i< AdapterIndex-1 ;d=d->next, i++);        \n\tif ((fp=pcap_open(d->name, 65536, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf)) == NULL) return FALSE;\n\tif (pcap_sendpacket(fp, Packet->RawPacket, Packet->PacketSize) != 0) return FALSE;\n\treturn TRUE;\n}\n\nBOOL cWinpcapSend::InitializeAdapters()\n{\n\tif (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1) return FALSE;\n        \n\tnAdapters = 0;\n\tAdapters = (NETWORK_ADAPTERS_SEND*)malloc(nAdapters * sizeof(NETWORK_ADAPTERS_SEND));\n\n\tfor(d=alldevs; d; d=d->next)\n\t{\n\t\tAdapters = (NETWORK_ADAPTERS_SEND*)realloc(Adapters, (nAdapters + 1) * sizeof(NETWORK_ADAPTERS_SEND));\n\t\tstrcpy_s((CHAR*)Adapters[nAdapters].ID,strlen(d->name) + 1, d->name);\n\n\t\tif (d->description)\n\t\t\tstrcpy_s((CHAR*)Adapters[nAdapters].Name, strlen(d->description) + 1, d->description);\n\t\telse\n\t\t\tstrcpy_s((CHAR*)Adapters[nAdapters].Name, strlen(\"No description available\"), \"No description available\");\n\n\t\tnAdapters++;\n\t}\n\n\treturn TRUE;\n};\n\n\ncWinpcapSend::~cWinpcapSend()\n{\n\tpcap_freealldevs(alldevs);\n\tfree(Adapters);\n}\n","avg_line_length":30.5217391304,"max_line_length":109,"alphanum_fraction":0.7188983856,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5301,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/****************************************************************************************\n*  @author: kzvd4729                                         created: Jun\/22\/2020 22:34                        \n*  solution_verdict: Wrong answer on test 12                 language: GNU C++17                               \n*  run_time: 31 ms                                           memory_used: 15700 KB                             \n*  problem: https:\/\/codeforces.com\/contest\/1036\/problem\/E\n****************************************************************************************\/\n#include<iostream>\n#include<vector>\n#include<cstring>\n#include<map>\n#include<bitset>\n#include<assert.h>\n#include<algorithm>\n#include<iomanip>\n#include<cmath>\n#include<set>\n#include<queue>\n#include<unordered_map>\n#include<random>\n#include<chrono>\n#include<stack>\n#include<deque>\n#define long long long\nusing namespace std;\nconst int N=1e6;\n#define setp(a) cout<<setprecision(a)<<fixed\nconst double eps=1e-7,pi=acos(-1.0);\n int sgn(double d)\n{\n  if(fabs(d)<eps)return 0;return d<0.0?-1:1;\n}\nstruct point\n{\n  double x,y;\n  point(){};point(double _x,double _y):x(_x),y(_y){}\n  point operator+(point p){return point(x+p.x,y+p.y);}\n  point operator-(point p){return point(x-p.x,y-p.y);}\n  point operator*(double d){return point(x*d,y*d);}\n  point operator\/(double d){return point(x\/d,y\/d);}\n  bool operator==(point p){return x==p.x&&y==p.y;}\n  bool operator<(const point &p)const{return x<p.x||(x==p.x&&y<p.y);}\n  double value(){return sqrt(x*x+y*y);}\n  double dist(point p){return sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));}\n  point unitVector()\n  {\n    \/\/invalid if vector is (0,0)\n    double v=value();return point(x\/v,y\/v);\n  }\n  double operator*(point p)\n  {\n    return x*p.x+y*p.y;\/\/0 if vectors are perpendicular;\n  }\n  double operator^(point p)\n  {\n    return x*p.y-y*p.x;\/\/0 if two vectors are same\n    \/\/signed area of the parallelogram by two vector\n    \/\/positive if p is ccw to the vector\n  }\n  point rotateCCW(double a)\/\/radian\n  {\n    return point(x*cos(a)-y*sin(a),x*sin(a)+y*cos(a));\n  }\n  point rotateCCW90(){return point(-y,x);}\n  point rotateCCW180(){return point(-x,-y);}\n  point rotateCCW270(){return point(y,-x);}\n};\ndouble radToDeg(double r){return r*180.0\/pi;}\ndouble degToRed(double d){return d*pi\/180.0;}\ndouble modifiedatan2(point p)\/\/clockwise full angle with positive x axis\n{\n  double ang=atan2(p.y,p.x);if(ang<0)ang+=pi+pi;\/\/carefull\n  return radToDeg(ang);\/\/deg return \n}\nstruct line\n{\n  point p,v;\/\/v is vector,going through p;\n  line(){}\n  line(point _p,point _v):p(_p),v(_v){}\n  void makeLine(point p1,point p2){p=p1,v=p2-p1;}\n  bool onLine(point p1)\n  {\n    if(sgn(v^(p1-p))!=0)return false;\/\/area of triangle has to be 0\n    return true;\n  }\n  double pointDist(point p1)\n  {\n    \/\/area of triangle\/base of triangle\n    return abs((v^(p1-p))\/v.value());\/\/signed based on cw ans ccw\n  }\n  line perpendicular(point p1){return line(p1,v.rotateCCW90());}\n  point intersection(line l)\n  {\n    \/\/no solution for parallel line.\n    return p+v*((l.v^(p-l.p))\/(v^l.v));\n  }\n};\nstruct segment\n{\n  point a,b;\n  segment(){}\n  segment(point _a,point _b):a(_a),b(_b){}\n  \/\/onLine and onSegment\n  bool onLine(point p)\n  {\n    line l;l.makeLine(a,b);\n    if(!l.onLine(p))return false;\n    if(p.x>=min(a.x,b.x)&&p.x<=max(a.x,b.x)&&p.y>=min(a.y,b.y)&&p.y<=max(a.y,b.y))\n      return true;\/\/precision \n    return false;\n  }\n  int segmentIntersect(segment sg)\n  {\n    int s1,s2,s3,s4;\n    int d1=sgn(s1=(b-a)^(sg.a-a)),d2=sgn(s2=(b-a)^(sg.b-a));\n    int d3=sgn(s3=(sg.b-sg.a)^(a-sg.a)),d4=sgn(s4=(sg.b-sg.a)^(b-sg.a));\n    if((d1^d2)==-2&&(d3^d4)==-2)return 1;\n    else if(d1==0&&sgn((a-sg.a)*(b-sg.a))<=0)return 2;\n    else if(d2==0&&sgn((a-sg.b)*(b-sg.b))<=0)return 2;\n    else if(d3==0&&sgn((sg.a-a)*(sg.b-a))<=0)return 2;\n    else if(d4==0&&sgn((sg.a-b)*(sg.b-b))<=0)return 2;\n    return 0;\n  }\n  \/\/this is a very bad way to do this\n  double segmentToPointDist(point p)\n  {\n    line l,r;l.makeLine(a,b);r=l.perpendicular(p);\n    double ret=min(a.dist(p),b.dist(p));\n    if(onLine(l.intersection(r)))ret=l.pointDist(p);\n    return ret;\n  }\n  double segmentSegmentDist(segment sg)\n  {\n    if(segmentIntersect(sg))return 0;\n    double ret=segmentToPointDist(sg.a);\n    ret=min(ret,segmentToPointDist(sg.b));\n    ret=min(ret,sg.segmentToPointDist(a));\n    ret=min(ret,sg.segmentToPointDist(b));\n    return ret;\n  }\n};\nbool isInt(double x)\n{\n  double z=round(x);\n  return fabs(x-z)<=eps;\n}\nint a[N+2],b[N+2],c[N+2],d[N+2];\nint main()\n{\n  ios_base::sync_with_stdio(0);cin.tie(0);\n  int n;cin>>n;int ans=0;\n  for(int i=1;i<=n;i++)\n  {\n    cin>>a[i]>>b[i]>>c[i]>>d[i];\n    ans+=__gcd(abs(c[i]-a[i]),abs(d[i]-b[i]))+1;\n  }\n  set<pair<int,int> >st;\n  for(int i=1;i<=n;i++)\n  {\n    for(int j=1;j<=n;j++)\n    {\n      if(i==j)continue;\n      segment s1(point(a[i],b[i]),point(c[i],d[i]));\n      segment s2(point(a[j],b[j]),point(c[j],d[j]));\n       int in=s1.segmentIntersect(s2);if(in==0)continue;\n      \/\/if(in==2)cout<<i<<\" --> \"<<j<<endl;\n       line l1(point(a[i],b[i]),point(c[i]-a[i],d[i]-b[i]));\n      line l2(point(a[j],b[j]),point(c[j]-a[j],d[j]-b[j]));\n       point p=l1.intersection(l2);\n      if(isInt(p.x)&&isInt(p.y))\n        st.insert({round(p.x),round(p.y)});\n    }\n  }\n  cout<<ans-st.size()<<endl;\n  return 0;\n}","avg_line_length":30.2914285714,"max_line_length":111,"alphanum_fraction":0.5714016223,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2156,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":268.0,"content":"#include \"catch.hpp\"\n\n#include \"..\/anchors.h\"\n#include \"..\/config.h\"\n\nTEST_CASE(\"Generate anchors no throw\", \"[anchors]\") {\n  Config config;\n  torch::Tensor boxes;\n  CHECK_NOTHROW(boxes = GeneratePyramidAnchors(\n                    config.rpn_anchor_scales, config.rpn_anchor_ratios,\n                    config.backbone_shapes, config.backbone_strides,\n                    config.rpn_anchor_stride));\n}\n\nTEST_CASE(\"Generate anchors\", \"[anchors]\") {\n  std::vector<uint32_t> image_shape = {800, 600};\n  std::vector<float> scales = {32, 64};\n  std::vector<float> ratios = {0.5f, 1.f, 2.f};\n  std::vector<float> feature_strides = {4, 8};\n  std::vector<std::pair<float, float>> feature_shapes;\n  uint32_t anchor_stride = 10;\n\n  \/\/ compute backbone size from input image size\n  for (auto stride : feature_strides) {\n    feature_shapes.push_back(\n        {image_shape[0] \/ stride, image_shape[1] \/ stride});\n  }\n\n  uint64_t total_size = 0;\n  for (size_t i = 0; i < scales.size(); ++i) {\n    auto features_num = std::round(feature_shapes[i].first \/ anchor_stride) *\n                        std::round(feature_shapes[i].second \/ anchor_stride);\n    total_size += ratios.size() * features_num;\n  }\n\n  torch::Tensor boxes;\n  CHECK_NOTHROW(boxes = GeneratePyramidAnchors(scales, ratios, feature_shapes,\n                                               feature_strides, anchor_stride));\n  REQUIRE(total_size == boxes.size(0));\n  REQUIRE(4 == boxes.size(1));\n\n  auto half_w = static_cast<float>(image_shape[0]) \/ 2.f;\n  auto half_h = static_cast<float>(image_shape[1]) \/ 2.f;\n\n  auto boxes_data = boxes.accessor<float, 2>();\n  for (int64_t i = 0; i < boxes.size(0); ++i) {\n    auto y1 = boxes_data[i][0];\n    auto x1 = boxes_data[i][1];\n    auto y2 = boxes_data[i][2];\n    auto x2 = boxes_data[i][3];\n    REQUIRE(x1 >= -half_h);\n    REQUIRE(x2 >= -half_h);\n    REQUIRE(y1 >= -half_w);\n    REQUIRE(y2 >= -half_w);\n\n    REQUIRE(x1 < static_cast<float>(image_shape[1]) + half_h);\n    REQUIRE(x2 < static_cast<float>(image_shape[1]) + half_h);\n    REQUIRE(y1 < static_cast<float>(image_shape[0]) + half_w);\n    REQUIRE(y2 < static_cast<float>(image_shape[0]) + half_w);\n  }\n}\n","avg_line_length":34.7741935484,"max_line_length":80,"alphanum_fraction":0.6331168831,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2090,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-4.0","MIT"],"max_stars_count":1.0,"content":"\/\/ System::Net::WebException::WebException();\r\n\r\n\/*\r\nThis program demonstrates the 'WebException()' constructor of 'WebException' class.\r\nIt creates a 'HttpConnect' Object* and calls the 'ConnectHttpServer' method with an invalid 'URL'.\r\nWhen the method tries to establish a socket connection to that address an exception is thrown.In\r\nthe 'catch' block  a new 'WebException' Object* is created  and  thrown to the caller.That exception\r\nis caught in the calling method and the error message is dispalyed to the console.\r\n*\/\r\n\r\n#using <System.dll>\r\n\r\nusing namespace System;\r\nusing namespace System::Net;\r\nusing namespace System::Net::Sockets;\r\nusing namespace System::Text;\r\n\r\npublic ref class HttpConnect\r\n{\r\npublic:\r\n   void ConnectHttpServer( String^ connectUri )\r\n   {\r\n\/\/ <Snippet1>\r\n      try\r\n      {\r\n         \/\/ A 'Socket' object has been created.\r\n         Socket^ httpSocket = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );\r\n         \r\n\r\n         \/\/ The IPaddress of the unknown uri is resolved using the 'Dns::Resolve' method.\r\n\r\n         IPHostEntry^ hostEntry = Dns::Resolve( \"http:\/\/www.contoso.com\" );\r\n\r\n         IPAddress^ serverAddress = hostEntry->AddressList[ 0 ];\r\n         IPEndPoint^ endPoint = gcnew IPEndPoint( serverAddress, 80 );\r\n         httpSocket->Connect( endPoint );\r\n         Console::WriteLine( \"Connection created successfully\" );\r\n         httpSocket->Close();\r\n      }\r\n      catch ( SocketException^ e ) \r\n      {\r\n         String^ exp = e->Message;\r\n         \/\/ Throw the WebException with no parameters.\r\n         throw gcnew WebException;\r\n      }\r\n\/\/ <\/Snippet1>\r\n   }\r\n};\r\n\r\nint main()\r\n{\r\n   try\r\n   {\r\n      HttpConnect^ myHttpConnect = gcnew HttpConnect;\r\n      \/\/ If the Uri is valid  then 'ConnectHttpServer' method will connect to the server.\r\n      myHttpConnect->ConnectHttpServer( \"www.contoso.com\" );\r\n   }\r\n   catch ( WebException^ e ) \r\n   {\r\n      Console::WriteLine( \"The Exception is: {0}\", e->Message );\r\n      Console::WriteLine( \"The Exception is: Unable to Contact the server\" );\r\n   }\r\n}\r\n","avg_line_length":32.65625,"max_line_length":112,"alphanum_fraction":0.6497607656,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":286,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":49.0,"content":"\/\/ stdafx.cpp : source file that includes just the standard includes\n\/\/ License.pch will be the pre-compiled header\n\/\/ stdafx.obj will contain the pre-compiled type information\n\n#include \"stdafx.h\"\n\n\/\/ TODO: reference any additional headers you need in STDAFX.H\n\/\/ and not in this file\n","avg_line_length":31.7777777778,"max_line_length":68,"alphanum_fraction":0.7622377622,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":17377,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/*\n *    Copyright (c) 2008-2021 Nuovation System Designs, LLC\n *    All rights reserved.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n *\/\n\n\/**\n *    @file\n *      This file implements Nuovations Log Utilities functions that may\n *      be used for logging the contents of arbitrary memory\n *      locations.\n *\/\n\n#include <LogUtilities\/LogMemoryUtilities.hpp>\n\n#include <string>\n\nusing namespace std;\n\n#include <ctype.h>\n#include <inttypes.h>\n#include <stddef.h>\n#include <stdint.h>\n\n#include <LogUtilities\/LogGlobals.hpp>\n\nnamespace Nuovations\n{\n\nnamespace Log\n{\n\nnamespace Utilities\n{\n\nnamespace Memory\n{\n\n\/**\n *  @brief\n *    Write a log message using the global Debug logger instance, with\n *    no indent and at the default level, containing the memory at the\n *    specified address formatted as 1 byte units with the specified\n *    number of memory units.\n *\n *  @param[in]  inAddress  The memory address to log.\n *  @param[in]  inUnits    The number of memory units to log.\n *\n *  @ingroup memory-utilities\n *\n *\/\nvoid\nWrite(const void * inAddress, size_t inUnits)\n{\n    static const Log::Indent  kIndent = 0;\n    static const Log::Level   kLevel  = 0;\n    static const unsigned int kWidth  = sizeof(uint8_t);\n\n    Write(Log::Debug(), kIndent, kLevel, inAddress, inUnits, kWidth);\n}\n\n\/**\n *  @brief\n *    Write a log message using the global Debug logger instance, with\n *    no indent and at the provided level, containing the memory at\n *    the specified address formatted as 1 byte units with the\n *    specified number of memory units.\n *\n *  @param[in]  inLevel    The level the current message is to be logged\n *                         at.\n *  @param[in]  inAddress  The memory address to log.\n *  @param[in]  inUnits    The number of memory units to log.\n *\n *  @ingroup memory-utilities\n *\n *\/\nvoid\nWrite(Log::Level inLevel, const void * inAddress, size_t inUnits)\n{\n    static const Log::Indent  kIndent = 0;\n    static const unsigned int kWidth  = sizeof(uint8_t);\n\n    Write(Log::Debug(), kIndent, inLevel, inAddress, inUnits, kWidth);\n}\n\n\/**\n *  @brief\n *    Write a log message using the global Debug logger instance, with\n *    the provided indent and level, containing the memory at the\n *    specified address formatted as 1 byte units with the specified\n *    number of memory units.\n *\n *  @param[in]  inIndent   The level of indendation desired for the\n *                         provided log message.\n *  @param[in]  inLevel    The level the current message is to be logged\n *                         at.\n *  @param[in]  inAddress  The memory address to log.\n *  @param[in]  inUnits    The number of memory units to log.\n *\n *  @ingroup memory-utilities\n *\n *\/\nvoid\nWrite(Log::Indent  inIndent,\n      Log::Level   inLevel,\n      const void * inAddress,\n      size_t       inUnits)\n{\n    static const unsigned int kWidth = sizeof(uint8_t);\n\n    Write(Log::Debug(), inIndent, inLevel, inAddress, inUnits, kWidth);\n}\n\n\/**\n *  @brief\n *    Write a log message using the global Debug logger instance, with\n *    no indent and at the default level, containing the memory at the\n *    specified address formatted with the specified width and number\n *    of memory units of that width.\n *\n *  @param[in]  inAddress  The memory address to log.\n *  @param[in]  inUnits    The number of memory units to log.\n *  @param[in]  inWidth    The width, in bytes, to format the memory\n *                         units as: may be one of 1, 2, 4, or 8,\n *                         corresponding to sizeof (uint8_t), sizeof\n *                         (uint16_t), sizeof (uint32_t), or sizeof\n *                         (uint64_t), respectively.\n *\n *  @ingroup memory-utilities\n *\n *\/\nvoid\nWrite(const void * inAddress, size_t inUnits, unsigned int inWidth)\n{\n    static const Log::Indent kIndent = 0;\n    static const Log::Level  kLevel  = 0;\n\n    Write(Log::Debug(), kIndent, kLevel, inAddress, inUnits, inWidth);\n}\n\n\/**\n *  @brief\n *    Write a log message using the global Debug logger instance, with\n *    no indent and at the provided level, containing the memory at the\n *    specified address formatted at the specified width and number of\n *    memory units of that width.\n *\n *  @param[in]  inLevel    The level the current message is to be logged\n *                         at.\n *  @param[in]  inAddress  The memory address to log.\n *  @param[in]  inUnits    The number of memory units to log.\n *  @param[in]  inWidth    The width, in bytes, to format the memory\n *                         units as: may be one of 1, 2, 4, or 8,\n *                         corresponding to sizeof (uint8_t), sizeof\n *                         (uint16_t), sizeof (uint32_t), or sizeof\n *                         (uint64_t), respectively.\n *\n *  @ingroup memory-utilities\n *\n *\/\nvoid\nWrite(Log::Level   inLevel,\n      const void * inAddress,\n      size_t       inUnits,\n      unsigned int inWidth)\n{\n    static const Log::Indent kIndent = 0;\n\n    Write(Log::Debug(), kIndent, inLevel, inAddress, inUnits, inWidth);\n}\n\n\/**\n *  @brief\n *    Write a log message using the global Debug logger instance, with\n *    no indent and at the default level, containing the memory at the\n *    specified address formatted at the specified width and number of\n *    memory units of that width.\n *\n *  @param[in]  inIndent   The level of indendation desired for the\n *                         provided log message.\n *  @param[in]  inLevel    The level the current message is to be logged\n *                         at.\n *  @param[in]  inAddress  The memory address to log.\n *  @param[in]  inUnits    The number of memory units to log.\n *  @param[in]  inWidth    The width, in bytes, to format the memory\n *                         units as: may be one of 1, 2, 4, or 8,\n *                         corresponding to sizeof (uint8_t), sizeof\n *                         (uint16_t), sizeof (uint32_t), or sizeof\n *                         (uint64_t), respectively.\n *\n *  @ingroup memory-utilities\n *\n *\/\nvoid\nWrite(Log::Indent  inIndent,\n      Log::Level   inLevel,\n      const void * inAddress,\n      size_t       inUnits,\n      unsigned int inWidth)\n{\n    Write(Log::Debug(), inIndent, inLevel, inAddress, inUnits, inWidth);\n}\n\n\/**\n *  @brief\n *    Write a log message using the indicated logger, with no indent\n *    and at the default level, containing the memory at the specified\n *    address formatted as 1 byte units with the specified number of\n *    memory units.\n *\n *  @param[in]  inLogger   A reference to the logger with which to write\n *                         the specified contents of memory.\n *  @param[in]  inAddress  The memory address to log.\n *  @param[in]  inUnits    The number of memory units to log.\n *\n *  @ingroup memory-utilities\n *\n *\/\nvoid\nWrite(Logger & inLogger, const void * inAddress, size_t inUnits)\n{\n    static const Log::Indent  kIndent = 0;\n    static const Log::Level   kLevel  = 0;\n    static const unsigned int kWidth  = sizeof(uint8_t);\n\n    Write(inLogger, kIndent, kLevel, inAddress, inUnits, kWidth);\n}\n\n\/**\n *  @brief\n *    Write a log message using the indicated logger, with no indent\n *    and at the provided level, containing the memory at the\n *    specified address formatted as 1 byte units with the specified\n *    number of memory units.\n *\n *  @param[in]  inLogger   A reference to the logger with which to write\n *                         the specified contents of memory.\n *  @param[in]  inLevel    The level the current message is to be logged\n *                         at.\n *  @param[in]  inAddress  The memory address to log.\n *  @param[in]  inUnits    The number of memory units to log.\n *\n *  @ingroup memory-utilities\n *\n *\/\nvoid\nWrite(Logger &     inLogger,\n      Log::Level   inLevel,\n      const void * inAddress,\n      size_t       inUnits)\n{\n    static const Log::Indent  kIndent = 0;\n    static const unsigned int kWidth  = sizeof(uint8_t);\n\n    Write(inLogger, kIndent, inLevel, inAddress, inUnits, kWidth);\n}\n\n\/**\n *  @brief\n *    Write a log message using the indicated logger, with the\n *    provided indent and level, containing the memory at the\n *    specified address formatted as 1 byte units with the specified\n *    number of memory units.\n *\n *  @param[in]  inLogger   A reference to the logger with which to write\n *                         the specified contents of memory.\n *  @param[in]  inIndent   The level of indendation desired for the\n *                         provided log message.\n *  @param[in]  inLevel    The level the current message is to be logged\n *                         at.\n *  @param[in]  inAddress  The memory address to log.\n *  @param[in]  inUnits    The number of memory units to log.\n *\n *  @ingroup memory-utilities\n *\n *\/\nvoid\nWrite(Logger &     inLogger,\n      Log::Indent  inIndent,\n      Log::Level   inLevel,\n      const void * inAddress,\n      size_t       inUnits)\n{\n    static const unsigned int kWidth = sizeof(uint8_t);\n\n    Write(inLogger, inIndent, inLevel, inAddress, inUnits, kWidth);\n}\n\n\/**\n *  @brief\n *    Write a log message using the indicated logger, with no indent\n *    and at the default level, containing the memory at the specified\n *    address formatted with the specified width and number of memory\n *    units of that width.\n *\n *  @param[in]  inLogger   A reference to the logger with which to write\n *                         the specified contents of memory.\n *  @param[in]  inAddress  The memory address to log.\n *  @param[in]  inUnits    The number of memory units to log.\n *  @param[in]  inWidth    The width, in bytes, to format the memory\n *                         units as: may be one of 1, 2, 4, or 8,\n *                         corresponding to sizeof (uint8_t), sizeof\n *                         (uint16_t), sizeof (uint32_t), or sizeof\n *                         (uint64_t), respectively.\n *\n *  @ingroup memory-utilities\n *\n *\/\nvoid\nWrite(Logger &     inLogger,\n      const void * inAddress,\n      size_t       inUnits,\n      unsigned int inWidth)\n{\n    static const Log::Indent kIndent = 0;\n    static const Log::Level  kLevel  = 0;\n\n    Write(inLogger, kIndent, kLevel, inAddress, inUnits, inWidth);\n}\n\n\/**\n *  @brief\n *    Write a log message using the indicated logger, with no indent\n *    and at the provided level, containing the memory at the\n *    specified address formatted at the specified width and number of\n *    memory units of that width.\n *\n *  @param[in]  inLogger   A reference to the logger with which to write\n *                         the specified contents of memory.\n *  @param[in]  inLevel    The level the current message is to be logged\n *                         at.\n *  @param[in]  inAddress  The memory address to log.\n *  @param[in]  inUnits    The number of memory units to log.\n *  @param[in]  inWidth    The width, in bytes, to format the memory\n *                         units as: may be one of 1, 2, 4, or 8,\n *                         corresponding to sizeof (uint8_t), sizeof\n *                         (uint16_t), sizeof (uint32_t), or sizeof\n *                         (uint64_t), respectively.\n *\n *  @ingroup memory-utilities\n *\n *\/\nvoid\nWrite(Logger &     inLogger,\n      Log::Level   inLevel,\n      const void * inAddress,\n      size_t       inUnits,\n      unsigned int inWidth)\n{\n    static const Log::Indent kIndent = 0;\n\n    Write(inLogger, kIndent, inLevel, inAddress, inUnits, inWidth);\n}\n\nstatic inline void\nWriteAddress(Log::Logger &       inLogger,\n             const Log::Indent & inIndent,\n             const Log::Level &  inLevel,\n             void const * const  inAddress)\n{\n    inLogger.Write(inIndent,\n                   inLevel,\n                   \"%*p: \",\n                   static_cast<int>(sizeof(inAddress)),\n                   inAddress);\n}\n\nstatic inline void\nWriteData(Log::Logger &        inLogger,\n          const Log::Indent &  inIndent,\n          const Log::Level &   inLevel,\n          const uint64_t &     inData,\n          const unsigned int & inWidth)\n{\n    \/*\n     * The more succinct approach to this would have been:\n     *\n     *     inLogger.Write(inIndent,\n     *                    inLevel,\n     *                    \"%.*x \",\n     *                    inWidth << 1,\n     *                    data);\n     *\n     * however, this does not seem to work correctly and portably for\n     * 64-bit types. Consequently, we need to use literal,\n     * width-specific format specifiers from inttypes.h.\n     *\n     *\/\n\n    switch (inWidth) {\n\n    case 1:\n        inLogger.Write(inIndent, inLevel, \"%02\"  PRIx8  \" \", static_cast<uint8_t>(inData));\n        break;\n\n    case 2:\n        inLogger.Write(inIndent, inLevel, \"%04\"  PRIx16 \" \", static_cast<uint16_t>(inData));\n        break;\n\n    case 4:\n        inLogger.Write(inIndent, inLevel, \"%08\"  PRIx32 \" \", static_cast<uint32_t>(inData));\n        break;\n\n    case 8:\n        inLogger.Write(inIndent, inLevel, \"%016\" PRIx64 \" \", static_cast<uint64_t>(inData));\n        break;\n\n    default:\n        break;\n\n    }\n}\n\nstatic inline void\nWriteFill(Log::Logger &        inLogger,\n          const Log::Indent &  inIndent,\n          const Log::Level &   inLevel,\n          const unsigned int & inWidth)\n{\n    static const char * const kFill = \"  \";\n\n    inLogger.Write(inIndent, inLevel, \"%*s \", inWidth << 1, kFill);\n}\n\nstatic inline void\nWriteASCII(Log::Logger &       inLogger,\n           const Log::Indent & inIndent,\n           const Log::Level &  inLevel,\n           const std::string & inAscii)\n{\n    inLogger.Write(inIndent, inLevel, \"'%s'\\n\", inAscii.c_str());\n}\n\n\/**\n *  @brief\n *    Write a log message using the indicated logger, with no indent\n *    and at the default level, containing the memory at the specified\n *    address formatted at the specified width and number of memory\n *    units of that width.\n *\n *  @param[in]  inLogger   A reference to the logger with which to write\n *                         the specified contents of memory.\n *  @param[in]  inIndent   The level of indendation desired for the\n *                         provided log message.\n *  @param[in]  inLevel    The level the current message is to be logged\n *                         at.\n *  @param[in]  inAddress  The memory address to log.\n *  @param[in]  inUnits    The number of memory units to log.\n *  @param[in]  inWidth    The width, in bytes, to format the memory\n *                         units as: may be one of 1, 2, 4, or 8,\n *                         corresponding to sizeof (uint8_t), sizeof\n *                         (uint16_t), sizeof (uint32_t), or sizeof\n *                         (uint64_t), respectively.\n *\n *  @ingroup memory-utilities\n *\n *\/\nvoid\nWrite(Logger &     inLogger,\n      Log::Indent  inIndent,\n      Log::Level   inLevel,\n      const void * inAddress,\n      size_t       inUnits,\n      unsigned int inWidth)\n{\n    const size_t    kDensity = 16;\n    const size_t    lSize    = inUnits * inWidth;\n    uint64_t        data     = 0;\n    size_t          fill;\n    string          ascii;\n    uint8_t const * p;\n\n    \/* Determine the amount of fill to complete a line *\/\n\n    if ((lSize % kDensity) != 0) {\n        fill = kDensity - (lSize % kDensity);\n    } else {\n        fill = 0;\n    }\n\n    p = static_cast<uint8_t const *>(inAddress);\n\n    for (unsigned int i = 0; i < (lSize + fill); i += inWidth) {\n\n        \/*\n         * Grab the 1, 2, 4 or 8 byte quantity to display; otherwise,\n         * there is nothing to do but return early.\n         *\/\n\n        switch (inWidth) {\n\n        case 1:     data = *reinterpret_cast<const uint8_t *>(p);     break;\n        case 2:     data = *reinterpret_cast<const uint16_t *>(p);    break;\n        case 4:     data = *reinterpret_cast<const uint32_t *>(p);    break;\n        case 8:     data = *reinterpret_cast<const uint64_t *>(p);    break;\n\n        default:    return;\n\n        }\n\n        \/* Decode the data into an ASCII represenation *\/\n\n        for (unsigned int k = 0; k < inWidth; k++) {\n\n            if (i < lSize) {\n                const char c = static_cast<char>(*p++);\n\n                ascii += ((isprint(c) || c == ' ') ? c : '.');\n\n            } else {\n                ascii += '.';\n\n            }\n        }\n\n        \/* Print the address\/offset label *\/\n\n        if (i % kDensity == 0) {\n            WriteAddress(inLogger, inIndent, inLevel, p);\n        }\n\n        \/* Print the data or fill byte(s) *\/\n\n        if (i < lSize) {\n            WriteData(inLogger, inIndent, inLevel, data, inWidth);\n\n        } else {\n            WriteFill(inLogger, inIndent, inLevel, inWidth);\n\n        }\n\n        \/* Print the decoded ASCII representation *\/\n\n        if (((i + inWidth) % kDensity) == 0) {\n            WriteASCII(inLogger, inIndent, inLevel, ascii);\n\n            ascii.clear();\n        }\n    }\n}\n\n}; \/\/ namespace Memory\n\n}; \/\/ namespace Utilities\n\n}; \/\/ namespace Log\n\n}; \/\/ namespace Nuovations\n","avg_line_length":31.0303571429,"max_line_length":92,"alphanum_fraction":0.5979167866,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4985,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include <algorithm>  \/\/ sort\n#include <iostream>   \/\/ cin y cout\n#include <vector>\n#include <cmath>      \/\/ abs()\n\/\/ #include <chrono>\n\n#include \"..\/..\/sources\/Point.hpp\"\n\n\n\/\/ Auxiliar para ordenar vector de puntos ascendentemente por valor en eje x.\nbool asc_x (const gal::Point &i, const gal::Point &j)\n{\n    int num_grande = 100;\n\n    return (i.get_x() * num_grande + i.get_y()) < (j.get_x() * num_grande + j.get_y());\n}\n\n\n\/\/ Auxiliar en encontrar el punto mas lejano dado un segmento.\ndouble distance_p(const gal::Point &a, const gal::Point &b, const gal::Point &p)\n{\n    return std::abs(((p.get_y() - a.get_y()) * (b.get_x() - a.get_x())) -\n                    ((b.get_y() - a.get_y()) * (p.get_x() - a.get_x())));\n}\n\n\n\/\/ Auxiliar en encontrar de qu\u00e9 lado se encuentra punto dado un segmento.\nint find_side(const gal::Point &a, const gal::Point &b, const gal::Point &p)\n{\n    int val = (((p.get_y() - a.get_y()) * (b.get_x() - a.get_x())) -\n               ((b.get_y() - a.get_y()) * (p.get_x() - a.get_x())));\n\n    if (val > 0)      { return 1; }\n    else if (val < 0) { return -1; }\n    else              { return 0; }\n}\n\n\n\/\/ Encuentra puntos en cerco convexo de los puntos\n\/\/ a la derecha del segmento AB orientado de A a B.\nvoid find_hull(std::vector<gal::Point> points, const gal::Point a,\n                const gal::Point b, std::vector<gal::Point> &convex_points)\n{\n    if (points.empty()) { return; }\n\n    int ind;\n    int max_dist = 0;\n\n    \/\/ Se busca el punto m\u00e1s lejano del segmento AB y se agrega al cerco.\n    for (int i = 0; i < points.size(); ++i)\n    {\n        int temp = distance_p(a, b, points[i]);\n        if (temp > max_dist)\n        {\n            ind = i;\n            max_dist = temp;\n        }\n    }\n\n    convex_points.push_back(points[ind]);\n    gal::Point c = points[ind];\n\n    \/*Los tres puntos A, B, C, particionan los puntos que quedan en 3:\n     * S0, atoc, y ctob, donde S0 son los puntos dentro del triangulo ABC,\n     * atoc son los puntos a la derecha del segmento AC orientado de A a C,\n     * y ctob son los puntos a la derecha del segmento BC orientado de B a C.*\/\n    std::vector<gal::Point> atoc;\n    std::vector<gal::Point> ctob;\n\n    for (int i = 0; i < points.size(); ++i)\n    {\n        if (find_side(a, c, points[i]) == -1)\n        {\n            atoc.push_back(points[i]);\n        }\n        if (find_side(c, b, points[i]) == -1)\n        {\n            ctob.push_back(points[i]);\n        }\n    }\n\n    find_hull(atoc, a, c, convex_points);\n    find_hull(ctob, c, b, convex_points);\n}\n\n\nvoid print_hull(std::vector<gal::Point> &points)\n{\n    if (points.size() < 3)\n    {\n        std::cout << \"No se puede hacer un cervo convexo con menos de 3 puntos en el plano.\" << std::endl;\n        return;\n    }\n\n    \/* Habiendo ordenado ascendentemente por los valores en el eje x, podemos\n     * afirmar que los valores de los extremos formar\u00e1n parte del cerco. *\/\n    std::vector<gal::Point> convex_points;\n\n    convex_points.push_back(points.front()); \/\/ A\n    convex_points.push_back(points.back());  \/\/ B\n\n    \/* El segmento AB divide los (n - 2) puntos\n     * que sobran en dos grupos: atob y btoa. *\/\n    std::vector<gal::Point> atob;\n    std::vector<gal::Point> btoa;\n\n    for (int i = 0; i < points.size(); ++i)\n    {\n        if (find_side(convex_points[0], convex_points[1], points[i]) == 1)\n        {\n            btoa.push_back(points[i]);\n        }\n        else if (find_side(convex_points[0], convex_points[1], points[i]) == -1)\n        {\n            atob.push_back(points[i]);\n        }\n    }\n\n    find_hull(atob, convex_points[0], convex_points[1], convex_points);\n    find_hull(btoa, convex_points[1], convex_points[0], convex_points);\n\n    std::cout << \"Los puntos que conforman el cerco convexo son:\" << std::endl;\n    std::sort(convex_points.begin(), convex_points.end(), asc_x);\n\n    while (!convex_points.empty())\n    {\n        std::cout << convex_points[0] << std::endl;\n        convex_points.erase(convex_points.begin());\n    }\n\n}\n\n\nint main(int argc, char const *argv[])\n{\n    \/\/ auto start = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\n\\n\\n\\t\\t-----INICIO PROGRAMA FIGURAS CONVEXAS-----\\n\\n\" << std::endl;\n\n\n    std::vector<gal::Point> points;\n    gal::Point p;\n\n    \/\/ Generando 10 puntos en plano xy\n\t\tp.set_xy(-2, 4);  points.push_back(p);\n    p.set_xy(-1, -3); points.push_back(p);\n\n    std::cout << \"En este plano hay \" << points.size() << \" puntos.\" << std::endl;\n    std::sort(points.begin(), points.end(), asc_x);\n\n    for (auto &point : points)\n    {\n        std::cout << point << std::endl;\n    }\n\n    print_hull(points);\n\n    \/\/ auto stop = std::chrono::high_resolution_clock::now(); \/\/ Aqui se guarda el tiempo en ese momento\n    \/\/ auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);\n    \/\/ std::cout << duration.count() << \" microsegundos.\\n\" << std::endl;\n\n    std::cout << \"\\n\\n\\t\\t----PROGRAMA FIGURAS CONVEXAS FINALIZADO----\\n\" << std::endl;\n    return 0;\n}\n","avg_line_length":30.3963414634,"max_line_length":106,"alphanum_fraction":0.584553661,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":21307,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Name:        svg.cpp\n\/\/ Purpose:     SVG sample\n\/\/ Author:      Chris Elliott\n\/\/ Modified by:\n\/\/ RCS-ID:      $Id$\n\/\/ Licence:     wxWindows licence\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#if wxUSE_SVG\n\n#ifndef WX_PRECOMP\n    #include \"wx\/dcmemory.h\"\n    #include \"wx\/dcscreen.h\"\n    #include \"wx\/icon.h\"\n    #include \"wx\/image.h\"\n#endif\n\n#include \"wx\/dcsvg.h\"\n#include \"wx\/wfstream.h\"\n#include \"wx\/filename.h\"\n\n#define wxSVG_DEBUG false\n\/\/ or true to see the calls being executed\n\n#define newline        wxString(wxT(\"\\n\"))\n#define space          wxString(wxT(\" \"))\n#define semicolon      wxString(wxT(\";\"))\n#define wx_round(a)    (int)((a)+.5)\n\n\n\/\/ ----------------------------------------------------------\n\/\/ Global utilities\n\/\/ ----------------------------------------------------------\n\nstatic inline double DegToRad(double deg) { return (deg * M_PI) \/ 180.0; }\n\nwxString wxColStr ( wxColour c )\n{\n    unsigned char r, g, b;\n    r = c.Red ();\n    g = c.Green ();\n    b = c. Blue ();\n\n    \/\/ possible Unicode bug here\n    wxString s = wxDecToHex(r) + wxDecToHex(g) + wxDecToHex(b);\n    return s;\n}\n\n\nwxString wxBrushString ( wxColour c, int style )\n{\n    wxString s = wxT(\"fill:#\") + wxColStr (c)  + semicolon + space;\n    switch ( style )\n    {\n        case wxBRUSHSTYLE_SOLID :\n            s = s + wxT(\"fill-opacity:1.0; \");\n            break;\n        case wxBRUSHSTYLE_TRANSPARENT:\n            s = s + wxT(\"fill-opacity:0.0; \");\n            break;\n\n        default :\n            wxASSERT_MSG(false, wxT(\"wxSVGFileDC::Requested Brush Style not available\"));\n\n    }\n    s = s + newline;\n    return s;\n}\n\n\/\/ ----------------------------------------------------------\n\/\/ wxSVGFileDCImpl\n\/\/ ----------------------------------------------------------\n\nIMPLEMENT_ABSTRACT_CLASS(wxSVGFileDCImpl, wxDC)\n\nwxSVGFileDCImpl::wxSVGFileDCImpl( wxSVGFileDC *owner, const wxString &filename,\n                    int width, int height, double dpi ) :\n        wxDCImpl( owner )\n    {\n        Init( filename, width, height, dpi );\n    }\n\nvoid wxSVGFileDCImpl::Init (const wxString &filename, int Width, int Height, double dpi)\n{\n    m_width = Width;\n    m_height = Height;\n\n    m_dpi = dpi;\n\n    m_OK = true;\n\n    m_mm_to_pix_x = dpi\/25.4;\n    m_mm_to_pix_y = dpi\/25.4;\n\n    m_backgroundBrush = *wxTRANSPARENT_BRUSH;\n    m_textForegroundColour = *wxBLACK;\n    m_textBackgroundColour = *wxWHITE;\n    m_colour = wxColourDisplay();\n\n    m_pen   = *wxBLACK_PEN;\n    m_font  = *wxNORMAL_FONT;\n    m_brush = *wxWHITE_BRUSH;\n\n    m_graphics_changed = true;\n\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/code here\n\n    m_outfile = new wxFileOutputStream(filename);\n    m_OK = m_outfile->Ok ();\n    if (m_OK)\n    {\n        m_filename = filename;\n        m_sub_images = 0;\n        wxString s;\n        s = wxT(\"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\"); s = s + newline;\n        write(s);\n        s = wxT(\"<!DOCTYPE svg PUBLIC \\\"-\/\/W3C\/\/DTD SVG 20010904\/\/EN\\\" \") + newline;\n        write(s);\n        s = wxT(\"\\\"http:\/\/www.w3.org\/TR\/2001\/REC-SVG-20010904\/DTD\/svg10.dtd\\\"> \") + newline;\n        write(s);\n        s =  wxT(\"<svg xmlns=\\\"http:\/\/www.w3.org\/2000\/svg\\\" xmlns:xlink=\\\"http:\/\/www.w3.org\/1999\/xlink\\\" \") + newline;\n        write(s);\n        s.Printf( wxT(\"    width=\\\"%.2gcm\\\" height=\\\"%.2gcm\\\" viewBox=\\\"0 0 %d %d \\\"> \\n\"), float(Width)\/dpi*2.54, float(Height)\/dpi*2.54, Width, Height );\n        write(s);\n        s = wxT(\"<title>SVG Picture created as \") + wxFileName(filename).GetFullName() + wxT(\" <\/title>\") + newline;\n        write(s);\n        s = wxString (wxT(\"<desc>Picture generated by wxSVG \")) + wxSVGVersion + wxT(\" <\/desc>\")+ newline;\n        write(s);\n        s =  wxT(\"<g style=\\\"fill:black; stroke:black; stroke-width:1\\\">\") + newline;\n        write(s);\n    }\n}\n\nwxSVGFileDCImpl::~wxSVGFileDCImpl()\n{\n    wxString s = wxT(\"<\/g> \\n<\/svg> \\n\");\n    write(s);\n    delete m_outfile;\n}\n\nvoid wxSVGFileDCImpl::DoGetSizeMM( int *width, int *height ) const\n{\n    if (width)\n        *width = wxRound( (double)m_width \/ m_mm_to_pix_x );\n\n    if (height)\n        *height = wxRound( (double)m_height \/ m_mm_to_pix_y );\n}\n\nwxSize wxSVGFileDCImpl::GetPPI() const\n{\n    return wxSize( wxRound(m_dpi), wxRound(m_dpi) );\n}\n\nvoid wxSVGFileDCImpl::DoDrawLine (wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2)\n{\n    if (m_graphics_changed) NewGraphics ();\n    wxString s;\n    s.Printf ( wxT(\"<path d=\\\"M%d %d L%d %d\\\" \/> \\n\"), x1,y1,x2,y2 );\n    if (m_OK)\n    {\n        write(s);\n    }\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::DrawLine Call executed\"));\n    CalcBoundingBox(x1, y1);\n    CalcBoundingBox(x2, y2);\n    return;\n}\n\nvoid wxSVGFileDCImpl::DoDrawLines(int n, wxPoint points[], wxCoord xoffset , wxCoord yoffset )\n{\n    for ( int i = 1; i < n; i++ )\n    {\n        DoDrawLine ( points [i-1].x + xoffset, points [i-1].y + yoffset,\n            points [ i ].x + xoffset, points [ i ].y + yoffset );\n    }\n}\n\nvoid wxSVGFileDCImpl::DoDrawPoint (wxCoord x1, wxCoord y1)\n{\n    wxString s;\n    if (m_graphics_changed) NewGraphics ();\n    s = wxT(\"<g style = \\\"stroke-linecap:round;\\\" > \") + newline;\n    write(s);\n    DoDrawLine ( x1,y1,x1,y1 );\n    s = wxT(\"<\/g>\");\n    write(s);\n}\n\nvoid wxSVGFileDCImpl::DoDrawCheckMark(wxCoord x1, wxCoord y1, wxCoord width, wxCoord height)\n{\n    wxDCImpl::DoDrawCheckMark (x1,y1,width,height);\n}\n\nvoid wxSVGFileDCImpl::DoDrawText(const wxString& text, wxCoord x1, wxCoord y1)\n{\n    DoDrawRotatedText(text, x1,y1,0.0);\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::DrawText Call executed\"));\n}\n\nvoid wxSVGFileDCImpl::DoDrawRotatedText(const wxString& sText, wxCoord x, wxCoord y, double angle)\n{\n    \/\/known bug; if the font is drawn in a scaled DC, it will not behave exactly as wxMSW\n    if (m_graphics_changed) NewGraphics ();\n    wxString s, sTmp;\n\n    \/\/ calculate bounding box\n    wxCoord w, h, desc;\n    DoGetTextExtent(sText, &w, &h, &desc);\n\n    double rad = DegToRad(angle);\n\n    \/\/ wxT(\"upper left\") and wxT(\"upper right\")\n    CalcBoundingBox(x, y);\n    CalcBoundingBox((wxCoord)(x + w*cos(rad)), (wxCoord)(y - h*sin(rad)));\n\n    \/\/ wxT(\"bottom left\") and wxT(\"bottom right\")\n    x += (wxCoord)(h*sin(rad));\n    y += (wxCoord)(h*cos(rad));\n    CalcBoundingBox(x, y);\n    CalcBoundingBox((wxCoord)(x + h*sin(rad)), (wxCoord)(y + h*cos(rad)));\n\n    if (m_backgroundMode == wxBRUSHSTYLE_SOLID)\n    {\n        \/\/ draw background first\n        \/\/ just like DoDrawRectangle except we pass the text color to it and set the border to a 1 pixel wide text background\n\n        wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::Draw Rotated Text Call plotting text background\"));\n        sTmp.Printf ( wxT(\" <rect x=\\\"%d\\\" y=\\\"%d\\\" width=\\\"%d\\\" height=\\\"%d\\\"  \"), x,y+desc-h, w, h );\n        s = sTmp + wxT(\"style=\\\"fill:#\") + wxColStr (m_textBackgroundColour) + wxT(\"; \");\n        s = s + wxT(\"stroke-width:1; stroke:#\") + wxColStr (m_textBackgroundColour) + wxT(\"; \");\n        sTmp.Printf ( wxT(\"\\\" transform=\\\"rotate( %.2g %d %d )  \\\">\"), -angle, x,y );\n        s = s + sTmp + newline;\n        write(s);\n    }\n    \/\/now do the text itself\n    s.Printf (wxT(\" <text x=\\\"%d\\\" y=\\\"%d\\\" \"),x,y );\n\n    sTmp = m_font.GetFaceName ();\n    if (sTmp.Len () > 0)  s = s + wxT(\"style=\\\"font-family:\") + sTmp + wxT(\"; \");\n    else s = s + wxT(\"style=\\\" \");\n\n    wxString fontweights [3] = { wxT(\"normal\"), wxT(\"lighter\"), wxT(\"bold\") };\n    s = s + wxT(\"font-weight:\") + fontweights[m_font.GetWeight() - wxNORMAL] + semicolon + space;\n\n    wxString fontstyles [5] = { wxT(\"normal\"), wxT(\"style error\"), wxT(\"style error\"), wxT(\"italic\"), wxT(\"oblique\") };\n    s = s + wxT(\"font-style:\") + fontstyles[m_font.GetStyle() - wxNORMAL] + semicolon  + space;\n\n    sTmp.Printf (wxT(\"font-size:%dpt; fill:#\"), m_font.GetPointSize () );\n    s = s + sTmp;\n    s = s + wxColStr (m_textForegroundColour) + wxT(\"; stroke:#\") + wxColStr (m_textForegroundColour) + wxT(\"; \");\n    sTmp.Printf ( wxT(\"stroke-width:0;\\\"  transform=\\\"rotate( %.2g %d %d )  \\\" >\"),  -angle, x,y );\n    s = s + sTmp + sText + wxT(\"<\/text> \") + newline;\n    if (m_OK)\n    {\n        write(s);\n    }\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::DrawRotatedText Call executed\"));\n}\n\nvoid wxSVGFileDCImpl::DoDrawRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height)\n{\n    DoDrawRoundedRectangle(x, y, width, height, 0);\n}\n\nvoid wxSVGFileDCImpl::DoDrawRoundedRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height, double radius )\n\n{\n    if (m_graphics_changed) NewGraphics ();\n    wxString s;\n\n    s.Printf ( wxT(\" <rect x=\\\"%d\\\" y=\\\"%d\\\" width=\\\"%d\\\" height=\\\"%d\\\" rx=\\\"%.2g\\\" \"),\n            x, y, width, height, radius );\n\n    s = s + wxT(\" \/> \") + newline;\n    write(s);\n\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::DoDrawRoundedRectangle Call executed\"));\n    CalcBoundingBox(x, y);\n    CalcBoundingBox(x + width, y + height);\n}\n\nvoid wxSVGFileDCImpl::DoDrawPolygon(int n, wxPoint points[],\n                                    wxCoord xoffset, wxCoord yoffset,\n                                    wxPolygonFillMode fillStyle)\n{\n    if (m_graphics_changed) NewGraphics ();\n    wxString s, sTmp;\n    s = wxT(\"<polygon style=\\\"\");\n    if ( fillStyle == wxODDEVEN_RULE )\n        s = s + wxT(\"fill-rule:evenodd; \");\n    else\n        s = s + wxT(\"fill-rule:nonzero; \");\n\n    s = s  + wxT(\"\\\" \\npoints=\\\"\");\n\n    for (int i = 0; i < n;  i++)\n    {\n        sTmp.Printf ( wxT(\"%d,%d\"), points [i].x+xoffset, points[i].y+yoffset );\n        s = s + sTmp + newline;\n        CalcBoundingBox ( points [i].x+xoffset, points[i].y+yoffset);\n    }\n    s = s + wxT(\"\\\" \/> \");\n    s = s + newline;\n    write(s);\n\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::DoDrawPolygon Call executed\"));\n}\n\nvoid wxSVGFileDCImpl::DoDrawEllipse (wxCoord x, wxCoord y, wxCoord width, wxCoord height)\n\n{\n    if (m_graphics_changed) NewGraphics ();\n\n    int rh = height \/2;\n    int rw = width  \/2;\n\n    wxString s;\n    s.Printf ( wxT(\"<ellipse cx=\\\"%d\\\" cy=\\\"%d\\\" rx=\\\"%d\\\" ry=\\\"%d\\\" \"), x+rw,y+rh, rw, rh );\n    s = s + wxT(\" \/> \") + newline;\n\n    write(s);\n\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::DoDrawEllipse Call executed\"));\n    CalcBoundingBox(x, y);\n    CalcBoundingBox(x + width, y + height);\n}\n\nvoid wxSVGFileDCImpl::DoDrawArc(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, wxCoord xc, wxCoord yc)\n{\n    \/* Draws an arc of a circle, centred on (xc, yc), with starting point\n    (x1, y1) and ending at (x2, y2). The current pen is used for the outline\n    and the current brush for filling the shape.\n\n    The arc is drawn in an anticlockwise direction from the start point to\n    the end point.\n\n    Might be better described as Pie drawing *\/\n\n    if (m_graphics_changed) NewGraphics ();\n    wxString s;\n\n    \/\/ we need the radius of the circle which has two estimates\n    double r1 = sqrt ( double( (x1-xc)*(x1-xc) ) + double( (y1-yc)*(y1-yc) ) );\n    double r2 = sqrt ( double( (x2-xc)*(x2-xc) ) + double( (y2-yc)*(y2-yc) ) );\n\n    wxASSERT_MSG( (fabs ( r2-r1 ) <= 3), wxT(\"wxSVGFileDC::DoDrawArc Error in getting radii of circle\"));\n    if ( fabs ( r2-r1 ) > 3 )    \/\/pixels\n    {\n        s = wxT(\"<!--- wxSVGFileDC::DoDrawArc Error in getting radii of circle --> \\n\");\n        write(s);\n    }\n\n    double theta1 = atan2((double)(yc-y1),(double)(x1-xc));\n    if ( theta1 < 0 ) theta1 = theta1 + M_PI * 2;\n    double theta2 = atan2((double)(yc-y2), (double)(x2-xc));\n    if ( theta2 < 0 ) theta2 = theta2 + M_PI * 2;\n    if ( theta2 < theta1 ) theta2 = theta2 + M_PI *2;\n\n    int fArc;                  \/\/ flag for large or small arc 0 means less than 180 degrees\n    if ( fabs(theta2 - theta1) > M_PI ) fArc = 1; else fArc = 0;\n\n    int fSweep = 0;             \/\/ flag for sweep always 0\n\n    s.Printf ( wxT(\"<path d=\\\"M%d %d A%.2g %.2g 0.0 %d %d %d %d L%d %d z \"),\n        x1,y1, r1, r2, fArc, fSweep, x2, y2, xc, yc );\n\n    \/\/ the z means close the path and fill\n    s = s + wxT(\" \\\" \/> \") + newline;\n\n\n    if (m_OK)\n    {\n        write(s);\n    }\n\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::DoDrawArc Call executed\"));\n}\n\nvoid wxSVGFileDCImpl::DoDrawEllipticArc(wxCoord x,wxCoord y,wxCoord w,wxCoord h,double sa,double ea)\n{\n    \/*\n    Draws an arc of an ellipse. The current pen is used for drawing the arc\n    and the current brush is used for drawing the pie. This function is\n    currently only available for X window and PostScript device contexts.\n\n    x and y specify the x and y coordinates of the upper-left corner of the\n    rectangle that contains the ellipse.\n\n    width and height specify the width and height of the rectangle that\n    contains the ellipse.\n\n    start and end specify the start and end of the arc relative to the\n    three-o'clock position from the center of the rectangle. Angles are\n    specified in degrees (360 is a complete circle). Positive values mean\n    counter-clockwise motion. If start is equal to end, a complete ellipse\n    will be drawn. *\/\n\n    \/\/known bug: SVG draws with the current pen along the radii, but this does not happen in wxMSW\n\n    if (m_graphics_changed) NewGraphics ();\n\n    wxString s;\n    \/\/radius\n    double rx = w \/ 2;\n    double ry = h \/ 2;\n    \/\/ center\n    double xc = x + rx;\n    double yc = y + ry;\n\n    double xs, ys, xe, ye;\n    xs = xc + rx * cos (DegToRad(sa));\n    xe = xc + rx * cos (DegToRad(ea));\n    ys = yc - ry * sin (DegToRad(sa));\n    ye = yc - ry * sin (DegToRad(ea));\n\n    \/\/\/now same as circle arc...\n\n    double theta1 = atan2(ys-yc, xs-xc);\n    double theta2 = atan2(ye-yc, xe-xc);\n\n    int fArc;                  \/\/ flag for large or small arc 0 means less than 180 degrees\n    if ( (theta2 - theta1) > 0 ) fArc = 1; else fArc = 0;\n\n    int fSweep;\n    if ( fabs(theta2 - theta1) > M_PI) fSweep = 1; else fSweep = 0;\n\n    s.Printf ( wxT(\"<path d=\\\"M%d %d A%d %d 0.0 %d %d  %d %d L %d %d z \"),\n        int(xs), int(ys), int(rx), int(ry),\n        fArc, fSweep, int(xe), int(ye), int(xc), int(yc)  );\n\n\n    s = s + wxT(\" \\\" \/> \") + newline;\n\n    if (m_OK)\n    {\n        write(s);\n    }\n\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::DoDrawEllipticArc Call executed\"));\n}\n\nvoid wxSVGFileDCImpl::DoGetTextExtent(const wxString& string, wxCoord *w, wxCoord *h, wxCoord *descent , wxCoord *externalLeading , const wxFont *font) const\n\n{\n    wxScreenDC sDC;\n\n    sDC.SetFont (m_font);\n    if ( font != NULL ) sDC.SetFont ( *font );\n    sDC.GetTextExtent(string, w,  h, descent, externalLeading );\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::GetTextExtent Call executed\"));\n}\n\nwxCoord wxSVGFileDCImpl::GetCharHeight() const\n\n{\n    wxScreenDC sDC;\n    sDC.SetFont (m_font);\n\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::GetCharHeight Call executing\"));\n    return ( sDC.GetCharHeight() );\n\n}\n\nwxCoord wxSVGFileDCImpl::GetCharWidth() const\n{\n    wxScreenDC sDC;\n    sDC.SetFont (m_font);\n\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::GetCharWidth Call executing\"));\n    return ( sDC.GetCharWidth() );\n\n}\n\n\n\/\/ ----------------------------------------------------------\n\/\/ wxSVGFileDCImpl - set functions\n\/\/ ----------------------------------------------------------\n\nvoid wxSVGFileDCImpl::SetBackground( const wxBrush &brush )\n{\n\n    m_backgroundBrush = brush;\n    return;\n}\n\n\nvoid wxSVGFileDCImpl::SetBackgroundMode( int mode )\n{\n    m_backgroundMode = mode;\n    return;\n}\n\n\nvoid wxSVGFileDCImpl::SetBrush(const wxBrush& brush)\n\n{\n    m_brush = brush;\n\n    m_graphics_changed = true;\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::SetBrush Call executed\"));\n}\n\n\nvoid wxSVGFileDCImpl::SetPen(const wxPen& pen)\n{\n    \/\/ width, color, ends, joins : currently implemented\n    \/\/ dashes, stipple :  not implemented\n    m_pen = pen;\n\n    m_graphics_changed = true;\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::SetPen Call executed\"));\n}\n\nvoid wxSVGFileDCImpl::NewGraphics ()\n{\n\n    int w = m_pen.GetWidth ();\n    wxColour c = m_pen.GetColour ();\n\n    wxString s, sBrush, sPenCap, sPenJoin, sPenStyle, sLast, sWarn;\n\n    sBrush = wxT(\"<\/g>\\n<g style=\\\"\") + wxBrushString ( m_brush.GetColour (), m_brush.GetStyle () )\n            + wxT(\"  stroke:#\") + wxColStr (c) + wxT(\"; \");\n\n    switch ( m_pen.GetCap () )\n    {\n        case  wxCAP_PROJECTING :\n            sPenCap = wxT(\"stroke-linecap:square; \");\n            break;\n        case  wxCAP_BUTT :\n            sPenCap = wxT(\"stroke-linecap:butt; \");\n            break;\n        case    wxCAP_ROUND :\n        default :\n            sPenCap = wxT(\"stroke-linecap:round; \");\n    };\n    switch ( m_pen.GetJoin () )\n    {\n        case  wxJOIN_BEVEL :\n            sPenJoin = wxT(\"stroke-linejoin:bevel; \");\n            break;\n        case  wxJOIN_MITER :\n            sPenJoin = wxT(\"stroke-linejoin:miter; \");\n            break;\n        case    wxJOIN_ROUND :\n        default :\n            sPenJoin = wxT(\"stroke-linejoin:round; \");\n    };\n\n    switch ( m_pen.GetStyle () )\n    {\n        case  wxPENSTYLE_SOLID :\n            sPenStyle = wxT(\"stroke-opacity:1.0; stroke-opacity:1.0; \");\n            break;\n        case  wxPENSTYLE_TRANSPARENT :\n            sPenStyle = wxT(\"stroke-opacity:0.0; stroke-opacity:0.0; \");\n            break;\n        default :\n            wxASSERT_MSG(false, wxT(\"wxSVGFileDC::SetPen Call called to set a Style which is not available\"));\n            sWarn = sWarn + wxT(\"<!--- wxSVGFileDC::SetPen Call called to set a Style which is not available --> \\n\");\n    }\n\n    sLast.Printf( wxT(\"stroke-width:%d\\\" \\n   transform=\\\"translate(%.2g %.2g) scale(%.2g %.2g)\\\">\"),\n                w, double(m_logicalOriginX), double(m_logicalOriginY), m_scaleX, m_scaleY  );\n\n    s = sBrush + sPenCap + sPenJoin + sPenStyle + sLast + newline + sWarn;\n    write(s);\n    m_graphics_changed = false;\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::NewGraphics Call executed\"));\n}\n\n\nvoid wxSVGFileDCImpl::SetFont(const wxFont& font)\n\n{\n    m_font = font;\n\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::SetFont Call executed\"));\n}\n\n\/\/ export a bitmap as a raster image in png\nbool wxSVGFileDCImpl::DoBlit(wxCoord xdest, wxCoord ydest, wxCoord width, wxCoord height,\n                        wxDC* source, wxCoord xsrc, wxCoord ysrc,\n                        wxRasterOperationMode logicalFunc \/*= wxCOPY*\/, bool useMask \/*= false*\/,\n                        wxCoord \/*xsrcMask = -1*\/, wxCoord \/*ysrcMask = -1*\/)\n{\n    if (logicalFunc != wxCOPY)\n    {\n        wxASSERT_MSG(false, wxT(\"wxSVGFileDC::DoBlit Call requested nonCopy mode; this is not possible\"));\n        return false;\n    }\n    if (useMask != false)\n    {\n        wxASSERT_MSG(false, wxT(\"wxSVGFileDC::DoBlit Call requested false mask; this is not possible\"));\n        return false;\n    }\n    wxBitmap myBitmap (width, height);\n    wxMemoryDC memDC;\n    memDC.SelectObject( myBitmap );\n    memDC.Blit(0, 0, width, height, source, xsrc, ysrc);\n    memDC.SelectObject( wxNullBitmap );\n    DoDrawBitmap(myBitmap, xdest, ydest);\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::DoBlit Call executed\"));\n    return false;\n}\n\nvoid wxSVGFileDCImpl::DoDrawIcon(const class wxIcon & myIcon, wxCoord x, wxCoord y)\n{\n    wxBitmap myBitmap (myIcon.GetWidth(), myIcon.GetHeight() );\n    wxMemoryDC memDC;\n    memDC.SelectObject( myBitmap );\n    memDC.DrawIcon(myIcon,0,0);\n    memDC.SelectObject( wxNullBitmap );\n    DoDrawBitmap(myBitmap, x, y);\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::DoDrawIcon Call executed\"));\n    return;\n}\n\nvoid wxSVGFileDCImpl::DoDrawBitmap(const class wxBitmap & bmp, wxCoord x, wxCoord y , bool  WXUNUSED(bTransparent) \/*=0*\/ )\n{\n    if (m_graphics_changed) NewGraphics ();\n\n    wxString sTmp, s, sPNG;\n    if ( wxImage::FindHandler(wxBITMAP_TYPE_PNG) == NULL )\n        wxImage::AddHandler(new wxPNGHandler);\n\n\/\/ create suitable file name\n    sTmp.Printf ( wxT(\"_image%d.png\"), m_sub_images);\n    sPNG = m_filename.BeforeLast(wxT('.')) + sTmp;\n    while (wxFile::Exists(sPNG) )\n    {\n        m_sub_images ++;\n        sTmp.Printf ( wxT(\"_image%d.png\"), m_sub_images);\n        sPNG = m_filename.BeforeLast(wxT('.')) + sTmp;\n    }\n\n\/\/create copy of bitmap (wxGTK doesn't like saving a constant bitmap)\n    wxBitmap myBitmap = bmp;\n\/\/save it\n    bool bPNG_OK = myBitmap.SaveFile(sPNG,wxBITMAP_TYPE_PNG);\n\n\/\/ reference the bitmap from the SVG doc\n\/\/ only use filename & ext\n    sPNG = sPNG.AfterLast(wxFileName::GetPathSeparator());\n\n\/\/ reference the bitmap from the SVG doc\n    int w = myBitmap.GetWidth();\n    int h = myBitmap.GetHeight();\n    sTmp.Printf ( wxT(\" <image x=\\\"%d\\\" y=\\\"%d\\\" width=\\\"%dpx\\\" height=\\\"%dpx\\\" \"), x,y,w,h );\n    s = s + sTmp;\n    sTmp.Printf ( wxT(\" xlink:href=\\\"%s\\\"> \\n\"), sPNG.c_str() );\n    s = s + sTmp + wxT(\"<title>Image from wxSVG<\/title>  <\/image>\") + newline;\n\n    if (m_OK && bPNG_OK)\n    {\n        write(s);\n    }\n    m_OK = m_outfile->Ok () && bPNG_OK;\n    wxASSERT_MSG(!wxSVG_DEBUG, wxT(\"wxSVGFileDC::DoDrawBitmap Call executed\"));\n\n    return;\n}\n\nvoid wxSVGFileDCImpl::write(const wxString &s)\n{\n    const wxCharBuffer buf = s.utf8_str();\n    m_outfile->Write(buf, strlen((const char *)buf));\n    m_OK = m_outfile->Ok();\n}\n\n\n#ifdef __BORLANDC__\n#pragma warn .rch\n#pragma warn .ccc\n#endif\n\n#endif \/\/ wxUSE_SVG\n\n","avg_line_length":30.9245283019,"max_line_length":157,"alphanum_fraction":0.5937016004,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3393,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":25.0,"content":"#ifndef __UI_NOTIFICATION_BUBBLE_HEADER\n#define __UI_NOTIFICATION_BUBBLE_HEADER\n\n\n\n\n#include <allegro_flare\/allegro_flare.h>\n#include <AllegroFlare\/Color.hpp>\n#include <allegro_flare\/widget.h>\n#include <allegro_flare\/box.h>\n\n#include <allegro5\/allegro_font.h>\n#include <allegro5\/allegro_primitives.h>\n\n\n\n\nusing namespace allegro_flare;\nusing namespace AllegroFlare;\n\n\n\nclass UINotificationBubble : public UIWidget\n{\nprivate:\n   std::string text;\n   bool paused;\n   float spawn_time, lifespan;\n   float opacity;\n   ALLEGRO_FONT *font;\n\npublic:\n   UINotificationBubble(UIWidget *parent, float x, float y, std::string text)\n      : UIWidget(parent, \"UINotificationBubble\", new UISurfaceAreaBox(x, y, 280, 90))\n      , text(text)\n      , font(Framework::font(\"DroidSerif.ttf 20\"))\n      , spawn_time(Framework::time_now)\n      , lifespan(4.0)\n      , paused(false)\n      , opacity(0)\n   {\n      Framework::motion().cmove_to(&this->opacity, 1.0, 0.5);\n\n      this->surface_area->placement.align.x = 1.0;\n      this->surface_area->placement.align.y = 1.0;\n   }\n\n   ~UINotificationBubble()\n   {\n      Framework::motion().clear_animations_on(&this->opacity);\n   }\n\n   void on_timer()\n   {\n      if (paused || delete_me) return;\n\n      if ((Framework::time_now - spawn_time) > lifespan)\n      {\n         delete_me = true;\n         Framework::motion().cmove_to(&this->opacity, 0, 0.6);\n      }\n   }\n\n   void on_mouse_enter()\n   {\n      if (delete_me) return;\n\n      paused = true;\n      Framework::motion().cmove_to(&this->opacity, 1.0, 0.5);\n   }\n\n   void on_mouse_leave()\n   {\n      if (delete_me) return;\n\n      paused = false;\n      spawn_time  = Framework::time_now;\n   }\n\n   void on_draw()\n   {\n      if (delete_me) return;\n\n      al_draw_filled_rounded_rectangle(0, 0, place.size.x, place.size.y, 6, 6, color::hex(\"#fce566\", opacity));\n      al_draw_text(font, color::hex(\"645710\", opacity), 23, 20, 0, text.c_str());\n   }\n};\n\n\n\n\n#endif\n\n\n\n\nclass NotificationBubbleTestProject : public UIScreen\n{\npublic:\n   float mouse_x;\n   float mouse_y;\n   UIText *bubble_count_text;\n   NotificationBubbleTestProject(Display *display)\n      : UIScreen(display)\n      , mouse_x(display->width()\/2)\n      , mouse_y(display->height()\/2)\n      , bubble_count_text(NULL)\n   {\n      al_set_mouse_xy(display->al_display, mouse_x, mouse_y);\n      new UIText(this, 40, 30, \"Move the mouse and press any key to spawn a NotificationBubble.\");\n      bubble_count_text = new UIText(this, 40, 60, \"Number of active bubbles: 0\");\n   }\n   std::string get_random_quote()\n   {\n      return \"Anyone who considers protocol unimportant has never dealt with a cat.\\n-- R. Heinlein\";\n   }\n   void on_mouse_move(float x, float y, float dx, float dy) override\n   {\n      mouse_x = x;\n      mouse_y = y;\n   }\n   void on_mouse_down() override\n   {\n      new UINotificationBubble(this, mouse_x, mouse_y, get_random_quote());\n   }\n   void primary_timer_func() override\n   {\n      std::string message = \"Number of active bubbles: \";\n      message += tostring(this->num_children());\n      bubble_count_text->set_text(message);\n\n      UIScreen::primary_timer_func();\n   }\n};\n\n\n\n\nint main(int argc, char *argv[])\n{\n   Framework::initialize();\n   Display *display = Framework::create_display(1280, 800, false);\n\n   NotificationBubbleTestProject *proj = new NotificationBubbleTestProject(display);\n\n   Framework::run_loop();\n   return 0;\n}\n\n\n\n\n","avg_line_length":22.1764705882,"max_line_length":111,"alphanum_fraction":0.6578249337,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":52783,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["AML"],"max_stars_count":5.0,"content":"\/*\n* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n* its licensors.\n*\n* For complete copyright and license terms please see the LICENSE at the root of this\n* distribution (the \"License\"). All use of this software is governed by the License,\n* or, if provided, by the license below or the license accompanying this file. Do not\n* remove or modify any license notices. This file is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n*\n*\/\n\/\/ Original file Copyright Crytek GMBH or its affiliates, used under license.\n\n#include \"StdAfx.h\"\n#include \"Inventory.h\"\n#include <IEntitySystem.h>\n#include \"IGameObject.h\"\n#include \"CryAction.h\"\n#include \"ScriptBind_Inventory.h\"\n#include \"IActorSystem.h\"\n#include \"IEntityPoolManager.h\"\n\nDECLARE_DEFAULT_COMPONENT_FACTORY(CInventory, CInventory)\n\n\/\/------------------------------------------------------------------------\nCInventory::CInventory()\n    : m_pActor(0)\n    , m_iteratingListeners(false)\n    , m_ignoreNextClear(false)\n{\n    m_stats.slots.reserve(gEnv->pConsole->GetCVar(\"i_inventory_capacity\")->GetIVal());\n    m_bSerializeLTL = false;\n}\n\n\/\/------------------------------------------------------------------------\nCInventory::~CInventory()\n{\n    CCryAction* pCryAction = static_cast<CCryAction*>(gEnv->pGame->GetIGameFramework());\n    pCryAction->GetInventoryScriptBind()->DetachFrom(this);\n}\n\n\/\/------------------------------------------------------------------------\nbool CInventory::Init(IGameObject* pGameObject)\n{\n    SetGameObject(pGameObject);\n    \/\/ attach script bind\n    CCryAction* pCryAction = static_cast<CCryAction*>(gEnv->pGame->GetIGameFramework());\n    pCryAction->GetInventoryScriptBind()->AttachTo(this);\n\n    m_pGameFrameWork = pCryAction;\n\n    m_pActor = pCryAction->GetIActorSystem()->GetActor(pGameObject->GetEntityId());\n\n    return true;\n}\n\n\/\/------------------------------------------------------------------------\nbool CInventory::ReloadExtension(IGameObject* pGameObject, const SEntitySpawnParams& params)\n{\n    ResetGameObject();\n\n    Destroy();\n\n    return true;\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::PostReloadExtension(IGameObject* pGameObject, const SEntitySpawnParams& params)\n{\n    \/\/ attach script bind\n    CCryAction* pCryAction = static_cast<CCryAction*>(gEnv->pGame->GetIGameFramework());\n    pCryAction->GetInventoryScriptBind()->AttachTo(this);\n\n    m_pActor = pCryAction->GetIActorSystem()->GetActor(pGameObject->GetEntityId());\n}\n\n\/\/------------------------------------------------------------------------\nbool CInventory::GetEntityPoolSignature(TSerialize signature)\n{\n    signature.BeginGroup(\"Inventory\");\n    signature.EndGroup();\n    return true;\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::FullSerialize(TSerialize ser)\n{\n    MEMSTAT_CONTEXT(EMemStatContextTypes::MSC_Other, 0, \"Inventory serialization\");\n\n    IEntityPoolManager* pMgr = gEnv->pEntitySystem->GetIEntityPoolManager();\n\n    if (pMgr && !gEnv->pSystem->IsSerializingFile())\n    {\n        \/\/ Entities being activated from the pool shouldn't\n        \/\/  serialize their inventories. The item ids in the bookmark\n        \/\/  refer to the previous entities which no longer exist, instead the\n        \/\/  actor will have been given a new equipment pack instead.\n        \/\/  In that case just holster the default weapon. We will have to\n        \/\/  select it after on the behavior or on the entity side\n\n        if (ser.IsReading())\n        {\n            EntityId currentItemId = 0;\n            bool isUsing = false;\n\n            ser.Value(\"using\", isUsing);\n            ser.Value(\"CurrentItem\", currentItemId);\n\n            if (currentItemId)\n            {\n                IItem* pItem = m_pGameFrameWork->GetIItemSystem()->GetItem(currentItemId);\n                if (pItem && isUsing && !pItem->IsUsed())\n                {\n                    pItem->Use(GetEntityId());\n\n                    return;\n                }\n            }\n\n            HolsterItem(true);\n        }\n        else\n        {\n            bool isUsing = false;\n            if (IItem* pItem = m_pGameFrameWork->GetIItemSystem()->GetItem(m_stats.currentItemId))\n            {\n                isUsing = pItem->IsUsed() && pItem->GetOwnerId() == GetEntityId();\n            }\n\n            ser.Value(\"using\", isUsing);\n            ser.Value(\"CurrentItem\", m_stats.currentItemId);\n        }\n\n        return;\n    }\n\n    ser.BeginGroup(\"InventoryItems\");\n\n    ser.Value(\"CurrentItem\", m_stats.currentItemId);\n    ser.Value(\"HolsterItem\", m_stats.holsteredItemId);\n    ser.Value(\"LastItem\", m_stats.lastItemId);\n    int s = m_stats.slots.size();\n    ser.Value(\"InventorySize\", s);\n    if (ser.IsReading())\n    {\n        m_stats.slots.resize(s);\n    }\n\n    ser.Value(\"Slots\", m_stats.slots);\n\n    ser.BeginGroup(\"accessorySlots\");\n    int exSize = m_stats.accessorySlots.size();\n    ser.Value(\"Size\", exSize);\n\n    for (int i = 0; i < IInventory::eInventorySlot_Last; ++i)\n    {\n        ser.BeginGroup(\"SlotInfo\");\n        ser.Value(\"slotInfoCount\", m_stats.slotsInfo[i].count);\n        ser.Value(\"slotInfoLastSelected\", m_stats.slotsInfo[i].lastSelected);\n        ser.EndGroup();\n    }\n\n    if (ser.IsReading())\n    {\n        m_stats.accessorySlots.resize(0);\n        if (exSize > 0)\n        {\n            m_stats.accessorySlots.reserve(exSize);\n        }\n    }\n    for (int i = 0; i < exSize; ++i)\n    {\n        string accessoryName;\n        if (ser.IsWriting())\n        {\n            accessoryName = m_stats.accessorySlots[i]->GetName();\n        }\n\n        ser.BeginGroup(\"Class\");\n        ser.Value(\"AccessoryName\", accessoryName);\n        ser.EndGroup();\n\n        if (ser.IsReading())\n        {\n            IEntityClass* pAccessoryClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(accessoryName);\n            CRY_ASSERT(pAccessoryClass);\n            if (pAccessoryClass != NULL)\n            {\n                m_stats.accessorySlots.push_back(pAccessoryClass);\n            }\n        }\n    }\n    ser.EndGroup();\/\/\"accessorySlots\"\n\n    ser.BeginGroup(\"Ammo\");\n    if (ser.IsReading())\n    {\n        m_stats.ammoInfo.clear();\n    }\n\n    TAmmoInfoMap::iterator ammoInfoIt = m_stats.ammoInfo.begin();\n    int ammoAmount = m_stats.ammoInfo.size();\n    ser.Value(\"AmmoAmount\", ammoAmount);\n    for (int i = 0; i < ammoAmount; ++i)\n    {\n        string name;\n        int amount = 0;\n        int capacity = 0;\n        if (ser.IsWriting())\n        {\n            IEntityClass* pAmmoClass = ammoInfoIt->first;\n            CRY_ASSERT(pAmmoClass);\n            name = (pAmmoClass) ? pAmmoClass->GetName() : \"\";\n\n            const SAmmoInfo& ammoInfo = ammoInfoIt->second;\n\n            amount = ammoInfo.GetCount();\n            \/\/users = ammoInfo.GetUserCount();\n            capacity = ammoInfo.GetCapacity();\n            \/\/ Only use this iterator writing. If we're reading, we change the size\n            \/\/ of the map and end up with an out of sync (and invalid) iterator.\n            ++ammoInfoIt;\n        }\n        ser.BeginGroup(\"Ammo\");\n        ser.Value(\"AmmoName\", name);\n        ser.Value(\"Bullets\", amount);\n        ser.Value(\"Capacity\", capacity);\n        ser.EndGroup();\n        if (ser.IsReading())\n        {\n            IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name);\n            CRY_ASSERT(pClass);\n            TAmmoInfoMap::iterator it = m_stats.ammoInfo.find(pClass);\n            if (it == m_stats.ammoInfo.end())\n            {\n                m_stats.ammoInfo[pClass] = SAmmoInfo(amount, capacity);\n            }\n            else\n            {\n                it->second.SetCount(amount);\n                it->second.SetCapacity(capacity);\n            }\n        }\n    }\n    ser.EndGroup();\n\n    \/*\n        ser.BeginGroup(\"CategorySlots\");\n\n        for (TSlotsInfo::iterator it = m_stats.slotsInfo.begin(); it != m_stats.slotsInfo.end(); ++it)\n        {\n            ser.Value(\"Count\", it->second.count);\n        }\n\n        ser.EndGroup();*\/\n\n\n    ser.EndGroup();\n}\n\nvoid CInventory::PostSerialize()\n{\n    for (int i = 0; i < IInventory::eInventorySlot_Last; ++i)\n    {\n        const int itemIndex = FindItem(m_stats.slotsInfo[i].lastSelected);\n\n        \/\/ For whatever reason we don't have this last item in the inventory,\n        \/\/ so find a suitable item in the same slot.\n        if (itemIndex == -1)\n        {\n            const EntityId entityId = GetAnyEntityInSlot(i);\n\n            SetLastSelectedInSlot(entityId);\n        }\n    }\n\n    \/\/ Benito - This is last minute workaround to solve a strange bug:\n    \/\/ If the game is saved while you had equipped a 'heavy weapon' (dynamic one, not present in the level) but this ones is holstered at the moment of save\n    \/\/ when the game is loaded, the item is not restored properly, because the entity does not get a serialize call.\n    \/\/ This code ensures that weapon goes back to the hands of the player, adding as many checks here as possible before doing the final call\n    const bool ownerActorIsClientNotInVehicle = (m_pActor != NULL) && m_pActor->IsClient() && (m_pActor->GetLinkedVehicle() == NULL);\n    if (ownerActorIsClientNotInVehicle)\n    {\n        IItem* pCurrentItem = gEnv->pGame->GetIGameFramework()->GetIItemSystem()->GetItem(m_stats.currentItemId);\n        if ((pCurrentItem != NULL) && (pCurrentItem->GetOwnerId() == 0))\n        {\n            if (pCurrentItem->CanUse(m_pActor->GetEntityId()))\n            {\n                m_stats.currentItemId = 0; \/\/Reset and use it again\n                pCurrentItem->Use(m_pActor->GetEntityId());\n            }\n        }\n    }\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::SerializeInventoryForLevelChange(TSerialize ser)\n{\n    IActor* pActor = GetActor();\n    if (!pActor)\n    {\n        return;\n    }\n\n    if (ser.IsReading())\n    {\n        m_stats.ammoInfo.clear();\n    }\n\n    m_bSerializeLTL = true;\n\n    \/\/Items by class (accessories)\n    ser.BeginGroup(\"accessorySlots\");\n    int exSize = m_stats.accessorySlots.size();\n    ser.Value(\"Size\", exSize);\n\n    if (ser.IsReading())\n    {\n        m_stats.accessorySlots.resize(0);\n        if (exSize > 0)\n        {\n            m_stats.accessorySlots.reserve(exSize);\n        }\n    }\n    for (int i = 0; i < exSize; ++i)\n    {\n        string accessoryName;\n        if (ser.IsWriting())\n        {\n            accessoryName = m_stats.accessorySlots[i]->GetName();\n        }\n\n        ser.BeginGroup(\"Class\");\n        ser.Value(\"AccessoryName\", accessoryName);\n        ser.EndGroup();\n\n        if (ser.IsReading())\n        {\n            IEntityClass* pAccessoryClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(accessoryName);\n            CRY_ASSERT(pAccessoryClass);\n            if (pAccessoryClass)\n            {\n                m_stats.accessorySlots.push_back(pAccessoryClass);\n            }\n        }\n    }\n    ser.EndGroup();\/\/\"accessorySlots\"\n\n    if (ser.IsReading())\n    {\n        for (int r = 0; r < m_stats.slots.size(); ++r)\n        {\n            IItem* pItem = m_pGameFrameWork->GetIItemSystem()->GetItem(m_stats.slots[r]);\n            if (pItem)\n            {\n                pItem->Drop();\n                pItem->GetEntity()->SetFlags(pItem->GetEntity()->GetFlags() | ENTITY_FLAG_UPDATE_HIDDEN);\n                pItem->GetEntity()->Hide(true);\n                gEnv->pEntitySystem->RemoveEntity(m_stats.slots[r]);\n            }\n        }\n    }\n\n    int numItems = 0;\n\n    string currentItemNameOnReading;\n\n    if (ser.IsReading())\n    {\n        m_stats.slots.clear();\n        m_stats.currentItemId = 0;\n        m_stats.holsteredItemId = 0;\n        m_stats.lastItemId = 0;\n\n        string itemName;\n        ser.Value(\"numOfItems\", numItems);\n        for (int i = 0; i < numItems; ++i)\n        {\n            ser.BeginGroup(\"Items\");\n            bool nextItemExists = false;\n            ser.Value(\"nextItemExists\", nextItemExists);\n            if (nextItemExists)\n            {\n                ser.Value(\"ItemName\", itemName);\n                EntityId id = m_pGameFrameWork->GetIItemSystem()->GiveItem(pActor, itemName.c_str(), false, false, false);\n                IItem* pItem = m_pGameFrameWork->GetIItemSystem()->GetItem(id);\n                if (pItem)\n                {\n                    \/\/actual serialization\n                    pItem->SerializeLTL(ser);\n                }\n                else\n                {\n                    CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_ERROR, \"Couldn't spawn inventory item %s, got id %i.\", itemName.c_str(), id);\n                }\n            }\n\n            ser.EndGroup();\n        }\n        ser.Value(\"CurrentItemName\", itemName);\n        if (_stricmp(itemName.c_str(), \"none\"))\n        {\n            currentItemNameOnReading = itemName;\n            IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(itemName.c_str());\n            if (pClass)\n            {\n                if (IItem* pItem = m_pGameFrameWork->GetIItemSystem()->GetItem(GetItemByClass(pClass)))\n                {\n                    if (pActor->GetCurrentItem() && pActor->GetCurrentItem() != pItem)\n                    {\n                        pActor->GetCurrentItem()->Select(false);\n                    }\n                    pItem->Select(true);\n                    m_stats.currentItemId = pItem->GetEntityId();\n                }\n                else\n                {\n                    m_stats.currentItemId = m_pGameFrameWork->GetIItemSystem()->GiveItem(pActor, itemName.c_str(), false, true, false);\n                }\n            }\n        }\n    }\n    else\n    {\n        numItems  = m_stats.slots.size();\n        ser.Value(\"numOfItems\", numItems);\n\n        for (int i = 0; i < numItems; ++i)\n        {\n            ser.BeginGroup(\"Items\");\n            IItem* pItem = m_pGameFrameWork->GetIItemSystem()->GetItem(m_stats.slots[i]);\n            bool nextItem = true;\n            if (pItem)\n            {\n                ser.Value(\"nextItemExists\", nextItem);\n                ser.Value(\"ItemName\", pItem->GetEntity()->GetClass()->GetName());\n                pItem->SerializeLTL(ser);\n            }\n            else\n            {\n                nextItem = false;\n                ser.Value(\"nextItemExists\", nextItem);\n            }\n            ser.EndGroup();\n        }\n        bool currentItemIsInInventory = stl::find(m_stats.slots, m_stats.currentItemId);\n        IItem* pCurrentItem = NULL;\n\n        if (currentItemIsInInventory)\n        {\n            pCurrentItem = m_pGameFrameWork->GetIItemSystem()->GetItem(m_stats.currentItemId);\n        }\n        else\n        {\n            pCurrentItem = m_pGameFrameWork->GetIItemSystem()->GetItem(GetHolsteredItem());\n            \/\/Fallback to last selected one...\n            if (!pCurrentItem)\n            {\n                pCurrentItem = m_pGameFrameWork->GetIItemSystem()->GetItem(GetLastItem());\n                \/\/ desperate fallback to any weapon...\n                \/\/ this fallback should never be needed. However, right now it happens if the player loads a savegame where a heavyweapon is being used, right before the end of the mission.\n                \/\/ that is a bug, but at this point is safer to just do this bruteforce fallback instead of fixing it\n                \/\/ TODO: to fix that and remove this fallback...\n                if (!pCurrentItem)\n                {\n                    for (int i = 0; i < numItems; ++i)\n                    {\n                        IItem* pItem = m_pGameFrameWork->GetIItemSystem()->GetItem(m_stats.slots[i]);\n                        if (pItem)\n                        {\n                            const char* pCategoryName = m_pGameFrameWork->GetIItemSystem()->GetItemCategory(pItem->GetEntity()->GetClass()->GetName());\n                            if (pCategoryName)\n                            {\n                                EInventorySlots slotType = GetSlotForItemCategory(pCategoryName);\n                                if (slotType == eInventorySlot_Weapon)\n                                {\n                                    pCurrentItem = pItem;\n                                    break;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        if (pCurrentItem)\n        {\n            ser.Value(\"CurrentItemName\", pCurrentItem->GetEntity()->GetClass()->GetName());\n        }\n        else\n        {\n            string name(\"none\");\n            ser.Value(\"CurrentItemName\", name);\n        }\n    }\n\n    \/\/**************************************AMMO\n\n    ser.BeginGroup(\"Ammo\");\n\n    TAmmoInfoMap::iterator ammoInfoIt = m_stats.ammoInfo.begin();\n    int ammoAmount = m_stats.ammoInfo.size();\n    ser.Value(\"AmmoAmount\", ammoAmount);\n    for (int i = 0; i < ammoAmount; ++i)\n    {\n        string name;\n        int amount = 0;\n        int users = 0;\n        int capacity = 0;\n        if (ser.IsWriting())\n        {\n            IEntityClass* pAmmoClass = ammoInfoIt->first;\n            CRY_ASSERT(pAmmoClass);\n            name = (pAmmoClass) ? pAmmoClass->GetName() : \"\";\n            const SAmmoInfo& ammoInfo = ammoInfoIt->second;\n            ;\n            amount = ammoInfo.GetCount();\n            capacity = ammoInfo.GetCapacity();\n\n            ++ammoInfoIt;\n        }\n        ser.BeginGroup(\"Ammo\");\n        ser.Value(\"AmmoName\", name);\n        ser.Value(\"Bullets\", amount);\n        ser.Value(\"Capacity\", capacity);\n        ser.EndGroup();\n        if (ser.IsReading())\n        {\n            IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name);\n            CRY_ASSERT(pClass);\n            TAmmoInfoMap::iterator it = m_stats.ammoInfo.find(pClass);\n            if (it == m_stats.ammoInfo.end())\n            {\n                m_stats.ammoInfo[pClass] = SAmmoInfo(amount, capacity);\n            }\n            else\n            {\n                it->second.SetCount(amount);\n                it->second.SetCapacity(capacity);\n            }\n        }\n    }\n\n    ser.EndGroup();\n\n    m_bSerializeLTL = false;\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::ProcessEvent(SEntityEvent& event)\n{\n    FUNCTION_PROFILER(gEnv->pSystem, PROFILE_ACTION);\n\n    if (event.event == ENTITY_EVENT_RESET)\n    {\n        if (gEnv->IsEditor())\n        {\n            if (event.nParam[0]) \/\/ entering game mode in editor\n            {\n                m_editorstats = m_stats;\n            }\n            else\n            {\/\/ leaving game mode\n                if (m_stats.currentItemId != m_editorstats.currentItemId)\n                {\n                    m_pGameFrameWork->GetIItemSystem()->SetActorItem(m_pActor, m_editorstats.currentItemId, false);\n                }\n                m_stats = m_editorstats;\n\n                \/\/Validate inventory, some things might have changed, like some FG removing items while in editor game\n                Validate();\n            }\n        }\n    }\n}\n\n\/\/------------------------------------------------------------------------\nbool CInventory::AddItem(EntityId id)\n{\n    if (FindItem(id) > -1)\n    {\n        return true;\n    }\n\n    if (m_stats.slots.size() >= gEnv->pConsole->GetCVar(\"i_inventory_capacity\")->GetIVal())\n    {\n        return false;\n    }\n\n    AddItemToCategorySlot(id);\n\n    m_stats.slots.push_back(id);\n    std::sort(m_stats.slots.begin(), m_stats.slots.end(), compare_slots());\n\n    TListenerVec::iterator iter = m_listeners.begin();\n    m_iteratingListeners = true;\n    while (iter != m_listeners.end())\n    {\n        (*iter)->OnAddItem(id);\n        ++iter;\n    }\n    m_iteratingListeners = false;\n\n    return true;\n}\n\n\/\/------------------------------------------------------------------------\nbool CInventory::RemoveItem(EntityId id)\n{\n    bool result = stl::find_and_erase(m_stats.slots, id);\n\n    if (result)\n    {\n        RemoveItemFromCategorySlot(id);\n    }\n\n    return result;\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::RemoveAllItems(bool forceClear)\n{\n    this->Clear(forceClear);\n}\n\n\/\/------------------------------------------------------------------------\nint CInventory::Validate()\n{\n    TInventoryVector copyOfSlots;\n    copyOfSlots.reserve(m_stats.slots.size());\n    std::swap(copyOfSlots, m_stats.slots);\n\n    int count = 0;\n    const int slotCount = copyOfSlots.size();\n\n    IEntitySystem* pEntitySystem = gEnv->pEntitySystem;\n    for (int i = 0; i < slotCount; ++i)\n    {\n        EntityId itemId = copyOfSlots[i];\n        IEntity* pEntity = pEntitySystem->GetEntity(itemId);\n        if (!pEntity)\n        {\n            ++count;\n        }\n        else\n        {\n            m_stats.slots.push_back(itemId);\n        }\n    }\n\n    return count;\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::Destroy()\n{\n    \/\/\n    \/\/CryLog(\"%s::CInventory::Destroy()\",GetEntity()->GetName());\n    \/\/\n    if (!GetISystem()->IsSerializingFile())\n    {\n        IEntitySystem* pEntitySystem = gEnv->pEntitySystem;\n        IItemSystem* pItemSystem = gEnv->pGame->GetIGameFramework()->GetIItemSystem();\n\n        TInventoryVector deleteList = m_stats.slots;\n        for (TInventoryIt it = deleteList.begin(); it != deleteList.end(); ++it)\n        {\n            EntityId entityId = *it;\n\n            IItem* pItem = pItemSystem->GetItem(entityId);\n            if (pItem)\n            {\n                RemoveItemFromCategorySlot(pItem->GetEntityId());\n                pItem->RemoveOwnerAttachedAccessories();\n                pItem->AttachToHand(false);\n                pItem->AttachToBack(false);\n                pItem->SetOwnerId(0);\n            }\n\n            pEntitySystem->RemoveEntity(entityId);\n        }\n    }\n\n    Clear();\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::Clear(bool forceClear)\n{\n    if (m_ignoreNextClear && !forceClear)\n    {\n        m_ignoreNextClear = false;\n        return;\n    }\n\n    if (!gEnv->bServer)\n    {\n        IItemSystem* pItemSystem = gEnv->pGame->GetIGameFramework()->GetIItemSystem();\n\n        TInventoryIt end = m_stats.slots.end();\n        for (TInventoryIt it = m_stats.slots.begin(); it != end; ++it)\n        {\n            if (IItem* pItem = pItemSystem->GetItem(*it))\n            {\n                pItem->RemoveOwnerAttachedAccessories();\n                pItem->AttachToHand(false);\n                pItem->AttachToBack(false);\n                pItem->SetOwnerId(0);\n                pItem->GetEntity()->Hide(true);\n            }\n        }\n    }\n\n    m_stats.slots.clear();\n    m_stats.accessorySlots.clear();\n    ResetAmmoAndUsers();\n\n    for (int i = 0; i < IInventory::eInventorySlot_Last; ++i)\n    {\n        m_stats.slotsInfo[i].Reset();\n    }\n\n    m_stats.currentItemId = 0;\n    m_stats.holsteredItemId = 0;\n    m_stats.lastItemId = 0;\n\n    TListenerVec::iterator iter = m_listeners.begin();\n    m_iteratingListeners = true;\n    while (iter != m_listeners.end())\n    {\n        (*iter)->OnClearInventory();\n        ++iter;\n    }\n    m_iteratingListeners = false;\n}\n\n\/\/------------------------------------------------------------------------\n#if DEBUG_INVENTORY_ENABLED\n\nvoid CInventory::Dump() const\n{\n    struct Dumper\n    {\n        Dumper(EntityId entityId, const char* desc)\n        {\n            IEntitySystem* pEntitySystem = gEnv->pEntitySystem;\n            IEntity* pEntity = pEntitySystem->GetEntity(entityId);\n            CryLogAlways(\">> Id: %d [%s] $3%s $5%s\", entityId, pEntity ? pEntity->GetName() : \"<unknown>\", pEntity ? pEntity->GetClass()->GetName() : \"<unknown>\", desc ? desc : \"\");\n        }\n    };\n\n    int count = GetCount();\n    CryLogAlways(\"-- $3%s$1's Inventory: %d Items --\", GetEntity()->GetName(), count);\n\n    if (count)\n    {\n        for (TInventoryCIt it = m_stats.slots.begin(); it != m_stats.slots.end(); ++it)\n        {\n            Dumper dump(*it, 0);\n        }\n    }\n\n    CryLogAlways(\">> --\");\n\n    Dumper current(m_stats.currentItemId, \"Current\");\n    Dumper last(m_stats.lastItemId, \"Last\");\n    Dumper holstered(m_stats.holsteredItemId, \"Holstered\");\n\n    CryLogAlways(\"-- $3%s$1's Inventory: %\" PRISIZE_T \" Ammo Types --\", GetEntity()->GetName(), m_stats.ammoInfo.size());\n\n    if (!m_stats.ammoInfo.empty())\n    {\n        for (TAmmoInfoMap::const_iterator ait = m_stats.ammoInfo.begin(); ait != m_stats.ammoInfo.end(); ++ait)\n        {\n            CryLogAlways(\">> [%s] $3%d$1\/$3%d\", ait->first->GetName(), ait->second.GetCount(), GetAmmoCapacity(ait->first));\n        }\n    }\n}\n\n#endif \/\/DEBUG_INVENTORY_ENABLED\n\n\/\/------------------------------------------------------------------------\nint CInventory::GetCapacity() const\n{\n    return gEnv->pConsole->GetCVar(\"i_inventory_capacity\")->GetIVal();\n}\n\n\/\/------------------------------------------------------------------------\nint CInventory::GetCount() const\n{\n    return m_stats.slots.size();\n}\n\n\/\/------------------------------------------------------------------------\nint CInventory::GetCountOfClass(const char* className) const\n{\n    int count = 0;\n\n    IEntitySystem* pEntitySystem = gEnv->pEntitySystem;\n\n    IEntityClass* pClass = (className != NULL) ? pEntitySystem->GetClassRegistry()->FindClass(className) : NULL;\n    if (pClass)\n    {\n        for (TInventoryCIt it = m_stats.slots.begin(); it != m_stats.slots.end(); ++it)\n        {\n            IEntity* pEntity = pEntitySystem->GetEntity(*it);\n            if ((pEntity != NULL) && (pEntity->GetClass() == pClass))\n            {\n                ++count;\n            }\n        }\n        TInventoryVectorEx::const_iterator endEx = m_stats.accessorySlots.end();\n        for (TInventoryVectorEx::const_iterator cit = m_stats.accessorySlots.begin(); cit != endEx; ++cit)\n        {\n            if (*cit == pClass)\n            {\n                count++;\n            }\n        }\n    }\n\n    return count;\n}\n\/\/------------------------------------------------------------------------\nint CInventory::GetCountOfCategory(const char* categoryName) const\n{\n    IItemSystem* pItemSystem = gEnv->pGame->GetIGameFramework()->GetIItemSystem();\n\n    int count = 0;\n    TInventoryCIt end = m_stats.slots.end();\n    for (TInventoryCIt it = m_stats.slots.begin(); it != end; ++it)\n    {\n        IItem* pItem = pItemSystem->GetItem(*it);\n        if (pItem)\n        {\n            const char* cat = pItemSystem->GetItemCategory(pItem->GetEntity()->GetClass()->GetName());\n            if (!strcmp(cat, categoryName))\n            {\n                count++;\n            }\n        }\n    }\n    TInventoryVectorEx::const_iterator endEx = m_stats.accessorySlots.end();\n    for (TInventoryVectorEx::const_iterator cit = m_stats.accessorySlots.begin(); cit != endEx; ++cit)\n    {\n        const char* cat = pItemSystem->GetItemCategory((*cit)->GetName());\n        if (!strcmp(cat, categoryName))\n        {\n            count++;\n        }\n    }\n\n    return count;\n}\n\n\/\/------------------------------------------------------------------------\nint CInventory::GetCountOfUniqueId(uint8 uniqueId) const\n{\n    \/\/Skip uniqueId 0\n    if (!uniqueId)\n    {\n        return 0;\n    }\n\n    IItemSystem* pItemSystem = gEnv->pGame->GetIGameFramework()->GetIItemSystem();\n\n    int count = 0;\n    TInventoryCIt end = m_stats.slots.end();\n    for (TInventoryCIt it = m_stats.slots.begin(); it != end; ++it)\n    {\n        IItem* pItem = pItemSystem->GetItem(*it);\n        if (pItem)\n        {\n            uint8 id = pItemSystem->GetItemUniqueId(pItem->GetEntity()->GetClass()->GetName());\n            if (id == uniqueId)\n            {\n                count++;\n            }\n        }\n    }\n\n    TInventoryVectorEx::const_iterator endEx = m_stats.accessorySlots.end();\n    for (TInventoryVectorEx::const_iterator cit = m_stats.accessorySlots.begin(); cit != endEx; ++cit)\n    {\n        uint8 id = pItemSystem->GetItemUniqueId((*cit)->GetName());\n        if (id == uniqueId)\n        {\n            count++;\n        }\n    }\n\n    return count;\n}\n\n\/\/------------------------------------------------------------------------\nint CInventory::GetSlotCount(int slotId) const\n{\n    return m_stats.slotsInfo[slotId].count;\n}\n\n\/\/------------------------------------------------------------------------\nEntityId CInventory::GetItem(int slotId) const\n{\n    if (slotId < 0 || slotId >= m_stats.slots.size())\n    {\n        return 0;\n    }\n    return m_stats.slots[slotId];\n}\n\n\/\/------------------------------------------------------------------------\nconst char* CInventory::GetItemString(int slotId) const\n{\n    if (slotId < 0 || slotId >= m_stats.slots.size())\n    {\n        return \"\";\n    }\n\n    EntityId ItemId = GetItem(slotId);\n    IEntity* pEntity =  gEnv->pEntitySystem->GetEntity(ItemId);\n    if (pEntity)\n    {\n        return pEntity->GetClass()->GetName();\n    }\n    else\n    {\n        return \"\";\n    }\n}\n\n\/\/------------------------------------------------------------------------\nEntityId CInventory::GetItemByClass(IEntityClass* pClass, IItem* pIgnoreItem) const\n{\n    if (!pClass)\n    {\n        return 0;\n    }\n\n    IEntitySystem* pEntitySystem = gEnv->pEntitySystem;\n\n    TInventoryCIt end = m_stats.slots.end();\n    for (TInventoryCIt it = m_stats.slots.begin(); it != end; ++it)\n    {\n        if (IEntity* pEntity = pEntitySystem->GetEntity(*it))\n        {\n            if (pEntity->GetClass() == pClass)\n            {\n                if (!pIgnoreItem || pIgnoreItem->GetEntity() != pEntity)\n                {\n                    return *it;\n                }\n            }\n        }\n    }\n\n    return 0;\n}\n\n\/\/------------------------------------------------------------------------\nIItem* CInventory::GetItemByName(const char* name) const\n{\n    if (!name)\n    {\n        return 0;\n    }\n\n    IEntitySystem* pEntitySystem = gEnv->pEntitySystem;\n\n    TInventoryCIt end = m_stats.slots.end();\n    for (TInventoryCIt it = m_stats.slots.begin(); it != end; ++it)\n    {\n        if (IEntity* pEntity = pEntitySystem->GetEntity(*it))\n        {\n            if (!strcmp(pEntity->GetName(), name))\n            {\n                return gEnv->pGame->GetIGameFramework()->GetIItemSystem()->GetItem(pEntity->GetId());\n            }\n        }\n    }\n\n    return 0;\n}\n\n\/\/------------------------------------------\nint CInventory::GetAccessoryCount() const\n{\n    return m_stats.accessorySlots.size();\n}\n\n\/\/----------------------------------------\nconst char* CInventory::GetAccessory(int slotId) const\n{\n    if (slotId >= 0 && slotId < m_stats.accessorySlots.size())\n    {\n        return m_stats.accessorySlots[slotId]->GetName();\n    }\n\n    return NULL;\n}\n\n\/\/----------------------------------------\nconst IEntityClass* CInventory::GetAccessoryClass(int slotId) const\n{\n    if (slotId >= 0 && slotId < m_stats.accessorySlots.size())\n    {\n        return m_stats.accessorySlots[slotId];\n    }\n\n    return NULL;\n}\n\n\/\/----------------------------------------\nbool CInventory::HasAccessory(IEntityClass* pClass) const\n{\n    int size = m_stats.accessorySlots.size();\n    for (int i = 0; i < size; i++)\n    {\n        if (m_stats.accessorySlots[i] == pClass)\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\n\/\/-------------------------------------------------------------------\nbool CInventory::AddAccessory(IEntityClass* accessoryClass)\n{\n    if (accessoryClass == NULL)\n    {\n        return false;\n    }\n\n    if (GetAccessorySlotIndex(accessoryClass) > -1)\n    {\n        return true;\n    }\n\n    m_stats.accessorySlots.push_back(accessoryClass);\n    std::sort(m_stats.accessorySlots.begin(), m_stats.accessorySlots.end(), compare_class_slots());\n\n    TListenerVec::iterator iter = m_listeners.begin();\n    m_iteratingListeners = true;\n    while (iter != m_listeners.end())\n    {\n        (*iter)->OnAddAccessory(accessoryClass);\n        ++iter;\n    }\n    m_iteratingListeners = false;\n\n    return true;\n}\n\n\/\/-------------------------------------------------------------------\nint CInventory::GetAccessorySlotIndex(IEntityClass* accessoryClass) const\n{\n    for (int i = 0; i < m_stats.accessorySlots.size(); i++)\n    {\n        if (m_stats.accessorySlots[i] == accessoryClass)\n        {\n            return i;\n        }\n    }\n    return -1;\n}\n\n\/\/------------------------------------------------------------------------\nint CInventory::FindItem(EntityId itemId) const\n{\n    for (int i = 0; i < m_stats.slots.size(); i++)\n    {\n        if (m_stats.slots[i] == itemId)\n        {\n            return i;\n        }\n    }\n    return -1;\n}\n\n\/\/------------------------------------------------------------------------\nint CInventory::FindNext(IEntityClass* pClass,  const char* category, int firstSlot, bool wrap) const\n{\n    IEntitySystem* pEntitySystem = gEnv->pEntitySystem;\n    for (int i = (firstSlot > -1) ? firstSlot + 1 : 0; i < m_stats.slots.size(); i++)\n    {\n        IEntity* pEntity = pEntitySystem->GetEntity(m_stats.slots[i]);\n        bool ok = true;\n        if (pEntity->GetClass() != pClass)\n        {\n            ok = false;\n        }\n        if (ok && category && category[0] && strcmp(m_pGameFrameWork->GetIItemSystem()->GetItemCategory(pEntity->GetClass()->GetName()), category))\n        {\n            ok = false;\n        }\n\n        if (ok)\n        {\n            return i;\n        }\n    }\n\n    if (wrap && firstSlot > 0)\n    {\n        for (int i = 0; i < firstSlot; i++)\n        {\n            IEntity* pEntity = pEntitySystem->GetEntity(m_stats.slots[i]);\n            bool ok = true;\n            if (pEntity->GetClass() != pClass)\n            {\n                ok = false;\n            }\n            if (ok && category && category[0] && strcmp(m_pGameFrameWork->GetIItemSystem()->GetItemCategory(pEntity->GetClass()->GetName()), category))\n            {\n                ok = false;\n            }\n\n            if (ok)\n            {\n                return i;\n            }\n        }\n    }\n\n    return -1;\n}\n\n\/\/------------------------------------------------------------------------\nint CInventory::FindPrev(IEntityClass* pClass, const char* category, int firstSlot, bool wrap) const\n{\n    IEntitySystem* pEntitySystem = gEnv->pEntitySystem;\n    for (int i = (firstSlot > -1) ? firstSlot + 1 : 0; i < m_stats.slots.size(); i++)\n    {\n        IEntity* pEntity = pEntitySystem->GetEntity(m_stats.slots[firstSlot - i]);\n        bool ok = true;\n        if (pEntity->GetClass() != pClass)\n        {\n            ok = false;\n        }\n        if (ok && category && category[0] && strcmp(m_pGameFrameWork->GetIItemSystem()->GetItemCategory(pEntity->GetClass()->GetName()), category))\n        {\n            ok = false;\n        }\n\n        if (ok)\n        {\n            return i;\n        }\n    }\n\n    if (wrap && firstSlot > 0)\n    {\n        int count = GetCount();\n        for (int i = 0; i < firstSlot; i++)\n        {\n            IEntity* pEntity = pEntitySystem->GetEntity(m_stats.slots[count - i + firstSlot]);\n            bool ok = true;\n            if (pEntity->GetClass() != pClass)\n            {\n                ok = false;\n            }\n            if (ok && category && category[0] && strcmp(m_pGameFrameWork->GetIItemSystem()->GetItemCategory(pEntity->GetClass()->GetName()), category))\n            {\n                ok = false;\n            }\n\n            if (ok)\n            {\n                return i;\n            }\n        }\n    }\n\n    return -1;\n}\n\n\/\/------------------------------------------------------------------------\nEntityId CInventory::GetHolsteredItem() const\n{\n    return m_stats.holsteredItemId;\n}\n\n\/\/------------------------------------------------------------------------\nEntityId CInventory::GetCurrentItem() const\n{\n    return m_stats.currentItemId;\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::SetCurrentItem(EntityId itemId)\n{\n    m_stats.currentItemId = itemId;\n\n    SetLastSelectedInSlot(itemId);\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::SetLastItem(EntityId itemId)\n{\n    m_stats.lastItemId = itemId;\n}\n\n\/\/------------------------------------------------------------------------\nEntityId CInventory::GetLastItem() const\n{\n    if (FindItem(m_stats.lastItemId) > -1)\n    {\n        return m_stats.lastItemId;\n    }\n\n    return 0;\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::HolsterItem(bool holster)\n{\n    \/\/CryLogAlways(\"%s::HolsterItem(%s)\", GetEntity()->GetName(), holster?\"true\":\"false\");\n\n    if (!holster)\n    {\n        if (m_stats.holsteredItemId)\n        {\n            IItem* pItem = m_pGameFrameWork->GetIItemSystem()->GetItem(m_stats.holsteredItemId);\n\n            if (pItem && pItem->CanSelect())\n            {\n                m_pGameFrameWork->GetIItemSystem()->SetActorItem(GetActor(), m_stats.holsteredItemId, false);\n            }\n            else\n            {\n                m_pGameFrameWork->GetIItemSystem()->SetActorItem(GetActor(), GetLastItem(), false);\n            }\n        }\n\n        m_stats.holsteredItemId = 0;\n    }\n    else if (m_stats.currentItemId && (!m_stats.holsteredItemId || m_stats.holsteredItemId == m_stats.currentItemId))\n    {\n        m_stats.holsteredItemId = m_stats.currentItemId;\n        m_pGameFrameWork->GetIItemSystem()->SetActorItem(GetActor(), (EntityId)0, false);\n    }\n}\n\n\/\/------------------------------------------------------------------------\nint CInventory::GetAmmoTypesCount() const\n{\n    return m_stats.ammoInfo.size();\n}\n\n\/\/------------------------------------------------------------------------\nIEntityClass* CInventory::GetAmmoType(int idx) const\n{\n    CRY_ASSERT(idx < m_stats.ammoInfo.size());\n    TAmmoInfoMap::const_iterator it = m_stats.ammoInfo.begin();\n    std::advance(it, idx);\n    return it->first;\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::SetAmmoCount(IEntityClass* pAmmoType, int count)\n{\n    int capacity = GetAmmoCapacity(pAmmoType);\n    CRY_ASSERT(pAmmoType);\n    if (pAmmoType)\n    {\n        if (capacity > 0)\n        {\n            m_stats.ammoInfo[pAmmoType].SetCount(min(count, capacity));\n        }\n        else\n        {\n            m_stats.ammoInfo[pAmmoType].SetCount(count);\n        }\n    }\n\n    TListenerVec::iterator iter = m_listeners.begin();\n    m_iteratingListeners = true;\n    while (iter != m_listeners.end())\n    {\n        (*iter)->OnSetAmmoCount(pAmmoType, count);\n        ++iter;\n    }\n    m_iteratingListeners = false;\n}\n\n\/\/------------------------------------------------------------------------\nint CInventory::GetAmmoCount(IEntityClass* pAmmoType) const\n{\n    TAmmoInfoMap::const_iterator it = m_stats.ammoInfo.find(pAmmoType);\n    if (it != m_stats.ammoInfo.end())\n    {\n        return it->second.GetCount();\n    }\n\n    return 0;\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::SetAmmoCapacity(IEntityClass* pAmmoType, int max)\n{\n    \/\/\n    \/\/CryLog(\"%s::CInventory::SetAmmoCapacity(%s,%d)\", GetEntity()->GetName(),pAmmoType->GetName(), max);\n    \/\/\n    if (pAmmoType)\n    {\n        m_stats.ammoInfo[pAmmoType].SetCapacity(max);\n\n        if (GetAmmoCount(pAmmoType) > max)\n        {\n            SetAmmoCount(pAmmoType, max);\n        }\n    }\n}\n\n\/\/------------------------------------------------------------------------\nint CInventory::GetAmmoCapacity(IEntityClass* pAmmoType) const\n{\n    TAmmoInfoMap::const_iterator it = m_stats.ammoInfo.find(pAmmoType);\n    if (it != m_stats.ammoInfo.end())\n    {\n        return it->second.GetCapacity();\n    }\n\n    return 0;\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::ResetAmmo()\n{\n    TAmmoInfoMap::iterator ammoInfoEndIt = m_stats.ammoInfo.end();\n    for (TAmmoInfoMap::iterator ammoInfoIt = m_stats.ammoInfo.begin(); ammoInfoIt != ammoInfoEndIt; ++ammoInfoIt)\n    {\n        ammoInfoIt->second.ResetCount();\n    }\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::SetInventorySlotCapacity(IInventory::EInventorySlots slotId, unsigned int capacity)\n{\n    CRY_ASSERT_MESSAGE(((slotId >= 0) && (slotId < IInventory::eInventorySlot_Last)), \"Invalid inventory slot!\");\n\n    m_stats.slotsInfo[slotId].maxCapacity = capacity;\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::AssociateItemCategoryToSlot(const char* itemCategory, IInventory::EInventorySlots slotId)\n{\n    CRY_ASSERT_MESSAGE(((slotId >= 0) && (slotId < IInventory::eInventorySlot_Last)), \"Invalid inventory slot!\");\n\n    m_stats.categoriesToSlot.insert(TCategoriesToSlot::value_type(itemCategory, slotId));\n}\n\n\/\/------------------------------------------------------------------------\nEntityId CInventory::GetLastSelectedInSlot(IInventory::EInventorySlots slotId) const\n{\n    CRY_ASSERT_MESSAGE(((slotId >= 0) && (slotId < IInventory::eInventorySlot_Last)), \"Invalid inventory slot!\");\n\n    return m_stats.slotsInfo[slotId].lastSelected;\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::SetLastSelectedInSlot(EntityId entityId)\n{\n    EInventorySlots slot = GetSlotFromEntityID(entityId);\n    if (slot < eInventorySlot_Last)\n    {\n        m_stats.slotsInfo[slot].lastSelected = entityId;\n    }\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::AddItemToCategorySlot(EntityId entityId)\n{\n    EInventorySlots slot = GetSlotFromEntityID(entityId);\n    if (slot < eInventorySlot_Last)\n    {\n        m_stats.slotsInfo[slot].count++;\n\n        if ((m_stats.slotsInfo[slot].lastSelected == 0) || (gEnv->pEntitySystem->GetEntity(m_stats.slotsInfo[slot].lastSelected) == NULL))\n        {\n            m_stats.slotsInfo[slot].lastSelected = entityId;\n        }\n    }\n}\n\n\/\/------------------------------------------------------------------------\nvoid CInventory::RemoveItemFromCategorySlot(EntityId entityId)\n{\n    EInventorySlots slot = GetSlotFromEntityID(entityId);\n    if (slot < eInventorySlot_Last)\n    {\n        m_stats.slotsInfo[slot].count--;\n        if ((m_stats.slotsInfo[slot].count > 0) && (entityId == m_stats.slotsInfo[slot].lastSelected))\n        {\n            const EntityId entityID = GetAnyEntityInSlot(slot);\n            if (entityID != 0)\n            {\n                m_stats.slotsInfo[slot].lastSelected = entityID;\n            }\n        }\n        else\n        {\n            m_stats.slotsInfo[slot].lastSelected = 0;\n        }\n    }\n}\n\n\/\/------------------------------------------------------------------------\nbool CInventory::IsAvailableSlotForItemClass(const char* itemClass) const\n{\n    const char* category = m_pGameFrameWork->GetIItemSystem()->GetItemCategory(itemClass);\n\n    \/\/If not category info, assume there is space\n    if (!category || category[0] == '\\0')\n    {\n        return true;\n    }\n\n    return IsAvailableSlotForItemCategory(category);\n}\n\n\/\/------------------------------------------------------------------------\nbool CInventory::IsAvailableSlotForItemCategory(const char* itemCategory) const\n{\n    TCategoriesToSlot::const_iterator catToSlotCit = m_stats.categoriesToSlot.find(CONST_TEMP_STRING(itemCategory));\n    if (catToSlotCit == m_stats.categoriesToSlot.end())\n    {\n        return true;\n    }\n\n    const SSlotInfo& slotInfo = m_stats.slotsInfo[catToSlotCit->second];\n\n    return (slotInfo.maxCapacity > slotInfo.count);\n}\n\n\/\/------------------------------------------------------------------------\nbool CInventory::AreItemsInSameSlot(const char* itemClass1, const char* itemClass2) const\n{\n    const char* category1 = m_pGameFrameWork->GetIItemSystem()->GetItemCategory(itemClass1);\n    if (!category1 || category1[0] == '\\0')\n    {\n        return false;\n    }\n\n    const char* category2 = m_pGameFrameWork->GetIItemSystem()->GetItemCategory(itemClass2);\n    if (!category2 || category2[0] == '\\0')\n    {\n        return false;\n    }\n\n    TCategoriesToSlot::const_iterator cit1 = m_stats.categoriesToSlot.find(CONST_TEMP_STRING(category1));\n    TCategoriesToSlot::const_iterator cit2 = m_stats.categoriesToSlot.find(CONST_TEMP_STRING(category2));\n    TCategoriesToSlot::const_iterator end = m_stats.categoriesToSlot.end();\n\n    return ((cit1 != end) && (cit2 != end) && (cit1->second == cit2->second));\n}\n\n\/\/----------------------------------------------------------------------\nIInventory::EInventorySlots CInventory::GetSlotForItemCategory(const char* itemCategory) const\n{\n    TCategoriesToSlot::const_iterator cit1 = m_stats.categoriesToSlot.find(CONST_TEMP_STRING(itemCategory));\n\n    return (cit1 != m_stats.categoriesToSlot.end()) ? cit1->second : IInventory::eInventorySlot_Last;\n}\n\n\/\/------------------------------------------------------------------------\n\/\/ client side call for RemoveAllItems\nvoid CInventory::RMIReqToServer_RemoveAllItems() const\n{\n    TRMIInventory_Dummy Info;\n\n    GetGameObject()->InvokeRMI(SvReq_RemoveAllItems(), Info, eRMI_ToServer);\n}\n\n\n\/\/ RMI receiver in the server to remove all items from the inventory. changes are automatically propagated to the clients\nIMPLEMENT_RMI(CInventory, SvReq_RemoveAllItems)\n{\n    IItemSystem* pItemSystem = CCryAction::GetCryAction()->GetIItemSystem();\n\n    IItem* pItem = pItemSystem->GetItem(GetCurrentItem());\n    if (pItem)\n    {\n        pItem->Select(false);\n        pItemSystem->SetActorItem(GetActor(), (EntityId)0, false);\n    }\n\n    Destroy();\n\n    if (gEnv->bMultiplayer)\n    {\n        TRMIInventory_Dummy Info;\n        GetGameObject()->InvokeRMI(Cl_RemoveAllAmmo(), Info, eRMI_ToAllClients);\n    }\n    else\n    {\n        ResetAmmo();\n    }\n\n    return true;\n}\n\n\n\n\/\/------------------------------------------------------------------------\n\/\/ client side call for AddItem\nvoid CInventory::RMIReqToServer_AddItem(const char* _pszItemClass) const\n{\n    TRMIInventory_Item Info(_pszItemClass);\n\n    GetGameObject()->InvokeRMI(SvReq_AddItem(), Info, eRMI_ToServer);\n}\n\n\n\/\/ RMI receiver in the server to add an item to the inventory. change is automatically propagated to the clients\nIMPLEMENT_RMI(CInventory, SvReq_AddItem)\n{\n    TRMIInventory_Item Info(params);\n\n    gEnv->pGame->GetIGameFramework()->GetIItemSystem()->GiveItem(GetActor(), Info.m_ItemClass.c_str(), false, true, true);\n\n    return true;\n}\n\n\n\n\n\/\/------------------------------------------------------------------------\n\/\/ client side call for RemoveItem\nvoid CInventory::RMIReqToServer_RemoveItem(const char* _pszItemClass) const\n{\n    TRMIInventory_Item Info(_pszItemClass);\n\n    GetGameObject()->InvokeRMI(SvReq_RemoveItem(), Info, eRMI_ToServer);\n}\n\n\n\/\/ RMI receiver in the server to remove an item from the inventory. change is automatically propagated to the clients\nIMPLEMENT_RMI(CInventory, SvReq_RemoveItem)\n{\n    TRMIInventory_Item Info(params);\n\n    IItemSystem* pItemSystem = CCryAction::GetCryAction()->GetIItemSystem();\n\n    IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(Info.m_ItemClass.c_str());\n    if (pClass)\n    {\n        IItem* pItem = pItemSystem->GetItem(GetItemByClass(pClass));\n        if (pItem && pItem->GetEntityId() == GetCurrentItem())\n        {\n            pItem->Select(false);\n            pItemSystem->SetActorItem(GetActor(), (EntityId)0, false);\n        }\n\n        if (pItem)\n        {\n            gEnv->pEntitySystem->RemoveEntity(pItem->GetEntityId());\n        }\n    }\n    return true;\n}\n\n\n\n\/\/------------------------------------------------------------------------\nIMPLEMENT_RMI(CInventory, Cl_SetAmmoCapacity)\n{\n    IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(params.m_AmmoClass.c_str());\n    CRY_ASSERT(pClass);\n\n    SetAmmoCapacity(pClass, params.m_iAmount);\n\n    return true;\n}\n\n\/\/------------------------------------------------------------------------\n\/\/ client side call for SetAmmoCount\nvoid CInventory::RMIReqToServer_SetAmmoCount(const char* _pszAmmoClass, int _iAmount) const\n{\n    TRMIInventory_Ammo Info(_pszAmmoClass, _iAmount);\n\n    GetGameObject()->InvokeRMI(SvReq_SetAmmoCount(), Info, eRMI_ToServer);\n}\n\n\/\/ RMI receiver in the server to set the ammo count for an ammo class in the inventory.\nIMPLEMENT_RMI(CInventory, SvReq_SetAmmoCount)\n{\n    TRMIInventory_Ammo Info(params);\n\n    GetGameObject()->InvokeRMI(Cl_SetAmmoCount(), Info, eRMI_ToAllClients);\n    return true;\n}\n\n\/\/ RMI receiver in clients for SetAmmoCount. This is needed because ammo changes are not automatically propagated\nIMPLEMENT_RMI(CInventory, Cl_SetAmmoCount)\n{\n    TRMIInventory_Ammo Info(params);\n\n    IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(Info.m_AmmoClass.c_str());\n    if (pClass)\n    {\n        SetAmmoCount(pClass, Info.m_iAmount);\n    }\n    return true;\n}\n\n\n\/\/ RMI receiver in clients for RemoveAllAmmo. This is needed because ammo changes are not automatically propagated\nIMPLEMENT_RMI(CInventory, Cl_RemoveAllAmmo)\n{\n    ResetAmmo();\n    return true;\n}\n\n\n\/\/------------------------------------------------------------------------\n\/\/ client side call for AddEquipmentPack\nvoid CInventory::RMIReqToServer_AddEquipmentPack(const char* _pszEquipmentPack, bool _bAdd, bool _bPrimary) const\n{\n    TRMIInventory_EquipmentPack Info(_pszEquipmentPack, _bAdd, _bPrimary);\n\n    GetGameObject()->InvokeRMI(SvReq_AddEquipmentPack(), Info, eRMI_ToServer);\n}\n\n\n\/\/ RMI receiver in the server to add an equipment pack to the inventory. change is automatically propagated to the clients\nIMPLEMENT_RMI(CInventory, SvReq_AddEquipmentPack)\n{\n    TRMIInventory_EquipmentPack Info(params);\n\n    CCryAction::GetCryAction()->GetIItemSystem()->GetIEquipmentManager()->GiveEquipmentPack(GetActor(), Info.m_EquipmentPack.c_str(), Info.m_bAdd, Info.m_bPrimary);\n\n    return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CInventory::AddAmmoUser(IEntityClass* pAmmoType)\n{\n    CRY_ASSERT(pAmmoType);\n\n    if (pAmmoType)\n    {\n        m_stats.ammoInfo[pAmmoType].AddUser();\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CInventory::RemoveAmmoUser(IEntityClass* pAmmoType)\n{\n    CRY_ASSERT(pAmmoType);\n\n    TAmmoInfoMap::iterator ammoUserIt = m_stats.ammoInfo.find(pAmmoType);\n\n    CRY_ASSERT_MESSAGE(ammoUserIt != m_stats.ammoInfo.end(), \"Trying to remove user of an ammo which never was added.\");\n\n    if (ammoUserIt != m_stats.ammoInfo.end())\n    {\n        ammoUserIt->second.RemoveUser();\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint CInventory::GetNumberOfUsersForAmmo(IEntityClass* pAmmoType) const\n{\n    TAmmoInfoMap::const_iterator ammoUserCit = m_stats.ammoInfo.find(pAmmoType);\n    if (ammoUserCit != m_stats.ammoInfo.end())\n    {\n        return ammoUserCit->second.GetUserCount();\n    }\n\n    return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CInventory::ResetAmmoAndUsers()\n{\n    m_stats.ammoInfo.clear();\n}\n\n\nvoid CInventory::AddListener(struct IInventoryListener* pListener)\n{\n    CRY_ASSERT_MESSAGE(m_iteratingListeners == false, \"AddListener called during a listener broadcast.\");\n    stl::push_back_unique(m_listeners, pListener);\n}\n\n\nvoid CInventory::RemoveListener(struct IInventoryListener* pListener)\n{\n    CRY_ASSERT_MESSAGE(m_iteratingListeners == false, \"RemoveListener called during a listener broadcast.\");\n    stl::find_and_erase(m_listeners, pListener);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CInventory::SetHolsteredItem(EntityId itemId)\n{\n    m_stats.holsteredItemId = itemId;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CInventory::IgnoreNextClear()\n{\n    m_ignoreNextClear = true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCInventory::EInventorySlots CInventory::GetSlotFromEntityID(EntityId entityID) const\n{\n    IEntity* pEntity = gEnv->pEntitySystem->GetEntity(entityID);\n\n    if (pEntity)\n    {\n        const char* category = m_pGameFrameWork->GetIItemSystem()->GetItemCategory(pEntity->GetClass()->GetName());\n\n        if (!category || category[0] == '\\0')\n        {\n            return eInventorySlot_Last;\n        }\n\n        TCategoriesToSlot::const_iterator catToSlotCit = m_stats.categoriesToSlot.find(CONST_TEMP_STRING(category));\n        if (catToSlotCit == m_stats.categoriesToSlot.end())\n        {\n            return eInventorySlot_Last;\n        }\n\n        return catToSlotCit->second;\n    }\n\n    return eInventorySlot_Last;\n}\n\nEntityId CInventory::GetAnyEntityInSlot(int slot) const\n{\n    TInventoryCIt it = m_stats.slots.begin();\n    const TInventoryCIt iEnd = m_stats.slots.end();\n    for (; it != iEnd; ++it)\n    {\n        if (GetSlotFromEntityID(*it) == slot)\n        {\n            return *it;\n        }\n    }\n\n    return 0;\n}","avg_line_length":30.2135088724,"max_line_length":189,"alphanum_fraction":0.5418600686,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":27873,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/===-- ODRHash.cpp - Hashing to diagnose ODR failures ----------*- C++ -*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/ This file implements the ODRHash class, which calculates a hash based\n\/\/\/ on AST nodes, which is stable across different runs.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/AST\/ODRHash.h\"\n\n#include \"clang\/AST\/DeclVisitor.h\"\n#include \"clang\/AST\/NestedNameSpecifier.h\"\n#include \"clang\/AST\/StmtVisitor.h\"\n#include \"clang\/AST\/TypeVisitor.h\"\n\nusing namespace clang;\n\nvoid ODRHash::AddStmt(const Stmt *S) {\n  assert(S && \"Expecting non-null pointer.\");\n  S->ProcessODRHash(ID, *this);\n}\n\nvoid ODRHash::AddIdentifierInfo(const IdentifierInfo *II) {\n  assert(II && \"Expecting non-null pointer.\");\n  ID.AddString(II->getName());\n}\n\nvoid ODRHash::AddDeclarationName(DeclarationName Name, bool TreatAsDecl) {\n  if (TreatAsDecl)\n    \/\/ Matches the NamedDecl check in AddDecl\n    AddBoolean(true);\n\n  AddDeclarationNameImpl(Name);\n\n  if (TreatAsDecl)\n    \/\/ Matches the ClassTemplateSpecializationDecl check in AddDecl\n    AddBoolean(false);\n}\n\nvoid ODRHash::AddDeclarationNameImpl(DeclarationName Name) {\n  \/\/ Index all DeclarationName and use index numbers to refer to them.\n  auto Result = DeclNameMap.insert(std::make_pair(Name, DeclNameMap.size()));\n  ID.AddInteger(Result.first->second);\n  if (!Result.second) {\n    \/\/ If found in map, the the DeclarationName has previously been processed.\n    return;\n  }\n\n  \/\/ First time processing each DeclarationName, also process its details.\n  AddBoolean(Name.isEmpty());\n  if (Name.isEmpty())\n    return;\n\n  auto Kind = Name.getNameKind();\n  ID.AddInteger(Kind);\n  switch (Kind) {\n  case DeclarationName::Identifier:\n    AddIdentifierInfo(Name.getAsIdentifierInfo());\n    break;\n  case DeclarationName::ObjCZeroArgSelector:\n  case DeclarationName::ObjCOneArgSelector:\n  case DeclarationName::ObjCMultiArgSelector: {\n    Selector S = Name.getObjCSelector();\n    AddBoolean(S.isNull());\n    AddBoolean(S.isKeywordSelector());\n    AddBoolean(S.isUnarySelector());\n    unsigned NumArgs = S.getNumArgs();\n    for (unsigned i = 0; i < NumArgs; ++i) {\n      AddIdentifierInfo(S.getIdentifierInfoForSlot(i));\n    }\n    break;\n  }\n  case DeclarationName::CXXConstructorName:\n  case DeclarationName::CXXDestructorName:\n    AddQualType(Name.getCXXNameType());\n    break;\n  case DeclarationName::CXXOperatorName:\n    ID.AddInteger(Name.getCXXOverloadedOperator());\n    break;\n  case DeclarationName::CXXLiteralOperatorName:\n    AddIdentifierInfo(Name.getCXXLiteralIdentifier());\n    break;\n  case DeclarationName::CXXConversionFunctionName:\n    AddQualType(Name.getCXXNameType());\n    break;\n  case DeclarationName::CXXUsingDirective:\n    break;\n  case DeclarationName::CXXDeductionGuideName: {\n    auto *Template = Name.getCXXDeductionGuideTemplate();\n    AddBoolean(Template);\n    if (Template) {\n      AddDecl(Template);\n    }\n  }\n  }\n}\n\nvoid ODRHash::AddNestedNameSpecifier(const NestedNameSpecifier *NNS) {\n  assert(NNS && \"Expecting non-null pointer.\");\n  const auto *Prefix = NNS->getPrefix();\n  AddBoolean(Prefix);\n  if (Prefix) {\n    AddNestedNameSpecifier(Prefix);\n  }\n  auto Kind = NNS->getKind();\n  ID.AddInteger(Kind);\n  switch (Kind) {\n  case NestedNameSpecifier::Identifier:\n    AddIdentifierInfo(NNS->getAsIdentifier());\n    break;\n  case NestedNameSpecifier::Namespace:\n    AddDecl(NNS->getAsNamespace());\n    break;\n  case NestedNameSpecifier::NamespaceAlias:\n    AddDecl(NNS->getAsNamespaceAlias());\n    break;\n  case NestedNameSpecifier::TypeSpec:\n  case NestedNameSpecifier::TypeSpecWithTemplate:\n    AddType(NNS->getAsType());\n    break;\n  case NestedNameSpecifier::Global:\n  case NestedNameSpecifier::Super:\n    break;\n  }\n}\n\nvoid ODRHash::AddTemplateName(TemplateName Name) {\n  auto Kind = Name.getKind();\n  ID.AddInteger(Kind);\n\n  switch (Kind) {\n  case TemplateName::Template:\n    AddDecl(Name.getAsTemplateDecl());\n    break;\n  \/\/ TODO: Support these cases.\n  case TemplateName::OverloadedTemplate:\n  case TemplateName::QualifiedTemplate:\n  case TemplateName::DependentTemplate:\n  case TemplateName::SubstTemplateTemplateParm:\n  case TemplateName::SubstTemplateTemplateParmPack:\n    break;\n  }\n}\n\nvoid ODRHash::AddTemplateArgument(TemplateArgument TA) {\n  const auto Kind = TA.getKind();\n  ID.AddInteger(Kind);\n\n  switch (Kind) {\n    case TemplateArgument::Null:\n      llvm_unreachable(\"Expected valid TemplateArgument\");\n    case TemplateArgument::Type:\n      AddQualType(TA.getAsType());\n      break;\n    case TemplateArgument::Declaration:\n      AddDecl(TA.getAsDecl());\n      break;\n    case TemplateArgument::NullPtr:\n    case TemplateArgument::Integral:\n      break;\n    case TemplateArgument::Template:\n    case TemplateArgument::TemplateExpansion:\n      AddTemplateName(TA.getAsTemplateOrTemplatePattern());\n      break;\n    case TemplateArgument::Expression:\n      AddStmt(TA.getAsExpr());\n      break;\n    case TemplateArgument::Pack:\n      ID.AddInteger(TA.pack_size());\n      for (auto SubTA : TA.pack_elements()) {\n        AddTemplateArgument(SubTA);\n      }\n      break;\n  }\n}\n\nvoid ODRHash::AddTemplateParameterList(const TemplateParameterList *TPL) {\n  assert(TPL && \"Expecting non-null pointer.\");\n\n  ID.AddInteger(TPL->size());\n  for (auto *ND : TPL->asArray()) {\n    AddSubDecl(ND);\n  }\n}\n\nvoid ODRHash::clear() {\n  DeclNameMap.clear();\n  Bools.clear();\n  ID.clear();\n}\n\nunsigned ODRHash::CalculateHash() {\n  \/\/ Append the bools to the end of the data segment backwards.  This allows\n  \/\/ for the bools data to be compressed 32 times smaller compared to using\n  \/\/ ID.AddBoolean\n  const unsigned unsigned_bits = sizeof(unsigned) * CHAR_BIT;\n  const unsigned size = Bools.size();\n  const unsigned remainder = size % unsigned_bits;\n  const unsigned loops = size \/ unsigned_bits;\n  auto I = Bools.rbegin();\n  unsigned value = 0;\n  for (unsigned i = 0; i < remainder; ++i) {\n    value <<= 1;\n    value |= *I;\n    ++I;\n  }\n  ID.AddInteger(value);\n\n  for (unsigned i = 0; i < loops; ++i) {\n    value = 0;\n    for (unsigned j = 0; j < unsigned_bits; ++j) {\n      value <<= 1;\n      value |= *I;\n      ++I;\n    }\n    ID.AddInteger(value);\n  }\n\n  assert(I == Bools.rend());\n  Bools.clear();\n  return ID.ComputeHash();\n}\n\nnamespace {\n\/\/ Process a Decl pointer.  Add* methods call back into ODRHash while Visit*\n\/\/ methods process the relevant parts of the Decl.\nclass ODRDeclVisitor : public ConstDeclVisitor<ODRDeclVisitor> {\n  typedef ConstDeclVisitor<ODRDeclVisitor> Inherited;\n  llvm::FoldingSetNodeID &ID;\n  ODRHash &Hash;\n\npublic:\n  ODRDeclVisitor(llvm::FoldingSetNodeID &ID, ODRHash &Hash)\n      : ID(ID), Hash(Hash) {}\n\n  void AddStmt(const Stmt *S) {\n    Hash.AddBoolean(S);\n    if (S) {\n      Hash.AddStmt(S);\n    }\n  }\n\n  void AddIdentifierInfo(const IdentifierInfo *II) {\n    Hash.AddBoolean(II);\n    if (II) {\n      Hash.AddIdentifierInfo(II);\n    }\n  }\n\n  void AddQualType(QualType T) {\n    Hash.AddQualType(T);\n  }\n\n  void AddDecl(const Decl *D) {\n    Hash.AddBoolean(D);\n    if (D) {\n      Hash.AddDecl(D);\n    }\n  }\n\n  void AddTemplateArgument(TemplateArgument TA) {\n    Hash.AddTemplateArgument(TA);\n  }\n\n  void Visit(const Decl *D) {\n    ID.AddInteger(D->getKind());\n    Inherited::Visit(D);\n  }\n\n  void VisitNamedDecl(const NamedDecl *D) {\n    Hash.AddDeclarationName(D->getDeclName());\n    Inherited::VisitNamedDecl(D);\n  }\n\n  void VisitValueDecl(const ValueDecl *D) {\n    if (!isa<FunctionDecl>(D)) {\n      AddQualType(D->getType());\n    }\n    Inherited::VisitValueDecl(D);\n  }\n\n  void VisitVarDecl(const VarDecl *D) {\n    Hash.AddBoolean(D->isStaticLocal());\n    Hash.AddBoolean(D->isConstexpr());\n    const bool HasInit = D->hasInit();\n    Hash.AddBoolean(HasInit);\n    if (HasInit) {\n      AddStmt(D->getInit());\n    }\n    Inherited::VisitVarDecl(D);\n  }\n\n  void VisitParmVarDecl(const ParmVarDecl *D) {\n    \/\/ TODO: Handle default arguments.\n    Inherited::VisitParmVarDecl(D);\n  }\n\n  void VisitAccessSpecDecl(const AccessSpecDecl *D) {\n    ID.AddInteger(D->getAccess());\n    Inherited::VisitAccessSpecDecl(D);\n  }\n\n  void VisitStaticAssertDecl(const StaticAssertDecl *D) {\n    AddStmt(D->getAssertExpr());\n    AddStmt(D->getMessage());\n\n    Inherited::VisitStaticAssertDecl(D);\n  }\n\n  void VisitFieldDecl(const FieldDecl *D) {\n    const bool IsBitfield = D->isBitField();\n    Hash.AddBoolean(IsBitfield);\n\n    if (IsBitfield) {\n      AddStmt(D->getBitWidth());\n    }\n\n    Hash.AddBoolean(D->isMutable());\n    AddStmt(D->getInClassInitializer());\n\n    Inherited::VisitFieldDecl(D);\n  }\n\n  void VisitFunctionDecl(const FunctionDecl *D) {\n    \/\/ Handled by the ODRHash for FunctionDecl\n    ID.AddInteger(D->getODRHash());\n\n    Inherited::VisitFunctionDecl(D);\n  }\n\n  void VisitCXXMethodDecl(const CXXMethodDecl *D) {\n    \/\/ Handled by the ODRHash for FunctionDecl\n\n    Inherited::VisitCXXMethodDecl(D);\n  }\n\n  void VisitTypedefNameDecl(const TypedefNameDecl *D) {\n    AddQualType(D->getUnderlyingType());\n\n    Inherited::VisitTypedefNameDecl(D);\n  }\n\n  void VisitTypedefDecl(const TypedefDecl *D) {\n    Inherited::VisitTypedefDecl(D);\n  }\n\n  void VisitTypeAliasDecl(const TypeAliasDecl *D) {\n    Inherited::VisitTypeAliasDecl(D);\n  }\n\n  void VisitFriendDecl(const FriendDecl *D) {\n    TypeSourceInfo *TSI = D->getFriendType();\n    Hash.AddBoolean(TSI);\n    if (TSI) {\n      AddQualType(TSI->getType());\n    } else {\n      AddDecl(D->getFriendDecl());\n    }\n  }\n\n  void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {\n    \/\/ Only care about default arguments as part of the definition.\n    const bool hasDefaultArgument =\n        D->hasDefaultArgument() && !D->defaultArgumentWasInherited();\n    Hash.AddBoolean(hasDefaultArgument);\n    if (hasDefaultArgument) {\n      AddTemplateArgument(D->getDefaultArgument());\n    }\n    Hash.AddBoolean(D->isParameterPack());\n\n    Inherited::VisitTemplateTypeParmDecl(D);\n  }\n\n  void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {\n    \/\/ Only care about default arguments as part of the definition.\n    const bool hasDefaultArgument =\n        D->hasDefaultArgument() && !D->defaultArgumentWasInherited();\n    Hash.AddBoolean(hasDefaultArgument);\n    if (hasDefaultArgument) {\n      AddStmt(D->getDefaultArgument());\n    }\n    Hash.AddBoolean(D->isParameterPack());\n\n    Inherited::VisitNonTypeTemplateParmDecl(D);\n  }\n\n  void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D) {\n    \/\/ Only care about default arguments as part of the definition.\n    const bool hasDefaultArgument =\n        D->hasDefaultArgument() && !D->defaultArgumentWasInherited();\n    Hash.AddBoolean(hasDefaultArgument);\n    if (hasDefaultArgument) {\n      AddTemplateArgument(D->getDefaultArgument().getArgument());\n    }\n    Hash.AddBoolean(D->isParameterPack());\n\n    Inherited::VisitTemplateTemplateParmDecl(D);\n  }\n\n  void VisitTemplateDecl(const TemplateDecl *D) {\n    Hash.AddTemplateParameterList(D->getTemplateParameters());\n\n    Inherited::VisitTemplateDecl(D);\n  }\n\n  void VisitRedeclarableTemplateDecl(const RedeclarableTemplateDecl *D) {\n    Hash.AddBoolean(D->isMemberSpecialization());\n    Inherited::VisitRedeclarableTemplateDecl(D);\n  }\n\n  void VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) {\n    AddDecl(D->getTemplatedDecl());\n    ID.AddInteger(D->getTemplatedDecl()->getODRHash());\n    Inherited::VisitFunctionTemplateDecl(D);\n  }\n\n  void VisitEnumConstantDecl(const EnumConstantDecl *D) {\n    AddStmt(D->getInitExpr());\n    Inherited::VisitEnumConstantDecl(D);\n  }\n};\n} \/\/ namespace\n\n\/\/ Only allow a small portion of Decl's to be processed.  Remove this once\n\/\/ all Decl's can be handled.\nbool ODRHash::isWhitelistedDecl(const Decl *D, const DeclContext *Parent) {\n  if (D->isImplicit()) return false;\n  if (D->getDeclContext() != Parent) return false;\n\n  switch (D->getKind()) {\n    default:\n      return false;\n    case Decl::AccessSpec:\n    case Decl::CXXConstructor:\n    case Decl::CXXDestructor:\n    case Decl::CXXMethod:\n    case Decl::EnumConstant: \/\/ Only found in EnumDecl's.\n    case Decl::Field:\n    case Decl::Friend:\n    case Decl::FunctionTemplate:\n    case Decl::StaticAssert:\n    case Decl::TypeAlias:\n    case Decl::Typedef:\n    case Decl::Var:\n      return true;\n  }\n}\n\nvoid ODRHash::AddSubDecl(const Decl *D) {\n  assert(D && \"Expecting non-null pointer.\");\n\n  ODRDeclVisitor(ID, *this).Visit(D);\n}\n\nvoid ODRHash::AddCXXRecordDecl(const CXXRecordDecl *Record) {\n  assert(Record && Record->hasDefinition() &&\n         \"Expected non-null record to be a definition.\");\n\n  const DeclContext *DC = Record;\n  while (DC) {\n    if (isa<ClassTemplateSpecializationDecl>(DC)) {\n      return;\n    }\n    DC = DC->getParent();\n  }\n\n  AddDecl(Record);\n\n  \/\/ Filter out sub-Decls which will not be processed in order to get an\n  \/\/ accurate count of Decl's.\n  llvm::SmallVector<const Decl *, 16> Decls;\n  for (Decl *SubDecl : Record->decls()) {\n    if (isWhitelistedDecl(SubDecl, Record)) {\n      Decls.push_back(SubDecl);\n      if (auto *Function = dyn_cast<FunctionDecl>(SubDecl)) {\n        \/\/ Compute\/Preload ODRHash into FunctionDecl.\n        Function->getODRHash();\n      }\n    }\n  }\n\n  ID.AddInteger(Decls.size());\n  for (auto SubDecl : Decls) {\n    AddSubDecl(SubDecl);\n  }\n\n  const ClassTemplateDecl *TD = Record->getDescribedClassTemplate();\n  AddBoolean(TD);\n  if (TD) {\n    AddTemplateParameterList(TD->getTemplateParameters());\n  }\n\n  ID.AddInteger(Record->getNumBases());\n  auto Bases = Record->bases();\n  for (auto Base : Bases) {\n    AddQualType(Base.getType());\n    ID.AddInteger(Base.isVirtual());\n    ID.AddInteger(Base.getAccessSpecifierAsWritten());\n  }\n}\n\nvoid ODRHash::AddFunctionDecl(const FunctionDecl *Function,\n                              bool SkipBody) {\n  assert(Function && \"Expecting non-null pointer.\");\n\n  \/\/ Skip functions that are specializations or in specialization context.\n  const DeclContext *DC = Function;\n  while (DC) {\n    if (isa<ClassTemplateSpecializationDecl>(DC)) return;\n    if (auto *F = dyn_cast<FunctionDecl>(DC)) {\n      if (F->isFunctionTemplateSpecialization()) {\n        if (!isa<CXXMethodDecl>(DC)) return;\n        if (DC->getLexicalParent()->isFileContext()) return;\n        \/\/ Inline method specializations are the only supported\n        \/\/ specialization for now.\n      }\n    }\n    DC = DC->getParent();\n  }\n\n  ID.AddInteger(Function->getDeclKind());\n\n  const auto *SpecializationArgs = Function->getTemplateSpecializationArgs();\n  AddBoolean(SpecializationArgs);\n  if (SpecializationArgs) {\n    ID.AddInteger(SpecializationArgs->size());\n    for (const TemplateArgument &TA : SpecializationArgs->asArray()) {\n      AddTemplateArgument(TA);\n    }\n  }\n\n  if (const auto *Method = dyn_cast<CXXMethodDecl>(Function)) {\n    AddBoolean(Method->isConst());\n    AddBoolean(Method->isVolatile());\n  }\n\n  ID.AddInteger(Function->getStorageClass());\n  AddBoolean(Function->isInlineSpecified());\n  AddBoolean(Function->isVirtualAsWritten());\n  AddBoolean(Function->isPure());\n  AddBoolean(Function->isDeletedAsWritten());\n  AddBoolean(Function->isExplicitlyDefaulted());\n\n  AddDecl(Function);\n\n  AddQualType(Function->getReturnType());\n\n  ID.AddInteger(Function->param_size());\n  for (auto Param : Function->parameters())\n    AddSubDecl(Param);\n\n  if (SkipBody) {\n    AddBoolean(false);\n    return;\n  }\n\n  const bool HasBody = Function->isThisDeclarationADefinition() &&\n                       !Function->isDefaulted() && !Function->isDeleted() &&\n                       !Function->isLateTemplateParsed();\n  AddBoolean(HasBody);\n  if (!HasBody) {\n    return;\n  }\n\n  auto *Body = Function->getBody();\n  AddBoolean(Body);\n  if (Body)\n    AddStmt(Body);\n\n  \/\/ Filter out sub-Decls which will not be processed in order to get an\n  \/\/ accurate count of Decl's.\n  llvm::SmallVector<const Decl *, 16> Decls;\n  for (Decl *SubDecl : Function->decls()) {\n    if (isWhitelistedDecl(SubDecl, Function)) {\n      Decls.push_back(SubDecl);\n    }\n  }\n\n  ID.AddInteger(Decls.size());\n  for (auto SubDecl : Decls) {\n    AddSubDecl(SubDecl);\n  }\n}\n\nvoid ODRHash::AddEnumDecl(const EnumDecl *Enum) {\n  assert(Enum);\n  AddDeclarationName(Enum->getDeclName());\n\n  AddBoolean(Enum->isScoped());\n  if (Enum->isScoped())\n    AddBoolean(Enum->isScopedUsingClassTag());\n\n  if (Enum->getIntegerTypeSourceInfo())\n    AddQualType(Enum->getIntegerType());\n\n  \/\/ Filter out sub-Decls which will not be processed in order to get an\n  \/\/ accurate count of Decl's.\n  llvm::SmallVector<const Decl *, 16> Decls;\n  for (Decl *SubDecl : Enum->decls()) {\n    if (isWhitelistedDecl(SubDecl, Enum)) {\n      assert(isa<EnumConstantDecl>(SubDecl) && \"Unexpected Decl\");\n      Decls.push_back(SubDecl);\n    }\n  }\n\n  ID.AddInteger(Decls.size());\n  for (auto SubDecl : Decls) {\n    AddSubDecl(SubDecl);\n  }\n\n}\n\nvoid ODRHash::AddDecl(const Decl *D) {\n  assert(D && \"Expecting non-null pointer.\");\n  D = D->getCanonicalDecl();\n\n  const NamedDecl *ND = dyn_cast<NamedDecl>(D);\n  AddBoolean(ND);\n  if (!ND) {\n    ID.AddInteger(D->getKind());\n    return;\n  }\n\n  AddDeclarationName(ND->getDeclName());\n\n  const auto *Specialization =\n            dyn_cast<ClassTemplateSpecializationDecl>(D);\n  AddBoolean(Specialization);\n  if (Specialization) {\n    const TemplateArgumentList &List = Specialization->getTemplateArgs();\n    ID.AddInteger(List.size());\n    for (const TemplateArgument &TA : List.asArray())\n      AddTemplateArgument(TA);\n  }\n}\n\nnamespace {\n\/\/ Process a Type pointer.  Add* methods call back into ODRHash while Visit*\n\/\/ methods process the relevant parts of the Type.\nclass ODRTypeVisitor : public TypeVisitor<ODRTypeVisitor> {\n  typedef TypeVisitor<ODRTypeVisitor> Inherited;\n  llvm::FoldingSetNodeID &ID;\n  ODRHash &Hash;\n\npublic:\n  ODRTypeVisitor(llvm::FoldingSetNodeID &ID, ODRHash &Hash)\n      : ID(ID), Hash(Hash) {}\n\n  void AddStmt(Stmt *S) {\n    Hash.AddBoolean(S);\n    if (S) {\n      Hash.AddStmt(S);\n    }\n  }\n\n  void AddDecl(Decl *D) {\n    Hash.AddBoolean(D);\n    if (D) {\n      Hash.AddDecl(D);\n    }\n  }\n\n  void AddQualType(QualType T) {\n    Hash.AddQualType(T);\n  }\n\n  void AddType(const Type *T) {\n    Hash.AddBoolean(T);\n    if (T) {\n      Hash.AddType(T);\n    }\n  }\n\n  void AddNestedNameSpecifier(const NestedNameSpecifier *NNS) {\n    Hash.AddBoolean(NNS);\n    if (NNS) {\n      Hash.AddNestedNameSpecifier(NNS);\n    }\n  }\n\n  void AddIdentifierInfo(const IdentifierInfo *II) {\n    Hash.AddBoolean(II);\n    if (II) {\n      Hash.AddIdentifierInfo(II);\n    }\n  }\n\n  void VisitQualifiers(Qualifiers Quals) {\n    ID.AddInteger(Quals.getAsOpaqueValue());\n  }\n\n  void Visit(const Type *T) {\n    ID.AddInteger(T->getTypeClass());\n    Inherited::Visit(T);\n  }\n\n  void VisitType(const Type *T) {}\n\n  void VisitAdjustedType(const AdjustedType *T) {\n    AddQualType(T->getOriginalType());\n    AddQualType(T->getAdjustedType());\n    VisitType(T);\n  }\n\n  void VisitDecayedType(const DecayedType *T) {\n    AddQualType(T->getDecayedType());\n    AddQualType(T->getPointeeType());\n    VisitAdjustedType(T);\n  }\n\n  void VisitArrayType(const ArrayType *T) {\n    AddQualType(T->getElementType());\n    ID.AddInteger(T->getSizeModifier());\n    VisitQualifiers(T->getIndexTypeQualifiers());\n    VisitType(T);\n  }\n  void VisitConstantArrayType(const ConstantArrayType *T) {\n    T->getSize().Profile(ID);\n    VisitArrayType(T);\n  }\n\n  void VisitDependentSizedArrayType(const DependentSizedArrayType *T) {\n    AddStmt(T->getSizeExpr());\n    VisitArrayType(T);\n  }\n\n  void VisitIncompleteArrayType(const IncompleteArrayType *T) {\n    VisitArrayType(T);\n  }\n\n  void VisitVariableArrayType(const VariableArrayType *T) {\n    AddStmt(T->getSizeExpr());\n    VisitArrayType(T);\n  }\n\n  void VisitAttributedType(const AttributedType *T) {\n    ID.AddInteger(T->getAttrKind());\n    AddQualType(T->getModifiedType());\n    AddQualType(T->getEquivalentType());\n\n    VisitType(T);\n  }\n\n  void VisitBlockPointerType(const BlockPointerType *T) {\n    AddQualType(T->getPointeeType());\n    VisitType(T);\n  }\n\n  void VisitBuiltinType(const BuiltinType *T) {\n    ID.AddInteger(T->getKind());\n    VisitType(T);\n  }\n\n  void VisitComplexType(const ComplexType *T) {\n    AddQualType(T->getElementType());\n    VisitType(T);\n  }\n\n  void VisitDecltypeType(const DecltypeType *T) {\n    AddStmt(T->getUnderlyingExpr());\n    AddQualType(T->getUnderlyingType());\n    VisitType(T);\n  }\n\n  void VisitDependentDecltypeType(const DependentDecltypeType *T) {\n    VisitDecltypeType(T);\n  }\n\n  void VisitDeducedType(const DeducedType *T) {\n    AddQualType(T->getDeducedType());\n    VisitType(T);\n  }\n\n  void VisitAutoType(const AutoType *T) {\n    ID.AddInteger((unsigned)T->getKeyword());\n    VisitDeducedType(T);\n  }\n\n  void VisitDeducedTemplateSpecializationType(\n      const DeducedTemplateSpecializationType *T) {\n    Hash.AddTemplateName(T->getTemplateName());\n    VisitDeducedType(T);\n  }\n\n  void VisitDependentAddressSpaceType(const DependentAddressSpaceType *T) {\n    AddQualType(T->getPointeeType());\n    AddStmt(T->getAddrSpaceExpr());\n    VisitType(T);\n  }\n\n  void VisitDependentSizedExtVectorType(const DependentSizedExtVectorType *T) {\n    AddQualType(T->getElementType());\n    AddStmt(T->getSizeExpr());\n    VisitType(T);\n  }\n\n  void VisitFunctionType(const FunctionType *T) {\n    AddQualType(T->getReturnType());\n    T->getExtInfo().Profile(ID);\n    Hash.AddBoolean(T->isConst());\n    Hash.AddBoolean(T->isVolatile());\n    Hash.AddBoolean(T->isRestrict());\n    VisitType(T);\n  }\n\n  void VisitFunctionNoProtoType(const FunctionNoProtoType *T) {\n    VisitFunctionType(T);\n  }\n\n  void VisitFunctionProtoType(const FunctionProtoType *T) {\n    ID.AddInteger(T->getNumParams());\n    for (auto ParamType : T->getParamTypes())\n      AddQualType(ParamType);\n\n    VisitFunctionType(T);\n  }\n\n  void VisitInjectedClassNameType(const InjectedClassNameType *T) {\n    AddDecl(T->getDecl());\n    VisitType(T);\n  }\n\n  void VisitMemberPointerType(const MemberPointerType *T) {\n    AddQualType(T->getPointeeType());\n    AddType(T->getClass());\n    VisitType(T);\n  }\n\n  void VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {\n    AddQualType(T->getPointeeType());\n    VisitType(T);\n  }\n\n  void VisitObjCObjectType(const ObjCObjectType *T) {\n    AddDecl(T->getInterface());\n\n    auto TypeArgs = T->getTypeArgsAsWritten();\n    ID.AddInteger(TypeArgs.size());\n    for (auto Arg : TypeArgs) {\n      AddQualType(Arg);\n    }\n\n    auto Protocols = T->getProtocols();\n    ID.AddInteger(Protocols.size());\n    for (auto Protocol : Protocols) {\n      AddDecl(Protocol);\n    }\n\n    Hash.AddBoolean(T->isKindOfType());\n\n    VisitType(T);\n  }\n\n  void VisitObjCInterfaceType(const ObjCInterfaceType *T) {\n    \/\/ This type is handled by the parent type ObjCObjectType.\n    VisitObjCObjectType(T);\n  }\n\n  void VisitObjCTypeParamType(const ObjCTypeParamType *T) {\n    AddDecl(T->getDecl());\n    auto Protocols = T->getProtocols();\n    ID.AddInteger(Protocols.size());\n    for (auto Protocol : Protocols) {\n      AddDecl(Protocol);\n    }\n\n    VisitType(T);\n  }\n\n  void VisitPackExpansionType(const PackExpansionType *T) {\n    AddQualType(T->getPattern());\n    VisitType(T);\n  }\n\n  void VisitParenType(const ParenType *T) {\n    AddQualType(T->getInnerType());\n    VisitType(T);\n  }\n\n  void VisitPipeType(const PipeType *T) {\n    AddQualType(T->getElementType());\n    Hash.AddBoolean(T->isReadOnly());\n    VisitType(T);\n  }\n\n  void VisitPointerType(const PointerType *T) {\n    AddQualType(T->getPointeeType());\n    VisitType(T);\n  }\n\n  void VisitReferenceType(const ReferenceType *T) {\n    AddQualType(T->getPointeeTypeAsWritten());\n    VisitType(T);\n  }\n\n  void VisitLValueReferenceType(const LValueReferenceType *T) {\n    VisitReferenceType(T);\n  }\n\n  void VisitRValueReferenceType(const RValueReferenceType *T) {\n    VisitReferenceType(T);\n  }\n\n  void\n  VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {\n    AddType(T->getReplacedParameter());\n    Hash.AddTemplateArgument(T->getArgumentPack());\n    VisitType(T);\n  }\n\n  void VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {\n    AddType(T->getReplacedParameter());\n    AddQualType(T->getReplacementType());\n    VisitType(T);\n  }\n\n  void VisitTagType(const TagType *T) {\n    AddDecl(T->getDecl());\n    VisitType(T);\n  }\n\n  void VisitRecordType(const RecordType *T) { VisitTagType(T); }\n  void VisitEnumType(const EnumType *T) { VisitTagType(T); }\n\n  void VisitTemplateSpecializationType(const TemplateSpecializationType *T) {\n    ID.AddInteger(T->getNumArgs());\n    for (const auto &TA : T->template_arguments()) {\n      Hash.AddTemplateArgument(TA);\n    }\n    Hash.AddTemplateName(T->getTemplateName());\n    VisitType(T);\n  }\n\n  void VisitTemplateTypeParmType(const TemplateTypeParmType *T) {\n    ID.AddInteger(T->getDepth());\n    ID.AddInteger(T->getIndex());\n    Hash.AddBoolean(T->isParameterPack());\n    AddDecl(T->getDecl());\n  }\n\n  void VisitTypedefType(const TypedefType *T) {\n    AddDecl(T->getDecl());\n    QualType UnderlyingType = T->getDecl()->getUnderlyingType();\n    VisitQualifiers(UnderlyingType.getQualifiers());\n    while (true) {\n      if (const TypedefType *Underlying =\n              dyn_cast<TypedefType>(UnderlyingType.getTypePtr())) {\n        UnderlyingType = Underlying->getDecl()->getUnderlyingType();\n        continue;\n      }\n      if (const ElaboratedType *Underlying =\n              dyn_cast<ElaboratedType>(UnderlyingType.getTypePtr())) {\n        UnderlyingType = Underlying->getNamedType();\n        continue;\n      }\n\n      break;\n    }\n    AddType(UnderlyingType.getTypePtr());\n    VisitType(T);\n  }\n\n  void VisitTypeOfExprType(const TypeOfExprType *T) {\n    AddStmt(T->getUnderlyingExpr());\n    Hash.AddBoolean(T->isSugared());\n    if (T->isSugared())\n      AddQualType(T->desugar());\n\n    VisitType(T);\n  }\n  void VisitTypeOfType(const TypeOfType *T) {\n    AddQualType(T->getUnderlyingType());\n    VisitType(T);\n  }\n\n  void VisitTypeWithKeyword(const TypeWithKeyword *T) {\n    ID.AddInteger(T->getKeyword());\n    VisitType(T);\n  };\n\n  void VisitDependentNameType(const DependentNameType *T) {\n    AddNestedNameSpecifier(T->getQualifier());\n    AddIdentifierInfo(T->getIdentifier());\n    VisitTypeWithKeyword(T);\n  }\n\n  void VisitDependentTemplateSpecializationType(\n      const DependentTemplateSpecializationType *T) {\n    AddIdentifierInfo(T->getIdentifier());\n    AddNestedNameSpecifier(T->getQualifier());\n    ID.AddInteger(T->getNumArgs());\n    for (const auto &TA : T->template_arguments()) {\n      Hash.AddTemplateArgument(TA);\n    }\n    VisitTypeWithKeyword(T);\n  }\n\n  void VisitElaboratedType(const ElaboratedType *T) {\n    AddNestedNameSpecifier(T->getQualifier());\n    AddQualType(T->getNamedType());\n    VisitTypeWithKeyword(T);\n  }\n\n  void VisitUnaryTransformType(const UnaryTransformType *T) {\n    AddQualType(T->getUnderlyingType());\n    AddQualType(T->getBaseType());\n    VisitType(T);\n  }\n\n  void VisitUnresolvedUsingType(const UnresolvedUsingType *T) {\n    AddDecl(T->getDecl());\n    VisitType(T);\n  }\n\n  void VisitVectorType(const VectorType *T) {\n    AddQualType(T->getElementType());\n    ID.AddInteger(T->getNumElements());\n    ID.AddInteger(T->getVectorKind());\n    VisitType(T);\n  }\n\n  void VisitExtVectorType(const ExtVectorType * T) {\n    VisitVectorType(T);\n  }\n};\n} \/\/ namespace\n\nvoid ODRHash::AddType(const Type *T) {\n  assert(T && \"Expecting non-null pointer.\");\n  ODRTypeVisitor(ID, *this).Visit(T);\n}\n\nvoid ODRHash::AddQualType(QualType T) {\n  AddBoolean(T.isNull());\n  if (T.isNull())\n    return;\n  SplitQualType split = T.split();\n  ID.AddInteger(split.Quals.getAsOpaqueValue());\n  AddType(split.Ty);\n}\n\nvoid ODRHash::AddBoolean(bool Value) {\n  Bools.push_back(Value);\n}\n","avg_line_length":26.4952471483,"max_line_length":80,"alphanum_fraction":0.6782549421,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11729,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":10.0,"content":"#include \"header.hpp\"\n\n\n\/\/---[ Class Python Methods ]-----------\nstatic int Device_init(occa::py::Device *self,\n                       PyObject *args,\n                       PyObject *kwargs) {\n  self->device = NULL;\n\n  occa::device device;\n  occa::properties props;\n\n  occa::py::kwargParser parser;\n  parser\n    .startOptionalKwargs()\n    .add(\"device\", device)\n    .add(\"props\", props);\n\n  if (!parser.parse(args, kwargs)) {\n    return -1;\n  }\n\n  OCCA_INIT_TRY(\n    if (device.isInitialized()) {\n      self->device = new occa::device(device);\n    } else if (props.isInitialized()) {\n      self->device = new occa::device(props);\n    }\n  );\n\n  return 0;\n}\n\nstatic void Device_dealloc(occa::py::Device *self) {\n  delete self->device;\n  Py_TYPE(self)->tp_free((PyObject*) self);\n}\n\/\/======================================\n\n\n\/\/---[ Class Methods ]------------------\nstatic PyObject* Device_is_initialized(occa::py::Device *self) {\n  OCCA_TRY(\n    return occa::py::toPy(\n      (bool) (self->device &&\n              self->device->isInitialized())\n    );\n  );\n}\n\nstatic PyObject* Device_free(occa::py::Device *self) {\n  OCCA_TRY(\n    if (self->device) {\n      self->device->free();\n    }\n  );\n  return occa::py::None();\n}\n\nstatic PyObject* Device_mode(occa::py::Device *self) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n  OCCA_TRY(\n    return occa::py::toPy(\n      self->device->mode()\n    );\n  );\n}\n\nstatic PyObject* Device_properties(occa::py::Device *self) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n  OCCA_TRY(\n    return occa::py::toPy(\n      self->device->properties()\n    );\n  );\n}\n\nstatic PyObject* Device_kernel_properties(occa::py::Device *self) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n  OCCA_TRY(\n    return occa::py::toPy(\n      self->device->kernelProperties()\n    );\n  );\n}\n\nstatic PyObject* Device_memory_properties(occa::py::Device *self) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n  OCCA_TRY(\n    return occa::py::toPy(\n      self->device->memoryProperties()\n    );\n  );\n}\n\nstatic PyObject* Device_memory_size(occa::py::Device *self) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n  OCCA_TRY(\n    return occa::py::toPy(\n      (long long) self->device->memorySize()\n    );\n  );\n}\n\nstatic PyObject* Device_memory_allocated(occa::py::Device *self) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n  OCCA_TRY(\n    return occa::py::toPy(\n      (long long) self->device->memoryAllocated()\n    );\n  );\n}\n\nstatic PyObject* Device_finish(occa::py::Device *self) {\n  OCCA_TRY(\n    if (self->device) {\n      self->device->finish();\n    }\n  );\n  return occa::py::None();\n}\n\nstatic PyObject* Device_has_separate_memory_space(occa::py::Device *self) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n  OCCA_TRY(\n    return occa::py::toPy(\n      self->device->hasSeparateMemorySpace()\n    );\n  );\n}\n\n\n\/\/  |---[ Stream ]----------------------\nstatic PyObject* Device_create_stream(occa::py::Device *self) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n  OCCA_TRY(\n    return occa::py::toPy(\n      self->device->createStream()\n    );\n  );\n}\n\nstatic PyObject* Device_get_stream(occa::py::Device *self) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n  OCCA_TRY(\n    return occa::py::toPy(\n      self->device->getStream()\n    );\n  );\n}\n\nstatic PyObject* Device_set_stream(occa::py::Device *self,\n                                   PyObject *args,\n                                   PyObject *kwargs) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n\n  occa::stream stream;\n\n  occa::py::kwargParser parser;\n  parser\n    .add(\"stream\", stream);\n\n  if (!parser.parse(args, kwargs)) {\n    return NULL;\n  }\n\n  OCCA_TRY(\n    self->device->setStream(stream);\n  );\n\n  return occa::py::None();\n}\n\nstatic PyObject* Device_tag_stream(occa::py::Device *self) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n  OCCA_TRY(\n    return occa::py::toPy(\n      self->device->tagStream()\n    );\n  );\n}\n\nstatic PyObject* Device_wait_for(occa::py::Device *self,\n                                 PyObject *args,\n                                 PyObject *kwargs) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n\n  occa::streamTag tag;\n\n  occa::py::kwargParser parser;\n  parser\n    .add(\"tag\", tag);\n\n  if (!parser.parse(args, kwargs)) {\n    return NULL;\n  }\n\n  OCCA_TRY(\n    self->device->waitFor(tag);\n  );\n  return occa::py::None();\n}\n\nstatic PyObject* Device_time_between(occa::py::Device *self,\n                                     PyObject *args,\n                                     PyObject *kwargs) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n\n  occa::streamTag start, end;\n\n  occa::py::kwargParser parser;\n  parser\n    .add(\"start\", start)\n    .add(\"end\", end);\n\n  if (!parser.parse(args, kwargs)) {\n    return NULL;\n  }\n\n  OCCA_TRY(\n    return occa::py::toPy(\n      self->device->timeBetween(start, end)\n    );\n  );\n}\n\/\/  |===================================\n\n\n\/\/  |---[ Kernel ]----------------------\nstatic PyObject* Device_build_kernel(occa::py::Device *self,\n                                     PyObject *args,\n                                     PyObject *kwargs) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n\n  std::string filename, kernel;\n  occa::properties props;\n\n  occa::py::kwargParser parser;\n  parser\n    .add(\"filename\", filename)\n    .add(\"kernel\", kernel)\n    .add(\"props\", props);\n\n  if (!parser.parse(args, kwargs)) {\n    return NULL;\n  }\n\n  OCCA_TRY(\n    return occa::py::toPy(\n      self->device->buildKernel(filename, kernel, props)\n    );\n  );\n}\n\nstatic PyObject* Device_build_kernel_from_string(occa::py::Device *self,\n                                                 PyObject *args,\n                                                 PyObject *kwargs) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n\n  std::string source, kernel;\n  occa::properties props;\n\n  occa::py::kwargParser parser;\n  parser\n    .add(\"source\", source)\n    .add(\"kernel\", kernel)\n    .add(\"props\", props);\n\n  if (!parser.parse(args, kwargs)) {\n    return NULL;\n  }\n\n  OCCA_TRY(\n    return occa::py::toPy(\n      self->device->buildKernelFromString(source, kernel, props)\n    );\n  );\n}\n\nstatic PyObject* Device_build_kernel_from_binary(occa::py::Device *self,\n                                                 PyObject *args,\n                                                 PyObject *kwargs) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n\n  std::string filename, kernel;\n  occa::properties props;\n\n  occa::py::kwargParser parser;\n  parser\n    .add(\"filename\", filename)\n    .add(\"kernel\", kernel)\n    .add(\"props\", props);\n\n  if (!parser.parse(args, kwargs)) {\n    return NULL;\n  }\n\n  OCCA_TRY(\n    return occa::py::toPy(\n      self->device->buildKernelFromBinary(filename, kernel, props)\n    );\n  );\n}\n\/\/  |===================================\n\n\n\/\/  |---[ Memory ]----------------------\nstatic PyObject* Device_malloc(occa::py::Device *self,\n                               PyObject *args,\n                               PyObject *kwargs) {\n  if (!self->device) {\n    return occa::py::None();\n  }\n\n  long long entries = 0;\n  occa::py::ndArray src;\n  occa::dtype_t dtype;\n  occa::properties props;\n\n  occa::py::kwargParser parser;\n  parser\n    .startOptionalKwargs()\n    .add(\"entries\", entries)\n    .add(\"src\", src)\n    .add(\"dtype\", dtype)\n    .add(\"props\", props);\n\n  if (!parser.parse(args, kwargs)) {\n    return NULL;\n  }\n\n  if (!entries) {\n    entries = src.size();\n  }\n\n  OCCA_TRY(\n    return occa::py::toPy(\n      self->device->malloc(entries,\n                           dtype,\n                           src.ptr(),\n                           props)\n    );\n  );\n}\n\/\/  |===================================\n\nstatic PyObject* Device_ptr_as_long(occa::py::Device *self) {\n  OCCA_TRY(\n    return occa::py::toPy(\n      (long long) self->device->getModeDevice()\n    );\n  );\n}\n\/\/======================================\n\n\n\/\/---[ Module ]-------------------------\n#define DEVICE_METHOD_NO_ARGS(FUNC)             \\\n  OCCA_PY_METHOD_NO_ARGS(#FUNC, Device_##FUNC)\n\n#define DEVICE_METHOD_WITH_KWARGS(FUNC)             \\\n  OCCA_PY_METHOD_WITH_KWARGS(#FUNC, Device_##FUNC)\n\nOCCA_PY_METHODS(\n  Device_methods,\n  DEVICE_METHOD_NO_ARGS(is_initialized),\n  DEVICE_METHOD_NO_ARGS(free),\n  DEVICE_METHOD_NO_ARGS(mode),\n  DEVICE_METHOD_NO_ARGS(properties),\n  DEVICE_METHOD_NO_ARGS(kernel_properties),\n  DEVICE_METHOD_NO_ARGS(memory_properties),\n  DEVICE_METHOD_NO_ARGS(memory_size),\n  DEVICE_METHOD_NO_ARGS(memory_allocated),\n  DEVICE_METHOD_NO_ARGS(finish),\n  DEVICE_METHOD_NO_ARGS(has_separate_memory_space),\n  DEVICE_METHOD_NO_ARGS(create_stream),\n  DEVICE_METHOD_NO_ARGS(get_stream),\n  DEVICE_METHOD_WITH_KWARGS(set_stream),\n  DEVICE_METHOD_NO_ARGS(tag_stream),\n  DEVICE_METHOD_WITH_KWARGS(wait_for),\n  DEVICE_METHOD_WITH_KWARGS(time_between),\n  DEVICE_METHOD_WITH_KWARGS(build_kernel),\n  DEVICE_METHOD_WITH_KWARGS(build_kernel_from_string),\n  DEVICE_METHOD_WITH_KWARGS(build_kernel_from_binary),\n  DEVICE_METHOD_WITH_KWARGS(malloc),\n  DEVICE_METHOD_NO_ARGS(ptr_as_long)\n);\n\nstatic PyTypeObject DeviceType = {\n  PyVarObject_HEAD_INIT(NULL, 0)\n  \"occa.c.Device\",                          \/\/ tp_name\n  sizeof(occa::py::Device),                 \/\/ tp_basicsize\n  0,                                        \/\/ tp_itemsize\n  (destructor) Device_dealloc,              \/\/ tp_dealloc\n  0,                                        \/\/ tp_print\n  0,                                        \/\/ tp_getattr\n  0,                                        \/\/ tp_setattr\n  0,                                        \/\/ tp_reserved\n  0,                                        \/\/ tp_repr\n  0,                                        \/\/ tp_as_number\n  0,                                        \/\/ tp_as_sequence\n  0,                                        \/\/ tp_as_mapping\n  0,                                        \/\/ tp_hash\n  0,                                        \/\/ tp_call\n  0,                                        \/\/ tp_str\n  0,                                        \/\/ tp_getattro\n  0,                                        \/\/ tp_setattro\n  0,                                        \/\/ tp_as_buffer\n  Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, \/\/ tp_flags\n  \"Wrapper for occa::device\",               \/\/ tp_doc\n  0,                                        \/\/ tp_traverse\n  0,                                        \/\/ tp_clear\n  0,                                        \/\/ tp_richcompare\n  0,                                        \/\/ tp_weaklistoffset\n  0,                                        \/\/ tp_iter\n  0,                                        \/\/ tp_iternext\n  Device_methods,                           \/\/ tp_methods\n  0,                                        \/\/ tp_members\n  0,                                        \/\/ tp_getset\n  0,                                        \/\/ tp_base\n  0,                                        \/\/ tp_dict\n  0,                                        \/\/ tp_descr_get\n  0,                                        \/\/ tp_descr_set\n  0,                                        \/\/ tp_dictoffset\n  (initproc) Device_init,                   \/\/ tp_init\n  0,                                        \/\/ tp_alloc\n  0                                         \/\/ tp_new\n};\n\nstatic bool device_has_valid_module() {\n  DeviceType.tp_new = PyType_GenericNew;\n  return PyType_Ready(&DeviceType) >= 0;\n}\n\nstatic void device_init_module(PyObject *module) {\n  Py_INCREF(&DeviceType);\n  PyModule_AddObject(module,\n                     \"Device\",\n                     (PyObject*) &DeviceType);\n}\n\nOCCA_PY_MODULE(device, OCCA_PY_NO_METHODS)\n\/\/======================================\n","avg_line_length":24.6407563025,"max_line_length":75,"alphanum_fraction":0.5117230795,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2087,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":84.0,"content":"#include \"httpconnectionhandlerpool.h\"\n\nHttpConnectionHandlerPool::HttpConnectionHandlerPool(QSettings* settings, HttpRequestHandler* requestHandler)\n    : QObject()\n{\n    Q_ASSERT(settings!=0);\n    this->settings=settings;\n    this->requestHandler=requestHandler;\n    cleanupTimer.start(settings->value(\"cleanupInterval\",1000).toInt());\n    connect(&cleanupTimer, SIGNAL(timeout()), SLOT(cleanup()));\n}\n\n\nHttpConnectionHandlerPool::~HttpConnectionHandlerPool() {    \n    foreach(HttpConnectionHandler* handler, pool) {\n        connect(handler,SIGNAL(finished()),handler,SLOT(deleteLater()));\n        handler->quit();\n    }\n}\n\n\nHttpConnectionHandler* HttpConnectionHandlerPool::getConnectionHandler() {   \n    HttpConnectionHandler* freeHandler=0;\n    mutex.lock();\n    \/\/ find a free handler in pool\n    foreach(HttpConnectionHandler* handler, pool) {\n        if (!handler->isBusy()) {\n            freeHandler=handler;\n            freeHandler->setBusy();\n            break;\n        }\n    }\n    \/\/ create a new handler, if necessary\n    if (!freeHandler) {\n        int maxConnectionHandlers=settings->value(\"maxThreads\",100).toInt();\n        if (pool.count()<maxConnectionHandlers) {\n            freeHandler=new HttpConnectionHandler(settings,requestHandler);\n            freeHandler->setBusy();\n            pool.append(freeHandler);\n        }\n    }\n    mutex.unlock();\n    return freeHandler;\n}\n\n\n\nvoid HttpConnectionHandlerPool::cleanup() {\n    int maxIdleHandlers=settings->value(\"minThreads\",1).toInt();\n    int idleCounter=0;\n    mutex.lock();\n    foreach(HttpConnectionHandler* handler, pool) {\n        if (!handler->isBusy()) {\n            if (++idleCounter > maxIdleHandlers) {\n                pool.removeOne(handler);\n                qDebug(\"HttpConnectionHandlerPool: Removed connection handler (%p), pool size is now %i\",handler,pool.size());\n                connect(handler,SIGNAL(finished()),handler,SLOT(deleteLater()));\n                handler->quit();\n                break; \/\/ remove only one handler in each interval\n            }\n        }\n    }\n    mutex.unlock();\n}\n","avg_line_length":32.1076923077,"max_line_length":126,"alphanum_fraction":0.6406324868,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13088,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <QtGlobal>\n\/\/ Automatically generated by extract_strings.py\n#ifdef __GNUC__\n#define UNUSED __attribute__((unused))\n#else\n#define UNUSED\n#endif\nstatic const char UNUSED *bitcoin_strings[] = {QT_TRANSLATE_NOOP(\"bitcoin-core\", \"To use the %s option\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"%s, you must set a rpcpassword in the configuration file:\\n\"\n\" %s\\n\"\n\"It is recommended you use the following random password:\\n\"\n\"rpcuser=Foxyrpc\\n\"\n\"rpcpassword=%s\\n\"\n\"(you do not need to remember this password)\\n\"\n\"The username and password MUST NOT be the same.\\n\"\n\"If the file does not exist, create it with owner-readable-only file \"\n\"permissions.\\n\"\n\"It is also recommended to set alertnotify so you are notified of problems;\\n\"\n\"for example: alertnotify=echo %%s | mail -s \\\"Foxy Alert\\\" admin@foo.\"\n\"com\\n\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"An error occurred while setting up the RPC port %u for listening on IPv6, \"\n\"falling back to IPv4: %s\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"An error occurred while setting up the RPC port %u for listening on IPv4: %s\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"You must set rpcpassword=<password> in the configuration file:\\n\"\n\"%s\\n\"\n\"If the file does not exist, create it with owner-readable-only file \"\n\"permissions.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Foxy version\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Usage:\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Send command to -server or Foxyd\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"List commands\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Get help for a command\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Foxy\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Options:\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"This help message\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Specify configuration file (default: Foxy.conf)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Specify pid file (default: Foxyd.pid)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Specify data directory\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Specify wallet file (within data directory)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Set database cache size in megabytes (default: 25)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Set database disk log size in megabytes (default: 100)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Specify connection timeout in milliseconds (default: 5000)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Connect through socks proxy\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Select the version of socks proxy to use (4-5, default: 5)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Use proxy to reach tor hidden services (default: same as -proxy)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Allow DNS lookups for -addnode, -seednode and -connect\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Listen for connections on <port> (default: 23185 or testnet: 33185)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Maintain at most <n> connections to peers (default: 125)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Add a node to connect to and attempt to keep the connection open\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Connect only to the specified node(s)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Connect to a node to retrieve peer addresses, and disconnect\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Specify your own public address\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Only connect to nodes in network <net> (IPv4, IPv6 or Tor)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Discover own IP address (default: 1 when listening and no -externalip)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Find peers using internet relay chat (default: 0)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Accept connections from outside (default: 1 if no -proxy or -connect)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Bind to given address. Use [host]:port notation for IPv6\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Find peers using DNS lookup (default: 1)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Stake your coins to support network and gain reward (default: 1)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Sync time with other nodes. Disable if time on your system is precise e.g. \"\n\"syncing with NTP (default: 1)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Sync checkpoints policy (default: strict)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Threshold for disconnecting misbehaving peers (default: 100)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Number of seconds to keep misbehaving peers from reconnecting (default: \"\n\"86400)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Use UPnP to map the listening port (default: 1 when listening)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Use UPnP to map the listening port (default: 0)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Detach block and address databases. Increases shutdown time (default: 0)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Fee per KB to add to transactions you send\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"When creating transactions, ignore inputs with value less than this \"\n\"(default: 0.01)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Accept command line and JSON-RPC commands\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Run in the background as a daemon and accept commands\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Use the test network\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Output extra debugging information. Implies all other -debug* options\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Output extra network debugging information\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Prepend debug output with timestamp\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Shrink debug.log file on client startup (default: 1 when no -debug)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Send trace\/debug info to console instead of debug.log file\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Send trace\/debug info to debugger\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Username for JSON-RPC connections\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Password for JSON-RPC connections\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Listen for JSON-RPC connections on <port> (default: 23186 or testnet: 33186)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Allow JSON-RPC connections from specified IP address\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Send commands to node running on <ip> (default: 127.0.0.1)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Execute command when the best block changes (%s in cmd is replaced by block \"\n\"hash)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Execute command when a wallet transaction changes (%s in cmd is replaced by \"\n\"TxID)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Require a confirmations for change (default: 0)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Enforce transaction scripts to use canonical PUSH operators (default: 1)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Execute command when a relevant alert is received (%s in cmd is replaced by \"\n\"message)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Upgrade wallet to latest format\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Set key pool size to <n> (default: 100)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Rescan the block chain for missing wallet transactions\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Attempt to recover private keys from a corrupt wallet.dat\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"How many blocks to check at startup (default: 2500, 0 = all)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"How thorough the block verification is (0-6, default: 1)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Imports blocks from external blk000?.dat file\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Block creation options:\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Set minimum block size in bytes (default: 0)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Set maximum block size in bytes (default: 250000)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Set maximum size of high-priority\/low-fee transactions in bytes (default: \"\n\"27000)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"SSL options: (see the Bitcoin Wiki for SSL setup instructions)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Use OpenSSL (https) for JSON-RPC connections\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Server certificate file (default: server.cert)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Server private key (default: server.pem)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:\"\n\"@STRENGTH)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Invalid amount for -paytxfee=<amount>: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Warning: -paytxfee is set very high! This is the transaction fee you will \"\n\"pay if you send a transaction.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Invalid amount for -mininput=<amount>: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Wallet %s resides outside data directory %s.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Cannot obtain a lock on data directory %s.  Foxy is probably already \"\n\"running.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Verifying database integrity...\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Error initializing database environment %s! To recover, BACKUP THAT \"\n\"DIRECTORY, then remove everything from it except for wallet.dat.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as \"\n\"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect \"\n\"you should restore from a backup.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"wallet.dat corrupt, salvage failed\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Unknown -socks proxy version requested: %i\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Unknown network specified in -onlynet: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Invalid -proxy address: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Invalid -tor address: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Cannot resolve -bind address: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Failed to listen on any port. Use -listen=0 if you want this.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Cannot resolve -externalip address: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Invalid amount for -reservebalance=<amount>\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Unable to sign checkpoint, wrong checkpointkey?\\n\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Loading block index...\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error loading blkindex.dat\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Loading wallet...\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error loading wallet.dat: Wallet corrupted\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Warning: error reading wallet.dat! All keys read correctly, but transaction \"\n\"data or address book entries might be missing or incorrect.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error loading wallet.dat: Wallet requires newer version of Foxy\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Wallet needed to be rewritten: restart Foxy to complete\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error loading wallet.dat\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Cannot downgrade wallet\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Cannot initialize keypool\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Cannot write default address\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Rescanning...\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Importing blockchain data file.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Importing bootstrap blockchain data file.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Loading addresses...\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error: could not start node\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Done loading\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Unable to bind to %s on this computer. Foxy is probably already running.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Unable to bind to %s on this computer (bind returned error %d, %s)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error: Wallet locked, unable to create transaction  \"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error: Wallet unlocked for staking only, unable to create transaction.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Error: This transaction requires a transaction fee of at least %s because of \"\n\"its amount, complexity, or use of recently received funds  \"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error: Transaction creation failed  \"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Sending...\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Error: The transaction was rejected.  This might happen if some of the coins \"\n\"in your wallet were already spent, such as if you used a copy of wallet.dat \"\n\"and coins were spent in the copy but not marked as spent here.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Invalid amount\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Insufficient funds\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Warning: Please check that your computer's date and time are correct! If \"\n\"your clock is wrong Foxy will not work properly.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Warning: This version is obsolete, upgrade required!\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"WARNING: syncronized checkpoint violation detected, but skipped!\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Warning: Disk space is low!\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"WARNING: Invalid checkpoint found! Displayed transactions may not be \"\n\"correct! You may need to upgrade, or notify developers.\"),\n};","avg_line_length":65.1144278607,"max_line_length":108,"alphanum_fraction":0.7593979218,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13962,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":560.0,"content":"\/\/ Copyright (c) 2021 by Apex.AI Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ SPDX-License-Identifier: Apache-2.0\n\n#include \"iceoryx_hoofs\/posix_wrapper\/named_pipe.hpp\"\n#include \"iceoryx_hoofs\/cxx\/deadline_timer.hpp\"\n#include \"iceoryx_hoofs\/cxx\/helplets.hpp\"\n#include \"iceoryx_hoofs\/posix_wrapper\/posix_call.hpp\"\n\n#include <thread>\n\nnamespace iox\n{\nnamespace posix\n{\nconstexpr const char NamedPipe::NAMED_PIPE_PREFIX[];\nconstexpr units::Duration NamedPipe::CYCLE_TIME;\nconstexpr units::Duration NamedPipe::NamedPipeData::WAIT_FOR_INIT_SLEEP_TIME;\nconstexpr units::Duration NamedPipe::NamedPipeData::WAIT_FOR_INIT_TIMEOUT;\n\nNamedPipe::NamedPipe() noexcept\n{\n    this->m_isInitialized = false;\n    this->m_errorValue = IpcChannelError::NOT_INITIALIZED;\n}\n\n\/\/ NOLINTNEXTLINE(readability-function-size) todo(iox-#832): make a struct out of arguments\nNamedPipe::NamedPipe(const IpcChannelName_t& name,\n                     const IpcChannelSide channelSide,\n                     const size_t maxMsgSize,\n                     const uint64_t maxMsgNumber) noexcept\n{\n    \/\/ We do not store maxMsgSize or maxMsgNumber, this is just technical debt since every ipc channel\n    \/\/ requires the same behavior as the message queue. The named pipe would get later two template\n    \/\/ parameters MAX_MSG_SIZE and MAX_MSG_NUMBER from which the Message_t size and m_messages queue\n    \/\/ size is obtained. Reducing the max message size \/ number of messages even further would not gain\n    \/\/ reduced memory usage or decreased runtime. See issue #832.\n    if (name.size() + strlen(NAMED_PIPE_PREFIX) > MAX_MESSAGE_SIZE)\n    {\n        std::cerr << \"The named pipe name: \\\"\" << name\n                  << \"\\\" is too long. Maxium name length is: \" << MAX_MESSAGE_SIZE - strlen(NAMED_PIPE_PREFIX)\n                  << std::endl;\n        m_isInitialized = false;\n        m_errorValue = IpcChannelError::INVALID_CHANNEL_NAME;\n        return;\n    }\n\n    \/\/ leading slash is allowed even though it is not a valid file name\n    bool isValidPipeName = cxx::isValidFileName(name)\n                           \/\/ name is checked for emptiness, so it's ok to get a first member\n                           \/\/ NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n                           || (!name.empty() && name.c_str()[0] == '\/' && cxx::isValidFileName(*name.substr(1)));\n    if (!isValidPipeName)\n    {\n        std::cerr << \"The named pipe name: \\\"\" << name << \"\\\" is not a valid file path name.\" << std::endl;\n        m_isInitialized = false;\n        m_errorValue = IpcChannelError::INVALID_CHANNEL_NAME;\n        return;\n    }\n\n    if (maxMsgSize > MAX_MESSAGE_SIZE)\n    {\n        std::cerr << \"A message size of \" << maxMsgSize << \" exceeds the maximum message size for named pipes of \"\n                  << MAX_MESSAGE_SIZE << std::endl;\n        m_isInitialized = false;\n        m_errorValue = IpcChannelError::MAX_MESSAGE_SIZE_EXCEEDED;\n        return;\n    }\n\n    if (maxMsgNumber > MAX_NUMBER_OF_MESSAGES)\n    {\n        std::cerr << \"A message amount of \" << maxMsgNumber\n                  << \" exceeds the maximum number of messages for named pipes of \" << MAX_NUMBER_OF_MESSAGES\n                  << std::endl;\n        m_isInitialized = false;\n        m_errorValue = IpcChannelError::MAX_MESSAGE_SIZE_EXCEEDED;\n        return;\n    }\n\n    if (SharedMemoryObject::create(\n            convertName(NAMED_PIPE_PREFIX, name),\n            \/\/ add alignment since we require later aligned memory to perform the placement new of\n            \/\/ m_messages. when we add the alignment it is guaranteed that enough memory should be available.\n            sizeof(NamedPipeData) + alignof(NamedPipeData),\n            AccessMode::READ_WRITE,\n            (channelSide == IpcChannelSide::SERVER) ? OpenMode::OPEN_OR_CREATE : OpenMode::OPEN_EXISTING,\n            iox::posix::SharedMemoryObject::NO_ADDRESS_HINT)\n            .and_then([&](auto& r) { m_sharedMemory.emplace(std::move(r)); })\n            .or_else([&](auto) {\n                std::cerr << \"Unable to open shared memory: \\\"\" << convertName(NAMED_PIPE_PREFIX, name)\n                          << \"\\\" for named pipe \\\"\" << name << \"\\\"\" << std::endl;\n                m_isInitialized = false;\n                m_errorValue = (channelSide == IpcChannelSide::CLIENT) ? IpcChannelError::NO_SUCH_CHANNEL\n                                                                       : IpcChannelError::INTERNAL_LOGIC_ERROR;\n            })\n            .has_error())\n    {\n        return;\n    }\n\n    m_data = static_cast<NamedPipeData*>(m_sharedMemory->allocate(sizeof(NamedPipeData), alignof(NamedPipeData)));\n\n    m_isInitialized = true;\n    if (m_sharedMemory->hasOwnership())\n    {\n        new (m_data) NamedPipeData(m_isInitialized, m_errorValue, maxMsgNumber);\n    }\n    else\n    {\n        m_isInitialized = m_data->waitForInitialization();\n        if (!m_isInitialized)\n        {\n            m_errorValue = IpcChannelError::INTERNAL_LOGIC_ERROR;\n        }\n    }\n}\n\nNamedPipe::NamedPipe(NamedPipe&& rhs) noexcept\n{\n    *this = std::move(rhs);\n}\n\nNamedPipe& NamedPipe::operator=(NamedPipe&& rhs) noexcept\n{\n    if (this != &rhs)\n    {\n        IOX_DISCARD_RESULT(destroy());\n        CreationPattern_t::operator=(std::move(rhs));\n\n        m_sharedMemory = std::move(rhs.m_sharedMemory);\n        m_data = std::move(rhs.m_data);\n        rhs.m_data = nullptr;\n    }\n\n    return *this;\n}\n\nNamedPipe::~NamedPipe() noexcept\n{\n    IOX_DISCARD_RESULT(destroy());\n}\n\ntemplate <typename Prefix>\nIpcChannelName_t NamedPipe::convertName(const Prefix& p, const IpcChannelName_t& name) noexcept\n{\n    return IpcChannelName_t(cxx::TruncateToCapacity,\n                            \/\/ NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n                            cxx::concatenate(p, (name.c_str()[0] == '\/') ? *name.substr(1) : name).c_str());\n}\n\ncxx::expected<IpcChannelError> NamedPipe::destroy() noexcept\n{\n    if (m_isInitialized)\n    {\n        m_isInitialized = false;\n        m_errorValue = IpcChannelError::NOT_INITIALIZED;\n        if (m_sharedMemory->hasOwnership())\n        {\n            m_data->~NamedPipeData();\n        }\n        m_sharedMemory.reset();\n        m_data = nullptr;\n    }\n    return cxx::success<>();\n}\n\n\/\/ NOLINTNEXTLINE(readability-convert-member-functions-to-static) API can be misused if IPC channel changes\ncxx::expected<bool, IpcChannelError> NamedPipe::isOutdated() noexcept\n{\n    return cxx::success<bool>(false);\n}\n\ncxx::expected<bool, IpcChannelError> NamedPipe::unlinkIfExists(const IpcChannelName_t& name) noexcept\n{\n    constexpr int ERROR_CODE = -1;\n    auto unlinkCall = posixCall(iox_shm_unlink)(convertName(NAMED_PIPE_PREFIX, name).c_str())\n                          .failureReturnValue(ERROR_CODE)\n                          .ignoreErrnos(ENOENT)\n                          .evaluate();\n    if (!unlinkCall.has_error())\n    {\n        return cxx::success<bool>(unlinkCall->errnum != ENOENT);\n    }\n\n    return cxx::error<IpcChannelError>(IpcChannelError::INTERNAL_LOGIC_ERROR);\n}\n\ncxx::expected<IpcChannelError> NamedPipe::trySend(const std::string& message) const noexcept\n{\n    if (!m_isInitialized)\n    {\n        return cxx::error<IpcChannelError>(IpcChannelError::NOT_INITIALIZED);\n    }\n\n    if (message.size() > MAX_MESSAGE_SIZE)\n    {\n        return cxx::error<IpcChannelError>(IpcChannelError::MESSAGE_TOO_LONG);\n    }\n\n    auto result = m_data->sendSemaphore().tryWait();\n    cxx::Expects(!result.has_error());\n\n    if (*result)\n    {\n        IOX_DISCARD_RESULT(m_data->messages.push(Message_t(cxx::TruncateToCapacity, message)));\n        cxx::Expects(!m_data->receiveSemaphore().post().has_error());\n        return cxx::success<>();\n    }\n    return cxx::error<IpcChannelError>(IpcChannelError::TIMEOUT);\n}\n\ncxx::expected<IpcChannelError> NamedPipe::send(const std::string& message) const noexcept\n{\n    if (!m_isInitialized)\n    {\n        return cxx::error<IpcChannelError>(IpcChannelError::NOT_INITIALIZED);\n    }\n\n    if (message.size() > MAX_MESSAGE_SIZE)\n    {\n        return cxx::error<IpcChannelError>(IpcChannelError::MESSAGE_TOO_LONG);\n    }\n\n    cxx::Expects(!m_data->sendSemaphore().wait().has_error());\n    IOX_DISCARD_RESULT(m_data->messages.push(Message_t(cxx::TruncateToCapacity, message)));\n    cxx::Expects(!m_data->receiveSemaphore().post().has_error());\n\n    return cxx::success<>();\n}\n\ncxx::expected<IpcChannelError> NamedPipe::timedSend(const std::string& message,\n                                                    const units::Duration& timeout) const noexcept\n{\n    if (!m_isInitialized)\n    {\n        return cxx::error<IpcChannelError>(IpcChannelError::NOT_INITIALIZED);\n    }\n\n    if (message.size() > MAX_MESSAGE_SIZE)\n    {\n        return cxx::error<IpcChannelError>(IpcChannelError::MESSAGE_TOO_LONG);\n    }\n\n    auto result = m_data->sendSemaphore().timedWait(timeout);\n    cxx::Expects(!result.has_error());\n\n    if (*result == SemaphoreWaitState::NO_TIMEOUT)\n    {\n        IOX_DISCARD_RESULT(m_data->messages.push(Message_t(cxx::TruncateToCapacity, message)));\n        cxx::Expects(!m_data->receiveSemaphore().post().has_error());\n        return cxx::success<>();\n    }\n    return cxx::error<IpcChannelError>(IpcChannelError::TIMEOUT);\n}\n\ncxx::expected<std::string, IpcChannelError> NamedPipe::receive() const noexcept\n{\n    if (!m_isInitialized)\n    {\n        return cxx::error<IpcChannelError>(IpcChannelError::NOT_INITIALIZED);\n    }\n\n    cxx::Expects(!m_data->receiveSemaphore().wait().has_error());\n    auto message = m_data->messages.pop();\n    if (message.has_value())\n    {\n        cxx::Expects(!m_data->sendSemaphore().post().has_error());\n        return cxx::success<std::string>(message->c_str());\n    }\n    return cxx::error<IpcChannelError>(IpcChannelError::INTERNAL_LOGIC_ERROR);\n}\n\ncxx::expected<std::string, IpcChannelError> NamedPipe::tryReceive() const noexcept\n{\n    if (!m_isInitialized)\n    {\n        return cxx::error<IpcChannelError>(IpcChannelError::NOT_INITIALIZED);\n    }\n\n    auto result = m_data->receiveSemaphore().tryWait();\n    cxx::Expects(!result.has_error());\n\n    if (*result)\n    {\n        auto message = m_data->messages.pop();\n        if (message.has_value())\n        {\n            cxx::Expects(!m_data->sendSemaphore().post().has_error());\n            return cxx::success<std::string>(message->c_str());\n        }\n        return cxx::error<IpcChannelError>(IpcChannelError::INTERNAL_LOGIC_ERROR);\n    }\n\n    return cxx::error<IpcChannelError>(IpcChannelError::TIMEOUT);\n}\n\ncxx::expected<std::string, IpcChannelError> NamedPipe::timedReceive(const units::Duration& timeout) const noexcept\n{\n    if (!m_isInitialized)\n    {\n        return cxx::error<IpcChannelError>(IpcChannelError::NOT_INITIALIZED);\n    }\n\n    auto result = m_data->receiveSemaphore().timedWait(timeout);\n    cxx::Expects(!result.has_error());\n\n    if (*result == SemaphoreWaitState::NO_TIMEOUT)\n    {\n        auto message = m_data->messages.pop();\n        if (message.has_value())\n        {\n            cxx::Expects(!m_data->sendSemaphore().post().has_error());\n            return cxx::success<std::string>(message->c_str());\n        }\n        return cxx::error<IpcChannelError>(IpcChannelError::INTERNAL_LOGIC_ERROR);\n    }\n    return cxx::error<IpcChannelError>(IpcChannelError::TIMEOUT);\n}\n\n\/\/ NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) semaphores are initalized via placementCreate call\nNamedPipe::NamedPipeData::NamedPipeData(bool& isInitialized,\n                                        IpcChannelError& error,\n                                        const uint64_t maxMsgNumber) noexcept\n{\n    auto signalError = [&](const char* name) {\n        std::cerr << \"Unable to create \" << name << \" semaphore for named pipe \\\"\" << 'x' << \"\\\"\";\n        isInitialized = false;\n        error = IpcChannelError::INTERNAL_LOGIC_ERROR;\n    };\n\n    Semaphore::placementCreate(\n        &semaphores[SEND_SEMAPHORE], CreateUnnamedSharedMemorySemaphore, static_cast<unsigned int>(maxMsgNumber))\n        .or_else([&](auto) { signalError(\"send\"); });\n\n    if (!isInitialized)\n    {\n        return;\n    }\n\n    Semaphore::placementCreate(&semaphores[RECEIVE_SEMAPHORE], CreateUnnamedSharedMemorySemaphore, 0U)\n        .or_else([&](auto) { signalError(\"receive\"); });\n\n    if (!isInitialized)\n    {\n        return;\n    }\n\n    initializationGuard.store(VALID_DATA);\n}\n\nNamedPipe::NamedPipeData::~NamedPipeData() noexcept\n{\n    if (hasValidState())\n    {\n        sendSemaphore().~Semaphore();\n        receiveSemaphore().~Semaphore();\n    }\n}\n\nSemaphore& NamedPipe::NamedPipeData::sendSemaphore() noexcept\n{\n    return reinterpret_cast<Semaphore&>(semaphores[SEND_SEMAPHORE]);\n}\n\nSemaphore& NamedPipe::NamedPipeData::receiveSemaphore() noexcept\n{\n    return reinterpret_cast<Semaphore&>(semaphores[RECEIVE_SEMAPHORE]);\n}\n\nbool NamedPipe::NamedPipeData::waitForInitialization() const noexcept\n{\n    if (hasValidState())\n    {\n        return true;\n    }\n\n    cxx::DeadlineTimer deadlineTimer(WAIT_FOR_INIT_TIMEOUT);\n\n    while (!deadlineTimer.hasExpired())\n    {\n        std::this_thread::sleep_for(std::chrono::nanoseconds(WAIT_FOR_INIT_SLEEP_TIME.toNanoseconds()));\n        if (hasValidState())\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\nbool NamedPipe::NamedPipeData::hasValidState() const noexcept\n{\n    return initializationGuard.load() == VALID_DATA;\n}\n\n} \/\/ namespace posix\n} \/\/ namespace iox\n","avg_line_length":34.0536585366,"max_line_length":114,"alphanum_fraction":0.6514825956,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5807,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":168.0,"content":"\/\/ unions.cpp\n\/\/ Copyright (c) 2014 - 2017, zhiayang\n\/\/ Licensed under the Apache License Version 2.0.\n\n#include \"ast.h\"\n#include \"errors.h\"\n#include \"typecheck.h\"\n\n#include \"ir\/type.h\"\n#include \"memorypool.h\"\n\n\/\/ defined in typecheck\/structs.cpp\nvoid checkFieldRecursion(sst::TypecheckState* fs, fir::Type* strty, fir::Type* field, const Location& floc);\nvoid checkTransparentFieldRedefinition(sst::TypecheckState* fs, sst::TypeDefn* defn, const std::vector<sst::StructFieldDefn*>& fields);\n\n\n\n\nTCResult ast::UnionDefn::generateDeclaration(sst::TypecheckState* fs, fir::Type* infer, const TypeParamMap_t& gmaps)\n{\n\tfs->pushLoc(this);\n\tdefer(fs->popLoc());\n\n\tauto [ success, ret ] = this->checkForExistingDeclaration(fs, gmaps);\n\tif(!success)    return TCResult::getParametric();\n\telse if(ret)    return TCResult(ret);\n\n\tauto defnname = util::typeParamMapToString(this->name, gmaps);\n\n\tbool israw = this->attrs.has(attr::RAW);\n\n\tsst::TypeDefn* defn = 0;\n\tif(israw)   defn = util::pool<sst::RawUnionDefn>(this->loc);\n\telse        defn = util::pool<sst::UnionDefn>(this->loc);\n\n\tdefn->bareName = this->name;\n\tdefn->attrs = this->attrs;\n\n\tdefn->id = Identifier(defnname, IdKind::Type);\n\tdefn->id.scope = this->enclosingScope;\n\tdefn->visibility = this->visibility;\n\tdefn->original = this;\n\tdefn->enclosingScope = this->enclosingScope;\n\tdefn->innerScope = this->enclosingScope.appending(defnname);\n\n\tif(israw)   defn->type = fir::RawUnionType::createWithoutBody(defn->id.convertToName());\n\telse        defn->type = fir::UnionType::createWithoutBody(defn->id.convertToName());\n\n\tif(auto err = fs->checkForShadowingOrConflictingDefinition(defn, [](auto, auto) -> bool { return true; }))\n\t\treturn TCResult(err);\n\n\tdefn->enclosingScope.stree->addDefinition(defnname, defn, gmaps);\n\n\tthis->genericVersions.push_back({ defn, fs->getGenericContextStack() });\n\n\tfs->typeDefnMap[defn->type] = defn;\n\treturn TCResult(defn);\n}\n\n\nTCResult ast::UnionDefn::typecheck(sst::TypecheckState* fs, fir::Type* infer, const TypeParamMap_t& gmaps)\n{\n\tfs->pushLoc(this);\n\tdefer(fs->popLoc());\n\n\tauto tcr = this->generateDeclaration(fs, infer, gmaps);\n\tif(tcr.isParametric())  return tcr;\n\telse if(tcr.isError())  error(this, \"failed to generate declaration for union '%s'\", this->name);\n\n\n\tif(this->finishedTypechecking.find(tcr.defn()) != this->finishedTypechecking.end())\n\t\treturn TCResult(tcr.defn());\n\n\tsst::TypeDefn* ret = 0;\n\tif(this->attrs.has(attr::RAW))\n\t{\n\t\tauto defn = dcast(sst::RawUnionDefn, tcr.defn());\n\t\ticeAssert(defn);\n\n\t\tfs->teleportInto(defn->innerScope);\n\n\t\t\/\/* in many ways raw unions resemble structs rather than tagged unions\n\t\t\/\/* and since we are using sst::StructFieldDefn for the variants, we will need\n\t\t\/\/* to enter the struct body.\n\n\t\tauto unionTy = defn->type->toRawUnionType();\n\t\tfs->pushSelfContext(unionTy);\n\n\t\tutil::hash_map<std::string, fir::Type*> types;\n\t\tutil::hash_map<std::string, sst::StructFieldDefn*> fields;\n\n\n\n\t\tauto make_field = [fs, unionTy](const std::string& name, const Location& loc, pts::Type* ty) -> sst::StructFieldDefn* {\n\n\t\t\tauto vdef = util::pool<ast::VarDefn>(loc);\n\t\t\tvdef->immut = false;\n\t\t\tvdef->name = name;\n\t\t\tvdef->initialiser = nullptr;\n\t\t\tvdef->type = ty;\n\t\t\tvdef->isField = true;\n\n\t\t\tauto sfd = dcast(sst::StructFieldDefn, vdef->typecheck(fs).defn());\n\t\t\ticeAssert(sfd);\n\n\t\t\tif(fir::isRefCountedType(sfd->type))\n\t\t\t\terror(sfd, \"reference-counted type '%s' cannot be a member of a raw union\", sfd->type);\n\n\t\t\tcheckFieldRecursion(fs, unionTy, sfd->type, sfd->loc);\n\t\t\treturn sfd;\n\t\t};\n\n\t\tstd::vector<sst::StructFieldDefn*> tfields;\n\t\tstd::vector<sst::StructFieldDefn*> allFields;\n\n\t\tfor(auto variant : this->cases)\n\t\t{\n\t\t\tauto sfd = make_field(variant.first, std::get<1>(variant.second), std::get<2>(variant.second));\n\t\t\ticeAssert(sfd);\n\n\t\t\tfields[sfd->id.name] = sfd;\n\t\t\ttypes[sfd->id.name] = sfd->type;\n\n\t\t\tallFields.push_back(sfd);\n\t\t}\n\n\n\t\t\/\/ do the transparent fields\n\t\t{\n\t\t\tsize_t tfn = 0;\n\t\t\tfor(auto [ loc, pty ] : this->transparentFields)\n\t\t\t{\n\t\t\t\tauto sfd = make_field(fir::obfuscateName(\"transparent_field\", tfn++), loc, pty);\n\t\t\t\ticeAssert(sfd);\n\n\t\t\t\tsfd->isTransparentField = true;\n\n\t\t\t\t\/\/ still add to the types, cos we need to compute sizes and stuff\n\t\t\t\ttypes[sfd->id.name] = sfd->type;\n\t\t\t\ttfields.push_back(sfd);\n\t\t\t\tallFields.push_back(sfd);\n\t\t\t}\n\t\t}\n\n\t\tcheckTransparentFieldRedefinition(fs, defn, allFields);\n\n\n\t\tdefn->fields = fields;\n\t\tdefn->transparentFields = tfields;\n\n\n\n\n\t\tunionTy->setBody(types);\n\n\t\tfs->popSelfContext();\n\t\tret = defn;\n\t}\n\telse\n\t{\n\t\tauto defn = dcast(sst::UnionDefn, tcr.defn());\n\t\ticeAssert(defn);\n\n\t\tfs->teleportInto(defn->innerScope);\n\n\t\tutil::hash_map<std::string, std::pair<size_t, fir::Type*>> vars;\n\t\tstd::vector<std::pair<sst::UnionVariantDefn*, size_t>> vdefs;\n\n\t\ticeAssert(this->transparentFields.empty());\n\n\t\tfor(auto variant : this->cases)\n\t\t{\n\t\t\tvars[variant.first] = { std::get<0>(variant.second), (std::get<2>(variant.second)\n\t\t\t\t? fs->convertParserTypeToFIR(std::get<2>(variant.second)) : fir::Type::getVoid())\n\t\t\t};\n\n\n\t\t\tauto vdef = util::pool<sst::UnionVariantDefn>(std::get<1>(variant.second));\n\t\t\tvdef->parentUnion = defn;\n\t\t\tvdef->variantName = variant.first;\n\t\t\tvdef->id = Identifier(defn->id.name + \"::\" + variant.first, IdKind::Name);\n\t\t\tvdef->id.scope = fs->scope();\n\n\t\t\tvdefs.push_back({ vdef, std::get<0>(variant.second) });\n\n\t\t\tfs->stree->addDefinition(variant.first, vdef);\n\n\t\t\tdefn->variants[variant.first] = vdef;\n\t\t}\n\n\t\tauto unionTy = defn->type->toUnionType();\n\t\tunionTy->setBody(vars);\n\n\t\t\/\/ in a bit of stupidity, we need to set the type of each definition properly.\n\t\tfor(const auto& [ uvd, id ] : vdefs)\n\t\t\tuvd->type = unionTy->getVariant(id);\n\n\t\tret = defn;\n\t}\n\n\ticeAssert(ret);\n\tthis->finishedTypechecking.insert(ret);\n\n\tfs->teleportOut();\n\n\treturn TCResult(ret);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","avg_line_length":25.3580786026,"max_line_length":135,"alphanum_fraction":0.681935595,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1023,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/****************************************************\n*   Template for coding contests                    *\n*   Author    :    Sanjeev Sharma                   *\n*   Email     :    thedevelopersanjeev@gmail.com    *\n*****************************************************\/\n#pragma GCC optimize (\"O3\")\n#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize (\"unroll-loops\")\n#pragma GCC optimize(\"no-stack-protector,fast-math\")\n#pragma GCC target (\"sse4\")\n#pragma comment(linker, \"\/stack:200000000\")\n\n#include <bits\/stdc++.h>\n#include <ext\/pb_ds\/tree_policy.hpp>\n#include <ext\/pb_ds\/assoc_container.hpp>\n\n#define deb(x) cout << #x << \" is \" << x << \"\\n\";\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\nconst double PI = 2 * acos(0.0);\nconst long long INF = 1e18L + 5;\ntemplate <typename T>\nusing ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\n\nint main(){\n\tios_base::sync_with_stdio(false);\n\tcin.tie(NULL);\n\tint n, k;\n\tcin >>n >>k;\n\tcout <<floor(log2(n) \/ log2(k)) + 1;\n\treturn 0;\n}\n","avg_line_length":29.2285714286,"max_line_length":96,"alphanum_fraction":0.5826001955,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2936,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":null,"content":"#include \"imagewidget.h\"\n#include \"ui_imagewidget.h\"\n\n#include <opencv2\/opencv.hpp>\n#include <iostream>\n\nImageWidget::ImageWidget(QWidget *parent) :\n\tQDockWidget(parent), ui(new Ui::ImageWidget)\n{\n    ui->setupUi(this);\n\t_imageUnit = NULL;\n}\n\nImageWidget::~ImageWidget()\n{\n\tif(_imageUnit != NULL)\n\t\tdelete[] _imageUnit;\n\tdelete ui;\n}\n\nvoid ImageWidget::init(int count)\n{\n    _imageUnit = new ImageUnit[count];\n    for(int i = 0; i < count; i++)\n    {\n        ui->imageLayout->addWidget(&_imageUnit[i], i, 0, 1, 1);\n        connect(this, SIGNAL(sendDraw(uchar*,int,int,QWidget*)),    &_imageUnit[i], SLOT(recvDraw(uchar*,int,int,QWidget*)));\n        connect(this, SIGNAL(sendTitle(QString,QWidget*)),          &_imageUnit[i], SLOT(recvTitle(QString,QWidget*)));\n    }\n\t_unitCount = count;\n    _beforePath.resize(count);\n}\n\nvoid ImageWidget::setImage(int id, int type, QString path)\n{\n    if(path.isEmpty() == true)\n    {\n        _imageUnit[id].setDraw(0, 0, 0);\n    }\n    if(_beforePath[id] == path)\n        return;\n\n    cv::Mat originalImage;\n    originalImage = cv::imread(path.toStdString().c_str());\n\n    if (originalImage.data)\n    {\n        cv::cvtColor(originalImage, originalImage, cv::COLOR_BGR2RGB);\n\n        switch (type)\n        {\n        case 1: {\n            \/\/Rotate 90 degree\n            cv::Point2f pc(originalImage.cols\/2., originalImage.rows\/2.);\n            cv::Mat r = cv::getRotationMatrix2D(pc, 90, 1.0);\n            cv::warpAffine(originalImage, originalImage, r, originalImage.size());\n\n            cv::resize(originalImage, originalImage, cv::Size( originalImage.cols, originalImage.rows ), 0, 0, CV_INTER_NN );\n            break;\n        }\n        case 2:\n            cv::resize(originalImage, originalImage, cv::Size( originalImage.cols\/4, originalImage.rows\/4 ), 0, 0, CV_INTER_NN );\n            break;\n\n        default:\n            cv::resize(originalImage, originalImage, cv::Size( originalImage.cols, originalImage.rows ), 0, 0, CV_INTER_NN );\n            break;\n        }\n\n        \/\/_imageUnit[id].setDraw(originalImage.data, originalImage.cols, originalImage.rows);\n\n        emit sendDraw(originalImage.data, originalImage.cols, originalImage.rows, &_imageUnit[id]);\n        _beforePath[id] = path;\n    }\n    \/\/if(path.isEmpty()==false)\n\t\/\/        _imageUnit[id].setImage(path);\n}\n\nvoid ImageWidget::setTitle(int id, QString path)\n{\n    if(_unitCount > id)\n    {\n        \/\/_imageUnit[id].setTitle(path);\n        emit sendTitle(path, &_imageUnit[id]);\n    }\n\telse\n\t\tstd::cout << \"[error] id matching error\" << std::endl;\n}\n\nvoid ImageWidget::update()\n{\n}\n\nvoid ImageWidget::recvCamState(bool state)\n{\n}\n\nvoid ImageWidget::recvWriteAutoShoot(bool checked)\n{\n}\n\nvoid ImageWidget::recvWriteAutoConfig(bool checked)\n{\n}\n\nvoid ImageWidget::recvWriteShoot()\n{\n}\n\nvoid ImageWidget::recvWriteStore(bool checked)\n{\n}\n\nvoid ImageWidget::recvWriteConfigNum(int pNum)\n{\n}\n\nvoid ImageWidget::recvWriteShutdown()\n{\n}\n\n","avg_line_length":24.0655737705,"max_line_length":129,"alphanum_fraction":0.6376021798,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4259,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*===================== begin_copyright_notice ==================================\n\nCopyright (c) 2017 Intel Corporation\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and\/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n======================= end_copyright_notice ==================================*\/\n\n#include \"AdaptorCommon\/ImplicitArgs.hpp\"\n#include \"Compiler\/Optimizer\/OpenCLPasses\/PrivateMemory\/PrivateMemoryBufferAnalysis.hpp\"\n#include \"Compiler\/MetaDataApi\/MetaDataApi.h\"\n#include \"Compiler\/IGCPassSupport.h\"\n\nusing namespace llvm;\nusing namespace IGC;\nusing namespace IGC::IGCMD;\n\n\/\/ Register pass to igc-opt\n#define PASS_FLAG \"igc-private-mem-buffer-analysis\"\n#define PASS_DESCRIPTION \"Analizes the size and offset of private mem allocas and the total per WI size\"\n#define PASS_CFG_ONLY false\n#define PASS_ANALYSIS true\nIGC_INITIALIZE_PASS_BEGIN(PrivateMemoryBufferAnalysis, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)\n\/\/IGC_INITIALIZE_PASS_DEPENDENCY(DataLayout)\nIGC_INITIALIZE_PASS_END(PrivateMemoryBufferAnalysis, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)\n\nchar PrivateMemoryBufferAnalysis::ID = 0;\n\nPrivateMemoryBufferAnalysis::PrivateMemoryBufferAnalysis() : ModulePass(ID)\n{\n    initializePrivateMemoryBufferAnalysisPass(*PassRegistry::getPassRegistry());\n}\n\nbool PrivateMemoryBufferAnalysis::runOnModule(llvm::Module& M)\n{\n    \/\/ Get the analysis\n    m_DL = &M.getDataLayout();\n\n    \/\/ Clear data for processing new module\n    m_privateInfoMap.clear();\n\n    for (Module::iterator I = M.begin(); I != M.end(); ++I)\n    {\n        runOnFunction(*I);\n    }\n\n    return false;\n}\n\nvoid PrivateMemoryBufferAnalysis::runOnFunction(llvm::Function& F)\n{\n    if (F.isDeclaration())\n    {\n        return;\n    }\n\n    \/\/ Processing new function\n    m_currentOffset = 0;\n    m_maxAlignment = 0;\n\n    visit(F);\n\n    \/\/ Align total size for the next WI\n    m_currentOffset = iSTD::Align(m_currentOffset, m_maxAlignment);\n\n    \/\/ Map total private buffer size to current function\n    m_privateInfoMap[&F].m_bufferTotalSize = m_currentOffset;\n}\n\nvoid PrivateMemoryBufferAnalysis::visitAllocaInst(AllocaInst& AI)\n{\n    assert(AI.getType()->getAddressSpace() == ADDRESS_SPACE_PRIVATE && \"Allocaitons are expected to be in private address space\");\n\n    \/\/ If private memory has no users, no point of analysing it.\n    if (AI.use_empty()) return;\n\n    Function* pFunc = AI.getParent()->getParent();\n\n    m_privateInfoMap[pFunc].m_allocaInsts.push_back(&AI);\n\n    unsigned int alignment = AI.getAlignment();\n    if (alignment == 0) {\n        alignment = m_DL->getABITypeAlignment(AI.getAllocatedType());\n    }\n\n    \/\/ Update max alignment\n    if (alignment > m_maxAlignment)\n    {\n        m_maxAlignment = alignment;\n    }\n\n    \/\/ Determine buffer offset\n    m_currentOffset = iSTD::Align(m_currentOffset, alignment);\n    m_privateInfoMap[pFunc].m_bufferOffsets[&AI] = m_currentOffset;\n\n    \/\/ Determine buffer size\n    assert(isa<ConstantInt>(AI.getArraySize()) && \"Private memory array size is expected to be constant int!\");\n    unsigned int bufferSize = static_cast<unsigned int>(cast<ConstantInt>(AI.getArraySize())->getZExtValue() * m_DL->getTypeAllocSize(AI.getAllocatedType()));\n    m_privateInfoMap[pFunc].m_bufferSizes[&AI] = bufferSize;\n\n    \/\/ Advance offset\n    m_currentOffset += bufferSize;\n}\n","avg_line_length":34.9098360656,"max_line_length":158,"alphanum_fraction":0.7349142991,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5154,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2017-2019, The Motif Project\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification, are\n\/\/ permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice, this list of\n\/\/    conditions and the following disclaimer.\n\/\/\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice, this list\n\/\/    of conditions and the following disclaimer in the documentation and\/or other\n\/\/    materials provided with the distribution.\n\/\/\n\/\/ 3. Neither the name of the copyright holder nor the names of its contributors may be\n\/\/    used to endorse or promote products derived from this software without specific\n\/\/    prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n\/\/ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n\/\/ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n\/\/ THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n\/\/ STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n\/\/ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include \"messages_map.hpp\"\n#include \"messages\/messages.pb.h\"\n#include \"messages\/messages-common.pb.h\"\n#include \"messages\/messages-management.pb.h\"\n#include \"messages\/messages-motif.pb.h\"\n\n#ifdef WITH_TREZOR_DEBUGGING\n#include \"messages\/messages-debug.pb.h\"\n#endif\n\nusing namespace std;\nusing namespace hw::trezor;\n\nnamespace hw{\nnamespace trezor\n{\n\n  const char * TYPE_PREFIX = \"MessageType_\";\n  const char * PACKAGES[] = {\n      \"hw.trezor.messages.\",\n      \"hw.trezor.messages.common.\",\n      \"hw.trezor.messages.management.\",\n#ifdef WITH_TREZOR_DEBUGGING\n      \"hw.trezor.messages.debug.\",\n#endif\n      \"hw.trezor.messages.motif.\"\n  };\n\n  google::protobuf::Message * MessageMapper::get_message(int wire_number) {\n    return MessageMapper::get_message(static_cast<messages::MessageType>(wire_number));\n  }\n\n  google::protobuf::Message * MessageMapper::get_message(messages::MessageType wire_number) {\n    const string &messageTypeName = hw::trezor::messages::MessageType_Name(wire_number);\n    if (messageTypeName.empty()) {\n      throw exc::EncodingException(std::string(\"Message descriptor not found: \") + std::to_string(wire_number));\n    }\n\n    string messageName = messageTypeName.substr(strlen(TYPE_PREFIX));\n    return MessageMapper::get_message(messageName);\n  }\n\n  google::protobuf::Message * MessageMapper::get_message(const std::string & msg_name) {\n    \/\/ Each package instantiation so lookup works\n    hw::trezor::messages::common::Success::default_instance();\n    hw::trezor::messages::management::Cancel::default_instance();\n    hw::trezor::messages::motif::MotifGetAddress::default_instance();\n\n#ifdef WITH_TREZOR_DEBUGGING\n    hw::trezor::messages::debug::DebugLinkDecision::default_instance();\n#endif\n\n    google::protobuf::Descriptor const * desc = nullptr;\n    for(const string &text : PACKAGES){\n      desc = google::protobuf::DescriptorPool::generated_pool()\n          ->FindMessageTypeByName(text + msg_name);\n      if (desc != nullptr){\n        break;\n      }\n    }\n\n    if (desc == nullptr){\n      throw exc::EncodingException(std::string(\"Message not found: \") + msg_name);\n    }\n\n    google::protobuf::Message* message =\n        google::protobuf::MessageFactory::generated_factory()\n            ->GetPrototype(desc)->New();\n\n    return message;\n\n\/\/    \/\/ CODEGEN way, fast\n\/\/    switch(wire_number){\n\/\/      case 501:\n\/\/        return new messages::motif::MotifTransactionSignRequest();\n\/\/      default:\n\/\/        throw std::runtime_error(\"not implemented\");\n\/\/    }\n\/\/\n\/\/    \/\/ CODEGEN message -> number: specification\n\/\/    \/\/    messages::MessageType get_message_wire_number(const messages::motif::MotifTransactionSignRequest * msg) { return 501; }\n\/\/    \/\/    messages::MessageType get_message_wire_number(const messages::management::ping * msg)\n\/\/\n  }\n\n  messages::MessageType MessageMapper::get_message_wire_number(const google::protobuf::Message * msg){\n    return MessageMapper::get_message_wire_number(msg->GetDescriptor()->name());\n  }\n\n  messages::MessageType MessageMapper::get_message_wire_number(const google::protobuf::Message & msg){\n    return MessageMapper::get_message_wire_number(msg.GetDescriptor()->name());\n  }\n\n  messages::MessageType MessageMapper::get_message_wire_number(const std::string & msg_name){\n    string enumMessageName = std::string(TYPE_PREFIX) + msg_name;\n\n    messages::MessageType res;\n    bool r = hw::trezor::messages::MessageType_Parse(enumMessageName, &res);\n    if (!r){\n      throw exc::EncodingException(std::string(\"Message \") + msg_name + \" not found\");\n    }\n\n    return res;\n  }\n\n}\n}\n","avg_line_length":37.6204379562,"max_line_length":131,"alphanum_fraction":0.7225455957,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2240,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/*\r\n** $Id: TP_Logging_Server.cpp 80826 2008-03-04 14:51:23Z wotte $\r\n**\r\n** Copyright 2002 Addison Wesley. All Rights Reserved.\r\n*\/\r\n\r\n#include \"ace\/OS_Memory.h\"\r\n#include \"ace\/Guard_T.h\"\r\n#include \"ace\/Message_Block.h\"\r\n#include \"TP_Logging_Server.h\"\r\n\r\nint TP_Logging_Handler::handle_input (ACE_HANDLE) {\r\n  ACE_Message_Block *mblk = 0;\r\n  if (logging_handler_.recv_log_record (mblk) != -1) {\r\n    ACE_Message_Block *log_blk = 0;\r\n    ACE_NEW_RETURN\r\n      (log_blk, ACE_Message_Block\r\n                  (reinterpret_cast<char *> (this)), -1);\r\n    log_blk->cont (mblk);\r\n    ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, guard, lock_, -1);\r\n    if (TP_LOGGING_TASK::instance ()->put (log_blk) == -1)\r\n    { log_blk->release (); return -1; }\r\n    ++queued_count_;\r\n    return 0;\r\n  } else return -1;\r\n}\r\n\r\n\r\nint\r\nTP_Logging_Handler::handle_close (ACE_HANDLE handle,\r\n                                  ACE_Reactor_Mask) {\r\n  int close_now = 0;\r\n  if (handle != ACE_INVALID_HANDLE) {\r\n    ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, guard, lock_, -1);\r\n    if (queued_count_ == 0)\r\n      close_now = 1;\r\n    else\r\n      deferred_close_ = 1;\r\n  } else {\r\n    ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, guard, lock_, -1);\r\n    queued_count_--;\r\n    if (queued_count_ == 0) close_now = deferred_close_;\r\n  }\r\n\r\n  if (close_now)\r\n    return Logging_Event_Handler::handle_close ();\r\n  return 0;\r\n}\r\n\r\n\r\nint TP_Logging_Task::svc () {\r\n  for (ACE_Message_Block *log_blk; getq (log_blk) != -1; ) {\r\n    TP_Logging_Handler *tp_handler = reinterpret_cast<TP_Logging_Handler *> (log_blk->rd_ptr ());\r\n    Logging_Handler logging_handler (tp_handler->log_file ());\r\n    logging_handler.write_log_record (log_blk->cont ());\r\n\r\n    log_blk->release ();\r\n    tp_handler->handle_close (ACE_INVALID_HANDLE, 0);\r\n  }\r\n  return 0;\r\n}\r\n\r\nACE_FACTORY_DEFINE (TPLS, TP_Logging_Server)\r\n\r\n#if defined (ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION)\r\ntemplate ACE_Singleton<TP_Logging_Task, ACE_Null_Mutex> *\r\n  ACE_Singleton<TP_Logging_Task, ACE_Null_Mutex>::singleton_;\r\ntemplate ACE_Unmanaged_Singleton<TP_Logging_Task, ACE_Null_Mutex> *\r\n  ACE_Unmanaged_Singleton<TP_Logging_Task, ACE_Null_Mutex>::singleton_;\r\n#endif \/* ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION *\/\r\n","avg_line_length":31.5492957746,"max_line_length":98,"alphanum_fraction":0.6834821429,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1649,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":1.0,"content":"#include \"hive_gui.h\"\r\n#include \"login_ui.h\"\r\nstruct lua_State * hive_state; \/\/main lua_state for start hive cell\r\nint send_to_hive(char * name,char * data,int data_len){\r\n\treturn send_to_cell(hive_state,name,data,data_len);\r\n}\r\nint registerto_hive(char * name,int size,HWND handle){\r\n\treturn regist_handle(hive_state,name,size,handle);\r\n}\r\nstatic void *\r\nstart_hive(void *p)\r\n{   assert(!hive_state);\r\n\thive_state = luaL_newstate();\r\n\tluaL_openlibs(hive_state);\r\n\tluaopen_base(hive_state);\r\n\t\/\/hive gui api to lua \r\n\tlua_pushcfunction(hive_state, hive_gui_lib);\r\n\tlua_rawsetp(hive_state, LUA_REGISTRYINDEX, \"hive_gui_lib\");\r\n\tchar * file = (char *)p;\r\n\tint err = luaL_dofile(hive_state, file);\r\n\t\r\n\tif (err) {\r\n\t\tconst char * err_str =lua_tostring(hive_state,-1);\r\n\t\tlua_close(hive_state);\r\n\t\texit(999);\r\n\t\treturn NULL;\r\n\t} \r\n\treturn NULL;\r\n\r\n}\r\nint APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE \/*hPrevInstance*\/, LPSTR \/*lpCmdLine*\/, int nCmdShow)\r\n{\r\n\tCPaintManagerUI::SetInstance(hInstance);\r\n    CPaintManagerUI::SetResourcePath(CPaintManagerUI::GetInstancePath()+_T(\"skin\"));\r\n    CStdString path = CPaintManagerUI::GetInstancePath()+_T(\"main.lua\");\r\n\tLPCTSTR s =path.GetData();\r\n\t\r\n\tHANDLE pid =CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)start_hive,(LPVOID)s, 0, NULL);\r\n\r\n    HRESULT Hr = ::CoInitialize(NULL);\r\n    if( FAILED(Hr) ) return 0;\r\n\r\n\r\n    LoginUI* ui = new LoginUI();\r\n    if( ui == NULL ) return 0;\r\n    ui->Create(NULL, _T(\"login................\"), UI_WNDSTYLE_FRAME, WS_EX_WINDOWEDGE);\r\n    ui->CenterWindow();\r\n    ui->ShowWindow(true);\r\n\r\n    CPaintManagerUI::MessageLoop();\r\n\r\n    ::CoUninitialize();\r\n\t return 0;\r\n}","avg_line_length":30.537037037,"max_line_length":106,"alphanum_fraction":0.6889023651,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":14113,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":43.0,"content":"\/*\n * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <tencentcloud\/cmq\/v20190304\/model\/Subscription.h>\n\nusing TencentCloud::CoreInternalOutcome;\nusing namespace TencentCloud::Cmq::V20190304::Model;\nusing namespace std;\n\nSubscription::Subscription() :\n    m_subscriptionNameHasBeenSet(false),\n    m_subscriptionIdHasBeenSet(false),\n    m_topicOwnerHasBeenSet(false),\n    m_msgCountHasBeenSet(false),\n    m_lastModifyTimeHasBeenSet(false),\n    m_createTimeHasBeenSet(false),\n    m_bindingKeyHasBeenSet(false),\n    m_endpointHasBeenSet(false),\n    m_filterTagsHasBeenSet(false),\n    m_protocolHasBeenSet(false),\n    m_notifyStrategyHasBeenSet(false),\n    m_notifyContentFormatHasBeenSet(false)\n{\n}\n\nCoreInternalOutcome Subscription::Deserialize(const rapidjson::Value &value)\n{\n    string requestId = \"\";\n\n\n    if (value.HasMember(\"SubscriptionName\") && !value[\"SubscriptionName\"].IsNull())\n    {\n        if (!value[\"SubscriptionName\"].IsString())\n        {\n            return CoreInternalOutcome(Core::Error(\"response `Subscription.SubscriptionName` IsString=false incorrectly\").SetRequestId(requestId));\n        }\n        m_subscriptionName = string(value[\"SubscriptionName\"].GetString());\n        m_subscriptionNameHasBeenSet = true;\n    }\n\n    if (value.HasMember(\"SubscriptionId\") && !value[\"SubscriptionId\"].IsNull())\n    {\n        if (!value[\"SubscriptionId\"].IsString())\n        {\n            return CoreInternalOutcome(Core::Error(\"response `Subscription.SubscriptionId` IsString=false incorrectly\").SetRequestId(requestId));\n        }\n        m_subscriptionId = string(value[\"SubscriptionId\"].GetString());\n        m_subscriptionIdHasBeenSet = true;\n    }\n\n    if (value.HasMember(\"TopicOwner\") && !value[\"TopicOwner\"].IsNull())\n    {\n        if (!value[\"TopicOwner\"].IsUint64())\n        {\n            return CoreInternalOutcome(Core::Error(\"response `Subscription.TopicOwner` IsUint64=false incorrectly\").SetRequestId(requestId));\n        }\n        m_topicOwner = value[\"TopicOwner\"].GetUint64();\n        m_topicOwnerHasBeenSet = true;\n    }\n\n    if (value.HasMember(\"MsgCount\") && !value[\"MsgCount\"].IsNull())\n    {\n        if (!value[\"MsgCount\"].IsUint64())\n        {\n            return CoreInternalOutcome(Core::Error(\"response `Subscription.MsgCount` IsUint64=false incorrectly\").SetRequestId(requestId));\n        }\n        m_msgCount = value[\"MsgCount\"].GetUint64();\n        m_msgCountHasBeenSet = true;\n    }\n\n    if (value.HasMember(\"LastModifyTime\") && !value[\"LastModifyTime\"].IsNull())\n    {\n        if (!value[\"LastModifyTime\"].IsUint64())\n        {\n            return CoreInternalOutcome(Core::Error(\"response `Subscription.LastModifyTime` IsUint64=false incorrectly\").SetRequestId(requestId));\n        }\n        m_lastModifyTime = value[\"LastModifyTime\"].GetUint64();\n        m_lastModifyTimeHasBeenSet = true;\n    }\n\n    if (value.HasMember(\"CreateTime\") && !value[\"CreateTime\"].IsNull())\n    {\n        if (!value[\"CreateTime\"].IsUint64())\n        {\n            return CoreInternalOutcome(Core::Error(\"response `Subscription.CreateTime` IsUint64=false incorrectly\").SetRequestId(requestId));\n        }\n        m_createTime = value[\"CreateTime\"].GetUint64();\n        m_createTimeHasBeenSet = true;\n    }\n\n    if (value.HasMember(\"BindingKey\") && !value[\"BindingKey\"].IsNull())\n    {\n        if (!value[\"BindingKey\"].IsArray())\n            return CoreInternalOutcome(Core::Error(\"response `Subscription.BindingKey` is not array type\"));\n\n        const rapidjson::Value &tmpValue = value[\"BindingKey\"];\n        for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)\n        {\n            m_bindingKey.push_back((*itr).GetString());\n        }\n        m_bindingKeyHasBeenSet = true;\n    }\n\n    if (value.HasMember(\"Endpoint\") && !value[\"Endpoint\"].IsNull())\n    {\n        if (!value[\"Endpoint\"].IsString())\n        {\n            return CoreInternalOutcome(Core::Error(\"response `Subscription.Endpoint` IsString=false incorrectly\").SetRequestId(requestId));\n        }\n        m_endpoint = string(value[\"Endpoint\"].GetString());\n        m_endpointHasBeenSet = true;\n    }\n\n    if (value.HasMember(\"FilterTags\") && !value[\"FilterTags\"].IsNull())\n    {\n        if (!value[\"FilterTags\"].IsArray())\n            return CoreInternalOutcome(Core::Error(\"response `Subscription.FilterTags` is not array type\"));\n\n        const rapidjson::Value &tmpValue = value[\"FilterTags\"];\n        for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)\n        {\n            m_filterTags.push_back((*itr).GetString());\n        }\n        m_filterTagsHasBeenSet = true;\n    }\n\n    if (value.HasMember(\"Protocol\") && !value[\"Protocol\"].IsNull())\n    {\n        if (!value[\"Protocol\"].IsString())\n        {\n            return CoreInternalOutcome(Core::Error(\"response `Subscription.Protocol` IsString=false incorrectly\").SetRequestId(requestId));\n        }\n        m_protocol = string(value[\"Protocol\"].GetString());\n        m_protocolHasBeenSet = true;\n    }\n\n    if (value.HasMember(\"NotifyStrategy\") && !value[\"NotifyStrategy\"].IsNull())\n    {\n        if (!value[\"NotifyStrategy\"].IsString())\n        {\n            return CoreInternalOutcome(Core::Error(\"response `Subscription.NotifyStrategy` IsString=false incorrectly\").SetRequestId(requestId));\n        }\n        m_notifyStrategy = string(value[\"NotifyStrategy\"].GetString());\n        m_notifyStrategyHasBeenSet = true;\n    }\n\n    if (value.HasMember(\"NotifyContentFormat\") && !value[\"NotifyContentFormat\"].IsNull())\n    {\n        if (!value[\"NotifyContentFormat\"].IsString())\n        {\n            return CoreInternalOutcome(Core::Error(\"response `Subscription.NotifyContentFormat` IsString=false incorrectly\").SetRequestId(requestId));\n        }\n        m_notifyContentFormat = string(value[\"NotifyContentFormat\"].GetString());\n        m_notifyContentFormatHasBeenSet = true;\n    }\n\n\n    return CoreInternalOutcome(true);\n}\n\nvoid Subscription::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const\n{\n\n    if (m_subscriptionNameHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"SubscriptionName\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, rapidjson::Value(m_subscriptionName.c_str(), allocator).Move(), allocator);\n    }\n\n    if (m_subscriptionIdHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"SubscriptionId\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, rapidjson::Value(m_subscriptionId.c_str(), allocator).Move(), allocator);\n    }\n\n    if (m_topicOwnerHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"TopicOwner\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, m_topicOwner, allocator);\n    }\n\n    if (m_msgCountHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"MsgCount\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, m_msgCount, allocator);\n    }\n\n    if (m_lastModifyTimeHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"LastModifyTime\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, m_lastModifyTime, allocator);\n    }\n\n    if (m_createTimeHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"CreateTime\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, m_createTime, allocator);\n    }\n\n    if (m_bindingKeyHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"BindingKey\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);\n\n        for (auto itr = m_bindingKey.begin(); itr != m_bindingKey.end(); ++itr)\n        {\n            value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);\n        }\n    }\n\n    if (m_endpointHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"Endpoint\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, rapidjson::Value(m_endpoint.c_str(), allocator).Move(), allocator);\n    }\n\n    if (m_filterTagsHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"FilterTags\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);\n\n        for (auto itr = m_filterTags.begin(); itr != m_filterTags.end(); ++itr)\n        {\n            value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);\n        }\n    }\n\n    if (m_protocolHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"Protocol\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, rapidjson::Value(m_protocol.c_str(), allocator).Move(), allocator);\n    }\n\n    if (m_notifyStrategyHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"NotifyStrategy\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, rapidjson::Value(m_notifyStrategy.c_str(), allocator).Move(), allocator);\n    }\n\n    if (m_notifyContentFormatHasBeenSet)\n    {\n        rapidjson::Value iKey(rapidjson::kStringType);\n        string key = \"NotifyContentFormat\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, rapidjson::Value(m_notifyContentFormat.c_str(), allocator).Move(), allocator);\n    }\n\n}\n\n\nstring Subscription::GetSubscriptionName() const\n{\n    return m_subscriptionName;\n}\n\nvoid Subscription::SetSubscriptionName(const string& _subscriptionName)\n{\n    m_subscriptionName = _subscriptionName;\n    m_subscriptionNameHasBeenSet = true;\n}\n\nbool Subscription::SubscriptionNameHasBeenSet() const\n{\n    return m_subscriptionNameHasBeenSet;\n}\n\nstring Subscription::GetSubscriptionId() const\n{\n    return m_subscriptionId;\n}\n\nvoid Subscription::SetSubscriptionId(const string& _subscriptionId)\n{\n    m_subscriptionId = _subscriptionId;\n    m_subscriptionIdHasBeenSet = true;\n}\n\nbool Subscription::SubscriptionIdHasBeenSet() const\n{\n    return m_subscriptionIdHasBeenSet;\n}\n\nuint64_t Subscription::GetTopicOwner() const\n{\n    return m_topicOwner;\n}\n\nvoid Subscription::SetTopicOwner(const uint64_t& _topicOwner)\n{\n    m_topicOwner = _topicOwner;\n    m_topicOwnerHasBeenSet = true;\n}\n\nbool Subscription::TopicOwnerHasBeenSet() const\n{\n    return m_topicOwnerHasBeenSet;\n}\n\nuint64_t Subscription::GetMsgCount() const\n{\n    return m_msgCount;\n}\n\nvoid Subscription::SetMsgCount(const uint64_t& _msgCount)\n{\n    m_msgCount = _msgCount;\n    m_msgCountHasBeenSet = true;\n}\n\nbool Subscription::MsgCountHasBeenSet() const\n{\n    return m_msgCountHasBeenSet;\n}\n\nuint64_t Subscription::GetLastModifyTime() const\n{\n    return m_lastModifyTime;\n}\n\nvoid Subscription::SetLastModifyTime(const uint64_t& _lastModifyTime)\n{\n    m_lastModifyTime = _lastModifyTime;\n    m_lastModifyTimeHasBeenSet = true;\n}\n\nbool Subscription::LastModifyTimeHasBeenSet() const\n{\n    return m_lastModifyTimeHasBeenSet;\n}\n\nuint64_t Subscription::GetCreateTime() const\n{\n    return m_createTime;\n}\n\nvoid Subscription::SetCreateTime(const uint64_t& _createTime)\n{\n    m_createTime = _createTime;\n    m_createTimeHasBeenSet = true;\n}\n\nbool Subscription::CreateTimeHasBeenSet() const\n{\n    return m_createTimeHasBeenSet;\n}\n\nvector<string> Subscription::GetBindingKey() const\n{\n    return m_bindingKey;\n}\n\nvoid Subscription::SetBindingKey(const vector<string>& _bindingKey)\n{\n    m_bindingKey = _bindingKey;\n    m_bindingKeyHasBeenSet = true;\n}\n\nbool Subscription::BindingKeyHasBeenSet() const\n{\n    return m_bindingKeyHasBeenSet;\n}\n\nstring Subscription::GetEndpoint() const\n{\n    return m_endpoint;\n}\n\nvoid Subscription::SetEndpoint(const string& _endpoint)\n{\n    m_endpoint = _endpoint;\n    m_endpointHasBeenSet = true;\n}\n\nbool Subscription::EndpointHasBeenSet() const\n{\n    return m_endpointHasBeenSet;\n}\n\nvector<string> Subscription::GetFilterTags() const\n{\n    return m_filterTags;\n}\n\nvoid Subscription::SetFilterTags(const vector<string>& _filterTags)\n{\n    m_filterTags = _filterTags;\n    m_filterTagsHasBeenSet = true;\n}\n\nbool Subscription::FilterTagsHasBeenSet() const\n{\n    return m_filterTagsHasBeenSet;\n}\n\nstring Subscription::GetProtocol() const\n{\n    return m_protocol;\n}\n\nvoid Subscription::SetProtocol(const string& _protocol)\n{\n    m_protocol = _protocol;\n    m_protocolHasBeenSet = true;\n}\n\nbool Subscription::ProtocolHasBeenSet() const\n{\n    return m_protocolHasBeenSet;\n}\n\nstring Subscription::GetNotifyStrategy() const\n{\n    return m_notifyStrategy;\n}\n\nvoid Subscription::SetNotifyStrategy(const string& _notifyStrategy)\n{\n    m_notifyStrategy = _notifyStrategy;\n    m_notifyStrategyHasBeenSet = true;\n}\n\nbool Subscription::NotifyStrategyHasBeenSet() const\n{\n    return m_notifyStrategyHasBeenSet;\n}\n\nstring Subscription::GetNotifyContentFormat() const\n{\n    return m_notifyContentFormat;\n}\n\nvoid Subscription::SetNotifyContentFormat(const string& _notifyContentFormat)\n{\n    m_notifyContentFormat = _notifyContentFormat;\n    m_notifyContentFormatHasBeenSet = true;\n}\n\nbool Subscription::NotifyContentFormatHasBeenSet() const\n{\n    return m_notifyContentFormatHasBeenSet;\n}\n\n","avg_line_length":29.5251046025,"max_line_length":150,"alphanum_fraction":0.6865301495,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3315,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*******************************************************************\nCopyright(c) 2016, Harry He\nAll rights reserved.\n\nDistributed under the BSD license.\n(See accompanying file LICENSE.txt at\nhttps:\/\/github.com\/zhedahht\/CodingInterviewChinese2\/blob\/master\/LICENSE.txt)\n*******************************************************************\/\n\n\/\/==================================================================\n\/\/ \u300a\u5251\u6307Offer\u2014\u2014\u540d\u4f01\u9762\u8bd5\u5b98\u7cbe\u8bb2\u5178\u578b\u7f16\u7a0b\u9898\u300b\u4ee3\u7801\n\/\/ \u4f5c\u8005\uff1a\u4f55\u6d77\u6d9b\n\/\/==================================================================\n\n\/\/ \u9762\u8bd5\u989845\uff1a\u628a\u6570\u7ec4\u6392\u6210\u6700\u5c0f\u7684\u6570\n\/\/ \u9898\u76ee\uff1a\u8f93\u5165\u4e00\u4e2a\u6b63\u6574\u6570\u6570\u7ec4\uff0c\u628a\u6570\u7ec4\u91cc\u6240\u6709\u6570\u5b57\u62fc\u63a5\u8d77\u6765\u6392\u6210\u4e00\u4e2a\u6570\uff0c\u6253\u5370\u80fd\u62fc\n\/\/ \u63a5\u51fa\u7684\u6240\u6709\u6570\u5b57\u4e2d\u6700\u5c0f\u7684\u4e00\u4e2a\u3002\u4f8b\u5982\u8f93\u5165\u6570\u7ec4{3, 32, 321}\uff0c\u5219\u6253\u5370\u51fa\u8fd93\u4e2a\u6570\n\/\/ \u5b57\u80fd\u6392\u6210\u7684\u6700\u5c0f\u6570\u5b57321323\u3002\n\n#include \"cstdio\"\n#include <string>\n#include <algorithm>\n\nint compare(const void* strNumber1, const void* strNumber2);\n\n\/\/ int\u578b\u6574\u6570\u7528\u5341\u8fdb\u5236\u8868\u793a\u6700\u591a\u53ea\u670910\u4f4d\nconst int g_MaxNumberLength = 10;\n \nchar* g_StrCombine1 = new char[g_MaxNumberLength * 2 + 1];\nchar* g_StrCombine2 = new char[g_MaxNumberLength * 2 + 1];\n \nvoid PrintMinNumber(const int* numbers, int length)\n{\n    if(numbers == nullptr || length <= 0)\n        return;\n \n    char** strNumbers = (char**)(new char*[length]);\n    for(int i = 0; i < length; ++i)\n    {\n        strNumbers[i] = new char[g_MaxNumberLength + 1];\n        sprintf(strNumbers[i], \"%d\", numbers[i]);\n    }\n \n    qsort(strNumbers, length, sizeof(char*), compare);\n \n    for(int i = 0; i < length; ++i)\n        printf(\"%s\", strNumbers[i]);\n    printf(\"\\n\");\n \n    for(int i = 0; i < length; ++i)\n        delete[] strNumbers[i];\n    delete[] strNumbers;\n}\n \n\/\/ \u5982\u679c[strNumber1][strNumber2] > [strNumber2][strNumber1], \u8fd4\u56de\u503c\u5927\u4e8e0\n\/\/ \u5982\u679c[strNumber1][strNumber2] = [strNumber2][strNumber1], \u8fd4\u56de\u503c\u7b49\u4e8e0\n\/\/ \u5982\u679c[strNumber1][strNumber2] < [strNumber2][strNumber1], \u8fd4\u56de\u503c\u5c0f\u4e8e0\nint compare(const void* strNumber1, const void* strNumber2)\n{\n    \/\/ [strNumber1][strNumber2]\n    strcpy(g_StrCombine1, *(const char**)strNumber1);\n    strcat(g_StrCombine1, *(const char**)strNumber2);\n \n    \/\/ [strNumber2][strNumber1]\n    strcpy(g_StrCombine2, *(const char**)strNumber2);\n    strcat(g_StrCombine2, *(const char**)strNumber1);\n \n    return strcmp(g_StrCombine1, g_StrCombine2);\n}\n\n\/\/ ====================\u6d4b\u8bd5\u4ee3\u7801====================\nvoid Test(const char* testName, int* numbers, int length, const char* expectedResult)\n{\n    if(testName != nullptr)\n        printf(\"%s begins:\\n\", testName);\n\n    if(expectedResult != nullptr)\n        printf(\"Expected result is: \\t%s\\n\", expectedResult);\n\n    printf(\"Actual result is: \\t\");\n    PrintMinNumber(numbers, length);\n\n    printf(\"\\n\");\n}\n\nvoid Test1()\n{\n    int numbers[] = {3, 5, 1, 4, 2};\n    Test(\"Test1\", numbers, sizeof(numbers)\/sizeof(int), \"12345\");\n}\n\nvoid Test2()\n{\n    int numbers[] = {3, 32, 321};\n    Test(\"Test2\", numbers, sizeof(numbers)\/sizeof(int), \"321323\");\n}\n\nvoid Test3()\n{\n    int numbers[] = {3, 323, 32123};\n    Test(\"Test3\", numbers, sizeof(numbers)\/sizeof(int), \"321233233\");\n}\n\nvoid Test4()\n{\n    int numbers[] = {1, 11, 111};\n    Test(\"Test4\", numbers, sizeof(numbers)\/sizeof(int), \"111111\");\n}\n\n\/\/ \u6570\u7ec4\u4e2d\u53ea\u6709\u4e00\u4e2a\u6570\u5b57\nvoid Test5()\n{\n    int numbers[] = {321};\n    Test(\"Test5\", numbers, sizeof(numbers)\/sizeof(int), \"321\");\n}\n\nvoid Test6()\n{\n    Test(\"Test6\", nullptr, 0, \"Don't print anything.\");\n}\n\n\nint main(int argc, char* argv[])\n{\n    Test1();\n    Test2();\n    Test3();\n    Test4();\n    Test5();\n    Test6();\n\n    return 0;\n}\n\n","avg_line_length":24.5555555556,"max_line_length":85,"alphanum_fraction":0.578280543,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2183,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":5.0,"content":"\/\/ Copyright 2015, Tobias Hermann and the FunctionalPlus contributors.\n\/\/ https:\/\/github.com\/Dobiasd\/FunctionalPlus\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <fplus\/fplus.hpp>\n#include <range\/v3\/all.hpp>\n\nconst auto times_3 = [](int i){return 3 * i;};\nconst auto is_odd_int = [](int i){return i % 2 == 0;};\nconst auto as_string_length = [](int i){return std::to_string(i).size();};\n\nint main()\n{\n    const auto times_3 = [](int i){return 3 * i;};\n    const auto is_odd_int = [](int i){return i % 2 == 0;};\n    const auto as_string_length = [](int i){return std::to_string(i).size();};\n\n    typedef std::chrono::time_point<std::chrono::system_clock> Time;\n\n    for (int i = 0; i < 3; ++i)\n    {\n        \/\/ FunctionalPlus\n        Time startTimeFPlus = std::chrono::system_clock::now();\n        using namespace fplus;\n        const auto result_fplus = fwd::apply(\n            numbers(0, 15000000)\n            , fwd::transform(times_3)\n            , fwd::drop_if(is_odd_int)\n            , fwd::transform(as_string_length)\n            , fwd::sum());\n        Time endTimeFPlus = std::chrono::system_clock::now();\n        std::chrono::duration<double> elapsed_s_fplus =\n            endTimeFPlus - startTimeFPlus;\n        std::cout << \"(check: \" << result_fplus <<\n            \"), elapsed time fplus:    \" << elapsed_s_fplus.count() << \"s\\n\";\n\n        \/\/ range-v3\n        Time startTimeRangev3 = std::chrono::system_clock::now();\n        using namespace ranges;\n        const auto result_range_v3 =\n            accumulate(\n                view::ints(0)\n                | view::take(15000000)\n                | view::transform(times_3)\n                | view::remove_if(is_odd_int)\n                | view::transform(as_string_length)\n                , 0);\n        Time endTimeRangev3 = std::chrono::system_clock::now();\n        std::chrono::duration<double> elapsed_s_rangev3 =\n            endTimeRangev3 - startTimeRangev3;\n        std::cout << \"(check: \" << result_range_v3 <<\n            \"), elapsed time range-v3: \" << elapsed_s_rangev3.count() << \"s\\n\";\n    }\n}\n","avg_line_length":38.298245614,"max_line_length":79,"alphanum_fraction":0.5895556574,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":847,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\n#include <cstdlib>\n#include <cmath>\n#include <complex>\nusing std::complex;\nbool almost_equal(complex<double> x, complex<double> gold, float tol) {\n  return std::abs(gold) * (1-tol) <= std::abs(x) && std::abs(x) <= std::abs(gold) * (1 + tol);\n}\n#pragma omp declare reduction(+: complex<double>: omp_out += omp_in)\nvoid test_target_simd() {\n  const int N0 { 32768 };\n  const complex<double> expected_value { N0 };\n  complex<double> counter_N0{};\n  #pragma omp target simd map(tofrom: counter_N0) reduction(+: counter_N0)\n  for (int i0 = 0 ; i0 < N0 ; i0++ )\n  {\n    counter_N0 = counter_N0 + complex<double> { 1. };\n  }\n  if (!almost_equal(counter_N0, expected_value, 0.1)) {\n    std::cerr << \"Expected: \" << expected_value << \" Got: \" << counter_N0 << std::endl;\n    std::exit(112);\n  }\n}\nint main()\n{\n    test_target_simd();\n}\n","avg_line_length":30.25,"max_line_length":94,"alphanum_fraction":0.6422668241,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":297,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"testlib.h\"\r\nusing namespace std;\r\n\r\nint main(int argc, char** argv) {\r\n    registerGen(argc, argv, 1);\r\n\r\n    int N = atoi(argv[1]);\r\n\r\n    int n = rnd.next(1, N);\r\n    for (int i = 0; i < n; i++) {\r\n        cout << char(rnd.next('a', 'z'));\r\n    }\r\n    cout << endl;\r\n\r\n    return 0;\r\n}","avg_line_length":18.5625,"max_line_length":42,"alphanum_fraction":0.4814814815,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2013,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":5.0,"content":"#include \"stdafx.h\"\n#include \"Filing.h\"\n\nFiling::Filing()\n{\n\tthis->Startup();\n}\n\nFiling::~Filing()\n{\n\tdelete this->ExePath;\n\tdelete this->LogDirectoryPath;\n}\n\nvoid Filing::Startup()\n{\n\tCreateDirectory(LogDirectoryPath->c_str(), NULL);\n\n\t\/\/Session log directory.\n\tCreateDirectory(this->currentInstanceLog->c_str(), NULL);\n}\n\nbool Filing::DoesDirectoryExist(string* Path)\n{\n\tDWORD ftyp = GetFileAttributesA(Path->c_str());\n\n\tif (ftyp == INVALID_FILE_ATTRIBUTES)\n\t{\n\t\tcout << \"Invalid path!\\r\\n\";\n\t\treturn false;  \/\/something is wrong with your path!\n\t}\n\n\tif (ftyp & FILE_ATTRIBUTE_DIRECTORY)\n\t{\n\t\treturn true;   \/\/ this is a directory!\n\t}\n\n\treturn false;    \/\/ this is not a directory!\n}\n\nwstring* Filing::GetPathToExe()\n{\n#ifdef UNICODE\n\tTCHAR ownPth[260];\n#else\n\tchar ownPth[MAX_Path];\n#endif \/\/ UNICODE\n\n\t\/\/ Will contain exe path\n\tHMODULE hModule = GetModuleHandle(NULL);\n\tif (hModule != NULL)\n\t{\n\t\t\/\/ When passing NULL to GetModuleHandle, it returns handle of exe itself\n\t\tGetModuleFileName(hModule, ownPth, (sizeof(ownPth)));\n\t\treturn new wstring(ownPth);\n\t}\n\telse\n\t{\n\t\tcout << \"Error! NullPointerException!\";\n\t\treturn NULL;\n\t}\n}\n\nwstring* Filing::GetLogDirectoryPath()\n{\n\twstring *directory;\n\tconst size_t last_slash_idx = ExePath->rfind('\\\\');\n\tif (string::npos != last_slash_idx)\n\t{\n\t\tdirectory = new wstring(ExePath->substr(0, last_slash_idx));\n\t\tdirectory->append(L\"\\\\Logs\");\n\t}\n\telse\n\t{\n\t\tConsole->WriteLine(\"Error! Directory not found from path!\");\n\t}\n\treturn directory;\n}\n\nwstring* Filing::getInstanceDirPath()\n{\n\twstring* dir = new wstring(*this->LogDirectoryPath);\n\tdir->append(L\"\\\\\");\n\n\ttime_t rawtime;\n\ttm* timeinfo;\n\tchar buffer[81];\n\ttime(&rawtime);\n\ttimeinfo = std::localtime(&rawtime);\n\n\tstrftime(buffer, 80, \"%Y-%m-%d-%H-%M-%S]\", timeinfo);\n\n\tint len;\n\tint slength = 82;\n\tlen = MultiByteToWideChar(CP_ACP, 0, buffer, slength, 0, 0);\n\twchar_t* buf = new wchar_t[len];\n\tMultiByteToWideChar(CP_ACP, 0, buffer, slength, buf, len);\n\twstring r(buf);\n\n\tdir->append(r);\n\n\tdelete[] buf;\n\treturn dir;\n}\n","avg_line_length":19.1714285714,"max_line_length":74,"alphanum_fraction":0.6870342772,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":30455,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/***************************************************************************\n * Copyright 1998-2020 by authors (see AUTHORS.txt)                        *\n *                                                                         *\n *   This file is part of LuxCoreRender.                                   *\n *                                                                         *\n * Licensed under the Apache License, Version 2.0 (the \"License\");         *\n * you may not use this file except in compliance with the License.        *\n * You may obtain a copy of the License at                                 *\n *                                                                         *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                          *\n *                                                                         *\n * Unless required by applicable law or agreed to in writing, software     *\n * distributed under the License is distributed on an \"AS IS\" BASIS,       *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*\n * See the License for the specific language governing permissions and     *\n * limitations under the License.                                          *\n ***************************************************************************\/\n\n#include <limits>\n#include <algorithm>\n#include <exception>\n\n#include <boost\/lexical_cast.hpp>\n#include <boost\/foreach.hpp>\n\n#include <OpenImageIO\/imageio.h>\n#include <OpenImageIO\/imagebuf.h>\n\n#include \"luxrays\/core\/geometry\/point.h\"\n#include \"luxrays\/utils\/properties.h\"\n#include \"luxrays\/utils\/safesave.h\"\n#include \"luxrays\/utils\/fileext.h\"\n#include \"slg\/editaction.h\"\n#include \"slg\/film\/film.h\"\n#include \"slg\/film\/sampleresult.h\"\n\nusing namespace std;\nusing namespace luxrays;\nusing namespace slg;\nOIIO_NAMESPACE_USING\n\ntypedef unsigned char BYTE;\n\n\/\/------------------------------------------------------------------------------\n\/\/ Film\n\/\/------------------------------------------------------------------------------\n\nsize_t Film::GetOutputSize(const FilmOutputs::FilmOutputType type) const {\n\tswitch (type) {\n\t\tcase FilmOutputs::RGB:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::RGBA:\n\t\t\treturn 4 * pixelCount;\n\t\tcase FilmOutputs::RGB_IMAGEPIPELINE:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::RGBA_IMAGEPIPELINE:\n\t\t\treturn 4 * pixelCount;\n\t\tcase FilmOutputs::ALPHA:\n\t\t\treturn pixelCount;\n\t\tcase FilmOutputs::DEPTH:\n\t\t\treturn pixelCount;\n\t\tcase FilmOutputs::POSITION:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::GEOMETRY_NORMAL:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::SHADING_NORMAL:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::MATERIAL_ID:\n\t\t\treturn pixelCount;\n\t\tcase FilmOutputs::DIRECT_DIFFUSE:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::DIRECT_GLOSSY:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::EMISSION:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::INDIRECT_DIFFUSE:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::INDIRECT_GLOSSY:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::INDIRECT_SPECULAR:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::MATERIAL_ID_MASK:\n\t\t\treturn pixelCount;\n\t\tcase FilmOutputs::DIRECT_SHADOW_MASK:\n\t\t\treturn pixelCount;\n\t\tcase FilmOutputs::INDIRECT_SHADOW_MASK:\n\t\t\treturn pixelCount;\n\t\tcase FilmOutputs::RADIANCE_GROUP:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::UV:\n\t\t\treturn 2 * pixelCount;\n\t\tcase FilmOutputs::RAYCOUNT:\n\t\t\treturn pixelCount;\n\t\tcase FilmOutputs::BY_MATERIAL_ID:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::IRRADIANCE:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::OBJECT_ID:\n\t\t\treturn pixelCount;\n\t\tcase FilmOutputs::OBJECT_ID_MASK:\n\t\t\treturn pixelCount;\n\t\tcase FilmOutputs::BY_OBJECT_ID:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::SAMPLECOUNT:\n\t\t\treturn pixelCount;\n\t\tcase FilmOutputs::CONVERGENCE:\n\t\t\treturn pixelCount;\n\t\tcase FilmOutputs::MATERIAL_ID_COLOR:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::ALBEDO:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::AVG_SHADING_NORMAL:\n\t\t\treturn 3 * pixelCount;\n\t\tcase FilmOutputs::NOISE:\n\t\t\treturn pixelCount;\n\t\tcase FilmOutputs::USER_IMPORTANCE:\n\t\t\treturn pixelCount;\n\t\tdefault:\n\t\t\tthrow runtime_error(\"Unknown FilmOutputType in Film::GetOutputSize(): \" + ToString(type));\n\t}\n}\n\nbool Film::HasOutput(const FilmOutputs::FilmOutputType type) const {\n\tswitch (type) {\n\t\tcase FilmOutputs::RGB:\n\t\t\treturn HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) || HasChannel(RADIANCE_PER_SCREEN_NORMALIZED);\n\t\tcase FilmOutputs::RGB_IMAGEPIPELINE:\n\t\t\treturn HasChannel(IMAGEPIPELINE);\n\t\tcase FilmOutputs::RGBA:\n\t\t\treturn (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) || HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) && HasChannel(ALPHA);\n\t\tcase FilmOutputs::RGBA_IMAGEPIPELINE:\n\t\t\treturn HasChannel(IMAGEPIPELINE) && HasChannel(ALPHA);\n\t\tcase FilmOutputs::ALPHA:\n\t\t\treturn HasChannel(ALPHA);\n\t\tcase FilmOutputs::DEPTH:\n\t\t\treturn HasChannel(DEPTH);\n\t\tcase FilmOutputs::POSITION:\n\t\t\treturn HasChannel(POSITION);\n\t\tcase FilmOutputs::GEOMETRY_NORMAL:\n\t\t\treturn HasChannel(GEOMETRY_NORMAL);\n\t\tcase FilmOutputs::SHADING_NORMAL:\n\t\t\treturn HasChannel(SHADING_NORMAL);\n\t\tcase FilmOutputs::MATERIAL_ID:\n\t\t\treturn HasChannel(MATERIAL_ID);\n\t\tcase FilmOutputs::DIRECT_DIFFUSE:\n\t\t\treturn HasChannel(DIRECT_DIFFUSE);\n\t\tcase FilmOutputs::DIRECT_GLOSSY:\n\t\t\treturn HasChannel(DIRECT_GLOSSY);\n\t\tcase FilmOutputs::EMISSION:\n\t\t\treturn HasChannel(EMISSION);\n\t\tcase FilmOutputs::INDIRECT_DIFFUSE:\n\t\t\treturn HasChannel(INDIRECT_DIFFUSE);\n\t\tcase FilmOutputs::INDIRECT_GLOSSY:\n\t\t\treturn HasChannel(INDIRECT_GLOSSY);\n\t\tcase FilmOutputs::INDIRECT_SPECULAR:\n\t\t\treturn HasChannel(INDIRECT_SPECULAR);\n\t\tcase FilmOutputs::MATERIAL_ID_MASK:\n\t\t\treturn HasChannel(MATERIAL_ID_MASK);\n\t\tcase FilmOutputs::DIRECT_SHADOW_MASK:\n\t\t\treturn HasChannel(DIRECT_SHADOW_MASK);\n\t\tcase FilmOutputs::INDIRECT_SHADOW_MASK:\n\t\t\treturn HasChannel(INDIRECT_SHADOW_MASK);\n\t\tcase FilmOutputs::RADIANCE_GROUP:\n\t\t\treturn true;\n\t\tcase FilmOutputs::UV:\n\t\t\treturn HasChannel(UV);\n\t\tcase FilmOutputs::RAYCOUNT:\n\t\t\treturn HasChannel(RAYCOUNT);\n\t\tcase FilmOutputs::BY_MATERIAL_ID:\n\t\t\treturn HasChannel(BY_MATERIAL_ID);\n\t\tcase FilmOutputs::IRRADIANCE:\n\t\t\treturn HasChannel(IRRADIANCE);\n\t\tcase FilmOutputs::OBJECT_ID:\n\t\t\treturn HasChannel(OBJECT_ID);\n\t\tcase FilmOutputs::OBJECT_ID_MASK:\n\t\t\treturn HasChannel(OBJECT_ID_MASK);\n\t\tcase FilmOutputs::BY_OBJECT_ID:\n\t\t\treturn HasChannel(BY_OBJECT_ID);\n\t\tcase FilmOutputs::SAMPLECOUNT:\n\t\t\treturn HasChannel(SAMPLECOUNT);\n\t\tcase FilmOutputs::CONVERGENCE:\n\t\t\treturn HasChannel(CONVERGENCE);\n\t\tcase FilmOutputs::SERIALIZED_FILM:\n\t\t\treturn filmOutputs.HasType(FilmOutputs::SERIALIZED_FILM);\n\t\tcase FilmOutputs::MATERIAL_ID_COLOR:\n\t\t\treturn HasChannel(MATERIAL_ID_COLOR);\n\t\tcase FilmOutputs::ALBEDO:\n\t\t\treturn HasChannel(ALBEDO);\n\t\tcase FilmOutputs::AVG_SHADING_NORMAL:\n\t\t\treturn HasChannel(AVG_SHADING_NORMAL);\n\t\tcase FilmOutputs::NOISE:\n\t\t\treturn HasChannel(NOISE);\n\t\tcase FilmOutputs::USER_IMPORTANCE:\n\t\t\treturn HasChannel(USER_IMPORTANCE);\n\t\tdefault:\n\t\t\tthrow runtime_error(\"Unknown film output type in Film::HasOutput(): \" + ToString(type));\n\t}\n}\n\nvoid Film::Output() {\n\tfor (u_int i = 0; i < filmOutputs.GetCount(); ++i)\n\t\tOutput(filmOutputs.GetFileName(i), filmOutputs.GetType(i),&filmOutputs.GetProperties(i));\n}\n\nvoid Film::Output(const string &fileName,const FilmOutputs::FilmOutputType type,\n\t\tconst Properties *props, const bool executeImagePipeline) { \n\t\/\/ Handle the special case of the serialized film output\n\tif (type == FilmOutputs::SERIALIZED_FILM) {\n\t\tif (!filmOutputs.HasType(FilmOutputs::SERIALIZED_FILM))\n\t\t\tthrow runtime_error(\"SERIALIZED_FILM has not been configured as output in Film::Output()\");\n\n\t\tSLG_LOG(\"Outputting film: \" << fileName << \" type: \" << ToString(type));\n\n\t\tif (filmOutputs.UseSafeSave()) {\n\t\t\tSafeSave safeSave(fileName);\n\n\t\t\tFilm::SaveSerialized(safeSave.GetSaveFileName(), this);\n\n\t\t\tsafeSave.Process();\n\t\t} else\n\t\t\tFilm::SaveSerialized(fileName, this);\n\t\t\n\t\treturn;\n\t}\n\n\tu_int maskMaterialIDsIndex = 0;\n\tu_int byMaterialIDsIndex = 0;\n\tu_int maskObjectIDsIndex = 0;\n\tu_int byObjectIDsIndex = 0;\n\tu_int radianceGroupIndex = 0;\n\tu_int imagePipelineIndex = 0;\n\tu_int channelCount = 3;\n\n\tswitch (type) {\n\t\tcase FilmOutputs::RGB:\n\t\t\tif (!HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && !HasChannel(RADIANCE_PER_SCREEN_NORMALIZED))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::RGB_IMAGEPIPELINE:\n\t\t\tif (!HasChannel(IMAGEPIPELINE))\n\t\t\t\treturn;\n\t\t\timagePipelineIndex = props ? props->Get(Property(\"index\")(0)).Get<u_int>() : 0;\n\t\t\tif (imagePipelineIndex >= imagePipelines.size())\n\t\t\t\treturn;\n\t\t\tif (executeImagePipeline)\n\t\t\t\tExecuteImagePipeline(imagePipelineIndex);\n\t\t\tbreak;\n\t\tcase FilmOutputs::RGBA:\n\t\t\tif ((!HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && !HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) || !HasChannel(ALPHA))\n\t\t\t\treturn;\n\t\t\tchannelCount = 4;\n\t\t\tbreak;\n\t\tcase FilmOutputs::RGBA_IMAGEPIPELINE:\n\t\t\tif (!HasChannel(IMAGEPIPELINE) || !HasChannel(ALPHA))\n\t\t\t\treturn;\n\t\t\timagePipelineIndex = props ? props->Get(Property(\"index\")(0)).Get<u_int>() : 0;\n\t\t\tif (imagePipelineIndex >= imagePipelines.size())\n\t\t\t\treturn;\n\t\t\tif (executeImagePipeline)\n\t\t\t\tExecuteImagePipeline(imagePipelineIndex);\n\t\t\tchannelCount = 4;\n\t\t\tbreak;\n\t\tcase FilmOutputs::ALPHA:\n\t\t\tif (!HasChannel(ALPHA))\n\t\t\t\treturn;\n\t\t\tchannelCount = 1;\n\t\t\tbreak;\n\t\tcase FilmOutputs::DEPTH:\n\t\t\tif (!HasChannel(DEPTH))\n\t\t\t\treturn;\n\t\t\tchannelCount = 1;\t\t\n\t\t\tbreak;\n\t\tcase FilmOutputs::POSITION:\n\t\t\tif (!HasChannel(POSITION))\n\t\t\t\treturn;\t\n\t\t\tbreak;\n\t\tcase FilmOutputs::GEOMETRY_NORMAL:\n\t\t\tif (!HasChannel(GEOMETRY_NORMAL))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::SHADING_NORMAL:\n\t\t\tif (!HasChannel(SHADING_NORMAL))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::MATERIAL_ID:\n\t\t\tif (!HasChannel(MATERIAL_ID))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::DIRECT_DIFFUSE:\n\t\t\tif (!HasChannel(DIRECT_DIFFUSE))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::DIRECT_GLOSSY:\n\t\t\tif (!HasChannel(DIRECT_GLOSSY))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::EMISSION:\n\t\t\tif (!HasChannel(EMISSION))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::INDIRECT_DIFFUSE:\n\t\t\tif (!HasChannel(INDIRECT_DIFFUSE))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::INDIRECT_GLOSSY:\n\t\t\tif (!HasChannel(INDIRECT_GLOSSY))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::INDIRECT_SPECULAR:\n\t\t\tif (!HasChannel(INDIRECT_SPECULAR))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::MATERIAL_ID_MASK:\n\t\t\tif (HasChannel(MATERIAL_ID_MASK) && props) {\n\t\t\t\tchannelCount = 1;\t\t\n\t\t\t\t\/\/ Look for the material mask ID index\n\t\t\t\tconst u_int id = props->Get(Property(\"id\")(255)).Get<u_int>();\n\t\t\t\tbool found = false;\n\t\t\t\tfor (u_int i = 0; i < maskMaterialIDs.size(); ++i) {\n\t\t\t\t\tif (maskMaterialIDs[i] == id) {\n\t\t\t\t\t\tmaskMaterialIDsIndex = i;\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!found)\n\t\t\t\t\treturn;\n\t\t\t} else\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::DIRECT_SHADOW_MASK:\n\t\t\tif (!HasChannel(DIRECT_SHADOW_MASK))\n\t\t\t      return;\n\t\t\tchannelCount = 1;\n\t\t\tbreak;\n\t\tcase FilmOutputs::INDIRECT_SHADOW_MASK:\n\t\t\tif (!HasChannel(INDIRECT_SHADOW_MASK))\n\t\t\t\treturn;\n\t\t\tchannelCount = 1;\n\t\t\tbreak;\n\t\tcase FilmOutputs::RADIANCE_GROUP:\n\t\t\tif (!props)\n\t\t\t\treturn;\t\t\n\t\t\tradianceGroupIndex = props->Get(Property(\"id\")(0)).Get<u_int>();\n\t\t\tif (radianceGroupIndex >= radianceGroupCount)\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::UV:\n\t\t\tif (!HasChannel(UV))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::RAYCOUNT:\n\t\t\tif (!HasChannel(RAYCOUNT))\n\t\t\t\treturn;\n\t\t\tchannelCount = 1;\n\t\t\tbreak;\n\t\tcase FilmOutputs::BY_MATERIAL_ID:\n\t\t\tif (HasChannel(BY_MATERIAL_ID) && props) {\n\t\t\t\t\/\/ Look for the material mask ID index\n\t\t\t\tconst u_int id = props->Get(Property(\"id\")(255)).Get<u_int>();\n\t\t\t\tbool found = false;\n\t\t\t\tfor (u_int i = 0; i < byMaterialIDs.size(); ++i) {\n\t\t\t\t\tif (byMaterialIDs[i] == id) {\n\t\t\t\t\t\tbyMaterialIDsIndex = i;\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!found)\n\t\t\t\t\treturn;\n\t\t\t} else\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::IRRADIANCE:\n\t\t\tif (!HasChannel(IRRADIANCE))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::OBJECT_ID:\n\t\t\tif (!HasChannel(OBJECT_ID))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::OBJECT_ID_MASK:\n\t\t\tif (HasChannel(OBJECT_ID_MASK) && props) {\n\t\t\t\tchannelCount = 1;\t\t\n\t\t\t\t\/\/ Look for the object mask ID index\n\t\t\t\tconst u_int id = props->Get(Property(\"id\")(255)).Get<u_int>();\n\t\t\t\tbool found = false;\n\t\t\t\tfor (u_int i = 0; i < maskObjectIDs.size(); ++i) {\n\t\t\t\t\tif (maskObjectIDs[i] == id) {\n\t\t\t\t\t\tmaskObjectIDsIndex = i;\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!found)\n\t\t\t\t\treturn;\n\t\t\t} else\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::BY_OBJECT_ID:\n\t\t\tif (HasChannel(BY_OBJECT_ID) && props) {\n\t\t\t\t\/\/ Look for the object mask ID index\n\t\t\t\tconst u_int id = props->Get(Property(\"id\")(255)).Get<u_int>();\n\t\t\t\tbool found = false;\n\t\t\t\tfor (u_int i = 0; i < byObjectIDs.size(); ++i) {\n\t\t\t\t\tif (byObjectIDs[i] == id) {\n\t\t\t\t\t\tbyObjectIDsIndex = i;\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!found)\n\t\t\t\t\treturn;\n\t\t\t} else\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::SAMPLECOUNT:\n\t\t\tif (!HasChannel(SAMPLECOUNT))\n\t\t\t\treturn;\n\t\t\tchannelCount = 1;\n\t\t\tbreak;\n\t\tcase FilmOutputs::CONVERGENCE:\n\t\t\tif (!HasChannel(CONVERGENCE))\n\t\t\t\treturn;\n\t\t\tchannelCount = 1;\n\t\t\tbreak;\n\t\tcase FilmOutputs::MATERIAL_ID_COLOR:\n\t\t\tif (!HasChannel(MATERIAL_ID_COLOR))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::ALBEDO:\n\t\t\tif (!HasChannel(ALBEDO))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::AVG_SHADING_NORMAL:\n\t\t\tif (!HasChannel(AVG_SHADING_NORMAL))\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\tcase FilmOutputs::NOISE:\n\t\t\tif (!HasChannel(NOISE))\n\t\t\t\treturn;\n\t\t\tchannelCount = 1;\n\t\t\tbreak;\n\t\tcase FilmOutputs::USER_IMPORTANCE:\n\t\t\tif (!HasChannel(USER_IMPORTANCE))\n\t\t\t\treturn;\n\t\t\tchannelCount = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow runtime_error(\"Unknown film output type in Film::Output(): \" + ToString(type));\n\t}\n\n\tImageBuf buffer;\n\t\n\tSLG_LOG(\"Outputting film: \" << fileName << \" type: \" << ToString(type));\n\n\tbool hdrImage = false;\n\tconst string fileExtension = GetFileNameExt(fileName);\n\tif (fileExtension == \".exr\" || fileExtension == \".hdr\")\n\t\thdrImage = true;\n\n\tif ((type == FilmOutputs::MATERIAL_ID) || (type == FilmOutputs::OBJECT_ID) ||\n\t\t\t((type == FilmOutputs::SAMPLECOUNT) && (!hdrImage))) {\n\t\t\/\/ For IDs we must copy into int buffer first or risk screwing up the IDs\n\t\tImageSpec spec(width, height, channelCount, TypeDesc::UINT8);\n\t\tbuffer.reset(spec);\n\n\t\tGenericFrameBuffer<1, 0, u_int> *channel;\n\t\tswitch (type) {\n\t\t\tcase FilmOutputs::MATERIAL_ID:\n\t\t\t\tchannel = channel_MATERIAL_ID;\n\t\t\t\tbreak;\n\t\t\tcase FilmOutputs::OBJECT_ID:\n\t\t\t\tchannel = channel_OBJECT_ID;\n\t\t\t\tbreak;\n\t\t\tcase FilmOutputs::SAMPLECOUNT:\n\t\t\t\tchannel = channel_SAMPLECOUNT;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow runtime_error(\"Unknown film output type in Film::Output(): \" + ToString(type));\n\t\t}\n\n\t\tfor (ImageBuf::ConstIterator<BYTE> it(buffer); !it.done(); ++it) {\n\t\t\tu_int x = it.x();\n\t\t\tu_int y = it.y();\n\t\t\tBYTE *pixel = (BYTE *)buffer.pixeladdr(x, y, 0);\n\t\t\ty = height - y - 1;\n\t\t\t\n\t\t\tif (pixel == NULL)\n\t\t\t\tthrow runtime_error(\"Error while unpacking film data, could not address buffer!\");\n\n\t\t\tconst u_int src = *(channel->GetPixel(x, y));\n\t\t\tpixel[0] = (BYTE)(src & 0x0000ffu);\n\t\t\tpixel[1] = (BYTE)((src & 0x00ff00u) >> 8);\n\t\t\tpixel[2] = (BYTE)((src & 0xff0000u) >> 16);\n\t\t}\n\t} else {\n\t\t\/\/ OIIO 1 channel EXR output is apparently not working, I write 3 channels as\n\t\t\/\/ temporary workaround\n\t\t\/\/\n\t\t\/\/ Note: they are working is just that 1 channel EXR is supposed to be alpha\n\t\t\/\/ and not grey so it is not shown by some program like exrdisplay\n\n\t\t\/\/ For all others copy into float buffer first and let OIIO figure out the conversion on write\n\t\tImageSpec spec(width, height, (channelCount == 1) ? 3 : channelCount, TypeDesc::FLOAT);\n\t\tbuffer.reset(spec);\n\t\n\t\tconst double RADIANCE_PER_SCREEN_NORMALIZED_SampleCount = samplesCounts.GetSampleCount_RADIANCE_PER_SCREEN_NORMALIZED();\n\t\t\n\t\tfor (ImageBuf::ConstIterator<float> it(buffer); !it.done(); ++it) {\n\t\t\tu_int x = it.x();\n\t\t\tu_int y = it.y();\n\t\t\tfloat *pixel = (float *)buffer.pixeladdr(x, y, 0);\n\t\t\ty = height - y - 1;\n\n\t\t\tif (pixel == NULL)\n\t\t\t\tthrow runtime_error(\"Error while unpacking film data, could not address buffer!\");\n\n\t\t\tswitch (type) {\n\t\t\t\tcase FilmOutputs::RGB: {\n\t\t\t\t\t\/\/ Accumulate all light groups\t\t\t\n\t\t\t\t\tGetPixelFromMergedSampleBuffers(0, RADIANCE_PER_SCREEN_NORMALIZED_SampleCount,\n\t\t\t\t\t\t\tx, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::RGB_IMAGEPIPELINE: {\n\t\t\t\t\tchannel_IMAGEPIPELINEs[imagePipelineIndex]->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::RGBA: {\n\t\t\t\t\t\/\/ Accumulate all light groups\n\t\t\t\t\tGetPixelFromMergedSampleBuffers(0, RADIANCE_PER_SCREEN_NORMALIZED_SampleCount,\n\t\t\t\t\t\t\tx, y, pixel);\n\t\t\t\t\tchannel_ALPHA->GetWeightedPixel(x, y, &pixel[3]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::RGBA_IMAGEPIPELINE: {\n\t\t\t\t\tchannel_IMAGEPIPELINEs[imagePipelineIndex]->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tchannel_ALPHA->GetWeightedPixel(x, y, &pixel[3]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::ALPHA: {\n\t\t\t\t\tchannel_ALPHA->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::DEPTH: {\n\t\t\t\t\tchannel_DEPTH->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::POSITION: {\n\t\t\t\t\tchannel_POSITION->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::GEOMETRY_NORMAL: {\n\t\t\t\t\tchannel_GEOMETRY_NORMAL->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::SHADING_NORMAL: {\n\t\t\t\t\tchannel_SHADING_NORMAL->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::DIRECT_DIFFUSE: {\n\t\t\t\t\tchannel_DIRECT_DIFFUSE->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::DIRECT_GLOSSY: {\n\t\t\t\t\tchannel_DIRECT_GLOSSY->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::EMISSION: {\n\t\t\t\t\tchannel_EMISSION->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::INDIRECT_DIFFUSE: {\n\t\t\t\t\tchannel_INDIRECT_DIFFUSE->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::INDIRECT_GLOSSY: {\n\t\t\t\t\tchannel_INDIRECT_GLOSSY->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::INDIRECT_SPECULAR: {\n\t\t\t\t\tchannel_INDIRECT_SPECULAR->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::MATERIAL_ID_MASK: {\n\t\t\t\t\tchannel_MATERIAL_ID_MASKs[maskMaterialIDsIndex]->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::DIRECT_SHADOW_MASK: {\n\t\t\t\t\tchannel_DIRECT_SHADOW_MASK->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::INDIRECT_SHADOW_MASK: {\n\t\t\t\t\tchannel_INDIRECT_SHADOW_MASK->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::RADIANCE_GROUP: {\n\t\t\t\t\t\/\/ Clear the pixel\n\t\t\t\t\tpixel[0] = 0.f;\n\t\t\t\t\tpixel[1] = 0.f;\n\t\t\t\t\tpixel[2] = 0.f;\n\n\t\t\t\t\t\/\/ Accumulate all light groups\n\t\t\t\t\tif (radianceGroupIndex < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size()) {\n\t\t\t\t\t\tchannel_RADIANCE_PER_SCREEN_NORMALIZEDs[radianceGroupIndex]->AccumulateWeightedPixel(x, y, pixel);\n\n\t\t\t\t\t\t\/\/ Normalize the value\n\t\t\t\t\t\tconst float factor = RADIANCE_PER_SCREEN_NORMALIZED_SampleCount \/ pixelCount;\n\t\t\t\t\t\tpixel[0] *= factor;\n\t\t\t\t\t\tpixel[1] *= factor;\n\t\t\t\t\t\tpixel[2] *= factor;\n\t\t\t\t\t}\n\t\t\t\t\tif (radianceGroupIndex < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size())\n\t\t\t\t\t\tchannel_RADIANCE_PER_PIXEL_NORMALIZEDs[radianceGroupIndex]->AccumulateWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::UV: {\n\t\t\t\t\tchannel_UV->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tpixel[2] = 0.f;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::RAYCOUNT: {\n\t\t\t\t\tchannel_RAYCOUNT->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::BY_MATERIAL_ID: {\n\t\t\t\t\tchannel_BY_MATERIAL_IDs[byMaterialIDsIndex]->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::IRRADIANCE: {\n\t\t\t\t\tchannel_IRRADIANCE->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::OBJECT_ID_MASK: {\n\t\t\t\t\tchannel_OBJECT_ID_MASKs[maskObjectIDsIndex]->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::BY_OBJECT_ID: {\n\t\t\t\t\tchannel_BY_OBJECT_IDs[byObjectIDsIndex]->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::SAMPLECOUNT: {\n\t\t\t\t\tu_int val;\n\t\t\t\t\tchannel_SAMPLECOUNT->GetWeightedPixel(x, y, &val);\n\t\t\t\t\tpixel[0] = val;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::CONVERGENCE: {\n\t\t\t\t\tchannel_CONVERGENCE->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::MATERIAL_ID_COLOR: {\n\t\t\t\t\tchannel_MATERIAL_ID_COLOR->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::ALBEDO: {\n\t\t\t\t\tchannel_ALBEDO->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::AVG_SHADING_NORMAL: {\n\t\t\t\t\tchannel_AVG_SHADING_NORMAL->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\t\/\/ Normalize the value (should I ?)\n\t\t\t\t\t\/*const float length2 = pixel[0] * pixel[0] + pixel[1] * pixel[1] + pixel[2] * pixel[2];\n\t\t\t\t\tif (length2 > 0.f) {\n\t\t\t\t\t\tconst float k = 1.f \/ sqrtf(length2);\n\t\t\t\t\t\tpixel[0] *= k;\n\t\t\t\t\t\tpixel[1] *= k;\n\t\t\t\t\t\tpixel[2] *= k;\n\t\t\t\t\t}*\/\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::NOISE: {\n\t\t\t\t\tchannel_NOISE->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase FilmOutputs::USER_IMPORTANCE: {\n\t\t\t\t\tchannel_USER_IMPORTANCE->GetWeightedPixel(x, y, pixel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tthrow runtime_error(\"Unknown film output type in Film::Output(): \" + ToString(type));\n\t\t\t}\n\n\t\t\t\/\/ OIIO 1 channel EXR output is apparently not working, I write 3 channels as\n\t\t\t\/\/ temporary workaround\n\t\t\tif (channelCount == 1) {\n\t\t\t\tpixel[1] = pixel[0];\n\t\t\t\tpixel[2] = pixel[0];\n\t\t\t}\n\t\t}\n\t}\n\n\tif (filmOutputs.UseSafeSave()) {\n\t\tSafeSave safeSave(fileName);\n\n\t\tif (!buffer.write(safeSave.GetSaveFileName()))\n\t\t\tthrow runtime_error(\"Error while writing an output type in Film::Output(): \" +\n\t\t\t\t\tsafeSave.GetSaveFileName() + \" (error = \" + geterror() + \")\");\n\n\t\tsafeSave.Process();\n\t} else {\n\t\tif (!buffer.write(fileName))\n\t\t\tthrow runtime_error(\"Error while writing an output type in Film::Output(): \" +\n\t\t\t\t\tfileName + \" (error = \" + geterror() + \")\");\n\t}\n}\n\nu_int Film::GetOutputCount(const FilmOutputs::FilmOutputType type) const {\n\tswitch (type) {\n\t\tcase FilmOutputs::RGB_IMAGEPIPELINE:\n\t\t\treturn channel_IMAGEPIPELINEs.size();\n\t\tcase FilmOutputs::RGBA_IMAGEPIPELINE:\n\t\t\treturn channel_IMAGEPIPELINEs.size();\n\t\tcase FilmOutputs::MATERIAL_ID_MASK:\n\t\t\treturn channel_MATERIAL_ID_MASKs.size();\n\t\tcase FilmOutputs::RADIANCE_GROUP:\n\t\t\treturn channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size();\n\t\tcase FilmOutputs::BY_MATERIAL_ID:\n\t\t\treturn channel_BY_MATERIAL_IDs.size();\n\t\tcase FilmOutputs::OBJECT_ID_MASK:\n\t\t\treturn channel_OBJECT_ID_MASKs.size();\n\t\tcase FilmOutputs::BY_OBJECT_ID:\n\t\t\treturn channel_BY_OBJECT_IDs.size();\n\t\tdefault:\n\t\t\tif (HasOutput(type))\n\t\t\t\treturn 1;\n\t\t\telse\n\t\t\t\treturn 0;\n\t}\n}\n\ntemplate<> void Film::GetOutput<float>(const FilmOutputs::FilmOutputType type, float *buffer,\n\t\tconst u_int index, const bool executeImagePipeline) {\n\tif (!HasOutput(type))\n\t\tthrow runtime_error(\"Film output not defined in Film::GetOutput<float>(): \" + ToString(type));\n\n\tif (index > GetOutputCount(type))\n\t\tthrow runtime_error(\"Film output index not defined in Film::GetOutput<float>(): \" + ToString(type) + \"\/\" + ToString(index));\n\n\tswitch (type) {\n\t\tcase FilmOutputs::RGB: {\n\t\t\tconst double RADIANCE_PER_SCREEN_NORMALIZED_SampleCount = samplesCounts.GetSampleCount_RADIANCE_PER_SCREEN_NORMALIZED();\n\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tGetPixelFromMergedSampleBuffers(0,\n\t\t\t\t\t\tRADIANCE_PER_SCREEN_NORMALIZED_SampleCount,\n\t\t\t\t\t\ti, &buffer[i * 3]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::RGB_IMAGEPIPELINE:\n\t\t\tif (executeImagePipeline)\n\t\t\t\tExecuteImagePipeline(index);\n\n\t\t\tcopy(channel_IMAGEPIPELINEs[index]->GetPixels(), channel_IMAGEPIPELINEs[index]->GetPixels() + pixelCount * 3, buffer);\n\t\t\tbreak;\n\t\tcase FilmOutputs::RGBA: {\n\t\t\tconst double RADIANCE_PER_SCREEN_NORMALIZED_SampleCount = samplesCounts.GetSampleCount_RADIANCE_PER_SCREEN_NORMALIZED();\n\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i) {\n\t\t\t\tconst u_int offset = i * 4;\n\t\t\t\tGetPixelFromMergedSampleBuffers(0,\n\t\t\t\t\t\tRADIANCE_PER_SCREEN_NORMALIZED_SampleCount,\n\t\t\t\t\t\ti, &buffer[offset]);\n\t\t\t\tchannel_ALPHA->GetWeightedPixel(i, &buffer[offset + 3]);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::RGBA_IMAGEPIPELINE: {\n\t\t\tif (executeImagePipeline)\n\t\t\t\tExecuteImagePipeline(index);\n\n\t\t\tfloat *srcRGB = channel_IMAGEPIPELINEs[index]->GetPixels();\n\t\t\tfloat *dst = buffer;\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i) {\n\t\t\t\t*dst++ = *srcRGB++;\n\t\t\t\t*dst++ = *srcRGB++;\n\t\t\t\t*dst++ = *srcRGB++;\n\t\t\t\tchannel_ALPHA->GetWeightedPixel(i, dst++);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::ALPHA: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_ALPHA->GetWeightedPixel(i, &buffer[i]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::DEPTH:\n\t\t\tcopy(channel_DEPTH->GetPixels(), channel_DEPTH->GetPixels() + pixelCount, buffer);\n\t\t\tbreak;\n\t\tcase FilmOutputs::POSITION:\n\t\t\tcopy(channel_POSITION->GetPixels(), channel_POSITION->GetPixels() + pixelCount * 3, buffer);\n\t\t\tbreak;\n\t\tcase FilmOutputs::GEOMETRY_NORMAL:\n\t\t\tcopy(channel_GEOMETRY_NORMAL->GetPixels(), channel_GEOMETRY_NORMAL->GetPixels() + pixelCount * 3, buffer);\n\t\t\tbreak;\n\t\tcase FilmOutputs::SHADING_NORMAL:\n\t\t\tcopy(channel_SHADING_NORMAL->GetPixels(), channel_SHADING_NORMAL->GetPixels() + pixelCount * 3, buffer);\n\t\t\tbreak;\n\t\tcase FilmOutputs::DIRECT_DIFFUSE: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_DIRECT_DIFFUSE->GetWeightedPixel(i, &buffer[i * 3]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::DIRECT_GLOSSY: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_DIRECT_GLOSSY->GetWeightedPixel(i, &buffer[i * 3]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::EMISSION: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_EMISSION->GetWeightedPixel(i, &buffer[i * 3]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::INDIRECT_DIFFUSE: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_INDIRECT_DIFFUSE->GetWeightedPixel(i, &buffer[i * 3]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::INDIRECT_GLOSSY: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_INDIRECT_GLOSSY->GetWeightedPixel(i, &buffer[i * 3]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::INDIRECT_SPECULAR: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_INDIRECT_SPECULAR->GetWeightedPixel(i, &buffer[i * 3]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::MATERIAL_ID_MASK: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_MATERIAL_ID_MASKs[index]->GetWeightedPixel(i, &buffer[i]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::DIRECT_SHADOW_MASK: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_DIRECT_SHADOW_MASK->GetWeightedPixel(i, &buffer[i]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::INDIRECT_SHADOW_MASK: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_INDIRECT_SHADOW_MASK->GetWeightedPixel(i, &buffer[i]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::RADIANCE_GROUP: {\n\t\t\tfill(buffer, buffer + 3 * pixelCount, 0.f);\n\n\t\t\tif (index < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size()) {\n\t\t\t\tconst ImagePipeline *ip = (imagePipelines.size() > 0) ? imagePipelines[0] : NULL;\n\n\t\t\t\tfloat *dst = buffer;\n\t\t\t\tfor (u_int i = 0; i < pixelCount; ++i) {\n\t\t\t\t\tfloat c[3];\n\t\t\t\t\tchannel_RADIANCE_PER_PIXEL_NORMALIZEDs[index]->GetWeightedPixel(i, c);\n\t\t\t\t\tif (ip)\n\t\t\t\t\t\tip->radianceChannelScales[index].Scale(c);\n\n\t\t\t\t\t*dst++ += c[0];\n\t\t\t\t\t*dst++ += c[1];\n\t\t\t\t\t*dst++ += c[2];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (index < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size()) {\n\t\t\t\tconst ImagePipeline *ip = (imagePipelines.size() > 0) ? imagePipelines[0] : NULL;\n\n\t\t\t\tfloat *dst = buffer;\n\t\t\t\tfor (u_int i = 0; i < pixelCount; ++i) {\n\t\t\t\t\tfloat c[3];\n\t\t\t\t\tchannel_RADIANCE_PER_SCREEN_NORMALIZEDs[index]->GetWeightedPixel(i, c);\n\t\t\t\t\tif (ip)\n\t\t\t\t\t\tip->radianceChannelScales[index].Scale(c);\n\n\t\t\t\t\t*dst++ += c[0];\n\t\t\t\t\t*dst++ += c[1];\n\t\t\t\t\t*dst++ += c[2];\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::UV:\n\t\t\tcopy(channel_UV->GetPixels(), channel_UV->GetPixels() + pixelCount * 2, buffer);\n\t\t\tbreak;\n\t\tcase FilmOutputs::RAYCOUNT:\n\t\t\tcopy(channel_RAYCOUNT->GetPixels(), channel_RAYCOUNT->GetPixels() + pixelCount, buffer);\n\t\t\tbreak;\n\t\tcase FilmOutputs::BY_MATERIAL_ID: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_BY_MATERIAL_IDs[index]->GetWeightedPixel(i, &buffer[i * 3]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::IRRADIANCE: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_IRRADIANCE->GetWeightedPixel(i, &buffer[i * 3]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::OBJECT_ID_MASK: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_OBJECT_ID_MASKs[index]->GetWeightedPixel(i, &buffer[i]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::BY_OBJECT_ID: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_BY_OBJECT_IDs[index]->GetWeightedPixel(i, &buffer[i * 3]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::CONVERGENCE:\n\t\t\tcopy(channel_CONVERGENCE->GetPixels(), channel_CONVERGENCE->GetPixels() + pixelCount, buffer);\n\t\t\tbreak;\n\t\tcase FilmOutputs::MATERIAL_ID_COLOR: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_MATERIAL_ID_COLOR->GetWeightedPixel(i, &buffer[i * 3]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::ALBEDO: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_ALBEDO->GetWeightedPixel(i, &buffer[i * 3]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::AVG_SHADING_NORMAL: {\n\t\t\tfor (u_int i = 0; i < pixelCount; ++i)\n\t\t\t\tchannel_AVG_SHADING_NORMAL->GetWeightedPixel(i, &buffer[i * 3]);\n\t\t\tbreak;\n\t\t}\n\t\tcase FilmOutputs::NOISE:\n\t\t\tcopy(channel_NOISE->GetPixels(), channel_NOISE->GetPixels() + pixelCount, buffer);\n\t\t\tbreak;\n\t\tcase FilmOutputs::USER_IMPORTANCE:\n\t\t\tcopy(channel_USER_IMPORTANCE->GetPixels(), channel_USER_IMPORTANCE->GetPixels() + pixelCount, buffer);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow runtime_error(\"Unknown film output type in Film::GetOutput<float>(): \" + ToString(type));\n\t}\n}\n\ntemplate<> void Film::GetOutput<u_int>(const FilmOutputs::FilmOutputType type, u_int *buffer,\n\t\tconst u_int index, const bool executeImagePipeline) {\n\tif (!HasOutput(type))\n\t\tthrow runtime_error(\"Film output not defined in Film::GetOutput<u_int>(): \" + ToString(type));\n\n\tif (index > GetOutputCount(type))\n\t\tthrow runtime_error(\"Film output index not defined in Film::GetOutput<float>(): \" + ToString(type) + \"\/\" + ToString(index));\n\n\tswitch (type) {\n\t\tcase FilmOutputs::MATERIAL_ID:\n\t\t\tcopy(channel_MATERIAL_ID->GetPixels(), channel_MATERIAL_ID->GetPixels() + pixelCount, buffer);\n\t\t\tbreak;\n\t\tcase FilmOutputs::OBJECT_ID:\n\t\t\tcopy(channel_OBJECT_ID->GetPixels(), channel_OBJECT_ID->GetPixels() + pixelCount, buffer);\n\t\t\tbreak;\n\t\tcase FilmOutputs::SAMPLECOUNT:\n\t\t\tcopy(channel_SAMPLECOUNT->GetPixels(), channel_SAMPLECOUNT->GetPixels() + pixelCount, buffer);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow runtime_error(\"Unknown film output type in Film::GetOutput<u_int>(): \" + ToString(type));\n\t}\n}\n","avg_line_length":31.7901878914,"max_line_length":126,"alphanum_fraction":0.6715810212,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":208,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"#include <kickstart\/all.hpp>\nusing namespace kickstart::all;\n\nvoid cppmain()\n{\n    out << fsx::path_of_executable().to_string() << endl;\n}\n\nauto main() -> int { return with_exceptions_displayed( cppmain ); }\n","avg_line_length":20.8,"max_line_length":67,"alphanum_fraction":0.6971153846,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1296,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include \"Controller.h\"\n\n\/\/WIP\n\/*\nglm::vec3 Controller::translateInput()\n{\n    glm::vec3 change;\n    float speed = 0.25f;\n    if (sf::Keyboard::isKeyPressed(sf::Keyboard::LControl))\n    {\n        speed *= 8;\n    }\n\n    if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))\n    {\n        change.x += -glm::cos(glm::radians(rotation.y + 90)) * speed;\n        change.z += -glm::sin(glm::radians(rotation.y + 90)) * speed;\n    }\n    if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))\n    {\n        change.x += glm::cos(glm::radians(rotation.y + 90)) * speed;\n        change.z += glm::sin(glm::radians(rotation.y + 90)) * speed;\n    }\n    if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))\n    {\n        change.x += -glm::cos(glm::radians(rotation.y)) * speed;\n        change.z += -glm::sin(glm::radians(rotation.y)) * speed;\n    }\n    if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))\n    {\n        change.x += glm::cos(glm::radians(rotation.y)) * speed;\n        change.z += glm::sin(glm::radians(rotation.y)) * speed;\n    }\n\n    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)&& (m_isOnGround))\n    {\n        change.y += speed;\n    }\n    else if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift))\n    {\n        change.y -= speed;\n    }\n\n    return change;\n}\n\nsf::Vector2i Controller::mouseInput()\n{\n\n}\n*\/\n","avg_line_length":24.9230769231,"max_line_length":73,"alphanum_fraction":0.5648148148,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":16132,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\n#include \"Angel.h\"\n#include <assert.h>\n\ntypedef Angel::vec4 point4;\ntypedef Angel::vec4 color4;\n\nconst int NumVertices = 36; \/\/(6 faces)(2 triangles\/face)(3 vertices\/triangle)\nconst int NumNodes = 11;\nconst int NumAngles = 11;\n\npoint4 points[NumVertices];\ncolor4 colors[NumVertices];\n\npoint4 vertices[8] = {\n    point4( -0.5, -0.5, 0.5, 1.0 ),\n    point4( -0.5, 0.5, 0.5, 1.0 ),\n    point4( 0.5, 0.5, 0.5, 1.0 ),\n    point4( 0.5, -0.5, 0.5, 1.0 ),\n    point4( -0.5, -0.5, -0.5, 1.0 ),\n    point4( -0.5, 0.5, -0.5, 1.0 ),\n    point4( 0.5, 0.5, -0.5, 1.0 ),\n    point4( 0.5, -0.5, -0.5, 1.0 )\n};\n\n\/\/ RGBA olors\ncolor4 vertex_colors[8] = {\n    color4( 0.0, 0.0, 0.0, 1.0 ),  \/\/ black\n    color4( 1.0, 0.0, 0.0, 1.0 ),  \/\/ red\n    color4( 1.0, 1.0, 0.0, 1.0 ),  \/\/ yellow\n    color4( 0.0, 1.0, 0.0, 1.0 ),  \/\/ green\n    color4( 0.0, 0.0, 1.0, 1.0 ),  \/\/ blue\n    color4( 1.0, 0.0, 1.0, 1.0 ),  \/\/ magenta\n    color4( 1.0, 1.0, 1.0, 1.0 ),  \/\/ white\n    color4( 0.0, 1.0, 1.0, 1.0 )   \/\/ cyan\n};\n\n\/\/----------------------------------------------------------------------------\n\n class MatrixStack {\n    int    _index;\n    int    _size;\n    mat4*  _matrices;\n\n   public:\n    MatrixStack( int numMatrices = 32 ):_index(0), _size(numMatrices)\n        { _matrices = new mat4[numMatrices]; }\n\n    ~MatrixStack()\n\t{ delete[]_matrices; }\n\n    void push( const mat4& m ) {\n        assert( _index + 1 < _size );\n        _matrices[_index++] = m;\n    }\n\n    mat4& pop( void ) {\n        assert( _index - 1 >= 0 );\n        _index--;\n         return _matrices[_index];\n    }\n};\n\nMatrixStack  mvstack; \n\n\nmat4         model_view;\nGLuint       ModelView, Projection;\n\n\n\/\/----------------------------------------------------------------------------\n\n#define TORSO_HEIGHT 5.0\n#define TORSO_WIDTH 1.0\n#define UPPER_ARM_HEIGHT 3.0\n#define LOWER_ARM_HEIGHT 2.0\n#define UPPER_LEG_WIDTH  0.5\n#define LOWER_LEG_WIDTH  0.5\n#define LOWER_LEG_HEIGHT 2.0\n#define UPPER_LEG_HEIGHT 3.0\n#define UPPER_LEG_WIDTH  0.5\n#define UPPER_ARM_WIDTH  0.5\n#define LOWER_ARM_WIDTH  0.5\n#define HEAD_HEIGHT 1.5\n#define HEAD_WIDTH 1.0\n\n\/\/ Set up menu item indices, which we can alos use with the joint angles\nenum {\n    Torso = 0,\n    Head  = 1,\n    Head1 = 1,\n    Head2 = 2,\n    LeftUpperArm = 3,\n    LeftLowerArm = 4,\n    RightUpperArm = 5,\n    RightLowerArm = 6,\n    LeftUpperLeg = 7,\n    LeftLowerLeg = 8,\n    RightUpperLeg = 9,\n    RightLowerLeg = 10,\n    Quit\n};\n\n\/\/ Joint angles with initial values\nGLfloat\ntheta[NumAngles] = {\n    0.0,    \/\/ Torso\n    0.0,    \/\/ Head1\n    0.0,    \/\/ Head2\n    0.0,    \/\/ LeftUpperArm\n    0.0,    \/\/ LeftLowerArm\n    0.0,    \/\/ RightUpperArm\n    0.0,    \/\/ RightLowerArm\n    180.0,  \/\/ LeftUpperLeg\n    0.0,     \/\/ LeftLowerLeg\n    180.0,  \/\/ RightUpperLeg\n    0.0    \/\/ RightLowerLeg\n};\n\nGLint angle = Head2;\n\n\/\/----------------------------------------------------------------------------\n\nstruct Node {\n    mat4  transform;\n    void  (*render)( void );\n    Node* sibling;\n    Node* child;\n\n    Node() :\n\trender(NULL), sibling(NULL), child(NULL) {}\n    \n    Node( mat4& m, void (*render)( void ), Node* sibling, Node* child ) :\n\ttransform(m), render(render), sibling(sibling), child(child) {}\n};\n\nNode  nodes[NumNodes];\n\n\/\/----------------------------------------------------------------------------\n\nint Index = 0;\n\nvoid\nquad( int a, int b, int c, int d )\n{\n    colors[Index] = vertex_colors[a]; points[Index] = vertices[a]; Index++;\n    colors[Index] = vertex_colors[a]; points[Index] = vertices[b]; Index++;\n    colors[Index] = vertex_colors[a]; points[Index] = vertices[c]; Index++;\n    colors[Index] = vertex_colors[a]; points[Index] = vertices[a]; Index++;\n    colors[Index] = vertex_colors[a]; points[Index] = vertices[c]; Index++;\n    colors[Index] = vertex_colors[a]; points[Index] = vertices[d]; Index++;\n}\n\nvoid\ncolorcube( void )\n{\n    quad( 1, 0, 3, 2 );\n    quad( 2, 3, 7, 6 );\n    quad( 3, 0, 4, 7 );\n    quad( 6, 5, 1, 2 );\n    quad( 4, 5, 6, 7 );\n    quad( 5, 4, 0, 1 );\n}\n\n\/\/----------------------------------------------------------------------------\n\nvoid\ntraverse( Node* node )\n{\n    if ( node == NULL ) { return; }\n\n     mvstack.push( model_view );\n\n    model_view *= node->transform;\n    node->render();\n\n      traverse( node->child ); \n    if ( node->child != NULL) { traverse( node->child ); }\n\n    model_view = mvstack.pop();\n\n     traverse( node->sibling ); \n    if ( node->sibling != NULL) { traverse( node->sibling ); }\n}\n\n\/\/----------------------------------------------------------------------------\n\nvoid\ntorso()\n{\n    mvstack.push( model_view );\n\n    mat4 instance = ( Translate( 0.0, 0.5 * TORSO_HEIGHT, 0.0 ) *\n\t\t      Scale( TORSO_WIDTH, TORSO_HEIGHT, TORSO_WIDTH ) );\n    \n    glUniformMatrix4fv( ModelView, 1, GL_TRUE, model_view * instance );\n    glDrawArrays( GL_TRIANGLES, 0, NumVertices );\n\n    model_view = mvstack.pop();\n}\n\nvoid\nhead()\n{\n    mvstack.push( model_view );\n\n    mat4 instance = (Translate( 0.0, 0.5 * HEAD_HEIGHT, 0.0 ) *\n\t\t     Scale( HEAD_WIDTH, HEAD_HEIGHT, HEAD_WIDTH ) );\n    \n    glUniformMatrix4fv( ModelView, 1, GL_TRUE, model_view * instance );\n    glDrawArrays( GL_TRIANGLES, 0, NumVertices );\n\n    model_view = mvstack.pop();\n}\n\nvoid\nleft_upper_arm()\n{\n    mvstack.push( model_view );\n\n    mat4 instance = (Translate( 0.0, 0.5 * UPPER_ARM_HEIGHT, 0.0 ) *\n\t\t     Scale( UPPER_ARM_WIDTH,\n\t\t\t    UPPER_ARM_HEIGHT,\n\t\t\t    UPPER_ARM_WIDTH ) );\n\n    glUniformMatrix4fv( ModelView, 1, GL_TRUE, model_view * instance );\n    glDrawArrays( GL_TRIANGLES, 0, NumVertices );\n\n    model_view = mvstack.pop();\n}\n\nvoid\nleft_lower_arm()\n{\n    mvstack.push( model_view );\n\n    mat4 instance = ( Translate( 0.0, 0.5 * LOWER_ARM_HEIGHT, 0.0 ) *\n\t\t      Scale( LOWER_ARM_WIDTH,\n\t\t\t     LOWER_ARM_HEIGHT,\n\t\t\t     LOWER_ARM_WIDTH ) );\n    \n    glUniformMatrix4fv( ModelView, 1, GL_TRUE, model_view * instance );\n    glDrawArrays( GL_TRIANGLES, 0, NumVertices );\n\n    model_view = mvstack.pop();\n}\n\nvoid\nright_upper_arm()\n{\n    mvstack.push( model_view );\n\n    mat4 instance = (Translate( 0.0, 0.5 * UPPER_ARM_HEIGHT, 0.0 ) *\n\t\t     Scale( UPPER_ARM_WIDTH,\n\t\t\t    UPPER_ARM_HEIGHT,\n\t\t\t    UPPER_ARM_WIDTH ) );\n    \n    glUniformMatrix4fv( ModelView, 1, GL_TRUE, model_view * instance );\n    glDrawArrays( GL_TRIANGLES, 0, NumVertices );\n\n    model_view = mvstack.pop();\n}\n\nvoid\nright_lower_arm()\n{\n    mvstack.push( model_view );\n\n    mat4 instance = (Translate( 0.0, 0.5 * LOWER_ARM_HEIGHT, 0.0 ) *\n\t\t     Scale( LOWER_ARM_WIDTH,\n\t\t\t    LOWER_ARM_HEIGHT,\n\t\t\t    LOWER_ARM_WIDTH ) );\n    \n    glUniformMatrix4fv( ModelView, 1, GL_TRUE, model_view * instance );\n    glDrawArrays( GL_TRIANGLES, 0, NumVertices );\n\n    model_view = mvstack.pop();\n}\n\nvoid\nleft_upper_leg()\n{\n    mvstack.push( model_view );\n\n    mat4 instance = ( Translate( 0.0, 0.5 * UPPER_LEG_HEIGHT, 0.0 ) *\n\t\t      Scale( UPPER_LEG_WIDTH,\n\t\t\t     UPPER_LEG_HEIGHT,\n\t\t\t     UPPER_LEG_WIDTH ) );\n    \n    glUniformMatrix4fv( ModelView, 1, GL_TRUE, model_view * instance );\n    glDrawArrays( GL_TRIANGLES, 0, NumVertices );\n\n    model_view = mvstack.pop();\n}\n\nvoid\nleft_lower_leg()\n{\n    mvstack.push( model_view );\n\n    mat4 instance = (Translate( 0.0, 0.5 * LOWER_LEG_HEIGHT, 0.0 ) *\n\t\t     Scale( LOWER_LEG_WIDTH,\n\t\t\t    LOWER_LEG_HEIGHT,\n\t\t\t    LOWER_LEG_WIDTH ) );\n    \n    glUniformMatrix4fv( ModelView, 1, GL_TRUE, model_view * instance );\n    glDrawArrays( GL_TRIANGLES, 0, NumVertices );\n\n    model_view = mvstack.pop();\n}\n\nvoid\nright_upper_leg()\n{\n    mvstack.push( model_view );\n\n    mat4 instance = (Translate( 0.0, 0.5 * UPPER_LEG_HEIGHT, 0.0 ) *\n\t\t     Scale( UPPER_LEG_WIDTH,\n\t\t\t    UPPER_LEG_HEIGHT,\n\t\t\t    UPPER_LEG_WIDTH ) );\n\n    glUniformMatrix4fv( ModelView, 1, GL_TRUE, model_view * instance );\n    glDrawArrays( GL_TRIANGLES, 0, NumVertices );\n\n    model_view = mvstack.pop();\n}\n\nvoid\nright_lower_leg()\n{\n    mvstack.push( model_view );\n\n    mat4 instance = ( Translate( 0.0, 0.5 * LOWER_LEG_HEIGHT, 0.0 ) *\n\t\t      Scale( LOWER_LEG_WIDTH,\n\t\t\t     LOWER_LEG_HEIGHT,\n\t\t\t     LOWER_LEG_WIDTH ) );\n    \n    glUniformMatrix4fv( ModelView, 1, GL_TRUE, model_view * instance );\n    glDrawArrays( GL_TRIANGLES, 0, NumVertices );\n\n    model_view = mvstack.pop();\n}\n\n\/\/----------------------------------------------------------------------------\n\nvoid\ndisplay()\n{\n    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n    traverse( &nodes[Torso] );\n    glutSwapBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\n\nvoid\nmouse( int button, int state, int x, int y )\n{\n    if ( button == GLUT_LEFT_BUTTON && state == GLUT_DOWN ) {\n        theta[angle] += 5.0;\n        if ( theta[angle] > 360.0 ) { theta[angle] -= 360.0; }\n    }\n\n    if ( button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN ) {\n        theta[angle] -= 5.0;\n        if ( theta[angle] < 0.0 ) { theta[angle] += 360.0; }\n    }\n\n    \/\/mvstack.push( model_view );\n    \n    switch( angle ) {\n\tcase Torso:\n\t    nodes[Torso].transform =\n\t\tRotateY( theta[Torso] );\n\t    break;\n\n\tcase Head1: case Head2:\n\t    nodes[Head].transform =\n\t\tTranslate(0.0, TORSO_HEIGHT+0.5*HEAD_HEIGHT, 0.0) *\n\t\tRotateX(theta[Head1]) *\n\t\tRotateY(theta[Head2]) *\n\t\tTranslate(0.0, -0.5*HEAD_HEIGHT, 0.0);\n\t    break;\n\n\tcase LeftUpperArm:\n\t    nodes[LeftUpperArm].transform = \n\t\tTranslate(-(TORSO_WIDTH+UPPER_ARM_WIDTH),\n\t\t\t  0.9*TORSO_HEIGHT, 0.0) *\n\t\tRotateX(theta[LeftUpperArm]);\n\t    break;\n\n\tcase RightUpperArm:\n\t    nodes[RightUpperArm].transform = \n\t\tTranslate(TORSO_WIDTH+UPPER_ARM_WIDTH, 0.9*TORSO_HEIGHT, 0.0) *\n\t\tRotateX(theta[RightUpperArm]);\n\t    break;\n\n\tcase RightUpperLeg:\n\t    nodes[RightUpperLeg].transform = \n\t\tTranslate(TORSO_WIDTH+UPPER_LEG_WIDTH,\n\t\t\t  0.1*UPPER_LEG_HEIGHT, 0.0) *\n\t\tRotateX(theta[RightUpperLeg]);\n\t    break;\n\n\tcase LeftUpperLeg:\n\t    nodes[LeftUpperLeg].transform = \n\t\tTranslate(-(TORSO_WIDTH+UPPER_LEG_WIDTH),\n\t\t\t  0.1*UPPER_LEG_HEIGHT, 0.0) *\n\t\tRotateX(theta[LeftUpperLeg]);\n\t    break;\n\n\tcase LeftLowerArm:\n\t    nodes[LeftLowerArm].transform = \n\t\tTranslate(0.0, UPPER_ARM_HEIGHT, 0.0) *\n\t\tRotateX(theta[LeftLowerArm]);\n\t    break;\n\n\tcase LeftLowerLeg:\n\t    nodes[LeftLowerLeg].transform = \n\t\tTranslate(0.0, UPPER_LEG_HEIGHT, 0.0) *\n\t\tRotateX(theta[LeftLowerLeg]);\n\t    break;\n\n\tcase RightLowerLeg:\n\t    nodes[RightLowerLeg].transform =\n\t\tTranslate(0.0, UPPER_LEG_HEIGHT, 0.0) *\n\t\tRotateX(theta[RightLowerLeg]);\n\t    break;\n\n\tcase RightLowerArm:\n\t    nodes[RightLowerArm].transform =\n\t\tTranslate(0.0, UPPER_ARM_HEIGHT, 0.0) *\n\t\tRotateX(theta[RightLowerArm]);\n\t    break;\n    }\n\n    \/\/ model_view = mvstack.pop();\n    glutPostRedisplay();\n}\n\n\/\/----------------------------------------------------------------------------\n\nvoid\nmenu( int option )\n{\n    if ( option == Quit ) {\n\texit( EXIT_SUCCESS );\n    }\n\n    angle = option;\n}\n\n\/\/----------------------------------------------------------------------------\n\nvoid\nreshape( int width, int height )\n{\n    glViewport( 0, 0, width, height );\n\n    GLfloat left = -10.0, right = 10.0;\n    GLfloat bottom = -10.0, top = 10.0;\n    GLfloat zNear = -10.0, zFar = 10.0;\n\n    GLfloat aspect = GLfloat( width ) \/ height;\n\n    if ( aspect > 1.0 ) {\n        left *= aspect;\n        right *= aspect;\n    }\n    else {\n        bottom \/= aspect;\n        top \/= aspect;\n    }\n\n    mat4 projection = Ortho( left, right, bottom, top, zNear, zFar );\n    glUniformMatrix4fv( Projection, 1, GL_TRUE, projection );\n\n    model_view = mat4( 1.0 );   \/\/ An Identity matrix\n}\n\n\/\/----------------------------------------------------------------------------\n\nvoid\ninitNodes( void )\n{\n    mat4  m;\n    \n    m = RotateY( theta[Torso] );\n    nodes[Torso] = Node( m, torso, NULL, &nodes[Head1] );\n\n    m = Translate(0.0, TORSO_HEIGHT+0.5*HEAD_HEIGHT, 0.0) *\n\tRotateX(theta[Head1]) *\n\tRotateY(theta[Head2]);\n    nodes[Head1] = Node( m, head, &nodes[LeftUpperArm], NULL );\n\n    m = Translate(-(TORSO_WIDTH+UPPER_ARM_WIDTH), 0.9*TORSO_HEIGHT, 0.0) *\n\tRotateX(theta[LeftUpperArm]);\n    nodes[LeftUpperArm] =\n\tNode( m, left_upper_arm, &nodes[RightUpperArm], &nodes[LeftLowerArm] );\n\n    m = Translate(TORSO_WIDTH+UPPER_ARM_WIDTH, 0.9*TORSO_HEIGHT, 0.0) *\n\tRotateX(theta[RightUpperArm]);\n    nodes[RightUpperArm] =\n\tNode( m, right_upper_arm,\n\t      &nodes[LeftUpperLeg], &nodes[RightLowerArm] );\n\n    m = Translate(-(TORSO_WIDTH+UPPER_LEG_WIDTH), 0.1*UPPER_LEG_HEIGHT, 0.0) *\n\tRotateX(theta[LeftUpperLeg]);\n    nodes[LeftUpperLeg] =\n\tNode( m, left_upper_leg, &nodes[RightUpperLeg], &nodes[LeftLowerLeg] );\n\n    m = Translate(TORSO_WIDTH+UPPER_LEG_WIDTH, 0.1*UPPER_LEG_HEIGHT, 0.0) *\n\tRotateX(theta[RightUpperLeg]);\n    nodes[RightUpperLeg] =\n\tNode( m, right_upper_leg, NULL, &nodes[RightLowerLeg] );\n\n    m = Translate(0.0, UPPER_ARM_HEIGHT, 0.0) * RotateX(theta[LeftLowerArm]);\n    nodes[LeftLowerArm] = Node( m, left_lower_arm, NULL, NULL );\n\n    m = Translate(0.0, UPPER_ARM_HEIGHT, 0.0) * RotateX(theta[RightLowerArm]);\n    nodes[RightLowerArm] = Node( m, right_lower_arm, NULL, NULL );\n\n    m = Translate(0.0, UPPER_LEG_HEIGHT, 0.0) * RotateX(theta[LeftLowerLeg]);\n    nodes[LeftLowerLeg] = Node( m, left_lower_leg, NULL, NULL );\n\n    m = Translate(0.0, UPPER_LEG_HEIGHT, 0.0) * RotateX(theta[RightLowerLeg]);\n    nodes[RightLowerLeg] = Node( m, right_lower_leg, NULL, NULL );\n\n}\n\n\/\/----------------------------------------------------------------------------\n\nvoid\ninit( void )\n{\n    colorcube();\n\n    \/\/ Initialize tree\n    initNodes();\n    \n    \/\/ Create a vertex array object\n    GLuint vao;\n    glGenVertexArraysAPPLE( 1, &vao );\n    glBindVertexArrayAPPLE( vao );\n\n    \/\/ Create and initialize a buffer object\n    GLuint buffer;\n    glGenBuffers( 1, &buffer );\n    glBindBuffer( GL_ARRAY_BUFFER, buffer );\n    glBufferData( GL_ARRAY_BUFFER, sizeof(points) + sizeof(colors),\n                  NULL, GL_DYNAMIC_DRAW );\n    glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(points), points );\n    glBufferSubData( GL_ARRAY_BUFFER, sizeof(points), sizeof(colors),\n                     colors );\n\n    \/\/ Load shaders and use the resulting shader program\n    GLuint program = InitShader( \"vshader83.glsl\", \"fshader83.glsl\" );\n    glUseProgram( program );\n\n    GLuint vPosition = glGetAttribLocation( program, \"vPosition\" );\n    glEnableVertexAttribArray( vPosition );\n    glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0,\n\t\t\t   BUFFER_OFFSET(0) );\n\n    GLuint vColor = glGetAttribLocation( program, \"vColor\" );\n    glEnableVertexAttribArray( vColor );\n    glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0,\n\t\t\t   BUFFER_OFFSET(sizeof(points)) );\n\n    ModelView = glGetUniformLocation( program, \"ModelView\" );\n    Projection = glGetUniformLocation( program, \"Projection\" );\n\n    glEnable( GL_DEPTH_TEST );\n    glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );\n\n    glClearColor( 1.0, 1.0, 1.0, 1.0 );\n\n}\n\n\/\/----------------------------------------------------------------------------\n\nvoid\nkeyboard( unsigned char key, int x, int y )\n{\n    switch( key ) {\n\tcase 033: \/\/ Escape Key\n\tcase 'q': case 'Q':\n\t    exit( EXIT_SUCCESS );\n\t    break;\n    }\n}\n\n\/\/----------------------------------------------------------------------------\n\nint\nmain( int argc, char **argv )\n{\n    glutInit( &argc, argv );\n    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );\n    glutInitWindowSize( 512, 512 );\n    glutCreateWindow( \"robot\" );\n\n    init();\n\n    glutDisplayFunc( display );\n    glutReshapeFunc( reshape );\n    glutKeyboardFunc( keyboard );\n    glutMouseFunc( mouse );\n\n    glutCreateMenu( menu );\n    glutAddMenuEntry( \"torso\", Torso );\n    glutAddMenuEntry( \"head1\", Head1 );\n    glutAddMenuEntry( \"head2\", Head2 );\n    glutAddMenuEntry( \"right_upper_arm\", RightUpperArm );\n    glutAddMenuEntry( \"right_lower_arm\", RightLowerArm );\n    glutAddMenuEntry( \"left_upper_arm\", LeftUpperArm );\n    glutAddMenuEntry( \"left_lower_arm\", LeftLowerArm );\n    glutAddMenuEntry( \"right_upper_leg\", RightUpperLeg );\n    glutAddMenuEntry( \"right_lower_leg\", RightLowerLeg );\n    glutAddMenuEntry( \"left_upper_leg\", LeftUpperLeg );\n    glutAddMenuEntry( \"left_lower_leg\", LeftLowerLeg );\n    glutAddMenuEntry( \"quit\", Quit );\n    glutAttachMenu( GLUT_MIDDLE_BUTTON );\n\n    glutMainLoop();\n    return 0;\n}\n","avg_line_length":25.6878980892,"max_line_length":78,"alphanum_fraction":0.5893255641,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3523,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ individual.cpp : \n\/\/\n\n#include \"stdafx.h\"\n#include \"assert.h\"\n#include \"debug.h\"\n#include \"random.h\"\n#include \"config.h\"\n#include \"strategy.h\"\n#include \"individual.h\"\n\nstatic DefectAlways    StratD;\nstatic CooperateAlways StratC;\nstatic Tit4Tat         StratT;\nstatic EmptyStrategy   StratNull;\n\nENERGY_UNITS Individual::m_stdEnergyCapacity;\nENERGY_UNITS Individual::m_initialEnergy;\n\nconst std::array< Strategy * const, Strategy::COUNT > Individual::m_apStrat =\n{ \n\t&StratD, \/\/ Strategy::Id::defect,   \n\t&StratC, \/\/ Strategy::Id::cooperate,\n\t&StratT  \/\/ Strategy::Id::tit4tat,  \n};\n\nvoid Individual::RefreshCache( )\n{\n    m_stdEnergyCapacity = ENERGY_UNITS(Config::GetConfigValueShort( Config::tId::stdCapacity ));\n    m_initialEnergy     = ENERGY_UNITS(Config::GetConfigValueShort( Config::tId::initialEnergy ));\n}\n\nIndividual::Individual( )\n{ \n    ResetIndividual( );\n}\n\nvoid Individual::ResetIndividual( )\n{ \n    m_id.Set2Null( ); \n    m_genBirth.Set2Null();\n    m_origin     = tOrigin::undefined;\n    m_enStock    = 0_ENERGY_UNITS;\n    m_enCapacity = 0_ENERGY_UNITS;\n    m_strategyId = Strategy::Id::empty;\n    m_stratData.SetMemorySize( 0 );\n    m_genome.InitGenome( );\n};\n\nvoid Individual::Create\n( \n    IND_ID         const id,\n    EVO_GENERATION const genBirth,\n    Strategy::Id   const strategyId\n)\n{\n    m_genome.InitGenome( );\n    m_id         = id;\n    m_genBirth   = genBirth;\n    m_origin     = tOrigin::editor;\n    m_enCapacity = m_stdEnergyCapacity;\n    m_strategyId = strategyId;\n    m_stratData.SetMemorySize( m_genome.GetAllele(GeneType::Id::memSize) );  \/\/ clears memory. Experience not inheritable.\n    SetEnergy( m_initialEnergy ); \/\/ makes IsAlive() true. Last assignment to avoid race conditions  \n}\n\n\/\/ Clone - creates a mutated clone of this individual\n\/\/         all member variables of new individual are initialized after this function\n\nvoid Individual::Clone\n(\n    IND_ID         const   id,\n    EVO_GENERATION const   genBirth,\n    PERCENT        const   mutationRate,\n    Random               & random,\n    Individual     const & indParent\n)\n{\n    m_id         = id;\n    m_genBirth   = genBirth;\n    m_origin     = tOrigin::cloning;\n    m_enCapacity = indParent.m_enCapacity;\n    m_strategyId = indParent.m_strategyId;\n    m_genome.Mutate( mutationRate, random );\n    m_stratData.SetMemorySize( m_genome.GetAllele(GeneType::Id::memSize) );  \/\/ clears memory. Experience not inheritable.\n}\n\nstatic Individual const & selectParent\n(\n    Random           & random,\n    Individual const & indParA,\n    Individual const & indParB\n)\n{\n    return random.NextBooleanValue( ) ? indParA : indParB;\n}\n\n\/\/ Breed - creates a child with a mix of genes of both parents\n\/\/         all member variables of new individual are initialized after this function\n\nvoid Individual::Breed\n(\n    IND_ID         const   id,\n    EVO_GENERATION const   genBirth,\n    PERCENT        const   mutationRate,\n    Random               & random,\n    Individual     const & indParentA,\n    Individual     const & indParentB\n)\n{\n    m_id         = id;\n    m_genBirth   = genBirth;\n    m_origin     = tOrigin::marriage;\n    m_enCapacity = selectParent( random, indParentA, indParentB ).m_enCapacity;\n    m_strategyId = selectParent( random, indParentA, indParentB ).m_strategyId;\n    m_genome.Recombine( indParentA.m_genome, indParentB.m_genome, random );\n    m_genome.Mutate( mutationRate, random );\n    m_stratData.SetMemorySize( m_genome.GetAllele(GeneType::Id::memSize) );  \/\/ clears memory. Experience not inheritable.\n}\n","avg_line_length":29.3583333333,"max_line_length":122,"alphanum_fraction":0.6832245246,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6266,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":1.0,"content":"\/\/ Advent of Code 2018\n\/\/ Day 23: Experimental Emergency Teleportation\n\/\/ #include <bits\/stdc++.h>\n\/\/ #include <array>\n\/\/ #include <bitset>\n\/\/ #include <cassert>\n\/\/ #include <deque>\n\/\/ #include <list>\n\/\/ #include <map>\n\/\/ #include <numeric>\n\/\/ #include <regex>\n\/\/ #include <sstream>\n\/\/ #include <string>\n\/\/ #include <unordered_map>\n\/\/ #include <unordered_set>\n#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <iostream>\n#include <set>\n#include <vector>\nusing namespace std;\n\n\/\/ nanobot: location (x,y,z) and signal radius (r)\nstruct Bot {\n    int64_t x, y, z, r{0};\n\n    \/\/ for set comparisons\n    bool operator<(const Bot &rhs) const {\n        \/\/ return r > rhs.r;\n        if (x < rhs.x)\n            return true;\n        else if (x > rhs.x)\n            return false;\n        if (y < rhs.y)\n            return true;\n        else if (y > rhs.y)\n            return false;\n        if (z < rhs.z)\n            return true;\n        else\n            return z < rhs.z;\n    }\n\n    \/\/ for set comparisons\n    \/\/ bool operator==(const Bot &p) const {\n    \/\/     return x == p.x && y == p.y && z == p.z;\n    \/\/ }\n};\n\n\/\/ same thing, really\ntypedef Bot Point;\n\n\/\/ output a bot\nostream &operator<<(ostream &os, const Bot &b) {\n    os << b.x << \",\" << b.y << \",\" << b.z << \",\" << b.r;\n    return os;\n}\n\n\/\/ parse the input bots\nistream &operator>>(istream &is, vector<Bot> &bots) {\n    int64_t x, y, z, r;\n    while (scanf(\"pos=<%ld,%ld,%ld>, r=%ld\\n\", &x, &y, &z, &r) == 4)\n        bots.push_back({x, y, z, r});\n    return is;\n}\n\n\/\/ manhattan distance\nint64_t mhDist(const Point &a, const Point &b) {\n    return abs(a.x - b.x) + abs(a.y - b.y) + abs(a.z - b.z);\n}\n\n\/\/ is a bot\/point within range of another bot's signal radius?\nbool inRange(const Bot &bot, const Point &point, const int64_t &buffer) {\n    return (mhDist(bot, point) <= bot.r + buffer);\n}\n\n\/\/  Progressive refinement, as seen in other solutions.\n\/\/  Not guaranteed to always work.\nvoid solve() {\n    vector<Bot> bots;\n    cin >> bots;\n\n    \/\/ part 1\n    \/\/ find the bot with the strongest signal radius\n    sort(bots.begin(), bots.end(), \/\/ sort by greater signal strength radius\n         [](const Bot &lhs, const Bot &rhs) { return lhs.r > rhs.r; });\n\n    \/\/ count how many bots are within the strongest bot's signal radius\n    Bot strongestBot = bots[0];\n    int64_t numBotsInRange = \/\/ part 1 memo\n        count_if(bots.begin(), bots.end(),\n                 [&](const Bot &bot) { return inRange(strongestBot, bot, 0); });\n\n    \/\/ part 2\n    \/\/ first find the points that are in range of the largest number of bots\n    \/\/ compute the bounding box of the bot's locations + signal radii\n    int64_t x_min{0}, y_min{0}, z_min{0}, x_max{0}, y_max{0}, z_max{0};\n    for (auto &b : bots) {\n        x_min = min(x_min, b.x - b.r), x_max = max(x_max, b.x + b.r + 1);\n        y_min = min(y_min, b.y - b.r), y_max = max(y_max, b.y + b.r + 1);\n        z_min = min(z_min, b.z - b.r), z_max = max(z_max, b.z + b.r + 1);\n    }\n\n    \/\/ range is the bbox size, is a power of 2, and is halved each iteration\n    int64_t x_size{x_max - x_min}, y_size{y_max - y_min}, z_size{z_max - z_min};\n    int64_t range{int64_t(2) << int(log2(x_size + y_size + z_size))}; \/\/ perim\n\n    \/\/ starting points: 8 corners of the bbox\n    set<Point> tryPoints, bestPoints;\n    for (int64_t dx = 0; dx <= 1; ++dx)\n        for (int64_t dy = 0; dy <= 1; ++dy)\n            for (int64_t dz = 0; dz <= 1; ++dz) {\n                tryPoints.insert({x_min + (dx * range), y_min + (dy * range),\n                                  z_min + (dz * range), 0});\n            }\n\n    \/\/ progressively refine the best points as the range is halved to 0\n    while (1) {\n        int64_t bestCount{0};\n        for (auto &point : tryPoints) {\n            int64_t numBotsInRange =\n                count_if(bots.begin(), bots.end(), [&](const Bot &bot) {\n                    return inRange(bot, point, range);\n                });\n\n            \/\/ keep the best points: most bots in range of it\n            if (numBotsInRange >= bestCount) {\n                if (numBotsInRange > bestCount) {\n                    bestCount = numBotsInRange;\n                    bestPoints.clear();\n                }\n                bestPoints.insert(point);\n            }\n        }\n\n        \/\/ range is 0, done!\n        if (!range)\n            break;\n\n        \/\/ setup next halving iteration\n        range >>= 1;\n        tryPoints.clear();\n        if (!range) \/\/ last iteration\n            swap(tryPoints, bestPoints);\n        else {\n            for (auto &point : bestPoints) {\n                for (int64_t dx = -range; dx <= range; dx += range)\n                    for (int64_t dy = -range; dy <= range; dy += range)\n                        for (int64_t dz = -range; dz <= range; dz += range)\n                            tryPoints.insert(\n                                {point.x + dx, point.y + dy, point.z + dz});\n            }\n        }\n    }\n\n    \/\/ finally, find the closest point to the origin in the best point set\n    \/\/ int64_t closestToOrigin{numeric_limits<int64_t>::max()}; \/\/ part2 memo\n    int64_t closestToOrigin{INT64_MAX}; \/\/ part2 memo\n    for (auto &point : bestPoints)\n        closestToOrigin = min(closestToOrigin, mhDist(point, {0, 0, 0}));\n\n    \/\/ Part 1: Find the nanobot with the largest signal radius. How many\n    \/\/ nanobots are in range of its signals?\n    cout << \"[Part 01] = \" << numBotsInRange << endl; \/\/ 408\n\n    \/\/ Part 2: Find the coordinates that are in range of the largest number of\n    \/\/ nanobots. What is the shortest manhattan distance between any of those\n    \/\/ points and (0,0,0)?\n    cout << \"[Part 02] = \" << closestToOrigin << endl; \/\/ 121167568\n}\n\n\/\/ Main: Time the solver.\nint main() {\n    \/\/ Speed up C++ io by unsyncing with C stdio and untie cin\/cout.\n    ios_base::sync_with_stdio(false);\n    std::cin.tie(0);\n    \/\/ Time the solve() function in milliseconds.\n    auto start_time = std::chrono::high_resolution_clock::now();\n    solve();\n    auto end_time = std::chrono::high_resolution_clock::now();\n    auto ms_count = std::chrono::duration_cast<std::chrono::milliseconds>(\n                        end_time - start_time)\n                        .count();\n    std::clog << \"[Runtime] = \" << ms_count << \"ms\" << std::endl;\n}","avg_line_length":33.688172043,"max_line_length":80,"alphanum_fraction":0.5520268114,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7290,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/  By downloading, copying, installing or using the software you agree to this license.\n\/\/  If you do not agree to this license, do not download, install,\n\/\/  copy or use the software.\n\/\/\n\/\/\n\/\/                        Intel License Agreement\n\/\/                For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2000, Intel Corporation, all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/   * Redistribution's of source code must retain the above copyright notice,\n\/\/     this list of conditions and the following disclaimer.\n\/\/\n\/\/   * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/     this list of conditions and the following disclaimer in the documentation\n\/\/     and\/or other materials provided with the distribution.\n\/\/\n\/\/   * The name of Intel Corporation may not be used to endorse or promote products\n\/\/     derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#include  \"stdafx.h\"\n#include  <stdio.h>\n#include  <stdlib.h>\n#include  <ctype.h>\n#include  <string.h>\n\n#include  \"lexer.h\"\n\ntypedef struct _HashEntry\n{\n    unsigned  hash;\n    int       len;\n    struct _HashEntry* next;\n    const char* str;\n}\nHashEntry;\n\nHashEntry   keyword_storage[100];\n\n#define  HASHTABLE_SIZE   17\nHashEntry*  keyword_table[HASHTABLE_SIZE];\nstatic int  hash_init = 0;\n\nconst char* keywords[] = \n{\n    \"break\",    \"case\",     \"char\",     \"const\",\n    \"continue\", \"default\",  \"do\",       \"double\",\n    \"else\",     \"enum\",     \"extern\",   \"float\",\n    \"for\",      \"goto\",     \"if\",       \"int\",\n    \"long\",     \"register\", \"return\",   \"short\",\n    \"signed\",   \"sizeof\",   \"static\",   \"struct\",\n    \"switch\",   \"typedef\",  \"union\",    \"unsigned\",\n    \"void\",     \"volatile\", \"while\",    0\n};\n\n\ninline unsigned  calc_hash( const char* text, int len )\n{\n    int j, shift = 0;\n    unsigned hash = len;\n    for( j = 0; j < len; j++ )\n    {\n        shift += 11;\n        if( shift >= 32 ) shift -= 32;\n        hash ^= ((unsigned char*)text)[j] << shift;\n    }\n    return hash;\n}\n\n\nvoid InitLexer( Lexer* lexer, const char* text )\n{\n    lexer->text = text;\n    lexer->pos = 0;\n\n    if( !hash_init )\n    {\n        int  i;\n        int  count[HASHTABLE_SIZE];\n        memset( count, 0, sizeof(count));\n        memset( keyword_table, 0, sizeof( keyword_table));\n\n        for( i = 0; keywords[i] != 0; i++ )\n        {\n            int idx, len;\n            keyword_storage[i].len = len = strlen( keywords[i] );\n            keyword_storage[i].hash = calc_hash( keywords[i], len );\n            keyword_storage[i].str = keywords[i];\n            idx = keyword_storage[i].hash % HASHTABLE_SIZE; \n            keyword_storage[i].next = keyword_table[idx];\n            keyword_table[idx] = keyword_storage + i;\n            count[idx]++;\n        }\n        hash_init = 1;\n    }\n}\n\n\nHashEntry* find_text( const char* str, int len )\n{\n    unsigned hash = calc_hash( str, len );\n    int idx = hash % HASHTABLE_SIZE;\n    HashEntry* entry = keyword_table[idx];\n\n    while( entry )\n    {\n        if( entry->hash == hash &&\n            entry->len == len &&\n            !strncmp( entry->str, str, len )) break;\n        entry = entry->next;\n    }\n    return entry;\n}\n\n\nvoid  GetToken( Lexer* lexer, Token* token )\n{\n    const char* text = lexer->text;\n    int pos = lexer->pos;\n    token->type = TOKEN_NORMAL;\n\n    while( isspace(text[pos])) pos++;\n    token->start = pos;\n\n    switch( text[pos] )\n    {\n    case '\/': pos++;\n              switch( text[pos] )\n              {\n              case '\/': \/* end-line comment *\/\n                  token->type = TOKEN_COMMENT;\n                  ++pos; while( text[pos] != '\\n' && text[pos] != '\\0' ) pos++;\n                  break;\n              case '*':\n                  token->type = TOKEN_COMMENT;\n                  ++pos;\n                  while( text[pos] != '\\0' )\n                  {\n                      if( text[pos] == '*' && text[pos+1] == '\/')\n                      {\n                          pos += 2;\n                          break;\n                      }\n                      pos++;\n                  }\n                  break;\n              }\n              break;\n    case '\\0':  token->type = TOKEN_END;\n                return; \n\n    case '\\\"':  token->type = TOKEN_STRING;\n                pos++;\n                for(;;)\n                {\n                    if( text[pos] == '\\0' || text[pos] == '\\\"' || text[pos] == '\\n' )\n                        break;\n                    if( text[pos] == '\\\\' )\n                    {\n                        pos += 2;\n                        if( text[pos] == '\\n' ) pos++;\n                    }\n                    else\n                    {\n                        pos++;\n                    }\n                }\n                if( text[pos] == '\\\"') pos++;\n                break;\n\n    case '\\'':  token->type = TOKEN_STRING;\n                pos++;\n                for(;;)\n                {\n                    if( text[pos] == '\\0' || text[pos] == '\\'' || text[pos] == '\\n' )\n                        break;\n                    pos += text[pos] == '\\\\' ? 2 : 1;\n                }\n                if( text[pos] == '\\'') pos++;\n                break;\n    default:\n        if( isalpha( text[pos] ) || text[pos] == '_' )\n        {\n            pos++;\n            while( isalnum( text[pos] ) || text[pos] == '_' ) pos++;\n\n            if( find_text( text + token->start, pos - token->start ))\n            {\n                token->type = TOKEN_KEYWORD;\n            }\n        }\n        else if( isdigit(text[pos]) || (text[pos] == '.' && isdigit(text[pos+1])))\n        {\n            int pos1 = pos;\n            token->type = TOKEN_NUMBER;\n            pos++; while( isalnum( text[pos])) pos++;\n            if( (text[pos] == '+' || text[pos] == '-') && text[pos-1] == 'e')\n            {\n                while( isdigit(text[pos1]) || text[pos1] == '.') pos1++;\n                if( pos1 == pos - 1 )\n                {\n                    pos++;\n                    while( isdigit(text[pos])) pos++;\n                }\n            }\n        }\n        else \n        {\n            pos++;\n        }\n    }\n\n    lexer->pos = pos;\n}\n","avg_line_length":30.8898305085,"max_line_length":90,"alphanum_fraction":0.4873799726,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":9249,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"#include \"electionguard\/hash.hpp\"\n\n#include \"..\/kremlin\/Hacl_Bignum256.h\"\n#include \"..\/kremlin\/Hacl_Streaming_SHA2.h\"\n#include \"log.hpp\"\n\n#include <iomanip>\n#include <iostream>\n\nusing std::get;\nusing std::make_unique;\nusing std::nullptr_t;\nusing std::out_of_range;\nusing std::reference_wrapper;\nusing std::string;\nusing std::to_string;\nusing std::unique_ptr;\nusing std::vector;\n\nnamespace electionguard\n{\n    template <typename T> string hash_inner_vector(vector<T> inner_vector);\n    void push_hash_update(Hacl_Streaming_SHA2_state_sha2_224 *p, CryptoHashableType a);\n\n    const char delimiter_char = '|';\n    const string null_string = \"null\";\n\n    uint8_t delimiter[1] = {delimiter_char};\n\n    unique_ptr<ElementModQ> hash_elems(const vector<CryptoHashableType> &a)\n    {\n        uint8_t output[MAX_Q_SIZE] = {};\n        Hacl_Streaming_SHA2_state_sha2_224 *p = Hacl_Streaming_SHA2_create_in_256();\n        Hacl_Streaming_SHA2_update_256(p, static_cast<uint8_t *>(delimiter), sizeof(delimiter));\n\n        if (a.empty()) {\n            push_hash_update(p, null_string);\n        } else {\n            for (const CryptoHashableType &item : a) {\n                push_hash_update(p, item);\n            }\n        }\n\n        Hacl_Streaming_SHA2_finish_256(p, static_cast<uint8_t *>(output));\n\n        auto *bigNum =\n          Hacl_Bignum256_new_bn_from_bytes_be(sizeof(output), static_cast<uint8_t *>(output));\n        if (bigNum == nullptr) {\n            throw out_of_range(\"bytes_to_p could not allocate\");\n        }\n\n        \/\/ The ElementModQ constructor expects the bignum\n        \/\/ to be a certain size, but there's no guarantee\n        \/\/ that constraint is satisfied by new_bn_from_bytes_be\n        \/\/ so copy it into a new element that is the correct size\n        \/\/ and free the allocated resources\n        uint64_t element[MAX_Q_LEN] = {};\n        memcpy(static_cast<uint64_t *>(element), bigNum, sizeof(output));\n        Hacl_Streaming_SHA2_free_256(p);\n        free(bigNum);\n\n        \/\/ TODO: take the result mod Q - 1\n        \/\/ to produce a result that is [0,q-1]\n        return make_unique<ElementModQ>(element);\n    }\n\n    unique_ptr<ElementModQ> hash_elems(CryptoHashableType a)\n    {\n        return hash_elems(vector<CryptoHashableType>{move(a)});\n    }\n\n    template <typename T> string hash_inner_vector(vector<T> inner_vector)\n    {\n        vector<CryptoHashableType> hashable_vector(inner_vector.begin(), inner_vector.end());\n        return hash_elems(hashable_vector)->toHex();\n    }\n\n    enum CryptoHashableTypeEnum {\n        NULL_PTR = 0,\n        CRYPTOHASHABLE_PTR = 1,\n        ELEMENTMODP_PTR = 2,\n        ELEMENTMODQ_PTR = 3,\n        CRYPTOHASHABLE_REF = 4,\n        ELEMENTMODP_REF = 5,\n        ELEMENTMODQ_REF = 6,\n        CRYPTOHASHABLE_CONST_REF = 7,\n        ELEMENTMODP_CONST_REF = 8,\n        ELEMENTMODQ_CONST_REF = 9,\n        UINT64_T = 10,\n        STRING = 11,\n        VECTOR_CRYPTOHASHABLE_PTR = 12,\n        VECTOR_ELEMENTMODP_PTR = 13,\n        VECTOR_ELEMENTMODQ_PTR = 14,\n        VECTOR_CRYPTOHASHABLE_REF = 15,\n        VECTOR_ELEMENTMODP_REF = 16,\n        VECTOR_ELEMENTMODQ_REF = 17,\n        VECTOR_CRYPTOHASHABLE_CONST_REF = 18,\n        VECTOR_ELEMENTMODP_CONST_REF = 19,\n        VECTOR_ELEMENTMODQ_CONST_REF = 20,\n        VECTOR_UINT64_T = 21,\n        VECTOR_STRING = 22\n    };\n\n    void push_hash_update(Hacl_Streaming_SHA2_state_sha2_224 *p, CryptoHashableType a)\n    {\n        string input_string;\n        switch (a.index()) {\n            case NULL_PTR: \/\/ nullptr_t\n            {\n                input_string = null_string;\n                break;\n            }\n            case CRYPTOHASHABLE_PTR: \/\/ CryptoHashable *\n            {\n                auto hashable = get<CryptoHashable *>(a)->crypto_hash();\n                input_string = hashable->toHex();\n                break;\n            }\n            case ELEMENTMODP_PTR: \/\/ ElementModP *\n            {\n                input_string = get<ElementModP *>(a)->toHex();\n                break;\n            }\n            case ELEMENTMODQ_PTR: \/\/ ElementModQ *\n            {\n                input_string = get<ElementModQ *>(a)->toHex();\n                break;\n            }\n            case CRYPTOHASHABLE_REF: \/\/ reference_wrapper<CryptoHashable>\n            {\n                auto hashable = get<reference_wrapper<CryptoHashable>>(a).get().crypto_hash();\n                input_string = hashable->toHex();\n                \/\/Log::debug(\"input string: \" + input_string);\n                break;\n            }\n            case ELEMENTMODP_REF: \/\/ reference_wrapper<ElementModP>\n            {\n                input_string = get<reference_wrapper<ElementModP>>(a).get().toHex();\n                break;\n            }\n            case ELEMENTMODQ_REF: \/\/ reference_wrapper<ElementModQ>\n            {\n                input_string = get<reference_wrapper<ElementModQ>>(a).get().toHex();\n                break;\n            }\n            case CRYPTOHASHABLE_CONST_REF: \/\/ reference_wrapper<const CryptoHashable>\n            {\n                auto hashable = get<reference_wrapper<const CryptoHashable>>(a).get().crypto_hash();\n                input_string = hashable->toHex();\n                break;\n            }\n            case ELEMENTMODP_CONST_REF: \/\/ reference_wrapper<const ElementModP>\n            {\n                input_string = get<reference_wrapper<const ElementModP>>(a).get().toHex();\n                break;\n            }\n            case ELEMENTMODQ_CONST_REF: \/\/ reference_wrapper<const ElementModQ>\n            {\n                input_string = get<reference_wrapper<const ElementModQ>>(a).get().toHex();\n                break;\n            }\n            case UINT64_T: \/\/ uint64_t\n            {\n                uint64_t i = get<uint64_t>(a);\n                if (i != 0) {\n                    input_string = to_string(i);\n                }\n                break;\n            }\n            case STRING: \/\/ string\n            {\n                input_string = get<string>(a);\n                break;\n            }\n            case VECTOR_CRYPTOHASHABLE_PTR: \/\/ vector<CryptoHashable *>\n            {\n                input_string =\n                  hash_inner_vector<CryptoHashable *>(get<vector<CryptoHashable *>>(a));\n                break;\n            }\n            case VECTOR_ELEMENTMODP_PTR: \/\/ vector<ElementModP *>\n            {\n                input_string = hash_inner_vector<ElementModP *>(get<vector<ElementModP *>>(a));\n                break;\n            }\n            case VECTOR_ELEMENTMODQ_PTR: \/\/ vector<ElementModQ *>\n            {\n                input_string = hash_inner_vector<ElementModQ *>(get<vector<ElementModQ *>>(a));\n                break;\n            }\n            case VECTOR_CRYPTOHASHABLE_REF: \/\/ vector<reference_wrapper<CryptoHashable>>\n            {\n                input_string = hash_inner_vector<reference_wrapper<CryptoHashable>>(\n                  get<vector<reference_wrapper<CryptoHashable>>>(a));\n                break;\n            }\n            case VECTOR_ELEMENTMODP_REF: \/\/ vector<reference_wrapper<ElementModP>>\n            {\n                input_string = hash_inner_vector<reference_wrapper<ElementModP>>(\n                  get<vector<reference_wrapper<ElementModP>>>(a));\n                break;\n            }\n            case VECTOR_ELEMENTMODQ_REF: \/\/ vector<reference_wrapper<ElementModQ>>\n            {\n                input_string = hash_inner_vector<reference_wrapper<ElementModQ>>(\n                  get<vector<reference_wrapper<ElementModQ>>>(a));\n                break;\n            }\n            case VECTOR_CRYPTOHASHABLE_CONST_REF: \/\/ vector<reference_wrapper<const CryptoHashable>>\n            {\n                input_string = hash_inner_vector<reference_wrapper<const CryptoHashable>>(\n                  get<vector<reference_wrapper<const CryptoHashable>>>(a));\n                break;\n            }\n            case VECTOR_ELEMENTMODP_CONST_REF: \/\/ vector<reference_wrapper<const ElementModP>>\n            {\n                input_string = hash_inner_vector<reference_wrapper<const ElementModP>>(\n                  get<vector<reference_wrapper<const ElementModP>>>(a));\n                break;\n            }\n            case VECTOR_ELEMENTMODQ_CONST_REF: \/\/ vector<reference_wrapper<const ElementModQ>>\n            {\n                input_string = hash_inner_vector<reference_wrapper<const ElementModQ>>(\n                  get<vector<reference_wrapper<const ElementModQ>>>(a));\n                break;\n            }\n            case VECTOR_UINT64_T: \/\/ vector<uint64_t>\n            {\n                input_string = hash_inner_vector<uint64_t>(get<vector<uint64_t>>(a));\n                break;\n            }\n            case VECTOR_STRING: \/\/ vector<string>\n            {\n                input_string = hash_inner_vector<string>(get<vector<string>>(a));\n                break;\n            }\n        }\n\n        if (input_string.empty()) {\n            input_string = null_string;\n        }\n\n        const auto *input = reinterpret_cast<const uint8_t *>(input_string.c_str());\n        Hacl_Streaming_SHA2_update_256(p, const_cast<uint8_t *>(input), input_string.size());\n        Hacl_Streaming_SHA2_update_256(p, static_cast<uint8_t *>(delimiter), sizeof(delimiter));\n    }\n} \/\/ namespace electionguard\n","avg_line_length":37.2943548387,"max_line_length":100,"alphanum_fraction":0.5734674019,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1671,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":315.0,"content":"\/\/ A simple C++ program to find \n\/\/ maximum score that \n\/\/ maximizing player can get. \n#include<bits\/stdc++.h> \nusing namespace std; \n  \n\/\/SOURCE CODE FROM https:\/\/www.geeksforgeeks.org\/minimax-algorithm-in-game-theory-set-1-introduction\/\n\n\n\/\/ Returns the optimal value a maximizer can obtain. \n\/\/ depth is current depth in game tree. \n\/\/ nodeIndex is index of current node in scores[]. \n\/\/ isMax is true if current move is \n\/\/ of maximizer, else false \n\/\/ scores[] stores leaves of Game tree. \n\/\/ h is maximum height of Game tree \nint minimax(int depth, int nodeIndex, bool isMax, \n            int scores[], int h) \n{ \n    \/\/ Terminating condition. i.e \n    \/\/ leaf node is reached \n    if (depth == h) \n        return scores[nodeIndex]; \n  \n    \/\/  If current move is maximizer, \n    \/\/ find the maximum attainable \n    \/\/ value \n    if (isMax) \n       return max(minimax(depth+1, nodeIndex*2, false, scores, h), \n            minimax(depth+1, nodeIndex*2 + 1, false, scores, h)); \n  \n    \/\/ Else (If current move is Minimizer), find the minimum \n    \/\/ attainable value \n    else\n        return min(minimax(depth+1, nodeIndex*2, true, scores, h), \n            minimax(depth+1, nodeIndex*2 + 1, true, scores, h)); \n} \n  \n\/\/ A utility function to find Log n in base 2 \nint log2(int n) \n{ \n  return (n==1)? 0 : 1 + log2(n\/2); \n} \n  \n\/\/ Driver code \nint main() \n{ \n    \/\/ The number of elements in scores must be \n    \/\/ a power of 2. \n    int scores[] = {3, 5, 2, 9, 12, 5, 23, 23}; \n    int n = sizeof(scores)\/sizeof(scores[0]); \n    int h = log2(n); \n    int res = minimax(0, 0, true, scores, h); \n    cout << \"The optimal value is : \" << res << endl; \n    return 0; \n} ","avg_line_length":29.8392857143,"max_line_length":101,"alphanum_fraction":0.6092160383,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4309,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include \"edhclient_socket.h\"\n#include \"edhclient_private.h\"\n\n#include <iostream>\n\n#include <QFile>\n\n#include <QtNetwork\/QTcpSocket>\n#include <QtNetwork\/QSslSocket>\n#include <QtNetwork\/QSslConfiguration>\n\nusing namespace eDrillingHub;\n\nstatic const QString message_end_marker = QString(\"\\r\\n\");\n\nSocketClient::SocketClient(bool secure) {\n    if (secure) {\n        auto socket = new QSslSocket();\n        _socket.reset(socket);\n        _ssl_socket = true;\n    } else {\n        _socket.reset(new QTcpSocket());\n        _ssl_socket = false;\n    }\n\n    connect(_socket.get(), &QTcpSocket::readyRead, this, &SocketClient::_onSocketReadyRead);\n    connect(_socket.get(), &QTcpSocket::stateChanged, this, [this](QAbstractSocket::SocketState state) {\n        switch (state) {\n        case QAbstractSocket::ConnectedState:\n            _socket->setSocketOption(QAbstractSocket::LowDelayOption, 1);\n            if (_ssl_socket) {\n                auto sslsocket = dynamic_cast<QSslSocket*>(_socket.get());\n                QObject::connect(sslsocket, &QSslSocket::encrypted, [=] {\n                    emit connected();\n                });\n                sslsocket->startClientEncryption();\n            } else {\n                emit connected();\n            }\n            break;\n        case QAbstractSocket::UnconnectedState:\n            emit disconnected();\n            break;\n        default:\n            break;\n        }\n    });\n}\n\nSocketClient* SocketClient::create(bool secure) {\n    std::unique_ptr<SocketClient> client;\n\n    client.reset(new SocketClient(secure));\n    if (secure) {\n        QFile ca(\":\/edhclient\/CA-eDrilling.crt\");\n        if (! ca.open(QIODevice::ReadOnly)) {\n            std::cerr << \"eDrilling CA Certificate not found, compilation error\" << std::endl;\n            return nullptr;\n        }\n\n        auto sslsocket = dynamic_cast<QSslSocket*>(client.get()->_socket.get());\n        sslsocket->addCaCertificates(QSslConfiguration::systemCaCertificates());\n        sslsocket->addCaCertificate(QSslCertificate(&ca, QSsl::Pem));\n        sslsocket->setProtocol(QSsl::TlsV1_2OrLater);\n    }\n\n    return client.release();\n}\n\nvoid SocketClient::open() {\n    if (_networkProxy) {\n        _socket->setProxy(*_networkProxy);\n    }\n    _socket->connectToHost(_priv->host, _priv->port, QIODevice::ReadWrite);\n}\n\nvoid SocketClient::close() {\n    _socket->close();\n}\n\nvoid SocketClient::setIgnoreSslErrors(bool enable) {\n    auto ssl_socket = dynamic_cast<QSslSocket*>(_socket.get());\n    if (ssl_socket == nullptr) {\n        return;\n    }\n\n    if (enable) {\n        QObject::connect(ssl_socket, static_cast<void (QSslSocket::*)(const QList<QSslError> &errors)>(&QSslSocket::sslErrors), &SocketClient::_onSslError);\n        QObject::connect(ssl_socket, static_cast<void (QSslSocket::*)(const QList<QSslError> &errors)>(&QSslSocket::sslErrors),\n                         ssl_socket, static_cast<void (QSslSocket::*)(const QList<QSslError> &errors)>(&QSslSocket::ignoreSslErrors));\n    } else {\n        QObject::disconnect(ssl_socket, static_cast<void (QSslSocket::*)(const QList<QSslError> &errors)>(&QSslSocket::sslErrors), nullptr, nullptr);\n    }\n}\n\nQString SocketClient::errorString() {\n    return _socket->errorString();\n}\n\nvoid SocketClient::write(const QString &message) {\n    _socket->write(message.toUtf8());\n    _socket->write(message_end_marker.toUtf8());\n}\n\nvoid SocketClient::writeBinary(const QByteArray &data) {\n    _socket->write(data);\n}\n\nvoid SocketClient::_onSocketReadyRead() {\n    QByteArray bytes = _socket->readAll();\n    _readBuffer.append(bytes);\n\n    _readBufferIdx = 0;\n    _readBufferPos = _readBuffer.indexOf(message_end_marker);\n\n    if (_readBufferPos >= 0) {\n        while (_readBufferPos >= 0) {\n            QString reply = QString::fromUtf8(_readBuffer.mid(_readBufferIdx, _readBufferPos - _readBufferIdx));\n\n            _readBufferIdx = _readBufferPos + message_end_marker.length();\n            _readBufferPos = _readBuffer.indexOf(message_end_marker, _readBufferIdx);\n\n            handle(reply);\n        }\n\n        _readBuffer.remove(0, _readBufferIdx);\n    }\n}\n\nvoid SocketClient::_onSslError(const QList<QSslError> &errors) {\n    for (const auto& error : errors) {\n        std::cerr << \"SocketClient: SSL Error: \" << error.errorString().toStdString() << std::endl;\n    }\n}\n","avg_line_length":31.9185185185,"max_line_length":156,"alphanum_fraction":0.6449292179,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":774,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"..\/global.h\"\n\/**\n * @brief \n * SYNTAX: PRINT relation_name\n *\/\nbool syntacticParsePRINT()\n{\n    logger.log(\"syntacticParsePRINT\");\n    if (tokenizedQuery.size() != 2)\n    {\n        cout << \"SYNTAX ERROR\" << endl;\n        return false;\n    }\n    parsedQuery.queryType = PRINT;\n    parsedQuery.printRelationName = tokenizedQuery[1];\n    return true;\n}\n\nbool semanticParsePRINT()\n{\n    logger.log(\"semanticParsePRINT\");\n    if (!tableCatalogue.isTable(parsedQuery.printRelationName))\n    {\n        cout << \"SEMANTIC ERROR: Relation doesn't exist\" << endl;\n        return false;\n    }\n    return true;\n}\n\nvoid executePRINT()\n{\n    logger.log(\"executePRINT\");\n    Table *table = tableCatalogue.getTable(parsedQuery.printRelationName);\n    table->print();\n    return;\n}\n","avg_line_length":20.9189189189,"max_line_length":74,"alphanum_fraction":0.642118863,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":647,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/*\nPROBLEM LINK: https:\/\/www.hackerrank.com\/challenges\/kangaroo\/problem\n*\/\n\n#include<bits\/stdc++.h>\nusing namespace std;\n\nbool Meet(int x1, int v1, int x2, int v2)\n{\n    if(x1<x2 && v1<=v2)\n        return false;\n    if(x1>x2 && v1>=v2)\n        return false;\n    \n    if(x1 < x2)\n    {\n        swap(x1,x2);\n        swap(v1,v2);\n    }\n    \n    while(x1 >= x2){\n        if(x1 == x2)\n            return true;\n        \n        x1 += v1;\n        x2 += v2;\n    }\n    return false;\n}\n\nint main()\n{\n    int x1, v1, x2, v2;\n    cin >> x1 >> v1 >> x2 >> v2;\n    if (Meet(x1, v1, x2, v2))\n        cout << \"YES\";\n    else\n        cout << \"NO\";\n    return 0;\n}\n","avg_line_length":15.7804878049,"max_line_length":68,"alphanum_fraction":0.4528593509,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3934,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Copyright (c) 2014-2017 The Dash Core developers\n\/\/ Copyright (c) 2019 The NachoCoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"rpc\/protocol.h\"\n\n#include \"random.h\"\n#include \"tinyformat.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n#include \"utiltime.h\"\n#include \"version.h\"\n\n#include <stdint.h>\n#include <fstream>\n\n\/**\n * JSON-RPC protocol.  Bitcoin speaks version 1.0 for maximum compatibility,\n * but uses JSON-RPC 1.1\/2.0 standards for parts of the 1.0 standard that were\n * unspecified (HTTP errors and contents of 'error').\n * \n * 1.0 spec: http:\/\/json-rpc.org\/wiki\/specification\n * 1.2 spec: http:\/\/jsonrpc.org\/historical\/json-rpc-over-http.html\n *\/\n\nUniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params, const UniValue& id)\n{\n    UniValue request(UniValue::VOBJ);\n    request.push_back(Pair(\"method\", strMethod));\n    request.push_back(Pair(\"params\", params));\n    request.push_back(Pair(\"id\", id));\n    return request;\n}\n\nUniValue JSONRPCReplyObj(const UniValue& result, const UniValue& error, const UniValue& id)\n{\n    UniValue reply(UniValue::VOBJ);\n    if (!error.isNull())\n        reply.push_back(Pair(\"result\", NullUniValue));\n    else\n        reply.push_back(Pair(\"result\", result));\n    reply.push_back(Pair(\"error\", error));\n    reply.push_back(Pair(\"id\", id));\n    return reply;\n}\n\nstd::string JSONRPCReply(const UniValue& result, const UniValue& error, const UniValue& id)\n{\n    UniValue reply = JSONRPCReplyObj(result, error, id);\n    return reply.write() + \"\\n\";\n}\n\nUniValue JSONRPCError(int code, const std::string& message)\n{\n    UniValue error(UniValue::VOBJ);\n    error.push_back(Pair(\"code\", code));\n    error.push_back(Pair(\"message\", message));\n    return error;\n}\n\n\/** Username used when cookie authentication is in use (arbitrary, only for\n * recognizability in debugging\/logging purposes)\n *\/\nstatic const std::string COOKIEAUTH_USER = \"__cookie__\";\n\/** Default name for auth cookie file *\/\nstatic const std::string COOKIEAUTH_FILE = \".cookie\";\n\nboost::filesystem::path GetAuthCookieFile()\n{\n    boost::filesystem::path path(GetArg(\"-rpccookiefile\", COOKIEAUTH_FILE));\n    if (!path.is_complete()) path = GetDataDir() \/ path;\n    return path;\n}\n\nbool GenerateAuthCookie(std::string *cookie_out)\n{\n    const size_t COOKIE_SIZE = 32;\n    unsigned char rand_pwd[COOKIE_SIZE];\n    GetRandBytes(rand_pwd, COOKIE_SIZE);\n\n    std::string cookie = COOKIEAUTH_USER + \":\" + HexStr(rand_pwd, rand_pwd+COOKIE_SIZE);\n\n    \/** the umask determines what permissions are used to create this file -\n     * these are set to 077 in init.cpp unless overridden with -sysperms.\n     *\/\n    std::ofstream file;\n    boost::filesystem::path filepath = GetAuthCookieFile();\n    file.open(filepath.string().c_str());\n    if (!file.is_open()) {\n        LogPrintf(\"Unable to open cookie authentication file %s for writing\\n\", filepath.string());\n        return false;\n    }\n    file << cookie;\n    file.close();\n    LogPrintf(\"Generated RPC authentication cookie %s\\n\", filepath.string());\n\n    if (cookie_out)\n        *cookie_out = cookie;\n    return true;\n}\n\nbool GetAuthCookie(std::string *cookie_out)\n{\n    std::ifstream file;\n    std::string cookie;\n    boost::filesystem::path filepath = GetAuthCookieFile();\n    file.open(filepath.string().c_str());\n    if (!file.is_open())\n        return false;\n    std::getline(file, cookie);\n    file.close();\n\n    if (cookie_out)\n        *cookie_out = cookie;\n    return true;\n}\n\nvoid DeleteAuthCookie()\n{\n    try {\n        boost::filesystem::remove(GetAuthCookieFile());\n    } catch (const boost::filesystem::filesystem_error& e) {\n        LogPrintf(\"%s: Unable to remove random auth cookie file: %s\\n\", __func__, e.what());\n    }\n}\n\n","avg_line_length":30.2615384615,"max_line_length":100,"alphanum_fraction":0.6898830707,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2881,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/\/===-- CommandObjectScript.cpp ---------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"CommandObjectScript.h\"\n\n\n#include \"lldb\/Core\/Debugger.h\"\n\n#include \"lldb\/DataFormatters\/DataVisualization.h\"\n\n#include \"lldb\/Interpreter\/CommandInterpreter.h\"\n#include \"lldb\/Interpreter\/CommandReturnObject.h\"\n#include \"lldb\/Interpreter\/ScriptInterpreter.h\"\n#include \"lldb\/Utility\/Args.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\n\/\/-------------------------------------------------------------------------\n\/\/ CommandObjectScript\n\/\/-------------------------------------------------------------------------\n\nCommandObjectScript::CommandObjectScript(CommandInterpreter &interpreter,\n                                         ScriptLanguage script_lang)\n    : CommandObjectRaw(\n          interpreter, \"script\",\n          \"Invoke the script interpreter with provided code and display any \"\n          \"results.  Start the interactive interpreter if no code is supplied.\",\n          \"script [<script-code>]\") {}\n\nCommandObjectScript::~CommandObjectScript() {}\n\nbool CommandObjectScript::DoExecute(llvm::StringRef command,\n                                    CommandReturnObject &result) {\n#ifdef LLDB_DISABLE_PYTHON\n  \/\/ if we ever support languages other than Python this simple #ifdef won't\n  \/\/ work\n  result.AppendError(\"your copy of LLDB does not support scripting.\");\n  result.SetStatus(eReturnStatusFailed);\n  return false;\n#else\n  if (m_interpreter.GetDebugger().GetScriptLanguage() ==\n      lldb::eScriptLanguageNone) {\n    result.AppendError(\n        \"the script-lang setting is set to none - scripting not available\");\n    result.SetStatus(eReturnStatusFailed);\n    return false;\n  }\n\n  ScriptInterpreter *script_interpreter = GetDebugger().GetScriptInterpreter();\n\n  if (script_interpreter == nullptr) {\n    result.AppendError(\"no script interpreter\");\n    result.SetStatus(eReturnStatusFailed);\n    return false;\n  }\n\n  DataVisualization::ForceUpdate(); \/\/ script might change Python code we use\n                                    \/\/ for formatting.. make sure we keep up to\n                                    \/\/ date with it\n\n  if (command.empty()) {\n    script_interpreter->ExecuteInterpreterLoop();\n    result.SetStatus(eReturnStatusSuccessFinishNoResult);\n    return result.Succeeded();\n  }\n\n  \/\/ We can do better when reporting the status of one-liner script execution.\n  if (script_interpreter->ExecuteOneLine(command, &result))\n    result.SetStatus(eReturnStatusSuccessFinishNoResult);\n  else\n    result.SetStatus(eReturnStatusFailed);\n\n  return result.Succeeded();\n#endif\n}\n","avg_line_length":35.1341463415,"max_line_length":80,"alphanum_fraction":0.6365845193,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":957,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":4.0,"content":"\/*\n * NoteFrequencyTable.cpp\n *\n *  Created on: Jul 13, 2019\n *      Author: vqtrong\n *\/\n\n#include <math.h>\n#include \"AudioGeneration\/NoteFrequencyTable.h\"\n\n\n\/\/ For more info about the following values please see https:\/\/en.wikipedia.org\/wiki\/MIDI_tuning_standard\nfloat twoToTheOne12th_ = 1.059463094f;\nfloat a440Hz_ = 440.0;\nint a440Index_ = 57;\n\n\/\/ See MIDI standard, it seems to be generally agreed that MIDI notes range in index from \n\/\/ 0-to-127 with middle C at 60.\nconst int indexCount = 128;\n\nfloat noteFrequency = 0.0;\nfloat noteFrequencyTable_[indexCount];\n\nvoid initializeNoteFrequencyTable()\n{\n    volatile uint16_t i = 0;\n\n    for (i = 0; i < indexCount; ++i)\n    {\n        noteFrequencyTable_[i] = a440Hz_\n                * powf(twoToTheOne12th_, static_cast<float>(i - a440Index_));\n    }\n}\n\nfloat getFrequency(uint8_t noteIndex)\n{\n    if (noteIndex > indexCount)\n    {\n        return 0.0;\n    }\n\n    return noteFrequencyTable_[noteIndex];\n}\n","avg_line_length":21.75,"max_line_length":105,"alphanum_fraction":0.6865203762,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1123,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":34.0,"content":"\/*\n * Copyright (c) 2000-2001,2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved.\n * \n * @APPLE_LICENSE_HEADER_START@\n * \n * This file contains Original Code and\/or Modifications of Original Code\n * as defined in and that are subject to the Apple Public Source License\n * Version 2.0 (the 'License'). You may not use this file except in\n * compliance with the License. Please obtain a copy of the License at\n * http:\/\/www.opensource.apple.com\/apsl\/ and read it before using this\n * file.\n * \n * The Original Code and all software distributed under the License are\n * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER\n * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,\n * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.\n * Please see the License for the specific language governing rights and\n * limitations under the License.\n * \n * @APPLE_LICENSE_HEADER_END@\n *\/\n\n\n\/\/\n\/\/ cssmwalkers - walkers for standard CSSM datatypes and wrappers\n\/\/\n#include <security_cdsa_utilities\/cssmwalkers.h>\n","avg_line_length":38.724137931,"max_line_length":83,"alphanum_fraction":0.7586821015,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2014,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\n#include \"reflection\/caster.h\"\n#include \"reflection\/declare_types.h\"\n\nnamespace reflect {\n\nnamespace CastType {\n\nstd::string to_string(type t) {\n    switch (t) {\n        case DYNAMIC:\n            return \"DYNAMIC\";\n        case REINTERPRET:\n            return \"REINTERPRET\";\n        case STATIC:\n            return \"STATIC\";\n        case CONST:\n            return \"CONST\";\n        case C:\n            return \"C\";\n    }\n    return \"\";\n}\n\n}\n\nVariant TypeCaster::cast(Variant& variant, CastType::type type) {\n    \n    CastFuncRef func = nullptr;\n    switch (type) {\n        case CastType::DYNAMIC:\n            func = dynamic_ptr;\n            break;\n        case CastType::CONST:\n            func = const_ptr;\n            break;\n        case CastType::STATIC:\n            func = static_ptr;\n            break;\n        case CastType::REINTERPRET:\n            func = reinterpret_ptr;\n            break;\n        case CastType::C:\n            func = c_ptr;\n            break;\n    }\n    \n    Variant result = func(variant);\n    \n    if (result.get_type() == Type::from<void>()) {\n        throw invalid_cast(\n            \"Cast type '\" + CastType::to_string(type) +\n            \"' from type '\" + from_type->get_name() +\n            \"' to type '\" + to_type->get_name() +\n            \"' is not supported\"\n        );\n    }\n    \n    return result;\n}\n\nType* TypeCaster::get_from_type() {\n    return from_type;\n}\n\nType* TypeCaster::get_to_type() {\n    return to_type;\n}\n\nVariant Caster::add_pointer(Variant variant) {\n    return add_ptr(variant);\n}\n\nVariant Caster::remove_pointer(Variant variant) {\n    return remove_ptr(variant);\n}\n\nVariant Caster::cast(Type* type, Variant variant, CastType::type cast) {\n    if (registered_casts.count(type) == 0) {\n        throw invalid_type(\"Type '\" + type->get_name() + \"' is not registered for casting, use AT_DECLARE_TYPE_CAST()\");\n    }\n    TypeCaster* type_caster = registered_casts[type];\n    return type_caster->cast(variant, cast);\n}\n\nType* Caster::get_type() {\n    return type;\n}\n\n}\n","avg_line_length":22.1318681319,"max_line_length":120,"alphanum_fraction":0.5655412115,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2397,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include \"Cursor.h\"\n#include \"HealthBar.h\"\n#include \"SpecialBar.h\"\n#include \"UserInterfaceManager.h\"\n#include \"GameObjectRegistryLocator.h\"\n#include \"GameObjectRegistryService.h\"\n#include \"GraphicAssetResources.h\"\n#include \"GraphicObject.h\"\n\nusing std::shared_ptr;\n\nUserInterfaceManager::UserInterfaceManager() :\n_waveTitlePosition(Vector2(SCREEN_WIDTH \/ 2, (SCREEN_HEIGHT \/ 2) - 300)), _centerScreenPosition(Vector2(SCREEN_WIDTH \/ 2, (SCREEN_HEIGHT \/ 2)))\n{\n\t\/\/Create Player specific elements and add them to the scene\n\tstatic const auto cursor = std::make_shared<Cursor>();\n\tGameObjectRegistryLocator::GetCreatorService()->AddGameObjectToScene(cursor);\n\n\tstatic const auto hBar = std::make_shared<HealthBar>(Vector2(15, SCREEN_HEIGHT - 150));\n\tGameObjectRegistryLocator::GetCreatorService()->AddGameObjectToScene(hBar);\n\n\tstatic const auto sBar = std::make_shared<SpecialBar>(Vector2(90, SCREEN_HEIGHT - 132));\n\tGameObjectRegistryLocator::GetCreatorService()->AddGameObjectToScene(sBar);\n\n\t\/\/Initialize Title Screens and connect them to their appropriate GameObjectEvent in the event Map\n\tstatic std::shared_ptr<GraphicObject> _GameOverTitlePrototype = std::make_shared<GraphicObject>(Resources::Graphics::GAME_OVER_SCREEN);\n\tstatic std::shared_ptr<GraphicObject> _VictoryTitlePrototype = std::make_shared<GraphicObject>(Resources::Graphics::VICTORY_SCREEN);\n\tstatic std::shared_ptr<GraphicObject> _WaveTitlePrototype = std::make_shared<GraphicObject>(Resources::Graphics::WAVE_START, 2.75);\n\tstatic std::shared_ptr<GraphicObject> _FinalWaveTitlePrototype = std::make_shared<GraphicObject>(Resources::Graphics::FINAL_WAVE_START, 2.75);\n\n\t_eventMap.insert({ GameObjectEvent::WAVE_START, {_WaveTitlePrototype, _waveTitlePosition} });\n\t_eventMap.insert({ GameObjectEvent::FINAL_WAVE_START, {_FinalWaveTitlePrototype, _waveTitlePosition} });\n\t_eventMap.insert({ GameObjectEvent::VICTORY, {_VictoryTitlePrototype, _centerScreenPosition} });\n\t_eventMap.insert({ GameObjectEvent::GAME_OVER, {_GameOverTitlePrototype, _centerScreenPosition} });\n}\n\nvoid UserInterfaceManager::Notify(const GameObjectEvent& eventType)\n{\n\tif (_eventMap.find(eventType) != _eventMap.end())\n\t{\n\t\tconst auto uiElementPrototype = _eventMap.at(eventType);\n\t\tconst auto uiElement = uiElementPrototype.first->Clone(uiElementPrototype.second);\n\t\tGameObjectRegistryLocator::GetCreatorService()->AddGameObjectToScene(uiElement);\n\t}\n}","avg_line_length":53.2666666667,"max_line_length":143,"alphanum_fraction":0.8060075094,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":12979,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":9.0,"content":"\/\/ Copyright (c) Microsoft Corporation.\r\n\/\/ Licensed under the MIT License.\r\n#include \"pch.h\"\r\n#include \"winget\/GroupPolicy.h\"\r\n#include \"AppInstallerLogging.h\"\r\n\r\nusing namespace AppInstaller::StringResource;\r\n\r\nnamespace AppInstaller::Settings\r\n{\r\n    namespace\r\n    {\r\n        const GroupPolicy& InstanceInternal(std::optional<GroupPolicy*> overridePolicy = {})\r\n        {\r\n            const static GroupPolicy s_groupPolicy{ Registry::Key::OpenIfExists(HKEY_LOCAL_MACHINE, \"Software\\\\Policies\\\\Microsoft\\\\Windows\\\\AppInstaller\") };\r\n            static GroupPolicy* s_override = nullptr;\r\n\r\n            if (overridePolicy.has_value())\r\n            {\r\n                s_override = overridePolicy.value();\r\n            }\r\n\r\n            return (s_override ? *s_override : s_groupPolicy);\r\n        }\r\n\r\n        template<Registry::Value::Type T>\r\n        std::optional<decltype(std::declval<Registry::Value>().GetValue<T>())> GetRegistryValue(const Registry::Key& key, const std::string_view valueName)\r\n        {\r\n            if (!key)\r\n            {\r\n                \/\/ Key does not exist; there's nothing to return\r\n                return std::nullopt;\r\n            }\r\n\r\n            auto regValue = key[valueName];\r\n            if (!regValue.has_value())\r\n            {\r\n                \/\/ Value does not exist\r\n                return std::nullopt;\r\n            }\r\n\r\n            auto value = regValue->TryGetValue<T>();\r\n            if (!value.has_value())\r\n            {\r\n                AICLI_LOG(Core, Warning, << \"Value for policy '\" << valueName << \"' does not have expected type\");\r\n                return std::nullopt;\r\n            }\r\n\r\n            return std::move(value.value());\r\n        }\r\n\r\n        std::optional<bool> RegistryValueIsTrue(const Registry::Key& key, std::string_view valueName)\r\n        {\r\n            auto intValue = GetRegistryValue<Registry::Value::Type::DWord>(key, valueName);\r\n            if (!intValue.has_value())\r\n            {\r\n                return std::nullopt;\r\n            }\r\n\r\n            AICLI_LOG(Core, Info, << \"Found policy '\" << valueName << \"', Value: \" << *intValue);\r\n            return (bool)*intValue;\r\n        }\r\n\r\n        PolicyState GetStateInternal(const Registry::Key& key, TogglePolicy::Policy policy)\r\n        {\r\n            \/\/ Default to not configured if there is no policy for this\r\n            if (policy == TogglePolicy::Policy::None)\r\n            {\r\n                return PolicyState::NotConfigured;\r\n            }\r\n\r\n            auto togglePolicy = TogglePolicy::GetPolicy(policy);\r\n\r\n            \/\/ Policies are not configured if there is no registry value.\r\n            auto setting = RegistryValueIsTrue(key, togglePolicy.RegValueName());\r\n            if (!setting.has_value())\r\n            {\r\n                return PolicyState::NotConfigured;\r\n            }\r\n\r\n            \/\/ Return flag as-is or invert depending on the policy\r\n            return *setting ? PolicyState::Enabled : PolicyState::Disabled;\r\n        }\r\n\r\n        template <ValuePolicy P>\r\n        void Validate(const Registry::Key& policiesKey, GroupPolicy::ValuePoliciesMap& policies)\r\n        {\r\n            auto value = details::ValuePolicyMapping<P>::ReadAndValidate(policiesKey);\r\n            if (value.has_value())\r\n            {\r\n                policies.Add<P>(std::move(*value));\r\n            }\r\n        }\r\n\r\n        template <>\r\n        void Validate<ValuePolicy::None>(const Registry::Key&, GroupPolicy::ValuePoliciesMap&) {};\r\n\r\n        template <size_t... P>\r\n        void ValidateAllValuePolicies(\r\n            const Registry::Key& policiesKey,\r\n            GroupPolicy::ValuePoliciesMap& policies,\r\n            std::index_sequence<P...>)\r\n        {\r\n            \/\/ Use folding to call each policy validate function.\r\n            (FoldHelper{}, ..., Validate<static_cast<ValuePolicy>(P)>(policiesKey, policies));\r\n        }\r\n\r\n        \/\/ Reads a list from a Group Policy.\r\n        \/\/ The list is stored in a sub-key of the policies key, and each value in that key is a list item.\r\n        \/\/ Cases not considered by this function because we don't use them:\r\n        \/\/  - When the list is in an arbitrary key, not a sub key.\r\n        \/\/  - When the list values are mixed with other values and are identified by a prefix in their names.\r\n        \/\/  - When the value names are relevant.\r\n        template<ValuePolicy P>\r\n        std::optional<typename details::ValuePolicyMapping<P>::value_t> ReadList(const Registry::Key& policiesKey)\r\n        {\r\n            using Mapping = details::ValuePolicyMapping<P>;\r\n\r\n            auto listKey = policiesKey.SubKey(Mapping::KeyName);\r\n            if (!listKey.has_value())\r\n            {\r\n                return std::nullopt;\r\n            }\r\n\r\n            std::vector<Mapping::item_t> items;\r\n            for (const auto& value : listKey->Values())\r\n            {\r\n                auto item = Mapping::ReadAndValidateItem(value);\r\n                if (item.has_value())\r\n                {\r\n                    items.emplace_back(std::move(item.value()));\r\n                }\r\n                else\r\n                {\r\n                    AICLI_LOG(Core, Warning, << \"Failed to read Group Policy list value. Policy [\" << Mapping::KeyName << \"], Value [\" << value.Name() << ']');\r\n                }\r\n            }\r\n\r\n            return items;\r\n        }\r\n\r\n        std::optional<SourceFromPolicy> ReadSourceFromRegistryValue(const Registry::Value& item)\r\n        {\r\n            auto jsonString = item.TryGetValue<Registry::Value::Type::String>();\r\n            if (!jsonString.has_value())\r\n            {\r\n                AICLI_LOG(Core, Warning, << \"Registry value is not a string\");\r\n                return std::nullopt;\r\n            }\r\n\r\n            int stringLength = static_cast<int>(jsonString->length());\r\n            Json::Value sourceJson;\r\n            Json::CharReaderBuilder charReaderBuilder;\r\n            const std::unique_ptr<Json::CharReader> jsonReader(charReaderBuilder.newCharReader());\r\n            Json::String jsonErrors;\r\n            if (!jsonReader->parse(jsonString->c_str(), jsonString->c_str() + stringLength, &sourceJson, &jsonErrors))\r\n            {\r\n                AICLI_LOG(Core, Warning, << \"Registry value does not contain a valid JSON: \" << jsonErrors);\r\n                return std::nullopt;\r\n            }\r\n\r\n            SourceFromPolicy source;\r\n\r\n            auto readSourceAttribute = [&](const std::string& name, std::string SourceFromPolicy::* member)\r\n            {\r\n                if (sourceJson.isMember(name) && sourceJson[name].isString())\r\n                {\r\n                    source.*member = sourceJson[name].asString();\r\n                    return true;\r\n                }\r\n                else\r\n                {\r\n                    AICLI_LOG(Core, Warning, << \"Source JSON does not contain a string value for \" << name);\r\n                    return false;\r\n                }\r\n            };\r\n\r\n            bool allRead = readSourceAttribute(\"Name\", &SourceFromPolicy::Name)\r\n                && readSourceAttribute(\"Arg\", &SourceFromPolicy::Arg)\r\n                && readSourceAttribute(\"Type\", &SourceFromPolicy::Type)\r\n                && readSourceAttribute(\"Data\", &SourceFromPolicy::Data)\r\n                && readSourceAttribute(\"Identifier\", &SourceFromPolicy::Identifier);\r\n            if (!allRead)\r\n            {\r\n                return std::nullopt;\r\n            }\r\n\r\n            return source;\r\n        }\r\n    }\r\n\r\n    namespace details\r\n    {\r\n#define POLICY_MAPPING_DEFAULT_LIST_READ(_policy_) \\\r\n        std::optional<typename ValuePolicyMapping<_policy_>::value_t> ValuePolicyMapping<_policy_>::ReadAndValidate(const Registry::Key& policiesKey) \\\r\n        { \\\r\n            return ReadList<_policy_>(policiesKey); \\\r\n        }\r\n\r\n        POLICY_MAPPING_DEFAULT_LIST_READ(ValuePolicy::AdditionalSources);\r\n        POLICY_MAPPING_DEFAULT_LIST_READ(ValuePolicy::AllowedSources);\r\n\r\n        std::nullopt_t ValuePolicyMapping<ValuePolicy::None>::ReadAndValidate(const Registry::Key&)\r\n        {\r\n            return std::nullopt;\r\n        }\r\n\r\n        std::optional<uint32_t> ValuePolicyMapping<ValuePolicy::SourceAutoUpdateIntervalInMinutes>::ReadAndValidate(const Registry::Key& policiesKey)\r\n        {\r\n            using Mapping = ValuePolicyMapping<ValuePolicy::SourceAutoUpdateIntervalInMinutes>;\r\n            return GetRegistryValue<Mapping::ValueType>(policiesKey, Mapping::ValueName);\r\n        }\r\n\r\n        std::optional<SourceFromPolicy> ValuePolicyMapping<ValuePolicy::AdditionalSources>::ReadAndValidateItem(const Registry::Value& item)\r\n        {\r\n            return ReadSourceFromRegistryValue(item);\r\n        }\r\n\r\n        std::optional<SourceFromPolicy> ValuePolicyMapping<ValuePolicy::AllowedSources>::ReadAndValidateItem(const Registry::Value& item)\r\n        {\r\n            return ReadSourceFromRegistryValue(item);\r\n        }\r\n    }\r\n\r\n    TogglePolicy TogglePolicy::GetPolicy(TogglePolicy::Policy policy)\r\n    {\r\n        switch (policy)\r\n        {\r\n        case TogglePolicy::Policy::WinGet:\r\n            return TogglePolicy(policy, \"EnableAppInstaller\"sv, String::PolicyEnableWinGet);\r\n        case TogglePolicy::Policy::Settings: return\r\n            TogglePolicy(policy, \"EnableSettings\"sv, String::PolicyEnableWingetSettings);\r\n        case TogglePolicy::Policy::ExperimentalFeatures:\r\n            return TogglePolicy(policy, \"EnableExperimentalFeatures\"sv, String::PolicyEnableExperimentalFeatures);\r\n        case TogglePolicy::Policy::LocalManifestFiles:\r\n            return TogglePolicy(policy, \"EnableLocalManifestFiles\"sv, String::PolicyEnableLocalManifests);\r\n        case TogglePolicy::Policy::HashOverride:\r\n            return TogglePolicy(policy, \"EnableHashOverride\"sv, String::PolicyEnableHashOverride);\r\n        case TogglePolicy::Policy::DefaultSource:\r\n            return TogglePolicy(policy, \"EnableDefaultSource\"sv, String::PolicyEnableDefaultSource);\r\n        case TogglePolicy::Policy::MSStoreSource:\r\n            return TogglePolicy(policy, \"EnableMicrosoftStoreSource\"sv, String::PolicyEnableMSStoreSource);\r\n        case TogglePolicy::Policy::AdditionalSources:\r\n            return TogglePolicy(policy, \"EnableAdditionalSources\"sv, String::PolicyAdditionalSources);\r\n        case TogglePolicy::Policy::AllowedSources:\r\n            return TogglePolicy(policy, \"EnableAllowedSources\"sv, String::PolicyAllowedSources);\r\n        default:\r\n            THROW_HR(E_UNEXPECTED);\r\n        }\r\n    }\r\n\r\n    std::vector<TogglePolicy> TogglePolicy::GetAllPolicies()\r\n    {\r\n        using Toggle_t = std::underlying_type_t<TogglePolicy::Policy>;\r\n\r\n        std::vector<TogglePolicy> result;\r\n\r\n        \/\/ Skip \"None\"\r\n        for (Toggle_t i = 1 + static_cast<Toggle_t>(TogglePolicy::Policy::None); i < static_cast<Toggle_t>(TogglePolicy::Policy::Max); ++i)\r\n        {\r\n            result.emplace_back(GetPolicy(static_cast<Policy>(i)));\r\n        }\r\n\r\n        return result;\r\n    }\r\n\r\n    std::string SourceFromPolicy::ToJsonString() const\r\n    {\r\n        Json::Value json{ Json::ValueType::objectValue };\r\n        json[\"Name\"] = Name;\r\n        json[\"Type\"] = Type;\r\n        json[\"Arg\"] = Arg;\r\n        json[\"Data\"] = Data;\r\n        json[\"Identifier\"] = Identifier;\r\n\r\n        Json::StreamWriterBuilder writerBuilder;\r\n        writerBuilder.settings_[\"indentation\"] = \"\";\r\n        return Json::writeString(writerBuilder, json);\r\n    }\r\n\r\n    GroupPolicy::GroupPolicy(const Registry::Key& key)\r\n    {\r\n        ValidateAllValuePolicies(key, m_values, std::make_index_sequence<static_cast<size_t>(ValuePolicy::Max)>());\r\n\r\n        using Toggle_t = std::underlying_type_t<TogglePolicy::Policy>;\r\n        for (Toggle_t i = static_cast<Toggle_t>(TogglePolicy::Policy::None); i < static_cast<Toggle_t>(TogglePolicy::Policy::Max); ++i)\r\n        {\r\n            auto policy = static_cast<TogglePolicy::Policy>(i);\r\n            m_toggles[policy] = GetStateInternal(key, policy);\r\n        }\r\n    }\r\n\r\n    PolicyState GroupPolicy::GetState(TogglePolicy::Policy policy) const\r\n    {\r\n        auto itr = m_toggles.find(policy);\r\n        if (itr == m_toggles.end())\r\n        {\r\n            return PolicyState::NotConfigured;\r\n        }\r\n\r\n        return itr->second;\r\n    }\r\n\r\n    bool GroupPolicy::IsEnabled(TogglePolicy::Policy policy) const\r\n    {\r\n        if (policy == TogglePolicy::Policy::None)\r\n        {\r\n            return true;\r\n        }\r\n\r\n        PolicyState state = GetState(policy);\r\n        if (state == PolicyState::NotConfigured)\r\n        {\r\n            return TogglePolicy::GetPolicy(policy).DefaultIsEnabled();\r\n        }\r\n\r\n        return state == PolicyState::Enabled;\r\n    }\r\n\r\n    GroupPolicy const& GroupPolicy::Instance()\r\n    {\r\n        return InstanceInternal();\r\n    }\r\n\r\n    void GroupPolicy::OverrideInstance(GroupPolicy* overridePolicy)\r\n    {\r\n        InstanceInternal(overridePolicy);\r\n    }\r\n\r\n    void GroupPolicy::ResetInstance()\r\n    {\r\n        InstanceInternal(nullptr);\r\n    }\r\n}","avg_line_length":38.8592814371,"max_line_length":160,"alphanum_fraction":0.5827875799,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2342,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <bench\/bench.h>\n#include <chainparams.h>\n#include <consensus\/merkle.h>\n#include <consensus\/validation.h>\n#include <pow.h>\n#include <test\/util\/setup_common.h>\n#include <txmempool.h>\n#include <validation.h>\n\n\nstatic void DuplicateInputs(benchmark::Bench& bench)\n{\n    TestingSetup test_setup{\n        CBaseChainParams::REGTEST,\n        \/* extra_args *\/ {\n            \"-nodebuglogfile\",\n            \"-nodebug\",\n        },\n    };\n\n    const CScript SCRIPT_PUB{CScript(OP_TRUE)};\n\n    const CChainParams& chainparams = Params();\n\n    CBlock block{};\n    CMutableTransaction coinbaseTx{};\n    CMutableTransaction naughtyTx{};\n\n    LOCK(cs_main);\n    CBlockIndex* pindexPrev = ::ChainActive().Tip();\n    assert(pindexPrev != nullptr);\n    block.nBits = GetNextWorkRequired(pindexPrev, &block, chainparams.GetConsensus(), false);\n    block.nNonce = 0;\n    auto nHeight = pindexPrev->nHeight + 1;\n\n    \/\/ Make a coinbase TX\n    coinbaseTx.vin.resize(1);\n    coinbaseTx.vin[0].prevout.SetNull();\n    coinbaseTx.vout.resize(1);\n    coinbaseTx.vout[0].scriptPubKey = SCRIPT_PUB;\n    coinbaseTx.vout[0].nValue = GetBlockSubsidy(nHeight, chainparams.GetConsensus());\n    coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;\n\n\n    naughtyTx.vout.resize(1);\n    naughtyTx.vout[0].nValue = 0;\n    naughtyTx.vout[0].scriptPubKey = SCRIPT_PUB;\n\n    uint64_t n_inputs = (((MAX_BLOCK_SERIALIZED_SIZE \/ WITNESS_SCALE_FACTOR) - (CTransaction(coinbaseTx).GetTotalSize() + CTransaction(naughtyTx).GetTotalSize())) \/ 41) - 100;\n    for (uint64_t x = 0; x < (n_inputs - 1); ++x) {\n        naughtyTx.vin.emplace_back(GetRandHash(), 0, CScript(), 0);\n    }\n    naughtyTx.vin.emplace_back(naughtyTx.vin.back());\n\n    block.vtx.push_back(MakeTransactionRef(std::move(coinbaseTx)));\n    block.vtx.push_back(MakeTransactionRef(std::move(naughtyTx)));\n\n    block.hashMerkleRoot = BlockMerkleRoot(block);\n\n    bench.run([&] {\n        BlockValidationState cvstate{};\n        assert(!CheckBlock(block, cvstate, chainparams.GetConsensus(), false, false));\n        assert(cvstate.GetRejectReason() == \"bad-txns-inputs-duplicate\");\n    });\n}\n\nBENCHMARK(DuplicateInputs);\n","avg_line_length":32.5277777778,"max_line_length":175,"alphanum_fraction":0.6874466268,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":602,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["WTFPL"],"max_stars_count":8.0,"content":"#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nint main() {\n    int m;\n    std::cin >> m;\n    std::vector<int> a[26];\n    for (int i = 0; i < m; i++) {\n        int id;\n        std::string s;\n        std::cin >> id >> s;\n        for (auto i : s) {\n            a[i - 'A'].push_back(id);\n        }\n    }\n    auto p{std::max_element(std::begin(a), std::end(a), [](auto&& x, auto&& y){\n        return x.size() < y.size();\n    })};\n    std::cout << char('A' + (p - a)) << std::endl << p->size() << std::endl;\n    for (auto i : *p) {\n        std::cout << i << std::endl;\n    }\n}","avg_line_length":24.08,"max_line_length":79,"alphanum_fraction":0.4418604651,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":502,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":7.0,"content":"#include \"trim.hpp\"\n\n#include \"is_whitespace.hpp\"\n\nnamespace Utopia\n{\n\tvoid trim(std::string& str)\n\t{\n\t\tltrim(str);\n\t\trtrim(str);\n\t}\n\n\tvoid ltrim(std::string& str)\n\t{\n\t\twhile (!str.empty())\n\t\t{\n\t\t\tauto i = str.cbegin();\n\t\t\tconst char c = *i;\n\t\t\tif (!is_whitespace(c))\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstr.erase(i);\n\t\t}\n\t}\n\n\tvoid rtrim(std::string& str)\n\t{\n\t\twhile (!str.empty())\n\t\t{\n\t\t\tauto i = (str.cend() - 1);\n\t\t\tconst char  c = *i;\n\t\t\tif (!is_whitespace(c))\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstr.erase(i);\n\t\t}\n\t}\n}\n","avg_line_length":12.243902439,"max_line_length":29,"alphanum_fraction":0.53187251,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3956,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-3.0","Apache-2.0","MIT"],"max_stars_count":2.0,"content":"\/*************************************************************************\/\n\/*  audio_driver_dummy.cpp                                               *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                    http:\/\/www.godotengine.org                         *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md)    *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n#include \"audio_driver_dummy.h\"\n\n#include \"global_config.h\"\n#include \"os\/os.h\"\n\nError AudioDriverDummy::init() {\n\n\tactive = false;\n\tthread_exited = false;\n\texit_thread = false;\n\tpcm_open = false;\n\tsamples_in = NULL;\n\n\tmix_rate = 44100;\n\tspeaker_mode = SPEAKER_MODE_STEREO;\n\tchannels = 2;\n\n\tint latency = GLOBAL_DEF(\"audio\/output_latency\", 25);\n\tbuffer_size = nearest_power_of_2(latency * mix_rate \/ 1000);\n\n\tsamples_in = memnew_arr(int32_t, buffer_size * channels);\n\n\tmutex = Mutex::create();\n\tthread = Thread::create(AudioDriverDummy::thread_func, this);\n\n\treturn OK;\n};\n\nvoid AudioDriverDummy::thread_func(void *p_udata) {\n\n\tAudioDriverDummy *ad = (AudioDriverDummy *)p_udata;\n\n\tuint64_t usdelay = (ad->buffer_size \/ float(ad->mix_rate)) * 1000000;\n\n\twhile (!ad->exit_thread) {\n\n\t\tif (!ad->active) {\n\n\t\t} else {\n\n\t\t\tad->lock();\n\n\t\t\tad->audio_server_process(ad->buffer_size, ad->samples_in);\n\n\t\t\tad->unlock();\n\t\t};\n\n\t\tOS::get_singleton()->delay_usec(usdelay);\n\t};\n\n\tad->thread_exited = true;\n};\n\nvoid AudioDriverDummy::start() {\n\n\tactive = true;\n};\n\nint AudioDriverDummy::get_mix_rate() const {\n\n\treturn mix_rate;\n};\n\nAudioDriver::SpeakerMode AudioDriverDummy::get_speaker_mode() const {\n\n\treturn speaker_mode;\n};\n\nvoid AudioDriverDummy::lock() {\n\n\tif (!thread || !mutex)\n\t\treturn;\n\tmutex->lock();\n};\n\nvoid AudioDriverDummy::unlock() {\n\n\tif (!thread || !mutex)\n\t\treturn;\n\tmutex->unlock();\n};\n\nvoid AudioDriverDummy::finish() {\n\n\tif (!thread)\n\t\treturn;\n\n\texit_thread = true;\n\tThread::wait_to_finish(thread);\n\n\tif (samples_in) {\n\t\tmemdelete_arr(samples_in);\n\t};\n\n\tmemdelete(thread);\n\tif (mutex)\n\t\tmemdelete(mutex);\n\tthread = NULL;\n};\n\nAudioDriverDummy::AudioDriverDummy() {\n\n\tmutex = NULL;\n\tthread = NULL;\n};\n\nAudioDriverDummy::~AudioDriverDummy(){\n\n};\n","avg_line_length":28.4604316547,"max_line_length":75,"alphanum_fraction":0.555611729,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1014,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include \"Basic\/TasksManage.h\"\n#include \"LuaScript.h\"\n\nTaskHandle_t TaskHandle_LuaScript = 0;\n\nstatic const char *ScriptText = 0;\nstatic String ScriptFilePath;\n\nvoid LuaScriptStart(const char *script)\n{\n    ScriptText = script;\n    ScriptFilePath = \"\";\n\n    xTaskNotifyGive(TaskHandle_LuaScript);\n}\n\nvoid LuaScriptExecuteFile(String file)\n{\n    ScriptText = NULL;\n    ScriptFilePath = file;\n    \n    xTaskNotifyGive(TaskHandle_LuaScript);\n}\n\nvoid Task_LuaScript(void *pvParameters)\n{\n    for(;;)\n    {\n        luaScript.begin();\n        LuaReg_Time();\n        \/\/LuaReg_GPIO();\n        LuaReg_ModuleCtrl();\n        \/\/LuaReg_Com();\n        LuaReg_LVGL();\n        \n        ulTaskNotifyTake(pdTRUE, portMAX_DELAY);\n\n        if(ScriptText)\n        {\n            luaScript.doString(ScriptText);\n        }\n        \n        if(ScriptFilePath != \"\")\n        {\n            luaScript.doFile(ScriptFilePath.c_str());\n        }\n        \n        luaScript.end();\n        lua_close(luaScript.L);\n        luaScript.L = 0;\n    }\n}\n","avg_line_length":19.1320754717,"max_line_length":53,"alphanum_fraction":0.5936883629,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13721,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":null,"content":"\/\/ http:\/\/turtle.sourceforge.net\n\/\/\n\/\/ Copyright Mathieu Champlon 2009\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include \"mock_error.hpp\"\n#include <turtle\/mock.hpp>\n#include <boost\/test\/auto_unit_test.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/bind.hpp>\n\nnamespace\n{\n    template< typename T >\n    void my_function( T& t )\n    {\n        t.my_method( \"some parameter\" );\n    }\n    MOCK_CLASS( mock_class )\n    {\n        MOCK_METHOD_EXT( my_method, 1, void( const std::string& ), my_tag )\n    };\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_object_for_static_polymorphism, mock_error_fixture )\n{\n    const mock_class m;\n    MOCK_EXPECT( m.my_tag ).once().with( \"some parameter\" );\n    my_function( m );\n    CHECK_CALLS( 1 );\n}\n\nnamespace\n{\n    MOCK_CLASS( mock_class_with_operator )\n    {\n        MOCK_CONST_METHOD_EXT( operator+=, 1, mock_class_with_operator&( int ), addition )\n    };\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_addition_operator, mock_error_fixture )\n{\n    mock_class_with_operator m;\n    MOCK_EXPECT( m.addition ).once().returns( boost::ref( m ) );\n    m += 1;\n    CHECK_CALLS( 1 );\n}\n\nnamespace\n{\n    MOCK_CLASS( mock_class_with_conversion_operator )\n    {\n        MOCK_CONVERSION_OPERATOR( operator, int, conversion )\n    };\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_conversion_operator, mock_error_fixture )\n{\n    mock_class_with_conversion_operator m;\n    MOCK_EXPECT( m.conversion ).once().returns( 42 );\n    BOOST_CHECK_EQUAL( 42, static_cast< int >( m ) );\n    CHECK_CALLS( 1 );\n}\n\nnamespace\n{\n    template< typename T >\n    MOCK_CLASS( mock_template_class_with_conversion_operator )\n    {\n        MOCK_CONVERSION_OPERATOR_TPL( operator, T, conversion )\n    };\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_template_conversion_operator, mock_error_fixture )\n{\n    mock_template_class_with_conversion_operator< int > m;\n    MOCK_EXPECT( m.conversion ).once().returns( 42 );\n    BOOST_CHECK_EQUAL( 42, static_cast< int >( m ) );\n    CHECK_CALLS( 1 );\n}\n\nnamespace\n{\n    MOCK_CLASS( mock_class_with_const_conversion_operator )\n    {\n        MOCK_CONST_CONVERSION_OPERATOR( operator, int, conversion )\n    };\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_const_conversion_operator, mock_error_fixture )\n{\n    mock_class_with_const_conversion_operator m;\n    MOCK_EXPECT( m.conversion ).once().returns( 42 );\n    int i = m;\n    BOOST_CHECK_EQUAL( 42, i );\n    CHECK_CALLS( 1 );\n}\n\nnamespace\n{\n    MOCK_CLASS( mock_class_with_non_const_conversion_operator )\n    {\n        MOCK_CONST_CONVERSION_OPERATOR( operator, int, conversion )\n    };\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_non_const_conversion_operator, mock_error_fixture )\n{\n    mock_class_with_non_const_conversion_operator m;\n    MOCK_EXPECT( m.conversion ).once().returns( 42 );\n    int i = m;\n    BOOST_CHECK_EQUAL( 42, i );\n    CHECK_CALLS( 1 );\n}\n\nnamespace\n{\n    template< typename T >\n    MOCK_CLASS( mock_template_class_with_const_conversion_operator )\n    {\n        MOCK_CONST_CONVERSION_OPERATOR_TPL( operator, T, conversion )\n    };\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_template_const_conversion_operator, mock_error_fixture )\n{\n    mock_template_class_with_const_conversion_operator< int > m;\n    MOCK_EXPECT( m.conversion ).once().returns( 42 );\n    BOOST_CHECK_EQUAL( 42, static_cast< int >( m ) );\n    CHECK_CALLS( 1 );\n}\n\nnamespace\n{\n    template< typename T >\n    MOCK_CLASS( mock_template_class_with_non_const_conversion_operator )\n    {\n        MOCK_NON_CONST_CONVERSION_OPERATOR_TPL( operator, T, conversion )\n    };\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_template_non_const_conversion_operator, mock_error_fixture )\n{\n    mock_template_class_with_non_const_conversion_operator< int > m;\n    MOCK_EXPECT( m.conversion ).once().returns( 42 );\n    BOOST_CHECK_EQUAL( 42, static_cast< int >( m ) );\n    CHECK_CALLS( 1 );\n}\n\nnamespace\n{\n    MOCK_CLASS( my_mock )\n    {\n        MOCK_CONST_METHOD_EXT( my_method, 1, void( int ), my_method )\n        MOCK_CONST_METHOD_EXT( my_method_2, 1, void( int ), my_method_2 )\n    };\n}\n\nBOOST_FIXTURE_TEST_CASE( MOCK_CONST_METHOD_EXT_macro_defines_a_bindable_method, mock_error_fixture )\n{\n    my_mock m;\n    boost::bind( &my_mock::my_method, &m, 42 );\n}\n\nBOOST_FIXTURE_TEST_CASE( MOCK_VERIFY_macro, mock_error_fixture )\n{\n    my_mock m;\n    MOCK_VERIFY( m.my_method );\n}\n\nBOOST_FIXTURE_TEST_CASE( MOCK_RESET_macro, mock_error_fixture )\n{\n    my_mock m;\n    MOCK_RESET( m.my_method );\n}\n\nBOOST_FIXTURE_TEST_CASE( MOCK_EXPECT_macro, mock_error_fixture )\n{\n    my_mock m;\n    MOCK_EXPECT( m.my_method ).once().with( 42 );\n    m.my_method( 42 );\n    CHECK_CALLS( 1 );\n}\n\nnamespace\n{\n    template< typename T >\n    std::string to_string( const T& t )\n    {\n        std::stringstream s;\n        s << t;\n        return s.str();\n    }\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_object_is_named, mock_error_fixture )\n{\n    my_mock m;\n    BOOST_CHECK_EQUAL( \"?.my_mock::my_method\", to_string( MOCK_ANONYMOUS_HELPER( m.my_method ) ) );\n    BOOST_CHECK_EQUAL( \"?.my_mock::my_method_2\", to_string( MOCK_ANONYMOUS_HELPER( m.my_method_2 ) ) );\n    BOOST_CHECK_EQUAL( \"m.my_mock::my_method\", to_string( MOCK_HELPER( m.my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m.my_mock::my_method_2\", to_string( MOCK_ANONYMOUS_HELPER( m.my_method_2 ) ) );\n    BOOST_CHECK_EQUAL( \"m.my_mock::my_method\", to_string( MOCK_ANONYMOUS_HELPER( m.my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m.my_mock::my_method\", to_string( MOCK_HELPER( m.my_method ) ) );\n}\n\n#ifdef MOCK_AUTO_PTR\n\nBOOST_FIXTURE_TEST_CASE( mock_object_auto_pointer_is_named, mock_error_fixture )\n{\n    std::auto_ptr< my_mock > m( new my_mock );\n    BOOST_CHECK_EQUAL( \"?.my_mock::my_method\", to_string( MOCK_ANONYMOUS_HELPER( m->my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m->my_mock::my_method\", to_string( MOCK_HELPER( m->my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m->my_mock::my_method\", to_string( MOCK_ANONYMOUS_HELPER( m->my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m->my_mock::my_method\", to_string( MOCK_HELPER( m->my_method ) ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_object_const_auto_pointer_is_named, mock_error_fixture )\n{\n    const std::auto_ptr< my_mock > m( new my_mock );\n    BOOST_CHECK_EQUAL( \"?.my_mock::my_method\", to_string( MOCK_ANONYMOUS_HELPER( m->my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m->my_mock::my_method\", to_string( MOCK_HELPER( m->my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m->my_mock::my_method\", to_string( MOCK_ANONYMOUS_HELPER( m->my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m->my_mock::my_method\", to_string( MOCK_HELPER( m->my_method ) ) );\n}\n\n#endif \/\/ MOCK_AUTO_PTR\n\nBOOST_FIXTURE_TEST_CASE( mock_object_shared_pointer_is_named, mock_error_fixture )\n{\n    boost::shared_ptr< my_mock > m( new my_mock );\n    BOOST_CHECK_EQUAL( \"?.my_mock::my_method\", to_string( MOCK_ANONYMOUS_HELPER( m->my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m->my_mock::my_method\", to_string( MOCK_HELPER( m->my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m->my_mock::my_method\", to_string( MOCK_ANONYMOUS_HELPER( m->my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m->my_mock::my_method\", to_string( MOCK_HELPER( m->my_method ) ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_object_const_shared_pointer_is_named, mock_error_fixture )\n{\n    const boost::shared_ptr< my_mock > m( new my_mock );\n    BOOST_CHECK_EQUAL( \"?.my_mock::my_method\", to_string( MOCK_ANONYMOUS_HELPER( m->my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m->my_mock::my_method\", to_string( MOCK_HELPER( m->my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m->my_mock::my_method\", to_string( MOCK_ANONYMOUS_HELPER( m->my_method ) ) );\n    BOOST_CHECK_EQUAL( \"m->my_mock::my_method\", to_string( MOCK_HELPER( m->my_method ) ) );\n}\n\nnamespace\n{\n    struct my_custom_mock\n    {\n        MOCK_METHOD_EXT( my_method, 0, void(), my_tag )\n        MOCK_METHOD_EXT( my_method_2, 0, void(), my_tag_2 )\n    };\n}\n\nBOOST_FIXTURE_TEST_CASE( custom_mock_object_without_macros_and_without_inheriting_from_object_is_named, mock_error_fixture )\n{\n    my_custom_mock m;\n    BOOST_CHECK_EQUAL( \"?.my_custom_mock::my_tag\", to_string( MOCK_ANONYMOUS_HELPER( m.my_tag ) ) );\n    BOOST_CHECK_EQUAL( \"?.my_custom_mock::my_tag_2\", to_string( MOCK_ANONYMOUS_HELPER( m.my_tag_2 ) ) );\n    BOOST_CHECK_EQUAL( \"m.my_custom_mock::my_tag\", to_string( MOCK_HELPER( m.my_tag ) ) );\n    BOOST_CHECK_EQUAL( \"m.my_custom_mock::my_tag_2\", to_string( MOCK_ANONYMOUS_HELPER( m.my_tag_2 ) ) );\n    BOOST_CHECK_EQUAL( \"m.my_custom_mock::my_tag\", to_string( MOCK_ANONYMOUS_HELPER( m.my_tag ) ) );\n    BOOST_CHECK_EQUAL( \"m.my_custom_mock::my_tag\", to_string( MOCK_HELPER( m.my_tag ) ) );\n}\n\nnamespace\n{\n    struct my_custom_mock_object : mock::object\n    {\n        MOCK_METHOD_EXT( my_method, 0, void(), my_tag )\n        MOCK_METHOD_EXT( my_method_2, 0, void(), my_tag_2 )\n    };\n}\n\nBOOST_FIXTURE_TEST_CASE( custom_mock_object_without_macros_is_named, mock_error_fixture )\n{\n    my_custom_mock_object m;\n    BOOST_CHECK_EQUAL( \"?.my_custom_mock_object::my_tag\", to_string( MOCK_ANONYMOUS_HELPER( m.my_tag ) ) );\n    BOOST_CHECK_EQUAL( \"?.my_custom_mock_object::my_tag_2\", to_string( MOCK_ANONYMOUS_HELPER( m.my_tag_2 ) ) );\n    BOOST_CHECK_EQUAL( \"m.my_custom_mock_object::my_tag\", to_string( MOCK_HELPER( m.my_tag ) ) );\n    BOOST_CHECK_EQUAL( \"m.my_custom_mock_object::my_tag_2\", to_string( MOCK_ANONYMOUS_HELPER( m.my_tag_2 ) ) );\n    BOOST_CHECK_EQUAL( \"m.my_custom_mock_object::my_tag\", to_string( MOCK_ANONYMOUS_HELPER( m.my_tag ) ) );\n    BOOST_CHECK_EQUAL( \"m.my_custom_mock_object::my_tag\", to_string( MOCK_HELPER( m.my_tag ) ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_functor, mock_error_fixture )\n{\n    MOCK_FUNCTOR( f1, void() );\n    MOCK_FUNCTOR( f2, int( const std::string& ) );\n}\n\nnamespace\n{\n    template< typename T >\n    struct tpl_functor_class\n    {\n        MOCK_FUNCTOR_TPL( f, void( T ) );\n    };\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_functor_reset, mock_error_fixture )\n{\n    MOCK_FUNCTOR( f, void() );\n    MOCK_RESET( f );\n    mock::reset( f );\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_functor_verify, mock_error_fixture )\n{\n    MOCK_FUNCTOR( f, void() );\n    MOCK_VERIFY( f );\n    mock::verify( f );\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_functor_is_named, mock_error_fixture )\n{\n    MOCK_FUNCTOR( f, void() );\n    BOOST_CHECK_EQUAL( \"f\", to_string( MOCK_HELPER( f ) ) );\n}\n\nnamespace\n{\n    MOCK_FUNCTION( mock_function, 1, float( int ), mock_function )\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_function_is_named, mock_error_fixture )\n{\n    BOOST_CHECK_EQUAL( \"mock_function\", to_string( MOCK_HELPER( mock_function ) ) );\n}\n\nnamespace\n{\n    MOCK_CLASS( static_function_class )\n    {\n        MOCK_STATIC_METHOD( f, 1, float( int ), f )\n    };\n}\n\nBOOST_FIXTURE_TEST_CASE( mock_static_function_is_named, mock_error_fixture )\n{\n    BOOST_CHECK_EQUAL( \"static_function_class::f\", to_string( MOCK_HELPER( static_function_class::f ) ) );\n}\n\nnamespace\n{\n    MOCK_CLASS( round_parenthesized_signature )\n    {\n        MOCK_METHOD_EXT( m0, 0, BOOST_IDENTITY_TYPE((std::map< int, int >())), m0 )\n        MOCK_STATIC_METHOD( m1, 0, BOOST_IDENTITY_TYPE((std::map< int, int >())), m1 )\n        MOCK_FUNCTOR( f0, BOOST_IDENTITY_TYPE((std::map< int, int >())) );\n    };\n    MOCK_FUNCTION( fun0, 0, BOOST_IDENTITY_TYPE((std::map< int, int >())), fun0 )\n}\n\n#ifdef MOCK_VARIADIC_MACROS\n\nnamespace\n{\n    struct base\n    {\n        virtual ~base()\n        {}\n\n        virtual void m1() = 0;\n    };\n\n    MOCK_BASE_CLASS( variadic, base )\n    {\n        MOCK_METHOD( m1, 0 )\n        MOCK_METHOD( m2, 0, void() )\n        MOCK_METHOD( m3, 0, void(), m3 )\n        MOCK_CONST_METHOD( m4, 0, void() )\n        MOCK_CONST_METHOD( m5, 0, void(), m5 )\n        MOCK_NON_CONST_METHOD( m6, 0, void() )\n        MOCK_NON_CONST_METHOD( m7, 0, void(), m7 )\n        MOCK_STATIC_METHOD( m8, 0, void() )\n        MOCK_STATIC_METHOD( m9, 0, void(), m9 )\n    };\n\n    template< typename T >\n    MOCK_BASE_CLASS( variadic_tpl, base )\n    {\n        MOCK_METHOD( m1, 0, void() )\n        MOCK_METHOD_TPL( m2, 0, T() )\n        MOCK_METHOD_TPL( m3, 0, T(), m3 )\n        MOCK_CONST_METHOD_TPL( m4, 0, T() )\n        MOCK_CONST_METHOD_TPL( m5, 0, T(), m5 )\n        MOCK_NON_CONST_METHOD_TPL( m6, 0, T() )\n        MOCK_NON_CONST_METHOD_TPL( m7, 0, T(), m7 )\n        MOCK_STATIC_METHOD_TPL( m8, 0, T() )\n        MOCK_STATIC_METHOD_TPL( m9, 0, T(), m9 )\n    };\n\n    MOCK_BASE_CLASS( comma_base, std::map< int, int > )\n    {};\n\n    MOCK_FUNCTION( fun1, 0, void() )\n    MOCK_FUNCTION( fun2, 0, void(), fun2 )\n    MOCK_FUNCTION( fun3, 0, BOOST_IDENTITY_TYPE((std::map< int, int >())) )\n\n    MOCK_FUNCTOR( f_variadic, std::map< int, int >() );\n}\n\n#else \/\/ MOCK_VARIADIC_MACROS\n\nnamespace\n{\n    struct base\n    {\n        virtual ~base()\n        {}\n\n        virtual void m1() = 0;\n    };\n\n    MOCK_BASE_CLASS( derived, base )\n    {\n        MOCK_METHOD( m1, 0 )\n    };\n\n    template< typename T >\n    MOCK_BASE_CLASS( derived_tpl, base )\n    {\n        MOCK_METHOD_EXT( m1, 0, void(), m1 )\n    };\n}\n\n#endif \/\/ MOCK_VARIADIC_MACROS\n\n#ifdef BOOST_MSVC\n#   define MOCK_STDCALL __stdcall\n#else\n#   define MOCK_STDCALL\n#endif\n\nnamespace stdcall\n{\n    struct base\n    {\n        virtual ~base()\n        {}\n\n        virtual void MOCK_STDCALL m1() = 0;\n    };\n\n    MOCK_BASE_CLASS( derived, base )\n    {\n        MOCK_CONSTRUCTOR( MOCK_STDCALL derived, 0, (), derived )\n        MOCK_DESTRUCTOR( MOCK_STDCALL ~derived, derived )\n        MOCK_CONVERSION_OPERATOR( MOCK_STDCALL operator, int, to_int )\n        MOCK_METHOD_EXT( MOCK_STDCALL m1, 0, void(), m1 )\n        MOCK_METHOD_EXT( MOCK_STDCALL m2, 0, void(), m2 )\n#ifdef MOCK_VARIADIC_MACROS\n        MOCK_METHOD( MOCK_STDCALL m3, 0, void(), m3 )\n#endif\n        MOCK_STATIC_METHOD( MOCK_STDCALL m4, 0, void(), m4 )\n    };\n\n    MOCK_FUNCTION( MOCK_STDCALL f, 0, void(), f )\n}\n","avg_line_length":29.5075268817,"max_line_length":124,"alphanum_fraction":0.6882880257,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":85521,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2017 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <base58.h>\n#include <chain.h>\n#include <clientversion.h>\n#include <consensus\/validation.h>\n#include <core_io.h>\n#include <crypto\/ripemd160.h>\n#include <httpserver.h>\n#include <init.h>\n#include <merkleblock.h>\n#include <net.h>\n#include <netbase.h>\n#include <rpc\/blockchain.h>\n#include <rpc\/server.h>\n#include <rpc\/util.h>\n#include <sidechain.h>\n#include <sidechaindb.h>\n#include <timedata.h>\n#include <txdb.h>\n#include <util.h>\n#include <utilmoneystr.h>\n#include <utilstrencodings.h>\n#include <validation.h>\n#ifdef ENABLE_WALLET\n#include <wallet\/coincontrol.h>\n#include <wallet\/rpcwallet.h>\n#include <wallet\/wallet.h>\n#include <wallet\/walletdb.h>\n#endif\n#include <warnings.h>\n\n#include <stdint.h>\n#ifdef HAVE_MALLOC_INFO\n#include <malloc.h>\n#endif\n\n#include <univalue.h>\n\n#ifdef ENABLE_WALLET\nclass DescribeAddressVisitor : public boost::static_visitor<UniValue>\n{\npublic:\n    CWallet * const pwallet;\n\n    explicit DescribeAddressVisitor(CWallet *_pwallet) : pwallet(_pwallet) {}\n\n    void ProcessSubScript(const CScript& subscript, UniValue& obj, bool include_addresses = false) const\n    {\n        \/\/ Always present: script type and redeemscript\n        txnouttype which_type;\n        std::vector<std::vector<unsigned char>> solutions_data;\n        Solver(subscript, which_type, solutions_data);\n        obj.pushKV(\"script\", GetTxnOutputType(which_type));\n        obj.pushKV(\"hex\", HexStr(subscript.begin(), subscript.end()));\n\n        CTxDestination embedded;\n        UniValue a(UniValue::VARR);\n        if (ExtractDestination(subscript, embedded)) {\n            \/\/ Only when the script corresponds to an address.\n            UniValue subobj = boost::apply_visitor(*this, embedded);\n            subobj.pushKV(\"address\", EncodeDestination(embedded));\n            subobj.pushKV(\"scriptPubKey\", HexStr(subscript.begin(), subscript.end()));\n            \/\/ Always report the pubkey at the top level, so that `getnewaddress()['pubkey']` always works.\n            if (subobj.exists(\"pubkey\")) obj.pushKV(\"pubkey\", subobj[\"pubkey\"]);\n            obj.pushKV(\"embedded\", std::move(subobj));\n            if (include_addresses) a.push_back(EncodeDestination(embedded));\n        } else if (which_type == TX_MULTISIG) {\n            \/\/ Also report some information on multisig scripts (which do not have a corresponding address).\n            \/\/ TODO: abstract out the common functionality between this logic and ExtractDestinations.\n            obj.pushKV(\"sigsrequired\", solutions_data[0][0]);\n            UniValue pubkeys(UniValue::VARR);\n            for (size_t i = 1; i < solutions_data.size() - 1; ++i) {\n                CPubKey key(solutions_data[i].begin(), solutions_data[i].end());\n                if (include_addresses) a.push_back(EncodeDestination(key.GetID()));\n                pubkeys.push_back(HexStr(key.begin(), key.end()));\n            }\n            obj.pushKV(\"pubkeys\", std::move(pubkeys));\n        }\n\n        \/\/ The \"addresses\" field is confusing because it refers to public keys using their P2PKH address.\n        \/\/ For that reason, only add the 'addresses' field when needed for backward compatibility. New applications\n        \/\/ can use the 'embedded'->'address' field for P2SH or P2WSH wrapped addresses, and 'pubkeys' for\n        \/\/ inspecting multisig participants.\n        if (include_addresses) obj.pushKV(\"addresses\", std::move(a));\n    }\n\n    UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); }\n\n    UniValue operator()(const CKeyID &keyID) const {\n        UniValue obj(UniValue::VOBJ);\n        CPubKey vchPubKey;\n        obj.push_back(Pair(\"isscript\", false));\n        obj.push_back(Pair(\"iswitness\", false));\n        if (pwallet && pwallet->GetPubKey(keyID, vchPubKey)) {\n            obj.push_back(Pair(\"pubkey\", HexStr(vchPubKey)));\n            obj.push_back(Pair(\"iscompressed\", vchPubKey.IsCompressed()));\n        }\n        return obj;\n    }\n\n    UniValue operator()(const CScriptID &scriptID) const {\n        UniValue obj(UniValue::VOBJ);\n        CScript subscript;\n        obj.push_back(Pair(\"isscript\", true));\n        obj.push_back(Pair(\"iswitness\", false));\n        if (pwallet && pwallet->GetCScript(scriptID, subscript)) {\n            ProcessSubScript(subscript, obj, true);\n        }\n        return obj;\n    }\n\n    UniValue operator()(const WitnessV0KeyHash& id) const\n    {\n        UniValue obj(UniValue::VOBJ);\n        CPubKey pubkey;\n        obj.push_back(Pair(\"isscript\", false));\n        obj.push_back(Pair(\"iswitness\", true));\n        obj.push_back(Pair(\"witness_version\", 0));\n        obj.push_back(Pair(\"witness_program\", HexStr(id.begin(), id.end())));\n        if (pwallet && pwallet->GetPubKey(CKeyID(id), pubkey)) {\n            obj.push_back(Pair(\"pubkey\", HexStr(pubkey)));\n        }\n        return obj;\n    }\n\n    UniValue operator()(const WitnessV0ScriptHash& id) const\n    {\n        UniValue obj(UniValue::VOBJ);\n        CScript subscript;\n        obj.push_back(Pair(\"isscript\", true));\n        obj.push_back(Pair(\"iswitness\", true));\n        obj.push_back(Pair(\"witness_version\", 0));\n        obj.push_back(Pair(\"witness_program\", HexStr(id.begin(), id.end())));\n        CRIPEMD160 hasher;\n        uint160 hash;\n        hasher.Write(id.begin(), 32).Finalize(hash.begin());\n        if (pwallet && pwallet->GetCScript(CScriptID(hash), subscript)) {\n            ProcessSubScript(subscript, obj);\n        }\n        return obj;\n    }\n\n    UniValue operator()(const WitnessUnknown& id) const\n    {\n        UniValue obj(UniValue::VOBJ);\n        CScript subscript;\n        obj.push_back(Pair(\"iswitness\", true));\n        obj.push_back(Pair(\"witness_version\", (int)id.version));\n        obj.push_back(Pair(\"witness_program\", HexStr(id.program, id.program + id.length)));\n        return obj;\n    }\n};\n#endif\n\nUniValue validateaddress(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            \"validateaddress \\\"address\\\"\\n\"\n            \"\\nReturn information about the given bitcoin address.\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"address\\\"     (string, required) The bitcoin address to validate\\n\"\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"isvalid\\\" : true|false,       (boolean) If the address is valid or not. If not, this is the only property returned.\\n\"\n            \"  \\\"address\\\" : \\\"address\\\",        (string) The bitcoin address validated\\n\"\n            \"  \\\"scriptPubKey\\\" : \\\"hex\\\",       (string) The hex encoded scriptPubKey generated by the address\\n\"\n            \"  \\\"ismine\\\" : true|false,        (boolean) If the address is yours or not\\n\"\n            \"  \\\"iswatchonly\\\" : true|false,   (boolean) If the address is watchonly\\n\"\n            \"  \\\"isscript\\\" : true|false,      (boolean, optional) If the address is P2SH or P2WSH. Not included for unknown witness types.\\n\"\n            \"  \\\"iswitness\\\" : true|false,     (boolean) If the address is P2WPKH, P2WSH, or an unknown witness version\\n\"\n            \"  \\\"witness_version\\\" : version   (number, optional) For all witness output types, gives the version number.\\n\"\n            \"  \\\"witness_program\\\" : \\\"hex\\\"     (string, optional) For all witness output types, gives the script or key hash present in the address.\\n\"\n            \"  \\\"script\\\" : \\\"type\\\"             (string, optional) The output script type. Only if \\\"isscript\\\" is true and the redeemscript is known. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash, witness_unknown\\n\"\n            \"  \\\"hex\\\" : \\\"hex\\\",                (string, optional) The redeemscript for the P2SH or P2WSH address\\n\"\n            \"  \\\"addresses\\\"                   (string, optional) Array of addresses associated with the known redeemscript (only if \\\"iswitness\\\" is false). This field is superseded by the \\\"pubkeys\\\" field and the address inside \\\"embedded\\\".\\n\"\n            \"    [\\n\"\n            \"      \\\"address\\\"\\n\"\n            \"      ,...\\n\"\n            \"    ]\\n\"\n            \"  \\\"pubkeys\\\"                     (string, optional) Array of pubkeys associated with the known redeemscript (only if \\\"script\\\" is \\\"multisig\\\")\\n\"\n            \"    [\\n\"\n            \"      \\\"pubkey\\\"\\n\"\n            \"      ,...\\n\"\n            \"    ]\\n\"\n            \"  \\\"sigsrequired\\\" : xxxxx        (numeric, optional) Number of signatures required to spend multisig output (only if \\\"script\\\" is \\\"multisig\\\")\\n\"\n            \"  \\\"pubkey\\\" : \\\"publickeyhex\\\",    (string, optional) The hex value of the raw public key, for single-key addresses (possibly embedded in P2SH or P2WSH)\\n\"\n            \"  \\\"embedded\\\" : {...},           (object, optional) information about the address embedded in P2SH or P2WSH, if relevant and known. It includes all validateaddress output fields for the embedded address, excluding \\\"isvalid\\\", metadata (\\\"timestamp\\\", \\\"hdkeypath\\\", \\\"hdmasterkeyid\\\") and relation to the wallet (\\\"ismine\\\", \\\"iswatchonly\\\", \\\"account\\\").\\n\"\n            \"  \\\"iscompressed\\\" : true|false,  (boolean) If the address is compressed\\n\"\n            \"  \\\"account\\\" : \\\"account\\\"         (string) DEPRECATED. The account associated with the address, \\\"\\\" is the default account\\n\"\n            \"  \\\"timestamp\\\" : timestamp,      (number, optional) The creation time of the key if available in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"  \\\"hdkeypath\\\" : \\\"keypath\\\"       (string, optional) The HD keypath if the key is HD and available\\n\"\n            \"  \\\"hdmasterkeyid\\\" : \\\"<hash160>\\\" (string, optional) The Hash160 of the HD master pubkey\\n\"\n            \"}\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"validateaddress\", \"\\\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\\\"\")\n            + HelpExampleRpc(\"validateaddress\", \"\\\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\\\"\")\n        );\n\n#ifdef ENABLE_WALLET\n    CWallet * const pwallet = GetWalletForJSONRPCRequest(request);\n\n    LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);\n#else\n    LOCK(cs_main);\n#endif\n\n    CTxDestination dest = DecodeDestination(request.params[0].get_str());\n    bool isValid = IsValidDestination(dest);\n\n    UniValue ret(UniValue::VOBJ);\n    ret.push_back(Pair(\"isvalid\", isValid));\n    if (isValid)\n    {\n        std::string currentAddress = EncodeDestination(dest);\n        ret.push_back(Pair(\"address\", currentAddress));\n\n        CScript scriptPubKey = GetScriptForDestination(dest);\n        ret.push_back(Pair(\"scriptPubKey\", HexStr(scriptPubKey.begin(), scriptPubKey.end())));\n\n#ifdef ENABLE_WALLET\n        isminetype mine = pwallet ? IsMine(*pwallet, dest) : ISMINE_NO;\n        ret.push_back(Pair(\"ismine\", bool(mine & ISMINE_SPENDABLE)));\n        ret.push_back(Pair(\"iswatchonly\", bool(mine & ISMINE_WATCH_ONLY)));\n        UniValue detail = boost::apply_visitor(DescribeAddressVisitor(pwallet), dest);\n        ret.pushKVs(detail);\n        if (pwallet && pwallet->mapAddressBook.count(dest)) {\n            ret.push_back(Pair(\"account\", pwallet->mapAddressBook[dest].name));\n        }\n        if (pwallet) {\n            const CKeyMetadata* meta = nullptr;\n            CKeyID key_id = GetKeyForDestination(*pwallet, dest);\n            if (!key_id.IsNull()) {\n                auto it = pwallet->mapKeyMetadata.find(key_id);\n                if (it != pwallet->mapKeyMetadata.end()) {\n                    meta = &it->second;\n                }\n            }\n            if (!meta) {\n                auto it = pwallet->m_script_metadata.find(CScriptID(scriptPubKey));\n                if (it != pwallet->m_script_metadata.end()) {\n                    meta = &it->second;\n                }\n            }\n            if (meta) {\n                ret.push_back(Pair(\"timestamp\", meta->nCreateTime));\n                if (!meta->hdKeypath.empty()) {\n                    ret.push_back(Pair(\"hdkeypath\", meta->hdKeypath));\n                    ret.push_back(Pair(\"hdmasterkeyid\", meta->hdMasterKeyID.GetHex()));\n                }\n            }\n        }\n#endif\n    }\n    return ret;\n}\n\n\/\/ Needed even with !ENABLE_WALLET, to pass (ignored) pointers around\nclass CWallet;\n\nUniValue createmultisig(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() < 2 || request.params.size() > 2)\n    {\n        std::string msg = \"createmultisig nrequired [\\\"key\\\",...]\\n\"\n            \"\\nCreates a multi-signature address with n signature of m keys required.\\n\"\n            \"It returns a json object with the address and redeemScript.\\n\"\n            \"\\nArguments:\\n\"\n            \"1. nrequired                    (numeric, required) The number of required signatures out of the n keys or addresses.\\n\"\n            \"2. \\\"keys\\\"                       (string, required) A json array of hex-encoded public keys\\n\"\n            \"     [\\n\"\n            \"       \\\"key\\\"                    (string) The hex-encoded public key\\n\"\n            \"       ,...\\n\"\n            \"     ]\\n\"\n\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"address\\\":\\\"multisigaddress\\\",  (string) The value of the new multisig address.\\n\"\n            \"  \\\"redeemScript\\\":\\\"script\\\"       (string) The string value of the hex-encoded redemption script.\\n\"\n            \"}\\n\"\n\n            \"\\nExamples:\\n\"\n            \"\\nCreate a multisig address from 2 public keys\\n\"\n            + HelpExampleCli(\"createmultisig\", \"2 \\\"[\\\\\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\\\\\",\\\\\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\\\\\"]\\\"\") +\n            \"\\nAs a json rpc call\\n\"\n            + HelpExampleRpc(\"createmultisig\", \"2, \\\"[\\\\\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\\\\\",\\\\\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\\\\\"]\\\"\")\n        ;\n        throw std::runtime_error(msg);\n    }\n\n    int required = request.params[0].get_int();\n\n    \/\/ Get the public keys\n    const UniValue& keys = request.params[1].get_array();\n    std::vector<CPubKey> pubkeys;\n    for (unsigned int i = 0; i < keys.size(); ++i) {\n        if (IsHex(keys[i].get_str()) && (keys[i].get_str().length() == 66 || keys[i].get_str().length() == 130)) {\n            pubkeys.push_back(HexToPubKey(keys[i].get_str()));\n        } else {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf(\"Invalid public key: %s\\nNote that from v0.16, createmultisig no longer accepts addresses.\"\n            \" Users must use addmultisigaddress to create multisig addresses with addresses known to the wallet.\", keys[i].get_str()));\n        }\n    }\n\n    \/\/ Construct using pay-to-script-hash:\n    CScript inner = CreateMultisigRedeemscript(required, pubkeys);\n    CScriptID innerID(inner);\n\n    UniValue result(UniValue::VOBJ);\n    result.push_back(Pair(\"address\", EncodeDestination(innerID)));\n    result.push_back(Pair(\"redeemScript\", HexStr(inner.begin(), inner.end())));\n\n    return result;\n}\n\nUniValue verifymessage(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 3)\n        throw std::runtime_error(\n            \"verifymessage \\\"address\\\" \\\"signature\\\" \\\"message\\\"\\n\"\n            \"\\nVerify a signed message\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"address\\\"         (string, required) The bitcoin address to use for the signature.\\n\"\n            \"2. \\\"signature\\\"       (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\\n\"\n            \"3. \\\"message\\\"         (string, required) The message that was signed.\\n\"\n            \"\\nResult:\\n\"\n            \"true|false   (boolean) If the signature is verified or not.\\n\"\n            \"\\nExamples:\\n\"\n            \"\\nUnlock the wallet for 30 seconds\\n\"\n            + HelpExampleCli(\"walletpassphrase\", \"\\\"mypassphrase\\\" 30\") +\n            \"\\nCreate the signature\\n\"\n            + HelpExampleCli(\"signmessage\", \"\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\" \\\"my message\\\"\") +\n            \"\\nVerify the signature\\n\"\n            + HelpExampleCli(\"verifymessage\", \"\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\" \\\"signature\\\" \\\"my message\\\"\") +\n            \"\\nAs json rpc\\n\"\n            + HelpExampleRpc(\"verifymessage\", \"\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\", \\\"signature\\\", \\\"my message\\\"\")\n        );\n\n    LOCK(cs_main);\n\n    std::string strAddress  = request.params[0].get_str();\n    std::string strSign     = request.params[1].get_str();\n    std::string strMessage  = request.params[2].get_str();\n\n    CTxDestination destination = DecodeDestination(strAddress);\n    if (!IsValidDestination(destination)) {\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid address\");\n    }\n\n    const CKeyID *keyID = boost::get<CKeyID>(&destination);\n    if (!keyID) {\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Address does not refer to key\");\n    }\n\n    bool fInvalid = false;\n    std::vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);\n\n    if (fInvalid)\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Malformed base64 encoding\");\n\n    CHashWriter ss(SER_GETHASH, 0);\n    ss << strMessageMagic;\n    ss << strMessage;\n\n    CPubKey pubkey;\n    if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))\n        return false;\n\n    return (pubkey.GetID() == *keyID);\n}\n\nUniValue signmessagewithprivkey(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 2)\n        throw std::runtime_error(\n            \"signmessagewithprivkey \\\"privkey\\\" \\\"message\\\"\\n\"\n            \"\\nSign a message with the private key of an address\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"privkey\\\"         (string, required) The private key to sign the message with.\\n\"\n            \"2. \\\"message\\\"         (string, required) The message to create a signature of.\\n\"\n            \"\\nResult:\\n\"\n            \"\\\"signature\\\"          (string) The signature of the message encoded in base 64\\n\"\n            \"\\nExamples:\\n\"\n            \"\\nCreate the signature\\n\"\n            + HelpExampleCli(\"signmessagewithprivkey\", \"\\\"privkey\\\" \\\"my message\\\"\") +\n            \"\\nVerify the signature\\n\"\n            + HelpExampleCli(\"verifymessage\", \"\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\" \\\"signature\\\" \\\"my message\\\"\") +\n            \"\\nAs json rpc\\n\"\n            + HelpExampleRpc(\"signmessagewithprivkey\", \"\\\"privkey\\\", \\\"my message\\\"\")\n        );\n\n    std::string strPrivkey = request.params[0].get_str();\n    std::string strMessage = request.params[1].get_str();\n\n    CBitcoinSecret vchSecret;\n    bool fGood = vchSecret.SetString(strPrivkey);\n    if (!fGood)\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid private key\");\n    CKey key = vchSecret.GetKey();\n    if (!key.IsValid())\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Private key outside allowed range\");\n\n    CHashWriter ss(SER_GETHASH, 0);\n    ss << strMessageMagic;\n    ss << strMessage;\n\n    std::vector<unsigned char> vchSig;\n    if (!key.SignCompact(ss.GetHash(), vchSig))\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Sign failed\");\n\n    return EncodeBase64(vchSig.data(), vchSig.size());\n}\n\nUniValue setmocktime(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            \"setmocktime timestamp\\n\"\n            \"\\nSet the local time to given timestamp (-regtest only)\\n\"\n            \"\\nArguments:\\n\"\n            \"1. timestamp  (integer, required) Unix seconds-since-epoch timestamp\\n\"\n            \"   Pass 0 to go back to using the system time.\"\n        );\n\n    if (!Params().MineBlocksOnDemand())\n        throw std::runtime_error(\"setmocktime for regression testing (-regtest mode) only\");\n\n    \/\/ For now, don't change mocktime if we're in the middle of validation, as\n    \/\/ this could have an effect on mempool time-based eviction, as well as\n    \/\/ IsCurrentForFeeEstimation() and IsInitialBlockDownload().\n    \/\/ TODO: figure out the right way to synchronize around mocktime, and\n    \/\/ ensure all call sites of GetTime() are accessing this safely.\n    LOCK(cs_main);\n\n    RPCTypeCheck(request.params, {UniValue::VNUM});\n    SetMockTime(request.params[0].get_int64());\n\n    return NullUniValue;\n}\n\nstatic UniValue RPCLockedMemoryInfo()\n{\n    LockedPool::Stats stats = LockedPoolManager::Instance().stats();\n    UniValue obj(UniValue::VOBJ);\n    obj.push_back(Pair(\"used\", uint64_t(stats.used)));\n    obj.push_back(Pair(\"free\", uint64_t(stats.free)));\n    obj.push_back(Pair(\"total\", uint64_t(stats.total)));\n    obj.push_back(Pair(\"locked\", uint64_t(stats.locked)));\n    obj.push_back(Pair(\"chunks_used\", uint64_t(stats.chunks_used)));\n    obj.push_back(Pair(\"chunks_free\", uint64_t(stats.chunks_free)));\n    return obj;\n}\n\n#ifdef HAVE_MALLOC_INFO\nstatic std::string RPCMallocInfo()\n{\n    char *ptr = nullptr;\n    size_t size = 0;\n    FILE *f = open_memstream(&ptr, &size);\n    if (f) {\n        malloc_info(0, f);\n        fclose(f);\n        if (ptr) {\n            std::string rv(ptr, size);\n            free(ptr);\n            return rv;\n        }\n    }\n    return \"\";\n}\n#endif\n\nUniValue getmemoryinfo(const JSONRPCRequest& request)\n{\n    \/* Please, avoid using the word \"pool\" here in the RPC interface or help,\n     * as users will undoubtedly confuse it with the other \"memory pool\"\n     *\/\n    if (request.fHelp || request.params.size() > 1)\n        throw std::runtime_error(\n            \"getmemoryinfo (\\\"mode\\\")\\n\"\n            \"Returns an object containing information about memory usage.\\n\"\n            \"Arguments:\\n\"\n            \"1. \\\"mode\\\" determines what kind of information is returned. This argument is optional, the default mode is \\\"stats\\\".\\n\"\n            \"  - \\\"stats\\\" returns general statistics about memory usage in the daemon.\\n\"\n            \"  - \\\"mallocinfo\\\" returns an XML string describing low-level heap state (only available if compiled with glibc 2.10+).\\n\"\n            \"\\nResult (mode \\\"stats\\\"):\\n\"\n            \"{\\n\"\n            \"  \\\"locked\\\": {               (json object) Information about locked memory manager\\n\"\n            \"    \\\"used\\\": xxxxx,          (numeric) Number of bytes used\\n\"\n            \"    \\\"free\\\": xxxxx,          (numeric) Number of bytes available in current arenas\\n\"\n            \"    \\\"total\\\": xxxxxxx,       (numeric) Total number of bytes managed\\n\"\n            \"    \\\"locked\\\": xxxxxx,       (numeric) Amount of bytes that succeeded locking. If this number is smaller than total, locking pages failed at some point and key data could be swapped to disk.\\n\"\n            \"    \\\"chunks_used\\\": xxxxx,   (numeric) Number allocated chunks\\n\"\n            \"    \\\"chunks_free\\\": xxxxx,   (numeric) Number unused chunks\\n\"\n            \"  }\\n\"\n            \"}\\n\"\n            \"\\nResult (mode \\\"mallocinfo\\\"):\\n\"\n            \"\\\"<malloc version=\\\"1\\\">...\\\"\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getmemoryinfo\", \"\")\n            + HelpExampleRpc(\"getmemoryinfo\", \"\")\n        );\n\n    std::string mode = request.params[0].isNull() ? \"stats\" : request.params[0].get_str();\n    if (mode == \"stats\") {\n        UniValue obj(UniValue::VOBJ);\n        obj.push_back(Pair(\"locked\", RPCLockedMemoryInfo()));\n        return obj;\n    } else if (mode == \"mallocinfo\") {\n#ifdef HAVE_MALLOC_INFO\n        return RPCMallocInfo();\n#else\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"mallocinfo is only available when compiled with glibc 2.10+\");\n#endif\n    } else {\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"unknown mode \" + mode);\n    }\n}\n\nuint32_t getCategoryMask(UniValue cats) {\n    cats = cats.get_array();\n    uint32_t mask = 0;\n    for (unsigned int i = 0; i < cats.size(); ++i) {\n        uint32_t flag = 0;\n        std::string cat = cats[i].get_str();\n        if (!GetLogCategory(&flag, &cat)) {\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"unknown logging category \" + cat);\n        }\n        if (flag == BCLog::NONE) {\n            return 0;\n        }\n        mask |= flag;\n    }\n    return mask;\n}\n\nUniValue logging(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() > 2) {\n        throw std::runtime_error(\n            \"logging ( <include> <exclude> )\\n\"\n            \"Gets and sets the logging configuration.\\n\"\n            \"When called without an argument, returns the list of categories with status that are currently being debug logged or not.\\n\"\n            \"When called with arguments, adds or removes categories from debug logging and return the lists above.\\n\"\n            \"The arguments are evaluated in order \\\"include\\\", \\\"exclude\\\".\\n\"\n            \"If an item is both included and excluded, it will thus end up being excluded.\\n\"\n            \"The valid logging categories are: \" + ListLogCategories() + \"\\n\"\n            \"In addition, the following are available as category names with special meanings:\\n\"\n            \"  - \\\"all\\\",  \\\"1\\\" : represent all logging categories.\\n\"\n            \"  - \\\"none\\\", \\\"0\\\" : even if other logging categories are specified, ignore all of them.\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"include\\\"        (array of strings, optional) A json array of categories to add debug logging\\n\"\n            \"     [\\n\"\n            \"       \\\"category\\\"   (string) the valid logging category\\n\"\n            \"       ,...\\n\"\n            \"     ]\\n\"\n            \"2. \\\"exclude\\\"        (array of strings, optional) A json array of categories to remove debug logging\\n\"\n            \"     [\\n\"\n            \"       \\\"category\\\"   (string) the valid logging category\\n\"\n            \"       ,...\\n\"\n            \"     ]\\n\"\n            \"\\nResult:\\n\"\n            \"{                   (json object where keys are the logging categories, and values indicates its status\\n\"\n            \"  \\\"category\\\": 0|1,  (numeric) if being debug logged or not. 0:inactive, 1:active\\n\"\n            \"  ...\\n\"\n            \"}\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"logging\", \"\\\"[\\\\\\\"all\\\\\\\"]\\\" \\\"[\\\\\\\"http\\\\\\\"]\\\"\")\n            + HelpExampleRpc(\"logging\", \"[\\\"all\\\"], \\\"[libevent]\\\"\")\n        );\n    }\n\n    uint32_t originalLogCategories = logCategories;\n    if (request.params[0].isArray()) {\n        logCategories |= getCategoryMask(request.params[0]);\n    }\n\n    if (request.params[1].isArray()) {\n        logCategories &= ~getCategoryMask(request.params[1]);\n    }\n\n    \/\/ Update libevent logging if BCLog::LIBEVENT has changed.\n    \/\/ If the library version doesn't allow it, UpdateHTTPServerLogging() returns false,\n    \/\/ in which case we should clear the BCLog::LIBEVENT flag.\n    \/\/ Throw an error if the user has explicitly asked to change only the libevent\n    \/\/ flag and it failed.\n    uint32_t changedLogCategories = originalLogCategories ^ logCategories;\n    if (changedLogCategories & BCLog::LIBEVENT) {\n        if (!UpdateHTTPServerLogging(logCategories & BCLog::LIBEVENT)) {\n            logCategories &= ~BCLog::LIBEVENT;\n            if (changedLogCategories == BCLog::LIBEVENT) {\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"libevent logging cannot be updated when using libevent before v2.1.1.\");\n            }\n        }\n    }\n\n    UniValue result(UniValue::VOBJ);\n    std::vector<CLogCategoryActive> vLogCatActive = ListActiveLogCategories();\n    for (const auto& logCatActive : vLogCatActive) {\n        result.pushKV(logCatActive.category, logCatActive.active);\n    }\n\n    return result;\n}\n\nUniValue createcriticaldatatx(const JSONRPCRequest& request)\n{\n    \/\/ TODO finish\n    \/\/\n    if (request.fHelp || request.params.size() != 3)\n        throw std::runtime_error(\n            \"createcriticaldatatx\\n\"\n            \"Create a critical data transaction\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"amount\\\"         (numeric or string, required) The amount in \" + CURRENCY_UNIT + \" to be spent.\\n\"\n            \"2. \\\"height\\\"         (numeric, required) The block height this transaction must be included in.\\n\"\n            \"3. \\\"criticalhash\\\"   (string, required) h* you want added to a coinbase\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"createcriticaldatatx\", \"\\\"amount\\\", \\\"height\\\", \\\"criticalhash\\\"\")\n            + HelpExampleRpc(\"createcriticaldatatx\", \"\\\"amount\\\", \\\"height\\\", \\\"criticalhash\\\"\")\n            );\n\n    \/\/ TODO remove after finished\n    throw JSONRPCError(RPC_INTERNAL_ERROR, \"Sorry, this function is not supported yet.\");\n\n    \/\/ Amount\n    CAmount nAmount = AmountFromValue(request.params[0]);\n    if (nAmount <= 0)\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid amount for send\");\n\n    int nHeight = request.params[1].get_int();\n\n    \/\/ Critical hash\n    uint256 hashCritical = uint256S(request.params[2].get_str());\n    if (hashCritical.IsNull())\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid h*\");\n\n#ifdef ENABLE_WALLET\n    \/\/ Create and send the transaction\n    std::string strError;\n    if (vpwallets.empty()){\n        strError = \"Error: no wallets are available\";\n        throw JSONRPCError(RPC_WALLET_ERROR, strError);\n    }\n    std::vector<CRecipient> vecSend;\n    CRecipient recipient = {CScript() << OP_0, nAmount, false};\n    vecSend.push_back(recipient);\n\n    LOCK2(cs_main, vpwallets[0]->cs_wallet);\n\n    CWalletTx wtx;\n    CReserveKey reservekey(vpwallets[0]);\n    CAmount nFeeRequired;\n    int nChangePosRet = -1;\n    \/\/TODO: set this as a real thing\n    CCoinControl cc;\n    if (!vpwallets[0]->CreateTransaction(vecSend, wtx, reservekey, nFeeRequired, nChangePosRet, strError, cc)) {\n        if (nAmount + nFeeRequired > vpwallets[0]->GetBalance())\n            strError = strprintf(\"Error: This transaction requires a transaction fee of at least %s\", FormatMoney(nFeeRequired));\n        throw JSONRPCError(RPC_WALLET_ERROR, strError);\n    }\n    CValidationState state;\n    if (!vpwallets[0]->CommitTransaction(wtx, reservekey, g_connman.get(), state)) {\n        strError = strprintf(\"Error: The transaction was rejected! Reason given: %s\", state.GetRejectReason());\n        throw JSONRPCError(RPC_WALLET_ERROR, strError);\n    }\n#endif\n\n    UniValue ret(UniValue::VOBJ);\n#ifdef ENABLE_WALLET\n    ret.push_back(Pair(\"txid\", wtx.GetHash().GetHex()));\n    ret.push_back(Pair(\"nChangePos\", nChangePosRet));\n#endif\n\n    return ret;\n}\n\nUniValue listsidechainctip(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() < 1)\n        throw std::runtime_error(\n            \"listsidechainctip\\n\"\n            \"Returns the crtitical transaction index pair for nSidechain\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"nsidechain\\\"      (numeric, required) The sidechain number\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"listsidechainctip\", \"\\\"nsidechain\\\"\")\n            + HelpExampleRpc(\"listsidechainctip\", \"\\\"nsidechain\\\"\")\n            );\n\n    \/\/ Is nSidechain valid?\n    int nSidechain = request.params[0].get_int();\n    if (!scdb.IsSidechainActive(nSidechain))\n        throw JSONRPCError(RPC_MISC_ERROR, \"Invalid sidechain number!\");\n\n    SidechainCTIP ctip;\n    if (!scdb.GetCTIP(nSidechain, ctip))\n        throw JSONRPCError(RPC_MISC_ERROR, \"No CTIP found for sidechain!\");\n\n    UniValue obj(UniValue::VOBJ);\n    obj.push_back(Pair(\"txid\", ctip.out.hash.ToString()));\n    obj.push_back(Pair(\"n\", (int64_t)ctip.out.n));\n    obj.push_back(Pair(\"amount\", ctip.amount));\n    obj.push_back(Pair(\"amountformatted\", FormatMoney(ctip.amount)));\n\n    return obj;\n}\n\nUniValue listsidechaindeposits(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() < 1)\n        throw std::runtime_error(\n            \"listsidechaindeposits\\n\"\n            \"List the most recent cached deposits for sidechain.\\n\"\n            \"Optionally limited to count. Note that this only has access to \"\n            \"deposits which are currently cached.\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"sidechainkey\\\"  (string, required) The sidechain key\\n\"\n            \"2. \\\"txid\\\"          (string, optional) Only return deposits after this deposit TXID\\n\"\n            \"3. \\\"n\\\"             (numeric, optional, required if txid is set) The output index of the previous argument txn\\n\"\n            \"4. \\\"count\\\"         (numeric, optional) The number of most recent deposits to list\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"listsidechaindeposits\", \"\\\"sidechainkey\\\", \\\"count\\\"\")\n            + HelpExampleRpc(\"listsidechaindeposits\", \"\\\"sidechainkey\\\", \\\"count\\\"\")\n            );\n\n#ifdef ENABLE_WALLET\n    \/\/ Check for active wallet\n    std::string strError;\n    if (vpwallets.empty()) {\n        strError = \"Error: no wallets are available\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_WALLET_ERROR, strError);\n    }\n#endif\n\n    \/\/ Check address bytes (sha256 hash)\n    std::string strSidechain = request.params[0].get_str();\n    uint256 hashSidechain = uint256S(strSidechain);\n    if (hashSidechain.IsNull()) {\n        std::string strError = \"Invalid sidechain key!\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_MISC_ERROR, strError);\n    }\n\n    \/\/ If TXID was passed in, make sure we also received N\n    if (request.params.size() > 1 && request.params.size() < 3) {\n        std::string strError = \"Output index 'n' is required if TXID is provided!\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_MISC_ERROR, strError);\n    }\n\n    \/\/ Was a TXID passed in?\n    uint256 txidKnown;\n    if (request.params.size() > 1) {\n        std::string strTXID = request.params[1].get_str();\n        txidKnown = uint256S(strTXID);\n        if (txidKnown.IsNull()) {\n            std::string strError = \"Invalid TXID!\";\n            LogPrintf(\"%s: %s\\n\", __func__, strError);\n            throw JSONRPCError(RPC_MISC_ERROR, strError);\n        }\n    }\n\n    \/\/ Was N passed in?\n    uint32_t nKnown = 0;\n    if (request.params.size() > 2) {\n        nKnown = request.params[2].get_int();\n    }\n\n    \/\/ Figure out the base58 encoding of the private key\n    CKey key;\n    key.Set(hashSidechain.begin(), hashSidechain.end(), false);\n    CBitcoinSecret vchSecret(key);\n\n    \/\/ Get number of recent deposits to return (default is all cached deposits)\n    bool fLimit = false;\n    int count = 0;\n    if (request.params.size() == 4) {\n        fLimit = true;\n        count = request.params[3].get_int();\n    }\n\n    UniValue arr(UniValue::VARR);\n\n#ifdef ENABLE_WALLET\n    std::vector<SidechainDeposit> vDeposit = scdb.GetDeposits(vchSecret.ToString());\n    if (!vDeposit.size()) {\n        std::string strError = \"No deposits in cache for this sidechain!\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_MISC_ERROR, strError);\n    }\n\n    for (auto rit = vDeposit.crbegin(); rit != vDeposit.crend(); rit++) {\n        const SidechainDeposit d = *rit;\n\n        \/\/ Check if we have reached a deposit the sidechain already has. The\n        \/\/ sidechain can pass in a TXID & output index 'n' to let us know what\n        \/\/ the latest deposit they've already received is.\n        if (!txidKnown.IsNull() && d.tx.GetHash() == txidKnown && d.nBurnIndex == nKnown)\n        {\n            LogPrintf(\"%s: Reached known deposit. TXID: %s n: %u\\n\",\n                    __func__, txidKnown.ToString(), nKnown);\n            break;\n        }\n\n        \/\/ Add deposit txid to set\n        uint256 txid = d.tx.GetHash();\n        std::set<uint256> setTxids;\n        setTxids.insert(txid);\n\n        LOCK(cs_main);\n\n        BlockMap::iterator it = mapBlockIndex.find(d.hashBlock);\n        if (it == mapBlockIndex.end()) {\n            std::string strError = \"Block hash not found\";\n            LogPrintf(\"%s: %s\\n\", __func__, strError);\n            throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n        }\n\n        CBlockIndex* pblockindex = it->second;\n        if (pblockindex == NULL) {\n            std::string strError = \"Block index null\";\n            LogPrintf(\"%s: %s\\n\", __func__, strError);\n            throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n        }\n\n        if (!chainActive.Contains(pblockindex)) {\n            std::string strError = \"Block not in active chain\";\n            LogPrintf(\"%s: %s\\n\", __func__, strError);\n            throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n        }\n#endif\n\n#ifdef ENABLE_WALLET\n        UniValue obj(UniValue::VOBJ);\n        obj.push_back(Pair(\"nsidechain\", d.nSidechain));\n        obj.push_back(Pair(\"strdest\", d.strDest));\n        obj.push_back(Pair(\"txhex\", EncodeHexTx(d.tx)));\n        obj.push_back(Pair(\"nburnindex\", (int)d.nBurnIndex));\n        obj.push_back(Pair(\"ntx\", (int)d.nTx));\n        obj.push_back(Pair(\"hashblock\", d.hashBlock.ToString()));\n\n        arr.push_back(obj);\n#endif\n        if (fLimit) {\n            count--;\n            if (count <= 0)\n                break;\n        }\n    }\n\n    return arr;\n}\n\nUniValue countsidechaindeposits(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            \"countsidechaindeposits\\n\"\n            \"Returns the number of deposits (for nSidechain) currently cached. \"\n            \"Note that this doesn't count all sidechain deposits, just the \"\n            \"number currently cached by the node.\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"nsidechain\\\"      (numeric, required) The sidechain number\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"countsidechaindeposits\", \"\\\"nsidechain\\\"\")\n            + HelpExampleRpc(\"countsidechaindeposits\", \"\\\"nsidechain\\\"\")\n            );\n\n#ifdef ENABLE_WALLET\n    \/\/ Check for active wallet\n    std::string strError;\n    if (vpwallets.empty()) {\n        strError = \"Error: no wallets are available\";\n        throw JSONRPCError(RPC_WALLET_ERROR, strError);\n    }\n#endif\n\n    \/\/ Is nSidechain valid?\n    int nSidechain = request.params[0].get_int();\n    if (!scdb.IsSidechainActive(nSidechain))\n        throw JSONRPCError(RPC_MISC_ERROR, \"Invalid sidechain number\");\n\n    int count = 0;\n\n    \/\/ Get latest deposit from sidechain DB deposit cache\n    std::vector<SidechainDeposit> vDeposit = scdb.GetDeposits(nSidechain);\n    count = vDeposit.size();\n\n    return count;\n}\n\nUniValue receivewithdrawalbundle(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 2)\n        throw std::runtime_error(\n            \"receivewithdrawalbundle\\n\"\n            \"Called by sidechain to announce new withdrawal for verification\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"nsidechain\\\"      (int, required) The sidechain number\\n\"\n            \"2. \\\"rawtx\\\"           (string, required) The raw transaction hex\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"receivewithdrawalbundle\", \"\")\n            + HelpExampleRpc(\"receivewithdrawalbundle\", \"\")\n     );\n\n#ifndef ENABLE_WALLET\n    strError = \"Error: Wallet disabled\";\n    LogPrintf(\"%s: %s\\n\", __func__, strError);\n    throw JSONRPCError(RPC_WALLET_ERROR, strError);\n#endif\n\n#ifdef ENABLE_WALLET\n    \/\/ Check for active wallet\n    std::string strError;\n    CWallet * const pwallet = GetWalletForJSONRPCRequest(request);\n    if (!pwallet) {\n        strError = \"Error: no wallets are available\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_WALLET_ERROR, strError);\n    }\n#endif\n\n    \/\/ Is nSidechain valid?\n    int nSidechain = request.params[0].get_int();\n    if (!scdb.IsSidechainActive(nSidechain)) {\n        strError = \"Invalid sidechain number!\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_MISC_ERROR, strError);\n    }\n\n    \/\/ Create CTransaction from hex\n    CMutableTransaction mtx;\n    std::string hex = request.params[1].get_str();\n    if (!DecodeHexTx(mtx, hex)) {\n        strError = \"Invalid transaction hex!\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_MISC_ERROR, strError);\n    }\n\n    CTransaction withdrawal(mtx);\n\n    if (withdrawal.IsNull()) {\n        strError = \"Invalid withdrawal hex\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_MISC_ERROR, strError);\n    }\n\n    \/\/ Reject the withdrawal if it spends more than the sidechain's CTIP as it won't\n    \/\/ be accepted anyway\n    CAmount amount = withdrawal.GetValueOut();\n    std::vector<COutput> vSidechainCoin;\n    CScript scriptPubKey;\n    if (!scdb.GetSidechainScript(nSidechain, scriptPubKey)) {\n        strError = \"Cannot get script for sidechain!\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_MISC_ERROR, strError);\n    }\n\n    SidechainCTIP ctip;\n    if (!scdb.GetCTIP(nSidechain, ctip)) {\n        strError = \"Rejecting withdrawal: No CTIP found!\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_MISC_ERROR, strError);\n    }\n\n    if (amount > ctip.amount) {\n        strError = \"Rejecting withdrawal: Withdrawn amount greater than CTIP amount!\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_MISC_ERROR, strError);\n    }\n\n    \/\/ Check for the required withdrawal change return destination OP_RETURN output\n    for (size_t i = 0; i < mtx.vout.size(); i++) {\n        const CScript& scriptPubKey = mtx.vout[i].scriptPubKey;\n        if (!scriptPubKey.size())\n            continue;\n        if (scriptPubKey.front() != OP_RETURN)\n            continue;\n\n        if (scriptPubKey.size() < 3) {\n            strError = \"Rejecting Withdrawal: First OP_RETURN output invalid size (too small)!\\n\";\n            LogPrintf(\"%s: %s\\n\", __func__, strError);\n            throw JSONRPCError(RPC_MISC_ERROR, strError);\n        }\n\n        CScript::const_iterator pDest = scriptPubKey.begin() + 1;\n        opcodetype opcode;\n        std::vector<unsigned char> vch;\n        if (!scriptPubKey.GetOp(pDest, opcode, vch) || vch.empty()) {\n            strError = \"Rejecting Withdrawal: First OP_RETURN output invalid. (Failed GetOp)!\\n\";\n            LogPrintf(\"%s: %s\\n\", __func__, strError);\n            throw JSONRPCError(RPC_MISC_ERROR, strError);\n        }\n        std::string strDest((const char*)vch.data(), vch.size());\n        if (strDest != SIDECHAIN_WITHDRAWAL_RETURN_DEST) {\n            strError = \"Rejecting Withdrawal: First OP_RETURN output invalid. (incorrect dest)!\\n\";\n            LogPrintf(\"%s: %s\\n\", __func__, strError);\n            throw JSONRPCError(RPC_MISC_ERROR, strError);\n        }\n        break;\n    }\n\n    \/\/ Add Withdrawal to our local cache so that we can create a Withdrawal hash commitment\n    \/\/ in the next block we mine to begin the verification process\n    if (!scdb.CacheWithdrawalTx(withdrawal, nSidechain)) {\n        strError = \"Withdrawal rejected from cache (duplicate?)\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_MISC_ERROR, strError);\n    }\n\n    \/\/ Return Withdrawal hash to verify it has been received\n    UniValue ret(UniValue::VOBJ);\n    ret.push_back(Pair(\"wtxid\", withdrawal.GetHash().GetHex()));\n    return ret;\n}\n\nUniValue verifybmm(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 2)\n        throw std::runtime_error(\n            \"verifybmm\\n\"\n            \"Check if a mainchain block includes BMM for a sidechain h*\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"blockhash\\\"      (string, required) mainchain blockhash with h*\\n\"\n            \"2. \\\"bmmhash\\\"        (string, required) h* to locate\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"verifybmm\", \"\\\"blockhash\\\", \\\"bmmhash\\\"\")\n            + HelpExampleRpc(\"verifybmm\", \"\\\"blockhash\\\", \\\"bmmhash\\\"\")\n            );\n\n    uint256 hashBlock = uint256S(request.params[0].get_str());\n    uint256 hashBMM = uint256S(request.params[1].get_str());\n\n    if (!mapBlockIndex.count(hashBlock)) {\n        std::string strError = \"Block not found\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    CBlockIndex* pblockindex = mapBlockIndex[hashBlock];\n    if (pblockindex == NULL)\n    {\n        std::string strError = \"pblockindex null\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    CBlock block;\n    if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))\n    {\n        std::string strError = \"Failed to read block from disk\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    if (!block.vtx.size()) {\n        std::string strError = \"No txns in block\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    bool fBMMFound = false;\n    const CTransaction &txCoinbase = *(block.vtx[0]);\n    for (const CTxOut& out : txCoinbase.vout) {\n        const CScript& scriptPubKey = out.scriptPubKey;\n\n        if (scriptPubKey.size() < sizeof(uint256) + 5)\n            continue;\n        if (scriptPubKey[0] != OP_RETURN)\n            continue;\n\n        \/\/ TODO add script function to check for commit & return data\n\n        \/\/ Get h*\n        std::vector<unsigned char> vch (scriptPubKey.begin() + 5, scriptPubKey.begin() + 37);\n\n        \/\/ TODO return the bytes\n        \/\/ Get Bytes\n        if (scriptPubKey.size() > 37) {\n            std::vector<unsigned char> vchBytes(scriptPubKey.begin() + 37, scriptPubKey.end());\n        }\n\n        if (hashBMM == uint256(vch))\n            fBMMFound = true;\n    }\n\n    if (!fBMMFound) {\n        std::string strError = \"h* not found in block\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    UniValue ret(UniValue::VOBJ);\n    UniValue obj(UniValue::VOBJ);\n    obj.push_back(Pair(\"txid\", txCoinbase.GetHash().ToString()));\n    obj.push_back(Pair(\"time\", itostr(block.nTime)));\n    ret.push_back(Pair(\"bmm\", obj));\n\n    return ret;\n}\n\nUniValue verifydeposit(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 3)\n        throw std::runtime_error(\n            \"verifydeposit\\n\"\n            \"Check if a mainchain block includes valid deposit with txid.\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"blockhash\\\"      (string, required) mainchain blockhash with deposit\\n\"\n            \"2. \\\"txid\\\"           (string, required) deposit txid to locate\\n\"\n            \"3. \\\"nTx\\\"            (int, required) deposit tx number in block\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"verifybmm\", \"\\\"blockhash\\\", \\\"txid\\\"\")\n            + HelpExampleRpc(\"verifybmm\", \"\\\"blockhash\\\", \\\"txid\\\"\")\n            );\n\n    uint256 hashBlock = uint256S(request.params[0].get_str());\n    uint256 txid = uint256S(request.params[1].get_str());\n    int nTx = request.params[2].get_int();\n\n    if (!mapBlockIndex.count(hashBlock)) {\n        std::string strError = \"Block not found\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    CBlockIndex* pblockindex = mapBlockIndex[hashBlock];\n    if (pblockindex == NULL)\n    {\n        std::string strError = \"pblockindex null\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    if (!scdb.HaveDepositCached(txid)) {\n        std::string strError = \"SCDB does not know deposit\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    CBlock block;\n    if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))\n    {\n        std::string strError = \"Failed to read block from disk\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    if (!block.vtx.size()) {\n        std::string strError = \"No txns in block\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    if ((int)block.vtx.size() <= nTx) {\n        std::string strError = \"nTx out of range for block\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    const CTransaction &tx = *(block.vtx[nTx]);\n    if (tx.GetHash() != txid) {\n        std::string strError = \"Transaction at block index specified does not match txid\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    SidechainDeposit deposit;\n    if (!scdb.TxnToDeposit(tx, nTx, hashBlock, deposit)) {\n        std::string strError = \"Invalid deposit transaction format\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    return tx.GetHash().ToString();\n}\n\nUniValue listpreviousblockhashes(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 0)\n        throw std::runtime_error(\n            \"listpreviousblockhashes\\n\"\n            \"List the 5 most recent mainchain block hashes. Used by sidechains \" \\\n            \"to help search for BMM commitments.\\n\"\n            \"\\nArguments:\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"listpreviousblockhashes\", \"\")\n            + HelpExampleRpc(\"listpreviousblockhashes\", \"\")\n            );\n\n    int nHeight = chainActive.Height();\n    int nStart = nHeight - 4;\n    if (!(nHeight > 0) || !(nStart > 0))\n        throw JSONRPCError(RPC_INTERNAL_ERROR, \"Insufficient blocks connected to complete request!\");\n\n    std::vector<uint256> vHash;\n    for (int i = nStart; i <= nHeight; i++) {\n        uint256 hashBlock = chainActive[i]->GetBlockHash();\n        vHash.push_back(hashBlock);\n    }\n\n    UniValue ret(UniValue::VARR);\n    for (const uint256& hash : vHash) {\n        UniValue obj(UniValue::VOBJ);\n        obj.push_back(Pair(\"hash\", hash.ToString()));\n        ret.push_back(obj);\n    }\n\n    return ret;\n}\n\nUniValue listactivesidechains(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 0)\n        throw std::runtime_error(\n            \"listactivesidechains\\n\"\n            \"List active sidechains.\\n\"\n            \"\\nArguments:\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"listactivesidechains\", \"\")\n            + HelpExampleRpc(\"listactivesidechains\", \"\")\n            );\n\n    std::vector<Sidechain> vActive = scdb.GetActiveSidechains();\n    UniValue ret(UniValue::VARR);\n    for (const Sidechain& s : vActive) {\n        UniValue obj(UniValue::VOBJ);\n        obj.push_back(Pair(\"title\", s.title));\n        obj.push_back(Pair(\"description\", s.description));\n        obj.push_back(Pair(\"privatekey\", s.strPrivKey));\n        obj.push_back(Pair(\"keyid\", s.strKeyID));\n        obj.push_back(Pair(\"nversion\", s.nVersion));\n        obj.push_back(Pair(\"hashid1\", s.hashID1.ToString()));\n        obj.push_back(Pair(\"hashid2\", s.hashID2.ToString()));\n\n        ret.push_back(obj);\n    }\n\n    return ret;\n}\n\nUniValue listsidechainactivationstatus(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 0)\n        throw std::runtime_error(\n            \"listsidechainactivationstatus\\n\"\n            \"List activation status of all pending sidechains.\\n\"\n            \"\\nArguments:\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"listsidechainactivationstatus\", \"\")\n            + HelpExampleRpc(\"listsidechainactivationstatus\", \"\")\n            );\n\n    std::vector<SidechainActivationStatus> vStatus;\n    vStatus = scdb.GetSidechainActivationStatus();\n\n    UniValue ret(UniValue::VARR);\n    for (const SidechainActivationStatus& s : vStatus) {\n        UniValue obj(UniValue::VOBJ);\n        obj.push_back(Pair(\"title\", s.proposal.title));\n        obj.push_back(Pair(\"description\", s.proposal.description));\n        obj.push_back(Pair(\"privatekey\", s.proposal.strPrivKey));\n        obj.push_back(Pair(\"keyid\", s.proposal.strKeyID));\n        obj.push_back(Pair(\"nage\", s.nAge));\n        obj.push_back(Pair(\"nfail\", s.nFail));\n\n        ret.push_back(obj);\n    }\n\n    return ret;\n}\n\nUniValue listsidechainproposals(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 0)\n        throw std::runtime_error(\n            \"listsidechainproposals\\n\"\n            \"List your own cached sidechain proposals\\n\"\n            \"\\nArguments:\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"listsidechainproposals\", \"\")\n            + HelpExampleRpc(\"listsidechainproposals\", \"\")\n            );\n\n    std::vector<Sidechain> vProposal = scdb.GetSidechainProposals();\n    UniValue ret(UniValue::VARR);\n    for (const Sidechain& s : vProposal) {\n        UniValue obj(UniValue::VOBJ);\n        obj.push_back(Pair(\"title\", s.title));\n        obj.push_back(Pair(\"description\", s.description));\n        obj.push_back(Pair(\"privatekey\", s.strPrivKey));\n        obj.push_back(Pair(\"keyid\", s.strKeyID));\n        obj.push_back(Pair(\"nversion\", s.nVersion));\n        obj.push_back(Pair(\"hashid1\", s.hashID1.ToString()));\n        obj.push_back(Pair(\"hashid2\", s.hashID2.ToString()));\n\n        ret.push_back(obj);\n    }\n\n    return ret;\n}\n\nUniValue getsidechainactivationstatus(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            \"getsidechainactivationstatus\\n\"\n            \"List activation status for nSidechain.\\n\"\n            \"\\nArguments:\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getsidechainactivationstatus\", \"\")\n            + HelpExampleRpc(\"getsidechainactivationstatus\", \"\")\n            );\n\n    \/\/ TODO\n    std::vector<SidechainActivationStatus> vStatus;\n    vStatus = scdb.GetSidechainActivationStatus();\n\n    UniValue ret(UniValue::VARR);\n    for (const SidechainActivationStatus& s : vStatus) {\n        UniValue obj(UniValue::VOBJ);\n        obj.push_back(Pair(\"title\", s.proposal.title));\n        obj.push_back(Pair(\"description\", s.proposal.description));\n        obj.push_back(Pair(\"privatekey\", s.proposal.strPrivKey));\n        obj.push_back(Pair(\"keyid\", s.proposal.strKeyID));\n        obj.push_back(Pair(\"nage\", s.nAge));\n        obj.push_back(Pair(\"nfail\", s.nFail));\n        obj.push_back(Pair(\"proposalhash\", s.proposal.GetHash().ToString()));\n\n        ret.push_back(obj);\n    }\n\n    return ret;\n}\n\nUniValue createsidechainproposal(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() < 4 || request.params.size() > 7)\n        throw std::runtime_error(\n            \"createsidechainproposal\\n\"\n            \"Generates a sidechain proposal to be included in the next block \" \\\n            \"mined by this node.\\n\"\\\n            \"Note that this will not broadcast the proposal to other nodes. \" \\\n            \"You must mine a block which includes your proposal to complete \" \\\n            \"the process. Pending proposals created by this node will \" \\\n            \"automatically be included in the soonest block mined possible.\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"nsidechain\\\"   (numeric, required) sidechain slot number\\n\"\n            \"2. \\\"title\\\"        (string, required) sidechain title\\n\"\n            \"3. \\\"description\\\"  (string, required) sidechain description\\n\"\n            \"4. \\\"keyhash\\\"      (string, required) any SHA256 hash (used to generate private key)\\n\"\n            \"5. \\\"version\\\"      (numeric, optional) sidechain \/ proposal version\\n\"\n            \"6. \\\"hashid1\\\"      (string, optional) 256 bits used to identify sidechain\\n\"\n            \"7. \\\"hashid2\\\"      (string, optional) 160 bits used to identify sidechain\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"createsidechainproposal\", \"\")\n            + HelpExampleRpc(\"createsidechainproposal\", \"\")\n            );\n\n    int nSidechain = request.params[0].get_int();\n    if (nSidechain < 0 || nSidechain > 255)\n        throw JSONRPCError(RPC_MISC_ERROR, \"Invalid sidechain number!\");\n\n    std::string strTitle = request.params[1].get_str();\n    std::string strDescription = request.params[2].get_str();\n    std::string strHash = request.params[3].get_str();\n\n    int nVersion = -1;\n    if (request.params.size() >= 5)\n        nVersion = request.params[4].get_int();\n\n    std::string strHashID1 = \"\";\n    std::string strHashID2 = \"\";\n    if (request.params.size() >= 6) {\n        strHashID1 = request.params[5].get_str();\n        if (strHashID1.size() != 64)\n            throw JSONRPCError(RPC_MISC_ERROR, \"HashID1 size invalid!\");\n    }\n    if (request.params.size() == 7) {\n        strHashID2 = request.params[6].get_str();\n        if (strHashID2.size() != 40)\n            throw JSONRPCError(RPC_MISC_ERROR, \"HashID2 size invalid!\");\n    }\n\n    if (strTitle.empty())\n        throw JSONRPCError(RPC_INTERNAL_ERROR, \"Sidechain must have a title!\");\n\n    \/\/ TODO maybe we should allow sidechains with no description? Anyways this\n    \/\/ isn't a consensus rule right now\n    if (strDescription.empty())\n        throw JSONRPCError(RPC_INTERNAL_ERROR, \"Sidechain must have a description!\");\n\n    uint256 hash = uint256S(strHash);\n    if (hash.IsNull())\n        throw JSONRPCError(RPC_INTERNAL_ERROR, \"Invalid sidechain key hash!\");\n\n    CKey key;\n    key.Set(hash.begin(), hash.end(), false);\n    if (!key.IsValid())\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Private key outside allowed range\");\n\n    CBitcoinSecret vchSecret(key);\n    if (!vchSecret.IsValid())\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid private key encoding\");\n\n    CPubKey pubkey = key.GetPubKey();\n    assert(key.VerifyPubKey(pubkey));\n    CKeyID vchAddress = pubkey.GetID();\n\n    \/\/ Generate deposit script\n    CScript sidechainScript = CScript() << OP_DUP << OP_HASH160 << ToByteVector(vchAddress) << OP_EQUALVERIFY << OP_CHECKSIG;\n\n    Sidechain proposal;\n    proposal.nSidechain = nSidechain;\n    proposal.title = strTitle;\n    proposal.description = strDescription;\n    proposal.strPrivKey = vchSecret.ToString();\n    proposal.strKeyID = HexStr(vchAddress);\n    proposal.scriptPubKey = sidechainScript;\n    if (nVersion >= 0)\n        proposal.nVersion = nVersion;\n    else\n        proposal.nVersion = 0;\n    if (!strHashID1.empty())\n        proposal.hashID1 = uint256S(strHashID1);\n    if (!strHashID2.empty())\n        proposal.hashID2 = uint160S(strHashID2);\n\n    \/\/ Cache proposal so that it can be added to the next block we mine\n    scdb.CacheSidechainProposals(std::vector<Sidechain>{proposal});\n\n    \/\/ Cache the hash of the sidechain to ACK it\n    scdb.CacheSidechainHashToAck(proposal.GetHash());\n\n    UniValue obj(UniValue::VOBJ);\n    obj.push_back(Pair(\"nSidechain\", proposal.nVersion));\n    obj.push_back(Pair(\"title\", proposal.title));\n    obj.push_back(Pair(\"description\", proposal.description));\n    obj.push_back(Pair(\"privatekey\", proposal.strPrivKey));\n    obj.push_back(Pair(\"keyid\", proposal.strKeyID));\n    obj.push_back(Pair(\"version\", proposal.nVersion));\n    obj.push_back(Pair(\"hashID1\", proposal.hashID1.ToString()));\n    obj.push_back(Pair(\"hashID2\", proposal.hashID2.ToString()));\n\n    return obj;\n}\n\nUniValue setwithdrawalvote(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 3)\n        throw std::runtime_error(\n            \"setwithdrawalvote\\n\"\n            \"Set custom vote for sidechain Withdrawal.\\n\"\n            \"\\nArguments:\\n\"\n            \"1. vote (\\\"upvote\\\"\/\\\"downvote\\\"\/\\\"abstain\\\")  (string, required) vote\\n\"\n            \"2. nsidechain                            (numeric, required) Sidechain number of Withdrawal\\n\"\n            \"3. hash                                  (string, required) Hash of the withdrawal\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"setwithdrawalvote\", \"\")\n            + HelpExampleRpc(\"setwithdrawalvote\", \"\")\n            );\n\n    std::string strVote = request.params[0].get_str();\n    if (strVote != \"upvote\" && strVote != \"downvote\" && strVote != \"abstain\")\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid vote (must be \\\"upvote\\\", \\\"downvote\\\" or \\\"abstain\\\")\");\n\n    \/\/ nSidechain\n    int nSidechain = request.params[1].get_int();\n\n    if (!scdb.IsSidechainActive(nSidechain))\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Sidechain number\");\n\n    std::string strHash = request.params[2].get_str();\n    if (strHash.size() != 64)\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Withdrawal hash length\");\n\n    uint256 hash = uint256S(strHash);\n    if (hash.IsNull())\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Withdrawal hash\");\n\n    SidechainCustomVote vote;\n    vote.nSidechain = nSidechain;\n    vote.hash = hash;\n\n    if (strVote == \"upvote\") {\n        vote.vote = SCDB_UPVOTE;\n    }\n    else\n    if (strVote == \"downvote\") {\n        vote.vote = SCDB_DOWNVOTE;\n    }\n    else\n    if (strVote == \"abstain\") {\n        vote.vote = SCDB_ABSTAIN;\n    }\n\n    \/\/ TODO improve error message\n    if (!scdb.CacheCustomVotes(std::vector<SidechainCustomVote> {vote}))\n        throw JSONRPCError(RPC_MISC_ERROR, \"Failed to cache Withdrawal vote!\");\n\n    return NullUniValue;\n}\n\nUniValue clearwithdrawalvotes(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size())\n        throw std::runtime_error(\n            \"clearwithdrawalvotes\\n\"\n            \"Delete all custom Withdrawal vote(s).\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"clearwithdrawalvotes\", \"\")\n            + HelpExampleRpc(\"clearwithdrawalvotes\", \"\")\n            );\n\n    scdb.ResetWithdrawalVotes();\n\n    return NullUniValue;\n}\n\nUniValue listwithdrawalvotes(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 0)\n        throw std::runtime_error(\n            \"listwithdrawalvotes\\n\"\n            \"List custom votes for sidechain Withdrawal(s).\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"listwithdrawalvotes\", \"\")\n            + HelpExampleRpc(\"listwithdrawalvotes\", \"\")\n            );\n\n    std::vector<SidechainCustomVote> vCustomVote = scdb.GetCustomVoteCache();\n\n    UniValue ret(UniValue::VARR);\n\n    for (const SidechainCustomVote& v : vCustomVote) {\n        std::string strVote = \"\";\n        if (v.vote == SCDB_UPVOTE) {\n            strVote = \"upvote\";\n        }\n        else\n        if (v.vote == SCDB_DOWNVOTE) {\n            strVote = \"downvote\";\n        }\n        else\n        if (v.vote == SCDB_ABSTAIN) {\n            strVote = \"abstain\";\n        }\n\n        UniValue obj(UniValue::VOBJ);\n        obj.push_back(Pair(\"nSidechain\", v.nSidechain));\n        obj.push_back(Pair(\"vote\", strVote));\n        obj.push_back(Pair(\"hash\", v.hash.ToString()));\n        ret.push_back(obj);\n    }\n\n    return ret;\n}\n\nUniValue getaveragefee(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() > 2)\n        throw std::runtime_error(\n            \"getaveragefee\\n\"\n            \"\\nArguments:\\n\"\n            \"1. block_count     (numeric, optional, default=6) number of blocks to scan\\n\"\n            \"2. start_height    (numeric, optional, default=current block count) block height to start from\\n\"\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"fee\\\" : x.x,   (numeric) average of fees in \" + CURRENCY_UNIT + \"\/kB\\n\"\n            \"}\\n\"\n            \"\\n\"\n            \"\\nExample:\\n\"\n            + HelpExampleCli(\"getaveragefee\", \"6 10\")\n            );\n\n    int nBlocks = 6;\n    if (request.params.size() >= 1)\n        nBlocks = request.params[0].get_int();\n\n    int nHeight = chainActive.Height();\n    if (request.params.size() == 2) {\n        int nHeightIn = request.params[1].get_int();\n        if (nHeightIn > nHeight)\n            throw JSONRPCError(RPC_MISC_ERROR, \"Invalid start height!\");\n\n        nHeight = nHeightIn;\n    }\n\n    if (nBlocks > nHeight)\n        throw JSONRPCError(RPC_INTERNAL_ERROR, \"Invalid number of blocks!\");\n\n    int nTx = 0;\n    CAmount nTotalFees = 0;\n    for (int i = nHeight; i >= (nHeight - nBlocks); i--) {\n        uint256 hashBlock = chainActive[i]->GetBlockHash();\n\n        if (mapBlockIndex.count(hashBlock) == 0)\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Block not found\");\n\n        CBlock block;\n        CBlockIndex* pblockindex = mapBlockIndex[hashBlock];\n        if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)\n            throw JSONRPCError(RPC_MISC_ERROR, \"Block not available (pruned data)\");\n\n        if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))\n            throw JSONRPCError(RPC_MISC_ERROR, \"Block not found on disk\");\n\n        \/\/ We don't have the coins (they are spent) to look up the transaction\n        \/\/ input amounts for calculation of fees. Instead, get the block subsidy\n        \/\/ for the height and subtract it from the coinbase output amount to\n        \/\/ estimate fees paid in the block.\n        CAmount nSubsidy = GetBlockSubsidy(i, Params().GetConsensus());\n        CAmount nCoinbase = block.vtx[0]->GetValueOut();\n\n        \/\/ Record total fees in the block\n        nTotalFees += nCoinbase - nSubsidy;\n        \/\/ Record number of transactions\n        nTx += block.vtx.size();\n    }\n\n    UniValue result(UniValue::VOBJ);\n    result.push_back(Pair(\"feeaverage\", ValueFromAmount(nTotalFees \/ nTx)));\n    return result;\n}\n\nUniValue getworkscore(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 2)\n        throw std::runtime_error(\n            \"getworkscore \\\"nsidechain\\\" \\\"hash\\\")\\n\"\n            \"Request the workscore of a Withdrawal\\n\"\n            \"\\nArguments:\\n\"\n            \"1. nsidechain     (numeric, required) Sidechain number to look up Withdrawal of\\n\"\n            \"2. hash           (string, required) Hash of the Withdrawal\\n\"\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"workscore\\\" : x,   (numeric) workscore of Withdrawal\\n\"\n            \"}\\n\"\n            \"\\n\"\n            \"\\nExample:\\n\"\n            + HelpExampleCli(\"getworkscore\", \"0 hash\")\n            );\n\n    \/\/ nSidechain\n    int nSidechain = request.params[0].get_int();\n\n    if (!scdb.IsSidechainActive(nSidechain))\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Sidechain number\");\n\n    std::string strHash = request.params[1].get_str();\n    if (strHash.size() != 64)\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Withdrawal hash length\");\n\n    uint256 hash = uint256S(strHash);\n    if (hash.IsNull())\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Withdrawal hash\");\n\n    std::vector<SidechainWithdrawalState> vState = scdb.GetState(nSidechain);\n    if (vState.empty())\n        throw JSONRPCError(RPC_TYPE_ERROR, \"No Withdrawal(s) in SCDB for sidechain\");\n\n    int nWorkScore = -1;\n    for (const SidechainWithdrawalState& s : vState) {\n        if (s.hash == hash) {\n            nWorkScore = s.nWorkScore;\n            break;\n        }\n    }\n\n    if (nWorkScore == -1)\n        throw JSONRPCError(RPC_TYPE_ERROR, \"No Withdrawal workscore in SCDB\");\n\n    return nWorkScore;\n}\n\nUniValue listwithdrawalstatus(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            \"listwithdrawalstatus \\\"nsidechain\\\")\\n\"\n            \"Request the workscore of a Withdrawal\\n\"\n            \"\\nArguments:\\n\"\n            \"1. nsidechain     (numeric, required) Sidechain number to look up Withdrawal(s) of\\n\"\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"hash\\\" : (string) hash of Withdrawal\\n\"\n            \"  \\\"nblocksleft\\\" : x, (numeric) verification blocks remaining\\n\"\n            \"  \\\"workscore\\\" : x, (numeric) workscore of Withdrawal\\n\"\n            \"}\\n\"\n            \"\\n\"\n            \"\\nExample:\\n\"\n            + HelpExampleCli(\"getworkscore\", \"0 hash\")\n            );\n\n    \/\/ nSidechain\n    int nSidechain = request.params[0].get_int();\n\n    if (!scdb.IsSidechainActive(nSidechain))\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Sidechain number\");\n\n    std::vector<SidechainWithdrawalState> vState = scdb.GetState(nSidechain);\n    if (vState.empty())\n        throw JSONRPCError(RPC_TYPE_ERROR, \"No Withdrawal(s) in SCDB for sidechain\");\n\n    UniValue ret(UniValue::VARR);\n    for (const SidechainWithdrawalState& s : vState) {\n        UniValue obj(UniValue::VOBJ);\n\n        obj.push_back(Pair(\"hash\", s.hash.ToString()));\n        obj.push_back(Pair(\"nblocksleft\", s.nBlocksLeft));\n        obj.push_back(Pair(\"nworkscore\", s.nWorkScore));\n\n        ret.push_back(obj);\n    }\n\n    return ret;\n}\n\nUniValue listcachedwithdrawaltx(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            \"listcachedwithdrawaltx\\n\"\n            \"List my cached Withdrawal(s) for nSidechain\\n\"\n            \"\\nArguments:\\n\"\n            \"1. nsidechain     (numeric, required) Sidechain number to list Withdrawal(s) of\\n\"\n            \"\\nResult: (array)\\n\"\n            \"{\\n\"\n            \"  \\\"hash\\\" : x (string) hash of Withdrawal\\n\"\n            \"}\\n\"\n            \"\\n\"\n            \"\\nExample:\\n\"\n            + HelpExampleCli(\"listcachedwithdrawaltransactions\", \"0\")\n            );\n\n    \/\/ nSidechain\n    int nSidechain = request.params[0].get_int();\n\n    if (!scdb.IsSidechainActive(nSidechain))\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Sidechain number\");\n\n    std::vector<SidechainWithdrawalState> vState = scdb.GetState(nSidechain);\n    if (vState.empty())\n        throw JSONRPCError(RPC_TYPE_ERROR, \"No Withdrawal(s) in SCDB for sidechain\");\n\n    UniValue ret(UniValue::VARR);\n    for (const SidechainWithdrawalState& s : vState) {\n        UniValue obj(UniValue::VOBJ);\n        obj.push_back(Pair(\"hash\", s.hash.ToString()));\n\n        ret.push_back(obj);\n    }\n\n    return ret;\n}\n\nUniValue havespentwithdrawal(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 2)\n        throw std::runtime_error(\n            \"havespentwithdrawal\\n\"\n            \"Return whether this Withdrawal was spent\\n\"\n            \"\\nResult: true | false \\n\"\n            \"\\nExample:\\n\"\n            + HelpExampleCli(\"havespentwithdrawal\", \"hash, nsidechain\")\n            );\n\n    std::string strHash = request.params[0].get_str();\n    if (strHash.size() != 64)\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Withdrawal hash length\");\n\n    uint256 hash = uint256S(strHash);\n    if (hash.IsNull())\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Withdrawal hash\");\n\n    int nSidechain = request.params[1].get_int();\n\n    if (!scdb.IsSidechainActive(nSidechain))\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Sidechain number\");\n\n    bool fSpent = scdb.HaveSpentWithdrawal(hash, nSidechain);\n\n    return fSpent;\n}\n\nUniValue havefailedwithdrawal(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 2)\n        throw std::runtime_error(\n            \"havefailedwithdrawal\\n\"\n            \"Return whether this Withdrawal failed\\n\"\n            \"\\nResult: true | false \\n\"\n            \"\\nExample:\\n\"\n            + HelpExampleCli(\"havefailedwithdrawal\", \"hash, nsidechain\")\n            );\n\n    std::string strHash = request.params[0].get_str();\n    if (strHash.size() != 64)\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Withdrawal hash length\");\n\n    uint256 hash = uint256S(strHash);\n    if (hash.IsNull())\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Withdrawal hash\");\n\n    int nSidechain = request.params[1].get_int();\n\n    if (!scdb.IsSidechainActive(nSidechain))\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid Sidechain number\");\n\n    bool fFailed = scdb.HaveFailedWithdrawal(hash, nSidechain);\n\n    return fFailed;\n}\n\nUniValue listspentwithdrawals(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size())\n        throw std::runtime_error(\n            \"listspentwithdrawals\\n\"\n            \"List Withdrawal(s) which have been approved by workscore and spent\\n\"\n            \"\\nResult: (array)\\n\"\n            \"{\\n\"\n            \"  \\\"nsidechain\\\" : (numeric) Sidechain number of Withdrawal\\n\"\n            \"  \\\"hash\\\" : (string) hash of Withdrawal\\n\"\n            \"  \\\"hashblock\\\"   : (string) hash of block Withdrawal was spent in\\n\"\n            \"}\\n\"\n            \"\\n\"\n            \"\\nExample:\\n\"\n            + HelpExampleCli(\"listspentwithdrawals\", \"\")\n            );\n\n    std::vector<SidechainSpentWithdrawal> vSpent = scdb.GetSpentWithdrawalCache();\n    if (vSpent.empty())\n        throw JSONRPCError(RPC_TYPE_ERROR, \"No spent Withdrawal(s) in cache!\");\n\n    UniValue ret(UniValue::VARR);\n    for (const SidechainSpentWithdrawal& s : vSpent) {\n        UniValue obj(UniValue::VOBJ);\n\n        obj.push_back(Pair(\"nsidechain\", s.nSidechain));\n        obj.push_back(Pair(\"hash\", s.hash.ToString()));\n        obj.push_back(Pair(\"hashblock\", s.hashBlock.ToString()));\n\n        ret.push_back(obj);\n    }\n\n    return ret;\n}\n\nUniValue listfailedwithdrawals(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size())\n        throw std::runtime_error(\n            \"listfailedwithdrawals\\n\"\n            \"List Withdrawal(s) which have failed\\n\"\n            \"\\nResult: (array)\\n\"\n            \"{\\n\"\n            \"  \\\"nsidechain\\\" : (numeric) Sidechain number of Withdrawal\\n\"\n            \"  \\\"hash\\\" : (string) hash of withdrawal\\n\"\n            \"}\\n\"\n            \"\\n\"\n            \"\\nExample:\\n\"\n            + HelpExampleCli(\"listfailedwithdrawals\", \"\")\n            );\n\n    std::vector<SidechainFailedWithdrawal> vFailed = scdb.GetFailedWithdrawalCache();\n    if (vFailed.empty())\n        throw JSONRPCError(RPC_TYPE_ERROR, \"No failed Withdrawal(s) in cache!\");\n\n    UniValue ret(UniValue::VARR);\n    for (const SidechainFailedWithdrawal& f : vFailed) {\n        UniValue obj(UniValue::VOBJ);\n\n        obj.push_back(Pair(\"nsidechain\", f.nSidechain));\n        obj.push_back(Pair(\"hash\", f.hash.ToString()));\n\n        ret.push_back(obj);\n    }\n\n    return ret;\n}\n\nUniValue getscdbhash(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size())\n        throw std::runtime_error(\n            \"getscdbhash\\n\"\n            \"Get SCDB hash.\\n\"\n            );\n\n    UniValue ret(UniValue::VOBJ);\n    ret.push_back(Pair(\"hashscdb\", scdb.GetSCDBHash().ToString()));\n\n    return ret;\n}\n\nUniValue gettotalscdbhash(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size())\n        throw std::runtime_error(\n            \"gettotalscdbhash\\n\"\n            \"Get hash of every member of SCDB combined.\\n\"\n            );\n\n    UniValue ret(UniValue::VOBJ);\n    ret.push_back(Pair(\"hashscdbtotal\", scdb.GetTotalSCDBHash().ToString()));\n\n    return ret;\n}\n\nUniValue getscdbdataforblock(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            \"getscdbdataforblock\\n\"\n            \"Get SCDB data from leveldb for the specified block hash\\n\"\n            \"\\nResult:\\n\"\n            \"\\\"nsidechains\\\" : (numeric) Number of active sidechains\\n\"\n            \"\\nArray of Withdrawal status\\n\"\n            \"{\\n\"\n            \"  \\\"nsidechain\\\"  : (numeric) Sidechain number of Withdrawal\\n\"\n            \"  \\\"nblocksleft\\\" : (numeric) Blocks remaining to validate Withdrawal\\n\"\n            \"  \\\"nworkscore\\\"  : (numeric) Number of ACK(s) Withdrawal has received\\n\"\n            \"  \\\"hash\\\" : (string) hash of withdrawal\\n\"\n            \"}\\n\"\n            \"\\n\"\n            \"\\nExample:\\n\"\n            + HelpExampleCli(\"getscdbdataforblock\", \"hashblock\")\n            );\n\n\n    uint256 hashBlock = uint256S(request.params[0].get_str());\n\n    LOCK(cs_main);\n\n    BlockMap::iterator it = mapBlockIndex.find(hashBlock);\n    if (it == mapBlockIndex.end()) {\n        std::string strError = \"Block hash not found\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    CBlockIndex* pblockindex = it->second;\n    if (pblockindex == NULL) {\n        std::string strError = \"Block index null\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    SidechainBlockData data;\n    if (!psidechaintree->GetBlockData(hashBlock, data))\n        throw JSONRPCError(RPC_INTERNAL_ERROR, \"Couldn't find data for block.\");\n\n    UniValue ret(UniValue::VARR);\n    UniValue obj(UniValue::VOBJ);\n    obj.push_back(Pair(\"nsidechains\", (uint64_t)data.vWithdrawalStatus.size()));\n    ret.push_back(obj);\n    for (auto& x : data.vWithdrawalStatus) {\n        for (auto& y : x) {\n            UniValue obj(UniValue::VOBJ);\n            obj.push_back(Pair(\"nsidechain\", y.nSidechain));\n            obj.push_back(Pair(\"nblocksleft\", y.nBlocksLeft));\n            obj.push_back(Pair(\"nworkscore\", y.nWorkScore));\n            obj.push_back(Pair(\"hash\", y.hash.ToString()));\n            ret.push_back(obj);\n        }\n    }\n\n    \/\/ TODO print vActivationStatus\n    \/\/ TODO print vSidechain\n\n    return ret;\n}\n\nUniValue listfailedbmm(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size())\n        throw std::runtime_error(\n            \"listfailedbmm\\n\"\n            \"Print the list of failed BMM transactions yet to be abandoned.\\n\"\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"txid\\\" : (string) Failed BMM txid.\\n\"\n            \"}\\n\"\n            \"\\n\"\n            \"\\nExample:\\n\"\n            + HelpExampleCli(\"listfailedbmm\", \"\")\n            );\n\n    std::set<uint256> setTxid = scdb.GetRemovedBMM();\n\n    UniValue ret(UniValue::VARR);\n    for (const uint256& u : setTxid) {\n        UniValue obj(UniValue::VOBJ);\n        obj.push_back(Pair(\"txid\", u.ToString()));\n        ret.push_back(obj);\n    }\n\n    return ret;\n}\n\nUniValue getopreturndata(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            \"getopreturndata\\n\"\n            \"Print OP_RETURN data for block.\\n\"\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"txid\\\"   : (string) transaction id\\n\"\n            \"  \\\"size\\\"   : (numeric) transaction size.\\n\"\n            \"  \\\"fees\\\"   : (numeric) transaction fees.\\n\"\n            \"  \\\"hex\\\"    : (string) hex from output.\\n\"\n            \"  \\\"decode\\\" : (string) decoded hex.\\n\"\n            \"}\\n\"\n            \"\\n\"\n            \"\\nExample:\\n\"\n            + HelpExampleCli(\"getopreturndata\", \"\")\n            );\n\n    uint256 hashBlock = uint256S(request.params[0].get_str());\n\n    BlockMap::iterator it = mapBlockIndex.find(hashBlock);\n    if (it == mapBlockIndex.end()) {\n        std::string strError = \"Block hash not found\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    CBlockIndex* pblockindex = it->second;\n    if (pblockindex == NULL) {\n        std::string strError = \"Block index null\";\n        LogPrintf(\"%s: %s\\n\", __func__, strError);\n        throw JSONRPCError(RPC_INTERNAL_ERROR, strError);\n    }\n\n    std::vector<OPReturnData> vData;\n    if (!popreturndb->GetBlockData(hashBlock, vData))\n        throw JSONRPCError(RPC_INTERNAL_ERROR, \"Couldn't find data for block.\");\n\n    UniValue ret(UniValue::VARR);\n    for (const OPReturnData& d : vData) {\n        UniValue obj(UniValue::VOBJ);\n        obj.push_back(Pair(\"txid\", d.txid.ToString()));\n        obj.push_back(Pair(\"size\", (uint64_t)d.nSize));\n        obj.push_back(Pair(\"fees\", FormatMoney(d.fees)));\n        obj.push_back(Pair(\"hex\", HexStr(d.script.begin(), d.script.end(), false)));\n\n        std::string strDecode;\n        for (const unsigned char& c : d.script) {\n            strDecode += c;\n        }\n        obj.push_back(Pair(\"decode\", strDecode));\n\n        ret.push_back(obj);\n    }\n\n    return ret;\n}\n\nUniValue echo(const JSONRPCRequest& request)\n{\n    if (request.fHelp)\n        throw std::runtime_error(\n            \"echo|echojson \\\"message\\\" ...\\n\"\n            \"\\nSimply echo back the input arguments. This command is for testing.\\n\"\n            \"\\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in\"\n            \"skydoge-cli and the GUI. There is no server-side difference.\"\n        );\n\n    return request.params;\n}\n\nstatic UniValue getinfo_deprecated(const JSONRPCRequest& request)\n{\n    throw JSONRPCError(RPC_METHOD_NOT_FOUND,\n        \"getinfo\\n\"\n        \"\\nThis call was removed in version 0.16.0. Use the appropriate fields from:\\n\"\n        \"- getblockchaininfo: blocks, difficulty, chain\\n\"\n        \"- getnetworkinfo: version, protocolversion, timeoffset, connections, proxy, relayfee, warnings\\n\"\n        \"- getwalletinfo: balance, keypoololdest, keypoolsize, paytxfee, unlocked_until, walletversion\\n\"\n        \"\\nskydoge-cli has the option -getinfo to collect and format these in the old format.\"\n    );\n}\n\nstatic const CRPCCommand commands[] =\n{ \/\/  category              name                      actor (function)         argNames\n  \/\/  --------------------- ------------------------  -----------------------  ----------\n    { \"control\",            \"getmemoryinfo\",          &getmemoryinfo,          {\"mode\"} },\n    { \"control\",            \"logging\",                &logging,                {\"include\", \"exclude\"}},\n    { \"util\",               \"validateaddress\",        &validateaddress,        {\"address\"} }, \/* uses wallet if enabled *\/\n    { \"util\",               \"createmultisig\",         &createmultisig,         {\"nrequired\",\"keys\"} },\n    { \"util\",               \"verifymessage\",          &verifymessage,          {\"address\",\"signature\",\"message\"} },\n    { \"util\",               \"signmessagewithprivkey\", &signmessagewithprivkey, {\"privkey\",\"message\"} },\n\n    \/* Not shown in help *\/\n    { \"hidden\",             \"setmocktime\",            &setmocktime,            {\"timestamp\"}},\n    { \"hidden\",             \"echo\",                   &echo,                   {\"arg0\",\"arg1\",\"arg2\",\"arg3\",\"arg4\",\"arg5\",\"arg6\",\"arg7\",\"arg8\",\"arg9\"}},\n    { \"hidden\",             \"echojson\",               &echo,                   {\"arg0\",\"arg1\",\"arg2\",\"arg3\",\"arg4\",\"arg5\",\"arg6\",\"arg7\",\"arg8\",\"arg9\"}},\n    { \"hidden\",             \"getinfo\",                &getinfo_deprecated,     {}},\n\n    \/\/ TODO improve & shorten name. Sort alphabetically\n    \/* DriveChain rpc commands (mainly used by sidechains) *\/\n    { \"DriveChain\",  \"createcriticaldatatx\",          &createcriticaldatatx,            {\"amount\", \"height\", \"criticalhash\"}},\n    { \"DriveChain\",  \"listsidechainctip\",             &listsidechainctip,               {\"nsidechain\"}},\n    { \"DriveChain\",  \"listsidechaindeposits\",         &listsidechaindeposits,           {\"addressbytes\"}},\n    { \"DriveChain\",  \"countsidechaindeposits\",        &countsidechaindeposits,          {\"nsidechain\"}},\n    { \"DriveChain\",  \"receivewithdrawalbundle\",       &receivewithdrawalbundle,         {\"nsidechain\",\"rawtx\"}},\n    { \"DriveChain\",  \"verifybmm\",                     &verifybmm,                       {\"blockhash\", \"bmmhash\"}},\n    { \"DriveChain\",  \"verifydeposit\",                 &verifydeposit,                   {\"blockhash\", \"txid\", \"ntx\"}},\n    { \"DriveChain\",  \"listpreviousblockhashes\",       &listpreviousblockhashes,         {}},\n    { \"DriveChain\",  \"listactivesidechains\",          &listactivesidechains,            {}},\n    { \"DriveChain\",  \"listsidechainactivationstatus\", &listsidechainactivationstatus,   {}},\n    { \"DriveChain\",  \"listsidechainproposals\",        &listsidechainproposals,          {}},\n    { \"DriveChain\",  \"getsidechainactivationstatus\",  &getsidechainactivationstatus,    {}},\n    { \"DriveChain\",  \"createsidechainproposal\",       &createsidechainproposal,         {\"nsidechain\", \"title\", \"description\", \"keyhash\", \"nversion\", \"hashid1\", \"hashid2\"}},\n    { \"DriveChain\",  \"clearwithdrawalvotes\",          &clearwithdrawalvotes,            {}},\n    { \"DriveChain\",  \"setwithdrawalvote\",             &setwithdrawalvote,               {\"vote\", \"nsidechain\", \"hashwithdrawal\"}},\n    { \"DriveChain\",  \"listwithdrawalvotes\",           &listwithdrawalvotes,             {}},\n    { \"DriveChain\",  \"getaveragefee\",                 &getaveragefee,                   {\"numblocks\", \"startheight\"}},\n    { \"DriveChain\",  \"getworkscore\",                  &getworkscore,                    {\"nsidechain\", \"hashwithdrawal\"}},\n    { \"DriveChain\",  \"havespentwithdrawal\",           &havespentwithdrawal,             {\"hashwithdrawal\", \"nsidechain\"}},\n    { \"DriveChain\",  \"havefailedwithdrawal\",          &havefailedwithdrawal,            {\"hashwithdrawal\", \"nsidechain\"}},\n    { \"DriveChain\",  \"listcachedwithdrawaltx\",        &listcachedwithdrawaltx,          {\"nsidechain\"}},\n    { \"DriveChain\",  \"listwithdrawalstatus\",          &listwithdrawalstatus,            {\"nsidechain\"}},\n    { \"DriveChain\",  \"listspentwithdrawals\",          &listspentwithdrawals,            {}},\n    { \"DriveChain\",  \"listfailedwithdrawals\",         &listfailedwithdrawals,           {}},\n    { \"DriveChain\",  \"getscdbhash\",                   &getscdbhash,                     {}},\n    { \"DriveChain\",  \"gettotalscdbhash\",              &gettotalscdbhash,                {}},\n    { \"DriveChain\",  \"getscdbdataforblock\",           &getscdbdataforblock,             {\"blockhash\"}},\n    { \"DriveChain\",  \"listfailedbmm\",                 &listfailedbmm,                   {}},\n\n    \/* Coin News RPC *\/\n    { \"CoinNews\",    \"getopreturndata\",               &getopreturndata,                 {\"blockhash\"}},\n\n};\n\nvoid RegisterMiscRPCCommands(CRPCTable &t)\n{\n    for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)\n        t.appendCommand(commands[vcidx].name, &commands[vcidx]);\n}\n","avg_line_length":39.795718939,"max_line_length":373,"alphanum_fraction":0.6068801815,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":289,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/*\n * Copyright (C) 2014-2016 Pavel Dolgov\n *\n * See the LICENSE file for terms of use.\n *\/\n\n#include <stdlib.h>\n#include <time.h>\n\n#include \"ConsoleView.hpp\"\n\nint main(int argc, char* argv[]) {\n    srand(time(NULL));\n    ConsoleView console_view;\n    console_view.view();\n    return 0;\n}\n","avg_line_length":16.0555555556,"max_line_length":41,"alphanum_fraction":0.6470588235,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":18227,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":7.0,"content":"\/\/\n\/\/ Copyright 2016 Pixar\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"Apache License\")\n\/\/ with the following modification; you may not use this file except in\n\/\/ compliance with the Apache License and the following modification to it:\n\/\/ Section 6. Trademarks. is deleted and replaced with:\n\/\/\n\/\/ 6. Trademarks. This License does not grant permission to use the trade\n\/\/    names, trademarks, service marks, or product names of the Licensor\n\/\/    and its affiliates, except as required to comply with Section 4(c) of\n\/\/    the License and to reproduce the content of the NOTICE file.\n\/\/\n\/\/ You may obtain a copy of the Apache License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the Apache License with the above modification is\n\/\/ distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the Apache License for the specific\n\/\/ language governing permissions and limitations under the Apache License.\n\/\/\n#include \"pxr\/imaging\/glf\/glew.h\"\n\n#include \"pxr\/imaging\/hd\/vtBufferSource.h\"\n#include \"pxr\/imaging\/hd\/conversions.h\"\n#include \"pxr\/imaging\/hd\/perfLog.h\"\n\n#include \"pxr\/base\/vt\/array.h\"\n#include \"pxr\/base\/vt\/types.h\"\n\n#include \"pxr\/base\/gf\/vec2d.h\"\n#include \"pxr\/base\/gf\/vec2f.h\"\n#include \"pxr\/base\/gf\/vec2i.h\"\n\n#include \"pxr\/base\/gf\/vec3d.h\"\n#include \"pxr\/base\/gf\/vec3f.h\"\n#include \"pxr\/base\/gf\/vec3i.h\"\n\n#include \"pxr\/base\/gf\/vec4d.h\"\n#include \"pxr\/base\/gf\/vec4f.h\"\n#include \"pxr\/base\/gf\/vec4i.h\"\n\n#include \"pxr\/base\/gf\/matrix4d.h\"\n#include \"pxr\/base\/gf\/matrix4f.h\"\n\n#include \"pxr\/base\/tf\/getenv.h\"\n\n#include <boost\/type_traits.hpp>\n\n#include <boost\/mpl\/assert.hpp>\n#include <boost\/mpl\/contains.hpp>\n#include <boost\/mpl\/if.hpp>\n#include <boost\/mpl\/or.hpp>\n#include <boost\/mpl\/and.hpp>\n#include <boost\/mpl\/int.hpp>\n#include <boost\/mpl\/for_each.hpp>\n#include <boost\/mpl\/has_xxx.hpp>\n\n#include <boost\/utility\/enable_if.hpp>\n\n#include <iostream>\n\n\/\/ ------------------------------------------------------------------------- \/\/\n\/\/ Generic helpers for extracting data from VtValue into char[]\n\/\/ ------------------------------------------------------------------------- \/\/\n\/\/ What's happening here:\n\/\/\n\/\/   * HdVtBufferSource gets initialized with a VtValue and calls\n\/\/     _ExtractArrayData to convert it to a raw byte array.\n\/\/\n\/\/   * _ExtractArrayData does a type dispatch and checks if the VtValue\n\/\/     provided is holding one of the HdVtBufferSource::AcceptedTypes\n\/\/\n\/\/   * When it determines the actual held type, the _Extractor is initialized\n\/\/     with the held T or VtArray<T> value\n\/\/\n\/\/   * For VtArray<T>, the appropriate _GetNumComponents method is then\n\/\/     selected based on the element type of the VtArray\n\/\/\n\/\/   * The OpenGL data type enumeration is selected using _GetGLType<T>, where\n\/\/     T is VtArray<T>::ElementType\n\/\/\n\/\/ This code is self contained and could be split off into a Vt conversion\n\/\/ helper module.\n\/\/ ------------------------------------------------------------------------- \/\/\n\n\/\/ Convert runtime element type into GL component and element type enums.\nstruct _GLDataType {\n    _GLDataType(int componentType, int elementType)\n        : componentType(componentType)\n        , elementType(elementType) { }\n    int componentType;\n    int elementType;\n};\ntemplate<typename T> _GLDataType _GetGLType();\ntemplate<> _GLDataType _GetGLType<char>()\n        { return _GLDataType(GL_BYTE, GL_BYTE); }\ntemplate<> _GLDataType _GetGLType<short>()\n        { return _GLDataType(GL_SHORT, GL_SHORT); }\ntemplate<> _GLDataType _GetGLType<unsigned short>()\n        { return _GLDataType(GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT); }\ntemplate<> _GLDataType _GetGLType<int>()\n        { return _GLDataType(GL_INT, GL_INT); }\ntemplate<> _GLDataType _GetGLType<size_t>()\n        { return _GLDataType(GL_UNSIGNED_INT64_NV, GL_UNSIGNED_INT64_NV); }\ntemplate<> _GLDataType _GetGLType<GfVec2i>()\n        { return _GLDataType(GL_INT, GL_INT_VEC2); }\ntemplate<> _GLDataType _GetGLType<GfVec3i>()\n        { return _GLDataType(GL_INT, GL_INT_VEC3); }\ntemplate<> _GLDataType _GetGLType<GfVec4i>()\n        { return _GLDataType(GL_INT, GL_INT_VEC4); }\ntemplate<> _GLDataType _GetGLType<unsigned int>()\n        { return _GLDataType(GL_UNSIGNED_INT, GL_UNSIGNED_INT); }\ntemplate<> _GLDataType _GetGLType<float>()\n        { return _GLDataType(GL_FLOAT, GL_FLOAT); }\ntemplate<> _GLDataType _GetGLType<GfVec2f>()\n        { return _GLDataType(GL_FLOAT, GL_FLOAT_VEC2); }\ntemplate<> _GLDataType _GetGLType<GfVec3f>()\n        { return _GLDataType(GL_FLOAT, GL_FLOAT_VEC3); }\ntemplate<> _GLDataType _GetGLType<GfVec4f>()\n        { return _GLDataType(GL_FLOAT, GL_FLOAT_VEC4); }\ntemplate<> _GLDataType _GetGLType<double>()\n        { return _GLDataType(GL_DOUBLE, GL_DOUBLE); }\ntemplate<> _GLDataType _GetGLType<GfVec2d>()\n        { return _GLDataType(GL_DOUBLE, GL_DOUBLE_VEC2); }\ntemplate<> _GLDataType _GetGLType<GfVec3d>()\n        { return _GLDataType(GL_DOUBLE, GL_DOUBLE_VEC3); }\ntemplate<> _GLDataType _GetGLType<GfVec4d>()\n        { return _GLDataType(GL_DOUBLE, GL_DOUBLE_VEC4); }\ntemplate<> _GLDataType _GetGLType<GfMatrix4f>()\n        { return _GLDataType(GL_FLOAT, GL_FLOAT_MAT4); }\ntemplate<> _GLDataType _GetGLType<GfMatrix4d>()\n        { return _GLDataType(GL_DOUBLE, GL_DOUBLE_MAT4); }\ntemplate<> _GLDataType _GetGLType<Hd_BSplinePatchIndex>()\n        { return _GLDataType(GL_INT, GL_INT); }\n\n\n\/\/ XXX: we don't have BOOST_TTI_HAS_MEMBER_DATA yet. (requires boost 1.54)\n\/\/ http:\/\/en.wikibooks.org\/wiki\/More_C%2B%2B_Idioms\/Member_Detector\n#define HAS_MEMBER_DATA(name)                                           \\\n    template <typename T, bool Enabled=boost::is_class<T>::value>       \\\n    struct has_##name {   \/* if T is int, float, double etc *\/          \\\n        static bool const value = false;                                \\\n    };                                                                  \\\n    template <typename T>                                               \\\n    struct has_##name<T, true> {  \/* if T is class *\/                   \\\n        struct B { int name; };                                         \\\n        struct D : T, B { };                                            \\\n        template<typename C, C> struct ChT;                             \\\n        template<typename C> static char (&f(ChT<int B::*, &C::name>*))[1]; \\\n        template<typename C> static char (&f(...))[2];                  \\\n        static bool const value = sizeof(f<D>(0)) == 2;                 \\\n    };\n\n\/\/ mpl helpers to check an existence of data member\nHAS_MEMBER_DATA(dimension);\nHAS_MEMBER_DATA(numRows);\n\n\/\/ ------------------------------------------------------------------------- \/\/\n\/\/ Determine the number of components in each element, because the ElementTypes\n\/\/ held by VtArray do not have compatible interfaces, the following methods are\n\/\/ specialized for each category of element type: integral\/float, GfVec*,\n\/\/ GfMatrix* etc.\n\n\/\/ Integral\/Float types.\ntemplate <typename T>\nshort\n_GetNumComponents(T const& array,\n                  typename boost::enable_if<\n                            boost::mpl::or_<\n                                boost::is_integral<typename T::ElementType>,\n                                boost::is_float<typename T::ElementType>\n                                >\n                            , T>::type* = 0) {\n    return 1;\n}\n\n\/\/ GfVec* types. \ntemplate <typename T>\nshort \n_GetNumComponents(T const& array, typename boost::enable_if<\n                  has_dimension<typename T::ElementType> >::type* = 0) {\n    typedef typename T::ElementType ET;\n    return ET::dimension;\n}\n\n\/\/ GfMatrix* types.\ntemplate <typename T>\nshort \n_GetNumComponents(T const& array, typename boost::enable_if<\n                  has_numRows<typename T::ElementType> >::type* = 0) {\n    typedef typename T::ElementType ET;\n    return ET::numRows * ET::numColumns;\n}\n\n\/\/ ------------------------------------------------------------------------- \/\/\n\/\/ Helper class for extracting the data from a VtValue<T> or\n\/\/ VtValue< VtArray<T> >.\n\/\/ \nclass _Extractor {\npublic:\n    _Extractor()\n        : _glDataType(0, 0)\n        , _size(0)\n        , _numComponents(0)\n        , _data(NULL)\n    { }\n\n    \/\/ mpl helpers to check an existence of nested type\n    BOOST_MPL_HAS_XXX_TRAIT_DEF(ElementType);\n\n    \/\/ single values (float, double, int)\n    template <typename T>\n    void\n    Extract(T const& value,\n            typename boost::enable_if<\n              boost::mpl::or_<\n                boost::is_integral<T>, boost::is_float<T> > >::type* = 0){\n        \/\/ This method is only called once, with the actual value in the\n        \/\/ VtValue\n        TF_VERIFY(_data == NULL);\n        TF_VERIFY(_numComponents == 0);\n\n        \/\/ size of single value in interleaved struct rounds up to\n        \/\/ sizeof(GLint) according to GL spec.\n        _size = std::max(sizeof(T), sizeof(GLint));\n        _numComponents = 1;\n        _glDataType = _GetGLType<T>();\n\n        \/\/ Hold a pointer to the heldtype\n        _data = &value;\n    }\n\n    \/\/ vector\n    template <typename T>\n    void\n    Extract(T const& value,\n            typename boost::enable_if<has_dimension<T> >::type* = 0) {\n        \/\/ This method is only called once, with the actual vector in the\n        \/\/ VtValue\n        TF_VERIFY(_data == NULL);\n        TF_VERIFY(_numComponents == 0);\n\n        \/\/ Calculate the size.\n        _size = sizeof(T);\n        _numComponents = T::dimension;\n        _glDataType = _GetGLType<typename T::ScalarType>();\n\n        \/\/ Hold a pointer to the GfVec\n        _data = value.GetArray();\n    }\n\n    \/\/ matrix\n    template <typename T>\n    void\n    Extract(T const& value,\n            typename boost::enable_if<has_numRows<T> >::type* = 0) {\n        \/\/ This method is only called once, with the actual matrix held in the\n        \/\/ VtValue.\n        TF_VERIFY(_data == NULL);\n        TF_VERIFY(_numComponents == 0);\n\n        \/\/ Calculate the size.\n        _size = sizeof(T);\n        _numComponents = T::numRows * T::numColumns;\n        _glDataType = _GetGLType<typename T::ScalarType>();\n\n        \/\/ Hold a pointer to the GfMatrix\n        _data = value.GetArray();\n    }\n\n    \/\/ array\n    template <typename T>\n    void\n    Extract(T const& array,\n            typename boost::enable_if<has_ElementType<T> >::type* = 0) {\n        typedef typename T::ElementType ElementType;\n\n        \/\/ This method is only called once, with the actual array held in the\n        \/\/ VtValue.\n        TF_VERIFY(_data == NULL);\n        TF_VERIFY(_numComponents == 0);\n\n        \/\/ Calculate the size.\n        _size = array.size() * sizeof(ElementType);\n\n        \/\/ Extract data that requires additional dispatch based on the element\n        \/\/ type.\n        _numComponents = _GetNumComponents(array);\n        _glDataType = _GetGLType<ElementType>();\n\n        \/\/ Hold a pointer to the internal storage of the VtArray. A new buffer\n        \/\/ could be allocated at this point, if holding the VtValue has\n        \/\/ negative side effects.\n        if (array.size() > 0) _data = array.cdata();\n    }\n\n    _GLDataType GetGLDataType() {return _glDataType;}\n    size_t GetSize() {return _size;}\n    short GetNumComponents() {return _numComponents;}\n    void const* GetData() {return _data;}\n\nprivate:\n\n    _GLDataType _glDataType;\n    size_t _size;\n    short _numComponents;\n    void const* _data;\n};\n\n\/\/ ------------------------------------------------------------------------- \/\/\n\/\/ Works in conjunction with _ExtractArrayData to detect the held type of a\n\/\/ VtValue.\ntemplate<typename FUNCTOR>\nstruct _TypeChecker {\n    _TypeChecker(VtValue const& value, FUNCTOR& extractor)\n        : _value(value)\n        , _extractor(extractor)\n    {\n        \/*Nothing*\/\n    }\n\n    template <typename T>\n    void operator()(T) {\n        \/\/ Check each type T, if the VtValue is holding the current T, then\n        \/\/ bind the value to the extractor.\n        if (_value.IsHolding<typename T::Type>())\n            _extractor.Extract(_value.UncheckedGet<typename T::Type>());\n    }\n\nprivate:\n    VtValue const& _value;\n    FUNCTOR& _extractor;\n};\n\nstatic\n_Extractor\n_ExtractArrayData(VtValue const& value) {\n    \/\/ Type dispatch to _Extractor.\n    \/\/\n    \/\/ Iterate over each acceptable type T, calling typeChecker<T>(), which\n    \/\/ internally calls value.IsHolding<T>(); if the VtValue IS holding a T,\n    \/\/ then pass the held value to _Extractor::Extract<T>(value).\n    _Extractor e;\n    boost::mpl::for_each<HdVtBufferSource::AcceptedTypes\n                         >(_TypeChecker<_Extractor>(value, e));\n    \/\/ Guarantee that the _Extractor::Extract method was called exactly once\n    \/\/ and issue a runtime error otherwise. (The only case where Extract wont\n    \/\/ be called is when the VtValue is holding an unacceptable type).\n    if (e.GetNumComponents() == 0) {\n        TF_RUNTIME_ERROR(\"HdVtBufferSource initialized with VtValue holding \"\n                         \"unacceptable type: %s\",\n                         value.GetType().GetTypeName().c_str());\n    }\n    return e;\n}\n\n\/\/ ------------------------------------------------------------------------- \/\/\n\/\/ HdVtBufferSource Implementation\n\/\/ ------------------------------------------------------------------------- \/\/\n\nHdVtBufferSource::HdVtBufferSource(TfToken const& name, VtValue const& value,\n                                   bool staticArray)\n    : _name(name), _value(value), _staticArray(staticArray)\n{\n    HD_TRACE_FUNCTION();\n    \/\/ Extract element size from value.\n    \/\/ This also guarantees the VtValue is an accepted type.\n    \/\/\n    \/\/ note: make sure to extract the pointer from [_value], not [value],\n    \/\/ since if the VtValue holds a tiny type whose size is less than\n    \/\/ sizeof(void*), it uses LocalStorage and doesn't allocate a COW storage.\n    \/\/ In that case the pointer to the held type of [value] is on stack,\n    \/\/ would be invalid.\n    _Extractor arrayInfo = _ExtractArrayData(_value);\n\n    \/\/ Copy the values out of the extractor.\n    _glComponentDataType = arrayInfo.GetGLDataType().componentType;\n    _glElementDataType = arrayInfo.GetGLDataType().elementType;\n    _size = arrayInfo.GetSize();\n    _numComponents = arrayInfo.GetNumComponents();\n    _data = arrayInfo.GetData();\n}\n\nHdVtBufferSource::HdVtBufferSource(TfToken const &name, GfMatrix4d const &matrix)\n    : _name(name), _staticArray(false)\n{\n    if (GetDefaultMatrixType() == GL_DOUBLE) {\n        _value = VtValue(matrix);\n        _glComponentDataType = GL_DOUBLE;\n        _glElementDataType = GL_DOUBLE_MAT4;\n        _size = sizeof(matrix);\n        _numComponents = 16;\n        _data = _value.UncheckedGet<GfMatrix4d>().GetArray();\n    } else {\n        GfMatrix4f fmatrix(\n            matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3],\n            matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3],\n            matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3],\n            matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3]);\n        _value = VtValue(fmatrix);\n        _glComponentDataType = GL_FLOAT;\n        _glElementDataType = GL_FLOAT_MAT4;\n        _size = sizeof(fmatrix);\n        _numComponents = 16;\n        _data = _value.UncheckedGet<GfMatrix4f>().GetArray();\n    }\n}\n\nHdVtBufferSource::HdVtBufferSource(TfToken const &name,\n                                   VtArray<GfMatrix4d> const &matrices,\n                                   bool staticArray)\n    : _name(name), _staticArray(staticArray)\n{\n    if (GetDefaultMatrixType() == GL_DOUBLE) {\n        _value = VtValue(matrices);\n        _glComponentDataType = GL_DOUBLE;\n        _glElementDataType = GL_DOUBLE_MAT4;\n        _size = sizeof(GfMatrix4d) * matrices.size();\n        _numComponents = 16;\n        \/\/ Hold a pointer to the internal storage of the VtArray (_value).\n        if (matrices.size() > 0) _data = matrices.cdata();\n    } else {\n        VtArray<GfMatrix4f> fmatrices(matrices.size());\n        for (size_t i = 0; i < matrices.size(); ++i) {\n            GfMatrix4d const &matrix = matrices[i];\n            GfMatrix4f fmatrix(\n                matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3],\n                matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3],\n                matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3],\n                matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3]);\n            fmatrices[i] = fmatrix;\n        }\n        _value = VtValue(fmatrices);\n        _glComponentDataType = GL_FLOAT;\n        _glElementDataType = GL_FLOAT_MAT4;\n        _size = sizeof(GfMatrix4f) * fmatrices.size();\n        _numComponents = 16;\n        \/\/ Hold a pointer to the internal storage of the VtArray (_value).\n        if (fmatrices.size() > 0) _data = fmatrices.cdata();\n    }\n}\n\nHdVtBufferSource::~HdVtBufferSource()\n{\n}\n\n\/*static*\/\nGLenum\nHdVtBufferSource::GetDefaultMatrixType()\n{\n    static GLenum matrixType =\n        TfGetenvBool(\"HD_ENABLE_DOUBLE_MATRIX\", false) ? GL_DOUBLE : GL_FLOAT;\n    return matrixType;\n}\n\n\/*virtual*\/\nint\nHdVtBufferSource::GetNumElements() const\n{\n    return _size \/ (_numComponents *\n                    HdConversions::GetComponentSize(_glComponentDataType));\n}\n\nbool\nHdVtBufferSource::_CheckValid() const\n{\n    \/\/ This is using the same check as _ExtractArrayData()\n    \/\/ to check for validity.\n    \/\/\n    \/\/ Note: Can't do _size check as an empty buffer is valid\n    return ((_numComponents > 0) &&\n            (_glComponentDataType > 0) &&\n            (_glElementDataType > 0));\n}\n\nstd::ostream &operator <<(std::ostream &out,\n                                 const HdVtBufferSource& self) {\n    out << \"Buffer Source:\\n\";\n    out << \"    Size: \"                  << self._size << \"\\n\";\n    out << \"    GL Component DataType: \" << self._glComponentDataType << \"\\n\";\n    out << \"    GL Element DataType: \"   << self._glElementDataType << \"\\n\";\n    out << \"    Num Elements: \"          << self.GetNumElements() << \"\\n\";\n    out << \"    Element Size: \"          << self.GetElementSize() << \"\\n\";\n    out << \"    Num Components: \"        << self._numComponents << \"\\n\";\n    out << \"    Component Size: \"        << self.GetComponentSize() << \"\\n\";\n    return out;\n}\n","avg_line_length":37.1221995927,"max_line_length":81,"alphanum_fraction":0.6087672135,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":26001,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/\n\/\/  MLTextUtils.cpp\n\/\/  madronalib\n\/\/\n\/\/  Created by Randy Jones on 12\/3\/14.\n\/\/\n\/\/\n\n#include \"MLTextUtils.h\"\n\n#include <cstring>\n\n#include \"MLDSPScalarMath.h\"\n#include \"MLMemoryUtils.h\"\n#include \"aes256.h\"\n#include \"utf.hpp\"\n\nnamespace ml\n{\nnamespace textUtils\n{\nstatic const int npos = -1;\n\nbool isDigit(CodePoint c)\n{\n  if (c >= '0' && c <= '9') return true;\n  return false;\n}\nbool isASCII(CodePoint c) { return (c < 0x7f); }\n\nbool isLatin(CodePoint c)\n{\n  \/\/ includes Latin-1 Supplement\n  return (c <= 0xFF);\n}\n\nbool isWhitespace(CodePoint ch)\n{\n  return (ch >= 0x0009 && ch <= 0x000D) || ch == 0x0020 || ch == 0x0085 || ch == 0x00A0 ||\n         ch == 0x1680 || (ch >= 0x2000 && ch <= 0x200A) || ch == 0x2028 || ch == 0x2029 ||\n         ch == 0x202F || ch == 0x205F || ch == 0x3000;\n}\n\nbool isCJK(CodePoint ch)\n{\n  return (ch >= 0x4E00 && ch <= 0x9FBF)      \/\/ CJK Unified Ideographs\n         || (ch >= 0x2E80 && ch <= 0x2FDF)   \/\/ CJK Radicals Supplement & Kangxi Radicals\n         || (ch >= 0x2FF0 && ch <= 0x30FF)   \/\/ Ideographic Description Characters, CJK Symbols\n                                             \/\/ and Punctuation & Japanese\n         || (ch >= 0x3100 && ch <= 0x31BF)   \/\/ Korean\n         || (ch >= 0xAC00 && ch <= 0xD7AF)   \/\/ Hangul Syllables\n         || (ch >= 0xF900 && ch <= 0xFAFF)   \/\/ CJK Compatibility Ideographs\n         || (ch >= 0xFE30 && ch <= 0xFE4F)   \/\/ CJK Compatibility Forms\n         || (ch >= 0x31C0 && ch <= 0x4DFF);  \/\/ Other exiensions\n}\n\nchar* spaceStr(size_t numIndents)\n{\n  static char* pBuf = (char*)\"                                                   \";\n  static size_t len = strlen(pBuf);\n  size_t n = numIndents * 2;\n  n = ml::clamp(n, (size_t)0, len);\n  return &pBuf[len - n];\n}\n\nint digitsToNaturalNumber(const char32_t* p)\n{\n  constexpr int kMaxDigits = 16;\n\n  if (!p) return 0;\n  int v = 0;\n  int l = 0;\n  int d;\n  char c;\n\n  while (p[l])\n  {\n    c = p[l];\n    if (c >= '0' && c <= '9')\n      d = (c - '0');\n    else\n      break;\n    v = (v * 10) + d;\n    l++;\n    if (l >= kMaxDigits) return -1;\n  }\n  return v;\n}\n\nint textToNaturalNumber(const TextFragment& frag)\n{\n  std::vector<CodePoint> vec = textToCodePoints(frag);\n  return digitsToNaturalNumber(vec.data());\n}\n\nTextFragment naturalNumberToText(int i)\n{\n  constexpr int kMaxDigits = 16;\n\n  char buf[kMaxDigits]{};\n  char* p = buf + kMaxDigits - 1;\n  char* end = p;\n\n  \/\/ null-terminate the string\n  *end = 0;\n\n  \/\/ work backwards\n  do\n  {\n    p--;\n    if (p < buf) return \"overflow\";\n    *p = '0' + (i % 10);\n    i \/= 10;\n  } while (i != 0);\n  return (TextFragment(p, end - p));\n}\n\n\/\/ numeric\n\nTextFragment floatNumberToText(float f, int precision)\n{\n  \/\/ const float maxFloat = std::numeric_limits<float>::max();\n  constexpr int kMaxPrecision = 10;\n  constexpr int kScientificStart = 5;\n  constexpr int kMaxDigits = 32;\n  constexpr int kTableZeroOffset = 38;\n  constexpr float powersOfTen[kTableZeroOffset * 2 + 1]{\n      1e-38, 1e-37, 1e-36, 1e-35, 1e-34, 1e-33, 1e-32, 1e-31, 1e-30, 1e-29, 1e-28, 1e-27, 1e-26,\n      1e-25, 1e-24, 1e-23, 1e-22, 1e-21, 1e-20, 1e-19, 1e-18, 1e-17, 1e-16, 1e-15, 1e-14, 1e-13,\n      1e-12, 1e-11, 1e-10, 1e-09, 1e-08, 1e-07, 1e-06, 1e-05, 1e-04, 1e-03, 1e-02, 1e-01, 1e+00,\n      1e+01, 1e+02, 1e+03, 1e+04, 1e+05, 1e+06, 1e+07, 1e+08, 1e+09, 1e+10, 1e+11, 1e+12, 1e+13,\n      1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20, 1e+21, 1e+22, 1e+23, 1e+24, 1e+25, 1e+26,\n      1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38};\n\n  char buf[kMaxDigits];\n  char* writePtr = buf;\n  float value = f;\n  const int p = std::min(precision, kMaxPrecision);\n  const float epsilon =\n      std::max(fabs(f * powersOfTen[kTableZeroOffset - p]), std::numeric_limits<float>::min());\n\n  if (isnan(f))\n  {\n    *writePtr++ = 'n';\n    *writePtr++ = 'a';\n    *writePtr++ = 'n';\n  }\n  else\n  {\n    if (value < 0)\n    {\n      value = -value;\n      *writePtr++ = '-';\n    }\n\n    if (value > powersOfTen[kTableZeroOffset * 2])\n    {\n      *writePtr++ = 'i';\n      *writePtr++ = 'n';\n      *writePtr++ = 'f';\n    }\n    else if (value < powersOfTen[0])\n    {\n      *writePtr++ = '0';\n      *writePtr++ = '.';\n    }\n    else\n    {\n      \/\/ get the exponent using linear search, starting from center\n      int y = kTableZeroOffset;\n      while (value > powersOfTen[y])\n      {\n        y++;\n      }\n      while (value < powersOfTen[y])\n      {\n        y--;\n      }\n      int exponent = y - kTableZeroOffset;\n      int absExponent = std::abs(exponent);\n\n      if (absExponent < kScientificStart)\n      \/\/ write in decimal notation\n      {\n        \/\/ first write any leading zeroes\n        if (exponent < -1)\n        {\n          *writePtr++ = '0';\n          *writePtr++ = '.';\n          int zeroes = -exponent - 1;\n          for (int i = 0; i < zeroes; ++i)\n          {\n            *writePtr++ = '0';\n          }\n        }\n        else if (exponent == -1)\n        {\n          *writePtr++ = '0';\n        }\n\n        \/\/ then write nonzero digits\n        do\n        {\n          if (exponent == -1)\n          {\n            *writePtr++ = '.';\n          }\n          int onesInt = truncf(value * powersOfTen[kTableZeroOffset - exponent]);\n          *writePtr++ = '0' + onesInt;\n          value = value - onesInt * powersOfTen[kTableZeroOffset + exponent];\n          exponent--;\n        } while ((value > epsilon) || (exponent >= 0));\n      }\n      else\n      \/\/ write in scientific notation\n      {\n        const char exponentSign = exponent >= 0 ? '+' : '-';\n\n        \/\/ write mantissa\n        int onesInt = value * powersOfTen[kTableZeroOffset - exponent];\n        *writePtr++ = '0' + onesInt;\n        *writePtr++ = '.';\n        while (value > epsilon)\n        {\n          value = value - onesInt * powersOfTen[kTableZeroOffset + exponent];\n          exponent--;\n          onesInt = value * powersOfTen[kTableZeroOffset - exponent];\n          *writePtr++ = '0' + onesInt;\n        }\n\n        \/\/ write exponent\n        *writePtr++ = 'e';\n        *writePtr++ = exponentSign;\n        *writePtr++ = '0' + absExponent \/ 10;\n        *writePtr++ = '0' + absExponent % 10;\n      }\n    }\n  }\n  return TextFragment(buf, writePtr - buf);\n}\n\nbool fragmentContainsCodePoint(TextFragment f, CodePoint cp)\n{\n  for (const CodePoint c : f)\n  {\n    if (c == cp) return true;\n  }\n  return false;\n}\n\nfloat textToFloatNumber(const TextFragment& frag)\n{\n  float sign = 1;\n  float wholePart = 0, fracPart = 0, fracPlace = 1;\n  float exponentSign = 1, exponent = 0;\n  bool hasExp = false;\n  auto it = frag.begin();\n  const TextFragment digits{\"0123456789\"};\n  std::vector<std::pair<TextFragment, std::function<void()> > > segments{\n      {\"NaN\", [&]() { wholePart = std::numeric_limits<float>::quiet_NaN(); }},\n      {\"-\", [&]() { sign = -sign; }},\n      {\"inf\", [&]() { wholePart = std::numeric_limits<float>::infinity(); }},\n      {digits, [&]() { wholePart = wholePart * 10.0f + ((*it) - '0'); }},\n      {\".\", [&]() {}},\n      {digits, [&]() { fracPart += ((*it) - '0') * (fracPlace *= 0.1f); }},\n      {\"e+\", [&]() { hasExp = true; }},\n      {\"-\", [&]() { exponentSign = -exponentSign; }},\n      {digits, [&]() { exponent = exponent * 10.0f + ((*it) - '0'); }}};\n\n  for (auto segment : segments)\n  {\n    while (fragmentContainsCodePoint(segment.first, *it))\n    {\n      segment.second();\n      ++it;\n    }\n  }\n\n  float base = sign * (wholePart + fracPart);\n  return hasExp ? base * powf(10.f, exponent * exponentSign) : base;\n}\n\nint findFirst(const TextFragment& frag, const CodePoint b)\n{\n  int r = npos;\n  if (!frag) return r;\n  int i = 0;\n  for (const CodePoint c : frag)\n  {\n    if (!validateCodePoint(c)) return r;\n    if (c == b)\n    {\n      r = i;\n      break;\n    }\n    i++;\n  }\n  return r;\n}\n\nint findLast(const TextFragment& frag, const CodePoint b)\n{\n  int r = npos;\n  if (!frag) return r;\n  int i = 0;\n  for (const CodePoint c : frag)\n  {\n    if (!validateCodePoint(c)) return r;\n    if (c == b)\n    {\n      r = i;\n    }\n    i++;\n  }\n  return r;\n}\n\nint findFirst(const TextFragment& frag, std::function<bool(CodePoint)> matchFn)\n{\n  int r = npos;\n  if (!frag) return r;\n  int i = 0;\n  for (const CodePoint c : frag)\n  {\n    if (!validateCodePoint(c)) return r;\n    if (matchFn(c))\n    {\n      r = i;\n      break;\n    }\n    i++;\n  }\n  return r;\n}\n\n\/\/ TODO dumb, have to call matchFn on each code point because we have no reverse\n\/\/ iterator\nint findLast(const TextFragment& frag, std::function<bool(CodePoint)> matchFn)\n{\n  int r = npos;\n  if (!frag) return r;\n  int i = 0;\n  for (const CodePoint c : frag)\n  {\n    if (!validateCodePoint(c)) return r;\n    if (matchFn(c))\n    {\n      r = i;\n    }\n    i++;\n  }\n  return r;\n}\n\nTextFragment subText(const TextFragment& frag, size_t start, size_t end)\n{\n  \/\/ this impl does an unneccesary copy, to keep TextFragment very simple for\n  \/\/ now.\n  if (!frag) return TextFragment();\n  if (start >= end) return TextFragment();\n\n  \/\/ temp buffer big enough to hold whole input fragment if needed.\n  \/\/ we won't know the output fragment size in bytes until iterating the code\n  \/\/ points.\n  size_t len = frag.lengthInBytes();\n  SmallStackBuffer<char, kShortFragmentSizeInChars> temp(len);\n  char* buf = temp.data();\n  char* pb = buf;\n\n  auto first = TextFragment::Iterator(frag.getText());\n  auto it = first;\n  for (int i = 0; i < start; ++i)\n  {\n    ++it;\n  }\n\n  for (int i = 0; i < end - start; ++i)\n  {\n    \/\/ write the codepoint as UTF-8 to the buffer\n    if (!validateCodePoint(*it)) return TextFragment();\n    pb = utf::internal::utf_traits<utf::utf8>::encode(*it, pb);\n    ++it;\n  }\n\n  return TextFragment(buf, pb - buf);\n}\n\nTextFragment map(const TextFragment& frag, std::function<CodePoint(CodePoint)> f)\n{\n  if (!frag) return TextFragment();\n  std::vector<CodePoint> vec = textToCodePoints(frag);\n  std::transform(vec.begin(), vec.end(), vec.begin(), f);\n  return codePointsToText(vec);\n}\n\nTextFragment reduce(const TextFragment& frag, std::function<bool(CodePoint)> matchFn)\n{\n  if (!frag) return TextFragment();\n  size_t len = frag.lengthInBytes();\n  SmallStackBuffer<char, kShortFragmentSizeInChars> temp(len);\n  char* buf = temp.data();\n  char* pb = buf;\n\n  for (const CodePoint c : frag)\n  {\n    if (!validateCodePoint(c)) return TextFragment();\n    if (matchFn(c))\n    {\n      pb = utf::internal::utf_traits<utf::utf8>::encode(c, pb);\n    }\n  }\n\n  return TextFragment(buf, pb - buf);\n}\n\nstd::vector<TextFragment> split(TextFragment frag, CodePoint delimiter)\n{\n  std::vector<TextFragment> output;\n  int start = 0;\n  int end = 0;\n  int pieceLen = 0;\n  for (const CodePoint c : frag)\n  {\n    if (!validateCodePoint(c)) return std::vector<TextFragment>();\n    pieceLen++;\n    end++;\n    if (c == delimiter)\n    {\n      if (pieceLen > 1)\n      {\n        output.push_back(subText(frag, start, end - 1));\n      }\n      start = end;\n      pieceLen = 0;\n    }\n  }\n  if (pieceLen > 0)\n  {\n    output.push_back(subText(frag, start, end));\n  }\n  return output;\n}\n\nTextFragment join(const std::vector<TextFragment>& vec)\n{\n  TextFragment sum;\n  size_t len = vec.size();\n  for (int i = 0; i < len; ++i)\n  {\n    TextFragment frag = vec[i];\n    sum = TextFragment(sum, vec[i]);\n  }\n  return sum;\n}\n\nTextFragment join(const std::vector<TextFragment>& vec, CodePoint delimiter)\n{\n  TextFragment delimFrag(delimiter);\n  TextFragment sum;\n  size_t len = vec.size();\n  for (int i = 0; i < len; ++i)\n  {\n    TextFragment frag = vec[i];\n    sum = TextFragment(sum, vec[i]);\n    if ((i >= 0) && (i < len - 1))\n    {\n      sum = TextFragment(sum, delimFrag);\n    }\n  }\n  return sum;\n}\n\nTextFragment stripFileExtension(const TextFragment& frag)\n{\n  int dotLoc = findLast(frag, '.');\n  if (dotLoc >= 0)\n  {\n    return subText(frag, 0, dotLoc);\n  }\n  return frag;\n}\n\nTextFragment getShortFileName(const TextFragment& frag)\n{\n  int slashLoc = findLast(frag, '\/');\n  if (slashLoc >= 0)\n  {\n    return subText(frag, slashLoc + 1, frag.lengthInCodePoints());\n  }\n  return frag;\n}\n\nTextFragment getPath(const TextFragment& frag)\n{\n  int slashLoc = findLast(frag, '\/');\n  if (slashLoc >= 0)\n  {\n    return subText(frag, 0, slashLoc);\n  }\n  return frag;\n}\n\n\/\/ TODO extend to recognize Cyrillic and other scripts\nSymbol bestScriptForTextFragment(const TextFragment& frag)\n{\n  for (const CodePoint c : frag)\n  {\n    if (!validateCodePoint(c)) return \"unknown\";\n    \/\/ if there are any CJK characters, return CJK\n    if (isCJK(c))\n    {\n      return \"cjk\";\n    }\n    else if (!isLatin(c))\n    {\n      return \"unknown\";\n    }\n  }\n  return \"latin\";\n}\n\nstatic const char base64table[] =\n    \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=\";\nint indexOf(const char* str, char c)\n{\n  int r = -1;\n  size_t len = strlen(str);\n  for (size_t i = 0; i < len; ++i)\n  {\n    if (str[i] == c)\n    {\n      r = (int)i;\n      break;\n    }\n  }\n  return r;\n}\n\nTextFragment base64Encode(const std::vector<uint8_t>& in)\n{\n  size_t len = in.size();\n  std::vector<char> out;\n  int b;\n  for (size_t i = 0; i < len; i += 3)\n  {\n    b = (in[i] & 0xFC) >> 2;\n    out.push_back(base64table[b]);\n    b = (in[i] & 0x03) << 4;\n    if (i + 1 < len)\n    {\n      b |= (in[i + 1] & 0xF0) >> 4;\n      out.push_back(base64table[b]);\n      b = (in[i + 1] & 0x0F) << 2;\n      if (i + 2 < len)\n      {\n        b |= (in[i + 2] & 0xC0) >> 6;\n        out.push_back(base64table[b]);\n        b = in[i + 2] & 0x3F;\n        out.push_back(base64table[b]);\n      }\n      else\n      {\n        out.push_back(base64table[b]);\n        out.push_back('=');\n      }\n    }\n    else\n    {\n      out.push_back(base64table[b]);\n      out.push_back('=');\n      out.push_back('=');\n    }\n  }\n  out.push_back(0);\n  return TextFragment(out.data());\n}\n\nstd::vector<uint8_t> base64Decode(const TextFragment& frag)\n{\n  size_t len = frag.lengthInBytes();\n  if (len % 4) return std::vector<uint8_t>();\n  std::vector<uint8_t> decoded;\n  const char* inChars = frag.getText();\n  int b[4];\n  for (int i = 0; i < len; i += 4)\n  {\n    for (int j = 0; j < 4; ++j)\n    {\n      b[j] = indexOf(base64table, inChars[i + j]);\n    }\n    decoded.push_back((b[0] << 2) | (b[1] >> 4));\n    if (b[2] < 64)\n    {\n      decoded.push_back((b[1] << 4) | (b[2] >> 2));\n      if (b[3] < 64)\n      {\n        decoded.push_back((b[2] << 6) | b[3]);\n      }\n    }\n  }\n  return decoded;\n}\n\nTextFragment stripWhitespaceAtEnds(const TextFragment& frag)\n{\n  std::function<bool(CodePoint)> f([](CodePoint c) { return !isWhitespace(c); });\n  int first = findFirst(frag, f);\n  int last = findLast(frag, f);\n  if ((first == npos) || (last == npos)) return TextFragment();\n  return (subText(frag, first, last + 1));\n}\n\nTextFragment stripAllWhitespace(const TextFragment& frag)\n{\n  std::function<bool(CodePoint)> f([](CodePoint c) { return !isWhitespace(c); });\n  return reduce(frag, f);\n}\n\nstd::vector<uint8_t> AES256CBCEncode(const std::vector<uint8_t>& input,\n                                     const std::vector<uint8_t>& key,\n                                     const std::vector<uint8_t>& iv)\n{\n  if (!(input.size() > 0) || !(key.size() == 32) || !(iv.size() == 32))\n    return std::vector<uint8_t>();\n\n  aes256_context ctx;\n  aes256_init(&ctx, key.data());\n\n  const int blockSize = 16;\n  size_t inputSize = input.size();\n  size_t blocks = inputSize \/ blockSize + 1;\n  size_t paddedSize = blockSize * (blocks);\n\n  \/\/ add PKCS padding\n  std::vector<uint8_t> plaintext = input;\n  plaintext.resize(paddedSize);\n  size_t padBytes = paddedSize - inputSize;\n  for (size_t i = inputSize; i < paddedSize; ++i)\n  {\n    plaintext[i] = padBytes;\n  }\n\n  std::vector<uint8_t> ciphertext(paddedSize);\n  uint8_t currentIV[blockSize];\n  uint8_t workVector[blockSize];\n\n  for (size_t i = 0; i < blockSize; ++i)\n  {\n    currentIV[i] = iv[i];\n  }\n\n  for (size_t b = 0; b < blocks; ++b)\n  {\n    \/\/ get plaintext XOR IV\n    for (size_t i = 0; i < blockSize; ++i)\n    {\n      workVector[i] = plaintext[b * blockSize + i] ^ currentIV[i];\n    }\n\n    aes256_encrypt_ecb(&ctx, workVector);\n\n    \/\/ write to ciphertext, get new IV\n    for (size_t i = 0; i < blockSize; ++i)\n    {\n      ciphertext[b * blockSize + i] = workVector[i];\n      currentIV[i] = workVector[i];\n    }\n  }\n\n  aes256_done(&ctx);\n  return ciphertext;\n}\n\nstd::vector<uint8_t> AES256CBCDecode(const std::vector<uint8_t>& cipher,\n                                     const std::vector<uint8_t>& key,\n                                     const std::vector<uint8_t>& iv)\n{\n  if (!(cipher.size() > 0) || (key.size() < 32) || (iv.size() < 32)) return std::vector<uint8_t>();\n\n  aes256_context ctx;\n  aes256_init(&ctx, key.data());\n\n  const int blockSize = 16;\n  size_t blocks = cipher.size() \/ blockSize;\n\n  std::vector<uint8_t> plaintext(blockSize * blocks);\n\n  uint8_t currentIV[blockSize];\n  uint8_t nextIV[blockSize];\n  uint8_t workVector[blockSize];\n\n  for (int i = 0; i < blockSize; ++i)\n  {\n    currentIV[i] = iv[i];\n  }\n\n  for (int b = 0; b < blocks; ++b)\n  {\n    \/\/ get next cipher block and use ciphertext as next IV\n    for (int i = 0; i < blockSize; ++i)\n    {\n      workVector[i] = cipher[b * blockSize + i];\n      nextIV[i] = workVector[i];\n    }\n\n    aes256_decrypt_ecb(&ctx, workVector);\n\n    \/\/ write to plaintext, XOR work vector with IV\n    for (int i = 0; i < blockSize; ++i)\n    {\n      workVector[i] ^= currentIV[i];\n      plaintext[b * blockSize + i] = workVector[i];\n      currentIV[i] = nextIV[i];\n    }\n  }\n\n  aes256_done(&ctx);\n\n  \/\/ remove PKCS padding\n  size_t paddedSize = plaintext.size();\n  if (paddedSize % blockSize == 0)\n  {\n    int padBytes = plaintext[paddedSize - 1];\n    if ((padBytes <= 16) && (padBytes < paddedSize))\n    {\n      plaintext.resize(paddedSize - padBytes);\n    }\n  }\n\n  return plaintext;\n}\n\nbool collate(const TextFragment& a, const TextFragment& b)\n{\n  auto ia = a.begin();\n  auto ib = b.begin();\n\n  int iterEnds = 0;\n  while (!iterEnds)\n  {\n    CodePoint ca = *ia;\n    CodePoint cb = *ib;\n\n    if (!validateCodePoint(ca)) return false;\n    if (!validateCodePoint(cb)) return false;\n\n    if (ca != cb)\n    {\n      \/\/ the code points differ.\n      \/\/ compare codepoints, produce a result and bail.\n      if (isLatin(ca) && isLatin(cb))\n      {\n        char la = tolower(ca);\n        char lb = tolower(cb);\n\n        if (la != lb)\n        {\n          \/\/ different letters\n          return la < lb;\n        }\n        else\n        {\n          \/\/ different cases but same letter. define lower case as less within\n          \/\/ letter.\n          return ca > cb;\n        }\n      }\n      else\n      {\n        \/\/ TODO collate other languages better using miniutf library.\n        return ca < cb;\n      }\n    }\n    else\n    {\n      ++ia;\n      ++ib;\n    }\n\n    int aEnd = (ia == a.end());\n    int bEnd = (ib == b.end());\n    iterEnds = (aEnd << 1) | bEnd;\n  }\n\n  switch (iterEnds)\n  {\n    case 1:  \/\/ b ended but not a: a > b.\n      return false;\n    case 2:  \/\/ a ended but not b: a < b.\n      return true;\n    case 3:   \/\/ both ended, a == b.\n    default:  \/\/ impossible\n      return false;\n  }\n  return false;\n}\n\n#pragma mark Symbol utilities\n\nSymbol addFinalNumber(Symbol sym, int n)\n{\n  TextFragment t(sym.getTextFragment(), textUtils::naturalNumberToText(n));\n  return Symbol(t.getText());\n}\n\nSymbol stripFinalNumber(Symbol sym)\n{\n  const TextFragment& frag = sym.getTextFragment();\n  size_t points = frag.lengthInCodePoints();\n\n  \/\/ TODO make more readble using random access fragment class\n\n  SmallStackBuffer<CodePoint, kShortFragmentSizeInCodePoints> temp(points + 1);\n  CodePoint* buf = temp.data();\n\n  \/\/ read into char32 array for random access\n  int i = 0;\n  for (CodePoint c : frag)\n  {\n    if (!validateCodePoint(c)) return Symbol();\n    buf[i++] = c;\n  }\n\n  \/\/ null terminate\n  buf[points] = 0;\n\n  \/\/ no final number? return\n  if (!textUtils::isDigit(buf[points - 1])) return sym;\n\n  \/\/ read backwards until non-digit\n  size_t firstDigitPos = 0;\n  for (size_t i = points - 2; i >= 0; --i)\n  {\n    char32_t c = buf[i];\n    if (!textUtils::isDigit(c))\n    {\n      firstDigitPos = i + 1;\n      break;\n    }\n  }\n\n  ml::TextFragment subFrag(textUtils::subText(frag, 0, firstDigitPos));\n  return subFrag.getText();\n}\n\n\/\/ if the symbol's text ends in a positive integer, return that number.\n\/\/ Otherwise return 0.\nint getFinalNumber(Symbol sym)\n{\n  \/\/ make temporary buffer of decoded code points, hopefully on stack\n  const TextFragment& frag = sym.getTextFragment();\n  size_t points = frag.lengthInCodePoints();\n\n  \/\/ TODO make more readble using random access fragment class\n\n  SmallStackBuffer<CodePoint, kShortFragmentSizeInCodePoints> decodedPoints(points + 1);\n  CodePoint* buf = decodedPoints.data();\n\n  \/\/ read into char32 array for random access\n  int i = 0;\n  for (CodePoint c : frag)\n  {\n    if (!validateCodePoint(c)) return 0;\n    buf[i++] = c;\n  }\n\n  \/\/ null terminate char32_t string\n  buf[i] = 0;\n\n  \/\/ no final number? return\n  if (!textUtils::isDigit(buf[i - 1])) return 0;\n\n  \/\/ read backwards until non-digit\n  int firstDigitPos = 0;\n  for (i--; i >= 0; --i)\n  {\n    char32_t c = buf[i];\n    if (!textUtils::isDigit(c))\n    {\n      firstDigitPos = i + 1;\n      break;\n    }\n  }\n\n  \/\/ note, null terminated char32_t string needed\n  int r = digitsToNaturalNumber(buf + firstDigitPos);\n  return r;\n}\n\nSymbol stripFinalCharacter(Symbol sym)\n{\n  TextFragment frag = sym.getTextFragment();\n  size_t len = frag.lengthInCodePoints();\n  return Symbol(subText(frag, 0, len - 1));\n}\n\n#pragma mark NameMaker\n\n\/\/ base-26 arithmetic with letters (A = 0) produces A, B, ... Z, BA, BB ...\nconst TextFragment NameMaker::nextName()\n{\n  std::vector<int> digits;\n  const int base = 26;\n  const char baseChar = 'A';\n  int a, m, d, rem;\n\n  a = index++;\n\n  if (!a)\n  {\n    digits.push_back(0);\n  }\n  else\n    while (a)\n    {\n      d = a \/ base;\n      m = d * base;\n      rem = a - m;\n      digits.push_back(rem);\n      a = d;\n    }\n\n  int c = 0;\n  while (digits.size() && (c < maxLen - 1))\n  {\n    d = digits.back();\n    digits.pop_back();\n\n    buf[c++] = static_cast<char>(d) + baseChar;\n  }\n\n  buf[c++] = 0;\n  return TextFragment(buf);\n}\n\nclass NoiseGen\n{\n public:\n  NoiseGen() : mSeed(0) {}\n  ~NoiseGen() {}\n\n  inline void step() { mSeed = mSeed * 0x0019660D + 0x3C6EF35F; }\n\n  inline uint32_t getIntSample()\n  {\n    step();\n    return mSeed;\n  }\n\n  void reset() { mSeed = 0; }\n\n private:\n  uint32_t mSeed = 0;\n};\n\nstatic const char kLetters[33] = \"aabcdeefghijklmnnoopqrssttuvwxyz\";\nstd::vector<Symbol> vectorOfNonsenseSymbols(int len)\n{\n  NoiseGen randSource;\n  std::vector<Symbol> words;\n  for (int i = 0; i < len; ++i)\n  {\n    std::string newStr;\n    uint32_t r32 = randSource.getIntSample() >> 16;\n    int wordLen = (r32 & 7) + 3;\n\n    for (int j = 0; j < wordLen; ++j)\n    {\n      r32 = randSource.getIntSample() >> 16;\n      int idx = (r32 & 31);\n      newStr += (kLetters[idx]);\n    }\n    words.push_back(Symbol(newStr.c_str()));\n  }\n  return words;\n}\n\nml::Text formatNumber(const float number, const int digits, const int precision, const bool doSign,\n                      Symbol mode) throw()\n{\n  const std::vector<ml::Text> pitchNames{\"A\",  \"A#\", \"B\", \"C\",  \"C#\", \"D\",\n                                         \"D#\", \"E\",  \"F\", \"F#\", \"G\",  \"G#\"};\n\n  const int bufLength = 16;\n  char numBuf[bufLength] = {0};\n  char format[bufLength] = {0};\n  float tweakedNumber;\n\n  \/\/ get digits to display\n  int m = (precision > 0) ? std::max(digits, precision + 1) : digits;\n  int d = ceil(log10f(fabs(number) + 1.));\n  int p = (d + precision > m) ? m - d : precision;\n  p = std::max(p, 0);\n\n  \/\/  printf(\"---------number: %-+10.2f\\n\", number);\n  \/\/  printf(\"---------number: %-+10.8f\\n\", number);\n  \/\/  printf(\"max: %d, digits: %d, after decimal: %d\\n\", m, d, p);\n\n  tweakedNumber = number;\n  if (mode == \"default\")\n  {\n    if (doSign)\n    {\n      snprintf(format, bufLength, \"X-+0%1d.%1df\", m, p);\n    }\n    else\n    {\n      snprintf(format, bufLength, \"X-0%1d.%1df\", m, p);\n    }\n    format[0] = 37;  \/\/ '%'\n    snprintf(numBuf, bufLength, format, tweakedNumber);\n  }\n  else if (mode == \"ratio\")\n  {\n    bool done = false;\n    for (int a = 1; a <= 8 && !done; ++a)\n    {\n      for (int b = 1; b <= 4 && !done; ++b)\n      {\n        if (fabs(number - (float)a \/ (float)b) < 0.001)\n        {\n          snprintf(numBuf, bufLength, \"%d\/%d\", a, b);\n          done = true;\n        }\n      }\n    }\n    if (!done)\n    {\n      if (doSign)\n      {\n        snprintf(format, bufLength, \"X-+0%1d.%1df\", m, p);\n      }\n      else\n      {\n        snprintf(format, bufLength, \"X-0%1d.%1df\", m, p);\n      }\n      format[0] = 37;  \/\/ '%'\n      snprintf(numBuf, bufLength, format, tweakedNumber);\n    }\n  }\n  else if (mode == \"pitch1\")  \/\/ just show As\n  {\n    int octave = log2(number \/ (27.5f - 0.01f));\n    float quant = (pow(2.f, (float)octave) * 27.5f);\n    float distFromOctave = fabs(number - quant);\n    if (distFromOctave < 0.01)\n    {\n      snprintf(format, bufLength, \"X-0%1d.%1df\\nA%d\", m, p, octave);\n    }\n    else\n    {\n      snprintf(format, bufLength, \"X-0%1d.%1df\", m, p);\n    }\n    format[0] = 37;  \/\/ '%'\n    snprintf(numBuf, bufLength, format, tweakedNumber);\n  }\n  else if (mode == \"pitch2\")  \/\/ show all notes\n  {\n    int note = log2f(number \/ (27.5f - 0.01f)) * 12.f;\n    float quantizedNotePitch = (pow(2.f, (float)note \/ 12.f) * 27.5f);\n    float distFromNote = fabs(number - quantizedNotePitch);\n    if (distFromNote < 0.01)\n    {\n      const int octaveFromC = (note - 3) \/ 12;\n      snprintf(format, bufLength, \"X-0%1d.%1df\\n%s%d\", m, p, pitchNames[note % 12].getText(),\n               octaveFromC);\n    }\n    else\n    {\n      snprintf(format, bufLength, \"X-0%1d.%1df\", m, p);\n    }\n    format[0] = 37;  \/\/ '%'\n    snprintf(numBuf, bufLength, format, tweakedNumber);\n  }\n  else if (mode == \"db\")\n  {\n    if (doSign)\n    {\n      snprintf(format, bufLength, \"X-+0%1d.%1dfdB\", m, p);\n    }\n    else\n    {\n      snprintf(format, bufLength, \"X-0%1d.%1dfdB\", m, p);\n    }\n    format[0] = 37;  \/\/ '%'\n    snprintf(numBuf, bufLength, format, tweakedNumber);\n  }\n\n  return Text(numBuf);\n}\n\n}  \/\/ namespace textUtils\n}  \/\/ namespace ml\n","avg_line_length":23.7669104205,"max_line_length":99,"alphanum_fraction":0.5645936695,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":59744,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"V8DealerFeature.h\"\n\n#include <regex>\n#include <thread>\n\n#include \"Actions\/ActionFeature.h\"\n#include \"Actions\/actions.h\"\n#include \"ApplicationFeatures\/V8PlatformFeature.h\"\n#include \"ApplicationFeatures\/V8SecurityFeature.h\"\n#include \"Basics\/ArangoGlobalContext.h\"\n#include \"Basics\/ConditionLocker.h\"\n#include \"Basics\/FileUtils.h\"\n#include \"Basics\/ScopeGuard.h\"\n#include \"Basics\/StringUtils.h\"\n#include \"Basics\/Thread.h\"\n#include \"Basics\/application-exit.h\"\n#include \"Basics\/files.h\"\n#include \"Basics\/system-functions.h\"\n#include \"Cluster\/ClusterFeature.h\"\n#include \"Cluster\/ServerState.h\"\n#include \"FeaturePhases\/ClusterFeaturePhase.h\"\n#include \"Logger\/LogMacros.h\"\n#include \"Logger\/Logger.h\"\n#include \"Logger\/LoggerStream.h\"\n#include \"ProgramOptions\/ProgramOptions.h\"\n#include \"ProgramOptions\/Section.h\"\n#include \"Random\/RandomGenerator.h\"\n#include \"Rest\/Version.h\"\n#include \"RestServer\/DatabasePathFeature.h\"\n#include \"RestServer\/FrontendFeature.h\"\n#include \"RestServer\/ScriptFeature.h\"\n#include \"RestServer\/SystemDatabaseFeature.h\"\n#include \"Scheduler\/SchedulerFeature.h\"\n#include \"Transaction\/V8Context.h\"\n#include \"V8\/JavaScriptSecurityContext.h\"\n#include \"V8\/v8-buffer.h\"\n#include \"V8\/v8-conv.h\"\n#include \"V8\/v8-globals.h\"\n#include \"V8\/v8-shell.h\"\n#include \"V8\/v8-utils.h\"\n#include \"V8\/v8-deadline.h\"\n#include \"V8Server\/FoxxQueuesFeature.h\"\n#include \"V8Server\/V8Context.h\"\n#include \"V8Server\/v8-actions.h\"\n#include \"V8Server\/v8-ttl.h\"\n#include \"V8Server\/v8-user-functions.h\"\n#include \"V8Server\/v8-user-structures.h\"\n#include \"VocBase\/vocbase.h\"\n\nusing namespace arangodb;\nusing namespace arangodb::application_features;\nusing namespace arangodb::basics;\nusing namespace arangodb::options;\n\nV8DealerFeature* V8DealerFeature::DEALER = nullptr;\n\nnamespace {\nclass V8GcThread : public Thread {\n public:\n  explicit V8GcThread(V8DealerFeature& dealer)\n      : Thread(dealer.server(), \"V8GarbageCollector\"),\n        _dealer(dealer),\n        _lastGcStamp(static_cast<uint64_t>(TRI_microtime())) {}\n\n  ~V8GcThread() { shutdown(); }\n\n public:\n  void run() override { _dealer.collectGarbage(); }\n\n  double getLastGcStamp() {\n    return static_cast<double>(_lastGcStamp.load(std::memory_order_acquire));\n  }\n\n  void updateGcStamp(double value) {\n    _lastGcStamp.store(static_cast<uint64_t>(value), std::memory_order_release);\n  }\n\n private:\n  V8DealerFeature& _dealer;\n  std::atomic<uint64_t> _lastGcStamp;\n};\n}  \/\/ namespace\n\nV8DealerFeature::V8DealerFeature(application_features::ApplicationServer& server)\n    : application_features::ApplicationFeature(server, \"V8Dealer\"),\n      _gcFrequency(60.0),\n      _gcInterval(2000),\n      _maxContextAge(60.0),\n      _copyInstallation(false),\n      _nrMaxContexts(0),\n      _nrMinContexts(0),\n      _nrInflightContexts(0),\n      _maxContextInvocations(0),\n      _allowAdminExecute(false),\n      _enableJS(true),\n      _nextId(0),\n      _stopping(false),\n      _gcFinished(false),\n      _dynamicContextCreationBlockers(0),\n      _contextsCreated(server.getFeature<arangodb::MetricsFeature>().counter(\n          \"arangodb_v8_context_created\", 0, \"V8 contexts created\")),\n      _contextsDestroyed(server.getFeature<arangodb::MetricsFeature>().counter(\n          \"arangodb_v8_context_destroyed\", 0, \"V8 contexts destroyed\")),\n      _contextsEntered(server.getFeature<arangodb::MetricsFeature>().counter(\n          \"arangodb_v8_context_entered\", 0, \"V8 context enter events\")),\n      _contextsExited(server.getFeature<arangodb::MetricsFeature>().counter(\n          \"arangodb_v8_context_exited\", 0, \"V8 context exit events\")),\n      _contextsEnterFailures(server.getFeature<arangodb::MetricsFeature>().counter(\n          \"arangodb_v8_context_enter_failures\", 0, \"V8 context enter failures\")) {\n  setOptional(true);\n  startsAfter<ClusterFeaturePhase>();\n\n  startsAfter<ActionFeature>();\n  startsAfter<V8PlatformFeature>();\n  startsAfter<V8SecurityFeature>();\n}\n\nvoid V8DealerFeature::collectOptions(std::shared_ptr<ProgramOptions> options) {\n  options->addSection(\"javascript\", \"Configure the JavaScript engine\");\n\n  options->addOption(\n      \"--javascript.gc-frequency\",\n      \"JavaScript time-based garbage collection frequency (each x seconds)\",\n      new DoubleParameter(&_gcFrequency),\n      arangodb::options::makeFlags(\n      arangodb::options::Flags::DefaultNoComponents,\n      arangodb::options::Flags::OnCoordinator,\n      arangodb::options::Flags::OnSingle,\n      arangodb::options::Flags::Hidden));\n\n  options->addOption(\n      \"--javascript.gc-interval\",\n      \"JavaScript request-based garbage collection interval (each x requests)\",\n      new UInt64Parameter(&_gcInterval),\n      arangodb::options::makeFlags(\n      arangodb::options::Flags::DefaultNoComponents,\n      arangodb::options::Flags::OnCoordinator,\n      arangodb::options::Flags::OnSingle,\n      arangodb::options::Flags::Hidden));\n\n  options->addOption(\n      \"--javascript.app-path\", \"directory for Foxx applications\",\n      new StringParameter(&_appPath),\n      arangodb::options::makeFlags(\n      arangodb::options::Flags::DefaultNoComponents,\n      arangodb::options::Flags::OnCoordinator,\n      arangodb::options::Flags::OnSingle));\n\n  options->addOption(\n      \"--javascript.startup-directory\",\n      \"path to the directory containing JavaScript startup scripts\",\n      new StringParameter(&_startupDirectory),\n      arangodb::options::makeFlags(\n      arangodb::options::Flags::DefaultNoComponents,\n      arangodb::options::Flags::OnCoordinator,\n      arangodb::options::Flags::OnSingle));\n\n  options->addOption(\n      \"--javascript.module-directory\",\n      \"additional paths containing JavaScript modules\",\n      new VectorParameter<StringParameter>(&_moduleDirectories),\n      arangodb::options::makeFlags(\n      arangodb::options::Flags::DefaultNoComponents,\n      arangodb::options::Flags::OnCoordinator,\n      arangodb::options::Flags::OnSingle,\n      arangodb::options::Flags::Hidden));\n\n  options->addOption(\n      \"--javascript.copy-installation\",\n      \"copy contents of 'javascript.startup-directory' on first start\",\n      new BooleanParameter(&_copyInstallation),\n      arangodb::options::makeFlags(\n      arangodb::options::Flags::DefaultNoComponents,\n      arangodb::options::Flags::OnCoordinator,\n      arangodb::options::Flags::OnSingle));\n\n  options->addOption(\n      \"--javascript.v8-contexts\",\n      \"maximum number of V8 contexts that are created for \"\n      \"executing JavaScript actions\",\n      new UInt64Parameter(&_nrMaxContexts),\n      arangodb::options::makeFlags(\n      arangodb::options::Flags::DefaultNoComponents,\n      arangodb::options::Flags::OnCoordinator,\n      arangodb::options::Flags::OnSingle));\n\n  options->addOption(\n      \"--javascript.v8-contexts-minimum\",\n      \"minimum number of V8 contexts that keep available for \"\n      \"executing JavaScript actions\",\n      new UInt64Parameter(&_nrMinContexts),\n      arangodb::options::makeFlags(\n      arangodb::options::Flags::DefaultNoComponents,\n      arangodb::options::Flags::OnCoordinator,\n      arangodb::options::Flags::OnSingle));\n\n  options->addOption(\n      \"--javascript.v8-contexts-max-invocations\",\n      \"maximum number of invocations for each V8 context before it is disposed\",\n      new UInt64Parameter(&_maxContextInvocations),\n      arangodb::options::makeFlags(\n      arangodb::options::Flags::DefaultNoComponents,\n      arangodb::options::Flags::OnCoordinator,\n      arangodb::options::Flags::OnSingle,\n      arangodb::options::Flags::Hidden));\n\n  options->addOption(\n      \"--javascript.v8-contexts-max-age\",\n      \"maximum age for each V8 context (in seconds) before it is disposed\",\n      new DoubleParameter(&_maxContextAge),\n      arangodb::options::makeFlags(\n      arangodb::options::Flags::DefaultNoComponents,\n      arangodb::options::Flags::OnCoordinator,\n      arangodb::options::Flags::OnSingle,\n      arangodb::options::Flags::Hidden));\n\n  options->addOption(\n      \"--javascript.allow-admin-execute\",\n      \"for testing purposes allow '_admin\/execute', NEVER enable on production\",\n      new BooleanParameter(&_allowAdminExecute),\n      arangodb::options::makeFlags(\n      arangodb::options::Flags::DefaultNoComponents,\n      arangodb::options::Flags::OnCoordinator,\n      arangodb::options::Flags::OnSingle,\n      arangodb::options::Flags::Hidden));\n\n  options->addOption(\n      \"--javascript.enabled\", \"enable the V8 JavaScript engine\",\n      new BooleanParameter(&_enableJS),\n      arangodb::options::makeFlags(\n      arangodb::options::Flags::DefaultNoComponents,\n      arangodb::options::Flags::OnCoordinator,\n      arangodb::options::Flags::OnSingle,\n      arangodb::options::Flags::Hidden));\n}\n\nvoid V8DealerFeature::validateOptions(std::shared_ptr<ProgramOptions> options) {\n  ProgramOptions::ProcessingResult const& result = options->processingResult();\n\n  V8SecurityFeature& v8security = server().getFeature<V8SecurityFeature>();\n\n  \/\/ DBServer and Agent don't need JS. Agent role handled in AgencyFeature\n  if (ServerState::instance()->getRole() == ServerState::RoleEnum::ROLE_DBSERVER &&\n      (!result.touched(\"console\") ||\n       !*(options->get<BooleanParameter>(\"console\")->ptr))) {\n    \/\/ specifying --console requires JavaScript, so we can only turn it off\n    \/\/ if not specified\n    _enableJS = false;\n  }\n\n  if (!_enableJS) {\n    disable();\n    server().disableFeatures(\n        std::vector<std::type_index>{std::type_index(typeid(V8PlatformFeature)),\n                                     std::type_index(typeid(ActionFeature)),\n                                     std::type_index(typeid(ScriptFeature)),\n                                     std::type_index(typeid(FoxxQueuesFeature)),\n                                     std::type_index(typeid(FrontendFeature))});\n    return;\n  }\n\n  \/\/ check the startup path\n  if (_startupDirectory.empty()) {\n    LOG_TOPIC(\"6330a\", FATAL, arangodb::Logger::V8)\n        << \"no 'javascript.startup-directory' has been supplied, giving up\";\n    FATAL_ERROR_EXIT();\n  }\n\n  \/\/ remove trailing \/ from path and set path\n  auto ctx = ArangoGlobalContext::CONTEXT;\n\n  if (ctx == nullptr) {\n    LOG_TOPIC(\"ae845\", FATAL, arangodb::Logger::V8) << \"failed to get global context\";\n    FATAL_ERROR_EXIT();\n  }\n\n  ctx->normalizePath(_startupDirectory, \"javascript.startup-directory\", true);\n  v8security.addToInternalWhitelist(_startupDirectory, FSAccessType::READ);\n\n  ctx->normalizePath(_moduleDirectories, \"javascript.module-directory\", false);\n\n  \/\/ try to append the current version name to the startup directory,\n  \/\/ so instead of \"\/path\/to\/js\" we will get \"\/path\/to\/js\/3.4.0\"\n  std::string const versionAppendix =\n      std::regex_replace(rest::Version::getServerVersion(), std::regex(\"-.*$\"),\n                         \"\");\n  std::string versionedPath =\n      basics::FileUtils::buildFilename(_startupDirectory, versionAppendix);\n\n  LOG_TOPIC(\"604da\", DEBUG, Logger::V8)\n      << \"checking for existence of version-specific startup-directory '\"\n      << versionedPath << \"'\";\n  if (basics::FileUtils::isDirectory(versionedPath)) {\n    \/\/ version-specific js path exists!\n    _startupDirectory = versionedPath;\n  }\n\n  for (auto& it : _moduleDirectories) {\n    versionedPath = basics::FileUtils::buildFilename(it, versionAppendix);\n\n    LOG_TOPIC(\"8e21a\", DEBUG, Logger::V8)\n        << \"checking for existence of version-specific module-directory '\"\n        << versionedPath << \"'\";\n    if (basics::FileUtils::isDirectory(versionedPath)) {\n      \/\/ version-specific js path exists!\n      it = versionedPath;\n    }\n    v8security.addToInternalWhitelist(it, FSAccessType::READ);\n  }\n\n  \/\/ check whether app-path was specified\n  if (_appPath.empty()) {\n    LOG_TOPIC(\"a161b\", FATAL, arangodb::Logger::V8)\n        << \"no value has been specified for --javascript.app-path\";\n    FATAL_ERROR_EXIT();\n  }\n\n  \/\/ Tests if this path is either a directory (ok) or does not exist (we create\n  \/\/ it in ::start) If it is something else this will throw an error.\n  ctx->normalizePath(_appPath, \"javascript.app-path\", false);\n  v8security.addToInternalWhitelist(_appPath, FSAccessType::READ);\n  v8security.addToInternalWhitelist(_appPath, FSAccessType::WRITE);\n  v8security.dumpAccessLists();\n\n  \/\/ use a minimum of 1 second for GC\n  if (_gcFrequency < 1) {\n    _gcFrequency = 1;\n  }\n}\n\nvoid V8DealerFeature::prepare() {\n  auto& cluster = server().getFeature<ClusterFeature>();\n  defineDouble(\"SYS_DEFAULT_REPLICATION_FACTOR_SYSTEM\", cluster.systemReplicationFactor());\n}\n\nvoid V8DealerFeature::start() {\n  if (_copyInstallation) {\n    copyInstallationFiles();  \/\/ will exit process if it fails\n  } else {\n    \/\/ don't copy JS files on startup\n    \/\/ now check if we have a js directory inside the database directory, and if\n    \/\/ it looks good\n    auto& dbPathFeature = server().getFeature<DatabasePathFeature>();\n    const std::string dbJSPath =\n        FileUtils::buildFilename(dbPathFeature.directory(), \"js\");\n    const std::string checksumFile =\n        FileUtils::buildFilename(dbJSPath, StaticStrings::checksumFileJs);\n    const std::string serverPath = FileUtils::buildFilename(dbJSPath, \"server\");\n    const std::string commonPath = FileUtils::buildFilename(dbJSPath, \"common\");\n    if (FileUtils::isDirectory(dbJSPath) && FileUtils::exists(checksumFile) &&\n        FileUtils::isDirectory(serverPath) && FileUtils::isDirectory(commonPath)) {\n      \/\/ only load node modules from original startup path\n      _nodeModulesDirectory = _startupDirectory;\n      \/\/ js directory inside database directory looks good. now use it!\n      _startupDirectory = dbJSPath;\n    }\n  }\n\n  LOG_TOPIC(\"77c97\", DEBUG, Logger::V8)\n      << \"effective startup-directory: \" << _startupDirectory\n      << \", effective module-directories: \" << _moduleDirectories\n      << \", node-modules-directory: \" << _nodeModulesDirectory;\n\n  _startupLoader.setDirectory(_startupDirectory);\n  ServerState::instance()->setJavaScriptPath(_startupDirectory);\n\n  \/\/ dump paths\n  {\n    std::vector<std::string> paths;\n\n    paths.push_back(std::string(\"startup '\" + _startupDirectory + \"'\"));\n\n    if (!_moduleDirectories.empty()) {\n      paths.push_back(\n          std::string(\"module '\" + StringUtils::join(_moduleDirectories, \";\") + \"'\"));\n    }\n\n    if (!_appPath.empty()) {\n      paths.push_back(std::string(\"application '\" + _appPath + \"'\"));\n\n      \/\/ create app directory if it does not exist\n      if (!basics::FileUtils::isDirectory(_appPath)) {\n        std::string systemErrorStr;\n        long errorNo;\n\n        int res = TRI_CreateRecursiveDirectory(_appPath.c_str(), errorNo, systemErrorStr);\n\n        if (res == TRI_ERROR_NO_ERROR) {\n          LOG_TOPIC(\"86aa0\", INFO, arangodb::Logger::FIXME)\n              << \"created javascript.app-path directory '\" << _appPath << \"'\";\n        } else {\n          LOG_TOPIC(\"2d23f\", FATAL, arangodb::Logger::FIXME)\n              << \"unable to create javascript.app-path directory '\" << _appPath\n              << \"': \" << systemErrorStr;\n          FATAL_ERROR_EXIT();\n        }\n      }\n    }\n\n    LOG_TOPIC(\"86632\", INFO, arangodb::Logger::V8)\n        << \"JavaScript using \" << StringUtils::join(paths, \", \");\n  }\n\n  \/\/ set singleton\n  DEALER = this;\n\n  if (_nrMinContexts < 1) {\n    _nrMinContexts = 1;\n  }\n\n  \/\/ try to guess a suitable number of contexts\n  if (0 == _nrMaxContexts) {\n    \/\/ automatic maximum number of contexts should not be below 16\n    \/\/ this is because the number of cores may be too few for the cluster\n    \/\/ startup to properly run through with all its parallel requests\n    \/\/ and the potential need for multiple V8 contexts\n    _nrMaxContexts = (std::max)(uint64_t(0 \/*scheduler->concurrency()*\/), uint64_t(16));\n  }\n\n  if (_nrMinContexts > _nrMaxContexts) {\n    \/\/ max contexts must not be lower than min contexts\n    _nrMaxContexts = _nrMinContexts;\n  }\n\n  LOG_TOPIC(\"09e14\", DEBUG, Logger::V8) << \"number of V8 contexts: min: \" << _nrMinContexts\n                               << \", max: \" << _nrMaxContexts;\n\n  defineDouble(\"V8_CONTEXTS\", static_cast<double>(_nrMaxContexts));\n\n  \/\/ setup instances\n  {\n    CONDITION_LOCKER(guard, _contextCondition);\n    _contexts.reserve(static_cast<size_t>(_nrMaxContexts));\n    _busyContexts.reserve(static_cast<size_t>(_nrMaxContexts));\n    _idleContexts.reserve(static_cast<size_t>(_nrMaxContexts));\n    _dirtyContexts.reserve(static_cast<size_t>(_nrMaxContexts));\n\n    for (size_t i = 0; i < _nrMinContexts; ++i) {\n      guard.unlock();  \/\/ avoid lock order inversion in buildContext\n      V8Context* context = buildContext(nextId());\n      guard.lock();\n      TRI_ASSERT(context != nullptr);\n      try {\n        _contexts.push_back(context);\n      } catch (...) {\n        delete context;\n        throw;\n      }\n      ++_contextsCreated;\n    }\n\n    TRI_ASSERT(_contexts.size() > 0);\n    TRI_ASSERT(_contexts.size() <= _nrMaxContexts);\n    for (auto& context : _contexts) {\n      \/\/ apply context update is only run on contexts that no other\n      \/\/ threads can see (yet)\n      guard.unlock();\n      applyContextUpdate(context);\n      guard.lock();\n      _idleContexts.push_back(context);\n    }\n  }\n\n  auto& sysDbFeature = server().getFeature<arangodb::SystemDatabaseFeature>();\n  auto database = sysDbFeature.use();\n\n  loadJavaScriptFileInAllContexts(database.get(), \"server\/initialize.js\", nullptr);\n  startGarbageCollection();\n}\n\nvoid V8DealerFeature::copyInstallationFiles() {\n  if (!_enableJS &&\n      (ServerState::instance()->isAgent() || ServerState::instance()->isDBServer())) {\n    \/\/ skip expensive file-copying in case we are an agency or db server\n    \/\/ these do not need JavaScript support\n    return;\n  }\n\n  \/\/ get base path from DatabasePathFeature\n  auto& dbPathFeature = server().getFeature<DatabasePathFeature>();\n  std::string const copyJSPath =\n      FileUtils::buildFilename(dbPathFeature.directory(), \"js\");\n  if (copyJSPath == _startupDirectory) {\n    LOG_TOPIC(\"89fe2\", FATAL, arangodb::Logger::V8)\n        << \"'javascript.startup-directory' cannot be inside \"\n           \"'database.directory'\";\n    FATAL_ERROR_EXIT();\n  }\n  TRI_ASSERT(!copyJSPath.empty());\n\n  _nodeModulesDirectory = _startupDirectory;\n\n  const std::string checksumFile =\n      FileUtils::buildFilename(_startupDirectory, StaticStrings::checksumFileJs);\n  const std::string copyChecksumFile =\n      FileUtils::buildFilename(copyJSPath, StaticStrings::checksumFileJs);\n\n  bool overwriteCopy = false;\n  if (!FileUtils::exists(copyJSPath) || !FileUtils::exists(checksumFile) ||\n      !FileUtils::exists(copyChecksumFile)) {\n    overwriteCopy = true;\n  } else {\n    try {\n      overwriteCopy =\n          (FileUtils::slurp(copyChecksumFile) != FileUtils::slurp(checksumFile));\n    } catch (basics::Exception const& e) {\n      LOG_TOPIC(\"efa47\", ERR, Logger::V8) << \"Error reading '\" << StaticStrings::checksumFileJs\n                                 << \"' from disk: \" << e.what();\n      overwriteCopy = true;\n    }\n  }\n\n  if (overwriteCopy) {\n    \/\/ sanity check before removing an existing directory:\n    \/\/ check if for some reason we will be trying to remove the entire database\n    \/\/ directory...\n    if (FileUtils::exists(FileUtils::buildFilename(copyJSPath, \"ENGINE\"))) {\n      LOG_TOPIC(\"214d1\", FATAL, Logger::V8)\n          << \"JS installation path '\" << copyJSPath << \"' seems to be invalid\";\n      FATAL_ERROR_EXIT();\n    }\n\n    LOG_TOPIC(\"dd1c0\", DEBUG, Logger::V8) << \"Copying JS installation files from '\"\n                                 << _startupDirectory << \"' to '\" << copyJSPath << \"'\";\n    int res = TRI_ERROR_NO_ERROR;\n    if (FileUtils::exists(copyJSPath)) {\n      res = TRI_RemoveDirectory(copyJSPath.c_str());\n      if (res != TRI_ERROR_NO_ERROR) {\n        LOG_TOPIC(\"1a20d\", FATAL, Logger::V8) << \"Error cleaning JS installation path '\"\n                                     << copyJSPath << \"': \" << TRI_errno_string(res);\n        FATAL_ERROR_EXIT();\n      }\n    }\n    if (!FileUtils::createDirectory(copyJSPath, &res)) {\n      LOG_TOPIC(\"b8c79\", FATAL, Logger::V8) << \"Error creating JS installation path '\"\n                                   << copyJSPath << \"': \" << TRI_errno_string(res);\n      FATAL_ERROR_EXIT();\n    }\n\n    \/\/ intentionally do not copy js\/node\/node_modules...\n    \/\/ we avoid copying this directory because it contains 5000+ files at the\n    \/\/ moment, and copying them one by one is darn slow at least on Windows...\n    std::string const versionAppendix =\n        std::regex_replace(rest::Version::getServerVersion(),\n                           std::regex(\"-.*$\"), \"\");\n    std::string const nodeModulesPath =\n        FileUtils::buildFilename(\"js\", \"node\", \"node_modules\");\n    std::string const nodeModulesPathVersioned =\n        basics::FileUtils::buildFilename(\"js\", versionAppendix, \"node\",\n                                         \"node_modules\");\n\n    std::regex const binRegex(\"[\/\\\\\\\\]\\\\.bin[\/\\\\\\\\]\", std::regex::ECMAScript);\n\n    auto filter = [&nodeModulesPath, &nodeModulesPathVersioned, &binRegex](std::string const& filename) -> bool {\n      if (std::regex_search(filename, binRegex)) {\n        \/\/ don't copy files in .bin\n        return true;\n      }\n      std::string normalized = filename;\n      FileUtils::normalizePath(normalized);\n      if ((!nodeModulesPath.empty() && \n           normalized.size() >= nodeModulesPath.size() &&\n           normalized.substr(normalized.size() - nodeModulesPath.size(), nodeModulesPath.size()) == nodeModulesPath) ||\n          (!nodeModulesPathVersioned.empty() &&\n           normalized.size() >= nodeModulesPathVersioned.size() &&\n           normalized.substr(normalized.size() - nodeModulesPathVersioned.size(), nodeModulesPathVersioned.size()) == nodeModulesPathVersioned)) {\n        \/\/ filter it out!\n        return true;\n      }\n      \/\/ let the file\/directory pass through\n      return false;\n    };\n\n    std::string error;\n    if (!FileUtils::copyRecursive(_startupDirectory, copyJSPath, filter, error)) {\n      LOG_TOPIC(\"45261\", FATAL, Logger::V8) << \"Error copying JS installation files to '\"\n                                   << copyJSPath << \"': \" << error;\n      FATAL_ERROR_EXIT();\n    }\n\n    \/\/ attempt to copy enterprise JS files too.\n    \/\/ only required for developer installations, not packages\n    std::string const enterpriseJs =\n        basics::FileUtils::buildFilename(_startupDirectory, \"..\", \"enterprise\",\n                                         \"js\");\n\n    if (FileUtils::isDirectory(enterpriseJs)) {\n      std::function<bool(std::string const&)> const passAllFilter =\n          [](std::string const&) { return false; };\n      if (!FileUtils::copyRecursive(enterpriseJs, copyJSPath, passAllFilter, error)) {\n        LOG_TOPIC(\"ae9d3\", WARN, Logger::V8)\n            << \"Error copying enterprise JS installation files to '\"\n            << copyJSPath << \"': \" << error;\n      }\n    }\n  }\n  _startupDirectory = copyJSPath;\n}\n\nV8Context* V8DealerFeature::addContext() {\n  if (server().isStopping()) {\n    THROW_ARANGO_EXCEPTION(TRI_ERROR_SHUTTING_DOWN);\n  }\n\n  V8Context* context = buildContext(nextId());\n\n  try {\n    \/\/ apply context update is only run on contexts that no other\n    \/\/ threads can see (yet)\n    applyContextUpdate(context);\n\n    auto& sysDbFeature = server().getFeature<arangodb::SystemDatabaseFeature>();\n    auto database = sysDbFeature.use();\n\n    TRI_ASSERT(database != nullptr);\n\n    \/\/ no other thread can use the context when we are here, as the\n    \/\/ context has not been added to the global list of contexts yet\n    loadJavaScriptFileInContext(database.get(), \"server\/initialize.js\", context, nullptr);\n\n    ++_contextsCreated;\n\n    return context;\n  } catch (...) {\n    delete context;\n    throw;\n  }\n}\n\nvoid V8DealerFeature::unprepare() {\n  shutdownContexts();\n\n  \/\/ delete GC thread after all action threads have been stopped\n  _gcThread.reset();\n\n  DEALER = nullptr;\n}\n\nbool V8DealerFeature::addGlobalContextMethod(std::string const& method) {\n  bool result = true;\n\n  CONDITION_LOCKER(guard, _contextCondition);\n\n  for (auto& context : _contexts) {\n    try {\n      if (!context->addGlobalContextMethod(method)) {\n        result = false;\n      }\n    } catch (...) {\n      result = false;\n    }\n  }\n  return result;\n}\n\nvoid V8DealerFeature::collectGarbage() {\n  V8GcThread* gc = static_cast<V8GcThread*>(_gcThread.get());\n  TRI_ASSERT(gc != nullptr);\n\n  \/\/ this flag will be set to true if we timed out waiting for a GC signal\n  \/\/ if set to true, the next cycle will use a reduced wait time so the GC\n  \/\/ can be performed more early for all dirty contexts. The flag is set\n  \/\/ to false again once all contexts have been cleaned up and there is nothing\n  \/\/ more to do\n  bool useReducedWait = false;\n  bool preferFree = false;\n\n  \/\/ the time we'll wait for a signal\n  uint64_t const regularWaitTime = static_cast<uint64_t>(_gcFrequency * 1000.0 * 1000.0);\n\n  \/\/ the time we'll wait for a signal when the previous wait timed out\n  uint64_t const reducedWaitTime = static_cast<uint64_t>(_gcFrequency * 1000.0 * 200.0);\n\n  while (!_stopping) {\n    try {\n      V8Context* context = nullptr;\n      bool wasDirty = false;\n\n      {\n        bool gotSignal = false;\n        preferFree = !preferFree;\n        CONDITION_LOCKER(guard, _contextCondition);\n\n        if (_dirtyContexts.empty()) {\n          uint64_t waitTime = useReducedWait ? reducedWaitTime : regularWaitTime;\n\n          \/\/ we'll wait for a signal or a timeout\n          gotSignal = guard.wait(waitTime);\n        }\n\n        if (preferFree && !_idleContexts.empty()) {\n          context = pickFreeContextForGc();\n        }\n\n        if (context == nullptr && !_dirtyContexts.empty()) {\n          context = _dirtyContexts.back();\n          _dirtyContexts.pop_back();\n          if (context->invocationsSinceLastGc() < 50 && !context->_hasActiveExternals) {\n            \/\/ don't collect this one yet. it doesn't have externals, so there\n            \/\/ is no urge for garbage collection\n            _idleContexts.emplace_back(context);\n            context = nullptr;\n          } else {\n            wasDirty = true;\n          }\n        }\n\n        if (context == nullptr && !preferFree && !gotSignal && !_idleContexts.empty()) {\n          \/\/ we timed out waiting for a signal, so we have idle time that we can\n          \/\/ spend on running the GC pro-actively\n          \/\/ We'll pick one of the free contexts and clean it up\n          context = pickFreeContextForGc();\n        }\n\n        \/\/ there is no context to clean up, probably they all have been cleaned\n        \/\/ up already. increase the wait time so we don't cycle too much in the\n        \/\/ GC loop and waste CPU unnecessary\n        useReducedWait = (context != nullptr);\n      }\n\n      \/\/ update last gc time\n      double lastGc = TRI_microtime();\n      gc->updateGcStamp(lastGc);\n\n      if (context != nullptr) {\n        LOG_TOPIC(\"6bb08\", TRACE, arangodb::Logger::V8)\n            << \"collecting V8 garbage in context #\" << context->id()\n            << \", invocations total: \" << context->invocations()\n            << \", invocations since last gc: \" << context->invocationsSinceLastGc()\n            << \", hasActive: \" << context->_hasActiveExternals\n            << \", wasDirty: \" << wasDirty;\n        bool hasActiveExternals = false;\n        auto isolate = context->_isolate;\n        {\n          \/\/ this guard will lock and enter the isolate\n          \/\/ and automatically exit and unlock it when it runs out of scope\n          V8ContextEntryGuard contextGuard(context);\n\n          v8::HandleScope scope(isolate);\n\n          auto localContext = v8::Local<v8::Context>::New(isolate, context->_context);\n\n          localContext->Enter();\n          {\n            v8::Context::Scope contextScope(localContext);\n\n            context->assertLocked();\n\n            TRI_GET_GLOBALS();\n            v8g->_inForcedCollect = true;\n            TRI_RunGarbageCollectionV8(isolate, 1.0);\n            v8g->_inForcedCollect = false;\n            hasActiveExternals = v8g->hasActiveExternals();\n          }\n          localContext->Exit();\n        }\n\n        \/\/ update garbage collection statistics\n        context->_hasActiveExternals = hasActiveExternals;\n        context->setCleaned(lastGc);\n\n        {\n          CONDITION_LOCKER(guard, _contextCondition);\n\n          if (_contexts.size() > _nrMinContexts && !context->isDefault() &&\n              context->shouldBeRemoved(_maxContextAge, _maxContextInvocations) &&\n              _dynamicContextCreationBlockers == 0) {\n            \/\/ remove the extra context as it is not needed anymore\n            _contexts.erase(std::remove_if(_contexts.begin(), _contexts.end(),\n                                           [&context](V8Context* c) {\n                                             return (c->id() == context->id());\n                                           }));\n\n            LOG_TOPIC(\"0a995\", DEBUG, Logger::V8)\n                << \"removed superfluous V8 context #\" << context->id()\n                << \", number of contexts is now: \" << _contexts.size();\n\n            guard.unlock();\n            shutdownContext(context);\n          } else {\n            \/\/ put it back into the free list\n            if (wasDirty) {\n              _idleContexts.emplace_back(context);\n            } else {\n              _idleContexts.insert(_idleContexts.begin(), context);\n            }\n            guard.broadcast();\n          }\n        }\n      } else {\n        useReducedWait = true;  \/\/ sanity\n      }\n    } catch (...) {\n      \/\/ simply ignore errors here\n      useReducedWait = false;\n    }\n  }\n\n  _gcFinished = true;\n}\n\nvoid V8DealerFeature::unblockDynamicContextCreation() {\n  CONDITION_LOCKER(guard, _contextCondition);\n\n  TRI_ASSERT(_dynamicContextCreationBlockers > 0);\n  --_dynamicContextCreationBlockers;\n}\n\nvoid V8DealerFeature::loadJavaScriptFileInAllContexts(TRI_vocbase_t* vocbase,\n                                                      std::string const& file,\n                                                      VPackBuilder* builder) {\n  if (builder != nullptr) {\n    builder->openArray();\n  }\n\n  std::vector<V8Context*> contexts;\n  {\n    CONDITION_LOCKER(guard, _contextCondition);\n\n    while (_nrInflightContexts > 0) {\n      \/\/ wait until all pending context creation requests have been satisified\n      guard.wait(10000);\n    }\n\n    \/\/ copy the list of contexts into a local variable\n    contexts = _contexts;\n    \/\/ block the addition or removal of contexts\n    ++_dynamicContextCreationBlockers;\n  }\n\n  TRI_DEFER(unblockDynamicContextCreation());\n\n  LOG_TOPIC(\"1364d\", TRACE, Logger::V8) << \"loading JavaScript file '\" << file << \"' in all (\"\n                               << contexts.size() << \") V8 contexts\";\n\n  \/\/ now safely scan the local copy of the contexts\n  for (auto& context : contexts) {\n    CONDITION_LOCKER(guard, _contextCondition);\n\n    while (_busyContexts.find(context) != _busyContexts.end()) {\n      \/\/ we must not enter the context if another thread is also using it...\n      guard.wait(10000);\n    }\n\n    auto it = std::find(_dirtyContexts.begin(), _dirtyContexts.end(), context);\n    if (it != _dirtyContexts.end()) {\n      \/\/ context is in _dirtyContexts\n      \/\/ remove it from there\n      _dirtyContexts.erase(it);\n\n      guard.unlock();\n      try {\n        loadJavaScriptFileInContext(vocbase, file, context, builder);\n      } catch (...) {\n        guard.lock();\n        _dirtyContexts.push_back(context);\n        throw;\n      }\n      \/\/ and re-insert it after we are done\n      guard.lock();\n      _dirtyContexts.push_back(context);\n    } else {\n      \/\/ if the context is neither busy nor dirty, it must be idle\n      auto it = std::find(_idleContexts.begin(), _idleContexts.end(), context);\n      if (it != _idleContexts.end()) {\n        \/\/ remove it from there\n        _idleContexts.erase(it);\n\n        guard.unlock();\n        try {\n          loadJavaScriptFileInContext(vocbase, file, context, builder);\n        } catch (...) {\n          guard.lock();\n          _idleContexts.push_back(context);\n          throw;\n        }\n        \/\/ and re-insert it after we are done\n        guard.lock();\n        _idleContexts.push_back(context);\n      } else {\n        LOG_TOPIC(\"d3a7f\", WARN, Logger::V8) << \"v8 context #\" << context->id() << \" has disappeared\";\n      }\n    }\n  }\n\n  if (builder != nullptr) {\n    builder->close();\n  }\n}\n\nvoid V8DealerFeature::startGarbageCollection() {\n  TRI_ASSERT(_gcThread == nullptr);\n  _gcThread.reset(new V8GcThread(*this));\n  _gcThread->start();\n\n  _gcFinished = false;\n}\n\nvoid V8DealerFeature::prepareLockedContext(TRI_vocbase_t* vocbase, V8Context* context,\n                                           JavaScriptSecurityContext const& securityContext) {\n  TRI_ASSERT(vocbase != nullptr);\n\n  \/\/ when we get here, we should have a context and an isolate\n  context->assertLocked();\n\n  auto isolate = context->_isolate;\n\n  {\n    v8::HandleScope scope(isolate);\n    auto localContext = v8::Local<v8::Context>::New(isolate, context->_context);\n    localContext->Enter();\n\n    {\n      v8::Context::Scope contextScope(localContext);\n\n      context->assertLocked();\n      TRI_GET_GLOBALS();\n\n      \/\/ initialize the context data\n      v8g->_expressionContext = nullptr;\n      v8g->_vocbase = vocbase;\n      v8g->_securityContext = securityContext;\n\n      try {\n        LOG_TOPIC(\"94226\", TRACE, arangodb::Logger::V8)\n            << \"entering V8 context #\" << context->id();\n        context->handleGlobalContextMethods();\n      } catch (...) {\n        \/\/ ignore errors here\n      }\n    }\n  }\n}\n\n\/\/\/ @brief enter a V8 context\n\/\/\/ currently returns a nullptr if no context can be acquired in time\nV8Context* V8DealerFeature::enterContext(TRI_vocbase_t* vocbase, JavaScriptSecurityContext const& securityContext) {\n  TRI_ASSERT(vocbase != nullptr);\n\n  if (_stopping) {\n    return nullptr;\n  }\n\n  if (!vocbase->use()) {\n    return nullptr;\n  }\n\n\n  double const startTime = TRI_microtime();\n  TRI_ASSERT(v8::Isolate::GetCurrent() == nullptr);\n\n  V8Context* context = nullptr;\n\n  \/\/ look for a free context\n  {\n    CONDITION_LOCKER(guard, _contextCondition);\n\n    while (_idleContexts.empty() && !_stopping) {\n      TRI_ASSERT(guard.isLocked());\n\n      LOG_TOPIC(\"619ab\", TRACE, arangodb::Logger::V8) << \"waiting for unused V8 context\";\n\n      if (!_dirtyContexts.empty()) {\n        \/\/ we'll use a dirty context in this case\n        _idleContexts.push_back(_dirtyContexts.back());\n        _dirtyContexts.pop_back();\n        break;\n      }\n\n      bool const contextLimitNotExceeded =\n          (_contexts.size() + _nrInflightContexts < _nrMaxContexts);\n\n      if (contextLimitNotExceeded && _dynamicContextCreationBlockers == 0) {\n        ++_nrInflightContexts;\n\n        TRI_ASSERT(guard.isLocked());\n        guard.unlock();\n\n        try {\n          LOG_TOPIC(\"973d7\", DEBUG, Logger::V8) << \"creating additional V8 context\";\n          context = addContext();\n        } catch (...) {\n          guard.lock();\n\n          \/\/ clean up state\n          --_nrInflightContexts;\n          throw;\n        }\n\n        \/\/ must re-lock\n        TRI_ASSERT(!guard.isLocked());\n        guard.lock();\n\n        --_nrInflightContexts;\n        try {\n          _contexts.push_back(context);\n        } catch (...) {\n          \/\/ oops\n          delete context;\n          context = nullptr;\n          ++_contextsDestroyed;\n          continue;\n        }\n\n        TRI_ASSERT(guard.isLocked());\n        try {\n          _idleContexts.push_back(context);\n          LOG_TOPIC(\"25f94\", DEBUG, Logger::V8)\n              << \"created additional V8 context #\" << context->id()\n              << \", number of contexts is now \" << _contexts.size();\n        } catch (...) {\n          TRI_ASSERT(!_contexts.empty());\n          _contexts.pop_back();\n          TRI_ASSERT(context != nullptr);\n          delete context;\n          ++_contextsDestroyed;\n        }\n\n        guard.broadcast();\n        continue;\n      }\n\n      TRI_ASSERT(guard.isLocked());\n\n      constexpr double maxWaitTime = 60.0;\n      double const now = TRI_microtime();\n      if (now - startTime >= maxWaitTime) {\n        vocbase->release();\n\n        ++_contextsEnterFailures;\n        \n        LOG_TOPIC(\"e1807\", WARN, arangodb::Logger::V8)\n            << \"giving up waiting for unused V8 context for '\"\n            << securityContext.typeName() << \"' operation after \"\n            << Logger::FIXED(maxWaitTime) << \" s - \"\n            << \"contexts: \" << _contexts.size() << \"\/\" << _nrMaxContexts \n            << \", idle: \" << _idleContexts.size() \n            << \", busy: \" << _busyContexts.size() \n            << \", dirty: \" << _dirtyContexts.size() \n            << \", in flight: \" << _nrInflightContexts\n            << \" - context overview following...\";\n\n        size_t i = 0;\n        for (auto const& it : _contexts) {\n          ++i;\n          LOG_TOPIC(\"74439\", WARN, arangodb::Logger::V8)\n              << \"- context #\" << it->id() \n              << \" (\" << i << \"\/\" << _contexts.size() << \")\"\n              << \": acquired: \" << Logger::FIXED(now - it->acquired()) << \" s ago\" \n              << \", performing '\" << it->description() << \"' operation\";\n        }\n        return nullptr;\n      }\n      \n      guard.wait(100000);\n    }\n\n    TRI_ASSERT(guard.isLocked());\n\n    \/\/ in case we are in the shutdown phase, do not enter a context!\n    \/\/ the context might have been deleted by the shutdown\n    if (_stopping) {\n      vocbase->release();\n      return nullptr;\n    }\n\n    TRI_ASSERT(!_idleContexts.empty());\n\n    context = _idleContexts.back();\n    LOG_TOPIC(\"bbe93\", TRACE, arangodb::Logger::V8)\n        << \"found unused V8 context #\" << context->id();\n    TRI_ASSERT(context != nullptr);\n\n    _idleContexts.pop_back();\n\n    \/\/ should not fail because we reserved enough space beforehand\n    _busyContexts.emplace(context);\n\n    context->setDescription(securityContext.typeName(), TRI_microtime());\n  }\n\n  TRI_ASSERT(context != nullptr);\n  context->lockAndEnter();\n  context->assertLocked();\n\n  prepareLockedContext(vocbase, context, securityContext);\n  ++_contextsEntered;\n\n  return context;\n}\n\nvoid V8DealerFeature::exitContextInternal(V8Context* context) {\n  TRI_DEFER(context->unlockAndExit());\n  cleanupLockedContext(context);\n}\n\nvoid V8DealerFeature::cleanupLockedContext(V8Context* context) {\n  TRI_ASSERT(context != nullptr);\n\n  LOG_TOPIC(\"e1c52\", TRACE, arangodb::Logger::V8) << \"leaving V8 context #\" << context->id();\n\n  auto isolate = context->_isolate;\n  TRI_ASSERT(isolate != nullptr);\n  TRI_GET_GLOBALS();\n  context->assertLocked();\n\n  bool canceled = false;\n\n  if (V8PlatformFeature::isOutOfMemory(isolate)) {\n    static double const availableTime = 300.0;\n\n    v8::HandleScope scope(isolate);\n    {\n      auto localContext = v8::Local<v8::Context>::New(isolate, context->_context);\n      localContext->Enter();\n\n      {\n        v8::Context::Scope contextScope(localContext);\n        v8g->_inForcedCollect = true;\n        TRI_RunGarbageCollectionV8(isolate, availableTime);\n        v8g->_inForcedCollect = false;\n      }\n\n      \/\/ needs to be reset after the garbage collection\n      V8PlatformFeature::resetOutOfMemory(isolate);\n\n      localContext->Exit();\n    }\n  }\n\n  \/\/ update data for later garbage collection\n  {\n    TRI_GET_GLOBALS();\n    context->_hasActiveExternals = v8g->hasActiveExternals();\n    TRI_vocbase_t* vocbase = v8g->_vocbase;\n\n    TRI_ASSERT(vocbase != nullptr);\n    \/\/ release last recently used vocbase\n    vocbase->release();\n\n    \/\/ check for cancelation requests\n    canceled = v8g->_canceled;\n    v8g->_canceled = false;\n  }\n\n  \/\/ check if we need to execute global context methods\n  bool const runGlobal = context->hasGlobalMethodsQueued();\n\n  {\n    v8::HandleScope scope(isolate);\n\n    \/\/ if the execution was canceled, we need to cleanup\n    if (canceled) {\n      context->handleCancelationCleanup();\n    }\n\n    \/\/ run global context methods\n    if (runGlobal) {\n      context->assertLocked();\n\n      try {\n        context->handleGlobalContextMethods();\n      } catch (...) {\n        \/\/ ignore errors here\n      }\n    }\n\n    TRI_GET_GLOBALS();\n\n    \/\/ reset the context data; gc should be able to run without it\n    v8g->_expressionContext = nullptr;\n    v8g->_vocbase = nullptr;\n    v8g->_securityContext.reset();\n\n    \/\/ now really exit\n    auto localContext = v8::Local<v8::Context>::New(isolate, context->_context);\n    localContext->Exit();\n  }\n}\n\nvoid V8DealerFeature::exitContext(V8Context* context) {\n  cleanupLockedContext(context);\n\n  V8GcThread* gc = static_cast<V8GcThread*>(_gcThread.get());\n\n  if (gc != nullptr) {\n    \/\/ default is no garbage collection\n    bool performGarbageCollection = false;\n    bool forceGarbageCollection = false;\n\n    \/\/ postpone garbage collection for standard contexts\n    double lastGc = gc->getLastGcStamp();\n    if (context->_lastGcStamp + _gcFrequency < lastGc) {\n      performGarbageCollection = true;\n      if (context->_lastGcStamp + 30 * _gcFrequency < lastGc) {\n        \/\/ force the GC, so that it happens eventually\n        forceGarbageCollection = true;\n        LOG_TOPIC(\"f543a\", TRACE, arangodb::Logger::V8)\n            << \"V8 context #\" << context->id()\n            << \" has reached GC timeout threshold and will be forced into GC\";\n      } else {\n        LOG_TOPIC(\"f3526\", TRACE, arangodb::Logger::V8)\n            << \"V8 context #\" << context->id()\n            << \" has reached GC timeout threshold and will be scheduled for GC\";\n      }\n    } else if (context->invocationsSinceLastGc() >= _gcInterval) {\n      LOG_TOPIC(\"c6441\", TRACE, arangodb::Logger::V8)\n          << \"V8 context #\" << context->id()\n          << \" has reached maximum number of requests and will \"\n             \"be scheduled for GC\";\n      performGarbageCollection = true;\n    }\n\n    context->unlockAndExit();\n    CONDITION_LOCKER(guard, _contextCondition);\n\n    context->clearDescription();\n\n    if (performGarbageCollection && (forceGarbageCollection || !_idleContexts.empty())) {\n      \/\/ only add the context to the dirty list if there is at least one other\n      \/\/ free context\n\n      \/\/ note that re-adding the context here should not fail as we reserved\n      \/\/ enough room for all contexts during startup\n      _dirtyContexts.emplace_back(context);\n    } else {\n      \/\/ note that re-adding the context here should not fail as we reserved\n      \/\/ enough room for all contexts during startup\n      _idleContexts.emplace_back(context);\n    }\n\n    _busyContexts.erase(context);\n\n    LOG_TOPIC(\"fc763\", TRACE, arangodb::Logger::V8)\n        << \"returned dirty V8 context #\" << context->id();\n    guard.broadcast();\n  } else {\n    context->unlockAndExit();\n    CONDITION_LOCKER(guard, _contextCondition);\n\n    context->clearDescription();\n\n    _busyContexts.erase(context);\n    \/\/ note that re-adding the context here should not fail as we reserved\n    \/\/ enough room for all contexts during startup\n    _idleContexts.emplace_back(context);\n\n    LOG_TOPIC(\"82410\", TRACE, arangodb::Logger::V8)\n        << \"returned dirty V8 context #\" << context->id() << \" back into free\";\n    guard.broadcast();\n  }\n\n  ++_contextsExited;\n}\n\nvoid V8DealerFeature::defineContextUpdate(\n    std::function<void(v8::Isolate*, v8::Handle<v8::Context>, size_t)> func,\n    TRI_vocbase_t* vocbase) {\n  _contextUpdates.emplace_back(func, vocbase);\n}\n\n\/\/ apply context update is only run on contexts that no other\n\/\/ threads can see (yet)\nvoid V8DealerFeature::applyContextUpdate(V8Context* context) {\n  for (auto& p : _contextUpdates) {\n    auto vocbase = p.second;\n\n    if (vocbase == nullptr) {\n      vocbase =\n          server().hasFeature<arangodb::SystemDatabaseFeature>()\n              ? server().getFeature<arangodb::SystemDatabaseFeature>().use().get()\n              : nullptr;\n\n      if (!vocbase) {\n        continue;\n      }\n    }\n\n    if (!vocbase->use()) {\n      \/\/ oops\n      continue;\n    }\n\n    JavaScriptSecurityContext securityContext = JavaScriptSecurityContext::createInternalContext();\n\n    context->lockAndEnter();\n    prepareLockedContext(vocbase, context, securityContext);\n    TRI_DEFER(exitContextInternal(context));\n\n    {\n      v8::HandleScope scope(context->_isolate);\n      auto localContext = v8::Local<v8::Context>::New(context->_isolate, context->_context);\n      localContext->Enter();\n\n      {\n        v8::Context::Scope contextScope(localContext);\n        p.first(context->_isolate, localContext, context->id());\n      }\n\n      localContext->Exit();\n    }\n\n    LOG_TOPIC(\"73e16\", TRACE, arangodb::Logger::V8) << \"updated V8 context #\" << context->id();\n  }\n}\n\nvoid V8DealerFeature::shutdownContexts() {\n  _stopping = true;\n\n  \/\/ wait for all contexts to finish\n  {\n    CONDITION_LOCKER(guard, _contextCondition);\n    guard.broadcast();\n\n    for (size_t n = 0; n < 10 * 5; ++n) {\n      if (_busyContexts.empty()) {\n        LOG_TOPIC(\"36259\", DEBUG, arangodb::Logger::V8) << \"no busy V8 contexts\";\n        break;\n      }\n\n      LOG_TOPIC(\"ea785\", DEBUG, arangodb::Logger::V8) << \"waiting for busy V8 contexts (\"\n                                             << _busyContexts.size() << \") to finish \";\n\n      guard.wait(100 * 1000);\n    }\n  }\n\n  \/\/ send all busy contexts a terminate signal\n  {\n    CONDITION_LOCKER(guard, _contextCondition);\n\n    for (auto& it : _busyContexts) {\n      LOG_TOPIC(\"e907b\", WARN, arangodb::Logger::V8)\n          << \"sending termination signal to V8 context #\" << it->id();\n      it->_isolate->TerminateExecution();\n    }\n  }\n\n  \/\/ wait for one minute\n  {\n    CONDITION_LOCKER(guard, _contextCondition);\n\n    for (size_t n = 0; n < 10 * 60; ++n) {\n      if (_busyContexts.empty()) {\n        break;\n      }\n\n      guard.wait(100000);\n    }\n  }\n\n  if (!_busyContexts.empty()) {\n    LOG_TOPIC(\"4b09f\", FATAL, arangodb::Logger::V8) << \"cannot shutdown V8 contexts\";\n    FATAL_ERROR_EXIT();\n  }\n\n  \/\/ stop GC thread\n  if (_gcThread != nullptr) {\n    LOG_TOPIC(\"c6543\", DEBUG, arangodb::Logger::V8)\n        << \"waiting for V8 GC thread to finish action\";\n    _gcThread->beginShutdown();\n\n    \/\/ wait until garbage collector thread is done\n    while (!_gcFinished) {\n      std::this_thread::sleep_for(std::chrono::milliseconds(10));\n    }\n\n    LOG_TOPIC(\"ea409\", DEBUG, arangodb::Logger::V8)\n        << \"commanding V8 GC thread to terminate\";\n  }\n\n  \/\/ shutdown all instances\n  {\n    std::vector<V8Context*> contexts;\n    {\n      CONDITION_LOCKER(guard, _contextCondition);\n      contexts = _contexts;\n      _contexts.clear();\n    }\n\n    for (auto& context : contexts) {\n      shutdownContext(context);\n    }\n  }\n\n  LOG_TOPIC(\"7cdb2\", DEBUG, arangodb::Logger::V8) << \"V8 contexts are shut down\";\n}\n\nV8Context* V8DealerFeature::pickFreeContextForGc() {\n  int const n = static_cast<int>(_idleContexts.size());\n\n  if (n == 0) {\n    \/\/ this is easy...\n    return nullptr;\n  }\n\n  V8GcThread* gc = static_cast<V8GcThread*>(_gcThread.get());\n  TRI_ASSERT(gc != nullptr);\n\n  \/\/ we got more than 1 context to clean up, pick the one with the \"oldest\" GC\n  \/\/ stamp\n  int pickedContextNr = -1;  \/\/ index of context with lowest GC stamp, -1 means \"none\"\n\n  for (int i = n - 1; i > 0; --i) {\n    \/\/ check if there's actually anything to clean up in the context\n    if (_idleContexts[i]->invocationsSinceLastGc() < 50 && !_idleContexts[i]->_hasActiveExternals) {\n      continue;\n    }\n\n    \/\/ compare last GC stamp\n    if (pickedContextNr == -1 || _idleContexts[i]->_lastGcStamp <=\n                                     _idleContexts[pickedContextNr]->_lastGcStamp) {\n      pickedContextNr = i;\n    }\n  }\n\n  \/\/ we now have the context to clean up in pickedContextNr\n\n  if (pickedContextNr == -1) {\n    \/\/ no context found\n    return nullptr;\n  }\n\n  \/\/ this is the context to clean up\n  V8Context* context = _idleContexts[pickedContextNr];\n  TRI_ASSERT(context != nullptr);\n\n  \/\/ now compare its last GC timestamp with the last global GC stamp\n  if (context->_lastGcStamp + _gcFrequency >= gc->getLastGcStamp()) {\n    \/\/ no need yet to clean up the context\n    return nullptr;\n  }\n\n  \/\/ we'll pop the context from the vector. the context might be at\n  \/\/ any position in the vector so we need to move the other elements\n  \/\/ around\n  if (n > 1) {\n    for (int i = pickedContextNr; i < n - 1; ++i) {\n      _idleContexts[i] = _idleContexts[i + 1];\n    }\n  }\n  _idleContexts.pop_back();\n\n  return context;\n}\n\nV8Context* V8DealerFeature::buildContext(size_t id) {\n  V8PlatformFeature& v8platform = server().getFeature<V8PlatformFeature>();\n\n  \/\/ create isolate\n  v8::Isolate* isolate = v8platform.createIsolate();\n  TRI_ASSERT(isolate != nullptr);\n\n  \/\/ pass isolate to a new context\n  auto context = std::make_unique<V8Context>(id, isolate);\n\n  try {\n    \/\/ this guard will lock and enter the isolate\n    \/\/ and automatically exit and unlock it when it runs out of scope\n    V8ContextEntryGuard contextGuard(context.get());\n\n    v8::HandleScope scope(isolate);\n\n    v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);\n\n    v8::Persistent<v8::Context> persistentContext;\n    persistentContext.Reset(isolate, v8::Context::New(isolate, nullptr, global));\n    auto localContext = v8::Local<v8::Context>::New(isolate, persistentContext);\n\n    localContext->Enter();\n\n    {\n      v8::Context::Scope contextScope(localContext);\n\n      TRI_CreateV8Globals(server(), isolate, id);\n      context->_context.Reset(context->_isolate, localContext);\n\n      if (context->_context.IsEmpty()) {\n        LOG_TOPIC(\"ba904\", FATAL, arangodb::Logger::V8) << \"cannot initialize V8 engine\";\n        FATAL_ERROR_EXIT();\n      }\n\n      v8::Handle<v8::Object> globalObj = localContext->Global();\n      globalObj->Set(localContext, TRI_V8_ASCII_STRING(isolate, \"GLOBAL\"), globalObj).FromMaybe(false);\n      globalObj->Set(localContext, TRI_V8_ASCII_STRING(isolate, \"global\"), globalObj).FromMaybe(false);\n      globalObj->Set(localContext, TRI_V8_ASCII_STRING(isolate, \"root\"),   globalObj).FromMaybe(false);\n\n      std::string modules = \"\";\n      std::string sep = \"\";\n\n      std::vector<std::string> directories;\n      directories.insert(directories.end(), _moduleDirectories.begin(),\n                         _moduleDirectories.end());\n      directories.emplace_back(_startupDirectory);\n      if (!_nodeModulesDirectory.empty() && _nodeModulesDirectory != _startupDirectory) {\n        directories.emplace_back(_nodeModulesDirectory);\n      }\n\n      for (auto const& directory : directories) {\n        modules += sep;\n        sep = \";\";\n\n        modules += FileUtils::buildFilename(directory, \"server\/modules\") + sep +\n                   FileUtils::buildFilename(directory, \"common\/modules\") + sep +\n                   FileUtils::buildFilename(directory, \"node\");\n      }\n      TRI_InitV8UserFunctions(isolate, localContext);\n      TRI_InitV8UserStructures(isolate, localContext);\n      TRI_InitV8Buffer(isolate);\n      TRI_InitV8Utils(isolate, localContext, _startupDirectory, modules);\n      TRI_InitV8ServerUtils(isolate);\n      TRI_InitV8Shell(isolate);\n      TRI_InitV8Ttl(isolate);\n\n      {\n        v8::HandleScope scope(isolate);\n\n        TRI_AddGlobalVariableVocbase(isolate,\n                                     TRI_V8_ASCII_STRING(isolate, \"APP_PATH\"),\n                                     TRI_V8_STD_STRING(isolate, _appPath));\n\n        for (auto j : _definedBooleans) {\n          localContext->Global()\n              ->DefineOwnProperty(TRI_IGETC, TRI_V8_STD_STRING(isolate, j.first),\n                                  v8::Boolean::New(isolate, j.second),\n                                  v8::ReadOnly)\n              .FromMaybe(false);  \/\/ Ignore it...\n        }\n\n        for (auto j : _definedDoubles) {\n          localContext->Global()\n              ->DefineOwnProperty(TRI_IGETC, TRI_V8_STD_STRING(isolate, j.first),\n                                  v8::Number::New(isolate, j.second), v8::ReadOnly)\n              .FromMaybe(false);  \/\/ Ignore it...\n        }\n\n        for (auto const& j : _definedStrings) {\n          localContext->Global()\n              ->DefineOwnProperty(TRI_IGETC, TRI_V8_STD_STRING(isolate, j.first),\n                                  TRI_V8_STD_STRING(isolate, j.second),\n                                  v8::ReadOnly)\n              .FromMaybe(false);  \/\/ Ignore it...\n        }\n      }\n    }\n\n    \/\/ and return from the context\n    localContext->Exit();\n  } catch (...) {\n    LOG_TOPIC(\"35586\", WARN, Logger::V8)\n        << \"caught exception during context initialization\";\n    v8platform.disposeIsolate(isolate);\n    throw;\n  }\n\n  \/\/ some random delay value to add as an initial garbage collection offset\n  \/\/ this avoids collecting all contexts at the very same time\n  double const randomWait = static_cast<double>(RandomGenerator::interval(0, 60));\n\n  \/\/ initialize garbage collection for context\n  context->_hasActiveExternals = true;\n  context->_lastGcStamp = TRI_microtime() + randomWait;\n\n  LOG_TOPIC(\"83428\", TRACE, arangodb::Logger::V8) << \"initialized V8 context #\" << id;\n\n  return context.release();\n}\n\nV8DealerFeature::Statistics V8DealerFeature::getCurrentContextNumbers() {\n  CONDITION_LOCKER(guard, _contextCondition);\n\n  return {_contexts.size(), _busyContexts.size(), _dirtyContexts.size(),\n          _idleContexts.size(), _nrMaxContexts, _nrMinContexts};\n}\n\nstd::vector<V8DealerFeature::DetailedContextStatistics> V8DealerFeature::getCurrentContextDetails() {\n  std::vector<V8DealerFeature::DetailedContextStatistics> result;\n  {\n    CONDITION_LOCKER(guard, _contextCondition);\n    result.reserve(_contexts.size());\n    for (auto oneCtx : _contexts) {\n      auto isolate = oneCtx->_isolate;\n      TRI_GET_GLOBALS();\n      result.push_back(DetailedContextStatistics\n                       {\n                        v8g->_id,\n                        v8g->_lastMaxTime,\n                        v8g->_countOfTimes,\n                        v8g->_heapMax,\n                        v8g->_heapLow,\n                        oneCtx->invocations()\n                       });\n    }\n  }\n  return result;\n}\n\nbool V8DealerFeature::loadJavaScriptFileInContext(TRI_vocbase_t* vocbase,\n                                                  std::string const& file, V8Context* context,\n                                                  VPackBuilder* builder) {\n  TRI_ASSERT(vocbase != nullptr);\n  TRI_ASSERT(context != nullptr);\n\n  if (_stopping) {\n    return false;\n  }\n\n  if (!vocbase->use()) {\n    return false;\n  }\n\n  JavaScriptSecurityContext securityContext = JavaScriptSecurityContext::createInternalContext();\n\n  context->lockAndEnter();\n  prepareLockedContext(vocbase, context, securityContext);\n  TRI_DEFER(exitContextInternal(context));\n\n  try {\n    loadJavaScriptFileInternal(file, context, builder);\n  } catch (...) {\n    LOG_TOPIC(\"e099e\", WARN, Logger::V8)\n        << \"caught exception while executing JavaScript file '\" << file\n        << \"' in context #\" << context->id();\n    throw;\n  }\n\n  return true;\n}\n\nvoid V8DealerFeature::loadJavaScriptFileInternal(std::string const& file, V8Context* context,\n                                                 VPackBuilder* builder) {\n  v8::HandleScope scope(context->_isolate);\n  auto localContext = v8::Local<v8::Context>::New(context->_isolate, context->_context);\n  localContext->Enter();\n\n  {\n    v8::Context::Scope contextScope(localContext);\n\n    switch (_startupLoader.loadScript(context->_isolate, localContext, file, builder)) {\n      case JSLoader::eSuccess:\n        LOG_TOPIC(\"29e73\", TRACE, arangodb::Logger::V8) << \"loaded JavaScript file '\" << file << \"'\";\n        break;\n      case JSLoader::eFailLoad:\n        LOG_TOPIC(\"0f13b\", FATAL, arangodb::Logger::V8)\n            << \"cannot load JavaScript file '\" << file << \"'\";\n        FATAL_ERROR_EXIT();\n        break;\n      case JSLoader::eFailExecute:\n        LOG_TOPIC(\"69ac3\", FATAL, arangodb::Logger::V8)\n            << \"error during execution of JavaScript file '\" << file << \"'\";\n        FATAL_ERROR_EXIT();\n        break;\n    }\n  }\n\n  localContext->Exit();\n\n  LOG_TOPIC(\"53bbb\", TRACE, arangodb::Logger::V8) << \"loaded JavaScript file '\" << file\n                                         << \"' for V8 context #\" << context->id();\n}\n\nvoid V8DealerFeature::shutdownContext(V8Context* context) {\n  TRI_ASSERT(context != nullptr);\n  LOG_TOPIC(\"7946e\", TRACE, arangodb::Logger::V8)\n      << \"shutting down V8 context #\" << context->id();\n\n  auto isolate = context->_isolate;\n  {\n    \/\/ this guard will lock and enter the isolate\n    \/\/ and automatically exit and unlock it when it runs out of scope\n    V8ContextEntryGuard contextGuard(context);\n\n    v8::HandleScope scope(isolate);\n    TRI_GET_GLOBALS();\n\n    auto localContext = v8::Local<v8::Context>::New(isolate, context->_context);\n    localContext->Enter();\n\n    {\n      v8::Context::Scope contextScope(localContext);\n\n      TRI_VisitActions(\n          [&isolate](TRI_action_t* action) { action->visit(isolate); });\n\n      v8g->_inForcedCollect = true;\n      TRI_RunGarbageCollectionV8(isolate, 30.0);\n      v8g->_inForcedCollect = false;\n\n      TRI_GET_GLOBALS();\n\n      if (v8g != nullptr) {\n        if (v8g->_transactionContext != nullptr) {\n          delete static_cast<transaction::V8Context*>(v8g->_transactionContext);\n          v8g->_transactionContext = nullptr;\n        }\n        delete v8g;\n      }\n    }\n\n    localContext->Exit();\n  }\n\n  context->_context.Reset();\n\n  server().getFeature<V8PlatformFeature>().disposeIsolate(isolate);\n\n  LOG_TOPIC(\"34c28\", TRACE, arangodb::Logger::V8) << \"closed V8 context #\" << context->id();\n\n  delete context;\n  ++_contextsDestroyed;\n}\n\nV8ContextGuard::V8ContextGuard(TRI_vocbase_t* vocbase,\n                               JavaScriptSecurityContext const& securityContext)\n    : _isolate(nullptr), _context(nullptr) {\n  _context = V8DealerFeature::DEALER->enterContext(vocbase, securityContext);\n  if (_context == nullptr) {\n    THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_RESOURCE_LIMIT,\n                                   \"unable to acquire V8 context in time\");\n  }\n  _isolate = _context->_isolate;\n}\n\nV8ContextGuard::~V8ContextGuard() {\n  if (_context) {\n    try {\n      V8DealerFeature::DEALER->exitContext(_context);\n    } catch (...) {\n    }\n  }\n}\n\nV8ConditionalContextGuard::V8ConditionalContextGuard(Result& res, v8::Isolate*& isolate,\n                                                     TRI_vocbase_t* vocbase,\n                                                     JavaScriptSecurityContext const& securityContext)\n    : _isolate(isolate),\n      _context(nullptr),\n      _active(isolate ? false : true) {\n  TRI_ASSERT(vocbase != nullptr);\n  if (_active) {\n    _context = V8DealerFeature::DEALER->enterContext(vocbase, securityContext);\n    if (!_context) {\n      res.reset(TRI_ERROR_INTERNAL,\n                \"V8ConditionalContextGuard - could not acquire context\");\n      return;\n    }\n    isolate = _context->_isolate;\n  }\n}\n\nV8ConditionalContextGuard::~V8ConditionalContextGuard() {\n  if (_active && _context) {\n    try {\n      V8DealerFeature::DEALER->exitContext(_context);\n    } catch (...) {\n    }\n    _isolate = nullptr;\n  }\n}\n","avg_line_length":33.5263748597,"max_line_length":146,"alphanum_fraction":0.6364153723,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1662,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"\/\/ This file is part of Wintermute Engine\r\n\/\/ For conditions of distribution and use, see copyright notice in license.txt\r\n\/\/ http:\/\/dead-code.org\/redir.php?target=wme\r\n\r\n\r\n#include \"dcgf.h\"\r\n#include \"BSaveThumbHelper.h\"\r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\nCBSaveThumbHelper::CBSaveThumbHelper(CBGame* inGame):CBBase(inGame)\r\n{\r\n\tm_Thumbnail = NULL;\r\n\tm_RichThumbnail = NULL;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\nCBSaveThumbHelper::~CBSaveThumbHelper(void)\r\n{\r\n\tSAFE_DELETE(m_Thumbnail);\r\n\tSAFE_DELETE(m_RichThumbnail);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\nHRESULT CBSaveThumbHelper::StoreThumbnail(bool DoFlip)\r\n{\r\n\tSAFE_DELETE(m_Thumbnail);\r\n\tSAFE_DELETE(m_RichThumbnail);\r\n\r\n\tif(Game->m_RichSavedGames || (Game->m_ThumbnailWidth > 0 && Game->m_ThumbnailHeight > 0))\r\n\t{\r\n\t\tif(DoFlip)\r\n\t\t{\r\n\t\t\tGame->DisplayContent(false);\r\n\t\t\tGame->m_Renderer->Flip();\r\n\t\t}\r\n\r\n\t\tCBImage* Screenshot = Game->m_Renderer->TakeScreenshot();\r\n\t\tif(!Screenshot) return E_FAIL;\r\n\r\n\t\t\/\/ normal thumbnail\r\n\t\tif(Game->m_ThumbnailWidth > 0 && Game->m_ThumbnailHeight > 0)\r\n\t\t{\r\n\t\t\tm_Thumbnail = new CBImage(Game);\r\n\t\t\tm_Thumbnail->CopyFrom(Screenshot, Game->m_ThumbnailWidth, Game->m_ThumbnailHeight);\r\n\t\t}\r\n\r\n\t\t\/\/ rich saved game thumbnail\r\n\t\tif(Game->m_RichSavedGames)\r\n\t\t{\r\n\t\t\tint Width = 256;\r\n\t\t\tint Height = Width * ((float)Game->m_Renderer->m_Height \/ (float)Game->m_Renderer->m_Width);\r\n\r\n\t\t\tm_RichThumbnail = new CBImage(Game);\r\n\t\t\tm_RichThumbnail->CopyFrom(Screenshot, Width, Height);\r\n\t\t}\r\n\r\n\t\tSAFE_DELETE(Screenshot);\r\n\t}\r\n\treturn S_OK;\r\n}","avg_line_length":27.2459016393,"max_line_length":96,"alphanum_fraction":0.6022864019,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1680,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"#include <bits\/stdc++.h>\nusing namespace std;\n \n#define ff first\n#define ss second\n#define ll long long\n \ntypedef vector<int> vi;\ntypedef pair<int,int> ii;\ntypedef set<int> si;\ntypedef vector<vi> vii;\ntypedef vector<ii> vpi;\ntypedef vector<ll> vll;\nint oo = (1e9) + 7;\nll oo2 = 1ll*oo*oo;\n\nclass UnionFind {\n    private:\n    int numSets;\n    vi p, rank, setSize;\n\n    public:\n    UnionFind(int n) {\n        rank.assign(n, 0);\n        numSets = n;\n        setSize.assign(n, 1);\n        p.resize(n);\n        for(int i = 0; i < n; i++) p[i] = i;\n    }\n    int findSet(int i) {\n        return (p[i] == i) ? i : (p[i] = findSet(p[i]));\n    }\n    bool isSameSet(int i, int j) {\n        return findSet(i) == findSet(j);\n    }\n\n    void unionSet(int i, int j) {\n        if(!isSameSet(i, j)) {\n            int x = findSet(i), y = findSet(j);\n            if(rank[x] > rank[y]) {\n                setSize[findSet(x)] += setSize[findSet(y)];\n                p[y] = x;\n            } else {\n                setSize[findSet(y)] += setSize[findSet(x)];\n                p[x] = y;\n                if(rank[x] == rank[y]) rank[y]++;\n            }\n            numSets--;\n        }\n    }\n    int getSize(int i) {\n        return setSize[findSet(i)];\n    }\n    int getSets() {\n        return numSets;\n    }\n};\n\n\nint main() {\n    int n, m;\n    int tc;\n    cin >> tc;\n\n    while(tc--) {\n        scanf(\"%d %d\", &n, &m);\n        UnionFind UF(n);\n        int ans = 1;\n        while(m--) {\n            int a, b;\n            scanf(\"%d %d\", &a, &b);\n            a--, b--;\n            UF.unionSet(a, b);\n            ans = max(ans, UF.getSize(a)); \n        }\n        printf(\"%d\\n\", ans);\n    }    \n\n    return 0;\n}\n","avg_line_length":20.7407407407,"max_line_length":59,"alphanum_fraction":0.4452380952,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":406,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\n#include<stdio.h>\n\nint main()\n{\n    double a , b;\n    int n ;\n    scanf(\"%d\" , &n);\n    while(n --){\n        scanf(\"%lf%lf\" , &a , &b);\n        if(b == 0)printf(\"%.12lf\\n\" , 1.0);\n        else if(a == 0)printf(\"%.12lf\\n\" , 0.5);\n        else {\n            if(a <= 4 * b)\n                printf(\"%.12lf\\n\" , 0.5 + a \/ (b * 16.0) );\n            else printf(\"%.12lf\\n\" , (a - b) \/ a );\n\n        }\n\n    }\n\n\n}\n","avg_line_length":16.9166666667,"max_line_length":59,"alphanum_fraction":0.342364532,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5856,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"ofSoundPlayer.h\"\n#include \"ofLog.h\"\n#include \"glm\/common.hpp\"\n\nusing namespace std;\n\n\/\/ these are global functions, that affect every sound \/ channel:\n\/\/ ------------------------------------------------------------\n\/\/ ------------------------------------------------------------\n\n\/\/--------------------\nvoid ofSoundStopAll(){\n\t#ifdef OF_SOUND_PLAYER_FMOD\n\t\tofFmodSoundStopAll();\n\t#else\n\t\tofLogWarning(\"ofSoundPlayer\") << \"ofSoundStopAll() not implemented on this platform\";\n\t#endif\n}\n\n\/\/--------------------\nvoid ofSoundSetVolume(float vol){\n\t#ifdef OF_SOUND_PLAYER_FMOD\n\t\tofFmodSoundSetVolume(vol);\n\t#else\n\t\tofLogWarning(\"ofSoundPlayer\") << \"ofSoundSetVolume() not implemented on this platform\";\n\t#endif\n}\n\n\/\/--------------------\nvoid ofSoundUpdate(){\n\t#ifdef OF_SOUND_PLAYER_FMOD\n\t\tofFmodSoundUpdate();\n\t#endif\n}\n\n#if !defined(TARGET_ANDROID) && !defined(TARGET_LINUX_ARM)\n\/\/--------------------\nvoid ofSoundShutdown(){\n\t#ifdef OF_SOUND_PLAYER_FMOD\n\t\tofFmodSoundPlayer::closeFmod();\n\t#endif\n\t\/\/ ofSoundShutdown doesn't log an \"unimplemented\" message like the related functions\n\t\/\/ above, because it's called by the openFrameworks shutdown routine regardless\n}\n#endif\n\n\/\/--------------------\nfloat * ofSoundGetSpectrum(int nBands){\n\t#ifdef OF_SOUND_PLAYER_FMOD\n\t\treturn ofFmodSoundGetSpectrum(nBands);\n\t#elif defined(OF_SOUND_PLAYER_OPENAL)\n\t\treturn ofOpenALSoundPlayer::getSystemSpectrum(nBands);\n\t#elif defined(OF_SOUND_PLAYER_EMSCRIPTEN)\n\t\treturn ofxEmscriptenSoundPlayer::getSystemSpectrum(nBands);\n\t#else\n\t\tofLogWarning(\"ofSoundPlayer\") << \"ofSoundGetSpectrum() not implemented on this platform, returning nullptr\";\n\t\treturn nullptr;\n\t#endif\n}\n\n\/\/---------------------------------------------------------------------------\nofSoundPlayer::ofSoundPlayer (){\n#ifdef OF_SOUND_PLAYER_TYPE\n\tplayer\t= std::make_shared<OF_SOUND_PLAYER_TYPE>();\n#endif\n}\n\n\/\/---------------------------------------------------------------------------\nvoid ofSoundPlayer::setPlayer(shared_ptr<ofBaseSoundPlayer> newPlayer){\n\tplayer = std::move(newPlayer);\n}\n\n\/\/--------------------------------------------------------------------\nshared_ptr<ofBaseSoundPlayer> ofSoundPlayer::getPlayer(){\n\treturn player;\n}\n\n\/\/--------------------------------------------------------------------\nbool ofSoundPlayer::load(const std::filesystem::path& fileName, bool stream){\n\tif( player ){\n\t\treturn player->load(fileName, stream);\n\t}\n\treturn false;\n}\n\n\/\/--------------------------------------------------------------------\nbool ofSoundPlayer::loadSound(string fileName, bool stream){\n\treturn load(fileName,stream);\n}\n\n\/\/--------------------------------------------------------------------\nvoid ofSoundPlayer::unload(){\n\tif( player ){\n\t\tplayer->unload();\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nvoid ofSoundPlayer::unloadSound(){\n\tunload();\n}\n\n\/\/--------------------------------------------------------------------\nvoid ofSoundPlayer::play(){\n\tif( player ){\n\t\tplayer->play();\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nvoid ofSoundPlayer::stop(){\n\tif( player ){\n\t\tplayer->stop();\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nvoid ofSoundPlayer::setVolume(float vol){\n\tif( player ){\n\t\tplayer->setVolume(vol);\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nvoid ofSoundPlayer::setPan(float pan){\n\tif( player ){\n\t\tplayer->setPan(glm::clamp(pan,-1.0f,1.0f));\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nvoid ofSoundPlayer::setSpeed(float spd){\n\tif( player ){\n\t\tplayer->setSpeed(spd);\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nvoid ofSoundPlayer::setPaused(bool bP){\n\tif( player ){\n\t\tplayer->setPaused(bP);\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nvoid ofSoundPlayer::setLoop(bool bLp){\n\tif( player ){\n\t\tplayer->setLoop(bLp);\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nvoid ofSoundPlayer::setMultiPlay(bool bMp){\n\tif( player ){\n\t\tplayer->setMultiPlay(bMp);\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nvoid ofSoundPlayer::setPosition(float pct){\n\tif( player ){\n\t\tplayer->setPosition(pct);\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nvoid ofSoundPlayer::setPositionMS(int ms){\n\tif( player ){\n\t\tplayer->setPositionMS(ms);\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nfloat ofSoundPlayer::getPosition() const{\n\tif( player ){\n\t\treturn player->getPosition();\n\t} else {\n\t\treturn 0;\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nint ofSoundPlayer::getPositionMS() const{\n\tif( player ){\n\t\treturn player->getPositionMS();\n\t} else {\n\t\treturn 0;\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nbool ofSoundPlayer::isPlaying() const{\n\tif( player ){\n\t\treturn player->isPlaying();\n\t} else {\n\t\treturn false;\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nbool ofSoundPlayer::getIsPlaying() const{\n\treturn isPlaying();\n}\n\n\/\/--------------------------------------------------------------------\nbool ofSoundPlayer::isLoaded() const{\n\tif( player ){\n\t\treturn player->isLoaded();\n\t} else {\n\t\treturn false; \n\t}\n}\n\n\/\/--------------------------------------------------------------------\nfloat ofSoundPlayer::getSpeed() const{\n\tif( player ){\n\t\treturn player->getSpeed();\n\t} else {\n\t\treturn 0;\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nfloat ofSoundPlayer::getPan() const{\n\tif( player ){\n\t\treturn player->getPan();\n\t} else {\n\t\treturn 0;\n\t}\n}\n\n\/\/--------------------------------------------------------------------\nfloat ofSoundPlayer::getVolume() const{\n\tif( player ){\n\t\treturn player->getVolume();\n\t} else {\n\t\treturn 0;\n\t}\n}\n","avg_line_length":24.4,"max_line_length":110,"alphanum_fraction":0.4672131148,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2407,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"BulletWorld.h\"\r\n#include \"BulletRigid.h\"\r\n#include \"BulletConverter.h\"\r\n\r\nusing namespace Crystal::Math;\r\nusing namespace Crystal::Physics;\r\n\r\nBulletWorld::BulletWorld():\r\n\tdispatcher(&collisionConfig)\r\n{\r\n\tworld = new btDiscreteDynamicsWorld(&dispatcher, &overlappingPairCache, &solver, &collisionConfig);\r\n}\r\n\r\nvoid BulletWorld::add(BulletRigid* rigid)\r\n{\r\n\tworld->addRigidBody(rigid->getBody());\r\n\trigids.push_back(rigid);\r\n}\r\n\r\nvoid BulletWorld::setExternalForce(const Vector3d<float>& f)\r\n{\r\n\tworld->setGravity(BulletConverter::convert(f));\r\n}\r\n\r\nvoid BulletWorld::simulate(const float timeStep)\r\n{\r\n\tworld->stepSimulation(timeStep, 10);\r\n}\r\n\r\nvoid BulletWorld::setBoundary(const Box3d<float>& box)\r\n{\r\n\tbtBoxShape* worldBoxShape = new btBoxShape( BulletConverter::convert( box.getLength() * 0.5 ));\r\n\r\n\t\/\/\/create 6 planes\/half spaces\r\n\tfor (int i = 0; i < 6; i++)\r\n\t{\r\n\t\tbtTransform groundTransform;\r\n\t\tgroundTransform.setIdentity();\r\n\t\tgroundTransform.setOrigin(BulletConverter::convert( box.getCenter()) );\r\n\t\tbtVector4 planeEq;\r\n\t\tworldBoxShape->getPlaneEquation(planeEq, i);\r\n\r\n\t\tbtCollisionShape* shape = new btStaticPlaneShape(-planeEq, planeEq[3]);\r\n\t\tbtDefaultMotionState* state = new btDefaultMotionState(groundTransform);\r\n\t\tbtRigidBody::btRigidBodyConstructionInfo plain_body_ci(0.0f, state, shape);\r\n\t\tbtRigidBody* body = new btRigidBody(plain_body_ci);\r\n\t\tworld->addRigidBody(body);\r\n\t}\r\n\t\/*\r\n\t{\r\n\t\tbtStaticPlaneShape* shape = new btBoxShape(BulletConverter::convert(box));\r\n\t\tbtDefaultMotionState* state = new btDefaultMotionState();\r\n\t\tbtRigidBody::btRigidBodyConstructionInfo plain_body_ci(0.0f, state, shape);\r\n\t\tbtRigidBody* body = new btRigidBody(plain_body_ci);\r\n\t\tworld->addRigidBody(body);\r\n\t}\r\n\r\n\t{\r\n\t\tbtStaticPlaneShape* shape = new btStaticPlaneShape(btVector3(1.0f, 0.0f, 0.0f), box.getMinX());\r\n\t\tbtDefaultMotionState* state = new btDefaultMotionState();\r\n\t\tbtRigidBody::btRigidBodyConstructionInfo plain_body_ci(0.0f, state, shape);\r\n\t\tbtRigidBody* body = new btRigidBody(plain_body_ci);\r\n\t\tworld->addRigidBody(body);\r\n\t}\r\n\r\n\t{\r\n\t\tbtCollisionShape* shape = new btStaticPlaneShape(btVector3(0.0f, 0.0f, 1.0f), box.getMinZ());\r\n\t\tbtDefaultMotionState* state = new btDefaultMotionState();\r\n\t\tbtRigidBody::btRigidBodyConstructionInfo plain_body_ci(0.0f, state, shape);\r\n\t\tbtRigidBody* body = new btRigidBody(plain_body_ci);\r\n\t\tworld->addRigidBody(body);\r\n\t}\r\n\t*\/\r\n}\r\n","avg_line_length":32.0933333333,"max_line_length":101,"alphanum_fraction":0.7361861238,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6581,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":48.0,"content":"\/\/\n\/\/ Copyright (c) 2021 the rbfx project.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include \"..\/Precompiled.h\"\n\n#include \"ParticleGraph.h\"\n\n#include \"Nodes\/Constant.h\"\n#include \"ParticleGraphNode.h\"\n#include \"ParticleGraphSystem.h\"\n#include \"Urho3D\/Resource\/Graph.h\"\n\n#include <Urho3D\/IO\/Log.h>\n\nnamespace Urho3D\n{\n\nParticleGraph::ParticleGraph(Context* context)\n    : Object(context)\n{\n}\n\nParticleGraph::~ParticleGraph() = default;\n\nunsigned ParticleGraph::Add(const SharedPtr<ParticleGraphNode> node)\n{\n    if (!node)\n    {\n        URHO3D_LOGERROR(\"Can't add empty node\");\n        return 0;\n    }\n    const auto index = static_cast<unsigned>(nodes_.size());\n    nodes_.push_back(node);\n    node->SetGraph(this, index);\n    return index;\n}\n\nunsigned ParticleGraph::GetNumNodes() const { return static_cast<unsigned>(nodes_.size()); }\n\nSharedPtr<ParticleGraphNode> ParticleGraph::GetNode(unsigned index) const\n{\n    if (index >= nodes_.size())\n    {\n        URHO3D_LOGERROR(\"Node index out of bounds\");\n        return {};\n    }\n    return nodes_[index];\n}\n\nbool ParticleGraph::LoadGraph(Graph& graph)\n{\n    ParticleGraphReader reader(*this, graph);\n    return reader.Read();\n}\n\nbool ParticleGraph::SaveGraph(Graph& graph)\n{\n    graph.Clear();\n    ParticleGraphWriter writer(*this, graph);\n    return writer.Write();\n}\n\nvoid ParticleGraph::SerializeInBlock(Archive& archive)\n{\n    Graph graph(context_);\n    if (archive.IsInput())\n    {\n        graph.SerializeInBlock(archive);\n        LoadGraph(graph);\n    }\n    else\n    {\n        SaveGraph(graph);\n        graph.SerializeInBlock(archive);\n    }\n}\n\nParticleGraphWriter::ParticleGraphWriter(ParticleGraph& particleGraph, Graph& graph)\n    : particleGraph_(particleGraph)\n    , graph_(graph)\n    , system_(particleGraph.GetContext()->GetSubsystem<ParticleGraphSystem>())\n{\n    nodes_.resize(particleGraph_.GetNumNodes());\n    for (unsigned i = 0; i < particleGraph_.GetNumNodes(); ++i)\n    {\n        nodes_[i] = 0;\n    }\n}\n\nbool ParticleGraphWriter::Write()\n{\n    for (unsigned i=0; i<particleGraph_.GetNumNodes(); ++i)\n    {\n        const auto id = WriteNode(i);\n        if (!id)\n            return false;\n    }\n    return true;\n}\n\nunsigned ParticleGraphWriter::WriteNode(unsigned index)\n{\n    if (nodes_[index])\n    {\n        return nodes_[index];\n    }\n    const auto node = particleGraph_.GetNode(index);\n    const auto outNode = graph_.Create(node->GetTypeName());\n    nodes_[index] = outNode->GetID();\n    if (!node->Save(*this, *outNode))\n        return false;\n    return true;\n}\n\nGraphPinRef<GraphOutPin> ParticleGraphWriter::GetSourcePin(unsigned nodeIndex, unsigned pinIndex)\n{\n    const auto node = particleGraph_.GetNode(nodeIndex);\n    const auto outNode = nodes_[nodeIndex];\n    const auto pin = node->GetPin(pinIndex);\n    return graph_.GetNode(outNode)->GetOrAddOutput(pin.GetName());\n}\n\nParticleGraphReader::ParticleGraphReader(ParticleGraph& particleGraph, Graph& graph)\n    : particleGraph_(particleGraph)\n    , graph_(graph)\n    , system_(particleGraph.GetContext()->GetSubsystem<ParticleGraphSystem>())\n{\n    graph.GetNodeIds(ids_);\n}\n\nunsigned ParticleGraphReader::ReadNode(unsigned id)\n{\n    {\n        const auto it = nodes_.find(id);\n        if (it != nodes_.end())\n        {\n            if (it->second == ParticleGraph::INVALID_NODE_INDEX)\n            {\n                URHO3D_LOGERROR(\"Loop detected at particle graph\");\n                return it->second;\n            }\n            return it->second;\n        }\n    }\n    nodes_[id] = ParticleGraph::INVALID_NODE_INDEX;\n\n    auto *srcNode = graph_.GetNode(id);\n    auto newNode = system_->CreateObject(srcNode->GetNameHash());\n    if (!newNode)\n    {\n        URHO3D_LOGERROR(Format(\"Unknown node type {}\", srcNode->GetName()));\n        return ParticleGraph::INVALID_NODE_INDEX;\n    }\n    SharedPtr<ParticleGraphNode> dstNode;\n    dstNode.StaticCast(newNode);\n    if (!dstNode->Load(*this, *srcNode))\n        return ParticleGraph::INVALID_NODE_INDEX;\n\n    for (unsigned i=0; i<dstNode->GetNumPins(); ++i)\n    {\n        auto pin = dstNode->GetPin(i);\n        if (pin.IsInput() && pin.GetRequestedType() != VAR_NONE)\n        {\n            if (pin.GetConnectedNodeIndex() == ParticleGraph::INVALID_NODE_INDEX)\n            {\n                auto constNode = MakeShared<ParticleGraphNodes::Constant>(system_->GetContext());\n                constNode->SetValue(Variant(pin.GetRequestedType()));\n                auto constIndex = particleGraph_.Add(constNode);\n                dstNode->SetPinSource(i, constIndex, 0);\n            }\n        }\n    }\n\n    auto dstIndex =  particleGraph_.Add(dstNode);\n    nodes_[id] = dstIndex;\n    return dstIndex;\n}\nunsigned ParticleGraphReader::GetOrAddConstant(const Variant& constValue)\n{\n    const auto it = constants_.find(constValue);\n    if (it == constants_.end())\n    {\n        const auto constNode = MakeShared<ParticleGraphNodes::Constant>(particleGraph_.GetContext());\n        constNode->SetValue(constValue);\n        return constants_[constValue] = particleGraph_.Add(constNode);\n    }\n    return it->second;\n\n}\nunsigned ParticleGraphReader::GetInputPinIndex(unsigned nodeIndex, const ea::string& string)\n{\n    const auto node = particleGraph_.GetNode(nodeIndex);\n    if (!node)\n        return ParticleGraphNode::INVALID_PIN;\n    return node->GetPinIndex(string);\n}\n\nbool ParticleGraphReader::Read()\n{\n    for (const unsigned id : ids_)\n    {\n        if (ReadNode(id) == ParticleGraph::INVALID_NODE_INDEX)\n            return false;\n    }\n    return true;\n}\n\n} \/\/ namespace Urho3D\n","avg_line_length":28.8640350877,"max_line_length":101,"alphanum_fraction":0.6720863091,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6053,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":6.0,"content":"\/*\n * Copyright (C) 2016 Yusuke Suzuki <utatane.tea@gmail.com>\n * Copyright (C) 2016-2017 Apple Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n * THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"BytecodeRewriter.h\"\n\n#include \"JSCJSValueInlines.h\"\n#include \"PreciseJumpTargetsInlines.h\"\n#include <wtf\/BubbleSort.h>\n\nnamespace JSC {\n\nvoid BytecodeRewriter::applyModification()\n{\n    for (size_t insertionIndex = m_insertions.size(); insertionIndex--;) {\n        Insertion& insertion = m_insertions[insertionIndex];\n        if (insertion.type == Insertion::Type::Remove)\n            m_writer.m_instructions.remove(insertion.index.bytecodeOffset, insertion.length());\n        else {\n            if (insertion.includeBranch == IncludeBranch::Yes) {\n                int finalOffset = insertion.index.bytecodeOffset + calculateDifference(m_insertions.begin(), m_insertions.begin() + insertionIndex);\n                adjustJumpTargetsInFragment(finalOffset, insertion);\n            }\n            m_writer.m_instructions.insertVector(insertion.index.bytecodeOffset, insertion.instructions.m_instructions);\n        }\n    }\n    m_insertions.clear();\n}\n\nvoid BytecodeRewriter::execute()\n{\n    WTF::bubbleSort(m_insertions.begin(), m_insertions.end(), [] (const Insertion& lhs, const Insertion& rhs) {\n        return lhs.index < rhs.index;\n    });\n\n    m_codeBlock->applyModification(*this, m_writer);\n}\n\nvoid BytecodeRewriter::adjustJumpTargetsInFragment(unsigned finalOffset, Insertion& insertion)\n{\n    for (auto& instruction : insertion.instructions) {\n        if (isBranch(instruction->opcodeID())) {\n            unsigned bytecodeOffset = finalOffset + instruction.offset();\n            updateStoredJumpTargetsForInstruction(m_codeBlock, finalOffset, instruction, [&](int32_t label) {\n                int absoluteOffset = adjustAbsoluteOffset(label);\n                return absoluteOffset - static_cast<int>(bytecodeOffset);\n            });\n        }\n    }\n}\n\nvoid BytecodeRewriter::insertImpl(InsertionPoint insertionPoint, IncludeBranch includeBranch, InstructionStreamWriter&& writer)\n{\n    ASSERT(insertionPoint.position == Position::Before || insertionPoint.position == Position::After);\n    m_insertions.append(Insertion {\n        insertionPoint,\n        Insertion::Type::Insert,\n        includeBranch,\n        0,\n        WTFMove(writer)\n    });\n}\n\nint32_t BytecodeRewriter::adjustJumpTarget(InsertionPoint startPoint, InsertionPoint jumpTargetPoint)\n{\n    if (startPoint < jumpTargetPoint) {\n        int jumpTarget = jumpTargetPoint.bytecodeOffset;\n        auto start = std::lower_bound(m_insertions.begin(), m_insertions.end(), startPoint, [&] (const Insertion& insertion, InsertionPoint startPoint) {\n            return insertion.index < startPoint;\n        });\n        if (start != m_insertions.end()) {\n            auto end = std::lower_bound(m_insertions.begin(), m_insertions.end(), jumpTargetPoint, [&] (const Insertion& insertion, InsertionPoint jumpTargetPoint) {\n                return insertion.index < jumpTargetPoint;\n            });\n            jumpTarget += calculateDifference(start, end);\n        }\n        return jumpTarget - startPoint.bytecodeOffset;\n    }\n\n    if (startPoint == jumpTargetPoint)\n        return 0;\n\n    return -adjustJumpTarget(jumpTargetPoint, startPoint);\n}\n\n\/\/ FIXME: unit test the logic in this method\n\/\/ https:\/\/bugs.webkit.org\/show_bug.cgi?id=190950\nvoid BytecodeRewriter::adjustJumpTargets()\n{\n    auto currentInsertion = m_insertions.begin();\n    auto outOfLineJumpTargets = m_codeBlock->replaceOutOfLineJumpTargets();\n\n    int offset = 0;\n    for (InstructionStream::Offset i = 0; i < m_writer.size();) {\n        int before = 0;\n        int after = 0;\n        int remove = 0;\n        while (currentInsertion != m_insertions.end() && static_cast<InstructionStream::Offset>(currentInsertion->index.bytecodeOffset) == i) {\n            auto size = currentInsertion->length();\n            if (currentInsertion->type == Insertion::Type::Remove)\n                remove += size;\n            else if (currentInsertion->index.position == Position::Before)\n                before += size;\n            else if (currentInsertion->index.position == Position::After)\n                after += size;\n            ++currentInsertion;\n        }\n\n        offset += before;\n\n        if (!remove) {\n            auto instruction = m_writer.ref(i);\n            updateStoredJumpTargetsForInstruction(m_codeBlock, offset, instruction, [&](int32_t relativeOffset) {\n                return adjustJumpTarget(instruction.offset(), instruction.offset() + relativeOffset);\n            }, outOfLineJumpTargets);\n            i += instruction->size();\n        } else {\n            offset -= remove;\n            i += remove;\n        }\n\n        offset += after;\n    }\n}\n\n} \/\/ namespace JSC\n","avg_line_length":40.3533333333,"max_line_length":165,"alphanum_fraction":0.6794977697,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1870,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\n#include \"Particle.h\"\n#include \"model_gauge.h\"\n\nSerialLogHandler logHandler(115200, LOG_LEVEL_INFO);\nSYSTEM_MODE(MANUAL);\n\n\/\/ define your new battery model config first, or use the default config in model_gauge.h\n\/\/ example: LG INR21700 battery model get from the .ini file\nconst model_config_t model_config_example = {\n    .EmptyAdjustment=0,\n    .FullAdjustment=100,\n    .RCOMP0 = 92,\n    .TempCoUp = -0.453125,\n    .TempCoDown = -0.8125,\n    .OCVTest = 58560,\n    .SOCCheckA = 203,\n    .SOCCheckB = 205,\n    .bits = 19,\n    .model_data = {\n        0x88, 0x70, 0xAA, 0x10, 0xAD, 0x90, 0xB0, 0x60, 0xB3, 0xF0, 0xB7, 0x00, 0xB8, 0xF0, 0xBC, 0x50,\n        0xBF, 0xE0, 0xC2, 0x00, 0xC4, 0x60, 0xC7, 0x40, 0xCA, 0xD0, 0xCC, 0x40, 0xCD, 0x00, 0xDA, 0xC0, \n        0x00, 0x40, 0x07, 0x00, 0x0C, 0x00, 0x10, 0x40, 0x13, 0x00, 0x1D, 0x60, 0x19, 0x20, 0x1A, 0xE0,\n        0x13, 0xC0, 0x15, 0x80, 0x11, 0xC0, 0x13, 0x20, 0x3D, 0x00, 0x5E, 0x60, 0x01, 0x20, 0x01, 0x20,\n    }\n};\n\n\/\/ create the ModelGauge object with the model config\nModelGauge model_gauge(model_config_example);\n\nvoid setup()\n{\n    Serial.begin();\n    waitFor(Serial.isConnected, 5000);\n    delay(50);\n\n    \/\/ load model config when power on \n    model_gauge.load_config();\n}\n\nvoid loop()\n{\n    static uint32_t last_10s = 0;\n    static uint32_t last_1h = 0;\n\n    \/\/ print soc every 10 seconds\n    if(System.uptime() - last_10s >= 10)\n    {\n        last_10s = System.uptime();\n        \n        \/\/ read battery voltage and soc from ModelGauge\n        float volt = model_gauge.get_volt();\n        float soc  = model_gauge.get_soc();\n        Log.info(\">>> volt:%.2f, soc:%.2f%%\", volt, soc);\n    }\n\n    \/\/ verify model every 1 hour\n    if(System.uptime() - last_1h >= 3600)\n    {\n        last_1h = System.uptime();\n\n        \/\/ verify model, reload model if verify failed\n        model_gauge.verify_model();\n    }\n}\n","avg_line_length":28.3333333333,"max_line_length":104,"alphanum_fraction":0.6310160428,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5649,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["FTL"],"max_stars_count":1.0,"content":"\/*\n   Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.\n   Copyright (c) 2017, The LineageOS Project\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are\n   met:\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above\n      copyright notice, this list of conditions and the following\n      disclaimer in the documentation and\/or other materials provided\n      with the distribution.\n    * Neither the name of The Linux Foundation nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\n   THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESS OR IMPLIED\n   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT\n   ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS\n   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n   BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n   OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n   IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <stdlib.h>\n#include <unistd.h>\n#include <fcntl.h>\n\n#include \"vendor_init.h\"\n#include \"property_service.h\"\n#include \"log.h\"\n#include \"util.h\"\n\n#define DEVINFO_FILE \"\/dev\/block\/bootdevice\/by-name\/devinfo\"\n\nstatic int read_file2(const char *fname, char *data, int max_size)\n{\n    int fd, rc;\n\n    if (max_size < 1)\n        return 0;\n\n    fd = open(fname, O_RDONLY);\n    if (fd < 0) {\n        ERROR(\"failed to open '%s'\\n\", fname);\n        return 0;\n    }\n\n    rc = read(fd, data, max_size - 1);\n    if ((rc > 0) && (rc < max_size))\n        data[rc] = '\\0';\n    else\n        data[0] = '\\0';\n    close(fd);\n\n    return 1;\n}\n\nvoid init_alarm_boot_properties()\n{\n    char const *alarm_file = \"\/proc\/sys\/kernel\/boot_reason\";\n    char buf[64];\n\n    if(read_file2(alarm_file, buf, sizeof(buf))) {\n        \/*\n         * Setup ro.alarm_boot value to true when it is RTC triggered boot up\n         * For existing PMIC chips, the following mapping applies\n         * for the value of boot_reason:\n         *\n         * 0 -> unknown\n         * 1 -> hard reset\n         * 2 -> sudden momentary power loss (SMPL)\n         * 3 -> real time clock (RTC)\n         * 4 -> DC charger inserted\n         * 5 -> USB charger insertd\n         * 6 -> PON1 pin toggled (for secondary PMICs)\n         * 7 -> CBLPWR_N pin toggled (for external power supply)\n         * 8 -> KPDPWR_N pin toggled (power key pressed)\n         *\/\n        if (buf[0] == '0') {\n            property_set(\"ro.boot.bootreason\", \"invalid\");\n            property_set(\"ro.alarm_boot\", \"false\");\n        }\n        else if (buf[0] == '1') {\n            property_set(\"ro.boot.bootreason\", \"hard_reset\");\n            property_set(\"ro.alarm_boot\", \"false\");\n        }\n        else if (buf[0] == '2') {\n            property_set(\"ro.boot.bootreason\", \"smpl\");\n            property_set(\"ro.alarm_boot\", \"false\");\n        }\n        else if (buf[0] == '3'){\n            property_set(\"ro.alarm_boot\", \"true\");\n        }\n        else if (buf[0] == '4') {\n            property_set(\"ro.boot.bootreason\", \"dc_chg\");\n            property_set(\"ro.alarm_boot\", \"false\");\n        }\n        else if (buf[0] == '5') {\n            property_set(\"ro.boot.bootreason\", \"usb_chg\");\n            property_set(\"ro.alarm_boot\", \"false\");\n        }\n        else if (buf[0] == '6') {\n            property_set(\"ro.boot.bootreason\", \"pon1\");\n            property_set(\"ro.alarm_boot\", \"false\");\n        }\n        else if (buf[0] == '7') {\n            property_set(\"ro.boot.bootreason\", \"cblpwr\");\n            property_set(\"ro.alarm_boot\", \"false\");\n        }\n        else if (buf[0] == '8') {\n            property_set(\"ro.boot.bootreason\", \"kpdpwr\");\n            property_set(\"ro.alarm_boot\", \"false\");\n        }\n    }\n}\n\nvoid vendor_load_properties() {\n    char device[PROP_VALUE_MAX];\n    int isX520 = 0, isX522 = 0, isX526 = 0, isX527 = 0;\n\n    \/\/ Default props\n    property_set(\"ro.thermanager.config\", \"\/system\/etc\/thermanager.xml\");\n\n    if (read_file2(DEVINFO_FILE, device, sizeof(device)))\n    {\n        if (!strncmp(device, \"s2_open\", 7))\n        {\n            isX520 = 1;\n        }\n        else if (!strncmp(device, \"s2_oversea\", 10))\n        {\n            isX522 = 1;\n        }\n        else if (!strncmp(device, \"s2_india\", 8))\n        {\n            isX526 = 1;\n        }\n        else if (!strncmp(device, \"s2_ww\", 5))\n        {\n            isX527 = 1;\n        }\n    }\n\n    if (isX520)\n    {\n        \/\/ This is X520\n        property_set(\"ro.product.model\", \"X520\");\n    }\n    else if (isX522)\n    {\n        \/\/ This is X522\n        property_set(\"ro.product.model\", \"X522\");\n    }\n    else if (isX526)\n    {\n        \/\/ This is X526\n        property_set(\"ro.product.model\", \"X526\");\n        property_set(\"ro.thermanager.config\", \"\/system\/etc\/thermanager_X526.xml\");\n    }\n    else if (isX527)\n    {\n        \/\/ This is X527\n        property_set(\"ro.product.model\", \"X527\");\n    }\n    else\n    {\n        \/\/ Unknown variant\n        property_set(\"ro.product.model\", \"X52X\");\n    }\n\n    init_alarm_boot_properties();\n}\n","avg_line_length":31.3833333333,"max_line_length":82,"alphanum_fraction":0.5882457072,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4108,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"cube_sphere.hpp\"\n\n\nglm::vec3 CubeToSphere(const glm::vec3& p)\n{\n    \/*\n    auto x2 = p.x * p.x;\n    auto y2 = p.y * p.y;\n    auto z2 = p.z * p.z;\n\n    auto x = p.x * glm::sqrt(1.0f - (y2 + z2) \/ 2 + (y2 * z2) \/ 3);\n    auto y = p.y * glm::sqrt(1.0f - (z2 + x2) \/ 2 + (z2 * x2) \/ 3);\n    auto z = p.z * glm::sqrt(1.0f - (x2 + y2) \/ 2 + (x2 * y2) \/ 3);\n    \n    return glm::vec3(x, y, z);\n    *\/\n    return glm::normalize(p);\n}\n\nglm::vec3 SphereToCube(const glm::vec3& p)\n{\n    float max = glm::abs(p.x);\n    max = glm::max(glm::abs(p.y), max);\n    max = glm::max(glm::abs(p.z), max);\n    return p \/ max;\n}\n\nglm::vec3 SphereHeightmapPoint(\n    glm::vec3 direction,\n    CubemapData& heightmap)\n{\n    auto coordinates = CubemapData::PointCoordinates(direction);\n    auto height = BilinearInterpolate(heightmap, coordinates, 0);\n    return direction * (0.5f + height);\n}\n\nglm::vec3 SphereHeightmapPoint(\n    CubemapCoordinates coordinates,\n    CubemapData& heightmap)\n{\n    auto direction = CubeToSphere(CubemapData::CubePoint(coordinates));\n    auto height = BilinearInterpolate(heightmap, coordinates, 0);\n    return direction * (0.5f + height);\n}\n\nglm::vec3 SphereHeightmapUTangent(\n    glm::vec3 direction,\n    CubemapData& heightmap)\n{\n    float step = 1.0f \/ heightmap.GetResolution();\n\n    auto coordinates = CubemapData::PointCoordinates(direction);\n    auto p0 = SphereHeightmapPoint(coordinates, heightmap);\n\n    coordinates.u += step;\n    auto p1 = SphereHeightmapPoint(coordinates, heightmap);\n\n    auto tangent = (p1 - p0) \/ step;\n\n    return tangent;\n}\n\nglm::vec3 SphereHeightmapVTangent(\n    glm::vec3 direction,\n    CubemapData& heightmap)\n{\n    float step = 1.0f \/ heightmap.GetResolution();\n\n    auto coordinates = CubemapData::PointCoordinates(direction);\n    auto p0 = SphereHeightmapPoint(coordinates, heightmap);\n\n    coordinates.v += step;\n    auto p1 = SphereHeightmapPoint(coordinates, heightmap);\n\n    auto tangent = (p1 - p0) \/ step;\n\n    return tangent;\n}\n\nstd::shared_ptr<Mesh<Vertex_XNTBUV>> BuildSphereMesh(int n_face_divisions)\n{\n    \/\/ Initialize mesh storage\n    int n_vertices_per_face = n_face_divisions * n_face_divisions;\n    int n_vertices = n_vertices_per_face * 6;\n\n    int n_triangles_per_face = (n_face_divisions - 1) * (n_face_divisions - 1) * 2;\n    int n_triangles = n_triangles_per_face * 6;\n\n    auto mesh = std::make_shared<Mesh<Vertex_XNTBUV>>();\n    mesh->SetVertexCount(n_vertices);\n    mesh->SetTriangleCount(n_triangles);\n\n    \/\/ Add data\n    uint32_t vertex_index = 0;\n    uint32_t triangle_index = 0;\n    for (int face_id = CubeFace::Begin; face_id < CubeFace::End; ++face_id)\n    {\n        auto face = static_cast<CubeFace>(face_id);\n        for (int i = 0; i < n_face_divisions; ++i)\n        {\n            float face_u = i \/ (n_face_divisions - 1.0f);\n            for (int j = 0; j < n_face_divisions; ++j)\n            {\n                float face_v = j \/ (n_face_divisions - 1.0f);\n\n                \/\/ Vertex\n                auto& vertex = mesh->GetVertex(vertex_index);\n                vertex.position = CubeToSphere(\n                    CubemapData::CubePoint(\n                        CubemapCoordinates{ face, face_u, face_v }));\n                vertex.normal = glm::normalize(vertex.position);\n                vertex.uv = glm::vec2(face_u, face_v);\n\n                \/\/ Triangles\n                if (i != n_face_divisions - 1 && j != n_face_divisions - 1)\n                {\n                    mesh->GetIndex(triangle_index, 0) = vertex_index;\n                    mesh->GetIndex(triangle_index, 1) = vertex_index + 1;\n                    mesh->GetIndex(triangle_index, 2) = vertex_index + n_face_divisions + 1;\n                    triangle_index++;\n\n                    mesh->GetIndex(triangle_index, 0) = vertex_index;\n                    mesh->GetIndex(triangle_index, 1) = vertex_index + n_face_divisions + 1;\n                    mesh->GetIndex(triangle_index, 2) = vertex_index + n_face_divisions;\n                    triangle_index++;\n                }\n\n                vertex_index++;\n            }\n        }\n    }\n\n    return mesh;\n}\n","avg_line_length":30.4296296296,"max_line_length":92,"alphanum_fraction":0.5973709834,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6002,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/**\n * @file HelloWorldPublisher.cpp\n *\n *\/\n\n#include \"HelloWorldPubSubTypes.h\"\n\n#include <fastdds\/dds\/domain\/DomainParticipantFactory.hpp>\n#include <fastdds\/dds\/domain\/DomainParticipant.hpp>\n#include <fastdds\/dds\/topic\/TypeSupport.hpp>\n#include <fastdds\/dds\/publisher\/Publisher.hpp>\n#include <fastdds\/dds\/publisher\/DataWriter.hpp>\n#include <fastdds\/dds\/publisher\/DataWriterListener.hpp>\n\n#include <signal.h>\n\nusing namespace eprosima::fastdds::dds;\n\nstatic volatile int sigintH = 1;\n\n\/* Handel Ctrl-C *\/\nvoid sigintHandler(int sig_num) {\n  sigintH = 0;\n}\n\nclass HelloWorldPublisher\n{\nprivate:\n\n    HelloWorld hello_;\n\n    DomainParticipant* participant_;\n\n    Publisher* publisher_;\n\n    Topic* topic_;\n\n    DataWriter* writer_;\n\n    TypeSupport type_;\n\n    class PubListener : public DataWriterListener\n    {\n    public:\n\n        PubListener()\n            : matched_(0)\n        {\n        }\n\n        ~PubListener() override\n        {\n        }\n\n        void on_publication_matched(\n                DataWriter*,\n                const PublicationMatchedStatus& info) override\n        {\n            if (info.current_count_change == 1)\n            {\n                matched_ = info.total_count;\n                std::cout << \"Publisher matched.\" << std::endl;\n            }\n            else if (info.current_count_change == -1)\n            {\n                matched_ = info.total_count;\n                std::cout << \"Publisher unmatched.\" << std::endl;\n            }\n            else\n            {\n                std::cout << info.current_count_change\n                        << \" is not a valid value for PublicationMatchedStatus current count change.\" << std::endl;\n            }\n        }\n\n        std::atomic_int matched_;\n\n    } listener_;\n\npublic:\n\n    HelloWorldPublisher()\n        : participant_(nullptr)\n        , publisher_(nullptr)\n        , topic_(nullptr)\n        , writer_(nullptr)\n        , type_(new HelloWorldPubSubType())\n    {\n    }\n\n    virtual ~HelloWorldPublisher()\n    {\n        if (writer_ != nullptr)\n        {\n            publisher_->delete_datawriter(writer_);\n        }\n        if (publisher_ != nullptr)\n        {\n            participant_->delete_publisher(publisher_);\n        }\n        if (topic_ != nullptr)\n        {\n            participant_->delete_topic(topic_);\n        }\n        DomainParticipantFactory::get_instance()->delete_participant(participant_);\n    }\n\n    \/\/!Initialize the publisher\n    bool init()\n    {\n        \/\/hello_.index(0);\n        \/\/hello_.message(\"HelloWorld\");\n        \/\/double val[10] = {1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9};\n        std::array<double, 8> tmpArr;\n        tmpArr[0] = 15.856;\n        hello_.arr(tmpArr);\n        hello_.value(0.0);\n        hello_.instanceID(1);\n        hello_.message(\"Not History Pub\");\n\n        DomainParticipantQos participantQos;\n        participantQos.name(\"Participant_publisher\");\n        participant_ = DomainParticipantFactory::get_instance()->create_participant(0, participantQos);\n\n        if (participant_ == nullptr)\n        {\n            return false;\n        }\n\n        \/\/ Register the Type\n        type_.register_type(participant_);\n\n        \/\/ Create the publications Topic\n        topic_ = participant_->create_topic(\"HelloWorldTopic\", \"HelloWorld\", TOPIC_QOS_DEFAULT);\n\n        if (topic_ == nullptr)\n        {\n            return false;\n        }\n\n        \/\/ Create the Publisher\n        publisher_ = participant_->create_publisher(PUBLISHER_QOS_DEFAULT, nullptr);\n\n        if (publisher_ == nullptr)\n        {\n            return false;\n        }\n\n        \/\/ Create the DataWriter\n        DataWriterQos dwQos;\n        dwQos.reliability().kind = RELIABLE_RELIABILITY_QOS;\n        dwQos.reliability().max_blocking_time = 10;\n        \/\/dwQos.reliability().kind = BEST_EFFORT_RELIABILITY_QOS;\n\n        \/\/dwQos.durability_service().history_kind = KEEP_LAST_HISTORY_QOS;\n        \/\/dwQos.durability_service().history_depth = 10;\n        \n        \/\/writer_ = publisher_->create_datawriter(topic_, DATAWRITER_QOS_DEFAULT, &listener_);\n        writer_ = publisher_->create_datawriter(topic_, dwQos, &listener_);\n\n        if (writer_ == nullptr)\n        {\n            return false;\n        }\n        return true;\n    }\n\n    \/\/!Send a publication\n    bool publish()\n    {\n        if (listener_.matched_ > 0)\n        {\n            \/\/hello_.index(hello_.index() + 1);\n            hello_.value(hello_.value() + 1.0);\n            writer_->write(&hello_);\n            return true;\n        }\n        return false;\n    }\n\n    \/\/!Run the Publisher\n    void run(\n            uint32_t samples)\n    {\n        uint32_t samples_sent = 0;\n        \/\/while (samples_sent < samples)\n        while(sigintH)\n        {\n            if (publish())\n            {\n                samples_sent++;\n                std::cout << \"Value: \" << hello_.value() << \" SENT\" << std::endl;\n            }\n            std::this_thread::sleep_for(std::chrono::milliseconds(500));\n        }\n    }\n};\n\nint main(\n        int argc,\n        char** argv)\n{\n    signal(SIGINT, sigintHandler);\n\n    std::cout << \"Starting publisher.\" << std::endl;\n    \n    int samples = 1;\n\n    HelloWorldPublisher* mypub = new HelloWorldPublisher();\n\n    if(mypub->init())\n    {\n        mypub->run(static_cast<uint32_t>(samples));\n    }\n\n    delete mypub;\n    std::cout << \"Publisher clean up.\" << std::endl;\n    return 0;\n}\n","avg_line_length":25.6495726496,"max_line_length":115,"alphanum_fraction":0.5834721759,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3823,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["UPL-1.0","Apache-2.0"],"max_stars_count":6.0,"content":"\/*\n * Copyright (c) 2000, 2020, Oracle and\/or its affiliates.\n *\n * Licensed under the Universal Permissive License v 1.0 as shown at\n * http:\/\/oss.oracle.com\/licenses\/upl.\n *\/\n#include \"coherence\/io\/pof\/PortableObjectSerializer.hpp\"\n\n#include \"coherence\/io\/Evolvable.hpp\"\n#include \"coherence\/io\/IOException.hpp\"\n#include \"coherence\/io\/pof\/PortableObject.hpp\"\n#include \"coherence\/util\/Binary.hpp\"\n\n#include <algorithm>\n#include <typeinfo>\n\nCOH_OPEN_NAMESPACE3(coherence,io,pof)\n\nusing coherence::io::Evolvable;\nusing coherence::io::IOException;\nusing coherence::util::Binary;\n\n\n\/\/ ----- constructors -------------------------------------------------------\n\nPortableObjectSerializer::PortableObjectSerializer(int32_t nTypeId)\n        : m_nTypeId(nTypeId)\n    {\n    }\n\n\n\/\/ ----- PofSerializer interface --------------------------------------------\n\nvoid PortableObjectSerializer::serialize(PofWriter::Handle hOut, Object::View v) const\n    {\n    PortableObject::View vPortable;\n    try\n        {\n        vPortable = cast<PortableObject::View>(v);\n        }\n    catch (Exception::View e)\n        {\n        String::View vsClass;\n        try\n            {\n            vsClass = hOut->getPofContext()->getClassName(m_nTypeId);\n            }\n        catch (...) {}\n\n        String::View vsActual;\n        try\n            {\n            vsActual = Class::getClassName(v);\n            }\n        catch (...) {}\n\n        COH_THROW_STREAM (IOException,\n                \"An exception occurred writing a PortableObject\"\n                << \" user type to a POF stream: type-id=\" << m_nTypeId\n                << \", class-name=\"\n                << (NULL == vsClass ? \"N\/A\" : vsClass)\n                << \", actual class-name=\"\n                << (NULL == vsActual ? \"N\/A\" : vsActual)\n                << \", exception=\" << e);\n        }\n\n    \/\/ set the version identifier\n    Evolvable::View vEvolvable = cast<Evolvable::View>(vPortable, false);\n    bool            fEvolvable = NULL != vEvolvable;\n    if (fEvolvable)\n        {\n        hOut->setVersionId(std::max(vEvolvable->getDataVersion(),\n                vEvolvable->getImplVersion()));\n        }\n\n    \/\/ write out the object's properties\n    vPortable->writeExternal(hOut);\n\n    \/\/ write out any future properties\n    Binary::View vBin;\n    if (fEvolvable)\n        {\n        vBin = vEvolvable->getFutureData();\n        }\n    hOut->writeRemainder(vBin);\n    }\n\nObject::Holder PortableObjectSerializer::deserialize(PofReader::Handle hIn) const\n    {\n    \/\/ create a new instance of the user type\n    PortableObject::Handle hPortable;\n    try\n        {\n        hPortable = cast<PortableObject::Handle>(hIn->getPofContext()\n                ->getClass(m_nTypeId)->newInstance());\n        hIn->registerIdentity(hPortable);\n        }\n    catch (Exception::View e)\n        {\n        String::View vsClass;\n        try\n            {\n            vsClass = hIn->getPofContext()->getClassName(m_nTypeId);\n            }\n        catch (...) {}\n\n        COH_THROW_STREAM (IOException,\n                \"An exception occurred instantiating a PortableObject\"\n                << \" user type from a POF stream: type-id=\" << m_nTypeId\n                << \", class-name=\" << (NULL == vsClass ? \"N\/A\" : vsClass)\n                << \", exception=\" << e);\n        }\n\n    \/\/ set the version identifier\n    Evolvable::Handle hEvolvable = cast<Evolvable::Handle>(hPortable, false);\n    bool              fEvolvable = NULL != hEvolvable;\n    if (fEvolvable)\n        {\n        hEvolvable->setDataVersion(hIn->getVersionId());\n        }\n\n    \/\/ read the object's properties\n    hPortable->readExternal(hIn);\n\n    \/\/ read any future properties\n    Binary::View vBin = hIn->readRemainder();\n    if (fEvolvable)\n        {\n        hEvolvable->setFutureData(vBin);\n        }\n\n    return hPortable;\n    }\n\nCOH_CLOSE_NAMESPACE3\n","avg_line_length":28.1102941176,"max_line_length":86,"alphanum_fraction":0.5650013079,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11009,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <Babylon\/Plugins\/ExternalTexture.h>\n#include <Babylon\/Graphics\/Device.h>\n#include <Babylon\/Graphics\/DeviceContext.h>\n#include <Babylon\/Graphics\/RendererType.h>\n#include <Babylon\/Graphics\/Texture.h>\n#include <napi\/napi_pointer.h>\n#include <bx\/bx.h>\n#include <bgfx\/bgfx.h>\n#include <dxgiformat.h>\n#include <winrt\/base.h>\n\n\/\/ clang-format off\n\n\/\/ Copied from renderer_d3d.h\n#define DXGI_FORMAT_ASTC_4X4_UNORM        DXGI_FORMAT(134)\n#define DXGI_FORMAT_ASTC_4X4_UNORM_SRGB   DXGI_FORMAT(135)\n#define DXGI_FORMAT_ASTC_5X4_UNORM        DXGI_FORMAT(138)\n#define DXGI_FORMAT_ASTC_5X4_UNORM_SRGB   DXGI_FORMAT(139)\n#define DXGI_FORMAT_ASTC_5X5_UNORM        DXGI_FORMAT(142)\n#define DXGI_FORMAT_ASTC_5X5_UNORM_SRGB   DXGI_FORMAT(143)\n#define DXGI_FORMAT_ASTC_6X5_UNORM        DXGI_FORMAT(146)\n#define DXGI_FORMAT_ASTC_6X5_UNORM_SRGB   DXGI_FORMAT(147)\n#define DXGI_FORMAT_ASTC_6X6_UNORM        DXGI_FORMAT(150)\n#define DXGI_FORMAT_ASTC_6X6_UNORM_SRGB   DXGI_FORMAT(151)\n#define DXGI_FORMAT_ASTC_8X5_UNORM        DXGI_FORMAT(154)\n#define DXGI_FORMAT_ASTC_8X5_UNORM_SRGB   DXGI_FORMAT(155)\n#define DXGI_FORMAT_ASTC_8X6_UNORM        DXGI_FORMAT(158)\n#define DXGI_FORMAT_ASTC_8X6_UNORM_SRGB   DXGI_FORMAT(159)\n#define DXGI_FORMAT_ASTC_10X5_UNORM       DXGI_FORMAT(166)\n#define DXGI_FORMAT_ASTC_10X5_UNORM_SRGB  DXGI_FORMAT(167)\n\n\/\/ Copied from renderer_d3d11.cpp\nnamespace\n{\n    struct TextureFormatInfo\n    {\n        DXGI_FORMAT m_fmt;\n        DXGI_FORMAT m_fmtSrgb;\n    };\n\n    const TextureFormatInfo s_textureFormat[] =\n    {\n        { DXGI_FORMAT_BC1_UNORM,          DXGI_FORMAT_BC1_UNORM_SRGB       }, \/\/ BC1\n        { DXGI_FORMAT_BC2_UNORM,          DXGI_FORMAT_BC2_UNORM_SRGB       }, \/\/ BC2\n        { DXGI_FORMAT_BC3_UNORM,          DXGI_FORMAT_BC3_UNORM_SRGB       }, \/\/ BC3\n        { DXGI_FORMAT_BC4_UNORM,          DXGI_FORMAT_UNKNOWN              }, \/\/ BC4\n        { DXGI_FORMAT_BC5_UNORM,          DXGI_FORMAT_UNKNOWN              }, \/\/ BC5\n        { DXGI_FORMAT_BC6H_SF16,          DXGI_FORMAT_UNKNOWN              }, \/\/ BC6H\n        { DXGI_FORMAT_BC7_UNORM,          DXGI_FORMAT_BC7_UNORM_SRGB       }, \/\/ BC7\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ ETC1\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ ETC2\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ ETC2A\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ ETC2A1\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ PTC12\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ PTC14\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ PTC12A\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ PTC14A\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ PTC22\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ PTC24\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ ATC\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ ATCE\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ ATCI\n        { DXGI_FORMAT_ASTC_4X4_UNORM,     DXGI_FORMAT_ASTC_4X4_UNORM_SRGB  }, \/\/ ASTC4x4\n        { DXGI_FORMAT_ASTC_5X5_UNORM,     DXGI_FORMAT_ASTC_5X5_UNORM_SRGB  }, \/\/ ASTC5x5\n        { DXGI_FORMAT_ASTC_6X6_UNORM,     DXGI_FORMAT_ASTC_6X6_UNORM_SRGB  }, \/\/ ASTC6x6\n        { DXGI_FORMAT_ASTC_8X5_UNORM,     DXGI_FORMAT_ASTC_8X5_UNORM_SRGB  }, \/\/ ASTC8x5\n        { DXGI_FORMAT_ASTC_8X6_UNORM,     DXGI_FORMAT_ASTC_8X6_UNORM_SRGB  }, \/\/ ASTC8x6\n        { DXGI_FORMAT_ASTC_10X5_UNORM,    DXGI_FORMAT_ASTC_10X5_UNORM_SRGB }, \/\/ ASTC10x5\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ Unknown\n        { DXGI_FORMAT_R1_UNORM,           DXGI_FORMAT_UNKNOWN              }, \/\/ R1\n        { DXGI_FORMAT_A8_UNORM,           DXGI_FORMAT_UNKNOWN              }, \/\/ A8\n        { DXGI_FORMAT_R8_UNORM,           DXGI_FORMAT_UNKNOWN              }, \/\/ R8\n        { DXGI_FORMAT_R8_SINT,            DXGI_FORMAT_UNKNOWN              }, \/\/ R8I\n        { DXGI_FORMAT_R8_UINT,            DXGI_FORMAT_UNKNOWN              }, \/\/ R8U\n        { DXGI_FORMAT_R8_SNORM,           DXGI_FORMAT_UNKNOWN              }, \/\/ R8S\n        { DXGI_FORMAT_R16_UNORM,          DXGI_FORMAT_UNKNOWN              }, \/\/ R16\n        { DXGI_FORMAT_R16_SINT,           DXGI_FORMAT_UNKNOWN              }, \/\/ R16I\n        { DXGI_FORMAT_R16_UINT,           DXGI_FORMAT_UNKNOWN              }, \/\/ R16U\n        { DXGI_FORMAT_R16_FLOAT,          DXGI_FORMAT_UNKNOWN              }, \/\/ R16F\n        { DXGI_FORMAT_R16_SNORM,          DXGI_FORMAT_UNKNOWN              }, \/\/ R16S\n        { DXGI_FORMAT_R32_SINT,           DXGI_FORMAT_UNKNOWN              }, \/\/ R32I\n        { DXGI_FORMAT_R32_UINT,           DXGI_FORMAT_UNKNOWN              }, \/\/ R32U\n        { DXGI_FORMAT_R32_FLOAT,          DXGI_FORMAT_UNKNOWN              }, \/\/ R32F\n        { DXGI_FORMAT_R8G8_UNORM,         DXGI_FORMAT_UNKNOWN              }, \/\/ RG8\n        { DXGI_FORMAT_R8G8_SINT,          DXGI_FORMAT_UNKNOWN              }, \/\/ RG8I\n        { DXGI_FORMAT_R8G8_UINT,          DXGI_FORMAT_UNKNOWN              }, \/\/ RG8U\n        { DXGI_FORMAT_R8G8_SNORM,         DXGI_FORMAT_UNKNOWN              }, \/\/ RG8S\n        { DXGI_FORMAT_R16G16_UNORM,       DXGI_FORMAT_UNKNOWN              }, \/\/ RG16\n        { DXGI_FORMAT_R16G16_SINT,        DXGI_FORMAT_UNKNOWN              }, \/\/ RG16I\n        { DXGI_FORMAT_R16G16_UINT,        DXGI_FORMAT_UNKNOWN              }, \/\/ RG16U\n        { DXGI_FORMAT_R16G16_FLOAT,       DXGI_FORMAT_UNKNOWN              }, \/\/ RG16F\n        { DXGI_FORMAT_R16G16_SNORM,       DXGI_FORMAT_UNKNOWN              }, \/\/ RG16S\n        { DXGI_FORMAT_R32G32_SINT,        DXGI_FORMAT_UNKNOWN              }, \/\/ RG32I\n        { DXGI_FORMAT_R32G32_UINT,        DXGI_FORMAT_UNKNOWN              }, \/\/ RG32U\n        { DXGI_FORMAT_R32G32_FLOAT,       DXGI_FORMAT_UNKNOWN              }, \/\/ RG32F\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ RGB8\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ RGB8I\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ RGB8U\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ RGB8S\n        { DXGI_FORMAT_R9G9B9E5_SHAREDEXP, DXGI_FORMAT_UNKNOWN              }, \/\/ RGB9E5F\n        { DXGI_FORMAT_B8G8R8A8_UNORM,     DXGI_FORMAT_B8G8R8A8_UNORM_SRGB  }, \/\/ BGRA8\n        { DXGI_FORMAT_R8G8B8A8_UNORM,     DXGI_FORMAT_R8G8B8A8_UNORM_SRGB  }, \/\/ RGBA8\n        { DXGI_FORMAT_R8G8B8A8_SINT,      DXGI_FORMAT_R8G8B8A8_UNORM_SRGB  }, \/\/ RGBA8I\n        { DXGI_FORMAT_R8G8B8A8_UINT,      DXGI_FORMAT_R8G8B8A8_UNORM_SRGB  }, \/\/ RGBA8U\n        { DXGI_FORMAT_R8G8B8A8_SNORM,     DXGI_FORMAT_UNKNOWN              }, \/\/ RGBA8S\n        { DXGI_FORMAT_R16G16B16A16_UNORM, DXGI_FORMAT_UNKNOWN              }, \/\/ RGBA16\n        { DXGI_FORMAT_R16G16B16A16_SINT,  DXGI_FORMAT_UNKNOWN              }, \/\/ RGBA16I\n        { DXGI_FORMAT_R16G16B16A16_UINT,  DXGI_FORMAT_UNKNOWN              }, \/\/ RGBA16U\n        { DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_UNKNOWN              }, \/\/ RGBA16F\n        { DXGI_FORMAT_R16G16B16A16_SNORM, DXGI_FORMAT_UNKNOWN              }, \/\/ RGBA16S\n        { DXGI_FORMAT_R32G32B32A32_SINT,  DXGI_FORMAT_UNKNOWN              }, \/\/ RGBA32I\n        { DXGI_FORMAT_R32G32B32A32_UINT,  DXGI_FORMAT_UNKNOWN              }, \/\/ RGBA32U\n        { DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_UNKNOWN              }, \/\/ RGBA32F\n        { DXGI_FORMAT_B5G6R5_UNORM,       DXGI_FORMAT_UNKNOWN              }, \/\/ R5G6B5\n        { DXGI_FORMAT_B4G4R4A4_UNORM,     DXGI_FORMAT_UNKNOWN              }, \/\/ RGBA4\n        { DXGI_FORMAT_B5G5R5A1_UNORM,     DXGI_FORMAT_UNKNOWN              }, \/\/ RGB5A1\n        { DXGI_FORMAT_R10G10B10A2_UNORM,  DXGI_FORMAT_UNKNOWN              }, \/\/ RGB10A2\n        { DXGI_FORMAT_R11G11B10_FLOAT,    DXGI_FORMAT_UNKNOWN              }, \/\/ RG11B10F\n        { DXGI_FORMAT_UNKNOWN,            DXGI_FORMAT_UNKNOWN              }, \/\/ UnknownDepth\n        { DXGI_FORMAT_R16_TYPELESS,       DXGI_FORMAT_UNKNOWN              }, \/\/ D16\n        { DXGI_FORMAT_R24G8_TYPELESS,     DXGI_FORMAT_UNKNOWN              }, \/\/ D24\n        { DXGI_FORMAT_R24G8_TYPELESS,     DXGI_FORMAT_UNKNOWN              }, \/\/ D24S8\n        { DXGI_FORMAT_R24G8_TYPELESS,     DXGI_FORMAT_UNKNOWN              }, \/\/ D32\n        { DXGI_FORMAT_R32_TYPELESS,       DXGI_FORMAT_UNKNOWN              }, \/\/ D16F\n        { DXGI_FORMAT_R32_TYPELESS,       DXGI_FORMAT_UNKNOWN              }, \/\/ D24F\n        { DXGI_FORMAT_R32_TYPELESS,       DXGI_FORMAT_UNKNOWN              }, \/\/ D32F\n        { DXGI_FORMAT_R24G8_TYPELESS,     DXGI_FORMAT_UNKNOWN              }, \/\/ D0S8\n    };\n    BX_STATIC_ASSERT(bgfx::TextureFormat::Count == BX_COUNTOF(s_textureFormat));\n}\n\n\/\/ clang-format on\n\nnamespace Babylon::Plugins\n{\n    class ExternalTexture::Impl\n    {\n    public:\n        Impl(Graphics::TextureT ptr)\n        {\n            m_ptr.copy_from(ptr);\n\n            D3D11_RESOURCE_DIMENSION type;\n            m_ptr->GetType(&type);\n            if (type != D3D11_RESOURCE_DIMENSION_TEXTURE2D)\n            {\n                throw std::runtime_error{\"Unsupported texture type\"};\n            }\n\n            m_ptr.as<ID3D11Texture2D>()->GetDesc(&m_desc);\n            if (m_desc.MipLevels > 1)\n            {\n                throw std::runtime_error{\"Unsupported texture mip levels\"};\n            }\n\n            for (int i = 0; i < BX_COUNTOF(s_textureFormat); ++i)\n            {\n                const auto& info = s_textureFormat[i];\n                if (info.m_fmt == m_desc.Format || info.m_fmtSrgb == m_desc.Format)\n                {\n                    m_format = static_cast<bgfx::TextureFormat::Enum>(i);\n                    if (info.m_fmtSrgb == m_desc.Format)\n                    {\n                        m_flags |= BGFX_TEXTURE_SRGB;\n                    }\n                    break;\n                }\n            }\n        }\n\n        uint16_t Width() const\n        {\n            return static_cast<uint16_t>(m_desc.Width);\n        }\n\n        uint16_t Height() const\n        {\n            return static_cast<uint16_t>(m_desc.Height);\n        }\n\n        bgfx::TextureFormat::Enum Format() const\n        {\n            return m_format;\n        }\n\n        bool HasMips() const\n        {\n            return m_desc.MipLevels == 0;\n        }\n\n        uint64_t Flags() const\n        {\n            return m_flags;\n        }\n\n        uintptr_t Ptr() const\n        {\n            return reinterpret_cast<uintptr_t>(m_ptr.get());\n        }\n\n    private:\n        winrt::com_ptr<ID3D11Resource> m_ptr{};\n        D3D11_TEXTURE2D_DESC m_desc{};\n        bgfx::TextureFormat::Enum m_format{bgfx::TextureFormat::Unknown};\n        uint64_t m_flags{};\n    };\n}\n\n#include \"ExternalTexture_Shared.h\"\n","avg_line_length":52.4238095238,"max_line_length":93,"alphanum_fraction":0.5793441729,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":352,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\n\n\n#include \"PhysicsApplication.hpp\"\n\nusing namespace fs;\n\nint main(int arg, char** argv)\n{\n    try\n    {\n        fs::SimpleApplicationPtr simpleApplication(new fs::PhysicsApplication());\n        simpleApplication->run();\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"Unknwon error: \" << e.what() << std::endl;\n    }\n\n    return 0;\n}\n","avg_line_length":16.0,"max_line_length":81,"alphanum_fraction":0.5852272727,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2280,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/*\n * Copyright 2016 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ This is a helper for the parentDeathSignal test in SubprocessTest.cpp.\n\/\/\n\/\/ Basically, we create two processes, a parent and a child, and set the\n\/\/ child to receive SIGUSR1 when the parent exits.  We set the child to\n\/\/ create a file when that happens.  The child then kills the parent; the test\n\/\/ will verify that the file actually gets created, which means that everything\n\/\/ worked as intended.\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <signal.h>\n#include <unistd.h>\n\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n\n#include <folly\/Conv.h>\n#include <folly\/Subprocess.h>\n\nusing folly::Subprocess;\n\nDEFINE_bool(child, false, \"\");\n\nnamespace {\nconstexpr int kSignal = SIGUSR1;\n}  \/\/ namespace\n\nvoid runChild(const char* file) {\n  \/\/ Block SIGUSR1 so it's queued\n  sigset_t sigs;\n  CHECK_ERR(sigemptyset(&sigs));\n  CHECK_ERR(sigaddset(&sigs, kSignal));\n  CHECK_ERR(sigprocmask(SIG_BLOCK, &sigs, nullptr));\n\n  \/\/ Kill the parent, wait for our signal.\n  CHECK_ERR(kill(getppid(), SIGKILL));\n\n  int sig = 0;\n  CHECK_ERR(sigwait(&sigs, &sig));\n  CHECK_EQ(sig, kSignal);\n\n  \/\/ Signal completion by creating the file\n  CHECK_ERR(creat(file, 0600));\n}\n\nvoid runParent(const char* file) {\n  std::vector<std::string> args {\"\/proc\/self\/exe\", \"--child\", file};\n  Subprocess proc(\n      args,\n      Subprocess::Options().parentDeathSignal(kSignal));\n  CHECK(proc.poll().running());\n\n  \/\/ The child will kill us.\n  for (;;) {\n    pause();\n  }\n}\n\nint main(int argc, char *argv[]) {\n  gflags::ParseCommandLineFlags(&argc, &argv, true);\n  CHECK_EQ(argc, 2);\n  if (FLAGS_child) {\n    runChild(argv[1]);\n  } else {\n    runParent(argv[1]);\n  }\n  return 0;\n}\n","avg_line_length":26.511627907,"max_line_length":79,"alphanum_fraction":0.698245614,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":19265,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":11.0,"content":"\n#include <vector>\n#include <string>\n#include <iostream>\n#include <functional>\n#include <unordered_set>\n#include <unordered_map>\n\n#include <filesystem>\n#include <fstream>\n\n#include <clang-c\/Index.h>\n\nstd::string getString(CXString str) {\n\tstd::string cStr(clang_getCString(str));\n\tclang_disposeString(str);\n\treturn cStr;\n}\n\nstd::string getNamespace(CXCursor cursor) {\n\tCXCursor semParent = clang_getCursorSemanticParent(cursor);\n\tauto kind = clang_getCursorKind(semParent);\n\n\tif (kind == CXCursorKind::CXCursor_FirstInvalid ||\n\t\tkind == CXCursorKind::CXCursor_TranslationUnit)\n\t\treturn {};\n\n\n\tif (kind == CXCursorKind::CXCursor_Namespace)\n\t\treturn getNamespace(semParent) + \"::\" + getString(clang_getCursorSpelling(semParent));\n\treturn getNamespace(semParent);\n}\n\nstd::string getFullQualifiedName(CXCursor cursor) {\n\tCXCursor semParent = clang_getCursorSemanticParent(cursor);\n\tauto kind = clang_getCursorKind(semParent);\n\tif (kind == CXCursorKind::CXCursor_FirstInvalid ||\n\t\tkind == CXCursorKind::CXCursor_TranslationUnit)\n\t\treturn {};\n\n\tstd::string currentLayerName = getString(clang_getCursorSpelling(semParent));\n\tif (currentLayerName.empty())\n\t\treturn getFullQualifiedName(semParent);\n\treturn getFullQualifiedName(semParent) + \"::\" + currentLayerName;\n}\n\nstd::string g_currentlyWorkedOnFile;\n\nbool isCursorFromCurrentFile(CXCursor cursor) {\n\tCXSourceLocation sourceLoc = clang_getCursorLocation(clang_getCursorDefinition(cursor));\n\n\tCXFile sourceF;\n\tunsigned int a, b, c;\n\tclang_getFileLocation(sourceLoc, &sourceF, &a, &b, &c);\n\n\tCXString fileName = clang_getFileName(sourceF);\n\tconst char* cstr = clang_getCString(fileName);\n\tif (cstr != nullptr) {\n\t\tbool retVal = (g_currentlyWorkedOnFile == cstr);\n\t\tstd::cout << g_currentlyWorkedOnFile << \" vs \" << std::string(cstr) << \" - \" << (retVal ? \"true\" : \"false\") << std::endl;\n\t\tclang_disposeString(fileName);\n\t\treturn retVal;\n\t}\n\treturn false;\n}\n\nstd::vector<std::string> getAnnotations(CXCursor cursor) {\n\tstd::vector<std::string> output;\n\tclang_visitChildren(\n\t\tcursor,\n\t\t[](CXCursor cursor, CXCursor \/* parent *\/, CXClientData client_data) {\n\t\t\tif (clang_getCursorKind(cursor) == CXCursorKind::CXCursor_AnnotateAttr) {\n\t\t\t\tauto* outputPtr = static_cast<std::vector<std::string>*>(client_data);\n\t\t\t\toutputPtr->emplace_back(getString(clang_getCursorDisplayName(cursor)));\n\t\t\t}\n\t\t\treturn CXChildVisitResult::CXChildVisit_Continue;\n\t\t},\n\t\t&output\n\t\t\t);\n\treturn output;\n}\n\nstruct field\n{\n\tbool operator == (const field& other) const = default;\n\n\tstd::string spelling;\n\tstd::string type;\n\tstd::vector<std::string> annotations;\n};\n\nnamespace std {\n\ttemplate<>\n\tstruct hash<field> {\n\t\tsize_t operator()(const field& f) const {\n\t\t\treturn std::hash<std::string>()(f.spelling);\n\t\t}\n\t};\n}\n\nstruct reflected_type\n{\n\tstd::unordered_set<field> m_fields;\n\tstd::vector<std::string> annotations;\n\tbool generate_reflection = true;\n\tbool generate_serialization = true;\n};\n\nstd::vector<std::string> namespaces;\nstd::vector<char const*> g_clangOptions;\nstd::unordered_map<std::string, reflected_type> g_reflected_types;\n\nbool handleInterestingCursor(CXCursor cursor, std::string canonicalType = \"\", bool generate_serialization = true) {\n\n\tCXCursorKind kind = clang_getCursorKind(cursor);\n\n\tif (kind == CXCursorKind::CXCursor_FieldDecl) {\n\t\tstd::string spelling = getString(clang_getCursorSpelling(cursor));\n\t\tstd::string displayName = getString(clang_getCursorDisplayName(cursor));\n\n\t\tif (clang_getCXXAccessSpecifier(cursor) != CX_CXXAccessSpecifier::CX_CXXPublic) {\n\t\t\treturn false;\n\t\t}\n\n\t\tCXType def = clang_getCursorType(cursor);\n\t\tCXType canonType = clang_getCanonicalType(def);\n\t\tstd::string field_type_spelling = getString(clang_getTypeSpelling(canonType));\n\n\t\tstruct userData {\n\t\t\tstd::string field_type_spelling;\n\t\t\tbool generate_serialization;\n\t\t};\n\n\t\tuserData data;\n\t\tdata.field_type_spelling = field_type_spelling;\n\t\tstd::cout << \"checking: \" << getString(clang_getCursorSpelling(clang_getCursorDefinition(cursor))) << std::endl;\n\t\tdata.generate_serialization = isCursorFromCurrentFile(clang_getTypeDeclaration(clang_getCursorType(cursor)));\n\n\t\tclang_Type_visitFields(\n\t\t\tcanonType,\n\t\t\t[](CXCursor fieldCursor, CXClientData client_data) {\n\t\t\t\thandleInterestingCursor(fieldCursor, static_cast<userData*>(client_data)->field_type_spelling, static_cast<userData*>(client_data)->generate_serialization);\n\t\t\t\treturn CXVisitorResult::CXVisit_Continue;\n\t\t\t},\n\t\t\t&data\n\t\t\t\t);\n\n\t\tfield currentField;\n\t\tcurrentField.spelling = spelling;\n\t\tcurrentField.type = field_type_spelling;\n\t\tcurrentField.annotations = getAnnotations(cursor);\n\n\t\tif (canonicalType.empty()) {\n\t\t\tstd::string fullTypeName = getFullQualifiedName(cursor);\n\t\t\tg_reflected_types[fullTypeName].m_fields.emplace(currentField);\n\t\t}\n\t\telse {\n\t\t\tg_reflected_types[\"::\" + canonicalType].m_fields.emplace(currentField);\n\t\t\tg_reflected_types[\"::\" + canonicalType].generate_serialization = generate_serialization;\n\t\t}\n\t}\n\n\tif (kind == CXCursor_StructDecl || kind == CXCursor_ClassDecl) {\n\t\tstd::string spelling = getString(clang_getCursorSpelling(cursor));\n\t\tstd::string targetTypeName = getString(clang_getTypeSpelling(clang_getCursorType(cursor)));\n\t\tif (!canonicalType.empty()) {\n\t\t\ttargetTypeName = canonicalType;\n\t\t}\n\n\t\t\/\/ serialization only generated for types declared in processed file.\n\t\tif (canonicalType.empty()) {\n\t\t\tstd::cout << \"canonType: \" << canonicalType << \", targetType: \" << targetTypeName << std::endl;\n\t\t\tg_reflected_types[\"::\" + targetTypeName].generate_serialization = isCursorFromCurrentFile(clang_getCursorDefinition(cursor));\n\t\t}\n\n\t\t\/\/ handle inheritance - visit through base classes recursively.\n\t\tclang_visitChildren(\n\t\t\tcursor,\n\t\t\t[](CXCursor child, CXCursor \/* parent *\/, CXClientData data) {\n\t\t\t\tif (clang_getCursorKind(child) == CXCursorKind::CXCursor_CXXBaseSpecifier) {\n\t\t\t\t\tCXType childType = clang_getCursorType(child);\n\n\t\t\t\t\t\/\/ call once with the base type - to enable recursive base class crawling.\n\t\t\t\t\thandleInterestingCursor(clang_getTypeDeclaration(childType), *static_cast<std::string*>(data));\n\n\t\t\t\t\t\/\/ and call once for each field to attach base class public members to derived class reflection.\n\t\t\t\t\tclang_Type_visitFields(\n\t\t\t\t\t\tchildType,\n\t\t\t\t\t\t[](CXCursor fieldCursor, CXClientData client_data) {\n\t\t\t\t\t\t\thandleInterestingCursor(fieldCursor, *static_cast<std::string*>(client_data));\n\t\t\t\t\t\t\treturn CXVisitorResult::CXVisit_Continue;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdata\n\t\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn CXChildVisit_Continue;\n\t\t\t},\n\t\t\t&targetTypeName\n\t\t\t\t);\n\n\t\tCXType type = clang_getCursorType(cursor);\n\t\tauto typeSizeOf = clang_Type_getSizeOf(type);\n\t\tif (typeSizeOf == CXTypeLayoutError_Incomplete || typeSizeOf == CXTypeLayoutError_Dependent) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!spelling.empty()) {\n\t\t\t\/\/ ensures the type is created (operator []), and also stores annotations if present.\n\t\t\tg_reflected_types[getFullQualifiedName(cursor) + \"::\" + spelling].annotations = getAnnotations(cursor);\n\t\t}\n\t}\n\n\treturn false;\n}\n\nvoid compile(CXIndex& index, std::string path);\n\nstd::vector<std::string> g_generated_reflection_functions;\n\nvoid write_results(std::string source_file) {\n\t{\n\t\tstd::string templateTypeNamePrefix(\"type-parameter\");\n\t\tstd::vector<std::string> templateTypes;\n\t\tfor (auto&& type : g_reflected_types) {\n\t\t\tfor (auto&& field : type.second.m_fields) {\n\t\t\t\tif (field.type.length() > templateTypeNamePrefix.length() && field.type.find(templateTypeNamePrefix) != std::string::npos) {\n\t\t\t\t\ttemplateTypes.emplace_back(type.first);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (auto&& typeName : templateTypes) {\n\t\t\tstd::cout << \"erasing incomplete template type \" << typeName << std::endl;\n\t\t\tg_reflected_types.erase(typeName);\n\t\t}\n\n\t\tstd::string standardTypePrefix(\"::std::\");\n\t\tstd::vector<std::string> standardTypes;\n\t\tfor (auto&& type : g_reflected_types) {\n\t\t\tif (type.first.length() > standardTypePrefix.length() && memcmp(type.first.data(), standardTypePrefix.data(), standardTypePrefix.length()) == 0) {\n\t\t\t\tstandardTypes.emplace_back(type.first);\n\t\t\t}\n\t\t}\n\n\t\tfor (auto&& typeName : standardTypes) {\n\t\t\tstd::cout << \"erasing standard type \" << typeName << std::endl;\n\t\t\tg_reflected_types.erase(typeName);\n\t\t}\n\t}\n\n\tstd::string includeSourceFile = source_file;\n\n\t\/\/ format processed header file paths\n\t{\n\t\t\/\/ for (auto&& path : compiledHeaderFiles) {\n\t\tfor (auto& c : source_file) {\n\t\t\tif (c == '\\\\')\n\t\t\t\tc = '\/';\n\t\t}\n\n\t\twhile (source_file.front() == '.' || source_file.front() == '\/') {\n\t\t\tsource_file.erase(source_file.begin());\n\t\t}\n\n\t\tauto pos = source_file.find(std::string(\"src\/\"));\n\t\tif (pos != std::string::npos) {\n\t\t\tincludeSourceFile = source_file.substr(pos + 4);\n\t\t}\n\t\t\/\/ }\n\t}\n\n\n\tstd::string pathBase = source_file.substr(0, source_file.size() - 4);\n\tstd::string functionRandomName = \"register_generated_reflections_\";\n\n\t{\n\t\tstd::string randomPartOfName = std::to_string(std::chrono::high_resolution_clock::now().time_since_epoch().count()) + \"_\" + std::to_string(rand());\n\t\tfor (auto& c : randomPartOfName) {\n\t\t\tif (c >= '0' && c <= '9') {\n\t\t\t\tc -= '0';\n\t\t\t\tc += 'a';\n\t\t\t}\n\t\t}\n\t\tfunctionRandomName += randomPartOfName;\n\t}\n\n\tg_generated_reflection_functions.emplace_back(functionRandomName);\n\n\t\/\/ write reflection hpp\n\t{\n\t\tstd::cout << \"writing '\" << pathBase + \"_reflection.hpp\" << \"'\" << std::endl;\n\t\tstd::ofstream fileOutput(pathBase + \"_reflection.hpp\");\n\t\tstd::ostream& output = fileOutput;\n\n\t\toutput << std::endl << \"\/\/ This is a generated file. Not productive to modify by hand.\" << std::endl;\n\t\toutput << std::endl;\n\t\toutput << \"namespace rynx {\" << std::endl;\n\t\toutput << \"namespace reflection {\" << std::endl;\n\t\toutput << \"class reflections;\" << std::endl;\n\t\toutput << \"namespace generated {\" << std::endl;\n\t\toutput << \"void \" << functionRandomName << \"(rynx::reflection::reflections& type_reflections);\" << std::endl;\n\t\toutput << \"extern int \" << functionRandomName << \"_i;\" << std::endl;\n\t\toutput << \"}\" << std::endl;\n\t\toutput << \"}\" << std::endl;\n\t\toutput << \"}\" << std::endl;\n\t}\n\n\t\/\/ write reflection cpp\n\t{\n\t\tstd::cout << \"writing '\" << pathBase + \"_reflection.cpp\" << \"'\" << std::endl;\n\t\tstd::ofstream fileOutput(pathBase + \"_reflection.cpp\");\n\t\tstd::ostream& output = fileOutput;\n\n\t\t{\n\t\t\toutput << std::endl << \"\/\/ This is a generated file. Not productive to modify by hand.\" << std::endl;\n\n\t\t\t\/\/ include processed files.\n\t\t\toutput << \"#include <\" << (includeSourceFile.substr(0, includeSourceFile.size() - 4) + \"_reflection.hpp>\") << std::endl;\n\t\t\t\/\/ for (auto&& path : compiledHeaderFiles) {\n\t\t\toutput << \"#include <\" << includeSourceFile << \">\" << std::endl;\n\t\t\t\/\/ }\n\t\t\toutput << \"#include <rynx\/tech\/reflection.hpp>\" << std::endl;\n\n\t\t\toutput << std::endl;\n\t\t\toutput << \"namespace rynx {\" << std::endl;\n\t\t\toutput << \"namespace reflection {\" << std::endl;\n\t\t\toutput << \"namespace generated {\" << std::endl;\n\n\t\t\toutput << std::endl << \"void \" << functionRandomName << \"(rynx::reflection::reflections& type_reflections) {\" << std::endl;\n\n\t\t\tfor (auto&& type : g_reflected_types) {\n\t\t\t\tif (!type.second.generate_reflection)\n\t\t\t\t\tcontinue;\n\n\t\t\t\toutput << \"{\" << std::endl;\n\t\t\t\tif (type.second.m_fields.empty()) {\n\t\t\t\t\toutput << \"\\t\" << \"type_reflections.create<\" << type.first << \">();\" << std::endl;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\toutput << \"\\t\" << \"auto& reflection = type_reflections.create<\" << type.first << \">();\" << std::endl;\n\t\t\t\t}\n\n\t\t\t\tfor (auto&& field : type.second.m_fields) {\n\t\t\t\t\toutput << \"\\t\" << \"reflection.add_field(\\\"\" << field.spelling << \"\\\", &\" << type.first << \"::\" << field.spelling;\n\t\t\t\t\tif (!field.annotations.empty()) {\n\t\t\t\t\t\toutput << \", std::vector<std::string>{\\n\\t\\t\\\"\" << field.annotations.front() << \"\\\"\";\n\t\t\t\t\t\tfor (int annotation_i = 1; annotation_i < field.annotations.size(); ++annotation_i) {\n\t\t\t\t\t\t\toutput << \",\\n\\t\\t\\\"\" << field.annotations[annotation_i] << \"\\\"\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutput << \"\\n\\t}\";\n\t\t\t\t\t}\n\n\t\t\t\t\toutput << \");\" << std::endl;\n\t\t\t\t}\n\t\t\t\toutput << \"}\" << std::endl << std::endl;\n\t\t\t}\n\n\t\t\toutput << std::endl << \"} \/\/ reflection register func\" << std::endl;\n\n\t\t\toutput << \"rynx::reflection::internal::registration_object \" << functionRandomName << \"_loader([](rynx::reflection::reflections& type_reflections) { \" << functionRandomName << \"(type_reflections); });\" << std::endl;\n\t\t\toutput << \"int \" << functionRandomName << \"_i = 0;\" << std::endl;\n\n\t\t\toutput\n\t\t\t\t<< std::endl << \"} \/\/ namespace generated\"\n\t\t\t\t<< std::endl << \"} \/\/ namespace reflection\"\n\t\t\t\t<< std::endl << \"} \/\/ namespace rynx\"\n\t\t\t\t<< std::endl;\n\t\t}\n\t}\n\n\t\/\/ write serialization hpp\n\t{\n\t\tstd::cout << \"writing '\" << pathBase + \"_serialization.hpp\" << \"'\" << std::endl;\n\t\tstd::ofstream fileOutput(pathBase + \"_serialization.hpp\");\n\t\tstd::ostream& output = fileOutput;\n\n\t\tbool compiler_is_forced_to_evaluate_reflection_loader_obj = false;\n\n\t\t{\n\t\t\toutput << std::endl << \"\/\/ This is a generated file. Not productive to modify by hand.\" << std::endl;\n\n\t\t\t\/\/ include processed files.\n\t\t\t\/\/ for (auto&& path : compiledHeaderFiles) {\n\t\t\toutput << \"#include <\" << includeSourceFile << \">\" << std::endl;\n\t\t\t\/\/ }\n\t\t\toutput << \"#include <rynx\/tech\/serialization.hpp>\" << std::endl;\n\n\t\t\toutput << std::endl;\n\t\t\toutput << \"namespace rynx {\" << std::endl;\n\t\t\toutput << \"namespace reflection { namespace generated { \";\n\t\t\toutput << \"extern int \" << (functionRandomName + \"_i;\");\n\t\t\toutput << \"}}\" << std::endl;\n\n\n\t\t\toutput << \"namespace serialization {\" << std::endl;\n\n\t\t\tfor (auto&& type : g_reflected_types) {\n\t\t\t\tbool skipType = false;\n\t\t\t\tfor (auto&& ann : type.second.annotations)\n\t\t\t\t\tskipType |= (ann == \"transient\");\n\n\t\t\t\tif (skipType)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (!type.second.generate_serialization) {\n\t\t\t\t\tstd::cout << \"serialization not generated for \" << type.first << std::endl;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\toutput << \"template<> struct Serialize<\" + type.first + \"> {\\n\";\n\t\t\t\toutput << \"\\ttemplate<typename IOStream> static void serialize(const \" + type.first + \"& t, IOStream& writer) {\\n\";\n\t\t\t\tfor (auto&& field : type.second.m_fields) {\n\t\t\t\t\tif (true || !compiler_is_forced_to_evaluate_reflection_loader_obj) {\n\t\t\t\t\t\toutput << \"\\t\\t++rynx::reflection::generated::\" << (functionRandomName + \"_i;\\n\");\n\t\t\t\t\t\tcompiler_is_forced_to_evaluate_reflection_loader_obj = true;\n\t\t\t\t\t}\n\t\t\t\t\toutput << \"\\t\\t\" << \"rynx::serialize(t.\" << field.spelling << \", writer);\\n\";\n\t\t\t\t}\n\t\t\t\toutput << \"\\t}\" << std::endl;\n\n\t\t\t\toutput << \"\\ttemplate<typename IOStream> static void deserialize(\" + type.first + \"& t, IOStream& reader) {\\n\";\n\t\t\t\tfor (auto&& field : type.second.m_fields) {\n\t\t\t\t\toutput << \"\\t\\t\" << \"rynx::deserialize(t.\" << field.spelling << \", reader);\\n\";\n\t\t\t\t}\n\t\t\t\toutput << \"\\t}\" << std::endl;\n\n\t\t\t\toutput << \"};\" << std::endl << std::endl;\n\n\n\t\t\t\t\/\/ also write definition for \"for_each_id_field\"\n\t\t\t\tbool is_id_type = (type.first == \"::rynx::ecs::id\" || type.first == \"::rynx::id\" || type.first == \"::rynx::ecs_internal::id\");\n\n\t\t\t\t\/\/ only write the definitions if this type is not an id type, and has some fields.\n\t\t\t\tif (!type.second.m_fields.empty() && !is_id_type) {\n\t\t\t\t\toutput << \"template<> struct for_each_id_field_t<\" << type.first << \"> {\\n\";\n\t\t\t\t\toutput << \"\\ttemplate<typename Op> static void execute(\" << type.first << \"& t, Op&& op) {\\n\";\n\t\t\t\t\tif (!compiler_is_forced_to_evaluate_reflection_loader_obj) {\n\t\t\t\t\t\toutput << \"\\t\\t++rynx::reflection::generated::\" << (functionRandomName + \"_i;\\n\");\n\t\t\t\t\t\tcompiler_is_forced_to_evaluate_reflection_loader_obj = true;\n\t\t\t\t\t}\n\t\t\t\t\tfor (auto&& field : type.second.m_fields) {\n\t\t\t\t\t\toutput << \"\\t\\trynx::for_each_id_field(t.\" << field.spelling << \", std::forward<Op>(op));\\n\";\n\t\t\t\t\t}\n\t\t\t\t\toutput << \"\\t}\" << std::endl; \/\/ end function\n\t\t\t\t\toutput << \"};\" << std::endl << std::endl; \/\/ end struct\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toutput << std::endl << \"} \/\/ namespace serialization\"\n\t\t\t\t<< std::endl << \"} \/\/ namespace rynx\"\n\t\t\t\t<< std::endl;\n\t\t}\n\t}\n}\n\nint main(int argc, char** argv) {\n\tstd::vector<std::string> fileMatchers;\n\tstd::vector<std::string> fileEnds;\n\tstd::vector<std::string> compiledHeaderFiles;\n\n\tstd::string source_code_scan_path = \".\";\n\n\tfor (int i = 1; i < argc; ++i) {\n\t\tif (std::string(argv[i]) == \"-filename-contains\") {\n\t\t\tfileMatchers.emplace_back(std::string(argv[++i]));\n\t\t}\n\t\telse if (std::string(argv[i]) == \"-filename-ends-with\") {\n\t\t\tfileEnds.emplace_back(std::string(argv[++i]));\n\t\t}\n\t\telse if (std::string(argv[i]) == \"-gen-for-namespace\") {\n\t\t\tnamespaces.emplace_back(std::string(argv[++i]));\n\t\t}\n\t\telse if (std::string(argv[i]) == \"-I\") {\n\t\t\tg_clangOptions.emplace_back(argv[i]);\n\t\t\tg_clangOptions.emplace_back(argv[++i]);\n\t\t}\n\t\telse if (std::string(argv[i]).starts_with(\"-D\")) {\n\t\t\tg_clangOptions.emplace_back(argv[i]);\n\t\t\tg_clangOptions.emplace_back(argv[++i]);\n\t\t}\n\t\telse if (std::string(argv[i]).find(std::string(\"--std\")) != std::string::npos) {\n\t\t\tg_clangOptions.emplace_back(argv[i]);\n\t\t}\n\t\telse if (std::string(argv[i]) == \"-src_path\") {\n\t\t\tsource_code_scan_path = argv[++i];\n\t\t}\n\t\telse {\n\t\t\tstd::cerr << \"unrecognized option '\" << std::string(argv[i]) << \"', commands are:\\n\"\n\t\t\t\t\"-filename-contains <partial matching string, for example \\\"-filename-contains components\\\">\\n\"\n\t\t\t\t\"-filename-ends-with <only concider files that end with this string. for example cpp>\\n\"\n\t\t\t\t\"-gen-for-namespace ::namespace::to::gen\\n\"\n\t\t\t\t\"-I <includepath>\\n\"\n\t\t\t\t\"-Dmydefine\\n\"\n\t\t\t\t\"-src_path <source code root path>\"\n\t\t\t\t\"--std=desiredstandard\" << std::endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tg_clangOptions.emplace_back(\"-DRYNX_CODEGEN\");\n\n\tCXIndex index = clang_createIndex(0, 0);\n\tstd::filesystem::path wd_path(\".\");\n\tstd::filesystem::directory_entry wd(wd_path);\n\n\tfor (auto& p : std::filesystem::recursive_directory_iterator(source_code_scan_path)) {\n\t\tif (p.is_regular_file()) {\n\t\t\tstd::string path_string = p.path().string();\n\n\t\t\tbool matchesAny = fileMatchers.empty();\n\t\t\tfor (auto&& matcher : fileMatchers)\n\t\t\t\tmatchesAny |= (path_string.find(matcher) != std::string::npos);\n\n\t\t\tbool endsWithMatch = fileEnds.empty();\n\t\t\tfor (auto&& fileEnd : fileEnds)\n\t\t\t\tendsWithMatch |= path_string.ends_with(fileEnd);\n\n\t\t\tif (matchesAny && endsWithMatch) {\n\t\t\t\tg_reflected_types.clear();\n\n\t\t\t\tcompiledHeaderFiles.emplace_back(path_string);\n\t\t\t\tcompile(index, path_string);\n\n\t\t\t\twrite_results(path_string);\n\t\t\t}\n\t\t}\n\t}\n\n\tclang_disposeIndex(index);\n\treturn 0;\n}\n\nvoid compile(CXIndex& index, std::string path) {\n\tstd::cout << \"processing \" << path << \" ...\" << std::endl;\n\n\tCXTranslationUnit unit;\n\t[[maybe_unused]] CXErrorCode error = clang_parseTranslationUnit2(index, path.c_str(), g_clangOptions.data(), int(g_clangOptions.size()), nullptr, 0, 0, &unit);\n\n\tstd::vector<std::string> includeNamespace = { \"\" };\n\tg_currentlyWorkedOnFile = path;\n\n\tCXCursor cursor = clang_getTranslationUnitCursor(unit);\n\tclang_visitChildren(\n\t\tcursor,\n\t\t[](CXCursor cursor, CXCursor \/* parent *\/, CXClientData \/* client_data *\/) {\n\t\t\tstd::string fullNamespace = getNamespace(cursor);\n\t\t\tbool accept = namespaces.empty();\n\t\t\tfor (auto&& ns_name : namespaces) {\n\t\t\t\taccept |= (fullNamespace.find(ns_name) != std::string::npos);\n\t\t\t}\n\n\t\t\tif (accept) {\n\t\t\t\tif (handleInterestingCursor(cursor))\n\t\t\t\t\tCXChildVisitResult::CXChildVisit_Continue;\n\t\t\t}\n\t\t\treturn CXChildVisitResult::CXChildVisit_Recurse;\n\t\t},\n\t\tnullptr\n\t\t\t);\n\n\tclang_disposeTranslationUnit(unit);\n\n\tfor (auto&& type : g_reflected_types) {\n\t\tif (type.second.m_fields.empty()) {\n\t\t\ttype.second.generate_serialization = false;\n\t\t}\n\t}\n}\n","avg_line_length":33.798245614,"max_line_length":218,"alphanum_fraction":0.6704905269,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":24486,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["blessing"],"max_stars_count":354.0,"content":"\/***********************************************************************************************************************\n*  OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.\n*\n*  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n*  following conditions are met:\n*\n*  (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n*  disclaimer.\n*\n*  (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following\n*  disclaimer in the documentation and\/or other materials provided with the distribution.\n*\n*  (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products\n*  derived from this software without specific prior written permission from the respective party.\n*\n*  (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works\n*  may not use the \"OpenStudio\" trademark, \"OS\", \"os\", or any other confusingly similar designation without specific prior\n*  written permission from Alliance for Sustainable Energy, LLC.\n*\n*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n*  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED\n*  STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n*  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n*  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n*  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n*  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************************************************************\/\n\n#include \"ZoneMixing.hpp\"\n#include \"ZoneMixing_Impl.hpp\"\n\n#include \"ThermalZone.hpp\"\n#include \"ThermalZone_Impl.hpp\"\n#include \"Schedule.hpp\"\n#include \"Schedule_Impl.hpp\"\n#include \"ScheduleTypeLimits.hpp\"\n#include \"ScheduleTypeRegistry.hpp\"\n#include \"Model.hpp\"\n\n#include <utilities\/idd\/IddFactory.hxx>\n#include <utilities\/idd\/OS_ZoneMixing_FieldEnums.hxx>\n\n#include \"..\/utilities\/units\/Unit.hpp\"\n\n#include \"..\/utilities\/core\/Assert.hpp\"\n\nnamespace openstudio {\nnamespace model {\n\n  namespace detail {\n\n    ZoneMixing_Impl::ZoneMixing_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle)\n      : ModelObject_Impl(idfObject, model, keepHandle) {\n      OS_ASSERT(idfObject.iddObject().type() == ZoneMixing::iddObjectType());\n    }\n\n    ZoneMixing_Impl::ZoneMixing_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle)\n      : ModelObject_Impl(other, model, keepHandle) {\n      OS_ASSERT(other.iddObject().type() == ZoneMixing::iddObjectType());\n    }\n\n    ZoneMixing_Impl::ZoneMixing_Impl(const ZoneMixing_Impl& other, Model_Impl* model, bool keepHandle) : ModelObject_Impl(other, model, keepHandle) {}\n\n    const std::vector<std::string>& ZoneMixing_Impl::outputVariableNames() const {\n      static const std::vector<std::string> result{\n        \"Zone Mixing Volume\",\n        \"Zone Mixing Current Density Air Volume Flow Rate\",\n        \"Zone Mixing Standard Density Air Volume Flow Rate\",\n        \"Zone Mixing Mass\",\n        \"Zone Mixing Mass Flow Rate\",\n        \"Zone Mixing Sensible Heat Loss Energy\",\n        \"Zone Mixing Sensible Heat Gain Energy\",\n        \"Zone Mixing Latent Heat Loss Energy\",\n        \"Zone Mixing Latent Heat Gain Energy\",\n        \"Zone Mixing Total Heat Loss Energy\",\n        \"Zone Mixing Total Heat Gain Energy\"\n        \/\/ DLM: these are not working yet\n        \/\/ https:\/\/github.com\/NREL\/EnergyPlus\/issues\/5042\n        \/\/\"Zone Mixing Receiving Air Mass Flow Rate\",\n        \/\/\"Zone Mixing Source Air Mass Flow Rate\",\n      };\n      return result;\n    }\n\n    IddObjectType ZoneMixing_Impl::iddObjectType() const {\n      return ZoneMixing::iddObjectType();\n    }\n\n    std::vector<ScheduleTypeKey> ZoneMixing_Impl::getScheduleTypeKeys(const Schedule& schedule) const {\n      \/\/ TODO: Check schedule display names.\n      std::vector<ScheduleTypeKey> result;\n      UnsignedVector fieldIndices = getSourceIndices(schedule.handle());\n      UnsignedVector::const_iterator b(fieldIndices.begin()), e(fieldIndices.end());\n      if (std::find(b, e, OS_ZoneMixingFields::ScheduleName) != e) {\n        result.push_back(ScheduleTypeKey(\"ZoneMixing\", \"Zone Mixing\"));\n      }\n      if (std::find(b, e, OS_ZoneMixingFields::DeltaTemperatureScheduleName) != e) {\n        result.push_back(ScheduleTypeKey(\"ZoneMixing\", \"Delta Temperature\"));\n      }\n      if (std::find(b, e, OS_ZoneMixingFields::MinimumZoneTemperatureScheduleName) != e) {\n        result.push_back(ScheduleTypeKey(\"ZoneMixing\", \"Minimum Zone Temperature\"));\n      }\n      if (std::find(b, e, OS_ZoneMixingFields::MaximumZoneTemperatureScheduleName) != e) {\n        result.push_back(ScheduleTypeKey(\"ZoneMixing\", \"Maximum Zone Temperature\"));\n      }\n      if (std::find(b, e, OS_ZoneMixingFields::MinimumSourceZoneTemperatureScheduleName) != e) {\n        result.push_back(ScheduleTypeKey(\"ZoneMixing\", \"Minimum Source Zone Temperature\"));\n      }\n      if (std::find(b, e, OS_ZoneMixingFields::MaximumSourceZoneTemperatureScheduleName) != e) {\n        result.push_back(ScheduleTypeKey(\"ZoneMixing\", \"Maximum Source Zone Temperature\"));\n      }\n      if (std::find(b, e, OS_ZoneMixingFields::MinimumOutdoorTemperatureScheduleName) != e) {\n        result.push_back(ScheduleTypeKey(\"ZoneMixing\", \"Minimum Outdoor Temperature\"));\n      }\n      if (std::find(b, e, OS_ZoneMixingFields::MaximumOutdoorTemperatureScheduleName) != e) {\n        result.push_back(ScheduleTypeKey(\"ZoneMixing\", \"Maximum Outdoor Temperature\"));\n      }\n      return result;\n    }\n\n    ThermalZone ZoneMixing_Impl::zone() const {\n      boost::optional<ThermalZone> value = getObject<ModelObject>().getModelObjectTarget<ThermalZone>(OS_ZoneMixingFields::ZoneName);\n      if (!value) {\n        LOG_AND_THROW(briefDescription() << \" does not have a receiving ThermalZone.\");\n      }\n      return value.get();\n    }\n\n    Schedule ZoneMixing_Impl::schedule() const {\n      boost::optional<Schedule> value = getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_ZoneMixingFields::ScheduleName);\n      if (!value) {\n        LOG_AND_THROW(briefDescription() << \" does not have an Schedule attached.\");\n      }\n      return value.get();\n    }\n\n    std::string ZoneMixing_Impl::designFlowRateCalculationMethod() const {\n      boost::optional<std::string> value = getString(OS_ZoneMixingFields::DesignFlowRateCalculationMethod, true);\n      OS_ASSERT(value);\n      return value.get();\n    }\n\n    boost::optional<double> ZoneMixing_Impl::designFlowRate() const {\n      return getDouble(OS_ZoneMixingFields::DesignFlowRate, true);\n    }\n\n    boost::optional<double> ZoneMixing_Impl::flowRateperZoneFloorArea() const {\n      return getDouble(OS_ZoneMixingFields::FlowRateperZoneFloorArea, true);\n    }\n\n    boost::optional<double> ZoneMixing_Impl::flowRateperPerson() const {\n      return getDouble(OS_ZoneMixingFields::FlowRateperPerson, true);\n    }\n\n    boost::optional<double> ZoneMixing_Impl::airChangesperHour() const {\n      return getDouble(OS_ZoneMixingFields::AirChangesperHour, true);\n    }\n\n    boost::optional<ThermalZone> ZoneMixing_Impl::sourceZone() const {\n      return getObject<ModelObject>().getModelObjectTarget<ThermalZone>(OS_ZoneMixingFields::SourceZoneName);\n    }\n\n    boost::optional<double> ZoneMixing_Impl::deltaTemperature() const {\n      return getDouble(OS_ZoneMixingFields::DeltaTemperature);\n    }\n\n    boost::optional<Schedule> ZoneMixing_Impl::deltaTemperatureSchedule() const {\n      return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_ZoneMixingFields::DeltaTemperatureScheduleName);\n    }\n\n    boost::optional<Schedule> ZoneMixing_Impl::minimumZoneTemperatureSchedule() const {\n      return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_ZoneMixingFields::MinimumZoneTemperatureScheduleName);\n    }\n\n    boost::optional<Schedule> ZoneMixing_Impl::maximumZoneTemperatureSchedule() const {\n      return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_ZoneMixingFields::MaximumZoneTemperatureScheduleName);\n    }\n\n    boost::optional<Schedule> ZoneMixing_Impl::minimumSourceZoneTemperatureSchedule() const {\n      return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_ZoneMixingFields::MinimumSourceZoneTemperatureScheduleName);\n    }\n\n    boost::optional<Schedule> ZoneMixing_Impl::maximumSourceZoneTemperatureSchedule() const {\n      return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_ZoneMixingFields::MaximumSourceZoneTemperatureScheduleName);\n    }\n\n    boost::optional<Schedule> ZoneMixing_Impl::minimumOutdoorTemperatureSchedule() const {\n      return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_ZoneMixingFields::MinimumOutdoorTemperatureScheduleName);\n    }\n\n    boost::optional<Schedule> ZoneMixing_Impl::maximumOutdoorTemperatureSchedule() const {\n      return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_ZoneMixingFields::MaximumOutdoorTemperatureScheduleName);\n    }\n\n    bool ZoneMixing_Impl::setSchedule(Schedule& schedule) {\n      bool result = ModelObject_Impl::setSchedule(OS_ZoneMixingFields::ScheduleName, \"ZoneMixing\", \"Zone Mixing\", schedule);\n      return result;\n    }\n\n    bool ZoneMixing_Impl::setDesignFlowRate(double designFlowRate) {\n      bool result(false);\n      result = setDouble(OS_ZoneMixingFields::DesignFlowRate, designFlowRate);\n      if (result) {\n        result = setString(OS_ZoneMixingFields::DesignFlowRateCalculationMethod, \"Flow\/Zone\");\n        OS_ASSERT(result);\n        \/\/result = setString(OS_ZoneMixingFields::DesignFlowRate, \"\");\n        \/\/OS_ASSERT(result);\n        result = setString(OS_ZoneMixingFields::FlowRateperZoneFloorArea, \"\");\n        OS_ASSERT(result);\n        result = setString(OS_ZoneMixingFields::FlowRateperPerson, \"\");\n        OS_ASSERT(result);\n        result = setString(OS_ZoneMixingFields::AirChangesperHour, \"\");\n        OS_ASSERT(result);\n      }\n      return result;\n    }\n\n    bool ZoneMixing_Impl::setFlowRateperZoneFloorArea(double flowRateperZoneFloorArea) {\n      bool result(false);\n      result = setDouble(OS_ZoneMixingFields::FlowRateperZoneFloorArea, flowRateperZoneFloorArea);\n      if (result) {\n        result = setString(OS_ZoneMixingFields::DesignFlowRateCalculationMethod, \"Flow\/Area\");\n        OS_ASSERT(result);\n        result = setString(OS_ZoneMixingFields::DesignFlowRate, \"\");\n        OS_ASSERT(result);\n        \/\/result = setString(OS_ZoneMixingFields::FlowRateperZoneFloorArea, \"\");\n        \/\/OS_ASSERT(result);\n        result = setString(OS_ZoneMixingFields::FlowRateperPerson, \"\");\n        OS_ASSERT(result);\n        result = setString(OS_ZoneMixingFields::AirChangesperHour, \"\");\n        OS_ASSERT(result);\n      }\n      return result;\n    }\n\n    bool ZoneMixing_Impl::setFlowRateperPerson(double flowRateperPerson) {\n      bool result(false);\n      result = setDouble(OS_ZoneMixingFields::FlowRateperPerson, flowRateperPerson);\n      if (result) {\n        result = setString(OS_ZoneMixingFields::DesignFlowRateCalculationMethod, \"Flow\/Person\");\n        OS_ASSERT(result);\n        result = setString(OS_ZoneMixingFields::DesignFlowRate, \"\");\n        OS_ASSERT(result);\n        result = setString(OS_ZoneMixingFields::FlowRateperZoneFloorArea, \"\");\n        OS_ASSERT(result);\n        \/\/result = setString(OS_ZoneMixingFields::FlowRateperPerson, \"\");\n        \/\/OS_ASSERT(result);\n        result = setString(OS_ZoneMixingFields::AirChangesperHour, \"\");\n        OS_ASSERT(result);\n      }\n      return result;\n    }\n\n    bool ZoneMixing_Impl::setAirChangesperHour(double airChangesperHour) {\n      bool result(false);\n      result = setDouble(OS_ZoneMixingFields::AirChangesperHour, airChangesperHour);\n      if (result) {\n        result = setString(OS_ZoneMixingFields::DesignFlowRateCalculationMethod, \"AirChanges\/Hour\");\n        OS_ASSERT(result);\n        result = setString(OS_ZoneMixingFields::DesignFlowRate, \"\");\n        OS_ASSERT(result);\n        result = setString(OS_ZoneMixingFields::FlowRateperZoneFloorArea, \"\");\n        OS_ASSERT(result);\n        result = setString(OS_ZoneMixingFields::FlowRateperPerson, \"\");\n        OS_ASSERT(result);\n        \/\/result = setString(OS_ZoneMixingFields::AirChangesperHour, \"\");\n        \/\/OS_ASSERT(result);\n      }\n      return result;\n    }\n\n    bool ZoneMixing_Impl::setSourceZone(const ThermalZone& zone) {\n      bool result(false);\n\n      \/\/ source zone cannot be the same as this zone\n      if (zone.handle() != this->zone().handle()) {\n        result = setPointer(OS_ZoneMixingFields::SourceZoneName, zone.handle());\n      }\n      return result;\n    }\n\n    void ZoneMixing_Impl::resetSourceZone() {\n      bool result = setString(OS_ZoneMixingFields::SourceZoneName, \"\");\n      OS_ASSERT(result);\n    }\n\n    bool ZoneMixing_Impl::setDeltaTemperature(double deltaTemperature) {\n      bool result = setDouble(OS_ZoneMixingFields::DeltaTemperature, deltaTemperature);\n      OS_ASSERT(result);\n      resetDeltaTemperatureSchedule();\n      return result;\n    }\n\n    void ZoneMixing_Impl::resetDeltaTemperature() {\n      bool result = setString(OS_ZoneMixingFields::DeltaTemperature, \"\");\n      OS_ASSERT(result);\n    }\n\n    bool ZoneMixing_Impl::setDeltaTemperatureSchedule(Schedule& schedule) {\n      bool result = ModelObject_Impl::setSchedule(OS_ZoneMixingFields::DeltaTemperatureScheduleName, \"ZoneMixing\", \"Delta Temperature\", schedule);\n      if (result) {\n        resetDeltaTemperature();\n      }\n      return result;\n    }\n\n    void ZoneMixing_Impl::resetDeltaTemperatureSchedule() {\n      bool result = setString(OS_ZoneMixingFields::DeltaTemperatureScheduleName, \"\");\n      OS_ASSERT(result);\n    }\n\n    bool ZoneMixing_Impl::setMinimumZoneTemperatureSchedule(Schedule& schedule) {\n      bool result =\n        ModelObject_Impl::setSchedule(OS_ZoneMixingFields::MinimumZoneTemperatureScheduleName, \"ZoneMixing\", \"Minimum Zone Temperature\", schedule);\n      return result;\n    }\n\n    void ZoneMixing_Impl::resetMinimumZoneTemperatureSchedule() {\n      bool result = setString(OS_ZoneMixingFields::MinimumZoneTemperatureScheduleName, \"\");\n      OS_ASSERT(result);\n    }\n\n    bool ZoneMixing_Impl::setMaximumZoneTemperatureSchedule(Schedule& schedule) {\n      bool result =\n        ModelObject_Impl::setSchedule(OS_ZoneMixingFields::MaximumZoneTemperatureScheduleName, \"ZoneMixing\", \"Maximum Zone Temperature\", schedule);\n      return result;\n    }\n\n    void ZoneMixing_Impl::resetMaximumZoneTemperatureSchedule() {\n      bool result = setString(OS_ZoneMixingFields::MaximumZoneTemperatureScheduleName, \"\");\n      OS_ASSERT(result);\n    }\n\n    bool ZoneMixing_Impl::setMinimumSourceZoneTemperatureSchedule(Schedule& schedule) {\n      bool result = ModelObject_Impl::setSchedule(OS_ZoneMixingFields::MinimumSourceZoneTemperatureScheduleName, \"ZoneMixing\",\n                                                  \"Minimum Source Zone Temperature\", schedule);\n      return result;\n    }\n\n    void ZoneMixing_Impl::resetMinimumSourceZoneTemperatureSchedule() {\n      bool result = setString(OS_ZoneMixingFields::MinimumSourceZoneTemperatureScheduleName, \"\");\n      OS_ASSERT(result);\n    }\n\n    bool ZoneMixing_Impl::setMaximumSourceZoneTemperatureSchedule(Schedule& schedule) {\n      bool result = ModelObject_Impl::setSchedule(OS_ZoneMixingFields::MaximumSourceZoneTemperatureScheduleName, \"ZoneMixing\",\n                                                  \"Maximum Source Zone Temperature\", schedule);\n      return result;\n    }\n\n    void ZoneMixing_Impl::resetMaximumSourceZoneTemperatureSchedule() {\n      bool result = setString(OS_ZoneMixingFields::MaximumSourceZoneTemperatureScheduleName, \"\");\n      OS_ASSERT(result);\n    }\n\n    bool ZoneMixing_Impl::setMinimumOutdoorTemperatureSchedule(Schedule& schedule) {\n      bool result = ModelObject_Impl::setSchedule(OS_ZoneMixingFields::MinimumOutdoorTemperatureScheduleName, \"ZoneMixing\",\n                                                  \"Minimum Outdoor Temperature\", schedule);\n      return result;\n    }\n\n    void ZoneMixing_Impl::resetMinimumOutdoorTemperatureSchedule() {\n      bool result = setString(OS_ZoneMixingFields::MinimumOutdoorTemperatureScheduleName, \"\");\n      OS_ASSERT(result);\n    }\n\n    bool ZoneMixing_Impl::setMaximumOutdoorTemperatureSchedule(Schedule& schedule) {\n      bool result = ModelObject_Impl::setSchedule(OS_ZoneMixingFields::MaximumOutdoorTemperatureScheduleName, \"ZoneMixing\",\n                                                  \"Maximum Outdoor Temperature\", schedule);\n      return result;\n    }\n\n    void ZoneMixing_Impl::resetMaximumOutdoorTemperatureSchedule() {\n      bool result = setString(OS_ZoneMixingFields::MaximumOutdoorTemperatureScheduleName, \"\");\n      OS_ASSERT(result);\n    }\n\n    std::vector<EMSActuatorNames> ZoneMixing_Impl::emsActuatorNames() const {\n      std::vector<EMSActuatorNames> actuators{{\"ZoneMixing\", \"Air Exchange Flow Rate\"}};\n      return actuators;\n    }\n\n    std::vector<std::string> ZoneMixing_Impl::emsInternalVariableNames() const {\n      std::vector<std::string> types;\n      return types;\n    }\n  }  \/\/ namespace detail\n\n  ZoneMixing::ZoneMixing(const ThermalZone& zone) : ModelObject(ZoneMixing::iddObjectType(), zone.model()) {\n    OS_ASSERT(getImpl<detail::ZoneMixing_Impl>());\n\n    bool ok = setPointer(OS_ZoneMixingFields::ZoneName, zone.handle());\n    OS_ASSERT(ok);\n\n    ok = setPointer(OS_ZoneMixingFields::ScheduleName, zone.model().alwaysOnContinuousSchedule().handle());\n    OS_ASSERT(ok);\n\n    ok = setDesignFlowRate(0.0);\n    OS_ASSERT(ok);\n  }\n\n  IddObjectType ZoneMixing::iddObjectType() {\n    return IddObjectType(IddObjectType::OS_ZoneMixing);\n  }\n\n  ThermalZone ZoneMixing::zone() const {\n    return getImpl<detail::ZoneMixing_Impl>()->zone();\n  }\n\n  Schedule ZoneMixing::schedule() const {\n    return getImpl<detail::ZoneMixing_Impl>()->schedule();\n  }\n\n  std::string ZoneMixing::designFlowRateCalculationMethod() const {\n    return getImpl<detail::ZoneMixing_Impl>()->designFlowRateCalculationMethod();\n  }\n\n  boost::optional<double> ZoneMixing::designFlowRate() const {\n    return getImpl<detail::ZoneMixing_Impl>()->designFlowRate();\n  }\n\n  boost::optional<double> ZoneMixing::flowRateperZoneFloorArea() const {\n    return getImpl<detail::ZoneMixing_Impl>()->flowRateperZoneFloorArea();\n  }\n\n  boost::optional<double> ZoneMixing::flowRateperPerson() const {\n    return getImpl<detail::ZoneMixing_Impl>()->flowRateperPerson();\n  }\n\n  boost::optional<double> ZoneMixing::airChangesperHour() const {\n    return getImpl<detail::ZoneMixing_Impl>()->airChangesperHour();\n  }\n\n  boost::optional<ThermalZone> ZoneMixing::sourceZone() const {\n    return getImpl<detail::ZoneMixing_Impl>()->sourceZone();\n  }\n\n  boost::optional<double> ZoneMixing::deltaTemperature() const {\n    return getImpl<detail::ZoneMixing_Impl>()->deltaTemperature();\n  }\n\n  boost::optional<Schedule> ZoneMixing::deltaTemperatureSchedule() const {\n    return getImpl<detail::ZoneMixing_Impl>()->deltaTemperatureSchedule();\n  }\n\n  boost::optional<Schedule> ZoneMixing::minimumZoneTemperatureSchedule() const {\n    return getImpl<detail::ZoneMixing_Impl>()->minimumZoneTemperatureSchedule();\n  }\n\n  boost::optional<Schedule> ZoneMixing::maximumZoneTemperatureSchedule() const {\n    return getImpl<detail::ZoneMixing_Impl>()->maximumZoneTemperatureSchedule();\n  }\n\n  boost::optional<Schedule> ZoneMixing::minimumSourceZoneTemperatureSchedule() const {\n    return getImpl<detail::ZoneMixing_Impl>()->minimumSourceZoneTemperatureSchedule();\n  }\n\n  boost::optional<Schedule> ZoneMixing::maximumSourceZoneTemperatureSchedule() const {\n    return getImpl<detail::ZoneMixing_Impl>()->maximumSourceZoneTemperatureSchedule();\n  }\n\n  boost::optional<Schedule> ZoneMixing::minimumOutdoorTemperatureSchedule() const {\n    return getImpl<detail::ZoneMixing_Impl>()->minimumOutdoorTemperatureSchedule();\n  }\n\n  boost::optional<Schedule> ZoneMixing::maximumOutdoorTemperatureSchedule() const {\n    return getImpl<detail::ZoneMixing_Impl>()->maximumOutdoorTemperatureSchedule();\n  }\n\n  bool ZoneMixing::setSchedule(Schedule& schedule) {\n    return getImpl<detail::ZoneMixing_Impl>()->setSchedule(schedule);\n  }\n\n  bool ZoneMixing::setDesignFlowRate(double designFlowRate) {\n    return getImpl<detail::ZoneMixing_Impl>()->setDesignFlowRate(designFlowRate);\n  }\n\n  bool ZoneMixing::setFlowRateperZoneFloorArea(double flowRateperZoneFloorArea) {\n    return getImpl<detail::ZoneMixing_Impl>()->setFlowRateperZoneFloorArea(flowRateperZoneFloorArea);\n  }\n\n  bool ZoneMixing::setFlowRateperPerson(double flowRateperPerson) {\n    return getImpl<detail::ZoneMixing_Impl>()->setFlowRateperPerson(flowRateperPerson);\n  }\n\n  bool ZoneMixing::setAirChangesperHour(double airChangesperHour) {\n    return getImpl<detail::ZoneMixing_Impl>()->setAirChangesperHour(airChangesperHour);\n  }\n\n  bool ZoneMixing::setSourceZone(const ThermalZone& zone) {\n    return getImpl<detail::ZoneMixing_Impl>()->setSourceZone(zone);\n  }\n\n  void ZoneMixing::resetSourceZone() {\n    getImpl<detail::ZoneMixing_Impl>()->resetSourceZone();\n  }\n\n  bool ZoneMixing::setDeltaTemperature(double deltaTemperature) {\n    return getImpl<detail::ZoneMixing_Impl>()->setDeltaTemperature(deltaTemperature);\n  }\n\n  void ZoneMixing::resetDeltaTemperature() {\n    getImpl<detail::ZoneMixing_Impl>()->resetDeltaTemperature();\n  }\n\n  bool ZoneMixing::setDeltaTemperatureSchedule(Schedule& schedule) {\n    return getImpl<detail::ZoneMixing_Impl>()->setDeltaTemperatureSchedule(schedule);\n  }\n\n  void ZoneMixing::resetDeltaTemperatureSchedule() {\n    getImpl<detail::ZoneMixing_Impl>()->resetDeltaTemperatureSchedule();\n  }\n\n  bool ZoneMixing::setMinimumZoneTemperatureSchedule(Schedule& schedule) {\n    return getImpl<detail::ZoneMixing_Impl>()->setMinimumZoneTemperatureSchedule(schedule);\n  }\n\n  void ZoneMixing::resetMinimumZoneTemperatureSchedule() {\n    getImpl<detail::ZoneMixing_Impl>()->resetMinimumZoneTemperatureSchedule();\n  }\n\n  bool ZoneMixing::setMaximumZoneTemperatureSchedule(Schedule& schedule) {\n    return getImpl<detail::ZoneMixing_Impl>()->setMaximumZoneTemperatureSchedule(schedule);\n  }\n\n  void ZoneMixing::resetMaximumZoneTemperatureSchedule() {\n    getImpl<detail::ZoneMixing_Impl>()->resetMaximumZoneTemperatureSchedule();\n  }\n\n  bool ZoneMixing::setMinimumSourceZoneTemperatureSchedule(Schedule& schedule) {\n    return getImpl<detail::ZoneMixing_Impl>()->setMinimumSourceZoneTemperatureSchedule(schedule);\n  }\n\n  void ZoneMixing::resetMinimumSourceZoneTemperatureSchedule() {\n    getImpl<detail::ZoneMixing_Impl>()->resetMinimumSourceZoneTemperatureSchedule();\n  }\n\n  bool ZoneMixing::setMaximumSourceZoneTemperatureSchedule(Schedule& schedule) {\n    return getImpl<detail::ZoneMixing_Impl>()->setMaximumSourceZoneTemperatureSchedule(schedule);\n  }\n\n  void ZoneMixing::resetMaximumSourceZoneTemperatureSchedule() {\n    getImpl<detail::ZoneMixing_Impl>()->resetMaximumSourceZoneTemperatureSchedule();\n  }\n\n  bool ZoneMixing::setMinimumOutdoorTemperatureSchedule(Schedule& schedule) {\n    return getImpl<detail::ZoneMixing_Impl>()->setMinimumOutdoorTemperatureSchedule(schedule);\n  }\n\n  void ZoneMixing::resetMinimumOutdoorTemperatureSchedule() {\n    getImpl<detail::ZoneMixing_Impl>()->resetMinimumOutdoorTemperatureSchedule();\n  }\n\n  bool ZoneMixing::setMaximumOutdoorTemperatureSchedule(Schedule& schedule) {\n    return getImpl<detail::ZoneMixing_Impl>()->setMaximumOutdoorTemperatureSchedule(schedule);\n  }\n\n  void ZoneMixing::resetMaximumOutdoorTemperatureSchedule() {\n    getImpl<detail::ZoneMixing_Impl>()->resetMaximumOutdoorTemperatureSchedule();\n  }\n\n  \/\/\/ @cond\n  ZoneMixing::ZoneMixing(std::shared_ptr<detail::ZoneMixing_Impl> impl) : ModelObject(std::move(impl)) {}\n  \/\/\/ @endcond\n\n}  \/\/ namespace model\n}  \/\/ namespace openstudio\n","avg_line_length":43.0333919156,"max_line_length":150,"alphanum_fraction":0.7253941028,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4538,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2015 - 2020 Jean Wallet\n\/\/ Copyright (c) 2015 - 2020 The AYCHDeveloper\n\/\/ Distributed under the MIT software license, the AGPL-3.0 or later, see the accompanying\n\/\/ file LICENSE or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\/\/ file LICENSE or https:\/\/www.gnu.org\/licenses.\n\n#include <bench\/bench.h>\n\n#include <assert.h>\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <regex>\n#include <numeric>\n\nvoid benchmark::ConsolePrinter::header()\n{\n    std::cout << \"# Benchmark, evals, iterations, total, min, max, median\" << std::endl;\n}\n\nvoid benchmark::ConsolePrinter::result(const State& state)\n{\n    auto results = state.m_elapsed_results;\n    std::sort(results.begin(), results.end());\n\n    double total = state.m_num_iters * std::accumulate(results.begin(), results.end(), 0.0);\n\n    double front = 0;\n    double back = 0;\n    double median = 0;\n\n    if (!results.empty()) {\n        front = results.front();\n        back = results.back();\n\n        size_t mid = results.size() \/ 2;\n        median = results[mid];\n        if (0 == results.size() % 2) {\n            median = (results[mid] + results[mid + 1]) \/ 2;\n        }\n    }\n\n    std::cout << std::setprecision(6);\n    std::cout << state.m_name << \", \" << state.m_num_evals << \", \" << state.m_num_iters << \", \" << total << \", \" << front << \", \" << back << \", \" << median << std::endl;\n}\n\nvoid benchmark::ConsolePrinter::footer() {}\nbenchmark::PlotlyPrinter::PlotlyPrinter(std::string plotly_url, int64_t width, int64_t height)\n    : m_plotly_url(plotly_url), m_width(width), m_height(height)\n{\n}\n\nvoid benchmark::PlotlyPrinter::header()\n{\n    std::cout << \"<html><head>\"\n              << \"<script src=\\\"\" << m_plotly_url << \"\\\"><\/script>\"\n              << \"<\/head><body><div id=\\\"myDiv\\\" style=\\\"width:\" << m_width << \"px; height:\" << m_height << \"px\\\"><\/div>\"\n              << \"<script> var data = [\"\n              << std::endl;\n}\n\nvoid benchmark::PlotlyPrinter::result(const State& state)\n{\n    std::cout << \"{ \" << std::endl\n              << \"  name: '\" << state.m_name << \"', \" << std::endl\n              << \"  y: [\";\n\n    const char* prefix = \"\";\n    for (const auto& e : state.m_elapsed_results) {\n        std::cout << prefix << std::setprecision(6) << e;\n        prefix = \", \";\n    }\n    std::cout << \"],\" << std::endl\n              << \"  boxpoints: 'all', jitter: 0.3, pointpos: 0, type: 'box',\"\n              << std::endl\n              << \"},\" << std::endl;\n}\n\nvoid benchmark::PlotlyPrinter::footer()\n{\n    std::cout << \"]; var layout = { showlegend: false, yaxis: { rangemode: 'tozero', autorange: true } };\"\n              << \"Plotly.newPlot('myDiv', data, layout);\"\n              << \"<\/script><\/body><\/html>\";\n}\n\n\nbenchmark::BenchRunner::BenchmarkMap& benchmark::BenchRunner::benchmarks()\n{\n    static std::map<std::string, Bench> benchmarks_map;\n    return benchmarks_map;\n}\n\nbenchmark::BenchRunner::BenchRunner(std::string name, benchmark::BenchFunction func, uint64_t num_iters_for_one_second)\n{\n    benchmarks().insert(std::make_pair(name, Bench{func, num_iters_for_one_second}));\n}\n\nvoid benchmark::BenchRunner::RunAll(Printer& printer, uint64_t num_evals, double scaling, const std::string& filter, bool is_list_only)\n{\n    if (!std::ratio_less_equal<benchmark::clock::period, std::micro>::value) {\n        std::cerr << \"WARNING: Clock precision is worse than microsecond - benchmarks may be less accurate!\\n\";\n    }\n#ifdef DEBUG\n    std::cerr << \"WARNING: This is a debug build - may result in slower benchmarks.\\n\";\n#endif\n\n    std::regex reFilter(filter);\n    std::smatch baseMatch;\n\n    printer.header();\n\n    for (const auto& p : benchmarks()) {\n        if (!std::regex_match(p.first, baseMatch, reFilter)) {\n            continue;\n        }\n\n        uint64_t num_iters = static_cast<uint64_t>(p.second.num_iters_for_one_second * scaling);\n        if (0 == num_iters) {\n            num_iters = 1;\n        }\n        State state(p.first, num_evals, num_iters, printer);\n        if (!is_list_only) {\n            p.second.func(state);\n        }\n        printer.result(state);\n    }\n\n    printer.footer();\n}\n\nbool benchmark::State::UpdateTimer(const benchmark::time_point current_time)\n{\n    if (m_start_time != time_point()) {\n        std::chrono::duration<double> diff = current_time - m_start_time;\n        m_elapsed_results.push_back(diff.count() \/ m_num_iters);\n\n        if (m_elapsed_results.size() == m_num_evals) {\n            return false;\n        }\n    }\n\n    m_num_iters_left = m_num_iters - 1;\n    return true;\n}\n","avg_line_length":31.2965517241,"max_line_length":169,"alphanum_fraction":0.6007051565,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6054,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"rpcserver.h\"\n#include \"rpcclient.h\"\n#include \"init.h\"\n#include \"main.h\"\n#include \"noui.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/filesystem.hpp>\n\n\/* Introduction text for doxygen: *\/\n\n\/*! \\mainpage Developer documentation\n *\n * \\section intro_sec Introduction\n *\n * This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin (http:\/\/www.bitcoin.org\/),\n * which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate\n * with no central authority: managing transactions and issuing money are carried out collectively by the network.\n *\n * The software is a community-driven open source project, released under the MIT license.\n *\n * \\section Navigation\n * Use the buttons <code>Namespaces<\/code>, <code>Classes<\/code> or <code>Files<\/code> at the top of the page to start navigating the code.\n *\/\n\nstatic bool fDaemon;\n\nvoid DetectShutdownThread(boost::thread_group* threadGroup)\n{\n    bool fShutdown = ShutdownRequested();\n    \/\/ Tell the main threads to shutdown.\n    while (!fShutdown)\n    {\n        MilliSleep(200);\n        fShutdown = ShutdownRequested();\n    }\n    if (threadGroup)\n    {\n        threadGroup->interrupt_all();\n        threadGroup->join_all();\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Start\n\/\/\nbool AppInit(int argc, char* argv[])\n{\n    boost::thread_group threadGroup;\n    boost::thread* detectShutdownThread = NULL;\n\n    bool fRet = false;\n    try\n    {\n        \/\/\n        \/\/ Parameters\n        \/\/\n        \/\/ If Qt is used, parameters\/bitcoin.conf are parsed in qt\/bitcoin.cpp's main()\n        ParseParameters(argc, argv);\n        if (!boost::filesystem::is_directory(GetDataDir(false)))\n        {\n            fprintf(stderr, \"Error: Specified data directory \\\"%s\\\" does not exist.\\n\", mapArgs[\"-datadir\"].c_str());\n            return false;\n        }\n        try\n        {\n            ReadConfigFile(mapArgs, mapMultiArgs);\n        } catch(std::exception &e) {\n            fprintf(stderr,\"Error reading configuration file: %s\\n\", e.what());\n            return false;\n        }\n        \/\/ Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause)\n        if (!SelectParamsFromCommandLine()) {\n            fprintf(stderr, \"Error: Invalid combination of -regtest and -testnet.\\n\");\n            return false;\n        }\n\n        if (mapArgs.count(\"-?\") || mapArgs.count(\"--help\"))\n        {\n            \/\/ First part of help message is specific to bitcoind \/ RPC client\n            std::string strUsage = _(\"Blood Core Daemon\") + \" \" + _(\"version\") + \" \" + FormatFullVersion() + \"\\n\\n\" +\n                _(\"Usage:\") + \"\\n\" +\n                  \"  bloodd [options]                     \" + _(\"Start Blood Core Daemon\") + \"\\n\" +\n                _(\"Usage (deprecated, use blood-cli):\") + \"\\n\" +\n                  \"  bloodd [options] <command> [params]  \" + _(\"Send command to Blood Core\") + \"\\n\" +\n                  \"  bloodd [options] help                \" + _(\"List commands\") + \"\\n\" +\n                  \"  bloodd [options] help <command>      \" + _(\"Get help for a command\") + \"\\n\";\n\n            strUsage += \"\\n\" + HelpMessage(HMM_BITCOIND);\n            strUsage += \"\\n\" + HelpMessageCli(false);\n\n            fprintf(stdout, \"%s\", strUsage.c_str());\n            return false;\n        }\n\n        \/\/ Command-line RPC\n        bool fCommandLine = false;\n        for (int i = 1; i < argc; i++)\n            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], \"blood:\"))\n                fCommandLine = true;\n\n        if (fCommandLine)\n        {\n            int ret = CommandLineRPC(argc, argv);\n            exit(ret);\n        }\n#ifndef WIN32\n        fDaemon = GetBoolArg(\"-daemon\", false);\n        if (fDaemon)\n        {\n            fprintf(stdout, \"Blood server starting\\n\");\n\n            \/\/ Daemonize\n            pid_t pid = fork();\n            if (pid < 0)\n            {\n                fprintf(stderr, \"Error: fork() returned %d errno %d\\n\", pid, errno);\n                return false;\n            }\n            if (pid > 0) \/\/ Parent process, pid is child process id\n            {\n                CreatePidFile(GetPidFile(), pid);\n                return true;\n            }\n            \/\/ Child process falls through to rest of initialization\n\n            pid_t sid = setsid();\n            if (sid < 0)\n                fprintf(stderr, \"Error: setsid() returned %d errno %d\\n\", sid, errno);\n        }\n#endif\n        SoftSetBoolArg(\"-server\", true);\n\n        detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));\n        fRet = AppInit2(threadGroup);\n    }\n    catch (std::exception& e) {\n        PrintExceptionContinue(&e, \"AppInit()\");\n    } catch (...) {\n        PrintExceptionContinue(NULL, \"AppInit()\");\n    }\n\n    if (!fRet)\n    {\n        if (detectShutdownThread)\n            detectShutdownThread->interrupt();\n\n        threadGroup.interrupt_all();\n        \/\/ threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of\n        \/\/ the startup-failure cases to make sure they don't result in a hang due to some\n        \/\/ thread-blocking-waiting-for-another-thread-during-startup case\n    }\n\n    if (detectShutdownThread)\n    {\n        detectShutdownThread->join();\n        delete detectShutdownThread;\n        detectShutdownThread = NULL;\n    }\n    Shutdown();\n\n    return fRet;\n}\n\nint main(int argc, char* argv[])\n{\n    SetupEnvironment();\n\n    bool fRet = false;\n\n    \/\/ Connect bitcoind signal handlers\n    noui_connect();\n\n    fRet = AppInit(argc, argv);\n\n    if (fRet && fDaemon)\n        return 0;\n\n    return (fRet ? 0 : 1);\n}\n","avg_line_length":32.0317460317,"max_line_length":145,"alphanum_fraction":0.5730095804,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":35673,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":8.0,"content":"\/\/------------------------------------------------------------------------------\r\n\/\/ File: Windowless.cpp\r\n\/\/\r\n\/\/ Desc: DirectShow sample code - a simple Windowless VMR media file player\r\n\/\/\r\n\/\/ Copyright (c) Microsoft Corporation.  All rights reserved.\r\n\/\/------------------------------------------------------------------------------\r\n\r\n#include <tchar.h>\r\n#include <dshow.h>\r\n#include <shellapi.h>\r\n#include <commctrl.h>\r\n#include <commdlg.h>\r\n#include <stdio.h>\r\n\r\n#include <d3d9.h>\r\n#include <vmr9.h>\r\n\r\n#include \"windowless.h\"\r\n\r\n\/\/ Common files\r\n#include \"smartptr.h\"\r\n#include \"dshowutil.h\"\r\n\r\n\/\/ An application can advertise the existence of its filter graph\r\n\/\/ by registering the graph with a global Running Object Table (ROT).\r\n\/\/ The GraphEdit application can detect and remotely view the running\r\n\/\/ filter graph, allowing you to 'spy' on the graph with GraphEdit.\r\n\/\/\r\n\/\/ To enable registration in this sample, define REGISTER_FILTERGRAPH.\r\n\/\/\r\n#define REGISTER_FILTERGRAPH\r\n\r\n\/\/\r\n\/\/ Global data\r\n\/\/\r\nHWND      ghApp=0;\r\nHMENU     ghMenu=0;\r\nHINSTANCE ghInst=0;\r\nTCHAR     g_szFileName[MAX_PATH]={0};\r\nBOOL      g_bAudioOnly=FALSE;\r\nLONG      g_lVolume=VOLUME_FULL;\r\nDWORD     g_dwGraphRegister=0;\r\nPLAYSTATE g_psCurrent=Stopped;\r\ndouble    g_PlaybackRate=1.0;\r\nRECT      g_rcDest={0};\r\n\r\n\/\/ DirectShow interfaces\r\nIGraphBuilder *pGB = NULL;\r\nIMediaControl *pMC = NULL;\r\nIMediaEventEx *pME = NULL;\r\nIBasicAudio   *pBA = NULL;\r\nIMediaSeeking *pMS = NULL;\r\nIMediaPosition *pMP = NULL;\r\nIVideoFrameStep *pFS = NULL;\r\n\r\n\/\/ VMR9 interfaces\r\nIVMRWindowlessControl9 *pWC = NULL;\r\n\r\nconst int AUDIO=1, VIDEO=2; \/\/ Used for enabling playback menu items\r\n\r\n\r\nHRESULT PlayMovieInWindow(LPTSTR szFile)\r\n{\r\n    HRESULT hr;\r\n\r\n    \/\/ Check input string\r\n    if (szFile == NULL)\r\n        return E_POINTER;\r\n\r\n    \/\/ Clear open dialog remnants before calling RenderFile()\r\n    UpdateWindow(ghApp);\r\n\r\n    \/\/ Get the interface for DirectShow's GraphBuilder\r\n    JIF(CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,\r\n                         IID_IGraphBuilder, (void **)&pGB));\r\n\r\n    if(SUCCEEDED(hr))\r\n    {\r\n        SmartPtr <IBaseFilter> pVmr;\r\n\r\n        \/\/ Create the Video Mixing Renderer and add it to the graph\r\n        JIF(InitializeWindowlessVMR(&pVmr));\r\n\r\n        \/\/ Render the file programmatically to use the VMR9 as renderer.\r\n        \/\/ Pass TRUE to create an audio renderer also.\r\n        if (FAILED(hr = RenderFileToVideoRenderer(pGB, szFile, TRUE)))\r\n            return hr;\r\n\r\n        \/\/ QueryInterface for DirectShow interfaces\r\n        JIF(pGB->QueryInterface(IID_IMediaControl, (void **)&pMC));\r\n        JIF(pGB->QueryInterface(IID_IMediaEventEx, (void **)&pME));\r\n        JIF(pGB->QueryInterface(IID_IMediaSeeking, (void **)&pMS));\r\n        JIF(pGB->QueryInterface(IID_IMediaPosition, (void **)&pMP));\r\n        JIF(pGB->QueryInterface(IID_IBasicAudio, (void **)&pBA));\r\n\r\n        \/\/ Is this an audio-only file (no video component)?\r\n        CheckVisibility();\r\n\r\n        \/\/ Have the graph signal event via window callbacks for performance\r\n        JIF(pME->SetNotifyWindow((OAHWND)ghApp, WM_GRAPHNOTIFY, 0));\r\n\r\n        if (!g_bAudioOnly)\r\n        {\r\n            JIF(InitVideoWindow(1, 1));\r\n            GetFrameStepInterface();\r\n        }\r\n        else\r\n        {\r\n            JIF(InitPlayerWindow());\r\n            EnablePlaybackMenu(TRUE, AUDIO);\r\n        }\r\n\r\n        \/\/ Complete initialization\r\n        CheckSizeMenu(ID_FILE_SIZE_NORMAL);\r\n        ShowWindow(ghApp, SW_SHOWNORMAL);\r\n        UpdateWindow(ghApp);\r\n        SetForegroundWindow(ghApp);\r\n        SetFocus(ghApp);\r\n\r\n        g_PlaybackRate = 1.0;\r\n        UpdateMainTitle();\r\n\r\n#ifdef REGISTER_FILTERGRAPH\r\n        hr = AddGraphToRot(pGB, &g_dwGraphRegister);\r\n        if (FAILED(hr))\r\n        {\r\n            Msg(TEXT(\"Failed to register filter graph with ROT!  hr=0x%x\"), hr);\r\n            g_dwGraphRegister = 0;\r\n        }\r\n#endif\r\n\r\n        \/\/ Run the graph to play the media file\r\n        JIF(pMC->Run());\r\n        g_psCurrent=Running;\r\n\r\n        SetFocus(ghApp);\r\n    }\r\n\r\n    return hr;\r\n}\r\n\r\n\r\nHRESULT InitVideoWindow(int nMultiplier, int nDivider)\r\n{\r\n    LONG lHeight, lWidth;\r\n    HRESULT hr = S_OK;\r\n\r\n    if (!pWC)\r\n        return S_OK;\r\n\r\n    \/\/ Read the default video size\r\n    hr = pWC->GetNativeVideoSize(&lWidth, &lHeight, NULL, NULL);\r\n    if (hr == E_NOINTERFACE)\r\n        return S_OK;\r\n\r\n    EnablePlaybackMenu(TRUE, VIDEO);\r\n\r\n    \/\/ Account for requests of normal, half, or double size\r\n    lWidth  = lWidth  * nMultiplier \/ nDivider;\r\n    lHeight = lHeight * nMultiplier \/ nDivider;\r\n\r\n    int nTitleHeight  = GetSystemMetrics(SM_CYCAPTION);\r\n    int nBorderWidth  = GetSystemMetrics(SM_CXBORDER);\r\n    int nBorderHeight = GetSystemMetrics(SM_CYBORDER);\r\n\r\n    \/\/ Account for size of title bar and borders for exact match\r\n    \/\/ of window client area to default video size\r\n    SetWindowPos(ghApp, NULL, 0, 0, lWidth + 2*nBorderWidth,\r\n                 lHeight + nTitleHeight + 2*nBorderHeight,\r\n                 SWP_NOMOVE | SWP_NOOWNERZORDER);\r\n\r\n    GetClientRect(ghApp, &g_rcDest);\r\n    hr = pWC->SetVideoPosition(NULL, &g_rcDest);\r\n\r\n    return hr;\r\n}\r\n\r\n\r\nHRESULT InitPlayerWindow(void)\r\n{\r\n    \/\/ Reset to a default size for audio and after closing a clip\r\n    SetWindowPos(ghApp, NULL, 0, 0,\r\n                 DEFAULT_AUDIO_WIDTH,\r\n                 DEFAULT_AUDIO_HEIGHT,\r\n                 SWP_NOMOVE | SWP_NOOWNERZORDER);\r\n\r\n    \/\/ Check the 'full size' menu item\r\n    CheckSizeMenu(ID_FILE_SIZE_NORMAL);\r\n    EnablePlaybackMenu(FALSE, 0);\r\n\r\n    return S_OK;\r\n}\r\n\r\n\r\nvoid MoveVideoWindow(void)\r\n{\r\n    HRESULT hr;\r\n\r\n    \/\/ Track the movement of the container window and resize as needed\r\n    if(pWC)\r\n    {\r\n        GetClientRect(ghApp, &g_rcDest);\r\n        hr = pWC->SetVideoPosition(NULL, &g_rcDest);\r\n    }\r\n}\r\n\r\n\r\nvoid CheckVisibility(void)\r\n{\r\n    HRESULT hr;\r\n\r\n    \/\/ Clear the global flag\r\n    g_bAudioOnly = FALSE;\r\n\r\n    \/\/\r\n    \/\/ Because this sample explicitly loads the VMR9 into the filter graph\r\n    \/\/ before rendering a file, the IVMRWindowlessControl interface will exist\r\n    \/\/ for all properly rendered files.  As a result, we can't depend on the\r\n    \/\/ existence of the pWC interface to determine whether the media file has\r\n    \/\/ a video component.  Instead, check the width and height values.\r\n    \/\/\r\n    if (pWC)\r\n    {\r\n        LONG lWidth=0, lHeight=0;\r\n\r\n        hr = pWC->GetNativeVideoSize(&lWidth, &lHeight, 0, 0);\r\n        if (hr == E_NOINTERFACE)\r\n        {\r\n            \/\/ If this video is encoded with an unsupported codec,\r\n            \/\/ we won't see any video, although the audio will work if it is\r\n            \/\/ of a supported format.\r\n            g_bAudioOnly = TRUE;\r\n        }\r\n\r\n        \/\/ If this is an audio-only clip, width and height will be 0.\r\n        if ((lWidth == 0) && (lHeight == 0))\r\n            g_bAudioOnly = TRUE;\r\n    }\r\n    else\r\n    {\r\n        \/\/ No windowless control interface, so assume audio only\r\n        g_bAudioOnly = TRUE;\r\n    }\r\n\r\n}\r\n\r\n\r\nvoid PauseClip(void)\r\n{\r\n    if (!pMC)\r\n        return;\r\n\r\n    \/\/ Toggle play\/pause behavior\r\n    if((g_psCurrent == Paused) || (g_psCurrent == Stopped))\r\n    {\r\n        if (SUCCEEDED(pMC->Run()))\r\n            g_psCurrent = Running;\r\n    }\r\n    else\r\n    {\r\n        if (SUCCEEDED(pMC->Pause()))\r\n            g_psCurrent = Paused;\r\n    }\r\n\r\n    UpdateMainTitle();\r\n}\r\n\r\n\r\nvoid StopClip(void)\r\n{\r\n    HRESULT hr;\r\n\r\n    if ((!pMC) || (!pMS))\r\n        return;\r\n\r\n    \/\/ Stop and reset postion to beginning\r\n    if((g_psCurrent == Paused) || (g_psCurrent == Running))\r\n    {\r\n        LONGLONG pos = 0;\r\n        hr = pMC->Stop();\r\n        g_psCurrent = Stopped;\r\n\r\n        \/\/ Seek to the beginning\r\n        hr = pMS->SetPositions(&pos, AM_SEEKING_AbsolutePositioning ,\r\n                               NULL, AM_SEEKING_NoPositioning);\r\n\r\n        \/\/ Display the first frame to indicate the reset condition\r\n        hr = pMC->Pause();\r\n    }\r\n\r\n    UpdateMainTitle();\r\n}\r\n\r\n\r\nvoid OpenClip()\r\n{\r\n    HRESULT hr;\r\n\r\n    \/\/ If no filename specified by command line, show file open dialog\r\n    if(g_szFileName[0] == L'\\0')\r\n    {\r\n        TCHAR szFilename[MAX_PATH];\r\n\r\n        UpdateMainTitle();\r\n        InitPlayerWindow();\r\n        SetForegroundWindow(ghApp);\r\n\r\n        if (! GetClipFileName(szFilename))\r\n        {\r\n            DWORD dwDlgErr = CommDlgExtendedError();\r\n\r\n            \/\/ Don't show output if user cancelled the selection (no dlg error)\r\n            if (dwDlgErr)\r\n            {\r\n                Msg(TEXT(\"GetClipFileName Failed! Error=0x%x\\r\\n\"), GetLastError());\r\n            }\r\n            return;\r\n        }\r\n\r\n        \/\/ This sample does not support playback of ASX playlists.\r\n        \/\/ Since this could be confusing to a user, display a warning\r\n        \/\/ message if an ASX file was opened.\r\n        if (_tcsnicmp(szFilename, TEXT(\".asx\"), 4) == 0)\r\n        {\r\n            Msg(TEXT(\"ASX Playlists are not supported by this application.\\n\\n\")\r\n                TEXT(\"Please select a valid media file.\\0\"));\r\n            return;\r\n        }\r\n\r\n        StringCchCopy(g_szFileName, NUMELMS(g_szFileName), szFilename);\r\n    }\r\n\r\n    \/\/ Reset status variables\r\n    g_psCurrent = Stopped;\r\n    g_lVolume = VOLUME_FULL;\r\n\r\n    \/\/ Start playing the media file\r\n    hr = PlayMovieInWindow(g_szFileName);\r\n\r\n    \/\/ If we couldn't play the clip, clean up\r\n    if (FAILED(hr))\r\n        CloseClip();\r\n}\r\n\r\n\r\nBOOL GetClipFileName(LPTSTR szName)\r\n{\r\n    static OPENFILENAME ofn={0};\r\n    static BOOL bSetInitialDir = FALSE;\r\n\r\n    \/\/ Reset filename\r\n    *szName = 0;\r\n\r\n    \/\/ Fill in standard structure fields\r\n    ofn.lStructSize       = sizeof(OPENFILENAME);\r\n    ofn.hwndOwner         = ghApp;\r\n    ofn.lpstrFilter       = NULL;\r\n    ofn.lpstrFilter       = FILE_FILTER_TEXT;\r\n    ofn.lpstrCustomFilter = NULL;\r\n    ofn.nFilterIndex      = 1;\r\n    ofn.lpstrFile         = szName;\r\n    ofn.nMaxFile          = MAX_PATH;\r\n    ofn.lpstrTitle        = TEXT(\"Open Media File...\\0\");\r\n    ofn.lpstrFileTitle    = NULL;\r\n    ofn.lpstrDefExt       = TEXT(\"*\\0\");\r\n    ofn.Flags             = OFN_FILEMUSTEXIST | OFN_READONLY | OFN_PATHMUSTEXIST;\r\n\r\n    \/\/ Remember the path of the first selected file\r\n    if (bSetInitialDir == FALSE)\r\n    {\r\n        ofn.lpstrInitialDir = DEFAULT_MEDIA_PATH;\r\n        bSetInitialDir = TRUE;\r\n    }\r\n    else\r\n        ofn.lpstrInitialDir = NULL;\r\n\r\n    \/\/ Create the standard file open dialog and return its result\r\n    return GetOpenFileName((LPOPENFILENAME)&ofn);\r\n}\r\n\r\n\r\nvoid CloseClip()\r\n{\r\n    HRESULT hr;\r\n\r\n    \/\/ Stop media playback\r\n    if(pMC)\r\n        hr = pMC->Stop();\r\n\r\n    \/\/ Clear global flags\r\n    g_psCurrent = Stopped;\r\n    g_bAudioOnly = TRUE;\r\n\r\n    \/\/ Free DirectShow interfaces\r\n    CloseInterfaces();\r\n\r\n    \/\/ Clear file name to allow selection of new file with open dialog\r\n    g_szFileName[0] = L'\\0';\r\n\r\n    \/\/ No current media state\r\n    g_psCurrent = Init;\r\n\r\n    \/\/ Reset the player window\r\n    RECT rect;\r\n    GetClientRect(ghApp, &rect);\r\n    InvalidateRect(ghApp, &rect, TRUE);\r\n\r\n    UpdateMainTitle();\r\n    InitPlayerWindow();\r\n}\r\n\r\n\r\nvoid CloseInterfaces(void)\r\n{\r\n    HRESULT hr;\r\n\r\n    \/\/ Disable event callbacks\r\n    if (pME)\r\n        hr = pME->SetNotifyWindow((OAHWND)NULL, 0, 0);\r\n\r\n#ifdef REGISTER_FILTERGRAPH\r\n    if (g_dwGraphRegister)\r\n    {\r\n        RemoveGraphFromRot(g_dwGraphRegister);\r\n        g_dwGraphRegister = 0;\r\n    }\r\n#endif\r\n\r\n    \/\/ Release and zero DirectShow interfaces\r\n    SAFE_RELEASE(pME);\r\n    SAFE_RELEASE(pMS);\r\n    SAFE_RELEASE(pMP);\r\n    SAFE_RELEASE(pMC);\r\n    SAFE_RELEASE(pBA);\r\n    SAFE_RELEASE(pWC);\r\n    SAFE_RELEASE(pFS);\r\n    SAFE_RELEASE(pGB);\r\n}\r\n\r\n\r\nvoid Msg(TCHAR *szFormat, ...)\r\n{\r\n    TCHAR szBuffer[1024];  \/\/ Large buffer for long filenames or URLs\r\n    const size_t NUMCHARS = sizeof(szBuffer) \/ sizeof(szBuffer[0]);\r\n    const int LASTCHAR = NUMCHARS - 1;\r\n\r\n    \/\/ Format the input string\r\n    va_list pArgs;\r\n    va_start(pArgs, szFormat);\r\n\r\n    \/\/ Use a bounded buffer size to prevent buffer overruns.  Limit count to\r\n    \/\/ character size minus one to allow for a NULL terminating character.\r\n    (void)StringCchVPrintf(szBuffer, NUMCHARS - 1, szFormat, pArgs);\r\n    va_end(pArgs);\r\n\r\n    \/\/ Ensure that the formatted string is NULL-terminated\r\n    szBuffer[LASTCHAR] = TEXT('\\0');\r\n\r\n    \/\/ Display a message box with the formatted string\r\n    MessageBox(NULL, szBuffer, TEXT(\"Windowless Sample\"), MB_OK);\r\n}\r\n\r\n\r\nHRESULT ToggleMute(void)\r\n{\r\n    HRESULT hr=S_OK;\r\n\r\n    if ((!pGB) || (!pBA))\r\n        return S_OK;\r\n\r\n    \/\/ Read current volume\r\n    hr = pBA->get_Volume(&g_lVolume);\r\n    if (hr == E_NOTIMPL)\r\n    {\r\n        \/\/ Fail quietly if this is a video-only media file\r\n        return S_OK;\r\n    }\r\n    else if (FAILED(hr))\r\n    {\r\n        Msg(TEXT(\"Failed to read audio volume!  hr=0x%x\\r\\n\"), hr);\r\n        return hr;\r\n    }\r\n\r\n    \/\/ Switch volume levels\r\n    if (g_lVolume == VOLUME_FULL)\r\n        g_lVolume = VOLUME_SILENCE;\r\n    else\r\n        g_lVolume = VOLUME_FULL;\r\n\r\n    \/\/ Set new volume\r\n    JIF(pBA->put_Volume(g_lVolume));\r\n\r\n    UpdateMainTitle();\r\n    return hr;\r\n}\r\n\r\n\r\nvoid UpdateMainTitle(void)\r\n{\r\n    TCHAR szTitle[MAX_PATH]={0}, szFile[MAX_PATH]={0};\r\n    HRESULT hr;\r\n\r\n    \/\/ If no file is loaded, just show the application title\r\n    if (g_szFileName[0] == L'\\0')\r\n    {\r\n        hr = StringCchCopy(szTitle, NUMELMS(szTitle), APPLICATIONNAME);\r\n    }\r\n\r\n    \/\/ Otherwise, show useful information\r\n    else\r\n    {\r\n        \/\/ Get file name without full path\r\n        GetFilename(g_szFileName, szFile);\r\n\r\n        char szPlaybackRate[16];\r\n        TCHAR szRate[24];\r\n\r\n        if (g_PlaybackRate == 1.0)\r\n            szPlaybackRate[0] = '\\0';\r\n        else\r\n            hr = StringCchPrintfA(szPlaybackRate, NUMELMS(szPlaybackRate), \"(Rate:%2.2f)\\0\", g_PlaybackRate);\r\n\r\n        hr = StringCchPrintf(szRate, NUMELMS(szRate), TEXT(\"%hs\"), szPlaybackRate);\r\n\r\n        \/\/ Update the window title to show filename and play state\r\n        hr = StringCchPrintf(szTitle, NUMELMS(szTitle), TEXT(\"%s [%s] %s%s%s\\0\\0\"),\r\n                szFile,\r\n                g_bAudioOnly ? TEXT(\"Audio\\0\") : TEXT(\"Video\\0\"),\r\n                (g_lVolume == VOLUME_SILENCE) ? TEXT(\"(Muted)\\0\") : TEXT(\"\\0\"),\r\n                (g_psCurrent == Paused) ? TEXT(\"(Paused)\\0\") : TEXT(\"\\0\"),\r\n                szRate);\r\n    }\r\n\r\n    SetWindowText(ghApp, szTitle);\r\n}\r\n\r\n\r\nvoid GetFilename(TCHAR *pszFull, TCHAR *pszFile)\r\n{\r\n    int nLength;\r\n    TCHAR szPath[MAX_PATH]={0};\r\n    BOOL bSetFilename=FALSE;\r\n\r\n    \/\/ Strip path and return just the file's name\r\n    (void)StringCchCopy(szPath, MAX_PATH, pszFull);\r\n    szPath[MAX_PATH-1] = 0;\r\n\r\n    nLength = (int) _tcslen(szPath);\r\n\r\n    for (int i=nLength-1; i>=0; i--)\r\n    {\r\n        if ((szPath[i] == '\\\\') || (szPath[i] == '\/'))\r\n        {\r\n            szPath[i] = '\\0';\r\n            StringCchCopy(pszFile, MAX_PATH, &szPath[i+1]);\r\n            bSetFilename = TRUE;\r\n            break;\r\n        }\r\n    }\r\n\r\n    \/\/ If there was no path given (just a file name), then\r\n    \/\/ just copy the full path to the target path.\r\n    if (!bSetFilename)\r\n        (void)StringCchCopy(pszFile, MAX_PATH, pszFull);\r\n\r\n    pszFile[MAX_PATH-1] = 0;        \/\/ Ensure null-termination\r\n}\r\n\r\n\r\n\/\/\r\n\/\/ Some video renderers support stepping media frame by frame with the\r\n\/\/ IVideoFrameStep interface.  See the interface documentation for more\r\n\/\/ details on frame stepping.\r\n\/\/\r\nBOOL GetFrameStepInterface(void)\r\n{\r\n    HRESULT hr;\r\n    IVideoFrameStep *pFSTest = NULL;\r\n\r\n    \/\/ Get the frame step interface, if supported\r\n    hr = pGB->QueryInterface(__uuidof(IVideoFrameStep), (PVOID *)&pFSTest);\r\n    if (FAILED(hr))\r\n        return FALSE;\r\n\r\n    \/\/ Check if this decoder can step\r\n    hr = pFSTest->CanStep(0L, NULL);\r\n\r\n    if (hr == S_OK)\r\n    {\r\n        pFS = pFSTest;  \/\/ Save interface to global variable for later use\r\n        return TRUE;\r\n    }\r\n    else\r\n    {\r\n        pFSTest->Release();\r\n        return FALSE;\r\n    }\r\n}\r\n\r\n\r\nHRESULT StepOneFrame(void)\r\n{\r\n    HRESULT hr=S_OK;\r\n\r\n    \/\/ If the Frame Stepping interface exists, use it to step one frame\r\n    if (pFS)\r\n    {\r\n        \/\/ The graph must be paused for frame stepping to work\r\n        if (g_psCurrent != State_Paused)\r\n            PauseClip();\r\n\r\n        \/\/ Step the requested number of frames, if supported\r\n        hr = pFS->Step(1, NULL);\r\n    }\r\n\r\n    return hr;\r\n}\r\n\r\n\r\nHRESULT StepFrames(int nFramesToStep)\r\n{\r\n    HRESULT hr=S_OK;\r\n\r\n    \/\/ If the Frame Stepping interface exists, use it to step frames\r\n    if (pFS)\r\n    {\r\n        \/\/ The renderer may not support frame stepping for more than one\r\n        \/\/ frame at a time, so check for support.  S_OK indicates that the\r\n        \/\/ renderer can step nFramesToStep successfully.\r\n        if ((hr = pFS->CanStep(nFramesToStep, NULL)) == S_OK)\r\n        {\r\n            \/\/ The graph must be paused for frame stepping to work\r\n            if (g_psCurrent != State_Paused)\r\n                PauseClip();\r\n\r\n            \/\/ Step the requested number of frames, if supported\r\n            hr = pFS->Step(nFramesToStep, NULL);\r\n        }\r\n    }\r\n\r\n    return hr;\r\n}\r\n\r\n\r\nHRESULT ModifyRate(double dRateAdjust)\r\n{\r\n    HRESULT hr=S_OK;\r\n    double dRate;\r\n\r\n    \/\/ If the IMediaPosition interface exists, use it to set rate\r\n    if ((pMP) && (dRateAdjust != 0))\r\n    {\r\n        if ((hr = pMP->get_Rate(&dRate)) == S_OK)\r\n        {\r\n            \/\/ Add current rate to adjustment value\r\n            double dNewRate = dRate + dRateAdjust;\r\n            hr = pMP->put_Rate(dNewRate);\r\n\r\n            \/\/ Save global rate\r\n            if (SUCCEEDED(hr))\r\n            {\r\n                g_PlaybackRate = dNewRate;\r\n                UpdateMainTitle();\r\n            }\r\n        }\r\n    }\r\n\r\n    return hr;\r\n}\r\n\r\n\r\nHRESULT SetRate(double dRate)\r\n{\r\n    HRESULT hr=S_OK;\r\n\r\n    \/\/ If the IMediaPosition interface exists, use it to set rate\r\n    if (pMP)\r\n    {\r\n        hr = pMP->put_Rate(dRate);\r\n\r\n        \/\/ Save global rate\r\n        if (SUCCEEDED(hr))\r\n        {\r\n            g_PlaybackRate = dRate;\r\n            UpdateMainTitle();\r\n        }\r\n    }\r\n\r\n    return hr;\r\n}\r\n\r\n\r\nHRESULT HandleGraphEvent(void)\r\n{\r\n    LONG evCode;\r\n\tLONG_PTR evParam1, evParam2;\r\n    HRESULT hr=S_OK;\r\n\r\n    \/\/ Make sure that we don't access the media event interface\r\n    \/\/ after it has already been released.\r\n    if (!pME)\r\n        return S_OK;\r\n\r\n    \/\/ Process all queued events\r\n    while(SUCCEEDED(pME->GetEvent(&evCode, &evParam1, &evParam2, 0)))\r\n    {\r\n        \/\/ Free memory associated with callback, since we're not using it\r\n        hr = pME->FreeEventParams(evCode, evParam1, evParam2);\r\n\r\n        \/\/ If this is the end of the clip, reset to beginning\r\n        if(EC_COMPLETE == evCode)\r\n        {\r\n            LONGLONG pos=0;\r\n\r\n            \/\/ Reset to first frame of movie\r\n            hr = pMS->SetPositions(&pos, AM_SEEKING_AbsolutePositioning ,\r\n                                   NULL, AM_SEEKING_NoPositioning);\r\n            if (FAILED(hr))\r\n            {\r\n                \/\/ If seeking failed, just stop and restart playback\r\n                hr = pMC->Stop();\r\n                hr = pMC->Run();\r\n            }\r\n        }\r\n    }\r\n\r\n    return hr;\r\n}\r\n\r\n\r\nvoid CheckSizeMenu(WPARAM wParam)\r\n{\r\n    WPARAM nItems[4] = {ID_FILE_SIZE_HALF,    ID_FILE_SIZE_DOUBLE,\r\n                        ID_FILE_SIZE_NORMAL,  ID_FILE_SIZE_THREEQUARTER};\r\n\r\n    \/\/ Set\/clear checkboxes that indicate the size of the video clip\r\n    for (int i=0; i<4; i++)\r\n    {\r\n        \/\/ Check the selected item\r\n        CheckMenuItem(ghMenu, (UINT) nItems[i],\r\n                     (UINT) (wParam == nItems[i]) ? MF_CHECKED : MF_UNCHECKED);\r\n    }\r\n}\r\n\r\n\r\nvoid EnablePlaybackMenu(BOOL bEnable, int nMediaType)\r\n{\r\n    int i;\r\n    WPARAM nItems[15] = {ID_FILE_PAUSE,       ID_FILE_STOP,\r\n                         ID_FILE_MUTE,        ID_RATE_INCREASE,\r\n                         ID_RATE_DECREASE,    ID_RATE_NORMAL,\r\n                         ID_RATE_HALF,        ID_RATE_DOUBLE,\r\n                         ID_SINGLE_STEP,\r\n                         ID_FILE_SIZE_HALF,   ID_FILE_SIZE_DOUBLE,\r\n                         ID_FILE_SIZE_NORMAL, ID_FILE_SIZE_THREEQUARTER,\r\n                         ID_CAPTURE_IMAGE,    ID_DISPLAY_IMAGE};\r\n\r\n    \/\/ Enable\/disable menu items related to playback (pause, stop, mute)\r\n    for (i=0; i<8; i++)\r\n    {\r\n        EnableMenuItem(ghMenu, (UINT) nItems[i],\r\n                      (UINT) (bEnable) ? MF_ENABLED : MF_GRAYED);\r\n    }\r\n\r\n    \/\/ Enable\/disable menu items related to video size\r\n    for (i=8; i<15; i++)\r\n    {\r\n        EnableMenuItem(ghMenu, (UINT) nItems[i],\r\n                     (UINT) (nMediaType == VIDEO) ? MF_ENABLED : MF_GRAYED);\r\n    }\r\n}\r\n\r\n\r\nLRESULT CALLBACK AboutDlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)\r\n{\r\n    switch (message)\r\n    {\r\n        case WM_INITDIALOG:\r\n            return TRUE;\r\n\r\n        case WM_COMMAND:\r\n            if (wParam == IDOK)\r\n            {\r\n                EndDialog(hWnd, TRUE);\r\n                return TRUE;\r\n            }\r\n            break;\r\n    }\r\n\r\n    return FALSE;\r\n}\r\n\r\n\r\nLRESULT CALLBACK WndMainProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)\r\n{\r\n    switch(message)\r\n    {\r\n        case WM_PAINT:\r\n            OnPaint(hWnd);\r\n            break;\r\n\r\n        case WM_DISPLAYCHANGE:\r\n            if (pWC)\r\n                pWC->DisplayModeChanged();\r\n            break;\r\n\r\n        \/\/ Resize the video when the window changes\r\n        case WM_MOVE:\r\n        case WM_SIZE:\r\n            if ((hWnd == ghApp) && (!g_bAudioOnly))\r\n                MoveVideoWindow();\r\n            break;\r\n\r\n        \/\/ Enforce a minimum size\r\n        case WM_GETMINMAXINFO:\r\n            {\r\n                LPMINMAXINFO lpmm = (LPMINMAXINFO) lParam;\r\n                if (lpmm)\r\n                {\r\n                    lpmm->ptMinTrackSize.x = MINIMUM_VIDEO_WIDTH;\r\n                    lpmm->ptMinTrackSize.y = MINIMUM_VIDEO_HEIGHT;\r\n                }\r\n            }\r\n            break;\r\n\r\n        case WM_RBUTTONDOWN:\r\n            CaptureImage(CAPTURED_IMAGE_NAME);\r\n            break;\r\n\r\n        case WM_KEYDOWN:\r\n\r\n            switch(toupper((int) wParam))\r\n            {\r\n                \/\/ Frame stepping\r\n                case VK_SPACE:\r\n                case '1':\r\n                    StepOneFrame();\r\n                    break;\r\n\r\n                \/\/ Frame stepping (multiple frames)\r\n                case '2':\r\n                case '3':\r\n                case '4':\r\n                case '5':\r\n                case '6':\r\n                case '7':\r\n                case '8':\r\n                case '9':\r\n                    StepFrames((int) wParam - '0');\r\n                    break;\r\n\r\n                case VK_LEFT:       \/\/ Reduce playback speed by 25%\r\n                    ModifyRate(-0.5);\r\n                    break;\r\n\r\n                case VK_RIGHT:      \/\/ Increase playback speed by 25%\r\n                    ModifyRate(0.5);\r\n                    break;\r\n\r\n                case VK_DOWN:       \/\/ Set playback speed to normal\r\n                    SetRate(1.0);\r\n                    break;\r\n\r\n                case 'P':\r\n                    PauseClip();\r\n                    break;\r\n\r\n                case 'S':\r\n                    StopClip();\r\n                    break;\r\n\r\n                case 'M':\r\n                    ToggleMute();\r\n                    break;\r\n\r\n               case 'H':\r\n                    InitVideoWindow(1,2);\r\n                    CheckSizeMenu(wParam);\r\n                    break;\r\n                case 'N':\r\n                    InitVideoWindow(1,1);\r\n                    CheckSizeMenu(wParam);\r\n                    break;\r\n                case 'D':\r\n                    InitVideoWindow(2,1);\r\n                    CheckSizeMenu(wParam);\r\n                    break;\r\n                case 'T':\r\n                    InitVideoWindow(3,4);\r\n                    CheckSizeMenu(wParam);\r\n                    break;\r\n\r\n                case VK_ESCAPE:\r\n                    CloseClip();\r\n                    break;\r\n\r\n                case VK_F12:\r\n                case 'Q':\r\n                case 'X':\r\n                    CloseClip();\r\n                    break;\r\n            }\r\n            break;\r\n\r\n        case WM_COMMAND:\r\n\r\n            switch(wParam)\r\n            { \/\/ Menus\r\n\r\n                case ID_FILE_OPENCLIP:\r\n                    \/\/ If we have ANY file open, close it and shut down DirectShow\r\n                    if (g_psCurrent != Init)\r\n                        CloseClip();\r\n\r\n                    \/\/ Open the new clip\r\n                    OpenClip();\r\n                    break;\r\n\r\n                case ID_FILE_EXIT:\r\n                    CloseClip();\r\n                    PostQuitMessage(0);\r\n                    break;\r\n\r\n                case ID_FILE_PAUSE:\r\n                    PauseClip();\r\n                    break;\r\n\r\n                case ID_FILE_STOP:\r\n                    StopClip();\r\n                    break;\r\n\r\n                case ID_FILE_CLOSE:\r\n                    CloseClip();\r\n                    break;\r\n\r\n                case ID_FILE_MUTE:\r\n                    ToggleMute();\r\n                    break;\r\n\r\n                case ID_CAPTURE_IMAGE:\r\n                    CaptureImage(CAPTURED_IMAGE_NAME);\r\n                    break;\r\n\r\n                case ID_DISPLAY_IMAGE:\r\n                    DisplayCapturedImage(CAPTURED_IMAGE_NAME);\r\n                    break;\r\n\r\n                case ID_HELP_ABOUT:\r\n                    DialogBox(ghInst, MAKEINTRESOURCE(IDD_ABOUTBOX),\r\n                              ghApp,  (DLGPROC) AboutDlgProc);\r\n                    break;\r\n\r\n                case ID_FILE_SIZE_HALF:\r\n                    InitVideoWindow(1,2);\r\n                    CheckSizeMenu(wParam);\r\n                    break;\r\n                case ID_FILE_SIZE_NORMAL:\r\n                    InitVideoWindow(1,1);\r\n                    CheckSizeMenu(wParam);\r\n                    break;\r\n                case ID_FILE_SIZE_DOUBLE:\r\n                    InitVideoWindow(2,1);\r\n                    CheckSizeMenu(wParam);\r\n                    break;\r\n                case ID_FILE_SIZE_THREEQUARTER:\r\n                    InitVideoWindow(3,4);\r\n                    CheckSizeMenu(wParam);\r\n                    break;\r\n\r\n                case ID_SINGLE_STEP:\r\n                    StepOneFrame();\r\n                    break;\r\n\r\n                case ID_RATE_DECREASE:     \/\/ Reduce playback speed by 25%\r\n                    ModifyRate(-0.5);\r\n                    break;\r\n                case ID_RATE_INCREASE:     \/\/ Increase playback speed by 25%\r\n                    ModifyRate(0.5);\r\n                    break;\r\n                case ID_RATE_NORMAL:       \/\/ Set playback speed to normal\r\n                    SetRate(1.0);\r\n                    break;\r\n                case ID_RATE_HALF:         \/\/ Set playback speed to 1\/2 normal\r\n                    SetRate(0.5);\r\n                    break;\r\n                case ID_RATE_DOUBLE:       \/\/ Set playback speed to 2x normal\r\n                    SetRate(2.0);\r\n                    break;\r\n\r\n            } \/\/ Menus\r\n            break;\r\n\r\n\r\n        case WM_GRAPHNOTIFY:\r\n            HandleGraphEvent();\r\n            break;\r\n\r\n        case WM_CLOSE:\r\n            SendMessage(ghApp, WM_COMMAND, ID_FILE_EXIT, 0);\r\n            break;\r\n\r\n        case WM_DESTROY:\r\n            PostQuitMessage(0);\r\n            break;\r\n\r\n        default:\r\n            return DefWindowProc(hWnd, message, wParam, lParam);\r\n\r\n    } \/\/ Window msgs handling\r\n\r\n    return DefWindowProc(hWnd, message, wParam, lParam);\r\n}\r\n\r\n\r\nint PASCAL wWinMain(HINSTANCE hInstC, HINSTANCE hInstP, LPWSTR lpCmdLine, int nCmdShow)\r\n{\r\n    MSG msg={0};\r\n    WNDCLASS wc;\r\n\r\n    \/\/ Initialize COM\r\n    if(FAILED(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED)))\r\n    {\r\n        Msg(TEXT(\"CoInitialize Failed!\\r\\n\"));\r\n        exit(1);\r\n    }\r\n\r\n    \/\/ Verify that the VMR9 is present on this system\r\n    if(!VerifyVMR9())\r\n        return FALSE;\r\n\r\n    \/\/ Was a filename specified on the command line?\r\n    if(lpCmdLine[0] != '\\0')\r\n    {\r\n        (void)StringCchCopy(g_szFileName, NUMELMS(g_szFileName), lpCmdLine);\r\n    }\r\n\r\n    \/\/ Set initial media state\r\n    g_psCurrent = Init;\r\n\r\n    \/\/ Register the window class\r\n    ZeroMemory(&wc, sizeof wc);\r\n    ghInst = wc.hInstance = hInstC;\r\n    wc.lpfnWndProc   = WndMainProc;\r\n    wc.lpszClassName = CLASSNAME;\r\n    wc.lpszMenuName  = MAKEINTRESOURCE(IDR_MENU);\r\n    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);\r\n    wc.hIcon         = NULL;\r\n    if(!RegisterClass(&wc))\r\n    {\r\n        Msg(TEXT(\"RegisterClass Failed! Error=0x%x\\r\\n\"), GetLastError());\r\n        CoUninitialize();\r\n        exit(1);\r\n    }\r\n\r\n    \/\/ Create the main window.  The WS_CLIPCHILDREN style is required.\r\n    ghApp = CreateWindow(CLASSNAME, APPLICATIONNAME,\r\n                         WS_OVERLAPPEDWINDOW | WS_CAPTION | WS_CLIPCHILDREN | WS_VISIBLE,\r\n                         CW_USEDEFAULT, CW_USEDEFAULT,\r\n                         DEFAULT_AUDIO_WIDTH, DEFAULT_AUDIO_HEIGHT,\r\n                         0, 0, ghInst, 0);\r\n\r\n    if(ghApp)\r\n    {\r\n        \/\/ Save menu handle for later use\r\n        ghMenu = GetMenu(ghApp);\r\n        EnablePlaybackMenu(FALSE, 0);\r\n\r\n        \/\/ If a media file was specified on the command line, open it now.\r\n        \/\/ (If the first character in the string isn't NULL, post an open clip message.)\r\n        if (g_szFileName[0] != 0)\r\n            PostMessage(ghApp, WM_COMMAND, ID_FILE_OPENCLIP, 0);\r\n\r\n        \/\/ Main message loop\r\n        while(GetMessage(&msg,NULL,0,0))\r\n        {\r\n            TranslateMessage(&msg);\r\n            DispatchMessage(&msg);\r\n        }\r\n    }\r\n    else\r\n    {\r\n        Msg(TEXT(\"Failed to create the main window! Error=0x%x\\r\\n\"), GetLastError());\r\n    }\r\n\r\n    \/\/ Finished with COM\r\n    CoUninitialize();\r\n\r\n    return (int) msg.wParam;\r\n}\r\n\r\n\r\n\r\nHRESULT InitializeWindowlessVMR(IBaseFilter **ppVmr9)\r\n{\r\n    IBaseFilter* pVmr = NULL;\r\n\r\n    if (!ppVmr9)\r\n        return E_POINTER;\r\n    *ppVmr9 = NULL;\r\n\r\n    \/\/ Create the VMR and add it to the filter graph.\r\n    HRESULT hr = CoCreateInstance(CLSID_VideoMixingRenderer9, NULL,\r\n                     CLSCTX_INPROC, IID_IBaseFilter, (void**)&pVmr);\r\n    if (SUCCEEDED(hr))\r\n    {\r\n        hr = pGB->AddFilter(pVmr, L\"Video Mixing Renderer 9\");\r\n        if (SUCCEEDED(hr))\r\n        {\r\n            \/\/ Set the rendering mode and number of streams\r\n            SmartPtr <IVMRFilterConfig9> pConfig;\r\n\r\n            JIF(pVmr->QueryInterface(IID_IVMRFilterConfig9, (void**)&pConfig));\r\n            JIF(pConfig->SetRenderingMode(VMR9Mode_Windowless));\r\n\r\n            hr = pVmr->QueryInterface(IID_IVMRWindowlessControl9, (void**)&pWC);\r\n            if( SUCCEEDED(hr))\r\n            {\r\n                JIF(pWC->SetVideoClippingWindow(ghApp));\r\n                JIF(pWC->SetBorderColor(RGB(0,0,0)));\r\n            }\r\n        }\r\n\r\n        \/\/ Don't release the pVmr interface because we are copying it into\r\n        \/\/ the caller's ppVmr9 pointer\r\n        *ppVmr9 = pVmr;\r\n    }\r\n\r\n    return hr;\r\n}\r\n\r\n\r\nvoid OnPaint(HWND hwnd)\r\n{\r\n    HRESULT hr;\r\n    PAINTSTRUCT ps;\r\n    HDC         hdc;\r\n    RECT        rcClient;\r\n\r\n    GetClientRect(hwnd, &rcClient);\r\n    hdc = BeginPaint(hwnd, &ps);\r\n\r\n    if(pWC && !g_bAudioOnly)\r\n    {\r\n        \/\/ When using VMR Windowless mode, you must explicitly tell the\r\n        \/\/ renderer when to repaint the video in response to WM_PAINT\r\n        \/\/ messages.  This is most important when the video is stopped\r\n        \/\/ or paused, since the VMR won't be automatically updating the\r\n        \/\/ window as the video plays.\r\n        hr = pWC->RepaintVideo(hwnd, hdc);\r\n    }\r\n    else  \/\/ No video image. Just paint the whole client area.\r\n    {\r\n        FillRect(hdc, &rcClient, (HBRUSH)(COLOR_BTNFACE + 1));\r\n    }\r\n\r\n    EndPaint(hwnd, &ps);\r\n}\r\n\r\n\r\nBOOL CaptureImage(LPCTSTR szFile)\r\n{\r\n    HRESULT hr;\r\n\r\n    if(pWC && !g_bAudioOnly)\r\n    {\r\n        BYTE* lpCurrImage = NULL;\r\n\r\n        \/\/ Read the current video frame into a byte buffer.  The information\r\n        \/\/ will be returned in a packed Windows DIB and will be allocated\r\n        \/\/ by the VMR.\r\n        if(SUCCEEDED(hr = pWC->GetCurrentImage(&lpCurrImage)))\r\n        {\r\n            BITMAPFILEHEADER    hdr;\r\n            DWORD               dwSize, dwWritten;\r\n            LPBITMAPINFOHEADER  pdib = (LPBITMAPINFOHEADER) lpCurrImage;\r\n\r\n            \/\/ Create a new file to store the bitmap data\r\n            HANDLE hFile = CreateFile(szFile, GENERIC_WRITE, FILE_SHARE_READ, NULL,\r\n                                      CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);\r\n\r\n            if (hFile == INVALID_HANDLE_VALUE)\r\n                return FALSE;\r\n\r\n            \/\/ Initialize the bitmap header\r\n            dwSize = DibSize(pdib);\r\n            hdr.bfType          = BFT_BITMAP;\r\n            hdr.bfSize          = dwSize + sizeof(BITMAPFILEHEADER);\r\n            hdr.bfReserved1     = 0;\r\n            hdr.bfReserved2     = 0;\r\n            hdr.bfOffBits       = (DWORD)sizeof(BITMAPFILEHEADER) + pdib->biSize +\r\n                DibPaletteSize(pdib);\r\n\r\n            \/\/ Write the bitmap header and bitmap bits to the file\r\n            WriteFile(hFile, (LPCVOID) &hdr, sizeof(BITMAPFILEHEADER), &dwWritten, 0);\r\n            WriteFile(hFile, (LPCVOID) pdib, dwSize, &dwWritten, 0);\r\n\r\n            \/\/ Close the file\r\n            CloseHandle(hFile);\r\n\r\n            \/\/ The app must free the image data returned from GetCurrentImage()\r\n            CoTaskMemFree(lpCurrImage);\r\n\r\n            \/\/ Give user feedback that the write has completed\r\n            TCHAR szDir[MAX_PATH];\r\n\r\n            GetCurrentDirectory(MAX_PATH, szDir);\r\n\r\n            \/\/ Strip off the trailing slash, if it exists\r\n            int nLength = (int) _tcslen(szDir);\r\n            if (szDir[nLength-1] == TEXT('\\\\'))\r\n                szDir[nLength-1] = TEXT('\\0');\r\n\r\n            Msg(TEXT(\"Captured current image to %s\\\\%s.\"), szDir, szFile);\r\n            return TRUE;\r\n        }\r\n        else\r\n        {\r\n            Msg(TEXT(\"Failed to capture image!  hr=0x%x\"), hr);\r\n            return FALSE;\r\n        }\r\n    }\r\n\r\n    return FALSE;\r\n}\r\n\r\nvoid DisplayCapturedImage(LPCTSTR szFile)\r\n{\r\n    \/\/ Open the bitmap with the system-default application\r\n    ShellExecute(ghApp, TEXT(\"open\\0\"), szFile, NULL, NULL, SW_SHOWNORMAL);\r\n}\r\n\r\n\r\n\r\n\r\n\/\/----------------------------------------------------------------------------\r\n\/\/  VerifyVMR9\r\n\/\/\r\n\/\/  Verifies that VMR9 COM objects exist on the system and that the VMR9\r\n\/\/  can be instantiated.\r\n\/\/\r\n\/\/  Returns: FALSE if the VMR9 can't be created\r\n\/\/----------------------------------------------------------------------------\r\n\r\nBOOL VerifyVMR9(void)\r\n{\r\n    HRESULT hr;\r\n\r\n    \/\/ Verify that the VMR exists on this system\r\n    IBaseFilter* pBF = NULL;\r\n    hr = CoCreateInstance(CLSID_VideoMixingRenderer9, NULL,\r\n                          CLSCTX_INPROC,\r\n                          IID_IBaseFilter,\r\n                          (LPVOID *)&pBF);\r\n    if(SUCCEEDED(hr))\r\n    {\r\n        pBF->Release();\r\n        return TRUE;\r\n    }\r\n    else\r\n    {\r\n        MessageBox(NULL,\r\n            TEXT(\"This application requires the VMR-9.\\r\\n\\r\\n\")\r\n\r\n            TEXT(\"The VMR-9 is not enabled when viewing through a Remote\\r\\n\")\r\n            TEXT(\" Desktop session. You can run VMR-enabled applications only\\r\\n\") \r\n            TEXT(\"on your local computer.\\r\\n\\r\\n\")\r\n\r\n            TEXT(\"\\r\\nThis sample will now exit.\"),\r\n\r\n            TEXT(\"Video Mixing Renderer (VMR9) capabilities are required\"), MB_OK);\r\n\r\n        return FALSE;\r\n    }\r\n}","avg_line_length":27.9788235294,"max_line_length":110,"alphanum_fraction":0.5325035741,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7082,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":10.0,"content":"\/**********************************************************************************\/\n\/* This file is part of spla project                                              *\/\n\/* https:\/\/github.com\/JetBrains-Research\/spla                                     *\/\n\/**********************************************************************************\/\n\/* MIT License                                                                    *\/\n\/*                                                                                *\/\n\/* Copyright (c) 2021 JetBrains-Research                                          *\/\n\/*                                                                                *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining a copy   *\/\n\/* of this software and associated documentation files (the \"Software\"), to deal  *\/\n\/* in the Software without restriction, including without limitation the rights   *\/\n\/* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell      *\/\n\/* copies of the Software, and to permit persons to whom the Software is          *\/\n\/* furnished to do so, subject to the following conditions:                       *\/\n\/*                                                                                *\/\n\/* The above copyright notice and this permission notice shall be included in all *\/\n\/* copies or substantial portions of the Software.                                *\/\n\/*                                                                                *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR     *\/\n\/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,       *\/\n\/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE    *\/\n\/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER         *\/\n\/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  *\/\n\/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  *\/\n\/* SOFTWARE.                                                                      *\/\n\/**********************************************************************************\/\n\n#include <spla-algo\/SplaAlgoSssp.hpp>\n#include <spla-cpp\/Spla.hpp>\n\n#include <compute\/SplaIndicesToRowOffsets.hpp>\n#include <core\/SplaError.hpp>\n\n#include <limits>\n#include <queue>\n#include <vector>\n\nvoid spla::Sssp(RefPtr<Vector> &sp_v, const RefPtr<Matrix> &sp_A, Index s) {\n    CHECK_RAISE_ERROR(sp_A.IsNotNull(), NullPointer, \"Passed null argument\");\n    CHECK_RAISE_ERROR(sp_A->GetNrows() == sp_A->GetNcols(), DimensionMismatch, \"Matrix must be nxn\");\n    CHECK_RAISE_ERROR(s < sp_A->GetNrows(), InvalidArgument, \"Start index must be withing A bounds\");\n\n    auto &library = sp_A->GetLibrary();\n    auto type = sp_A->GetType();\n    auto n = sp_A->GetNrows();\n\n    CHECK_RAISE_ERROR(type->IsBuiltIn(), InvalidArgument, \"Must be built-in type\");\n    CHECK_RAISE_ERROR(type == Types::Float32(library), InvalidArgument, \"Must be float32 type\");\n\n    float zero = 0.0f;\n\n    \/\/ Used to check if something changed\n    auto reduceOp = Functions::PlusFloat32(library);\n    \/\/ Used to concatenate paths lengths\n    auto multOp = Functions::PlusFloat32(library);\n    \/\/ Used find shortest path almond others\n    auto addOp = Functions::MinFloat32(library);\n\n    \/\/ Vector with reached paths\n    sp_v = Vector::Make(n, type, library);\n    \/\/ Temporary to store new reached paths\n    auto sp_w = Vector::Make(n, type, library);\n    \/\/ Scalar to store reduce succ\n    auto sp_succ = Scalar::Make(type, library);\n\n    \/\/ Set v[s] = w[s] = 0.0f - so start is reached in 0.0\n    auto sp_setup = Expression::Make(library);\n    sp_setup->MakeDataWrite(sp_v, DataVector::Make(&s, &zero, 1, library));\n    sp_setup->MakeDataWrite(sp_w, DataVector::Make(&s, &zero, 1, library));\n    sp_setup->SubmitWait();\n\n    std::size_t iterations = 0;\n    float succLast = 0.0f;\n    float succ = 1.0f;\n\n    while (iterations < n && succ != succLast) {\n        succLast = succ;\n\n        auto sp_iter = Expression::Make(library);\n\n        auto t1 = sp_iter->MakeVxM(sp_w, nullptr, multOp, addOp, sp_w, sp_A);\n        auto t2 = sp_iter->MakeEWiseAdd(sp_v, nullptr, addOp, sp_v, sp_w);\n        auto t3 = sp_iter->MakeReduce(sp_succ, reduceOp, sp_v);\n        auto t4 = sp_iter->MakeDataRead(sp_succ, DataScalar::Make(&succ, library));\n\n        sp_iter->Dependency(t1, t2);\n        sp_iter->Dependency(t2, t3);\n        sp_iter->Dependency(t3, t4);\n        sp_iter->SubmitWait();\n\n        iterations += 1;\n    }\n\n#if defined(SPLA_DEBUG) || defined(SPLA_DEBUG_RELEASE)\n    std::cout << \"Exec iterations: \" << iterations << \"\\n\";\n#endif\n}\n\nvoid spla::Sssp(RefPtr<HostVector> &v, const RefPtr<HostMatrix> &A, Index s) {\n    CHECK_RAISE_ERROR(A.IsNotNull(), NullPointer, \"Passed null argument\");\n    CHECK_RAISE_ERROR(A->GetNrows() == A->GetNcols(), DimensionMismatch, \"Matrix must be nxn\");\n    CHECK_RAISE_ERROR(s < A->GetNrows(), InvalidArgument, \"Start index must be withing A bounds\");\n    CHECK_RAISE_ERROR(A->GetElementSize() == sizeof(float), InvalidType, \"Matrix A must have float values of size 4\");\n\n    auto n = A->GetNrows();\n    auto inf = std::numeric_limits<float>::max();\n\n    \/\/ Note: implementation of shortest path fastest algorithms\n    \/\/ see for details https:\/\/en.wikipedia.org\/wiki\/Shortest_Path_Faster_Algorithm\n\n    \/\/ Offset to fetch rows by index\n    std::vector<Index> offsets;\n    \/\/ Initial distances to vertices\n    std::vector<float> distances(n, inf);\n    \/\/ Track already reached vertices\n    std::vector<bool> isInQueue(n, false);\n    \/\/ Queue of the search\n    std::queue<Index> front;\n\n    \/\/ Compute row offsets\n    IndicesToRowOffsets(A->GetRowIndices(), offsets, n);\n\n    \/\/ Start from s\n    front.push(s);\n    distances[s] = 0.0f;\n    isInQueue[s] = true;\n\n    while (!front.empty()) {\n        auto i = front.front();\n        front.pop();\n        isInQueue[i] = false;\n\n        \/\/ Traverse all adjacent neighbors\n        for (Index k = offsets[i]; k < offsets[i + 1]; k++) {\n            auto j = A->GetColIndices()[k];\n            auto w = *(reinterpret_cast<const float *>(A->GetValues().data()) + k);\n\n            if (distances[j] == inf || distances[i] + w < distances[j]) {\n                distances[j] = distances[i] + w;\n                if (!isInQueue[j]) {\n                    isInQueue[j] = true;\n                    front.push(j);\n                }\n            }\n        }\n    }\n\n    \/\/ Define reached vertices\n    std::vector<Index> rows;\n    std::vector<float> values;\n\n    \/\/ Add in order only reached vertices\n    for (Index k = 0; k < n; k++) {\n        if (distances[k] != inf) {\n            rows.push_back(k);\n            values.push_back(distances[k]);\n        }\n    }\n\n    \/\/ Convert to raw data\n    std::vector<unsigned char> data(values.size() * sizeof(float));\n    std::memcpy(data.data(), values.data(), values.size() * sizeof(float));\n\n    \/\/ Build result vector\n    v = RefPtr<HostVector>(new HostVector(n, std::move(rows), std::move(data)));\n}","avg_line_length":42.6626506024,"max_line_length":118,"alphanum_fraction":0.5626941542,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":837,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"#include \"transaction\/transaction-request.h\"\n\nnamespace txservice::transaction\n{\nTransactionRequest::TransactionRequest()\n{\n    current_ = 0;\n}\nTransactionRequest::TransactionRequest(const TransactionRequest &that)\n    : operation_request_queue_(that.operation_request_queue_),\n      current_(that.current_)\n{\n}\n\nvoid TransactionRequest::PushRequest(std::shared_ptr<OperationRequest> operation_request)\n{\n    operation_request_queue_.push_back(operation_request);\n}\n\nstd::shared_ptr<OperationRequest> TransactionRequest::CurrentRequest()\n{\n    if (current_ >= operation_request_queue_.size())\n    {\n        return nullptr;\n    }\n    else\n    {\n        return operation_request_queue_[current_++];\n    }\n}\n\nvoid TransactionRequest::Reset()\n{\n    operation_request_queue_.clear();\n    current_ = 0;\n}\n}  \/\/ namespace txservice::transaction","avg_line_length":22.6216216216,"max_line_length":89,"alphanum_fraction":0.7443249701,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3927,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["IJG"],"max_stars_count":null,"content":"\/\/ Copyright (C) 2002-2012 Nikolaus Gebhardt\n\/\/ This file is part of the \"Irrlicht Engine\".\n\/\/ For conditions of distribution and use, see copyright notice in irrlicht.h\n\n#include \"IrrCompileConfig.h\"\n\nstatic const char* const copyright = \"Irrlicht Engine (c) 2002-2012 Nikolaus Gebhardt\";\n\n#ifdef _IRR_WINDOWS_\n\t#include <windows.h>\n\t#if defined(_DEBUG) && !defined(__GNUWIN32__) && !defined(_WIN32_WCE)\n\t\t#include <crtdbg.h>\n\t#endif \/\/ _DEBUG\n#endif\n\n#include \"irrlicht.h\"\n#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_\n#include \"CIrrDeviceWin32.h\"\n#endif\n\n#ifdef _IRR_COMPILE_WITH_OSX_DEVICE_\n#include \"MacOSX\/CIrrDeviceMacOSX.h\"\n#endif\n\n#ifdef _IRR_COMPILE_WITH_WINDOWS_CE_DEVICE_\n#include \"CIrrDeviceWinCE.h\"\n#endif\n\n#ifdef _IRR_COMPILE_WITH_X11_DEVICE_\n#include \"CIrrDeviceLinux.h\"\n#endif\n\n#ifdef _IRR_COMPILE_WITH_SDL_DEVICE_\n#include \"CIrrDeviceSDL.h\"\n#endif\n\n#ifdef _IRR_COMPILE_WITH_FB_DEVICE_\n#include \"CIrrDeviceFB.h\"\n#endif\n\n#ifdef _IRR_COMPILE_WITH_CONSOLE_DEVICE_\n#include \"CIrrDeviceConsole.h\"\n#endif\n\nnamespace irr\n{\n\t\/\/! stub for calling createDeviceEx\n\tIRRLICHT_API IrrlichtDevice* IRRCALLCONV createDevice(video::E_DRIVER_TYPE driverType,\n\t\t\tconst core::dimension2d<u32>& windowSize,\n\t\t\tu32 bits, bool fullscreen,\n\t\t\tbool stencilbuffer, bool vsync, IEventReceiver* res)\n\t{\n\t\tSIrrlichtCreationParameters p;\n\t\tp.DriverType = driverType;\n\t\tp.WindowSize = windowSize;\n\t\tp.Bits = (u8)bits;\n\t\tp.Fullscreen = fullscreen;\n\t\tp.Stencilbuffer = stencilbuffer;\n\t\tp.Vsync = vsync;\n\t\tp.EventReceiver = res;\n\n\t\treturn createDeviceEx(p);\n\t}\n\n\textern \"C\" IRRLICHT_API IrrlichtDevice* IRRCALLCONV createDeviceEx(const SIrrlichtCreationParameters& params)\n\t{\n\n\t\tIrrlichtDevice* dev = 0;\n\n#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_\n\t\tif (params.DeviceType == EIDT_WIN32 || (!dev && params.DeviceType == EIDT_BEST))\n\t\t\tdev = new CIrrDeviceWin32(params);\n#endif\n\n#ifdef _IRR_COMPILE_WITH_OSX_DEVICE_\n\t\tif (params.DeviceType == EIDT_OSX || (!dev && params.DeviceType == EIDT_BEST))\n\t\t\tdev = new CIrrDeviceMacOSX(params);\n#endif\n\n#ifdef _IRR_COMPILE_WITH_WINDOWS_CE_DEVICE_\n\t\tif (params.DeviceType == EIDT_WINCE || (!dev && params.DeviceType == EIDT_BEST))\n\t\t\tdev = new CIrrDeviceWinCE(params);\n#endif\n\n#ifdef _IRR_COMPILE_WITH_X11_DEVICE_\n\t\tif (params.DeviceType == EIDT_X11 || (!dev && params.DeviceType == EIDT_BEST))\n\t\t\tdev = new CIrrDeviceLinux(params);\n#endif\n\n#ifdef _IRR_COMPILE_WITH_SDL_DEVICE_\n\t\tif (params.DeviceType == EIDT_SDL || (!dev && params.DeviceType == EIDT_BEST))\n\t\t\tdev = new CIrrDeviceSDL(params);\n#endif\n\n#ifdef _IRR_COMPILE_WITH_FB_DEVICE_\n\t\tif (params.DeviceType == EIDT_FRAMEBUFFER || (!dev && params.DeviceType == EIDT_BEST))\n\t\t\tdev = new CIrrDeviceFB(params);\n#endif\n\n#ifdef _IRR_COMPILE_WITH_CONSOLE_DEVICE_\n\t\tif (params.DeviceType == EIDT_CONSOLE || (!dev && params.DeviceType == EIDT_BEST))\n\t\t\tdev = new CIrrDeviceConsole(params);\n#endif\n\n\t\tif (dev && !dev->getVideoDriver() && params.DriverType != video::EDT_NULL)\n\t\t{\n\t\t\tdev->closeDevice(); \/\/ destroy window\n\t\t\tdev->run(); \/\/ consume quit message\n\t\t\tdev->drop();\n\t\t\tdev = 0;\n\t\t}\n\n\t\treturn dev;\n\t}\n\nnamespace core\n{\n\tconst matrix4 IdentityMatrix(matrix4::EM4CONST_IDENTITY);\n\tirr::core::stringc LOCALE_DECIMAL_POINTS(\".\");\n}\n\nnamespace video\n{\n\tSMaterial IdentityMaterial;\n}\n\n} \/\/ end namespace irr\n\n\n#if defined(_IRR_WINDOWS_API_) && !defined(_IRR_STATIC_LIB_)\n\nBOOL APIENTRY DllMain( HANDLE hModule,\n                       DWORD  ul_reason_for_call,\n                       LPVOID lpReserved )\n{\n\t\/\/ _crtBreakAlloc = 139;\n\n    switch (ul_reason_for_call)\n\t{\n\t\tcase DLL_PROCESS_ATTACH:\n\t\t\t#if defined(_DEBUG) && !defined(__GNUWIN32__) && !defined(__BORLANDC__) && !defined (_WIN32_WCE) && !defined (_IRR_XBOX_PLATFORM_)\n\t\t\t\t_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CRTDBG_ALLOC_MEM_DF);\n\t\t\t#endif\n\t\t\tbreak;\n\t\tcase DLL_THREAD_ATTACH:\n\t\tcase DLL_THREAD_DETACH:\n\t\tcase DLL_PROCESS_DETACH:\n\t\t\tbreak;\n    }\n    return TRUE;\n}\n\n#endif \/\/ defined(_IRR_WINDOWS_)\n\n","avg_line_length":25.335483871,"max_line_length":133,"alphanum_fraction":0.7382225618,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":91,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <iostream>\nusing namespace std;\n\nint main()\n{\n\tcout << \"Hello World\";\n\treturn 0;\n}","avg_line_length":11.375,"max_line_length":23,"alphanum_fraction":0.6593406593,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10559,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n * This file belongs to the Galois project, a C++ library for exploiting\n * parallelism. The code is being released under the terms of the 3-Clause BSD\n * License (a copy is located in LICENSE.txt at the top-level directory).\n *\n * Copyright (C) 2018, The University of Texas at Austin. All rights reserved.\n * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS\n * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF\n * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF\n * DEALING OR USAGE OF TRADE.  NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH\n * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances\n * shall University be liable for incidental, special, indirect, direct or\n * consequential damages or loss of profits, interruption of business, or\n * related expenses which may arise from use of Software or Documentation,\n * including but not limited to those resulting from defects in Software and\/or\n * Documentation, or loss or inaccuracy of data of any kind.\n *\/\n\n#include \"katana\/analytics\/k_core\/k_core.h\"\n\n#include \"katana\/ArrowRandomAccessBuilder.h\"\n#include \"katana\/Statistics.h\"\n#include \"katana\/TypedPropertyGraph.h\"\n\nusing namespace katana::analytics;\n\nconst int KCorePlan::kChunkSize = 64;\n\n\/*******************************************************************************\n * Functions for running the algorithm\n ******************************************************************************\/\n\/\/! Node deadness can be derived from current degree and k value, so no field\n\/\/! necessary.\nstruct KCoreNodeCurrentDegree : public katana::AtomicPODProperty<uint32_t> {};\n\nstruct KCoreNodeAlive : public katana::PODProperty<uint32_t> {};\n\nusing NodeData = std::tuple<KCoreNodeCurrentDegree>;\nusing EdgeData = std::tuple<>;\ntypedef katana::TypedPropertyGraph<NodeData, EdgeData> Graph;\ntypedef typename Graph::Node GNode;\n\n\/**\n * Initialize degree fields in graph with current degree. Since symmetric,\n * out edge count is equivalent to in-edge count.\n *\n * @param graph Graph to initialize degrees in\n *\/\nvoid\nDegreeCounting(Graph* graph) {\n  katana::do_all(\n      katana::iterate(*graph),\n      [&](const GNode& node) {\n        auto& node_current_degree =\n            graph->GetData<KCoreNodeCurrentDegree>(node);\n        node_current_degree.store(\n            std::distance(graph->edge_begin(node), graph->edge_end(node)));\n      },\n      katana::loopname(\"DegreeCounting\"), katana::no_stats());\n}\n\n\/**\n * Setup initial worklist of dead nodes.\n *\n * @param graph Graph to operate on\n * @param initial_worklist Empty worklist to be filled with dead nodes.\n * @param k_core_number Each node in the core is expected to have degree <= k_core_number.\n *\/\nvoid\nSetupInitialWorklist(\n    const Graph& graph, katana::InsertBag<GNode>& initial_worklist,\n    uint32_t k_core_number) {\n  katana::do_all(\n      katana::iterate(graph),\n      [&](const GNode& node) {\n        const auto& node_current_degree =\n            graph.GetData<KCoreNodeCurrentDegree>(node);\n        if (node_current_degree < k_core_number) {\n          \/\/! Dead node, add to initial_worklist for processing later.\n          initial_worklist.emplace(node);\n        }\n      },\n      katana::loopname(\"InitialWorklistSetup\"), katana::no_stats());\n}\n\n\/**\n * Starting with initial dead nodes as current worklist; decrement degree;\n * add to next worklist; switch next with current and repeat until worklist\n * is empty (i.e. no more dead nodes).\n *\n * @param graph Graph to operate on\n * @param k_core_number Each node in the core is expected to have degree <= k_core_number\n *\/\nvoid\nSyncCascadeKCore(Graph* graph, uint32_t k_core_number) {\n  auto current = std::make_unique<katana::InsertBag<GNode>>();\n  auto next = std::make_unique<katana::InsertBag<GNode>>();\n\n  \/\/! Setup worklist.\n  SetupInitialWorklist(*graph, *next, k_core_number);\n\n  while (!next->empty()) {\n    \/\/! Make \"next\" into current.\n    std::swap(current, next);\n    next->clear();\n\n    katana::do_all(\n        katana::iterate(*current),\n        [&](const GNode& dead_node) {\n          \/\/! Decrement degree of all neighbors.\n          for (auto e : graph->edges(dead_node)) {\n            auto dest = graph->GetEdgeDest(e);\n            auto& dest_current_degree =\n                graph->GetData<KCoreNodeCurrentDegree>(dest);\n            uint32_t old_degree = katana::atomicSub(dest_current_degree, 1u);\n\n            if (old_degree == k_core_number) {\n              \/\/! This thread was responsible for putting degree of destination\n              \/\/! below threshold; add to worklist.\n              next->emplace(*dest);\n            }\n          }\n        },\n        katana::steal(), katana::chunk_size<KCorePlan::kChunkSize>(),\n        katana::loopname(\"KCore Synchronous\"));\n  }\n}\n\n\/**\n * Starting with initial dead nodes, decrement degree and add to worklist\n * as they drop below 'k' threshold until worklist is empty (i.e. no more dead\n * nodes).\n *\n * @param graph Graph to operate on\n * @param k_core_number Each node in the core is expected to have degree <= k_core_number.\n *\/\nvoid\nAsyncCascadeKCore(Graph* graph, uint32_t k_core_number) {\n  katana::InsertBag<GNode> initial_worklist;\n  \/\/! Setup worklist.\n  SetupInitialWorklist(*graph, initial_worklist, k_core_number);\n\n  katana::for_each(\n      katana::iterate(initial_worklist),\n      [&](const GNode& dead_node, auto& ctx) {\n        \/\/! Decrement degree of all neighbors.\n        for (auto e : graph->edges(dead_node)) {\n          auto dest = graph->GetEdgeDest(e);\n          auto& dest_current_degree =\n              graph->GetData<KCoreNodeCurrentDegree>(dest);\n          uint32_t old_degree = katana::atomicSub(dest_current_degree, 1u);\n\n          if (old_degree == k_core_number) {\n            \/\/! This thread was responsible for putting degree of destination\n            \/\/! below threshold: add to worklist.\n            ctx.push(*dest);\n          }\n        }\n      },\n      katana::disable_conflict_detection(),\n      katana::chunk_size<KCorePlan::kChunkSize>(),\n      katana::loopname(\"KCore Asynchronous\"));\n}\n\n\/**\n * After computation is finished, the nodes left in the core\n * are marked as alive.\n *\n * @param graph Graph to operate on\n * @param k_core_number Each node in the core is expected to have degree <= k_core_number.\n *\/\nkatana::Result<void>\nKCoreMarkAliveNodes(\n    katana::TypedPropertyGraph<\n        std::tuple<KCoreNodeAlive, KCoreNodeCurrentDegree>, std::tuple<>>*\n        graph,\n    uint32_t k_core_number) {\n  katana::do_all(\n      katana::iterate(*graph),\n      [&](const GNode& node) {\n        auto& node_current_degree =\n            graph->GetData<KCoreNodeCurrentDegree>(node);\n        auto& node_flag = graph->GetData<KCoreNodeAlive>(node);\n        node_flag = 1;\n        if (node_current_degree < k_core_number) {\n          node_flag = 0;\n        }\n      },\n      katana::loopname(\"KCore Mark Nodes in Core\"));\n  return katana::ResultSuccess();\n}\n\nstatic katana::Result<void>\nKCoreImpl(\n    katana::TypedPropertyGraph<\n        std::tuple<KCoreNodeCurrentDegree>, std::tuple<>>* graph,\n    KCorePlan algo, uint32_t k_core_number) {\n  size_t approxNodeData = 4 * (graph->num_nodes() + graph->num_edges());\n  katana::EnsurePreallocated(8, approxNodeData);\n  katana::ReportPageAllocGuard page_alloc;\n\n  \/\/! Intialization of degrees.\n  DegreeCounting(graph);\n\n  \/\/! Begins main computation.\n  katana::StatTimer exec_time(\"KCore\");\n\n  exec_time.start();\n\n  switch (algo.algorithm()) {\n  case KCorePlan::kSynchronous:\n    SyncCascadeKCore(graph, k_core_number);\n    break;\n  case KCorePlan::kAsynchronous:\n    AsyncCascadeKCore(graph, k_core_number);\n    break;\n  default:\n    return katana::ErrorCode::AssertionFailed;\n  }\n  exec_time.stop();\n\n  return katana::ResultSuccess();\n}\n\nkatana::Result<void>\nkatana::analytics::KCore(\n    katana::PropertyGraph* pg, uint32_t k_core_number,\n    const std::string& output_property_name, KCorePlan algo) {\n  katana::analytics::TemporaryPropertyGuard temporary_property{pg};\n  if (auto result = ConstructNodeProperties<std::tuple<KCoreNodeCurrentDegree>>(\n          pg, {temporary_property.name()});\n      !result) {\n    return result.error();\n  }\n\n  auto pg_result = Graph::Make(pg, {temporary_property.name()}, {});\n  if (!pg_result) {\n    return pg_result.error();\n  }\n  auto graph = pg_result.value();\n\n  if (auto result_compute = KCoreImpl(&graph, algo, k_core_number);\n      !result_compute) {\n    return result_compute.error();\n  }\n  \/\/ Post processing. Mark alive nodes.\n  if (auto result = ConstructNodeProperties<std::tuple<KCoreNodeAlive>>(\n          pg, {output_property_name});\n      !result) {\n    return result.error();\n  }\n  auto pg_final_result = katana::TypedPropertyGraph<\n      std::tuple<KCoreNodeAlive, KCoreNodeCurrentDegree>, std::tuple<>>::\n      Make(pg, {output_property_name, temporary_property.name()}, {});\n  if (!pg_final_result) {\n    return pg_final_result.error();\n  }\n  auto graph_final = pg_final_result.value();\n\n  return KCoreMarkAliveNodes(&graph_final, k_core_number);\n}\n\n\/\/ Doxygen doesn't correctly handle implementation annotations that do not\n\/\/ appear in the declaration.\n\/\/\/ \\cond DO_NOT_DOCUMENT\n\/\/ TODO (gill) Add a validity routine.\nkatana::Result<void>\nkatana::analytics::KCoreAssertValid(\n    [[maybe_unused]] katana::PropertyGraph* pg,\n    [[maybe_unused]] uint32_t k_core_number,\n    [[maybe_unused]] const std::string& property_name) {\n  return katana::ResultSuccess();\n}\n\nkatana::Result<KCoreStatistics>\nkatana::analytics::KCoreStatistics::Compute(\n    katana::PropertyGraph* pg, [[maybe_unused]] uint32_t k_core_number,\n    const std::string& property_name) {\n  auto pg_result = katana::TypedPropertyGraph<\n      std::tuple<KCoreNodeAlive>, std::tuple<>>::Make(pg, {property_name}, {});\n  if (!pg_result) {\n    return pg_result.error();\n  }\n\n  auto graph = pg_result.value();\n\n  katana::GAccumulator<uint32_t> alive_nodes;\n  alive_nodes.reset();\n\n  katana::do_all(\n      katana::iterate(graph),\n      [&](const GNode& node) {\n        auto& node_alive = graph.GetData<KCoreNodeAlive>(node);\n        if (node_alive) {\n          alive_nodes += 1;\n        }\n      },\n      katana::loopname(\"KCore sanity check\"), katana::no_stats());\n\n  return KCoreStatistics{alive_nodes.reduce()};\n}\n\/\/\/ \\endcond DO_NOT_DOCUMENT\n\nvoid\nkatana::analytics::KCoreStatistics::Print(std::ostream& os) const {\n  os << \"Number of nodes in the core = \" << number_of_nodes_in_kcore\n     << std::endl;\n}\n","avg_line_length":34.0612903226,"max_line_length":90,"alphanum_fraction":0.6768633393,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7875,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MulanPSL-1.0"],"max_stars_count":796.0,"content":"\/*\n * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.\n *\n * OpenArkCompiler is licensed under the Mulan PSL v1.\n * You can use this software according to the terms and conditions of the Mulan PSL v1.\n * You may obtain a copy of Mulan PSL v1 at:\n *\n *     http:\/\/license.coscl.org.cn\/MulanPSL\n *\n * THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR\n * FIT FOR A PARTICULAR PURPOSE.\n * See the Mulan PSL v1 for more details.\n *\/\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n#include <memory>\n#include \"feir_test_base.h\"\n#include \"feir_var.h\"\n#include \"feir_var_reg.h\"\n#include \"feir_var_name.h\"\n#include \"feir_type_helper.h\"\n#include \"mplfe_ut_regx.h\"\n#include \"feir_builder.h\"\n\nnamespace maple {\nclass FEIRVarTest : public FEIRTestBase {\n public:\n  FEIRVarTest() = default;\n  virtual ~FEIRVarTest() = default;\n};\n\nTEST_F(FEIRVarTest, FEIRVarReg) {\n  std::unique_ptr<FEIRType> type = FEIRTypeHelper::CreateTypeByJavaName(\"Ljava\/lang\/Object;\", false, true);\n  FEIRVarReg varReg(1, std::move(type));\n  varReg.SetGlobal(false);\n  MIRSymbol *symbol = varReg.GenerateMIRSymbol(mirBuilder);\n  RedirectCout();\n  std::string symbolName = symbol->GetName();\n  std::string strPattern = MPLFEUTRegx::RegName(1) + \"_\" + MPLFEUTRegx::RefIndex(MPLFEUTRegx::kAnyNumber);\n  EXPECT_EQ(MPLFEUTRegx::Match(symbolName, strPattern), true);\n  symbol->Dump(true, 0);\n  std::string symbolDump = GetBufferString();\n  std::string strPattern2 = \"var %\" + MPLFEUTRegx::RegName(1) + \"_\" + MPLFEUTRegx::RefIndex(MPLFEUTRegx::kAnyNumber) +\n                            MPLFEUTRegx::Any();\n  EXPECT_EQ(MPLFEUTRegx::Match(symbolDump, strPattern2), true);\n  RestoreCout();\n}\n\nTEST_F(FEIRVarTest, FEIRVarName) {\n  std::unique_ptr<FEIRType> type = FEIRTypeHelper::CreateTypeByJavaName(\"Ljava\/lang\/Object;\", false, true);\n  GStrIdx nameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(\"Ljava_2Flang_2FObject_3B_7Cklass\");\n  FEIRVarName varName(nameIdx, std::move(type));\n  varName.SetGlobal(true);\n  MIRSymbol *symbol = varName.GenerateMIRSymbol(mirBuilder);\n  RedirectCout();\n  std::string symbolName = symbol->GetName();\n  EXPECT_EQ(symbolName, \"Ljava_2Flang_2FObject_3B_7Cklass\");\n  symbol->Dump(false, 0);\n  std::string symbolDump = GetBufferString();\n  std::string strPattern2 = std::string(\"var \\\\$\") + \"Ljava_2Flang_2FObject_3B_7Cklass\" + MPLFEUTRegx::Any();\n  EXPECT_EQ(MPLFEUTRegx::Match(symbolDump, strPattern2), true);\n  RestoreCout();\n}\n\nTEST_F(FEIRVarTest, FEIRVarTransDirect) {\n  UniqueFEIRVar var = FEIRBuilder::CreateVarReg(0, PTY_ref, false);\n  FEIRVarTrans trans(FEIRVarTransKind::kFEIRVarTransDirect, var);\n  RedirectCout();\n  UniqueFEIRType type1 = FEIRTypeHelper::CreateTypeByJavaName(\"Ljava\/lang\/Object;\", false, false);\n  UniqueFEIRType type1T = trans.GetType(type1);\n  type1T->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<$Ljava_2Flang_2FObject_3B>\");\n  ClearBufferString();\n\n  UniqueFEIRType type2 = FEIRTypeHelper::CreateTypeByJavaName(\"Ljava\/lang\/Object;\", false, true);\n  UniqueFEIRType type2T = trans.GetType(type2);\n  type2T->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<* <$Ljava_2Flang_2FObject_3B>>\");\n  ClearBufferString();\n\n  UniqueFEIRType type3 = FEIRTypeHelper::CreateTypeByJavaName(\"I\", false, false);\n  UniqueFEIRType type3T = trans.GetType(type3);\n  type3T->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"i32\");\n  ClearBufferString();\n\n  UniqueFEIRType type4 = FEIRTypeHelper::CreateTypeByJavaName(\"[I\", false, true);\n  UniqueFEIRType type4T = trans.GetType(type4);\n  type4T->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<* <[] i32>>\");\n  ClearBufferString();\n  RestoreCout();\n}\n\nTEST_F(FEIRVarTest, FEIRVarTransArrayDimIncr) {\n  UniqueFEIRVar var = FEIRBuilder::CreateVarReg(0, PTY_ref, false);\n  FEIRVarTrans trans(FEIRVarTransKind::kFEIRVarTransArrayDimIncr, var);\n  RedirectCout();\n  UniqueFEIRType type1 = FEIRTypeHelper::CreateTypeByJavaName(\"Ljava\/lang\/Object;\", false, false);\n  UniqueFEIRType type1T = trans.GetType(type1);\n  UniqueFEIRType type1T2 = trans.GetType(type1, PTY_ref, false);\n  type1T->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<* <[] <* <$Ljava_2Flang_2FObject_3B>>>>\");\n  ClearBufferString();\n  type1T2->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<[] <* <$Ljava_2Flang_2FObject_3B>>>\");\n  ClearBufferString();\n\n  UniqueFEIRType type2 = FEIRTypeHelper::CreateTypeByJavaName(\"[Ljava\/lang\/Object;\", false, true);\n  UniqueFEIRType type2T = trans.GetType(type2);\n  UniqueFEIRType type2T2 = trans.GetType(type2, PTY_ref, false);\n  type2T->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<* <[] <* <[] <* <$Ljava_2Flang_2FObject_3B>>>>>>\");\n  ClearBufferString();\n  type2T2->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<* <[] <* <[] <* <$Ljava_2Flang_2FObject_3B>>>>>>\");\n  ClearBufferString();\n\n  UniqueFEIRType type3 = FEIRTypeHelper::CreateTypeByJavaName(\"I\", false, false);\n  UniqueFEIRType type3T = trans.GetType(type3);\n  UniqueFEIRType type3T2 = trans.GetType(type3, PTY_ref, false);\n  type3T->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<* <[] i32>>\");\n  ClearBufferString();\n  type3T2->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<[] i32>\");\n  ClearBufferString();\n\n  UniqueFEIRType type4 = FEIRTypeHelper::CreateTypeByJavaName(\"[I\", false, true);\n  UniqueFEIRType type4T = trans.GetType(type4);\n  UniqueFEIRType type4T2 = trans.GetType(type4, PTY_ref, false);\n  type4T->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<* <[] <* <[] i32>>>>\");\n  ClearBufferString();\n  type4T2->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<* <[] <* <[] i32>>>>\");\n  ClearBufferString();\n  RestoreCout();\n}\n\nTEST_F(FEIRVarTest, FEIRVarTransArrayDimDecr) {\n  UniqueFEIRVar var = FEIRBuilder::CreateVarReg(0, PTY_ref, false);\n  FEIRVarTrans trans(FEIRVarTransKind::kFEIRVarTransArrayDimDecr, var);\n  RedirectCout();\n  UniqueFEIRType type1 = FEIRTypeHelper::CreateTypeByJavaName(\"[Ljava\/lang\/Object;\", false, false);\n  UniqueFEIRType type1T = trans.GetType(type1);\n  UniqueFEIRType type1T2 = trans.GetType(type1, PTY_ref, false);\n  type1T->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<* <$Ljava_2Flang_2FObject_3B>>\");\n  ClearBufferString();\n  type1T2->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<$Ljava_2Flang_2FObject_3B>\");\n  ClearBufferString();\n\n  UniqueFEIRType type2 = FEIRTypeHelper::CreateTypeByJavaName(\"[[Ljava\/lang\/Object;\", false, true);\n  UniqueFEIRType type2T = trans.GetType(type2);\n  UniqueFEIRType type2T2 = trans.GetType(type2, PTY_ref, false);\n  type2T->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<* <[] <* <$Ljava_2Flang_2FObject_3B>>>>\");\n  ClearBufferString();\n  type2T2->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<* <[] <* <$Ljava_2Flang_2FObject_3B>>>>\");\n  ClearBufferString();\n\n  UniqueFEIRType type3 = FEIRTypeHelper::CreateTypeByJavaName(\"[I\", false, false);\n  UniqueFEIRType type3T = trans.GetType(type3);\n  UniqueFEIRType type3T2 = trans.GetType(type3, PTY_ref, false);\n  type3T->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"i32\");\n  ClearBufferString();\n  type3T2->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"i32\");\n  ClearBufferString();\n\n  UniqueFEIRType type4 = FEIRTypeHelper::CreateTypeByJavaName(\"[[I\", false, false);\n  UniqueFEIRType type4T = trans.GetType(type4);\n  UniqueFEIRType type4T2 = trans.GetType(type4, PTY_ref, false);\n  type4T->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<* <[] i32>>\");\n  ClearBufferString();\n  type4T2->GenerateMIRType()->Dump(0);\n  EXPECT_EQ(GetBufferString(), \"<[] i32>\");\n  ClearBufferString();\n  RestoreCout();\n}\n}  \/\/ namespace maple","avg_line_length":42.1122994652,"max_line_length":118,"alphanum_fraction":0.7274920635,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7799,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ license:BSD-3-Clause\n\/\/ copyright-holders:Aaron Giles\n\/***************************************************************************\n\n    Atari Vindicators hardware\n\n****************************************************************************\/\n\n#include \"emu.h\"\n#include \"includes\/vindictr.h\"\n\n\n\n\/*************************************\n *\n *  Tilemap callbacks\n *\n *************************************\/\n\nTILE_GET_INFO_MEMBER(vindictr_state::get_alpha_tile_info)\n{\n\tuint16_t data = m_alpha_tilemap->basemem_read(tile_index);\n\tint code = data & 0x3ff;\n\tint color = ((data >> 10) & 0x0f) | ((data >> 9) & 0x20);\n\tint opaque = data & 0x8000;\n\tSET_TILE_INFO_MEMBER(1, code, color, opaque ? TILE_FORCE_LAYER0 : 0);\n}\n\n\nTILE_GET_INFO_MEMBER(vindictr_state::get_playfield_tile_info)\n{\n\tuint16_t data = m_playfield_tilemap->basemem_read(tile_index);\n\tint code = (m_playfield_tile_bank * 0x1000) + (data & 0xfff);\n\tint color = 0x10 + 2 * ((data >> 12) & 7);\n\tSET_TILE_INFO_MEMBER(0, code, color, (data >> 15) & 1);\n}\n\n\n\n\/*************************************\n *\n *  Video system start\n *\n *************************************\/\n\nconst atari_motion_objects_config vindictr_state::s_mob_config =\n{\n\t0,                  \/* index to which gfx system *\/\n\t1,                  \/* number of motion object banks *\/\n\t1,                  \/* are the entries linked? *\/\n\t0,                  \/* are the entries split? *\/\n\t0,                  \/* render in reverse order? *\/\n\t0,                  \/* render in swapped X\/Y order? *\/\n\t0,                  \/* does the neighbor bit affect the next object? *\/\n\t8,                  \/* pixels per SLIP entry (0 for no-slip) *\/\n\t0,                  \/* pixel offset for SLIPs *\/\n\t0,                  \/* maximum number of links to visit\/scanline (0=all) *\/\n\n\t0x100,              \/* base palette entry *\/\n\t0x100,              \/* maximum number of colors *\/\n\t0,                  \/* transparent pen index *\/\n\n\t{{ 0,0,0,0x03ff }}, \/* mask for the link *\/\n\t{{ 0x7fff,0,0,0 }}, \/* mask for the code index *\/\n\t{{ 0,0x000f,0,0 }}, \/* mask for the color *\/\n\t{{ 0,0xff80,0,0 }}, \/* mask for the X position *\/\n\t{{ 0,0,0xff80,0 }}, \/* mask for the Y position *\/\n\t{{ 0,0,0x0038,0 }}, \/* mask for the width, in tiles*\/\n\t{{ 0,0,0x0007,0 }}, \/* mask for the height, in tiles *\/\n\t{{ 0,0,0x0040,0 }}, \/* mask for the horizontal flip *\/\n\t{{ 0 }},            \/* mask for the vertical flip *\/\n\t{{ 0,0x0070,0,0 }}, \/* mask for the priority *\/\n\t{{ 0 }},            \/* mask for the neighbor *\/\n\t{{ 0 }},            \/* mask for absolute coordinates *\/\n\n\t{{ 0 }},            \/* mask for the special value *\/\n\t0                  \/* resulting value to indicate \"special\" *\/\n};\n\nvoid vindictr_state::video_start()\n{\n\t\/* save states *\/\n\tsave_item(NAME(m_playfield_tile_bank));\n\tsave_item(NAME(m_playfield_xscroll));\n\tsave_item(NAME(m_playfield_yscroll));\n}\n\n\n\n\/*************************************\n *\n *  Palette RAM control\n *\n *************************************\/\n\nWRITE16_MEMBER( vindictr_state::vindictr_paletteram_w )\n{\n\tstatic const int ztable[16] =\n\t\t{ 0x0, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11 };\n\tint c;\n\n\t\/* first blend the data *\/\n\tCOMBINE_DATA(&m_generic_paletteram_16[offset]);\n\tdata = m_generic_paletteram_16[offset];\n\n\t\/* now generate colors at all 16 intensities *\/\n\tfor (c = 0; c < 8; c++)\n\t{\n\t\tint i = ztable[((data >> 12) + (c * 2)) & 15];\n\t\tint r = ((data >> 8) & 15) * i;\n\t\tint g = ((data >> 4) & 15) * i;\n\t\tint b = ((data >> 0) & 15) * i;\n\n\t\tm_palette->set_pen_color(offset + c*2048,rgb_t(r,g,b));\n\t}\n}\n\n\n\n\/*************************************\n *\n *  Periodic scanline updater\n *\n *************************************\/\n\nvoid vindictr_state::scanline_update(screen_device &screen, int scanline)\n{\n\tint x;\n\n\t\/* keep in range *\/\n\tint offset = ((scanline - 8) \/ 8) * 64 + 42;\n\tif (offset < 0)\n\t\toffset += 0x7c0;\n\telse if (offset >= 0x7c0)\n\t\treturn;\n\n\t\/* update the current parameters *\/\n\tfor (x = 42; x < 64; x++)\n\t{\n\t\tuint16_t data = m_alpha_tilemap->basemem_read(offset++);\n\n\t\tswitch ((data >> 9) & 7)\n\t\t{\n\t\t\tcase 2:     \/* \/PFB *\/\n\t\t\t\tif (m_playfield_tile_bank != (data & 7))\n\t\t\t\t{\n\t\t\t\t\tscreen.update_partial(scanline - 1);\n\t\t\t\t\tm_playfield_tile_bank = data & 7;\n\t\t\t\t\tm_playfield_tilemap->mark_all_dirty();\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 3:     \/* \/PFHSLD *\/\n\t\t\t\tif (m_playfield_xscroll != (data & 0x1ff))\n\t\t\t\t{\n\t\t\t\t\tscreen.update_partial(scanline - 1);\n\t\t\t\t\tm_playfield_tilemap->set_scrollx(0, data);\n\t\t\t\t\tm_playfield_xscroll = data & 0x1ff;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 4:     \/* \/MOHS *\/\n\t\t\t\tif (m_mob->xscroll() != (data & 0x1ff))\n\t\t\t\t{\n\t\t\t\t\tscreen.update_partial(scanline - 1);\n\t\t\t\t\tm_mob->set_xscroll(data & 0x1ff);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 5:     \/* \/PFSPC *\/\n\t\t\t\tbreak;\n\n\t\t\tcase 6:     \/* \/VIRQ *\/\n\t\t\t\tscanline_int_gen(*m_maincpu);\n\t\t\t\tbreak;\n\n\t\t\tcase 7:     \/* \/PFVS *\/\n\t\t\t{\n\t\t\t\t\/* a new vscroll latches the offset into a counter; we must adjust for this *\/\n\t\t\t\tint offset = scanline;\n\t\t\t\tconst rectangle &visible_area = screen.visible_area();\n\t\t\t\tif (offset > visible_area.max_y)\n\t\t\t\t\toffset -= visible_area.max_y + 1;\n\n\t\t\t\tif (m_playfield_yscroll != ((data - offset) & 0x1ff))\n\t\t\t\t{\n\t\t\t\t\tscreen.update_partial(scanline - 1);\n\t\t\t\t\tm_playfield_tilemap->set_scrolly(0, data - offset);\n\t\t\t\t\tm_mob->set_yscroll((data - offset) & 0x1ff);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\/*************************************\n *\n *  Main refresh\n *\n *************************************\/\n\nuint32_t vindictr_state::screen_update_vindictr(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)\n{\n\t\/\/ start drawing\n\tm_mob->draw_async(cliprect);\n\n\t\/* draw the playfield *\/\n\tm_playfield_tilemap->draw(screen, bitmap, cliprect, 0, 0);\n\n\t\/\/ draw and merge the MO\n\tbitmap_ind16 &mobitmap = m_mob->bitmap();\n\tfor (const sparse_dirty_rect *rect = m_mob->first_dirty_rect(cliprect); rect != nullptr; rect = rect->next())\n\t\tfor (int y = rect->min_y; y <= rect->max_y; y++)\n\t\t{\n\t\t\tuint16_t *mo = &mobitmap.pix16(y);\n\t\t\tuint16_t *pf = &bitmap.pix16(y);\n\t\t\tfor (int x = rect->min_x; x <= rect->max_x; x++)\n\t\t\t\tif (mo[x] != 0xffff)\n\t\t\t\t{\n\t\t\t\t\t\/* partially verified via schematics (there are a lot of PALs involved!):\n\n\t\t\t\t\t    SHADE = PAL(MPR1-0, LB7-0, PFX6-5, PFX3-2, PF\/M)\n\n\t\t\t\t\t    if (SHADE)\n\t\t\t\t\t        CRA |= 0x100\n\n\t\t\t\t\t    MOG3-1 = ~MAT3-1 if MAT6==1 and MSD3==1\n\t\t\t\t\t*\/\n\t\t\t\t\tint mopriority = mo[x] >> atari_motion_objects_device::PRIORITY_SHIFT;\n\n\t\t\t\t\t\/* upper bit of MO priority signals special rendering and doesn't draw anything *\/\n\t\t\t\t\tif (mopriority & 4)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\/* MO pen 1 doesn't draw, but it sets the SHADE flag and bumps the palette offset *\/\n\t\t\t\t\tif ((mo[x] & 0x0f) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((mo[x] & 0xf0) != 0)\n\t\t\t\t\t\t\tpf[x] |= 0x100;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tpf[x] = mo[x] & atari_motion_objects_device::DATA_MASK;\n\n\t\t\t\t\t\/* don't erase yet -- we need to make another pass later *\/\n\t\t\t\t}\n\t\t}\n\n\t\/* add the alpha on top *\/\n\tm_alpha_tilemap->draw(screen, bitmap, cliprect, 0, 0);\n\n\t\/* now go back and process the upper bit of MO priority *\/\n\tfor (const sparse_dirty_rect *rect = m_mob->first_dirty_rect(cliprect); rect != nullptr; rect = rect->next())\n\t\tfor (int y = rect->min_y; y <= rect->max_y; y++)\n\t\t{\n\t\t\tuint16_t *mo = &mobitmap.pix16(y);\n\t\t\tuint16_t *pf = &bitmap.pix16(y);\n\t\t\tfor (int x = rect->min_x; x <= rect->max_x; x++)\n\t\t\t\tif (mo[x] != 0xffff)\n\t\t\t\t{\n\t\t\t\t\tint mopriority = mo[x] >> atari_motion_objects_device::PRIORITY_SHIFT;\n\n\t\t\t\t\t\/* upper bit of MO priority might mean palette kludges *\/\n\t\t\t\t\tif (mopriority & 4)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/* if bit 2 is set, start setting high palette bits *\/\n\t\t\t\t\t\tif (mo[x] & 2)\n\t\t\t\t\t\t\tm_mob->apply_stain(bitmap, pf, mo, x, y);\n\n\t\t\t\t\t\t\/* if the upper bit of pen data is set, we adjust the final intensity *\/\n\t\t\t\t\t\tif (mo[x] & 8)\n\t\t\t\t\t\t\tpf[x] |= (~mo[x] & 0xe0) << 6;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\treturn 0;\n}\n","avg_line_length":27.8535714286,"max_line_length":119,"alphanum_fraction":0.547377869,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":320,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":85.0,"content":"#include <string_view>\n#include <iostream>\n#include <clue\/clue.h>\n\nint main(int argc, char** argv) {\n    clue::CommandLine cl(\"Add\", \"Add two numbers\");\n\n    int a, b;\n    cl.Positional(&a);\n    cl.Positional(&b);\n\n    cl.ParseArgs(argc, argv, clue::kRequired | clue::kNoDefault);\n    std::cout << a + b << std::endl;\n}\n","avg_line_length":21.3333333333,"max_line_length":65,"alphanum_fraction":0.615625,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3717,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":89.0,"content":"\/\/\n\/\/ Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton\n\/\/ Copyright (C) 2015 Vadim Zeitlin\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n\n#define SOCI_SOURCE\n\n#include \"soci\/error.h\"\n\n#include <sstream>\n#include <vector>\n\nnamespace soci\n{\n\nclass soci_error_extra_info\n{\npublic:\n    soci_error_extra_info()\n    {\n    }\n\n    \/\/ Default copy ctor, assignment operator and dtor are fine.\n\n    char const* get_full_message(std::string const& message)\n    {\n        if (full_message_.empty())\n        {\n            full_message_ = message;\n\n            if (!contexts_.empty())\n            {\n                \/\/ This is a hack, but appending the extra context to the\n                \/\/ message looks much better if we remove the full stop at its\n                \/\/ end first.\n                if (*full_message_.rbegin() == '.')\n                    full_message_.erase(full_message_.size() - 1);\n\n                \/\/ Now do append all the extra context we have.\n                typedef std::vector<std::string>::const_iterator iter_type;\n                for (iter_type i = contexts_.begin(); i != contexts_.end(); ++i)\n                {\n                    full_message_ += \" \";\n                    full_message_ += *i;\n                }\n\n                \/\/ It seems better to always terminate the full message with a\n                \/\/ full stop, even if the original error message didn't have it\n                \/\/ (and if it had, we just restore the one we chopped off).\n                full_message_ += \".\";\n            }\n        }\n\n        return full_message_.c_str();\n    }\n\n    void add_context(std::string const& context)\n    {\n        full_message_.clear();\n        contexts_.push_back(context);\n    }\n\nprivate:\n    \/\/ The full error message, we need to store it as a string as we return a\n    \/\/ pointer to its contents from get_full_message().\n    std::string full_message_;\n\n    \/\/ If non-empty, contains extra context for this exception, e.g.\n    \/\/ information about the SQL statement that resulted in it, with the top\n    \/\/ element corresponding to the most global context.\n    std::vector<std::string> contexts_;\n};\n\nnamespace\n{\n\n\/\/ Make a safe, even in presence of exceptions, heap-allocated copy of the\n\/\/ given object if it's non-null (otherwise just return null pointer).\nsoci_error_extra_info *make_safe_copy(soci_error_extra_info* info)\n{\n    try\n    {\n        return info ? new soci_error_extra_info(*info) : NULL;\n    }\n    catch (...)\n    {\n        \/\/ Copy ctor of an exception class shouldn't throw to avoid program\n        \/\/ termination, so it's better to lose the extra information than allow\n        \/\/ an exception to except from here.\n        return NULL;\n    }\n}\n\n} \/\/ anonymous namespace\n\nsoci_error::soci_error(std::string const & msg)\n     : std::runtime_error(msg)\n{\n    info_ = NULL;\n}\n\nsoci_error::soci_error(soci_error const& e)\n    : std::runtime_error(e)\n{\n    info_ = make_safe_copy(e.info_);\n}\n\nsoci_error& soci_error::operator=(soci_error const& e)\n{\n    std::runtime_error::operator=(e);\n\n    delete info_;\n    info_ = make_safe_copy(e.info_);\n\n    return *this;\n}\n\nsoci_error::~soci_error() throw()\n{\n    delete info_;\n}\n\nstd::string soci_error::get_error_message() const\n{\n    return std::runtime_error::what();\n}\n\nchar const* soci_error::what() const throw()\n{\n    if (info_)\n        return info_->get_full_message(get_error_message());\n\n    return std::runtime_error::what();\n}\n\nvoid soci_error::add_context(std::string const& context)\n{\n    if (!info_)\n        info_ = new soci_error_extra_info();\n\n    info_->add_context(context);\n}\n\n} \/\/ namespace soci\n","avg_line_length":25.1148648649,"max_line_length":80,"alphanum_fraction":0.6198547215,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2807,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"lexer.h\"\n#include \"syntaxerror.h\"\n\n#include <QDebug>\n\nLexer::Lexer(QString text, bool debug)\n    : m_text(text)\n    , m_debug(debug)\n    , m_pos(0)\n{\n    m_currentChar = text[m_pos];\n    this->debug(QString(\"Will parse '%1'\").arg(m_text));\n}\n\nvoid Lexer::debug(QString message)\n{\n    if (m_debug) {\n        qDebug() << message;\n    }\n}\n\nvoid Lexer::skipWhitespace()\n{\n    while (m_currentChar.isSpace()) {\n        advance();\n    }\n}\n\nint Lexer::integer()\n{\n    debug(QString(\"INT\"));\n    QString result;\n    while (m_currentChar.isDigit()) {\n        result += m_currentChar;\n        advance();\n    }\n    debug(QString(\"INT: Found chars in digit: %1\").arg(result));\n    bool ok;\n    int castedResult = result.toInt(&ok);\n    debug(QString(\"INT: Casting ok: %1, with result: %2\").arg(ok).arg(castedResult));\n    if (!ok) {\n        throw new SyntaxError(\"INT: Syntax error\");\n    }\n\n    return castedResult;\n}\n\nToken Lexer::getNextToken()\n{\n    debug(QString(\"GNT %1 at %2\").arg(long(this)).arg(m_pos));\n    while (!m_currentChar.isNull()) {\n        if (m_currentChar.isSpace()) {\n            debug(QString(\"GNT: Skipping spaces\"));\n            skipWhitespace();\n            continue;\n        }\n\n        if (m_currentChar.isDigit()) {\n            debug(QString(\"GNT: Found digit\"));\n            return Token(Token::Type::INTEGER, integer());\n        }\n\n        if (m_currentChar == '+') {\n            debug(QString(\"GNT: Found +\"));\n            advance();\n            return Token(Token::Type::PLUS);\n        }\n\n        if (m_currentChar == '(') {\n            debug(QString(\"GNT: Found (\"));\n            advance();\n            return Token(Token::Type::LPAREN);\n        }\n\n        if (m_currentChar == ')') {\n            debug(QString(\"GNT: Found )\"));\n            advance();\n            return Token(Token::Type::RPAREN);\n        }\n\n        if (m_currentChar == '-') {\n            debug(QString(\"GNT: Found -\"));\n            advance();\n            return Token(Token::Type::MINUS);\n        }\n\n        if (m_currentChar == '*') {\n            debug(QString(\"GNT: Found *\"));\n            advance();\n            return Token(Token::Type::MULT);\n        }\n\n        if (m_currentChar == '\/') {\n            debug(QString(\"GNT: Found \/\"));\n            advance();\n            return Token(Token::Type::DIV);\n        }\n        debug(QString(\"GNT: Did not find token: %1\").arg(m_currentChar));\n        QString error = QString(\"GNT: Unexpected token: %1\").arg(m_currentChar);\n        throw new SyntaxError(error.toLocal8Bit().constData());\n    }\n\n    return Token(Token::Type::TEOF);\n}\n\nvoid Lexer::advance()\n{\n    m_pos++;\n    debug(QString(\"ADVANCE to %1\").arg(m_pos));\n    if (m_pos > m_text.length() - 1) {\n        m_currentChar = QChar::Null;\n    } else {\n        m_currentChar = m_text.at(m_pos);\n    }\n}\n","avg_line_length":24.1982758621,"max_line_length":85,"alphanum_fraction":0.5258282864,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10103,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause-LBNL"],"max_stars_count":null,"content":"\/* Copyright 2020 Remi Lehe\n *\n * This file is part of WarpX.\n *\n * License: BSD-3-Clause-LBNL\n *\/\n#include \"FieldSolver\/FiniteDifferenceSolver\/FiniteDifferenceSolver.H\"\n\n#include \"BoundaryConditions\/PML.H\"\n#include \"BoundaryConditions\/PMLComponent.H\"\n#include \"BoundaryConditions\/PML_current.H\"\n#ifndef WARPX_DIM_RZ\n#   include \"FieldSolver\/FiniteDifferenceSolver\/FiniteDifferenceAlgorithms\/CartesianYeeAlgorithm.H\"\n#   include \"FieldSolver\/FiniteDifferenceSolver\/FiniteDifferenceAlgorithms\/CartesianCKCAlgorithm.H\"\n#   include \"FieldSolver\/FiniteDifferenceSolver\/FiniteDifferenceAlgorithms\/CartesianNodalAlgorithm.H\"\n#else\n#   include \"FieldSolver\/FiniteDifferenceSolver\/FiniteDifferenceAlgorithms\/CylindricalYeeAlgorithm.H\"\n#endif\n#include \"Utils\/TextMsg.H\"\n#include \"Utils\/WarpXAlgorithmSelection.H\"\n#include \"Utils\/WarpXConst.H\"\n\n#include <AMReX.H>\n#include <AMReX_Array4.H>\n#include <AMReX_Config.H>\n#include <AMReX_Extension.H>\n#include <AMReX_FabArray.H>\n#include <AMReX_GpuContainers.H>\n#include <AMReX_GpuControl.H>\n#include <AMReX_GpuLaunch.H>\n#include <AMReX_GpuQualifiers.H>\n#include <AMReX_IndexType.H>\n#include <AMReX_MFIter.H>\n#include <AMReX_MultiFab.H>\n#include <AMReX_REAL.H>\n\n#include <AMReX_BaseFwd.H>\n\n#include <array>\n\nusing namespace amrex;\n\n\/**\n * \\brief Update the E field, over one timestep\n *\/\nvoid FiniteDifferenceSolver::EvolveEPML (\n    std::array< amrex::MultiFab*, 3 > Efield,\n    std::array< amrex::MultiFab*, 3 > const Bfield,\n    std::array< amrex::MultiFab*, 3 > const Jfield,\n    std::array< amrex::MultiFab*, 3 > const edge_lengths,\n    amrex::MultiFab* const Ffield,\n    MultiSigmaBox const& sigba,\n    amrex::Real const dt, bool pml_has_particles ) {\n\n   \/\/ Select algorithm (The choice of algorithm is a runtime option,\n   \/\/ but we compile code for each algorithm, using templates)\n#ifdef WARPX_DIM_RZ\n    amrex::ignore_unused(Efield, Bfield, Jfield, Ffield, sigba, dt, pml_has_particles, edge_lengths);\n    amrex::Abort(Utils::TextMsg::Err(\n        \"PML are not implemented in cylindrical geometry.\"));\n#else\n    if (m_do_nodal) {\n\n        EvolveEPMLCartesian <CartesianNodalAlgorithm> (\n            Efield, Bfield, Jfield, edge_lengths, Ffield, sigba, dt, pml_has_particles );\n\n    } else if (m_fdtd_algo == MaxwellSolverAlgo::Yee || m_fdtd_algo == MaxwellSolverAlgo::ECT) {\n\n        EvolveEPMLCartesian <CartesianYeeAlgorithm> (\n            Efield, Bfield, Jfield,  edge_lengths, Ffield, sigba, dt, pml_has_particles );\n\n    } else if (m_fdtd_algo == MaxwellSolverAlgo::CKC) {\n\n        EvolveEPMLCartesian <CartesianCKCAlgorithm> (\n            Efield, Bfield, Jfield,  edge_lengths, Ffield, sigba, dt, pml_has_particles );\n\n    } else {\n        amrex::Abort(Utils::TextMsg::Err(\"EvolveEPML: Unknown algorithm\"));\n    }\n#endif\n}\n\n\n#ifndef WARPX_DIM_RZ\n\ntemplate<typename T_Algo>\nvoid FiniteDifferenceSolver::EvolveEPMLCartesian (\n    std::array< amrex::MultiFab*, 3 > Efield,\n    std::array< amrex::MultiFab*, 3 > const Bfield,\n    std::array< amrex::MultiFab*, 3 > const Jfield,\n    std::array< amrex::MultiFab*, 3 > const edge_lengths,\n    amrex::MultiFab* const Ffield,\n    MultiSigmaBox const& sigba,\n    amrex::Real const dt, bool pml_has_particles ) {\n\n    Real c2 = PhysConst::c * PhysConst::c;\n\n#ifdef WARPX_MAG_LLG\n    c2 *= PhysConst::mu0;\n#endif\n\n    \/\/ Loop through the grids, and over the tiles within each grid\n#ifdef AMREX_USE_OMP\n#pragma omp parallel if (amrex::Gpu::notInLaunchRegion())\n#endif\n    for ( MFIter mfi(*Efield[0], TilingIfNotGPU()); mfi.isValid(); ++mfi ) {\n\n        \/\/ Extract field data for this grid\/tile\n        Array4<Real> const& Ex = Efield[0]->array(mfi);\n        Array4<Real> const& Ey = Efield[1]->array(mfi);\n        Array4<Real> const& Ez = Efield[2]->array(mfi);\n        Array4<Real> const& Bx = Bfield[0]->array(mfi);\n        Array4<Real> const& By = Bfield[1]->array(mfi);\n        Array4<Real> const& Bz = Bfield[2]->array(mfi);\n\n#ifdef AMREX_USE_EB\n        Array4<Real> const& lx = edge_lengths[0]->array(mfi);\n        Array4<Real> const& ly = edge_lengths[1]->array(mfi);\n        Array4<Real> const& lz = edge_lengths[2]->array(mfi);\n#endif\n\n        \/\/ Extract stencil coefficients\n        Real const * const AMREX_RESTRICT coefs_x = m_stencil_coefs_x.dataPtr();\n        int const n_coefs_x = m_stencil_coefs_x.size();\n        Real const * const AMREX_RESTRICT coefs_y = m_stencil_coefs_y.dataPtr();\n        int const n_coefs_y = m_stencil_coefs_y.size();\n        Real const * const AMREX_RESTRICT coefs_z = m_stencil_coefs_z.dataPtr();\n        int const n_coefs_z = m_stencil_coefs_z.size();\n\n        \/\/ Extract tileboxes for which to loop\n        Box const& tex  = mfi.tilebox(Efield[0]->ixType().ixType());\n        Box const& tey  = mfi.tilebox(Efield[1]->ixType().ixType());\n        Box const& tez  = mfi.tilebox(Efield[2]->ixType().ixType());\n\n        \/\/ Loop over the cells and update the fields\n        amrex::ParallelFor(tex, tey, tez,\n\n            [=] AMREX_GPU_DEVICE (int i, int j, int k){\n#ifdef AMREX_USE_EB\n                if(lx(i, j, k) <= 0) return;\n#endif\n\n                Ex(i, j, k, PMLComp::xz) -= c2 * dt * (\n                    T_Algo::DownwardDz(By, coefs_z, n_coefs_z, i, j, k, PMLComp::yx)\n                  + T_Algo::DownwardDz(By, coefs_z, n_coefs_z, i, j, k, PMLComp::yz) );\n                Ex(i, j, k, PMLComp::xy) += c2 * dt * (\n                    T_Algo::DownwardDy(Bz, coefs_y, n_coefs_y, i, j, k, PMLComp::zx)\n                  + T_Algo::DownwardDy(Bz, coefs_y, n_coefs_y, i, j, k, PMLComp::zy) );\n            },\n\n            [=] AMREX_GPU_DEVICE (int i, int j, int k){\n#ifdef AMREX_USE_EB\n                if(ly(i, j, k)<=0) return;\n#endif\n\n                Ey(i, j, k, PMLComp::yx) -= c2 * dt * (\n                    T_Algo::DownwardDx(Bz, coefs_x, n_coefs_x, i, j, k, PMLComp::zx)\n                  + T_Algo::DownwardDx(Bz, coefs_x, n_coefs_x, i, j, k, PMLComp::zy) );\n                Ey(i, j, k, PMLComp::yz) += c2 * dt * (\n                    T_Algo::DownwardDz(Bx, coefs_z, n_coefs_z, i, j, k, PMLComp::xy)\n                  + T_Algo::DownwardDz(Bx, coefs_z, n_coefs_z, i, j, k, PMLComp::xz) );\n            },\n\n            [=] AMREX_GPU_DEVICE (int i, int j, int k){\n#ifdef AMREX_USE_EB\n                if(lz(i, j, k) <= 0) return;\n#endif\n\n                Ez(i, j, k, PMLComp::zy) -= c2 * dt * (\n                    T_Algo::DownwardDy(Bx, coefs_y, n_coefs_y, i, j, k, PMLComp::xy)\n                  + T_Algo::DownwardDy(Bx, coefs_y, n_coefs_y, i, j, k, PMLComp::xz) );\n                Ez(i, j, k, PMLComp::zx) += c2 * dt * (\n                    T_Algo::DownwardDx(By, coefs_x, n_coefs_x, i, j, k, PMLComp::yx)\n                  + T_Algo::DownwardDx(By, coefs_x, n_coefs_x, i, j, k, PMLComp::yz) );\n            }\n\n        );\n\n        \/\/ If F is not a null pointer, further update E using the grad(F) term\n        \/\/ (hyperbolic correction for errors in charge conservation)\n        if (Ffield) {\n            \/\/ Extract field data for this grid\/tile\n            Array4<Real> const& F = Ffield->array(mfi);\n\n            \/\/ Loop over the cells and update the fields\n            amrex::ParallelFor(tex, tey, tez,\n\n                [=] AMREX_GPU_DEVICE (int i, int j, int k){\n                    Ex(i, j, k, PMLComp::xx) += c2 * dt * (\n                        T_Algo::UpwardDx(F, coefs_x, n_coefs_x, i, j, k, PMLComp::x)\n                      + T_Algo::UpwardDx(F, coefs_x, n_coefs_x, i, j, k, PMLComp::y)\n                      + T_Algo::UpwardDx(F, coefs_x, n_coefs_x, i, j, k, PMLComp::z) );\n                },\n                [=] AMREX_GPU_DEVICE (int i, int j, int k){\n                    Ey(i, j, k, PMLComp::yy) += c2 * dt * (\n                        T_Algo::UpwardDy(F, coefs_y, n_coefs_y, i, j, k, PMLComp::x)\n                      + T_Algo::UpwardDy(F, coefs_y, n_coefs_y, i, j, k, PMLComp::y)\n                      + T_Algo::UpwardDy(F, coefs_y, n_coefs_y, i, j, k, PMLComp::z) );\n                },\n                [=] AMREX_GPU_DEVICE (int i, int j, int k){\n                    Ez(i, j, k, PMLComp::zz) += c2 * dt * (\n                        T_Algo::UpwardDz(F, coefs_z, n_coefs_z, i, j, k, PMLComp::x)\n                      + T_Algo::UpwardDz(F, coefs_z, n_coefs_z, i, j, k, PMLComp::y)\n                      + T_Algo::UpwardDz(F, coefs_z, n_coefs_z, i, j, k, PMLComp::z) );\n                }\n            );\n        }\n\n        \/\/ Update the E field in the PML, using the current\n        \/\/ deposited by the particles in the PML\n        if (pml_has_particles) {\n\n            \/\/ Extract field data for this grid\/tile\n            Array4<Real> const& Jx = Jfield[0]->array(mfi);\n            Array4<Real> const& Jy = Jfield[1]->array(mfi);\n            Array4<Real> const& Jz = Jfield[2]->array(mfi);\n            const Real* sigmaj_x = sigba[mfi].sigma[0].data();\n            const Real* sigmaj_y = sigba[mfi].sigma[1].data();\n            const Real* sigmaj_z = sigba[mfi].sigma[2].data();\n            int const x_lo = sigba[mfi].sigma[0].lo();\n#if defined(WARPX_DIM_3D)\n            int const y_lo = sigba[mfi].sigma[1].lo();\n            int const z_lo = sigba[mfi].sigma[2].lo();\n#else\n            int const y_lo = 0;\n            int const z_lo = sigba[mfi].sigma[1].lo();\n#endif\n            const Real mu_c2_dt = (PhysConst::mu0*PhysConst::c*PhysConst::c) * dt;\n\n            amrex::ParallelFor( tex, tey, tez,\n                [=] AMREX_GPU_DEVICE (int i, int j, int k) {\n                    push_ex_pml_current(i, j, k, Ex, Jx,\n                        sigmaj_y, sigmaj_z, y_lo, z_lo, mu_c2_dt);\n                },\n                [=] AMREX_GPU_DEVICE (int i, int j, int k) {\n                    push_ey_pml_current(i, j, k, Ey, Jy,\n                        sigmaj_x, sigmaj_z, x_lo, z_lo, mu_c2_dt);\n                },\n                [=] AMREX_GPU_DEVICE (int i, int j, int k) {\n                    push_ez_pml_current(i, j, k, Ez, Jz,\n                        sigmaj_x, sigmaj_y, x_lo, y_lo, mu_c2_dt);\n                }\n            );\n        }\n\n    }\n\n#ifndef AMREX_USE_EB\n    amrex::ignore_unused(edge_lengths);\n#endif\n\n}\n\n#endif \/\/ corresponds to ifndef WARPX_DIM_RZ\n","avg_line_length":39.6196078431,"max_line_length":101,"alphanum_fraction":0.589923785,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":16328,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":115.0,"content":"\/*\n  FirmataMarshaller.cpp\n  Copyright (c) 2006-2008 Hans-Christoph Steiner.  All rights reserved.\n  Copyright (C) 2009-2016 Jeff Hoefs.  All rights reserved.\n\n  This library is free software; you can redistribute it and\/or\n  modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  See file LICENSE.txt for further informations on licensing terms.\n*\/\n\n\/\/******************************************************************************\n\/\/* Includes\n\/\/******************************************************************************\n\n#include \"FirmataMarshaller.h\"\n\n#if defined(__cplusplus) && !defined(ARDUINO)\n#include <cstring>\n#else\n#include <string.h>\n#endif\n\n#include \"FirmataConstants.h\"\n\nusing namespace firmata;\n\n\/\/******************************************************************************\n\/\/* Support Functions\n\/\/******************************************************************************\n\n\/**\n * Request or halt a stream of analog readings from the Firmata host application. The range of pins is\n * limited to [0..15] when using the REPORT_ANALOG. The maximum result of the REPORT_ANALOG is limited to 14 bits\n * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG\n * message.\n * @param pin The analog pin for which to request the value (limited to pins 0 - 15).\n * @param stream_enable A zero value will disable the stream, a non-zero will enable the stream\n * @note The maximum resulting value is 14-bits (16384).\n *\/\nvoid FirmataMarshaller::reportAnalog(uint8_t pin, bool stream_enable)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    \/\/ pin can only be 0-15, so chop higher bits\n    FirmataStream->write(REPORT_ANALOG | (pin & 0xF));\n    FirmataStream->write(stream_enable);\n}\n\n\/**\n * Request or halt an 8-bit port stream from the Firmata host application (protocol v2 and later).\n * Send 14-bits in a single digital message (protocol v1).\n * @param portNumber The port number for which to request the value. Note that this is not the same as a \"port\" on the\n * physical microcontroller. Ports are defined in order per every 8 pins in ascending order\n * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc.\n * @param stream_enable A zero value will disable the stream, a non-zero will enable the stream\n *\/\nvoid FirmataMarshaller::reportDigitalPort(uint8_t portNumber, bool stream_enable)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    FirmataStream->write(REPORT_DIGITAL | (portNumber & 0xF));\n    FirmataStream->write(stream_enable);\n}\n\n\/**\n * An alternative to the normal analog message, this extended version allows addressing beyond\n * pin 15 and supports sending analog values with any number of bits.\n * @param pin The analog pin to which the value is sent.\n * @param bytec The size of the storage for the analog value\n * @param bytev The pointer to the location of the analog value\n *\/\nvoid FirmataMarshaller::sendExtendedAnalog(uint8_t pin, size_t bytec, uint8_t *bytev)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    FirmataStream->write(START_SYSEX);\n    FirmataStream->write(EXTENDED_ANALOG);\n    FirmataStream->write(pin);\n    encodeByteStream(bytec, bytev, bytec);\n    FirmataStream->write(END_SYSEX);\n}\n\n\/**\n * Transform 8-bit stream into 7-bit message\n * @param bytec The number of data bytes in the message.\n * @param bytev A pointer to the array of data bytes to send in the message.\n * @param max_bytes Force message to be n bytes, regardless of data bits.\n *\/\nvoid FirmataMarshaller::encodeByteStream (size_t bytec, uint8_t *bytev, size_t max_bytes)\nconst\n{\n    static const size_t transmit_bits = 7;\n    static const uint8_t transmit_mask = ((1 << transmit_bits) - 1);\n\n    size_t bytes_sent = 0;\n    size_t outstanding_bits = 0;\n    uint8_t outstanding_bit_cache = *bytev;\n\n    if ( !max_bytes )\n    {\n        max_bytes = static_cast<size_t>(-1);\n    }\n    for (size_t i = 0 ; (i < bytec) && (bytes_sent < max_bytes) ; ++i)\n    {\n        uint8_t transmit_byte = (outstanding_bit_cache | (bytev[i] << outstanding_bits));\n        FirmataStream->write(transmit_mask & transmit_byte);\n        ++bytes_sent;\n        outstanding_bit_cache = (bytev[i] >> (transmit_bits - outstanding_bits));\n        outstanding_bits = (outstanding_bits + (8 - transmit_bits));\n        for ( ; (outstanding_bits >= transmit_bits) && (bytes_sent < max_bytes) ; )\n        {\n            transmit_byte = outstanding_bit_cache;\n            FirmataStream->write(transmit_mask & transmit_byte);\n            ++bytes_sent;\n            outstanding_bit_cache >>= transmit_bits;\n            outstanding_bits -= transmit_bits;\n        }\n    }\n    if ( outstanding_bits && (bytes_sent < max_bytes) )\n    {\n        FirmataStream->write(static_cast<uint8_t>((1 << outstanding_bits) - 1) & outstanding_bit_cache);\n    }\n}\n\n\/\/******************************************************************************\n\/\/* Constructors\n\/\/******************************************************************************\n\n\/**\n * The FirmataMarshaller class.\n *\/\nFirmataMarshaller::FirmataMarshaller()\n    :\n    FirmataStream((Stream *)NULL)\n{\n}\n\n\/\/******************************************************************************\n\/\/* Public Methods\n\/\/******************************************************************************\n\n\/**\n * Reassign the Firmata stream transport.\n * @param s A reference to the Stream transport object. This can be any type of\n * transport that implements the Stream interface. Some examples include Ethernet, WiFi\n * and other UARTs on the board (Serial1, Serial2, etc).\n *\/\nvoid FirmataMarshaller::begin(Stream &s)\n{\n    FirmataStream = &s;\n}\n\n\/**\n * Closes the FirmataMarshaller stream by setting its stream reference to `(Stream *)NULL`\n *\/\nvoid FirmataMarshaller::end(void)\n{\n    FirmataStream = (Stream *)NULL;\n}\n\n\/\/******************************************************************************\n\/\/* Output Stream Handling\n\/\/******************************************************************************\n\n\/**\n * Query the target's firmware name and version\n *\/\nvoid FirmataMarshaller::queryFirmwareVersion(void)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    FirmataStream->write(START_SYSEX);\n    FirmataStream->write(REPORT_FIRMWARE);\n    FirmataStream->write(END_SYSEX);\n}\n\n\/**\n * Query the target's Firmata protocol version\n *\/\nvoid FirmataMarshaller::queryVersion(void)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    FirmataStream->write(REPORT_VERSION);\n}\n\n\/**\n * Halt the stream of analog readings from the Firmata host application. The range of pins is\n * limited to [0..15] when using the REPORT_ANALOG. The maximum result of the REPORT_ANALOG is limited to 14 bits\n * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG\n * message.\n * @param pin The analog pin for which to request the value (limited to pins 0 - 15).\n *\/\nvoid FirmataMarshaller::reportAnalogDisable(uint8_t pin)\nconst\n{\n    reportAnalog(pin, false);\n}\n\n\/**\n * Request a stream of analog readings from the Firmata host application. The range of pins is\n * limited to [0..15] when using the REPORT_ANALOG. The maximum result of the REPORT_ANALOG is limited to 14 bits\n * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG\n * message.\n * @param pin The analog pin for which to request the value (limited to pins 0 - 15).\n *\/\nvoid FirmataMarshaller::reportAnalogEnable(uint8_t pin)\nconst\n{\n    reportAnalog(pin, true);\n}\n\n\/**\n * Halt an 8-bit port stream from the Firmata host application (protocol v2 and later).\n * Send 14-bits in a single digital message (protocol v1).\n * @param portNumber The port number for which to request the value. Note that this is not the same as a \"port\" on the\n * physical microcontroller. Ports are defined in order per every 8 pins in ascending order\n * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc.\n *\/\nvoid FirmataMarshaller::reportDigitalPortDisable(uint8_t portNumber)\nconst\n{\n    reportDigitalPort(portNumber, false);\n}\n\n\/**\n * Request an 8-bit port stream from the Firmata host application (protocol v2 and later).\n * Send 14-bits in a single digital message (protocol v1).\n * @param portNumber The port number for which to request the value. Note that this is not the same as a \"port\" on the\n * physical microcontroller. Ports are defined in order per every 8 pins in ascending order\n * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc.\n *\/\nvoid FirmataMarshaller::reportDigitalPortEnable(uint8_t portNumber)\nconst\n{\n    reportDigitalPort(portNumber, true);\n}\n\n\/**\n * Send an analog message to the Firmata host application. The range of pins is limited to [0..15]\n * when using the ANALOG_MESSAGE. The maximum value of the ANALOG_MESSAGE is limited to 14 bits\n * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG\n * message.\n * @param pin The analog pin to which the value is sent.\n * @param value The value of the analog pin (0 - 1024 for 10-bit analog, 0 - 4096 for 12-bit, etc).\n * @note The maximum value is 14-bits (16384).\n *\/\nvoid FirmataMarshaller::sendAnalog(uint8_t pin, uint16_t value)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    if ( (0xF >= pin) && (0x3FFF >= value) )\n    {\n        FirmataStream->write(ANALOG_MESSAGE | pin);\n        encodeByteStream(sizeof(value), reinterpret_cast<uint8_t *>(&value), sizeof(value));\n    }\n    else\n    {\n        sendExtendedAnalog(pin, sizeof(value), reinterpret_cast<uint8_t *>(&value));\n    }\n}\n\n\/**\n * Send an analog mapping query to the Firmata host application. The resulting sysex message will\n * have an ANALOG_MAPPING_RESPONSE command byte, followed by a list of pins [0-n]; where each\n * pin will specify its corresponding analog pin number or 0x7F (127) if not applicable.\n *\/\nvoid FirmataMarshaller::sendAnalogMappingQuery(void)\nconst\n{\n    sendSysex(ANALOG_MAPPING_QUERY, 0, NULL);\n}\n\n\/**\n * Send a capability query to the Firmata host application. The resulting sysex message will have\n * a CAPABILITY_RESPONSE command byte, followed by a list of byte tuples (mode and mode resolution)\n * for each pin; where each pin list is terminated by 0x7F (127).\n *\/\nvoid FirmataMarshaller::sendCapabilityQuery(void)\nconst\n{\n    sendSysex(CAPABILITY_QUERY, 0, NULL);\n}\n\n\/**\n * Send a single digital pin value to the Firmata host application.\n * @param pin The digital pin to send the value of.\n * @param value The value of the pin.\n *\/\nvoid FirmataMarshaller::sendDigital(uint8_t pin, uint8_t value)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    FirmataStream->write(SET_DIGITAL_PIN_VALUE);\n    FirmataStream->write(pin & 0x7F);\n    FirmataStream->write(value != 0);\n}\n\n\n\/**\n * Send an 8-bit port in a single digital message (protocol v2 and later).\n * Send 14-bits in a single digital message (protocol v1).\n * @param portNumber The port number to send. Note that this is not the same as a \"port\" on the\n * physical microcontroller. Ports are defined in order per every 8 pins in ascending order\n * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc.\n * @param portData The value of the port. The value of each pin in the port is represented by a bit.\n *\/\nvoid FirmataMarshaller::sendDigitalPort(uint8_t portNumber, uint16_t portData)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    FirmataStream->write(DIGITAL_MESSAGE | (portNumber & 0xF));\n    \/\/ Tx bits  0-6 (protocol v1 and higher)\n    \/\/ Tx bits 7-13 (bit 7 only for protocol v2 and higher)\n    encodeByteStream(sizeof(portData), reinterpret_cast<uint8_t *>(&portData), sizeof(portData));\n}\n\n\/**\n * Sends the firmware name and version to the Firmata host application.\n * @param major The major verison number\n * @param minor The minor version number\n * @param bytec The length of the firmware name\n * @param bytev The firmware name array\n *\/\nvoid FirmataMarshaller::sendFirmwareVersion(uint8_t major, uint8_t minor, size_t bytec, uint8_t *bytev)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    size_t i;\n    FirmataStream->write(START_SYSEX);\n    FirmataStream->write(REPORT_FIRMWARE);\n    FirmataStream->write(major);\n    FirmataStream->write(minor);\n    for (i = 0; i < bytec; ++i)\n    {\n        encodeByteStream(sizeof(bytev[i]), reinterpret_cast<uint8_t *>(&bytev[i]));\n    }\n    FirmataStream->write(END_SYSEX);\n}\n\n\/**\n * Send the Firmata protocol version to the Firmata host application.\n * @param major The major verison number\n * @param minor The minor version number\n *\/\nvoid FirmataMarshaller::sendVersion(uint8_t major, uint8_t minor)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    FirmataStream->write(REPORT_VERSION);\n    FirmataStream->write(major);\n    FirmataStream->write(minor);\n}\n\n\/**\n * Send the pin mode\/configuration. The pin configuration (or mode) in Firmata represents the\n * current function of the pin. Examples are digital input or output, analog input, pwm, i2c,\n * serial (uart), etc.\n * @param pin The pin to configure.\n * @param config The configuration value for the specified pin.\n *\/\nvoid FirmataMarshaller::sendPinMode(uint8_t pin, uint8_t config)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    FirmataStream->write(SET_PIN_MODE);\n    FirmataStream->write(pin);\n    FirmataStream->write(config);\n}\n\n\/**\n * Send a pin state query to the Firmata host application. The resulting sysex message will have\n * a PIN_STATE_RESPONSE command byte, followed by the pin number, the pin mode and a stream of\n * bits to indicate any *data* written to the pin (pin state).\n * @param pin The pin to query\n * @note The pin state is any data written to the pin (i.e. pin state != pin value)\n *\/\nvoid FirmataMarshaller::sendPinStateQuery(uint8_t pin)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    FirmataStream->write(START_SYSEX);\n    FirmataStream->write(PIN_STATE_QUERY);\n    FirmataStream->write(pin);\n    FirmataStream->write(END_SYSEX);\n}\n\n\/**\n * Send a sysex message where all values after the command byte are packet as 2 7-bit bytes\n * (this is not always the case so this function is not always used to send sysex messages).\n * @param command The sysex command byte.\n * @param bytec The number of data bytes in the message (excludes start, command and end bytes).\n * @param bytev A pointer to the array of data bytes to send in the message.\n *\/\nvoid FirmataMarshaller::sendSysex(uint8_t command, size_t bytec, uint8_t *bytev)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    size_t i;\n    FirmataStream->write(START_SYSEX);\n    FirmataStream->write(command);\n    for (i = 0; i < bytec; ++i)\n    {\n        encodeByteStream(sizeof(bytev[i]), reinterpret_cast<uint8_t *>(&bytev[i]));\n    }\n    FirmataStream->write(END_SYSEX);\n}\n\n\/**\n * Send a string to the Firmata host application.\n * @param string A pointer to the char string\n *\/\nvoid FirmataMarshaller::sendString(const char *string)\nconst\n{\n    sendSysex(STRING_DATA, strlen(string), reinterpret_cast<uint8_t *>(const_cast<char *>(string)));\n}\n\n\/**\n * The sampling interval sets how often analog data and i2c data is reported to the client.\n * @param interval_ms The interval (in milliseconds) at which to sample\n * @note The default sampling interval is 19ms\n *\/\nvoid FirmataMarshaller::setSamplingInterval(uint16_t interval_ms)\nconst\n{\n    sendSysex(SAMPLING_INTERVAL, sizeof(interval_ms), reinterpret_cast<uint8_t *>(&interval_ms));\n}\n\n\/**\n * Perform a software reset on the target. For example, StandardFirmata.ino will initialize\n * everything to a known state and reset the parsing buffer.\n *\/\nvoid FirmataMarshaller::systemReset(void)\nconst\n{\n    if ( (Stream *)NULL == FirmataStream )\n    {\n        return;\n    }\n    FirmataStream->write(SYSTEM_RESET);\n}\n","avg_line_length":33.6659793814,"max_line_length":118,"alphanum_fraction":0.6713008329,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4427,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2.0,"content":"\ufeff\/*\n* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\").\n* You may not use this file except in compliance with the License.\n* A copy of the License is located at\n*\n*  http:\/\/aws.amazon.com\/apache2.0\n*\n* or in the \"license\" file accompanying this file. This file is distributed\n* on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n* express or implied. See the License for the specific language governing\n* permissions and limitations under the License.\n*\/\n\n#include <aws\/apigatewayv2\/model\/UpdateIntegrationResult.h>\n#include <aws\/core\/utils\/json\/JsonSerializer.h>\n#include <aws\/core\/AmazonWebServiceResult.h>\n#include <aws\/core\/utils\/StringUtils.h>\n#include <aws\/core\/utils\/UnreferencedParam.h>\n\n#include <utility>\n\nusing namespace Aws::ApiGatewayV2::Model;\nusing namespace Aws::Utils::Json;\nusing namespace Aws::Utils;\nusing namespace Aws;\n\nUpdateIntegrationResult::UpdateIntegrationResult() : \n    m_connectionType(ConnectionType::NOT_SET),\n    m_contentHandlingStrategy(ContentHandlingStrategy::NOT_SET),\n    m_integrationType(IntegrationType::NOT_SET),\n    m_passthroughBehavior(PassthroughBehavior::NOT_SET),\n    m_timeoutInMillis(0)\n{\n}\n\nUpdateIntegrationResult::UpdateIntegrationResult(const Aws::AmazonWebServiceResult<JsonValue>& result) : \n    m_connectionType(ConnectionType::NOT_SET),\n    m_contentHandlingStrategy(ContentHandlingStrategy::NOT_SET),\n    m_integrationType(IntegrationType::NOT_SET),\n    m_passthroughBehavior(PassthroughBehavior::NOT_SET),\n    m_timeoutInMillis(0)\n{\n  *this = result;\n}\n\nUpdateIntegrationResult& UpdateIntegrationResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)\n{\n  JsonView jsonValue = result.GetPayload().View();\n  if(jsonValue.ValueExists(\"connectionId\"))\n  {\n    m_connectionId = jsonValue.GetString(\"connectionId\");\n\n  }\n\n  if(jsonValue.ValueExists(\"connectionType\"))\n  {\n    m_connectionType = ConnectionTypeMapper::GetConnectionTypeForName(jsonValue.GetString(\"connectionType\"));\n\n  }\n\n  if(jsonValue.ValueExists(\"contentHandlingStrategy\"))\n  {\n    m_contentHandlingStrategy = ContentHandlingStrategyMapper::GetContentHandlingStrategyForName(jsonValue.GetString(\"contentHandlingStrategy\"));\n\n  }\n\n  if(jsonValue.ValueExists(\"credentialsArn\"))\n  {\n    m_credentialsArn = jsonValue.GetString(\"credentialsArn\");\n\n  }\n\n  if(jsonValue.ValueExists(\"description\"))\n  {\n    m_description = jsonValue.GetString(\"description\");\n\n  }\n\n  if(jsonValue.ValueExists(\"integrationId\"))\n  {\n    m_integrationId = jsonValue.GetString(\"integrationId\");\n\n  }\n\n  if(jsonValue.ValueExists(\"integrationMethod\"))\n  {\n    m_integrationMethod = jsonValue.GetString(\"integrationMethod\");\n\n  }\n\n  if(jsonValue.ValueExists(\"integrationResponseSelectionExpression\"))\n  {\n    m_integrationResponseSelectionExpression = jsonValue.GetString(\"integrationResponseSelectionExpression\");\n\n  }\n\n  if(jsonValue.ValueExists(\"integrationType\"))\n  {\n    m_integrationType = IntegrationTypeMapper::GetIntegrationTypeForName(jsonValue.GetString(\"integrationType\"));\n\n  }\n\n  if(jsonValue.ValueExists(\"integrationUri\"))\n  {\n    m_integrationUri = jsonValue.GetString(\"integrationUri\");\n\n  }\n\n  if(jsonValue.ValueExists(\"passthroughBehavior\"))\n  {\n    m_passthroughBehavior = PassthroughBehaviorMapper::GetPassthroughBehaviorForName(jsonValue.GetString(\"passthroughBehavior\"));\n\n  }\n\n  if(jsonValue.ValueExists(\"requestParameters\"))\n  {\n    Aws::Map<Aws::String, JsonView> requestParametersJsonMap = jsonValue.GetObject(\"requestParameters\").GetAllObjects();\n    for(auto& requestParametersItem : requestParametersJsonMap)\n    {\n      m_requestParameters[requestParametersItem.first] = requestParametersItem.second.AsString();\n    }\n  }\n\n  if(jsonValue.ValueExists(\"requestTemplates\"))\n  {\n    Aws::Map<Aws::String, JsonView> requestTemplatesJsonMap = jsonValue.GetObject(\"requestTemplates\").GetAllObjects();\n    for(auto& requestTemplatesItem : requestTemplatesJsonMap)\n    {\n      m_requestTemplates[requestTemplatesItem.first] = requestTemplatesItem.second.AsString();\n    }\n  }\n\n  if(jsonValue.ValueExists(\"templateSelectionExpression\"))\n  {\n    m_templateSelectionExpression = jsonValue.GetString(\"templateSelectionExpression\");\n\n  }\n\n  if(jsonValue.ValueExists(\"timeoutInMillis\"))\n  {\n    m_timeoutInMillis = jsonValue.GetInteger(\"timeoutInMillis\");\n\n  }\n\n\n\n  return *this;\n}\n","avg_line_length":29.3178807947,"max_line_length":145,"alphanum_fraction":0.7666591371,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2682,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"   #include<bits\/stdc++.h>\n  using namespace std;\n    #define ll long long\n    #define fr(i,a,b) for(int i =a ; i < b; i++)\n    #define FR(i,a,b) for(int i =a ; i > b; i--) \n    #define frj(j,a,b) for(int j =a ; j < b; j++)\n    #define FRE(i,a,b) for(int i =a ; i >= b; i--) \n    #define fre(i,a,b) for(int i =a ; i <= b; i++)\n    #define fra(s) for(auto it = s.begin(); it != s.end() ; ++it)\n\n    #define mkp make_pair \n    #define pb push_back\n    #define pii pair<int,int>\n    #define speed   ios::sync_with_stdio(false), cin.tie(0) , cout.tie(0)\n    #define c(a,b) cout<<a<<\"--\"<<b<<endl;\n    #define frv(i,a,v) for(int i =  a ; i < v.size() ; ++i)\n    #define cp(a,i)  cout<<a[i].first<<\" \"<<a[i].second<<endl;\n    #define pp(a) cout<<a.first<<\" \"<<a.second<<endl;\n    \/\/sum array\n    #define sa(n) int a[n]; int s[n];cin>>a[0];s[0]=a[0];fr(i,1,n) {cin>>a[i];s[i]=s[i-1]+a[i];}\n    #define sa1(n) int a[n+1]; long long s[n+1]; a[0]=0; s[0]=0;cin>>a[1];s[1]=a[1];fr(i,2,n+1) {cin>>a[i];\\\n    s[i]=s[i-1]+a[i];}\n\n    #define pr(a,n) fr(i,0,n){cout<<a[i]<<\" \";}cout<<endl;\n    #define prv(v)   for(auto it = v.begin() ; it!= v.end() ;++it){cout<<*it<<\" \";}cout<<endl;\n    #define prs(s)   for(auto x : s){cout<<x<<\" \";}cout<<endl;\n    \n    #define all(x)           x.begin(), x.end()\n    #define prm(m,r,c) fr(i,0,r){frj(j,0,c){cout<<m[i][j]<<\" \"; }cout<<endl;}\n    #define fillm(m,r,c,k) fr(i,0,r)frj(j,0,c)m[i][j]=k;\n    constexpr auto PI  = 3.14159265358979323846L;\n    constexpr auto eps = 1e-6;\n    constexpr auto mod = 1000000007;\n    #define MOD 1000000007\n   \/\/ #define maxv 200005\n    #define MAXN 100001\n\n  template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<\"(\"; for (auto& v: vec) out<<v<<\", \"; return out<<\")\"; }\n  template<class T> ostream& operator<<(ostream& out, set<T> vec) { out<<\"(\"; for (auto& v: vec) out<<v<<\", \"; return out<<\")\"; }\n\nvoid solve(){\n  \n  int n;\n  cin>>n;\n  int a[n];\n  int sum=0;\n  \n  fr(i,0,n){\n  cin>>a[i];\n  sum+=a[i];\n  }\n\n  if(sum%2!=0){\n    cout<<\"NO\"<<endl;return ;\n  }\n  int req_sum = sum\/2;\n  bool dp[2][req_sum+1];\n  fillm(dp,2,req_sum+1,false);\n  dp[0][a[0]]=true;\n  fr(i,0,n)\n  dp[0][0]=true;\n\n  fr(i,1,n)\n  {\n    frj(j,0,req_sum+1)\n    {\n      if(dp[0][j]==true)\n        { if(j+a[i]<=req_sum)\n          dp[1][j+a[i]]=true;\n          dp[1][j]=true;\n        }\n    }\n    frj(j,0,req_sum+1)\n    {\n      if(dp[1][j]==true)\n        dp[0][j]=true;\n    }\n  }\n  \/\/prm(dp,2,req_sum+1);\n  if(dp[1][req_sum] == true)\n    cout<<\"YES\"<<endl;\n  else\n    cout<<\"NO\"<<endl;\n\n}\n  \n    int main(){\n      speed;\n        \n\n      int t;\n      cin>>t;\n      while(t--)\n      {\n        solve();        \n      }\n      return 0;\n\n  }","avg_line_length":27.0909090909,"max_line_length":132,"alphanum_fraction":0.4917971663,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":34945,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":1.0,"content":"#include \"uicommon.h\"\n\n#include <functional>\n\n\/\/ DF data structure definition headers\n#include \"DataDefs.h\"\n#include \"Types.h\"\n#include \"df\/build_req_choice_genst.h\"\n#include \"df\/build_req_choice_specst.h\"\n#include \"df\/item.h\"\n#include \"df\/ui.h\"\n#include \"df\/ui_build_selector.h\"\n#include \"df\/viewscreen_dwarfmodest.h\"\n#include \"df\/items_other_id.h\"\n#include \"df\/job.h\"\n#include \"df\/world.h\"\n#include \"df\/building_constructionst.h\"\n#include \"df\/building_design.h\"\n\n#include \"modules\/Gui.h\"\n#include \"modules\/Buildings.h\"\n#include \"modules\/Maps.h\"\n#include \"modules\/Items.h\"\n\n#include \"TileTypes.h\"\n#include \"df\/job_item.h\"\n#include \"df\/dfhack_material_category.h\"\n#include \"df\/general_ref_building_holderst.h\"\n#include \"modules\/Job.h\"\n#include \"df\/building_design.h\"\n#include \"df\/buildings_other_id.h\"\n#include \"modules\/World.h\"\n#include \"df\/building.h\"\n#include \"df\/building_doorst.h\"\n\nusing df::global::ui;\nusing df::global::ui_build_selector;\nusing df::global::world;\n\nDFHACK_PLUGIN(\"buildingplan\");\n#define PLUGIN_VERSION 0.9\n\nstruct MaterialDescriptor\n{\n    df::item_type item_type;\n    int16_t item_subtype;\n    int16_t type;\n    int32_t index;\n    bool valid;\n\n    bool matches(const MaterialDescriptor &a) const\n    {\n        return a.valid && valid && \n            a.type == type && \n            a.index == index &&\n            a.item_type == item_type &&\n            a.item_subtype == item_subtype;\n    }\n};\n\nstruct coord32_t\n{\n    int32_t x, y, z;\n\n    df::coord get_coord16() const\n    {\n        return df::coord(x, y, z);\n    }\n};\n\nDFhackCExport command_result plugin_shutdown ( color_ostream &out )\n{\n    return CR_OK;\n}\n\n#define MAX_MASK 10\n#define MAX_MATERIAL 21\n#define SIDEBAR_WIDTH 30\n\nstatic bool show_debugging = false;\n\nstatic void debug(const string &msg)\n{\n    if (!show_debugging)\n        return;\n\n    color_ostream_proxy out(Core::getInstance().getConsole());\n    out << \"DEBUG (buildingplan): \" << msg << endl;\n}\n\n\/*\n * Material Choice Screen\n *\/\n\nstruct ItemFilter\n{\n    df::dfhack_material_category mat_mask;\n    vector<MaterialInfo> materials;\n    df::item_quality min_quality;\n    bool decorated_only;\n\n    ItemFilter() : min_quality(item_quality::Ordinary), decorated_only(false), valid(true)\n    {    }\n\n    bool matchesMask(MaterialInfo &mat)\n    {\n        return (mat_mask.whole) ? mat.matches(mat_mask) : true;\n    }\n\n    bool matches(const df::dfhack_material_category mask) const\n    {\n        return mask.whole & mat_mask.whole;\n    }\n\n    bool matches(MaterialInfo &material) const\n    {\n        return any_of(materials.begin(), materials.end(), \n            [&] (const MaterialInfo &m) { return material.matches(m); });\n    }\n\n    bool matches(df::item *item)\n    {\n        if (item->getQuality() < min_quality)\n            return false;\n\n        if (decorated_only && !item->hasImprovements())\n            return false;\n\n        auto imattype = item->getActualMaterial();\n        auto imatindex = item->getActualMaterialIndex();\n        auto item_mat = MaterialInfo(imattype, imatindex);\n\n        return (materials.size() == 0) ? matchesMask(item_mat) : matches(item_mat);\n    }\n\n    vector<string> getMaterialFilterAsVector()\n    {\n        vector<string> descriptions;\n\n        transform_(materials, descriptions,\n            [] (MaterialInfo m) { return m.toString(); });\n\n        if (descriptions.size() == 0)\n            bitfield_to_string(&descriptions, mat_mask);\n\n        if (descriptions.size() == 0)\n            descriptions.push_back(\"any\");\n\n        return descriptions;\n    }\n\n    string getMaterialFilterAsSerial()\n    {\n        string str;\n\n        str.append(bitfield_to_string(mat_mask, \",\"));\n        str.append(\"\/\");\n        if (materials.size() > 0)\n        {\n            for_each_(materials,\n                [&] (MaterialInfo &m) { str.append(m.getToken() + \",\"); });\n\n            if (str[str.size()-1] == ',')\n                str.resize(str.size () - 1);\n        }\n\n        return str;\n    }\n\n    bool parseSerializedMaterialTokens(string str)\n    {\n        valid = false;\n        vector<string> tokens;\n        split_string(&tokens, str, \"\/\");\n               \n        if (tokens.size() > 0 && !tokens[0].empty())\n        {\n            if (!parseJobMaterialCategory(&mat_mask, tokens[0]))\n                return false;\n        }\n\n        if (tokens.size() > 1 && !tokens[1].empty())\n        {\n            vector<string> mat_names;\n            split_string(&mat_names, tokens[1], \",\");\n            for (auto m = mat_names.begin(); m != mat_names.end(); m++)\n            {\n                MaterialInfo material;\n                if (!material.find(*m) || !material.isValid())\n                    return false;\n\n                materials.push_back(material);\n            }\n        }\n\n        valid = true;\n        return true;\n    }\n\n    string getMinQuality()\n    {\n        return ENUM_KEY_STR(item_quality, min_quality);\n    }\n\n    bool isValid()\n    {\n        return valid;\n    }\n\n    void clear()\n    {\n        mat_mask.whole = 0;\n        materials.clear();\n    }\n\nprivate:\n    bool valid;\n};\n\n\nclass ViewscreenChooseMaterial : public dfhack_viewscreen\n{\npublic:\n    ViewscreenChooseMaterial(ItemFilter *filter)\n    {\n        selected_column = 0;\n        masks_column.setTitle(\"Type\");\n        masks_column.multiselect = true;\n        masks_column.allow_search = false;\n        masks_column.left_margin = 2;\n        materials_column.left_margin = MAX_MASK + 3;\n        materials_column.setTitle(\"Material\");\n        materials_column.multiselect = true;\n        this->filter = filter;\n\n        masks_column.changeHighlight(0);\n\n        populateMasks();\n        populateMaterials();\n\n        masks_column.selectDefaultEntry();\n        materials_column.selectDefaultEntry();\n        materials_column.changeHighlight(0);\n    }\n\n    void feed(set<df::interface_key> *input)\n    {\n        bool key_processed = false;\n        switch (selected_column)\n        {\n        case 0:\n            key_processed = masks_column.feed(input);\n            if (input->count(interface_key::SELECT))\n                populateMaterials(); \/\/ Redo materials lists based on category selection\n            break;\n        case 1:\n            key_processed = materials_column.feed(input);\n            break;\n        }\n\n        if (key_processed)\n            return;\n\n        if (input->count(interface_key::LEAVESCREEN))\n        {\n            input->clear();\n            Screen::dismiss(this);\n            return;\n        }\n        if (input->count(interface_key::CUSTOM_SHIFT_C))\n        {\n            filter->clear();\n            masks_column.clearSelection();\n            materials_column.clearSelection();\n            populateMaterials();\n        }\n        else if  (input->count(interface_key::SEC_SELECT))\n        {\n            \/\/ Convert list selections to material filters\n\n\n            filter->mat_mask.whole = 0;\n            filter->materials.clear();\n\n            \/\/ Category masks\n            auto masks = masks_column.getSelectedElems();\n            for_each_(masks,\n                [&] (df::dfhack_material_category &m) { filter->mat_mask.whole |= m.whole; });\n\n            \/\/ Specific materials\n            auto materials = materials_column.getSelectedElems();\n            transform_(materials, filter->materials,\n                [] (MaterialInfo &m) { return m; });\n\n            Screen::dismiss(this);\n        }\n        else if  (input->count(interface_key::CURSOR_LEFT))\n        {\n            --selected_column;\n            validateColumn();\n        }\n        else if  (input->count(interface_key::CURSOR_RIGHT))\n        {\n            selected_column++;\n            validateColumn();\n        }\n        else if (enabler->tracking_on && enabler->mouse_lbut)\n        {\n            if (masks_column.setHighlightByMouse())\n                selected_column = 0;\n            else if (materials_column.setHighlightByMouse())\n                selected_column = 1;\n\n            enabler->mouse_lbut = enabler->mouse_rbut = 0;\n        }\n    }\n\n    void render()\n    {\n        if (Screen::isDismissed(this))\n            return;\n\n        dfhack_viewscreen::render();\n\n        Screen::clear();\n        Screen::drawBorder(\"  Building Material  \");\n\n        masks_column.display(selected_column == 0);\n        materials_column.display(selected_column == 1);\n\n        int32_t y = gps->dimy - 3;\n        int32_t x = 2;\n        OutputHotkeyString(x, y, \"Toggle\", \"Enter\");\n        x += 3;\n        OutputHotkeyString(x, y, \"Save\", \"Shift-Enter\");\n        x += 3;\n        OutputHotkeyString(x, y, \"Clear\", \"C\");\n        x += 3;\n        OutputHotkeyString(x, y, \"Cancel\", \"Esc\");\n    }\n\n    std::string getFocusString() { return \"buildingplan_choosemat\"; }\n\nprivate:\n    ListColumn<df::dfhack_material_category> masks_column;\n    ListColumn<MaterialInfo> materials_column;\n    int selected_column;\n    ItemFilter *filter;\n\n    df::building_type btype;\n\n    void addMaskEntry(df::dfhack_material_category &mask, const string &text)\n    {\n        auto entry = ListEntry<df::dfhack_material_category>(pad_string(text, MAX_MASK, false), mask);\n        if (filter->matches(mask))\n            entry.selected = true;\n\n        masks_column.add(entry);\n    }\n\n    void populateMasks()\n    {\n        masks_column.clear();\n        df::dfhack_material_category mask;\n\n        mask.whole = 0;\n        mask.bits.stone = true;\n        addMaskEntry(mask, \"Stone\");\n\n        mask.whole = 0;\n        mask.bits.wood = true;\n        addMaskEntry(mask, \"Wood\");\n\n        mask.whole = 0;\n        mask.bits.metal = true;\n        addMaskEntry(mask, \"Metal\");\n\n        mask.whole = 0;\n        mask.bits.soap = true;\n        addMaskEntry(mask, \"Soap\");\n\n        masks_column.filterDisplay();\n    }\n    \n    void populateMaterials()\n    {\n        materials_column.clear();\n        df::dfhack_material_category selected_category;\n        vector<df::dfhack_material_category> selected_masks = masks_column.getSelectedElems();\n        if (selected_masks.size() == 1)\n            selected_category = selected_masks[0];\n        else if (selected_masks.size() > 1)\n            return;\n\n        df::world_raws &raws = world->raws;\n        for (int i = 1; i < DFHack::MaterialInfo::NUM_BUILTIN; i++)\n        {\n            auto obj = raws.mat_table.builtin[i];\n            if (obj)\n            {\n                MaterialInfo material;\n                material.decode(i, -1);\n                addMaterialEntry(selected_category, material, material.toString());\n            }\n        }\n\n        for (size_t i = 0; i < raws.inorganics.size(); i++)\n        {\n            df::inorganic_raw *p = raws.inorganics[i];\n            MaterialInfo material;\n            material.decode(0, i);\n            addMaterialEntry(selected_category, material, material.toString());\n        }\n\n        decltype(selected_category) wood_flag;\n        wood_flag.bits.wood = true;\n        if (!selected_category.whole || selected_category.bits.wood)\n        {\n            for (size_t i = 0; i < raws.plants.all.size(); i++)\n            {\n                df::plant_raw *p = raws.plants.all[i];\n                for (size_t j = 0; p->material.size() > 1 && j < p->material.size(); j++)\n                {\n                    auto t = p->material[j];\n                    if (p->material[j]->id != \"WOOD\")\n                        continue;\n\n                    MaterialInfo material;\n                    material.decode(DFHack::MaterialInfo::PLANT_BASE+j, i);\n                    auto name = material.toString();\n                    ListEntry<MaterialInfo> entry(pad_string(name, MAX_MATERIAL, false), material);\n                    if (filter->matches(material))\n                        entry.selected = true;\n\n                    materials_column.add(entry);\n                }\n            }\n        }\n        materials_column.sort();\n    }\n\n    void addMaterialEntry(df::dfhack_material_category &selected_category, \n                          MaterialInfo &material, string name)\n    {\n        if (!selected_category.whole || material.matches(selected_category))\n        {\n            ListEntry<MaterialInfo> entry(pad_string(name, MAX_MATERIAL, false), material);\n            if (filter->matches(material))\n                entry.selected = true;\n\n            materials_column.add(entry);\n        }\n    }\n\n    void validateColumn()\n    {\n        set_to_limit(selected_column, 1);\n    }\n\n    void resize(int32_t x, int32_t y)\n    {\n        dfhack_viewscreen::resize(x, y);\n        masks_column.resize();\n        materials_column.resize();\n    }\n};\n\n\n\/\/ START Planning \nclass PlannedBuilding\n{\npublic:\n    PlannedBuilding(df::building *building, ItemFilter *filter)\n    {\n        this->building = building;\n        this->filter = *filter;\n        pos = df::coord(building->centerx, building->centery, building->z);\n        config = DFHack::World::AddPersistentData(\"buildingplan\/constraints\");\n        config.val() = filter->getMaterialFilterAsSerial();\n        config.ival(1) = building->id;\n        config.ival(2) = filter->min_quality + 1;\n        config.ival(3) = static_cast<int>(filter->decorated_only) + 1;\n    }\n\n    PlannedBuilding(PersistentDataItem &config, color_ostream &out)\n    {\n        this->config = config;\n\n        if (!filter.parseSerializedMaterialTokens(config.val()))\n        {\n            out.printerr(\"Buildingplan: Cannot parse filter: %s\\nDiscarding.\", config.val().c_str());\n            return;\n        }\n\n        building = df::building::find(config.ival(1));\n        if (!building)\n            return;\n\n        pos = df::coord(building->centerx, building->centery, building->z);\n        filter.min_quality = static_cast<df::item_quality>(config.ival(2) - 1);\n        filter.decorated_only = config.ival(3) - 1;\n    }\n\n    df::building_type getType()\n    {\n        return building->getType();\n    }\n\n    bool assignClosestItem(vector<df::item *> *items_vector)\n    {\n        decltype(items_vector->begin()) closest_item;\n        int32_t closest_distance = -1;\n        for (auto item_iter = items_vector->begin(); item_iter != items_vector->end(); item_iter++)\n        {\n            auto item = *item_iter;\n            if (!filter.matches(item))\n                continue;\n\n            auto pos = item->pos;\n            auto distance = abs(pos.x - building->centerx) + \n                abs(pos.y - building->centery) + \n                abs(pos.z - building->z) * 50;\n\n            if (closest_distance > -1 && distance >= closest_distance)\n                continue;\n\n            closest_distance = distance;\n            closest_item = item_iter;\n        }\n\n        if (closest_distance > -1 && assignItem(*closest_item))\n        {\n            debug(\"Item assigned\");\n            items_vector->erase(closest_item);\n            remove();\n            return true;\n        }\n\n        return false;\n    }\n\n    bool assignItem(df::item *item)\n    {\n        auto ref = df::allocate<df::general_ref_building_holderst>();\n        if (!ref)\n        {\n            Core::printerr(\"Could not allocate general_ref_building_holderst\\n\");\n            return false;\n        }\n\n        ref->building_id = building->id;\n\n        if (building->jobs.size() != 1)\n            return false;\n        \n        auto job = building->jobs[0];\n\n        for_each_(job->job_items, [] (df::job_item *x) { delete x; });\n        job->job_items.clear();\n        job->flags.bits.suspend = false;\n\n        bool rough = false;\n        Job::attachJobItem(job, item, df::job_item_ref::Hauled);\n        if (item->getType() == item_type::BOULDER)\n            rough = true;\n        building->mat_type = item->getMaterial();\n        building->mat_index = item->getMaterialIndex();\n\n        job->mat_type = building->mat_type;\n        job->mat_index = building->mat_index;\n\n        if (building->needsDesign())\n        {\n            auto act = (df::building_actual *) building;\n            act->design = new df::building_design();\n            act->design->flags.bits.rough = rough;\n        }\n\n        return true;\n    }\n\n    bool isValid()\n    {\n        bool valid = filter.isValid() && \n            building && Buildings::findAtTile(pos) == building &&\n            building->getBuildStage() == 0;\n\n        if (!valid)\n            remove();\n\n        return valid;\n    }\n\n    bool isCurrentlySelectedBuilding()\n    {\n        return isValid() && (building == world->selected_building);\n    }\n\n    ItemFilter *getFilter()\n    {\n        return &filter;\n    }\n\n    void remove()\n    {\n        DFHack::World::DeletePersistentData(config);\n    }\n\nprivate:\n    df::building *building;\n    PersistentDataItem config;\n    df::coord pos;\n    ItemFilter filter;\n};\n\n\nstatic map<df::building_type, bool> planmode_enabled, saved_planmodes;\n\nclass Planner\n{\npublic:\n    bool in_dummmy_screen;\n\n    Planner() : quickfort_mode(false), in_dummmy_screen(false)\n    {\n\n    }\n\n    bool isPlanableBuilding(const df::building_type type) const\n    {\n        return item_for_building_type.find(type) != item_for_building_type.end();\n    }\n\n    void reset(color_ostream &out)\n    {\n        planned_buildings.clear();\n        std::vector<PersistentDataItem> items;\n        DFHack::World::GetPersistentData(&items, \"buildingplan\/constraints\");\n\n        for (auto i = items.begin(); i != items.end(); i++)\n        {\n            PlannedBuilding pb(*i, out);\n            if (pb.isValid())\n                planned_buildings.push_back(pb);\n        }\n    }\n\n    void initialize()\n    {\n        vector<string> item_names;\n        typedef df::enum_traits<df::item_type> item_types;\n        int size = item_types::last_item_value - item_types::first_item_value+1;\n        for (size_t i = 1; i < size; i++)\n        {\n            is_relevant_item_type[(df::item_type) (i-1)] = false;\n            string item_name = toLower(item_types::key_table[i]);\n            string item_name_clean;\n            for (auto c = item_name.begin(); c != item_name.end(); c++)\n            {\n                if (*c == '_')\n                    continue;\n                item_name_clean += *c;\n            }\n            item_names.push_back(item_name_clean);\n        }\n        \n        typedef df::enum_traits<df::building_type> building_types;\n        size = building_types::last_item_value - building_types::first_item_value+1;\n        for (size_t i = 1; i < size; i++)\n        {\n            auto building_type = (df::building_type) (i-1);\n            if (building_type == building_type::Weapon || building_type == building_type::Floodgate)\n                continue;\n\n            string building_name = toLower(building_types::key_table[i]);\n            for (size_t j = 0; j < item_names.size(); j++)\n            {\n                if (building_name == item_names[j])\n                {\n                    auto btype = (df::building_type) (i-1);\n                    auto itype = (df::item_type) j;\n\n                    item_for_building_type[btype] = itype;\n                    default_item_filters[btype] =  ItemFilter();\n                    available_item_vectors[itype] = vector<df::item *>();\n                    is_relevant_item_type[itype] = true;\n\n                    if (planmode_enabled.find(btype) == planmode_enabled.end())\n                    {\n                        planmode_enabled[btype] = false;\n                    }\n                }\n            }\n        }\n    }\n\n    void addPlannedBuilding(df::building *bld)\n    {\n        PlannedBuilding pb(bld, &default_item_filters[bld->getType()]);\n        planned_buildings.push_back(pb);\n    }\n\n    void doCycle()\n    {\n        debug(\"Running Cycle\");\n        if (planned_buildings.size() == 0)\n            return;\n\n        debug(\"Planned count: \" + int_to_string(planned_buildings.size()));\n\n        gather_available_items();\n        for (auto building_iter = planned_buildings.begin(); building_iter != planned_buildings.end();)\n        {\n            if (building_iter->isValid())\n            {\n                if (show_debugging)\n                    debug(string(\"Trying to allocate \") + enum_item_key_str(building_iter->getType()));\n\n                auto required_item_type = item_for_building_type[building_iter->getType()];\n                auto items_vector = &available_item_vectors[required_item_type];\n                if (items_vector->size() == 0 || !building_iter->assignClosestItem(items_vector))\n                {\n                    debug(\"Unable to allocate an item\");\n                    ++building_iter;\n                    continue;\n                }\n            }\n            debug(\"Removing building plan\");\n            building_iter = planned_buildings.erase(building_iter);\n        }\n    }\n\n    bool allocatePlannedBuilding(df::building_type type)\n    {\n        coord32_t cursor;\n        if (!Gui::getCursorCoords(cursor.x, cursor.y, cursor.z))\n            return false;\n\n        auto newinst = Buildings::allocInstance(cursor.get_coord16(), type);\n        if (!newinst)\n            return false;\n\n        df::job_item *filter = new df::job_item();\n        filter->item_type = item_type::NONE;\n        filter->mat_index = 0;\n        filter->flags2.bits.building_material = true;\n        std::vector<df::job_item*> filters;\n        filters.push_back(filter);\n\n        if (!Buildings::constructWithFilters(newinst, filters))\n        {\n            delete newinst;\n            return false;\n        }\n\n        for (auto iter = newinst->jobs.begin(); iter != newinst->jobs.end(); iter++)\n        {\n            (*iter)->flags.bits.suspend = true;\n        }\n\n        if (type == building_type::Door)\n        {\n            auto door = virtual_cast<df::building_doorst>(newinst);\n            if (door)\n                door->door_flags.bits.pet_passable = true;\n        }\n\n        addPlannedBuilding(newinst);\n\n        return true;\n    }\n\n    PlannedBuilding *getSelectedPlannedBuilding()\n    {\n        for (auto building_iter = planned_buildings.begin(); building_iter != planned_buildings.end(); building_iter++)\n        {\n            if (building_iter->isCurrentlySelectedBuilding())\n            {\n                return &(*building_iter);\n            }\n        }\n\n        return nullptr;\n    }\n\n    void removeSelectedPlannedBuilding()\n    {\n        getSelectedPlannedBuilding()->remove();\n    }\n\n    ItemFilter *getDefaultItemFilterForType(df::building_type type)\n    {\n        return &default_item_filters[type];\n    }\n\n    void cycleDefaultQuality(df::building_type type)\n    {\n        auto quality = &getDefaultItemFilterForType(type)->min_quality;\n        *quality = static_cast<df::item_quality>(*quality + 1);\n        if (*quality == item_quality::Artifact)\n            (*quality) = item_quality::Ordinary;\n    }\n\n    void enableQuickfortMode()\n    {\n        saved_planmodes = planmode_enabled;\n        for_each_(planmode_enabled, \n            [] (pair<const df::building_type, bool>& pair) { pair.second = true; } );\n\n        quickfort_mode = true;\n    }\n\n    void disableQuickfortMode()\n    {\n        planmode_enabled = saved_planmodes;\n        quickfort_mode = false;\n    }\n\n    bool inQuickFortMode()\n    {\n        return quickfort_mode;\n    }\n\nprivate:\n    map<df::building_type, df::item_type> item_for_building_type;\n    map<df::building_type, ItemFilter> default_item_filters;\n    map<df::item_type, vector<df::item *>> available_item_vectors;\n    map<df::item_type, bool> is_relevant_item_type; \/\/Needed for fast check when looping over all items\n    bool quickfort_mode;\n\n    vector<PlannedBuilding> planned_buildings;\n\n    void gather_available_items()\n    {\n        debug(\"Gather available items\");\n        for (auto iter = available_item_vectors.begin(); iter != available_item_vectors.end(); iter++)\n        {\n            iter->second.clear();\n        }\n\n        \/\/ Precompute a bitmask with the bad flags\n        df::item_flags bad_flags;\n        bad_flags.whole = 0;\n\n#define F(x) bad_flags.bits.x = true;\n        F(dump); F(forbid); F(garbage_collect);\n        F(hostile); F(on_fire); F(rotten); F(trader);\n        F(in_building); F(construction); F(artifact);\n#undef F\n\n        std::vector<df::item*> &items = world->items.other[items_other_id::IN_PLAY];\n\n        for (size_t i = 0; i < items.size(); i++)\n        {\n            df::item *item = items[i];\n\n            if (item->flags.whole & bad_flags.whole)\n                continue;\n\n            df::item_type itype = item->getType();\n            if (!is_relevant_item_type[itype])\n                continue;\n\n            if (itype == item_type::BOX && item->isBag())\n                continue; \/\/Skip bags\n\n            if (item->flags.bits.artifact)\n                continue;\n\n            if (item->flags.bits.in_job ||\n                item->isAssignedToStockpile() ||\n                item->flags.bits.owned ||\n                item->flags.bits.in_chest)\n            {\n                continue;\n            }\n\n            available_item_vectors[itype].push_back(item);\n        }\n    }\n};\n\nstatic Planner planner;\n\n\nstatic bool is_planmode_enabled(df::building_type type)\n{\n    if (planmode_enabled.find(type) == planmode_enabled.end())\n    {\n        return false;\n    }\n\n    return planmode_enabled[type];\n}\n\n#define DAY_TICKS 1200\nDFhackCExport command_result plugin_onupdate(color_ostream &out)\n{\n    static decltype(world->frame_counter) last_frame_count = 0;\n    if ((world->frame_counter - last_frame_count) >= DAY_TICKS\/2)\n    {\n        last_frame_count = world->frame_counter;\n        planner.doCycle();\n    }\n\n    return CR_OK;\n}\n\n\/\/START Viewscreen Hook\nstruct buildingplan_hook : public df::viewscreen_dwarfmodest\n{\n    \/\/START UI Methods\n    typedef df::viewscreen_dwarfmodest interpose_base;\n\n    void send_key(const df::interface_key &key)\n    {\n        set< df::interface_key > keys;\n        keys.insert(key);\n        this->feed(&keys);\n    }\n\n    bool isInPlannedBuildingQueryMode()\n    {\n        return (ui->main.mode == df::ui_sidebar_mode::QueryBuilding || \n            ui->main.mode == df::ui_sidebar_mode::BuildingItems) &&\n            planner.getSelectedPlannedBuilding();\n    }\n\n    bool isInPlannedBuildingPlacementMode()\n    {\n        return ui->main.mode == ui_sidebar_mode::Build &&\n            ui_build_selector &&\n            ui_build_selector->stage < 2 &&\n            planner.isPlanableBuilding(ui_build_selector->building_type);\n    }\n\n    bool handleInput(set<df::interface_key> *input)\n    {\n        if (isInPlannedBuildingPlacementMode())\n        {\n            auto type = ui_build_selector->building_type;\n            if (input->count(interface_key::CUSTOM_P))\n            {\n                planmode_enabled[type] = !planmode_enabled[type];\n                if (!planmode_enabled[type])\n                {\n                    send_key(interface_key::CURSOR_DOWN_Z);\n                    send_key(interface_key::CURSOR_UP_Z);\n                    planner.in_dummmy_screen = false;\n                }\n                return true;\n            }\n            \n            if (is_planmode_enabled(type))\n            {\n                if (planner.inQuickFortMode() && planner.in_dummmy_screen)\n                {\n                    if (input->count(interface_key::SELECT) || input->count(interface_key::SEC_SELECT)\n                         || input->count(interface_key::LEAVESCREEN))\n                    {\n                        planner.in_dummmy_screen = false;\n                        send_key(interface_key::LEAVESCREEN);\n                    }\n\n                    return true;\n                }\n\n                if (input->count(interface_key::SELECT))\n                {\n                    if (ui_build_selector->errors.size() == 0 && planner.allocatePlannedBuilding(type))\n                    {\n                        send_key(interface_key::CURSOR_DOWN_Z);\n                        send_key(interface_key::CURSOR_UP_Z);\n                        if (planner.inQuickFortMode())\n                        {\n                            planner.in_dummmy_screen = true;\n                        }\n                    }\n\n                    return true;\n                }\n                else if (input->count(interface_key::CUSTOM_F))\n                {\n                    if (!planner.inQuickFortMode())\n                    {\n                        planner.enableQuickfortMode();\n                    }\n                    else\n                    {\n                        planner.disableQuickfortMode();\n                    }\n                }\n                else if (input->count(interface_key::CUSTOM_M))\n                {\n                    Screen::show(new ViewscreenChooseMaterial(planner.getDefaultItemFilterForType(type)));\n                }\n                else if (input->count(interface_key::CUSTOM_Q))\n                {\n                    planner.cycleDefaultQuality(type);\n                }\n                else if (input->count(interface_key::CUSTOM_D))\n                {\n                    planner.getDefaultItemFilterForType(type)->decorated_only =\n                        !planner.getDefaultItemFilterForType(type)->decorated_only;\n                }\n            }\n        }\n        else if (isInPlannedBuildingQueryMode())\n        {\n            if (input->count(interface_key::SUSPENDBUILDING))\n            {\n                return true; \/\/ Don't unsuspend planned buildings\n            }\n            else if (input->count(interface_key::DESTROYBUILDING))\n            {\n                planner.removeSelectedPlannedBuilding(); \/\/ Remove persistent data\n            }\n            \n        }\n\n        return false;\n    }\n\n    DEFINE_VMETHOD_INTERPOSE(void, feed, (set<df::interface_key> *input))\n    {\n        if (!handleInput(input))\n            INTERPOSE_NEXT(feed)(input);\n    }\n\n    DEFINE_VMETHOD_INTERPOSE(void, render, ())\n    {\n        bool plannable = isInPlannedBuildingPlacementMode();\n        if (plannable && is_planmode_enabled(ui_build_selector->building_type))\n        {\n            if (ui_build_selector->stage < 1)\n            {\n                \/\/ No materials but turn on cursor\n                ui_build_selector->stage = 1;\n            }\n\n            for (auto iter = ui_build_selector->errors.begin(); iter != ui_build_selector->errors.end();)\n            {\n                \/\/FIXME Hide bags\n                if (((*iter)->find(\"Needs\") != string::npos && **iter != \"Needs adjacent wall\")  ||\n                    (*iter)->find(\"No access\") != string::npos)\n                {\n                    iter = ui_build_selector->errors.erase(iter);\n                }\n                else\n                {\n                    ++iter;\n                }\n            }\n        }\n\n        INTERPOSE_NEXT(render)();\n\n        auto dims = Gui::getDwarfmodeViewDims();\n        int left_margin = dims.menu_x1 + 1;\n        int x = left_margin;\n        auto type = ui_build_selector->building_type;\n        if (plannable)\n        {\n            if (planner.inQuickFortMode() && planner.in_dummmy_screen)\n            {\n                Screen::Pen pen(' ',COLOR_BLACK);\n                int y = dims.y1 + 1;\n                Screen::fillRect(pen, x, y, dims.menu_x2, y + 20);\n\n                ++y;\n\n                OutputString(COLOR_BROWN, x, y, \"Quickfort Placeholder\", true, left_margin);\n                OutputString(COLOR_WHITE, x, y, \"Enter, Shift-Enter or Esc\", true, left_margin);\n            }\n            else\n            {\n                int y = 23;\n\n                OutputToggleString(x, y, \"Planning Mode\", \"p\", is_planmode_enabled(type), true, left_margin);\n\n                if (is_planmode_enabled(type))\n                {\n                    OutputToggleString(x, y, \"Quickfort Mode\", \"f\", planner.inQuickFortMode(), true, left_margin);\n\n                    auto filter = planner.getDefaultItemFilterForType(type);\n\n                    OutputHotkeyString(x, y, \"Min Quality: \", \"q\");\n                    OutputString(COLOR_BROWN, x, y, filter->getMinQuality(), true, left_margin);\n\n                    OutputHotkeyString(x, y, \"Decorated Only: \", \"d\");\n                    OutputString(COLOR_BROWN, x, y, \n                        (filter->decorated_only) ? \"Yes\" : \"No\", true, left_margin);\n\n                    OutputHotkeyString(x, y, \"Material Filter:\", \"m\", true, left_margin);\n                    auto filter_descriptions = filter->getMaterialFilterAsVector();\n                    for_each_(filter_descriptions, \n                        [&](string d) { OutputString(COLOR_BROWN, x, y, \"   *\" + d, true, left_margin); });\n                }\n                else\n                {\n                    planner.in_dummmy_screen = false;\n                }\n            }\n        }\n        else if (isInPlannedBuildingQueryMode())\n        {\n            planner.in_dummmy_screen = false;\n\n            \/\/ Hide suspend toggle option\n            int y = 20;\n            Screen::Pen pen(' ', COLOR_BLACK);\n            Screen::fillRect(pen, x, y, dims.menu_x2, y);\n\n            auto filter = planner.getSelectedPlannedBuilding()->getFilter();\n            y = 24;\n            OutputString(COLOR_BROWN, x, y, \"Planned Building Filter:\", true, left_margin);\n            OutputString(COLOR_BLUE, x, y, filter->getMinQuality(), true, left_margin);\n\n            if (filter->decorated_only)\n                OutputString(COLOR_BLUE, x, y, \"Decorated Only\", true, left_margin);\n\n            OutputString(COLOR_BROWN, x, y, \"Materials:\", true, left_margin);\n            auto filters = filter->getMaterialFilterAsVector();\n            for_each_(filters,\n                [&](string d) { OutputString(COLOR_BLUE, x, y, \"*\" + d, true, left_margin); });\n        }\n        else\n        {\n            planner.in_dummmy_screen = false;\n        }\n    }\n};\n\nIMPLEMENT_VMETHOD_INTERPOSE(buildingplan_hook, feed);\nIMPLEMENT_VMETHOD_INTERPOSE(buildingplan_hook, render);\n\n\nstatic command_result buildingplan_cmd(color_ostream &out, vector <string> & parameters)\n{\n    if (!parameters.empty())\n    {\n        if (parameters.size() == 1 && toLower(parameters[0])[0] == 'v')\n        {\n            out << \"Building Plan\" << endl << \"Version: \" << PLUGIN_VERSION << endl;\n        }\n        else if (parameters.size() == 2 && toLower(parameters[0]) == \"debug\")\n        {\n            show_debugging = (toLower(parameters[1]) == \"on\");\n            out << \"Debugging \" << ((show_debugging) ? \"enabled\" : \"disabled\") << endl;\n        }        \n    }\n\n    return CR_OK;\n}\n\n\nDFhackCExport command_result plugin_init ( color_ostream &out, std::vector <PluginCommand> &commands)\n{\n    if (!gps || !INTERPOSE_HOOK(buildingplan_hook, feed).apply() || !INTERPOSE_HOOK(buildingplan_hook, render).apply())\n        out.printerr(\"Could not insert buildingplan hooks!\\n\");\n\n    commands.push_back(\n        PluginCommand(\n        \"buildingplan\", \"Place furniture before it's built\",\n        buildingplan_cmd, false, \"\"));\n    planner.initialize();\n\n    return CR_OK;\n}\n\n\nDFhackCExport command_result plugin_onstatechange(color_ostream &out, state_change_event event)\n{\n    switch (event) {\n    case SC_MAP_LOADED:\n        planner.reset(out);\n        break;\n    default:\n        break;\n    }\n\n    return CR_OK;\n}\n","avg_line_length":29.5143581081,"max_line_length":119,"alphanum_fraction":0.5543282301,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1616,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":7.0,"content":"\/\/ -*- C++ -*-\n\/**\n * @file    dds4ccm_topic_listener_t.cpp\n * @author  Marcel Smit, Martin Corino\n *\n * @brief   TopicListener for DDS4CCM4CIAOX11\n *\n * @copyright Copyright (c) Remedy IT Expertise BV\n *\/\n#include \"dds4ccm\/logger\/dds4ccm_log.h\"\n\nnamespace CIAOX11\n{\n  namespace DDS4CCM\n  {\n    template <typename EVT_STRATEGY>\n    TopicListener_T<EVT_STRATEGY>::TopicListener_T (const EVT_STRATEGY &evs)\n      : evs_ (evs)\n    {\n      DDS4CCM_LOG_TRACE(\"TopicListener_T::TopicListener_T\");\n    }\n\n    template <typename EVT_STRATEGY>\n    void\n    TopicListener_T<EVT_STRATEGY>::on_inconsistent_topic (\n      IDL::traits< ::DDS::Topic>::ref_type the_topic,\n      const ::DDS::InconsistentTopicStatus & status)\n    {\n      DDS4CCM_LOG_TRACE(\"TopicListener_T::on_inconsistent_topic\");\n\n      DDS4CCM_LOG_DEBUG (\"TopicListener_T::on_inconsistent_topic - \"\n        << IDL::traits< ::DDS::InconsistentTopicStatus>::write (status));\n\n      this->evs_.handle_inconsistent_topic_event (the_topic, status);\n    }\n\n    template <typename EVT_STRATEGY>\n    ::DDS::StatusMask\n     TopicListener_T<EVT_STRATEGY>::get_mask (\n      IDL::traits< CCM_DDS::ConnectorStatusListener>::ref_type error_listener)\n    {\n      DDS4CCM_LOG_TRACE(\"TopicListener_T::get_mask\");\n\n      ::DDS::StatusMask mask { ::DDS::STATUS_MASK_NONE };\n\n      if (error_listener)\n      {\n        mask = ::DDS::INCONSISTENT_TOPIC_STATUS;\n      }\n\n      DDS4CCM_LOG_DEBUG (\"TopicListener_T::get_mask - \"\n        << \"Mask becomes <\"\n        << IDL::traits< ::DDS::StatusMask>::write<status_mask_formatter> (mask)\n        << \">.\");\n      return mask;\n    }\n  }\n}\n\n","avg_line_length":26.9333333333,"max_line_length":79,"alphanum_fraction":0.6639851485,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2780,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":3.0,"content":"#include <systemlib\/mavlink_log.h>\n#include <matrix\/math.hpp>\n#include \"..\/BlockLocalPositionEstimator.hpp\"\n\nextern orb_advert_t mavlink_log_pub;\n\n\/\/ required number of samples for sensor\n\/\/ to initialize\nstatic const uint32_t \t\tREQ_BARO_INIT_COUNT = 100;\nstatic const uint32_t \t\tBARO_TIMEOUT =   \t100000;\t\/\/ 0.1 s\n\nvoid BlockLocalPositionEstimator::baroInit()\n{\n\t\/\/ measure\n\tVector<float, n_y_baro> y;\n\n\tif (baroMeasure(y) != OK) {\n\t\t_baroStats.reset();\n\t\treturn;\n\t}\n\n\t\/\/ if finished\n\tif (_baroStats.getCount() > REQ_BARO_INIT_COUNT) {\n\t\t_baroAltOrigin = _baroStats.getMean()(0);\n\t\tmavlink_and_console_log_info(&mavlink_log_pub,\n\t\t\t\t\t     \"[lpe] baro init %d m std %d cm\",\n\t\t\t\t\t     (int)_baroStats.getMean()(0),\n\t\t\t\t\t     (int)(100 * _baroStats.getStdDev()(0)));\n\t\t_baroInitialized = true;\n\t\t_baroFault = FAULT_NONE;\n\n\t\t\/\/ only initialize alt origin with baro and no gps\n\t\tif (!_altOriginInitialized && !_gps_on.get()) {\n\t\t\t_altOriginInitialized = true;\n\t\t\t_altOrigin = _baroAltOrigin;\n\t\t}\n\t}\n}\n\nint BlockLocalPositionEstimator::baroMeasure(Vector<float, n_y_baro> &y)\n{\n\t\/\/measure\n\ty.setZero();\n\ty(0) = _sub_sensor.get().baro_alt_meter;\n\t_baroStats.update(y);\n\t_time_last_baro = _timeStamp;\n\treturn OK;\n}\n\nvoid BlockLocalPositionEstimator::baroCorrect()\n{\n\t\/\/ measure\n\tVector<float, n_y_baro> y;\n\n\tif (baroMeasure(y) != OK) { return; }\n\n\t\/\/ subtract baro origin alt\n\ty -= _baroAltOrigin;\n\n\t\/\/ baro measurement matrix\n\tMatrix<float, n_y_baro, n_x> C;\n\tC.setZero();\n\tC(Y_baro_z, X_z) = -1; \/\/ measured altitude, negative down dir.\n\n\tMatrix<float, n_y_baro, n_y_baro> R;\n\tR.setZero();\n\tR(0, 0) = _baro_stddev.get() * _baro_stddev.get();\n\n\t\/\/ residual\n\tMatrix<float, n_y_baro, n_y_baro> S_I =\n\t\tinv<float, n_y_baro>((C * _P * C.transpose()) + R);\n\tVector<float, n_y_baro> r = y - (C * _x);\n\n\t\/\/ fault detection\n\tfloat beta = (r.transpose() * (S_I * r))(0, 0);\n\n\tif (beta > BETA_TABLE[n_y_baro]) {\n\t\tif (_baroFault < FAULT_MINOR) {\n\t\t\tif (beta > 2.0f * BETA_TABLE[n_y_baro]) {\n\t\t\t\tmavlink_and_console_log_critical(&mavlink_log_pub, \"[lpe] baro fault, r %5.2f m, beta %5.2f\",\n\t\t\t\t\t\t\t\t double(r(0)), double(beta));\n\t\t\t}\n\n\t\t\t_baroFault = FAULT_MINOR;\n\t\t}\n\n\t} else if (_baroFault) {\n\t\t_baroFault = FAULT_NONE;\n\t\t\/\/mavlink_and_console_log_info(&mavlink_log_pub, \"[lpe] baro OK\");\n\t}\n\n\t\/\/ kalman filter correction if no fault\n\tif (_baroFault < fault_lvl_disable) {\n\t\tMatrix<float, n_x, n_y_baro> K = _P * C.transpose() * S_I;\n\t\tVector<float, n_x> dx = K * r;\n\t\tcorrectionLogic(dx);\n\t\t_x += dx;\n\t\t_P -= K * C * _P;\n\t}\n}\n\nvoid BlockLocalPositionEstimator::baroCheckTimeout()\n{\n\tif (_timeStamp - _time_last_baro > BARO_TIMEOUT) {\n\t\tif (_baroInitialized) {\n\t\t\t_baroInitialized = false;\n\t\t\t_baroStats.reset();\n\t\t\tmavlink_and_console_log_info(&mavlink_log_pub, \"[lpe] baro timeout \");\n\t\t}\n\t}\n}\n","avg_line_length":24.8214285714,"max_line_length":97,"alphanum_fraction":0.6791366906,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4784,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":3.0,"content":"\/\/[ LazyVector\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/  Copyright 2008 Eric Niebler. Distributed under the Boost\n\/\/  Software License, Version 1.0. (See accompanying file\n\/\/  LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n\/\/ This example constructs a mini-library for linear algebra, using\n\/\/ expression templates to eliminate the need for temporaries when\n\/\/ adding vectors of numbers.\n\/\/\n\/\/ This example uses a domain with a grammar to prune the set\n\/\/ of overloaded operators. Only those operators that produce\n\/\/ valid lazy vector expressions are allowed.\n\n#include <vector>\n#include <iostream>\n#include <boost\/mpl\/int.hpp>\n#include <boost\/proto\/core.hpp>\n#include <boost\/proto\/context.hpp>\nnamespace mpl = boost::mpl;\nnamespace proto = boost::proto;\nusing proto::_;\n\n\/\/ This grammar describes which lazy vector expressions\n\/\/ are allowed; namely, vector terminals and addition\n\/\/ and subtraction of lazy vector expressions.\nstruct LazyVectorGrammar\n  : proto::or_<\n        proto::terminal< std::vector<_> >\n      , proto::plus< LazyVectorGrammar, LazyVectorGrammar >\n      , proto::minus< LazyVectorGrammar, LazyVectorGrammar >\n    >\n{};\n\n\/\/ Expressions in the lazy vector domain must conform\n\/\/ to the lazy vector grammar\nstruct lazy_vector_domain;\n\n\/\/ Here is an evaluation context that indexes into a lazy vector\n\/\/ expression, and combines the result.\ntemplate<typename Size = std::size_t>\nstruct lazy_subscript_context\n{\n    lazy_subscript_context(Size subscript)\n      : subscript_(subscript)\n    {}\n\n    \/\/ Use default_eval for all the operations ...\n    template<typename Expr, typename Tag = typename Expr::proto_tag>\n    struct eval\n      : proto::default_eval<Expr, lazy_subscript_context>\n    {};\n\n    \/\/ ... except for terminals, which we index with our subscript\n    template<typename Expr>\n    struct eval<Expr, proto::tag::terminal>\n    {\n        typedef typename proto::result_of::value<Expr>::type::value_type result_type;\n\n        result_type operator ()( Expr const & expr, lazy_subscript_context & ctx ) const\n        {\n            return proto::value( expr )[ ctx.subscript_ ];\n        }\n    };\n\n    Size subscript_;\n};\n\n\/\/ Here is the domain-specific expression wrapper, which overrides\n\/\/ operator [] to evaluate the expression using the lazy_subscript_context.\ntemplate<typename Expr>\nstruct lazy_vector_expr\n  : proto::extends<Expr, lazy_vector_expr<Expr>, lazy_vector_domain>\n{\n    typedef proto::extends<Expr, lazy_vector_expr<Expr>, lazy_vector_domain> base_type;\n\n    lazy_vector_expr( Expr const & expr = Expr() )\n      : base_type( expr )\n    {}\n\n    \/\/ Use the lazy_subscript_context<> to implement subscripting\n    \/\/ of a lazy vector expression tree.\n    template< typename Size >\n    typename proto::result_of::eval< Expr, lazy_subscript_context<Size> >::type\n    operator []( Size subscript ) const\n    {\n        lazy_subscript_context<Size> ctx(subscript);\n        return proto::eval(*this, ctx);\n    }\n};\n\n\/\/ Here is our lazy_vector terminal, implemented in terms of lazy_vector_expr\ntemplate< typename T >\nstruct lazy_vector\n  : lazy_vector_expr< typename proto::terminal< std::vector<T> >::type >\n{\n    typedef typename proto::terminal< std::vector<T> >::type expr_type;\n\n    lazy_vector( std::size_t size = 0, T const & value = T() )\n      : lazy_vector_expr<expr_type>( expr_type::make( std::vector<T>( size, value ) ) )\n    {}\n\n    \/\/ Here we define a += operator for lazy vector terminals that\n    \/\/ takes a lazy vector expression and indexes it. expr[i] here\n    \/\/ uses lazy_subscript_context<> under the covers.\n    template< typename Expr >\n    lazy_vector &operator += (Expr const & expr)\n    {\n        std::size_t size = proto::value(*this).size();\n        for(std::size_t i = 0; i < size; ++i)\n        {\n            proto::value(*this)[i] += expr[i];\n        }\n        return *this;\n    }\n};\n\n\/\/ Tell proto that in the lazy_vector_domain, all\n\/\/ expressions should be wrapped in laxy_vector_expr<>\nstruct lazy_vector_domain\n  : proto::domain<proto::generator<lazy_vector_expr>, LazyVectorGrammar>\n{};\n\nint main()\n{\n    \/\/ lazy_vectors with 4 elements each.\n    lazy_vector< double > v1( 4, 1.0 ), v2( 4, 2.0 ), v3( 4, 3.0 );\n\n    \/\/ Add two vectors lazily and get the 2nd element.\n    double d1 = ( v2 + v3 )[ 2 ];   \/\/ Look ma, no temporaries!\n    std::cout << d1 << std::endl;\n\n    \/\/ Subtract two vectors and add the result to a third vector.\n    v1 += v2 - v3;                  \/\/ Still no temporaries!\n    std::cout << '{' << v1[0] << ',' << v1[1]\n              << ',' << v1[2] << ',' << v1[3] << '}' << std::endl;\n\n    \/\/ This expression is disallowed because it does not conform\n    \/\/ to the LazyVectorGrammar\n    \/\/(v2 + v3) += v1;\n\n    return 0;\n}\n\/\/]\n","avg_line_length":32.9931034483,"max_line_length":88,"alphanum_fraction":0.6599080268,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1539,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ ----------------------------------------------------------------------------\n\/\/ -                        Open3D: www.open3d.org                            -\n\/\/ ----------------------------------------------------------------------------\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2018 www.open3d.org\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/ ----------------------------------------------------------------------------\n\n#include \"UnitTest.h\"\n\nTEST(PickingShader, Default)\n{\n    NotImplemented();\n}\n","avg_line_length":46.6363636364,"max_line_length":80,"alphanum_fraction":0.6107862248,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":35227,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <thrift\/lib\/cpp2\/async\/RocketClientChannel.h>\n\n#include <memory>\n#include <utility>\n\n#include <fmt\/core.h>\n#include <folly\/ExceptionString.h>\n#include <folly\/GLog.h>\n#include <folly\/Likely.h>\n#include <folly\/Memory.h>\n#include <folly\/Try.h>\n#include <folly\/compression\/Compression.h>\n#include <folly\/fibers\/FiberManager.h>\n#include <folly\/io\/IOBuf.h>\n#include <folly\/io\/IOBufQueue.h>\n#include <folly\/io\/async\/AsyncTransport.h>\n#include <folly\/io\/async\/EventBase.h>\n#include <folly\/io\/async\/Request.h>\n\n#include <thrift\/lib\/cpp\/TApplicationException.h>\n#include <thrift\/lib\/cpp\/protocol\/TBase64Utils.h>\n#include <thrift\/lib\/cpp\/transport\/THeader.h>\n#include <thrift\/lib\/cpp2\/Flags.h>\n#include <thrift\/lib\/cpp2\/async\/HeaderChannel.h>\n#include <thrift\/lib\/cpp2\/async\/RequestChannel.h>\n#include <thrift\/lib\/cpp2\/async\/ResponseChannel.h>\n#include <thrift\/lib\/cpp2\/protocol\/CompactProtocol.h>\n#include <thrift\/lib\/cpp2\/transport\/core\/EnvelopeUtil.h>\n#include <thrift\/lib\/cpp2\/transport\/core\/RpcMetadataUtil.h>\n#include <thrift\/lib\/cpp2\/transport\/core\/ThriftClientCallback.h>\n#include <thrift\/lib\/cpp2\/transport\/core\/TryUtil.h>\n#include <thrift\/lib\/cpp2\/transport\/rocket\/PayloadUtils.h>\n#include <thrift\/lib\/cpp2\/transport\/rocket\/RocketException.h>\n#include <thrift\/lib\/cpp2\/transport\/rocket\/client\/RocketClient.h>\n#include <thrift\/lib\/thrift\/gen-cpp2\/RpcMetadata_constants.h>\n#include <thrift\/lib\/thrift\/gen-cpp2\/RpcMetadata_types.h>\n\nTHRIFT_FLAG_DEFINE_bool(rocket_client_new_protocol_key, false);\n\nusing namespace apache::thrift::transport;\n\nnamespace apache {\nnamespace thrift {\n\nnamespace {\nfolly::Try<FirstResponsePayload> decodeResponseError(\n    rocket::RocketException&& ex,\n    uint16_t protocolId,\n    folly::StringPiece methodName) noexcept {\n  switch (ex.getErrorCode()) {\n    case rocket::ErrorCode::CANCELED:\n    case rocket::ErrorCode::INVALID:\n    case rocket::ErrorCode::REJECTED:\n      break;\n    default:\n      return folly::Try<FirstResponsePayload>(\n          folly::make_exception_wrapper<TApplicationException>(fmt::format(\n              \"Unexpected error frame type: {}\",\n              static_cast<uint32_t>(ex.getErrorCode()))));\n  }\n\n  ResponseRpcError responseError;\n  try {\n    rocket::unpackCompact(responseError, ex.moveErrorData().get());\n  } catch (...) {\n    return folly::Try<FirstResponsePayload>(\n        folly::make_exception_wrapper<TApplicationException>(fmt::format(\n            \"Error parsing error frame: {}\",\n            folly::exceptionStr(std::current_exception()).toStdString())));\n  }\n\n  folly::Optional<std::string> exCode;\n  TApplicationException::TApplicationExceptionType exType{\n      TApplicationException::UNKNOWN};\n  switch (responseError.code_ref().value_or(ResponseRpcErrorCode::UNKNOWN)) {\n    case ResponseRpcErrorCode::OVERLOAD:\n      exCode = kOverloadedErrorCode;\n      exType = TApplicationException::LOADSHEDDING;\n      break;\n    case ResponseRpcErrorCode::TASK_EXPIRED:\n      exCode = kTaskExpiredErrorCode;\n      exType = TApplicationException::TIMEOUT;\n      break;\n    case ResponseRpcErrorCode::QUEUE_OVERLOADED:\n    case ResponseRpcErrorCode::SHUTDOWN:\n      exCode = kQueueOverloadedErrorCode;\n      exType = TApplicationException::LOADSHEDDING;\n      break;\n    case ResponseRpcErrorCode::INJECTED_FAILURE:\n      exCode = kInjectedFailureErrorCode;\n      exType = TApplicationException::INJECTED_FAILURE;\n      break;\n    case ResponseRpcErrorCode::REQUEST_PARSING_FAILURE:\n      exCode = kRequestParsingErrorCode;\n      exType = TApplicationException::UNSUPPORTED_CLIENT_TYPE;\n      break;\n    case ResponseRpcErrorCode::QUEUE_TIMEOUT:\n      exCode = kServerQueueTimeoutErrorCode;\n      exType = TApplicationException::TIMEOUT;\n      break;\n    case ResponseRpcErrorCode::RESPONSE_TOO_BIG:\n      exCode = kResponseTooBigErrorCode;\n      exType = TApplicationException::INTERNAL_ERROR;\n      break;\n    case ResponseRpcErrorCode::WRONG_RPC_KIND:\n      exCode = kRequestTypeDoesntMatchServiceFunctionType;\n      exType = TApplicationException::UNKNOWN_METHOD;\n      break;\n    case ResponseRpcErrorCode::UNKNOWN_METHOD:\n      exCode = kMethodUnknownErrorCode;\n      exType = TApplicationException::UNKNOWN_METHOD;\n      break;\n    case ResponseRpcErrorCode::CHECKSUM_MISMATCH:\n      exCode = kUnknownErrorCode;\n      exType = TApplicationException::CHECKSUM_MISMATCH;\n      break;\n    case ResponseRpcErrorCode::INTERRUPTION:\n      exType = TApplicationException::INTERRUPTION;\n      break;\n    case ResponseRpcErrorCode::APP_OVERLOAD:\n      exCode = kAppOverloadedErrorCode;\n      exType = TApplicationException::LOADSHEDDING;\n      break;\n    case ResponseRpcErrorCode::UNKNOWN_INTERACTION_ID:\n      exCode = kInteractionIdUnknownErrorCode;\n      break;\n    case ResponseRpcErrorCode::INTERACTION_CONSTRUCTOR_ERROR:\n      exCode = kInteractionConstructorErrorErrorCode;\n      break;\n    default:\n      exCode = kUnknownErrorCode;\n      break;\n  }\n\n  ResponseRpcMetadata metadata;\n  if (exCode) {\n    metadata.otherMetadata_ref().emplace();\n    (*metadata.otherMetadata_ref())[\"ex\"] = *exCode;\n  }\n  if (auto loadRef = responseError.load_ref()) {\n    metadata.load_ref() = *loadRef;\n  }\n  return folly::Try<FirstResponsePayload>(FirstResponsePayload(\n      LegacySerializedResponse(\n          protocolId,\n          methodName,\n          TApplicationException(\n              exType, responseError.what_utf8_ref().value_or(\"\")))\n          .buffer,\n      std::move(metadata)));\n}\n\nFOLLY_NODISCARD folly::exception_wrapper processFirstResponse(\n    ResponseRpcMetadata& metadata,\n    std::unique_ptr<folly::IOBuf>& payload,\n    uint16_t protocolId,\n    folly::StringPiece methodName) {\n  if (auto payloadMetadataRef = metadata.payloadMetadata_ref()) {\n    const auto isProxiedResponse =\n        metadata.proxiedPayloadMetadata_ref().has_value();\n\n    switch (payloadMetadataRef->getType()) {\n      case PayloadMetadata::responseMetadata:\n        payload =\n            LegacySerializedResponse(\n                protocolId, methodName, SerializedResponse(std::move(payload)))\n                .buffer;\n        break;\n      case PayloadMetadata::exceptionMetadata: {\n        auto& exceptionMetadataBase =\n            payloadMetadataRef->get_exceptionMetadata();\n        auto otherMetadataRef = metadata.otherMetadata_ref();\n        if (!otherMetadataRef) {\n          otherMetadataRef.emplace();\n        }\n        auto exceptionNameRef = exceptionMetadataBase.name_utf8_ref();\n        auto exceptionWhatRef = exceptionMetadataBase.what_utf8_ref();\n        if (auto exceptionMetadataRef = exceptionMetadataBase.metadata_ref()) {\n          switch (exceptionMetadataRef->getType()) {\n            case PayloadExceptionMetadata::declaredException:\n              if (exceptionNameRef) {\n                (*otherMetadataRef)[isProxiedResponse ? \"puex\" : \"uex\"] =\n                    *exceptionNameRef;\n              }\n              if (exceptionWhatRef) {\n                (*otherMetadataRef)[isProxiedResponse ? \"puexw\" : \"uexw\"] =\n                    *exceptionWhatRef;\n              }\n              payload = LegacySerializedResponse(\n                            protocolId,\n                            methodName,\n                            SerializedResponse(std::move(payload)))\n                            .buffer;\n              break;\n            case PayloadExceptionMetadata::proxyException:\n              (*otherMetadataRef)\n                  [isProxiedResponse ? \"servicerouter:sr_error\"\n                                     : \"servicerouter:sr_internal_error\"] =\n                      protocol::base64Encode(payload->coalesce());\n              payload =\n                  LegacySerializedResponse(\n                      protocolId,\n                      methodName,\n                      TApplicationException(exceptionWhatRef.value_or(\"\")))\n                      .buffer;\n              break;\n            case PayloadExceptionMetadata::proxiedException:\n              (*otherMetadataRef)[\"servicerouter:sr_error\"] =\n                  protocol::base64Encode(payload->coalesce());\n              payload =\n                  LegacySerializedResponse(\n                      protocolId,\n                      methodName,\n                      TApplicationException(exceptionWhatRef.value_or(\"\")))\n                      .buffer;\n              break;\n            case PayloadExceptionMetadata::appClientException:\n              (*otherMetadataRef)[isProxiedResponse ? \"pex\" : \"ex\"] =\n                  kAppClientErrorCode;\n              FOLLY_FALLTHROUGH;\n            default:\n              if (exceptionNameRef) {\n                (*otherMetadataRef)[isProxiedResponse ? \"puex\" : \"uex\"] =\n                    *exceptionNameRef;\n              }\n              if (exceptionWhatRef) {\n                (*otherMetadataRef)[isProxiedResponse ? \"puexw\" : \"uexw\"] =\n                    *exceptionWhatRef;\n              }\n              payload =\n                  LegacySerializedResponse(\n                      protocolId,\n                      methodName,\n                      TApplicationException(exceptionWhatRef.value_or(\"\")))\n                      .buffer;\n          }\n        } else {\n          return TApplicationException(\"Missing payload exception metadata\");\n        }\n        break;\n      }\n      default:\n        return TApplicationException(\"Invalid payload metadata type\");\n    }\n  }\n  return {};\n}\n\nclass FirstRequestProcessorStream : public StreamClientCallback,\n                                    private StreamServerCallback {\n public:\n  FirstRequestProcessorStream(\n      uint16_t protocolId,\n      folly::StringPiece methodName,\n      StreamClientCallback* clientCallback,\n      folly::EventBase* evb)\n      : protocolId_(protocolId),\n        methodName_(methodName),\n        clientCallback_(clientCallback),\n        evb_(evb) {}\n\n  FOLLY_NODISCARD bool onFirstResponse(\n      FirstResponsePayload&& firstResponse,\n      folly::EventBase* evb,\n      StreamServerCallback* serverCallback) override {\n    SCOPE_EXIT {\n      delete this;\n    };\n    DCHECK_EQ(evb, evb_);\n    if (auto error = processFirstResponse(\n            firstResponse.metadata,\n            firstResponse.payload,\n            protocolId_,\n            methodName_)) {\n      serverCallback->onStreamCancel();\n      clientCallback_->onFirstResponseError(std::move(error));\n      return false;\n    }\n    serverCallback->resetClientCallback(*clientCallback_);\n    return clientCallback_->onFirstResponse(\n        std::move(firstResponse), evb, serverCallback);\n  }\n  void onFirstResponseError(folly::exception_wrapper ew) override {\n    SCOPE_EXIT {\n      delete this;\n    };\n    ew.handle(\n        [&](rocket::RocketException& ex) {\n          auto response =\n              decodeResponseError(std::move(ex), protocolId_, methodName_);\n          if (response.hasException()) {\n            clientCallback_->onFirstResponseError(\n                std::move(response).exception());\n            return;\n          }\n\n          if (clientCallback_->onFirstResponse(\n                  std::move(*response), evb_, this)) {\n            DCHECK(clientCallback_);\n            clientCallback_->onStreamComplete();\n          }\n        },\n        [&](...) { clientCallback_->onFirstResponseError(std::move(ew)); });\n  }\n\n  bool onStreamNext(StreamPayload&&) override {\n    std::terminate();\n  }\n  void onStreamError(folly::exception_wrapper) override {\n    std::terminate();\n  }\n  void onStreamComplete() override {\n    std::terminate();\n  }\n  void resetServerCallback(StreamServerCallback&) override {\n    std::terminate();\n  }\n\n  void onStreamCancel() override {\n    clientCallback_ = nullptr;\n  }\n  bool onStreamRequestN(uint64_t) override {\n    return true;\n  }\n  void resetClientCallback(StreamClientCallback& clientCallback) override {\n    clientCallback_ = &clientCallback;\n  }\n\n private:\n  const uint16_t protocolId_;\n  const std::string methodName_;\n  StreamClientCallback* clientCallback_;\n  folly::EventBase* evb_;\n};\n\nclass FirstRequestProcessorSink : public SinkClientCallback,\n                                  private SinkServerCallback {\n public:\n  FirstRequestProcessorSink(\n      uint16_t protocolId,\n      folly::StringPiece methodName,\n      SinkClientCallback* clientCallback,\n      folly::EventBase* evb)\n      : protocolId_(protocolId),\n        methodName_(methodName),\n        clientCallback_(clientCallback),\n        evb_(evb) {}\n\n  FOLLY_NODISCARD bool onFirstResponse(\n      FirstResponsePayload&& firstResponse,\n      folly::EventBase* evb,\n      SinkServerCallback* serverCallback) override {\n    SCOPE_EXIT {\n      delete this;\n    };\n    if (auto error = processFirstResponse(\n            firstResponse.metadata,\n            firstResponse.payload,\n            protocolId_,\n            methodName_)) {\n      serverCallback->onSinkError(\n          folly::make_exception_wrapper<TApplicationException>(\n              TApplicationException::INTERRUPTION,\n              \"process first response error\"));\n      clientCallback_->onFirstResponseError(std::move(error));\n      return false;\n    }\n    serverCallback->resetClientCallback(*clientCallback_);\n    return clientCallback_->onFirstResponse(\n        std::move(firstResponse), evb, serverCallback);\n  }\n  void onFirstResponseError(folly::exception_wrapper ew) override {\n    SCOPE_EXIT {\n      delete this;\n    };\n    ew.handle(\n        [&](rocket::RocketException& ex) {\n          auto response =\n              decodeResponseError(std::move(ex), protocolId_, methodName_);\n          if (response.hasException()) {\n            clientCallback_->onFirstResponseError(\n                std::move(response).exception());\n            return;\n          }\n\n          if (clientCallback_->onFirstResponse(\n                  std::move(*response), evb_, this)) {\n            DCHECK(clientCallback_);\n            \/\/ This exception will be ignored, but we have to send it to follow\n            \/\/ the contract.\n            clientCallback_->onFinalResponseError(\n                folly::make_exception_wrapper<TApplicationException>(\n                    TApplicationException::INTERRUPTION,\n                    \"Initial response error\"));\n          }\n        },\n        [&](...) {\n          clientCallback_->onFirstResponseError(std::move(ew));\n          return false;\n        });\n  }\n\n  void onFinalResponse(StreamPayload&&) override {\n    std::terminate();\n  }\n  void onFinalResponseError(folly::exception_wrapper) override {\n    std::terminate();\n  }\n  FOLLY_NODISCARD bool onSinkRequestN(uint64_t) override {\n    std::terminate();\n  }\n  void resetServerCallback(SinkServerCallback&) override {\n    std::terminate();\n  }\n\n  bool onSinkNext(StreamPayload&&) override {\n    return true;\n  }\n  void onSinkError(folly::exception_wrapper) override {\n    clientCallback_ = nullptr;\n  }\n  bool onSinkComplete() override {\n    return true;\n  }\n  void resetClientCallback(SinkClientCallback& clientCallback) override {\n    clientCallback_ = &clientCallback;\n  }\n\n private:\n  const uint16_t protocolId_;\n  const std::string methodName_;\n  SinkClientCallback* clientCallback_;\n  folly::EventBase* evb_;\n};\n\nvoid setCompression(RequestRpcMetadata& metadata, ssize_t payloadSize) {\n  if (auto compressionConfig = metadata.compressionConfig_ref()) {\n    if (auto codecRef = compressionConfig->codecConfig_ref()) {\n      if (payloadSize >\n          compressionConfig->compressionSizeLimit_ref().value_or(0)) {\n        switch (codecRef->getType()) {\n          case CodecConfig::zlibConfig:\n            metadata.compression_ref() = CompressionAlgorithm::ZLIB;\n            break;\n          case CodecConfig::zstdConfig:\n            metadata.compression_ref() = CompressionAlgorithm::ZSTD;\n            break;\n          default:\n            break;\n        }\n      }\n    }\n  }\n}\n} \/\/ namespace\n\nclass RocketClientChannel::SingleRequestSingleResponseCallback final\n    : public rocket::RocketClient::RequestResponseCallback {\n  using InflightGuardT =\n      decltype(std::declval<RocketClientChannel>().inflightGuard());\n\n public:\n  SingleRequestSingleResponseCallback(\n      RequestClientCallback::Ptr cb,\n      InflightGuardT g,\n      uint16_t protocolId,\n      std::string methodName,\n      size_t requestSerializedSize,\n      size_t requestWireSize)\n      : cb_(std::move(cb)),\n        g_(std::move(g)),\n        protocolId_(protocolId),\n        methodName_(std::move(methodName)),\n        requestSerializedSize_(requestSerializedSize),\n        requestWireSize_(requestWireSize) {}\n\n  void onWriteSuccess() noexcept override {\n    cb_->onRequestSent();\n  }\n\n  void onResponsePayload(\n      folly::Try<rocket::Payload>&& payload) noexcept override {\n    folly::Try<FirstResponsePayload> response;\n    RpcSizeStats stats;\n    stats.requestSerializedSizeBytes = requestSerializedSize_;\n    stats.requestWireSizeBytes = requestWireSize_;\n    if (payload.hasException()) {\n      if (!payload.exception().with_exception<rocket::RocketException>(\n              [&](auto& ex) {\n                response = decodeResponseError(\n                    std::move(ex), protocolId_, methodName_);\n              })) {\n        cb_.release()->onResponseError(std::move(payload.exception()));\n        return;\n      }\n      if (response.hasException()) {\n        cb_.release()->onResponseError(std::move(response.exception()));\n        return;\n      }\n    } else {\n      stats.responseWireSizeBytes =\n          payload->metadataAndDataSize() - payload->metadataSize();\n\n      response = rocket::unpack<FirstResponsePayload>(std::move(*payload));\n      if (response.hasException()) {\n        cb_.release()->onResponseError(std::move(response.exception()));\n        return;\n      }\n      if (auto error = processFirstResponse(\n              response->metadata,\n              response->payload,\n              protocolId_,\n              methodName_)) {\n        cb_.release()->onResponseError(std::move(error));\n        return;\n      }\n    }\n\n    stats.responseSerializedSizeBytes =\n        response->payload->computeChainDataLength();\n\n    auto tHeader = std::make_unique<transport::THeader>();\n    tHeader->setClientType(THRIFT_ROCKET_CLIENT_TYPE);\n\n    apache::thrift::detail::fillTHeaderFromResponseRpcMetadata(\n        response->metadata, *tHeader);\n    cb_.release()->onResponse(ClientReceiveState(\n        static_cast<uint16_t>(-1),\n        std::move(response->payload),\n        std::move(tHeader),\n        nullptr, \/* ctx *\/\n        stats));\n  }\n\n private:\n  RequestClientCallback::Ptr cb_;\n  InflightGuardT g_;\n  const uint16_t protocolId_;\n  std::string methodName_;\n  const size_t requestSerializedSize_;\n  const size_t requestWireSize_;\n};\n\nclass RocketClientChannel::SingleRequestNoResponseCallback final\n    : public rocket::RocketClient::RequestFnfCallback {\n  using InflightGuardT =\n      decltype(std::declval<RocketClientChannel>().inflightGuard());\n\n public:\n  SingleRequestNoResponseCallback(\n      RequestClientCallback::Ptr cb,\n      InflightGuardT g)\n      : cb_(std::move(cb)), g_(std::move(g)) {}\n\n  void onWrite(folly::Try<void> writeResult) noexcept override {\n    auto* cbPtr = cb_.release();\n    if (writeResult.hasException()) {\n      cbPtr->onResponseError(std::move(writeResult).exception());\n    } else {\n      cbPtr->onRequestSent();\n    }\n  }\n\n private:\n  RequestClientCallback::Ptr cb_;\n  InflightGuardT g_;\n};\n\nrocket::SetupFrame RocketClientChannel::makeSetupFrame(\n    RequestSetupMetadata meta) {\n  meta.maxVersion_ref() = 6;\n  if (const auto& hostId = ClientChannel::getHostId(); hostId) {\n    meta.clientHostId_ref() = *hostId;\n  }\n  CompactProtocolWriter compactProtocolWriter;\n  folly::IOBufQueue paramQueue;\n  compactProtocolWriter.setOutput(&paramQueue);\n  meta.write(&compactProtocolWriter);\n\n  \/\/ Serialize RocketClient's major\/minor version (which is separate from the\n  \/\/ rsocket protocol major\/minor version) into setup metadata.\n  auto buf = folly::IOBuf::createCombined(\n      sizeof(int32_t) + meta.serializedSize(&compactProtocolWriter));\n  folly::IOBufQueue queue;\n  queue.append(std::move(buf));\n  folly::io::QueueAppender appender(&queue, \/* do not grow *\/ 0);\n  const uint32_t protocolKey = THRIFT_FLAG(rocket_client_new_protocol_key)\n      ? RpcMetadata_constants::kRocketProtocolKey()\n      : 1;\n  appender.writeBE<uint32_t>(protocolKey); \/\/ Rocket protocol key\n  \/\/ Append serialized setup parameters to setup frame metadata\n  appender.insert(paramQueue.move());\n\n  return rocket::SetupFrame(\n      rocket::Payload::makeFromMetadataAndData(queue.move(), {}));\n}\n\nvoid RocketClientChannel::handleMetadataPush(\n    rocket::MetadataPushFrame&& frame) {\n  if (!frame.metadata()) {\n    return;\n  }\n\n  try {\n    CompactProtocolReader reader;\n    reader.setInput(frame.metadata());\n    ServerPushMetadata metadata;\n    metadata.read(&reader);\n    switch (metadata.getType()) {\n      case ServerPushMetadata::setupResponse: {\n        if (auto version = metadata.setupResponse_ref()->version_ref()) {\n          serverVersion_ = *version;\n        }\n        break;\n      }\n      default:\n        break;\n    }\n  } catch (...) {\n    FB_LOG_EVERY_MS(WARNING, 60 * 1000)\n        << \"fail to deserialize metadata push frame\"\n        << folly::exceptionStr(std::current_exception());\n  }\n}\n\nRocketClientChannel::RocketClientChannel(\n    folly::AsyncTransport::UniquePtr socket,\n    RequestSetupMetadata meta)\n    : evb_(socket->getEventBase()),\n      rclient_(rocket::RocketClient::create(\n          *evb_,\n          std::move(socket),\n          std::make_unique<rocket::SetupFrame>(makeSetupFrame(std::move(meta))),\n          [this](rocket::MetadataPushFrame&& frame) {\n            handleMetadataPush(std::move(frame));\n          })) {}\n\nRocketClientChannel::~RocketClientChannel() {\n  unsetOnDetachable();\n  if (rclient_) {\n    rclient_->setOnMetadataPush(nullptr);\n  }\n  closeNow();\n}\n\nvoid RocketClientChannel::setFlushList(FlushList* flushList) {\n  if (rclient_) {\n    rclient_->setFlushList(flushList);\n  }\n}\n\nvoid RocketClientChannel::setNegotiatedCompressionAlgorithm(\n    CompressionAlgorithm compressionAlgo) {\n  if (rclient_) {\n    rclient_->setNegotiatedCompressionAlgorithm(compressionAlgo);\n  }\n}\n\nvoid RocketClientChannel::setAutoCompressSizeLimit(int32_t size) {\n  if (rclient_) {\n    rclient_->setAutoCompressSizeLimit(size);\n  }\n}\n\nRocketClientChannel::Ptr RocketClientChannel::newChannel(\n    folly::AsyncTransport::UniquePtr socket) {\n  return RocketClientChannel::Ptr(\n      new RocketClientChannel(std::move(socket), RequestSetupMetadata()));\n}\nRocketClientChannel::Ptr RocketClientChannel::newChannelWithMetadata(\n    folly::AsyncTransport::UniquePtr socket,\n    RequestSetupMetadata meta) {\n  return RocketClientChannel::Ptr(\n      new RocketClientChannel(std::move(socket), std::move(meta)));\n}\n\nvoid RocketClientChannel::sendRequestResponse(\n    const RpcOptions& rpcOptions,\n    folly::StringPiece methodName,\n    SerializedRequest&& request,\n    std::shared_ptr<transport::THeader> header,\n    RequestClientCallback::Ptr cb) {\n  sendThriftRequest(\n      rpcOptions,\n      RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE,\n      methodName,\n      std::move(request),\n      std::move(header),\n      std::move(cb));\n}\n\nvoid RocketClientChannel::sendRequestNoResponse(\n    const RpcOptions& rpcOptions,\n    folly::StringPiece methodName,\n    SerializedRequest&& request,\n    std::shared_ptr<transport::THeader> header,\n    RequestClientCallback::Ptr cb) {\n  sendThriftRequest(\n      rpcOptions,\n      RpcKind::SINGLE_REQUEST_NO_RESPONSE,\n      methodName,\n      std::move(request),\n      std::move(header),\n      std::move(cb));\n}\n\nvoid RocketClientChannel::sendRequestStream(\n    const RpcOptions& rpcOptions,\n    folly::StringPiece methodName,\n    SerializedRequest&& request,\n    std::shared_ptr<THeader> header,\n    StreamClientCallback* clientCallback) {\n  DestructorGuard dg(this);\n\n  auto metadata = apache::thrift::detail::makeRequestRpcMetadata(\n      rpcOptions,\n      RpcKind::SINGLE_REQUEST_STREAMING_RESPONSE,\n      static_cast<ProtocolId>(protocolId_),\n      methodName,\n      timeout_,\n      *header,\n      getPersistentWriteHeaders(),\n      serverVersion_);\n\n  std::chrono::milliseconds firstResponseTimeout;\n  if (!preSendValidation(\n          metadata, rpcOptions, clientCallback, firstResponseTimeout)) {\n    return;\n  }\n\n  auto buf = std::move(request.buffer);\n  setCompression(metadata, buf->computeChainDataLength());\n\n  return rclient_->sendRequestStream(\n      rocket::pack(metadata, std::move(buf)),\n      firstResponseTimeout,\n      rpcOptions.getChunkTimeout(),\n      rpcOptions.getChunkBufferSize(),\n      new FirstRequestProcessorStream(\n          protocolId_, methodName, clientCallback, evb_));\n}\n\nvoid RocketClientChannel::sendRequestSink(\n    const RpcOptions& rpcOptions,\n    folly::StringPiece methodName,\n    SerializedRequest&& request,\n    std::shared_ptr<transport::THeader> header,\n    SinkClientCallback* clientCallback) {\n  DestructorGuard dg(this);\n\n  auto metadata = apache::thrift::detail::makeRequestRpcMetadata(\n      rpcOptions,\n      RpcKind::SINK,\n      static_cast<ProtocolId>(protocolId_),\n      methodName,\n      timeout_,\n      *header,\n      getPersistentWriteHeaders(),\n      serverVersion_);\n\n  std::chrono::milliseconds firstResponseTimeout;\n  if (!preSendValidation(\n          metadata, rpcOptions, clientCallback, firstResponseTimeout)) {\n    return;\n  }\n\n  auto buf = std::move(request.buffer);\n  setCompression(metadata, buf->computeChainDataLength());\n\n  return rclient_->sendRequestSink(\n      rocket::pack(metadata, std::move(buf)),\n      firstResponseTimeout,\n      new FirstRequestProcessorSink(\n          protocolId_, methodName, clientCallback, evb_),\n      rpcOptions.getEnablePageAlignment(),\n      header->getDesiredCompressionConfig());\n}\n\nvoid RocketClientChannel::sendThriftRequest(\n    const RpcOptions& rpcOptions,\n    RpcKind kind,\n    folly::StringPiece methodName,\n    SerializedRequest&& request,\n    std::shared_ptr<transport::THeader> header,\n    RequestClientCallback::Ptr cb) {\n  DestructorGuard dg(this);\n\n  auto metadata = apache::thrift::detail::makeRequestRpcMetadata(\n      rpcOptions,\n      kind,\n      static_cast<ProtocolId>(protocolId_),\n      methodName,\n      timeout_,\n      *header,\n      getPersistentWriteHeaders(),\n      serverVersion_);\n\n  std::chrono::milliseconds timeout;\n  if (!preSendValidation(metadata, rpcOptions, cb, timeout)) {\n    return;\n  }\n\n  auto buf = std::move(request.buffer);\n  setCompression(metadata, buf->computeChainDataLength());\n\n  switch (kind) {\n    case RpcKind::SINGLE_REQUEST_NO_RESPONSE:\n      sendSingleRequestNoResponse(metadata, std::move(buf), std::move(cb));\n      break;\n\n    case RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE:\n      sendSingleRequestSingleResponse(\n          metadata, timeout, std::move(buf), std::move(cb));\n      break;\n\n    case RpcKind::SINGLE_REQUEST_STREAMING_RESPONSE:\n      \/\/ should no longer reach here anymore, use sendRequestStream\n      DCHECK(false);\n      break;\n\n    default:\n      folly::assume_unreachable();\n  }\n}\n\nvoid RocketClientChannel::sendSingleRequestNoResponse(\n    const RequestRpcMetadata& metadata,\n    std::unique_ptr<folly::IOBuf> buf,\n    RequestClientCallback::Ptr cb) {\n  auto requestPayload = rocket::pack(metadata, std::move(buf));\n  const bool isSync = cb->isSync();\n  SingleRequestNoResponseCallback callback(std::move(cb), inflightGuard());\n\n  if (isSync && folly::fibers::onFiber()) {\n    callback.onWrite(rclient_->sendRequestFnfSync(std::move(requestPayload)));\n  } else {\n    rclient_->sendRequestFnf(\n        std::move(requestPayload),\n        folly::copy_to_unique_ptr(std::move(callback)));\n  }\n}\n\nvoid RocketClientChannel::sendSingleRequestSingleResponse(\n    const RequestRpcMetadata& metadata,\n    std::chrono::milliseconds timeout,\n    std::unique_ptr<folly::IOBuf> buf,\n    RequestClientCallback::Ptr cb) {\n  const auto requestSerializedSize = buf->computeChainDataLength();\n  auto requestPayload = rocket::pack(metadata, std::move(buf));\n  const auto requestWireSize = requestPayload.dataSize();\n  const bool isSync = cb->isSync();\n  SingleRequestSingleResponseCallback callback(\n      std::move(cb),\n      inflightGuard(),\n      static_cast<uint16_t>(metadata.protocol_ref().value_unchecked()),\n      metadata.name_ref().value_or({}),\n      requestSerializedSize,\n      requestWireSize);\n\n  if (isSync && folly::fibers::onFiber()) {\n    callback.onResponsePayload(rclient_->sendRequestResponseSync(\n        std::move(requestPayload), timeout, &callback));\n  } else {\n    rclient_->sendRequestResponse(\n        std::move(requestPayload),\n        timeout,\n        folly::copy_to_unique_ptr(std::move(callback)));\n  }\n}\n\nvoid onResponseError(\n    RequestClientCallback::Ptr& cb,\n    folly::exception_wrapper ew) {\n  cb.release()->onResponseError(std::move(ew));\n}\n\nvoid onResponseError(StreamClientCallback* cb, folly::exception_wrapper ew) {\n  cb->onFirstResponseError(std::move(ew));\n}\n\nvoid onResponseError(SinkClientCallback* cb, folly::exception_wrapper ew) {\n  cb->onFirstResponseError(std::move(ew));\n}\n\ntemplate <typename CallbackPtr>\nbool RocketClientChannel::preSendValidation(\n    RequestRpcMetadata& metadata,\n    const RpcOptions& rpcOptions,\n    CallbackPtr& cb,\n    std::chrono::milliseconds& firstResponseTimeout) {\n  metadata.seqId_ref().reset();\n  DCHECK(metadata.kind_ref().has_value());\n\n  if (!rclient_) {\n    \/\/ Channel destroyed by explicit closeNow() call.\n    onResponseError(\n        cb,\n        folly::make_exception_wrapper<TTransportException>(\n            TTransportException::NOT_OPEN,\n            \"Connection not open: client destroyed due to closeNow.\"));\n    return false;\n  }\n\n  if (!rclient_->isAlive()) {\n    \/\/ Channel is not in connected state due to some pre-existing transport\n    \/\/ exception, pass it back for some breadcrumbs.\n    onResponseError(\n        cb,\n        folly::make_exception_wrapper<TTransportException>(\n            TTransportException::NOT_OPEN,\n            folly::sformat(\n                \"Connection not open: {}\",\n                rclient_->getLastTransportError().what())));\n    return false;\n  }\n\n  if (inflightRequestsAndStreams() >= maxInflightRequestsAndStreams_) {\n    TTransportException ex(\n        TTransportException::NETWORK_ERROR,\n        \"Too many active requests on connection\");\n    \/\/ Might be able to create another transaction soon\n    ex.setOptions(TTransportException::CHANNEL_IS_VALID);\n    onResponseError(cb, std::move(ex));\n    return false;\n  }\n\n  firstResponseTimeout =\n      std::chrono::milliseconds(metadata.clientTimeoutMs_ref().value_or(0));\n  if (rpcOptions.getClientOnlyTimeouts()) {\n    metadata.clientTimeoutMs_ref().reset();\n    metadata.queueTimeoutMs_ref().reset();\n  }\n\n  if (auto interactionId = rpcOptions.getInteractionId()) {\n    evb_->dcheckIsInEventBaseThread();\n    if (auto* name = folly::get_ptr(pendingInteractions_, interactionId)) {\n      InteractionCreate create;\n      create.set_interactionId(interactionId);\n      create.set_interactionName(std::move(*name));\n      metadata.interactionCreate_ref() = std::move(create);\n      pendingInteractions_.erase(interactionId);\n    } else {\n      metadata.interactionId_ref() = interactionId;\n    }\n  }\n\n  return true;\n}\n\nClientChannel::SaturationStatus RocketClientChannel::getSaturationStatus() {\n  DCHECK(evb_ && evb_->isInEventBaseThread());\n  return ClientChannel::SaturationStatus(\n      inflightRequestsAndStreams(), maxInflightRequestsAndStreams_);\n}\n\nvoid RocketClientChannel::closeNow() {\n  DCHECK(!evb_ || evb_->isInEventBaseThread());\n  if (auto rclient = std::move(rclient_)) {\n    rclient->close(transport::TTransportException(\n        transport::TTransportException::INTERRUPTED, \"Client shutdown.\"));\n  }\n}\n\nvoid RocketClientChannel::setCloseCallback(CloseCallback* closeCallback) {\n  if (rclient_) {\n    rclient_->setCloseCallback([closeCallback] {\n      if (closeCallback) {\n        closeCallback->channelClosed();\n      }\n    });\n  }\n}\n\nfolly::AsyncTransport* FOLLY_NULLABLE RocketClientChannel::getTransport() {\n  if (!rclient_) {\n    return nullptr;\n  }\n\n  auto* transportWrapper = rclient_->getTransportWrapper();\n  return transportWrapper\n      ? transportWrapper->getUnderlyingTransport<folly::AsyncTransport>()\n      : nullptr;\n}\n\nbool RocketClientChannel::good() {\n  DCHECK(!evb_ || evb_->isInEventBaseThread());\n  return rclient_ && rclient_->isAlive();\n}\n\nsize_t RocketClientChannel::inflightRequestsAndStreams() const {\n  return shared_->inflightRequests + (rclient_ ? rclient_->streams() : 0);\n}\n\nvoid RocketClientChannel::setTimeout(uint32_t timeoutMs) {\n  DCHECK(!evb_ || evb_->isInEventBaseThread());\n  if (auto* transport = getTransport()) {\n    transport->setSendTimeout(timeoutMs);\n  }\n  timeout_ = std::chrono::milliseconds(timeoutMs);\n}\n\nvoid RocketClientChannel::attachEventBase(folly::EventBase* evb) {\n  DCHECK(evb->isInEventBaseThread());\n  if (rclient_) {\n    rclient_->attachEventBase(*evb);\n  }\n  evb_ = evb;\n}\n\nvoid RocketClientChannel::detachEventBase() {\n  DCHECK(isDetachable());\n  DCHECK(getDestructorGuardCount() == 0);\n\n  if (rclient_) {\n    rclient_->detachEventBase();\n  }\n  evb_ = nullptr;\n}\n\nbool RocketClientChannel::isDetachable() {\n  DCHECK(!evb_ || evb_->isInEventBaseThread());\n  auto* transport = getTransport();\n  return !evb_ || !transport || !rclient_ ||\n      (rclient_->isDetachable() && pendingInteractions_.empty());\n}\n\nvoid RocketClientChannel::setOnDetachable(\n    folly::Function<void()> onDetachable) {\n  DCHECK(rclient_);\n  ClientChannel::setOnDetachable(std::move(onDetachable));\n  rclient_->setOnDetachable([this] {\n    if (isDetachable()) {\n      notifyDetachable();\n    }\n  });\n}\n\nvoid RocketClientChannel::unsetOnDetachable() {\n  ClientChannel::unsetOnDetachable();\n  if (rclient_) {\n    rclient_->setOnDetachable(nullptr);\n  }\n}\n\nvoid RocketClientChannel::terminateInteraction(InteractionId id) {\n  evb_->dcheckIsInEventBaseThread();\n  auto pending = pendingInteractions_.find(id);\n  if (pending != pendingInteractions_.end()) {\n    pendingInteractions_.erase(pending);\n    releaseInteractionId(std::move(id));\n    return;\n  }\n  rclient_->terminateInteraction(id);\n  releaseInteractionId(std::move(id));\n}\n\nInteractionId RocketClientChannel::registerInteraction(\n    folly::StringPiece name,\n    int64_t id) {\n  CHECK(!name.empty());\n  CHECK_GT(id, 0);\n  evb_->dcheckIsInEventBaseThread();\n\n  auto res = pendingInteractions_.insert({id, name.str()});\n  DCHECK(res.second);\n\n  rclient_->addInteraction();\n\n  return createInteractionId(id);\n}\n\nconstexpr std::chrono::seconds RocketClientChannel::kDefaultRpcTimeout;\n} \/\/ namespace thrift\n} \/\/ namespace apache\n","avg_line_length":32.2887259395,"max_line_length":80,"alphanum_fraction":0.6764697533,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":28120,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":47.0,"content":"\/\/***************************************************************************\n\/\/ FIBTEST.CPP\n\/\/\n\/\/ Test program for the F-heap implementation.\n\/\/ Copyright (c) 1996 by John Boyer.\n\/\/ See header file for free usage information.\n\/\/***************************************************************************\n\n#include <math.h>\n#include \"mex.h\"\n\nextern void _main();\n\n#include <stdlib.h>\n#include <iostream.h>\n#include <stdio.h>\n#include <conio.h>\n#include <ctype.h>\n#include <memory.h>\n#include <time.h>\n\n#include \"fibheap.h\"\n\n#define _FIBHEAP_CPP\n\n\/\/***************************************************************************\n\/\/ This Fibonacci heap implementation is Copyright (c) 1996 by John Boyer.\n\/\/ See the header file for free usage information.\n\/\/***************************************************************************\n\n\/\/***************************************************************************\n\/\/ The classes in this package are designed to allow the package user\n\/\/ to quickly and easily develop applications that require a heap data\n\/\/ structure.  Using amortized analysis, the asymptotically fastest heap\n\/\/ data structure is the Fibonacci heap.  The constants are a little\n\/\/ high so the real speed gain will not be seen until larger data sets\n\/\/ are required, but in most cases, if the data set is small, then the\n\/\/ run-time will be neglible anyway.\n\/\/\n\/\/ To use this heap class you need do only two things.  First, subclass\n\/\/ the FibHeapNode class to create the class of objects that you'd\n\/\/ like to store in a heap.  Second, create an instance of the FibHeap\n\/\/ class, which can then be used to Insert(), ExtractMin(), etc.,\n\/\/ instances of your FibHeapNode subclass.  Notice that you don't need\n\/\/ to create a subclass of the FibHeap class.\n\/\/\n\/\/ The application-specific data object that you'd like to store in a heap\n\/\/ will have a key value.  In the class that you derive from FibHeapNode,\n\/\/ you will need to define the key structure then provide assignment (=),\n\/\/ equality (==) and less-than operators and a destructor.  These functions\n\/\/ are declared virtual so that the code in the FibHeap class can compare,\n\/\/ assign and destroy your objects by calling on your code.\n\/\/\n\/\/ The overloaded operators in your defined class MUST call functions in\n\/\/ the Fibonacci heap node class first.  For assignment, the function\n\/\/ FHN_Assign() should be called before code that deals with the copy of\n\/\/ the key value.  For comparison operators, the function FHN_Cmp() should\n\/\/ appear first.  If it returns 0, then keys can be compared as normal.\n\/\/ The following indicates what the three most common operators must do\n\/\/ based on the return value of FHN_Cmp() \n\/\/\n\/\/ For ==, if zero returned, then compare keys\n\/\/\t   if non-zero X returned, then return 0\n\/\/ For <,  if zero returned, then compare keys\n\/\/         if non-zero X returned, then return X<0?1:0\n\/\/ For >,  if zero returned, then compare keys\n\/\/         if non-zero X returned, then return X>0?1:0   \n\/\/***************************************************************************\n\n#include <stdlib.h>\n#include <iostream.h>\n#include <stdio.h>\n#include <conio.h>\n\n#include \"fibheap.h\"\n\n\/\/***************************************************************************\n\/\/=========================================================\n\/\/ FibHeapNode Constructor\n\/\/=========================================================\n\/\/***************************************************************************\n\nFibHeapNode::FibHeapNode()\n{\n     Left = Right = Parent = Child = NULL;\n     Degree = Mark = NegInfinityFlag = 0;\n}\n\n\/\/=========================================================\n\/\/ FibHeapNode Destructor\n\/\/\n\/\/ Body is empty, but declaration is required in order to\n\/\/ force virtual.  This will ensure that FibHeap class\n\/\/ calls derived class destructors.\n\/\/=========================================================\n\nFibHeapNode::~FibHeapNode()\n{\n}\n\n\/\/=========================================================\n\/\/ FHN_Assign()\n\/\/\n\/\/ To be used as first step of an assignment operator in a\n\/\/ derived class.  The derived class will handle assignment\n\/\/ of key value, and this function handles copy of the\n\/\/ NegInfinityFlag (which overrides the key value if it is\n\/\/ set).\n\/\/=========================================================\n\nvoid FibHeapNode::FHN_Assign(FibHeapNode& RHS)\n{\n     NegInfinityFlag = RHS.NegInfinityFlag;\n}\n\n\/\/=========================================================\n\/\/ FHN_Cmp()\n\/\/\n\/\/ To be used as the first step of ALL comparators in a\n\/\/ derived class.\n\/\/\n\/\/ Compares the relative state of the two neg. infinity\n\/\/ flags.  Note that 'this' is the left hand side.  If\n\/\/ LHS neg. infinity is set, then it will be less than (-1)\n\/\/ the RHS unless RHS neg. infinity flag is also set.\n\/\/ Only if function returns 0 should the key comparison\n\/\/ defined in the derived class be performed, e.g.\n\/\/\n\/\/ For ==, if zero returned, then compare keys\n\/\/\t   if non-zero X returned, then return 0\n\/\/ For <,  if zero returned, then compare keys\n\/\/         if non-zero X returned, then return X<0?1:0\n\/\/ For >,  if zero returned, then compare keys\n\/\/         if non-zero X returned, then return X>0?1:0    \n\/\/=========================================================\n\nint  FibHeapNode::FHN_Cmp(FibHeapNode& RHS)\n{\n     if (NegInfinityFlag)\n\t return RHS.NegInfinityFlag ? 0 : -1;\n     return RHS.NegInfinityFlag ? 1 : 0; \n}\n\n\/\/========================================================================\n\/\/ We do, on occasion, compare and assign objects of type FibHeapNode, but\n\/\/ only when the NegInfinityFlag is set.  See for example FibHeap::Delete().\n\/\/\n\/\/ Also, these functions exemplify what a derived class should do.\n\/\/========================================================================\n\nvoid FibHeapNode::operator =(FibHeapNode& RHS)\n{\n     FHN_Assign(RHS);\n     \/\/ Key assignment goes here in derived classes\n}\n\nint  FibHeapNode::operator ==(FibHeapNode& RHS)\n{\n     if (FHN_Cmp(RHS)) return 0;\n     \/\/ Key compare goes here in derived classes\n     return 1;\n}\n\nint  FibHeapNode::operator <(FibHeapNode& RHS)\n{\nint X;\n\n     if ((X=FHN_Cmp(RHS)) != 0)\n\t  return X < 0 ? 1 : 0;\n     \/\/ Key compare goes here in derived classes\n     return 0;\n}\n\n\/\/=========================================================\n\/\/ Print()\n\/\/=========================================================\n\nvoid FibHeapNode::Print()\n{\n     if (NegInfinityFlag)\n\t cout << \"-inf.\";\n}\n\n\/\/***************************************************************************\n\/\/===========================================================================\n\/\/ FibHeap Constructor\n\/\/===========================================================================\n\/\/***************************************************************************\n\nFibHeap::FibHeap()\n{\n     MinRoot = NULL;\n     NumNodes = NumTrees = NumMarkedNodes = 0;\n     ClearHeapOwnership();\n}\n\n\/\/===========================================================================\n\/\/ FibHeap Destructor\n\/\/===========================================================================\n\nFibHeap::~FibHeap()\n{\nFibHeapNode *Temp;\n\n     if (GetHeapOwnership())\n     {\n         while (MinRoot != NULL)\n         {\n             Temp = ExtractMin();\n             delete Temp;\n\t }\n     }\n}\n\n\/\/===========================================================================\n\/\/ Insert() - O(1) actual; O(2) amortized\n\/\/\n\/\/ I am using O(2) here to indicate that although Insert() is\n\/\/ constant time, its amortized rating is more costly because some\n\/\/ of the work of inserting is done by other operations such as\n\/\/ ExtractMin(), which is where tree-balancing occurs.\n\/\/\n\/\/ The child pointer is deliberately not set to NULL because Insert()\n\/\/ is also used internally to help put whole trees onto the root list.\n\/\/===========================================================================\n\nvoid FibHeap::Insert(FibHeapNode *NewNode)\n{\n     if (NewNode == NULL) return;\n\n\/\/ If the heap is currently empty, then new node becomes singleton\n\/\/ circular root list\n \n     if (MinRoot == NULL)\n\t MinRoot = NewNode->Left = NewNode->Right = NewNode;\n\n     else\n     {\n\/\/ Pointers from NewNode set to insert between MinRoot and MinRoot->Right\n\n         NewNode->Right = MinRoot->Right;\n\t NewNode->Left = MinRoot;\n\n\/\/ Set Pointers to NewNode  \n\n\t NewNode->Left->Right = NewNode;\n         NewNode->Right->Left = NewNode;\n\n\/\/ The new node becomes new MinRoot if it is less than current MinRoot\n\n         if (*NewNode < *MinRoot)\n\t     MinRoot = NewNode;\n     }\n\n\/\/ We have one more node in the heap, and it is a tree on the root list\n\n     NumNodes++;\n\n     NumTrees++;\n     NewNode->Parent = NULL;\n}\n\n\/\/===========================================================================\n\/\/ Union() - O(1) actual; O(1) amortized\n\/\/===========================================================================\n\nvoid FibHeap::Union(FibHeap *OtherHeap)\n{\nFibHeapNode *Min1, *Min2, *Next1, *Next2;\n\n     if (OtherHeap == NULL || OtherHeap->MinRoot == NULL) return;\n\n\/\/ We join the two circular lists by cutting each list between its\n\/\/ min node and the node after the min.  This code just pulls those\n\/\/ nodes into temporary variables so we don't get lost as changes\n\/\/ are made.\n\n     Min1 = MinRoot;\n     Min2 = OtherHeap->MinRoot;\n     Next1 = Min1->Right;\n     Next2 = Min2->Right;\n\n\/\/ To join the two circles, we join the minimum nodes to the next\n\/\/ nodes on the opposite chains.  Conceptually, it looks like the way\n\/\/ two bubbles join to form one larger bubble.  They meet at one point\n\/\/ of contact, then expand out to make the bigger circle.\n \n     Min1->Right = Next2;\n     Next2->Left = Min1;\n     Min2->Right = Next1;\n     Next1->Left = Min2;\n\n\/\/ Choose the new minimum for the heap\n \n     if (*Min2 < *Min1)\n         MinRoot = Min2;\n\n\/\/ Set the amortized analysis statistics and size of the new heap\n                   \n     NumNodes += OtherHeap->NumNodes;\n     NumMarkedNodes += OtherHeap->NumMarkedNodes;\n     NumTrees += OtherHeap->NumTrees;\n\n\/\/ Complete the union by setting the other heap to emptiness\n\/\/ then destroying it\n\n     OtherHeap->MinRoot  = NULL;\n     OtherHeap->NumNodes =\n     OtherHeap->NumTrees =\n     OtherHeap->NumMarkedNodes = 0;\n\n     delete OtherHeap;\n}\n\n\/\/===========================================================================\n\/\/ Minimum - O(1) actual; O(1) amortized\n\/\/===========================================================================\n\nFibHeapNode *FibHeap::Minimum()\n{\n     return MinRoot;\n}\n\n\/\/===========================================================================\n\/\/ ExtractMin() - O(n) worst-case actual; O(lg n) amortized\n\/\/===========================================================================\n\nFibHeapNode *FibHeap::ExtractMin()\n{\nFibHeapNode *Result;\nFibHeap *ChildHeap = NULL;\n\n\/\/ Remove minimum node and set MinRoot to next node\n\n     if ((Result = Minimum()) == NULL)\n          return NULL;\n\n     MinRoot = Result->Right;\n     Result->Right->Left = Result->Left;\n     Result->Left->Right = Result->Right;\n     Result->Left = Result->Right = NULL;\n\n     NumNodes --;\n     if (Result->Mark)\n     {\n\t NumMarkedNodes --;\n         Result->Mark = 0;\n     }\n     Result->Degree = 0;\n\n\/\/ Attach child list of Minimum node to the root list of the heap\n\/\/ If there is no child list, then do no work\n\n     if (Result->Child == NULL)\n     {\n\t if (MinRoot == Result)\n\t     MinRoot = NULL;\n     }\n\n\/\/ If MinRoot==Result then there was only one root tree, so the\n\/\/ root list is simply the child list of that node (which is\n\/\/ NULL if this is the last node in the list)\n\n     else if (MinRoot == Result)\n         MinRoot = Result->Child;\n\n\/\/ If MinRoot is different, then the child list is pushed into a\n\/\/ new temporary heap, which is then merged by Union() onto the\n\/\/ root list of this heap.\n\n     else \n     {\n         ChildHeap = new FibHeap();\n         ChildHeap->MinRoot = Result->Child;\n     }\n\n\/\/ Complete the disassociation of the Result node from the heap\n\n     if (Result->Child != NULL)\n\t Result->Child->Parent = NULL;\n     Result->Child = Result->Parent = NULL;\n\n\/\/ If there was a child list, then we now merge it with the\n\/\/\trest of the root list\n\n     if (ChildHeap)\n         Union(ChildHeap);\n\n\/\/ Consolidate heap to find new minimum and do reorganize work\n\n     if (MinRoot != NULL)\n         _Consolidate();\n\n\/\/ Return the minimum node, which is now disassociated with the heap\n\/\/ It has Left, Right, Parent, Child, Mark and Degree cleared.\n\n     return Result;\n}\n\n\/\/===========================================================================\n\/\/ DecreaseKey() - O(lg n) actual; O(1) amortized\n\/\/\n\/\/ The O(lg n) actual cost stems from the fact that the depth, and\n\/\/ therefore the number of ancestor parents, is bounded by O(lg n).\n\/\/===========================================================================\n\nint  FibHeap::DecreaseKey(FibHeapNode *theNode, FibHeapNode& NewKey)\n{\nFibHeapNode *theParent;\n\n     if (theNode==NULL || *theNode < NewKey)\n         return NOTOK;\n\n     *theNode = NewKey;\n\n     theParent = theNode->Parent;\n     if (theParent != NULL && *theNode < *theParent)\n     {\n         _Cut(theNode, theParent);\n         _CascadingCut(theParent);\n     }\n\n     if (*theNode < *MinRoot)\n         MinRoot = theNode;\n\n     return OK;\n}\n\n\/\/===========================================================================\n\/\/ Delete() - O(lg n) amortized; ExtractMin() dominates\n\/\/\n\/\/ Notice that if we don't own the heap nodes, then we clear the\n\/\/ NegInfinityFlag on the deleted node.  Presumably, the programmer\n\/\/ will be reusing the node.\n\/\/===========================================================================\n\nint  FibHeap::Delete(FibHeapNode *theNode)\n{\nFibHeapNode Temp;\nint Result;\n\n     if (theNode == NULL) return NOTOK;\n\n     Temp.NegInfinityFlag = 1;\n     Result = DecreaseKey(theNode, Temp);\n\n     if (Result == OK)\n         if (ExtractMin() == NULL)\n             Result = NOTOK;\n\n     if (Result == OK)\n     {\n         if (GetHeapOwnership())\n\t      delete theNode;\n\t else theNode->NegInfinityFlag = 0;\n     }\n         \n     return Result;\n}\n\n\/\/========================================================================\n\/\/ Print()\n\/\/\n\/\/ Used internally for debugging purposes.  The function prints the key\n\/\/ value for each node along the root list, then it calls itself on each\n\/\/ child list.   \n\/\/========================================================================\n\nvoid FibHeap::Print(FibHeapNode *Tree, FibHeapNode *theParent)\n{\nFibHeapNode* Temp = NULL;\n\n     if (Tree == NULL) Tree = MinRoot;\n\n     Temp = Tree;\n     do {\n\tif (Temp->Left == NULL)\n\t    mexPrintf( \"(Left is NULL)\" );\n\tTemp->Print();\n\tif (Temp->Parent != theParent)\n\t    mexPrintf(\"(Parent is incorrect)\" );\n\tif (Temp->Right == NULL)\n\t     mexPrintf( \"(Right is NULL)\" );\n\telse if (Temp->Right->Left != Temp)\n\t     mexPrintf( \"(Error in left link left) ->\" );\n\telse mexPrintf( \" <-> \" );\n\n\tTemp = Temp->Right;\n\n\tif (kbhit() && getch() == 27)\n\t{\n\t    cout << \"Hit a key to resume or ESC to break\\n\";\n\t    if (getch() == 27)\n                break;\n        }\n     } while (Temp != NULL && Temp != Tree);\n     mexPrintf( \"\\n\" );\n\n     Temp = Tree;\n     do {\n\tmexPrintf( \"Children of \" );\n\tTemp->Print();\n\tmexPrintf( \": \" );\n\tif (Temp->Child == NULL)\n\t     mexPrintf( \"NONE\\n\" );\n        else Print(Temp->Child, Temp);\n\tTemp = Temp->Right;\n     } while (Temp!=NULL && Temp != Tree);\n\n     if (theParent == NULL)\n     {\n     char ch;\n\n\t mexPrintf( \"\\n\\n\\n\" );\n         cin >> ch;\n     }\n}\n\n\/\/===========================================================================\n\/\/===========================================================================\n\nvoid FibHeap::_Exchange(FibHeapNode*& N1, FibHeapNode*& N2)\n{\nFibHeapNode *Temp;\n\n     Temp = N1;\n     N1 = N2;\n     N2 = Temp;\n}\n\n\/\/===========================================================================\n\/\/ Consolidate()\n\/\/\n\/\/ Internal function that reorganizes heap as part of an ExtractMin().\n\/\/ We must find new minimum in heap, which could be anywhere along the\n\/\/ root list.  The search could be O(n) since all nodes could be on\n\/\/ the root list.  So, we reorganize the tree into more of a binomial forest\n\/\/ structure, and then find the new minimum on the consolidated O(lg n) sized\n\/\/ root list, and in the process set each Parent pointer to NULL, and count\n\/\/ the number of resulting subtrees.\n\/\/\n\/\/ Note that after a list of n inserts, there will be n nodes on the root\n\/\/ list, so the first ExtractMin() will be O(n) regardless of whether or\n\/\/ not we consolidate.  However, the consolidation causes subsequent\n\/\/ ExtractMin() operations to be O(lg n).  Furthermore, the extra cost of\n\/\/ the first ExtractMin() is covered by the higher amortized cost of\n\/\/ Insert(), which is the real governing factor in how costly the first\n\/\/ ExtractMin() will be.\n\/\/===========================================================================\n\nvoid FibHeap::_Consolidate()\n{\nFibHeapNode *x, *y, *w;\nFibHeapNode *A[1+8*sizeof(long)]; \/\/ 1+lg(n)\nint  I=0, Dn = 1+8*sizeof(long);\nshort d;\n\n\/\/ Initialize the consolidation detection array\n\n     for (I=0; I < Dn; I++)\n          A[I] = NULL;\n\n\/\/ We need to loop through all elements on root list.\n\/\/ When a collision of degree is found, the two trees\n\/\/ are consolidated in favor of the one with the lesser\n\/\/ element key value.  We first need to break the circle\n\/\/ so that we can have a stopping condition (we can't go\n\/\/ around until we reach the tree we started with\n\/\/ because all root trees are subject to becoming a\n\/\/ child during the consolidation).\n\n     MinRoot->Left->Right = NULL;\n     MinRoot->Left = NULL;\n     w = MinRoot;\n\n     do {\n\/\/cout << \"Top of Consolidate's loop\\n\";\n\/\/Print(w);\n\n\tx = w;\n        d = x->Degree;\n        w = w->Right;\n\n\/\/ We need another loop here because the consolidated result\n\/\/ may collide with another large tree on the root list.\n\n        while (A[d] != NULL)\n        {\n             y = A[d];\n\t     if (*y < *x)\n\t\t _Exchange(x, y);\n             if (w == y) w = y->Right;\n             _Link(y, x);\n             A[d] = NULL;\n             d++;\n\/\/cout << \"After a round of Linking\\n\";\n\/\/Print(x);\n\t}\n\tA[d] = x;\n\n     } while (w != NULL);\n\n\/\/ Now we rebuild the root list, find the new minimum,\n\/\/ set all root list nodes' parent pointers to NULL and\n\/\/ count the number of subtrees.\n\n     MinRoot = NULL;\n     NumTrees = 0;\n     for (I = 0; I < Dn; I++)\n          if (A[I] != NULL)\n              _AddToRootList(A[I]);\n}\n\n\/\/===========================================================================\n\/\/ The node y is removed from the root list and becomes a subtree of node x.\n\/\/===========================================================================\n\nvoid FibHeap::_Link(FibHeapNode *y, FibHeapNode *x)\n{\n\/\/ Remove node y from root list\n\n     if (y->Right != NULL)\n\t y->Right->Left = y->Left;\n     if (y->Left != NULL)\n         y->Left->Right = y->Right;\n     NumTrees--;\n\n\/\/ Make node y a singleton circular list with a parent of x\n\n     y->Left = y->Right = y;\n     y->Parent = x;\n\n\/\/ If node x has no children, then list y is its new child list\n\n     if (x->Child == NULL)\n\t x->Child = y;\n\n\/\/ Otherwise, node y must be added to node x's child list\n\n     else\n     {\n         y->Left = x->Child;\n         y->Right = x->Child->Right;\n         x->Child->Right = y;\n         y->Right->Left = y;\n     }\n\n\/\/ Increase the degree of node x because it's now a bigger tree\n\n     x->Degree ++;\n\n\/\/ Node y has just been made a child, so clear its mark\n\n     if (y->Mark) NumMarkedNodes--;\n     y->Mark = 0;\n}\n\n\/\/===========================================================================\n\/\/===========================================================================\n\nvoid FibHeap::_AddToRootList(FibHeapNode *x)\n{\n     if (x->Mark) NumMarkedNodes --;\n     x->Mark = 0;\n\n     NumNodes--;\n     Insert(x);\n}\n\n\/\/===========================================================================\n\/\/ Remove node x from the child list of its parent node y\n\/\/===========================================================================\n\nvoid FibHeap::_Cut(FibHeapNode *x, FibHeapNode *y)\n{\n     if (y->Child == x)\n         y->Child = x->Right;\n     if (y->Child == x)\n\t y->Child = NULL;\n\n     y->Degree --;\n\n     x->Left->Right = x->Right;\n     x->Right->Left = x->Left;\n\n     _AddToRootList(x);\n}\n\n\/\/===========================================================================\n\/\/ Cuts each node in parent list, putting successive ancestor nodes on the\n\/\/ root list until we either arrive at the root list or until we find an\n\/\/ ancestor that is unmarked.  When a mark is set (which only happens during\n\/\/ a cascading cut), it means that one child subtree has been lost; if a\n\/\/ second subtree is lost later during another cascading cut, then we move\n\/\/ the node to the root list so that it can be re-balanced on the next\n\/\/ consolidate. \n\/\/===========================================================================\n\nvoid FibHeap::_CascadingCut(FibHeapNode *y)\n{\nFibHeapNode *z = y->Parent;\n\n     while (z != NULL)\n     {\n         if (y->Mark == 0)\n         {\n             y->Mark = 1;\n             NumMarkedNodes++;\n             z = NULL;\n         }\n         else\n         {\n             _Cut(y, z);\n             y = z;\n\t     z = y->Parent;\n         }\n     }\n}\n\n\nclass HeapNode : public FibHeapNode\n{\n      double   N;\n      long int IndexV;\n\npublic:\n\n      HeapNode() : FibHeapNode() { N = 0; };   \n\n      virtual void operator =(FibHeapNode& RHS);\n      virtual int  operator ==(FibHeapNode& RHS);\n      virtual int  operator <(FibHeapNode& RHS);\n\n      virtual void operator =(double NewKeyVal );\n      virtual void Print();\n\n      double GetKeyValue() { return N; };       \/* !!!! *\/\n      void SetKeyValue(double n) { N = n; };\n\n      long int GetIndexValue() { return IndexV; };\n      void SetIndexValue( long int v) { IndexV = v; };\n\n};\n\nvoid HeapNode::Print()\n{\n     FibHeapNode::Print();\n     mexPrintf( \"%f (%d)\" , N , IndexV );\n}\n\nvoid HeapNode::operator =(double NewKeyVal)\n{\n     HeapNode Temp;\n     Temp.N = N = NewKeyVal;\n     FHN_Assign(Temp);\n}\n\nvoid HeapNode::operator =(FibHeapNode& RHS)\n{\n     FHN_Assign(RHS);\n     N = ((HeapNode&) RHS).N;\n}\n\nint  HeapNode::operator ==(FibHeapNode& RHS)\n{\n     if (FHN_Cmp(RHS)) return 0;\n     return N == ((HeapNode&) RHS).N ? 1 : 0;\n}\n\nint  HeapNode::operator <(FibHeapNode& RHS)\n{\nint X;\n\n     if ((X=FHN_Cmp(RHS)) != 0)\n\t  return X < 0 ? 1 : 0;\n\n     return N < ((HeapNode&) RHS).N ? 1 : 0;\n};\n\nint IntCmp(const void *pA, const void *pB)\n{\nint A, B;\n\n    A = *((const int *) pA);\n    B = *((const int *) pB);\n    if (A < B) return -1;\n    if (A == B) return 0;\n    return 1; \n}\n\nvoid dodijk_sparse( \n             long int M,\n             long int N,\n             long int S,\n             double   *D,\n             double   *sr,\n             int      *irs,\n             int      *jcs,\n             HeapNode *A,\n             FibHeap  *theHeap  )\n{\n   int      finished;\n   long int i,startind,endind,whichneighbor,ndone,index,switchwith,closest,closesti;\n   long int *INDICES;\n   double   closestD,arclength; \n   double   INF,SMALL,olddist;\n   HeapNode *Min;\n   HeapNode Temp;\n\n   INF   = mxGetInf();\n   SMALL = mxGetEps();\n\n   \/* initialize *\/\n   for (i=0; i<M; i++) \n   {\n      if (i!=S) A[ i ] = (double) INF; else A[ i ] = (double) SMALL;\n      if (i!=S) D[ i ] = (double) INF; else D[ i ] = (double) SMALL;\n\t  theHeap->Insert( &A[i] );\n      A[ i ].SetIndexValue( (long int) i );\n   }\n   \n\n   \/\/ Insert 0 then extract it.  This will cause the\n   \/\/ Fibonacci heap to get balanced.\n\n   theHeap->Insert(&Temp);\n   theHeap->ExtractMin();\n\n   \/*theHeap->Print();\n   for (i=0; i<M; i++)\n   {\n      closest = A[ i ].GetIndexValue();\n      closestD = A[ i ].GetKeyValue();\n      mexPrintf( \"Index at i=%d =%d  value=%f\\n\" , i , closest , closestD );\n   }*\/   \n\n   \/* loop over nonreached nodes *\/\n   finished = 0;\n   ndone    = 0;\n   while ((finished==0) && (ndone < M))\n   {\n      \/\/if ((ndone % 100) == 0) mexPrintf( \"Done with node %d\\n\" , ndone );\n\n      Min = (HeapNode *) theHeap->ExtractMin();\n      closest  = Min->GetIndexValue();\n      closestD = Min->GetKeyValue();\n\n      if ((closest<0) || (closest>=M)) mexErrMsgTxt( \"Minimum Index out of bound...\" );\n\n      \/\/theHeap->Print();\n      \/\/mexPrintf( \"EXTRACTED MINIMUM  NDone=%d S=%d closest=%d closestD=%f\\n\" , ndone , S , closest , closestD );\n      \/\/mexErrMsgTxt( \"Exiting...\" );\n\n      D[ closest ] = closestD;\n\n      if (closestD == INF) finished=1; else\n      {\n         \/* add the closest to the determined list *\/\n         ndone++;         \n          \n         \/* relax all nodes adjacent to closest *\/\n         startind = jcs[ closest   ];\n         endind   = jcs[ closest+1 ] - 1;\n\n         if (startind!=endind+1)\n         for (i=startind; i<=endind; i++)\n         {\n            whichneighbor = irs[ i ];\n            arclength = sr[ i ];\n            olddist   = D[ whichneighbor ];\n\n            \/\/mexPrintf( \"INSPECT NEIGHBOR #%d  olddist=%f newdist=%f\\n\" , whichneighbor , olddist , closestD+arclength );            \n\n            if ( olddist > ( closestD + arclength ))\n            {\n               D[ whichneighbor ] = closestD + arclength;\n\n\t           Temp = A[ whichneighbor ];\n\t           Temp.SetKeyValue( closestD + arclength );\n               theHeap->DecreaseKey( &A[ whichneighbor ], Temp );\n\n               \/\/mexPrintf( \"UPDATING NODE #%d  olddist=%f newdist=%f\\n\" , whichneighbor , olddist , closestD+arclength );\n            }\n         }\n\n      }\n      \n   }\n}\n\n\nvoid mexFunction(\n\t\t int          nlhs,\n\t\t mxArray      *plhs[],\n\t\t int          nrhs,\n\t\t const mxArray *prhs[]\n\t\t )\n{\n  double    *sr,*D,*P,*SS,*Dsmall,*Psmall;\n  int       *irs,*jcs;\n  long int  M,N,S,MS,NS,i,j,in;\n\n  HeapNode *A = NULL;\n  FibHeap  *theHeap = NULL;\n  \n  if (nrhs != 2)\n  {\n      mexErrMsgTxt( \"Only 2 input arguments allowed.\" );\n  }\n      else if (nlhs != 1) \n   {\n      mexErrMsgTxt( \"Only 1 output argument allowed.\" );\n   }\n   \n   M = mxGetM( prhs[0] );\n   N = mxGetN( prhs[0] );\n   \n   if (M != N) mexErrMsgTxt( \"Input matrix needs to be square.\" );\n    \n   SS = mxGetPr(prhs[1]);\n   MS = mxGetM( prhs[1] );\n   NS = mxGetN( prhs[1] );\n     \n   if ((MS==0) || (NS==0) || ((MS>1) && (NS>1))) mexErrMsgTxt( \"Source nodes are specified in one dimensional matrix only\" );\n   if (NS>MS) MS=NS;\n     \n   plhs[0] = mxCreateDoubleMatrix( MS,M, mxREAL);\n   D = mxGetPr(plhs[0]);\n    \n   Dsmall = (double *) mxCalloc( M , sizeof( double ));\n\n   if (mxIsSparse( prhs[ 0 ] ) == 1)\n   {\n     \/* dealing with sparse array *\/\n     sr      = mxGetPr(prhs[0]);\n     irs     = mxGetIr(prhs[0]);\n     jcs     = mxGetJc(prhs[0]);\n\n     \/\/ Setup for the Fibonacci heap\n\n     \n\n     for (i=0; i<MS; i++)\n     {\n        if ((theHeap = new FibHeap) == NULL || (A = new HeapNode[M+1]) == NULL )\n        {\n\t      mexErrMsgTxt( \"Memory allocation failed-- ABORTING.\\n\" );\n        }\n\n        theHeap->ClearHeapOwnership();\n\n        S = (long int) *( SS + i );\n        S--;\n\n        if ((S < 0) || (S > M-1)) mexErrMsgTxt( \"Source node(s) out of bound\" );\n\n        \/* -------------------------------------------------------------------------------------------------\n                                    run the dijkstra code \n           ------------------------------------------------------------------------------------------------- *\/\n\n        \/\/mexPrintf( \"Working on i=%d\\n\" , i );\n\n        dodijk_sparse( M,N,S,Dsmall,sr,irs,jcs,A,theHeap );\n\n        for (j=0; j<M; j++) \n        {\n           *( D + j*MS + i ) = *( Dsmall + j );\n\n         \/\/mexPrintf( \"Distance i=%d to j=%d =%f\\n\" , S+1 , j , *( Dsmall + j ) ); \n        }\n         \n        \n       \n        \/* -------------------------------------------------------------------------------------------------\n                                    end of the dijkstra code \n           ------------------------------------------------------------------------------------------------- *\/\n        \n        delete theHeap;\n        delete[] A;\n     } \n\n     \n\n   } else mexErrMsgTxt( \"Function not implemented for full arrays\" );\n\n}\n","avg_line_length":28.4903748734,"max_line_length":134,"alphanum_fraction":0.5126955903,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1097,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAXN = 5e5 + 5;\n\nint a[MAXN];\nlong long pref[MAXN];\nlong long alices_force_pref[MAXN];\nstring s;\n\nint main() {\n  int n;\n  scanf(\"%d\", &n);\n  for (int i = 1; i <= n; ++i) {\n    scanf(\"%d\", &a[i]);\n    pref[i] = pref[i - 1] + a[i];\n  }\n  cin >> s;\n\n  for (int i = 1; i <= n; ++i) {\n    alices_force_pref[i] = alices_force_pref[i - 1];\n    if (s[i - 1] == 'A') {\n      alices_force_pref[i] += a[i];\n    }\n  }\n\n  long long ans = 0;\n\n  \/\/ prefix\n  for (int i = 0; i <= n; ++i) {\n    long long alices_force = alices_force_pref[n] - alices_force_pref[i] +\n      pref[i] - alices_force_pref[i];\n    long long bobs_force = pref[n] - alices_force;\n    ans = max(ans, bobs_force);\n  }\n\n  \/\/ suffix\n  for (int i = 1; i <= n; ++i) {\n    long long alices_force = alices_force_pref[i - 1] + (pref[n] - pref[i - 1] -\n        (alices_force_pref[n] - alices_force_pref[i - 1]));\n    long long bobs_force = pref[n] - alices_force;\n    ans = max(ans, bobs_force);\n  }\n\n  cout << ans << \"\\n\";\n\n  return 0;\n}\n","avg_line_length":20.6981132075,"max_line_length":80,"alphanum_fraction":0.5587967183,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":754,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/\/ test056.cpp - write cells containing separator character\n\n#include <rapidcsv.h>\n#include \"unittest.h\"\n\nint main()\n{\n  int rv = 0;\n\n  std::string csv =\n    \"-,A,B,C\\n\"\n    \"1,\\\"3,8\\\",9,81\\n\"\n    \"2,4,16,\\\"256,8\\\"\\n\"\n    ;\n\n  std::string path = unittest::TempPath();\n  unittest::WriteFile(path, csv);\n  std::string outpath = unittest::TempPath();\n\n  try\n  {\n    rapidcsv::Document doc(path);\n    doc.SetCell<std::string>(\"C\", \"2\", \"256,8\");\n    doc.Save(outpath);\n    std::string csvread = unittest::ReadFile(outpath);\n    unittest::ExpectEqual(std::string, csv, csvread);\n  }\n  catch(const std::exception& ex)\n  {\n    std::cout << ex.what() << std::endl;\n    rv = 1;\n  }\n\n  unittest::DeleteFile(path);\n  unittest::DeleteFile(outpath);\n\n  return rv;\n}\n\n","avg_line_length":18.85,"max_line_length":59,"alphanum_fraction":0.6021220159,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7312,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":778.0,"content":"\/\/ -*- C++ -*-\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <regex>\n\n\/\/ namespace regex_constants\n\/\/ {\n\/\/\n\/\/ emum match_flag_type  \/\/ bitmask type\n\/\/ {\n\/\/     match_default     = 0,\n\/\/     match_not_bol     = unspecified,\n\/\/     match_not_eol     = unspecified,\n\/\/     match_not_bow     = unspecified,\n\/\/     match_not_eow     = unspecified,\n\/\/     match_any         = unspecified,\n\/\/     match_not_null    = unspecified,\n\/\/     match_continuous  = unspecified,\n\/\/     match_prev_avail  = unspecified,\n\/\/     format_default    = 0,\n\/\/     format_sed        = unspecified,\n\/\/     format_no_copy    = unspecified,\n\/\/     format_first_only = unspecified\n\/\/ };\n\/\/\n\/\/ }\n\n#include <regex>\n#include <cassert>\n#include \"test_macros.h\"\n\nint main(int, char**)\n{\n    assert(std::regex_constants::match_default == 0);\n    assert(std::regex_constants::match_not_bol != 0);\n    assert(std::regex_constants::match_not_eol != 0);\n    assert(std::regex_constants::match_not_bow != 0);\n    assert(std::regex_constants::match_not_eow != 0);\n    assert(std::regex_constants::match_any != 0);\n    assert(std::regex_constants::match_not_null != 0);\n    assert(std::regex_constants::match_continuous != 0);\n    assert(std::regex_constants::match_prev_avail != 0);\n    assert(std::regex_constants::format_default == 0);\n    assert(std::regex_constants::format_sed != 0);\n    assert(std::regex_constants::format_no_copy != 0);\n    assert(std::regex_constants::format_first_only != 0);\n\n    assert((std::regex_constants::match_not_bol & std::regex_constants::match_not_eol) == 0);\n    assert((std::regex_constants::match_not_bol & std::regex_constants::match_not_bow) == 0);\n    assert((std::regex_constants::match_not_bol & std::regex_constants::match_not_eow) == 0);\n    assert((std::regex_constants::match_not_bol & std::regex_constants::match_any) == 0);\n    assert((std::regex_constants::match_not_bol & std::regex_constants::match_not_null) == 0);\n    assert((std::regex_constants::match_not_bol & std::regex_constants::match_continuous) == 0);\n    assert((std::regex_constants::match_not_bol & std::regex_constants::match_prev_avail) == 0);\n    assert((std::regex_constants::match_not_bol & std::regex_constants::format_sed) == 0);\n    assert((std::regex_constants::match_not_bol & std::regex_constants::format_no_copy) == 0);\n    assert((std::regex_constants::match_not_bol & std::regex_constants::format_first_only) == 0);\n\n    assert((std::regex_constants::match_not_eol & std::regex_constants::match_not_bow) == 0);\n    assert((std::regex_constants::match_not_eol & std::regex_constants::match_not_eow) == 0);\n    assert((std::regex_constants::match_not_eol & std::regex_constants::match_any) == 0);\n    assert((std::regex_constants::match_not_eol & std::regex_constants::match_not_null) == 0);\n    assert((std::regex_constants::match_not_eol & std::regex_constants::match_continuous) == 0);\n    assert((std::regex_constants::match_not_eol & std::regex_constants::match_prev_avail) == 0);\n    assert((std::regex_constants::match_not_eol & std::regex_constants::format_sed) == 0);\n    assert((std::regex_constants::match_not_eol & std::regex_constants::format_no_copy) == 0);\n    assert((std::regex_constants::match_not_eol & std::regex_constants::format_first_only) == 0);\n\n    assert((std::regex_constants::match_not_bow & std::regex_constants::match_not_eow) == 0);\n    assert((std::regex_constants::match_not_bow & std::regex_constants::match_any) == 0);\n    assert((std::regex_constants::match_not_bow & std::regex_constants::match_not_null) == 0);\n    assert((std::regex_constants::match_not_bow & std::regex_constants::match_continuous) == 0);\n    assert((std::regex_constants::match_not_bow & std::regex_constants::match_prev_avail) == 0);\n    assert((std::regex_constants::match_not_bow & std::regex_constants::format_sed) == 0);\n    assert((std::regex_constants::match_not_bow & std::regex_constants::format_no_copy) == 0);\n    assert((std::regex_constants::match_not_bow & std::regex_constants::format_first_only) == 0);\n\n    assert((std::regex_constants::match_not_eow & std::regex_constants::match_any) == 0);\n    assert((std::regex_constants::match_not_eow & std::regex_constants::match_not_null) == 0);\n    assert((std::regex_constants::match_not_eow & std::regex_constants::match_continuous) == 0);\n    assert((std::regex_constants::match_not_eow & std::regex_constants::match_prev_avail) == 0);\n    assert((std::regex_constants::match_not_eow & std::regex_constants::format_sed) == 0);\n    assert((std::regex_constants::match_not_eow & std::regex_constants::format_no_copy) == 0);\n    assert((std::regex_constants::match_not_eow & std::regex_constants::format_first_only) == 0);\n\n    assert((std::regex_constants::match_any & std::regex_constants::match_not_null) == 0);\n    assert((std::regex_constants::match_any & std::regex_constants::match_continuous) == 0);\n    assert((std::regex_constants::match_any & std::regex_constants::match_prev_avail) == 0);\n    assert((std::regex_constants::match_any & std::regex_constants::format_sed) == 0);\n    assert((std::regex_constants::match_any & std::regex_constants::format_no_copy) == 0);\n    assert((std::regex_constants::match_any & std::regex_constants::format_first_only) == 0);\n\n    assert((std::regex_constants::match_not_null & std::regex_constants::match_continuous) == 0);\n    assert((std::regex_constants::match_not_null & std::regex_constants::match_prev_avail) == 0);\n    assert((std::regex_constants::match_not_null & std::regex_constants::format_sed) == 0);\n    assert((std::regex_constants::match_not_null & std::regex_constants::format_no_copy) == 0);\n    assert((std::regex_constants::match_not_null & std::regex_constants::format_first_only) == 0);\n\n    assert((std::regex_constants::match_continuous & std::regex_constants::match_prev_avail) == 0);\n    assert((std::regex_constants::match_continuous & std::regex_constants::format_sed) == 0);\n    assert((std::regex_constants::match_continuous & std::regex_constants::format_no_copy) == 0);\n    assert((std::regex_constants::match_continuous & std::regex_constants::format_first_only) == 0);\n\n    assert((std::regex_constants::match_prev_avail & std::regex_constants::format_sed) == 0);\n    assert((std::regex_constants::match_prev_avail & std::regex_constants::format_no_copy) == 0);\n    assert((std::regex_constants::match_prev_avail & std::regex_constants::format_first_only) == 0);\n\n    assert((std::regex_constants::format_sed & std::regex_constants::format_no_copy) == 0);\n    assert((std::regex_constants::format_sed & std::regex_constants::format_first_only) == 0);\n\n    assert((std::regex_constants::format_no_copy & std::regex_constants::format_first_only) == 0);\n\n    std::regex_constants::match_flag_type e1 = std::regex_constants::match_not_bol;\n    std::regex_constants::match_flag_type e2 = std::regex_constants::match_not_eol;\n    e1 = ~e1;\n    e1 = e1 & e2;\n    e1 = e1 | e2;\n    e1 = e1 ^ e2;\n    e1 &= e2;\n    e1 |= e2;\n    e1 ^= e2;\n\n  return 0;\n}\n","avg_line_length":55.8167938931,"max_line_length":100,"alphanum_fraction":0.6959792123,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3613,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/*******************************************************************************\n * Copyright (C) 2016 Maxim Integrated Products, Inc., All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL MAXIM INTEGRATED BE LIABLE FOR ANY CLAIM, DAMAGES\n * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n * Except as contained in this notice, the name of Maxim Integrated\n * Products, Inc. shall not be used except as stated in the Maxim Integrated\n * Products, Inc. Branding Policy.\n *\n * The mere transfer of this software does not imply any licenses\n * of trade secrets, proprietary technology, copyrights, patents,\n * trademarks, maskwork rights, or any other form of intellectual\n * property whatsoever. Maxim Integrated Products, Inc. retains all\n * ownership rights.\n *******************************************************************************\n *\/\n\n#include \"mbed.h\"\n#include \"LIS2DH.h\"\n#include \"StringInOut.h\"\n#include \"StringHelper.h\"\n#include \"Peripherals.h\"\n\n#define LIS2DH_SLAVE_ADDRESS 0x32\n#define LIS2DH_REG_PART_ID   0x0F\n\n\/\/******************************************************************************\nint LIS2DH_ReadReg(char argStrs[32][32], char replyStrs[32][32]) {\n  uint8_t args[1];\n  uint8_t reply[1];\n  ProcessArgs(argStrs, args, sizeof(args));\n  LIS2DH *lis2dh = Peripherals::lis2dh();\n  lis2dh->readReg((LIS2DH::LIS2DH_REG_map_t)args[0], (char *)reply);\n  FormatReply(reply, sizeof(reply), replyStrs);\n  return 0;\n}\n\n\/\/******************************************************************************\nint LIS2DH_WriteReg(char argStrs[32][32], char replyStrs[32][32]) {\n  uint8_t args[2];\n  uint8_t reply[1];\n  ProcessArgs(argStrs, args, sizeof(args));\n  LIS2DH *lis2dh = Peripherals::lis2dh();\n  lis2dh->writeReg((LIS2DH::LIS2DH_REG_map_t)args[0], args[1]); \/\/\/< pass in the register address\n  reply[0] = 0x80;\n  FormatReply(reply, sizeof(reply), replyStrs);\n  return 0;\n}\n\nextern int highDataRate;\n\/\/******************************************************************************\nint LIS2DH_InitStart(char argStrs[32][32], char replyStrs[32][32]) {\n  uint8_t args[2];\n  uint8_t reply[1];\n  ProcessArgs(argStrs, args, sizeof(args));\n  LIS2DH *lis2dh = Peripherals::lis2dh();\n  if (args[0] >= LIS2DH_DATARATE_200HZ) {\n    highDataRate = 1;\n  }\n  lis2dh->initStart(args[0], args[1]);\n  reply[0] = 0x80;\n  FormatReply(reply, sizeof(reply), replyStrs);\n  return 0;\n}\n\n\/\/******************************************************************************\nint LIS2DH_Stop(char argStrs[32][32], char replyStrs[32][32]) {\n  uint8_t reply[1];\n  LIS2DH *lis2dh = Peripherals::lis2dh();\n  lis2dh->stop();\n  reply[0] = 0x80;\n  FormatReply(reply, sizeof(reply), replyStrs);\n  return 0;\n}\n","avg_line_length":39.7032967033,"max_line_length":97,"alphanum_fraction":0.6332687517,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1112,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <map>\n\n\/\/ class map\n\n\/\/       iterator upper_bound(const key_type& k);\n\/\/ const_iterator upper_bound(const key_type& k) const;\n\/\/\n\/\/   The member function templates find, count, lower_bound, upper_bound, and\n\/\/ equal_range shall not participate in overload resolution unless the\n\/\/ qualified-id Compare::is_transparent is valid and denotes a type\n\n#include \"defs.h\"\n#include \"fail_defs.h\"\n\n\n#include \"contiguous\/map.h\"\n#include \"catch.hpp\"\n\n#include \"is_transparent.h\"\n\nTEST_CASE(\"map ops upper bound3 fail\")\n{\n#if LIBCPP_STD_VER > 11\n#ifdef MAP_UBOUND_FAIL3\n    {\n    typedef contiguous::map<int, double, transparent_less_not_a_type> M;\n\n    M().upper_bound(C2Int{5});\n    }\n\tREQUIRE(false); \/\/ this should have failed at compile time\n#endif\n#endif\n}\n","avg_line_length":25.8604651163,"max_line_length":80,"alphanum_fraction":0.6079136691,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2176,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Using array<T,N> to create Body Mass Index (BMI) table\n\/\/ BMI = weight\/(height*height)\n\/\/ weight in kilograms, height in meters\n\n#include <iostream>\n#include <iomanip>\n#include <array> \/\/ For array<T,N>\n\nint main()\n{\n\tconst unsigned min_wt{ 100 }; \/\/ Minimum weight in table (in pounds)\n\tconst unsigned max_wt{ 250 }; \/\/ Maximum weight in table\n\tconst unsigned wt_step{ 10 };\n\tconst size_t wt_count{ 1 + (max_wt - min_wt) \/ wt_step };\n\n\tconst unsigned min_ht{ 48 }; \/\/ Minimum height in table (inches)\n\tconst unsigned max_ht{ 84 }; \/\/ Maximum height in table\n\tconst unsigned ht_step{ 2 };\n\tconst size_t ht_count{ 1 + (max_ht - min_ht) \/ ht_step };\n\n\tconst double lbs_per_kg{ 2.2 };  \/\/ Pounds per kilogram\n\tconst double ins_per_m{ 39.37 }; \/\/ Inches per meter\n\tstd::array<unsigned, wt_count> weight_lbs{};\n\tstd::array<unsigned, ht_count> height_ins{};\n\n\t\/\/ Create weights from 100lbs in steps of 10lbs\n\tfor (size_t i{}, w{ min_wt }; i < wt_count; w += wt_step, ++i)\n\t{\n\t\tweight_lbs[i] = w;\n\t}\n\t\/\/ Create heights from 48 inches in steps of 2 inches\n\tfor (size_t i{}, h{ min_ht }; h <= max_ht; h += ht_step)\n\t{\n\t\theight_ins.at(i++) = h;\n\t}\n\t\/\/ Output table headings\n\tstd::cout << std::setw(7) << \" |\";\n\tfor (auto w : weight_lbs)\n\t\tstd::cout << std::setw(5) << w << \"  |\";\n\tstd::cout << std::endl;\n\t\/\/ Output line below headings\n\tfor (size_t i{ 1 }; i < wt_count; ++i)\n\t\tstd::cout << \"---------\";\n\tstd::cout << std::endl;\n\n\tdouble bmi{};          \/\/ Stores BMI\n\tunsigned int feet{};   \/\/ Whole feet for output\n\tunsigned int inches{}; \/\/ Whole inches for output\n\tconst unsigned int inches_per_foot{ 12U };\n\tfor (auto h : height_ins)\n\t{\n\t\tfeet = h \/ inches_per_foot;\n\t\tinches = h % inches_per_foot;\n\t\tstd::cout << std::setw(2) << feet << \"'\" << std::setw(2) << inches << '\"' << '|';\n\t\tstd::cout << std::fixed << std::setprecision(1);\n\t\tfor (auto w : weight_lbs)\n\t\t{\n\t\t\tbmi = h \/ ins_per_m;\n\t\t\tbmi = (w \/ lbs_per_kg) \/ (bmi * bmi);\n\t\t\tstd::cout << std::setw(2) << \" \" << bmi << \" |\";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\t\/\/ Output line below table\n\tfor (size_t i{ 1 }; i < wt_count; ++i)\n\t\tstd::cout << \"---------\";\n\tstd::cout << \"\\nBMI from 18.5 to 24.9 is normal\" << std::endl;\n}\n","avg_line_length":31.5362318841,"max_line_length":83,"alphanum_fraction":0.6116727941,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":45328,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\n\n#include \"scene\/CountTrianglesVisitor.hpp\"\n\n#include \"renderModules\/PipelineStructs.hpp\"\n\n#include \"renderModules\/PBRTPipeline.hpp\"\n#include \"renderModules\/Accumulator.hpp\"\n#include \"renderModules\/FormatConverter.hpp\"\n#include \"renderModules\/denoisers\/BFR.hpp\"\n#include \"renderModules\/denoisers\/BFRBlender.hpp\"\n#include \"renderModules\/denoisers\/BMFR.hpp\"\n#include \"renderModules\/Taa.hpp\"\n#include \"io\/RenderIO.hpp\"\n\n#include \"terrain\/TerrainImporter.hpp\"\n#include \"terrain\/TerrainPipeline.hpp\"\n#include \"terrain\/TerrainAccelerationStructureManager.hpp\"\n\n#include \"Gui.hpp\"\n\n#include <vsg\/all.h>\n#include <vsgXchange\/images.h>\n#include <vsgXchange\/models.h>\n\n#include <nlohmann\/json.hpp>\n\n#include <iostream>\n\n#include \"..\/external\/vsgXchange\/src\/assimp\/3DFrontImporter.h\"\n\n#define _DEBUG\n\nclass RayTracingPushConstantsValue : public vsg::Inherit<vsg::Value<RayTracingPushConstants>, RayTracingPushConstantsValue>\n{\npublic:\n    RayTracingPushConstantsValue() {}\n};\n\nenum class DenoisingType\n{\n    None,\n    BMFR,\n    BFR,\n    SVG\n};\nDenoisingType denoisingType = DenoisingType::None;\n\nenum class DenoisingBlockSize\n{\n    x8,\n    x16,\n    x32,\n    x64,\n    x8x16x32\n};\nDenoisingBlockSize denoisingBlockSize = DenoisingBlockSize::x32;\n\nclass LoggingRedirectSentry\n{\npublic:\n    LoggingRedirectSentry(std::ostream *outStream, std::streambuf *originalBuffer)\n        : outStream(outStream), originalBuffer(originalBuffer)\n    {\n    }\n    ~LoggingRedirectSentry()\n    {\n        \/\/reset to standard output\n        outStream->rdbuf(originalBuffer);\n    }\n\nprivate:\n    std::ostream *outStream;\n    std::streambuf *originalBuffer;\n};\n\nint main(int argc, char **argv)\n{\n    try\n    {\n        vsg::CommandLine arguments(&argc, argv);\n\n        \/\/ load config\n        nlohmann::json config_json;\n        {\n            auto config_path = arguments.value(std::string(), \"--config\");\n            if (!config_path.empty())\n            {\n                std::ifstream scene_file(config_path);\n                if (!scene_file)\n                {\n                    std::cout << \"Failed to load config file \" << config_path << \".\" << std::endl;\n                    return 1;\n                }\n                scene_file >> config_json;\n            }\n        }\n\n        \/\/ ensure that cout and cerr are reset to their standard output when main() is exited\n        LoggingRedirectSentry coutSentry(&std::cout, std::cout.rdbuf());\n        LoggingRedirectSentry cerrSenry(&std::cerr, std::cerr.rdbuf());\n        std::ofstream out(\"out_log.txt\");\n        std::ofstream err_log(\"err_log.txt\");\n        if (arguments.read({\"--log\", \"-l\"}))\n        {\n            \/\/ redirect cout and cerr to log files\n            std::cout.rdbuf(out.rdbuf());\n            std::cerr.rdbuf(err_log.rdbuf());\n        }\n\n        auto windowTraits = vsg::WindowTraits::create();\n        windowTraits->windowTitle = \"VulkanPBRT\";\n        windowTraits->debugLayer = arguments.read({\"--debug\", \"-d\"});\n        windowTraits->apiDumpLayer = arguments.read({\"--api\", \"-a\"});\n        windowTraits->fullscreen = arguments.read({\"--fullscreen\", \"-fs\"});\n        if (arguments.read({\"--window\", \"-w\"}, windowTraits->width, windowTraits->height))\n            windowTraits->fullscreen = false;\n        arguments.read(\"--screen\", windowTraits->screenNum);\n\n        auto numFrames = arguments.value(-1, \"-f\");\n        auto samplesPerPixel = arguments.value(1, \"--spp\");\n        auto depthPath = arguments.value(std::string(), \"--depths\");\n        auto exportDepthPath = arguments.value(std::string(), \"--exportDepth\");\n        auto positionPath = arguments.value(std::string(), \"--positions\");\n        auto exportPositionPath = arguments.value(std::string(), \"--exportPosition\");\n        auto normalPath = arguments.value(std::string(), \"--normals\");\n        auto exportNormalPath = arguments.value(std::string(), \"--exportNormal\");\n        auto albedoPath = arguments.value(std::string(), \"--albedos\");\n        auto exportAlbedoPath = arguments.value(std::string(), \"--exportAlbedo\");\n        auto materialPath = arguments.value(std::string(), \"--materials\");\n        auto exportMaterialPath = arguments.value(std::string(), \"--exportMaterial\");\n        auto illuminationPath = arguments.value(std::string(), \"--illuminations\");\n        auto exportIlluminationPath = arguments.value(std::string(), \"--exportIllumination\");\n        auto matricesPath = arguments.value(std::string(), \"--matrices\");\n        auto exportMatricesPath = arguments.value(std::string(), \"--exportMatrices\");\n        auto sceneFilename = arguments.value(std::string(), \"-i\");\n        bool use_external_buffers = normalPath.size();\n        bool exportIllumination = exportIlluminationPath.size();\n        bool exportGBuffer = exportNormalPath.size() || exportDepthPath.size() || exportPositionPath.size() || exportAlbedoPath.size() || exportMaterialPath.size();\n        bool storeMatrices = exportGBuffer || exportMatricesPath.size();\n\n        auto terrainHeightmapFilename = arguments.value(std::string(), \"-th\");\n        auto terrainTextureFilename = arguments.value(std::string(), \"-tx\");\n        auto terrainScale = arguments.value(1.0f, { \"--terrain-scale\", \"-ts\" });\n        auto terrainScaleVertexHeight = arguments.value(1.0f, { \"--terrain-scale-vertex-height\", \"-tsvh\" });\n        bool terrainFormatLa2d = arguments.read(\"--la2d\");\n        bool textureFormatS3tc = arguments.read(\"--s3tc\");\n        auto terrainHeightmapLod = arguments.value(-1, \"-thl\");\n        auto terrainTextureLod = arguments.value(terrainHeightmapLod, \"-txl\");\n        auto terrainMaxRecursionDepth = arguments.value((uint32_t) 0, \"-r\");\n        auto terrainTilesX = arguments.value((uint32_t) 1, \"--tilesx\");\n        auto terrainTilesY = arguments.value((uint32_t) 1, \"--tilesy\");\n        auto terrainTileLengthLodFactor = arguments.value((int)1, \"--tile-length-lod-factor\");\n\n        if (sceneFilename.empty() && !use_external_buffers && terrainHeightmapFilename.empty())\n        {\n            std::cout << \"Missing input parameter \\\"-i <path_to_model>\\\" or \\\"-th <path_to_terrain_heightmap> -tx <path_to_terrain_texture>\\\".\" << std::endl;\n        }\n        if (arguments.read(\"m\"))\n            sceneFilename = \"models\/raytracing_scene.vsgt\";\n        if (arguments.errors())\n            return arguments.writeErrorMessages(std::cerr);\n\n        std::string denoisingTypeStr;\n        if (arguments.read(\"--denoiser\", denoisingTypeStr))\n        {\n            if (denoisingTypeStr == \"bmfr\")\n                denoisingType = DenoisingType::BMFR;\n            else if (denoisingTypeStr == \"bfr\")\n                denoisingType = DenoisingType::BFR;\n            else if (denoisingTypeStr == \"svgf\")\n                denoisingType = DenoisingType::SVG;\n            else if (denoisingTypeStr == \"none\")\n            {\n            }\n            else\n                std::cout << \"Unknown denoising type: \" << denoisingTypeStr << std::endl;\n        }\n        bool useTaa = arguments.read(\"--taa\");\n        bool useFlyNavigation = arguments.read(\"--fly\");\n#ifdef _DEBUG\n        \/\/ overwriting command line options for debug\n        \/\/windowTraits->debugLayer = true;\n        windowTraits->width = 1800;\n        windowTraits->height = 990;\n#endif\n        windowTraits->queueFlags = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;\n        windowTraits->imageAvailableSemaphoreWaitFlag = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;\n        windowTraits->swapchainPreferences.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;\n        windowTraits->deviceExtensionNames = {VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME, VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME, VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME, VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME, VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME, VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, VK_KHR_SPIRV_1_4_EXTENSION_NAME, VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME};\n        windowTraits->vulkanVersion = VK_API_VERSION_1_2;\n        auto &enabledAccelerationStructureFeatures = windowTraits->deviceFeatures->get<VkPhysicalDeviceAccelerationStructureFeaturesKHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR>();\n        auto &enabledRayTracingPipelineFeatures = windowTraits->deviceFeatures->get<VkPhysicalDeviceRayTracingPipelineFeaturesKHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR>();\n        enabledAccelerationStructureFeatures.accelerationStructure = VK_TRUE;\n        enabledRayTracingPipelineFeatures.rayTracingPipeline = VK_TRUE;\n        auto &enabledPhysicalDeviceVk12Feature = windowTraits->deviceFeatures->get<VkPhysicalDeviceVulkan12Features, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES>();\n        enabledPhysicalDeviceVk12Feature.runtimeDescriptorArray = VK_TRUE;\n        enabledPhysicalDeviceVk12Feature.bufferDeviceAddress = VK_TRUE;\n        enabledPhysicalDeviceVk12Feature.descriptorIndexing = VK_TRUE;\n        enabledPhysicalDeviceVk12Feature.shaderStorageBufferArrayNonUniformIndexing = VK_TRUE;\n        enabledPhysicalDeviceVk12Feature.shaderSampledImageArrayNonUniformIndexing = VK_TRUE;\n\n        \/\/ load scene or images\n        vsg::ref_ptr<vsg::Node> loaded_scene;\n        std::vector<vsg::ref_ptr<OfflineGBuffer>> offlineGBuffers;\n        std::vector<vsg::ref_ptr<OfflineIllumination>> offlineIlluminations;\n        std::vector<CameraMatrices> cameraMatrices;\n        if (!terrainHeightmapFilename.empty()) {\n            auto terrainImporter = TerrainImporter::create(terrainHeightmapFilename, terrainTextureFilename, terrainScale, terrainScaleVertexHeight, terrainFormatLa2d, textureFormatS3tc, terrainHeightmapLod, terrainTextureLod, 0, terrainTilesX, terrainTilesY, terrainTileLengthLodFactor);\n            \/\/auto terrainImporter = TerrainImporter::create(terrainHeightmapFilename, terrainTextureFilename, terrainScale, terrainScaleVertexHeight, terrainFormatLa2d, textureFormatS3tc, 0, 0, 0, terrainTilesX, terrainTilesY, terrainTileLengthLodFactor);\n            loaded_scene = terrainImporter->importTerrain();\n            if (!loaded_scene) {\n                std::cout << \"Terrain heightmap not found: \" << terrainHeightmapFilename << std::endl;\n                return 1;\n            }\n            std::cout << \"Terrain import successful\" << std::endl;\n        }\n        else if(!use_external_buffers){\n            AI3DFrontImporter::ReadConfig(config_json);\n            auto options = vsg::Options::create(vsgXchange::assimp::create(), vsgXchange::dds::create(), vsgXchange::stbi::create()); \/\/using the assimp loader\n            loaded_scene = vsg::read_cast<vsg::Node>(sceneFilename, options);\n            if (!loaded_scene)\n            {\n                std::cout << \"Scene not found: \" << sceneFilename << std::endl;\n                return 1;\n            }\n        }\n        else\n        {\n            if (numFrames <= 0)\n            {\n                std::cout << \"No number of frames given. For usage of external GBuffer and Illumination information use \\\"-f\\\" to inform about the number of frames.\" << std::endl;\n                return 1;\n            }\n            if (matricesPath.empty())\n            {\n                std::cout << \"Camera matrices are missing. Insert location of file with camera information via \\\"--matrices\\\".\" << std::endl;\n                return 1;\n            }\n            cameraMatrices = MatrixIO::importMatrices(matricesPath);\n            if (cameraMatrices.empty())\n            {\n                std::cout << \"Camera matrices could not be loaded\" << std::endl;\n                return 1;\n            }\n            if (positionPath.size())\n            {\n                offlineGBuffers = GBufferIO::importGBufferPosition(positionPath, normalPath, materialPath, albedoPath, cameraMatrices, numFrames);\n            }\n            else\n            {\n                offlineGBuffers = GBufferIO::importGBufferDepth(depthPath, normalPath, materialPath, albedoPath, numFrames);\n            }\n            offlineIlluminations = IlluminationBufferIO::importIllumination(illuminationPath, numFrames);\n            windowTraits->width = offlineGBuffers[0]->depth->width();\n            windowTraits->height = offlineGBuffers[0]->depth->height();\n        }\n        if (exportIllumination)\n        {\n            if (numFrames <= 0)\n            {\n                std::cout << \"No number of frames given. For usage of Illumination export use \\\"-f\\\" to inform about the number of frames.\" << std::endl;\n                return 1;\n            }\n            if (offlineIlluminations.empty())\n            {\n                offlineIlluminations.resize(numFrames);\n                for (auto &i : offlineIlluminations)\n                {\n                    i = OfflineIllumination::create();\n                    i->noisy = vsg::vec4Array2D::create(windowTraits->width, windowTraits->height);\n                }\n            }\n        }\n        if (exportGBuffer)\n        {\n            if (numFrames <= 0)\n            {\n                std::cout << \"No number of frames given. For usage of GBuffer export use \\\"-f\\\" to inform about the number of frames.\" << std::endl;\n                return 1;\n            }\n            if (offlineGBuffers.empty())\n            {\n                offlineGBuffers.resize(numFrames);\n                for (auto &i : offlineGBuffers)\n                {\n                    i = OfflineGBuffer::create();\n                    i->depth = vsg::floatArray2D::create(windowTraits->width, windowTraits->height);\n                    i->normal = vsg::vec2Array2D::create(windowTraits->width, windowTraits->height);\n                    i->albedo = vsg::ubvec4Array2D::create(windowTraits->width, windowTraits->height);\n                    i->material = vsg::ubvec4Array2D::create(windowTraits->width, windowTraits->height);\n                }\n            }\n        }\n        if (storeMatrices)\n        {\n            cameraMatrices.resize(numFrames);\n            for (auto &matrix : cameraMatrices)\n            {\n                matrix.proj = vsg::mat4();\n                matrix.invProj = vsg::mat4();\n            }\n        }\n\n        auto window = vsg::Window::create(windowTraits);\n        if (!window)\n        {\n            std::cout << \"Could not create windows.\" << std::endl;\n            return 1;\n        }\n        auto viewer = vsg::Viewer::create();\n        viewer->addWindow(window);\n\n        vsg::ref_ptr<vsg::Device> device(window->getOrCreateDevice());\n\n        \/\/setting a custom render pass for imgui non clear rendering\n        {\n            vsg::AttachmentDescription colorAttachment = vsg::defaultColorAttachment(window->surfaceFormat().format);\n            colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;\n            colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;\n            colorAttachment.initialLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;\n            vsg::AttachmentDescription depthAttachment = vsg::defaultDepthAttachment(window->depthFormat());\n            depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;\n            depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;\n            vsg::RenderPass::Attachments attachments{\n                colorAttachment,\n                depthAttachment};\n\n            VkAttachmentReference colorAttachmentRef = {};\n            colorAttachmentRef.attachment = 0;\n            colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n\n            VkAttachmentReference depthAttachmentRef = {};\n            depthAttachmentRef.attachment = 1;\n            depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;\n\n            vsg::SubpassDescription subpass = {};\n            subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;\n            subpass.colorAttachments.emplace_back(colorAttachmentRef);\n            subpass.depthStencilAttachments.emplace_back(depthAttachmentRef);\n\n            vsg::RenderPass::Subpasses subpasses{subpass};\n\n            \/\/ image layout transition\n            VkSubpassDependency colorDependency = {};\n            colorDependency.srcSubpass = VK_SUBPASS_EXTERNAL;\n            colorDependency.dstSubpass = 0;\n            colorDependency.srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;\n            colorDependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;\n            colorDependency.srcAccessMask = 0;\n            colorDependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\n            colorDependency.dependencyFlags = 0;\n\n            \/\/ depth buffer is shared between swap chain images\n            VkSubpassDependency depthDependency = {};\n            depthDependency.srcSubpass = VK_SUBPASS_EXTERNAL;\n            depthDependency.dstSubpass = 0;\n            depthDependency.srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;\n            depthDependency.dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;\n            depthDependency.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;\n            depthDependency.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;\n            depthDependency.dependencyFlags = 0;\n\n            vsg::RenderPass::Dependencies dependencies{colorDependency, depthDependency};\n\n            auto renderPass = vsg::RenderPass::create(device, attachments, subpasses, dependencies);\n            window->setRenderPass(renderPass);\n        }\n\n        \/\/create camera matrices\n        auto perspective = vsg::Perspective::create(60, static_cast<double>(windowTraits->width) \/ static_cast<double>(windowTraits->height), .1, 1000);\n        \/\/auto lookAt = vsg::LookAt::create(vsg::dvec3(0.0, -3, 1), vsg::dvec3(0.0, 0.0, 1), vsg::dvec3(0.0, 0.0, 1.0));\n        auto lookAt = vsg::LookAt::create(vsg::dvec3(0.0, 0.0, 1.0), vsg::dvec3(1.0, -1.0, 1.0), vsg::dvec3(0.0, 0.0, 1.0));\n\n        \/\/ set push constants\n        auto rayTracingPushConstantsValue = RayTracingPushConstantsValue::create();\n        rayTracingPushConstantsValue->value().projInverse = perspective->inverse();\n        rayTracingPushConstantsValue->value().viewInverse = lookAt->inverse();\n        rayTracingPushConstantsValue->value().prevView = lookAt->transform();\n        rayTracingPushConstantsValue->value().frameNumber = 0;\n        rayTracingPushConstantsValue->value().sampleNumber = 0;\n        auto pushConstants = vsg::PushConstants::create(VK_SHADER_STAGE_RAYGEN_BIT_KHR, 0, rayTracingPushConstantsValue);\n        auto computeConstants = vsg::PushConstants::create(VK_SHADER_STAGE_COMPUTE_BIT, 0, rayTracingPushConstantsValue);\n\n        vsg::ref_ptr<GBuffer> gBuffer;\n        vsg::ref_ptr<IlluminationBuffer> illuminationBuffer;\n        vsg::ref_ptr<AccumulationBuffer> accumulationBuffer;\n        bool writeGBuffer;\n        if (denoisingType != DenoisingType::None)\n        {\n            writeGBuffer = true;\n            gBuffer = GBuffer::create(windowTraits->width, windowTraits->height);\n            illuminationBuffer = IlluminationBufferDemodulatedFloat::create(windowTraits->width, windowTraits->height);\n        }\n        else\n        {\n            writeGBuffer = false;\n            illuminationBuffer = IlluminationBufferFinalFloat::create(windowTraits->width, windowTraits->height);\n        }\n        if (exportIllumination && !gBuffer)\n        {\n            writeGBuffer = true;\n            gBuffer = GBuffer::create(windowTraits->width, windowTraits->height);\n        }\n        if (useTaa && !accumulationBuffer)\n        {\n            \/\/ TODO: need the velocity buffer\n        }\n\n        \/\/ raytracing pipeline setup\n        uint32_t maxRecursionDepth = terrainMaxRecursionDepth;\n        \/\/vsg::ref_ptr<PBRTPipeline> pbrtPipeline;\n        vsg::ref_ptr<TerrainPipeline> pbrtPipeline;\n        vsg::ref_ptr<vsg::TopLevelAccelerationStructure> tlas;\n        if(!use_external_buffers)\n        {\n            \/\/pbrtPipeline = PBRTPipeline::create(loaded_scene, gBuffer, illuminationBuffer, writeGBuffer, RayTracingRayOrigin::CAMERA);\n            pbrtPipeline = TerrainPipeline::create(loaded_scene, gBuffer, illuminationBuffer, writeGBuffer, RayTracingRayOrigin::CAMERA, maxRecursionDepth);\n\n            \/\/ setup tlas\n            vsg::BuildAccelerationStructureTraversal buildAccelStruct(device);\n            loaded_scene->accept(buildAccelStruct);\n            pbrtPipeline->setTlas(buildAccelStruct.tlas);\n            tlas = buildAccelStruct.tlas;\n        }\n        else\n        {\n            if (!gBuffer)\n                gBuffer = GBuffer::create(offlineGBuffers[0]->depth->width(), offlineGBuffers[0]->depth->height());\n            switch (offlineIlluminations[0]->noisy->getLayout().format)\n            {\n            case VK_FORMAT_R16G16B16A16_SFLOAT:\n                illuminationBuffer = IlluminationBufferDemodulated::create(offlineIlluminations[0]->noisy->width(), offlineIlluminations[0]->noisy->height());\n                break;\n            case VK_FORMAT_R32G32B32A32_SFLOAT:\n                illuminationBuffer = IlluminationBufferDemodulatedFloat::create(offlineIlluminations[0]->noisy->width(), offlineIlluminations[0]->noisy->height());\n                break;\n            default:\n                std::cout << \"Offline illumination buffer image format not compatible\" << std::endl;\n                return 1;\n            }\n        }\n        \/\/ -------------------------------------------------------------------------------------\n        \/\/ image layout conversions and correct binding of different denoising tequniques\n        \/\/ -------------------------------------------------------------------------------------\n        vsg::CompileTraversal imageLayoutCompile(window);\n        auto commands = vsg::Commands::create();\n        auto offlineGBufferStager = OfflineGBuffer::create();\n        auto offlineIlluminationBufferStager = OfflineIllumination::create();\n        vsg::ref_ptr<vsg::QueryPool> queryPool;\n        if (pbrtPipeline)\n        {\n            queryPool = vsg::QueryPool::create(); \/\/standard init has 1 timestamp place\n            queryPool->queryCount = 2;\n            auto resetQuery = vsg::ResetQueryPool::create(queryPool);\n            auto write1 = vsg::WriteTimestamp::create(queryPool, 0, VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR);\n            auto write2 = vsg::WriteTimestamp::create(queryPool, 1, VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR);\n            commands->addChild(resetQuery);\n            commands->addChild(write1);\n            pbrtPipeline->addTraceRaysToCommandGraph(commands, pushConstants);\n            commands->addChild(write2);\n            illuminationBuffer = pbrtPipeline->getIlluminationBuffer();\n        }\n        else\n        {\n            if (offlineGBuffers.size() < numFrames || offlineIlluminations.size() < numFrames)\n            {\n                std::cout << \"Missing offline GBuffer or offline Illumination Buffer info\" << std::endl;\n                return 1;\n            }\n            offlineGBufferStager->uploadToGBufferCommand(gBuffer, commands, imageLayoutCompile.context);\n            offlineIlluminationBufferStager->uploadToIlluminationBufferCommand(illuminationBuffer, commands, imageLayoutCompile.context);\n        }\n\n        vsg::ref_ptr<Accumulator> accumulator;\n        if(denoisingType != DenoisingType::None){\n            accumulator = Accumulator::create(gBuffer, illuminationBuffer, !use_external_buffers);\n            accumulator->addDispatchToCommandGraph(commands);\n            accumulationBuffer = accumulator->accumulationBuffer;\n            illuminationBuffer->compile(imageLayoutCompile.context);\n            illuminationBuffer->updateImageLayouts(imageLayoutCompile.context);\n            illuminationBuffer = accumulator->accumulatedIllumination; \/\/swap illumination buffer to accumulated illumination for correct use in the following pipelines\n        }\n\n        vsg::ref_ptr<vsg::DescriptorImage> finalDescriptorImage;\n        switch (denoisingType)\n        {\n        case DenoisingType::None:\n            finalDescriptorImage = illuminationBuffer->illuminationImages[0];\n            break;\n        case DenoisingType::BFR:\n            switch (denoisingBlockSize)\n            {\n            case DenoisingBlockSize::x8:\n            {\n                auto bfr8 = BFR::create(windowTraits->width, windowTraits->height, 8, 8, gBuffer, illuminationBuffer, accumulationBuffer);\n                bfr8->compile(imageLayoutCompile.context);\n                bfr8->updateImageLayouts(imageLayoutCompile.context);\n                bfr8->addDispatchToCommandGraph(commands, computeConstants);\n                finalDescriptorImage = bfr8->getFinalDescriptorImage();\n                break;\n            }\n            case DenoisingBlockSize::x16:\n            {\n                auto bfr16 = BFR::create(windowTraits->width, windowTraits->height, 16, 16, gBuffer, illuminationBuffer, accumulationBuffer);\n                bfr16->compile(imageLayoutCompile.context);\n                bfr16->updateImageLayouts(imageLayoutCompile.context);\n                bfr16->addDispatchToCommandGraph(commands, computeConstants);\n                finalDescriptorImage = bfr16->getFinalDescriptorImage();\n                break;\n            }\n            case DenoisingBlockSize::x32:\n            {\n                auto bfr32 = BFR::create(windowTraits->width, windowTraits->height, 32, 32, gBuffer, illuminationBuffer, accumulationBuffer);\n                bfr32->compile(imageLayoutCompile.context);\n                bfr32->updateImageLayouts(imageLayoutCompile.context);\n                bfr32->addDispatchToCommandGraph(commands, computeConstants);\n                finalDescriptorImage = bfr32->getFinalDescriptorImage();\n                break;\n            }\n            case DenoisingBlockSize::x8x16x32:\n            {\n                auto bfr8 = BFR::create(windowTraits->width, windowTraits->height, 8, 8, gBuffer, illuminationBuffer, accumulationBuffer);\n                auto bfr16 = BFR::create(windowTraits->width, windowTraits->height, 16, 16, gBuffer, illuminationBuffer, accumulationBuffer);\n                auto bfr32 = BFR::create(windowTraits->width, windowTraits->height, 32, 32, gBuffer, illuminationBuffer, accumulationBuffer);\n                auto blender = BFRBlender::create(windowTraits->width, windowTraits->height,\n                                                  illuminationBuffer->illuminationImages[0], illuminationBuffer->illuminationImages[1],\n                                                  bfr8->getFinalDescriptorImage(), bfr16->getFinalDescriptorImage(), bfr32->getFinalDescriptorImage());\n                bfr8->compile(imageLayoutCompile.context);\n                bfr8->updateImageLayouts(imageLayoutCompile.context);\n                bfr16->compile(imageLayoutCompile.context);\n                bfr16->updateImageLayouts(imageLayoutCompile.context);\n                bfr32->compile(imageLayoutCompile.context);\n                bfr32->updateImageLayouts(imageLayoutCompile.context);\n                blender->compile(imageLayoutCompile.context);\n                blender->updateImageLayouts(imageLayoutCompile.context);\n                bfr8->addDispatchToCommandGraph(commands, computeConstants);\n                bfr16->addDispatchToCommandGraph(commands, computeConstants);\n                bfr32->addDispatchToCommandGraph(commands, computeConstants);\n                blender->addDispatchToCommandGraph(commands);\n                finalDescriptorImage = blender->getFinalDescriptorImage();\n                break;\n            }\n            }\n            break;\n        case DenoisingType::BMFR:\n            switch (denoisingBlockSize)\n            {\n            case DenoisingBlockSize::x8:\n            {\n                auto bmfr8 = BMFR::create(windowTraits->width, windowTraits->height, 8, 8, gBuffer, illuminationBuffer, accumulationBuffer, 64);\n                bmfr8->compile(imageLayoutCompile.context);\n                bmfr8->updateImageLayouts(imageLayoutCompile.context);\n                bmfr8->addDispatchToCommandGraph(commands, computeConstants);\n                finalDescriptorImage = bmfr8->getFinalDescriptorImage();\n                break;\n            }\n            case DenoisingBlockSize::x16:\n            {\n                auto bmfr16 = BMFR::create(windowTraits->width, windowTraits->height, 16, 16, gBuffer, illuminationBuffer, accumulationBuffer);\n                bmfr16->compile(imageLayoutCompile.context);\n                bmfr16->updateImageLayouts(imageLayoutCompile.context);\n                bmfr16->addDispatchToCommandGraph(commands, computeConstants);\n                finalDescriptorImage = bmfr16->getFinalDescriptorImage();\n                break;\n            }\n            case DenoisingBlockSize::x32:\n            {\n                auto bmfr32 = BMFR::create(windowTraits->width, windowTraits->height, 32, 32, gBuffer, illuminationBuffer, accumulationBuffer);\n                bmfr32->compile(imageLayoutCompile.context);\n                bmfr32->updateImageLayouts(imageLayoutCompile.context);\n                bmfr32->addDispatchToCommandGraph(commands, computeConstants);\n                finalDescriptorImage = bmfr32->getFinalDescriptorImage();\n                break;\n            }\n            case DenoisingBlockSize::x8x16x32:\n                auto bmfr8 = BMFR::create(windowTraits->width, windowTraits->height, 8, 8, gBuffer, illuminationBuffer, accumulationBuffer, 64);\n                auto bmfr16 = BMFR::create(windowTraits->width, windowTraits->height, 16, 16, gBuffer, illuminationBuffer, accumulationBuffer);\n                auto bmfr32 = BMFR::create(windowTraits->width, windowTraits->height, 32, 32, gBuffer, illuminationBuffer, accumulationBuffer);\n                auto blender = BFRBlender::create(windowTraits->width, windowTraits->height,\n                                                  illuminationBuffer->illuminationImages[1], illuminationBuffer->illuminationImages[2],\n                                                  bmfr8->getFinalDescriptorImage(), bmfr16->getFinalDescriptorImage(), bmfr32->getFinalDescriptorImage());\n                bmfr8->compile(imageLayoutCompile.context);\n                bmfr8->updateImageLayouts(imageLayoutCompile.context);\n                bmfr16->compile(imageLayoutCompile.context);\n                bmfr16->updateImageLayouts(imageLayoutCompile.context);\n                bmfr32->compile(imageLayoutCompile.context);\n                bmfr32->updateImageLayouts(imageLayoutCompile.context);\n                blender->compile(imageLayoutCompile.context);\n                blender->updateImageLayouts(imageLayoutCompile.context);\n                bmfr8->addDispatchToCommandGraph(commands, computeConstants);\n                bmfr16->addDispatchToCommandGraph(commands, computeConstants);\n                bmfr32->addDispatchToCommandGraph(commands, computeConstants);\n                blender->addDispatchToCommandGraph(commands);\n                finalDescriptorImage = blender->getFinalDescriptorImage();\n                break;\n            }\n            break;\n        case DenoisingType::SVG:\n            std::cout << \"Not yet implemented\" << std::endl;\n            break;\n        }\n\n        if (useTaa && accumulationBuffer)\n        {\n            auto taa = Taa::create(windowTraits->width, windowTraits->height, 16, 16, gBuffer, accumulationBuffer, finalDescriptorImage);\n            taa->compile(imageLayoutCompile.context);\n            taa->updateImageLayouts(imageLayoutCompile.context);\n            taa->addDispatchToCommandGraph(commands);\n            finalDescriptorImage = taa->getFinalDescriptorImage();\n        }\n        if (exportGBuffer)\n        {\n            if (!gBuffer)\n            {\n                std::cout << \"GBuffer information not available, export not possible\" << std::endl;\n                return 1;\n            }\n            offlineGBufferStager->downloadFromGBufferCommand(gBuffer, commands, imageLayoutCompile.context);\n        }\n        if (exportIllumination)\n        {\n            if (finalDescriptorImage->imageInfoList[0]->imageView->image->format != VK_FORMAT_R32G32B32A32_SFLOAT)\n            {\n                std::cout << \"Final image layout is not compatible illumination buffer export\" << std::endl;\n                return 1;\n            }\n            offlineIlluminationBufferStager->downloadFromIlluminationBufferCommand(illuminationBuffer, commands, imageLayoutCompile.context);\n        }\n        if (finalDescriptorImage->imageInfoList[0]->imageView->image->format != VK_FORMAT_B8G8R8A8_UNORM)\n        {\n            auto converter = FormatConverter::create(finalDescriptorImage->imageInfoList[0]->imageView, VK_FORMAT_B8G8R8A8_UNORM);\n            converter->compileImages(imageLayoutCompile.context);\n            converter->updateImageLayouts(imageLayoutCompile.context);\n            converter->addDispatchToCommandGraph(commands);\n            finalDescriptorImage = converter->finalImage;\n        }\n        if (gBuffer)\n        {\n            gBuffer->compile(imageLayoutCompile.context);\n            gBuffer->updateImageLayouts(imageLayoutCompile.context);\n        }\n        if (accumulationBuffer)\n        {\n            accumulationBuffer->compile(imageLayoutCompile.context);\n            accumulationBuffer->updateImageLayouts(imageLayoutCompile.context);\n        }\n        if (illuminationBuffer)\n        {\n            illuminationBuffer->compile(imageLayoutCompile.context);\n            illuminationBuffer->updateImageLayouts(imageLayoutCompile.context);\n        }\n        imageLayoutCompile.context.record();\n\n        if (accumulationBuffer)\n        {\n            accumulationBuffer->copyToBackImages(commands, gBuffer, illuminationBuffer);\n        }\n\n        \/\/ set GUI values\n        auto guiValues = Gui::Values::create();\n        guiValues->width = windowTraits->width;\n        guiValues->height = windowTraits->height;\n        CountTrianglesVisitor counter;\n        if (loaded_scene)\n            loaded_scene->accept(counter);\n        guiValues->triangleCount = counter.triangleCount;\n        guiValues->raysPerPixel = maxRecursionDepth * 2; \/\/for each depth recursion one next event estimate is done\n\n        auto viewport = vsg::ViewportState::create(0, 0, windowTraits->width, windowTraits->height);\n        auto camera = vsg::Camera::create(perspective, lookAt, viewport);\n        auto renderGraph = vsg::createRenderGraphForView(window, camera, vsgImGui::RenderImGui::create(window, Gui(guiValues))); \/\/ render graph for gui rendering\n        renderGraph->clearValues.clear();                                                                                        \/\/removing clear values to avoid clearing the raytraced image\n\n        auto commandGraph = vsg::CommandGraph::create(window);\n        commandGraph->addChild(commands);\n        commandGraph->addChild(vsg::CopyImageViewToWindow::create(finalDescriptorImage->imageInfoList[0]->imageView, window));\n        commandGraph->addChild(renderGraph);\n\n        \/\/close handler to close and imgui handler to forward to imgui\n        viewer->addEventHandler(vsgImGui::SendEventsToImGui::create());\n        viewer->addEventHandler(vsg::CloseHandler::create(viewer));\n        if (useFlyNavigation)\n            viewer->addEventHandler(vsg::FlyNavigation::create(camera));\n        else\n            viewer->addEventHandler(vsg::Trackball::create(camera));\n        viewer->assignRecordAndSubmitTaskAndPresentation({commandGraph});\n        \/\/viewer->compile();\n        auto compileTraversal = viewer->compile(device);\n        auto context = vsg::ref_ptr<vsg::Context>(&compileTraversal->context);\n\n\n        int maxLod = terrainHeightmapLod;\n        if (terrainTextureLod > maxLod) maxLod = terrainHeightmapLod;\n\n        auto tasManager = TerrainAccelerationStructureManager::create(terrainTilesX, terrainTilesY, maxLod + 1, context);\n\n        int currentHeightmapLod = terrainHeightmapLod;\n        int currentTextureLod = terrainTextureLod;\n        for (int currentLod = maxLod; currentLod >= -terrainTileLengthLodFactor; --currentLod) {\n            auto terrainImporter = TerrainImporter::create(terrainHeightmapFilename, terrainTextureFilename, terrainScale, terrainScaleVertexHeight, terrainFormatLa2d, textureFormatS3tc, currentHeightmapLod, currentTextureLod, 0, terrainTilesX, terrainTilesY, terrainTileLengthLodFactor);\n            tasManager->loadLodLevel(terrainImporter, currentLod);\n\n            if (currentHeightmapLod > 0) --currentHeightmapLod;\n            if (currentTextureLod > 0) --currentTextureLod;\n        }\n\n\n        \/\/ waiting for image layout transitions\n        imageLayoutCompile.context.waitForCompletion();\n\n        vsg::ref_ptr<vsg::TopLevelAccelerationStructure> tlas2;\n        \/\/auto terrainScene = tasManager->createCompleteScene(-terrainTileLengthLodFactor);\n\n        context->buildAccelerationStructureCommands.clear();\n        \/\/tlas2->compile(*context);\n        std::vector<vsg::ref_ptr<vsg::TopLevelAccelerationStructure>> tlasTestVector;\n        for (int currentLod = maxLod; currentLod >= -terrainTileLengthLodFactor; --currentLod) {\n            auto tlasTest = tasManager->createTlas(currentLod, true);\n            tlasTest->compile(*context);\n            tlasTestVector.push_back(tlasTest);\n        }\n        \/\/auto tlasTest0 = tasManager->createTlas(maxLod, true);\n        \/\/tlasTest0->compile(*context);\n        \/\/auto tlasTest1 = tasManager->createTlas(maxLod - 1, true);\n        \/\/tlasTest1->compile(*context);\n        \/\/auto tlasTest2 = tasManager->createTlas(maxLod - 2, true);\n        \/\/tlasTest2->compile(*context);\n        \/\/auto tlasTest3 = tasManager->createTlas(maxLod - 3, true);\n        \/\/tlasTest3->compile(*context);\n        \/\/tasManager->createTlas(maxLod - 1, true)->compile(*context);\n        \/\/tasManager->createTlas(maxLod - 2, true)->compile(*context);\n        \/\/tasManager->createTlas(maxLod - 3, true)->compile(*context);\n        context->record();\n\n        int framesAtSamePositionCount = 0;\n        auto oldEyePos = lookAt->eye;\n        bool terrainLodUpdatePerformed = false;\n\n        int frame_index = 0;\n        int sample_index = 0;\n        while(viewer->advanceToNextFrame() && (numFrames < 0 || frame_index < numFrames))\n        {\n            viewer->handleEvents();\n            if ((vsg::mat4)vsg::lookAt(lookAt->eye, lookAt->center, lookAt->up) != rayTracingPushConstantsValue->value().prevView)\n            {\n                \/\/ clear samples when the camera has moved\n                sample_index = 0;\n            }\n\n            if (lookAt->eye == oldEyePos) {\n                framesAtSamePositionCount++;\n            }\n            else {\n                oldEyePos = lookAt->eye;\n                framesAtSamePositionCount = 0;\n                terrainLodUpdatePerformed = false;\n            }\n\n            bool resetSamples = false;\n            \/\/if (rayTracingPushConstantsValue->value().frameNumber == 200) {\n            if (guiValues->updateTerrainLodButtonPressed || (framesAtSamePositionCount > 0 && ! terrainLodUpdatePerformed)) {\n                std::cout << \"update\" << std::endl;\n\n                \/\/auto terrainImporter3 = TerrainImporter::create(terrainHeightmapFilename, terrainTextureFilename, terrainScale, terrainScaleVertexHeight, terrainFormatLa2d, textureFormatS3tc, terrainHeightmapLod, terrainTextureLod, 0, terrainTilesX, terrainTilesY, terrainTileLengthLodFactor);\n                \/\/auto terrainImporter2 = TerrainImporter::create(terrainHeightmapFilename, terrainTextureFilename, terrainScale, terrainScaleVertexHeight, terrainFormatLa2d, textureFormatS3tc, terrainHeightmapLod-1, terrainTextureLod-1, 0, terrainTilesX, terrainTilesY, terrainTileLengthLodFactor);\n\n                \/\/auto tasManager = TerrainAccelerationStructureManager::create(terrainTilesX, terrainTilesY, 2, context);\n                \/\/tasManager->loadLodLevel(terrainImporter3, 0);\n                \/\/tasManager->loadLodLevel(terrainImporter2, 1);\n                \/\/tlas2 = tasManager->createTlas(-terrainTileLengthLodFactor);\n                \/\/auto terrainScene = tasManager->createScene(-terrainTileLengthLodFactor);\n\n                \/\/tlas2 = tasManager->createTlas(-terrainTileLengthLodFactor, false);\n                \/\/auto terrainScene = tasManager->createScene(-terrainTileLengthLodFactor);\n\n                double scaleModifier = terrainScale * 20.0;\n                if (terrainTileLengthLodFactor > 0) {\n                    scaleModifier *= (1L << terrainTileLengthLodFactor);\n                } else {\n                    scaleModifier \/= (1L << -terrainTileLengthLodFactor);\n                }\n\n                auto eyePosInTileCoords = lookAt->eye \/ scaleModifier;\n                eyePosInTileCoords.y *= -1;\n\n                auto pair = tasManager->createTlasAndScene(-terrainTileLengthLodFactor, eyePosInTileCoords);\n                tlas2 = pair.first;\n                auto terrainScene = pair.second;\n\n                context->buildAccelerationStructureCommands.clear();\n\n                \/\/tlas2->compile(*context);\n\n                \/\/pbrtPipeline->updateScene(terrainImporter3->loadedScene, context);\n                pbrtPipeline->updateScene(terrainScene, context);\n\n                pbrtPipeline->updateTlas(tlas2, context);\n\n                context->record();\n                \/\/context->waitForCompletion();\n\n                resetSamples = true;\n\n                CountTrianglesVisitor triangleCounter;\n                terrainScene->accept(triangleCounter);\n                guiValues->triangleCount = triangleCounter.triangleCount;\n\n                terrainLodUpdatePerformed = true;\n            }\n            if (rayTracingPushConstantsValue->value().frameNumber == -1000) {\n                std::cout << \"1000\" << std::endl;\n\n                context->buildAccelerationStructureCommands.clear();\n\n                pbrtPipeline->updateScene(loaded_scene, context);\n                pbrtPipeline->updateTlas(tlas, context);\n\n                context->record();\n                \/\/context->waitForCompletion();\n\n                resetSamples = true;\n\n                CountTrianglesVisitor triangleCounter;\n                loaded_scene->accept(triangleCounter);\n                guiValues->triangleCount = triangleCounter.triangleCount;\n            }\n\n\n\n            \n\n            rayTracingPushConstantsValue->value().viewInverse = lookAt->inverse();\n            rayTracingPushConstantsValue->value().frameNumber = frame_index;\n            rayTracingPushConstantsValue->value().sampleNumber = sample_index;\n            guiValues->sampleNumber = sample_index;\n            \n            if (use_external_buffers)\n            {\n                offlineGBufferStager->transferStagingDataFrom(offlineGBuffers[frame_index]);\n                offlineIlluminationBufferStager->transferStagingDataFrom(offlineIlluminations[frame_index]);\n                if (accumulator)\n                   accumulator->setCameraMatrices(frame_index, cameraMatrices[frame_index], cameraMatrices[frame_index ? frame_index - 1 : frame_index]);\n            }\n            else if (accumulator)\n            {\n                CameraMatrices a{}, b{};\n                a.invView = lookAt->inverse();\n                a.invProj = perspective->inverse();\n                a.proj = perspective->transform();\n                b.view = rayTracingPushConstantsValue->value().prevView;\n                accumulator->setCameraMatrices(rayTracingPushConstantsValue->value().frameNumber, a, b);\n            }\n\n            viewer->update();\n            viewer->recordAndSubmit();\n            viewer->present();\n\n            rayTracingPushConstantsValue->value().prevView = lookAt->transform();\n\n            if (sample_index + 1 >= samplesPerPixel) {\n                if (exportGBuffer || exportIllumination) {\n                    viewer->deviceWaitIdle();\n                    if (exportIllumination) {\n                        offlineIlluminationBufferStager->transferStagingDataTo(offlineIlluminations[frame_index]);\n                    }\n                    if (exportGBuffer) {\n                        offlineGBufferStager->transferStagingDataTo(offlineGBuffers[frame_index]);\n                    }\n                }\n                if (storeMatrices) {\n                    cameraMatrices[frame_index].view = lookAt->transform();\n                    cameraMatrices[frame_index].invView = lookAt->inverse();\n                    cameraMatrices[frame_index].proj.value() = perspective->transform();\n                    cameraMatrices[frame_index].invProj.value() = perspective->inverse();\n                }\n                frame_index++;\n            }\n            sample_index++;\n        }\n\n        \/\/ exporting all images\n        if (exportGBuffer)\n            GBufferIO::exportGBuffer(exportPositionPath, exportDepthPath, exportNormalPath, exportMaterialPath, exportAlbedoPath, numFrames, offlineGBuffers, cameraMatrices);\n        if (exportIllumination)\n            IlluminationBufferIO::exportIllumination(exportIlluminationPath, numFrames, offlineIlluminations);\n        if (exportMatricesPath.size())\n            MatrixIO::exportMatrices(exportMatricesPath, cameraMatrices);\n    }\n    catch (const vsg::Exception &e)\n    {\n        std::cout << e.message << \" VkResult = \" << e.result << std::endl;\n        return 0;\n    }\n    return 0;\n}","avg_line_length":50.5892857143,"max_line_length":399,"alphanum_fraction":0.6376411931,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":745,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":10.0,"content":"#include \"Events\/WantItems.h\"\n\nusing namespace event;\n\n\/* constructors\/destructor *\/\nWantItems::WantItems(bool dropping, bool safe_stash) : Event(\"WantItems\"), _dropping(dropping), _safe_stash(safe_stash), _items() {\n}\n\nWantItems::~WantItems() {\n}\n\n\/* methods *\/\nint WantItems::id() {\n\treturn ID;\n}\n\nstd::map<unsigned char, Item>& WantItems::items() {\n\treturn _items;\n}\n\nstd::map<unsigned char, Item>& WantItems::items(const std::map<unsigned char, Item>& items) {\n\t_items = items;\n\treturn this->items();\n}\n\nvoid WantItems::clear() {\n\t_items.clear();\n}\n\nvoid WantItems::addItem(unsigned char key, const Item& item) {\n\t_items[key] = item;\n}\n\nbool WantItems::dropping() {\n\treturn _dropping;\n}\n\nbool WantItems::safeStash() {\n\treturn _safe_stash;\n}\n","avg_line_length":18.1707317073,"max_line_length":131,"alphanum_fraction":0.6979865772,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":28005,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["PostgreSQL","Zlib","OpenSSL"],"max_stars_count":null,"content":"\/**\n * ScriptDev2 is an extension for mangos providing enhanced features for\n * area triggers, creatures, game objects, instances, items, and spells beyond\n * the default database scripting in mangos.\n *\n * Copyright (C) 2006-2013  ScriptDev2 <http:\/\/www.scriptdev2.com\/>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\n * World of Warcraft, and all World of Warcraft or Warcraft art, images,\n * and lore are copyrighted by Blizzard Entertainment, Inc.\n *\/\n\n\/**\n * ScriptData\n * SDName:      instance_blackrock_spire\n * SD%Complete: 75\n * SDComment:   The Stadium event is missing some yells. Seal of Ascension related event NYI\n * SDCategory:  Blackrock Spire\n * EndScriptData\n *\/\n\n#include \"precompiled.h\"\n#include \"blackrock_spire.h\"\n\nenum\n{\n    AREATRIGGER_ENTER_UBRS      = 2046,\n    AREATRIGGER_STADIUM         = 2026,\n\n    \/\/ Arena event dialogue - handled by instance\n    SAY_NEFARIUS_INTRO_1        = -1229004,\n    SAY_NEFARIUS_INTRO_2        = -1229005,\n    SAY_NEFARIUS_ATTACK_1       = -1229006,\n    SAY_REND_JOIN               = -1229007,\n    SAY_NEFARIUS_ATTACK_2       = -1229008,\n    SAY_NEFARIUS_ATTACK_3       = -1229009,\n    SAY_NEFARIUS_ATTACK_4       = -1229010,\n    SAY_REND_LOSE_1             = -1229011,\n    SAY_REND_LOSE_2             = -1229012,\n    SAY_NEFARIUS_LOSE_3         = -1229013,\n    SAY_NEFARIUS_LOSE_4         = -1229014,\n    SAY_REND_ATTACK             = -1229015,\n    SAY_NEFARIUS_WARCHIEF       = -1229016,\n    SAY_NEFARIUS_VICTORY        = -1229018,\n\n    \/\/ Emberseer event\n    EMOTE_BEGIN                 = -1229000,\n    SPELL_EMBERSEER_GROWING     = 16048,\n\n    \/\/ Solakar Flamewreath Event\n    SAY_ROOKERY_EVENT_START     = -1229020,\n    NPC_ROOKERY_GUARDIAN        = 10258,\n    NPC_ROOKERY_HATCHER         = 10683,\n};\n\n\/* Areatrigger\n1470 Instance Entry\n1628 LBRS, between Spiders and Ogres\n1946 LBRS, ubrs pre-quest giver (1)\n1986 LBRS, ubrs pre-quest giver (2)\n1987 LBRS, ubrs pre-quest giver (3)\n2026 UBRS, stadium event trigger\n2046 UBRS, way to upper\n2066 UBRS, The Beast - Exit (to the dark chamber)\n2067 UBRS, The Beast - Entry\n2068 LBRS, fall out of map\n3726 UBRS, entrance to BWL\n*\/\n\nstatic const DialogueEntry aStadiumDialogue[] =\n{\n    {NPC_LORD_VICTOR_NEFARIUS,  0,                          1000},\n    {SAY_NEFARIUS_INTRO_1,      NPC_LORD_VICTOR_NEFARIUS,   7000},\n    {SAY_NEFARIUS_INTRO_2,      NPC_LORD_VICTOR_NEFARIUS,   5000},\n    {NPC_BLACKHAND_HANDLER,     0,                          0},\n    {SAY_NEFARIUS_LOSE_4,       NPC_LORD_VICTOR_NEFARIUS,   3000},\n    {SAY_REND_ATTACK,           NPC_REND_BLACKHAND,         2000},\n    {SAY_NEFARIUS_WARCHIEF,     NPC_LORD_VICTOR_NEFARIUS,   0},\n    {SAY_NEFARIUS_VICTORY,      NPC_LORD_VICTOR_NEFARIUS,   5000},\n    {NPC_REND_BLACKHAND,        0,                          0},\n    {0, 0, 0},\n};\n\nstatic const float rookeryEventSpawnPos[3] = {43.7685f, -259.82f, 91.6483f};\n\ninstance_blackrock_spire::instance_blackrock_spire(Map* pMap) : ScriptedInstance(pMap), DialogueHelper(aStadiumDialogue),\n    m_uiFlamewreathEventTimer(0),\n    m_uiFlamewreathWaveCount(0),\n    m_uiStadiumEventTimer(0),\n    m_uiStadiumWaves(0),\n    m_uiStadiumMobsAlive(0)\n{\n    Initialize();\n}\n\nvoid instance_blackrock_spire::Initialize()\n{\n    memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));\n    memset(&m_aRoomRuneGuid, 0, sizeof(m_aRoomRuneGuid));\n    InitializeDialogueHelper(this);\n}\n\nvoid instance_blackrock_spire::OnObjectCreate(GameObject* pGo)\n{\n    switch (pGo->GetEntry())\n    {\n        case GO_EMBERSEER_IN:\n            if (GetData(TYPE_ROOM_EVENT) == DONE)\n            {\n                pGo->SetGoState(GO_STATE_ACTIVE);\n            }\n            break;\n        case GO_DOORS:\n            break;\n        case GO_EMBERSEER_OUT:\n            if (GetData(TYPE_EMBERSEER) == DONE)\n            {\n                pGo->SetGoState(GO_STATE_ACTIVE);\n            }\n            break;\n        case GO_FATHER_FLAME:\n        case GO_GYTH_ENTRY_DOOR:\n        case GO_GYTH_COMBAT_DOOR:\n        case GO_DRAKKISATH_DOOR_1:\n        case GO_DRAKKISATH_DOOR_2:\n            break;\n        case GO_GYTH_EXIT_DOOR:\n            if (GetData(TYPE_STADIUM) == DONE)\n            {\n                pGo->SetGoState(GO_STATE_ACTIVE);\n            }\n            break;\n\n        case GO_ROOM_1_RUNE:\n            m_aRoomRuneGuid[0] = pGo->GetObjectGuid();\n            return;\n        case GO_ROOM_2_RUNE:\n            m_aRoomRuneGuid[1] = pGo->GetObjectGuid();\n            return;\n        case GO_ROOM_3_RUNE:\n            m_aRoomRuneGuid[2] = pGo->GetObjectGuid();\n            return;\n        case GO_ROOM_4_RUNE:\n            m_aRoomRuneGuid[3] = pGo->GetObjectGuid();\n            return;\n        case GO_ROOM_5_RUNE:\n            m_aRoomRuneGuid[4] = pGo->GetObjectGuid();\n            return;\n        case GO_ROOM_6_RUNE:\n            m_aRoomRuneGuid[5] = pGo->GetObjectGuid();\n            return;\n        case GO_ROOM_7_RUNE:\n            m_aRoomRuneGuid[6] = pGo->GetObjectGuid();\n            return;\n\n        case GO_EMBERSEER_RUNE_1:\n        case GO_EMBERSEER_RUNE_2:\n        case GO_EMBERSEER_RUNE_3:\n        case GO_EMBERSEER_RUNE_4:\n        case GO_EMBERSEER_RUNE_5:\n        case GO_EMBERSEER_RUNE_6:\n        case GO_EMBERSEER_RUNE_7:\n            m_lEmberseerRunesGUIDList.push_back(pGo->GetObjectGuid());\n            return;\n\n        default:\n            return;\n    }\n    m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid();\n}\n\nvoid instance_blackrock_spire::OnCreatureCreate(Creature* pCreature)\n{\n    switch (pCreature->GetEntry())\n    {\n        case NPC_PYROGUARD_EMBERSEER:\n        case NPC_SOLAKAR_FLAMEWREATH:\n        case NPC_LORD_VICTOR_NEFARIUS:\n        case NPC_GYTH:\n        case NPC_REND_BLACKHAND:\n        case NPC_SCARSHIELD_INFILTRATOR:\n            m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid();\n            break;\n\n        case NPC_BLACKHAND_SUMMONER:\n        case NPC_BLACKHAND_VETERAN:\n            m_lRoomEventMobGUIDList.push_back(pCreature->GetObjectGuid());\n            break;\n        case NPC_BLACKHAND_INCARCERATOR:\n            m_lIncarceratorGUIDList.push_back(pCreature->GetObjectGuid());\n            break;\n    }\n}\n\nvoid instance_blackrock_spire::SetData(uint32 uiType, uint32 uiData)\n{\n    switch (uiType)\n    {\n        case TYPE_ROOM_EVENT:\n            if (uiData == DONE)\n            {\n                DoUseDoorOrButton(GO_EMBERSEER_IN);\n            }\n            m_auiEncounter[uiType] = uiData;\n            break;\n        case TYPE_EMBERSEER:\n            \/\/ Don't set the same data twice\n            if (m_auiEncounter[uiType] == uiData)\n            {\n                break;\n            }\n            \/\/ Combat door\n            DoUseDoorOrButton(GO_DOORS);\n            \/\/ Respawn all incarcerators and reset the runes on FAIL\n            if (uiData == FAIL)\n            {\n                for (GuidList::const_iterator itr = m_lIncarceratorGUIDList.begin(); itr != m_lIncarceratorGUIDList.end(); ++itr)\n                {\n                    if (Creature* pIncarcerator = instance->GetCreature(*itr))\n                    {\n                        if (!pIncarcerator->IsAlive())\n                        {\n                            pIncarcerator->Respawn();\n                        }\n                        pIncarcerator->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE);\n                    }\n                }\n\n                DoUseEmberseerRunes(true);\n            }\n            else if (uiData == DONE)\n            {\n                DoUseEmberseerRunes();\n                DoUseDoorOrButton(GO_EMBERSEER_OUT);\n            }\n            m_auiEncounter[uiType] = uiData;\n            break;\n        case TYPE_FLAMEWREATH:\n            if (uiData == FAIL)\n            {\n                m_uiFlamewreathEventTimer = 0;\n                m_uiFlamewreathWaveCount = 0;\n            }\n            m_auiEncounter[uiType] = uiData;\n            break;\n        case TYPE_STADIUM:\n            \/\/ Don't set the same data twice\n            if (m_auiEncounter[uiType] == uiData)\n            {\n                break;\n            }\n            \/\/ Combat door\n            DoUseDoorOrButton(GO_GYTH_ENTRY_DOOR);\n            \/\/ Start event\n            if (uiData == IN_PROGRESS)\n            {\n                StartNextDialogueText(SAY_NEFARIUS_INTRO_1);\n            }\n            else if (uiData == DONE)\n            {\n                DoUseDoorOrButton(GO_GYTH_EXIT_DOOR);\n            }\n            else if (uiData == FAIL)\n            {\n                \/\/ Despawn Nefarius and Rend on fail (the others are despawned OnCreatureEvade())\n                if (Creature* pNefarius = GetSingleCreatureFromStorage(NPC_LORD_VICTOR_NEFARIUS))\n                {\n                    pNefarius->ForcedDespawn();\n                }\n                if (Creature* pRend = GetSingleCreatureFromStorage(NPC_REND_BLACKHAND))\n                {\n                    pRend->ForcedDespawn();\n                }\n                if (Creature* pGyth = GetSingleCreatureFromStorage(NPC_GYTH))\n                {\n                    pGyth->ForcedDespawn();\n                }\n\n                m_uiStadiumEventTimer = 0;\n                m_uiStadiumMobsAlive = 0;\n                m_uiStadiumWaves = 0;\n            }\n            m_auiEncounter[uiType] = uiData;\n            break;\n        case TYPE_DRAKKISATH:\n        case TYPE_VALTHALAK:\n            m_auiEncounter[uiType] = uiData;\n            break;\n    }\n\n    if (uiData == DONE)\n    {\n        OUT_SAVE_INST_DATA;\n\n        std::ostringstream saveStream;\n        saveStream << m_auiEncounter[0] << \" \" << m_auiEncounter[1] << \" \" << m_auiEncounter[2] << \" \" << m_auiEncounter[3] << \" \" << m_auiEncounter[4] << \" \" << m_auiEncounter[5];\n\n        m_strInstData = saveStream.str();\n\n        SaveToDB();\n        OUT_SAVE_INST_DATA_COMPLETE;\n    }\n}\n\nvoid instance_blackrock_spire::Load(const char* chrIn)\n{\n    if (!chrIn)\n    {\n        OUT_LOAD_INST_DATA_FAIL;\n        return;\n    }\n\n    OUT_LOAD_INST_DATA(chrIn);\n\n    std::istringstream loadStream(chrIn);\n    loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3] >> m_auiEncounter[4] >> m_auiEncounter[5];\n\n    for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)\n    {\n        if (m_auiEncounter[i] == IN_PROGRESS)\n        {\n            m_auiEncounter[i] = NOT_STARTED;\n        }\n    }\n\n    OUT_LOAD_INST_DATA_COMPLETE;\n}\n\nuint32 instance_blackrock_spire::GetData(uint32 uiType) const\n{\n    if (uiType < MAX_ENCOUNTER)\n    {\n        return m_auiEncounter[uiType];\n    }\n\n    return 0;\n}\n\nvoid instance_blackrock_spire::DoSortRoomEventMobs()\n{\n    if (GetData(TYPE_ROOM_EVENT) != NOT_STARTED)\n    {\n        return;\n    }\n\n    for (uint8 i = 0; i < MAX_ROOMS; ++i)\n    {\n        if (GameObject* pRune = instance->GetGameObject(m_aRoomRuneGuid[i]))\n        {\n            for (GuidList::const_iterator itr = m_lRoomEventMobGUIDList.begin(); itr != m_lRoomEventMobGUIDList.end(); ++itr)\n            {\n                Creature* pCreature = instance->GetCreature(*itr);\n                if (pCreature && pCreature->IsAlive() && pCreature->GetDistance(pRune) < 10.0f)\n                {\n                    m_alRoomEventMobGUIDSorted[i].push_back(*itr);\n                }\n            }\n        }\n    }\n\n    SetData(TYPE_ROOM_EVENT, IN_PROGRESS);\n}\n\nvoid instance_blackrock_spire::OnCreatureDeath(Creature* pCreature)\n{\n    switch (pCreature->GetEntry())\n    {\n        case NPC_BLACKHAND_SUMMONER:\n        case NPC_BLACKHAND_VETERAN:\n            \/\/ Handle Runes\n            if (m_auiEncounter[TYPE_ROOM_EVENT] == IN_PROGRESS)\n            {\n                uint8 uiNotEmptyRoomsCount = 0;\n                for (uint8 i = 0; i < MAX_ROOMS; ++i)\n                {\n                    if (m_aRoomRuneGuid[i])                 \/\/ This check is used, to ensure which runes still need processing\n                    {\n                        m_alRoomEventMobGUIDSorted[i].remove(pCreature->GetObjectGuid());\n                        if (m_alRoomEventMobGUIDSorted[i].empty())\n                        {\n                            DoUseDoorOrButton(m_aRoomRuneGuid[i]);\n                            m_aRoomRuneGuid[i].Clear();\n                        }\n                        else\n                        {\n                            ++uiNotEmptyRoomsCount;    \/\/ found an not empty room\n                        }\n                    }\n                }\n                if (!uiNotEmptyRoomsCount)\n                {\n                    SetData(TYPE_ROOM_EVENT, DONE);\n                }\n            }\n            break;\n        case NPC_SOLAKAR_FLAMEWREATH:\n            SetData(TYPE_FLAMEWREATH, DONE);\n            break;\n        case NPC_DRAKKISATH:\n            SetData(TYPE_DRAKKISATH, DONE);\n            DoUseDoorOrButton(GO_DRAKKISATH_DOOR_1);\n            DoUseDoorOrButton(GO_DRAKKISATH_DOOR_2);\n            break;\n        case NPC_CHROMATIC_WHELP:\n        case NPC_CHROMATIC_DRAGON:\n        case NPC_BLACKHAND_HANDLER:\n            \/\/ check if it's summoned - some npcs with the same entry are already spawned in the instance\n            if (!pCreature->IsTemporarySummon())\n            {\n                break;\n            }\n            --m_uiStadiumMobsAlive;\n            if (m_uiStadiumMobsAlive == 0)\n            {\n                DoSendNextStadiumWave();\n            }\n            break;\n        case NPC_GYTH:\n        case NPC_REND_BLACKHAND:\n            --m_uiStadiumMobsAlive;\n            if (m_uiStadiumMobsAlive == 0)\n            {\n                StartNextDialogueText(SAY_NEFARIUS_VICTORY);\n            }\n            break;\n    }\n}\n\nvoid instance_blackrock_spire::OnCreatureEvade(Creature* pCreature)\n{\n    switch (pCreature->GetEntry())\n    {\n            \/\/ Emberseer should evade if the incarcerators evade\n        case NPC_BLACKHAND_INCARCERATOR:\n            if (Creature* pEmberseer = GetSingleCreatureFromStorage(NPC_PYROGUARD_EMBERSEER))\n            {\n                pEmberseer->AI()->EnterEvadeMode();\n            }\n            break;\n        case NPC_SOLAKAR_FLAMEWREATH:\n        case NPC_ROOKERY_GUARDIAN:\n        case NPC_ROOKERY_HATCHER:\n            SetData(TYPE_FLAMEWREATH, FAIL);\n            break;\n        case NPC_CHROMATIC_WHELP:\n        case NPC_CHROMATIC_DRAGON:\n        case NPC_BLACKHAND_HANDLER:\n        case NPC_GYTH:\n        case NPC_REND_BLACKHAND:\n            \/\/ check if it's summoned - some npcs with the same entry are already spawned in the instance\n            if (!pCreature->IsTemporarySummon())\n            {\n                break;\n            }\n            SetData(TYPE_STADIUM, FAIL);\n            pCreature->ForcedDespawn();\n            break;\n    }\n}\n\nvoid instance_blackrock_spire::OnCreatureEnterCombat(Creature* pCreature)\n{\n    switch (pCreature->GetEntry())\n    {\n            \/\/ Once one of the Incarcerators gets Aggro, the door should close\n        case NPC_BLACKHAND_INCARCERATOR:\n            SetData(TYPE_EMBERSEER, IN_PROGRESS);\n            break;\n    }\n}\n\nvoid instance_blackrock_spire::DoProcessEmberseerEvent()\n{\n    if (GetData(TYPE_EMBERSEER) == DONE || GetData(TYPE_EMBERSEER) == IN_PROGRESS)\n    {\n        return;\n    }\n\n    if (m_lIncarceratorGUIDList.empty())\n    {\n        script_error_log(\"Npc %u couldn't be found. Please check your DB content!\", NPC_BLACKHAND_INCARCERATOR);\n        return;\n    }\n\n    \/\/ start to grow\n    if (Creature* pEmberseer = GetSingleCreatureFromStorage(NPC_PYROGUARD_EMBERSEER))\n    {\n        \/\/ If already casting, return\n        if (pEmberseer->HasAura(SPELL_EMBERSEER_GROWING))\n        {\n            return;\n        }\n\n        DoScriptText(EMOTE_BEGIN, pEmberseer);\n        pEmberseer->CastSpell(pEmberseer, SPELL_EMBERSEER_GROWING, true);\n    }\n\n    \/\/ remove the incarcerators flags and stop casting\n    for (GuidList::const_iterator itr = m_lIncarceratorGUIDList.begin(); itr != m_lIncarceratorGUIDList.end(); ++itr)\n    {\n        if (Creature* pCreature = instance->GetCreature(*itr))\n        {\n            if (pCreature->IsAlive())\n            {\n                pCreature->InterruptNonMeleeSpells(false);\n                pCreature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE);\n            }\n        }\n    }\n}\n\nvoid instance_blackrock_spire::DoUseEmberseerRunes(bool bReset)\n{\n    if (m_lEmberseerRunesGUIDList.empty())\n    {\n        return;\n    }\n\n    for (GuidList::const_iterator itr = m_lEmberseerRunesGUIDList.begin(); itr != m_lEmberseerRunesGUIDList.end(); ++itr)\n    {\n        if (bReset)\n        {\n            if (GameObject* pRune = instance->GetGameObject(*itr))\n            {\n                pRune->ResetDoorOrButton();\n            }\n        }\n        else\n        {\n            DoUseDoorOrButton(*itr);\n        }\n    }\n}\n\nvoid instance_blackrock_spire::JustDidDialogueStep(int32 iEntry)\n{\n    switch (iEntry)\n    {\n        case NPC_BLACKHAND_HANDLER:\n            m_uiStadiumEventTimer = 1000;\n            \/\/ Move the two near the balcony\n            if (Creature* pRend = GetSingleCreatureFromStorage(NPC_REND_BLACKHAND))\n            {\n                pRend->SetFacingTo(aStadiumLocs[5].m_fO);\n            }\n            if (Creature* pNefarius = GetSingleCreatureFromStorage(NPC_LORD_VICTOR_NEFARIUS))\n            {\n                pNefarius->GetMotionMaster()->MovePoint(0, aStadiumLocs[5].m_fX, aStadiumLocs[5].m_fY, aStadiumLocs[5].m_fZ);\n            }\n            break;\n        case SAY_NEFARIUS_WARCHIEF:\n            \/\/ Prepare for Gyth - note: Nefarius should be moving around the balcony\n            if (Creature* pRend = GetSingleCreatureFromStorage(NPC_REND_BLACKHAND))\n            {\n                pRend->ForcedDespawn(5000);\n                pRend->SetWalk(false);\n                pRend->GetMotionMaster()->MovePoint(0, aStadiumLocs[6].m_fX, aStadiumLocs[6].m_fY, aStadiumLocs[6].m_fZ);\n            }\n            m_uiStadiumEventTimer = 30000;\n            break;\n        case SAY_NEFARIUS_VICTORY:\n            SetData(TYPE_STADIUM, DONE);\n            break;\n        case NPC_REND_BLACKHAND:\n            \/\/ Despawn Nefarius\n            if (Creature* pNefarius = GetSingleCreatureFromStorage(NPC_LORD_VICTOR_NEFARIUS))\n            {\n                pNefarius->ForcedDespawn(5000);\n                pNefarius->GetMotionMaster()->MovePoint(0, aStadiumLocs[6].m_fX, aStadiumLocs[6].m_fY, aStadiumLocs[6].m_fZ);\n            }\n            break;\n    }\n}\n\nvoid instance_blackrock_spire::DoSendNextStadiumWave()\n{\n    if (m_uiStadiumWaves < MAX_STADIUM_WAVES)\n    {\n        \/\/ Send current wave mobs\n        if (Creature* pNefarius = GetSingleCreatureFromStorage(NPC_LORD_VICTOR_NEFARIUS))\n        {\n            float fX, fY, fZ;\n            for (uint8 i = 0; i < MAX_STADIUM_MOBS_PER_WAVE; ++i)\n            {\n                if (aStadiumEventNpcs[m_uiStadiumWaves][i] == 0)\n                {\n                    continue;\n                }\n\n                pNefarius->GetRandomPoint(aStadiumLocs[0].m_fX, aStadiumLocs[0].m_fY, aStadiumLocs[0].m_fZ, 7.0f, fX, fY, fZ);\n                fX = std::min(aStadiumLocs[0].m_fX, fX);    \/\/ Halfcircle - suits better the rectangular form\n                if (Creature* pTemp = pNefarius->SummonCreature(aStadiumEventNpcs[m_uiStadiumWaves][i], fX, fY, fZ, 0.0f, TEMPSUMMON_DEAD_DESPAWN, 0))\n                {\n                    \/\/ Get some point in the center of the stadium\n                    pTemp->GetRandomPoint(aStadiumLocs[2].m_fX, aStadiumLocs[2].m_fY, aStadiumLocs[2].m_fZ, 5.0f, fX, fY, fZ);\n                    fX = std::min(aStadiumLocs[2].m_fX, fX);\/\/ Halfcircle - suits better the rectangular form\n\n                    pTemp->GetMotionMaster()->MovePoint(0, fX, fY, fZ);\n                    ++m_uiStadiumMobsAlive;\n                }\n            }\n        }\n\n        DoUseDoorOrButton(GO_GYTH_COMBAT_DOOR);\n    }\n    \/\/ All waves are cleared - start Gyth intro\n    else if (m_uiStadiumWaves == MAX_STADIUM_WAVES)\n    {\n        StartNextDialogueText(SAY_NEFARIUS_LOSE_4);\n    }\n    else\n    {\n        \/\/ Send Gyth\n        if (Creature* pNefarius = GetSingleCreatureFromStorage(NPC_LORD_VICTOR_NEFARIUS))\n        {\n            if (Creature* pTemp = pNefarius->SummonCreature(NPC_GYTH, aStadiumLocs[1].m_fX, aStadiumLocs[1].m_fY, aStadiumLocs[1].m_fZ, 0.0f, TEMPSUMMON_DEAD_DESPAWN, 0))\n            {\n                pTemp->GetMotionMaster()->MovePoint(0, aStadiumLocs[2].m_fX, aStadiumLocs[2].m_fY, aStadiumLocs[2].m_fZ);\n            }\n        }\n\n        \/\/ Set this to 2, because Rend will be summoned later during the fight\n        m_uiStadiumMobsAlive = 2;\n\n        DoUseDoorOrButton(GO_GYTH_COMBAT_DOOR);\n    }\n\n    ++m_uiStadiumWaves;\n\n    \/\/ Stop the timer when all the waves have been sent\n    if (m_uiStadiumWaves >= MAX_STADIUM_WAVES)\n    {\n        m_uiStadiumEventTimer = 0;\n    }\n    else\n    {\n        m_uiStadiumEventTimer = 60000;\n    }\n}\n\nvoid instance_blackrock_spire::DoSendNextFlamewreathWave()\n{\n    GameObject* pSummoner = GetSingleGameObjectFromStorage(GO_FATHER_FLAME);\n    if (!pSummoner)\n    {\n        return;\n    }\n\n    \/\/ TODO - The npcs would move nicer if they had DB waypoints, so i suggest to change their default movement to DB waypoints, and random movement when they reached their goal\n\n    if (m_uiFlamewreathWaveCount < 6)                       \/\/ Send two adds (6 waves, then boss)\n    {\n        Creature* pSummoned = NULL;\n        for (uint8 i = 0; i < 2; ++i)\n        {\n            float fX, fY, fZ;\n            pSummoner->GetRandomPoint(rookeryEventSpawnPos[0], rookeryEventSpawnPos[1], rookeryEventSpawnPos[2], 2.5f, fX, fY, fZ);\n            \/\/ Summon Rookery Hatchers in first wave, else random\n            pSummoned = pSummoner->SummonCreature(urand(0, 1) && m_uiFlamewreathWaveCount ? NPC_ROOKERY_GUARDIAN : NPC_ROOKERY_HATCHER, fX, fY, fZ, 0.0, TEMPSUMMON_TIMED_OOC_OR_DEAD_DESPAWN, 300000);\n            if (pSummoned)\n            {\n                pSummoner->GetContactPoint(pSummoned, fX, fY, fZ);\n                pSummoned->GetMotionMaster()->MovePoint(1, fX, fY, pSummoner->GetPositionZ());\n            }\n        }\n        if (pSummoned && m_uiFlamewreathWaveCount == 0)\n        {\n            DoScriptText(SAY_ROOKERY_EVENT_START, pSummoned);\n        }\n\n        if (m_uiFlamewreathWaveCount < 4)\n        {\n            m_uiFlamewreathEventTimer = 30000;\n        }\n        else if (m_uiFlamewreathWaveCount < 6)\n        {\n            m_uiFlamewreathEventTimer = 40000;\n        }\n        else\n        {\n            m_uiFlamewreathEventTimer = 10000;\n        }\n\n        ++m_uiFlamewreathWaveCount;\n    }\n    else                                                    \/\/ Send Flamewreath\n    {\n        if (Creature* pSolakar = pSummoner->SummonCreature(NPC_SOLAKAR_FLAMEWREATH, rookeryEventSpawnPos[0], rookeryEventSpawnPos[1], rookeryEventSpawnPos[2], 0.0f, TEMPSUMMON_TIMED_OOC_OR_DEAD_DESPAWN, HOUR * IN_MILLISECONDS))\n        {\n            pSolakar->GetMotionMaster()->MovePoint(1, pSummoner->GetPositionX(), pSummoner->GetPositionY(), pSummoner->GetPositionZ());\n        }\n        SetData(TYPE_FLAMEWREATH, SPECIAL);\n        m_uiFlamewreathEventTimer = 0;\n    }\n}\n\nvoid instance_blackrock_spire::Update(uint32 uiDiff)\n{\n    DialogueUpdate(uiDiff);\n\n    if (m_uiStadiumEventTimer)\n    {\n        if (m_uiStadiumEventTimer <= uiDiff)\n        {\n            DoSendNextStadiumWave();\n        }\n        else\n        {\n            m_uiStadiumEventTimer -= uiDiff;\n        }\n    }\n\n    if (m_uiFlamewreathEventTimer)\n    {\n        if (m_uiFlamewreathEventTimer <= uiDiff)\n        {\n            DoSendNextFlamewreathWave();\n        }\n        else\n        {\n            m_uiFlamewreathEventTimer -= uiDiff;\n        }\n    }\n}\n\nvoid instance_blackrock_spire::StartflamewreathEventIfCan()\n{\n    \/\/ Already done or currently in progress - or endboss done\n    if (m_auiEncounter[TYPE_FLAMEWREATH] == DONE || m_auiEncounter[TYPE_FLAMEWREATH] == IN_PROGRESS || m_auiEncounter[TYPE_DRAKKISATH] == DONE)\n    {\n        return;\n    }\n\n    \/\/ Boss still around\n    if (GetSingleCreatureFromStorage(NPC_SOLAKAR_FLAMEWREATH, true))\n    {\n        return;\n    }\n\n    \/\/ Start summoning of mobs\n    m_uiFlamewreathEventTimer = 1;\n    m_uiFlamewreathWaveCount = 0;\n}\n\nInstanceData* GetInstanceData_instance_blackrock_spire(Map* pMap)\n{\n    return new instance_blackrock_spire(pMap);\n}\n\nbool AreaTrigger_at_blackrock_spire(Player* pPlayer, AreaTriggerEntry const* pAt)\n{\n    if (!pPlayer->IsAlive() || pPlayer->isGameMaster())\n    {\n        return false;\n    }\n\n    switch (pAt->id)\n    {\n        case AREATRIGGER_ENTER_UBRS:\n            if (instance_blackrock_spire* pInstance = (instance_blackrock_spire*) pPlayer->GetInstanceData())\n            {\n                pInstance->DoSortRoomEventMobs();\n            }\n            break;\n        case AREATRIGGER_STADIUM:\n            if (instance_blackrock_spire* pInstance = (instance_blackrock_spire*) pPlayer->GetInstanceData())\n            {\n                if (pInstance->GetData(TYPE_STADIUM) == IN_PROGRESS || pInstance->GetData(TYPE_STADIUM) == DONE)\n                {\n                    return false;\n                }\n\n                \/\/ Summon Nefarius and Rend for the dialogue event\n                \/\/ Note: Nefarius and Rend need to be hostile and not attackable\n                if (Creature* pNefarius = pPlayer->SummonCreature(NPC_LORD_VICTOR_NEFARIUS, aStadiumLocs[3].m_fX, aStadiumLocs[3].m_fY, aStadiumLocs[3].m_fZ, aStadiumLocs[3].m_fO, TEMPSUMMON_CORPSE_DESPAWN, 0))\n                {\n                    pNefarius->SetFactionTemporary(FACTION_BLACK_DRAGON, TEMPFACTION_NONE);\n                }\n                if (Creature* pRend = pPlayer->SummonCreature(NPC_REND_BLACKHAND, aStadiumLocs[4].m_fX, aStadiumLocs[4].m_fY, aStadiumLocs[4].m_fZ, aStadiumLocs[4].m_fO, TEMPSUMMON_CORPSE_DESPAWN, 0))\n                {\n                    pRend->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);\n                }\n\n                pInstance->SetData(TYPE_STADIUM, IN_PROGRESS);\n            }\n            break;\n    }\n    return false;\n}\n\nbool ProcessEventId_event_spell_altar_emberseer(uint32 \/*uiEventId*\/, Object* pSource, Object* \/*pTarget*\/, bool bIsStart)\n{\n    if (bIsStart && pSource->GetTypeId() == TYPEID_PLAYER)\n    {\n        if (instance_blackrock_spire* pInstance = (instance_blackrock_spire*)((Player*)pSource)->GetInstanceData())\n        {\n            pInstance->DoProcessEmberseerEvent();\n            return true;\n        }\n    }\n    return false;\n}\n\nbool GOUse_go_father_flame(Player* \/*pPlayer*\/, GameObject* pGo)\n{\n    if (instance_blackrock_spire* pInstance = (instance_blackrock_spire*)pGo->GetInstanceData())\n    {\n        pInstance->StartflamewreathEventIfCan();\n    }\n\n    return true;\n}\n\nvoid AddSC_instance_blackrock_spire()\n{\n    Script* pNewScript;\n\n    pNewScript = new Script;\n    pNewScript->Name = \"instance_blackrock_spire\";\n    pNewScript->GetInstanceData = &GetInstanceData_instance_blackrock_spire;\n    pNewScript->RegisterSelf();\n\n    pNewScript = new Script;\n    pNewScript->Name = \"at_blackrock_spire\";\n    pNewScript->pAreaTrigger = &AreaTrigger_at_blackrock_spire;\n    pNewScript->RegisterSelf();\n\n    pNewScript = new Script;\n    pNewScript->Name = \"event_spell_altar_emberseer\";\n    pNewScript->pProcessEventId = &ProcessEventId_event_spell_altar_emberseer;\n    pNewScript->RegisterSelf();\n\n    pNewScript = new Script;\n    pNewScript->Name = \"go_father_flame\";\n    pNewScript->pGOUse = &GOUse_go_father_flame;\n    pNewScript->RegisterSelf();\n}\n","avg_line_length":32.9083431257,"max_line_length":227,"alphanum_fraction":0.5897875379,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":22106,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Copyright (C) 2014 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/#define LOG_NDEBUG 0\n#define LOG_TAG \"SoftOpus\"\n#include <utils\/Log.h>\n\n#include \"SoftOpus.h\"\n#include <OMX_AudioExt.h>\n#include <OMX_IndexExt.h>\n\n#include <media\/stagefright\/foundation\/ADebug.h>\n#include <media\/stagefright\/MediaDefs.h>\n\nextern \"C\" {\n    #include <opus.h>\n    #include <opus_multistream.h>\n}\n\nnamespace android {\n\nstatic const int kRate = 48000;\n\n\/\/ Opus uses Vorbis channel mapping, and Vorbis channel mapping specifies\n\/\/ mappings for up to 8 channels. This information is part of the Vorbis I\n\/\/ Specification:\n\/\/ http:\/\/www.xiph.org\/vorbis\/doc\/Vorbis_I_spec.html\nstatic const int kMaxChannels = 8;\n\ntemplate<class T>\nstatic void InitOMXParams(T *params) {\n    params->nSize = sizeof(T);\n    params->nVersion.s.nVersionMajor = 1;\n    params->nVersion.s.nVersionMinor = 0;\n    params->nVersion.s.nRevision = 0;\n    params->nVersion.s.nStep = 0;\n}\n\nSoftOpus::SoftOpus(\n        const char *name,\n        const OMX_CALLBACKTYPE *callbacks,\n        OMX_PTR appData,\n        OMX_COMPONENTTYPE **component)\n    : SimpleSoftOMXComponent(name, callbacks, appData, component),\n      mInputBufferCount(0),\n      mDecoder(NULL),\n      mHeader(NULL),\n      mCodecDelay(0),\n      mSeekPreRoll(0),\n      mAnchorTimeUs(0),\n      mNumFramesOutput(0),\n      mHaveEOS(false),\n      mOutputPortSettingsChange(NONE) {\n    initPorts();\n    CHECK_EQ(initDecoder(), (status_t)OK);\n}\n\nSoftOpus::~SoftOpus() {\n    if (mDecoder != NULL) {\n        opus_multistream_decoder_destroy(mDecoder);\n        mDecoder = NULL;\n    }\n    if (mHeader != NULL) {\n        delete mHeader;\n        mHeader = NULL;\n    }\n}\n\nvoid SoftOpus::initPorts() {\n    OMX_PARAM_PORTDEFINITIONTYPE def;\n    InitOMXParams(&def);\n\n    def.nPortIndex = 0;\n    def.eDir = OMX_DirInput;\n    def.nBufferCountMin = kNumBuffers;\n    def.nBufferCountActual = def.nBufferCountMin;\n    def.nBufferSize = 960 * 6;\n    def.bEnabled = OMX_TRUE;\n    def.bPopulated = OMX_FALSE;\n    def.eDomain = OMX_PortDomainAudio;\n    def.bBuffersContiguous = OMX_FALSE;\n    def.nBufferAlignment = 1;\n\n    def.format.audio.cMIMEType =\n        const_cast<char *>(MEDIA_MIMETYPE_AUDIO_OPUS);\n\n    def.format.audio.pNativeRender = NULL;\n    def.format.audio.bFlagErrorConcealment = OMX_FALSE;\n    def.format.audio.eEncoding =\n        (OMX_AUDIO_CODINGTYPE)OMX_AUDIO_CodingAndroidOPUS;\n\n    addPort(def);\n\n    def.nPortIndex = 1;\n    def.eDir = OMX_DirOutput;\n    def.nBufferCountMin = kNumBuffers;\n    def.nBufferCountActual = def.nBufferCountMin;\n    def.nBufferSize = kMaxNumSamplesPerBuffer * sizeof(int16_t) * kMaxChannels;\n    def.bEnabled = OMX_TRUE;\n    def.bPopulated = OMX_FALSE;\n    def.eDomain = OMX_PortDomainAudio;\n    def.bBuffersContiguous = OMX_FALSE;\n    def.nBufferAlignment = 2;\n\n    def.format.audio.cMIMEType = const_cast<char *>(\"audio\/raw\");\n    def.format.audio.pNativeRender = NULL;\n    def.format.audio.bFlagErrorConcealment = OMX_FALSE;\n    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;\n\n    addPort(def);\n}\n\nstatus_t SoftOpus::initDecoder() {\n    return OK;\n}\n\nOMX_ERRORTYPE SoftOpus::internalGetParameter(\n        OMX_INDEXTYPE index, OMX_PTR params) {\n    switch ((int)index) {\n        case OMX_IndexParamAudioPortFormat:\n        {\n            OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =\n                (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;\n\n            if (!isValidOMXParam(formatParams)) {\n                return OMX_ErrorBadParameter;\n            }\n\n            if (formatParams->nPortIndex > 1) {\n                return OMX_ErrorUndefined;\n            }\n\n            if (formatParams->nIndex > 0) {\n                return OMX_ErrorNoMore;\n            }\n\n            formatParams->eEncoding =\n                (formatParams->nPortIndex == 0)\n                    ? (OMX_AUDIO_CODINGTYPE)OMX_AUDIO_CodingAndroidOPUS :\n                       OMX_AUDIO_CodingPCM;\n\n            return OMX_ErrorNone;\n        }\n\n        case OMX_IndexParamAudioAndroidOpus:\n        {\n            OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams =\n                (OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params;\n\n            if (!isValidOMXParam(opusParams)) {\n                return OMX_ErrorBadParameter;\n            }\n\n            if (opusParams->nPortIndex != 0) {\n                return OMX_ErrorUndefined;\n            }\n\n            opusParams->nAudioBandWidth = 0;\n            opusParams->nSampleRate = kRate;\n            opusParams->nBitRate = 0;\n\n            if (!isConfigured()) {\n                opusParams->nChannels = 1;\n            } else {\n                opusParams->nChannels = mHeader->channels;\n            }\n\n            return OMX_ErrorNone;\n        }\n\n        case OMX_IndexParamAudioPcm:\n        {\n            OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =\n                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;\n\n            if (!isValidOMXParam(pcmParams)) {\n                return OMX_ErrorBadParameter;\n            }\n\n            if (pcmParams->nPortIndex != 1) {\n                return OMX_ErrorUndefined;\n            }\n\n            pcmParams->eNumData = OMX_NumericalDataSigned;\n            pcmParams->eEndian = OMX_EndianBig;\n            pcmParams->bInterleaved = OMX_TRUE;\n            pcmParams->nBitPerSample = 16;\n            pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;\n            pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;\n            pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;\n            pcmParams->nSamplingRate = kRate;\n\n            if (!isConfigured()) {\n                pcmParams->nChannels = 1;\n            } else {\n                pcmParams->nChannels = mHeader->channels;\n            }\n\n            return OMX_ErrorNone;\n        }\n\n        default:\n            return SimpleSoftOMXComponent::internalGetParameter(index, params);\n    }\n}\n\nOMX_ERRORTYPE SoftOpus::internalSetParameter(\n        OMX_INDEXTYPE index, const OMX_PTR params) {\n    switch ((int)index) {\n        case OMX_IndexParamStandardComponentRole:\n        {\n            const OMX_PARAM_COMPONENTROLETYPE *roleParams =\n                (const OMX_PARAM_COMPONENTROLETYPE *)params;\n\n            if (!isValidOMXParam(roleParams)) {\n                return OMX_ErrorBadParameter;\n            }\n\n            if (strncmp((const char *)roleParams->cRole,\n                        \"audio_decoder.opus\",\n                        OMX_MAX_STRINGNAME_SIZE - 1)) {\n                return OMX_ErrorUndefined;\n            }\n\n            return OMX_ErrorNone;\n        }\n\n        case OMX_IndexParamAudioPortFormat:\n        {\n            const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =\n                (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;\n\n            if (!isValidOMXParam(formatParams)) {\n                return OMX_ErrorBadParameter;\n            }\n\n            if (formatParams->nPortIndex > 1) {\n                return OMX_ErrorUndefined;\n            }\n\n            if ((formatParams->nPortIndex == 0\n                        && formatParams->eEncoding !=\n                           (OMX_AUDIO_CODINGTYPE)OMX_AUDIO_CodingAndroidOPUS)\n                || (formatParams->nPortIndex == 1\n                        && formatParams->eEncoding != OMX_AUDIO_CodingPCM)) {\n                return OMX_ErrorUndefined;\n            }\n\n            return OMX_ErrorNone;\n        }\n\n        case OMX_IndexParamAudioAndroidOpus:\n        {\n            const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams =\n                (const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params;\n\n            if (!isValidOMXParam(opusParams)) {\n                return OMX_ErrorBadParameter;\n            }\n\n            if (opusParams->nPortIndex != 0) {\n                return OMX_ErrorUndefined;\n            }\n\n            return OMX_ErrorNone;\n        }\n\n        default:\n            return SimpleSoftOMXComponent::internalSetParameter(index, params);\n    }\n}\n\nbool SoftOpus::isConfigured() const {\n    return mInputBufferCount >= 1;\n}\n\nstatic uint16_t ReadLE16(const uint8_t *data, size_t data_size,\n                         uint32_t read_offset) {\n    if (read_offset + 1 > data_size)\n        return 0;\n    uint16_t val;\n    val = data[read_offset];\n    val |= data[read_offset + 1] << 8;\n    return val;\n}\n\n\/\/ Maximum packet size used in Xiph's opusdec.\nstatic const int kMaxOpusOutputPacketSizeSamples = 960 * 6;\n\n\/\/ Default audio output channel layout. Used to initialize |stream_map| in\n\/\/ OpusHeader, and passed to opus_multistream_decoder_create() when the header\n\/\/ does not contain mapping information. The values are valid only for mono and\n\/\/ stereo output: Opus streams with more than 2 channels require a stream map.\nstatic const int kMaxChannelsWithDefaultLayout = 2;\nstatic const uint8_t kDefaultOpusChannelLayout[kMaxChannelsWithDefaultLayout] = { 0, 1 };\n\n\/\/ Parses Opus Header. Header spec: http:\/\/wiki.xiph.org\/OggOpus#ID_Header\nstatic bool ParseOpusHeader(const uint8_t *data, size_t data_size,\n                            OpusHeader* header) {\n    \/\/ Size of the Opus header excluding optional mapping information.\n    const size_t kOpusHeaderSize = 19;\n\n    \/\/ Offset to the channel count byte in the Opus header.\n    const size_t kOpusHeaderChannelsOffset = 9;\n\n    \/\/ Offset to the pre-skip value in the Opus header.\n    const size_t kOpusHeaderSkipSamplesOffset = 10;\n\n    \/\/ Offset to the gain value in the Opus header.\n    const size_t kOpusHeaderGainOffset = 16;\n\n    \/\/ Offset to the channel mapping byte in the Opus header.\n    const size_t kOpusHeaderChannelMappingOffset = 18;\n\n    \/\/ Opus Header contains a stream map. The mapping values are in the header\n    \/\/ beyond the always present |kOpusHeaderSize| bytes of data. The mapping\n    \/\/ data contains stream count, coupling information, and per channel mapping\n    \/\/ values:\n    \/\/   - Byte 0: Number of streams.\n    \/\/   - Byte 1: Number coupled.\n    \/\/   - Byte 2: Starting at byte 2 are |header->channels| uint8 mapping\n    \/\/             values.\n    const size_t kOpusHeaderNumStreamsOffset = kOpusHeaderSize;\n    const size_t kOpusHeaderNumCoupledOffset = kOpusHeaderNumStreamsOffset + 1;\n    const size_t kOpusHeaderStreamMapOffset = kOpusHeaderNumStreamsOffset + 2;\n\n    if (data_size < kOpusHeaderSize) {\n        ALOGV(\"Header size is too small.\");\n        return false;\n    }\n    header->channels = *(data + kOpusHeaderChannelsOffset);\n\n    if (header->channels <= 0 || header->channels > kMaxChannels) {\n        ALOGV(\"Invalid Header, wrong channel count: %d\", header->channels);\n        return false;\n    }\n    header->skip_samples = ReadLE16(data, data_size,\n                                        kOpusHeaderSkipSamplesOffset);\n    header->gain_db = static_cast<int16_t>(\n                              ReadLE16(data, data_size,\n                                       kOpusHeaderGainOffset));\n    header->channel_mapping = *(data + kOpusHeaderChannelMappingOffset);\n    if (!header->channel_mapping) {\n        if (header->channels > kMaxChannelsWithDefaultLayout) {\n            ALOGV(\"Invalid Header, missing stream map.\");\n            return false;\n        }\n        header->num_streams = 1;\n        header->num_coupled = header->channels > 1;\n        header->stream_map[0] = 0;\n        header->stream_map[1] = 1;\n        return true;\n    }\n    if (data_size < kOpusHeaderStreamMapOffset + header->channels) {\n        ALOGV(\"Invalid stream map; insufficient data for current channel \"\n              \"count: %d\", header->channels);\n        return false;\n    }\n    header->num_streams = *(data + kOpusHeaderNumStreamsOffset);\n    header->num_coupled = *(data + kOpusHeaderNumCoupledOffset);\n    if (header->num_streams + header->num_coupled != header->channels) {\n        ALOGV(\"Inconsistent channel mapping.\");\n        return false;\n    }\n    for (int i = 0; i < header->channels; ++i)\n      header->stream_map[i] = *(data + kOpusHeaderStreamMapOffset + i);\n    return true;\n}\n\n\/\/ Convert nanoseconds to number of samples.\nstatic uint64_t ns_to_samples(uint64_t ns, int kRate) {\n    return static_cast<double>(ns) * kRate \/ 1000000000;\n}\n\nvoid SoftOpus::handleEOS() {\n    List<BufferInfo *> &inQueue = getPortQueue(0);\n    List<BufferInfo *> &outQueue = getPortQueue(1);\n    CHECK(!inQueue.empty() && !outQueue.empty());\n\n    BufferInfo *outInfo = *outQueue.begin();\n    OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;\n    outHeader->nFilledLen = 0;\n    outHeader->nFlags = OMX_BUFFERFLAG_EOS;\n    mHaveEOS = true;\n\n    outQueue.erase(outQueue.begin());\n    outInfo->mOwnedByUs = false;\n    notifyFillBufferDone(outHeader);\n\n    BufferInfo *inInfo = *inQueue.begin();\n    OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;\n    inQueue.erase(inQueue.begin());\n    inInfo->mOwnedByUs = false;\n    notifyEmptyBufferDone(inHeader);\n\n    ++mInputBufferCount;\n}\n\nvoid SoftOpus::onQueueFilled(OMX_U32 \/* portIndex *\/) {\n    List<BufferInfo *> &inQueue = getPortQueue(0);\n    List<BufferInfo *> &outQueue = getPortQueue(1);\n\n    if (mOutputPortSettingsChange != NONE) {\n        return;\n    }\n\n    while (!mHaveEOS && !inQueue.empty() && !outQueue.empty()) {\n        BufferInfo *inInfo = *inQueue.begin();\n        OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;\n\n        if (mInputBufferCount < 3) {\n            const uint8_t *data = inHeader->pBuffer + inHeader->nOffset;\n            size_t size = inHeader->nFilledLen;\n\n            if ((inHeader->nFlags & OMX_BUFFERFLAG_EOS) && size == 0) {\n                handleEOS();\n                return;\n            }\n\n            if (mInputBufferCount == 0) {\n                CHECK(mHeader == NULL);\n                mHeader = new OpusHeader();\n                memset(mHeader, 0, sizeof(*mHeader));\n                if (!ParseOpusHeader(data, size, mHeader)) {\n                    ALOGV(\"Parsing Opus Header failed.\");\n                    notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);\n                    return;\n                }\n\n                uint8_t channel_mapping[kMaxChannels] = {0};\n                if (mHeader->channels <= kMaxChannelsWithDefaultLayout) {\n                    memcpy(&channel_mapping,\n                           kDefaultOpusChannelLayout,\n                           kMaxChannelsWithDefaultLayout);\n                } else {\n                    memcpy(&channel_mapping,\n                           mHeader->stream_map,\n                           mHeader->channels);\n                }\n\n                int status = OPUS_INVALID_STATE;\n                mDecoder = opus_multistream_decoder_create(kRate,\n                                                           mHeader->channels,\n                                                           mHeader->num_streams,\n                                                           mHeader->num_coupled,\n                                                           channel_mapping,\n                                                           &status);\n                if (!mDecoder || status != OPUS_OK) {\n                    ALOGV(\"opus_multistream_decoder_create failed status=%s\",\n                          opus_strerror(status));\n                    notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);\n                    return;\n                }\n                status =\n                    opus_multistream_decoder_ctl(mDecoder,\n                                                 OPUS_SET_GAIN(mHeader->gain_db));\n                if (status != OPUS_OK) {\n                    ALOGV(\"Failed to set OPUS header gain; status=%s\",\n                          opus_strerror(status));\n                    notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);\n                    return;\n                }\n            } else if (mInputBufferCount == 1) {\n                mCodecDelay = ns_to_samples(\n                                  *(reinterpret_cast<int64_t*>(inHeader->pBuffer +\n                                                               inHeader->nOffset)),\n                                  kRate);\n                mSamplesToDiscard = mCodecDelay;\n            } else {\n                mSeekPreRoll = ns_to_samples(\n                                   *(reinterpret_cast<int64_t*>(inHeader->pBuffer +\n                                                                inHeader->nOffset)),\n                                   kRate);\n                notify(OMX_EventPortSettingsChanged, 1, 0, NULL);\n                mOutputPortSettingsChange = AWAITING_DISABLED;\n            }\n\n            if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {\n                handleEOS();\n                return;\n            }\n\n            inQueue.erase(inQueue.begin());\n            inInfo->mOwnedByUs = false;\n            notifyEmptyBufferDone(inHeader);\n            ++mInputBufferCount;\n\n            continue;\n        }\n\n        \/\/ Ignore CSD re-submissions.\n        if (mInputBufferCount >= 3 && (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG)) {\n            if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {\n                handleEOS();\n                return;\n            }\n\n            inQueue.erase(inQueue.begin());\n            inInfo->mOwnedByUs = false;\n            notifyEmptyBufferDone(inHeader);\n            continue;\n        }\n\n        BufferInfo *outInfo = *outQueue.begin();\n        OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;\n\n        if ((inHeader->nFlags & OMX_BUFFERFLAG_EOS) && inHeader->nFilledLen == 0) {\n            handleEOS();\n            return;\n        }\n\n        if (inHeader->nOffset == 0) {\n            mAnchorTimeUs = inHeader->nTimeStamp;\n            mNumFramesOutput = 0;\n        }\n\n        \/\/ When seeking to zero, |mCodecDelay| samples has to be discarded\n        \/\/ instead of |mSeekPreRoll| samples (as we would when seeking to any\n        \/\/ other timestamp).\n        if (inHeader->nTimeStamp == 0) {\n            mSamplesToDiscard = mCodecDelay;\n        }\n\n        const uint8_t *data = inHeader->pBuffer + inHeader->nOffset;\n        const uint32_t size = inHeader->nFilledLen;\n        size_t frameSize = kMaxOpusOutputPacketSizeSamples;\n        if (frameSize > outHeader->nAllocLen \/ sizeof(int16_t) \/ mHeader->channels) {\n            frameSize = outHeader->nAllocLen \/ sizeof(int16_t) \/ mHeader->channels;\n            android_errorWriteLog(0x534e4554, \"27833616\");\n        }\n\n        int numFrames = opus_multistream_decode(mDecoder,\n                                                data,\n                                                size,\n                                                (int16_t *)outHeader->pBuffer,\n                                                frameSize,\n                                                0);\n        if (numFrames < 0) {\n            ALOGE(\"opus_multistream_decode returned %d\", numFrames);\n            notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);\n            return;\n        }\n\n        outHeader->nOffset = 0;\n        if (mSamplesToDiscard > 0) {\n            if (mSamplesToDiscard > numFrames) {\n                mSamplesToDiscard -= numFrames;\n                numFrames = 0;\n            } else {\n                numFrames -= mSamplesToDiscard;\n                outHeader->nOffset = mSamplesToDiscard * sizeof(int16_t) *\n                                     mHeader->channels;\n                mSamplesToDiscard = 0;\n            }\n        }\n\n        outHeader->nFilledLen = numFrames * sizeof(int16_t) * mHeader->channels;\n\n        outHeader->nTimeStamp = mAnchorTimeUs +\n                                (mNumFramesOutput * 1000000ll) \/\n                                kRate;\n\n        mNumFramesOutput += numFrames;\n\n        if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {\n            outHeader->nFlags = OMX_BUFFERFLAG_EOS;\n            mHaveEOS = true;\n        } else {\n            outHeader->nFlags = 0;\n        }\n\n        inInfo->mOwnedByUs = false;\n        inQueue.erase(inQueue.begin());\n        notifyEmptyBufferDone(inHeader);\n        ++mInputBufferCount;\n\n        outInfo->mOwnedByUs = false;\n        outQueue.erase(outQueue.begin());\n        notifyFillBufferDone(outHeader);\n    }\n}\n\nvoid SoftOpus::onPortFlushCompleted(OMX_U32 portIndex) {\n    if (portIndex == 0 && mDecoder != NULL) {\n        \/\/ Make sure that the next buffer output does not still\n        \/\/ depend on fragments from the last one decoded.\n        mNumFramesOutput = 0;\n        opus_multistream_decoder_ctl(mDecoder, OPUS_RESET_STATE);\n        mAnchorTimeUs = 0;\n        mSamplesToDiscard = mSeekPreRoll;\n        mHaveEOS = false;\n    }\n}\n\nvoid SoftOpus::onReset() {\n    mInputBufferCount = 0;\n    mNumFramesOutput = 0;\n    if (mDecoder != NULL) {\n        opus_multistream_decoder_destroy(mDecoder);\n        mDecoder = NULL;\n    }\n    if (mHeader != NULL) {\n        delete mHeader;\n        mHeader = NULL;\n    }\n\n    mOutputPortSettingsChange = NONE;\n    mHaveEOS = false;\n}\n\nvoid SoftOpus::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {\n    if (portIndex != 1) {\n        return;\n    }\n\n    switch (mOutputPortSettingsChange) {\n        case NONE:\n            break;\n\n        case AWAITING_DISABLED:\n        {\n            CHECK(!enabled);\n            mOutputPortSettingsChange = AWAITING_ENABLED;\n            break;\n        }\n\n        default:\n        {\n            CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);\n            CHECK(enabled);\n            mOutputPortSettingsChange = NONE;\n            break;\n        }\n    }\n}\n\n}  \/\/ namespace android\n\nandroid::SoftOMXComponent *createSoftOMXComponent(\n        const char *name, const OMX_CALLBACKTYPE *callbacks,\n        OMX_PTR appData, OMX_COMPONENTTYPE **component) {\n    return new android::SoftOpus(name, callbacks, appData, component);\n}\n","avg_line_length":33.6468797565,"max_line_length":89,"alphanum_fraction":0.5796163937,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":22938,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":252.0,"content":"\/\/========= Copyright (c), Valve LLC, All rights reserved. ============\n\/\/\n\/\/ Purpose:\n\/\/\n\/\/ $NoKeywords: $\n\/\/=============================================================================\n\n#include \"stdafx.h\"\n#include \"gcsystemaccess.h\"\n#include \"gcjob.h\"\n#include \"gcsdk\/gcreportprinter.h\"\n\n\n\/\/ memdbgon must be the last include file in a .cpp file!!!\n#include \"tier0\/memdbgon.h\"\n\nnamespace GCSDK\n{\n\n\nstatic GCConVar gcaccess_enable( \"gcaccess_enable\", \"1\", \"Kill switch that disables all gcaccess tracking and systems\" );\n\nDECLARE_GC_EMIT_GROUP( g_EGAccess, access );\n\n\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------\nGCAccessSystem_t GenerateUniqueGCAccessID()\n{\n\tstatic GCAccessSystem_t s_nID = 0;\n\treturn s_nID++;\n}\n\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------\n\/\/ CGCAccessSystem\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------\n\n\/\/a GCAccess system that has been registered\nclass CGCAccessSystem\n{\npublic:\n\t\/\/the name of the system for display\n\tCUtlString\t\t\tm_sName;\n\t\/\/the unique ID for this system\n\tGCAccessSystem_t\tm_nID;\n\t\/\/which actions should be enabled or disabled for this system in particular\n\tuint32\t\t\t\tm_nActions;\n\tuint32\t\t\t\tm_nSuppressActions;\n\n\tstruct AccessStats_t\n\t{\n\t\tAccessStats_t();\n\t\tvoid Add( const AccessStats_t& rhs );\n\t\t\/\/how many raw accesses have we had?\n\t\tuint32\t\tm_nNumValid;\n\t\t\/\/how many failed because the context didn't have rights?\n\t\tuint32\t\tm_nNumFail;\n\t\t\/\/how many failed because the associated ID wasn't valid?\n\t\tuint32\t\tm_nNumFailID;\n\t};\n\n\tstruct TrackedJob_t\n\t{\n\t\tCUtlString\t\tm_sContext;\n\t\tAccessStats_t\tm_Stats;\n\t};\n\n\t\/\/which jobs have violated this system access rights\n\tCUtlHashMapLarge< uintp, TrackedJob_t >\tm_Jobs;\n};\n\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------\n\/\/ CGCAccessContext\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------\n\nCGCAccessContext::CGCAccessContext() :\n\tm_nActions( 0 ),\n\tm_nSuppressActions( 0 )\n{\n}\n\nvoid CGCAccessContext::Init( const char* pszName, uint32 nActions, uint32 nSuppressActions )\n{\n\tm_sName = pszName;\n\tm_nActions = nActions;\n\tm_nSuppressActions = nSuppressActions;\n}\n\nvoid CGCAccessContext::AddSystem( GCAccessSystem_t nSystem )\n{\n\tm_nSystems.InsertIfNotFound( nSystem );\n}\n\nbool CGCAccessContext::HasSystem( GCAccessSystem_t system ) const\n{\n\treturn ( m_nSystems.Find( system ) != m_nSystems.InvalidIndex() );\n}\n\nbool CGCAccessContext::IsSubsetOf( const CGCAccessContext& context ) const\n{\n\tFOR_EACH_VEC( m_nSystems, nCurrSystem )\n\t{\n\t\tif( !context.HasSystem( m_nSystems[ nCurrSystem ] ) )\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\nvoid CGCAccessContext::AddSystemsFrom( const CGCAccessContext& context )\n{\n\tFOR_EACH_VEC( context.m_nSystems, nCurrSystem )\n\t{\n\t\tAddSystem( context.m_nSystems[ nCurrSystem ] );\n\t}\n}\n\nvoid CGCAccessContext::SetAction( EGCAccessAction eAction, bool bSet )\n{\n\tif( bSet )\n\t\tm_nActions |= eAction;\n\telse\n\t\tm_nActions &= ~( uint32 )eAction;\n}\n\nvoid CGCAccessContext::SetSuppressAction( EGCAccessAction eAction, bool bSet )\n{\n\tif( bSet )\n\t\tm_nSuppressActions |= eAction;\n\telse\n\t\tm_nSuppressActions &= ~( uint32 )eAction;\n}\n\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------\n\/\/ CGCAccess\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------\n\nstatic CGCAccess g_GCAccess;\nCGCAccess& GGCAccess()\n{\n\treturn g_GCAccess;\n}\n\nCGCAccessSystem::AccessStats_t::AccessStats_t()\n\t: m_nNumFail( 0 )\n\t, m_nNumFailID( 0 )\n\t, m_nNumValid( 0 )\n{}\n\nvoid CGCAccessSystem::AccessStats_t::Add( const AccessStats_t& rhs )\n{\n\tm_nNumFail += rhs.m_nNumFail;\n\tm_nNumFailID += rhs.m_nNumFailID;\n\tm_nNumValid += rhs.m_nNumValid;\n}\n\nCGCAccess::CGCAccess() :\n\tm_nActions( GCAccessAction_TrackSuccess | GCAccessAction_TrackFail| GCAccessAction_ReturnFail ),\n\tm_nSuppressActions( 0 )\n{\n\tm_GlobalContext.Init( \"Global\" );\n}\n\nvoid CGCAccess::RegisterSystem( const char* pszName, GCAccessSystem_t nID, uint32 nActions, uint32 nSupressActions )\n{\n\t\/\/make sure that we don't have a conflict\n\tint nIndex = m_Systems.Find( nID );\n\tif( nIndex != m_Systems.InvalidIndex() )\n\t{\n\t\t\/\/ !FIXME!\n\t\t\/\/ DOTAMERGE AssertMsg varargs\n\t\tAssertMsg3( false, \"Multiple systems conflciting in Register System: ID %d, original: %s, new %s\", nID, m_Systems[ nIndex ]->m_sName.String(), pszName );\n\t\treturn;\n\t}\n\n\tCGCAccessSystem* pSystem = new CGCAccessSystem;\n\tpSystem->m_sName = pszName;\n\tpSystem->m_nID = nID;\n\tpSystem->m_nActions = nActions;\n\tpSystem->m_nSuppressActions = nSupressActions;\n\tm_Systems.Insert( nID, pSystem );\n}\n\nbool CGCAccess::ValidateAccess( GCAccessSystem_t nSystem )\n{\n\t\/\/global kill switch\n\tif( !gcaccess_enable.GetBool() )\n\t\treturn true;\n\n\treturn InternalValidateAccess( nSystem, CSteamID(), CSteamID() );\t\n}\n\nbool CGCAccess::ValidateSteamIDAccess( GCAccessSystem_t nSystem, CSteamID steamID )\n{\n\t\/\/global kill switch\n\tif( !gcaccess_enable.GetBool() )\n\t\treturn true;\n\n\tCSteamID expectedID = ( g_pJobCur ) ? g_pJobCur->SOVALIDATE_GetSteamID() : steamID;\n\treturn InternalValidateAccess( nSystem, steamID, expectedID );\t\n}\n\nbool CGCAccess::InternalValidateAccess( GCAccessSystem_t nSystem, CSteamID steamID, CSteamID expectedID )\n{\n\t\/\/see if tracking for this system is disabled. This list is almost always empty, so just use a linear search for now.\n\tFOR_EACH_VEC( m_SuppressAccess, nAction )\n\t{\n\t\tif( m_SuppressAccess[ nAction ].m_nSystem == nSystem )\n\t\t\treturn true;\n\t}\n\n\t\/\/assume the global context\n\tconst CGCAccessContext* pContext = &m_GlobalContext;\n\tconst char* pszJobName = \"[global]\";\n\n\t\/\/if we have a job, use it's context\n\tif( g_pJobCur )\n\t{\n\t\tconst CGCJob* pJob = static_cast< const CGCJob* >( g_pJobCur );\n\t\tpszJobName = pJob->GetName();\n\t\tif( pJob->GetContext() )\n\t\t\tpContext = pJob->GetContext();\n\t}\n\n\t\/\/is this a valid system to access\n\tbool bValidSteamID = ( steamID == expectedID );\n\tbool bValidSystem = pContext->HasSystem( nSystem );\n\tbool bValidAccess = ( bValidSystem && bValidSteamID );\n\n\t\/\/determine the actions we want to do for tracking\n\tuint32 nActions = pContext->GetActions() | m_nActions;\n\tuint32 nSuppressActions = pContext->GetSuppressActions() | m_nSuppressActions;\n\n\t\/\/look up the system that we are accessing\n\tCGCAccessSystem* pSystem = NULL;\n\tint nSystemIndex = m_Systems.Find( nSystem );\n\tif( nSystemIndex == m_Systems.InvalidIndex() )\n\t{\n\t\t\/\/ !FIXME! DOTAMERGE\n\t\t\/\/ AssertMsg varargs\n\t\tAssertMsg1( false, \"Error: Tracking a system that has not been registered. Make sure to register system %u\", nSystem );\n\t}\n\telse\n\t{\n\t\t\/\/make sure that we have a stat entry for this job\n\t\tpSystem = m_Systems[ nSystemIndex ];\n\t\tnActions |= pSystem->m_nActions;\n\t\tnSuppressActions |= pSystem->m_nSuppressActions;\n\t}\n\n\t\/\/remove any suppressed actions\n\tnActions &= ~nSuppressActions;\n\n\t\/\/see if we need to track this access\n\tbool bTrackSuccess = ( nActions & GCAccessAction_TrackSuccess ) && bValidAccess;\n\tbool bTrackFail    = ( nActions & GCAccessAction_TrackFail ) && !bValidAccess;\n\tif( ( bTrackSuccess || bTrackFail ) && pSystem )\n\t{\n\t\t\/\/make sure that we have a stat entry for this job\n\t\tint nJobIndex = pSystem->m_Jobs.Find( ( uintp )pszJobName );\n\t\tif( nJobIndex == pSystem->m_Jobs.InvalidIndex() )\n\t\t{\n\t\t\tnJobIndex = pSystem->m_Jobs.Insert( ( uintp )pszJobName );\n\t\t\tpSystem->m_Jobs[ nJobIndex ].m_sContext = pContext->GetName();\n\t\t}\n\t\t\n\t\t\/\/update our stats based upon what was valid and what wasn't\n\t\tCGCAccessSystem::AccessStats_t& stats = pSystem->m_Jobs[ nJobIndex ].m_Stats; \n\t\tif( bTrackSuccess )\n\t\t\tstats.m_nNumValid++;\n\n\t\tif( bTrackFail )\n\t\t{\n\t\t\tif( !bValidSteamID )\n\t\t\t\tstats.m_nNumFailID++;\n\t\t\tif( !bValidSystem )\n\t\t\t\tstats.m_nNumFail++;\n\t\t}\n\t}\n\n\t\/\/see if this is a single access we want to try and track\n\tFOR_EACH_VEC( m_SingleAsserts, nCurrAssert )\n\t{\n\t\tSingleAssert_t* pAssert = m_SingleAsserts[ nCurrAssert ];\n\t\tif( nSystem == pAssert->m_System )\n\t\t{\n\t\t\tif( V_stricmp( ( pAssert->m_bContext ) ? pContext->GetName() : pszJobName, pAssert->m_sContextOrJob ) == 0 )\n\t\t\t{\n\t\t\t\t\/\/log this assert\n\t\t\t\t{\n\t\t\t\t\t\/\/ !FIXME! DOTAMERGE\n\t\t\t\t\t\/\/CGCInterface::CDisableAssertRateLimit disableAssertLimit;\n\n\t\t\t\t\t\/\/ !FIXME! DOTAMERGE\n\t\t\t\t\t\/\/ AssertMsg varargs\n\t\t\t\t\tAssertMsg3( false, \"GCSystemAccess Caught %s (context %s) calling into %s\", pszJobName, pContext->GetName(), pSystem ? pSystem->m_sName.String() : \"unknown\" );\n\t\t\t\t}\n\n\t\t\t\t\/\/and clear it\n\t\t\t\tdelete pAssert;\n\t\t\t\tm_SingleAsserts.FastRemove( nCurrAssert );\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/at this point, if it is a valid access, just bail\n\tif( bValidAccess )\n\t\treturn true;\n\n\t\/\/otherwise, handle the failure case\n\tif( nActions & ( GCAccessAction_Msg | GCAccessAction_Assert ) )\n\t{\n\t\tint nSystemIndex = m_Systems.Find( nSystem );\n\t\tconst char* pszSystem = ( nSystemIndex != m_Systems.InvalidIndex() ) ? m_Systems[ nSystemIndex ]->m_sName.String() : \"<unregistered>\";\n\n\t\t\/\/display a message based upon if it was a system or ID violation\n\t\tCFmtStr1024 szMsg;\n\t\tif( !bValidSystem )\n\t\t{\n\t\t\tszMsg.sprintf( \"Job %s Accessed invalid system %s (%u) while in context %s\\n\", pszJobName, pszSystem, nSystem, pContext->GetName() );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tszMsg.sprintf( \"Job %s Accessed invalid steam ID %s but expected %s in system %s (%u) while in context %s\\n\", pszJobName, steamID.RenderLink(), expectedID.RenderLink(), pszSystem, nSystem, pContext->GetName() );\n\t\t}\n\n\t\tif( nActions & GCAccessAction_Msg )\n\t\t\tEG_MSG( g_EGAccess, \"%s\", szMsg.String() );\n\t\tif( nActions & GCAccessAction_Assert )\n\t\t{\n\t\t\t\/\/ !FIXME! DOTAMERGE\n\t\t\t\/\/ AssertMsg varargs\n\t\t\tAssertMsg1( false, \"%s\", szMsg.String() );\n\t\t}\n\t}\n\n\treturn !( nActions & GCAccessAction_ReturnFail );\n}\n\nvoid CGCAccess::SuppressAccess( GCAccessSystem_t nSystem, bool bEnable )\n{\n\t\/\/see if it is an existing item already suppressed that we need to modify the ref count of\n\tFOR_EACH_VEC( m_SuppressAccess, nAccess )\n\t{\n\t\tif( m_SuppressAccess[ nAccess ].m_nSystem == nSystem )\n\t\t{\n\t\t\tif( bEnable )\n\t\t\t{\n\t\t\t\t\/\/to enable, we want to decrease the disable count, or remove if we are fully re-enabled\n\t\t\t\tif( m_SuppressAccess[ nAccess ].m_nCount <= 1 )\n\t\t\t\t\tm_SuppressAccess.FastRemove( nAccess );\n\t\t\t\telse\n\t\t\t\t\tm_SuppressAccess[ nAccess ].m_nCount--;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_SuppressAccess[ nAccess ].m_nCount++;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/\/only add it to the list if we are disabling\n\tif( !bEnable )\n\t{\n\t\tSuppressAccess_t access;\n\t\taccess.m_nSystem = nSystem;\n\t\taccess.m_nCount = 1;\n\t\tm_SuppressAccess.AddToTail( access );\n\t}\n}\n\nvoid CGCAccess::ClearSystemStats()\n{\n\tFOR_EACH_MAP_FAST( m_Systems, nSystem )\n\t{\n\t\tm_Systems[ nSystem ]->m_Jobs.Purge();\n\t}\n}\n\nbool CGCAccess::CatchSingleAssert( const char* pszSystem, bool bContext, const char* pszContextOrJob )\n{\n\t\/\/find the system we are referencing so we don't add invalid breakpoints if we can avoid it\n\tGCAccessSystem_t nSystemID = ( GCAccessSystem_t )-1;\n\tFOR_EACH_MAP_FAST( m_Systems, nSystem )\n\t{\n\t\tif( V_stricmp( m_Systems[ nSystem ]->m_sName, pszSystem ) == 0 )\n\t\t{\n\t\t\tnSystemID = m_Systems.Key( nSystem );\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif( nSystemID == ( GCAccessSystem_t )-1 )\n\t\treturn false;\n\n\tSingleAssert_t* pAssert = new SingleAssert_t;\n\tpAssert->m_System\t\t\t= nSystemID;\n\tpAssert->m_bContext\t\t\t= bContext;\n\tpAssert->m_sContextOrJob\t= pszContextOrJob;\n\tm_SingleAsserts.AddToTail( pAssert );\n\treturn true;\n}\n\nvoid CGCAccess::ClearSingleAsserts()\n{\n\tm_SingleAsserts.PurgeAndDeleteElements();\n}\n\n\n\/\/given a display type and a stats object, determines if it meets the criteria\nstatic bool ShouldDisplayStats( CGCAccess::EDisplay eDisplay, const CGCAccessSystem::AccessStats_t& stats )\n{\n\tif( eDisplay == CGCAccess::eDisplay_Referenced )\n\t\treturn ( stats.m_nNumFail + stats.m_nNumFailID + stats.m_nNumValid ) > 0;\n\tif( eDisplay == CGCAccess::eDisplay_Violations )\n\t\treturn ( stats.m_nNumFail + stats.m_nNumFailID ) > 0;\n\tif( eDisplay == CGCAccess::eDisplay_IDViolations )\n\t\treturn stats.m_nNumFailID > 0;\n\n\t\/\/unknown, so just assume all\n\treturn true;\n}\n\n\nvoid CGCAccess::ReportJobs( const char* pszContext, EDisplay eDisplay ) const\n{\n\t\/\/collect all of the job stats into a single summary table\n\tCUtlHashMapLarge< uintp, CGCAccessSystem::TrackedJob_t > jobs;\n\tFOR_EACH_MAP_FAST( m_Systems, nSystem )\n\t{\n\t\tconst CGCAccessSystem* pSystem = m_Systems[ nSystem ];\n\t\tFOR_EACH_MAP_FAST( pSystem->m_Jobs, nJob )\n\t\t{\n\t\t\tconst CGCAccessSystem::TrackedJob_t& job = pSystem->m_Jobs[ nJob ];\n\t\t\t\/\/skip any contexts we don't care about\n\t\t\tif( pszContext && ( V_stricmp( pszContext, job.m_sContext ) != 0 ) )\n\t\t\t\tcontinue;\n\t\t\tif( !ShouldDisplayStats( eDisplay, job.m_Stats ) )\n\t\t\t\tcontinue;\n\n\t\t\tint nIndex = jobs.Find( pSystem->m_Jobs.Key( nJob ) );\n\t\t\tif( nIndex == jobs.InvalidIndex() )\n\t\t\t{\n\t\t\t\tnIndex = jobs.Insert( pSystem->m_Jobs.Key( nJob ) );\n\t\t\t\tjobs[ nIndex ].m_sContext = job.m_sContext;\n\t\t\t}\n\n\t\t\tjobs[ nIndex ].m_Stats.Add( job.m_Stats );\n\t\t}\n\t}\n\n\tCGCReportPrinter rp;\n\trp.AddStringColumn( \"Job\" );\n\trp.AddStringColumn( \"Context\" );\n\trp.AddIntColumn( \"Valid\", CGCReportPrinter::eSummary_Total );\n\trp.AddIntColumn( \"Invalid\", CGCReportPrinter::eSummary_Total );\n\trp.AddIntColumn( \"InvalidID\", CGCReportPrinter::eSummary_Total );\n\n\tFOR_EACH_MAP_FAST( jobs, nJob )\n\t{\n\t\trp.StrValue( ( const char* )jobs.Key( nJob ), CFmtStr( \"gcaccess_dump_job \\\"%s\\\" %d\", ( const char* )jobs.Key( nJob ), eDisplay ).String() );\n\t\trp.StrValue( jobs[ nJob ].m_sContext, CFmtStr( \"gcaccess_dump_context \\\"%s\\\" %d\", jobs[ nJob ].m_sContext.String(), eDisplay ).String() );\n\t\trp.IntValue( jobs[ nJob ].m_Stats.m_nNumValid );\n\t\trp.IntValue( jobs[ nJob ].m_Stats.m_nNumFail );\n\t\trp.IntValue( jobs[ nJob ].m_Stats.m_nNumFailID );\n\t\trp.CommitRow();\n\t}\n\n\trp.SortReport( \"Job\", false );\n\trp.PrintReport( SPEW_CONSOLE );\n}\n\nvoid CGCAccess::ReportSystems( const char* pszContext, EDisplay eDisplay ) const\n{\n\tCGCReportPrinter rp;\n\trp.AddStringColumn( \"System\" );\n\trp.AddIntColumn( \"ID\", CGCReportPrinter::eSummary_None );\n\trp.AddIntColumn( \"Jobs\", CGCReportPrinter::eSummary_None );\n\trp.AddIntColumn( \"Valid\", CGCReportPrinter::eSummary_Total );\n\trp.AddIntColumn( \"Invalid\", CGCReportPrinter::eSummary_Total );\n\trp.AddIntColumn( \"InvalidID\", CGCReportPrinter::eSummary_Total );\n\n\tFOR_EACH_MAP_FAST( m_Systems, nSystem )\n\t{\n\t\tconst CGCAccessSystem* pSystem = m_Systems[ nSystem ];\n\t\tCGCAccessSystem::AccessStats_t stats;\n\t\tFOR_EACH_MAP_FAST( pSystem->m_Jobs, nJob )\n\t\t{\n\t\t\tconst CGCAccessSystem::TrackedJob_t& job = pSystem->m_Jobs[ nJob ];\n\t\t\t\/\/skip any contexts we don't care about\n\t\t\tif( pszContext && ( V_stricmp( pszContext, job.m_sContext ) != 0 ) )\n\t\t\t\tcontinue;\t\t\n\n\t\t\tstats.Add( job.m_Stats );\n\t\t}\n\n\t\tif( !ShouldDisplayStats( eDisplay, stats ) )\n\t\t\tcontinue;\n\n\t\trp.StrValue( pSystem->m_sName, CFmtStr( \"gcaccess_dump_system \\\"%s\\\" %d\", pSystem->m_sName.String(), eDisplay ).String() );\n\t\trp.IntValue( pSystem->m_nID );\n\t\trp.IntValue( pSystem->m_Jobs.Count() );\n\t\trp.IntValue( stats.m_nNumValid );\n\t\trp.IntValue( stats.m_nNumFail );\n\t\trp.IntValue( stats.m_nNumFailID );\n\t\trp.CommitRow();\n\t}\n\n\trp.SortReport( \"System\", false );\n\trp.PrintReport( SPEW_CONSOLE );\n}\n\nvoid CGCAccess::FullReport( const char* pszSystemFilter, const char* pszContextFilter, const char* pszJobFilter, EDisplay eDisplay ) const\n{\n\tCGCReportPrinter rp;\n\trp.AddStringColumn( \"Job\" );\n\trp.AddStringColumn( \"Context\" );\n\trp.AddStringColumn( \"System\" );\n\trp.AddIntColumn( \"Valid\", CGCReportPrinter::eSummary_Total );\n\trp.AddIntColumn( \"Invalid\", CGCReportPrinter::eSummary_Total );\n\trp.AddIntColumn( \"InvalidID\", CGCReportPrinter::eSummary_Total );\n\n\tFOR_EACH_MAP_FAST( m_Systems, nSystem )\n\t{\n\t\tconst CGCAccessSystem* pSystem = m_Systems[ nSystem ];\n\t\tif( pszSystemFilter && V_stricmp( pszSystemFilter, pSystem->m_sName ) )\n\t\t\tcontinue;\n\n\t\tFOR_EACH_MAP_FAST( pSystem->m_Jobs, nJob )\n\t\t{\n\t\t\tconst CGCAccessSystem::AccessStats_t& stats = pSystem->m_Jobs[ nJob ].m_Stats; \n\t\t\tconst char* pszJob = ( const char* )pSystem->m_Jobs.Key( nJob );\n\t\t\tconst char* pszContext = ( const char* )pSystem->m_Jobs[ nJob ].m_sContext;\n\n\t\t\tif( !ShouldDisplayStats( eDisplay, stats ) )\n\t\t\t\tcontinue;\t\t\t\n\t\t\tif( pszJobFilter && V_stricmp( pszJobFilter, pszJob ) )\n\t\t\t\tcontinue;\n\t\t\tif( pszContextFilter && V_stricmp( pszContextFilter, pszContext ) )\n\t\t\t\tcontinue;\n\n\t\t\trp.StrValue( pszJob, CFmtStr( \"gcaccess_dump_job \\\"%s\\\" %d\", pszJob, eDisplay ).String() );\n\t\t\trp.StrValue( pszContext, CFmtStr( \"gcaccess_dump_context \\\"%s\\\" %d\", pszContext, eDisplay ).String() );\n\t\t\trp.StrValue( pSystem->m_sName, CFmtStr( \"gcaccess_dump_system \\\"%s\\\" %d\", pSystem->m_sName.String(), eDisplay ).String() );\n\t\t\trp.IntValue( stats.m_nNumValid );\n\t\t\trp.IntValue( stats.m_nNumFail );\n\t\t\trp.IntValue( stats.m_nNumFailID );\n\t\t\trp.CommitRow();\n\t\t}\n\t}\n\n\trp.SortReport( \"Context\", false );\n\trp.PrintReport( SPEW_CONSOLE );\n}\n\nvoid CGCAccess::DependencyReport( const char* pszSystem, EDisplay eDisplay ) const\n{\n\t\/\/first off, we need to find the system we are scanning for dependencies on\n\tconst CGCAccessSystem* pMatchSystem = NULL;\n\tFOR_EACH_MAP_FAST( m_Systems, nSystem )\n\t{\n\t\tconst CGCAccessSystem* pSystem = m_Systems[ nSystem ];\n\t\tif( V_stricmp( pszSystem, pSystem->m_sName ) == 0 )\n\t\t{\n\t\t\tpMatchSystem = pSystem;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif( !pMatchSystem )\n\t{\n\t\tEG_MSG( SPEW_CONSOLE, \"Unable to find system %s for dependency report\\n\", pszSystem );\n\t\treturn;\n\t}\n\n\t\/\/now generate our report\n\tCGCReportPrinter rp;\n\trp.AddStringColumn( \"Job\" );\n\trp.AddStringColumn( \"Context\" );\n\trp.AddStringColumn( \"System\" );\n\trp.AddIntColumn( \"Valid\", CGCReportPrinter::eSummary_Total );\n\trp.AddIntColumn( \"Invalid\", CGCReportPrinter::eSummary_Total );\n\trp.AddIntColumn( \"InvalidID\", CGCReportPrinter::eSummary_Total );\n\n\tFOR_EACH_MAP_FAST( m_Systems, nSystem )\n\t{\n\t\tconst CGCAccessSystem* pSystem = m_Systems[ nSystem ];\n\t\t\/\/skip ourself\n\t\tif( pSystem == pMatchSystem )\n\t\t\tcontinue;\n\n\t\tFOR_EACH_MAP_FAST( pSystem->m_Jobs, nJob )\n\t\t{\n\t\t\tconst CGCAccessSystem::AccessStats_t& stats = pSystem->m_Jobs[ nJob ].m_Stats; \n\t\t\tconst char* pszJob = ( const char* )pSystem->m_Jobs.Key( nJob );\n\t\t\tconst char* pszContext = ( const char* )pSystem->m_Jobs[ nJob ].m_sContext;\n\n\t\t\t\/\/skip any job that isn't using our match system\n\t\t\tif( !pMatchSystem->m_Jobs.HasElement( ( uintp )pszJob ) )\n\t\t\t\tcontinue;\n\t\t\tif( !ShouldDisplayStats( eDisplay, stats ) )\n\t\t\t\tcontinue;\t\n\n\t\t\trp.StrValue( pszJob, CFmtStr( \"gcaccess_dump_job \\\"%s\\\" %d\", pszJob, eDisplay ).String() );\n\t\t\trp.StrValue( pszContext, CFmtStr( \"gcaccess_dump_context \\\"%s\\\" %d\", pszContext, eDisplay ).String() );\n\t\t\trp.StrValue( pSystem->m_sName, CFmtStr( \"gcaccess_dump_system \\\"%s\\\" %d\", pSystem->m_sName.String(), eDisplay ).String() );\n\t\t\trp.IntValue( stats.m_nNumValid );\n\t\t\trp.IntValue( stats.m_nNumFail );\n\t\t\trp.IntValue( stats.m_nNumFailID );\n\t\t\trp.CommitRow();\n\t\t}\n\t}\n\n\trp.SortReport( \"System\", false );\n\trp.PrintReport( SPEW_CONSOLE );\n\n\n}\n\nGC_CON_COMMAND_PARAMS( gcaccess_dump_job, 1, \"<Job Name> Dumps all of the accesses associated with the specified job\" )\n{\n\tCGCAccess::EDisplay eDisplay = ( args.ArgC() >= 3 ) ? ( CGCAccess::EDisplay )V_atoi( args[ 2 ] ) : CGCAccess::eDisplay_Referenced;\n\tGGCAccess().FullReport( NULL, NULL, args[ 1 ], eDisplay );\n}\n\nGC_CON_COMMAND_PARAMS( gcaccess_dump_context, 1, \"<Job Name> Dumps all of the accesses associated with the specified context\" )\n{\n\tCGCAccess::EDisplay eDisplay = ( args.ArgC() >= 3 ) ? ( CGCAccess::EDisplay )V_atoi( args[ 2 ] ) : CGCAccess::eDisplay_Referenced;\n\tGGCAccess().FullReport( NULL, args[ 1 ], NULL, eDisplay );\n}\n\nGC_CON_COMMAND_PARAMS( gcaccess_dump_system, 1, \"<Job Name> Dumps all of the accesses associated with the specified system\" )\n{\n\tCGCAccess::EDisplay eDisplay = ( args.ArgC() >= 3 ) ? ( CGCAccess::EDisplay )V_atoi( args[ 2 ] ) : CGCAccess::eDisplay_Referenced;\n\tGGCAccess().FullReport( args[ 1 ], NULL, NULL, eDisplay );\n}\n\nGC_CON_COMMAND_PARAMS( gcaccess_dump_context_jobs, 1, \"<Context Name> Dumps all of the accesses associated with the specified context\" )\n{\n\tCGCAccess::EDisplay eDisplay = ( args.ArgC() >= 3 ) ? ( CGCAccess::EDisplay )V_atoi( args[ 2 ] ) : CGCAccess::eDisplay_Referenced;\n\tGGCAccess().ReportJobs( args[ 1 ], eDisplay );\n}\n\nGC_CON_COMMAND_PARAMS( gcaccess_dump_context_systems, 1, \"<Context Name> Dumps all of the accesses associated with the specified context\" )\n{\n\tCGCAccess::EDisplay eDisplay = ( args.ArgC() >= 3 ) ? ( CGCAccess::EDisplay )V_atoi( args[ 2 ] ) : CGCAccess::eDisplay_Referenced;\n\tGGCAccess().ReportSystems( args[ 1 ], eDisplay );\n}\n\nGC_CON_COMMAND_PARAMS( gcaccess_dump_system_dependencies, 1, \"<System Name> This will dump out for all jobs that reference the specified system, what other systems they reference\" )\n{\n\tCGCAccess::EDisplay eDisplay = ( args.ArgC() >= 3 ) ? ( CGCAccess::EDisplay )V_atoi( args[ 2 ] ) : CGCAccess::eDisplay_Referenced;\n\tGGCAccess().DependencyReport( args[ 1 ], eDisplay );\n}\n\nGC_CON_COMMAND( gcaccess_dump_jobs, \"Dumps all the jobs that have been tracked with the gcaccess system as well as count of violations\" )\n{\n\tCGCAccess::EDisplay eDisplay = ( args.ArgC() >= 2 ) ? ( CGCAccess::EDisplay )V_atoi( args[ 1 ] ) : CGCAccess::eDisplay_Referenced;\n\tGGCAccess().ReportJobs( NULL, eDisplay);\n}\n\nGC_CON_COMMAND( gcaccess_dump_systems, \"Dumps all the systems that have been tracked with the gcaccess system as well as count of violations\" )\n{\n\tCGCAccess::EDisplay eDisplay = ( args.ArgC() >= 2 ) ? ( CGCAccess::EDisplay )V_atoi( args[ 1 ] ) : CGCAccess::eDisplay_Referenced;\n\tGGCAccess().ReportSystems( NULL, eDisplay );\n}\n\nGC_CON_COMMAND( gcaccess_dump_full, \"Dumps all the information tracked by the gcaccess\" )\n{\n\tCGCAccess::EDisplay eDisplay = ( args.ArgC() >= 2 ) ? ( CGCAccess::EDisplay )V_atoi( args[ 1 ] ) : CGCAccess::eDisplay_Referenced;\n\tGGCAccess().FullReport( NULL, NULL, NULL, eDisplay );\n}\n\nGC_CON_COMMAND_PARAMS( gcaccess_catch_context, 2, \"<system> <context> - Catches and generates an assert when the specified context calls into the provided system. This will only generate a single assert\" )\n{\n\tif( !GGCAccess().CatchSingleAssert( args[ 1 ], true, args[ 2 ] ) )\n\t\tEG_MSG( SPEW_CONSOLE, \"Unable to register catch, likely \\'%s\\' is not a valid system.\", args[ 1 ] );\n}\n\nGC_CON_COMMAND_PARAMS( gcaccess_catch_job, 2, \"<system> <job> - Catches and generates an assert when the specified job calls into the provided system. This will only generate a single assert\" )\n{\n\tif( !GGCAccess().CatchSingleAssert( args[ 1 ], false, args[ 2 ] ) )\n\t\tEG_MSG( SPEW_CONSOLE, \"Unable to register catch, likely \\'%s\\' is not a valid system.\", args[ 1 ] );\n}\n\nGC_CON_COMMAND( gcaccess_catch_clear, \"Clears all previously specified catches\" )\n{\n\tGGCAccess().ClearSingleAsserts();\n}\n\n} \/\/namespace GCSDK\n","avg_line_length":33.1953690304,"max_line_length":214,"alphanum_fraction":0.6829714884,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3620,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":3.0,"content":"\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrCopySurfaceOp.h\"\n\n#include \"GrGpu.h\"\n#include \"GrMemoryPool.h\"\n#include \"GrRecordingContext.h\"\n#include \"GrRecordingContextPriv.h\"\n\n\/\/ returns true if the read\/written rect intersects the src\/dst and false if not.\nstatic bool clip_src_rect_and_dst_point(const GrSurfaceProxy* dst,\n                                        const GrSurfaceProxy* src,\n                                        const SkIRect& srcRect,\n                                        const SkIPoint& dstPoint,\n                                        SkIRect* clippedSrcRect,\n                                        SkIPoint* clippedDstPoint) {\n    *clippedSrcRect = srcRect;\n    *clippedDstPoint = dstPoint;\n\n    \/\/ clip the left edge to src and dst bounds, adjusting dstPoint if necessary\n    if (clippedSrcRect->fLeft < 0) {\n        clippedDstPoint->fX -= clippedSrcRect->fLeft;\n        clippedSrcRect->fLeft = 0;\n    }\n    if (clippedDstPoint->fX < 0) {\n        clippedSrcRect->fLeft -= clippedDstPoint->fX;\n        clippedDstPoint->fX = 0;\n    }\n\n    \/\/ clip the top edge to src and dst bounds, adjusting dstPoint if necessary\n    if (clippedSrcRect->fTop < 0) {\n        clippedDstPoint->fY -= clippedSrcRect->fTop;\n        clippedSrcRect->fTop = 0;\n    }\n    if (clippedDstPoint->fY < 0) {\n        clippedSrcRect->fTop -= clippedDstPoint->fY;\n        clippedDstPoint->fY = 0;\n    }\n\n    \/\/ clip the right edge to the src and dst bounds.\n    if (clippedSrcRect->fRight > src->width()) {\n        clippedSrcRect->fRight = src->width();\n    }\n    if (clippedDstPoint->fX + clippedSrcRect->width() > dst->width()) {\n        clippedSrcRect->fRight = clippedSrcRect->fLeft + dst->width() - clippedDstPoint->fX;\n    }\n\n    \/\/ clip the bottom edge to the src and dst bounds.\n    if (clippedSrcRect->fBottom > src->height()) {\n        clippedSrcRect->fBottom = src->height();\n    }\n    if (clippedDstPoint->fY + clippedSrcRect->height() > dst->height()) {\n        clippedSrcRect->fBottom = clippedSrcRect->fTop + dst->height() - clippedDstPoint->fY;\n    }\n\n    \/\/ The above clipping steps may have inverted the rect if it didn't intersect either the src or\n    \/\/ dst bounds.\n    return !clippedSrcRect->isEmpty();\n}\n\nstd::unique_ptr<GrOp> GrCopySurfaceOp::Make(GrRecordingContext* context,\n                                            GrSurfaceProxy* dstProxy,\n                                            GrSurfaceProxy* srcProxy,\n                                            const SkIRect& srcRect,\n                                            const SkIPoint& dstPoint) {\n    SkASSERT(dstProxy);\n    SkASSERT(srcProxy);\n    SkIRect clippedSrcRect;\n    SkIPoint clippedDstPoint;\n    \/\/ If the rect is outside the srcProxy or dstProxy then we've already succeeded.\n    if (!clip_src_rect_and_dst_point(dstProxy, srcProxy, srcRect, dstPoint,\n                                     &clippedSrcRect, &clippedDstPoint)) {\n        return nullptr;\n    }\n    if (GrPixelConfigIsCompressed(dstProxy->config())) {\n        return nullptr;\n    }\n\n    GrOpMemoryPool* pool = context->priv().opMemoryPool();\n\n    return pool->allocate<GrCopySurfaceOp>(dstProxy, srcProxy, clippedSrcRect, clippedDstPoint);\n}\n\nvoid GrCopySurfaceOp::onExecute(GrOpFlushState* state, const SkRect& chainBounds) {\n    if (!fSrc.get()->instantiate(state->resourceProvider())) {\n        return;\n    }\n\n    state->commandBuffer()->copy(fSrc.get()->peekSurface(), fSrc.get()->origin(), fSrcRect,\n                                 fDstPoint);\n}\n","avg_line_length":37.3195876289,"max_line_length":99,"alphanum_fraction":0.6005524862,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4285,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-4-Clause","BSD-3-Clause"],"max_stars_count":83.0,"content":"\/*        D I M E N S I O N A L E X P O N E N T S . C P P\n * BRL-CAD\n *\n * Copyright (c) 1994-2021 United States Government as represented by\n * the U.S. Army Research Laboratory.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this file; see the file named COPYING for more\n * information.\n *\/\n\/** @file DimensionalExponents.cpp\n *\n * Routines to convert STEP \"DimensionalExponents\" to BRL-CAD BREP\n * structures.\n *\n *\/\n\n#include \"STEPWrapper.h\"\n#include \"Factory.h\"\n\n#include \"DimensionalExponents.h\"\n\n#define CLASSNAME \"DimensionalExponents\"\n#define ENTITYNAME \"Dimensional_Exponents\"\nstring DimensionalExponents::entityname = Factory::RegisterClass(ENTITYNAME, (FactoryMethod)DimensionalExponents::Create);\n\nDimensionalExponents::DimensionalExponents()\n{\n    step = NULL;\n    id = 0;\n    length_exponent = 0.0;\n    mass_exponent = 0.0;\n    time_exponent = 0.0;\n    electric_current_exponent = 0.0;\n    thermodynamic_temperature_exponent = 0.0;\n    amount_of_substance_exponent = 0.0;\n    luminous_intensity_exponent = 0.0;\n}\n\nDimensionalExponents::DimensionalExponents(STEPWrapper *sw, int step_id)\n{\n    step = sw;\n    id = step_id;\n    length_exponent = 0.0;\n    mass_exponent = 0.0;\n    time_exponent = 0.0;\n    electric_current_exponent = 0.0;\n    thermodynamic_temperature_exponent = 0.0;\n    amount_of_substance_exponent = 0.0;\n    luminous_intensity_exponent = 0.0;\n}\n\nDimensionalExponents::~DimensionalExponents()\n{\n}\n\nbool\nDimensionalExponents::Load(STEPWrapper *sw, SDAI_Application_instance *sse)\n{\n    step = sw;\n    id = sse->STEPfile_id;\n\n    \/\/ need to do this for local attributes to makes sure we have\n    \/\/ the actual entity and not a complex\/supertype parent\n    sse = step->getEntity(sse, ENTITYNAME);\n\n    length_exponent = step->getRealAttribute(sse, \"length_exponent\");\n    mass_exponent = step->getRealAttribute(sse, \"mass_exponent\");\n    time_exponent = step->getRealAttribute(sse, \"time_exponent\");\n    electric_current_exponent = step->getRealAttribute(sse, \"electric_current_exponent\");\n    thermodynamic_temperature_exponent = step->getRealAttribute(sse, \"thermodynamic_temperature_exponent\");\n    amount_of_substance_exponent = step->getRealAttribute(sse, \"amount_of_substance_exponent\");\n    luminous_intensity_exponent = step->getRealAttribute(sse, \"luminous_intensity_exponent\");\n\n    sw->entity_status[id] = STEP_LOADED;\n\n    return true;\n}\n\nvoid\nDimensionalExponents::Print(int level)\n{\n    TAB(level);\n    std::cout << CLASSNAME << \":\" << \"(\";\n    std::cout << \"ID:\" << STEPid() << \")\" << std::endl;\n\n    TAB(level);\n    std::cout << \"Local Attributes:\" << std::endl;\n    TAB(level + 1);\n    std::cout << \"length_exponent:\" << length_exponent << std::endl;\n    TAB(level + 1);\n    std::cout << \"mass_exponent:\" << mass_exponent << std::endl;\n    TAB(level + 1);\n    std::cout << \"time_exponent:\" << time_exponent << std::endl;\n    TAB(level + 1);\n    std::cout << \"electric_current_exponent:\" << electric_current_exponent << std::endl;\n    TAB(level + 1);\n    std::cout << \"thermodynamic_temperature_exponent:\" << thermodynamic_temperature_exponent << std::endl;\n    TAB(level + 1);\n    std::cout << \"amount_of_substance_exponent:\" << amount_of_substance_exponent << std::endl;\n    TAB(level + 1);\n    std::cout << \"luminous_intensity_exponent:\" << luminous_intensity_exponent << std::endl;\n}\n\nSTEPEntity *\nDimensionalExponents::GetInstance(STEPWrapper *sw, int id)\n{\n    return new DimensionalExponents(sw, id);\n}\n\nSTEPEntity *\nDimensionalExponents::Create(STEPWrapper *sw, SDAI_Application_instance *sse)\n{\n    return STEPEntity::CreateEntity(sw, sse, GetInstance, CLASSNAME);\n}\n\n\/\/ Local Variables:\n\/\/ tab-width: 8\n\/\/ mode: C++\n\/\/ c-basic-offset: 4\n\/\/ indent-tabs-mode: t\n\/\/ c-file-style: \"stroustrup\"\n\/\/ End:\n\/\/ ex: shiftwidth=4 tabstop=8\n","avg_line_length":31.9776119403,"max_line_length":122,"alphanum_fraction":0.7108518086,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2903,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/\/\/ @file       test\/rational-test.cpp\n\/\/\/ @brief      Test-cases for vnix::rat::rational.\n\/\/\/ @copyright  2019 Thomas E. Vaughan; all rights reserved.\n\/\/\/ @license    BSD three-clause; see LICENSE.\n\n#include \"..\/vnix\/rat.hpp\"\n#include \"catch.hpp\"\n#include <sstream> \/\/ for ostringstream\n\nusing namespace vnix;\n\n\nTEST_CASE(\"Constructor from num and den works as expected.\", \"[rational]\") {\n  rat8_t constexpr r1;\n  REQUIRE(!r1.to_bool());\n  REQUIRE(r1.to_int() == 0);\n  REQUIRE(r1.to_float() == 0);\n  REQUIRE(r1.to_double() == 0);\n\n  rat8_t constexpr r2(3);\n  REQUIRE(r2.to_bool());\n  REQUIRE(r2.to_int() == 3);\n  REQUIRE(r2.to_float() == 3);\n  REQUIRE(r2.to_double() == 3);\n\n  rat8_t constexpr r3(3, 2);\n  REQUIRE(r3.to_bool());\n  REQUIRE_THROWS(r3.to_int());\n  REQUIRE(r3.to_float() == 1.5);\n  REQUIRE(r3.to_double() == 1.5);\n\n  rat8_t constexpr r4(4, -4);\n  REQUIRE(r4.to_bool());\n  REQUIRE(r4.to_int() == -1);\n  REQUIRE(r4.to_float() == -1);\n  REQUIRE(r4.to_double() == -1);\n}\n\n\nTEST_CASE(\"Conversion-constructor works as expected.\", \"[rational]\") {\n  rat8_t constexpr r1(3, 2);\n  rat16_t constexpr r2(r1);\n  REQUIRE(r2.to_double() == 1.5);\n  REQUIRE(r1 == r2);\n}\n\n\nTEST_CASE(\"Addition and subtraction work.\", \"[rational]\") {\n  rat8_t  r1(3, 2);\n  rat16_t r1a(1);\n  r1 += r1a;\n  REQUIRE(r1 == rat8_t(5, 2));\n  rat32_t r1s(1);\n  r1 -= r1s;\n  REQUIRE(r1 == rat8_t(3, 2));\n  rat16_t constexpr r2(-3, 4);\n  rat16_t constexpr r3(1, 6);\n  REQUIRE(r2 + r3 == rat16_t(-7, 12));\n  REQUIRE(r2 - r3 == rat16_t(-11, 12));\n}\n\n\nTEST_CASE(\"Reciprocal works as expected.\", \"[rational]\") {\n  rat8_t r1(-3, 2);\n  rat8_t r2(2, 3);\n  REQUIRE(r1.reciprocal() == -r2);\n  REQUIRE_NOTHROW(rat8_t(8).reciprocal());\n  REQUIRE_THROWS(rat8_t(9).reciprocal());\n}\n\n\nTEST_CASE(\"Multiplication and division work.\", \"[rational]\") {\n  rat8_t r1(-3, 2);\n  rat8_t r2(-1, 4);\n  REQUIRE(r1 * r2 == rat8_t(3, 8));\n  REQUIRE(r1 \/ r2 == rat8_t(6));\n  rat8_t r1m(1, 2);\n  r1 *= r1m;\n  REQUIRE(r1 == rat8_t(-3, 4));\n  rat8_t r1d(2, 3);\n  r1 \/= r1d;\n  REQUIRE(r1 == rat8_t(-9, 8));\n}\n\n\nTEST_CASE(\"Encoding and decoding work as expected.\", \"[rational]\") {\n  rat8_t  r1(-3, 4);\n  uint8_t code = 0xE8 | 0x03;\n  REQUIRE(rat8_t::encode(r1) == code);\n  REQUIRE(rat8_t::decode(code) == r1);\n}\n\n\nTEST_CASE(\"Comparison operators work as expected.\", \"[rational]\") {\n  rat8_t r1(1, 2);\n  rat8_t r2(-3, 8);\n  REQUIRE(r1 == r1);\n  REQUIRE(r1 != r2);\n  REQUIRE(r1 >= r1);\n  REQUIRE(r1 >= r2);\n  REQUIRE(r1 > r2);\n  REQUIRE(r2 <= r1);\n  REQUIRE(r2 < r1);\n}\n\n\nTEST_CASE(\"Unary operators work as expected.\", \"[rational]\") {\n  rat8_t r1(4, 6);\n  rat8_t r2(-2, 3);\n  REQUIRE(r1 == +r1);\n  REQUIRE(r1 == -r2);\n}\n\n\nTEST_CASE(\"Stream-output works as expected.\", \"[rational]\") {\n  rat8_t             r1 = 4;\n  rat8_t             r2(-6, 8);\n  std::ostringstream oss1, oss2;\n  oss1 << r1;\n  oss2 << r2;\n  REQUIRE(oss1.str() == \"4\");\n  REQUIRE(oss2.str() == \"-3\/4\");\n}\n","avg_line_length":23.4112903226,"max_line_length":76,"alphanum_fraction":0.6048914916,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4952,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":52.0,"content":"\/\/ Copyright (c) 2019 The PIVX Developers\n\/\/ Copyright (c) 2020 The PIVX Developers\n\/\/ Copyright (c) 2020 The DogeCash Developers\n\n\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"qt\/dogecash\/settings\/settingswalletrepairwidget.h\"\n#include \"qt\/dogecash\/settings\/forms\/ui_settingswalletrepairwidget.h\"\n#include \"qt\/dogecash\/qtutils.h\"\n\nSettingsWalletRepairWidget::SettingsWalletRepairWidget(DOGECGUI* _window, QWidget *parent) :\n    PWidget(_window, parent),\n    ui(new Ui::SettingsWalletRepairWidget)\n{\n    ui->setupUi(this);\n    this->setStyleSheet(parent->styleSheet());\n\n    \/\/ Containers\n    ui->left->setProperty(\"cssClass\", \"container\");\n    ui->left->setContentsMargins(10,10,10,10);\n    ui->scrollStack->setProperty(\"cssClass\", \"container\");\n\n    \/\/ Title\n    ui->labelTitle->setText(tr(\"Wallet Repair\"));\n    ui->labelTitle->setProperty(\"cssClass\", \"text-title-screen\");\n    ui->labelSubtitle1->setProperty(\"cssClass\", \"text-subtitle\");\n\n    \/\/ Labels\n    setCssProperty({ui->labelMessageSalvage, ui->labelMessageRescan, ui->labelMessageRecover1,\n                    ui->labelMessageRecover2, ui->labelMessageUpgrade, ui->labelMessageRebuild,\n                    ui->labelMessageDelete}, \"text-main-settings\");\n\n    \/\/ Buttons\n    setCssProperty({ui->pushButtonSalvage, ui->pushButtonRescan, ui->pushButtonRecover1,\n                    ui->pushButtonRecover2, ui->pushButtonUpgrade, ui->pushButtonRebuild,\n                    ui->pushButtonDelete}, \"btn-primary\");\n\n    \/\/ Wallet Repair Buttons\n    connect(ui->pushButtonSalvage, &QPushButton::clicked, this, &SettingsWalletRepairWidget::walletSalvage);\n    connect(ui->pushButtonRescan, &QPushButton::clicked, this, &SettingsWalletRepairWidget::walletRescan);\n    connect(ui->pushButtonRecover1, &QPushButton::clicked, this, &SettingsWalletRepairWidget::walletZaptxes1);\n    connect(ui->pushButtonRecover2, &QPushButton::clicked, this, &SettingsWalletRepairWidget::walletZaptxes2);\n    connect(ui->pushButtonUpgrade, &QPushButton::clicked, this, &SettingsWalletRepairWidget::walletUpgrade);\n    connect(ui->pushButtonRebuild, &QPushButton::clicked, this, &SettingsWalletRepairWidget::walletReindex);\n    connect(ui->pushButtonDelete, &QPushButton::clicked, this, &SettingsWalletRepairWidget::walletResync);\n}\n\n\/** Restart wallet with \"-salvagewallet\" *\/\nvoid SettingsWalletRepairWidget::walletSalvage()\n{\n    buildParameterlist(SALVAGEWALLET);\n}\n\n\/** Restart wallet with \"-rescan\" *\/\nvoid SettingsWalletRepairWidget::walletRescan()\n{\n    buildParameterlist(RESCAN);\n}\n\n\/** Restart wallet with \"-zapwallettxes=1\" *\/\nvoid SettingsWalletRepairWidget::walletZaptxes1()\n{\n    buildParameterlist(ZAPTXES1);\n}\n\n\/** Restart wallet with \"-zapwallettxes=2\" *\/\nvoid SettingsWalletRepairWidget::walletZaptxes2()\n{\n    buildParameterlist(ZAPTXES2);\n}\n\n\/** Restart wallet with \"-upgradewallet\" *\/\nvoid SettingsWalletRepairWidget::walletUpgrade()\n{\n    buildParameterlist(UPGRADEWALLET);\n}\n\n\/** Restart wallet with \"-reindex\" *\/\nvoid SettingsWalletRepairWidget::walletReindex()\n{\n    buildParameterlist(REINDEX);\n}\n\n\/** Restart wallet with \"-resync\" *\/\nvoid SettingsWalletRepairWidget::walletResync()\n{\n    QString resyncWarning = tr(\"This will delete your local blockchain folders and the wallet will synchronize the complete Blockchain from scratch.<br \/><br \/>\");\n    resyncWarning +=   tr(\"This needs quite some time and downloads a lot of data.<br \/><br \/>\");\n    resyncWarning +=   tr(\"Your transactions and funds will be visible again after the download has completed.<br \/><br \/>\");\n    resyncWarning +=   tr(\"Do you want to continue?.<br \/>\");\n    QMessageBox::StandardButton retval = QMessageBox::question(this, tr(\"Confirm resync Blockchain\"),\n                                                               resyncWarning,\n                                                               QMessageBox::Yes | QMessageBox::Cancel,\n                                                               QMessageBox::Cancel);\n\n    if (retval != QMessageBox::Yes) {\n        \/\/ Resync canceled\n        return;\n    }\n\n    \/\/ Restart and resync\n    buildParameterlist(RESYNC);\n}\n\n\/** Build command-line parameter list for restart *\/\nvoid SettingsWalletRepairWidget::buildParameterlist(QString arg)\n{\n    \/\/ Get command-line arguments and remove the application name\n    QStringList args = QApplication::arguments();\n    args.removeFirst();\n\n    \/\/ Remove existing repair-options\n    args.removeAll(SALVAGEWALLET);\n    args.removeAll(RESCAN);\n    args.removeAll(ZAPTXES1);\n    args.removeAll(ZAPTXES2);\n    args.removeAll(UPGRADEWALLET);\n    args.removeAll(REINDEX);\n\n    \/\/ Append repair parameter to command line.\n    args.append(arg);\n\n    \/\/ Send command-line arguments to DOGECGUI::handleRestart()\n    Q_EMIT handleRestart(args);\n}\n\nSettingsWalletRepairWidget::~SettingsWalletRepairWidget()\n{\n    delete ui;\n}\n","avg_line_length":37.2330827068,"max_line_length":163,"alphanum_fraction":0.7009289176,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":138,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":17.0,"content":"#include <cstdio>\nusing namespace std;\n\nint main() {\n\tint v, t;\n\twhile (scanf(\"%d %d\", &v, &t) != EOF) printf(\"%d\\n\", 2*v*t);\n\treturn 0;\n}","avg_line_length":17.25,"max_line_length":61,"alphanum_fraction":0.5579710145,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":930,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"#include <stdio.h>\n#include <math.h>\n#include <iostream>\nusing namespace std;\n\nlong long DP[205][11][21];\nint d[205];\n\n#define mod(a,b) ((a)%(b)<0?(a)%(b)+(b):(a)%(b))\n\nint main(){\n    int N,Q,D,M,cse=1,qi,cnt,s,i;\n\n    while(scanf(\"%d%d\",&N,&Q)==2 && (N||Q))\n    {\n        for(i=0;i<N;i++)\n            cin>>d[i];\n\n        for(i=0;i<=N;i++)\n            for(s=0;s<21;s++)\n                DP[i][0][s]=(s==0?1:0);\n\n        printf(\"SET %d:\\n\",cse++);\n        for(qi=1;qi<=Q;qi++){\n            scanf(\"%d%d\",&D,&M);\n\n            for(cnt=1;cnt<=M;cnt++)\n                for(s=0;s<D;s++)\n                    DP[N][cnt][s]=0;\n\n            for(i=N-1;i>=0;i--)\n                for(cnt=1;cnt<=M;cnt++)\n                    for(s=0;s<D;s++)\n                        DP[i][cnt][s]=    DP[i+1][cnt-1][mod(s+d[i],D)]+\n                                        DP[i+1][cnt][s];\n\n            printf(\"QUERY %d: %lli\\n\",qi,DP[0][M][0]);\n        }\n    }\n}","avg_line_length":23.25,"max_line_length":72,"alphanum_fraction":0.3537634409,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":65170,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Licensed to the .NET Foundation under one or more agreements.\n\/\/ The .NET Foundation licenses this file to you under the MIT license.\n\n\n\/****************************************************************************\/\n\/*                              gccover.cpp                                 *\/\n\/****************************************************************************\/\n\n\/* This file holds code that is designed to test GC pointer tracking in\n   fully interruptible code.  We basically do a GC everywhere we can in\n   jitted code\n *\/\n\/****************************************************************************\/\n\n\n#include \"common.h\"\n\n#ifdef HAVE_GCCOVER\n\n#pragma warning(disable:4663)\n\n#include \"eeconfig.h\"\n#include \"gms.h\"\n#include \"utsem.h\"\n#include \"gccover.h\"\n#include \"virtualcallstub.h\"\n#include \"threadsuspend.h\"\n\n#if defined(TARGET_AMD64) || defined(TARGET_ARM)\n#include \"gcinfodecoder.h\"\n#endif\n\n#include \"disassembler.h\"\n\n\/****************************************************************************\/\n\nMethodDesc* AsMethodDesc(size_t addr);\nstatic PBYTE getTargetOfCall(PBYTE instrPtr, PCONTEXT regs, PBYTE*nextInstr);\n#if defined(TARGET_ARM) || defined(TARGET_ARM64)\nstatic void replaceSafePointInstructionWithGcStressInstr(UINT32 safePointOffset, LPVOID codeStart);\nstatic bool replaceInterruptibleRangesWithGcStressInstr (UINT32 startOffset, UINT32 stopOffset, LPVOID codeStart);\n#endif\n\n\/\/ There is a call target instruction, try to find the MethodDesc for where target points to.\n\/\/ Returns nullptr if it can't find it.\nstatic MethodDesc* getTargetMethodDesc(PCODE target)\n{\n    MethodDesc* targetMD = ExecutionManager::GetCodeMethodDesc(target);\n    if (targetMD != nullptr)\n    {\n        \/\/ It is JIT\/NGened call.\n        return targetMD;\n    }\n\n    VirtualCallStubManager::StubKind vsdStubKind = VirtualCallStubManager::SK_UNKNOWN;\n    VirtualCallStubManager *pVSDStubManager = VirtualCallStubManager::FindStubManager(target, &vsdStubKind);\n    if (vsdStubKind != VirtualCallStubManager::SK_BREAKPOINT && vsdStubKind != VirtualCallStubManager::SK_UNKNOWN)\n    {\n        \/\/ It is a VSD stub manager.\n        DispatchToken token(VirtualCallStubManager::GetTokenFromStubQuick(pVSDStubManager, target, vsdStubKind));\n        _ASSERTE(token.IsValid());\n        return VirtualCallStubManager::GetInterfaceMethodDescFromToken(token);\n    }\n    if (RangeSectionStubManager::GetStubKind(target) == STUB_CODE_BLOCK_PRECODE)\n    {\n        \/\/ The address looks like a value stub, try to get the method descriptor.\n        return MethodDesc::GetMethodDescFromStubAddr(target, TRUE);\n    }\n\n    return nullptr;\n}\n\nbool IsGcCoverageInterruptInstruction(PBYTE instrPtr)\n{\n    UINT32 instrVal;\n\n#if defined(TARGET_ARM64)\n    instrVal = *reinterpret_cast<UINT32*>(instrPtr);\n#elif defined(TARGET_ARM)\n    size_t instrLen = GetARMInstructionLength(instrPtr);\n    if (instrLen == 2)\n    {\n        instrVal = *reinterpret_cast<UINT16*>(instrPtr);\n    }\n    else\n    {\n        instrVal = *reinterpret_cast<UINT32*>(instrPtr);\n    }\n#else \/\/ x64 and x86\n    instrVal = *instrPtr;\n#endif\n\n    return IsGcCoverageInterruptInstructionVal(instrVal);\n}\n\nbool IsOriginalInstruction(PBYTE instrPtr, GCCoverageInfo* gcCover, DWORD offset)\n{\n#if defined(TARGET_ARM64)\n    UINT32 instrVal = *reinterpret_cast<UINT32*>(instrPtr);\n    UINT32 origInstrVal = *reinterpret_cast<UINT32*>(gcCover->savedCode + offset);\n    return (instrVal == origInstrVal);\n#elif defined(TARGET_ARM)\n    size_t instrLen = GetARMInstructionLength(instrPtr);\n    if (instrLen == 2)\n    {\n        UINT16 instrVal = *reinterpret_cast<UINT16*>(instrPtr);\n        UINT16 origInstrVal = *reinterpret_cast<UINT16*>(gcCover->savedCode + offset);\n        return (instrVal == origInstrVal);\n    }\n    else\n    {\n        _ASSERTE(instrLen == 4);\n        UINT32 instrVal = *reinterpret_cast<UINT32*>(instrPtr);\n        UINT32 origInstrVal = *reinterpret_cast<UINT32*>(gcCover->savedCode + offset);\n        return (instrVal == origInstrVal);\n    }\n#else \/\/ x64 and x86\n    UINT8 instrVal = *reinterpret_cast<UINT8*>(instrPtr);\n    UINT8 origInstrVal = gcCover->savedCode[offset];\n    return (instrVal == origInstrVal);\n#endif\n}\n\n\nvoid SetupAndSprinkleBreakpoints(\n    NativeCodeVersion               nativeCodeVersion,\n    EECodeInfo                    * pCodeInfo,\n    IJitManager::MethodRegionInfo   methodRegionInfo,\n    BOOL                            fZapped\n    )\n{\n    _ASSERTE(!nativeCodeVersion.IsNull());\n\n    \/\/ Allocate room for the GCCoverageInfo and copy of the method instructions\n    MethodDesc *pMD = nativeCodeVersion.GetMethodDesc();\n    size_t memSize = sizeof(GCCoverageInfo) + methodRegionInfo.hotSize + methodRegionInfo.coldSize;\n    GCCoverageInfo* gcCover = (GCCoverageInfo*)(void*) pMD->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocAlignedMem(memSize, CODE_SIZE_ALIGN);\n\n    memset(gcCover, 0, sizeof(GCCoverageInfo));\n\n    gcCover->methodRegion      = methodRegionInfo;\n    gcCover->codeMan           = pCodeInfo->GetCodeManager();\n    gcCover->gcInfoToken       = pCodeInfo->GetGCInfoToken();\n    gcCover->callerThread      = 0;\n    gcCover->doingEpilogChecks = true;\n\n    gcCover->SprinkleBreakpoints(gcCover->savedCode,\n                                 gcCover->methodRegion.hotStartAddress,\n                                 gcCover->methodRegion.hotSize,\n                                 0,\n                                 fZapped);\n\n    \/\/ This is not required for ARM* as the above call does the work for both hot & cold regions\n#if !defined(TARGET_ARM) && !defined(TARGET_ARM64)\n    if (gcCover->methodRegion.coldSize != 0)\n    {\n        gcCover->SprinkleBreakpoints(gcCover->savedCode + gcCover->methodRegion.hotSize,\n                                     gcCover->methodRegion.coldStartAddress,\n                                     gcCover->methodRegion.coldSize,\n                                     gcCover->methodRegion.hotSize,\n                                     fZapped);\n    }\n#endif\n\n    nativeCodeVersion.SetGCCoverageInfo(gcCover);\n}\n\nvoid SetupAndSprinkleBreakpointsForJittedMethod(NativeCodeVersion               nativeCodeVersion,\n                                                PCODE                           codeStart\n                                               )\n{\n    _ASSERTE(!nativeCodeVersion.IsNull());\n\n    EECodeInfo codeInfo(codeStart);\n    _ASSERTE(codeInfo.IsValid());\n    _ASSERTE(codeInfo.GetRelOffset() == 0);\n\n    IJitManager::MethodRegionInfo methodRegionInfo;\n    codeInfo.GetMethodRegionInfo(&methodRegionInfo);\n\n    _ASSERTE(PCODEToPINSTR(codeStart) == methodRegionInfo.hotStartAddress);\n\n#ifdef _DEBUG\n    if (!g_pConfig->SkipGCCoverage(nativeCodeVersion.GetMethodDesc()->GetModule()->GetSimpleName()))\n#endif\n    SetupAndSprinkleBreakpoints(nativeCodeVersion,\n                                &codeInfo,\n                                methodRegionInfo,\n                                FALSE\n                               );\n}\n\n\/****************************************************************************\/\n\/* called when a method is first jitted when GCStress level 4 or 8 is on *\/\n\nvoid SetupGcCoverage(NativeCodeVersion nativeCodeVersion, BYTE* methodStartPtr)\n{\n    _ASSERTE(!nativeCodeVersion.IsNull());\n\n#ifdef _DEBUG\n    if (!g_pConfig->ShouldGcCoverageOnMethod(nativeCodeVersion.GetMethodDesc()->m_pszDebugMethodName)) {\n        return;\n    }\n#endif\n\n    \/\/ Ideally we would assert here that m_GcCover is NULL.\n    \/\/\n    \/\/ However, we can't do that (at least not yet), because we may\n    \/\/ invoke this method more than once on a given\n    \/\/ MethodDesc. Examples include prejitted methods and rejitted\n    \/\/ methods.\n    \/\/\n    \/\/ In the prejit case, we can't safely re-instrument an already\n    \/\/ instrumented method. By bailing out here, we will use the\n    \/\/ original instrumentation, which should still be valid as\n    \/\/ the method code has not changed.\n    \/\/\n    \/\/ In the rejit case, the old method code may still be active and\n    \/\/ instrumented, so we need to preserve that gc cover info.  By\n    \/\/ bailing out here we will skip instrumenting the rejitted native\n    \/\/ code, and since the rejitted method does not get instrumented\n    \/\/ we should be able to tolerate that the gc cover info does not\n    \/\/ match.\n    if (nativeCodeVersion.GetGCCoverageInfo() != NULL)\n    {\n        return;\n    }\n\n    PCODE codeStart = (PCODE) methodStartPtr;\n    SetupAndSprinkleBreakpointsForJittedMethod(nativeCodeVersion, codeStart);\n}\n\n#ifdef FEATURE_PREJIT\n\nvoid SetupGcCoverageForNativeMethod(NativeCodeVersion nativeCodeVersion,\n                                    PCODE codeStart,\n                                     IJitManager::MethodRegionInfo& methodRegionInfo\n                                   )\n{\n    _ASSERTE(!nativeCodeVersion.IsNull());\n\n    EECodeInfo codeInfo(codeStart);\n    _ASSERTE(codeInfo.IsValid());\n    _ASSERTE(codeInfo.GetRelOffset() == 0);\n\n    _ASSERTE(PCODEToPINSTR(codeStart) == methodRegionInfo.hotStartAddress);\n\n    SetupAndSprinkleBreakpoints(nativeCodeVersion,\n                                &codeInfo,\n                                methodRegionInfo,\n                                TRUE\n                               );\n}\n\nvoid SetupGcCoverageForNativeImage(Module* module)\n{\n    \/\/ Disable IBC logging here because of NGen image is not fully initialized yet. Eager bound\n    \/\/ indirection cells are not initialized yet and so IBC logging would crash while attempting to dereference them.\n    IBCLoggingDisabler disableLogging;\n\n#if 0\n    \/\/ Debug code\n    LPWSTR wszSetupGcCoverage = CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_SetupGcCoverage);\n\n    if (!wszSetupGcCoverage)\n    {\n        printf(\"wszSetupGcCoverage is NULL. Will not SetupGcCoverage for any module.\\n\");\n        return;\n    }\n    else\n    {\n        if ((wcscmp(W(\"*\"), wszSetupGcCoverage) == 0) ||  \/\/ \"*\" means will gcstress all modules\n            (wcsstr(module->GetDebugName(), wszSetupGcCoverage) != NULL))\n        {\n            printf(\"[%ws] matched %ws\\n\", wszSetupGcCoverage, module->GetDebugName());\n            \/\/ Fall through\n        }\n        else\n        {\n            printf(\"[%ws] NOT match %ws\\n\", wszSetupGcCoverage, module->GetDebugName());\n            return;\n        }\n    }\n#endif\n\n#ifdef _DEBUG\n    if (g_pConfig->SkipGCCoverage(module->GetSimpleName()))\n        return;\n#endif\n\n    MethodIterator mi(module);\n    while (mi.Next())\n    {\n        PTR_MethodDesc pMD = mi.GetMethodDesc();\n        PCODE pMethodStart = mi.GetMethodStartAddress();\n\n        IJitManager::MethodRegionInfo methodRegionInfo;\n        mi.GetMethodRegionInfo(&methodRegionInfo);\n\n        SetupGcCoverageForNativeMethod(NativeCodeVersion(pMD), pMethodStart, methodRegionInfo);\n    }\n}\n#endif\n\n\nvoid ReplaceInstrAfterCall(PBYTE instrToReplace, MethodDesc* callMD)\n{\n    ReturnKind returnKind = callMD->GetReturnKind(true);\n    if (!IsValidReturnKind(returnKind))\n    {\n#if defined(TARGET_AMD64) && defined(TARGET_UNIX)\n        _ASSERTE(!\"Unexpected return kind for x64 Unix.\");\n#else\n        \/\/ SKip GC coverage after the call.\n        return;\n#endif\n    }\n    _ASSERTE(IsValidReturnKind(returnKind));\n\n    bool ispointerKind = IsPointerReturnKind(returnKind);\n#ifdef TARGET_ARM\n    size_t instrLen = GetARMInstructionLength(instrToReplace);\n    bool protectReturn = ispointerKind;\n    if (protectReturn)\n        if (instrLen == 2)\n            *(WORD*)instrToReplace = INTERRUPT_INSTR_PROTECT_RET;\n        else\n            *(DWORD*)instrToReplace = INTERRUPT_INSTR_PROTECT_RET_32;\n    else\n        if (instrLen == 2)\n            *(WORD*)instrToReplace = INTERRUPT_INSTR;\n        else\n            *(DWORD*)instrToReplace = INTERRUPT_INSTR_32;\n#elif defined(TARGET_ARM64)\n    bool protectReturn = ispointerKind;\n    if (protectReturn)\n        *(DWORD*)instrToReplace = INTERRUPT_INSTR_PROTECT_RET;\n    else\n        *(DWORD*)instrToReplace = INTERRUPT_INSTR;\n#elif defined(TARGET_AMD64) || defined(TARGET_X86)\n\n\n    if (ispointerKind)\n    {\n        bool protectRegister[2] = { false, false };\n\n        bool moreRegisters = false;\n\n        ReturnKind fieldKind1 = ExtractRegReturnKind(returnKind, 0, moreRegisters);\n        if (IsPointerFieldReturnKind(fieldKind1))\n        {\n            protectRegister[0] = true;\n        }\n        if (moreRegisters)\n        {\n            ReturnKind fieldKind2 = ExtractRegReturnKind(returnKind, 1, moreRegisters);\n            if (IsPointerFieldReturnKind(fieldKind2))\n            {\n                protectRegister[1] = true;\n            }\n        }\n        _ASSERTE(!moreRegisters);\n\n        if (protectRegister[0] && !protectRegister[1])\n        {\n            *instrToReplace = INTERRUPT_INSTR_PROTECT_FIRST_RET;\n        }\n        else\n        {\n#if !defined(TARGET_AMD64) || !defined(TARGET_UNIX)\n            _ASSERTE(!\"Not expected multi reg return with pointers.\");\n#endif \/\/ !TARGET_AMD64 || !TARGET_UNIX\n            if (!protectRegister[0] && protectRegister[1])\n            {\n                *instrToReplace = INTERRUPT_INSTR_PROTECT_SECOND_RET;\n            }\n            else\n            {\n                _ASSERTE(protectRegister[0] && protectRegister[1]);\n                *instrToReplace = INTERRUPT_INSTR_PROTECT_BOTH_RET;\n            }\n        }\n    }\n    else\n    {\n        *instrToReplace = INTERRUPT_INSTR;\n    }\n#else\n    _ASSERTE(!\"not implemented for platform\");\n#endif\n}\n\n#ifdef TARGET_AMD64\n\nclass GCCoverageRangeEnumerator\n{\nprivate:\n\n    ICodeManager *m_pCodeManager;\n    GCInfoToken m_pvGCTable;\n    BYTE *m_codeStart;\n    BYTE *m_codeEnd;\n    BYTE *m_curFuncletEnd;\n    BYTE *m_nextFunclet;\n\n\n    BYTE* GetNextFunclet ()\n    {\n        if (m_nextFunclet == NULL)\n            return m_codeEnd;\n\n        BYTE *pCurFunclet = (BYTE*)EECodeInfo::findNextFunclet(m_nextFunclet, m_codeEnd - m_nextFunclet, (LPVOID*)&m_curFuncletEnd);\n        m_nextFunclet = (pCurFunclet != NULL) ? m_curFuncletEnd : NULL;\n\n        if (pCurFunclet == NULL)\n            return m_codeEnd;\n\n        LOG((LF_JIT, LL_INFO1000, \"funclet range %p-%p\\n\", pCurFunclet, m_curFuncletEnd));\n\n        \/\/\n        \/\/ workaround - adjust the funclet end address to exclude uninterruptible\n        \/\/ code at the end of each funclet.  The jit currently puts data like\n        \/\/ jump tables in the code portion of the allocation, instead of the\n        \/\/ read-only portion.\n        \/\/\n        \/\/ TODO: If the entire range is uninterruptible, we should skip the\n        \/\/ entire funclet.\n        \/\/\n        unsigned ofsLastInterruptible = m_pCodeManager->FindEndOfLastInterruptibleRegion(\n                static_cast<unsigned int>(pCurFunclet     - m_codeStart),\n                static_cast<unsigned int>(m_curFuncletEnd - m_codeStart),\n                m_pvGCTable);\n\n        if (ofsLastInterruptible)\n        {\n            m_curFuncletEnd = m_codeStart + ofsLastInterruptible;\n            LOG((LF_JIT, LL_INFO1000, \"adjusted end to %p\\n\", m_curFuncletEnd));\n        }\n\n        return pCurFunclet;\n    }\n\n\npublic:\n\n    GCCoverageRangeEnumerator (ICodeManager *pCodeManager, GCInfoToken pvGCTable, BYTE *codeStart, SIZE_T codeSize)\n    {\n        m_pCodeManager = pCodeManager;\n        m_pvGCTable = pvGCTable;\n        m_codeStart = codeStart;\n        m_codeEnd = codeStart + codeSize;\n        m_nextFunclet = codeStart;\n\n        GetNextFunclet();\n    }\n\n    \/\/ Checks that the given pointer is inside of a range where gc should be\n    \/\/ tested.  If not, increments the pointer until it is, and returns the\n    \/\/ new pointer.\n    BYTE *EnsureInRange (BYTE *cur)\n    {\n        if (cur >= m_curFuncletEnd)\n        {\n            cur = GetNextFunclet();\n        }\n\n        return cur;\n    }\n\n    BYTE *SkipToNextRange ()\n    {\n        return GetNextFunclet();\n    }\n};\n\n#endif \/\/ TARGET_AMD64\n\n\/****************************************************************************\/\n\/* sprinkle interrupt instructions that will stop on every GCSafe location\n   regionOffsetAdj - Represents the offset of the current region\n                     from the beginning of the method (is 0 for hot region)\n*\/\n\nvoid GCCoverageInfo::SprinkleBreakpoints(\n        BYTE * saveAddr,\n        PCODE  pCode,\n        size_t codeSize,\n        size_t regionOffsetAdj,\n        BOOL   fZapped)\n{\n#if (defined(TARGET_X86) || defined(TARGET_AMD64)) && USE_DISASSEMBLER\n\n    BYTE * codeStart = (BYTE *)pCode;\n\n    memcpy(saveAddr, codeStart, codeSize);\n\n    \/\/ For prejitted code we have to remove the write-protect on the code page\n    if (fZapped)\n    {\n        DWORD oldProtect;\n        ClrVirtualProtect(codeStart, codeSize, PAGE_EXECUTE_READWRITE, &oldProtect);\n    }\n\n    PBYTE cur;\n    BYTE* codeEnd = codeStart + codeSize;\n\n    EECodeInfo codeInfo((PCODE)codeStart);\n\n    static ConfigDWORD fGcStressOnDirectCalls; \/\/ ConfigDWORD must be a static variable\n\n\n#ifdef TARGET_AMD64\n    GCCoverageRangeEnumerator rangeEnum(codeMan, gcInfoToken, codeStart, codeSize);\n\n    GcInfoDecoder safePointDecoder(gcInfoToken, (GcInfoDecoderFlags)0, 0);\n    bool fSawPossibleSwitch = false;\n#endif\n\n    cur = codeStart;\n    Disassembler disassembler;\n\n    \/\/ When we find a direct call instruction and we are partially-interruptible\n    \/\/  we determine the target and place a breakpoint after the call\n    \/\/  to simulate the hijack\n    \/\/ However, we need to wait until we disassemble the instruction\n    \/\/  after the call in order to put the breakpoint or we'll mess up\n    \/\/  the disassembly\n    \/\/ This variable is non-null if the previous instruction was a direct call,\n    \/\/  and we have found it's target MethodDesc\n    MethodDesc* prevDirectCallTargetMD = NULL;\n\n    \/* TODO. Simulating the hijack could cause problems in cases where the\n       return register is not always a valid GC ref on the return offset.\n       That could happen if we got to the return offset via a branch\n       and not via return from the preceding call. However, this has not been\n       an issue so far.\n\n       Example:\n        mov eax, someval\n        test eax, eax\n        jCC AFTERCALL\n        call MethodWhichReturnsGCobject \/\/ return value is not used\n        AFTERCALL:\n    *\/\n\n    while (cur < codeEnd)\n    {\n        _ASSERTE(*cur != INTERRUPT_INSTR && *cur != INTERRUPT_INSTR_CALL);\n\n        MethodDesc* targetMD = NULL;\n        InstructionType instructionType;\n        size_t len = disassembler.DisassembleInstruction(cur, codeEnd - cur, &instructionType);\n\n#ifdef TARGET_AMD64\n        \/\/ REVISIT_TODO apparently the jit does not use the entire RUNTIME_FUNCTION range\n        \/\/ for code.  It uses some for switch tables.  Because the first few offsets\n        \/\/ may be decodable as instructions, we can't reason about where we should\n        \/\/ encounter invalid instructions.  However, we do not want to silently skip\n        \/\/ large chunks of methods just because the JIT started emitting a new\n        \/\/ instruction, so only assume it is a switch table if we've seen the switch\n        \/\/ code (an indirect unconditional jump)\n        if ((len == 0) && fSawPossibleSwitch)\n        {\n            LOG((LF_JIT, LL_WARNING, \"invalid instruction at %p (possibly start of switch table)\\n\", cur));\n            cur = rangeEnum.SkipToNextRange();\n            prevDirectCallTargetMD = NULL;\n            fSawPossibleSwitch = false;\n            continue;\n        }\n#endif\n\n        _ASSERTE(len > 0);\n        _ASSERTE(len <= (size_t)(codeEnd-cur));\n\n        switch(instructionType)\n        {\n        case InstructionType::Call_IndirectUnconditional:\n#ifdef TARGET_AMD64\n            if(safePointDecoder.IsSafePoint((UINT32)(cur + len - codeStart + regionOffsetAdj)))\n#endif\n            {\n               *cur = INTERRUPT_INSTR_CALL;        \/\/ return value.  May need to protect\n            }\n            break;\n\n        case InstructionType::Call_DirectUnconditional:\n            if(fGcStressOnDirectCalls.val(CLRConfig::INTERNAL_GcStressOnDirectCalls))\n            {\n#ifdef TARGET_AMD64\n                if(safePointDecoder.IsSafePoint((UINT32)(cur + len - codeStart + regionOffsetAdj)))\n#endif\n                {\n                    PBYTE nextInstr;\n                    PBYTE target = getTargetOfCall(cur, NULL, &nextInstr);\n\n                    if (target != 0)\n                    {\n                        targetMD = getTargetMethodDesc((PCODE)target);\n                    }\n                }\n            }\n            break;\n\n#ifdef TARGET_AMD64\n        case InstructionType::Branch_IndirectUnconditional:\n            fSawPossibleSwitch = true;\n            break;\n#endif\n\n        default:\n            \/\/ Clang issues an error saying that some enum values are not handled in the switch, that's intended\n            break;\n        }\n\n        if (prevDirectCallTargetMD != 0)\n        {\n            ReplaceInstrAfterCall(cur, prevDirectCallTargetMD);\n        }\n\n        \/\/ For fully interruptible code, we end up whacking every instruction\n        \/\/ to INTERRUPT_INSTR.  For non-fully interruptible code, we end\n        \/\/ up only touching the call instructions (specially so that we\n        \/\/ can really do the GC on the instruction just after the call).\n        size_t dwRelOffset = (cur - codeStart) + regionOffsetAdj;\n        _ASSERTE(FitsIn<DWORD>(dwRelOffset));\n        if (codeMan->IsGcSafe(&codeInfo, static_cast<DWORD>(dwRelOffset)))\n        {\n            *cur = INTERRUPT_INSTR;\n        }\n\n#ifdef TARGET_X86\n        \/\/ we will whack every instruction in the prolog and epilog to make certain\n        \/\/ our unwinding logic works there.\n        if (codeMan->IsInPrologOrEpilog((cur - codeStart) + (DWORD)regionOffsetAdj, gcInfoToken, NULL))\n        {\n            *cur = INTERRUPT_INSTR;\n        }\n#endif\n\n        \/\/ If we couldn't find the method desc targetMD is zero\n        prevDirectCallTargetMD = targetMD;\n\n        cur += len;\n\n#ifdef TARGET_AMD64\n        PBYTE newCur = rangeEnum.EnsureInRange(cur);\n        if(newCur != cur)\n        {\n            prevDirectCallTargetMD = NULL;\n            cur = newCur;\n            fSawPossibleSwitch = false;\n        }\n#endif\n    }\n\n    \/\/ If we are not able to place an interrupt at the first instruction, this means that\n    \/\/ we are partially interruptible with no prolog.  Just don't bother to do the\n    \/\/ the epilog checks, since the epilog will be trivial (a single return instr)\n    assert(codeSize > 0);\n    if ((regionOffsetAdj==0) && (*codeStart != INTERRUPT_INSTR))\n        doingEpilogChecks = false;\n\n#elif defined(TARGET_ARM) || defined(TARGET_ARM64)\n    \/\/Save the method code from hotRegion\n    memcpy(saveAddr, (BYTE*)methodRegion.hotStartAddress, methodRegion.hotSize);\n\n    if (methodRegion.coldSize > 0)\n    {\n        \/\/Save the method code from coldRegion\n        memcpy(saveAddr+methodRegion.hotSize, (BYTE*)methodRegion.coldStartAddress, methodRegion.coldSize);\n    }\n\n    \/\/ For prejitted code we have to remove the write-protect on the code page\n    if (fZapped)\n    {\n        DWORD oldProtect;\n        ClrVirtualProtect((BYTE*)methodRegion.hotStartAddress, methodRegion.hotSize, PAGE_EXECUTE_READWRITE, &oldProtect);\n\n        if (methodRegion.coldSize > 0)\n        {\n            ClrVirtualProtect((BYTE*)methodRegion.coldStartAddress, methodRegion.coldSize, PAGE_EXECUTE_READWRITE, &oldProtect);\n        }\n    }\n\n    GcInfoDecoder safePointDecoder(gcInfoToken, (GcInfoDecoderFlags)0, 0);\n\n    assert(methodRegion.hotSize > 0);\n\n#ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED\n    safePointDecoder.EnumerateSafePoints(&replaceSafePointInstructionWithGcStressInstr,this);\n#endif \/\/ PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED\n\n    safePointDecoder.EnumerateInterruptibleRanges(&replaceInterruptibleRangesWithGcStressInstr, this);\n\n    FlushInstructionCache(GetCurrentProcess(), (BYTE*)methodRegion.hotStartAddress, methodRegion.hotSize);\n\n    if (methodRegion.coldSize > 0)\n    {\n        FlushInstructionCache(GetCurrentProcess(), (BYTE*)methodRegion.coldStartAddress, methodRegion.coldSize);\n    }\n\n#else\n    _ASSERTE(!\"not implemented for platform\");\n#endif \/\/ TARGET_X86\n}\n\n#if defined(TARGET_ARM) || defined(TARGET_ARM64)\n\n#ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED\n\nvoid replaceSafePointInstructionWithGcStressInstr(UINT32 safePointOffset, LPVOID pGCCover)\n{\n    PCODE pCode = NULL;\n    IJitManager::MethodRegionInfo *ptr = &(((GCCoverageInfo*)pGCCover)->methodRegion);\n\n    \/\/Get code address from offset\n    if (safePointOffset < ptr->hotSize)\n        pCode = ptr->hotStartAddress + safePointOffset;\n    else if(safePointOffset - ptr->hotSize < ptr->coldSize)\n    {\n        SIZE_T coldOffset = safePointOffset - ptr->hotSize;\n        pCode = ptr->coldStartAddress + coldOffset;\n    }\n    else\n    {\n        \/\/For some methods( eg MCCTest.MyClass.GetSum2 in test file jit\\jit64\\mcc\\interop\\mcc_i07.il) gcinfo points to a safepoint\n        \/\/beyond the length of the method. So commenting the below assert.\n        \/\/_ASSERTE(safePointOffset - ptr->hotSize < ptr->coldSize);\n        return;\n    }\n\n    PBYTE instrPtr = (BYTE*)PCODEToPINSTR(pCode);\n\n    \/\/ For code sequences of the type\n    \/\/ BL func1\n    \/\/ BL func2    \/\/ Safe point 1\n    \/\/ mov r1 r0  \/\/ Safe point 2\n    \/\/ Both the above safe points instruction must be replaced with gcStress instruction.\n    \/\/ However as the first safe point is already replaced with gcstress instruction, decoding of the call\n    \/\/ instruction will fail when processing for the 2nd safe point. Therefore saved instruction must be used instead of\n    \/\/ instrPtr for decoding the call instruction.\n    PBYTE savedInstrPtr = ((GCCoverageInfo*)pGCCover)->savedCode + safePointOffset;\n\n    \/\/Determine if instruction before the safe point is call using immediate (BLX Imm)  or call by register (BLX Rm)\n    BOOL  instructionIsACallThroughRegister = FALSE;\n    BOOL instructionIsACallThroughImmediate = FALSE;\n\n#if defined(TARGET_ARM)\n\n    \/\/ POSSIBLE BUG: Note that we are looking backwards by 2 or 4 bytes, looking for particular call instruction encodings.\n    \/\/ However, we don't know if the previous instruction is 2 bytes or 4 bytes. Looking back 2 bytes could be looking into\n    \/\/ the middle of a 4-byte instruction. The only safe way to do this is by walking forward from the first instruction of\n    \/\/ the function.\n\n    \/\/ call by register instruction is two bytes (BL<c> Reg T1 encoding)\n    WORD instr = *((WORD*)savedInstrPtr - 1);\n    instr = instr & 0xff87;\n    if ((instr ^ 0x4780) == 0)\n    {\n        \/\/ It is call by register\n        instructionIsACallThroughRegister = TRUE;\n    }\n    else\n    {\n        \/\/ call using immediate instructions are 4 bytes (BL<c> <label> T1 encoding)\n        instr = *((WORD*)savedInstrPtr - 2);\n        instr = instr & 0xf800;\n        if ((instr ^ 0xf000) == 0)\n        {\n            if ((*(((WORD*)savedInstrPtr) - 1) & 0xd000) == 0xd000)\n            {\n                \/\/ It is call by immediate\n                instructionIsACallThroughImmediate = TRUE;\n            }\n        }\n    }\n\n#elif defined(TARGET_ARM64)\n    DWORD instr = *((DWORD*)savedInstrPtr - 1);\n\n    \/\/ Is the call through a register or an immediate offset\n    \/\/ BL\n    \/\/ Encoding: 0x94000000 & [imm26]\n    if ((instr & 0xFC000000) == 0x94000000)\n    {\n        instructionIsACallThroughImmediate = TRUE;\n    }\n    \/\/ BLR\n    \/\/ Encoding: 0xD63F0000 & (Rn<<5)\n    else if ((instr & 0xFFFFFC1F) == 0xD63F0000)\n    {\n        instructionIsACallThroughRegister = TRUE;\n    }\n#endif  \/\/ _TARGET_XXXX_\n\n    \/\/ safe point must always be after a call instruction\n    \/\/ and cannot be both call by register & immediate\n    \/\/ The safe points are also marked at jump calls( a special variant of\n    \/\/ tail call). However that call site will never appear on the stack.\n    \/\/ So commenting the assert for now. As for such places the previous\n    \/\/ instruction will not be a call instruction.\n    \/\/_ASSERTE(instructionIsACallThroughRegister ^ instructionIsACallThroughImmediate);\n\n    if(instructionIsACallThroughRegister)\n    {\n        \/\/ If it is call by register then cannot know MethodDesc so replace the call instruction with illegal instruction\n        \/\/ safe point will be replaced with appropriate illegal instruction at execution time when reg value is known\n#if defined(TARGET_ARM)\n        *((WORD*)instrPtr - 1) = INTERRUPT_INSTR_CALL;\n#elif defined(TARGET_ARM64)\n        *((DWORD*)instrPtr - 1) = INTERRUPT_INSTR_CALL;\n#endif \/\/ _TARGET_XXXX_\n    }\n    else if(instructionIsACallThroughImmediate)\n    {\n        \/\/ If it is call by immediate then find the methodDesc\n        PBYTE nextInstr;\n        PBYTE target = getTargetOfCall((PBYTE)((WORD*)savedInstrPtr-2), NULL, &nextInstr);\n\n        if (target != 0)\n        {\n            \/\/Target is calculated wrt the saved instruction pointer\n            \/\/Find the real target wrt the real instruction pointer\n            int delta = static_cast<int>(target - savedInstrPtr);\n            target = delta + instrPtr;\n\n            MethodDesc* targetMD = getTargetMethodDesc((PCODE)target);\n\n            if (targetMD != 0)\n            {\n\n                \/\/ The instruction about to be replaced cannot already be a gcstress instruction\n                _ASSERTE(!IsGcCoverageInterruptInstruction(instrPtr));\n\n                \/\/\n                \/\/ When applying GC coverage breakpoints at native image load time, the code here runs\n                \/\/ before eager fixups are applied for the module being loaded.  The direct call target\n                \/\/ never requires restore, however it is possible that it is initially in an invalid state\n                \/\/ and remains invalid until one or more eager fixups are applied.\n                \/\/\n                \/\/ ReplaceInstrAfterCall consults the method signature, meaning it consults the\n                \/\/ metadata in the owning module.  For generic instantiations stored in non-preferred\n                \/\/ modules, reaching the owning module requires following the module override pointer for\n                \/\/ the enclosing MethodTable.  In this case, the module override pointer is generally\n                \/\/ invalid until an associated eager fixup is applied.\n                \/\/\n                \/\/ In situations like this, ReplaceInstrAfterCall will try to dereference an\n                \/\/ unresolved fixup and will AV.\n                \/\/\n                \/\/ Given all of this, skip the ReplaceInstrAfterCall call by default to avoid\n                \/\/ unexpected AVs.  This implies leaving out the GC coverage breakpoints for direct calls\n                \/\/ unless COMPlus_GcStressOnDirectCalls=1 is explicitly set in the environment.\n                \/\/\n\n                static ConfigDWORD fGcStressOnDirectCalls;\n\n                if (fGcStressOnDirectCalls.val(CLRConfig::INTERNAL_GcStressOnDirectCalls))\n                {\n                    ReplaceInstrAfterCall(instrPtr, targetMD);\n                }\n            }\n        }\n    }\n}\n#endif \/\/ PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED\n\n\/\/Replaces the provided interruptible range with corresponding 2 or 4 byte gcStress illegal instruction\nbool replaceInterruptibleRangesWithGcStressInstr (UINT32 startOffset, UINT32 stopOffset, LPVOID pGCCover)\n{\n    PCODE pCode = NULL;\n    PBYTE rangeStart = NULL;\n    PBYTE rangeStop = NULL;\n\n    \/\/Interruptible range can span across hot & cold region\n    int acrossHotRegion = 1; \/\/ 1 means range is not across end of hot region & 2 is when it is across end of hot region\n\n    \/\/Find the code addresses from offsets\n    IJitManager::MethodRegionInfo *ptr = &(((GCCoverageInfo*)pGCCover)->methodRegion);\n    if (startOffset < ptr->hotSize)\n    {\n        pCode = ptr->hotStartAddress + startOffset;\n        rangeStart = (BYTE*)PCODEToPINSTR(pCode);\n\n        if(stopOffset <= ptr->hotSize)\n        {\n            pCode = ptr->hotStartAddress + stopOffset;\n            rangeStop = (BYTE*)PCODEToPINSTR(pCode);\n        }\n        else\n        {\n            \/\/Interruptible range is spanning across hot & cold region\n            pCode = ptr->hotStartAddress + ptr->hotSize;\n            rangeStop = (BYTE*)PCODEToPINSTR(pCode);\n            acrossHotRegion++;\n        }\n    }\n    else\n    {\n        SIZE_T coldOffset = startOffset - ptr->hotSize;\n        _ASSERTE(coldOffset < ptr->coldSize);\n        pCode = ptr->coldStartAddress + coldOffset;\n        rangeStart = (BYTE*)PCODEToPINSTR(pCode);\n\n        coldOffset = stopOffset - ptr->hotSize;\n        _ASSERTE(coldOffset <= ptr->coldSize);\n        pCode = ptr->coldStartAddress + coldOffset;\n        rangeStop = (BYTE*)PCODEToPINSTR(pCode);\n    }\n\n    \/\/ Need to do two iterations if interruptible range spans across hot & cold region\n    while(acrossHotRegion--)\n    {\n        PBYTE instrPtr = rangeStart;\n        while(instrPtr < rangeStop)\n        {\n            \/\/ The instruction about to be replaced cannot already be a gcstress instruction\n            _ASSERTE(!IsGcCoverageInterruptInstruction(instrPtr));\n#if defined(TARGET_ARM)\n            size_t instrLen = GetARMInstructionLength(instrPtr);\n\n            if (instrLen == 2)\n                *((WORD*)instrPtr)  = INTERRUPT_INSTR;\n            else\n            {\n                *((DWORD*)instrPtr) = INTERRUPT_INSTR_32;\n            }\n\n            instrPtr += instrLen;\n#elif defined(TARGET_ARM64)\n            *((DWORD*)instrPtr) = INTERRUPT_INSTR;\n            instrPtr += 4;\n#endif \/\/ TARGET_XXXX_\n\n        }\n\n        if(acrossHotRegion)\n        {\n            \/\/Set rangeStart & rangeStop for the second iteration\n            _ASSERTE(acrossHotRegion==1);\n            rangeStart = (BYTE*)PCODEToPINSTR(ptr->coldStartAddress);\n            pCode = ptr->coldStartAddress + stopOffset - ptr->hotSize;\n            rangeStop = (BYTE*)PCODEToPINSTR(pCode);\n        }\n    }\n    return FALSE;\n}\n#endif \/\/ defined(TARGET_ARM) || defined(TARGET_ARM64)\n\nstatic size_t getRegVal(unsigned regNum, PCONTEXT regs)\n{\n    return *getRegAddr(regNum, regs);\n}\n\n\/****************************************************************************\/\nstatic PBYTE getTargetOfCall(PBYTE instrPtr, PCONTEXT regs, PBYTE* nextInstr) {\n\n    BYTE sibindexadj = 0;\n    BYTE baseadj = 0;\n    WORD displace = 0;\n\n    \/\/ In certain situations, the instruction bytes are read from a different\n    \/\/ location than the actual bytes being executed.\n    \/\/ When decoding the instructions of a method which is sprinkled with\n    \/\/ TRAP instructions for GCStress, we decode the bytes from a copy\n    \/\/ of the instructions stored before the traps-for-gc were inserted.\n    \/\/ However, the PC-relative addressing\/displacement of the CALL-target\n    \/\/ will still be with respect to the currently executing PC.\n    \/\/ So, if a register context is available, we pick the PC from it\n    \/\/ (for address calculation purposes only).\n\n    PBYTE PC = (regs) ? (PBYTE)GetIP(regs) : instrPtr;\n\n#ifdef TARGET_ARM\n    if((instrPtr[1] & 0xf0) == 0xf0) \/\/ direct call\n    {\n        int imm32 = GetThumb2BlRel24((UINT16 *)instrPtr);\n        *nextInstr = instrPtr + 4;\n        return PC + 4 + imm32;\n    }\n    else if(((instrPtr[1] & 0x47) == 0x47) & ((instrPtr[0] & 0x80) == 0x80)) \/\/ indirect call\n    {\n        *nextInstr = instrPtr + 2;\n        unsigned int regnum = (instrPtr[0] & 0x78) >> 3;\n        return (BYTE *)getRegVal(regnum, regs);\n    }\n    else\n    {\n        return 0; \/\/ Not a call.\n    }\n#elif defined(TARGET_ARM64)\n   if (((*reinterpret_cast<DWORD*>(instrPtr)) & 0xFC000000) == 0x94000000)\n   {\n       \/\/ call through immediate\n       int imm26 = ((*((DWORD*)instrPtr)) & 0x03FFFFFF)<<2;\n       \/\/ SignExtend the immediate value.\n       imm26 = (imm26 << 4) >> 4;\n       *nextInstr = instrPtr + 4;\n       return PC + imm26;\n   }\n   else if (((*reinterpret_cast<DWORD*>(instrPtr)) & 0xFFFFC1F) == 0xD63F0000)\n   {\n       \/\/ call through register\n       *nextInstr = instrPtr + 4;\n       unsigned int regnum = ((*(DWORD*)instrPtr) >> 5) & 0x1F;\n       return (BYTE *)getRegVal(regnum, regs);\n   }\n   else\n   {\n       return 0; \/\/ Fail\n   }\n#endif\n\n#ifdef TARGET_AMD64\n\n    if ((instrPtr[0] & 0xf0) == REX_PREFIX_BASE)\n    {\n        static_assert_no_msg(REX_SIB_BASE_EXT == REX_MODRM_RM_EXT);\n        if (instrPtr[0] & REX_SIB_BASE_EXT)\n            baseadj = 8;\n\n        if (instrPtr[0] & REX_SIB_INDEX_EXT)\n            sibindexadj = 8;\n\n        instrPtr++;\n    }\n\n#endif \/\/ TARGET_AMD64\n\n    if (instrPtr[0] == 0xE8) {  \/\/ Direct Relative Near\n        *nextInstr = instrPtr + 5;\n\n        size_t base = (size_t) PC + 5;\n\n        INT32 displacement = (INT32) (\n            ((UINT32)instrPtr[1]) +\n            (((UINT32)instrPtr[2]) << 8) +\n            (((UINT32)instrPtr[3]) << 16) +\n            (((UINT32)instrPtr[4]) << 24)\n            );\n\n        \/\/ Note that the signed displacement is sign-extended\n        \/\/  to 64-bit on AMD64\n        return((PBYTE)(base + (SSIZE_T)displacement));\n    }\n\n    if (instrPtr[0] == 0xFF) { \/\/ Indirect Absolute Near\n\n        _ASSERTE(regs);\n\n        BYTE mod = (instrPtr[1] & 0xC0) >> 6;\n        BYTE rm  = (instrPtr[1] & 0x7);\n        PBYTE result;\n\n        switch (mod) {\n        case 0:\n        case 1:\n        case 2:\n\n            if (rm == 4) {\n\n                \/\/\n                \/\/ Get values from the SIB byte\n                \/\/\n                BYTE ss    = (instrPtr[2] & 0xC0) >> 6;\n                BYTE index = (instrPtr[2] & 0x38) >> 3;\n                BYTE base  = (instrPtr[2] & 0x7);\n\n                \/\/\n                \/\/ Get starting value\n                \/\/\n                if ((mod == 0) && (base == 5)) {\n                    result = 0;\n                } else {\n                    result = (BYTE *)getRegVal(baseadj + base, regs);\n                }\n\n                \/\/\n                \/\/ Add in the [index]\n                \/\/\n                if (index != 0x4) {\n                    result = result + (getRegVal(sibindexadj + index, regs) << ss);\n                }\n\n                \/\/\n                \/\/ Finally add in the offset\n                \/\/\n                if (mod == 0) {\n\n                    if (base == 5) {\n                        result = result + *((int *)&instrPtr[3]);\n                        displace += 7;\n                    } else {\n                        displace += 3;\n                    }\n\n                } else if (mod == 1) {\n\n                    result = result + *((char *)&instrPtr[3]);\n                    displace += 4;\n\n                } else { \/\/ == 2\n\n                    result = result + *((int *)&instrPtr[3]);\n                    displace += 7;\n\n                }\n\n            } else {\n\n                \/\/\n                \/\/ Get the value we need from the register.\n                \/\/\n\n                if ((mod == 0) && (rm == 5)) {\n#ifdef TARGET_AMD64\n                    \/\/ at this point instrPtr should be pointing at the beginning\n                    \/\/ of the byte sequence for the call instruction.  the operand\n                    \/\/ is a RIP-relative address from the next instruction, so to\n                    \/\/ calculate the address of the next instruction we need to\n                    \/\/ jump forward 6 bytes: 1 for the opcode, 1 for the ModRM byte,\n                    \/\/ and 4 for the operand.  see AMD64 Programmer's Manual Vol 3.\n                    result = PC + 6;\n#else\n                    result = 0;\n#endif \/\/ TARGET_AMD64\n                } else {\n                    result = (PBYTE)getRegVal(baseadj + rm, regs);\n                }\n\n                if (mod == 0) {\n\n                    if (rm == 5) {\n                        result = result + *((int *)&instrPtr[2]);\n                        displace += 6;\n                    } else {\n                        displace += 2;\n                    }\n\n                } else if (mod == 1) {\n\n                    result = result + *((char *)&instrPtr[2]);\n                    displace += 3;\n\n                } else { \/\/ == 2\n\n                    result = result + *((int *)&instrPtr[2]);\n                    displace += 6;\n\n                }\n\n            }\n\n            \/\/\n            \/\/ Now dereference thru the result to get the resulting IP.\n            \/\/\n            result = (PBYTE)(*((PBYTE *)result));\n\n            break;\n\n        case 3:\n        default:\n\n            result = (PBYTE)getRegVal(baseadj + rm, regs);\n            displace += 2;\n            break;\n\n        }\n\n        *nextInstr = instrPtr + displace;\n        return result;\n\n    }\n\n    return(0);      \/\/ Fail\n}\n\n\/****************************************************************************\/\n\n#ifdef TARGET_X86\n\nvoid checkAndUpdateReg(DWORD& origVal, DWORD curVal, bool gcHappened) {\n    if (origVal == curVal)\n        return;\n\n    \/\/ If these asserts go off, they indicate either that unwinding out of a epilog is wrong or that\n    \/\/ the validation infrastructure has got a bug.\n\n    _ASSERTE(gcHappened);    \/\/ If the register values are different, a GC must have happened\n    _ASSERTE(GCHeapUtilities::GetGCHeap()->IsHeapPointer((BYTE*) size_t(origVal)));    \/\/ And the pointers involved are on the GCHeap\n    _ASSERTE(GCHeapUtilities::GetGCHeap()->IsHeapPointer((BYTE*) size_t(curVal)));\n    origVal = curVal;       \/\/ this is now the best estimate of what should be returned.\n}\n\n#endif \/\/ TARGET_X86\n\n\nint GCcoverCount = 0;\n\nvoid* forceStack[8];\n\n\/****************************************************************************\/\n\nbool IsGcCoverageInterrupt(LPVOID ip)\n{\n    \/\/ Determine if the IP is valid for a GC marker first, before trying to dereference it to check the instruction\n\n    EECodeInfo codeInfo(reinterpret_cast<PCODE>(ip));\n    if (!codeInfo.IsValid())\n    {\n        return false;\n    }\n\n    NativeCodeVersion nativeCodeVersion = codeInfo.GetNativeCodeVersion();\n    _ASSERTE(!nativeCodeVersion.IsNull());\n    GCCoverageInfo *gcCover = nativeCodeVersion.GetGCCoverageInfo();\n    if (gcCover == nullptr)\n    {\n        return false;\n    }\n\n    PBYTE instrPtr = reinterpret_cast<PBYTE>(ip);\n\n    if (IsGcCoverageInterruptInstruction(instrPtr))\n    {\n        return true;\n    }\n\n    if (IsOriginalInstruction(instrPtr, gcCover, codeInfo.GetRelOffset()))\n    {\n        \/\/ Another thread may have already changed the code back to the original.\n        return true;\n    }\n    return false;\n}\n\n\/\/ Remove the GcCoverage interrupt instruction, and restore the\n\/\/ original instruction. Only one instruction must be used,\n\/\/ because multiple threads can be executing the same code stream.\n\nvoid RemoveGcCoverageInterrupt(TADDR instrPtr, BYTE * savedInstrPtr, GCCoverageInfo* gcCover, DWORD offset)\n{\n#ifdef TARGET_ARM\n        if (GetARMInstructionLength(savedInstrPtr) == 2)\n            *(WORD *)instrPtr  = *(WORD *)savedInstrPtr;\n        else\n            *(DWORD *)instrPtr = *(DWORD *)savedInstrPtr;\n#elif defined(TARGET_ARM64)\n        *(DWORD *)instrPtr = *(DWORD *)savedInstrPtr;\n#else\n        *(BYTE *)instrPtr = *savedInstrPtr;\n#endif\n\n#ifdef TARGET_X86\n    \/\/ Epilog checking relies on precise control of when instrumentation for the  first prolog \n    \/\/ instruction is enabled or disabled. In particular, if a function has multiple epilogs, or\n    \/\/ the first execution of the function terminates via an exception, and subsequent completions\n    \/\/ do not, then the function may trigger a false stress fault if epilog checks are not disabled.\n    if (offset == 0)\n    {\n        gcCover->doingEpilogChecks = false;\n    }\n#endif \/\/ TARGET_X86\n\n        FlushInstructionCache(GetCurrentProcess(), (LPCVOID)instrPtr, 4);\n}\n\n\/\/ A managed thread (T) can race with the GC as follows:\n\/\/ 1)\tAt the first safepoint, we notice that T is in preemptive mode during the call for GCStress\n\/\/      So, it is put it in cooperative mode for the purpose of GCStress(fPremptiveGcDisabledForGcStress)\n\/\/ 2)\tWe DoGCStress(). Start off background GC in a different thread.\n\/\/ 3)\tThen the thread T is put back to preemptive mode (because that's where it was).\n\/\/      Thread T continues execution along with the GC thread.\n\/\/ 4)\tThe Jitted code puts thread T to cooperative mode, as part of PInvoke epilog\n\/\/ 5)\tNow instead of CORINFO_HELP_STOP_FOR_GC(), we hit the GCStress trap and start\n\/\/      another round of GCStress while in Cooperative mode.\n\/\/ 6)\tNow, thread T can modify the stack (ex: RedirectionFrame setup) while the GC thread is scanning it.\n\/\/\n\/\/ This race is now mitigated below. Where we won't initiate a stress mode GC\n\/\/ for a thread in cooperative mode with an active ICF, if g_TrapReturningThreads is true.\n\nBOOL OnGcCoverageInterrupt(PCONTEXT regs)\n{\n    \/\/ So that you can set counted breakpoint easily;\n    GCcoverCount++;\n    forceStack[0]= &regs;                \/\/ This is so I can see it fastchecked\n\n    PCODE controlPc = GetIP(regs);\n    TADDR instrPtr = PCODEToPINSTR(controlPc);\n\n    forceStack[0] = &instrPtr;            \/\/ This is so I can see it fastchecked\n\n    EECodeInfo codeInfo(controlPc);\n    if (!codeInfo.IsValid())\n        return(FALSE);\n\n    MethodDesc* pMD = codeInfo.GetMethodDesc();\n    DWORD offset = codeInfo.GetRelOffset();\n\n    forceStack[1] = &pMD;                \/\/ This is so I can see it fastchecked\n    forceStack[2] = &offset;             \/\/ This is so I can see it fastchecked\n\n    NativeCodeVersion nativeCodeVersion = codeInfo.GetNativeCodeVersion();\n    _ASSERTE(!nativeCodeVersion.IsNull());\n    GCCoverageInfo* gcCover = nativeCodeVersion.GetGCCoverageInfo();\n    forceStack[3] = &gcCover;            \/\/ This is so I can see it fastchecked\n    if (gcCover == 0)\n        return(FALSE);        \/\/ we aren't doing code gcCoverage on this function\n\n    BYTE * savedInstrPtr = &gcCover->savedCode[offset];\n\n    Thread* pThread = GetThread();\n    if (!pThread)\n    {\n        \/\/ No thread at the moment so we aren't doing coverage for this function.\n        \/\/ This should only occur for methods with the UnmanagedCallersOnlyAttribute,\n        \/\/ where the call could be coming from a thread unknown to the CLR and\n        \/\/ we haven't created a thread yet - see PreStubWorker_Preemptive().\n        _ASSERTE(pMD->HasUnmanagedCallersOnlyAttribute());\n        RemoveGcCoverageInterrupt(instrPtr, savedInstrPtr, gcCover, offset);\n        return TRUE;\n    }\n\n    \/\/ If the thread is in preemptive mode then we must be in a\n    \/\/ PInvoke stub, a method that has an inline PInvoke frame,\n    \/\/ or be in a reverse PInvoke stub that's about to return.\n    \/\/\n    \/\/ The PInvoke cases should should properly report GC refs if we\n    \/\/ trigger GC here. But a reverse PInvoke stub may over-report\n    \/\/ leading to spurious failures, as we would not normally report\n    \/\/ anything for this method at this point.\n    if (!pThread->PreemptiveGCDisabled() && pMD->HasUnmanagedCallersOnlyAttribute())\n    {\n        RemoveGcCoverageInterrupt(instrPtr, savedInstrPtr, gcCover, offset);\n        return TRUE;\n    }\n\n    \/\/ If we're in cooperative mode, we're supposed to stop for GC,\n    \/\/ and there's an active ICF, don't initiate a stress GC.\n    if (g_TrapReturningThreads && pThread->PreemptiveGCDisabled())\n    {\n        Frame* pFrame = pThread->GetFrame();\n        if (InlinedCallFrame::FrameHasActiveCall(pFrame))\n        {\n            RemoveGcCoverageInterrupt(instrPtr, savedInstrPtr, gcCover, offset);\n            return TRUE;\n        }\n    }\n\n#if defined(USE_REDIRECT_FOR_GCSTRESS) && !defined(TARGET_UNIX)\n    \/\/ If we're unable to redirect, then we simply won't test GC at this\n    \/\/ location.\n    if (!pThread->CheckForAndDoRedirectForGCStress(regs))\n    {\n        RemoveGcCoverageInterrupt(instrPtr, savedInstrPtr, gcCover, offset);\n    }\n\n#else \/\/ !USE_REDIRECT_FOR_GCSTRESS\n\n#ifdef _DEBUG\n    if (!g_pConfig->SkipGCCoverage(pMD->GetModule()->GetSimpleName()))\n#endif\n    DoGcStress(regs, codeInfo.GetNativeCodeVersion());\n\n#endif \/\/ !USE_REDIRECT_FOR_GCSTRESS\n\n    return TRUE;\n}\n\n\/\/ There are some code path in DoGcStress to return without doing a GC but we\n\/\/ now relies on EE suspension to update the GC STRESS instruction.\n\/\/ We need to do a extra EE suspension\/resume even without GC.\nFORCEINLINE void UpdateGCStressInstructionWithoutGC ()\n{\n    ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_OTHER);\n    ThreadSuspend::RestartEE(TRUE, TRUE);\n}\n\n\/****************************************************************************\/\n\nvoid DoGcStress (PCONTEXT regs, NativeCodeVersion nativeCodeVersion)\n{\n    PCODE controlPc = GetIP(regs);\n    PBYTE instrPtr = reinterpret_cast<PBYTE>(PCODEToPINSTR(controlPc));\n\n    if (nativeCodeVersion.IsNull())\n    {\n        nativeCodeVersion = ExecutionManager::GetNativeCodeVersion(controlPc);\n        if (nativeCodeVersion.IsNull())\n            return;\n    }\n\n    GCCoverageInfo *gcCover = nativeCodeVersion.GetGCCoverageInfo();\n\n    EECodeInfo codeInfo(controlPc);\n    _ASSERTE(codeInfo.GetNativeCodeVersion() == nativeCodeVersion);\n    DWORD offset = codeInfo.GetRelOffset();\n\n    Thread *pThread = GetThread();\n    _ASSERTE(pThread);\n\n    \/\/ There is a race condition with the computation of `atCall`. Multiple threads could enter\n    \/\/ this function (DoGcStress) at the same time. If one reads `*instrPtr` and sets `atCall`\n    \/\/ to `true`, it will proceed to, lower down in this function, call `pThread->CommitGCStressInstructionUpdate()`\n    \/\/ to replace the GCStress instruction at the call back to the original call instruction.\n    \/\/ Other threads could then read `*instrPtr` and see the actual call instruction instead of the\n    \/\/ call-specific GCStress instruction (INTERRUPT_INSTR_CALL[_32]). If `atCall` is set to false as\n    \/\/ a result, then we'll do a GCStress as if this is a fully-interruptible code site, which is isn't,\n    \/\/ which can leads to asserts (or, presumably, other failures). So, we have to check\n    \/\/ `if (!IsGcCoverageInterruptInstruction(instrPtr))` after we read `*instrPtr`.\n\n    bool atCall;\n    bool afterCallProtect[2] = { false, false };\n\n#if defined(TARGET_X86) || defined(TARGET_AMD64)\n\n    BYTE instrVal = *instrPtr;\n    forceStack[6] = &instrVal;            \/\/ This is so I can see it fastchecked\n\n    atCall = (instrVal == INTERRUPT_INSTR_CALL);\n\n    if (instrVal == INTERRUPT_INSTR_PROTECT_BOTH_RET)\n    {\n        afterCallProtect[0] = afterCallProtect[1] = true;\n    }\n    else if (instrVal == INTERRUPT_INSTR_PROTECT_FIRST_RET)\n    {\n        afterCallProtect[0] = true;\n    }\n    else if (instrVal == INTERRUPT_INSTR_PROTECT_SECOND_RET)\n    {\n        afterCallProtect[1] = true;\n    }\n\n#elif defined(TARGET_ARM)\n\n    forceStack[6] = (WORD*)instrPtr;            \/\/ This is so I can see it fastchecked\n\n    size_t instrLen = GetARMInstructionLength(instrPtr);\n\n    if (instrLen == 2)\n    {\n        WORD instrVal = *(WORD*)instrPtr;\n        atCall              = (instrVal == INTERRUPT_INSTR_CALL);\n        afterCallProtect[0] = (instrVal == INTERRUPT_INSTR_PROTECT_RET);\n    }\n    else\n    {\n        _ASSERTE(instrLen == 4);\n\n        DWORD instrVal32 = *(DWORD*)instrPtr;\n\n        atCall              = (instrVal32 == INTERRUPT_INSTR_CALL_32);\n        afterCallProtect[0] = (instrVal32 == INTERRUPT_INSTR_PROTECT_RET_32);\n    }\n\n#elif defined(TARGET_ARM64)\n\n    DWORD instrVal = *(DWORD *)instrPtr;\n    forceStack[6] = &instrVal;            \/\/ This is so I can see it fastchecked\n\n    atCall = (instrVal == INTERRUPT_INSTR_CALL);\n    afterCallProtect[0] = (instrVal == INTERRUPT_INSTR_PROTECT_RET);\n\n#endif \/\/ _TARGET_*\n\n    if (!IsGcCoverageInterruptInstruction(instrPtr))\n    {\n        \/\/ This assert can fail if another thread changed original instruction to\n        \/\/ GCCoverage Interrupt instruction between these two commands. Uncomment it\n        \/\/ when threading issue gets resolved.\n        \/\/ _ASSERTE(IsOriginalInstruction(instrPtr, gcCover, offset));\n\n        \/\/ Someone beat us to it, just go on running.\n        return;\n    }\n\n#ifdef TARGET_X86\n    \/* are we at the very first instruction?  If so, capture the register state *\/\n    bool bShouldUpdateProlog = true;\n    if (gcCover->doingEpilogChecks) {\n        if (offset == 0) {\n            if ((gcCover->callerThread == 0) && (FastInterlockCompareExchangePointer(&gcCover->callerThread, pThread, 0) == 0)) {\n                gcCover->callerRegs = *regs;\n                gcCover->gcCount = GCHeapUtilities::GetGCHeap()->GetGcCount();\n                bShouldUpdateProlog = false;\n            }\n            else {\n                \/\/ We have been in this routine before.  Give up on epilog checking because\n                \/\/ it is hard to insure that the saved caller register state is correct\n                \/\/ This also has the effect of only doing the checking once per routine\n                \/\/ (Even if there are multiple epilogs)\n                gcCover->doingEpilogChecks = false;\n            }\n        }\n\n        \/\/ If some other thread removes interrupt points, we abandon epilog testing\n        \/\/ for this routine since the barrier at the beginning of the routine may not\n        \/\/ be up anymore, and thus the caller context is now not guaranteed to be correct.\n        \/\/ This should happen only very rarely so is not a big deal.\n        if (gcCover->callerThread != pThread)\n            gcCover->doingEpilogChecks = false;\n    }\n\n    instrVal = gcCover->savedCode[offset];\n#endif \/\/ TARGET_X86\n\n\n    \/\/ <GCStress instruction update race>\n    \/\/ Remove the interrupt instruction the next time we suspend the EE,\n    \/\/ which should happen below in the call to StressHeap().  This is\n    \/\/ done with the EE suspended so that we do not race with the executing\n    \/\/ code on some other thread.  If we allow that race, we may sometimes\n    \/\/ get a STATUS_ACCESS_VIOLATION instead of the expected\n    \/\/ STATUS_PRIVILEGED_INSTRUCTION because the OS has to inspect the code\n    \/\/ stream to determine which exception code to raise.  As a result, some\n    \/\/ thread may take the exception due to the HLT, but by the time the OS\n    \/\/ inspects the code stream, the HLT may be replaced with the original\n    \/\/ code and it will just raise a STATUS_ACCESS_VIOLATION.\n#ifdef TARGET_X86\n    \/\/ only restore the original instruction if:\n    \/\/    this is not the first instruction in the method's prolog, or\n    \/\/    if it is, only if this is the second time we run in this method\n    \/\/ note that if this is the second time in the prolog we've already disabled epilog checks\n    if (offset != 0 || bShouldUpdateProlog)\n#endif\n    pThread->PostGCStressInstructionUpdate((BYTE*)instrPtr, &gcCover->savedCode[offset]);\n\n#ifdef TARGET_X86\n    \/* are we in a prolog or epilog?  If so just test the unwind logic\n       but don't actually do a GC since the prolog and epilog are not\n       GC safe points *\/\n    if (gcCover->codeMan->IsInPrologOrEpilog(offset, gcCover->gcInfoToken, NULL))\n    {\n        \/\/ We are not at a GC safe point so we can't Suspend EE (Suspend EE will yield to GC).\n        \/\/ But we still have to update the GC Stress instruction. We do it directly without suspending\n        \/\/ other threads, which means a race on updating is still possible. But for X86 the window of\n        \/\/ race is so small that we could ignore it. We need a better solution if the race becomes a real problem.\n        \/\/ see details about <GCStress instruction update race> in comments above\n        pThread->CommitGCStressInstructionUpdate ();\n\n        REGDISPLAY regDisp;\n        CONTEXT copyRegs = *regs;\n\n        pThread->Thread::InitRegDisplay(&regDisp, &copyRegs, true);\n        pThread->UnhijackThread();\n\n        CodeManState codeManState;\n        codeManState.dwIsSet = 0;\n\n        \/\/ unwind out of the prolog or epilog\n        gcCover->codeMan->UnwindStackFrame(&regDisp,\n                &codeInfo, UpdateAllRegs, &codeManState, NULL);\n\n        \/\/ Note we always doing the unwind, since that at does some checking (that we\n        \/\/ unwind to a valid return address), but we only do the precise checking when\n        \/\/ we are certain we have a good caller state\n        if (gcCover->doingEpilogChecks) {\n            \/\/ Confirm that we recovered our register state properly\n            _ASSERTE(regDisp.PCTAddr == TADDR(gcCover->callerRegs.Esp));\n\n            \/\/ If a GC happened in this function, then the registers will not match\n            \/\/ precisely.  However there is still checks we can do.  Also we can update\n            \/\/ the saved register to its new value so that if a GC does not happen between\n            \/\/ instructions we can recover (and since GCs are not allowed in the\n            \/\/ prologs and epilogs, we get get complete coverage except for the first\n            \/\/ instruction in the epilog  (TODO: fix it for the first instr Case)\n\n            _ASSERTE(pThread->PreemptiveGCDisabled());    \/\/ Epilogs should be in cooperative mode, no GC can happen right now.\n            bool gcHappened = gcCover->gcCount != GCHeapUtilities::GetGCHeap()->GetGcCount();\n            checkAndUpdateReg(gcCover->callerRegs.Edi, *regDisp.GetEdiLocation(), gcHappened);\n            checkAndUpdateReg(gcCover->callerRegs.Esi, *regDisp.GetEsiLocation(), gcHappened);\n            checkAndUpdateReg(gcCover->callerRegs.Ebx, *regDisp.GetEbxLocation(), gcHappened);\n            checkAndUpdateReg(gcCover->callerRegs.Ebp, *regDisp.GetEbpLocation(), gcHappened);\n\n            gcCover->gcCount = GCHeapUtilities::GetGCHeap()->GetGcCount();\n\n        }\n        return;\n    }\n#endif \/\/ TARGET_X86\n\n#if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_ARM64)\n\n    \/* In non-fully interruptible code, if the EIP is just after a call instr\n       means something different because it expects that we are IN the\n       called method, not actually at the instruction just after the call. This\n       is important, because until the called method returns, IT is responsible\n       for protecting the return value.  Thus just after a call instruction\n       we have to protect EAX if the method being called returns a GC pointer.\n\n       To figure this out, we need to stop AT the call so we can determine the\n       target (and thus whether it returns one or more GC pointers), and then place\n       a different interrupt instruction so that the GCCover harness protects\n       the return value register(s) before doing the GC. This effectively simulates\n       a hijack in non-fully interruptible code *\/\n\n    \/* TODO. Simulating the hijack could cause problems in cases where the\n       return register is not always a valid GC ref on the return offset.\n       That could happen if we got to the return offset via a branch\n       and not via return from the preceding call. However, this has not been\n       an issue so far.\n\n       Example:\n        mov eax, someval\n        test eax, eax\n        jCC AFTERCALL\n        call MethodWhichReturnsGCobject \/\/ return value is not used\n        AFTERCALL:\n    *\/\n\n    if (atCall) {\n        \/\/ We need to update the GC Stress instruction. With partially-interruptible code\n        \/\/ the call instruction is not a GC safe point so we can't use\n        \/\/ StressHeap or UpdateGCStressInstructionWithoutGC to take care of updating;\n        \/\/ So we just update the instruction directly. There are still chances for a race,\n        \/\/ but it's not been a problem so far.\n        \/\/ see details about <GCStress instruction update race> in comments above\n        pThread->CommitGCStressInstructionUpdate ();\n        PBYTE nextInstr;\n        PBYTE target = getTargetOfCall((BYTE*) instrPtr, regs, (BYTE**)&nextInstr);\n        if (target != 0)\n        {\n            if (!pThread->PreemptiveGCDisabled())\n            {\n                \/\/ We are in preemptive mode in JITTed code. This implies that we are into IL stub\n                \/\/ close to PINVOKE method. This call will never return objectrefs.\n#ifdef TARGET_ARM\n                size_t instrLen = GetARMInstructionLength(nextInstr);\n                if (instrLen == 2)\n                    *(WORD*)nextInstr  = INTERRUPT_INSTR;\n                else\n                    *(DWORD*)nextInstr = INTERRUPT_INSTR_32;\n#elif defined(TARGET_ARM64)\n                *(DWORD*)nextInstr = INTERRUPT_INSTR;\n#else\n                *nextInstr = INTERRUPT_INSTR;\n#endif\n            }\n            else\n            {\n                MethodDesc* targetMD = getTargetMethodDesc((PCODE)target);\n\n                if (targetMD != 0)\n                {\n                    \/\/ @Todo: possible race here, might need to be fixed  if it become a problem.\n                    \/\/ It could become a problem if 64bit does partially interrupt work.\n                    \/\/ OK, we have the MD, mark the instruction after the CALL\n                    \/\/ appropriately\n                    ReplaceInstrAfterCall(nextInstr, targetMD);\n                }\n            }\n        }\n\n        \/\/ Must flush instruction cache before returning as instruction has been modified.\n        \/\/ Note this needs to reach beyond the call by up to 4 bytes.\n        FlushInstructionCache(GetCurrentProcess(), (LPCVOID)instrPtr, 10);\n\n        \/\/ It's not GC safe point, the GC Stress instruction is\n        \/\/ already committed and interrupt is already put at next instruction so we just return.\n        return;\n    }\n#else\n    PORTABILITY_ASSERT(\"DoGcStress - NYI on this platform\");\n#endif \/\/ _TARGET_*\n\n    bool enableWhenDone = false;\n    if (!pThread->PreemptiveGCDisabled())\n    {\n        pThread->DisablePreemptiveGC();\n        enableWhenDone = true;\n    }\n\n\n#if 0\n    \/\/ TODO currently disabled.  we only do a GC once per instruction location.\n\n  \/* note that for multiple threads, we can loose track and\n       forget to set reset the interrupt after we executed\n       an instruction, so some instruction points will not be\n       executed twice, but we still ge350t very good coverage\n       (perfect for single threaded cases) *\/\n\n    \/* if we have not run this instruction in the past *\/\n    \/* remember to wack it to an INTERUPT_INSTR again *\/\n\n    if (!gcCover->IsBitSetForOffset(offset))  {\n        \/\/ gcCover->curInstr = instrPtr;\n        gcCover->SetBitForOffset(offset);\n    }\n#endif \/\/ 0\n\n\n#if !defined(USE_REDIRECT_FOR_GCSTRESS)\n    \/\/\n    \/\/ If we redirect for gc stress, we don't need this frame on the stack,\n    \/\/ the redirection will push a resumable frame.\n    \/\/\n    FrameWithCookie<ResumableFrame> frame(regs);\n    frame.Push(pThread);\n#endif \/\/ USE_REDIRECT_FOR_GCSTRESS\n\n\n    DWORD_PTR retValRegs[2] = { 0 };\n    UINT  numberOfRegs = 0;\n\n    if (afterCallProtect[0])\n    {\n#if defined(TARGET_AMD64)\n        retValRegs[numberOfRegs++] = regs->Rax;\n#elif defined(TARGET_X86)\n        retValRegs[numberOfRegs++] = regs->Eax;\n#elif  defined(TARGET_ARM)\n        retValRegs[numberOfRegs++] = regs->R0;\n#elif defined(TARGET_ARM64)\n        retValRegs[numberOfRegs++] = regs->X0;\n#endif \/\/ TARGET_ARM64\n    }\n\n    if (afterCallProtect[1])\n    {\n#if defined(TARGET_AMD64) && defined(TARGET_UNIX)\n        retValRegs[numberOfRegs++] = regs->Rdx;\n#else \/\/ !TARGET_AMD64 || !TARGET_UNIX\n        _ASSERTE(!\"Not expected multi reg return with pointers.\");\n#endif \/\/ !TARGET_AMD64 || !TARGET_UNIX\n    }\n\n    _ASSERTE(sizeof(OBJECTREF) == sizeof(DWORD_PTR));\n    GCFrame gcFrame(pThread, (OBJECTREF*)retValRegs, numberOfRegs, TRUE);\n\n    MethodDesc *pMD = nativeCodeVersion.GetMethodDesc();\n    LOG((LF_GCROOTS, LL_EVERYTHING, \"GCCOVER: Doing GC at method %s::%s offset 0x%x\\n\",\n            pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName, offset));\n\n    \/\/-------------------------------------------------------------------------\n    \/\/ Do the actual stress work\n    \/\/\n\n    \/\/ BUG(github #10318) - when not using allocation contexts, the alloc lock\n    \/\/ must be acquired here. Until fixed, this assert prevents random heap corruption.\n    assert(GCHeapUtilities::UseThreadAllocationContexts());\n    GCHeapUtilities::GetGCHeap()->StressHeap(GetThread()->GetAllocContext());\n\n    \/\/ StressHeap can exit early w\/o forcing a SuspendEE to trigger the instruction update\n    \/\/ We can not rely on the return code to determine if the instruction update happened\n    \/\/ Use HasPendingGCStressInstructionUpdate() to be certain.\n    if(pThread->HasPendingGCStressInstructionUpdate())\n        UpdateGCStressInstructionWithoutGC ();\n\n    \/\/ Must flush instruction cache before returning as instruction has been modified.\n    FlushInstructionCache(GetCurrentProcess(), (LPCVOID)instrPtr, 4);\n\n    CONSISTENCY_CHECK(!pThread->HasPendingGCStressInstructionUpdate());\n\n    if (numberOfRegs != 0)\n    {\n        if (afterCallProtect[0])\n        {\n#if defined(TARGET_AMD64)\n            regs->Rax = retValRegs[0];\n#elif defined(TARGET_X86)\n            regs->Eax = retValRegs[0];\n#elif defined(TARGET_ARM)\n            regs->R0 = retValRegs[0];\n#elif defined(TARGET_ARM64)\n            regs->X[0] = retValRegs[0];\n#else\n            PORTABILITY_ASSERT(\"DoGCStress - return register\");\n#endif\n        }\n\n        if (afterCallProtect[1])\n        {\n#if defined(TARGET_AMD64) && defined(TARGET_UNIX)\n            regs->Rdx = retValRegs[numberOfRegs - 1];\n#else \/\/ !TARGET_AMD64 || !TARGET_UNIX\n            _ASSERTE(!\"Not expected multi reg return with pointers.\");\n#endif \/\/ !TARGET_AMD64 || !TARGET_UNIX\n        }\n    }\n\n#if !defined(USE_REDIRECT_FOR_GCSTRESS)\n    frame.Pop(pThread);\n#endif \/\/ USE_REDIRECT_FOR_GCSTRESS\n\n    if (enableWhenDone)\n    {\n        BOOL b = GC_ON_TRANSITIONS(FALSE);      \/\/ Don't do a GCStress 3 GC here\n        pThread->EnablePreemptiveGC();\n        GC_ON_TRANSITIONS(b);\n    }\n\n    return;\n\n}\n\n#endif \/\/ HAVE_GCCOVER\n\n","avg_line_length":36.2256809339,"max_line_length":148,"alphanum_fraction":0.6289090072,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5023,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/=================================================================\r\n\/\/ Copyright 2017 Advanced Micro Devices, Inc. All rights reserved.\r\n\/\/=================================================================\r\n#include <memory>\r\n#include <map>\r\n#include <utility>\r\n#include <sstream>\r\n\/\/ Infra.\r\n#ifdef _WIN32\r\n#pragma warning(push)\r\n#pragma warning(disable:4309)\r\n#endif\r\n#include <AMDTOSWrappers\/Include\/osEnvironmentVariable.h>\r\n#include <AMDTOSWrappers\/Include\/osProcess.h>\r\n#include <Utils\/Include\/rgLog.h>\r\n#ifdef _WIN32\r\n#pragma warning(pop)\r\n#endif\r\n\/\/ Backend.\r\n#include <RadeonGPUAnalyzerBackend\/Include\/beProgramBuilderOpenCL.h>\r\n\/\/ Local.\r\n#include <RadeonGPUAnalyzerCLI\/Src\/kcConfig.h>\r\n#include <RadeonGPUAnalyzerCLI\/Src\/kcParseCmdLine.h>\r\n#include <RadeonGPUAnalyzerCLI\/Src\/kcCLICommanderCL.h>\r\n#include <RadeonGPUAnalyzerCLI\/Src\/kcCliStringConstants.h>\r\n#include <RadeonGPUAnalyzerCLI\/Src\/kcCLICommanderOpenGL.h>\r\n#include <RadeonGPUAnalyzerCLI\/Src\/kcCLICommanderVkOffline.h>\r\n#include <RadeonGPUAnalyzerCLI\/Src\/kcCLICommanderVulkan.h>\r\n#include <RadeonGPUAnalyzerCLI\/Src\/kcUtils.h>\r\n#include <RadeonGPUAnalyzerCLI\/Src\/kcCLICommanderLightning.h>\r\n#ifdef _WIN32\r\n#include <RadeonGPUAnalyzerCLI\/Src\/kcCLICommanderDX11.h>\r\n#include <RadeonGPUAnalyzerCLI\/Src\/kcCLICommanderDX12.h>\r\n#endif\r\nusing namespace beKA;\r\nstatic void loggingCallback(const string& s)\r\n{\r\n    rgLog::stdOut << s.c_str() << std::flush;\r\n}\r\n\/\/ Perform finalizing actions before exiting.\r\nstatic void Shutdown()\r\n{\r\n    rgLog::file << KC_STR_CLI_LOG_CLOSE << std::endl;\r\n    rgLog::Close();\r\n}\r\nint main(int argc, char* argv[])\r\n{\r\n    bool   status = true;\r\n    Config config;\r\n    std::stringstream  msg;\r\n#ifdef _WIN64\r\n    \/\/ Enable 64-bit build for OpenCL.\r\n    osEnvironmentVariable envVar64Bit(STR_OCL_ENV_VAR_GPU_FORCE_64BIT_PTR_NAME, STR_OCL_ENV_VAR_GPU_FORCE_64BIT_PTR_VALUE);\r\n    osSetCurrentProcessEnvVariable(envVar64Bit);\r\n#endif \/\/ _WIN64\r\n    status = status && ParseCmdLine(argc, argv, config);\r\n    status = status && kcUtils::InitCLILogFile(config);\r\n    \/\/ Create corresponding Commander object.\r\n    std::shared_ptr<kcCLICommander> pCommander = nullptr;\r\n    if (status)\r\n    {\r\n        switch (config.m_mode)\r\n        {\r\n        case Mode_None:\r\n            if (config.m_RequestedCommand == Config::ccVersion)\r\n            {\r\n                kcUtils::PrintRgaVersion();\r\n            }\r\n            break;\r\n        case Mode_OpenCL:\r\n            pCommander = std::make_shared<kcCLICommanderCL>();\r\n            break;\r\n#ifdef _WIN32\r\n        case Mode_DX11:\r\n        case Mode_AMDIL:\r\n            pCommander = std::make_shared<kcCLICommanderDX>();\r\n            break;\r\n        case Mode_DX12:\r\n            pCommander = std::make_shared<kcCLICommanderDX12>();\r\n            break;\r\n#endif\r\n        case Mode_OpenGL:\r\n            pCommander = std::make_shared<kcCLICommanderOpenGL>();\r\n            break;\r\n        case Mode_Vk_Offline:\r\n        case Mode_Vk_Offline_Spv:\r\n        case Mode_Vk_Offline_SpvTxt:\r\n            pCommander = std::make_shared<kcCLICommanderVkOffline>();\r\n            break;\r\n        case Mode_Vulkan:\r\n            pCommander = std::make_shared<kcCLICommanderVulkan>();\r\n            break;\r\n        case Mode_Rocm_OpenCL:\r\n        {\r\n            pCommander = std::make_shared<kcCLICommanderLightning>();\r\n            if (static_cast<kcCLICommanderLightning&>(*pCommander).Init(config, loggingCallback) != beKA::beStatus_SUCCESS)\r\n            {\r\n                rgLog::stdErr << STR_ERR_INITIALIZATION_FAILURE << std::endl;\r\n                status = false;\r\n            }\r\n            break;\r\n        }\r\n        }\r\n    }\r\n    \/\/ Perform requested actions.\r\n    if (status && pCommander != nullptr)\r\n    {\r\n        switch (config.m_RequestedCommand)\r\n        {\r\n        case Config::ccCompile:\r\n        case Config::ccGenTemplateFile:\r\n            pCommander->RunCompileCommands(config, loggingCallback);\r\n            \/\/ Perform post-compile steps\r\n            pCommander->RunPostCompileSteps(config);\r\n            break;\r\n        case Config::ccListEntries:\r\n            pCommander->ListEntries(config, loggingCallback);\r\n            break;\r\n        case Config::ccListAsics:\r\n            if (!pCommander->PrintAsicList(config))\r\n            {\r\n                rgLog::stdOut << STR_ERR_CANNOT_EXTRACT_SUPPORTED_DEVICE_LIST << std::endl;\r\n                status = false;\r\n            }\r\n            break;\r\n        case Config::ccListAdapters:\r\n            pCommander->ListAdapters(config, loggingCallback);\r\n            break;\r\n        case Config::ccVersion:\r\n            pCommander->Version(config, loggingCallback);\r\n            break;\r\n        case Config::ccInvalid:\r\n            rgLog::stdOut << STR_ERR_NO_VALID_CMD_DETECTED << std::endl;\r\n            status = false;\r\n            break;\r\n        }\r\n    }\r\n    else if (status && config.m_RequestedCommand == Config::ccGenVersionInfoFile)\r\n    {\r\n        kcCLICommander::GenerateVersionInfoFile(config);\r\n    }\r\n    Shutdown();\r\n    return 0;\r\n}","avg_line_length":34.8819444444,"max_line_length":124,"alphanum_fraction":0.6147720486,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1133,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":25.0,"content":"\n#include \"test_instructions.h\"\n#include \"ppc\/instruction.h\"\n\nvoid TestInstruction::run() {\n    TEST_METHOD(test_build)\n    TEST_METHOD(test_copy)\n    TEST_METHOD(test_move)\n    TEST_METHOD(test_code_name)\n    TEST_METHOD(test_get_variables)\n    TEST_METHOD(test_used_registers)\n    TEST_METHOD(test_destination_registers)\n    TEST_METHOD(test_source_registers)\n}\n\nvoid TestInstruction::test_build() {\n    throw testing::skip_test();\n}\n\nvoid TestInstruction::test_copy() {\n    throw testing::skip_test();\n}\n\nvoid TestInstruction::test_move() {\n    throw testing::skip_test();\n}\n\nvoid TestInstruction::test_code_name() {\n    throw testing::skip_test();\n}\n\nvoid TestInstruction::test_get_variables() {\n    throw testing::skip_test();\n}\n\nvoid TestInstruction::test_used_registers() {\n    throw testing::skip_test();\n}\n\nvoid TestInstruction::test_destination_registers() {\n    throw testing::skip_test();\n}\n\nvoid TestInstruction::test_source_registers() {\n    throw testing::skip_test();\n}\n\nvoid test_condition() {\n    throw testing::skip_test();\n}\n\nvoid run_instructions_tests() {\n    TEST(TestInstruction())\n    TEST(test_condition)\n}\n","avg_line_length":20.2321428571,"max_line_length":52,"alphanum_fraction":0.733451015,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2407,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2012-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"script\/script.h\"\n#include \"test\/test_stp.h\"\n\n#include <boost\/test\/unit_test.hpp>\n\nusing namespace std;\n\nBOOST_FIXTURE_TEST_SUITE(script_P2PK_tests, BasicTestingSetup)\n\n    BOOST_AUTO_TEST_CASE(ispaytopublickey_test)\n    {\n        BOOST_TEST_MESSAGE(\"Running IsPayToPublicKey Test\");\n\n        \/\/ Test CScript::IsPayToPublicKey()\n        static const unsigned char p2pkcompressedeven[] = {\n                0x41, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OP_CHECKSIG\n        };\n        BOOST_CHECK(CScript(p2pkcompressedeven, p2pkcompressedeven + sizeof(p2pkcompressedeven)).IsPayToPublicKey());\n\n        static const unsigned char p2pkcompressedodd[] = {\n                0x41, 0x03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OP_CHECKSIG\n        };\n        BOOST_CHECK(CScript(p2pkcompressedodd, p2pkcompressedodd + sizeof(p2pkcompressedodd)).IsPayToPublicKey());\n\n        static const unsigned char p2pkuncompressed[] = {\n                0x41, 0x04, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OP_CHECKSIG\n        };\n        BOOST_CHECK(CScript(p2pkuncompressed, p2pkuncompressed + sizeof(p2pkuncompressed)).IsPayToPublicKey());\n\n        static const unsigned char missingop[] = {\n                0x41, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n        };\n        BOOST_CHECK(!CScript(missingop, missingop + sizeof(missingop)).IsPayToPublicKey());\n\n        static const unsigned char wrongop[] = {\n                0x41, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OP_EQUALVERIFY\n        };\n        BOOST_CHECK(!CScript(wrongop, wrongop + sizeof(wrongop)).IsPayToPublicKey());\n\n        static const unsigned char tooshort[] = {\n                0x41, 0x02, 0, 0, OP_CHECKSIG\n        };\n        BOOST_CHECK(!CScript(tooshort, tooshort + sizeof(tooshort)).IsPayToPublicKey());\n\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":45.4150943396,"max_line_length":138,"alphanum_fraction":0.5857914416,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":672,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":4879.0,"content":"#include \"drape_frontend\/threads_commutator.hpp\"\n\n#include \"drape_frontend\/base_renderer.hpp\"\n\n#include \"base\/assert.hpp\"\n\n#include <utility>\n\nnamespace df\n{\n\nvoid ThreadsCommutator::RegisterThread(ThreadName name, BaseRenderer * acceptor)\n{\n  VERIFY(m_acceptors.insert(std::make_pair(name, acceptor)).second, ());\n}\n\nvoid ThreadsCommutator::PostMessage(ThreadName name, drape_ptr<Message> && message, MessagePriority priority)\n{\n  TAcceptorsMap::iterator it = m_acceptors.find(name);\n  ASSERT(it != m_acceptors.end(), ());\n  if (it != m_acceptors.end() && it->second->CanReceiveMessages())\n    it->second->PostMessage(std::move(message), priority);\n}\n\n} \/\/ namespace df\n\n","avg_line_length":24.8888888889,"max_line_length":109,"alphanum_fraction":0.7410714286,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":9031,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":20.0,"content":"#include <cassert>\n#include <stdexcept>\n#include <fcntl.h>\n#include <unistd.h>\n#include <poll.h>\n#include <sys\/eventfd.h>\n\n#include \"config\/op_config_file.hpp\"\n#include \"core\/op_log.h\"\n#include \"core\/op_thread.h\"\n#include \"timesync\/bintime.hpp\"\n#include \"utils\/random.hpp\"\n\n#include \"network\/arg_parser.hpp\"\n#include \"network\/utils\/network_sockaddr.hpp\"\n#include \"protocol.hpp\"\n#include \"server_udp.hpp\"\n\nnamespace openperf::network::internal::firehose {\n\ntl::expected<int, std::string> server_udp::new_server(\n    int domain, in_port_t port, const std::optional<std::string>& interface)\n{\n    struct sockaddr_storage client_storage;\n    auto* server_ptr = reinterpret_cast<sockaddr*>(&client_storage);\n\n    switch (domain) {\n    case AF_INET: {\n        auto* server4 = reinterpret_cast<sockaddr_in*>(server_ptr);\n        server4->sin_family = AF_INET;\n        server4->sin_port = htons(port);\n        server4->sin_addr.s_addr = htonl(INADDR_ANY);\n        break;\n    }\n    case AF_INET6: {\n        auto* server6 = reinterpret_cast<sockaddr_in6*>(server_ptr);\n        server6->sin6_family = AF_INET6;\n        server6->sin6_port = htons(port);\n        server6->sin6_addr = in6addr_any;\n        break;\n    }\n    default:\n        return tl::make_unexpected<std::string>(strerror(EINVAL));\n    }\n\n    int sock = 0, enable = true;\n    if ((sock = m_driver->socket(domain, SOCK_DGRAM, 0)) == -1) {\n        OP_LOG(OP_LOG_ERROR,\n               \"Unable to open %s UDP server socket: %s\\n\",\n               (domain == AF_INET6) ? \"IPv6\" : \"IPv4\",\n               strerror(errno));\n        return tl::make_unexpected<std::string>(strerror(errno));\n    }\n\n    if (interface) {\n        if (m_driver->setsockopt(sock,\n                                 SOL_SOCKET,\n                                 SO_BINDTODEVICE,\n                                 interface.value().c_str(),\n                                 interface.value().size())\n            < 0) {\n            auto err = errno;\n            m_driver->close(sock);\n            return tl::make_unexpected<std::string>(strerror(err));\n        }\n    }\n\n    if (m_driver->setsockopt(\n            sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable))\n        != 0) {\n        auto err = errno;\n        m_driver->close(sock);\n        return tl::make_unexpected<std::string>(strerror(err));\n    }\n\n    \/* Update to non-blocking socket *\/\n    int flags = m_driver->fcntl(sock, F_GETFL);\n    if (flags == -1) {\n        auto err = errno;\n        m_driver->close(sock);\n        return tl::make_unexpected(strerror(err));\n    }\n\n    if (m_driver->fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1) {\n        auto err = errno;\n        m_driver->close(sock);\n        return tl::make_unexpected(strerror(err));\n    }\n\n    if (m_driver->bind(sock, server_ptr, get_sa_len(server_ptr)) == -1) {\n        OP_LOG(OP_LOG_ERROR,\n               \"Unable to bind to socket (domain = %d, protocol = UDP): %s\\n\",\n               domain,\n               strerror(errno));\n        auto err = errno;\n        m_driver->close(sock);\n        return tl::make_unexpected<std::string>(strerror(err));\n    }\n\n    static auto read_timeout =\n        timesync::to_timeval(config::operation_timeout());\n    if (m_driver->setsockopt(\n            sock, SOL_SOCKET, SO_RCVTIMEO, &read_timeout, sizeof(read_timeout))\n        != 0) {\n        OP_LOG(OP_LOG_WARNING,\n               \"Unable to set socket timeout (domain = %d, protocol = \"\n               \"UDP): %s\\n\",\n               domain,\n               strerror(errno));\n    }\n\n    return sock;\n}\n\nserver_udp::server_udp(in_port_t port,\n                       const std::optional<std::string>& interface,\n                       const drivers::driver_ptr& driver)\n    : m_stopped(false)\n{\n    m_driver = driver;\n\n    m_eventfd = eventfd(0, EFD_NONBLOCK);\n    if (m_eventfd < 0) {\n        throw std::system_error(\n            errno, std::generic_category(), \"Failed to create eventfd\");\n    }\n\n    \/* IPv6 any supports IPv4 and IPv6 *\/\n    tl::expected<int, std::string> res;\n    if ((res = new_server(AF_INET6, port, interface)); res) {\n        OP_LOG(OP_LOG_DEBUG, \"Network UDP load server IPv4\/IPv6.\\n\");\n    } else if ((res = new_server(AF_INET, port, interface)); res) {\n        OP_LOG(OP_LOG_DEBUG, \"Network UDP load server IPv4.\\n\");\n    } else {\n        throw std::runtime_error(\"Cannot create UDP server: \" + res.error());\n    }\n\n    m_fd = res.value();\n\n    run_worker_thread();\n}\n\nserver_udp::~server_udp()\n{\n    m_stopped.store(true, std::memory_order_relaxed);\n    eventfd_write(m_eventfd, 1);\n    if (m_worker_thread.joinable()) m_worker_thread.join();\n\n    if (m_fd.load() >= 0) { m_driver->close(m_fd); }\n\n    close(m_eventfd);\n}\n\n\/\/ One worker for udp\nvoid server_udp::run_worker_thread()\n{\n    m_worker_thread = std::thread([&] {\n        \/\/ Set the thread name\n        op_thread_setname(\"op_net_srv_w\");\n\n        ssize_t recv_or_err = 0;\n        connection_t conn = {\n            .fd = m_fd, .state = STATE_WAITING, .bytes_left = 0};\n        sockaddr_storage client_storage;\n        auto* client = reinterpret_cast<sockaddr*>(&client_storage);\n        socklen_t client_length = sizeof(struct sockaddr_in6);\n\n        std::vector<uint8_t> read_buffer(net_request_size);\n        std::vector<uint8_t> send_buffer(send_buffer_size);\n        utils::op_prbs23_fill(send_buffer.data(), send_buffer.size());\n\n        while (!m_stopped.load(std::memory_order_relaxed)) {\n            \/\/ Wait for rx data or eventfd notification\n            std::array<struct pollfd, 2> pfd;\n            pfd[0] = {.fd = m_eventfd, .events = POLLIN, .revents = 0};\n            pfd[1] = {.fd = m_fd, .events = POLLIN, .revents = 0};\n            int npoll = poll(pfd.data(), pfd.size(), -1);\n            if (npoll < 0 && errno != EINTR) {\n                OP_LOG(OP_LOG_ERROR, \"poll failed.  %s\", strerror(errno));\n                break;\n            }\n            if (npoll <= 0) { continue; }\n\n            if (pfd[0].revents & POLLIN) {\n                eventfd_t value = 0;\n                eventfd_read(m_eventfd, &value);\n            }\n\n            while ((recv_or_err = m_driver->recvfrom(m_fd,\n                                                     read_buffer.data(),\n                                                     read_buffer.size(),\n                                                     0,\n                                                     client,\n                                                     &client_length))\n                   != -1) {\n                uint8_t* recv_cursor = read_buffer.data();\n                size_t bytes_left = recv_or_err;\n                m_stat.bytes_received += recv_or_err;\n                m_stat.connections++;\n\n                auto req = firehose::parse_request(recv_cursor, bytes_left);\n                if (!req) {\n                    char ntopbuf[INET6_ADDRSTRLEN];\n                    const char* addr = inet_ntop(client->sa_family,\n                                                 get_sa_addr(client),\n                                                 ntopbuf,\n                                                 INET6_ADDRSTRLEN);\n                    OP_LOG(OP_LOG_ERROR,\n                           \"Invalid firehose request received \"\n                           \"from %s:%d\\n\",\n                           addr ? addr : \"unknown\",\n                           ntohs(get_sa_port(client)));\n                    OP_LOG(OP_LOG_ERROR,\n                           \"recv = %zu, bytes_left = %zu\\n\",\n                           recv_or_err,\n                           bytes_left);\n                    continue;\n                }\n                conn.state = (req.value().action == action_t::GET)\n                                 ? STATE_WRITING\n                                 : STATE_READING;\n                conn.bytes_left = req.value().length;\n                bytes_left -= firehose::net_request_size;\n                recv_cursor += firehose::net_request_size;\n\n                while (conn.state == STATE_WRITING && conn.bytes_left) {\n                    size_t produced =\n                        std::min(send_buffer.size(), conn.bytes_left);\n                    ssize_t send_or_err = m_driver->sendto(m_fd,\n                                                           send_buffer.data(),\n                                                           produced,\n                                                           0,\n                                                           client,\n                                                           client_length);\n                    if (send_or_err == -1) {\n                        conn.state = STATE_ERROR;\n                        conn.bytes_left = 0;\n                        m_stat.errors++;\n                    } else {\n                        conn.bytes_left -= send_or_err;\n                        m_stat.bytes_sent += send_or_err;\n                    }\n                }\n                m_stat.closed++;\n            }\n        }\n        op_log_close();\n    });\n}\n\n} \/\/ namespace openperf::network::internal::firehose\n","avg_line_length":35.8373015873,"max_line_length":79,"alphanum_fraction":0.5027128779,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4603,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"#if defined _MSC_VER || defined __CYGWIN__ || defined _WIN32\n#define _CRT_SECURE_NO_WARNINGS\n# ifndef WIN32_LEAN_AND_MEAN\n#  define WIN32_LEAN_AND_MEAN\n# endif\n# ifndef NOMINMAX\n#  define NOMINMAX\n# endif\n#endif\n#if defined _WIN32 || defined __CYGWIN__\n#  include <windows.h>\n#else\n#  include <pthread.h>\n#  include <string.h>\n#  include <unistd.h>\n#endif\n\n#ifdef __linux__\n#  ifndef __ANDROID__\n#    include <syscall.h>\n#  endif\n#  include <fcntl.h>\n#endif\n\n#ifdef __MINGW32__\n#  define __STDC_FORMAT_MACROS\n#endif\n#include <inttypes.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"TracySystem.hpp\"\n\n#ifdef TRACY_ENABLE\n#  include <atomic>\n#  include \"TracyAlloc.hpp\"\n#endif\n\nnamespace tracy\n{\n\n#ifdef TRACY_ENABLE\nstruct ThreadNameData\n{\n    uint64_t id;\n    const char* name;\n    ThreadNameData* next;\n};\nTRACY_API std::atomic<ThreadNameData*>& GetThreadNameData();\nTRACY_API void InitRPMallocThread();\n#endif\n\nvoid SetThreadName( const char* name )\n{\n#if defined _WIN32 && !defined PTW32_VERSION && !defined __WINPTHREADS_VERSION\n#  if defined NTDDI_WIN10_RS2 && NTDDI_VERSION >= NTDDI_WIN10_RS2\n    wchar_t buf[256];\n    mbstowcs( buf, name, 256 );\n    SetThreadDescription( GetCurrentThread(), buf );\n#  else\n    const DWORD MS_VC_EXCEPTION=0x406D1388;\n#    pragma pack( push, 8 )\n    struct THREADNAME_INFO\n    {\n        DWORD dwType;\n        LPCSTR szName;\n        DWORD dwThreadID;\n        DWORD dwFlags;\n    };\n#    pragma pack(pop)\n\n    DWORD ThreadId = GetCurrentThreadId();\n    THREADNAME_INFO info;\n    info.dwType = 0x1000;\n    info.szName = name;\n    info.dwThreadID = ThreadId;\n    info.dwFlags = 0;\n\n    __try\n    {\n        RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)\/sizeof(ULONG_PTR), (ULONG_PTR*)&info );\n    }\n    __except(EXCEPTION_EXECUTE_HANDLER)\n    {\n    }\n#  endif\n#elif defined _GNU_SOURCE && !defined __EMSCRIPTEN__ && !defined __CYGWIN__\n    {\n        const auto sz = strlen( name );\n        if( sz <= 15 )\n        {\n            pthread_setname_np( pthread_self(), name );\n        }\n        else\n        {\n            char buf[16];\n            memcpy( buf, name, 15 );\n            buf[15] = '\\0';\n            pthread_setname_np( pthread_self(), buf );\n        }\n    }\n#endif\n#ifdef TRACY_ENABLE\n    {\n        InitRPMallocThread();\n        const auto sz = strlen( name );\n        char* buf = (char*)tracy_malloc( sz+1 );\n        memcpy( buf, name, sz );\n        buf[sz+1] = '\\0';\n        auto data = (ThreadNameData*)tracy_malloc( sizeof( ThreadNameData ) );\n        data->id = detail::GetThreadHandleImpl();\n        data->name = buf;\n        data->next = GetThreadNameData().load( std::memory_order_relaxed );\n        while( !GetThreadNameData().compare_exchange_weak( data->next, data, std::memory_order_release, std::memory_order_relaxed ) ) {}\n    }\n#endif\n}\n\nconst char* GetThreadName( uint64_t id )\n{\n    static char buf[256];\n#ifdef TRACY_ENABLE\n    auto ptr = GetThreadNameData().load( std::memory_order_relaxed );\n    while( ptr )\n    {\n        if( ptr->id == id )\n        {\n            return ptr->name;\n        }\n        ptr = ptr->next;\n    }\n#endif\n#if 1\n#  ifdef _WIN32\n\/\/#    if defined NTDDI_WIN10_RS2 && NTDDI_VERSION >= NTDDI_WIN10_RS2\n    auto hnd = OpenThread( THREAD_QUERY_LIMITED_INFORMATION, FALSE, (DWORD)id );\n    if( hnd != 0 )\n    {\n        PWSTR tmp;\n        GetThreadDescription( hnd, &tmp );\n        auto vret = wcstombs( buf, tmp, sizeof(buf) );\n        CloseHandle( hnd );\n        if(vret != 0 )\n        {\n            return buf;\n        }\n    }\n\/\/#    endif\n#  elif defined __GLIBC__ && !defined __ANDROID__ && !defined __EMSCRIPTEN__ && !defined __CYGWIN__\n    if( pthread_getname_np( (pthread_t)id, buf, 256 ) == 0 )\n    {\n        return buf;\n    }\n#  elif defined __linux__\n    int cs, fd;\n    char path[32];\n#   ifdef __ANDROID__\n    int tid = gettid();\n#   else\n    int tid = (int) syscall( SYS_gettid );\n#   endif\n    snprintf( path, sizeof( path ), \"\/proc\/self\/task\/%d\/comm\", tid );\n    sprintf( buf, \"%\" PRIu64, id );\n#   ifndef __ANDROID__\n    pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, &cs );\n#   endif\n    if ( ( fd = open( path, O_RDONLY ) ) > 0) {\n        int len = read( fd, buf, 255 );\n        if( len > 0 )\n        {\n            buf[len] = 0;\n            if( len > 1 && buf[len-1] == '\\n' )\n            {\n                buf[len-1] = 0;\n            }\n        }\n        close( fd );\n    }\n#   ifndef __ANDROID__\n    pthread_setcancelstate( cs, 0 );\n#   endif\n    return buf;\n#  endif\n#endif\n#ifdef _MSC_VER\n\tsprintf_s(buf, \"%\" PRIu64, id);\n#else\n    sprintf( buf, \"%\" PRIu64, id );\n#endif\n    return buf;\n}\n\n}\n","avg_line_length":23.7268041237,"max_line_length":136,"alphanum_fraction":0.6017814469,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1107,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"class Solution {\npublic:\n    vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {\n        int soldiers=0;\n        vector<int> index;\n        set<pair<int,int>> m;  \/\/changed to set from unordered_map and map as they doesn't store repeated values\n\n        for(int i=0; i<mat.size(); i++)\n        {\n            for(int j=0; j<mat[i].size(); j++)\n            {\n                \/\/if we encounter a '1' while traversing, increment the soldier variable\n                if(mat[i][j]==1)\n                    soldiers++;\n            }\n            \/\/insert the no. of soldiers and the current row they are present in, in a set\n            m.insert({soldiers, i});\n\n            \/\/resetting the count of no. of soldiers to 0 after iterating each row\n            soldiers=0;\n        }\n\n        for(auto itr: m)\n        {\n            if(k==0)\n                break;\n            \/\/pushing the k weakest rows in the index vector\n            index.push_back(itr.second);\n            k--;\n        }\n        return index;\n    }\n};\n\n\/*\n   TC:- O(nlogn), where n=no. of rows\n   SC:- O(n), n=no. of rows(pair in a set)\n*\/\n","avg_line_length":28.3846153846,"max_line_length":112,"alphanum_fraction":0.4995483288,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":629,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":5.0,"content":"#include<iostream>\n#include<bits\/stdc++.h>\nusing namespace std;\n#define ll long long\n#define mp make_pair\n#define pb push_back\n\n\nint main() {\n    int n; cin>>n;\n    int arr[n];\n    for(int i=0; i<n; i++) cin>>arr[i];\n    int q; cin>>q;\n    int sum[n];\n    sum[0] = arr[0];\n\n    for(int i=1; i<n; i++){\n        sum[i] = arr[i] + sum[i-1];\n    }\n\n    while(q--){\n        int a,b;\n        cin>>a>>b;\n        if(a==b) {\n            cout<<arr[a]<<endl;\n            continue;\n        }\n\n        if(a!=0){\n            cout<<sum[b]-sum[a-1]<<endl;\n        }\n        else {\n            cout<<sum[b]<<endl;\n        }\n    }\n\n    return 0;\n}","avg_line_length":16.5526315789,"max_line_length":40,"alphanum_fraction":0.4276629571,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":26116,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/*\n * Copyright (c) 2018, Arm Limited and affiliates.\n * SPDX-License-Identifier: Apache-2.0\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"CellularStateMachine.h\"\n#include \"CellularDevice.h\"\n#include \"CellularLog.h\"\n#include \"Thread.h\"\n\n#ifndef MBED_TRACE_MAX_LEVEL\n#define MBED_TRACE_MAX_LEVEL TRACE_LEVEL_INFO\n#endif\n\n\/\/ timeout to wait for AT responses\n#define TIMEOUT_POWER_ON     (1*1000)\n#define TIMEOUT_SIM_PIN      (1*1000)\n#define TIMEOUT_NETWORK      (10*1000)\n\/** CellularStateMachine does connecting up to packet service attach, and\n *  after that it's up to CellularContext::connect() to connect to PDN.\n *  If CellularContext or an application does not set timeout (via `CellularDevice::set_timeout`)\n *  then TIMEOUT_CONNECT is used also for connecting to PDN and also for socket operations.\n *\/\n#define TIMEOUT_CONNECT      (60*1000)\n#define TIMEOUT_REGISTRATION (180*1000)\n\n\/\/ maximum time when retrying network register, attach and connect in seconds ( 20minutes )\n#define TIMEOUT_NETWORK_MAX (20*60)\n\n#define RETRY_COUNT_DEFAULT 3\n\n\nconst int STM_STOPPED = -99;\nconst int ACTIVE_PDP_CONTEXT = 0x01;\nconst int ATTACHED_TO_NETWORK = 0x02;\nconst int DEVICE_READY = 0x04;\n\nnamespace mbed {\n\nCellularStateMachine::CellularStateMachine(CellularDevice &device, events::EventQueue &queue, CellularNetwork &nw) :\n    _cellularDevice(device), _state(STATE_INIT), _next_state(_state), _target_state(_state),\n    _event_status_cb(0), _network(nw), _queue(queue), _queue_thread(0), _sim_pin(0),\n    _retry_count(0), _event_timeout(-1), _event_id(-1), _plmn(0), _command_success(false),\n    _is_retry(false), _cb_data(), _current_event(CellularDeviceReady), _status(0)\n{\n#if MBED_CONF_CELLULAR_RANDOM_MAX_START_DELAY == 0\n    _start_time = 0;\n#else\n    \/\/ so that not every device don't start at the exact same time (for example after power outage)\n    _start_time = rand() % (MBED_CONF_CELLULAR_RANDOM_MAX_START_DELAY);\n#endif \/\/ MBED_CONF_CELLULAR_RANDOM_MAX_START_DELAY\n\n    \/\/ set initial retry values in seconds\n    _retry_timeout_array[0] = 1; \/\/ double time on each retry in order to keep network happy\n    _retry_timeout_array[1] = 2;\n    _retry_timeout_array[2] = 4;\n    _retry_timeout_array[3] = 8;\n    _retry_timeout_array[4] = 16;\n    _retry_timeout_array[5] = 32;\n    _retry_timeout_array[6] = 64;\n    _retry_timeout_array[7] = 128; \/\/ if around two minutes was not enough then let's wait much longer\n    _retry_timeout_array[8] = 600;\n    _retry_timeout_array[9] = TIMEOUT_NETWORK_MAX;\n    _retry_array_length = CELLULAR_RETRY_ARRAY_SIZE;\n\n    _state_timeout_power_on = TIMEOUT_POWER_ON;\n    _state_timeout_sim_pin = TIMEOUT_SIM_PIN;\n    _state_timeout_registration = TIMEOUT_REGISTRATION;\n    _state_timeout_network = TIMEOUT_NETWORK;\n    _state_timeout_connect = TIMEOUT_CONNECT;\n}\n\nCellularStateMachine::~CellularStateMachine()\n{\n    tr_debug(\"CellularStateMachine destruct\");\n    stop();\n}\n\nvoid CellularStateMachine::reset()\n{\n    _state = STATE_INIT;\n    _event_timeout = -1;\n    _event_id = -1;\n    _is_retry = false;\n    _status = 0;\n    _target_state = STATE_INIT;\n    enter_to_state(STATE_INIT);\n}\n\nvoid CellularStateMachine::stop()\n{\n    tr_debug(\"CellularStateMachine stop\");\n    if (_queue_thread) {\n        _queue_thread->terminate();\n        delete _queue_thread;\n        _queue_thread = NULL;\n    }\n\n    reset();\n    _event_id = STM_STOPPED;\n}\n\nbool CellularStateMachine::power_on()\n{\n    _cb_data.error = _cellularDevice.hard_power_on();\n    if (_cb_data.error != NSAPI_ERROR_OK) {\n        tr_warn(\"Hard power on failed.\");\n        return false;\n    }\n    return true;\n}\n\nvoid CellularStateMachine::set_sim_pin(const char *sim_pin)\n{\n    _sim_pin = sim_pin;\n}\n\nvoid CellularStateMachine::set_plmn(const char *plmn)\n{\n    _plmn = plmn;\n}\n\nbool CellularStateMachine::open_sim()\n{\n    CellularDevice::SimState state = CellularDevice::SimStateUnknown;\n    \/\/ wait until SIM is readable\n    \/\/ here you could add wait(secs) if you know start delay of your SIM\n    _cb_data.error = _cellularDevice.get_sim_state(state);\n    if (_cb_data.error != NSAPI_ERROR_OK) {\n        tr_info(\"Waiting for SIM (err while reading)...\");\n        return false;\n    }\n\n    \/\/ report current state so callback can set sim pin if needed\n    _cb_data.status_data = state;\n    send_event_cb(CellularSIMStatusChanged);\n\n    if (state == CellularDevice::SimStatePinNeeded) {\n        if (_sim_pin) {\n            tr_info(\"Entering PIN to open SIM\");\n            _cb_data.error = _cellularDevice.set_pin(_sim_pin);\n            if (_cb_data.error) {\n                tr_error(\"Failed to set PIN: error %d\", _cb_data.error);\n            }\n        } else {\n            \/\/ No sim pin provided even it's needed, stop state machine\n            tr_error(\"PIN required but no SIM pin provided.\");\n            _retry_count = CELLULAR_RETRY_ARRAY_SIZE;\n            return false;\n        }\n    }\n\n    bool sim_ready = state == CellularDevice::SimStateReady;\n\n    if (sim_ready) {\n        _cb_data.error = _network.set_registration(_plmn);\n        tr_debug(\"STM: set_registration: %d, plmn: %s\", _cb_data.error, _plmn ? _plmn : \"NULL\");\n        if (_cb_data.error) {\n            return false;\n        }\n    }\n\n    return sim_ready;\n}\n\nbool CellularStateMachine::is_registered()\n{\n    CellularNetwork::RegistrationStatus status;\n    bool is_registered = false;\n\n    \/\/ accept only CGREG\/CEREG. CREG is for circuit switch network changed. If we accept CREG attach will fail if also\n    \/\/ CGREG\/CEREG is not registered.\n    for (int type = 0; type < CellularNetwork::C_REG; type++) {\n        if (get_network_registration((CellularNetwork::RegistrationType) type, status, is_registered)) {\n            if (is_registered) {\n                break;\n            }\n        }\n    }\n\n    _cb_data.status_data = status;\n    \/\/ in manual registering we are forcing registration to certain network so we don't accept active context or attached\n    \/\/ as indication that device is registered to correct network.\n    if (_plmn && strlen(_plmn)) {\n        return is_registered;\n    }\n    return is_registered || _status;\n}\n\nbool CellularStateMachine::get_network_registration(CellularNetwork::RegistrationType type,\n                                                    CellularNetwork::RegistrationStatus &status, bool &is_registered)\n{\n    is_registered = false;\n    bool is_roaming = false;\n    CellularNetwork::registration_params_t reg_params;\n    _cb_data.error = _network.get_registration_params(type, reg_params);\n\n    if (_cb_data.error != NSAPI_ERROR_OK) {\n        if (_cb_data.error != NSAPI_ERROR_UNSUPPORTED) {\n            tr_warn(\"Get network registration failed (type %d)!\", type);\n        }\n        return false;\n    }\n    status = reg_params._status;\n    switch (status) {\n        case CellularNetwork::RegisteredRoaming:\n            is_roaming = true;\/\/ @suppress(\"No break at end of case\")\n        \/\/ fall-through\n        case CellularNetwork::RegisteredHomeNetwork:\n            is_registered = true;\n            break;\n        case CellularNetwork::RegisteredSMSOnlyRoaming:\n            is_roaming = true;\/\/ @suppress(\"No break at end of case\")\n        \/\/ fall-through\n        case CellularNetwork::RegisteredSMSOnlyHome:\n            tr_warn(\"SMS only network registration!\");\n            break;\n        case CellularNetwork::RegisteredCSFBNotPreferredRoaming:\n            is_roaming = true; \/\/ @suppress(\"No break at end of case\")\n        \/\/ fall-through\n        case CellularNetwork::RegisteredCSFBNotPreferredHome:\n            tr_warn(\"Not preferred network registration!\");\n            break;\n        case CellularNetwork::AttachedEmergencyOnly:\n            tr_warn(\"Emergency only network registration!\");\n            break;\n        case CellularNetwork::RegistrationDenied:\n        case CellularNetwork::NotRegistered:\n        case CellularNetwork::Unknown:\n        case CellularNetwork::SearchingNetwork:\n        default:\n            break;\n    }\n\n    if (is_roaming) {\n        tr_info(\"Roaming network.\");\n    }\n\n    return true;\n}\n\nvoid CellularStateMachine::report_failure(const char *msg)\n{\n    tr_error(\"CellularStateMachine failure: %s\", msg);\n\n    _event_id = -1;\n    _cb_data.final_try = true;\n    send_event_cb(_current_event);\n\n    tr_error(\"CellularStateMachine target state %s, current state %s\", get_state_string(_target_state), get_state_string(_state));\n}\n\nconst char *CellularStateMachine::get_state_string(CellularState state) const\n{\n#if MBED_CONF_MBED_TRACE_ENABLE\n    static const char *strings[STATE_MAX_FSM_STATE] = { \"Init\", \"Power\", \"Device ready\", \"SIM pin\", \"Signal quality\", \"Registering network\", \"Attaching network\"};\n    return strings[state];\n#else\n    return NULL;\n#endif \/\/ #if MBED_CONF_MBED_TRACE_ENABLE\n}\n\nvoid CellularStateMachine::enter_to_state(CellularState state)\n{\n    _next_state = state;\n    _retry_count = 0;\n    _command_success = false;\n    _cb_data.error = NSAPI_ERROR_OK;\n    _cb_data.status_data = -1;\n    _cb_data.final_try = false;\n}\n\nvoid CellularStateMachine::retry_state_or_fail()\n{\n    if (_retry_count < _retry_array_length) {\n        tr_debug(\"%s: retry %d\/%d\", get_state_string(_state), _retry_count, _retry_array_length);\n        \/\/ send info to application\/driver about error logic so it can implement proper error logic\n        _cb_data.status_data = _current_event;\n        _cb_data.data = &_retry_count;\n        _cb_data.error = NSAPI_ERROR_OK;\n        send_event_cb(CellularStateRetryEvent);\n\n        _event_timeout = _retry_timeout_array[_retry_count];\n        _is_retry = true;\n        _cb_data.error = NSAPI_ERROR_OK;\n        _retry_count++;\n    } else {\n        _cb_data.final_try = true;\n        report_failure(get_state_string(_state));\n    }\n}\n\nvoid CellularStateMachine::state_init()\n{\n    change_timeout(_state_timeout_power_on);\n    tr_info(\"Start connecting (timeout %d ms)\", _state_timeout_power_on);\n    _cb_data.error = _cellularDevice.is_ready();\n    _status = _cb_data.error ? 0 : DEVICE_READY;\n    if (_cb_data.error != NSAPI_ERROR_OK) {\n        _event_timeout = _start_time;\n        if (_start_time > 0) {\n            tr_info(\"Startup delay %d ms\", _start_time);\n        }\n        enter_to_state(STATE_POWER_ON);\n    } else {\n        enter_to_state(STATE_DEVICE_READY);\n    }\n}\n\nvoid CellularStateMachine::state_power_on()\n{\n    change_timeout(_state_timeout_power_on);\n    tr_info(\"Modem power ON (timeout %d ms)\", _state_timeout_power_on);\n    if (power_on()) {\n        enter_to_state(STATE_DEVICE_READY);\n    } else {\n        \/\/ retry to power on device\n        retry_state_or_fail();\n    }\n}\n\nbool CellularStateMachine::device_ready()\n{\n    tr_info(\"Modem ready\");\n\n#ifdef MBED_CONF_CELLULAR_RADIO_ACCESS_TECHNOLOGY\n    MBED_ASSERT(MBED_CONF_CELLULAR_RADIO_ACCESS_TECHNOLOGY >= CellularNetwork::RAT_GSM &&\n                MBED_CONF_CELLULAR_RADIO_ACCESS_TECHNOLOGY < CellularNetwork::RAT_UNKNOWN);\n    nsapi_error_t err = _network.set_access_technology((CellularNetwork::RadioAccessTechnology)MBED_CONF_CELLULAR_RADIO_ACCESS_TECHNOLOGY);\n    if (err != NSAPI_ERROR_OK && err != NSAPI_ERROR_UNSUPPORTED) {\n        tr_warning(\"Failed to set access technology to %d\", MBED_CONF_CELLULAR_RADIO_ACCESS_TECHNOLOGY);\n        return false;\n    }\n#endif \/\/ MBED_CONF_CELLULAR_DEBUG_AT\n\n    send_event_cb(CellularDeviceReady);\n    _cellularDevice.set_ready_cb(0);\n\n    return true;\n}\n\nvoid CellularStateMachine::state_device_ready()\n{\n    change_timeout(_state_timeout_power_on);\n    if (!(_status & DEVICE_READY)) {\n        tr_debug(\"Device was not ready, calling soft_power_on()\");\n        _cb_data.error = _cellularDevice.soft_power_on();\n    }\n    if (_cb_data.error == NSAPI_ERROR_OK) {\n        _cb_data.error = _cellularDevice.init();\n        if (_cb_data.error == NSAPI_ERROR_OK) {\n            if (device_ready()) {\n                _status = 0;\n                enter_to_state(STATE_SIM_PIN);\n            }\n        } else {\n            _status = 0;\n            enter_to_state(STATE_INIT);\n        }\n    }\n    if (_cb_data.error != NSAPI_ERROR_OK) {\n        if (_retry_count == 0) {\n            _cellularDevice.set_ready_cb(callback(this, &CellularStateMachine::device_ready_cb));\n        }\n        retry_state_or_fail();\n    }\n}\n\nvoid CellularStateMachine::state_sim_pin()\n{\n    change_timeout(_state_timeout_sim_pin);\n    tr_info(\"Setup SIM (timeout %d ms)\", _state_timeout_sim_pin);\n    if (open_sim()) {\n        bool success = false;\n        for (int type = 0; type < CellularNetwork::C_MAX; type++) {\n            _cb_data.error = _network.set_registration_urc((CellularNetwork::RegistrationType)type, true);\n            if (!_cb_data.error && (type == CellularNetwork::C_EREG || type == CellularNetwork::C_GREG)) {\n                success = true;\n            }\n        }\n        if (!success) {\n            tr_error(\"Failed to set CEREG\/CGREG URC's for registration\");\n            retry_state_or_fail();\n            return;\n        }\n\n        if (_network.is_active_context()) { \/\/ check if context was already activated\n            tr_debug(\"Active context found.\");\n            _status |= ACTIVE_PDP_CONTEXT;\n        }\n        CellularNetwork::AttachStatus status = CellularNetwork::Detached; \/\/ check if modem is already attached to a network\n        if (_network.get_attach(status) == NSAPI_ERROR_OK && status == CellularNetwork::Attached) {\n            _status |= ATTACHED_TO_NETWORK;\n            tr_debug(\"Cellular already attached.\");\n        }\n\n        \/\/ if packet domain event reporting is not set it's not a stopper. We might lack some events when we are\n        \/\/ dropped from the network.\n        _cb_data.error = _network.set_packet_domain_event_reporting(true);\n        if (_cb_data.error == NSAPI_STATUS_ERROR_UNSUPPORTED) {\n            tr_warning(\"Packet domain event reporting not supported!\");\n        } else if (_cb_data.error) {\n            tr_warning(\"Packet domain event reporting set failed!\");\n        }\n        enter_to_state(STATE_SIGNAL_QUALITY);\n    } else {\n        retry_state_or_fail();\n    }\n}\n\nvoid CellularStateMachine::state_signal_quality()\n{\n    _cb_data.error = _network.get_signal_quality(_signal_quality.rssi, &_signal_quality.ber);\n\n    if (_cb_data.error != NSAPI_ERROR_OK) {\n        retry_state_or_fail();\n    } else {\n        _cb_data.data = &_signal_quality;\n        send_event_cb(_current_event);\n        enter_to_state(STATE_REGISTERING_NETWORK);\n    }\n}\n\nvoid CellularStateMachine::state_registering()\n{\n    change_timeout(_state_timeout_network);\n    if (is_registered()) {\n        if (_cb_data.status_data != CellularNetwork::RegisteredHomeNetwork &&\n                _cb_data.status_data != CellularNetwork::RegisteredRoaming && _status) {\n            \/\/ there was already activated context or attached to network, and registration status is not registered, set to already registered.\n            _cb_data.status_data = CellularNetwork::AlreadyRegistered;\n        }\n        _cb_data.error = NSAPI_ERROR_OK;\n        send_event_cb(_current_event);\n        \/\/ we are already registered, go to attach\n        enter_to_state(STATE_ATTACHING_NETWORK);\n    } else {\n        tr_info(\"Network registration (timeout %d ms)\", _state_timeout_registration);\n        change_timeout(_state_timeout_registration);\n        if (!_command_success && !_plmn) { \/\/ don't call set_registration twice for manual registration\n            _cb_data.error = _network.set_registration(_plmn);\n            _command_success = (_cb_data.error == NSAPI_ERROR_OK);\n        }\n        retry_state_or_fail();\n    }\n}\n\nvoid CellularStateMachine::state_attaching()\n{\n    if (_status != ATTACHED_TO_NETWORK) {\n        change_timeout(_state_timeout_connect);\n        tr_info(\"Attaching network (timeout %d ms)\", _state_timeout_connect);\n        _cb_data.error = _network.set_attach();\n    }\n    if (_cb_data.error == NSAPI_ERROR_OK) {\n        _cb_data.status_data = CellularNetwork::Attached;\n        send_event_cb(_current_event);\n    } else {\n        retry_state_or_fail();\n    }\n}\n\nvoid CellularStateMachine::continue_from_state(CellularState state)\n{\n    _mutex.lock();\n    tr_info(\"%s => %s\", get_state_string((CellularStateMachine::CellularState)_state),\n            get_state_string((CellularStateMachine::CellularState)state));\n    _state = state;\n    enter_to_state(state);\n    _event_id = _queue.call_in(0, this, &CellularStateMachine::event);\n    if (!_event_id) {\n        _event_id = -1;\n        _cb_data.error = NSAPI_ERROR_NO_MEMORY;\n        report_failure(\"Failed to call queue.\");\n        stop();\n    }\n    _mutex.unlock();\n}\n\nnsapi_error_t CellularStateMachine::run_to_state(CellularStateMachine::CellularState state)\n{\n    _mutex.lock();\n    \/\/ call pre_event via queue so that it's in same thread and it's safe to decisions\n    int id = _queue.call_in(0, this, &CellularStateMachine::pre_event, state);\n    if (!id) {\n        report_failure(\"Failed to call queue.\");\n        stop();\n        _mutex.unlock();\n        return NSAPI_ERROR_NO_MEMORY;\n    }\n    _mutex.unlock();\n    return NSAPI_ERROR_OK;\n}\n\nvoid CellularStateMachine::pre_event(CellularState state)\n{\n    if (_target_state < state) {\n        \/\/ new wanted state will not be achieved with current _target_state so update it\n        _target_state = state;\n    } else {\n        \/\/ wanted state is already \/ will be achieved, return without launching new event\n        return;\n    }\n    \/\/ if _event_id is -1 it means that new event is not going to be launched so we must launch new event\n    if (_event_id == -1) {\n        if (!_cb_data.final_try) {\n            \/\/ update next state so that we don't continue from previous state if state machine was paused and then started again.\n            \/\/ but only if earlier try did not finish to failure, then we must continue from that state\n            _state = _next_state;\n        }\n        enter_to_state(_next_state);\n        _event_id = _queue.call_in(0, this, &CellularStateMachine::event);\n        if (!_event_id) {\n            _event_id = -1;\n            report_failure(\"Failed to call queue.\");\n            stop();\n        }\n    }\n}\n\nbool CellularStateMachine::get_current_status(CellularStateMachine::CellularState &current_state, CellularStateMachine::CellularState &target_state)\n{\n    bool is_running;\n    _mutex.lock();\n    current_state = _state;\n    target_state = _target_state;\n    if (_event_id == -1 || _event_id == STM_STOPPED) {\n        is_running = false;\n    } else {\n        is_running = true;\n    }\n    _mutex.unlock();\n    return is_running;\n}\n\nvoid CellularStateMachine::event()\n{\n    \/\/ Don't send Signal quality when in signal quality state or it can confuse callback functions when running retry logic\n    if (_state > STATE_SIGNAL_QUALITY) {\n        _cb_data.error = _network.get_signal_quality(_signal_quality.rssi, &_signal_quality.ber);\n        _cb_data.data = &_signal_quality;\n\n        if (_cb_data.error == NSAPI_ERROR_OK) {\n            send_event_cb(CellularSignalQuality);\n            if (_signal_quality.rssi == CellularNetwork::SignalQualityUnknown) {\n                tr_info(\"RSSI unknown\");\n            } else {\n                tr_info(\"RSSI %d dBm\", _signal_quality.rssi);\n            }\n        }\n    }\n\n    _event_timeout = -1;\n    _is_retry = false;\n\n    switch (_state) {\n        case STATE_INIT:\n            _current_event = CellularDeviceReady;\n            state_init();\n            break;\n        case STATE_POWER_ON:\n            _current_event = CellularDeviceReady;\n            state_power_on();\n            break;\n        case STATE_DEVICE_READY:\n            _current_event = CellularDeviceReady;\n            state_device_ready();\n            break;\n        case STATE_SIM_PIN:\n            _current_event = CellularSIMStatusChanged;\n            state_sim_pin();\n            break;\n        case STATE_SIGNAL_QUALITY:\n            _current_event = CellularSignalQuality;\n            state_signal_quality();\n            break;\n        case STATE_REGISTERING_NETWORK:\n            _current_event = CellularRegistrationStatusChanged;\n            state_registering();\n            break;\n        case STATE_ATTACHING_NETWORK:\n            _current_event = CellularAttachNetwork;\n            state_attaching();\n            break;\n        default:\n            MBED_ASSERT(0);\n            break;\n    }\n\n    if (check_is_target_reached()) {\n        _event_id = -1;\n        return;\n    }\n\n    if (_next_state != _state || _event_timeout >= 0) {\n        if (_next_state != _state) { \/\/ state exit condition\n            tr_debug(\"%s => %s\", get_state_string((CellularStateMachine::CellularState)_state),\n                     get_state_string((CellularStateMachine::CellularState)_next_state));\n        } else {\n            tr_info(\"Continue after %d seconds\", _event_timeout);\n        }\n        _state = _next_state;\n        if (_event_timeout == -1) {\n            _event_timeout = 0;\n        }\n        _event_id = _queue.call_in(_event_timeout * 1000, callback(this, &CellularStateMachine::event));\n        if (!_event_id) {\n            _cb_data.error = NSAPI_ERROR_NO_MEMORY;\n            report_failure(\"CellularStateMachine event failure!\");\n            return;\n        }\n    }\n}\n\nnsapi_error_t CellularStateMachine::start_dispatch()\n{\n    if (!_queue_thread) {\n        _queue_thread = new rtos::Thread(osPriorityNormal, 2048, NULL, \"stm_queue\");\n        _event_id = STM_STOPPED;\n    }\n\n    if (_event_id == STM_STOPPED) {\n        if (_queue_thread->start(callback(&_queue, &events::EventQueue::dispatch_forever)) != osOK) {\n            report_failure(\"Failed to start thread.\");\n            stop();\n            return NSAPI_ERROR_NO_MEMORY;\n        }\n    }\n\n    _event_id = -1;\n\n    return NSAPI_ERROR_OK;\n}\n\nvoid CellularStateMachine::set_cellular_callback(mbed::Callback<void(nsapi_event_t, intptr_t)> status_cb)\n{\n    _event_status_cb = status_cb;\n}\n\nvoid CellularStateMachine::send_event_cb(cellular_connection_status_t status)\n{\n    if (_event_status_cb) {\n        _event_status_cb((nsapi_event_t)status, (intptr_t)&_cb_data);\n    }\n}\n\nvoid CellularStateMachine::change_timeout(const int &timeout)\n{\n    _cb_data.status_data = _current_event;\n    _cb_data.data = &timeout;\n    _cb_data.error = NSAPI_ERROR_OK;\n    \/\/ event callback is a preferred method to communicate to CellularDevice,\n    \/\/ for example calling CellularDevice::set_timeout would call back to this class\n    send_event_cb(CellularDeviceTimeout);\n}\n\nbool CellularStateMachine::check_is_target_reached()\n{\n    if (((_target_state == _state || _target_state < _next_state) && _cb_data.error == NSAPI_ERROR_OK && !_is_retry) ||\n            _event_id == STM_STOPPED) {\n        if (_target_state != _state && _target_state < _next_state) {\n            \/\/ we are skipping the state, update _state to current state because we have reached it\n            _state = _target_state;\n        }\n        _event_id = -1;\n        return true;\n    }\n    return false;\n}\n\nvoid CellularStateMachine::cellular_event_changed(nsapi_event_t ev, intptr_t ptr)\n{\n    cell_callback_data_t *data = (cell_callback_data_t *)ptr;\n    if ((cellular_connection_status_t)ev == CellularRegistrationStatusChanged && (\n                _state == STATE_REGISTERING_NETWORK || _state == STATE_SIGNAL_QUALITY)) {\n        \/\/ expect packet data so only these states are valid\n        CellularNetwork::registration_params_t reg_params;\n        nsapi_error_t err = _network.get_registration_params(reg_params);\n\n        if (err == NSAPI_ERROR_OK && (reg_params._type == CellularNetwork::C_EREG || reg_params._type == CellularNetwork::C_GREG)) {\n            if ((data->status_data == CellularNetwork::RegisteredHomeNetwork ||\n                    data->status_data == CellularNetwork::RegisteredRoaming) && data->error == NSAPI_ERROR_OK) {\n                _queue.cancel(_event_id);\n                _is_retry = false;\n                _event_id = -1;\n                if (!check_is_target_reached()) {\n                    continue_from_state(STATE_ATTACHING_NETWORK);\n                }\n            }\n        } else {\n            tr_debug(\"creg event, discard...\");\n        }\n    }\n}\n\nvoid CellularStateMachine::device_ready_cb()\n{\n    tr_debug(\"Device ready callback\");\n    if (_state == STATE_DEVICE_READY && _cellularDevice.init() == NSAPI_ERROR_OK) {\n        tr_debug(\"State was STATE_DEVICE_READY and at mode ready, cancel state and move to next\");\n        _queue.cancel(_event_id);\n        _event_id = -1;\n        if (device_ready()) {\n            _is_retry = false;\n            _status = 0;\n            if (!check_is_target_reached()) {\n                continue_from_state(STATE_SIM_PIN);\n            }\n        } else {\n            continue_from_state(STATE_DEVICE_READY);\n        }\n    }\n}\n\nvoid CellularStateMachine::set_retry_timeout_array(const uint16_t timeout[], int array_len)\n{\n    if (!timeout || array_len <= 0) {\n        _retry_array_length = 0;\n        return;\n    }\n    _retry_array_length = array_len > CELLULAR_RETRY_ARRAY_SIZE ? CELLULAR_RETRY_ARRAY_SIZE : array_len;\n    for (int i = 0; i < _retry_array_length; i++) {\n        _retry_timeout_array[i] = timeout[i];\n    }\n}\n\nvoid CellularStateMachine::get_retry_timeout_array(uint16_t *timeout, int &array_len) const\n{\n    for (int i = 0; i < _retry_array_length; i++) {\n        timeout[i] = _retry_timeout_array[i];\n    }\n    array_len = _retry_array_length;\n}\n\nvoid CellularStateMachine::set_timeout(int timeout)\n{\n    _state_timeout_power_on = timeout;\n    _state_timeout_sim_pin = timeout;\n    _state_timeout_registration = timeout;\n    _state_timeout_network = timeout;\n    _state_timeout_connect = timeout;\n}\n\n} \/\/ namespace\n\n","avg_line_length":34.4538258575,"max_line_length":162,"alphanum_fraction":0.6641522438,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":30476,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Copyright (c) 2014-2015 The Luq developers\n\/\/ Copyright (c) 2015-2017 The PIVX developers \n\/\/ Copyright (c) 2015-2017 The LUQ developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"guiutil.h\"\n\n#include \"bitcoinaddressvalidator.h\"\n#include \"bitcoinunits.h\"\n#include \"qvalidatedlineedit.h\"\n#include \"walletmodel.h\"\n\n#include \"init.h\"\n#include \"main.h\"\n#include \"primitives\/transaction.h\"\n#include \"protocol.h\"\n#include \"script\/script.h\"\n#include \"script\/standard.h\"\n#include \"util.h\"\n\n#ifdef WIN32\n#ifdef _WIN32_WINNT\n#undef _WIN32_WINNT\n#endif\n#define _WIN32_WINNT 0x0501\n#ifdef _WIN32_IE\n#undef _WIN32_IE\n#endif\n#define _WIN32_IE 0x0501\n#define WIN32_LEAN_AND_MEAN 1\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n#include \"shellapi.h\"\n#include \"shlobj.h\"\n#include \"shlwapi.h\"\n#endif\n\n#include <boost\/filesystem.hpp>\n#include <boost\/filesystem\/fstream.hpp>\n#if BOOST_FILESYSTEM_VERSION >= 3\n#include <boost\/filesystem\/detail\/utf8_codecvt_facet.hpp>\n#endif\n\n#include <QAbstractItemView>\n#include <QApplication>\n#include <QClipboard>\n#include <QDateTime>\n#include <QDesktopServices>\n#include <QDesktopWidget>\n#include <QDoubleValidator>\n#include <QFileDialog>\n#include <QFont>\n#include <QLineEdit>\n#include <QSettings>\n#include <QTextDocument> \/\/ for Qt::mightBeRichText\n#include <QThread>\n\n#if QT_VERSION < 0x050000\n#include <QUrl>\n#else\n#include <QUrlQuery>\n#endif\n\n#if BOOST_FILESYSTEM_VERSION >= 3\nstatic boost::filesystem::detail::utf8_codecvt_facet utf8;\n#endif\n\n#if defined(Q_OS_MAC)\nextern double NSAppKitVersionNumber;\n#if !defined(NSAppKitVersionNumber10_8)\n#define NSAppKitVersionNumber10_8 1187\n#endif\n#if !defined(NSAppKitVersionNumber10_9)\n#define NSAppKitVersionNumber10_9 1265\n#endif\n#endif\n\n#define URI_SCHEME \"luq\"\n\nnamespace GUIUtil\n{\nQString dateTimeStr(const QDateTime& date)\n{\n    return date.date().toString(Qt::SystemLocaleShortDate) + QString(\" \") + date.toString(\"hh:mm\");\n}\n\nQString dateTimeStr(qint64 nTime)\n{\n    return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));\n}\n\nQFont bitcoinAddressFont()\n{\n    QFont font(\"Monospace\");\n#if QT_VERSION >= 0x040800\n    font.setStyleHint(QFont::Monospace);\n#else\n    font.setStyleHint(QFont::TypeWriter);\n#endif\n    return font;\n}\n\nvoid setupAddressWidget(QValidatedLineEdit* widget, QWidget* parent)\n{\n    parent->setFocusProxy(widget);\n\n    widget->setFont(bitcoinAddressFont());\n#if QT_VERSION >= 0x040700\n    \/\/ We don't want translators to use own addresses in translations\n    \/\/ and this is the only place, where this address is supplied.\n    widget->setPlaceholderText(QObject::tr(\"Enter a LUQ address (e.g. %1)\").arg(\"LgSABhg3sg8GExgpLLCP11P2dU5iqB5mGD\"));\n#endif\n    widget->setValidator(new BitcoinAddressEntryValidator(parent));\n    widget->setCheckValidator(new BitcoinAddressCheckValidator(parent));\n}\n\nvoid setupAmountWidget(QLineEdit* widget, QWidget* parent)\n{\n    QDoubleValidator* amountValidator = new QDoubleValidator(parent);\n    amountValidator->setDecimals(8);\n    amountValidator->setBottom(0.0);\n    widget->setValidator(amountValidator);\n    widget->setAlignment(Qt::AlignRight | Qt::AlignVCenter);\n}\n\nbool parseBitcoinURI(const QUrl& uri, SendCoinsRecipient* out)\n{\n    \/\/ return if URI is not valid or is no LUQ: URI\n    if (!uri.isValid() || uri.scheme() != QString(URI_SCHEME))\n        return false;\n\n    SendCoinsRecipient rv;\n    rv.address = uri.path();\n    \/\/ Trim any following forward slash which may have been added by the OS\n    if (rv.address.endsWith(\"\/\")) {\n        rv.address.truncate(rv.address.length() - 1);\n    }\n    rv.amount = 0;\n\n#if QT_VERSION < 0x050000\n    QList<QPair<QString, QString> > items = uri.queryItems();\n#else\n    QUrlQuery uriQuery(uri);\n    QList<QPair<QString, QString> > items = uriQuery.queryItems();\n#endif\n    for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) {\n        bool fShouldReturnFalse = false;\n        if (i->first.startsWith(\"req-\")) {\n            i->first.remove(0, 4);\n            fShouldReturnFalse = true;\n        }\n\n        if (i->first == \"label\") {\n            rv.label = i->second;\n            fShouldReturnFalse = false;\n        }\n        if (i->first == \"message\") {\n            rv.message = i->second;\n            fShouldReturnFalse = false;\n        } else if (i->first == \"amount\") {\n            if (!i->second.isEmpty()) {\n                if (!BitcoinUnits::parse(BitcoinUnits::LUQ, i->second, &rv.amount)) {\n                    return false;\n                }\n            }\n            fShouldReturnFalse = false;\n        }\n\n        if (fShouldReturnFalse)\n            return false;\n    }\n    if (out) {\n        *out = rv;\n    }\n    return true;\n}\n\nbool parseBitcoinURI(QString uri, SendCoinsRecipient* out)\n{\n    \/\/ Convert luq:\/\/ to luq:\n    \/\/\n    \/\/    Cannot handle this later, because luq:\/\/ will cause Qt to see the part after \/\/ as host,\n    \/\/    which will lower-case it (and thus invalidate the address).\n    if (uri.startsWith(URI_SCHEME \":\/\/\", Qt::CaseInsensitive)) {\n        uri.replace(0, std::strlen(URI_SCHEME) + 3, URI_SCHEME \":\");\n    }\n    QUrl uriInstance(uri);\n    return parseBitcoinURI(uriInstance, out);\n}\n\nQString formatBitcoinURI(const SendCoinsRecipient& info)\n{\n    QString ret = QString(URI_SCHEME \":%1\").arg(info.address);\n    int paramCount = 0;\n\n    if (info.amount) {\n        ret += QString(\"?amount=%1\").arg(BitcoinUnits::format(BitcoinUnits::LUQ, info.amount, false, BitcoinUnits::separatorNever));\n        paramCount++;\n    }\n\n    if (!info.label.isEmpty()) {\n        QString lbl(QUrl::toPercentEncoding(info.label));\n        ret += QString(\"%1label=%2\").arg(paramCount == 0 ? \"?\" : \"&\").arg(lbl);\n        paramCount++;\n    }\n\n    if (!info.message.isEmpty()) {\n        QString msg(QUrl::toPercentEncoding(info.message));\n        ret += QString(\"%1message=%2\").arg(paramCount == 0 ? \"?\" : \"&\").arg(msg);\n        paramCount++;\n    }\n\n    return ret;\n}\n\nbool isDust(const QString& address, const CAmount& amount)\n{\n    CTxDestination dest = CBitcoinAddress(address.toStdString()).Get();\n    CScript script = GetScriptForDestination(dest);\n    CTxOut txOut(amount, script);\n    return txOut.IsDust(::minRelayTxFee);\n}\n\nQString HtmlEscape(const QString& str, bool fMultiLine)\n{\n#if QT_VERSION < 0x050000\n    QString escaped = Qt::escape(str);\n#else\n    QString escaped = str.toHtmlEscaped();\n#endif\n    escaped = escaped.replace(\" \", \"&nbsp;\");\n    if (fMultiLine) {\n        escaped = escaped.replace(\"\\n\", \"<br>\\n\");\n    }\n    return escaped;\n}\n\nQString HtmlEscape(const std::string& str, bool fMultiLine)\n{\n    return HtmlEscape(QString::fromStdString(str), fMultiLine);\n}\n\nvoid copyEntryData(QAbstractItemView* view, int column, int role)\n{\n    if (!view || !view->selectionModel())\n        return;\n    QModelIndexList selection = view->selectionModel()->selectedRows(column);\n\n    if (!selection.isEmpty()) {\n        \/\/ Copy first item\n        setClipboard(selection.at(0).data(role).toString());\n    }\n}\n\nQString getSaveFileName(QWidget* parent, const QString& caption, const QString& dir, const QString& filter, QString* selectedSuffixOut)\n{\n    QString selectedFilter;\n    QString myDir;\n    if (dir.isEmpty()) \/\/ Default to user documents location\n    {\n#if QT_VERSION < 0x050000\n        myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);\n#else\n        myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);\n#endif\n    } else {\n        myDir = dir;\n    }\n    \/* Directly convert path to native OS path separators *\/\n    QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter));\n\n    \/* Extract first suffix from filter pattern \"Description (*.foo)\" or \"Description (*.foo *.bar ...) *\/\n    QRegExp filter_re(\".* \\\\(\\\\*\\\\.(.*)[ \\\\)]\");\n    QString selectedSuffix;\n    if (filter_re.exactMatch(selectedFilter)) {\n        selectedSuffix = filter_re.cap(1);\n    }\n\n    \/* Add suffix if needed *\/\n    QFileInfo info(result);\n    if (!result.isEmpty()) {\n        if (info.suffix().isEmpty() && !selectedSuffix.isEmpty()) {\n            \/* No suffix specified, add selected suffix *\/\n            if (!result.endsWith(\".\"))\n                result.append(\".\");\n            result.append(selectedSuffix);\n        }\n    }\n\n    \/* Return selected suffix if asked to *\/\n    if (selectedSuffixOut) {\n        *selectedSuffixOut = selectedSuffix;\n    }\n    return result;\n}\n\nQString getOpenFileName(QWidget* parent, const QString& caption, const QString& dir, const QString& filter, QString* selectedSuffixOut)\n{\n    QString selectedFilter;\n    QString myDir;\n    if (dir.isEmpty()) \/\/ Default to user documents location\n    {\n#if QT_VERSION < 0x050000\n        myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);\n#else\n        myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);\n#endif\n    } else {\n        myDir = dir;\n    }\n    \/* Directly convert path to native OS path separators *\/\n    QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter));\n\n    if (selectedSuffixOut) {\n        \/* Extract first suffix from filter pattern \"Description (*.foo)\" or \"Description (*.foo *.bar ...) *\/\n        QRegExp filter_re(\".* \\\\(\\\\*\\\\.(.*)[ \\\\)]\");\n        QString selectedSuffix;\n        if (filter_re.exactMatch(selectedFilter)) {\n            selectedSuffix = filter_re.cap(1);\n        }\n        *selectedSuffixOut = selectedSuffix;\n    }\n    return result;\n}\n\nQt::ConnectionType blockingGUIThreadConnection()\n{\n    if (QThread::currentThread() != qApp->thread()) {\n        return Qt::BlockingQueuedConnection;\n    } else {\n        return Qt::DirectConnection;\n    }\n}\n\nbool checkPoint(const QPoint& p, const QWidget* w)\n{\n    QWidget* atW = QApplication::widgetAt(w->mapToGlobal(p));\n    if (!atW) return false;\n    return atW->topLevelWidget() == w;\n}\n\nbool isObscured(QWidget* w)\n{\n    return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() \/ 2, w->height() \/ 2), w));\n}\n\nvoid openDebugLogfile()\n{\n    boost::filesystem::path pathDebug = GetDataDir() \/ \"debug.log\";\n\n    \/* Open debug.log with the associated application *\/\n    if (boost::filesystem::exists(pathDebug))\n        QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDebug)));\n}\n\nvoid openConfigfile()\n{\n    boost::filesystem::path pathConfig = GetConfigFile();\n\n    \/* Open luq.conf with the associated application *\/\n    if (boost::filesystem::exists(pathConfig))\n        QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig)));\n}\n\nvoid openMNConfigfile()\n{\n    boost::filesystem::path pathConfig = GetMasternodeConfigFile();\n\n    \/* Open masternode.conf with the associated application *\/\n    if (boost::filesystem::exists(pathConfig))\n        QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig)));\n}\n\nvoid showBackups()\n{\n    boost::filesystem::path pathBackups = GetDataDir() \/ \"backups\";\n\n    \/* Open folder with default browser *\/\n    if (boost::filesystem::exists(pathBackups))\n        QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathBackups)));\n}\n\nvoid SubstituteFonts(const QString& language)\n{\n#if defined(Q_OS_MAC)\n\/\/ Background:\n\/\/ OSX's default font changed in 10.9 and QT is unable to find it with its\n\/\/ usual fallback methods when building against the 10.7 sdk or lower.\n\/\/ The 10.8 SDK added a function to let it find the correct fallback font.\n\/\/ If this fallback is not properly loaded, some characters may fail to\n\/\/ render correctly.\n\/\/\n\/\/ The same thing happened with 10.10. .Helvetica Neue DeskInterface is now default.\n\/\/\n\/\/ Solution: If building with the 10.7 SDK or lower and the user's platform\n\/\/ is 10.9 or higher at runtime, substitute the correct font. This needs to\n\/\/ happen before the QApplication is created.\n#if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8\n    if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8) {\n        if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9)\n            \/* On a 10.9 - 10.9.x system *\/\n            QFont::insertSubstitution(\".Lucida Grande UI\", \"Lucida Grande\");\n        else {\n            \/* 10.10 or later system *\/\n            if (language == \"zh_CN\" || language == \"zh_TW\" || language == \"zh_HK\") \/\/ traditional or simplified Chinese\n                QFont::insertSubstitution(\".Helvetica Neue DeskInterface\", \"Heiti SC\");\n            else if (language == \"ja\") \/\/ Japanesee\n                QFont::insertSubstitution(\".Helvetica Neue DeskInterface\", \"Songti SC\");\n            else\n                QFont::insertSubstitution(\".Helvetica Neue DeskInterface\", \"Lucida Grande\");\n        }\n    }\n#endif\n#endif\n}\n\nToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject* parent) : QObject(parent),\n                                                                                        size_threshold(size_threshold)\n{\n}\n\nbool ToolTipToRichTextFilter::eventFilter(QObject* obj, QEvent* evt)\n{\n    if (evt->type() == QEvent::ToolTipChange) {\n        QWidget* widget = static_cast<QWidget*>(obj);\n        QString tooltip = widget->toolTip();\n        if (tooltip.size() > size_threshold && !tooltip.startsWith(\"<qt\")) {\n            \/\/ Escape the current message as HTML and replace \\n by <br> if it's not rich text\n            if (!Qt::mightBeRichText(tooltip))\n                tooltip = HtmlEscape(tooltip, true);\n            \/\/ Envelop with <qt><\/qt> to make sure Qt detects every tooltip as rich text\n            \/\/ and style='white-space:pre' to preserve line composition\n            tooltip = \"<qt style='white-space:pre'>\" + tooltip + \"<\/qt>\";\n            widget->setToolTip(tooltip);\n            return true;\n        }\n    }\n    return QObject::eventFilter(obj, evt);\n}\n\nvoid TableViewLastColumnResizingFixer::connectViewHeadersSignals()\n{\n    connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(on_sectionResized(int, int, int)));\n    connect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));\n}\n\n\/\/ We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.\nvoid TableViewLastColumnResizingFixer::disconnectViewHeadersSignals()\n{\n    disconnect(tableView->horizontalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(on_sectionResized(int, int, int)));\n    disconnect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));\n}\n\n\/\/ Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.\n\/\/ Refactored here for readability.\nvoid TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)\n{\n#if QT_VERSION < 0x050000\n    tableView->horizontalHeader()->setResizeMode(logicalIndex, resizeMode);\n#else\n    tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode);\n#endif\n}\n\nvoid TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width)\n{\n    tableView->setColumnWidth(nColumnIndex, width);\n    tableView->horizontalHeader()->resizeSection(nColumnIndex, width);\n}\n\nint TableViewLastColumnResizingFixer::getColumnsWidth()\n{\n    int nColumnsWidthSum = 0;\n    for (int i = 0; i < columnCount; i++) {\n        nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i);\n    }\n    return nColumnsWidthSum;\n}\n\nint TableViewLastColumnResizingFixer::getAvailableWidthForColumn(int column)\n{\n    int nResult = lastColumnMinimumWidth;\n    int nTableWidth = tableView->horizontalHeader()->width();\n\n    if (nTableWidth > 0) {\n        int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column);\n        nResult = std::max(nResult, nTableWidth - nOtherColsWidth);\n    }\n\n    return nResult;\n}\n\n\/\/ Make sure we don't make the columns wider than the tables viewport width.\nvoid TableViewLastColumnResizingFixer::adjustTableColumnsWidth()\n{\n    disconnectViewHeadersSignals();\n    resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex));\n    connectViewHeadersSignals();\n\n    int nTableWidth = tableView->horizontalHeader()->width();\n    int nColsWidth = getColumnsWidth();\n    if (nColsWidth > nTableWidth) {\n        resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));\n    }\n}\n\n\/\/ Make column use all the space available, useful during window resizing.\nvoid TableViewLastColumnResizingFixer::stretchColumnWidth(int column)\n{\n    disconnectViewHeadersSignals();\n    resizeColumn(column, getAvailableWidthForColumn(column));\n    connectViewHeadersSignals();\n}\n\n\/\/ When a section is resized this is a slot-proxy for ajustAmountColumnWidth().\nvoid TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize)\n{\n    adjustTableColumnsWidth();\n    int remainingWidth = getAvailableWidthForColumn(logicalIndex);\n    if (newSize > remainingWidth) {\n        resizeColumn(logicalIndex, remainingWidth);\n    }\n}\n\n\/\/ When the tabless geometry is ready, we manually perform the stretch of the \"Message\" column,\n\/\/ as the \"Stretch\" resize mode does not allow for interactive resizing.\nvoid TableViewLastColumnResizingFixer::on_geometriesChanged()\n{\n    if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0) {\n        disconnectViewHeadersSignals();\n        resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));\n        connectViewHeadersSignals();\n    }\n}\n\n\/**\n * Initializes all internal variables and prepares the\n * the resize modes of the last 2 columns of the table and\n *\/\nTableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth) : tableView(table),\n                                                                                                                                          lastColumnMinimumWidth(lastColMinimumWidth),\n                                                                                                                                          allColumnsMinimumWidth(allColsMinimumWidth)\n{\n    columnCount = tableView->horizontalHeader()->count();\n    lastColumnIndex = columnCount - 1;\n    secondToLastColumnIndex = columnCount - 2;\n    tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth);\n    setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive);\n    setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive);\n}\n\n\/**\n * Class constructor.\n * @param[in] seconds   Number of seconds to convert to a DHMS string\n *\/\nDHMSTableWidgetItem::DHMSTableWidgetItem(const int64_t seconds) : QTableWidgetItem(),\n                                                                  value(seconds)\n{\n    this->setText(QString::fromStdString(DurationToDHMS(seconds)));\n}\n\n\/**\n * Comparator overload to ensure that the \"DHMS\"-type durations as used in\n * the \"active-since\" list in the masternode tab are sorted by the elapsed\n * duration (versus the string value being sorted).\n * @param[in] item      Right hand side of the less than operator\n *\/\nbool DHMSTableWidgetItem::operator<(QTableWidgetItem const& item) const\n{\n    DHMSTableWidgetItem const* rhs =\n        dynamic_cast<DHMSTableWidgetItem const*>(&item);\n\n    if (!rhs)\n        return QTableWidgetItem::operator<(item);\n\n    return value < rhs->value;\n}\n\n#ifdef WIN32\nboost::filesystem::path static StartupShortcutPath()\n{\n    return GetSpecialFolderPath(CSIDL_STARTUP) \/ \"LUQ.lnk\";\n}\n\nbool GetStartOnSystemStartup()\n{\n    \/\/ check for LUQ.lnk\n    return boost::filesystem::exists(StartupShortcutPath());\n}\n\nbool SetStartOnSystemStartup(bool fAutoStart)\n{\n    \/\/ If the shortcut exists already, remove it for updating\n    boost::filesystem::remove(StartupShortcutPath());\n\n    if (fAutoStart) {\n        CoInitialize(NULL);\n\n        \/\/ Get a pointer to the IShellLink interface.\n        IShellLink* psl = NULL;\n        HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,\n            CLSCTX_INPROC_SERVER, IID_IShellLink,\n            reinterpret_cast<void**>(&psl));\n\n        if (SUCCEEDED(hres)) {\n            \/\/ Get the current executable path\n            TCHAR pszExePath[MAX_PATH];\n            GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));\n\n            TCHAR pszArgs[5] = TEXT(\"-min\");\n\n            \/\/ Set the path to the shortcut target\n            psl->SetPath(pszExePath);\n            PathRemoveFileSpec(pszExePath);\n            psl->SetWorkingDirectory(pszExePath);\n            psl->SetShowCmd(SW_SHOWMINNOACTIVE);\n            psl->SetArguments(pszArgs);\n\n            \/\/ Query IShellLink for the IPersistFile interface for\n            \/\/ saving the shortcut in persistent storage.\n            IPersistFile* ppf = NULL;\n            hres = psl->QueryInterface(IID_IPersistFile,\n                reinterpret_cast<void**>(&ppf));\n            if (SUCCEEDED(hres)) {\n                WCHAR pwsz[MAX_PATH];\n                \/\/ Ensure that the string is ANSI.\n                MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);\n                \/\/ Save the link by calling IPersistFile::Save.\n                hres = ppf->Save(pwsz, TRUE);\n                ppf->Release();\n                psl->Release();\n                CoUninitialize();\n                return true;\n            }\n            psl->Release();\n        }\n        CoUninitialize();\n        return false;\n    }\n    return true;\n}\n\n#elif defined(Q_OS_LINUX)\n\n\/\/ Follow the Desktop Application Autostart Spec:\n\/\/  http:\/\/standards.freedesktop.org\/autostart-spec\/autostart-spec-latest.html\n\nboost::filesystem::path static GetAutostartDir()\n{\n    namespace fs = boost::filesystem;\n\n    char* pszConfigHome = getenv(\"XDG_CONFIG_HOME\");\n    if (pszConfigHome) return fs::path(pszConfigHome) \/ \"autostart\";\n    char* pszHome = getenv(\"HOME\");\n    if (pszHome) return fs::path(pszHome) \/ \".config\" \/ \"autostart\";\n    return fs::path();\n}\n\nboost::filesystem::path static GetAutostartFilePath()\n{\n    return GetAutostartDir() \/ \"luq.desktop\";\n}\n\nbool GetStartOnSystemStartup()\n{\n    boost::filesystem::ifstream optionFile(GetAutostartFilePath());\n    if (!optionFile.good())\n        return false;\n    \/\/ Scan through file for \"Hidden=true\":\n    std::string line;\n    while (!optionFile.eof()) {\n        getline(optionFile, line);\n        if (line.find(\"Hidden\") != std::string::npos &&\n            line.find(\"true\") != std::string::npos)\n            return false;\n    }\n    optionFile.close();\n\n    return true;\n}\n\nbool SetStartOnSystemStartup(bool fAutoStart)\n{\n    if (!fAutoStart)\n        boost::filesystem::remove(GetAutostartFilePath());\n    else {\n        char pszExePath[MAX_PATH + 1];\n        memset(pszExePath, 0, sizeof(pszExePath));\n        if (readlink(\"\/proc\/self\/exe\", pszExePath, sizeof(pszExePath) - 1) == -1)\n            return false;\n\n        boost::filesystem::create_directories(GetAutostartDir());\n\n        boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out | std::ios_base::trunc);\n        if (!optionFile.good())\n            return false;\n        \/\/ Write a luq.desktop file to the autostart directory:\n        optionFile << \"[Desktop Entry]\\n\";\n        optionFile << \"Type=Application\\n\";\n        optionFile << \"Name=LUQ\\n\";\n        optionFile << \"Exec=\" << pszExePath << \" -min\\n\";\n        optionFile << \"Terminal=false\\n\";\n        optionFile << \"Hidden=false\\n\";\n        optionFile.close();\n    }\n    return true;\n}\n\n\n#elif defined(Q_OS_MAC)\n\/\/ based on: https:\/\/github.com\/Mozketo\/LaunchAtLoginController\/blob\/master\/LaunchAtLoginController.m\n\n#include <CoreFoundation\/CoreFoundation.h>\n#include <CoreServices\/CoreServices.h>\n\nLSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl);\nLSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)\n{\n    \/\/ loop through the list of startup items and try to find the luq app\n    CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL);\n    for (int i = 0; i < CFArrayGetCount(listSnapshot); i++) {\n        LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);\n        UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;\n        CFURLRef currentItemURL = NULL;\n        LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL);\n        if (currentItemURL && CFEqual(currentItemURL, findUrl)) {\n            \/\/ found\n            CFRelease(currentItemURL);\n            return item;\n        }\n        if (currentItemURL) {\n            CFRelease(currentItemURL);\n        }\n    }\n    return NULL;\n}\n\nbool GetStartOnSystemStartup()\n{\n    CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());\n    LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);\n    LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);\n    return !!foundItem; \/\/ return boolified object\n}\n\nbool SetStartOnSystemStartup(bool fAutoStart)\n{\n    CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());\n    LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);\n    LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);\n\n    if (fAutoStart && !foundItem) {\n        \/\/ add luq app to startup item list\n        LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL);\n    } else if (!fAutoStart && foundItem) {\n        \/\/ remove item\n        LSSharedFileListItemRemove(loginItems, foundItem);\n    }\n    return true;\n}\n#else\n\nbool GetStartOnSystemStartup()\n{\n    return false;\n}\nbool SetStartOnSystemStartup(bool fAutoStart) { return false; }\n\n#endif\n\nvoid saveWindowGeometry(const QString& strSetting, QWidget* parent)\n{\n    QSettings settings;\n    settings.setValue(strSetting + \"Pos\", parent->pos());\n    settings.setValue(strSetting + \"Size\", parent->size());\n}\n\nvoid restoreWindowGeometry(const QString& strSetting, const QSize& defaultSize, QWidget* parent)\n{\n    QSettings settings;\n    QPoint pos = settings.value(strSetting + \"Pos\").toPoint();\n    QSize size = settings.value(strSetting + \"Size\", defaultSize).toSize();\n\n    if (!pos.x() && !pos.y()) {\n        QRect screen = QApplication::desktop()->screenGeometry();\n        pos.setX((screen.width() - size.width()) \/ 2);\n        pos.setY((screen.height() - size.height()) \/ 2);\n    }\n\n    parent->resize(size);\n    parent->move(pos);\n}\n\n\/\/ Check whether a theme is not build-in\nbool isExternal(QString theme)\n{\n    if (theme.isEmpty())\n        return false;\n\n    return (theme.operator!=(\"default\"));\n}\n\n\/\/ Open CSS when configured\nQString loadStyleSheet()\n{\n    QString styleSheet;\n    QSettings settings;\n    QString cssName;\n    QString theme = settings.value(\"theme\", \"\").toString();\n\n    if (isExternal(theme)) {\n        \/\/ External CSS\n        settings.setValue(\"fCSSexternal\", true);\n        boost::filesystem::path pathAddr = GetDataDir() \/ \"themes\/\";\n        cssName = pathAddr.string().c_str() + theme + \"\/css\/theme.css\";\n    } else {\n        \/\/ Build-in CSS\n        settings.setValue(\"fCSSexternal\", false);\n        if (!theme.isEmpty()) {\n            cssName = QString(\":\/css\/\") + theme;\n        } else {\n            cssName = QString(\":\/css\/default\");\n            settings.setValue(\"theme\", \"default\");\n        }\n    }\n\n    QFile qFile(cssName);\n    if (qFile.open(QFile::ReadOnly)) {\n        styleSheet = QLatin1String(qFile.readAll());\n    }\n\n    return styleSheet;\n}\n\nvoid setClipboard(const QString& str)\n{\n    QApplication::clipboard()->setText(str, QClipboard::Clipboard);\n    QApplication::clipboard()->setText(str, QClipboard::Selection);\n}\n\n#if BOOST_FILESYSTEM_VERSION >= 3\nboost::filesystem::path qstringToBoostPath(const QString& path)\n{\n    return boost::filesystem::path(path.toStdString(), utf8);\n}\n\nQString boostPathToQString(const boost::filesystem::path& path)\n{\n    return QString::fromStdString(path.string(utf8));\n}\n#else\n#warning Conversion between boost path and QString can use invalid character encoding with boost_filesystem v2 and older\nboost::filesystem::path qstringToBoostPath(const QString& path)\n{\n    return boost::filesystem::path(path.toStdString());\n}\n\nQString boostPathToQString(const boost::filesystem::path& path)\n{\n    return QString::fromStdString(path.string());\n}\n#endif\n\nQString formatDurationStr(int secs)\n{\n    QStringList strList;\n    int days = secs \/ 86400;\n    int hours = (secs % 86400) \/ 3600;\n    int mins = (secs % 3600) \/ 60;\n    int seconds = secs % 60;\n\n    if (days)\n        strList.append(QString(QObject::tr(\"%1 d\")).arg(days));\n    if (hours)\n        strList.append(QString(QObject::tr(\"%1 h\")).arg(hours));\n    if (mins)\n        strList.append(QString(QObject::tr(\"%1 m\")).arg(mins));\n    if (seconds || (!days && !hours && !mins))\n        strList.append(QString(QObject::tr(\"%1 s\")).arg(seconds));\n\n    return strList.join(\" \");\n}\n\nQString formatServicesStr(quint64 mask)\n{\n    QStringList strList;\n\n    \/\/ Just scan the last 8 bits for now.\n    for (int i = 0; i < 8; i++) {\n        uint64_t check = 1 << i;\n        if (mask & check) {\n            switch (check) {\n            case NODE_NETWORK:\n                strList.append(QObject::tr(\"NETWORK\"));\n                break;\n            case NODE_BLOOM:\n            case NODE_BLOOM_WITHOUT_MN:\n                strList.append(QObject::tr(\"BLOOM\"));\n                break;\n            default:\n                strList.append(QString(\"%1[%2]\").arg(QObject::tr(\"UNKNOWN\")).arg(check));\n            }\n        }\n    }\n\n    if (strList.size())\n        return strList.join(\" & \");\n    else\n        return QObject::tr(\"None\");\n}\n\nQString formatPingTime(double dPingTime)\n{\n    return dPingTime == 0 ? QObject::tr(\"N\/A\") : QString(QObject::tr(\"%1 ms\")).arg(QString::number((int)(dPingTime * 1000), 10));\n}\n\n} \/\/ namespace GUIUtil\n","avg_line_length":33.0901194354,"max_line_length":247,"alphanum_fraction":0.6672463578,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":45076,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"config\/bitcoin-config.h\"\n#endif\n\n#include \"bitcoingui.h\"\n\n#include \"bitcoinunits.h\"\n#include \"clientmodel.h\"\n#include \"guiconstants.h\"\n#include \"guiutil.h\"\n#include \"modaloverlay.h\"\n#include \"networkstyle.h\"\n#include \"notificator.h\"\n#include \"openuridialog.h\"\n#include \"optionsdialog.h\"\n#include \"optionsmodel.h\"\n#include \"platformstyle.h\"\n#include \"rpcconsole.h\"\n#include \"utilitydialog.h\"\n\n#ifdef ENABLE_WALLET\n#include \"walletframe.h\"\n#include \"walletmodel.h\"\n#endif \/\/ ENABLE_WALLET\n\n#ifdef Q_OS_MAC\n#include \"macdockiconhandler.h\"\n#endif\n\n#include \"chainparams.h\"\n#include \"init.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n\n#include <iostream>\n\n#include <QAction>\n#include <QApplication>\n#include <QDateTime>\n#include <QDesktopWidget>\n#include <QDragEnterEvent>\n#include <QListWidget>\n#include <QMenuBar>\n#include <QMessageBox>\n#include <QMimeData>\n#include <QProgressDialog>\n#include <QSettings>\n#include <QShortcut>\n#include <QStackedWidget>\n#include <QStatusBar>\n#include <QStyle>\n#include <QTimer>\n#include <QToolBar>\n#include <QVBoxLayout>\n\n#if QT_VERSION < 0x050000\n#include <QTextDocument>\n#include <QUrl>\n#else\n#include <QUrlQuery>\n#endif\n\nconst std::string BitcoinGUI::DEFAULT_UIPLATFORM =\n#if defined(Q_OS_MAC)\n        \"macosx\"\n#elif defined(Q_OS_WIN)\n        \"windows\"\n#else\n        \"other\"\n#endif\n        ;\n\n\/** Display name for default wallet name. Uses tilde to avoid name\n * collisions in the future with additional wallets *\/\nconst QString BitcoinGUI::DEFAULT_WALLET = \"~Default\";\n\nBitcoinGUI::BitcoinGUI(const PlatformStyle *_platformStyle, const NetworkStyle *networkStyle, QWidget *parent) :\n    QMainWindow(parent),\n    enableWallet(false),\n    clientModel(0),\n    walletFrame(0),\n    unitDisplayControl(0),\n    labelWalletEncryptionIcon(0),\n    labelWalletHDStatusIcon(0),\n    connectionsControl(0),\n    labelBlocksIcon(0),\n    progressBarLabel(0),\n    progressBar(0),\n    progressDialog(0),\n    appMenuBar(0),\n    overviewAction(0),\n    historyAction(0),\n    quitAction(0),\n    sendCoinsAction(0),\n    sendCoinsMenuAction(0),\n    usedSendingAddressesAction(0),\n    usedReceivingAddressesAction(0),\n    signMessageAction(0),\n    verifyMessageAction(0),\n    aboutAction(0),\n    receiveCoinsAction(0),\n    receiveCoinsMenuAction(0),\n    optionsAction(0),\n    toggleHideAction(0),\n    encryptWalletAction(0),\n    backupWalletAction(0),\n    changePassphraseAction(0),\n    aboutQtAction(0),\n    openRPCConsoleAction(0),\n    openAction(0),\n    showHelpMessageAction(0),\n    trayIcon(0),\n    trayIconMenu(0),\n    notificator(0),\n    rpcConsole(0),\n    helpMessageDialog(0),\n    modalOverlay(0),\n    prevBlocks(0),\n    spinnerFrame(0),\n    platformStyle(_platformStyle)\n{\n    GUIUtil::restoreWindowGeometry(\"nWindow\", QSize(850, 550), this);\n\n    QString windowTitle = tr(PACKAGE_NAME) + \" - \";\n#ifdef ENABLE_WALLET\n    enableWallet = WalletModel::isWalletEnabled();\n#endif \/\/ ENABLE_WALLET\n    if(enableWallet)\n    {\n        windowTitle += tr(\"Wallet\");\n    } else {\n        windowTitle += tr(\"Node\");\n    }\n    windowTitle += \" \" + networkStyle->getTitleAddText();\n#ifndef Q_OS_MAC\n    QApplication::setWindowIcon(networkStyle->getTrayAndWindowIcon());\n    setWindowIcon(networkStyle->getTrayAndWindowIcon());\n#else\n    MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon());\n#endif\n    setWindowTitle(windowTitle);\n\n#if defined(Q_OS_MAC) && QT_VERSION < 0x050000\n    \/\/ This property is not implemented in Qt 5. Setting it has no effect.\n    \/\/ A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras.\n    setUnifiedTitleAndToolBarOnMac(true);\n#endif\n\n    rpcConsole = new RPCConsole(_platformStyle, 0);\n    helpMessageDialog = new HelpMessageDialog(this, false);\n#ifdef ENABLE_WALLET\n    if(enableWallet)\n    {\n        \/** Create wallet frame and make it the central widget *\/\n        walletFrame = new WalletFrame(_platformStyle, this);\n        setCentralWidget(walletFrame);\n    } else\n#endif \/\/ ENABLE_WALLET\n    {\n        \/* When compiled without wallet or -disablewallet is provided,\n         * the central widget is the rpc console.\n         *\/\n        setCentralWidget(rpcConsole);\n    }\n\n    \/\/ Accept D&D of URIs\n    setAcceptDrops(true);\n\n    \/\/ Create actions for the toolbar, menu bar and tray\/dock icon\n    \/\/ Needs walletFrame to be initialized\n    createActions();\n\n    \/\/ Create application menu bar\n    createMenuBar();\n\n    \/\/ Create the toolbars\n    createToolBars();\n\n    \/\/ Create system tray icon and notification\n    createTrayIcon(networkStyle);\n\n    \/\/ Create status bar\n    statusBar();\n\n    \/\/ Disable size grip because it looks ugly and nobody needs it\n    statusBar()->setSizeGripEnabled(false);\n\n    \/\/ Status bar notification icons\n    QFrame *frameBlocks = new QFrame();\n    frameBlocks->setContentsMargins(0,0,0,0);\n    frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);\n    QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);\n    frameBlocksLayout->setContentsMargins(3,0,3,0);\n    frameBlocksLayout->setSpacing(3);\n    unitDisplayControl = new UnitDisplayStatusBarControl(platformStyle);\n    labelWalletEncryptionIcon = new QLabel();\n    labelWalletHDStatusIcon = new QLabel();\n    connectionsControl = new GUIUtil::ClickableLabel();\n    labelBlocksIcon = new GUIUtil::ClickableLabel();\n    if(enableWallet)\n    {\n        frameBlocksLayout->addStretch();\n        frameBlocksLayout->addWidget(unitDisplayControl);\n        frameBlocksLayout->addStretch();\n        frameBlocksLayout->addWidget(labelWalletEncryptionIcon);\n        frameBlocksLayout->addWidget(labelWalletHDStatusIcon);\n    }\n    frameBlocksLayout->addStretch();\n    frameBlocksLayout->addWidget(connectionsControl);\n    frameBlocksLayout->addStretch();\n    frameBlocksLayout->addWidget(labelBlocksIcon);\n    frameBlocksLayout->addStretch();\n\n    \/\/ Progress bar and label for blocks download\n    progressBarLabel = new QLabel();\n    progressBarLabel->setVisible(false);\n    progressBar = new GUIUtil::ProgressBar();\n    progressBar->setAlignment(Qt::AlignCenter);\n    progressBar->setVisible(false);\n\n    \/\/ Override style sheet for progress bar for styles that have a segmented progress bar,\n    \/\/ as they make the text unreadable (workaround for issue #1071)\n    \/\/ See https:\/\/qt-project.org\/doc\/qt-4.8\/gallery.html\n    QString curStyle = QApplication::style()->metaObject()->className();\n    if(curStyle == \"QWindowsStyle\" || curStyle == \"QWindowsXPStyle\")\n    {\n        progressBar->setStyleSheet(\"QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }\");\n    }\n\n    statusBar()->addWidget(progressBarLabel);\n    statusBar()->addWidget(progressBar);\n    statusBar()->addPermanentWidget(frameBlocks);\n\n    \/\/ Install event filter to be able to catch status tip events (QEvent::StatusTip)\n    this->installEventFilter(this);\n\n    \/\/ Initially wallet actions should be disabled\n    setWalletActionsEnabled(false);\n\n    \/\/ Subscribe to notifications from core\n    subscribeToCoreSignals();\n\n    connect(connectionsControl, SIGNAL(clicked(QPoint)), this, SLOT(toggleNetworkActive()));\n\n    modalOverlay = new ModalOverlay(this->centralWidget());\n#ifdef ENABLE_WALLET\n    if(enableWallet) {\n        connect(walletFrame, SIGNAL(requestedSyncWarningInfo()), this, SLOT(showModalOverlay()));\n        connect(labelBlocksIcon, SIGNAL(clicked(QPoint)), this, SLOT(showModalOverlay()));\n        connect(progressBar, SIGNAL(clicked(QPoint)), this, SLOT(showModalOverlay()));\n    }\n#endif\n}\n\nBitcoinGUI::~BitcoinGUI()\n{\n    \/\/ Unsubscribe from notifications from core\n    unsubscribeFromCoreSignals();\n\n    GUIUtil::saveWindowGeometry(\"nWindow\", this);\n    if(trayIcon) \/\/ Hide tray icon, as deleting will let it linger until quit (on Ubuntu)\n        trayIcon->hide();\n#ifdef Q_OS_MAC\n    delete appMenuBar;\n    MacDockIconHandler::cleanup();\n#endif\n\n    delete rpcConsole;\n}\n\nvoid BitcoinGUI::createActions()\n{\n    QActionGroup *tabGroup = new QActionGroup(this);\n\n    overviewAction = new QAction(platformStyle->SingleColorIcon(\":\/icons\/overview\"), tr(\"&Overview\"), this);\n    overviewAction->setStatusTip(tr(\"Show general overview of wallet\"));\n    overviewAction->setToolTip(overviewAction->statusTip());\n    overviewAction->setCheckable(true);\n    overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));\n    tabGroup->addAction(overviewAction);\n\n    sendCoinsAction = new QAction(platformStyle->SingleColorIcon(\":\/icons\/send\"), tr(\"&Send\"), this);\n    sendCoinsAction->setStatusTip(tr(\"Send coins to a Litecoin address\"));\n    sendCoinsAction->setToolTip(sendCoinsAction->statusTip());\n    sendCoinsAction->setCheckable(true);\n    sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));\n    tabGroup->addAction(sendCoinsAction);\n\n    sendCoinsMenuAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/send\"), sendCoinsAction->text(), this);\n    sendCoinsMenuAction->setStatusTip(sendCoinsAction->statusTip());\n    sendCoinsMenuAction->setToolTip(sendCoinsMenuAction->statusTip());\n\n    receiveCoinsAction = new QAction(platformStyle->SingleColorIcon(\":\/icons\/receiving_addresses\"), tr(\"&Receive\"), this);\n    receiveCoinsAction->setStatusTip(tr(\"Request payments (generates QR codes and CadornaCoin: URIs)\"));\n    receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());\n    receiveCoinsAction->setCheckable(true);\n    receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));\n    tabGroup->addAction(receiveCoinsAction);\n\n    receiveCoinsMenuAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/receiving_addresses\"), receiveCoinsAction->text(), this);\n    receiveCoinsMenuAction->setStatusTip(receiveCoinsAction->statusTip());\n    receiveCoinsMenuAction->setToolTip(receiveCoinsMenuAction->statusTip());\n\n    historyAction = new QAction(platformStyle->SingleColorIcon(\":\/icons\/history\"), tr(\"&Transactions\"), this);\n    historyAction->setStatusTip(tr(\"Browse transaction history\"));\n    historyAction->setToolTip(historyAction->statusTip());\n    historyAction->setCheckable(true);\n    historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));\n    tabGroup->addAction(historyAction);\n\n#ifdef ENABLE_WALLET\n    \/\/ These showNormalIfMinimized are needed because Send Coins and Receive Coins\n    \/\/ can be triggered from the tray menu, and need to show the GUI to be useful.\n    connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\n    connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));\n    connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\n    connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));\n    connect(sendCoinsMenuAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\n    connect(sendCoinsMenuAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));\n    connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\n    connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));\n    connect(receiveCoinsMenuAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\n    connect(receiveCoinsMenuAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));\n    connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\n    connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));\n#endif \/\/ ENABLE_WALLET\n\n    quitAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/quit\"), tr(\"E&xit\"), this);\n    quitAction->setStatusTip(tr(\"Quit application\"));\n    quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));\n    quitAction->setMenuRole(QAction::QuitRole);\n    aboutAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/about\"), tr(\"&About %1\").arg(tr(PACKAGE_NAME)), this);\n    aboutAction->setStatusTip(tr(\"Show information about %1\").arg(tr(PACKAGE_NAME)));\n    aboutAction->setMenuRole(QAction::AboutRole);\n    aboutAction->setEnabled(false);\n    aboutQtAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/about_qt\"), tr(\"About &Qt\"), this);\n    aboutQtAction->setStatusTip(tr(\"Show information about Qt\"));\n    aboutQtAction->setMenuRole(QAction::AboutQtRole);\n    optionsAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/options\"), tr(\"&Options...\"), this);\n    optionsAction->setStatusTip(tr(\"Modify configuration options for %1\").arg(tr(PACKAGE_NAME)));\n    optionsAction->setMenuRole(QAction::PreferencesRole);\n    optionsAction->setEnabled(false);\n    toggleHideAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/about\"), tr(\"&Show \/ Hide\"), this);\n    toggleHideAction->setStatusTip(tr(\"Show or hide the main Window\"));\n\n    encryptWalletAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/lock_closed\"), tr(\"&Encrypt Wallet...\"), this);\n    encryptWalletAction->setStatusTip(tr(\"Encrypt the private keys that belong to your wallet\"));\n    encryptWalletAction->setCheckable(true);\n    backupWalletAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/filesave\"), tr(\"&Backup Wallet...\"), this);\n    backupWalletAction->setStatusTip(tr(\"Backup wallet to another location\"));\n    changePassphraseAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/key\"), tr(\"&Change Passphrase...\"), this);\n    changePassphraseAction->setStatusTip(tr(\"Change the passphrase used for wallet encryption\"));\n    signMessageAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/edit\"), tr(\"Sign &message...\"), this);\n    signMessageAction->setStatusTip(tr(\"Sign messages with your Litecoin addresses to prove you own them\"));\n    verifyMessageAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/verify\"), tr(\"&Verify message...\"), this);\n    verifyMessageAction->setStatusTip(tr(\"Verify messages to ensure they were signed with specified Litecoin addresses\"));\n\n    openRPCConsoleAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/debugwindow\"), tr(\"&Debug window\"), this);\n    openRPCConsoleAction->setStatusTip(tr(\"Open debugging and diagnostic console\"));\n    \/\/ initially disable the debug window menu item\n    openRPCConsoleAction->setEnabled(false);\n\n    usedSendingAddressesAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/address-book\"), tr(\"&Sending addresses...\"), this);\n    usedSendingAddressesAction->setStatusTip(tr(\"Show the list of used sending addresses and labels\"));\n    usedReceivingAddressesAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/address-book\"), tr(\"&Receiving addresses...\"), this);\n    usedReceivingAddressesAction->setStatusTip(tr(\"Show the list of used receiving addresses and labels\"));\n\n    openAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/open\"), tr(\"Open &URI...\"), this);\n    openAction->setStatusTip(tr(\"Open a CadornaCoin: URI or payment request\"));\n\n    showHelpMessageAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/info\"), tr(\"&Command-line options\"), this);\n    showHelpMessageAction->setMenuRole(QAction::NoRole);\n    showHelpMessageAction->setStatusTip(tr(\"Show the %1 help message to get a list with possible Litecoin command-line options\").arg(tr(PACKAGE_NAME)));\n\n    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));\n    connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));\n    connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));\n    connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));\n    connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));\n    connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked()));\n    connect(openRPCConsoleAction, SIGNAL(triggered()), this, SLOT(showDebugWindow()));\n    \/\/ prevents an open debug window from becoming stuck\/unusable on client shutdown\n    connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide()));\n\n#ifdef ENABLE_WALLET\n    if(walletFrame)\n    {\n        connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));\n        connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));\n        connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));\n        connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));\n        connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));\n        connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses()));\n        connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses()));\n        connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked()));\n    }\n#endif \/\/ ENABLE_WALLET\n\n    new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C), this, SLOT(showDebugWindowActivateConsole()));\n    new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_D), this, SLOT(showDebugWindow()));\n}\n\nvoid BitcoinGUI::createMenuBar()\n{\n#ifdef Q_OS_MAC\n    \/\/ Create a decoupled menu bar on Mac which stays even if the window is closed\n    appMenuBar = new QMenuBar();\n#else\n    \/\/ Get the main window's menu bar on other platforms\n    appMenuBar = menuBar();\n#endif\n\n    \/\/ Configure the menus\n    QMenu *file = appMenuBar->addMenu(tr(\"&File\"));\n    if(walletFrame)\n    {\n        file->addAction(openAction);\n        file->addAction(backupWalletAction);\n        file->addAction(signMessageAction);\n        file->addAction(verifyMessageAction);\n        file->addSeparator();\n        file->addAction(usedSendingAddressesAction);\n        file->addAction(usedReceivingAddressesAction);\n        file->addSeparator();\n    }\n    file->addAction(quitAction);\n\n    QMenu *settings = appMenuBar->addMenu(tr(\"&Settings\"));\n    if(walletFrame)\n    {\n        settings->addAction(encryptWalletAction);\n        settings->addAction(changePassphraseAction);\n        settings->addSeparator();\n    }\n    settings->addAction(optionsAction);\n\n    QMenu *help = appMenuBar->addMenu(tr(\"&Help\"));\n    if(walletFrame)\n    {\n        help->addAction(openRPCConsoleAction);\n    }\n    help->addAction(showHelpMessageAction);\n    help->addSeparator();\n    help->addAction(aboutAction);\n    help->addAction(aboutQtAction);\n}\n\nvoid BitcoinGUI::createToolBars()\n{\n    if(walletFrame)\n    {\n        QToolBar *toolbar = addToolBar(tr(\"Tabs toolbar\"));\n        toolbar->setMovable(false);\n        toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);\n        toolbar->addAction(overviewAction);\n        toolbar->addAction(sendCoinsAction);\n        toolbar->addAction(receiveCoinsAction);\n        toolbar->addAction(historyAction);\n        overviewAction->setChecked(true);\n    }\n}\n\nvoid BitcoinGUI::setClientModel(ClientModel *_clientModel)\n{\n    this->clientModel = _clientModel;\n    if(_clientModel)\n    {\n        \/\/ Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,\n        \/\/ while the client has not yet fully loaded\n        createTrayIconMenu();\n\n        \/\/ Keep up to date with client\n        updateNetworkState();\n        connect(_clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));\n        connect(_clientModel, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));\n\n        modalOverlay->setKnownBestHeight(_clientModel->getHeaderTipHeight(), QDateTime::fromTime_t(_clientModel->getHeaderTipTime()));\n        setNumBlocks(_clientModel->getNumBlocks(), _clientModel->getLastBlockDate(), _clientModel->getVerificationProgress(nullptr), false);\n        connect(_clientModel, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool)));\n\n        \/\/ Receive and report messages from client model\n        connect(_clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int)));\n\n        \/\/ Show progress dialog\n        connect(_clientModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int)));\n\n        rpcConsole->setClientModel(_clientModel);\n#ifdef ENABLE_WALLET\n        if(walletFrame)\n        {\n            walletFrame->setClientModel(_clientModel);\n        }\n#endif \/\/ ENABLE_WALLET\n        unitDisplayControl->setOptionsModel(_clientModel->getOptionsModel());\n        \n        OptionsModel* optionsModel = _clientModel->getOptionsModel();\n        if(optionsModel)\n        {\n            \/\/ be aware of the tray icon disable state change reported by the OptionsModel object.\n            connect(optionsModel,SIGNAL(hideTrayIconChanged(bool)),this,SLOT(setTrayIconVisible(bool)));\n        \n            \/\/ initialize the disable state of the tray icon with the current value in the model.\n            setTrayIconVisible(optionsModel->getHideTrayIcon());\n        }\n    } else {\n        \/\/ Disable possibility to show main window via action\n        toggleHideAction->setEnabled(false);\n        if(trayIconMenu)\n        {\n            \/\/ Disable context menu on tray icon\n            trayIconMenu->clear();\n        }\n        \/\/ Propagate cleared model to child objects\n        rpcConsole->setClientModel(nullptr);\n#ifdef ENABLE_WALLET\n        if (walletFrame)\n        {\n            walletFrame->setClientModel(nullptr);\n        }\n#endif \/\/ ENABLE_WALLET\n        unitDisplayControl->setOptionsModel(nullptr);\n    }\n}\n\n#ifdef ENABLE_WALLET\nbool BitcoinGUI::addWallet(const QString& name, WalletModel *walletModel)\n{\n    if(!walletFrame)\n        return false;\n    setWalletActionsEnabled(true);\n    return walletFrame->addWallet(name, walletModel);\n}\n\nbool BitcoinGUI::setCurrentWallet(const QString& name)\n{\n    if(!walletFrame)\n        return false;\n    return walletFrame->setCurrentWallet(name);\n}\n\nvoid BitcoinGUI::removeAllWallets()\n{\n    if(!walletFrame)\n        return;\n    setWalletActionsEnabled(false);\n    walletFrame->removeAllWallets();\n}\n#endif \/\/ ENABLE_WALLET\n\nvoid BitcoinGUI::setWalletActionsEnabled(bool enabled)\n{\n    overviewAction->setEnabled(enabled);\n    sendCoinsAction->setEnabled(enabled);\n    sendCoinsMenuAction->setEnabled(enabled);\n    receiveCoinsAction->setEnabled(enabled);\n    receiveCoinsMenuAction->setEnabled(enabled);\n    historyAction->setEnabled(enabled);\n    encryptWalletAction->setEnabled(enabled);\n    backupWalletAction->setEnabled(enabled);\n    changePassphraseAction->setEnabled(enabled);\n    signMessageAction->setEnabled(enabled);\n    verifyMessageAction->setEnabled(enabled);\n    usedSendingAddressesAction->setEnabled(enabled);\n    usedReceivingAddressesAction->setEnabled(enabled);\n    openAction->setEnabled(enabled);\n}\n\nvoid BitcoinGUI::createTrayIcon(const NetworkStyle *networkStyle)\n{\n#ifndef Q_OS_MAC\n    trayIcon = new QSystemTrayIcon(this);\n    QString toolTip = tr(\"%1 client\").arg(tr(PACKAGE_NAME)) + \" \" + networkStyle->getTitleAddText();\n    trayIcon->setToolTip(toolTip);\n    trayIcon->setIcon(networkStyle->getTrayAndWindowIcon());\n    trayIcon->hide();\n#endif\n\n    notificator = new Notificator(QApplication::applicationName(), trayIcon, this);\n}\n\nvoid BitcoinGUI::createTrayIconMenu()\n{\n#ifndef Q_OS_MAC\n    \/\/ return if trayIcon is unset (only on non-Mac OSes)\n    if (!trayIcon)\n        return;\n\n    trayIconMenu = new QMenu(this);\n    trayIcon->setContextMenu(trayIconMenu);\n\n    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),\n            this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));\n#else\n    \/\/ Note: On Mac, the dock icon is used to provide the tray's functionality.\n    MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();\n    dockIconHandler->setMainWindow((QMainWindow *)this);\n    trayIconMenu = dockIconHandler->dockMenu();\n#endif\n\n    \/\/ Configuration of the tray icon (or dock icon) icon menu\n    trayIconMenu->addAction(toggleHideAction);\n    trayIconMenu->addSeparator();\n    trayIconMenu->addAction(sendCoinsMenuAction);\n    trayIconMenu->addAction(receiveCoinsMenuAction);\n    trayIconMenu->addSeparator();\n    trayIconMenu->addAction(signMessageAction);\n    trayIconMenu->addAction(verifyMessageAction);\n    trayIconMenu->addSeparator();\n    trayIconMenu->addAction(optionsAction);\n    trayIconMenu->addAction(openRPCConsoleAction);\n#ifndef Q_OS_MAC \/\/ This is built-in on Mac\n    trayIconMenu->addSeparator();\n    trayIconMenu->addAction(quitAction);\n#endif\n}\n\n#ifndef Q_OS_MAC\nvoid BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)\n{\n    if(reason == QSystemTrayIcon::Trigger)\n    {\n        \/\/ Click on system tray icon triggers show\/hide of the main window\n        toggleHidden();\n    }\n}\n#endif\n\nvoid BitcoinGUI::optionsClicked()\n{\n    if(!clientModel || !clientModel->getOptionsModel())\n        return;\n\n    OptionsDialog dlg(this, enableWallet);\n    dlg.setModel(clientModel->getOptionsModel());\n    dlg.exec();\n}\n\nvoid BitcoinGUI::aboutClicked()\n{\n    if(!clientModel)\n        return;\n\n    HelpMessageDialog dlg(this, true);\n    dlg.exec();\n}\n\nvoid BitcoinGUI::showDebugWindow()\n{\n    rpcConsole->showNormal();\n    rpcConsole->show();\n    rpcConsole->raise();\n    rpcConsole->activateWindow();\n}\n\nvoid BitcoinGUI::showDebugWindowActivateConsole()\n{\n    rpcConsole->setTabFocus(RPCConsole::TAB_CONSOLE);\n    showDebugWindow();\n}\n\nvoid BitcoinGUI::showHelpMessageClicked()\n{\n    helpMessageDialog->show();\n}\n\n#ifdef ENABLE_WALLET\nvoid BitcoinGUI::openClicked()\n{\n    OpenURIDialog dlg(this);\n    if(dlg.exec())\n    {\n        Q_EMIT receivedURI(dlg.getURI());\n    }\n}\n\nvoid BitcoinGUI::gotoOverviewPage()\n{\n    overviewAction->setChecked(true);\n    if (walletFrame) walletFrame->gotoOverviewPage();\n}\n\nvoid BitcoinGUI::gotoHistoryPage()\n{\n    historyAction->setChecked(true);\n    if (walletFrame) walletFrame->gotoHistoryPage();\n}\n\nvoid BitcoinGUI::gotoReceiveCoinsPage()\n{\n    receiveCoinsAction->setChecked(true);\n    if (walletFrame) walletFrame->gotoReceiveCoinsPage();\n}\n\nvoid BitcoinGUI::gotoSendCoinsPage(QString addr)\n{\n    sendCoinsAction->setChecked(true);\n    if (walletFrame) walletFrame->gotoSendCoinsPage(addr);\n}\n\nvoid BitcoinGUI::gotoSignMessageTab(QString addr)\n{\n    if (walletFrame) walletFrame->gotoSignMessageTab(addr);\n}\n\nvoid BitcoinGUI::gotoVerifyMessageTab(QString addr)\n{\n    if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);\n}\n#endif \/\/ ENABLE_WALLET\n\nvoid BitcoinGUI::updateNetworkState()\n{\n    int count = clientModel->getNumConnections();\n    QString icon;\n    switch(count)\n    {\n    case 0: icon = \":\/icons\/connect_0\"; break;\n    case 1: case 2: case 3: icon = \":\/icons\/connect_1\"; break;\n    case 4: case 5: case 6: icon = \":\/icons\/connect_2\"; break;\n    case 7: case 8: case 9: icon = \":\/icons\/connect_3\"; break;\n    default: icon = \":\/icons\/connect_4\"; break;\n    }\n\n    QString tooltip;\n\n    if (clientModel->getNetworkActive()) {\n        tooltip = tr(\"%n active connection(s) to Litecoin network\", \"\", count) + QString(\".<br>\") + tr(\"Click to disable network activity.\");\n    } else {\n        tooltip = tr(\"Network activity disabled.\") + QString(\"<br>\") + tr(\"Click to enable network activity again.\");\n        icon = \":\/icons\/network_disabled\";\n    }\n\n    \/\/ Don't word-wrap this (fixed-width) tooltip\n    tooltip = QString(\"<nobr>\") + tooltip + QString(\"<\/nobr>\");\n    connectionsControl->setToolTip(tooltip);\n\n    connectionsControl->setPixmap(platformStyle->SingleColorIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));\n}\n\nvoid BitcoinGUI::setNumConnections(int count)\n{\n    updateNetworkState();\n}\n\nvoid BitcoinGUI::setNetworkActive(bool networkActive)\n{\n    updateNetworkState();\n}\n\nvoid BitcoinGUI::updateHeadersSyncProgressLabel()\n{\n    int64_t headersTipTime = clientModel->getHeaderTipTime();\n    int headersTipHeight = clientModel->getHeaderTipHeight();\n    int estHeadersLeft = (GetTime() - headersTipTime) \/ Params().GetConsensus().nPowTargetSpacing;\n    if (estHeadersLeft > HEADER_HEIGHT_DELTA_SYNC)\n        progressBarLabel->setText(tr(\"Syncing Headers (%1%)...\").arg(QString::number(100.0 \/ (headersTipHeight+estHeadersLeft)*headersTipHeight, 'f', 1)));\n}\n\nvoid BitcoinGUI::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool header)\n{\n    if (modalOverlay)\n    {\n        if (header)\n            modalOverlay->setKnownBestHeight(count, blockDate);\n        else\n            modalOverlay->tipUpdate(count, blockDate, nVerificationProgress);\n    }\n    if (!clientModel)\n        return;\n\n    \/\/ Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbled text)\n    statusBar()->clearMessage();\n\n    \/\/ Acquire current block source\n    enum BlockSource blockSource = clientModel->getBlockSource();\n    switch (blockSource) {\n        case BLOCK_SOURCE_NETWORK:\n            if (header) {\n                updateHeadersSyncProgressLabel();\n                return;\n            }\n            progressBarLabel->setText(tr(\"Synchronizing with network...\"));\n            updateHeadersSyncProgressLabel();\n            break;\n        case BLOCK_SOURCE_DISK:\n            if (header) {\n                progressBarLabel->setText(tr(\"Indexing blocks on disk...\"));\n            } else {\n                progressBarLabel->setText(tr(\"Processing blocks on disk...\"));\n            }\n            break;\n        case BLOCK_SOURCE_REINDEX:\n            progressBarLabel->setText(tr(\"Reindexing blocks on disk...\"));\n            break;\n        case BLOCK_SOURCE_NONE:\n            if (header) {\n                return;\n            }\n            progressBarLabel->setText(tr(\"Connecting to peers...\"));\n            break;\n    }\n\n    QString tooltip;\n\n    QDateTime currentDate = QDateTime::currentDateTime();\n    qint64 secs = blockDate.secsTo(currentDate);\n\n    tooltip = tr(\"Processed %n block(s) of transaction history.\", \"\", count);\n\n    \/\/ Set icon state: spinning if catching up, tick otherwise\n    if(secs < 90*60)\n    {\n        tooltip = tr(\"Up to date\") + QString(\".<br>\") + tooltip;\n        labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(\":\/icons\/synced\").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));\n\n#ifdef ENABLE_WALLET\n        if(walletFrame)\n        {\n            walletFrame->showOutOfSyncWarning(false);\n            modalOverlay->showHide(true, true);\n        }\n#endif \/\/ ENABLE_WALLET\n\n        progressBarLabel->setVisible(false);\n        progressBar->setVisible(false);\n    }\n    else\n    {\n        QString timeBehindText = GUIUtil::formatNiceTimeOffset(secs);\n\n        progressBarLabel->setVisible(true);\n        progressBar->setFormat(tr(\"%1 behind\").arg(timeBehindText));\n        progressBar->setMaximum(1000000000);\n        progressBar->setValue(nVerificationProgress * 1000000000.0 + 0.5);\n        progressBar->setVisible(true);\n\n        tooltip = tr(\"Catching up...\") + QString(\"<br>\") + tooltip;\n        if(count != prevBlocks)\n        {\n            labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(QString(\n                \":\/movies\/spinner-%1\").arg(spinnerFrame, 3, 10, QChar('0')))\n                .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));\n            spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;\n        }\n        prevBlocks = count;\n\n#ifdef ENABLE_WALLET\n        if(walletFrame)\n        {\n            walletFrame->showOutOfSyncWarning(true);\n            modalOverlay->showHide();\n        }\n#endif \/\/ ENABLE_WALLET\n\n        tooltip += QString(\"<br>\");\n        tooltip += tr(\"Last received block was generated %1 ago.\").arg(timeBehindText);\n        tooltip += QString(\"<br>\");\n        tooltip += tr(\"Transactions after this will not yet be visible.\");\n    }\n\n    \/\/ Don't word-wrap this (fixed-width) tooltip\n    tooltip = QString(\"<nobr>\") + tooltip + QString(\"<\/nobr>\");\n\n    labelBlocksIcon->setToolTip(tooltip);\n    progressBarLabel->setToolTip(tooltip);\n    progressBar->setToolTip(tooltip);\n}\n\nvoid BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret)\n{\n    QString strTitle = tr(\"Litecoin\"); \/\/ default title\n    \/\/ Default to information icon\n    int nMBoxIcon = QMessageBox::Information;\n    int nNotifyIcon = Notificator::Information;\n\n    QString msgType;\n\n    \/\/ Prefer supplied title over style based title\n    if (!title.isEmpty()) {\n        msgType = title;\n    }\n    else {\n        switch (style) {\n        case CClientUIInterface::MSG_ERROR:\n            msgType = tr(\"Error\");\n            break;\n        case CClientUIInterface::MSG_WARNING:\n            msgType = tr(\"Warning\");\n            break;\n        case CClientUIInterface::MSG_INFORMATION:\n            msgType = tr(\"Information\");\n            break;\n        default:\n            break;\n        }\n    }\n    \/\/ Append title to \"Bitcoin - \"\n    if (!msgType.isEmpty())\n        strTitle += \" - \" + msgType;\n\n    \/\/ Check for error\/warning icon\n    if (style & CClientUIInterface::ICON_ERROR) {\n        nMBoxIcon = QMessageBox::Critical;\n        nNotifyIcon = Notificator::Critical;\n    }\n    else if (style & CClientUIInterface::ICON_WARNING) {\n        nMBoxIcon = QMessageBox::Warning;\n        nNotifyIcon = Notificator::Warning;\n    }\n\n    \/\/ Display message\n    if (style & CClientUIInterface::MODAL) {\n        \/\/ Check for buttons, use OK as default, if none was supplied\n        QMessageBox::StandardButton buttons;\n        if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))\n            buttons = QMessageBox::Ok;\n\n        showNormalIfMinimized();\n        QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this);\n        int r = mBox.exec();\n        if (ret != nullptr)\n            *ret = r == QMessageBox::Ok;\n    }\n    else\n        notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);\n}\n\nvoid BitcoinGUI::changeEvent(QEvent *e)\n{\n    QMainWindow::changeEvent(e);\n#ifndef Q_OS_MAC \/\/ Ignored on Mac\n    if(e->type() == QEvent::WindowStateChange)\n    {\n        if(clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray())\n        {\n            QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);\n            if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())\n            {\n                QTimer::singleShot(0, this, SLOT(hide()));\n                e->ignore();\n            }\n        }\n    }\n#endif\n}\n\nvoid BitcoinGUI::closeEvent(QCloseEvent *event)\n{\n#ifndef Q_OS_MAC \/\/ Ignored on Mac\n    if(clientModel && clientModel->getOptionsModel())\n    {\n        if(!clientModel->getOptionsModel()->getMinimizeOnClose())\n        {\n            \/\/ close rpcConsole in case it was open to make some space for the shutdown window\n            rpcConsole->close();\n\n            QApplication::quit();\n        }\n        else\n        {\n            QMainWindow::showMinimized();\n            event->ignore();\n        }\n    }\n#else\n    QMainWindow::closeEvent(event);\n#endif\n}\n\nvoid BitcoinGUI::showEvent(QShowEvent *event)\n{\n    \/\/ enable the debug window when the main window shows up\n    openRPCConsoleAction->setEnabled(true);\n    aboutAction->setEnabled(true);\n    optionsAction->setEnabled(true);\n}\n\n#ifdef ENABLE_WALLET\nvoid BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label)\n{\n    \/\/ On new transaction, make an info balloon\n    QString msg = tr(\"Date: %1\\n\").arg(date) +\n                  tr(\"Amount: %1\\n\").arg(BitcoinUnits::formatWithUnit(unit, amount, true)) +\n                  tr(\"Type: %1\\n\").arg(type);\n    if (!label.isEmpty())\n        msg += tr(\"Label: %1\\n\").arg(label);\n    else if (!address.isEmpty())\n        msg += tr(\"Address: %1\\n\").arg(address);\n    message((amount)<0 ? tr(\"Sent transaction\") : tr(\"Incoming transaction\"),\n             msg, CClientUIInterface::MSG_INFORMATION);\n}\n#endif \/\/ ENABLE_WALLET\n\nvoid BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)\n{\n    \/\/ Accept only URIs\n    if(event->mimeData()->hasUrls())\n        event->acceptProposedAction();\n}\n\nvoid BitcoinGUI::dropEvent(QDropEvent *event)\n{\n    if(event->mimeData()->hasUrls())\n    {\n        for (const QUrl &uri : event->mimeData()->urls())\n        {\n            Q_EMIT receivedURI(uri.toString());\n        }\n    }\n    event->acceptProposedAction();\n}\n\nbool BitcoinGUI::eventFilter(QObject *object, QEvent *event)\n{\n    \/\/ Catch status tip events\n    if (event->type() == QEvent::StatusTip)\n    {\n        \/\/ Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff\n        if (progressBarLabel->isVisible() || progressBar->isVisible())\n            return true;\n    }\n    return QMainWindow::eventFilter(object, event);\n}\n\n#ifdef ENABLE_WALLET\nbool BitcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient)\n{\n    \/\/ URI has to be valid\n    if (walletFrame && walletFrame->handlePaymentRequest(recipient))\n    {\n        showNormalIfMinimized();\n        gotoSendCoinsPage();\n        return true;\n    }\n    return false;\n}\n\nvoid BitcoinGUI::setHDStatus(int hdEnabled)\n{\n    labelWalletHDStatusIcon->setPixmap(platformStyle->SingleColorIcon(hdEnabled ? \":\/icons\/hd_enabled\" : \":\/icons\/hd_disabled\").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));\n    labelWalletHDStatusIcon->setToolTip(hdEnabled ? tr(\"HD key generation is <b>enabled<\/b>\") : tr(\"HD key generation is <b>disabled<\/b>\"));\n\n    \/\/ eventually disable the QLabel to set its opacity to 50% \n    labelWalletHDStatusIcon->setEnabled(hdEnabled);\n}\n\nvoid BitcoinGUI::setEncryptionStatus(int status)\n{\n    switch(status)\n    {\n    case WalletModel::Unencrypted:\n        labelWalletEncryptionIcon->hide();\n        encryptWalletAction->setChecked(false);\n        changePassphraseAction->setEnabled(false);\n        encryptWalletAction->setEnabled(true);\n        break;\n    case WalletModel::Unlocked:\n        labelWalletEncryptionIcon->show();\n        labelWalletEncryptionIcon->setPixmap(platformStyle->SingleColorIcon(\":\/icons\/lock_open\").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));\n        labelWalletEncryptionIcon->setToolTip(tr(\"Wallet is <b>encrypted<\/b> and currently <b>unlocked<\/b>\"));\n        encryptWalletAction->setChecked(true);\n        changePassphraseAction->setEnabled(true);\n        encryptWalletAction->setEnabled(false); \/\/ TODO: decrypt currently not supported\n        break;\n    case WalletModel::Locked:\n        labelWalletEncryptionIcon->show();\n        labelWalletEncryptionIcon->setPixmap(platformStyle->SingleColorIcon(\":\/icons\/lock_closed\").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));\n        labelWalletEncryptionIcon->setToolTip(tr(\"Wallet is <b>encrypted<\/b> and currently <b>locked<\/b>\"));\n        encryptWalletAction->setChecked(true);\n        changePassphraseAction->setEnabled(true);\n        encryptWalletAction->setEnabled(false); \/\/ TODO: decrypt currently not supported\n        break;\n    }\n}\n#endif \/\/ ENABLE_WALLET\n\nvoid BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)\n{\n    if(!clientModel)\n        return;\n\n    \/\/ activateWindow() (sometimes) helps with keyboard focus on Windows\n    if (isHidden())\n    {\n        show();\n        activateWindow();\n    }\n    else if (isMinimized())\n    {\n        showNormal();\n        activateWindow();\n    }\n    else if (GUIUtil::isObscured(this))\n    {\n        raise();\n        activateWindow();\n    }\n    else if(fToggleHidden)\n        hide();\n}\n\nvoid BitcoinGUI::toggleHidden()\n{\n    showNormalIfMinimized(true);\n}\n\nvoid BitcoinGUI::detectShutdown()\n{\n    if (ShutdownRequested())\n    {\n        if(rpcConsole)\n            rpcConsole->hide();\n        qApp->quit();\n    }\n}\n\nvoid BitcoinGUI::showProgress(const QString &title, int nProgress)\n{\n    if (nProgress == 0)\n    {\n        progressDialog = new QProgressDialog(title, \"\", 0, 100);\n        progressDialog->setWindowModality(Qt::ApplicationModal);\n        progressDialog->setMinimumDuration(0);\n        progressDialog->setCancelButton(0);\n        progressDialog->setAutoClose(false);\n        progressDialog->setValue(0);\n    }\n    else if (nProgress == 100)\n    {\n        if (progressDialog)\n        {\n            progressDialog->close();\n            progressDialog->deleteLater();\n        }\n    }\n    else if (progressDialog)\n        progressDialog->setValue(nProgress);\n}\n\nvoid BitcoinGUI::setTrayIconVisible(bool fHideTrayIcon)\n{\n    if (trayIcon)\n    {\n        trayIcon->setVisible(!fHideTrayIcon);\n    }\n}\n\nvoid BitcoinGUI::showModalOverlay()\n{\n    if (modalOverlay && (progressBar->isVisible() || modalOverlay->isLayerVisible()))\n        modalOverlay->toggleVisibility();\n}\n\nstatic bool ThreadSafeMessageBox(BitcoinGUI *gui, const std::string& message, const std::string& caption, unsigned int style)\n{\n    bool modal = (style & CClientUIInterface::MODAL);\n    \/\/ The SECURE flag has no effect in the Qt GUI.\n    \/\/ bool secure = (style & CClientUIInterface::SECURE);\n    style &= ~CClientUIInterface::SECURE;\n    bool ret = false;\n    \/\/ In case of modal message, use blocking connection to wait for user to click a button\n    QMetaObject::invokeMethod(gui, \"message\",\n                               modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,\n                               Q_ARG(QString, QString::fromStdString(caption)),\n                               Q_ARG(QString, QString::fromStdString(message)),\n                               Q_ARG(unsigned int, style),\n                               Q_ARG(bool*, &ret));\n    return ret;\n}\n\nvoid BitcoinGUI::subscribeToCoreSignals()\n{\n    \/\/ Connect signals to client\n    uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));\n    uiInterface.ThreadSafeQuestion.connect(boost::bind(ThreadSafeMessageBox, this, _1, _3, _4));\n}\n\nvoid BitcoinGUI::unsubscribeFromCoreSignals()\n{\n    \/\/ Disconnect signals from client\n    uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));\n    uiInterface.ThreadSafeQuestion.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _3, _4));\n}\n\nvoid BitcoinGUI::toggleNetworkActive()\n{\n    if (clientModel) {\n        clientModel->setNetworkActive(!clientModel->getNetworkActive());\n    }\n}\n\nUnitDisplayStatusBarControl::UnitDisplayStatusBarControl(const PlatformStyle *platformStyle) :\n    optionsModel(0),\n    menu(0)\n{\n    createContextMenu();\n    setToolTip(tr(\"Unit to show amounts in. Click to select another unit.\"));\n    QList<BitcoinUnits::Unit> units = BitcoinUnits::availableUnits();\n    int max_width = 0;\n    const QFontMetrics fm(font());\n    for (const BitcoinUnits::Unit unit : units)\n    {\n        max_width = qMax(max_width, fm.width(BitcoinUnits::name(unit)));\n    }\n    setMinimumSize(max_width, 0);\n    setAlignment(Qt::AlignRight | Qt::AlignVCenter);\n    setStyleSheet(QString(\"QLabel { color : %1 }\").arg(platformStyle->SingleColor().name()));\n}\n\n\/** So that it responds to button clicks *\/\nvoid UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent *event)\n{\n    onDisplayUnitsClicked(event->pos());\n}\n\n\/** Creates context menu, its actions, and wires up all the relevant signals for mouse events. *\/\nvoid UnitDisplayStatusBarControl::createContextMenu()\n{\n    menu = new QMenu(this);\n    for (BitcoinUnits::Unit u : BitcoinUnits::availableUnits())\n    {\n        QAction *menuAction = new QAction(QString(BitcoinUnits::name(u)), this);\n        menuAction->setData(QVariant(u));\n        menu->addAction(menuAction);\n    }\n    connect(menu,SIGNAL(triggered(QAction*)),this,SLOT(onMenuSelection(QAction*)));\n}\n\n\/** Lets the control know about the Options Model (and its signals) *\/\nvoid UnitDisplayStatusBarControl::setOptionsModel(OptionsModel *_optionsModel)\n{\n    if (_optionsModel)\n    {\n        this->optionsModel = _optionsModel;\n\n        \/\/ be aware of a display unit change reported by the OptionsModel object.\n        connect(_optionsModel,SIGNAL(displayUnitChanged(int)),this,SLOT(updateDisplayUnit(int)));\n\n        \/\/ initialize the display units label with the current value in the model.\n        updateDisplayUnit(_optionsModel->getDisplayUnit());\n    }\n}\n\n\/** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar *\/\nvoid UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits)\n{\n    setText(BitcoinUnits::name(newUnits));\n}\n\n\/** Shows context menu with Display Unit options by the mouse coordinates *\/\nvoid UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point)\n{\n    QPoint globalPos = mapToGlobal(point);\n    menu->exec(globalPos);\n}\n\n\/** Tells underlying optionsModel to update its current display unit. *\/\nvoid UnitDisplayStatusBarControl::onMenuSelection(QAction* action)\n{\n    if (action)\n    {\n        optionsModel->setDisplayUnit(action->data());\n    }\n}\n","avg_line_length":35.5208825847,"max_line_length":307,"alphanum_fraction":0.6907667051,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":550,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"base_type.h\"\n#include \"configurations.h\"\n#include \"log.h\"\n\nConfigurations::Configurations(const wstring& configFilePath, int argc, char** argv) {\n\tspdlog::info(\"Configurations\");\n\tbootStrapClassPath = L\"D:\/jvm\/modules\/java.base\";\n\tappClassPath = L\"D:\/github\/minijvm\/MiniJVM\/testclasses\";\n\t\/\/ \u5148\u5199\u6b7b\u4e86\u3002\u6d4b\u8bd5\uff0c\u4e4b\u540e\u4f1a\u4ece\u53c2\u6570\u89e3\u6790\u51fa\u6765\u3002\n\ttargetClass = L\"icu.mianshi.main.HelloMiniJvm\";\n}\n\n\nstring Configurations::toString() {\n\tstring s;\n\ts.append(\"MethodAreaType:\");\n\ts.append((this->isExtensibleMethodArea() ? \"Exensible\" : \"Fixed\"));\n\ts.append(\"\\n\");\n\treturn s;\n}","avg_line_length":27.5,"max_line_length":86,"alphanum_fraction":0.7236363636,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":813,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":null,"content":"\n\n#include <test\/jtx\/ticket.h>\n#include <ripple\/protocol\/jss.h>\n\nnamespace ripple {\nnamespace test {\nnamespace jtx {\n\nnamespace ticket {\n\nnamespace detail {\n\nJson::Value\ncreate (Account const& account,\n    boost::optional<Account> const& target,\n        boost::optional<std::uint32_t> const& expire)\n{\n    Json::Value jv;\n    jv[jss::Account] = account.human();\n    jv[jss::TransactionType] = jss::TicketCreate;\n    if (expire)\n        jv[\"Expiration\"] = *expire;\n    if (target)\n        jv[\"Target\"] = target->human();\n    return jv;\n}\n\n} \n\nJson::Value\ncancel(Account const& account, std::string const & ticketId)\n{\n    Json::Value jv;\n    jv[jss::TransactionType] = jss::TicketCancel;\n    jv[jss::Account] = account.human();\n    jv[\"TicketID\"] = ticketId;\n    return jv;\n}\n\n} \n\n} \n} \n} \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","avg_line_length":11.6142857143,"max_line_length":60,"alphanum_fraction":0.6137761378,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3569,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"editaddressdialog.h\"\n#include \"ui_editaddressdialog.h\"\n#include \"addresstablemodel.h\"\n#include \"guiutil.h\"\n\n#include <QDataWidgetMapper>\n#include <QMessageBox>\n\nEditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :\n    QDialog(parent),\n    ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)\n{\n    ui->setupUi(this);\n\n    GUIUtil::setupAddressWidget(ui->addressEdit, this);\n\n    switch(mode)\n    {\n    case NewReceivingAddress:\n        setWindowTitle(tr(\"New receiving address\"));\n        ui->addressEdit->setEnabled(false);\n        break;\n    case NewSendingAddress:\n        setWindowTitle(tr(\"New sending address\"));\n        break;\n    case EditReceivingAddress:\n        setWindowTitle(tr(\"Edit receiving address\"));\n        ui->addressEdit->setDisabled(true);\n        break;\n    case EditSendingAddress:\n        setWindowTitle(tr(\"Edit sending address\"));\n        break;\n    }\n\n    mapper = new QDataWidgetMapper(this);\n    mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);\n}\n\nEditAddressDialog::~EditAddressDialog()\n{\n    delete ui;\n}\n\nvoid EditAddressDialog::setModel(AddressTableModel *model)\n{\n    this->model = model;\n    mapper->setModel(model);\n    mapper->addMapping(ui->labelEdit, AddressTableModel::Label);\n    mapper->addMapping(ui->addressEdit, AddressTableModel::Address);\n}\n\nvoid EditAddressDialog::loadRow(int row)\n{\n    mapper->setCurrentIndex(row);\n}\n\nbool EditAddressDialog::saveCurrentRow()\n{\n    if(!model)\n        return false;\n    switch(mode)\n    {\n    case NewReceivingAddress:\n    case NewSendingAddress:\n        address = model->addRow(\n                mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,\n                ui->labelEdit->text(),\n                ui->addressEdit->text());\n        break;\n    case EditReceivingAddress:\n    case EditSendingAddress:\n        if(mapper->submit())\n        {\n            address = ui->addressEdit->text();\n        }\n        break;\n    }\n    return !address.isEmpty();\n}\n\nvoid EditAddressDialog::accept()\n{\n    if(!model)\n        return;\n    if(!saveCurrentRow())\n    {\n        switch(model->getEditStatus())\n        {\n        case AddressTableModel::DUPLICATE_ADDRESS:\n            QMessageBox::warning(this, windowTitle(),\n                tr(\"The entered address \\\"%1\\\" is already in the address book.\").arg(ui->addressEdit->text()),\n                QMessageBox::Ok, QMessageBox::Ok);\n            break;\n        case AddressTableModel::INVALID_ADDRESS:\n            QMessageBox::warning(this, windowTitle(),\n                tr(\"The entered address \\\"%1\\\" is not a valid GoldRushCoin address.\").arg(ui->addressEdit->text()),\n                QMessageBox::Ok, QMessageBox::Ok);\n            return;\n        case AddressTableModel::WALLET_UNLOCK_FAILURE:\n            QMessageBox::critical(this, windowTitle(),\n                tr(\"Could not unlock wallet.\"),\n                QMessageBox::Ok, QMessageBox::Ok);\n            return;\n        case AddressTableModel::KEY_GENERATION_FAILURE:\n            QMessageBox::critical(this, windowTitle(),\n                tr(\"New key generation failed.\"),\n                QMessageBox::Ok, QMessageBox::Ok);\n            return;\n        case AddressTableModel::OK:\n            \/\/ Failed with unknown reason. Just reject.\n            break;\n        }\n\n        return;\n    }\n    QDialog::accept();\n}\n\nQString EditAddressDialog::getAddress() const\n{\n    return address;\n}\n\nvoid EditAddressDialog::setAddress(const QString &address)\n{\n    this->address = address;\n    ui->addressEdit->setText(address);\n}\n","avg_line_length":27.6666666667,"max_line_length":115,"alphanum_fraction":0.6242644999,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1986,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"#pragma GCC optimize(\"Ofast\")\n#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma\")\n#pragma GCC optimize(\"unroll-loops\")\n#include <bits\/stdc++.h>\n#include <complex>\n#include <queue>\n#include <set>\n#include <unordered_set>\n#include <list>\n#include <chrono>\n#include <random>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <string>\n#include <vector>\n#include <map>\n#include <unordered_map>\n#include <stack>\n#include <iomanip>\n#include <fstream>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> p32;\ntypedef pair<ll, ll> p64;\ntypedef pair<double, double> pdd;\ntypedef vector<ll> v64;\ntypedef vector<int> v32;\ntypedef vector<vector<int>> vv32;\ntypedef vector<vector<ll>> vv64;\ntypedef vector<vector<p64>> vvp64;\ntypedef vector<p64> vp64;\ntypedef vector<p32> vp32;\nll MOD = 1000000007;\ndouble eps = 1e-12;\n#define forn(i, n) for (ll i = 0; i < n; i++)\n#define forsn(i, s, e) for (ll i = s; i < e; i++)\n#define rforn(i, s) for (ll i = s; i >= 0; i--)\n#define rforsn(i, s, e) for (ll i = s; i >= e; i--)\n#define ln \"\\n\"\n#define dbg(x) cout << #x << \" = \" << x << ln\n#define mp make_pair\n#define pb push_back\n#define fi first\n#define se second\n#define INF 2e18\n#define fast_cin()                    \\\n    ios_base::sync_with_stdio(false); \\\n    cin.tie(NULL);                    \\\n    cout.tie(NULL)\n#define all(x) (x).begin(), (x).end()\n#define al(arr, n) arr, arr + n\n#define sz(x) ((ll)(x).size())\nbool compare(ll a, ll b)\n{\n    return a > b;\n}\n\nvoid solve()\n{\n    ll n, m, k;\n    cin >> n >> m >> k;\n    ll arr[n];\n    forn(i, n)\n    {\n        cin >> arr[i];\n    }\n    sort(arr, arr + n, compare);\n    ll first = arr[0], second = arr[1];\n    ll rep = first * k + second;\n    ll res = (rep * (m \/ (k + 1))) + (m % (k + 1)) * first;\n    cout << res << endl;\n}\nint main()\n{\n    fast_cin();\n    \/\/ ll t;\n    \/\/ cin >> t;\n    \/\/ for (int it = 1; it <= t; it++)\n    \/\/ {\n        solve();\n    \/\/ }\n    return 0;\n}","avg_line_length":22.8275862069,"max_line_length":74,"alphanum_fraction":0.5871097684,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":22447,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":8.0,"content":"\/**\n* @author  Ian Stangoe\n*\n* LICENSE:\n* \n* This source file is part of OgreOggSound, an OpenAL wrapper library for   \n* use with the Ogre Rendering Engine.\t\t\t\t\t\t\t\t\t\t \n*                                                                           \n* Copyright (c) 2017 Ian Stangoe\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in\n* all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n* THE SOFTWARE. \t \n*\n*\/\n\n#include \"OgreOggStreamWavSound.h\"\n#include <string>\n#include <iostream>\n#include \"OgreOggSoundManager.h\"\n\nnamespace OgreOggSound\n{\n\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tOgreOggStreamWavSound::OgreOggStreamWavSound(\n\t\tconst Ogre::String& name\n\t\t#if OGRE_VERSION_MAJOR == 2\n\t\t, Ogre::IdType id, Ogre::ObjectMemoryManager *objMemMgr, Ogre::uint8 renderQueueId\n\t\t#endif\n\t) : OgreOggISound(\n\t\tname\n\t\t#if OGRE_VERSION_MAJOR == 2\n\t\t, id, objMemMgr, renderQueueId\n\t\t#endif\n\t)\n\t, mLoopOffsetBytes(0)\n\t, mStreamEOF(false)\n\t, mLastOffset(0.f)\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   \n\t\tmBuffers.reset(new BufferList(NUM_BUFFERS, AL_NONE));\n\t\tmFormatData.mFormat=0;\n\t\tmStream = true;\t   \n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tOgreOggStreamWavSound::~OgreOggStreamWavSound()\n\t{\t\t\n\t\t\/\/ Notify listener\n\t\tif ( mSoundListener ) mSoundListener->soundDestroyed(this);\n\t\n\t\t_release();\n\t\tif (mFormatData.mFormat) OGRE_DELETE_T(mFormatData.mFormat, WaveHeader, Ogre::MEMCATEGORY_GENERAL);\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tvoid OgreOggStreamWavSound::_openImpl(Ogre::DataStreamPtr& fileStream)\n\t{\n\t\t\/\/ WAVE descriptor vars\n\t\tChunkHeader\t\tc;\n\n\t\t\/\/ Store stream pointer\n\t\tmAudioStream = fileStream;\n\n\t\t\/\/ Allocate format structure\n\t\tmFormatData.mFormat = OGRE_NEW_T(WaveHeader, Ogre::MEMCATEGORY_GENERAL);\n\n\t\t\/\/ Read in \"RIFF\" chunk descriptor (4 bytes)\n\t\tmAudioStream->read(mFormatData.mFormat, sizeof(WaveHeader));\n\n\t\tOgre::String format;\n\t\tswitch(mFormatData.mFormat->mFormatTag)\n\t\t{\n\t\t\tcase 0x0001:\n\t\t\t\tformat = \"PCM\";\n\t\t\t\tbreak;\n\t\t\tcase 0x0003:\n\t\t\t\tformat = \"IEEE float (unsupported)\";\n\t\t\t\tbreak;\n\t\t\tcase 0x0006:\n\t\t\t\tformat = \"8-bit ITU-T G.711 A-law (unsupported)\";\n\t\t\t\tbreak;\n\t\t\tcase 0x0007:\n\t\t\t\tformat = \"8-bit ITU-T G.711 \u00b5-law (unsupported)\";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tformat = \"*unknown* (unsupported)\";\n\t\t\t\tbreak;\n\t\t}\n\n\t\tOgre::LogManager::getSingleton().logMessage(\"Sound '\" + mAudioStream->getName() + \"': Loading WAV with \" +\n\t\t\tOgre::StringConverter::toString(mFormatData.mFormat->mChannels) + \" channels, \" +\n\t\t\tOgre::StringConverter::toString(mFormatData.mFormat->mSamplesPerSec) + \" Hz, \" +\n\t\t\tOgre::StringConverter::toString(mFormatData.mFormat->mBitsPerSample) + \" bps \" +\n\t\t\tformat + \" format.\");\n\n\t\t\/\/ Valid 'RIFF'?\n\t\tif ( strncmp(mFormatData.mFormat->mRIFF, \"RIFF\", 4) != 0 )\n\t\t{\n\t\t\tOGRE_EXCEPT(Ogre::Exception::ERR_FILE_NOT_FOUND, fileStream->getName() + \" - Not a valid RIFF file!\", \"OgreOggStreamWavSound::_openImpl()\");\n\t\t}\n\n\t\t\/\/ Valid 'WAVE'?\n\t\tif ( strncmp(mFormatData.mFormat->mWAVE, \"WAVE\", 4) != 0 )\n\t\t{\n\t\t\tOGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, fileStream->getName() + \" - Not a valid WAVE file!\", \"OgreOggStreamWavSound::_openImpl()\");\n\t\t}\n\n\t\t\/\/ Valid 'fmt '?\n\t\tif ( strncmp(mFormatData.mFormat->mFMT, \"fmt\", 3) != 0 )\n\t\t{\n\t\t\tOGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, fileStream->getName() + \" - Invalid Format!\", \"OgreOggStreamWavSound::_openImpl()\");\n\t\t}\n\n\t\t\/\/ mFormatData.mFormat: Should be 16 unless compressed ( compressed NOT supported )\n\t\tif ( !mFormatData.mFormat->mHeaderSize>=16 )\n\t\t{\n\t\t\tOGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, fileStream->getName() + \" - Compressed WAV NOT supported!\", \"OgreOggStreamWavSound::_openImpl()\");\n\t\t}\n\n\t\t\/\/ PCM == 1\n\t\tif ( (mFormatData.mFormat->mFormatTag != 0x0001) && (mFormatData.mFormat->mFormatTag != 0xFFFE) )\n\t\t{\n\t\t\tOGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, fileStream->getName() + \" - WAV file NOT in PCM format!\", \"OgreOggStreamWavSound::_openImpl()\");\n\t\t}\n\n\t\t\/\/ Samples check..\n\t\tif ( (mFormatData.mFormat->mBitsPerSample!=16) && (mFormatData.mFormat->mBitsPerSample!=8) )\n\t\t{\n\t\t\tOGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, fileStream->getName() + \" - BitsPerSample NOT 8\/16, unsupported format!\", \"OgreOggStreamWavSound::_openImpl()\");\n\t\t}\n\n\t\t\/\/ Calculate extra WAV header info\n\t\tint extraBytes = mFormatData.mFormat->mHeaderSize - (sizeof(WaveHeader) - 20);\n\n\t\t\/\/ If WAVEFORMATEXTENSIBLE read attributes\n\t\tif (mFormatData.mFormat->mFormatTag==0xFFFE)\n\t\t{\n\t\t\textraBytes-=static_cast<int>(mAudioStream->read(&mFormatData.mSamples, 2));\n\t\t\textraBytes-=static_cast<int>(mAudioStream->read(&mFormatData.mChannelMask, 2));\n\t\t\textraBytes-=static_cast<int>(mAudioStream->read(&mFormatData.mSubFormat, 16));\n\t\t}\n\n\t\t\/\/ Skip\n\t\tmAudioStream->skip(extraBytes);\n\n\t\tdo\n\t\t{\n\t\t\t\/\/ Read in chunk header\n\t\t\tmAudioStream->read(&c, sizeof(ChunkHeader));\n\n\t\t\t\/\/ 'data' chunk...\n\t\t\tif ( strncmp(c.chunkID, \"data\", 4) == 0 )\n\t\t\t{\n\t\t\t\t\/\/ Store byte offset of start of audio data\n\t\t\t\tmAudioOffset = static_cast<unsigned int>(mAudioStream->tell());\n\n\t\t\t\t\/\/ Check data size\n\t\t\t\tint fileCheck = c.length % mFormatData.mFormat->mBlockAlign;\n\n\t\t\t\t\/\/ Store end pos\n\t\t\t\tmAudioEnd = mAudioOffset+(c.length-fileCheck);\n\n\t\t\t\t\/\/ Jump out\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\/\/ Skip unsupported chunk...\n\t\t\telse {\n\t\t\t\tif( (mAudioStream->tell() \/ sizeof(ChunkHeader)) % 100000 == 0)\n\t\t\t\t\tOgre::LogManager::getSingleton().logMessage(\"OgreOggStreamWavSound::_openImpl() - Looking for 'data' chunk in: \" + fileStream->getName());\n\n\t\t\t\tmAudioStream->skip(c.length);\n\t\t\t}\n\t\t}\n\t\twhile ( mAudioStream->eof() || ( strncmp(c.chunkID, \"data\", 4) != 0 ));\n\n\t\t\/\/ Create OpenAL buffer\n\t\talGetError();\t\t\t\t\t\t\t   \n\t\talGenBuffers(NUM_BUFFERS, &(*mBuffers)[0]);\n\t\tif ( alGetError()!=AL_NO_ERROR )\n\t\t\tOGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, \"Unable to create OpenAL buffer.\", \"OgreOggStreamWavSound::_openImpl()\");\n\n\t\t\/\/ Check format support\n\t\tif (!_queryBufferInfo())\n\t\t{\n\t\t\tOGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, \"Format NOT supported\", \"OgreOggStreamWavSound::_openImpl()\");\n\t\t}\n\n\t\t\/\/ Calculate length in seconds\n\t\tmPlayTime = static_cast<float>(((mAudioEnd-mAudioOffset)*8.f) \/ static_cast<float>((mFormatData.mFormat->mSamplesPerSec * mFormatData.mFormat->mChannels * mFormatData.mFormat->mBitsPerSample)));\n\n#if HAVE_EFX == 1\n\t\t\/\/ Upload to XRAM buffers if available\n\t\tif ( OgreOggSoundManager::getSingleton().hasXRamSupport() )\n\t\t\tOgreOggSoundManager::getSingleton().setXRamBuffer(NUM_BUFFERS, &(*mBuffers)[0]);\n#endif\n\t\t\/\/ Calculate loop offset in bytes\n\t\t\/\/ Set BEFORE sound loaded\n\t\tif ( mLoopOffset>0.f )\n\t\t{\n\t\t\tif ( mLoopOffset<mPlayTime ) \n\t\t\t{\n\t\t\t\t\/\/ Calculate offset in bytes aligned to block align\n\t\t\t\tmLoopOffsetBytes = static_cast<unsigned int>((mLoopOffset * (mFormatData.mFormat->mSamplesPerSec * mFormatData.mFormat->mChannels * mFormatData.mFormat->mBitsPerSample))\/8);\n\t\t\t\tmLoopOffsetBytes -= mLoopOffsetBytes % mFormatData.mFormat->mBlockAlign;\n\t\t\t}\n\t\t\telse\t\t\t\n\t\t\t{\n\t\t\t\tOgre::LogManager::getSingleton().logError(\"OgreOggStreamWavSound::_openImpl() - Loop time invalid!\");\n\t\t\t\tmLoopOffset=0.f;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\/\/ Notify listener\n\t\tif ( mSoundListener ) mSoundListener->soundLoaded(this);\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tbool OgreOggStreamWavSound::isMono()\n\t{\n\t\tif ( !mInitialised ) return false;\n\n\t\treturn ( (mFormat==AL_FORMAT_MONO16) || (mFormat==AL_FORMAT_MONO8) );\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tbool OgreOggStreamWavSound::_queryBufferInfo()\n\t{\n\t\tif ( !mFormatData.mFormat ) return false;\n\n\t\tswitch(mFormatData.mFormat->mChannels)\n\t\t{\n\t\tcase 1:\n\t\t\t{\n\t\t\t\tif ( mFormatData.mFormat->mBitsPerSample==8 )\n\t\t\t\t{\n\t\t\t\t\t\/\/ 8-bit mono\n\t\t\t\t\tmFormat = AL_FORMAT_MONO8;\n\n\t\t\t\t\t\/\/ IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ...\n\t\t\t\t\tmBufferSize = mFormatData.mFormat->mSamplesPerSec\/4;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ 16-bit mono\n\t\t\t\t\tmFormat = AL_FORMAT_MONO16;\n\n\t\t\t\t\t\/\/ Queue 250ms of audio data\n\t\t\t\t\tmBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2;\n\n\t\t\t\t\t\/\/ IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ...\n\t\t\t\t\tmBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\t{\n\t\t\t\tif ( mFormatData.mFormat->mBitsPerSample==8 )\n\t\t\t\t{\n\t\t\t\t\t\/\/ 8-bit stereo\n\t\t\t\t\tmFormat = AL_FORMAT_STEREO8;\n\n\t\t\t\t\t\/\/ Set BufferSize to 250ms (Frequency * 2 (8bit stereo) divided by 4 (quarter of a second))\n\t\t\t\t\tmBufferSize = mFormatData.mFormat->mSamplesPerSec >> 1;\n\n\t\t\t\t\t\/\/ IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ...\n\t\t\t\t\tmBufferSize -= (mBufferSize % 2);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ 16-bit stereo\n\t\t\t\t\tmFormat = AL_FORMAT_STEREO16;\n\n\t\t\t\t\t\/\/ Queue 250ms of audio data\n\t\t\t\t\tmBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2;\n\n\t\t\t\t\t\/\/ IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ...\n\t\t\t\t\tmBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\t{\n\t\t\t\t\/\/ 16-bit Quad surround\n\t\t\t\tmFormat = alGetEnumValue(\"AL_FORMAT_QUAD16\");\n\t\t\t\tif (!mFormat) return false;\n\n\t\t\t\t\/\/ Queue 250ms of audio data\n\t\t\t\tmBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2;\n\n\t\t\t\t\/\/ IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ...\n\t\t\t\tmBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 6:\n\t\t\t{\n\t\t\t\t\/\/ 16-bit 5.1 surround\n\t\t\t\tmFormat = alGetEnumValue(\"AL_FORMAT_51CHN16\");\n\t\t\t\tif (!mFormat) return false;\n\n\t\t\t\t\/\/ Queue 250ms of audio data\n\t\t\t\tmBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2;\n\n\t\t\t\t\/\/ IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ...\n\t\t\t\tmBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 7:\n\t\t\t{\n\t\t\t\t\/\/ 16-bit 7.1 surround\n\t\t\t\tmFormat = alGetEnumValue(\"AL_FORMAT_61CHN16\");\n\t\t\t\tif (!mFormat) return false;\n\n\t\t\t\t\/\/ Queue 250ms of audio data\n\t\t\t\tmBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2;\n\n\t\t\t\t\/\/ IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ...\n\t\t\t\tmBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\t{\n\t\t\t\t\/\/ 16-bit 8.1 surround\n\t\t\t\tmFormat = alGetEnumValue(\"AL_FORMAT_71CHN16\");\n\t\t\t\tif (!mFormat) return false;\n\n\t\t\t\t\/\/ Queue 250ms of audio data\n\t\t\t\tmBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2;\n\n\t\t\t\t\/\/ IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ...\n\t\t\t\tmBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t{\n\t\t\t\t\/\/ Error message\n\t\t\t\tOgre::LogManager::getSingleton().logMessage(\"Unable to determine number of channels: defaulting to 16-bit stereo\");\n\n\t\t\t\t\/\/ 16-bit stereo\n\t\t\t\tmFormat = AL_FORMAT_STEREO16;\n\n\t\t\t\t\/\/ Queue 250ms of audio data\n\t\t\t\tmBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2;\n\n\t\t\t\t\/\/ IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ...\n\t\t\t\tmBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\treturn true;\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tvoid OgreOggStreamWavSound::_release()\n\t{\n\t\tif ( mSource!=AL_NONE )\n\t\t{\n\t\t\tsetSource(AL_NONE);\n\t\t}\n\t\tfor (int i=0; i<NUM_BUFFERS; i++)\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\tif ((*mBuffers)[i]!=AL_NONE)\n\t\t\t\talDeleteBuffers(1, &(*mBuffers)[i]);\n\t\t}\n\t\tmPlayPosChanged = false;\n\t\tmPlayPos = 0.f;\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tvoid OgreOggStreamWavSound::_prebuffer()\n\t{\n\t\tif (mSource==AL_NONE) return;\n\n\t\tint i=0;\n\t\twhile ( i<NUM_BUFFERS )\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\tif ( _stream((*mBuffers)[i]) )\n\t\t\t\talSourceQueueBuffers(mSource, 1, &(*mBuffers)[i++]);\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tvoid OgreOggStreamWavSound::setSource(ALuint src)\n\t{\n\t\tif (src!=AL_NONE)\n\t\t{\n\t\t\t\/\/ Set source\n\t\t\tmSource=src;\n\n\t\t\t\/\/ Fill data buffers\n\t\t\t_prebuffer();\n\n\t\t\t\/\/ Init source\n\t\t\t_initSource();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Unqueue buffers\n\t\t\t_dequeue();\n\n\t\t\t\/\/ Set source\n\t\t\tmSource=src;\n\n\t\t\t\/\/ Cancel initialisation\n\t\t\tmInitialised = false;\n\t\t}\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tvoid OgreOggStreamWavSound::_updateAudioBuffers()\n\t{\n\t\tif (!isPlaying()) return;\n\n\t\tALenum state;\n\t\talGetSourcei(mSource, AL_SOURCE_STATE, &state);\n\n\t\tif (state == AL_PAUSED) return;\n\n\t\t\/\/ Ran out of buffer data?\n\t\tif (state == AL_STOPPED)\n\t\t{\n\t\t\tif(mStreamEOF)\n\t\t\t{\n\t\t\t\tstop();\t\t\t\n\n\t\t\t\t\/\/ Finished callback\n\t\t\t\tif ( mSoundListener ) \n\t\t\t\t\tmSoundListener->soundFinished(this);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ Clear audio data already played...\n\t\t\t\t_dequeue();\n\n\t\t\t\t\/\/ Fill with next chunk of audio...\n\t\t\t\t_prebuffer();\n\n\t\t\t\t\/\/ Play...\n\t\t\t\talSourcePlay(mSource);\n\t\t\t}\n\t\t}\n\n\t\tint processed;\n\n\t\talGetSourcei(mSource, AL_BUFFERS_PROCESSED, &processed);\n\n\t\twhile(processed--)\n\t\t{\n\t\t\tALuint buffer;\n\t\t\tALint size, bits, channels, freq;\n\n\t\t\talSourceUnqueueBuffers(mSource, 1, &buffer);\n\n\t\t\t\/\/ Get buffer details\n\t\t\talGetBufferi(buffer, AL_SIZE, &size);\n\t\t\talGetBufferi(buffer, AL_BITS, &bits);\n\t\t\talGetBufferi(buffer, AL_CHANNELS, &channels);\n\t\t\talGetBufferi(buffer, AL_FREQUENCY, &freq);    \n\n\t\t\t\/\/ Update offset (in seconds)\n\t\t\tmLastOffset += ((ALuint)size\/channels\/(bits\/8)) \/ (ALfloat)freq;\n\t\t\tif ( mLastOffset>=mPlayTime )\n\t\t\t{\n\t\t\t\tmLastOffset = mLastOffset-mPlayTime;\n\t\t\t\t\n\t\t\t\t\/**\tThis is the closest we can get to a loop trigger.\n\t\t\t\t@remarks \n\t\t\t\t\tIf played data size exceeds audio data size trigger callback.\n\t\t\t\t*\/\n\t\t\t\tif ( mSoundListener ) mSoundListener->soundLooping(this);\n\t\t\t}\n\n\t\t\tif ( _stream(buffer) ) \n\t\t\t{\n\t\t\t\talSourceQueueBuffers(mSource, 1, &buffer);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Handle play position change\n\t\tif ( mPlayPosChanged )\n\t\t{\n\t\t\t_updatePlayPosition();\n\t\t}\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tvoid OgreOggStreamWavSound::setLoopOffset(float startTime)\n\t{\n\t\t\/\/ Store requested loop time\n\t\tmLoopOffset = startTime;\n\n\t\t\/\/ Is sound ready?\n\t\tif ( !mAudioStream )\n\t\t{\n\t\t\t\/\/ Check valid loop point\n\t\t\tif ( mLoopOffset>=mPlayTime ) \n\t\t\t{\n\t\t\t\tOgre::LogManager::getSingleton().logError(\"OgreOggStreamWavSound::setLoopOffset() - Loop time invalid!\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ Calculate offset in bytes block aligned\n\t\t\tmLoopOffsetBytes = static_cast<unsigned int>(mLoopOffset * (mFormatData.mFormat->mSamplesPerSec));\n\t\t\tmLoopOffsetBytes -= mLoopOffsetBytes % mFormatData.mFormat->mBlockAlign;\n\t\t}\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tbool OgreOggStreamWavSound::_stream(ALuint buffer)\n\t{\n\t\tstd::vector<char> audioData;\n\t\tchar* data;\n\t\tint  bytes = 0;\n\t\tint  result = 0;\n\n\t\t\/\/ Create buffer\n\t\tdata = OGRE_ALLOC_T(char, mBufferSize, Ogre::MEMCATEGORY_GENERAL);\n\t\tmemset(data, 0, mBufferSize);\n\t\t\n\t\t\/\/ Read only what was asked for\n\t\twhile( !mStreamEOF && (static_cast<int>(audioData.size()) < mBufferSize) )\n\t\t{\n\t\t\tsize_t currPos = mAudioStream->tell();\n\t\t\t\/\/ Is looping about to occur?\n\t\t\tif ( (currPos+mBufferSize) > mAudioEnd )\n\t\t\t{\n\t\t\t\t\/\/ Calculate remaining data size\n\t\t\t\tsize_t remaining = mAudioEnd-currPos;\n\t\t\t\t\/\/ Read up to a buffer's worth of data\n\t\t\t\tif ( remaining )\n\t\t\t\t\tbytes = static_cast<int>(mAudioStream->read(data, remaining));\n\t\t\t\t\/\/ If set to loop wrap to start of stream\n\t\t\t\tif ( mLoop )\n\t\t\t\t{\n\t\t\t\t\tmAudioStream->seek(mAudioOffset + mLoopOffsetBytes);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tmStreamEOF=true;\n\t\t\t\t\t\/\/ EOF - finish.\n\t\t\t\t\tif (bytes==0) break;\n\t\t\t\t}\n\t\t\t\t\/\/ Append to end of buffer\n\t\t\t\taudioData.insert(audioData.end(), data, data + bytes);\n\t\t\t\t\/\/ Keep track of read data\n\t\t\t\tresult+=bytes;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ Read up to a buffer's worth of data\n\t\t\t\tbytes = static_cast<int>(mAudioStream->read(data, mBufferSize));\n\t\t\t\t\/\/ EOF check\n\t\t\t\tif (mAudioStream->eof())\n\t\t\t\t{\n\t\t\t\t\t\/\/ If set to loop wrap to start of stream\n\t\t\t\t\tif ( mLoop )\n\t\t\t\t\t{\n\t\t\t\t\t\tmAudioStream->seek(mAudioOffset);\n\t\t\t\t\t\t\/**\tThis is the closest we can get to a loop trigger.\n\t\t\t\t\t\tIf, whilst filling the buffers, we need to wrap the stream\n\t\t\t\t\t\tpointer, trigger the loop callback if defined.\n\t\t\t\t\t\tNOTE:- The accuracy of this method will be affected by a number of\n\t\t\t\t\t\tparameters, namely the buffer size, whether the sound has previously\n\t\t\t\t\t\tgiven up its source (therefore it will be re-filling all buffers, which,\n\t\t\t\t\t\tif the sound was close to eof will likely get triggered), and the quality\n\t\t\t\t\t\tof the sound, lower quality will hold a longer section of audio per buffer.\n\t\t\t\t\t\tIn ALL cases this trigger will happen BEFORE the audio audibly loops!!\n\t\t\t\t\t\t*\/\t\t\n\t\t\t\t\t\t\/\/ Notify listener\n\t\t\t\t\t\tif ( mSoundListener ) mSoundListener->soundLooping(this);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmStreamEOF=true;\n\t\t\t\t\t\t\/\/ EOF - finish.\n\t\t\t\t\t\tif (bytes==0) break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ Append to end of buffer\n\t\t\t\taudioData.insert(audioData.end(), data, data + bytes);\n\t\t\t\t\/\/ Keep track of read data\n\t\t\t\tresult+=bytes;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ EOF\n\t\tif(result == 0)\n\t\t{\n\t\t\tOGRE_FREE(data, Ogre::MEMCATEGORY_GENERAL);\n\t\t\treturn false;\n\t\t}\n\n\t\talGetError();\n\t\t\/\/ Copy buffer data\n\t\talBufferData(buffer, mFormat, &audioData[0], static_cast<ALsizei>(audioData.size()), mFormatData.mFormat->mSamplesPerSec);\n\n\t\t\/\/ Cleanup\n\t\tOGRE_FREE(data, Ogre::MEMCATEGORY_GENERAL);\n\n\t\treturn true;\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tvoid OgreOggStreamWavSound::_dequeue()\n\t{\n\t\tif(mSource == AL_NONE)\n\t\t\treturn;\n\n\t\tint queued=0;\n\n\t\talGetError();\n\n\t\t\/** Check current state\n\t\t@remarks\n\t\t\tFix for bug where prebuffering a streamed sound caused a buffer problem\n\t\t\tresulting in only 1st buffer repeatedly looping. This is because alSourceStop() \n\t\t\tdoesn't function correctly if the sources state hasn't previously been set!!???\n\t\t*\/\n\t\tALenum state;\n\t\talGetSourcei(mSource, AL_SOURCE_STATE, &state);\n\n\t\t\/\/ Force mSource to change state so the call to alSourceStop() will mark buffers correctly.\n\t\tif (state == AL_INITIAL)\n\t\t\talSourcePlay(mSource);\n\n\t\t\/\/ Stop source to allow unqueuing\n\t\talSourceStop(mSource);\n\n\t\t\/\/ Get number of buffers queued on source\n\t\talGetSourcei(mSource, AL_BUFFERS_PROCESSED, &queued);\n\n\t\t\/\/ Remove number of buffers from source\n\t\twhile (queued--)\n\t\t{\n\t\t\tALuint buffer;\n\t\t\talSourceUnqueueBuffers(mSource, 1, &buffer);\n\n\t\t\t\/\/ Any problems?\n\t\t\tif ( alGetError() ) \n\t\t\t{\n\t\t\t\tOgre::LogManager::getSingleton().logError(\"OgreOggStreamWavSound::_dequeue() - Unable to unqueue buffers\");\n\t\t\t}\n\t\t}\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tvoid OgreOggStreamWavSound::_pauseImpl()\n\t{\n\t\tassert(mState != SS_DESTROYED);\n\n\t\tif(mSource == AL_NONE) return;\n\n\t\talSourcePause(mSource);\n\t\tmState = SS_PAUSED;\n\t\t\n\t\t\/\/ Notify listener\n\t\tif ( mSoundListener ) mSoundListener->soundPaused(this);\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tvoid OgreOggStreamWavSound::_playImpl()\n\t{\n\t\tassert(mState != SS_DESTROYED);\n\n\t\tif(isPlaying())\treturn;\n\n\t\t\/\/ Grab a source if not already attached\n\t\tif (mSource == AL_NONE)\n\t\t\tif ( !OgreOggSoundManager::getSingleton()._requestSoundSource(this) )\n\t\t\t\treturn;\n\n\t\t\/\/ Play source\n\t\talGetError();\n\t\talSourcePlay(mSource);\n\t\tif ( alGetError() )\n\t\t{\n\t\t\tOgre::LogManager::getSingleton().logError(\"OgreOggStreamWavSound::_playImpl() - Unable to play sound\");\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Set play flag\n\t\tmState = SS_PLAYING;\n\t\t\n\t\t\/\/ Notify listener\n\t\tif ( mSoundListener ) mSoundListener->soundPlayed(this);\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tvoid OgreOggStreamWavSound::setPlayPosition(float seconds)\n\t{\n\t\tif(seconds < 0) return;\n\n\t\t\/\/ Wrap\n\t\tif ( seconds>mPlayTime ) \n\t\t\tdo { seconds-=mPlayTime; } while ( seconds>mPlayTime );\n\n\t\t\/\/ Store play position\n\t\tmPlayPos = seconds;\n\n\t\t\/\/ Set flag\n\t\tmPlayPosChanged = true;\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tfloat OgreOggStreamWavSound::getPlayPosition() const\n\t{ \n\t\tif ( !mSource ) return -1.f;\n\n\t\tfloat time=0.f;\n\t\talGetSourcef(mSource, AL_SEC_OFFSET, &time);\n\n\t\tif ( (mLastOffset+time)>=mPlayTime )\n\t\t\treturn (mLastOffset+time) - mPlayTime;\n\t\telse\n\t\t\treturn mLastOffset+time;\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tvoid OgreOggStreamWavSound::_updatePlayPosition()\n\t{\n\t\tif ( mSource==AL_NONE ) \n\t\t\treturn;\n\n\t\t\/\/ Get state\n\t\tbool playing = isPlaying();\n\t\tbool paused = isPaused();\n\n\t\t\/\/ Stop playback\n\t\tpause();\n\n\t\t\/\/ mBufferSize is 1\/4 of a second\n\t\tsize_t dataOffset = static_cast<size_t>(mPlayPos * mBufferSize * 4);\n\t\tmAudioStream->seek(mAudioOffset + dataOffset);\n\n\t\t\/\/ Unqueue audio\n\t\t_dequeue();\n\n\t\t\/\/ Fill buffers\n\t\t_prebuffer();\n\n\t\t\/\/ Set state\n\t\tif\t\t(playing) play();\n\t\telse if\t(paused) pause();\n\n\t\t\/\/ Set flag\n\t\tmPlayPosChanged = false;\n\t\tmLastOffset = mPlayPos;\n\t\tmStreamEOF=false;\n\t}\n\t\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*\/\n\tvoid OgreOggStreamWavSound::_stopImpl()\n\t{\n\t\tassert(mState != SS_DESTROYED);\n\n\t\tif(mSource != AL_NONE)\n\t\t{\n\t\t\t\/\/ Remove audio data from source\n\t\t\t_dequeue();\n\n\t\t\t\/\/ Stop playback\n\t\t\tmState = SS_STOPPED;\n\n\t\t\t\/\/ Reset stream pointer\n\t\t\tmAudioStream->seek(mAudioOffset);\n\t\t\tmLastOffset=0;\n\t\t\tmStreamEOF=false;\n\n\t\t\t\/\/ Reload audio data\n\t\t\t_prebuffer();\n\n\t\t\tif (mTemporary)\n\t\t\t{\n\t\t\t\tmState = SS_DESTROYED;\n\t\t\t\tOgreOggSoundManager::getSingleton()._destroyTemporarySound(this);\n\t\t\t}\n\t\t\t\/\/ Give up source immediately if specfied\n\t\t\telse if (mGiveUpSource) \n\t\t\t\tOgreOggSoundManager::getSingleton()._releaseSoundSource(this);\n\t\t\n\t\t\t\/\/ Notify listener\n\t\t\tif ( mSoundListener ) mSoundListener->soundStopped(this);\n\t\t}\n\t}\n}\n","avg_line_length":28.5222363405,"max_line_length":196,"alphanum_fraction":0.6355860471,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":294,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause-LBNL"],"max_stars_count":27.0,"content":"\/\/--- Version string for command-line app to export an EnergyPlus simulation as an FMU.\r\n\r\n\r\n\/\/--- Copyright notice.\r\n\/\/\r\n\/\/   Please see the header file.\r\n\r\n\r\n\/\/--- Includes.\r\n\/\/\r\n#include \"app-cmdln-version.h\"\r\n\r\n\r\n\/\/--- Global variables.\r\n\/\/\r\nconst char *const gp_cmdln_versionStr = \"0.1\";\r\n","avg_line_length":17.2941176471,"max_line_length":88,"alphanum_fraction":0.6292517007,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":66097,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":null,"content":"\/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.\r\n *\r\n *  Use of this source code is governed by a BSD-style license that can\r\n *  be found in the License.html file in the root of the source tree.\r\n *\/\r\n\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\/\/\r\n\/\/ Links:\r\n\/\/\r\n\/\/ http:\/\/www.fileformat.info\/format\/jpeg\/\r\n\/\/ http:\/\/park2.wakwak.com\/~tsuruzoh\/Computer\/Digicams\/exif-e.html\r\n\/\/ http:\/\/www.w3.org\/Graphics\/JPEG\/jfif3.pdf\r\n\/\/ http:\/\/www.sentex.net\/~mwandel\/jhead\/\r\n\/\/\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n\/\/---------------------------------------------------------------------------\r\n\/\/ Pre-compilation\r\n#include \"MediaInfo\/PreComp.h\"\r\n#ifdef __BORLANDC__\r\n    #pragma hdrstop\r\n#endif\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"MediaInfo\/Setup.h\"\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#if defined(MEDIAINFO_JPEG_YES)\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"MediaInfo\/Image\/File_Jpeg.h\"\r\n#include \"MediaInfo\/MediaInfo_Config_MediaInfo.h\"\r\n#include \"ZenLib\/Utils.h\"\r\n#include <vector>\r\nusing namespace ZenLib;\r\nusing namespace std;\r\n\/\/---------------------------------------------------------------------------\r\n\r\nnamespace MediaInfoLib\r\n{\r\n\r\n\/\/***************************************************************************\r\n\/\/ Constants\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nnamespace Elements\r\n{\r\n    const int16u TEM =0xFF01;\r\n    const int16u SOC =0xFF4F; \/\/JPEG 2000\r\n    const int16u SIZ =0xFF51; \/\/JPEG 2000\r\n    const int16u COD =0xFF52; \/\/JPEG 2000\r\n    const int16u COC =0xFF53; \/\/JPEG 2000\r\n    const int16u TLM =0xFF55; \/\/JPEG 2000\r\n    const int16u PLM =0xFF57; \/\/JPEG 2000\r\n    const int16u PLT =0xFF58; \/\/JPEG 2000\r\n    const int16u QCD =0xFF5C; \/\/JPEG 2000\r\n    const int16u QCC =0xFF5D; \/\/JPEG 2000\r\n    const int16u RGN =0xFF5E; \/\/JPEG 2000\r\n    const int16u POC =0xFF5F; \/\/JPEG 2000\r\n    const int16u PPM =0xFF60; \/\/JPEG 2000\r\n    const int16u PPT =0xFF61; \/\/JPEG 2000\r\n    const int16u CME =0xFF64; \/\/JPEG 2000\r\n    const int16u SOT =0xFF90; \/\/JPEG 2000\r\n    const int16u SOP =0xFF91; \/\/JPEG 2000\r\n    const int16u EPH =0xFF92; \/\/JPEG 2000\r\n    const int16u SOD =0xFF93; \/\/JPEG 2000\r\n    const int16u S0F0=0xFFC0;\r\n    const int16u S0F1=0xFFC1;\r\n    const int16u S0F2=0xFFC2;\r\n    const int16u S0F3=0xFFC3;\r\n    const int16u DHT =0xFFC4;\r\n    const int16u S0F5=0xFFC5;\r\n    const int16u S0F6=0xFFC6;\r\n    const int16u S0F7=0xFFC7;\r\n    const int16u JPG =0xFFC8;\r\n    const int16u S0F9=0xFFC9;\r\n    const int16u S0FA=0xFFCA;\r\n    const int16u S0FB=0xFFCB;\r\n    const int16u DAC =0xFFCC;\r\n    const int16u S0FD=0xFFCD;\r\n    const int16u S0FE=0xFFCE;\r\n    const int16u S0FF=0xFFCF;\r\n    const int16u RST0=0xFFD0;\r\n    const int16u RST1=0xFFD1;\r\n    const int16u RST2=0xFFD2;\r\n    const int16u RST3=0xFFD3;\r\n    const int16u RST4=0xFFD4;\r\n    const int16u RST5=0xFFD5;\r\n    const int16u RST6=0xFFD6;\r\n    const int16u RST7=0xFFD7;\r\n    const int16u SOI =0xFFD8;\r\n    const int16u EOI =0xFFD9; \/\/EOC in JPEG 2000\r\n    const int16u SOS =0xFFDA;\r\n    const int16u DQT =0xFFDB;\r\n    const int16u DNL =0xFFDC;\r\n    const int16u DRI =0xFFDD;\r\n    const int16u DHP =0xFFDE;\r\n    const int16u EXP =0xFFDF;\r\n    const int16u APP0=0xFFE0;\r\n    const int16u APP1=0xFFE1;\r\n    const int16u APP2=0xFFE2;\r\n    const int16u APP3=0xFFE3;\r\n    const int16u APP4=0xFFE4;\r\n    const int16u APP5=0xFFE5;\r\n    const int16u APP6=0xFFE6;\r\n    const int16u APP7=0xFFE7;\r\n    const int16u APP8=0xFFE8;\r\n    const int16u APP9=0xFFE9;\r\n    const int16u APPA=0xFFEA;\r\n    const int16u APPB=0xFFEB;\r\n    const int16u APPC=0xFFEC;\r\n    const int16u APPD=0xFFED;\r\n    const int16u APPE=0xFFEE;\r\n    const int16u APPF=0xFFEF;\r\n    const int16u JPG0=0xFFF0;\r\n    const int16u JPG1=0xFFF1;\r\n    const int16u JPG2=0xFFF2;\r\n    const int16u JPG3=0xFFF3;\r\n    const int16u JPG4=0xFFF4;\r\n    const int16u JPG5=0xFFF5;\r\n    const int16u JPG6=0xFFF6;\r\n    const int16u JPG7=0xFFF7;\r\n    const int16u JPG8=0xFFF8;\r\n    const int16u JPG9=0xFFF9;\r\n    const int16u JPGA=0xFFFA;\r\n    const int16u JPGB=0xFFFB;\r\n    const int16u JPGC=0xFFFC;\r\n    const int16u JPGD=0xFFFD;\r\n    const int16u COM =0xFFFE;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\n\/\/ Borland C++ does not accept local template\r\nstruct Jpeg_samplingfactor\r\n{\r\n    int8u Ci;\r\n    int8u Hi;\r\n    int8u Vi;\r\n};\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid Jpeg_AddDec(string& Current, int8u Value)\r\n{\r\n    if (Value < 10)\r\n        Current += '0' + Value;\r\n    else\r\n    {\r\n        Current += '1';\r\n        Current += '0' - 10 + Value;\r\n    }\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nstring Jpeg_WithLevel(string Profile, int8u Level, bool HasSubLevel=false)\r\n{\r\n    Profile += '@';\r\n    if (HasSubLevel)\r\n        Profile += 'M'; \/\/ Has Mainlevel\r\n    Profile += 'L';\r\n    Jpeg_AddDec(Profile, Level & 0xF);\r\n    if (HasSubLevel)\r\n    {\r\n        Profile += 'S'; \/\/ Has Sublevel\r\n        Profile += 'L';\r\n        Jpeg_AddDec(Profile, Level >> 4);\r\n    }\r\n    return Profile;\r\n}\r\n\r\nstring Jpeg2000_Rsiz(int16u Rsiz)\r\n{\r\n    switch (Rsiz)\r\n    {\r\n        case 0x0000: return \"No restrictions\";\r\n        case 0x0001: return \"Profile-0\";\r\n        case 0x0002: return \"Profile-1\";\r\n        case 0x0003: return \"D-Cinema 2k\";\r\n        case 0x0004: return \"D-Cinema 4k\";\r\n        case 0x0005: return \"D-Cinema 2k Scalable\";\r\n        case 0x0006: return \"D-Cinema 4k Scalable\";\r\n        case 0x0007: return \"Long-term storage\";\r\n        case 0x0306: return \"BCMR@L6\"; \/\/Broadcast Contribution Multi-tile Reversible\r\n        case 0x0307: return \"BCMR@L7\"; \/\/Broadcast Contribution Multi-tile Reversible\r\n        default:\r\n            switch ((Rsiz & 0xFFF0))\r\n            {\r\n                case 0x0100: return Jpeg_WithLevel(\"BCS\", (int8u)Rsiz); \/\/Broadcast Contribution Single-tile \r\n                case 0x0200: return Jpeg_WithLevel(\"BCM\", (int8u)Rsiz); \/\/Broadcast Contribution Multi-tile\r\n                default:;\r\n            }\r\n            switch ((Rsiz & 0xFF00))\r\n            {\r\n                case 0x0400: return Jpeg_WithLevel(\"IMFS2k\", (int8u)Rsiz, true); \/\/ IMF Single-tile 2k\r\n                case 0x0500: return Jpeg_WithLevel(\"IMFS4k\", (int8u)Rsiz, true); \/\/ IMF Single-tile 4k\r\n                case 0x0600: return Jpeg_WithLevel(\"IMFS8k\", (int8u)Rsiz, true); \/\/ IMF Single-tile 8k\r\n                case 0x0700: return Jpeg_WithLevel(\"IMFMR2k\", (int8u)Rsiz, true); \/\/ IMF Single\/Multi-tile 2k\r\n                case 0x0800: return Jpeg_WithLevel(\"IMFMR4k\", (int8u)Rsiz, true); \/\/ IMF Single\/Multi-tile 4k\r\n                case 0x0900: return Jpeg_WithLevel(\"IMFMR8k\", (int8u)Rsiz, true); \/\/ IMF Single\/Multi-tile 8k\r\n                default:;\r\n            }\r\n            return Ztring::ToZtring(Rsiz, 16).To_UTF8();\r\n    }\r\n}\r\n\r\nstring ICC_Tag(int32u Signature)\r\n{\r\n    switch (Signature)\r\n    {\r\n        case 0x63707274: return \"Copyright\";\r\n        case 0x64657363: return \"Profile description\";\r\n        case 0x77747074: return \"White point\";\r\n        case 0x626B7074: return \"Black point\";\r\n        case 0x72545243: return \"Reproduction curve, red\";\r\n        case 0x67545243: return \"Reproduction curve, green\";\r\n        case 0x62545243: return \"Reproduction curve, blue\";\r\n        case 0x7258595A: return \"Matrix, red\";\r\n        case 0x6758595A: return \"Matrix, green\";\r\n        case 0x6258595A: return \"Matrix, blue\";\r\n        default        : return Ztring().From_CC4(Signature).To_UTF8();\r\n    }\r\n}\r\n\r\nstring ICC_ColorSpace(int32u ColorSpace)\r\n{\r\n    switch (ColorSpace)\r\n    {\r\n        case 0x434D5920: return \"CMY\";\r\n        case 0x434D594B: return \"CMYK\";\r\n        case 0x47524159: return \"Y\";\r\n        case 0x484C5320: return \"HLS\";\r\n        case 0x48535620: return \"HSV\";\r\n        case 0x4C616220: return \"Lab\";\r\n        case 0x4C757620: return \"Luv\";\r\n        case 0x52474220: return \"RGB\";\r\n        case 0x58595A20: return \"XYZ\";\r\n        case 0x59436272: return \"YCbCr\";\r\n        case 0x59787920: return \"xyY\";\r\n        default        : return Ztring().From_CC4(ColorSpace).To_UTF8();\r\n    }\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Constructor\/Destructor\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nFile_Jpeg::File_Jpeg()\r\n{\r\n    \/\/Config\r\n    #if MEDIAINFO_EVENTS\r\n        ParserIDs[0]=MediaInfo_Parser_Jpeg;\r\n        StreamIDs_Width[0]=0;\r\n    #endif \/\/MEDIAINFO_EVENTS\r\n    #if MEDIAINFO_TRACE\r\n        Trace_Layers_Update(8); \/\/Stream\r\n    #endif \/\/MEDIAINFO_TRACE\r\n    MustSynchronize=true;\r\n    IsRawStream=true;\r\n\r\n    \/\/In\r\n    StreamKind=Stream_Image;\r\n    Interlaced=false;\r\n    #if MEDIAINFO_DEMUX\r\n    FrameRate=0;\r\n    #endif \/\/MEDIAINFO_DEMUX\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Streams management\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::Streams_Accept()\r\n{\r\n    if (!IsSub)\r\n    {\r\n        TestContinuousFileNames();\r\n\r\n        Stream_Prepare(Config->File_Names.size()>1?Stream_Video:StreamKind);\r\n        if (File_Size!=(int64u)-1)\r\n            Fill(StreamKind_Last, StreamPos_Last, Fill_Parameter(StreamKind_Last, Generic_StreamSize), File_Size);\r\n        if (StreamKind_Last==Stream_Video)\r\n            Fill(Stream_Video, StreamPos_Last, Video_FrameCount, Config->File_Names.size());\r\n    }\r\n    else\r\n        Stream_Prepare(StreamKind);\r\n\r\n    \/\/Configuration\r\n    Buffer_MaximumSize=64*1024*1024; \/\/Some big frames are possible (e.g YUV 4:2:2 10 bits 1080p)\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::Streams_Finish()\r\n{\r\n    if (StreamKind_Last==Stream_Video && Config->ParseSpeed>=1.0)\r\n        Fill (Stream_Video, 0, Video_StreamSize, Buffer_TotalBytes, 10, true);\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Static stuff\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nbool File_Jpeg::FileHeader_Begin()\r\n{\r\n    \/\/Element_Size\r\n    if (Buffer_Size<3)\r\n        return false; \/\/Must wait for more data\r\n\r\n    if (Buffer[2]!=0xFF\r\n     || (CC2(Buffer)!=Elements::SOI\r\n      && CC2(Buffer)!=Elements::SOC))\r\n    {\r\n        Reject(\"JPEG\");\r\n        return false;\r\n    }\r\n\r\n    \/\/All should be OK...\r\n    return true;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer - Synchro\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nbool File_Jpeg::Synchronize()\r\n{\r\n    \/\/Synchronizing\r\n    while(Buffer_Offset+2<=Buffer_Size && (Buffer[Buffer_Offset  ]!=0xFF\r\n                                        || Buffer[Buffer_Offset+1]==0x00))\r\n        Buffer_Offset++;\r\n\r\n    if (Buffer_Offset+1==Buffer_Size &&  Buffer[Buffer_Offset  ]!=0xFF)\r\n        Buffer_Offset++;\r\n\r\n    if (Buffer_Offset+2>Buffer_Size)\r\n        return false;\r\n\r\n    \/\/Synched is OK\r\n    Synched=true;\r\n    return true;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nbool File_Jpeg::Synched_Test()\r\n{\r\n    if (SOS_SOD_Parsed)\r\n        return true; \/\/\/No sync after SOD\r\n\r\n    \/\/Must have enough buffer for having header\r\n    if (Buffer_Offset+2>Buffer_Size)\r\n        return false;\r\n\r\n    \/\/Quick test of synchro\r\n    if (Buffer[Buffer_Offset]!=0xFF)\r\n    {\r\n        Synched=false;\r\n        return true;\r\n    }\r\n\r\n    \/\/We continue\r\n    return true;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::Synched_Init()\r\n{\r\n    APP0_JFIF_Parsed=false;\r\n    SOS_SOD_Parsed=false;\r\n    APPE_Adobe0_transform=(int8u)-1;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer - Demux\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#if MEDIAINFO_DEMUX\r\nbool File_Jpeg::Demux_UnpacketizeContainer_Test()\r\n{\r\n    if (!IsSub)\r\n    {\r\n        if (!Status[IsAccepted])\r\n        {\r\n            Accept();\r\n            if (Config->Demux_EventWasSent)\r\n                return false;\r\n        }\r\n        if (Config->File_Names.size()>1)\r\n            return Demux_UnpacketizeContainer_Test_OneFramePerFile();\r\n    }\r\n\r\n    if (Interlaced && Buffer_Offset==0)\r\n    {\r\n        bool StartIsFound=false;\r\n        while (Demux_Offset+2<=Buffer_Size)\r\n        {\r\n            int16u code=BigEndian2int16u(Buffer+Demux_Offset);\r\n            Demux_Offset+=2;\r\n            switch (code)\r\n            {\r\n                case Elements::SOD  :   \/\/JPEG-2000 start\r\n                                        StartIsFound=true;\r\n                case Elements::TEM  :\r\n                case Elements::RST0 :\r\n                case Elements::RST1 :\r\n                case Elements::RST2 :\r\n                case Elements::RST3 :\r\n                case Elements::RST4 :\r\n                case Elements::RST5 :\r\n                case Elements::RST6 :\r\n                case Elements::RST7 :\r\n                case Elements::SOC  :\r\n                case Elements::SOI  :\r\n                case Elements::EOI  :\r\n                             break;\r\n                default   :\r\n                            if (Demux_Offset+2>Buffer_Size)\r\n                                break;\r\n                            {\r\n                            int16u size=BigEndian2int16u(Buffer+Demux_Offset);\r\n                            if (Demux_Offset+2+size>Buffer_Size)\r\n                                break;\r\n                            Demux_Offset+=size;\r\n                            if (code==Elements::SOS) \/\/JPEG start\r\n                                StartIsFound=true;\r\n                            }\r\n            }\r\n            if (StartIsFound)\r\n                break;\r\n        }\r\n\r\n        while (Demux_Offset+2<=Buffer_Size)\r\n        {\r\n            while (Demux_Offset<Buffer_Size && Buffer[Demux_Offset]!=0xFF)\r\n                Demux_Offset++;\r\n            if (Demux_Offset+2<=Buffer_Size && Buffer[Demux_Offset+1]==0xD9) \/\/EOI (JPEG 2000)\r\n                break;\r\n            Demux_Offset++;\r\n        }\r\n        if (Demux_Offset+2<=Buffer_Size)\r\n            Demux_Offset+=2;\r\n    }\r\n    else\r\n        Demux_Offset=Buffer_Size;\r\n\r\n    if (Interlaced)\r\n    {\r\n        if (Field_Count==0 && FrameRate && Demux_Offset!=Buffer_Size)\r\n            FrameRate*=2; \/\/Now field rate\r\n        if (FrameRate)\r\n            FrameInfo.DUR=float64_int64s(1000000000\/FrameRate); \/\/Actually, field or frame rate\r\n    }\r\n\r\n    Demux_UnpacketizeContainer_Demux();\r\n\r\n    if (Interlaced)\r\n    {\r\n        if (FrameInfo.DTS!=(int64u)-1 && FrameInfo.DUR!=(int64u)-1)\r\n            FrameInfo.DTS+=FrameInfo.DUR;\r\n    }\r\n\r\n    return true;\r\n}\r\n#endif \/\/MEDIAINFO_DEMUX\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer - Global\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::Read_Buffer_Unsynched()\r\n{\r\n    SOS_SOD_Parsed=false;\r\n\r\n    Read_Buffer_Unsynched_OneFramePerFile();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::Read_Buffer_Continue()\r\n{\r\n    if (Config->ParseSpeed>=1.0 && IsSub && Status[IsFilled])\r\n    {\r\n        #if MEDIAINFO_DEMUX\r\n            if (Buffer_TotalBytes<Demux_TotalBytes)\r\n            {\r\n                Skip_XX(Demux_TotalBytes-Buffer_TotalBytes,     \"Data\"); \/\/We currently don't want to parse data during demux\r\n                Param_Info1(Frame_Count);\r\n                if (Interlaced)\r\n                {\r\n                    Field_Count++;\r\n                    Field_Count_InThisBlock++;\r\n                }\r\n                if (!Interlaced || Field_Count%2==0)\r\n                {\r\n                    Frame_Count++;\r\n                    if (Frame_Count_NotParsedIncluded!=(int64u)-1)\r\n                        Frame_Count_NotParsedIncluded++;\r\n                }\r\n                return;\r\n            }\r\n        #endif \/\/MEDIAINFO_DEMUX\r\n\r\n        #if MEDIAINFO_DEMUX\r\n        if (!Demux_UnpacketizeContainer)\r\n        #endif \/\/MEDIAINFO_DEMUX\r\n        {\r\n            Skip_XX(Buffer_Size,                                    \"Data\"); \/\/We currently don't want to parse data during demux\r\n            Param_Info1(Frame_Count);\r\n            if (Interlaced)\r\n                Field_Count+=2;\r\n            Frame_Count++;\r\n            if (Frame_Count_NotParsedIncluded!=(int64u)-1)\r\n                Frame_Count_NotParsedIncluded++;\r\n        }\r\n    }\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer - Per element\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::Header_Parse()\r\n{\r\n    if (SOS_SOD_Parsed)\r\n    {\r\n        Header_Fill_Code(0, \"Data\");\r\n        if (!Header_Parser_Fill_Size())\r\n        {\r\n            Element_WaitForMoreData();\r\n            return;\r\n        }\r\n        return;\r\n    }\r\n\r\n    \/\/Parsing\r\n    int16u code, size;\r\n    Get_B2 (code,                                               \"Marker\");\r\n    switch (code)\r\n    {\r\n        case Elements::TEM :\r\n        case Elements::RST0 :\r\n        case Elements::RST1 :\r\n        case Elements::RST2 :\r\n        case Elements::RST3 :\r\n        case Elements::RST4 :\r\n        case Elements::RST5 :\r\n        case Elements::RST6 :\r\n        case Elements::RST7 :\r\n        case Elements::SOC  :\r\n        case Elements::SOD  :\r\n        case Elements::SOI  :\r\n        case Elements::EOI  :\r\n                    size=0; break;\r\n        default   : Get_B2 (size,                               \"Fl - Frame header length\");\r\n    }\r\n\r\n    \/\/Filling\r\n    Header_Fill_Code(code, Ztring().From_CC2(code));\r\n    Header_Fill_Size(2+size);\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nbool File_Jpeg::Header_Parser_Fill_Size()\r\n{\r\n    \/\/Look for next Sync word\r\n    if (Buffer_Offset_Temp==0) \/\/Buffer_Offset_Temp is not 0 if Header_Parse_Fill_Size() has already parsed first frames\r\n        Buffer_Offset_Temp=Buffer_Offset;\r\n\r\n    #if MEDIAINFO_DEMUX\r\n        if (Buffer_TotalBytes+2<Demux_TotalBytes)\r\n            Buffer_Offset_Temp=(size_t)(Demux_TotalBytes-(Buffer_TotalBytes+2));\r\n    #endif \/\/MEDIAINFO_DEMUX\r\n\r\n    while (Buffer_Offset_Temp+2<=Buffer_Size)\r\n    {\r\n        while (Buffer_Offset_Temp<Buffer_Size && Buffer[Buffer_Offset_Temp]!=0xFF)\r\n            Buffer_Offset_Temp++;\r\n        if (Buffer_Offset_Temp+2<=Buffer_Size && Buffer[Buffer_Offset_Temp+1]==0xD9) \/\/EOI\r\n            break;\r\n        Buffer_Offset_Temp++;\r\n    }\r\n\r\n    \/\/Must wait more data?\r\n    if (Buffer_Offset_Temp+2>Buffer_Size)\r\n    {\r\n        if (\/*FrameIsAlwaysComplete ||*\/ File_Offset+Buffer_Size>=File_Size)\r\n            Buffer_Offset_Temp=Buffer_Size; \/\/We are sure that the next bytes are a start\r\n        else\r\n            return false;\r\n    }\r\n\r\n    \/\/OK, we continue\r\n    Header_Fill_Size(Buffer_Offset_Temp-Buffer_Offset);\r\n    Buffer_Offset_Temp=0;\r\n    return true;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::Data_Parse()\r\n{\r\n    #define CASE_INFO(_NAME, _DETAIL) \\\r\n        case Elements::_NAME : Element_Info1(#_NAME); Element_Info1(_DETAIL); _NAME(); break;\r\n\r\n    \/\/Parsing\r\n    if (SOS_SOD_Parsed)\r\n    {\r\n        Skip_XX(Element_Size,                                   \"Data\");\r\n        SOS_SOD_Parsed=false;\r\n        return;\r\n    }\r\n    switch (Element_Code)\r\n    {\r\n        CASE_INFO(TEM ,                                         \"TEM\");\r\n        CASE_INFO(SOC ,                                         \"Start of codestream\"); \/\/JPEG 2000\r\n        CASE_INFO(SIZ ,                                         \"Image and tile size\"); \/\/JPEG 2000\r\n        CASE_INFO(COD ,                                         \"Coding style default\"); \/\/JPEG 2000\r\n        CASE_INFO(COC ,                                         \"Coding style component\"); \/\/JPEG 2000\r\n        CASE_INFO(TLM ,                                         \"Tile-part lengths, main header\"); \/\/JPEG 2000\r\n        CASE_INFO(PLM ,                                         \"Packet length, main header\"); \/\/JPEG 2000\r\n        CASE_INFO(PLT ,                                         \"Packet length, tile-part header\"); \/\/JPEG 2000\r\n        CASE_INFO(QCD ,                                         \"Quantization default\"); \/\/JPEG 2000\r\n        CASE_INFO(QCC ,                                         \"Quantization component \"); \/\/JPEG 2000\r\n        CASE_INFO(RGN ,                                         \"Region-of-interest\"); \/\/JPEG 2000\r\n        CASE_INFO(POC ,                                         \"Progression order change\"); \/\/JPEG 2000\r\n        CASE_INFO(PPM ,                                         \"Packed packet headers, main header\"); \/\/JPEG 2000\r\n        CASE_INFO(PPT ,                                         \"Packed packet headers, tile-part header\"); \/\/JPEG 2000\r\n        CASE_INFO(CME ,                                         \"Comment and extension\"); \/\/JPEG 2000\r\n        CASE_INFO(SOT ,                                         \"Start of tile-part\"); \/\/JPEG 2000\r\n        CASE_INFO(SOP ,                                         \"Start of packet\"); \/\/JPEG 2000\r\n        CASE_INFO(EPH ,                                         \"End of packet header\"); \/\/JPEG 2000\r\n        CASE_INFO(SOD ,                                         \"Start of data\"); \/\/JPEG 2000\r\n        CASE_INFO(S0F0,                                         \"Baseline DCT (Huffman)\");\r\n        CASE_INFO(S0F1,                                         \"Extended sequential DCT (Huffman)\");\r\n        CASE_INFO(S0F2,                                         \"Progressive DCT (Huffman)\");\r\n        CASE_INFO(S0F3,                                         \"Lossless (sequential) (Huffman)\");\r\n        CASE_INFO(DHT ,                                         \"Define Huffman Tables\");\r\n        CASE_INFO(S0F5,                                         \"Differential sequential DCT (Huffman)\");\r\n        CASE_INFO(S0F6,                                         \"Differential progressive DCT (Huffman)\");\r\n        CASE_INFO(S0F7,                                         \"Differential lossless (sequential) (Huffman)\");\r\n        CASE_INFO(JPG ,                                         \"Reserved for JPEG extensions\");\r\n        CASE_INFO(S0F9,                                         \"Extended sequential DCT (Arithmetic)\");\r\n        CASE_INFO(S0FA,                                         \"Progressive DCT (Arithmetic)\");\r\n        CASE_INFO(S0FB,                                         \"Lossless (sequential) (Arithmetic)\");\r\n        CASE_INFO(DAC ,                                         \"Define Arithmetic Coding\");\r\n        CASE_INFO(S0FD,                                         \"Differential sequential DCT (Arithmetic)\");\r\n        CASE_INFO(S0FE,                                         \"Differential progressive DCT (Arithmetic)\");\r\n        CASE_INFO(S0FF,                                         \"Differential lossless (sequential) (Arithmetic)\");\r\n        CASE_INFO(RST0,                                         \"Restart Interval Termination 0\");\r\n        CASE_INFO(RST1,                                         \"Restart Interval Termination 1\");\r\n        CASE_INFO(RST2,                                         \"Restart Interval Termination 2\");\r\n        CASE_INFO(RST3,                                         \"Restart Interval Termination 3\");\r\n        CASE_INFO(RST4,                                         \"Restart Interval Termination 4\");\r\n        CASE_INFO(RST5,                                         \"Restart Interval Termination 5\");\r\n        CASE_INFO(RST6,                                         \"Restart Interval Termination 6\");\r\n        CASE_INFO(RST7,                                         \"Restart Interval Termination 7\");\r\n        CASE_INFO(SOI ,                                         \"Start Of Image\");\r\n        CASE_INFO(EOI ,                                         \"End Of Image\"); \/\/Is EOC (End of codestream) in JPEG 2000\r\n        CASE_INFO(SOS ,                                         \"Start Of Scan\");\r\n        CASE_INFO(DQT ,                                         \"Define Quantization Tables\");\r\n        CASE_INFO(DNL ,                                         \"Define Number of Lines\");\r\n        CASE_INFO(DRI ,                                         \"Define Restart Interval\");\r\n        CASE_INFO(DHP ,                                         \"Define Hierarchical Progression\");\r\n        CASE_INFO(EXP ,                                         \"Expand Reference Components\");\r\n        CASE_INFO(APP0,                                         \"Application-specific marker 0\");\r\n        CASE_INFO(APP1,                                         \"Application-specific marker 1\");\r\n        CASE_INFO(APP2,                                         \"Application-specific marker 2\");\r\n        CASE_INFO(APP3,                                         \"Application-specific marker 3\");\r\n        CASE_INFO(APP4,                                         \"Application-specific marker 4\");\r\n        CASE_INFO(APP5,                                         \"Application-specific marker 5\");\r\n        CASE_INFO(APP6,                                         \"Application-specific marker 6\");\r\n        CASE_INFO(APP7,                                         \"Application-specific marker 7\");\r\n        CASE_INFO(APP8,                                         \"Application-specific marker 8\");\r\n        CASE_INFO(APP9,                                         \"Application-specific marker 9\");\r\n        CASE_INFO(APPA,                                         \"Application-specific marker 10\");\r\n        CASE_INFO(APPB,                                         \"Application-specific marker 11\");\r\n        CASE_INFO(APPC,                                         \"Application-specific marker 12\");\r\n        CASE_INFO(APPD,                                         \"Application-specific marker 13\");\r\n        CASE_INFO(APPE,                                         \"Application-specific marker 14\");\r\n        CASE_INFO(APPF,                                         \"Application-specific marker 15\");\r\n        CASE_INFO(JPG0,                                         \"JPG\");\r\n        CASE_INFO(JPG1,                                         \"JPG\");\r\n        CASE_INFO(JPG2,                                         \"JPG\");\r\n        CASE_INFO(JPG3,                                         \"JPG\");\r\n        CASE_INFO(JPG4,                                         \"JPG\");\r\n        CASE_INFO(JPG5,                                         \"JPG\");\r\n        CASE_INFO(JPG6,                                         \"JPG\");\r\n        CASE_INFO(JPG7,                                         \"JPG\");\r\n        CASE_INFO(JPG8,                                         \"JPG\");\r\n        CASE_INFO(JPG9,                                         \"JPG\");\r\n        CASE_INFO(JPGA,                                         \"JPG\");\r\n        CASE_INFO(JPGB,                                         \"JPG\");\r\n        CASE_INFO(JPGC,                                         \"JPG\");\r\n        CASE_INFO(JPGD,                                         \"JPG\");\r\n        CASE_INFO(COM ,                                         \"Comment\");\r\n        default : Element_Info1(\"Reserved\");\r\n                  Skip_XX(Element_Size,                         \"Data\");\r\n    }\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Elements\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::SIZ()\r\n{\r\n    \/\/Parsing\r\n    vector<float> SamplingFactors;\r\n    vector<int8u> BitDepths;\r\n    int8u SamplingFactors_Max=0;\r\n    int32u Xsiz, Ysiz;\r\n    int16u Rsiz, Count;\r\n    Get_B2 (Rsiz,                                               \"Rsiz - Capability of the codestream\");\r\n    Get_B4 (Xsiz,                                               \"Xsiz - Image size X\");\r\n    Get_B4 (Ysiz,                                               \"Ysiz - Image size Y\");\r\n    Skip_B4(                                                    \"XOsiz - Image offset X\");\r\n    Skip_B4(                                                    \"YOsiz - Image offset Y\");\r\n    Skip_B4(                                                    \"tileW - Size of tile W\");\r\n    Skip_B4(                                                    \"tileH - Size of tile H\");\r\n    Skip_B4(                                                    \"XTOsiz - Upper-left tile offset X\");\r\n    Skip_B4(                                                    \"YTOsiz - Upper-left tile offset Y\");\r\n    Get_B2 (Count,                                              \"Components and initialize related arrays\");\r\n    for (int16u Pos=0; Pos<Count; Pos++)\r\n    {\r\n        Element_Begin1(\"Initialize related array\");\r\n        int8u BitDepth, compSubsX, compSubsY;\r\n        BS_Begin();\r\n        Skip_SB(                                                \"Signed\");\r\n        Get_S1 (7, BitDepth,                                    \"BitDepth\"); Param_Info1(1+BitDepth); Element_Info1(1+BitDepth);\r\n        BS_End();\r\n        Get_B1 (   compSubsX,                                   \"compSubsX\"); Element_Info1(compSubsX);\r\n        Get_B1 (   compSubsY,                                   \"compSubsY\"); Element_Info1(compSubsY);\r\n        Element_End0();\r\n\r\n        \/\/Filling list of HiVi\r\n        if (compSubsX)\r\n        {\r\n            SamplingFactors.push_back(((float)compSubsY)\/compSubsX);\r\n            if (((float)compSubsY)\/compSubsX>SamplingFactors_Max)\r\n                SamplingFactors_Max=(int8u)((float)compSubsY)\/compSubsX;\r\n        }\r\n\r\n        if (BitDepths.empty() || BitDepth!=BitDepths[0])\r\n            BitDepths.push_back(BitDepth);\r\n    }\r\n\r\n    FILLING_BEGIN_PRECISE();\r\n        if (Frame_Count==0 && Field_Count==0)\r\n        {\r\n            Accept(\"JPEG 2000\");\r\n            Fill(\"JPEG 2000\");\r\n\r\n            if (Count_Get(StreamKind_Last)==0)\r\n                Stream_Prepare(StreamKind_Last);\r\n            Fill(StreamKind_Last, 0, Fill_Parameter(StreamKind_Last, Generic_Format), \"JPEG 2000\");\r\n            Fill(StreamKind_Last, 0, Fill_Parameter(StreamKind_Last, Generic_Codec), \"JPEG 2000\");\r\n            Fill(StreamKind_Last, 0, \"Format_Profile\", Jpeg2000_Rsiz(Rsiz));\r\n            if (StreamKind_Last==Stream_Image)\r\n                Fill(Stream_Image, 0, Image_Codec_String, \"JPEG 2000\", Unlimited, true, true); \/\/To Avoid automatic filling\r\n            Fill(StreamKind_Last, 0, StreamKind_Last==Stream_Image?(size_t)Image_Width:(size_t)Video_Width, Xsiz);\r\n            Fill(StreamKind_Last, 0, StreamKind_Last==Stream_Image?(size_t)Image_Height:(size_t)Video_Height, Ysiz*(Interlaced?2:1)); \/\/If image is from interlaced content, must multiply height by 2\r\n\r\n            if (BitDepths.size()==1)\r\n                Fill(StreamKind_Last, 0, Fill_Parameter(StreamKind_Last, Generic_BitDepth), 1+BitDepths[0]);\r\n\r\n            \/\/Chroma subsampling\r\n            if (SamplingFactors_Max)\r\n                while (SamplingFactors_Max<4)\r\n                {\r\n                    for (size_t Pos=0; Pos<SamplingFactors.size(); Pos++)\r\n                        SamplingFactors[Pos]*=2;\r\n                    SamplingFactors_Max*=2;\r\n                }\r\n            while (SamplingFactors.size()<3)\r\n                SamplingFactors.push_back(0);\r\n            Ztring ChromaSubsampling;\r\n            for (size_t Pos=0; Pos<SamplingFactors.size(); Pos++)\r\n                ChromaSubsampling+=Ztring::ToZtring(SamplingFactors[Pos], 0)+__T(':');\r\n            if (!ChromaSubsampling.empty())\r\n            {\r\n                ChromaSubsampling.resize(ChromaSubsampling.size()-1);\r\n                Fill(StreamKind_Last, 0, \"ChromaSubsampling\", ChromaSubsampling);\r\n\r\n                \/\/Not for sure\r\n                if (ChromaSubsampling==__T(\"4:4:4\") && (Retrieve(StreamKind_Last, 0, \"Format_Profile\")==__T(\"D-Cinema 2k\") || Retrieve(StreamKind_Last, 0, \"Format_Profile\")==__T(\"D-Cinema 4k\")))\r\n                    Fill(StreamKind_Last, 0, \"ColorSpace\", \"XYZ\");\r\n                else if (!IsSub)\r\n                {\r\n                    if (ChromaSubsampling==__T(\"4:2:0\") || ChromaSubsampling==__T(\"4:2:2\"))\r\n                        Fill(StreamKind_Last, 0, \"ColorSpace\", \"YUV\");\r\n                    else if (ChromaSubsampling==__T(\"4:4:4\"))\r\n                        Fill(StreamKind_Last, 0, \"ColorSpace\", \"RGB\");\r\n                }\r\n            }\r\n        }\r\n    FILLING_END();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::COD()\r\n{\r\n    \/\/Parsing\r\n    int8u Style, Style2, Levels, MultipleComponentTransform;\r\n    bool PrecinctUsed;\r\n    Get_B1 (Style,                                              \"Scod - Style\");\r\n        Get_Flags (Style, 0, PrecinctUsed,                      \"Precinct used\");\r\n        Skip_Flags(Style, 1,                                    \"Use SOP (start of packet)\");\r\n        Skip_Flags(Style, 2,                                    \"Use EPH (end of packet header)\");\r\n    Get_B1 (Levels,                                             \"Number of decomposition levels\");\r\n    Skip_B1(                                                    \"Progression order\");\r\n    Skip_B2(                                                    \"Number of layers\");\r\n    Info_B1(DimX,                                               \"Code-blocks dimensions X (2^(n+2))\"); Param_Info2(1<<(DimX+2), \" pixels\");\r\n    Info_B1(DimY,                                               \"Code-blocks dimensions Y (2^(n+2))\"); Param_Info2(1<<(DimY+2), \" pixels\");\r\n    Get_B1 (Style2,                                             \"Style of the code-block coding passes\");\r\n        Skip_Flags(Style2, 0,                                   \"Selective arithmetic coding bypass\");\r\n        Skip_Flags(Style2, 1,                                   \"MQ states for all contexts\");\r\n        Skip_Flags(Style2, 2,                                   \"Regular termination\");\r\n        Skip_Flags(Style2, 3,                                   \"Vertically stripe-causal context formation\");\r\n        Skip_Flags(Style2, 4,                                   \"Error resilience info is embedded on MQ termination\");\r\n        Skip_Flags(Style2, 5,                                   \"Segmentation marker is to be inserted at the end of each normalization coding pass\");\r\n    Skip_B1(                                                    \"Transform\");\r\n    Get_B1(MultipleComponentTransform,                          \"Multiple component transform\");\r\n    if (PrecinctUsed)\r\n    {\r\n        BS_Begin();\r\n        Skip_S1(4,                                              \"LL sub-band width\");\r\n        Skip_S1(4,                                              \"LL sub-band height\");\r\n        BS_End();\r\n        for (int16u Pos=0; Pos<Levels; Pos++)\r\n        {\r\n            Element_Begin1(\"Decomposition level\");\r\n            BS_Begin();\r\n            Skip_S1(4,                                          \"decomposition level width\");\r\n            Skip_S1(4,                                          \"decomposition level height\");\r\n            BS_End();\r\n            Element_End0();\r\n        }\r\n    }\r\n\r\n    FILLING_BEGIN();\r\n        if (Frame_Count==0 && Field_Count==0)\r\n        {\r\n            switch (MultipleComponentTransform)\r\n            {\r\n                case 0x01 : Fill(StreamKind_Last, 0, \"Compression_Mode\", \"Lossless\"); break;\r\n                case 0x02 : Fill(StreamKind_Last, 0, \"Compression_Mode\", \"Lossy\"); break;\r\n                default   : ;\r\n            }\r\n        }\r\n    FILLING_END();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::QCD()\r\n{\r\n    \/\/Parsing\r\n    Skip_B1(                                                    \"Sqcd - Style\");\r\n    Skip_XX(Element_Size-Element_Offset,                        \"QCD data\");\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::SOD()\r\n{\r\n    SOS_SOD_Parsed=true;\r\n    if (Interlaced)\r\n    {\r\n        Field_Count++;\r\n        Field_Count_InThisBlock++;\r\n    }\r\n    if (!Interlaced || Field_Count%2==0)\r\n    {\r\n        Frame_Count++;\r\n        Frame_Count_InThisBlock++;\r\n        if (Frame_Count_NotParsedIncluded!=(int64u)-1)\r\n            Frame_Count_NotParsedIncluded++;\r\n        if (Status[IsFilled])\r\n            Fill();\r\n        if (Config->ParseSpeed<1.0)\r\n            Finish(\"JPEG 2000\"); \/\/No need of more\r\n    }\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::SOF_()\r\n{\r\n    \/\/Parsing\r\n    vector<Jpeg_samplingfactor> SamplingFactors;\r\n    int16u Height, Width;\r\n    int8u  Resolution, Count;\r\n    Get_B1 (Resolution,                                         \"P - Sample precision\");\r\n    Get_B2 (Height,                                             \"Y - Number of lines\");\r\n    Get_B2 (Width,                                              \"X - Number of samples per line\");\r\n    Get_B1 (Count,                                              \"Nf - Number of image components in frame\");\r\n    for (int8u Pos=0; Pos<Count; Pos++)\r\n    {\r\n        Jpeg_samplingfactor SamplingFactor;\r\n        Element_Begin1(\"Component\");\r\n        Get_B1 (   SamplingFactor.Ci,                           \"Ci - Component identifier\"); if (SamplingFactor.Ci>Count) Element_Info1(Ztring().append(1, (Char)SamplingFactor.Ci)); else Element_Info1(SamplingFactor.Ci);\r\n        BS_Begin();\r\n        Get_S1 (4, SamplingFactor.Hi,                           \"Hi - Horizontal sampling factor\"); Element_Info1(SamplingFactor.Hi);\r\n        Get_S1 (4, SamplingFactor.Vi,                           \"Vi - Vertical sampling factor\"); Element_Info1(SamplingFactor.Vi);\r\n        BS_End();\r\n        Skip_B1(                                                \"Tqi - Quantization table destination selector\");\r\n        Element_End0();\r\n\r\n        \/\/Filling list of HiVi\r\n        SamplingFactors.push_back(SamplingFactor);\r\n    }\r\n\r\n    FILLING_BEGIN_PRECISE();\r\n        if (Frame_Count==0 && Field_Count==0)\r\n        {\r\n            Accept(\"JPEG\");\r\n            Fill(\"JPEG\");\r\n\r\n            if (Count_Get(StreamKind_Last)==0)\r\n                Stream_Prepare(StreamKind_Last);\r\n            Fill(StreamKind_Last, 0, Fill_Parameter(StreamKind_Last, Generic_Format), \"JPEG\");\r\n            Fill(StreamKind_Last, 0, Fill_Parameter(StreamKind_Last, Generic_Codec), \"JPEG\");\r\n            if (StreamKind_Last==Stream_Image)\r\n                Fill(Stream_Image, 0, Image_Codec_String, \"JPEG\", Unlimited, true, true); \/\/To Avoid automatic filling\r\n            if (StreamKind_Last==Stream_Video)\r\n                Fill(Stream_Video, 0, Video_InternetMediaType, \"video\/JPEG\", Unlimited, true, true);\r\n            Fill(StreamKind_Last, 0, Fill_Parameter(StreamKind_Last, Generic_BitDepth), Resolution);\r\n            Fill(StreamKind_Last, 0, \"Height\", Height*(Interlaced?2:1));\r\n            Fill(StreamKind_Last, 0, \"Width\", Width);\r\n\r\n            \/\/ColorSpace from http:\/\/docs.oracle.com\/javase\/1.4.2\/docs\/api\/javax\/imageio\/metadata\/doc-files\/jpeg_metadata.html\r\n            \/\/TODO: if APPE_Adobe0_transform is present, indicate that K is inverted, see http:\/\/halicery.com\/Image\/jpeg\/JPEGCMYK.html\r\n            switch (APPE_Adobe0_transform)\r\n            {\r\n                case 0x01 :\r\n                            if (Count==3)\r\n                                Fill(StreamKind_Last, 0, \"ColorSpace\", \"YUV\");\r\n                            break;\r\n                case 0x02 :\r\n                            if (Count==4)\r\n                                Fill(StreamKind_Last, 0, \"ColorSpace\", \"YUVK\");\r\n                            break;\r\n                default   :\r\n                            {\r\n                            int8u Ci[256];\r\n                            memset(Ci, 0, 256);\r\n                            for (int8u Pos=0; Pos<Count; Pos++)\r\n                                Ci[SamplingFactors[Pos].Ci]++;\r\n\r\n                            switch (Count)\r\n                            {\r\n                                case 1 :    Fill(StreamKind_Last, 0, \"ColorSpace\", \"Y\"); break;\r\n                                case 2 :    Fill(StreamKind_Last, 0, \"ColorSpace\", \"YA\"); break;\r\n                                case 3 :\r\n                                                 if (!APP0_JFIF_Parsed && Ci['R']==1 && Ci['G']==1 && Ci['B']==1)                                                       \/\/RGB\r\n                                                Fill(StreamKind_Last, 0, \"ColorSpace\", \"RGB\");\r\n                                            else if ((Ci['Y']==1 && ((Ci['C']==1 && Ci['c']==1)                                                                         \/\/YCc\r\n                                                                  || Ci['C']==2))                                                                                       \/\/YCC\r\n                                                  || APP0_JFIF_Parsed                                                                                                   \/\/APP0 JFIF header present so YCC\r\n                                                  || APPE_Adobe0_transform==0                                                                                           \/\/transform set to YCC\r\n                                                  || (SamplingFactors[0].Ci==0 && SamplingFactors[1].Ci==1 && SamplingFactors[2].Ci==2)                                 \/\/012\r\n                                                  || (SamplingFactors[0].Ci==1 && SamplingFactors[1].Ci==2 && SamplingFactors[2].Ci==3))                                \/\/123\r\n                                                Fill(StreamKind_Last, 0, \"ColorSpace\", \"YUV\");\r\n                                            else if (APPE_Adobe0_transform==0 || APPE_Adobe0_transform==(int8u)-1)                                                      \/\/transform set to RGB (it is a guess)\r\n                                                Fill(StreamKind_Last, 0, \"ColorSpace\", \"RGB\");\r\n                                            break;\r\n                                case 4 :\r\n                                                 if (!APP0_JFIF_Parsed && Ci['R']==1 && Ci['G']==1 && Ci['B']==1 && Ci['A']==1)                                         \/\/RGBA\r\n                                                Fill(StreamKind_Last, 0, \"ColorSpace\", \"RGBA\");\r\n                                            else if ((Ci['Y']==1 && Ci['A']==1 && ((Ci['C']==1 && Ci['c']==1)                                                           \/\/YCcA\r\n                                                                                || Ci['C']==2))                                                                         \/\/YCCA\r\n                                                  || APP0_JFIF_Parsed                                                                                                   \/\/APP0 JFIF header present so YCCA\r\n                                                  || (SamplingFactors[0].Ci==0 && SamplingFactors[1].Ci==1 && SamplingFactors[2].Ci==2 && SamplingFactors[3].Ci==3)     \/\/0123\r\n                                                  || (SamplingFactors[0].Ci==1 && SamplingFactors[1].Ci==2 && SamplingFactors[2].Ci==3 && SamplingFactors[3].Ci==4))    \/\/1234\r\n                                                Fill(StreamKind_Last, 0, \"ColorSpace\", \"YUVA\");\r\n                                            else if (Ci['C']==1 && Ci['M']==1 && Ci['Y']==1 && Ci['K']==1)                                                              \/\/CMYK\r\n                                                Fill(StreamKind_Last, 0, \"ColorSpace\", \"CMYK\");\r\n                                            else if (APPE_Adobe0_transform==0 || APPE_Adobe0_transform==(int8u)-1)                                                      \/\/transform set to CMYK (it is a guess)\r\n                                                Fill(StreamKind_Last, 0, \"ColorSpace\", \"CMYK\");\r\n                                            break;\r\n                                default:    ;\r\n                            }\r\n                            }\r\n            }\r\n\r\n            \/\/Chroma subsampling\r\n            if ((SamplingFactors.size()==3 || SamplingFactors.size()==4) && SamplingFactors[1].Hi==1 && SamplingFactors[2].Hi==1 && SamplingFactors[1].Vi==1 && SamplingFactors[2].Vi==1)\r\n            {\r\n                string ChromaSubsampling;\r\n                switch (SamplingFactors[0].Hi)\r\n                {\r\n                    case 1 :\r\n                            switch (SamplingFactors[0].Vi)\r\n                            {\r\n                                case 1 : if (Retrieve(StreamKind_Last, 0, \"ColorSpace\").find(__T(\"YUV\"))==0) ChromaSubsampling=\"4:4:4\"; break;\r\n                                default: ;\r\n                            }\r\n                            break;\r\n                    case 2 :\r\n                            switch (SamplingFactors[0].Vi)\r\n                            {\r\n                                case 1 : ChromaSubsampling=\"4:2:2\"; break;\r\n                                case 2 : ChromaSubsampling=\"4:2:0\"; break;\r\n                                default: ;\r\n                            }\r\n                            break;\r\n                    case 4 :\r\n                            switch (SamplingFactors[0].Vi)\r\n                            {\r\n                                case 1 : ChromaSubsampling=\"4:1:1\"; break;\r\n                                case 2 : ChromaSubsampling=\"4:1:0\"; break;\r\n                                default: ;\r\n                            }\r\n                            break;\r\n                    default: ;\r\n                }\r\n                if (!ChromaSubsampling.empty())\r\n                {\r\n                    if (SamplingFactors.size()>3 && (SamplingFactors[3].Hi!=SamplingFactors[0].Hi || SamplingFactors[3].Vi!=SamplingFactors[0].Vi))\r\n                        ChromaSubsampling+=\":?\";\r\n                    Fill(StreamKind_Last, 0, \"ChromaSubsampling\", ChromaSubsampling);\r\n                }\r\n            }\r\n        }\r\n    FILLING_END();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::SOS()\r\n{\r\n    \/\/Parsing\r\n    int8u Count;\r\n    Get_B1 (Count,                                              \"Number of image components in scan\");\r\n    for (int8u Pos=0; Pos<Count; Pos++)\r\n    {\r\n        Skip_B1(                                                \"Scan component selector\");\r\n        Skip_B1(                                                \"Entropy coding table destination selector\");\r\n    }\r\n    Skip_B1(                                                    \"Start of spectral or predictor selection\");\r\n    Skip_B1(                                                    \"End of spectral selection\");\r\n    Skip_B1(                                                    \"Successive approximation bit position\");\r\n\r\n    FILLING_BEGIN_PRECISE();\r\n    SOS_SOD_Parsed=true;\r\n    if (Interlaced)\r\n    {\r\n        Field_Count++;\r\n        Field_Count_InThisBlock++;\r\n    }\r\n    if (!Interlaced || Field_Count%2==0)\r\n    {\r\n        Frame_Count++;\r\n        Frame_Count_InThisBlock++;\r\n        if (Frame_Count_NotParsedIncluded!=(int64u)-1)\r\n            Frame_Count_NotParsedIncluded++;\r\n    }\r\n    if (Status[IsFilled])\r\n        Fill();\r\n    if (Config->ParseSpeed<1.0)\r\n        Finish(\"JPEG\"); \/\/No need of more\r\n    FILLING_END();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::APP0()\r\n{\r\n    \/\/Parsing\r\n    int32u Name;\r\n    Get_C4(Name,                                                \"Name\");\r\n    switch (Name)\r\n    {\r\n        case 0x41564931 : APP0_AVI1(); break; \/\/\"AVI1\"\r\n        case 0x4A464946 : APP0_JFIF(); break; \/\/\"JFIF\"\r\n        case 0x4A464646 : APP0_JFFF(); break; \/\/\"JFFF\"\r\n        default         : Skip_XX(Element_Size-Element_Offset,  \"Unknown\");\r\n    }\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\n\/\/ From OpenDML AVI File Format Extensions\r\nvoid File_Jpeg::APP0_AVI1()\r\n{\r\n    Element_Info1(\"AVI1\");\r\n\r\n    \/\/Parsing\r\n    bool UnknownInterlacement_IsDetected=false;\r\n    int8u  FieldOrder=(int8u)-1;\r\n    Get_B1 (FieldOrder,                                         \"Polarity\");\r\n    if (Element_Size>=14)\r\n    {\r\n        int32u FieldSize, FieldSizeLessPadding;\r\n        Skip_B1(                                                \"Reserved\");\r\n        Get_B4 (FieldSize,                                      \"FieldSize\");\r\n        Get_B4 (FieldSizeLessPadding,                           \"FieldSizeLessPadding\");\r\n\r\n        \/\/Coherency\r\n        if (FieldOrder==0 && IsSub && FieldSize && FieldSize!=Buffer_Size)\r\n        {\r\n            if (FieldSizeLessPadding>1 && FieldSizeLessPadding<=Buffer_Size && Buffer[FieldSizeLessPadding-2]==0xFF && Buffer[FieldSizeLessPadding-1]==0xD9  \/\/EOI\r\n             &&                           FieldSize+1         < Buffer_Size && Buffer[FieldSize]             ==0xFF && Buffer[FieldSize+1]           ==0xD8) \/\/SOI\r\n                UnknownInterlacement_IsDetected=true;\r\n        }\r\n    }\r\n    Skip_XX(Element_Size-Element_Offset,                        \"Unknown\");\r\n\r\n    FILLING_BEGIN();\r\n        if (Frame_Count==0 && Field_Count==0)\r\n        {\r\n            Accept();\r\n\r\n            if (UnknownInterlacement_IsDetected)\r\n            {\r\n                Fill(Stream_Video, 0, Video_ScanType, \"Interlaced\");\r\n                Interlaced=true;\r\n            }\r\n            else\r\n            {\r\n            switch (FieldOrder)\r\n            {\r\n                case 0x00 : Fill(Stream_Video, 0, Video_Interlacement, \"PPF\"); Fill(Stream_Video, 0, Video_ScanType, \"Progressive\"); break;\r\n                case 0x01 : Fill(Stream_Video, 0, Video_Interlacement, \"TFF\"); Fill(Stream_Video, 0, Video_ScanType, \"Interlaced\"); Fill(Stream_Video, 0, Video_ScanOrder, \"TFF\"); Interlaced=true; break;\r\n                case 0x02 : Fill(Stream_Video, 0, Video_Interlacement, \"BFF\"); Fill(Stream_Video, 0, Video_ScanType, \"Interlaced\"); Fill(Stream_Video, 0, Video_ScanOrder, \"BFF\"); Interlaced=true; break;\r\n                default   : ;\r\n            }\r\n            }\r\n        }\r\n    FILLING_END();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::APP0_JFIF()\r\n{\r\n    Element_Info1(\"JFIF\");\r\n\r\n    \/\/Parsing\r\n    Skip_B1(                                                    \"Zero\");\r\n    int16u Width, Height;\r\n    int8u  Unit, ThumbailX, ThumbailY;\r\n    Skip_B2(                                                    \"Version\");\r\n    Get_B1 (Unit,                                               \"Unit\"); \/\/0=Pixels, 1=dpi, 2=dpcm\r\n    Get_B2 (Width,                                              \"Xdensity\");\r\n    Get_B2 (Height,                                             \"Ydensity\");\r\n    Get_B1 (ThumbailX,                                          \"Xthumbail\");\r\n    Get_B1 (ThumbailY,                                          \"Ythumbail\");\r\n    Skip_XX(3*ThumbailX*ThumbailY,                              \"RGB Thumbail\");\r\n\r\n    APP0_JFIF_Parsed=true;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::APP0_JFFF()\r\n{\r\n    Element_Info1(\"JFFF\");\r\n\r\n    Skip_B1(                                                    \"Zero\");\r\n    Skip_B1(                                                    \"extension_code\"); \/\/0x10 Thumbnail coded using JPEG, 0x11 Thumbnail stored using 1 byte\/pixel, 0x13 Thumbnail stored using 3 bytes\/pixel\r\n    if (Element_Size>Element_Offset)\r\n        Skip_XX(Element_Size-Element_Offset,                    \"extension_data\");\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::APP0_JFFF_JPEG()\r\n{\r\n    \/\/Parsing\r\n    Element_Begin1(\"Thumbail JPEG\");\r\n        if (Element_Size>Element_Offset)\r\n            Skip_XX(Element_Size-Element_Offset,                \"Data\");\r\n    Element_End0();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::APP0_JFFF_1B()\r\n{\r\n    \/\/Parsing\r\n    Element_Begin1(\"Thumbail 1 byte per pixel\");\r\n        int8u  ThumbailX, ThumbailY;\r\n        Get_B1 (ThumbailX,                                      \"Xthumbail\");\r\n        Get_B1 (ThumbailY,                                      \"Ythumbail\");\r\n        Skip_XX(768,                                            \"Palette\");\r\n        Skip_XX(ThumbailX*ThumbailY,                            \"Thumbail\");\r\n    Element_End0();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::APP0_JFFF_3B()\r\n{\r\n    \/\/Parsing\r\n    Element_Begin1(\"Thumbail 3 bytes per pixel\");\r\n        int8u  ThumbailX, ThumbailY;\r\n        Get_B1 (ThumbailX,                                      \"Xthumbail\");\r\n        Get_B1 (ThumbailY,                                      \"Ythumbail\");\r\n        Skip_XX(3*ThumbailX*ThumbailY,                          \"RGB Thumbail\");\r\n    Element_End0();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::APP1()\r\n{\r\n    \/\/Parsing\r\n    int64u Name;\r\n    Get_C6(Name,                                                \"Name\");\r\n\r\n    switch (Name)\r\n    {\r\n        case 0x457869660000LL : APP1_EXIF(); break; \/\/\"Exif\\0\\0\"\r\n        default               : Skip_XX(Element_Size-Element_Offset, \"Data\");\r\n    }\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::APP1_EXIF()\r\n{\r\n    Element_Info1(\"Exif\");\r\n\r\n    \/\/Parsing\r\n    int32u Alignment;\r\n    Get_C4(Alignment,                                           \"Alignment\");\r\n    if (Alignment==0x49492A00)\r\n        Skip_B4(                                                \"First_IFD\");\r\n    if (Alignment==0x4D4D2A00)\r\n        Skip_L4(                                                \"First_IFD\");\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::APP2()\r\n{\r\n    \/\/Parsing\r\n    if (Element_Size>=12 && Buffer[Buffer_Offset+11]==0 && string((const char*)Buffer+Buffer_Offset)==\"ICC_PROFILE\")\r\n    {\r\n        Element_Info1(\"ICC profile\");\r\n        int8u Pos;\r\n        Skip_Local(12,                                          \"Signature\");\r\n        Get_B1 (Pos,                                            \"Chunk position?\"); \/\/1-based?\r\n        Skip_B1(                                                \"Chunk Max?\"); \/\/1-based?\r\n        if (Pos<=1) \/\/Multi-chunk ICC is not supported so we test it is order to skip the extra ICC blocks\r\n            APP2_ICC_PROFILE();\r\n        else\r\n            Skip_XX(Element_Size-Element_Offset,                \"(Multi-chunk ICC is not supported)\");\r\n    }\r\n    else\r\n        Skip_XX(Element_Size,                                   \"Data\");\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nstruct icctagtable\r\n{\r\n    int32u Signature;\r\n    int32u Offset;\r\n    int32u Size;\r\n};\r\nvoid File_Jpeg::APP2_ICC_PROFILE()\r\n{\r\n    Element_Begin1(\"ICC profile\");\r\n\r\n    \/\/Parsing\r\n    int64u Element_Start=Element_Offset; \/\/ Needed for tags position\r\n    int32u ColorSpace;\r\n    Element_Begin1(\"Profile header\");\r\n        Skip_B4(                                                \"Profile size\");\r\n        Skip_C4(                                                \"Preferred CMM type\");\r\n        Element_Begin1(\"Profile version number\");\r\n            int8u M;\r\n            Get_B1(M,                                           \"Major\");\r\n            if (M>4)\r\n            {\r\n                Element_End0();\r\n                Element_End0();\r\n                Element_End0();\r\n                return;\r\n            }\r\n            BS_Begin();\r\n            Info_S1(4, m,                                       \"Minor\");\r\n            Info_S1(4, f,                                       \"Fix\");\r\n            BS_End();\r\n            Skip_B2(                                            \"Reserved\");\r\n            Element_Info1(Ztring().From_Number(M)+__T('.')+Ztring().From_Number(m)+__T('.')+Ztring().From_Number(f));\r\n        Element_End0();\r\n        Skip_C4(                                                \"Profile\/Device class\");\r\n        Get_C4 (ColorSpace,                                     \"Colour space of data\");\r\n        Skip_C4(                                                \"PCS\");\r\n        Element_Begin1(\"Date\/Time\");\r\n            Info_B2(YY,                                         \"Year\");\r\n            Info_B2(MM,                                         \"Month\");\r\n            Info_B2(DD,                                         \"Day\");\r\n            Info_B2(hh,                                         \"Hour\");\r\n            Info_B2(mm,                                         \"Minute\");\r\n            Info_B2(ss,                                         \"Second\");\r\n            #if MEDIAINFO_TRACE\r\n                string DateTime;\r\n                DateTime+='0'+YY\/1000;\r\n                DateTime+='0'+(YY%1000)\/100;\r\n                DateTime+='0'+(YY%100)\/10;\r\n                DateTime+='0'+(YY%1000);\r\n                DateTime+='-';\r\n                DateTime+='0'+MM\/10;\r\n                DateTime+='0'+(MM%10);\r\n                DateTime+='-';\r\n                DateTime+='0'+DD\/10;\r\n                DateTime+='0'+(DD%10);\r\n                DateTime+=' ';\r\n                DateTime+='0'+hh\/10;\r\n                DateTime+='0'+(hh%10);\r\n                DateTime+=':';\r\n                DateTime+='0'+mm\/10;\r\n                DateTime+='0'+(mm%10);\r\n                DateTime+=':';\r\n                DateTime+='0'+ss\/10;\r\n                DateTime+='0'+(ss%10);\r\n                Element_Info1(DateTime.c_str());\r\n            #endif \/\/MEDIAINFO_TRACE\r\n        Element_End0();\r\n        Skip_C4(                                                \"'acsp' profile file signature \");\r\n        Skip_C4(                                                \"Primary platform signature\");\r\n        Skip_B4(                                                \"Profile flags\");\r\n        Skip_C4(                                                \"Device manufacturer\");\r\n        Skip_B4(                                                \"Device model\");\r\n        Skip_B4(                                                \"Device attributes TODO 1\");\r\n        Skip_B4(                                                \"Device attributes TODO 2\");\r\n        Skip_B4(                                                \"Rendering Intent\");\r\n        Element_Begin1(\"Illuminant of the PCS\");\r\n            APP2_ICC_PROFILE_XYZNumber();\r\n        Element_End0();\r\n        Skip_C4(                                                \"Profile creator signature\");\r\n        Skip_XX(16,                                             \"Profile ID\");\r\n        Skip_XX(28,                                             \"Reserved\");\r\n    Element_End0();\r\n\r\n    int32u Count;\r\n    vector<icctagtable> TagTables;\r\n    Element_Begin1(\"Tag table\");\r\n        Get_B4(Count,                                           \"Count\");\r\n        if (Count*12>Element_Size-Element_Offset)\r\n            Count=(Element_Size-Element_Offset)\/12;\r\n        for (int32u i=0; i<Count; i++)\r\n        {\r\n            icctagtable TagTable;\r\n            Get_C4(TagTable.Signature,                          \"Signature\"); Param_Info1(ICC_Tag(TagTable.Signature).c_str());\r\n            Get_B4(TagTable.Offset,                             \"Offset\");\r\n            Get_B4(TagTable.Size,                               \"Size\");\r\n            if (((int64u)TagTable.Offset)+TagTable.Size<=Element_Size-Element_Start)\r\n                TagTables.push_back(TagTable);\r\n        }\r\n    Element_End0();\r\n\r\n    Element_Begin1(\"Tagged element data\");\r\n        Count=(int32u)TagTables.size();\r\n        for (int32u i=0; i<Count; i++)\r\n        {\r\n            icctagtable& TagTable=TagTables[i];\r\n            Ztring Name;\r\n            \r\n            Element_Begin1(ICC_Tag(TagTable.Signature).c_str());\r\n            Element_Offset=Element_Start+TagTable.Offset;\r\n            int32u Type;\r\n            Get_C4(Type,                                        \"Type\");\r\n            switch (Type)\r\n            {\r\n                case 0x63757276: \/\/curv\r\n                                if (TagTable.Size<12)\r\n                                    Skip_XX(TagTable.Size-4,    \"Unknown\");\r\n                                else\r\n                                {\r\n                                    int32u Count;\r\n                                    Skip_B4(                    \"Reserved\");\r\n                                    Get_B4(Count,               \"Count\");\r\n                                    if (12+4*((Count+1)\/2)!=TagTable.Size)\r\n                                        Skip_XX(TagTable.Size-12, \"Unknown\");\r\n                                    else\r\n                                    {\r\n                                        for (int32u i=0; i<Count; i++)\r\n                                            Skip_B2(            \"Value\");\r\n                                        if (Count%2)\r\n                                            Skip_B2(            \"Padding\");\r\n                                    }\r\n                                }\r\n                                break;\r\n                case 0x64657363: \/\/desc\r\n                                if (TagTable.Size<12)\r\n                                    Skip_XX(TagTable.Size-4,    \"Unknown\");\r\n                                else\r\n                                {\r\n                                    Skip_B7(                    \"?\");\r\n                                    Skip_B1(                    \"String size\");\r\n                                    Skip_Local(TagTable.Size-12, \"Value\"); \/\/TODO: beter handling of this complex type\r\n                                }\r\n                                break;\r\n                case 0x74657874: \/\/text\r\n                                if (TagTable.Size<8)\r\n                                    Skip_XX(TagTable.Size-4,    \"Unknown\");\r\n                                else\r\n                                {\r\n                                    Skip_B4(                    \"Reserved\");\r\n                                    Skip_Local(TagTable.Size-8, \"Value\");\r\n                                }\r\n                                break;\r\n                case 0x58595A20: \/\/XYZ\r\n                                if (TagTable.Size!=20)\r\n                                    Skip_XX(TagTable.Size-4,    \"Unknown\");\r\n                                else\r\n                                {\r\n                                    Skip_B4(                    \"Reserved\");\r\n                                    APP2_ICC_PROFILE_XYZNumber();\r\n                                }\r\n                                break;\r\n                default:        Skip_XX(TagTable.Size-4,        \"Unknown\");\r\n            }\r\n            Element_End0();\r\n        }\r\n    Element_End0();\r\n    Element_End0();\r\n\r\n    FILLING_BEGIN()\r\n        Fill(StreamKind, 0, \"ColorSpace_ICC\", ICC_ColorSpace(ColorSpace));\r\n    FILLING_END()\r\n}\r\n\r\nvoid File_Jpeg::APP2_ICC_PROFILE_XYZNumber()\r\n{\r\n    #if MEDIAINFO_TRACE\r\n        APP2_ICC_PROFILE_s15Fixed16Number(\"X\");\r\n        APP2_ICC_PROFILE_s15Fixed16Number(\"Y\");\r\n        APP2_ICC_PROFILE_s15Fixed16Number(\"Z\");\r\n    #else \/\/MEDIAINFO_TRACE\r\n        Element_Offset+=12;\r\n    #endif \/\/MEDIAINFO_TRACE\r\n}\r\n\r\nvoid File_Jpeg::APP2_ICC_PROFILE_s15Fixed16Number(const char* Name)\r\n{\r\n    Info_B4(Value,                                              Name); Param_Info1(Ztring().From_Number(((float64)Value)\/0x10000, 6));\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::APPE()\r\n{\r\n    \/\/Parsing\r\n    int64u Name;\r\n    Get_C6(Name,                                                \"Name\");\r\n    switch (Name)\r\n    {\r\n        case 0x41646F626500LL : APPE_Adobe0(); break; \/\/\"AVI1\"\r\n        default               : Skip_XX(Element_Size-Element_Offset, \"Unknown\");\r\n    }\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Jpeg::APPE_Adobe0()\r\n{\r\n    Element_Info1(\"Adobe\");\r\n\r\n    \/\/Parsing\r\n    int8u Version;\r\n    Get_B1(Version,                                             \"Version\");\r\n    if (Version==100)\r\n    {\r\n        int8u transform;\r\n        Skip_B2(                                                \"flags0\");\r\n        Skip_B2(                                                \"flags1\");\r\n        Get_B1 (transform,                                      \"transform\");\r\n\r\n        FILLING_BEGIN();\r\n            APPE_Adobe0_transform=transform;\r\n        FILLING_END();\r\n    }\r\n    else\r\n        Skip_XX(Element_Size-Element_Offset,                    \"unknown\");\r\n}\r\n\r\n} \/\/NameSpace\r\n\r\n#endif\r\n","avg_line_length":44.7508463101,"max_line_length":222,"alphanum_fraction":0.4167360092,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":12610,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":198.0,"content":"\/\/ test_bernoulli.cpp\r\n\r\n\/\/ Copyright John Maddock 2006.\r\n\/\/ Copyright  Paul A. Bristow 2007, 2012.\r\n\r\n\/\/ Use, modification and distribution are subject to the\r\n\/\/ Boost Software License, Version 1.0.\r\n\/\/ (See accompanying file LICENSE_1_0.txt\r\n\/\/ or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\r\n\/\/ Basic sanity test for Bernoulli Cumulative Distribution Function.\r\n\r\n#ifdef _MSC_VER\r\n#  pragma warning (disable : 4535) \/\/ calling _set_se_translator() requires \/EHa.\r\n#  pragma warning (disable : 4244) \/\/ conversion possible loss of data.\r\n#  pragma warning (disable : 4996) \/\/ 'putenv': The POSIX name for this item is deprecated.\r\n#  pragma warning (disable : 4127) \/\/ conditional expression is constant.\r\n#endif\r\n\r\n\/\/ Default domain error policy is\r\n\/\/ #define BOOST_MATH_DOMAIN_ERROR_POLICY throw_on_error\r\n\r\n#include <boost\/math\/concepts\/real_concept.hpp> \/\/ for real_concept\r\nusing ::boost::math::concepts::real_concept;\r\n\r\n#include <boost\/math\/distributions\/bernoulli.hpp> \/\/ for bernoulli_distribution\r\nusing boost::math::bernoulli_distribution;\r\n\r\n#include <boost\/test\/test_exec_monitor.hpp> \/\/ for test_main\r\n#include <boost\/test\/floating_point_comparison.hpp> \/\/ for BOOST_CHECK_CLOSE_FRACTION, BOOST_CHECK_EQUAL...\r\n\r\n#include <iostream>\r\nusing std::cout;\r\nusing std::endl;\r\nusing std::fixed;\r\nusing std::right;\r\nusing std::left;\r\nusing std::showpoint;\r\nusing std::showpos;\r\nusing std::setw;\r\nusing std::setprecision;\r\n\r\n#include <limits>\r\nusing std::numeric_limits;\r\n\r\ntemplate <class RealType> \/\/ Any floating-point type RealType.\r\nvoid test_spots(RealType)\r\n{ \/\/ Parameter only provides the type, float, double... value ignored.\r\n\r\n  \/\/ Basic sanity checks, test data may be to double precision only\r\n  \/\/ so set tolerance to 100 eps expressed as a fraction,\r\n  \/\/ or 100 eps of type double expressed as a fraction,\r\n  \/\/ whichever is the larger.\r\n\r\n  RealType tolerance = (std::max)\r\n      (boost::math::tools::epsilon<RealType>(),\r\n      static_cast<RealType>(std::numeric_limits<double>::epsilon()));\r\n   tolerance *= 100;\r\n\r\n  cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \"\r\n    << setprecision(3) << tolerance  << \" (or \" << tolerance * 100 << \"%).\" << endl;\r\n\r\n  \/\/ Sources of spot test values - calculator,\r\n  \/\/ or Steve Moshier's command interpreter V1.3 100 decimal digit calculator,\r\n  \/\/ Wolfram function evaluator.\r\n\r\n  using boost::math::bernoulli_distribution; \/\/ of type RealType.\r\n  using  ::boost::math::cdf;\r\n  using  ::boost::math::pdf;\r\n\r\n  BOOST_CHECK_EQUAL(bernoulli_distribution<RealType>(static_cast<RealType>(0.5)).success_fraction(), static_cast<RealType>(0.5));\r\n  BOOST_CHECK_EQUAL(bernoulli_distribution<RealType>(static_cast<RealType>(0.1L)).success_fraction(), static_cast<RealType>(0.1L));\r\n  BOOST_CHECK_EQUAL(bernoulli_distribution<RealType>(static_cast<RealType>(0.9L)).success_fraction(), static_cast<RealType>(0.9L));\r\n\r\n  BOOST_CHECK_THROW( \/\/ Constructor success_fraction outside 0 to 1.\r\n       bernoulli_distribution<RealType>(static_cast<RealType>(2)), std::domain_error);\r\n  BOOST_CHECK_THROW(\r\n       bernoulli_distribution<RealType>(static_cast<RealType>(-2)), std::domain_error);\r\n\r\n  BOOST_CHECK_THROW(\r\n       pdf( \/\/ pdf k neither 0 nor 1.\r\n          bernoulli_distribution<RealType>(static_cast<RealType>(0.25L)), static_cast<RealType>(-1)), std::domain_error);\r\n\r\n  BOOST_CHECK_THROW(\r\n       pdf( \/\/ pdf k neither 0 nor 1.\r\n          bernoulli_distribution<RealType>(static_cast<RealType>(0.25L)), static_cast<RealType>(2)), std::domain_error);\r\n \r\n  BOOST_CHECK_EQUAL(\r\n    pdf( \/\/ OK k (or n)\r\n    bernoulli_distribution<RealType>(static_cast<RealType>(0.5L)), static_cast<RealType>(0)),\r\n      static_cast<RealType>(0.5)); \/\/ Expect 1 - p.\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(\r\n    pdf( \/\/ OK k (or n)\r\n    bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)), static_cast<RealType>(0)),\r\n      static_cast<RealType>(0.4L), tolerance); \/\/ Expect  1 - p.\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(\r\n    pdf( \/\/ OK k (or n)\r\n    bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)), static_cast<RealType>(0)),\r\n      static_cast<RealType>(0.4L), tolerance); \/\/ Expect  1- p.\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(\r\n    pdf( \/\/ OK k (or n)\r\n    bernoulli_distribution<RealType>(static_cast<RealType>(0.4L)), static_cast<RealType>(0)),\r\n      static_cast<RealType>(0.6L), tolerance); \/\/ Expect  1- p.\r\n\r\n  BOOST_CHECK_EQUAL(\r\n       mean(bernoulli_distribution<RealType>(static_cast<RealType>(0.5L))), static_cast<RealType>(0.5L));\r\n\r\n  BOOST_CHECK_EQUAL(\r\n       mean(bernoulli_distribution<RealType>(static_cast<RealType>(0.1L))),\r\n       static_cast<RealType>(0.1L));\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(\r\n       variance(bernoulli_distribution<RealType>(static_cast<RealType>(0.1L))),\r\n       static_cast<RealType>(0.09L),\r\n       tolerance);\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(\r\n       skewness(bernoulli_distribution<RealType>(static_cast<RealType>(0.1L))),\r\n       static_cast<RealType>(2.666666666666666666666666666666666666666666L),\r\n       tolerance);\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(\r\n       kurtosis(bernoulli_distribution<RealType>(static_cast<RealType>(0.1L))),\r\n       static_cast<RealType>(8.11111111111111111111111111111111111111111111L),\r\n       tolerance);\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(\r\n       kurtosis_excess(bernoulli_distribution<RealType>(static_cast<RealType>(0.1L))),\r\n       static_cast<RealType>(5.11111111111111111111111111111111111111111111L),\r\n       tolerance);\r\n\r\n  BOOST_CHECK_THROW(\r\n     quantile(\r\n        bernoulli_distribution<RealType>(static_cast<RealType>(2)), \/\/ prob >1\r\n        static_cast<RealType>(0)), std::domain_error\r\n     );\r\n  BOOST_CHECK_THROW(\r\n     quantile(\r\n        bernoulli_distribution<RealType>(static_cast<RealType>(-1)), \/\/ prob < 0\r\n        static_cast<RealType>(0)), std::domain_error\r\n     );\r\n  BOOST_CHECK_THROW(\r\n     quantile(\r\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.5L)), \/\/ k >1\r\n        static_cast<RealType>(-1)), std::domain_error\r\n     );\r\n  BOOST_CHECK_THROW(\r\n     quantile(\r\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.5L)), \/\/ k < 0\r\n        static_cast<RealType>(2)), std::domain_error\r\n     );\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(\r\n     cdf(\r\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\r\n        static_cast<RealType>(0)), \r\n        static_cast<RealType>(0.4L), \/\/ 1 - p\r\n        tolerance\r\n     );\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(\r\n     cdf(\r\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\r\n        static_cast<RealType>(1)), \r\n        static_cast<RealType>(1), \/\/ p\r\n        tolerance\r\n     );\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(\r\n     cdf(complement(\r\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\r\n        static_cast<RealType>(1))), \r\n        static_cast<RealType>(0),\r\n        tolerance\r\n     );\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(\r\n     cdf(complement(\r\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\r\n        static_cast<RealType>(0))), \r\n        static_cast<RealType>(0.6L),\r\n        tolerance\r\n     );\r\n\r\n  BOOST_CHECK_EQUAL(\r\n     quantile(\r\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\r\n        static_cast<RealType>(0.1L)),  \/\/ < p\r\n        static_cast<RealType>(0) \r\n     );\r\n\r\n  BOOST_CHECK_EQUAL(\r\n     quantile(\r\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\r\n        static_cast<RealType>(0.9L)),  \/\/ > p\r\n        static_cast<RealType>(1) \r\n     );\r\n\r\n   BOOST_CHECK_EQUAL(\r\n     quantile(complement(\r\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\r\n        static_cast<RealType>(0.1L))),  \/\/ < p\r\n        static_cast<RealType>(1) \r\n     );\r\n\r\n   BOOST_CHECK_EQUAL(\r\n     quantile(complement(\r\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\r\n        static_cast<RealType>(0.9L))),  \/\/ > p\r\n        static_cast<RealType>(0) \r\n     );\r\n\r\n   \/\/ Checks for 'bad' parameters.\r\n   \/\/ Construction.\r\n   BOOST_CHECK_THROW(bernoulli_distribution<RealType>(-1), std::domain_error); \/\/ p outside 0 to 1.\r\n   BOOST_CHECK_THROW(bernoulli_distribution<RealType>(+2), std::domain_error); \/\/ p outside 0 to 1.\r\n\r\n   \/\/ Parameters.\r\n   bernoulli_distribution<RealType> dist(RealType(1)); \r\n   BOOST_CHECK_THROW(pdf(dist, -1), std::domain_error);\r\n   BOOST_CHECK_THROW(cdf(dist, -1), std::domain_error);\r\n   BOOST_CHECK_THROW(cdf(complement(dist, -1)), std::domain_error);\r\n   BOOST_CHECK_THROW(quantile(dist, 2), std::domain_error);\r\n   BOOST_CHECK_THROW(quantile(complement(dist, -1)), std::domain_error);\r\n   BOOST_CHECK_THROW(quantile(dist, -1), std::domain_error);\r\n   BOOST_CHECK_THROW(quantile(complement(dist, -1)), std::domain_error);\r\n     \r\n   \/\/ No longer allow any parameter to be NaN or inf, so all these tests should throw.\r\n   if (std::numeric_limits<RealType>::has_quiet_NaN)\r\n   { \r\n    \/\/ Attempt to construct from non-finite should throw.\r\n     RealType nan = std::numeric_limits<RealType>::quiet_NaN();\r\n     BOOST_CHECK_THROW(bernoulli_distribution<RealType> b(nan), std::domain_error);\r\n     \r\n    \/\/ Non-finite parameters should throw.\r\n     bernoulli_distribution<RealType> b(RealType(1)); \r\n     BOOST_CHECK_THROW(pdf(b, +nan), std::domain_error); \/\/ x = NaN\r\n     BOOST_CHECK_THROW(cdf(b, +nan), std::domain_error); \/\/ x = NaN\r\n     BOOST_CHECK_THROW(cdf(complement(b, +nan)), std::domain_error); \/\/ x = + nan\r\n     BOOST_CHECK_THROW(quantile(b, +nan), std::domain_error); \/\/ p = + nan\r\n     BOOST_CHECK_THROW(quantile(complement(b, +nan)), std::domain_error); \/\/ p = + nan\r\n  } \/\/ has_quiet_NaN\r\n\r\n  if (std::numeric_limits<RealType>::has_infinity)\r\n  {\r\n     RealType inf = std::numeric_limits<RealType>::infinity(); \r\n     BOOST_CHECK_THROW(bernoulli_distribution<RealType> w(inf), std::domain_error);\r\n\r\n     bernoulli_distribution<RealType> w(RealType(1)); \r\n     BOOST_CHECK_THROW(bernoulli_distribution<RealType> w(inf), std::domain_error);\r\n     BOOST_CHECK_THROW(pdf(w, +inf), std::domain_error); \/\/ x = inf\r\n     BOOST_CHECK_THROW(cdf(w, +inf), std::domain_error); \/\/ x = inf\r\n     BOOST_CHECK_THROW(cdf(complement(w, +inf)), std::domain_error); \/\/ x = + inf\r\n     BOOST_CHECK_THROW(quantile(w, +inf), std::domain_error); \/\/ p = + inf\r\n     BOOST_CHECK_THROW(quantile(complement(w, +inf)), std::domain_error); \/\/ p = + inf\r\n   } \/\/ has_infinity\r\n\r\n} \/\/ template <class RealType>void test_spots(RealType)\r\n\r\nint test_main(int, char* [])\r\n{\r\n   BOOST_MATH_CONTROL_FP;\r\n   \/\/ Check that can generate bernoulli distribution using both convenience methods:\r\n   bernoulli_distribution<double> bn1(0.5); \/\/ Using default RealType double.\r\n   boost::math::bernoulli bn2(0.5); \/\/ Using typedef. \r\n\r\n  BOOST_CHECK_EQUAL(bn1.success_fraction(), 0.5);\r\n  BOOST_CHECK_EQUAL(bn2.success_fraction(), 0.5);\r\n\r\n  BOOST_CHECK_EQUAL(kurtosis(bn2) -3, kurtosis_excess(bn2));\r\n  BOOST_CHECK_EQUAL(kurtosis_excess(bn2), -2);\r\n\r\n  \/\/using namespace boost::math; or \r\n  using boost::math::bernoulli;\r\n\r\n  double tol5eps = std::numeric_limits<double>::epsilon() * 5; \/\/ 5 eps as a fraction.\r\n  \/\/ Default bernoulli is type double, so these test values should also be type double.\r\n  BOOST_CHECK_CLOSE_FRACTION(kurtosis_excess(bernoulli(0.1)), 5.11111111111111111111111111111111111111111111111111, tol5eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(kurtosis_excess(bernoulli(0.9)), 5.11111111111111111111111111111111111111111111111111, tol5eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(kurtosis(bernoulli(0.6)), 1.\/0.4 + 1.\/0.6 -3., tol5eps);\r\n  BOOST_CHECK_EQUAL(kurtosis(bernoulli(0)), +std::numeric_limits<double>::infinity());\r\n  BOOST_CHECK_EQUAL(kurtosis(bernoulli(1)), +std::numeric_limits<double>::infinity());\r\n \/\/ \r\n\r\n  \/\/ Basic sanity-check spot values.\r\n\r\n  \/\/ (Parameter value, arbitrarily zero, only communicates the floating point type).\r\n  test_spots(0.0F); \/\/ Test float.\r\n  test_spots(0.0); \/\/ Test double.\r\n  test_spots(0.0L); \/\/ Test long double.\r\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\r\n  test_spots(boost::math::concepts::real_concept(0.)); \/\/ Test real concept.\r\n#endif\r\n\r\n  return 0;\r\n} \/\/ int test_main(int, char* [])\r\n\r\n\/*\r\n\r\nOutput is:\r\n\r\n  Description: Autorun \"J:\\Cpp\\MathToolkit\\test\\Math_test\\Debug\\test_bernouilli.exe\"\r\n  Running 1 test case...\r\n  Tolerance for type float is 1.19e-005 (or 0.00119%).\r\n  Tolerance for type double is 2.22e-014 (or 2.22e-012%).\r\n  Tolerance for type long double is 2.22e-014 (or 2.22e-012%).\r\n  Tolerance for type class boost::math::concepts::real_concept is 2.22e-014 (or 2.22e-012%).\r\n  \r\n  *** No errors detected\r\n\r\n\r\n*\/\r\n\r\n\r\n","avg_line_length":39.6540880503,"max_line_length":132,"alphanum_fraction":0.6861221253,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5267,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/\/\n\/\/ Created by Administrator on 2019\/12\/31.\n\/\/\n\n#include \"deskTopDraw.h\"\n#include \"publicbase\/def.h\"\n#include \"publicbase\/baseFunc.h\"\n#include \"network\/udphelplib.h\"\n#include <sys\/time.h>\n#include <unistd.h>\n#include <gl\/GLbase.h>\n#include <cstring>\n#include <cstdio>\n#include <network\/p2p_udp.h>\n\nextern JavaVM* g_vm;\njobject g_imgThis;\njmethodID g_imgMid;\n\nextern int g_screenWidth;\nextern int g_screenHeight;\nextern p2p_udp m_udphelp;\n#define  scaleX 300\n#define  scaleY 300\ndeskTopDraw::deskTopDraw() {\n    m_oldw=0;\n    m_oldh=0;\n\n    m_scalePoint=-1;\n    m_softwareShow=true;\n    return;\n}\nbool deskTopDraw::init() {\n    std::function<int()> p_func= std::bind( &deskTopDraw::draw,this);\n    mRenderer.requestRegDrawFunc(p_func);\n    m_yuv.setRc(m_showRC);\n    m_imgBuf.reserve(1024*1024);\n    return true;\n}\nint  deskTopDraw::draw(){\n    m_yuv.draw();\n    return 1;\n}\nbool deskTopDraw::reSetImg() {\n    m_oldw=0;\n    return true;\n}\nbool deskTopDraw::sendRecvImg(uint32_t retid) {\n    m_udphelp.sendRecvData(retid,\"1\",1);\n    return true;\n}\nbool deskTopDraw::requestIDR() {\n\n}\n\nbool deskTopDraw::mediaShow(const char *data, int len) {\n\n    JNIEnv* p_env = nullptr;\n    g_vm->AttachCurrentThread(&p_env, NULL);\n    jbyteArray jbarray = p_env->NewByteArray(len);\n    p_env->SetByteArrayRegion(jbarray, 0, len, (jbyte *) data);\n    p_env->CallVoidMethod(g_imgThis, g_imgMid, jbarray,len);\n    p_env->DeleteLocalRef(jbarray);\n    g_vm->DetachCurrentThread();\n    return true;\n}\n\nbool deskTopDraw::sendOnImgNum(uint32_t num) {\n    static int p_i = 0;\n    p_i++;\n    if (p_i != 2)\n    {\n        return true;\n    }\n    p_i = 0;\n    char p_temp[128] = {};\n    sprintf(p_temp,  \"fun=onImgCallBack&id=%u\", num);\n    m_udphelp.sendData(p_temp, strlen(p_temp));\n    return true;\n}\nbool deskTopDraw::sizeChange(float w, float h) {\n    m_oldw=w;\n    m_oldh=h;\n    reSetShowSize(w,h);\n    m_yuv.init(w,h);\n    \/\/m_yuv.setScaleDraw(m_scalePoint,2);\n   return true;\n}\nstd::string deskTopDraw::getBaseInfo() {\n    char p_str[128]={};\n    sprintf(p_str,\"func=setGameScreenSize&x=%d&y=%d&w=%d&h=%d&s=%f\",(int)m_showRC.x,(int)m_showRC.y,(int)m_showRC.w,(int)m_showRC.h,m_showScale);\n    return p_str;\n}\n\nbool deskTopDraw::setShowType(bool software) {\n\n}\nbool deskTopDraw::scale(int point) {\n    if(point==-1)\n    {\n        m_scalePoint=-1;\n        m_yuv.setUnScale();\n        return true;\n    }\n    m_scalePoint=point;\n    m_yuv.setScaleDraw(m_scalePoint,2);\n\n}\n\nbool deskTopDraw::getMousePoint(float &x, float &y) {\n    if (x < m_showRC.x || x > m_showRC.midX) {\n        return false;\n    }\n    if (y < m_showRC.y || y > m_showRC.midY) {\n        return false;\n    }\n    x = x - m_showRC.x;\n    x \/= m_showScale;\n    y = y - m_showRC.y;\n    y \/= m_showScale;\n    return true;\n}\n\nbool deskTopDraw::OnImg(strPtr str,uint32_t retid){\n    if (retid != 0) {\n        sendRecvImg(retid);\n    }\n    int p_len = webbase::post_i(*str, \"imgL\");\n    int p_w = webbase::post_i(*str, \"imgNW\");\n    int p_h = webbase::post_i(*str, \"imgH\");\n    int p_end=webbase::post_i(*str,\"end\");\n    int c = str->find(\"data=\");\n    if (c == -1)\n    {\n        return false;\n    }\n    c += 5;\n    if (p_len + c > str->length())\n    {\n        return true;\n    }\n    if(p_end==0){\n        if(m_imgBuf.size()>1024*900)\n        {\n            m_imgBuf.resize(0);\n        }\n        m_imgBuf.append(&(*str)[c], p_len);\n        return false;\n    }\n    sendOnImgNum(static_cast<uint32_t>(webbase::post_i((*str), \"imgNum\")));\n    char* p_imgData= nullptr;\n\n    if(m_imgBuf.size()>0)\n    {\n        m_imgBuf.append(&(*str)[c], p_len);\n        p_imgData=&m_imgBuf[0];\n        p_len=m_imgBuf.size();\n    } else{\n        p_imgData=&(*str)[c];\n    }\n    char**\tp_retData = NULL;\n    int\t\tp_retLength = 0;\n    if(!m_softwareShow){\n        mediaShow(p_imgData,p_len);\n        m_imgBuf.resize(0);\n        return true;\n    }\n\n    struct timeval tpstart, tpend;\n    float timeuse;\n    gettimeofday(&tpstart, NULL);\n    if (!m_h264Decode.deCode(p_w, p_h, p_w, p_h, p_imgData, p_len, &p_retData, p_retLength)) {\n        m_imgBuf.resize(0);\n        requestIDR();\n        return  false;\n    }\n    m_imgBuf.resize(0);\n\n    if(p_w!=m_oldw || p_h != m_oldh){\n        sizeChange(p_w,p_h);\n    }\n\n    gettimeofday(&tpend, NULL);\n    timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;\n    timeuse \/= 1000;\n    Elog(\"decodeTime:[%f][%d]\",timeuse,p_len);\n\n    gettimeofday(&tpstart, NULL);\n    m_yuv.setData((const char**)p_retData);\n\n    mRenderer.nativeDraw();\n    gettimeofday(&tpend, NULL);\n    timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;\n    timeuse \/= 1000;\n    Elog(\"showTime:[%f]\",timeuse);\n    return true;\n}\n\nbool deskTopDraw::reSetShowSize(float w, float h) {\n    float p_wScale = g_screenWidth \/ w;\n    float p_hScale = g_screenHeight \/ h;\n    m_showScale = p_wScale < p_hScale ? p_wScale : p_hScale;\n    m_showRC.w = w * m_showScale;\n    m_showRC.h = h * m_showScale;\n    m_showRC.x = (g_screenWidth - m_showRC.w) \/ 2;\n    m_showRC.y = (g_screenHeight - m_showRC.h) \/ 2;\n    m_showRC.midX = m_showRC.w + m_showRC.x;\n    m_showRC.midY = m_showRC.h + m_showRC.y;\n    ntl::bridgeToWeb(getBaseInfo().c_str());\n    return true;\n}\n\ndeskTopDraw g_deskTopDraw;","avg_line_length":24.7276995305,"max_line_length":145,"alphanum_fraction":0.6227453959,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8653,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":4587.0,"content":"\/*\n* Copyright (C) 2015 - 2018 Intel Corporation.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions are met:\n* 1. Redistributions of source code must retain the above copyright notice(s),\n*    this list of conditions and the following disclaimer.\n* 2. Redistributions in binary form must reproduce the above copyright notice(s),\n*    this list of conditions and the following disclaimer in the documentation\n*    and\/or other materials provided with the distribution.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS\n* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO\n* EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <stdio.h>\n#include <assert.h>\n#include <iostream>\n#include <vector>\n\n#include \"Configuration.hpp\"\n#include \"AllocatorFactory.hpp\"\n#include \"TaskFactory.hpp\"\n#include \"Task.hpp\"\n#include \"ConsoleLog.hpp\"\n#include \"Stats.hpp\"\n#include \"Thread.hpp\"\n#include \"Tests.hpp\"\n#include \"CommandLine.hpp\"\n#include \"FunctionCallsPerformanceTask.h\"\n#include \"StressIncreaseToMax.h\"\n\n\/*\nCommand line description.\nSyntax:\n\tkey=value\nOptions:\n\t- 'test' - specify the test case. This option can be used with the following values: 'calls', 'all' or 'self',\n\twhere:\n\t\t'calls' - function calls performance test,\n\t\t'all' - execute both above ('footprint' and 'calls') tests,\n\t\t'self' - execute self tests\n\t\t's1' - stress tests\n\t\t(perform allocations until the maximum amount of allocated memory has been reached, than frees allocated memory.\n\t\tIf the time interval has not been exceed, than repeat the test),\n\t- 'operations' - the number of memory operations per thread\n\t- 'size_from' - lower bound for the random sizes of allocation\n\t- 'size_to' - upper bound for the random sizes of allocation\n\t- 'seed' - random seed\n\t- 'threads_num' - the number of threads per test case\n\t- 'time' - minimum execution time interval\n\t- 'kind' - the kind to test\n\t- 'csv_log' - if 'true' then log to csv file memory operations and statistics\n\t- 'call' specify the allocation function call. This option can be used with the following values: 'malloc' (default), 'calloc', 'realloc',\n\t- 'requested_memory_limit' test stops when the requested memory limit has been reached\n* - maximum of available memory in OS, or maximum memory based 'operations' parameter\nExample:\n1. Performance test:\n.\/perf_tool test=all operations=1000 size_from=32 size_to=20480 seed=11 threads_num=200\n2. Stress test\n.\/perf_tool test=s1 time=120 kind=MEMKIND_HBW size_from=1048576 csv_log=true requested_memory_limit=1048576\n*\/\n\nint main(int argc, char *argv[])\n{\n    unsigned mem_operations_num = 1000;\n    size_t size_from = 32, size_to = 2048*1024;\n    unsigned seed = 11;\n    \/\/should be at least one\n    size_t threads_number = 10;\n\n    CommandLine cmd_line(argc, argv);\n\n    if((argc >= 1) && cmd_line.is_option_set(\"test\", \"self\")) {\n        execute_self_tests();\n        getchar();\n    }\n\n    cmd_line.parse_with_strtol(\"operations\", mem_operations_num);\n    cmd_line.parse_with_strtol(\"size_from\", size_from);\n    cmd_line.parse_with_strtol(\"size_to\", size_to);\n    cmd_line.parse_with_strtol(\"seed\", seed);\n    cmd_line.parse_with_strtol(\"threads_num\", threads_number);\n\n    bool is_csv_log_enabled = cmd_line.is_option_set(\"csv_log\", \"true\");\n\n    \/\/Heap Manager initialization\n    std::vector<AllocatorFactory::initialization_stat> stats =\n        AllocatorFactory().initialization_test();\n\n    if(!cmd_line.is_option_set(\"print_init_stats\", \"false\")) {\n        printf(\"\\nInitialization overhead:\\n\");\n        for (int i=0; i<stats.size(); i++) {\n            AllocatorFactory::initialization_stat stat = stats[i];\n            printf(\"%32s : time=%7.7f.s, ref_delta_time=%15f, node0=%10fMB, node1=%7.7fMB\\n\",\n                   AllocatorTypes::allocator_name(stat.allocator_type).c_str(),\n                   stat.total_time,\n                   stat.ref_delta_time,\n                   stat.memory_overhead[0],\n                   stat.memory_overhead[1]);\n        }\n    }\n\n    \/\/Stress test by repeatedly increasing memory (to maximum), until given time interval has been exceed.\n    if(cmd_line.is_option_set(\"test\", \"s1\")) {\n        printf(\"Stress test (StressIncreaseToMax) start. \\n\");\n\n        if(!cmd_line.is_option_present(\"operations\"))\n            mem_operations_num = 1000000;\n\n        unsigned time = 120; \/\/Default time interval.\n        cmd_line.parse_with_strtol(\"time\", time);\n\n        size_t requested_memory_limit = 1024*1024;\n        cmd_line.parse_with_strtol(\"requested_memory_limit\", requested_memory_limit);\n\n        unsigned allocator = AllocatorTypes::MEMKIND_HBW;\n        if(cmd_line.is_option_present(\"kind\")) {\n            \/\/Enable memkind allocator and specify kind.\n            allocator = AllocatorTypes::allocator_type(cmd_line.get_option_value(\"kind\"));\n        }\n        TypesConf allocator_types;\n        allocator_types.enable_type(allocator);\n\n        TypesConf enable_func_calls;\n        enable_func_calls.enable_type(FunctionCalls::MALLOC);\n\n        TaskConf task_conf = {\n            mem_operations_num,\n            {\n                mem_operations_num,\n                size_from, \/\/No random sizes.\n                size_from\n            },\n            enable_func_calls,\n            allocator_types,\n            11,\n            is_csv_log_enabled,\n        };\n\n        StressIncreaseToMax::execute_test_iterations(task_conf, time,\n                                                     requested_memory_limit);\n        return 0;\n    }\n\n    printf(\"\\nTest configuration: \\n\");\n    printf(\"\\t memory operations per thread = %u \\n\", mem_operations_num);\n    printf(\"\\t seed = %d\\n\", seed);\n    printf(\"\\t number of threads = %zu\\n\", threads_number);\n    printf(\"\\t size from-to = %zu-%zu\\n\\n\", size_from, size_to);\n\n    assert(size_from <= size_to);\n\n\n    TypesConf func_calls;\n    func_calls.enable_type(FunctionCalls::FREE);\n\n    if(cmd_line.is_option_present(\"call\")) {\n        \/\/Enable heap manager function call.\n        func_calls.enable_type(FunctionCalls::function_type(\n                                   cmd_line.get_option_value(\"call\")));\n    } else {\n        func_calls.enable_type(FunctionCalls::MALLOC);\n    }\n\n    TypesConf allocator_types;\n    if(cmd_line.is_option_present(\"allocator\")) {\n        allocator_types.enable_type(AllocatorTypes::allocator_type(\n                                        cmd_line.get_option_value(\"allocator\")));\n    } else {\n        for(unsigned i = 0; i <= AllocatorTypes::MEMKIND_HBW_PREFERRED; i++) {\n            allocator_types.enable_type(i);\n        }\n    }\n\n    TaskConf conf = {\n        mem_operations_num, \/\/number memory operations\n        {\n            mem_operations_num, \/\/number of memory operations\n            size_from, \/\/min. size of single allocation\n            size_to \/\/max. size of single allocatioion\n        },\n        func_calls, \/\/enable function calls\n        allocator_types, \/\/enable allocators\n        seed, \/\/random seed\n        is_csv_log_enabled,\n    };\n\n    \/\/Function calls test\n    if(cmd_line.is_option_set(\"test\", \"calls\") ||\n       cmd_line.is_option_set(\"test\", \"all\")) {\n        TaskFactory task_factory;\n        std::vector<Thread *> threads;\n        std::vector<Task *> tasks;\n\n        for (int i=0; i<threads_number; i++) {\n            FunctionCallsPerformanceTask *task =\n                static_cast<FunctionCallsPerformanceTask *>(\n                    task_factory.create(conf)\n                );\n            tasks.push_back(task);\n            threads.push_back(new Thread(task));\n            conf.seed += 1;\n        }\n\n        ThreadsManager threads_manager(threads);\n        threads_manager.start();\n        threads_manager.barrier();\n\n        TimeStats stats;\n        for (int i=0; i<tasks.size(); i++) {\n            stats += tasks[i]->get_results();\n        }\n\n        ConsoleLog::print_table(stats);\n        ConsoleLog::print_requested_memory(stats, \"func. calls test\");\n\n        threads_manager.release();\n    }\n\n    return 0;\n}\n","avg_line_length":37.2974137931,"max_line_length":139,"alphanum_fraction":0.6637004507,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2054,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"#include \"TestHarness.h\"\n#include \"Buffer.h\"\n\nTEST(Stack_BufferLayout, creation_BufferLayout)\n{\n  Engine::BufferLayout layout(\n    {\n      {Engine::ShaderDataType::FLOAT, \"float\", true},\n      {Engine::ShaderDataType::VEC3, \"vec3\", false},\n      {Engine::ShaderDataType::MAT3, \"mat3\", true},\n      {Engine::ShaderDataType::IVEC2, \"ivec2\", false}\n    });\n\n  unsigned char * buf = new unsigned char[layout.Size()];\n  layout.Serialize(buf);\n  Engine::BufferLayout output;\n  output.Deserialize(buf);\n\n  CHECK(layout.GetStride() == output.GetStride());\n\n  CHECK(layout.GetElements()[0].name == output.GetElements()[0].name);\n  CHECK(layout.GetElements()[0].type == output.GetElements()[0].type);\n  CHECK(layout.GetElements()[0].size == output.GetElements()[0].size);\n  CHECK(layout.GetElements()[0].offset == output.GetElements()[0].offset);\n  CHECK(layout.GetElements()[0].normalized == output.GetElements()[0].normalized);\n\n  CHECK(layout.GetElements()[1].name == output.GetElements()[1].name);\n  CHECK(layout.GetElements()[1].type == output.GetElements()[1].type);\n  CHECK(layout.GetElements()[1].size == output.GetElements()[1].size);\n  CHECK(layout.GetElements()[1].offset == output.GetElements()[1].offset);\n  CHECK(layout.GetElements()[1].normalized == output.GetElements()[1].normalized);\n\n  CHECK(layout.GetElements()[2].name == output.GetElements()[2].name);\n  CHECK(layout.GetElements()[2].type == output.GetElements()[2].type);\n  CHECK(layout.GetElements()[2].size == output.GetElements()[2].size);\n  CHECK(layout.GetElements()[2].offset == output.GetElements()[2].offset);\n  CHECK(layout.GetElements()[2].normalized == output.GetElements()[2].normalized);\n\n  CHECK(layout.GetElements()[3].name == output.GetElements()[3].name);\n  CHECK(layout.GetElements()[3].type == output.GetElements()[3].type);\n  CHECK(layout.GetElements()[3].size == output.GetElements()[3].size);\n  CHECK(layout.GetElements()[3].offset == output.GetElements()[3].offset);\n  CHECK(layout.GetElements()[3].normalized == output.GetElements()[3].normalized);\n\n  delete[] buf;\n}","avg_line_length":44.652173913,"max_line_length":82,"alphanum_fraction":0.6932814021,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":39586,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":null,"content":"\/\/---------------------------------------------------------------------------\r\n\/\/\r\n\/\/ Name:        chessFrame.cpp\r\n\/\/ Author:      gurkesaft\r\n\/\/ Created:     6\/23\/2007 3:18:51 PM\r\n\/\/ Description: chessFrame class implementation\r\n\/\/\r\n\/\/---------------------------------------------------------------------------\r\n\r\n#include \"chessFrame.h\"\r\n#include <wx\/file.h>\r\n#include <wx\/textfile.h>\r\n#include <wx\/stopwatch.h>\r\n#define TOP true\r\n#define BOTTOM false\r\n\r\n\/\/Do not add custom headers between\r\n\/\/Header Include Start and Header Include End\r\n\/\/wxDev-C++ designer will remove them\r\n\/\/\/\/Header Include Start\r\n\/\/\/\/Header Include End\r\n\r\n\/\/----------------------------------------------------------------------------\r\n\/\/ chessFrame\r\n\/\/----------------------------------------------------------------------------\r\n\/\/Add Custom Events only in the appropriate block.\r\n\/\/Code added in other places will be removed by wxDev-C++\r\n\/\/\/\/Event Table Start\r\nBEGIN_EVENT_TABLE(chessFrame,wxFrame)\r\n\t\/\/\/\/Manual Code Start\r\n\t\/\/EVT_KEY_DOWN(chessFrame::OnKeyDown)\r\n\t\/\/\/\/Manual Code End\r\n\t\r\n\tEVT_CLOSE(chessFrame::OnClose)\r\n\tEVT_TIMER(ID_TIMERUPDATE,chessFrame::timerUpdateTimer)\r\n\tEVT_TIMER(ID_TIMERCLOCK,chessFrame::timerClockTimer)\r\n\tEVT_TIMER(ID_TIMERRELEASEMOUSE,chessFrame::timerReleaseMouseTimer)\r\n\tEVT_TIMER(ID_TIMERDRAW,chessFrame::timerDrawTimer)\r\n\tEVT_BUTTON(ID_BUTTONSWAP,chessFrame::buttonSwapClick)\r\n\tEVT_BUTTON(ID_BUTTONRESET,chessFrame::buttonResetClick)\r\n\tEVT_BUTTON(ID_BUTTONPAUSE,chessFrame::buttonPauseClick)\r\n\tEVT_TEXT_ENTER(ID_EDITTIMEBOTTOM,chessFrame::editTimeBottomEnter)\r\n\tEVT_TEXT(ID_EDITTIMEBOTTOM,chessFrame::editTimeBottomUpdated)\r\n\tEVT_TEXT_ENTER(ID_EDITTIMETOP,chessFrame::editTimeTopEnter)\r\n\tEVT_TEXT(ID_EDITTIMETOP,chessFrame::editTimeTopUpdated)\r\n\tEVT_TOGGLEBUTTON(ID_TOGGLETOP,chessFrame::toggleTopClick)\r\n\tEVT_TOGGLEBUTTON(ID_TOGGLEBOTTOM,chessFrame::toggleBottomClick)\r\n\tEVT_BUTTON(ID_BUTTONLOAD,chessFrame::buttonLoadClick)\r\n\tEVT_BUTTON(ID_BUTTONSAVE,chessFrame::buttonSaveClick)\r\n\tEVT_BUTTON(ID_BUTTONOPTIONS,chessFrame::buttonOptionsClick)\r\n\tEVT_BUTTON(ID_BUTTONTEST,chessFrame::buttonTestClick)\r\n\tEVT_CHECKBOX(ID_CHECKBOXREVERSED,chessFrame::checkBoxReversedClick)\r\n\tEVT_CHECKBOX(ID_CHECKBOXEDITMODE,chessFrame::checkBoxEditModeClick)\r\n\tEVT_BUTTON(ID_BUTTONDISCONNECT,chessFrame::buttonDisconnectClick)\r\n\tEVT_BUTTON(ID_BUTTONSETUP,chessFrame::buttonSetupClick)\r\n\tEVT_TEXT_ENTER(ID_EDITCHAT,chessFrame::editChatEnter)\r\n\tEVT_BUTTON(ID_BUTTONHOST,chessFrame::buttonHostClick)\r\n\tEVT_BUTTON(ID_BUTTONJOIN,chessFrame::buttonJoinClick)\r\nEND_EVENT_TABLE()\r\n\/\/\/\/Event Table End\r\n\r\nchessFrame::chessFrame(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style)\r\n: wxFrame(parent, id, title, position, size, style)\r\n{\r\n\tCreateGUIControls();\r\n\toptions  = new optionsFrame(this);\r\n    board    = new MyGLCanvas(this, panelBoard, ID_PANELBOARD, wxPoint(0,0), panelBoard->GetSize());\r\n    hostjoin = new HostJoinDialog(this);\r\n    \r\n    \/\/ connect the hotkeys\r\n    board->Connect(wxEVT_KEY_DOWN, wxKeyEventHandler(MyGLCanvas::OnKeyDown));\r\n    board->SetFocus();\r\n\r\n    \/\/ set some defaults\r\n    client = NULL;\r\n    server = NULL;\r\n    \r\n    \/\/ set the colors\r\n    board->SetDefaultColors();\r\n    \r\n    \/\/ now load the last user settings.\r\n    LoadSettings();\r\n    \r\n    \/\/ if we're on quiet debug mode, clear the last copy of debug.txt\r\n    if(options->checkBoxDebug->GetValue())\r\n    {\r\n        wxFile f;\r\n        f.Open(\"debug.txt\", wxFile::write);\r\n        f.Close();\r\n    }\r\n    \r\n    \/\/ set the button colors on the options dialog\r\n    options->UpdateColorButtons();\r\n}\r\n\r\nchessFrame::~chessFrame()\r\n{\r\n    Debug(\"~chessFrame()\");\r\n    \/\/options->Hide();\r\n    \/\/options->Destroy();\r\n}\r\n\r\nvoid chessFrame::CreateGUIControls()\r\n{\r\n    loading_chessnuts = true;\r\n    \r\n\t\/\/Do not add custom code between\r\n\t\/\/GUI Items Creation Start and GUI Items Creation End\r\n\t\/\/wxDev-C++ designer will remove them.\r\n\t\/\/Add the custom code before or after the blocks\r\n\t\/\/\/\/GUI Items Creation Start\r\n\r\n\tpanelBackground = new wxPanel(this, ID_PANELBACKGROUND, wxPoint(0,0), wxSize(867,514));\r\n\tpanelBackground->SetBackgroundColour(wxColour(244,244,244));\r\n\tpanelBackground->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tpanelBoard = new wxPanel(panelBackground, ID_PANELBOARD, wxPoint(4,4), wxSize(508,508), wxWANTS_CHARS);\r\n\tpanelBoard->SetBackgroundColour(wxColour(*wxWHITE));\r\n\tpanelBoard->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tmemoLog = new wxTextCtrl(panelBackground, ID_MEMOLOG, wxT(\"\"), wxPoint(516,24), wxSize(245,231), wxTE_READONLY | wxTE_MULTILINE, wxDefaultValidator, wxT(\"memoLog\"));\r\n\tmemoLog->SetMaxLength(0);\r\n\tmemoLog->AppendText(wxT(\"\"));\r\n\tmemoLog->SetFocus();\r\n\tmemoLog->SetInsertionPointEnd();\r\n\tmemoLog->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tbuttonJoin = new wxButton(panelBackground, ID_BUTTONJOIN, wxT(\"Join\"), wxPoint(764,24), wxSize(50,21), 0, wxDefaultValidator, wxT(\"buttonJoin\"));\r\n\tbuttonJoin->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tbuttonHost = new wxButton(panelBackground, ID_BUTTONHOST, wxT(\"Host\"), wxPoint(816,24), wxSize(50,21), 0, wxDefaultValidator, wxT(\"buttonHost\"));\r\n\tbuttonHost->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\teditChat = new wxTextCtrl(panelBackground, ID_EDITCHAT, wxT(\"\"), wxPoint(546,259), wxSize(319,19), wxTE_PROCESS_ENTER, wxDefaultValidator, wxT(\"editChat\"));\r\n\teditChat->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tbuttonSetup = new wxButton(panelBackground, ID_BUTTONSETUP, wxT(\"Set Up\"), wxPoint(819,342), wxSize(47,21), 0, wxDefaultValidator, wxT(\"buttonSetup\"));\r\n\tbuttonSetup->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tWxStaticText3 = new wxStaticText(panelBackground, ID_WXSTATICTEXT3, wxT(\"Chat:\"), wxPoint(517,262), wxDefaultSize, 0, wxT(\"WxStaticText3\"));\r\n\tWxStaticText3->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\twxArrayString arrayStringFor_listPeople;\r\n\tlistPeople = new wxListBox(panelBackground, ID_LISTPEOPLE, wxPoint(765,48), wxSize(100,184), arrayStringFor_listPeople, wxLB_SINGLE);\r\n\tlistPeople->Enable(false);\r\n\tlistPeople->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tbuttonDisconnect = new wxButton(panelBackground, ID_BUTTONDISCONNECT, wxT(\"Disconnect\"), wxPoint(764,235), wxSize(102,21), 0, wxDefaultValidator, wxT(\"buttonDisconnect\"));\r\n\tbuttonDisconnect->Enable(false);\r\n\tbuttonDisconnect->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\twxArrayString arrayStringFor_comboSetup;\r\n\tarrayStringFor_comboSetup.Add(wxT(\"Standard Chess\"));\r\n\tarrayStringFor_comboSetup.Add(wxT(\"Basic Random\"));\r\n\tarrayStringFor_comboSetup.Add(wxT(\"Fischer Random\"));\r\n\tarrayStringFor_comboSetup.Add(wxT(\"Just Pawns\"));\r\n\tarrayStringFor_comboSetup.Add(wxT(\"Clear Board\"));\r\n\tcomboSetup = new wxComboBox(panelBackground, ID_COMBOSETUP, wxT(\"\"), wxPoint(516,342), wxSize(189,21), arrayStringFor_comboSetup, wxCB_READONLY, wxDefaultValidator, wxT(\"comboSetup\"));\r\n\tcomboSetup->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tcheckBoxEditMode = new wxCheckBox(panelBackground, ID_CHECKBOXEDITMODE, wxT(\"Edit Mode\"), wxPoint(584,320), wxSize(65,17), 0, wxDefaultValidator, wxT(\"checkBoxEditMode\"));\r\n\tcheckBoxEditMode->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tcheckBoxReversed = new wxCheckBox(panelBackground, ID_CHECKBOXREVERSED, wxT(\"Reversed\"), wxPoint(516,320), wxSize(63,17), 0, wxDefaultValidator, wxT(\"checkBoxReversed\"));\r\n\tcheckBoxReversed->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\twxArrayString arrayStringFor_comboSetupStyle;\r\n\tarrayStringFor_comboSetupStyle.Add(wxT(\"Normal\"));\r\n\tarrayStringFor_comboSetupStyle.Add(wxT(\"Odd\"));\r\n\tarrayStringFor_comboSetupStyle.Add(wxT(\"Uncorrelated\"));\r\n\tcomboSetupStyle = new wxComboBox(panelBackground, ID_COMBOSETUPSTYLE, wxT(\"\"), wxPoint(709,342), wxSize(107,21), arrayStringFor_comboSetupStyle, 0, wxDefaultValidator, wxT(\"comboSetupStyle\"));\r\n\tcomboSetupStyle->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tbuttonTest = new wxButton(panelBackground, ID_BUTTONTEST, wxT(\"Test\"), wxPoint(404,71), wxSize(44,25), 0, wxDefaultValidator, wxT(\"buttonTest\"));\r\n\tbuttonTest->Show(false);\r\n\tbuttonTest->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tbuttonOptions = new wxButton(panelBackground, ID_BUTTONOPTIONS, wxT(\"Options\"), wxPoint(819,318), wxSize(47,21), 0, wxDefaultValidator, wxT(\"buttonOptions\"));\r\n\tbuttonOptions->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tbuttonSave = new wxButton(panelBackground, ID_BUTTONSAVE, wxT(\"Save\"), wxPoint(740,318), wxSize(37,21), 0, wxDefaultValidator, wxT(\"buttonSave\"));\r\n\tbuttonSave->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tbuttonLoad = new wxButton(panelBackground, ID_BUTTONLOAD, wxT(\"Load\"), wxPoint(779,318), wxSize(38,21), 0, wxDefaultValidator, wxT(\"buttonLoad\"));\r\n\tbuttonLoad->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\ttoggleBottom = new wxToggleButton(panelBackground, ID_TOGGLEBOTTOM, wxT(\"\"), wxPoint(515,461), wxSize(52,52), 0, wxDefaultValidator, wxT(\"toggleBottom\"));\r\n\ttoggleBottom->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\ttoggleTop = new wxToggleButton(panelBackground, ID_TOGGLETOP, wxT(\"\"), wxPoint(515,405), wxSize(52,52), 0, wxDefaultValidator, wxT(\"toggleTop\"));\r\n\ttoggleTop->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\teditTimeTop = new wxTextCtrl(panelBackground, ID_EDITTIMETOP, wxT(\"00:15:00\"), wxPoint(571,406), wxSize(245,51), wxTE_PROCESS_ENTER, wxDefaultValidator, wxT(\"editTimeTop\"));\r\n\teditTimeTop->SetFont(wxFont(37, wxSWISS, wxNORMAL,wxBOLD, false, wxT(\"Courier New\")));\r\n\r\n\teditTimeBottom = new wxTextCtrl(panelBackground, ID_EDITTIMEBOTTOM, wxT(\"00:15:00\"), wxPoint(571,462), wxSize(245,50), wxTE_PROCESS_ENTER, wxDefaultValidator, wxT(\"editTimeBottom\"));\r\n\teditTimeBottom->SetFont(wxFont(37, wxSWISS, wxNORMAL,wxBOLD, false, wxT(\"Courier New\")));\r\n\r\n\tbuttonPause = new wxButton(panelBackground, ID_BUTTONPAUSE, wxT(\"Pause\"), wxPoint(819,446), wxSize(47,20), 0, wxDefaultValidator, wxT(\"buttonPause\"));\r\n\tbuttonPause->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tbuttonReset = new wxButton(panelBackground, ID_BUTTONRESET, wxT(\"Reset\"), wxPoint(819,469), wxSize(47,20), 0, wxDefaultValidator, wxT(\"buttonReset\"));\r\n\tbuttonReset->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tbuttonSwap = new wxButton(panelBackground, ID_BUTTONSWAP, wxT(\"Swap\"), wxPoint(819,492), wxSize(47,20), 0, wxDefaultValidator, wxT(\"buttonSwap\"));\r\n\tbuttonSwap->SetFont(wxFont(8, wxSWISS, wxNORMAL,wxNORMAL, false, wxT(\"Tahoma\")));\r\n\r\n\tWxStaticText2 = new wxStaticText(panelBackground, ID_WXSTATICTEXT2, wxT(\"Chess Clock                                \"), wxPoint(516,383), wxDefaultSize, 0, wxT(\"WxStaticText2\"));\r\n\tWxStaticText2->SetForegroundColour(wxColour(192,192,192));\r\n\tWxStaticText2->SetFont(wxFont(12, wxSWISS, wxNORMAL,wxBOLD, true, wxT(\"Tahoma\")));\r\n\r\n\tWxStaticText6 = new wxStaticText(panelBackground, ID_WXSTATICTEXT6, wxT(\"Board Configuration                  \"), wxPoint(516,296), wxDefaultSize, 0, wxT(\"WxStaticText6\"));\r\n\tWxStaticText6->SetForegroundColour(wxColour(192,192,192));\r\n\tWxStaticText6->SetFont(wxFont(12, wxSWISS, wxNORMAL,wxBOLD, true, wxT(\"Tahoma\")));\r\n\r\n\tWxStaticText1 = new wxStaticText(panelBackground, ID_WXSTATICTEXT1, wxT(\"                              \"), wxPoint(715,296), wxDefaultSize, 0, wxT(\"WxStaticText1\"));\r\n\tWxStaticText1->SetForegroundColour(wxColour(192,192,192));\r\n\tWxStaticText1->SetFont(wxFont(12, wxSWISS, wxNORMAL,wxBOLD, true, wxT(\"Tahoma\")));\r\n\r\n\tWxStaticText4 = new wxStaticText(panelBackground, ID_WXSTATICTEXT4, wxT(\"                              \"), wxPoint(715,383), wxDefaultSize, 0, wxT(\"WxStaticText4\"));\r\n\tWxStaticText4->SetForegroundColour(wxColour(192,192,192));\r\n\tWxStaticText4->SetFont(wxFont(12, wxSWISS, wxNORMAL,wxBOLD, true, wxT(\"Tahoma\")));\r\n\r\n\tWxStaticText5 = new wxStaticText(panelBackground, ID_WXSTATICTEXT5, wxT(\"Network ______________\"), wxPoint(516,1), wxDefaultSize, 0, wxT(\"WxStaticText5\"));\r\n\tWxStaticText5->SetForegroundColour(wxColour(192,192,192));\r\n\tWxStaticText5->SetFont(wxFont(12, wxSWISS, wxNORMAL,wxBOLD, true, wxT(\"Tahoma\")));\r\n\r\n\tWxStaticText7 = new wxStaticText(panelBackground, ID_WXSTATICTEXT7, wxT(\"                              \"), wxPoint(715,1), wxDefaultSize, 0, wxT(\"WxStaticText7\"));\r\n\tWxStaticText7->SetForegroundColour(wxColour(192,192,192));\r\n\tWxStaticText7->SetFont(wxFont(12, wxSWISS, wxNORMAL,wxBOLD, true, wxT(\"Tahoma\")));\r\n\r\n\tdialogSave =  new wxFileDialog(this, wxT(\"Choose a file\"), wxT(\"\"), wxT(\"\"), wxT(\"*.*\"), wxSAVE);\r\n\r\n\ttimerDraw = new wxTimer();\r\n\ttimerDraw->SetOwner(this, ID_TIMERDRAW);\r\n\ttimerDraw->Start(10);\r\n\r\n\tdialogOpen =  new wxFileDialog(this, wxT(\"Choose a file\"), wxT(\"\"), wxT(\"\"), wxT(\"*.*\"), wxOPEN);\r\n\r\n\ttimerReleaseMouse = new wxTimer();\r\n\ttimerReleaseMouse->SetOwner(this, ID_TIMERRELEASEMOUSE);\r\n\r\n\ttimerClock = new wxTimer();\r\n\ttimerClock->SetOwner(this, ID_TIMERCLOCK);\r\n\r\n\ttimerUpdate = new wxTimer();\r\n\ttimerUpdate->SetOwner(this, ID_TIMERUPDATE);\r\n\r\n\tSetTitle(wxT(\"chessnuts\"));\r\n\tSetIcon(wxNullIcon);\r\n\tSetSize(-389,-4,875,548);\r\n\tCenter();\r\n\t\r\n\t\/\/\/\/GUI Items Creation End\r\n\r\n\r\n    \/\/ my setup stuff\r\n    comboSetup->SetSelection(0);\r\n    comboSetupStyle->SetSelection(0);\r\n\r\n     \/\/ seed the random number with the time in seconds\r\n    time_t seconds;\r\n    time(&seconds);\r\n    srand((unsigned int) seconds);\r\n    \r\n    clockblocker_top = false;\r\n    clockblocker_bottom = false;\r\n    \r\n    ms_top    = StringToMilli(editTimeTop->GetValue());\r\n    ms_bottom = StringToMilli(editTimeTop->GetValue());\r\n    ms_top_start    = ms_top;\r\n    ms_bottom_start = ms_bottom;\r\n    \r\n    loading_chessnuts = false;\r\n}\r\n\r\nvoid chessFrame::SaveSettings()\r\n{\r\n    wxFile f;\r\n    if(f.Open(\"settings\", wxFile::write))\r\n    {\r\n        f.Write(hostjoin->editName->GetValue().Strip() + \"\\n\");\r\n        f.Write(hostjoin->editAddress  ->GetValue().Strip() + \"\\n\");\r\n        f.Write(hostjoin->editPort->GetValue().Strip() + \"\\n\");\r\n        s.sprintf(\"%i\\n%i\\n%i\\n%i\\n\", \r\n                    checkBoxEditMode->GetValue(),\r\n                    checkBoxReversed->GetValue(),\r\n                    comboSetupStyle->GetSelection(),\r\n                    comboSetup->GetSelection()); \r\n        f.Write(s);\r\n        f.Write(board->AssembleBoardString()+\"\\n\");\r\n        f.Write(board->PackHighlights()+\"\\n\");\r\n        \r\n        s.sprintf(\"%i\\n%i\\n%i\\n%i\\n%i\\n%i\\n\",\r\n                    options->checkBoxDebug->GetValue(),\r\n                    options->checkBoxHands->GetValue(),\r\n                    options->checkBoxRefreshEnabled->GetValue(),\r\n                    options->spinMax->GetValue(),\r\n                    options->spinSpeed->GetValue(),\r\n                    options->checkBoxNewMethod->GetValue());\r\n        f.Write(s);\r\n\r\n        s.sprintf(\"%ld\\n%ld\\n%ld\\n%ld\\n\",\r\n                    ms_top,\r\n                    ms_top_start,\r\n                    ms_bottom,\r\n                    ms_bottom_start);\r\n        f.Write(s);\r\n        \r\n        s.sprintf(\"%i\\n\", options->sliderSmoothing->GetValue());\r\n        f.Write(s);\r\n\r\n        f.Write(board->color_white_square.GetAsString(wxC2S_CSS_SYNTAX) + \"\\n\");\r\n        f.Write(board->color_black_square.GetAsString(wxC2S_CSS_SYNTAX) + \"\\n\");\r\n        f.Write(board->color_white_piece .GetAsString(wxC2S_CSS_SYNTAX) + \"\\n\");\r\n        f.Write(board->color_black_piece .GetAsString(wxC2S_CSS_SYNTAX) + \"\\n\");\r\n        f.Write(board->color_background  .GetAsString(wxC2S_CSS_SYNTAX) + \"\\n\");\r\n        f.Write(board->color_border      .GetAsString(wxC2S_CSS_SYNTAX) + \"\\n\");\r\n\r\n        f.Write(board->highlight_pickup ->color.GetAsString(wxC2S_CSS_SYNTAX) + \"\\n\");\r\n        f.Write(board->highlight_take   ->color.GetAsString(wxC2S_CSS_SYNTAX) + \"\\n\");\r\n        f.Write(board->highlight_putdown->color.GetAsString(wxC2S_CSS_SYNTAX) + \"\\n\");\r\n        \r\n        s.sprintf(\"%i\\n\", options->checkBoxLoudDebug->GetValue()); f.Write(s);\r\n\r\n        f.Close();\r\n    } else {Log(\"Could not save to settings file.\");}\r\n}\r\n\r\nvoid chessFrame::LoadSettings()\r\n{\r\n    if(!wxFile::Exists(\"settings\")) return;\r\n    \r\n    long n;\r\n    size_t size;\r\n    \r\n    wxTextFile f;\r\n    if(f.Open(\"settings\"))\r\n    {\r\n        size = f.GetLineCount();\r\n        \r\n        if(size > 0) hostjoin->editName  -> SetValue(f.GetLine(0).Strip());\r\n        if(size > 1) hostjoin->editAddress    -> SetValue(f.GetLine(1).Strip());\r\n        if(size > 2) hostjoin->editPort  -> SetValue(f.GetLine(2).Strip());\r\n        if(size > 3) {f.GetLine(3).ToLong(&n); checkBoxEditMode->SetValue(n);}\r\n        if(size > 4) {f.GetLine(4).ToLong(&n); checkBoxReversed->SetValue(n);}\r\n        if(size > 5) {f.GetLine(5).ToLong(&n); comboSetupStyle->SetSelection((int)n);}\r\n        if(size > 6) {f.GetLine(6).ToLong(&n); comboSetup     ->SetSelection((int)n);}\r\n        if(size > 7)\r\n        {\r\n            s = f.GetLine(7).Strip();\r\n            board->UnpackBoardString(s);\r\n        }\r\n        if(size > 8)\r\n        {\r\n            s = f.GetLine(8).Strip();\r\n            board->UnpackHighlights(s);\r\n        }\r\n        \r\n        \r\n        if(size > 9) {f.GetLine(9).ToLong(&n);  options->checkBoxDebug->SetValue(n);}\r\n        if(size > 10){f.GetLine(10).ToLong(&n); options->checkBoxHands->SetValue(n);}\r\n        if(size > 11){f.GetLine(11).ToLong(&n); options->checkBoxRefreshEnabled->SetValue(n);}\r\n        if(size > 12){f.GetLine(12).ToLong(&n); options->spinMax->SetValue((int)n);}\r\n        if(size > 13){f.GetLine(13).ToLong(&n); options->spinSpeed->SetValue((int)n);}\r\n        if(size > 14){f.GetLine(14).ToLong(&n); options->checkBoxNewMethod->SetValue((int)n);}\r\n        \r\n        if(size > 15){f.GetLine(15).ToLong(&n); ms_top = n;}\r\n        if(size > 16){f.GetLine(16).ToLong(&n); ms_top_start = n;}\r\n        if(size > 17){f.GetLine(17).ToLong(&n); ms_bottom = n;}\r\n        if(size > 18){f.GetLine(18).ToLong(&n); ms_bottom_start = n;}\r\n        SetClocks();\r\n        \r\n        if(size > 19){f.GetLine(19).ToLong(&n); options->sliderSmoothing->SetValue((int)n); wxScrollEvent e; options->sliderSmoothingScroll(e);}\r\n        \r\n        if(size > 20){board->color_white_square .Set(f.GetLine(20).Strip());}\r\n        if(size > 21){board->color_black_square .Set(f.GetLine(21).Strip());}\r\n        if(size > 22){board->color_white_piece  .Set(f.GetLine(22).Strip());}\r\n        if(size > 23){board->color_black_piece  .Set(f.GetLine(23).Strip());}\r\n        if(size > 24){board->color_background   .Set(f.GetLine(24).Strip());}\r\n        if(size > 25){board->color_border       .Set(f.GetLine(25).Strip());}\r\n\r\n        if(size > 26){board->highlight_pickup ->color.Set(f.GetLine(26).Strip());}\r\n        if(size > 27){board->highlight_take   ->color.Set(f.GetLine(27).Strip());}\r\n        if(size > 28){board->highlight_putdown->color.Set(f.GetLine(28).Strip());}\r\n\r\n        if(size > 29){f.GetLine(29).ToLong(&n); options->checkBoxLoudDebug->SetValue(n);} \r\n\r\n        f.Close();\r\n    }\r\n    else Log(\"Could not open settings file.\");\r\n}\r\n\r\n\r\n\r\nvoid chessFrame::OnClose(wxCloseEvent& event)\r\n{\r\n    Debug(\"chessFrame::OnClose())\");\r\n    \r\n    SaveSettings();\r\n    Debug(\"settings saved\");\r\n    \r\n    \/\/delete board;\r\n    \/\/board = NULL;\r\n\r\n    if(client)\r\n    {\r\n        wxCommandEvent e;\r\n        buttonDisconnectClick(e);\r\n    }\r\n    if(server)\r\n    {\r\n        ShutdownServer();\r\n    }\r\n    Destroy();\r\n}\r\n\r\nvoid chessFrame::Log(wxString line)\r\n{\r\n    this->memoLog->AppendText(\"*** \"+line+\"\\n\");\r\n    if(options->checkBoxDebug->GetValue())\r\n    {\r\n        \/\/ also write the output to a debug.txt\r\n        wxFile f;\r\n        f.Open(\"debug.txt\", wxFile::write_append);\r\n        f.Write(\"-------\\n\"+line+\"\\n\");\r\n        f.Close();\r\n    }\r\n}\r\n\r\nvoid chessFrame::Debug(wxString line)\r\n{\r\n    if(options->checkBoxDebug->GetValue())\r\n    {\r\n        \/\/ if we're in loud mode, show it in the log too\r\n        if(options->checkBoxLoudDebug->GetValue()) \r\n            this->memoLog->AppendText(\"-------\\n\"+line+\"\\n\");\r\n        \r\n        \/\/ also write the output to a debug.txt\r\n        wxFile f;\r\n        f.Open(\"debug.txt\", wxFile::write_append);\r\n        f.Write(\"-------\\n\"+line+\"\\n\");\r\n        f.Close();\r\n    }\r\n}\r\n\r\n\r\nvoid chessFrame::buttonJoinClick(wxCommandEvent& event)\r\n{\r\n    \/\/ Pop up the join dialog, and only join if the client clicks \"okay\"\r\n    hostjoin->editAddress->Enable(); \/\/ we need all the fields for joining!\r\n    if(!hostjoin->ShowModal()) return;\r\n    \r\n    if(client != NULL)\r\n    {\r\n        Debug(\"client not NULL, deleting.\");\r\n        delete client;\r\n        client = NULL;\r\n    }\r\n    client = new MyClient(this);\r\n    \r\n    DisableConnect();\r\n    \r\n    Log(\"Trying to connect to \"+hostjoin->editAddress->GetValue()+\"...\");\r\n\tclient->Connect(hostjoin->editAddress->GetValue(), hostjoin->editPort->GetValue(), \"chessticle\");\r\n\r\n    if(client->connection == NULL) \r\n    {\r\n        Log(\"Connection FAILED. FAILURE!\");\r\n        delete client;\r\n        client = NULL;\r\n        EnableConnect();\r\n    }\r\n    else\r\n    {\r\n        Log(\"Success!\");\r\n        \r\n        \/\/ Send your name, and the server should send back the user list and board\r\n        client->connection->Poke(\"name\", (wxChar *)hostjoin->editName->GetValue().GetData());\r\n    }\r\n}\r\n\r\nvoid chessFrame::buttonHostClick(wxCommandEvent& event)\r\n{\r\n    \/\/ get the hosting info (address is not necessary for hosting)\r\n    hostjoin->editAddress->Disable();\r\n    if(!hostjoin->ShowModal()) return;\r\n    \r\n    \/\/ delete the old server object and create a new one\r\n    if(server != NULL)\r\n    {\r\n        Debug(\"Server object already exists. Deleting.\");\r\n        delete server;\r\n        server = NULL;\r\n    }\r\n    server = new MyServer(this);\r\n    \r\n    \/\/ actually start hosting!\r\n    server->Create(hostjoin->editPort->GetValue());\r\n    Log(\"Server started on TCP port \"+hostjoin->editPort->GetValue());\r\n\r\n    \/\/ add the first element of the people list (you)\r\n    listPeople->Clear();\r\n    listPeople->Append(hostjoin->editName->GetValue(), (wxClientData *)new MyClientData(this, 0));\r\n\r\n    \/\/ dim\/enable the appropriate buttons\r\n    DisableConnect();\r\n}\r\n\r\nvoid chessFrame::DisableConnect()\r\n{\r\n    buttonJoin->Disable();\r\n    buttonHost->Disable();\r\n    hostjoin->editAddress->Disable();\r\n    hostjoin->editPort->Disable();\r\n    listPeople->Enable();\r\n    buttonDisconnect->Enable();\r\n    \r\n    if(client) \r\n    {\r\n        options->spinSpeed->Disable();\r\n        options->spinMax->Disable();\r\n        options->checkBoxHands->Disable();\r\n        options->checkBoxRefreshEnabled->Disable();\r\n        options->checkBoxNewMethod->Disable();\r\n    }\r\n}\r\n\r\nvoid chessFrame::EnableConnect()\r\n{\r\n    client = NULL;\r\n    server = NULL;\r\n    \r\n    options->spinMax->Enable();\r\n    options->spinSpeed->Enable();\r\n    options->checkBoxHands->Enable();\r\n    options->checkBoxRefreshEnabled->Enable();\r\n    options->checkBoxNewMethod->Enable();\r\n    \r\n    buttonJoin->Enable();\r\n    buttonHost->Enable();\r\n    hostjoin->editAddress->Enable();\r\n    hostjoin->editPort->Enable();\r\n    listPeople->Disable();\r\n    buttonDisconnect->Disable();\r\n}\r\n\r\nvoid chessFrame::editChatEnter(wxCommandEvent& event)\r\n{\r\n    s = \"<\"+hostjoin->editName->GetValue()+\"> \"+editChat->GetValue();\r\n\r\n    if(client != NULL)\r\n    {\r\n        client->connection->Poke(\"chat\", (wxChar *)&s[0]);\r\n    }\r\n    if(server != NULL)\r\n    {\r\n        memoLog->AppendText(s+\"\\n\");\r\n        server->PokeEveryone(\"chat\", (wxChar *)&s[0]);\r\n    }\r\n    \r\n\teditChat->Clear();\r\n}\r\n\r\nvoid chessFrame::buttonSetupClick(wxCommandEvent& event)\r\n{\r\n\tboard->SetupBoard(comboSetup->GetSelection(), comboSetupStyle->GetSelection()); \/\/ this does a draw and an update\r\n}\r\n\r\nvoid chessFrame::UpdateErrbody()\r\n{\r\n    \/\/ update the server\/clients\r\n    if(server != NULL) server->UpdateErrbody();\r\n    if(client != NULL) client->UpdateErrbody();\r\n}\r\n\r\nvoid chessFrame::timerUpdateTimer(wxTimerEvent& event)\r\n{\r\n    \/\/ send the coordinates of the mouse piece\r\n    if(server) server->SendMouse();\r\n    if(client) client->SendMouse();\r\n}\r\n\r\nvoid chessFrame::ClearClientList()\r\n{\r\n    Debug(\"ClearClientList()\");\r\n    listPeople->Clear();\r\n}\r\n\r\nvoid chessFrame::buttonDisconnectClick(wxCommandEvent& event)\r\n{\r\n    \/\/ if you're a client, just disconnect!\r\n    if(client)\r\n    {\r\n        Debug(\"Disconnecting client, deleting resources...\");\r\n        delete client; \/\/ this disconnects too\r\n        client = NULL;\r\n        \r\n        \/\/ now we have to delete all the entries in the user list\r\n        ClearClientList();\r\n        \r\n        EnableConnect();\r\n    }\r\n    \r\n    \/\/ if you're a server, disconnect the selected client or shut it down\r\n    else if(server != NULL)\r\n    {\r\n        \/\/ get the selection\r\n        int n = listPeople->GetSelection();\r\n        \r\n        \/\/ if a client is selected, disconnect them\r\n        if(n > 0) server->Disconnect((unsigned int)n);\r\n        \r\n        \/\/ otherwise, shut down the server!\r\n        else\r\n        {\r\n            ShutdownServer();\r\n        }\r\n    }\r\n}\r\n\r\nvoid chessFrame::ToggleEditMode()\r\n{\r\n    \/\/ if we're in edit mode, the draw will take care of the clearing\/adding pieces\r\n    \/\/ if we're leaving edit mode, we should clear the border\r\n    if(!checkBoxEditMode->GetValue())\r\n    {\r\n        for(int n=0; n<=9; n++)\r\n        {\r\n            board->pieces[n][0] = NULL;\r\n            board->pieces[n][9] = NULL;\r\n        }   \r\n    }\r\n\r\n    \/\/board->Draw();\r\n}\r\n\r\nvoid chessFrame::checkBoxEditModeClick(wxCommandEvent& event)\r\n{\r\n    \/\/ enable or disable edit mode\r\n    ToggleEditMode();\r\n    \r\n    \/\/ now tell everyone to go to edit mode\r\n    if(client != NULL) client->connection->SendErrthing();\r\n    if(server != NULL) server->UpdateErrbody();\r\n}\r\n\r\nvoid chessFrame::timerReleaseMouseTimer(wxTimerEvent& event)\r\n{\r\n\t\/\/ This timer releases the mouse from being frozen after a half second,\r\n\t\/\/ in case you want to click the same square without moving first.\r\n\tboard->last_clicked_square_x = -1;\r\n\tboard->last_clicked_square_y = -1;\r\n}\r\n\r\nvoid chessFrame::checkBoxReversedClick(wxCommandEvent& event)\r\n{\r\n\tboard->Reverse();\r\n\t\r\n\t\/\/ also swap the timers\r\n    SwapClocks();\r\n}\r\n\r\n\r\nvoid chessFrame::buttonTestClick(wxCommandEvent& event)\r\n{\r\n    \r\n}\r\n\r\n\r\n\r\nvoid chessFrame::ShutdownServer()\r\n{\r\n    if(server)\r\n    {\r\n        \/\/ disconnect everything and clean up\r\n        server->PokeEveryone(\"chat\", \"Server is shutting down. Seeya!\");\r\n\r\n        \/\/ loop over everyone and disconnect them\r\n        for(unsigned int m=listPeople->GetCount()-1; m>=1; m--) server->Disconnect(m);\r\n\r\n        Log(\"Shutting down server...\");\r\n\r\n        delete server;\r\n        server = NULL;\r\n\r\n        \/\/ clear the client list\r\n        listPeople->Clear();\r\n\r\n        EnableConnect();\r\n    }\r\n}\r\n\r\nvoid chessFrame::buttonOptionsClick(wxCommandEvent& event)\r\n{\r\n\toptions->Show();\r\n\toptions->Raise();\r\n}\r\n\r\nvoid chessFrame::editUserUpdated(wxCommandEvent& event)\r\n{\r\n\tif(client) client->connection->Poke(\"=\", (wxChar *)event.GetString().GetData());\r\n\tif(server) \r\n    {\r\n        s = \"=\";\r\n        server->PokeEveryone(s+(char)0, (wxChar *)event.GetString().GetData());\r\n        listPeople->SetString(0, event.GetString());\r\n    }\r\n}\r\n\r\n\r\nvoid chessFrame::timerDrawTimer(wxTimerEvent& event)\r\n{\r\n    \/\/ First thing we do is update the interpolation if necessary\r\n    double time;\r\n\r\n    \/\/ update all the floater coordinates\r\n\t\/\/ the current coordinate should be (time\/transit time)*(target-start)+start\r\n\tMyClientData *c;\r\n    for(unsigned int n=0; n < listPeople->GetCount(); n++)\r\n    {\r\n        \/\/ our floater will always be NULL\r\n        c = (MyClientData *)listPeople->GetClientData(n);\r\n\r\n        \/\/ don't do any processing\/drawing if the floater is nothing.\r\n        if(c->floater) \r\n        {\r\n            \/\/ get the elapsed time for this floater\r\n            time = (double)c->timeypoo.Time();\r\n    \r\n            \/\/ get the current coordinates\r\n            c->x = c->x_start + (c->x_target - c->x_start)*time\/(options->floaty_smooth*(double)options->spinSpeed->GetValue());\r\n            c->y = c->y_start + (c->y_target - c->y_start)*time\/(options->floaty_smooth*(double)options->spinSpeed->GetValue());\r\n    \r\n            \/\/ if the time is greater than the transit time, then\r\n            \/\/ set it to the the final position, and stop the timer\r\n            if(time >= (double)options->spinSpeed->GetValue()\/0.8)\r\n            {\r\n                c->x = c->x_target;\r\n                c->y = c->y_target;\r\n            }\r\n        }\r\n    }\r\n\r\n    \r\n    \/\/ now actually draw the board\r\n    board->Draw();\r\n}\r\n\r\nvoid chessFrame::buttonSaveClick(wxCommandEvent& event)\r\n{\r\n    wxFile f;\r\n    dialogSave->SetWildcard(\"nuts files (*.nuts)|*.nuts\");\r\n\tif(dialogSave->ShowModal() == wxID_OK)\r\n\t{\r\n        Debug(\"Saving board configuration to '\"+dialogSave->GetPath()+\"'\");\r\n        \r\n        \/\/ open the file\r\n        if(f.Open(dialogSave->GetPath(), wxFile::write))\r\n        {\r\n            f.Write(board->AssembleBoardString()+\"\\n\");\r\n            f.Write(board->PackHighlights());\r\n            \r\n            if(checkBoxReversed->GetValue()) s.sprintf(\"\\n%ld\\n%ld\", ms_bottom, ms_top);\r\n            else                             s.sprintf(\"\\n%ld\\n%ld\", ms_top, ms_bottom);\r\n            f.Write(s);\r\n            \r\n            f.Close();\r\n        }\r\n        else Log(\"Could not open file for writing.\");\r\n    }\r\n}\r\n\r\nvoid chessFrame::buttonLoadClick(wxCommandEvent& event)\r\n{\r\n\twxTextFile f;\r\n\tdialogOpen->SetWildcard(\"nuts files (*.nuts)|*.nuts\");\r\n\tif(dialogOpen->ShowModal() == wxID_OK)\r\n\t{\r\n        Debug(\"Loading board configuration from '\"+dialogOpen->GetPath()+\"'\");\r\n        \r\n        \/\/ open the file\r\n        if(f.Open(dialogOpen->GetPath()) && f.GetLineCount() >= 2)\r\n        {\r\n            board->UnpackBoardString(f.GetLine(0).Strip());\r\n            board->UnpackHighlights(f.GetLine(1).Strip());\r\n            \r\n            if(checkBoxReversed->GetValue())\r\n            {\r\n                f.GetLine(2).Strip().ToLong(&ms_bottom);\r\n                f.GetLine(3).Strip().ToLong(&ms_top);\r\n            }\r\n            else\r\n            {\r\n                f.GetLine(2).Strip().ToLong(&ms_top);\r\n                f.GetLine(3).Strip().ToLong(&ms_bottom);\r\n            }\r\n            Pause();\r\n            SetClocks();\r\n            \r\n            board->UpdateErrbody();\r\n            f.Close();\r\n        }\r\n        else Log(\"Could not open file for reading.\");\r\n    }\r\n}\r\n\r\nvoid chessFrame::toggleBottomClick(wxCommandEvent& event)\r\n{\r\n    \/\/ make the GUI look right\r\n    toggleBottom->SetValue(true);\r\n    toggleTop->SetValue(false);\r\n    \r\n    \/\/ set the starting point so we can keep track of elapsed time\r\n\tms_top_last = ms_top;\r\n\t\r\n\tSendToggles();\r\n\t\r\n\t\/\/ start a stopwatch at zero\r\n\ttimeypoo.Start(0);\r\n\ttimerClock->Start(100);\r\n}\r\nvoid chessFrame::toggleTopClick(wxCommandEvent& event)\r\n{\r\n\t\/\/ make the GUI look right\r\n    toggleBottom->SetValue(false);\r\n    toggleTop->SetValue(true);\r\n    \r\n    \/\/ set the starting point so we can keep track of elapsed time\r\n\tms_bottom_last = ms_bottom;\r\n\r\n    SendToggles();\r\n    \r\n\t\/\/ start a stopwatch (at zero)\r\n\ttimeypoo.Start(0);\r\n    timerClock->Start(100);\r\n}\r\n\r\nlong chessFrame::StringToMilli(wxString time)\r\n{\r\n    long t;\r\n    long ms;\r\n    int sign = 1;\r\n    \r\n    \/\/ first split it by \":\"'s\r\n    wxArrayString a = SplitString(time, \":\");\r\n    \r\n    \/\/ if we only get one element, try splitting by \".\"\r\n    if(a.GetCount() == 1) \r\n    {\r\n        a = SplitString(time, \".\");\r\n        if(a.GetCount() > 1) sign = -1;\r\n    }\r\n    \r\n    if(a.GetCount() == 1) \/\/ minutes only\r\n    {\r\n        \/\/ if it's a bad number, quit out\r\n        if(a[0] == \"\")       a[0] = \"0\";\r\n        if(!a[0].ToLong(&t)) return 0;\r\n        \/\/ return the tenths based on minutes\r\n        return sign*t*60*1000;\r\n    }\r\n    else if(a.GetCount() == 2) \/\/ minutes:seconds\r\n    {\r\n        if(a[0] == \"\")       a[0] = \"0\";\r\n        if(!a[0].ToLong(&t)) return 0;\r\n        ms = t*60*1000;\r\n        \r\n        if(a[1] == \"\")       a[1] = \"0\";\r\n        if(!a[1].ToLong(&t)) return 0;\r\n        return sign*(ms+t*1000);\r\n    }\r\n    else if(a.GetCount() == 3) \/\/ hours:minutes:seconds\r\n    {\r\n        if(a[0] == \"\")       a[0] = \"0\";\r\n        if(!a[0].ToLong(&t)) return 0;\r\n        ms = t*60*60*1000;\r\n        \r\n        if(a[1] == \"\")       a[1] = \"0\";\r\n        if(!a[1].ToLong(&t)) return 0;\r\n        ms += t*60*1000;\r\n        \r\n        if(a[2] == \"\")       a[2] = \"0\";\r\n        if(!a[2].ToLong(&t)) return 0;\r\n        return sign*(ms + t*1000);\r\n    }\r\n    \r\n    \/\/ no good format\r\n    return 0;\r\n}\r\n\r\nwxString chessFrame::MilliToString(long ms)\r\n{\r\n    int hours   = ms \/ (1000*60*60);\r\n    int minutes = (ms-hours*1000*60*60) \/ (1000*60);\r\n    int seconds = (ms-hours*1000*60*60-minutes*1000*60) \/ 1000;\r\n    \r\n    if(ms > 0) s.sprintf(\"%02i:%02i:%02i\", hours, minutes, seconds);\r\n    else       s.sprintf(\"%02i.%02i.%02i\", -hours, -minutes, -seconds);\r\n    \r\n    return s;\r\n}\r\n\r\nvoid chessFrame::editTimeBottomUpdated(wxCommandEvent& event)\r\n{\r\n\tif(loading_chessnuts) return;\r\n    \r\n    \/\/ tell everyone what we're doing\r\n    if(clockblocker_bottom) clockblocker_bottom = false;\r\n    else\r\n    {\r\n        \/\/ if clockblocker is true, it means the program is setting the timer, not us\r\n        \r\n        \/\/ convert the string into milliseconds\r\n        ms_bottom = StringToMilli(editTimeBottom->GetValue());\r\n        ms_bottom_start = ms_bottom;\r\n\r\n        \/\/ make sure the timer stops since we're editing stuff\r\n        timerClock->Stop();\r\n        Poke(\"ClockStop\", \"\");\r\n        if(checkBoxReversed->GetValue()) Poke(\"ClockTop\",    (wxChar *)editTimeBottom->GetValue().GetData());\r\n        else                             Poke(\"ClockBottom\", (wxChar *)editTimeBottom->GetValue().GetData());\r\n    }\r\n    \r\n}\r\n\r\nvoid chessFrame::editTimeTopUpdated(wxCommandEvent& event)\r\n{\r\n\tif(loading_chessnuts) return;\r\n\r\n    \/\/ tell everyone what we're doing\r\n    if(clockblocker_top) clockblocker_top = false;\r\n    else\r\n    {\r\n        \/\/ convert the string into ms\r\n        ms_top = StringToMilli(editTimeTop->GetValue());\r\n        ms_top_start = ms_top;\r\n\r\n        \/\/ make sure the timer stops since we're editing stuff\r\n        timerClock->Stop();\r\n        Poke(\"ClockStop\", \"\");\r\n        if(checkBoxReversed->GetValue()) Poke(\"ClockBottom\", (wxChar *)editTimeTop->GetValue().GetData());\r\n        else                             Poke(\"ClockTop\",    (wxChar *)editTimeTop->GetValue().GetData());\r\n    }\r\n}\r\n\r\nvoid chessFrame::Poke(const wxString &item, wxChar *data, int size, wxIPCFormat format)\r\n{\r\n    Debug(\"chessFrame::Poke()\");\r\n    if     (client) client->connection->Poke(item, data, size, format);\r\n    else if(server) server->    PokeEveryone(item, data, size, format);\r\n}\r\n\r\nvoid chessFrame::timerClockTimer(wxTimerEvent& event)\r\n{\r\n\t\/\/ get the current timer in ms\r\n\tlong t = timeypoo.Time();\r\n\t\r\n\t\/\/ subtract this value from the appropriate ms\r\n\tif(toggleBottom->GetValue())   ms_top = ms_top_last - t;\r\n    else if(toggleTop->GetValue()) ms_bottom = ms_bottom_last - t;\r\n    else                           Log(\"Timer shouldn't be running, but it is!\");\r\n\r\n    SetClocks();\r\n}\r\n\r\nvoid chessFrame::Pause()\r\n{\r\n    \/\/ unpush the buttons\r\n    toggleTop->SetValue(false);\r\n    toggleBottom->SetValue(false);\r\n\r\n    \/\/ stop the clock\r\n\ttimerClock->Stop();\r\n}\r\n\r\nvoid chessFrame::SetClocks()\r\n{\r\n    \/\/ update the GUI\r\n    clockblocker_top = true;\r\n    clockblocker_bottom = true;\r\n    editTimeTop   ->SetValue(MilliToString(ms_top));\r\n    editTimeBottom->SetValue(MilliToString(ms_bottom));\r\n    \r\n    \/\/ update colors depending on +\/-\r\n    wxColour white(255,255,255);\r\n    wxColour red  (255,200,200);\r\n    \r\n    if(ms_bottom > 0) editTimeBottom->SetBackgroundColour(white);\r\n    else              editTimeBottom->SetBackgroundColour(red);\r\n    if(ms_top    > 0) editTimeTop   ->SetBackgroundColour(white);\r\n    else              editTimeTop   ->SetBackgroundColour(red);      \r\n}\r\n\r\nvoid chessFrame::SendTimes()\r\n{\r\n    \/\/ send times\r\n\tlong times[2];\r\n\tif(checkBoxReversed->GetValue())\r\n    {\r\n        times[1] = ms_top;\r\n\t    times[0] = ms_bottom;\r\n    }\r\n    else\r\n    {\r\n        times[0] = ms_top;\r\n\t    times[1] = ms_bottom;\r\n    }\r\n    Poke(\"Clocks\", (char *)times, 2*sizeof(long));\r\n}\r\n\r\nvoid chessFrame::SendToggles()\r\n{\r\n    long times[2];\r\n    \r\n    \/\/ send a toggle event, based on which toggle is pressed\r\n    if(toggleBottom->GetValue())\r\n    {\r\n        if(checkBoxReversed->GetValue())\r\n        {\r\n            times[1] = ms_top;\r\n    \t    times[0] = ms_bottom;\r\n            Poke(\"ToggleTop\",    (wxChar *)times, sizeof(long)*2);\r\n        }\r\n        else\r\n        {\r\n            times[0] = ms_top;\r\n    \t    times[1] = ms_bottom;\r\n            Poke(\"ToggleBottom\", (wxChar *)times, sizeof(long)*2);\r\n        }\r\n    }\r\n    else if(toggleTop->GetValue())\r\n    {\r\n    \r\n    \tif(checkBoxReversed->GetValue())\r\n        {\r\n            times[1] = ms_top;\r\n    \t    times[0] = ms_bottom;\r\n            Poke(\"ToggleBottom\", (wxChar *)times, sizeof(long)*2);\r\n        }\r\n        else\r\n        {\r\n            times[0] = ms_top;\r\n    \t    times[1] = ms_bottom;\r\n            Poke(\"ToggleTop\", (wxChar *)times, sizeof(long)*2);\r\n        }\r\n    }\r\n    else \/\/ no toggles are pressed!\r\n    {\r\n        \/\/ make sure we're paused\r\n        Pause();\r\n        \r\n        \/\/ send a clock stop so the buttons are unpressed and the clock is stopped\r\n        Poke(\"ClockStop\", \"\");\r\n        \r\n        \/\/ send the times\r\n        SendTimes();\r\n    }\r\n}\r\n\r\nvoid chessFrame::buttonPauseClick(wxCommandEvent& event)\r\n{\r\n    Pause();\r\n    Poke(\"ClockStop\", \"\");\r\n    SetClocks();\r\n    SendTimes();\r\n}\r\n\r\nvoid chessFrame::buttonResetClick(wxCommandEvent& event)\r\n{\r\n\tPause();\r\n\tPoke(\"ClockStop\", \"\");\r\n\t\r\n\t\/\/ se the times to the last manually entered values\r\n\tms_top    = ms_top_start;\r\n\tms_bottom = ms_bottom_start;\r\n\t\r\n\t\/\/ update the GUI\r\n    SetClocks();\r\n    SendTimes();\r\n}\r\n\r\nvoid chessFrame::SwapClocks()\r\n{\r\n    s = editTimeBottom->GetValue();\r\n    long ms       = ms_bottom;\r\n    long ms_last  = ms_bottom_last;\r\n    long ms_start = ms_bottom_start;\r\n    bool toggle   = toggleBottom->GetValue();\r\n\r\n    ms_bottom       = ms_top;\r\n    ms_bottom_last  = ms_top_last;\r\n    ms_bottom_start = ms_top_start;\r\n    toggleBottom->SetValue(toggleTop->GetValue());\r\n    clockblocker_bottom = true;\r\n    editTimeBottom->SetValue(editTimeTop->GetValue());\r\n\r\n    ms_top       = ms;\r\n    ms_top_last  = ms_last;\r\n    ms_top_start = ms_start;\r\n    toggleTop->SetValue(toggle);\r\n    clockblocker_top = true;\r\n    editTimeTop->SetValue(s);\r\n}\r\n\r\nvoid chessFrame::buttonSwapClick(wxCommandEvent& event)\r\n{\r\n\tSwapClocks();\r\n\t\r\n    \/\/ also update everyone\r\n\tSendToggles();\r\n}\r\n\r\nvoid chessFrame::editTimeTopEnter(wxCommandEvent& event)\r\n{\r\n    \/\/ convert the string into ms\r\n    ms_top = StringToMilli(editTimeTop->GetValue());\r\n    ms_top_start = ms_top;\r\n\r\n    wxCommandEvent e;\r\n\tbuttonPauseClick(e);\r\n}\r\n\r\nvoid chessFrame::editTimeBottomEnter(wxCommandEvent& event)\r\n{\r\n    \/\/ convert the string into milliseconds\r\n    ms_bottom = StringToMilli(editTimeBottom->GetValue());\r\n    ms_bottom_start = ms_bottom;\r\n\r\n    wxCommandEvent e;\r\n    buttonPauseClick(e);\r\n}\r\n","avg_line_length":34.9390997352,"max_line_length":194,"alphanum_fraction":0.6186025363,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1944,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"tools.h\"\n#include <iostream>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing std::vector;\n\nTools::Tools() {}\n\nTools::~Tools() {}\n\nVectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations,\n                              const vector<VectorXd> &ground_truth)\n{\n   \/**\n   * TODO: Calculate the RMSE here.\n   *\/\n   VectorXd result = VectorXd(4);\n   result << 0, 0, 0, 0;\n\n   for (unsigned int i = 0; i < estimations.size(); ++i)\n   {\n\n      VectorXd residual = estimations[i] - ground_truth[i];\n\n      \/\/ coefficient-wise multiplication\n      residual = residual.array() * residual.array();\n      result += residual;\n   }\n   result = result \/ estimations.size();\n\n   result = result.array().sqrt();\n\n   return result;\n}\n\nMatrixXd Tools::CalculateJacobian(const VectorXd &x_state)\n{\n   \/**\n   * Done:\n   * Calculate a Jacobian here.\n   *\/\n   float px = x_state(0);\n   float py = x_state(1);\n   float vx = x_state(2);\n   float vy = x_state(3);\n\n   \/\/ pre-compute a set of terms to avoid repeated calculation\n   float c1 = px * px + py * py;\n   float c2 = sqrt(c1);\n   float c3 = (c1 * c2);\n\n   MatrixXd Hj = MatrixXd(3, 4);\n\n   \/\/ check division by zero\n   if (fabs(c1) < 0.0001)\n   {\n      Hj << 0, 0, 0, 0,\n          0, 0, 0, 0,\n          0, 0, 0, 0;\n      return Hj;\n   }\n   else\n   {\n      \/\/ compute the Jacobian matrix\n      Hj << (px \/ c2), (py \/ c2), 0, 0,\n          -(py \/ c1), (px \/ c1), 0, 0,\n          py * (vx * py - vy * px) \/ c3, px * (px * vy - py * vx) \/ c3, px \/ c2, py \/ c2;\n      return Hj;\n   }\n}\n\nVectorXd Tools::Cart2Polar(const VectorXd &x_state)\n{\n   \/\/recover state parameters\n   double px = x_state(0);\n   double py = x_state(1);\n   double vx = x_state(2);\n   double vy = x_state(3);\n\n   double rho = sqrt(px * px + py * py);\n   double phi = atan2(py, px);\n   double rho_dot = (rho != 0) ? (px * vx + py * vy) \/ rho : 0;\n\n   VectorXd x_polar(3);\n   x_polar << rho, phi, rho_dot;\n\n   return x_polar;\n}","avg_line_length":21.8426966292,"max_line_length":89,"alphanum_fraction":0.558127572,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":12857,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":11.0,"content":"\ufeff#ifndef _CRT_SECURE_NO_WARNINGS\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n\n#include \"application.h\"\n\n#include <core\/md_log.h>\n#include <core\/md_common.h>\n#include <core\/md_allocator.h>\n\n#include \"gfx\/gl.h\"\n#include <GLFW\/glfw3.h>\n#include <nfd.h>\n#if MD_PLATFORM_WINDOWS\n#ifndef WIN32_LEAN_AND_MEAN\n#define WIN32_LEAN_AND_MEAN 1\n#endif\n#define GLFW_EXPOSE_NATIVE_WIN32\n#define GLFW_EXPOSE_NATIVE_WGL\n#include <GLFW\/glfw3native.h>\n#endif\n#include <imgui.h>\n#include \"imgui_impl_glfw.h\"\n#include \"imgui_impl_opengl3.h\"\n\n\/\/ Compressed fonts\n\/\/#include \"cousine_font.inl\"\n\/\/#include \"droid_sans.inl\"\n#include \"droid_sans_mono.inl\"\n#include \"fa_solid.inl\"\n\n#include <implot.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n\nnamespace application {\n\n\/\/ Data\nstatic struct {\n    Context internal_ctx{};\n} data;\n\nstatic void error_callback(int error, const char* description) { md_printf(MD_LOG_TYPE_ERROR, \"%d: %s\\n\", error, description); }\n\nstatic void APIENTRY gl_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message,\n                                 const void* userParam) {\n    (void)source;\n    (void)type;\n    (void)id;\n    (void)severity;\n    (void)length;\n    (void)userParam;\n\n    if (severity > GL_DEBUG_SEVERITY_LOW) {\n        md_print(MD_LOG_TYPE_INFO, message);\n    }\n    if (severity == GL_DEBUG_SEVERITY_HIGH) {\n        md_printf(MD_LOG_TYPE_ERROR, \"A SEVERE GL ERROR HAS OCCURED: %s\", message);\n        abort();\n    }\n}\n\nstatic void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {\n    if (action == GLFW_PRESS) {\n        data.internal_ctx.input.mouse.down[button] = true;\n        data.internal_ctx.input.mouse.hit[button] = true;\n    } else if (action == GLFW_RELEASE) {\n        data.internal_ctx.input.mouse.down[button] = false;\n        data.internal_ctx.input.mouse.release[button] = true;\n    }\n\n    ImGui_ImplGlfw_MouseButtonCallback(window, button, action, mods);\n}\n\nstatic void mouse_scroll_callback(GLFWwindow* window, double xoffset, double yoffset) {\n    data.internal_ctx.input.mouse.scroll_delta = (float)yoffset;\n    ImGui_ImplGlfw_ScrollCallback(window, xoffset, yoffset);\n}\n\nstatic void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {\n    if (action == GLFW_PRESS) {\n        data.internal_ctx.input.key.down[key] = true;\n        data.internal_ctx.input.key.hit[key] = true;\n    }\n    if (action == GLFW_RELEASE) {\n        data.internal_ctx.input.key.down[key] = false;\n    }\n\n    ImGui_ImplGlfw_KeyCallback(window, key, scancode, action, mods);\n}\n\nstatic void char_callback(GLFWwindow* window, unsigned int c) { ImGui_ImplGlfw_CharCallback(window, c); }\n\nbool initialize(Context* ctx, int64_t width, int64_t height, const char* title) {\n    if (!glfwInit()) {\n        \/\/ TODO Throw critical error\n        error_callback(1, \"Error while initializing glfw.\");\n        return false;\n    }\n    glfwSetErrorCallback(error_callback);\n\n#if MD_PLATFORM_OSX\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n#endif\n    GLFWwindow* window = glfwCreateWindow((int)width, (int)height, title, NULL, NULL);\n    if (!window) {\n        error_callback(2, \"Could not create glfw window.\");\n        return false;\n    }\n\n    glfwMakeContextCurrent(window);\n    glfwSwapInterval(1);\n    if (gl3wInit() != GL3W_OK) {\n        error_callback(3, \"Could not load gl functions.\");\n        return false;\n    }\n\n    if (glDebugMessageCallback) {\n        glEnable(GL_DEBUG_OUTPUT);\n        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);\n        glDebugMessageCallback(gl_callback, NULL);\n        glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, true);\n    }\n\n    glfwGetVersion(&data.internal_ctx.gl_info.version.major, &data.internal_ctx.gl_info.version.minor, &data.internal_ctx.gl_info.version.revision);\n\n    IMGUI_CHECKVERSION();\n    ImGui::CreateContext();\n    ImPlot::CreateContext();\n    ImGuiIO& io = ImGui::GetIO();\n    io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;  \/\/ Enable Keyboard Controls\n    \/\/ io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      \/\/ Enable Gamepad Controls\n    io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;  \/\/ Enable Docking\n    io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;  \/\/ Enable Multi-Viewport \/ Platform Windows\n    \/\/ io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoTaskBarIcons;\n    \/\/ io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoMerge;\n    io.ConfigFlags |= ImGuiConfigFlags_DpiEnableScaleFonts;\n    \/\/ io.ConfigDockingWithShift = true;\n    io.ConfigWindowsMoveFromTitleBarOnly = true;\n\n    \/\/ default range is 0x0020 - 0x00FF.\n    \/\/ Added some greek letters\n    \/*\n    {\n        static const ImWchar ranges[] = {0x0020, 0x00FF, 0x03C6, 0x03C8, 0};\n        ImFontConfig config;\n        config.OversampleV = 1;\n        config.OversampleH = 1;\n        config.RasterizerMultiply = 0.9f;\n        config.PixelSnapH = true;\n        ImGui::GetIO().Fonts->AddFontFromMemoryCompressedTTF((void*)DroidSans_compressed_data, DroidSans_compressed_size, 16.f, &config, ranges);\n    }\n    *\/\n    const ImWchar ranges_characters[] = {0x0020, 0x00FF, 0x03C6, 0x03C8, 0};\n    const ImWchar ranges_icons[] = {ICON_MIN_FA, ICON_MAX_FA, 0};\n    const float scaling_factors[] = {1.0, 1.5};\n    const char* font_names[] = {\"Default Size Droid Sans\", \"Large Size Droid Sans\"};\n\n    for (int i = 0; i < ARRAY_SIZE(scaling_factors); ++i) {\n        ImFontConfig config;\n        snprintf(config.Name, sizeof(config.Name), \"%s\", font_names[i]);\n        config.OversampleV = 1;\n        config.OversampleH = 3;\n        config.PixelSnapH = true;\n\n        const float scl = scaling_factors[i];\n\n        \/\/ CHARACTERS\n        config.RasterizerMultiply = 1.f;\n        ImGui::GetIO().Fonts->AddFontFromMemoryCompressedTTF((void*)droid_sans_mono_compressed_data, droid_sans_mono_compressed_size, 16 * scl, &config, ranges_characters);\n\n        \/\/ ICONS\n        config.RasterizerMultiply = 0.9f;\n        config.MergeMode = true;\n        ImGui::GetIO().Fonts->AddFontFromMemoryCompressedTTF((void*)fa_solid_compressed_data, fa_solid_compressed_size, 14 * scl, &config, ranges_icons);\n    }\n\n    io.Fonts->Build();\n\n    ImGui_ImplGlfw_InitForOpenGL(window, false);\n    ImGui_ImplOpenGL3_Init(\"#version 150\");\n\n    data.internal_ctx.window.ptr = window;\n    data.internal_ctx.window.title = title;\n    data.internal_ctx.window.width = (int)width;\n    data.internal_ctx.window.height = (int)height;\n    data.internal_ctx.window.vsync = true;\n\n    int w, h;\n    glfwGetFramebufferSize(window, &w, &h);\n    data.internal_ctx.framebuffer.width = w;\n    data.internal_ctx.framebuffer.height = h;\n\n    double x, y;\n    glfwGetCursorPos(window, &x, &y);\n    Coordinate win_coord = {(float)x, (float)y};\n    data.internal_ctx.input.mouse.win_coord = win_coord;\n\n    const float half_res_x = width * 0.5f;\n    const float half_res_y = height * 0.5f;\n    Coordinate ndc_coord = {(win_coord.x - half_res_x) \/ half_res_x, ((height - win_coord.y) - half_res_y) \/ half_res_y};\n    data.internal_ctx.input.mouse.ndc_delta = ndc_coord - data.internal_ctx.input.mouse.ndc_coord;\n    data.internal_ctx.input.mouse.ndc_coord = ndc_coord;\n\n    data.internal_ctx.input.mouse.moving = false;\n\n    glfwSetMouseButtonCallback(window, mouse_button_callback);\n    glfwSetScrollCallback(window, mouse_scroll_callback);\n    glfwSetKeyCallback(window, key_callback);\n    glfwSetCharCallback(window, char_callback);\n\n    memcpy(ctx, &data.internal_ctx, sizeof(Context));\n\n    return true;\n}\n\nvoid shutdown(Context* ctx) {\n    glfwDestroyWindow((GLFWwindow*)data.internal_ctx.window.ptr);\n    ImGui_ImplGlfw_Shutdown();\n    ImPlot::DestroyContext();\n    ImGui::DestroyContext();\n    glfwTerminate();\n\n    ctx->window.ptr = nullptr;\n    ctx->window.title = \"\";\n    ctx->window.width = 0;\n    ctx->window.height = 0;\n}\n\nvoid update(Context* ctx) {\n    \/\/ Reset hit states\n    memset(data.internal_ctx.input.key.hit, 0, MAX_KEYS);\n    memset(data.internal_ctx.input.key.release, 0, MAX_KEYS);\n    memset(data.internal_ctx.input.mouse.hit, 0, MAX_MOUSE_BUTTONS);\n    memset(data.internal_ctx.input.mouse.release, 0, MAX_MOUSE_BUTTONS);\n    data.internal_ctx.input.mouse.scroll_delta = 0;\n\n    glfwPollEvents();\n\n    ImGui_ImplOpenGL3_NewFrame();\n    ImGui_ImplGlfw_NewFrame();\n    ImGui::NewFrame();\n\n    if (ctx->window.width != data.internal_ctx.window.width || ctx->window.height != data.internal_ctx.window.height) {\n        glfwSetWindowSize((GLFWwindow*)ctx->window.ptr, ctx->window.width, ctx->window.height);\n        data.internal_ctx.window.width = ctx->window.width;\n        data.internal_ctx.window.height = ctx->window.height;\n    }\n    int w, h;\n    glfwGetFramebufferSize((GLFWwindow*)data.internal_ctx.window.ptr, &w, &h);\n    data.internal_ctx.framebuffer.width = w;\n    data.internal_ctx.framebuffer.height = h;\n\n    glfwGetWindowSize((GLFWwindow*)data.internal_ctx.window.ptr, &w, &h);\n    data.internal_ctx.window.width = w;\n    data.internal_ctx.window.height = h;\n\n    if (ctx->window.vsync != data.internal_ctx.window.vsync) {\n        data.internal_ctx.window.vsync = ctx->window.vsync;\n        glfwSwapInterval((int)ctx->window.vsync);\n    }\n\n    data.internal_ctx.window.should_close = (bool)glfwWindowShouldClose((GLFWwindow*)data.internal_ctx.window.ptr);\n\n    double x, y;\n    glfwGetCursorPos((GLFWwindow*)data.internal_ctx.window.ptr, &x, &y);\n    Coordinate win_coord{(float)x, (float)y};\n\n    \/\/ If user has modified value, set the mouse pointer to that value\n    if (ctx->input.mouse.win_coord != data.internal_ctx.input.mouse.win_coord) {\n        win_coord = ctx->input.mouse.win_coord;\n    }\n\n    data.internal_ctx.input.mouse.win_delta = win_coord - data.internal_ctx.input.mouse.win_coord;\n    data.internal_ctx.input.mouse.win_coord = win_coord;\n\n    constexpr Coordinate zero_coord{0, 0};\n    data.internal_ctx.input.mouse.moving = data.internal_ctx.input.mouse.win_delta != zero_coord;\n\n    const float half_res_x = w * 0.5f;\n    const float half_res_y = h * 0.5f;\n    data.internal_ctx.input.mouse.ndc_coord = {(win_coord.x - half_res_x) \/ half_res_x, ((h - win_coord.y) - half_res_y) \/ half_res_y};\n\n    \/\/ Any mouse key hit\n    bool any_mouse_key_hit = false;\n    for (int i = 0; i < MAX_MOUSE_BUTTONS; i++) {\n        if (data.internal_ctx.input.mouse.hit[i]) {\n            any_mouse_key_hit = true;\n            break;\n        }\n    }\n\n    static Coordinate mouse_click_coord = win_coord;\n    if (any_mouse_key_hit) {\n        mouse_click_coord = win_coord;\n    }\n\n    for (int i = 0; i < MAX_MOUSE_BUTTONS; i++) {\n        data.internal_ctx.input.mouse.clicked[i] = (mouse_click_coord == win_coord) && data.internal_ctx.input.mouse.release[i];\n    }\n\n    double t = glfwGetTime();\n    data.internal_ctx.timing.delta_s = (t - data.internal_ctx.timing.total_s);\n    data.internal_ctx.timing.total_s = t;\n\n    memcpy(ctx, &data.internal_ctx, sizeof(Context));\n}\n\nvoid render_imgui(Context* ctx) {\n    (void)ctx;\n    GLFWwindow* window = (GLFWwindow*)data.internal_ctx.window.ptr;\n\n    ImGui::Render();\n    glfwMakeContextCurrent(window);\n    ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());\n\n    \/\/ Update and Render additional Platform Windows\n    if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable) {\n        ImGui::UpdatePlatformWindows();\n        ImGui::RenderPlatformWindowsDefault();\n    }\n\n    glfwMakeContextCurrent(window);\n}\n\nvoid swap_buffers(Context* ctx) { glfwSwapBuffers((GLFWwindow*)ctx->window.ptr); }\n\nFileDialogResult file_dialog(FileDialogFlags flags, str_t path, str_t filter) {\n    ASSERT(path.len >= 0);\n    ASSERT(filter.len >= 0);\n\n    \/\/ Create zero terminated strings\n    path = copy_str(path, default_temp_allocator);\n    filter = copy_str(filter, default_temp_allocator);\n\n    nfdchar_t* out_path = NULL;\n    nfdresult_t result = NFD_ERROR;\n\n    if (flags & FileDialogFlags_Open) {\n        result = NFD_OpenDialog(filter.ptr, path.ptr, &out_path);\n    } else if (flags & FileDialogFlags_Save) {\n        result = NFD_SaveDialog(filter.ptr, path.ptr, &out_path);\n    }\n\n    free_str(path, default_temp_allocator);\n    free_str(filter, default_temp_allocator);\n\n    FileDialogResult res = {};\n\n    if (result == NFD_OKAY) {\n        strncpy(res.path, out_path, ARRAY_SIZE(res.path)-1);\n        res.path_len = strnlen(res.path, ARRAY_SIZE(res.path));\n        convert_backslashes(res.path, ARRAY_SIZE(res.path));\n        goto done;\n    } else if (result == NFD_CANCEL) {\n        res.result = FileDialogResult::Cancel;\n        goto done;\n    }\n    md_printf(MD_LOG_TYPE_ERROR, \"%s\\n\", NFD_GetError());\n\ndone:\n    if (out_path) free(out_path);\n    return res;\n}\n\n}  \/\/ namespace application\n","avg_line_length":34.6549865229,"max_line_length":172,"alphanum_fraction":0.6957299526,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1477,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":28.0,"content":"\/* TEMPLATE GENERATED TESTCASE FILE\r\nFilename: CWE191_Integer_Underflow__int_fgets_sub_83_goodG2B.cpp\r\nLabel Definition File: CWE191_Integer_Underflow__int.label.xml\r\nTemplate File: sources-sinks-83_goodG2B.tmpl.cpp\r\n*\/\r\n\/*\r\n * @description\r\n * CWE: 191 Integer Underflow\r\n * BadSource: fgets Read data from the console using fgets()\r\n * GoodSource: Set data to a small, non-zero number (negative two)\r\n * Sinks: sub\r\n *    GoodSink: Ensure there will not be an underflow before subtracting 1 from data\r\n *    BadSink : Subtract 1 from data, which can cause an Underflow\r\n * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack\r\n *\r\n * *\/\r\n#ifndef OMITGOOD\r\n\r\n#include \"std_testcase.h\"\r\n#include \"CWE191_Integer_Underflow__int_fgets_sub_83.h\"\r\n\r\n#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)\r\n\r\nnamespace CWE191_Integer_Underflow__int_fgets_sub_83\r\n{\r\nCWE191_Integer_Underflow__int_fgets_sub_83_goodG2B::CWE191_Integer_Underflow__int_fgets_sub_83_goodG2B(int dataCopy)\r\n{\r\n    data = dataCopy;\r\n    \/* FIX: Use a small, non-zero value that will not cause an integer underflow in the sinks *\/\r\n    data = -2;\r\n}\r\n\r\nCWE191_Integer_Underflow__int_fgets_sub_83_goodG2B::~CWE191_Integer_Underflow__int_fgets_sub_83_goodG2B()\r\n{\r\n    {\r\n        \/* POTENTIAL FLAW: Subtracting 1 from data could cause an underflow *\/\r\n        int result = data - 1;\r\n        printIntLine(result);\r\n    }\r\n}\r\n}\r\n#endif \/* OMITGOOD *\/\r\n","avg_line_length":34.3488372093,"max_line_length":122,"alphanum_fraction":0.7420446852,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11683,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/\/ Copyright (c) 2011-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <blockencodings.h>\n#include <consensus\/merkle.h>\n#include <chainparams.h>\n#include <random.h>\n\n#include <test\/test_electrum.h>\n\n#include <boost\/test\/unit_test.hpp>\n\nstruct RegtestingSetup : public TestingSetup {\n    RegtestingSetup() : TestingSetup(CBaseChainParams::REGTEST) {}\n};\n\nBOOST_FIXTURE_TEST_SUITE(blockencodings_tests, RegtestingSetup)\n\nstatic CBlock BuildBlockTestCase() {\n    CBlock block;\n    CMutableTransaction tx;\n    tx.vin.resize(1);\n    tx.vin[0].scriptSig.resize(10);\n    tx.vout.resize(1);\n    tx.vout[0].nValue = 42;\n\n    block.vtx.resize(3);\n    block.vtx[0] = tx;\n    block.nVersion = 42;\n    block.hashPrevBlock = GetRandHash();\n    block.nBits = 0x207fffff;\n\n    tx.vin[0].prevout.hash = GetRandHash();\n    tx.vin[0].prevout.n = 0;\n    block.vtx[1] = tx;\n\n    tx.vin.resize(10);\n    for (size_t i = 0; i < tx.vin.size(); i++) {\n        tx.vin[i].prevout.hash = GetRandHash();\n        tx.vin[i].prevout.n = 0;\n    }\n    block.vtx[2] = tx;\n\n    bool mutated;\n    block.hashMerkleRoot = BlockMerkleRoot(block, &mutated);\n    assert(!mutated);\n    while (!CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())) ++block.nNonce;\n    return block;\n}\n\n\/\/ Number of shared use_counts we expect for a tx we havent touched\n\/\/ == 2 (mempool + our copy from the GetSharedTx call)\n#define SHARED_TX_OFFSET 2\n\nBOOST_AUTO_TEST_CASE(SimpleRoundTripTest)\n{\n    CTxMemPool pool(CFeeRate(0));\n    TestMemPoolEntryHelper entry;\n    CBlock block(BuildBlockTestCase());\n\n    pool.addUnchecked(block.vtx[2].GetHash(), entry.FromTx(block.vtx[2]));\n    BOOST_CHECK_EQUAL(pool.mapTx.find(block.vtx[2].GetHash())->GetSharedTx().use_count(), SHARED_TX_OFFSET + 0);\n\n    \/\/ Do a simple ShortTxIDs RT\n    {\n        CBlockHeaderAndShortTxIDs shortIDs(block);\n\n        CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n        stream << shortIDs;\n\n        CBlockHeaderAndShortTxIDs shortIDs2;\n        stream >> shortIDs2;\n\n        PartiallyDownloadedBlock partialBlock(&pool);\n        BOOST_CHECK(partialBlock.InitData(shortIDs2) == READ_STATUS_OK);\n        BOOST_CHECK( partialBlock.IsTxAvailable(0));\n        BOOST_CHECK(!partialBlock.IsTxAvailable(1));\n        BOOST_CHECK( partialBlock.IsTxAvailable(2));\n\n        BOOST_CHECK_EQUAL(pool.mapTx.find(block.vtx[2].GetHash())->GetSharedTx().use_count(), SHARED_TX_OFFSET + 1);\n\n        std::list<CTransaction> removed;\n        pool.removeRecursive(block.vtx[2], removed);\n        BOOST_CHECK_EQUAL(removed.size(), 1);\n\n        CBlock block2;\n        std::vector<CTransaction> vtx_missing;\n        BOOST_CHECK(partialBlock.FillBlock(block2, vtx_missing) == READ_STATUS_INVALID); \/\/ No transactions\n\n        vtx_missing.push_back(block.vtx[2]); \/\/ Wrong transaction\n        partialBlock.FillBlock(block2, vtx_missing); \/\/ Current implementation doesn't check txn here, but don't require that\n        bool mutated;\n        BOOST_CHECK(block.hashMerkleRoot != BlockMerkleRoot(block2, &mutated));\n\n        vtx_missing[0] = block.vtx[1];\n        CBlock block3;\n        BOOST_CHECK(partialBlock.FillBlock(block3, vtx_missing) == READ_STATUS_OK);\n        BOOST_CHECK_EQUAL(block.GetHash().ToString(), block3.GetHash().ToString());\n        BOOST_CHECK_EQUAL(block.hashMerkleRoot.ToString(), BlockMerkleRoot(block3, &mutated).ToString());\n        BOOST_CHECK(!mutated);\n    }\n}\n\nclass TestHeaderAndShortIDs {\n    \/\/ Utility to encode custom CBlockHeaderAndShortTxIDs\npublic:\n    CBlockHeader header;\n    uint64_t nonce;\n    std::vector<uint64_t> shorttxids;\n    std::vector<PrefilledTransaction> prefilledtxn;\n\n    TestHeaderAndShortIDs(const CBlockHeaderAndShortTxIDs& orig) {\n        CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n        stream << orig;\n        stream >> *this;\n    }\n    TestHeaderAndShortIDs(const CBlock& block) :\n        TestHeaderAndShortIDs(CBlockHeaderAndShortTxIDs(block)) {}\n\n    uint64_t GetShortID(const uint256& txhash) const {\n        CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n        stream << *this;\n        CBlockHeaderAndShortTxIDs base;\n        stream >> base;\n        return base.GetShortID(txhash);\n    }\n\n    ADD_SERIALIZE_METHODS;\n\n    template <typename Stream, typename Operation>\n    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {\n        READWRITE(header);\n        READWRITE(nonce);\n        size_t shorttxids_size = shorttxids.size();\n        READWRITE(VARINT(shorttxids_size));\n        shorttxids.resize(shorttxids_size);\n        for (size_t i = 0; i < shorttxids.size(); i++) {\n            uint32_t lsb = shorttxids[i] & 0xffffffff;\n            uint16_t msb = (shorttxids[i] >> 32) & 0xffff;\n            READWRITE(lsb);\n            READWRITE(msb);\n            shorttxids[i] = (uint64_t(msb) << 32) | uint64_t(lsb);\n        }\n        READWRITE(prefilledtxn);\n    }\n};\n\nBOOST_AUTO_TEST_CASE(NonCoinbasePreforwardRTTest)\n{\n    CTxMemPool pool(CFeeRate(0));\n    TestMemPoolEntryHelper entry;\n    CBlock block(BuildBlockTestCase());\n\n    pool.addUnchecked(block.vtx[2].GetHash(), entry.FromTx(block.vtx[2]));\n    BOOST_CHECK_EQUAL(pool.mapTx.find(block.vtx[2].GetHash())->GetSharedTx().use_count(), SHARED_TX_OFFSET + 0);\n\n    \/\/ Test with pre-forwarding tx 1, but not coinbase\n    {\n        TestHeaderAndShortIDs shortIDs(block);\n        shortIDs.prefilledtxn.resize(1);\n        shortIDs.prefilledtxn[0] = {1, block.vtx[1]};\n        shortIDs.shorttxids.resize(2);\n        shortIDs.shorttxids[0] = shortIDs.GetShortID(block.vtx[0].GetHash());\n        shortIDs.shorttxids[1] = shortIDs.GetShortID(block.vtx[2].GetHash());\n\n        CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n        stream << shortIDs;\n\n        CBlockHeaderAndShortTxIDs shortIDs2;\n        stream >> shortIDs2;\n\n        PartiallyDownloadedBlock partialBlock(&pool);\n        BOOST_CHECK(partialBlock.InitData(shortIDs2) == READ_STATUS_OK);\n        BOOST_CHECK(!partialBlock.IsTxAvailable(0));\n        BOOST_CHECK( partialBlock.IsTxAvailable(1));\n        BOOST_CHECK( partialBlock.IsTxAvailable(2));\n\n        BOOST_CHECK_EQUAL(pool.mapTx.find(block.vtx[2].GetHash())->GetSharedTx().use_count(), SHARED_TX_OFFSET + 1);\n\n        CBlock block2;\n        std::vector<CTransaction> vtx_missing;\n        BOOST_CHECK(partialBlock.FillBlock(block2, vtx_missing) == READ_STATUS_INVALID); \/\/ No transactions\n\n        vtx_missing.push_back(block.vtx[1]); \/\/ Wrong transaction\n        partialBlock.FillBlock(block2, vtx_missing); \/\/ Current implementation doesn't check txn here, but don't require that\n        bool mutated;\n        BOOST_CHECK(block.hashMerkleRoot != BlockMerkleRoot(block2, &mutated));\n\n        vtx_missing[0] = block.vtx[0];\n        CBlock block3;\n        BOOST_CHECK(partialBlock.FillBlock(block3, vtx_missing) == READ_STATUS_OK);\n        BOOST_CHECK_EQUAL(block.GetHash().ToString(), block3.GetHash().ToString());\n        BOOST_CHECK_EQUAL(block.hashMerkleRoot.ToString(), BlockMerkleRoot(block3, &mutated).ToString());\n        BOOST_CHECK(!mutated);\n\n        BOOST_CHECK_EQUAL(pool.mapTx.find(block.vtx[2].GetHash())->GetSharedTx().use_count(), SHARED_TX_OFFSET + 1);\n    }\n    BOOST_CHECK_EQUAL(pool.mapTx.find(block.vtx[2].GetHash())->GetSharedTx().use_count(), SHARED_TX_OFFSET + 0);\n}\n\nBOOST_AUTO_TEST_CASE(SufficientPreforwardRTTest)\n{\n    CTxMemPool pool(CFeeRate(0));\n    TestMemPoolEntryHelper entry;\n    CBlock block(BuildBlockTestCase());\n\n    pool.addUnchecked(block.vtx[1].GetHash(), entry.FromTx(block.vtx[1]));\n    BOOST_CHECK_EQUAL(pool.mapTx.find(block.vtx[1].GetHash())->GetSharedTx().use_count(), SHARED_TX_OFFSET + 0);\n\n    \/\/ Test with pre-forwarding coinbase + tx 2 with tx 1 in mempool\n    {\n        TestHeaderAndShortIDs shortIDs(block);\n        shortIDs.prefilledtxn.resize(2);\n        shortIDs.prefilledtxn[0] = {0, block.vtx[0]};\n        shortIDs.prefilledtxn[1] = {1, block.vtx[2]}; \/\/ id == 1 as it is 1 after index 1\n        shortIDs.shorttxids.resize(1);\n        shortIDs.shorttxids[0] = shortIDs.GetShortID(block.vtx[1].GetHash());\n\n        CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n        stream << shortIDs;\n\n        CBlockHeaderAndShortTxIDs shortIDs2;\n        stream >> shortIDs2;\n\n        PartiallyDownloadedBlock partialBlock(&pool);\n        BOOST_CHECK(partialBlock.InitData(shortIDs2) == READ_STATUS_OK);\n        BOOST_CHECK( partialBlock.IsTxAvailable(0));\n        BOOST_CHECK( partialBlock.IsTxAvailable(1));\n        BOOST_CHECK( partialBlock.IsTxAvailable(2));\n\n        BOOST_CHECK_EQUAL(pool.mapTx.find(block.vtx[1].GetHash())->GetSharedTx().use_count(), SHARED_TX_OFFSET + 1);\n\n        CBlock block2;\n        std::vector<CTransaction> vtx_missing;\n        BOOST_CHECK(partialBlock.FillBlock(block2, vtx_missing) == READ_STATUS_OK);\n        BOOST_CHECK_EQUAL(block.GetHash().ToString(), block2.GetHash().ToString());\n        bool mutated;\n        BOOST_CHECK_EQUAL(block.hashMerkleRoot.ToString(), BlockMerkleRoot(block2, &mutated).ToString());\n        BOOST_CHECK(!mutated);\n\n        BOOST_CHECK_EQUAL(pool.mapTx.find(block.vtx[1].GetHash())->GetSharedTx().use_count(), SHARED_TX_OFFSET + 1);\n    }\n    BOOST_CHECK_EQUAL(pool.mapTx.find(block.vtx[1].GetHash())->GetSharedTx().use_count(), SHARED_TX_OFFSET + 0);\n}\n\nBOOST_AUTO_TEST_CASE(EmptyBlockRoundTripTest)\n{\n    CTxMemPool pool(CFeeRate(0));\n    CMutableTransaction coinbase;\n    coinbase.vin.resize(1);\n    coinbase.vin[0].scriptSig.resize(10);\n    coinbase.vout.resize(1);\n    coinbase.vout[0].nValue = 42;\n\n    CBlock block;\n    block.vtx.resize(1);\n    block.vtx[0] = coinbase;\n    block.nVersion = 42;\n    block.hashPrevBlock = GetRandHash();\n    block.nBits = 0x207fffff;\n\n    bool mutated;\n    block.hashMerkleRoot = BlockMerkleRoot(block, &mutated);\n    assert(!mutated);\n    while (!CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())) ++block.nNonce;\n\n    \/\/ Test simple header round-trip with only coinbase\n    {\n        CBlockHeaderAndShortTxIDs shortIDs(block);\n\n        CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n        stream << shortIDs;\n\n        CBlockHeaderAndShortTxIDs shortIDs2;\n        stream >> shortIDs2;\n\n        PartiallyDownloadedBlock partialBlock(&pool);\n        BOOST_CHECK(partialBlock.InitData(shortIDs2) == READ_STATUS_OK);\n        BOOST_CHECK(partialBlock.IsTxAvailable(0));\n\n        CBlock block2;\n        std::vector<CTransaction> vtx_missing;\n        BOOST_CHECK(partialBlock.FillBlock(block2, vtx_missing) == READ_STATUS_OK);\n        BOOST_CHECK_EQUAL(block.GetHash().ToString(), block2.GetHash().ToString());\n        bool mutated;\n        BOOST_CHECK_EQUAL(block.hashMerkleRoot.ToString(), BlockMerkleRoot(block2, &mutated).ToString());\n        BOOST_CHECK(!mutated);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(TransactionsRequestSerializationTest) {\n    BlockTransactionsRequest req1;\n    req1.blockhash = GetRandHash();\n    req1.indexes.resize(4);\n    req1.indexes[0] = 0;\n    req1.indexes[1] = 1;\n    req1.indexes[2] = 3;\n    req1.indexes[3] = 4;\n\n    CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n    stream << req1;\n\n    BlockTransactionsRequest req2;\n    stream >> req2;\n\n    BOOST_CHECK_EQUAL(req1.blockhash.ToString(), req2.blockhash.ToString());\n    BOOST_CHECK_EQUAL(req1.indexes.size(), req2.indexes.size());\n    BOOST_CHECK_EQUAL(req1.indexes[0], req2.indexes[0]);\n    BOOST_CHECK_EQUAL(req1.indexes[1], req2.indexes[1]);\n    BOOST_CHECK_EQUAL(req1.indexes[2], req2.indexes[2]);\n    BOOST_CHECK_EQUAL(req1.indexes[3], req2.indexes[3]);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":36.9715189873,"max_line_length":125,"alphanum_fraction":0.6869810836,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1585,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\ufeff#include <QCoreApplication>\r\n#include <QFile>\r\n#include <QSettings>\r\n#include <QProcess>\r\n#include <QDir>\r\n\r\n#include \"Objects\/controlunit.h\"\r\n#include \"Objects\/planner.h\"\r\n#include \"Objects\/scene.h\"\r\n\r\n#include \"Tests\/connectiontests.h\"\r\n#include \"Tests\/reconnectiontests.h\"\r\n#include \"Tests\/transfertests.h\"\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n    QCoreApplication a(argc, argv);\r\n\r\n    const QString defaultRcaIp     = \"localhost\";\r\n    const QString defaultSceneIp   = \"localhost\";\r\n    const quint16 defaultRcaPort   = 8000;\r\n    const quint16 defaultScenePort = 8080;\r\n\r\n    QSettings settings(\"..\/config.ini\", QSettings::IniFormat);\r\n    QString rcaIp = settings.value(\"HOSTS\/Rca\", defaultRcaIp).toString();\r\n    QString sceneIp = settings.value(\"HOSTS\/Scene\", defaultSceneIp).toString();\r\n    quint16 rcaPort = static_cast<quint16>(settings.value(\"PORTS\/Rca\", defaultRcaPort).toInt());\r\n    quint16 scenePort  = static_cast<quint16>(settings.value(\"PORTS\/Scene\", defaultScenePort).toInt());\r\n\r\n    QDir dir = QDir::current();\r\n    dir.cdUp();\r\n    dir.cdUp();\r\n    dir.cd(\"System\/release\");\r\n    QString pathToRcaExec = dir.path();\r\n\r\n    int waitTime = 300;\r\n\r\n    auto res1 = QTest::qExec(new ConnectionTests(rcaIp, sceneIp, rcaPort, scenePort, pathToRcaExec, waitTime), argc, argv);\r\n    auto res2 = QTest::qExec(new TransferTests(rcaIp, sceneIp, rcaPort, scenePort, pathToRcaExec, waitTime), argc, argv);\r\n    auto res3 = QTest::qExec(new ReconnectionTests(rcaIp, sceneIp, rcaPort, scenePort, pathToRcaExec, waitTime), argc, argv);\r\n    return res1 + res2 + res3;\r\n}\r\n","avg_line_length":36.8604651163,"max_line_length":126,"alphanum_fraction":0.6940063091,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3575,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n#include \"oneflow\/core\/framework\/framework.h\"\n\nnamespace oneflow {\n\nREGISTER_USER_OP(\"bias_add\")\n    .Input(\"a\")\n    .Input(\"b\")\n    .Output(\"out\")\n    .Attr<int32_t>(\"axis\")\n    .SetTensorDescInferFn([](user_op::InferContext* ctx) -> Maybe<void> {\n      const auto* a_tensor_desc = ctx->TensorDesc4ArgNameAndIndex(\"a\", 0);\n      const auto* b_tensor_desc = ctx->TensorDesc4ArgNameAndIndex(\"b\", 0);\n      const auto bias_add_axis = ctx->Attr<int32_t>(\"axis\");\n      CHECK_EQ_OR_RETURN(b_tensor_desc->shape().NumAxes(), 1);\n      CHECK_GE_OR_RETURN(bias_add_axis, 0);\n      CHECK_LT_OR_RETURN(bias_add_axis, a_tensor_desc->shape().NumAxes());\n      CHECK_EQ_OR_RETURN(a_tensor_desc->shape().At(bias_add_axis), b_tensor_desc->shape().At(0));\n      *ctx->OutputShape(\"out\", 0) = ctx->InputShape(\"a\", 0);\n      *ctx->OutputIsDynamic4ArgNameAndIndex(\"out\", 0) = ctx->InputIsDynamic4ArgNameAndIndex(\"a\", 0);\n      return Maybe<void>::Ok();\n    })\n    .SetGetSbpFn([](user_op::SbpContext* ctx) -> Maybe<void> {\n      const auto axis = ctx->Attr<int32_t>(\"axis\");\n      for (int64_t i = 0; i < ctx->LogicalTensorDesc4InputArgNameAndIndex(\"a\", 0).shape().NumAxes();\n           ++i) {\n        if (i == axis) { continue; }\n        ctx->NewBuilder()\n            .Split(user_op::OpArg(\"a\", 0), i)\n            .Broadcast(user_op::OpArg(\"b\", 0))\n            .Split(ctx->outputs(), i)\n            .Build();\n      }\n      ctx->NewBuilder()\n          .Split(user_op::OpArg(\"b\", 0), 0)\n          .Split(user_op::OpArg(\"a\", 0), axis)\n          .Split(ctx->outputs(), axis)\n          .Build();\n      return Maybe<void>::Ok();\n    })\n    .SetDataTypeInferFn([](user_op::InferContext* ctx) -> Maybe<void> {\n      *ctx->OutputDType(\"out\", 0) = ctx->InputDType(\"a\", 0);\n      return Maybe<void>::Ok();\n    });\n\nREGISTER_USER_OP_GRAD(\"bias_add\")\n    .SetGenBackwardOpConfFn([](const user_op::UserOpWrapper& op, user_op::AddOpFn AddOp) {\n      if (op.NeedGenGradTensor4OpInput(\"a\", 0)) {\n        op.BindGradTensorWithOpInput(op.GetGradTensorWithOpOutput(\"out\", 0), \"a\", 0);\n      }\n      if (op.NeedGenGradTensor4OpInput(\"b\", 0)) {\n        const int64_t num_axes = op.TensorDesc4ArgNameAndIndex(\"a\", 0).shape().NumAxes();\n        const int32_t bias_add_axis = op.attr<int32_t>(\"axis\");\n        std::vector<int32_t> reduce_axes_vec;\n        FOR_RANGE(int64_t, i, 0, num_axes) {\n          if (i != bias_add_axis) { reduce_axes_vec.push_back(i); }\n        }\n        user_op::UserOpConfWrapperBuilder builder(op.op_name() + \"_grad\");\n        auto grad_op = builder.Op(\"reduce_sum\")\n                           .Input(\"input_tensor\", op.GetGradTensorWithOpOutput(\"out\", 0))\n                           .Output(\"output_tensor\")\n                           .Attr(\"axis\", reduce_axes_vec)\n                           .Attr(\"keepdims\", false)\n                           .Build();\n        AddOp(grad_op);\n        op.BindGradTensorWithOpInput(grad_op.output(\"output_tensor\", 0), \"b\", 0);\n      }\n    });\n\n}  \/\/ namespace oneflow\n","avg_line_length":42.0588235294,"max_line_length":100,"alphanum_fraction":0.6229370629,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1263,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":14.0,"content":"\/\/ Copyright (c) 2018 The Dash Core developers\n\/\/ Copyright (c) 2019 The BitGreen Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <special\/specialdb.h>\n\nstd::unique_ptr<CSpecialDB> pspecialdb;\n\nCSpecialDB::CSpecialDB(size_t nCacheSize, bool fMemory, bool fWipe) :\n    db(fMemory ? \"\" : (GetDataDir() \/ \"specialdb\"), nCacheSize, fMemory, fWipe),\n    rootBatch(db),\n    rootDBTransaction(db, rootBatch),\n    curDBTransaction(rootDBTransaction, rootDBTransaction)\n{\n}\n\nbool CSpecialDB::CommitRootTransaction()\n{\n    assert(curDBTransaction.IsClean());\n    rootDBTransaction.Commit();\n    bool ret = db.WriteBatch(rootBatch);\n    rootBatch.Clear();\n    return ret;\n}\n\nbool CSpecialDB::VerifyBestBlock(const uint256& hash)\n{\n    \/\/ Make sure specialdb is consistent.\n    \/\/ If we already have best block hash saved, the previous block should match it.\n    uint256 hashBestBlock;\n    bool fHasBestBlock = Read(\"b_b\", hashBestBlock);\n    uint256 hashBlockIndex = fHasBestBlock ? hash : uint256();\n    assert(hashBestBlock == hashBlockIndex);\n\n    return fHasBestBlock;\n}\n\nvoid CSpecialDB::WriteBestBlock(const uint256& hash)\n{\n    Write(\"b_b\", hash);\n}\n","avg_line_length":29.3720930233,"max_line_length":84,"alphanum_fraction":0.7276326207,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3990,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":8.0,"content":"\/*\r\nBullet Continuous Collision Detection and Physics Library\r\nCopyright (c) 2003-2007 Erwin Coumans  http:\/\/continuousphysics.com\/Bullet\/\r\n\r\nThis software is provided 'as-is', without any express or implied warranty.\r\nIn no event will the authors be held liable for any damages arising from the use of this software.\r\nPermission is granted to anyone to use this software for any purpose, \r\nincluding commercial applications, and to alter it and redistribute it freely, \r\nsubject to the following restrictions:\r\n\r\n1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.\r\n2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.\r\n3. This notice may not be removed or altered from any source distribution.\r\n*\/\r\n\r\n#include \"SerializeDemo.h\"\r\n#include \"GlutStuff.h\"\r\n#include \"GLDebugDrawer.h\"\r\n#include \"btBulletDynamicsCommon.h\"\r\n#include \"LinearMath\/btHashMap.h\"\r\n#include \"btBulletFile.h\"\r\n#include \"CommandLineArguments.h\"\r\n\r\n\r\n#ifdef USE_AMD_OPENCL\r\n\r\n\r\n\r\n#include \"btOpenCLUtils.h\"\r\n\r\n#include <LinearMath\/btScalar.h>\r\n\r\ncl_context        g_cxMainContext;\r\ncl_device_id      g_cdDevice;\r\ncl_command_queue  g_cqCommandQue;\r\n\r\n\r\n\/\/ Returns true if OpenCL is initialized properly, false otherwise.\r\nbool initCL( void* glCtx, void* glDC )\r\n{\r\n\tconst char* vendorSDK = btOpenCLUtils::getSdkVendorName();\r\n\tprintf(\"This program was compiled using the %s OpenCL SDK\\n\",vendorSDK);\r\n\r\n    int ciErrNum = 0;\r\n\r\n#ifdef BT_USE_CLEW\r\n    ciErrNum = clewInit( \"OpenCL.dll\" );\r\n    if ( ciErrNum != CLEW_SUCCESS ) {\r\n        return false;\r\n    }\r\n#endif\r\n\r\n#if defined(CL_PLATFORM_MINI_CL)\r\n    cl_device_type deviceType = CL_DEVICE_TYPE_CPU;\r\n#elif defined(CL_PLATFORM_AMD)\r\n    cl_device_type deviceType = CL_DEVICE_TYPE_GPU;\r\n#elif defined(CL_PLATFORM_NVIDIA)\r\n    cl_device_type deviceType = CL_DEVICE_TYPE_GPU;\r\n#else\r\n    cl_device_type deviceType = CL_DEVICE_TYPE_CPU;\r\n#endif\r\n\r\n\tg_cxMainContext = btOpenCLUtils::createContextFromType(deviceType, &ciErrNum, glCtx, glDC);\r\n    oclCHECKERROR(ciErrNum, CL_SUCCESS);\r\n\r\n\tint numDev = btOpenCLUtils::getNumDevices(g_cxMainContext);\r\n\tif (!numDev)\r\n\t\treturn false;\r\n\r\n    g_cdDevice =  btOpenCLUtils::getDevice(g_cxMainContext,0);\r\n    \r\n    btOpenCLDeviceInfo clInfo;\r\n\tbtOpenCLUtils::getDeviceInfo(g_cdDevice,clInfo);\r\n\tbtOpenCLUtils::printDeviceInfo(g_cdDevice);\r\n\r\n    \/\/ create a command-queue\r\n    g_cqCommandQue = clCreateCommandQueue(g_cxMainContext, g_cdDevice, 0, &ciErrNum);\r\n    oclCHECKERROR(ciErrNum, CL_SUCCESS);\r\n\r\n    return true;\r\n}\r\n\r\n#endif \/\/#ifdef USE_AMD_OPENCL\r\n\r\n\t\r\nint main(int argc,char** argv)\r\n{\r\n\tCommandLineArguments arg(argc,argv);\r\n\tchar* filename=0;\r\n\targ.GetCmdLineArgument(\"filename\", filename);\r\n\tbool dumpXml = arg.CheckCmdLineFlag(\"dump_xml\");\r\n\tif (!dumpXml && !filename)\r\n\t{\r\n\t\tprintf(\"There are some optional commandline arguments for this demo:\\n\");\r\n\t\tprintf(\"Load another .bullet file instead of testFile.bullet:\\n\");\r\n\t\tprintf(\"--filename=testfile.bullet\\n\");\r\n\t\tprintf(\"Dump the imported .bullet file to XML\\n\");\r\n\t\tprintf(\"--dump_xml\\n\");\r\n\t\t\r\n\t}\r\n\r\n\t\r\n\t\r\n\tGLDebugDrawer\tgDebugDrawer;\r\n#ifdef USE_AMD_OPENCL\r\n\t\r\n\tbool initialized = initCL(0,0);\r\n\tbtAssert(initialized);\r\n#endif \/\/USE_AMD_OPENCL\r\n\r\n\t\r\n\tSerializeDemo serializeDemo;\r\n\t\r\n\tint mode = 0;\r\n\tif (dumpXml)\r\n\t\tmode |=bParse::FD_VERBOSE_EXPORT_XML;\r\n\tif (filename)\r\n\t\tserializeDemo.setFileName(filename);\r\n\tserializeDemo.setVerboseMode(mode);\r\n\t\r\n\tserializeDemo.initPhysics();\r\n\tserializeDemo.getDynamicsWorld()->setDebugDrawer(&gDebugDrawer);\r\n\r\n\r\n#ifdef CHECK_MEMORY_LEAKS\r\n\tserializeDemo.exitPhysics();\r\n#else\r\n\treturn glutmain(argc, argv,640,480,\"Bullet Physics Demo. http:\/\/bulletphysics.org\",&serializeDemo);\r\n#endif\r\n\t\r\n\t\/\/default glut doesn't return from mainloop\r\n\treturn 0;\r\n}\r\n\r\n","avg_line_length":29.5555555556,"max_line_length":244,"alphanum_fraction":0.7368421053,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":18223,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-4.0","BSD-3-Clause"],"max_stars_count":null,"content":"\/\/ Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\/\/ Unit Test\r\n\r\n\/\/ Copyright (c) 2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n\/\/ This file was modified by Oracle on 2017.\r\n\/\/ Modifications copyright (c) 2017, Oracle and\/or its affiliates.\r\n\/\/ Contributed and\/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n\/\/ Use, modification and distribution is subject to the Boost Software License,\r\n\/\/ Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <string>\r\n\r\n#include <boost\/type_traits\/is_same.hpp>\r\n\r\n#if defined(TEST_WITH_SVG)\r\n#  include <boost\/geometry\/io\/svg\/svg_mapper.hpp>\r\n#endif\r\n\r\n#include <geometry_test_common.hpp>\r\n\r\n\r\n#include <boost\/geometry.hpp>\r\n#include <boost\/geometry\/algorithms\/detail\/overlay\/debug_turn_info.hpp>\r\n#include <boost\/geometry\/geometries\/geometries.hpp>\r\n\r\n\/\/#include <boost\/geometry\/extensions\/algorithms\/inverse.hpp>\r\n\r\n#if defined(TEST_WITH_SVG)\r\n#  include <boost\/geometry\/io\/svg\/svg_mapper.hpp>\r\n#endif\r\n\r\n#include \"multi_overlay_cases.hpp\"\r\n\r\n\r\n#if defined(TEST_WITH_SVG)\r\ntemplate <typename Mapper>\r\nstruct map_visitor\r\n{\r\n    map_visitor(Mapper& mapper)\r\n        : m_mapper(mapper)\r\n        , m_traverse_seq(0)\r\n        , m_do_output(true)\r\n    {}\r\n\r\n    void print(char const* header)\r\n    {}\r\n\r\n    template <typename Turns>\r\n    void print(char const* header, Turns const& turns, int turn_index)\r\n    {\r\n        std::string style = \"fill:rgb(0,0,0);font-family:Arial;font-size:6px\";\r\n        stream(turns, turns[turn_index], turns[turn_index].operations[0], header, style);\r\n    }\r\n\r\n    template <typename Turns>\r\n    void print(char const* header, Turns const& turns, int turn_index, int op_index)\r\n    {\r\n        std::string style = \"fill:rgb(0,0,0);font-family:Arial;font-size:6px\";\r\n        stream(turns, turns[turn_index], turns[turn_index].operations[op_index], header, style);\r\n    }\r\n\r\n    template <typename Turns>\r\n    void visit_turns(int phase, Turns const& turns)\r\n    {\r\n        typedef typename boost::range_value<Turns>::type turn_type;\r\n        int index = 0;\r\n        BOOST_FOREACH(turn_type const& turn, turns)\r\n        {\r\n            switch (phase)\r\n            {\r\n                case 1 :\r\n                    m_mapper.map(turn.point, \"fill:rgb(255,128,0);\"\r\n                            \"stroke:rgb(0,0,0);stroke-width:1\", 3);\r\n                    break;\r\n                case 11 :\r\n                    m_mapper.map(turn.point, \"fill:rgb(92,255,0);\" \/\/ Greenish\r\n                            \"stroke:rgb(0,0,0);stroke-width:1\", 3);\r\n                    break;\r\n                case 21 :\r\n                    m_mapper.map(turn.point, \"fill:rgb(0,128,255);\" \/\/ Blueish\r\n                            \"stroke:rgb(0,0,0);stroke-width:1\", 3);\r\n                    break;\r\n                case 3 :\r\n                    label_turn(index, turn);\r\n                    break;\r\n            }\r\n            index++;\r\n        }\r\n    }\r\n\r\n    template <typename Turns, typename Turn, typename Operation>\r\n    std::string stream_turn_index(Turns const& turns, Turn const& turn, Operation const& op)\r\n    {\r\n        std::ostringstream out;\r\n\r\n        if (turn.cluster_id >= 0)\r\n        {\r\n            out << \"cl=\" << turn.cluster_id << \" \";\r\n        }\r\n\r\n        \/\/ Because turn index is unknown here, and still useful for debugging,\r\n        std::size_t index = 0;\r\n        for (typename Turns::const_iterator it = turns.begin();\r\n           it != turns.end(); ++it, ++index)\r\n        {\r\n          Turn const& t = *it;\r\n          if (&t == &turn)\r\n          {\r\n              out << index;\r\n              break;\r\n          }\r\n        }\r\n\r\n        if (&op == &turn.operations[0]) { out << \"[0]\"; }\r\n        if (&op == &turn.operations[1]) { out << \"[1]\"; }\r\n        return out.str();\r\n    }\r\n\r\n    template <typename Clusters, typename Turns>\r\n    void visit_clusters(Clusters const& clusters, Turns const& turns)\r\n    {\r\n        typedef typename boost::range_value<Turns>::type turn_type;\r\n        int index = 0;\r\n        BOOST_FOREACH(turn_type const& turn, turns)\r\n        {\r\n            if (turn.cluster_id >= 0)\r\n            {\r\n                std::cout << \" TURN: \" << index << \"  part of cluster \"  << turn.cluster_id << std::endl;\r\n            }\r\n            index++;\r\n        }\r\n\r\n        for (typename Clusters::const_iterator it = clusters.begin(); it != clusters.end(); ++it)\r\n        {\r\n            std::cout << \" CLUSTER \" << it->first << \": \";\r\n            for (typename std::set<bg::signed_size_type>::const_iterator sit\r\n                 = it->second.turn_indices.begin();\r\n                 sit != it->second.turn_indices.end(); ++sit)\r\n            {\r\n                std::cout << \" \"  << *sit;\r\n            }\r\n            std::cout << std::endl;\r\n        }\r\n\r\n        std::cout << std::endl;\r\n\r\n    }\r\n\r\n    template <typename Turns, typename Turn, typename Operation>\r\n    void visit_traverse(Turns const& turns, Turn const& turn, Operation const& op, const std::string& header)\r\n    {\r\n        typedef typename boost::range_value<Turns>::type turn_type;\r\n\r\n        if (! m_do_output)\r\n        {\r\n            return;\r\n        }\r\n\r\n        std::cout << \"Visit turn \" << stream_turn_index(turns, turn, op)\r\n                  << \" \" << bg::operation_char(turn.operations[0].operation)\r\n                    << bg::operation_char(turn.operations[1].operation)\r\n                << \" (\" << bg::operation_char(op.operation) << \")\"\r\n                << \" \"  << header << std::endl;\r\n\r\n        \/\/ Uncomment for more detailed debug info in SVG on traversal\r\n        std::string style\r\n                = header == \"Visit\" ? \"fill:rgb(80,80,80)\" : \"fill:rgb(0,0,0)\";\r\n\r\n        style += \";font-family:Arial;font-size:6px\";\r\n\r\n        stream(turns, turn, op, header.substr(0, 1), style);\r\n    }\r\n\r\n    template <typename Turns, typename Turn, typename Operation>\r\n    void visit_traverse_reject(Turns const& turns, Turn const& turn, Operation const& op,\r\n                               bg::detail::overlay::traverse_error_type error)\r\n    {\r\n        if (! m_do_output)\r\n        {\r\n            return;\r\n        }\r\n        std::cout << \"Reject turn \" << stream_turn_index(turns, turn, op)\r\n                  << bg::operation_char(turn.operations[0].operation)\r\n                    << bg::operation_char(turn.operations[1].operation)\r\n                << \" (\" << bg::operation_char(op.operation) << \")\"\r\n                << \" \"  << bg::detail::overlay::traverse_error_string(error) << std::endl;\r\n        \/\/return;\r\n\r\n        std::string style =  \"fill:rgb(255,0,0);font-family:Arial;font-size:7px\";\r\n        stream(turns, turn, op, bg::detail::overlay::traverse_error_string(error), style);\r\n\r\n        m_do_output = false;\r\n    }\r\n\r\n    template <typename Turns, typename Turn, typename Operation>\r\n    void visit_traverse_select_turn_from_cluster(Turns const& turns, Turn const& turn, Operation const& op)\r\n    {\r\n        std::cout << \"Visit turn from cluster \" << stream_turn_index(turns, turn, op)\r\n                  << \" \" << bg::operation_char(turn.operations[0].operation)\r\n                    << bg::operation_char(turn.operations[1].operation)\r\n                << \" (\" << bg::operation_char(op.operation) << \")\"\r\n                << std::endl;\r\n        return;\r\n    }\r\n\r\n    template <typename Turns, typename Turn, typename Operation>\r\n    void stream(Turns const& turns, Turn const& turn, Operation const& op, const std::string& header, const std::string& style)\r\n    {\r\n        std::ostringstream out;\r\n        out << m_traverse_seq++ << \" \" << header\r\n            << \" \" << stream_turn_index(turns, turn, op);\r\n\r\n        out << \" \" << bg::visited_char(op.visited);\r\n\r\n        add_text(turn, out.str(), style);\r\n    }\r\n\r\n    template <typename Turn>\r\n    bool label_operation(Turn const& turn, int index, std::ostream& os)\r\n    {\r\n        os << bg::operation_char(turn.operations[index].operation);\r\n        bool result = false;\r\n        if (! turn.discarded)\r\n        {\r\n            if (turn.operations[index].enriched.next_ip_index != -1)\r\n            {\r\n                os << \"->\" << turn.operations[index].enriched.next_ip_index;\r\n                if (turn.operations[index].enriched.next_ip_index != -1)\r\n                {\r\n                    result = true;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                os << \"->\"  << turn.operations[index].enriched.travels_to_ip_index;\r\n                if (turn.operations[index].enriched.travels_to_ip_index != -1)\r\n                {\r\n                    result = true;\r\n                }\r\n            }\r\n\r\n            os << \" {\" << turn.operations[index].enriched.region_id\r\n               << (turn.operations[index].enriched.isolated ? \" ISO\" : \"\")\r\n               << \"}\";\r\n\r\n            if (! turn.operations[index].enriched.startable)\r\n            {\r\n                os << \"$\";\r\n            }\r\n        }\r\n\r\n        return result;\r\n    }\r\n\r\n    template <typename Turn>\r\n    void label_turn(int index, Turn const& turn)\r\n    {\r\n        std::ostringstream out;\r\n        out << index << \" \";\r\n        if (turn.cluster_id != -1)\r\n        {\r\n            out << \" c=\" << turn.cluster_id << \" \";\r\n        }\r\n        bool lab1 = label_operation(turn, 0, out);\r\n        out << \" \/ \";\r\n        bool lab2 = label_operation(turn, 1, out);\r\n        if (turn.switch_source)\r\n        {\r\n            out << \"#\";\r\n        }\r\n        if (turn.discarded)\r\n        {\r\n            out << \"!\";\r\n        }\r\n        if (turn.has_colocated_both)\r\n        {\r\n            out << \"+\";\r\n        }\r\n        bool const self_turn = bg::detail::overlay::is_self_turn<bg::overlay_union>(turn);\r\n        if (self_turn)\r\n        {\r\n            out << \"@\";\r\n        }\r\n\r\n        std::string font8 = \"font-family:Arial;font-size:6px\";\r\n        std::string font6 = \"font-family:Arial;font-size:4px\";\r\n        std::string style =  \"fill:rgb(0,0,255);\" + font8;\r\n        if (self_turn)\r\n        {\r\n            if (turn.discarded)\r\n            {\r\n                style =  \"fill:rgb(128,28,128);\" + font6;\r\n            }\r\n            else\r\n            {\r\n                style =  \"fill:rgb(255,0,255);\" + font8;\r\n            }\r\n        }\r\n        else if (turn.discarded)\r\n        {\r\n            style =  \"fill:rgb(92,92,92);\" + font6;\r\n        }\r\n        else if (turn.cluster_id != -1)\r\n        {\r\n            style =  \"fill:rgb(0,0,255);\" + font8;\r\n        }\r\n        else if (! lab1 || ! lab2)\r\n        {\r\n            style =  \"fill:rgb(0,0,255);\" + font6;\r\n        }\r\n\r\n        add_text(turn, out.str(), style);\r\n    }\r\n\r\n    template <typename Turn>\r\n    void add_text(Turn const& turn, std::string const& text, std::string const& style)\r\n    {\r\n        int const margin = 5;\r\n        int const lineheight = 6;\r\n        double const half = 0.5;\r\n        double const ten = 10;\r\n\r\n        \/\/ Map characteristics\r\n        \/\/ Create a rounded off point\r\n        std::pair<int, int> p\r\n            = std::make_pair(\r\n                boost::numeric_cast<int>(half\r\n                    + ten * bg::get<0>(turn.point)),\r\n                boost::numeric_cast<int>(half\r\n                    + ten * bg::get<1>(turn.point))\r\n                );\r\n        m_mapper.text(turn.point, text, style, margin, m_offsets[p], lineheight);\r\n        m_offsets[p] += lineheight;\r\n    }\r\n\r\n\r\n    Mapper& m_mapper;\r\n    std::map<std::pair<int, int>, int> m_offsets;\r\n    int m_traverse_seq;\r\n    bool m_do_output;\r\n\r\n};\r\n#endif\r\n\r\ntemplate <typename Geometry, bg::overlay_type OverlayType>\r\nvoid test_overlay(std::string const& caseid,\r\n        std::string const& wkt1, std::string const& wkt2,\r\n        double expected_area,\r\n        std::size_t expected_clip_count,\r\n        std::size_t expected_hole_count)\r\n{\r\n    Geometry g1;\r\n    bg::read_wkt(wkt1, g1);\r\n\r\n    Geometry g2;\r\n    bg::read_wkt(wkt2, g2);\r\n\r\n    \/\/ Reverse if necessary\r\n    bg::correct(g1);\r\n    bg::correct(g2);\r\n\r\n#if defined(TEST_WITH_SVG)\r\n    bool const ccw = bg::point_order<Geometry>::value == bg::counterclockwise;\r\n    bool const open = bg::closure<Geometry>::value == bg::open;\r\n\r\n    std::ostringstream filename;\r\n    filename << \"overlay\"\r\n        << \"_\" << caseid\r\n        << \"_\" << string_from_type<typename bg::coordinate_type<Geometry>::type>::name()\r\n        << (ccw ? \"_ccw\" : \"\")\r\n        << (open ? \"_open\" : \"\")\r\n#ifdef BOOST_GEOMETRY_INCLUDE_SELF_TURNS\r\n        << \"_self\"\r\n#endif\r\n#if defined(BOOST_GEOMETRY_NO_ROBUSTNESS)\r\n        << \"_no_rob\"\r\n#endif\r\n        << \".svg\";\r\n\r\n    std::ofstream svg(filename.str().c_str());\r\n\r\n    typedef bg::svg_mapper<typename bg::point_type<Geometry>::type> svg_mapper;\r\n\r\n    svg_mapper mapper(svg, 500, 500);\r\n    mapper.add(g1);\r\n    mapper.add(g2);\r\n\r\n    \/\/ Input shapes in green (src=0) \/ blue (src=1)\r\n    mapper.map(g1, \"fill-opacity:0.5;fill:rgb(153,204,0);\"\r\n            \"stroke:rgb(153,204,0);stroke-width:3\");\r\n    mapper.map(g2, \"fill-opacity:0.3;fill:rgb(51,51,153);\"\r\n            \"stroke:rgb(51,51,153);stroke-width:3\");\r\n#endif\r\n\r\n\r\n    typedef typename boost::range_value<Geometry>::type geometry_out;\r\n    typedef bg::detail::overlay::overlay\r\n        <\r\n            Geometry, Geometry,\r\n            bg::detail::overlay::do_reverse<bg::point_order<Geometry>::value>::value,\r\n            OverlayType == bg::overlay_difference\r\n            ? ! bg::detail::overlay::do_reverse<bg::point_order<Geometry>::value>::value\r\n            : bg::detail::overlay::do_reverse<bg::point_order<Geometry>::value>::value,\r\n            bg::detail::overlay::do_reverse<bg::point_order<Geometry>::value>::value,\r\n            geometry_out,\r\n            OverlayType\r\n        > overlay;\r\n\r\n    typedef typename bg::strategy::intersection::services::default_strategy\r\n        <\r\n            typename bg::cs_tag<Geometry>::type\r\n        >::type strategy_type;\r\n\r\n    strategy_type strategy;\r\n\r\n    typedef typename bg::rescale_overlay_policy_type\r\n    <\r\n        Geometry,\r\n        Geometry\r\n    >::type rescale_policy_type;\r\n\r\n    rescale_policy_type robust_policy\r\n        = bg::get_rescale_policy<rescale_policy_type>(g1, g2);\r\n\r\n#if defined(TEST_WITH_SVG)\r\n    map_visitor<svg_mapper> visitor(mapper);\r\n#else\r\n    bg::detail::overlay::overlay_null_visitor visitor;\r\n#endif\r\n\r\n    Geometry result;\r\n    overlay::apply(g1, g2, robust_policy, std::back_inserter(result),\r\n                   strategy, visitor);\r\n\r\n    BOOST_CHECK_CLOSE(bg::area(result), expected_area, 0.001);\r\n    BOOST_CHECK_MESSAGE((bg::num_interior_rings(result) == expected_hole_count),\r\n                        caseid\r\n                        << \" hole count: detected: \" << bg::num_interior_rings(result)\r\n                        << \" expected: \"  << expected_hole_count);\r\n    BOOST_CHECK_MESSAGE((result.size() == expected_clip_count),\r\n                        caseid\r\n                        << \" clip count: detected: \" << result.size()\r\n                        << \" expected: \"  << expected_clip_count);\r\n\r\n#if defined(TEST_WITH_SVG)\r\n    mapper.map(result, \"fill-opacity:0.2;stroke-opacity:0.4;fill:rgb(255,0,0);\"\r\n                        \"stroke:rgb(255,0,255);stroke-width:8\");\r\n\r\n#endif\r\n}\r\n\r\n#define TEST_INTERSECTION(caseid, area, clips, holes) (test_overlay<multi_polygon, bg::overlay_intersection>) \\\r\n    ( #caseid \"_int\", caseid[0], caseid[1], area, clips, holes)\r\n#define TEST_UNION(caseid, area, clips, holes) (test_overlay<multi_polygon, bg::overlay_union>) \\\r\n    ( #caseid \"_union\", caseid[0], caseid[1], area, clips, holes)\r\n#define TEST_DIFFERENCE_A(caseid, area, clips, holes) (test_overlay<multi_polygon, bg::overlay_difference>) \\\r\n    ( #caseid \"_diff_a\", caseid[0], caseid[1], area, clips, holes)\r\n#define TEST_DIFFERENCE_B(caseid, area, clips, holes) (test_overlay<multi_polygon, bg::overlay_difference>) \\\r\n    ( #caseid \"_diff_b\", caseid[1], caseid[0], area, clips, holes)\r\n\r\n#define TEST_INTERSECTION_WITH(caseid, index1, index2, area, clips, holes) (test_overlay<multi_polygon, bg::overlay_intersection>) \\\r\n    ( #caseid \"_int_\" #index1 \"_\" #index2, caseid[index1], caseid[index2], area, clips, holes)\r\n#define TEST_UNION_WITH(caseid, index1, index2, area, clips, holes) (test_overlay<multi_polygon, bg::overlay_union>) \\\r\n    ( #caseid \"_union\" #index1 \"_\" #index2, caseid[index1], caseid[index2], area, clips, holes)\r\n\r\ntemplate <typename T, bool Clockwise>\r\nvoid test_all()\r\n{\r\n    typedef bg::model::point<T, 2, bg::cs::cartesian> point_type;\r\n    typedef bg::model::polygon<point_type, Clockwise> polygon;\r\n    typedef bg::model::multi_polygon<polygon> multi_polygon;\r\n\r\n    TEST_UNION(case_multi_simplex, 14.58, 1, 0);\r\n    TEST_INTERSECTION(case_multi_simplex, 6.42, 2, 0);\r\n\r\n    TEST_DIFFERENCE_A(case_multi_simplex, 5.58, 5, 0);\r\n    TEST_DIFFERENCE_B(case_multi_simplex, 2.58, 4, 0);\r\n\r\n    \/\/ Contains 5 clusters, needing immediate selection of next turn\r\n    TEST_UNION_WITH(case_58_multi, 0, 3, 19.8333333, 2, 0);\r\n\r\n    \/\/ Contains many clusters, needing to exclude u\/u turns\r\n    TEST_UNION(case_recursive_boxes_3, 56.5, 17, 6);\r\n\r\n    \/\/ Contains 4 clusters, one of which having 4 turns\r\n    TEST_UNION(case_recursive_boxes_7, 7.0, 2, 0);\r\n\r\n    \/\/ Contains 5 clusters, needing immediate selection of next turn\r\n    TEST_UNION(case_89_multi, 6.0, 1, 0);\r\n\r\n    \/\/ Needs ux\/next_turn_index==-1 to be filtered out\r\n    TEST_INTERSECTION(case_77_multi, 9.0, 5, 0);\r\n    TEST_UNION(case_101_multi, 22.25, 1, 3);\r\n    TEST_INTERSECTION(case_101_multi, 4.75, 4, 0);\r\n\r\n    TEST_INTERSECTION(case_recursive_boxes_11, 1.0, 2, 0);\r\n    TEST_INTERSECTION(case_recursive_boxes_30, 6.0, 4, 0);\r\n\r\n    TEST_UNION(case_recursive_boxes_4, 96.75, 1, 2);\r\n    TEST_INTERSECTION_WITH(case_58_multi, 2, 6, 13.25, 1, 1);\r\n    TEST_INTERSECTION_WITH(case_72_multi, 1, 2, 6.15, 3, 1);\r\n    TEST_UNION(case_recursive_boxes_12, 6.0, 6, 0);\r\n    TEST_UNION(case_recursive_boxes_13, 10.25, 3, 0);\r\n\r\n\r\n\/\/    std::cout\r\n\/\/        << \"    \\\"\"\r\n\/\/        << bg::inverse<multi_polygon>(case_65_multi[0], 1.0)\r\n\/\/        << \"\\\"\" << std::endl;\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n    test_all<double, true>();\r\n\/\/    test_all<double, false>();\r\n    return 0;\r\n }\r\n","avg_line_length":34.644486692,"max_line_length":133,"alphanum_fraction":0.5583054382,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3766,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/\/ Generated by Haxe 4.2.1+bf9ff69\n#include <hxcpp.h>\n\n#ifndef INCLUDED_lime_graphics_opengl_ext_OES_rgb8_rgba8\n#include <lime\/graphics\/opengl\/ext\/OES_rgb8_rgba8.h>\n#endif\n\nHX_DEFINE_STACK_FRAME(_hx_pos_4c7657ea6f006b0a_4_new,\"lime.graphics.opengl.ext.OES_rgb8_rgba8\",\"new\",0x41961de6,\"lime.graphics.opengl.ext.OES_rgb8_rgba8.new\",\"lime\/graphics\/opengl\/ext\/OES_rgb8_rgba8.hx\",4,0xbc116168)\nnamespace lime{\nnamespace graphics{\nnamespace opengl{\nnamespace ext{\n\nvoid OES_rgb8_rgba8_obj::__construct(){\n            \tHX_STACKFRAME(&_hx_pos_4c7657ea6f006b0a_4_new)\nHXLINE(   7)\t\tthis->RGBA8_OES = 32856;\nHXLINE(   6)\t\tthis->RGB8_OES = 32849;\n            \t}\n\nDynamic OES_rgb8_rgba8_obj::__CreateEmpty() { return new OES_rgb8_rgba8_obj; }\n\nvoid *OES_rgb8_rgba8_obj::_hx_vtable = 0;\n\nDynamic OES_rgb8_rgba8_obj::__Create(::hx::DynamicArray inArgs)\n{\n\t::hx::ObjectPtr< OES_rgb8_rgba8_obj > _hx_result = new OES_rgb8_rgba8_obj();\n\t_hx_result->__construct();\n\treturn _hx_result;\n}\n\nbool OES_rgb8_rgba8_obj::_hx_isInstanceOf(int inClassId) {\n\treturn inClassId==(int)0x00000001 || inClassId==(int)0x42ddb87c;\n}\n\n\nOES_rgb8_rgba8_obj::OES_rgb8_rgba8_obj()\n{\n}\n\n::hx::Val OES_rgb8_rgba8_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)\n{\n\tswitch(inName.length) {\n\tcase 8:\n\t\tif (HX_FIELD_EQ(inName,\"RGB8_OES\") ) { return ::hx::Val( RGB8_OES ); }\n\t\tbreak;\n\tcase 9:\n\t\tif (HX_FIELD_EQ(inName,\"RGBA8_OES\") ) { return ::hx::Val( RGBA8_OES ); }\n\t}\n\treturn super::__Field(inName,inCallProp);\n}\n\n::hx::Val OES_rgb8_rgba8_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)\n{\n\tswitch(inName.length) {\n\tcase 8:\n\t\tif (HX_FIELD_EQ(inName,\"RGB8_OES\") ) { RGB8_OES=inValue.Cast< int >(); return inValue; }\n\t\tbreak;\n\tcase 9:\n\t\tif (HX_FIELD_EQ(inName,\"RGBA8_OES\") ) { RGBA8_OES=inValue.Cast< int >(); return inValue; }\n\t}\n\treturn super::__SetField(inName,inValue,inCallProp);\n}\n\nvoid OES_rgb8_rgba8_obj::__GetFields(Array< ::String> &outFields)\n{\n\toutFields->push(HX_(\"RGB8_OES\",a9,3d,a2,bb));\n\toutFields->push(HX_(\"RGBA8_OES\",82,4a,84,a1));\n\tsuper::__GetFields(outFields);\n};\n\n#ifdef HXCPP_SCRIPTABLE\nstatic ::hx::StorageInfo OES_rgb8_rgba8_obj_sMemberStorageInfo[] = {\n\t{::hx::fsInt,(int)offsetof(OES_rgb8_rgba8_obj,RGB8_OES),HX_(\"RGB8_OES\",a9,3d,a2,bb)},\n\t{::hx::fsInt,(int)offsetof(OES_rgb8_rgba8_obj,RGBA8_OES),HX_(\"RGBA8_OES\",82,4a,84,a1)},\n\t{ ::hx::fsUnknown, 0, null()}\n};\nstatic ::hx::StaticInfo *OES_rgb8_rgba8_obj_sStaticStorageInfo = 0;\n#endif\n\nstatic ::String OES_rgb8_rgba8_obj_sMemberFields[] = {\n\tHX_(\"RGB8_OES\",a9,3d,a2,bb),\n\tHX_(\"RGBA8_OES\",82,4a,84,a1),\n\t::String(null()) };\n\n::hx::Class OES_rgb8_rgba8_obj::__mClass;\n\nvoid OES_rgb8_rgba8_obj::__register()\n{\n\tOES_rgb8_rgba8_obj _hx_dummy;\n\tOES_rgb8_rgba8_obj::_hx_vtable = *(void **)&_hx_dummy;\n\t::hx::Static(__mClass) = new ::hx::Class_obj();\n\t__mClass->mName = HX_(\"lime.graphics.opengl.ext.OES_rgb8_rgba8\",f4,f2,33,97);\n\t__mClass->mSuper = &super::__SGetClass();\n\t__mClass->mConstructEmpty = &__CreateEmpty;\n\t__mClass->mConstructArgs = &__Create;\n\t__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;\n\t__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;\n\t__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 \/* sStaticFields *\/);\n\t__mClass->mMembers = ::hx::Class_obj::dupFunctions(OES_rgb8_rgba8_obj_sMemberFields);\n\t__mClass->mCanCast = ::hx::TCanCast< OES_rgb8_rgba8_obj >;\n#ifdef HXCPP_SCRIPTABLE\n\t__mClass->mMemberStorageInfo = OES_rgb8_rgba8_obj_sMemberStorageInfo;\n#endif\n#ifdef HXCPP_SCRIPTABLE\n\t__mClass->mStaticStorageInfo = OES_rgb8_rgba8_obj_sStaticStorageInfo;\n#endif\n\t::hx::_hx_RegisterClass(__mClass->mName, __mClass);\n}\n\n} \/\/ end namespace lime\n} \/\/ end namespace graphics\n} \/\/ end namespace opengl\n} \/\/ end namespace ext\n","avg_line_length":33.0350877193,"max_line_length":216,"alphanum_fraction":0.7466808285,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1903,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\n#include <set>\n#include <string>\n#include <vector>\nusing namespace std;\n\/\/ Given a non-empty string s and a dictionary wordDict containing a list of\n\/\/  non-empty words, determine if s can be segmented into a space-separated\n\/\/  sequence of one or more dictionary words.\n\/\/ ERROR Time Limit Exceeded\nclass Solution {\n    set<string> dict;\n    bool findWordBreak(string s) {\n        if (s.size() == 0)\n            return true;\n        for (int i = 1; i <= s.size(); i++) {\n            if (dict.count(s.substr(0, i)) == 1 && findWordBreak(s.substr(i))) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n  public:\n    bool wordBreak(string s, vector<string> &wordDict) {\n        for (string i : wordDict) {\n            dict.insert(i);\n        }\n        return findWordBreak(s);\n    }\n};\n\n\/\/ Input: s = \"applepenapple\", wordDict = [\"apple\", \"pen\"]\n\/\/ Output: true\n\/\/ \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab\"\n\/\/ [\"a\",\"aa\",\"aaa\",\"aaaa\",\"aaaaa\",\"aaaaaa\",\"aaaaaaa\",\"aaaaaaaa\",\"aaaaaaaaa\",\"aaaaaaaaaa\"]\n\/\/ false\nint main(int argc, char const *argv[]) {\n    \/\/ string s = \"applepenapple\";\n    \/\/ vector<string> wordDict = {\"apple\", \"pen\"};\n    \/\/ string s = \"catsandog\";\n    \/\/ vector<string> wordDict = {\"cats\", \"dog\", \"sand\", \"and\", \"cat\"};\n    string s = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n               \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n               \"aaaaaaaaaaaaaaaaaaaaaaaab\";\n    vector<string> wordDict = {\"a\",         \"aa\",        \"aaa\",     \"aaaa\",\n                               \"aaaaa\",     \"aaaaaa\",    \"aaaaaaa\", \"aaaaaaaa\",\n                               \"aaaaaaaaa\", \"aaaaaaaaaa\"};\n    Solution sol;\n    cout << sol.wordBreak(s, wordDict) << endl;\n    return 0;\n}\n","avg_line_length":36.5961538462,"max_line_length":156,"alphanum_fraction":0.6027325276,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4369,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":null,"content":"\/\/ tea.cpp - modified by Wei Dai from code in the original paper\r\n\r\n#include \"pch.h\"\r\n#include \"tea.h\"\r\n#include \"misc.h\"\r\n\r\nNAMESPACE_BEGIN(CryptoPP_NV_2)\r\n\r\nstatic const word32 DELTA = 0x9e3779b9;\r\ntypedef BlockGetAndPut<word32, BigEndian> Block;\r\n\r\n#define UINT32_CAST(x) ((word32*)(void*)(x))\r\n#define CONST_UINT32_CAST(x) ((const word32*)(const void*)(x))\r\n\r\nvoid TEA::Base::UncheckedSetKey(const byte *userKey, unsigned int length, const NameValuePairs &params)\r\n{\r\n\tAssertValidKeyLength(length);\r\n\r\n\tGetUserKey(BIG_ENDIAN_ORDER, m_k.begin(), 4, userKey, KEYLENGTH);\r\n\tm_limit = GetRoundsAndThrowIfInvalid(params, this) * DELTA;\r\n}\r\n\r\nvoid TEA::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const\r\n{\r\n\tword32 y, z, sum = 0;\r\n\tBlock::Get(inBlock)(y)(z);\r\n\r\n\t\/\/ http:\/\/github.com\/weidai11\/CryptoPP_NV_2\/issues\/503\r\n\twhile (*const_cast<volatile word32*>(&sum) != m_limit)\r\n\t{\r\n\t\tsum += DELTA;\r\n\t\ty += ((z << 4) + m_k[0]) ^ (z + sum) ^ ((z >> 5) + m_k[1]);\r\n\t\tz += ((y << 4) + m_k[2]) ^ (y + sum) ^ ((y >> 5) + m_k[3]);\r\n\t}\r\n\r\n\tBlock::Put(xorBlock, outBlock)(y)(z);\r\n}\r\n\r\nvoid TEA::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const\r\n{\r\n\tword32 y, z, sum = m_limit;\r\n\tBlock::Get(inBlock)(y)(z);\r\n\r\n\t\/\/ http:\/\/github.com\/weidai11\/CryptoPP_NV_2\/issues\/503\r\n\twhile (*const_cast<volatile word32*>(&sum) != 0)\r\n\t{\r\n\t\tz -= ((y << 4) + m_k[2]) ^ (y + sum) ^ ((y >> 5) + m_k[3]);\r\n\t\ty -= ((z << 4) + m_k[0]) ^ (z + sum) ^ ((z >> 5) + m_k[1]);\r\n\t\tsum -= DELTA;\r\n\t}\r\n\r\n\tBlock::Put(xorBlock, outBlock)(y)(z);\r\n}\r\n\r\nvoid XTEA::Base::UncheckedSetKey(const byte *userKey, unsigned int length,  const NameValuePairs &params)\r\n{\r\n\tAssertValidKeyLength(length);\r\n\r\n\tGetUserKey(BIG_ENDIAN_ORDER, m_k.begin(), 4, userKey, KEYLENGTH);\r\n\tm_limit = GetRoundsAndThrowIfInvalid(params, this) * DELTA;\r\n}\r\n\r\nvoid XTEA::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const\r\n{\r\n\tword32 y, z, sum = 0;\r\n\tBlock::Get(inBlock)(y)(z);\r\n\r\n\t\/\/ http:\/\/github.com\/weidai11\/CryptoPP_NV_2\/issues\/503\r\n\twhile (*const_cast<volatile word32*>(&sum) != m_limit)\r\n\t{\r\n\t\ty += ((z<<4 ^ z>>5) + z) ^ (sum + m_k[sum&3]);\r\n\t\tsum += DELTA;\r\n\t\tz += ((y<<4 ^ y>>5) + y) ^ (sum + m_k[sum>>11 & 3]);\r\n\t}\r\n\r\n\tBlock::Put(xorBlock, outBlock)(y)(z);\r\n}\r\n\r\nvoid XTEA::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const\r\n{\r\n\tword32 y, z, sum = m_limit;\r\n\tBlock::Get(inBlock)(y)(z);\r\n\r\n\t\/\/ http:\/\/github.com\/weidai11\/CryptoPP_NV_2\/issues\/503\r\n\twhile (*const_cast<volatile word32*>(&sum) != 0)\r\n\t{\r\n\t\tz -= ((y<<4 ^ y>>5) + y) ^ (sum + m_k[sum>>11 & 3]);\r\n\t\tsum -= DELTA;\r\n\t\ty -= ((z<<4 ^ z>>5) + z) ^ (sum + m_k[sum&3]);\r\n\t}\r\n\r\n\tBlock::Put(xorBlock, outBlock)(y)(z);\r\n}\r\n\r\n#define MX ((z>>5^y<<2)+(y>>3^z<<4))^((sum^y)+(m_k[(p&3)^e]^z))\r\n\r\nvoid BTEA::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const\r\n{\r\n\tCryptoPP_NV_2_UNUSED(xorBlock);\r\n\tCryptoPP_NV_2_ASSERT(IsAlignedOn(inBlock,GetAlignmentOf<word32>()));\r\n\tCryptoPP_NV_2_ASSERT(IsAlignedOn(outBlock,GetAlignmentOf<word32>()));\r\n\r\n\tunsigned int n = m_blockSize \/ 4;\r\n\tword32 *v = UINT32_CAST(outBlock);\r\n\tConditionalByteReverse(BIG_ENDIAN_ORDER, v, CONST_UINT32_CAST(inBlock), m_blockSize);\r\n\r\n\tword32 y, z = v[n-1], e;\r\n\tword32 p, q = 6+52\/n;\r\n\tword32 sum = 0;\r\n\r\n\twhile (q-- > 0)\r\n\t{\r\n\t\tsum += DELTA;\r\n\t\te = sum>>2 & 3;\r\n\t\tfor (p = 0; p < n-1; p++)\r\n\t\t{\r\n\t\t\ty = v[p+1];\r\n\t\t\tz = v[p] += MX;\r\n\t\t}\r\n\t\ty = v[0];\r\n\t\tz = v[n-1] += MX;\r\n\t}\r\n\r\n\tConditionalByteReverse(BIG_ENDIAN_ORDER, v, v, m_blockSize);\r\n}\r\n\r\nvoid BTEA::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const\r\n{\r\n\tCryptoPP_NV_2_UNUSED(xorBlock);\r\n\tCryptoPP_NV_2_ASSERT(IsAlignedOn(inBlock,GetAlignmentOf<word32>()));\r\n\tCryptoPP_NV_2_ASSERT(IsAlignedOn(outBlock,GetAlignmentOf<word32>()));\r\n\r\n\tunsigned int n = m_blockSize \/ 4;\r\n\tword32 *v = UINT32_CAST(outBlock);\r\n\tConditionalByteReverse(BIG_ENDIAN_ORDER, v, CONST_UINT32_CAST(inBlock), m_blockSize);\r\n\r\n\tword32 y = v[0], z, e;\r\n\tword32 p, q = 6+52\/n;\r\n\tword32 sum = q * DELTA;\r\n\r\n\twhile (sum != 0)\r\n\t{\r\n\t\te = sum>>2 & 3;\r\n\t\tfor (p = n-1; p > 0; p--)\r\n\t\t{\r\n\t\t\tz = v[p-1];\r\n\t\t\ty = v[p] -= MX;\r\n\t\t}\r\n\r\n\t\tz = v[n-1];\r\n\t\ty = v[0] -= MX;\r\n\t\tsum -= DELTA;\r\n\t}\r\n\r\n\tConditionalByteReverse(BIG_ENDIAN_ORDER, v, v, m_blockSize);\r\n}\r\n\r\nNAMESPACE_END\r\n","avg_line_length":27.4779874214,"max_line_length":106,"alphanum_fraction":0.6211947814,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":251592,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n * Copyright (c) 2015 Andrew Kelley\n *\n * This file is part of zig, which is MIT licensed.\n * See http:\/\/opensource.org\/licenses\/MIT\n *\/\n#include \"all_types.hpp\"\n#include \"analyze.hpp\"\n#include \"c_tokenizer.hpp\"\n#include \"error.hpp\"\n#include \"ir.hpp\"\n#include \"os.hpp\"\n#include \"translate_c.hpp\"\n#include \"parser.hpp\"\n#include \"zig_clang.h\"\n\n#include <string.h>\n\nstruct Alias {\n    Buf *new_name;\n    Buf *canon_name;\n};\n\nenum TransScopeId {\n    TransScopeIdSwitch,\n    TransScopeIdVar,\n    TransScopeIdBlock,\n    TransScopeIdRoot,\n    TransScopeIdWhile,\n};\n\nstruct TransScope {\n    TransScopeId id;\n    TransScope *parent;\n};\n\nstruct TransScopeSwitch {\n    TransScope base;\n    AstNode *switch_node;\n    uint32_t case_index;\n    bool found_default;\n    Buf *end_label_name;\n};\n\nstruct TransScopeVar {\n    TransScope base;\n    Buf *c_name;\n    Buf *zig_name;\n};\n\nstruct TransScopeBlock {\n    TransScope base;\n    AstNode *node;\n};\n\nstruct TransScopeRoot {\n    TransScope base;\n};\n\nstruct TransScopeWhile {\n    TransScope base;\n    AstNode *node;\n};\n\nstruct Context {\n    AstNode *root;\n    VisibMod visib_mod;\n    bool want_export;\n    HashMap<const void *, AstNode *, ptr_hash, ptr_eq> decl_table;\n    HashMap<Buf *, AstNode *, buf_hash, buf_eql_buf> macro_table;\n    HashMap<Buf *, AstNode *, buf_hash, buf_eql_buf> global_table;\n    ZigClangSourceManager *source_manager;\n    ZigList<Alias> aliases;\n    bool warnings_on;\n\n    CodeGen *codegen;\n    ZigClangASTContext *ctx;\n\n    TransScopeRoot *global_scope;\n    HashMap<Buf *, bool, buf_hash, buf_eql_buf> ptr_params;\n};\n\nenum ResultUsed {\n    ResultUsedNo,\n    ResultUsedYes,\n};\n\nenum TransLRValue {\n    TransLValue,\n    TransRValue,\n};\n\nstatic TransScopeRoot *trans_scope_root_create(Context *c);\nstatic TransScopeWhile *trans_scope_while_create(Context *c, TransScope *parent_scope);\nstatic TransScopeBlock *trans_scope_block_create(Context *c, TransScope *parent_scope);\nstatic TransScopeVar *trans_scope_var_create(Context *c, TransScope *parent_scope, Buf *wanted_name);\nstatic TransScopeSwitch *trans_scope_switch_create(Context *c, TransScope *parent_scope);\n\nstatic TransScopeBlock *trans_scope_block_find(TransScope *scope);\n\nstatic AstNode *resolve_record_decl(Context *c, const ZigClangRecordDecl *record_decl);\nstatic AstNode *resolve_enum_decl(Context *c, const ZigClangEnumDecl *enum_decl);\nstatic AstNode *resolve_typedef_decl(Context *c, const ZigClangTypedefNameDecl *typedef_decl);\n\nstatic int trans_stmt_extra(Context *c, TransScope *scope, const ZigClangStmt *stmt,\n        ResultUsed result_used, TransLRValue lrval,\n        AstNode **out_node, TransScope **out_child_scope,\n        TransScope **out_node_scope);\nstatic TransScope *trans_stmt(Context *c, TransScope *scope, const ZigClangStmt *stmt, AstNode **out_node);\nstatic AstNode *trans_expr(Context *c, ResultUsed result_used, TransScope *scope, const ZigClangExpr *expr, TransLRValue lrval);\nstatic AstNode *trans_type(Context *c, const ZigClangType *ty, ZigClangSourceLocation source_loc);\nstatic AstNode *trans_qual_type(Context *c, ZigClangQualType qt, ZigClangSourceLocation source_loc);\nstatic AstNode *trans_bool_expr(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangExpr *expr, TransLRValue lrval);\nstatic AstNode *trans_ap_value(Context *c, const ZigClangAPValue *ap_value, ZigClangQualType qt,\n        ZigClangSourceLocation source_loc);\nstatic bool c_is_unsigned_integer(Context *c, ZigClangQualType qt);\n\n\nATTRIBUTE_PRINTF(3, 4)\nstatic void emit_warning(Context *c, ZigClangSourceLocation sl, const char *format, ...) {\n    if (!c->warnings_on) {\n        return;\n    }\n\n    va_list ap;\n    va_start(ap, format);\n    Buf *msg = buf_vprintf(format, ap);\n    va_end(ap);\n\n    const char *filename_bytes = ZigClangSourceManager_getFilename(c->source_manager,\n            ZigClangSourceManager_getSpellingLoc(c->source_manager, sl));\n    Buf *path;\n    if (filename_bytes) {\n        path = buf_create_from_str(filename_bytes);\n    } else {\n        path = buf_sprintf(\"(no file)\");\n    }\n    unsigned line = ZigClangSourceManager_getSpellingLineNumber(c->source_manager, sl);\n    unsigned column = ZigClangSourceManager_getSpellingColumnNumber(c->source_manager, sl);\n    fprintf(stderr, \"%s:%u:%u: warning: %s\\n\", buf_ptr(path), line, column, buf_ptr(msg));\n}\n\nstatic void add_global_weak_alias(Context *c, Buf *new_name, Buf *canon_name) {\n    Alias *alias = c->aliases.add_one();\n    alias->new_name = new_name;\n    alias->canon_name = canon_name;\n}\n\nstatic Buf *trans_lookup_zig_symbol(Context *c, TransScope *scope, Buf *c_symbol_name) {\n    while (scope != nullptr) {\n        if (scope->id == TransScopeIdVar) {\n            TransScopeVar *var_scope = (TransScopeVar *)scope;\n            if (buf_eql_buf(var_scope->c_name, c_symbol_name)) {\n                return var_scope->zig_name;\n            }\n        }\n        scope = scope->parent;\n    }\n    return c_symbol_name;\n}\n\nstatic AstNode * trans_create_node(Context *c, NodeType id) {\n    AstNode *node = allocate<AstNode>(1);\n    node->type = id;\n    \/\/ TODO line\/column. mapping to C file??\n    return node;\n}\n\nstatic AstNode *trans_create_node_break(Context *c, Buf *label_name, AstNode *value_node) {\n    AstNode *node = trans_create_node(c, NodeTypeBreak);\n    node->data.break_expr.name = label_name;\n    node->data.break_expr.expr = value_node;\n    return node;\n}\n\nstatic AstNode *trans_create_node_return(Context *c, AstNode *value_node) {\n    AstNode *node = trans_create_node(c, NodeTypeReturnExpr);\n    node->data.return_expr.kind = ReturnKindUnconditional;\n    node->data.return_expr.expr = value_node;\n    return node;\n}\n\nstatic AstNode *trans_create_node_if(Context *c, AstNode *cond_node, AstNode *then_node, AstNode *else_node) {\n    AstNode *node = trans_create_node(c, NodeTypeIfBoolExpr);\n    node->data.if_bool_expr.condition = cond_node;\n    node->data.if_bool_expr.then_block = then_node;\n    node->data.if_bool_expr.else_node = else_node;\n    return node;\n}\n\nstatic AstNode *trans_create_node_float_lit(Context *c, double value) {\n    AstNode *node = trans_create_node(c, NodeTypeFloatLiteral);\n    node->data.float_literal.bigfloat = allocate<BigFloat>(1);\n    bigfloat_init_64(node->data.float_literal.bigfloat, value);\n    return node;\n}\n\nstatic AstNode *trans_create_node_symbol(Context *c, Buf *name) {\n    AstNode *node = trans_create_node(c, NodeTypeSymbol);\n    node->data.symbol_expr.symbol = name;\n    return node;\n}\n\nstatic AstNode *trans_create_node_symbol_str(Context *c, const char *name) {\n    return trans_create_node_symbol(c, buf_create_from_str(name));\n}\n\nstatic AstNode *trans_create_node_builtin_fn_call(Context *c, Buf *name) {\n    AstNode *node = trans_create_node(c, NodeTypeFnCallExpr);\n    node->data.fn_call_expr.fn_ref_expr = trans_create_node_symbol(c, name);\n    node->data.fn_call_expr.modifier = CallModifierBuiltin;\n    return node;\n}\n\nstatic AstNode *trans_create_node_builtin_fn_call_str(Context *c, const char *name) {\n    return trans_create_node_builtin_fn_call(c, buf_create_from_str(name));\n}\n\nstatic AstNode *trans_create_node_opaque(Context *c) {\n    return trans_create_node_builtin_fn_call_str(c, \"OpaqueType\");\n}\n\nstatic AstNode *trans_create_node_cast(Context *c, AstNode *dest_type, AstNode *operand) {\n    AstNode *node = trans_create_node(c, NodeTypeFnCallExpr);\n    node->data.fn_call_expr.fn_ref_expr = trans_create_node_symbol(c, buf_create_from_str(\"as\"));\n    node->data.fn_call_expr.modifier = CallModifierBuiltin;\n    node->data.fn_call_expr.params.append(dest_type);\n    node->data.fn_call_expr.params.append(operand);\n    return node;\n}\n\nstatic AstNode *trans_create_node_fn_call_1(Context *c, AstNode *fn_ref_expr, AstNode *arg1) {\n    AstNode *node = trans_create_node(c, NodeTypeFnCallExpr);\n    node->data.fn_call_expr.fn_ref_expr = fn_ref_expr;\n    node->data.fn_call_expr.params.append(arg1);\n    return node;\n}\n\nstatic AstNode *trans_create_node_field_access(Context *c, AstNode *container, Buf *field_name) {\n    AstNode *node = trans_create_node(c, NodeTypeFieldAccessExpr);\n    if (container->type == NodeTypeSymbol) {\n        assert(container->data.symbol_expr.symbol != nullptr);\n    }\n    node->data.field_access_expr.struct_expr = container;\n    node->data.field_access_expr.field_name = field_name;\n    return node;\n}\n\nstatic AstNode *trans_create_node_field_access_str(Context *c, AstNode *container, const char *field_name) {\n    return trans_create_node_field_access(c, container, buf_create_from_str(field_name));\n}\n\nstatic AstNode *trans_create_node_ptr_deref(Context *c, AstNode *child_node) {\n    AstNode *node = trans_create_node(c, NodeTypePtrDeref);\n    node->data.ptr_deref_expr.target = child_node;\n    return node;\n}\n\nstatic AstNode *trans_create_node_prefix_op(Context *c, PrefixOp op, AstNode *child_node) {\n    AstNode *node = trans_create_node(c, NodeTypePrefixOpExpr);\n    node->data.prefix_op_expr.prefix_op = op;\n    node->data.prefix_op_expr.primary_expr = child_node;\n    return node;\n}\n\nstatic AstNode *trans_create_node_unwrap_null(Context *c, AstNode *child_node) {\n    AstNode *node = trans_create_node(c, NodeTypeUnwrapOptional);\n    node->data.unwrap_optional.expr = child_node;\n    return node;\n}\n\nstatic AstNode *trans_create_node_bin_op(Context *c, AstNode *lhs_node, BinOpType op, AstNode *rhs_node) {\n    AstNode *node = trans_create_node(c, NodeTypeBinOpExpr);\n    node->data.bin_op_expr.op1 = lhs_node;\n    node->data.bin_op_expr.bin_op = op;\n    node->data.bin_op_expr.op2 = rhs_node;\n    return node;\n}\n\nstatic AstNode *maybe_suppress_result(Context *c, ResultUsed result_used, AstNode *node) {\n    if (result_used == ResultUsedYes) return node;\n    return trans_create_node_bin_op(c,\n        trans_create_node_symbol_str(c, \"_\"),\n        BinOpTypeAssign,\n        node);\n}\n\nstatic TokenId ptr_len_to_token_id(PtrLen ptr_len) {\n    switch (ptr_len) {\n        case PtrLenSingle:\n            return TokenIdStar;\n        case PtrLenUnknown:\n            return TokenIdBracketStarBracket;\n        case PtrLenC:\n            return TokenIdBracketStarCBracket;\n    }\n    zig_unreachable();\n}\n\nstatic AstNode *trans_create_node_ptr_type(Context *c, bool is_const, bool is_volatile, AstNode *child_node, PtrLen ptr_len) {\n    AstNode *node = trans_create_node(c, NodeTypePointerType);\n    node->data.pointer_type.star_token = allocate<ZigToken>(1);\n    node->data.pointer_type.star_token->id = ptr_len_to_token_id(ptr_len);\n    node->data.pointer_type.is_const = is_const;\n    node->data.pointer_type.is_volatile = is_volatile;\n    node->data.pointer_type.op_expr = child_node;\n    return node;\n}\n\nstatic AstNode *trans_create_node_addr_of(Context *c, AstNode *child_node) {\n    AstNode *node = trans_create_node(c, NodeTypePrefixOpExpr);\n    node->data.prefix_op_expr.prefix_op = PrefixOpAddrOf;\n    node->data.prefix_op_expr.primary_expr = child_node;\n    return node;\n}\n\nstatic AstNode *trans_create_node_bool(Context *c, bool value) {\n    AstNode *bool_node = trans_create_node(c, NodeTypeBoolLiteral);\n    bool_node->data.bool_literal.value = value;\n    return bool_node;\n}\n\nstatic AstNode *trans_create_node_str_lit_c(Context *c, Buf *buf) {\n    AstNode *node = trans_create_node(c, NodeTypeStringLiteral);\n    node->data.string_literal.buf = buf;\n    node->data.string_literal.c = true;\n    return node;\n}\n\nstatic AstNode *trans_create_node_str_lit_non_c(Context *c, Buf *buf) {\n    AstNode *node = trans_create_node(c, NodeTypeStringLiteral);\n    node->data.string_literal.buf = buf;\n    node->data.string_literal.c = false;\n    return node;\n}\n\nstatic AstNode *trans_create_node_unsigned_negative(Context *c, uint64_t x, bool is_negative) {\n    AstNode *node = trans_create_node(c, NodeTypeIntLiteral);\n    node->data.int_literal.bigint = allocate<BigInt>(1);\n    bigint_init_data(node->data.int_literal.bigint, &x, 1, is_negative);\n    return node;\n}\n\nstatic AstNode *trans_create_node_unsigned(Context *c, uint64_t x) {\n    return trans_create_node_unsigned_negative(c, x, false);\n}\n\nstatic AstNode *trans_create_node_unsigned_negative_type(Context *c, uint64_t x, bool is_negative,\n        const char *type_name)\n{\n    AstNode *lit_node = trans_create_node_unsigned_negative(c, x, is_negative);\n    return trans_create_node_cast(c, trans_create_node_symbol_str(c, type_name), lit_node);\n}\n\nstatic AstNode *trans_create_node_array_type(Context *c, AstNode *size_node, AstNode *child_type_node) {\n    AstNode *node = trans_create_node(c, NodeTypeArrayType);\n    node->data.array_type.size = size_node;\n    node->data.array_type.child_type = child_type_node;\n    return node;\n}\n\nstatic AstNode *trans_create_node_var_decl(Context *c, VisibMod visib_mod, bool is_const, Buf *var_name,\n        AstNode *type_node, AstNode *init_node)\n{\n    AstNode *node = trans_create_node(c, NodeTypeVariableDeclaration);\n    node->data.variable_declaration.visib_mod = visib_mod;\n    node->data.variable_declaration.symbol = var_name;\n    node->data.variable_declaration.is_const = is_const;\n    node->data.variable_declaration.type = type_node;\n    node->data.variable_declaration.expr = init_node;\n    return node;\n}\n\nstatic AstNode *trans_create_node_var_decl_global(Context *c, bool is_const, Buf *var_name, AstNode *type_node,\n        AstNode *init_node)\n{\n    return trans_create_node_var_decl(c, c->visib_mod, is_const, var_name, type_node, init_node);\n}\n\nstatic AstNode *trans_create_node_var_decl_local(Context *c, bool is_const, Buf *var_name, AstNode *type_node,\n        AstNode *init_node)\n{\n    return trans_create_node_var_decl(c, VisibModPrivate, is_const, var_name, type_node, init_node);\n}\n\nstatic AstNode *trans_create_node_inline_fn(Context *c, Buf *fn_name, AstNode *ref_node, AstNode *src_proto_node) {\n    AstNode *fn_def = trans_create_node(c, NodeTypeFnDef);\n    AstNode *fn_proto = trans_create_node(c, NodeTypeFnProto);\n    fn_proto->data.fn_proto.visib_mod = c->visib_mod;\n    fn_proto->data.fn_proto.name = fn_name;\n    fn_proto->data.fn_proto.fn_inline = FnInlineAlways;\n    fn_proto->data.fn_proto.return_type = src_proto_node->data.fn_proto.return_type; \/\/ TODO ok for these to alias?\n\n    fn_def->data.fn_def.fn_proto = fn_proto;\n    fn_proto->data.fn_proto.fn_def_node = fn_def;\n\n    AstNode *unwrap_node = trans_create_node_unwrap_null(c, ref_node);\n    AstNode *fn_call_node = trans_create_node(c, NodeTypeFnCallExpr);\n    fn_call_node->data.fn_call_expr.fn_ref_expr = unwrap_node;\n\n    for (size_t i = 0; i < src_proto_node->data.fn_proto.params.length; i += 1) {\n        AstNode *src_param_node = src_proto_node->data.fn_proto.params.at(i);\n        Buf *param_name = src_param_node->data.param_decl.name;\n        if (!param_name) param_name = buf_sprintf(\"arg%\" ZIG_PRI_usize \"\", i);\n\n        AstNode *dest_param_node = trans_create_node(c, NodeTypeParamDecl);\n        dest_param_node->data.param_decl.name = param_name;\n        dest_param_node->data.param_decl.type = src_param_node->data.param_decl.type;\n        dest_param_node->data.param_decl.is_noalias = src_param_node->data.param_decl.is_noalias;\n        fn_proto->data.fn_proto.params.append(dest_param_node);\n\n        fn_call_node->data.fn_call_expr.params.append(trans_create_node_symbol(c, param_name));\n\n    }\n\n    AstNode *block = trans_create_node(c, NodeTypeBlock);\n    block->data.block.statements.resize(1);\n    block->data.block.statements.items[0] = trans_create_node_return(c, fn_call_node);\n\n    fn_def->data.fn_def.body = block;\n    return fn_def;\n}\n\nstatic AstNode *trans_create_node_grouped_expr(Context *c, AstNode *child) {\n\tAstNode *node = trans_create_node(c, NodeTypeGroupedExpr);\n\tnode->data.grouped_expr = child;\n\treturn node;\n}\n\nstatic AstNode *get_global(Context *c, Buf *name) {\n    {\n        auto entry = c->global_table.maybe_get(name);\n        if (entry) {\n            return entry->value;\n        }\n    }\n    {\n        auto entry = c->macro_table.maybe_get(name);\n        if (entry)\n            return entry->value;\n    }\n    ZigType *type;\n    if (get_primitive_type(c->codegen, name, &type) != ErrorPrimitiveTypeNotFound) {\n        return trans_create_node_symbol(c, name);\n    }\n    return nullptr;\n}\n\nstatic void add_top_level_decl(Context *c, Buf *name, AstNode *node) {\n    c->global_table.put(name, node);\n    c->root->data.container_decl.decls.append(node);\n}\n\nstatic AstNode *add_global_var(Context *c, Buf *var_name, AstNode *value_node) {\n    bool is_const = true;\n    AstNode *type_node = nullptr;\n    AstNode *node = trans_create_node_var_decl_global(c, is_const, var_name, type_node, value_node);\n    add_top_level_decl(c, var_name, node);\n    return node;\n}\n\nstatic AstNode *trans_create_node_apint(Context *c, const ZigClangAPSInt *aps_int) {\n    AstNode *node = trans_create_node(c, NodeTypeIntLiteral);\n    node->data.int_literal.bigint = allocate<BigInt>(1);\n    bool is_negative = ZigClangAPSInt_isSigned(aps_int) && ZigClangAPSInt_isNegative(aps_int);\n    if (!is_negative) {\n        bigint_init_data(node->data.int_literal.bigint,\n                ZigClangAPSInt_getRawData(aps_int),\n                ZigClangAPSInt_getNumWords(aps_int),\n                false);\n        return node;\n    }\n    const ZigClangAPSInt *negated = ZigClangAPSInt_negate(aps_int);\n    bigint_init_data(node->data.int_literal.bigint, ZigClangAPSInt_getRawData(negated),\n            ZigClangAPSInt_getNumWords(negated), true);\n    ZigClangAPSInt_free(negated);\n    return node;\n}\n\nstatic AstNode *trans_create_node_apfloat(Context *c, const ZigClangAPFloat *ap_float) {\n    uint8_t buf[128];\n    size_t written = ZigClangAPFloat_convertToHexString(ap_float, (char *)buf, 0, false,\n            ZigClangAPFloat_roundingMode_NearestTiesToEven);\n    AstNode *node = trans_create_node(c, NodeTypeFloatLiteral);\n    node->data.float_literal.bigfloat = allocate<BigFloat>(1);\n    if (bigfloat_init_buf(node->data.float_literal.bigfloat, buf, written)) {\n        node->data.float_literal.overflow = true;\n    }\n    return node;\n}\n\nstatic const ZigClangType *qual_type_canon(ZigClangQualType qt) {\n    ZigClangQualType canon = ZigClangQualType_getCanonicalType(qt);\n    return ZigClangQualType_getTypePtr(canon);\n}\n\nstatic ZigClangQualType get_expr_qual_type(Context *c, const ZigClangExpr *expr) {\n    \/\/ String literals in C are `char *` but they should really be `const char *`.\n    if (ZigClangExpr_getStmtClass(expr) == ZigClangStmt_ImplicitCastExprClass) {\n        const ZigClangImplicitCastExpr *cast_expr = reinterpret_cast<const ZigClangImplicitCastExpr *>(expr);\n        if (ZigClangImplicitCastExpr_getCastKind(cast_expr) == ZigClangCK_ArrayToPointerDecay) {\n            const ZigClangExpr *sub_expr = ZigClangImplicitCastExpr_getSubExpr(cast_expr);\n            if (ZigClangExpr_getStmtClass(sub_expr) == ZigClangStmt_StringLiteralClass) {\n                ZigClangQualType array_qt = ZigClangExpr_getType(sub_expr);\n                const ZigClangArrayType *array_type = reinterpret_cast<const ZigClangArrayType *>(\n                        ZigClangQualType_getTypePtr(array_qt));\n                ZigClangQualType pointee_qt = ZigClangArrayType_getElementType(array_type);\n                ZigClangQualType_addConst(&pointee_qt);\n                return ZigClangASTContext_getPointerType(c->ctx, pointee_qt);\n            }\n        }\n    }\n    return ZigClangExpr_getType(expr);\n}\n\nstatic ZigClangQualType get_expr_qual_type_before_implicit_cast(Context *c, const ZigClangExpr *expr) {\n    if (ZigClangExpr_getStmtClass(expr) == ZigClangStmt_ImplicitCastExprClass) {\n        const ZigClangImplicitCastExpr *cast_expr = reinterpret_cast<const ZigClangImplicitCastExpr *>(expr);\n        return get_expr_qual_type(c, ZigClangImplicitCastExpr_getSubExpr(cast_expr));\n    }\n    return ZigClangExpr_getType(expr);\n}\n\nstatic AstNode *get_expr_type(Context *c, const ZigClangExpr *expr) {\n    return trans_qual_type(c, get_expr_qual_type(c, expr), ZigClangExpr_getBeginLoc(expr));\n}\n\nstatic bool is_c_void_type(AstNode *node) {\n    return (node->type == NodeTypeSymbol && buf_eql_str(node->data.symbol_expr.symbol, \"c_void\"));\n}\n\nstatic bool qual_type_is_ptr(ZigClangQualType qt) {\n    const ZigClangType *ty = qual_type_canon(qt);\n    return ZigClangType_getTypeClass(ty) == ZigClangType_Pointer;\n}\n\nstatic const ZigClangFunctionProtoType *qual_type_get_fn_proto(ZigClangQualType qt, bool *is_ptr) {\n    const ZigClangType *ty = qual_type_canon(qt);\n    *is_ptr = false;\n\n    if (ZigClangType_getTypeClass(ty) == ZigClangType_Pointer) {\n        *is_ptr = true;\n        ZigClangQualType child_qt = ZigClangType_getPointeeType(ty);\n        ty = ZigClangQualType_getTypePtr(child_qt);\n    }\n\n    if (ZigClangType_getTypeClass(ty) == ZigClangType_FunctionProto) {\n        return reinterpret_cast<const ZigClangFunctionProtoType*>(ty);\n    }\n\n    return nullptr;\n}\n\nstatic bool qual_type_is_fn_ptr(ZigClangQualType qt) {\n    bool is_ptr;\n    if (qual_type_get_fn_proto(qt, &is_ptr)) {\n        return is_ptr;\n    }\n\n    return false;\n}\n\nstatic uint32_t qual_type_int_bit_width(Context *c, const ZigClangQualType qt, ZigClangSourceLocation source_loc) {\n    const ZigClangType *ty = ZigClangQualType_getTypePtr(qt);\n    switch (ZigClangType_getTypeClass(ty)) {\n        case ZigClangType_Builtin:\n            {\n                const ZigClangBuiltinType *builtin_ty = reinterpret_cast<const ZigClangBuiltinType*>(ty);\n                switch (ZigClangBuiltinType_getKind(builtin_ty)) {\n                    case ZigClangBuiltinTypeChar_U:\n                    case ZigClangBuiltinTypeUChar:\n                    case ZigClangBuiltinTypeChar_S:\n                    case ZigClangBuiltinTypeSChar:\n                        return 8;\n                    case ZigClangBuiltinTypeUInt128:\n                    case ZigClangBuiltinTypeInt128:\n                        return 128;\n                    default:\n                        return 0;\n                }\n                zig_unreachable();\n            }\n        case ZigClangType_Typedef:\n            {\n                const ZigClangTypedefType *typedef_ty = reinterpret_cast<const ZigClangTypedefType*>(ty);\n                const ZigClangTypedefNameDecl *typedef_decl = ZigClangTypedefType_getDecl(typedef_ty);\n                const char *type_name = ZigClangDecl_getName_bytes_begin((const ZigClangDecl *)typedef_decl);\n                if (strcmp(type_name, \"uint8_t\") == 0 || strcmp(type_name, \"int8_t\") == 0) {\n                    return 8;\n                } else if (strcmp(type_name, \"uint16_t\") == 0 || strcmp(type_name, \"int16_t\") == 0) {\n                    return 16;\n                } else if (strcmp(type_name, \"uint32_t\") == 0 || strcmp(type_name, \"int32_t\") == 0) {\n                    return 32;\n                } else if (strcmp(type_name, \"uint64_t\") == 0 || strcmp(type_name, \"int64_t\") == 0) {\n                    return 64;\n                } else {\n                    return 0;\n                }\n            }\n        default:\n            return 0;\n    }\n    zig_unreachable();\n}\n\n\nstatic AstNode *qual_type_to_log2_int_ref(Context *c, const ZigClangQualType qt,\n        ZigClangSourceLocation source_loc)\n{\n    uint32_t int_bit_width = qual_type_int_bit_width(c, qt, source_loc);\n    if (int_bit_width != 0) {\n        \/\/ we can perform the log2 now.\n        uint64_t cast_bit_width = log2_u64(int_bit_width);\n        return trans_create_node_symbol(c, buf_sprintf(\"u%\" ZIG_PRI_u64, cast_bit_width));\n    }\n\n    AstNode *zig_type_node = trans_qual_type(c, qt, source_loc);\n\n\/\/    @import(\"std\").math.Log2Int(c_long);\n\/\/\n\/\/    FnCall\n\/\/        FieldAccess\n\/\/            FieldAccess\n\/\/                FnCall (.builtin = true)\n\/\/                    Symbol \"import\"\n\/\/                    ZigClangStringLiteral \"std\"\n\/\/                Symbol \"math\"\n\/\/            Symbol \"Log2Int\"\n\/\/        zig_type_node\n\n    AstNode *import_fn_call = trans_create_node_builtin_fn_call_str(c, \"import\");\n    import_fn_call->data.fn_call_expr.params.append(trans_create_node_str_lit_non_c(c, buf_create_from_str(\"std\")));\n    AstNode *inner_field_access = trans_create_node_field_access_str(c, import_fn_call, \"math\");\n    AstNode *outer_field_access = trans_create_node_field_access_str(c, inner_field_access, \"Log2Int\");\n    AstNode *log2int_fn_call = trans_create_node_fn_call_1(c, outer_field_access, zig_type_node);\n\n    return log2int_fn_call;\n}\n\nstatic bool qual_type_child_is_fn_proto(ZigClangQualType qt) {\n    const ZigClangType *ty = ZigClangQualType_getTypePtr(qt);\n    if (ZigClangType_getTypeClass(ty) == ZigClangType_Paren) {\n        const ZigClangParenType *paren_type = reinterpret_cast<const ZigClangParenType *>(ty);\n        ZigClangQualType inner_type = ZigClangParenType_getInnerType(paren_type);\n        if (ZigClangQualType_getTypeClass(inner_type) == ZigClangType_FunctionProto) {\n            return true;\n        }\n    } else if (ZigClangType_getTypeClass(ty) == ZigClangType_Attributed) {\n        const ZigClangAttributedType *attr_type = reinterpret_cast<const ZigClangAttributedType *>(ty);\n        return qual_type_child_is_fn_proto(ZigClangAttributedType_getEquivalentType(attr_type));\n    }\n    return false;\n}\n\nstatic AstNode* trans_c_ptr_cast(Context *c, ZigClangSourceLocation source_location, ZigClangQualType dest_type,\n                                 ZigClangQualType src_type, AstNode *expr)\n{\n    const ZigClangType *ty = ZigClangQualType_getTypePtr(dest_type);\n    const ZigClangQualType child_type = ZigClangType_getPointeeType(ty);\n\n    AstNode *dest_type_node = trans_type(c, ty, source_location);\n    AstNode *child_type_node = trans_qual_type(c, child_type, source_location);\n\n    \/\/ Implicit downcasting from higher to lower alignment values is forbidden,\n    \/\/ use @alignCast to side-step this problem\n    AstNode *ptrcast_node = trans_create_node_builtin_fn_call_str(c, \"ptrCast\");\n    ptrcast_node->data.fn_call_expr.params.append(dest_type_node);\n\n    if (ZigClangType_isVoidType(qual_type_canon(child_type))) {\n        \/\/ void has 1-byte alignment\n        ptrcast_node->data.fn_call_expr.params.append(expr);\n    } else {\n        AstNode *alignof_node = trans_create_node_builtin_fn_call_str(c, \"alignOf\");\n        alignof_node->data.fn_call_expr.params.append(child_type_node);\n        AstNode *aligncast_node = trans_create_node_builtin_fn_call_str(c, \"alignCast\");\n        aligncast_node->data.fn_call_expr.params.append(alignof_node);\n        aligncast_node->data.fn_call_expr.params.append(expr);\n\n        ptrcast_node->data.fn_call_expr.params.append(aligncast_node);\n    }\n\n    return ptrcast_node;\n}\n\nstatic AstNode* trans_c_cast(Context *c, ZigClangSourceLocation source_location, ZigClangQualType dest_type,\n        ZigClangQualType src_type, AstNode *expr)\n{\n    \/\/ The only way void pointer casts are valid C code, is if\n    \/\/ the value of the expression is ignored. We therefore just\n    \/\/ return the expr, and let the system that ignores values\n    \/\/ translate this correctly.\n    if (ZigClangType_isVoidType(qual_type_canon(dest_type))) {\n        return expr;\n    }\n    if (ZigClangQualType_eq(dest_type, src_type)) {\n        return expr;\n    }\n    if (qual_type_is_ptr(dest_type) && qual_type_is_ptr(src_type)) {\n        return trans_c_ptr_cast(c, source_location, dest_type, src_type, expr);\n    }\n    if (c_is_unsigned_integer(c, dest_type) && qual_type_is_ptr(src_type)) {\n        AstNode *addr_node = trans_create_node_builtin_fn_call_str(c, \"ptrToInt\");\n        addr_node->data.fn_call_expr.params.append(expr);\n        return trans_create_node_cast(c, trans_qual_type(c, dest_type, source_location), addr_node);\n    }\n    if (c_is_unsigned_integer(c, src_type) && qual_type_is_ptr(dest_type)) {\n        AstNode *ptr_node = trans_create_node_builtin_fn_call_str(c, \"intToPtr\");\n        ptr_node->data.fn_call_expr.params.append(trans_qual_type(c, dest_type, source_location));\n        ptr_node->data.fn_call_expr.params.append(expr);\n        return ptr_node;\n    }\n    \/\/ TODO: maybe widen to increase size\n    \/\/ TODO: maybe bitcast to change sign\n    \/\/ TODO: maybe truncate to reduce size\n    return trans_create_node_cast(c, trans_qual_type(c, dest_type, source_location), expr);\n}\n\nstatic bool c_is_signed_integer(Context *c, ZigClangQualType qt) {\n    const ZigClangType *c_type = qual_type_canon(qt);\n    if (ZigClangType_getTypeClass(c_type) != ZigClangType_Builtin)\n        return false;\n    const ZigClangBuiltinType *builtin_ty = reinterpret_cast<const ZigClangBuiltinType*>(c_type);\n    switch (ZigClangBuiltinType_getKind(builtin_ty)) {\n        case ZigClangBuiltinTypeSChar:\n        case ZigClangBuiltinTypeShort:\n        case ZigClangBuiltinTypeInt:\n        case ZigClangBuiltinTypeLong:\n        case ZigClangBuiltinTypeLongLong:\n        case ZigClangBuiltinTypeInt128:\n        case ZigClangBuiltinTypeWChar_S:\n            return true;\n        default:\n            return false;\n    }\n}\n\nstatic bool c_is_unsigned_integer(Context *c, ZigClangQualType qt) {\n    const ZigClangType *c_type = qual_type_canon(qt);\n    if (ZigClangType_getTypeClass(c_type) != ZigClangType_Builtin)\n        return false;\n    const ZigClangBuiltinType *builtin_ty = reinterpret_cast<const ZigClangBuiltinType*>(c_type);\n    switch (ZigClangBuiltinType_getKind(builtin_ty)) {\n        case ZigClangBuiltinTypeChar_U:\n        case ZigClangBuiltinTypeUChar:\n        case ZigClangBuiltinTypeChar_S:\n        case ZigClangBuiltinTypeUShort:\n        case ZigClangBuiltinTypeUInt:\n        case ZigClangBuiltinTypeULong:\n        case ZigClangBuiltinTypeULongLong:\n        case ZigClangBuiltinTypeUInt128:\n        case ZigClangBuiltinTypeWChar_U:\n            return true;\n        default:\n            return false;\n    }\n}\n\nstatic bool c_is_builtin_type(Context *c, ZigClangQualType qt, ZigClangBuiltinTypeKind kind) {\n    const ZigClangType *c_type = qual_type_canon(qt);\n    if (ZigClangType_getTypeClass(c_type) != ZigClangType_Builtin)\n        return false;\n    const ZigClangBuiltinType *builtin_ty = reinterpret_cast<const ZigClangBuiltinType*>(c_type);\n    return ZigClangBuiltinType_getKind(builtin_ty) == kind;\n}\n\nstatic bool c_is_float(Context *c, ZigClangQualType qt) {\n    const ZigClangType *c_type = ZigClangQualType_getTypePtr(qt);\n    if (ZigClangType_getTypeClass(c_type) != ZigClangType_Builtin)\n        return false;\n    const ZigClangBuiltinType *builtin_ty = reinterpret_cast<const ZigClangBuiltinType*>(c_type);\n    switch (ZigClangBuiltinType_getKind(builtin_ty)) {\n        case ZigClangBuiltinTypeHalf:\n        case ZigClangBuiltinTypeFloat:\n        case ZigClangBuiltinTypeDouble:\n        case ZigClangBuiltinTypeFloat128:\n        case ZigClangBuiltinTypeLongDouble:\n            return true;\n        default:\n            return false;\n    }\n}\n\nstatic bool qual_type_has_wrapping_overflow(Context *c, ZigClangQualType qt) {\n    if (c_is_signed_integer(c, qt) || c_is_float(c, qt)) {\n        \/\/ float and signed integer overflow is undefined behavior.\n        return false;\n    } else {\n        \/\/ unsigned integer overflow wraps around.\n        return true;\n    }\n}\n\nstatic bool type_is_function(Context *c, const ZigClangType *ty, ZigClangSourceLocation source_loc) {\n    switch (ZigClangType_getTypeClass(ty)) {\n        case ZigClangType_FunctionProto:\n        case ZigClangType_FunctionNoProto:\n            return true;\n        case ZigClangType_Elaborated: {\n            const ZigClangElaboratedType *elaborated_ty = reinterpret_cast<const ZigClangElaboratedType*>(ty);\n            ZigClangQualType qt = ZigClangElaboratedType_getNamedType(elaborated_ty);\n            return type_is_function(c, ZigClangQualType_getTypePtr(qt), source_loc);\n        }\n        case ZigClangType_Typedef: {\n            const ZigClangTypedefType *typedef_ty = reinterpret_cast<const ZigClangTypedefType*>(ty);\n            const ZigClangTypedefNameDecl *typedef_decl = ZigClangTypedefType_getDecl(typedef_ty);\n            ZigClangQualType underlying_type = ZigClangTypedefNameDecl_getUnderlyingType(typedef_decl);\n            return type_is_function(c, ZigClangQualType_getTypePtr(underlying_type), source_loc);\n        }\n        default:\n            return false;\n    }\n}\n\nstatic bool type_is_opaque(Context *c, const ZigClangType *ty, ZigClangSourceLocation source_loc) {\n    switch (ZigClangType_getTypeClass(ty)) {\n        case ZigClangType_Builtin: {\n            const ZigClangBuiltinType *builtin_ty = reinterpret_cast<const ZigClangBuiltinType*>(ty);\n            return ZigClangBuiltinType_getKind(builtin_ty) == ZigClangBuiltinTypeVoid;\n        }\n        case ZigClangType_Record: {\n            const ZigClangRecordType *record_ty = reinterpret_cast<const ZigClangRecordType*>(ty);\n            const ZigClangRecordDecl *record_decl = ZigClangRecordType_getDecl(record_ty);\n            const ZigClangRecordDecl *record_def = ZigClangRecordDecl_getDefinition(record_decl);\n            if (record_def == nullptr) {\n                return true;\n            }\n            for (ZigClangRecordDecl_field_iterator it = ZigClangRecordDecl_field_begin(record_def),\n                    it_end = ZigClangRecordDecl_field_end(record_def);\n                    ZigClangRecordDecl_field_iterator_neq(it, it_end);\n                    it = ZigClangRecordDecl_field_iterator_next(it))\n            {\n                const ZigClangFieldDecl *field_decl = ZigClangRecordDecl_field_iterator_deref(it);\n\n                if (ZigClangFieldDecl_isBitField(field_decl)) {\n                    return true;\n                }\n            }\n            return false;\n        }\n        case ZigClangType_Elaborated: {\n            const ZigClangElaboratedType *elaborated_ty = reinterpret_cast<const ZigClangElaboratedType*>(ty);\n            ZigClangQualType qt = ZigClangElaboratedType_getNamedType(elaborated_ty);\n            return type_is_opaque(c, ZigClangQualType_getTypePtr(qt), source_loc);\n        }\n        case ZigClangType_Typedef: {\n            const ZigClangTypedefType *typedef_ty = reinterpret_cast<const ZigClangTypedefType*>(ty);\n            const ZigClangTypedefNameDecl *typedef_decl = ZigClangTypedefType_getDecl(typedef_ty);\n            ZigClangQualType underlying_type = ZigClangTypedefNameDecl_getUnderlyingType(typedef_decl);\n            return type_is_opaque(c, ZigClangQualType_getTypePtr(underlying_type), source_loc);\n        }\n        default:\n            return false;\n    }\n}\n\nstatic AstNode *trans_type(Context *c, const ZigClangType *ty, ZigClangSourceLocation source_loc) {\n    switch (ZigClangType_getTypeClass(ty)) {\n        case ZigClangType_Builtin:\n            {\n                const ZigClangBuiltinType *builtin_ty = reinterpret_cast<const ZigClangBuiltinType *>(ty);\n                switch (ZigClangBuiltinType_getKind(builtin_ty)) {\n                    case ZigClangBuiltinTypeVoid:\n                        return trans_create_node_symbol_str(c, \"c_void\");\n                    case ZigClangBuiltinTypeBool:\n                        return trans_create_node_symbol_str(c, \"bool\");\n                    case ZigClangBuiltinTypeChar_U:\n                    case ZigClangBuiltinTypeUChar:\n                    case ZigClangBuiltinTypeChar_S:\n                    case ZigClangBuiltinTypeChar8:\n                        return trans_create_node_symbol_str(c, \"u8\");\n                    case ZigClangBuiltinTypeSChar:\n                        return trans_create_node_symbol_str(c, \"i8\");\n                    case ZigClangBuiltinTypeUShort:\n                        return trans_create_node_symbol_str(c, \"c_ushort\");\n                    case ZigClangBuiltinTypeUInt:\n                        return trans_create_node_symbol_str(c, \"c_uint\");\n                    case ZigClangBuiltinTypeULong:\n                        return trans_create_node_symbol_str(c, \"c_ulong\");\n                    case ZigClangBuiltinTypeULongLong:\n                        return trans_create_node_symbol_str(c, \"c_ulonglong\");\n                    case ZigClangBuiltinTypeShort:\n                        return trans_create_node_symbol_str(c, \"c_short\");\n                    case ZigClangBuiltinTypeInt:\n                        return trans_create_node_symbol_str(c, \"c_int\");\n                    case ZigClangBuiltinTypeLong:\n                        return trans_create_node_symbol_str(c, \"c_long\");\n                    case ZigClangBuiltinTypeLongLong:\n                        return trans_create_node_symbol_str(c, \"c_longlong\");\n                    case ZigClangBuiltinTypeUInt128:\n                        return trans_create_node_symbol_str(c, \"u128\");\n                    case ZigClangBuiltinTypeInt128:\n                        return trans_create_node_symbol_str(c, \"i128\");\n                    case ZigClangBuiltinTypeFloat:\n                        return trans_create_node_symbol_str(c, \"f32\");\n                    case ZigClangBuiltinTypeDouble:\n                        return trans_create_node_symbol_str(c, \"f64\");\n                    case ZigClangBuiltinTypeFloat128:\n                        return trans_create_node_symbol_str(c, \"f128\");\n                    case ZigClangBuiltinTypeFloat16:\n                        return trans_create_node_symbol_str(c, \"f16\");\n                    case ZigClangBuiltinTypeLongDouble:\n                        return trans_create_node_symbol_str(c, \"c_longdouble\");\n                    case ZigClangBuiltinTypeWChar_U:\n                    case ZigClangBuiltinTypeChar16:\n                    case ZigClangBuiltinTypeChar32:\n                    case ZigClangBuiltinTypeWChar_S:\n                    case ZigClangBuiltinTypeHalf:\n                    case ZigClangBuiltinTypeNullPtr:\n                    case ZigClangBuiltinTypeObjCId:\n                    case ZigClangBuiltinTypeObjCClass:\n                    case ZigClangBuiltinTypeObjCSel:\n                    case ZigClangBuiltinTypeOMPArraySection:\n                    case ZigClangBuiltinTypeDependent:\n                    case ZigClangBuiltinTypeOverload:\n                    case ZigClangBuiltinTypeBoundMember:\n                    case ZigClangBuiltinTypePseudoObject:\n                    case ZigClangBuiltinTypeUnknownAny:\n                    case ZigClangBuiltinTypeBuiltinFn:\n                    case ZigClangBuiltinTypeARCUnbridgedCast:\n                    case ZigClangBuiltinTypeShortAccum:\n                    case ZigClangBuiltinTypeAccum:\n                    case ZigClangBuiltinTypeLongAccum:\n                    case ZigClangBuiltinTypeUShortAccum:\n                    case ZigClangBuiltinTypeUAccum:\n                    case ZigClangBuiltinTypeULongAccum:\n\n                    case ZigClangBuiltinTypeOCLImage1dRO:\n                    case ZigClangBuiltinTypeOCLImage1dArrayRO:\n                    case ZigClangBuiltinTypeOCLImage1dBufferRO:\n                    case ZigClangBuiltinTypeOCLImage2dRO:\n                    case ZigClangBuiltinTypeOCLImage2dArrayRO:\n                    case ZigClangBuiltinTypeOCLImage2dDepthRO:\n                    case ZigClangBuiltinTypeOCLImage2dArrayDepthRO:\n                    case ZigClangBuiltinTypeOCLImage2dMSAARO:\n                    case ZigClangBuiltinTypeOCLImage2dArrayMSAARO:\n                    case ZigClangBuiltinTypeOCLImage2dMSAADepthRO:\n                    case ZigClangBuiltinTypeOCLImage2dArrayMSAADepthRO:\n                    case ZigClangBuiltinTypeOCLImage3dRO:\n                    case ZigClangBuiltinTypeOCLImage1dWO:\n                    case ZigClangBuiltinTypeOCLImage1dArrayWO:\n                    case ZigClangBuiltinTypeOCLImage1dBufferWO:\n                    case ZigClangBuiltinTypeOCLImage2dWO:\n                    case ZigClangBuiltinTypeOCLImage2dArrayWO:\n                    case ZigClangBuiltinTypeOCLImage2dDepthWO:\n                    case ZigClangBuiltinTypeOCLImage2dArrayDepthWO:\n                    case ZigClangBuiltinTypeOCLImage2dMSAAWO:\n                    case ZigClangBuiltinTypeOCLImage2dArrayMSAAWO:\n                    case ZigClangBuiltinTypeOCLImage2dMSAADepthWO:\n                    case ZigClangBuiltinTypeOCLImage2dArrayMSAADepthWO:\n                    case ZigClangBuiltinTypeOCLImage3dWO:\n                    case ZigClangBuiltinTypeOCLImage1dRW:\n                    case ZigClangBuiltinTypeOCLImage1dArrayRW:\n                    case ZigClangBuiltinTypeOCLImage1dBufferRW:\n                    case ZigClangBuiltinTypeOCLImage2dRW:\n                    case ZigClangBuiltinTypeOCLImage2dArrayRW:\n                    case ZigClangBuiltinTypeOCLImage2dDepthRW:\n                    case ZigClangBuiltinTypeOCLImage2dArrayDepthRW:\n                    case ZigClangBuiltinTypeOCLImage2dMSAARW:\n                    case ZigClangBuiltinTypeOCLImage2dArrayMSAARW:\n                    case ZigClangBuiltinTypeOCLImage2dMSAADepthRW:\n                    case ZigClangBuiltinTypeOCLImage2dArrayMSAADepthRW:\n                    case ZigClangBuiltinTypeOCLImage3dRW:\n                    case ZigClangBuiltinTypeOCLSampler:\n                    case ZigClangBuiltinTypeOCLEvent:\n                    case ZigClangBuiltinTypeOCLClkEvent:\n                    case ZigClangBuiltinTypeOCLQueue:\n                    case ZigClangBuiltinTypeOCLReserveID:\n                    case ZigClangBuiltinTypeShortFract:\n                    case ZigClangBuiltinTypeFract:\n                    case ZigClangBuiltinTypeLongFract:\n                    case ZigClangBuiltinTypeUShortFract:\n                    case ZigClangBuiltinTypeUFract:\n                    case ZigClangBuiltinTypeULongFract:\n                    case ZigClangBuiltinTypeSatShortAccum:\n                    case ZigClangBuiltinTypeSatAccum:\n                    case ZigClangBuiltinTypeSatLongAccum:\n                    case ZigClangBuiltinTypeSatUShortAccum:\n                    case ZigClangBuiltinTypeSatUAccum:\n                    case ZigClangBuiltinTypeSatULongAccum:\n                    case ZigClangBuiltinTypeSatShortFract:\n                    case ZigClangBuiltinTypeSatFract:\n                    case ZigClangBuiltinTypeSatLongFract:\n                    case ZigClangBuiltinTypeSatUShortFract:\n                    case ZigClangBuiltinTypeSatUFract:\n                    case ZigClangBuiltinTypeSatULongFract:\n                    case ZigClangBuiltinTypeOCLIntelSubgroupAVCMcePayload:\n                    case ZigClangBuiltinTypeOCLIntelSubgroupAVCImePayload:\n                    case ZigClangBuiltinTypeOCLIntelSubgroupAVCRefPayload:\n                    case ZigClangBuiltinTypeOCLIntelSubgroupAVCSicPayload:\n                    case ZigClangBuiltinTypeOCLIntelSubgroupAVCMceResult:\n                    case ZigClangBuiltinTypeOCLIntelSubgroupAVCImeResult:\n                    case ZigClangBuiltinTypeOCLIntelSubgroupAVCRefResult:\n                    case ZigClangBuiltinTypeOCLIntelSubgroupAVCSicResult:\n                    case ZigClangBuiltinTypeOCLIntelSubgroupAVCImeResultSingleRefStreamout:\n                    case ZigClangBuiltinTypeOCLIntelSubgroupAVCImeResultDualRefStreamout:\n                    case ZigClangBuiltinTypeOCLIntelSubgroupAVCImeSingleRefStreamin:\n                    case ZigClangBuiltinTypeOCLIntelSubgroupAVCImeDualRefStreamin:\n                        emit_warning(c, source_loc, \"unsupported builtin type\");\n                        return nullptr;\n                }\n                break;\n            }\n        case ZigClangType_Pointer:\n            {\n                ZigClangQualType child_qt = ZigClangType_getPointeeType(ty);\n                AstNode *child_node = trans_qual_type(c, child_qt, source_loc);\n                if (child_node == nullptr) {\n                    emit_warning(c, source_loc, \"pointer to unsupported type\");\n                    return nullptr;\n                }\n\n                if (qual_type_child_is_fn_proto(child_qt)) {\n                    return trans_create_node_prefix_op(c, PrefixOpOptional, child_node);\n                }\n\n                if (type_is_function(c, ZigClangQualType_getTypePtr(child_qt), source_loc)) {\n                    return trans_create_node_prefix_op(c, PrefixOpOptional, child_node);\n                } else if (type_is_opaque(c, ZigClangQualType_getTypePtr(child_qt), source_loc)) {\n                    AstNode *pointer_node = trans_create_node_ptr_type(c,\n                            ZigClangQualType_isConstQualified(child_qt),\n                            ZigClangQualType_isVolatileQualified(child_qt),\n                            child_node, PtrLenSingle);\n                    return trans_create_node_prefix_op(c, PrefixOpOptional, pointer_node);\n                } else {\n                    return trans_create_node_ptr_type(c,\n                            ZigClangQualType_isConstQualified(child_qt),\n                            ZigClangQualType_isVolatileQualified(child_qt),\n                            child_node, PtrLenC);\n                }\n            }\n        case ZigClangType_Typedef:\n            {\n                const ZigClangTypedefType *typedef_ty = reinterpret_cast<const ZigClangTypedefType*>(ty);\n                const ZigClangTypedefNameDecl *typedef_decl = ZigClangTypedefType_getDecl(typedef_ty);\n                return resolve_typedef_decl(c, typedef_decl);\n            }\n        case ZigClangType_Elaborated:\n            {\n                const ZigClangElaboratedType *elaborated_ty = reinterpret_cast<const ZigClangElaboratedType*>(ty);\n                switch (ZigClangElaboratedType_getKeyword(elaborated_ty)) {\n                    case ZigClangETK_Struct:\n                    case ZigClangETK_Enum:\n                    case ZigClangETK_Union:\n                        return trans_qual_type(c, ZigClangElaboratedType_getNamedType(elaborated_ty), source_loc);\n                    case ZigClangETK_Interface:\n                    case ZigClangETK_Class:\n                    case ZigClangETK_Typename:\n                    case ZigClangETK_None:\n                        emit_warning(c, source_loc, \"unsupported elaborated type\");\n                        return nullptr;\n                }\n            }\n        case ZigClangType_FunctionProto:\n        case ZigClangType_FunctionNoProto:\n            {\n                const ZigClangFunctionType *fn_ty = reinterpret_cast<const ZigClangFunctionType*>(ty);\n\n                AstNode *proto_node = trans_create_node(c, NodeTypeFnProto);\n                switch (ZigClangFunctionType_getCallConv(fn_ty)) {\n                    case ZigClangCallingConv_C:           \/\/ __attribute__((cdecl))\n                        proto_node->data.fn_proto.cc = CallingConventionC;\n                        proto_node->data.fn_proto.is_extern = true;\n                        break;\n                    case ZigClangCallingConv_X86StdCall:  \/\/ __attribute__((stdcall))\n                        proto_node->data.fn_proto.cc = CallingConventionStdcall;\n                        break;\n                    case ZigClangCallingConv_X86FastCall: \/\/ __attribute__((fastcall))\n                        emit_warning(c, source_loc, \"unsupported calling convention: x86 fastcall\");\n                        return nullptr;\n                    case ZigClangCallingConv_X86ThisCall: \/\/ __attribute__((thiscall))\n                        emit_warning(c, source_loc, \"unsupported calling convention: x86 thiscall\");\n                        return nullptr;\n                    case ZigClangCallingConv_X86VectorCall: \/\/ __attribute__((vectorcall))\n                        emit_warning(c, source_loc, \"unsupported calling convention: x86 vectorcall\");\n                        return nullptr;\n                    case ZigClangCallingConv_X86Pascal:   \/\/ __attribute__((pascal))\n                        emit_warning(c, source_loc, \"unsupported calling convention: x86 pascal\");\n                        return nullptr;\n                    case ZigClangCallingConv_Win64: \/\/ __attribute__((ms_abi))\n                        emit_warning(c, source_loc, \"unsupported calling convention: win64\");\n                        return nullptr;\n                    case ZigClangCallingConv_X86_64SysV:  \/\/ __attribute__((sysv_abi))\n                        emit_warning(c, source_loc, \"unsupported calling convention: x86 64sysv\");\n                        return nullptr;\n                    case ZigClangCallingConv_X86RegCall:\n                        emit_warning(c, source_loc, \"unsupported calling convention: x86 reg\");\n                        return nullptr;\n                    case ZigClangCallingConv_AAPCS:       \/\/ __attribute__((pcs(\"aapcs\")))\n                        emit_warning(c, source_loc, \"unsupported calling convention: aapcs\");\n                        return nullptr;\n                    case ZigClangCallingConv_AAPCS_VFP:   \/\/ __attribute__((pcs(\"aapcs-vfp\")))\n                        emit_warning(c, source_loc, \"unsupported calling convention: aapcs-vfp\");\n                        return nullptr;\n                    case ZigClangCallingConv_IntelOclBicc: \/\/ __attribute__((intel_ocl_bicc))\n                        emit_warning(c, source_loc, \"unsupported calling convention: intel_ocl_bicc\");\n                        return nullptr;\n                    case ZigClangCallingConv_SpirFunction: \/\/ default for OpenCL functions on SPIR target\n                        emit_warning(c, source_loc, \"unsupported calling convention: SPIR function\");\n                        return nullptr;\n                    case ZigClangCallingConv_OpenCLKernel:\n                        emit_warning(c, source_loc, \"unsupported calling convention: OpenCLKernel\");\n                        return nullptr;\n                    case ZigClangCallingConv_Swift:\n                        emit_warning(c, source_loc, \"unsupported calling convention: Swift\");\n                        return nullptr;\n                    case ZigClangCallingConv_PreserveMost:\n                        emit_warning(c, source_loc, \"unsupported calling convention: PreserveMost\");\n                        return nullptr;\n                    case ZigClangCallingConv_PreserveAll:\n                        emit_warning(c, source_loc, \"unsupported calling convention: PreserveAll\");\n                        return nullptr;\n                    case ZigClangCallingConv_AArch64VectorCall:\n                        emit_warning(c, source_loc, \"unsupported calling convention: AArch64VectorCall\");\n                        return nullptr;\n                }\n\n                if (ZigClangFunctionType_getNoReturnAttr(fn_ty)) {\n                    proto_node->data.fn_proto.return_type = trans_create_node_symbol_str(c, \"noreturn\");\n                } else {\n                    proto_node->data.fn_proto.return_type = trans_qual_type(c,\n                            ZigClangFunctionType_getReturnType(fn_ty), source_loc);\n                    if (proto_node->data.fn_proto.return_type == nullptr) {\n                        emit_warning(c, source_loc, \"unsupported function proto return type\");\n                        return nullptr;\n                    }\n                    \/\/ convert c_void to actual void (only for return type)\n                    \/\/ we do want to look at the AstNode instead of ZigClangQualType, because\n                    \/\/ if they do something like:\n                    \/\/     typedef Foo void;\n                    \/\/     void foo(void) -> Foo;\n                    \/\/ we want to keep the return type AST node.\n                    if (is_c_void_type(proto_node->data.fn_proto.return_type)) {\n                        proto_node->data.fn_proto.return_type = trans_create_node_symbol_str(c, \"void\");\n                    }\n                }\n\n                \/\/emit_warning(c, source_loc, \"TODO figure out fn prototype fn name\");\n                const char *fn_name = nullptr;\n                if (fn_name != nullptr) {\n                    proto_node->data.fn_proto.name = buf_create_from_str(fn_name);\n                }\n\n                if (ZigClangType_getTypeClass(ty) == ZigClangType_FunctionNoProto) {\n                    return proto_node;\n                }\n\n                const ZigClangFunctionProtoType *fn_proto_ty = reinterpret_cast<const ZigClangFunctionProtoType*>(ty);\n\n                proto_node->data.fn_proto.is_var_args = ZigClangFunctionProtoType_isVariadic(fn_proto_ty);\n                size_t param_count = ZigClangFunctionProtoType_getNumParams(fn_proto_ty);\n\n                for (size_t i = 0; i < param_count; i += 1) {\n                    ZigClangQualType qt = ZigClangFunctionProtoType_getParamType(fn_proto_ty, i);\n                    AstNode *param_type_node = trans_qual_type(c, qt, source_loc);\n\n                    if (param_type_node == nullptr) {\n                        emit_warning(c, source_loc, \"unresolved function proto parameter type\");\n                        return nullptr;\n                    }\n\n                    AstNode *param_node = trans_create_node(c, NodeTypeParamDecl);\n                    \/\/emit_warning(c, source_loc, \"TODO figure out fn prototype param name\");\n                    const char *param_name = nullptr;\n                    if (param_name != nullptr) {\n                        param_node->data.param_decl.name = buf_create_from_str(param_name);\n                    }\n                    param_node->data.param_decl.is_noalias = ZigClangQualType_isRestrictQualified(qt);\n                    param_node->data.param_decl.type = param_type_node;\n                    proto_node->data.fn_proto.params.append(param_node);\n                }\n                \/\/ TODO check for always_inline attribute\n                \/\/ TODO check for align attribute\n\n                return proto_node;\n            }\n        case ZigClangType_Record:\n            {\n                const ZigClangRecordType *record_ty = reinterpret_cast<const ZigClangRecordType*>(ty);\n                return resolve_record_decl(c, ZigClangRecordType_getDecl(record_ty));\n            }\n        case ZigClangType_Enum:\n            {\n                const ZigClangEnumType *enum_ty = reinterpret_cast<const ZigClangEnumType*>(ty);\n                return resolve_enum_decl(c, ZigClangEnumType_getDecl(enum_ty));\n            }\n        case ZigClangType_ConstantArray:\n            {\n                const ZigClangConstantArrayType *const_arr_ty = reinterpret_cast<const ZigClangConstantArrayType *>(ty);\n                AstNode *child_type_node = trans_qual_type(c,\n                        ZigClangConstantArrayType_getElementType(const_arr_ty), source_loc);\n                if (child_type_node == nullptr) {\n                    emit_warning(c, source_loc, \"unresolved array element type\");\n                    return nullptr;\n                }\n                const ZigClangAPInt *size_ap_int = ZigClangConstantArrayType_getSize(const_arr_ty);\n                uint64_t size = ZigClangAPInt_getLimitedValue(size_ap_int, UINT64_MAX);\n                AstNode *size_node = trans_create_node_unsigned(c, size);\n                return trans_create_node_array_type(c, size_node, child_type_node);\n            }\n        case ZigClangType_Paren:\n            {\n                const ZigClangParenType *paren_ty = reinterpret_cast<const ZigClangParenType *>(ty);\n                return trans_qual_type(c, ZigClangParenType_getInnerType(paren_ty), source_loc);\n            }\n        case ZigClangType_Decayed:\n            {\n                const ZigClangDecayedType *decayed_ty = reinterpret_cast<const ZigClangDecayedType *>(ty);\n                return trans_qual_type(c, ZigClangDecayedType_getDecayedType(decayed_ty), source_loc);\n            }\n        case ZigClangType_Attributed:\n            {\n                const ZigClangAttributedType *attributed_ty = reinterpret_cast<const ZigClangAttributedType *>(ty);\n                return trans_qual_type(c, ZigClangAttributedType_getEquivalentType(attributed_ty), source_loc);\n            }\n        case ZigClangType_MacroQualified:\n            {\n                const ZigClangMacroQualifiedType *macroqualified_ty = reinterpret_cast<const ZigClangMacroQualifiedType *>(ty);\n                return trans_qual_type(c, ZigClangMacroQualifiedType_getModifiedType(macroqualified_ty), source_loc);\n            }\n        case ZigClangType_IncompleteArray:\n            {\n                const ZigClangIncompleteArrayType *incomplete_array_ty = reinterpret_cast<const ZigClangIncompleteArrayType *>(ty);\n                ZigClangQualType child_qt = ZigClangIncompleteArrayType_getElementType(incomplete_array_ty);\n                AstNode *child_type_node = trans_qual_type(c, child_qt, source_loc);\n                if (child_type_node == nullptr) {\n                    emit_warning(c, source_loc, \"unresolved array element type\");\n                    return nullptr;\n                }\n                AstNode *pointer_node = trans_create_node_ptr_type(c,\n                        ZigClangQualType_isConstQualified(child_qt),\n                        ZigClangQualType_isVolatileQualified(child_qt),\n                        child_type_node, PtrLenC);\n                return pointer_node;\n            }\n        case ZigClangType_BlockPointer:\n        case ZigClangType_LValueReference:\n        case ZigClangType_RValueReference:\n        case ZigClangType_MemberPointer:\n        case ZigClangType_VariableArray:\n        case ZigClangType_DependentSizedArray:\n        case ZigClangType_DependentSizedExtVector:\n        case ZigClangType_Vector:\n        case ZigClangType_ExtVector:\n        case ZigClangType_UnresolvedUsing:\n        case ZigClangType_Adjusted:\n        case ZigClangType_TypeOfExpr:\n        case ZigClangType_TypeOf:\n        case ZigClangType_Decltype:\n        case ZigClangType_UnaryTransform:\n        case ZigClangType_TemplateTypeParm:\n        case ZigClangType_SubstTemplateTypeParm:\n        case ZigClangType_SubstTemplateTypeParmPack:\n        case ZigClangType_TemplateSpecialization:\n        case ZigClangType_Auto:\n        case ZigClangType_InjectedClassName:\n        case ZigClangType_DependentName:\n        case ZigClangType_DependentTemplateSpecialization:\n        case ZigClangType_PackExpansion:\n        case ZigClangType_ObjCObject:\n        case ZigClangType_ObjCInterface:\n        case ZigClangType_Complex:\n        case ZigClangType_ObjCObjectPointer:\n        case ZigClangType_Atomic:\n        case ZigClangType_Pipe:\n        case ZigClangType_ObjCTypeParam:\n        case ZigClangType_DeducedTemplateSpecialization:\n        case ZigClangType_DependentAddressSpace:\n        case ZigClangType_DependentVector:\n            emit_warning(c, source_loc, \"unsupported type: '%s'\", ZigClangType_getTypeClassName(ty));\n            return nullptr;\n    }\n    zig_unreachable();\n}\n\nstatic AstNode *trans_qual_type(Context *c, ZigClangQualType qt, ZigClangSourceLocation source_loc) {\n    return trans_type(c, ZigClangQualType_getTypePtr(qt), source_loc);\n}\n\nstatic int trans_compound_stmt_inline(Context *c, TransScope *scope, const ZigClangCompoundStmt *stmt,\n        AstNode *block_node, TransScope **out_node_scope)\n{\n    assert(block_node->type == NodeTypeBlock);\n    for (ZigClangCompoundStmt_const_body_iterator it = ZigClangCompoundStmt_body_begin(stmt),\n        end_it = ZigClangCompoundStmt_body_end(stmt); it != end_it; ++it)\n    {\n        AstNode *child_node;\n        scope = trans_stmt(c, scope, *it, &child_node);\n        if (scope == nullptr)\n            return ErrorUnexpected;\n        if (child_node != nullptr)\n            block_node->data.block.statements.append(child_node);\n    }\n    if (out_node_scope != nullptr) {\n        *out_node_scope = scope;\n    }\n    return ErrorNone;\n}\n\nstatic AstNode *trans_compound_stmt(Context *c, TransScope *scope, const ZigClangCompoundStmt *stmt,\n        TransScope **out_node_scope)\n{\n    TransScopeBlock *child_scope_block = trans_scope_block_create(c, scope);\n    if (trans_compound_stmt_inline(c, &child_scope_block->base, stmt, child_scope_block->node, out_node_scope))\n        return nullptr;\n    return child_scope_block->node;\n}\n\nstatic AstNode *trans_stmt_expr(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangStmtExpr *stmt, TransScope **out_node_scope)\n{\n    AstNode *block = trans_compound_stmt(c, scope, ZigClangStmtExpr_getSubStmt(stmt), out_node_scope);\n    if (block == nullptr)\n        return block;\n    assert(block->type == NodeTypeBlock);\n    if (block->data.block.statements.length == 0)\n        return block;\n\n    Buf *label = buf_create_from_str(\"x\");\n    block->data.block.name = label;\n    AstNode *return_expr = block->data.block.statements.pop();\n    if (return_expr->type == NodeTypeBinOpExpr &&\n        return_expr->data.bin_op_expr.bin_op == BinOpTypeAssign &&\n        return_expr->data.bin_op_expr.op1->type == NodeTypeSymbol)\n       {\n        Buf *symbol_buf = return_expr->data.bin_op_expr.op1->data.symbol_expr.symbol;\n           if (strcmp(\"_\", buf_ptr(symbol_buf)) == 0)\n               return_expr = return_expr->data.bin_op_expr.op2;\n       }\n    block->data.block.statements.append(trans_create_node_break(c, label, return_expr));\n    return maybe_suppress_result(c, result_used, block);\n}\n\nstatic AstNode *trans_return_stmt(Context *c, TransScope *scope, const ZigClangReturnStmt *stmt) {\n    const ZigClangExpr *value_expr = ZigClangReturnStmt_getRetValue(stmt);\n    if (value_expr == nullptr) {\n        return trans_create_node(c, NodeTypeReturnExpr);\n    } else {\n        AstNode *return_node = trans_create_node(c, NodeTypeReturnExpr);\n        return_node->data.return_expr.expr = trans_expr(c, ResultUsedYes, scope, value_expr, TransRValue);\n        if (return_node->data.return_expr.expr == nullptr)\n            return nullptr;\n        return return_node;\n    }\n}\n\nstatic AstNode *trans_integer_literal(Context *c, ResultUsed result_used, const ZigClangIntegerLiteral *stmt) {\n    ZigClangExprEvalResult result;\n    if (!ZigClangIntegerLiteral_EvaluateAsInt(stmt, &result, c->ctx)) {\n        emit_warning(c, ZigClangExpr_getBeginLoc((ZigClangExpr*)stmt), \"invalid integer literal\");\n        return nullptr;\n    }\n    AstNode *node = trans_create_node_apint(c, ZigClangAPValue_getInt(&result.Val));\n    return maybe_suppress_result(c, result_used, node);\n}\n\nstatic AstNode *trans_floating_literal(Context *c, ResultUsed result_used, const ZigClangFloatingLiteral *stmt) {\n    ZigClangAPFloat *result;\n    if (!ZigClangExpr_EvaluateAsFloat((const ZigClangExpr *)stmt, &result, c->ctx)) {\n        emit_warning(c, ZigClangExpr_getBeginLoc((ZigClangExpr*)stmt), \"invalid floating literal\");\n        return nullptr;\n    }\n    AstNode *node = trans_create_node_apfloat(c, result);\n    return maybe_suppress_result(c, result_used, node);\n}\n\nstatic AstNode *trans_character_literal(Context *c, ResultUsed result_used, const ZigClangCharacterLiteral *stmt) {\n    switch (ZigClangCharacterLiteral_getKind(stmt)) {\n        case ZigClangCharacterLiteral_CharacterKind_Ascii:\n            {\n                unsigned val = ZigClangCharacterLiteral_getValue(stmt);\n                \/\/ C has a somewhat obscure feature called multi-character character\n                \/\/ constant\n                if (val > 255)\n                    return trans_create_node_unsigned(c, val);\n            }\n            \/\/ fallthrough\n        case ZigClangCharacterLiteral_CharacterKind_UTF8:\n            {\n                AstNode *node = trans_create_node(c, NodeTypeCharLiteral);\n                node->data.char_literal.value = ZigClangCharacterLiteral_getValue(stmt);\n                return maybe_suppress_result(c, result_used, node);\n            }\n        case ZigClangCharacterLiteral_CharacterKind_UTF16:\n            emit_warning(c, ZigClangCharacterLiteral_getBeginLoc(stmt), \"TODO support UTF16 character literals\");\n            return nullptr;\n        case ZigClangCharacterLiteral_CharacterKind_UTF32:\n            emit_warning(c, ZigClangCharacterLiteral_getBeginLoc(stmt), \"TODO support UTF32 character literals\");\n            return nullptr;\n        case ZigClangCharacterLiteral_CharacterKind_Wide:\n            emit_warning(c, ZigClangCharacterLiteral_getBeginLoc(stmt), \"TODO support wide character literals\");\n            return nullptr;\n    }\n    zig_unreachable();\n}\n\nstatic AstNode *trans_constant_expr(Context *c, ResultUsed result_used, const ZigClangConstantExpr *expr) {\n    const ZigClangExpr *as_expr = reinterpret_cast<const ZigClangExpr *>(expr);\n    ZigClangExprEvalResult result;\n    if (!ZigClangExpr_EvaluateAsConstantExpr((const ZigClangExpr *)expr, &result,\n                ZigClangExpr_EvaluateForCodeGen, c->ctx))\n    {\n        emit_warning(c, ZigClangExpr_getBeginLoc(as_expr), \"invalid constant expression\");\n        return nullptr;\n    }\n    AstNode *node = trans_ap_value(c, &result.Val, ZigClangExpr_getType(as_expr),\n            ZigClangExpr_getBeginLoc(as_expr));\n    return maybe_suppress_result(c, result_used, node);\n}\n\nstatic AstNode *trans_conditional_operator(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangConditionalOperator *stmt)\n{\n    AstNode *node = trans_create_node(c, NodeTypeIfBoolExpr);\n\n    const ZigClangExpr *cond_expr = ZigClangConditionalOperator_getCond(stmt);\n    const ZigClangExpr *true_expr = ZigClangConditionalOperator_getTrueExpr(stmt);\n    const ZigClangExpr *false_expr = ZigClangConditionalOperator_getFalseExpr(stmt);\n\n    node->data.if_bool_expr.condition = trans_expr(c, ResultUsedYes, scope, cond_expr, TransRValue);\n    if (node->data.if_bool_expr.condition == nullptr)\n        return nullptr;\n\n    node->data.if_bool_expr.then_block = trans_expr(c, result_used, scope, true_expr, TransRValue);\n    if (node->data.if_bool_expr.then_block == nullptr)\n        return nullptr;\n\n    node->data.if_bool_expr.else_node = trans_expr(c, result_used, scope, false_expr, TransRValue);\n    if (node->data.if_bool_expr.else_node == nullptr)\n        return nullptr;\n\n    return maybe_suppress_result(c, result_used, node);\n}\n\nstatic AstNode *trans_create_bin_op(Context *c, TransScope *scope, const ZigClangExpr *lhs,\n        BinOpType bin_op, const ZigClangExpr *rhs)\n{\n    AstNode *node = trans_create_node(c, NodeTypeBinOpExpr);\n    node->data.bin_op_expr.bin_op = bin_op;\n\n    node->data.bin_op_expr.op1 = trans_expr(c, ResultUsedYes, scope, lhs, TransRValue);\n    if (node->data.bin_op_expr.op1 == nullptr)\n        return nullptr;\n\n    node->data.bin_op_expr.op2 = trans_expr(c, ResultUsedYes, scope, rhs, TransRValue);\n    if (node->data.bin_op_expr.op2 == nullptr)\n        return nullptr;\n\n    return node;\n}\n\nstatic AstNode *trans_create_bool_bin_op(Context *c, TransScope *scope, const ZigClangExpr *lhs,\n        BinOpType bin_op, const ZigClangExpr *rhs)\n{\n    assert(bin_op == BinOpTypeBoolAnd || bin_op == BinOpTypeBoolOr);\n    AstNode *node = trans_create_node(c, NodeTypeBinOpExpr);\n    node->data.bin_op_expr.bin_op = bin_op;\n\n    node->data.bin_op_expr.op1 = trans_bool_expr(c, ResultUsedYes, scope, lhs, TransRValue);\n    if (node->data.bin_op_expr.op1 == nullptr)\n        return nullptr;\n\n    node->data.bin_op_expr.op2 = trans_bool_expr(c, ResultUsedYes, scope, rhs, TransRValue);\n    if (node->data.bin_op_expr.op2 == nullptr)\n        return nullptr;\n\n    return node;\n}\n\nstatic AstNode *trans_create_assign(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangExpr *lhs, const ZigClangExpr *rhs)\n{\n    if (result_used == ResultUsedNo) {\n        \/\/ common case\n        AstNode *node = trans_create_node(c, NodeTypeBinOpExpr);\n        node->data.bin_op_expr.bin_op = BinOpTypeAssign;\n\n        node->data.bin_op_expr.op1 = trans_expr(c, ResultUsedYes, scope, lhs, TransLValue);\n        if (node->data.bin_op_expr.op1 == nullptr)\n            return nullptr;\n\n        node->data.bin_op_expr.op2 = trans_expr(c, ResultUsedYes, scope, rhs, TransRValue);\n        if (node->data.bin_op_expr.op2 == nullptr)\n            return nullptr;\n\n        return node;\n    } else {\n        \/\/ worst case\n        \/\/ c: lhs = rhs\n        \/\/ zig: (x: {\n        \/\/ zig:     const _tmp = rhs;\n        \/\/ zig:     lhs = _tmp;\n        \/\/ zig:     break :x _tmp\n        \/\/ zig: })\n\n        TransScopeBlock *child_scope = trans_scope_block_create(c, scope);\n        Buf *label_name = buf_create_from_str(\"x\");\n        child_scope->node->data.block.name = label_name;\n\n        \/\/ const _tmp = rhs;\n        AstNode *rhs_node = trans_expr(c, ResultUsedYes, &child_scope->base, rhs, TransRValue);\n        if (rhs_node == nullptr) return nullptr;\n        \/\/ TODO: avoid name collisions with generated variable names\n        Buf* tmp_var_name = buf_create_from_str(\"_tmp\");\n        AstNode *tmp_var_decl = trans_create_node_var_decl_local(c, true, tmp_var_name, nullptr, rhs_node);\n        child_scope->node->data.block.statements.append(tmp_var_decl);\n\n        \/\/ lhs = _tmp;\n        AstNode *lhs_node = trans_expr(c, ResultUsedYes, &child_scope->base, lhs, TransLValue);\n        if (lhs_node == nullptr) return nullptr;\n        child_scope->node->data.block.statements.append(\n            trans_create_node_bin_op(c, lhs_node, BinOpTypeAssign,\n                trans_create_node_symbol(c, tmp_var_name)));\n\n        \/\/ break :x _tmp\n        AstNode *tmp_symbol_node = trans_create_node_symbol(c, tmp_var_name);\n        child_scope->node->data.block.statements.append(trans_create_node_break(c, label_name, tmp_symbol_node));\n\n        return trans_create_node_grouped_expr(c, child_scope->node);\n    }\n}\n\nstatic AstNode *trans_create_shift_op(Context *c, TransScope *scope, ZigClangQualType result_type,\n        const ZigClangExpr *lhs_expr, BinOpType bin_op, const ZigClangExpr *rhs_expr)\n{\n    ZigClangSourceLocation rhs_location = ZigClangExpr_getBeginLoc(rhs_expr);\n    AstNode *rhs_type = qual_type_to_log2_int_ref(c, result_type, rhs_location);\n    \/\/ lhs >> u5(rh)\n\n    AstNode *lhs = trans_expr(c, ResultUsedYes, scope, lhs_expr, TransLValue);\n    if (lhs == nullptr) return nullptr;\n\n    AstNode *rhs = trans_expr(c, ResultUsedYes, scope, rhs_expr, TransRValue);\n    if (rhs == nullptr) return nullptr;\n    AstNode *coerced_rhs = trans_create_node_cast(c, rhs_type, rhs);\n\n    return trans_create_node_bin_op(c, lhs, bin_op, coerced_rhs);\n}\n\nstatic AstNode *trans_binary_operator(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangBinaryOperator *stmt)\n{\n    switch (ZigClangBinaryOperator_getOpcode(stmt)) {\n        case ZigClangBO_PtrMemD:\n            emit_warning(c, ZigClangBinaryOperator_getBeginLoc(stmt), \"TODO handle more C binary operators: BO_PtrMemD\");\n            return nullptr;\n        case ZigClangBO_PtrMemI:\n            emit_warning(c, ZigClangBinaryOperator_getBeginLoc(stmt), \"TODO handle more C binary operators: BO_PtrMemI\");\n            return nullptr;\n        case ZigClangBO_Cmp:\n            emit_warning(c, ZigClangBinaryOperator_getBeginLoc(stmt), \"TODO handle more C binary operators: BO_Cmp\");\n            return nullptr;\n        case ZigClangBO_Mul: {\n            AstNode *node = trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt),\n                qual_type_has_wrapping_overflow(c, ZigClangBinaryOperator_getType(stmt)) ? BinOpTypeMultWrap : BinOpTypeMult,\n                ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_Div:\n            if (qual_type_has_wrapping_overflow(c, ZigClangBinaryOperator_getType(stmt))) {\n                \/\/ unsigned\/float division uses the operator\n                AstNode *node = trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt), BinOpTypeDiv, ZigClangBinaryOperator_getRHS(stmt));\n                return maybe_suppress_result(c, result_used, node);\n            } else {\n                \/\/ signed integer division uses @divTrunc\n                AstNode *fn_call = trans_create_node_builtin_fn_call_str(c, \"divTrunc\");\n                AstNode *lhs = trans_expr(c, ResultUsedYes, scope, ZigClangBinaryOperator_getLHS(stmt), TransLValue);\n                if (lhs == nullptr) return nullptr;\n                fn_call->data.fn_call_expr.params.append(lhs);\n                AstNode *rhs = trans_expr(c, ResultUsedYes, scope, ZigClangBinaryOperator_getRHS(stmt), TransLValue);\n                if (rhs == nullptr) return nullptr;\n                fn_call->data.fn_call_expr.params.append(rhs);\n                return maybe_suppress_result(c, result_used, fn_call);\n            }\n        case ZigClangBO_Rem:\n            if (qual_type_has_wrapping_overflow(c, ZigClangBinaryOperator_getType(stmt))) {\n                \/\/ unsigned\/float division uses the operator\n                AstNode *node = trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt), BinOpTypeMod, ZigClangBinaryOperator_getRHS(stmt));\n                return maybe_suppress_result(c, result_used, node);\n            } else {\n                \/\/ signed integer division uses @rem\n                AstNode *fn_call = trans_create_node_builtin_fn_call_str(c, \"rem\");\n                AstNode *lhs = trans_expr(c, ResultUsedYes, scope, ZigClangBinaryOperator_getLHS(stmt), TransLValue);\n                if (lhs == nullptr) return nullptr;\n                fn_call->data.fn_call_expr.params.append(lhs);\n                AstNode *rhs = trans_expr(c, ResultUsedYes, scope, ZigClangBinaryOperator_getRHS(stmt), TransLValue);\n                if (rhs == nullptr) return nullptr;\n                fn_call->data.fn_call_expr.params.append(rhs);\n                return maybe_suppress_result(c, result_used, fn_call);\n            }\n        case ZigClangBO_Add: {\n            AstNode *node = trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt),\n                qual_type_has_wrapping_overflow(c, ZigClangBinaryOperator_getType(stmt)) ? BinOpTypeAddWrap : BinOpTypeAdd,\n                ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_Sub: {\n            AstNode *node = trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt),\n                qual_type_has_wrapping_overflow(c, ZigClangBinaryOperator_getType(stmt)) ? BinOpTypeSubWrap : BinOpTypeSub,\n                ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_Shl: {\n            AstNode *node = trans_create_shift_op(c, scope, ZigClangBinaryOperator_getType(stmt), ZigClangBinaryOperator_getLHS(stmt), BinOpTypeBitShiftLeft, ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_Shr: {\n            AstNode *node = trans_create_shift_op(c, scope, ZigClangBinaryOperator_getType(stmt), ZigClangBinaryOperator_getLHS(stmt), BinOpTypeBitShiftRight, ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_LT: {\n            AstNode *node =trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt), BinOpTypeCmpLessThan, ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_GT: {\n            AstNode *node = trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt), BinOpTypeCmpGreaterThan, ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_LE: {\n            AstNode *node = trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt), BinOpTypeCmpLessOrEq, ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_GE: {\n            AstNode *node = trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt), BinOpTypeCmpGreaterOrEq, ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_EQ: {\n            AstNode *node = trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt), BinOpTypeCmpEq, ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_NE: {\n            AstNode *node = trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt), BinOpTypeCmpNotEq, ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_And: {\n            AstNode *node = trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt), BinOpTypeBinAnd, ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_Xor: {\n            AstNode *node = trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt), BinOpTypeBinXor, ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_Or: {\n            AstNode *node = trans_create_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt), BinOpTypeBinOr, ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_LAnd: {\n            AstNode *node = trans_create_bool_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt), BinOpTypeBoolAnd, ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_LOr: {\n            AstNode *node = trans_create_bool_bin_op(c, scope, ZigClangBinaryOperator_getLHS(stmt), BinOpTypeBoolOr, ZigClangBinaryOperator_getRHS(stmt));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangBO_Assign:\n            return trans_create_assign(c, result_used, scope, ZigClangBinaryOperator_getLHS(stmt), ZigClangBinaryOperator_getRHS(stmt));\n        case ZigClangBO_Comma:\n            {\n                TransScopeBlock *scope_block = trans_scope_block_create(c, scope);\n                Buf *label_name = buf_create_from_str(\"x\");\n                scope_block->node->data.block.name = label_name;\n\n                AstNode *lhs = trans_expr(c, ResultUsedNo, &scope_block->base, ZigClangBinaryOperator_getLHS(stmt), TransRValue);\n                if (lhs == nullptr)\n                    return nullptr;\n                scope_block->node->data.block.statements.append(lhs);\n\n                AstNode *rhs = trans_expr(c, ResultUsedYes, &scope_block->base, ZigClangBinaryOperator_getRHS(stmt), TransRValue);\n                if (rhs == nullptr)\n                    return nullptr;\n\n                rhs = trans_create_node_break(c, label_name, rhs);\n                scope_block->node->data.block.statements.append(rhs);\n                return maybe_suppress_result(c, result_used, scope_block->node);\n            }\n        case ZigClangBO_MulAssign:\n        case ZigClangBO_DivAssign:\n        case ZigClangBO_RemAssign:\n        case ZigClangBO_AddAssign:\n        case ZigClangBO_SubAssign:\n        case ZigClangBO_ShlAssign:\n        case ZigClangBO_ShrAssign:\n        case ZigClangBO_AndAssign:\n        case ZigClangBO_XorAssign:\n        case ZigClangBO_OrAssign:\n            zig_unreachable();\n    }\n\n    zig_unreachable();\n}\n\nstatic AstNode *trans_create_compound_assign_shift(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangCompoundAssignOperator *stmt, BinOpType assign_op, BinOpType bin_op)\n{\n    ZigClangSourceLocation rhs_location = ZigClangExpr_getBeginLoc(ZigClangCompoundAssignOperator_getRHS(stmt));\n    ZigClangQualType computation_lhs_type = ZigClangCompoundAssignOperator_getComputationLHSType(stmt);\n    AstNode *rhs_type = qual_type_to_log2_int_ref(c, computation_lhs_type, rhs_location);\n    ZigClangQualType computation_result_type = ZigClangCompoundAssignOperator_getComputationResultType(stmt);\n\n    bool use_intermediate_casts = ZigClangQualType_getTypePtr(computation_lhs_type) !=\n        ZigClangQualType_getTypePtr(computation_result_type);\n    if (!use_intermediate_casts && result_used == ResultUsedNo) {\n        \/\/ simple common case, where the C and Zig are identical:\n        \/\/ lhs >>= rhs\n        AstNode *lhs = trans_expr(c, ResultUsedYes, scope, ZigClangCompoundAssignOperator_getLHS(stmt), TransLValue);\n        if (lhs == nullptr) return nullptr;\n\n        AstNode *rhs = trans_expr(c, ResultUsedYes, scope, ZigClangCompoundAssignOperator_getRHS(stmt), TransRValue);\n        if (rhs == nullptr) return nullptr;\n        AstNode *coerced_rhs = trans_create_node_cast(c, rhs_type, rhs);\n\n        return trans_create_node_bin_op(c, lhs, assign_op, coerced_rhs);\n    } else {\n        \/\/ need more complexity. worst case, this looks like this:\n        \/\/ c:   lhs >>= rhs\n        \/\/ zig: (x: {\n        \/\/ zig:     const _ref = &lhs;\n        \/\/ zig:     *_ref = result_type(operation_type(*_ref) >> u5(rhs));\n        \/\/ zig:     break :x *_ref\n        \/\/ zig: })\n        \/\/ where u5 is the appropriate type\n\n        TransScopeBlock *child_scope = trans_scope_block_create(c, scope);\n        Buf *label_name = buf_create_from_str(\"x\");\n        child_scope->node->data.block.name = label_name;\n\n        \/\/ const _ref = &lhs;\n        AstNode *lhs = trans_expr(c, ResultUsedYes, &child_scope->base,\n                ZigClangCompoundAssignOperator_getLHS(stmt), TransLValue);\n        if (lhs == nullptr) return nullptr;\n        AstNode *addr_of_lhs = trans_create_node_addr_of(c, lhs);\n        \/\/ TODO: avoid name collisions with generated variable names\n        Buf* tmp_var_name = buf_create_from_str(\"_ref\");\n        AstNode *tmp_var_decl = trans_create_node_var_decl_local(c, true, tmp_var_name, nullptr, addr_of_lhs);\n        child_scope->node->data.block.statements.append(tmp_var_decl);\n\n        \/\/ *_ref = result_type(operation_type(*_ref) >> u5(rhs));\n\n        AstNode *rhs = trans_expr(c, ResultUsedYes, &child_scope->base, ZigClangCompoundAssignOperator_getRHS(stmt), TransRValue);\n        if (rhs == nullptr) return nullptr;\n        AstNode *coerced_rhs = trans_create_node_cast(c, rhs_type, rhs);\n\n        \/\/ operation_type(*_ref)\n        AstNode *operation_type_cast = trans_c_cast(c, rhs_location,\n            computation_lhs_type,\n            ZigClangExpr_getType(ZigClangCompoundAssignOperator_getLHS(stmt)),\n            trans_create_node_ptr_deref(c, trans_create_node_symbol(c, tmp_var_name)));\n\n        \/\/ result_type(... >> u5(rhs))\n        AstNode *result_type_cast = trans_c_cast(c, rhs_location,\n            computation_result_type,\n            computation_lhs_type,\n            trans_create_node_bin_op(c,\n                operation_type_cast,\n                bin_op,\n                coerced_rhs));\n\n        \/\/ *_ref = ...\n        AstNode *assign_statement = trans_create_node_bin_op(c,\n            trans_create_node_ptr_deref(c,\n                trans_create_node_symbol(c, tmp_var_name)),\n            BinOpTypeAssign, result_type_cast);\n\n        child_scope->node->data.block.statements.append(assign_statement);\n\n        if (result_used == ResultUsedYes) {\n            \/\/ break :x *_ref\n            child_scope->node->data.block.statements.append(\n                trans_create_node_break(c, label_name,\n                    trans_create_node_ptr_deref(c,\n                        trans_create_node_symbol(c, tmp_var_name))));\n        }\n\n        return trans_create_node_grouped_expr(c, child_scope->node);\n    }\n}\n\nstatic AstNode *trans_create_compound_assign(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangCompoundAssignOperator *stmt, BinOpType assign_op, BinOpType bin_op)\n{\n    if (result_used == ResultUsedNo) {\n        \/\/ simple common case, where the C and Zig are identical:\n        \/\/ lhs += rhs\n        AstNode *lhs = trans_expr(c, ResultUsedYes, scope, ZigClangCompoundAssignOperator_getLHS(stmt), TransLValue);\n        if (lhs == nullptr) return nullptr;\n        AstNode *rhs = trans_expr(c, ResultUsedYes, scope, ZigClangCompoundAssignOperator_getRHS(stmt), TransRValue);\n        if (rhs == nullptr) return nullptr;\n        return trans_create_node_bin_op(c, lhs, assign_op, rhs);\n    } else {\n        \/\/ need more complexity. worst case, this looks like this:\n        \/\/ c:   lhs += rhs\n        \/\/ zig: (x: {\n        \/\/ zig:     const _ref = &lhs;\n        \/\/ zig:     *_ref = *_ref + rhs;\n        \/\/ zig:     break :x *_ref\n        \/\/ zig: })\n\n        TransScopeBlock *child_scope = trans_scope_block_create(c, scope);\n        Buf *label_name = buf_create_from_str(\"x\");\n        child_scope->node->data.block.name = label_name;\n\n        \/\/ const _ref = &lhs;\n        AstNode *lhs = trans_expr(c, ResultUsedYes, &child_scope->base,\n                ZigClangCompoundAssignOperator_getLHS(stmt), TransLValue);\n        if (lhs == nullptr) return nullptr;\n        AstNode *addr_of_lhs = trans_create_node_addr_of(c, lhs);\n        \/\/ TODO: avoid name collisions with generated variable names\n        Buf* tmp_var_name = buf_create_from_str(\"_ref\");\n        AstNode *tmp_var_decl = trans_create_node_var_decl_local(c, true, tmp_var_name, nullptr, addr_of_lhs);\n        child_scope->node->data.block.statements.append(tmp_var_decl);\n\n        \/\/ *_ref = *_ref + rhs;\n\n        AstNode *rhs = trans_expr(c, ResultUsedYes, &child_scope->base,\n                ZigClangCompoundAssignOperator_getRHS(stmt), TransRValue);\n        if (rhs == nullptr) return nullptr;\n\n        AstNode *assign_statement = trans_create_node_bin_op(c,\n            trans_create_node_ptr_deref(c,\n                trans_create_node_symbol(c, tmp_var_name)),\n            BinOpTypeAssign,\n            trans_create_node_bin_op(c,\n                trans_create_node_ptr_deref(c,\n                    trans_create_node_symbol(c, tmp_var_name)),\n                bin_op,\n                rhs));\n        child_scope->node->data.block.statements.append(assign_statement);\n\n        \/\/ break :x *_ref\n        child_scope->node->data.block.statements.append(\n            trans_create_node_break(c, label_name,\n                trans_create_node_ptr_deref(c,\n                    trans_create_node_symbol(c, tmp_var_name))));\n\n        return trans_create_node_grouped_expr(c, child_scope->node);\n    }\n}\n\n\nstatic AstNode *trans_compound_assign_operator(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangCompoundAssignOperator *stmt)\n{\n    switch (ZigClangCompoundAssignOperator_getOpcode(stmt)) {\n        case ZigClangBO_MulAssign:\n            if (qual_type_has_wrapping_overflow(c, ZigClangCompoundAssignOperator_getType(stmt)))\n                return trans_create_compound_assign(c, result_used, scope, stmt, BinOpTypeAssignTimesWrap, BinOpTypeMultWrap);\n            else\n                return trans_create_compound_assign(c, result_used, scope, stmt, BinOpTypeAssignTimes, BinOpTypeMult);\n        case ZigClangBO_DivAssign:\n            emit_warning(c, ZigClangCompoundAssignOperator_getBeginLoc(stmt), \"TODO handle more C compound assign operators: BO_DivAssign\");\n            return nullptr;\n        case ZigClangBO_RemAssign:\n            emit_warning(c, ZigClangCompoundAssignOperator_getBeginLoc(stmt), \"TODO handle more C compound assign operators: BO_RemAssign\");\n            return nullptr;\n        case ZigClangBO_Cmp:\n            emit_warning(c, ZigClangCompoundAssignOperator_getBeginLoc(stmt), \"TODO handle more C compound assign operators: BO_Cmp\");\n            return nullptr;\n        case ZigClangBO_AddAssign:\n            if (qual_type_has_wrapping_overflow(c, ZigClangCompoundAssignOperator_getType(stmt)))\n                return trans_create_compound_assign(c, result_used, scope, stmt, BinOpTypeAssignPlusWrap, BinOpTypeAddWrap);\n            else\n                return trans_create_compound_assign(c, result_used, scope, stmt, BinOpTypeAssignPlus, BinOpTypeAdd);\n        case ZigClangBO_SubAssign:\n            if (qual_type_has_wrapping_overflow(c, ZigClangCompoundAssignOperator_getType(stmt)))\n                return trans_create_compound_assign(c, result_used, scope, stmt, BinOpTypeAssignMinusWrap, BinOpTypeSubWrap);\n            else\n                return trans_create_compound_assign(c, result_used, scope, stmt, BinOpTypeAssignMinus, BinOpTypeSub);\n        case ZigClangBO_ShlAssign:\n            return trans_create_compound_assign_shift(c, result_used, scope, stmt, BinOpTypeAssignBitShiftLeft, BinOpTypeBitShiftLeft);\n        case ZigClangBO_ShrAssign:\n            return trans_create_compound_assign_shift(c, result_used, scope, stmt, BinOpTypeAssignBitShiftRight, BinOpTypeBitShiftRight);\n        case ZigClangBO_AndAssign:\n            return trans_create_compound_assign(c, result_used, scope, stmt, BinOpTypeAssignBitAnd, BinOpTypeBinAnd);\n        case ZigClangBO_XorAssign:\n            return trans_create_compound_assign(c, result_used, scope, stmt, BinOpTypeAssignBitXor, BinOpTypeBinXor);\n        case ZigClangBO_OrAssign:\n            return trans_create_compound_assign(c, result_used, scope, stmt, BinOpTypeAssignBitOr, BinOpTypeBinOr);\n        case ZigClangBO_PtrMemD:\n        case ZigClangBO_PtrMemI:\n        case ZigClangBO_Assign:\n        case ZigClangBO_Mul:\n        case ZigClangBO_Div:\n        case ZigClangBO_Rem:\n        case ZigClangBO_Add:\n        case ZigClangBO_Sub:\n        case ZigClangBO_Shl:\n        case ZigClangBO_Shr:\n        case ZigClangBO_LT:\n        case ZigClangBO_GT:\n        case ZigClangBO_LE:\n        case ZigClangBO_GE:\n        case ZigClangBO_EQ:\n        case ZigClangBO_NE:\n        case ZigClangBO_And:\n        case ZigClangBO_Xor:\n        case ZigClangBO_Or:\n        case ZigClangBO_LAnd:\n        case ZigClangBO_LOr:\n        case ZigClangBO_Comma:\n            zig_unreachable();\n    }\n\n    zig_unreachable();\n}\n\nstatic AstNode *trans_implicit_cast_expr(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangImplicitCastExpr *stmt)\n{\n    switch (ZigClangImplicitCastExpr_getCastKind(stmt)) {\n        case ZigClangCK_LValueToRValue:\n            return trans_expr(c, ResultUsedYes, scope, ZigClangImplicitCastExpr_getSubExpr(stmt), TransRValue);\n        case ZigClangCK_IntegralCast:\n            {\n                AstNode *target_node = trans_expr(c, ResultUsedYes, scope, ZigClangImplicitCastExpr_getSubExpr(stmt), TransRValue);\n                if (target_node == nullptr)\n                    return nullptr;\n                AstNode *node = trans_c_cast(c, ZigClangImplicitCastExpr_getBeginLoc(stmt),\n                    ZigClangExpr_getType(reinterpret_cast<const ZigClangExpr *>(stmt)),\n                    ZigClangExpr_getType(ZigClangImplicitCastExpr_getSubExpr(stmt)),\n                    target_node);\n                return maybe_suppress_result(c, result_used, node);\n            }\n        case ZigClangCK_FunctionToPointerDecay:\n        case ZigClangCK_ArrayToPointerDecay:\n            {\n                AstNode *target_node = trans_expr(c, ResultUsedYes, scope, ZigClangImplicitCastExpr_getSubExpr(stmt), TransRValue);\n                if (target_node == nullptr)\n                    return nullptr;\n                return maybe_suppress_result(c, result_used, target_node);\n            }\n        case ZigClangCK_BitCast:\n            {\n                AstNode *target_node = trans_expr(c, ResultUsedYes, scope, ZigClangImplicitCastExpr_getSubExpr(stmt), TransRValue);\n                if (target_node == nullptr)\n                    return nullptr;\n\n                const ZigClangQualType dest_type = get_expr_qual_type(c, reinterpret_cast<const ZigClangExpr *>(stmt));\n                const ZigClangQualType src_type = get_expr_qual_type(c, ZigClangImplicitCastExpr_getSubExpr(stmt));\n\n                return trans_c_cast(c, ZigClangImplicitCastExpr_getBeginLoc(stmt),\n                        dest_type, src_type, target_node);\n            }\n        case ZigClangCK_NullToPointer:\n            return trans_create_node(c, NodeTypeNullLiteral);\n        case ZigClangCK_NoOp:\n            return trans_expr(c, ResultUsedYes, scope, ZigClangImplicitCastExpr_getSubExpr(stmt), TransRValue);\n        case ZigClangCK_Dependent:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C translation cast CK_Dependent\");\n            return nullptr;\n        case ZigClangCK_LValueBitCast:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C translation cast CK_LValueBitCast\");\n            return nullptr;\n        case ZigClangCK_BaseToDerived:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C translation cast CK_BaseToDerived\");\n            return nullptr;\n        case ZigClangCK_DerivedToBase:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C translation cast CK_DerivedToBase\");\n            return nullptr;\n        case ZigClangCK_UncheckedDerivedToBase:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C translation cast CK_UncheckedDerivedToBase\");\n            return nullptr;\n        case ZigClangCK_Dynamic:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C translation cast CK_Dynamic\");\n            return nullptr;\n        case ZigClangCK_ToUnion:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C translation cast CK_ToUnion\");\n            return nullptr;\n        case ZigClangCK_NullToMemberPointer:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C translation cast CK_NullToMemberPointer\");\n            return nullptr;\n        case ZigClangCK_BaseToDerivedMemberPointer:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C translation cast CK_BaseToDerivedMemberPointer\");\n            return nullptr;\n        case ZigClangCK_DerivedToBaseMemberPointer:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C translation cast CK_DerivedToBaseMemberPointer\");\n            return nullptr;\n        case ZigClangCK_MemberPointerToBoolean:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C translation cast CK_MemberPointerToBoolean\");\n            return nullptr;\n        case ZigClangCK_ReinterpretMemberPointer:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C translation cast CK_ReinterpretMemberPointer\");\n            return nullptr;\n        case ZigClangCK_UserDefinedConversion:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C translation cast CK_UserDefinedConversion\");\n            return nullptr;\n        case ZigClangCK_ConstructorConversion:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_ConstructorConversion\");\n            return nullptr;\n        case ZigClangCK_PointerToBoolean:\n            {\n                const ZigClangExpr *expr = ZigClangImplicitCastExpr_getSubExpr(stmt);\n                AstNode *val = trans_expr(c, ResultUsedYes, scope, expr, TransRValue);\n                if (val == nullptr)\n                    return nullptr;\n\n                AstNode *val_ptr = trans_create_node_builtin_fn_call_str(c, \"ptrToInt\");\n                val_ptr->data.fn_call_expr.params.append(val);\n\n                AstNode *zero = trans_create_node_unsigned(c, 0);\n\n                \/\/ Translate as @ptrToInt((&val) != 0)\n                return trans_create_node_bin_op(c, val_ptr, BinOpTypeCmpNotEq, zero);\n            }\n        case ZigClangCK_ToVoid:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_ToVoid\");\n            return nullptr;\n        case ZigClangCK_VectorSplat:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_VectorSplat\");\n            return nullptr;\n        case ZigClangCK_IntegralToBoolean:\n            {\n                const ZigClangExpr *expr = ZigClangImplicitCastExpr_getSubExpr(stmt);\n\n                bool expr_val;\n                if (ZigClangExpr_EvaluateAsBooleanCondition(expr, &expr_val, c->ctx, false)) {\n                    return trans_create_node_bool(c, expr_val);\n                }\n\n                AstNode *val = trans_expr(c, ResultUsedYes, scope, expr, TransRValue);\n                if (val == nullptr)\n                    return nullptr;\n\n                AstNode *zero = trans_create_node_unsigned(c, 0);\n\n                \/\/ Translate as val != 0\n                return trans_create_node_bin_op(c, val, BinOpTypeCmpNotEq, zero);\n            }\n        case ZigClangCK_PointerToIntegral:\n            {\n                AstNode *target_node = trans_expr(c, ResultUsedYes, scope, ZigClangImplicitCastExpr_getSubExpr(stmt), TransRValue);\n                if (target_node == nullptr)\n                    return nullptr;\n\n                AstNode *dest_type_node = get_expr_type(c, (const ZigClangExpr *)stmt);\n                if (dest_type_node == nullptr)\n                    return nullptr;\n\n                AstNode *val_node = trans_create_node_builtin_fn_call_str(c, \"ptrToInt\");\n                val_node->data.fn_call_expr.params.append(target_node);\n                \/\/ @ptrToInt always returns a usize\n                AstNode *node = trans_create_node_builtin_fn_call_str(c, \"intCast\");\n                node->data.fn_call_expr.params.append(dest_type_node);\n                node->data.fn_call_expr.params.append(val_node);\n\n                return maybe_suppress_result(c, result_used, node);\n            }\n        case ZigClangCK_IntegralToPointer:\n            {\n                AstNode *target_node = trans_expr(c, ResultUsedYes, scope, ZigClangImplicitCastExpr_getSubExpr(stmt), TransRValue);\n                if (target_node == nullptr)\n                    return nullptr;\n\n                AstNode *dest_type_node = get_expr_type(c, (const ZigClangExpr *)stmt);\n                if (dest_type_node == nullptr)\n                    return nullptr;\n\n                AstNode *node = trans_create_node_builtin_fn_call_str(c, \"intToPtr\");\n                node->data.fn_call_expr.params.append(dest_type_node);\n                node->data.fn_call_expr.params.append(target_node);\n\n                return maybe_suppress_result(c, result_used, node);\n            }\n        case ZigClangCK_IntegralToFloating:\n        case ZigClangCK_FloatingToIntegral:\n            {\n                AstNode *target_node = trans_expr(c, ResultUsedYes, scope, ZigClangImplicitCastExpr_getSubExpr(stmt), TransRValue);\n                if (target_node == nullptr)\n                    return nullptr;\n\n                AstNode *dest_type_node = get_expr_type(c, (const ZigClangExpr *)stmt);\n                if (dest_type_node == nullptr)\n                    return nullptr;\n\n                char const *fn = (ZigClangImplicitCastExpr_getCastKind(stmt) == ZigClangCK_IntegralToFloating) ?\n                    \"intToFloat\" : \"floatToInt\";\n                AstNode *node = trans_create_node_builtin_fn_call_str(c, fn);\n                node->data.fn_call_expr.params.append(dest_type_node);\n                node->data.fn_call_expr.params.append(target_node);\n\n                return maybe_suppress_result(c, result_used, node);\n            }\n        case ZigClangCK_FixedPointCast:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_FixedPointCast\");\n            return nullptr;\n        case ZigClangCK_FixedPointToBoolean:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_FixedPointToBoolean\");\n            return nullptr;\n        case ZigClangCK_FloatingToBoolean:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_FloatingToBoolean\");\n            return nullptr;\n        case ZigClangCK_BooleanToSignedIntegral:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_BooleanToSignedIntegral\");\n            return nullptr;\n        case ZigClangCK_FloatingCast:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_FloatingCast\");\n            return nullptr;\n        case ZigClangCK_CPointerToObjCPointerCast:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_CPointerToObjCPointerCast\");\n            return nullptr;\n        case ZigClangCK_BlockPointerToObjCPointerCast:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_BlockPointerToObjCPointerCast\");\n            return nullptr;\n        case ZigClangCK_AnyPointerToBlockPointerCast:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_AnyPointerToBlockPointerCast\");\n            return nullptr;\n        case ZigClangCK_ObjCObjectLValueCast:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_ObjCObjectLValueCast\");\n            return nullptr;\n        case ZigClangCK_FloatingRealToComplex:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_FloatingRealToComplex\");\n            return nullptr;\n        case ZigClangCK_FloatingComplexToReal:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_FloatingComplexToReal\");\n            return nullptr;\n        case ZigClangCK_FloatingComplexToBoolean:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_FloatingComplexToBoolean\");\n            return nullptr;\n        case ZigClangCK_FloatingComplexCast:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_FloatingComplexCast\");\n            return nullptr;\n        case ZigClangCK_FloatingComplexToIntegralComplex:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_FloatingComplexToIntegralComplex\");\n            return nullptr;\n        case ZigClangCK_IntegralRealToComplex:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_IntegralRealToComplex\");\n            return nullptr;\n        case ZigClangCK_IntegralComplexToReal:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_IntegralComplexToReal\");\n            return nullptr;\n        case ZigClangCK_IntegralComplexToBoolean:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_IntegralComplexToBoolean\");\n            return nullptr;\n        case ZigClangCK_IntegralComplexCast:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_IntegralComplexCast\");\n            return nullptr;\n        case ZigClangCK_IntegralComplexToFloatingComplex:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_IntegralComplexToFloatingComplex\");\n            return nullptr;\n        case ZigClangCK_ARCProduceObject:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_ARCProduceObject\");\n            return nullptr;\n        case ZigClangCK_ARCConsumeObject:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_ARCConsumeObject\");\n            return nullptr;\n        case ZigClangCK_ARCReclaimReturnedObject:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_ARCReclaimReturnedObject\");\n            return nullptr;\n        case ZigClangCK_ARCExtendBlockObject:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_ARCExtendBlockObject\");\n            return nullptr;\n        case ZigClangCK_AtomicToNonAtomic:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_AtomicToNonAtomic\");\n            return nullptr;\n        case ZigClangCK_NonAtomicToAtomic:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_NonAtomicToAtomic\");\n            return nullptr;\n        case ZigClangCK_CopyAndAutoreleaseBlockObject:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_CopyAndAutoreleaseBlockObject\");\n            return nullptr;\n        case ZigClangCK_BuiltinFnToFnPtr:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_BuiltinFnToFnPtr\");\n            return nullptr;\n        case ZigClangCK_ZeroToOCLOpaqueType:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_ZeroToOCLOpaqueType\");\n            return nullptr;\n        case ZigClangCK_AddressSpaceConversion:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_AddressSpaceConversion\");\n            return nullptr;\n        case ZigClangCK_IntToOCLSampler:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_IntToOCLSampler\");\n            return nullptr;\n        case ZigClangCK_LValueToRValueBitCast:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_LValueToRValueBitCast\");\n            return nullptr;\n        case ZigClangCK_FixedPointToIntegral:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_FixedPointToIntegral\");\n            return nullptr;\n        case ZigClangCK_IntegralToFixedPoint:\n            emit_warning(c, ZigClangImplicitCastExpr_getBeginLoc(stmt), \"TODO handle C CK_IntegralToFixedPointral\");\n            return nullptr;\n    }\n    zig_unreachable();\n}\n\nstatic AstNode *trans_decl_ref_expr(Context *c, TransScope *scope, const ZigClangDeclRefExpr *stmt, TransLRValue lrval) {\n    const ZigClangValueDecl *value_decl = ZigClangDeclRefExpr_getDecl(stmt);\n    Buf *c_symbol_name = buf_create_from_str(ZigClangDecl_getName_bytes_begin((const ZigClangDecl *)value_decl));\n    Buf *zig_symbol_name = trans_lookup_zig_symbol(c, scope, c_symbol_name);\n    if (lrval == TransLValue) {\n        c->ptr_params.put(zig_symbol_name, true);\n    }\n    return trans_create_node_symbol(c, zig_symbol_name);\n}\n\nstatic AstNode *trans_create_post_crement(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangUnaryOperator *stmt, BinOpType assign_op)\n{\n    const ZigClangExpr *op_expr = ZigClangUnaryOperator_getSubExpr(stmt);\n\n    if (result_used == ResultUsedNo) {\n        \/\/ common case\n        \/\/ c: expr++\n        \/\/ zig: expr += 1\n        return trans_create_node_bin_op(c,\n            trans_expr(c, ResultUsedYes, scope, op_expr, TransLValue),\n            assign_op,\n            trans_create_node_unsigned(c, 1));\n    }\n    \/\/ worst case\n    \/\/ c: expr++\n    \/\/ zig: (x: {\n    \/\/ zig:     const _ref = &expr;\n    \/\/ zig:     const _tmp = *_ref;\n    \/\/ zig:     *_ref += 1;\n    \/\/ zig:     break :x _tmp\n    \/\/ zig: })\n    TransScopeBlock *child_scope = trans_scope_block_create(c, scope);\n    Buf *label_name = buf_create_from_str(\"x\");\n    child_scope->node->data.block.name = label_name;\n\n    \/\/ const _ref = &expr;\n    AstNode *expr = trans_expr(c, ResultUsedYes, &child_scope->base, op_expr, TransLValue);\n    if (expr == nullptr) return nullptr;\n    AstNode *addr_of_expr = trans_create_node_addr_of(c, expr);\n    \/\/ TODO: avoid name collisions with generated variable names\n    Buf* ref_var_name = buf_create_from_str(\"_ref\");\n    AstNode *ref_var_decl = trans_create_node_var_decl_local(c, true, ref_var_name, nullptr, addr_of_expr);\n    child_scope->node->data.block.statements.append(ref_var_decl);\n\n    \/\/ const _tmp = *_ref;\n    Buf* tmp_var_name = buf_create_from_str(\"_tmp\");\n    AstNode *tmp_var_decl = trans_create_node_var_decl_local(c, true, tmp_var_name, nullptr,\n        trans_create_node_ptr_deref(c,\n            trans_create_node_symbol(c, ref_var_name)));\n    child_scope->node->data.block.statements.append(tmp_var_decl);\n\n    \/\/ *_ref += 1;\n    AstNode *assign_statement = trans_create_node_bin_op(c,\n        trans_create_node_ptr_deref(c,\n            trans_create_node_symbol(c, ref_var_name)),\n        assign_op,\n        trans_create_node_unsigned(c, 1));\n    child_scope->node->data.block.statements.append(assign_statement);\n\n    \/\/ break :x _tmp\n    child_scope->node->data.block.statements.append(trans_create_node_break(c, label_name, trans_create_node_symbol(c, tmp_var_name)));\n\n    return trans_create_node_grouped_expr(c, child_scope->node);\n}\n\nstatic AstNode *trans_create_pre_crement(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangUnaryOperator *stmt, BinOpType assign_op)\n{\n    const ZigClangExpr *op_expr = ZigClangUnaryOperator_getSubExpr(stmt);\n\n    if (result_used == ResultUsedNo) {\n        \/\/ common case\n        \/\/ c: ++expr\n        \/\/ zig: expr += 1\n        return trans_create_node_bin_op(c,\n            trans_expr(c, ResultUsedYes, scope, op_expr, TransLValue),\n            assign_op,\n            trans_create_node_unsigned(c, 1));\n    }\n    \/\/ worst case\n    \/\/ c: ++expr\n    \/\/ zig: (x: {\n    \/\/ zig:     const _ref = &expr;\n    \/\/ zig:     *_ref += 1;\n    \/\/ zig:     break :x *_ref\n    \/\/ zig: })\n    TransScopeBlock *child_scope = trans_scope_block_create(c, scope);\n    Buf *label_name = buf_create_from_str(\"x\");\n    child_scope->node->data.block.name = label_name;\n\n    \/\/ const _ref = &expr;\n    AstNode *expr = trans_expr(c, ResultUsedYes, &child_scope->base, op_expr, TransLValue);\n    if (expr == nullptr) return nullptr;\n    AstNode *addr_of_expr = trans_create_node_addr_of(c, expr);\n    \/\/ TODO: avoid name collisions with generated variable names\n    Buf* ref_var_name = buf_create_from_str(\"_ref\");\n    AstNode *ref_var_decl = trans_create_node_var_decl_local(c, true, ref_var_name, nullptr, addr_of_expr);\n    child_scope->node->data.block.statements.append(ref_var_decl);\n\n    \/\/ *_ref += 1;\n    AstNode *assign_statement = trans_create_node_bin_op(c,\n        trans_create_node_ptr_deref(c,\n            trans_create_node_symbol(c, ref_var_name)),\n        assign_op,\n        trans_create_node_unsigned(c, 1));\n    child_scope->node->data.block.statements.append(assign_statement);\n\n    \/\/ break :x *_ref\n    AstNode *deref_expr = trans_create_node_ptr_deref(c,\n            trans_create_node_symbol(c, ref_var_name));\n    child_scope->node->data.block.statements.append(trans_create_node_break(c, label_name, deref_expr));\n\n    return trans_create_node_grouped_expr(c, child_scope->node);\n}\n\nstatic AstNode *trans_unary_operator(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangUnaryOperator *stmt)\n{\n    switch (ZigClangUnaryOperator_getOpcode(stmt)) {\n        case ZigClangUO_PostInc:\n            if (qual_type_has_wrapping_overflow(c, ZigClangUnaryOperator_getType(stmt)))\n                return trans_create_post_crement(c, result_used, scope, stmt, BinOpTypeAssignPlusWrap);\n            else\n                return trans_create_post_crement(c, result_used, scope, stmt, BinOpTypeAssignPlus);\n        case ZigClangUO_PostDec:\n            if (qual_type_has_wrapping_overflow(c, ZigClangUnaryOperator_getType(stmt)))\n                return trans_create_post_crement(c, result_used, scope, stmt, BinOpTypeAssignMinusWrap);\n            else\n                return trans_create_post_crement(c, result_used, scope, stmt, BinOpTypeAssignMinus);\n        case ZigClangUO_PreInc:\n            if (qual_type_has_wrapping_overflow(c, ZigClangUnaryOperator_getType(stmt)))\n                return trans_create_pre_crement(c, result_used, scope, stmt, BinOpTypeAssignPlusWrap);\n            else\n                return trans_create_pre_crement(c, result_used, scope, stmt, BinOpTypeAssignPlus);\n        case ZigClangUO_PreDec:\n            if (qual_type_has_wrapping_overflow(c, ZigClangUnaryOperator_getType(stmt)))\n                return trans_create_pre_crement(c, result_used, scope, stmt, BinOpTypeAssignMinusWrap);\n            else\n                return trans_create_pre_crement(c, result_used, scope, stmt, BinOpTypeAssignMinus);\n        case ZigClangUO_AddrOf:\n            {\n                AstNode *value_node = trans_expr(c, result_used, scope, ZigClangUnaryOperator_getSubExpr(stmt), TransLValue);\n                if (value_node == nullptr)\n                    return value_node;\n                return trans_create_node_addr_of(c, value_node);\n            }\n        case ZigClangUO_Deref:\n            {\n                AstNode *value_node = trans_expr(c, result_used, scope, ZigClangUnaryOperator_getSubExpr(stmt), TransRValue);\n                if (value_node == nullptr)\n                    return nullptr;\n                bool is_fn_ptr = qual_type_is_fn_ptr(ZigClangExpr_getType(ZigClangUnaryOperator_getSubExpr(stmt)));\n                if (is_fn_ptr)\n                    return value_node;\n                AstNode *unwrapped = trans_create_node_unwrap_null(c, value_node);\n                return trans_create_node_ptr_deref(c, unwrapped);\n            }\n        case ZigClangUO_Plus:\n            emit_warning(c, ZigClangUnaryOperator_getBeginLoc(stmt), \"TODO handle C translation UO_Plus\");\n            return nullptr;\n        case ZigClangUO_Minus:\n            {\n                const ZigClangExpr *op_expr = ZigClangUnaryOperator_getSubExpr(stmt);\n                if (!qual_type_has_wrapping_overflow(c, ZigClangExpr_getType(op_expr))) {\n                    AstNode *node = trans_create_node(c, NodeTypePrefixOpExpr);\n                    node->data.prefix_op_expr.prefix_op = PrefixOpNegation;\n\n                    node->data.prefix_op_expr.primary_expr = trans_expr(c, ResultUsedYes, scope, op_expr, TransRValue);\n                    if (node->data.prefix_op_expr.primary_expr == nullptr)\n                        return nullptr;\n\n                    return node;\n                } else if (c_is_unsigned_integer(c, ZigClangExpr_getType(op_expr))) {\n                    \/\/ we gotta emit 0 -% x\n                    AstNode *node = trans_create_node(c, NodeTypeBinOpExpr);\n                    node->data.bin_op_expr.op1 = trans_create_node_unsigned(c, 0);\n\n                    node->data.bin_op_expr.op2 = trans_expr(c, ResultUsedYes, scope, op_expr, TransRValue);\n                    if (node->data.bin_op_expr.op2 == nullptr)\n                        return nullptr;\n\n                    node->data.bin_op_expr.bin_op = BinOpTypeSubWrap;\n                    return node;\n                } else {\n                    emit_warning(c, ZigClangUnaryOperator_getBeginLoc(stmt), \"C negation with non float non integer\");\n                    return nullptr;\n                }\n            }\n        case ZigClangUO_Not:\n            {\n                const ZigClangExpr *op_expr = ZigClangUnaryOperator_getSubExpr(stmt);\n                AstNode *sub_node = trans_expr(c, ResultUsedYes, scope, op_expr, TransRValue);\n                if (sub_node == nullptr)\n                    return nullptr;\n\n                return trans_create_node_prefix_op(c, PrefixOpBinNot, sub_node);\n            }\n        case ZigClangUO_LNot:\n            {\n                const ZigClangExpr *op_expr = ZigClangUnaryOperator_getSubExpr(stmt);\n                AstNode *sub_node = trans_bool_expr(c, ResultUsedYes, scope, op_expr, TransRValue);\n                if (sub_node == nullptr)\n                    return nullptr;\n\n                return trans_create_node_prefix_op(c, PrefixOpBoolNot, sub_node);\n            }\n        case ZigClangUO_Real:\n            emit_warning(c, ZigClangUnaryOperator_getBeginLoc(stmt), \"TODO handle C translation UO_Real\");\n            return nullptr;\n        case ZigClangUO_Imag:\n            emit_warning(c, ZigClangUnaryOperator_getBeginLoc(stmt), \"TODO handle C translation UO_Imag\");\n            return nullptr;\n        case ZigClangUO_Extension:\n            return trans_expr(c, result_used, scope, ZigClangUnaryOperator_getSubExpr(stmt), TransLValue);\n        case ZigClangUO_Coawait:\n            emit_warning(c, ZigClangUnaryOperator_getBeginLoc(stmt), \"TODO handle C translation UO_Coawait\");\n            return nullptr;\n    }\n    zig_unreachable();\n}\n\nstatic int trans_local_declaration(Context *c, TransScope *scope, const ZigClangDeclStmt *stmt,\n        AstNode **out_node, TransScope **out_scope)\n{\n    \/\/ declarations are added via the scope\n    *out_node = nullptr;\n\n    TransScopeBlock *scope_block = trans_scope_block_find(scope);\n    assert(scope_block != nullptr);\n\n    for (ZigClangDeclStmt_const_decl_iterator iter = ZigClangDeclStmt_decl_begin(stmt),\n            iter_end = ZigClangDeclStmt_decl_end(stmt);\n        iter != iter_end; ++iter)\n    {\n        ZigClangDecl *decl = *iter;\n        switch (ZigClangDecl_getKind(decl)) {\n            case ZigClangDeclVar: {\n                ZigClangVarDecl *var_decl = (ZigClangVarDecl *)decl;\n                ZigClangQualType qual_type = ZigClangVarDecl_getTypeSourceInfo_getType(var_decl);\n                AstNode *init_node = nullptr;\n                if (ZigClangVarDecl_hasInit(var_decl)) {\n                    init_node = trans_expr(c, ResultUsedYes, scope, ZigClangVarDecl_getInit(var_decl), TransRValue);\n                    if (init_node == nullptr)\n                        return ErrorUnexpected;\n\n                } else {\n                    init_node = trans_create_node(c, NodeTypeUndefinedLiteral);\n                }\n                AstNode *type_node = trans_qual_type(c, qual_type, ZigClangDeclStmt_getBeginLoc(stmt));\n                if (type_node == nullptr)\n                    return ErrorUnexpected;\n\n                Buf *c_symbol_name = buf_create_from_str(ZigClangDecl_getName_bytes_begin((const ZigClangDecl *)var_decl));\n\n                TransScopeVar *var_scope = trans_scope_var_create(c, scope, c_symbol_name);\n                scope = &var_scope->base;\n\n                AstNode *node = trans_create_node_var_decl_local(c,\n                        ZigClangQualType_isConstQualified(qual_type),\n                        var_scope->zig_name, type_node, init_node);\n\n                scope_block->node->data.block.statements.append(node);\n                continue;\n            }\n            case ZigClangDeclAccessSpec:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle decl kind AccessSpec\");\n                return ErrorUnexpected;\n            case ZigClangDeclBlock:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Block\");\n                return ErrorUnexpected;\n            case ZigClangDeclCaptured:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Captured\");\n                return ErrorUnexpected;\n            case ZigClangDeclClassScopeFunctionSpecialization:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ClassScopeFunctionSpecialization\");\n                return ErrorUnexpected;\n            case ZigClangDeclEmpty:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Empty\");\n                return ErrorUnexpected;\n            case ZigClangDeclExport:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Export\");\n                return ErrorUnexpected;\n            case ZigClangDeclExternCContext:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ExternCContext\");\n                return ErrorUnexpected;\n            case ZigClangDeclFileScopeAsm:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C FileScopeAsm\");\n                return ErrorUnexpected;\n            case ZigClangDeclFriend:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Friend\");\n                return ErrorUnexpected;\n            case ZigClangDeclFriendTemplate:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C FriendTemplate\");\n                return ErrorUnexpected;\n            case ZigClangDeclImport:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Import\");\n                return ErrorUnexpected;\n            case ZigClangDeclLinkageSpec:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C LinkageSpec\");\n                return ErrorUnexpected;\n            case ZigClangDeclLabel:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Label\");\n                return ErrorUnexpected;\n            case ZigClangDeclNamespace:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Namespace\");\n                return ErrorUnexpected;\n            case ZigClangDeclNamespaceAlias:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C NamespaceAlias\");\n                return ErrorUnexpected;\n            case ZigClangDeclObjCCompatibleAlias:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ObjCCompatibleAlias\");\n                return ErrorUnexpected;\n            case ZigClangDeclObjCCategory:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ObjCCategory\");\n                return ErrorUnexpected;\n            case ZigClangDeclObjCCategoryImpl:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ObjCCategoryImpl\");\n                return ErrorUnexpected;\n            case ZigClangDeclObjCImplementation:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ObjCImplementation\");\n                return ErrorUnexpected;\n            case ZigClangDeclObjCInterface:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ObjCInterface\");\n                return ErrorUnexpected;\n            case ZigClangDeclObjCProtocol:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ObjCProtocol\");\n                return ErrorUnexpected;\n            case ZigClangDeclObjCMethod:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ObjCMethod\");\n                return ErrorUnexpected;\n            case ZigClangDeclObjCProperty:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ObjCProperty\");\n                return ErrorUnexpected;\n            case ZigClangDeclBuiltinTemplate:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C BuiltinTemplate\");\n                return ErrorUnexpected;\n            case ZigClangDeclClassTemplate:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ClassTemplate\");\n                return ErrorUnexpected;\n            case ZigClangDeclFunctionTemplate:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C FunctionTemplate\");\n                return ErrorUnexpected;\n            case ZigClangDeclTypeAliasTemplate:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C TypeAliasTemplate\");\n                return ErrorUnexpected;\n            case ZigClangDeclVarTemplate:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C VarTemplate\");\n                return ErrorUnexpected;\n            case ZigClangDeclTemplateTemplateParm:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C TemplateTemplateParm\");\n                return ErrorUnexpected;\n            case ZigClangDeclEnum:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Enum\");\n                return ErrorUnexpected;\n            case ZigClangDeclRecord:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Record\");\n                return ErrorUnexpected;\n            case ZigClangDeclCXXRecord:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C CXXRecord\");\n                return ErrorUnexpected;\n            case ZigClangDeclClassTemplateSpecialization:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ClassTemplateSpecialization\");\n                return ErrorUnexpected;\n            case ZigClangDeclClassTemplatePartialSpecialization:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ClassTemplatePartialSpecialization\");\n                return ErrorUnexpected;\n            case ZigClangDeclTemplateTypeParm:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C TemplateTypeParm\");\n                return ErrorUnexpected;\n            case ZigClangDeclObjCTypeParam:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ObjCTypeParam\");\n                return ErrorUnexpected;\n            case ZigClangDeclTypeAlias:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C TypeAlias\");\n                return ErrorUnexpected;\n            case ZigClangDeclTypedef:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Typedef\");\n                return ErrorUnexpected;\n            case ZigClangDeclUnresolvedUsingTypename:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C UnresolvedUsingTypename\");\n                return ErrorUnexpected;\n            case ZigClangDeclUsing:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Using\");\n                return ErrorUnexpected;\n            case ZigClangDeclUsingDirective:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C UsingDirective\");\n                return ErrorUnexpected;\n            case ZigClangDeclUsingPack:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C UsingPack\");\n                return ErrorUnexpected;\n            case ZigClangDeclUsingShadow:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C UsingShadow\");\n                return ErrorUnexpected;\n            case ZigClangDeclConstructorUsingShadow:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ConstructorUsingShadow\");\n                return ErrorUnexpected;\n            case ZigClangDeclBinding:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Binding\");\n                return ErrorUnexpected;\n            case ZigClangDeclField:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Field\");\n                return ErrorUnexpected;\n            case ZigClangDeclObjCAtDefsField:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ObjCAtDefsField\");\n                return ErrorUnexpected;\n            case ZigClangDeclObjCIvar:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ObjCIvar\");\n                return ErrorUnexpected;\n            case ZigClangDeclFunction:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Function\");\n                return ErrorUnexpected;\n            case ZigClangDeclCXXDeductionGuide:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C CXXDeductionGuide\");\n                return ErrorUnexpected;\n            case ZigClangDeclCXXMethod:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C CXXMethod\");\n                return ErrorUnexpected;\n            case ZigClangDeclCXXConstructor:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C CXXConstructor\");\n                return ErrorUnexpected;\n            case ZigClangDeclCXXConversion:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C CXXConversion\");\n                return ErrorUnexpected;\n            case ZigClangDeclCXXDestructor:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C CXXDestructor\");\n                return ErrorUnexpected;\n            case ZigClangDeclMSProperty:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C MSProperty\");\n                return ErrorUnexpected;\n            case ZigClangDeclNonTypeTemplateParm:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C NonTypeTemplateParm\");\n                return ErrorUnexpected;\n            case ZigClangDeclDecomposition:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Decomposition\");\n                return ErrorUnexpected;\n            case ZigClangDeclImplicitParam:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ImplicitParam\");\n                return ErrorUnexpected;\n            case ZigClangDeclOMPCapturedExpr:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C OMPCapturedExpr\");\n                return ErrorUnexpected;\n            case ZigClangDeclParmVar:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ParmVar\");\n                return ErrorUnexpected;\n            case ZigClangDeclVarTemplateSpecialization:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C VarTemplateSpecialization\");\n                return ErrorUnexpected;\n            case ZigClangDeclVarTemplatePartialSpecialization:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C VarTemplatePartialSpecialization\");\n                return ErrorUnexpected;\n            case ZigClangDeclEnumConstant:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C EnumConstant\");\n                return ErrorUnexpected;\n            case ZigClangDeclIndirectField:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C IndirectField\");\n                return ErrorUnexpected;\n            case ZigClangDeclOMPDeclareReduction:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C OMPDeclareReduction\");\n                return ErrorUnexpected;\n            case ZigClangDeclUnresolvedUsingValue:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C UnresolvedUsingValue\");\n                return ErrorUnexpected;\n            case ZigClangDeclOMPRequires:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C OMPRequires\");\n                return ErrorUnexpected;\n            case ZigClangDeclOMPThreadPrivate:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C OMPThreadPrivate\");\n                return ErrorUnexpected;\n            case ZigClangDeclObjCPropertyImpl:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C ObjCPropertyImpl\");\n                return ErrorUnexpected;\n            case ZigClangDeclPragmaComment:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C PragmaComment\");\n                return ErrorUnexpected;\n            case ZigClangDeclPragmaDetectMismatch:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C PragmaDetectMismatch\");\n                return ErrorUnexpected;\n            case ZigClangDeclStaticAssert:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C StaticAssert\");\n                return ErrorUnexpected;\n            case ZigClangDeclTranslationUnit:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C TranslationUnit\");\n                return ErrorUnexpected;\n            case ZigClangDeclConcept:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C Concept\");\n                return ErrorUnexpected;\n            case ZigClangDeclOMPDeclareMapper:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C OMPDeclareMapper\");\n                return ErrorUnexpected;\n            case ZigClangDeclOMPAllocate:\n                emit_warning(c, ZigClangDeclStmt_getBeginLoc(stmt), \"TODO handle C OMPAllocate\");\n                return ErrorUnexpected;\n        }\n        zig_unreachable();\n    }\n\n    *out_scope = scope;\n    return ErrorNone;\n}\n\nstatic AstNode *to_enum_zero_cmp(Context *c, AstNode *expr, AstNode *enum_type) {\n    AstNode *tag_type = trans_create_node_builtin_fn_call_str(c, \"TagType\");\n    tag_type->data.fn_call_expr.params.append(enum_type);\n\n    \/\/ @TagType(Enum)(0)\n    AstNode *zero = trans_create_node_unsigned_negative(c, 0, false);\n    AstNode *casted_zero = trans_create_node_cast(c, tag_type, zero);\n\n    \/\/ @bitCast(Enum, @TagType(Enum)(0))\n    AstNode *bitcast = trans_create_node_builtin_fn_call_str(c, \"bitCast\");\n    bitcast->data.fn_call_expr.params.append(enum_type);\n    bitcast->data.fn_call_expr.params.append(casted_zero);\n\n    return trans_create_node_bin_op(c, expr, BinOpTypeCmpNotEq, bitcast);\n}\n\nstatic AstNode *trans_bool_expr(Context *c, ResultUsed result_used, TransScope *scope, const ZigClangExpr *expr, TransLRValue lrval) {\n    AstNode *res = trans_expr(c, result_used, scope, expr, lrval);\n    if (res == nullptr)\n        return nullptr;\n\n    switch (res->type) {\n        case NodeTypeBinOpExpr:\n            switch (res->data.bin_op_expr.bin_op) {\n                case BinOpTypeBoolOr:\n                case BinOpTypeBoolAnd:\n                case BinOpTypeCmpEq:\n                case BinOpTypeCmpNotEq:\n                case BinOpTypeCmpLessThan:\n                case BinOpTypeCmpGreaterThan:\n                case BinOpTypeCmpLessOrEq:\n                case BinOpTypeCmpGreaterOrEq:\n                    return res;\n                default:\n                    break;\n            }\n\n        case NodeTypePrefixOpExpr:\n            switch (res->data.prefix_op_expr.prefix_op) {\n                case PrefixOpBoolNot:\n                    return res;\n                default:\n                    break;\n            }\n\n        case NodeTypeBoolLiteral:\n            return res;\n\n        default:\n            break;\n    }\n\n\n    const ZigClangType *ty = ZigClangQualType_getTypePtr(get_expr_qual_type_before_implicit_cast(c, expr));\n    auto classs = ZigClangType_getTypeClass(ty);\n    switch (classs) {\n        case ZigClangType_Builtin:\n        {\n            const ZigClangBuiltinType *builtin_ty = reinterpret_cast<const ZigClangBuiltinType*>(ty);\n            switch (ZigClangBuiltinType_getKind(builtin_ty)) {\n                case ZigClangBuiltinTypeBool:\n                case ZigClangBuiltinTypeChar_U:\n                case ZigClangBuiltinTypeUChar:\n                case ZigClangBuiltinTypeChar_S:\n                case ZigClangBuiltinTypeSChar:\n                case ZigClangBuiltinTypeUShort:\n                case ZigClangBuiltinTypeUInt:\n                case ZigClangBuiltinTypeULong:\n                case ZigClangBuiltinTypeULongLong:\n                case ZigClangBuiltinTypeShort:\n                case ZigClangBuiltinTypeInt:\n                case ZigClangBuiltinTypeLong:\n                case ZigClangBuiltinTypeLongLong:\n                case ZigClangBuiltinTypeUInt128:\n                case ZigClangBuiltinTypeInt128:\n                case ZigClangBuiltinTypeFloat:\n                case ZigClangBuiltinTypeDouble:\n                case ZigClangBuiltinTypeFloat128:\n                case ZigClangBuiltinTypeLongDouble:\n                case ZigClangBuiltinTypeWChar_U:\n                case ZigClangBuiltinTypeChar8:\n                case ZigClangBuiltinTypeChar16:\n                case ZigClangBuiltinTypeChar32:\n                case ZigClangBuiltinTypeWChar_S:\n                case ZigClangBuiltinTypeFloat16:\n                    return trans_create_node_bin_op(c, res, BinOpTypeCmpNotEq, trans_create_node_unsigned_negative(c, 0, false));\n                case ZigClangBuiltinTypeNullPtr:\n                    return trans_create_node_bin_op(c, res, BinOpTypeCmpNotEq,\n                            trans_create_node(c, NodeTypeNullLiteral));\n\n                case ZigClangBuiltinTypeVoid:\n                case ZigClangBuiltinTypeHalf:\n                case ZigClangBuiltinTypeObjCId:\n                case ZigClangBuiltinTypeObjCClass:\n                case ZigClangBuiltinTypeObjCSel:\n                case ZigClangBuiltinTypeOMPArraySection:\n                case ZigClangBuiltinTypeDependent:\n                case ZigClangBuiltinTypeOverload:\n                case ZigClangBuiltinTypeBoundMember:\n                case ZigClangBuiltinTypePseudoObject:\n                case ZigClangBuiltinTypeUnknownAny:\n                case ZigClangBuiltinTypeBuiltinFn:\n                case ZigClangBuiltinTypeARCUnbridgedCast:\n                case ZigClangBuiltinTypeOCLImage1dRO:\n                case ZigClangBuiltinTypeOCLImage1dArrayRO:\n                case ZigClangBuiltinTypeOCLImage1dBufferRO:\n                case ZigClangBuiltinTypeOCLImage2dRO:\n                case ZigClangBuiltinTypeOCLImage2dArrayRO:\n                case ZigClangBuiltinTypeOCLImage2dDepthRO:\n                case ZigClangBuiltinTypeOCLImage2dArrayDepthRO:\n                case ZigClangBuiltinTypeOCLImage2dMSAARO:\n                case ZigClangBuiltinTypeOCLImage2dArrayMSAARO:\n                case ZigClangBuiltinTypeOCLImage2dMSAADepthRO:\n                case ZigClangBuiltinTypeOCLImage2dArrayMSAADepthRO:\n                case ZigClangBuiltinTypeOCLImage3dRO:\n                case ZigClangBuiltinTypeOCLImage1dWO:\n                case ZigClangBuiltinTypeOCLImage1dArrayWO:\n                case ZigClangBuiltinTypeOCLImage1dBufferWO:\n                case ZigClangBuiltinTypeOCLImage2dWO:\n                case ZigClangBuiltinTypeOCLImage2dArrayWO:\n                case ZigClangBuiltinTypeOCLImage2dDepthWO:\n                case ZigClangBuiltinTypeOCLImage2dArrayDepthWO:\n                case ZigClangBuiltinTypeOCLImage2dMSAAWO:\n                case ZigClangBuiltinTypeOCLImage2dArrayMSAAWO:\n                case ZigClangBuiltinTypeOCLImage2dMSAADepthWO:\n                case ZigClangBuiltinTypeOCLImage2dArrayMSAADepthWO:\n                case ZigClangBuiltinTypeOCLImage3dWO:\n                case ZigClangBuiltinTypeOCLImage1dRW:\n                case ZigClangBuiltinTypeOCLImage1dArrayRW:\n                case ZigClangBuiltinTypeOCLImage1dBufferRW:\n                case ZigClangBuiltinTypeOCLImage2dRW:\n                case ZigClangBuiltinTypeOCLImage2dArrayRW:\n                case ZigClangBuiltinTypeOCLImage2dDepthRW:\n                case ZigClangBuiltinTypeOCLImage2dArrayDepthRW:\n                case ZigClangBuiltinTypeOCLImage2dMSAARW:\n                case ZigClangBuiltinTypeOCLImage2dArrayMSAARW:\n                case ZigClangBuiltinTypeOCLImage2dMSAADepthRW:\n                case ZigClangBuiltinTypeOCLImage2dArrayMSAADepthRW:\n                case ZigClangBuiltinTypeOCLImage3dRW:\n                case ZigClangBuiltinTypeOCLSampler:\n                case ZigClangBuiltinTypeOCLEvent:\n                case ZigClangBuiltinTypeOCLClkEvent:\n                case ZigClangBuiltinTypeOCLQueue:\n                case ZigClangBuiltinTypeOCLReserveID:\n                case ZigClangBuiltinTypeShortAccum:\n                case ZigClangBuiltinTypeAccum:\n                case ZigClangBuiltinTypeLongAccum:\n                case ZigClangBuiltinTypeUShortAccum:\n                case ZigClangBuiltinTypeUAccum:\n                case ZigClangBuiltinTypeULongAccum:\n                case ZigClangBuiltinTypeShortFract:\n                case ZigClangBuiltinTypeFract:\n                case ZigClangBuiltinTypeLongFract:\n                case ZigClangBuiltinTypeUShortFract:\n                case ZigClangBuiltinTypeUFract:\n                case ZigClangBuiltinTypeULongFract:\n                case ZigClangBuiltinTypeSatShortAccum:\n                case ZigClangBuiltinTypeSatAccum:\n                case ZigClangBuiltinTypeSatLongAccum:\n                case ZigClangBuiltinTypeSatUShortAccum:\n                case ZigClangBuiltinTypeSatUAccum:\n                case ZigClangBuiltinTypeSatULongAccum:\n                case ZigClangBuiltinTypeSatShortFract:\n                case ZigClangBuiltinTypeSatFract:\n                case ZigClangBuiltinTypeSatLongFract:\n                case ZigClangBuiltinTypeSatUShortFract:\n                case ZigClangBuiltinTypeSatUFract:\n                case ZigClangBuiltinTypeSatULongFract:\n                case ZigClangBuiltinTypeOCLIntelSubgroupAVCMcePayload:\n                case ZigClangBuiltinTypeOCLIntelSubgroupAVCImePayload:\n                case ZigClangBuiltinTypeOCLIntelSubgroupAVCRefPayload:\n                case ZigClangBuiltinTypeOCLIntelSubgroupAVCSicPayload:\n                case ZigClangBuiltinTypeOCLIntelSubgroupAVCMceResult:\n                case ZigClangBuiltinTypeOCLIntelSubgroupAVCImeResult:\n                case ZigClangBuiltinTypeOCLIntelSubgroupAVCRefResult:\n                case ZigClangBuiltinTypeOCLIntelSubgroupAVCSicResult:\n                case ZigClangBuiltinTypeOCLIntelSubgroupAVCImeResultSingleRefStreamout:\n                case ZigClangBuiltinTypeOCLIntelSubgroupAVCImeResultDualRefStreamout:\n                case ZigClangBuiltinTypeOCLIntelSubgroupAVCImeSingleRefStreamin:\n                case ZigClangBuiltinTypeOCLIntelSubgroupAVCImeDualRefStreamin:\n                    return res;\n            }\n            break;\n        }\n        case ZigClangType_Pointer:\n            return trans_create_node_bin_op(c, res, BinOpTypeCmpNotEq, trans_create_node(c, NodeTypeNullLiteral));\n\n        case ZigClangType_Typedef:\n        {\n            const ZigClangTypedefType *typedef_ty = reinterpret_cast<const ZigClangTypedefType*>(ty);\n            const ZigClangTypedefNameDecl *typedef_decl = ZigClangTypedefType_getDecl(typedef_ty);\n            auto existing_entry = c->decl_table.maybe_get((void*)ZigClangTypedefNameDecl_getCanonicalDecl(typedef_decl));\n            if (existing_entry) {\n                return existing_entry->value;\n            }\n\n            return res;\n        }\n\n        case ZigClangType_Enum:\n        {\n            const ZigClangEnumType *enum_ty = reinterpret_cast<const ZigClangEnumType *>(ty);\n            AstNode *enum_type = resolve_enum_decl(c, ZigClangEnumType_getDecl(enum_ty));\n            return to_enum_zero_cmp(c, res, enum_type);\n        }\n\n        case ZigClangType_Elaborated:\n        {\n            const ZigClangElaboratedType *elaborated_ty = reinterpret_cast<const ZigClangElaboratedType*>(ty);\n            switch (ZigClangElaboratedType_getKeyword(elaborated_ty)) {\n                case ZigClangETK_Enum: {\n                    AstNode *enum_type = trans_qual_type(c, ZigClangElaboratedType_getNamedType(elaborated_ty),\n                            ZigClangExpr_getBeginLoc(expr));\n                    return to_enum_zero_cmp(c, res, enum_type);\n                }\n                case ZigClangETK_Struct:\n                case ZigClangETK_Union:\n                case ZigClangETK_Interface:\n                case ZigClangETK_Class:\n                case ZigClangETK_Typename:\n                case ZigClangETK_None:\n                    return res;\n            }\n        }\n\n        case ZigClangType_FunctionProto:\n        case ZigClangType_Record:\n        case ZigClangType_ConstantArray:\n        case ZigClangType_Paren:\n        case ZigClangType_Decayed:\n        case ZigClangType_Attributed:\n        case ZigClangType_IncompleteArray:\n        case ZigClangType_BlockPointer:\n        case ZigClangType_LValueReference:\n        case ZigClangType_RValueReference:\n        case ZigClangType_MemberPointer:\n        case ZigClangType_VariableArray:\n        case ZigClangType_DependentSizedArray:\n        case ZigClangType_DependentSizedExtVector:\n        case ZigClangType_Vector:\n        case ZigClangType_ExtVector:\n        case ZigClangType_FunctionNoProto:\n        case ZigClangType_UnresolvedUsing:\n        case ZigClangType_Adjusted:\n        case ZigClangType_TypeOfExpr:\n        case ZigClangType_TypeOf:\n        case ZigClangType_Decltype:\n        case ZigClangType_UnaryTransform:\n        case ZigClangType_TemplateTypeParm:\n        case ZigClangType_SubstTemplateTypeParm:\n        case ZigClangType_SubstTemplateTypeParmPack:\n        case ZigClangType_TemplateSpecialization:\n        case ZigClangType_Auto:\n        case ZigClangType_InjectedClassName:\n        case ZigClangType_DependentName:\n        case ZigClangType_DependentTemplateSpecialization:\n        case ZigClangType_PackExpansion:\n        case ZigClangType_ObjCObject:\n        case ZigClangType_ObjCInterface:\n        case ZigClangType_Complex:\n        case ZigClangType_ObjCObjectPointer:\n        case ZigClangType_Atomic:\n        case ZigClangType_Pipe:\n        case ZigClangType_ObjCTypeParam:\n        case ZigClangType_DeducedTemplateSpecialization:\n        case ZigClangType_DependentAddressSpace:\n        case ZigClangType_DependentVector:\n        case ZigClangType_MacroQualified:\n            return res;\n    }\n    zig_unreachable();\n}\n\nstatic AstNode *trans_while_loop(Context *c, TransScope *scope, const ZigClangWhileStmt *stmt) {\n    TransScopeWhile *while_scope = trans_scope_while_create(c, scope);\n\n    while_scope->node->data.while_expr.condition = trans_bool_expr(c, ResultUsedYes, scope,\n            ZigClangWhileStmt_getCond(stmt), TransRValue);\n    if (while_scope->node->data.while_expr.condition == nullptr)\n        return nullptr;\n\n    TransScope *body_scope = trans_stmt(c, &while_scope->base, ZigClangWhileStmt_getBody(stmt),\n            &while_scope->node->data.while_expr.body);\n    if (body_scope == nullptr)\n        return nullptr;\n\n    return while_scope->node;\n}\n\nstatic AstNode *trans_if_statement(Context *c, TransScope *scope, const ZigClangIfStmt *stmt) {\n    \/\/ if (c) t\n    \/\/ if (c) t else e\n    AstNode *if_node = trans_create_node(c, NodeTypeIfBoolExpr);\n\n    TransScope *then_scope = trans_stmt(c, scope, ZigClangIfStmt_getThen(stmt), &if_node->data.if_bool_expr.then_block);\n    if (then_scope == nullptr)\n        return nullptr;\n\n    if (ZigClangIfStmt_getElse(stmt) != nullptr) {\n        TransScope *else_scope = trans_stmt(c, scope, ZigClangIfStmt_getElse(stmt), &if_node->data.if_bool_expr.else_node);\n        if (else_scope == nullptr)\n            return nullptr;\n    }\n\n    if_node->data.if_bool_expr.condition = trans_bool_expr(c, ResultUsedYes, scope, ZigClangIfStmt_getCond(stmt),\n            TransRValue);\n    if (if_node->data.if_bool_expr.condition == nullptr)\n        return nullptr;\n\n    return if_node;\n}\n\nstatic AstNode *trans_call_expr(Context *c, ResultUsed result_used, TransScope *scope, const ZigClangCallExpr *stmt) {\n    AstNode *node = trans_create_node(c, NodeTypeFnCallExpr);\n\n    AstNode *callee_raw_node = trans_expr(c, ResultUsedYes, scope, ZigClangCallExpr_getCallee(stmt), TransRValue);\n    if (callee_raw_node == nullptr)\n        return nullptr;\n\n    bool is_ptr = false;\n    const ZigClangFunctionProtoType *fn_ty = qual_type_get_fn_proto(\n            ZigClangExpr_getType(ZigClangCallExpr_getCallee(stmt)), &is_ptr);\n    AstNode *callee_node = nullptr;\n    if (is_ptr && fn_ty) {\n        if (ZigClangExpr_getStmtClass(ZigClangCallExpr_getCallee(stmt)) == ZigClangStmt_ImplicitCastExprClass) {\n            const ZigClangImplicitCastExpr *implicit_cast = reinterpret_cast<const ZigClangImplicitCastExpr *>(\n                    ZigClangCallExpr_getCallee(stmt));\n            if (ZigClangImplicitCastExpr_getCastKind(implicit_cast) == ZigClangCK_FunctionToPointerDecay) {\n                const ZigClangExpr *subexpr = ZigClangImplicitCastExpr_getSubExpr(implicit_cast);\n                if (ZigClangExpr_getStmtClass(subexpr) == ZigClangStmt_DeclRefExprClass) {\n                    const ZigClangDeclRefExpr *decl_ref = reinterpret_cast<const ZigClangDeclRefExpr *>(subexpr);\n                    const ZigClangNamedDecl *named_decl = ZigClangDeclRefExpr_getFoundDecl(decl_ref);\n                    if (ZigClangDecl_getKind((const ZigClangDecl *)named_decl) == ZigClangDeclFunction) {\n                        callee_node = callee_raw_node;\n                    }\n                }\n            }\n        }\n        if (callee_node == nullptr) {\n            callee_node = trans_create_node_unwrap_null(c, callee_raw_node);\n        }\n    } else {\n        callee_node = callee_raw_node;\n    }\n\n    node->data.fn_call_expr.fn_ref_expr = callee_node;\n\n    unsigned num_args = ZigClangCallExpr_getNumArgs(stmt);\n    const ZigClangExpr * const* args = ZigClangCallExpr_getArgs(stmt);\n    for (unsigned i = 0; i < num_args; i += 1) {\n        AstNode *arg_node = trans_expr(c, ResultUsedYes, scope, args[i], TransRValue);\n        if (arg_node == nullptr)\n            return nullptr;\n\n        node->data.fn_call_expr.params.append(arg_node);\n    }\n\n    if (result_used == ResultUsedNo && fn_ty &&\n        !ZigClangType_isVoidType(qual_type_canon(ZigClangFunctionProtoType_getReturnType(fn_ty))))\n    {\n        node = trans_create_node_bin_op(c, trans_create_node_symbol_str(c, \"_\"), BinOpTypeAssign, node);\n    }\n\n    return node;\n}\n\nstatic AstNode *trans_member_expr(Context *c, ResultUsed result_used, TransScope *scope,\n    const ZigClangMemberExpr *stmt)\n{\n    AstNode *container_node = trans_expr(c, ResultUsedYes, scope, ZigClangMemberExpr_getBase(stmt), TransRValue);\n    if (container_node == nullptr)\n        return nullptr;\n\n    if (ZigClangMemberExpr_isArrow(stmt)) {\n        container_node = trans_create_node_ptr_deref(c, container_node);\n    }\n\n    const char *name = ZigClangDecl_getName_bytes_begin((const ZigClangDecl *)ZigClangMemberExpr_getMemberDecl(stmt));\n\n    AstNode *node = trans_create_node_field_access_str(c, container_node, name);\n    return maybe_suppress_result(c, result_used, node);\n}\n\nstatic AstNode *trans_array_subscript_expr(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangArraySubscriptExpr *stmt)\n{\n    AstNode *container_node = trans_expr(c, ResultUsedYes, scope, ZigClangArraySubscriptExpr_getBase(stmt),\n            TransRValue);\n    if (container_node == nullptr)\n        return nullptr;\n\n    AstNode *idx_node = trans_expr(c, ResultUsedYes, scope, ZigClangArraySubscriptExpr_getIdx(stmt), TransRValue);\n    if (idx_node == nullptr)\n        return nullptr;\n\n\n    AstNode *node = trans_create_node(c, NodeTypeArrayAccessExpr);\n    node->data.array_access_expr.array_ref_expr = container_node;\n    node->data.array_access_expr.subscript = idx_node;\n    return maybe_suppress_result(c, result_used, node);\n}\n\nstatic AstNode *trans_c_style_cast_expr(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangCStyleCastExpr *stmt, TransLRValue lrvalue)\n{\n    AstNode *sub_expr_node = trans_expr(c, ResultUsedYes, scope, ZigClangCStyleCastExpr_getSubExpr(stmt), lrvalue);\n    if (sub_expr_node == nullptr)\n        return nullptr;\n\n    AstNode *cast = trans_c_cast(c, ZigClangCStyleCastExpr_getBeginLoc(stmt), ZigClangCStyleCastExpr_getType(stmt),\n            ZigClangExpr_getType(ZigClangCStyleCastExpr_getSubExpr(stmt)), sub_expr_node);\n    if (cast == nullptr)\n        return nullptr;\n\n    return maybe_suppress_result(c, result_used, cast);\n}\n\nstatic AstNode *trans_unary_expr_or_type_trait_expr(Context *c, ResultUsed result_used,\n        TransScope *scope, const ZigClangUnaryExprOrTypeTraitExpr *stmt)\n{\n    AstNode *type_node = trans_qual_type(c, ZigClangUnaryExprOrTypeTraitExpr_getTypeOfArgument(stmt),\n            ZigClangUnaryExprOrTypeTraitExpr_getBeginLoc(stmt));\n    if (type_node == nullptr)\n        return nullptr;\n\n    AstNode *node = trans_create_node_builtin_fn_call_str(c, \"sizeOf\");\n    node->data.fn_call_expr.params.append(type_node);\n    return maybe_suppress_result(c, result_used, node);\n}\n\nstatic AstNode *trans_do_loop(Context *c, TransScope *parent_scope, const ZigClangDoStmt *stmt) {\n    TransScopeWhile *while_scope = trans_scope_while_create(c, parent_scope);\n\n    while_scope->node->data.while_expr.condition = trans_create_node_bool(c, true);\n\n    AstNode *body_node;\n    TransScope *child_scope;\n    if (ZigClangStmt_getStmtClass(ZigClangDoStmt_getBody(stmt)) == ZigClangStmt_CompoundStmtClass) {\n        \/\/ there's already a block in C, so we'll append our condition to it.\n        \/\/ c: do {\n        \/\/ c:   a;\n        \/\/ c:   b;\n        \/\/ c: } while(c);\n        \/\/ zig: while (true) {\n        \/\/ zig:   a;\n        \/\/ zig:   b;\n        \/\/ zig:   if (!cond) break;\n        \/\/ zig: }\n\n        \/\/ We call the low level function so that we can set child_scope to the scope of the generated block.\n        if (trans_stmt_extra(c, &while_scope->base, ZigClangDoStmt_getBody(stmt), ResultUsedNo, TransRValue,\n                    &body_node, nullptr, &child_scope))\n        {\n            return nullptr;\n        }\n        assert(body_node->type == NodeTypeBlock);\n    } else {\n        \/\/ the C statement is without a block, so we need to create a block to contain it.\n        \/\/ c: do\n        \/\/ c:   a;\n        \/\/ c: while(c);\n        \/\/ zig: while (true) {\n        \/\/ zig:   a;\n        \/\/ zig:   if (!cond) break;\n        \/\/ zig: }\n        TransScopeBlock *child_block_scope = trans_scope_block_create(c, &while_scope->base);\n        body_node = child_block_scope->node;\n        AstNode *child_statement;\n        child_scope = trans_stmt(c, &child_block_scope->base, ZigClangDoStmt_getBody(stmt), &child_statement);\n        if (child_scope == nullptr) return nullptr;\n        if (child_statement != nullptr) {\n            body_node->data.block.statements.append(child_statement);\n        }\n    }\n\n    \/\/ if (!cond) break;\n    AstNode *condition_node = trans_expr(c, ResultUsedYes, child_scope, ZigClangDoStmt_getCond(stmt), TransRValue);\n    if (condition_node == nullptr) return nullptr;\n    AstNode *terminator_node = trans_create_node(c, NodeTypeIfBoolExpr);\n    terminator_node->data.if_bool_expr.condition = trans_create_node_prefix_op(c, PrefixOpBoolNot, condition_node);\n    terminator_node->data.if_bool_expr.then_block = trans_create_node(c, NodeTypeBreak);\n\n    assert(terminator_node != nullptr);\n    body_node->data.block.statements.append(terminator_node);\n\n    while_scope->node->data.while_expr.body = body_node;\n\n    return while_scope->node;\n}\n\nstatic AstNode *trans_for_loop(Context *c, TransScope *parent_scope, const ZigClangForStmt *stmt) {\n    AstNode *loop_block_node;\n    TransScopeWhile *while_scope;\n    TransScope *cond_scope;\n    const ZigClangStmt *init_stmt = ZigClangForStmt_getInit(stmt);\n    if (init_stmt == nullptr) {\n        while_scope = trans_scope_while_create(c, parent_scope);\n        loop_block_node = while_scope->node;\n        cond_scope = parent_scope;\n    } else {\n        TransScopeBlock *child_scope = trans_scope_block_create(c, parent_scope);\n        loop_block_node = child_scope->node;\n\n        AstNode *vars_node;\n        cond_scope = trans_stmt(c, &child_scope->base, init_stmt, &vars_node);\n        if (cond_scope == nullptr)\n            return nullptr;\n        if (vars_node != nullptr)\n            child_scope->node->data.block.statements.append(vars_node);\n\n        while_scope = trans_scope_while_create(c, cond_scope);\n\n        child_scope->node->data.block.statements.append(while_scope->node);\n    }\n\n    const ZigClangExpr *cond_expr = ZigClangForStmt_getCond(stmt);\n    if (cond_expr == nullptr) {\n        while_scope->node->data.while_expr.condition = trans_create_node_bool(c, true);\n    } else {\n        while_scope->node->data.while_expr.condition = trans_bool_expr(c, ResultUsedYes, cond_scope,\n                cond_expr, TransRValue);\n\n        if (while_scope->node->data.while_expr.condition == nullptr)\n            return nullptr;\n    }\n\n    const ZigClangExpr *inc_expr = ZigClangForStmt_getInc(stmt);\n    if (inc_expr != nullptr) {\n        AstNode *inc_node = trans_expr(c, ResultUsedNo, cond_scope, inc_expr, TransRValue);\n        if (inc_node == nullptr)\n            return nullptr;\n        while_scope->node->data.while_expr.continue_expr = inc_node;\n    }\n\n    AstNode *body_statement;\n    TransScope *body_scope = trans_stmt(c, &while_scope->base, ZigClangForStmt_getBody(stmt), &body_statement);\n    if (body_scope == nullptr)\n        return nullptr;\n\n    if (body_statement == nullptr) {\n        while_scope->node->data.while_expr.body = trans_create_node(c, NodeTypeBlock);\n    } else {\n        while_scope->node->data.while_expr.body = body_statement;\n    }\n\n    return loop_block_node;\n}\n\nstatic AstNode *trans_switch_stmt(Context *c, TransScope *parent_scope, const ZigClangSwitchStmt *stmt) {\n    TransScopeBlock *block_scope = trans_scope_block_create(c, parent_scope);\n\n    TransScopeSwitch *switch_scope;\n\n    const ZigClangDeclStmt *var_decl_stmt = ZigClangSwitchStmt_getConditionVariableDeclStmt(stmt);\n    if (var_decl_stmt == nullptr) {\n        switch_scope = trans_scope_switch_create(c, &block_scope->base);\n    } else {\n        AstNode *vars_node;\n        TransScope *var_scope = trans_stmt(c, &block_scope->base, (const ZigClangStmt *)var_decl_stmt, &vars_node);\n        if (var_scope == nullptr)\n            return nullptr;\n        if (vars_node != nullptr)\n            block_scope->node->data.block.statements.append(vars_node);\n        switch_scope = trans_scope_switch_create(c, var_scope);\n    }\n    block_scope->node->data.block.statements.append(switch_scope->switch_node);\n\n    \/\/ TODO avoid name collisions\n    Buf *end_label_name = buf_create_from_str(\"__switch\");\n    switch_scope->end_label_name = end_label_name;\n    block_scope->node->data.block.name = end_label_name;\n\n    const ZigClangExpr *cond_expr = ZigClangSwitchStmt_getCond(stmt);\n    assert(cond_expr != nullptr);\n\n    AstNode *expr_node = trans_expr(c, ResultUsedYes, &block_scope->base, cond_expr, TransRValue);\n    if (expr_node == nullptr)\n        return nullptr;\n    switch_scope->switch_node->data.switch_expr.expr = expr_node;\n\n    AstNode *body_node;\n    const ZigClangStmt *body_stmt = ZigClangSwitchStmt_getBody(stmt);\n    if (ZigClangStmt_getStmtClass(body_stmt) == ZigClangStmt_CompoundStmtClass) {\n        if (trans_compound_stmt_inline(c, &switch_scope->base, (const ZigClangCompoundStmt *)body_stmt,\n                                       block_scope->node, nullptr))\n        {\n            return nullptr;\n        }\n    } else {\n        TransScope *body_scope = trans_stmt(c, &switch_scope->base, body_stmt, &body_node);\n        if (body_scope == nullptr)\n            return nullptr;\n        if (body_node != nullptr)\n            block_scope->node->data.block.statements.append(body_node);\n    }\n\n    if (!switch_scope->found_default && !ZigClangSwitchStmt_isAllEnumCasesCovered(stmt)) {\n        AstNode *prong_node = trans_create_node(c, NodeTypeSwitchProng);\n        prong_node->data.switch_prong.expr = trans_create_node_break(c, end_label_name, nullptr);\n        switch_scope->switch_node->data.switch_expr.prongs.append(prong_node);\n    }\n\n    return block_scope->node;\n}\n\nstatic TransScopeSwitch *trans_scope_switch_find(TransScope *scope) {\n    while (scope != nullptr) {\n        if (scope->id == TransScopeIdSwitch) {\n            return (TransScopeSwitch *)scope;\n        }\n        scope = scope->parent;\n    }\n    return nullptr;\n}\n\nstatic int trans_switch_case(Context *c, TransScope *parent_scope, const ZigClangCaseStmt *stmt, AstNode **out_node,\n                             TransScope **out_scope) {\n    *out_node = nullptr;\n\n    if (ZigClangCaseStmt_getRHS(stmt) != nullptr) {\n        emit_warning(c, ZigClangCaseStmt_getBeginLoc(stmt), \"TODO support GNU switch case a ... b extension\");\n        return ErrorUnexpected;\n    }\n\n    TransScopeSwitch *switch_scope = trans_scope_switch_find(parent_scope);\n    assert(switch_scope != nullptr);\n\n    Buf *label_name = buf_sprintf(\"__case_%\" PRIu32, switch_scope->case_index);\n    switch_scope->case_index += 1;\n\n    {\n        \/\/ Add the prong\n        AstNode *prong_node = trans_create_node(c, NodeTypeSwitchProng);\n        AstNode *item_node = trans_expr(c, ResultUsedYes, &switch_scope->base, ZigClangCaseStmt_getLHS(stmt),\n                TransRValue);\n        if (item_node == nullptr)\n            return ErrorUnexpected;\n        prong_node->data.switch_prong.items.append(item_node);\n        prong_node->data.switch_prong.expr = trans_create_node_break(c, label_name, nullptr);\n        switch_scope->switch_node->data.switch_expr.prongs.append(prong_node);\n    }\n\n    TransScopeBlock *scope_block = trans_scope_block_find(parent_scope);\n\n    AstNode *case_block = trans_create_node(c, NodeTypeBlock);\n    case_block->data.block.name = label_name;\n    case_block->data.block.statements = scope_block->node->data.block.statements;\n    scope_block->node->data.block.statements = {0};\n    scope_block->node->data.block.statements.append(case_block);\n\n    AstNode *sub_stmt_node;\n    TransScope *new_scope = trans_stmt(c, parent_scope, ZigClangCaseStmt_getSubStmt(stmt), &sub_stmt_node);\n    if (new_scope == nullptr)\n        return ErrorUnexpected;\n    if (sub_stmt_node != nullptr)\n        scope_block->node->data.block.statements.append(sub_stmt_node);\n\n    *out_scope = new_scope;\n    return ErrorNone;\n}\n\nstatic int trans_switch_default(Context *c, TransScope *parent_scope, const ZigClangDefaultStmt *stmt,\n        AstNode **out_node, TransScope **out_scope)\n{\n    *out_node = nullptr;\n\n    TransScopeSwitch *switch_scope = trans_scope_switch_find(parent_scope);\n    assert(switch_scope != nullptr);\n\n    Buf *label_name = buf_sprintf(\"__default\");\n\n    {\n        \/\/ Add the prong\n        AstNode *prong_node = trans_create_node(c, NodeTypeSwitchProng);\n        prong_node->data.switch_prong.expr = trans_create_node_break(c, label_name, nullptr);\n        switch_scope->switch_node->data.switch_expr.prongs.append(prong_node);\n        switch_scope->found_default = true;\n    }\n\n    TransScopeBlock *scope_block = trans_scope_block_find(parent_scope);\n\n    AstNode *case_block = trans_create_node(c, NodeTypeBlock);\n    case_block->data.block.name = label_name;\n    case_block->data.block.statements = scope_block->node->data.block.statements;\n    scope_block->node->data.block.statements = {0};\n    scope_block->node->data.block.statements.append(case_block);\n\n    AstNode *sub_stmt_node;\n    TransScope *new_scope = trans_stmt(c, parent_scope, ZigClangDefaultStmt_getSubStmt(stmt), &sub_stmt_node);\n    if (new_scope == nullptr)\n        return ErrorUnexpected;\n    if (sub_stmt_node != nullptr)\n        scope_block->node->data.block.statements.append(sub_stmt_node);\n\n    *out_scope = new_scope;\n    return ErrorNone;\n}\n\nstatic AstNode *trans_string_literal(Context *c, ResultUsed result_used, TransScope *scope,\n        const ZigClangStringLiteral *stmt)\n{\n    switch (ZigClangStringLiteral_getKind(stmt)) {\n        case ZigClangStringLiteral_StringKind_Ascii:\n        case ZigClangStringLiteral_StringKind_UTF8: {\n            size_t str_len;\n            const char *str_ptr = ZigClangStringLiteral_getString_bytes_begin_size(stmt, &str_len);\n            AstNode *node = trans_create_node_str_lit_c(c, buf_create_from_mem(str_ptr, str_len));\n            return maybe_suppress_result(c, result_used, node);\n        }\n        case ZigClangStringLiteral_StringKind_UTF16:\n            emit_warning(c, ZigClangStmt_getBeginLoc((const ZigClangStmt *)stmt), \"TODO support UTF16 string literals\");\n            return nullptr;\n        case ZigClangStringLiteral_StringKind_UTF32:\n            emit_warning(c, ZigClangStmt_getBeginLoc((const ZigClangStmt *)stmt), \"TODO support UTF32 string literals\");\n            return nullptr;\n        case ZigClangStringLiteral_StringKind_Wide:\n            emit_warning(c, ZigClangStmt_getBeginLoc((const ZigClangStmt *)stmt), \"TODO support wide string literals\");\n            return nullptr;\n    }\n    zig_unreachable();\n}\n\nstatic AstNode *trans_break_stmt(Context *c, TransScope *scope, const ZigClangBreakStmt *stmt) {\n    TransScope *cur_scope = scope;\n    while (cur_scope != nullptr) {\n        if (cur_scope->id == TransScopeIdWhile) {\n            return trans_create_node(c, NodeTypeBreak);\n        } else if (cur_scope->id == TransScopeIdSwitch) {\n            TransScopeSwitch *switch_scope = (TransScopeSwitch *)cur_scope;\n            return trans_create_node_break(c, switch_scope->end_label_name, nullptr);\n        }\n        cur_scope = cur_scope->parent;\n    }\n    zig_unreachable();\n}\n\nstatic AstNode *trans_continue_stmt(Context *c, TransScope *scope, const ZigClangContinueStmt *stmt) {\n    return trans_create_node(c, NodeTypeContinue);\n}\n\nstatic AstNode *trans_predefined_expr(Context *c, ResultUsed result_used, TransScope *scope,\n    const ZigClangPredefinedExpr *expr)\n{\n    return trans_string_literal(c, result_used, scope, ZigClangPredefinedExpr_getFunctionName(expr));\n}\n\nstatic int wrap_stmt(AstNode **out_node, TransScope **out_scope, TransScope *in_scope, AstNode *result_node) {\n    if (result_node == nullptr)\n        return ErrorUnexpected;\n    *out_node = result_node;\n    if (out_scope != nullptr)\n        *out_scope = in_scope;\n    return ErrorNone;\n}\n\nstatic int trans_stmt_extra(Context *c, TransScope *scope, const ZigClangStmt *stmt,\n        ResultUsed result_used, TransLRValue lrvalue,\n        AstNode **out_node, TransScope **out_child_scope,\n        TransScope **out_node_scope)\n{\n    ZigClangStmtClass sc = ZigClangStmt_getStmtClass(stmt);\n    switch (sc) {\n        case ZigClangStmt_ReturnStmtClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_return_stmt(c, scope, (const ZigClangReturnStmt *)stmt));\n        case ZigClangStmt_CompoundStmtClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_compound_stmt(c, scope, (const ZigClangCompoundStmt *)stmt, out_node_scope));\n        case ZigClangStmt_IntegerLiteralClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_integer_literal(c, result_used, (const ZigClangIntegerLiteral *)stmt));\n        case ZigClangStmt_ConditionalOperatorClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_conditional_operator(c, result_used, scope, (const ZigClangConditionalOperator *)stmt));\n        case ZigClangStmt_BinaryOperatorClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_binary_operator(c, result_used, scope, (const ZigClangBinaryOperator *)stmt));\n        case ZigClangStmt_CompoundAssignOperatorClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_compound_assign_operator(c, result_used, scope, (const ZigClangCompoundAssignOperator *)stmt));\n        case ZigClangStmt_ImplicitCastExprClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_implicit_cast_expr(c, result_used, scope, (const ZigClangImplicitCastExpr *)stmt));\n        case ZigClangStmt_DeclRefExprClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_decl_ref_expr(c, scope, (const ZigClangDeclRefExpr *)stmt, lrvalue));\n        case ZigClangStmt_UnaryOperatorClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_unary_operator(c, result_used, scope, (const ZigClangUnaryOperator *)stmt));\n        case ZigClangStmt_DeclStmtClass:\n            return trans_local_declaration(c, scope, (const ZigClangDeclStmt *)stmt, out_node, out_child_scope);\n        case ZigClangStmt_DoStmtClass:\n        case ZigClangStmt_WhileStmtClass: {\n            AstNode *while_node = sc == ZigClangStmt_DoStmtClass\n                ? trans_do_loop(c, scope, (const ZigClangDoStmt *)stmt)\n                : trans_while_loop(c, scope, (const ZigClangWhileStmt *)stmt);\n\n            if (while_node == nullptr)\n                return ErrorUnexpected;\n\n            assert(while_node->type == NodeTypeWhileExpr);\n            if (while_node->data.while_expr.body == nullptr)\n                while_node->data.while_expr.body = trans_create_node(c, NodeTypeBlock);\n\n            return wrap_stmt(out_node, out_child_scope, scope, while_node);\n        }\n        case ZigClangStmt_IfStmtClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_if_statement(c, scope, (const ZigClangIfStmt *)stmt));\n        case ZigClangStmt_CallExprClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_call_expr(c, result_used, scope, (const ZigClangCallExpr *)stmt));\n        case ZigClangStmt_NullStmtClass:\n            *out_node = trans_create_node(c, NodeTypeBlock);\n            *out_child_scope = scope;\n            return ErrorNone;\n        case ZigClangStmt_MemberExprClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_member_expr(c, result_used, scope, (const ZigClangMemberExpr *)stmt));\n        case ZigClangStmt_ArraySubscriptExprClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_array_subscript_expr(c, result_used, scope, (const ZigClangArraySubscriptExpr *)stmt));\n        case ZigClangStmt_CStyleCastExprClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_c_style_cast_expr(c, result_used, scope, (const ZigClangCStyleCastExpr *)stmt, lrvalue));\n        case ZigClangStmt_UnaryExprOrTypeTraitExprClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_unary_expr_or_type_trait_expr(c, result_used, scope, (const ZigClangUnaryExprOrTypeTraitExpr *)stmt));\n        case ZigClangStmt_ForStmtClass: {\n            AstNode *node = trans_for_loop(c, scope, (const ZigClangForStmt *)stmt);\n            return wrap_stmt(out_node, out_child_scope, scope, node);\n        }\n        case ZigClangStmt_StringLiteralClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_string_literal(c, result_used, scope, (const ZigClangStringLiteral *)stmt));\n        case ZigClangStmt_BreakStmtClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_break_stmt(c, scope, (const ZigClangBreakStmt *)stmt));\n        case ZigClangStmt_ContinueStmtClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_continue_stmt(c, scope, (const ZigClangContinueStmt *)stmt));\n        case ZigClangStmt_ParenExprClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_expr(c, result_used, scope,\n                        ZigClangParenExpr_getSubExpr((const ZigClangParenExpr *)stmt), lrvalue));\n        case ZigClangStmt_SwitchStmtClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                             trans_switch_stmt(c, scope, (const ZigClangSwitchStmt *)stmt));\n        case ZigClangStmt_CaseStmtClass:\n            return trans_switch_case(c, scope, (const ZigClangCaseStmt *)stmt, out_node, out_child_scope);\n        case ZigClangStmt_DefaultStmtClass:\n            return trans_switch_default(c, scope, (const ZigClangDefaultStmt *)stmt, out_node, out_child_scope);\n        case ZigClangStmt_ConstantExprClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_constant_expr(c, result_used, (const ZigClangConstantExpr *)stmt));\n        case ZigClangStmt_PredefinedExprClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                             trans_predefined_expr(c, result_used, scope, (const ZigClangPredefinedExpr *)stmt));\n        case ZigClangStmt_StmtExprClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_stmt_expr(c, result_used, scope, (const ZigClangStmtExpr *)stmt, out_node_scope));\n        case ZigClangStmt_NoStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C NoStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_GCCAsmStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C GCCAsmStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_MSAsmStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C MSAsmStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_AttributedStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C AttributedStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXCatchStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXCatchStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXForRangeStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXForRangeStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXTryStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXTryStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CapturedStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CapturedStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CoreturnStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CoreturnStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CoroutineBodyStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CoroutineBodyStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_BinaryConditionalOperatorClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C BinaryConditionalOperatorClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_AddrLabelExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C AddrLabelExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ArrayInitIndexExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ArrayInitIndexExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ArrayInitLoopExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ArrayInitLoopExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ArrayTypeTraitExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ArrayTypeTraitExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_AsTypeExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C AsTypeExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_AtomicExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C AtomicExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_BlockExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C BlockExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXBindTemporaryExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXBindTemporaryExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXBoolLiteralExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXBoolLiteralExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXConstructExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXConstructExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXTemporaryObjectExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXTemporaryObjectExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXDefaultArgExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXDefaultArgExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXDefaultInitExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXDefaultInitExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXDeleteExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXDeleteExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXDependentScopeMemberExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXDependentScopeMemberExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXFoldExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXFoldExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXInheritedCtorInitExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXInheritedCtorInitExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXNewExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXNewExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXNoexceptExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXNoexceptExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXNullPtrLiteralExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXNullPtrLiteralExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXPseudoDestructorExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXPseudoDestructorExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXScalarValueInitExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXScalarValueInitExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXStdInitializerListExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXStdInitializerListExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXThisExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXThisExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXThrowExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXThrowExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXTypeidExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXTypeidExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXUnresolvedConstructExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXUnresolvedConstructExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXUuidofExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXUuidofExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CUDAKernelCallExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CUDAKernelCallExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXMemberCallExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXMemberCallExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXOperatorCallExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXOperatorCallExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_UserDefinedLiteralClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C UserDefinedLiteralClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXFunctionalCastExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXFunctionalCastExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXConstCastExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXConstCastExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXDynamicCastExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXDynamicCastExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXReinterpretCastExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXReinterpretCastExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CXXStaticCastExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CXXStaticCastExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCBridgedCastExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCBridgedCastExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CharacterLiteralClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_character_literal(c, result_used, (const ZigClangCharacterLiteral *)stmt));\n            return ErrorUnexpected;\n        case ZigClangStmt_ChooseExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ChooseExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CompoundLiteralExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CompoundLiteralExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ConvertVectorExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ConvertVectorExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CoawaitExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CoawaitExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_CoyieldExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C CoyieldExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_DependentCoawaitExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C DependentCoawaitExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_DependentScopeDeclRefExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C DependentScopeDeclRefExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_DesignatedInitExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C DesignatedInitExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_DesignatedInitUpdateExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C DesignatedInitUpdateExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ExpressionTraitExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ExpressionTraitExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ExtVectorElementExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ExtVectorElementExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_FixedPointLiteralClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C FixedPointLiteralClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_FloatingLiteralClass:\n            return wrap_stmt(out_node, out_child_scope, scope,\n                    trans_floating_literal(c, result_used, (const ZigClangFloatingLiteral *)stmt));\n        case ZigClangStmt_ExprWithCleanupsClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ExprWithCleanupsClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_FunctionParmPackExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C FunctionParmPackExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_GNUNullExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C GNUNullExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_GenericSelectionExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C GenericSelectionExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ImaginaryLiteralClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ImaginaryLiteralClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ImplicitValueInitExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ImplicitValueInitExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_InitListExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C InitListExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_LambdaExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C LambdaExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_MSPropertyRefExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C MSPropertyRefExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_MSPropertySubscriptExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C MSPropertySubscriptExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_MaterializeTemporaryExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C MaterializeTemporaryExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_NoInitExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C NoInitExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPArraySectionExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPArraySectionExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCArrayLiteralClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCArrayLiteralClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCAvailabilityCheckExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCAvailabilityCheckExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCBoolLiteralExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCBoolLiteralExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCBoxedExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCBoxedExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCDictionaryLiteralClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCDictionaryLiteralClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCEncodeExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCEncodeExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCIndirectCopyRestoreExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCIndirectCopyRestoreExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCIsaExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCIsaExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCIvarRefExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCIvarRefExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCMessageExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCMessageExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCPropertyRefExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCPropertyRefExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCProtocolExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCProtocolExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCSelectorExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCSelectorExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCStringLiteralClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCStringLiteralClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCSubscriptRefExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCSubscriptRefExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OffsetOfExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OffsetOfExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OpaqueValueExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OpaqueValueExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_UnresolvedLookupExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C UnresolvedLookupExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_UnresolvedMemberExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C UnresolvedMemberExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_PackExpansionExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C PackExpansionExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ParenListExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ParenListExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_PseudoObjectExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C PseudoObjectExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ShuffleVectorExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ShuffleVectorExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_SizeOfPackExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C SizeOfPackExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_SubstNonTypeTemplateParmExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C SubstNonTypeTemplateParmExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_SubstNonTypeTemplateParmPackExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C SubstNonTypeTemplateParmPackExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_TypeTraitExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C TypeTraitExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_TypoExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C TypoExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_VAArgExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C VAArgExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_GotoStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C GotoStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_IndirectGotoStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C IndirectGotoStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_LabelStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C LabelStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_MSDependentExistsStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C MSDependentExistsStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPAtomicDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPAtomicDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPBarrierDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPBarrierDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPCancelDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPCancelDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPCancellationPointDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPCancellationPointDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPCriticalDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPCriticalDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPFlushDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPFlushDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPDistributeDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPDistributeDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPDistributeParallelForDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPDistributeParallelForDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPDistributeParallelForSimdDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPDistributeParallelForSimdDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPDistributeSimdDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPDistributeSimdDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPForDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPForDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPForSimdDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPForSimdDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPParallelForDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPParallelForDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPParallelForSimdDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPParallelForSimdDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPSimdDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPSimdDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetParallelForSimdDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetParallelForSimdDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetSimdDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetSimdDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetTeamsDistributeDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetTeamsDistributeDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetTeamsDistributeParallelForDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetTeamsDistributeParallelForDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetTeamsDistributeParallelForSimdDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetTeamsDistributeParallelForSimdDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetTeamsDistributeSimdDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetTeamsDistributeSimdDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTaskLoopDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTaskLoopDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTaskLoopSimdDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTaskLoopSimdDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTeamsDistributeDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTeamsDistributeDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTeamsDistributeParallelForDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTeamsDistributeParallelForDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTeamsDistributeParallelForSimdDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTeamsDistributeParallelForSimdDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTeamsDistributeSimdDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTeamsDistributeSimdDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPMasterDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPMasterDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPOrderedDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPOrderedDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPParallelDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPParallelDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPParallelSectionsDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPParallelSectionsDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPSectionDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPSectionDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPSectionsDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPSectionsDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPSingleDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPSingleDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetDataDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetDataDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetEnterDataDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetEnterDataDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetExitDataDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetExitDataDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetParallelDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetParallelDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetParallelForDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetParallelForDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetTeamsDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetTeamsDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTargetUpdateDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTargetUpdateDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTaskDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTaskDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTaskgroupDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTaskgroupDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTaskwaitDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTaskwaitDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTaskyieldDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTaskyieldDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_OMPTeamsDirectiveClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C OMPTeamsDirectiveClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCAtCatchStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCAtCatchStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCAtFinallyStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCAtFinallyStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCAtSynchronizedStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCAtSynchronizedStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCAtThrowStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCAtThrowStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCAtTryStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCAtTryStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCAutoreleasePoolStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCAutoreleasePoolStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_ObjCForCollectionStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C ObjCForCollectionStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_SEHExceptStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C SEHExceptStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_SEHFinallyStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C SEHFinallyStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_SEHLeaveStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C SEHLeaveStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_SEHTryStmtClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C SEHTryStmtClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_BuiltinBitCastExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C BuiltinBitCastExprClass\");\n            return ErrorUnexpected;\n        case ZigClangStmt_SourceLocExprClass:\n            emit_warning(c, ZigClangStmt_getBeginLoc(stmt), \"TODO handle C SourceLocExprClass\");\n            return ErrorUnexpected;\n    }\n    zig_unreachable();\n}\n\n\/\/ Returns null if there was an error\nstatic AstNode *trans_expr(Context *c, ResultUsed result_used, TransScope *scope, const ZigClangExpr *expr,\n        TransLRValue lrval)\n{\n    AstNode *result_node;\n    TransScope *result_scope;\n    if (trans_stmt_extra(c, scope, (const ZigClangStmt *)expr, result_used, lrval, &result_node, &result_scope, nullptr)) {\n        return nullptr;\n    }\n    return result_node;\n}\n\n\/\/ Statements have no result and no concept of L or R value.\n\/\/ Returns child scope, or null if there was an error\nstatic TransScope *trans_stmt(Context *c, TransScope *scope, const ZigClangStmt *stmt, AstNode **out_node) {\n    TransScope *child_scope;\n    if (trans_stmt_extra(c, scope, stmt, ResultUsedNo, TransRValue, out_node, &child_scope, nullptr)) {\n        return nullptr;\n    }\n    return child_scope;\n}\n\nstatic void visit_fn_decl(Context *c, const ZigClangFunctionDecl *fn_decl) {\n    Buf *fn_name = buf_create_from_str(ZigClangDecl_getName_bytes_begin((const ZigClangDecl *)fn_decl));\n\n    if (get_global(c, fn_name)) {\n        \/\/ we already saw this function\n        return;\n    }\n\n    AstNode *proto_node = trans_qual_type(c, ZigClangFunctionDecl_getType(fn_decl),\n            ZigClangFunctionDecl_getLocation(fn_decl));\n    if (proto_node == nullptr) {\n        emit_warning(c, ZigClangFunctionDecl_getLocation(fn_decl),\n                \"unable to resolve prototype of function '%s'\", buf_ptr(fn_name));\n        return;\n    }\n\n    proto_node->data.fn_proto.name = fn_name;\n    proto_node->data.fn_proto.is_extern = !ZigClangFunctionDecl_hasBody(fn_decl);\n\n    ZigClangStorageClass sc = ZigClangFunctionDecl_getStorageClass(fn_decl);\n    if (sc == ZigClangStorageClass_None) {\n        proto_node->data.fn_proto.visib_mod = c->visib_mod;\n        proto_node->data.fn_proto.is_export = ZigClangFunctionDecl_hasBody(fn_decl) ? c->want_export : false;\n    } else if (sc == ZigClangStorageClass_Extern || sc == ZigClangStorageClass_Static) {\n        proto_node->data.fn_proto.visib_mod = c->visib_mod;\n    } else if (sc == ZigClangStorageClass_PrivateExtern) {\n        emit_warning(c, ZigClangFunctionDecl_getLocation(fn_decl), \"unsupported storage class: private extern\");\n        return;\n    } else {\n        emit_warning(c, ZigClangFunctionDecl_getLocation(fn_decl), \"unsupported storage class: unknown\");\n        return;\n    }\n\n    TransScope *scope = &c->global_scope->base;\n\n    for (size_t i = 0; i < proto_node->data.fn_proto.params.length; i += 1) {\n        AstNode *param_node = proto_node->data.fn_proto.params.at(i);\n        const ZigClangParmVarDecl *param = ZigClangFunctionDecl_getParamDecl(fn_decl, i);\n        const char *name = ZigClangDecl_getName_bytes_begin((const ZigClangDecl *)param);\n\n        Buf *proto_param_name;\n        if (strlen(name) != 0) {\n            proto_param_name = buf_create_from_str(name);\n        } else {\n            proto_param_name = param_node->data.param_decl.name;\n            if (proto_param_name == nullptr) {\n                proto_param_name = buf_sprintf(\"arg%\" ZIG_PRI_usize \"\", i);\n            }\n        }\n\n        TransScopeVar *scope_var = trans_scope_var_create(c, scope, proto_param_name);\n        scope = &scope_var->base;\n\n        param_node->data.param_decl.name = scope_var->zig_name;\n    }\n\n    if (!ZigClangFunctionDecl_hasBody(fn_decl)) {\n        \/\/ just a prototype\n        add_top_level_decl(c, proto_node->data.fn_proto.name, proto_node);\n        return;\n    }\n\n    \/\/ actual function definition with body\n    c->ptr_params.clear();\n    const ZigClangStmt *body = ZigClangFunctionDecl_getBody(fn_decl);\n    AstNode *actual_body_node;\n    TransScope *result_scope = trans_stmt(c, scope, body, &actual_body_node);\n    if (result_scope == nullptr) {\n        emit_warning(c, ZigClangFunctionDecl_getLocation(fn_decl), \"unable to translate function\");\n        return;\n    }\n    assert(actual_body_node != nullptr);\n    assert(actual_body_node->type == NodeTypeBlock);\n\n    \/\/ it worked\n\n    AstNode *body_node_with_param_inits = trans_create_node(c, NodeTypeBlock);\n\n    for (size_t i = 0; i < proto_node->data.fn_proto.params.length; i += 1) {\n        AstNode *param_node = proto_node->data.fn_proto.params.at(i);\n        Buf *good_name = param_node->data.param_decl.name;\n\n        if (c->ptr_params.maybe_get(good_name) != nullptr) {\n            \/\/ TODO: avoid name collisions\n            Buf *mangled_name = buf_sprintf(\"_arg_%s\", buf_ptr(good_name));\n            param_node->data.param_decl.name = mangled_name;\n\n            \/\/ var c_name = _mangled_name;\n            AstNode *parameter_init = trans_create_node_var_decl_local(c, false, good_name, nullptr, trans_create_node_symbol(c, mangled_name));\n\n            body_node_with_param_inits->data.block.statements.append(parameter_init);\n        }\n    }\n\n    for (size_t i = 0; i < actual_body_node->data.block.statements.length; i += 1) {\n        body_node_with_param_inits->data.block.statements.append(actual_body_node->data.block.statements.at(i));\n    }\n\n    AstNode *fn_def_node = trans_create_node(c, NodeTypeFnDef);\n    fn_def_node->data.fn_def.fn_proto = proto_node;\n    fn_def_node->data.fn_def.body = body_node_with_param_inits;\n\n    proto_node->data.fn_proto.fn_def_node = fn_def_node;\n    add_top_level_decl(c, fn_def_node->data.fn_def.fn_proto->data.fn_proto.name, fn_def_node);\n}\n\nstatic AstNode *resolve_typdef_as_builtin(Context *c, const ZigClangTypedefNameDecl *typedef_decl, const char *primitive_name) {\n    AstNode *node = trans_create_node_symbol_str(c, primitive_name);\n    c->decl_table.put(typedef_decl, node);\n    return node;\n}\n\nstatic AstNode *resolve_typedef_decl(Context *c, const ZigClangTypedefNameDecl *typedef_decl) {\n    auto existing_entry = c->decl_table.maybe_get((void*)ZigClangTypedefNameDecl_getCanonicalDecl(typedef_decl));\n    if (existing_entry) {\n        return existing_entry->value;\n    }\n\n    ZigClangQualType child_qt = ZigClangTypedefNameDecl_getUnderlyingType(typedef_decl);\n    Buf *type_name = buf_create_from_str(ZigClangDecl_getName_bytes_begin((const ZigClangDecl *)typedef_decl));\n\n    if (buf_eql_str(type_name, \"uint8_t\")) {\n        return resolve_typdef_as_builtin(c, typedef_decl, \"u8\");\n    } else if (buf_eql_str(type_name, \"int8_t\")) {\n        return resolve_typdef_as_builtin(c, typedef_decl, \"i8\");\n    } else if (buf_eql_str(type_name, \"uint16_t\")) {\n        return resolve_typdef_as_builtin(c, typedef_decl, \"u16\");\n    } else if (buf_eql_str(type_name, \"int16_t\")) {\n        return resolve_typdef_as_builtin(c, typedef_decl, \"i16\");\n    } else if (buf_eql_str(type_name, \"uint32_t\")) {\n        return resolve_typdef_as_builtin(c, typedef_decl, \"u32\");\n    } else if (buf_eql_str(type_name, \"int32_t\")) {\n        return resolve_typdef_as_builtin(c, typedef_decl, \"i32\");\n    } else if (buf_eql_str(type_name, \"uint64_t\")) {\n        return resolve_typdef_as_builtin(c, typedef_decl, \"u64\");\n    } else if (buf_eql_str(type_name, \"int64_t\")) {\n        return resolve_typdef_as_builtin(c, typedef_decl, \"i64\");\n    } else if (buf_eql_str(type_name, \"intptr_t\")) {\n        return resolve_typdef_as_builtin(c, typedef_decl, \"isize\");\n    } else if (buf_eql_str(type_name, \"uintptr_t\")) {\n        return resolve_typdef_as_builtin(c, typedef_decl, \"usize\");\n    } else if (buf_eql_str(type_name, \"ssize_t\")) {\n        return resolve_typdef_as_builtin(c, typedef_decl, \"isize\");\n    } else if (buf_eql_str(type_name, \"size_t\")) {\n        return resolve_typdef_as_builtin(c, typedef_decl, \"usize\");\n    }\n\n    \/\/ if the underlying type is anonymous, we can special case it to just\n    \/\/ use the name of this typedef\n    \/\/ TODO\n\n    \/\/ trans_qual_type here might cause us to look at this typedef again so we put the item in the map first\n    AstNode *symbol_node = trans_create_node_symbol(c, type_name);\n    c->decl_table.put(ZigClangTypedefNameDecl_getCanonicalDecl(typedef_decl), symbol_node);\n\n    AstNode *type_node = trans_qual_type(c, child_qt, ZigClangTypedefNameDecl_getLocation(typedef_decl));\n    if (type_node == nullptr) {\n        emit_warning(c, ZigClangTypedefNameDecl_getLocation(typedef_decl),\n                \"typedef %s - unresolved child type\", buf_ptr(type_name));\n        c->decl_table.put(typedef_decl, nullptr);\n        \/\/ TODO add global var with type_name equal to @compileError(\"unable to resolve C type\") \n        return nullptr;\n    }\n    add_global_var(c, type_name, type_node);\n\n    return symbol_node;\n}\n\nstruct AstNode *demote_enum_to_opaque(Context *c, const ZigClangEnumDecl *enum_decl, Buf *full_type_name,\n        Buf *bare_name)\n{\n    AstNode *opaque_node = trans_create_node_opaque(c);\n    if (full_type_name == nullptr) {\n        c->decl_table.put(ZigClangEnumDecl_getCanonicalDecl(enum_decl), opaque_node);\n        return opaque_node;\n    }\n    AstNode *symbol_node = trans_create_node_symbol(c, full_type_name);\n    add_global_weak_alias(c, bare_name, full_type_name);\n    add_global_var(c, full_type_name, opaque_node);\n    c->decl_table.put(ZigClangEnumDecl_getCanonicalDecl(enum_decl), symbol_node);\n    return symbol_node;\n}\n\nstatic AstNode *resolve_enum_decl(Context *c, const ZigClangEnumDecl *enum_decl) {\n    auto existing_entry = c->decl_table.maybe_get(ZigClangEnumDecl_getCanonicalDecl(enum_decl));\n    if (existing_entry) {\n        return existing_entry->value;\n    }\n\n    const char *raw_name = ZigClangDecl_getName_bytes_begin((const ZigClangDecl *)enum_decl);\n    bool is_anonymous = (raw_name[0] == 0);\n    Buf *bare_name = is_anonymous ? nullptr : buf_create_from_str(raw_name);\n    Buf *full_type_name = is_anonymous ? nullptr : buf_sprintf(\"enum_%s\", buf_ptr(bare_name));\n\n    const ZigClangEnumDecl *enum_def = ZigClangEnumDecl_getDefinition(enum_decl);\n    if (!enum_def) {\n        return demote_enum_to_opaque(c, enum_decl, full_type_name, bare_name);\n    }\n\n\n    bool pure_enum = true;\n    uint32_t field_count = 0;\n    for (ZigClangEnumDecl_enumerator_iterator it = ZigClangEnumDecl_enumerator_begin(enum_def),\n            it_end = ZigClangEnumDecl_enumerator_end(enum_def);\n        ZigClangEnumDecl_enumerator_iterator_neq(it, it_end);\n        it = ZigClangEnumDecl_enumerator_iterator_next(it), field_count += 1)\n    {\n        const ZigClangEnumConstantDecl *enum_const = ZigClangEnumDecl_enumerator_iterator_deref(it);\n        if (ZigClangEnumConstantDecl_getInitExpr(enum_const)) {\n            pure_enum = false;\n        }\n    }\n    AstNode *tag_int_type = trans_qual_type(c, ZigClangEnumDecl_getIntegerType(enum_decl),\n            ZigClangEnumDecl_getLocation(enum_decl));\n    assert(tag_int_type);\n\n    AstNode *enum_node = trans_create_node(c, NodeTypeContainerDecl);\n    enum_node->data.container_decl.kind = ContainerKindEnum;\n    enum_node->data.container_decl.layout = ContainerLayoutExtern;\n    \/\/ TODO only emit this tag type if the enum tag type is not the default.\n    \/\/ I don't know what the default is, need to figure out how clang is deciding.\n    \/\/ it appears to at least be different across gcc\/msvc\n    if (!c_is_builtin_type(c, ZigClangEnumDecl_getIntegerType(enum_decl), ZigClangBuiltinTypeUInt) &&\n        !c_is_builtin_type(c, ZigClangEnumDecl_getIntegerType(enum_decl), ZigClangBuiltinTypeInt))\n    {\n        enum_node->data.container_decl.init_arg_expr = tag_int_type;\n    }\n    enum_node->data.container_decl.fields.resize(field_count);\n    uint32_t i = 0;\n    for (ZigClangEnumDecl_enumerator_iterator it = ZigClangEnumDecl_enumerator_begin(enum_def),\n            it_end = ZigClangEnumDecl_enumerator_end(enum_def);\n        ZigClangEnumDecl_enumerator_iterator_neq(it, it_end);\n        it = ZigClangEnumDecl_enumerator_iterator_next(it), i += 1)\n    {\n        const ZigClangEnumConstantDecl *enum_const = ZigClangEnumDecl_enumerator_iterator_deref(it);\n\n        Buf *enum_val_name = buf_create_from_str(ZigClangDecl_getName_bytes_begin((const ZigClangDecl *)enum_const));\n        Buf *field_name;\n        if (bare_name != nullptr && buf_starts_with_buf(enum_val_name, bare_name)) {\n            field_name = buf_slice(enum_val_name, buf_len(bare_name), buf_len(enum_val_name));\n        } else {\n            field_name = enum_val_name;\n        }\n\n        AstNode *int_node = pure_enum && !is_anonymous ?\n            nullptr : trans_create_node_apint(c, ZigClangEnumConstantDecl_getInitVal(enum_const));\n        AstNode *field_node = trans_create_node(c, NodeTypeStructField);\n        field_node->data.struct_field.name = field_name;\n        field_node->data.struct_field.type = nullptr;\n        field_node->data.struct_field.value = int_node;\n        enum_node->data.container_decl.fields.items[i] = field_node;\n\n        \/\/ in C each enum value is in the global namespace. so we put them there too.\n        \/\/ at this point we can rely on the enum emitting successfully\n        if (is_anonymous) {\n            Buf *enum_val_name = buf_create_from_str(ZigClangDecl_getName_bytes_begin((const ZigClangDecl *)enum_const));\n            add_global_var(c, enum_val_name, int_node);\n        } else {\n            AstNode *field_access_node = trans_create_node_field_access(c,\n                    trans_create_node_symbol(c, full_type_name), field_name);\n            add_global_var(c, enum_val_name, field_access_node);\n        }\n    }\n\n    if (is_anonymous) {\n        c->decl_table.put(ZigClangEnumDecl_getCanonicalDecl(enum_decl), enum_node);\n        return enum_node;\n    } else {\n        AstNode *symbol_node = trans_create_node_symbol(c, full_type_name);\n        add_global_weak_alias(c, bare_name, full_type_name);\n        add_global_var(c, full_type_name, enum_node);\n        c->decl_table.put(ZigClangEnumDecl_getCanonicalDecl(enum_decl), symbol_node);\n        return enum_node;\n    }\n}\n\nstatic AstNode *demote_struct_to_opaque(Context *c, const ZigClangRecordDecl *record_decl,\n        Buf *full_type_name, Buf *bare_name)\n{\n    AstNode *opaque_node = trans_create_node_opaque(c);\n    if (full_type_name == nullptr) {\n        c->decl_table.put(ZigClangRecordDecl_getCanonicalDecl(record_decl), opaque_node);\n        return opaque_node;\n    }\n    AstNode *symbol_node = trans_create_node_symbol(c, full_type_name);\n    add_global_weak_alias(c, bare_name, full_type_name);\n    add_global_var(c, full_type_name, opaque_node);\n    c->decl_table.put(ZigClangRecordDecl_getCanonicalDecl(record_decl), symbol_node);\n    return symbol_node;\n}\n\nstatic AstNode *resolve_record_decl(Context *c, const ZigClangRecordDecl *record_decl) {\n    auto existing_entry = c->decl_table.maybe_get(ZigClangRecordDecl_getCanonicalDecl(record_decl));\n    if (existing_entry) {\n        return existing_entry->value;\n    }\n\n    const char *raw_name = ZigClangDecl_getName_bytes_begin((const ZigClangDecl *)record_decl);\n    const char *container_kind_name;\n    ContainerKind container_kind;\n    if (ZigClangRecordDecl_isUnion(record_decl)) {\n        container_kind_name = \"union\";\n        container_kind = ContainerKindUnion;\n    } else if (ZigClangRecordDecl_isStruct(record_decl)) {\n        container_kind_name = \"struct\";\n        container_kind = ContainerKindStruct;\n    } else {\n        emit_warning(c, ZigClangRecordDecl_getLocation(record_decl),\n                \"skipping record %s, not a struct or union\", raw_name);\n        c->decl_table.put(ZigClangRecordDecl_getCanonicalDecl(record_decl), nullptr);\n        return nullptr;\n    }\n\n    bool is_anonymous = ZigClangRecordDecl_isAnonymousStructOrUnion(record_decl) || raw_name[0] == 0;\n    Buf *bare_name = is_anonymous ? nullptr : buf_create_from_str(raw_name);\n    Buf *full_type_name = (bare_name == nullptr) ?\n        nullptr : buf_sprintf(\"%s_%s\", container_kind_name, buf_ptr(bare_name));\n\n    const ZigClangRecordDecl *record_def = ZigClangRecordDecl_getDefinition(record_decl);\n    if (record_def == nullptr) {\n        return demote_struct_to_opaque(c, record_decl, full_type_name, bare_name);\n    }\n\n    \/\/ count fields and validate\n    uint32_t field_count = 0;\n    for (ZigClangRecordDecl_field_iterator it = ZigClangRecordDecl_field_begin(record_def),\n        it_end = ZigClangRecordDecl_field_end(record_def);\n        ZigClangRecordDecl_field_iterator_neq(it, it_end);\n        it = ZigClangRecordDecl_field_iterator_next(it), field_count += 1)\n    {\n        const ZigClangFieldDecl *field_decl = ZigClangRecordDecl_field_iterator_deref(it);\n\n        if (ZigClangFieldDecl_isBitField(field_decl)) {\n            emit_warning(c, ZigClangFieldDecl_getLocation(field_decl),\n                    \"%s %s demoted to opaque type - has bitfield\", container_kind_name,\n                    is_anonymous ? \"(anon)\" : buf_ptr(bare_name));\n            return demote_struct_to_opaque(c, record_decl, full_type_name, bare_name);\n        }\n    }\n\n    AstNode *struct_node = trans_create_node(c, NodeTypeContainerDecl);\n    struct_node->data.container_decl.kind = container_kind;\n    struct_node->data.container_decl.layout = ContainerLayoutExtern;\n\n    \/\/ TODO handle attribute packed\n\n    struct_node->data.container_decl.fields.resize(field_count);\n\n    \/\/ must be before fields in case a circular reference happens\n    if (is_anonymous) {\n        c->decl_table.put(ZigClangRecordDecl_getCanonicalDecl(record_decl), struct_node);\n    } else {\n        c->decl_table.put(ZigClangRecordDecl_getCanonicalDecl(record_decl), trans_create_node_symbol(c, full_type_name));\n    }\n\n    uint32_t i = 0;\n    for (ZigClangRecordDecl_field_iterator it = ZigClangRecordDecl_field_begin(record_def),\n        it_end = ZigClangRecordDecl_field_end(record_def);\n        ZigClangRecordDecl_field_iterator_neq(it, it_end);\n        it = ZigClangRecordDecl_field_iterator_next(it), i += 1)\n    {\n        const ZigClangFieldDecl *field_decl = ZigClangRecordDecl_field_iterator_deref(it);\n\n        AstNode *field_node = trans_create_node(c, NodeTypeStructField);\n        field_node->data.struct_field.name = buf_create_from_str(ZigClangDecl_getName_bytes_begin((const ZigClangDecl *)field_decl));\n        field_node->data.struct_field.type = trans_qual_type(c, ZigClangFieldDecl_getType(field_decl),\n                ZigClangFieldDecl_getLocation(field_decl));\n\n        if (field_node->data.struct_field.type == nullptr) {\n            emit_warning(c, ZigClangFieldDecl_getLocation(field_decl),\n                    \"%s %s demoted to opaque type - unresolved type\",\n                    container_kind_name,\n                    is_anonymous ? \"(anon)\" : buf_ptr(bare_name));\n\n            return demote_struct_to_opaque(c, record_decl, full_type_name, bare_name);\n        }\n\n        struct_node->data.container_decl.fields.items[i] = field_node;\n    }\n\n    if (is_anonymous) {\n        return struct_node;\n    } else {\n        add_global_weak_alias(c, bare_name, full_type_name);\n        add_global_var(c, full_type_name, struct_node);\n        return trans_create_node_symbol(c, full_type_name);\n    }\n}\n\nstatic AstNode *trans_ap_value(Context *c, const ZigClangAPValue *ap_value, ZigClangQualType qt,\n        ZigClangSourceLocation source_loc)\n{\n    switch (ZigClangAPValue_getKind(ap_value)) {\n        case ZigClangAPValueInt:\n            return trans_create_node_apint(c, ZigClangAPValue_getInt(ap_value));\n        case ZigClangAPValueNone:\n            return trans_create_node(c, NodeTypeUndefinedLiteral);\n        case ZigClangAPValueArray: {\n            emit_warning(c, source_loc, \"TODO add a test case for this code\");\n\n            unsigned init_count = ZigClangAPValue_getArrayInitializedElts(ap_value);\n            unsigned all_count = ZigClangAPValue_getArraySize(ap_value);\n            unsigned leftover_count = all_count - init_count;\n            AstNode *init_node = trans_create_node(c, NodeTypeContainerInitExpr);\n            AstNode *arr_type_node = trans_qual_type(c, qt, source_loc);\n            if (leftover_count != 0) { \/\/ We can't use the size of the final array for a partial initializer.\n                bigint_init_unsigned(arr_type_node->data.array_type.size->data.int_literal.bigint, init_count);\n            }\n            init_node->data.container_init_expr.type = arr_type_node;\n            init_node->data.container_init_expr.kind = ContainerInitKindArray;\n\n            const ZigClangType *qt_type = ZigClangQualType_getTypePtr(qt);\n            ZigClangQualType child_qt = ZigClangArrayType_getElementType(ZigClangType_getAsArrayTypeUnsafe(qt_type));\n\n            for (size_t i = 0; i < init_count; i += 1) {\n                const ZigClangAPValue *elem_ap_val = ZigClangAPValue_getArrayInitializedElt(ap_value, i);\n                AstNode *elem_node = trans_ap_value(c, elem_ap_val, child_qt, source_loc);\n                if (elem_node == nullptr)\n                    return nullptr;\n                init_node->data.container_init_expr.entries.append(elem_node);\n            }\n            if (leftover_count == 0) {\n                return init_node;\n            }\n\n            const ZigClangAPValue *filler_ap_val = ZigClangAPValue_getArrayFiller(ap_value);\n            AstNode *filler_node = trans_ap_value(c, filler_ap_val, child_qt, source_loc);\n            if (filler_node == nullptr)\n                return nullptr;\n\n            AstNode* filler_arr_type = trans_create_node(c, NodeTypeArrayType);\n            *filler_arr_type = *arr_type_node;\n            filler_arr_type->data.array_type.size = trans_create_node_unsigned(c, 1);\n\n            AstNode *filler_arr_1 = trans_create_node(c, NodeTypeContainerInitExpr);\n            filler_arr_1->data.container_init_expr.type = filler_arr_type;\n            filler_arr_1->data.container_init_expr.kind = ContainerInitKindArray;\n            filler_arr_1->data.container_init_expr.entries.append(filler_node);\n\n            AstNode *rhs_node;\n            if (leftover_count == 1) {\n                rhs_node = filler_arr_1;\n            } else {\n                AstNode *amt_node = trans_create_node_unsigned(c, leftover_count);\n                rhs_node = trans_create_node_bin_op(c, filler_arr_1, BinOpTypeArrayMult, amt_node);\n            }\n\n            if (init_count == 0) {\n                return rhs_node;\n            }\n\n            return trans_create_node_bin_op(c, init_node, BinOpTypeArrayCat, rhs_node);\n        }\n        case ZigClangAPValueLValue: {\n            const ZigClangAPValueLValueBase lval_base = ZigClangAPValue_getLValueBase(ap_value);\n            if (const ZigClangExpr *expr = ZigClangAPValueLValueBase_dyn_cast_Expr(lval_base)) {\n                return trans_expr(c, ResultUsedYes, &c->global_scope->base, expr, TransRValue);\n            }\n            emit_warning(c, source_loc, \"TODO handle initializer LValue ValueDecl\");\n            return nullptr;\n        }\n        case ZigClangAPValueFloat:\n            emit_warning(c, source_loc, \"unsupported initializer value kind: Float\");\n            return nullptr;\n        case ZigClangAPValueComplexInt:\n            emit_warning(c, source_loc, \"unsupported initializer value kind: ComplexInt\");\n            return nullptr;\n        case ZigClangAPValueComplexFloat:\n            emit_warning(c, source_loc, \"unsupported initializer value kind: ComplexFloat\");\n            return nullptr;\n        case ZigClangAPValueVector:\n            emit_warning(c, source_loc, \"unsupported initializer value kind: Vector\");\n            return nullptr;\n        case ZigClangAPValueStruct:\n            emit_warning(c, source_loc, \"unsupported initializer value kind: Struct\");\n            return nullptr;\n        case ZigClangAPValueUnion:\n            emit_warning(c, source_loc, \"unsupported initializer value kind: Union\");\n            return nullptr;\n        case ZigClangAPValueMemberPointer:\n            emit_warning(c, source_loc, \"unsupported initializer value kind: MemberPointer\");\n            return nullptr;\n        case ZigClangAPValueAddrLabelDiff:\n            emit_warning(c, source_loc, \"unsupported initializer value kind: AddrLabelDiff\");\n            return nullptr;\n        case ZigClangAPValueIndeterminate:\n            emit_warning(c, source_loc, \"unsupported initializer value kind: Indeterminate\");\n            return nullptr;\n        case ZigClangAPValueFixedPoint:\n            emit_warning(c, source_loc, \"unsupported initializer value kind: FixedPoint\");\n            return nullptr;\n    }\n    zig_unreachable();\n}\n\nstatic void visit_var_decl(Context *c, const ZigClangVarDecl *var_decl) {\n    Buf *name = buf_create_from_str(ZigClangDecl_getName_bytes_begin((const ZigClangDecl *)var_decl));\n\n    switch (ZigClangVarDecl_getTLSKind(var_decl)) {\n        case ZigClangVarDecl_TLSKind_None:\n            break;\n        case ZigClangVarDecl_TLSKind_Static:\n            emit_warning(c, ZigClangVarDecl_getLocation(var_decl),\n                    \"ignoring variable '%s' - static thread local storage\", buf_ptr(name));\n            return;\n        case ZigClangVarDecl_TLSKind_Dynamic:\n            emit_warning(c, ZigClangVarDecl_getLocation(var_decl),\n                    \"ignoring variable '%s' - dynamic thread local storage\", buf_ptr(name));\n            return;\n    }\n\n    ZigClangQualType qt = ZigClangVarDecl_getType(var_decl);\n    AstNode *var_type = trans_qual_type(c, qt, ZigClangVarDecl_getLocation(var_decl));\n    if (var_type == nullptr) {\n        emit_warning(c, ZigClangVarDecl_getLocation(var_decl), \"ignoring variable '%s' - unresolved type\", buf_ptr(name));\n        return;\n    }\n\n    bool is_extern = ZigClangVarDecl_hasExternalStorage(var_decl);\n    bool is_static = ZigClangVarDecl_isFileVarDecl(var_decl);\n    bool is_const = ZigClangQualType_isConstQualified(qt);\n\n    if (is_static && !is_extern) {\n        AstNode *init_node;\n        if (ZigClangVarDecl_hasInit(var_decl)) {\n            const ZigClangAPValue *ap_value = ZigClangVarDecl_evaluateValue(var_decl);\n            if (ap_value == nullptr) {\n                emit_warning(c, ZigClangVarDecl_getLocation(var_decl),\n                        \"ignoring variable '%s' - unable to evaluate initializer\", buf_ptr(name));\n                return;\n            }\n            init_node = trans_ap_value(c, ap_value, qt, ZigClangVarDecl_getLocation(var_decl));\n            if (init_node == nullptr)\n                return;\n        } else {\n            init_node = trans_create_node(c, NodeTypeUndefinedLiteral);\n        }\n\n        AstNode *var_node = trans_create_node_var_decl_global(c, is_const, name, var_type, init_node);\n        add_top_level_decl(c, name, var_node);\n        return;\n    }\n\n    if (is_extern) {\n        AstNode *var_node = trans_create_node_var_decl_global(c, is_const, name, var_type, nullptr);\n        var_node->data.variable_declaration.is_extern = true;\n        add_top_level_decl(c, name, var_node);\n        return;\n    }\n\n    emit_warning(c, ZigClangVarDecl_getLocation(var_decl),\n        \"ignoring variable '%s' - non-extern, non-static variable\", buf_ptr(name));\n    return;\n}\n\nstatic bool decl_visitor(void *context, const ZigClangDecl *decl) {\n    Context *c = (Context*)context;\n\n    switch (ZigClangDecl_getKind(decl)) {\n        case ZigClangDeclFunction:\n            visit_fn_decl(c, reinterpret_cast<const ZigClangFunctionDecl*>(decl));\n            break;\n        case ZigClangDeclTypedef:\n            resolve_typedef_decl(c, reinterpret_cast<const ZigClangTypedefNameDecl *>(decl));\n            break;\n        case ZigClangDeclEnum:\n            resolve_enum_decl(c, reinterpret_cast<const ZigClangEnumDecl *>(decl));\n            break;\n        case ZigClangDeclRecord:\n            resolve_record_decl(c, reinterpret_cast<const ZigClangRecordDecl *>(decl));\n            break;\n        case ZigClangDeclVar:\n            visit_var_decl(c, reinterpret_cast<const ZigClangVarDecl *>(decl));\n            break;\n        default:\n            emit_warning(c, ZigClangDecl_getLocation(decl), \"ignoring %s decl\", ZigClangDecl_getDeclKindName(decl));\n    }\n\n    return true;\n}\n\nstatic bool name_exists_global(Context *c, Buf *name) {\n    return get_global(c, name) != nullptr;\n}\n\nstatic bool name_exists_scope(Context *c, Buf *name, TransScope *scope) {\n    while (scope != nullptr) {\n        if (scope->id == TransScopeIdVar) {\n            TransScopeVar *var_scope = (TransScopeVar *)scope;\n            if (buf_eql_buf(name, var_scope->zig_name)) {\n                return true;\n            }\n        }\n        scope = scope->parent;\n    }\n    return name_exists_global(c, name);\n}\n\nstatic Buf *get_unique_name(Context *c, Buf *name, TransScope *scope) {\n    Buf *proposed_name = name;\n    int count = 0;\n    while (name_exists_scope(c, proposed_name, scope)) {\n        if (proposed_name == name) {\n            proposed_name = buf_alloc();\n        }\n        buf_resize(proposed_name, 0);\n        buf_appendf(proposed_name, \"%s_%d\", buf_ptr(name), count);\n        count += 1;\n    }\n    return proposed_name;\n}\n\nstatic TransScopeRoot *trans_scope_root_create(Context *c) {\n    TransScopeRoot *result = allocate<TransScopeRoot>(1);\n    result->base.id = TransScopeIdRoot;\n    return result;\n}\n\nstatic TransScopeWhile *trans_scope_while_create(Context *c, TransScope *parent_scope) {\n    TransScopeWhile *result = allocate<TransScopeWhile>(1);\n    result->base.id = TransScopeIdWhile;\n    result->base.parent = parent_scope;\n    result->node = trans_create_node(c, NodeTypeWhileExpr);\n    return result;\n}\n\nstatic TransScopeBlock *trans_scope_block_create(Context *c, TransScope *parent_scope) {\n    TransScopeBlock *result = allocate<TransScopeBlock>(1);\n    result->base.id = TransScopeIdBlock;\n    result->base.parent = parent_scope;\n    result->node = trans_create_node(c, NodeTypeBlock);\n    return result;\n}\n\nstatic TransScopeVar *trans_scope_var_create(Context *c, TransScope *parent_scope, Buf *wanted_name) {\n    TransScopeVar *result = allocate<TransScopeVar>(1);\n    result->base.id = TransScopeIdVar;\n    result->base.parent = parent_scope;\n    result->c_name = wanted_name;\n    result->zig_name = get_unique_name(c, wanted_name, parent_scope);\n    return result;\n}\n\nstatic TransScopeSwitch *trans_scope_switch_create(Context *c, TransScope *parent_scope) {\n    TransScopeSwitch *result = allocate<TransScopeSwitch>(1);\n    result->base.id = TransScopeIdSwitch;\n    result->base.parent = parent_scope;\n    result->switch_node = trans_create_node(c, NodeTypeSwitchExpr);\n    return result;\n}\n\nstatic TransScopeBlock *trans_scope_block_find(TransScope *scope) {\n    while (scope != nullptr) {\n        if (scope->id == TransScopeIdBlock) {\n            return (TransScopeBlock *)scope;\n        }\n        scope = scope->parent;\n    }\n    return nullptr;\n}\n\nstatic void render_aliases(Context *c) {\n    for (size_t i = 0; i < c->aliases.length; i += 1) {\n        Alias *alias = &c->aliases.at(i);\n        if (name_exists_global(c, alias->new_name))\n            continue;\n\n        add_global_var(c, alias->new_name, trans_create_node_symbol(c, alias->canon_name));\n    }\n}\n\nstatic AstNode *trans_lookup_ast_container_typeof(Context *c, AstNode *ref_node);\n\nstatic AstNode *trans_lookup_ast_container(Context *c, AstNode *type_node) {\n    if (type_node == nullptr) {\n        return nullptr;\n    } else if (type_node->type == NodeTypeContainerDecl) {\n        return type_node;\n    } else if (type_node->type == NodeTypePrefixOpExpr) {\n        return type_node;\n    } else if (type_node->type == NodeTypeSymbol) {\n        AstNode *existing_node = get_global(c, type_node->data.symbol_expr.symbol);\n        if (existing_node == nullptr)\n            return nullptr;\n        if (existing_node->type != NodeTypeVariableDeclaration)\n            return nullptr;\n        return trans_lookup_ast_container(c, existing_node->data.variable_declaration.expr);\n    } else if (type_node->type == NodeTypeFieldAccessExpr) {\n        AstNode *container_node = trans_lookup_ast_container_typeof(c, type_node->data.field_access_expr.struct_expr);\n        if (container_node == nullptr)\n            return nullptr;\n        if (container_node->type != NodeTypeContainerDecl)\n            return container_node;\n\n        for (size_t i = 0; i < container_node->data.container_decl.fields.length; i += 1) {\n            AstNode *field_node = container_node->data.container_decl.fields.items[i];\n            if (buf_eql_buf(field_node->data.struct_field.name, type_node->data.field_access_expr.field_name)) {\n                return trans_lookup_ast_container(c, field_node->data.struct_field.type);\n            }\n        }\n        return nullptr;\n    } else {\n        return nullptr;\n    }\n}\n\nstatic AstNode *trans_lookup_ast_container_typeof(Context *c, AstNode *ref_node) {\n    if (ref_node->type == NodeTypeSymbol) {\n        AstNode *existing_node = get_global(c, ref_node->data.symbol_expr.symbol);\n        if (existing_node == nullptr)\n            return nullptr;\n        if (existing_node->type != NodeTypeVariableDeclaration)\n            return nullptr;\n        return trans_lookup_ast_container(c, existing_node->data.variable_declaration.type);\n    } else if (ref_node->type == NodeTypeFieldAccessExpr) {\n        AstNode *container_node = trans_lookup_ast_container_typeof(c, ref_node->data.field_access_expr.struct_expr);\n        if (container_node == nullptr)\n            return nullptr;\n        if (container_node->type != NodeTypeContainerDecl)\n            return container_node;\n        for (size_t i = 0; i < container_node->data.container_decl.fields.length; i += 1) {\n            AstNode *field_node = container_node->data.container_decl.fields.items[i];\n            if (buf_eql_buf(field_node->data.struct_field.name, ref_node->data.field_access_expr.field_name)) {\n                return trans_lookup_ast_container(c, field_node->data.struct_field.type);\n            }\n        }\n        return nullptr;\n    } else {\n        return nullptr;\n    }\n}\n\nstatic AstNode *trans_lookup_ast_maybe_fn(Context *c, AstNode *ref_node) {\n    AstNode *prefix_node = trans_lookup_ast_container_typeof(c, ref_node);\n    if (prefix_node == nullptr)\n        return nullptr;\n    if (prefix_node->type != NodeTypePrefixOpExpr)\n        return nullptr;\n    if (prefix_node->data.prefix_op_expr.prefix_op != PrefixOpOptional)\n        return nullptr;\n\n    AstNode *fn_proto_node = prefix_node->data.prefix_op_expr.primary_expr;\n    if (fn_proto_node->type != NodeTypeFnProto)\n        return nullptr;\n\n    return fn_proto_node;\n}\n\nstatic void render_macros(Context *c) {\n    auto it = c->macro_table.entry_iterator();\n    for (;;) {\n        auto *entry = it.next();\n        if (!entry)\n            break;\n\n        AstNode *proto_node;\n        AstNode *value_node = entry->value;\n        if (value_node->type == NodeTypeFnDef) {\n            add_top_level_decl(c, value_node->data.fn_def.fn_proto->data.fn_proto.name, value_node);\n        } else if ((proto_node = trans_lookup_ast_maybe_fn(c, value_node))) {\n            \/\/ If a macro aliases a global variable which is a function pointer, we conclude that\n            \/\/ the macro is intended to represent a function that assumes the function pointer\n            \/\/ variable is non-null and calls it.\n            AstNode *inline_fn_node = trans_create_node_inline_fn(c, entry->key, value_node, proto_node);\n            add_top_level_decl(c, entry->key, inline_fn_node);\n        } else {\n            add_global_var(c, entry->key, value_node);\n        }\n    }\n}\n\nstatic AstNode *parse_ctok_primary_expr(Context *c, CTokenize *ctok, size_t *tok_i);\nstatic AstNode *parse_ctok_expr(Context *c, CTokenize *ctok, size_t *tok_i);\nstatic AstNode *parse_ctok_prefix_op_expr(Context *c, CTokenize *ctok, size_t *tok_i);\n\nstatic AstNode *parse_ctok_num_lit(Context *c, CTokenize *ctok, size_t *tok_i, bool negate) {\n    CTok *tok = &ctok->tokens.at(*tok_i);\n    if (tok->id == CTokIdNumLitInt) {\n        *tok_i += 1;\n        switch (tok->data.num_lit_int.suffix) {\n            case CNumLitSuffixNone:\n                return trans_create_node_unsigned_negative(c, tok->data.num_lit_int.x, negate);\n            case CNumLitSuffixL:\n                return trans_create_node_unsigned_negative_type(c, tok->data.num_lit_int.x, negate, \"c_long\");\n            case CNumLitSuffixU:\n                return trans_create_node_unsigned_negative_type(c, tok->data.num_lit_int.x, negate, \"c_uint\");\n            case CNumLitSuffixLU:\n                return trans_create_node_unsigned_negative_type(c, tok->data.num_lit_int.x, negate, \"c_ulong\");\n            case CNumLitSuffixLL:\n                return trans_create_node_unsigned_negative_type(c, tok->data.num_lit_int.x, negate, \"c_longlong\");\n            case CNumLitSuffixLLU:\n                return trans_create_node_unsigned_negative_type(c, tok->data.num_lit_int.x, negate, \"c_ulonglong\");\n        }\n        zig_unreachable();\n    } else if (tok->id == CTokIdNumLitFloat) {\n        *tok_i += 1;\n        double value = negate ? -tok->data.num_lit_float : tok->data.num_lit_float;\n        return trans_create_node_float_lit(c, value);\n    }\n    return nullptr;\n}\n\nstatic AstNode *parse_ctok_primary_expr(Context *c, CTokenize *ctok, size_t *tok_i) {\n    CTok *tok = &ctok->tokens.at(*tok_i);\n    switch (tok->id) {\n        case CTokIdCharLit:\n            *tok_i += 1;\n            return trans_create_node_unsigned(c, tok->data.char_lit);\n        case CTokIdStrLit:\n            *tok_i += 1;\n            return trans_create_node_str_lit_c(c, buf_create_from_buf(&tok->data.str_lit));\n        case CTokIdMinus:\n            *tok_i += 1;\n            return parse_ctok_num_lit(c, ctok, tok_i, true);\n        case CTokIdNumLitInt:\n        case CTokIdNumLitFloat:\n            return parse_ctok_num_lit(c, ctok, tok_i, false);\n        case CTokIdSymbol:\n            {\n                *tok_i += 1;\n                Buf *symbol_name = buf_create_from_buf(&tok->data.symbol);\n                return trans_create_node_symbol(c, symbol_name);\n            }\n        case CTokIdLParen:\n            {\n                *tok_i += 1;\n                AstNode *inner_node = parse_ctok_expr(c, ctok, tok_i);\n                if (inner_node == nullptr) {\n                    return nullptr;\n                }\n\n                CTok *next_tok = &ctok->tokens.at(*tok_i);\n                if (next_tok->id == CTokIdRParen) {\n                    *tok_i += 1;\n                    return inner_node;\n                }\n\n                AstNode *node_to_cast = parse_ctok_expr(c, ctok, tok_i);\n                if (node_to_cast == nullptr) {\n                    return nullptr;\n                }\n\n                CTok *next_tok2 = &ctok->tokens.at(*tok_i);\n                if (next_tok2->id != CTokIdRParen) {\n                    return nullptr;\n                }\n                *tok_i += 1;\n\n\n                \/\/if (@typeId(@typeOf(x)) == @import(\"builtin\").TypeId.Pointer)\n                \/\/    @ptrCast(dest, x)\n                \/\/else if (@typeId(@typeOf(x)) == @import(\"builtin\").TypeId.Integer)\n                \/\/    @intToPtr(dest, x)\n                \/\/else\n                \/\/    (dest)(x)\n\n                AstNode *import_builtin = trans_create_node_builtin_fn_call_str(c, \"import\");\n                import_builtin->data.fn_call_expr.params.append(trans_create_node_str_lit_non_c(c, buf_create_from_str(\"builtin\")));\n                AstNode *typeid_type = trans_create_node_field_access_str(c, import_builtin, \"TypeId\");\n                AstNode *typeid_pointer = trans_create_node_field_access_str(c, typeid_type, \"Pointer\");\n                AstNode *typeid_integer = trans_create_node_field_access_str(c, typeid_type, \"Int\");\n                AstNode *typeof_x = trans_create_node_builtin_fn_call_str(c, \"typeOf\");\n                typeof_x->data.fn_call_expr.params.append(node_to_cast);\n                AstNode *typeid_value = trans_create_node_builtin_fn_call_str(c, \"typeId\");\n                typeid_value->data.fn_call_expr.params.append(typeof_x);\n\n                AstNode *outer_if_cond = trans_create_node_bin_op(c, typeid_value, BinOpTypeCmpEq, typeid_pointer);\n                AstNode *inner_if_cond = trans_create_node_bin_op(c, typeid_value, BinOpTypeCmpEq, typeid_integer);\n                AstNode *inner_if_then = trans_create_node_builtin_fn_call_str(c, \"intToPtr\");\n                inner_if_then->data.fn_call_expr.params.append(inner_node);\n                inner_if_then->data.fn_call_expr.params.append(node_to_cast);\n                AstNode *inner_if_else = trans_create_node_cast(c, inner_node, node_to_cast);\n                AstNode *inner_if = trans_create_node_if(c, inner_if_cond, inner_if_then, inner_if_else);\n                AstNode *outer_if_then = trans_create_node_builtin_fn_call_str(c, \"ptrCast\");\n                outer_if_then->data.fn_call_expr.params.append(inner_node);\n                outer_if_then->data.fn_call_expr.params.append(node_to_cast);\n                return trans_create_node_if(c, outer_if_cond, outer_if_then, inner_if);\n            }\n        case CTokIdDot:\n        case CTokIdEOF:\n        case CTokIdRParen:\n        case CTokIdAsterisk:\n        case CTokIdBang:\n        case CTokIdTilde:\n        case CTokIdShl:\n        case CTokIdLt:\n            \/\/ not able to make sense of this\n            return nullptr;\n    }\n    zig_unreachable();\n}\n\nstatic AstNode *parse_ctok_expr(Context *c, CTokenize *ctok, size_t *tok_i) {\n    return parse_ctok_prefix_op_expr(c, ctok, tok_i);\n}\n\nstatic AstNode *parse_ctok_suffix_op_expr(Context *c, CTokenize *ctok, size_t *tok_i) {\n    AstNode *node = parse_ctok_primary_expr(c, ctok, tok_i);\n    if (node == nullptr)\n        return nullptr;\n\n    while (true) {\n        CTok *first_tok = &ctok->tokens.at(*tok_i);\n        if (first_tok->id == CTokIdDot) {\n            *tok_i += 1;\n\n            CTok *name_tok = &ctok->tokens.at(*tok_i);\n            if (name_tok->id != CTokIdSymbol) {\n                return nullptr;\n            }\n            *tok_i += 1;\n\n            node = trans_create_node_field_access(c, node, buf_create_from_buf(&name_tok->data.symbol));\n        } else if (first_tok->id == CTokIdAsterisk) {\n            *tok_i += 1;\n\n            node = trans_create_node_ptr_type(c, false, false, node, PtrLenC);\n        } else if (first_tok->id == CTokIdShl) {\n            *tok_i += 1;\n\n            AstNode *rhs_node = parse_ctok_expr(c, ctok, tok_i);\n            if (rhs_node == nullptr)\n                return nullptr;\n            node = trans_create_node_bin_op(c, node, BinOpTypeBitShiftLeft, rhs_node);\n        } else {\n            return node;\n        }\n    }\n}\n\nstatic AstNode *parse_ctok_prefix_op_expr(Context *c, CTokenize *ctok, size_t *tok_i) {\n    CTok *op_tok = &ctok->tokens.at(*tok_i);\n\n    switch (op_tok->id) {\n        case CTokIdBang:\n            {\n                *tok_i += 1;\n                AstNode *prefix_op_expr = parse_ctok_prefix_op_expr(c, ctok, tok_i);\n                if (prefix_op_expr == nullptr)\n                    return nullptr;\n                return trans_create_node_prefix_op(c, PrefixOpBoolNot, prefix_op_expr);\n            }\n        case CTokIdMinus:\n            {\n                *tok_i += 1;\n                AstNode *prefix_op_expr = parse_ctok_prefix_op_expr(c, ctok, tok_i);\n                if (prefix_op_expr == nullptr)\n                    return nullptr;\n                return trans_create_node_prefix_op(c, PrefixOpNegation, prefix_op_expr);\n            }\n        case CTokIdTilde:\n            {\n                *tok_i += 1;\n                AstNode *prefix_op_expr = parse_ctok_prefix_op_expr(c, ctok, tok_i);\n                if (prefix_op_expr == nullptr)\n                    return nullptr;\n                return trans_create_node_prefix_op(c, PrefixOpBinNot, prefix_op_expr);\n            }\n        case CTokIdAsterisk:\n            {\n                *tok_i += 1;\n                AstNode *prefix_op_expr = parse_ctok_prefix_op_expr(c, ctok, tok_i);\n                if (prefix_op_expr == nullptr)\n                    return nullptr;\n                return trans_create_node_ptr_deref(c, prefix_op_expr);\n            }\n        default:\n            return parse_ctok_suffix_op_expr(c, ctok, tok_i);\n    }\n}\n\nstatic void process_macro(Context *c, CTokenize *ctok, Buf *name, const char *char_ptr) {\n    tokenize_c_macro(ctok, (const uint8_t *)char_ptr);\n\n    if (ctok->error) {\n        return;\n    }\n\n    size_t tok_i = 0;\n    CTok *name_tok = &ctok->tokens.at(tok_i);\n    assert(name_tok->id == CTokIdSymbol && buf_eql_buf(&name_tok->data.symbol, name));\n    tok_i += 1;\n\n    AstNode *result_node = parse_ctok_suffix_op_expr(c, ctok, &tok_i);\n    if (result_node == nullptr) {\n        return;\n    }\n    CTok *eof_tok = &ctok->tokens.at(tok_i);\n    if (eof_tok->id != CTokIdEOF) {\n        return;\n    }\n    if (result_node->type == NodeTypeSymbol) {\n        \/\/ if it equals itself, ignore. for example, from stdio.h:\n        \/\/ #define stdin stdin\n        Buf *symbol_name = result_node->data.symbol_expr.symbol;\n        if (buf_eql_buf(name, symbol_name)) {\n            return;\n        }\n    }\n    c->macro_table.put(name, result_node);\n}\n\nstatic void process_preprocessor_entities(Context *c, ZigClangASTUnit *unit) {\n    CTokenize ctok = {{0}};\n\n    \/\/ TODO if we see #undef, delete it from the table\n    for (ZigClangPreprocessingRecord_iterator it = ZigClangASTUnit_getLocalPreprocessingEntities_begin(unit),\n        it_end = ZigClangASTUnit_getLocalPreprocessingEntities_end(unit); it.I != it_end.I; it.I += 1)\n    {\n        ZigClangPreprocessedEntity *entity = ZigClangPreprocessingRecord_iterator_deref(it);\n\n        switch (ZigClangPreprocessedEntity_getKind(entity)) {\n            case ZigClangPreprocessedEntity_InvalidKind:\n            case ZigClangPreprocessedEntity_InclusionDirectiveKind:\n            case ZigClangPreprocessedEntity_MacroExpansionKind:\n                continue;\n            case ZigClangPreprocessedEntity_MacroDefinitionKind:\n                {\n                    ZigClangMacroDefinitionRecord *macro = reinterpret_cast<ZigClangMacroDefinitionRecord *>(entity);\n                    const char *raw_name = ZigClangMacroDefinitionRecord_getName_getNameStart(macro);\n                    ZigClangSourceLocation begin_loc = ZigClangMacroDefinitionRecord_getSourceRange_getBegin(macro);\n                    ZigClangSourceLocation end_loc = ZigClangMacroDefinitionRecord_getSourceRange_getEnd(macro);\n\n                    if (ZigClangSourceLocation_eq(begin_loc, end_loc)) {\n                        \/\/ this means it is a macro without a value\n                        \/\/ we don't care about such things\n                        continue;\n                    }\n                    Buf *name = buf_create_from_str(raw_name);\n                    if (name_exists_global(c, name)) {\n                        continue;\n                    }\n\n                    const char *begin_c = ZigClangSourceManager_getCharacterData(c->source_manager, begin_loc);\n                    process_macro(c, &ctok, name, begin_c);\n                }\n        }\n    }\n}\n\nError parse_h_file(CodeGen *codegen, AstNode **out_root_node,\n        Stage2ErrorMsg **errors_ptr, size_t *errors_len,\n        const char **args_begin, const char **args_end,\n        Stage2TranslateMode mode, const char *resources_path)\n{\n    Context context = {0};\n    Context *c = &context;\n    c->warnings_on = codegen->verbose_cimport;\n    if (mode == Stage2TranslateModeImport) {\n        c->visib_mod = VisibModPub;\n        c->want_export = false;\n    } else {\n        c->visib_mod = VisibModPub;\n        c->want_export = true;\n    }\n    c->decl_table.init(8);\n    c->macro_table.init(8);\n    c->global_table.init(8);\n    c->ptr_params.init(8);\n    c->codegen = codegen;\n    c->global_scope = trans_scope_root_create(c);\n\n    ZigClangASTUnit *ast_unit = ZigClangLoadFromCommandLine(args_begin, args_end, errors_ptr, errors_len,\n            resources_path);\n    if (ast_unit == nullptr) {\n        if (*errors_len == 0) return ErrorNoMem;\n        return ErrorCCompileErrors;\n    }\n\n    c->ctx = ZigClangASTUnit_getASTContext(ast_unit);\n    c->source_manager = ZigClangASTUnit_getSourceManager(ast_unit);\n    c->root = trans_create_node(c, NodeTypeContainerDecl);\n    c->root->data.container_decl.is_root = true;\n\n    ZigClangASTUnit_visitLocalTopLevelDecls(ast_unit, c, decl_visitor);\n\n    process_preprocessor_entities(c, ast_unit);\n\n    render_macros(c);\n    render_aliases(c);\n\n    *out_root_node = c->root;\n\n    ZigClangASTUnit_delete(ast_unit);\n\n    return ErrorNone;\n}\n","avg_line_length":48.6826625387,"max_line_length":196,"alphanum_fraction":0.6759038443,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2073,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/\n\/\/ Created by chenlei on 2020\/5\/3.\n\/\/\n\n#include \"HttpData.h\"\n\nHttpData::HttpData() {\n    httpRes = \"HTTP\/1.1 200 OK\\r\\nConnection: Keep-Alive\\r\\nContent-Type: text\/html; charset=UTF-8\\r\\nContent-Length: 1048576\\r\\n\\r\\n123456\";\n    for (int i = 0; i < 1048570; i++) {\n        httpRes += '\\0';\n    }\n}\n\nvoid HttpData::handleRead(int _fd) {\n    char buf[4096];\n    int n = 0;\n    while ((n = ::read(_fd, buf, sizeof buf)) > 0) {\n        if (true)\n            printf(\"read %d bytes\\n\", n);\n        std::string &readed = cons[_fd].readed;\n        readed.append(buf, n);\n        if (readed.length() > 4) {\n            if (readed.substr(readed.length() - 2, 2) == \"\\n\\n\" || readed.substr(readed.length() - 4, 4) == \"\\r\\n\\r\\n\") {\n                \/\/\u5f53\u8bfb\u53d6\u5230\u4e00\u4e2a\u5b8c\u6574\u7684http\u8bf7\u6c42\uff0c\u6d4b\u8bd5\u53d1\u9001\u54cd\u5e94\n                sendRes(_fd);\n            }\n        }\n    }\/\/\u5c06socket\u4e2d\u7684\u6570\u636e\u8bfb\u5b8c\u4e86\uff0c\u4f46\u662f\u8bf7\u6c42\u53ef\u80fd\u8fd8\u6ca1\u6709\u5b8c\u5168\u5199\u5165\u5230socket\uff08\u5176\u4e2d\u539f\u56e0\u53ef\u80fd\u662f\u8bf7\u6c42\u6570\u636e\u592a\u5927\uff0c\u800csocket\u5927\u5c0f\u6709\u9650\uff09\n    if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))\n        return; \/\/\u8fd4\u56de\u540e\uff0csocket\u4e2d\u53ef\u80fd\u5f88\u5feb\u53c8\u4f1a\u88ab\u5199\u5165\u6570\u636e\uff0c\u5219\u53c8\u4f1a\u51fa\u53d1epoll_wait()\n    \/\/\u5b9e\u9645\u5e94\u7528\u4e2d\uff0cn<0\u5e94\u5f53\u68c0\u67e5\u5404\u7c7b\u9519\u8bef\uff0c\u5982EINTR\n    if (n < 0) {\n        printf(\"read %d error: %d %s\\n\", _fd, errno, strerror(errno));\n    }\n    close(_fd);\n    cons.erase(_fd);\n}\n\nvoid HttpData::handleWrite(int _fd) {\n    sendRes(_fd);\n}\n\nvoid HttpData::sendRes(int _fd) {\n    Con &con = cons[_fd];\n    if (!con.readed.length())   \/\/\u82e5\u6765\u81eaclient\u7684\u8bf7\u6c42\u6ca1\u6709\u6570\u636e\uff0c\u5219\u4e0d\u4f1a\u7ed9\u56de\u590d\n        return;\n    size_t left = httpRes.length() - con.written;\n    int wd = 0;\n    while ((wd = ::write(_fd, httpRes.data() + con.written, left)) > 0) {\n        con.written += wd;\n        left -= wd;\n        if (true)\n            printf(\"write %d bytes left: %lu\\n\", wd, left);\n    };\n    if (left == 0) {\n        \/\/        close(_fd); \/\/ \u6d4b\u8bd5\u4e2d\u4f7f\u7528\u4e86keepalive\uff0c\u56e0\u6b64\u4e0d\u5173\u95ed\u8fde\u63a5\u3002\u8fde\u63a5\u4f1a\u5728read\u4e8b\u4ef6\u4e2d\u5173\u95ed\n        cons.erase(_fd);\n        return;\n    }\n    if (wd < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))    \/\/\u7f13\u51b2\u533a\u5df2\u6ee1\uff0c\u9700\u8981\u7b49\u5f85socket\u518d\u6b21\u53d8\u4e3a\u53ef\u5199\n        return; \/\/\u5373\u5c06\u5f53\u524dsocket\u53d1\u9001\u7ed9client\u540e\uff0csocket\u53d8\u4e3a\u53ef\u5199\uff0c\u7136\u540e\u518d\u63a5\u7740\u5199\n    if (wd <= 0) {\n        printf(\"write error for %d: %d %s\\n\", _fd, errno, strerror(errno));\n        close(_fd);\n        cons.erase(_fd);\n    }\n}\n\n","avg_line_length":30.0434782609,"max_line_length":141,"alphanum_fraction":0.5460684998,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4194,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ type_traits\n\n\/\/ is_nothrow_destructible\n\n\/\/ Prevent warning when testing the Abstract test type.\n#if defined(__clang__)\n#\tpragma clang diagnostic ignored \"-Wdelete-non-virtual-dtor\"\n#endif\n\n\/\/ #include \"..\/test_macros.h\"\n#include \"test-utilities.hpp\"\n#include <catch2\/catch.hpp>\n\n#include \"rider\/faiz\/type_traits.hpp\"\n\nnamespace\n{\n\n\ttemplate<class T>\n\tvoid\n\ttest_is_nothrow_destructible()\n\t{\n\t\tSTATIC_REQUIRE(Rider::Faiz::is_nothrow_destructible<T>::value);\n\t\tSTATIC_REQUIRE(Rider::Faiz::is_nothrow_destructible<const T>::value);\n\t\tSTATIC_REQUIRE(Rider::Faiz::is_nothrow_destructible<volatile T>::value);\n\t\tSTATIC_REQUIRE(\n\t\t\tRider::Faiz::is_nothrow_destructible<const volatile T>::value);\n#if TEST_STD_VER > 14\n\t\tSTATIC_REQUIRE(Rider::Faiz::is_nothrow_destructible_v<T>);\n\t\tSTATIC_REQUIRE(Rider::Faiz::is_nothrow_destructible_v<const T>);\n\t\tSTATIC_REQUIRE(Rider::Faiz::is_nothrow_destructible_v<volatile T>);\n\t\tSTATIC_REQUIRE(\n\t\t\tRider::Faiz::is_nothrow_destructible_v<const volatile T>);\n#endif\n\t}\n\n\ttemplate<class T>\n\tvoid\n\ttest_is_not_nothrow_destructible()\n\t{\n\t\tSTATIC_REQUIRE(!Rider::Faiz::is_nothrow_destructible<T>::value);\n\t\tSTATIC_REQUIRE(!Rider::Faiz::is_nothrow_destructible<const T>::value);\n\t\tSTATIC_REQUIRE(\n\t\t\t!Rider::Faiz::is_nothrow_destructible<volatile T>::value);\n\t\tSTATIC_REQUIRE(\n\t\t\t!Rider::Faiz::is_nothrow_destructible<const volatile T>::value);\n#if TEST_STD_VER > 14\n\t\tSTATIC_REQUIRE(!Rider::Faiz::is_nothrow_destructible_v<T>);\n\t\tSTATIC_REQUIRE(!Rider::Faiz::is_nothrow_destructible_v<const T>);\n\t\tSTATIC_REQUIRE(!Rider::Faiz::is_nothrow_destructible_v<volatile T>);\n\t\tSTATIC_REQUIRE(\n\t\t\t!Rider::Faiz::is_nothrow_destructible_v<const volatile T>);\n#endif\n\t}\n\n\n\tstruct PublicDestructor\n\t{\n\tpublic:\n\t\t~PublicDestructor()\n\t\t{}\n\t};\n\tstruct ProtectedDestructor\n\t{\n\tprotected:\n\t\t~ProtectedDestructor()\n\t\t{}\n\t};\n\tstruct PrivateDestructor\n\t{\n\tprivate:\n\t\t~PrivateDestructor()\n\t\t{}\n\t};\n\n\tstruct VirtualPublicDestructor\n\t{\n\tpublic:\n\t\tvirtual ~VirtualPublicDestructor()\n\t\t{}\n\t};\n\tstruct VirtualProtectedDestructor\n\t{\n\tprotected:\n\t\tvirtual ~VirtualProtectedDestructor()\n\t\t{}\n\t};\n\tstruct VirtualPrivateDestructor\n\t{\n\tprivate:\n\t\tvirtual ~VirtualPrivateDestructor()\n\t\t{}\n\t};\n\n\tstruct PurePublicDestructor\n\t{\n\tpublic:\n\t\tvirtual ~PurePublicDestructor() = 0;\n\t};\n\tstruct PureProtectedDestructor\n\t{\n\tprotected:\n\t\tvirtual ~PureProtectedDestructor() = 0;\n\t};\n\tstruct PurePrivateDestructor\n\t{\n\tprivate:\n\t\tvirtual ~PurePrivateDestructor() = 0;\n\t};\n\n\tclass Empty\n\t{};\n\n\n\tunion Union\n\t{};\n\n\tstruct bit_zero\n\t{\n\t\tint : 0;\n\t};\n\n\tclass Abstract\n\t{\n\t\tvirtual void\n\t\tfoo()\n\t\t\t= 0;\n\t};\n\n\n} \/\/ namespace\nTEST_CASE(\"is_nothrow_destructible.libcxx: \")\n{\n\ttest_is_not_nothrow_destructible<void>();\n\ttest_is_not_nothrow_destructible<char[]>();\n\ttest_is_not_nothrow_destructible<char[][3]>();\n\n\ttest_is_nothrow_destructible<int&>();\n\ttest_is_nothrow_destructible<int>();\n\ttest_is_nothrow_destructible<double>();\n\ttest_is_nothrow_destructible<int*>();\n\ttest_is_nothrow_destructible<const int*>();\n\ttest_is_nothrow_destructible<char[3]>();\n\n#if TEST_STD_VER >= 11\n\t\/\/ requires noexcept. These are all destructible.\n\ttest_is_nothrow_destructible<PublicDestructor>();\n\ttest_is_nothrow_destructible<VirtualPublicDestructor>();\n\ttest_is_nothrow_destructible<PurePublicDestructor>();\n\ttest_is_nothrow_destructible<bit_zero>();\n\ttest_is_nothrow_destructible<Abstract>();\n\ttest_is_nothrow_destructible<Empty>();\n\ttest_is_nothrow_destructible<Union>();\n\n\t\/\/ requires access control\n\ttest_is_not_nothrow_destructible<ProtectedDestructor>();\n\ttest_is_not_nothrow_destructible<PrivateDestructor>();\n\ttest_is_not_nothrow_destructible<VirtualProtectedDestructor>();\n\ttest_is_not_nothrow_destructible<VirtualPrivateDestructor>();\n\ttest_is_not_nothrow_destructible<PureProtectedDestructor>();\n\ttest_is_not_nothrow_destructible<PurePrivateDestructor>();\n#endif\n}\n","avg_line_length":24.2427745665,"max_line_length":80,"alphanum_fraction":0.7334287077,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":54189,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/* Copyright 2017 - 2021 R. Thomas\n * Copyright 2017 - 2021 Quarkslab\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <utility>\n#include <algorithm>\n#include <iterator>\n#include <map>\n#include <numeric>\n#include <limits>\n\n#include \"logging.hpp\"\n#include \"hash_stream.hpp\"\n\n#include \"LIEF\/exception.hpp\"\n#include \"LIEF\/utils.hpp\"\n#include \"LIEF\/BinaryStream\/VectorStream.hpp\"\n#include \"LIEF\/iostream.hpp\"\n\n#include \"LIEF\/Abstract\/Relocation.hpp\"\n\n#include \"LIEF\/PE\/hash.hpp\"\n#include \"LIEF\/PE\/Structures.hpp\"\n#include \"LIEF\/PE\/Binary.hpp\"\n#include \"LIEF\/PE\/Builder.hpp\"\n#include \"LIEF\/PE\/utils.hpp\"\n#include \"LIEF\/PE\/EnumToString.hpp\"\n#include \"LIEF\/PE\/ResourceDirectory.hpp\"\n#include \"LIEF\/PE\/ResourceData.hpp\"\n#include \"LIEF\/PE\/DataDirectory.hpp\"\n#include \"LIEF\/PE\/Section.hpp\"\n#include \"LIEF\/PE\/Relocation.hpp\"\n#include \"LIEF\/PE\/RelocationEntry.hpp\"\n#include \"LIEF\/PE\/ImportEntry.hpp\"\n#include \"LIEF\/PE\/ExportEntry.hpp\"\n#include \"LIEF\/PE\/ResourcesManager.hpp\"\n#include \"LIEF\/PE\/Symbol.hpp\"\n#include \"LIEF\/PE\/LoadConfigurations\/LoadConfiguration.hpp\"\n\nnamespace LIEF {\nnamespace PE {\n\nstatic const std::map<MACHINE_TYPES, std::pair<ARCHITECTURES, std::set<MODES>>> arch_pe_to_lief {\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_UNKNOWN,   {ARCH_NONE,  {}}},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_AMD64,     {ARCH_X86,   {MODE_64}}},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_ARM,       {ARCH_ARM,   {MODE_32}}}, \/\/ MODE_LITTLE_ENDIAN\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_ARMNT,     {ARCH_ARM,   {MODE_32, MODE_V7, MODE_THUMB}}},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_ARM64,     {ARCH_ARM64, {MODE_64, MODE_V8}}},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_I386,      {ARCH_X86,   {MODE_32}}},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_IA64,      {ARCH_INTEL, {MODE_64}}},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_THUMB,     {ARCH_ARM,   {MODE_32, MODE_THUMB}}},\n};\n\nstatic const std::map<MACHINE_TYPES, ENDIANNESS> arch_pe_to_endi_lief {\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_UNKNOWN,   ENDIANNESS::ENDIAN_NONE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_AM33,      ENDIANNESS::ENDIAN_NONE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_AMD64,     ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_ARM,       ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_ARMNT,     ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_ARM64,     ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_EBC,       ENDIANNESS::ENDIAN_NONE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_I386,      ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_IA64,      ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_M32R,      ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_MIPS16,    ENDIANNESS::ENDIAN_BIG},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_MIPSFPU,   ENDIANNESS::ENDIAN_BIG},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_MIPSFPU16, ENDIANNESS::ENDIAN_BIG},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_POWERPC,   ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_POWERPCFP, ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_R4000,     ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_RISCV32,   ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_RISCV64,   ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_RISCV128,  ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_SH3,       ENDIANNESS::ENDIAN_NONE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_SH3DSP,    ENDIANNESS::ENDIAN_NONE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_SH4,       ENDIANNESS::ENDIAN_NONE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_SH5,       ENDIANNESS::ENDIAN_NONE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_THUMB,     ENDIANNESS::ENDIAN_LITTLE},\n  {MACHINE_TYPES::IMAGE_FILE_MACHINE_WCEMIPSV2, ENDIANNESS::ENDIAN_LITTLE},\n};\n\n\nBinary::Binary(void) :\n  dos_header_{},\n  rich_header_{},\n  header_{},\n  optional_header_{},\n  available_sections_space_{0xc}, \/\/ (0x400 - 0x1f8) \/ sizeof(IMAGE_SECTION_HEADER)\n  has_rich_header_{false},\n  has_tls_{false},\n  has_imports_{false},\n  has_exports_{false},\n  has_resources_{false},\n  has_exceptions_{false},\n  has_relocations_{false},\n  has_debug_{false},\n  has_configuration_{false},\n  is_reproducible_build_{false},\n  tls_{},\n  sections_{},\n  data_directories_{},\n  symbols_{},\n  strings_table_{},\n  relocations_{},\n  resources_{nullptr},\n  imports_{},\n  export_{},\n  debug_{},\n  overlay_{},\n  dos_stub_{},\n  load_configuration_{nullptr}\n{}\n\nBinary::~Binary(void) {\n  for (Section *section : this->sections_) {\n    delete section;\n  }\n\n  for (DataDirectory *directory : this->data_directories_) {\n    delete directory;\n  }\n\n  for (Relocation *relocation : this->relocations_) {\n    delete relocation;\n  }\n\n  if (this->resources_ != nullptr) {\n    delete this->resources_;\n  }\n\n  if (this->load_configuration_ != nullptr) {\n    delete this->load_configuration_;\n  }\n}\n\nPE_TYPE Binary::type(void) const {\n  return this->type_;\n}\n\n\nBinary::Binary(const std::string& name, PE_TYPE type) :\n  Binary::Binary{}\n{\n  this->type_ = type;\n  this->name_ = name;\n\n  if (type == PE_TYPE::PE32) {\n    this->header().machine(MACHINE_TYPES::IMAGE_FILE_MACHINE_I386);\n\n    this->header().sizeof_optional_header(sizeof(pe32_optional_header) + (DEFAULT_NUMBER_DATA_DIRECTORIES + 1) * sizeof(pe_data_directory));\n    this->header().add_characteristic(HEADER_CHARACTERISTICS::IMAGE_FILE_32BIT_MACHINE);\n\n    this->optional_header().magic(PE_TYPE::PE32);\n  } else {\n    this->header().machine(MACHINE_TYPES::IMAGE_FILE_MACHINE_AMD64);\n    this->header().sizeof_optional_header(sizeof(pe64_optional_header) + (DEFAULT_NUMBER_DATA_DIRECTORIES + 1) * sizeof(pe_data_directory));\n    this->header().add_characteristic(HEADER_CHARACTERISTICS::IMAGE_FILE_LARGE_ADDRESS_AWARE);\n\n    this->optional_header().magic(PE_TYPE::PE32_PLUS);\n  }\n\n  \/\/ Add data directories\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::EXPORT_TABLE});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::IMPORT_TABLE});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::RESOURCE_TABLE});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::EXCEPTION_TABLE});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::CERTIFICATE_TABLE});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::BASE_RELOCATION_TABLE});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::DEBUG});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::ARCHITECTURE});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::GLOBAL_PTR});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::TLS_TABLE});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::LOAD_CONFIG_TABLE});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::BOUND_IMPORT});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::IAT});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::DELAY_IMPORT_DESCRIPTOR});\n  this->data_directories_.emplace_back(new DataDirectory{DATA_DIRECTORY::CLR_RUNTIME_HEADER});\n\n  this->optional_header().sizeof_headers(this->sizeof_headers());\n  this->optional_header().sizeof_image(this->virtual_size());\n}\n\nvoid Binary::write(const std::string& filename) {\n  Builder builder{this};\n\n  builder.\n    build_imports(false).\n    patch_imports(false).\n    build_relocations(false).\n    build_tls(false).\n    build_resources(true);\n\n  builder.build();\n  builder.write(filename);\n}\n\nTLS& Binary::tls(void) {\n  return const_cast<TLS&>(static_cast<const Binary*>(this)->tls());\n}\n\n\nconst TLS& Binary::tls(void) const {\n  return this->tls_;\n}\n\nvoid Binary::tls(const TLS& tls) {\n  this->tls_ = tls;\n  this->has_tls_ = true;\n}\n\nuint64_t Binary::va_to_offset(uint64_t VA) {\n\n  \/\/TODO: add checks relocation\/va < imagebase\n  uint64_t rva = VA - this->optional_header().imagebase();\n  return this->rva_to_offset(rva);\n}\n\nuint64_t Binary::rva_to_offset(uint64_t RVA) {\n  auto&& it_section = std::find_if(\n      std::begin(this->sections_),\n      std::end(this->sections_),\n      [RVA] (const Section* section)\n      {\n        if (section == nullptr) {\n          return false;\n        }\n        return (RVA >= section->virtual_address() and\n            RVA < (section->virtual_address() + section->virtual_size()));\n      });\n\n  if (it_section == std::end(sections_)) {\n    \/\/ If not found within a section,\n    \/\/ we assume that rva == offset\n    return RVA;\n  }\n  LIEF_TRACE(\"rva_to_offset(0x{:x}): {}\", RVA, (*it_section)->name());\n\n  \/\/ rva - virtual_address + pointer_to_raw_data\n  uint32_t section_alignment = this->optional_header().section_alignment();\n  uint32_t file_alignment    = this->optional_header().file_alignment();\n  if (section_alignment < 0x1000) {\n    section_alignment = file_alignment;\n  }\n\n  uint64_t section_va     = (*it_section)->virtual_address();\n  uint64_t section_offset = (*it_section)->pointerto_raw_data();\n\n  section_va     = align(section_va, section_alignment);\n  section_offset = align(section_offset, file_alignment);\n  return ((RVA - section_va) + section_offset);\n}\n\nconst Section& Binary::section_from_offset(uint64_t offset) const {\n  auto&& it_section = std::find_if(\n      std::begin(this->sections_),\n      std::end(this->sections_),\n      [&offset] (const Section* section) {\n        if (section == nullptr) {\n          return false;\n        }\n        return (\n            offset >= section->pointerto_raw_data() and\n            offset < (section->pointerto_raw_data() + section->sizeof_raw_data()));\n      });\n\n  if (it_section == std::end(this->sections_)) {\n    throw LIEF::not_found(\"Section not found\");\n  }\n\n  return **it_section;\n}\n\nSection& Binary::section_from_offset(uint64_t offset) {\n  return const_cast<Section&>(static_cast<const Binary*>(this)->section_from_offset(offset));\n}\n\n\nconst Section& Binary::section_from_rva(uint64_t virtual_address) const {\n  auto&& it_section = std::find_if(\n      std::begin(this->sections_),\n      std::end(this->sections_),\n      [&virtual_address] (const Section* section) {\n        if (section == nullptr) {\n          return false;\n        }\n        return (\n            virtual_address >= section->virtual_address() and\n            virtual_address < (section->virtual_address() + section->virtual_size()));\n      });\n\n  if (it_section == std::end(this->sections_)) {\n    throw LIEF::not_found(\"Section not found\");\n  }\n\n\n  return **it_section;\n}\n\nSection& Binary::section_from_rva(uint64_t virtual_address) {\n  return const_cast<Section&>(static_cast<const Binary*>(this)->section_from_rva(virtual_address));\n}\n\n\n\nDataDirectory& Binary::data_directory(DATA_DIRECTORY index) {\n  return const_cast<DataDirectory&>(static_cast<const Binary*>(this)->data_directory(index));\n}\n\nconst DataDirectory& Binary::data_directory(DATA_DIRECTORY index) const {\n  if (static_cast<size_t>(index) < this->data_directories_.size() and this->data_directories_[static_cast<size_t>(index)] != nullptr) {\n    return *this->data_directories_[static_cast<size_t>(index)];\n  } else {\n    throw not_found(\"Data directory doesn't exist\");\n  }\n}\n\n\nbool Binary::has(DATA_DIRECTORY index) const {\n  auto&& it = std::find_if(\n      std::begin(this->data_directories_),\n      std::end(this->data_directories_),\n      [index] (const DataDirectory* d) {\n        return d->type() == index;\n      });\n  return it != std::end(this->data_directories_);\n}\n\nbool Binary::has_rich_header(void) const {\n  return this->has_rich_header_;\n}\n\nbool Binary::has_tls(void) const {\n  return this->has_tls_;\n}\n\nbool Binary::has_imports(void) const {\n  return this->has_imports_;\n}\n\nbool Binary::has_signatures(void) const {\n  return not this->signatures_.empty();\n}\n\nbool Binary::has_exports(void) const {\n  return this->has_exports_;\n}\n\nbool Binary::has_resources(void) const {\n  return this->has_resources_ and this->resources_ != nullptr;\n}\n\nbool Binary::has_exceptions(void) const {\n  return this->has(DATA_DIRECTORY::EXCEPTION_TABLE);\n  \/\/return this->has_exceptions_;\n}\n\n\nbool Binary::has_relocations(void) const {\n  return this->has_relocations_;\n}\n\nbool Binary::has_debug(void) const {\n  return this->has_debug_;\n}\n\nbool Binary::is_reproducible_build(void) const {\n  return this->is_reproducible_build_;\n}\n\nbool Binary::has_configuration(void) const {\n  return this->has_configuration_ and this->load_configuration_ != nullptr;\n}\n\nconst LoadConfiguration& Binary::load_configuration(void) const {\n  if (not this->has_configuration()) {\n    throw not_found(\"The binary doesn't have load configuration\");\n  }\n  return *this->load_configuration_;\n}\n\nLoadConfiguration& Binary::load_configuration(void) {\n  return const_cast<LoadConfiguration&>(static_cast<const Binary*>(this)->load_configuration());\n}\n\n\/\/\n\/\/ Interface with LIEF::Binary\n\/\/\nLIEF::symbols_t Binary::get_abstract_symbols(void) {\n  LIEF::symbols_t lief_symbols;\n  for (Symbol& s : this->symbols_) {\n    lief_symbols.push_back(&s);\n  }\n  return lief_symbols;\n}\n\n\n\/\/ Sections\n\/\/ ========\n\nit_sections Binary::sections(void) {\n  return this->sections_;\n}\n\n\nit_const_sections Binary::sections(void) const {\n  return this->sections_;\n}\n\nLIEF::sections_t Binary::get_abstract_sections(void) {\n  return {std::begin(this->sections_), std::end(this->sections_)};\n}\n\n\nSection& Binary::get_section(const std::string& name) {\n  return const_cast<Section&>(static_cast<const Binary*>(this)->get_section(name));\n}\n\nconst Section& Binary::get_section(const std::string& name) const {\n  auto&& section_it = std::find_if(\n      std::begin(this->sections_),\n      std::end(this->sections_),\n      [&name] (const Section* section)\n      {\n        return section != nullptr and section->name() == name;\n      });\n\n  if (section_it == std::end(this->sections_)) {\n    throw LIEF::not_found(\"No such section with this name\");\n  }\n  return **section_it;\n}\n\n\nconst Section& Binary::import_section(void) const {\n  if (not this->has_imports()) {\n    throw not_found(\"Current binary doesn't have Import directory\");\n  }\n  const DataDirectory& import_directory = this->data_directory(DATA_DIRECTORY::IMPORT_TABLE);\n  return import_directory.section();\n}\n\n\nSection& Binary::import_section(void) {\n  return const_cast<Section&>(static_cast<const Binary*>(this)->import_section());\n}\n\n\/\/ Headers\n\/\/ =======\n\n\/\/ Dos Header\n\/\/ ----------\nDosHeader& Binary::dos_header(void) {\n  return const_cast<DosHeader&>(static_cast<const Binary*>(this)->dos_header());\n}\n\n\nconst DosHeader& Binary::dos_header(void) const {\n  return this->dos_header_;\n}\n\n\n\/\/ Standard header\n\/\/ ---------------\nHeader& Binary::header(void) {\n  return const_cast<Header&>(static_cast<const Binary*>(this)->header());\n}\n\n\nconst Header& Binary::header(void) const {\n  return this->header_;\n}\n\n\/\/ Optional Header\n\/\/ ---------------\nconst OptionalHeader& Binary::optional_header(void) const {\n  return this->optional_header_;\n}\n\n\nOptionalHeader& Binary::optional_header(void) {\n  return const_cast<OptionalHeader&>(static_cast<const Binary*>(this)->optional_header());\n}\n\n\n\n\nuint64_t Binary::virtual_size(void) const {\n  uint64_t size = 0;\n  size += this->dos_header().addressof_new_exeheader();\n  size += sizeof(pe_header);\n  if (this->type_ == PE_TYPE::PE32) {\n    size += sizeof(pe32_optional_header);\n  } else {\n    size += sizeof(pe64_optional_header);\n  }\n  for (const Section* section : this->sections_) {\n    size = std::max(size, section->virtual_address() + section->virtual_size());\n  }\n  size = LIEF::align(size, this->optional_header().section_alignment());\n  return size;\n}\n\n\nuint32_t Binary::sizeof_headers(void) const {\n  uint32_t size = 0;\n  size += this->dos_header().addressof_new_exeheader();\n  size += sizeof(pe_header);\n  if (this->type_ == PE_TYPE::PE32) {\n    size += sizeof(pe32_optional_header);\n  } else {\n    size += sizeof(pe64_optional_header);\n  }\n\n  size += sizeof(pe_data_directory) * (this->data_directories_.size() + 1);\n  size += sizeof(pe_section) * (this->sections_.size() + 1);\n  size = static_cast<uint32_t>(LIEF::align(size, this->optional_header().file_alignment()));\n  return size;\n\n}\n\nvoid Binary::remove_section(const std::string& name, bool clear) {\n\n\n  auto&& it_section = std::find_if(\n      std::begin(this->sections_),\n      std::end(this->sections_),\n      [&name] (const Section* section) {\n        return section->name() == name;\n      });\n\n  if (it_section == std::end(this->sections_)) {\n    LIEF_ERR(\"Unable to find section: '{}'\", name);\n    return;\n  }\n\n  return this->remove(**it_section, clear);\n}\n\n\nvoid Binary::remove(const Section& section, bool clear) {\n  auto&& it_section = std::find_if(\n      std::begin(this->sections_),\n      std::end(this->sections_),\n      [&section] (const Section* s) {\n        return *s == section;\n      });\n  if (it_section == std::end(this->sections_)) {\n    LIEF_ERR(\"Unable to find section: '{}'\", section.name());\n    return;\n  }\n\n  Section* to_remove = *it_section;\n  const size_t section_index = std::distance(std::begin(this->sections_), it_section);\n\n  if (section_index < (this->sections_.size() - 1) and section_index > 0) {\n    Section* previous = this->sections_[section_index - 1];\n    const size_t raw_size_gap = (to_remove->offset() + to_remove->size()) - (previous->offset() + previous->size());\n    previous->size(previous->size() + raw_size_gap);\n\n    const size_t vsize_size_gap = (to_remove->virtual_address() + to_remove->virtual_size()) - (previous->virtual_address() + previous->virtual_size());\n    previous->virtual_size(previous->virtual_size() + vsize_size_gap);\n  }\n\n\n  if (clear) {\n    to_remove->clear(0);\n  }\n\n  delete to_remove;\n  this->sections_.erase(it_section);\n\n  this->header().numberof_sections(this->header().numberof_sections() - 1);\n\n  this->optional_header().sizeof_headers(this->sizeof_headers());\n  this->optional_header().sizeof_image(static_cast<uint32_t>(this->virtual_size()));\n}\n\nvoid Binary::make_space_for_new_section(void) {\n  const uint32_t shift = align(sizeof(pe_section), this->optional_header().file_alignment());\n  LIEF_DEBUG(\"Making space for a new section header\");\n  LIEF_DEBUG(\"  -> Shifting all sections by 0x{:x}\", shift);\n\n  \/\/ Shift offset of the section content by the size of\n  \/\/ a section header aligned on \"file alignment\"\n  for (Section* section : this->sections_) {\n    section->pointerto_raw_data(section->pointerto_raw_data() + shift);\n  }\n  this->available_sections_space_++;\n}\n\nSection& Binary::add_section(const Section& section, PE_SECTION_TYPES type) {\n\n  if (this->available_sections_space_ < 0) {\n    this->make_space_for_new_section();\n    return this->add_section(section, type);\n  }\n\n  \/\/ Check if a section of type **type** already exist\n  auto&& it_section = std::find_if(\n      std::begin(this->sections_),\n      std::end(this->sections_),\n      [&type] (const Section* s) {\n        return s != nullptr and s->is_type(type);\n      });\n\n  if (it_section != std::end(this->sections_)) {\n    Section* s = *it_section;\n    s->remove_type(type);\n  }\n\n  Section* new_section                = new Section{section};\n  std::vector<uint8_t> content        = new_section->content();\n  const uint32_t section_size         = static_cast<uint32_t>(content.size());\n  const uint32_t section_size_aligned = static_cast<uint32_t>(align(section_size, this->optional_header().file_alignment()));\n  const uint32_t virtual_size         = section_size;\n\n  content.insert(std::end(content), section_size_aligned - section_size, 0);\n  new_section->content(content);\n\n  \/\/ Compute new section offset\n  uint64_t new_section_offset = align(std::accumulate(\n      std::begin(this->sections_),\n      std::end(this->sections_), this->sizeof_headers(),\n      [] (uint64_t offset, const Section* s) {\n        return std::max<uint64_t>(s->pointerto_raw_data() + s->sizeof_raw_data(), offset);\n      }), this->optional_header().file_alignment());\n\n  LIEF_DEBUG(\"New section offset: 0x{:x}\", new_section_offset);\n\n\n  \/\/ Compute new section Virtual address\n  const uint64_t new_section_va = align(std::accumulate(\n      std::begin(this->sections_),\n      std::end(this->sections_), this->optional_header().section_alignment(),\n      [] (uint64_t va, const Section* s) {\n        return std::max<uint64_t>(s->virtual_address() + s->virtual_size(), va);\n      }), this->optional_header().section_alignment());\n\n  LIEF_DEBUG(\"New section VA: 0x{:x}\", new_section_va);\n\n  new_section->add_type(type);\n\n  if (new_section->pointerto_raw_data() == 0) {\n    new_section->pointerto_raw_data(new_section_offset);\n  }\n\n  if (new_section->sizeof_raw_data() == 0) {\n    new_section->sizeof_raw_data(section_size_aligned);\n  }\n\n  if (new_section->virtual_address() == 0) {\n    new_section->virtual_address(new_section_va);\n  }\n\n  if (new_section->virtual_size() == 0) {\n    new_section->virtual_size(virtual_size);\n  }\n\n  if (new_section->is_type(PE_SECTION_TYPES::TEXT)) {\n    new_section->add_characteristic(SECTION_CHARACTERISTICS::IMAGE_SCN_CNT_CODE);\n    new_section->add_characteristic(SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_EXECUTE);\n    new_section->add_characteristic(SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_READ);\n    this->optional_header().baseof_code(static_cast<uint32_t>(new_section->virtual_address()));\n    this->optional_header().sizeof_code(new_section->sizeof_raw_data());\n  }\n\n  if (new_section->is_type(PE_SECTION_TYPES::DATA)) {\n    new_section->add_characteristic(SECTION_CHARACTERISTICS::IMAGE_SCN_CNT_INITIALIZED_DATA);\n    new_section->add_characteristic(SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_READ);\n    new_section->add_characteristic(SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_WRITE);\n\n    if (this->type() == PE_TYPE::PE32) {\n      this->optional_header().baseof_data(static_cast<uint32_t>(new_section->virtual_address()));\n    }\n    this->optional_header().sizeof_initialized_data(new_section->sizeof_raw_data());\n  }\n\n\n  if (type == PE_SECTION_TYPES::IMPORT) {\n\n    new_section->add_characteristic(SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_READ);\n    new_section->add_characteristic(SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_EXECUTE);\n    new_section->add_characteristic(SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_WRITE);\n\n    this->data_directory(DATA_DIRECTORY::IMPORT_TABLE).RVA(new_section->virtual_address());\n    this->data_directory(DATA_DIRECTORY::IMPORT_TABLE).size(new_section->sizeof_raw_data());\n    this->data_directory(DATA_DIRECTORY::IMPORT_TABLE).section_ = new_section;\n    this->data_directory(DATA_DIRECTORY::IAT).RVA(0);\n    this->data_directory(DATA_DIRECTORY::IAT).size(0);\n  }\n\n  if (type == PE_SECTION_TYPES::RELOCATION) {\n    this->data_directory(DATA_DIRECTORY::BASE_RELOCATION_TABLE).RVA(new_section->virtual_address());\n    this->data_directory(DATA_DIRECTORY::BASE_RELOCATION_TABLE).size(new_section->virtual_size());\n    this->data_directory(DATA_DIRECTORY::BASE_RELOCATION_TABLE).section_ = new_section;\n  }\n\n  if (type == PE_SECTION_TYPES::RESOURCE) {\n    this->data_directory(DATA_DIRECTORY::RESOURCE_TABLE).RVA(new_section->virtual_address());\n    this->data_directory(DATA_DIRECTORY::RESOURCE_TABLE).size(new_section->size());\n    this->data_directory(DATA_DIRECTORY::RESOURCE_TABLE).section_ = new_section;\n  }\n\n  if (type == PE_SECTION_TYPES::TLS) {\n    this->data_directory(DATA_DIRECTORY::TLS_TABLE).RVA(new_section->virtual_address());\n    this->data_directory(DATA_DIRECTORY::TLS_TABLE).size(new_section->size());\n    this->data_directory(DATA_DIRECTORY::TLS_TABLE).section_ = new_section;\n  }\n\n\n  if (this->sections_.size() >= std::numeric_limits<uint16_t>::max()) {\n    throw pe_error(\"Binary reachs its maximum number of sections\");\n  }\n\n  this->available_sections_space_--;\n  this->sections_.push_back(new_section);\n\n  \/\/ Update headers\n  this->header().numberof_sections(static_cast<uint16_t>(this->sections_.size()));\n\n  this->optional_header().sizeof_image(this->virtual_size());\n  this->optional_header().sizeof_headers(this->sizeof_headers());\n  return *(this->sections_.back());\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Methods to manage relocations\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nit_relocations Binary::relocations(void) {\n  return this->relocations_;\n}\n\n\nit_const_relocations Binary::relocations(void) const {\n  return this->relocations_;\n}\n\n\nRelocation& Binary::add_relocation(const Relocation& relocation) {\n  Relocation* newone = new Relocation{relocation};\n  this->relocations_.push_back(newone);\n  return *newone;\n}\n\n\n\/\/void Binary::remove_relocation(std::vector<Relocation>::iterator it) {\n\/\/  this->relocations_.erase(it);\n\/\/}\n\n\nvoid Binary::remove_all_relocations(void) {\n  for (Relocation* r : this->relocations_) {\n    delete r;\n  }\n  this->relocations_.clear();\n}\n\n\nLIEF::relocations_t Binary::get_abstract_relocations(void) {\n  LIEF::relocations_t abstract_relocs;\n  for (Relocation& relocation : this->relocations()) {\n    for (RelocationEntry& entry : relocation.entries()) {\n      abstract_relocs.push_back(&entry);\n    }\n  }\n  return abstract_relocs;\n}\n\n\/\/ Imports\n\/\/ =======\n\nit_imports Binary::imports(void) {\n  return {this->imports_};\n}\n\nit_const_imports Binary::imports(void) const {\n  return {this->imports_};\n}\n\nImportEntry& Binary::add_import_function(const std::string& library, const std::string& function) {\n  auto&& it_import = std::find_if(\n      std::begin(this->imports_),\n      std::end(this->imports_),\n      [&library] (const Import& import)\n      {\n        return import.name() == library;\n      });\n\n  if (it_import == std::end(this->imports_)) {\n    \/\/TODO: add the library\n    throw not_found(\"The library doesn't exist\");\n  }\n\n  it_import->add_entry({function});\n  return it_import->get_entry(function);\n}\n\nImport& Binary::add_library(const std::string& name) {\n  this->imports_.emplace_back(name);\n  if (this->imports_.size() > 0) {\n    this->has_imports_ = true;\n  }\n  return this->imports_.back();\n}\n\nvoid Binary::remove_library(const std::string&) {\n  throw LIEF::not_implemented(\"To implement\");\n}\n\nvoid Binary::remove_all_libraries(void) {\n  this->imports_ = {};\n}\n\nuint32_t Binary::predict_function_rva(const std::string& library, const std::string& function) {\n\n  auto&& it_import = std::find_if(\n      this->imports_.cbegin(),\n      this->imports_.cend(),\n      [&library] (const Import& imp) {\n        return imp.name() == library;\n      });\n\n  if (it_import == std::end(this->imports_)) {\n    LIEF_ERR(\"Unable to find library {}\", library);\n    return 0;\n  }\n\n  it_const_import_entries entries = it_import->entries();\n\n  \/\/ Some weird library define a function twice\n  size_t nb_functions = std::count_if(\n      entries.cbegin(),\n      entries.cend(),\n      [&function](const ImportEntry& entry )\n      {\n        return not entry.is_ordinal() and entry.name() == function;\n      });\n\n  if (nb_functions == 0) {\n    LIEF_ERR(\"Unable to find the function '{}' in '{}'\", function, library);\n    return 0;\n  }\n\n  if (nb_functions > 1) {\n    LIEF_ERR(\"{} is defined #{:d} times in {}\", function, nb_functions, library);\n    return 0;\n  }\n\n  uint32_t import_table_size = static_cast<uint32_t>((this->imports().size() + 1) * sizeof(pe_import)); \/\/ +1 for the null entry\n\n  uint32_t address = import_table_size;\n\n  uint32_t lookup_table_size = 0;\n  for (const Import& f : this->imports_) {\n    if (this->type_ == PE_TYPE::PE32) {\n      lookup_table_size += (f.entries().size() + 1) * sizeof(uint32_t);\n    } else {\n      lookup_table_size += (f.entries().size() + 1) * sizeof(uint64_t);\n    }\n  }\n\n  address += lookup_table_size;\n\n  for (auto&& it_imp = this->imports_.cbegin();\n      (it_imp->name() != library and it_imp != this->imports_.cend());\n       ++it_imp) {\n    if (this->type_ == PE_TYPE::PE32) {\n      address += sizeof(uint32_t) * (it_imp->entries().size() + 1);\n    } else {\n      address += sizeof(uint64_t) * (it_imp->entries().size() + 1);\n    }\n  }\n\n\n  for (auto&& it_func = entries.cbegin();\n      (it_func->name() != function and it_func != entries.cend());\n       ++it_func) {\n    if (this->type_ == PE_TYPE::PE32) {\n      address += sizeof(uint32_t);\n    } else {\n      address += sizeof(uint64_t);\n    }\n  }\n\n\n  \/\/ We assume the the idata section will be the last section\n  const uint64_t next_virtual_address = align(std::accumulate(\n      std::begin(this->sections_),\n      std::end(this->sections_), this->optional_header().section_alignment(),\n      [] (uint64_t va, const Section* s) {\n        return std::max<uint64_t>(s->virtual_address() + s->virtual_size(), va);\n      }), this->optional_header().section_alignment());\n\n  return next_virtual_address + address;\n}\n\n\nbool Binary::has_import(const std::string& import_name) const {\n\n  auto&& it_import = std::find_if(\n      std::begin(this->imports_),\n      std::end(this->imports_),\n      [&import_name] (const Import& import) {\n        return import.name() == import_name;\n      });\n\n  return it_import != std::end(this->imports_);\n}\n\n\nImport& Binary::get_import(const std::string& import_name) {\n  return const_cast<Import&>(static_cast<const Binary*>(this)->get_import(import_name));\n}\n\nconst Import& Binary::get_import(const std::string& import_name) const {\n\n  if (not this->has_import(import_name)) {\n    throw not_found(\"Unable to find the '\" + import_name + \"' library\");\n  }\n\n  auto&& it_import = std::find_if(\n      std::begin(this->imports_),\n      std::end(this->imports_),\n      [&import_name] (const Import& import) {\n        return import.name() == import_name;\n      });\n\n  return *it_import;\n}\n\n\nExport& Binary::get_export(void) {\n  return const_cast<Export&>(static_cast<const Binary*>(this)->get_export());\n}\n\n\nconst Export& Binary::get_export(void) const {\n  return this->export_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Methods to manage Resources\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Binary::set_resources(const ResourceDirectory& resource) {\n  delete this->resources_;\n  this->resources_ = new ResourceDirectory{resource};\n}\n\n\nvoid Binary::set_resources(const ResourceData& resource) {\n  delete this->resources_;\n  this->resources_ = new ResourceData{resource};\n}\n\nResourceNode& Binary::resources(void) {\n  return const_cast<ResourceNode&>(static_cast<const Binary*>(this)->resources());\n}\n\nconst ResourceNode& Binary::resources(void) const {\n  if (this->resources_ != nullptr) {\n    return *this->resources_;\n  } else {\n    throw not_found(\"No resources\");\n  }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Methods to manage DataDirectories\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nit_data_directories Binary::data_directories(void) {\n  return it_data_directories{this->data_directories_};\n}\n\nit_const_data_directories Binary::data_directories(void) const {\n  return it_const_data_directories{this->data_directories_};\n}\n\n\ndebug_entries_t& Binary::debug(void) {\n  return const_cast<debug_entries_t&>(static_cast<const Binary*>(this)->debug());\n}\n\n\nconst debug_entries_t& Binary::debug(void) const {\n  return this->debug_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Various methods\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nit_const_signatures Binary::signatures(void) const {\n  return this->signatures_;\n}\n\nstd::vector<uint8_t> Binary::authentihash(ALGORITHMS algo) const {\n  static const std::map<ALGORITHMS, hashstream::HASH> HMAP = {\n    {ALGORITHMS::MD5,     hashstream::HASH::MD5},\n    {ALGORITHMS::SHA_1,   hashstream::HASH::SHA1},\n    {ALGORITHMS::SHA_256, hashstream::HASH::SHA256},\n    {ALGORITHMS::SHA_384, hashstream::HASH::SHA384},\n    {ALGORITHMS::SHA_512, hashstream::HASH::SHA512},\n  };\n  auto it_hash = HMAP.find(algo);\n  if (it_hash == std::end(HMAP)) {\n    LIEF_WARN(\"Unsupported hash algorithm: {}\", to_string(algo));\n    return {};\n  }\n  const size_t sizeof_ptr = this->type_ == PE_TYPE::PE32 ? sizeof(uint32_t) : sizeof(uint64_t);\n  const hashstream::HASH hash_type = it_hash->second;\n  hashstream ios(hash_type);\n  \/\/vector_iostream ios;\n  ios \/\/ Hash dos header\n    .write(this->dos_header_.magic())\n    .write(this->dos_header_.used_bytes_in_the_last_page())\n    .write(this->dos_header_.file_size_in_pages())\n    .write(this->dos_header_.numberof_relocation())\n    .write(this->dos_header_.header_size_in_paragraphs())\n    .write(this->dos_header_.minimum_extra_paragraphs())\n    .write(this->dos_header_.maximum_extra_paragraphs())\n    .write(this->dos_header_.initial_relative_ss())\n    .write(this->dos_header_.initial_sp())\n    .write(this->dos_header_.checksum())\n    .write(this->dos_header_.initial_ip())\n    .write(this->dos_header_.initial_relative_cs())\n    .write(this->dos_header_.addressof_relocation_table())\n    .write(this->dos_header_.overlay_number())\n    .write(this->dos_header_.reserved())\n    .write(this->dos_header_.oem_id())\n    .write(this->dos_header_.oem_info())\n    .write(this->dos_header_.reserved2())\n    .write(this->dos_header_.addressof_new_exeheader())\n    .write(this->dos_stub_);\n\n  ios \/\/ Hash PE Header\n    .write(this->header_.signature())\n    .write(static_cast<uint16_t>(this->header_.machine()))\n    .write(this->header_.numberof_sections())\n    .write(this->header_.time_date_stamp())\n    .write(this->header_.pointerto_symbol_table())\n    .write(this->header_.numberof_symbols())\n    .write(this->header_.sizeof_optional_header())\n    .write(static_cast<uint16_t>(this->header_.characteristics()));\n\n  ios \/\/ Hash OptionalHeader\n    .write(static_cast<uint16_t>(this->optional_header_.magic()))\n    .write(this->optional_header_.major_linker_version())\n    .write(this->optional_header_.minor_linker_version())\n    .write(this->optional_header_.sizeof_code())\n    .write(this->optional_header_.sizeof_initialized_data())\n    .write(this->optional_header_.sizeof_uninitialized_data())\n    .write(this->optional_header_.addressof_entrypoint())\n    .write(this->optional_header_.baseof_code());\n\n  if (this->type_ == PE_TYPE::PE32) {\n    ios.write(this->optional_header_.baseof_data());\n  }\n  ios \/\/ Continuation of optional header\n    .write_sized_int(this->optional_header_.imagebase(), sizeof_ptr)\n    .write(this->optional_header_.section_alignment())\n    .write(this->optional_header_.file_alignment())\n    .write(this->optional_header_.major_operating_system_version())\n    .write(this->optional_header_.minor_operating_system_version())\n    .write(this->optional_header_.major_image_version())\n    .write(this->optional_header_.minor_image_version())\n    .write(this->optional_header_.major_subsystem_version())\n    .write(this->optional_header_.minor_subsystem_version())\n    .write(this->optional_header_.win32_version_value())\n    .write(this->optional_header_.sizeof_image())\n    .write(this->optional_header_.sizeof_headers())\n    \/\/ this->optional_header_.checksum()) is not a part of the hash\n    .write(static_cast<uint16_t>(this->optional_header_.subsystem()))\n    .write(static_cast<uint16_t>(this->optional_header_.dll_characteristics()))\n    .write_sized_int(this->optional_header_.sizeof_stack_reserve(), sizeof_ptr)\n    .write_sized_int(this->optional_header_.sizeof_stack_commit(), sizeof_ptr)\n    .write_sized_int(this->optional_header_.sizeof_heap_reserve(), sizeof_ptr)\n    .write_sized_int(this->optional_header_.sizeof_heap_commit(), sizeof_ptr)\n    .write(this->optional_header_.loader_flags())\n    .write(this->optional_header_.numberof_rva_and_size());\n\n  for (const DataDirectory* dir : this->data_directories_) {\n    if (dir->type() == DATA_DIRECTORY::CERTIFICATE_TABLE) {\n      continue;\n    }\n    ios\n      .write(dir->RVA())\n      .write(dir->size());\n  }\n\n  \/\/ Empty data directory\n  ios\n    .write<uint32_t>(0)\n    .write<uint32_t>(0);\n\n  for (const Section* sec : this->sections_) {\n    std::array<char, 8> name = {0};\n    const std::string& sec_name = sec->name();\n    uint32_t name_length = std::min<uint32_t>(sec_name.size() + 1, sizeof(name));\n    std::copy(sec_name.c_str(), sec_name.c_str() + name_length, std::begin(name));\n    ios\n      .write(name)\n      .write(sec->virtual_size())\n      .write<uint32_t>(sec->virtual_address())\n      .write(sec->sizeof_raw_data())\n      .write(sec->pointerto_raw_data())\n      .write(sec->pointerto_relocation())\n      .write(sec->pointerto_line_numbers())\n      .write(sec->numberof_relocations())\n      .write(sec->numberof_line_numbers())\n      .write(static_cast<uint32_t>(sec->characteristics()));\n  }\n  \/\/LIEF_DEBUG(\"Section padding at 0x{:x}\", ios.tellp());\n  ios.write(this->section_offset_padding_);\n\n  std::vector<Section*> sections = this->sections_;\n\n  \/\/ Sort by file offset\n  std::sort(\n      std::begin(sections),\n      std::end(sections),\n      [] (const Section* lhs, const Section* rhs) {\n        return  lhs->pointerto_raw_data() < rhs->pointerto_raw_data();\n    });\n\n  uint64_t position = 0;\n  for (const Section* sec : sections) {\n    const std::vector<uint8_t>& pad     = sec->padding();\n    const std::vector<uint8_t>& content = sec->content();\n    LIEF_DEBUG(\"Authentihash:  Append section {:<8}: [0x{:04x}, 0x{:04x}] + [0x{:04x}] = [0x{:04x}, 0x{:04x}]\",\n        sec->name(),\n        sec->offset(), sec->offset() + content.size(), pad.size(),\n        sec->offset(), sec->offset() + content.size() + pad.size());\n    if (\/* overlapping *\/ sec->offset() < position) {\n      \/\/ Trunc the beginning of the overlap\n      if (position <= sec->offset() + content.size()) {\n        const uint64_t start_p = position - sec->offset();\n        const uint64_t size = content.size() - start_p;\n        ios\n          .write(content.data() + start_p, size)\n          .write(pad);\n      } else {\n        LIEF_WARN(\"Overlapping in the padding area\");\n      }\n    } else {\n      ios\n        .write(content)\n        .write(pad);\n    }\n    position = sec->offset() + content.size() + pad.size();\n  }\n  if (this->overlay_.size() > 0) {\n    const DataDirectory& cert_dir = this->data_directory(DATA_DIRECTORY::CERTIFICATE_TABLE);\n    LIEF_DEBUG(\"Add overlay and omit 0x{:08x} - 0x{:08x}\", cert_dir.RVA(), cert_dir.RVA() + cert_dir.size());\n    if (cert_dir.RVA() > 0 and cert_dir.size() > 0) {\n      const uint64_t start_cert_offset = cert_dir.RVA() - this->overlay_offset_;\n      const uint64_t end_cert_offset   = start_cert_offset + cert_dir.size();\n      LIEF_DEBUG(\"Add [0x{:x}, 0x{:x}]\", this->overlay_offset_, this->overlay_offset_ + start_cert_offset);\n      LIEF_DEBUG(\"Add [0x{:x}, 0x{:x}]\",\n          this->overlay_offset_ + end_cert_offset, this->overlay_offset_ + this->overlay_.size() - end_cert_offset);\n      ios\n        .write(this->overlay_.data(), start_cert_offset)\n        .write(this->overlay_.data() + end_cert_offset, this->overlay_.size() - end_cert_offset);\n    }\n  }\n  \/\/ios.write(this->overlay_);\n  \/\/ When something gets wrong with the hash:\n  \/\/ std::vector<uint8_t> out = ios.raw();\n  \/\/ std::ofstream output_file{\"\/tmp\/hash.blob\", std::ios::out | std::ios::binary | std::ios::trunc};\n  \/\/ if (output_file) {\n  \/\/   std::copy(\n  \/\/       std::begin(out),\n  \/\/       std::end(out),\n  \/\/       std::ostreambuf_iterator<char>(output_file));\n  \/\/ }\n  \/\/ std::vector<uint8_t> hash = hashstream(hash_type).write(out).raw();\n\n  std::vector<uint8_t> hash = ios.raw();\n  LIEF_DEBUG(\"{}\", hex_dump(hash));\n  return hash;\n}\n\nSignature::VERIFICATION_FLAGS Binary::verify_signature(Signature::VERIFICATION_CHECKS checks) const {\n  if (not this->has_signatures()) {\n    return Signature::VERIFICATION_FLAGS::NO_SIGNATURE;\n  }\n\n  for (size_t i = 0; i < this->signatures_.size(); ++i) {\n    const Signature& sig = this->signatures_[i];\n    Signature::VERIFICATION_FLAGS flags = this->verify_signature(sig, checks);\n    if (flags != Signature::VERIFICATION_FLAGS::OK) {\n      LIEF_INFO(\"Verification failed for signature #{:d} (0b{:b})\", i, static_cast<uintptr_t>(flags));\n      return flags;\n    }\n  }\n  return Signature::VERIFICATION_FLAGS::OK;\n}\n\nSignature::VERIFICATION_FLAGS Binary::verify_signature(const Signature& sig, Signature::VERIFICATION_CHECKS checks) const {\n  if (not is_true(checks & Signature::VERIFICATION_CHECKS::HASH_ONLY)) {\n    const Signature::VERIFICATION_FLAGS value = sig.check(checks);\n    if (value != Signature::VERIFICATION_FLAGS::OK) {\n      LIEF_INFO(\"Bad signature (0b{:b})\", static_cast<uintptr_t>(value));\n      return value;\n    }\n  }\n\n  \/\/ Check that the authentihash matches Content Info's digest\n  const std::vector<uint8_t>& authhash = this->authentihash(sig.digest_algorithm());\n  const std::vector<uint8_t>& chash = sig.content_info().digest();\n  if (authhash != chash) {\n    LIEF_INFO(\"Authentihash and Content info's digest does not match:\\n  {}\\n  {}\",\n        hex_dump(authhash), hex_dump(chash));\n    return Signature::VERIFICATION_FLAGS::BAD_SIGNATURE;\n  }\n  return Signature::VERIFICATION_FLAGS::OK;\n}\n\n\nstd::vector<Symbol>& Binary::symbols(void) {\n  return const_cast<std::vector<Symbol>&>(static_cast<const Binary*>(this)->symbols());\n}\n\n\nconst std::vector<Symbol>& Binary::symbols(void) const {\n  return this->symbols_;\n}\n\n\nLIEF::Binary::functions_t Binary::get_abstract_exported_functions(void) const {\n  LIEF::Binary::functions_t result;\n  if (this->has_exports()) {\n    for (const ExportEntry& entry : this->get_export().entries()) {\n      const std::string& name = entry.name();\n      if(not name.empty()) {\n        result.emplace_back(name, entry.address(), Function::flags_list_t{Function::FLAGS::EXPORTED});\n      }\n    }\n  }\n  return result;\n}\n\nLIEF::Binary::functions_t Binary::get_abstract_imported_functions(void) const {\n  LIEF::Binary::functions_t result;\n  if (this->has_imports()) {\n    for (const Import& import : this->imports()) {\n      const Import& resolved = resolve_ordinals(import);\n      for (const ImportEntry& entry : resolved.entries()) {\n        const std::string& name = entry.name();\n        if(not name.empty()) {\n          result.emplace_back(name, entry.iat_address(), Function::flags_list_t{Function::FLAGS::IMPORTED});\n        }\n      }\n    }\n  }\n  return result;\n}\n\n\nstd::vector<std::string> Binary::get_abstract_imported_libraries(void) const {\n  std::vector<std::string> result;\n  for (const Import& import : this->imports()) {\n    result.push_back(import.name());\n  }\n  return result;\n}\n\nLIEF::Header Binary::get_abstract_header(void) const {\n  LIEF::Header header;\n\n  try {\n    const std::pair<ARCHITECTURES, std::set<MODES>>& am = arch_pe_to_lief.at(this->header().machine());\n    header.architecture(am.first);\n    header.modes(am.second);\n  } catch (const std::out_of_range&) {\n    throw not_implemented(to_string(this->header().machine()));\n  }\n\n  header.entrypoint(this->entrypoint());\n\n  if (this->header().has_characteristic(HEADER_CHARACTERISTICS::IMAGE_FILE_DLL)) {\n    header.object_type(OBJECT_TYPES::TYPE_LIBRARY);\n  } else if (this->header().has_characteristic(HEADER_CHARACTERISTICS::IMAGE_FILE_EXECUTABLE_IMAGE)) {\n    header.object_type(OBJECT_TYPES::TYPE_EXECUTABLE);\n  } else {\n    header.object_type(OBJECT_TYPES::TYPE_NONE);\n  }\n\n  try {\n    ENDIANNESS endianness = arch_pe_to_endi_lief.at(this->header().machine());\n    header.endianness(endianness);\n  } catch (const std::out_of_range&) {\n    throw not_implemented(\"Endianness not found for \" + std::string(to_string(this->header().machine())));\n  }\n\n  return header;\n}\n\n\n\nvoid Binary::hook_function(const std::string& function, uint64_t address) {\n\n  for (const Import& import : this->imports_) {\n    for (const ImportEntry& import_entry : import.entries()) {\n      if (import_entry.name() == function) {\n        return hook_function(import.name(), function, address);\n      }\n    }\n  }\n\n  LIEF_WARN(\"Unable to find library associated with function '{}'\", function);\n}\n\n\nvoid Binary::hook_function(const std::string& library, const std::string& function, uint64_t address) {\n  this->hooks_[library][function] = address;\n}\n\n\/\/ LIEF Interface\n\/\/ ==============\nuint64_t Binary::entrypoint(void) const {\n  return this->optional_header().imagebase() + this->optional_header().addressof_entrypoint();\n}\n\nvoid Binary::patch_address(uint64_t address, const std::vector<uint8_t>& patch_value, LIEF::Binary::VA_TYPES addr_type) {\n  uint64_t rva = address;\n\n  if (addr_type == LIEF::Binary::VA_TYPES::VA or addr_type == LIEF::Binary::VA_TYPES::AUTO) {\n    const int64_t delta = address - this->optional_header().imagebase();\n\n    if (delta > 0 or addr_type == LIEF::Binary::VA_TYPES::VA) {\n      rva -= this->optional_header().imagebase();\n    }\n  }\n\n  \/\/ Find the section associated with the virtual address\n  Section& section_topatch = this->section_from_rva(rva);\n  const uint64_t offset = rva - section_topatch.virtual_address();\n  std::vector<uint8_t>& content = section_topatch.content_ref();\n  std::copy(\n      std::begin(patch_value),\n      std::end(patch_value),\n      content.data() + offset);\n\n}\n\nvoid Binary::patch_address(uint64_t address, uint64_t patch_value, size_t size, LIEF::Binary::VA_TYPES addr_type) {\n  if (size > sizeof(patch_value)) {\n    LIEF_ERR(\"Invalid size (0x{:x})\", size);\n    return;\n  }\n\n  uint64_t rva = address;\n\n  if (addr_type == LIEF::Binary::VA_TYPES::VA or addr_type == LIEF::Binary::VA_TYPES::AUTO) {\n    const int64_t delta = address - this->optional_header().imagebase();\n\n    if (delta > 0 or addr_type == LIEF::Binary::VA_TYPES::VA) {\n      rva -= this->optional_header().imagebase();\n    }\n  }\n\n  Section& section_topatch = this->section_from_rva(rva);\n  const uint64_t offset = rva - section_topatch.virtual_address();\n  std::vector<uint8_t>& content = section_topatch.content_ref();\n\n  std::copy(\n      reinterpret_cast<uint8_t*>(&patch_value),\n      reinterpret_cast<uint8_t*>(&patch_value) + size,\n      content.data() + offset);\n\n}\n\nstd::vector<uint8_t> Binary::get_content_from_virtual_address(uint64_t virtual_address, uint64_t size, LIEF::Binary::VA_TYPES addr_type) const {\n  uint64_t rva = virtual_address;\n\n  if (addr_type == LIEF::Binary::VA_TYPES::VA or addr_type == LIEF::Binary::VA_TYPES::AUTO) {\n    const int64_t delta = virtual_address - this->optional_header().imagebase();\n\n    if (delta > 0 or addr_type == LIEF::Binary::VA_TYPES::VA) {\n      rva -= this->optional_header().imagebase();\n    }\n  }\n  const Section& section = this->section_from_rva(rva);\n  std::vector<uint8_t> content = section.content();\n  const uint64_t offset = rva - section.virtual_address();\n  uint64_t checked_size = size;\n  if ((offset + checked_size) > content.size()) {\n    checked_size = checked_size - (offset + checked_size - content.size());\n  }\n\n  return {content.data() + offset, content.data() + offset + checked_size};\n\n}\n\nbool Binary::is_pie(void) const {\n  return this->optional_header().has(DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE);\n}\n\nbool Binary::has_nx(void) const {\n  return this->optional_header().has(DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_NX_COMPAT);\n}\n\n\/\/ Overlay\n\/\/ =======\n\nconst std::vector<uint8_t>& Binary::overlay(void) const {\n  return this->overlay_;\n}\n\nstd::vector<uint8_t>& Binary::overlay(void) {\n  return const_cast<std::vector<uint8_t>&>(static_cast<const Binary*>(this)->overlay());\n}\n\n\/\/ Dos stub\n\/\/ ========\n\nconst std::vector<uint8_t>& Binary::dos_stub(void) const {\n  return this->dos_stub_;\n}\n\nstd::vector<uint8_t>& Binary::dos_stub(void) {\n  return const_cast<std::vector<uint8_t>&>(static_cast<const Binary*>(this)->dos_stub());\n}\n\n\nvoid Binary::dos_stub(const std::vector<uint8_t>& content) {\n  this->dos_stub_ = content;\n}\n\n\/\/ Rich Header\n\/\/ -----------\nRichHeader& Binary::rich_header(void) {\n  return const_cast<RichHeader&>(static_cast<const Binary*>(this)->rich_header());\n}\n\nconst RichHeader& Binary::rich_header(void) const {\n  return this->rich_header_;\n}\n\nvoid Binary::rich_header(const RichHeader& rich_header) {\n  this->rich_header_ = rich_header;\n  this->has_rich_header_ = true;\n}\n\n\/\/ Resource manager\n\/\/ ===============\n\nResourcesManager Binary::resources_manager(void) {\n  if (this->resources_ == nullptr or not this->has_resources()) {\n    throw not_found(\"There is no resources in the binary\");\n  }\n  return ResourcesManager{this->resources_};\n}\n\nconst ResourcesManager Binary::resources_manager(void) const {\n  if (this->resources_ == nullptr or not this->has_resources()) {\n    throw not_found(\"There is no resources in the binary\");\n  }\n  return ResourcesManager{this->resources_};\n}\n\n\nLIEF::Binary::functions_t Binary::ctor_functions(void) const {\n  LIEF::Binary::functions_t functions;\n\n  if (this->has_tls()) {\n    const std::vector<uint64_t>& clbs = this->tls().callbacks();\n    for (size_t i = 0; i < clbs.size(); ++i) {\n      functions.emplace_back(\n          \"tls_\" + std::to_string(i),\n          clbs[i],\n          Function::flags_list_t{Function::FLAGS::CONSTRUCTOR});\n\n    }\n  }\n  return functions;\n}\n\n\nLIEF::Binary::functions_t Binary::functions(void) const {\n\n  static const auto func_cmd = [] (const Function& lhs, const Function& rhs) {\n    return lhs.address() < rhs.address();\n  };\n  std::set<Function, decltype(func_cmd)> functions_set(func_cmd);\n\n  LIEF::Binary::functions_t exception_functions = this->exception_functions();\n  LIEF::Binary::functions_t exported            = this->get_abstract_exported_functions();\n  LIEF::Binary::functions_t ctors               = this->ctor_functions();\n\n  std::move(\n      std::begin(exception_functions),\n      std::end(exception_functions),\n      std::inserter(functions_set, std::end(functions_set)));\n\n  std::move(\n      std::begin(exported),\n      std::end(exported),\n      std::inserter(functions_set, std::end(functions_set)));\n\n  std::move(\n      std::begin(ctors),\n      std::end(ctors),\n      std::inserter(functions_set, std::end(functions_set)));\n\n  return {std::begin(functions_set), std::end(functions_set)};\n}\n\nLIEF::Binary::functions_t Binary::exception_functions(void) const {\n  LIEF::Binary::functions_t functions;\n  if (not this->has_exceptions()) {\n    return functions;\n  }\n\n\n  const DataDirectory& exception_dir = this->data_directory(DATA_DIRECTORY::EXCEPTION_TABLE);\n  std::vector<uint8_t> exception_data = this->get_content_from_virtual_address(exception_dir.RVA(), exception_dir.size());\n  VectorStream vs{std::move(exception_data)};\n  const size_t nb_entries = vs.size() \/ sizeof(pe_exception_entry_x64); \/\/ TODO: Handle other architectures\n\n  for (size_t i = 0; i < nb_entries; ++i) {\n    if (not vs.can_read<pe_exception_entry_x64>()) {\n      LIEF_ERR(\"Corrupted entry #{:02d}\", i);\n      break;\n    }\n    const pe_exception_entry_x64& entry = vs.read<pe_exception_entry_x64>();\n    Function f{entry.address_start_rva};\n    if (entry.address_end_rva > entry.address_start_rva) {\n      f.size(entry.address_end_rva - entry.address_start_rva);\n    }\n    functions.push_back(std::move(f));\n  }\n  return functions;\n}\n\n\nvoid Binary::accept(Visitor& visitor) const {\n  visitor.visit(*this);\n}\n\n\nbool Binary::operator==(const Binary& rhs) const {\n  size_t hash_lhs = Hash::hash(*this);\n  size_t hash_rhs = Hash::hash(rhs);\n  return hash_lhs == hash_rhs;\n}\n\nbool Binary::operator!=(const Binary& rhs) const {\n  return not (*this == rhs);\n}\n\n\nstd::ostream& Binary::print(std::ostream& os) const {\n\n  os << \"Dos Header\" << std::endl;\n  os << \"==========\" << std::endl;\n\n  os << this->dos_header();\n  os << std::endl;\n\n\n  if (this->has_rich_header()) {\n    os << \"Rich Header\" << std::endl;\n    os << \"===========\" << std::endl;\n    os << this->rich_header() << std::endl;\n    os << std::endl;\n  }\n\n\n  os << \"Header\" << std::endl;\n  os << \"======\" << std::endl;\n\n  os << this->header();\n  os << std::endl;\n\n\n  os << \"Optional Header\" << std::endl;\n  os << \"===============\" << std::endl;\n\n  os << this->optional_header();\n  os << std::endl;\n\n\n  os << \"Data directories\" << std::endl;\n  os << \"================\" << std::endl;\n\n  for (const DataDirectory& data_directory : this->data_directories()) {\n    os << data_directory << std::endl;\n  }\n  os << std::endl;\n\n\n  os << \"Sections\" << std::endl;\n  os << \"========\" << std::endl;\n\n  for (const Section& section : this->sections()) {\n    os << section << std::endl;;\n  }\n  os << std::endl;\n\n\n  if (this->has_tls()) {\n    os << \"TLS\" << std::endl;\n    os << \"===\" << std::endl;\n    os << this->tls() << std::endl;\n    os << std::endl;\n  }\n\n\n  if (this->has_signatures()) {\n    os << \"Signatures\" << std::endl;\n    os << \"==========\" << std::endl;\n    for (const Signature& sig : this->signatures_) {\n      os << sig << std::endl;\n    }\n    os << std::endl;\n  }\n\n\n  if (this->has_imports()) {\n    os << \"Imports\" << std::endl;\n    os << \"=======\" << std::endl;\n    for (const Import& import : this->imports()) {\n      os << import << std::endl;\n    }\n    os << std::endl;\n  }\n\n\n  if (this->has_debug()) {\n    os << \"Debug\" << std::endl;\n    os << \"=====\" << std::endl;\n    for (const Debug& debug : this->debug()) {\n      os << debug << std::endl;\n    }\n    os << std::endl;\n  }\n\n\n  if (this->has_relocations()) {\n    os << \"Relocations\" << std::endl;\n    os << \"===========\" << std::endl;\n    for (const Relocation& relocation : this->relocations()) {\n      os << relocation << std::endl;\n    }\n    os << std::endl;\n  }\n\n\n  if (this->has_exports()) {\n    os << \"Export\" << std::endl;\n    os << \"======\" << std::endl;\n    os << this->get_export() << std::endl;\n    os << std::endl;\n  }\n\n\n  if (this->has_resources()) {\n    os << \"Resources\" << std::endl;\n    os << \"=========\" << std::endl;\n    os << this->resources_manager() << std::endl;\n    os << std::endl;\n  }\n\n  os << \"Symbols\" << std::endl;\n  os << \"=======\" << std::endl;\n\n  for (const Symbol& symbol : this->symbols()) {\n    os << symbol << std::endl;;\n  }\n  os << std::endl;\n\n\n  if (this->has_configuration()) {\n    os << \"Load Configuration\" << std::endl;\n    os << \"==================\" << std::endl;\n\n    os << this->load_configuration();\n\n    os << std::endl;\n  }\n\n\n\n  return os;\n}\n\n} \/\/ namesapce PE\n} \/\/ namespace LIEF\n","avg_line_length":31.6339754816,"max_line_length":152,"alphanum_fraction":0.6839764528,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":277,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":50.0,"content":"#include \"sai_vs.h\"\n\nVS_GENERIC_QUAD(ROUTER_INTERFACE,router_interface);\nVS_GENERIC_STATS(ROUTER_INTERFACE,router_interface);\n\nconst sai_router_interface_api_t vs_router_interface_api = {\n\n    VS_GENERIC_QUAD_API(router_interface)\n    VS_GENERIC_STATS_API(router_interface)\n};\n","avg_line_length":25.1818181818,"max_line_length":60,"alphanum_fraction":0.844765343,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4659,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <tencentcloud\/gaap\/v20180529\/model\/ProxySimpleInfo.h>\n\nusing TencentCloud::CoreInternalOutcome;\nusing namespace TencentCloud::Gaap::V20180529::Model;\nusing namespace rapidjson;\nusing namespace std;\n\nProxySimpleInfo::ProxySimpleInfo() :\n    m_proxyIdHasBeenSet(false),\n    m_proxyNameHasBeenSet(false),\n    m_listenerListHasBeenSet(false)\n{\n}\n\nCoreInternalOutcome ProxySimpleInfo::Deserialize(const Value &value)\n{\n    string requestId = \"\";\n\n\n    if (value.HasMember(\"ProxyId\") && !value[\"ProxyId\"].IsNull())\n    {\n        if (!value[\"ProxyId\"].IsString())\n        {\n            return CoreInternalOutcome(Error(\"response `ProxySimpleInfo.ProxyId` IsString=false incorrectly\").SetRequestId(requestId));\n        }\n        m_proxyId = string(value[\"ProxyId\"].GetString());\n        m_proxyIdHasBeenSet = true;\n    }\n\n    if (value.HasMember(\"ProxyName\") && !value[\"ProxyName\"].IsNull())\n    {\n        if (!value[\"ProxyName\"].IsString())\n        {\n            return CoreInternalOutcome(Error(\"response `ProxySimpleInfo.ProxyName` IsString=false incorrectly\").SetRequestId(requestId));\n        }\n        m_proxyName = string(value[\"ProxyName\"].GetString());\n        m_proxyNameHasBeenSet = true;\n    }\n\n    if (value.HasMember(\"ListenerList\") && !value[\"ListenerList\"].IsNull())\n    {\n        if (!value[\"ListenerList\"].IsArray())\n            return CoreInternalOutcome(Error(\"response `ProxySimpleInfo.ListenerList` is not array type\"));\n\n        const Value &tmpValue = value[\"ListenerList\"];\n        for (Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)\n        {\n            ListenerInfo item;\n            CoreInternalOutcome outcome = item.Deserialize(*itr);\n            if (!outcome.IsSuccess())\n            {\n                outcome.GetError().SetRequestId(requestId);\n                return outcome;\n            }\n            m_listenerList.push_back(item);\n        }\n        m_listenerListHasBeenSet = true;\n    }\n\n\n    return CoreInternalOutcome(true);\n}\n\nvoid ProxySimpleInfo::ToJsonObject(Value &value, Document::AllocatorType& allocator) const\n{\n\n    if (m_proxyIdHasBeenSet)\n    {\n        Value iKey(kStringType);\n        string key = \"ProxyId\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, Value(m_proxyId.c_str(), allocator).Move(), allocator);\n    }\n\n    if (m_proxyNameHasBeenSet)\n    {\n        Value iKey(kStringType);\n        string key = \"ProxyName\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, Value(m_proxyName.c_str(), allocator).Move(), allocator);\n    }\n\n    if (m_listenerListHasBeenSet)\n    {\n        Value iKey(kStringType);\n        string key = \"ListenerList\";\n        iKey.SetString(key.c_str(), allocator);\n        value.AddMember(iKey, Value(kArrayType).Move(), allocator);\n\n        int i=0;\n        for (auto itr = m_listenerList.begin(); itr != m_listenerList.end(); ++itr, ++i)\n        {\n            value[key.c_str()].PushBack(Value(kObjectType).Move(), allocator);\n            (*itr).ToJsonObject(value[key.c_str()][i], allocator);\n        }\n    }\n\n}\n\n\nstring ProxySimpleInfo::GetProxyId() const\n{\n    return m_proxyId;\n}\n\nvoid ProxySimpleInfo::SetProxyId(const string& _proxyId)\n{\n    m_proxyId = _proxyId;\n    m_proxyIdHasBeenSet = true;\n}\n\nbool ProxySimpleInfo::ProxyIdHasBeenSet() const\n{\n    return m_proxyIdHasBeenSet;\n}\n\nstring ProxySimpleInfo::GetProxyName() const\n{\n    return m_proxyName;\n}\n\nvoid ProxySimpleInfo::SetProxyName(const string& _proxyName)\n{\n    m_proxyName = _proxyName;\n    m_proxyNameHasBeenSet = true;\n}\n\nbool ProxySimpleInfo::ProxyNameHasBeenSet() const\n{\n    return m_proxyNameHasBeenSet;\n}\n\nvector<ListenerInfo> ProxySimpleInfo::GetListenerList() const\n{\n    return m_listenerList;\n}\n\nvoid ProxySimpleInfo::SetListenerList(const vector<ListenerInfo>& _listenerList)\n{\n    m_listenerList = _listenerList;\n    m_listenerListHasBeenSet = true;\n}\n\nbool ProxySimpleInfo::ListenerListHasBeenSet() const\n{\n    return m_listenerListHasBeenSet;\n}\n\n","avg_line_length":28.2363636364,"max_line_length":137,"alphanum_fraction":0.6718179867,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8664,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"#include <Core\/Geometry\/MeshPrimitives.hpp>\n#include <Core\/Geometry\/TriangleMesh.hpp>\n#include <catch2\/catch.hpp>\n\nTEST_CASE( \"Core\/Geometry\/TriangleMesh\", \"[Core][Core\/Geometry][TriangleMesh]\" ) {\n    using Ra::Core::Vector3;\n    using Ra::Core::Geometry::TriangleMesh;\n    using Vec3AttribHandle = Ra::Core::Utils::AttribHandle<Vector3>;\n\n    TriangleMesh mesh = Ra::Core::Geometry::makeBox();\n\n    \/\/ base attributes are automatically added\n    auto h_pos = mesh.getAttribHandle<Vector3>( \"in_position\" );\n    REQUIRE( mesh.isValid( h_pos ) );\n    auto h_nor = mesh.getAttribHandle<Vector3>( \"in_normal\" );\n    REQUIRE( mesh.isValid( h_nor ) );\n\n    \/\/ Add\/Remove attributes without filling it\n    auto handleEmpty = mesh.addAttrib<Vec3AttribHandle::value_type>( \"empty\" );\n    mesh.removeAttrib( handleEmpty );\n    REQUIRE( !mesh.isValid( handleEmpty ) );\n    handleEmpty = mesh.addAttrib<Vec3AttribHandle::value_type>( \"empty\" );\n    REQUIRE( mesh.isValid( handleEmpty ) );\n    mesh.removeAttrib( handleEmpty );\n    handleEmpty = mesh.getAttribHandle<Vec3AttribHandle::value_type>( \"empty\" );\n    REQUIRE( !mesh.isValid( handleEmpty ) );\n\n    \/\/ Test access to the attribute container\n    auto handleFilled     = mesh.addAttrib<Vec3AttribHandle::value_type>( \"filled\" );\n    auto& attribFilled    = mesh.getAttrib( handleFilled );\n    auto& containerFilled = attribFilled.getDataWithLock();\n    REQUIRE( attribFilled.isLocked() );\n\n    \/\/ Test filling and removing vec3 attributes\n    for ( int i = 0; i != int( mesh.vertices().size() ); ++i )\n        containerFilled.push_back( Vec3AttribHandle::value_type::Random() );\n    attribFilled.unlock();\n\n    auto handleFilled2     = mesh.getAttribHandle<Vec3AttribHandle::value_type>( \"filled\" );\n    auto& containerFilled2 = mesh.getAttrib( handleFilled2 ).data();\n    REQUIRE( containerFilled == containerFilled2 );\n\n    mesh.removeAttrib( handleFilled );\n\n    \/\/ Test attribute creation by type, filling and removal\n    auto handle      = mesh.addAttrib<Eigen::Matrix<unsigned int, 1, 1>>( \"filled2\" );\n    auto& container3 = mesh.getAttrib( handle ).getDataWithLock();\n    using HandleType = decltype( handle );\n\n    for ( int i = 0; i != int( mesh.vertices().size() ); ++i )\n        container3.push_back( typename HandleType::value_type( i ) );\n    mesh.getAttrib( handle ).unlock();\n    mesh.removeAttrib( handle );\n\n    \/\/ Test dummy handle\n    auto invalid = mesh.getAttribHandle<float>( \"toto\" );\n    REQUIRE( !mesh.isValid( invalid ) );\n\n    \/\/ Test attribute copy\n    const auto v0         = mesh.vertices()[0];\n    TriangleMesh meshCopy = mesh;\n    meshCopy.copyAllAttributes( mesh );\n    REQUIRE( mesh.vertices()[0].isApprox( v0 ) );\n    meshCopy.verticesWithLock()[0] += Ra::Core::Vector3( 0.5, 0.5, 0.5 );\n    meshCopy.verticesUnlock();\n    REQUIRE( !meshCopy.vertices()[0].isApprox( v0 ) );\n\n    \/\/ For the documentation in doc\/developer\/mesh.md\n    \/\/! [create TriangleMesh]\n    using Ra::Core::Geometry::TriangleMesh;\n    TriangleMesh m;\n    TriangleMesh::PointAttribHandle::Container vertices;\n    TriangleMesh::NormalAttribHandle::Container normals;\n    TriangleMesh::IndexContainerType indices;\n\n    vertices.push_back( {0, 0, 0} );\n    vertices.push_back( {1, 0, 0} );\n    vertices.push_back( {0, 2, 0} );\n    normals.push_back( {0, 0, 1} );\n    normals.push_back( {0, 0, 1} );\n    normals.push_back( {0, 0, 1} );\n\n    m.setVertices( std::move( vertices ) );\n    m.setNormals( std::move( normals ) );\n\n    m.setIndices( {{0, 1, 2}} );\n\n    auto handle1  = m.addAttrib<Vector3>( \"vector3_attrib\" );\n    auto& attrib1 = m.getAttrib( handle1 );\n    auto& buf     = attrib1.getDataWithLock();\n\n    buf.reserve( 3 );\n    buf.push_back( {1, 1, 1} );\n    buf.push_back( {2, 2, 2} );\n    buf.push_back( {3, 3, 3} );\n    attrib1.unlock();\n\n    auto handle2  = m.addAttrib<float>( \"float_attrib\" );\n    auto& attrib2 = m.getAttrib( handle2 );\n    attrib2.setData( {1.f, 2.f, 3.f} );\n\n    TriangleMesh m2;\n    m2.copyBaseGeometry( m );\n    m2.copyAttributes( m, handle1 );\n    \/\/! [create TriangleMesh]\n\n    m2.copyAttributes( m, handle2 );\n\n    auto& attribM2_1 = m2.getAttrib( handle1 );\n    auto& attribM2_2 = m2.getAttrib( handle2 );\n    REQUIRE( attribM2_1.getSize() == 3 );\n    REQUIRE( attribM2_1.getElementSize() == 3 );\n    REQUIRE( attribM2_1.getStride() == sizeof( Vector3 ) );\n    REQUIRE( attribM2_1.getBufferSize() == 3 * sizeof( Vector3 ) );\n    attribM2_1.resize( 10 );\n    REQUIRE( attribM2_1.getSize() == 10 );\n    REQUIRE( attribM2_1.getElementSize() == 3 );\n    REQUIRE( attribM2_1.getStride() == sizeof( Vector3 ) );\n    REQUIRE( attribM2_1.getBufferSize() == 10 * sizeof( Vector3 ) );\n    REQUIRE( attribM2_2.getSize() == 3 );\n    REQUIRE( attribM2_2.getElementSize() == 1 );\n    REQUIRE( attribM2_2.getStride() == sizeof( float ) );\n    REQUIRE( attribM2_2.getBufferSize() == 3 * sizeof( float ) );\n\n    auto& attrMgr = m2.vertexAttribs();\n\n    REQUIRE( attrMgr.getAttribPtr( handle1 ) == attrMgr.getAttribBase( attribM2_1.getName() ) );\n    REQUIRE( nullptr == attrMgr.getAttribBase( \"unkown\" ) );\n\n    int cpt = 0;\n    attrMgr.for_each_attrib(\n        [&cpt, &attribM2_1, &attribM2_2, &attrMgr]( Ra::Core::Utils::AttribBase* b ) {\n            cpt++;\n            \/\/ 3 since we want to skip position and normals\n            if ( cpt == 3 )\n            {\n                auto& t        = b->cast<Vector3>();\n                const void* p1 = t.dataPtr();\n                const void* p2 = attribM2_1.dataPtr();\n                REQUIRE( p1 == p2 );\n            }\n            if ( cpt == 4 )\n            {\n                \/\/ const to check const cast;\n                const Ra::Core::Utils::AttribBase* cb   = b;\n                const Ra::Core::Utils::Attrib<float>& t = cb->cast<float>();\n                REQUIRE( t.dataPtr() == attribM2_2.dataPtr() );\n            }\n        } );\n    REQUIRE( cpt == attrMgr.getNumAttribs() );\n    const Ra::Core::Utils::AttribHandle<float>::Container newData {0.f, 1.f, 2.f};\n    attrMgr.setAttrib( handle2, newData );\n    REQUIRE( m2.getAttrib( handle2 ).data() == newData );\n}\n\nTEST_CASE( \"Core\/Geometry\/TriangleMesh\/CopyAllAttributes\", \"[Core][Core\/Geometry][TriangleMesh]\" ) {\n    using Ra::Core::Vector2;\n    using Ra::Core::Vector3;\n    using Ra::Core::Geometry::TriangleMesh;\n    using Vec3AttribHandle = Ra::Core::Utils::AttribHandle<Vector3>;\n    using Ra::Core::Geometry::TriangleMesh;\n\n    TriangleMesh m;\n    TriangleMesh::PointAttribHandle::Container vertices;\n    TriangleMesh::NormalAttribHandle::Container normals;\n    TriangleMesh::IndexContainerType indices;\n\n    vertices.push_back( {0, 0, 0} );\n    vertices.push_back( {1, 0, 0} );\n    vertices.push_back( {0, 2, 0} );\n    normals.push_back( {0, 0, 1} );\n    normals.push_back( {0, 0, 1} );\n    normals.push_back( {0, 0, 1} );\n\n    m.setVertices( std::move( vertices ) );\n    m.setNormals( std::move( normals ) );\n\n    m.setIndices( {{0, 1, 2}} );\n\n    auto handle1  = m.addAttrib<Vector2>( \"vector2_attrib\" );\n    auto& attrib1 = m.getAttrib( handle1 );\n    auto& buf1    = attrib1.getDataWithLock();\n\n    buf1.reserve( 3 );\n    buf1.push_back( {1, 1} );\n    buf1.push_back( {2, 2} );\n    buf1.push_back( {3, 3} );\n    attrib1.unlock();\n\n    auto handle2  = m.addAttrib<float>( \"float_attrib\" );\n    auto& attrib2 = m.getAttrib( handle2 );\n    attrib2.setData( {1.f, 2.f, 3.f} );\n\n    using Vector5 = Eigen::Matrix<Scalar, 5, 1>;\n    auto handle3  = m.addAttrib<Vector5>( \"vector5_attrib\" );\n    auto& attrib3 = m.getAttrib( handle3 );\n    auto& buf3    = attrib3.getDataWithLock();\n\n    buf3.reserve( 3 );\n    for ( int val = 1; val <= 3; ++val )\n    {\n        Vector5 v;\n        v << val, val, val, val, val;\n        buf3.push_back( v );\n    }\n    attrib3.unlock();\n\n    TriangleMesh m3;\n\n    m3.copyBaseGeometry( m );\n\n    \/\/ this one do not copy Vector5 attrib\n    m3.copyAllAttributes( m );\n\n    REQUIRE( m3.getAttribHandle<Vector3>( attrib1.getName() ).idx().isValid() );\n    REQUIRE( m3.getAttribHandle<float>( attrib2.getName() ).idx().isValid() );\n    REQUIRE( m3.getAttribHandle<Vector5>( attrib3.getName() ).idx().isInvalid() );\n    REQUIRE( !m3.vertexAttribs().hasSameAttribs( m.vertexAttribs() ) );\n    REQUIRE( !m.vertexAttribs().hasSameAttribs( m3.vertexAttribs() ) );\n\n    \/\/ but we can copy it explicitly\n    auto handleM3 = m3.addAttrib( \"vector5_attrib\", m.getAttrib( handle3 ).data() );\n\n    REQUIRE( m3.vertexAttribs().hasSameAttribs( m.vertexAttribs() ) );\n    REQUIRE( m.vertexAttribs().hasSameAttribs( m3.vertexAttribs() ) );\n\n    m3.getAttribBase( \"vector5_attrib\" )->setName( \"better\" );\n    REQUIRE( m3.getAttrib( handleM3 ).getName() == \"better\" );\n}\n","avg_line_length":37.6695652174,"max_line_length":100,"alphanum_fraction":0.629501385,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1156,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"solid\/Box.hpp\"\n\n\nBox::Box(double cr_co, SolidType type, VEC center, VEC rotation, VEC extendAxis) :\n        Solid(cr_co, type),\n        center(center),\n        rotation(rotation),\n        extendAxis(extendAxis) { }\n\nVEC Box::localCoord(VEC globalCoord) {\n    VEC local = rotateCoord(globalCoord - center, -rotation);\n    return local;\n}\n\nVEC Box::globalCoord(VEC localCoord) {\n    VEC global = rotateCoord(localCoord, rotation) + center;\n    return global;\n}\n\ndouble Box::implicitFunction(VEC pos) {\n    VEC diff_pos_local = sqrt(square(localCoord(pos))) - extendAxis;\n    double implicit = max(diff_pos_local);\n    return implicit;\n}\n\nvoid Box::react(shared_ptr<Particle> part, double delta_t) {\n    if (detect(part->next_pos)) {\n        VEC local_next_pos = localCoord(part->next_pos);\n        VEC intersec_loc = min(extendAxis, max(- extendAxis, local_next_pos));\n        VEC intersec_glob = globalCoord(intersec_loc);\n        double dist = norm(intersec_glob - part->next_pos);\n        VEC intersec_normal = normalise(globalCoord(local_next_pos - intersec_loc));\n        reaction(part, intersec_glob, dist, intersec_normal, delta_t);\n    }\n}\n","avg_line_length":32.1111111111,"max_line_length":84,"alphanum_fraction":0.6868512111,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":814,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"UISelectableObject.h\"\n#include \"..\\UISelector\\UIObjectSelector.h\"\n#include \"System\\graphics\\textureManager.h\"\n#include \"World\\Tile.h\"\n\nUISelectableObject::UISelectableObject(UIObjectSelector * _selector, int _posX, int _posY, unsigned int _layer, \n                                       int _index)\n    : UISelectable(_selector, _posX, _posY, Tile::TILE_SIZE, Tile::TILE_SIZE, _layer, _index)\n{\n}\n\nvoid UISelectableObject::render()\n{\n    TextureManager::spriteSheets[TextureManager::OBJECT_ICONS].renderTile(positionX, positionY, index + selector->getOffset(),\n                                                                          1, 1, false, false,\n                                                                          0, Tile::TILE_SIZE \/ 2, Tile::TILE_SIZE \/ 2);\n    UISelectable::render();\n}","avg_line_length":45.2222222222,"max_line_length":126,"alphanum_fraction":0.5823095823,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":17906,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"#include \"sendcoinsdialog.h\"\n#include \"ui_sendcoinsdialog.h\"\n\n#include \"init.h\"\n#include \"walletmodel.h\"\n#include \"addresstablemodel.h\"\n#include \"addressbookpage.h\"\n\n#include \"bitcoinunits.h\"\n#include \"addressbookpage.h\"\n#include \"optionsmodel.h\"\n#include \"sendcoinsentry.h\"\n#include \"guiutil.h\"\n#include \"askpassphrasedialog.h\"\n\n#include \"coincontrol.h\"\n#include \"coincontroldialog.h\"\n\n#include <QMessageBox>\n#include <QLocale>\n#include <QTextDocument>\n#include <QScrollBar>\n#include <QClipboard>\n\nSendCoinsDialog::SendCoinsDialog(QWidget *parent) :\n    QDialog(parent),\n    ui(new Ui::SendCoinsDialog),\n    model(0)\n{\n    ui->setupUi(this);\n\n#ifdef Q_OS_MAC \/\/ Icons on push buttons are very uncommon on Mac\n    ui->addButton->setIcon(QIcon());\n    ui->clearButton->setIcon(QIcon());\n    ui->sendButton->setIcon(QIcon());\n#endif\n\n#if QT_VERSION >= 0x040700\n    \/* Do not move this to the XML file, Qt before 4.7 will choke on it *\/\n    ui->lineEditCoinControlChange->setPlaceholderText(tr(\"Enter a nonolivecoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)\"));\n#endif\n\n    addEntry();\n\n    connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));\n    connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));\n\n    \/\/ Coin Control\n    ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont());\n    connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked()));\n    connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int)));\n    connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &)));\n\n    \/\/ Coin Control: clipboard actions\n    QAction *clipboardQuantityAction = new QAction(tr(\"Copy quantity\"), this);\n    QAction *clipboardAmountAction = new QAction(tr(\"Copy amount\"), this);\n    QAction *clipboardFeeAction = new QAction(tr(\"Copy fee\"), this);\n    QAction *clipboardAfterFeeAction = new QAction(tr(\"Copy after fee\"), this);\n    QAction *clipboardBytesAction = new QAction(tr(\"Copy bytes\"), this);\n    QAction *clipboardPriorityAction = new QAction(tr(\"Copy priority\"), this);\n    QAction *clipboardLowOutputAction = new QAction(tr(\"Copy low output\"), this);\n    QAction *clipboardChangeAction = new QAction(tr(\"Copy change\"), this);\n    connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity()));\n    connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount()));\n    connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee()));\n    connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee()));\n    connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes()));\n    connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority()));\n    connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput()));\n    connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange()));\n    ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);\n    ui->labelCoinControlAmount->addAction(clipboardAmountAction);\n    ui->labelCoinControlFee->addAction(clipboardFeeAction);\n    ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);\n    ui->labelCoinControlBytes->addAction(clipboardBytesAction);\n    ui->labelCoinControlPriority->addAction(clipboardPriorityAction);\n    ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);\n    ui->labelCoinControlChange->addAction(clipboardChangeAction);\n\n    fNewRecipientAllowed = true;\n}\n\nvoid SendCoinsDialog::setModel(WalletModel *model)\n{\n    this->model = model;\n\n    for(int i = 0; i < ui->entries->count(); ++i)\n    {\n        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n        if(entry)\n        {\n            entry->setModel(model);\n        }\n    }\n    if(model && model->getOptionsModel())\n    {\n        setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());\n        connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));\n        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n\n        \/\/ Coin Control\n        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels()));\n        connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool)));\n        connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels()));\n        ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures());\n        coinControlUpdateLabels();\n    }\n}\n\nSendCoinsDialog::~SendCoinsDialog()\n{\n    delete ui;\n}\n\nvoid SendCoinsDialog::on_sendButton_clicked()\n{\n    QList<SendCoinsRecipient> recipients;\n    bool valid = true;\n\n    if(!model)\n        return;\n\n    for(int i = 0; i < ui->entries->count(); ++i)\n    {\n        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n        if(entry)\n        {\n            if(entry->validate())\n            {\n                recipients.append(entry->getValue());\n            }\n            else\n            {\n                valid = false;\n            }\n        }\n    }\n\n    if(!valid || recipients.isEmpty())\n    {\n        return;\n    }\n\n    \/\/ Format confirmation message\n    QStringList formatted;\n    foreach(const SendCoinsRecipient &rcp, recipients)\n    {\n        formatted.append(tr(\"<b>%1<\/b> to %2 (%3)\").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address));\n    }\n\n    fNewRecipientAllowed = false;\n\n    QMessageBox::StandardButton retval = QMessageBox::question(this, tr(\"Confirm send coins\"),\n                          tr(\"Are you sure you want to send %1?\").arg(formatted.join(tr(\" and \"))),\n          QMessageBox::Yes|QMessageBox::Cancel,\n          QMessageBox::Cancel);\n\n    if(retval != QMessageBox::Yes)\n    {\n        fNewRecipientAllowed = true;\n        return;\n    }\n\n    WalletModel::UnlockContext ctx(model->requestUnlock());\n    if(!ctx.isValid())\n    {\n        \/\/ Unlock wallet was cancelled\n        fNewRecipientAllowed = true;\n        return;\n    }\n\n    WalletModel::SendCoinsReturn sendstatus;\n\n    if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures())\n        sendstatus = model->sendCoins(recipients);\n    else\n        sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl);\n\n    switch(sendstatus.status)\n    {\n    case WalletModel::InvalidAddress:\n        QMessageBox::warning(this, tr(\"Send Coins\"),\n            tr(\"The recipient address is not valid, please recheck.\"),\n            QMessageBox::Ok, QMessageBox::Ok);\n        break;\n    case WalletModel::InvalidAmount:\n        QMessageBox::warning(this, tr(\"Send Coins\"),\n            tr(\"The amount to pay must be larger than 0.\"),\n            QMessageBox::Ok, QMessageBox::Ok);\n        break;\n    case WalletModel::AmountExceedsBalance:\n        QMessageBox::warning(this, tr(\"Send Coins\"),\n            tr(\"The amount exceeds your balance.\"),\n            QMessageBox::Ok, QMessageBox::Ok);\n        break;\n    case WalletModel::AmountWithFeeExceedsBalance:\n        QMessageBox::warning(this, tr(\"Send Coins\"),\n            tr(\"The total exceeds your balance when the %1 transaction fee is included.\").\n            arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)),\n            QMessageBox::Ok, QMessageBox::Ok);\n        break;\n    case WalletModel::DuplicateAddress:\n        QMessageBox::warning(this, tr(\"Send Coins\"),\n            tr(\"Duplicate address found, can only send to each address once per send operation.\"),\n            QMessageBox::Ok, QMessageBox::Ok);\n        break;\n    case WalletModel::TransactionCreationFailed:\n        QMessageBox::warning(this, tr(\"Send Coins\"),\n            tr(\"Error: Transaction creation failed.\"),\n            QMessageBox::Ok, QMessageBox::Ok);\n        break;\n    case WalletModel::TransactionCommitFailed:\n        QMessageBox::warning(this, tr(\"Send Coins\"),\n            tr(\"Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.\"),\n            QMessageBox::Ok, QMessageBox::Ok);\n        break;\n    case WalletModel::Aborted: \/\/ User aborted, nothing to do\n        break;\n    case WalletModel::OK:\n        accept();\n        CoinControlDialog::coinControl->UnSelectAll();\n        coinControlUpdateLabels();\n        break;\n    }\n    fNewRecipientAllowed = true;\n}\n\nvoid SendCoinsDialog::clear()\n{\n    \/\/ Remove entries until only one left\n    while(ui->entries->count())\n    {\n        delete ui->entries->takeAt(0)->widget();\n    }\n    addEntry();\n\n    updateRemoveEnabled();\n\n    ui->sendButton->setDefault(true);\n}\n\nvoid SendCoinsDialog::reject()\n{\n    clear();\n}\n\nvoid SendCoinsDialog::accept()\n{\n    clear();\n}\n\nSendCoinsEntry *SendCoinsDialog::addEntry()\n{\n    SendCoinsEntry *entry = new SendCoinsEntry(this);\n    entry->setModel(model);\n    ui->entries->addWidget(entry);\n    connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));\n    connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels()));\n\n    updateRemoveEnabled();\n\n    \/\/ Focus the field, so that entry can start immediately\n    entry->clear();\n    entry->setFocus();\n    ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());\n    QCoreApplication::instance()->processEvents();\n    QScrollBar* bar = ui->scrollArea->verticalScrollBar();\n    if(bar)\n        bar->setSliderPosition(bar->maximum());\n    return entry;\n}\n\nvoid SendCoinsDialog::updateRemoveEnabled()\n{\n    \/\/ Remove buttons are enabled as soon as there is more than one send-entry\n    bool enabled = (ui->entries->count() > 1);\n    for(int i = 0; i < ui->entries->count(); ++i)\n    {\n        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n        if(entry)\n        {\n            entry->setRemoveEnabled(enabled);\n        }\n    }\n    setupTabChain(0);\n    coinControlUpdateLabels();\n}\n\nvoid SendCoinsDialog::removeEntry(SendCoinsEntry* entry)\n{\n    delete entry;\n    updateRemoveEnabled();\n}\n\nQWidget *SendCoinsDialog::setupTabChain(QWidget *prev)\n{\n    for(int i = 0; i < ui->entries->count(); ++i)\n    {\n        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n        if(entry)\n        {\n            prev = entry->setupTabChain(prev);\n        }\n    }\n    QWidget::setTabOrder(prev, ui->addButton);\n    QWidget::setTabOrder(ui->addButton, ui->sendButton);\n    return ui->sendButton;\n}\n\nvoid SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)\n{\n    if(!fNewRecipientAllowed)\n        return;\n\n    SendCoinsEntry *entry = 0;\n    \/\/ Replace the first entry if it is still unused\n    if(ui->entries->count() == 1)\n    {\n        SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());\n        if(first->isClear())\n        {\n            entry = first;\n        }\n    }\n    if(!entry)\n    {\n        entry = addEntry();\n    }\n\n    entry->setValue(rv);\n}\n\nbool SendCoinsDialog::handleURI(const QString &uri)\n{\n    SendCoinsRecipient rv;\n    \/\/ URI has to be valid\n    if (GUIUtil::parseBitcoinURI(uri, &rv))\n    {\n        CBitcoinAddress address(rv.address.toStdString());\n        if (!address.IsValid())\n            return false;\n        pasteEntry(rv);\n        return true;\n    }\n\n    return false;\n}\n\nvoid SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)\n{\n    Q_UNUSED(stake);\n    Q_UNUSED(unconfirmedBalance);\n    Q_UNUSED(immatureBalance);\n    if(!model || !model->getOptionsModel())\n        return;\n\n    int unit = model->getOptionsModel()->getDisplayUnit();\n    ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));\n}\n\nvoid SendCoinsDialog::updateDisplayUnit()\n{\n    if(model && model->getOptionsModel())\n    {\n        \/\/ Update labelBalance with the current balance and the current unit\n        ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance()));\n    }\n}\n\n\/\/ Coin Control: copy label \"Quantity\" to clipboard\nvoid SendCoinsDialog::coinControlClipboardQuantity()\n{\n    QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text());\n}\n\n\/\/ Coin Control: copy label \"Amount\" to clipboard\nvoid SendCoinsDialog::coinControlClipboardAmount()\n{\n    QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(\" \")));\n}\n\n\/\/ Coin Control: copy label \"Fee\" to clipboard\nvoid SendCoinsDialog::coinControlClipboardFee()\n{\n    QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(\" \")));\n}\n\n\/\/ Coin Control: copy label \"After fee\" to clipboard\nvoid SendCoinsDialog::coinControlClipboardAfterFee()\n{\n    QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(\" \")));\n}\n\n\/\/ Coin Control: copy label \"Bytes\" to clipboard\nvoid SendCoinsDialog::coinControlClipboardBytes()\n{\n    QApplication::clipboard()->setText(ui->labelCoinControlBytes->text());\n}\n\n\/\/ Coin Control: copy label \"Priority\" to clipboard\nvoid SendCoinsDialog::coinControlClipboardPriority()\n{\n    QApplication::clipboard()->setText(ui->labelCoinControlPriority->text());\n}\n\n\/\/ Coin Control: copy label \"Low output\" to clipboard\nvoid SendCoinsDialog::coinControlClipboardLowOutput()\n{\n    QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text());\n}\n\n\/\/ Coin Control: copy label \"Change\" to clipboard\nvoid SendCoinsDialog::coinControlClipboardChange()\n{\n    QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(\" \")));\n}\n\n\/\/ Coin Control: settings menu - coin control enabled\/disabled by user\nvoid SendCoinsDialog::coinControlFeatureChanged(bool checked)\n{\n    ui->frameCoinControl->setVisible(checked);\n\n    if (!checked && model) \/\/ coin control features disabled\n        CoinControlDialog::coinControl->SetNull();\n}\n\n\/\/ Coin Control: button inputs -> show actual coin control dialog\nvoid SendCoinsDialog::coinControlButtonClicked()\n{\n    CoinControlDialog dlg;\n    dlg.setModel(model);\n    dlg.exec();\n    coinControlUpdateLabels();\n}\n\n\/\/ Coin Control: checkbox custom change address\nvoid SendCoinsDialog::coinControlChangeChecked(int state)\n{\n    if (model)\n    {\n        if (state == Qt::Checked)\n            CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get();\n        else\n            CoinControlDialog::coinControl->destChange = CNoDestination();\n    }\n\n    ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked));\n    ui->labelCoinControlChangeLabel->setEnabled((state == Qt::Checked));\n}\n\n\/\/ Coin Control: custom change address changed\nvoid SendCoinsDialog::coinControlChangeEdited(const QString & text)\n{\n    if (model)\n    {\n        CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get();\n\n        \/\/ label for the change address\n        ui->labelCoinControlChangeLabel->setStyleSheet(\"QLabel{color:black;}\");\n        if (text.isEmpty())\n            ui->labelCoinControlChangeLabel->setText(\"\");\n        else if (!CBitcoinAddress(text.toStdString()).IsValid())\n        {\n            ui->labelCoinControlChangeLabel->setStyleSheet(\"QLabel{color:red;}\");\n            ui->labelCoinControlChangeLabel->setText(tr(\"WARNING: Invalid nonolivecoin address\"));\n        }\n        else\n        {\n            QString associatedLabel = model->getAddressTableModel()->labelForAddress(text);\n            if (!associatedLabel.isEmpty())\n                ui->labelCoinControlChangeLabel->setText(associatedLabel);\n            else\n            {\n                CPubKey pubkey;\n                CKeyID keyid;\n                CBitcoinAddress(text.toStdString()).GetKeyID(keyid);   \n                if (model->getPubKey(keyid, pubkey))\n                    ui->labelCoinControlChangeLabel->setText(tr(\"(no label)\"));\n                else\n                {\n                    ui->labelCoinControlChangeLabel->setStyleSheet(\"QLabel{color:red;}\");\n                    ui->labelCoinControlChangeLabel->setText(tr(\"WARNING: unknown change address\"));\n                }\n            }\n        }\n    }\n}\n\n\/\/ Coin Control: update labels\nvoid SendCoinsDialog::coinControlUpdateLabels()\n{\n    if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures())\n        return;\n\n    \/\/ set pay amounts\n    CoinControlDialog::payAmounts.clear();\n    for(int i = 0; i < ui->entries->count(); ++i)\n    {\n        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n        if(entry)\n            CoinControlDialog::payAmounts.append(entry->getValue().amount);\n    }\n\n    if (CoinControlDialog::coinControl->HasSelected())\n    {\n        \/\/ actual coin control calculation\n        CoinControlDialog::updateLabels(model, this);\n\n        \/\/ show coin control stats\n        ui->labelCoinControlAutomaticallySelected->hide();\n        ui->widgetCoinControl->show();\n    }\n    else\n    {\n        \/\/ hide coin control stats\n        ui->labelCoinControlAutomaticallySelected->show();\n        ui->widgetCoinControl->hide();\n        ui->labelCoinControlInsuffFunds->hide();\n    }\n}\n","avg_line_length":34.3685220729,"max_line_length":233,"alphanum_fraction":0.6706690495,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1723,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/\/\n\/\/ @ClassName RobotPath\n\/\/ @Description TODO\n\/\/ @Date 2019\/2\/19 2:46 PM\n\/\/ @Created by Insomnia\n\/\/\n\n#include <stdio.h>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nclass Solution {\npublic:\n    int movingCount(int threshold, int rows, int cols) {\n        vector<vector<bool> > matrix(rows + 1, vector<bool>(cols + 1, false));\n\n        int res = helper(matrix, threshold, rows, cols, 0, 0);\n        return res;\n    }\n\nprivate:\n\n    int helper(vector<vector<bool> > &matrix, int max, int rows, int cols, int curRow, int curCol) {\n\n        int res = 0;\n\n        if (check(matrix, max, rows, cols, curRow, curCol)) {\n            matrix[curRow][curCol] = true;\n            res = 1 + helper(matrix, max, rows, cols, curRow + 1, curCol)\n                    + helper(matrix, max, rows, cols, curRow - 1, curCol)\n                      + helper(matrix, max, rows, cols, curRow , curCol + 1)\n                        + helper(matrix, max, rows, cols, curRow , curCol - 1);\n        }\n\n        return res;\n    }\n\n    bool check(vector<vector<bool> > &matrix, int max, int rows, int cols, int curRow, int curCol) {\n        if (curRow >= 0 && curRow < rows && curCol >= 0 && curCol < cols && (matrix[curRow][curCol] == false) && (getSum(curRow, curCol) <= max)) {\n            return true;\n        }\n        return false;\n    }\n\n    int getSum(int x, int y) {\n        int sum = 0;\n        while (x) {\n            int tmp = x % 10;\n            sum += tmp;\n            x \/= 10;\n        }\n\n        while (y) {\n            int tmp = y % 10;\n            sum += tmp;\n            y \/= 10;\n        }\n\n        return sum;\n    }\n\n};\nint main() {\n\n    Solution sol;\n\n    cout << sol.movingCount(10, 10 ,18) << endl;\n\n    return 0;\n}\n","avg_line_length":23.602739726,"max_line_length":147,"alphanum_fraction":0.5095763204,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5195,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/**\n\tCopyright (c) 2009 James Wynn (james@jameswynn.com)\n\n\tPermission is hereby granted, free of charge, to any person obtaining a copy\n\tof this software and associated documentation files (the \"Software\"), to deal\n\tin the Software without restriction, including without limitation the rights\n\tto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\tcopies of the Software, and to permit persons to whom the Software is\n\tfurnished to do so, subject to the following conditions:\n\n\tThe above copyright notice and this permission notice shall be included in\n\tall copies or substantial portions of the Software.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\tTHE SOFTWARE.\n*\/\n\n#include <FileWatcher\/FileWatcher.h>\n#include <FileWatcher\/FileWatcherImpl.h>\n\n#if FILEWATCHER_PLATFORM == FILEWATCHER_PLATFORM_WIN32\n#\tinclude <FileWatcher\/FileWatcherWin32.h>\n#\tdefine FILEWATCHER_IMPL FileWatcherWin32\n#elif FILEWATCHER_PLATFORM == FILEWATCHER_PLATFORM_KQUEUE\n#\tinclude <FileWatcher\/FileWatcherOSX.h>\n#\tdefine FILEWATCHER_IMPL FileWatcherOSX\n#elif FILEWATCHER_PLATFORM == FILEWATCHER_PLATFORM_LINUX\n#\tinclude <FileWatcher\/FileWatcherLinux.h>\n#\tdefine FILEWATCHER_IMPL FileWatcherLinux\n#endif\n\nnamespace FW\n{\n\n\t\/\/--------\n\tFileWatcher::FileWatcher()\n\t{\n\t\tmImpl = new FILEWATCHER_IMPL();\n\t}\n\n\t\/\/--------\n\tFileWatcher::~FileWatcher()\n\t{\n\t\tdelete mImpl;\n\t\tmImpl = 0;\n\t}\n\n\t\/\/--------\n\tWatchID FileWatcher::addWatch(const String& directory, FileWatchListener* watcher)\n\t{\n\t\treturn mImpl->addWatch(directory, watcher, false);\n\t}\n\n\t\/\/--------\n\tWatchID FileWatcher::addWatch(const String& directory, FileWatchListener* watcher, bool recursive)\n\t{\n\t\treturn mImpl->addWatch(directory, watcher, recursive);\n\t}\n\n\t\/\/--------\n\tvoid FileWatcher::removeWatch(const String& directory)\n\t{\n\t\tmImpl->removeWatch(directory);\n\t}\n\n\t\/\/--------\n\tvoid FileWatcher::removeWatch(WatchID watchid)\n\t{\n\t\tmImpl->removeWatch(watchid);\n\t}\n\n\t\/\/--------\n\tvoid FileWatcher::update()\n\t{\n\t\tmImpl->update();\n\t}\n\n\tvoid async_filewatcher_thread(AsyncFileWatcher* arg)\n\t{\n\t\tAsyncFileWatcher& watcher_handle = *arg;\n\t\tBufferedFileWatcher& watcher = watcher_handle.m_watch;\n\n\t\twhile (watcher_handle.m_running)\n\t\t{\n\t\t\twatcher.update();\n\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(50));\n\t\t}\n\t}\n\n\tBufferedFileWatcher::BufferedFileWatcher()\n\t{\n\t}\n\n\tBufferedFileWatcher::~BufferedFileWatcher()\n\t{\n\t}\n\n\tvoid BufferedFileWatcher::addWatch(const String & directory, FileWatchListener * watcher, WatchID* target)\n\t{\n\t\taddWatch(directory, watcher, false, target);\n\t}\n\n\tvoid BufferedFileWatcher::addWatch(const String & directory, FileWatchListener * watcher, bool recursive, WatchID* target)\n\t{\n\t\tcommand_struct str;\n\t\tstr.Type = AddWatch;\n\t\tstr.path = directory;\n\t\tstr.Add.watcher = watcher;\n\t\tstr.Add.recursive = recursive;\n\t\tstr.Add.target = target;\n\n\t\tstd::lock_guard<std::mutex> lock(m_mutex);\n\t\tm_commands.push(str);\n\t}\n\n\tvoid BufferedFileWatcher::removeWatch(const String & directory)\n\t{\n\t\tcommand_struct str;\n\t\tstr.Type = RemoveWatchStr;\n\t\tstr.path = directory;\n\t\t\n\t\tstd::lock_guard<std::mutex> lock(m_mutex);\n\t\tm_commands.push(str);\n\t}\n\n\tvoid BufferedFileWatcher::removeWatch(WatchID watchid)\n\t{\n\t\tcommand_struct str;\n\t\tstr.Type = RemoveWatchID;\n\t\tstr.RemoveID.id = watchid;\n\t\t\n\t\tstd::lock_guard<std::mutex> lock(m_mutex);\n\t\tm_commands.push(str);\n\t}\n\n\tvoid BufferedFileWatcher::update()\n\t{\n\t\tif (!m_commands.empty())\n\t\t{\n\t\t\tstd::lock_guard<std::mutex> lock(m_mutex);\n\t\t\twhile (!m_commands.empty())\n\t\t\t{\n\t\t\t\tauto cmd = m_commands.front();\n\t\t\t\tm_commands.pop();\n\n\t\t\t\tswitch (cmd.Type)\n\t\t\t\t{\n\t\t\t\tcase AddWatch:\n\t\t\t\t{\n\t\t\t\t\tauto ret = m_watcher.addWatch(cmd.path, cmd.Add.watcher, cmd.Add.recursive);\n\t\t\t\t\tif (cmd.Add.target != NULL)\n\t\t\t\t\t\t*cmd.Add.target = ret;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase RemoveWatchID:\n\t\t\t\t\tm_watcher.removeWatch(cmd.RemoveID.id);\n\t\t\t\t\tbreak;\n\t\t\t\tcase RemoveWatchStr:\n\t\t\t\t\tm_watcher.removeWatch(cmd.path);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tm_watcher.update();\n\t}\n\n\tAsyncFileWatcher::AsyncFileWatcher() : m_running(true)\n\t{\n\t\tm_thr = std::thread(async_filewatcher_thread, this);\n\t}\n\n\tAsyncFileWatcher::~AsyncFileWatcher()\n\t{\n\t\tm_running = false;\n\t\tm_thr.join();\n\t}\n\n\tvoid AsyncFileWatcher::addWatch(const String & directory, FileWatchListener * watcher, WatchID * target)\n\t{\n\t\tm_watch.addWatch(directory, watcher, target);\n\t}\n\n\tvoid AsyncFileWatcher::addWatch(const String & directory, FileWatchListener * watcher, bool recursive, WatchID * target)\n\t{\n\t\tm_watch.addWatch(directory, watcher, recursive, target);\n\t}\n\n\tvoid AsyncFileWatcher::removeWatch(const String & directory)\n\t{\n\t\tm_watch.removeWatch(directory);\n\t}\n\n\tvoid AsyncFileWatcher::removeWatch(WatchID watchid)\n\t{\n\t\tm_watch.removeWatch(watchid);\n\t}\n\n\tvoid AsyncFileWatcher::update()\n\t{\n\t\t\/\/ no-op, handled by our thread\n\t}\n\n};\/\/namespace FW\n","avg_line_length":24.6208530806,"max_line_length":123,"alphanum_fraction":0.7260827719,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5294,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":13.0,"content":"\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"core\/paint\/FieldsetPainter.h\"\n\n#include \"core\/layout\/LayoutFieldset.h\"\n#include \"core\/paint\/BoxDecorationData.h\"\n#include \"core\/paint\/BoxPainter.h\"\n#include \"core\/paint\/LayoutObjectDrawingRecorder.h\"\n#include \"core\/paint\/PaintInfo.h\"\n#include \"platform\/graphics\/GraphicsContextStateSaver.h\"\n\nnamespace blink {\n\nvoid FieldsetPainter::paintBoxDecorationBackground(const PaintInfo& paintInfo, const LayoutPoint& paintOffset)\n{\n    if (!paintInfo.shouldPaintWithinRoot(&m_layoutFieldset))\n        return;\n\n    LayoutRect paintRect(paintOffset, m_layoutFieldset.size());\n    LayoutBox* legend = m_layoutFieldset.findInFlowLegend();\n    if (!legend)\n        return BoxPainter(m_layoutFieldset).paintBoxDecorationBackground(paintInfo, paintOffset);\n\n    if (LayoutObjectDrawingRecorder::useCachedDrawingIfPossible(paintInfo.context, m_layoutFieldset, paintInfo.phase, paintOffset))\n        return;\n\n    \/\/ FIXME: We need to work with \"rl\" and \"bt\" block flow directions.  In those\n    \/\/ cases the legend is embedded in the right and bottom borders respectively.\n    \/\/ https:\/\/bugs.webkit.org\/show_bug.cgi?id=47236\n    if (m_layoutFieldset.style()->isHorizontalWritingMode()) {\n        LayoutUnit yOff = (legend->location().y() > 0) ? LayoutUnit() : (legend->size().height() - m_layoutFieldset.borderTop()) \/ 2;\n        paintRect.setHeight(paintRect.height() - yOff);\n        paintRect.setY(paintRect.y() + yOff);\n    } else {\n        LayoutUnit xOff = (legend->location().x() > 0) ? LayoutUnit() : (legend->size().width() - m_layoutFieldset.borderLeft()) \/ 2;\n        paintRect.setWidth(paintRect.width() - xOff);\n        paintRect.setX(paintRect.x() + xOff);\n    }\n\n    LayoutObjectDrawingRecorder recorder(paintInfo.context, m_layoutFieldset, paintInfo.phase, paintRect, paintOffset);\n    BoxDecorationData boxDecorationData(m_layoutFieldset);\n\n    if (boxDecorationData.bleedAvoidance == BackgroundBleedNone)\n        BoxPainter::paintBoxShadow(paintInfo, paintRect, m_layoutFieldset.styleRef(), Normal);\n    BoxPainter(m_layoutFieldset).paintFillLayers(paintInfo, boxDecorationData.backgroundColor, m_layoutFieldset.style()->backgroundLayers(), paintRect);\n    BoxPainter::paintBoxShadow(paintInfo, paintRect, m_layoutFieldset.styleRef(), Inset);\n\n    if (!boxDecorationData.hasBorderDecoration)\n        return;\n\n    \/\/ Create a clipping region around the legend and paint the border as normal\n    GraphicsContext& graphicsContext = paintInfo.context;\n    GraphicsContextStateSaver stateSaver(graphicsContext);\n\n    \/\/ FIXME: We need to work with \"rl\" and \"bt\" block flow directions.  In those\n    \/\/ cases the legend is embedded in the right and bottom borders respectively.\n    \/\/ https:\/\/bugs.webkit.org\/show_bug.cgi?id=47236\n    if (m_layoutFieldset.style()->isHorizontalWritingMode()) {\n        LayoutUnit clipTop = paintRect.y();\n        LayoutUnit clipHeight = max(static_cast<LayoutUnit>(m_layoutFieldset.style()->borderTopWidth()), legend->size().height() - ((legend->size().height() - m_layoutFieldset.borderTop()) \/ 2));\n        graphicsContext.clipOut(pixelSnappedIntRect(paintRect.x() + legend->location().x(), clipTop, legend->size().width(), clipHeight));\n    } else {\n        LayoutUnit clipLeft = paintRect.x();\n        LayoutUnit clipWidth = max(static_cast<LayoutUnit>(m_layoutFieldset.style()->borderLeftWidth()), legend->size().width());\n        graphicsContext.clipOut(pixelSnappedIntRect(clipLeft, paintRect.y() + legend->location().y(), clipWidth, legend->size().height()));\n    }\n\n    BoxPainter::paintBorder(m_layoutFieldset, paintInfo, paintRect, m_layoutFieldset.styleRef());\n}\n\nvoid FieldsetPainter::paintMask(const PaintInfo& paintInfo, const LayoutPoint& paintOffset)\n{\n    if (m_layoutFieldset.style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask)\n        return;\n\n    LayoutRect paintRect = LayoutRect(paintOffset, m_layoutFieldset.size());\n    LayoutBox* legend = m_layoutFieldset.findInFlowLegend();\n    if (!legend)\n        return BoxPainter(m_layoutFieldset).paintMask(paintInfo, paintOffset);\n\n    if (LayoutObjectDrawingRecorder::useCachedDrawingIfPossible(paintInfo.context, m_layoutFieldset, paintInfo.phase, paintOffset))\n        return;\n\n    \/\/ FIXME: We need to work with \"rl\" and \"bt\" block flow directions.  In those\n    \/\/ cases the legend is embedded in the right and bottom borders respectively.\n    \/\/ https:\/\/bugs.webkit.org\/show_bug.cgi?id=47236\n    if (m_layoutFieldset.style()->isHorizontalWritingMode()) {\n        LayoutUnit yOff = (legend->location().y() > 0) ? LayoutUnit() : (legend->size().height() - m_layoutFieldset.borderTop()) \/ 2;\n        paintRect.expand(0, -yOff);\n        paintRect.move(0, yOff);\n    } else {\n        LayoutUnit xOff = (legend->location().x() > 0) ? LayoutUnit() : (legend->size().width() - m_layoutFieldset.borderLeft()) \/ 2;\n        paintRect.expand(-xOff, 0);\n        paintRect.move(xOff, 0);\n    }\n\n    LayoutObjectDrawingRecorder recorder(paintInfo.context, m_layoutFieldset, paintInfo.phase, paintRect, paintOffset);\n    BoxPainter(m_layoutFieldset).paintMaskImages(paintInfo, paintRect);\n}\n\n} \/\/ namespace blink\n","avg_line_length":50.9038461538,"max_line_length":195,"alphanum_fraction":0.7234605213,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":31732,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1132.0,"content":"#include \"Accessdb.h\"\n#include \"Hostdb.h\"\n#include \"TcpSocket.h\"\n#include \"Multicast.h\"\n#include \"HttpServer.h\"\n#include \"Facebook.h\"\n\nstatic bool printCalendars ( SafeBuf &sb , time_t startDate ) ;\nstatic bool printCalendar ( SafeBuf &sb ,\n\t\t\t    int32_t showDay,\n\t\t\t    int32_t showMonth,\n\t\t\t    int32_t showYear ) ;\n\n\n\nAccessdb g_accessdb;\n\nstatic void handleRequestaa ( UdpSlot *slot , int32_t niceness ) ;\n\nbool Accessdb::registerHandler ( ) {\n\t\/\/ . register ourselves with the udp server\n\t\/\/ . it calls our callback when it receives a msg of type 0x0A\n\tif ( ! g_udpServer.registerHandler ( 0xaa, handleRequestaa )) \n\t\treturn false;\n\treturn true;\n}\n\n\nbool Accessdb::init ( ) {\n\n\tint32_t maxTreeMem = 3000000; \/\/ g_conf.m_accessdbMaxTreeMem;\n\tint32_t nodeSize = sizeof(AccessRec)+8+12+4 + sizeof(collnum_t);\n\t\/\/ . We take a snapshot of g_stats every minute.\n\t\/\/ . Each sample struct taken from g_stats ranges from 1k - 2k\n\t\/\/   after compression depending on the state of the\n\t\/\/   all errors arrays.\n\tuint32_t maxTreeNodes  = maxTreeMem \/ nodeSize;\n\t\/\/ assume low niceness\n\tm_niceness = 0;\n\tm_msg4InUse = false;\n\t\/\/ make the rec cache 0 bytes, cuz we are just using page cache now\n\tif ( ! m_rdb.init ( g_hostdb.m_dir\t\t, \/\/ working directory\n\t\t\t    \"accessdb\"\t\t\t, \/\/ dbname\n\t\t\t    true\t\t\t, \/\/ dedup keys\n\t\t\t    4+8    , \/\/ fixed data size (ip+fbid)\n\t\t\t    2,\/\/g_conf.m_accessdbMinFilesToMerge ,\n\t\t\t    maxTreeMem                  ,\n\t\t\t    maxTreeNodes\t\t,\n\t\t\t    true\t\t\t, \/\/ balance tree?\n\t\t\t    0                        , \/\/ m_accessdbMaxCchMem\n\t\t\t    0 ,\/\/ maxCacheNodes\t\t,\n\t\t\t    false\t\t\t, \/\/ use half keys?\n\t\t\t    false\t\t\t, \/\/ cache from disk?\n\t\t\t    NULL\t\t\t, \/\/ page cache pointer\n\t\t\t    false\t\t\t, \/\/ is titledb?\n\t\t\t    false\t\t\t, \/\/ preload cache?\n\t\t\t    sizeof(key128_t)\t\t, \/\/ key size\n\t\t\t    false , \/\/ bias disk page cache?\n\t\t\t    true )) \/\/ iscollectionless? syncdb,facebookdb,...\n\t\treturn false;\n\t\/\/ add the base since it is a collectionless rdb\n\treturn m_rdb.addColl ( NULL );\n}\n\n\n\n\/\/ Make sure we need this function.\n\/\/ main.cpp currently uses the addColl from m_rdb\nbool Accessdb::addColl ( char *coll, bool doVerify ) {\n\tif ( ! m_rdb.addColl ( coll ) ) return false;\n\treturn true;\n}\n\n\/\/static Msg4 s_msg4;\n\/\/static s_msg4InUse = false;\n\nvoid addedAccessRecWrapper ( void *state ) {\n\tg_accessdb.m_msg4InUse = false;\n}\n\nkey128_t Accessdb::makeKey1 ( int64_t now, int64_t widgetId64 ) {\n\tkey128_t ak;\n\tak.n1 = now;\n\tak.n0 = widgetId64;\n\t\/\/ make it a positive key\n\tak.n0 <<= 1;\n\tak.n0 |= 0x01;\n\treturn ak;\n}\n\nkey128_t Accessdb::makeKey2 ( int64_t now, int64_t widgetId64 ) {\n\tkey128_t ak;\n\t\/\/ indicate its the 2nd type of key by setting high bit\n\tak.n1 = widgetId64 | 0x8000000000000000LL;\n\tak.n0 = now;\n\t\/\/ make it a positive key\n\tak.n0 <<= 1;\n\tak.n0 |= 0x01;\n\treturn ak;\n}\n\n\/\/ . store two entries:\n\/\/ . time64|widgetid64|ip|fbid\n\/\/ . widgetid64|time64|ip|fbid\n\/\/ . storing group is based on the lower bits of the time64\nbool Accessdb::addAccess ( HttpRequest *hr , int32_t ip ) {\n\n\tint64_t now = gettimeofdayInMillisecondsGlobalNoCore(); \n\tint64_t fbId = hr->getLongLongFromCookie(\"fbid\",0LL);\n\tint64_t widgetId64 = hr->getLongLongFromCookie(\"widgetid\",0LL);\n\n\t\/\/ not if widgetid is bogus\n\tif ( widgetId64 & 0x8000000000000000LL ) return true;\n\t\/\/ or now can't have this top bit set. we use that as indicator!\n\tif ( now & 0x8000000000000000LL ) { char *xx=NULL;*xx=0; }\n\n\t\/\/ log if this is a problem! we need to know it so we can fix\n\tif ( m_msg4InUse ) {\n\t\tlog(\"access: msg4 is in use!!!!\");\n\t\treturn true;\n\t}\n\n\t\/\/ do not keep this on the stack in case the msg4 blocks!\n\t\/\/AccessRec arec[2];\n\tm_arec[0].m_key128 = g_accessdb.makeKey1(now,widgetId64);\n\tm_arec[0].m_ip     = ip;\n\tm_arec[0].m_fbId   = fbId;\n\tm_arec[1].m_key128 = g_accessdb.makeKey2(now,widgetId64);\n\tm_arec[1].m_ip     = ip;\n\tm_arec[1].m_fbId   = fbId;\n\t\/\/log(\"msg4: timestamp = %\"UINT64\"\",now);\n\t\/\/ this has like a 1 second delay before it flushes so you might\n\t\/\/ not see you current access until that passes\n\tif ( ! m_msg4InUse &&\n\t     ! m_msg4.addMetaList ( (char *)&m_arec[0] ,\n\t\t\t\t    (int32_t)2*sizeof(AccessRec),\n\t\t\t\t    (collnum_t)0, \/\/ collnum\n\t\t\t\t    NULL, \/\/ state\n\t\t\t\t    addedAccessRecWrapper,\n\t\t\t\t    0, \/\/ niceness\n\t\t\t\t    RDB_ACCESSDB ) )\n\t\t\/\/ if this blocked, mark it as in use\n\t\tm_msg4InUse = true;\n\treturn true;\n}\n\nclass MsgaaRequest {\npublic:\n\tint32_t      m_startDate;\n\tint64_t m_widgetId;\n\tint32_t      m_minRecSizes;\n};\n\n\n\nclass Stateaa {\npublic:\n\tint32_t m_replies;\n\tint32_t m_requests;\n\tint32_t m_errno;\n\tTcpSocket *m_socket;\n\tMsgfb m_msgfb;\n\n\tMsgaaRequest m_request;\n\t\/\/ for allocating usually like 32 multicasts\n\tint32_t m_numMulticasts;\n\tMulticast m_mcasts[MAX_HOSTS];\n};\n\nstatic void gotMulticastReplyWrapperaa ( void *state , void *state2 );\n\nstatic void gotFBUserInfoWrapper ( void *state );\nstatic bool gotFBUserInfo ( Stateaa *st ) ;\n\n\/\/ . returns false if blocked, true otherwise\n\/\/ . sets errno on error\n\/\/ . make a web page displaying the config of this host\n\/\/ . call g_httpServer.sendDynamicPage() to send it\nbool sendPageAccount ( TcpSocket *s , HttpRequest *r ) {\n\n\tStateaa *st ;\n\ttry { st = new (Stateaa); }\n\tcatch ( ... ) { \n\t\tg_errno = ENOMEM;\n\t\tlog(\"access: new(%i): %s\", sizeof(Stateaa),mstrerror(g_errno));\n\t\tg_httpServer.sendErrorReply ( s, 500, mstrerror(g_errno) ); \n\t\treturn true; \n\t}\n\tmnew ( st , sizeof(Stateaa) , \"Stateaa\" );\n\t\/\/ reset counts\n\tst->m_errno = 0;\n\tst->m_replies = 0;\n\tst->m_requests = 0;\n\tst->m_socket = s;\n\n\t\/\/ get startdate\n\tint32_t startDate = r->getLong(\"sd\",0);\n\tif ( startDate == 0 ) startDate = getTimeGlobalNoCore() - 7*86400;\n\n\t\/\/ get widgetid\n\tint64_t widgetId = r->getLongLong(\"widgetid\",0);\n\t\/\/ set request\n\tst->m_request.m_startDate = startDate;\n\tst->m_request.m_widgetId  = widgetId;\n\tst->m_request.m_minRecSizes = 10000;\n\n\t\/\/ first get facebook rec\n\tif ( ! st->m_msgfb.getFacebookUserInfo ( r ,\n\t\t\t\t\t\t st->m_socket,\n\t\t\t\t\t\t NULL,\/\/coll,\n\t\t\t\t\t\t st ,\n\t\t\t\t\t\t \"\", \/\/ redirpath\n\t\t\t\t\t\t gotFBUserInfoWrapper,\n\t\t\t\t\t\t 0 )) \/\/ niceness\n\t\treturn false;\n\t\/\/ got it\n\treturn gotFBUserInfo ( st );\n}\n\nvoid gotFBUserInfoWrapper ( void *state ) {\n\tStateaa *st = (Stateaa *)state;\n\tif ( ! gotFBUserInfo ( st ) ) return;\n\t\/\/ there is no callback to call, it must have sent an http reply\n}\n\n\/\/ from PageEvents.cpp\nbool printLoginScript ( SafeBuf &sb , char *redirUrl = NULL ) ;\nbool printHtmlHeader ( SafeBuf &sb , char *title , bool printPrimaryDiv ,\n\t\t       SearchInput *si , bool staticPage );\nbool printBlackBar(SafeBuf &sb,Msgfb *msgfb,char *page,int32_t ip,bool printLogo,\n\t\t   bool igoogle, class State7 *st );\nbool printPageTitle ( SafeBuf &sb, char *title );\nbool printHtmlTail ( SafeBuf *sb , Msgfb *msgfb , bool printUnsubscribedPopup);\n\n\nbool gotFBUserInfo ( Stateaa *st ) {\n\n\n\t\/\/ if not logged into facebook...\n\tif ( ! st->m_msgfb.m_fbId ) {\n\t\tSafeBuf sb;\n\t\tprintHtmlHeader ( sb , \"My Account\", 1 ,NULL,true);\n\t\tchar *path = \"\/account.html\";\n\t\tprintBlackBar (sb,&st->m_msgfb, path , st->m_socket->m_ip,1,0,\n\t\t\t       NULL);\n\t\tprintPageTitle (sb,\"<nobr>My Account<\/nobr>\");\n\t\tsb.safePrintf( \"<tr>\"\n\t\t\t       \"<td width=196px><\/td>\"\n\t\t\t       \"<td width=%s>\"\n\t\t\t       \"<br>\"\n\t\t\t       \"<br>\"\n\t\t\t       \"<br>\"\n\t\t\t       \"<center>\"\n\t\t\t       \"<b>Login with Facebook to access \"\n\t\t\t       \"your account.\"\n\t\t\t       \"<\/b>\"\n\t\t\t       \"<br>\"\n\t\t\t       \"<br>\" \n\t\t\t       \"<a id=login2 \"\n\t\t\t       \"onclick=\\\"\"\n\t\t\t       , RESULTSWIDTHSTR\n\t\t\t       );\n\t\tprintLoginScript ( sb );\n\t\tsb.safePrintf(\"\\\">\"\n\t\t\t      \"<img \"\n\t\t\t      \"align=center width=132 height=20 \"\n\t\t\t      \"src=\/fblogin.png border=0><\/a>\" \n\t\t\t      \"<br><br>\"\n\t\t\t      \"<\/center>\"\n\t\t\t      \"<\/td>\"\n\t\t\t      \"<\/tr>\" \n\t\t\t      \"<\/table>\"\n\t\t\t      );\n\t\tprintHtmlTail ( &sb , &st->m_msgfb, false );\n\t\tTcpSocket *s = st->m_socket;\n\t\t\/\/ nuke the state now\n\t\tmdelete ( st , sizeof(Stateaa) , \"Stateaa\" );\n\t\tdelete (st);\n\t\tint32_t bufLen = sb.length();\n\t\t\/\/ . send this page\n\t\t\/\/ . encapsulates in html header and tail\n\t\t\/\/ . make a Mime\n\t\tg_httpServer.sendDynamicPage ( s, sb.getBufStart(), bufLen );\n\t\treturn true;\n\t}\n\n\t\/\/ if widgetid not explicitly given use facebook id of the user\n\tif ( st->m_request.m_widgetId == 0 )\n\t\tst->m_request.m_widgetId  = st->m_msgfb.m_fbId;\n\n\tchar *request = (char *)&st->m_request;\n\tint32_t  requestSize = sizeof(MsgaaRequest);\n\n\t\/\/ send the request to every host in the network\n\tfor ( int32_t i = 0 ; i < g_hostdb.getNumGroups() ; i++ ) {\n\t\t\/\/ count send outs\n\t\tst->m_requests++;\n\t\t\/\/ get group id\n\t\tuint32_t gid = g_hostdb.getGroupId ( i );\n\t\t\/\/ get the multicast for this group, int16_tcut\n\t\tMulticast *m = &st->m_mcasts[i];\n\t\t\/\/ send it out\n\t\tif ( ! m->send ( request    , \n\t\t\t\t requestSize, \n\t\t\t\t 0xaa         , \/\/ msgType 0xaa\n\t\t\t\t false        , \/\/ does multicast own request?\n\t\t\t\t gid          , \/\/ group + offset\n\t\t\t\t false        , \/\/ send to whole group?\n\t\t\t\t 0            , \/\/ key is passed on startKey\n\t\t\t\t st           , \/\/ state data\n\t\t\t\t NULL         , \/\/ state data\n\t\t\t\t gotMulticastReplyWrapperaa ,\n\t\t\t\t 30      , \/\/ timeout in seconds (was 30)\n\t\t\t\t 0 , \/\/ niceness     ,\n\t\t\t\t false, \/\/ realtimeudp?\n\t\t\t\t -1 , \/\/ first host to try\n\t\t\t\t NULL            , \/\/ reply buf\n\t\t\t\t 0 , \/\/ reply buf max size\n\t\t\t\t true      , \/\/ free reply buf?\n\t\t\t\t true            , \/\/ do disk load balancing?\n\t\t\t\t 0,\/\/maxCacheAge     ,\n\t\t\t\t 0 , \/\/ *(key_t *)cacheKey        ,\n\t\t\t\t RDB_ACCESSDB    ,\n\t\t\t\t -1      ) ) { \/\/ minrecsizes\n\t\t\tlog(\"accessdb: multicast send failed\");\n\t\t\tst->m_errno = g_errno;\n\t\t\tm->reset();\n\t\t\tst->m_replies++;\n\t\t}\n\t}\n\n\t\/\/ return false if blocked\n\tif ( st->m_replies < st->m_requests ) return false;\n\n\t\/\/ we did not block\n\tgotMulticastReplyWrapperaa ( st , NULL );\n\t\/\/ i guess no blocking?\n\treturn true;\n}\n\nvoid gotMulticastReplyWrapperaa ( void *state , void *state2 ) {\n\n\tStateaa *st = (Stateaa *)state;\n\t\/\/ count it\n\tst->m_replies++;\n\t\/\/ return if awaiting more replies\n\tif ( st->m_replies < st->m_requests ) return;\n\n\tkey128_t sk;\n\tkey128_t ek;\n\tsk.setMin();\n\tek.setMax();\n\tchar *startKey = (char *)&sk;\n\tchar *endKey   = (char *)&ek;\n\tint32_t ks = sizeof(key128_t);\n\tint32_t ds = sizeof(AccessRec) - ks;\n\n\t\/\/ ptrs to fbrecs that have your widgetid\n\tSafeBuf ptrBuf;\n\n\t\/\/ store page into here\n\tSafeBuf sb;\n\n\t\/\/ each mutlicast reply is a list\n\tRdbList lists[MAX_HOSTS];\n\tRdbList *plists[MAX_HOSTS];\n\tchar    *m_freeMe    [MAX_HOSTS];\n\tint32_t     m_freeMeSize[MAX_HOSTS];\n\n\tint32_t numLists = g_hostdb.getNumGroups();\n\tfor ( int32_t i = 0 ; i < numLists ; i++ ) {\n\t\t\/\/ get the multicast for this group, int16_tcut\n\t\tMulticast *m = &st->m_mcasts[i];\n\t\t\/\/ get the reply\n\t\tint32_t  replySize;\n\t\tint32_t  replyMaxSize;\n\t\tbool  freeReply;\n\t\tchar *reply = m->getBestReply ( &replySize , \n\t\t\t\t\t\t&replyMaxSize , \n\t\t\t\t\t\t&freeReply );\n\t\t\/\/ save it for freeing\n\t\tif ( freeReply ) {\n\t\t\tm_freeMe     [i] = reply;\n\t\t\tm_freeMeSize [i] = replyMaxSize;\n\t\t}\n\t\telse {\n\t\t\tm_freeMe[i] = NULL;\n\t\t}\n\n\t\t\/\/ first is size of the first list\n\t\tchar *p = reply;\n\t\tchar *pend = p + replySize;\n\t\tint32_t firstListSize = *(int32_t *)p;\n\t\tp += 4;\n\n\n\t\tlists[i].set ( p,\n\t\t\t       firstListSize,\n\t\t\t       p,\n\t\t\t       firstListSize,\n\t\t\t       startKey,\n\t\t\t       endKey,\n\t\t\t       ds,\n\t\t\t       false,\n\t\t\t       false,\n\t\t\t       ks);\n\t\tplists[i] = &lists[i];\n\n\t\t\/\/ a facebook list follows that\n\t\tp += firstListSize;\n\n\t\tint32_t secondListSize = pend - p;\n\n\n\t\t\/\/ point to each facebook rec\n\t\tRdbList fblist;\n\t\tfblist.set ( p,\n\t\t\t     secondListSize,\n\t\t\t     p,\n\t\t\t     secondListSize,\n\t\t\t     startKey,\n\t\t\t     endKey,\n\t\t\t     -1, \/\/ fixeddatasize\n\t\t\t     false,\/\/ owndata?\n\t\t\t     false, \/\/ usehalfkeys?\n\t\t\t     sizeof(key96_t) ); \/\/ facebookdb keysize\n\t\t\/\/ scan list to add ptrs \n\t\tfor ( ; ! fblist.isExhausted() ; fblist.skipCurrentRec() ) {\n\t\t\t\/\/ point to it\n\t\t\tFBRec *fbrec = (FBRec *)fblist.getCurrentRec();\n\t\t\tptrBuf.pushLong((int32_t)fbrec);\n\t\t}\n\t}\n\n\t\/\/ print the header from PageEvents.cpp\n\tprintHtmlHeader ( sb , \"My Account\", 1 ,NULL,true);\n\tchar *path = \"\/account.html\";\n\tprintBlackBar ( sb , &st->m_msgfb, path , st->m_socket->m_ip,1,0,NULL);\n\n\tprintPageTitle (sb,\"<nobr>My Account<\/nobr>\");\n\n\tsb.safePrintf(\"<div style=width:780px;>\");\n\n\t\/\/int64_t widgetId = st->m_request.m_widgetId;\n\n\t\/*\n\tsb.safePrintf(\"<br>\"\n\t\t      \"<div style=\\\"border:2px solid black\\\">\"\n\t\t      \"<table \"\n\t\t      \"width=100%% cellspacing=0 border=0>\"\n\t\t      \"<tr><td class=grad1 height=30px>\" \/\/ <td width=10px>\"\n\t\t      \/\/\"<img src=\/eventguru.png width=64 height=64>\"\n\t\t      \/\/\"<\/td>\"\n\t\t      \/\/\"<td width=100%%>\"\n\t\t      \"<center>\"\n\t\t      \"<font color=black>\"\n\t\t      \"<b>\"\n\t\t      \"Displaying traffic data for the widget of id \"\n\t\t      \"<a href=http:\/\/www.facebook.com\/%\"UINT64\">%\"UINT64\"<\/a>\"\n\t\t      \"<\/b>\"\n\t\t      \"<\/font>\"\n\t\t      \"<\/center>\"\n\t\t      \"<\/td><\/tr><\/table>\"\n\t\t      \"<\/div>\"\n\t\t      \"<br>\"\n\t\t      , widgetId\n\t\t      , widgetId\n\t\t      );\n\t*\/\n\n\t\/\/ widgetmaster table\n\tsb.safePrintf(\"<table border=1 width=780px; cellpadding=6 \"\n\t\t      \"cellspacing=3>\"\n\t\t      \"<tr><td colspan=10 class=grad4>\"\n\t\t      \"<center>\"\n\t\t      \"<font style=color:white;>\"\n\t\t      \"<b>Personal Info<\/b>\"\n\t\t      \"<\/font>\"\n\t\t      \"<\/center><\/td><\/tr>\"\n\t\t      \"<tr><td>Your Name<\/td>\"\n\t\t      \"<td>%s<\/td><\/tr>\"\n\t\t      \"<tr><td>Your Facebook ID<\/td>\"\n\t\t      \"<td>\"\n\t\t      \"<a href=\\\"http:\/\/www.facebook.com\/%\"INT64\"\\\">%\"INT64\"<\/a>\"\n\t\t      \"<\/td><\/tr>\"\n\t\t      \"<tr><td>Your Widget ID<\/td>\"\n\t\t      \"<td>\"\n\t\t      \"<a href=\\\"http:\/\/www.facebook.com\/%\"INT64\"\\\">%\"INT64\"<\/a>\"\n\t\t      \"<\/td><\/tr>\"\n\t\t      \"<\/table><br>\"\n\t\t      ,st->m_msgfb.m_fbrecPtr->ptr_name\n\t\t      ,st->m_msgfb.m_fbId\n\t\t      ,st->m_msgfb.m_fbId\n\t\t      ,st->m_msgfb.m_fbId\n\t\t      ,st->m_msgfb.m_fbId\n\t\t      );\n\n\t\/\/ print out a calendar table of dates...\n\t\/\/ really you can just pick a start time and that is when we\n\t\/\/ start reading from.\n\t\/\/ but also be able to select a month...\n\t\/\/ maybe print 5 calendars, with the one in the middle\n\t\/\/ being the current month.\n\tprintCalendars ( sb , st->m_request.m_startDate );\n\n\t\/\/ display table of facebook converts widgetmaster did\n\tsb.safePrintf(\"<table border=1 width=780px; cellpadding=6 \"\n\t\t      \"cellspacing=3>\"\n\t\t      \"<tr><td colspan=10 class=grad4>\"\n\t\t      \"<center>\"\n\t\t      \"<font style=color:white;>\"\n\t\t      \"<b>Event Guru Logins<\/b>\"\n\t\t      \"<\/font>\"\n\t\t      \"<\/center><\/td><\/tr>\"\n\t\t      \"<tr><td><nobr>Login Time (UTC)<\/nobr><\/td>\"\n\t\t      \"<td><nobr>Last Login IP<\/nobr><\/td>\"\n\t\t      \"<td>Country<\/td>\"\n\t\t      \"<td>Facebook ID<\/td>\"\n\t\t      \"<td>Widget ID<\/td>\"\n\t\t      \"<td><nobr>Payout*<\/nobr><\/td>\"\n\t\t      \"<\/tr>\" );\n\tFBRec **ppp = (FBRec **)ptrBuf.getBufStart();\n\tint32_t n = ptrBuf.length() \/ 4;\n\tfor ( int32_t i = 0 ; i < n ; i++ ) {\n\t\tFBRec *fbrec = ppp[i];\n\t\t\/\/ skip if its you! you can't visit your own widget...\n\t\tif ( fbrec->m_fbId == fbrec->m_originatingWidgetId ) continue;\n\t\tstruct tm *timeStruct = gmtime ( &fbrec->m_firstFacebookLogin);\n\t\tchar time[256];\n\t\tstrftime ( time , 256 , \"%b %e %T %Y\", timeStruct );\n\t\tfloat cash = 0.00;\n\t\tcash = 1.00;\n\t\tsb.safePrintf(\"<tr>\"\n\t\t\t      \"<td><nobr>%s<\/nobr><\/td>\"\n\t\t\t      \"<td>%s<\/td>\"\n\t\t\t      \"<td>%s<\/td>\"\n\t\t\t      \"<td><a href=http:\/\/www.facebook.com\/%\"UINT64\">\"\n\t\t\t      \"%\"UINT64\"<\/a><\/td>\"\n\t\t\t      \"<td>%\"UINT64\"<\/td>\"\n\t\t\t      \"<td>$%.02f<\/td>\"\n\t\t\t      \"<\/tr>\"\n\t\t\t      ,time \/\/ fbrec->m_firstFacebookLogin\n\t\t\t      ,iptoa(fbrec->m_lastLoginIP)\n\t\t\t      ,\"US\"\n\t\t\t      ,fbrec->m_fbId\n\t\t\t      ,fbrec->m_fbId\n\t\t\t      ,fbrec->m_originatingWidgetId\n\t\t\t      ,cash\n\t\t\t      );\n\t}\n\tsb.safePrintf(\"<\/table><br>\");\n\n\tsb.safePrintf(\"<\/div>\");\n\n\tint32_t minRecSizes = st->m_request.m_minRecSizes;\n\n\t\/\/ merge them together into a single list\n\tRdbList final;\n\t\/\/ owndata must be true for merge_r to work!\n\tfinal.set ( NULL,0,NULL,0,startKey,endKey,ds,true,false,ks);\n\tfinal.prepareForMerge( plists,numLists,minRecSizes);\n\tfinal.merge_r ( plists , \n\t\t\tnumLists ,\n\t\t\tstartKey,\n\t\t\tendKey ,\n\t\t\t10000 ,\n\t\t\ttrue , \/\/ remove neg?\n\t\t\tRDB_ACCESSDB,\n\t\t\tNULL,\n\t\t\tNULL,\n\t\t\tNULL,\n\t\t\tfalse,\n\t\t\t0 ); \/\/ niceness\n\t\n\t\/\/\n\t\/\/ print out first 100\n\t\/\/\n\n\t\/\/ table headers\n\tsb.safePrintf ( \"<table cellpadding=4 width=780px border=1>\"\n\t\t\t\"<tr><td colspan=10 class=grad4>\"\n\n\t\t\t\"<center>\"\n\t\t\t\"<font style=color:white;>\"\n\t\t\t\"<b>Event Guru Hits<\/b>\"\n\t\t\t\"<\/font>\"\n\t\t\t\"<\/center>\"\n\n\t\t\t\"<\/td><\/tr>\"\n\t\t\t\"<tr>\"\n\t\t\t\"<td><nobr>User Access Time (UTC)<\/nobr><\/td>\"\n\t\t\t\"<td>User IP<\/td>\"\n\t\t\t\"<td>User Facebook ID<\/td>\"\n\t\t\t\"<td>Widget ID<\/td>\"\n\t\t\t\"<\/tr>\"\n\t\t\t);\n\n\tfinal.resetListPtr();\n\tfor ( ;  ! final.isExhausted() ; final.skipCurrentRecord() ) {\n\t\tchar *rec = final.getCurrentRec();\n\t\tAccessRec *ar = (AccessRec *)rec;\n\t\tuint64_t timestamp = ar->m_key128.n1;\n\t\tuint64_t widgetId = ar->m_key128.n0;\n\t\t\/\/ overrun the delbit\n\t\twidgetId >>= 1;\n\t\t\/\/ swap them? we do two different types of lookups.\n\t\t\/\/ if widgetid is 1, which means *any* then the starttime\n\t\t\/\/ leads, otherwise the widgetid leads.\n\t\tif ( timestamp & 0x8000000000000000LL ) {\n\t\t\ttimestamp &= 0x7fffffffffffffffLL;\n\t\t\tint64_t tmp = widgetId;\n\t\t\twidgetId = timestamp;\n\t\t\ttimestamp = tmp;\n\t\t}\n\t\tint32_t timestamp32 = timestamp \/ 1000;\n\t\tstruct tm *timeStruct = gmtime ( &timestamp32 );\n\t\tchar time[256];\n\t\tstrftime ( time , 256 , \"%b %e %T %Y\", timeStruct );\n\t\tsb.safePrintf(\"<tr>\"\n\t\t\t      \/\/\"<td>%\"UINT64\"<\/td>\"\n\t\t\t      \"<td><nobr>%s<\/nobr><\/td>\"\n\t\t\t      \"<td>%s<\/td>\"\n\t\t\t      \"<td>\"\n\t\t\t      , time\n\t\t\t      , iptoa(ar->m_ip)\n\t\t\t      );\n\t\tif ( ar->m_fbId )\n\t\t\tsb.safePrintf(\"<a href=http:\/\/www.facebook.\"\n\t\t\t\t      \"com\/%\"UINT64\">%\"UINT64\"\"\n\t\t\t\t      \"<\/a>\"\n\t\t\t\t      , ar->m_fbId\n\t\t\t\t      , ar->m_fbId\n\t\t\t\t      );\n\t\telse\n\t\t\tsb.safePrintf(\"%\"UINT64\"\" , ar->m_fbId );\n\n\t\tsb.safePrintf ( \"<\/td>\"\n\t\t\t\t\"<td>%\"UINT64\"<\/td>\"\n\t\t\t\t\"<\/tr>\"\n\t\t\t\t, widgetId\n\t\t\t\t);\n\t}\n\n\t\/\/ end table\n\tsb.safePrintf ( \"<\/table><br>\" );\n\n\tprintHtmlTail ( &sb , &st->m_msgfb, false );\n\t\n\t\/\/ free the multicast replies here\n\tfor ( int32_t i = 0 ; i < numLists ; i++ ) {\n\t\tif ( ! m_freeMe[i] ) continue;\n\t\tmfree ( m_freeMe[i] ,m_freeMeSize[i],\"acmcrep\");\n\t}\n\n\t\/\/ make a cookie in case they just logged in through this page!\n\t\/\/ otherwise the login doesn't \"stick\"\n\tSafeBuf cb;\n\tif ( st->m_msgfb.m_fbId )\n\t\tcb.safePrintf(\"Set-Cookie: fbid=%\"UINT64\";\\r\\n\",\n\t\t\t      st->m_msgfb.m_fbId);\n\tchar *cookiePtr = NULL;\n\tif ( cb.length() ) cookiePtr = cb.getBufStart();\n\t\n\n\tTcpSocket *s = st->m_socket;\n\n\t\/\/ nuke the state now\n\tmdelete ( st , sizeof(Stateaa) , \"Stateaa\" );\n\tdelete (st);\n\n\tint32_t bufLen = sb.length();\n\t\/\/ . send this page\n\t\/\/ . encapsulates in html header and tail\n\t\/\/ . make a Mime\n\tg_httpServer.sendDynamicPage ( s, sb.getBufStart(), bufLen ,\n\t\t\t\t       0 , \/\/ cachetime in secs\n\t\t\t\t       false , \/\/ postreply?\n\t\t\t\t       \"text\/html\", \/\/ content type\n\t\t\t\t       -1, \/\/ http status -1->200\n\t\t\t\t       cookiePtr,\n\t\t\t\t       \"utf-8\" );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ HANDLER FUNCTION\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass Stateab {\npublic:\n\tint32_t m_startDate;\n\tint64_t m_widgetId;\n\tint32_t m_minRecSizes;\n\tUdpSlot *m_slot;\n\tint32_t m_niceness;\n\n\tMsg5 m_msg5;\n\tRdbList m_accessList;\n\tRdbList m_facebookList;\n\tkey96_t m_fbstartKey;\n\t\/\/ store facebook recs in here that match widgetid\n\tSafeBuf m_retBuf;\n};\n\nstatic void gotAccessListWrapper ( void *state , RdbList *list, Msg5 *msg5 ) ;\n\n\nvoid handleRequestaa  ( UdpSlot *slot , int32_t niceness ) {\n\n\tStateab *st ;\n\ttry { st = new (Stateab); }\n\tcatch ( ... ) { \n\t\tg_errno = ENOMEM;\n\t\tlog(\"Stateab: new(%i): %s\",sizeof(Stateab),mstrerror(g_errno));\n\t\tg_udpServer.sendErrorReply ( slot, g_errno ); \n\t\treturn;\n\t}\n\tmnew ( st , sizeof(Stateab) , \"Stateab\" );\n\n\t\/\/ . read in beginning at start key using msg5.\n\t\/\/ . limit to provided widget id\n\tMsgaaRequest *req  = (MsgaaRequest *)slot->m_readBuf;\n\n\t\/\/ save widgetid, startdate, minrecsizes, etc.\n\tst->m_startDate   = req->m_startDate;\n\tst->m_widgetId    = req->m_widgetId;\n\tst->m_minRecSizes = req->m_minRecSizes;\n\tst->m_slot        = slot;\n\tst->m_niceness    = niceness;\n\n\t\/\/ int16_tcut\n\tint64_t wgid = req->m_widgetId;\n\t\/\/ convert into milliseconds\n\tint64_t timestamp = ((int64_t)req->m_startDate) * 1000;\n\t\/\/ back 7 days from now if this is zero\n\tif ( req->m_startDate == 0 ) {\n\t\ttimestamp = gettimeofdayInMillisecondsGlobalNoCore(); \n\t\t\/\/ back 7 days from now\n\t\ttimestamp -= 7*86400*1000;\n\t}\n\n\tint64_t longTime = 86400LL*365LL*1000LL*10; \/\/ 10 years in millisecs\n\t\/\/ use the 2nd type of key... those have widgetid first and then\n\t\/\/ the timestamp\n\tkey128_t startKey  = g_accessdb.makeKey2 ( timestamp ,wgid );\n\tkey128_t endKey    = g_accessdb.makeKey2 ( timestamp + longTime, wgid);\n\t\/\/ widget id of 0 means ANY widget\n\tif ( wgid == 0 ) {\n\t\tstartKey = g_accessdb.makeKey1(timestamp , 0 );\n\t\tendKey   = g_accessdb.makeKey1(timestamp + longTime, 0 );\n\t}\n\t\/\/ lookup accessdb records from that time going forward\n\tif ( ! st->m_msg5.getList ( RDB_ACCESSDB ,\n\t\t\t\t    \"\", \/\/ m_coll          ,\n\t\t\t\t    &st->m_accessList ,\n\t\t\t\t    &startKey      ,\n\t\t\t\t    &endKey        ,\n\t\t\t\t    st->m_minRecSizes   ,\n\t\t\t\t    true          , \/\/ includeTree\n\t\t\t\t    false         , \/\/ add to cache?\n\t\t\t\t    0             , \/\/ max cache age\n\t\t\t\t    0             , \/\/ startFileNum  ,\n\t\t\t\t    -1            , \/\/ numFiles      ,\n\t\t\t\t    st           , \/\/ state\n\t\t\t\t    gotAccessListWrapper , \/\/ callback\n\t\t\t\t    st->m_niceness ,\n\t\t\t\t    false         )) \/\/ err correction?\n\t\treturn;\n\t\/\/ we got it without blocking\n\tgotAccessListWrapper ( st , NULL, NULL );\n}\n\nstatic bool scanLoop ( Stateab *st ) ;\n\nstatic void sendListsBack ( Stateab *state );\n\n\nvoid gotAccessListWrapper ( void *state , RdbList *list, Msg5 *msg5 ) {\n\n\tStateab *st = (Stateab *)state;\n\n\t\/\/ store size of this list since we will be adding the\n\t\/\/ facebook into m_retBuf right after. (firstListSize)\n\tst->m_retBuf.pushLong ( st->m_accessList.m_listSize );\n\t\/\/ now store list from what we read into retBuf\n\tst->m_retBuf.safeMemcpy ( st->m_accessList.getList() ,\n\t\t\t\t  st->m_accessList.m_listSize );\n\t\t\t\t  \n\t\/\/ reset start key for scan\n\tst->m_fbstartKey.setMin();\n\t\/\/ . returns false if blocked, true otherwise\n\t\/\/ . scan ALL facebookdb for recs originating from this widgetid\n\tif ( ! scanLoop( st ) ) return;\n\t\/\/ it didn't block\n\tsendListsBack ( st );\n}\n\n\nstatic void gotScanListWrapper ( void *state, RdbList *list , Msg5 *msg5 ) ;\nstatic void gotScanList ( Stateab *st ) ;\n\n\/\/ . scan facebookdb and get every facebookid, and couple it with the\n\/\/   time we gotta send the email\n\/\/ . sort by that in emailTree\n\/\/ . re-scan facebookdb every few hours in case of new entries or if\n\/\/   someone updates their email\n\/\/ . i would also call addToEmailTree if a new facebookdb rec comes in.\n\/\/   perhaps do that from Rdb.cpp?\n\/\/ . returns false if blocked true otherwise\nbool scanLoop ( Stateab *st ) {\n\n\tkey96_t endKey   ;\n\tendKey.setMax();\n\t\/\/ get a meg at a time\n\tint32_t minRecSizes = 1024*1024;\n\tkey96_t oldk; oldk.setMin();\n\n loop:\n\t\/\/ use msg5 to get the list, should ALWAYS block since no threads\n\tif ( ! st->m_msg5.getList ( RDB_FACEBOOKDB    ,\n\t\t\t\t    \"\", \/\/ m_coll          ,\n\t\t\t\t    &st->m_facebookList ,\n\t\t\t\t    &st->m_fbstartKey      ,\n\t\t\t\t    &endKey        ,\n\t\t\t\t    minRecSizes   ,\n\t\t\t\t    true          , \/\/ includeTree\n\t\t\t\t    false         , \/\/ add to cache?\n\t\t\t\t    0             , \/\/ max cache age\n\t\t\t\t    0             , \/\/ startFileNum  ,\n\t\t\t\t    -1            , \/\/ numFiles      ,\n\t\t\t\t    st            , \/\/ state\n\t\t\t\t    gotScanListWrapper , \/\/ callback\n\t\t\t\t    st->m_niceness ,\n\t\t\t\t    false         )) \/\/ err correction?\n\t\t\/\/ return false if we blocked\n\t\treturn false;\n\t\/\/ stuff the m_emailTree with some data based on m_list\n\tgotScanList ( st );\n\t\/\/ if something, get more\n\tif ( ! st->m_facebookList.isEmpty() ) goto loop;\n\t\/\/ i guess we did not block?\n\treturn true;\n}\n\nvoid gotScanListWrapper ( void *state, RdbList *list , Msg5 *msg5 ) {\n\t\/\/ use this\n\tStateab *st = (Stateab *)state;\n\t\/\/ this never blocks\n\tgotScanList ( st );\n\t\/\/ and resume the loop. return if it blocked.\n\tif ( ! scanLoop ( st ) ) return;\n\t\/\/ alldone\n\tsendListsBack ( st );\n}\n\n\nvoid gotScanList ( Stateab *st ) {\n\n\t\/\/int32_t now = getTimeGlobal();\n\t\/\/int32_t dayStart = now  - ( now % 86400 );\n\n\tif ( st->m_facebookList.isEmpty() ) return;\n\n\t\/\/ loop over entries in list\n\tfor ( st->m_facebookList.resetListPtr() ; \n\t      ! st->m_facebookList.isExhausted() ;\n\t      st->m_facebookList.skipCurrentRecord() ) {\n\t\t\/\/ get it\n\t\tchar *drec = st->m_facebookList.getCurrentRec();\n\t\tint32_t drecSize = st->m_facebookList.getCurrentRecSize();\n\t\t\/\/ sanity check. delete key?\n\t\tif ( (drec[0] & 0x01) == 0x00 ) continue;\n\t\t\/\/ get widgetit\n\t\tFBRec *fr = (FBRec *)drec;\n\t\t\/\/ but allow widget id of 0 through if its set to 1\n\t\tint64_t wgid = fr->m_originatingWidgetId;\n\t\tif ( wgid == 0 ) wgid = 1;\n\t\t\/\/ a zero widgetid means any! a one means came from no widget.\n\t\tif ( st->m_widgetId && wgid != st->m_widgetId ) continue;\n\t\t\/\/ copy over to same list\n\t\tst->m_retBuf.safeMemcpy ( drec , drecSize );\n\t}\n\tst->m_fbstartKey = *(key96_t *)st->m_facebookList.getLastKey();\n\tst->m_fbstartKey += (uint32_t) 1;\n\t\/\/ watch out for wrap around\n\t\/\/if ( startKey < *(key96_t *)list.getLastKey() ) return;\n}\n\n\n\nvoid sendListsBack ( Stateab *st ) {\n\n\tchar *data = st->m_retBuf.getBufStart();\n\tint32_t  dataSize = st->m_retBuf.length();\n\tint32_t  allocSize = st->m_retBuf.getCapacity();\n\n\t\/\/ release it so udpserver can free it\n\tst->m_retBuf.detachBuf();\n\n\t\/\/ save slot\n\tUdpSlot *slot = st->m_slot;\n\n\t\/\/ nuke the state now\n\tmdelete ( st , sizeof(Stateab) , \"stateab\" );\n\tdelete (st);\n\t\n\tg_udpServer.sendReply_ass ( data            ,\n\t\t\t\t    dataSize        ,\n\t\t\t\t    data            ,\n\t\t\t\t    allocSize       ,\n\t\t\t\t    slot            ,\n\t\t\t\t    60              ,\n\t\t\t\t    NULL            ,\n\t\t\t\t    NULL , \/\/ doneSending_ass ,\n\t\t\t\t    -1              ,\n\t\t\t\t    -1              ,\n\t\t\t\t    true            );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ the calendar for the page accessdb\n\/\/\n\/\/\/\/\/\/\/\/\/\/\n\n\/\/ . print 5 calendars in a row, with current one in the middle\n\/\/ . all are in UTC\nbool printCalendars ( SafeBuf &sb , int32_t startDate ) {\n\t\/\/ parse it up\n\tint32_t now = startDate; \/\/ getTimeGlobalNoCore();\n\tstruct tm *timeStruct = gmtime ( &now );\n\n\t\/\/ get month number (0 to 11)\n\tint32_t thisMonth = timeStruct->tm_mon; \/\/ 0-11\n\tint32_t thisDay   = timeStruct->tm_mday;\n\tint32_t thisYear  = timeStruct->tm_year + 1900;\n\n\tint32_t prevMonth1;\n\tint32_t prevYear1;\n\tint32_t postMonth1;\n\tint32_t postYear1;\n\n\tprevMonth1 = thisMonth - 1;\n\tprevYear1  = thisYear;\n\tif ( prevMonth1 < 0 ) {\n\t\tprevMonth1 += 12;\n\t\tprevYear1--;\n\t}\n\n\tpostMonth1 = thisMonth + 1;\n\tpostYear1  = thisYear;\n\tif ( postMonth1 >= 12 ) {\n\t\tpostMonth1 -= 12;\n\t\tprevYear1++;\n\t}\n\n\tsb.safePrintf(\"<table border=0 width=780px; cellpadding=6 \"\n\t\t      \"cellspacing=3 class=grad1>\"\n\t\t      \"<tr><td colspan=10 class=grad4>\"\n\t\t      \"<center>\"\n\t\t      \"<font style=color:white;>\"\n\t\t      \"<b>Select a Date<\/b>\"\n\t\t      \"<\/font>\"\n\t\t      \"<\/center><\/td><\/tr>\"\n\t\t      );\n\n\tsb.safePrintf(\"<tr><td>\" );\n\n\tprintCalendar ( sb , 0 , prevMonth1 , prevYear1 );\n\n\tsb.safePrintf(\"<\/td><td>\");\n\n\tprintCalendar ( sb , thisDay , thisMonth , thisYear );\n\n\tsb.safePrintf(\"<\/td><td>\");\n\n\tprintCalendar ( sb , 0 , postMonth1 , postYear1 );\n\n\tsb.safePrintf(\"<\/td><\/tr><\/table><br>\");\n\n\treturn true;\n}\n\n\/\/ \"now\" is from the msg40 we used\nbool printCalendar ( SafeBuf &sb ,\n\t\t     int32_t showDay,\n\t\t     int32_t showMonth,\n\t\t     int32_t showYear ) {\n\n\n\t\/\/ compute show dow\n\tstruct tm tss;\n\ttss.tm_mon  = showMonth;\n\ttss.tm_mday = 1;\n\ttss.tm_sec = 0;\n\ttss.tm_min = 0;\n\ttss.tm_hour = 0;\n\ttss.tm_year = showYear - 1900;\n\ttime_t mt = mktime ( &tss );\n\t\/\/ now get dow of the first day of this month\n\tstruct tm *tt = gmtime ( &mt );\n\tint32_t firstDayOfWeek = tt->tm_wday; \/\/ 0-6\n\t\/\/ this is that day\n\ttime_t startDate = mt;\n\n\n\t\/\/ get today's month\/day\/year\n\tint32_t now = getTimeGlobalNoCore();\n\tstruct tm *nt = gmtime ( &now );\n\tint32_t nowDay   = nt->tm_mday;\n\tint32_t nowMonth = nt->tm_mon;\n\tint32_t nowYear  = nt->tm_year + 1900;\n\n\t\n\t\/\/ we got days per month. leap year?\n\tint32_t daysInMonth = getNumDaysInMonth ( showMonth , showYear );\n\n\t\/\/ prev month abbr\n\tchar *nextStr, *str, *prevStr;\n\tif ( showMonth == 0  ) { prevStr = \"Dec\"; str=\"Jan\"; nextStr = \"Feb\"; }\n\tif ( showMonth == 1  ) { prevStr = \"Jan\"; str=\"Feb\"; nextStr = \"Mar\"; }\n\tif ( showMonth == 2  ) { prevStr = \"Feb\"; str=\"Mar\"; nextStr = \"Apr\"; }\n\tif ( showMonth == 3  ) { prevStr = \"Mar\"; str=\"Apr\"; nextStr = \"May\"; }\n\tif ( showMonth == 4  ) { prevStr = \"Apr\"; str=\"May\"; nextStr = \"Jun\"; }\n\tif ( showMonth == 5  ) { prevStr = \"May\"; str=\"Jun\"; nextStr = \"Jul\"; }\n\tif ( showMonth == 6  ) { prevStr = \"Jun\"; str=\"Jul\"; nextStr = \"Aug\"; }\n\tif ( showMonth == 7  ) { prevStr = \"Jul\"; str=\"Aug\"; nextStr = \"Sep\"; }\n\tif ( showMonth == 8  ) { prevStr = \"Aug\"; str=\"Sep\"; nextStr = \"Oct\"; }\n\tif ( showMonth == 9  ) { prevStr = \"Sep\"; str=\"Oct\"; nextStr = \"Nov\"; }\n\tif ( showMonth == 10 ) { prevStr = \"Oct\"; str=\"Nov\"; nextStr = \"Dec\"; }\n\tif ( showMonth == 11 ) { prevStr = \"Nov\"; str=\"Dec\"; nextStr = \"Jan\"; }\n\n\tint32_t prevYear  = showYear;\n\tint32_t prevMonth = showMonth - 1;\n\tif ( prevMonth < 0 ) {\n\t\tprevMonth = 11;\n\t\tprevYear--;\n\t}\n\tint32_t nextYear = showYear;\n\tint32_t nextMonth = showMonth + 1;\n\tif ( nextMonth >= 12 ) {\n\t\tnextMonth = 0;\n\t\tnextYear++;\n\t}\n\n\t\/\/ print print out calendar header\n\tsb.safePrintf(\"<table cellspacing=0 cellpadding=3>\"\n\t\t      \"<tr>\"\n\t\t      \"<td>\"\n\t\t      \/\/\"<font size=-2>\"\n\t\t      \/\/\"<a \"\n\t\t      \/\/\"style=\\\"color:black\\\" \"\n\t\t      \/\/\"href=\/traffic?displayyear=%\"INT32\"&displaymonth=%\"INT32\">%s<\/a>\"\n\t\t      \/\/\"<\/font>\"\n\t\t      \"<\/td>\"\n\t\t      \"<td colspan=5><center>%s %\"INT32\"<\/center><\/td>\"\n\t\t      \"<td>\"\n\t\t      \/\/\"<font size=-2>\"\n\t\t      \/\/\"<a \"\n\t\t      \/\/\"style=\\\"color:black\\\" \"\n\t\t      \/\/\"href=\/traffic?displayyear=%\"INT32\"&displaymonth=%\"INT32\">%s<\/a>\"\n\t\t      \/\/\"<\/font>\"\n\t\t      \"<\/td>\"\n\t\t      \"<\/tr>\\n\"\n\t\t      \"<tr>\"\n\t\t      \"<td>S<\/td>\"\n\t\t      \"<td>M<\/td>\"\n\t\t      \"<td>T<\/td>\"\n\t\t      \"<td>W<\/td>\"\n\t\t      \"<td>T<\/td>\"\n\t\t      \"<td>F<\/td>\"\n\t\t      \"<td>S<\/td>\"\n\t\t      \"<\/tr>\\n\"\n\t\t      \/\/ cal now for prev month\n\t\t      \/\/, prevYear\n\t\t      \/\/, prevMonth\n\t\t      \/\/, prevStr\n\t\t      , str \n\t\t      , showYear\n\t\t      \/\/ cal now for next month\n\t\t      \/\/, nextYear\n\t\t      \/\/, nextMonth\n\t\t      \/\/, nextStr \n\t\t      );\n\tbool printed = false;\n\tint32_t count = 1;\n\n\tbool showCursor = true;\n\n\t\/\/ print out days of the week header\n\tfor ( int32_t i = 0 ; i < 35 ; i++ ) {\n\t\tif ( i % 7 == 0 )\n\t\t\tsb.safePrintf(\"<tr>\");\n\t\t\/\/ is it today?\n\t\tif ( count == nowDay && \n\t\t     showMonth == nowMonth &&\n\t\t     showYear == nowYear &&\n\t\t     i>= firstDayOfWeek && \n\t\t     showCursor )\n\t\t\tsb.safePrintf(\"<td class=cal \"\n\t\t\t\t      \"style=background-color:yellow;\"\n\t\t\t\t      \"color:black\");\n\t\telse if ( count == showDay && \n\t\t\t  \/\/clockMonth == showMonth && \n\t\t\t  \/\/clockYear == showYear &&\n\t\t\t  i>= firstDayOfWeek )\n\t\t\tsb.safePrintf(\"<td class=cal \"\n\t\t\t\t      \"style=background-color:red\");\n\t\telse\n\t\t\tsb.safePrintf(\"<td class=cal\");\n\t\t\/\/ do not start printing until first day of month\n\t\tif ( (i >= firstDayOfWeek || printed) &&\n\t\t     count <= daysInMonth ) {\n\t\t\tprinted = true;\n\t\t\t\/\/lo clockSet2=getYearMonthStart(showYear,showMonth+1);\n\t\t\t\/\/ add day to it\n\t\t\t\/\/clockSet2 += (count-1) * 86400;\n\t\t\t\/\/ clockSet is in utc...\n\t\t\t\/\/clockSet2 -= timeZoneOffset * 3600;\n\t\t\t\/\/ end the <td>\n\t\t\t\/*\n\t\t\tsb.safePrintf(\" onclick=\\\"\"\n\t\t\t\t      \/\/ set hidden tag clockset val\n\t\t\t\t      \/\/ set all to gray if not yellow\n\t\t\t\t      \/\/ set clicked to red if not yellow\n\t\t\t\t      \"top.window.href='\/traffic?sd=%\"UINT32\"';\\\">\"\n\t\t\t\t      , startDate + (count-1)*86400\n\t\t\t\t      );\n\t\t\t*\/\n\t\t\tsb.safePrintf(\"><a href=\/account.html?sd=%\"UINT32\">%\"INT32\"<\/a>\"\n\t\t\t\t      \"<\/td>\" \n\t\t\t\t      , startDate + (count-1)*86400\n\t\t\t\t      , count );\n\t\t\tcount++;\n\t\t}\n\t\telse \n\t\t\tsb.safePrintf(\"><\/td>\");\n\t\tif ( (i+1) % 7 == 0 )\n\t\t\tsb.safePrintf(\"<\/tr>\\n\");\n\t}\n\tsb.safePrintf(\"<\/table>\");\n\treturn true;\n}\n","avg_line_length":27.7135371179,"max_line_length":81,"alphanum_fraction":0.5901928652,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":27079,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-Source-Code"],"max_stars_count":3.0,"content":"\/*\n    Based off :\n    1) ESPHelper.cpp - Copyright (c) 2017 ItKindaWorks Inc All right reserved. github.com\/ItKindaWorks\n    2) https:\/\/github.com\/JoaoLopesF\/ESP8266-RemoteDebug-Telnet\n\n*\/\n\n#include \"ESPHelper.h\"\n\nWiFiServer telnetServer(TELNET_PORT);\n\n\/\/initializer with single netInfo network\nESPHelper::ESPHelper(netInfo * startingNet) {\n    \/\/disconnect from and previous wifi networks\n    WiFi.softAPdisconnect();\n    WiFi.disconnect();\n\n    \/\/setup current network information\n    _currentNet = *startingNet;\n\n    \/\/validate various bits of network\/MQTT info\n\n    \/\/network pass\n    if (_currentNet.pass[0] == '\\0') {\n        _passSet = false;\n    } else {\n        _passSet = true;\n    }\n\n    \/\/ssid\n    if (_currentNet.ssid[0] == '\\0') {\n        _ssidSet = false;\n    } else {\n        _ssidSet = true;\n    }\n\n    \/\/mqtt host\n    if (_currentNet.mqttHost[0] == '\\0') {\n        _mqttSet = false;\n    } else {\n        _mqttSet = true;\n    }\n\n    \/\/mqtt port\n    if (_currentNet.mqttPort == 0) {\n        _currentNet.mqttPort = 1883;\n    }\n\n    \/\/mqtt username\n    if (_currentNet.mqttUser[0] == '\\0') {\n        _mqttUserSet = false;\n    } else {\n        _mqttUserSet = true;\n    }\n\n    \/\/mqtt password\n    if (_currentNet.mqttPass[0] == '\\0') {\n        _mqttPassSet = false;\n    } else {\n        _mqttPassSet = true;\n    }\n\n    \/\/disable hopping on single network\n    _hoppingAllowed = false;\n\n    \/\/disable ota by default\n    _useOTA = false;\n}\n\n\/\/start the wifi & mqtt systems and attempt connection (currently blocking)\n\/\/true on: parameter check validated\n\/\/false on: parameter check failed\nbool ESPHelper::begin(const char * hostname) {\n#ifdef USE_SERIAL1\n    Serial1.begin(115200);\n    Serial1.setDebugOutput(true);\n#endif\n\n#ifdef USE_SERIAL\n    Serial.begin(115200);\n    Serial.setDebugOutput(true);\n#endif\n\n    \/\/ set hostname first\n    strcpy(_hostname, hostname);\n    OTA_enable();\n\n    setBoottime(\"<unknown>\");\n\n    if (_ssidSet) {\n        strcpy(_clientName, hostname);\n\n        \/*\n        \/\/ Generate client name based on MAC address and last 8 bits of microsecond counter\n\n        _clientName += \"esp-\";\n        uint8_t mac[6];\n        WiFi.macAddress(mac);\n        _clientName += macToStr(mac);\n        *\/\n\n\/\/ set hostname\n\/\/ can ping by <hostname> or on Windows10 it's <hostname>.\n#if defined(ESP8266)\n        WiFi.hostname(_hostname);\n#elif defined(ESP32)\n        WiFi.setHostname(_hostname);\n#endif\n\n        \/\/set the wifi mode to station and begin the wifi (connect using either ssid or ssid\/pass)\n        WiFi.mode(WIFI_STA);\n        if (_passSet) {\n            WiFi.begin(_currentNet.ssid, _currentNet.pass);\n        } else {\n            WiFi.begin(_currentNet.ssid);\n        }\n\n        \/\/as long as an mqtt ip has been set create an instance of PubSub for client\n        if (_mqttSet) {\n            \/\/make mqtt client use either the secure or non-secure wifi client depending on the setting\n            if (_useSecureClient) {\n                client = PubSubClient(_currentNet.mqttHost, _currentNet.mqttPort, wifiClientSecure);\n            } else {\n                client = PubSubClient(_currentNet.mqttHost, _currentNet.mqttPort, wifiClient);\n            }\n\n            \/\/set the mqtt message callback if needed\n            if (_mqttCallbackSet) {\n                client.setCallback(_mqttCallback);\n            }\n        }\n\n        \/\/define a dummy instance of mqtt so that it is instantiated if no mqtt ip is set\n        else {\n            \/\/make mqtt client use either the secure or non-secure wifi client depending on the setting\n            \/\/(this shouldnt be needed if making a dummy connection since the idea would be that there wont be mqtt in this case)\n            if (_useSecureClient) {\n                client = PubSubClient(\"192.168.1.255\", _currentNet.mqttPort, wifiClientSecure);\n            } else {\n                client = PubSubClient(\"192.168.1.255\", _currentNet.mqttPort, wifiClient);\n            }\n        }\n\n        \/\/ota event handlers\n        ArduinoOTA.onStart([]() { \/* ota start code *\/ });\n        ArduinoOTA.onEnd([]() {\n            \/\/on ota end we disconnect from wifi cleanly before restarting.\n            WiFi.softAPdisconnect();\n            WiFi.disconnect();\n            uint8_t timeout = 0;\n            \/\/max timeout of 2seconds before just dropping out and restarting\n            while (WiFi.status() != WL_DISCONNECTED && timeout < 200) {\n                timeout++;\n            }\n        });\n        ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { \/* ota progress code *\/ });\n        ArduinoOTA.onError([](ota_error_t error) { \/* ota error code *\/ });\n\n        \/\/initially attempt to connect to wifi when we begin (but only block for 2 seconds before timing out)\n        uint8_t timeout = 0; \/\/counter for begin connection attempts\n        while (((!client.connected() && _mqttSet) || WiFi.status() != WL_CONNECTED)\n               && timeout < 200) { \/\/max 2 sec before timeout\n            reconnect();\n            timeout++;\n        }\n\n        \/\/attempt to start ota if needed\n        OTA_begin();\n\n        \/\/ Initialize the telnet server\n        telnetServer.begin();\n        telnetServer.setNoDelay(true);\n\n        \/\/ init command buffer for console commands\n        memset(_command, 0, sizeof(_command));\n\n        consoleShowHelp(); \/\/ show this at bootup\n\n        \/\/mark the system as started and return\n        _hasBegun = true;\n\n        return true;\n    }\n\n    \/\/if no ssid was set even then dont try to begin and return false\n    return false;\n}\n\n\/\/end the instance of ESPHelper (shutdown wifi, ota, mqtt)\nvoid ESPHelper::end() {\n    \/\/ Stop telnet Client & Server\n    if (telnetClient && telnetClient.connected()) {\n        telnetClient.stop();\n    }\n\n    \/\/ Stop server\n    telnetServer.stop();\n\n    OTA_disable();\n    WiFi.softAPdisconnect();\n    WiFi.disconnect();\n\n    uint8_t timeout = 0;\n    while (WiFi.status() != WL_DISCONNECTED && timeout < 200) {\n        timeout++;\n    }\n\n#ifdef USE_SERIAL\n    Serial.flush();\n#endif\n\n#ifdef USE_SERIAL1\n    Serial1.flush();\n#endif\n}\n\n\/\/main loop - should be called as often as possible - handles wifi\/mqtt connection and mqtt handler\n\/\/true on: network\/server connected\n\/\/false on: network or server disconnected\nint ESPHelper::loop() {\n    if (_ssidSet) {\n        \/\/check for good connections and attempt a reconnect if needed\n        if (((_mqttSet && !client.connected()) || setConnectionStatus() < WIFI_ONLY) && _connectionStatus != BROADCAST) {\n            reconnect();\n        }\n\n        \/\/run the wifi loop as long as the connection status is at a minimum of BROADCAST\n        if (_connectionStatus >= BROADCAST) {\n            \/\/run the MQTT loop if we have a full connection\n            if (_connectionStatus == FULL_CONNECTION) {\n                client.loop();\n            }\n\n            \/\/check for whether we want to use OTA and whether the system is running\n            if (_useOTA && _OTArunning) {\n                ArduinoOTA.handle();\n            }\n\n            \/\/if we want to use OTA but its not running yet, start it up.\n            else if (_useOTA && !_OTArunning) {\n                OTA_begin();\n                ArduinoOTA.handle();\n            }\n\n            \/\/ do the telnet stuff\n            consoleHandle();\n\n            return _connectionStatus;\n        }\n    }\n\n    \/\/return -1 for no connection because of bad network info\n    return -1;\n}\n\n\/\/subscribe to a specific topic (does not add to topic list)\n\/\/true on: subscription success\n\/\/false on: subscription failed (either from PubSub lib or network is disconnected)\nbool ESPHelper::subscribe(const char * topic, uint8_t qos) {\n    if (_connectionStatus == FULL_CONNECTION) {\n        \/\/set the return value to the output of subscribe\n        bool returnVal = client.subscribe(topic, qos);\n\n        \/\/loop mqtt client\n        client.loop();\n        return returnVal;\n    }\n\n    \/\/if not fully connected return false\n    else {\n        return false;\n    }\n}\n\n\/\/add a topic to the list of subscriptions and attempt to subscribe to the topic on the spot\n\/\/true on: subscription added to list (does not guarantee that the topic was subscribed to, only that it was added to the list)\n\/\/false on: subscription not added to list\nbool ESPHelper::addSubscription(const char * topic) {\n    \/\/default return value is false\n    bool subscribed = false;\n\n    \/\/loop through finding the next available slot for a subscription and add it\n    for (uint8_t i = 0; i < MAX_SUBSCRIPTIONS; i++) {\n        if (_subscriptions[i].isUsed == false) {\n            _subscriptions[i].topic  = topic;\n            _subscriptions[i].isUsed = true;\n            subscribed               = true;\n            break;\n        }\n    }\n\n    \/\/if added to the list, subscribe to the topic\n    if (subscribed) {\n        subscribe(topic, _qos);\n    }\n\n    return subscribed;\n}\n\n\/\/loops through list of subscriptions and attempts to subscribe to all topics\nvoid ESPHelper::resubscribe() {\n    for (uint8_t i = 0; i < MAX_SUBSCRIPTIONS; i++) {\n        if (_subscriptions[i].isUsed) {\n            subscribe(_subscriptions[i].topic, _qos);\n            yield();\n        }\n    }\n}\n\n\/\/manually unsubscribes from a topic (This is basically just a wrapper for the pubsubclient function)\nbool ESPHelper::unsubscribe(const char * topic) {\n    return client.unsubscribe(topic);\n}\n\n\/\/publish to a specified topic\nvoid ESPHelper::publish(const char * topic, const char * payload) {\n    if (_mqttSet) {\n        publish(topic, payload, false);\n    }\n}\n\n\/\/publish to a specified topic with a given retain level\nvoid ESPHelper::publish(const char * topic, const char * payload, bool retain) {\n    client.publish(topic, payload, retain);\n}\n\n\/\/set the callback function for MQTT\nvoid ESPHelper::setMQTTCallback(MQTT_CALLBACK_SIGNATURE) {\n    _mqttCallback = callback;\n\n    \/\/only set the callback if using mqtt AND the system has already been started. Otherwise just save it for later\n    if (_hasBegun && _mqttSet) {\n        client.setCallback(_mqttCallback);\n    }\n    _mqttCallbackSet = true;\n}\n\n\/\/sets a custom function to run when connection to wifi is established\nvoid ESPHelper::setWifiCallback(void (*callback)()) {\n    _wifiCallback    = callback;\n    _wifiCallbackSet = true;\n}\n\n\/\/attempts to connect to wifi & mqtt server if not connected\nvoid ESPHelper::reconnect() {\n    static uint8_t tryCount = 0;\n\n    if (_connectionStatus != BROADCAST && setConnectionStatus() != FULL_CONNECTION) {\n        logger(LOG_CONSOLE, \"Attempting WiFi Connection...\");\n        \/\/attempt to connect to the wifi if connection is lost\n        if (WiFi.status() != WL_CONNECTED) {\n            _connectionStatus = NO_CONNECTION;\n\n            \/\/increment try count each time it cannot connect (this is used to determine when to hop to a new network)\n            tryCount++;\n            if (tryCount == 20) {\n                \/\/change networks (if possible) when we have tried to connect 20 times and failed\n                changeNetwork();\n                tryCount = 0;\n                return;\n            }\n        }\n\n        \/\/ make sure we are connected to WIFI before attempting to reconnect to MQTT\n        \/\/----note---- maybe want to reset tryCount whenever we succeed at getting wifi connection?\n        if (WiFi.status() == WL_CONNECTED) {\n            \/\/if the wifi previously wasnt connected but now is, run the callback\n            if (_connectionStatus < WIFI_ONLY && _wifiCallbackSet) {\n                _wifiCallback();\n            }\n\n            logger(LOG_CONSOLE, \"---WiFi Connected!---\");\n            _connectionStatus = WIFI_ONLY;\n\n            \/\/attempt to connect to mqtt when we finally get connected to WiFi\n            if (_mqttSet) {\n                static uint8_t timeout = 0; \/\/allow a max of 5 mqtt connection attempts before timing out\n                if (!client.connected() && timeout < 5) {\n                    logger(LOG_CONSOLE, \"Attempting MQTT connection...\");\n\n                    uint8_t connected = 0;\n\n                    \/\/connect to mqtt with user\/pass\n                    if (_mqttUserSet) {\n                        connected = client.connect(_clientName, _currentNet.mqttUser, _currentNet.mqttPass);\n                    }\n\n                    \/\/connect to mqtt without credentials\n                    else {\n                        connected = client.connect(_clientName);\n                    }\n\n                    \/\/if connected, subscribe to the topic(s) we want to be notified about\n                    if (connected) {\n                        logger(LOG_CONSOLE, \" -- Connected\");\n\n                        \/\/if using https, verify the fingerprint of the server before setting full connection (return on fail)\n                        \/\/ removing this as not supported with ESP32, see https:\/\/github.com\/espressif\/arduino-esp32\/issues\/278\n                        \/*\n                            if (wifiClientSecure.verify(_fingerprint,\n                                                        _currentNet.mqttHost)) {\n                                logger(LOG_CONSOLE,\n                                       \"Certificate Matches - SUCCESS\\n\");\n                            } else {\n                                logger(LOG_CONSOLE,\n                                       \"Certificate Doesn't Match - FAIL\\n\");\n                                return;\n                            }\n                        }\n                        *\/\n\n                        _connectionStatus = FULL_CONNECTION;\n                        resubscribe();\n                        timeout = 0;\n                    } else {\n                        logger(LOG_CONSOLE, \" -- Failed\\n\");\n                    }\n                    timeout++;\n                }\n\n                \/\/if we still cant connect to mqtt after 10 attempts increment the try count\n                if (timeout >= 5 && !client.connected()) {\n                    timeout = 0;\n                    tryCount++;\n                    if (tryCount == 20) {\n                        changeNetwork();\n                        tryCount = 0;\n                        return;\n                    }\n                }\n            }\n        }\n\n        \/\/reset the reconnect metro\n        \/\/reconnectMetro.reset();\n    }\n}\n\nuint8_t ESPHelper::setConnectionStatus() {\n    \/\/assume no connection\n    uint8_t returnVal = NO_CONNECTION;\n\n    \/\/make sure were not in broadcast mode\n    if (_connectionStatus != BROADCAST) {\n        \/\/if connected to wifi set the mode to wifi only and run the callback if needed\n        if (WiFi.status() == WL_CONNECTED) {\n            if (_connectionStatus < WIFI_ONLY\n                && _wifiCallbackSet) { \/\/if the wifi previously wasn't connected but now is, run the callback\n                _wifiCallback();\n            }\n            returnVal = WIFI_ONLY;\n\n            \/\/if mqtt is connected as well then set the status to full connection\n            if (client.connected()) {\n                returnVal = FULL_CONNECTION;\n            }\n        }\n    }\n\n    else {\n        returnVal = BROADCAST;\n    }\n\n    \/\/set the connection status and return\n    _connectionStatus = returnVal;\n    return returnVal;\n}\n\n\/\/changes the current network settings to the next listed network if network hopping is allowed\nvoid ESPHelper::changeNetwork() {\n    \/\/only attempt to change networks if hopping is allowed\n    if (_hoppingAllowed) {\n        \/\/change the index\/reset to 0 if we've hit the last network setting\n        _currentIndex++;\n        if (_currentIndex >= _netCount) {\n            _currentIndex = 0;\n        }\n\n        \/\/set the current netlist to the new network\n        _currentNet = *_netList[_currentIndex];\n\n        \/\/verify various bits of network info\n\n        \/\/network password\n        if (_currentNet.pass[0] == '\\0') {\n            _passSet = false;\n        } else {\n            _passSet = true;\n        }\n\n        \/\/ssid\n        if (_currentNet.ssid[0] == '\\0') {\n            _ssidSet = false;\n        } else {\n            _ssidSet = true;\n        }\n\n        \/\/mqtt host\n        if (_currentNet.mqttHost[0] == '\\0') {\n            _mqttSet = false;\n        } else {\n            _mqttSet = true;\n        }\n\n        \/\/mqtt username\n        if (_currentNet.mqttUser[0] == '\\0') {\n            _mqttUserSet = false;\n        } else {\n            _mqttUserSet = true;\n        }\n\n        \/\/mqtt password\n        if (_currentNet.mqttPass[0] == '\\0') {\n            _mqttPassSet = false;\n        } else {\n            _mqttPassSet = true;\n        }\n\n        printf(\"Trying next network: %s\\n\", _currentNet.ssid);\n\n        \/\/update the network connection\n        updateNetwork();\n    }\n}\n\nvoid ESPHelper::updateNetwork() {\n    logger(LOG_CONSOLE, \"\\tDisconnecting from WiFi\");\n    WiFi.disconnect();\n    logger(LOG_CONSOLE, \"\\tAttempting to begin on new network...\");\n\n    \/\/set the wifi mode\n    WiFi.mode(WIFI_STA);\n\n    \/\/connect to the network\n    if (_passSet && _ssidSet) {\n        WiFi.begin(_currentNet.ssid, _currentNet.pass);\n    } else if (_ssidSet) {\n        WiFi.begin(_currentNet.ssid);\n    } else {\n        WiFi.begin(\"NO_SSID_SET\");\n    }\n\n    logger(LOG_CONSOLE, \"\\tSetting new MQTT server\");\n    \/\/setup the mqtt broker info\n    if (_mqttSet) {\n        client.setServer(_currentNet.mqttHost, _currentNet.mqttPort);\n    } else {\n        client.setServer(\"192.168.1.3\", 1883);\n    }\n\n    logger(LOG_CONSOLE, \"\\tDone - Ready for next reconnect attempt\");\n}\n\n\/\/enable use of OTA updates\nvoid ESPHelper::OTA_enable() {\n    _useOTA = true;\n    ArduinoOTA.setHostname(_hostname);\n    OTA_begin();\n}\n\n\/\/begin the OTA subsystem but with a check for connectivity and enabled use of OTA\nvoid ESPHelper::OTA_begin() {\n    if (_connectionStatus >= BROADCAST && _useOTA) {\n        ArduinoOTA.begin();\n        _OTArunning = true;\n    }\n}\n\n\/\/disable use of OTA updates\nvoid ESPHelper::OTA_disable() {\n    _useOTA     = false;\n    _OTArunning = false;\n}\n\n\/\/ Is CR or LF ?\nbool ESPHelper::isCRLF(char character) {\n    return (character == '\\r' || character == '\\n');\n}\n\n\/\/ handler for Telnet\nvoid ESPHelper::consoleHandle() {\n    \/\/ look for Client\n    if (telnetServer.hasClient()) {\n        if (telnetClient && telnetClient.connected()) {\n            \/\/ Verify if the IP is same than actual connection\n            WiFiClient newClient;\n            newClient = telnetServer.available();\n            String ip = newClient.remoteIP().toString();\n\n            if (ip == telnetClient.remoteIP().toString()) {\n                \/\/ Reconnect\n                telnetClient.stop();\n                telnetClient = newClient;\n            } else {\n                \/\/ Desconnect (not allow more than one connection)\n                newClient.stop();\n                return;\n            }\n        } else {\n            \/\/ New TCP client\n            telnetClient = telnetServer.available();\n        }\n\n        if (!telnetClient) { \/\/ No client yet ???\n            return;\n        }\n\n        \/\/ Set client\n        telnetClient.setNoDelay(true); \/\/ faster\n        telnetClient.flush();          \/\/ clear input buffer, to prevent strange characters\n\n        _lastTimeCommand = millis(); \/\/ To mark time for inactivity\n\n        \/\/ Show the initial message\n        consoleShowHelp();\n\n        \/\/ Empty buffer\n        while (telnetClient.available()) {\n            telnetClient.read();\n        }\n    }\n\n    \/\/ Is client connected ? (to reduce overhead in active)\n    _telnetConnected = (telnetClient && telnetClient.connected());\n\n    \/\/ Get command over telnet\n    if (_telnetConnected) {\n        char last = ' '; \/\/ To avoid processing double \"\\r\\n\"\n\n        while (telnetClient.available()) { \/\/ get data from Client\n\n            \/\/ Get character\n            char character = telnetClient.read();\n\n            \/\/ Newline (CR or LF) - once one time if (\\r\\n)\n            if (isCRLF(character) == true) {\n                if (isCRLF(last) == false) {\n                    \/\/ Process the command\n                    if (strlen(_command) > 0) {\n                        consoleProcessCommand();\n                    }\n                }\n                \/\/ reset for next command\n                memset(_command, 0, sizeof(_command));\n            } else if (isPrintable(character)) {\n                \/\/ Concat char to end of buffer\n                uint16_t len      = strlen(_command);\n                _command[len]     = character;\n                _command[len + 1] = '\\0';\n            }\n\n            \/\/ Last char\n            last = character;\n        }\n\n        \/\/ Inactivity - close connection if not received commands from user in telnet to reduce overheads\n        if ((millis() - _lastTimeCommand) > MAX_TIME_INACTIVE) {\n            telnetClient.println(\"* Closing session due to inactivity\");\n            telnetClient.flush();\n            telnetClient.stop();\n            _telnetConnected = false;\n        }\n    }\n}\n\n\/\/ Set callback of sketch function to process project messages\nvoid ESPHelper::consoleSetCallBackProjectCmds(command_t * cmds, uint8_t count, void (*callback)()) {\n    _helpProjectCmds            = cmds;     \/\/ command list\n    _helpProjectCmds_count      = count;    \/\/ numiber of commands\n    _consoleCallbackProjectCmds = callback; \/\/ external function to handle commands\n}\n\n\/\/ Set bootime received as a string from HA\nvoid ESPHelper::setBoottime(const char * boottime) {\n    strcpy(_boottime, boottime);\n}\n\n\/\/ overrides the write call to print to the telnet connection\nsize_t ESPHelper::write(uint8_t character) {\n    if (!_verboseMessages)\n        return 0;\n\n    \/\/static uint32_t elapsed = 0;\n\n    \/\/ If start of a new line, initiate a new string buffer with time counter as a prefix\n    if (_newLine) {\n        unsigned long upt = millis();\n        sprintf(bufferPrint,\n                \"(%s%02d:%02d:%02d%s) \",\n                COLOR_CYAN,\n                (uint8_t)((upt \/ (1000 * 60 * 60)) % 24),\n                (uint8_t)((upt \/ (1000 * 60)) % 60),\n                (uint8_t)((upt \/ 1000) % 60),\n                COLOR_RESET);\n        _newLine = false;\n    }\n\n    \/\/ Print ?\n    bool doPrint = false;\n\n    \/\/ New line ?\n    if (character == '\\n') {\n        _newLine = true;\n        doPrint  = true;\n    } else if (strlen(bufferPrint) == BUFFER_PRINT - 1) { \/\/ Limit of buffer\n        doPrint = true;\n    }\n\n    \/\/ Add character to telnet buffer\n    uint16_t len     = strlen(bufferPrint);\n    bufferPrint[len] = character;\n\n    if (_newLine) {\n        \/\/ add additional \\r for windows\n        bufferPrint[++len] = '\\r';\n    }\n\n    \/\/ terminate string\n    bufferPrint[++len] = '\\0';\n\n    \/\/ Send the characters buffered by print.h\n    if (doPrint) {\n        if (_telnetConnected) {\n            telnetClient.print(bufferPrint);\n        }\n\n\/\/ echo to Serial if enabled\n#ifdef USE_SERIAL\n        Serial.print(bufferPrint);\n#endif\n\n#ifdef USE_SERIAL1\n        Serial1.print(bufferPrint);\n#endif\n\n        \/\/ Empty the buffer\n        bufferPrint[0] = '\\0';\n    }\n\n    return len + 1;\n}\n\n\/\/ Show help of commands\nvoid ESPHelper::consoleShowHelp() {\n    String help = \"********************************\\n\\r* Remote Telnet Command Center \"\n                  \"*\\n\\r********************************\\n\\r\";\n    help += \"* Device hostname: \" + WiFi.hostname() + \"\\tIP: \" + WiFi.localIP().toString()\n            + \"\\tMAC address: \" + WiFi.macAddress() + \"\\n\\r\";\n    help += \"* Connected to WiFi AP: \" + WiFi.SSID() + \"\\n\\r\";\n    help += \"* Boot time: \";\n    help.concat(_boottime);\n    help += \"\\n\\r* Free Heap RAM: \";\n    help.concat(ESP.getFreeHeap());\n    help += \" bytes\\n\\r\";\n    help += \"*\\n\\r* Commands:\\n\\r*  ?=this help, q=quit telnet, $=show used memory, !=reboot, &=suspend all \"\n            \"notifications\\n\\r\";\n\n    \/\/ print custom commands if available\n    if (_consoleCallbackProjectCmds) {\n        for (uint8_t i = 0; i < _helpProjectCmds_count; i++) {\n            \/\/for (uint8_t i = 0; i < 5; i++) {\n            help += FPSTR(\"*  \");\n            help += FPSTR(_helpProjectCmds[i].key);\n            help += FPSTR(\" \");\n            help += FPSTR(_helpProjectCmds[i].description);\n            help += FPSTR(\"\\n\\r\");\n        }\n    }\n\n    telnetClient.print(help);\n\n#ifdef USE_SERIAL\n    Serial.print(help);\n#endif\n\n#ifdef USE_SERIAL1\n    Serial1.print(help);\n#endif\n}\n\n\/\/ reset \/ restart\nvoid ESPHelper::resetESP() {\n    telnetClient.println(\"* Reboot ESP...\");\n    telnetClient.flush();\n    telnetClient.stop();\n    \/\/ end();\n\n    \/\/ Reset\n    ESP.restart();\n    \/\/ ESP.reset(); \/\/ for ESP8266 only\n}\n\n\/\/ Get last command received\nchar * ESPHelper::consoleGetLastCommand() {\n    return _command;\n}\n\n\/\/ Process user command over telnet\nvoid ESPHelper::consoleProcessCommand() {\n    \/\/ Set time of last command received\n    _lastTimeCommand = millis();\n    uint8_t cmd      = _command[0];\n\n    if (!_verboseMessages) {\n        telnetClient.println(\"Warning, all messages are supsended. Use & to enable.\");\n    }\n\n    \/\/ Process the command\n    if (cmd == '?') {\n        consoleShowHelp();   \/\/ Show help\n    } else if (cmd == 'q') { \/\/ quit\n        telnetClient.println(\"* Closing telnet connection...\");\n        telnetClient.stop();\n    } else if (cmd == '$') {\n        telnetClient.print(\"* Free Heap RAM (bytes): \");\n        telnetClient.println(ESP.getFreeHeap());\n    } else if (cmd == '!') {\n        resetESP();\n    } else if (cmd == '&') {\n        _verboseMessages = !_verboseMessages; \/\/ toggle\n        telnetClient.printf(\"Suspend all messages is %s\\n\\r\", _verboseMessages ? \"disabled\" : \"enabled\");\n    } else {\n        \/\/ custom Project commands\n        if (_consoleCallbackProjectCmds) {\n            _consoleCallbackProjectCmds();\n        }\n    }\n}\n\n\/\/ Logger\n\/\/ LOG_CONSOLE sends to the Telnet session\n\/\/ LOG_HA sends to Telnet session plus a MQTT for Home Assistant\n\/\/ LOG_NONE turns off all logging\nvoid ESPHelper::logger(log_level_t level, const char * message) {\n    \/\/ do we log to the telnet window?\n    if ((level == LOG_CONSOLE) && (telnetClient && telnetClient.connected())) {\n        telnetClient.println(message);\n        telnetClient.flush();\n    } else if (level == LOG_HA) {\n        char s[100];\n        sprintf(s, \"%s: %s\\n\", _hostname, message); \/\/ add new line, for the debug telnet printer\n        publish(MQTT_NOTIFICATION, s, false);\n    }\n\n\/\/ print to Serial if set in platform.io (requires recompile)\n#ifdef USE_SERIAL\n    Serial.println(message);\n#endif\n\n#ifdef USE_SERIAL1\n    Serial.println(message);\n#endif\n}\n\n\/\/ send specific command to HA via MQTT\n\/\/ format is: home\/<hostname>\/command\/<cmd>\nvoid ESPHelper::sendHACommand(const char * cmd) {\n    \/\/logger(LOG_CONSOLE, \"Sending command to HA...\");\n\n    char s[100];\n    sprintf(s, \"%s%s\/%s\", MQTT_BASE, _hostname, MQTT_TOPIC_COMMAND);\n\n    publish(s, cmd, false);\n}\n\n\/\/ send specific start command to HA via MQTT, which returns the boottime\n\/\/ format is: home\/<hostname>\/start\nvoid ESPHelper::sendStart() {\n    \/\/logger(LOG_CONSOLE, \"Sending Start command to HA...\");\n\n    char s[100];\n    sprintf(s, \"%s%s\/%s\", MQTT_BASE, _hostname, MQTT_TOPIC_START);\n\n    \/\/ send initial payload of \"start\" to kick things off\n    publish(s, MQTT_TOPIC_START, false);\n}\n","avg_line_length":30.8768529076,"max_line_length":129,"alphanum_fraction":0.5753166661,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4961,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n* \/\/******************************************************************\n* \/\/\n* \/\/ Copyright 2015 Intel Corporation.\n* \/\/\n* \/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n* \/\/\n* \/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n* \/\/ you may not use this file except in compliance with the License.\n* \/\/ You may obtain a copy of the License at\n* \/\/\n* \/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n* \/\/\n* \/\/ Unless required by applicable law or agreed to in writing, software\n* \/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n* \/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* \/\/ See the License for the specific language governing permissions and\n* \/\/ limitations under the License.\n* \/\/\n* \/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n*\/\n#include \"JniOnObserveListener.h\"\n#include \"JniOcResource.h\"\n#include \"JniOcRepresentation.h\"\n#include \"JniUtils.h\"\n\nJniOnObserveListener::JniOnObserveListener(JNIEnv *env, jobject jListener, JniOcResource* owner)\n    : m_ownerResource(owner)\n{\n    m_jwListener = env->NewWeakGlobalRef(jListener);\n}\n\nJniOnObserveListener::~JniOnObserveListener()\n{\n    if (m_jwListener)\n    {\n        jint ret;\n        JNIEnv *env = GetJNIEnv(ret);\n        if (nullptr == env) return;\n\n        env->DeleteWeakGlobalRef(m_jwListener);\n        m_jwListener = nullptr;\n\n        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\n    }\n}\n\nvoid JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,\n    const OCRepresentation& ocRepresentation, const int& eCode, const int& sequenceNumber)\n{\n    jint envRet;\n    JNIEnv *env = GetJNIEnv(envRet);\n    if (nullptr == env) return;\n\n    jobject jListener = env->NewLocalRef(m_jwListener);\n    if (!jListener)\n    {\n        checkExAndRemoveListener(env);\n        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\n        return;\n    }\n    jclass clsL = env->GetObjectClass(jListener);\n    if (!clsL)\n    {\n        checkExAndRemoveListener(env);\n        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\n        return;\n    }\n\n    if (OC_STACK_OK != eCode && OC_STACK_RESOURCE_CREATED != eCode && OC_STACK_RESOURCE_DELETED != eCode)\n    {\n        jobject ex = GetOcException(eCode, \"stack error in onObserveCallback\");\n        if (!ex)\n        {\n            checkExAndRemoveListener(env);\n            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\n            return;\n        }\n        jmethodID midL = env->GetMethodID(clsL, \"onObserveFailed\", \"(Ljava\/lang\/Throwable;)V\");\n        if (!midL)\n        {\n            checkExAndRemoveListener(env);\n            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\n            return;\n        }\n        env->CallVoidMethod(jListener, midL, ex);\n    }\n    else\n    {\n        jobject jHeaderOptionList = JniUtils::convertHeaderOptionsVectorToJavaList(env, headerOptions);\n        if (!jHeaderOptionList)\n        {\n            checkExAndRemoveListener(env);\n            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\n            return;\n        }\n\n        OCRepresentation * rep = new OCRepresentation(ocRepresentation);\n        jlong handle = reinterpret_cast<jlong>(rep);\n        jobject jRepresentation = env->NewObject(g_cls_OcRepresentation,\n            g_mid_OcRepresentation_N_ctor_bool, handle, true);\n        if (!jRepresentation)\n        {\n            delete rep;\n            checkExAndRemoveListener(env);\n            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\n            return;\n        }\n\n        jmethodID midL = env->GetMethodID(clsL, \"onObserveCompleted\",\n            \"(Ljava\/util\/List;Lorg\/iotivity\/base\/OcRepresentation;I)V\");\n        if (!midL)\n        {\n            checkExAndRemoveListener(env);\n            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\n            return;\n        }\n\n        env->CallVoidMethod(jListener, midL, jHeaderOptionList, jRepresentation,\n            static_cast<jint>(sequenceNumber));\n        if (env->ExceptionCheck())\n        {\n            LOGE(\"Java exception is thrown\");\n            delete rep;\n            jthrowable ex = env->ExceptionOccurred();\n            env->ExceptionClear();\n            m_ownerResource->removeOnObserveListener(env, m_jwListener);\n            env->Throw((jthrowable)ex);\n        }\n\n        if (OC_OBSERVE_DEREGISTER == sequenceNumber)\n        {\n            checkExAndRemoveListener(env);\n        }\n    }\n\n    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\n}\n\nvoid JniOnObserveListener::checkExAndRemoveListener(JNIEnv* env)\n{\n    if (env->ExceptionCheck())\n    {\n        jthrowable ex = env->ExceptionOccurred();\n        env->ExceptionClear();\n        m_ownerResource->removeOnObserveListener(env, m_jwListener);\n        env->Throw((jthrowable)ex);\n    }\n    else\n    {\n        m_ownerResource->removeOnObserveListener(env, m_jwListener);\n    }\n}","avg_line_length":32.4248366013,"max_line_length":105,"alphanum_fraction":0.6063293691,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2232,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2.0,"content":"\/* file: kernel_function_fpt.cpp *\/\n\/*******************************************************************************\n* Copyright 2014-2017 Intel Corporation\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*******************************************************************************\/\n\n\/*\n\/\/++\n\/\/  Implementation of kernel function algorithm and types methods.\n\/\/--\n*\/\n\n#include \"kernel_function_types.h\"\n\nnamespace daal\n{\nnamespace algorithms\n{\nnamespace kernel_function\n{\nnamespace interface1\n{\n\/**\n * Allocates memory to store results of the kernel function algorithm\n * \\param[in] input  Pointer to the structure with the input objects\n * \\param[in] par    Pointer to the structure of the algorithm parameters\n * \\param[in] method       Computation method\n *\/\ntemplate <typename algorithmFPType>\nDAAL_EXPORT services::Status Result::allocate(const daal::algorithms::Input *input, const daal::algorithms::Parameter *par, const int method)\n{\n    const Input *algInput = static_cast<const Input *>(input);\n\n    const size_t nVectors1 = algInput->get(X)->getNumberOfRows();\n    const size_t nVectors2 = algInput->get(Y)->getNumberOfRows();\n    Argument::set(values, data_management::SerializationIfacePtr(\n                      new data_management::HomogenNumericTable<algorithmFPType>(nVectors2, nVectors1,\n                                                                                data_management::NumericTable::doAllocate)));\n    return services::Status();\n}\n\ntemplate DAAL_EXPORT services::Status Result::allocate<DAAL_FPTYPE>(const daal::algorithms::Input *input, const daal::algorithms::Parameter *par, const int method);\n\n}\/\/ namespace interface1\n}\/\/ namespace kernel function\n}\/\/ namespace algorithms\n}\/\/ namespace daal\n","avg_line_length":37.8305084746,"max_line_length":164,"alphanum_fraction":0.6698028674,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1704,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\n\nusing namespace std;\n\n\/\/ Implementor\nclass DrawingImplementor {\n\npublic:\n    virtual void drawSquare(double) =0;\n\n    virtual  ~DrawingImplementor() {};\n};\n\n\/\/ concrete implementor\n\nclass DrawingImlementorA : public DrawingImplementor {\npublic:\n    DrawingImlementorA() {\n\n    }\n\n    virtual ~DrawingImlementorA() {\n\n    }\n\n    void drawSquare(double side) {\n        cout << \"\\nImplementorA.square with side = \" << side << \"\\n\";\n\n    }\n};\n\n\/\/ concrete implementor\nclass DrawingImlementorB : public DrawingImplementor {\npublic:\n    DrawingImlementorB() {\n\n    }\n\n    virtual ~DrawingImlementorB() {}\n\n    void drawSquare(double side) {\n        cout << \"\\nImplementorB.square with side = \" << side << \"\\n\";\n    }\n};\n\n\/\/ abstraction\nclass Shape {\npublic:\n    virtual void draw() =0;\n\n    virtual void resize(double pct) =0;\n\n    virtual ~Shape() {\n\n    }\n};\n\n\nclass Square : public Shape {\npublic:\n    Square(double s, DrawingImplementor &implementor) : side(s), drawingImplementor(implementor) {\n    }\n\n    virtual  ~Square() {\n\n    }\n\n    \/\/ low level i.e Implementation specific\n    void draw() {\n        drawingImplementor.drawSquare(side);\n    }\n\n    \/\/ high level i.e abstraction specifc\n    void resize(double pct) {\n        side *= pct;\n    }\n\n\nprivate:\n    double side;\n    DrawingImplementor &drawingImplementor;\n};\n\n\nint main() {\n\n    DrawingImlementorA imlementorA;\n    DrawingImlementorB imlementorB;\n\n    Square squareA(1.0, imlementorA);\n    Square squareB(2.0, imlementorB);\n\n    Shape *shapes[2];\n    shapes[0] = &squareA;\n    shapes[1] = &squareB;\n\n    shapes[0]->resize(10.0);\n    shapes[0]->draw();\n\n    shapes[1]->resize(10);\n    shapes[1]->draw();\n\n    return 0;\n}","avg_line_length":16.3846153846,"max_line_length":98,"alphanum_fraction":0.6285211268,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2897,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>   \/\/ cout\n#include <algorithm>  \/\/ copy, fill\n\n#include \"tasks.hpp\"\n\n\/\/ \u0418\u0421\u041f\u041e\u041b\u042c\u0417\u041e\u0412\u0410\u041d\u0418\u0415 \u041b\u042e\u0411\u042b\u0425 \u0414\u0420\u0423\u0413\u0418\u0425 \u0411\u0418\u0411\u041b\u0418\u041e\u0422\u0415\u041a \u041d\u0415 \u0421\u041e\u0412\u0415\u0422\u0423\u0415\u0422\u0421\u042f \u0418 \u041c\u041e\u0416\u0415\u0422 \u041f\u041e\u0412\u041b\u0418\u042f\u0422\u042c \u041d\u0410 \u0412\u0410\u0428\u0418 \u0411\u0410\u041b\u041b\u042b\n\nusing std::cout;\nusing std::fill;\nusing std::copy;\n\n\/\/ \u0417\u0430\u0434\u0430\u043d\u0438\u0435 1\nvoid swap_args(int *lhs, int *rhs) {\n\n    if(lhs && rhs){\n        int d = *lhs;\n        *lhs = *rhs;\n        *rhs = d;\n    }\n}\n\n\/\/ \u0417\u0430\u0434\u0430\u043d\u0438\u0435 2\nint **allocate_2d_array(int num_rows, int num_cols, int init_value) {\nif(num_rows>0 && num_cols>0) {\n\n\n    int **array_2d = new int *[num_rows];\n\n    for (int row_index = 0; row_index < num_rows; row_index++) {\n        array_2d[row_index] = new int[num_cols];\n    }\n\n    for (int row_index = 0; row_index < num_rows; row_index++) {\n        for (int column_index = 0; column_index < num_cols; column_index++) {\n            array_2d[row_index][column_index]=init_value;\n        }\n    }\n    return array_2d;\n}\n    return nullptr;\n}\n\n\n\/\/ \u0417\u0430\u0434\u0430\u043d\u0438\u0435 3\nbool copy_2d_array(int **arr_2d_source, int **arr_2d_target, int num_rows, int num_cols) {\n    if(arr_2d_source==0||arr_2d_target==0||num_cols<0||num_rows<0){\n        return false;\n    } else {\n        for (int i = 0; i < num_rows; i++) {\n            for (int j = 0; j < num_cols; j++) {\n                std::copy(arr_2d_target[i], arr_2d_target[i] + num_cols, arr_2d_source[i]);\n            }\n        }\n        return arr_2d_source;\n    }\n\n}\n\n\/\/ \u0417\u0430\u0434\u0430\u043d\u0438\u0435 4\nvoid reverse_1d_array(vector<int> &arr) {\n    for(int i = 0;i<arr.size()\/2;i++){\n        int a = arr[i];\n        arr[i] = arr[arr.size()-i-1];\n        arr[arr.size()-i-1]=a;\n    }\n\n}\n\n\/\/ \u0417\u0430\u0434\u0430\u043d\u0438\u0435 5\nvoid reverse_1d_array(int *arr_begin, int *arr_end) {\n    if(arr_begin!= nullptr && arr_end!= nullptr){\n        int arrSize = arr_end-arr_begin+1;\n        for(int i =0;i<arrSize\/2;i++){\n            int a = arr_begin[i];\n            arr_begin[i] = arr_begin[arrSize-i-1];\n            arr_begin[arrSize-i-1]=a;\n        }\n    }\n}\n\n\/\/ \u0417\u0430\u0434\u0430\u043d\u0438\u0435 6\nint *find_max_element(int *arr, int size) {\n    if (arr != nullptr && size >= 0) {\n        int *max = &arr[0];\n        for (int i = 1; i<size; i++) {\n            if (arr[i] > *max) {\n                max = &arr[i];\n            }\n        }\n        return max;\n    }\n    return nullptr;\n}\n\n\/\/ \u0417\u0430\u0434\u0430\u043d\u0438\u0435 7\nvector<int> find_odd_numbers(vector<int> &arr) {\n    vector<int> odd_numbers;\n    for(int element : arr){\n        if(abs(element) % 2 == 1){\n            odd_numbers.push_back(element);\n        }\n    }\n    if(!odd_numbers.empty()){\n        return odd_numbers;\n    }\n    return {};\n}\n\n\/\/ \u0417\u0430\u0434\u0430\u043d\u0438\u0435 8\nvector<int> find_common_elements(vector<int> &arr_a, vector<int> &arr_b) {\n    vector<int> common_elements;\n    for(int element1:arr_a){\n        for(int element2 : arr_b){\n            if(element1==element2){\n                common_elements.push_back(element1);\n            }\n        }\n    }\n    if(common_elements.size()>=0){\n        return common_elements;\n    }\n    return {};\n}\n","avg_line_length":23.3629032258,"max_line_length":91,"alphanum_fraction":0.5547117708,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2500,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":null,"content":"#define CATCH_CONFIG_MAIN \/\/ This tells the catch header to generate a main\n\n#include <catch2\/catch.hpp>\n#include \"vec3.h\"\n#include \"ray.h\"\n\nusing ray_tracer::vector::Vec3;\nusing ray_tracer::vector::Point3;\nusing ray_tracer::ray::Ray;\n\nTEST_CASE(\"Ray creation with default creates a ray with zero origin and zero direction\", \"[ray]\") {\n    Ray test_obj;\n    REQUIRE(test_obj.origin()[0] == 0.0f);\n    REQUIRE(test_obj.origin()[1] == 0.0f);\n    REQUIRE(test_obj.origin()[2] == 0.0f);\n\n    REQUIRE(test_obj.direction()[0] == 0.0f);\n    REQUIRE(test_obj.direction()[1] == 0.0f);\n    REQUIRE(test_obj.direction()[2] == 0.0f);\n}\n\nTEST_CASE(\"Ray creation with parameters creates an expected ray\", \"[ray]\") {\n    Ray test_obj{{1.0f, 2.0f, 3.0f},\n                 {4.0f, 5.0f, 6.0f}};\n    REQUIRE(test_obj.origin()[0] == 1.0f);\n    REQUIRE(test_obj.origin()[1] == 2.0f);\n    REQUIRE(test_obj.origin()[2] == 3.0f);\n\n    REQUIRE(test_obj.direction()[0] == 4.0f);\n    REQUIRE(test_obj.direction()[1] == 5.0f);\n    REQUIRE(test_obj.direction()[2] == 6.0f);\n}\n\nTEST_CASE(\"Ray origin (0 0 0) direction (1 2 3) at 2.0 is (2 4 6)\", \"[ray]\") {\n    Ray test_obj{{0.0f, 0.0f, 0.0f},\n                 {1.0f, 2.0f, 3.0f}};\n    auto ray_at_2 = test_obj.at(2.0f);\n    REQUIRE(ray_at_2[0] == 2.0f);\n    REQUIRE(ray_at_2[1] == 4.0f);\n    REQUIRE(ray_at_2[2] == 6.0f);\n}\n\nTEST_CASE(\"Ray origin (1 2 3) direction (1 2 3) at -2.0 is (-1 -2 -3)\", \"[ray]\") {\n    Ray test_obj{{1.0f, 2.0f, 3.0f},\n                 {1.0f, 2.0f, 3.0f}};\n    auto ray_at_2 = test_obj.at(-2.0f);\n    REQUIRE(ray_at_2[0] == -1.0f);\n    REQUIRE(ray_at_2[1] == -2.0f);\n    REQUIRE(ray_at_2[2] == -3.0f);\n}\n\nTEST_CASE(\"Ray operator== return true and operator!= return false when direction and normal are equal\", \"[ray]\") {\n    Ray a{{1.0f, 2.0f, 3.0f},\n          {1.0f, 2.0f, 3.0f}};\n    Ray b{{1.0f, 2.0f, 3.0f},\n          {1.0f, 2.0f, 3.0f}};\n    REQUIRE(a == b);\n    REQUIRE_FALSE(a != b);\n}\n\nTEST_CASE(\"Ray operator== return false and operator!= return true when normals are not equal\", \"[ray]\") {\n    Ray a{{1.0f, 2.0f, 3.0f},\n          {1.0f, 2.0f, 3.0f}};\n    Ray b{{1.0f, 2.0f, 3.0f},\n          {0.0f, 2.0f, 3.0f}};\n    REQUIRE_FALSE(a == b);\n    REQUIRE(a != b);\n}\n\nTEST_CASE(\"Ray operator== return false and operator!= return true when directions are not equal\", \"[ray]\") {\n    Ray a{{1.0f, 2.0f, 3.0f},\n          {1.0f, 2.0f, 3.0f}};\n    Ray b{{0.0f, 2.0f, 3.0f},\n          {1.0f, 2.0f, 3.0f}};\n    REQUIRE_FALSE(a == b);\n    REQUIRE(a != b);\n}\n","avg_line_length":32.0512820513,"max_line_length":114,"alphanum_fraction":0.5704,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1906,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <catk\/syntax.hpp>\n#include <catk\/symdb.hpp>\n#include \"forward_decl.hpp\"\n#include <catk\/utils.hpp>\n#include <boost\/lexical_cast.hpp>\nnamespace catk::analysis::alloc_sym_dep {\n\nstatic auto float_type(const syntax::AST& right) {\n  using Func   = std::function<void(symdb::PrimaryUnion&, const syntax::AST&)>;\n  using FloatMap = std::unordered_map<\n    std::string, std::tuple<symdb::Type*, Func>\n  >;\n  auto& type_db = catk::get_type_db();\n  static FloatMap tag_to_type = [&type_db](){\n    FloatMap res;\n    Func func;\n\n    func = [](auto& pu, const auto& right){ \n      auto& literal = syntax::FPLiteral::literal(right);\n      pu = boost::lexical_cast<float>(literal.content()); \n    };\n    res[\"f32\" ] = std::make_tuple(&type_db[symdb::CATK_FLOAT32] , std::move(func));\n\n    func = [](auto& pu, const auto& right){ \n      auto& literal = syntax::FPLiteral::literal(right);\n      pu = boost::lexical_cast<double>(literal.content()); \n    };\n    res[\"f64\"] = std::make_tuple(&type_db[symdb::CATK_FLOAT64], std::move(func));\n\n    return res;\n  }();\n\n  catk::rt_assert(right.is<syntax::IntLiteral>(), \"BUG: literal should be integer.\");\n  auto& tag = syntax::FPLiteral::tag(right);\n  return tag_to_type.at(tag.content());\n}\n\nvoid float_def(\n  const syntax::AST& left, \n  const syntax::AST& right, \n  symdb::Symbol* parent\n) {\n  auto& sym_db = catk::get_sym_db();\n  auto& type_db = catk::get_type_db();\n  auto& id = *sym_db.alloc(); \n  auto [ptype, caster] = float_type(right);\n  auto& type = *ptype;\n\n  id.set_locatable(true);\n  id.set_identifier(true);\n  id.set_solid(true);\n  id.name = left.content();\n  id.type = &type;\n  parent->accessable[id.name] = &id;\n\n  auto& literal = *sym_db.alloc();\n  literal.set_literal(true);\n  literal.set_solid(true);\n  literal.type = &type; \n  caster(literal.content, right);\n\n  id.related.push_back(&literal);\n  left.set_symbol(id);\n  right.set_symbol(literal);\n}\n\n}","avg_line_length":28.447761194,"max_line_length":85,"alphanum_fraction":0.6600209864,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":497,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Zlib"],"max_stars_count":2.0,"content":"#include <iostream>\n#include <cassert>\n\n#include \"KF_test.hpp\"\n\nint main(int argc, char *argv[]) {\n    TEST_NAME();\n\n    COL_circle first = {\n\tVector3{10, 0, 0},\n\t10\n    };\n\n    COL_circle second = {\n\tVector3{0, 0, 0},\n\t10\n    };\n\n    COL_circle third = {\n\tVector3{100, 0, 0},\n\t10\n    };\n    \n    TEST_BOOL(check_circle_circle(first, second),\n\t      \"circle and circle collision\");\n\n    TEST_BOOL(!check_circle_circle(second, third),\n\t      \"circle and circle no collision\");\n    \n    return 0;\n}\n","avg_line_length":15.53125,"max_line_length":50,"alphanum_fraction":0.5975855131,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":19454,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["FTL"],"max_stars_count":55.0,"content":"\/* Copyright (c) 2011-2015, The Linux Foundation. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n *       copyright notice, this list of conditions and the following\n *       disclaimer in the documentation and\/or other materials provided\n *       with the distribution.\n *     * Neither the name of The Linux Foundation, nor the names of its\n *       contributors may be used to endorse or promote products derived\n *       from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n#define LOG_NDDEBUG 0\n#define LOG_TAG \"LocSvc_EngAdapter\"\n\n#include <sys\/stat.h>\n#include <errno.h>\n#include <ctype.h>\n#include <cutils\/properties.h>\n#include <LocEngAdapter.h>\n#include \"loc_eng_msg.h\"\n#include \"loc_log.h\"\n\n#define CHIPSET_SERIAL_NUMBER_MAX_LEN 16\n#define USER_AGENT_MAX_LEN 512\n\nusing namespace loc_core;\n\nLocInternalAdapter::LocInternalAdapter(LocEngAdapter* adapter) :\n    LocAdapterBase(adapter->getMsgTask()),\n    mLocEngAdapter(adapter)\n{\n}\nvoid LocInternalAdapter::setPositionModeInt(LocPosMode& posMode) {\n    sendMsg(new LocEngPositionMode(mLocEngAdapter, posMode));\n}\nvoid LocInternalAdapter::startFixInt() {\n    sendMsg(new LocEngStartFix(mLocEngAdapter));\n}\nvoid LocInternalAdapter::stopFixInt() {\n    sendMsg(new LocEngStopFix(mLocEngAdapter));\n}\nvoid LocInternalAdapter::getZppInt() {\n    sendMsg(new LocEngGetZpp(mLocEngAdapter));\n}\n\nLocEngAdapter::LocEngAdapter(LOC_API_ADAPTER_EVENT_MASK_T mask,\n                             void* owner, ContextBase* context,\n                             LocThread::tCreate tCreator) :\n    LocAdapterBase(mask,\n                   \/\/Get the AFW context if VzW context has not already been intialized in\n                   \/\/loc_ext\n                   context == NULL?\n                   LocDualContext::getLocFgContext(tCreator,\n                                                   NULL,\n                                                   LocDualContext::mLocationHalName,\n                                                   false)\n                   :context),\n    mOwner(owner), mInternalAdapter(new LocInternalAdapter(this)),\n    mUlp(new UlpProxyBase()), mNavigating(false),\n    mSupportsAgpsRequests(false),\n    mSupportsPositionInjection(false),\n    mSupportsTimeInjection(false),\n    mPowerVote(0)\n{\n    memset(&mFixCriteria, 0, sizeof(mFixCriteria));\n    mFixCriteria.mode = LOC_POSITION_MODE_INVALID;\n    LOC_LOGD(\"LocEngAdapter created\");\n}\n\ninline\nLocEngAdapter::~LocEngAdapter()\n{\n    delete mInternalAdapter;\n    LOC_LOGV(\"LocEngAdapter deleted\");\n}\n\nvoid LocEngAdapter::setXtraUserAgent() {\n    struct LocSetXtraUserAgent : public LocMsg {\n        const ContextBase* const mContext;\n        inline LocSetXtraUserAgent(ContextBase* context) :\n            LocMsg(), mContext(context) {\n        }\n        virtual void proc() const {\n            char release[PROPERTY_VALUE_MAX];\n            char manufacture[PROPERTY_VALUE_MAX];\n            char model[PROPERTY_VALUE_MAX];\n            char board[PROPERTY_VALUE_MAX];\n            char brand[PROPERTY_VALUE_MAX];\n            char chipsetsn[CHIPSET_SERIAL_NUMBER_MAX_LEN];\n            char userAgent[USER_AGENT_MAX_LEN];\n            const char defVal[] = \"-\";\n\n            property_get(\"ro.build.version.release\", release,     defVal);\n            property_get(\"ro.product.manufacturer\",  manufacture, defVal);\n            property_get(\"ro.product.model\", model,   defVal);\n            property_get(\"ro.product.board\", board,   defVal);\n            property_get(\"ro.product.brand\", brand,   defVal);\n            getChipsetSerialNo(chipsetsn, sizeof(chipsetsn), defVal);\n\n            encodeInPlace(release, PROPERTY_VALUE_MAX);\n            encodeInPlace(manufacture, PROPERTY_VALUE_MAX);\n            encodeInPlace(model, PROPERTY_VALUE_MAX);\n            encodeInPlace(board, PROPERTY_VALUE_MAX);\n            encodeInPlace(brand, PROPERTY_VALUE_MAX);\n\n            snprintf(userAgent, sizeof(userAgent), \"A\/%s\/%s\/%s\/%s\/-\/QCX3\/s%u\/-\/%s\/-\/%s\/-\/-\/-\",\n                     release, manufacture, model, board,\n                     mContext->getIzatDevId(), chipsetsn, brand);\n\n            for (int i = 0; i < sizeof(userAgent) && userAgent[i]; i++) {\n                if (' ' == userAgent[i]) userAgent[i] = '#';\n            }\n\n            saveUserAgentString(userAgent, strlen(userAgent));\n            LOC_LOGV(\"%s] UserAgent %s\", __func__, userAgent);\n        }\n\n        void saveUserAgentString(const char* data, const int len) const {\n            const char XTRA_FOLDER[] = \"\/data\/misc\/location\/xtra\";\n            const char USER_AGENT_FILE[] = \"\/data\/misc\/location\/xtra\/useragent.txt\";\n\n            if (data == NULL || len < 1) {\n                LOC_LOGE(\"%s:%d]: invalid input data = %p len = %d\", __func__, __LINE__, data, len);\n                return;\n            }\n\n            struct stat s;\n            int err = stat(XTRA_FOLDER, &s);\n            if (err < 0) {\n                if (ENOENT == errno) {\n                    if (mkdir(XTRA_FOLDER, 0700) < 0) {\n                        LOC_LOGE(\"%s:%d]: make XTRA_FOLDER failed\", __func__, __LINE__);\n                        return;\n                    }\n                } else {\n                    LOC_LOGE(\"%s:%d]: XTRA_FOLDER invalid\", __func__, __LINE__);\n                    return;\n                }\n            }\n\n            FILE* file = fopen(USER_AGENT_FILE, \"wt\");\n            if (file == NULL) {\n                LOC_LOGE(\"%s:%d]: open USER_AGENT_FILE failed\", __func__, __LINE__);\n                return;\n            }\n\n            size_t written = fwrite(data, 1, len, file);\n            fclose(file);\n            file = NULL;\n\n            \/\/ set file permission\n            chmod(USER_AGENT_FILE, 0600);\n\n            if (written != len) {\n                LOC_LOGE(\"%s:%d]: write USER_AGENT_FILE failed\", __func__, __LINE__);\n            }\n        }\n\n        void getChipsetSerialNo(char buf[], int buflen, const char def[]) const {\n            const char SOC_SERIAL_NUMBER[] = \"\/sys\/devices\/soc0\/serial_number\";\n\n            FILE* file = fopen(SOC_SERIAL_NUMBER, \"rt\");\n            if (file == NULL) {\n                \/\/ use default upon unreadable file\n                strlcpy(buf, def, buflen);\n\n            } else {\n                size_t size = fread(buf, 1, buflen - 1, file);\n                if (size == 0) {\n                   \/\/ use default upon empty file\n                   strlcpy(buf, def, buflen);\n\n                } else {\n                   buf[size] = '\\0';\n                }\n\n                fclose(file);\n\n                \/\/ remove trailing spaces\n                char *s;\n                s = buf + strlen(buf);\n                while (--s >= buf) {\n                    if (!isspace(*s)) break;\n                    *s = 0;\n                }\n            }\n\n            return;\n        }\n\n        \/**\n         *  encode the given string value such that all separator characters ('\/','+','|','%')\n         *  in the string are repaced by their corresponding encodings (%2F\",\"%2B\",\"%7C\", \"%25\")\n         *\/\n        static void encodeInPlace(char value[], const int size) {\n            char buffer[size];\n\n            struct ENCODE {\n                const char ch;\n                const char *code;\n            };\n\n            const ENCODE encodings[] = { {'\/', \"%2F\"}, {'+', \"%2B\"}, {'|', \"%7C\",}, {'%', \"%25\"} };\n            const int nencodings = (int)sizeof(encodings) \/ sizeof(encodings[0]);\n\n            int inpos = 0, outpos = 0;\n            while(value[inpos] != '\\0' && outpos < size - 1) {\n                \/\/ check if escaped character\n                int escchar = 0;\n                while(escchar < nencodings && encodings[escchar].ch != value[inpos]) {\n                    escchar++;\n                }\n\n                if (escchar == nencodings) {\n                    \/\/ non escaped character\n                    buffer[outpos++] = value[inpos++];\n                    continue;\n                }\n\n                \/\/ escaped character\n                int codepos = 0;\n                #define NUM_CHARS_IN_CODE 3\n\n                if (outpos + NUM_CHARS_IN_CODE >= size) {\n                    \/\/ skip last character if there is insufficient space\n                    break;\n                }\n\n                while(outpos < size - 1 && codepos < NUM_CHARS_IN_CODE) {\n                    buffer[outpos++] = encodings[escchar].code[codepos++];\n                }\n                inpos++;\n            }\n\n            \/\/ copy to ouput\n            value[outpos] = '\\0';\n            while(--outpos >= 0) {\n                value[outpos] = buffer[outpos];\n            }\n        }\n    };\n\n    sendMsg(new LocSetXtraUserAgent(mContext));\n}\n\nvoid LocInternalAdapter::setUlpProxy(UlpProxyBase* ulp) {\n    struct LocSetUlpProxy : public LocMsg {\n        LocAdapterBase* mAdapter;\n        UlpProxyBase* mUlp;\n        inline LocSetUlpProxy(LocAdapterBase* adapter, UlpProxyBase* ulp) :\n            LocMsg(), mAdapter(adapter), mUlp(ulp) {\n        }\n        virtual void proc() const {\n            LOC_LOGV(\"%s] ulp %p adapter %p\", __func__,\n                     mUlp, mAdapter);\n            mAdapter->setUlpProxy(mUlp);\n        }\n    };\n\n    sendMsg(new LocSetUlpProxy(mLocEngAdapter, ulp));\n}\n\nvoid LocEngAdapter::setUlpProxy(UlpProxyBase* ulp)\n{\n    if (ulp == mUlp) {\n        \/\/This takes care of the case when double initalization happens\n        \/\/and we get the same object back for UlpProxyBase . Do nothing\n        return;\n    }\n\n    LOC_LOGV(\"%s] %p\", __func__, ulp);\n    if (NULL == ulp) {\n        LOC_LOGE(\"%s:%d]: ulp pointer is NULL\", __func__, __LINE__);\n        ulp = new UlpProxyBase();\n    }\n\n    if (LOC_POSITION_MODE_INVALID != mUlp->mPosMode.mode) {\n        \/\/ need to send this mode and start msg to ULP\n        ulp->sendFixMode(mUlp->mPosMode);\n    }\n\n    if(mUlp->mFixSet) {\n        ulp->sendStartFix();\n    }\n\n    delete mUlp;\n    mUlp = ulp;\n}\n\nint LocEngAdapter::setGpsLockMsg(LOC_GPS_LOCK_MASK lockMask)\n{\n    struct LocEngAdapterGpsLock : public LocMsg {\n        LocEngAdapter* mAdapter;\n        LOC_GPS_LOCK_MASK mLockMask;\n        inline LocEngAdapterGpsLock(LocEngAdapter* adapter, LOC_GPS_LOCK_MASK lockMask) :\n            LocMsg(), mAdapter(adapter), mLockMask(lockMask)\n        {\n            locallog();\n        }\n        inline virtual void proc() const {\n            mAdapter->setGpsLock(mLockMask);\n        }\n        inline  void locallog() const {\n            LOC_LOGV(\"LocEngAdapterGpsLock - mLockMask: %x\", mLockMask);\n        }\n        inline virtual void log() const {\n            locallog();\n        }\n    };\n    sendMsg(new LocEngAdapterGpsLock(this, lockMask));\n    return 0;\n}\n\nvoid LocEngAdapter::requestPowerVote()\n{\n    if (getPowerVoteRight()) {\n        \/* Power voting without engine lock:\n         * 101: vote down, 102-104 - vote up\n         * These codes are used not to confuse with actual engine lock\n         * functionality, that can't be used in SSR scenario, as it\n         * conflicts with initialization sequence.\n         *\/\n        bool powerUp = getPowerVote();\n        LOC_LOGV(\"LocEngAdapterVotePower - Vote Power: %d\", (int)powerUp);\n        setGpsLock(powerUp ? 103 : 101);\n    }\n}\n\nvoid LocInternalAdapter::reportPosition(UlpLocation &location,\n                                        GpsLocationExtended &locationExtended,\n                                        void* locationExt,\n                                        enum loc_sess_status status,\n                                        LocPosTechMask loc_technology_mask)\n{\n    sendMsg(new LocEngReportPosition(mLocEngAdapter,\n                                     location,\n                                     locationExtended,\n                                     locationExt,\n                                     status,\n                                     loc_technology_mask));\n}\n\n\nvoid LocEngAdapter::reportPosition(UlpLocation &location,\n                                   GpsLocationExtended &locationExtended,\n                                   void* locationExt,\n                                   enum loc_sess_status status,\n                                   LocPosTechMask loc_technology_mask)\n{\n    if (! mUlp->reportPosition(location,\n                               locationExtended,\n                               locationExt,\n                               status,\n                               loc_technology_mask )) {\n        mInternalAdapter->reportPosition(location,\n                                         locationExtended,\n                                         locationExt,\n                                         status,\n                                         loc_technology_mask);\n    }\n}\n\nvoid LocInternalAdapter::reportSv(GnssSvStatus &svStatus,\n                                  GpsLocationExtended &locationExtended,\n                                  void* svExt){\n    sendMsg(new LocEngReportSv(mLocEngAdapter, svStatus,\n                               locationExtended, svExt));\n}\n\nvoid LocEngAdapter::reportSv(GnssSvStatus &svStatus,\n                             GpsLocationExtended &locationExtended,\n                             void* svExt)\n{\n\n    \/\/ We want to send SV info to ULP to help it in determining GNSS\n    \/\/ signal strength ULP will forward the SV reports to HAL without\n    \/\/ any modifications\n    if (! mUlp->reportSv(svStatus, locationExtended, svExt)) {\n        mInternalAdapter->reportSv(svStatus, locationExtended, svExt);\n    }\n}\n\n\nvoid LocEngAdapter::reportSvMeasurement(GnssSvMeasurementSet &svMeasurementSet)\n{\n    \/\/ We send SvMeasurementSet to AmtProxy\/ULPProxy to be forwarded as necessary.\n    if (! mUlp->reportSvMeasurement(svMeasurementSet)) {\n        \/\/Send to Internal Adapter later if needed by LA\n    }\n}\n\nvoid LocEngAdapter::reportSvPolynomial(GnssSvPolynomial &svPolynomial)\n{\n    \/\/ We send SvMeasurementSet to AmtProxy\/ULPProxy to be forwarded as necessary.\n    if (! mUlp->reportSvPolynomial(svPolynomial)) {\n       \/\/Send to Internal Adapter later if needed by LA\n    }\n}\n\nvoid LocEngAdapter::setInSession(bool inSession)\n{\n    mNavigating = inSession;\n    mLocApi->setInSession(inSession);\n    if (!mNavigating) {\n        mFixCriteria.mode = LOC_POSITION_MODE_INVALID;\n    }\n}\n\nvoid LocInternalAdapter::reportStatus(GpsStatusValue status)\n{\n    sendMsg(new LocEngReportStatus(mLocEngAdapter, status));\n}\n\nvoid LocEngAdapter::reportStatus(GpsStatusValue status)\n{\n    if (!mUlp->reportStatus(status)) {\n        mInternalAdapter->reportStatus(status);\n    }\n}\n\ninline\nvoid LocEngAdapter::reportNmea(const char* nmea, int length)\n{\n    sendMsg(new LocEngReportNmea(mOwner, nmea, length));\n}\n\ninline\nbool LocEngAdapter::reportXtraServer(const char* url1,\n                                        const char* url2,\n                                        const char* url3,\n                                        const int maxlength)\n{\n    if (mSupportsAgpsRequests) {\n        sendMsg(new LocEngReportXtraServer(mOwner, url1,\n                                           url2, url3, maxlength));\n    }\n    return mSupportsAgpsRequests;\n}\n\ninline\nbool LocEngAdapter::requestATL(int connHandle, AGpsType agps_type)\n{\n    if (mSupportsAgpsRequests) {\n        sendMsg(new LocEngRequestATL(mOwner,\n                                     connHandle, agps_type));\n    }\n    return mSupportsAgpsRequests;\n}\n\ninline\nbool LocEngAdapter::releaseATL(int connHandle)\n{\n    if (mSupportsAgpsRequests) {\n        sendMsg(new LocEngReleaseATL(mOwner, connHandle));\n    }\n    return mSupportsAgpsRequests;\n}\n\ninline\nbool LocEngAdapter::requestXtraData()\n{\n    if (mSupportsAgpsRequests) {\n        sendMsg(new LocEngRequestXtra(mOwner));\n    }\n    return mSupportsAgpsRequests;\n}\n\ninline\nbool LocEngAdapter::requestTime()\n{\n    if (mSupportsAgpsRequests) {\n        sendMsg(new LocEngRequestTime(mOwner));\n    }\n    return mSupportsAgpsRequests;\n}\n\ninline\nbool LocEngAdapter::requestNiNotify(GpsNiNotification &notif, const void* data)\n{\n    if (mSupportsAgpsRequests) {\n        notif.size = sizeof(notif);\n        notif.timeout = LOC_NI_NO_RESPONSE_TIME;\n\n        sendMsg(new LocEngRequestNi(mOwner, notif, data));\n    }\n    return mSupportsAgpsRequests;\n}\n\ninline\nbool LocEngAdapter::requestSuplES(int connHandle)\n{\n    if (mSupportsAgpsRequests)\n        sendMsg(new LocEngRequestSuplEs(mOwner, connHandle));\n    return mSupportsAgpsRequests;\n}\n\ninline\nbool LocEngAdapter::reportDataCallOpened()\n{\n    if(mSupportsAgpsRequests)\n        sendMsg(new LocEngSuplEsOpened(mOwner));\n    return mSupportsAgpsRequests;\n}\n\ninline\nbool LocEngAdapter::reportDataCallClosed()\n{\n    if(mSupportsAgpsRequests)\n        sendMsg(new LocEngSuplEsClosed(mOwner));\n    return mSupportsAgpsRequests;\n}\n\ninline\nvoid LocEngAdapter::handleEngineDownEvent()\n{\n    sendMsg(new LocEngDown(mOwner));\n}\n\ninline\nvoid LocEngAdapter::handleEngineUpEvent()\n{\n    sendMsg(new LocEngUp(mOwner));\n}\n\nenum loc_api_adapter_err LocEngAdapter::setTime(GpsUtcTime time,\n                                                int64_t timeReference,\n                                                int uncertainty)\n{\n    loc_api_adapter_err result = LOC_API_ADAPTER_ERR_SUCCESS;\n\n    LOC_LOGD(\"%s:%d]: mSupportsTimeInjection is %d\",\n             __func__, __LINE__, mSupportsTimeInjection);\n\n    if (mSupportsTimeInjection) {\n        LOC_LOGD(\"%s:%d]: Injecting time\", __func__, __LINE__);\n        result = mLocApi->setTime(time, timeReference, uncertainty);\n    }\n\n    return result;\n}\n\nenum loc_api_adapter_err LocEngAdapter::setXtraVersionCheck(int check)\n{\n    enum loc_api_adapter_err ret;\n    ENTRY_LOG();\n    enum xtra_version_check eCheck;\n    switch (check) {\n    case 0:\n        eCheck = DISABLED;\n        break;\n    case 1:\n        eCheck = AUTO;\n        break;\n    case 2:\n        eCheck = XTRA2;\n        break;\n    case 3:\n        eCheck = XTRA3;\n        break;\n    default:\n        eCheck = DISABLED;\n    }\n    ret = mLocApi->setXtraVersionCheck(eCheck);\n    EXIT_LOG(%d, ret);\n    return ret;\n}\n\nvoid LocEngAdapter::reportGnssMeasurementData(GnssData &gnssMeasurementData)\n{\n    sendMsg(new LocEngReportGnssMeasurement(mOwner,\n                                           gnssMeasurementData));\n}\n\n\/*\n  Set Gnss Constellation Config\n *\/\nbool LocEngAdapter::gnssConstellationConfig()\n{\n    LOC_LOGD(\"entering %s\", __func__);\n    bool result = false;\n    result = mLocApi->gnssConstellationConfig();\n    return result;\n}\n","avg_line_length":32.3693843594,"max_line_length":100,"alphanum_fraction":0.5811658271,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":16870,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/*\n * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>\n * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>\n * Copyright (C) 2005 Eric Seidel <eric@webkit.org>\n * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>\n * Copyright (C) 2010 Zoltan Herczeg <zherczeg@webkit.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB.  If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"config.h\"\n#include \"FEConvolveMatrix.h\"\n\n#include \"Filter.h\"\n#include <wtf\/text\/TextStream.h>\n\n#include <runtime\/Uint8ClampedArray.h>\n#include <wtf\/ParallelJobs.h>\n#include <wtf\/WorkQueue.h>\n\nnamespace WebCore {\n\nFEConvolveMatrix::FEConvolveMatrix(Filter& filter, const IntSize& kernelSize,\n    float divisor, float bias, const IntPoint& targetOffset, EdgeModeType edgeMode,\n    const FloatPoint& kernelUnitLength, bool preserveAlpha, const Vector<float>& kernelMatrix)\n    : FilterEffect(filter)\n    , m_kernelSize(kernelSize)\n    , m_divisor(divisor)\n    , m_bias(bias)\n    , m_targetOffset(targetOffset)\n    , m_edgeMode(edgeMode)\n    , m_kernelUnitLength(kernelUnitLength)\n    , m_preserveAlpha(preserveAlpha)\n    , m_kernelMatrix(kernelMatrix)\n{\n    ASSERT(m_kernelSize.width() > 0);\n    ASSERT(m_kernelSize.height() > 0);\n}\n\nRef<FEConvolveMatrix> FEConvolveMatrix::create(Filter& filter, const IntSize& kernelSize,\n    float divisor, float bias, const IntPoint& targetOffset, EdgeModeType edgeMode,\n    const FloatPoint& kernelUnitLength, bool preserveAlpha, const Vector<float>& kernelMatrix)\n{\n    return adoptRef(*new FEConvolveMatrix(filter, kernelSize, divisor, bias, targetOffset, edgeMode, kernelUnitLength,\n        preserveAlpha, kernelMatrix));\n}\n\nvoid FEConvolveMatrix::setKernelSize(const IntSize& kernelSize)\n{\n    ASSERT(kernelSize.width() > 0);\n    ASSERT(kernelSize.height() > 0);\n    m_kernelSize = kernelSize;\n}\n\nvoid FEConvolveMatrix::setKernel(const Vector<float>& kernel)\n{\n    m_kernelMatrix = kernel; \n}\n\nbool FEConvolveMatrix::setDivisor(float divisor)\n{\n    ASSERT(divisor);\n    if (m_divisor == divisor)\n        return false;\n    m_divisor = divisor;\n    return true;\n}\n\nbool FEConvolveMatrix::setBias(float bias)\n{\n    if (m_bias == bias)\n        return false;\n    m_bias = bias;\n    return true;\n}\n\nbool FEConvolveMatrix::setTargetOffset(const IntPoint& targetOffset)\n{\n    if (m_targetOffset == targetOffset)\n        return false;\n    m_targetOffset = targetOffset;\n    return true;\n}\n\nbool FEConvolveMatrix::setEdgeMode(EdgeModeType edgeMode)\n{\n    if (m_edgeMode == edgeMode)\n        return false;\n    m_edgeMode = edgeMode;\n    return true;\n}\n\nbool FEConvolveMatrix::setKernelUnitLength(const FloatPoint& kernelUnitLength)\n{\n    ASSERT(kernelUnitLength.x() > 0);\n    ASSERT(kernelUnitLength.y() > 0);\n    if (m_kernelUnitLength == kernelUnitLength)\n        return false;\n    m_kernelUnitLength = kernelUnitLength;\n    return true;\n}\n\nbool FEConvolveMatrix::setPreserveAlpha(bool preserveAlpha)\n{\n    if (m_preserveAlpha == preserveAlpha)\n        return false;\n    m_preserveAlpha = preserveAlpha;\n    return true;\n}\n\n\/*\n   -----------------------------------\n      ConvolveMatrix implementation\n   -----------------------------------\n\n   The image rectangle is split in the following way:\n\n      +---------------------+\n      |          A          |\n      +---------------------+\n      |   |             |   |\n      | B |      C      | D |\n      |   |             |   |\n      +---------------------+\n      |          E          |\n      +---------------------+\n\n   Where region C contains those pixels, whose values\n   can be calculated without crossing the edge of the rectangle.\n\n   Example:\n      Image size: width: 10, height: 10\n\n      Order (kernel matrix size): width: 3, height 4\n      Target: x:1, y:3\n\n      The following figure shows the target inside the kernel matrix:\n\n        ...\n        ...\n        ...\n        .X.\n\n   The regions in this case are the following:\n      Note: (x1, y1) top-left and (x2, y2) is the bottom-right corner\n      Note: row x2 and column y2 is not part of the region\n            only those (x, y) pixels, where x1 <= x < x2 and y1 <= y < y2\n\n      Region A: x1: 0, y1: 0, x2: 10, y2: 3\n      Region B: x1: 0, y1: 3, x2: 1, y2: 10\n      Region C: x1: 1, y1: 3, x2: 9, y2: 10\n      Region D: x1: 9, y1: 3, x2: 10, y2: 10\n      Region E: x1: 0, y1: 10, x2: 10, y2: 10 (empty region)\n\n   Since region C (often) contains most of the pixels, we implemented\n   a fast algoritm to calculate these values, called fastSetInteriorPixels.\n   For other regions, fastSetOuterPixels is used, which calls getPixelValue,\n   to handle pixels outside of the image. In a rare situations, when\n   kernel matrix is bigger than the image, all pixels are calculated by this\n   function.\n\n   Although these two functions have lot in common, I decided not to make\n   common a template for them, since there are key differences as well,\n   and would make it really hard to understand.\n*\/\n\nstatic ALWAYS_INLINE unsigned char clampRGBAValue(float channel, unsigned char max = 255)\n{\n    if (channel <= 0)\n        return 0;\n    if (channel >= max)\n        return max;\n    return channel;\n}\n\ntemplate<bool preserveAlphaValues>\nALWAYS_INLINE void setDestinationPixels(const Uint8ClampedArray& sourcePixels, Uint8ClampedArray& destPixels, int& pixel, float* totals, float divisor, float bias)\n{\n    unsigned char maxAlpha = preserveAlphaValues ? 255 : clampRGBAValue(totals[3] \/ divisor + bias);\n    for (int i = 0; i < 3; ++i)\n        destPixels.set(pixel++, clampRGBAValue(totals[i] \/ divisor + bias, maxAlpha));\n\n    if (preserveAlphaValues) {\n        destPixels.set(pixel, sourcePixels.item(pixel));\n        ++pixel;\n    } else\n        destPixels.set(pixel++, maxAlpha);\n}\n\n#if COMPILER(MSVC)\n\/\/ Incorrectly diagnosing overwrite of stack in |totals| due to |preserveAlphaValues|.\n#pragma warning(push)\n#pragma warning(disable: 4789)\n#endif\n\n\/\/ Only for region C\ntemplate<bool preserveAlphaValues>\nALWAYS_INLINE void FEConvolveMatrix::fastSetInteriorPixels(PaintingData& paintingData, int clipRight, int clipBottom, int yStart, int yEnd)\n{\n    \/\/ edge mode does not affect these pixels\n    int pixel = (m_targetOffset.y() * paintingData.width + m_targetOffset.x()) * 4;\n    int kernelIncrease = clipRight * 4;\n    int xIncrease = (m_kernelSize.width() - 1) * 4;\n    \/\/ Contains the sum of rgb(a) components\n    float totals[3 + (preserveAlphaValues ? 0 : 1)];\n\n    \/\/ m_divisor cannot be 0, SVGFEConvolveMatrixElement ensures this\n    ASSERT(m_divisor);\n\n    \/\/ Skip the first '(clipBottom - yEnd)' lines\n    pixel += (clipBottom - yEnd) * (xIncrease + (clipRight + 1) * 4);\n    int startKernelPixel = (clipBottom - yEnd) * (xIncrease + (clipRight + 1) * 4);\n\n    for (int y = yEnd + 1; y > yStart; --y) {\n        for (int x = clipRight + 1; x > 0; --x) {\n            int kernelValue = paintingData.kernelMatrix.size() - 1;\n            int kernelPixel = startKernelPixel;\n            int width = m_kernelSize.width();\n\n            totals[0] = 0;\n            totals[1] = 0;\n            totals[2] = 0;\n            if (!preserveAlphaValues)\n                totals[3] = 0;\n\n            while (kernelValue >= 0) {\n                totals[0] += paintingData.kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray.item(kernelPixel++));\n                totals[1] += paintingData.kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray.item(kernelPixel++));\n                totals[2] += paintingData.kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray.item(kernelPixel++));\n                if (!preserveAlphaValues)\n                    totals[3] += paintingData.kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray.item(kernelPixel));\n                ++kernelPixel;\n                --kernelValue;\n                if (!--width) {\n                    kernelPixel += kernelIncrease;\n                    width = m_kernelSize.width();\n                }\n            }\n\n            setDestinationPixels<preserveAlphaValues>(paintingData.srcPixelArray, paintingData.dstPixelArray, pixel, totals, m_divisor, paintingData.bias);\n            startKernelPixel += 4;\n        }\n        pixel += xIncrease;\n        startKernelPixel += xIncrease;\n    }\n}\n\nALWAYS_INLINE int FEConvolveMatrix::getPixelValue(PaintingData& paintingData, int x, int y)\n{\n    if (x >= 0 && x < paintingData.width && y >= 0 && y < paintingData.height)\n        return (y * paintingData.width + x) << 2;\n\n    switch (m_edgeMode) {\n    default: \/\/ EDGEMODE_NONE\n        return -1;\n    case EDGEMODE_DUPLICATE:\n        if (x < 0)\n            x = 0;\n        else if (x >= paintingData.width)\n            x = paintingData.width - 1;\n        if (y < 0)\n            y = 0;\n        else if (y >= paintingData.height)\n            y = paintingData.height - 1;\n        return (y * paintingData.width + x) << 2;\n    case EDGEMODE_WRAP:\n        while (x < 0)\n            x += paintingData.width;\n        x %= paintingData.width;\n        while (y < 0)\n            y += paintingData.height;\n        y %= paintingData.height;\n        return (y * paintingData.width + x) << 2;\n    }\n}\n\n\/\/ For other regions than C\ntemplate<bool preserveAlphaValues>\nvoid FEConvolveMatrix::fastSetOuterPixels(PaintingData& paintingData, int x1, int y1, int x2, int y2)\n{\n    int pixel = (y1 * paintingData.width + x1) * 4;\n    int height = y2 - y1;\n    int width = x2 - x1;\n    int beginKernelPixelX = x1 - m_targetOffset.x();\n    int startKernelPixelX = beginKernelPixelX;\n    int startKernelPixelY = y1 - m_targetOffset.y();\n    int xIncrease = (paintingData.width - width) * 4;\n    \/\/ Contains the sum of rgb(a) components\n    float totals[3 + (preserveAlphaValues ? 0 : 1)];\n\n    \/\/ m_divisor cannot be 0, SVGFEConvolveMatrixElement ensures this\n    ASSERT(m_divisor);\n\n    for (int y = height; y > 0; --y) {\n        for (int x = width; x > 0; --x) {\n            int kernelValue = paintingData.kernelMatrix.size() - 1;\n            int kernelPixelX = startKernelPixelX;\n            int kernelPixelY = startKernelPixelY;\n            int width = m_kernelSize.width();\n\n            totals[0] = 0;\n            totals[1] = 0;\n            totals[2] = 0;\n            if (!preserveAlphaValues)\n                totals[3] = 0;\n\n            while (kernelValue >= 0) {\n                int pixelIndex = getPixelValue(paintingData, kernelPixelX, kernelPixelY);\n                if (pixelIndex >= 0) {\n                    totals[0] += paintingData.kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray.item(pixelIndex));\n                    totals[1] += paintingData.kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray.item(pixelIndex + 1));\n                    totals[2] += paintingData.kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray.item(pixelIndex + 2));\n                }\n                if (!preserveAlphaValues && pixelIndex >= 0)\n                    totals[3] += paintingData.kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray.item(pixelIndex + 3));\n                ++kernelPixelX;\n                --kernelValue;\n                if (!--width) {\n                    kernelPixelX = startKernelPixelX;\n                    ++kernelPixelY;\n                    width = m_kernelSize.width();\n                }\n            }\n\n            setDestinationPixels<preserveAlphaValues>(paintingData.srcPixelArray, paintingData.dstPixelArray, pixel, totals, m_divisor, paintingData.bias);\n            ++startKernelPixelX;\n        }\n        pixel += xIncrease;\n        startKernelPixelX = beginKernelPixelX;\n        ++startKernelPixelY;\n    }\n}\n\n#if COMPILER(MSVC)\n#pragma warning(pop) \/\/ Disable of 4789\n#endif\n\nALWAYS_INLINE void FEConvolveMatrix::setInteriorPixels(PaintingData& paintingData, int clipRight, int clipBottom, int yStart, int yEnd)\n{\n    \/\/ Must be implemented here, since it refers another ALWAYS_INLINE\n    \/\/ function, which defined in this C++ source file as well\n    if (m_preserveAlpha)\n        fastSetInteriorPixels<true>(paintingData, clipRight, clipBottom, yStart, yEnd);\n    else\n        fastSetInteriorPixels<false>(paintingData, clipRight, clipBottom, yStart, yEnd);\n}\n\nALWAYS_INLINE void FEConvolveMatrix::setOuterPixels(PaintingData& paintingData, int x1, int y1, int x2, int y2)\n{\n    \/\/ Although this function can be moved to the header, it is implemented here\n    \/\/ because setInteriorPixels is also implemented here\n    if (m_preserveAlpha)\n        fastSetOuterPixels<true>(paintingData, x1, y1, x2, y2);\n    else\n        fastSetOuterPixels<false>(paintingData, x1, y1, x2, y2);\n}\n\nvoid FEConvolveMatrix::platformApplySoftware()\n{\n    FilterEffect* in = inputEffect(0);\n\n    Uint8ClampedArray* resultImage;\n    if (m_preserveAlpha)\n        resultImage = createUnmultipliedImageResult();\n    else\n        resultImage = createPremultipliedImageResult();\n    if (!resultImage)\n        return;\n\n    IntRect effectDrawingRect = requestedRegionOfInputImageData(in->absolutePaintRect());\n\n    RefPtr<Uint8ClampedArray> srcPixelArray;\n    if (m_preserveAlpha)\n        srcPixelArray = in->unmultipliedResult(effectDrawingRect);\n    else\n        srcPixelArray = in->premultipliedResult(effectDrawingRect);\n\n    if (!srcPixelArray)\n        return;\n\n    IntSize paintSize = absolutePaintRect().size();\n    PaintingData paintingData = {\n        *srcPixelArray,\n        *resultImage,\n        paintSize.width(),\n        paintSize.height(),\n        m_bias * 255,\n        normalizedFloats(m_kernelMatrix)\n    };\n\n    \/\/ Drawing fully covered pixels\n    int clipRight = paintSize.width() - m_kernelSize.width();\n    int clipBottom = paintSize.height() - m_kernelSize.height();\n\n    if (clipRight < 0 || clipBottom < 0) {\n        \/\/ Rare situation, not optimizied for speed\n        setOuterPixels(paintingData, 0, 0, paintSize.width(), paintSize.height());\n        return;\n    }\n\n    if (int iterations = (absolutePaintRect().width() * absolutePaintRect().height()) \/ s_minimalRectDimension) {\n        int stride = clipBottom \/ iterations;\n        int chunkCount = (clipBottom + stride - 1) \/ stride;\n\n        WorkQueue::concurrentApply(chunkCount, [&](size_t index) {\n            int yStart = (stride * index);\n            int yEnd = std::min<int>(stride * (index + 1), clipBottom);\n\n            setInteriorPixels(paintingData, clipRight, clipBottom, yStart, yEnd);\n        });\n    } else\n        setInteriorPixels(paintingData, clipRight, clipBottom, 0, clipBottom);\n\n    clipRight += m_targetOffset.x() + 1;\n    clipBottom += m_targetOffset.y() + 1;\n    if (m_targetOffset.y() > 0)\n        setOuterPixels(paintingData, 0, 0, paintSize.width(), m_targetOffset.y());\n    if (clipBottom < paintSize.height())\n        setOuterPixels(paintingData, 0, clipBottom, paintSize.width(), paintSize.height());\n    if (m_targetOffset.x() > 0)\n        setOuterPixels(paintingData, 0, m_targetOffset.y(), m_targetOffset.x(), clipBottom);\n    if (clipRight < paintSize.width())\n        setOuterPixels(paintingData, clipRight, m_targetOffset.y(), paintSize.width(), clipBottom);\n}\n\nstatic TextStream& operator<<(TextStream& ts, const EdgeModeType& type)\n{\n    switch (type) {\n    case EDGEMODE_UNKNOWN:\n        ts << \"UNKNOWN\";\n        break;\n    case EDGEMODE_DUPLICATE:\n        ts << \"DUPLICATE\";\n        break;\n    case EDGEMODE_WRAP:\n        ts << \"WRAP\";\n        break;\n    case EDGEMODE_NONE:\n        ts << \"NONE\";\n        break;\n    }\n    return ts;\n}\n\nTextStream& FEConvolveMatrix::externalRepresentation(TextStream& ts) const\n{\n    ts << indent << \"[feConvolveMatrix\";\n    FilterEffect::externalRepresentation(ts);\n    ts << \" order=\\\"\" << m_kernelSize << \"\\\" \"\n       << \"kernelMatrix=\\\"\" << m_kernelMatrix  << \"\\\" \"\n       << \"divisor=\\\"\" << m_divisor << \"\\\" \"\n       << \"bias=\\\"\" << m_bias << \"\\\" \"\n       << \"target=\\\"\" << m_targetOffset << \"\\\" \"\n       << \"edgeMode=\\\"\" << m_edgeMode << \"\\\" \"\n       << \"kernelUnitLength=\\\"\" << m_kernelUnitLength << \"\\\" \"\n       << \"preserveAlpha=\\\"\" << m_preserveAlpha << \"\\\"]\\n\";\n\n    TextStream::IndentScope indentScope(ts);\n    inputEffect(0)->externalRepresentation(ts);\n    return ts;\n}\n\n}; \/\/ namespace WebCore\n","avg_line_length":35.3668763103,"max_line_length":163,"alphanum_fraction":0.6370480142,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":207335,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/===--- TypeCheckDecl.cpp - Type Checking for Declarations ---------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements semantic analysis for declarations.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"CodeSynthesis.h\"\n#include \"ConstraintSystem.h\"\n#include \"DerivedConformances.h\"\n#include \"TypeChecker.h\"\n#include \"TypeCheckAccess.h\"\n#include \"TypeCheckType.h\"\n#include \"MiscDiagnostics.h\"\n#include \"swift\/AST\/AccessScope.h\"\n#include \"swift\/AST\/ASTPrinter.h\"\n#include \"swift\/AST\/ASTVisitor.h\"\n#include \"swift\/AST\/ASTWalker.h\"\n#include \"swift\/AST\/ExistentialLayout.h\"\n#include \"swift\/AST\/Expr.h\"\n#include \"swift\/AST\/ForeignErrorConvention.h\"\n#include \"swift\/AST\/GenericEnvironment.h\"\n#include \"swift\/AST\/GenericSignatureBuilder.h\"\n#include \"swift\/AST\/Initializer.h\"\n#include \"swift\/AST\/NameLookup.h\"\n#include \"swift\/AST\/PrettyStackTrace.h\"\n#include \"swift\/AST\/PropertyWrappers.h\"\n#include \"swift\/AST\/ProtocolConformance.h\"\n#include \"swift\/AST\/ReferencedNameTracker.h\"\n#include \"swift\/AST\/TypeWalker.h\"\n#include \"swift\/Basic\/Statistic.h\"\n#include \"swift\/Parse\/Lexer.h\"\n#include \"swift\/Parse\/Parser.h\"\n#include \"swift\/Serialization\/SerializedModuleLoader.h\"\n#include \"swift\/Strings.h\"\n#include \"swift\/AST\/TypeCheckRequests.h\"\n#include \"swift\/Basic\/Defer.h\"\n#include \"llvm\/ADT\/APFloat.h\"\n#include \"llvm\/ADT\/APInt.h\"\n#include \"llvm\/ADT\/APSInt.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/DJB.h\"\n\nusing namespace swift;\n\n#define DEBUG_TYPE \"TypeCheckDecl\"\n\nnamespace {\n\n\/\/\/ Used during enum raw value checking to identify duplicate raw values.\n\/\/\/ Character, string, float, and integer literals are all keyed by value.\n\/\/\/ Float and integer literals are additionally keyed by numeric equivalence.\nstruct RawValueKey {\n  enum class Kind : uint8_t {\n    String, Float, Int, Tombstone, Empty\n  } kind;\n  \n  struct IntValueTy {\n    uint64_t v0;\n    uint64_t v1;\n\n    IntValueTy(const APInt &bits) {\n      APInt bits128 = bits.sextOrTrunc(128);\n      assert(bits128.getBitWidth() <= 128);\n      const uint64_t *data = bits128.getRawData();\n      v0 = data[0];\n      v1 = data[1];\n    }\n  };\n\n  struct FloatValueTy {\n    uint64_t v0;\n    uint64_t v1;\n  };\n\n  \/\/ FIXME: doesn't accommodate >64-bit or signed raw integer or float values.\n  union {\n    StringRef stringValue;\n    uint32_t charValue;\n    IntValueTy intValue;\n    FloatValueTy floatValue;\n  };\n  \n  explicit RawValueKey(LiteralExpr *expr) {\n    switch (expr->getKind()) {\n    case ExprKind::IntegerLiteral:\n      kind = Kind::Int;\n      intValue = IntValueTy(cast<IntegerLiteralExpr>(expr)->getValue());\n      return;\n    case ExprKind::FloatLiteral: {\n      APFloat value = cast<FloatLiteralExpr>(expr)->getValue();\n      llvm::APSInt asInt(127, \/*isUnsigned=*\/false);\n      bool isExact = false;\n      APFloat::opStatus status =\n          value.convertToInteger(asInt, APFloat::rmTowardZero, &isExact);\n      if (asInt.getBitWidth() <= 128 && status == APFloat::opOK && isExact) {\n        kind = Kind::Int;\n        intValue = IntValueTy(asInt);\n        return;\n      }\n      APInt bits = value.bitcastToAPInt();\n      const uint64_t *data = bits.getRawData();\n      if (bits.getBitWidth() == 80) {\n        kind = Kind::Float;\n        floatValue = FloatValueTy{ data[0], data[1] };\n      } else {\n        assert(bits.getBitWidth() == 64);\n        kind = Kind::Float;\n        floatValue = FloatValueTy{ data[0], 0 };\n      }\n      return;\n    }\n    case ExprKind::StringLiteral:\n      kind = Kind::String;\n      stringValue = cast<StringLiteralExpr>(expr)->getValue();\n      return;\n    default:\n      llvm_unreachable(\"not a valid literal expr for raw value\");\n    }\n  }\n  \n  explicit RawValueKey(Kind k) : kind(k) {\n    assert((k == Kind::Tombstone || k == Kind::Empty)\n           && \"this ctor is only for creating DenseMap special values\");\n  }\n};\n  \n\/\/\/ Used during enum raw value checking to identify the source of a raw value,\n\/\/\/ which may have been derived by auto-incrementing, for diagnostic purposes.\nstruct RawValueSource {\n  \/\/\/ The decl that has the raw value.\n  EnumElementDecl *sourceElt;\n  \/\/\/ If the sourceDecl didn't explicitly name a raw value, this is the most\n  \/\/\/ recent preceding decl with an explicit raw value. This is used to\n  \/\/\/ diagnose 'autoincrementing from' messages.\n  EnumElementDecl *lastExplicitValueElt;\n};\n\n} \/\/ end anonymous namespace\n\nnamespace llvm {\n\ntemplate<>\nclass DenseMapInfo<RawValueKey> {\npublic:\n  static RawValueKey getEmptyKey() {\n    return RawValueKey(RawValueKey::Kind::Empty);\n  }\n  static RawValueKey getTombstoneKey() {\n    return RawValueKey(RawValueKey::Kind::Tombstone);\n  }\n  static unsigned getHashValue(RawValueKey k) {\n    switch (k.kind) {\n    case RawValueKey::Kind::Float:\n      \/\/ Hash as bits. We want to treat distinct but IEEE-equal values as not\n      \/\/ equal.\n      return DenseMapInfo<uint64_t>::getHashValue(k.floatValue.v0) ^\n             DenseMapInfo<uint64_t>::getHashValue(k.floatValue.v1);\n    case RawValueKey::Kind::Int:\n      return DenseMapInfo<uint64_t>::getHashValue(k.intValue.v0) &\n             DenseMapInfo<uint64_t>::getHashValue(k.intValue.v1);\n    case RawValueKey::Kind::String:\n      \/\/ FIXME: DJB seed=0, audit whether the default seed could be used.\n      return llvm::djbHash(k.stringValue, 0);\n    case RawValueKey::Kind::Empty:\n    case RawValueKey::Kind::Tombstone:\n      return 0;\n    }\n\n    llvm_unreachable(\"Unhandled RawValueKey in switch.\");\n  }\n  static bool isEqual(RawValueKey a, RawValueKey b) {\n    if (a.kind != b.kind)\n      return false;\n    switch (a.kind) {\n    case RawValueKey::Kind::Float:\n      \/\/ Hash as bits. We want to treat distinct but IEEE-equal values as not\n      \/\/ equal.\n      return a.floatValue.v0 == b.floatValue.v0 &&\n             a.floatValue.v1 == b.floatValue.v1;\n    case RawValueKey::Kind::Int:\n      return a.intValue.v0 == b.intValue.v0 &&\n             a.intValue.v1 == b.intValue.v1;\n    case RawValueKey::Kind::String:\n      return a.stringValue.equals(b.stringValue);\n    case RawValueKey::Kind::Empty:\n    case RawValueKey::Kind::Tombstone:\n      return true;\n    }\n\n    llvm_unreachable(\"Unhandled RawValueKey in switch.\");\n  }\n};\n  \n} \/\/ namespace llvm\n\n\/\/\/ Check that the declaration attributes are ok.\nstatic void validateAttributes(TypeChecker &TC, Decl *D);\n\n\/\/\/ Check the inheritance clause of a type declaration or extension thereof.\n\/\/\/\n\/\/\/ This routine performs detailed checking of the inheritance clause of the\n\/\/\/ given type or extension. It need only be called within the primary source\n\/\/\/ file.\nstatic void checkInheritanceClause(\n                    llvm::PointerUnion<TypeDecl *, ExtensionDecl *> declUnion) {\n  DeclContext *DC;\n  MutableArrayRef<TypeLoc> inheritedClause;\n  ExtensionDecl *ext = nullptr;\n  TypeDecl *typeDecl = nullptr;\n  Decl *decl;\n  if ((ext = declUnion.dyn_cast<ExtensionDecl *>())) {\n    decl = ext;\n    DC = ext;\n\n    inheritedClause = ext->getInherited();\n\n    \/\/ Protocol extensions cannot have inheritance clauses.\n    if (auto proto = ext->getExtendedProtocolDecl()) {\n      if (!inheritedClause.empty()) {\n        ext->diagnose(diag::extension_protocol_inheritance,\n                 proto->getName())\n          .highlight(SourceRange(inheritedClause.front().getSourceRange().Start,\n                                 inheritedClause.back().getSourceRange().End));\n        return;\n      }\n    }\n  } else {\n    typeDecl = declUnion.get<TypeDecl *>();\n    decl = typeDecl;\n    if (auto nominal = dyn_cast<NominalTypeDecl>(typeDecl)) {\n      DC = nominal;\n    } else {\n      DC = typeDecl->getDeclContext();\n    }\n\n    inheritedClause = typeDecl->getInherited();\n  }\n\n  \/\/ Can this declaration's inheritance clause contain a class or\n  \/\/ subclass existential?\n  bool canHaveSuperclass = (isa<ClassDecl>(decl) ||\n                            (isa<ProtocolDecl>(decl) &&\n                             !cast<ProtocolDecl>(decl)->isObjC()));\n\n  ASTContext &ctx = decl->getASTContext();\n  auto &diags = ctx.Diags;\n\n  \/\/ Retrieve the location of the start of the inheritance clause.\n  auto getStartLocOfInheritanceClause = [&] {\n    if (ext)\n      return ext->getSourceRange().End;\n\n    return typeDecl->getNameLoc();\n  };\n\n  \/\/ Compute the source range to be used when removing something from an\n  \/\/ inheritance clause.\n  auto getRemovalRange = [&](unsigned i) {\n    \/\/ If there is just one entry, remove the entire inheritance clause.\n    if (inheritedClause.size() == 1) {\n      SourceLoc start = getStartLocOfInheritanceClause();\n      SourceLoc end = inheritedClause[i].getSourceRange().End;\n      return SourceRange(Lexer::getLocForEndOfToken(ctx.SourceMgr, start),\n                         Lexer::getLocForEndOfToken(ctx.SourceMgr, end));\n    }\n\n    \/\/ If we're at the first entry, remove from the start of this entry to the\n    \/\/ start of the next entry.\n    if (i == 0) {\n      return SourceRange(inheritedClause[i].getSourceRange().Start,\n                         inheritedClause[i+1].getSourceRange().Start);\n    }\n\n    \/\/ Otherwise, remove from the end of the previous entry to the end of this\n    \/\/ entry.\n    SourceLoc afterPriorLoc =\n      Lexer::getLocForEndOfToken(ctx.SourceMgr,\n                                 inheritedClause[i-1].getSourceRange().End);\n\n    SourceLoc afterMyEndLoc =\n      Lexer::getLocForEndOfToken(ctx.SourceMgr,\n                                 inheritedClause[i].getSourceRange().End);\n\n    return SourceRange(afterPriorLoc, afterMyEndLoc);\n  };\n\n  \/\/ Check all of the types listed in the inheritance clause.\n  Type superclassTy;\n  SourceRange superclassRange;\n  Optional<std::pair<unsigned, SourceRange>> inheritedAnyObject;\n  for (unsigned i = 0, n = inheritedClause.size(); i != n; ++i) {\n    auto &inherited = inheritedClause[i];\n\n    \/\/ Validate the type.\n    InheritedTypeRequest request{declUnion, i, TypeResolutionStage::Interface};\n    Type inheritedTy = evaluateOrDefault(ctx.evaluator, request, Type());\n\n    \/\/ If we couldn't resolve an the inherited type, or it contains an error,\n    \/\/ ignore it.\n    if (!inheritedTy || inheritedTy->hasError())\n      continue;\n\n    \/\/ For generic parameters and associated types, the GSB checks constraints;\n    \/\/ however, we still want to fire off the requests to produce diagnostics\n    \/\/ in some circular validation cases.\n    if (isa<AbstractTypeParamDecl>(decl))\n      continue;\n\n    \/\/ Check whether we inherited from 'AnyObject' twice.\n    \/\/ Other redundant-inheritance scenarios are checked below, the\n    \/\/ GenericSignatureBuilder (for protocol inheritance) or the\n    \/\/ ConformanceLookupTable (for protocol conformance).\n    if (inheritedTy->isAnyObject()) {\n      if (inheritedAnyObject) {\n        \/\/ If the first occurrence was written as 'class', downgrade the error\n        \/\/ to a warning in such case for backward compatibility with\n        \/\/ Swift <= 4.\n        auto knownIndex = inheritedAnyObject->first;\n        auto knownRange = inheritedAnyObject->second;\n        SourceRange removeRange = getRemovalRange(knownIndex);\n        if (!ctx.LangOpts.isSwiftVersionAtLeast(5) &&\n            (isa<ProtocolDecl>(decl) || isa<AbstractTypeParamDecl>(decl)) &&\n            Lexer::getTokenAtLocation(ctx.SourceMgr, knownRange.Start)\n              .is(tok::kw_class)) {\n          SourceLoc classLoc = knownRange.Start;\n\n          diags.diagnose(classLoc, diag::duplicate_anyobject_class_inheritance)\n            .fixItRemoveChars(removeRange.Start, removeRange.End);\n        } else {\n          diags.diagnose(inherited.getSourceRange().Start,\n                 diag::duplicate_inheritance, inheritedTy)\n            .fixItRemoveChars(removeRange.Start, removeRange.End);\n        }\n        continue;\n      }\n\n      \/\/ Note that we saw inheritance from 'AnyObject'.\n      inheritedAnyObject = { i, inherited.getSourceRange() };\n    }\n\n    if (inheritedTy->isExistentialType()) {\n      auto layout = inheritedTy->getExistentialLayout();\n\n      \/\/ Subclass existentials are not allowed except on classes and\n      \/\/ non-@objc protocols.\n      if (layout.explicitSuperclass &&\n          !canHaveSuperclass) {\n        decl->diagnose(diag::inheritance_from_protocol_with_superclass,\n                       inheritedTy);\n        continue;\n      }\n\n      \/\/ AnyObject is not allowed except on protocols.\n      if (layout.hasExplicitAnyObject &&\n          !isa<ProtocolDecl>(decl)) {\n        decl->diagnose(canHaveSuperclass\n                       ? diag::inheritance_from_non_protocol_or_class\n                       : diag::inheritance_from_non_protocol,\n                       inheritedTy);\n        continue;\n      }\n\n      \/\/ If the existential did not have a class constraint, we're done.\n      if (!layout.explicitSuperclass)\n        continue;\n\n      \/\/ Classes and protocols can inherit from subclass existentials.\n      \/\/ For classes, we check for a duplicate superclass below.\n      \/\/ For protocols, the GSB emits its own warning instead.\n      if (isa<ProtocolDecl>(decl))\n        continue;\n\n      assert(isa<ClassDecl>(decl));\n      assert(canHaveSuperclass);\n      inheritedTy = layout.explicitSuperclass;\n    }\n\n    \/\/ If this is an enum inheritance clause, check for a raw type.\n    if (isa<EnumDecl>(decl)) {\n      \/\/ Check if we already had a raw type.\n      if (superclassTy) {\n        if (superclassTy->isEqual(inheritedTy)) {\n          auto removeRange = getRemovalRange(i);\n          diags.diagnose(inherited.getSourceRange().Start,\n                         diag::duplicate_inheritance, inheritedTy)\n            .fixItRemoveChars(removeRange.Start, removeRange.End);\n        } else {\n          diags.diagnose(inherited.getSourceRange().Start,\n                         diag::multiple_enum_raw_types, superclassTy,\n                         inheritedTy)\n            .highlight(superclassRange);\n        }\n        continue;\n      }\n      \n      \/\/ If this is not the first entry in the inheritance clause, complain.\n      if (i > 0) {\n        auto removeRange = getRemovalRange(i);\n\n        diags.diagnose(inherited.getSourceRange().Start,\n                       diag::raw_type_not_first, inheritedTy)\n          .fixItRemoveChars(removeRange.Start, removeRange.End)\n          .fixItInsert(inheritedClause[0].getSourceRange().Start,\n                       inheritedTy.getString() + \", \");\n\n        \/\/ Fall through to record the raw type.\n      }\n\n      \/\/ Record the raw type.\n      superclassTy = inheritedTy;\n      superclassRange = inherited.getSourceRange();\n      continue;\n    }\n\n    \/\/ If this is a class type, it may be the superclass. We end up here when\n    \/\/ the inherited type is either itself a class, or when it is a subclass\n    \/\/ existential via the existential type path above.\n    if (inheritedTy->getClassOrBoundGenericClass()) {\n      \/\/ First, check if we already had a superclass.\n      if (superclassTy) {\n        \/\/ FIXME: Check for shadowed protocol names, i.e., NSObject?\n\n        if (superclassTy->isEqual(inheritedTy)) {\n          \/\/ Duplicate superclass.\n          auto removeRange = getRemovalRange(i);\n          diags.diagnose(inherited.getSourceRange().Start,\n                         diag::duplicate_inheritance, inheritedTy)\n            .fixItRemoveChars(removeRange.Start, removeRange.End);\n        } else {\n          \/\/ Complain about multiple inheritance.\n          \/\/ Don't emit a Fix-It here. The user has to think harder about this.\n          diags.diagnose(inherited.getSourceRange().Start,\n                         diag::multiple_inheritance, superclassTy, inheritedTy)\n            .highlight(superclassRange);\n        }\n        continue;\n      }\n\n      \/\/ If this is not the first entry in the inheritance clause, complain.\n      if (isa<ClassDecl>(decl) && i > 0) {\n        auto removeRange = getRemovalRange(i);\n        diags.diagnose(inherited.getSourceRange().Start,\n                       diag::superclass_not_first, inheritedTy)\n          .fixItRemoveChars(removeRange.Start, removeRange.End)\n          .fixItInsert(inheritedClause[0].getSourceRange().Start,\n                       inheritedTy.getString() + \", \");\n\n        \/\/ Fall through to record the superclass.\n      }\n\n      if (canHaveSuperclass) {\n        \/\/ Record the superclass.\n        superclassTy = inheritedTy;\n        superclassRange = inherited.getSourceRange();\n        continue;\n      }\n    }\n\n    \/\/ We can't inherit from a non-class, non-protocol type.\n    decl->diagnose(canHaveSuperclass\n                   ? diag::inheritance_from_non_protocol_or_class\n                   : diag::inheritance_from_non_protocol,\n                   inheritedTy);\n    \/\/ FIXME: Note pointing to the declaration 'inheritedTy' references?\n  }\n}\n\n\/\/\/ Check the inheritance clauses generic parameters along with any\n\/\/\/ requirements stored within the generic parameter list.\nstatic void checkGenericParams(GenericParamList *genericParams,\n                               DeclContext *owningDC,\n                               TypeChecker &tc) {\n  if (!genericParams)\n    return;\n\n  for (auto gp : *genericParams) {\n    tc.checkDeclAttributesEarly(gp);\n    checkInheritanceClause(gp);\n  }\n\n  \/\/ Force visitation of each of the requirements here.\n  RequirementRequest::visitRequirements(WhereClauseOwner(owningDC,\n                                                         genericParams),\n                                        TypeResolutionStage::Interface,\n                                        [](Requirement, RequirementRepr *) {\n                                          return false;\n                                        });\n}\n\n\/\/\/ Retrieve the set of protocols the given protocol inherits.\nstatic llvm::TinyPtrVector<ProtocolDecl *>\ngetInheritedForCycleCheck(TypeChecker &tc,\n                          ProtocolDecl *proto,\n                          ProtocolDecl **scratch) {\n  TinyPtrVector<ProtocolDecl *> result;\n\n  bool anyObject = false;\n  for (const auto &found :\n         getDirectlyInheritedNominalTypeDecls(proto, anyObject)) {\n    if (auto protoDecl = dyn_cast<ProtocolDecl>(found.second))\n      result.push_back(protoDecl);\n  }\n\n  return result;\n}\n\n\/\/\/ Retrieve the superclass of the given class.\nstatic ArrayRef<ClassDecl *> getInheritedForCycleCheck(TypeChecker &tc,\n                                                       ClassDecl *classDecl,\n                                                       ClassDecl **scratch) {\n  if (classDecl->hasSuperclass()) {\n    *scratch = classDecl->getSuperclassDecl();\n    return *scratch;\n  }\n  return { };\n}\n\n\/\/\/ Retrieve the raw type of the given enum.\nstatic ArrayRef<EnumDecl *> getInheritedForCycleCheck(TypeChecker &tc,\n                                                      EnumDecl *enumDecl,\n                                                      EnumDecl **scratch) {\n  if (enumDecl->hasRawType()) {\n    *scratch = enumDecl->getRawType()->getEnumOrBoundGenericEnum();\n    return *scratch ? ArrayRef<EnumDecl*>(*scratch) : ArrayRef<EnumDecl*>{};\n  }\n  return { };\n}\n\n\/\/\/ Check for circular inheritance.\ntemplate<typename T>\nstatic void checkCircularity(TypeChecker &tc, T *decl,\n                             Diag<Identifier> circularDiag,\n                             DescriptiveDeclKind declKind,\n                             SmallVectorImpl<T *> &path) {\n  switch (decl->getCircularityCheck()) {\n  case CircularityCheck::Checked:\n    return;\n\n  case CircularityCheck::Checking: {\n    \/\/ We're already checking this type, which means we have a cycle.\n\n    \/\/ The beginning of the path might not be part of the cycle, so find\n    \/\/ where the cycle starts.\n    assert(!path.empty());\n\n    auto cycleStart = path.end() - 1;\n    while (*cycleStart != decl) {\n      assert(cycleStart != path.begin() && \"Missing cycle start?\");\n      --cycleStart;\n    }\n\n    \/\/ If the path length is 1 the type directly references itself.\n    if (path.end() - cycleStart == 1) {\n      tc.diagnose(path.back()->getLoc(),\n                  circularDiag,\n                  path.back()->getName());\n\n      break;\n    }\n\n    \/\/ Diagnose the cycle.\n    tc.diagnose(decl->getLoc(), circularDiag,\n                (*cycleStart)->getName());\n    for (auto i = cycleStart + 1, iEnd = path.end(); i != iEnd; ++i) {\n      tc.diagnose(*i, diag::kind_declname_declared_here,\n                  declKind, (*i)->getName());\n    }\n\n    break;\n  }\n\n  case CircularityCheck::Unchecked: {\n    \/\/ Walk to the inherited class or protocols.\n    path.push_back(decl);\n    decl->setCircularityCheck(CircularityCheck::Checking);\n    T *scratch = nullptr;\n    for (auto inherited : getInheritedForCycleCheck(tc, decl, &scratch)) {\n      checkCircularity(tc, inherited, circularDiag, declKind, path);\n    }\n    decl->setCircularityCheck(CircularityCheck::Checked);\n    path.pop_back();\n    break;\n  }\n  }\n}\n\n\/\/\/ Set each bound variable in the pattern to have an error type.\nstatic void setBoundVarsTypeError(Pattern *pattern, ASTContext &ctx) {\n  pattern->forEachVariable([&](VarDecl *var) {\n    \/\/ Don't change the type of a variable that we've been able to\n    \/\/ compute a type for.\n    if (var->hasType() && !var->getType()->hasError())\n      return;\n\n    var->markInvalid();\n  });\n}\n\n\/\/\/ Expose TypeChecker's handling of GenericParamList to SIL parsing.\nGenericEnvironment *\nTypeChecker::handleSILGenericParams(GenericParamList *genericParams,\n                                    DeclContext *DC) {\n  if (genericParams == nullptr)\n    return nullptr;\n\n  SmallVector<GenericParamList *, 2> nestedList;\n  for (; genericParams; genericParams = genericParams->getOuterParameters()) {\n    nestedList.push_back(genericParams);\n  }\n\n  std::reverse(nestedList.begin(), nestedList.end());\n\n  for (unsigned i = 0, e = nestedList.size(); i < e; ++i) {\n    auto genericParams = nestedList[i];\n    genericParams->setDepth(i);\n  }\n\n  return checkGenericEnvironment(nestedList.back(), DC,\n                                 \/*parentSig=*\/nullptr,\n                                 \/*allowConcreteGenericParams=*\/true,\n                                 \/*ext=*\/nullptr);\n}\n\n\/\/\/ Build a default initializer for the given type.\nstatic Expr *buildDefaultInitializer(TypeChecker &tc, Type type) {\n  \/\/ Default-initialize optional types and weak values to 'nil'.\n  if (type->getReferenceStorageReferent()->getOptionalObjectType())\n    return new (tc.Context) NilLiteralExpr(SourceLoc(), \/*Implicit=*\/true);\n\n  \/\/ Build tuple literals for tuple types.\n  if (auto tupleType = type->getAs<TupleType>()) {\n    SmallVector<Expr *, 2> inits;\n    for (const auto &elt : tupleType->getElements()) {\n      if (elt.isVararg())\n        return nullptr;\n\n      auto eltInit = buildDefaultInitializer(tc, elt.getType());\n      if (!eltInit)\n        return nullptr;\n\n      inits.push_back(eltInit);\n    }\n\n    return TupleExpr::createImplicit(tc.Context, inits, { });\n  }\n\n  \/\/ We don't default-initialize anything else.\n  return nullptr;\n}\n\n\/\/\/ Check whether \\c current is a redeclaration.\nstatic void checkRedeclaration(TypeChecker &tc, ValueDecl *current) {\n  \/\/ If we've already checked this declaration, don't do it again.\n  if (current->alreadyCheckedRedeclaration())\n    return;\n\n  \/\/ If there's no type yet, come back to it later.\n  if (!current->hasInterfaceType())\n    return;\n  \n  \/\/ Make sure we don't do this checking again.\n  current->setCheckedRedeclaration(true);\n\n  \/\/ Ignore invalid and anonymous declarations.\n  if (current->isInvalid() || !current->hasName())\n    return;\n\n  \/\/ If this declaration isn't from a source file, don't check it.\n  \/\/ FIXME: Should restrict this to the source file we care about.\n  DeclContext *currentDC = current->getDeclContext();\n  SourceFile *currentFile = currentDC->getParentSourceFile();\n  if (!currentFile || currentDC->isLocalContext())\n    return;\n\n  ReferencedNameTracker *tracker = currentFile->getReferencedNameTracker();\n  bool isCascading = (current->getFormalAccess() > AccessLevel::FilePrivate);\n\n  \/\/ Find other potential definitions.\n  SmallVector<ValueDecl *, 4> otherDefinitions;\n  if (currentDC->isTypeContext()) {\n    \/\/ Look within a type context.\n    if (auto nominal = currentDC->getSelfNominalTypeDecl()) {\n      auto found = nominal->lookupDirect(current->getBaseName());\n      otherDefinitions.append(found.begin(), found.end());\n      if (tracker)\n        tracker->addUsedMember({nominal, current->getBaseName()}, isCascading);\n    }\n  } else {\n    \/\/ Look within a module context.\n    currentFile->getParentModule()->lookupValue({ }, current->getBaseName(),\n                                                NLKind::QualifiedLookup,\n                                                otherDefinitions);\n    if (tracker)\n      tracker->addTopLevelName(current->getBaseName(), isCascading);\n  }\n\n  \/\/ Compare this signature against the signature of other\n  \/\/ declarations with the same name.\n  OverloadSignature currentSig = current->getOverloadSignature();\n  CanType currentSigType = current->getOverloadSignatureType();\n  ModuleDecl *currentModule = current->getModuleContext();\n  for (auto other : otherDefinitions) {\n    \/\/ Skip invalid declarations and ourselves.\n    if (current == other || other->isInvalid())\n      continue;\n\n    \/\/ Skip declarations in other modules.\n    if (currentModule != other->getModuleContext())\n      continue;\n\n    \/\/ Don't compare methods vs. non-methods (which only happens with\n    \/\/ operators).\n    if (currentDC->isTypeContext() != other->getDeclContext()->isTypeContext())\n      continue;\n\n    \/\/ Check whether the overload signatures conflict (ignoring the type for\n    \/\/ now).\n    auto otherSig = other->getOverloadSignature();\n    if (!conflicting(currentSig, otherSig))\n      continue;\n\n    \/\/ Validate the declaration but only if it came from a different context.\n    if (other->getDeclContext() != current->getDeclContext())\n      tc.validateDecl(other);\n\n    \/\/ Skip invalid or not yet seen declarations.\n    if (other->isInvalid() || !other->hasInterfaceType())\n      continue;\n\n    \/\/ Skip declarations in other files.\n    \/\/ In practice, this means we will warn on a private declaration that\n    \/\/ shadows a non-private one, but only in the file where the shadowing\n    \/\/ happens. We will warn on conflicting non-private declarations in both\n    \/\/ files.\n    if (!other->isAccessibleFrom(currentDC))\n      continue;\n\n    const auto markInvalid = [&current]() {\n      current->setInvalid();\n      if (auto *varDecl = dyn_cast<VarDecl>(current))\n        if (varDecl->hasType())\n          varDecl->setType(ErrorType::get(varDecl->getType()));\n      if (current->hasInterfaceType())\n        current->setInterfaceType(ErrorType::get(current->getInterfaceType()));\n    };\n\n    \/\/ Thwart attempts to override the same declaration more than once.\n    const auto *currentOverride = current->getOverriddenDecl();\n    const auto *otherOverride = other->getOverriddenDecl();\n    if (currentOverride && currentOverride == otherOverride) {\n      tc.diagnose(current, diag::multiple_override, current->getFullName());\n      tc.diagnose(other, diag::multiple_override_prev, other->getFullName());\n      markInvalid();\n      break;\n    }\n\n    \/\/ Get the overload signature type.\n    CanType otherSigType = other->getOverloadSignatureType();\n\n    bool wouldBeSwift5Redeclaration = false;\n    auto isRedeclaration = conflicting(tc.Context, currentSig, currentSigType,\n                                       otherSig, otherSigType,\n                                       &wouldBeSwift5Redeclaration);\n    \/\/ If there is another conflict, complain.\n    if (isRedeclaration || wouldBeSwift5Redeclaration) {\n      \/\/ If the two declarations occur in the same source file, make sure\n      \/\/ we get the diagnostic ordering to be sensible.\n      if (auto otherFile = other->getDeclContext()->getParentSourceFile()) {\n        if (currentFile == otherFile &&\n            current->getLoc().isValid() &&\n            other->getLoc().isValid() &&\n            tc.Context.SourceMgr.isBeforeInBuffer(current->getLoc(),\n                                                  other->getLoc())) {\n          std::swap(current, other);\n        }\n      }\n\n      \/\/ If we're currently looking at a .sil and the conflicting declaration\n      \/\/ comes from a .sib, don't error since we won't be considering the sil\n      \/\/ from the .sib. So it's fine for the .sil to shadow it, since that's the\n      \/\/ one we want.\n      if (currentFile->Kind == SourceFileKind::SIL) {\n        auto *otherFile = dyn_cast<SerializedASTFile>(\n            other->getDeclContext()->getModuleScopeContext());\n        if (otherFile && otherFile->isSIB())\n          continue;\n      }\n\n      \/\/ If the conflicting declarations have non-overlapping availability and,\n      \/\/ we allow the redeclaration to proceed if...\n      \/\/\n      \/\/ - they are initializers with different failability,\n      bool isAcceptableVersionBasedChange = false;\n      {\n        const auto *currentInit = dyn_cast<ConstructorDecl>(current);\n        const auto *otherInit = dyn_cast<ConstructorDecl>(other);\n        if (currentInit && otherInit &&\n            ((currentInit->getFailability() == OTK_None) !=\n             (otherInit->getFailability() == OTK_None))) {\n          isAcceptableVersionBasedChange = true;\n        }\n      }\n      \/\/ - one throws and the other does not,\n      {\n        const auto *currentAFD = dyn_cast<AbstractFunctionDecl>(current);\n        const auto *otherAFD = dyn_cast<AbstractFunctionDecl>(other);\n        if (currentAFD && otherAFD &&\n            currentAFD->hasThrows() != otherAFD->hasThrows()) {\n          isAcceptableVersionBasedChange = true;\n        }\n      }\n      \/\/ - or they are computed properties of different types,\n      {\n        const auto *currentVD = dyn_cast<VarDecl>(current);\n        const auto *otherVD = dyn_cast<VarDecl>(other);\n        if (currentVD && otherVD &&\n            !currentVD->hasStorage() &&\n            !otherVD->hasStorage() &&\n            !currentVD->getInterfaceType()->isEqual(\n              otherVD->getInterfaceType())) {\n          isAcceptableVersionBasedChange = true;\n        }\n      }\n\n      if (isAcceptableVersionBasedChange) {\n        class AvailabilityRange {\n          Optional<llvm::VersionTuple> introduced;\n          Optional<llvm::VersionTuple> obsoleted;\n\n        public:\n          static AvailabilityRange from(const ValueDecl *VD) {\n            AvailabilityRange result;\n            for (auto *attr : VD->getAttrs().getAttributes<AvailableAttr>()) {\n              if (attr->PlatformAgnostic ==\n                    PlatformAgnosticAvailabilityKind::SwiftVersionSpecific) {\n                if (attr->Introduced)\n                  result.introduced = attr->Introduced;\n                if (attr->Obsoleted)\n                  result.obsoleted = attr->Obsoleted;\n              }\n            }\n            return result;\n          }\n\n          bool fullyPrecedes(const AvailabilityRange &other) const {\n            if (!obsoleted.hasValue())\n              return false;\n            if (!other.introduced.hasValue())\n              return false;\n            return *obsoleted <= *other.introduced;\n          }\n\n          bool overlaps(const AvailabilityRange &other) const {\n            return !fullyPrecedes(other) && !other.fullyPrecedes(*this);\n          }\n        };\n\n        auto currentAvail = AvailabilityRange::from(current);\n        auto otherAvail = AvailabilityRange::from(other);\n        if (!currentAvail.overlaps(otherAvail))\n          continue;\n      }\n\n      \/\/ If both are VarDecls, and both have exactly the same type, then\n      \/\/ matching the Swift 4 behaviour (i.e. just emitting the future-compat\n      \/\/ warning) will result in SILGen crashes due to both properties mangling\n      \/\/ the same, so it's better to just follow the Swift 5 behaviour and emit\n      \/\/ the actual error.\n      if (wouldBeSwift5Redeclaration && isa<VarDecl>(current) &&\n          isa<VarDecl>(other) &&\n          current->getInterfaceType()->isEqual(other->getInterfaceType())) {\n        wouldBeSwift5Redeclaration = false;\n      }\n\n      \/\/ If this isn't a redeclaration in the current version of Swift, but\n      \/\/ would be in Swift 5 mode, emit a warning instead of an error.\n      if (wouldBeSwift5Redeclaration) {\n        tc.diagnose(current, diag::invalid_redecl_swift5_warning,\n                    current->getFullName());\n        tc.diagnose(other, diag::invalid_redecl_prev, other->getFullName());\n      } else {\n        const auto *otherInit = dyn_cast<ConstructorDecl>(other);\n        \/\/ Provide a better description for implicit initializers.\n        if (otherInit && otherInit->isImplicit()) {\n          \/\/ Skip conflicts with inherited initializers, which only happen\n          \/\/ when the current declaration is within an extension. The override\n          \/\/ checker should have already taken care of emitting a more\n          \/\/ productive diagnostic.\n          if (!other->getOverriddenDecl())\n            tc.diagnose(current, diag::invalid_redecl_init,\n                        current->getFullName(),\n                        otherInit->isMemberwiseInitializer());\n        } else {\n          tc.diagnose(current, diag::invalid_redecl, current->getFullName());\n          tc.diagnose(other, diag::invalid_redecl_prev, other->getFullName());\n        }\n        markInvalid();\n      }\n\n      \/\/ Make sure we don't do this checking again for the same decl. We also\n      \/\/ set this at the beginning of the function, but we might have swapped\n      \/\/ the decls for diagnostics; so ensure we also set this for the actual\n      \/\/ decl we diagnosed on.\n      current->setCheckedRedeclaration(true);\n      break;\n    }\n  }\n}\n\n\/\/\/ Does the context allow pattern bindings that don't bind any variables?\nstatic bool contextAllowsPatternBindingWithoutVariables(DeclContext *dc) {\n  \n  \/\/ Property decls in type context must bind variables.\n  if (dc->isTypeContext())\n    return false;\n  \n  \/\/ Global variable decls must bind variables, except in scripts.\n  if (dc->isModuleScopeContext()) {\n    if (dc->getParentSourceFile()\n        && dc->getParentSourceFile()->isScriptMode())\n      return true;\n    \n    return false;\n  }\n  \n  return true;\n}\n\n\/\/\/ Validate the \\c entryNumber'th entry in \\c binding.\nstatic void validatePatternBindingEntry(TypeChecker &tc,\n                                        PatternBindingDecl *binding,\n                                        unsigned entryNumber) {\n  \/\/ If the pattern already has a type, we're done.\n  if (binding->getPattern(entryNumber)->hasType())\n    return;\n\n  \/\/ Resolve the pattern.\n  auto *pattern = tc.resolvePattern(binding->getPattern(entryNumber),\n                                    binding->getDeclContext(),\n                                    \/*isStmtCondition*\/true);\n  if (!pattern) {\n    binding->setInvalid();\n    binding->getPattern(entryNumber)->setType(ErrorType::get(tc.Context));\n    return;\n  }\n\n  binding->setPattern(entryNumber, pattern,\n                      binding->getPatternList()[entryNumber].getInitContext());\n\n  \/\/ Validate 'static'\/'class' on properties in nominal type decls.\n  auto StaticSpelling = binding->getStaticSpelling();\n  if (StaticSpelling != StaticSpellingKind::None &&\n      isa<ExtensionDecl>(binding->getDeclContext())) {\n    if (auto *NTD = binding->getDeclContext()->getSelfNominalTypeDecl()) {\n      if (!isa<ClassDecl>(NTD)) {\n        if (StaticSpelling == StaticSpellingKind::KeywordClass) {\n          tc.diagnose(binding, diag::class_var_not_in_class, false)\n            .fixItReplace(binding->getStaticLoc(), \"static\");\n          tc.diagnose(NTD, diag::extended_type_declared_here);\n        }\n      }\n    }\n  }\n\n  \/\/ Check the pattern. We treat type-checking a PatternBindingDecl like\n  \/\/ type-checking an expression because that's how the initial binding is\n  \/\/ checked, and they have the same effect on the file's dependencies.\n  \/\/\n  \/\/ In particular, it's \/not\/ correct to check the PBD's DeclContext because\n  \/\/ top-level variables in a script file are accessible from other files,\n  \/\/ even though the PBD is inside a TopLevelCodeDecl.\n  TypeResolutionOptions options(TypeResolverContext::PatternBindingDecl);\n\n  if (binding->isInitialized(entryNumber)) {\n    \/\/ If we have an initializer, we can also have unknown types.\n    options |= TypeResolutionFlags::AllowUnspecifiedTypes;\n    options |= TypeResolutionFlags::AllowUnboundGenerics;\n  }\n\n  if (tc.typeCheckPattern(pattern, binding->getDeclContext(), options)) {\n    setBoundVarsTypeError(pattern, tc.Context);\n    binding->setInvalid();\n    pattern->setType(ErrorType::get(tc.Context));\n    return;\n  }\n\n  \/\/ If the pattern didn't get a type or if it contains an unbound generic type,\n  \/\/ we'll need to check the initializer.\n  if (!pattern->hasType() || pattern->getType()->hasUnboundGenericType()) {\n    if (tc.typeCheckPatternBinding(binding, entryNumber))\n      return;\n    \n    \/\/ A pattern binding at top level is not allowed to pick up another decl's\n    \/\/ opaque result type as its type by type inference.\n    if (!binding->getDeclContext()->isLocalContext()\n        && binding->getInit(entryNumber)->getType()->hasOpaqueArchetype()) {\n      \/\/ TODO: Check whether the type is the pattern binding's own opaque type.\n      tc.diagnose(binding, diag::inferred_opaque_type,\n                  binding->getInit(entryNumber)->getType());\n    }\n  }\n\n  \/\/ If the pattern binding appears in a type or library file context, then\n  \/\/ it must bind at least one variable.\n  if (!contextAllowsPatternBindingWithoutVariables(binding->getDeclContext())) {\n    llvm::SmallVector<VarDecl*, 2> vars;\n    binding->getPattern(entryNumber)->collectVariables(vars);\n    if (vars.empty()) {\n      \/\/ Selector for error message.\n      enum : unsigned {\n        Property,\n        GlobalVariable,\n      };\n      tc.diagnose(binding->getPattern(entryNumber)->getLoc(),\n                  diag::pattern_binds_no_variables,\n                  binding->getDeclContext()->isTypeContext()\n                                                   ? Property : GlobalVariable);\n    }\n  }\n\n  \/\/ If we have any type-adjusting attributes, apply them here.\n  assert(binding->getPattern(entryNumber)->hasType() && \"Type missing?\");\n  if (auto var = binding->getSingleVar()) {\n    tc.checkTypeModifyingDeclAttributes(var);\n  }\n}\n\n\/\/\/ Validate the entries in the given pattern binding declaration.\nstatic void validatePatternBindingEntries(TypeChecker &tc,\n                                          PatternBindingDecl *binding) {\n  if (binding->hasValidationStarted())\n    return;\n\n  DeclValidationRAII IBV(binding);\n\n  for (unsigned i = 0, e = binding->getNumPatternEntries(); i != e; ++i)\n    validatePatternBindingEntry(tc, binding, i);\n}\n\nnamespace {\n\/\/ The raw values of this enum must be kept in sync with\n\/\/ diag::implicitly_final_cannot_be_open.\nenum class ImplicitlyFinalReason : unsigned {\n  \/\/\/ A property was declared with 'let'.\n  Let,\n  \/\/\/ The containing class is final.\n  FinalClass,\n  \/\/\/ A member was declared as 'static'.\n  Static\n};\n}\n\nstatic bool inferFinalAndDiagnoseIfNeeded(ValueDecl *D, ClassDecl *cls,\n                                          StaticSpellingKind staticSpelling) {\n  \/\/ Are there any reasons to infer 'final'? Prefer 'static' over the class\n  \/\/ being final for the purposes of diagnostics.\n  Optional<ImplicitlyFinalReason> reason;\n  if (staticSpelling == StaticSpellingKind::KeywordStatic) {\n    reason = ImplicitlyFinalReason::Static;\n\n    if (auto finalAttr = D->getAttrs().getAttribute<FinalAttr>()) {\n      auto finalRange = finalAttr->getRange();\n      if (finalRange.isValid()) {\n        auto &context = D->getASTContext();\n        context.Diags.diagnose(finalRange.Start, diag::static_decl_already_final)\n        .fixItRemove(finalRange);\n      }\n    }\n  } else if (cls->isFinal()) {\n    reason = ImplicitlyFinalReason::FinalClass;\n  }\n\n  if (!reason)\n    return false;\n\n  if (D->getFormalAccess() == AccessLevel::Open) {\n    auto &context = D->getASTContext();\n    auto diagID = diag::implicitly_final_cannot_be_open;\n    if (!context.isSwiftVersionAtLeast(5))\n      diagID = diag::implicitly_final_cannot_be_open_swift4;\n    auto inFlightDiag = context.Diags.diagnose(D, diagID,\n                                    static_cast<unsigned>(reason.getValue()));\n    fixItAccess(inFlightDiag, D, AccessLevel::Public);\n  }\n\n  return true;\n}\n\n\/\/\/ Make the given declaration 'dynamic', if it isn't already marked as such.\nstatic void makeDynamic(ValueDecl *decl) {\n  \/\/ If there isn't already a 'dynamic' attribute, add an inferred one.\n  if (decl->getAttrs().hasAttribute<DynamicAttr>())\n    return;\n  \n  auto attr = new (decl->getASTContext()) DynamicAttr(\/*implicit=*\/true);\n  decl->getAttrs().add(attr);\n}\n\nstatic llvm::Expected<bool> isStorageDynamic(Evaluator &evaluator,\n                                             AccessorDecl *accessor) {\n  auto isDynamicResult = evaluator(IsDynamicRequest{accessor->getStorage()});\n\n  if (!isDynamicResult)\n    return isDynamicResult;\n\n  return *isDynamicResult;\n}\n\n\/\/\/ Runtime-replacable accessors are dynamic when their storage declaration\n\/\/\/ is dynamic and they were explicitly defined or they are implicitly defined\n\/\/\/ getter\/setter because no accessor was defined.\nstatic llvm::Expected<bool>\ndoesAccessorNeedDynamicAttribute(AccessorDecl *accessor, Evaluator &evaluator) {\n  auto kind = accessor->getAccessorKind();\n  auto storage = accessor->getStorage();\n  bool isObjC = storage->isObjC();\n\n  switch (kind) {\n  case AccessorKind::Get: {\n    auto readImpl = storage->getReadImpl();\n    if (!isObjC &&\n        (readImpl == ReadImplKind::Read || readImpl == ReadImplKind::Address))\n      return false;\n    return isStorageDynamic(evaluator, accessor);\n  }\n  case AccessorKind::Set: {\n    auto writeImpl = storage->getWriteImpl();\n    if (!isObjC && (writeImpl == WriteImplKind::Modify ||\n                    writeImpl == WriteImplKind::MutableAddress ||\n                    writeImpl == WriteImplKind::StoredWithObservers))\n      return false;\n    return isStorageDynamic(evaluator, accessor);\n  }\n  case AccessorKind::Read:\n    if (!isObjC && storage->getReadImpl() == ReadImplKind::Read)\n      return isStorageDynamic(evaluator, accessor);\n    return false;\n  case AccessorKind::Modify: {\n    if (!isObjC && storage->getWriteImpl() == WriteImplKind::Modify)\n      return isStorageDynamic(evaluator, accessor);\n    return false;\n  }\n  case AccessorKind::MutableAddress: {\n    if (!isObjC && storage->getWriteImpl() == WriteImplKind::MutableAddress)\n      return isStorageDynamic(evaluator, accessor);\n    return false;\n  }\n  case AccessorKind::Address: {\n    if (!isObjC && storage->getReadImpl() == ReadImplKind::Address)\n      return isStorageDynamic(evaluator, accessor);\n    return false;\n  }\n  case AccessorKind::DidSet:\n  case AccessorKind::WillSet:\n    if (!isObjC &&\n        storage->getWriteImpl() == WriteImplKind::StoredWithObservers)\n      return isStorageDynamic(evaluator, accessor);\n    return false;\n  }\n  llvm_unreachable(\"covered switch\");\n}\n\nllvm::Expected<bool>\nIsFinalRequest::evaluate(Evaluator &evaluator, ValueDecl *decl) const {\n  if (isa<ClassDecl>(decl))\n    return decl->getAttrs().hasAttribute<FinalAttr>();\n\n  auto cls = decl->getDeclContext()->getSelfClassDecl();\n  if (!cls)\n    return false;\n\n  switch (decl->getKind()) {\n    case DeclKind::Var: {\n      \/\/ Properties are final if they are declared 'static' or a 'let'\n      auto *VD = cast<VarDecl>(decl);\n\n      \/\/ Backing storage for 'lazy' or property wrappers is always final.\n      if (VD->isLazyStorageProperty() ||\n          VD->getOriginalWrappedProperty())\n        return true;\n\n      if (auto *nominalDecl = VD->getDeclContext()->getSelfClassDecl()) {\n        \/\/ If this variable is a class member, mark it final if the\n        \/\/ class is final, or if it was declared with 'let'.\n        auto *PBD = VD->getParentPatternBinding();\n        if (PBD && inferFinalAndDiagnoseIfNeeded(decl, cls, PBD->getStaticSpelling()))\n          return true;\n\n        if (VD->isLet()) {\n          if (VD->getFormalAccess() == AccessLevel::Open) {\n            auto &context = decl->getASTContext();\n            auto diagID = diag::implicitly_final_cannot_be_open;\n            if (!context.isSwiftVersionAtLeast(5))\n              diagID = diag::implicitly_final_cannot_be_open_swift4;\n            auto inFlightDiag =\n              context.Diags.diagnose(decl, diagID,\n                                     static_cast<unsigned>(ImplicitlyFinalReason::Let));\n            fixItAccess(inFlightDiag, decl, AccessLevel::Public);\n          }\n\n          return true;\n        }\n      }\n\n      break;\n    }\n\n    case DeclKind::Func: {\n      \/\/ Methods declared 'static' are final.\n      auto staticSpelling = cast<FuncDecl>(decl)->getStaticSpelling();\n      if (inferFinalAndDiagnoseIfNeeded(decl, cls, staticSpelling))\n        return true;\n      break;\n    }\n\n    case DeclKind::Accessor:\n      if (auto accessor = dyn_cast<AccessorDecl>(decl)) {\n        switch (accessor->getAccessorKind()) {\n          case AccessorKind::DidSet:\n          case AccessorKind::WillSet:\n            \/\/ Observing accessors are marked final if in a class.\n            return true;\n\n          case AccessorKind::Read:\n          case AccessorKind::Modify:\n          case AccessorKind::Get:\n          case AccessorKind::Set: {\n            \/\/ Coroutines and accessors are final if their storage is.\n            auto storage = accessor->getStorage();\n            if (storage->isFinal())\n              return true;\n            break;\n          }\n\n          default:\n            break;\n        }\n      }\n      break;\n\n    case DeclKind::Subscript: {\n      \/\/ Member subscripts.\n      auto staticSpelling = cast<SubscriptDecl>(decl)->getStaticSpelling();\n      if (inferFinalAndDiagnoseIfNeeded(decl, cls, staticSpelling))\n        return true;\n      break;\n    }\n\n    default:\n      break;\n  }\n\n  if (decl->getAttrs().hasAttribute<FinalAttr>())\n    return true;\n\n  return false;\n}\n\nllvm::Expected<bool>\nIsDynamicRequest::evaluate(Evaluator &evaluator, ValueDecl *decl) const {\n  \/\/ If we can't infer dynamic here, don't.\n  if (!DeclAttribute::canAttributeAppearOnDecl(DAK_Dynamic, decl))\n    return false;\n\n  \/\/ Add dynamic if -enable-implicit-dynamic was requested.\n  TypeChecker::addImplicitDynamicAttribute(decl);\n\n  \/\/ If 'dynamic' was explicitly specified, check it.\n  if (decl->getAttrs().hasAttribute<DynamicAttr>()) {\n    return true;\n  }\n\n  if (auto accessor = dyn_cast<AccessorDecl>(decl)) {\n    \/\/ Swift 5: Runtime-replacable accessors are dynamic when their storage declaration\n    \/\/ is dynamic and they were explicitly defined or they are implicitly defined\n    \/\/ getter\/setter because no accessor was defined.\n    if (decl->getASTContext().LangOpts.isSwiftVersionAtLeast(5))\n      return doesAccessorNeedDynamicAttribute(accessor, evaluator);\n\n    \/\/ Pre Swift 5: Runtime-replacable accessors are dynamic when their storage declaration\n    \/\/ is dynamic. Other accessors are never dynamic.\n    switch (accessor->getAccessorKind()) {\n    case AccessorKind::Get:\n    case AccessorKind::Set: {\n      auto isDynamicResult = evaluator(\n          IsDynamicRequest{accessor->getStorage()});\n      if (isDynamicResult && *isDynamicResult)\n        makeDynamic(decl);\n      \n      return isDynamicResult;  \n    }\n\n#define OBJC_ACCESSOR(ID, KEYWORD)\n#define ACCESSOR(ID) \\\n    case AccessorKind::ID:\n#include \"swift\/AST\/AccessorKinds.def\"\n      return false;\n    }\n  }\n\n  \/\/ The 'NSManaged' attribute implies 'dynamic'.\n  \/\/ FIXME: Use a semantic check for NSManaged rather than looking for the\n  \/\/ attribute (which could be ill-formed).\n  if (decl->getAttrs().hasAttribute<NSManagedAttr>()) {\n    makeDynamic(decl);\n    return true;\n  }\n\n  \/\/ The presence of 'final' blocks the inference of 'dynamic'.\n  if (decl->isFinal())\n    return false;\n\n  \/\/ Types are never 'dynamic'.\n  if (isa<TypeDecl>(decl))\n    return false;\n\n  \/\/ A non-@objc entity is never 'dynamic'.\n  if (!decl->isObjC())\n    return false;\n\n  \/\/ @objc declarations in class extensions are implicitly dynamic.\n  \/\/ This is intended to enable overriding the declarations.\n  auto dc = decl->getDeclContext();\n  if (isa<ExtensionDecl>(dc) && dc->getSelfClassDecl()) {\n    makeDynamic(decl);\n    return true;\n  }\n\n  \/\/ If any of the declarations overridden by this declaration are dynamic\n  \/\/ or were imported from Objective-C, this declaration is dynamic.\n  \/\/ Don't do this if the declaration is not exposed to Objective-C; that's\n  \/\/ currently the (only) manner in which one can make an override of a\n  \/\/ dynamic declaration non-dynamic.\n  auto overriddenDecls = evaluateOrDefault(evaluator,\n    OverriddenDeclsRequest{decl}, {});\n  for (auto overridden : overriddenDecls) {\n    if (overridden->isDynamic() || overridden->hasClangNode()) {\n      makeDynamic(decl);\n      return true;\n    }\n  }\n\n  return false;\n}\n\nllvm::Expected<ArrayRef<Requirement>>\nRequirementSignatureRequest::evaluate(Evaluator &evaluator, ProtocolDecl *proto) const {\n  GenericSignatureBuilder builder(proto->getASTContext());\n\n  \/\/ Add all of the generic parameters.\n  proto->createGenericParamsIfMissing();\n  for (auto gp : *proto->getGenericParams())\n    builder.addGenericParameter(gp);\n\n  \/\/ Add the conformance of 'self' to the protocol.\n  auto selfType =\n    proto->getSelfInterfaceType()->castTo<GenericTypeParamType>();\n  auto requirement =\n    Requirement(RequirementKind::Conformance, selfType,\n              proto->getDeclaredInterfaceType());\n\n  builder.addRequirement(\n          requirement,\n          GenericSignatureBuilder::RequirementSource::forRequirementSignature(\n                                                      builder, selfType, proto),\n          nullptr);\n\n  auto reqSignature = std::move(builder).computeGenericSignature(\n                        SourceLoc(),\n                        \/*allowConcreteGenericPArams=*\/false,\n                        \/*allowBuilderToMove=*\/false);\n  return reqSignature->getRequirements();\n}\n\nllvm::Expected<Type>\nDefaultDefinitionTypeRequest::evaluate(Evaluator &evaluator,\n                                       AssociatedTypeDecl *assocType) const {\n  if (assocType->Resolver) {\n    auto defaultType = assocType->Resolver->loadAssociatedTypeDefault(\n                                    assocType, assocType->ResolverContextData);\n    assocType->Resolver = nullptr;\n    return defaultType;\n  }\n\n  TypeRepr *defaultDefinition = assocType->getDefaultDefinitionTypeRepr();\n  if (defaultDefinition) {\n    auto resolution = TypeResolution::forInterface(assocType->getDeclContext());\n    return resolution.resolveType(defaultDefinition, None);\n  }\n\n  return Type();\n}\n\nnamespace {\n  \/\/\/ How to generate the raw value for each element of an enum that doesn't\n  \/\/\/ have one explicitly specified.\n  enum class AutomaticEnumValueKind {\n    \/\/\/ Raw values cannot be automatically generated.\n    None,\n    \/\/\/ The raw value is the enum element's name.\n    String,\n    \/\/\/ The raw value is the previous element's raw value, incremented.\n    \/\/\/\n    \/\/\/ For the first element in the enum, the raw value is 0.\n    Integer,\n  };\n} \/\/ end anonymous namespace\n\n\/\/\/ Given the raw value literal expression for an enum case, produces the\n\/\/\/ auto-incremented raw value for the subsequent case, or returns null if\n\/\/\/ the value is not auto-incrementable.\nstatic LiteralExpr *getAutomaticRawValueExpr(TypeChecker &TC,\n                                             AutomaticEnumValueKind valueKind,\n                                             EnumElementDecl *forElt,\n                                             LiteralExpr *prevValue) {\n  switch (valueKind) {\n  case AutomaticEnumValueKind::None:\n    TC.diagnose(forElt->getLoc(),\n                diag::enum_non_integer_convertible_raw_type_no_value);\n    return nullptr;\n\n  case AutomaticEnumValueKind::String:\n    return new (TC.Context) StringLiteralExpr(forElt->getNameStr(), SourceLoc(),\n                                              \/*Implicit=*\/true);\n\n  case AutomaticEnumValueKind::Integer:\n    \/\/ If there was no previous value, start from zero.\n    if (!prevValue) {\n      return new (TC.Context) IntegerLiteralExpr(\"0\", SourceLoc(),\n                                                 \/*Implicit=*\/true);\n    }\n    \/\/ If the prevValue is not a well-typed integer, then break.\n    if (!prevValue->getType())\n      return nullptr;\n\n    if (auto intLit = dyn_cast<IntegerLiteralExpr>(prevValue)) {\n      APInt nextVal = intLit->getValue().sextOrSelf(128) + 1;\n      bool negative = nextVal.slt(0);\n      if (negative)\n        nextVal = -nextVal;\n\n      llvm::SmallString<10> nextValStr;\n      nextVal.toStringSigned(nextValStr);\n      auto expr = new (TC.Context)\n        IntegerLiteralExpr(TC.Context.AllocateCopy(StringRef(nextValStr)),\n                           forElt->getLoc(), \/*Implicit=*\/true);\n      if (negative)\n        expr->setNegative(forElt->getLoc());\n\n      return expr;\n    }\n\n    TC.diagnose(forElt->getLoc(),\n                diag::enum_non_integer_raw_value_auto_increment);\n    return nullptr;\n  }\n\n  llvm_unreachable(\"Unhandled AutomaticEnumValueKind in switch.\");\n}\n\nstatic void checkEnumRawValues(TypeChecker &TC, EnumDecl *ED) {\n  Type rawTy = ED->getRawType();\n\n  if (!rawTy) {\n    return;\n  }\n\n  if (ED->getGenericEnvironmentOfContext() != nullptr)\n    rawTy = ED->mapTypeIntoContext(rawTy);\n  if (rawTy->hasError())\n    return;\n\n  AutomaticEnumValueKind valueKind;\n  \/\/ Swift enums require that the raw type is convertible from one of the\n  \/\/ primitive literal protocols.\n  auto conformsToProtocol = [&](KnownProtocolKind protoKind) {\n      ProtocolDecl *proto = TC.getProtocol(ED->getLoc(), protoKind);\n      return TypeChecker::conformsToProtocol(rawTy, proto,\n                                             ED->getDeclContext(), None);\n  };\n\n  static auto otherLiteralProtocolKinds = {\n    KnownProtocolKind::ExpressibleByFloatLiteral,\n    KnownProtocolKind::ExpressibleByUnicodeScalarLiteral,\n    KnownProtocolKind::ExpressibleByExtendedGraphemeClusterLiteral,\n  };\n\n  if (conformsToProtocol(KnownProtocolKind::ExpressibleByIntegerLiteral)) {\n    valueKind = AutomaticEnumValueKind::Integer;\n  } else if (conformsToProtocol(KnownProtocolKind::ExpressibleByStringLiteral)){\n    valueKind = AutomaticEnumValueKind::String;\n  } else if (std::any_of(otherLiteralProtocolKinds.begin(),\n                         otherLiteralProtocolKinds.end(),\n                         conformsToProtocol)) {\n    valueKind = AutomaticEnumValueKind::None;\n  } else {\n    TC.diagnose(ED->getInherited().front().getSourceRange().Start,\n                diag::raw_type_not_literal_convertible,\n                rawTy);\n    ED->getInherited().front().setInvalidType(TC.Context);\n    return;\n  }\n\n  \/\/ We need at least one case to have a raw value.\n  if (ED->getAllElements().empty()) {\n    TC.diagnose(ED->getInherited().front().getSourceRange().Start,\n                diag::empty_enum_raw_type);\n    return;\n  }\n\n  \/\/ Check the raw values of the cases.\n  LiteralExpr *prevValue = nullptr;\n  EnumElementDecl *lastExplicitValueElt = nullptr;\n\n  \/\/ Keep a map we can use to check for duplicate case values.\n  llvm::SmallDenseMap<RawValueKey, RawValueSource, 8> uniqueRawValues;\n\n  for (auto elt : ED->getAllElements()) {\n    \/\/ Skip if the raw value expr has already been checked.\n    if (elt->getTypeCheckedRawValueExpr())\n      continue;\n\n    \/\/ Make sure the element is checked out before we poke at it.\n    TC.validateDecl(elt);\n    \n    if (elt->isInvalid())\n      continue;\n\n    \/\/ We don't yet support raw values on payload cases.\n    if (elt->hasAssociatedValues()) {\n      TC.diagnose(elt->getLoc(),\n                  diag::enum_with_raw_type_case_with_argument);\n      TC.diagnose(ED->getInherited().front().getSourceRange().Start,\n                  diag::enum_raw_type_here, rawTy);\n      elt->setInvalid();\n      continue;\n    }\n    \n    \/\/ Check the raw value expr, if we have one.\n    if (auto *rawValue = elt->getRawValueExpr()) {\n      Expr *typeCheckedExpr = rawValue;\n      auto resultTy = TC.typeCheckExpression(typeCheckedExpr, ED,\n                                             TypeLoc::withoutLoc(rawTy),\n                                             CTP_EnumCaseRawValue);\n      if (resultTy) {\n        elt->setTypeCheckedRawValueExpr(typeCheckedExpr);\n      }\n      lastExplicitValueElt = elt;\n    } else {\n      \/\/ If the enum element has no explicit raw value, try to\n      \/\/ autoincrement from the previous value, or start from zero if this\n      \/\/ is the first element.\n      auto nextValue = getAutomaticRawValueExpr(TC, valueKind, elt, prevValue);\n      if (!nextValue) {\n        elt->setInvalid();\n        break;\n      }\n      elt->setRawValueExpr(nextValue);\n      Expr *typeChecked = nextValue;\n      auto resultTy = TC.typeCheckExpression(\n          typeChecked, ED, TypeLoc::withoutLoc(rawTy), CTP_EnumCaseRawValue);\n      if (resultTy)\n        elt->setTypeCheckedRawValueExpr(typeChecked);\n    }\n    prevValue = elt->getRawValueExpr();\n    assert(prevValue && \"continued without setting raw value of enum case\");\n\n    \/\/ If we didn't find a valid initializer (maybe the initial value was\n    \/\/ incompatible with the raw value type) mark the entry as being erroneous.\n    if (!elt->getTypeCheckedRawValueExpr()) {\n      elt->setInvalid();\n      continue;\n    }\n\n    TC.checkEnumElementErrorHandling(elt);\n\n    \/\/ Find the type checked version of the LiteralExpr used for the raw value.\n    \/\/ this is unfortunate, but is needed because we're digging into the\n    \/\/ literals to get information about them, instead of accepting general\n    \/\/ expressions.\n    LiteralExpr *rawValue = elt->getRawValueExpr();\n    if (!rawValue->getType()) {\n      elt->getTypeCheckedRawValueExpr()->forEachChildExpr([&](Expr *E)->Expr* {\n        if (E->getKind() == rawValue->getKind())\n          rawValue = cast<LiteralExpr>(E);\n        return E;\n      });\n      elt->setRawValueExpr(rawValue);\n    }\n\n    prevValue = rawValue;\n    assert(prevValue && \"continued without setting raw value of enum case\");\n\n    \/\/ Check that the raw value is unique.\n    RawValueKey key(rawValue);\n    RawValueSource source{elt, lastExplicitValueElt};\n\n    auto insertIterPair = uniqueRawValues.insert({key, source});\n    if (insertIterPair.second)\n      continue;\n\n    \/\/ Diagnose the duplicate value.\n    SourceLoc diagLoc = elt->getRawValueExpr()->isImplicit()\n        ? elt->getLoc() : elt->getRawValueExpr()->getLoc();\n    TC.diagnose(diagLoc, diag::enum_raw_value_not_unique);\n    assert(lastExplicitValueElt &&\n           \"should not be able to have non-unique raw values when \"\n           \"relying on autoincrement\");\n    if (lastExplicitValueElt != elt &&\n        valueKind == AutomaticEnumValueKind::Integer) {\n      TC.diagnose(lastExplicitValueElt->getRawValueExpr()->getLoc(),\n                  diag::enum_raw_value_incrementing_from_here);\n    }\n\n    RawValueSource prevSource = insertIterPair.first->second;\n    auto foundElt = prevSource.sourceElt;\n    diagLoc = foundElt->getRawValueExpr()->isImplicit()\n        ? foundElt->getLoc() : foundElt->getRawValueExpr()->getLoc();\n    TC.diagnose(diagLoc, diag::enum_raw_value_used_here);\n    if (foundElt != prevSource.lastExplicitValueElt &&\n        valueKind == AutomaticEnumValueKind::Integer) {\n      if (prevSource.lastExplicitValueElt)\n        TC.diagnose(prevSource.lastExplicitValueElt\n                      ->getRawValueExpr()->getLoc(),\n                    diag::enum_raw_value_incrementing_from_here);\n      else\n        TC.diagnose(ED->getAllElements().front()->getLoc(),\n                    diag::enum_raw_value_incrementing_from_zero);\n    }\n  }\n}\n\n\/\/\/ Walks up the override chain for \\p CD until it finds an initializer that is\n\/\/\/ required and non-implicit. If no such initializer exists, returns the\n\/\/\/ declaration where \\c required was introduced (i.e. closest to the root\n\/\/\/ class).\nstatic const ConstructorDecl *\nfindNonImplicitRequiredInit(const ConstructorDecl *CD) {\n  while (CD->isImplicit()) {\n    auto *overridden = CD->getOverriddenDecl();\n    if (!overridden || !overridden->isRequired())\n      break;\n    CD = overridden;\n  }\n  return CD;\n}\n\n\n\/\/\/ For building the higher-than component of the diagnostic path,\n\/\/\/ we use the visited set, which we've embellished with information\n\/\/\/ about how we reached a particular node.  This is reasonable because\n\/\/\/ we need to maintain the set anyway.\nstatic void buildHigherThanPath(PrecedenceGroupDecl *last,\n                          const llvm::DenseMap<PrecedenceGroupDecl *,\n                                        PrecedenceGroupDecl *> &visitedFrom,\n                          raw_ostream &out) {\n  auto it = visitedFrom.find(last);\n  assert(it != visitedFrom.end());\n  auto from = it->second;\n  if (from) {\n    buildHigherThanPath(from, visitedFrom, out);\n  }\n  out << last->getName() << \" -> \";\n}\n\n\/\/\/ For building the lower-than component of the diagnostic path,\n\/\/\/ we just do a depth-first search to find a path.\nstatic bool buildLowerThanPath(PrecedenceGroupDecl *start,\n                               PrecedenceGroupDecl *target,\n                               raw_ostream &out) {\n  if (start == target) {\n    out << start->getName();\n    return true;\n  }\n\n  if (start->isInvalid())\n    return false;\n\n  for (auto &rel : start->getLowerThan()) {\n    if (rel.Group && buildLowerThanPath(rel.Group, target, out)) {\n      out << \" -> \" << start->getName();\n      return true;\n    }\n  }\n\n  return false;\n}\n\nstatic void checkPrecedenceCircularity(TypeChecker &TC,\n                                       PrecedenceGroupDecl *PGD) {\n  \/\/ Don't diagnose if this group is already marked invalid.\n  if (PGD->isInvalid()) return;\n\n  \/\/ The cycle doesn't necessarily go through this specific group,\n  \/\/ so we need a proper visited set to avoid infinite loops.  We\n  \/\/ also record a back-reference so that we can easily reconstruct\n  \/\/ the cycle.\n  llvm::DenseMap<PrecedenceGroupDecl*, PrecedenceGroupDecl*> visitedFrom;\n  SmallVector<PrecedenceGroupDecl*, 4> stack;\n\n  \/\/ Fill out the targets set.\n  llvm::SmallPtrSet<PrecedenceGroupDecl*, 4> targets;\n  stack.push_back(PGD);\n  do {\n    auto cur = stack.pop_back_val();\n\n    \/\/ If we reach an invalid node, just bail out.\n    if (cur->isInvalid()) {\n      PGD->setInvalid();\n      return;\n    }\n\n    targets.insert(cur);\n\n    for (auto &rel : cur->getLowerThan()) {\n      if (!rel.Group) continue;\n\n      \/\/ We can't have cycles in the lower-than relationship\n      \/\/ because it has to point outside of the module.\n\n      stack.push_back(rel.Group);\n    }\n  } while (!stack.empty());\n\n  \/\/ Make sure that the PGD is its own source.\n  visitedFrom.insert({PGD, nullptr});\n\n  stack.push_back(PGD);\n  do {\n    auto cur = stack.pop_back_val();\n\n    \/\/ If we reach an invalid node, just bail out.\n    if (cur->isInvalid()) {\n      PGD->setInvalid();\n      return;\n    }\n\n    for (auto &rel : cur->getHigherThan()) {\n      if (!rel.Group) continue;\n\n      \/\/ Check whether we've reached a target declaration.\n      if (!targets.count(rel.Group)) {\n        \/\/ If not, check whether we've visited this group before.\n        if (visitedFrom.insert({rel.Group, cur}).second) {\n          \/\/ If not, add it to the queue.\n          stack.push_back(rel.Group);\n        }\n\n        \/\/ Note that we'll silently ignore cycles that don't go through PGD.\n        \/\/ We should eventually process the groups that are involved.\n        continue;\n      }\n\n      \/\/ Otherwise, we have something to report.\n      SmallString<128> path;\n      {\n        llvm::raw_svector_ostream str(path);\n\n        \/\/ Build the higherThan portion of the path (PGD -> cur).\n        buildHigherThanPath(cur, visitedFrom, str);\n\n        \/\/ Build the lowerThan portion of the path (rel.Group -> PGD).\n        buildLowerThanPath(PGD, rel.Group, str);\n      }\n      \n      TC.diagnose(PGD->getHigherThanLoc(), diag::precedence_group_cycle, path);\n      PGD->setInvalid();\n      return;\n    }\n  } while (!stack.empty());\n}\n\n\/\/\/ Do a primitive lookup for the given precedence group.  This does\n\/\/\/ not validate the precedence group or diagnose if the lookup fails\n\/\/\/ (other than via ambiguity); for that, use\n\/\/\/ TypeChecker::lookupPrecedenceGroup.\n\/\/\/\n\/\/\/ Pass an invalid source location to suppress diagnostics.\nstatic PrecedenceGroupDecl *\nlookupPrecedenceGroupPrimitive(DeclContext *dc, Identifier name,\n                               SourceLoc nameLoc) {\n  if (auto sf = dc->getParentSourceFile()) {\n    bool cascading = dc->isCascadingContextForLookup(false);\n    return sf->lookupPrecedenceGroup(name, cascading, nameLoc);\n  } else {\n    return dc->getParentModule()->lookupPrecedenceGroup(name, nameLoc);\n  }\n}\n\nvoid TypeChecker::validateDecl(PrecedenceGroupDecl *PGD) {\n  checkDeclAttributesEarly(PGD);\n  checkDeclAttributes(PGD);\n\n  if (PGD->isInvalid() || PGD->hasValidationStarted())\n    return;\n  DeclValidationRAII IBV(PGD);\n\n  bool isInvalid = false;\n\n  \/\/ Validate the higherThan relationships.\n  bool addedHigherThan = false;\n  for (auto &rel : PGD->getMutableHigherThan()) {\n    if (rel.Group) continue;\n\n    auto group = lookupPrecedenceGroupPrimitive(PGD->getDeclContext(),\n                                                rel.Name, rel.NameLoc);\n    if (group) {\n      rel.Group = group;\n      validateDecl(group);\n      addedHigherThan = true;\n    } else if (!PGD->isInvalid()) {\n      diagnose(rel.NameLoc, diag::unknown_precedence_group, rel.Name);\n      isInvalid = true;\n    }\n  }\n\n  \/\/ Validate the lowerThan relationships.\n  for (auto &rel : PGD->getMutableLowerThan()) {\n    if (rel.Group) continue;\n\n    auto dc = PGD->getDeclContext();\n    auto group = lookupPrecedenceGroupPrimitive(dc, rel.Name, rel.NameLoc);\n    if (group) {\n      if (group->getDeclContext()->getParentModule()\n            == dc->getParentModule()) {\n        if (!PGD->isInvalid()) {\n          diagnose(rel.NameLoc, diag::precedence_group_lower_within_module);\n          diagnose(group->getNameLoc(), diag::kind_declared_here,\n                   DescriptiveDeclKind::PrecedenceGroup);\n          isInvalid = true;\n        }\n      } else {\n        rel.Group = group;\n        validateDecl(group);\n      }\n    } else if (!PGD->isInvalid()) {\n      diagnose(rel.NameLoc, diag::unknown_precedence_group, rel.Name);\n      isInvalid = true;\n    }\n  }\n\n  \/\/ Check for circularity.\n  if (addedHigherThan) {\n    checkPrecedenceCircularity(*this, PGD);\n  }\n\n  if (isInvalid) PGD->setInvalid();\n}\n\nPrecedenceGroupDecl *TypeChecker::lookupPrecedenceGroup(DeclContext *dc,\n                                                        Identifier name,\n                                                        SourceLoc nameLoc) {\n  auto group = lookupPrecedenceGroupPrimitive(dc, name, nameLoc);\n  if (group) {\n    validateDecl(group);\n  } else if (nameLoc.isValid()) {\n    \/\/ FIXME: avoid diagnosing this multiple times per source file.\n    diagnose(nameLoc, diag::unknown_precedence_group, name);\n  }\n  return group;\n}\n\nstatic NominalTypeDecl *resolveSingleNominalTypeDecl(\n    DeclContext *DC, SourceLoc loc, Identifier ident, TypeChecker &tc,\n    TypeResolutionFlags flags = TypeResolutionFlags(0)) {\n  auto *TyR = new (tc.Context) SimpleIdentTypeRepr(loc, ident);\n  TypeLoc typeLoc = TypeLoc(TyR);\n\n  TypeResolutionOptions options = TypeResolverContext::TypeAliasDecl;\n  options |= flags;\n  if (tc.validateType(typeLoc, TypeResolution::forInterface(DC), options))\n    return nullptr;\n\n  return typeLoc.getType()->getAnyNominal();\n}\n\nstatic bool checkDesignatedTypes(OperatorDecl *OD,\n                                 ArrayRef<Identifier> identifiers,\n                                 ArrayRef<SourceLoc> identifierLocs,\n                                 TypeChecker &TC) {\n  assert(identifiers.size() == identifierLocs.size());\n\n  SmallVector<NominalTypeDecl *, 1> designatedNominalTypes;\n  auto *DC = OD->getDeclContext();\n\n  for (auto index : indices(identifiers)) {\n    auto *decl = resolveSingleNominalTypeDecl(DC, identifierLocs[index],\n                                              identifiers[index], TC);\n\n    if (!decl)\n      return true;\n\n    designatedNominalTypes.push_back(decl);\n  }\n\n  auto &ctx = TC.Context;\n  OD->setDesignatedNominalTypes(ctx.AllocateCopy(designatedNominalTypes));\n  return false;\n}\n\n\/\/\/ Validate the given operator declaration.\n\/\/\/\n\/\/\/ This establishes key invariants, such as an InfixOperatorDecl's\n\/\/\/ reference to its precedence group and the transitive validity of that\n\/\/\/ group.\nvoid TypeChecker::validateDecl(OperatorDecl *OD) {\n  checkDeclAttributesEarly(OD);\n  checkDeclAttributes(OD);\n\n  auto IOD = dyn_cast<InfixOperatorDecl>(OD);\n\n  auto enableOperatorDesignatedTypes =\n      getLangOpts().EnableOperatorDesignatedTypes;\n\n  \/\/ Pre- or post-fix operator?\n  if (!IOD) {\n    auto nominalTypes = OD->getDesignatedNominalTypes();\n    if (nominalTypes.empty() && enableOperatorDesignatedTypes) {\n      auto identifiers = OD->getIdentifiers();\n      auto identifierLocs = OD->getIdentifierLocs();\n      if (checkDesignatedTypes(OD, identifiers, identifierLocs, *this))\n        OD->setInvalid();\n    }\n    return;\n  }\n\n  if (!IOD->getPrecedenceGroup()) {\n    PrecedenceGroupDecl *group = nullptr;\n\n    auto identifiers = IOD->getIdentifiers();\n    auto identifierLocs = IOD->getIdentifierLocs();\n\n    if (!identifiers.empty()) {\n      group = lookupPrecedenceGroupPrimitive(IOD->getDeclContext(),\n                                             identifiers[0], identifierLocs[0]);\n      if (group) {\n        identifiers = identifiers.slice(1);\n        identifierLocs = identifierLocs.slice(1);\n      } else {\n        \/\/ If we're either not allowing types, or we are allowing them\n        \/\/ and this identifier is not a type, emit an error as if it's\n        \/\/ a precedence group.\n        auto *DC = OD->getDeclContext();\n        if (!(enableOperatorDesignatedTypes &&\n              resolveSingleNominalTypeDecl(\n                  DC, identifierLocs[0], identifiers[0], *this,\n                  TypeResolutionFlags::SilenceErrors))) {\n          diagnose(identifierLocs[0], diag::unknown_precedence_group,\n                   identifiers[0]);\n          identifiers = identifiers.slice(1);\n          identifierLocs = identifierLocs.slice(1);\n        }\n      }\n    }\n\n    if (!identifiers.empty() && !enableOperatorDesignatedTypes) {\n      assert(!group);\n      diagnose(identifierLocs[0], diag::unknown_precedence_group,\n               identifiers[0]);\n      identifiers = identifiers.slice(1);\n      identifierLocs = identifierLocs.slice(1);\n      assert(identifiers.empty() && identifierLocs.empty());\n    }\n\n    if (!group) {\n      group = lookupPrecedenceGroupPrimitive(\n          IOD->getDeclContext(), Context.Id_DefaultPrecedence, SourceLoc());\n    }\n\n    if (group) {\n      validateDecl(group);\n      IOD->setPrecedenceGroup(group);\n    } else {\n      diagnose(IOD->getLoc(), diag::missing_builtin_precedence_group,\n               Context.Id_DefaultPrecedence);\n    }\n\n    auto nominalTypes = IOD->getDesignatedNominalTypes();\n    if (nominalTypes.empty() && enableOperatorDesignatedTypes) {\n      if (checkDesignatedTypes(IOD, identifiers, identifierLocs, *this)) {\n        IOD->setInvalid();\n        return;\n      }\n    }\n  }\n}\n\nstatic bool doesContextHaveValueSemantics(DeclContext *dc) {\n  if (Type contextTy = dc->getDeclaredInterfaceType())\n    return !contextTy->hasReferenceSemantics();\n  return false;\n}\n\nstatic void validateSelfAccessKind(TypeChecker &TC, FuncDecl *FD) {\n  \/\/ Validate the mutating attribute if present, and install it into the bit\n  \/\/ on funcdecl (instead of just being a DeclAttribute).\n  if (FD->getAttrs().hasAttribute<MutatingAttr>())\n    FD->setSelfAccessKind(SelfAccessKind::Mutating);\n  else if (FD->getAttrs().hasAttribute<NonMutatingAttr>())\n    FD->setSelfAccessKind(SelfAccessKind::NonMutating);\n  else if (FD->getAttrs().hasAttribute<ConsumingAttr>())\n    FD->setSelfAccessKind(SelfAccessKind::__Consuming);\n\n  if (FD->isMutating()) {\n    if (!FD->isInstanceMember() ||\n        !doesContextHaveValueSemantics(FD->getDeclContext()))\n      FD->setSelfAccessKind(SelfAccessKind::NonMutating);\n  }\n}\n\nstatic bool validateAccessorIsMutating(TypeChecker &TC, FuncDecl *accessor) {\n  assert(accessor && \"accessor not present!\");\n  validateSelfAccessKind(TC, accessor);\n  return accessor->isMutating();\n}\n\nstatic bool computeIsGetterMutating(TypeChecker &TC,\n                                    AbstractStorageDecl *storage) {\n  \/\/ 'lazy' overrides the normal accessor-based rules and heavily\n  \/\/ restricts what accessors can be used.  The getter is considered\n  \/\/ mutating if this is instance storage on a value type.\n  if (storage->getAttrs().hasAttribute<LazyAttr>()) {\n    return storage->getDeclContext()->isTypeContext() &&\n           !storage->getDeclContext()->getSelfClassDecl() &&\n           !storage->isStatic();\n  }\n\n  \/\/ If we have an attached property wrapper, the getter is mutating if\n  \/\/ the \"value\" property of the wrapper type is mutating and we're in\n  \/\/ a context that has value semantics.\n  if (auto var = dyn_cast<VarDecl>(storage)) {\n    if (auto wrapperInfo = var->getAttachedPropertyWrapperTypeInfo()) {\n      if (wrapperInfo.valueVar &&\n          (!storage->getGetter() || storage->getGetter()->isImplicit())) {\n        TC.validateDecl(wrapperInfo.valueVar);\n        return wrapperInfo.valueVar->isGetterMutating() &&\n            var->isInstanceMember() &&\n            doesContextHaveValueSemantics(var->getDeclContext());\n      }\n    }\n  }\n\n  switch (storage->getReadImpl()) {\n  case ReadImplKind::Stored:\n    return false;\n\n  case ReadImplKind::Get:\n  case ReadImplKind::Inherited:\n    return validateAccessorIsMutating(TC, storage->getGetter());\n\n  case ReadImplKind::Address:\n    return validateAccessorIsMutating(TC, storage->getAddressor());\n\n  case ReadImplKind::Read:\n    return validateAccessorIsMutating(TC, storage->getReadCoroutine());\n  }\n\n  llvm_unreachable(\"bad impl kind\");\n}\n\nstatic bool computeIsSetterMutating(TypeChecker &TC,\n                                    AbstractStorageDecl *storage) {\n  \/\/ If we have an attached property wrapper, the setter is mutating if\n  \/\/ the \"value\" property of the wrapper type is mutating and we're in\n  \/\/ a context that has value semantics.\n  if (auto var = dyn_cast<VarDecl>(storage)) {\n    if (auto wrapperInfo = var->getAttachedPropertyWrapperTypeInfo()) {\n      if (wrapperInfo.valueVar &&\n          (!storage->getSetter() || storage->getSetter()->isImplicit())) {\n        TC.validateDecl(wrapperInfo.valueVar);\n        return wrapperInfo.valueVar->isSetterMutating() &&\n            var->isInstanceMember() &&\n            doesContextHaveValueSemantics(var->getDeclContext());\n      }\n    }\n  }\n\n  auto impl = storage->getImplInfo();\n  switch (impl.getWriteImpl()) {\n  case WriteImplKind::Immutable:\n  case WriteImplKind::Stored:\n    \/\/ Instance member setters are mutating; static property setters and\n    \/\/ top-level setters are not.\n    \/\/ It's important that we use this logic for \"immutable\" storage\n    \/\/ in order to handle initialization of let-properties.\n    return storage->isInstanceMember() &&\n           doesContextHaveValueSemantics(storage->getDeclContext());\n\n  case WriteImplKind::StoredWithObservers:\n  case WriteImplKind::InheritedWithObservers:\n  case WriteImplKind::Set: {\n    auto result = validateAccessorIsMutating(TC, storage->getSetter());\n\n    \/\/ As a special extra check, if the user also gave us a modify\n    \/\/ coroutine, check that it has the same mutatingness as the setter.\n    \/\/ TODO: arguably this should require the spelling to match even when\n    \/\/ it's the implied value.\n    if (impl.getReadWriteImpl() == ReadWriteImplKind::Modify) {\n      auto modifyAccessor = storage->getModifyCoroutine();\n      auto modifyResult = validateAccessorIsMutating(TC, modifyAccessor);\n      if ((result || storage->isGetterMutating()) != modifyResult) {\n        TC.diagnose(modifyAccessor,\n                    diag::modify_mutatingness_differs_from_setter,\n                    modifyResult ? SelfAccessKind::Mutating\n                                 : SelfAccessKind::NonMutating,\n                    modifyResult ? SelfAccessKind::NonMutating\n                                 : SelfAccessKind::Mutating);\n        TC.diagnose(storage->getSetter(), diag::previous_accessor, \"setter\", 0);\n        modifyAccessor->setInvalid();\n      }\n    }\n\n    return result;\n  }\n\n  case WriteImplKind::MutableAddress:\n    return validateAccessorIsMutating(TC, storage->getMutableAddressor());\n\n  case WriteImplKind::Modify:\n    return validateAccessorIsMutating(TC, storage->getModifyCoroutine());\n  }\n  llvm_unreachable(\"bad storage kind\");\n}\n\nstatic bool shouldUseOpaqueReadAccessor(TypeChecker &TC,\n                                        AbstractStorageDecl *storage) {\n  return storage->getAttrs().hasAttribute<BorrowedAttr>();\n}\n\nstatic void validateAbstractStorageDecl(TypeChecker &TC,\n                                        AbstractStorageDecl *storage) {\n  if (storage->getOpaqueResultTypeDecl()) {\n    if (auto sf = storage->getInnermostDeclContext()->getParentSourceFile()) {\n      sf->markDeclWithOpaqueResultTypeAsValidated(storage);\n    }\n  }\n  \n  if (shouldUseOpaqueReadAccessor(TC, storage))\n    storage->setOpaqueReadOwnership(OpaqueReadOwnership::Borrowed);\n\n  \/\/ isGetterMutating and isSetterMutating are part of the signature\n  \/\/ of a storage declaration and need to be validated immediately.\n  storage->setIsGetterMutating(computeIsGetterMutating(TC, storage));\n  storage->setIsSetterMutating(computeIsSetterMutating(TC, storage));\n\n  \/\/ Everything else about the accessors can wait until finalization.\n  \/\/ This will validate all the accessors.\n  TC.DeclsToFinalize.insert(storage);\n}\n\nstatic void finalizeAbstractStorageDecl(TypeChecker &TC,\n                                        AbstractStorageDecl *storage) {\n  TC.validateDecl(storage);\n\n  \/\/ Add any mandatory accessors now.\n  maybeAddAccessorsToStorage(storage);\n\n  for (auto accessor : storage->getAllAccessors()) {\n    \/\/ Are there accessors we can safely ignore here, like maybe observers?\n    TC.validateDecl(accessor);\n\n    \/\/ Finalize the accessors as well.\n    TC.DeclsToFinalize.insert(accessor);\n  }\n}\n\n\/\/\/ Check the requirements in the where clause of the given \\c source\n\/\/\/ to ensure that they don't introduce additional 'Self' requirements.\nstatic void checkProtocolSelfRequirements(ProtocolDecl *proto,\n                                          TypeDecl *source) {\n  RequirementRequest::visitRequirements(source, TypeResolutionStage::Interface,\n      [&](const Requirement &req, RequirementRepr *reqRepr) {\n        switch (req.getKind()) {\n        case RequirementKind::Conformance:\n        case RequirementKind::Layout:\n        case RequirementKind::Superclass:\n          if (reqRepr &&\n              req.getFirstType()->isEqual(proto->getSelfInterfaceType())) {\n            auto &diags = proto->getASTContext().Diags;\n            diags.diagnose(reqRepr->getSubjectLoc().getLoc(),\n                           diag::protocol_where_clause_self_requirement);\n          }\n\n          return false;\n\n        case RequirementKind::SameType:\n          return false;\n        }\n        llvm_unreachable(\"unhandled kind\");\n      });\n}\n\nnamespace {\nclass DeclChecker : public DeclVisitor<DeclChecker> {\npublic:\n  TypeChecker &TC;\n\n  explicit DeclChecker(TypeChecker &TC) : TC(TC) {}\n\n  void visit(Decl *decl) {\n    if (TC.Context.Stats)\n      TC.Context.Stats->getFrontendCounters().NumDeclsTypechecked++;\n\n    FrontendStatsTracer StatsTracer(TC.Context.Stats, \"typecheck-decl\", decl);\n    PrettyStackTraceDecl StackTrace(\"type-checking\", decl);\n    \n    DeclVisitor<DeclChecker>::visit(decl);\n\n    TC.checkUnsupportedProtocolType(decl);\n\n    if (auto VD = dyn_cast<ValueDecl>(decl)) {\n      checkRedeclaration(TC, VD);\n\n      \/\/ Make sure we finalize this declaration.\n      TC.DeclsToFinalize.insert(VD);\n\n      \/\/ If this is a member of a nominal type, don't allow it to have a name of\n      \/\/ \"Type\" or \"Protocol\" since we reserve the X.Type and X.Protocol\n      \/\/ expressions to mean something builtin to the language.  We *do* allow\n      \/\/ these if they are escaped with backticks though.\n      auto &Context = TC.Context;\n      if (VD->getDeclContext()->isTypeContext() &&\n          (VD->getFullName().isSimpleName(Context.Id_Type) ||\n           VD->getFullName().isSimpleName(Context.Id_Protocol)) &&\n          VD->getNameLoc().isValid() &&\n          Context.SourceMgr.extractText({VD->getNameLoc(), 1}) != \"`\") {\n        TC.diagnose(VD->getNameLoc(), diag::reserved_member_name,\n                    VD->getFullName(), VD->getBaseName().getIdentifier().str());\n        TC.diagnose(VD->getNameLoc(), diag::backticks_to_escape)\n            .fixItReplace(VD->getNameLoc(),\n                          \"`\" + VD->getBaseName().userFacingName().str() + \"`\");\n      }\n    }\n  }\n\n  \/\/===--------------------------------------------------------------------===\/\/\n  \/\/ Visit Methods.\n  \/\/===--------------------------------------------------------------------===\/\/\n\n  void visitGenericTypeParamDecl(GenericTypeParamDecl *D) {\n    llvm_unreachable(\"cannot reach here\");\n  }\n  \n  void visitImportDecl(ImportDecl *ID) {\n    TC.checkDeclAttributesEarly(ID);\n    TC.checkDeclAttributes(ID);\n  }\n\n  void visitOperatorDecl(OperatorDecl *OD) {\n    TC.validateDecl(OD);\n    checkAccessControl(TC, OD);\n  }\n\n  void visitPrecedenceGroupDecl(PrecedenceGroupDecl *PGD) {\n    TC.validateDecl(PGD);\n    checkAccessControl(TC, PGD);\n  }\n\n  void visitMissingMemberDecl(MissingMemberDecl *MMD) {\n    llvm_unreachable(\"should always be type-checked already\");\n  }\n\n  void visitBoundVariable(VarDecl *VD) {\n    \/\/ WARNING: Anything you put in this function will only be run when the\n    \/\/ VarDecl is fully type-checked within its own file. It will NOT be run\n    \/\/ when the VarDecl is merely used from another file.\n    TC.validateDecl(VD);\n\n    \/\/ Set up accessors, also lowering lazy and @NSManaged properties.\n    maybeAddAccessorsToStorage(VD);\n\n    \/\/ Add the '@_hasStorage' attribute if this property is stored.\n    if (VD->hasStorage() && !VD->getAttrs().hasAttribute<HasStorageAttr>())\n      VD->getAttrs().add(new (TC.Context) HasStorageAttr(\/*isImplicit=*\/true));\n\n    \/\/ Reject cases where this is a variable that has storage but it isn't\n    \/\/ allowed.\n    if (VD->hasStorage()) {\n      \/\/ Stored properties in protocols are diagnosed in\n      \/\/ maybeAddAccessorsToStorage(), to ensure they run when a\n      \/\/ protocol requirement is validated but not type checked.\n\n      \/\/ Enums and extensions cannot have stored instance properties.\n      \/\/ Static stored properties are allowed, with restrictions\n      \/\/ enforced below.\n      if (isa<EnumDecl>(VD->getDeclContext()) &&\n          !VD->isStatic() && !VD->isInvalid()) {\n        \/\/ Enums can only have computed properties.\n        TC.diagnose(VD->getLoc(), diag::enum_stored_property);\n        VD->markInvalid();\n      } else if (isa<ExtensionDecl>(VD->getDeclContext()) &&\n                 !VD->isStatic() && !VD->isInvalid() &&\n                 !VD->getAttrs().getAttribute<DynamicReplacementAttr>()) {\n        TC.diagnose(VD->getLoc(), diag::extension_stored_property);\n        VD->markInvalid();\n      }\n      \n      \/\/ We haven't implemented type-level storage in some contexts.\n      if (VD->isStatic()) {\n        auto PBD = VD->getParentPatternBinding();\n        \/\/ Selector for unimplemented_static_var message.\n        enum : unsigned {\n          Misc,\n          GenericTypes,\n          Classes,\n          ProtocolExtensions\n        };\n        auto unimplementedStatic = [&](unsigned diagSel) {\n          auto staticLoc = PBD->getStaticLoc();\n          TC.diagnose(VD->getLoc(), diag::unimplemented_static_var,\n                      diagSel, PBD->getStaticSpelling(),\n                      diagSel == Classes)\n            .highlight(staticLoc);\n        };\n\n        auto DC = VD->getDeclContext();\n\n        \/\/ Non-stored properties are fine.\n        if (!PBD->hasStorage()) {\n          \/\/ do nothing\n\n        \/\/ Stored type variables in a generic context need to logically\n        \/\/ occur once per instantiation, which we don't yet handle.\n        } else if (DC->getExtendedProtocolDecl()) {\n          unimplementedStatic(ProtocolExtensions);\n        } else if (DC->isGenericContext()\n               && !DC->getGenericSignatureOfContext()->areAllParamsConcrete()) {\n          unimplementedStatic(GenericTypes);\n        } else if (DC->getSelfClassDecl()) {\n          auto StaticSpelling = PBD->getStaticSpelling();\n          if (StaticSpelling != StaticSpellingKind::KeywordStatic)\n            unimplementedStatic(Classes);\n        }\n      }\n    }\n\n    if (!checkOverrides(VD)) {\n      \/\/ If a property has an override attribute but does not override\n      \/\/ anything, complain.\n      auto overridden = VD->getOverriddenDecl();\n      if (auto *OA = VD->getAttrs().getAttribute<OverrideAttr>()) {\n        if (!overridden) {\n          TC.diagnose(VD, diag::property_does_not_override)\n            .highlight(OA->getLocation());\n          OA->setInvalid();\n        }\n      }\n    }\n\n    TC.checkDeclAttributes(VD);\n\n    triggerAccessorSynthesis(TC, VD);\n\n    \/\/ Under the Swift 3 inference rules, if we have @IBInspectable or\n    \/\/ @GKInspectable but did not infer @objc, warn that the attribute is\n    if (!VD->isObjC() && TC.Context.LangOpts.EnableSwift3ObjCInference) {\n      if (auto attr = VD->getAttrs().getAttribute<IBInspectableAttr>()) {\n        TC.diagnose(attr->getLocation(),\n                    diag::attribute_meaningless_when_nonobjc,\n                    attr->getAttrName())\n          .fixItRemove(attr->getRange());\n      }\n\n      if (auto attr = VD->getAttrs().getAttribute<GKInspectableAttr>()) {\n        TC.diagnose(attr->getLocation(),\n                    diag::attribute_meaningless_when_nonobjc,\n                    attr->getAttrName())\n          .fixItRemove(attr->getRange());\n      }\n    }\n\n    if (VD->getAttrs().hasAttribute<DynamicReplacementAttr>())\n      TC.checkDynamicReplacementAttribute(VD);\n  }\n\n  void visitBoundVars(Pattern *P) {\n    P->forEachVariable([&] (VarDecl *VD) { this->visitBoundVariable(VD); });\n  }\n\n  void visitPatternBindingDecl(PatternBindingDecl *PBD) {\n    DeclContext *DC = PBD->getDeclContext();\n\n    \/\/ Check all the pattern\/init pairs in the PBD.\n    validatePatternBindingEntries(TC, PBD);\n\n    TC.checkDeclAttributesEarly(PBD);\n\n    for (unsigned i = 0, e = PBD->getNumPatternEntries(); i != e; ++i) {\n      \/\/ Type check each VarDecl that this PatternBinding handles.\n      visitBoundVars(PBD->getPattern(i));\n\n      \/\/ If we have a type but no initializer, check whether the type is\n      \/\/ default-initializable. If so, do it.\n      if (PBD->getPattern(i)->hasType() &&\n          !PBD->isInitialized(i) &&\n          PBD->getPattern(i)->hasStorage() &&\n          !PBD->getPattern(i)->getType()->hasError()) {\n\n        \/\/ Decide whether we should suppress default initialization.\n        \/\/\n        \/\/ Note: Swift 4 had a bug where properties with a desugared optional\n        \/\/ type like Optional<Int> had a half-way behavior where sometimes\n        \/\/ they behave like they are default initialized, and sometimes not.\n        \/\/\n        \/\/ In Swift 5 mode, use the right condition here, and only default\n        \/\/ initialize properties with a sugared Optional type.\n        \/\/\n        \/\/ (The restriction to sugared types only comes because we don't have\n        \/\/ the iterative declaration checker yet; so in general, we cannot\n        \/\/ look at the type of a property at all, and can only look at the\n        \/\/ TypeRepr, because we haven't validated the property yet.)\n        if (TC.Context.isSwiftVersionAtLeast(5)) {\n          if (!PBD->isDefaultInitializable(i))\n            continue;\n        } else {\n          if (PBD->getPattern(i)->isNeverDefaultInitializable())\n            continue;\n        }\n\n        auto type = PBD->getPattern(i)->getType();\n        if (auto defaultInit = buildDefaultInitializer(TC, type)) {\n          \/\/ If we got a default initializer, install it and re-type-check it\n          \/\/ to make sure it is properly coerced to the pattern type.\n          PBD->setInit(i, defaultInit);\n        }\n      }\n\n      if (PBD->isInitialized(i)) {\n        \/\/ Add the attribute that preserves the \"has an initializer\" value across\n        \/\/ module generation, as required for TBDGen.\n        PBD->getPattern(i)->forEachVariable([&](VarDecl *VD) {\n          if (VD->hasStorage() &&\n              !VD->getAttrs().hasAttribute<HasInitialValueAttr>()) {\n            auto *attr = new (TC.Context) HasInitialValueAttr(\n                \/*IsImplicit=*\/true);\n            VD->getAttrs().add(attr);\n          }\n        });\n      }\n    }\n\n    bool isInSILMode = false;\n    if (auto sourceFile = DC->getParentSourceFile())\n      isInSILMode = sourceFile->Kind == SourceFileKind::SIL;\n    bool isTypeContext = DC->isTypeContext();\n\n    \/\/ If this is a declaration without an initializer, reject code if\n    \/\/ uninitialized vars are not allowed.\n    for (unsigned i = 0, e = PBD->getNumPatternEntries(); i != e; ++i) {\n      auto entry = PBD->getPatternList()[i];\n    \n      if (entry.isInitialized() || isInSILMode) continue;\n      \n      entry.getPattern()->forEachVariable([&](VarDecl *var) {\n        \/\/ If the variable has no storage, it never needs an initializer.\n        if (!var->hasStorage())\n          return;\n\n        if (var->isInvalid() || PBD->isInvalid())\n          return;\n\n        auto markVarAndPBDInvalid = [PBD, var] {\n          PBD->setInvalid();\n          var->setInvalid();\n          if (!var->hasType())\n            var->markInvalid();\n        };\n\n        \/\/ Non-member observing properties need an initializer.\n        if (var->getWriteImpl() == WriteImplKind::StoredWithObservers &&\n            !isTypeContext) {\n          TC.diagnose(var->getLoc(), diag::observingprop_requires_initializer);\n          markVarAndPBDInvalid();\n          return;\n        }\n\n        \/\/ Static\/class declarations require an initializer unless in a\n        \/\/ protocol.\n        if (var->isStatic() && !isa<ProtocolDecl>(DC)) {\n          \/\/ ...but don't enforce this for SIL or parseable interface files.\n          switch (DC->getParentSourceFile()->Kind) {\n          case SourceFileKind::Interface:\n          case SourceFileKind::SIL:\n            return;\n          case SourceFileKind::Main:\n          case SourceFileKind::REPL:\n          case SourceFileKind::Library:\n            break;\n          }\n\n          TC.diagnose(var->getLoc(), diag::static_requires_initializer,\n                      var->getCorrectStaticSpelling());\n          markVarAndPBDInvalid();\n          return;\n        }\n\n        \/\/ Global variables require an initializer in normal source files.\n        if (DC->isModuleScopeContext()) {\n          switch (DC->getParentSourceFile()->Kind) {\n          case SourceFileKind::Main:\n          case SourceFileKind::REPL:\n          case SourceFileKind::Interface:\n          case SourceFileKind::SIL:\n            return;\n          case SourceFileKind::Library:\n            break;\n          }\n\n          TC.diagnose(var->getLoc(), diag::global_requires_initializer,\n                      var->isLet());\n          markVarAndPBDInvalid();\n          return;\n        }\n      });\n    }\n\n    TC.checkDeclAttributes(PBD);\n\n    checkAccessControl(TC, PBD);\n\n    \/\/ If the initializers in the PBD aren't checked yet, do so now.\n    for (unsigned i = 0, e = PBD->getNumPatternEntries(); i != e; ++i) {\n      if (!PBD->isInitialized(i))\n        continue;\n\n      if (!PBD->isInitializerChecked(i))\n        TC.typeCheckPatternBinding(PBD, i);\n\n      if (!PBD->isInvalid()) {\n        auto &entry = PBD->getPatternList()[i];\n        auto *init = PBD->getInit(i);\n\n        \/\/ If we're performing an binding to a weak or unowned variable from a\n        \/\/ constructor call, emit a warning that the instance will be immediately\n        \/\/ deallocated.\n        diagnoseUnownedImmediateDeallocation(TC, PBD->getPattern(i),\n                                              entry.getEqualLoc(),\n                                              init);\n\n        \/\/ If we entered an initializer context, contextualize any\n        \/\/ auto-closures we might have created.\n        \/\/ Note that we don't contextualize the initializer for a property\n        \/\/ with a wrapper, because the initializer will have been subsumed\n        \/\/ by the backing storage property.\n        if (!DC->isLocalContext() &&\n            !(PBD->getSingleVar() &&\n              PBD->getSingleVar()->getAttachedPropertyWrapper())) {\n          auto *initContext = cast_or_null<PatternBindingInitializer>(\n              entry.getInitContext());\n          if (initContext) {\n            \/\/ Check safety of error-handling in the declaration, too.\n            TC.checkInitializerErrorHandling(initContext, init);\n            (void) TC.contextualizeInitializer(initContext, init);\n          }\n        }\n      }\n    }\n  }\n\n  void visitSubscriptDecl(SubscriptDecl *SD) {\n    TC.validateDecl(SD);\n\n    if (!SD->isInvalid()) {\n      TC.checkReferencedGenericParams(SD);\n      checkGenericParams(SD->getGenericParams(), SD, TC);\n      TC.checkProtocolSelfRequirements(SD);\n    }\n\n    TC.checkDeclAttributes(SD);\n\n    checkAccessControl(TC, SD);\n\n    if (!checkOverrides(SD)) {\n      \/\/ If a subscript has an override attribute but does not override\n      \/\/ anything, complain.\n      if (auto *OA = SD->getAttrs().getAttribute<OverrideAttr>()) {\n        if (!SD->getOverriddenDecl()) {\n          TC.diagnose(SD, diag::subscript_does_not_override)\n            .highlight(OA->getLocation());\n          OA->setInvalid();\n        }\n      }\n    }\n\n    triggerAccessorSynthesis(TC, SD);\n    if (SD->getAttrs().hasAttribute<DynamicReplacementAttr>()) {\n      TC.checkDynamicReplacementAttribute(SD);\n    }\n\n    TC.checkParameterAttributes(SD->getIndices());\n    TC.checkDefaultArguments(SD->getIndices(), SD);\n  }\n\n  void visitTypeAliasDecl(TypeAliasDecl *TAD) {\n    TC.checkDeclAttributesEarly(TAD);\n\n    TC.validateDecl(TAD);\n    TC.checkDeclAttributes(TAD);\n\n    checkAccessControl(TC, TAD);\n  }\n  \n  void visitOpaqueTypeDecl(OpaqueTypeDecl *OTD) {\n    TC.checkDeclAttributesEarly(OTD);\n    \n    TC.validateDecl(OTD);\n    TC.checkDeclAttributes(OTD);\n    \n    checkAccessControl(TC, OTD);\n  }\n  \n  void visitAssociatedTypeDecl(AssociatedTypeDecl *AT) {\n    TC.checkDeclAttributesEarly(AT);\n\n    TC.validateDecl(AT);\n    TC.checkDeclAttributes(AT);\n\n    checkInheritanceClause(AT);\n    auto *proto = AT->getProtocol();\n\n    checkProtocolSelfRequirements(proto, AT);\n\n    if (proto->isObjC()) {\n      TC.diagnose(AT->getLoc(),\n                  diag::associated_type_objc,\n                  AT->getName(),\n                  proto->getName());\n    }\n\n    checkAccessControl(TC, AT);\n\n    \/\/ Trigger the checking for overridden declarations.\n    (void)AT->getOverriddenDecls();\n\n    auto defaultType = AT->getDefaultDefinitionType();\n    if (defaultType && !defaultType->hasError()) {\n      \/\/ associatedtype X = X is invalid\n      auto mentionsItself =\n        defaultType.findIf([&](Type defaultType) {\n          if (auto DMT = defaultType->getAs<DependentMemberType>()) {\n            return DMT->getAssocType() == AT;\n          }\n          return false;\n        });\n\n      if (mentionsItself) {\n        TC.diagnose(AT->getDefaultDefinitionTypeRepr()->getLoc(),\n                    diag::recursive_decl_reference,\n                    AT->getDescriptiveKind(), AT->getName());\n        AT->diagnose(diag::kind_declared_here, DescriptiveDeclKind::Type);\n      }\n    }\n  }\n\n  void checkUnsupportedNestedType(NominalTypeDecl *NTD) {\n    TC.diagnoseInlinableLocalType(NTD);\n\n    \/\/ We don't support protocols outside the top level of a file.\n    if (isa<ProtocolDecl>(NTD) &&\n        !NTD->getParent()->isModuleScopeContext()) {\n      TC.diagnose(NTD->getLoc(),\n                  diag::unsupported_nested_protocol,\n                  NTD->getName());\n      return;\n    }\n\n    \/\/ We don't support nested types in generics yet.\n    if (NTD->isGenericContext()) {\n      auto DC = NTD->getDeclContext();\n      if (auto proto = DC->getSelfProtocolDecl()) {\n        if (DC->getExtendedProtocolDecl()) {\n          TC.diagnose(NTD->getLoc(),\n                      diag::unsupported_type_nested_in_protocol_extension,\n                      NTD->getName(),\n                      proto->getName());\n        } else {\n          TC.diagnose(NTD->getLoc(),\n                      diag::unsupported_type_nested_in_protocol,\n                      NTD->getName(),\n                      proto->getName());\n        }\n      }\n\n      if (DC->isLocalContext() && DC->isGenericContext()) {\n        \/\/ A local generic context is a generic function.\n        if (auto AFD = dyn_cast<AbstractFunctionDecl>(DC)) {\n          TC.diagnose(NTD->getLoc(),\n                      diag::unsupported_type_nested_in_generic_function,\n                      NTD->getName(),\n                      AFD->getFullName());\n        } else {\n          TC.diagnose(NTD->getLoc(),\n                      diag::unsupported_type_nested_in_generic_closure,\n                      NTD->getName());\n        }\n      }\n    }\n  }\n\n  void visitEnumDecl(EnumDecl *ED) {\n    TC.checkDeclAttributesEarly(ED);\n\n    checkUnsupportedNestedType(ED);\n    TC.validateDecl(ED);\n    checkGenericParams(ED->getGenericParams(), ED, TC);\n\n    {\n      \/\/ Check for circular inheritance of the raw type.\n      SmallVector<EnumDecl *, 8> path;\n      path.push_back(ED);\n      checkCircularity(TC, ED, diag::circular_enum_inheritance,\n                       DescriptiveDeclKind::Enum, path);\n    }\n\n    for (Decl *member : ED->getMembers())\n      visit(member);\n\n    TC.checkDeclAttributes(ED);\n\n    checkInheritanceClause(ED);\n\n    checkAccessControl(TC, ED);\n\n    if (ED->hasRawType() && !ED->isObjC()) {\n      \/\/ ObjC enums have already had their raw values checked, but pure Swift\n      \/\/ enums haven't.\n      checkEnumRawValues(TC, ED);\n    }\n\n    TC.checkDeclCircularity(ED);\n    TC.ConformanceContexts.push_back(ED);\n  }\n\n  void visitStructDecl(StructDecl *SD) {\n    TC.checkDeclAttributesEarly(SD);\n\n    checkUnsupportedNestedType(SD);\n\n    TC.validateDecl(SD);\n    checkGenericParams(SD->getGenericParams(), SD, TC);\n\n    TC.addImplicitConstructors(SD);\n\n    for (Decl *Member : SD->getMembers())\n      visit(Member);\n\n    TC.checkDeclAttributes(SD);\n\n    checkInheritanceClause(SD);\n\n    checkAccessControl(TC, SD);\n\n    TC.checkDeclCircularity(SD);\n    TC.ConformanceContexts.push_back(SD);\n  }\n\n  \/\/\/ Check whether the given properties can be @NSManaged in this class.\n  static bool propertiesCanBeNSManaged(ClassDecl *classDecl,\n                                       ArrayRef<VarDecl *> vars) {\n    \/\/ Check whether we have an Objective-C-defined class in our\n    \/\/ inheritance chain.\n    if (!classDecl->checkAncestry(AncestryFlags::ClangImported))\n      return false;\n\n    \/\/ If all of the variables are @objc, we can use @NSManaged.\n    for (auto var : vars) {\n      if (!var->isObjC())\n        return false;\n    }\n\n    \/\/ Okay, we can use @NSManaged.\n    return true;\n  }\n\n  \/\/\/ Check that all stored properties have in-class initializers.\n  void checkRequiredInClassInits(ClassDecl *cd) {\n    ClassDecl *source = nullptr;\n    for (auto member : cd->getMembers()) {\n      auto pbd = dyn_cast<PatternBindingDecl>(member);\n      if (!pbd)\n        continue;\n\n      if (pbd->isStatic() || !pbd->hasStorage() || \n          pbd->isDefaultInitializable() || pbd->isInvalid())\n        continue;\n\n      \/\/ The variables in this pattern have not been\n      \/\/ initialized. Diagnose the lack of initial value.\n      pbd->setInvalid();\n      SmallVector<VarDecl *, 4> vars;\n      for (auto entry : pbd->getPatternList())\n        entry.getPattern()->collectVariables(vars);\n      bool suggestNSManaged = propertiesCanBeNSManaged(cd, vars);\n      switch (vars.size()) {\n      case 0:\n        llvm_unreachable(\"should have been marked invalid\");\n\n      case 1:\n        TC.diagnose(pbd->getLoc(), diag::missing_in_class_init_1,\n                    vars[0]->getName(), suggestNSManaged);\n        break;\n\n      case 2:\n        TC.diagnose(pbd->getLoc(), diag::missing_in_class_init_2,\n                    vars[0]->getName(), vars[1]->getName(), suggestNSManaged);\n        break;\n\n      case 3:\n        TC.diagnose(pbd->getLoc(), diag::missing_in_class_init_3plus,\n                    vars[0]->getName(), vars[1]->getName(), vars[2]->getName(),\n                    false, suggestNSManaged);\n        break;\n\n      default:\n        TC.diagnose(pbd->getLoc(), diag::missing_in_class_init_3plus,\n                    vars[0]->getName(), vars[1]->getName(), vars[2]->getName(),\n                    true, suggestNSManaged);\n        break;\n      }\n\n      \/\/ Figure out where this requirement came from.\n      if (!source) {\n        source = cd;\n        while (true) {\n          \/\/ If this class had the 'requires_stored_property_inits'\n          \/\/ attribute, diagnose here.\n          if (source->getAttrs().\n                hasAttribute<RequiresStoredPropertyInitsAttr>())\n            break;\n\n          \/\/ If the superclass doesn't require in-class initial\n          \/\/ values, the requirement was introduced at this point, so\n          \/\/ stop here.\n          auto superclass = source->getSuperclassDecl();\n          if (!superclass->requiresStoredPropertyInits())\n            break;\n\n          \/\/ Keep looking.\n          source = superclass;\n        }\n      }\n\n      \/\/ Add a note describing why we need an initializer.\n      TC.diagnose(source, diag::requires_stored_property_inits_here,\n                  source->getDeclaredType(), cd == source, suggestNSManaged);\n    }\n  }\n\n\n  void visitClassDecl(ClassDecl *CD) {\n    TC.checkDeclAttributesEarly(CD);\n\n    checkUnsupportedNestedType(CD);\n\n    TC.validateDecl(CD);\n    TC.requestSuperclassLayout(CD);\n    checkGenericParams(CD->getGenericParams(), CD, TC);\n\n    {\n      \/\/ Check for circular inheritance.\n      SmallVector<ClassDecl *, 8> path;\n      path.push_back(CD);\n      checkCircularity(TC, CD, diag::circular_class_inheritance,\n                       DescriptiveDeclKind::Class, path);\n    }\n\n    for (Decl *Member : CD->getMembers()) {\n      visit(Member);\n    }\n\n    \/\/ If this class requires all of its stored properties to have\n    \/\/ in-class initializers, diagnose this now.\n    if (CD->requiresStoredPropertyInits())\n      checkRequiredInClassInits(CD);\n\n    TC.addImplicitConstructors(CD);\n    CD->addImplicitDestructor();\n\n    if (auto superclassTy = CD->getSuperclass()) {\n      ClassDecl *Super = superclassTy->getClassOrBoundGenericClass();\n\n      if (auto *SF = CD->getParentSourceFile()) {\n        if (auto *tracker = SF->getReferencedNameTracker()) {\n          bool isPrivate =\n              CD->getFormalAccess() <= AccessLevel::FilePrivate;\n          tracker->addUsedMember({Super, Identifier()}, !isPrivate);\n        }\n      }\n\n      bool isInvalidSuperclass = false;\n\n      if (Super->isFinal()) {\n        TC.diagnose(CD, diag::inheritance_from_final_class,\n                    Super->getName());\n        \/\/ FIXME: should this really be skipping the rest of decl-checking?\n        return;\n      }\n\n      if (Super->hasClangNode() && Super->getGenericParams()\n          && superclassTy->hasTypeParameter()) {\n        TC.diagnose(CD,\n                    diag::inheritance_from_unspecialized_objc_generic_class,\n                    Super->getName());\n      }\n\n      switch (Super->getForeignClassKind()) {\n      case ClassDecl::ForeignKind::Normal:\n        break;\n      case ClassDecl::ForeignKind::CFType:\n        TC.diagnose(CD, diag::inheritance_from_cf_class,\n                    Super->getName());\n        isInvalidSuperclass = true;\n        break;\n      case ClassDecl::ForeignKind::RuntimeOnly:\n        TC.diagnose(CD, diag::inheritance_from_objc_runtime_visible_class,\n                    Super->getName());\n        isInvalidSuperclass = true;\n        break;\n      }\n\n      if (!isInvalidSuperclass && Super->hasMissingVTableEntries() &&\n          !Super->isResilient(CD->getParentModule(),\n                              ResilienceExpansion::Minimal)) {\n        auto *superFile = Super->getModuleScopeContext();\n        if (auto *serialized = dyn_cast<SerializedASTFile>(superFile)) {\n          if (serialized->getLanguageVersionBuiltWith() !=\n              TC.getLangOpts().EffectiveLanguageVersion) {\n            TC.diagnose(CD,\n                        diag::inheritance_from_class_with_missing_vtable_entries_versioned,\n                        Super->getName(),\n                        serialized->getLanguageVersionBuiltWith(),\n                        TC.getLangOpts().EffectiveLanguageVersion);\n            isInvalidSuperclass = true;\n          }\n        }\n        if (!isInvalidSuperclass) {\n          TC.diagnose(\n              CD, diag::inheritance_from_class_with_missing_vtable_entries,\n              Super->getName());\n          isInvalidSuperclass = true;\n        }\n      }\n\n      if (!TC.Context.isAccessControlDisabled()) {\n        \/\/ Require the superclass to be open if this is outside its\n        \/\/ defining module.  But don't emit another diagnostic if we\n        \/\/ already complained about the class being inherently\n        \/\/ un-subclassable.\n        if (!isInvalidSuperclass &&\n            !Super->hasOpenAccess(CD->getDeclContext()) &&\n            Super->getModuleContext() != CD->getModuleContext()) {\n          TC.diagnose(CD, diag::superclass_not_open, superclassTy);\n          isInvalidSuperclass = true;\n        }\n\n        \/\/ Require superclasses to be open if the subclass is open.\n        \/\/ This is a restriction we can consider lifting in the future,\n        \/\/ e.g. to enable a \"sealed\" superclass whose subclasses are all\n        \/\/ of one of several alternatives.\n        if (!isInvalidSuperclass &&\n            CD->getFormalAccess() == AccessLevel::Open &&\n            Super->getFormalAccess() != AccessLevel::Open) {\n          TC.diagnose(CD, diag::superclass_of_open_not_open, superclassTy);\n          TC.diagnose(Super, diag::superclass_here);\n        }\n      }\n    }\n\n    TC.checkDeclAttributes(CD);\n\n    checkInheritanceClause(CD);\n\n    checkAccessControl(TC, CD);\n\n    TC.checkDeclCircularity(CD);\n    TC.ConformanceContexts.push_back(CD);\n  }\n\n  void visitProtocolDecl(ProtocolDecl *PD) {\n    TC.checkDeclAttributesEarly(PD);\n\n    checkUnsupportedNestedType(PD);\n\n    TC.validateDecl(PD);\n    if (!PD->hasValidSignature())\n      return;\n\n    auto *SF = PD->getParentSourceFile();\n    {\n      \/\/ Check for circular inheritance within the protocol.\n      SmallVector<ProtocolDecl *, 8> path;\n      path.push_back(PD);\n      checkCircularity(TC, PD, diag::circular_protocol_def,\n                       DescriptiveDeclKind::Protocol, path);\n\n      if (SF) {\n        if (auto *tracker = SF->getReferencedNameTracker()) {\n          bool isNonPrivate =\n              (PD->getFormalAccess() > AccessLevel::FilePrivate);\n          for (auto *parentProto : PD->getInheritedProtocols())\n            tracker->addUsedMember({parentProto, Identifier()}, isNonPrivate);\n        }\n      }\n    }\n\n    \/\/ Check the members.\n    for (auto Member : PD->getMembers())\n      visit(Member);\n\n    TC.checkDeclAttributes(PD);\n\n    checkAccessControl(TC, PD);\n\n    checkInheritanceClause(PD);\n\n    TC.checkDeclCircularity(PD);\n    if (PD->isResilient())\n      if (!SF || SF->Kind != SourceFileKind::Interface)\n        TC.inferDefaultWitnesses(PD);\n\n    if (TC.Context.LangOpts.DebugGenericSignatures) {\n      auto requirementsSig =\n        GenericSignature::get({PD->getProtocolSelfType()},\n                              PD->getRequirementSignature());\n\n      llvm::errs() << \"Protocol requirement signature:\\n\";\n      PD->dumpRef(llvm::errs());\n      llvm::errs() << \"\\n\";\n      llvm::errs() << \"Requirement signature: \";\n      requirementsSig->print(llvm::errs());\n      llvm::errs() << \"\\n\";\n\n      \/\/ Note: One cannot canonicalize a requirement signature, because\n      \/\/ requirement signatures are necessarily missing requirements.\n      llvm::errs() << \"Canonical requirement signature: \";\n      auto canRequirementSig =\n        GenericSignature::getCanonical(requirementsSig->getGenericParams(),\n                                       requirementsSig->getRequirements(),\n                                       \/*skipValidation=*\/true);\n      canRequirementSig->print(llvm::errs());\n      llvm::errs() << \"\\n\";\n    }\n\n    \/\/ Explicitly calculate this bit.\n    (void) PD->existentialTypeSupported(&TC);\n\n    \/\/ Explicity compute the requirement signature to detect errors.\n    (void) PD->getRequirementSignature();\n  }\n\n  void visitVarDecl(VarDecl *VD) {\n    \/\/ Delay type-checking on VarDecls until we see the corresponding\n    \/\/ PatternBindingDecl.\n  }\n\n  \/\/\/ Determine whether the given declaration requires a definition.\n  \/\/\/\n  \/\/\/ Only valid for declarations that can have definitions, i.e.,\n  \/\/\/ functions, initializers, etc.\n  static bool requiresDefinition(Decl *decl) {\n    \/\/ Invalid, implicit, and Clang-imported declarations never\n    \/\/ require a definition.\n    if (decl->isInvalid() || decl->isImplicit() || decl->hasClangNode())\n      return false;\n\n    \/\/ Protocol requirements do not require definitions.\n    if (isa<ProtocolDecl>(decl->getDeclContext()))\n      return false;\n\n    \/\/ Functions can have _silgen_name, semantics, and NSManaged attributes.\n    if (auto func = dyn_cast<AbstractFunctionDecl>(decl)) {\n      if (func->getAttrs().hasAttribute<SILGenNameAttr>() ||\n          func->getAttrs().hasAttribute<SemanticsAttr>() ||\n          func->getAttrs().hasAttribute<NSManagedAttr>())\n        return false;\n    }\n\n    \/\/ Declarations in SIL and parseable interface files don't require\n    \/\/ definitions.\n    if (auto sourceFile = decl->getDeclContext()->getParentSourceFile()) {\n      switch (sourceFile->Kind) {\n      case SourceFileKind::SIL:\n      case SourceFileKind::Interface:\n        return false;\n      case SourceFileKind::Library:\n      case SourceFileKind::Main:\n      case SourceFileKind::REPL:\n        break;\n      }\n    }\n\n    \/\/ Everything else requires a definition.\n    return true;\n  }\n\n  void visitFuncDecl(FuncDecl *FD) {\n    TC.validateDecl(FD);\n\n    if (!FD->isInvalid()) {\n      checkGenericParams(FD->getGenericParams(), FD, TC);\n      TC.checkReferencedGenericParams(FD);\n      TC.checkProtocolSelfRequirements(FD);\n    }\n\n    checkAccessControl(TC, FD);\n\n    if (!checkOverrides(FD)) {\n      \/\/ If a method has an 'override' keyword but does not\n      \/\/ override anything, complain.\n      if (auto *OA = FD->getAttrs().getAttribute<OverrideAttr>()) {\n        if (!FD->getOverriddenDecl()) {\n          TC.diagnose(FD, diag::method_does_not_override)\n            .highlight(OA->getLocation());\n          OA->setInvalid();\n        }\n      }\n    }\n\n    if (requiresDefinition(FD) && !FD->hasBody()) {\n      \/\/ Complain if we should have a body.\n      TC.diagnose(FD->getLoc(), diag::func_decl_without_brace);\n    } else {\n      \/\/ Record the body.\n      TC.definedFunctions.push_back(FD);\n    }\n\n    if (FD->getAttrs().hasAttribute<DynamicReplacementAttr>()) {\n      TC.checkDynamicReplacementAttribute(FD);\n    }\n\n    TC.checkParameterAttributes(FD->getParameters());\n  }\n\n  void visitModuleDecl(ModuleDecl *) { }\n\n  void visitEnumCaseDecl(EnumCaseDecl *ECD) {\n    \/\/ The type-checker doesn't care about how these are grouped.\n  }\n\n  void visitEnumElementDecl(EnumElementDecl *EED) {\n    TC.checkDeclAttributesEarly(EED);\n\n    TC.validateDecl(EED);\n    TC.checkDeclAttributes(EED);\n\n    if (auto *PL = EED->getParameterList()) {\n      TC.checkParameterAttributes(PL);\n      TC.checkDefaultArguments(PL, EED);\n    }\n\n    checkAccessControl(TC, EED);\n  }\n\n  void visitExtensionDecl(ExtensionDecl *ED) {\n    TC.validateExtension(ED);\n\n    TC.checkDeclAttributesEarly(ED);\n\n    checkInheritanceClause(ED);\n\n    if (auto nominal = ED->getExtendedNominal()) {\n      TC.validateDecl(nominal);\n      if (auto *classDecl = dyn_cast<ClassDecl>(nominal))\n        TC.requestNominalLayout(classDecl);\n\n      \/\/ Check the raw values of an enum, since we might synthesize\n      \/\/ RawRepresentable while checking conformances on this extension.\n      if (auto enumDecl = dyn_cast<EnumDecl>(nominal)) {\n        if (enumDecl->hasRawType())\n          checkEnumRawValues(TC, enumDecl);\n      }\n\n      \/\/ Only generic and protocol types are permitted to have\n      \/\/ trailing where clauses.\n      if (auto trailingWhereClause = ED->getTrailingWhereClause()) {\n        if (!ED->getGenericParams() &&\n            !ED->isInvalid()) {\n          ED->diagnose(diag::extension_nongeneric_trailing_where,\n                       nominal->getFullName())\n          .highlight(trailingWhereClause->getSourceRange());\n        }\n      }\n    }\n\n    checkGenericParams(ED->getGenericParams(), ED, TC);\n\n    validateAttributes(TC, ED);\n\n    for (Decl *Member : ED->getMembers())\n      visit(Member);\n\n    TC.ConformanceContexts.push_back(ED);\n\n    if (!ED->isInvalid())\n      TC.checkDeclAttributes(ED);\n\n    checkAccessControl(TC, ED);\n  }\n\n  void visitTopLevelCodeDecl(TopLevelCodeDecl *TLCD) {\n    \/\/ See swift::performTypeChecking for TopLevelCodeDecl handling.\n    llvm_unreachable(\"TopLevelCodeDecls are handled elsewhere\");\n  }\n  \n  void visitIfConfigDecl(IfConfigDecl *ICD) {\n    \/\/ The active members of the #if block will be type checked along with\n    \/\/ their enclosing declaration.\n    TC.checkDeclAttributesEarly(ICD);\n    TC.checkDeclAttributes(ICD);\n  }\n\n  void visitPoundDiagnosticDecl(PoundDiagnosticDecl *PDD) {\n    if (PDD->hasBeenEmitted()) { return; }\n    PDD->markEmitted();\n    TC.diagnose(PDD->getMessage()->getStartLoc(),\n      PDD->isError() ? diag::pound_error : diag::pound_warning,\n      PDD->getMessage()->getValue())\n      .highlight(PDD->getMessage()->getSourceRange());\n  }\n\n  void visitConstructorDecl(ConstructorDecl *CD) {\n    TC.validateDecl(CD);\n\n    if (!CD->isInvalid()) {\n      checkGenericParams(CD->getGenericParams(), CD, TC);\n      TC.checkReferencedGenericParams(CD);\n      TC.checkProtocolSelfRequirements(CD);\n    }\n\n    \/\/ Check whether this initializer overrides an initializer in its\n    \/\/ superclass.\n    if (!checkOverrides(CD)) {\n      \/\/ If an initializer has an override attribute but does not override\n      \/\/ anything or overrides something that doesn't need an 'override'\n      \/\/ keyword (e.g., a convenience initializer), complain.\n      \/\/ anything, or overrides something that complain.\n      if (auto *attr = CD->getAttrs().getAttribute<OverrideAttr>()) {\n        if (!CD->getOverriddenDecl()) {\n          TC.diagnose(CD, diag::initializer_does_not_override)\n            .highlight(attr->getLocation());\n          attr->setInvalid();\n        } else if (attr->isImplicit()) {\n          \/\/ Don't diagnose implicit attributes.\n        } else if (overrideRequiresKeyword(CD->getOverriddenDecl())\n                     == OverrideRequiresKeyword::Never) {\n          \/\/ Special case: we are overriding a 'required' initializer, so we\n          \/\/ need (only) the 'required' keyword.\n          if (cast<ConstructorDecl>(CD->getOverriddenDecl())->isRequired()) {\n            if (CD->getAttrs().hasAttribute<RequiredAttr>()) {\n              TC.diagnose(CD, diag::required_initializer_override_keyword)\n                .fixItRemove(attr->getLocation());\n            } else {\n              TC.diagnose(CD, diag::required_initializer_override_wrong_keyword)\n                .fixItReplace(attr->getLocation(), \"required\");\n              CD->getAttrs().add(\n                new (TC.Context) RequiredAttr(\/*IsImplicit=*\/true));\n            }\n\n            TC.diagnose(findNonImplicitRequiredInit(CD->getOverriddenDecl()),\n                        diag::overridden_required_initializer_here);\n          } else {\n            \/\/ We tried to override a convenience initializer.\n            TC.diagnose(CD, diag::initializer_does_not_override)\n              .highlight(attr->getLocation());\n            TC.diagnose(CD->getOverriddenDecl(),\n                        diag::convenience_init_override_here);\n          }\n        }\n      }\n\n      \/\/ A failable initializer cannot override a non-failable one.\n      \/\/ This would normally be diagnosed by the covariance rules;\n      \/\/ however, those are disabled so that we can provide a more\n      \/\/ specific diagnostic here.\n      if (CD->getFailability() != OTK_None &&\n          CD->getOverriddenDecl() &&\n          CD->getOverriddenDecl()->getFailability() == OTK_None) {\n        TC.diagnose(CD, diag::failable_initializer_override,\n                    CD->getFullName());\n        TC.diagnose(CD->getOverriddenDecl(),\n                    diag::nonfailable_initializer_override_here,\n                    CD->getOverriddenDecl()->getFullName());\n      }\n    }\n\n    \/\/ If this initializer overrides a 'required' initializer, it must itself\n    \/\/ be marked 'required'.\n    if (!CD->getAttrs().hasAttribute<RequiredAttr>()) {\n      if (CD->getOverriddenDecl() && CD->getOverriddenDecl()->isRequired()) {\n        TC.diagnose(CD, diag::required_initializer_missing_keyword)\n          .fixItInsert(CD->getLoc(), \"required \");\n\n        TC.diagnose(findNonImplicitRequiredInit(CD->getOverriddenDecl()),\n                    diag::overridden_required_initializer_here);\n\n        CD->getAttrs().add(\n            new (TC.Context) RequiredAttr(\/*IsImplicit=*\/true));\n      }\n    }\n\n    if (CD->isRequired()) {\n      if (auto nominal = CD->getDeclContext()->getSelfNominalTypeDecl()) {\n        AccessLevel requiredAccess;\n        switch (nominal->getFormalAccess()) {\n        case AccessLevel::Open:\n          requiredAccess = AccessLevel::Public;\n          break;\n        case AccessLevel::Public:\n        case AccessLevel::Internal:\n          requiredAccess = AccessLevel::Internal;\n          break;\n        case AccessLevel::FilePrivate:\n        case AccessLevel::Private:\n          requiredAccess = AccessLevel::FilePrivate;\n          break;\n        }\n        if (CD->getFormalAccess() < requiredAccess) {\n          auto diag = TC.diagnose(CD, diag::required_initializer_not_accessible,\n                                  nominal->getFullName());\n          fixItAccess(diag, CD, requiredAccess);\n        }\n      }\n    }\n\n    TC.checkDeclAttributes(CD);\n    TC.checkParameterAttributes(CD->getParameters());\n\n    checkAccessControl(TC, CD);\n\n    if (requiresDefinition(CD) && !CD->hasBody()) {\n      \/\/ Complain if we should have a body.\n      TC.diagnose(CD->getLoc(), diag::missing_initializer_def);\n    } else {\n      TC.definedFunctions.push_back(CD);\n    }\n\n    if (CD->getAttrs().hasAttribute<DynamicReplacementAttr>()) {\n      TC.checkDynamicReplacementAttribute(CD);\n    }\n  }\n\n  void visitDestructorDecl(DestructorDecl *DD) {\n    TC.validateDecl(DD);\n    TC.checkDeclAttributes(DD);\n    TC.definedFunctions.push_back(DD);\n  }\n};\n} \/\/ end anonymous namespace\n\nbool TypeChecker::isAvailabilitySafeForConformance(\n    ProtocolDecl *proto, ValueDecl *requirement, ValueDecl *witness,\n    DeclContext *dc, AvailabilityContext &requirementInfo) {\n\n  \/\/ We assume conformances in\n  \/\/ non-SourceFiles have already been checked for availability.\n  if (!dc->getParentSourceFile())\n    return true;\n\n  NominalTypeDecl *conformingDecl = dc->getSelfNominalTypeDecl();\n  assert(conformingDecl && \"Must have conforming declaration\");\n\n  \/\/ Make sure that any access of the witness through the protocol\n  \/\/ can only occur when the witness is available. That is, make sure that\n  \/\/ on every version where the conforming declaration is available, if the\n  \/\/ requirement is available then the witness is available as well.\n  \/\/ We do this by checking that (an over-approximation of) the intersection of\n  \/\/ the requirement's available range with both the conforming declaration's\n  \/\/ available range and the protocol's available range is fully contained in\n  \/\/ (an over-approximation of) the intersection of the witnesses's available\n  \/\/ range with both the conforming type's available range and the protocol\n  \/\/ declaration's available range.\n  AvailabilityContext witnessInfo =\n      AvailabilityInference::availableRange(witness, Context);\n  requirementInfo = AvailabilityInference::availableRange(requirement, Context);\n\n  AvailabilityContext infoForConformingDecl =\n      overApproximateAvailabilityAtLocation(conformingDecl->getLoc(),\n                                            conformingDecl);\n\n  \/\/ Constrain over-approximates intersection of version ranges.\n  witnessInfo.constrainWith(infoForConformingDecl);\n  requirementInfo.constrainWith(infoForConformingDecl);\n\n  AvailabilityContext infoForProtocolDecl =\n      overApproximateAvailabilityAtLocation(proto->getLoc(), proto);\n\n  witnessInfo.constrainWith(infoForProtocolDecl);\n  requirementInfo.constrainWith(infoForProtocolDecl);\n\n  return requirementInfo.isContainedIn(witnessInfo);\n}\n\nvoid TypeChecker::typeCheckDecl(Decl *D) {\n  checkForForbiddenPrefix(D);\n  DeclChecker(*this).visit(D);\n}\n\n\/\/\/ Validate the underlying type of the given typealias.\nstatic void validateTypealiasType(TypeChecker &tc, TypeAliasDecl *typeAlias) {\n  TypeResolutionOptions options(\n    (typeAlias->getGenericParams() ?\n     TypeResolverContext::GenericTypeAliasDecl :\n     TypeResolverContext::TypeAliasDecl));\n\n  if (!typeAlias->getDeclContext()->isCascadingContextForLookup(\n        \/*functionsAreNonCascading*\/true)) {\n     options |= TypeResolutionFlags::KnownNonCascadingDependency;\n  }\n\n  \/\/ This can happen when code completion is attempted inside\n  \/\/ of typealias underlying type e.g. `typealias F = () -> Int#^TOK^#`\n  auto underlyingType = typeAlias->getUnderlyingTypeLoc();\n  if (underlyingType.isNull()) {\n    typeAlias->getUnderlyingTypeLoc().setInvalidType(tc.Context);\n    typeAlias->setInterfaceType(ErrorType::get(tc.Context));\n    return;\n  }\n\n  if (tc.validateType(typeAlias->getUnderlyingTypeLoc(),\n                    TypeResolution::forInterface(typeAlias, &tc), options)) {\n    typeAlias->setInvalid();\n    typeAlias->getUnderlyingTypeLoc().setInvalidType(tc.Context);\n  }\n\n  typeAlias->setUnderlyingType(typeAlias->getUnderlyingTypeLoc().getType());\n}\n\n\n\/\/\/ Bind the given function declaration, which declares an operator, to\n\/\/\/ the corresponding operator declaration.\nvoid bindFuncDeclToOperator(TypeChecker &TC, FuncDecl *FD) {\n  OperatorDecl *op = nullptr;\n  auto operatorName = FD->getFullName().getBaseIdentifier();\n\n  \/\/ Check for static\/final\/class when we're in a type.\n  auto dc = FD->getDeclContext();\n  if (dc->isTypeContext()) {\n    if (!FD->isStatic()) {\n      TC.diagnose(FD->getLoc(), diag::nonstatic_operator_in_type,\n                  operatorName,\n                  dc->getDeclaredInterfaceType())\n        .fixItInsert(FD->getAttributeInsertionLoc(\/*forModifier=*\/true),\n                     \"static \");\n\n      FD->setStatic();\n    } else if (auto classDecl = dc->getSelfClassDecl()) {\n      \/\/ For a class, we also need the function or class to be 'final'.\n      if (!classDecl->isFinal() && !FD->isFinal() &&\n          FD->getStaticSpelling() != StaticSpellingKind::KeywordStatic) {\n        TC.diagnose(FD->getLoc(), diag::nonfinal_operator_in_class,\n                    operatorName, dc->getDeclaredInterfaceType())\n          .fixItInsert(FD->getAttributeInsertionLoc(\/*forModifier=*\/true),\n                       \"final \");\n        FD->getAttrs().add(new (TC.Context) FinalAttr(\/*IsImplicit=*\/true));\n      }\n    }\n  } else if (!dc->isModuleScopeContext()) {\n    TC.diagnose(FD, diag::operator_in_local_scope);\n  }\n\n  SourceFile &SF = *FD->getDeclContext()->getParentSourceFile();\n  if (FD->isUnaryOperator()) {\n    if (FD->getAttrs().hasAttribute<PrefixAttr>()) {\n      op = SF.lookupPrefixOperator(operatorName,\n                                   FD->isCascadingContextForLookup(false),\n                                   FD->getLoc());\n    } else if (FD->getAttrs().hasAttribute<PostfixAttr>()) {\n      op = SF.lookupPostfixOperator(operatorName,\n                                    FD->isCascadingContextForLookup(false),\n                                    FD->getLoc());\n    } else {\n      auto prefixOp =\n          SF.lookupPrefixOperator(operatorName,\n                                  FD->isCascadingContextForLookup(false),\n                                  FD->getLoc());\n      auto postfixOp =\n          SF.lookupPostfixOperator(operatorName,\n                                   FD->isCascadingContextForLookup(false),\n                                   FD->getLoc());\n\n      \/\/ If we found both prefix and postfix, or neither prefix nor postfix,\n      \/\/ complain. We can't fix this situation.\n      if (static_cast<bool>(prefixOp) == static_cast<bool>(postfixOp)) {\n        TC.diagnose(FD, diag::declared_unary_op_without_attribute);\n\n        \/\/ If we found both, point at them.\n        if (prefixOp) {\n          TC.diagnose(prefixOp, diag::unary_operator_declaration_here, false)\n            .fixItInsert(FD->getLoc(), \"prefix \");\n          TC.diagnose(postfixOp, diag::unary_operator_declaration_here, true)\n            .fixItInsert(FD->getLoc(), \"postfix \");\n        } else {\n          \/\/ FIXME: Introduce a Fix-It that adds the operator declaration?\n        }\n\n        \/\/ FIXME: Errors could cascade here, because name lookup for this\n        \/\/ operator won't find this declaration.\n        return;\n      }\n\n      \/\/ We found only one operator declaration, so we know whether this\n      \/\/ should be a prefix or a postfix operator.\n\n      \/\/ Fix the AST and determine the insertion text.\n      const char *insertionText;\n      auto &C = FD->getASTContext();\n      if (postfixOp) {\n        insertionText = \"postfix \";\n        op = postfixOp;\n        FD->getAttrs().add(new (C) PostfixAttr(\/*implicit*\/false));\n      } else {\n        insertionText = \"prefix \";\n        op = prefixOp;\n        FD->getAttrs().add(new (C) PrefixAttr(\/*implicit*\/false));\n      }\n\n      \/\/ Emit diagnostic with the Fix-It.\n      TC.diagnose(FD->getFuncLoc(), diag::unary_op_missing_prepos_attribute,\n                  static_cast<bool>(postfixOp))\n        .fixItInsert(FD->getFuncLoc(), insertionText);\n      TC.diagnose(op, diag::unary_operator_declaration_here,\n                  static_cast<bool>(postfixOp));\n    }\n  } else if (FD->isBinaryOperator()) {\n    op = SF.lookupInfixOperator(operatorName,\n                                FD->isCascadingContextForLookup(false),\n                                FD->getLoc());\n  } else {\n    TC.diagnose(FD, diag::invalid_arg_count_for_operator);\n    return;\n  }\n\n  if (!op) {\n    \/\/ FIXME: Add Fix-It introducing an operator declaration?\n    TC.diagnose(FD, diag::declared_operator_without_operator_decl);\n    return;\n  }\n\n  FD->setOperatorDecl(op);\n}\n\nbool swift::isMemberOperator(FuncDecl *decl, Type type) {\n  \/\/ Check that member operators reference the type of 'Self'.\n  if (decl->isInvalid())\n    return true;\n\n  auto *DC = decl->getDeclContext();\n  auto selfNominal = DC->getSelfNominalTypeDecl();\n\n  \/\/ Check the parameters for a reference to 'Self'.\n  bool isProtocol = selfNominal && isa<ProtocolDecl>(selfNominal);\n  for (auto param : *decl->getParameters()) {\n    auto paramType = param->getInterfaceType();\n    if (!paramType) break;\n\n    \/\/ Look through a metatype reference, if there is one.\n    paramType = paramType->getMetatypeInstanceType();\n\n    auto nominal = paramType->getAnyNominal();\n    if (type.isNull()) {\n      \/\/ Is it the same nominal type?\n      if (selfNominal && nominal == selfNominal)\n        return true;\n    } else {\n      \/\/ Is it the same nominal type? Or a generic (which may or may not match)?\n      if (paramType->is<GenericTypeParamType>() ||\n          nominal == type->getAnyNominal())\n        return true;\n    }\n\n    if (isProtocol) {\n      \/\/ For a protocol, is it the 'Self' type parameter?\n      if (auto genericParam = paramType->getAs<GenericTypeParamType>())\n        if (genericParam->isEqual(DC->getSelfInterfaceType()))\n          return true;\n    }\n  }\n\n  return false;\n}\n\nbool checkDynamicSelfReturn(FuncDecl *func,\n                            TypeRepr *typeRepr,\n                            unsigned optionalDepth) {\n  \/\/ Look through parentheses.\n  if (auto parenRepr = dyn_cast<TupleTypeRepr>(typeRepr)) {\n    if (!parenRepr->isParenType()) return false;\n    return checkDynamicSelfReturn(func, parenRepr->getElementType(0),\n                                  optionalDepth);\n  }\n\n  \/\/ Look through attributes.\n  if (auto attrRepr = dyn_cast<AttributedTypeRepr>(typeRepr)) {\n    TypeAttributes attrs = attrRepr->getAttrs();\n    if (!attrs.empty())\n      return false;\n    return checkDynamicSelfReturn(func, attrRepr->getTypeRepr(),\n                                  optionalDepth);\n\n  }\n\n  \/\/ Look through optional types.\n  TypeRepr *base = nullptr;\n  if (auto *optRepr = dyn_cast<OptionalTypeRepr>(typeRepr))\n    base = optRepr->getBase();\n  else if (auto *optRepr =\n               dyn_cast<ImplicitlyUnwrappedOptionalTypeRepr>(typeRepr))\n    base = optRepr->getBase();\n\n  if (base) {\n    \/\/ But only one level.\n    if (optionalDepth != 0) return false;\n    return checkDynamicSelfReturn(func, base, optionalDepth + 1);\n  }\n\n  \/\/ Check whether we have a simple identifier type.\n  auto simpleRepr = dyn_cast<SimpleIdentTypeRepr>(typeRepr);\n  if (!simpleRepr)\n    return false;\n\n  \/\/ Check whether it is 'Self'.\n  if (simpleRepr->getIdentifier() != func->getASTContext().Id_Self)\n    return false;\n\n  \/\/ Note that the function has a dynamic Self return type and set\n  \/\/ the return type component to the dynamic self type.\n  return true;\n}\n\n\/\/\/ Check for methods that return 'DynamicResult'.\nbool checkDynamicSelfReturn(FuncDecl *func) {\n  \/\/ Check whether we have a specified result type.\n  auto typeRepr = func->getBodyResultTypeLoc().getTypeRepr();\n  if (!typeRepr)\n    return false;\n\n  \/\/ 'Self' on a free function is not dynamic 'Self'.\n  if (!func->getDeclContext()->getSelfClassDecl() &&\n      !isa<ProtocolDecl>(func->getDeclContext()))\n    return false;\n\n  \/\/ 'Self' on a property accessor is not dynamic 'Self'...even on a read-only\n  \/\/ property. We could implement it as such in the future.\n  if (isa<AccessorDecl>(func))\n    return false;\n\n  return checkDynamicSelfReturn(func, typeRepr, 0);\n}\n\nType buildAddressorResultType(TypeChecker &TC,\n                              AccessorDecl *addressor,\n                              Type valueType) {\n  assert(addressor->getAccessorKind() == AccessorKind::Address ||\n         addressor->getAccessorKind() == AccessorKind::MutableAddress);\n\n  Type pointerType =\n    (addressor->getAccessorKind() == AccessorKind::Address)\n      ? TC.getUnsafePointerType(addressor->getLoc(), valueType)\n      : TC.getUnsafeMutablePointerType(addressor->getLoc(), valueType);\n  return pointerType;\n}\n\nstatic TypeLoc getTypeLocForFunctionResult(FuncDecl *FD) {\n  auto accessor = dyn_cast<AccessorDecl>(FD);\n  if (!accessor) {\n    return FD->getBodyResultTypeLoc();\n  }\n\n  assert(accessor->isGetter());\n  auto *storage = accessor->getStorage();\n  assert(isa<VarDecl>(storage) || isa<SubscriptDecl>(storage));\n\n  if (auto *subscript = dyn_cast<SubscriptDecl>(storage))\n    return subscript->getElementTypeLoc();\n\n  return cast<VarDecl>(storage)->getTypeLoc();\n}\n\nvoid TypeChecker::validateDecl(ValueDecl *D) {\n  \/\/ Generic parameters are validated as part of their context.\n  if (isa<GenericTypeParamDecl>(D))\n    return;\n\n  \/\/ Handling validation failure due to re-entrancy is left\n  \/\/ up to the caller, who must call hasValidSignature() to\n  \/\/ check that validateDecl() returned a fully-formed decl.\n  if (D->hasValidationStarted()) {\n    \/\/ If this isn't reentrant (i.e. D has already been validated), the\n    \/\/ signature better be valid.\n    assert(D->isBeingValidated() || D->hasValidSignature());\n    return;\n  }\n\n  \/\/ FIXME: It would be nicer if Sema would always synthesize fully-typechecked\n  \/\/ declarations, but for now, you can make an imported type conform to a\n  \/\/ protocol with property requirements, which requires synthesizing getters\n  \/\/ and setters, etc.\n  if (!isa<VarDecl>(D) && !isa<AccessorDecl>(D)) {\n    assert(isa<SourceFile>(D->getDeclContext()->getModuleScopeContext()) &&\n           \"Should not validate imported or deserialized declarations\");\n  }\n\n  PrettyStackTraceDecl StackTrace(\"validating\", D);\n  FrontendStatsTracer StatsTracer(Context.Stats, \"validate-decl\", D);\n\n  if (hasEnabledForbiddenTypecheckPrefix())\n    checkForForbiddenPrefix(D);\n\n  \/\/ Validate the context.\n  auto dc = D->getDeclContext();\n  if (auto nominal = dyn_cast<NominalTypeDecl>(dc)) {\n    validateDecl(nominal);\n    if (!nominal->hasValidSignature())\n      return;\n  } else if (auto ext = dyn_cast<ExtensionDecl>(dc)) {\n    validateExtension(ext);\n    if (!ext->hasValidSignature())\n      return;\n  }\n\n  \/\/ Validating the parent may have triggered validation of this declaration,\n  \/\/ so just return if that was the case.\n  if (D->hasValidationStarted()) {\n    assert(D->hasValidSignature());\n    return;\n  }\n\n  if (Context.Stats)\n    Context.Stats->getFrontendCounters().NumDeclsValidated++;\n\n  switch (D->getKind()) {\n  case DeclKind::Import:\n  case DeclKind::Extension:\n  case DeclKind::PatternBinding:\n  case DeclKind::EnumCase:\n  case DeclKind::TopLevelCode:\n  case DeclKind::InfixOperator:\n  case DeclKind::PrefixOperator:\n  case DeclKind::PostfixOperator:\n  case DeclKind::PrecedenceGroup:\n  case DeclKind::IfConfig:\n  case DeclKind::PoundDiagnostic:\n  case DeclKind::MissingMember:\n    llvm_unreachable(\"not a value decl\");\n\n  case DeclKind::Module:\n    return;\n      \n  case DeclKind::GenericTypeParam:\n    llvm_unreachable(\"handled above\");\n\n  case DeclKind::AssociatedType: {\n    auto assocType = cast<AssociatedTypeDecl>(D);\n\n    DeclValidationRAII IBV(assocType);\n\n    \/\/ Finally, set the interface type.\n    if (!assocType->hasInterfaceType())\n      assocType->computeType();\n\n    break;\n  }\n\n  case DeclKind::TypeAlias: {\n    auto typeAlias = cast<TypeAliasDecl>(D);\n    \/\/ Check generic parameters, if needed.\n    DeclValidationRAII IBV(typeAlias);\n\n    validateGenericTypeSignature(typeAlias);\n    validateTypealiasType(*this, typeAlias);\n    break;\n  }\n      \n  case DeclKind::OpaqueType: {\n    auto opaque = cast<OpaqueTypeDecl>(D);\n    DeclValidationRAII IBV(opaque);\n    validateGenericTypeSignature(opaque);\n    break;\n  }\n\n  case DeclKind::Enum:\n  case DeclKind::Struct:\n  case DeclKind::Class: {\n    auto nominal = cast<NominalTypeDecl>(D);\n    nominal->computeType();\n\n    \/\/ Check generic parameters, if needed.\n    DeclValidationRAII IBV(nominal);\n    validateGenericTypeSignature(nominal);\n    nominal->setSignatureIsValidated();\n\n    validateAttributes(*this, D);\n\n    if (auto CD = dyn_cast<ClassDecl>(nominal)) {\n      \/\/ Determine whether we require in-class initializers.\n      if (CD->getAttrs().hasAttribute<RequiresStoredPropertyInitsAttr>() ||\n          (CD->hasSuperclass() &&\n           CD->getSuperclassDecl()->requiresStoredPropertyInits()))\n        CD->setRequiresStoredPropertyInits(true);\n    }\n\n    if (auto *ED = dyn_cast<EnumDecl>(nominal)) {\n      \/\/ @objc enums use their raw values as the value representation, so we\n      \/\/ need to force the values to be checked.\n      if (ED->isObjC())\n        checkEnumRawValues(*this, ED);\n    }\n\n    if (!isa<ClassDecl>(nominal))\n      requestNominalLayout(nominal);\n\n    break;\n  }\n\n  case DeclKind::Protocol: {\n    auto proto = cast<ProtocolDecl>(D);\n    if (!proto->hasInterfaceType())\n      proto->computeType();\n\n    \/\/ Validate the generic type signature, which is just <Self : P>.\n    DeclValidationRAII IBV(proto);\n    validateGenericTypeSignature(proto);\n    proto->setSignatureIsValidated();\n\n    \/\/ See the comment in validateDeclForNameLookup(); we may have validated\n    \/\/ the alias before we built the protocol's generic environment.\n    \/\/\n    \/\/ FIXME: Hopefully this can all go away with the ITC.\n    for (auto member : proto->getMembers()) {\n      if (auto *aliasDecl = dyn_cast<TypeAliasDecl>(member)) {\n        if (!aliasDecl->isGeneric()) {\n          aliasDecl->setGenericEnvironment(proto->getGenericEnvironment());\n\n          \/\/ The generic environment didn't exist until now, we may have\n          \/\/ unresolved types we will need to deal with, and need to record the\n          \/\/ appropriate substitutions for that environment. Wipe out the types\n          \/\/ and validate them again.\n          aliasDecl->getUnderlyingTypeLoc().setType(Type());\n          aliasDecl->setInterfaceType(Type());\n\n          \/\/ Check generic parameters, if needed.\n          if (aliasDecl->hasValidationStarted()) {\n            validateTypealiasType(*this, aliasDecl);\n          } else {\n            DeclValidationRAII IBV(aliasDecl);\n            validateTypealiasType(*this, aliasDecl);\n          }\n        }\n      }\n    }\n\n    validateAttributes(*this, D);\n\n    \/\/ FIXME: IRGen likes to emit @objc protocol descriptors even if the\n    \/\/ protocol comes from a different module or translation unit.\n    \/\/\n    \/\/ It would be nice if it didn't have to do that, then we could remove\n    \/\/ this case.\n    if (proto->isObjC())\n      requestNominalLayout(proto);\n\n    break;\n  }\n\n  case DeclKind::Param: {\n    auto *PD = cast<ParamDecl>(D);\n    if (!PD->hasInterfaceType()) {\n      \/\/ Can't fallthough because parameter without a type doesn't have\n      \/\/ valid signature, but that shouldn't matter anyway.\n      return;\n    }\n\n    auto type = PD->getInterfaceType();\n    if (type->hasError())\n      PD->markInvalid();\n    break;\n  }\n\n  case DeclKind::Var: {\n    auto *VD = cast<VarDecl>(D);\n    auto *PBD = VD->getParentPatternBinding();\n\n    \/\/ Note that we need to handle the fact that some VarDecls don't\n    \/\/ have a PatternBindingDecl, for example the iterator in a\n    \/\/ 'for ... in ...' loop.\n    if (PBD == nullptr) {\n      if (!VD->hasInterfaceType()) {\n        VD->setValidationToChecked();\n        VD->markInvalid();\n      }\n\n      break;\n    }\n\n    \/\/ If we're already checking our PatternBindingDecl, bail out\n    \/\/ without setting our own 'is being validated' flag, since we\n    \/\/ will attempt validation again later.\n    if (PBD->isBeingValidated())\n      return;\n\n    DeclValidationRAII IBV(D);\n\n    if (!VD->hasInterfaceType()) {\n      \/\/ Attempt to infer the type using initializer expressions.\n      validatePatternBindingEntries(*this, PBD);\n\n      auto parentPattern = VD->getParentPattern();\n      if (PBD->isInvalid() || !parentPattern->hasType()) {\n        parentPattern->setType(ErrorType::get(Context));\n        setBoundVarsTypeError(parentPattern, Context);\n      }\n\n      \/\/ Should have set a type above.\n      assert(VD->hasInterfaceType());\n    }\n\n    \/\/ We're not really done with processing the signature yet, but\n    \/\/ @objc checking requires the declaration to call itself validated\n    \/\/ so that it can be considered as a witness.\n    D->setSignatureIsValidated();\n\n    checkDeclAttributesEarly(VD);\n    validateAttributes(*this, VD);\n\n    \/\/ Perform accessor-related validation.\n    validateAbstractStorageDecl(*this, VD);\n\n    break;\n  }\n\n  case DeclKind::Func:\n  case DeclKind::Accessor: {\n    auto *FD = cast<FuncDecl>(D);\n    assert(!FD->hasInterfaceType());\n\n    \/\/ Bail out if we're in a recursive validation situation.\n    if (auto accessor = dyn_cast<AccessorDecl>(FD)) {\n      auto *storage = accessor->getStorage();\n      validateDecl(storage);\n      if (!storage->hasValidSignature())\n        return;\n    }\n\n    checkDeclAttributesEarly(FD);\n\n    DeclValidationRAII IBV(FD);\n\n    \/\/ Bind operator functions to the corresponding operator declaration.\n    if (FD->isOperator())\n      bindFuncDeclToOperator(*this, FD);\n\n    \/\/ Validate 'static'\/'class' on functions in extensions.\n    auto StaticSpelling = FD->getStaticSpelling();\n    if (StaticSpelling != StaticSpellingKind::None &&\n        isa<ExtensionDecl>(FD->getDeclContext())) {\n      if (auto *NTD = FD->getDeclContext()->getSelfNominalTypeDecl()) {\n        if (!isa<ClassDecl>(NTD)) {\n          if (StaticSpelling == StaticSpellingKind::KeywordClass) {\n            diagnose(FD, diag::class_func_not_in_class, false)\n                .fixItReplace(FD->getStaticLoc(), \"static\");\n            diagnose(NTD, diag::extended_type_declared_here);\n          }\n        }\n      }\n    }\n\n    validateSelfAccessKind(*this, FD);\n\n    \/\/ Check whether the return type is dynamic 'Self'.\n    FD->setDynamicSelf(checkDynamicSelfReturn(FD));\n\n    \/\/ Accessors should pick up various parts of their type signatures\n    \/\/ directly from the storage declaration instead of re-deriving them.\n    \/\/ FIXME: should this include the generic signature?\n    if (auto accessor = dyn_cast<AccessorDecl>(FD)) {\n      auto storage = accessor->getStorage();\n\n      \/\/ Note that it's important for correctness that we're filling in\n      \/\/ empty TypeLocs, because otherwise revertGenericFuncSignature might\n      \/\/ erase the types we set, causing them to be re-validated in a later\n      \/\/ pass.  That later validation might be incorrect even if the TypeLocs\n      \/\/ are a clone of the type locs from which we derived the value type,\n      \/\/ because the rules for interpreting types in parameter contexts\n      \/\/ are sometimes different from the rules elsewhere; for example,\n      \/\/ function types default to non-escaping.\n\n      auto valueParams = accessor->getParameters();\n\n      \/\/ Determine the value type.\n      Type valueIfaceTy = storage->getValueInterfaceType();\n      if (auto SD = dyn_cast<SubscriptDecl>(storage)) {\n        \/\/ Copy the index types instead of re-validating them.\n        auto indices = SD->getIndices();\n        for (size_t i = 0, e = indices->size(); i != e; ++i) {\n          auto subscriptParam = indices->get(i);\n          if (!subscriptParam->hasInterfaceType())\n            continue;\n\n          Type paramIfaceTy = subscriptParam->getInterfaceType();\n\n          auto accessorParam = valueParams->get(valueParams->size() - e + i);\n          accessorParam->setInterfaceType(paramIfaceTy);\n          accessorParam->getTypeLoc().setType(paramIfaceTy);\n        }\n      }\n\n      \/\/ Propagate the value type into the correct position.\n      switch (accessor->getAccessorKind()) {\n      \/\/ For getters, set the result type to the value type.\n      case AccessorKind::Get:\n        accessor->getBodyResultTypeLoc().setType(valueIfaceTy);\n        break;\n\n      \/\/ For setters and observers, set the old\/new value parameter's type\n      \/\/ to the value type.\n      case AccessorKind::DidSet:\n      case AccessorKind::WillSet:\n      case AccessorKind::Set: {\n        auto newValueParam = valueParams->get(0);\n        newValueParam->setInterfaceType(valueIfaceTy);\n        newValueParam->getTypeLoc().setType(valueIfaceTy);\n        break;\n      }\n\n      \/\/ Addressor result types can get complicated because of the owner.\n      case AccessorKind::Address:\n      case AccessorKind::MutableAddress:\n        if (Type resultType =\n              buildAddressorResultType(*this, accessor, valueIfaceTy)) {\n          accessor->getBodyResultTypeLoc().setType(resultType);\n        }\n        break;\n\n      \/\/ These don't mention the value type directly.\n      \/\/ If we add yield types to the function type, we'll need to update this.\n      case AccessorKind::Read:\n      case AccessorKind::Modify:\n        break;\n      }\n    }\n\n    validateGenericFuncOrSubscriptSignature(FD, FD, FD);\n    \n    if (!isa<AccessorDecl>(FD) || cast<AccessorDecl>(FD)->isGetter()) {\n      auto *TyR = getTypeLocForFunctionResult(FD).getTypeRepr();\n      if (TyR && TyR->getKind() == TypeReprKind::ImplicitlyUnwrappedOptional) {\n        auto &C = FD->getASTContext();\n        FD->getAttrs().add(\n            new (C) ImplicitlyUnwrappedOptionalAttr(\/* implicit= *\/ true));\n      }\n    }\n\n    \/\/ We want the function to be available for name lookup as soon\n    \/\/ as it has a valid interface type.\n    FD->setSignatureIsValidated();\n\n    if (FD->isInvalid())\n      break;\n\n    validateAttributes(*this, FD);\n\n    \/\/ Member functions need some special validation logic.\n    if (FD->getDeclContext()->isTypeContext()) {\n      if (FD->isOperator() && !isMemberOperator(FD, nullptr)) {\n        auto selfNominal = FD->getDeclContext()->getSelfNominalTypeDecl();\n        auto isProtocol = selfNominal && isa<ProtocolDecl>(selfNominal);\n        \/\/ We did not find 'Self'. Complain.\n        diagnose(FD, diag::operator_in_unrelated_type,\n                 FD->getDeclContext()->getDeclaredInterfaceType(), isProtocol,\n                 FD->getFullName());\n      }\n    }\n\n    \/\/ If the function is exported to C, it must be representable in (Obj-)C.\n    if (auto CDeclAttr = FD->getAttrs().getAttribute<swift::CDeclAttr>()) {\n      Optional<ForeignErrorConvention> errorConvention;\n      if (isRepresentableInObjC(FD, ObjCReason::ExplicitlyCDecl,\n                                errorConvention)) {\n        if (FD->hasThrows()) {\n          FD->setForeignErrorConvention(*errorConvention);\n          diagnose(CDeclAttr->getLocation(), diag::cdecl_throws);\n        }\n      }\n    }\n\n    checkDeclAttributes(FD);\n\n    \/\/ Mark the opaque result type as validated, if there is one.\n    if (FD->getOpaqueResultTypeDecl()) {\n      if (auto sf = FD->getDeclContext()->getParentSourceFile()) {\n        sf->markDeclWithOpaqueResultTypeAsValidated(FD);\n      }\n    }\n    \n    break;\n  }\n\n  case DeclKind::Constructor: {\n    auto *CD = cast<ConstructorDecl>(D);\n\n    DeclValidationRAII IBV(CD);\n\n    checkDeclAttributesEarly(CD);\n\n    \/\/ convenience initializers are only allowed on classes and in\n    \/\/ extensions thereof.\n    if (CD->isConvenienceInit()) {\n      if (auto extType = CD->getDeclContext()->getDeclaredInterfaceType()) {\n        auto extClass = extType->getClassOrBoundGenericClass();\n\n        \/\/ Forbid convenience inits on Foreign CF types, as Swift does not yet\n        \/\/ support user-defined factory inits.\n        if (extClass &&\n            extClass->getForeignClassKind() == ClassDecl::ForeignKind::CFType) {\n          diagnose(CD->getLoc(), diag::cfclass_convenience_init);\n        }\n\n        if (!extClass && !extType->hasError()) {\n          auto ConvenienceLoc =\n            CD->getAttrs().getAttribute<ConvenienceAttr>()->getLocation();\n\n          \/\/ Produce a tailored diagnostic for structs and enums.\n          bool isStruct = extType->getStructOrBoundGenericStruct() != nullptr;\n          if (isStruct || extType->getEnumOrBoundGenericEnum()) {\n            diagnose(CD->getLoc(), diag::enumstruct_convenience_init,\n                     isStruct ? \"structs\" : \"enums\")\n              .fixItRemove(ConvenienceLoc);\n          } else {\n            diagnose(CD->getLoc(), diag::nonclass_convenience_init, extType)\n              .fixItRemove(ConvenienceLoc);\n          }\n          CD->setInitKind(CtorInitializerKind::Designated);\n        }\n      }\n    } else if (auto extType = CD->getDeclContext()->getDeclaredInterfaceType()) {\n      \/\/ A designated initializer for a class must be written within the class\n      \/\/ itself.\n      \/\/\n      \/\/ This is because designated initializers of classes get a vtable entry,\n      \/\/ and extensions cannot add vtable entries to the extended type.\n      \/\/\n      \/\/ If we implement the ability for extensions defined in the same module\n      \/\/ (or the same file) to add vtable entries, we can re-evaluate this\n      \/\/ restriction.\n      if (extType->getClassOrBoundGenericClass() &&\n          isa<ExtensionDecl>(CD->getDeclContext()) &&\n          !(CD->getAttrs().hasAttribute<DynamicReplacementAttr>())) {\n        diagnose(CD->getLoc(), diag::designated_init_in_extension, extType)\n          .fixItInsert(CD->getLoc(), \"convenience \");\n        CD->setInitKind(CtorInitializerKind::Convenience);\n      } else if (CD->getDeclContext()->getExtendedProtocolDecl()) {\n        CD->setInitKind(CtorInitializerKind::Convenience);\n      }\n    }\n\n    validateGenericFuncOrSubscriptSignature(CD, CD, CD);\n\n    \/\/ We want the constructor to be available for name lookup as soon\n    \/\/ as it has a valid interface type.\n    CD->setSignatureIsValidated();\n\n    validateAttributes(*this, CD);\n\n    if (CD->getFailability() == OTK_ImplicitlyUnwrappedOptional) {\n      auto &C = CD->getASTContext();\n      CD->getAttrs().add(\n          new (C) ImplicitlyUnwrappedOptionalAttr(\/* implicit= *\/ true));\n    }\n\n    break;\n  }\n\n  case DeclKind::Destructor: {\n    auto *DD = cast<DestructorDecl>(D);\n\n    DeclValidationRAII IBV(DD);\n\n    checkDeclAttributesEarly(DD);\n\n    validateGenericFuncOrSubscriptSignature(DD, DD, DD);\n\n    DD->setSignatureIsValidated();\n\n    validateAttributes(*this, DD);\n    break;\n  }\n\n  case DeclKind::Subscript: {\n    auto *SD = cast<SubscriptDecl>(D);\n\n    DeclValidationRAII IBV(SD);\n\n    validateGenericFuncOrSubscriptSignature(SD, SD, SD);\n\n    SD->setSignatureIsValidated();\n\n    checkDeclAttributesEarly(SD);\n\n    validateAttributes(*this, SD);\n\n    auto *TyR = SD->getElementTypeLoc().getTypeRepr();\n    if (TyR && TyR->getKind() == TypeReprKind::ImplicitlyUnwrappedOptional) {\n      auto &C = SD->getASTContext();\n      SD->getAttrs().add(\n          new (C) ImplicitlyUnwrappedOptionalAttr(\/* implicit= *\/ true));\n    }\n\n    \/\/ Perform accessor-related validation.\n    validateAbstractStorageDecl(*this, SD);\n\n    break;\n  }\n\n  case DeclKind::EnumElement: {\n    auto *EED = cast<EnumElementDecl>(D);\n    EnumDecl *ED = EED->getParentEnum();\n\n    validateAttributes(*this, EED);\n\n    DeclValidationRAII IBV(EED);\n\n    if (auto *PL = EED->getParameterList()) {\n      typeCheckParameterList(PL,\n                             TypeResolution::forInterface(\n                                                    EED->getParentEnum(),\n                                                    ED->getGenericSignature()),\n                             TypeResolverContext::EnumElementDecl);\n    }\n\n    \/\/ If we have a raw value, make sure there's a raw type as well.\n    if (auto *rawValue = EED->getRawValueExpr()) {\n      if (!ED->hasRawType()) {\n        diagnose(rawValue->getLoc(),diag::enum_raw_value_without_raw_type);\n        \/\/ Recover by setting the raw type as this element's type.\n        Expr *typeCheckedExpr = rawValue;\n        if (!typeCheckExpression(typeCheckedExpr, ED)) {\n          EED->setTypeCheckedRawValueExpr(typeCheckedExpr);\n          checkEnumElementErrorHandling(EED);\n        }\n      } else {\n        \/\/ Wait until the second pass, when all the raw value expressions\n        \/\/ can be checked together.\n      }\n    }\n\n    \/\/ Now that we have an argument type we can set the element's declared\n    \/\/ type.\n    EED->computeType();\n\n    EED->setSignatureIsValidated();\n\n    if (auto argTy = EED->getArgumentInterfaceType()) {\n      assert(argTy->isMaterializable());\n      (void) argTy;\n    }\n\n    break;\n  }\n  }\n\n  assert(D->hasValidSignature());\n}\n\nvoid TypeChecker::validateDeclForNameLookup(ValueDecl *D) {\n  \/\/ Validate the context.\n  auto dc = D->getDeclContext();\n  if (auto nominal = dyn_cast<NominalTypeDecl>(dc)) {\n    validateDeclForNameLookup(nominal);\n    if (!nominal->hasInterfaceType())\n      return;\n  } else if (auto ext = dyn_cast<ExtensionDecl>(dc)) {\n    validateExtension(ext);\n    if (!ext->hasValidSignature())\n      return;\n  }\n\n  switch (D->getKind()) {\n  case DeclKind::Protocol: {\n    auto proto = cast<ProtocolDecl>(D);\n    if (proto->hasInterfaceType())\n      return;\n    proto->computeType();\n\n    \/\/ FIXME: IRGen likes to emit @objc protocol descriptors even if the\n    \/\/ protocol comes from a different module or translation unit.\n    \/\/\n    \/\/ It would be nice if it didn't have to do that, then we could remove\n    \/\/ this case.\n    if (proto->isObjC())\n      requestNominalLayout(proto);\n\n    break;\n  }\n  case DeclKind::AssociatedType: {\n    auto assocType = cast<AssociatedTypeDecl>(D);\n    if (assocType->hasInterfaceType())\n      return;\n    assocType->computeType();\n    break;\n  }\n  case DeclKind::TypeAlias: {\n    auto typealias = cast<TypeAliasDecl>(D);\n    if (typealias->getUnderlyingTypeLoc().getType())\n      return;\n\n    \/\/ Perform earlier validation of typealiases in protocols.\n    if (isa<ProtocolDecl>(dc)) {\n      if (!typealias->getGenericParams()) {\n        if (typealias->isBeingValidated()) return;\n\n        auto helper = [&] {\n          TypeResolutionOptions options(\n            (typealias->getGenericParams() ?\n             TypeResolverContext::GenericTypeAliasDecl :\n             TypeResolverContext::TypeAliasDecl));\n          if (validateType(typealias->getUnderlyingTypeLoc(),\n                           TypeResolution::forStructural(typealias), options)) {\n            typealias->setInvalid();\n            typealias->getUnderlyingTypeLoc().setInvalidType(Context);\n          }\n\n          typealias->setUnderlyingType(\n                                  typealias->getUnderlyingTypeLoc().getType());\n\n          \/\/ Note that this doesn't set the generic environment of the alias yet,\n          \/\/ because we haven't built one for the protocol.\n          \/\/\n          \/\/ See how validateDecl() sets the generic environment on alias members\n          \/\/ explicitly.\n          \/\/\n          \/\/ FIXME: Hopefully this can all go away with the ITC.\n        };\n\n        if (typealias->hasValidationStarted()) {\n          helper();\n        } else {\n          DeclValidationRAII IBV(typealias);\n          helper();\n        }\n\n        return;\n      }\n    }\n    LLVM_FALLTHROUGH;\n  }\n\n  default:\n    validateDecl(D);\n    break;\n  }\n}\n\nstatic bool shouldValidateMemberDuringFinalization(NominalTypeDecl *nominal,\n                                                   ValueDecl *VD) {\n  \/\/ For enums, we only need to validate enum elements to know\n  \/\/ the layout.\n  if (isa<EnumDecl>(nominal) &&\n      isa<EnumElementDecl>(VD))\n    return true;\n\n  \/\/ For structs, we only need to validate stored properties to\n  \/\/ know the layout.\n  if (isa<StructDecl>(nominal) &&\n      (isa<VarDecl>(VD) &&\n       !cast<VarDecl>(VD)->isStatic() &&\n       (cast<VarDecl>(VD)->hasStorage() ||\n        VD->getAttrs().hasAttribute<LazyAttr>() ||\n        cast<VarDecl>(VD)->getAttachedPropertyWrapper())))\n    return true;\n\n  \/\/ For classes, we need to validate properties and functions,\n  \/\/ but skipping nested types is OK.\n  if (isa<ClassDecl>(nominal) &&\n      !isa<TypeDecl>(VD))\n    return true;\n\n  \/\/ For protocols, skip nested typealiases and nominal types.\n  if (isa<ProtocolDecl>(nominal) &&\n      !isa<GenericTypeDecl>(VD))\n    return true;\n\n  return false;\n}\n\nvoid TypeChecker::requestMemberLayout(ValueDecl *member) {\n  auto *dc = member->getDeclContext();\n  if (auto *classDecl = dyn_cast<ClassDecl>(dc))\n    requestNominalLayout(classDecl);\n  if (auto *protocolDecl = dyn_cast<ProtocolDecl>(dc))\n    requestNominalLayout(protocolDecl);\n\n  if (auto ext = dyn_cast<ExtensionDecl>(dc)) {\n    if (ext->getSelfClassDecl()) {\n      \/\/ Finalize members of class extensions, to ensure we compute their\n      \/\/ @objc and dynamic state.\n      DeclsToFinalize.insert(member);\n    }\n  }\n\n  \/\/ If this represents (abstract) storage, form the appropriate accessors.\n  if (auto storage = dyn_cast<AbstractStorageDecl>(member)) {\n    validateAbstractStorageDecl(*this, storage);\n\n    \/\/ Request layout of the accessors for an @objc declaration.\n    \/\/ We can't delay validation of getters and setters on @objc properties,\n    \/\/ because if they never get validated at all then conformance checkers\n    \/\/ will complain about selector mismatches.\n    if (storage->isObjC()) {\n      maybeAddAccessorsToStorage(storage);\n      for (auto accessor : storage->getAllAccessors()) {\n        requestMemberLayout(accessor);\n      }\n    }\n  }\n}\n\nvoid TypeChecker::requestNominalLayout(NominalTypeDecl *nominalDecl) {\n  if (isa<SourceFile>(nominalDecl->getModuleScopeContext()))\n    DeclsToFinalize.insert(nominalDecl);\n}\n\nvoid TypeChecker::requestSuperclassLayout(ClassDecl *classDecl) {\n  if (auto *superclassDecl = classDecl->getSuperclassDecl()) {\n    if (superclassDecl)\n      requestNominalLayout(superclassDecl);\n  }\n}\n\n\/\/\/ \"Finalize\" the type so that SILGen can make copies of it, call\n\/\/\/ methods on it, etc. This requires forcing enough computation so\n\/\/\/ that (for example) a class can layout its vtable or a struct can\n\/\/\/ be laid out in memory.\nstatic void finalizeType(TypeChecker &TC, NominalTypeDecl *nominal) {\n  assert(!nominal->hasClangNode());\n  assert(isa<SourceFile>(nominal->getModuleScopeContext()));\n\n  if (auto *CD = dyn_cast<ClassDecl>(nominal)) {\n    \/\/ We need to add implicit initializers and dtors because it\n    \/\/ affects vtable layout.\n    TC.addImplicitConstructors(CD);\n    CD->addImplicitDestructor();\n  }\n\n  for (auto *D : nominal->getMembers()) {\n    auto VD = dyn_cast<ValueDecl>(D);\n    if (!VD)\n      continue;\n\n    if (!shouldValidateMemberDuringFinalization(nominal, VD))\n      continue;\n\n    TC.DeclsToFinalize.insert(VD);\n\n    \/\/ The only thing left to do is synthesize storage for lazy variables.\n    auto *prop = dyn_cast<VarDecl>(D);\n    if (!prop)\n      continue;\n\n    if (prop->getAttrs().hasAttribute<LazyAttr>() && !prop->isStatic() &&\n        (!prop->getGetter() || !prop->getGetter()->hasBody())) {\n      finalizeAbstractStorageDecl(TC, prop);\n      completeLazyVarImplementation(prop);\n    }\n\n    \/\/ Ensure that we create the backing variable for a property wrapper.\n    if (prop->getAttachedPropertyWrapper()) {\n      finalizeAbstractStorageDecl(TC, prop);\n      (void)prop->getPropertyWrapperBackingProperty();\n    }\n  }\n\n  if (auto *CD = dyn_cast<ClassDecl>(nominal)) {\n    \/\/ We need the superclass vtable layout as well.\n    TC.requestSuperclassLayout(CD);\n\n    auto forceConformance = [&](ProtocolDecl *protocol) {\n      if (auto ref = TypeChecker::conformsToProtocol(\n            CD->getDeclaredInterfaceType(), protocol, CD,\n            ConformanceCheckFlags::SkipConditionalRequirements,\n            SourceLoc())) {\n        auto conformance = ref->getConcrete();\n        if (conformance->getDeclContext() == CD &&\n            conformance->getState() == ProtocolConformanceState::Incomplete) {\n          TC.checkConformance(conformance->getRootNormalConformance());\n        }\n      }\n    };\n\n    \/\/ If the class is Encodable, Decodable or Hashable, force those\n    \/\/ conformances to ensure that the synthesized members appear in the vtable.\n    \/\/\n    \/\/ FIXME: Generalize this to other protocols for which\n    \/\/ we can derive conformances.\n    forceConformance(TC.Context.getProtocol(KnownProtocolKind::Decodable));\n    forceConformance(TC.Context.getProtocol(KnownProtocolKind::Encodable));\n    forceConformance(TC.Context.getProtocol(KnownProtocolKind::Hashable));\n  }\n\n  \/\/ validateDeclForNameLookup will not trigger an immediate full\n  \/\/ validation of protocols, but clients will assume that things\n  \/\/ like the requirement signature have been set.\n  if (auto PD = dyn_cast<ProtocolDecl>(nominal)) {\n    (void)PD->getInheritedProtocols();\n    TC.validateDecl(PD);\n  }\n}\n\nvoid TypeChecker::finalizeDecl(ValueDecl *decl) {\n  if (Context.Stats)\n    Context.Stats->getFrontendCounters().NumDeclsFinalized++;\n\n  validateDecl(decl);\n\n  if (auto nominal = dyn_cast<NominalTypeDecl>(decl)) {\n    finalizeType(*this, nominal);\n  } else if (auto storage = dyn_cast<AbstractStorageDecl>(decl)) {\n    finalizeAbstractStorageDecl(*this, storage);\n  }\n\n  \/\/ Compute access level.\n  (void)decl->getFormalAccess();\n\n  \/\/ Compute overrides.\n  (void)decl->getOverriddenDecls();\n\n  \/\/ Check whether the member is @objc or dynamic.\n  (void)decl->isObjC();\n  (void)decl->isDynamic();\n}\n\n\/\/\/ Determine whether this is a \"pass-through\" typealias, which has the\n\/\/\/ same type parameters as the nominal type it references and specializes\n\/\/\/ the underlying nominal type with exactly those type parameters.\n\/\/\/ For example, the following typealias \\c GX is a pass-through typealias:\n\/\/\/\n\/\/\/ \\code\n\/\/\/ struct X<T, U> { }\n\/\/\/ typealias GX<A, B> = X<A, B>\n\/\/\/ \\endcode\n\/\/\/\n\/\/\/ whereas \\c GX2 and \\c GX3 are not pass-through because \\c GX2 has\n\/\/\/ different type parameters and \\c GX3 doesn't pass its type parameters\n\/\/\/ directly through.\n\/\/\/\n\/\/\/ \\code\n\/\/\/ typealias GX2<A> = X<A, A>\n\/\/\/ typealias GX3<A, B> = X<B, A>\n\/\/\/ \\endcode\nstatic bool isPassThroughTypealias(TypeAliasDecl *typealias) {\n  \/\/ Pass-through only makes sense when the typealias refers to a nominal\n  \/\/ type.\n  Type underlyingType = typealias->getUnderlyingTypeLoc().getType();\n  auto nominal = underlyingType->getAnyNominal();\n  if (!nominal) return false;\n\n  \/\/ Check that the nominal type and the typealias are either both generic\n  \/\/ at this level or neither are.\n  if (nominal->isGeneric() != typealias->isGeneric())\n    return false;\n\n  \/\/ Make sure either both have generic signatures or neither do.\n  auto nominalSig = nominal->getGenericSignature();\n  auto typealiasSig = typealias->getGenericSignature();\n  if (static_cast<bool>(nominalSig) != static_cast<bool>(typealiasSig))\n    return false;\n\n  \/\/ If neither is generic, we're done: it's a pass-through alias.\n  if (!nominalSig) return true;\n\n  \/\/ Check that the type parameters are the same the whole way through.\n  auto nominalGenericParams = nominalSig->getGenericParams();\n  auto typealiasGenericParams = typealiasSig->getGenericParams();\n  if (nominalGenericParams.size() != typealiasGenericParams.size())\n    return false;\n  if (!std::equal(nominalGenericParams.begin(), nominalGenericParams.end(),\n                  typealiasGenericParams.begin(),\n                  [](GenericTypeParamType *gp1, GenericTypeParamType *gp2) {\n                    return gp1->isEqual(gp2);\n                  }))\n    return false;\n\n  \/\/ If neither is generic at this level, we have a pass-through typealias.\n  if (!typealias->isGeneric()) return true;\n\n  auto boundGenericType = underlyingType->getAs<BoundGenericType>();\n  if (!boundGenericType) return false;\n\n  \/\/ If our arguments line up with our innermost generic parameters, it's\n  \/\/ a passthrough typealias.\n  auto innermostGenericParams = typealiasSig->getInnermostGenericParams();\n  auto boundArgs = boundGenericType->getGenericArgs();\n  if (boundArgs.size() != innermostGenericParams.size())\n    return false;\n\n  return std::equal(boundArgs.begin(), boundArgs.end(),\n                    innermostGenericParams.begin(),\n                    [](Type arg, GenericTypeParamType *gp) {\n                      return arg->isEqual(gp);\n                    });\n}\n\n\/\/\/ Form the interface type of an extension from the raw type and the\n\/\/\/ extension's list of generic parameters.\nstatic Type formExtensionInterfaceType(\n                         TypeChecker &tc, ExtensionDecl *ext,\n                         Type type,\n                         GenericParamList *genericParams,\n                         SmallVectorImpl<std::pair<Type, Type>> &sameTypeReqs,\n                         bool &mustInferRequirements) {\n  if (type->is<ErrorType>())\n    return type;\n\n  \/\/ Find the nominal type declaration and its parent type.\n  if (type->is<ProtocolCompositionType>())\n    type = type->getCanonicalType();\n\n  Type parentType = type->getNominalParent();\n  GenericTypeDecl *genericDecl = type->getAnyGeneric();\n\n  \/\/ Reconstruct the parent, if there is one.\n  if (parentType) {\n    \/\/ Build the nested extension type.\n    auto parentGenericParams = genericDecl->getGenericParams()\n                                 ? genericParams->getOuterParameters()\n                                 : genericParams;\n    parentType =\n      formExtensionInterfaceType(tc, ext, parentType, parentGenericParams,\n                                 sameTypeReqs, mustInferRequirements);\n  }\n\n  \/\/ Find the nominal type.\n  auto nominal = dyn_cast<NominalTypeDecl>(genericDecl);\n  auto typealias = dyn_cast<TypeAliasDecl>(genericDecl);\n  if (!nominal) {\n    Type underlyingType = typealias->getUnderlyingTypeLoc().getType();\n    nominal = underlyingType->getNominalOrBoundGenericNominal();\n  }\n\n  \/\/ Form the result.\n  Type resultType;\n  SmallVector<Type, 2> genericArgs;\n  if (!nominal->isGeneric() || isa<ProtocolDecl>(nominal)) {\n    resultType = NominalType::get(nominal, parentType,\n                                  nominal->getASTContext());\n  } else {\n    auto currentBoundType = type->getAs<BoundGenericType>();\n\n    \/\/ Form the bound generic type with the type parameters provided.\n    unsigned gpIndex = 0;\n    for (auto gp : *genericParams) {\n      SWIFT_DEFER { ++gpIndex; };\n\n      auto gpType = gp->getDeclaredInterfaceType();\n      genericArgs.push_back(gpType);\n\n      if (currentBoundType) {\n        sameTypeReqs.push_back({gpType,\n                                currentBoundType->getGenericArgs()[gpIndex]});\n      }\n    }\n\n    resultType = BoundGenericType::get(nominal, parentType, genericArgs);\n  }\n\n  \/\/ If we have a typealias, try to form type sugar.\n  if (typealias && isPassThroughTypealias(typealias)) {\n    auto typealiasSig = typealias->getGenericSignature();\n    SubstitutionMap subMap;\n    if (typealiasSig) {\n      subMap = typealiasSig->getIdentitySubstitutionMap();\n\n      mustInferRequirements = true;\n    }\n\n    resultType = TypeAliasType::get(typealias, parentType, subMap,\n                                    resultType);\n  }\n\n  return resultType;\n}\n\n\/\/\/ Check the generic parameters of an extension, recursively handling all of\n\/\/\/ the parameter lists within the extension.\nstatic std::pair<GenericEnvironment *, Type>\ncheckExtensionGenericParams(TypeChecker &tc, ExtensionDecl *ext, Type type,\n                            GenericParamList *genericParams) {\n  assert(!ext->getGenericEnvironment());\n\n  \/\/ Form the interface type of the extension.\n  bool mustInferRequirements = false;\n  SmallVector<std::pair<Type, Type>, 4> sameTypeReqs;\n  Type extInterfaceType =\n    formExtensionInterfaceType(tc, ext, type, genericParams, sameTypeReqs,\n                               mustInferRequirements);\n\n  \/\/ Local function used to infer requirements from the extended type.\n  auto inferExtendedTypeReqs = [&](GenericSignatureBuilder &builder) {\n    auto source =\n      GenericSignatureBuilder::FloatingRequirementSource::forInferred(nullptr);\n\n    builder.inferRequirements(*ext->getModuleContext(),\n                              extInterfaceType,\n                              nullptr,\n                              source);\n\n    for (const auto &sameTypeReq : sameTypeReqs) {\n      builder.addRequirement(\n        Requirement(RequirementKind::SameType, sameTypeReq.first,\n                    sameTypeReq.second),\n        source, ext->getModuleContext());\n    }\n  };\n\n  \/\/ Validate the generic type signature.\n  auto *env = tc.checkGenericEnvironment(genericParams,\n                                         ext->getDeclContext(), nullptr,\n                                         \/*allowConcreteGenericParams=*\/true,\n                                         ext, inferExtendedTypeReqs,\n                                         (mustInferRequirements ||\n                                            !sameTypeReqs.empty()));\n\n  return { env, extInterfaceType };\n}\n\nstatic bool isNonGenericTypeAliasType(Type type) {\n  \/\/ A non-generic typealias can extend a specialized type.\n  if (auto *aliasType = dyn_cast<TypeAliasType>(type.getPointer()))\n    return aliasType->getDecl()->getGenericContextDepth() == (unsigned)-1;\n\n  return false;\n}\n\nstatic void validateExtendedType(ExtensionDecl *ext, TypeChecker &tc) {\n  \/\/ If we didn't parse a type, fill in an error type and bail out.\n  if (!ext->getExtendedTypeLoc().getTypeRepr()) {\n    ext->setInvalid();\n    ext->getExtendedTypeLoc().setInvalidType(tc.Context);\n    return;\n  }\n\n  \/\/ Validate the extended type.\n  TypeResolutionOptions options(TypeResolverContext::ExtensionBinding);\n  options |= TypeResolutionFlags::AllowUnboundGenerics;\n  if (tc.validateType(ext->getExtendedTypeLoc(),\n                      TypeResolution::forInterface(ext->getDeclContext()),\n                      options)) {\n    ext->setInvalid();\n    ext->getExtendedTypeLoc().setInvalidType(tc.Context);\n    return;\n  }\n\n  \/\/ Dig out the extended type.\n  auto extendedType = ext->getExtendedType();\n\n  \/\/ Hack to allow extending a generic typealias.\n  if (auto *unboundGeneric = extendedType->getAs<UnboundGenericType>()) {\n    if (auto *aliasDecl = dyn_cast<TypeAliasDecl>(unboundGeneric->getDecl())) {\n      auto extendedNominal = aliasDecl->getDeclaredInterfaceType()->getAnyNominal();\n      if (extendedNominal) {\n        extendedType = extendedNominal->getDeclaredType();\n        if (!isPassThroughTypealias(aliasDecl))\n          ext->getExtendedTypeLoc().setType(extendedType);\n      }\n    }\n  }\n\n  \/\/ Cannot extend a metatype.\n  if (extendedType->is<AnyMetatypeType>()) {\n    tc.diagnose(ext->getLoc(), diag::extension_metatype, extendedType)\n      .highlight(ext->getExtendedTypeLoc().getSourceRange());\n    ext->setInvalid();\n    ext->getExtendedTypeLoc().setInvalidType(tc.Context);\n    return;\n  }\n\n  \/\/ Cannot extend function types, tuple types, etc.\n  if (!extendedType->getAnyNominal()) {\n    tc.diagnose(ext->getLoc(), diag::non_nominal_extension, extendedType)\n      .highlight(ext->getExtendedTypeLoc().getSourceRange());\n    ext->setInvalid();\n    ext->getExtendedTypeLoc().setInvalidType(tc.Context);\n    return;\n  }\n\n  \/\/ Cannot extend a bound generic type, unless it's referenced via a\n  \/\/ non-generic typealias type.\n  if (extendedType->isSpecialized() &&\n      !isNonGenericTypeAliasType(extendedType)) {\n    tc.diagnose(ext->getLoc(), diag::extension_specialization,\n                extendedType->getAnyNominal()->getName())\n    .highlight(ext->getExtendedTypeLoc().getSourceRange());\n    ext->setInvalid();\n    ext->getExtendedTypeLoc().setInvalidType(tc.Context);\n    return;\n  }\n}\n\nvoid TypeChecker::validateExtension(ExtensionDecl *ext) {\n  \/\/ If we're currently validating, or have already validated this extension,\n  \/\/ there's nothing more to do now.\n  if (ext->hasValidationStarted())\n    return;\n\n  DeclValidationRAII IBV(ext);\n\n  validateExtendedType(ext, *this);\n\n  if (auto *nominal = ext->getExtendedNominal()) {\n    \/\/ If this extension was not already bound, it means it is either in an\n    \/\/ inactive conditional compilation block, or otherwise (incorrectly)\n    \/\/ nested inside of some other declaration. Make sure the generic\n    \/\/ parameter list of the extension exists to maintain invariants.\n    if (!ext->alreadyBoundToNominal())\n      ext->createGenericParamsIfMissing(nominal);\n\n    \/\/ Validate the nominal type declaration being extended.\n    validateDecl(nominal);\n\n    if (auto *genericParams = ext->getGenericParams()) {\n      GenericEnvironment *env;\n      Type extendedType = ext->getExtendedType();\n      std::tie(env, extendedType) = checkExtensionGenericParams(\n          *this, ext, extendedType,\n          genericParams);\n\n      ext->getExtendedTypeLoc().setType(extendedType);\n      ext->setGenericEnvironment(env);\n    }\n  }\n}\n\n\/\/\/ Build a default initializer string for the given pattern.\n\/\/\/\n\/\/\/ This string is suitable for display in diagnostics.\nstatic Optional<std::string> buildDefaultInitializerString(TypeChecker &tc,\n                                                           DeclContext *dc,\n                                                           Pattern *pattern) {\n  switch (pattern->getKind()) {\n#define REFUTABLE_PATTERN(Id, Parent) case PatternKind::Id:\n#define PATTERN(Id, Parent)\n#include \"swift\/AST\/PatternNodes.def\"\n    return None;\n  case PatternKind::Any:\n    return None;\n\n  case PatternKind::Named: {\n    if (!pattern->hasType())\n      return None;\n\n    \/\/ Special-case the various types we might see here.\n    auto type = pattern->getType();\n\n    \/\/ For literal-convertible types, form the corresponding literal.\n#define CHECK_LITERAL_PROTOCOL(Kind, String) \\\n    if (auto proto = tc.getProtocol(SourceLoc(), KnownProtocolKind::Kind)) { \\\n      if (tc.conformsToProtocol(type, proto, dc, \\\n                                ConformanceCheckFlags::InExpression)) \\\n        return std::string(String); \\\n    }\n    CHECK_LITERAL_PROTOCOL(ExpressibleByArrayLiteral, \"[]\")\n    CHECK_LITERAL_PROTOCOL(ExpressibleByDictionaryLiteral, \"[:]\")\n    CHECK_LITERAL_PROTOCOL(ExpressibleByUnicodeScalarLiteral, \"\\\"\\\"\")\n    CHECK_LITERAL_PROTOCOL(ExpressibleByExtendedGraphemeClusterLiteral, \"\\\"\\\"\")\n    CHECK_LITERAL_PROTOCOL(ExpressibleByFloatLiteral, \"0.0\")\n    CHECK_LITERAL_PROTOCOL(ExpressibleByIntegerLiteral, \"0\")\n    CHECK_LITERAL_PROTOCOL(ExpressibleByStringLiteral, \"\\\"\\\"\")\n#undef CHECK_LITERAL_PROTOCOL\n\n    \/\/ For optional types, use 'nil'.\n    if (type->getOptionalObjectType())\n      return std::string(\"nil\");\n\n    return None;\n  }\n\n  case PatternKind::Paren: {\n    if (auto sub = buildDefaultInitializerString(\n                     tc, dc, cast<ParenPattern>(pattern)->getSubPattern())) {\n      return \"(\" + *sub + \")\";\n    }\n\n    return None;\n  }\n\n  case PatternKind::Tuple: {\n    std::string result = \"(\";\n    bool first = true;\n    for (auto elt : cast<TuplePattern>(pattern)->getElements()) {\n      if (auto sub = buildDefaultInitializerString(tc, dc, elt.getPattern())) {\n        if (first) {\n          first = false;\n        } else {\n          result += \", \";\n        }\n\n        result += *sub;\n      } else {\n        return None;\n      }\n    }\n    result += \")\";\n    return result;\n  }\n\n  case PatternKind::Typed:\n    return buildDefaultInitializerString(\n             tc, dc, cast<TypedPattern>(pattern)->getSubPattern());\n\n  case PatternKind::Var:\n    return buildDefaultInitializerString(\n             tc, dc, cast<VarPattern>(pattern)->getSubPattern());\n  }\n\n  llvm_unreachable(\"Unhandled PatternKind in switch.\");\n}\n\n\/\/\/ Diagnose a class that does not have any initializers.\nstatic void diagnoseClassWithoutInitializers(TypeChecker &tc,\n                                             ClassDecl *classDecl) {\n  tc.diagnose(classDecl, diag::class_without_init,\n              classDecl->getDeclaredType());\n\n  \/\/ HACK: We've got a special case to look out for and diagnose specifically to\n  \/\/ improve the experience of seeing this, and mitigate some confusion.\n  \/\/\n  \/\/ For a class A which inherits from Decodable class B, class A may have\n  \/\/ additional members which prevent default initializer synthesis (and\n  \/\/ inheritance of other initializers). The user may have assumed that this\n  \/\/ case would synthesize Encodable\/Decodable conformance for class A the same\n  \/\/ way it may have for class B, or other classes.\n  \/\/\n  \/\/ It is helpful to suggest here that the user may have forgotten to override\n  \/\/ init(from:) (and encode(to:), if applicable) in a note, before we start\n  \/\/ listing the members that prevented initializer synthesis.\n  \/\/ TODO: Add a fixit along with this suggestion.\n  if (auto *superclassDecl = classDecl->getSuperclassDecl()) {\n    ASTContext &C = tc.Context;\n    auto *decodableProto = C.getProtocol(KnownProtocolKind::Decodable);\n    auto superclassType = superclassDecl->getDeclaredInterfaceType();\n    if (auto ref = TypeChecker::conformsToProtocol(superclassType, decodableProto,\n                                                   superclassDecl,\n                                                   ConformanceCheckOptions(),\n                                                   SourceLoc())) {\n      \/\/ super conforms to Decodable, so we've failed to inherit init(from:).\n      \/\/ Let's suggest overriding it here.\n      \/\/\n      \/\/ We're going to diagnose on the concrete init(from:) decl if it exists\n      \/\/ and isn't implicit; otherwise, on the subclass itself.\n      ValueDecl *diagDest = classDecl;\n      auto initFrom = DeclName(C, DeclBaseName::createConstructor(), C.Id_from);\n      auto result = tc.lookupMember(superclassDecl, superclassType, initFrom,\n                                    NameLookupFlags::ProtocolMembers |\n                                    NameLookupFlags::IgnoreAccessControl);\n\n      if (!result.empty() && !result.front().getValueDecl()->isImplicit())\n        diagDest = result.front().getValueDecl();\n\n      auto diagName = diag::decodable_suggest_overriding_init_here;\n\n      \/\/ This is also a bit of a hack, but the best place we've got at the\n      \/\/ moment to suggest this.\n      \/\/\n      \/\/ If the superclass also conforms to Encodable, it's quite\n      \/\/ likely that the user forgot to override its encode(to:). In this case,\n      \/\/ we can produce a slightly different diagnostic to suggest doing so.\n      auto *encodableProto = C.getProtocol(KnownProtocolKind::Encodable);\n      if ((ref = tc.conformsToProtocol(superclassType, encodableProto,\n                                       superclassDecl,\n                                       ConformanceCheckOptions(),\n                                       SourceLoc()))) {\n        \/\/ We only want to produce this version of the diagnostic if the\n        \/\/ subclass doesn't directly implement encode(to:).\n        \/\/ The direct lookup here won't see an encode(to:) if it is inherited\n        \/\/ from the superclass.\n        auto encodeTo = DeclName(C, C.Id_encode, C.Id_to);\n        if (classDecl->lookupDirect(encodeTo).empty())\n          diagName = diag::codable_suggest_overriding_init_here;\n      }\n\n      tc.diagnose(diagDest, diagName);\n    }\n  }\n\n  \/\/ Lazily construct a mapping from backing storage properties to the\n  \/\/ declared properties.\n  bool computedBackingToOriginalVars = false;\n  llvm::SmallDenseMap<VarDecl *, VarDecl *> backingToOriginalVars;\n  auto getOriginalVar = [&](VarDecl *var) -> VarDecl * {\n    \/\/ If we haven't computed the mapping yet, do so now.\n    if (!computedBackingToOriginalVars) {\n      for (auto member : classDecl->getMembers()) {\n        if (auto var = dyn_cast<VarDecl>(member)) {\n          if (auto backingVar = var->getPropertyWrapperBackingProperty()) {\n            backingToOriginalVars[backingVar] = var;\n          }\n        }\n      }\n\n      computedBackingToOriginalVars = true;\n    }\n\n    auto known = backingToOriginalVars.find(var);\n    if (known == backingToOriginalVars.end())\n      return nullptr;\n\n    return known->second;\n  };\n\n  for (auto member : classDecl->getMembers()) {\n    auto pbd = dyn_cast<PatternBindingDecl>(member);\n    if (!pbd)\n      continue;\n\n    if (pbd->isStatic() || !pbd->hasStorage() ||\n        pbd->isDefaultInitializable() || pbd->isInvalid())\n      continue;\n   \n    for (auto entry : pbd->getPatternList()) {\n      if (entry.isInitialized()) continue;\n      \n      SmallVector<VarDecl *, 4> vars;\n      entry.getPattern()->collectVariables(vars);\n      if (vars.empty()) continue;\n\n      \/\/ Replace the variables we found with the originals for diagnostic\n      \/\/ purposes.\n      for (auto &var : vars) {\n        if (auto originalVar = getOriginalVar(var))\n          var = originalVar;\n      }\n\n      auto varLoc = vars[0]->getLoc();\n      \n      Optional<InFlightDiagnostic> diag;\n      switch (vars.size()) {\n      case 1:\n        diag.emplace(tc.diagnose(varLoc, diag::note_no_in_class_init_1,\n                                 vars[0]->getName()));\n        break;\n      case 2:\n        diag.emplace(tc.diagnose(varLoc, diag::note_no_in_class_init_2,\n                                 vars[0]->getName(), vars[1]->getName()));\n        break;\n      case 3:\n        diag.emplace(tc.diagnose(varLoc, diag::note_no_in_class_init_3plus,\n                                 vars[0]->getName(), vars[1]->getName(), \n                                 vars[2]->getName(), false));\n        break;\n      default:\n        diag.emplace(tc.diagnose(varLoc, diag::note_no_in_class_init_3plus,\n                                 vars[0]->getName(), vars[1]->getName(), \n                                 vars[2]->getName(), true));\n        break;\n      }\n\n      if (auto defaultValueSuggestion\n             = buildDefaultInitializerString(tc, classDecl, entry.getPattern()))\n        diag->fixItInsertAfter(entry.getPattern()->getEndLoc(),\n                               \" = \" + *defaultValueSuggestion);\n    }\n  }\n}\n\nvoid TypeChecker::maybeDiagnoseClassWithoutInitializers(ClassDecl *classDecl) {\n  if (auto *SF = classDecl->getParentSourceFile()) {\n    \/\/ Allow classes without initializers in SIL and parseable interface files.\n    switch (SF->Kind) {\n    case SourceFileKind::SIL:\n    case SourceFileKind::Interface:\n      return;\n    case SourceFileKind::Library:\n    case SourceFileKind::Main:\n    case SourceFileKind::REPL:\n      break;\n    }\n  }\n\n  \/\/ Some heuristics to skip emitting a diagnostic if the class is already\n  \/\/ irreperably busted.\n  if (classDecl->isInvalid() ||\n      classDecl->inheritsSuperclassInitializers(nullptr))\n    return;\n\n  auto *superclassDecl = classDecl->getSuperclassDecl();\n  if (superclassDecl &&\n      superclassDecl->hasMissingDesignatedInitializers())\n    return;\n\n  for (auto member : classDecl->lookupDirect(DeclBaseName::createConstructor())) {\n    auto ctor = dyn_cast<ConstructorDecl>(member);\n    if (ctor && ctor->isDesignatedInit())\n      return;\n  }\n\n  diagnoseClassWithoutInitializers(*this, classDecl);\n}\n\n\/\/\/ Diagnose a missing required initializer.\nstatic void diagnoseMissingRequiredInitializer(\n              TypeChecker &TC,\n              ClassDecl *classDecl,\n              ConstructorDecl *superInitializer) {\n  \/\/ Find the location at which we should insert the new initializer.\n  SourceLoc insertionLoc;\n  SourceLoc indentationLoc;\n  for (auto member : classDecl->getMembers()) {\n    \/\/ If we don't have an indentation location yet, grab one from this\n    \/\/ member.\n    if (indentationLoc.isInvalid()) {\n      indentationLoc = member->getLoc();\n    }\n\n    \/\/ We only want to look at explicit constructors.\n    auto ctor = dyn_cast<ConstructorDecl>(member);\n    if (!ctor)\n      continue;\n\n    if (ctor->isImplicit())\n      continue;\n\n    insertionLoc = ctor->getEndLoc();\n    indentationLoc = ctor->getLoc();\n  }\n\n  \/\/ If no initializers were listed, start at the opening '{' for the class.\n  if (insertionLoc.isInvalid()) {\n    insertionLoc = classDecl->getBraces().Start;\n  }\n  if (indentationLoc.isInvalid()) {\n    indentationLoc = classDecl->getBraces().End;\n  }\n\n  \/\/ Adjust the insertion location to point at the end of this line (i.e.,\n  \/\/ the start of the next line).\n  insertionLoc = Lexer::getLocForEndOfLine(TC.Context.SourceMgr,\n                                           insertionLoc);\n\n  \/\/ Find the indentation used on the indentation line.\n  StringRef extraIndentation;\n  StringRef indentation = Lexer::getIndentationForLine(\n      TC.Context.SourceMgr, indentationLoc, &extraIndentation);\n\n  \/\/ Pretty-print the superclass initializer into a string.\n  \/\/ FIXME: Form a new initializer by performing the appropriate\n  \/\/ substitutions of subclass types into the superclass types, so that\n  \/\/ we get the right generic parameters.\n  std::string initializerText;\n  {\n    PrintOptions options;\n    options.PrintImplicitAttrs = false;\n\n    \/\/ Render the text.\n    llvm::raw_string_ostream out(initializerText);\n    {\n      ExtraIndentStreamPrinter printer(out, indentation);\n      printer.printNewline();\n\n      \/\/ If there is no explicit 'required', print one.\n      bool hasExplicitRequiredAttr = false;\n      if (auto requiredAttr\n            = superInitializer->getAttrs().getAttribute<RequiredAttr>())\n          hasExplicitRequiredAttr = !requiredAttr->isImplicit();\n\n      if (!hasExplicitRequiredAttr)\n        printer << \"required \";\n\n      superInitializer->print(printer, options);\n    }\n\n    \/\/ Add a dummy body.\n    out << \" {\\n\";\n    out << indentation << extraIndentation << \"fatalError(\\\"\";\n    superInitializer->getFullName().printPretty(out);\n    out << \" has not been implemented\\\")\\n\";\n    out << indentation << \"}\\n\";\n  }\n\n  \/\/ Complain.\n  TC.diagnose(insertionLoc, diag::required_initializer_missing,\n              superInitializer->getFullName(),\n              superInitializer->getDeclContext()->getDeclaredInterfaceType())\n    .fixItInsert(insertionLoc, initializerText);\n\n  TC.diagnose(findNonImplicitRequiredInit(superInitializer),\n              diag::required_initializer_here);\n}\n\nvoid TypeChecker::addImplicitConstructors(NominalTypeDecl *decl) {\n  \/\/ We can only synthesize implicit constructors for classes and structs.\n if (!isa<ClassDecl>(decl) && !isa<StructDecl>(decl))\n   return;\n\n  \/\/ If we already added implicit initializers, we're done.\n  if (decl->addedImplicitInitializers())\n    return;\n  \n  \/\/ Don't add implicit constructors for an invalid declaration\n  if (decl->isInvalid())\n    return;\n\n  \/\/ Don't add implicit constructors in parseable interfaces.\n  if (auto *SF = decl->getParentSourceFile()) {\n    if (SF->Kind == SourceFileKind::Interface) {\n      decl->setAddedImplicitInitializers();\n      return;\n    }\n  }\n\n  \/\/ Bail out if we're validating one of our constructors or stored properties\n  \/\/ already; we'll revisit the issue later.\n  if (isa<ClassDecl>(decl)) {\n    for (auto member : decl->getMembers()) {\n      if (auto ctor = dyn_cast<ConstructorDecl>(member)) {\n        validateDecl(ctor);\n        if (!ctor->hasValidSignature())\n          return;\n      }\n    }\n  }\n\n  if (isa<StructDecl>(decl)) {\n    for (auto member : decl->getMembers()) {\n      if (auto var = dyn_cast<VarDecl>(member)) {\n        if (!var->isMemberwiseInitialized(\/*preferDeclaredProperties=*\/true))\n          continue;\n\n        validateDecl(var);\n        if (!var->hasValidSignature())\n          return;\n      }\n    }\n  }\n\n  decl->setAddedImplicitInitializers();\n\n  \/\/ Check whether there is a user-declared constructor or an instance\n  \/\/ variable.\n  bool FoundMemberwiseInitializedProperty = false;\n  bool SuppressDefaultInitializer = false;\n  bool FoundDesignatedInit = false;\n\n  SmallVector<std::pair<ValueDecl *, Type>, 4> declaredInitializers;\n  llvm::SmallPtrSet<ConstructorDecl *, 4> overriddenInits;\n  if (decl->hasClangNode() && isa<ClassDecl>(decl)) {\n    \/\/ Objective-C classes may have interesting initializers in extensions.\n    for (auto member : decl->lookupDirect(DeclBaseName::createConstructor())) {\n      auto ctor = dyn_cast<ConstructorDecl>(member);\n      if (!ctor)\n        continue;\n\n      \/\/ Swift initializers added in extensions of Objective-C classes can never\n      \/\/ be overrides.\n      if (!ctor->hasClangNode())\n        continue;\n\n      if (auto overridden = ctor->getOverriddenDecl())\n        overriddenInits.insert(overridden);\n    }\n\n  } else {\n    SmallPtrSet<VarDecl *, 4> backingStorageVars;\n    for (auto member : decl->getMembers()) {\n      if (auto ctor = dyn_cast<ConstructorDecl>(member)) {\n        \/\/ Initializers that were synthesized to fulfill derived conformances\n        \/\/ should not prevent default initializer synthesis.\n        if (ctor->isDesignatedInit() && !ctor->isSynthesized())\n          FoundDesignatedInit = true;\n\n        if (isa<StructDecl>(decl))\n          continue;\n\n        if (!ctor->isInvalid()) {\n          auto type = getMemberTypeForComparison(Context, ctor, nullptr);\n          declaredInitializers.push_back({ctor, type});\n        }\n\n        if (auto overridden = ctor->getOverriddenDecl())\n          overriddenInits.insert(overridden);\n\n        continue;\n      }\n\n      if (auto var = dyn_cast<VarDecl>(member)) {\n        \/\/ If this variable has a property wrapper, go validate it to ensure\n        \/\/ that we create the backing storage property.\n        if (auto backingVar = var->getPropertyWrapperBackingProperty()) {\n          validateDecl(var);\n          maybeAddAccessorsToStorage(var);\n\n          backingStorageVars.insert(backingVar);\n        }\n\n        \/\/ Ignore the backing storage for properties with attached wrappers.\n        if (backingStorageVars.count(var) > 0)\n          continue;\n\n        if (var->isMemberwiseInitialized(\/*preferDeclaredProperties=*\/true)) {\n          \/\/ Initialized 'let' properties have storage, but don't get an argument\n          \/\/ to the memberwise initializer since they already have an initial\n          \/\/ value that cannot be overridden.\n          if (var->isLet() && var->isParentInitialized()) {\n          \n            \/\/ We cannot handle properties like:\n            \/\/   let (a,b) = (1,2)\n            \/\/ for now, just disable implicit init synthesization in structs in\n            \/\/ this case.\n            auto SP = var->getParentPattern();\n            if (auto *TP = dyn_cast<TypedPattern>(SP))\n              SP = TP->getSubPattern();\n            if (!isa<NamedPattern>(SP) && isa<StructDecl>(decl))\n              return;\n          \n            continue;\n          }\n        \n          FoundMemberwiseInitializedProperty = true;\n        }\n\n        continue;\n      }\n\n      \/\/ If a stored property lacks an initial value and if there is no way to\n      \/\/ synthesize an initial value (e.g. for an optional) then we suppress\n      \/\/ generation of the default initializer.\n      if (auto pbd = dyn_cast<PatternBindingDecl>(member)) {\n        if (pbd->hasStorage() && !pbd->isStatic()) {\n          for (auto entry : pbd->getPatternList()) {\n            if (entry.isInitialized()) continue;\n\n            \/\/ If one of the bound variables is @NSManaged, go ahead no matter\n            \/\/ what.\n            bool CheckDefaultInitializer = true;\n            entry.getPattern()->forEachVariable([&](VarDecl *vd) {\n              if (vd->getAttrs().hasAttribute<NSManagedAttr>())\n                CheckDefaultInitializer = false;\n            });\n          \n            \/\/ If we cannot default initialize the property, we cannot\n            \/\/ synthesize a default initializer for the class.\n            if (CheckDefaultInitializer && !pbd->isDefaultInitializable())\n              SuppressDefaultInitializer = true;\n          }\n        }\n        continue;\n      }\n    }\n  }\n\n  if (auto structDecl = dyn_cast<StructDecl>(decl)) {\n    assert(!structDecl->hasUnreferenceableStorage() &&\n           \"User-defined structs cannot have unreferenceable storage\");\n\n    if (!FoundDesignatedInit) {\n      \/\/ For a struct with memberwise initialized properties, we add a\n      \/\/ memberwise init.\n      if (FoundMemberwiseInitializedProperty) {\n        \/\/ Create the implicit memberwise constructor.\n        auto ctor = createImplicitConstructor(\n                      *this, decl, ImplicitConstructorKind::Memberwise);\n        decl->addMember(ctor);\n      }\n\n      \/\/ If we found a stored property, add a default constructor.\n      if (!SuppressDefaultInitializer)\n        defineDefaultConstructor(decl);\n    }\n    return;\n  }\n \n  \/\/ For a class with a superclass, automatically define overrides\n  \/\/ for all of the superclass's designated initializers.\n  \/\/ FIXME: Currently skipping generic classes.\n  auto classDecl = cast<ClassDecl>(decl);\n  if (Type superclassTy = classDecl->getSuperclass()) {\n    bool canInheritInitializers = (!SuppressDefaultInitializer &&\n                                   !FoundDesignatedInit);\n\n    \/\/ We can't define these overrides if we have any uninitialized\n    \/\/ stored properties.\n    if (SuppressDefaultInitializer && !FoundDesignatedInit &&\n        !classDecl->hasClangNode()) {\n      return;\n    }\n\n    auto *superclassDecl = superclassTy->getClassOrBoundGenericClass();\n    assert(superclassDecl && \"Superclass of class is not a class?\");\n    if (!superclassDecl->addedImplicitInitializers())\n      addImplicitConstructors(superclassDecl);\n\n    auto ctors = lookupConstructors(classDecl, superclassTy,\n                                    NameLookupFlags::IgnoreAccessControl);\n\n    bool canInheritConvenienceInitalizers =\n        !superclassDecl->hasMissingDesignatedInitializers();\n    SmallVector<ConstructorDecl *, 4> requiredConvenienceInitializers;\n    for (auto memberResult : ctors) {\n      auto member = memberResult.getValueDecl();\n\n      \/\/ Skip unavailable superclass initializers.\n      if (AvailableAttr::isUnavailable(member))\n        continue;\n\n      \/\/ Skip invalid superclass initializers.\n      auto superclassCtor = dyn_cast<ConstructorDecl>(member);\n      if (superclassCtor->isInvalid())\n        continue;\n\n      \/\/ If we have an override for this constructor, it's okay.\n      if (overriddenInits.count(superclassCtor) > 0)\n        continue;\n\n      \/\/ We only care about required or designated initializers.\n      if (!superclassCtor->isDesignatedInit()) {\n        if (superclassCtor->isRequired()) {\n          assert(superclassCtor->isInheritable() &&\n                 \"factory initializers cannot be 'required'\");\n          requiredConvenienceInitializers.push_back(superclassCtor);\n        }\n        continue;\n      }\n\n      \/\/ Otherwise, it may no longer be safe to inherit convenience\n      \/\/ initializers.\n      canInheritConvenienceInitalizers &= canInheritInitializers;\n\n      \/\/ Everything after this is only relevant for Swift classes being defined.\n      if (classDecl->hasClangNode())\n        continue;\n\n      \/\/ If the superclass initializer is not accessible from the derived\n      \/\/ class, don't synthesize an override, since we cannot reference the\n      \/\/ superclass initializer's method descriptor at all.\n      \/\/\n      \/\/ FIXME: This should be checked earlier as part of calculating\n      \/\/ canInheritInitializers.\n      if (!superclassCtor->isAccessibleFrom(classDecl))\n        continue;\n\n      \/\/ Diagnose a missing override of a required initializer.\n      if (superclassCtor->isRequired() && !canInheritInitializers) {\n        diagnoseMissingRequiredInitializer(*this, classDecl, superclassCtor);\n        continue;\n      }\n\n      \/\/ A designated or required initializer has not been overridden.\n\n      bool alreadyDeclared = false;\n      for (const auto &ctorAndType : declaredInitializers) {\n        auto *ctor = ctorAndType.first;\n        auto type = ctorAndType.second;\n        auto parentType = getMemberTypeForComparison(\n            Context, superclassCtor, ctor);\n\n        if (isOverrideBasedOnType(ctor, type, superclassCtor, parentType)) {\n          alreadyDeclared = true;\n          break;\n        }\n      }\n\n      \/\/ If we have already introduced an initializer with this parameter type,\n      \/\/ don't add one now.\n      if (alreadyDeclared)\n        continue;\n\n      \/\/ If we're inheriting initializers, create an override delegating\n      \/\/ to 'super.init'. Otherwise, create a stub which traps at runtime.\n      auto kind = canInheritInitializers\n                    ? DesignatedInitKind::Chaining\n                    : DesignatedInitKind::Stub;\n\n      \/\/ We have a designated initializer. Create an override of it.\n      \/\/ FIXME: Validation makes sure we get a generic signature here.\n      validateDecl(classDecl);\n      if (auto ctor = createDesignatedInitOverride(\n                        *this, classDecl, superclassCtor, kind)) {\n        classDecl->addMember(ctor);\n      }\n    }\n\n    if (canInheritConvenienceInitalizers) {\n      classDecl->setInheritsSuperclassInitializers();\n    } else {\n      for (ConstructorDecl *requiredCtor : requiredConvenienceInitializers)\n        diagnoseMissingRequiredInitializer(*this, classDecl, requiredCtor);\n    }\n\n    return;\n  }\n\n  if (!FoundDesignatedInit) {\n    \/\/ For a class with no superclass, automatically define a default\n    \/\/ constructor.\n\n    \/\/ ... unless there are uninitialized stored properties.\n    if (SuppressDefaultInitializer)\n      return;\n\n    defineDefaultConstructor(decl);\n  }\n}\n\nvoid TypeChecker::synthesizeMemberForLookup(NominalTypeDecl *target,\n                                            DeclName member) {\n  auto baseName = member.getBaseName();\n\n  \/\/ Checks whether the target conforms to the given protocol. If the\n  \/\/ conformance is incomplete, force the conformance.\n  \/\/\n  \/\/ Returns whether the target conforms to the protocol.\n  auto evaluateTargetConformanceTo = [&](ProtocolDecl *protocol) {\n    if (!protocol)\n      return false;\n\n    auto targetType = target->getDeclaredInterfaceType();\n    if (auto ref = conformsToProtocol(\n                        targetType, protocol, target,\n                        ConformanceCheckFlags::SkipConditionalRequirements)) {\n      if (auto *conformance = dyn_cast<NormalProtocolConformance>(\n            ref->getConcrete()->getRootConformance())) {\n        if (conformance->getState() == ProtocolConformanceState::Incomplete) {\n          checkConformance(conformance);\n        }\n      }\n\n      return true;\n    }\n\n    return false;\n  };\n\n  if (member.isSimpleName() && !baseName.isSpecial()) {\n    if (baseName.getIdentifier() == Context.Id_CodingKeys) {\n      \/\/ CodingKeys is a special type which may be synthesized as part of\n      \/\/ Encodable\/Decodable conformance. If the target conforms to either\n      \/\/ protocol and would derive conformance to either, the type may be\n      \/\/ synthesized.\n      \/\/ If the target conforms to either and the conformance has not yet been\n      \/\/ evaluated, then we should do that here.\n      \/\/\n      \/\/ Try to synthesize Decodable first. If that fails, try to synthesize\n      \/\/ Encodable. If either succeeds and CodingKeys should have been\n      \/\/ synthesized, it will be synthesized.\n      auto *decodableProto = Context.getProtocol(KnownProtocolKind::Decodable);\n      auto *encodableProto = Context.getProtocol(KnownProtocolKind::Encodable);\n      if (!evaluateTargetConformanceTo(decodableProto))\n        (void)evaluateTargetConformanceTo(encodableProto);\n    }\n  } else {\n    auto argumentNames = member.getArgumentNames();\n    if (member.isCompoundName() && argumentNames.size() != 1)\n      return;\n\n    if (baseName == DeclBaseName::createConstructor() &&\n        (member.isSimpleName() || argumentNames.front() == Context.Id_from)) {\n      \/\/ init(from:) may be synthesized as part of derived conformance to the\n      \/\/ Decodable protocol.\n      \/\/ If the target should conform to the Decodable protocol, check the\n      \/\/ conformance here to attempt synthesis.\n      auto *decodableProto = Context.getProtocol(KnownProtocolKind::Decodable);\n      (void)evaluateTargetConformanceTo(decodableProto);\n    } else if (!baseName.isSpecial() &&\n               baseName.getIdentifier() == Context.Id_encode &&\n               (member.isSimpleName() ||\n                argumentNames.front() == Context.Id_to)) {\n      \/\/ encode(to:) may be synthesized as part of derived conformance to the\n      \/\/ Encodable protocol.\n      \/\/ If the target should conform to the Encodable protocol, check the\n      \/\/ conformance here to attempt synthesis.\n      auto *encodableProto = Context.getProtocol(KnownProtocolKind::Encodable);\n      (void)evaluateTargetConformanceTo(encodableProto);\n    }\n  }\n}\n\nvoid TypeChecker::defineDefaultConstructor(NominalTypeDecl *decl) {\n  FrontendStatsTracer StatsTracer(Context.Stats, \"define-default-ctor\", decl);\n  PrettyStackTraceDecl stackTrace(\"defining default constructor for\",\n                                  decl);\n\n  \/\/ Clang-imported types should never get a default constructor, just a\n  \/\/ memberwise one.\n  if (decl->hasClangNode())\n    return;\n\n  \/\/ A class is only default initializable if it's a root class.\n  if (auto *classDecl = dyn_cast<ClassDecl>(decl)) {\n    \/\/ If the class has a superclass, we should have either inherited it's\n    \/\/ designated initializers or diagnosed the absence of our own.\n    if (classDecl->getSuperclass())\n      return;\n  }\n\n  \/\/ Create the default constructor.\n  auto ctor = createImplicitConstructor(*this, decl,\n                                        ImplicitConstructorKind::Default);\n\n  \/\/ Add the constructor.\n  decl->addMember(ctor);\n\n  \/\/ Create an empty body for the default constructor.\n  SmallVector<ASTNode, 1> stmts;\n  stmts.push_back(new (Context) ReturnStmt(decl->getLoc(), nullptr));\n  ctor->setBody(BraceStmt::create(Context, SourceLoc(), stmts, SourceLoc()));\n  ctor->setBodyTypeCheckedIfPresent();\n\n  \/\/ FIXME: This is still needed so that DI can check captures for\n  \/\/ initializer expressions. Rethink that completely.\n  Context.addSynthesizedDecl(ctor);\n}\n\nstatic void validateAttributes(TypeChecker &TC, Decl *D) {\n  DeclAttributes &Attrs = D->getAttrs();\n\n  auto checkObjCDeclContext = [](Decl *D) {\n    DeclContext *DC = D->getDeclContext();\n    if (DC->getSelfClassDecl())\n      return true;\n    if (auto *PD = dyn_cast<ProtocolDecl>(DC))\n      if (PD->isObjC())\n        return true;\n    return false;\n  };\n\n  if (auto objcAttr = Attrs.getAttribute<ObjCAttr>()) {\n    \/\/ Only certain decls can be ObjC.\n    Optional<Diag<>> error;\n    if (isa<ClassDecl>(D) ||\n        isa<ProtocolDecl>(D)) {\n      \/* ok *\/\n    } else if (auto Ext = dyn_cast<ExtensionDecl>(D)) {\n      if (!Ext->getSelfClassDecl())\n        error = diag::objc_extension_not_class;\n    } else if (auto ED = dyn_cast<EnumDecl>(D)) {\n      if (ED->isGenericContext())\n        error = diag::objc_enum_generic;\n    } else if (auto EED = dyn_cast<EnumElementDecl>(D)) {\n      auto ED = EED->getParentEnum();\n      if (!ED->getAttrs().hasAttribute<ObjCAttr>())\n        error = diag::objc_enum_case_req_objc_enum;\n      else if (objcAttr->hasName() && EED->getParentCase()->getElements().size() > 1)\n        error = diag::objc_enum_case_multi;\n    } else if (auto *func = dyn_cast<FuncDecl>(D)) {\n      if (!checkObjCDeclContext(D))\n        error = diag::invalid_objc_decl_context;\n      else if (auto accessor = dyn_cast<AccessorDecl>(func))\n        if (!accessor->isGetterOrSetter())\n          error = diag::objc_observing_accessor;\n    } else if (isa<ConstructorDecl>(D) ||\n               isa<DestructorDecl>(D) ||\n               isa<SubscriptDecl>(D) ||\n               isa<VarDecl>(D)) {\n      if (!checkObjCDeclContext(D))\n        error = diag::invalid_objc_decl_context;\n      \/* ok *\/\n    } else {\n      error = diag::invalid_objc_decl;\n    }\n\n    if (error) {\n      TC.diagnose(D->getStartLoc(), *error)\n        .fixItRemove(objcAttr->getRangeWithAt());\n      objcAttr->setInvalid();\n      return;\n    }\n\n    \/\/ If there is a name, check whether the kind of name is\n    \/\/ appropriate.\n    if (auto objcName = objcAttr->getName()) {\n      if (isa<ClassDecl>(D) || isa<ProtocolDecl>(D) || isa<VarDecl>(D)\n          || isa<EnumDecl>(D) || isa<EnumElementDecl>(D)\n          || isa<ExtensionDecl>(D)) {\n        \/\/ Types and properties can only have nullary\n        \/\/ names. Complain and recover by chopping off everything\n        \/\/ after the first name.\n        if (objcName->getNumArgs() > 0) {\n          SourceLoc firstNameLoc = objcAttr->getNameLocs().front();\n          SourceLoc afterFirstNameLoc = \n            Lexer::getLocForEndOfToken(TC.Context.SourceMgr, firstNameLoc);\n          TC.diagnose(firstNameLoc, diag::objc_name_req_nullary,\n                      D->getDescriptiveKind())\n            .fixItRemoveChars(afterFirstNameLoc, objcAttr->getRParenLoc());\n          const_cast<ObjCAttr *>(objcAttr)->setName(\n            ObjCSelector(TC.Context, 0, objcName->getSelectorPieces()[0]),\n            \/*implicit=*\/false);\n        }\n      } else if (isa<SubscriptDecl>(D) || isa<DestructorDecl>(D)) {\n        TC.diagnose(objcAttr->getLParenLoc(),\n                    isa<SubscriptDecl>(D)\n                      ? diag::objc_name_subscript\n                      : diag::objc_name_deinit);\n        const_cast<ObjCAttr *>(objcAttr)->clearName();\n      } else {\n        \/\/ We have a function. Make sure that the number of parameters\n        \/\/ matches the \"number of colons\" in the name.\n        auto func = cast<AbstractFunctionDecl>(D);\n        auto params = func->getParameters();\n        unsigned numParameters = params->size();\n        if (auto CD = dyn_cast<ConstructorDecl>(func))\n          if (CD->isObjCZeroParameterWithLongSelector())\n            numParameters = 0;  \/\/ Something like \"init(foo: ())\"\n\n        \/\/ A throwing method has an error parameter.\n        if (func->hasThrows())\n          ++numParameters;\n\n        unsigned numArgumentNames = objcName->getNumArgs();\n        if (numArgumentNames != numParameters) {\n          TC.diagnose(objcAttr->getNameLocs().front(), \n                      diag::objc_name_func_mismatch,\n                      isa<FuncDecl>(func), \n                      numArgumentNames, \n                      numArgumentNames != 1,\n                      numParameters,\n                      numParameters != 1,\n                      func->hasThrows());\n          D->getAttrs().add(\n            ObjCAttr::createUnnamed(TC.Context,\n                                    objcAttr->AtLoc,\n                                    objcAttr->Range.Start));\n          D->getAttrs().removeAttribute(objcAttr);\n        }\n      }\n    } else if (isa<EnumElementDecl>(D)) {\n      \/\/ Enum elements require names.\n      TC.diagnose(objcAttr->getLocation(), diag::objc_enum_case_req_name)\n        .fixItRemove(objcAttr->getRangeWithAt());\n      objcAttr->setInvalid();\n    }\n  }\n\n  if (auto nonObjcAttr = Attrs.getAttribute<NonObjCAttr>()) {\n    \/\/ Only extensions of classes; methods, properties, subscripts\n    \/\/ and constructors can be NonObjC.\n    \/\/ The last three are handled automatically by generic attribute\n    \/\/ validation -- for the first one, we have to check FuncDecls\n    \/\/ ourselves.\n    Optional<Diag<>> error;\n\n    auto func = dyn_cast<FuncDecl>(D);\n    if (func &&\n        (isa<DestructorDecl>(func) ||\n         !checkObjCDeclContext(func) ||\n         (isa<AccessorDecl>(func) &&\n          !cast<AccessorDecl>(func)->isGetterOrSetter()))) {\n      error = diag::invalid_nonobjc_decl;\n    }\n\n    if (auto ext = dyn_cast<ExtensionDecl>(D)) {\n      if (!ext->getSelfClassDecl())\n        error = diag::invalid_nonobjc_extension;\n    }\n\n    if (error) {\n      TC.diagnose(D->getStartLoc(), *error)\n        .fixItRemove(nonObjcAttr->getRangeWithAt());\n      nonObjcAttr->setInvalid();\n      return;\n    }\n  }\n\n  \/\/ Only protocol members can be optional.\n  if (auto *OA = Attrs.getAttribute<OptionalAttr>()) {\n    if (!isa<ProtocolDecl>(D->getDeclContext())) {\n      TC.diagnose(OA->getLocation(), diag::optional_attribute_non_protocol)\n        .fixItRemove(OA->getRange());\n      D->getAttrs().removeAttribute(OA);\n    } else if (!cast<ProtocolDecl>(D->getDeclContext())->isObjC()) {\n      TC.diagnose(OA->getLocation(),\n                  diag::optional_attribute_non_objc_protocol);\n      D->getAttrs().removeAttribute(OA);\n    } else if (isa<ConstructorDecl>(D)) {\n      TC.diagnose(OA->getLocation(),\n                  diag::optional_attribute_initializer);\n      D->getAttrs().removeAttribute(OA);\n    } else {\n      auto objcAttr = D->getAttrs().getAttribute<ObjCAttr>();\n      if (!objcAttr || objcAttr->isImplicit()) {\n        auto diag = TC.diagnose(OA->getLocation(),\n                                diag::optional_attribute_missing_explicit_objc);\n        if (auto VD = dyn_cast<ValueDecl>(D))\n          diag.fixItInsert(VD->getAttributeInsertionLoc(false), \"@objc \");\n      }\n    }\n  }\n\n  \/\/ Only protocols that are @objc can have \"unavailable\" methods.\n  if (auto AvAttr = Attrs.getUnavailable(TC.Context)) {\n    if (auto PD = dyn_cast<ProtocolDecl>(D->getDeclContext())) {\n      if (!PD->isObjC()) {\n        TC.diagnose(AvAttr->getLocation(),\n                    diag::unavailable_method_non_objc_protocol);\n        D->getAttrs().removeAttribute(AvAttr);\n      }\n    }\n  }\n}\n","avg_line_length":35.6858864028,"max_line_length":91,"alphanum_fraction":0.6402488726,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":965,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include \"versionNoInstallTest.h\"\n\nvoid VersionNoInstallTest::initTestCase()\n{\n\n}\n\nvoid VersionNoInstallTest::cleanupTestCase()\n{\n\n}\n\nvoid VersionNoInstallTest::test_initCase_data()\n{\n    versionData::loadVersionNameData();\n}\n\nvoid VersionNoInstallTest::test_initCase()\n{\n    QFETCH(QString, versionName);\n    QFETCH(VersionType, versionTypeResult);\n    QFETCH(int, versionNumberResult);\n    QFETCH(QString, versionNameSpaceResult);\n    QFETCH(QString, versionNameUnderscoreResult);\n    QString appName = versionData::randomString();\n    qDebug () << \"app name:     \" << appName;\n    VersionNoInstall *verNoIntsall = new VersionNoInstall (appName,versionName);\n\n    QCOMPARE(verNoIntsall->getVersionType(),versionTypeResult);\n    QCOMPARE(verNoIntsall->getVersionNumber(),versionNumberResult);\n    QCOMPARE(verNoIntsall->getFullName(), versionNameSpaceResult);\n    QCOMPARE(verNoIntsall->getAppName(), appName);\n    QCOMPARE(verNoIntsall->getIsInstall(), false);\n}\n","avg_line_length":27.5714285714,"max_line_length":80,"alphanum_fraction":0.7544041451,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":319,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/\n\/\/  RedWine.cpp\n\/\/  Bar\n\/\/\n\/\/  Created by Gabriel Kapach on 19\/09\/2017.\n\/\/  Copyright \u00a9 2017 Gabriel Kapach. All rights reserved.\n\/\/\n\n#include \"RedWine.hpp\"\n\nstring RedWine::prepare() {\n    return \"Well, you need to make sure the wine is as the room tempture (16\u00b0 - 18\u00b0), and then pour into a glass and serve.\\n\";\n}\n","avg_line_length":22.7857142857,"max_line_length":127,"alphanum_fraction":0.6645768025,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":41795,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/\/    _   _____   __________\n\/\/   | | \/ \/ _ | \/ __\/_  __\/     Visibility\n\/\/   | |\/ \/ __ |_\\ \\  \/ \/          Across\n\/\/   |___\/_\/ |_\/___\/ \/_\/       Space and Time\n\/\/\n\/\/ SPDX-FileCopyrightText: (c) 2016 The VAST Contributors\n\/\/ SPDX-License-Identifier: BSD-3-Clause\n\n#include \"vast\/system\/partition.hpp\"\n\n#include \"vast\/fwd.hpp\"\n\n#include \"vast\/address_synopsis.hpp\"\n#include \"vast\/aliases.hpp\"\n#include \"vast\/chunk.hpp\"\n#include \"vast\/concept\/hashable\/xxhash.hpp\"\n#include \"vast\/concept\/printable\/to_string.hpp\"\n#include \"vast\/concept\/printable\/vast\/expression.hpp\"\n#include \"vast\/concept\/printable\/vast\/table_slice.hpp\"\n#include \"vast\/concept\/printable\/vast\/uuid.hpp\"\n#include \"vast\/detail\/assert.hpp\"\n#include \"vast\/detail\/notifying_stream_manager.hpp\"\n#include \"vast\/detail\/settings.hpp\"\n#include \"vast\/detail\/tracepoint.hpp\"\n#include \"vast\/expression_visitors.hpp\"\n#include \"vast\/fbs\/partition.hpp\"\n#include \"vast\/fbs\/utils.hpp\"\n#include \"vast\/fbs\/uuid.hpp\"\n#include \"vast\/ids.hpp\"\n#include \"vast\/logger.hpp\"\n#include \"vast\/plugin.hpp\"\n#include \"vast\/qualified_record_field.hpp\"\n#include \"vast\/synopsis.hpp\"\n#include \"vast\/system\/indexer.hpp\"\n#include \"vast\/system\/local_segment_store.hpp\"\n#include \"vast\/system\/shutdown.hpp\"\n#include \"vast\/system\/status.hpp\"\n#include \"vast\/system\/terminate.hpp\"\n#include \"vast\/table_slice.hpp\"\n#include \"vast\/table_slice_column.hpp\"\n#include \"vast\/time.hpp\"\n#include \"vast\/type.hpp\"\n#include \"vast\/value_index.hpp\"\n\n#include <caf\/attach_continuous_stream_stage.hpp>\n#include <caf\/broadcast_downstream_manager.hpp>\n#include <caf\/deserializer.hpp>\n#include <caf\/error.hpp>\n#include <caf\/sec.hpp>\n#include <flatbuffers\/base.h> \/\/ FLATBUFFERS_MAX_BUFFER_SIZE\n#include <flatbuffers\/flatbuffers.h>\n\n#include <filesystem>\n#include <memory>\n#include <span>\n\nnamespace vast::system {\n\n\/\/\/ Gets the ACTIVE INDEXER at a certain position.\nactive_indexer_actor active_partition_state::indexer_at(size_t position) const {\n  VAST_ASSERT(position < indexers.size());\n  return as_vector(indexers)[position].second;\n}\n\nvoid active_partition_state::add_flush_listener(flush_listener_actor listener) {\n  VAST_DEBUG(\"{} adds a new 'flush' subscriber: {}\", self, listener);\n  flush_listeners.emplace_back(std::move(listener));\n  detail::notify_listeners_if_clean(*this, *stage);\n}\n\nvoid active_partition_state::notify_flush_listeners() {\n  VAST_DEBUG(\"{} sends 'flush' messages to {} listeners\", self,\n             flush_listeners.size());\n  for (auto& listener : flush_listeners)\n    self->send(listener, atom::flush_v);\n  flush_listeners.clear();\n}\n\n\/\/\/ Gets the INDEXER at a certain position.\nindexer_actor passive_partition_state::indexer_at(size_t position) const {\n  VAST_ASSERT(position < indexers.size());\n  auto& indexer = indexers[position];\n  \/\/ Deserialize the value index and spawn a passive_indexer lazily when it is\n  \/\/ requested for the first time.\n  if (!indexer) {\n    auto qualified_index = flatbuffer->indexes()->Get(position);\n    auto index = qualified_index->index();\n    auto data = index->data();\n    value_index_ptr state_ptr;\n    if (auto error = fbs::deserialize_bytes(data, state_ptr)) {\n      VAST_ERROR(\"{} failed to deserialize indexer at {} with error: \"\n                 \"{}\",\n                 self, position, render(error));\n      return {};\n    }\n    indexer = self->spawn(passive_indexer, id, std::move(state_ptr));\n  }\n  return indexer;\n}\n\nnamespace {\n\n\/\/ The functions in this namespace take PartitionState as template argument\n\/\/ because the impelementation is the same for passive and active partitions.\n\n\/\/\/ Gets the INDEXER at position in the layout.\n\/\/\/ @relates active_partition_state\n\/\/\/ @relates passive_partition_state\ntemplate <typename PartitionState>\nindexer_actor\nfetch_indexer(const PartitionState& state, const data_extractor& dx,\n              relational_operator op, const data& x) {\n  VAST_TRACE_SCOPE(\"{} {} {}\", VAST_ARG(dx), VAST_ARG(op), VAST_ARG(x));\n  \/\/ Sanity check.\n  if (dx.offset.empty())\n    return {};\n  if (auto index = state.combined_layout.flat_index_at(dx.offset))\n    return state.indexer_at(*index);\n  VAST_WARN(\"{} got invalid offset for the combined layout {}\", state.self,\n            state.combined_layout);\n  return {};\n}\n\n\/\/\/ Retrieves an INDEXER for a predicate with a data extractor.\n\/\/\/ @param dx The extractor.\n\/\/\/ @param op The operator (only used to precompute ids for type queries.\n\/\/\/ @param x The literal side of the predicate.\n\/\/\/ @relates active_partition_state\n\/\/\/ @relates passive_partition_state\ntemplate <typename PartitionState>\nindexer_actor\nfetch_indexer(const PartitionState& state, const meta_extractor& ex,\n              relational_operator op, const data& x) {\n  VAST_TRACE_SCOPE(\"{} {} {}\", VAST_ARG(ex), VAST_ARG(op), VAST_ARG(x));\n  ids row_ids;\n  if (ex.kind == meta_extractor::type) {\n    \/\/ We know the answer immediately: all IDs that are part of the table.\n    \/\/ However, we still have to \"lift\" this result into an actor for the\n    \/\/ EVALUATOR.\n    for (auto& [name, ids] : state.type_ids)\n      if (evaluate(name, op, x))\n        row_ids |= ids;\n  } else if (ex.kind == meta_extractor::field) {\n    auto s = caf::get_if<std::string>(&x);\n    if (!s) {\n      VAST_WARN(\"{} #field meta queries only support string \"\n                \"comparisons\",\n                state.self);\n      return {};\n    }\n    auto neg = is_negated(op);\n    for (const auto& field : record_type::each{state.combined_layout}) {\n      \/\/ As long as the combined layout is flattened, this must rely on\n      \/\/ a heuristic. We use the substring after the last dot for the\n      \/\/ field name.\n      \/\/ const auto& name = field.trace.back()->name;\n      auto fqn = field.key();\n      if (detail::ends_with(fqn, *s)) {\n        \/\/ Get ids.\n        for (const auto& [layout_name, ids] : state.type_ids)\n          if (detail::starts_with(field.key(), layout_name))\n            row_ids |= ids;\n      }\n    }\n    if (neg) {\n      auto partition_ids\n        = std::accumulate(state.type_ids.begin(), state.type_ids.end(), ids{},\n                          [](ids acc, const auto& x) {\n                            return acc | x.second;\n                          });\n      row_ids = partition_ids ^ row_ids;\n    }\n  } else {\n    VAST_WARN(\"{} got unsupported attribute: {}\", state.self, ex.kind);\n    return {};\n  }\n  \/\/ TODO: Spawning a one-shot actor is quite expensive. Maybe the\n  \/\/       partition could instead maintain this actor lazily.\n  return state.self->spawn([row_ids]() -> indexer_actor::behavior_type {\n    return {\n      [=](const curried_predicate&) {\n        return row_ids;\n      },\n      [](atom::shutdown) {\n        VAST_DEBUG(\"one-shot indexer received shutdown request\");\n      },\n    };\n  });\n}\n\n\/\/\/ Returns all INDEXERs that are involved in evaluating the expression.\n\/\/\/ @relates active_partition_state\n\/\/\/ @relates passive_partition_state\ntemplate <typename PartitionState>\nstd::vector<evaluation_triple>\nevaluate(const PartitionState& state, const expression& expr) {\n  std::vector<evaluation_triple> result;\n  \/\/ Pretend the partition is a table, and return fitted predicates for the\n  \/\/ partitions layout.\n  auto resolved = resolve(expr, state.combined_layout);\n  for (auto& kvp : resolved) {\n    \/\/ For each fitted predicate, look up the corresponding INDEXER\n    \/\/ according to the specified type of extractor.\n    auto& pred = kvp.second;\n    auto get_indexer_handle = [&](const auto& ext, const data& x) {\n      return fetch_indexer(state, ext, pred.op, x);\n    };\n    auto v = detail::overload{\n      [&](const meta_extractor& ex, const data& x) {\n        return get_indexer_handle(ex, x);\n      },\n      [&](const data_extractor& dx, const data& x) {\n        return get_indexer_handle(dx, x);\n      },\n      [](const auto&, const auto&) {\n        return indexer_actor{}; \/\/ clang-format fix\n      },\n    };\n    \/\/ Package the predicate, its position in the query and the required\n    \/\/ INDEXER as a \"job description\".\n    if (auto hdl = caf::visit(v, pred.lhs, pred.rhs))\n      result.emplace_back(kvp.first, curried(pred), std::move(hdl));\n  }\n  \/\/ Return the list of jobs, to be used by the EVALUATOR.\n  return result;\n}\n\n} \/\/ namespace\n\nbool partition_selector::operator()(const qualified_record_field& filter,\n                                    const table_slice_column& column) const {\n  return filter == column.field();\n}\n\ncaf::expected<flatbuffers::Offset<fbs::Partition>>\npack(flatbuffers::FlatBufferBuilder& builder, const active_partition_state& x) {\n  auto uuid = pack(builder, x.id);\n  if (!uuid)\n    return uuid.error();\n  std::vector<flatbuffers::Offset<fbs::qualified_value_index::v0>> indices;\n  \/\/ Note that the deserialization code relies on the order of indexers within\n  \/\/ the flatbuffers being preserved.\n  for (auto& [qf, actor] : x.indexers) {\n    auto actor_id = actor.id();\n    auto chunk_it = x.chunks.find(actor_id);\n    if (chunk_it == x.chunks.end())\n      return caf::make_error(ec::logic_error, \"no chunk for for actor id \"\n                                                + to_string(actor_id));\n    auto& chunk = chunk_it->second;\n    auto data = builder.CreateVector(\n      reinterpret_cast<const uint8_t*>(chunk->data()), chunk->size());\n    auto fieldname = builder.CreateString(qf.field_name);\n    fbs::value_index::v0Builder vbuilder(builder);\n    vbuilder.add_data(data);\n    auto vindex = vbuilder.Finish();\n    fbs::qualified_value_index::v0Builder qbuilder(builder);\n    qbuilder.add_field_name(fieldname);\n    qbuilder.add_index(vindex);\n    auto qindex = qbuilder.Finish();\n    indices.push_back(qindex);\n  }\n  auto indexes = builder.CreateVector(indices);\n  \/\/ Serialize layout.\n  auto combined_layout = fbs::serialize_bytes(builder, x.combined_layout);\n  if (!combined_layout)\n    return combined_layout.error();\n  std::vector<flatbuffers::Offset<fbs::type_ids::v0>> tids;\n  for (const auto& kv : x.type_ids) {\n    auto name = builder.CreateString(kv.first);\n    auto ids = fbs::serialize_bytes(builder, kv.second);\n    if (!ids)\n      return ids.error();\n    fbs::type_ids::v0Builder tids_builder(builder);\n    tids_builder.add_name(name);\n    tids_builder.add_ids(*ids);\n    tids.push_back(tids_builder.Finish());\n  }\n  auto type_ids = builder.CreateVector(tids);\n  \/\/ Serialize synopses.\n  auto maybe_ps = pack(builder, *x.synopsis);\n  if (!maybe_ps)\n    return maybe_ps.error();\n  flatbuffers::Offset<fbs::partition::store_header::v0> store_header = {};\n  auto store_name = builder.CreateString(x.store_id);\n  auto store_data = builder.CreateVector(\n    reinterpret_cast<const uint8_t*>(x.store_header->data()),\n    x.store_header->size());\n  fbs::partition::store_header::v0Builder store_builder(builder);\n  store_builder.add_id(store_name);\n  store_builder.add_data(store_data);\n  store_header = store_builder.Finish();\n  fbs::partition::v0Builder v0_builder(builder);\n  v0_builder.add_uuid(*uuid);\n  v0_builder.add_offset(x.offset);\n  v0_builder.add_events(x.events);\n  v0_builder.add_indexes(indexes);\n  v0_builder.add_partition_synopsis(*maybe_ps);\n  v0_builder.add_combined_layout(*combined_layout);\n  v0_builder.add_type_ids(type_ids);\n  v0_builder.add_store(store_header);\n  auto partition_v0 = v0_builder.Finish();\n  fbs::PartitionBuilder partition_builder(builder);\n  partition_builder.add_partition_type(fbs::partition::Partition::v0);\n  partition_builder.add_partition(partition_v0.Union());\n  auto partition = partition_builder.Finish();\n  fbs::FinishPartitionBuffer(builder, partition);\n  return partition;\n}\n\ncaf::error\nunpack(const fbs::partition::v0& partition, passive_partition_state& state) {\n  \/\/ Check that all fields exist.\n  if (!partition.uuid())\n    return caf::make_error(ec::format_error,\n                           \"missing 'uuid' field in partition \"\n                           \"flatbuffer\");\n  auto combined_layout = partition.combined_layout();\n  if (!combined_layout)\n    return caf::make_error(ec::format_error,\n                           \"missing 'layouts' field in partition \"\n                           \"flatbuffer\");\n  auto store_header = partition.store();\n  \/\/ If no store_id is set, use the global store for backwards compatibility.\n  if (store_header && !store_header->id())\n    return caf::make_error(ec::format_error, \"missing 'id' field in partition \"\n                                             \"store header\");\n  if (store_header && !store_header->data())\n    return caf::make_error(ec::format_error,\n                           \"missing 'data' field in partition \"\n                           \"store header\");\n  state.store_id\n    = store_header ? store_header->id()->str() : std::string{\"legacy_archive\"};\n  if (store_header && store_header->data())\n    state.store_header = std::span{\n      reinterpret_cast<const std::byte*>(store_header->data()->data()),\n      store_header->data()->size()};\n  auto indexes = partition.indexes();\n  if (!indexes)\n    return caf::make_error(ec::format_error,\n                           \"missing 'indexes' field in partition \"\n                           \"flatbuffer\");\n  for (auto qualified_index : *indexes) {\n    if (!qualified_index->field_name())\n      return caf::make_error(ec::format_error,\n                             \"missing field name in qualified \"\n                             \"index\");\n    auto index = qualified_index->index();\n    if (!index)\n      return caf::make_error(ec::format_error,\n                             \"missing index name in qualified \"\n                             \"index\");\n    if (!index->data())\n      return caf::make_error(ec::format_error, \"missing data in index\");\n  }\n  if (auto error = unpack(*partition.uuid(), state.id))\n    return error;\n  state.events = partition.events();\n  state.offset = partition.offset();\n  state.name = \"partition-\" + to_string(state.id);\n  if (auto error\n      = fbs::deserialize_bytes(combined_layout, state.combined_layout))\n    return error;\n  \/\/ This condition should be '!=', but then we cant deserialize in unit tests\n  \/\/ anymore without creating a bunch of index actors first. :\/\n  if (state.combined_layout.fields.size() < indexes->size()) {\n    VAST_ERROR(\"{} found incoherent number of indexers in deserialized \"\n               \"state; {} fields for {} indexes\",\n               state.name, state.combined_layout.fields.size(),\n               indexes->size());\n    return caf::make_error(ec::format_error, \"incoherent number of indexers\");\n  }\n  \/\/ We only create dummy entries here, since the positions of the `indexers`\n  \/\/ vector must be the same as in `combined_layout`. The actual indexers are\n  \/\/ deserialized and spawned lazily on demand.\n  state.indexers.resize(indexes->size());\n  VAST_DEBUG(\"{} found {} indexers for partition {}\", state.name,\n             indexes->size(), state.id);\n  auto type_ids = partition.type_ids();\n  for (size_t i = 0; i < type_ids->size(); ++i) {\n    auto type_ids_tuple = type_ids->Get(i);\n    auto name = type_ids_tuple->name();\n    auto ids_data = type_ids_tuple->ids();\n    auto& ids = state.type_ids[name->str()];\n    if (auto error = fbs::deserialize_bytes(ids_data, ids))\n      return error;\n  }\n  VAST_DEBUG(\"{} restored {} type-to-ids mapping for partition {}\", state.name,\n             state.type_ids.size(), state.id);\n  return caf::none;\n}\n\ncaf::error unpack(const fbs::partition::v0& x, partition_synopsis& ps) {\n  if (!x.partition_synopsis())\n    return caf::make_error(ec::format_error, \"missing partition synopsis\");\n  if (!x.type_ids())\n    return caf::make_error(ec::format_error, \"missing type_ids\");\n  return unpack(*x.partition_synopsis(), ps);\n}\n\nactive_partition_actor::behavior_type active_partition(\n  active_partition_actor::stateful_pointer<active_partition_state> self,\n  uuid id, filesystem_actor filesystem, caf::settings index_opts,\n  caf::settings synopsis_opts, store_actor store, std::string store_id,\n  chunk_ptr header) {\n  self->state.self = self;\n  self->state.name = \"partition-\" + to_string(id);\n  self->state.id = id;\n  self->state.offset = invalid_id;\n  self->state.events = 0;\n  self->state.filesystem = std::move(filesystem);\n  self->state.streaming_initiated = false;\n  self->state.synopsis = std::make_shared<partition_synopsis>();\n  self->state.synopsis_opts = std::move(synopsis_opts);\n  self->state.store_id = store_id;\n  self->state.store_header = std::move(header);\n  put(self->state.synopsis_opts, \"buffer-input-data\", true);\n  self->state.partition_local_stores = store_id != \"archive\";\n  self->state.store = std::move(store);\n  \/\/ The active partition stage is a caf stream stage that takes\n  \/\/ a stream of `table_slice` as input and produces several\n  \/\/ streams of `table_slice_column` as output.\n  self->state.stage = detail::attach_notifying_stream_stage(\n    self, true,\n    [=](caf::unit_t&) {\n      \/\/ nop\n    },\n    [=](caf::unit_t&, caf::downstream<table_slice_column>& out, table_slice x) {\n      VAST_TRACE_SCOPE(\"partition {} got table slice {} {}\", self->state.id,\n                       VAST_ARG(out), VAST_ARG(x));\n      \/\/ We rely on `invalid_id` actually being the highest possible id\n      \/\/ when using `min()` below.\n      static_assert(invalid_id == std::numeric_limits<vast::id>::max());\n      auto first = x.offset();\n      auto last = x.offset() + x.rows();\n      auto layout = flatten(x.layout());\n      auto it = self->state.type_ids.emplace(layout.name(), ids{}).first;\n      auto& ids = it->second;\n      VAST_ASSERT(first >= ids.size());\n      \/\/ Mark the ids of this table slice for the current type.\n      ids.append_bits(false, first - ids.size());\n      ids.append_bits(true, last - first);\n      self->state.offset = std::min(x.offset(), self->state.offset);\n      self->state.events += x.rows();\n      self->state.synopsis->add(x, self->state.synopsis_opts);\n      size_t col = 0;\n      VAST_ASSERT(!layout.fields.empty());\n      for (auto& field : layout.fields) {\n        auto qf = qualified_record_field{layout.name(), field};\n        auto& idx = self->state.indexers[qf];\n        if (!idx) {\n          self->state.combined_layout.fields.push_back(as_record_field(qf));\n          idx = self->spawn(active_indexer, field.type, index_opts);\n          auto slot = self->state.stage->add_outbound_path(idx);\n          self->state.stage->out().set_filter(slot, qf);\n          VAST_DEBUG(\"{} spawned new indexer for field {} at slot {}\", self,\n                     field.name, slot);\n        }\n        out.push(table_slice_column{x, col++, qf});\n      }\n    },\n    [=](caf::unit_t&, const caf::error& err) {\n      VAST_DEBUG(\"active partition {} finalized streaming {}\", id, render(err));\n      \/\/ We get an 'unreachable' error when the stream becomes unreachable\n      \/\/ because the actor was destroyed; in this case the state was already\n      \/\/ destroyed during `local_actor::on_exit()`.\n      if (err && err != caf::exit_reason::unreachable) {\n        VAST_ERROR(\"{} aborts with error: {}\", self, render(err));\n        return;\n      }\n    },\n    \/\/ Every \"outbound path\" has a path_state, which consists of a \"Filter\"\n    \/\/ and a vector of \"T\", the output buffer. In the case of a partition,\n    \/\/ we have:\n    \/\/\n    \/\/   T:      vast::table_slice_column\n    \/\/   Filter: vast::qualified_record_field\n    \/\/   Select: vast::system::partition_selector\n    \/\/\n    \/\/ NOTE: The broadcast_downstream_manager has to iterate over all\n    \/\/ indexers, and compute the qualified record field name for each. A\n    \/\/ specialized downstream manager could optimize this by using e.g. a map\n    \/\/ from qualified record fields to downstream indexers.\n    caf::policy::arg<caf::broadcast_downstream_manager<\n      table_slice_column, vast::qualified_record_field, partition_selector>>{});\n  self->set_exit_handler([=](const caf::exit_msg& msg) {\n    VAST_DEBUG(\"{} received EXIT from {} with reason: {}\", self, msg.source,\n               msg.reason);\n    if (self->state.streaming_initiated\n        && self->state.stage->inbound_paths().empty()) {\n      self->state.stage->out().fan_out_flush();\n      self->state.stage->out().close();\n      self->state.stage->out().force_emit_batches();\n    }\n    \/\/ Delay shutdown if we're currently in the process of persisting.\n    if (self->state.persistence_promise.pending()) {\n      std::call_once(self->state.shutdown_once, [=] {\n        VAST_DEBUG(\"{} delays partition shutdown because it is still \"\n                   \"writing to disk\",\n                   self);\n      });\n      using namespace std::chrono_literals;\n      \/\/ Ideally, we would use a self->delayed_delegate(self, ...) here, but CAF\n      \/\/ does not have this functionality. Since we do not care about the return\n      \/\/ value of the partition outselves, and the handler we delegate to\n      \/\/ already uses a response promise, we send the message anonymously. We\n      \/\/ also need to actor_cast self, since sending an exit message to a typed\n      \/\/ actor without using self->send_exit is not supported.\n      caf::delayed_anon_send(caf::actor_cast<caf::actor>(self), 100ms, msg);\n      return;\n    }\n    VAST_VERBOSE(\"{} shuts down after persisting partition state\", self);\n    \/\/ TODO: We must actor_cast to caf::actor here because 'shutdown' operates\n    \/\/ on 'std::vector<caf::actor>' only. That should probably be generalized\n    \/\/ in the future.\n    auto indexers = std::vector<caf::actor>{};\n    indexers.reserve(self->state.indexers.size());\n    auto copy = std::exchange(self->state.indexers, {});\n    for ([[maybe_unused]] auto&& [qf, indexer] : std::move(copy))\n      indexers.push_back(caf::actor_cast<caf::actor>(std::move(indexer)));\n    shutdown<policy::parallel>(self, std::move(indexers));\n  });\n  return {\n    [self](atom::erase) -> caf::result<atom::done> {\n      \/\/ Erase is sent by the disk monitor to erase this partition\n      \/\/ from disk, but an active partition does not have any files\n      \/\/ on disk, so it should never get selected for deletion.\n      VAST_WARN(\"{} got erase atom as an active partition\", self);\n      return caf::make_error(ec::logic_error, \"can not erase the active \"\n                                              \"partition\");\n    },\n    [self](caf::stream<table_slice> in) {\n      self->state.streaming_initiated = true;\n      return self->state.stage->add_inbound_path(in);\n    },\n    [self](atom::subscribe, atom::flush, const flush_listener_actor& listener) {\n      self->state.add_flush_listener(listener);\n    },\n    [self](atom::persist, const std::filesystem::path& part_dir,\n           const std::filesystem::path& synopsis_dir) {\n      VAST_DEBUG(\"{} got persist atom\", self);\n      \/\/ Ensure that the response promise has not already been initialized.\n      VAST_ASSERT(\n        !static_cast<caf::response_promise&>(self->state.persistence_promise)\n           .source());\n      self->state.persist_path = part_dir;\n      self->state.synopsis_path = synopsis_dir;\n      self->state.persisted_indexers = 0;\n      self->state.persistence_promise\n        = self->make_response_promise<std::shared_ptr<partition_synopsis>>();\n      self->send(self, atom::internal_v, atom::persist_v, atom::resume_v);\n      return self->state.persistence_promise;\n    },\n    [self](atom::internal, atom::persist, atom::resume) {\n      VAST_TRACE(\"{} resumes persist atom {}\", self,\n                 self->state.indexers.size());\n      if (self->state.streaming_initiated\n          && self->state.stage->inbound_paths().empty()) {\n        self->state.stage->out().fan_out_flush();\n        self->state.stage->out().close();\n        self->state.stage->out().force_emit_batches();\n      } else {\n        using namespace std::chrono_literals;\n        self->delayed_send(self, 50ms, atom::internal_v, atom::persist_v,\n                           atom::resume_v);\n        return;\n      }\n      if (self->state.indexers.empty()) {\n        self->state.persistence_promise.deliver(\n          caf::make_error(ec::logic_error, \"partition has no indexers\"));\n        return;\n      }\n      VAST_DEBUG(\"{} sends 'snapshot' to {} indexers\", self,\n                 self->state.indexers.size());\n      for (auto& kv : self->state.indexers) {\n        self->request(kv.second, caf::infinite, atom::snapshot_v)\n          .then(\n            [=](chunk_ptr chunk) {\n              ++self->state.persisted_indexers;\n              if (!self->state.persistence_promise.pending()) {\n                VAST_WARN(\"{} ignores persisted indexer because the \"\n                          \"persistence promise is already fulfilled\",\n                          self);\n                return;\n              }\n              auto sender = self->current_sender()->id();\n              if (!chunk) {\n                VAST_ERROR(\"{} failed to persist indexer {}\", self, sender);\n                self->state.persistence_promise.deliver(caf::make_error(\n                  ec::unspecified, \"failed to persist indexer\", sender));\n                return;\n              }\n              VAST_DEBUG(\"{} got chunk from {}\", self, sender);\n              self->state.chunks.emplace(sender, chunk);\n              if (self->state.persisted_indexers\n                  < self->state.indexers.size()) {\n                VAST_DEBUG(\n                  \"{} waits for more chunks after receiving {} out of {}\", self,\n                  self->state.persisted_indexers, self->state.indexers.size());\n                return;\n              }\n              \/\/ Shrink synopses for addr fields to optimal size.\n              self->state.synopsis->shrink();\n              \/\/ Create the partition flatbuffer.\n              flatbuffers::FlatBufferBuilder builder;\n              auto partition = pack(builder, self->state);\n              if (!partition) {\n                VAST_ERROR(\"{} failed to serialize {} with error: {}\", self,\n                           self->state.name, render(partition.error()));\n                self->state.persistence_promise.deliver(partition.error());\n                return;\n              }\n              VAST_ASSERT(self->state.persist_path);\n              VAST_ASSERT(self->state.synopsis_path);\n              \/\/ Note that this is a performance optimization: We used to store\n              \/\/ the partition synopsis inside the `Partition` flatbuffer, and\n              \/\/ then on startup the index would mmap all partitions and read\n              \/\/ the relevant part of the flatbuffer. However, due to the way\n              \/\/ the flatbuffer file format is structured this still needs three\n              \/\/ random file accesses: At the beginning to read vtable offset\n              \/\/ and file identifier, at the end to read the actual vtable, and\n              \/\/ finally at the actual data. On systems with aggressive\n              \/\/ readahead (ie., btrfs defaults to 4MiB), this can increase the\n              \/\/ i\/o at startup and thus the time to boot by more than 10x.\n              \/\/\n              \/\/ Since the synopsis should be small compared to the actual data,\n              \/\/ we store a redundant copy in the partition itself so we can\n              \/\/ regenerate the synopses as needed. This also means we don't\n              \/\/ need to handle errors here, since VAST can still start\n              \/\/ correctly (if a bit slower) when the write fails.\n              flatbuffers::FlatBufferBuilder synopsis_builder;\n              if (auto ps = pack(synopsis_builder, *self->state.synopsis)) {\n                fbs::PartitionSynopsisBuilder ps_builder(synopsis_builder);\n                ps_builder.add_partition_synopsis_type(\n                  fbs::partition_synopsis::PartitionSynopsis::v0);\n                ps_builder.add_partition_synopsis(ps->Union());\n                auto ps_offset = ps_builder.Finish();\n                fbs::FinishPartitionSynopsisBuffer(synopsis_builder, ps_offset);\n                auto ps_chunk = fbs::release(synopsis_builder);\n                self\n                  ->request(self->state.filesystem, caf::infinite,\n                            atom::write_v, *self->state.synopsis_path, ps_chunk)\n                  .then([=](atom::ok) {}, [=](caf::error) {});\n              }\n              auto fbchunk = fbs::release(builder);\n              VAST_DEBUG(\"{} persists partition with a total size of \"\n                         \"{} bytes\",\n                         self, fbchunk->size());\n              \/\/ TODO: Add a proper timeout.\n              self\n                ->request(self->state.filesystem, caf::infinite, atom::write_v,\n                          *self->state.persist_path, fbchunk)\n                .then(\n                  [=](atom::ok) {\n                    \/\/ Relinquish ownership and send the shrunken synopsis to\n                    \/\/ the index.\n                    self->state.persistence_promise.deliver(\n                      self->state.synopsis);\n                    self->state.synopsis.reset();\n                  },\n                  [=](caf::error e) {\n                    self->state.persistence_promise.deliver(std::move(e));\n                  });\n              return;\n            },\n            [=](caf::error err) {\n              VAST_ERROR(\"{} failed to persist indexer for {} with error: {}\",\n                         self, kv.first.fqn(), render(err));\n              ++self->state.persisted_indexers;\n              if (!self->state.persistence_promise.pending())\n                self->state.persistence_promise.deliver(std::move(err));\n            });\n      }\n    },\n    [self](vast::query query) -> caf::result<atom::done> {\n      \/\/ TODO: We should do a candidate check using `self->state.synopsis` and\n      \/\/ return early if that doesn't yield any results.\n      auto triples = evaluate(self->state, query.expr);\n      if (triples.empty())\n        return atom::done_v;\n      auto eval = self->spawn(evaluator, query.expr, triples);\n      auto rp = self->make_response_promise<atom::done>();\n      self->request(eval, caf::infinite, atom::run_v)\n        .then(\n          [self, rp, query = std::move(query)](const ids& hits) mutable {\n            \/\/ TODO: Use the first path if the expression can be evaluated\n            \/\/ exactly.\n            auto* count = caf::get_if<query::count>(&query.cmd);\n            if (count && count->mode == query::count::estimate) {\n              self->send(count->sink, rank(hits));\n              rp.deliver(atom::done_v);\n            } else {\n              rp.delegate(self->state.store, std::move(query), hits);\n            }\n          },\n          [rp](caf::error& err) mutable {\n            rp.deliver(std::move(err));\n          });\n      return rp;\n    },\n    [self](atom::status,\n           status_verbosity v) -> caf::typed_response_promise<caf::settings> {\n      struct extra_state {\n        size_t memory_usage = 0;\n        void deliver(caf::typed_response_promise<caf::settings>&& promise,\n                     caf::settings&& content) {\n          put(content, \"memory-usage\", memory_usage);\n          promise.deliver(std::move(content));\n        }\n      };\n      auto rs = make_status_request_state<extra_state>(self);\n      auto& indexer_states = put_list(rs->content, \"indexers\");\n      \/\/ Reservation is necessary to make sure the entries don't get relocated\n      \/\/ as the underlying vector grows - `ps` would refer to the wrong memory\n      \/\/ otherwise.\n      const auto timeout = defaults::system::initial_request_timeout \/ 5 * 3;\n      indexer_states.reserve(self->state.indexers.size());\n      for (auto& i : self->state.indexers) {\n        auto& ps = indexer_states.emplace_back().as_dictionary();\n        collect_status(\n          rs, timeout, v, i.second,\n          [rs, v, &ps, &field = i.first](caf::settings& response) {\n            put(ps, \"field\", field.fqn());\n            if (auto s = caf::get_if<caf::config_value::integer>( \/\/\n                  &response, \"memory-usage\"))\n              rs->memory_usage += *s;\n            if (v >= status_verbosity::debug)\n              detail::merge_settings(response, ps, policy::merge_lists::no);\n          },\n          [rs, &ps, &field = i.first](caf::error& err) {\n            VAST_WARN(\"{} failed to retrieve status from {} : {}\", rs->self,\n                      field.fqn(), fmt::to_string(err));\n            put(ps, \"error\", fmt::to_string(err));\n          });\n      }\n      return rs->promise;\n    },\n  };\n}\n\npartition_actor::behavior_type passive_partition(\n  partition_actor::stateful_pointer<passive_partition_state> self, uuid id,\n  store_actor legacy_archive, filesystem_actor filesystem,\n  const std::filesystem::path& path) {\n  self->state.self = self;\n  self->state.path = path;\n  self->state.archive = legacy_archive;\n  auto id_string = to_string(id);\n  VAST_TRACEPOINT(passive_partition_spawned, id_string.c_str());\n  self->set_exit_handler([=](const caf::exit_msg& msg) {\n    VAST_DEBUG(\"{} received EXIT from {} with reason: {}\", self, msg.source,\n               msg.reason);\n    \/\/ Receiving an EXIT message does not need to coincide with the state\n    \/\/ being destructed, so we explicitly clear the vector to release the\n    \/\/ references.\n    \/\/ TODO: We must actor_cast to caf::actor here because 'terminate'\n    \/\/ operates on 'std::vector<caf::actor>' only. That should probably be\n    \/\/ generalized in the future.\n    auto indexers = std::vector<caf::actor>{};\n    indexers.reserve(self->state.indexers.size());\n    for (auto&& indexer : std::exchange(self->state.indexers, {}))\n      indexers.push_back(caf::actor_cast<caf::actor>(std::move(indexer)));\n    if (msg.reason != caf::exit_reason::user_shutdown) {\n      self->quit(msg.reason);\n      return;\n    }\n    \/\/ When the shutdown was requested by the user (as opposed to the partition\n    \/\/ just dropping out of the LRU cache), pro-actively remove the indexers.\n    terminate<policy::parallel>(self, std::move(indexers))\n      .then(\n        [=](atom::done) {\n          VAST_DEBUG(\"{} shut down all indexers successfully\", self);\n          self->quit();\n        },\n        [=](const caf::error& err) {\n          VAST_ERROR(\"{} failed to shut down all indexers: {}\", self,\n                     render(err));\n          self->quit(err);\n        });\n  });\n  \/\/ We send a \"read\" to the fs actor and upon receiving the result deserialize\n  \/\/ the flatbuffer and switch to the \"normal\" partition behavior for responding\n  \/\/ to queries.\n  self->request(filesystem, caf::infinite, atom::mmap_v, path)\n    .then(\n      [=](chunk_ptr chunk) {\n        VAST_TRACE_SCOPE(\"{} {}\", self, VAST_ARG(chunk));\n        VAST_TRACEPOINT(passive_partition_loaded, id_string.c_str());\n        if (self->state.partition_chunk) {\n          VAST_WARN(\"{} ignores duplicate chunk\", self);\n          return;\n        }\n        if (!chunk) {\n          VAST_ERROR(\"{} got invalid chunk\", self);\n          self->quit();\n          return;\n        }\n        \/\/ FlatBuffers <= 1.11 does not correctly use '::flatbuffers::soffset_t'\n        \/\/ over 'soffset_t' in FLATBUFFERS_MAX_BUFFER_SIZE.\n        using ::flatbuffers::soffset_t;\n        if (chunk->size() >= FLATBUFFERS_MAX_BUFFER_SIZE) {\n          VAST_ERROR(\"failed to load partition at {} because its size of {} \"\n                     \"exceeds the \"\n                     \"maximum allowed size of {}\",\n                     path, chunk->size(), FLATBUFFERS_MAX_BUFFER_SIZE);\n          return self->quit();\n        }\n        \/\/ Deserialize chunk from the filesystem actor\n        auto partition = fbs::GetPartition(chunk->data());\n        if (partition->partition_type() != fbs::partition::Partition::v0) {\n          VAST_ERROR(\"{} found partition with invalid version of type: {}\",\n                     self, partition->GetFullyQualifiedName());\n          self->quit();\n          return;\n        }\n        auto partition_v0 = partition->partition_as_v0();\n        self->state.partition_chunk = chunk;\n        self->state.flatbuffer = partition_v0;\n        if (auto error = unpack(*self->state.flatbuffer, self->state)) {\n          VAST_ERROR(\"{} failed to unpack partition: {}\", self, render(error));\n          self->quit(std::move(error));\n          return;\n        }\n        if (self->state.store_id == \"legacy_archive\") {\n          self->state.store = self->state.archive;\n        } else {\n          auto plugin = plugins::find<store_plugin>(self->state.store_id);\n          if (!plugin) {\n            auto error = caf::make_error(ec::format_error,\n                                         \"encountered unhandled store backend\");\n            VAST_ERROR(\"{} encountered unknown store backend '{}'\", self,\n                       self->state.store_id);\n            self->quit(std::move(error));\n            return;\n          }\n          auto store = plugin->make_store(filesystem, self->state.store_header);\n          if (!store) {\n            VAST_ERROR(\"{} failed to spawn store: {}\", self,\n                       render(store.error()));\n            self->quit(caf::make_error(ec::system_error, \"failed to spawn \"\n                                                         \"store\"));\n            return;\n          }\n          self->state.store = *store;\n        }\n        if (id != self->state.id)\n          VAST_WARN(\"{} encountered partition id mismatch: restored {}\"\n                    \"from disk, expected {}\",\n                    self, self->state.id, id);\n        \/\/ Delegate all deferred evaluations now that we have the partition chunk.\n        VAST_DEBUG(\"{} delegates {} deferred evaluations\", self,\n                   self->state.deferred_evaluations.size());\n        for (auto&& [expr, rp] :\n             std::exchange(self->state.deferred_evaluations, {}))\n          rp.delegate(static_cast<partition_actor>(self), std::move(expr));\n      },\n      [=](caf::error err) {\n        VAST_ERROR(\"{} failed to load partition: {}\", self, render(err));\n        \/\/ Deliver the error for all deferred evaluations.\n        for (auto&& [expr, rp] :\n             std::exchange(self->state.deferred_evaluations, {})) {\n          \/\/ Because of a deficiency in the typed_response_promise API, we must\n          \/\/ access the underlying response_promise to deliver the error.\n          caf::response_promise& untyped_rp = rp;\n          untyped_rp.deliver(static_cast<partition_actor>(self), err);\n        }\n        \/\/ Quit the partition.\n        self->quit(std::move(err));\n      });\n  return {\n    [self](vast::query query) -> caf::result<atom::done> {\n      VAST_TRACE_SCOPE(\"{} {}\", self, VAST_ARG(query));\n      if (!self->state.partition_chunk)\n        return std::get<1>(self->state.deferred_evaluations.emplace_back(\n          std::move(query), self->make_response_promise<atom::done>()));\n      \/\/ We can safely assert that if we have the partition chunk already, all\n      \/\/ deferred evaluations were taken care of.\n      VAST_ASSERT(self->state.deferred_evaluations.empty());\n      \/\/ Don't handle queries after we already received an exit message, while\n      \/\/ the terminator is running. Since we require every partition to have at\n      \/\/ least one indexer, we can use this to check.\n      if (self->state.indexers.empty())\n        return caf::make_error(ec::system_error, \"can not handle query because \"\n                                                 \"shutdown was requested\");\n      auto triples = evaluate(self->state, query.expr);\n      if (triples.empty())\n        return atom::done_v;\n      auto eval = self->spawn(evaluator, query.expr, triples);\n      auto rp = self->make_response_promise<atom::done>();\n      self->request(eval, caf::infinite, atom::run_v)\n        .then(\n          [self, rp, query = std::move(query)](const ids& hits) mutable {\n            \/\/ TODO: Use the first path if the expression can be evaluated\n            \/\/ exactly.\n            auto* count = caf::get_if<query::count>(&query.cmd);\n            if (count && count->mode == query::count::estimate) {\n              self->send(count->sink, rank(hits));\n              rp.deliver(atom::done_v);\n            } else {\n              rp.delegate(self->state.store, std::move(query), hits);\n            }\n          },\n          [rp](caf::error& err) mutable {\n            rp.deliver(std::move(err));\n          });\n      return rp;\n    },\n    [self](atom::erase) -> caf::result<atom::done> {\n      VAST_WARN(\"erasing partition {} from path\", self->state.id,\n                self->state.path);\n      std::error_code err{};\n      std::filesystem::remove_all(self->state.path, err);\n      if (err)\n        VAST_WARN(\"{} could not erase partition at\", self, self->state.path);\n      vast::ids all_ids;\n      for (const auto& kv : self->state.type_ids) {\n        all_ids |= kv.second;\n      }\n      query q;\n      q.cmd = query::erase{};\n      return self->delegate(self->state.store, atom::erase_v,\n                            std::move(all_ids));\n    },\n    [self](atom::status,\n           status_verbosity \/*v*\/) -> caf::config_value::dictionary {\n      caf::settings result;\n      caf::put(result, \"size\", self->state.partition_chunk->size());\n      size_t mem_indexers = 0;\n      for (size_t i = 0; i < self->state.indexers.size(); ++i) {\n        if (self->state.indexers[i])\n          mem_indexers += sizeof(indexer_state)\n                          + self->state.flatbuffer->indexes()\n                              ->Get(i)\n                              ->index()\n                              ->data()\n                              ->size();\n      }\n      caf::put(result, \"memory-usage-indexers\", mem_indexers);\n      auto x = self->state.partition_chunk->incore();\n      if (!x) {\n        caf::put(result, \"memory-usage-incore\", render(x.error()));\n        caf::put(result, \"memory-usage\",\n                 self->state.partition_chunk->size() + mem_indexers\n                   + sizeof(self->state));\n      } else {\n        caf::put(result, \"memory-usage-incore\", *x);\n        caf::put(result, \"memory-usage\",\n                 *x + mem_indexers + sizeof(self->state));\n      }\n      return result;\n    },\n  };\n}\n\n} \/\/ namespace vast::system\n","avg_line_length":43.7643979058,"max_line_length":82,"alphanum_fraction":0.614260079,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":19200,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"main.h\"\n#include \"db.h\"\n#include \"txdb.h\"\n#include \"init.h\"\n#include \"miner.h\"\n#include \"bitcoinrpc.h\"\n\nusing namespace json_spirit;\nusing namespace std;\n\nValue getsubsidy(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() > 1)\n        throw runtime_error(\n            \"getsubsidy [nTarget]\\n\"\n            \"Returns proof-of-work subsidy value for the specified value of target.\");\n\n    return (uint64_t)GetProofOfWorkReward(0);\n}\n\nValue getmininginfo(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 0)\n        throw runtime_error(\n            \"getmininginfo\\n\"\n            \"Returns an object containing mining-related information.\");\n\n    uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;\n    pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);\n\n    Object obj, diff, weight;\n    obj.push_back(Pair(\"blocks\",        (int)nBestHeight));\n    obj.push_back(Pair(\"currentblocksize\",(uint64_t)nLastBlockSize));\n    obj.push_back(Pair(\"currentblocktx\",(uint64_t)nLastBlockTx));\n\n    diff.push_back(Pair(\"proof-of-work\",        GetDifficulty()));\n    diff.push_back(Pair(\"proof-of-stake\",       GetDifficulty(GetLastBlockIndex(pindexBest, true))));\n    diff.push_back(Pair(\"search-interval\",      (int)nLastCoinStakeSearchInterval));\n    obj.push_back(Pair(\"difficulty\",    diff));\n\n    obj.push_back(Pair(\"blockvalue\",    (uint64_t)GetProofOfWorkReward(0)));\n    obj.push_back(Pair(\"netmhashps\",     GetPoWMHashPS()));\n    obj.push_back(Pair(\"netstakeweight\", GetPoSKernelPS()));\n    obj.push_back(Pair(\"errors\",        GetWarnings(\"statusbar\")));\n    obj.push_back(Pair(\"pooledtx\",      (uint64_t)mempool.size()));\n\n    weight.push_back(Pair(\"minimum\",    (uint64_t)nMinWeight));\n    weight.push_back(Pair(\"maximum\",    (uint64_t)nMaxWeight));\n    weight.push_back(Pair(\"combined\",  (uint64_t)nWeight));\n    obj.push_back(Pair(\"stakeweight\", weight));\n\n    obj.push_back(Pair(\"stakeinterest\",    (uint64_t)COIN_YEAR_REWARD));\n    obj.push_back(Pair(\"testnet\",       fTestNet));\n    return obj;\n}\n\nValue getstakinginfo(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 0)\n        throw runtime_error(\n            \"getstakinginfo\\n\"\n            \"Returns an object containing staking-related information.\");\n\n    uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;\n    pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);\n\n    uint64_t nNetworkWeight = GetPoSKernelPS();\n    bool staking = nLastCoinStakeSearchInterval && nWeight;\n    int nExpectedTime = staking ? (nTargetSpacing * nNetworkWeight \/ nWeight) : -1;\n\n    Object obj;\n\n    obj.push_back(Pair(\"enabled\", GetBoolArg(\"-staking\", true)));\n    obj.push_back(Pair(\"staking\", staking));\n    obj.push_back(Pair(\"errors\", GetWarnings(\"statusbar\")));\n\n    obj.push_back(Pair(\"currentblocksize\", (uint64_t)nLastBlockSize));\n    obj.push_back(Pair(\"currentblocktx\", (uint64_t)nLastBlockTx));\n    obj.push_back(Pair(\"pooledtx\", (uint64_t)mempool.size()));\n\n    obj.push_back(Pair(\"difficulty\", GetDifficulty(GetLastBlockIndex(pindexBest, true))));\n    obj.push_back(Pair(\"search-interval\", (int)nLastCoinStakeSearchInterval));\n\n    obj.push_back(Pair(\"weight\", (uint64_t)nWeight));\n    obj.push_back(Pair(\"netstakeweight\", (uint64_t)nNetworkWeight));\n\n    obj.push_back(Pair(\"expectedtime\", nExpectedTime));\n\n    return obj;\n}\n\nValue getworkex(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() > 2)\n        throw runtime_error(\n            \"getworkex [data, coinbase]\\n\"\n            \"If [data, coinbase] is not specified, returns extended work data.\\n\"\n        );\n\n    if (vNodes.empty())\n        throw JSONRPCError(-9, \"BitchCoin is not connected!\");\n\n    if (IsInitialBlockDownload())\n        throw JSONRPCError(-10, \"BitchCoin is downloading blocks...\");\n\n    if (pindexBest->nHeight >= LAST_POW_BLOCK)\n        throw JSONRPCError(RPC_MISC_ERROR, \"No more PoW blocks\");\n\n    typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;\n    static mapNewBlock_t mapNewBlock;\n    static vector<CBlock*> vNewBlock;\n    static CReserveKey reservekey(pwalletMain);\n\n    if (params.size() == 0)\n    {\n        \/\/ Update block\n        static unsigned int nTransactionsUpdatedLast;\n        static CBlockIndex* pindexPrev;\n        static int64_t nStart;\n        static CBlock* pblock;\n        if (pindexPrev != pindexBest ||\n            (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))\n        {\n            if (pindexPrev != pindexBest)\n            {\n                \/\/ Deallocate old blocks since they're obsolete now\n                mapNewBlock.clear();\n                BOOST_FOREACH(CBlock* pblock, vNewBlock)\n                    delete pblock;\n                vNewBlock.clear();\n            }\n            nTransactionsUpdatedLast = nTransactionsUpdated;\n            pindexPrev = pindexBest;\n            nStart = GetTime();\n\n            \/\/ Create new block\n            pblock = CreateNewBlock(pwalletMain);\n            if (!pblock)\n                throw JSONRPCError(-7, \"Out of memory\");\n            vNewBlock.push_back(pblock);\n        }\n\n        \/\/ Update nTime\n        pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, GetAdjustedTime());\n        pblock->nNonce = 0;\n\n        \/\/ Update nExtraNonce\n        static unsigned int nExtraNonce = 0;\n        IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);\n\n        \/\/ Save\n        mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);\n\n        \/\/ Prebuild hash buffers\n        char pmidstate[32];\n        char pdata[128];\n        char phash1[64];\n        FormatHashBuffers(pblock, pmidstate, pdata, phash1);\n\n        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();\n\n        CTransaction coinbaseTx = pblock->vtx[0];\n        std::vector<uint256> merkle = pblock->GetMerkleBranch(0);\n\n        Object result;\n        result.push_back(Pair(\"data\",     HexStr(BEGIN(pdata), END(pdata))));\n        result.push_back(Pair(\"target\",   HexStr(BEGIN(hashTarget), END(hashTarget))));\n\n        CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);\n        ssTx << coinbaseTx;\n        result.push_back(Pair(\"coinbase\", HexStr(ssTx.begin(), ssTx.end())));\n\n        Array merkle_arr;\n\n        BOOST_FOREACH(uint256 merkleh, merkle) {\n            merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));\n        }\n\n        result.push_back(Pair(\"merkle\", merkle_arr));\n\n\n        return result;\n    }\n    else\n    {\n        \/\/ Parse parameters\n        vector<unsigned char> vchData = ParseHex(params[0].get_str());\n        vector<unsigned char> coinbase;\n\n        if(params.size() == 2)\n            coinbase = ParseHex(params[1].get_str());\n\n        if (vchData.size() != 128)\n            throw JSONRPCError(-8, \"Invalid parameter\");\n\n        CBlock* pdata = (CBlock*)&vchData[0];\n\n        \/\/ Byte reverse\n        for (int i = 0; i < 128\/4; i++)\n            ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);\n\n        \/\/ Get saved block\n        if (!mapNewBlock.count(pdata->hashMerkleRoot))\n            return false;\n        CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;\n\n        pblock->nTime = pdata->nTime;\n        pblock->nNonce = pdata->nNonce;\n\n        if(coinbase.size() == 0)\n            pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;\n        else\n            CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; \/\/ FIXME - HACK!\n\n        pblock->hashMerkleRoot = pblock->BuildMerkleTree();\n\n        return CheckWork(pblock, *pwalletMain, reservekey);\n    }\n}\n\n\nValue getwork(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() > 1)\n        throw runtime_error(\n            \"getwork [data]\\n\"\n            \"If [data] is not specified, returns formatted hash data to work on:\\n\"\n            \"  \\\"midstate\\\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\\n\" \/\/ deprecated\n            \"  \\\"data\\\" : block data\\n\"\n            \"  \\\"hash1\\\" : formatted hash buffer for second hash (DEPRECATED)\\n\" \/\/ deprecated\n            \"  \\\"target\\\" : little endian hash target\\n\"\n            \"If [data] is specified, tries to solve the block and returns true if it was successful.\");\n\n    if (vNodes.empty())\n        throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, \"BitchCoin is not connected!\");\n\n    if (IsInitialBlockDownload())\n        throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, \"BitchCoin is downloading blocks...\");\n\n    if (pindexBest->nHeight >= LAST_POW_BLOCK)\n        throw JSONRPCError(RPC_MISC_ERROR, \"No more PoW blocks\");\n\n    typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;\n    static mapNewBlock_t mapNewBlock;    \/\/ FIXME: thread safety\n    static vector<CBlock*> vNewBlock;\n    static CReserveKey reservekey(pwalletMain);\n\n    if (params.size() == 0)\n    {\n        \/\/ Update block\n        static unsigned int nTransactionsUpdatedLast;\n        static CBlockIndex* pindexPrev;\n        static int64_t nStart;\n        static CBlock* pblock;\n        if (pindexPrev != pindexBest ||\n            (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))\n        {\n            if (pindexPrev != pindexBest)\n            {\n                \/\/ Deallocate old blocks since they're obsolete now\n                mapNewBlock.clear();\n                BOOST_FOREACH(CBlock* pblock, vNewBlock)\n                    delete pblock;\n                vNewBlock.clear();\n            }\n\n            \/\/ Clear pindexPrev so future getworks make a new block, despite any failures from here on\n            pindexPrev = NULL;\n\n            \/\/ Store the pindexBest used before CreateNewBlock, to avoid races\n            nTransactionsUpdatedLast = nTransactionsUpdated;\n            CBlockIndex* pindexPrevNew = pindexBest;\n            nStart = GetTime();\n\n            \/\/ Create new block\n            pblock = CreateNewBlock(pwalletMain);\n            if (!pblock)\n                throw JSONRPCError(RPC_OUT_OF_MEMORY, \"Out of memory\");\n            vNewBlock.push_back(pblock);\n\n            \/\/ Need to update only after we know CreateNewBlock succeeded\n            pindexPrev = pindexPrevNew;\n        }\n\n        \/\/ Update nTime\n        pblock->UpdateTime(pindexPrev);\n        pblock->nNonce = 0;\n\n        \/\/ Update nExtraNonce\n        static unsigned int nExtraNonce = 0;\n        IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);\n\n        \/\/ Save\n        mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);\n\n        \/\/ Pre-build hash buffers\n        char pmidstate[32];\n        char pdata[128];\n        char phash1[64];\n        FormatHashBuffers(pblock, pmidstate, pdata, phash1);\n\n        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();\n\n        Object result;\n        result.push_back(Pair(\"midstate\", HexStr(BEGIN(pmidstate), END(pmidstate)))); \/\/ deprecated\n        result.push_back(Pair(\"data\",     HexStr(BEGIN(pdata), END(pdata))));\n        result.push_back(Pair(\"hash1\",    HexStr(BEGIN(phash1), END(phash1)))); \/\/ deprecated\n        result.push_back(Pair(\"target\",   HexStr(BEGIN(hashTarget), END(hashTarget))));\n        return result;\n    }\n    else\n    {\n        \/\/ Parse parameters\n        vector<unsigned char> vchData = ParseHex(params[0].get_str());\n        if (vchData.size() != 128)\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid parameter\");\n        CBlock* pdata = (CBlock*)&vchData[0];\n\n        \/\/ Byte reverse\n        for (int i = 0; i < 128\/4; i++)\n            ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);\n\n        \/\/ Get saved block\n        if (!mapNewBlock.count(pdata->hashMerkleRoot))\n            return false;\n        CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;\n\n        pblock->nTime = pdata->nTime;\n        pblock->nNonce = pdata->nNonce;\n        pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;\n        pblock->hashMerkleRoot = pblock->BuildMerkleTree();\n\n        return CheckWork(pblock, *pwalletMain, reservekey);\n    }\n}\n\n\nValue getblocktemplate(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() > 1)\n        throw runtime_error(\n            \"getblocktemplate [params]\\n\"\n            \"Returns data needed to construct a block to work on:\\n\"\n            \"  \\\"version\\\" : block version\\n\"\n            \"  \\\"previousblockhash\\\" : hash of current highest block\\n\"\n            \"  \\\"transactions\\\" : contents of non-coinbase transactions that should be included in the next block\\n\"\n            \"  \\\"coinbaseaux\\\" : data that should be included in coinbase\\n\"\n            \"  \\\"coinbasevalue\\\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\\n\"\n            \"  \\\"target\\\" : hash target\\n\"\n            \"  \\\"mintime\\\" : minimum timestamp appropriate for next block\\n\"\n            \"  \\\"curtime\\\" : current timestamp\\n\"\n            \"  \\\"mutable\\\" : list of ways the block template may be changed\\n\"\n            \"  \\\"noncerange\\\" : range of valid nonces\\n\"\n            \"  \\\"sigoplimit\\\" : limit of sigops in blocks\\n\"\n            \"  \\\"sizelimit\\\" : limit of block size\\n\"\n            \"  \\\"bits\\\" : compressed target of next block\\n\"\n            \"  \\\"height\\\" : height of the next block\\n\"\n            \"See https:\/\/en.bitcoin.it\/wiki\/BIP_0022 for full specification.\");\n\n    std::string strMode = \"template\";\n    if (params.size() > 0)\n    {\n        const Object& oparam = params[0].get_obj();\n        const Value& modeval = find_value(oparam, \"mode\");\n        if (modeval.type() == str_type)\n            strMode = modeval.get_str();\n        else if (modeval.type() == null_type)\n        {\n            \/* Do nothing *\/\n        }\n        else\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid mode\");\n    }\n\n    if (strMode != \"template\")\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid mode\");\n\n    if (vNodes.empty())\n        throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, \"BitchCoin is not connected!\");\n\n    if (IsInitialBlockDownload())\n        throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, \"BitchCoin is downloading blocks...\");\n\n    if (pindexBest->nHeight >= LAST_POW_BLOCK)\n        throw JSONRPCError(RPC_MISC_ERROR, \"No more PoW blocks\");\n\n    static CReserveKey reservekey(pwalletMain);\n\n    \/\/ Update block\n    static unsigned int nTransactionsUpdatedLast;\n    static CBlockIndex* pindexPrev;\n    static int64_t nStart;\n    static CBlock* pblock;\n    if (pindexPrev != pindexBest ||\n        (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))\n    {\n        \/\/ Clear pindexPrev so future calls make a new block, despite any failures from here on\n        pindexPrev = NULL;\n\n        \/\/ Store the pindexBest used before CreateNewBlock, to avoid races\n        nTransactionsUpdatedLast = nTransactionsUpdated;\n        CBlockIndex* pindexPrevNew = pindexBest;\n        nStart = GetTime();\n\n        \/\/ Create new block\n        if(pblock)\n        {\n            delete pblock;\n            pblock = NULL;\n        }\n        pblock = CreateNewBlock(pwalletMain);\n        if (!pblock)\n            throw JSONRPCError(RPC_OUT_OF_MEMORY, \"Out of memory\");\n\n        \/\/ Need to update only after we know CreateNewBlock succeeded\n        pindexPrev = pindexPrevNew;\n    }\n\n    \/\/ Update nTime\n    pblock->UpdateTime(pindexPrev);\n    pblock->nNonce = 0;\n\n    Array transactions;\n    map<uint256, int64_t> setTxIndex;\n    int i = 0;\n    CTxDB txdb(\"r\");\n    BOOST_FOREACH (CTransaction& tx, pblock->vtx)\n    {\n        uint256 txHash = tx.GetHash();\n        setTxIndex[txHash] = i++;\n\n        if (tx.IsCoinBase() || tx.IsCoinStake())\n            continue;\n\n        Object entry;\n\n        CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);\n        ssTx << tx;\n        entry.push_back(Pair(\"data\", HexStr(ssTx.begin(), ssTx.end())));\n\n        entry.push_back(Pair(\"hash\", txHash.GetHex()));\n\n        MapPrevTx mapInputs;\n        map<uint256, CTxIndex> mapUnused;\n        bool fInvalid = false;\n        if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))\n        {\n            entry.push_back(Pair(\"fee\", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));\n\n            Array deps;\n            BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)\n            {\n                if (setTxIndex.count(inp.first))\n                    deps.push_back(setTxIndex[inp.first]);\n            }\n            entry.push_back(Pair(\"depends\", deps));\n\n            int64_t nSigOps = tx.GetLegacySigOpCount();\n            nSigOps += tx.GetP2SHSigOpCount(mapInputs);\n            entry.push_back(Pair(\"sigops\", nSigOps));\n        }\n\n        transactions.push_back(entry);\n    }\n\n    Object aux;\n    aux.push_back(Pair(\"flags\", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));\n\n    uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();\n\n    static Array aMutable;\n    if (aMutable.empty())\n    {\n        aMutable.push_back(\"time\");\n        aMutable.push_back(\"transactions\");\n        aMutable.push_back(\"prevblock\");\n    }\n\n    Object result;\n    result.push_back(Pair(\"version\", pblock->nVersion));\n    result.push_back(Pair(\"previousblockhash\", pblock->hashPrevBlock.GetHex()));\n    result.push_back(Pair(\"transactions\", transactions));\n    result.push_back(Pair(\"coinbaseaux\", aux));\n    result.push_back(Pair(\"coinbasevalue\", (int64_t)pblock->vtx[0].vout[0].nValue));\n    result.push_back(Pair(\"target\", hashTarget.GetHex()));\n    result.push_back(Pair(\"mintime\", (int64_t)pindexPrev->GetPastTimeLimit()+1));\n    result.push_back(Pair(\"mutable\", aMutable));\n    result.push_back(Pair(\"noncerange\", \"00000000ffffffff\"));\n    result.push_back(Pair(\"sigoplimit\", (int64_t)MAX_BLOCK_SIGOPS));\n    result.push_back(Pair(\"sizelimit\", (int64_t)MAX_BLOCK_SIZE));\n    result.push_back(Pair(\"curtime\", (int64_t)pblock->nTime));\n    result.push_back(Pair(\"bits\", strprintf(\"%08x\", pblock->nBits)));\n    result.push_back(Pair(\"height\", (int64_t)(pindexPrev->nHeight+1)));\n\n    return result;\n}\n\nValue submitblock(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() < 1 || params.size() > 2)\n        throw runtime_error(\n            \"submitblock <hex data> [optional-params-obj]\\n\"\n            \"[optional-params-obj] parameter is currently ignored.\\n\"\n            \"Attempts to submit new block to network.\\n\"\n            \"See https:\/\/en.bitcoin.it\/wiki\/BIP_0022 for full specification.\");\n\n    vector<unsigned char> blockData(ParseHex(params[0].get_str()));\n    CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);\n    CBlock block;\n    try {\n        ssBlock >> block;\n    }\n    catch (std::exception &e) {\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"Block decode failed\");\n    }\n\n    bool fAccepted = ProcessBlock(NULL, &block);\n    if (!fAccepted)\n        return \"rejected\";\n\n    return Value::null;\n}\n\n","avg_line_length":36.2948960302,"max_line_length":138,"alphanum_fraction":0.6251041667,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":16821,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":4.0,"content":"\ufeff#include \"stdafx.h\"\n#include \"ZipArchive.h\"\n#include <assert.h>\n\n#ifndef __cplusplus\n#error ZipArchive requires C++ compilation (use a .cpp suffix)\n#endif\n\n#ifdef ZIP_WILDCARD\n#include <shlwapi.h>\n#pragma comment(lib, \"shlwapi.lib\")\n#endif\n\n\/\/ Include ZLIB stuff. ZLIB is maintained by Jean-loup Gailly and Mark Adler.\n\/\/ It is a general GZIP and PKZIP compatible compression library.\n#include <zconf.h>\n#include <zlib.h>\n\n#include <crtdbg.h>\n#include <tchar.h>\n#include <malloc.h>\n\n\nCZipFile::CZipFile(DWORD dwSize\/*=0*\/)\n\t\t: m_pData(NULL),\n\t\tm_dwSize(0),\n\t\tm_dwPos(0)\n\t{\n#ifdef ZLIB_DECRYPTION\n\t\tm_pCrcTable = NULL;\n#endif\n\t\tif(dwSize!=0)\n\t\t{\n\t\t\tm_pData=new BYTE[dwSize];\n\t\t\tm_dwSize=dwSize;\n\t\t}\n\t}\n\tCZipFile::~CZipFile()\n\t{\n\t\tClose();\n\t}\n\tBOOL CZipFile::Read(void* pBuffer, DWORD dwSize, LPDWORD pdwRead\/* = NULL*\/)\n\t{\n\t\t_ASSERTE(IsOpen());\n\n\t\tif (pdwRead != NULL)\n\t\t\t*pdwRead = 0;\n\t\tif (m_pData == NULL)\n\t\t\treturn FALSE;\n\t\tif (dwSize == 0 || m_dwPos >= m_dwSize)\n\t\t\treturn FALSE;\n\n\t\tif (m_dwPos + dwSize > m_dwSize)\n\t\t\tdwSize = m_dwSize - m_dwPos;\n\t\t::CopyMemory(pBuffer, m_pData + m_dwPos, dwSize);\n\t\tm_dwPos += dwSize;\n\t\tif (pdwRead != NULL)\n\t\t\t*pdwRead = dwSize;\n\n\t\treturn TRUE;\n\t}\n\tBOOL CZipFile::Close()\n\t{\n\t\tif (m_pData == NULL)\n\t\t\treturn TRUE;\n\n\t\tdelete[] m_pData;\n\t\tm_pData = NULL;\n\t\tm_dwSize = 0;\n\t\tm_dwPos = 0;\n\n\t\treturn TRUE;\n\t}\n\tBOOL CZipFile::IsOpen() const \n\t{\n\t\treturn m_pData != NULL;\n\t}\n\tBYTE* CZipFile::GetData() const\n\t{\n\t\t_ASSERTE(IsOpen());\n\t\treturn m_pData;\n\t}\n\tDWORD CZipFile::GetSize() const\n\t{\n\t\t_ASSERTE(IsOpen());\n\t\treturn m_dwSize;\n\t}\n\tDWORD CZipFile::GetPosition() const\n\t{\n\t\t_ASSERTE(IsOpen());\n\t\treturn m_dwPos;\n\t}\n\tDWORD CZipFile::Seek(DWORD dwOffset, UINT nFrom)\t\/\/\treturn old pos\n\t{\n\t\t_ASSERTE(IsOpen());\n\t\tDWORD dwPos = m_dwPos;\n\t\tswitch (nFrom)\n\t\t{\n\t\tcase FILE_BEGIN:\n\t\t\tm_dwPos = dwOffset;\n\t\t\tbreak;\n\t\tcase FILE_END:\n\t\t\tm_dwPos = m_dwSize + dwOffset;\n\t\t\tbreak;\n\t\tcase FILE_CURRENT:\n\t\t\tm_dwPos += dwOffset;\n\t\t\tbreak;\n\t\t}\n\t\tif (m_dwPos < 0)\n\t\t\tm_dwPos = 0;\n\t\tif (m_dwPos >= m_dwSize)\n\t\t\tm_dwPos = m_dwSize;\n\t\treturn dwPos;\n\t}\n\n#ifdef ZLIB_DECRYPTION\n\tBOOL CZipFile::_DecryptFile(LPCSTR pstrPassword, LPBYTE& pData, DWORD& dwSize, DWORD crc32)\n\t{\n\t\t_ASSERTE(pData);\n\t\t_ASSERTE(!::IsBadStringPtrA(pstrPassword, -1));\n\n\t\tif (!_InitKeys(pstrPassword))\n\t\t\treturn FALSE;\n\t\tif (!_DecryptHeader(pData, dwSize, crc32))\n\t\t\treturn FALSE;\n\t\tif (!_DecryptData(pData, dwSize))\n\t\t\treturn FALSE;\n\n\t\treturn TRUE;\n\t}\n\n\tBOOL CZipFile::_InitKeys(LPCSTR pstrPassword)\n\t{\n\t\tm_pCrcTable = get_crc_table();\n\t\tm_dwKey[0] = 305419896;\n\t\tm_dwKey[1] = 591751049;\n\t\tm_dwKey[2] = 878082192;\n\n\t\tint nLen = ::lstrlenA(pstrPassword);\n\t\tif (nLen == 0)\n\t\t\treturn FALSE;\n\n\t\tfor(int i = 0; i < nLen; i++)\n\t\t\t_UpdateKeys(pstrPassword[i]);\n\n\t\treturn TRUE;\n\t}\n\tvoid CZipFile::_UpdateKeys(BYTE c)\n\t{      \n\t\tm_dwKey[0] = _crc32(m_dwKey[0], c);\n\t\tm_dwKey[1] = m_dwKey[1] + (m_dwKey[0] & 0x000000FF);\n\t\tm_dwKey[1] = m_dwKey[1] * 134775813 + 1;\n\t\tBYTE b = (BYTE) (m_dwKey[1] >> 24);\n\t\tm_dwKey[2] = _crc32(m_dwKey[2], b);\n\t}\n\n    DWORD CZipFile::_crc32( DWORD c, BYTE b )\n    {\n        assert(m_pCrcTable);\n        return m_pCrcTable[((DWORD) (c) ^ (b)) & 0xFF] ^ ((c) >> 8);\n    }\n\n\tBOOL CZipFile::_DecryptHeader(LPBYTE pData, DWORD dwSize, DWORD crc32)\n\t{\n\t\tif (dwSize < 12)\n\t\t\treturn FALSE;\n\n\t\tBYTE header[12];\n\t\t::CopyMemory(&header, pData, 12);\n\t\tfor(int i = 0; i < 12; i++)\n\t\t{\n\t\t\tBYTE c = (BYTE)(header[i] ^ _DecryptByte());\n\t\t\t_UpdateKeys(c);\n\t\t\theader[i] = c;\n\t\t}\n\n\t\t\/\/ Password check\n\t\treturn header[11] == (BYTE)(crc32 >> 24);\n\t}\n\n    BYTE CZipFile::_DecryptByte() const\n    {\n        DWORD temp = (WORD) (m_dwKey[2] | 2);\n        return (BYTE)((temp * (temp ^ 1)) >> 8);\n    }\n\n\tBOOL CZipFile::_DecryptData(LPBYTE& pData, DWORD& dwSize)\n\t{\n\t\tLPBYTE pRawData;\n\t\tpRawData = new BYTE[dwSize - 12];\n\t\t_ASSERTE(pRawData);\n\n\t\tif (pRawData == NULL)\n\t\t\treturn FALSE;\n\n\t\tLPBYTE p = pRawData;\n\t\tfor(DWORD i = 12; i < dwSize; i++)\n\t\t{\n\t\t\tBYTE c = (BYTE) (pData[i] ^ _DecryptByte());\n\t\t\t_UpdateKeys(c);\n\t\t\t*p++ = c;\n\t\t}\n\n\t\tdelete[] pData;\n\t\tpData = pRawData;\n\t\tdwSize -= 12;\n\n\t\treturn TRUE;\n\t}\n#endif\t\/\/\tZLIB_DECRYPTION\n\n\tBOOL CZipFile::Attach(LPBYTE pData, DWORD dwSize)\n\t{\n\t\tif(m_pData) return FALSE;\n\t\t_ASSERTE(pData);\n\t\t_ASSERTE(!::IsBadReadPtr(pData,dwSize));\n\n\t\tm_pData = pData;\n\t\tm_dwSize = dwSize;\n\t\treturn TRUE;\n\t}\n\n\tvoid CZipFile::Detach()\n\t{\n\t\tm_pData = NULL;\n\t\tm_dwSize = 0;\n\t\tm_dwPos = 0;\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/CZipArchive\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\n\tCZipArchive::CZipArchive()\n\t\t: m_hFile(INVALID_HANDLE_VALUE),\n\t\tm_Files(NULL),\n\t\tm_DirData(NULL)\n\t{\n\t\tmemset(&m_Header, 0, sizeof(m_Header));\n\t}\n\tCZipArchive::~CZipArchive()\n\t{\n\t\tClose();\n\t}\n\n\tBOOL CZipArchive::OpenZip()\n\t{\n\t\t_ASSERTE(m_hFile);\n\n\t\tSeekFile(-(LONG)sizeof(m_Header), FILE_END);\n\n\t\tDWORD dwRead = ReadFile(&m_Header, sizeof(m_Header));\n\t\t_ASSERTE(dwRead == sizeof(m_Header));\n\n\t\tif (dwRead != sizeof(m_Header) || m_Header.sig != DIR_SIGNATURE)\n\t\t{\n\t\t\tClose();\n\t\t\treturn FALSE;\n\t\t}\n\n\t\t_ASSERTE(m_Header.nDirEntries < 1000); \/\/ Sanity check\n\n\t\tm_DirData = (LPBYTE)malloc(m_Header.dirSize);\n\t\t_ASSERTE(m_DirData);\n\n\t\tm_Files = new ZipDirFileHeader*[m_Header.nDirEntries];\n\t\t_ASSERTE(m_Files);\n\n\t\tif (m_Files == NULL || m_DirData == NULL)\n\t\t{\n\t\t\tClose();\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tSeekFile(-(LONG)(sizeof(m_Header) + m_Header.dirSize), FILE_END);\n\n\t\tdwRead = ReadFile(m_DirData, m_Header.dirSize);\n\t\t_ASSERTE(dwRead == m_Header.dirSize);\n\n\t\tif (dwRead != m_Header.dirSize)\n\t\t{\n\t\t\tClose();\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tLPBYTE pData = m_DirData;\n\t\tfor (int i = 0; i < m_Header.nDirEntries; i++)\n\t\t{\n\t\t\t\/\/ Set the header pointer in the m_Files array\n\t\t\tZipDirFileHeader* fh = (ZipDirFileHeader*) pData;\n\t\t\tm_Files[i] = fh;\n\t\t\tif (fh->sig != FILE_SIGNATURE)\n\t\t\t{\n\t\t\t\tClose();\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\t\/\/ Convert UNIX slash to Windows backslash in ANSI string\n\t\t\tLPSTR pszName = fh->GetName();\n\t\t\tfor(int j = 0; j < fh->fnameLen; j++, pszName++)\n\t\t\t\tif (*pszName == '\/')\n\t\t\t\t\t*pszName='\\\\';\n\n\t\t\t\/\/ Get next header\n\t\t\tpData += sizeof(ZipDirFileHeader) + fh->fnameLen + fh->xtraLen + fh->cmntLen;\n\t\t}\n\n\t\tm_szPassword[0] = '\\0';\n\n\t\treturn TRUE;\n\t}\n\tvoid CZipArchive::Close()\n\t{\n\t\tCloseFile();\n\n\t\tif (m_Files != NULL)\n\t\t{\n\t\t\tdelete[] m_Files;\n\t\t\tm_Files = NULL;\n\t\t}\n\t\tif (m_DirData != NULL)\n\t\t{\n\t\t\tfree(m_DirData);\n\t\t\tm_DirData = NULL;\n\t\t}\n\t\tmemset(&m_Header, 0, sizeof(m_Header));\n\t}\n\tBOOL CZipArchive::IsOpen() const\n\t{\n\t\treturn m_hFile != INVALID_HANDLE_VALUE;\n\t}\n\tint CZipArchive::GetEntries() const\n\t{\n\t\treturn m_Header.nDirEntries;\n\t}\n\n\tBOOL CZipArchive::SetPassword(LPCSTR pstrPassword)\n\t{\n        if(!pstrPassword) return FALSE;\n\n\t\tif (::lstrlenA(pstrPassword) >= sizeof(m_szPassword)-1)\n\t\t\treturn FALSE;\n\n\t\t::lstrcpyA(m_szPassword, pstrPassword);\n\t\treturn TRUE;\n\t}\n\n\t\/\/ ZIP File API\n\n\tBOOL CZipArchive::GetFile(LPCTSTR pszFileName, CZipFile& file)\n\t{\n\t\treturn GetFile(GetFileIndex(pszFileName),file);\n\t}\n\n\tBOOL CZipArchive::GetFile2(int iIndex, CZipFile& file)\n\t{\n\t\t_ASSERTE(IsOpen());\n\t\t_ASSERTE(iIndex >= 0 && iIndex < m_Header.nDirEntries);\n\n\t\tif (m_hFile == INVALID_HANDLE_VALUE)\n\t\t\treturn FALSE;\n\t\tif (iIndex < 0 || iIndex >= m_Header.nDirEntries)\n\t\t\treturn FALSE;\n\n\t\tZipLocalHeader hdr;\n\t\tSeekFile(m_Files[iIndex]->hdrOffset, FILE_BEGIN);\n\n\t\tDWORD dwRead = ReadFile(&hdr, sizeof(hdr));\n\t\tif (dwRead != sizeof(hdr))\n\t\t\treturn FALSE;\n\n\t\tif (hdr.sig != LOCAL_SIGNATURE)\n\t\t\treturn FALSE;\n\n\t\tSeekFile(hdr.fnameLen + hdr.xtraLen, FILE_CURRENT);\n\n\t\tDWORD dwSize = hdr.cSize;\n\t\tif (hdr.flag & 1)\n\t\t{\/\/\u8fd9\u4e2a\u63a5\u53e3\u4e0d\u652f\u6301\u52a0\u5bc6\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tswitch (hdr.compression)\n\t\t{\n\t\tcase LOCAL_COMP_STORE:\n\t\t\t_ASSERTE(hdr.cSize == hdr.ucSize);\n\t\t\tdwRead = ReadFile(file.GetData(), hdr.cSize);\n\t\t\treturn dwRead==hdr.cSize;\n\t\tcase LOCAL_COMP_DEFLAT: \n\t\t\t{\n\t\t\t\tif(file.GetSize()<hdr.ucSize) return FALSE;\n\t\t\t\t\/\/ Read Source Data.\n\t\t\t\tLPBYTE pData=new BYTE[hdr.cSize];\n\n\t\t\t\tif (pData == NULL)\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tdwRead = ReadFile(pData, hdr.cSize);\n\t\t\t\tif (dwRead != hdr.cSize)\n\t\t\t\t{\n\t\t\t\t\tdelete[] pData;\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\n\t\t\t\tLPBYTE pTarget=file.GetData();\n\n\t\t\t\tz_stream stream = { 0 };\n\t\t\t\tstream.next_in = (Bytef*) pData;\n\t\t\t\tstream.avail_in = (uInt) hdr.cSize;\n\t\t\t\tstream.next_out = (Bytef*) pTarget;\n\t\t\t\tstream.avail_out = hdr.ucSize;\n\t\t\t\tstream.zalloc = (alloc_func) NULL;\n\t\t\t\tstream.zfree = (free_func) NULL;\n\t\t\t\t\/\/ Perform inflation; wbits < 0 indicates no zlib header inside the data.\n\t\t\t\tint err = inflateInit2(&stream, -MAX_WBITS);\n\t\t\t\tif (err == Z_OK)\n\t\t\t\t{\n\t\t\t\t\terr = inflate(&stream, Z_OK);\n\t\t\t\t\tif (err != Z_OK && err != Z_STREAM_END)\n\t\t\t\t\t\t_ASSERTE(err == Z_OK);\n\t\t\t\t\tinflateEnd(&stream);\n\t\t\t\t\tif (err == Z_STREAM_END)\n\t\t\t\t\t\terr = Z_OK;\n\t\t\t\t\tinflateEnd(&stream);\n\t\t\t\t}\n\n\t\t\t\tdelete[] pData;\n\n\t\t\t\treturn err == Z_OK;\n\t\t\t}\n\t\tdefault:\n\t\t\t_ASSERTE(FALSE); \/\/ unsupported compression scheme\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\n\tBOOL CZipArchive::GetFile(int iIndex, CZipFile& file)\n\t{\n\t\t_ASSERTE(IsOpen());\n\t\t_ASSERTE(iIndex >= 0 && iIndex < m_Header.nDirEntries);\n\n\t\tif (m_hFile == INVALID_HANDLE_VALUE)\n\t\t\treturn FALSE;\n\t\tif (iIndex < 0 || iIndex >= m_Header.nDirEntries)\n\t\t\treturn FALSE;\n\n\t\tZipLocalHeader hdr;\n\t\tSeekFile(m_Files[iIndex]->hdrOffset, FILE_BEGIN);\n\n\t\tDWORD dwRead = ReadFile(&hdr, sizeof(hdr));\n\t\tif (dwRead != sizeof(hdr))\n\t\t\treturn FALSE;\n\n\t\tif (hdr.sig != LOCAL_SIGNATURE)\n\t\t\treturn FALSE;\n\n\t\tSeekFile(hdr.fnameLen + hdr.xtraLen, FILE_CURRENT);\n\n\t\t\/\/ \t\t\/\/ Decompress file if needed.\n\t\tLPBYTE pData;\n\t\tpData = new BYTE[hdr.cSize];\n\n\t\tif (pData == NULL)\n\t\t\treturn FALSE;\n\n\t\tdwRead = ReadFile(pData, hdr.cSize);\n\t\tif (dwRead != hdr.cSize)\n\t\t{\n            delete[] pData;\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tDWORD dwSize = hdr.cSize;\n\t\tif (hdr.flag & 1)\n\t\t{\n#ifdef ZLIB_DECRYPTION\n\t\t\tif (::lstrlenA(m_szPassword) == 0)\n\t\t\t{\n\t\t\t\tdelete[] pData;\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\tif (!file._DecryptFile(m_szPassword, pData, dwSize, hdr.crc32))\n\t\t\t{\n                delete[] pData;\n\t\t\t\treturn FALSE;\n\t\t\t}\n#else\n            delete[] pData;\n\t\t\treturn FALSE;\n#endif\n\t\t}\n\n\t\tswitch (hdr.compression)\n\t\t{\n\t\tcase LOCAL_COMP_STORE:\n\t\t\t\/\/_ASSERTE(hdr.cSize == hdr.ucSize);\/\/\u52a0\u5bc6\u7684\u65f6\u8fd9\u4e24\u4e2a\u503c\u4e0d\u4e00\u5b9a\u76f8\u7b49\n\t\t\tbreak;\n\t\tcase LOCAL_COMP_DEFLAT: \n\t\t\t{\n\t\t\t\tLPBYTE pTarget;\n\t\t\t\tpTarget = new BYTE[hdr.ucSize];\n\t\t\t\t_ASSERTE(pTarget);\n\n\t\t\t\tif (pTarget == NULL)\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tz_stream stream = { 0 };\n\t\t\t\tstream.next_in = (Bytef*) pData;\n\t\t\t\tstream.avail_in = (uInt) hdr.cSize;\n\t\t\t\tstream.next_out = (Bytef*) pTarget;\n\t\t\t\tstream.avail_out = hdr.ucSize;\n\t\t\t\tstream.zalloc = (alloc_func) NULL;\n\t\t\t\tstream.zfree = (free_func) NULL;\n\t\t\t\t\/\/ Perform inflation; wbits < 0 indicates no zlib header inside the data.\n\t\t\t\tint err = inflateInit2(&stream, -MAX_WBITS);\n\t\t\t\tif (err == Z_OK)\n\t\t\t\t{\n\t\t\t\t\terr = inflate(&stream, Z_OK);\n\t\t\t\t\tif (err != Z_OK && err != Z_STREAM_END)\n\t\t\t\t\t\t_ASSERTE(err == Z_OK);\n\t\t\t\t\tinflateEnd(&stream);\n\t\t\t\t\tif (err == Z_STREAM_END)\n\t\t\t\t\t\terr = Z_OK;\n\t\t\t\t\tinflateEnd(&stream);\n\t\t\t\t}\n\n\t\t\t\tdelete[] pData;\n\n\t\t\t\tif (err != Z_OK)\n\t\t\t\t{\n\t\t\t\t\tdelete[] pTarget;\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t\tpData = pTarget;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t_ASSERTE(FALSE); \/\/ unsupported compression scheme\n\t\t\treturn FALSE;\n\t\t}\n\t\t\/\/ The memory we allocated is passed to the file, which\n\t\t\/\/ takes ownership of it.\n\t\tfile.Attach(pData, hdr.ucSize);\n\n\t\treturn TRUE;\n\t}\n\n\t\/\/ FindFile API\n\n\tHANDLE CZipArchive::FindFirstFile(LPCTSTR pszFileName, LPZIP_FIND_DATA lpFindFileData) const\n\t{\n\t\t_ASSERTE(IsOpen());\n\t\t_ASSERTE(!::IsBadWritePtr(lpFindFileData, sizeof(ZIP_FIND_DATA)));\n\n\t\t::ZeroMemory(lpFindFileData, sizeof(ZIP_FIND_DATA));\n\n\t\t_ASSERTE(pszFileName != NULL);\n\t\tif (pszFileName == NULL || pszFileName[0] == '\\0')\n\t\t\treturn INVALID_HANDLE_VALUE;\n\n\t\tFindFileHandle* pFF;\n\t\tpFF = new FindFileHandle;\n\t\tif (pFF == NULL)\n\t\t\treturn INVALID_HANDLE_VALUE;\n\n\t\t::lstrcpy(pFF->szSearch, pszFileName);\n\t\tpFF->nPos = 0;\n\n\t\tBOOL bRet = FindNextFile((HANDLE)pFF, lpFindFileData);\n\t\tif (!bRet)\n\t\t{\n\t\t\tdelete pFF;\n\t\t\treturn INVALID_HANDLE_VALUE;\n\t\t}\n\t\treturn (HANDLE)pFF;\n\t}\n\tBOOL CZipArchive::FindNextFile(HANDLE hFindFile, LPZIP_FIND_DATA lpFindFileData) const\n\t{\n\t\t_ASSERTE(IsOpen());\n\n\t\tif (!IsOpen())\n\t\t\treturn FALSE;\n\t\tif (hFindFile == INVALID_HANDLE_VALUE || hFindFile == NULL)\n\t\t\treturn FALSE;\n\n\t\tFindFileHandle* pFF = reinterpret_cast<FindFileHandle*>(hFindFile);\n\t\twhile (TRUE)\n\t\t{\n\t\t\tif (pFF->nPos >= m_Header.nDirEntries)\n\t\t\t\treturn FALSE;\n\n\t\t\t\/\/ Extract filename and match with pattern\n\t\t\tZipDirFileHeader* fh = m_Files[pFF->nPos];\n\t\t\tTCHAR szFile[MAX_PATH] = { 0 };\n\t\t\t::OemToCharBuff(fh->GetName(), szFile, fh->fnameLen);\n\n#ifdef ZIP_WILDCARD\n\t\t\tif (::PathMatchSpec(szFile, pFF->szSearch) != NULL)\n#else\n\t\t\tif (_tcsicmp(szFile, pFF->szSearch) == 0)\n#endif\n\t\t\t{\n\t\t\t\t\/\/ Copy data to the ZIP_FIND_DATA structure\n\t\t\t\t::lstrcpy(lpFindFileData->szFileName, szFile);\n\t\t\t\tlpFindFileData->szComment[0] = _T('\\0'); \/\/ unsupported right now\n\t\t\t\tlpFindFileData->nFileSizeCompressed = fh->cSize;\n\t\t\t\tlpFindFileData->nFileSizeUncompressed = fh->ucSize;\n\t\t\t\t::DosDateTimeToFileTime(fh->modDate, fh->modTime, &lpFindFileData->ftCreationDate);\n\t\t\t\tlpFindFileData->nIndex = pFF->nPos;\n\n\t\t\t\t\/\/ Figure out the file attributes\n\t\t\t\tDWORD& dwFlags = lpFindFileData->dwFileAttributes = 0;\n\t\t\t\tif (fh->flag & 1)\n\t\t\t\t\tdwFlags |= FILE_ATTRIBUTE_ENCRYPTED;\n\t\t\t\tif (fh->flag & (2|4))\n\t\t\t\t\tdwFlags |= FILE_ATTRIBUTE_COMPRESSED;\n\t\t\t\tif (fh->flag & (16|32|64))\n\t\t\t\t\tdwFlags |= FILE_ATTRIBUTE_OFFLINE; \/\/ unsupported compression used\n\t\t\t\tif (dwFlags == 0)\n\t\t\t\t\tdwFlags = (fh->compression == LOCAL_COMP_STORE) ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL;\n\n\t\t\t\t\/\/ Ready for next entry...\n\t\t\t\tpFF->nPos++;\n\t\t\t\treturn TRUE;\n\t\t\t}\n\t\t\tpFF->nPos++;\n\t\t}\n\t\treturn FALSE;\n\t}\n\tBOOL CZipArchive::FindClose(HANDLE hFindFile) const\n\t{\n\t\tif (hFindFile == INVALID_HANDLE_VALUE || hFindFile == NULL)\n\t\t\treturn FALSE;\n\n\t\tFindFileHandle* pFF = reinterpret_cast<FindFileHandle*>(hFindFile);\n\t\tdelete pFF;\n\t\treturn TRUE;\n\t}\n\n\tBOOL CZipArchive::Open(LPCTSTR pszFileName)\n\t{\n\t\t_ASSERTE(!::IsBadStringPtr(pszFileName, MAX_PATH));\n\t\tHANDLE hFile = ::CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n\t\t\n\t\tif(INVALID_HANDLE_VALUE==hFile) return FALSE;\n\t\t\n\t\tClose();\n\t\tm_hFile=hFile;\n\t\tBOOL bOK=OpenZip();\n\t\tif(!bOK)\n\t\t{\n\t\t\tCloseHandle(m_hFile);\n\t\t\tm_hFile=INVALID_HANDLE_VALUE;\n\t\t}\n\t\treturn bOK;\n\t}\n\n\tBOOL CZipArchive::Open(LPBYTE pBytes, DWORD dwByteCount) \n\t{\n\t\tClose();\n\n\t\tm_fileRes.Attach(pBytes, dwByteCount);\n\n\t\t\/\/ ?\n\t\tm_hFile = (HANDLE)pBytes;\n\n\t\tBOOL bOK=OpenZip();\n\t\tif(!bOK)\n\t\t{\n\t\t\tm_fileRes.Detach();\n\t\t\tm_hFile=INVALID_HANDLE_VALUE;\n\t\t}\n\t\treturn bOK;\n\t}\n\n\tBOOL CZipArchive::Open( HMODULE hModule,LPCTSTR pszName,LPCTSTR pszType )\n\t{\n\t\tHRSRC hResInfo = ::FindResource(hModule, pszName, pszType);\n\t\tif (hResInfo == NULL)\n\t\t\treturn FALSE;\n\n\t\tDWORD dwLength = ::SizeofResource(hModule, hResInfo);\n\t\tif (dwLength == 0)\n\t\t\treturn FALSE;\n\n\t\tHGLOBAL hResData = ::LoadResource(hModule, hResInfo);\n\t\tif (hResData == NULL)\n\t\t\treturn FALSE;\n\n\t\tBYTE* pData = (BYTE*)::LockResource(hResData);\n\t\tif (pData == NULL)\n\t\t\treturn FALSE;\n\n\t\tClose();\n\n\t\tm_fileRes.Attach(pData, dwLength);\n\n\t\tm_hFile = (HANDLE)hResInfo;\n\n\t\tBOOL bOK=OpenZip();\n\t\tif(!bOK)\n\t\t{\n\t\t\tm_fileRes.Detach();\n\t\t\tm_hFile=INVALID_HANDLE_VALUE;\n\t\t}\n\t\treturn bOK;\n\t}\n\n\tvoid CZipArchive::CloseFile()\n\t{\n\t\tif (m_hFile != INVALID_HANDLE_VALUE)\n\t\t{\n\t\t\tif (m_fileRes.IsOpen())\n\t\t\t\tm_fileRes.Detach();\n\t\t\telse\n\t\t\t\t::CloseHandle(m_hFile);\n\t\t\tm_hFile = INVALID_HANDLE_VALUE;\n\t\t}\n\t}\n\n\tDWORD CZipArchive::ReadFile(void* pBuffer, DWORD dwBytes)\n\t{\n\t\t_ASSERTE(m_hFile != INVALID_HANDLE_VALUE);\n\n\t\tDWORD dwRead = 0;\n\n\t\tif (m_fileRes.IsOpen())\n\t\t\tm_fileRes.Read(pBuffer, dwBytes, &dwRead);\n\t\telse\n\t\t\t::ReadFile(m_hFile, pBuffer, dwBytes, &dwRead, NULL);\n\n\t\treturn dwRead;\n\t}\n\tDWORD CZipArchive::SeekFile(LONG lOffset, UINT nFrom)\n\t{\n\t\t_ASSERTE(m_hFile != INVALID_HANDLE_VALUE);\n\n\t\tif (m_fileRes.IsOpen())\n\t\t{\n\t\t\tm_fileRes.Seek(lOffset, nFrom);\n\t\t\treturn m_fileRes.GetPosition();\n\t\t}\n\n\t\treturn ::SetFilePointer(m_hFile, lOffset, NULL, nFrom);\n\t}\n\n\tDWORD CZipArchive::GetFileSize( LPCTSTR pszFileName )\n\t{\n\t\treturn GetFileSize(GetFileIndex(pszFileName));\n\t}\n\n\tDWORD CZipArchive::GetFileSize( int iIndex )\n\t{\n\t\tif(iIndex==-1) return 0;\n\n\t\tif (m_hFile == INVALID_HANDLE_VALUE)\n\t\t\treturn 0;\n\t\tif (iIndex < 0 || iIndex >= m_Header.nDirEntries)\n\t\t\treturn 0;\n\n\t\tZipLocalHeader hdr;\n\t\tSeekFile(m_Files[iIndex]->hdrOffset, FILE_BEGIN);\n\n\t\tDWORD dwRead = ReadFile(&hdr, sizeof(hdr));\n\t\tif (dwRead != sizeof(hdr))\n\t\t\treturn 0;\n\t\treturn hdr.ucSize;\n\t}\n\n\tint CZipArchive::GetFileIndex( LPCTSTR pszFileName )\n\t{\n\t\t_ASSERTE(IsOpen());\n\t\t_ASSERTE(!::IsBadStringPtr(pszFileName, MAX_PATH));\n\n\t\tZIP_FIND_DATA fd;\n\t\tHANDLE hFindFile = FindFirstFile(pszFileName, &fd);\n\t\tif (hFindFile == INVALID_HANDLE_VALUE)\n\t\t\treturn -1;\n\t\tFindClose(hFindFile);\n\t\treturn fd.nIndex;\n\t}","avg_line_length":21.510230179,"max_line_length":124,"alphanum_fraction":0.646037691,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":531,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include<iostream>\nusing namespace std;\n    double Power(double base, int exponent) {\n        if(base == 0) return 0;\n        if(exponent == 0) return 1;\n        double pow = 1.0;\n        int e = abs(exponent);\n        cout<<e<<endl; \n        if(e)\n        {\n            e\/=2;\n            double tmp = Power(base, e);\n            pow = tmp*tmp;\n        }\n        if(abs(exponent) % 2 == 1)\n            pow *= base;\n        if(exponent < 0)\n            pow = 1.0\/pow;\n        return pow;\n    }\n\t\t\nint main()\n{\n\tcout<<Power(2,-3);\n}\n","avg_line_length":20.4230769231,"max_line_length":45,"alphanum_fraction":0.4369114878,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3922,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":107.0,"content":"#include \"TextUtils.h\"\r\n\r\n#include <stdio.h>\r\n\r\n#include \"Core\/3rdpart\/pcreplusplus.h\"\r\n#include \"Core\/Utils\/StringUtils.h\"\r\n#include \"Core\/Utils\/CoreUtils.h\"\r\n#include \"Core\/3rdpart\/htmlentities.h\"\r\n\r\n\/\/#include <codecvt>\r\n\r\nnamespace IuTextUtils\r\n{\r\n    std::string BbCodeToHtml(const std::string& bbcode) {\r\n        std::string work = bbcode;\r\n        \r\n        pcrepp::Pcre reg2(\"\\\\[img\\\\](.+?)\\\\[\\\\\/img\\\\]\", \"imc\");\r\n        std::string work2 = reg2.replace(work, \"<img src=\\\"$1\\\" style=\\\"border:0\\\">\");\r\n        \r\n        pcrepp::Pcre reg(\"\\\\[url=(.+?)\\\\](.+?)\\\\[\/url\\\\]\", \"imc\");\r\n        std::string work3 = reg.replace(work2, \"<a href=\\\"$1\\\" target=\\\"_blank\\\">$2<\/a>\");\r\n        \r\n\r\n        \/*std::string work4;\r\n        {\r\n            pcrepp::Pcre reg3(\"\\\\[url\\\\](.+?)\\\\[\\\\\/url\\\\]\", \"imc\");\r\n             work4 = reg3.replace(work3, \"<a href=\\\"$0\\\" target=\\\"_blank\\\">$0<\/a>\");\r\n             \r\n        }\r\n        *\/\r\n\r\n        work3 = IuStringUtils::Replace(work3, \"\\r\\n\", \"<br\/>\");\r\n        work3 = IuStringUtils::Replace(work3, \"\\n\", \"<br\/>\");\r\n        return work3;\r\n    }\r\n\r\n    bool FileSaveContents(const std::string& fileName, const std::string& contents) {\r\n        FILE * f = IuCoreUtils::fopen_utf8(fileName.c_str(), \"wb\");\r\n        if ( !f ) {\r\n            return false;\r\n        }\r\n\r\n        fwrite(contents.c_str(),1,contents.length(), f);\r\n        fclose(f);\r\n        return true;\r\n    }\r\n\r\n#define UNI_MAX_BMP   (UTF32)0x0000FFFF\r\n#define UNI_SUR_HIGH_START  (UTF32)0xD800\r\n#define UNI_SUR_HIGH_END (UTF32)0xDBFF\r\n#define UNI_SUR_LOW_START (UTF32)0xDC00\r\n#define UNI_SUR_LOW_END (UTF32)0xDFFF\r\n#define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD\r\n\r\n#define UNI_MAX_UTF16 (UTF32)0x0010FFFF\r\n#define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF\r\n#define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF\r\nstatic const int halfShift = 10; \/* used for shifting by 10 bits *\/\r\nstatic const UTF32 halfBase = 0x0010000UL;\r\nstatic const UTF32 halfMask = 0x3FFUL;\r\n\r\nConversionResult ConvertUTF32toUTF16(const UTF32* source, const UTF32* sourceEnd, UTF16* target, UTF16* targetEnd, ConversionFlags flags) {\r\n    ConversionResult result = conversionOK;\r\n    while (source < sourceEnd) {\r\n        UTF32 ch;\r\n        if (target >= targetEnd) {\r\n            result = targetExhausted;\r\n            break;\r\n        }\r\n        ch = *source++;\r\n        if (ch <= UNI_MAX_BMP) { \/* Target is a character <= 0xFFFF *\/\r\n            \/* UTF-16 surrogate values are illegal in UTF-32; 0xffff or 0xfffe are both reserved values *\/\r\n            if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {\r\n                if (flags == strictConversion) {\r\n                    --source; \/* return to the illegal value itself *\/\r\n                    result = sourceIllegal;\r\n                    break;\r\n                }\r\n                else {\r\n                    *target++ = UNI_REPLACEMENT_CHAR;\r\n                }\r\n            }\r\n            else {\r\n                *target++ = (UTF16)ch; \/* normal case *\/\r\n            }\r\n        }\r\n        else if (ch > UNI_MAX_LEGAL_UTF32) {\r\n            if (flags == strictConversion) {\r\n                result = sourceIllegal;\r\n            }\r\n            else {\r\n                *target++ = UNI_REPLACEMENT_CHAR;\r\n            }\r\n        }\r\n        else {\r\n            \/* target is a character in range 0xFFFF - 0x10FFFF. *\/\r\n            if (target + 1 >= targetEnd) {\r\n                --source; \/* Back up source pointer! *\/\r\n                result = targetExhausted;\r\n                break;\r\n            }\r\n            ch -= halfBase;\r\n            *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START);\r\n            *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START);\r\n        }\r\n    }\r\n    return result;\r\n}\r\n\r\nstd::string DecodeHtmlEntities(const std::string& src)\r\n{\r\n    std::string res = src;\r\n    decode_html_entities_utf8(&res[0], 0);\r\n    res.resize(strlen(&res[0]));\r\n    return res;\r\n}\r\n\r\n};","avg_line_length":33.2372881356,"max_line_length":140,"alphanum_fraction":0.5308516063,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1148,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":30.0,"content":"\/*!\n  \\file transformation_test.cpp\n  \\author Sho Ikeda\n\n  Copyright (c) 2015-2018 Sho Ikeda\n  This software is released under the MIT License.\n  http:\/\/opensource.org\/licenses\/mit-license.php\n  *\/\n\n\/\/ Standard C++ library\n#include <tuple>\n\/\/ GoogleTest\n#include \"gtest\/gtest.h\"\n\/\/ Zisc\n#include \"zisc\/vector.hpp\"\n\/\/ Nanairo\n#include \"NanairoCore\/nanairo_core_config.hpp\"\n#include \"NanairoCore\/Geometry\/transformation.hpp\"\n#include \"NanairoCore\/Geometry\/vector.hpp\"\n\nTEST(TransformationTest, DefaultTangentTest)\n{\n  using nanairo::Transformation;\n  using nanairo::uint;\n\n  const nanairo::Vector3 normal{0.0, 0.0, 1.0};\n  const auto tangents = Transformation::calcDefaultTangent(normal);\n\n  const auto& tangent = std::get<0>(tangents);\n  const auto& bitangent = std::get<1>(tangents);\n\n  ASSERT_TRUE(nanairo::isUnitVector(tangent))\n      << \"The tangent vector isn't unit vector.\";\n  ASSERT_TRUE(nanairo::isUnitVector(bitangent))\n      << \"The bitangent vector isn't unit vector.\";\n\n  const auto n = zisc::cross(tangent, bitangent);\n  for (uint i = 0; i < 3; ++i)\n    ASSERT_DOUBLE_EQ(normal[i], n[i]) << \"The calculation of tangents are wrong.\";\n}\n","avg_line_length":28.0,"max_line_length":82,"alphanum_fraction":0.7168989547,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2284,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include \"MsgBox.h\"\n#include <sstream>\n#include \"GUIManager.h\"\n#include \"..\/SoundEngine\/SoundManager.h\"\n#include \"..\/OSEnvironment\/OSEnvironment.h\"\n\nsize_t MsgBox::mNumMsgBoxShown=0;\n\nMsgBox::MsgBox(const std::string& rootId)\n: CIWidget(NULL, NULL)\n{\n\tinitializeComponents(rootId);\n}\n\nMsgBox::~MsgBox()\n{\n\tmRootWindow->removeChildWindow(mEditBox);\n\tmParentWindow->removeChildWindow(mRootWindow);\n\n\tCEGUI::WindowManager* wm=CEGUI::WindowManager::getSingletonPtr();\n\n\tmRootWindow->removeChildWindow(mEditBox);\n\tmParentWindow->removeChildWindow(mRootWindow);\n\n\twm->destroyWindow(mEditBox);\n\twm->destroyWindow(mRootWindow);\n}\n\nvoid MsgBox::showModal(const std::string& title, const std::string& text)\n{\n\tmRootWindow->setText(title);\n\tmEditBox->setText(text);\n\tmRootWindow->setSize(CEGUI::UVector2(cegui_reldim(0.4f), cegui_reldim(0.2f)));\n\n\tsetModalState(true);\n\n\tmRootWindow->setPosition(CEGUI::UVector2(CEGUI::UDim(0.3f, 10.0f*mNumMsgBoxShown), CEGUI::UDim(0.4f, 10.0f * mNumMsgBoxShown)));\n\tshowWindow();\n\tmNumMsgBoxShown++;\n\n\tSoundManager::getSingletonPtr()->play(\"msgbox\");\n}\n\nvoid MsgBox::create()\n{\n\tCEGUI::WindowManager* wm=CEGUI::WindowManager::getSingletonPtr();\n\tmRootWindow=wm->createWindow(CIWidget::getGUIType(\"FrameWindow\"), getRootId());\n\tmRootWindow->setSize(CEGUI::UVector2(cegui_reldim(0.4f), cegui_reldim(0.2f)));\n\tmRootWindow->setPosition(CEGUI::UVector2(cegui_reldim(0.3f), cegui_reldim(0.4f)));\n\tmRootWindow->setAlpha(0.8f);\n\n\tmEditBox=static_cast<CEGUI::MultiLineEditbox*>(wm->createWindow(CIWidget::getGUIType(\"MultiLineEditbox\"), getUIId(\"editBox\")));\n\tmEditBox->setSize(CEGUI::UVector2(cegui_reldim(0.9f), cegui_reldim(0.75f)));\n\tmEditBox->setPosition(CEGUI::UVector2(cegui_reldim(0.05f), cegui_reldim(0.2f)));\n\tmEditBox->setReadOnly(true);\n\tmRootWindow->addChildWindow(mEditBox);\n\n\tmParentWindow->addChildWindow(mRootWindow);\n}\n\nvoid MsgBox::subscribeEvents()\n{\n\tmEventCancel=mRootWindow->subscribeEvent(CEGUI::FrameWindow::EventCloseClicked, CEGUI::Event::Subscriber(&MsgBox::onClicked_Cancel, this));\n}\n\nvoid MsgBox::unsubscribeEvents()\n{\n\tmEventCancel->disconnect();\n}\n\nbool MsgBox::onClicked_Cancel(const CEGUI::EventArgs& evt)\n{\n\tsetModalState(false);\n\thideWindow();\n\tGUIManager::getSingletonPtr()->hideMsgBox(this);\n\n\tmNumMsgBoxShown--;\n\n\treturn true;\n}\n","avg_line_length":28.1975308642,"max_line_length":140,"alphanum_fraction":0.7635726795,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":19735,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1537.0,"content":"\/****************************************************************************\n *\n *   Copyright (c) 2015 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n* @file vtol_type.cpp\n*\n* @author Roman Bapst \t\t<bapstroman@gmail.com>\n* @author Andreas Antener\t<andreas@uaventure.com>\n*\n*\/\n\n#include \"vtol_type.h\"\n#include \"vtol_att_control_main.h\"\n\n#include <float.h>\n#include <px4_platform_common\/defines.h>\n#include <matrix\/math.hpp>\n\nusing namespace matrix;\n\n#define THROTTLE_BLENDING_DUR_S 1.0f\n\n\nVtolType::VtolType(VtolAttitudeControl *att_controller) :\n\t_attc(att_controller),\n\t_vtol_mode(mode::ROTARY_WING)\n{\n\t_v_att = _attc->get_att();\n\t_v_att_sp = _attc->get_att_sp();\n\t_mc_virtual_att_sp = _attc->get_mc_virtual_att_sp();\n\t_fw_virtual_att_sp = _attc->get_fw_virtual_att_sp();\n\t_v_control_mode = _attc->get_control_mode();\n\t_vtol_vehicle_status = _attc->get_vtol_vehicle_status();\n\t_actuators_out_0 = _attc->get_actuators_out0();\n\t_actuators_out_1 = _attc->get_actuators_out1();\n\t_actuators_mc_in = _attc->get_actuators_mc_in();\n\t_actuators_fw_in = _attc->get_actuators_fw_in();\n\t_torque_setpoint_0 = _attc->get_torque_setpoint_0();\n\t_torque_setpoint_1 = _attc->get_torque_setpoint_1();\n\t_thrust_setpoint_0 = _attc->get_thrust_setpoint_0();\n\t_thrust_setpoint_1 = _attc->get_thrust_setpoint_1();\n\t_local_pos = _attc->get_local_pos();\n\t_local_pos_sp = _attc->get_local_pos_sp();\n\t_airspeed_validated = _attc->get_airspeed();\n\t_tecs_status = _attc->get_tecs_status();\n\t_land_detected = _attc->get_land_detected();\n\t_params = _attc->get_params();\n\n\tfor (auto &pwm_max : _max_mc_pwm_values.values) {\n\t\tpwm_max = PWM_DEFAULT_MAX;\n\t}\n\n\tfor (auto &pwm_disarmed : _disarmed_pwm_values.values) {\n\t\tpwm_disarmed = PWM_MOTOR_OFF;\n\t}\n}\n\nbool VtolType::init()\n{\n\tif (_params->ctrl_alloc != 1) {\n\t\tconst char *dev = _params->vt_mc_on_fmu ? PWM_OUTPUT1_DEVICE_PATH : PWM_OUTPUT0_DEVICE_PATH;\n\n\t\tint fd = px4_open(dev, 0);\n\n\t\tif (fd < 0) {\n\t\t\tPX4_ERR(\"can't open %s\", dev);\n\t\t\treturn false;\n\t\t}\n\n\t\tint ret = px4_ioctl(fd, PWM_SERVO_GET_MAX_PWM, (long unsigned int)&_max_mc_pwm_values);\n\t\t_current_max_pwm_values = _max_mc_pwm_values;\n\n\t\tif (ret != PX4_OK) {\n\t\t\tPX4_ERR(\"failed getting max values\");\n\t\t\tpx4_close(fd);\n\t\t\treturn false;\n\t\t}\n\n\t\tret = px4_ioctl(fd, PWM_SERVO_GET_MIN_PWM, (long unsigned int)&_min_mc_pwm_values);\n\n\t\tif (ret != PX4_OK) {\n\t\t\tPX4_ERR(\"failed getting min values\");\n\t\t\tpx4_close(fd);\n\t\t\treturn false;\n\t\t}\n\n\t\tret = px4_ioctl(fd, PWM_SERVO_GET_DISARMED_PWM, (long unsigned int)&_disarmed_pwm_values);\n\n\t\tif (ret != PX4_OK) {\n\t\t\tPX4_ERR(\"failed getting disarmed values\");\n\t\t\tpx4_close(fd);\n\t\t\treturn false;\n\t\t}\n\n\t\tpx4_close(fd);\n\n\t\t_main_motor_channel_bitmap = generate_bitmap_from_channel_numbers(_params->vtol_motor_id);\n\t\t_alternate_motor_channel_bitmap = generate_bitmap_from_channel_numbers(_params->fw_motors_off);\n\n\n\t\t\/\/ in order to get the main motors we take all motors and clear the alternate motor bits\n\t\tfor (int i = 0; i < 8; i++) {\n\t\t\tif (_alternate_motor_channel_bitmap & (1 << i)) {\n\t\t\t\t_main_motor_channel_bitmap &= ~(1 << i);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n\n}\n\nvoid VtolType::update_mc_state()\n{\n\tif (!_flag_idle_mc) {\n\t\t_flag_idle_mc = set_idle_mc();\n\t}\n\n\tresetAccelToPitchPitchIntegrator();\n\n\tVtolType::set_all_motor_state(motor_state::ENABLED);\n\n\t\/\/ copy virtual attitude setpoint to real attitude setpoint\n\tmemcpy(_v_att_sp, _mc_virtual_att_sp, sizeof(vehicle_attitude_setpoint_s));\n\n\t_mc_roll_weight = 1.0f;\n\t_mc_pitch_weight = 1.0f;\n\t_mc_yaw_weight = 1.0f;\n\t_mc_throttle_weight = 1.0f;\n}\n\nvoid VtolType::update_fw_state()\n{\n\tif (_flag_idle_mc) {\n\t\t_flag_idle_mc = !set_idle_fw();\n\t}\n\n\tresetAccelToPitchPitchIntegrator();\n\t_last_thr_in_fw_mode =  _actuators_fw_in->control[actuator_controls_s::INDEX_THROTTLE];\n\n\tVtolType::set_alternate_motor_state(motor_state::DISABLED);\n\n\t\/\/ copy virtual attitude setpoint to real attitude setpoint\n\tmemcpy(_v_att_sp, _fw_virtual_att_sp, sizeof(vehicle_attitude_setpoint_s));\n\t_mc_roll_weight = 0.0f;\n\t_mc_pitch_weight = 0.0f;\n\t_mc_yaw_weight = 0.0f;\n\n\t\/\/ tecs didn't publish an update yet after the transition\n\tif (_tecs_status->timestamp < _trans_finished_ts) {\n\t\t_tecs_running = false;\n\n\t} else if (!_tecs_running) {\n\t\t_tecs_running = true;\n\t\t_tecs_running_ts = hrt_absolute_time();\n\t}\n\n\t\/\/ TECS didn't publish yet or the position controller didn't publish yet AFTER tecs\n\t\/\/ only wait on TECS we're in a mode where it is actually running\n\tif ((!_tecs_running || (_tecs_running && _fw_virtual_att_sp->timestamp <= _tecs_running_ts))\n\t    && _v_control_mode->flag_control_altitude_enabled) {\n\n\t\twaiting_on_tecs();\n\t\t_throttle_blend_start_ts = hrt_absolute_time();\n\n\t} else if (shouldBlendThrottleAfterFrontTransition()) {\n\t\tconst float progress = (float)(hrt_absolute_time() - _throttle_blend_start_ts) * 1e-6f \/ THROTTLE_BLENDING_DUR_S;\n\n\t\tif (progress >= 1.0f) {\n\t\t\tstopBlendingThrottleAfterFrontTransition();\n\n\t\t} else {\n\t\t\tblendThrottleAfterFrontTransition(progress);\n\t\t}\n\t}\n\n\tcheck_quadchute_condition();\n}\n\nvoid VtolType::update_transition_state()\n{\n\thrt_abstime t_now = hrt_absolute_time();\n\t_transition_dt = (float)(t_now - _last_loop_ts) \/ 1e6f;\n\t_transition_dt = math::constrain(_transition_dt, 0.0001f, 0.02f);\n\t_last_loop_ts = t_now;\n\t_throttle_blend_start_ts = t_now;\n\n\n\n\tcheck_quadchute_condition();\n}\n\nfloat VtolType::update_and_get_backtransition_pitch_sp()\n{\n\t\/\/ maximum up or down pitch the controller is allowed to demand\n\tconst float pitch_lim = 0.3f;\n\tconst Eulerf euler(Quatf(_v_att->q));\n\n\tconst float track = atan2f(_local_pos->vy, _local_pos->vx);\n\tconst float accel_body_forward = cosf(track) * _local_pos->ax + sinf(track) * _local_pos->ay;\n\n\t\/\/ get accel error, positive means decelerating too slow, need to pitch up (must reverse dec_max, as it is a positive number)\n\tconst float accel_error_forward = _params->back_trans_dec_sp + accel_body_forward;\n\n\tconst float pitch_sp_new = _params->dec_to_pitch_ff * _params->back_trans_dec_sp + _accel_to_pitch_integ;\n\n\tfloat integrator_input = _params->dec_to_pitch_i * accel_error_forward;\n\n\tif ((pitch_sp_new >= pitch_lim && accel_error_forward > 0.0f) ||\n\t    (pitch_sp_new <= 0.f && accel_error_forward < 0.0f)) {\n\t\tintegrator_input = 0.0f;\n\t}\n\n\t_accel_to_pitch_integ += integrator_input * _transition_dt;\n\n\t\/\/ only allow positive (pitch up) pitch setpoint\n\treturn math::constrain(pitch_sp_new, 0.f, pitch_lim);\n}\n\nbool VtolType::can_transition_on_ground()\n{\n\treturn !_v_control_mode->flag_armed || _land_detected->landed;\n}\n\nvoid VtolType::check_quadchute_condition()\n{\n\tif (_attc->get_transition_command() == vtol_vehicle_status_s::VEHICLE_VTOL_STATE_MC && _attc->get_immediate_transition()\n\t    && !_quadchute_command_treated) {\n\t\t_attc->quadchute(VtolAttitudeControl::QuadchuteReason::ExternalCommand);\n\t\t_quadchute_command_treated = true;\n\t\t_attc->reset_immediate_transition();\n\n\t} else {\n\t\t_quadchute_command_treated = false;\n\t}\n\n\tif (!_tecs_running) {\n\t\t\/\/ reset the filtered height rate and heigh rate setpoint if TECS is not running\n\t\t_ra_hrate = 0.0f;\n\t\t_ra_hrate_sp = 0.0f;\n\t}\n\n\tif (_v_control_mode->flag_armed && !_land_detected->landed) {\n\t\tEulerf euler = Quatf(_v_att->q);\n\n\t\t\/\/ fixed-wing minimum altitude\n\t\tif (_params->fw_min_alt > FLT_EPSILON) {\n\n\t\t\tif (-(_local_pos->z) < _params->fw_min_alt) {\n\t\t\t\t_attc->quadchute(VtolAttitudeControl::QuadchuteReason::MinimumAltBreached);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ adaptive quadchute\n\t\tif (_params->fw_alt_err > FLT_EPSILON && _v_control_mode->flag_control_altitude_enabled) {\n\n\t\t\t\/\/ We use tecs for tracking in FW and local_pos_sp during transitions\n\t\t\tif (_tecs_running) {\n\t\t\t\t\/\/ 1 second rolling average\n\t\t\t\t_ra_hrate = (49 * _ra_hrate + _tecs_status->height_rate) \/ 50;\n\t\t\t\t_ra_hrate_sp = (49 * _ra_hrate_sp + _tecs_status->height_rate_setpoint) \/ 50;\n\n\t\t\t\t\/\/ are we dropping while requesting significant ascend?\n\t\t\t\tif (((_tecs_status->altitude_sp - _tecs_status->altitude_filtered) > _params->fw_alt_err) &&\n\t\t\t\t    (_ra_hrate < -1.0f) &&\n\t\t\t\t    (_ra_hrate_sp > 1.0f)) {\n\n\t\t\t\t\t_attc->quadchute(VtolAttitudeControl::QuadchuteReason::LossOfAlt);\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tconst bool height_error = _local_pos->z_valid && ((-_local_pos_sp->z - -_local_pos->z) > _params->fw_alt_err);\n\t\t\t\tconst bool height_rate_error = _local_pos->v_z_valid && (_local_pos->vz > 1.0f) && (_local_pos->z_deriv > 1.0f);\n\n\t\t\t\tif (height_error && height_rate_error) {\n\t\t\t\t\t_attc->quadchute(VtolAttitudeControl::QuadchuteReason::LargeAltError);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ fixed-wing maximum pitch angle\n\t\tif (_params->fw_qc_max_pitch > 0) {\n\n\t\t\tif (fabsf(euler.theta()) > fabsf(math::radians(_params->fw_qc_max_pitch))) {\n\t\t\t\t_attc->quadchute(VtolAttitudeControl::QuadchuteReason::MaximumPitchExceeded);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ fixed-wing maximum roll angle\n\t\tif (_params->fw_qc_max_roll > 0) {\n\n\t\t\tif (fabsf(euler.phi()) > fabsf(math::radians(_params->fw_qc_max_roll))) {\n\t\t\t\t_attc->quadchute(VtolAttitudeControl::QuadchuteReason::MaximumRollExceeded);\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool VtolType::set_idle_mc()\n{\n\tif (_params->ctrl_alloc == 1) {\n\t\treturn true;\n\t}\n\n\tunsigned pwm_value = _params->idle_pwm_mc;\n\tstruct pwm_output_values pwm_values {};\n\n\tfor (int i = 0; i < num_outputs_max; i++) {\n\t\tif (is_channel_set(i, generate_bitmap_from_channel_numbers(_params->vtol_motor_id))) {\n\t\t\tpwm_values.values[i] = pwm_value;\n\n\t\t} else {\n\t\t\tpwm_values.values[i] = _min_mc_pwm_values.values[i];\n\t\t}\n\n\t\tpwm_values.channel_count++;\n\t}\n\n\treturn apply_pwm_limits(pwm_values, pwm_limit_type::TYPE_MINIMUM);\n}\n\nbool VtolType::set_idle_fw()\n{\n\tif (_params->ctrl_alloc == 1) {\n\t\treturn true;\n\t}\n\n\tstruct pwm_output_values pwm_values {};\n\n\tfor (int i = 0; i < num_outputs_max; i++) {\n\t\tif (is_channel_set(i, generate_bitmap_from_channel_numbers(_params->vtol_motor_id))) {\n\t\t\tpwm_values.values[i] = PWM_DEFAULT_MIN;\n\n\t\t} else {\n\t\t\tpwm_values.values[i] = _min_mc_pwm_values.values[i];\n\t\t}\n\n\t\tpwm_values.channel_count++;\n\t}\n\n\treturn apply_pwm_limits(pwm_values, pwm_limit_type::TYPE_MINIMUM);\n}\n\nbool VtolType::apply_pwm_limits(struct pwm_output_values &pwm_values, pwm_limit_type type)\n{\n\tconst char *dev = _params->vt_mc_on_fmu ? PWM_OUTPUT1_DEVICE_PATH : PWM_OUTPUT0_DEVICE_PATH;\n\n\tint fd = px4_open(dev, 0);\n\n\tif (fd < 0) {\n\t\tPX4_WARN(\"can't open %s\", dev);\n\t\treturn false;\n\t}\n\n\tint ret;\n\n\tif (type == pwm_limit_type::TYPE_MINIMUM) {\n\t\tret = px4_ioctl(fd, PWM_SERVO_SET_MIN_PWM, (long unsigned int)&pwm_values);\n\n\t} else {\n\t\tret = px4_ioctl(fd, PWM_SERVO_SET_MAX_PWM, (long unsigned int)&pwm_values);\n\t}\n\n\tpx4_close(fd);\n\n\n\tif (ret != OK) {\n\t\tPX4_DEBUG(\"failed setting max values\");\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nvoid VtolType::set_all_motor_state(const motor_state target_state, const int value)\n{\n\tif (_params->ctrl_alloc == 1) {\n\t\treturn;\n\t}\n\n\tset_main_motor_state(target_state, value);\n\tset_alternate_motor_state(target_state, value);\n}\n\nvoid VtolType::set_main_motor_state(const motor_state target_state, const int value)\n{\n\tif (_params->ctrl_alloc == 1) {\n\t\treturn;\n\t}\n\n\tif (_main_motor_state != target_state || target_state == motor_state::VALUE) {\n\n\t\tif (set_motor_state(target_state, _main_motor_channel_bitmap, value)) {\n\t\t\t_main_motor_state = target_state;\n\t\t}\n\t}\n}\n\nvoid VtolType::set_alternate_motor_state(const motor_state target_state, const int value)\n{\n\tif (_params->ctrl_alloc == 1) {\n\t\treturn;\n\t}\n\n\tif (_alternate_motor_state != target_state || target_state == motor_state::VALUE) {\n\n\t\tif (set_motor_state(target_state, _alternate_motor_channel_bitmap, value)) {\n\t\t\t_alternate_motor_state = target_state;\n\t\t}\n\t}\n}\n\nbool VtolType::set_motor_state(const motor_state target_state, const int32_t channel_bitmap,  const int value)\n{\n\tswitch (target_state) {\n\tcase motor_state::ENABLED:\n\t\tfor (int i = 0; i < num_outputs_max; i++) {\n\t\t\tif (is_channel_set(i, channel_bitmap)) {\n\t\t\t\t_current_max_pwm_values.values[i] = _max_mc_pwm_values.values[i];\n\t\t\t}\n\t\t}\n\n\t\tbreak;\n\n\tcase motor_state::DISABLED:\n\t\tfor (int i = 0; i < num_outputs_max; i++) {\n\t\t\tif (is_channel_set(i, channel_bitmap)) {\n\t\t\t\t_current_max_pwm_values.values[i] = _disarmed_pwm_values.values[i];\n\t\t\t}\n\t\t}\n\n\t\tbreak;\n\n\tcase motor_state::IDLE:\n\n\t\tfor (int i = 0; i < num_outputs_max; i++) {\n\t\t\tif (is_channel_set(i, channel_bitmap)) {\n\t\t\t\t_current_max_pwm_values.values[i] = _params->idle_pwm_mc;\n\t\t\t}\n\t\t}\n\n\t\tbreak;\n\n\tcase motor_state::VALUE:\n\t\tfor (int i = 0; i < num_outputs_max; i++) {\n\t\t\tif (is_channel_set(i, channel_bitmap)) {\n\t\t\t\t_current_max_pwm_values.values[i] = value;\n\t\t\t}\n\t\t}\n\n\t\tbreak;\n\t}\n\n\t_current_max_pwm_values.channel_count = num_outputs_max;\n\n\treturn apply_pwm_limits(_current_max_pwm_values, pwm_limit_type::TYPE_MAXIMUM);\n}\n\nint VtolType::generate_bitmap_from_channel_numbers(const int channels)\n{\n\tint channel_bitmap = 0;\n\tint channel_numbers = channels;\n\n\tint tmp;\n\n\tfor (int i = 0; i < num_outputs_max; ++i) {\n\t\ttmp = channel_numbers % 10;\n\n\t\tif (tmp == 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tchannel_bitmap |= 1 << (tmp - 1);\n\t\tchannel_numbers = channel_numbers \/ 10;\n\t}\n\n\treturn channel_bitmap;\n}\n\nbool VtolType::is_channel_set(const int channel, const int bitmap)\n{\n\treturn bitmap & (1 << channel);\n}\n\n\nfloat VtolType::pusher_assist()\n{\n\t\/\/ Altitude above ground is distance sensor altitude if available, otherwise local z-position\n\tfloat dist_to_ground = -_local_pos->z;\n\n\tif (_local_pos->dist_bottom_valid) {\n\t\tdist_to_ground = _local_pos->dist_bottom;\n\t}\n\n\t\/\/ disable pusher assist depending on setting of forward_thrust_enable_mode:\n\tswitch (_params->vt_forward_thrust_enable_mode) {\n\tcase DISABLE: \/\/ disable in all modes\n\t\treturn 0.0f;\n\t\tbreak;\n\n\tcase ENABLE_WITHOUT_LAND: \/\/ disable in land mode\n\t\tif (_attc->get_pos_sp_triplet()->current.valid\n\t\t    && _attc->get_pos_sp_triplet()->current.type == position_setpoint_s::SETPOINT_TYPE_LAND\n\t\t    && _v_control_mode->flag_control_auto_enabled) {\n\t\t\treturn 0.0f;\n\t\t}\n\n\t\tbreak;\n\n\tcase ENABLE_ABOVE_MPC_LAND_ALT1: \/\/ disable if below MPC_LAND_ALT1\n\t\tif (!PX4_ISFINITE(dist_to_ground) || (dist_to_ground < _params->mpc_land_alt1)) {\n\t\t\treturn 0.0f;\n\t\t}\n\n\t\tbreak;\n\n\tcase ENABLE_ABOVE_MPC_LAND_ALT2: \/\/ disable if below MPC_LAND_ALT2\n\t\tif (!PX4_ISFINITE(dist_to_ground) || (dist_to_ground < _params->mpc_land_alt2)) {\n\t\t\treturn 0.0f;\n\t\t}\n\n\t\tbreak;\n\n\tcase ENABLE_ABOVE_MPC_LAND_ALT1_WITHOUT_LAND: \/\/ disable if below MPC_LAND_ALT1 or in land mode\n\t\tif ((_attc->get_pos_sp_triplet()->current.valid\n\t\t     && _attc->get_pos_sp_triplet()->current.type == position_setpoint_s::SETPOINT_TYPE_LAND\n\t\t     && _v_control_mode->flag_control_auto_enabled) ||\n\t\t    (!PX4_ISFINITE(dist_to_ground) || (dist_to_ground < _params->mpc_land_alt1))) {\n\t\t\treturn 0.0f;\n\t\t}\n\n\t\tbreak;\n\n\tcase ENABLE_ABOVE_MPC_LAND_ALT2_WITHOUT_LAND: \/\/ disable if below MPC_LAND_ALT2 or in land mode\n\t\tif ((_attc->get_pos_sp_triplet()->current.valid\n\t\t     && _attc->get_pos_sp_triplet()->current.type == position_setpoint_s::SETPOINT_TYPE_LAND\n\t\t     && _v_control_mode->flag_control_auto_enabled) ||\n\t\t    (!PX4_ISFINITE(dist_to_ground) || (dist_to_ground < _params->mpc_land_alt2))) {\n\t\t\treturn 0.0f;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\t\/\/ if the thrust scale param is zero or the drone is not in some position or altitude control mode,\n\t\/\/ then the pusher-for-pitch strategy is disabled and we can return\n\tif (_params->forward_thrust_scale < FLT_EPSILON || !(_v_control_mode->flag_control_position_enabled\n\t\t\t|| _v_control_mode->flag_control_altitude_enabled)) {\n\t\treturn 0.0f;\n\t}\n\n\t\/\/ Do not engage pusher assist during a failsafe event (could be a problem with the fixed wing drive)\n\tif (_attc->get_vtol_vehicle_status()->vtol_transition_failsafe) {\n\t\treturn 0.0f;\n\t}\n\n\tconst Dcmf R(Quatf(_v_att->q));\n\tconst Dcmf R_sp(Quatf(_v_att_sp->q_d));\n\tconst Eulerf euler(R);\n\tconst Eulerf euler_sp(R_sp);\n\n\t\/\/ direction of desired body z axis represented in earth frame\n\tVector3f body_z_sp(R_sp(0, 2), R_sp(1, 2), R_sp(2, 2));\n\n\t\/\/ rotate desired body z axis into new frame which is rotated in z by the current\n\t\/\/ heading of the vehicle. we refer to this as the heading frame.\n\tDcmf R_yaw = Eulerf(0.0f, 0.0f, -euler(2));\n\tbody_z_sp = R_yaw * body_z_sp;\n\tbody_z_sp.normalize();\n\n\t\/\/ calculate the desired pitch seen in the heading frame\n\t\/\/ this value corresponds to the amount the vehicle would try to pitch down\n\tconst float pitch_setpoint = atan2f(body_z_sp(0), body_z_sp(2));\n\n\t\/\/ normalized pusher support throttle (standard VTOL) or tilt (tiltrotor), initialize to 0\n\tfloat forward_thrust = 0.0f;\n\n\tfloat pitch_setpoint_min = _params->pitch_min_rad;\n\n\tif (_attc->get_pos_sp_triplet()->current.valid\n\t    && _attc->get_pos_sp_triplet()->current.type == position_setpoint_s::SETPOINT_TYPE_LAND) {\n\t\tpitch_setpoint_min = _params->land_pitch_min_rad; \/\/ set min pitch during LAND (usually lower to generate less lift)\n\t}\n\n\t\/\/ only allow pitching down up to threshold, the rest of the desired\n\t\/\/ forward acceleration will be compensated by the pusher\/tilt\n\n\tif (pitch_setpoint < pitch_setpoint_min) {\n\t\t\/\/ desired roll angle in heading frame stays the same\n\t\tconst float roll_new = -asinf(body_z_sp(1));\n\n\t\tforward_thrust = (sinf(pitch_setpoint_min) - sinf(pitch_setpoint)) * _params->forward_thrust_scale;\n\t\t\/\/ limit forward actuation to [0, 0.9]\n\t\tforward_thrust = math::constrain(forward_thrust, 0.0f, 0.9f);\n\n\t\t\/\/ Set the pitch to 0 if the pitch limit is negative (pitch down), but allow a positive (pitch up) pitch.\n\t\t\/\/ This can be used for tiltrotor to make them hover with a positive angle of attack\n\t\tconst float pitch_new = pitch_setpoint_min > 0.f ? pitch_setpoint_min : 0.f;\n\n\t\t\/\/ create corrected desired body z axis in heading frame\n\t\tconst Dcmf R_tmp = Eulerf(roll_new, pitch_new, 0.0f);\n\t\tVector3f tilt_new(R_tmp(0, 2), R_tmp(1, 2), R_tmp(2, 2));\n\n\t\t\/\/ rotate the vector into a new frame which is rotated in z by the desired heading\n\t\t\/\/ with respect to the earh frame.\n\t\tconst float yaw_error = wrap_pi(euler_sp(2) - euler(2));\n\t\tconst Dcmf R_yaw_correction = Eulerf(0.0f, 0.0f, -yaw_error);\n\t\ttilt_new = R_yaw_correction * tilt_new;\n\n\t\t\/\/ now extract roll and pitch setpoints\n\t\t_v_att_sp->pitch_body = atan2f(tilt_new(0), tilt_new(2));\n\t\t_v_att_sp->roll_body = -asinf(tilt_new(1));\n\n\t\tconst Quatf q_sp(Eulerf(_v_att_sp->roll_body, _v_att_sp->pitch_body, euler_sp(2)));\n\t\tq_sp.copyTo(_v_att_sp->q_d);\n\t}\n\n\treturn forward_thrust;\n\n}\n","avg_line_length":30.3149001536,"max_line_length":126,"alphanum_fraction":0.7289080314,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":390,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":427.0,"content":"\/\/===-- other.cpp -----------------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\nint otherfn()\n{\n    return 4; \/\/ other marker\n}\n","avg_line_length":27.8571428571,"max_line_length":80,"alphanum_fraction":0.3974358974,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":642,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":11.0,"content":"\/\/  Copyright John Maddock 2008.\r\n\/\/  Use, modification and distribution are subject to the\r\n\/\/  Boost Software License, Version 1.0.  (See accompanying file\r\n\/\/  LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\/\/\r\n#  include <pch.hpp>\r\n#ifndef BOOST_MATH_TR1_SOURCE\r\n#  define BOOST_MATH_TR1_SOURCE\r\n#endif\r\n#include <boost\/math\/tr1.hpp>\r\n#include <boost\/math\/special_functions\/zeta.hpp>\r\n#include \"c_policy.hpp\"\r\n\r\nextern \"C\" long double BOOST_MATH_TR1_DECL riemann_zetal BOOST_PREVENT_MACRO_SUBSTITUTION(long double x) BOOST_MATH_C99_THROW_SPEC\r\n{\r\n   return c_policies::zeta BOOST_PREVENT_MACRO_SUBSTITUTION(x);\r\n}\r\n\r\n\r\n","avg_line_length":32.1,"max_line_length":131,"alphanum_fraction":0.7632398754,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2466,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"#include \"replaylink.h\"\n#include \"league.h\"\n\n#include <iostream>\n#include <chrono>\n#include <thread>\n\n#include <..\/Patterns\/PatternSearch.h>\n#include <..\/Process\/Process.h>\n\nusing namespace blackbone;\nusing namespace std::chrono_literals;\n\nnamespace replay\n{\n\tcamera_impl::camera_impl()\n\t{\n\t}\n\n\tbool camera_impl::init()\n\t{\n\t\tif (connect_to_league() == false)\n\t\t\treturn false;\n\n\t\t\/\/ std::cout << \"Trying to find the pattern for the camera object...\" << std::endl;\n\n\t\tcamera_object_address = 0;\n\t\tPatternSearch pattern(\"\\x8B\\x0D\\xCC\\xCC\\xCC\\xCC\\x8B\\x49\\x24\\xE8\\xCC\\xCC\\xCC\\xCC\\x8B\");\n\n\t\tstd::vector<ptr_t> results;\n\t\tpattern.SearchRemoteWhole(internal::league_process, true, 0xCC, results);\n\n\t\t\/\/ Unable to find position offset\n\t\tif (results.size() == 0)\n\t\t{\n\t\t\t\/\/ std::cout << \"Unable to find the pattern.\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tif (internal::league_process.memory().Read<uint32_t>(results[0] + 2, camera_object_address))\n\t\t{\n\t\t\t\/\/ std::cout << \"Failed to read a part of the pattern.\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tif (internal::league_process.memory().Read<uint32_t>(camera_object_address, camera_object_address))\n\t\t{\n\t\t\t\/\/ std::cout << \"Failed to read in the multiplayer client.\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tif (internal::league_process.memory().Read<uint32_t>(camera_object_address + 12, camera_object_address))\n\t\t{\n\t\t\t\/\/ std::cout << \"Failed to get the camera object.\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tvector2 camera_impl::get_position()\n\t{\n\t\tvector2 t_result(0, 0);\n\t\tif (internal::league_process.memory().Read<float>(camera_object_address + 0x12c, t_result.x))\n\t\t{\n\t\t\t\/\/ std::cout << \"Failed to read x position of camera.\" << std::endl;\n\t\t\treturn vector2(-2, -2);\n\t\t}\n\n\t\tif (internal::league_process.memory().Read<float>(camera_object_address + 0x134, t_result.y))\n\t\t{\n\t\t\t\/\/ std::cout << \"Failed to read y position of camera.\" << std::endl;\n\t\t\treturn vector2(-3, -3);\n\t\t}\n\n\t\treturn t_result;\n\t}\n\n\tvoid camera_impl::set_position(float x, float y)\n\t{\n\t\tif (internal::league_process.memory().Write<float>(camera_object_address + 0x12c, x))\n\t\t{\n\t\t\t\/\/ std::cout << \"Failed to write x position of camera.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\tif (internal::league_process.memory().Write<float>(camera_object_address + 0x134, y))\n\t\t{\n\t\t\t\/\/ std::cout << \"Failed to write y position of camera.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tvoid camera_impl::set_position(vector2 vec)\n\t{\n\t\treturn set_position(vec.x, vec.y);\n\t}\n}\n","avg_line_length":24.9090909091,"max_line_length":106,"alphanum_fraction":0.6719383617,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1236,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":10.0,"content":"\/\/ ARKSurvivalEvolved (329.9) SDK\n\n#ifdef _MSC_VER\n\t#pragma pack(push, 0x8)\n#endif\n\n#include \"ARKSurvivalEvolved_PrimalItemConsumable_Egg_Trike_Bionic_parameters.hpp\"\n\nnamespace sdk\n{\n\/\/---------------------------------------------------------------------------\n\/\/Functions\n\/\/---------------------------------------------------------------------------\n\n\/\/ Function PrimalItemConsumable_Egg_Trike_Bionic.PrimalItemConsumable_Egg_Trike_Bionic_C.ExecuteUbergraph_PrimalItemConsumable_Egg_Trike_Bionic\n\/\/ ()\n\/\/ Parameters:\n\/\/ int                            EntryPoint                     (Parm, ZeroConstructor, IsPlainOldData)\n\nvoid UPrimalItemConsumable_Egg_Trike_Bionic_C::ExecuteUbergraph_PrimalItemConsumable_Egg_Trike_Bionic(int EntryPoint)\n{\n\tstatic auto fn = UObject::FindObject<UFunction>(\"Function PrimalItemConsumable_Egg_Trike_Bionic.PrimalItemConsumable_Egg_Trike_Bionic_C.ExecuteUbergraph_PrimalItemConsumable_Egg_Trike_Bionic\");\n\n\tUPrimalItemConsumable_Egg_Trike_Bionic_C_ExecuteUbergraph_PrimalItemConsumable_Egg_Trike_Bionic_Params params;\n\tparams.EntryPoint = EntryPoint;\n\n\tauto flags = fn->FunctionFlags;\n\n\tUObject::ProcessEvent(fn, &params);\n\n\tfn->FunctionFlags = flags;\n}\n\n\n}\n\n#ifdef _MSC_VER\n\t#pragma pack(pop)\n#endif\n","avg_line_length":30.9,"max_line_length":194,"alphanum_fraction":0.7079288026,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":68534,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"\ufeff#include \"il2cpp-config.h\"\n\n#ifndef _MSC_VER\n# include <alloca.h>\n#else\n# include <malloc.h>\n#endif\n\n\n#include <cstring>\n#include <string.h>\n#include <stdio.h>\n#include <cmath>\n#include <limits>\n#include <assert.h>\n#include <stdint.h>\n\n#include \"il2cpp-class-internals.h\"\n#include \"codegen\/il2cpp-codegen.h\"\n#include \"il2cpp-object-internals.h\"\n\n\n\/\/ System.Char[]\nstruct CharU5BU5D_t3528271667;\n\/\/ System.Void\nstruct Void_t1185182177;\n\/\/ System.Reflection.MethodInfo\nstruct MethodInfo_t;\n\/\/ System.DelegateData\nstruct DelegateData_t1677132599;\n\/\/ System.IAsyncResult\nstruct IAsyncResult_t767004451;\n\/\/ System.AsyncCallback\nstruct AsyncCallback_t3962456242;\n\n\n\n\n#ifndef RUNTIMEOBJECT_H\n#define RUNTIMEOBJECT_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Object\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ RUNTIMEOBJECT_H\n#ifndef VALUETYPE_T3640485471_H\n#define VALUETYPE_T3640485471_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.ValueType\nstruct  ValueType_t3640485471  : public RuntimeObject\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.ValueType\nstruct ValueType_t3640485471_marshaled_pinvoke\n{\n};\n\/\/ Native definition for COM marshalling of System.ValueType\nstruct ValueType_t3640485471_marshaled_com\n{\n};\n#endif \/\/ VALUETYPE_T3640485471_H\n#ifndef UNITYARLIGHTESTIMATE_T1498306117_H\n#define UNITYARLIGHTESTIMATE_T1498306117_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARLightEstimate\nstruct  UnityARLightEstimate_t1498306117 \n{\npublic:\n\t\/\/ System.Single UnityEngine.XR.iOS.UnityARLightEstimate::ambientIntensity\n\tfloat ___ambientIntensity_0;\n\t\/\/ System.Single UnityEngine.XR.iOS.UnityARLightEstimate::ambientColorTemperature\n\tfloat ___ambientColorTemperature_1;\n\npublic:\n\tinline static int32_t get_offset_of_ambientIntensity_0() { return static_cast<int32_t>(offsetof(UnityARLightEstimate_t1498306117, ___ambientIntensity_0)); }\n\tinline float get_ambientIntensity_0() const { return ___ambientIntensity_0; }\n\tinline float* get_address_of_ambientIntensity_0() { return &___ambientIntensity_0; }\n\tinline void set_ambientIntensity_0(float value)\n\t{\n\t\t___ambientIntensity_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_ambientColorTemperature_1() { return static_cast<int32_t>(offsetof(UnityARLightEstimate_t1498306117, ___ambientColorTemperature_1)); }\n\tinline float get_ambientColorTemperature_1() const { return ___ambientColorTemperature_1; }\n\tinline float* get_address_of_ambientColorTemperature_1() { return &___ambientColorTemperature_1; }\n\tinline void set_ambientColorTemperature_1(float value)\n\t{\n\t\t___ambientColorTemperature_1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ UNITYARLIGHTESTIMATE_T1498306117_H\n#ifndef ENUM_T4135868527_H\n#define ENUM_T4135868527_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Enum\nstruct  Enum_t4135868527  : public ValueType_t3640485471\n{\npublic:\n\npublic:\n};\n\nstruct Enum_t4135868527_StaticFields\n{\npublic:\n\t\/\/ System.Char[] System.Enum::split_char\n\tCharU5BU5D_t3528271667* ___split_char_0;\n\npublic:\n\tinline static int32_t get_offset_of_split_char_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___split_char_0)); }\n\tinline CharU5BU5D_t3528271667* get_split_char_0() const { return ___split_char_0; }\n\tinline CharU5BU5D_t3528271667** get_address_of_split_char_0() { return &___split_char_0; }\n\tinline void set_split_char_0(CharU5BU5D_t3528271667* value)\n\t{\n\t\t___split_char_0 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___split_char_0), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of System.Enum\nstruct Enum_t4135868527_marshaled_pinvoke\n{\n};\n\/\/ Native definition for COM marshalling of System.Enum\nstruct Enum_t4135868527_marshaled_com\n{\n};\n#endif \/\/ ENUM_T4135868527_H\n#ifndef VOID_T1185182177_H\n#define VOID_T1185182177_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Void\nstruct  Void_t1185182177 \n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ VOID_T1185182177_H\n#ifndef INTPTR_T_H\n#define INTPTR_T_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.IntPtr\nstruct  IntPtr_t \n{\npublic:\n\t\/\/ System.Void* System.IntPtr::m_value\n\tvoid* ___m_value_0;\n\npublic:\n\tinline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); }\n\tinline void* get_m_value_0() const { return ___m_value_0; }\n\tinline void** get_address_of_m_value_0() { return &___m_value_0; }\n\tinline void set_m_value_0(void* value)\n\t{\n\t\t___m_value_0 = value;\n\t}\n};\n\nstruct IntPtr_t_StaticFields\n{\npublic:\n\t\/\/ System.IntPtr System.IntPtr::Zero\n\tintptr_t ___Zero_1;\n\npublic:\n\tinline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); }\n\tinline intptr_t get_Zero_1() const { return ___Zero_1; }\n\tinline intptr_t* get_address_of_Zero_1() { return &___Zero_1; }\n\tinline void set_Zero_1(intptr_t value)\n\t{\n\t\t___Zero_1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTPTR_T_H\n#ifndef VECTOR4_T3319028937_H\n#define VECTOR4_T3319028937_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.Vector4\nstruct  Vector4_t3319028937 \n{\npublic:\n\t\/\/ System.Single UnityEngine.Vector4::x\n\tfloat ___x_1;\n\t\/\/ System.Single UnityEngine.Vector4::y\n\tfloat ___y_2;\n\t\/\/ System.Single UnityEngine.Vector4::z\n\tfloat ___z_3;\n\t\/\/ System.Single UnityEngine.Vector4::w\n\tfloat ___w_4;\n\npublic:\n\tinline static int32_t get_offset_of_x_1() { return static_cast<int32_t>(offsetof(Vector4_t3319028937, ___x_1)); }\n\tinline float get_x_1() const { return ___x_1; }\n\tinline float* get_address_of_x_1() { return &___x_1; }\n\tinline void set_x_1(float value)\n\t{\n\t\t___x_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_y_2() { return static_cast<int32_t>(offsetof(Vector4_t3319028937, ___y_2)); }\n\tinline float get_y_2() const { return ___y_2; }\n\tinline float* get_address_of_y_2() { return &___y_2; }\n\tinline void set_y_2(float value)\n\t{\n\t\t___y_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_z_3() { return static_cast<int32_t>(offsetof(Vector4_t3319028937, ___z_3)); }\n\tinline float get_z_3() const { return ___z_3; }\n\tinline float* get_address_of_z_3() { return &___z_3; }\n\tinline void set_z_3(float value)\n\t{\n\t\t___z_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_w_4() { return static_cast<int32_t>(offsetof(Vector4_t3319028937, ___w_4)); }\n\tinline float get_w_4() const { return ___w_4; }\n\tinline float* get_address_of_w_4() { return &___w_4; }\n\tinline void set_w_4(float value)\n\t{\n\t\t___w_4 = value;\n\t}\n};\n\nstruct Vector4_t3319028937_StaticFields\n{\npublic:\n\t\/\/ UnityEngine.Vector4 UnityEngine.Vector4::zeroVector\n\tVector4_t3319028937  ___zeroVector_5;\n\t\/\/ UnityEngine.Vector4 UnityEngine.Vector4::oneVector\n\tVector4_t3319028937  ___oneVector_6;\n\t\/\/ UnityEngine.Vector4 UnityEngine.Vector4::positiveInfinityVector\n\tVector4_t3319028937  ___positiveInfinityVector_7;\n\t\/\/ UnityEngine.Vector4 UnityEngine.Vector4::negativeInfinityVector\n\tVector4_t3319028937  ___negativeInfinityVector_8;\n\npublic:\n\tinline static int32_t get_offset_of_zeroVector_5() { return static_cast<int32_t>(offsetof(Vector4_t3319028937_StaticFields, ___zeroVector_5)); }\n\tinline Vector4_t3319028937  get_zeroVector_5() const { return ___zeroVector_5; }\n\tinline Vector4_t3319028937 * get_address_of_zeroVector_5() { return &___zeroVector_5; }\n\tinline void set_zeroVector_5(Vector4_t3319028937  value)\n\t{\n\t\t___zeroVector_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of_oneVector_6() { return static_cast<int32_t>(offsetof(Vector4_t3319028937_StaticFields, ___oneVector_6)); }\n\tinline Vector4_t3319028937  get_oneVector_6() const { return ___oneVector_6; }\n\tinline Vector4_t3319028937 * get_address_of_oneVector_6() { return &___oneVector_6; }\n\tinline void set_oneVector_6(Vector4_t3319028937  value)\n\t{\n\t\t___oneVector_6 = value;\n\t}\n\n\tinline static int32_t get_offset_of_positiveInfinityVector_7() { return static_cast<int32_t>(offsetof(Vector4_t3319028937_StaticFields, ___positiveInfinityVector_7)); }\n\tinline Vector4_t3319028937  get_positiveInfinityVector_7() const { return ___positiveInfinityVector_7; }\n\tinline Vector4_t3319028937 * get_address_of_positiveInfinityVector_7() { return &___positiveInfinityVector_7; }\n\tinline void set_positiveInfinityVector_7(Vector4_t3319028937  value)\n\t{\n\t\t___positiveInfinityVector_7 = value;\n\t}\n\n\tinline static int32_t get_offset_of_negativeInfinityVector_8() { return static_cast<int32_t>(offsetof(Vector4_t3319028937_StaticFields, ___negativeInfinityVector_8)); }\n\tinline Vector4_t3319028937  get_negativeInfinityVector_8() const { return ___negativeInfinityVector_8; }\n\tinline Vector4_t3319028937 * get_address_of_negativeInfinityVector_8() { return &___negativeInfinityVector_8; }\n\tinline void set_negativeInfinityVector_8(Vector4_t3319028937  value)\n\t{\n\t\t___negativeInfinityVector_8 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ VECTOR4_T3319028937_H\n#ifndef DELEGATE_T1188392813_H\n#define DELEGATE_T1188392813_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.Delegate\nstruct  Delegate_t1188392813  : public RuntimeObject\n{\npublic:\n\t\/\/ System.IntPtr System.Delegate::method_ptr\n\tIl2CppMethodPointer ___method_ptr_0;\n\t\/\/ System.IntPtr System.Delegate::invoke_impl\n\tintptr_t ___invoke_impl_1;\n\t\/\/ System.Object System.Delegate::m_target\n\tRuntimeObject * ___m_target_2;\n\t\/\/ System.IntPtr System.Delegate::method\n\tintptr_t ___method_3;\n\t\/\/ System.IntPtr System.Delegate::delegate_trampoline\n\tintptr_t ___delegate_trampoline_4;\n\t\/\/ System.IntPtr System.Delegate::method_code\n\tintptr_t ___method_code_5;\n\t\/\/ System.Reflection.MethodInfo System.Delegate::method_info\n\tMethodInfo_t * ___method_info_6;\n\t\/\/ System.Reflection.MethodInfo System.Delegate::original_method_info\n\tMethodInfo_t * ___original_method_info_7;\n\t\/\/ System.DelegateData System.Delegate::data\n\tDelegateData_t1677132599 * ___data_8;\n\npublic:\n\tinline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_ptr_0)); }\n\tinline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; }\n\tinline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; }\n\tinline void set_method_ptr_0(Il2CppMethodPointer value)\n\t{\n\t\t___method_ptr_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___invoke_impl_1)); }\n\tinline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; }\n\tinline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; }\n\tinline void set_invoke_impl_1(intptr_t value)\n\t{\n\t\t___invoke_impl_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___m_target_2)); }\n\tinline RuntimeObject * get_m_target_2() const { return ___m_target_2; }\n\tinline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; }\n\tinline void set_m_target_2(RuntimeObject * value)\n\t{\n\t\t___m_target_2 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___m_target_2), value);\n\t}\n\n\tinline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_3)); }\n\tinline intptr_t get_method_3() const { return ___method_3; }\n\tinline intptr_t* get_address_of_method_3() { return &___method_3; }\n\tinline void set_method_3(intptr_t value)\n\t{\n\t\t___method_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___delegate_trampoline_4)); }\n\tinline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; }\n\tinline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; }\n\tinline void set_delegate_trampoline_4(intptr_t value)\n\t{\n\t\t___delegate_trampoline_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_method_code_5() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_code_5)); }\n\tinline intptr_t get_method_code_5() const { return ___method_code_5; }\n\tinline intptr_t* get_address_of_method_code_5() { return &___method_code_5; }\n\tinline void set_method_code_5(intptr_t value)\n\t{\n\t\t___method_code_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of_method_info_6() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_info_6)); }\n\tinline MethodInfo_t * get_method_info_6() const { return ___method_info_6; }\n\tinline MethodInfo_t ** get_address_of_method_info_6() { return &___method_info_6; }\n\tinline void set_method_info_6(MethodInfo_t * value)\n\t{\n\t\t___method_info_6 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___method_info_6), value);\n\t}\n\n\tinline static int32_t get_offset_of_original_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___original_method_info_7)); }\n\tinline MethodInfo_t * get_original_method_info_7() const { return ___original_method_info_7; }\n\tinline MethodInfo_t ** get_address_of_original_method_info_7() { return &___original_method_info_7; }\n\tinline void set_original_method_info_7(MethodInfo_t * value)\n\t{\n\t\t___original_method_info_7 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___original_method_info_7), value);\n\t}\n\n\tinline static int32_t get_offset_of_data_8() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___data_8)); }\n\tinline DelegateData_t1677132599 * get_data_8() const { return ___data_8; }\n\tinline DelegateData_t1677132599 ** get_address_of_data_8() { return &___data_8; }\n\tinline void set_data_8(DelegateData_t1677132599 * value)\n\t{\n\t\t___data_8 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___data_8), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ DELEGATE_T1188392813_H\n#ifndef UNITYARMATRIX4X4_T4073345847_H\n#define UNITYARMATRIX4X4_T4073345847_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARMatrix4x4\nstruct  UnityARMatrix4x4_t4073345847 \n{\npublic:\n\t\/\/ UnityEngine.Vector4 UnityEngine.XR.iOS.UnityARMatrix4x4::column0\n\tVector4_t3319028937  ___column0_0;\n\t\/\/ UnityEngine.Vector4 UnityEngine.XR.iOS.UnityARMatrix4x4::column1\n\tVector4_t3319028937  ___column1_1;\n\t\/\/ UnityEngine.Vector4 UnityEngine.XR.iOS.UnityARMatrix4x4::column2\n\tVector4_t3319028937  ___column2_2;\n\t\/\/ UnityEngine.Vector4 UnityEngine.XR.iOS.UnityARMatrix4x4::column3\n\tVector4_t3319028937  ___column3_3;\n\npublic:\n\tinline static int32_t get_offset_of_column0_0() { return static_cast<int32_t>(offsetof(UnityARMatrix4x4_t4073345847, ___column0_0)); }\n\tinline Vector4_t3319028937  get_column0_0() const { return ___column0_0; }\n\tinline Vector4_t3319028937 * get_address_of_column0_0() { return &___column0_0; }\n\tinline void set_column0_0(Vector4_t3319028937  value)\n\t{\n\t\t___column0_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_column1_1() { return static_cast<int32_t>(offsetof(UnityARMatrix4x4_t4073345847, ___column1_1)); }\n\tinline Vector4_t3319028937  get_column1_1() const { return ___column1_1; }\n\tinline Vector4_t3319028937 * get_address_of_column1_1() { return &___column1_1; }\n\tinline void set_column1_1(Vector4_t3319028937  value)\n\t{\n\t\t___column1_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_column2_2() { return static_cast<int32_t>(offsetof(UnityARMatrix4x4_t4073345847, ___column2_2)); }\n\tinline Vector4_t3319028937  get_column2_2() const { return ___column2_2; }\n\tinline Vector4_t3319028937 * get_address_of_column2_2() { return &___column2_2; }\n\tinline void set_column2_2(Vector4_t3319028937  value)\n\t{\n\t\t___column2_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_column3_3() { return static_cast<int32_t>(offsetof(UnityARMatrix4x4_t4073345847, ___column3_3)); }\n\tinline Vector4_t3319028937  get_column3_3() const { return ___column3_3; }\n\tinline Vector4_t3319028937 * get_address_of_column3_3() { return &___column3_3; }\n\tinline void set_column3_3(Vector4_t3319028937  value)\n\t{\n\t\t___column3_3 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ UNITYARMATRIX4X4_T4073345847_H\n#ifndef ARPLANEANCHORALIGNMENT_T2311256121_H\n#define ARPLANEANCHORALIGNMENT_T2311256121_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.ARPlaneAnchorAlignment\nstruct  ARPlaneAnchorAlignment_t2311256121 \n{\npublic:\n\t\/\/ System.Int64 UnityEngine.XR.iOS.ARPlaneAnchorAlignment::value__\n\tint64_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ARPlaneAnchorAlignment_t2311256121, ___value___1)); }\n\tinline int64_t get_value___1() const { return ___value___1; }\n\tinline int64_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int64_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ ARPLANEANCHORALIGNMENT_T2311256121_H\n#ifndef UNITYARFACEGEOMETRY_T4178775532_H\n#define UNITYARFACEGEOMETRY_T4178775532_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARFaceGeometry\nstruct  UnityARFaceGeometry_t4178775532 \n{\npublic:\n\t\/\/ System.Int32 UnityEngine.XR.iOS.UnityARFaceGeometry::vertexCount\n\tint32_t ___vertexCount_0;\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityARFaceGeometry::vertices\n\tintptr_t ___vertices_1;\n\t\/\/ System.Int32 UnityEngine.XR.iOS.UnityARFaceGeometry::textureCoordinateCount\n\tint32_t ___textureCoordinateCount_2;\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityARFaceGeometry::textureCoordinates\n\tintptr_t ___textureCoordinates_3;\n\t\/\/ System.Int32 UnityEngine.XR.iOS.UnityARFaceGeometry::triangleCount\n\tint32_t ___triangleCount_4;\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityARFaceGeometry::triangleIndices\n\tintptr_t ___triangleIndices_5;\n\npublic:\n\tinline static int32_t get_offset_of_vertexCount_0() { return static_cast<int32_t>(offsetof(UnityARFaceGeometry_t4178775532, ___vertexCount_0)); }\n\tinline int32_t get_vertexCount_0() const { return ___vertexCount_0; }\n\tinline int32_t* get_address_of_vertexCount_0() { return &___vertexCount_0; }\n\tinline void set_vertexCount_0(int32_t value)\n\t{\n\t\t___vertexCount_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_vertices_1() { return static_cast<int32_t>(offsetof(UnityARFaceGeometry_t4178775532, ___vertices_1)); }\n\tinline intptr_t get_vertices_1() const { return ___vertices_1; }\n\tinline intptr_t* get_address_of_vertices_1() { return &___vertices_1; }\n\tinline void set_vertices_1(intptr_t value)\n\t{\n\t\t___vertices_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_textureCoordinateCount_2() { return static_cast<int32_t>(offsetof(UnityARFaceGeometry_t4178775532, ___textureCoordinateCount_2)); }\n\tinline int32_t get_textureCoordinateCount_2() const { return ___textureCoordinateCount_2; }\n\tinline int32_t* get_address_of_textureCoordinateCount_2() { return &___textureCoordinateCount_2; }\n\tinline void set_textureCoordinateCount_2(int32_t value)\n\t{\n\t\t___textureCoordinateCount_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_textureCoordinates_3() { return static_cast<int32_t>(offsetof(UnityARFaceGeometry_t4178775532, ___textureCoordinates_3)); }\n\tinline intptr_t get_textureCoordinates_3() const { return ___textureCoordinates_3; }\n\tinline intptr_t* get_address_of_textureCoordinates_3() { return &___textureCoordinates_3; }\n\tinline void set_textureCoordinates_3(intptr_t value)\n\t{\n\t\t___textureCoordinates_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_triangleCount_4() { return static_cast<int32_t>(offsetof(UnityARFaceGeometry_t4178775532, ___triangleCount_4)); }\n\tinline int32_t get_triangleCount_4() const { return ___triangleCount_4; }\n\tinline int32_t* get_address_of_triangleCount_4() { return &___triangleCount_4; }\n\tinline void set_triangleCount_4(int32_t value)\n\t{\n\t\t___triangleCount_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_triangleIndices_5() { return static_cast<int32_t>(offsetof(UnityARFaceGeometry_t4178775532, ___triangleIndices_5)); }\n\tinline intptr_t get_triangleIndices_5() const { return ___triangleIndices_5; }\n\tinline intptr_t* get_address_of_triangleIndices_5() { return &___triangleIndices_5; }\n\tinline void set_triangleIndices_5(intptr_t value)\n\t{\n\t\t___triangleIndices_5 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ UNITYARFACEGEOMETRY_T4178775532_H\n#ifndef ARTRACKINGSTATE_T3182235352_H\n#define ARTRACKINGSTATE_T3182235352_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.ARTrackingState\nstruct  ARTrackingState_t3182235352 \n{\npublic:\n\t\/\/ System.Int32 UnityEngine.XR.iOS.ARTrackingState::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ARTrackingState_t3182235352, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ ARTRACKINGSTATE_T3182235352_H\n#ifndef ARTRACKINGSTATEREASON_T2348933773_H\n#define ARTRACKINGSTATEREASON_T2348933773_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.ARTrackingStateReason\nstruct  ARTrackingStateReason_t2348933773 \n{\npublic:\n\t\/\/ System.Int32 UnityEngine.XR.iOS.ARTrackingStateReason::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ARTrackingStateReason_t2348933773, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ ARTRACKINGSTATEREASON_T2348933773_H\n#ifndef UNITYVIDEOPARAMS_T4155354995_H\n#define UNITYVIDEOPARAMS_T4155354995_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityVideoParams\nstruct  UnityVideoParams_t4155354995 \n{\npublic:\n\t\/\/ System.Int32 UnityEngine.XR.iOS.UnityVideoParams::yWidth\n\tint32_t ___yWidth_0;\n\t\/\/ System.Int32 UnityEngine.XR.iOS.UnityVideoParams::yHeight\n\tint32_t ___yHeight_1;\n\t\/\/ System.Int32 UnityEngine.XR.iOS.UnityVideoParams::screenOrientation\n\tint32_t ___screenOrientation_2;\n\t\/\/ System.Single UnityEngine.XR.iOS.UnityVideoParams::texCoordScale\n\tfloat ___texCoordScale_3;\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityVideoParams::cvPixelBufferPtr\n\tintptr_t ___cvPixelBufferPtr_4;\n\npublic:\n\tinline static int32_t get_offset_of_yWidth_0() { return static_cast<int32_t>(offsetof(UnityVideoParams_t4155354995, ___yWidth_0)); }\n\tinline int32_t get_yWidth_0() const { return ___yWidth_0; }\n\tinline int32_t* get_address_of_yWidth_0() { return &___yWidth_0; }\n\tinline void set_yWidth_0(int32_t value)\n\t{\n\t\t___yWidth_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_yHeight_1() { return static_cast<int32_t>(offsetof(UnityVideoParams_t4155354995, ___yHeight_1)); }\n\tinline int32_t get_yHeight_1() const { return ___yHeight_1; }\n\tinline int32_t* get_address_of_yHeight_1() { return &___yHeight_1; }\n\tinline void set_yHeight_1(int32_t value)\n\t{\n\t\t___yHeight_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_screenOrientation_2() { return static_cast<int32_t>(offsetof(UnityVideoParams_t4155354995, ___screenOrientation_2)); }\n\tinline int32_t get_screenOrientation_2() const { return ___screenOrientation_2; }\n\tinline int32_t* get_address_of_screenOrientation_2() { return &___screenOrientation_2; }\n\tinline void set_screenOrientation_2(int32_t value)\n\t{\n\t\t___screenOrientation_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_texCoordScale_3() { return static_cast<int32_t>(offsetof(UnityVideoParams_t4155354995, ___texCoordScale_3)); }\n\tinline float get_texCoordScale_3() const { return ___texCoordScale_3; }\n\tinline float* get_address_of_texCoordScale_3() { return &___texCoordScale_3; }\n\tinline void set_texCoordScale_3(float value)\n\t{\n\t\t___texCoordScale_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_cvPixelBufferPtr_4() { return static_cast<int32_t>(offsetof(UnityVideoParams_t4155354995, ___cvPixelBufferPtr_4)); }\n\tinline intptr_t get_cvPixelBufferPtr_4() const { return ___cvPixelBufferPtr_4; }\n\tinline intptr_t* get_address_of_cvPixelBufferPtr_4() { return &___cvPixelBufferPtr_4; }\n\tinline void set_cvPixelBufferPtr_4(intptr_t value)\n\t{\n\t\t___cvPixelBufferPtr_4 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ UNITYVIDEOPARAMS_T4155354995_H\n#ifndef OBJECT_T631007953_H\n#define OBJECT_T631007953_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.Object\nstruct  Object_t631007953  : public RuntimeObject\n{\npublic:\n\t\/\/ System.IntPtr UnityEngine.Object::m_CachedPtr\n\tintptr_t ___m_CachedPtr_0;\n\npublic:\n\tinline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_t631007953, ___m_CachedPtr_0)); }\n\tinline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; }\n\tinline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; }\n\tinline void set_m_CachedPtr_0(intptr_t value)\n\t{\n\t\t___m_CachedPtr_0 = value;\n\t}\n};\n\nstruct Object_t631007953_StaticFields\n{\npublic:\n\t\/\/ System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject\n\tint32_t ___OffsetOfInstanceIDInCPlusPlusObject_1;\n\npublic:\n\tinline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_t631007953_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); }\n\tinline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; }\n\tinline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; }\n\tinline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value)\n\t{\n\t\t___OffsetOfInstanceIDInCPlusPlusObject_1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of UnityEngine.Object\nstruct Object_t631007953_marshaled_pinvoke\n{\n\tintptr_t ___m_CachedPtr_0;\n};\n\/\/ Native definition for COM marshalling of UnityEngine.Object\nstruct Object_t631007953_marshaled_com\n{\n\tintptr_t ___m_CachedPtr_0;\n};\n#endif \/\/ OBJECT_T631007953_H\n#ifndef LIGHTDATATYPE_T2323651587_H\n#define LIGHTDATATYPE_T2323651587_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.LightDataType\nstruct  LightDataType_t2323651587 \n{\npublic:\n\t\/\/ System.Int32 UnityEngine.XR.iOS.LightDataType::value__\n\tint32_t ___value___1;\n\npublic:\n\tinline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(LightDataType_t2323651587, ___value___1)); }\n\tinline int32_t get_value___1() const { return ___value___1; }\n\tinline int32_t* get_address_of_value___1() { return &___value___1; }\n\tinline void set_value___1(int32_t value)\n\t{\n\t\t___value___1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ LIGHTDATATYPE_T2323651587_H\n#ifndef UNITYARPLANEGEOMETRY_T1646881137_H\n#define UNITYARPLANEGEOMETRY_T1646881137_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARPlaneGeometry\nstruct  UnityARPlaneGeometry_t1646881137 \n{\npublic:\n\t\/\/ System.Int32 UnityEngine.XR.iOS.UnityARPlaneGeometry::vertexCount\n\tint32_t ___vertexCount_0;\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityARPlaneGeometry::vertices\n\tintptr_t ___vertices_1;\n\t\/\/ System.Int32 UnityEngine.XR.iOS.UnityARPlaneGeometry::textureCoordinateCount\n\tint32_t ___textureCoordinateCount_2;\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityARPlaneGeometry::textureCoordinates\n\tintptr_t ___textureCoordinates_3;\n\t\/\/ System.Int32 UnityEngine.XR.iOS.UnityARPlaneGeometry::triangleCount\n\tint32_t ___triangleCount_4;\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityARPlaneGeometry::triangleIndices\n\tintptr_t ___triangleIndices_5;\n\t\/\/ System.Int32 UnityEngine.XR.iOS.UnityARPlaneGeometry::boundaryVertexCount\n\tint32_t ___boundaryVertexCount_6;\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityARPlaneGeometry::boundaryVertices\n\tintptr_t ___boundaryVertices_7;\n\npublic:\n\tinline static int32_t get_offset_of_vertexCount_0() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1646881137, ___vertexCount_0)); }\n\tinline int32_t get_vertexCount_0() const { return ___vertexCount_0; }\n\tinline int32_t* get_address_of_vertexCount_0() { return &___vertexCount_0; }\n\tinline void set_vertexCount_0(int32_t value)\n\t{\n\t\t___vertexCount_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_vertices_1() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1646881137, ___vertices_1)); }\n\tinline intptr_t get_vertices_1() const { return ___vertices_1; }\n\tinline intptr_t* get_address_of_vertices_1() { return &___vertices_1; }\n\tinline void set_vertices_1(intptr_t value)\n\t{\n\t\t___vertices_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_textureCoordinateCount_2() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1646881137, ___textureCoordinateCount_2)); }\n\tinline int32_t get_textureCoordinateCount_2() const { return ___textureCoordinateCount_2; }\n\tinline int32_t* get_address_of_textureCoordinateCount_2() { return &___textureCoordinateCount_2; }\n\tinline void set_textureCoordinateCount_2(int32_t value)\n\t{\n\t\t___textureCoordinateCount_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_textureCoordinates_3() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1646881137, ___textureCoordinates_3)); }\n\tinline intptr_t get_textureCoordinates_3() const { return ___textureCoordinates_3; }\n\tinline intptr_t* get_address_of_textureCoordinates_3() { return &___textureCoordinates_3; }\n\tinline void set_textureCoordinates_3(intptr_t value)\n\t{\n\t\t___textureCoordinates_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_triangleCount_4() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1646881137, ___triangleCount_4)); }\n\tinline int32_t get_triangleCount_4() const { return ___triangleCount_4; }\n\tinline int32_t* get_address_of_triangleCount_4() { return &___triangleCount_4; }\n\tinline void set_triangleCount_4(int32_t value)\n\t{\n\t\t___triangleCount_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_triangleIndices_5() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1646881137, ___triangleIndices_5)); }\n\tinline intptr_t get_triangleIndices_5() const { return ___triangleIndices_5; }\n\tinline intptr_t* get_address_of_triangleIndices_5() { return &___triangleIndices_5; }\n\tinline void set_triangleIndices_5(intptr_t value)\n\t{\n\t\t___triangleIndices_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of_boundaryVertexCount_6() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1646881137, ___boundaryVertexCount_6)); }\n\tinline int32_t get_boundaryVertexCount_6() const { return ___boundaryVertexCount_6; }\n\tinline int32_t* get_address_of_boundaryVertexCount_6() { return &___boundaryVertexCount_6; }\n\tinline void set_boundaryVertexCount_6(int32_t value)\n\t{\n\t\t___boundaryVertexCount_6 = value;\n\t}\n\n\tinline static int32_t get_offset_of_boundaryVertices_7() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1646881137, ___boundaryVertices_7)); }\n\tinline intptr_t get_boundaryVertices_7() const { return ___boundaryVertices_7; }\n\tinline intptr_t* get_address_of_boundaryVertices_7() { return &___boundaryVertices_7; }\n\tinline void set_boundaryVertices_7(intptr_t value)\n\t{\n\t\t___boundaryVertices_7 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ UNITYARPLANEGEOMETRY_T1646881137_H\n#ifndef MARSHALDIRECTIONALLIGHTESTIMATE_T3803901471_H\n#define MARSHALDIRECTIONALLIGHTESTIMATE_T3803901471_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.MarshalDirectionalLightEstimate\nstruct  MarshalDirectionalLightEstimate_t3803901471 \n{\npublic:\n\t\/\/ UnityEngine.Vector4 UnityEngine.XR.iOS.MarshalDirectionalLightEstimate::primaryDirAndIntensity\n\tVector4_t3319028937  ___primaryDirAndIntensity_0;\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.MarshalDirectionalLightEstimate::sphericalHarmonicCoefficientsPtr\n\tintptr_t ___sphericalHarmonicCoefficientsPtr_1;\n\npublic:\n\tinline static int32_t get_offset_of_primaryDirAndIntensity_0() { return static_cast<int32_t>(offsetof(MarshalDirectionalLightEstimate_t3803901471, ___primaryDirAndIntensity_0)); }\n\tinline Vector4_t3319028937  get_primaryDirAndIntensity_0() const { return ___primaryDirAndIntensity_0; }\n\tinline Vector4_t3319028937 * get_address_of_primaryDirAndIntensity_0() { return &___primaryDirAndIntensity_0; }\n\tinline void set_primaryDirAndIntensity_0(Vector4_t3319028937  value)\n\t{\n\t\t___primaryDirAndIntensity_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_sphericalHarmonicCoefficientsPtr_1() { return static_cast<int32_t>(offsetof(MarshalDirectionalLightEstimate_t3803901471, ___sphericalHarmonicCoefficientsPtr_1)); }\n\tinline intptr_t get_sphericalHarmonicCoefficientsPtr_1() const { return ___sphericalHarmonicCoefficientsPtr_1; }\n\tinline intptr_t* get_address_of_sphericalHarmonicCoefficientsPtr_1() { return &___sphericalHarmonicCoefficientsPtr_1; }\n\tinline void set_sphericalHarmonicCoefficientsPtr_1(intptr_t value)\n\t{\n\t\t___sphericalHarmonicCoefficientsPtr_1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ MARSHALDIRECTIONALLIGHTESTIMATE_T3803901471_H\n#ifndef SCRIPTABLEOBJECT_T2528358522_H\n#define SCRIPTABLEOBJECT_T2528358522_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.ScriptableObject\nstruct  ScriptableObject_t2528358522  : public Object_t631007953\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of UnityEngine.ScriptableObject\nstruct ScriptableObject_t2528358522_marshaled_pinvoke : public Object_t631007953_marshaled_pinvoke\n{\n};\n\/\/ Native definition for COM marshalling of UnityEngine.ScriptableObject\nstruct ScriptableObject_t2528358522_marshaled_com : public Object_t631007953_marshaled_com\n{\n};\n#endif \/\/ SCRIPTABLEOBJECT_T2528358522_H\n#ifndef UNITYMARSHALLIGHTDATA_T1623228070_H\n#define UNITYMARSHALLIGHTDATA_T1623228070_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityMarshalLightData\nstruct  UnityMarshalLightData_t1623228070 \n{\npublic:\n\t\/\/ UnityEngine.XR.iOS.LightDataType UnityEngine.XR.iOS.UnityMarshalLightData::arLightingType\n\tint32_t ___arLightingType_0;\n\t\/\/ UnityEngine.XR.iOS.UnityARLightEstimate UnityEngine.XR.iOS.UnityMarshalLightData::arLightEstimate\n\tUnityARLightEstimate_t1498306117  ___arLightEstimate_1;\n\t\/\/ UnityEngine.XR.iOS.MarshalDirectionalLightEstimate UnityEngine.XR.iOS.UnityMarshalLightData::arDirectonalLightEstimate\n\tMarshalDirectionalLightEstimate_t3803901471  ___arDirectonalLightEstimate_2;\n\npublic:\n\tinline static int32_t get_offset_of_arLightingType_0() { return static_cast<int32_t>(offsetof(UnityMarshalLightData_t1623228070, ___arLightingType_0)); }\n\tinline int32_t get_arLightingType_0() const { return ___arLightingType_0; }\n\tinline int32_t* get_address_of_arLightingType_0() { return &___arLightingType_0; }\n\tinline void set_arLightingType_0(int32_t value)\n\t{\n\t\t___arLightingType_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_arLightEstimate_1() { return static_cast<int32_t>(offsetof(UnityMarshalLightData_t1623228070, ___arLightEstimate_1)); }\n\tinline UnityARLightEstimate_t1498306117  get_arLightEstimate_1() const { return ___arLightEstimate_1; }\n\tinline UnityARLightEstimate_t1498306117 * get_address_of_arLightEstimate_1() { return &___arLightEstimate_1; }\n\tinline void set_arLightEstimate_1(UnityARLightEstimate_t1498306117  value)\n\t{\n\t\t___arLightEstimate_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_arDirectonalLightEstimate_2() { return static_cast<int32_t>(offsetof(UnityMarshalLightData_t1623228070, ___arDirectonalLightEstimate_2)); }\n\tinline MarshalDirectionalLightEstimate_t3803901471  get_arDirectonalLightEstimate_2() const { return ___arDirectonalLightEstimate_2; }\n\tinline MarshalDirectionalLightEstimate_t3803901471 * get_address_of_arDirectonalLightEstimate_2() { return &___arDirectonalLightEstimate_2; }\n\tinline void set_arDirectonalLightEstimate_2(MarshalDirectionalLightEstimate_t3803901471  value)\n\t{\n\t\t___arDirectonalLightEstimate_2 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ UNITYMARSHALLIGHTDATA_T1623228070_H\n#ifndef UNITYARIMAGEANCHORDATA_T4182571716_H\n#define UNITYARIMAGEANCHORDATA_T4182571716_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARImageAnchorData\nstruct  UnityARImageAnchorData_t4182571716 \n{\npublic:\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityARImageAnchorData::ptrIdentifier\n\tintptr_t ___ptrIdentifier_0;\n\t\/\/ UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARImageAnchorData::transform\n\tUnityARMatrix4x4_t4073345847  ___transform_1;\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityARImageAnchorData::referenceImageNamePtr\n\tintptr_t ___referenceImageNamePtr_2;\n\t\/\/ System.Single UnityEngine.XR.iOS.UnityARImageAnchorData::referenceImagePhysicalSize\n\tfloat ___referenceImagePhysicalSize_3;\n\npublic:\n\tinline static int32_t get_offset_of_ptrIdentifier_0() { return static_cast<int32_t>(offsetof(UnityARImageAnchorData_t4182571716, ___ptrIdentifier_0)); }\n\tinline intptr_t get_ptrIdentifier_0() const { return ___ptrIdentifier_0; }\n\tinline intptr_t* get_address_of_ptrIdentifier_0() { return &___ptrIdentifier_0; }\n\tinline void set_ptrIdentifier_0(intptr_t value)\n\t{\n\t\t___ptrIdentifier_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_transform_1() { return static_cast<int32_t>(offsetof(UnityARImageAnchorData_t4182571716, ___transform_1)); }\n\tinline UnityARMatrix4x4_t4073345847  get_transform_1() const { return ___transform_1; }\n\tinline UnityARMatrix4x4_t4073345847 * get_address_of_transform_1() { return &___transform_1; }\n\tinline void set_transform_1(UnityARMatrix4x4_t4073345847  value)\n\t{\n\t\t___transform_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_referenceImageNamePtr_2() { return static_cast<int32_t>(offsetof(UnityARImageAnchorData_t4182571716, ___referenceImageNamePtr_2)); }\n\tinline intptr_t get_referenceImageNamePtr_2() const { return ___referenceImageNamePtr_2; }\n\tinline intptr_t* get_address_of_referenceImageNamePtr_2() { return &___referenceImageNamePtr_2; }\n\tinline void set_referenceImageNamePtr_2(intptr_t value)\n\t{\n\t\t___referenceImageNamePtr_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_referenceImagePhysicalSize_3() { return static_cast<int32_t>(offsetof(UnityARImageAnchorData_t4182571716, ___referenceImagePhysicalSize_3)); }\n\tinline float get_referenceImagePhysicalSize_3() const { return ___referenceImagePhysicalSize_3; }\n\tinline float* get_address_of_referenceImagePhysicalSize_3() { return &___referenceImagePhysicalSize_3; }\n\tinline void set_referenceImagePhysicalSize_3(float value)\n\t{\n\t\t___referenceImagePhysicalSize_3 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ UNITYARIMAGEANCHORDATA_T4182571716_H\n#ifndef UNITYARFACEANCHORDATA_T2028622935_H\n#define UNITYARFACEANCHORDATA_T2028622935_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARFaceAnchorData\nstruct  UnityARFaceAnchorData_t2028622935 \n{\npublic:\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityARFaceAnchorData::ptrIdentifier\n\tintptr_t ___ptrIdentifier_0;\n\t\/\/ UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARFaceAnchorData::transform\n\tUnityARMatrix4x4_t4073345847  ___transform_1;\n\t\/\/ UnityEngine.XR.iOS.UnityARFaceGeometry UnityEngine.XR.iOS.UnityARFaceAnchorData::faceGeometry\n\tUnityARFaceGeometry_t4178775532  ___faceGeometry_2;\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityARFaceAnchorData::blendShapes\n\tintptr_t ___blendShapes_3;\n\t\/\/ System.Boolean UnityEngine.XR.iOS.UnityARFaceAnchorData::isTracked\n\tbool ___isTracked_4;\n\npublic:\n\tinline static int32_t get_offset_of_ptrIdentifier_0() { return static_cast<int32_t>(offsetof(UnityARFaceAnchorData_t2028622935, ___ptrIdentifier_0)); }\n\tinline intptr_t get_ptrIdentifier_0() const { return ___ptrIdentifier_0; }\n\tinline intptr_t* get_address_of_ptrIdentifier_0() { return &___ptrIdentifier_0; }\n\tinline void set_ptrIdentifier_0(intptr_t value)\n\t{\n\t\t___ptrIdentifier_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_transform_1() { return static_cast<int32_t>(offsetof(UnityARFaceAnchorData_t2028622935, ___transform_1)); }\n\tinline UnityARMatrix4x4_t4073345847  get_transform_1() const { return ___transform_1; }\n\tinline UnityARMatrix4x4_t4073345847 * get_address_of_transform_1() { return &___transform_1; }\n\tinline void set_transform_1(UnityARMatrix4x4_t4073345847  value)\n\t{\n\t\t___transform_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_faceGeometry_2() { return static_cast<int32_t>(offsetof(UnityARFaceAnchorData_t2028622935, ___faceGeometry_2)); }\n\tinline UnityARFaceGeometry_t4178775532  get_faceGeometry_2() const { return ___faceGeometry_2; }\n\tinline UnityARFaceGeometry_t4178775532 * get_address_of_faceGeometry_2() { return &___faceGeometry_2; }\n\tinline void set_faceGeometry_2(UnityARFaceGeometry_t4178775532  value)\n\t{\n\t\t___faceGeometry_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_blendShapes_3() { return static_cast<int32_t>(offsetof(UnityARFaceAnchorData_t2028622935, ___blendShapes_3)); }\n\tinline intptr_t get_blendShapes_3() const { return ___blendShapes_3; }\n\tinline intptr_t* get_address_of_blendShapes_3() { return &___blendShapes_3; }\n\tinline void set_blendShapes_3(intptr_t value)\n\t{\n\t\t___blendShapes_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_isTracked_4() { return static_cast<int32_t>(offsetof(UnityARFaceAnchorData_t2028622935, ___isTracked_4)); }\n\tinline bool get_isTracked_4() const { return ___isTracked_4; }\n\tinline bool* get_address_of_isTracked_4() { return &___isTracked_4; }\n\tinline void set_isTracked_4(bool value)\n\t{\n\t\t___isTracked_4 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\/\/ Native definition for P\/Invoke marshalling of UnityEngine.XR.iOS.UnityARFaceAnchorData\nstruct UnityARFaceAnchorData_t2028622935_marshaled_pinvoke\n{\n\tintptr_t ___ptrIdentifier_0;\n\tUnityARMatrix4x4_t4073345847  ___transform_1;\n\tUnityARFaceGeometry_t4178775532  ___faceGeometry_2;\n\tintptr_t ___blendShapes_3;\n\tint32_t ___isTracked_4;\n};\n\/\/ Native definition for COM marshalling of UnityEngine.XR.iOS.UnityARFaceAnchorData\nstruct UnityARFaceAnchorData_t2028622935_marshaled_com\n{\n\tintptr_t ___ptrIdentifier_0;\n\tUnityARMatrix4x4_t4073345847  ___transform_1;\n\tUnityARFaceGeometry_t4178775532  ___faceGeometry_2;\n\tintptr_t ___blendShapes_3;\n\tint32_t ___isTracked_4;\n};\n#endif \/\/ UNITYARFACEANCHORDATA_T2028622935_H\n#ifndef UNITYARUSERANCHORDATA_T1976826249_H\n#define UNITYARUSERANCHORDATA_T1976826249_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARUserAnchorData\nstruct  UnityARUserAnchorData_t1976826249 \n{\npublic:\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityARUserAnchorData::ptrIdentifier\n\tintptr_t ___ptrIdentifier_0;\n\t\/\/ UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARUserAnchorData::transform\n\tUnityARMatrix4x4_t4073345847  ___transform_1;\n\npublic:\n\tinline static int32_t get_offset_of_ptrIdentifier_0() { return static_cast<int32_t>(offsetof(UnityARUserAnchorData_t1976826249, ___ptrIdentifier_0)); }\n\tinline intptr_t get_ptrIdentifier_0() const { return ___ptrIdentifier_0; }\n\tinline intptr_t* get_address_of_ptrIdentifier_0() { return &___ptrIdentifier_0; }\n\tinline void set_ptrIdentifier_0(intptr_t value)\n\t{\n\t\t___ptrIdentifier_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_transform_1() { return static_cast<int32_t>(offsetof(UnityARUserAnchorData_t1976826249, ___transform_1)); }\n\tinline UnityARMatrix4x4_t4073345847  get_transform_1() const { return ___transform_1; }\n\tinline UnityARMatrix4x4_t4073345847 * get_address_of_transform_1() { return &___transform_1; }\n\tinline void set_transform_1(UnityARMatrix4x4_t4073345847  value)\n\t{\n\t\t___transform_1 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ UNITYARUSERANCHORDATA_T1976826249_H\n#ifndef UNITYARANCHORDATA_T1157236668_H\n#define UNITYARANCHORDATA_T1157236668_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARAnchorData\nstruct  UnityARAnchorData_t1157236668 \n{\npublic:\n\t\/\/ System.IntPtr UnityEngine.XR.iOS.UnityARAnchorData::ptrIdentifier\n\tintptr_t ___ptrIdentifier_0;\n\t\/\/ UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARAnchorData::transform\n\tUnityARMatrix4x4_t4073345847  ___transform_1;\n\t\/\/ UnityEngine.XR.iOS.ARPlaneAnchorAlignment UnityEngine.XR.iOS.UnityARAnchorData::alignment\n\tint64_t ___alignment_2;\n\t\/\/ UnityEngine.Vector4 UnityEngine.XR.iOS.UnityARAnchorData::center\n\tVector4_t3319028937  ___center_3;\n\t\/\/ UnityEngine.Vector4 UnityEngine.XR.iOS.UnityARAnchorData::extent\n\tVector4_t3319028937  ___extent_4;\n\t\/\/ UnityEngine.XR.iOS.UnityARPlaneGeometry UnityEngine.XR.iOS.UnityARAnchorData::planeGeometry\n\tUnityARPlaneGeometry_t1646881137  ___planeGeometry_5;\n\npublic:\n\tinline static int32_t get_offset_of_ptrIdentifier_0() { return static_cast<int32_t>(offsetof(UnityARAnchorData_t1157236668, ___ptrIdentifier_0)); }\n\tinline intptr_t get_ptrIdentifier_0() const { return ___ptrIdentifier_0; }\n\tinline intptr_t* get_address_of_ptrIdentifier_0() { return &___ptrIdentifier_0; }\n\tinline void set_ptrIdentifier_0(intptr_t value)\n\t{\n\t\t___ptrIdentifier_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_transform_1() { return static_cast<int32_t>(offsetof(UnityARAnchorData_t1157236668, ___transform_1)); }\n\tinline UnityARMatrix4x4_t4073345847  get_transform_1() const { return ___transform_1; }\n\tinline UnityARMatrix4x4_t4073345847 * get_address_of_transform_1() { return &___transform_1; }\n\tinline void set_transform_1(UnityARMatrix4x4_t4073345847  value)\n\t{\n\t\t___transform_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_alignment_2() { return static_cast<int32_t>(offsetof(UnityARAnchorData_t1157236668, ___alignment_2)); }\n\tinline int64_t get_alignment_2() const { return ___alignment_2; }\n\tinline int64_t* get_address_of_alignment_2() { return &___alignment_2; }\n\tinline void set_alignment_2(int64_t value)\n\t{\n\t\t___alignment_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_center_3() { return static_cast<int32_t>(offsetof(UnityARAnchorData_t1157236668, ___center_3)); }\n\tinline Vector4_t3319028937  get_center_3() const { return ___center_3; }\n\tinline Vector4_t3319028937 * get_address_of_center_3() { return &___center_3; }\n\tinline void set_center_3(Vector4_t3319028937  value)\n\t{\n\t\t___center_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_extent_4() { return static_cast<int32_t>(offsetof(UnityARAnchorData_t1157236668, ___extent_4)); }\n\tinline Vector4_t3319028937  get_extent_4() const { return ___extent_4; }\n\tinline Vector4_t3319028937 * get_address_of_extent_4() { return &___extent_4; }\n\tinline void set_extent_4(Vector4_t3319028937  value)\n\t{\n\t\t___extent_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_planeGeometry_5() { return static_cast<int32_t>(offsetof(UnityARAnchorData_t1157236668, ___planeGeometry_5)); }\n\tinline UnityARPlaneGeometry_t1646881137  get_planeGeometry_5() const { return ___planeGeometry_5; }\n\tinline UnityARPlaneGeometry_t1646881137 * get_address_of_planeGeometry_5() { return &___planeGeometry_5; }\n\tinline void set_planeGeometry_5(UnityARPlaneGeometry_t1646881137  value)\n\t{\n\t\t___planeGeometry_5 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ UNITYARANCHORDATA_T1157236668_H\n#ifndef MULTICASTDELEGATE_T_H\n#define MULTICASTDELEGATE_T_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ System.MulticastDelegate\nstruct  MulticastDelegate_t  : public Delegate_t1188392813\n{\npublic:\n\t\/\/ System.MulticastDelegate System.MulticastDelegate::prev\n\tMulticastDelegate_t * ___prev_9;\n\t\/\/ System.MulticastDelegate System.MulticastDelegate::kpm_next\n\tMulticastDelegate_t * ___kpm_next_10;\n\npublic:\n\tinline static int32_t get_offset_of_prev_9() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___prev_9)); }\n\tinline MulticastDelegate_t * get_prev_9() const { return ___prev_9; }\n\tinline MulticastDelegate_t ** get_address_of_prev_9() { return &___prev_9; }\n\tinline void set_prev_9(MulticastDelegate_t * value)\n\t{\n\t\t___prev_9 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___prev_9), value);\n\t}\n\n\tinline static int32_t get_offset_of_kpm_next_10() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___kpm_next_10)); }\n\tinline MulticastDelegate_t * get_kpm_next_10() const { return ___kpm_next_10; }\n\tinline MulticastDelegate_t ** get_address_of_kpm_next_10() { return &___kpm_next_10; }\n\tinline void set_kpm_next_10(MulticastDelegate_t * value)\n\t{\n\t\t___kpm_next_10 = value;\n\t\tIl2CppCodeGenWriteBarrier((&___kpm_next_10), value);\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ MULTICASTDELEGATE_T_H\n#ifndef INTERNAL_ARANCHORUPDATED_T2645242205_H\n#define INTERNAL_ARANCHORUPDATED_T2645242205_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARSessionNativeInterface\/internal_ARAnchorUpdated\nstruct  internal_ARAnchorUpdated_t2645242205  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_ARANCHORUPDATED_T2645242205_H\n#ifndef INTERNAL_ARANCHORREMOVED_T3371657877_H\n#define INTERNAL_ARANCHORREMOVED_T3371657877_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARSessionNativeInterface\/internal_ARAnchorRemoved\nstruct  internal_ARAnchorRemoved_t3371657877  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_ARANCHORREMOVED_T3371657877_H\n#ifndef INTERNAL_ARUSERANCHORADDED_T3285282493_H\n#define INTERNAL_ARUSERANCHORADDED_T3285282493_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARSessionNativeInterface\/internal_ARUserAnchorAdded\nstruct  internal_ARUserAnchorAdded_t3285282493  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_ARUSERANCHORADDED_T3285282493_H\n#ifndef INTERNAL_ARUSERANCHORUPDATED_T3964727538_H\n#define INTERNAL_ARUSERANCHORUPDATED_T3964727538_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARSessionNativeInterface\/internal_ARUserAnchorUpdated\nstruct  internal_ARUserAnchorUpdated_t3964727538  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_ARUSERANCHORUPDATED_T3964727538_H\n#ifndef INTERNAL_ARUSERANCHORREMOVED_T386858594_H\n#define INTERNAL_ARUSERANCHORREMOVED_T386858594_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARSessionNativeInterface\/internal_ARUserAnchorRemoved\nstruct  internal_ARUserAnchorRemoved_t386858594  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_ARUSERANCHORREMOVED_T386858594_H\n#ifndef INTERNAL_ARFACEANCHORADDED_T1021040265_H\n#define INTERNAL_ARFACEANCHORADDED_T1021040265_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARSessionNativeInterface\/internal_ARFaceAnchorAdded\nstruct  internal_ARFaceAnchorAdded_t1021040265  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_ARFACEANCHORADDED_T1021040265_H\n#ifndef INTERNAL_ARFACEANCHORREMOVED_T2563439402_H\n#define INTERNAL_ARFACEANCHORREMOVED_T2563439402_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARSessionNativeInterface\/internal_ARFaceAnchorRemoved\nstruct  internal_ARFaceAnchorRemoved_t2563439402  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_ARFACEANCHORREMOVED_T2563439402_H\n#ifndef INTERNAL_UNITYARCAMERA_T3920739388_H\n#define INTERNAL_UNITYARCAMERA_T3920739388_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.internal_UnityARCamera\nstruct  internal_UnityARCamera_t3920739388 \n{\npublic:\n\t\/\/ UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.internal_UnityARCamera::worldTransform\n\tUnityARMatrix4x4_t4073345847  ___worldTransform_0;\n\t\/\/ UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.internal_UnityARCamera::projectionMatrix\n\tUnityARMatrix4x4_t4073345847  ___projectionMatrix_1;\n\t\/\/ UnityEngine.XR.iOS.ARTrackingState UnityEngine.XR.iOS.internal_UnityARCamera::trackingState\n\tint32_t ___trackingState_2;\n\t\/\/ UnityEngine.XR.iOS.ARTrackingStateReason UnityEngine.XR.iOS.internal_UnityARCamera::trackingReason\n\tint32_t ___trackingReason_3;\n\t\/\/ UnityEngine.XR.iOS.UnityVideoParams UnityEngine.XR.iOS.internal_UnityARCamera::videoParams\n\tUnityVideoParams_t4155354995  ___videoParams_4;\n\t\/\/ UnityEngine.XR.iOS.UnityMarshalLightData UnityEngine.XR.iOS.internal_UnityARCamera::lightData\n\tUnityMarshalLightData_t1623228070  ___lightData_5;\n\t\/\/ UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.internal_UnityARCamera::displayTransform\n\tUnityARMatrix4x4_t4073345847  ___displayTransform_6;\n\t\/\/ System.UInt32 UnityEngine.XR.iOS.internal_UnityARCamera::getPointCloudData\n\tuint32_t ___getPointCloudData_7;\n\t\/\/ System.UInt32 UnityEngine.XR.iOS.internal_UnityARCamera::getLightEstimation\n\tuint32_t ___getLightEstimation_8;\n\npublic:\n\tinline static int32_t get_offset_of_worldTransform_0() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t3920739388, ___worldTransform_0)); }\n\tinline UnityARMatrix4x4_t4073345847  get_worldTransform_0() const { return ___worldTransform_0; }\n\tinline UnityARMatrix4x4_t4073345847 * get_address_of_worldTransform_0() { return &___worldTransform_0; }\n\tinline void set_worldTransform_0(UnityARMatrix4x4_t4073345847  value)\n\t{\n\t\t___worldTransform_0 = value;\n\t}\n\n\tinline static int32_t get_offset_of_projectionMatrix_1() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t3920739388, ___projectionMatrix_1)); }\n\tinline UnityARMatrix4x4_t4073345847  get_projectionMatrix_1() const { return ___projectionMatrix_1; }\n\tinline UnityARMatrix4x4_t4073345847 * get_address_of_projectionMatrix_1() { return &___projectionMatrix_1; }\n\tinline void set_projectionMatrix_1(UnityARMatrix4x4_t4073345847  value)\n\t{\n\t\t___projectionMatrix_1 = value;\n\t}\n\n\tinline static int32_t get_offset_of_trackingState_2() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t3920739388, ___trackingState_2)); }\n\tinline int32_t get_trackingState_2() const { return ___trackingState_2; }\n\tinline int32_t* get_address_of_trackingState_2() { return &___trackingState_2; }\n\tinline void set_trackingState_2(int32_t value)\n\t{\n\t\t___trackingState_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_trackingReason_3() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t3920739388, ___trackingReason_3)); }\n\tinline int32_t get_trackingReason_3() const { return ___trackingReason_3; }\n\tinline int32_t* get_address_of_trackingReason_3() { return &___trackingReason_3; }\n\tinline void set_trackingReason_3(int32_t value)\n\t{\n\t\t___trackingReason_3 = value;\n\t}\n\n\tinline static int32_t get_offset_of_videoParams_4() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t3920739388, ___videoParams_4)); }\n\tinline UnityVideoParams_t4155354995  get_videoParams_4() const { return ___videoParams_4; }\n\tinline UnityVideoParams_t4155354995 * get_address_of_videoParams_4() { return &___videoParams_4; }\n\tinline void set_videoParams_4(UnityVideoParams_t4155354995  value)\n\t{\n\t\t___videoParams_4 = value;\n\t}\n\n\tinline static int32_t get_offset_of_lightData_5() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t3920739388, ___lightData_5)); }\n\tinline UnityMarshalLightData_t1623228070  get_lightData_5() const { return ___lightData_5; }\n\tinline UnityMarshalLightData_t1623228070 * get_address_of_lightData_5() { return &___lightData_5; }\n\tinline void set_lightData_5(UnityMarshalLightData_t1623228070  value)\n\t{\n\t\t___lightData_5 = value;\n\t}\n\n\tinline static int32_t get_offset_of_displayTransform_6() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t3920739388, ___displayTransform_6)); }\n\tinline UnityARMatrix4x4_t4073345847  get_displayTransform_6() const { return ___displayTransform_6; }\n\tinline UnityARMatrix4x4_t4073345847 * get_address_of_displayTransform_6() { return &___displayTransform_6; }\n\tinline void set_displayTransform_6(UnityARMatrix4x4_t4073345847  value)\n\t{\n\t\t___displayTransform_6 = value;\n\t}\n\n\tinline static int32_t get_offset_of_getPointCloudData_7() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t3920739388, ___getPointCloudData_7)); }\n\tinline uint32_t get_getPointCloudData_7() const { return ___getPointCloudData_7; }\n\tinline uint32_t* get_address_of_getPointCloudData_7() { return &___getPointCloudData_7; }\n\tinline void set_getPointCloudData_7(uint32_t value)\n\t{\n\t\t___getPointCloudData_7 = value;\n\t}\n\n\tinline static int32_t get_offset_of_getLightEstimation_8() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t3920739388, ___getLightEstimation_8)); }\n\tinline uint32_t get_getLightEstimation_8() const { return ___getLightEstimation_8; }\n\tinline uint32_t* get_address_of_getLightEstimation_8() { return &___getLightEstimation_8; }\n\tinline void set_getLightEstimation_8(uint32_t value)\n\t{\n\t\t___getLightEstimation_8 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_UNITYARCAMERA_T3920739388_H\n#ifndef INTERNAL_ARIMAGEANCHORADDED_T958088978_H\n#define INTERNAL_ARIMAGEANCHORADDED_T958088978_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARSessionNativeInterface\/internal_ARImageAnchorAdded\nstruct  internal_ARImageAnchorAdded_t958088978  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_ARIMAGEANCHORADDED_T958088978_H\n#ifndef INTERNAL_ARIMAGEANCHORUPDATED_T294417830_H\n#define INTERNAL_ARIMAGEANCHORUPDATED_T294417830_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARSessionNativeInterface\/internal_ARImageAnchorUpdated\nstruct  internal_ARImageAnchorUpdated_t294417830  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_ARIMAGEANCHORUPDATED_T294417830_H\n#ifndef INTERNAL_ARIMAGEANCHORREMOVED_T1751104571_H\n#define INTERNAL_ARIMAGEANCHORREMOVED_T1751104571_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARSessionNativeInterface\/internal_ARImageAnchorRemoved\nstruct  internal_ARImageAnchorRemoved_t1751104571  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_ARIMAGEANCHORREMOVED_T1751104571_H\n#ifndef UNITYARKITPLUGINSETTINGS_T2201217663_H\n#define UNITYARKITPLUGINSETTINGS_T2201217663_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityARKitPluginSettings\nstruct  UnityARKitPluginSettings_t2201217663  : public ScriptableObject_t2528358522\n{\npublic:\n\t\/\/ System.Boolean UnityARKitPluginSettings::m_ARKitUsesFacetracking\n\tbool ___m_ARKitUsesFacetracking_2;\n\t\/\/ System.Boolean UnityARKitPluginSettings::AppRequiresARKit\n\tbool ___AppRequiresARKit_3;\n\npublic:\n\tinline static int32_t get_offset_of_m_ARKitUsesFacetracking_2() { return static_cast<int32_t>(offsetof(UnityARKitPluginSettings_t2201217663, ___m_ARKitUsesFacetracking_2)); }\n\tinline bool get_m_ARKitUsesFacetracking_2() const { return ___m_ARKitUsesFacetracking_2; }\n\tinline bool* get_address_of_m_ARKitUsesFacetracking_2() { return &___m_ARKitUsesFacetracking_2; }\n\tinline void set_m_ARKitUsesFacetracking_2(bool value)\n\t{\n\t\t___m_ARKitUsesFacetracking_2 = value;\n\t}\n\n\tinline static int32_t get_offset_of_AppRequiresARKit_3() { return static_cast<int32_t>(offsetof(UnityARKitPluginSettings_t2201217663, ___AppRequiresARKit_3)); }\n\tinline bool get_AppRequiresARKit_3() const { return ___AppRequiresARKit_3; }\n\tinline bool* get_address_of_AppRequiresARKit_3() { return &___AppRequiresARKit_3; }\n\tinline void set_AppRequiresARKit_3(bool value)\n\t{\n\t\t___AppRequiresARKit_3 = value;\n\t}\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ UNITYARKITPLUGINSETTINGS_T2201217663_H\n#ifndef INTERNAL_ARFACEANCHORUPDATED_T3423900432_H\n#define INTERNAL_ARFACEANCHORUPDATED_T3423900432_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARSessionNativeInterface\/internal_ARFaceAnchorUpdated\nstruct  internal_ARFaceAnchorUpdated_t3423900432  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_ARFACEANCHORUPDATED_T3423900432_H\n#ifndef INTERNAL_ARANCHORADDED_T1565083332_H\n#define INTERNAL_ARANCHORADDED_T1565083332_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARSessionNativeInterface\/internal_ARAnchorAdded\nstruct  internal_ARAnchorAdded_t1565083332  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_ARANCHORADDED_T1565083332_H\n#ifndef INTERNAL_ARSESSIONTRACKINGCHANGED_T1988849735_H\n#define INTERNAL_ARSESSIONTRACKINGCHANGED_T1988849735_H\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n\n\/\/ UnityEngine.XR.iOS.UnityARSessionNativeInterface\/internal_ARSessionTrackingChanged\nstruct  internal_ARSessionTrackingChanged_t1988849735  : public MulticastDelegate_t\n{\npublic:\n\npublic:\n};\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif \/\/ INTERNAL_ARSESSIONTRACKINGCHANGED_T1988849735_H\n\n\n\n\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Winvalid-offsetof\"\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2300 = { sizeof (internal_ARAnchorAdded_t1565083332), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2301 = { sizeof (internal_ARAnchorUpdated_t2645242205), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2302 = { sizeof (internal_ARAnchorRemoved_t3371657877), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2303 = { sizeof (internal_ARUserAnchorAdded_t3285282493), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2304 = { sizeof (internal_ARUserAnchorUpdated_t3964727538), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2305 = { sizeof (internal_ARUserAnchorRemoved_t386858594), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2306 = { sizeof (internal_ARFaceAnchorAdded_t1021040265), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2307 = { sizeof (internal_ARFaceAnchorUpdated_t3423900432), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2308 = { sizeof (internal_ARFaceAnchorRemoved_t2563439402), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2309 = { sizeof (internal_ARImageAnchorAdded_t958088978), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2310 = { sizeof (internal_ARImageAnchorUpdated_t294417830), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2311 = { sizeof (internal_ARImageAnchorRemoved_t1751104571), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2312 = { sizeof (internal_ARSessionTrackingChanged_t1988849735), sizeof(Il2CppMethodPointer), 0, 0 };\nextern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2313 = { sizeof (UnityARKitPluginSettings_t2201217663), -1, 0, 0 };\nextern const int32_t g_FieldOffsetTable2313[2] = \n{\n\tUnityARKitPluginSettings_t2201217663::get_offset_of_m_ARKitUsesFacetracking_2(),\n\tUnityARKitPluginSettings_t2201217663::get_offset_of_AppRequiresARKit_3(),\n};\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n","avg_line_length":38.3729003359,"max_line_length":200,"alphanum_fraction":0.8298654682,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1326,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ ServerDlg.cpp : implementation file\n\/\/\n\n#include \"stdafx.h\"\n#include \"SendMail.h\"\n#include \"ServDlg.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CServerDialog dialog\n\n\nCServerDialog::CServerDialog(CWnd* pParent \/*=NULL*\/)\n\t: CDialog(CServerDialog::IDD, pParent)\n{\n\t\/\/{{AFX_DATA_INIT(CServerDialog)\n\tm_strServer = _T(\"\");\n\tm_strFrom = _T(\"\");\n\t\/\/}}AFX_DATA_INIT\n}\n\n\nvoid CServerDialog::DoDataExchange(CDataExchange* pDX)\n{\n\tCDialog::DoDataExchange(pDX);\n\t\/\/{{AFX_DATA_MAP(CServerDialog)\n\tDDX_Text(pDX, IDC_SERVER, m_strServer);\n\tDDX_Text(pDX, IDC_FROM_ADDRESS, m_strFrom);\n\t\/\/}}AFX_DATA_MAP\n}\n\n\nBEGIN_MESSAGE_MAP(CServerDialog, CDialog)\n\t\/\/{{AFX_MSG_MAP(CServerDialog)\n\t\/\/}}AFX_MSG_MAP\nEND_MESSAGE_MAP()\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CServerDialog message handlers\n\n\nBOOL CServerDialog::OnInitDialog() \n{\n\tCDialog::OnInitDialog();\n\n\tCSendMailApp* pApp = (CSendMailApp*)AfxGetApp();\n\tpApp->GetSmtpInfo(m_strServer, m_strFrom);\n\t\n\tUpdateData(FALSE);\n\t\n\treturn TRUE;\n}\n\nvoid CServerDialog::OnOK() \n{\n\tUpdateData(TRUE);\n\n\tCSendMailApp* pApp = (CSendMailApp*)AfxGetApp();\n\tpApp->WriteSmtpInfo(m_strServer, m_strFrom);\n\t\n\tCDialog::OnOK();\n}\n","avg_line_length":19.5,"max_line_length":77,"alphanum_fraction":0.6478129713,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11268,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2016 The Bitcoin Core developers\n\/\/ Copyright (c) 2011-2012 Litecoin Developers\n\/\/ Copyright (c) 2013-2014 Dr Kimoto Chan\n\/\/ Copyright (c) 2009-2014 The DigiByte developers\n\/\/ Copyright (c) 2013-2014 NFGcoin Developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"pow.h\"\n\n#include \"arith_uint256.h\"\n#include \"bignum.h\"\n#include \"chain.h\"\n#include \"primitives\/block.h\"\n#include \"uint256.h\"\n#include \"util.h\"\n#include \"version.h\"\n#include \"chainparams.h\"\n\n#include <stdexcept>\n#include <vector>\n#include <openssl\/bn.h>\n#include <cmath>\n\nunsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const CBlockHeader *pblock, uint64_t TargetBlocksSpacingSeconds, uint64_t PastBlocksMin, uint64_t PastBlocksMax, const Consensus::Params& params) {\n\t\/* current difficulty formula, megacoin - kimoto gravity well *\/\n\tconst CBlockIndex  *BlockLastSolved\t\t\t\t= pindexLast;\n\tconst CBlockIndex  *BlockReading\t\t\t\t= pindexLast;\n\tconst CBlockHeader *BlockCreating\t\t\t\t= pblock;\n\t\t\t\t\t\tBlockCreating\t\t\t\t= BlockCreating;\n\tuint64_t\t\t\tPastBlocksMass\t\t\t\t= 0;\n\tint64_t\t\t\t\tPastRateActualSeconds\t\t= 0;\n\tint64_t\t\t\t\tPastRateTargetSeconds\t\t= 0;\n\tdouble\t\t\t\tPastRateAdjustmentRatio\t\t= double(1);\n\tCBigNum\t\t\t\tPastDifficultyAverage;\n\tCBigNum\t\t\t\tPastDifficultyAveragePrev;\n\tdouble\t\t\t\tEventHorizonDeviation;\n\tdouble\t\t\t\tEventHorizonDeviationFast;\n\tdouble\t\t\t\tEventHorizonDeviationSlow;\n\n    if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return UintToArith256(params.powLimit).GetCompact(); }\n\n\tfor (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {\n\t\tif (PastBlocksMax > 0 && i > PastBlocksMax) { break; }\n\t\tPastBlocksMass++;\n\n\t\tif (i == 1)\t{ PastDifficultyAverage.SetCompact(BlockReading->nBits); }\n\t\telse\t\t{ PastDifficultyAverage = ((CBigNum().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) \/ i) + PastDifficultyAveragePrev; }\n\t\tPastDifficultyAveragePrev = PastDifficultyAverage;\n\n\t\tPastRateActualSeconds\t\t\t= BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime();\n\t\tPastRateTargetSeconds\t\t\t= TargetBlocksSpacingSeconds * PastBlocksMass;\n\t\tPastRateAdjustmentRatio\t\t\t= double(1);\n\t\tif (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; }\n\t\tif (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n\t\tPastRateAdjustmentRatio\t\t\t= double(PastRateTargetSeconds) \/ double(PastRateActualSeconds);\n\t\t}\n\t\tEventHorizonDeviation\t\t\t= 1 + (0.7084 * std::pow((double(PastBlocksMass)\/double(144)), -1.228));\n\t\tEventHorizonDeviationFast\t\t= EventHorizonDeviation;\n\t\tEventHorizonDeviationSlow\t\t= 1 \/ EventHorizonDeviation;\n\n\t\tif (PastBlocksMass >= PastBlocksMin) {\n\t\t\tif ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; }\n\t\t}\n\t\tif (BlockReading->pprev == NULL) { assert(BlockReading); break; }\n\t\tBlockReading = BlockReading->pprev;\n\t}\n\n\tCBigNum bnNew(PastDifficultyAverage);\n\tif (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n\t\tbnNew *= PastRateActualSeconds;\n\t\tbnNew \/= PastRateTargetSeconds;\n\t}\n    if (bnNew > CBigNum(params.powLimit)) { bnNew = CBigNum(params.powLimit); }\n\n\treturn bnNew.GetCompact();\n}\n\n\nunsigned int static DarkGravityWave(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) {\n    \/* current difficulty formula, dash - DarkGravity v3, written by Evan Duffield - evan@dashpay.io *\/\n    const CBlockIndex *BlockLastSolved = pindexLast;\n    const CBlockIndex *BlockReading = pindexLast;\n    int64_t nActualTimespan = 0;\n    int64_t LastBlockTime = 0;\n    int64_t PastBlocksMin = 24;\n    int64_t PastBlocksMax = 24;\n    int64_t CountBlocks = 0;\n    CBigNum PastDifficultyAverage;\n    CBigNum PastDifficultyAveragePrev;\n\n    if (BlockLastSolved == NULL || BlockLastSolved->nHeight < Params().SwitchLyra2REv2_DGWblock() + PastBlocksMin) {\n        return UintToArith256(params.powLimit).GetCompact();\n    }\n\n    for (unsigned int i = 1; BlockReading && BlockReading->nHeight >= Params().SwitchLyra2REv2_DGWblock(); i++) {\n        if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }\n        CountBlocks++;\n\n        if(CountBlocks <= PastBlocksMin) {\n            if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }\n            else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks)+(CBigNum().SetCompact(BlockReading->nBits))) \/ (CountBlocks+1); }\n            PastDifficultyAveragePrev = PastDifficultyAverage;\n        }\n\n        if(LastBlockTime > 0){\n            int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime());\n            nActualTimespan += Diff;\n        }\n        LastBlockTime = BlockReading->GetBlockTime();\n\n        if (BlockReading->pprev == NULL) { assert(BlockReading); break; }\n        BlockReading = BlockReading->pprev;\n    }\n\n    CBigNum bnNew(PastDifficultyAverage);\n\n    int64_t _nTargetTimespan = CountBlocks*params.nPowTargetSpacing;\n\n    if (nActualTimespan < _nTargetTimespan\/3)\n        nActualTimespan = _nTargetTimespan\/3;\n    if (nActualTimespan > _nTargetTimespan*3)\n        nActualTimespan = _nTargetTimespan*3;\n\n    \/\/ Retarget\n    bnNew *= nActualTimespan;\n    bnNew \/= _nTargetTimespan;\n\n    if (bnNew > CBigNum(params.powLimit)){\n        bnNew = CBigNum(params.powLimit);\n    }\n\n    return bnNew.GetCompact();\n}\n\nunsigned int static GetNextWorkRequired_V2(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n\tstatic const int64_t\tBlocksTargetSpacing\t\t\t= params.nPowTargetSpacing;\n\tunsigned int\t\t\tTimeDaySeconds\t\t\t\t= 60 * 60 * 24;\n\tint64_t\t\t\t\t\tPastSecondsMin\t\t\t\t= TimeDaySeconds * 0.25;\n\tint64_t\t\t\t\t\tPastSecondsMax\t\t\t\t= TimeDaySeconds * 7;\n\tuint64_t\t\t\t\tPastBlocksMin\t\t\t\t= PastSecondsMin \/ BlocksTargetSpacing;\n\tuint64_t\t\t\t\tPastBlocksMax\t\t\t\t= PastSecondsMax \/ BlocksTargetSpacing;\n\n    if (params.fPowNoRetargeting)\n        return pindexLast->nBits;\n\n\treturn KimotoGravityWell(pindexLast, pblock, BlocksTargetSpacing, PastBlocksMin, PastBlocksMax, params);\n}\n\nunsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n    assert(pindexLast != nullptr);\n    unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();\n\n    \/\/ Genesis block and premine blocks\n    if (pindexLast == NULL || pindexLast->nHeight < params.premineBlocks)\n        return nProofOfWorkLimit;\n\n    if (params.fPowNoRetargeting)\n        return pindexLast->nBits;\n\n    if(pindexLast->nHeight+1 >= Params().SwitchLyra2REv2_DGWblock())\n    {\n        \/\/ DGWv3\n        return DarkGravityWave(pindexLast, pblock, params);\n    }\n    else if(pindexLast->nHeight+1 >= Params().SwitchKGWblock() && pindexLast->nHeight+1 < Params().SwitchDIGIblock()){\n        \/\/ KGW\n        return GetNextWorkRequired_V2(pindexLast, pblock, params);\n    }\n\n    int64_t adjustmentInterval = params.DifficultyAdjustmentInterval();\n    if ((pindexLast->nHeight+1) >= Params().SwitchDIGIblock()) {\n        adjustmentInterval = params.DifficultyAdjustmentIntervalDigisheld();\n    }\n\n    \/\/ Only change once per difficulty adjustment interval\n    if ((pindexLast->nHeight+1) % adjustmentInterval != 0)\n    {\n        if (params.fPowAllowMinDifficultyBlocks)\n        {\n            \/\/ Special difficulty rule for testnet:\n            \/\/ If the new block's timestamp is more than 2* 10 minutes\n            \/\/ then allow mining of a min-difficulty block.\n            if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)\n                return nProofOfWorkLimit;\n            else\n            {\n                \/\/ Return the last non-special-min-difficulty-rules-block\n                const CBlockIndex* pindex = pindexLast;\n                while (pindex->pprev && pindex->nHeight % adjustmentInterval != 0 && pindex->nBits == nProofOfWorkLimit)\n                    pindex = pindex->pprev;\n                return pindex->nBits;\n            }\n        }\n        return pindexLast->nBits;\n    }\n\n    \/\/ Go back by what we want to be 14 days worth of blocks\n    \/\/ NFGcoin: This fixes an issue where a 51% attack can change difficulty at will.\n    \/\/ Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz\n    int blockstogoback = adjustmentInterval-1;\n    if ((pindexLast->nHeight+1) != adjustmentInterval)\n        blockstogoback = adjustmentInterval;\n\n    \/\/ Go back by what we want to be 14 days worth of blocks\n    const CBlockIndex* pindexFirst = pindexLast;\n    for (int i = 0; pindexFirst && i < blockstogoback; i++)\n        pindexFirst = pindexFirst->pprev;\n\n    assert(pindexFirst);\n\n    return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);\n}\n\nunsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)\n{\n    if (params.fPowNoRetargeting)\n        return pindexLast->nBits;\n\n    bool fNewDifficultyProtocol = ((pindexLast->nHeight+1) >= Params().SwitchDIGIblock());\n    int64_t targetTimespan =  params.nPowTargetTimespan;\n    if (fNewDifficultyProtocol) {\n        targetTimespan = params.nPowTargetTimespanDigisheld;\n    }\n\n    \/\/ Limit adjustment step\n    int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;\n\n    if (fNewDifficultyProtocol) \/\/DigiShield implementation - thanks to RealSolid & WDC for this code\n    {\n        \/\/ amplitude filter - thanks to daft27 for this code\n        nActualTimespan = targetTimespan + (nActualTimespan - targetTimespan)\/8;\n        if (nActualTimespan < (targetTimespan - (targetTimespan\/4)) ) nActualTimespan = (targetTimespan - (targetTimespan\/4));\n        if (nActualTimespan > (targetTimespan + (targetTimespan\/2)) ) nActualTimespan = (targetTimespan + (targetTimespan\/2));\n    }\n    else{\n        if (nActualTimespan < params.nPowTargetTimespan\/4)\n            nActualTimespan = params.nPowTargetTimespan\/4;\n        if (nActualTimespan > params.nPowTargetTimespan*4)\n            nActualTimespan = params.nPowTargetTimespan*4;\n    }\n\n    \/\/ Retarget\n    arith_uint256 bnNew;\n    arith_uint256 bnOld;\n    bnNew.SetCompact(pindexLast->nBits);\n    bnOld = bnNew;\n    \/\/ NFGcoin: intermediate uint256 can overflow by 1 bit\n    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);\n    bool fShift = bnNew.bits() > bnPowLimit.bits() - 1;\n    if (fShift)\n        bnNew >>= 1;\n    bnNew *= nActualTimespan;\n    bnNew \/= targetTimespan;\n    if (fShift)\n        bnNew <<= 1;\n\n    if (bnNew > bnPowLimit)\n        bnNew = bnPowLimit;\n\n    return bnNew.GetCompact();\n}\n\nbool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)\n{\n    bool fNegative;\n    bool fOverflow;\n    arith_uint256 bnTarget;\n\n    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);\n\n    \/\/ Check range\n    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))\n        return false;\n\n    \/\/ Check proof of work matches claimed amount\n    if (UintToArith256(hash) > bnTarget)\n        return false;\n\n    return true;\n}\n","avg_line_length":39.5368421053,"max_line_length":216,"alphanum_fraction":0.701544196,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2628,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/\n\/\/ Game.cpp for cpp in \/home\/annibal\/cpp\/cp_2\/anniba_c\n\/\/ \n\/\/ Made by ANNIBAL Celine\n\/\/ Login   <anniba_c@etna-alternance.net>\n\/\/ \n\/\/ Started on  Wed Feb 15 12:25:05 2017 ANNIBAL Celine\n\/\/ Last update Thu Feb 16 15:53:34 2017 ANNIBAL Celine\n\/\/\n#include \"Game.hh\"\n\nGame *Game::m_instance = nullptr;\n\nGame::Game()\n{\n  std::cout << \"\\033c\" << std::endl;\n  std::cout << \"\\n\\n------------------ METAL GEAR PAPER ------------------\\n\\n\" << std::endl;\n  std::cout << \"Utiliser les touches wsqd pour avancer, et la touche 'q' pour quitter\\n\" << std::endl;\n  std::cout << \"Bienvenue dans nore jeu MGP ! \\nVotre mission : Trouver la sortie du labyrinth! \\nAttention, veillez \u00e0 \u00e9viter les gardes represent\u00e9s par des G, ainsi que leur champ de vision ':' au risque de mourir imm\u00e9diatement! \\nVous devez passer sur le coffre 'k' pour recup\u00e9rer une cl\u00e9 afin d'ouvrir la porte 'A' et pouvoir acc\u00e9der \u00e0 la sortie. \\nMais ne nous fiez pas aux apprences certains murs peuvent cacher des passages secrets.. \\n\" << std::endl;\n  std::cout << \"C'est parti !\\n\" << std::endl;\n  std::cout << \"Entrez 'c' pour commencer ou 'q' pour quitter !\" << std::endl;\n}\n\nGame::~Game()\n{\n}\n\nGame* Game::GetGame()\n{\n  if(! m_instance)\n    m_instance = new Game();\n  return(m_instance);\n}\n\nvoid Game::LoadMap()\n{\n  Player P = Player(1);\n  ReadMap myMap(\"lvl1.map\");\n  myMap.GetPlayerPos(P.x,P.y);\n  myMap.SetGuardMarks();\n  myMap.ShowMap();\n  MoveChar(&myMap, &P);\n}\n\nvoid Game::MoveChar(ReadMap *myMap, Player *P)\n{\n  char dir;\n  std::string answer;\n  std::map<char, Player::POSX> tab;\n  tab['w'] = Player::POSX::W;\n  tab['d'] = Player::POSX::D;\n  tab['a'] = Player::POSX::A;\n  tab['s'] = Player::POSX::S;\n\n  while(P->IsAlive && dir != 'q' && !P->Escape)\n    {\n      std::cin >> dir;\n      if(tab.find(dir) != tab.end())\n\t{\n\t  P->move(1,tab[dir],myMap);\n\t  myMap->ShowMap();\n\t}\n      else if(dir == 'q')\n\tstd::cout << \"A bientot !\" << std::endl;\n      else\n\tstd::cout << \"Mauvaise letter\" << std::endl;\n    }\n  \n  if(P->IsAlive == false)\n    {\n      std::cout << \"Boohh tu es mooort ! Rejouer ? Tapez 'oui' ou 'non' \" << std::endl;\n      std::cin >> answer;\n      if (answer == \"oui\")\n\t{\n\t  P->IsAlive = true;\n\t  LoadMap();\n\t}\t\n    }\n  else if(P->Escape)\n    std::cout << \"Youpi tu as gagn\u00e9(e) !\" << std::endl;\n}\n\nint main(void)\n{\n  char begin;\n  Game *butterfly=Game::GetGame();\n  std::cin >> begin;\n  while(begin != 'c' && begin != 'q')\n    {\n      std::cout << \"Veillez entrer 'c' ou 'q'\" << std::endl;\n      std::cin >> begin;\n    }\n  if(begin == 'c')\n    butterfly->LoadMap();\n  else if(begin == 'q')\n    std::cout << \"A bient\u00f4t\" << std::endl;\n  return 0;\n}\n","avg_line_length":26.5454545455,"max_line_length":457,"alphanum_fraction":0.5886605784,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":701,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-4.0","MIT"],"max_stars_count":2.0,"content":"\n\n\/\/ <Snippet1>\n#using <System.Xml.dll>\n\nusing namespace System;\nusing namespace System::IO;\nusing namespace System::Xml;\nint main()\n{\n   XmlDocument^ doc = gcnew XmlDocument;\n   doc->LoadXml( \"<book ISBN='1-861001-57-5'><title>Pride And Prejudice<\/title><\/book>\" );\n   \n   \/\/Create a new attribute.\n   XmlAttribute^ newAttr = doc->CreateAttribute( \"genre\" );\n   newAttr->Value = \"novel\";\n   \n   \/\/Create an attribute collection and add the new attribute\n   \/\/to the collection.\n   XmlAttributeCollection^ attrColl = doc->DocumentElement->Attributes;\n   attrColl->Append( newAttr );\n   Console::WriteLine( \"Display the modified XML...\\r\\n\" );\n   Console::WriteLine( doc->OuterXml );\n}\n\n\/\/ <\/Snippet1>\n","avg_line_length":25.962962963,"max_line_length":90,"alphanum_fraction":0.6847360913,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1256,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":25.0,"content":"\/*\n * Copyright 2021 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"scene.hpp\"\n\n\/\/ These are all stubs. Subclasses should override to implement their\n\/\/ specific functionality.\n\nvoid Scene::OnInstall() {}\n\nvoid Scene::DoFrame() {}\n\nvoid Scene::OnUninstall() {}\n\nvoid Scene::OnStartGraphics() {}\n\nvoid Scene::OnKillGraphics() {}\n\nvoid Scene::OnPointerDown(int pointerId, const struct PointerCoords *coords) {}\n\nvoid Scene::OnPointerUp(int pointerId, const struct PointerCoords *coords) {}\n\nvoid Scene::OnPointerMove(int pointerId, const struct PointerCoords *coords) {}\n\nvoid Scene::OnScreenResized(int width, int height) {}\n\nvoid Scene::OnPause() {}\n\nvoid Scene::OnResume() {}\n\nScene::~Scene() {}\n","avg_line_length":27.9111111111,"max_line_length":79,"alphanum_fraction":0.7356687898,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":21850,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/* connpool.cpp\n *\/\n\n\/*    Copyright 2009 10gen Inc.\n *\n *    This program is free software: you can redistribute it and\/or  modify\n *    it under the terms of the GNU Affero General Public License, version 3,\n *    as published by the Free Software Foundation.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU Affero General Public License for more details.\n *\n *    You should have received a copy of the GNU Affero General Public License\n *    along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *    As a special exception, the copyright holders give permission to link the\n *    code of portions of this program with the OpenSSL library under certain\n *    conditions as described in each individual source file and distribute\n *    linked combinations including the program with the OpenSSL library. You\n *    must comply with the GNU Affero General Public License in all respects\n *    for all of the code used other than as permitted herein. If you modify\n *    file(s) with this exception, you may extend this exception to your\n *    version of the file(s), but you are not obligated to do so. If you do not\n *    wish to do so, delete this exception statement from your version. If you\n *    delete this exception statement from all source files in the program,\n *    then also delete it in the license file.\n *\/\n\n\/\/ _ todo: reconnect?\n\n#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kNetwork\n\n#include \"mongo\/platform\/basic.h\"\n\n#include \"mongo\/client\/connpool.h\"\n\n#include <limits>\n#include <string>\n\n#include \"mongo\/client\/connection_string.h\"\n#include \"mongo\/client\/global_conn_pool.h\"\n#include \"mongo\/client\/replica_set_monitor.h\"\n#include \"mongo\/executor\/connection_pool_stats.h\"\n#include \"mongo\/stdx\/chrono.h\"\n#include \"mongo\/util\/exit.h\"\n#include \"mongo\/util\/log.h\"\n#include \"mongo\/util\/net\/socket_exception.h\"\n\n#if !defined(__has_feature)\n#define __has_feature(x) 0\n#endif\n\n#if __has_feature(address_sanitizer)\n#include <sanitizer\/lsan_interface.h>\n#endif\n\nnamespace mongo {\n\nnamespace {\nconst int kDefaultIdleTimeout = std::numeric_limits<int>::max();\nconst int kDefaultMaxInUse = std::numeric_limits<int>::max();\n}  \/\/ namespace\n\nusing std::endl;\nusing std::list;\nusing std::map;\nusing std::set;\nusing std::string;\nusing std::vector;\n\n\/\/ ------ PoolForHost ------\n\nPoolForHost::PoolForHost()\n    : _created(0),\n      _minValidCreationTimeMicroSec(0),\n      _type(ConnectionString::INVALID),\n      _maxPoolSize(kPoolSizeUnlimited),\n      _maxInUse(kDefaultMaxInUse),\n      _checkedOut(0),\n      _badConns(0),\n      _parentDestroyed(false),\n      _inShutdown(false) {}\n\nPoolForHost::~PoolForHost() {\n    clear();\n}\n\nvoid PoolForHost::clear() {\n    if (!_parentDestroyed) {\n        logNoCache() << \"Dropping all pooled connections to \" << _hostName << \"(with timeout of \"\n                     << _socketTimeoutSecs << \" seconds)\";\n    }\n\n    _pool = decltype(_pool){};\n}\n\nvoid PoolForHost::done(DBConnectionPool* pool, DBClientBase* c_raw) {\n    std::unique_ptr<DBClientBase> c{c_raw};\n    const bool isFailed = c->isFailed();\n\n    --_checkedOut;\n\n    \/\/ Remember that this host had a broken connection for later\n    if (isFailed) {\n        reportBadConnectionAt(c->getSockCreationMicroSec());\n    }\n\n    \/\/ Another (later) connection was reported as broken to this host\n    bool isBroken = c->getSockCreationMicroSec() < _minValidCreationTimeMicroSec;\n    if (isFailed || isBroken) {\n        _badConns++;\n        logNoCache() << \"Ending connection to host \" << _hostName << \"(with timeout of \"\n                     << _socketTimeoutSecs << \" seconds)\"\n                     << \" due to bad connection status; \" << openConnections()\n                     << \" connections to that host remain open\";\n        pool->onDestroy(c.get());\n    } else if (_maxPoolSize >= 0 && static_cast<int>(_pool.size()) >= _maxPoolSize) {\n        \/\/ We have a pool size that we need to enforce\n        logNoCache() << \"Ending idle connection to host \" << _hostName << \"(with timeout of \"\n                     << _socketTimeoutSecs << \" seconds)\"\n                     << \" because the pool meets constraints; \" << openConnections()\n                     << \" connections to that host remain open\";\n        pool->onDestroy(c.get());\n    } else {\n        \/\/ The connection is probably fine, save for later\n        _pool.push(std::move(c));\n    }\n}\n\nvoid PoolForHost::reportBadConnectionAt(uint64_t microSec) {\n    if (microSec != DBClientBase::INVALID_SOCK_CREATION_TIME &&\n        microSec > _minValidCreationTimeMicroSec) {\n        _minValidCreationTimeMicroSec = microSec;\n        logNoCache() << \"Detected bad connection created at \" << _minValidCreationTimeMicroSec\n                     << \" microSec, clearing pool for \" << _hostName << \" of \" << openConnections()\n                     << \" connections\" << endl;\n        clear();\n    }\n}\n\nbool PoolForHost::isBadSocketCreationTime(uint64_t microSec) {\n    return microSec != DBClientBase::INVALID_SOCK_CREATION_TIME &&\n        microSec <= _minValidCreationTimeMicroSec;\n}\n\nDBClientBase* PoolForHost::get(DBConnectionPool* pool, double socketTimeout) {\n    while (!_pool.empty()) {\n        auto sc = std::move(_pool.top());\n        _pool.pop();\n\n        if (!sc.ok()) {\n            _badConns++;\n            pool->onDestroy(sc.conn.get());\n            continue;\n        }\n\n        verify(sc.conn->getSoTimeout() == socketTimeout);\n\n        ++_checkedOut;\n        return sc.conn.release();\n    }\n\n    return nullptr;\n}\n\nvoid PoolForHost::flush() {\n    clear();\n}\n\nvoid PoolForHost::getStaleConnections(Date_t idleThreshold, vector<DBClientBase*>& stale) {\n    vector<StoredConnection> all;\n    while (!_pool.empty()) {\n        StoredConnection c = std::move(_pool.top());\n        _pool.pop();\n\n        if (c.ok() && !c.addedBefore(idleThreshold)) {\n            all.push_back(std::move(c));\n        } else {\n            _badConns++;\n            stale.emplace_back(c.conn.release());\n        }\n    }\n\n    for (auto& conn : all) {\n        _pool.push(std::move(conn));\n    }\n}\n\n\nPoolForHost::StoredConnection::StoredConnection(std::unique_ptr<DBClientBase> c)\n    : conn(std::move(c)), added(Date_t::now()) {}\n\nbool PoolForHost::StoredConnection::ok() {\n    \/\/ Poke the connection to see if we're still ok\n    return conn->isStillConnected();\n}\n\nbool PoolForHost::StoredConnection::addedBefore(Date_t time) {\n    return added < time;\n}\n\nvoid PoolForHost::createdOne(DBClientBase* base) {\n    if (_created == 0)\n        _type = base->type();\n    ++_created;\n    \/\/ _checkedOut is used to indicate the number of in-use connections so\n    \/\/ though we didn't actually check this connection out, we bump it here.\n    ++_checkedOut;\n}\n\nvoid PoolForHost::initializeHostName(const std::string& hostName) {\n    if (_hostName.empty()) {\n        _hostName = hostName;\n    }\n}\n\nvoid PoolForHost::waitForFreeConnection(int timeout, stdx::unique_lock<stdx::mutex>& lk) {\n    auto condition = [&] { return (numInUse() < _maxInUse || _inShutdown.load()); };\n\n    if (timeout > 0) {\n        stdx::chrono::seconds timeoutSeconds{timeout};\n\n        \/\/ If we timed out waiting without getting a new connection, throw.\n        uassert(ErrorCodes::ExceededTimeLimit,\n                str::stream() << \"too many connections to \" << _hostName << \":\" << timeout,\n                !_cv.wait_for(lk, timeoutSeconds, condition));\n    } else {\n        _cv.wait(lk, condition);\n    }\n}\n\nvoid PoolForHost::notifyWaiters() {\n    _cv.notify_one();\n}\n\nvoid PoolForHost::shutdown() {\n    _inShutdown.store(true);\n    _cv.notify_all();\n}\n\n\/\/ ------ DBConnectionPool::Detail ------\n\nclass DBConnectionPool::Detail {\npublic:\n    template <typename Connect>\n    static DBClientBase* get(DBConnectionPool* _this,\n                             const std::string& host,\n                             double timeout,\n                             Connect connect) {\n        while (!(_this->_inShutdown.load())) {\n            \/\/ Get a connection from the pool, if there is one.\n            std::unique_ptr<DBClientBase> c(_this->_get(host, timeout));\n            if (c) {\n                \/\/ This call may throw.\n                _this->onHandedOut(c.get());\n                return c.release();\n            }\n\n            \/\/ If there are no pooled connections for this host, create a new connection. If\n            \/\/ there are too many connections in this pool to make a new one, block until a\n            \/\/ connection is released.\n            {\n                stdx::unique_lock<stdx::mutex> lk(_this->_mutex);\n                PoolForHost& p = _this->_pools[PoolKey(host, timeout)];\n\n                if (p.openConnections() >= _this->_maxInUse) {\n                    log() << \"Too many in-use connections; waiting until there are fewer than \"\n                          << _this->_maxInUse;\n                    p.waitForFreeConnection(timeout, lk);\n                } else {\n                    \/\/ Drop the lock here, so we can connect without holding it.\n                    \/\/ _finishCreate will take the lock again.\n                    lk.unlock();\n\n                    \/\/ Create a new connection and return. All Connect functions\n                    \/\/ should throw if they cannot create a connection.\n                    auto c = connect();\n                    invariant(c);\n                    return _this->_finishCreate(host, timeout, c);\n                }\n            }\n        }\n\n        \/\/ If we get here, we are in shutdown, and it does not matter what we return.\n        invariant(_this->_inShutdown.load());\n        uassert(ErrorCodes::ShutdownInProgress, \"connection pool is in shutdown\", false);\n        MONGO_UNREACHABLE;\n    }\n};\n\n\/\/ ------ DBConnectionPool ------\n\nconst int PoolForHost::kPoolSizeUnlimited(-1);\n\nDBConnectionPool::DBConnectionPool()\n    : _name(\"dbconnectionpool\"),\n      _maxPoolSize(PoolForHost::kPoolSizeUnlimited),\n      _maxInUse(kDefaultMaxInUse),\n      _idleTimeout(kDefaultIdleTimeout),\n      _inShutdown(false),\n      _hooks(new list<DBConnectionHook*>())\n\n{}\n\nvoid DBConnectionPool::shutdown() {\n    if (!_inShutdown.swap(true)) {\n        stdx::lock_guard<stdx::mutex> L(_mutex);\n        for (auto i = _pools.begin(); i != _pools.end(); i++) {\n            PoolForHost& p = i->second;\n            p.shutdown();\n        }\n    }\n}\n\nDBClientBase* DBConnectionPool::_get(const string& ident, double socketTimeout) {\n    uassert(ErrorCodes::ShutdownInProgress,\n            \"Can't use connection pool during shutdown\",\n            !globalInShutdownDeprecated());\n    stdx::lock_guard<stdx::mutex> L(_mutex);\n    PoolForHost& p = _pools[PoolKey(ident, socketTimeout)];\n    p.setMaxPoolSize(_maxPoolSize);\n    p.setSocketTimeout(socketTimeout);\n    p.initializeHostName(ident);\n    return p.get(this, socketTimeout);\n}\n\nint DBConnectionPool::openConnections(const string& ident, double socketTimeout) {\n    stdx::lock_guard<stdx::mutex> L(_mutex);\n    PoolForHost& p = _pools[PoolKey(ident, socketTimeout)];\n    return p.openConnections();\n}\n\nDBClientBase* DBConnectionPool::_finishCreate(const string& ident,\n                                              double socketTimeout,\n                                              DBClientBase* conn) {\n    {\n        stdx::lock_guard<stdx::mutex> L(_mutex);\n        PoolForHost& p = _pools[PoolKey(ident, socketTimeout)];\n        p.setMaxPoolSize(_maxPoolSize);\n        p.initializeHostName(ident);\n        p.createdOne(conn);\n    }\n\n    try {\n        onCreate(conn);\n        onHandedOut(conn);\n    } catch (std::exception&) {\n        delete conn;\n        throw;\n    }\n\n    log() << \"Successfully connected to \" << ident << \" (\" << openConnections(ident, socketTimeout)\n          << \" connections now open to \" << ident << \" with a \" << socketTimeout\n          << \" second timeout)\";\n\n    return conn;\n}\n\nDBClientBase* DBConnectionPool::get(const ConnectionString& url, double socketTimeout) {\n    auto connect = [&]() {\n        string errmsg;\n        auto c = url.connect(StringData(), errmsg, socketTimeout).release();\n        uassert(13328, _name + \": connect failed \" + url.toString() + \" : \" + errmsg, c);\n        return c;\n    };\n\n    return Detail::get(this, url.toString(), socketTimeout, connect);\n}\n\nDBClientBase* DBConnectionPool::get(const string& host, double socketTimeout) {\n    auto connect = [&] {\n        const ConnectionString cs(uassertStatusOK(ConnectionString::parse(host)));\n\n        string errmsg;\n        auto c = cs.connect(StringData(), errmsg, socketTimeout).release();\n        if (!c) {\n            throwSocketError(SocketErrorKind::CONNECT_ERROR,\n                             host,\n                             str::stream() << _name << \" error: \" << errmsg);\n        }\n\n        return c;\n    };\n\n    return Detail::get(this, host, socketTimeout, connect);\n}\n\nDBClientBase* DBConnectionPool::get(const MongoURI& uri, double socketTimeout) {\n    auto connect = [&] {\n        string errmsg;\n        std::unique_ptr<DBClientBase> c(uri.connect(StringData(), errmsg, socketTimeout));\n        uassert(40356, _name + \": connect failed \" + uri.toString() + \" : \" + errmsg, c);\n        return c.release();\n    };\n\n    return Detail::get(this, uri.toString(), socketTimeout, connect);\n}\n\nint DBConnectionPool::getNumAvailableConns(const string& host, double socketTimeout) const {\n    stdx::lock_guard<stdx::mutex> L(_mutex);\n    auto it = _pools.find(PoolKey(host, socketTimeout));\n    return (it == _pools.end()) ? 0 : it->second.numAvailable();\n}\n\nint DBConnectionPool::getNumBadConns(const string& host, double socketTimeout) const {\n    stdx::lock_guard<stdx::mutex> L(_mutex);\n    auto it = _pools.find(PoolKey(host, socketTimeout));\n    return (it == _pools.end()) ? 0 : it->second.getNumBadConns();\n}\n\nvoid DBConnectionPool::onRelease(DBClientBase* conn) {\n    if (_hooks->empty()) {\n        return;\n    }\n\n    for (list<DBConnectionHook*>::iterator i = _hooks->begin(); i != _hooks->end(); i++) {\n        (*i)->onRelease(conn);\n    }\n}\n\nvoid DBConnectionPool::release(const string& host, DBClientBase* c) {\n    onRelease(c);\n\n    stdx::unique_lock<stdx::mutex> lk(_mutex);\n    PoolForHost& p = _pools[PoolKey(host, c->getSoTimeout())];\n    p.done(this, c);\n\n    lk.unlock();\n    p.notifyWaiters();\n}\n\nDBConnectionPool::~DBConnectionPool() {\n    \/\/ Do not log in destruction, because global connection pools get\n    \/\/ destroyed after the logging framework.\n    stdx::lock_guard<stdx::mutex> L(_mutex);\n    for (PoolMap::iterator i = _pools.begin(); i != _pools.end(); i++) {\n        PoolForHost& p = i->second;\n        p._parentDestroyed = true;\n    }\n\n#if __has_feature(address_sanitizer)\n    __lsan_ignore_object(_hooks);\n#endif\n}\n\nvoid DBConnectionPool::flush() {\n    stdx::lock_guard<stdx::mutex> L(_mutex);\n    for (PoolMap::iterator i = _pools.begin(); i != _pools.end(); i++) {\n        PoolForHost& p = i->second;\n        p.flush();\n    }\n}\n\nvoid DBConnectionPool::clear() {\n    stdx::lock_guard<stdx::mutex> L(_mutex);\n    LOG(2) << \"Removing connections on all pools owned by \" << _name << endl;\n    for (PoolMap::iterator iter = _pools.begin(); iter != _pools.end(); ++iter) {\n        iter->second.clear();\n    }\n}\n\nvoid DBConnectionPool::removeHost(const string& host) {\n    stdx::lock_guard<stdx::mutex> L(_mutex);\n    LOG(2) << \"Removing connections from all pools for host: \" << host << endl;\n    for (PoolMap::iterator i = _pools.begin(); i != _pools.end(); ++i) {\n        const string& poolHost = i->first.ident;\n        if (!serverNameCompare()(host, poolHost) && !serverNameCompare()(poolHost, host)) {\n            \/\/ hosts are the same\n            i->second.clear();\n        }\n    }\n}\n\nvoid DBConnectionPool::addHook(DBConnectionHook* hook) {\n    _hooks->push_back(hook);\n}\n\nvoid DBConnectionPool::onCreate(DBClientBase* conn) {\n    if (_hooks->size() == 0)\n        return;\n\n    for (list<DBConnectionHook*>::iterator i = _hooks->begin(); i != _hooks->end(); i++) {\n        (*i)->onCreate(conn);\n    }\n}\n\nvoid DBConnectionPool::onHandedOut(DBClientBase* conn) {\n    if (_hooks->size() == 0)\n        return;\n\n    for (list<DBConnectionHook*>::iterator i = _hooks->begin(); i != _hooks->end(); i++) {\n        (*i)->onHandedOut(conn);\n    }\n}\n\nvoid DBConnectionPool::onDestroy(DBClientBase* conn) {\n    if (_hooks->size() == 0)\n        return;\n\n    for (list<DBConnectionHook*>::iterator i = _hooks->begin(); i != _hooks->end(); i++) {\n        (*i)->onDestroy(conn);\n    }\n}\n\nvoid DBConnectionPool::appendConnectionStats(executor::ConnectionPoolStats* stats) const {\n    {\n        stdx::lock_guard<stdx::mutex> lk(_mutex);\n        for (PoolMap::const_iterator i = _pools.begin(); i != _pools.end(); ++i) {\n            if (i->second.numCreated() == 0)\n                continue;\n\n            \/\/ Mongos may use either a replica set uri or a list of addresses as\n            \/\/ the identifier here, so we always take the first server parsed out\n            \/\/ as our label for connPoolStats. Note that these stats will collide\n            \/\/ with any existing stats for the chosen host.\n            auto uri = ConnectionString::parse(i->first.ident);\n            invariant(uri.isOK());\n            HostAndPort host = uri.getValue().getServers().front();\n\n            executor::ConnectionStatsPer hostStats{static_cast<size_t>(i->second.numInUse()),\n                                                   static_cast<size_t>(i->second.numAvailable()),\n                                                   static_cast<size_t>(i->second.numCreated()),\n                                                   0};\n            stats->updateStatsForHost(\"global\", host, hostStats);\n        }\n    }\n}\n\nbool DBConnectionPool::serverNameCompare::operator()(const string& a, const string& b) const {\n    const char* ap = a.c_str();\n    const char* bp = b.c_str();\n\n    while (true) {\n        if (*ap == '\\0' || *ap == '\/') {\n            if (*bp == '\\0' || *bp == '\/')\n                return false;  \/\/ equal strings\n            else\n                return true;  \/\/ a is shorter\n        }\n\n        if (*bp == '\\0' || *bp == '\/')\n            return false;  \/\/ b is shorter\n\n        if (*ap < *bp)\n            return true;\n        else if (*ap > *bp)\n            return false;\n\n        ++ap;\n        ++bp;\n    }\n    verify(false);\n}\n\nbool DBConnectionPool::poolKeyCompare::operator()(const PoolKey& a, const PoolKey& b) const {\n    if (DBConnectionPool::serverNameCompare()(a.ident, b.ident))\n        return true;\n\n    if (DBConnectionPool::serverNameCompare()(b.ident, a.ident))\n        return false;\n\n    return a.timeout < b.timeout;\n}\n\nbool DBConnectionPool::isConnectionGood(const string& hostName, DBClientBase* conn) {\n    if (conn == NULL) {\n        return false;\n    }\n\n    if (conn->isFailed()) {\n        return false;\n    }\n\n    {\n        stdx::lock_guard<stdx::mutex> sl(_mutex);\n        PoolForHost& pool = _pools[PoolKey(hostName, conn->getSoTimeout())];\n        if (pool.isBadSocketCreationTime(conn->getSockCreationMicroSec())) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nvoid DBConnectionPool::taskDoWork() {\n    vector<DBClientBase*> toDelete;\n    auto idleThreshold = Date_t::now() - _idleTimeout;\n    {\n        \/\/ we need to get the connections inside the lock\n        \/\/ but we can actually delete them outside\n        stdx::lock_guard<stdx::mutex> lk(_mutex);\n        for (PoolMap::iterator i = _pools.begin(); i != _pools.end(); ++i) {\n            i->second.getStaleConnections(idleThreshold, toDelete);\n        }\n    }\n\n    for (size_t i = 0; i < toDelete.size(); i++) {\n        try {\n            onDestroy(toDelete[i]);\n            delete toDelete[i];\n        } catch (...) {\n            \/\/ we don't care if there was a socket error\n        }\n    }\n}\n\n\/\/ ------ ScopedDbConnection ------\n\nScopedDbConnection::ScopedDbConnection(const std::string& host, double socketTimeout)\n    : _host(host),\n      _conn(globalConnPool.get(host, socketTimeout)),\n      _socketTimeoutSecs(socketTimeout) {\n    _setSocketTimeout();\n}\n\nScopedDbConnection::ScopedDbConnection(const ConnectionString& host, double socketTimeout)\n    : _host(host.toString()),\n      _conn(globalConnPool.get(host, socketTimeout)),\n      _socketTimeoutSecs(socketTimeout) {\n    _setSocketTimeout();\n}\n\nScopedDbConnection::ScopedDbConnection(const MongoURI& uri, double socketTimeout)\n    : _host(uri.toString()),\n      _conn(globalConnPool.get(uri, socketTimeout)),\n      _socketTimeoutSecs(socketTimeout) {\n    _setSocketTimeout();\n}\n\nvoid ScopedDbConnection::done() {\n    if (!_conn) {\n        return;\n    }\n\n    globalConnPool.release(_host, _conn);\n    _conn = NULL;\n}\n\nvoid ScopedDbConnection::_setSocketTimeout() {\n    if (!_conn)\n        return;\n\n    if (_conn->type() == ConnectionString::MASTER)\n        static_cast<DBClientConnection*>(_conn)->setSoTimeout(_socketTimeoutSecs);\n}\n\nScopedDbConnection::~ScopedDbConnection() {\n    if (_conn) {\n        if (_conn->isFailed()) {\n            if (_conn->getSockCreationMicroSec() == DBClientBase::INVALID_SOCK_CREATION_TIME) {\n                kill();\n            } else {\n                \/\/ The pool takes care of deleting the failed connection - this\n                \/\/ will also trigger disposal of older connections in the pool\n                done();\n            }\n        } else {\n            \/* see done() comments above for why we log this line *\/\n            logNoCache() << \"scoped connection to \" << _conn->getServerAddress()\n                         << \" not being returned to the pool\" << endl;\n            kill();\n        }\n    }\n}\n\nvoid ScopedDbConnection::clearPool() {\n    globalConnPool.clear();\n}\n\nAtomicInt32 AScopedConnection::_numConnections;\n\n}  \/\/ namespace mongo\n","avg_line_length":32.3703703704,"max_line_length":99,"alphanum_fraction":0.6102059497,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2748,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"#include <bits\/stdc++.h>\ntypedef long long ll;\ntypedef long double ld;\n#define rep(i,n) for(ll i=0;i<(n);i++)\n#define repr(i,n) for(ll i=(n-1);i>=0;i--)\n#define all(x) x.begin(),x.end()\n#define br cout << \"\\n\";\nusing namespace std;\nconst long long INF = 1e10;\nconst long long MOD = 1e9+7;\nusing Graph = vector<vector<ll>>;\nusing pll = pair<ll, ll>;\ntemplate<class T> inline bool chmin(T &a, T b) { if(a > b){ a = b; return true;} return false;}\ntemplate<class T> inline bool chmax(T &a, T b) { if(a < b){ a = b; return true;} return false;}\nll ceilll(ll a, ll b) {return (a + b-1) \/ b;} \/\/ if(a%b == 0) (a\/b) + 1\nll get_digit(ll a) {ll digit = 0; while(a != 0){a \/= 10; digit++;} return digit;} \/\/ a != 0\ntemplate<typename T> void vecdbg(vector<T>& v){ rep(i, v.size()){cout << v[i] << \" \";} br;}\ntemplate<typename T> void vecvecdbg(vector<vector<T>>& v){ rep(i, v.size()){rep(j, v[i].size()){cout << v[i][j] << \" \";} br;}}\n\n\/\/ 0 false, 1 true \n\/\/ string number to int : -48\n\/\/ a to A : -32\n\/\/ ceil(a)  1.2->2.0\n\/\/ c++17\tg++ -std=c++17 a.cpp\n\/\/ global vector -> 0 initialization\n\nstruct PrimeNumber\n{\n    \/\/O(sqrt(n))\n    \/\/sosu hantei\n    bool is_prime(long long n){\n        for(long long i = 2; i * i <= n; i++){\n            if(n % i == 0) return false;\n        }\n        return n != 1;\n    }\n\n    \/\/O(sqrt(n))  isn't sorted\n    \/\/yakusu rekkyo\n    vector<long long> divisor(long long n){\n        vector<long long> res;\n        for(long long i = 1; i * i <= n; i++){\n            if(n % i == 0){\n                res.push_back(i);\n                if(i != n \/ i) res.push_back(n \/ i);\n            }\n        }\n        return res;\n    }\n\n    \/\/O(sqrt(n))\n    \/\/soinsu bunkai\n    map<long long, long long> prime_factor(long long n){\n        map<long long, long long> res;\n        for(long long i = 2; i * i <= n; i++){\n            while(n % i == 0){\n                n \/= i;\n                res[i]++;\n            }\n        }\n        if(n != 1) res[n] = 1;\n        return res;\n    }\n\n    \/\/O(n log log n)\n    \/\/n madeno sosu rekkyo\n    vector<long long> eratosthenes(long long n){\n        vector<long long> prime;\n        vector<bool> is_prime(n + 1, true);\n        long long p = 0;\n        is_prime[0] = false; is_prime[1] = false;\n        for(long long i = 2; i <= n; i++){\n            if(is_prime[i]) prime.push_back(i);\n            for(long long j = 2 * i; j <= n; j += i) is_prime[j] = false;\n        }\n        return prime;\n    }\n};\n\nint main() {\n    std::cout << std::fixed << std::setprecision(15);\n    ll n; cin >> n;\n    PrimeNumber p;\n    map<ll, ll> mp = p.prime_factor(n);\n    ll ans = 0;\n    for(auto i : mp){\n        ans = max(ans, i.first * i.second);\n        \/\/cout << i.first << \" \" << i.second << endl;\n    }\n    cout << ans << endl;\n}","avg_line_length":30.1978021978,"max_line_length":126,"alphanum_fraction":0.5014556041,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1101,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":20.0,"content":"\/\/#####################################################################\n\/\/ Copyright 2009, Avi Robinson-Mosher.\n\/\/ This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.\n\/\/#####################################################################\n\/\/ Class READ_WRITE_HEXAHEDRALIZED_VOLUME\n\/\/#####################################################################\n#ifndef COMPILE_WITHOUT_READ_WRITE_SUPPORT\n#include <PhysBAM_Geometry\/Read_Write\/Geometry\/READ_WRITE_HEXAHEDRALIZED_VOLUME.h>\nnamespace PhysBAM{\n\nvoid Register_Read_Write_Hexahedralized_Volume()\n{\n#define DIMENSION_READ_WRITE_HELPER(T,RW) \\\n    Read_Write<STRUCTURE<VECTOR<T,3> >,RW>::Register_Read_Write<HEXAHEDRALIZED_VOLUME<T> >();\n\n#ifdef COMPILE_WITHOUT_DOUBLE_SUPPORT\n#define RW_HELPER(RW) \\\n    DIMENSION_READ_WRITE_HELPER(float,RW)\n#else\n#define RW_HELPER(RW) \\\n    DIMENSION_READ_WRITE_HELPER(float,RW) \\\n    DIMENSION_READ_WRITE_HELPER(double,RW)\n#endif\n\n    RW_HELPER(float);\n#ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT\n    RW_HELPER(double);\n#endif\n}\n}\n#endif\n","avg_line_length":34.40625,"max_line_length":135,"alphanum_fraction":0.6503178928,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3551,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":null,"content":"#include \"..\/Include\/Base64.hpp\"\r\n\r\nusing namespace Fnd::Utility;\r\n\r\n\r\nconst unsigned char Base64::_encode_map[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/\";\r\n\r\nconst unsigned char Base64::_decode_map[128] =\r\n{\r\n\t127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\r\n\t127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\r\n\t127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\r\n\t127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\r\n\t127, 127, 127,  62, 127, 127, 127,  63,  52,  53,\r\n\t54,  55,  56,  57,  58,  59,  60,  61, 127, 127,\r\n\t127, 64, 127, 127, 127,   0,   1,   2,   3,   4,\r\n\t5,   6,   7,   8,   9,  10,  11,  12,  13,  14,\r\n\t15,  16,  17,  18,  19,  20,  21,  22,  23,  24,\r\n\t25, 127, 127, 127, 127, 127, 127,  26,  27,  28,\r\n\t29,  30,  31,  32,  33,  34,  35,  36,  37,  38,\r\n\t39,  40,  41,  42,  43,  44,  45,  46,  47,  48,\r\n\t49,  50,  51, 127, 127, 127, 127, 127\r\n};\r\n\r\nstd::string Base64::Encode( const std::vector<unsigned char>& source )\r\n{\r\n\treturn source.empty() ? \"\" : Encode( &source[0], (unsigned int)source.size() );\r\n}\r\n\r\nstd::string Base64::Encode( const unsigned char* source, unsigned int length )\r\n{\r\n\t\tstd::string dest;\r\n\r\n\tsize_t i, n;\r\n\tint C1, C2, C3;\r\n\r\n\tif( length == 0 )\r\n\t\treturn dest;\r\n\r\n\tn = ( length << 3 ) \/ 6;\r\n\r\n\tswitch( ( length << 3 ) - ( n * 6 ) )\r\n\t{\r\n\t\tcase 2: \r\n\t\t\tn += 3; \r\n\t\t\tbreak;\r\n\t\tcase 4:\r\n\t\t\tn += 2; \r\n\t\t\tbreak;\r\n\t\tdefault: break;\r\n\t}\r\n\r\n\tdest.reserve( n + 1 );\r\n\r\n\tn = ( length \/ 3 ) * 3;\r\n\r\n\tfor( i = 0; i < n; i += 3 )\r\n\t{\r\n\t\tC1 = source[i+0];\r\n\t\tC2 = source[i+1];\r\n\t\tC3 = source[i+2];\r\n\r\n\t\tdest += _encode_map[(C1 >> 2) & 0x3F];\r\n\t\tdest += _encode_map[(((C1 &  3) << 4) + (C2 >> 4)) & 0x3F];\r\n\t\tdest += _encode_map[(((C2 & 15) << 2) + (C3 >> 6)) & 0x3F];\r\n\t\tdest += _encode_map[C3 & 0x3F];\r\n\t}\r\n\r\n\tif( i < length )\r\n\t{\r\n\t\tC1 = source[i];\r\n\t\tC2 = ((i + 1) < length) ? source[i+1] : 0;\r\n\t\tdest += _encode_map[(C1 >> 2) & 0x3F];\r\n\t\tdest += _encode_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];\r\n\t\t\t\r\n\t\tif( (i + 1) < length )\r\n\t\t\tdest += _encode_map[((C2 & 15) << 2) & 0x3F];\r\n\t\telse dest +=  '=';\r\n\t\t\t\r\n\t\tdest += '=';\r\n\t}\r\n\t\t\t\t\r\n\treturn dest;\r\n}\r\n\r\nstd::vector<unsigned char> Base64::Decode( const std::string& source )\r\n{\r\n\treturn source.empty() ? std::vector<unsigned char>() : Decode( &source[0], (unsigned int)source.size() );\r\n}\r\n\r\nstd::vector<unsigned char> Base64::Decode( const char* source, unsigned int length )\r\n{\r\n\tstd::vector<unsigned char> dest;\r\n\r\n\tsize_t i, n;\r\n\tint j, x;\r\n\t\r\n\tfor( i = n = j = 0; i < length; i++ )\r\n\t{\r\n\t\tif( ( length - i ) >= 2 &&\r\n\t\t\tsource[i] == '\\r' && source[i + 1] == '\\n' )\r\n\t\t\t\tcontinue;\r\n\t\t\r\n\t\tif( source[i] == '\\n' )\r\n\t\t\tcontinue;\r\n\t\tif( source[i] == '=' && ++j > 2 )\r\n\t\t\treturn std::vector<unsigned char>();\r\n\t\tif( source[i] > 127 || _decode_map[source[i]] == 127 )\r\n\t\t\treturn std::vector<unsigned char>();\r\n\r\n\t\tif( _decode_map[source[i]] < 64 && j != 0 )\r\n\t\t\treturn std::vector<unsigned char>();\r\n\t\tn++;\r\n\t}\r\n\tif( n == 0 )\r\n\t\treturn std::vector<unsigned char>();\r\n\t\r\n\tn = ((n * 6) + 7) >> 3;\r\n\r\n\tdest.reserve(n);\r\n\r\n\tint src_iter = 0;\r\n\t\r\n\tfor( j = 3, n = x = 0; i > 0; i--, src_iter++ )\r\n\t{\r\n\t\tif( source[src_iter] == '\\r' || source[src_iter] == '\\n' )\r\n\t\t\tcontinue;\r\n\t\t\r\n\t\tj -= ( _decode_map[source[src_iter]] == 64 );\r\n\t\tx  = (x << 6) | ( _decode_map[source[src_iter]] & 0x3F );\r\n\t\t\r\n\t\tif( ++n == 4 )\r\n\t\t{\r\n\t\t\tn = 0;\r\n\t\t\tif( j > 0 ) dest.push_back( (unsigned char)( x >> 16 ) );\r\n\t\t\tif( j > 1 ) dest.push_back( (unsigned char)( x >>  8 ) );\r\n\t\t\tif( j > 2 ) dest.push_back( (unsigned char)( x       ) );\r\n\t\t}\r\n\t}\r\n\t\t\r\n\treturn dest;\r\n}","avg_line_length":25.0070422535,"max_line_length":112,"alphanum_fraction":0.5054914109,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2786,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\n#include <fstream>\n#include <deque>\n#include <iterator>\n#include <algorithm> \/\/reverse vector\n#include <limits> \/\/limites num\u00e9ricos\n#include <stdexcept> \/\/ for std::runtime_error\n#include <vector>\n#include <random>\n#include <string>\n\nusing namespace std;\n\n#define M 9\n#define N 9\n\nint g = 1;\/\/gap\nint h = 0;\n\nvector<char> s = {'t','a','c','g','g','g','t','a','t'};\nvector<char> t = {'g','g','a','c','g','t','a','c','g'};\n\nvoid execute(vector< vector<int> > &, \n\t\tvector< vector<int> > &, vector< vector<int> > &);\n\nint maximum(int, int, int);\n\nint score(char, char);\n\nint w(int);\n\nint main(int argc, char const *argv[])\n{\n\tvector< vector<int> > a, b, c;\n\n\ta = vector< vector<int> > (M + 1, vector<int> ( N + 1, -999 ) );\n\tb = vector< vector<int> > (M + 1, vector<int> ( N + 1, 0 ) );\n\tc = vector< vector<int> > (M + 1, vector<int> ( N + 1, 0 ) );\n\n\tfor (int j = 1; j <= N; j++)  c[0][j] = -999;\n\tfor (int i = 1; i <= M; i++)  b[i][0] = -999;\n\n\texecute(a,b,c);\n\n\treturn 0;\n}\n\nvoid execute(vector< vector<int> > &a, vector< vector<int> > &b, \n\tvector< vector<int> > &c) {\n\n\tint i = 0, j = 0;\n\t\n\t\/\/inicializando linha e coluna\n\ta[0][0] = 0;\n\tb[0][0] = -999;\n\tc[0][0] = -999;\n\n\tfor (int i = 1; i <= N; i++)\n\t{\n\t\ta[i][0] = -999;\n\t\tb[i][0] = -999;\n\t\tc[i][0] = -w(i);\n\t}\n\n\tfor (int i = 1; i <= M; i++)\n\t{\n\t\ta[0][i] = -999;\n\t\tb[0][i] = -w(i);\n\t\tc[0][i] = -999;\n\t}\n\n\tfor (i = 1; i <= N; i++)\n\t{\n\t\tfor (j = 1; j <= M; j++)\n\t\t{\n\t\t\ta[i][j] = score(s[i-1], t[j-1]) + maximum( a[i-1][j-1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t b[i-1][j-1], c[i-1][j-1] );\n\t\t\t\n\t\t\tint m1, m2, m3;\n\t\t\tm1 = a[i][j-1] -h-g;\n\t\t\tm2 = b[i][j-1] -g;\n\t\t\tm3 = c[i][j-1] -h-g;\n\t\t\tb[i][j] = maximum(m1,m2,m3);\n\n\t\t\tm1 = a[i-1][j] -h-g;\n\t\t\tm2 = b[i-1][j] -h-g;\n\t\t\tm3 = c[i-1][j] -g;\n\t\t\tc[i][j] = maximum(m1,m2,m3);\n\t\t}\n\t}\n\n\t\/\/imprime matriz de valores\n\tfor (int i = 0; i <= M; i++)\n\t{\n\t\tfor (int j = 0; j <= N; j++)\n\t\t{\n\t\t\tcout<<a[i][j]<<\" \";\n\t\t}\n\t\tcout<<\"\\n\";\n\t}\n\tcout<<\"\\n\";\n\n\t\/\/imprime matriz de valores\n\tfor (int i = 0; i <= M; i++)\n\t{\n\t\tfor (int j = 0; j <= N; j++)\n\t\t{\n\t\t\tcout<<b[i][j]<<\" \";\n\t\t}\n\t\tcout<<\"\\n\";\n\t}\n\tcout<<\"\\n\";\n\n\t\/\/imprime matriz de valores\n\tfor (int i = 0; i <= M; i++)\n\t{\n\t\tfor (int j = 0; j <= N; j++)\n\t\t{\n\t\t\tcout<<c[i][j]<<\" \";\n\t\t}\n\t\tcout<<\"\\n\";\n\t}\n\tcout<<\"\\n\";\n\n\tvector<vector<int>> optimal = vector< vector<int> > (M + 1, vector<int> ( N + 1, 0 ) );\n\n\tfor (int i = 0; i <= M; i++)\n\t{\n\t\tfor (int j = 0; j <= N; j++)\n\t\t{\n\t\t\toptimal[i][j] = maximum(a[i][j],b[i][j],c[i][j]);\n\t\t}\n\t}\n\n\tfor (int i = 0; i <= M; i++)\n\t{\n\t\tfor (int j = 0; j <= N; j++)\n\t\t{\n\t\t\tcout<<optimal[i][j]<<\" \";\n\t\t}\n\t\tcout<<\"\\n\";\n\t}\n\tcout<<\"\\n\";\n}\n\nint maximum(int a, int b, int c) {\n\n\tint m = max(a,b);\n\tm = max(m,c);\n\t\n\treturn m;\n}\n\nint score(char a, char b){\n\n\tif (a == b)\n\t{\n\t\treturn 1;\n\t}\n\n\treturn -1;\n}\n\nint w(int k){\n\n\treturn h + k*g;\n}","avg_line_length":16.6826347305,"max_line_length":88,"alphanum_fraction":0.4612347452,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":29518,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":3.0,"content":"\/*\n * Copyright (C) 2016 Open Source Robotics Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*\/\n\n#include \"gazebo_camera_manager_plugin.h\"\n\n#include <math.h>\n#include <string>\n#include <iostream>\n#include <boost\/filesystem.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <opencv2\/opencv.hpp>\n\n#include <development\/mavlink.h>\n\nusing namespace std;\nusing namespace gazebo;\nusing namespace cv;\n\n\/\/ #define DEBUG_MESSAGE_IO\n\nGZ_REGISTER_SENSOR_PLUGIN(CameraManagerPlugin)\n\nstatic void* start_thread(void* param) {\n    CameraManagerPlugin* plugin = (CameraManagerPlugin*)param;\n    plugin->cameraThread();\n    return nullptr;\n}\n\nCameraManagerPlugin::CameraManagerPlugin()\n    : SensorPlugin()\n{\n}\n\nCameraManagerPlugin::~CameraManagerPlugin()\n{\n    _parentSensor.reset();\n    _camera.reset();\n}\n\nvoid CameraManagerPlugin::Load(sensors::SensorPtr sensor, sdf::ElementPtr sdf)\n{\n    if (!sensor)\n        gzerr << \"Invalid sensor pointer.\\n\";\n\n    _parentSensor =\n#if GAZEBO_MAJOR_VERSION >= 7\n        std::dynamic_pointer_cast<sensors::CameraSensor>(sensor);\n#else\n        boost::dynamic_pointer_cast<sensors::CameraSensor>(sensor);\n#endif\n\n    if (!_parentSensor)\n    {\n        gzerr << \"CameraManagerPlugin requires a CameraSensor.\\n\";\n    }\n\n#if GAZEBO_MAJOR_VERSION >= 7\n    _camera = _parentSensor->Camera();\n#else\n    _camera = _parentSensor->GetCamera();\n#endif\n\n    if (!_parentSensor)\n    {\n        gzerr << \"CameraManagerPlugin not attached to a camera sensor\\n\";\n        return;\n    }\n    _scene = _camera->GetScene();\n#if GAZEBO_MAJOR_VERSION >= 8\n    _lastImageTime = _scene->SimTime();\n#else\n    _lastImageTime = _scene->GetSimTime();\n#endif\n\n#if GAZEBO_MAJOR_VERSION >= 7\n    _width    = _camera->ImageWidth();\n    _height   = _camera->ImageHeight();\n    _depth    = _camera->ImageDepth();\n    _format   = _camera->ImageFormat();\n#else\n    _width    = _camera->GetImageWidth();\n    _height   = _camera->GetImageHeight();\n    _depth    = _camera->GetImageDepth();\n    _format   = _camera->GetImageFormat();\n#endif\n\n    if (sdf->HasElement(\"robotNamespace\")) {\n        _namespace = sdf->GetElement(\"robotNamespace\")->Get<std::string>();\n    } else {\n        gzwarn << \"[gazebo_geotagging_images_camera_plugin] Please specify a robotNamespace.\\n\";\n    }\n\n    _destWidth = _width;\n    if (sdf->HasElement(\"width\")) {\n        _destWidth = sdf->GetElement(\"width\")->Get<int>();\n    }\n    _destHeight = _height;\n    if (sdf->HasElement(\"height\")) {\n        _destHeight = sdf->GetElement(\"height\")->Get<int>();\n    }\n    if (sdf->HasElement(\"maximum_zoom\")) {\n        _maxZoom = sdf->GetElement(\"maximum_zoom\")->Get<float>();\n    }\n\n    if (sdf->HasElement(\"video_uri\")) {\n        _videoURI = sdf->GetElement(\"video_uri\")->Get<std::string>();\n    }\n    if (sdf->HasElement(\"system_id\")) {\n        _systemID = sdf->GetElement(\"system_id\")->Get<int>();\n    }\n    if (sdf->HasElement(\"cam_component_id\")) {\n        _componentID = sdf->GetElement(\"cam_component_id\")->Get<int>();\n    }\n    if (sdf->HasElement(\"mavlink_cam_udp_port\")) {\n        _mavlinkCamPort = sdf->GetElement(\"mavlink_cam_udp_port\")->Get<int>();\n    }\n\n    \/\/check if exiftool exists\n    if (system(\"exiftool -ver &>\/dev\/null\") != 0) {\n        gzerr << \"exiftool not found. geotagging_images plugin will be disabled\" << endl;\n        gzerr << \"On Ubuntu, use 'sudo apt-get install libimage-exiftool-perl' to install\" << endl;\n        return;\n    }\n\n    _node_handle = transport::NodePtr(new transport::Node());\n    _node_handle->Init();\n\n    _parentSensor->SetActive(true);\n\n    \/\/ Get the root model name\n    const string scopedName = _parentSensor->ParentName();\n    vector<string> names_splitted;\n    boost::split(names_splitted, scopedName, boost::is_any_of(\"::\"));\n    names_splitted.erase(std::remove_if(begin(names_splitted), end(names_splitted),\n                                [](const string& name)\n                                { return name.size() == 0; }), end(names_splitted));\n    std::string rootModelName = names_splitted.front(); \/\/ The first element is the name of the root model\n\n    \/\/ the second to the last name is the model name\n    const std::string parentSensorModelName = names_splitted.rbegin()[1];\n\n    _newFrameConnection = _camera->ConnectNewImageFrame(\n                              boost::bind(&CameraManagerPlugin::OnNewFrame, this, _1));\n\n    _gpsSub = _node_handle->Subscribe(\"~\/\" + rootModelName + \"\/link\/gps\", &CameraManagerPlugin::OnNewGpsPosition, this);\n\n    _storageDir = \"frames\";\n    boost::filesystem::remove_all(_storageDir); \/\/clear existing images\n    boost::filesystem::create_directory(_storageDir);\n\n    if (_init_udp(sdf)) {\n        \/\/ Start UDP thread\n        pthread_t threadId;\n        pthread_create(&threadId, NULL, start_thread, this);\n    }\n}\n\nvoid CameraManagerPlugin::OnNewGpsPosition(GpsPtr& gps_msg) {\n    _lastGpsPosition.X() = gps_msg->latitude_deg();\n    _lastGpsPosition.Y() = gps_msg->longitude_deg();\n    _lastGpsPosition.Z() = gps_msg->altitude();\n    \/\/gzdbg << \"got gps pos: \"<<_lastGpsPosition.X() <<\", \"<<lastGpsPosition.Y() <<endl;\n}\n\nvoid CameraManagerPlugin::OnNewFrame(const unsigned char * image)\n{\n\n    _captureMutex.lock();\n    \/\/ Are we capturing at all?\n    if (_captureMode == CAPTURE_DISABLED) {\n        _captureMutex.unlock();\n        return;\n    }\n    _captureMutex.unlock();\n\n    \/\/ Check for time lapse capture\n#if GAZEBO_MAJOR_VERSION >= 8\n    common::Time currentTime = _scene->SimTime();\n#else\n    common::Time currentTime = _scene->GetSimTime();\n#endif\n    double elapsed = currentTime.Double() - _lastImageTime.Double();\n    if (_captureMode == CAPTURE_ELAPSED && (elapsed < _captureInterval)) {\n        return;\n    }\n\n    _lastImageTime = currentTime;\n\n#if GAZEBO_MAJOR_VERSION >= 7\n    image = _camera->ImageData(0);\n#else\n    image = _camera->GetImageData(0);\n#endif\n\n    Mat frame    = Mat(_height, _width, CV_8UC3);\n    Mat frameBGR = Mat(_height, _width, CV_8UC3);\n    frame.data   = (uchar*)image; \/\/frame has not the right color format yet -> convert\n    cvtColor(frame, frameBGR, COLOR_RGB2BGR);\n\n    char file_name[256];\n    snprintf(file_name, sizeof(file_name), \"%s\/DSC%05i.jpg\", _storageDir.c_str(), _imageCounter);\n\n    if (_destWidth != _width || _destHeight != _height) {\n        Mat frameResized;\n        cv::Size size(_destWidth, _destHeight);\n        cv::resize(frameBGR, frameResized, size);\n        imwrite(file_name, frameResized);\n    } else {\n        imwrite(file_name, frameBGR);\n    }\n\n    char gps_tag_command[1024];\n    double lat = _lastGpsPosition.X();\n    char north_south = 'N', east_west = 'E';\n    double lon = _lastGpsPosition.Y();\n    if (lat < 0.) {\n        lat = -lat;\n        north_south = 'S';\n    }\n    if (lon < 0.) {\n        lon = -lon;\n        east_west = 'W';\n    }\n    snprintf(gps_tag_command, sizeof(gps_tag_command),\n             \"exiftool -gpslatituderef=%c -gpslongituderef=%c -gpsaltituderef=above -gpslatitude=%.9lf -gpslongitude=%.9lf\"\n\/\/           \" -gpsdatetime=now -gpsmapdatum=WGS-84\"\n             \" -datetimeoriginal=now -gpsdop=0.8\"\n             \" -gpsmeasuremode=3-d -gpssatellites=13 -gpsaltitude=%.3lf -overwrite_original %s &>\/dev\/null\",\n             north_south, east_west, lat, lon, _lastGpsPosition.Z(), file_name);\n\n    if (system(gps_tag_command) < 0) {\n        gzerr << \"gps tag command failed\" << endl;\n        return;\n    }\n\n    gzmsg << \"Took picture: \" << file_name << endl;\n\n    \/\/ Send indication to GCS\n    mavlink_message_t msg;\n    mavlink_msg_camera_image_captured_pack_chan(\n        _systemID,\n        _componentID,\n        MAVLINK_COMM_1,\n        &msg,\n        currentTime.Double() * 1e3, \/\/ time boot ms\n        currentTime.Double() * 1e6, \/\/ time UTC\n        1, \/\/ camera ID\n        lat * 1e7,\n        lon * 1e7,\n        _lastGpsPosition.Z(),\n        0, \/\/ relative alt\n        0, \/\/ q[4]\n        _imageCounter,\n        1, \/\/ result\n        0 \/\/ file_url\n    );\n\n    \/\/ Send to GCS port directly\n    _send_mavlink_message(&msg);\n    ++_imageCounter;\n    _captureMutex.lock();\n    if (_captureMode == CAPTURE_SINGLE) {\n        _captureMode  = CAPTURE_DISABLED;\n    } else {\n        \/\/ _captureCount == 0 is infinite\n        if (_captureCount && --_captureCount < 1) {\n            _captureCount = 0;\n            _captureMode  = CAPTURE_DISABLED;\n        }\n    }\n    if (_captureMode == CAPTURE_DISABLED) {\n        gzdbg << \"Done with image capture\\n\";\n    }\n    _captureMutex.unlock();\n    \/\/ Send Capture Status\n    _send_capture_status();\n}\n\nvoid CameraManagerPlugin::_handle_message(mavlink_message_t *msg, struct sockaddr* srcaddr)\n{\n#if defined(DEBUG_MESSAGE_IO)\n    sockaddr_in* foo = (sockaddr_in*)srcaddr;\n    if (msg->sysid == 255) {\n        gzdbg << \"Message \" << std::to_string(msg->msgid).c_str() <<\n              \" \" << std::to_string(msg->sysid).c_str() << \" \" << std::to_string(msg->compid).c_str() <<\n              \" from: \" << inet_ntoa(foo->sin_addr) << \":\" << std::to_string(ntohs(foo->sin_port)).c_str() << endl;\n    }\n#endif\n    switch (msg->msgid) {\n    case MAVLINK_MSG_ID_COMMAND_LONG:\n        mavlink_command_long_t cmd;\n        mavlink_msg_command_long_decode(msg, &cmd);\n        mavlink_command_long_t digicam_ctrl_cmd;\n        if (cmd.target_component == _componentID) {\n            switch (cmd.command) {\n            case MAV_CMD_IMAGE_START_CAPTURE:\n                _handle_take_photo(msg, srcaddr);\n                break;\n            case MAV_CMD_IMAGE_STOP_CAPTURE:\n                _handle_stop_take_photo(msg, srcaddr);\n                break;\n            case MAV_CMD_REQUEST_CAMERA_INFORMATION:\n                _handle_camera_info(msg, srcaddr);\n                break;\n            case MAV_CMD_REQUEST_CAMERA_CAPTURE_STATUS:\n                _handle_request_camera_capture_status(msg, srcaddr);\n                break;\n            case MAV_CMD_REQUEST_STORAGE_INFORMATION:\n                _handle_storage_info(msg, srcaddr);\n                break;\n            case MAV_CMD_REQUEST_CAMERA_SETTINGS:\n                _handle_request_camera_settings(msg, srcaddr);\n                break;\n            case MAV_CMD_REQUEST_VIDEO_STREAM_INFORMATION:\n                _handle_request_video_stream_information(msg, srcaddr);\n                break;\n            case MAV_CMD_REQUEST_VIDEO_STREAM_STATUS:\n                _handle_request_video_stream_status(msg, srcaddr);\n                break;\n            case MAV_CMD_SET_CAMERA_MODE:\n                _handle_set_camera_mode(msg, srcaddr);\n                break;\n            case MAV_CMD_SET_CAMERA_ZOOM:\n                \/\/Control the Zoom of the camera\n                _handle_camera_zoom(msg, srcaddr);\n                break;\n            case MAV_CMD_RESET_CAMERA_SETTINGS:\n                \/\/ Just ACK and ignore\n                _send_cmd_ack(msg->sysid, msg->compid, MAV_CMD_RESET_CAMERA_SETTINGS, MAV_RESULT_ACCEPTED, srcaddr);\n                break;\n            case MAV_CMD_STORAGE_FORMAT:\n                \/\/ Just ACK and ignore\n                _send_cmd_ack(msg->sysid, msg->compid, MAV_CMD_STORAGE_FORMAT, MAV_RESULT_ACCEPTED, srcaddr);\n                break;\n            case MAV_CMD_VIDEO_START_STREAMING:\n                \/\/ Just ACK and ignore\n                _send_cmd_ack(msg->sysid, msg->compid, MAV_CMD_VIDEO_START_STREAMING, MAV_RESULT_ACCEPTED, srcaddr);\n                break;\n            case MAV_CMD_VIDEO_STOP_STREAMING:\n                \/\/ Just ACK and ignore\n                _send_cmd_ack(msg->sysid, msg->compid, MAV_CMD_VIDEO_STOP_STREAMING, MAV_RESULT_ACCEPTED, srcaddr);\n                break;\n            }\n        }\n        break;\n    }\n}\n\nvoid CameraManagerPlugin::_send_mavlink_message(const mavlink_message_t *message, struct sockaddr* srcaddr)\n{\n    struct sockaddr* target = srcaddr ? srcaddr : (struct sockaddr *)&_gcsaddr;\n    uint8_t buffer[MAVLINK_MAX_PACKET_LEN];\n    int packetlen = mavlink_msg_to_send_buffer(buffer, message);\n    ssize_t len = sendto(_fd, buffer, packetlen, 0, target, sizeof(_gcsaddr));\n    if (len <= 0) {\n        gzerr << \"Failed sending mavlink message\" << endl;\n#if defined(DEBUG_MESSAGE_IO)\n    } else {\n        sockaddr_in* foo = (sockaddr_in*)target;\n        gzdbg << \"Message \" << std::to_string(message->msgid).c_str() <<\n              \" \" << std::to_string(message->sysid).c_str() << \" \" << std::to_string(message->compid).c_str() <<\n              \" to: \" << inet_ntoa(foo->sin_addr) << \":\" << std::to_string(ntohs(foo->sin_port)).c_str() << endl;\n#endif\n    }\n}\n\nvoid CameraManagerPlugin::_send_cmd_ack(uint8_t target_sysid, uint8_t target_compid, uint16_t cmd, unsigned char result, struct sockaddr* srcaddr)\n{\n    mavlink_message_t msg;\n    mavlink_msg_command_ack_pack_chan(\n        _systemID,\n        _componentID,\n        MAVLINK_COMM_1,\n        &msg,\n        cmd,\n        result,\n        100,\n        0,\n        target_sysid,\n        target_compid);\n    _send_mavlink_message(&msg, srcaddr);\n}\n\nvoid CameraManagerPlugin::_send_heartbeat()\n{\n    mavlink_message_t msg;\n    mavlink_msg_heartbeat_pack_chan(_systemID, _componentID, MAVLINK_COMM_1, &msg, MAV_TYPE_GENERIC, MAV_AUTOPILOT_GENERIC, 0, 0, 0);\n    \/\/ Send to GCS port directly\n    _send_mavlink_message(&msg);\n    \/\/ Gazebo log output is using buffered IO for some reason\n    fflush(stdout);\n    fflush(stderr);\n}\n\nvoid CameraManagerPlugin::cameraThread() {\n    mavlink_status_t  status;\n    mavlink_message_t msg;\n    unsigned char buffer[16 * 1024];\n    while (true) {\n        ::poll(&_fds[0], (sizeof(_fds[0]) \/ sizeof(_fds[0])), 1000);\n        if (_fds[0].revents & POLLIN) {\n            struct sockaddr srcaddr;\n            socklen_t addrlen = sizeof(srcaddr);\n            int len = recvfrom(_fd, buffer, sizeof(buffer), 0, (struct sockaddr *)&srcaddr, &addrlen);\n            if (len > 0) {\n                for (unsigned i = 0; i < len; ++i)\n                {\n                    if (mavlink_parse_char(MAVLINK_COMM_1, buffer[i], &msg, &status))\n                    {\n                        \/\/ have a message, handle it\n                        _handle_message(&msg, &srcaddr);\n                        memset(&status, 0, sizeof(status));\n                        memset(&msg, 0, sizeof(msg));\n                    }\n                }\n            }\n        }\n        \/\/ Heartbeat\n#if GAZEBO_MAJOR_VERSION >= 8\n        common::Time current_time = _scene->SimTime();\n#else\n        common::Time current_time = _scene->GetSimTime();\n#endif\n        double elapsed = (current_time - _last_heartbeat).Double();\n        if (elapsed > 1.0) {\n            _last_heartbeat = current_time;\n            _send_heartbeat();\n        }\n\n        \/\/Move camera zoom incase of continuous zoom\n        \/\/ _zoom_cmd is set by MAV_CMD_SET_CAMERA_ZOOM\n        if (_zoom_cmd!=0) {\n            _zoom = std::max(std::min(float(_zoom + 0.05 * _zoom_cmd), _maxZoom), 1.0f);\n            _camera->SetHFOV(_hfov \/ _zoom);\n        }\n\n    }\n}\n\nbool CameraManagerPlugin::_init_udp(sdf::ElementPtr sdf) {\n    \/\/-- Target\n    uint32_t mavlink_addr = htonl(INADDR_LOOPBACK);\n    \/* TODO: We need to find if the system is setup for broadcast\n             and add the proper socket options and broadcast address\n             if that's the case. It's hardcoded to loopback for now.\n\n    if (sdf->HasElement(\"mavlink_telem_addr\")) {\n        std::string mavlink_addr = sdf->GetElement(\"mavlink_telem_addr\")->Get<std::string>();\n        if (mavlink_addr != \"INADDR_ANY\") {\n            mavlink_addr_ = inet_addr(mavlink_addr.c_str());\n            if (mavlink_addr_ == INADDR_NONE) {\n                fprintf(stderr, \"invalid mavlink_addr \\\"%s\\\"\\n\", mavlink_addr.c_str());\n                return;\n            }\n        }\n    }\n\n    *\/\n    \/\/Create socket\n    if ((_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {\n        gzerr << \"Create camera plugin UDP socket failed\" << endl;\n        return false;\n    }\n    memset((char *)&_myaddr, 0, sizeof(_myaddr));\n    _myaddr.sin_family = AF_INET;\n    _myaddr.sin_addr.s_addr = htonl(INADDR_ANY);\n    \/\/ Choose the default cam port\n    _myaddr.sin_port = htons(_mavlinkCamPort);\n    if (::bind(_fd, (struct sockaddr *)&_myaddr, sizeof(_myaddr)) < 0) {\n        gzerr << \"Bind failed for camera UDP plugin\" << endl;\n        return false;\n    }\n    _gcsaddr.sin_family = AF_INET;\n    _gcsaddr.sin_addr.s_addr = mavlink_addr;\n    _gcsaddr.sin_port = htons(14550);\n    _fds[0].fd = _fd;\n    _fds[0].events = POLLIN;\n    mavlink_status_t* chan_state = mavlink_get_channel_status(MAVLINK_COMM_1);\n    chan_state->flags &= ~(MAVLINK_STATUS_FLAG_OUT_MAVLINK1);\n    gzmsg << \"[Camera manager plugin]: Camera on udp port \" + std::to_string(_mavlinkCamPort) + \"\\n\";\n    return true;\n}\n\nvoid CameraManagerPlugin::_handle_take_photo(const mavlink_message_t *pMsg, struct sockaddr* srcaddr)\n{\n\n    gzdbg << \"Handle Start Capture\" << endl;\n    mavlink_command_long_t cmd;\n    mavlink_msg_command_long_decode(pMsg, &cmd);\n    std::lock_guard<std::mutex> guard(_captureMutex);\n    \/\/-- We we busy?\n    if (_captureMode != CAPTURE_DISABLED) {\n        _send_cmd_ack(pMsg->sysid, pMsg->compid,\n                      MAV_CMD_IMAGE_START_CAPTURE, MAV_RESULT_TEMPORARILY_REJECTED, srcaddr);\n        return;\n    }\n    \/\/-- Single capture?\n    if (cmd.param3 == 1) {\n        _captureMode = CAPTURE_SINGLE;\n        _send_cmd_ack(pMsg->sysid, pMsg->compid,\n                      MAV_CMD_IMAGE_START_CAPTURE, MAV_RESULT_ACCEPTED, srcaddr);\n        \/\/-- Time lapse?\n    } else if (cmd.param3 >= 0 && cmd.param2 > 0.0) {\n        gzdbg << \"Start time lapse of \" << (int)cmd.param3 << \" shots every \" << cmd.param2 << \" seconds.\\n\";\n        _captureInterval = cmd.param2;\n        _captureCount    = cmd.param3;\n        _captureMode     = CAPTURE_ELAPSED;\n        _send_cmd_ack(pMsg->sysid, pMsg->compid,\n                      MAV_CMD_IMAGE_START_CAPTURE, MAV_RESULT_ACCEPTED, srcaddr);\n    } else {\n        gzerr << \"Bad Start Capture argments: \" << cmd.param2 << \" \" << cmd.param3 << endl;\n        _send_cmd_ack(pMsg->sysid, pMsg->compid,\n                      MAV_CMD_IMAGE_START_CAPTURE, MAV_RESULT_UNSUPPORTED, srcaddr);\n    }\n}\n\nvoid CameraManagerPlugin::_handle_stop_take_photo(const mavlink_message_t *pMsg, struct sockaddr* srcaddr)\n{\n\n    gzdbg << \"Handle Stop Capture\" << endl;\n    mavlink_command_long_t cmd;\n    mavlink_msg_command_long_decode(pMsg, &cmd);\n    std::lock_guard<std::mutex> guard(_captureMutex);\n    _captureMode = CAPTURE_DISABLED;\n    _send_cmd_ack(pMsg->sysid, pMsg->compid,\n                  MAV_CMD_IMAGE_STOP_CAPTURE, MAV_RESULT_ACCEPTED, srcaddr);\n}\n\nvoid CameraManagerPlugin::_handle_request_camera_capture_status(const mavlink_message_t *pMsg, struct sockaddr* srcaddr)\n{\n    mavlink_command_long_t cmd;\n    mavlink_msg_command_long_decode(pMsg, &cmd);\n    \/\/ Should we execute the command\n    if (cmd.param1 != 1)\n    {\n        gzwarn << \"Camera capture status request ignored\" << endl;\n        return;\n    }\n    \/\/ ACK command received and accepted\n    _send_cmd_ack(pMsg->sysid, pMsg->compid, MAV_CMD_REQUEST_CAMERA_CAPTURE_STATUS, MAV_RESULT_ACCEPTED, srcaddr);\n    \/\/-- Specs call for recording time in ms. get_recording_time returns seconds.\n    _send_capture_status(srcaddr);\n}\n\nvoid CameraManagerPlugin::_handle_camera_info(const mavlink_message_t *pMsg, struct sockaddr* srcaddr)\n{\n    gzdbg << \"Send camera info\" << endl;\n    _send_cmd_ack(pMsg->sysid, pMsg->compid, MAV_CMD_REQUEST_CAMERA_INFORMATION, MAV_RESULT_ACCEPTED, srcaddr);\n    static const char vendor[MAVLINK_MSG_CAMERA_INFORMATION_FIELD_VENDOR_NAME_LEN] = \"PX4.io\";\n    static const char model[MAVLINK_MSG_CAMERA_INFORMATION_FIELD_MODEL_NAME_LEN] = \"Gazebo\";\n    static const char uri[MAVLINK_MSG_CAMERA_INFORMATION_FIELD_CAM_DEFINITION_URI_LEN] = {};\n    uint32_t camera_capabilities = CAMERA_CAP_FLAGS_CAPTURE_IMAGE | CAMERA_CAP_FLAGS_CAPTURE_VIDEO |\n            CAMERA_CAP_FLAGS_HAS_MODES | CAMERA_CAP_FLAGS_HAS_BASIC_ZOOM |\n            CAMERA_CAP_FLAGS_HAS_VIDEO_STREAM;\n\n    mavlink_message_t msg;\n    mavlink_msg_camera_information_pack_chan(\n        _systemID,\n        _componentID,\n        MAVLINK_COMM_1,\n        &msg,\n        0,                         \/\/ time_boot_ms\n        (const uint8_t *)vendor,   \/\/ const uint8_t * vendor_name\n        (const uint8_t *)model,    \/\/ const uint8_t * model_name\n        0x01,                      \/\/ uint32_t firmware_version\n        50.0f,                     \/\/ float focal_lenth\n        35.0f,                     \/\/ float  sensor_size_h\n        24.0f,                     \/\/ float  sensor_size_v\n        _width,                    \/\/ resolution_h\n        _height,                   \/\/ resolution_v\n        0,                         \/\/ lens_id\n        camera_capabilities,       \/\/ CAP_FLAGS\n        0,                         \/\/ Camera Definition Version\n        uri                        \/\/ URI\n    );\n    _send_mavlink_message(&msg, srcaddr);\n}\n\nvoid CameraManagerPlugin::_handle_request_camera_settings(const mavlink_message_t *pMsg, struct sockaddr* srcaddr)\n{\n    gzdbg << \"Send camera settings\" << endl;\n    mavlink_command_long_t cmd;\n    mavlink_msg_command_long_decode(pMsg, &cmd);\n    \/\/-- Should we execute the command\n    if ((int)cmd.param1 != 1)\n    {\n        gzwarn << \"Request ignored\" << endl;\n        return;\n    }\n    \/\/ ACK command received and accepted\n    _send_cmd_ack(pMsg->sysid, pMsg->compid, MAV_CMD_REQUEST_CAMERA_SETTINGS, MAV_RESULT_ACCEPTED, srcaddr);\n    mavlink_message_t msg;\n    mavlink_msg_camera_settings_pack_chan(\n        _systemID,\n        _componentID,\n        MAVLINK_COMM_1,\n        &msg,\n        0,                      \/\/ time_boot_ms\n        _mode,                  \/\/ Camera Mode\n        1.0E2 * (_zoom - 1.0)\/ (_maxZoom - 1.0),                    \/\/ Zoom level\n        NAN);                   \/\/ Focus level\n    _send_mavlink_message(&msg, srcaddr);\n}\n\nvoid CameraManagerPlugin::_handle_request_video_stream_status(const mavlink_message_t *pMsg, struct sockaddr* srcaddr)\n{\n    gzdbg << \"Send videostream status\" << endl;\n    mavlink_command_long_t cmd;\n    mavlink_msg_command_long_decode(pMsg, &cmd);\n    int sid = static_cast<int>(cmd.param1);\n    \/\/-- Should we execute the command\n    if ((int)cmd.param1 != 1)\n    {\n        gzwarn << \"Request ignored\" << endl;\n        return;\n    }\n    \/\/ ACK command received and accepted\n    _send_cmd_ack(pMsg->sysid, pMsg->compid, MAV_CMD_REQUEST_VIDEO_STREAM_STATUS, MAV_RESULT_ACCEPTED, srcaddr);\n    mavlink_message_t msg;\n    mavlink_msg_video_stream_status_pack_chan(\n        _systemID,\n        _componentID,                                     \/\/ Component ID\n        MAVLINK_COMM_1,\n        &msg,\n        static_cast<uint8_t>(sid),                              \/\/ Stream ID\n        VIDEO_STREAM_STATUS_FLAGS_RUNNING,                      \/\/ Flags (It's always running)\n        30,                                                     \/\/ Frame rate\n        _width,                                                  \/\/ Horizontal resolution\n        _height,                                                \/\/ Vertical resolution\n        2048,                                                   \/\/ Bit rate (made up)\n        0,                                                      \/\/ Rotation (none)\n        90                                                      \/\/ FOV (made up)\n    );\n    _send_mavlink_message(&msg, srcaddr);\n}\n\nvoid CameraManagerPlugin::_handle_request_video_stream_information(const mavlink_message_t *pMsg, struct sockaddr* srcaddr)\n{\n    gzdbg << \"Send videostream information\" << endl;\n    char name[MAVLINK_MSG_VIDEO_STREAM_INFORMATION_FIELD_NAME_LEN] = {};\n    snprintf(name, MAVLINK_MSG_VIDEO_STREAM_INFORMATION_FIELD_NAME_LEN, \"Visual Spectrum\");\n    mavlink_command_long_t cmd;\n    mavlink_msg_command_long_decode(pMsg, &cmd);\n    \/\/-- Should we execute the command\n    if ((int)cmd.param1 != 1)\n    {\n        gzwarn << \"Request ignored\" << endl;\n        return;\n    }\n\n    \/\/ ACK command received and accepted\n    _send_cmd_ack(pMsg->sysid, pMsg->compid, MAV_CMD_REQUEST_VIDEO_STREAM_INFORMATION, MAV_RESULT_ACCEPTED, srcaddr);\n\n    mavlink_message_t msg;\n    mavlink_msg_video_stream_information_pack_chan(\n        _systemID,\n        _componentID,                         \/\/ Component ID\n        MAVLINK_COMM_1,\n        &msg,\n        1,                                          \/\/ Stream ID\n        1,                                          \/\/ Stream count\n        VIDEO_STREAM_TYPE_RTPUDP,                   \/\/ Stream type\n        VIDEO_STREAM_STATUS_FLAGS_RUNNING,          \/\/ Flags (It's always running)\n        30,                                         \/\/ Frame rate\n        _width,                                     \/\/ Horizontal resolution\n        _height,                                    \/\/ Vertical resolution\n        2048,                                       \/\/ Bit rate\n        0,                                          \/\/ Rotation (none)\n        90,                                         \/\/ FOV (made up)\n        name,\n        _videoURI.c_str()\n    );\n    _send_mavlink_message(&msg, srcaddr);\n}\n\nvoid CameraManagerPlugin::_handle_set_camera_mode(const mavlink_message_t *pMsg, struct sockaddr* srcaddr)\n{\n    mavlink_command_long_t cmd;\n    mavlink_msg_command_long_decode(pMsg, &cmd);\n    _send_cmd_ack(pMsg->sysid, pMsg->compid,\n                  MAV_CMD_SET_CAMERA_MODE, MAV_RESULT_ACCEPTED, srcaddr);\n    if (_mode == CAMERA_MODE_VIDEO) {\n        _mode = CAMERA_MODE_IMAGE;\n    } else {\n        _mode = CAMERA_MODE_VIDEO;\n    }\n\n}\n\nvoid CameraManagerPlugin::_handle_camera_zoom(const mavlink_message_t *pMsg, struct sockaddr* srcaddr)\n{\n    mavlink_command_long_t cmd;\n    mavlink_msg_command_long_decode(pMsg, &cmd);\n    _send_cmd_ack(pMsg->sysid, pMsg->compid,\n                  MAV_CMD_SET_CAMERA_ZOOM, MAV_RESULT_ACCEPTED, srcaddr);\n\n    if (cmd.param1 == ZOOM_TYPE_CONTINUOUS) {\n        _zoom = std::max(std::min(float(_zoom + 0.1 * cmd.param2), _maxZoom), 1.0f);\n        _zoom_cmd = cmd.param2;\n    } else {\n        _zoom = std::max(std::min(float(_zoom + 0.1 * cmd.param2), _maxZoom), 1.0f);\n        _camera->SetHFOV(_hfov \/ _zoom);\n    }\n}\n\nvoid CameraManagerPlugin::_send_capture_status(struct sockaddr* srcaddr)\n{\n    _captureMutex.lock();\n    int status = _captureMode == CAPTURE_DISABLED ? 0 : (_captureMode == CAPTURE_SINGLE ? 1 : 3);\n    float interval = CAPTURE_ELAPSED ? (float)_captureInterval : 0.0f;\n    _captureMutex.unlock();\n    gzdbg << \"Send capture status\" << endl;\n    float available_mib = 0.0f;\n    boost::filesystem::space_info si = boost::filesystem::space(\".\");\n    available_mib = (float)((double)si.available \/ (1024.0 * 1024.0));\n\n#if GAZEBO_MAJOR_VERSION >= 9\n    common::Time current_time = _scene->SimTime();\n#else\n    common::Time current_time = _scene->GetSimTime();\n#endif\n\n    mavlink_message_t msg;\n    mavlink_msg_camera_capture_status_pack_chan(\n        _systemID,\n        _componentID,\n        MAVLINK_COMM_1,\n        &msg,\n        current_time.Double() * 1e3,\n        status,                                 \/\/ image status\n        0,                                      \/\/ video status (Idle)\n        interval,                               \/\/ image interval\n        0,                                      \/\/ recording time in ms\n        available_mib,                          \/\/ available storage capacity\n        _imageCounter);                         \/\/ total number of images\n    _send_mavlink_message(&msg, srcaddr);\n}\n\nvoid CameraManagerPlugin::_handle_storage_info(const mavlink_message_t *pMsg, struct sockaddr* srcaddr)\n{\n    gzdbg << \"Send storage info\" << endl;\n    float total_mib     = 0.0f;\n    float available_mib = 0.0f;\n    boost::filesystem::space_info si = boost::filesystem::space(\".\");\n    const std::string storage_name = \"SITL Camera Storage\";\n    available_mib = (float)((double)si.available \/ (1024.0 * 1024.0));\n    total_mib     = (float)((double)si.capacity  \/ (1024.0 * 1024.0));\n    _send_cmd_ack(pMsg->sysid, pMsg->compid, MAV_CMD_REQUEST_STORAGE_INFORMATION, MAV_RESULT_ACCEPTED, srcaddr);\n    uint8_t storage_usage = STORAGE_USAGE_FLAG_SET | STORAGE_USAGE_FLAG_PHOTO | STORAGE_USAGE_FLAG_VIDEO | STORAGE_USAGE_FLAG_LOGS;\n    mavlink_message_t msg;\n    mavlink_msg_storage_information_pack_chan(\n        _systemID,\n        _componentID,\n        MAVLINK_COMM_1,\n        &msg,\n        0,                                  \/\/ time_boot_ms\n        1,                                  \/\/ storage_id,\n        1,                                  \/\/ storage_count,\n        2,                                  \/\/ status: (formatted)\n        total_mib,\n        total_mib - available_mib,          \/\/ used_capacity,\n        available_mib,\n        NAN,                                \/\/ read_speed,\n        NAN,                                \/\/ write_speed\n        STORAGE_TYPE_OTHER,                 \/\/ storage type\n        storage_name.c_str(),               \/\/ storage name\n        storage_usage                       \/\/ storage usage\n    );\n    _send_mavlink_message(&msg, srcaddr);\n}\n","avg_line_length":37.6025477707,"max_line_length":146,"alphanum_fraction":0.609492513,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2407,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"assignment\/array_stack.hpp\"\n\n#include <algorithm>  \/\/ copy, fill\n#include <stdexcept>  \/\/ invalid_argument (\u041d\u0415\u041b\u042c\u0417\u042f \u0418\u0421\u041f\u041e\u041b\u042c\u0417\u041e\u0412\u0410\u0422\u042c)\n\nnamespace assignment {\n\n  ArrayStack::ArrayStack(int capacity) {\n\n    \/\/ \u0432\u044b\u0431\u0440\u0430\u0441\u044b\u0432\u0430\u0435\u043c \u043e\u0448\u0438\u0431\u043a\u0443, \u0435\u0441\u043b\u0438 \u0443\u043a\u0430\u0437\u0430\u043d\u0430 \u043d\u0435\u043f\u043e\u043b\u043e\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u0430\u044f \u0435\u043c\u043a\u043e\u0441\u0442\u044c \u0441\u0442\u0435\u043a\u0430\n    if (capacity <= 0) {\n      throw std::invalid_argument(\"capacity is not positive\");\n    }\n\n    size_ = 0;\n    capacity_ = capacity;\n    data_ = new int[capacity_];\n    std::fill(data_, data_ + capacity, 0);\n  }\n\n  ArrayStack::~ArrayStack() {\n    size_ = 0;\n    capacity_ = 0;\n    delete[] data_;\n    data_ = nullptr;\n  }\n\n  void ArrayStack::Push(int value) {\n    if (size_ >= capacity_){\n      Resize(capacity_ + kCapacityGrowthCoefficient);\n      data_[size_] = value;\n      size_++;\n    } else {\n      data_[size_] = value;\n      size_++;\n    }\n  }\n\n  bool ArrayStack::Pop() {\n    if(size_ == 0) {\n      return false;\n    }\n    int* new_data = new int[capacity_];\n    for(int i = 0; i < size_ - 1 ; i++){\n      new_data[i] = data_[i];\n    }\n    data_ = new_data;\n    size_ --;\n    return true;\n  }\n\n  void ArrayStack::Clear() {\n    delete[] data_;\n    data_ = nullptr;\n    size_ = 0;\n  }\n\n  std::optional<int> ArrayStack::Peek() const {\n    if(size_ > 0){\n      return data_[size_ - 1];\n    }\n    return std::nullopt;\n  }\n\n  bool ArrayStack::IsEmpty() const {\n    return size_ == 0;\n  }\n\n  int ArrayStack::size() const {\n    return size_;\n  }\n\n  int ArrayStack::capacity() const {\n    return capacity_;\n  }\n\n  bool ArrayStack::Resize(int new_capacity) {\n    if (new_capacity > capacity_){\n      int* new_data = new int[new_capacity];\n      for(int i = 0; i < size_; i++){\n        new_data[i] = data_[i];\n      }\n      delete[] data_;\n      data_ = new_data;\n      new_data = nullptr;\n      capacity_ = new_capacity;\n      return true;\n    }\n    return false;\n  }\n\n  \/\/ \u0414\u041b\u042f \u0422\u0415\u0421\u0422\u0418\u0420\u041e\u0412\u0410\u041d\u0418\u042f\n  ArrayStack::ArrayStack(const std::vector<int>& values, int capacity) {\n\n    size_ = static_cast<int>(values.size());\n    capacity_ = capacity;\n\n    data_ = new int[capacity]{};\n\n    std::copy(values.data(), values.data() + size_, data_);\n  }\n\n  std::vector<int> ArrayStack::toVector(std::optional<int> size) const {\n\n    if (capacity_ == 0 || data_ == nullptr) {\n      return {};\n    }\n\n    if (size.has_value()) {\n      return {data_, data_ + size.value()};\n    }\n\n    return {data_, data_ + capacity_};\n  }\n\n}  \/\/ namespace assignment\n","avg_line_length":20.5726495726,"max_line_length":72,"alphanum_fraction":0.5866223515,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2050,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":17.0,"content":"#include \"importprivatekeydialog.h\"\n#include \"ui_importprivatekeydialog.h\"\n\n#include \"addresstablemodel.h\"\n#include \"base58.h\"\n#include \"init.h\"\n\n#include <QDataWidgetMapper>\n#include <QMessageBox>\n#include <QClipboard>\n\nImportPrivateKeyDialog::ImportPrivateKeyDialog(QWidget *parent) :\n    QDialog(parent),\n    ui(new Ui::ImportPrivateKeyDialog), mapper(0), model(0)\n{\n    ui->setupUi(this);\n    ui->rescanCB->setChecked(true);\n\n    mapper = new QDataWidgetMapper(this);\n    mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);\n}\n\nImportPrivateKeyDialog::~ImportPrivateKeyDialog()\n{\n    delete ui;\n}\n\nvoid ImportPrivateKeyDialog::setModel(AddressTableModel *model)\n{\n    this->model = model;\n    if(!model)\n        return;\n\n    mapper->setModel(model);\n    mapper->addMapping(ui->labelEdit, AddressTableModel::Label);\n}\n\nvoid ImportPrivateKeyDialog::accept()\n{\n    if(!model)\n        return;\n\n    QString strKey = ui->keyEdit->text();\n    if (!strKey.isEmpty())\n    {\n        CPupaCoinSecret vchSecret;\n        bool fGood = vchSecret.SetString(strKey.toUtf8().constData());\n        if (fGood) {\n            QString strLabel = ui->labelEdit->text();\n            bool fRescan = ui->rescanCB->isChecked();\n\n            if (pwalletMain->ImportPrivateKey(vchSecret, strLabel.toUtf8().constData(), fRescan)) {\n                QMessageBox::information(this, tr(\"Success\"), tr(\"Private key successfully imported!\"));\n                \/\/ Refresh the \"receive\" tab\n                model->refresh();\n            }\n            else {\n                QMessageBox::warning(this, tr(\"Error\"), tr(\"Error adding key to wallet\"));\n                return;\n            }\n        }\n        else {\n            QMessageBox::warning(this, tr(\"Error\"), tr(\"Invalid private key\"));\n            return;\n        }\n    }\n    else\n    {\n        return;\n    }\n\n    QDialog::accept();\n}\n\nvoid ImportPrivateKeyDialog::on_ImportPrivateKeyPasteButton_clicked()\n{\n    \/\/ Paste text from clipboard into recipient field\n    ui->keyEdit->setText(QApplication::clipboard()->text());\n}\n","avg_line_length":25.625,"max_line_length":104,"alphanum_fraction":0.6273170732,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6161,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":4891.0,"content":"\/*\n *\n * This file is part of the open-source SeetaFace engine, which includes three modules:\n * SeetaFace Detection, SeetaFace Alignment, and SeetaFace Identification.\n *\n * This file is part of the SeetaFace Identification module, containing codes implementing the\n * face identification method described in the following paper:\n *\n *   \n *   VIPLFaceNet: An Open Source Deep Face Recognition SDK,\n *   Xin Liu, Meina Kan, Wanglong Wu, Shiguang Shan, Xilin Chen.\n *   In Frontiers of Computer Science.\n *\n *\n * Copyright (C) 2016, Visual Information Processing and Learning (VIPL) group,\n * Institute of Computing Technology, Chinese Academy of Sciences, Beijing, China.\n *\n * The codes are mainly developed by Wanglong Wu(a Ph.D supervised by Prof. Shiguang Shan)\n *\n * As an open-source face recognition engine: you can redistribute SeetaFace source codes\n * and\/or modify it under the terms of the BSD 2-Clause License.\n *\n * You should have received a copy of the BSD 2-Clause License along with the software.\n * If not, see < https:\/\/opensource.org\/licenses\/BSD-2-Clause>.\n *\n * Contact Info: you can send an email to SeetaFace@vipl.ict.ac.cn for any problems. \n *\n * Note: the above information must be kept whenever or wherever the codes are used.\n *\n *\/\n\n#include \"blob.h\"\n\n#include <cstdio>\n#include <cstring>\n#include <fstream>\n\nBlob::Blob() {\n  data_ = nullptr;\n  shape_.clear();\n}\n\nBlob::Blob(const Blob &source) {\n  if (data_)\n    data_ = nullptr;\n  shape_ = source.shape();\n  count_ = source.count();\n  data_ = source.data();\n}\n\nBlob::Blob(int n, int c, int h, int w) {\n  if (data_)\n    data_ = nullptr;\n  shape_.resize(4);\n  shape_[0] = n;\n  shape_[1] = c;\n  shape_[2] = h;\n  shape_[3] = w;\n  count_ = n * c * h * w;\n}\n\nBlob::Blob(int n, int c, int h, int w, float* data) {\n  if (data_)\n    data_ = nullptr;\n  shape_.resize(4);\n  shape_[0] = n;\n  shape_[1] = c;\n  shape_[2] = h;\n  shape_[3] = w;\n  count_ = n * c * h * w;\n  data_.reset(new float[count_], std::default_delete<float[]>());\n  memcpy(data_.get(), data, count_ * sizeof(float));\n}\n\nBlob::Blob(FILE* file) {\n  shape_.resize(4);\n  CHECK_EQ(fread(&(shape_[0]), sizeof(int), 1, file), 1);\n  CHECK_EQ(fread(&(shape_[1]), sizeof(int), 1, file), 1);\n  CHECK_EQ(fread(&(shape_[2]), sizeof(int), 1, file), 1);\n  CHECK_EQ(fread(&(shape_[3]), sizeof(int), 1, file), 1);\n  count_ = shape_[0] * shape_[1] * shape_[2] * shape_[3];\n  data_.reset(new float[count_], std::default_delete<float[]>());\n  CHECK_EQ(fread(data_.get(), sizeof(float), count_, file), count_);\n}\n\nBlob::~Blob() {\n  shape_.clear();\n  count_ = 0;\n  data_ = nullptr;\n}\n\nvoid Blob::reshape(int n, int c, int h, int w) {\n  shape_.resize(4);\n  shape_[0] = n;\n  shape_[1] = c;\n  shape_[2] = h;\n  shape_[3] = w;\n  count_ = n * c * h * w;\n  data_ = nullptr; \n}\n\nvoid Blob::Permute(int dim1, int dim2, int dim3, int dim4) {\n  \/\/ todo: check permute\n  std::vector<int> dim(4), redim(4), idx(4);\n  dim[0] = dim1 - 1; redim[dim[0]] = 0;\n  dim[1] = dim2 - 1; redim[dim[1]] = 1;\n  dim[2] = dim3 - 1; redim[dim[2]] = 2;\n  dim[3] = dim4 - 1; redim[dim[3]] = 3;\n  float* tmp = new float[count_];\n  float* dat = data_.get();\n  int cnt = 0;\n  for (idx[0] = 0; idx[0] < shape_[dim[0]]; ++ idx[0]) {\n    for (idx[1] = 0; idx[1] < shape_[dim[1]]; ++ idx[1]) {\n      for (idx[2] = 0; idx[2] < shape_[dim[2]]; ++ idx[2]) {\n        for (idx[3] = 0; idx[3] < shape_[dim[3]]; ++ idx[3]) {\n          tmp[cnt] = dat[offset(idx[redim[0]], idx[redim[1]], idx[redim[2]],\n              idx[redim[3]])];\n          cnt ++ ;\n        }\n      }\n    }\n  }\n  std::vector<int> tmp_shape(4);\n  for (int i = 0; i < 4; ++ i)\n    tmp_shape[i] = shape_[dim[i]];\n  for (int i = 0; i < 4; ++ i)\n    shape_[i] = tmp_shape[i];\n  memcpy(dat, tmp, sizeof(float) * count_);\n  delete[] tmp;\n}\n\nvoid Blob::Release() {\n  data_ = nullptr;\n}\n\nvoid Blob::SetData() {\n  if (!data_)\n    data_.reset(new float[count_], std::default_delete<float[]>());\n}\n\n\nvoid Blob::SetData(Blob &source) {\n  if (data_)\n    data_ = nullptr;\n  shape_ = source.shape();\n  count_ = num() * channels() * height() * width();\n  data_ = source.data();\n}\n\nvoid Blob::SetData(int n, int c, int h, int w) {\n  if (data_)\n    data_ = nullptr;\n  shape_.resize(4);\n  shape_[0] = n;\n  shape_[1] = c;\n  shape_[2] = h;\n  shape_[3] = w;\n  count_ = n * c * h * w;\n  data_.reset(new float[count_], std::default_delete<float[]>());\n}\n\n\nvoid Blob::CopyData(int n, int c, int h, int w, const float* const data) {\n  if (data_)\n    data_ = nullptr;\n  shape_.resize(4);\n  shape_[0] = n;\n  shape_[1] = c;\n  shape_[2] = h;\n  shape_[3] = w;\n  count_ = n * c * h * w;\n  data_.reset(new float[count_], std::default_delete<float[]>());\n  memcpy(data_.get(), data, count_ * sizeof(float));\n}\n\nvoid Blob::CopyData(int n, int c, int h, int w, \n    const unsigned char* const data) {\n  if (data_)\n    data_ = nullptr;\n  shape_.resize(4);\n  shape_[0] = n;\n  shape_[1] = c;\n  shape_[2] = h;\n  shape_[3] = w;\n  count_ = n * c * h * w;\n  data_.reset(new float[count_], std::default_delete<float[]>());\n  float* data_head = data_.get();\n  for (int i = 0; i < count_; ++ i)\n    data_head[i] = data[i];\n}\n\nvoid Blob::CopyTo(unsigned char* const data) {\n  const float* const data_head = data_.get();\n  for (int i = 0; i < count_; ++ i)\n    data[i] = std::min(255.0f, std::max(0.0f, data_head[i]));\n}\n\nvoid Blob::CopyTo(float* const data) {\n\tfloat* data_head = data_.get();\n\tmemcpy(data, data_head, count_ * sizeof(float));\n}\n\nvoid Blob::ToFile(const std::string file_name) {\n  std::ofstream ofs;\n  ofs.open(file_name, std::ofstream::out);\n  float* data = data_.get();\n  for (int i = 0; i < count_; ++ i) {\n    ofs << data[i] << \" \";\n  }\n  ofs << std::endl;\n  ofs.close();\n}\n\nvoid Blob::ToBinaryFile(const std::string file_name) {\n  FILE* file = nullptr;\n  fopen_s(&file, file_name.c_str(), \"wb\");\n  if (file == nullptr) {\n    LOG(ERROR) << file_name << \" not exist!\";\n    exit(0);\n  }\n  for (int i = 0; i < 4; ++ i) {\n    if (i < shape_.size())\n      fwrite(&shape_[i], 1, sizeof(int), file);\n    else {\n      int one = 1;\n      fwrite(&one, 1, sizeof(int), file);\n    }\n  }\n  fwrite(data_.get(), count_, sizeof(float), file);\n  fclose(file);\n}\n\n\n","avg_line_length":26.3290598291,"max_line_length":94,"alphanum_fraction":0.601363415,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":239,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"sprite2\/CacheMatVisitor.h\"\n#include \"sprite2\/Sprite.h\"\n\nnamespace s2\n{\n\nvoid CacheMatVisitor::Visit(const SprPtr& spr) const\n{\n#ifdef S2_SPR_CACHE_LOCAL_MAT_SHARE\n\tspr->CacheLocalMat();\n#endif \/\/ S2_SPR_CACHE_LOCAL_MAT_SHARE\n}\n\n}","avg_line_length":17.0714285714,"max_line_length":52,"alphanum_fraction":0.7824267782,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11788,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/****************************************************************************\n *\n *   Copyright (c) 2015 Estimation and Control Library (ECL). All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name ECL nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file airspeed_fusion.cpp\n * airspeed fusion methods.\n *\n * @author Carl Olsson <carlolsson.co@gmail.com>\n * @author Roman Bast <bapstroman@gmail.com>\n * @author Paul Riseborough <p_riseborough@live.com.au>\n *\n *\/\n#include \"..\/ecl.h\"\n#include \"ekf.h\"\n#include \"mathlib.h\"\n\nvoid Ekf::fuseAirspeed()\n{\n\t\/\/ Initialize variables\n\tfloat vn; \/\/ Velocity in north direction\n\tfloat ve; \/\/ Velocity in east direction\n\tfloat vd; \/\/ Velocity in downwards direction\n\tfloat vwn; \/\/ Wind speed in north direction\n\tfloat vwe; \/\/ Wind speed in east direction\n\tfloat v_tas_pred; \/\/ Predicted measurement\n\tfloat R_TAS = sq(math::constrain(_params.eas_noise, 0.5f, 5.0f) * math::constrain(_airspeed_sample_delayed.eas2tas, 0.9f,\n\t\t\t 10.0f)); \/\/ Variance for true airspeed measurement - (m\/sec)^2\n\tfloat SH_TAS[3] = {}; \/\/ Varialbe used to optimise calculations of measurement jacobian\n\tfloat H_TAS[24] = {}; \/\/ Observation Jacobian\n\tfloat SK_TAS[2] = {}; \/\/ Varialbe used to optimise calculations of the Kalman gain vector\n\tfloat Kfusion[24] = {}; \/\/ Kalman gain vector\n\n\t\/\/ Copy required states to local variable names\n\tvn = _state.vel(0);\n\tve = _state.vel(1);\n\tvd = _state.vel(2);\n\tvwn = _state.wind_vel(0);\n\tvwe = _state.wind_vel(1);\n\n\t\/\/ Calculate the predicted airspeed\n\tv_tas_pred = sqrtf((ve - vwe) * (ve - vwe) + (vn - vwn) * (vn - vwn) + vd * vd);\n\n\t\/\/ Perform fusion of True Airspeed measurement\n\tif (v_tas_pred > 1.0f) {\n\t\t\/\/ Calculate the observation jacobian\n\t\t\/\/ intermediate variable from algebraic optimisation\n\t\tSH_TAS[0] = 1.0f\/v_tas_pred;\n\t\tSH_TAS[1] = (SH_TAS[0]*(2.0f*ve - 2.0f*vwe))*0.5f;\n\t\tSH_TAS[2] = (SH_TAS[0]*(2.0f*vn - 2.0f*vwn))*0.5f;\n\n\t\tfor (uint8_t i = 0; i < _k_num_states; i++) { H_TAS[i] = 0.0f; }\n\n\t\tH_TAS[4] = SH_TAS[2];\n\t\tH_TAS[5] = SH_TAS[1];\n\t\tH_TAS[6] = vd*SH_TAS[0];\n\t\tH_TAS[22] = -SH_TAS[2];\n\t\tH_TAS[23] = -SH_TAS[1];\n\n\t\t\/\/ We don't want to update the innovation variance if the calculation is ill conditioned\n\t\tfloat _airspeed_innov_var_temp = (R_TAS + SH_TAS[2]*(P[4][4]*SH_TAS[2] + P[5][4]*SH_TAS[1] - P[22][4]*SH_TAS[2] - P[23][4]*SH_TAS[1] + P[6][4]*vd*SH_TAS[0]) + SH_TAS[1]*(P[4][5]*SH_TAS[2] + P[5][5]*SH_TAS[1] - P[22][5]*SH_TAS[2] - P[23][5]*SH_TAS[1] + P[6][5]*vd*SH_TAS[0]) - SH_TAS[2]*(P[4][22]*SH_TAS[2] + P[5][22]*SH_TAS[1] - P[22][22]*SH_TAS[2] - P[23][22]*SH_TAS[1] + P[6][22]*vd*SH_TAS[0]) - SH_TAS[1]*(P[4][23]*SH_TAS[2] + P[5][23]*SH_TAS[1] - P[22][23]*SH_TAS[2] - P[23][23]*SH_TAS[1] + P[6][23]*vd*SH_TAS[0]) + vd*SH_TAS[0]*(P[4][6]*SH_TAS[2] + P[5][6]*SH_TAS[1] - P[22][6]*SH_TAS[2] - P[23][6]*SH_TAS[1] + P[6][6]*vd*SH_TAS[0]));\n\n\t\tif (_airspeed_innov_var_temp >= R_TAS) { \/\/ Check for badly conditioned calculation\n\t\t\tSK_TAS[0] = 1.0f \/ _airspeed_innov_var_temp;\n\t\t\t_fault_status.flags.bad_airspeed = false;\n\n\t\t} else { \/\/ Reset the estimator covarinace matrix\n\t\t\t_fault_status.flags.bad_airspeed = true;\n\t\t\tinitialiseCovariance();\n\t\t\tECL_ERR(\"EKF airspeed fusion numerical error - covariance reset\");\n\t\t\treturn;\n\t\t}\n\n\t\tSK_TAS[1] = SH_TAS[1];\n\n\t\tif (((_time_last_imu - _time_last_gps) < 1e6) || ((_time_last_imu - _time_last_ext_vision) < 1e6) || ((_time_last_imu - _time_last_optflow) < 1e6)) {\n\t\t\t\/\/ If we are getting aiding from other sources, then don't allow the airspeed measurements to affect the non-windspeed states\n\t\t\tfor (unsigned row = 0; row <= 21; row++) {\n\t\t\t\tKfusion[row] = 0.0f;\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ we have no other source of aiding, so use airspeed measurements to correct states\n\t\t\tKfusion[0] = SK_TAS[0]*(P[0][4]*SH_TAS[2] - P[0][22]*SH_TAS[2] + P[0][5]*SK_TAS[1] - P[0][23]*SK_TAS[1] + P[0][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[1] = SK_TAS[0]*(P[1][4]*SH_TAS[2] - P[1][22]*SH_TAS[2] + P[1][5]*SK_TAS[1] - P[1][23]*SK_TAS[1] + P[1][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[2] = SK_TAS[0]*(P[2][4]*SH_TAS[2] - P[2][22]*SH_TAS[2] + P[2][5]*SK_TAS[1] - P[2][23]*SK_TAS[1] + P[2][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[3] = SK_TAS[0]*(P[3][4]*SH_TAS[2] - P[3][22]*SH_TAS[2] + P[3][5]*SK_TAS[1] - P[3][23]*SK_TAS[1] + P[3][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[4] = SK_TAS[0]*(P[4][4]*SH_TAS[2] - P[4][22]*SH_TAS[2] + P[4][5]*SK_TAS[1] - P[4][23]*SK_TAS[1] + P[4][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[5] = SK_TAS[0]*(P[5][4]*SH_TAS[2] - P[5][22]*SH_TAS[2] + P[5][5]*SK_TAS[1] - P[5][23]*SK_TAS[1] + P[5][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[6] = SK_TAS[0]*(P[6][4]*SH_TAS[2] - P[6][22]*SH_TAS[2] + P[6][5]*SK_TAS[1] - P[6][23]*SK_TAS[1] + P[6][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[7] = SK_TAS[0]*(P[7][4]*SH_TAS[2] - P[7][22]*SH_TAS[2] + P[7][5]*SK_TAS[1] - P[7][23]*SK_TAS[1] + P[7][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[8] = SK_TAS[0]*(P[8][4]*SH_TAS[2] - P[8][22]*SH_TAS[2] + P[8][5]*SK_TAS[1] - P[8][23]*SK_TAS[1] + P[8][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[9] = SK_TAS[0]*(P[9][4]*SH_TAS[2] - P[9][22]*SH_TAS[2] + P[9][5]*SK_TAS[1] - P[9][23]*SK_TAS[1] + P[9][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[10] = SK_TAS[0]*(P[10][4]*SH_TAS[2] - P[10][22]*SH_TAS[2] + P[10][5]*SK_TAS[1] - P[10][23]*SK_TAS[1] + P[10][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[11] = SK_TAS[0]*(P[11][4]*SH_TAS[2] - P[11][22]*SH_TAS[2] + P[11][5]*SK_TAS[1] - P[11][23]*SK_TAS[1] + P[11][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[12] = SK_TAS[0]*(P[12][4]*SH_TAS[2] - P[12][22]*SH_TAS[2] + P[12][5]*SK_TAS[1] - P[12][23]*SK_TAS[1] + P[12][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[13] = SK_TAS[0]*(P[13][4]*SH_TAS[2] - P[13][22]*SH_TAS[2] + P[13][5]*SK_TAS[1] - P[13][23]*SK_TAS[1] + P[13][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[14] = SK_TAS[0]*(P[14][4]*SH_TAS[2] - P[14][22]*SH_TAS[2] + P[14][5]*SK_TAS[1] - P[14][23]*SK_TAS[1] + P[14][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[15] = SK_TAS[0]*(P[15][4]*SH_TAS[2] - P[15][22]*SH_TAS[2] + P[15][5]*SK_TAS[1] - P[15][23]*SK_TAS[1] + P[15][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[16] = SK_TAS[0]*(P[16][4]*SH_TAS[2] - P[16][22]*SH_TAS[2] + P[16][5]*SK_TAS[1] - P[16][23]*SK_TAS[1] + P[16][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[17] = SK_TAS[0]*(P[17][4]*SH_TAS[2] - P[17][22]*SH_TAS[2] + P[17][5]*SK_TAS[1] - P[17][23]*SK_TAS[1] + P[17][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[18] = SK_TAS[0]*(P[18][4]*SH_TAS[2] - P[18][22]*SH_TAS[2] + P[18][5]*SK_TAS[1] - P[18][23]*SK_TAS[1] + P[18][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[19] = SK_TAS[0]*(P[19][4]*SH_TAS[2] - P[19][22]*SH_TAS[2] + P[19][5]*SK_TAS[1] - P[19][23]*SK_TAS[1] + P[19][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[20] = SK_TAS[0]*(P[20][4]*SH_TAS[2] - P[20][22]*SH_TAS[2] + P[20][5]*SK_TAS[1] - P[20][23]*SK_TAS[1] + P[20][6]*vd*SH_TAS[0]);\n\t\t\tKfusion[21] = SK_TAS[0]*(P[21][4]*SH_TAS[2] - P[21][22]*SH_TAS[2] + P[21][5]*SK_TAS[1] - P[21][23]*SK_TAS[1] + P[21][6]*vd*SH_TAS[0]);\n\t\t}\n\t\tKfusion[22] = SK_TAS[0]*(P[22][4]*SH_TAS[2] - P[22][22]*SH_TAS[2] + P[22][5]*SK_TAS[1] - P[22][23]*SK_TAS[1] + P[22][6]*vd*SH_TAS[0]);\n\t\tKfusion[23] = SK_TAS[0]*(P[23][4]*SH_TAS[2] - P[23][22]*SH_TAS[2] + P[23][5]*SK_TAS[1] - P[23][23]*SK_TAS[1] + P[23][6]*vd*SH_TAS[0]);\n\n\n\t\t\/\/ Calculate measurement innovation\n\t\t_airspeed_innov = v_tas_pred -\n\t\t\t\t  _airspeed_sample_delayed.true_airspeed;\n\n\t\t\/\/ Calculate the innovation variance\n\t\t_airspeed_innov_var = 1.0f \/ SK_TAS[0];\n\n\t\t\/\/ Compute the ratio of innovation to gate size\n\t\t_tas_test_ratio = sq(_airspeed_innov) \/ (sq(fmaxf(_params.tas_innov_gate, 1.0f)) * _airspeed_innov_var);\n\n\t\t\/\/ If the innovation consistency check fails then don't fuse the sample and indicate bad airspeed health\n\t\tif (_tas_test_ratio > 1.0f) {\n\t\t\t_innov_check_fail_status.flags.reject_airspeed = true;\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\t_innov_check_fail_status.flags.reject_airspeed = false;\n\t\t}\n\n\t\t\/\/ Airspeed measurement sample has passed check so record it\n\t\t_time_last_arsp_fuse = _time_last_imu;\n\n\t\t\/\/ apply covariance correction via P_new = (I -K*H)*P\n\t\t\/\/ first calculate expression for KHP\n\t\t\/\/ then calculate P - KHP\n\t\tfloat KHP[_k_num_states][_k_num_states];\n\t\tfloat KH[5];\n\t\tfor (unsigned row = 0; row < _k_num_states; row++) {\n\n\t\t\tKH[0] = Kfusion[row] * H_TAS[4];\n\t\t\tKH[1] = Kfusion[row] * H_TAS[5];\n\t\t\tKH[2] = Kfusion[row] * H_TAS[6];\n\t\t\tKH[3] = Kfusion[row] * H_TAS[22];\n\t\t\tKH[4] = Kfusion[row] * H_TAS[23];\n\n\t\t\tfor (unsigned column = 0; column < _k_num_states; column++) {\n\t\t\t\tfloat tmp = KH[0] * P[4][column];\n\t\t\t\ttmp += KH[1] * P[5][column];\n\t\t\t\ttmp += KH[2] * P[6][column];\n\t\t\t\ttmp += KH[3] * P[22][column];\n\t\t\t\ttmp += KH[4] * P[23][column];\n\t\t\t\tKHP[row][column] = tmp;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ if the covariance correction will result in a negative variance, then\n\t\t\/\/ the covariance marix is unhealthy and must be corrected\n\t\tbool healthy = true;\n\t\t_fault_status.flags.bad_airspeed = false;\n\t\tfor (int i = 0; i < _k_num_states; i++) {\n\t\t\tif (P[i][i] < KHP[i][i]) {\n\t\t\t\t\/\/ zero rows and columns\n\t\t\t\tzeroRows(P,i,i);\n\t\t\t\tzeroCols(P,i,i);\n\n\t\t\t\t\/\/flag as unhealthy\n\t\t\t\thealthy = false;\n\n\t\t\t\t\/\/ update individual measurement health status\n\t\t\t\t_fault_status.flags.bad_airspeed = true;\n\n\t\t\t}\n\t\t}\n\n\t\t\/\/ only apply covariance and state corrrections if healthy\n\t\tif (healthy) {\n\t\t\t\/\/ apply the covariance corrections\n\t\t\tfor (unsigned row = 0; row < _k_num_states; row++) {\n\t\t\t\tfor (unsigned column = 0; column < _k_num_states; column++) {\n\t\t\t\t\tP[row][column] = P[row][column] - KHP[row][column];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ correct the covariance marix for gross errors\n\t\t\tfixCovarianceErrors();\n\n\t\t\t\/\/ apply the state corrections\n\t\t\tfuse(Kfusion, _airspeed_innov);\n\n\t\t}\n\t}\n}\n\nvoid Ekf::get_wind_velocity(float *wind)\n{\n\twind[0] = _state.wind_vel(0);\n\twind[1] = _state.wind_vel(1);\n}\n\n\/*\n * Reset the wind states using the current airspeed measurement, ground relative nav velocity, yaw angle and assumption of zero sideslip\n*\/\nvoid Ekf::resetWindStates()\n{\n\t\/\/ get euler yaw angle\n\tEulerf euler321(_state.quat_nominal);\n\tfloat euler_yaw = euler321(2);\n\n\tif (_tas_data_ready && (_imu_sample_delayed.time_us - _airspeed_sample_delayed.time_us < 5e5)) {\n\t\t\/\/ estimate wind using zero sideslip assumption and airspeed measurement if airspeed available\n\t\t_state.wind_vel(0) = _state.vel(0) - _airspeed_sample_delayed.true_airspeed * cosf(euler_yaw);\n\t\t_state.wind_vel(1) = _state.vel(1) - _airspeed_sample_delayed.true_airspeed * sinf(euler_yaw);\n\n\t} else {\n\t\t\/\/ If we don't have an airspeed measurement, then assume the wind is zero\n\t\t_state.wind_vel(0) = 0.0f;\n\t\t_state.wind_vel(1) = 0.0f;\n\t}\n}\n","avg_line_length":47.5322580645,"max_line_length":641,"alphanum_fraction":0.6364947404,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1181,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2338.0,"content":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <string>\n\n\/\/ template<> struct char_traits<wchar_t>\n\n\/\/ typedef wchar_t   char_type;\n\/\/ typedef int       int_type;\n\/\/ typedef streamoff off_type;\n\/\/ typedef streampos pos_type;\n\/\/ typedef mbstate_t state_type;\n\n#include <string>\n#include <type_traits>\n\n#include \"test_macros.h\"\n\nint main(int, char**)\n{\n    static_assert((std::is_same<std::char_traits<wchar_t>::char_type, wchar_t>::value), \"\");\n    static_assert((std::is_same<std::char_traits<wchar_t>::int_type, std::wint_t>::value), \"\");\n    static_assert((std::is_same<std::char_traits<wchar_t>::off_type, std::streamoff>::value), \"\");\n    static_assert((std::is_same<std::char_traits<wchar_t>::pos_type, std::wstreampos>::value), \"\");\n    static_assert((std::is_same<std::char_traits<wchar_t>::state_type, std::mbstate_t>::value), \"\");\n\n  return 0;\n}\n","avg_line_length":34.7352941176,"max_line_length":100,"alphanum_fraction":0.6088060965,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2422,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":8.0,"content":"\/* test2048.Signal.cpp *\/\n\/\/----------------------------------------------------------------------------------------\n\/\/\n\/\/  Project: CCore 2.00\n\/\/\n\/\/  Tag: Fundamental\n\/\/\n\/\/  License: Boost Software License - Version 1.0 - August 17th, 2003\n\/\/\n\/\/            see http:\/\/www.boost.org\/LICENSE_1_0.txt or the local copy\n\/\/\n\/\/  Copyright (c) 2015 Sergey Strukov. All rights reserved.\n\/\/\n\/\/----------------------------------------------------------------------------------------\n\n#include <CCore\/test\/test.h>\n\n#include <CCore\/inc\/Signal.h>\n\nnamespace App {\n\nnamespace Private_2048 {\n\n\/* struct Test *\/\n\nstruct Test\n {\n  int num;\n\n  explicit Test(int num_) : num(num_),connector(this,&Test::test) {}\n\n  virtual void test(int x)\n   {\n    Printf(Con,\"Test(#;).test(#;)\\n\",num,x);\n\n    if( x==num ) connector.disconnect();\n   }\n\n  SignalConnector<Test,int> connector;\n };\n\n\/* struct Test2 *\/\n\nstruct Test2 : Test\n {\n  Test *obj;\n\n  explicit Test2(int num,Test *obj_) : Test(num),obj(obj_) {}\n\n  void test(int x) override\n   {\n    Printf(Con,\"Test2(#;).test(#;)\\n\",num,x);\n\n    if( x==obj->num ) obj->connector.disconnect();\n   }\n };\n\n\/* test1() *\/\n\nvoid test1()\n {\n  Signal<int> signal;\n\n  Test test1(1);\n\n  {\n   Test test2(2);\n\n   test1.connector.connect(signal);\n\n   signal.assert(100);\n\n   test2.connector.connect(signal);\n\n   signal.assert(200);\n\n   {\n    Test2 test3(3,&test2);\n\n    test3.connector.connect(signal);\n\n    signal.assert(2);\n    signal.assert(2);\n   }\n  }\n\n  signal.assert(300);\n }\n\n\/* struct TestIf *\/\n\nstruct TestIf\n {\n  virtual void test(int x)=0;\n };\n\n\/* struct Test3 *\/\n\nstruct Test3 : TestIf\n {\n  int num;\n\n  explicit Test3(int num_) : num(num_),connector(this) {}\n\n  void test(int x)\n   {\n    Printf(Con,\"Test3(#;).test(#;)\\n\",num,x);\n   }\n\n  SignalInterfaceConnector<TestIf> connector;\n };\n\n\/* test2() *\/\n\nvoid test2()\n {\n  SignalInterface<TestIf> signal;\n\n  Test3 test1(1);\n\n  {\n   Test3 test2(2);\n\n   test1.connector.connect(signal);\n\n   signal.assert( [] (TestIf &obj) { obj.test(100); } );\n\n   test2.connector.connect(signal);\n\n   signal.assert( [] (TestIf &obj) { obj.test(200); } );\n  }\n\n  signal.assert( [] (TestIf &obj) { obj.test(300); } );\n }\n\n} \/\/ namespace Private_2048\n\nusing namespace Private_2048;\n\n\/* Testit<2048> *\/\n\ntemplate<>\nconst char *const Testit<2048>::Name=\"Test2048 Signal\";\n\ntemplate<>\nbool Testit<2048>::Main()\n {\n  test1();\n  test2();\n\n  return true;\n }\n\n} \/\/ namespace App\n\n","avg_line_length":15.5256410256,"max_line_length":90,"alphanum_fraction":0.5631709331,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6455,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/**\n * \\file example\/device_io.cpp\n * MegEngine is Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\/\n\n#include <thread>\n#include \"..\/example.h\"\n#if LITE_BUILD_WITH_MGE\n\nusing namespace lite;\nusing namespace example;\n\n#if LITE_WITH_CUDA\n\nbool lite::example::device_input(const Args& args) {\n    std::string network_path = args.model_path;\n    std::string input_path = args.input_path;\n\n    \/\/! config the network running in CUDA device\n    lite::Config config{LiteDeviceType::LITE_CUDA};\n\n    \/\/! set NetworkIO\n    NetworkIO network_io;\n    std::string input_name = \"data\";\n    bool is_host = false;\n    IO device_input{input_name, is_host};\n    network_io.inputs.push_back(device_input);\n\n    \/\/! create and load the network\n    std::shared_ptr<Network> network =\n            std::make_shared<Network>(config, network_io);\n    network->load_model(network_path);\n\n    std::shared_ptr<Tensor> input_tensor = network->get_input_tensor(0);\n    Layout input_layout = input_tensor->get_layout();\n\n    \/\/! read data from numpy data file\n    auto src_tensor = parse_npy(input_path);\n\n    \/\/! malloc the device memory\n    auto tensor_device = Tensor(LiteDeviceType::LITE_CUDA, input_layout);\n\n    \/\/! copy to the device memory\n    tensor_device.copy_from(*src_tensor);\n\n    \/\/! Now the device memory if filled with user input data, set it to the\n    \/\/! input tensor\n    input_tensor->reset(tensor_device.get_memory_ptr(), input_layout);\n\n    \/\/! forward\n    network->forward();\n    network->wait();\n\n    \/\/! get the output data or read tensor set in network_in\n    std::shared_ptr<Tensor> output_tensor = network->get_output_tensor(0);\n    void* out_data = output_tensor->get_memory_ptr();\n    size_t out_length = output_tensor->get_tensor_total_size_in_byte() \/\n                        output_tensor->get_layout().get_elem_size();\n    float max = -1.0f;\n    float sum = 0.0f;\n    for (size_t i = 0; i < out_length; i++) {\n        float data = static_cast<float*>(out_data)[i];\n        sum += data;\n        if (max < data)\n            max = data;\n    }\n    printf(\"max=%e, sum=%e\\n\", max, sum);\n    return true;\n}\n\nbool lite::example::device_input_output(const Args& args) {\n    std::string network_path = args.model_path;\n    std::string input_path = args.input_path;\n\n    \/\/! config the network running in CUDA device\n    lite::Config config{LiteDeviceType::LITE_CUDA};\n\n    \/\/! set NetworkIO include input and output\n    NetworkIO network_io;\n    std::string input_name = \"data\";\n    std::string output_name = \"TRUE_DIV(EXP[12065],reduce0[12067])[12077]\";\n    bool is_host = false;\n    IO device_input{input_name, is_host};\n    IO device_output{output_name, is_host};\n    network_io.inputs.push_back(device_input);\n    network_io.outputs.push_back(device_output);\n\n    \/\/! create and load the network\n    std::shared_ptr<Network> network =\n            std::make_shared<Network>(config, network_io);\n    network->load_model(network_path);\n\n    std::shared_ptr<Tensor> input_tensor_device = network->get_input_tensor(0);\n    Layout input_layout = input_tensor_device->get_layout();\n\n    \/\/! read data from numpy data file\n    auto src_tensor = parse_npy(input_path);\n\n    \/\/! malloc the device memory\n    auto tensor_device = Tensor(LiteDeviceType::LITE_CUDA, input_layout);\n\n    \/\/! copy to the device memory\n    tensor_device.copy_from(*src_tensor);\n\n    \/\/! Now the device memory is filled with user input data, set it to the\n    \/\/! input tensor\n    input_tensor_device->reset(tensor_device.get_memory_ptr(), input_layout);\n\n    \/\/! forward\n    network->forward();\n    network->wait();\n\n    \/\/! output is in device, should copy it to host\n    std::shared_ptr<Tensor> output_tensor_device =\n            network->get_io_tensor(output_name);\n\n    auto output_tensor = std::make_shared<Tensor>();\n    output_tensor->copy_from(*output_tensor_device);\n\n    \/\/! get the output data or read tensor set in network_in\n    void* out_data = output_tensor->get_memory_ptr();\n    size_t out_length = output_tensor->get_tensor_total_size_in_byte() \/\n                        output_tensor->get_layout().get_elem_size();\n    float max = -1.0f;\n    float sum = 0.0f;\n    for (size_t i = 0; i < out_length; i++) {\n        float data = static_cast<float*>(out_data)[i];\n        sum += data;\n        if (max < data)\n            max = data;\n    }\n    printf(\"max=%e, sum=%e\\n\", max, sum);\n    return true;\n}\n\nbool lite::example::pinned_host_input(const Args& args) {\n    std::string network_path = args.model_path;\n    std::string input_path = args.input_path;\n\n    \/\/! config the network running in CUDA device\n    lite::Config config{LiteDeviceType::LITE_CUDA};\n\n    \/\/! create and load the network\n    std::shared_ptr<Network> network = std::make_shared<Network>(config);\n    network->load_model(network_path);\n\n    std::shared_ptr<Tensor> input_tensor = network->get_input_tensor(0);\n    Layout input_layout = input_tensor->get_layout();\n\n    \/\/! read data from numpy data file\n    auto src_tensor = parse_npy(input_path);\n    \/\/! malloc the pinned host memory\n    bool is_pinned_host = true;\n    auto tensor_pinned_input =\n            Tensor(LiteDeviceType::LITE_CUDA, input_layout, is_pinned_host);\n    \/\/! copy to the pinned memory\n    tensor_pinned_input.copy_from(*src_tensor);\n    \/\/! set the pinned host memory to the network as input\n    input_tensor->reset(tensor_pinned_input.get_memory_ptr(), input_layout);\n\n    \/\/! forward\n    network->forward();\n    network->wait();\n\n    \/\/! get the output data or read tensor set in network_in\n    std::shared_ptr<Tensor> output_tensor = network->get_output_tensor(0);\n    void* out_data = output_tensor->get_memory_ptr();\n    size_t out_length = output_tensor->get_tensor_total_size_in_byte() \/\n                        output_tensor->get_layout().get_elem_size();\n    float max = -1.0f;\n    float sum = 0.0f;\n    for (size_t i = 0; i < out_length; i++) {\n        float data = static_cast<float*>(out_data)[i];\n        sum += data;\n        if (max < data)\n            max = data;\n    }\n    printf(\"max=%e, sum=%e\\n\", max, sum);\n    return true;\n}\n\n#endif\n#endif\n\n\/\/ vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}\n","avg_line_length":33.6197916667,"max_line_length":89,"alphanum_fraction":0.6759101472,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":252,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\r\n#include \"CTypedSceneNodeManager.impl.h\"\r\n#include \"singleton.impl.h\"\r\n\r\n#include \"CSceneNodeInteriorDef.decl.h\"\r\ntemplate class CTypedSceneNodeManager<CSceneNodeInteriorDef>;\r\ntemplate CTypedSceneNodeManager<CSceneNodeInteriorDef> *GetSingleton();\r\n","avg_line_length":31.5,"max_line_length":72,"alphanum_fraction":0.8214285714,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":153,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":1.0,"content":"\/\/ License: The Unlicense (https:\/\/unlicense.org)\n#include <iostream>\n\nauto main() -> int {\n   std::cout << \"Hello, world!\" << std::endl;\n   return 0;\n}\n","avg_line_length":19.125,"max_line_length":49,"alphanum_fraction":0.6078431373,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":17573,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-3.0","MIT"],"max_stars_count":24.0,"content":"\n\/**********************************************************************\n\n  Audacity: A Digital Audio Editor\n\n  AColor.cpp\n\n  Dominic Mazzoni\n\n\n********************************************************************\/\/**\n\n\\class AColor\n\\brief AColor Manages color brushes and pens\n\nIt is also a place to document colour usage policy in Audacity\n\n*\/\/********************************************************************\/\n\n#include <wx\/colour.h>\n#include <wx\/dc.h>\n#include <wx\/settings.h>\n#include <wx\/utils.h>\n\n#include \"AColor.h\"\n#include \"Theme.h\"\n#include \"Experimental.h\"\n#include \"AllThemeResources.h\"\n\nbool AColor::inited = false;\nwxBrush AColor::lightBrush[2];\nwxBrush AColor::mediumBrush[2];\nwxBrush AColor::darkBrush[2];\nwxPen AColor::lightPen[2];\nwxPen AColor::mediumPen[2];\nwxPen AColor::darkPen[2];\n\nwxPen AColor::cursorPen;\nwxBrush AColor::indicatorBrush[2];\nwxPen AColor::indicatorPen[2];\nwxPen AColor::playRegionPen[2];\nwxBrush AColor::playRegionBrush[2];\n\nwxBrush AColor::muteBrush[2];\nwxBrush AColor::soloBrush;\n\nwxPen AColor::clippingPen;\n\nwxBrush AColor::envelopeBrush;\nwxPen AColor::envelopePen;\nwxPen AColor::WideEnvelopePen;\n\nwxBrush AColor::labelTextNormalBrush;\nwxBrush AColor::labelTextEditBrush;\nwxBrush AColor::labelUnselectedBrush;\nwxBrush AColor::labelSelectedBrush;\nwxBrush AColor::labelSyncLockSelBrush;\nwxPen AColor::labelUnselectedPen;\nwxPen AColor::labelSelectedPen;\nwxPen AColor::labelSyncLockSelPen;\nwxPen AColor::labelSurroundPen;\nwxPen AColor::trackFocusPens[3];\nwxPen AColor::snapGuidePen;\n\nwxBrush AColor::tooltipBrush;\n\n\/\/ The spare pen and brush possibly help us cut down on the\n\/\/ number of pens and brushes we need.\nwxPen AColor::sparePen;\nwxBrush AColor::spareBrush;\n\n\/\/\n\/\/ Draw an upward or downward pointing arrow.\n\/\/\nvoid AColor::Arrow(wxDC & dc, wxCoord x, wxCoord y, int width, bool down)\n{\n   if (width & 0x01) {\n      width--;\n   }\n\n   wxPoint pt[3];\n   int half = width \/ 2;\n\n   if (down) {\n      pt[0].x =     0; pt[0].y = 0;\n      pt[1].x = width; pt[1].y = 0;\n      pt[2].x =  half; pt[2].y = half;\n   }\n   else {\n      pt[0].x =     0; pt[0].y = half;\n      pt[1].x =  half; pt[1].y = 0;\n      pt[2].x = width; pt[2].y = half;\n   }\n\n   dc.DrawPolygon(3, pt, x, y);\n}\n\n\/\/\n\/\/ Draw a line while accounting for differences in wxWidgets versions\n\/\/\nvoid AColor::Line(wxDC & dc, wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2)\n{\n   \/\/ As of 2.8.9 (possibly earlier), wxDC::DrawLine() on the Mac draws the\n   \/\/ last point since it is now based on the new wxGraphicsContext system.\n   \/\/ Make the other platforms do the same thing since the other platforms\n   \/\/ \"may\" follow they get wxGraphicsContext going.\n#if defined(__WXMAC__)\n   dc.DrawLine(x1, y1, x2, y2);\n#else\n   bool point = false;\n\n   if (x1 == x2) {\n      if (y1 < y2) {\n         y2++;\n      }\n      else if (y2 < y1) {\n         y1++;\n      }\n      else {\n         point = true;\n      }\n   }\n   else if (y1 == y2) {\n      if (x1 < x2) {\n         x2++;\n      }\n      else if (x2 < x1) {\n         x1++;\n      }\n      else {\n         point = true;\n      }\n   }\n   else {\n      dc.DrawPoint(x2, y2);\n   }\n\n   if (point) {\n      dc.DrawPoint(x2, y2);\n   }\n   else {\n      dc.DrawLine(x1, y1, x2, y2);\n   }\n#endif\n}\n\n\/\/\n\/\/ Draws a focus rectangle (Taken directly from wxWidgets source)\n\/\/\nvoid AColor::DrawFocus(wxDC & dc, wxRect & rect)\n{\n   \/\/ draw the pixels manually: note that to behave in the same manner as\n   \/\/ DrawRect(), we must exclude the bottom and right borders from the\n   \/\/ rectangle\n   wxCoord x1 = rect.GetLeft(),\n         y1 = rect.GetTop(),\n         x2 = rect.GetRight(),\n         y2 = rect.GetBottom();\n\n   dc.SetPen(wxPen(wxT(\"MEDIUM GREY\"), 0, wxSOLID));\n\n   \/\/ this seems to be closer than what Windows does than wxINVERT although\n   \/\/ I'm still not sure if it's correct\n   dc.SetLogicalFunction(wxAND_REVERSE);\n\n   wxCoord z;\n   for ( z = x1 + 1; z < x2; z += 2 )\n      dc.DrawPoint(z, y1);\n\n   wxCoord shift = z == x2 ? 0 : 1;\n   for ( z = y1 + shift; z < y2; z += 2 )\n      dc.DrawPoint(x2, z);\n\n   shift = z == y2 ? 0 : 1;\n   for ( z = x2 - shift; z > x1; z -= 2 )\n      dc.DrawPoint(z, y2);\n\n   shift = z == x1 ? 0 : 1;\n   for ( z = y2 - shift; z > y1; z -= 2 )\n      dc.DrawPoint(x1, z);\n\n   dc.SetLogicalFunction(wxCOPY);\n}\n\nvoid AColor::Bevel(wxDC & dc, bool up, wxRect & r)\n{\n   if (up)\n      AColor::Light(&dc, false);\n   else\n      AColor::Dark(&dc, false);\n\n   AColor::Line(dc, r.x, r.y, r.x + r.width, r.y);\n   AColor::Line(dc, r.x, r.y, r.x, r.y + r.height);\n\n   if (!up)\n      AColor::Light(&dc, false);\n   else\n      AColor::Dark(&dc, false);\n\n   AColor::Line(dc, r.x + r.width, r.y, r.x + r.width, r.y + r.height);\n   AColor::Line(dc, r.x, r.y + r.height, r.x + r.width, r.y + r.height);\n}\n\nwxColour AColor::Blend( const wxColour & c1, const wxColour & c2 )\n{\n   wxColour c3(\n      (c1.Red() + c2.Red())\/2,\n      (c1.Green() + c2.Green())\/2,\n      (c1.Blue() + c2.Blue())\/2);\n   return c3;\n}\n\nvoid AColor::BevelTrackInfo(wxDC & dc, bool up, wxRect & r)\n{\n#ifndef EXPERIMENTAL_THEMING\n   Bevel( dc, up, r );\n#else\n   wxColour col;\n   col = Blend( theTheme.Colour( clrTrackInfo ), up ? wxColour( 255,255,255):wxColour(0,0,0));\n\n   wxPen pen( col );\n   dc.SetPen( pen );\n\n   dc.DrawLine(r.x, r.y, r.x + r.width, r.y);\n   dc.DrawLine(r.x, r.y, r.x, r.y + r.height);\n\n   col = Blend( theTheme.Colour( clrTrackInfo ), up ? wxColour(0,0,0): wxColour(255,255,255));\n\n   pen.SetColour( col );\n   dc.SetPen( pen );\n\n   dc.DrawLine(r.x + r.width, r.y, r.x + r.width, r.y + r.height);\n   dc.DrawLine(r.x, r.y + r.height, r.x + r.width + 1, r.y + r.height);\n#endif\n}\n\nvoid AColor::UseThemeColour( wxDC * dc, int iIndex )\n{\n   if (!inited)\n      Init();\n   wxColour col = theTheme.Colour( iIndex );\n   spareBrush.SetColour( col );\n   dc->SetBrush( spareBrush );\n   sparePen.SetColour( col );\n   dc->SetPen( sparePen );\n}\n\nvoid AColor::Light(wxDC * dc, bool selected)\n{\n   if (!inited)\n      Init();\n   int index = (int) selected;\n   dc->SetBrush(lightBrush[index]);\n   dc->SetPen(lightPen[index]);\n}\n\nvoid AColor::Medium(wxDC * dc, bool selected)\n{\n   if (!inited)\n      Init();\n   int index = (int) selected;\n   dc->SetBrush(mediumBrush[index]);\n   dc->SetPen(mediumPen[index]);\n}\n\n#if 0\n#ifdef EXPERIMENTAL_THEMING\n   UseThemeColour( dc, selected ? clrMediumSelected : clrMedium);\n#endif\n#ifdef EXPERIMENTAL_THEMING\n   UseThemeColour( dc, selected ? clrLightSelected : clrLight);\n#endif\n#endif\n\nvoid AColor::MediumTrackInfo(wxDC * dc, bool selected)\n{\n#ifdef EXPERIMENTAL_THEMING\n   UseThemeColour( dc, selected ? clrTrackInfoSelected : clrTrackInfo );\n#else\n   Medium( dc, selected );\n#endif\n}\n\n\nvoid AColor::Dark(wxDC * dc, bool selected)\n{\n   if (!inited)\n      Init();\n   int index = (int) selected;\n   dc->SetBrush(darkBrush[index]);\n   dc->SetPen(darkPen[index]);\n}\n\nvoid AColor::TrackPanelBackground(wxDC * dc, bool selected)\n{\n#ifdef EXPERIMENTAL_THEMING\n   UseThemeColour( dc, selected ? clrDarkSelected : clrDark);\n#else\n   Dark( dc, selected );\n#endif\n}\n\n\nvoid AColor::CursorColor(wxDC * dc)\n{\n   if (!inited)\n      Init();\n   dc->SetLogicalFunction(wxINVERT);\n   dc->SetPen(cursorPen);\n}\n\nvoid AColor::IndicatorColor(wxDC * dc, bool bIsNotRecording)\n{\n   if (!inited)\n      Init();\n   int index = (int) bIsNotRecording;\n   dc->SetPen(indicatorPen[index]);\n   dc->SetBrush(indicatorBrush[index]);\n}\n\nvoid AColor::PlayRegionColor(wxDC * dc, bool locked)\n{\n   if (!inited)\n      Init();\n   dc->SetPen(playRegionPen[(int)locked]);\n   dc->SetBrush(playRegionBrush[(int)locked]);\n}\n\nvoid AColor::TrackFocusPen(wxDC * dc, int level)\n{\n   if (!inited)\n      Init();\n   dc->SetPen(trackFocusPens[level]);\n}\n\nvoid AColor::SnapGuidePen(wxDC * dc)\n{\n   if (!inited)\n      Init();\n   dc->SetPen(snapGuidePen);\n}\n\nvoid AColor::Mute(wxDC * dc, bool on, bool selected, bool soloing)\n{\n   if (!inited)\n      Init();\n   int index = (int) selected;\n   if (on) {\n      dc->SetPen(*wxBLACK_PEN);\n      dc->SetBrush(muteBrush[(int) soloing]);\n   }\n   else {\n      dc->SetPen(*wxTRANSPARENT_PEN);\n      dc->SetBrush(mediumBrush[index]);\n   }\n}\n\nvoid AColor::Solo(wxDC * dc, bool on, bool selected)\n{\n   if (!inited)\n      Init();\n   int index = (int) selected;\n   if (on) {\n      dc->SetPen(*wxBLACK_PEN);\n      dc->SetBrush(soloBrush);\n   }\n   else {\n      dc->SetPen(*wxTRANSPARENT_PEN);\n      dc->SetBrush(mediumBrush[index]);\n   }\n}\n\nvoid AColor::ReInit()\n{\n   inited=false;\n   Init();\n}\n\nvoid AColor::Init()\n{\n   if (inited)\n      return;\n\n   wxColour light =\n       wxSystemSettings::GetColour(wxSYS_COLOUR_3DHIGHLIGHT);\n   wxColour med = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE);\n   wxColour dark =\n       wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW);\n\n   clippingPen.SetColour(0xCC, 0x11, 0x00);\n\n   theTheme.SetPenColour(   envelopePen,     clrEnvelope );\n   theTheme.SetPenColour(   WideEnvelopePen, clrEnvelope );\n   theTheme.SetBrushColour( envelopeBrush,   clrEnvelope );\n\n   WideEnvelopePen.SetWidth( 3 );\n\n   theTheme.SetBrushColour( labelTextNormalBrush,  clrLabelTextNormalBrush );\n   theTheme.SetBrushColour( labelTextEditBrush,    clrLabelTextEditBrush );\n   theTheme.SetBrushColour( labelUnselectedBrush,  clrLabelUnselectedBrush );\n   theTheme.SetBrushColour( labelSelectedBrush,    clrLabelSelectedBrush );\n   theTheme.SetBrushColour( labelSyncLockSelBrush, clrSyncLockSel );\n   theTheme.SetPenColour( labelUnselectedPen,   clrLabelUnselectedPen );\n   theTheme.SetPenColour( labelSelectedPen,     clrLabelSelectedPen );\n   theTheme.SetPenColour( labelSyncLockSelPen,  clrSyncLockSel );\n   theTheme.SetPenColour( labelSurroundPen,     clrLabelSurroundPen );\n\n   \/\/ These colors were modified to avoid using reserved colors red and green\n   \/\/ for the buttons.\n   theTheme.SetBrushColour( muteBrush[0],      clrMuteButtonActive);\n   theTheme.SetBrushColour( muteBrush[1],      clrMuteButtonVetoed);\n   theTheme.SetBrushColour( soloBrush,         clrMuteButtonActive);\n\n   theTheme.SetPenColour(   cursorPen,         clrCursorPen);\n   theTheme.SetPenColour(   indicatorPen[0],   clrRecordingPen);\n   theTheme.SetPenColour(   indicatorPen[1],   clrPlaybackPen);\n   theTheme.SetBrushColour( indicatorBrush[0], clrRecordingBrush);\n   theTheme.SetBrushColour( indicatorBrush[1], clrPlaybackBrush);\n\n   theTheme.SetBrushColour( playRegionBrush[0],clrRulerRecordingBrush);\n   theTheme.SetPenColour(   playRegionPen[0],  clrRulerRecordingPen);\n   theTheme.SetBrushColour( playRegionBrush[1],clrRulerPlaybackBrush);\n   theTheme.SetPenColour(   playRegionPen[1],  clrRulerPlaybackPen);\n\n   \/\/Determine tooltip color\n   tooltipBrush.SetColour( wxSystemSettingsNative::GetColour(wxSYS_COLOUR_INFOBK) );\n\n   \/\/ A tiny gradient of yellow surrounding the current focused track\n   theTheme.SetPenColour(   trackFocusPens[0],  clrTrackFocus0);\n   theTheme.SetPenColour(   trackFocusPens[1],  clrTrackFocus1);\n   theTheme.SetPenColour(   trackFocusPens[2],  clrTrackFocus2);\n\n   \/\/ A vertical line indicating that the selection or sliding has\n   \/\/ been snapped to the nearest boundary.\n   theTheme.SetPenColour(   snapGuidePen,      clrSnapGuide);\n\n#if defined(__WXMSW__) || defined(__WXGTK__)\n   \/\/ unselected\n   lightBrush[0].SetColour(light);\n   mediumBrush[0].SetColour(med);\n   darkBrush[0].SetColour(dark);\n   lightPen[0].SetColour(light);\n   mediumPen[0].SetColour(med);\n   darkPen[0].SetColour(dark);\n\n   \/\/ selected\n   lightBrush[1].SetColour(204, 204, 255);\n   mediumBrush[1].SetColour(200, 200, 214);\n   darkBrush[1].SetColour(148, 148, 170);\n   lightPen[1].SetColour(204, 204, 255);\n   mediumPen[1].SetColour(200, 200, 214);\n   darkPen[1].SetColour(0, 0, 0);\n\n#else\n\n#if defined(__WXMAC__)          \/\/ && defined(TARGET_CARBON)\n\n   \/\/ unselected\n   lightBrush[0].SetColour(246, 246, 255);\n   mediumBrush[0].SetColour(220, 220, 220);\n   darkBrush[0].SetColour(140, 140, 160);\n   lightPen[0].SetColour(246, 246, 255);\n   mediumPen[0].SetColour(220, 220, 220);\n   darkPen[0].SetColour(140, 140, 160);\n\n   \/\/ selected\n   lightBrush[1].SetColour(204, 204, 255);\n   mediumBrush[1].SetColour(180, 180, 192);\n   darkBrush[1].SetColour(148, 148, 170);\n   lightPen[1].SetColour(204, 204, 255);\n   mediumPen[1].SetColour(180, 180, 192);\n   darkPen[1].SetColour(148, 148, 170);\n\n#else\n\n   \/\/ unselected\n   lightBrush[0].SetColour(255, 255, 255);\n   mediumBrush[0].SetColour(204, 204, 204);\n   darkBrush[0].SetColour(130, 130, 130);\n   lightPen[0].SetColour(255, 255, 255);\n   mediumPen[0].SetColour(204, 204, 204);\n   darkPen[0].SetColour(130, 130, 130);\n\n   \/\/ selected\n   lightBrush[1].SetColour(204, 204, 255);\n   mediumBrush[1].SetColour(180, 180, 192);\n   darkBrush[1].SetColour(148, 148, 170);\n   lightPen[1].SetColour(204, 204, 255);\n   mediumPen[1].SetColour(180, 180, 192);\n   darkPen[1].SetColour(0, 0, 0);\n\n#endif\n\n#endif\n\n   inited = true;\n}\n\nconst int AColor_midicolors[16][3] = {\n   {255, 102, 102},             \/\/ 1=salmon\n   {204, 0, 0},                 \/\/ 2=red\n   {255, 117, 23},              \/\/ 3=orange\n   {255, 255, 0},               \/\/ 4=yellow\n   {0, 204, 0},                 \/\/ 5=green\n   {0, 204, 204},               \/\/ 6=turquoise\n   {0, 0, 204},                 \/\/ 7=blue\n   {153, 0, 255},               \/\/ 8=blue-violet\n\n   {140, 97, 54},               \/\/ 9=brown\n   {120, 120, 120},             \/\/ 10=gray (drums)\n   {255, 175, 40},              \/\/ 11=lt orange\n   {102, 255, 102},             \/\/ 12=lt green\n   {153, 255, 255},             \/\/ 13=lt turquoise\n   {153, 153, 255},             \/\/ 14=lt blue\n   {204, 102, 255},             \/\/ 15=lt blue-violet\n   {255, 51, 204}\n};                              \/\/ 16=lt red-violet\n\nvoid AColor::MIDIChannel(wxDC * dc, int channel \/* 1 - 16 *\/ )\n{\n   if (channel >= 1 && channel <= 16) {\n      const int *colors = AColor_midicolors[channel - 1];\n\n      dc->SetPen(wxPen(wxColour(colors[0],\n                                colors[1], colors[2]), 1, wxSOLID));\n      dc->SetBrush(wxBrush(wxColour(colors[0],\n                                    colors[1], colors[2]), wxSOLID));\n   } else {\n      dc->SetPen(wxPen(wxColour(153, 153, 153), 1, wxSOLID));\/\/ DONT-THEME Midi, unused.\n      dc->SetBrush(wxBrush(wxColour(153, 153, 153), wxSOLID));\n   }\n\n}\n\nvoid AColor::LightMIDIChannel(wxDC * dc, int channel \/* 1 - 16 *\/ )\n{\n   if (channel >= 1 && channel <= 16) {\n      const int *colors = AColor_midicolors[channel - 1];\n\n      dc->SetPen(wxPen(wxColour(127 + colors[0] \/ 2,\n                                127 + colors[1] \/ 2,\n                                127 + colors[2] \/ 2), 1, wxSOLID));\n      dc->SetBrush(wxBrush(wxColour(127 + colors[0] \/ 2,\n                                    127 + colors[1] \/ 2,\n                                    127 + colors[2] \/ 2), wxSOLID));\n   } else {\n      dc->SetPen(wxPen(wxColour(204, 204, 204), 1, wxSOLID));\n      dc->SetBrush(wxBrush(wxColour(204, 204, 204), wxSOLID));\n   }\n\n}\n\nvoid AColor::DarkMIDIChannel(wxDC * dc, int channel \/* 1 - 16 *\/ )\n{\n   if (channel >= 1 && channel <= 16) {\n      const int *colors = AColor_midicolors[channel - 1];\n\n      dc->SetPen(wxPen(wxColour(colors[0] \/ 2,\n                                colors[1] \/ 2,\n                                colors[2] \/ 2), 1, wxSOLID));\n      dc->SetBrush(wxBrush(wxColour(colors[0] \/ 2,\n                                    colors[1] \/ 2,\n                                    colors[2] \/ 2), wxSOLID));\n   } else {\n      dc->SetPen(wxPen(wxColour(102, 102, 102), 1, wxSOLID));\n      dc->SetBrush(wxBrush(wxColour(102, 102, 102), wxSOLID));\n   }\n\n}\n\nbool AColor::gradient_inited = 0;\n\nunsigned char AColor::gradient_pre[2][2][gradientSteps][3];\n\nvoid AColor::PreComputeGradient() {\n   {\n      if (!gradient_inited) {\n         gradient_inited = 1;\n\n         for (int selected = 0; selected <= 1; selected++)\n            for (int grayscale = 0; grayscale <= 1; grayscale++) {\n               float r, g, b;\n\n               int i;\n               for (i=0; i<gradientSteps; i++) {\n                  float value = float(i)\/gradientSteps;\n\n                  if (grayscale) {\n                     r = g = b = 0.84 - 0.84 * value;\n                  } else {\n                     const int gsteps = 4;\n                     float gradient[gsteps + 1][3] = {\n                        {float(0.75), float(0.75), float(0.75)},    \/\/ lt gray\n                        {float(0.30), float(0.60), float(1.00)},    \/\/ lt blue\n                        {float(0.90), float(0.10), float(0.90)},    \/\/ violet\n                        {float(1.00), float(0.00), float(0.00)},    \/\/ red\n                        {float(1.00), float(1.00), float(1.00)}     \/\/ white\n                     };\n\n                     int left = int (value * gsteps);\n                     int right = (left == gsteps ? gsteps : left + 1);\n\n                     float rweight = (value * gsteps) - left;\n                     float lweight = 1.0 - rweight;\n\n                     r = (gradient[left][0] * lweight) + (gradient[right][0] * rweight);\n                     g = (gradient[left][1] * lweight) + (gradient[right][1] * rweight);\n                     b = (gradient[left][2] * lweight) + (gradient[right][2] * rweight);\n                  }\n\n                  if (selected) {\n                     r *= 0.77f;\n                     g *= 0.77f;\n                     b *= 0.885f;\n                  }\n                  gradient_pre[selected][grayscale][i][0] = (unsigned char) (255 * r);\n                  gradient_pre[selected][grayscale][i][1] = (unsigned char) (255 * g);\n                  gradient_pre[selected][grayscale][i][2] = (unsigned char) (255 * b);\n               }\n            }\n      }\n   }\n}\n","avg_line_length":28.1618589744,"max_line_length":94,"alphanum_fraction":0.5867524043,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":711,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":5.0,"content":"#include \"Core\/Tasks\/BaseTask.h\"\n#include \"Core\/ApplicationManager.h\"\n\nvoid TaskDataHolder::SetUserData(const QVariant& data)\n{\n    userData = data;\n}\n\nconst QVariant& TaskDataHolder::GetUserData() const\n{\n    return userData;\n}\n\nvoid ErrorHolder::SetError(const QString& error) const\n{\n    errorText = error;\n}\n\nQString ErrorHolder::GetError() const\n{\n    return errorText;\n}\n\nbool ErrorHolder::HasError() const\n{\n    return errorText.isEmpty() == false;\n}\n\nBaseTask::BaseTask(ApplicationManager* appManager_)\n    : appManager(appManager_)\n{\n}\n\nRunTask::RunTask(ApplicationManager* appManager)\n    : BaseTask(appManager)\n{\n}\n\nBaseTask::eTaskType RunTask::GetTaskType() const\n{\n    return BaseTask::RUN_TASK;\n}\n","avg_line_length":16.5348837209,"max_line_length":54,"alphanum_fraction":0.7285513361,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":9490,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/\n\/\/ Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n\/\/ SPDX-License-Identifier: MIT\n\/\/\n\n#include <boost\/test\/unit_test.hpp>\n#include <Graph.hpp>\n#include <SubgraphView.hpp>\n#include <SubgraphViewSelector.hpp>\n#include <armnn\/backends\/OptimizationViews.hpp>\n#include <Network.hpp>\n\n#include \"CommonTestUtils.hpp\"\n#include \"MockBackend.hpp\"\n\nusing namespace armnn;\n\nvoid CheckLayers(Graph& graph)\n{\n    unsigned int m_inputLayerCount = 0, m_outputLayerCount = 0, m_addLayerCount = 0;\n    for(auto layer : graph)\n    {\n        switch(layer->GetType())\n        {\n            case LayerType::Input:\n                ++m_inputLayerCount;\n                BOOST_TEST((layer->GetName() == std::string(\"inLayer0\") ||\n                            layer->GetName() == std::string(\"inLayer1\")));\n                break;\n            \/\/ The Addition layer should become a PreCompiled Layer after Optimisation\n            case LayerType::PreCompiled:\n                ++m_addLayerCount;\n                BOOST_TEST(layer->GetName() == \"pre-compiled\");\n                break;\n            case LayerType::Output:\n                ++m_outputLayerCount;\n                BOOST_TEST(layer->GetName() == \"outLayer\");\n                break;\n            default:\n                \/\/Fail for anything else\n                BOOST_TEST(false);\n        }\n    }\n    BOOST_TEST(m_inputLayerCount == 2);\n    BOOST_TEST(m_outputLayerCount == 1);\n    BOOST_TEST(m_addLayerCount == 1);\n}\n\nBOOST_AUTO_TEST_SUITE(OptimizationViewsTestSuite)\n\nBOOST_AUTO_TEST_CASE(OptimizedViewsSubgraphLayerCount)\n{\n    OptimizationViews view;\n    \/\/ Construct a graph with 3 layers\n    Graph& baseGraph = view.GetGraph();\n\n    Layer* const inputLayer = baseGraph.AddLayer<InputLayer>(0, \"input\");\n\n    Convolution2dDescriptor convDescriptor;\n    PreCompiledDescriptor substitutionLayerDescriptor(1, 1);\n    Layer* const convLayer1 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, \"conv1\");\n    Layer* const convLayer2 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, \"conv2\");\n    Layer* const substitutableCompiledLayer =\n            baseGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, \"pre-compiled\");\n\n    Layer* const outputLayer = baseGraph.AddLayer<OutputLayer>(0, \"output\");\n\n    inputLayer->GetOutputSlot(0).Connect(convLayer1->GetInputSlot(0));\n    convLayer1->GetOutputSlot(0).Connect(convLayer2->GetInputSlot(0));\n    convLayer2->GetOutputSlot(0).Connect(outputLayer->GetInputSlot(0));\n\n    \/\/ Subgraph for a failed layer\n    SubgraphViewSelector::SubgraphViewPtr failedSubgraph =\n        CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),\n                               CreateOutputsFrom({convLayer1}),\n                               {convLayer1});\n    \/\/ Subgraph for an untouched layer\n    SubgraphViewSelector::SubgraphViewPtr untouchedSubgraph =\n            CreateSubgraphViewFrom(CreateInputsFrom({convLayer2}),\n                                   CreateOutputsFrom({convLayer2}),\n                                   {convLayer2});\n    \/\/ Subgraph for a substitutable layer\n    SubgraphViewSelector::SubgraphViewPtr substitutableSubgraph =\n            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),\n                                   CreateOutputsFrom({convLayer2}),\n                                   {substitutableCompiledLayer});\n    \/\/ Create a Graph containing a layer to substitute in\n    Graph substitutableGraph;\n    Layer* const substitutionpreCompiledLayer =\n            substitutableGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, \"pre-compiled\");\n\n    \/\/ Subgraph for a substitution layer\n    SubgraphViewSelector::SubgraphViewPtr substitutionSubgraph =\n            CreateSubgraphViewFrom(CreateInputsFrom({substitutionpreCompiledLayer}),\n                                   CreateOutputsFrom({substitutionpreCompiledLayer}),\n                                   {substitutionpreCompiledLayer});\n\n    \/\/ Sub in the graph\n    baseGraph.SubstituteSubgraph(*substitutableSubgraph, *substitutionSubgraph);\n\n    view.AddFailedSubgraph(SubgraphView(*failedSubgraph));\n    view.AddUntouchedSubgraph(SubgraphView(*untouchedSubgraph));\n\n    SubgraphViewSelector::SubgraphViewPtr baseSubgraph =\n            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),\n                                   CreateOutputsFrom({convLayer2}),\n                                   {substitutionpreCompiledLayer});\n    view.AddSubstitution({*baseSubgraph, *substitutionSubgraph});\n\n    \/\/ Construct original subgraph to compare against\n    SubgraphViewSelector::SubgraphViewPtr originalSubgraph =\n            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),\n            CreateOutputsFrom({convLayer2}),\n            {convLayer1, convLayer2, substitutionpreCompiledLayer});\n\n    BOOST_CHECK(view.Validate(*originalSubgraph));\n}\n\nBOOST_AUTO_TEST_CASE(OptimizedViewsSubgraphLayerCountFailValidate)\n{\n    OptimizationViews view;\n    \/\/ Construct a graph with 3 layers\n    Graph& baseGraph = view.GetGraph();\n\n    Layer* const inputLayer = baseGraph.AddLayer<InputLayer>(0, \"input\");\n\n    Convolution2dDescriptor convDescriptor;\n    PreCompiledDescriptor substitutionLayerDescriptor(1, 1);\n    Layer* const convLayer1 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, \"conv1\");\n    Layer* const convLayer2 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, \"conv2\");\n    Layer* const substitutableCompiledLayer =\n            baseGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, \"pre-compiled\");\n\n    Layer* const outputLayer = baseGraph.AddLayer<OutputLayer>(0, \"output\");\n\n    inputLayer->GetOutputSlot(0).Connect(convLayer1->GetInputSlot(0));\n    convLayer1->GetOutputSlot(0).Connect(convLayer2->GetInputSlot(0));\n    convLayer2->GetOutputSlot(0).Connect(outputLayer->GetInputSlot(0));\n\n    \/\/ Subgraph for an untouched layer\n    SubgraphViewSelector::SubgraphViewPtr untouchedSubgraph =\n            CreateSubgraphViewFrom(CreateInputsFrom({convLayer2}),\n                                   CreateOutputsFrom({convLayer2}),\n                                   {convLayer2});\n    \/\/ Subgraph for a substitutable layer\n    SubgraphViewSelector::SubgraphViewPtr substitutableSubgraph =\n            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),\n                                   CreateOutputsFrom({convLayer2}),\n                                   {substitutableCompiledLayer});\n    \/\/ Create a Graph containing a layer to substitute in\n    Graph substitutableGraph;\n    Layer* const substitutionpreCompiledLayer =\n            substitutableGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, \"pre-compiled\");\n\n    \/\/ Subgraph for a substitution layer\n    SubgraphViewSelector::SubgraphViewPtr substitutionSubgraph =\n            CreateSubgraphViewFrom(CreateInputsFrom({substitutionpreCompiledLayer}),\n                                   CreateOutputsFrom({substitutionpreCompiledLayer}),\n                                   {substitutionpreCompiledLayer});\n\n    \/\/ Sub in the graph\n    baseGraph.SubstituteSubgraph(*substitutableSubgraph, *substitutionSubgraph);\n\n    view.AddUntouchedSubgraph(SubgraphView(*untouchedSubgraph));\n\n    SubgraphViewSelector::SubgraphViewPtr baseSubgraph =\n            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),\n                                   CreateOutputsFrom({convLayer2}),\n                                   {substitutionpreCompiledLayer});\n    view.AddSubstitution({*baseSubgraph, *substitutionSubgraph});\n\n    \/\/ Construct original subgraph to compare against\n    SubgraphViewSelector::SubgraphViewPtr originalSubgraph =\n            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),\n                                   CreateOutputsFrom({convLayer2}),\n                                   {convLayer1, convLayer2, substitutionpreCompiledLayer});\n\n    \/\/ Validate should fail as convLayer1 is not counted\n    BOOST_CHECK(!view.Validate(*originalSubgraph));\n}\n\nBOOST_AUTO_TEST_CASE(OptimizeViewsValidateDeviceMockBackend)\n{\n    \/\/ build up the structure of the network\n    armnn::INetworkPtr net(armnn::INetwork::Create());\n\n    armnn::IConnectableLayer* input = net->AddInputLayer(0, \"inLayer0\");\n    armnn::IConnectableLayer* input1 = net->AddInputLayer(1, \"inLayer1\");\n\n    armnn::IConnectableLayer* addition = net->AddAdditionLayer(\"addLayer\");\n\n    armnn::IConnectableLayer* output = net->AddOutputLayer(0, \"outLayer\");\n\n    input->GetOutputSlot(0).Connect(addition->GetInputSlot(0));\n    input1->GetOutputSlot(0).Connect(addition->GetInputSlot(1));\n    addition->GetOutputSlot(0).Connect(output->GetInputSlot(0));\n\n    input->GetOutputSlot(0).SetTensorInfo(armnn::TensorInfo({ 1, 1, 4, 4 }, armnn::DataType::Float32));\n    input1->GetOutputSlot(0).SetTensorInfo(armnn::TensorInfo({ 1, 1, 4, 4 }, armnn::DataType::Float32));\n    addition->GetOutputSlot(0).SetTensorInfo(armnn::TensorInfo({ 1, 1, 4, 4 }, armnn::DataType::Float32));\n\n    armnn::MockBackendInitialiser initialiser;\n    armnn::IRuntime::CreationOptions options;\n    armnn::IRuntimePtr runtime(armnn::IRuntime::Create(options));\n\n    std::vector<armnn::BackendId> backends = { MockBackend().GetIdStatic() };\n    armnn::IOptimizedNetworkPtr optNet = armnn::Optimize(*net, backends, runtime->GetDeviceSpec());\n    BOOST_CHECK(optNet);\n\n    \/\/ Check the optimised graph\n    OptimizedNetwork* optNetObjPtr = boost::polymorphic_downcast<OptimizedNetwork*>(optNet.get());\n    CheckLayers(optNetObjPtr->GetGraph());\n}\n\nBOOST_AUTO_TEST_SUITE_END()","avg_line_length":44.1395348837,"max_line_length":106,"alphanum_fraction":0.6791359326,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5015,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ terrace.cpp\n\/\/\n\/\/ Copyright (C) 2003, 2004 Jason Bevins\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU Lesser General Public License as published by\n\/\/ the Free Software Foundation; either version 2.1 of the License, or (at\n\/\/ your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful, but WITHOUT\n\/\/ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n\/\/ FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public\n\/\/ License (COPYING.txt) for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this library; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\/\/\n\/\/ The developer's email is jlbezigvins@gmzigail.com (for great email, take\n\/\/ off every 'zig'.)\n\/\/\n\n#include \"interp.h\"\n#include \"misc.h\"\n#include \"module\/terrace.h\"\n\nusing namespace noise::module;\n\nusing namespace noise;\n\nTerrace::Terrace ():\n  Module (GetSourceModuleCount ()),\n  m_controlPointCount (0),\n  m_invertTerraces (false),\n  m_pControlPoints (NULL)\n{\n}\n\nTerrace::~Terrace ()\n{\n  delete[] m_pControlPoints;\n}\n\nvoid Terrace::AddControlPoint (double value)\n{\n  \/\/ Find the insertion point for the new control point and insert the new\n  \/\/ point at that position.  The control point array will remain sorted by\n  \/\/ value.\n  int insertionPos = FindInsertionPos (value);\n  InsertAtPos (insertionPos, value);\n}\n\nvoid Terrace::ClearAllControlPoints ()\n{\n  delete[] m_pControlPoints;\n  m_pControlPoints = NULL;\n  m_controlPointCount = 0;\n}\n\nint Terrace::FindInsertionPos (double value)\n{\n  int insertionPos;\n  for (insertionPos = 0; insertionPos < m_controlPointCount; insertionPos++) {\n    if (value < m_pControlPoints[insertionPos]) {\n      \/\/ We found the array index in which to insert the new control point.\n      \/\/ Exit now.\n      break;\n    } else if (value == m_pControlPoints[insertionPos]) {\n      \/\/ Each control point is required to contain a unique value, so throw\n      \/\/ an exception.\n      throw noise::ExceptionInvalidParam ();\n    }\n  }\n  return insertionPos;\n}\n\ndouble Terrace::GetValue (double x, double y, double z) const\n{\n  assert (m_pSourceModule[0] != NULL);\n  assert (m_controlPointCount >= 2);\n\n  \/\/ Get the output value from the source module.\n  double sourceModuleValue = m_pSourceModule[0]->GetValue (x, y, z);\n\n  \/\/ Find the first element in the control point array that has a value\n  \/\/ larger than the output value from the source module.\n  int indexPos;\n  for (indexPos = 0; indexPos < m_controlPointCount; indexPos++) {\n    if (sourceModuleValue < m_pControlPoints[indexPos]) {\n      break;\n    }\n  }\n\n  \/\/ Find the two nearest control points so that we can map their values\n  \/\/ onto a quadratic curve.\n  int index0 = ClampValue (indexPos - 1, 0, m_controlPointCount - 1);\n  int index1 = ClampValue (indexPos    , 0, m_controlPointCount - 1);\n\n  \/\/ If some control points are missing (which occurs if the output value from\n  \/\/ the source module is greater than the largest value or less than the\n  \/\/ smallest value of the control point array), get the value of the nearest\n  \/\/ control point and exit now.\n  if (index0 == index1) {\n    return m_pControlPoints[index1];\n  }\n\n  \/\/ Compute the alpha value used for linear interpolation.\n  double value0 = m_pControlPoints[index0];\n  double value1 = m_pControlPoints[index1];\n  double alpha = (sourceModuleValue - value0) \/ (value1 - value0);\n  if (m_invertTerraces) {\n    alpha = 1.0 - alpha;\n    SwapValues (value0, value1);\n  }\n\n  \/\/ Squaring the alpha produces the terrace effect.\n  alpha *= alpha;\n\n  \/\/ Now perform the linear interpolation given the alpha value.\n  return LinearInterp (value0, value1, alpha);\n}\n\nvoid Terrace::InsertAtPos (int insertionPos, double value)\n{\n  \/\/ Make room for the new control point at the specified position within\n  \/\/ the control point array.  The position is determined by the value of\n  \/\/ the control point; the control points must be sorted by value within\n  \/\/ that array.\n  double* newControlPoints = new double[m_controlPointCount + 1];\n  for (int i = 0; i < m_controlPointCount; i++) {\n    if (i < insertionPos) {\n      newControlPoints[i] = m_pControlPoints[i];\n    } else {\n      newControlPoints[i + 1] = m_pControlPoints[i];\n    }\n  }\n  delete[] m_pControlPoints;\n  m_pControlPoints = newControlPoints;\n  ++m_controlPointCount;\n\n  \/\/ Now that we've made room for the new control point within the array,\n  \/\/ add the new control point.\n  m_pControlPoints[insertionPos] = value;\n}\n\nvoid Terrace::MakeControlPoints (int controlPointCount)\n{\n  if (controlPointCount < 2) {\n    throw noise::ExceptionInvalidParam ();\n  }\n\n  ClearAllControlPoints ();\n\n  double terraceStep = 2.0 \/ ((double)controlPointCount - 1.0);\n  double curValue = -1.0;\n  for (int i = 0; i < (int)controlPointCount; i++) {\n    AddControlPoint (curValue);\n    curValue += terraceStep;\n  }\n}\n","avg_line_length":31.149068323,"max_line_length":78,"alphanum_fraction":0.7082751745,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1943,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/\/ Copyright (c) 2004-2019 Intel Corporation\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"umc_defs.h\"\n\n#if defined (MFX_ENABLE_VC1_VIDEO_CODEC)\n#include \"umc_vc1_common.h\"\n\nnamespace UMC\n{\n    namespace VC1Common\n    {\n\n        void SwapData(uint8_t *src, uint32_t dataSize)\n        {\n            uint32_t i;\n            uint32_t counter = 0;\n            uint32_t* pDst = (uint32_t*)src;\n            uint32_t  iCur = 0;\n\n            for(i = 0; i < dataSize+4; i++)\n            {\n                if (4 == counter)\n                {\n                    counter = 0;\n                    *pDst = iCur;\n                    pDst++;\n                    iCur = 0;\n                }\n\n                if (0 == counter)\n                    iCur = src[i];\n                iCur <<= 8;\n                iCur |= src[i];\n                ++counter;\n            }\n        }\n\n\n\n    }\n}\n#endif \/\/MFX_ENABLE_VC1_VIDEO_CODEC\n","avg_line_length":31.8524590164,"max_line_length":81,"alphanum_fraction":0.6083376222,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2899,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n *  Fileio.cpp\n *\n *\/\n\n#include \"Fileio.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h>\n\n\n#if 1\/\/def WINDOWS\n#include <direct.h>\n#define GetCurrentDir _getcwd\n#else\n#include <sys\/file.h>\n#include <sys\/mman.h>\n#include <unistd.h>\n#define GetCurrentDir getcwd\n#endif\n\nstatic char g_ApplicationDirectory[ FILENAME_MAX ];\t\/\/ needs to be CWD\nstatic bool g_WasInitialized = false;\n\n\/*\n=================================\nInitializeFileSystem\n=================================\n*\/\nvoid InitializeFileSystem() {\n\tif ( g_WasInitialized ) {\n\t\treturn;\n\t}\n\tg_WasInitialized = true;\n\n\tconst bool result = GetCurrentDir( g_ApplicationDirectory, sizeof( g_ApplicationDirectory ) );\n\tassert( result );\n\tif ( result ) {\n\t\tprintf( \"ApplicationDirectory: %s\\n\", g_ApplicationDirectory );\n\t} else {\n\t\tprintf( \"ERROR: Unable to get current working directory!\\n\");\n\t}\n}\n\n\/*\n=================================\nRelativePathToFullPath\n=================================\n*\/\nvoid RelativePathToFullPath( const char * relativePathName, char * fullPath ) {\n\tInitializeFileSystem();\n\n\tsprintf( fullPath, \"%s\/%s\", g_ApplicationDirectory, relativePathName );\n}\n\n \/*\n ====================================================\n GetFileData\n Opens the file and stores it in data\n ====================================================\n *\/\nbool GetFileData( const char * fileNameLocal, unsigned char ** data, unsigned int & size ) {\n\tInitializeFileSystem();\n\n\tchar fileName[ 2048 ];\n\tsprintf( fileName, \"%s\/%s\", g_ApplicationDirectory, fileNameLocal );\n\n\tFILE *file = NULL;\n\t\n\t\/\/ open file for reading\n\tprintf( \"opening file: %s\\n\", fileName );\n\tfile = fopen( fileName, \"rb\" );\n\t\n\t\/\/ handle any errors\n\tif ( file == NULL ) {\n\t\tprintf(\"ERROR: open file failed: %s\\n\", fileName );\n\t\treturn false;\n\t}\n\t\n\t\/\/ get file size\n\tfseek( file, 0, SEEK_END );\n\tfflush( file );\n\tsize = ftell( file );\n\tfflush( file );\n\trewind( file );\n\tfflush( file );\n\t\n\t\/\/ output file size\n\tprintf( \"file size: %u\\n\", size );\n\t\n\t\/\/ create the data buffer\n\t*data = (unsigned char*)malloc( ( size + 1 ) * sizeof( unsigned char ) );\n\t\/\/*data = (unsigned char*)calloc( size + 1, sizeof( unsigned char ) ); \/\/ calloc initializes memory to zero\n    \n\t\/\/ handle any errors\n\tif ( *data == NULL ) {\n\t\tprintf( \"ERROR: Could not allocate memory!\\n\" );\n\t\tfclose( file );\n\t\treturn false;\n\t}\n\n\t\/\/ zero out the memory\n\tmemset( *data, 0, ( size + 1 ) * sizeof( unsigned char ) );\n\t\n\t\/\/ read the data\n\tunsigned int bytesRead = (unsigned int)fread( *data, sizeof( unsigned char ), size, file );\n    fflush( file );\n\tprintf( \"total bytes read: %u\\n\", bytesRead );\n    \n    assert( bytesRead == size );\n\t\n\t\/\/ handle any errors\n\tif ( bytesRead != size ) {\n\t\tprintf( \"ERROR: reading file went wrong\\n\" );\n\t\tfclose( file );\n\t\tif ( *data != NULL ) {\n\t\t\tfree( *data );\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tfclose( file );\n\tprintf( \"Read file was success\\n\");\n\treturn true;\n}\n","avg_line_length":22.8267716535,"max_line_length":108,"alphanum_fraction":0.6043463263,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":17727,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0","MIT"],"max_stars_count":11.0,"content":"\/*\n * Copyright (c) Contributors to the Open 3D Engine Project.\n * For complete copyright and license terms please see the LICENSE at the root of this distribution.\n *\n * SPDX-License-Identifier: Apache-2.0 OR MIT\n *\n *\/\n\n#include <AzCore\/Math\/Vector2.h>\n#include <AzCore\/UnitTest\/TestTypes.h>\n\n#if defined(HAVE_BENCHMARK)\n\n#include <random>\n#include <benchmark\/benchmark.h>\n\nnamespace Benchmark\n{\n    class BM_MathVector2\n        : public benchmark::Fixture\n    {\n        void internalSetUp()\n        {\n            m_vecDataArray.resize(1000);\n\n            const unsigned int seed = 1;\n            std::mt19937_64 rng(seed);\n            std::uniform_real_distribution<float> unif;\n\n            std::generate(m_vecDataArray.begin(), m_vecDataArray.end(), [&unif, &rng]()\n            {\n                VecData vecData;\n                vecData.v1 = AZ::Vector2(unif(rng), unif(rng));\n                vecData.v2 = AZ::Vector2(unif(rng), unif(rng));\n                vecData.v3 = AZ::Vector2(unif(rng), unif(rng));\n                return vecData;\n            });\n        }\n    public:\n        void SetUp(const benchmark::State&) override\n        {\n            internalSetUp();\n        }\n        void SetUp(benchmark::State&) override\n        {\n            internalSetUp();\n        }\n\n        struct VecData\n        {\n            AZ::Vector2 v1;\n            AZ::Vector2 v2;\n            AZ::Vector2 v3;\n        };\n\n        std::vector<VecData> m_vecDataArray;\n    };\n\n    BENCHMARK_F(BM_MathVector2, GetSet)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            AZ::Vector2 v1, v2;\n            float x = 0.0f, y = 0.0f;\n            for (auto& vecData : m_vecDataArray)\n            {\n                x += vecData.v1.GetX();\n                y += vecData.v2.GetY();\n\n                x += vecData.v2.GetX();\n                y += vecData.v1.GetY();\n\n                v1.SetX(x);\n                v2.SetX(x);\n\n                v1.SetY(y);\n                v2.SetY(y);\n            }\n\n            benchmark::DoNotOptimize(v1);\n            benchmark::DoNotOptimize(v2);\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, ElementAccess)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            AZ::Vector2 v1, v2;\n            float x = 0.0f, y = 0.0f;\n\n            for (auto& vecData : m_vecDataArray)\n            {\n                x += vecData.v1.GetElement(0);\n                y += vecData.v2.GetElement(1);\n\n                x += vecData.v2.GetElement(0);\n                y += vecData.v1.GetElement(1);\n\n                v1.SetElement(0, x);\n                v2.SetElement(0, x);\n\n                v1.SetElement(1, y);\n                v2.SetElement(1, y);\n            }\n\n            benchmark::DoNotOptimize(v1);\n            benchmark::DoNotOptimize(v2);\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, CreateSelectCmpEqual)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = AZ::Vector2::CreateSelectCmpEqual(vecData.v1, vecData.v2, vecData.v2, vecData.v3);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, CreateSelectCmpGreaterEqual)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = AZ::Vector2::CreateSelectCmpGreaterEqual(vecData.v1, vecData.v2, vecData.v2, vecData.v3);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, CreateSelectCmpGreater)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = AZ::Vector2::CreateSelectCmpGreater(vecData.v1, vecData.v2, vecData.v2, vecData.v3);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetNormalized)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetNormalized();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetNormalizedEstimate)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetNormalizedEstimate();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, NormalizeWithLength)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                float result = vecData.v1.NormalizeWithLength();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, NormalizeWithLengthEstimate)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                float result = vecData.v1.NormalizeWithLengthEstimate();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetNormalizedSafe)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetNormalizedSafe();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetNormalizedSafeEstimate)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetNormalizedSafeEstimate();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetDistance)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                float result = vecData.v2.GetDistance(vecData.v1);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetDistanceEstimate)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                float result = vecData.v2.GetDistanceEstimate(vecData.v1);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, Lerp)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v2.Lerp(vecData.v1, 0.0f);\n                benchmark::DoNotOptimize(result);\n\n                result = vecData.v2.Lerp(vecData.v1, 0.25f);\n                benchmark::DoNotOptimize(result);\n\n                result = vecData.v2.Lerp(vecData.v1, 0.5f);\n                benchmark::DoNotOptimize(result);\n\n                result = vecData.v2.Lerp(vecData.v1, 0.75f);\n                benchmark::DoNotOptimize(result);\n\n                result = vecData.v2.Lerp(vecData.v1, 1.0f);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, Slerp)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v2.Slerp(vecData.v1, 0.0f);\n                benchmark::DoNotOptimize(result);\n\n                result = vecData.v2.Slerp(vecData.v1, 0.25f);\n                benchmark::DoNotOptimize(result);\n\n                result = vecData.v2.Slerp(vecData.v1, 0.5f);\n                benchmark::DoNotOptimize(result);\n\n                result = vecData.v2.Slerp(vecData.v1, 0.75f);\n                benchmark::DoNotOptimize(result);\n\n                result = vecData.v2.Slerp(vecData.v1, 1.0f);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, Nlerp)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v2.Nlerp(vecData.v1, 0.0f);\n                benchmark::DoNotOptimize(result);\n\n                result = vecData.v2.Nlerp(vecData.v1, 0.25f);\n                benchmark::DoNotOptimize(result);\n\n                result = vecData.v2.Nlerp(vecData.v1, 0.5f);\n                benchmark::DoNotOptimize(result);\n\n                result = vecData.v2.Nlerp(vecData.v1, 0.75f);\n                benchmark::DoNotOptimize(result);\n\n                result = vecData.v2.Nlerp(vecData.v1, 1.0f);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, Dot)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                float result = vecData.v1.Dot(vecData.v2);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, Equality)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                bool result = vecData.v1 == vecData.v2;\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, Inequality)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                bool result = vecData.v1 != vecData.v2;\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, IsLessThan)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                bool result = vecData.v1.IsLessThan(vecData.v2);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, IsLessEqualThan)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                bool result = vecData.v1.IsLessEqualThan(vecData.v2);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, IsGreaterThan)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                bool result = vecData.v1.IsGreaterThan(vecData.v2);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, IsGreaterEqualThan)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                bool result = vecData.v1.IsGreaterEqualThan(vecData.v2);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetMin)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetMin(vecData.v2);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetMax)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetMax(vecData.v2);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetClamp)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetClamp(vecData.v2, vecData.v3);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, Sub)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1 - vecData.v2;\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, Sum)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1 + vecData.v2;\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, Mul)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1 * vecData.v2;\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, Div)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1 \/ vecData.v2;\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetSin)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetSin();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetCos)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetCos();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetSinCos)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 sin, cos;\n                vecData.v1.GetSinCos(sin, cos);\n                benchmark::DoNotOptimize(sin);\n                benchmark::DoNotOptimize(cos);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetAcos)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetAcos();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetAtan)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetAtan();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetAtan2)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                float result = vecData.v1.GetAtan2();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetAngleMod)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetAngleMod();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, Angle)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                float result = vecData.v1.Angle(vecData.v2);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, AngleDeg)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                float result = vecData.v1.AngleDeg(vecData.v2);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetAbs)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetAbs();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetReciprocal)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetReciprocal();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetReciprocalEstimate)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetReciprocalEstimate();\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n\n    BENCHMARK_F(BM_MathVector2, GetProjected)(benchmark::State& state)\n    {\n        for (auto _ : state)\n        {\n            for (auto& vecData : m_vecDataArray)\n            {\n                AZ::Vector2 result = vecData.v1.GetProjected(vecData.v2);\n                benchmark::DoNotOptimize(result);\n            }\n        }\n    }\n}\n\n#endif\n","avg_line_length":27.5263975155,"max_line_length":126,"alphanum_fraction":0.502059006,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13833,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":2.0,"content":"\/\/ SPDX-License-Identifier: BSD-3-Clause\n\/\/ Copyright Contributors to the OpenColorIO Project.\n\n\n#include <string.h>\n\n#include <OpenColorIO\/OpenColorIO.h>\n\n#include \"ContextVariableUtils.h\"\n#include \"OpBuilders.h\"\n#include \"ops\/noop\/NoOps.h\"\n\n\nnamespace OCIO_NAMESPACE\n{\nColorSpaceTransformRcPtr ColorSpaceTransform::Create()\n{\n    return ColorSpaceTransformRcPtr(new ColorSpaceTransform(), &deleter);\n}\n\nvoid ColorSpaceTransform::deleter(ColorSpaceTransform* t)\n{\n    delete t;\n}\n\nclass ColorSpaceTransform::Impl\n{\npublic:\n    TransformDirection m_dir{ TRANSFORM_DIR_FORWARD  };\n    std::string m_src;\n    std::string m_dst;\n    bool m_dataBypass{ true };\n\n    Impl() = default;\n    Impl(const Impl &) = delete;\n\n    ~Impl() = default;\n\n    Impl& operator= (const Impl & rhs)\n    {\n        if (this != &rhs)\n        {\n            m_dir        = rhs.m_dir;\n            m_src        = rhs.m_src;\n            m_dst        = rhs.m_dst;\n            m_dataBypass = rhs.m_dataBypass;\n        }\n        return *this;\n    }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nColorSpaceTransform::ColorSpaceTransform()\n    : m_impl(new ColorSpaceTransform::Impl)\n{\n}\n\nTransformRcPtr ColorSpaceTransform::createEditableCopy() const\n{\n    ColorSpaceTransformRcPtr transform = ColorSpaceTransform::Create();\n    *(transform->m_impl) = *m_impl;\n    return transform;\n}\n\nColorSpaceTransform::~ColorSpaceTransform()\n{\n    delete m_impl;\n    m_impl = nullptr;\n}\n\nTransformDirection ColorSpaceTransform::getDirection() const noexcept\n{\n    return getImpl()->m_dir;\n}\n\nvoid ColorSpaceTransform::setDirection(TransformDirection dir) noexcept\n{\n    getImpl()->m_dir = dir;\n}\n\nvoid ColorSpaceTransform::validate() const\n{\n    Transform::validate();\n\n    if (getImpl()->m_src.empty())\n    {\n        throw Exception(\"ColorSpaceTransform: empty source color space name.\");\n    }\n\n    if (getImpl()->m_dst.empty())\n    {\n        throw Exception(\"ColorSpaceTransform: empty destination color space name.\");\n    }\n}\n\nconst char * ColorSpaceTransform::getSrc() const\n{\n    return getImpl()->m_src.c_str();\n}\n\nvoid ColorSpaceTransform::setSrc(const char * src)\n{\n    getImpl()->m_src = src;\n}\n\nconst char * ColorSpaceTransform::getDst() const\n{\n    return getImpl()->m_dst.c_str();\n}\n\nvoid ColorSpaceTransform::setDst(const char * dst)\n{\n    getImpl()->m_dst = dst;\n}\n\nbool ColorSpaceTransform::getDataBypass() const noexcept\n{\n    return getImpl()->m_dataBypass;\n}\n\nvoid ColorSpaceTransform::setDataBypass(bool bypass) noexcept\n{\n    getImpl()->m_dataBypass = bypass;\n}\n\nstd::ostream& operator<< (std::ostream& os, const ColorSpaceTransform& t)\n{\n    os << \"<ColorSpaceTransform \";\n    os << \"direction=\" << TransformDirectionToString(t.getDirection()) << \", \";\n    os << \"src=\" << t.getSrc() << \", \";\n    os << \"dst=\" << t.getDst();\n    const bool bypass = t.getDataBypass();\n    if (!bypass)\n    {\n        os << \"dataBypass=\" << bypass;\n    }\n    os << \">\";\n    return os;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace\n{\nvoid ThrowMissingCS(const char * srcdst, const char * cs)\n{\n    std::ostringstream os;\n    os << \"BuildColorSpaceOps failed: \" << srcdst << \" color space '\" << cs;\n    os << \"' could not be found.\";\n    throw Exception(os.str().c_str());\n}\n\nconstexpr char SRC_CS[] = \"source\";\nconstexpr char DST_CS[] = \"destination\";\n}\n\nvoid BuildColorSpaceOps(OpRcPtrVec & ops,\n                        const Config & config,\n                        const ConstContextRcPtr & context,\n                        const ColorSpaceTransform & colorSpaceTransform,\n                        TransformDirection dir)\n{\n    auto combinedDir = CombineTransformDirections(dir, colorSpaceTransform.getDirection());\n\n    ConstColorSpaceRcPtr src, dst;\n\n    if(combinedDir == TRANSFORM_DIR_FORWARD)\n    {\n        src = config.getColorSpace( context->resolveStringVar( colorSpaceTransform.getSrc() ) );\n        if (!src)\n        {\n            ThrowMissingCS(SRC_CS, colorSpaceTransform.getSrc());\n        }\n        dst = config.getColorSpace( context->resolveStringVar( colorSpaceTransform.getDst() ) );\n        if (!dst)\n        {\n            ThrowMissingCS(DST_CS, colorSpaceTransform.getDst());\n        }\n    }\n    else if(combinedDir == TRANSFORM_DIR_INVERSE)\n    {\n        dst = config.getColorSpace( context->resolveStringVar( colorSpaceTransform.getSrc() ) );\n        if (!dst)\n        {\n            ThrowMissingCS(SRC_CS, colorSpaceTransform.getSrc());\n        }\n        src = config.getColorSpace( context->resolveStringVar( colorSpaceTransform.getDst() ) );\n        if (!src)\n        {\n            ThrowMissingCS(DST_CS, colorSpaceTransform.getDst());\n        }\n    }\n\n    BuildColorSpaceOps(ops, config, context, src, dst, colorSpaceTransform.getDataBypass());\n}\n\nnamespace\n{\nbool AreColorSpacesInSameEqualityGroup(const ConstColorSpaceRcPtr & csa,\n                                       const ConstColorSpaceRcPtr & csb)\n{\n    std::string a = csa->getEqualityGroup();\n    std::string b = csb->getEqualityGroup();\n\n    if(!a.empty()) return (a==b);\n    return false;\n}\n\n}\n\nvoid BuildColorSpaceOps(OpRcPtrVec & ops,\n                        const Config & config,\n                        const ConstContextRcPtr & context,\n                        const ConstColorSpaceRcPtr & srcColorSpace,\n                        const ConstColorSpaceRcPtr & dstColorSpace,\n                        bool dataBypass)\n{\n    if(!srcColorSpace)\n        throw Exception(\"BuildColorSpaceOps failed, null srcColorSpace.\");\n    if(!dstColorSpace)\n        throw Exception(\"BuildColorSpaceOps failed, null dstColorSpace.\");\n\n    if(AreColorSpacesInSameEqualityGroup(srcColorSpace, dstColorSpace))\n        return;\n    if(dataBypass && (dstColorSpace->isData() || srcColorSpace->isData()))\n        return;\n\n    \/\/ Consider dt8 -> vd8?\n    \/\/ One would have to explode the srcColorSpace->getTransform(COLORSPACE_DIR_TO_REFERENCE);\n    \/\/ result, and walk through it step by step.  If the dstColorspace family were\n    \/\/ ever encountered in transit, we'd want to short circuit the result.\n\n    \/\/ Go from the srcColorSpace to the reference space.\n    BuildColorSpaceToReferenceOps(ops, config, context, srcColorSpace, dataBypass);\n\n    \/\/ There are two possible reference spaces, the main (scene-referred) one and the\n    \/\/ display-referred one.  If the src and dst use different reference spaces, use the\n    \/\/ default ViewTransform to convert between them.\n    BuildReferenceConversionOps(ops, config, context,\n                                srcColorSpace->getReferenceSpaceType(),\n                                dstColorSpace->getReferenceSpaceType());\n\n    \/\/ Go from the reference space to dstColorSpace.\n    BuildColorSpaceFromReferenceOps(ops, config, context, dstColorSpace, dataBypass);\n}\n\nvoid BuildColorSpaceToReferenceOps(OpRcPtrVec & ops,\n                                   const Config & config,\n                                   const ConstContextRcPtr & context,\n                                   const ConstColorSpaceRcPtr & srcColorSpace,\n                                   bool dataBypass)\n{\n    if (!srcColorSpace)\n        throw Exception(\"BuildColorSpaceOps failed, null colorSpace.\");\n\n    if (dataBypass && srcColorSpace->isData())\n        return;\n\n    AllocationData srcAllocation;\n    srcAllocation.allocation = srcColorSpace->getAllocation();\n    srcAllocation.vars.resize(srcColorSpace->getAllocationNumVars());\n    if (srcAllocation.vars.size() > 0)\n    {\n        srcColorSpace->getAllocationVars(&srcAllocation.vars[0]);\n    }\n\n    CreateGpuAllocationNoOp(ops, srcAllocation);\n\n    \/\/ Go to the reference space, either by using:\n    \/\/ * cs->ref in the forward direction.\n    \/\/ * ref->cs in the inverse direction.\n    if (srcColorSpace->getTransform(COLORSPACE_DIR_TO_REFERENCE))\n    {\n        BuildOps(ops, config, context, srcColorSpace->getTransform(COLORSPACE_DIR_TO_REFERENCE),\n                 TRANSFORM_DIR_FORWARD);\n    }\n    else if (srcColorSpace->getTransform(COLORSPACE_DIR_FROM_REFERENCE))\n    {\n        BuildOps(ops, config, context, srcColorSpace->getTransform(COLORSPACE_DIR_FROM_REFERENCE),\n                 TRANSFORM_DIR_INVERSE);\n    }\n    \/\/ Otherwise, both are not defined so its a no-op. This is not an error condition.\n}\n\nvoid BuildColorSpaceFromReferenceOps(OpRcPtrVec & ops,\n                                     const Config & config,\n                                     const ConstContextRcPtr & context,\n                                     const ConstColorSpaceRcPtr & dstColorSpace,\n                                     bool dataBypass)\n{\n    if (!dstColorSpace)\n        throw Exception(\"BuildColorSpaceOps failed, null colorSpace.\");\n\n    if (dataBypass && dstColorSpace->isData())\n        return;\n\n    \/\/ Go from the reference space, either by using:\n    \/\/ * ref->cs in the forward direction.\n    \/\/ * cs->ref in the inverse direction.\n    if (dstColorSpace->getTransform(COLORSPACE_DIR_FROM_REFERENCE))\n    {\n        BuildOps(ops, config, context, dstColorSpace->getTransform(COLORSPACE_DIR_FROM_REFERENCE),\n                    TRANSFORM_DIR_FORWARD);\n    }\n    else if (dstColorSpace->getTransform(COLORSPACE_DIR_TO_REFERENCE))\n    {\n        BuildOps(ops, config, context, dstColorSpace->getTransform(COLORSPACE_DIR_TO_REFERENCE),\n                    TRANSFORM_DIR_INVERSE);\n    }\n    \/\/ Otherwise, both are not defined so its a no-op. This is not an error condition.\n\n    AllocationData dstAllocation;\n    dstAllocation.allocation = dstColorSpace->getAllocation();\n    dstAllocation.vars.resize(dstColorSpace->getAllocationNumVars());\n    if (dstAllocation.vars.size() > 0)\n    {\n        dstColorSpace->getAllocationVars(&dstAllocation.vars[0]);\n    }\n\n    CreateGpuAllocationNoOp(ops, dstAllocation);\n}\n\nvoid BuildReferenceConversionOps(OpRcPtrVec & ops,\n                                 const Config & config,\n                                 const ConstContextRcPtr & context,\n                                 ReferenceSpaceType srcReferenceSpace,\n                                 ReferenceSpaceType dstReferenceSpace)\n{\n    if (srcReferenceSpace != dstReferenceSpace)\n    {\n        auto view = config.getDefaultSceneToDisplayViewTransform();\n        if (!view)\n        {\n            \/\/ Can not be the case for a valid config.\n            throw Exception(\"There is no view transform between the main scene-referred space \"\n                            \"and the display-referred space.\");\n        }\n        if (srcReferenceSpace == REFERENCE_SPACE_SCENE) \/\/ convert scene-referred to display-referred\n        {\n            if (view->getTransform(VIEWTRANSFORM_DIR_FROM_REFERENCE))\n            {\n                BuildOps(ops, config, context,\n                         view->getTransform(VIEWTRANSFORM_DIR_FROM_REFERENCE),\n                         TRANSFORM_DIR_FORWARD);\n            }\n            else if (view->getTransform(VIEWTRANSFORM_DIR_TO_REFERENCE))\n            {\n                BuildOps(ops, config, context,\n                         view->getTransform(VIEWTRANSFORM_DIR_TO_REFERENCE),\n                         TRANSFORM_DIR_INVERSE);\n            }\n        }\n        else \/\/ convert display-referred to scene-referred\n        {\n            if (view->getTransform(VIEWTRANSFORM_DIR_TO_REFERENCE))\n            {\n                BuildOps(ops, config, context,\n                         view->getTransform(VIEWTRANSFORM_DIR_TO_REFERENCE),\n                         TRANSFORM_DIR_FORWARD);\n            }\n            else if (view->getTransform(VIEWTRANSFORM_DIR_FROM_REFERENCE))\n            {\n                BuildOps(ops, config, context,\n                         view->getTransform(VIEWTRANSFORM_DIR_FROM_REFERENCE),\n                         TRANSFORM_DIR_INVERSE);\n            }\n        }\n    }\n}\n\nbool CollectContextVariables(const Config & config, \n                             const Context & context,\n                             ConstColorSpaceRcPtr & cs,\n                             ContextRcPtr & usedContextVars)\n{\n    bool foundContextVars = false;\n\n    if (cs)\n    {\n        ConstTransformRcPtr to = cs->getTransform(COLORSPACE_DIR_TO_REFERENCE);\n        if (to && CollectContextVariables(config, context, to, usedContextVars))\n        {\n            foundContextVars = true;\n        }\n\n        ConstTransformRcPtr from = cs->getTransform(COLORSPACE_DIR_FROM_REFERENCE);\n        if (from && CollectContextVariables(config, context, from, usedContextVars))\n        {\n            foundContextVars = true;\n        }\n    }\n\n    return foundContextVars;\n}\n\nbool CollectContextVariables(const Config & config, \n                             const Context & context,\n                             const ColorSpaceTransform & tr,\n                             ContextRcPtr & usedContextVars)\n{\n    bool foundContextVars = false;\n    \n    \/\/ NB: The search could return false positive but should not miss anything i.e. it looks\n    \/\/ for context variables in both directions even if only one will be used.\n\n    const std::string srcName(context.resolveStringVar(tr.getSrc(), usedContextVars));\n    if (0 != strcmp(srcName.c_str(), tr.getSrc()))\n    {\n        foundContextVars = true;\n    }\n\n    const std::string dstName(context.resolveStringVar(tr.getDst(), usedContextVars));\n    if (0 != strcmp(dstName.c_str(), tr.getDst()))\n    {\n        foundContextVars = true;\n    }\n\n    ConstColorSpaceRcPtr src = config.getColorSpace(srcName.c_str());\n    if (CollectContextVariables(config, context, src, usedContextVars))\n    {\n        foundContextVars = true;\n    }\n\n    ConstColorSpaceRcPtr dst = config.getColorSpace(dstName.c_str());\n    if (CollectContextVariables(config, context, dst, usedContextVars))\n    {\n        foundContextVars = true;\n    }\n\n    return foundContextVars;\n}\n\n} \/\/ namespace OCIO_NAMESPACE\n","avg_line_length":31.8,"max_line_length":103,"alphanum_fraction":0.616569074,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6353,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":605.0,"content":"\/\/===- OcamlGCPrinter.cpp - Ocaml frametable emitter ----------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements printing the assembly code for an Ocaml frametable.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/CodeGen\/AsmPrinter.h\"\n#include \"llvm\/CodeGen\/GCMetadata.h\"\n#include \"llvm\/CodeGen\/GCMetadataPrinter.h\"\n#include \"llvm\/IR\/BuiltinGCs.h\"\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/Mangler.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/MC\/MCContext.h\"\n#include \"llvm\/MC\/MCDirectives.h\"\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Target\/TargetLoweringObjectFile.h\"\n#include <cctype>\n#include <cstddef>\n#include <cstdint>\n#include <string>\n\nusing namespace llvm;\n\nnamespace {\n\nclass OcamlGCMetadataPrinter : public GCMetadataPrinter {\npublic:\n  void beginAssembly(Module &M, GCModuleInfo &Info, AsmPrinter &AP) override;\n  void finishAssembly(Module &M, GCModuleInfo &Info, AsmPrinter &AP) override;\n};\n\n} \/\/ end anonymous namespace\n\nstatic GCMetadataPrinterRegistry::Add<OcamlGCMetadataPrinter>\n    Y(\"ocaml\", \"ocaml 3.10-compatible collector\");\n\nvoid llvm::linkOcamlGCPrinter() {}\n\nstatic void EmitCamlGlobal(const Module &M, AsmPrinter &AP, const char *Id) {\n  const std::string &MId = M.getModuleIdentifier();\n\n  std::string SymName;\n  SymName += \"caml\";\n  size_t Letter = SymName.size();\n  SymName.append(MId.begin(), llvm::find(MId, '.'));\n  SymName += \"__\";\n  SymName += Id;\n\n  \/\/ Capitalize the first letter of the module name.\n  SymName[Letter] = toupper(SymName[Letter]);\n\n  SmallString<128> TmpStr;\n  Mangler::getNameWithPrefix(TmpStr, SymName, M.getDataLayout());\n\n  MCSymbol *Sym = AP.OutContext.getOrCreateSymbol(TmpStr);\n\n  AP.OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);\n  AP.OutStreamer->emitLabel(Sym);\n}\n\nvoid OcamlGCMetadataPrinter::beginAssembly(Module &M, GCModuleInfo &Info,\n                                           AsmPrinter &AP) {\n  AP.OutStreamer->SwitchSection(AP.getObjFileLowering().getTextSection());\n  EmitCamlGlobal(M, AP, \"code_begin\");\n\n  AP.OutStreamer->SwitchSection(AP.getObjFileLowering().getDataSection());\n  EmitCamlGlobal(M, AP, \"data_begin\");\n}\n\n\/\/\/ emitAssembly - Print the frametable. The ocaml frametable format is thus:\n\/\/\/\n\/\/\/   extern \"C\" struct align(sizeof(intptr_t)) {\n\/\/\/     uint16_t NumDescriptors;\n\/\/\/     struct align(sizeof(intptr_t)) {\n\/\/\/       void *ReturnAddress;\n\/\/\/       uint16_t FrameSize;\n\/\/\/       uint16_t NumLiveOffsets;\n\/\/\/       uint16_t LiveOffsets[NumLiveOffsets];\n\/\/\/     } Descriptors[NumDescriptors];\n\/\/\/   } caml${module}__frametable;\n\/\/\/\n\/\/\/ Note that this precludes programs from stack frames larger than 64K\n\/\/\/ (FrameSize and LiveOffsets would overflow). FrameTablePrinter will abort if\n\/\/\/ either condition is detected in a function which uses the GC.\n\/\/\/\nvoid OcamlGCMetadataPrinter::finishAssembly(Module &M, GCModuleInfo &Info,\n                                            AsmPrinter &AP) {\n  unsigned IntPtrSize = M.getDataLayout().getPointerSize();\n\n  AP.OutStreamer->SwitchSection(AP.getObjFileLowering().getTextSection());\n  EmitCamlGlobal(M, AP, \"code_end\");\n\n  AP.OutStreamer->SwitchSection(AP.getObjFileLowering().getDataSection());\n  EmitCamlGlobal(M, AP, \"data_end\");\n\n  \/\/ FIXME: Why does ocaml emit this??\n  AP.OutStreamer->emitIntValue(0, IntPtrSize);\n\n  AP.OutStreamer->SwitchSection(AP.getObjFileLowering().getDataSection());\n  EmitCamlGlobal(M, AP, \"frametable\");\n\n  int NumDescriptors = 0;\n  for (std::unique_ptr<GCFunctionInfo> &FI :\n       llvm::make_range(Info.funcinfo_begin(), Info.funcinfo_end())) {\n    if (FI->getStrategy().getName() != getStrategy().getName())\n      \/\/ this function is managed by some other GC\n      continue;\n    NumDescriptors += FI->size();\n  }\n\n  if (NumDescriptors >= 1 << 16) {\n    \/\/ Very rude!\n    report_fatal_error(\" Too much descriptor for ocaml GC\");\n  }\n  AP.emitInt16(NumDescriptors);\n  AP.emitAlignment(IntPtrSize == 4 ? Align(4) : Align(8));\n\n  for (std::unique_ptr<GCFunctionInfo> &FI :\n       llvm::make_range(Info.funcinfo_begin(), Info.funcinfo_end())) {\n    if (FI->getStrategy().getName() != getStrategy().getName())\n      \/\/ this function is managed by some other GC\n      continue;\n\n    uint64_t FrameSize = FI->getFrameSize();\n    if (FrameSize >= 1 << 16) {\n      \/\/ Very rude!\n      report_fatal_error(\"Function '\" + FI->getFunction().getName() +\n                         \"' is too large for the ocaml GC! \"\n                         \"Frame size \" +\n                         Twine(FrameSize) +\n                         \">= 65536.\\n\"\n                         \"(\" +\n                         Twine(reinterpret_cast<uintptr_t>(FI.get())) + \")\");\n    }\n\n    AP.OutStreamer->AddComment(\"live roots for \" +\n                               Twine(FI->getFunction().getName()));\n    AP.OutStreamer->AddBlankLine();\n\n    for (GCFunctionInfo::iterator J = FI->begin(), JE = FI->end(); J != JE;\n         ++J) {\n      size_t LiveCount = FI->live_size(J);\n      if (LiveCount >= 1 << 16) {\n        \/\/ Very rude!\n        report_fatal_error(\"Function '\" + FI->getFunction().getName() +\n                           \"' is too large for the ocaml GC! \"\n                           \"Live root count \" +\n                           Twine(LiveCount) + \" >= 65536.\");\n      }\n\n      AP.OutStreamer->emitSymbolValue(J->Label, IntPtrSize);\n      AP.emitInt16(FrameSize);\n      AP.emitInt16(LiveCount);\n\n      for (GCFunctionInfo::live_iterator K = FI->live_begin(J),\n                                         KE = FI->live_end(J);\n           K != KE; ++K) {\n        if (K->StackOffset >= 1 << 16) {\n          \/\/ Very rude!\n          report_fatal_error(\n              \"GC root stack offset is outside of fixed stack frame and out \"\n              \"of range for ocaml GC!\");\n        }\n        AP.emitInt16(K->StackOffset);\n      }\n\n      AP.emitAlignment(IntPtrSize == 4 ? Align(4) : Align(8));\n    }\n  }\n}\n","avg_line_length":34.7158469945,"max_line_length":80,"alphanum_fraction":0.619549819,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2806,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":18.0,"content":"\/*\n * Copyright (c) 2017-2018 ARM Limited.\n *\n * SPDX-License-Identifier: MIT\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n#include \"arm_compute\/runtime\/BlobMemoryPool.h\"\n\n#include \"arm_compute\/core\/Error.h\"\n#include \"arm_compute\/runtime\/IAllocator.h\"\n#include \"arm_compute\/runtime\/IMemoryPool.h\"\n#include \"arm_compute\/runtime\/Types.h\"\n#include \"support\/ToolchainSupport.h\"\n\n#include <vector>\n\nusing namespace arm_compute;\n\nBlobMemoryPool::BlobMemoryPool(IAllocator *allocator, std::vector<BlobInfo> blob_info)\n    : _allocator(allocator), _blobs(), _blob_info(std::move(blob_info))\n{\n    ARM_COMPUTE_ERROR_ON(!allocator);\n    allocate_blobs(_blob_info);\n}\n\nBlobMemoryPool::~BlobMemoryPool()\n{\n    ARM_COMPUTE_ERROR_ON(!_allocator);\n    free_blobs();\n}\n\nvoid BlobMemoryPool::acquire(MemoryMappings &handles)\n{\n    \/\/ Set memory to handlers\n    for(auto &handle : handles)\n    {\n        ARM_COMPUTE_ERROR_ON(handle.first == nullptr);\n        handle.first->set_region(_blobs[handle.second].get());\n    }\n}\n\nvoid BlobMemoryPool::release(MemoryMappings &handles)\n{\n    for(auto &handle : handles)\n    {\n        ARM_COMPUTE_ERROR_ON(handle.first == nullptr);\n        handle.first->set_region(nullptr);\n    }\n}\n\nMappingType BlobMemoryPool::mapping_type() const\n{\n    return MappingType::BLOBS;\n}\n\nstd::unique_ptr<IMemoryPool> BlobMemoryPool::duplicate()\n{\n    ARM_COMPUTE_ERROR_ON(!_allocator);\n    return support::cpp14::make_unique<BlobMemoryPool>(_allocator, _blob_info);\n}\n\nvoid BlobMemoryPool::allocate_blobs(const std::vector<BlobInfo> &blob_info)\n{\n    ARM_COMPUTE_ERROR_ON(!_allocator);\n\n    for(const auto &bi : blob_info)\n    {\n        _blobs.push_back(_allocator->make_region(bi.size, bi.alignment));\n    }\n}\n\nvoid BlobMemoryPool::free_blobs()\n{\n    _blobs.clear();\n}","avg_line_length":30.5,"max_line_length":86,"alphanum_fraction":0.7387740556,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4508,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":null,"content":"\/*\n  Morseo.cpp - Library for blinking Morse code.\n  Created by Louis O'Callaghan 2014.\n  http:\/\/louisocallaghan.com\n  Released into the public domain.\n*\/\n#include \"Arduino.h\"\n#include \"Morseo.h\"\n\nMorseo::Morseo(int pin)\n{\n  pinMode(pin, OUTPUT);\n  _pin = pin;\n}\n\n\/\/ supply a string and the program keys it to output in morse\nvoid Morseo::keyMessage(const char *message, keyCharacter callback)\n{\n  int i = 0;\n  while (message[i] != '\\0')\n  {\n    char next = message[i + 1];\n    if (message[i] == ' ')\n    {\n      delay(wordSpace);\n    }\n    else\n    {\n      \/\/ default behavior is to write to the pin specified in the constructor..\n      \/\/ not ultra-elegant but I think it will work\n      if (callback == NULL)\n        keyCharacterToPin(message[i]);\n      else\n        callback(message[i]);\n      \n      \/\/ if a non-whitespace character is next then wait a bit\n      if (next != '\\0' && next != ' ')\n        delay(charSpace);\n      \n      \/\/ if it's the end of the message then wait a bit longer before starting over\n      if (next == '\\0')\n        delay(messageSpace);\n    }\n    i++;\n  }\n}\n\n\/\/ takes a string representation of a morse letter and keys it\n\/\/ (periods and dashes only, like this: \"-.-\" for 'K')\nvoid Morseo::keyCharacterToPin(char letter)\n{\n  char morseString[maxMorseLength + 1]; \/\/ plus 1 for the null character\n  getMorse(letter, morseString);\n  \n  int i = 0;\n  while (morseString[i] != '\\0')\n  {\n    if (morseString[i] == '.')\n    {\n      keyPin(dot);\n    }\n    else if (morseString[i] == '-')\n    {\n      keyPin(dash);\n    }\n\n    \/\/ if this isn't end of string then wait a bit\n    if (morseString[++i] != '\\0')\n      delay(keySpace);\n  }\n  free(morseString);\n}\n\n\/\/ key on for some time period\nvoid Morseo::keyPin(int milliseconds)\n{\n  digitalWrite(_pin, HIGH);\n  delay(milliseconds);\n  digitalWrite(_pin, LOW);\n}\n\n\/\/ converts a character to a string of morse dots and dashes\n\/\/ ignores case and anything that's not 0-9 and a-z and space . , \/ @ ?\nvoid Morseo::getMorse(char character, char *buffer)\n{\n  if (character > 47 && character < 58)\n  {\n    getMorseNumber(character, buffer);\n    return;\n  }\n    \n  \/\/ toLower\n  if (character > 64 && character < 91)\n    character += 32;\n  \n  char* morseString;\n  \n  switch(character)\n  {\n    case 'a':\n      morseString = \".-\";\n      break;\n    case 'b':\n      morseString = \"-...\";\n      break;\n    case 'c':\n      morseString = \"-.-.\";\n      break;\n    case 'd':\n      morseString = \"-..\";\n      break;\n    case 'e':\n      morseString = \".\";\n      break;\n    case 'f':\n      morseString = \"..-.\";\n      break;\n    case 'g':\n      morseString = \"--.\";\n      break;\n    case 'h':\n      morseString = \"....\";\n      break;\n    case 'i':\n      morseString = \"..\";\n      break;\n    case 'j':\n      morseString = \".---\";\n      break;\n    case 'k':\n      morseString = \"-.-\";\n      break;\n    case 'l':\n      morseString = \".-..\";\n      break;\n    case 'm':\n      morseString = \"--\";\n      break;\n    case 'n':\n      morseString = \"-.\";\n      break;\n    case 'o':\n      morseString = \"---\";\n      break;\n    case 'p':\n      morseString = \".--.\";\n      break;\n    case 'q':\n      morseString = \"--.-\";\n      break;\n    case 'r':\n      morseString = \".-.\";\n      break;\n    case 's':\n      morseString = \"...\";\n      break;\n    case 't':\n      morseString = \"-\";\n      break;\n    case 'u':\n      morseString = \"..-\";\n      break;\n    case 'v':\n      morseString = \"...-\";\n      break;\n    case 'w':\n      morseString = \".--\";\n      break;\n    case 'x':\n      morseString = \"-..-\";\n      break;\n    case 'y':\n      morseString = \"-.--\";\n      break;\n    case 'z':\n      morseString = \"--..\";\n      break;\n    case '.':\n      morseString = \".-.-.-\";\n      break;\n    case ',':\n      morseString = \"--..--\";\n      break;\n    case '\/':\n      morseString = \"-..-.\";\n      break;\n    case '@':\n      morseString = \".--.-.\";\n      break;\n    case '?':\n      morseString = \"..--..\";\n      break;\n    case ' ':\n      morseString = \" \";\n      break;\n    default:\n      morseString = \"\";\n      break;\n  }\n  sprintf(buffer, morseString);\n}\n\n\/* trying to be clever and produce the pattern algorithmically:\n1: .----\n2: ..---\n3: ...--\n4: ....-\n5: .....\n6: -....\n7: --...\n8: ---..\n9: ----.\n0: -----\n*\/\nvoid Morseo::getMorseNumber(char const number, char *buffer)\n{\n    if (number < 48 || number > 57)\n      return;\n      \n    int i;\n    for (i = 0; i < 5; i++) {\n      buffer[i] = 45 + (((number - i > 48) && (number - i < 54)) ? 1 : 0);\n    }\n\n    buffer[5] = '\\0';\n}\n","avg_line_length":19.859030837,"max_line_length":83,"alphanum_fraction":0.5031055901,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4195,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit https:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"lightfactoryregistrar.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/modeling\/entity\/registerentityfactories.h\"\n#include \"renderer\/modeling\/light\/directionallight.h\"\n#include \"renderer\/modeling\/light\/lighttraits.h\"\n#include \"renderer\/modeling\/light\/maxomnilight.h\"\n#include \"renderer\/modeling\/light\/maxspotlight.h\"\n#include \"renderer\/modeling\/light\/pointlight.h\"\n#include \"renderer\/modeling\/light\/spotlight.h\"\n#include \"renderer\/modeling\/light\/sunlight.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/utility\/foreach.h\"\n#include \"foundation\/utility\/registrar.h\"\n\n\/\/ Standard headers.\n#include <cassert>\n#include <string>\n#include <utility>\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nAPPLESEED_DEFINE_APIARRAY(LightFactoryArray);\n\nstruct LightFactoryRegistrar::Impl\n{\n    Registrar<ILightFactory> m_registrar;\n};\n\nLightFactoryRegistrar::LightFactoryRegistrar(const SearchPaths& search_paths)\n  : impl(new Impl())\n{\n    reinitialize(search_paths);\n}\n\nLightFactoryRegistrar::~LightFactoryRegistrar()\n{\n    delete impl;\n}\n\nvoid LightFactoryRegistrar::reinitialize(const SearchPaths& search_paths)\n{\n    \/\/ The registrar must be cleared before the plugins are unloaded.\n    impl->m_registrar.clear();\n    unload_all_plugins();\n\n    \/\/ Register built-in factories.\n    register_factory(auto_release_ptr<FactoryType>(new DirectionalLightFactory()));\n    register_factory(auto_release_ptr<FactoryType>(new MaxOmniLightFactory()));\n    register_factory(auto_release_ptr<FactoryType>(new MaxSpotLightFactory()));\n    register_factory(auto_release_ptr<FactoryType>(new PointLightFactory()));\n    register_factory(auto_release_ptr<FactoryType>(new SpotLightFactory()));\n    register_factory(auto_release_ptr<FactoryType>(new SunLightFactory()));\n\n    \/\/ Register factories defined in plugins.\n    register_factories_from_plugins<Light>(\n        search_paths,\n        [this](void* plugin_entry_point)\n        {\n            auto create_fn = reinterpret_cast<ILightFactory* (*)()>(plugin_entry_point);\n            register_factory(foundation::auto_release_ptr<ILightFactory>(create_fn()));\n        });\n}\n\nLightFactoryArray LightFactoryRegistrar::get_factories() const\n{\n    FactoryArrayType factories;\n\n    for (const_each<Registrar<FactoryType>::Items> i = impl->m_registrar.items(); i; ++i)\n        factories.push_back(i->second);\n\n    return factories;\n}\n\nconst LightFactoryRegistrar::FactoryType* LightFactoryRegistrar::lookup(const char* name) const\n{\n    assert(name);\n    return impl->m_registrar.lookup(name);\n}\n\nvoid LightFactoryRegistrar::register_factory(auto_release_ptr<FactoryType> factory)\n{\n    const string model = factory->get_model();\n    impl->m_registrar.insert(model, move(factory));\n}\n\n}   \/\/ namespace renderer\n","avg_line_length":34.1056910569,"max_line_length":95,"alphanum_fraction":0.7620977354,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4052,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\ufeff#include \"winapi.h\"\n\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <deque>\n#include <utility>\n#include <algorithm>\n\n#include <cstdint>\n#include <cassert>\n\n#include \"agano.h\"\n#include <iterator>\n#include <functional>\n#include <type_traits>\n\nnamespace agano{\n  static_assert( std::is_trivial<wc_t>::value , \"wc_t is trivial\");\n  static_assert( std::is_standard_layout<wc_t>::value , \"wc_t is standard layout\" );\n\n  \/**\n     Textfragment \u3092 wc_t \u306b\u5206\u89e3\u3057\u3066\u3001container \u306b\u8a70\u3081\u308b\n   *\/\n  template< typename allocator_t,\n            template<typename,typename>\n            class Container_Type>\n  static inline Container_Type<wc_t,allocator_t>&\n  copy_from( Container_Type<wc_t,allocator_t>& dst ,const TextFragment& fragment )\n  {\n    using bind_member_t =std::remove_reference<decltype(dst)>::type;\n    std::for_each( std::begin( fragment.text ), std::end( fragment.text ) ,\n                   std::bind( &(bind_member_t::emplace_back<const wchar_t&,const wc_attribute&>) ,\n                              &dst , std::placeholders::_1 , fragment.attr) );\n    return dst;\n  }\n\n  \/**\n     \u30b3\u30f3\u30c6\u30ca\u306e\u4e2d\u306e [first,last) \u306eTextFragment \u3092 wc_t \u306b\u5206\u89e3\u3057\u3066\u3001container \u306b\u8a70\u3081\u308b\n   *\/\n  template< typename allocator_t,\n            template<typename,typename> class Container_Type ,\n            typename InputIterator >\n  static inline Container_Type<wc_t,allocator_t>&\n  copy_from( Container_Type<wc_t,allocator_t>&dst , InputIterator first , InputIterator last )\n  {\n    std::for_each( first , last ,\n                   [&]( std::add_const<decltype(*first )>::type &fragment ){\n                     copy_from( dst , fragment );\n                   } );\n    return dst;\n  }\n\n  std::deque<wc_t> to_wc_t( const std::deque<TextFragment>& fragments )\n  {\n    std::deque<wc_t> deque;\n    return copy_from( deque , std::begin( fragments ) , std::end( fragments ) );\n  }\n  \n  std::deque<wc_t> to_wc_t( const TextFragment& fragment )\n  {\n    std::deque<wc_t> deque{};\n    return copy_from( deque , fragment );\n  }\n\n  std::deque<wc_t> clip_paragraph( std::deque<TextFragment>& fragments )\n  {\n    std::deque<wc_t> buf;\n    auto rbegin = fragments.rbegin();\n\n\n    if( rbegin != fragments.rend() && (rbegin->terminate) ){\n        std::advance( rbegin,1 );\n    }\n    \n    auto ite = std::find_if( rbegin , fragments.rend() ,\n                              []( const TextFragment& fragment ){\n                                return fragment.terminate;\n                              } );\n     if( fragments.rend() == ite ){\n       copy_from( buf , std::begin( fragments ), std::end( fragments ) );\n       fragments.clear();\n     }else{\n       if( fragments.rbegin() == ite ){\n         std::advance( rbegin , -1 );\n       }\n       copy_from( buf ,\n                  std::make_reverse_iterator( ite ),\n                  std::make_reverse_iterator( fragments.rbegin() ) );\n       {\n         auto pos = std::cbegin(fragments);\n         std::advance( pos , ( fragments.size() - std::distance( fragments.rbegin(), ite ) ) );\n         fragments.erase( pos );\n       }\n     }\n    return buf;\n  }\n\n  void do_check()\n  {\n    ::OutputDebugString( TEXT(\"do_check()\\n\") );\n    std::deque<TextFragment> deq{};\n    {\n      auto deq_wc = clip_paragraph( deq );\n      std::cout << deq_wc.size() << std::endl;\n    }\n    {\n      {\n        TextFragment one = {L\"\uff11\u884c\u76ee\\n\", wc_attribute{} };\n        one.terminate = true;\n        deq.push_back( one );\n      }\n      {\n        TextFragment twoo = {L\"\uff12\u884c\u76ee\u524d\u534a\" , wc_attribute{} };\n        deq.push_back( twoo );\n      }\n      {\n        TextFragment two = {L\"\uff12\u884c\u76ee\u5f8c\u534a\\n\", wc_attribute{} };\n        two.terminate = true;\n        deq.push_back( two );\n      }\n      for( size_t i = 0; i< 4 ; ++i ){\n        auto deq_wc = clip_paragraph( deq );\n        std::cout << deq_wc.size() << std::endl;\n        std::wstring buf;\n        std::for_each( std::begin( deq_wc ), std::end( deq_wc ),\n                       [&buf]( const wc_t & c ){\n                         buf.push_back( c.c );\n                       });\n        OutputDebugStringW( buf.c_str() );\n      }\n      \n    }\n  }\n};\n\n","avg_line_length":29.5766423358,"max_line_length":98,"alphanum_fraction":0.5629318855,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4758,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":192.0,"content":"\/* ------------------------------------------------------------------\n * Copyright (C) 1998-2009 PacketVideo\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied.\n * See the License for the specific language governing permissions\n * and limitations under the License.\n * -------------------------------------------------------------------\n *\/\n\/****************************************************************************************\nPortions of this file are derived from the following 3GPP standard:\n\n    3GPP TS 26.073\n    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec\n    Available from http:\/\/www.3gpp.org\n\n(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)\nPermission to distribute, modify and use this file under the standard license\nterms listed above has been obtained from the copyright holder.\n****************************************************************************************\/\n\/*\n\n Filename: inv_sqrt_tbl.cpp\n\n------------------------------------------------------------------------------\n MODULE DESCRIPTION\n\n This file contains the declaration for table[] used by the inv_sqrt function.\n\n------------------------------------------------------------------------------\n*\/\n\n\/*----------------------------------------------------------------------------\n; INCLUDES\n----------------------------------------------------------------------------*\/\n#include \"inv_sqrt.h\"\n\n\/*--------------------------------------------------------------------------*\/\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n    \/*----------------------------------------------------------------------------\n    ; MACROS\n    ; [Define module specific macros here]\n    ----------------------------------------------------------------------------*\/\n\n    \/*----------------------------------------------------------------------------\n    ; DEFINES\n    ; [Include all pre-processor statements here. Include conditional\n    ; compile variables also.]\n    ----------------------------------------------------------------------------*\/\n\n    \/*----------------------------------------------------------------------------\n    ; LOCAL FUNCTION DEFINITIONS\n    ; [List function prototypes here]\n    ----------------------------------------------------------------------------*\/\n\n    \/*----------------------------------------------------------------------------\n    ; LOCAL VARIABLE DEFINITIONS\n    ; [Variable declaration - defined here and used outside this module]\n    ----------------------------------------------------------------------------*\/\n    const Word16 inv_sqrt_tbl[49] =\n    {\n\n        32767, 31790, 30894, 30070, 29309, 28602, 27945, 27330, 26755, 26214,\n        25705, 25225, 24770, 24339, 23930, 23541, 23170, 22817, 22479, 22155,\n        21845, 21548, 21263, 20988, 20724, 20470, 20225, 19988, 19760, 19539,\n        19326, 19119, 18919, 18725, 18536, 18354, 18176, 18004, 17837, 17674,\n        17515, 17361, 17211, 17064, 16921, 16782, 16646, 16514, 16384\n    };\n\n    \/*--------------------------------------------------------------------------*\/\n#ifdef __cplusplus\n}\n#endif\n\n\/*\n------------------------------------------------------------------------------\n FUNCTION NAME:\n------------------------------------------------------------------------------\n INPUT AND OUTPUT DEFINITIONS\n\n Inputs:\n    None\n\n Outputs:\n    None\n\n Returns:\n    None\n\n Global Variables Used:\n    None\n\n Local Variables Needed:\n    None\n\n------------------------------------------------------------------------------\n FUNCTION DESCRIPTION\n\n None\n\n------------------------------------------------------------------------------\n REQUIREMENTS\n\n None\n\n------------------------------------------------------------------------------\n REFERENCES\n\n [1] inv_sqrt.tab file,  UMTS GSM AMR speech codec, R99 - Version 3.2.0,\n March 2, 2001\n\n------------------------------------------------------------------------------\n PSEUDO-CODE\n\n\n------------------------------------------------------------------------------\n CAUTION [optional]\n [State any special notes, constraints or cautions for users of this function]\n\n------------------------------------------------------------------------------\n*\/\n\n\/*----------------------------------------------------------------------------\n; FUNCTION CODE\n----------------------------------------------------------------------------*\/\n\n","avg_line_length":34.2302158273,"max_line_length":89,"alphanum_fraction":0.3724253888,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":762,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\n#include \"Binding_pch.h\"\n\n\nusing namespace glsc;\n\n\nnamespace glscbinding\n{\n\n\nFunction<void, GLfloat, GLboolean> Binding::SampleCoverage(\"glSampleCoverage\");\nFunction<void, GLint, GLint, GLsizei, GLsizei> Binding::Scissor(\"glScissor\");\nFunction<void, GLenum, GLint, GLuint> Binding::StencilFunc(\"glStencilFunc\");\nFunction<void, GLenum, GLenum, GLint, GLuint> Binding::StencilFuncSeparate(\"glStencilFuncSeparate\");\nFunction<void, GLuint> Binding::StencilMask(\"glStencilMask\");\nFunction<void, GLenum, GLuint> Binding::StencilMaskSeparate(\"glStencilMaskSeparate\");\nFunction<void, GLenum, GLenum, GLenum> Binding::StencilOp(\"glStencilOp\");\nFunction<void, GLenum, GLenum, GLenum, GLenum> Binding::StencilOpSeparate(\"glStencilOpSeparate\");\n\n\n} \/\/ namespace glscbinding","avg_line_length":34.6363636364,"max_line_length":100,"alphanum_fraction":0.7860892388,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4721,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":2.0,"content":"\/*\n * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"RectangleTool.h\"\n#include \"ImageEditor.h\"\n#include \"Layer.h\"\n#include <LibGUI\/Action.h>\n#include <LibGUI\/Menu.h>\n#include <LibGUI\/Painter.h>\n#include <LibGfx\/Rect.h>\n#include <math.h>\n\nnamespace PixelPaint {\n\nRectangleTool::RectangleTool()\n{\n}\n\nRectangleTool::~RectangleTool()\n{\n}\n\nvoid RectangleTool::draw_using(GUI::Painter& painter, const Gfx::IntRect& rect)\n{\n    switch (m_mode) {\n    case Mode::Fill:\n        painter.fill_rect(rect, m_editor->color_for(m_drawing_button));\n        break;\n    case Mode::Outline:\n        painter.draw_rect(rect, m_editor->color_for(m_drawing_button));\n        break;\n    case Mode::Gradient:\n        painter.fill_rect_with_gradient(rect, m_editor->primary_color(), m_editor->secondary_color());\n        break;\n    default:\n        VERIFY_NOT_REACHED();\n    }\n}\n\nvoid RectangleTool::on_mousedown(Layer&, GUI::MouseEvent& event, GUI::MouseEvent&)\n{\n    if (event.button() != GUI::MouseButton::Left && event.button() != GUI::MouseButton::Right)\n        return;\n\n    if (m_drawing_button != GUI::MouseButton::None)\n        return;\n\n    m_drawing_button = event.button();\n    m_rectangle_start_position = event.position();\n    m_rectangle_end_position = event.position();\n    m_editor->update();\n}\n\nvoid RectangleTool::on_mouseup(Layer& layer, GUI::MouseEvent& event, GUI::MouseEvent&)\n{\n    if (event.button() == m_drawing_button) {\n        GUI::Painter painter(layer.bitmap());\n        auto rect = Gfx::IntRect::from_two_points(m_rectangle_start_position, m_rectangle_end_position);\n        draw_using(painter, rect);\n        m_drawing_button = GUI::MouseButton::None;\n        layer.did_modify_bitmap(*m_editor->image());\n        m_editor->did_complete_action();\n    }\n}\n\nvoid RectangleTool::on_mousemove(Layer&, GUI::MouseEvent& event, GUI::MouseEvent&)\n{\n    if (m_drawing_button == GUI::MouseButton::None)\n        return;\n\n    m_rectangle_end_position = event.position();\n    m_editor->update();\n}\n\nvoid RectangleTool::on_second_paint(const Layer& layer, GUI::PaintEvent& event)\n{\n    if (m_drawing_button == GUI::MouseButton::None)\n        return;\n\n    GUI::Painter painter(*m_editor);\n    painter.add_clip_rect(event.rect());\n    auto rect = Gfx::IntRect::from_two_points(\n        m_editor->layer_position_to_editor_position(layer, m_rectangle_start_position).to_type<int>(),\n        m_editor->layer_position_to_editor_position(layer, m_rectangle_end_position).to_type<int>());\n    draw_using(painter, rect);\n}\n\nvoid RectangleTool::on_keydown(GUI::KeyEvent& event)\n{\n    if (event.key() == Key_Escape && m_drawing_button != GUI::MouseButton::None) {\n        m_drawing_button = GUI::MouseButton::None;\n        m_editor->update();\n        event.accept();\n    }\n}\n\nvoid RectangleTool::on_tool_button_contextmenu(GUI::ContextMenuEvent& event)\n{\n    if (!m_context_menu) {\n        m_context_menu = GUI::Menu::construct();\n        m_context_menu->add_action(GUI::Action::create(\"Fill\", [this](auto&) {\n            m_mode = Mode::Fill;\n        }));\n        m_context_menu->add_action(GUI::Action::create(\"Outline\", [this](auto&) {\n            m_mode = Mode::Outline;\n        }));\n        m_context_menu->add_action(GUI::Action::create(\"Gradient\", [this](auto&) {\n            m_mode = Mode::Gradient;\n        }));\n    }\n    m_context_menu->popup(event.screen_position());\n}\n\n}\n","avg_line_length":34.2101449275,"max_line_length":104,"alphanum_fraction":0.6990044482,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8651,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":117.0,"content":"\/* \nCopyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved.\n \nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n \nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n \nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\n#include\"publishkernels.h\"\n\n\/************************************************************************************************************\ninput parameter validator.\nparam [in] node The handle to the node.\nparam [in] index The index of the parameter to validate.\n*************************************************************************************************************\/\nvx_status VX_CALLBACK CV_bilateralFilter_InputValidator(vx_node node, vx_uint32 index)\n{\n\tvx_status status = VX_SUCCESS;\n\tvx_parameter param = vxGetParameterByIndex(node, index);\n\n\tif (index == 0)\n\t{\n\t\tvx_image image;\n\t\tvx_df_image df_image = VX_DF_IMAGE_VIRT;\n\t\tSTATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &image, sizeof(vx_image)));\n\t\tSTATUS_ERROR_CHECK(vxQueryImage(image, VX_IMAGE_ATTRIBUTE_FORMAT, &df_image, sizeof(df_image)));\n\t\tif (df_image != VX_DF_IMAGE_U8)\n\t\t\tstatus = VX_ERROR_INVALID_VALUE;\n\t\tvxReleaseImage(&image);\n\t}\n\n\telse if (index == 1)\n\t{\n\t\tvx_image image;\n\t\tvx_df_image df_image = VX_DF_IMAGE_VIRT;\n\t\tSTATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &image, sizeof(vx_image)));\n\t\tSTATUS_ERROR_CHECK(vxQueryImage(image, VX_IMAGE_ATTRIBUTE_FORMAT, &df_image, sizeof(df_image)));\n\t\tif (df_image != VX_DF_IMAGE_U8)\n\t\t\tstatus = VX_ERROR_INVALID_VALUE;\n\t\tvxReleaseImage(&image);\n\t}\n\telse if (index == 2)\n\t{\n\t\tvx_scalar scalar = 0; vx_enum type = 0;\tvx_int32 value = 0;\n\t\tSTATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &scalar, sizeof(scalar)));\n\t\tSTATUS_ERROR_CHECK(vxQueryScalar(scalar, VX_SCALAR_ATTRIBUTE_TYPE, &type, sizeof(type)));\n\t\tSTATUS_ERROR_CHECK(vxReadScalarValue(scalar, &value));\n\t\tif (value < 0 || (value % 2 == 0) || type != VX_TYPE_INT32)\n\t\t\tstatus = VX_ERROR_INVALID_VALUE;\n\t\tvxReleaseScalar(&scalar);\n\t}\n\n\telse if (index == 3)\n\t{\n\t\tvx_scalar scalar = 0; vx_enum type = 0;\tvx_float32 value = 0;\n\t\tSTATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &scalar, sizeof(scalar)));\n\t\tSTATUS_ERROR_CHECK(vxQueryScalar(scalar, VX_SCALAR_ATTRIBUTE_TYPE, &type, sizeof(type)));\n\t\tSTATUS_ERROR_CHECK(vxReadScalarValue(scalar, &value));\n\t\tif (value < 0 || type != VX_TYPE_FLOAT32)\n\t\t\tstatus = VX_ERROR_INVALID_VALUE;\n\t\tvxReleaseScalar(&scalar);\n\t}\n\n\telse if (index == 4)\n\t{\n\t\tvx_scalar scalar = 0; vx_enum type = 0;\tvx_float32 value = 0;\n\t\tSTATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &scalar, sizeof(scalar)));\n\t\tSTATUS_ERROR_CHECK(vxQueryScalar(scalar, VX_SCALAR_ATTRIBUTE_TYPE, &type, sizeof(type)));\n\t\tSTATUS_ERROR_CHECK(vxReadScalarValue(scalar, &value));\n\t\tif (value < 0 || type != VX_TYPE_FLOAT32)\n\t\t\tstatus = VX_ERROR_INVALID_VALUE;\n\t\tvxReleaseScalar(&scalar);\n\t}\n\n\telse if (index == 5)\n\t{\n\t\tvx_scalar scalar = 0; vx_enum type = 0;\tvx_int32 value = 0;\n\t\tSTATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &scalar, sizeof(scalar)));\n\t\tSTATUS_ERROR_CHECK(vxQueryScalar(scalar, VX_SCALAR_ATTRIBUTE_TYPE, &type, sizeof(type)));\n\t\tSTATUS_ERROR_CHECK(vxReadScalarValue(scalar, &value));\n\t\tif (value < 0 || type != VX_TYPE_INT32)\n\t\t\tstatus = VX_ERROR_INVALID_VALUE;\n\t\tvxReleaseScalar(&scalar);\n\t}\n\n\tvxReleaseParameter(&param);\n\treturn status;\n}\n\n\/************************************************************************************************************\noutput parameter validator.\n*************************************************************************************************************\/\nvx_status VX_CALLBACK CV_bilateralFilter_OutputValidator(vx_node node, vx_uint32 index, vx_meta_format meta)\n{\n\tvx_status status = VX_SUCCESS;\n\tif (index == 1)\n\t{\n\t\tvx_parameter output_param = vxGetParameterByIndex(node, 1);\n\t\tvx_image output; vx_uint32 width = 0, height = 0; vx_df_image format = VX_DF_IMAGE_VIRT;\n\n\t\tSTATUS_ERROR_CHECK(vxQueryParameter(output_param, VX_PARAMETER_ATTRIBUTE_REF, &output, sizeof(vx_image)));\n\t\tSTATUS_ERROR_CHECK(vxQueryImage(output, VX_IMAGE_ATTRIBUTE_FORMAT, &format, sizeof(format)));\n\t\tSTATUS_ERROR_CHECK(vxQueryImage(output, VX_IMAGE_ATTRIBUTE_WIDTH, &width, sizeof(width)));\n\t\tSTATUS_ERROR_CHECK(vxQueryImage(output, VX_IMAGE_ATTRIBUTE_HEIGHT, &height, sizeof(height)));\n\n\t\tif (format != VX_DF_IMAGE_U8)\n\t\t\tstatus = VX_ERROR_INVALID_VALUE;\n\n\t\tSTATUS_ERROR_CHECK(vxSetMetaFormatAttribute(meta, VX_IMAGE_ATTRIBUTE_WIDTH, &width, sizeof(width)));\n\t\tSTATUS_ERROR_CHECK(vxSetMetaFormatAttribute(meta, VX_IMAGE_ATTRIBUTE_HEIGHT, &height, sizeof(height)));\n\t\tSTATUS_ERROR_CHECK(vxSetMetaFormatAttribute(meta, VX_IMAGE_ATTRIBUTE_FORMAT, &format, sizeof(format)));\n\n\t\tvxReleaseImage(&output);\n\t\tvxReleaseParameter(&output_param);\n\t}\n\treturn status;\n}\n\n\/************************************************************************************************************\nExecution Kernel\n*************************************************************************************************************\/\nvx_status VX_CALLBACK CV_bilateralFilter_Kernel(vx_node node, const vx_reference *parameters, vx_uint32 num)\n{\n\tvx_status status = VX_SUCCESS;\n\n\tvx_image image_in = (vx_image) parameters[0];\n\tvx_image image_out = (vx_image) parameters[1];\n\tvx_scalar D = (vx_scalar) parameters[2];\n\tvx_scalar SIGMA_C = (vx_scalar) parameters[3];\n\tvx_scalar SIGMA_S = (vx_scalar) parameters[4];\n\tvx_scalar BORDER = (vx_scalar) parameters[5];\n\n\tMat *mat, bl;\n\tint  d, Border;\n\tfloat Sigma_Color, Sigma_Space;\n\n\tvx_int32 value = 0;\n\tvx_float32 value_f = 0;\n\n\t\/\/Extracting Values from the Scalar into Ksize and Ddepth\n\tSTATUS_ERROR_CHECK(vxReadScalarValue(D, &value)); d = value;\n\tSTATUS_ERROR_CHECK(vxReadScalarValue(SIGMA_C, &value_f)); Sigma_Color = value_f;\n\tSTATUS_ERROR_CHECK(vxReadScalarValue(SIGMA_S, &value_f)); Sigma_Space = value_f;\n\tSTATUS_ERROR_CHECK(vxReadScalarValue(BORDER, &value)); Border = value;\n\n\t\/\/Converting VX Image to OpenCV Mat\n\tSTATUS_ERROR_CHECK(match_vx_image_parameters(image_in, image_out));\n\tSTATUS_ERROR_CHECK(VX_to_CV_Image(&mat, image_in));\n\n\t\/\/Compute using OpenCV\n\tcv::bilateralFilter(*mat, bl, d, Sigma_Color, Sigma_Space, Border);\n\n\t\/\/Converting OpenCV Mat into VX Image\n\tSTATUS_ERROR_CHECK(CV_to_VX_Image(image_out, &bl));\n\n\treturn status;\n}\n\n\/************************************************************************************************************\nFunction to Register the Kernel for Publish\n*************************************************************************************************************\/\nvx_status CV_bilateralFilter_Register(vx_context context)\n{\n\tvx_status status = VX_SUCCESS;\n\tvx_kernel kernel = vxAddKernel(context,\n\t\t\"org.opencv.bilateralfilter\",\n\t\tVX_KERNEL_OPENCV_BILATERAL_FILTER,\n\t\tCV_bilateralFilter_Kernel,\n\t\t6,\n\t\tCV_bilateralFilter_InputValidator,\n\t\tCV_bilateralFilter_OutputValidator,\n\t\tnullptr,\n\t\tnullptr);\n\n\tif (kernel)\n\t{\n\t\tPARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 0, VX_INPUT, VX_TYPE_IMAGE, VX_PARAMETER_STATE_REQUIRED));\n\t\tPARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 1, VX_OUTPUT, VX_TYPE_IMAGE, VX_PARAMETER_STATE_REQUIRED));\n\t\tPARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 2, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));\n\t\tPARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 3, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));\n\t\tPARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 4, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));\n\t\tPARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 5, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));\n\t\tPARAM_ERROR_CHECK(vxFinalizeKernel(kernel));\n\t}\n\n\tif (status != VX_SUCCESS)\n\t{\n\texit:\tvxRemoveKernel(kernel); return VX_FAILURE;\n\t}\n\n\treturn status;\n}\n","avg_line_length":41.5913461538,"max_line_length":110,"alphanum_fraction":0.7026933303,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2752,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/*\n * Copyright (c) 2016, 2017 ARM Limited.\n *\n * SPDX-License-Identifier: MIT\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n#include \"arm_compute\/runtime\/CL\/CLTensorAllocator.h\"\n\n#include \"arm_compute\/core\/Error.h\"\n#include \"arm_compute\/core\/TensorInfo.h\"\n#include \"arm_compute\/runtime\/CL\/CLScheduler.h\"\n\nusing namespace arm_compute;\n\nCLTensorAllocator::CLTensorAllocator()\n    : _buffer(), _mapping(nullptr)\n{\n}\n\nuint8_t *CLTensorAllocator::data()\n{\n    return _mapping;\n}\n\nconst cl::Buffer &CLTensorAllocator::cl_data() const\n{\n    return _buffer;\n}\n\nvoid CLTensorAllocator::allocate()\n{\n    ARM_COMPUTE_ERROR_ON(_buffer.get() != nullptr);\n\n    _buffer = cl::Buffer(CLScheduler::get().context(), CL_MEM_ALLOC_HOST_PTR | CL_MEM_READ_WRITE, info().total_size());\n    info().set_is_resizable(false);\n}\n\nvoid CLTensorAllocator::free()\n{\n    ARM_COMPUTE_ERROR_ON(_buffer.get() == nullptr);\n\n    _buffer = cl::Buffer();\n    info().set_is_resizable(true);\n}\n\nuint8_t *CLTensorAllocator::lock()\n{\n    ARM_COMPUTE_ERROR_ON(_mapping != nullptr);\n    _mapping = map(CLScheduler::get().queue(), true);\n    return _mapping;\n}\n\nvoid CLTensorAllocator::unlock()\n{\n    ARM_COMPUTE_ERROR_ON(_mapping == nullptr);\n    unmap(CLScheduler::get().queue(), _mapping);\n    _mapping = nullptr;\n}\n\nuint8_t *CLTensorAllocator::map(cl::CommandQueue &q, bool blocking)\n{\n    ARM_COMPUTE_ERROR_ON(_buffer.get() == nullptr);\n    return static_cast<uint8_t *>(q.enqueueMapBuffer(_buffer, blocking ? CL_TRUE : CL_FALSE, CL_MAP_READ | CL_MAP_WRITE, 0, info().total_size()));\n}\n\nvoid CLTensorAllocator::unmap(cl::CommandQueue &q, uint8_t *mapping)\n{\n    ARM_COMPUTE_ERROR_ON(_buffer.get() == nullptr);\n    q.enqueueUnmapMemObject(_buffer, mapping);\n}\n","avg_line_length":31.2727272727,"max_line_length":146,"alphanum_fraction":0.7372819767,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5078,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":6.0,"content":"\/*\n    Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)\n    Copyright (C) 2001 Dirk Mueller (mueller@kde.org)\n    Copyright (C) 2002 Waldo Bastian (bastian@kde.org)\n    Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)\n    Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public License\n    along with this library; see the file COPYING.LIB.  If not, write to\n    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n    Boston, MA 02110-1301, USA.\n\n    This class provides all functionality needed for loading images, style sheets and html\n    pages from the web. It has a memory cache for these objects.\n*\/\n\n#include \"config.h\"\n#include \"CachedCSSStyleSheet.h\"\n\n#include \"CachedResourceClient.h\"\n#include \"CachedResourceClientWalker.h\"\n#include \"HTTPParsers.h\"\n#include \"TextResourceDecoder.h\"\n#include \"SharedBuffer.h\"\n#include \"loader.h\"\n#include <wtf\/Vector.h>\n\nnamespace WebCore {\n\nCachedCSSStyleSheet::CachedCSSStyleSheet(const String& url, const String& charset)\n    : CachedResource(url, CSSStyleSheet)\n    , m_decoder(TextResourceDecoder::create(\"text\/css\", charset))\n{\n    \/\/ Prefer text\/css but accept any type (dell.com serves a stylesheet\n    \/\/ as text\/html; see <http:\/\/bugs.webkit.org\/show_bug.cgi?id=11451>).\n    setAccept(\"text\/css,*\/*;q=0.1\");\n}\n\nCachedCSSStyleSheet::~CachedCSSStyleSheet()\n{\n}\n\nvoid CachedCSSStyleSheet::didAddClient(CachedResourceClient *c)\n{\n    if (!m_loading)\n        c->setCSSStyleSheet(m_url, m_response.url(), m_decoder->encoding().name(), this);\n}\n\nvoid CachedCSSStyleSheet::allClientsRemoved()\n{\n    if (isSafeToMakePurgeable())\n        makePurgeable(true);\n}\n\nvoid CachedCSSStyleSheet::setEncoding(const String& chs)\n{\n    m_decoder->setEncoding(chs, TextResourceDecoder::EncodingFromHTTPHeader);\n}\n\nString CachedCSSStyleSheet::encoding() const\n{\n    return m_decoder->encoding().name();\n}\n    \nconst String CachedCSSStyleSheet::sheetText(bool enforceMIMEType, bool* hasValidMIMEType) const \n{ \n    ASSERT(!isPurgeable());\n\n    if (!m_data || m_data->isEmpty() || !canUseSheet(enforceMIMEType, hasValidMIMEType))\n        return String();\n    \n    if (!m_decodedSheetText.isNull())\n        return m_decodedSheetText;\n    \n    \/\/ Don't cache the decoded text, regenerating is cheap and it can use quite a bit of memory\n    String sheetText = m_decoder->decode(m_data->data(), m_data->size());\n    sheetText += m_decoder->flush();\n    return sheetText;\n}\n\nvoid CachedCSSStyleSheet::data(PassRefPtr<SharedBuffer> data, bool allDataReceived)\n{\n    if (!allDataReceived)\n        return;\n\n    m_data = data;\n    setEncodedSize(m_data.get() ? m_data->size() : 0);\n    \/\/ Decode the data to find out the encoding and keep the sheet text around during checkNotify()\n    if (m_data) {\n        m_decodedSheetText = m_decoder->decode(m_data->data(), m_data->size());\n        m_decodedSheetText += m_decoder->flush();\n    }\n    m_loading = false;\n    checkNotify();\n    \/\/ Clear the decoded text as it is unlikely to be needed immediately again and is cheap to regenerate.\n    m_decodedSheetText = String();\n}\n\nvoid CachedCSSStyleSheet::checkNotify()\n{\n    if (m_loading)\n        return;\n\n    CachedResourceClientWalker w(m_clients);\n    while (CachedResourceClient *c = w.next())\n        c->setCSSStyleSheet(m_url, m_response.url(), m_decoder->encoding().name(), this);\n}\n\nvoid CachedCSSStyleSheet::error()\n{\n    m_loading = false;\n    m_errorOccurred = true;\n    checkNotify();\n}\n\nbool CachedCSSStyleSheet::canUseSheet(bool enforceMIMEType, bool* hasValidMIMEType) const\n{\n    if (errorOccurred())\n        return false;\n        \n    if (!enforceMIMEType && !hasValidMIMEType)\n        return true;\n\n    \/\/ This check exactly matches Firefox.  Note that we grab the Content-Type\n    \/\/ header directly because we want to see what the value is BEFORE content\n    \/\/ sniffing.  Firefox does this by setting a \"type hint\" on the channel.\n    \/\/ This implementation should be observationally equivalent.\n    \/\/\n    \/\/ This code defaults to allowing the stylesheet for non-HTTP protocols so\n    \/\/ folks can use standards mode for local HTML documents.\n    String mimeType = extractMIMETypeFromMediaType(response().httpHeaderField(\"Content-Type\"));\n    bool typeOK = mimeType.isEmpty() || equalIgnoringCase(mimeType, \"text\/css\") || equalIgnoringCase(mimeType, \"application\/x-unknown-content-type\");\n    if (hasValidMIMEType)\n        *hasValidMIMEType = typeOK;\n    if (!enforceMIMEType)\n        return true;\n    return typeOK;\n}\n \n}\n","avg_line_length":33.6291390728,"max_line_length":149,"alphanum_fraction":0.7120913746,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1582,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/\n\/\/ Copyright (c) 2008-2016 the Urho3D project.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include \"..\/IK\/IK.h\"\n#include \"..\/IK\/IKConstraint.h\"\n#include \"..\/IK\/IKEffector.h\"\n#include \"..\/IK\/IKSolver.h\"\n\nnamespace Cross\n{\n\nconst char* IK_CATEGORY = \"Inverse Kinematics\";\n\n\/\/ ----------------------------------------------------------------------------\nvoid RegisterIKLibrary(Context* context)\n{\n    \/\/IKConstraint::RegisterObject(context);\n    IKEffector::RegisterObject(context);\n    IKSolver::RegisterObject(context);\n}\n\n} \/\/ namespace Cross\n","avg_line_length":37.6666666667,"max_line_length":80,"alphanum_fraction":0.711125158,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4293,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"sendcoinsentry.h\"\n#include \"ui_sendcoinsentry.h\"\n#include \"guiutil.h\"\n#include \"bitcoinunits.h\"\n#include \"addressbookpage.h\"\n#include \"walletmodel.h\"\n#include \"optionsmodel.h\"\n#include \"addresstablemodel.h\"\n\n#include <QApplication>\n#include <QClipboard>\n\nSendCoinsEntry::SendCoinsEntry(QWidget *parent) :\n    QFrame(parent),\n    ui(new Ui::SendCoinsEntry),\n    model(0)\n{\n    ui->setupUi(this);\n\n#ifdef Q_OS_MAC\n    ui->payToLayout->setSpacing(4);\n#endif\n#if QT_VERSION >= 0x040700\n    \/* Do not move this to the XML file, Qt before 4.7 will choke on it *\/\n    ui->addAsLabel->setPlaceholderText(tr(\"Enter a label for this address to add it to your address book\"));\n    ui->payTo->setPlaceholderText(tr(\"Enter a EGAME address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)\"));\n#endif\n    setFocusPolicy(Qt::TabFocus);\n    setFocusProxy(ui->payTo);\n\n    GUIUtil::setupAddressWidget(ui->payTo, this);\n}\n\nSendCoinsEntry::~SendCoinsEntry()\n{\n    delete ui;\n}\n\nvoid SendCoinsEntry::on_pasteButton_clicked()\n{\n    \/\/ Paste text from clipboard into recipient field\n    ui->payTo->setText(QApplication::clipboard()->text());\n}\n\nvoid SendCoinsEntry::on_addressBookButton_clicked()\n{\n    if(!model)\n        return;\n    AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);\n    dlg.setModel(model->getAddressTableModel());\n    if(dlg.exec())\n    {\n        ui->payTo->setText(dlg.getReturnValue());\n        ui->payAmount->setFocus();\n    }\n}\n\nvoid SendCoinsEntry::on_payTo_textChanged(const QString &address)\n{\n    if(!model)\n        return;\n    \/\/ Fill in label from address book, if address has an associated label\n    QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);\n    if(!associatedLabel.isEmpty())\n        ui->addAsLabel->setText(associatedLabel);\n}\n\nvoid SendCoinsEntry::setModel(WalletModel *model)\n{\n    this->model = model;\n\n    if(model && model->getOptionsModel())\n        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n\n    connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));\n\n    clear();\n}\n\nvoid SendCoinsEntry::setRemoveEnabled(bool enabled)\n{\n    ui->deleteButton->setEnabled(enabled);\n}\n\nvoid SendCoinsEntry::clear()\n{\n    ui->payTo->clear();\n    ui->addAsLabel->clear();\n    ui->payAmount->clear();\n    ui->payTo->setFocus();\n    \/\/ update the display unit, to not use the default (\"BTC\")\n    updateDisplayUnit();\n}\n\nvoid SendCoinsEntry::on_deleteButton_clicked()\n{\n    emit removeEntry(this);\n}\n\nbool SendCoinsEntry::validate()\n{\n    \/\/ Check input validity\n    bool retval = true;\n\n    if(!ui->payAmount->validate())\n    {\n        retval = false;\n    }\n    else\n    {\n        if(ui->payAmount->value() <= 0)\n        {\n            \/\/ Cannot send 0 coins or less\n            ui->payAmount->setValid(false);\n            retval = false;\n        }\n    }\n\n    if(!ui->payTo->hasAcceptableInput() ||\n       (model && !model->validateAddress(ui->payTo->text())))\n    {\n        ui->payTo->setValid(false);\n        retval = false;\n    }\n\n    return retval;\n}\n\nSendCoinsRecipient SendCoinsEntry::getValue()\n{\n    SendCoinsRecipient rv;\n\n    rv.address = ui->payTo->text();\n    rv.label = ui->addAsLabel->text();\n    rv.amount = ui->payAmount->value();\n\n    return rv;\n}\n\nQWidget *SendCoinsEntry::setupTabChain(QWidget *prev)\n{\n    QWidget::setTabOrder(prev, ui->payTo);\n    QWidget::setTabOrder(ui->payTo, ui->addressBookButton);\n    QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);\n    QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);\n    QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);\n    return ui->payAmount->setupTabChain(ui->addAsLabel);\n}\n\nvoid SendCoinsEntry::setValue(const SendCoinsRecipient &value)\n{\n    ui->payTo->setText(value.address);\n    ui->addAsLabel->setText(value.label);\n    ui->payAmount->setValue(value.amount);\n}\n\nbool SendCoinsEntry::isClear()\n{\n    return ui->payTo->text().isEmpty();\n}\n\nvoid SendCoinsEntry::setFocus()\n{\n    ui->payTo->setFocus();\n}\n\nvoid SendCoinsEntry::updateDisplayUnit()\n{\n    if(model && model->getOptionsModel())\n    {\n        \/\/ Update payAmount with the current unit\n        ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());\n    }\n}\n","avg_line_length":24.5314285714,"max_line_length":108,"alphanum_fraction":0.6722571628,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13867,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":10.0,"content":"\/\/===--- SILValueProjection.cpp -------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-value-projection\"\n#include \"swift\/SIL\/SILValueProjection.h\"\n#include \"swift\/SIL\/InstructionUtils.h\"\n#include \"llvm\/Support\/Debug.h\"\n\nusing namespace swift;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                              Utility Functions\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic inline void removeLSLocations(LSLocationValueMap &Values,\n                                     LSLocationList &FirstLevel) {\n  for (auto &X : FirstLevel)\n    Values.erase(X);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                              SILValue Projection\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid SILValueProjection::print(SILModule *Mod) {\n  llvm::outs() << Base;\n  Path.getValue().print(llvm::outs(), *Mod);\n}\n\nSILValue SILValueProjection::createExtract(SILValue Base,\n                                           const Optional<NewProjectionPath> &Path,\n                                           SILInstruction *Inst,\n                                           bool IsValExt) {\n  \/\/ If we found a projection path, but there are no projections, then the two\n  \/\/ loads must be the same, return PrevLI.\n  if (!Path || Path->empty())\n    return Base;\n\n  \/\/ Ok, at this point we know that we can construct our aggregate projections\n  \/\/ from our list of address projections.\n  SILValue LastExtract = Base;\n  SILBuilder Builder(Inst);\n  Builder.setCurrentDebugScope(Inst->getFunction()->getDebugScope());\n\n  \/\/ We use an auto-generated SILLocation for now.\n  \/\/ TODO: make the sil location more precise.\n  SILLocation Loc = RegularLocation::getAutoGeneratedLocation();\n\n  \/\/ Construct the path!\n  for (auto PI = Path->begin(), PE = Path->end(); PI != PE; ++PI) {\n    if (IsValExt) {\n      LastExtract =\n          PI->createObjectProjection(Builder, Loc, LastExtract).get();\n      continue;\n    }\n    LastExtract =\n        PI->createAddressProjection(Builder, Loc, LastExtract).get();\n  }\n\n  \/\/ Return the last extract we created.\n  return LastExtract;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                              Load Store Value\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid LSValue::expand(SILValue Base, SILModule *M, LSValueList &Vals,\n                     TypeExpansionAnalysis *TE) {\n  \/\/ To expand a LSValue to its indivisible parts, we first get the\n  \/\/ address projection paths from the accessed type to each indivisible field,\n  \/\/ i.e. leaf nodes, then we append these projection paths to the Base.\n  for (const auto &P : TE->getTypeExpansion((*Base).getType(), M, TEKind::TELeaf)) {\n    Vals.push_back(LSValue(Base, P.getValue()));\n  }\n}\n\nSILValue LSValue::reduce(LSLocation &Base, SILModule *M,\n                         LSLocationValueMap &Values,\n                         SILInstruction *InsertPt,\n                         TypeExpansionAnalysis *TE) {\n  \/\/ Walk bottom up the projection tree, try to reason about how to construct\n  \/\/ a single SILValue out of all the available values for all the memory\n  \/\/ locations.\n  \/\/\n  \/\/ First, get a list of all the leaf nodes and intermediate nodes for the\n  \/\/ Base memory location.\n  LSLocationList ALocs;\n  const NewProjectionPath &BasePath = Base.getPath().getValue();\n  for (const auto &P : TE->getTypeExpansion(Base.getType(M), M, TEKind::TENode)) {\n    ALocs.push_back(LSLocation(Base.getBase(), BasePath, P.getValue()));\n  }\n\n  \/\/ Second, go from leaf nodes to their parents. This guarantees that at the\n  \/\/ point the parent is processed, its children have been processed already.\n  for (auto I = ALocs.rbegin(), E = ALocs.rend(); I != E; ++I) {\n    \/\/ This is a leaf node, we have a value for it.\n    \/\/\n    \/\/ Reached the end of the projection tree, this is a leaf node.\n    LSLocationList FirstLevel;\n    I->getFirstLevelLSLocations(FirstLevel, M);\n    if (FirstLevel.empty())\n      continue;\n\n    \/\/ If this is a class reference type, we have reached end of the type tree.\n    if (I->getType(M).getClassOrBoundGenericClass())\n      continue;\n\n    \/\/ This is NOT a leaf node, we need to construct a value for it.\n\n    \/\/ There is only 1 children node and its value's projection path is not\n    \/\/ empty, keep stripping it.\n    auto Iter = FirstLevel.begin();\n    LSValue &FirstVal = Values[*Iter];\n    if (FirstLevel.size() == 1 && !FirstVal.hasEmptyNewProjectionPath()) {\n      Values[*I] = FirstVal.stripLastLevelProjection();\n      \/\/ We have a value for the parent, remove all the values for children.\n      removeLSLocations(Values, FirstLevel);\n      continue;\n    }\n    \n    \/\/ If there are more than 1 children and all the children nodes have\n    \/\/ LSValues with the same base and non-empty projection path. we can get\n    \/\/ away by not extracting value for every single field.\n    \/\/\n    \/\/ Simply create a new node with all the aggregated base value, i.e.\n    \/\/ stripping off the last level projection.\n    bool HasIdenticalValueBase = true;\n    SILValue FirstBase = FirstVal.getBase();\n    Iter = std::next(Iter);\n    for (auto EndIter = FirstLevel.end(); Iter != EndIter; ++Iter) {\n      LSValue &V = Values[*Iter];\n      HasIdenticalValueBase &= (FirstBase == V.getBase());\n    }\n\n    if (FirstLevel.size() > 1 && HasIdenticalValueBase && \n        !FirstVal.hasEmptyNewProjectionPath()) {\n      Values[*I] = FirstVal.stripLastLevelProjection();\n      \/\/ We have a value for the parent, remove all the values for children.\n      removeLSLocations(Values, FirstLevel);\n      continue;\n    }\n\n    \/\/ In 3 cases do we need aggregation.\n    \/\/\n    \/\/ 1. If there is only 1 child and we cannot strip off any projections,\n    \/\/ that means we need to create an aggregation.\n    \/\/ \n    \/\/ 2. There are multiple children and they have the same base, but empty\n    \/\/ projection paths.\n    \/\/\n    \/\/ 3. Children have values from different bases, We need to create\n    \/\/ extractions and aggregation in this case.\n    \/\/\n    llvm::SmallVector<SILValue, 8> Vals;\n    for (auto &X : FirstLevel) {\n      Vals.push_back(Values[X].materialize(InsertPt));\n    }\n    SILBuilder Builder(InsertPt);\n    Builder.setCurrentDebugScope(InsertPt->getFunction()->getDebugScope());\n    \n    \/\/ We use an auto-generated SILLocation for now.\n    \/\/ TODO: make the sil location more precise.\n    NullablePtr<swift::SILInstruction> AI =\n        Projection::createAggFromFirstLevelProjections(\n            Builder, RegularLocation::getAutoGeneratedLocation(),\n            I->getType(M).getObjectType(),\n            Vals);\n    \/\/ This is the Value for the current node.\n    NewProjectionPath P(Base.getType(M));\n    Values[*I] = LSValue(SILValue(AI.get()), P);\n    removeLSLocations(Values, FirstLevel);\n\n    \/\/ Keep iterating until we have reach the top-most level of the projection\n    \/\/ tree.\n    \/\/ i.e. the memory location represented by the Base.\n  }\n\n  assert(Values.size() == 1 && \"Should have a single location this point\");\n\n  \/\/ Finally materialize and return the forwarding SILValue.\n  return Values.begin()->second.materialize(InsertPt);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                                  Memory Location\n\/\/===----------------------------------------------------------------------===\/\/\n\nbool LSLocation::isMustAliasLSLocation(const LSLocation &RHS,\n                                       AliasAnalysis *AA) {\n  \/\/ If the bases are not must-alias, the locations may not alias.\n  if (!AA->isMustAlias(Base, RHS.getBase()))\n    return false;\n  \/\/ If projection paths are different, then the locations cannot alias.\n  if (!hasIdenticalProjectionPath(RHS))\n    return false;\n  return true;\n}\n\nbool LSLocation::isMayAliasLSLocation(const LSLocation &RHS,\n                                      AliasAnalysis *AA) {\n  \/\/ If the bases do not alias, then the locations cannot alias.\n  if (AA->isNoAlias(Base, RHS.getBase()))\n    return false;\n  \/\/ If one projection path is a prefix of another, then the locations\n  \/\/ could alias.\n  if (hasNonEmptySymmetricPathDifference(RHS))\n    return false;\n  return true;\n}\n\n\nbool LSLocation::isNonEscapingLocalLSLocation(SILFunction *Fn,\n                                              EscapeAnalysis *EA) {\n  \/\/ An alloc_stack is definitely dead at the end of the function.\n  if (isa<AllocStackInst>(Base))\n    return true;\n  \/\/ For other allocations we ask escape analysis.\t\t\n  auto *ConGraph = EA->getConnectionGraph(Fn);\n  if (isa<AllocationInst>(Base)) {\n    auto *Node = ConGraph->getNodeOrNull(Base, EA);\n    if (Node && !Node->escapes()) {\n      return true;\n    }\n  }\n  return false;\n}\n\nvoid LSLocation::getFirstLevelLSLocations(LSLocationList &Locs,\n                                          SILModule *Mod) {\n  SILType Ty = getType(Mod);\n  llvm::SmallVector<NewProjection, 8> Out;\n  NewProjection::getFirstLevelProjections(Ty, *Mod, Out);\n  for (auto &X : Out) {\n    NewProjectionPath P((*Base).getType());\n    P.append(Path.getValue());\n    P.append(X);\n    Locs.push_back(LSLocation(Base, P));\n  }\n}\n\nvoid LSLocation::expand(LSLocation Base, SILModule *M, LSLocationList &Locs,\n                        TypeExpansionAnalysis *TE) {\n  \/\/ To expand a memory location to its indivisible parts, we first get the\n  \/\/ address projection paths from the accessed type to each indivisible field,\n  \/\/ i.e. leaf nodes, then we append these projection paths to the Base.\n  \/\/\n  \/\/ Construct the LSLocation by appending the projection path from the\n  \/\/ accessed node to the leaf nodes.\n  const NewProjectionPath &BasePath = Base.getPath().getValue();\n  for (const auto &P : TE->getTypeExpansion(Base.getType(M), M, TEKind::TELeaf)) {\n    Locs.push_back(LSLocation(Base.getBase(), BasePath, P.getValue()));\n  }\n}\n\nvoid LSLocation::reduce(LSLocation Base, SILModule *M, LSLocationSet &Locs,\n                        TypeExpansionAnalysis *TE) {\n  \/\/ First, construct the LSLocation by appending the projection path from the\n  \/\/ accessed node to the leaf nodes.\n  LSLocationList Nodes;\n  const NewProjectionPath &BasePath = Base.getPath().getValue();\n  for (const auto &P : TE->getTypeExpansion(Base.getType(M), M, TEKind::TENode)) {\n    Nodes.push_back(LSLocation(Base.getBase(), BasePath, P.getValue()));\n  }\n\n  \/\/ Second, go from leaf nodes to their parents. This guarantees that at the\n  \/\/ point the parent is processed, its children have been processed already.\n  for (auto I = Nodes.rbegin(), E = Nodes.rend(); I != E; ++I) {\n    LSLocationList FirstLevel;\n    I->getFirstLevelLSLocations(FirstLevel, M);\n    \/\/ Reached the end of the projection tree, this is a leaf node.\n    if (FirstLevel.empty())\n      continue;\n\n    \/\/ If this is a class reference type, we have reached end of the type tree.\n    if (I->getType(M).getClassOrBoundGenericClass())\n      continue;\n\n    \/\/ This is NOT a leaf node, check whether all its first level children are\n    \/\/ alive.\n    bool Alive = true;\n    for (auto &X : FirstLevel) {\n      Alive &= Locs.find(X) != Locs.end();\n    }\n\n    \/\/ All first level locations are alive, create the new aggregated location.\n    if (Alive) {\n      for (auto &X : FirstLevel)\n        Locs.erase(X);\n      Locs.insert(*I);\n    }\n  }\n}\n\nvoid LSLocation::enumerateLSLocation(SILModule *M, SILValue Mem,\n                                     std::vector<LSLocation> &Locations,\n                                     LSLocationIndexMap &IndexMap,\n                                     LSLocationBaseMap &BaseMap,\n                                     TypeExpansionAnalysis *TypeCache) {\n  \/\/ We have processed this SILValue before.\n  if (BaseMap.find(Mem) != BaseMap.end())\n    return;\n\n  \/\/ Construct a Location to represent the memory written by this instruction.\n  SILValue UO = getUnderlyingObject(Mem);\n  LSLocation L(UO, NewProjectionPath::getProjectionPath(UO, Mem));\n\n  \/\/ If we cant figure out the Base or Projection Path for the memory location,\n  \/\/ simply ignore it for now.\n  if (!L.isValid())\n    return;\n\n  \/\/ Record the SILValue to location mapping.\n  BaseMap[Mem] = L; \n\n  \/\/ Expand the given Mem into individual fields and add them to the\n  \/\/ locationvault.\n  LSLocationList Locs;\n  LSLocation::expand(L, M, Locs, TypeCache);\n  for (auto &Loc : Locs) {\n   if (IndexMap.find(Loc) != IndexMap.end())\n     continue;\n   IndexMap[Loc] = Locations.size();\n   Locations.push_back(Loc);\n  }\n\n}\n\nvoid LSLocation::enumerateLSLocations(SILFunction &F,\n                                      std::vector<LSLocation> &Locations,\n                                      LSLocationIndexMap &IndexMap,\n                                     LSLocationBaseMap &BaseMap,\n                                      TypeExpansionAnalysis *TypeCache) {\n  \/\/ Enumerate all locations accessed by the loads or stores.\n  for (auto &B : F) {\n    for (auto &I : B) {\n      if (auto *LI = dyn_cast<LoadInst>(&I)) {\n        enumerateLSLocation(&I.getModule(), LI->getOperand(), Locations,\n                            IndexMap, BaseMap, TypeCache);\n        continue;\n      }\n      if (auto *SI = dyn_cast<StoreInst>(&I)) {\n        enumerateLSLocation(&I.getModule(), SI->getDest(), Locations,\n                            IndexMap, BaseMap, TypeCache);\n        continue;\n      }\n    }\n  }\n}\n","avg_line_length":38.6267409471,"max_line_length":84,"alphanum_fraction":0.6057546694,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7021,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":24.0,"content":"\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\/ \\file\n\/\/\/ Tests for SURGSIM_ASSERT() and SURGSIM_FAILURE().\n\n#include <gtest\/gtest.h>\n#include \"SurgSim\/Framework\/Assert.h\"\n\n\nclass MockOutput : public SurgSim::Framework::LogOutput\n{\npublic:\n\tMockOutput()\n\t{\n\t}\n\n\t~MockOutput()\n\t{\n\t}\n\n\tbool writeMessage(const std::string& message)\n\t{\n\t\tlogMessage = message;\n\t\treturn true;\n\t}\n\tvoid reset()\n\t{\n\t\tlogMessage = \"\";\n\t}\n\n\tstd::string logMessage;\n};\n\nclass AssertTest : public ::testing::Test\n{\npublic:\n\tvoid SetUp()\n\t{\n\t\tlogOutput = std::make_shared<MockOutput>();\n\t\ttestLogger = SurgSim::Framework::Logger::getLogger(\"test\");\n\t\ttestLogger->setOutput(logOutput);\n\t\t\/\/ testLogger will be used for assertions in most tests, due to the definition of SURGSIM_ASSERT_LOGGER below.\n\t\tsavedCallback = SurgSim::Framework::AssertMessage::getFailureCallback();\n\t}\n\n\tvoid TearDown()\n\t{\n\t\tSurgSim::Framework::AssertMessage::setFailureCallback(savedCallback);\n\t\ttestLogger.reset();\n\t\tlogOutput.reset();\n\t}\n\n\tstd::shared_ptr<MockOutput> logOutput;\n\tstd::shared_ptr<SurgSim::Framework::Logger> testLogger;\n\tSurgSim::Framework::AssertMessage::DeathCallback savedCallback = nullptr;\n};\n\ntypedef AssertTest AssertDeathTest;\n\n\nTEST_F(AssertTest, DefaultAssertLogger)\n{\n\tEXPECT_THROW(SURGSIM_ASSERT(1 == 2) << \"extra information would go here\", SurgSim::Framework::AssertionFailure);\n}\n\n#undef SURGSIM_ASSERT_LOGGER   \/\/ override the default definition\n#define SURGSIM_ASSERT_LOGGER testLogger   \/\/ defined in the test fixture, above\n\ninline bool stringContains(const std::string& string, const std::string& fragment)\n{\n\treturn string.find(fragment) != std::string::npos;\n}\n\nstatic int numIgnoredAssertions = 0;\n\nstatic void ignoreAssertionKeepGoing(const std::string& message)\n{\n\t++numIgnoredAssertions;\n}\n\nTEST_F(AssertTest, Assertion)\n{\n\tlogOutput->reset();\n\tEXPECT_THROW(SURGSIM_ASSERT(1 == 2) << \"extra information would go here\", SurgSim::Framework::AssertionFailure);\n\tEXPECT_TRUE(stringContains(logOutput->logMessage, \"1 == 2\")) <<\n\t\t\"message: '\" << logOutput->logMessage << \"'\";\n\tEXPECT_TRUE(stringContains(logOutput->logMessage, \"AssertTest.cpp\")) <<\n\t\t\"message: '\" << logOutput->logMessage << \"'\";\n\tEXPECT_TRUE(stringContains(logOutput->logMessage, \"extra information\")) <<\n\t\t\"message: '\" << logOutput->logMessage << \"'\";\n\n\tlogOutput->reset();\n\tEXPECT_NO_THROW({SURGSIM_ASSERT(3 == 3) << \"extra information would go here\";});\n\tEXPECT_EQ(\"\", logOutput->logMessage) <<\n\t\t\"message: '\" << logOutput->logMessage << \"'\";\n}\n\nTEST_F(AssertTest, Failure)\n{\n\tlogOutput->reset();\n\tEXPECT_THROW(SURGSIM_FAILURE() << \"extra information would go here\", SurgSim::Framework::AssertionFailure);\n\tEXPECT_TRUE(stringContains(logOutput->logMessage, \"AssertTest.cpp\")) <<\n\t\t\"message: '\" << logOutput->logMessage << \"'\";\n\tEXPECT_TRUE(stringContains(logOutput->logMessage, \"extra information\")) <<\n\t\t\"message: '\" << logOutput->logMessage << \"'\";\n}\n\nTEST_F(AssertTest, Manipulators)\n{\n\tlogOutput->reset();\n\tEXPECT_THROW(SURGSIM_ASSERT(1 == 2) << \"aAa\" << std::endl << \"bBb\", SurgSim::Framework::AssertionFailure);\n\tEXPECT_TRUE(stringContains(logOutput->logMessage, \"aAa\\nbBb\") ||\n\t\t\t\tstringContains(logOutput->logMessage, \"aAa\\r\\n\\bBb\")) <<\n\t\t\"message: '\" << logOutput->logMessage << \"'\";\n\n\tlogOutput->reset();\n\tEXPECT_THROW(SURGSIM_ASSERT(1 == 2) << \"[\" << std::hex << std::setw(5) << std::setfill('0') << 0x1234 << \"]\",\n\t\t\t\t SurgSim::Framework::AssertionFailure);\n\tEXPECT_TRUE(stringContains(logOutput->logMessage, \"[01234]\")) <<\n\t\t\"message: '\" << logOutput->logMessage << \"'\";\n\n\tlogOutput->reset();\n\t\/\/ The next message should not show any evidence of previous manipulators.\n\tEXPECT_THROW(SURGSIM_ASSERT(1 == 2) << \"[\" << 987 << \"]\", SurgSim::Framework::AssertionFailure);\n\tEXPECT_TRUE(stringContains(logOutput->logMessage, \"[987]\")) <<\n\t\t\"message: '\" << logOutput->logMessage << \"'\";\n}\n\nTEST_F(AssertTest, ExceptionBehavior)\n{\n\tlogOutput->reset();\n\n\tSurgSim::Framework::AssertMessage::setFailureBehaviorToThrow();\n\tEXPECT_THROW(SURGSIM_ASSERT(1 == 2) << \"extra information would go here\", SurgSim::Framework::AssertionFailure);\n\tEXPECT_NO_THROW({SURGSIM_ASSERT(3 == 3) << \"extra information would go here\";});\n\n\tEXPECT_THROW(SURGSIM_FAILURE() << \"extra information would go here\", SurgSim::Framework::AssertionFailure);\n}\n\nTEST_F(AssertTest, Callback)\n{\n\tlogOutput->reset();\n\n\ttypedef SurgSim::Framework::AssertMessage::DeathCallback CallbackType;\n\tconst CallbackType defaultCallback = SurgSim::Framework::AssertMessage::getFailureCallback();\n\n\tSurgSim::Framework::AssertMessage::setFailureBehaviorToThrow();\n\tconst CallbackType throwCallback = SurgSim::Framework::AssertMessage::getFailureCallback();\n\tEXPECT_EQ(throwCallback, defaultCallback);\n\n\tSurgSim::Framework::AssertMessage::setFailureCallback(ignoreAssertionKeepGoing);\n\tEXPECT_EQ(static_cast<CallbackType>(ignoreAssertionKeepGoing),\n\t\t\t  SurgSim::Framework::AssertMessage::getFailureCallback());\n\tnumIgnoredAssertions = 0;\n\tEXPECT_NO_THROW(SURGSIM_ASSERT(1 == 2) << \"extra information would go here\");\n\tEXPECT_EQ(1, numIgnoredAssertions);\n\tEXPECT_NO_THROW({SURGSIM_ASSERT(3 == 3) << \"extra information would go here\";});\n\tEXPECT_EQ(1, numIgnoredAssertions);\n\tEXPECT_NO_THROW(SURGSIM_FAILURE() << \"extra information would go here\");\n\tEXPECT_EQ(2, numIgnoredAssertions);\n\n\tSurgSim::Framework::AssertMessage::setFailureBehaviorToThrow();\n\tEXPECT_EQ(throwCallback, SurgSim::Framework::AssertMessage::getFailureCallback());\n\tEXPECT_THROW(SURGSIM_ASSERT(1 == 2) << \"extra information would go here\", SurgSim::Framework::AssertionFailure);\n\tEXPECT_EQ(2, numIgnoredAssertions);\n}\n\nTEST_F(AssertDeathTest, DebuggerBehaviorAssertFailed)\n{\n\tlogOutput->reset();\n\tSurgSim::Framework::AssertMessage::setFailureBehaviorToDeath();\n\t\/\/ The assertion should die with no output to stdout.\n\tASSERT_DEATH_IF_SUPPORTED({SURGSIM_ASSERT(1 == 2) << \"extra information would go here\";}, \"^$\");\n}\n\nTEST_F(AssertDeathTest, DebuggerBehaviorAssertSucceded)\n{\n\tlogOutput->reset();\n\tSurgSim::Framework::AssertMessage::setFailureBehaviorToDeath();\n\tEXPECT_NO_THROW({SURGSIM_ASSERT(3 == 3) << \"extra information would go here\";});\n}\n\nTEST_F(AssertDeathTest, DebuggerBehaviorFailure)\n{\n\tlogOutput->reset();\n\tSurgSim::Framework::AssertMessage::setFailureBehaviorToDeath();\n\t\/\/ The assertion should die with no output to stdout.\n\tASSERT_DEATH_IF_SUPPORTED({SURGSIM_FAILURE() << \"extra information would go here\";}, \"^$\");\n}\n","avg_line_length":34.5862068966,"max_line_length":113,"alphanum_fraction":0.7383563595,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4134,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":363.0,"content":"#include \"SpatialFunctionalTestFlowControllerSpawner.h\"\n\n\n#include \"Engine\/World.h\"\n#include \"Engine\/NetDriver.h\"\n#include \"GameFramework\/PlayerController.h\"\n#include \"LoadBalancing\/AbstractLBStrategy.h\"\n#include \"EngineClasses\/SpatialNetDriver.h\"\n#include \"SpatialFunctionalTestFlowController.h\"\n#include \"SpatialFunctionalTest.h\"\n\nSpatialFunctionalTestFlowControllerSpawner::SpatialFunctionalTestFlowControllerSpawner()\n\t: SpatialFunctionalTestFlowControllerSpawner(nullptr, TSubclassOf<ASpatialFunctionalTestFlowController>(ASpatialFunctionalTestFlowController::StaticClass()))\n{\n}\n\nSpatialFunctionalTestFlowControllerSpawner::SpatialFunctionalTestFlowControllerSpawner(ASpatialFunctionalTest* ControllerOwningTest, TSubclassOf<ASpatialFunctionalTestFlowController> FlowControllerClassToSpawn)\n\t: OwningTest(ControllerOwningTest),\n\tFlowControllerClass(FlowControllerClassToSpawn),\n\tNextClientControllerId(1)\n{\n}\n\nvoid SpatialFunctionalTestFlowControllerSpawner::ModifyFlowControllerClassToSpawn(TSubclassOf<ASpatialFunctionalTestFlowController> FlowControllerClassToSpawn)\n{\n\tFlowControllerClass = FlowControllerClassToSpawn;\n}\n\nASpatialFunctionalTestFlowController* SpatialFunctionalTestFlowControllerSpawner::SpawnServerFlowController()\n{\n\tUWorld* World = OwningTest->GetWorld();\n\tUNetDriver* NetDriver = World->GetNetDriver();\n\tif (NetDriver != nullptr && !NetDriver->IsServer())\n\t{\n\t\t\/\/Not a server, quit\n\t\treturn nullptr;\n\t}\n\n\tASpatialFunctionalTestFlowController* ServerFlowController = World->SpawnActorDeferred<ASpatialFunctionalTestFlowController>(FlowControllerClass, FTransform());\n\tServerFlowController->OwningTest = OwningTest;\n\tServerFlowController->WorkerDefinition = FWorkerDefinition{ ESpatialFunctionalTestWorkerType::Server, OwningServerIntanceId(World) };\n\n\tServerFlowController->FinishSpawning(FTransform(), true);\n\t\/\/ TODO: Replace locking with custom LB strategy - UNR-3393\n\tLockFlowControllerDelegations(ServerFlowController);\n\n\treturn ServerFlowController;\n}\n\nASpatialFunctionalTestFlowController* SpatialFunctionalTestFlowControllerSpawner::SpawnClientFlowController(APlayerController* OwningClient)\n{\n\tUWorld* World = OwningTest->GetWorld();\n\n\tASpatialFunctionalTestFlowController* FlowController = World->SpawnActorDeferred<ASpatialFunctionalTestFlowController>(FlowControllerClass, OwningTest->GetActorTransform(), OwningClient);\n\tFlowController->OwningTest = OwningTest;\n\tFlowController->WorkerDefinition = FWorkerDefinition{ ESpatialFunctionalTestWorkerType::Client , INVALID_FLOW_CONTROLLER_ID}; \/\/ by default have invalid id, Test Authority will set it to ensure uniqueness\n\t\n\tFlowController->FinishSpawning(OwningTest->GetActorTransform(), true);\n\t\/\/ TODO: Replace locking with custom LB strategy - UNR-3393\n\tLockFlowControllerDelegations(FlowController);\n\n\treturn FlowController;\n}\n\nvoid SpatialFunctionalTestFlowControllerSpawner::AssignClientFlowControllerId(ASpatialFunctionalTestFlowController* ClientFlowController)\n{\n\tcheck(OwningTest->HasAuthority() && ClientFlowController != nullptr && ClientFlowController->WorkerDefinition.Type == ESpatialFunctionalTestWorkerType::Client && ClientFlowController->WorkerDefinition.Id == INVALID_FLOW_CONTROLLER_ID);\n\n\tClientFlowController->CrossServerSetWorkerId(NextClientControllerId++);\n}\n\nuint8 SpatialFunctionalTestFlowControllerSpawner::OwningServerIntanceId(UWorld* World) const\n{\n\tUSpatialNetDriver* SpatialNetDriver = Cast<USpatialNetDriver>(World->GetNetDriver());\n\tif (SpatialNetDriver == nullptr || SpatialNetDriver->LoadBalanceStrategy == nullptr)\n\t{\n\t\t\/\/not load balanced test, default instance 1\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\treturn static_cast<uint8>(SpatialNetDriver->LoadBalanceStrategy->GetLocalVirtualWorkerId());\n\t}\n}\n\nvoid SpatialFunctionalTestFlowControllerSpawner::LockFlowControllerDelegations(ASpatialFunctionalTestFlowController* FlowController) const\n{\n\tUSpatialNetDriver* SpatialNetDriver = Cast<USpatialNetDriver>(FlowController->GetNetDriver());\n\tif(SpatialNetDriver == nullptr || SpatialNetDriver->LoadBalanceStrategy == nullptr)\n\t{\n\t\treturn;\n\t}\n\telse\n\t{\n\t\tSpatialNetDriver->LockingPolicy->AcquireLock(FlowController);\n\t}\n}\n","avg_line_length":42.1836734694,"max_line_length":236,"alphanum_fraction":0.8410740203,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3926,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\n#include <tuple>\n#include <string>\n#include <map>\n#include <utility>\n#include <unordered_set>\n#include <set>\n#include <vector>\n#include <limits>\n#include <algorithm>\n\nstruct Point\n{\n\tint x;\n\tint y;\n};\n\nbool operator<(const Point& lhs, const Point& rhs)\n{\n\treturn (lhs.y < rhs.y || (lhs.y == rhs.y && lhs.x < rhs.x));\n}\n\nenum class Type : char { Clay = '#', \/*Sand = '.',*\/ WetSand = '|', Water = '~'};\n\nstruct Range\n{\n\tint min;\n\tint max;\n};\n\nRange range(const std::string& range)\n{\n\tRange r;\n\tr.min = std::stoi(range.substr(0, range.find('.')));\n\tr.max = std::stoi(range.substr(range.rfind('.') + 1));\n\treturn r;\n}\n\nstd::vector<Point> xRange(const std::string& x, int y)\n{\n\tstd::vector<Point> points;\n\tauto [start, end] = range(x);\n\n\tfor (int x = start; x <= end; ++x)\n\t\tpoints.push_back({x, y});\n\n\treturn points;\n}\n\nstd::vector<Point> yRange(int x, const std::string& y)\n{\n\tstd::vector<Point> points;\n\tauto [start, end] = range(y);\n\n\tfor (int y = start; y <= end; ++y)\n\t\tpoints.push_back({x, y});\n\n\treturn points;\n}\n\nstd::map<Point, Type> readInput()\n{\n\tstd::map<Point, Type> input;\n\n\tstd::string line;\n\twhile (std::getline(std::cin, line)) {\n\t\tchar var1{line[0]};\n\t\tint var1Val{std::stoi(line.substr(2, line.find(',') - 2))};\n\t\tauto range{line.substr(line.rfind('=') + 1)};\n\n\t\tstd::vector<Point> points;\n\t\tif (var1 == 'x')\n\t\t\tpoints = yRange(var1Val, range);\n\t\telse\n\t\t\tpoints = xRange(range, var1Val);\n\n\t\tfor (const auto& p : points)\n\t\t\tinput.emplace(p, Type::Clay);\n\t}\n\n\treturn input;\n}\n\nstruct Bounds\n{\n\tRange X;\n\tRange Y;\n};\n\nBounds bounds(const std::map<Point, Type>& points)\n{\n\tint yMin{std::numeric_limits<int>::max()};\n\tint yMax{std::numeric_limits<int>::min()};\n\tint xMin{std::numeric_limits<int>::max()};\n\tint xMax{std::numeric_limits<int>::min()};\n\n\tfor (const auto& [p, t] : points) {\n\t\tyMin = std::min(yMin, p.y);\n\t\tyMax = std::max(yMax, p.y);\n\n\t\txMin = std::min(xMin, p.x);\n\t\txMax = std::max(xMax, p.x);\n\t}\n\n\treturn {{xMin, xMax}, {yMin, yMax}};\n}\n\nvoid setOverflow(int xFrom, int xTo, int y, int dir, std::map<Point, Type>& tiles)\n{\n\tfor (int x{xFrom}; x != xTo + dir; x += dir) {\n\t\tauto tile = tiles.find({x, y});\n\t\tif (tile != std::end(tiles)) {\n\t\t\tif (tile->second == Type::Clay)\n\t\t\t\tbreak;\n\t\t\ttile->second = Type::WetSand;\n\t\t}\n\t}\n}\n\nbool flow(Point current, std::map<Point, Type>& tiles, const Bounds& bounds)\n{\n\tif (tiles.find(current) != std::end(tiles))\n\t\treturn false;\n\n\tauto [x, y] = current;\n\tif (y > bounds.Y.max)\n\t\treturn true;\n\n\ttiles[current] = Type::WetSand;\n\n\tif (tiles.find({x, y + 1}) != std::end(tiles) && tiles.at({x, y + 1}) == Type::WetSand)\n\t\treturn true;\n\n\t\/\/ down\n\tif (flow({x, y + 1}, tiles, bounds))\n\t\treturn true;\n\n\t\/\/ left and right\n\tauto l = flow({x - 1, y}, tiles, bounds);\n\tauto r = flow({x + 1, y}, tiles, bounds);\n\tif (r)\n\t\tsetOverflow(x - 1, bounds.X.min, y, -1, tiles);\n\tif (l)\n\t\tsetOverflow(x + 1, bounds.X.max, y, 1, tiles);\n\tif (!l && !r)\n\t\ttiles[current] = Type::Water;\n\treturn (l || r);\n}\n\nvoid print(const std::map<Point, Type>& tiles, const Bounds& b)\n{\n\tfor (int y{1}; y <= b.Y.max; ++y) {\n\t\tfor (int x{b.X.min}; x <= b.X.max; ++x) {\n\t\t\tconst auto& tile{tiles.find({x, y})};\n\t\t\tif (tile != std::end(tiles))\n\t\t\t\tstd::cout << static_cast<char>(tile->second);\n\t\t\telse\n\t\t\t\tstd::cout << '.';\n\t\t}\n\t\tstd::cout << '\\n';\n\t}\n}\n\nint main()\n{\n\tauto input{readInput()};\n\tauto b = bounds(input);\n\n\tflow({500, 0}, input, b);\n\t\/* print(input, b); *\/\n\n\tstd::cout << \"part 1: \" << std::count_if(std::begin(input), std::end(input), [&b](const auto& tile) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst auto& [x, y] = tile.first;\n\t\t\t\t\t\t\t\t\t\t\t\t\treturn (tile.second != Type::Clay && y >= b.Y.min && y <= b.Y.max);\n\t\t\t\t\t\t\t\t\t\t\t\t })<< '\\n';\n\tstd::cout << \"part 2: \" << std::count_if(std::begin(input), std::end(input), [&b](const auto& tile) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst auto& [x, y] = tile.first;\n\t\t\t\t\t\t\t\t\t\t\t\t\treturn (tile.second == Type::Water && y >= b.Y.min && y <= b.Y.max);\n\t\t\t\t\t\t\t\t\t\t\t\t })<< '\\n';\n}\n","avg_line_length":21.6906077348,"max_line_length":102,"alphanum_fraction":0.5748853795,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":985171,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/*\n * Copyright (c) 2019 ARM Limited.\n *\n * SPDX-License-Identifier: MIT\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n#ifdef __ARM_FEATURE_SVE\n\n#include <algorithm>\n\n#include \"arm_gemm.hpp\"\n\n\n#include \"..\/..\/asmlib.hpp\"\n#include \"..\/..\/utils.hpp\"\n\nnamespace arm_gemm {\n\nvoid sve_smallK_hybrid_fp32_mla_1VLx8(const float *A, int lda, const float *B, float *C, int ldc, int M, int N, int K, const float *bias, Activation act, bool) {\n    const long loops_count = iceildiv(N, (int)get_vector_length<float>()) - 1;\n    const long ldab = lda * sizeof(float);\n    const long ldcb = ldc * sizeof(float);\n    const long odd_depth  = (K % 4) ? (K % 4) : 4;\n    const long last_width = N - (loops_count * get_vector_length<float>());\n    float nullbias[64];\n    if (!bias) {\n        memset(nullbias, 0, (1 * get_vector_length<float>() * sizeof(float)));\n    }\n    float minval = - static_cast<float>(std::numeric_limits<float>::infinity());\n    float maxval =   static_cast<float>(std::numeric_limits<float>::infinity());\n    const float * const minptr = &minval;\n    const float * const maxptr = &maxval;\n\n    switch(act.type)\n    {\n        default:\n        case Activation::Type::None:\n            break;\n        case Activation::Type::BoundedReLU:\n            maxval = static_cast<float>(act.param1);\n            \/* fall through *\/\n        case Activation::Type::ReLU:\n            minval = 0.0f;\n            break;\n    }\n\n    for (int y0=0; y0<M; y0+=8) {\n        long loops = loops_count;\n        long oob_rows = std::max(8 - (M-y0), 0);\n        long temp = 0;\n        const float *b_ptr0 = B;\n        const float *biasptr = bias ? bias : nullbias;\n        const uint64_t biasinc = bias ? get_vector_length<float>() * 1*sizeof(float) : 0;\n        const float *a_ptr0 = A + (y0 * lda);\n\n        float *c_ptr0 = C + (y0 * ldc);\n\n        switch(K) {\n            case 1:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #1\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7]\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #1\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #1\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 2:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #2\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #2\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #2\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 3:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #3\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #3\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #3\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 4:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #4\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #4\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #4\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 5:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #5\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #5\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #5\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 6:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #6\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #6\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #6\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 7:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #7\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #7\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #7\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 8:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 9:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #1\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #1\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #1\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #1\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 10:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #2\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #2\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #2\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #2\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 11:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #3\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #3\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #3\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #3\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 12:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #4\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #4\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #4\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #4\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 13:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #5\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #5\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #5\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #5\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 14:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #6\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #6\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #6\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #6\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 15:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #7\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #7\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #7\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #7\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 16:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 17:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #1\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #1\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #1\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #1\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 18:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #2\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #2\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #2\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #2\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 19:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #3\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #3\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #3\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #3\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 20:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #4\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #4\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #4\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #4\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 21:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #5\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #5\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #5\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #5\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 22:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #6\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #6\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #6\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #6\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            case 23:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #7\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #7\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #7\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #7\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n            default:\n            case 24:\n                __asm __volatile (\n                    \"a_ptr1 .req X0\\n\"\n                    \"a_ptr2 .req X1\\n\"\n                    \"a_ptr3 .req X2\\n\"\n                    \"a_ptr4 .req X3\\n\"\n                    \"a_ptr5 .req X4\\n\"\n                    \"a_ptr6 .req X5\\n\"\n                    \"a_ptr7 .req X6\\n\"\n                    \"c_ptr1 .req X7\\n\"\n                    \"c_ptr2 .req X8\\n\"\n                    \"c_ptr3 .req X9\\n\"\n                    \"c_ptr4 .req X10\\n\"\n                    \"c_ptr5 .req X11\\n\"\n                    \"c_ptr6 .req X12\\n\"\n                    \"c_ptr7 .req X13\\n\"\n                    \"add a_ptr1, %[a_ptr0], %[lda]\\n\"\n                    \"add c_ptr1, %[c_ptr0], %[ldc]\\n\"\n                    \"add a_ptr2, a_ptr1, %[lda]\\n\"\n                    \"add c_ptr2, c_ptr1, %[ldc]\\n\"\n                    \"add a_ptr3, a_ptr2, %[lda]\\n\"\n                    \"add c_ptr3, c_ptr2, %[ldc]\\n\"\n                    \"add a_ptr4, a_ptr3, %[lda]\\n\"\n                    \"add c_ptr4, c_ptr3, %[ldc]\\n\"\n                    \"add a_ptr5, a_ptr4, %[lda]\\n\"\n                    \"add c_ptr5, c_ptr4, %[ldc]\\n\"\n                    \"add a_ptr6, a_ptr5, %[lda]\\n\"\n                    \"add c_ptr6, c_ptr5, %[ldc]\\n\"\n                    \"add a_ptr7, a_ptr6, %[lda]\\n\"\n                    \"add c_ptr7, c_ptr6, %[ldc]\\n\"\n                    \"cbz %[oob_rows], 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr7, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr7, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr6, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr6, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr5, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr5, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr4, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr4, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr3, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr3, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr2, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr2, %[a_ptr0], #0x0\\n\"\n                    \"b.eq 1f\\n\"\n                    \"subs %[oob_rows], %[oob_rows], #0x1\\n\"\n                    \"add c_ptr1, %[c_ptr0], #0x0\\n\"\n                    \"add a_ptr1, %[a_ptr0], #0x0\\n\"\n                    \"1:\\n\"\n                    \"ptrue p7.s\\n\"\n                    \"whilelt p6.s, %[temp], %[odd_depth]\\n\"\n                    \"whilelt p0.s, %[temp], %[last_width]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"cbz %[loops], 2f\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"b.eq 3f\\n\"\n                    \"4:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"subs %[loops], %[loops], #0x1\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p7\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"b.ne 4b\\n\"\n                    \"3:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p7, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"st1w z25.s, p7, [c_ptr1]\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"st1w z26.s, p7, [c_ptr2]\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"st1w z27.s, p7, [c_ptr3]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"st1w z28.s, p7, [c_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"addvl c_ptr1, c_ptr1, #1\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"st1w z29.s, p7, [c_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"addvl c_ptr2, c_ptr2, #1\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"st1w z30.s, p7, [c_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"addvl c_ptr3, c_ptr3, #1\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"st1w z31.s, p7, [c_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"addvl c_ptr4, c_ptr4, #1\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"addvl c_ptr5, c_ptr5, #1\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"addvl c_ptr6, c_ptr6, #1\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"addvl c_ptr7, c_ptr7, #1\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"b 5f\\n\"\n                    \"2:\\n\"\n                    \"ld1w z24.s, p0\/z, [%[biasptr]]\\n\"\n                    \"add %[biasptr], %[biasptr], %[biasinc]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0]]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1]\\n\"\n                    \"mov z25.d, z24.d\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2]\\n\"\n                    \"mov z26.d, z24.d\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3]\\n\"\n                    \"mov z27.d, z24.d\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4]\\n\"\n                    \"mov z28.d, z24.d\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5]\\n\"\n                    \"mov z29.d, z24.d\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6]\\n\"\n                    \"mov z30.d, z24.d\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7]\\n\"\n                    \"mov z31.d, z24.d\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x10]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x10]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x10]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x10]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x10]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x10]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x10]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x10]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x20]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x20]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x20]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x20]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x20]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x20]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x20]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x20]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"ld1w z16.s, p7\/z, [%[b_ptr0]]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"ld1w z17.s, p7\/z, [%[b_ptr0], #1, MUL VL]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"ld1w z18.s, p7\/z, [%[b_ptr0], #2, MUL VL]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x30]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x30]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x30]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x30]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x30]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x30]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x30]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x30]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"ld1w z19.s, p7\/z, [%[b_ptr0], #3, MUL VL]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"ld1w z20.s, p7\/z, [%[b_ptr0], #4, MUL VL]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"ld1w z21.s, p7\/z, [%[b_ptr0], #5, MUL VL]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"ld1w z22.s, p7\/z, [%[b_ptr0], #6, MUL VL]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p7\/z, [%[a_ptr0], #0x40]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p7\/z, [a_ptr1, #0x40]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p7\/z, [a_ptr2, #0x40]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p7\/z, [a_ptr3, #0x40]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p7\/z, [a_ptr4, #0x40]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p7\/z, [a_ptr5, #0x40]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p7\/z, [a_ptr6, #0x40]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"ld1w z23.s, p7\/z, [%[b_ptr0], #7, MUL VL]\\n\"\n                    \"fmla z24.s, z16.s, z0.s[0]\\n\"\n                    \"ld1rqw z7.s, p7\/z, [a_ptr7, #0x40]\\n\"\n                    \"fmla z25.s, z16.s, z1.s[0]\\n\"\n                    \"addvl %[b_ptr0], %[b_ptr0], #8\\n\"\n                    \"fmla z26.s, z16.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z16.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z16.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z16.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z16.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z16.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z17.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z17.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z17.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z17.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z17.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z17.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z17.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z17.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z18.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z18.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z18.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z18.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z18.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z18.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z18.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z18.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z19.s, z0.s[3]\\n\"\n                    \"ld1rqw z0.s, p6\/z, [%[a_ptr0], #0x50]\\n\"\n                    \"fmla z25.s, z19.s, z1.s[3]\\n\"\n                    \"ld1rqw z1.s, p6\/z, [a_ptr1, #0x50]\\n\"\n                    \"fmla z26.s, z19.s, z2.s[3]\\n\"\n                    \"ld1rqw z2.s, p6\/z, [a_ptr2, #0x50]\\n\"\n                    \"fmla z27.s, z19.s, z3.s[3]\\n\"\n                    \"ld1rqw z3.s, p6\/z, [a_ptr3, #0x50]\\n\"\n                    \"fmla z28.s, z19.s, z4.s[3]\\n\"\n                    \"ld1rqw z4.s, p6\/z, [a_ptr4, #0x50]\\n\"\n                    \"fmla z29.s, z19.s, z5.s[3]\\n\"\n                    \"ld1rqw z5.s, p6\/z, [a_ptr5, #0x50]\\n\"\n                    \"fmla z30.s, z19.s, z6.s[3]\\n\"\n                    \"ld1rqw z6.s, p6\/z, [a_ptr6, #0x50]\\n\"\n                    \"fmla z31.s, z19.s, z7.s[3]\\n\"\n                    \"ld1rqw z7.s, p6\/z, [a_ptr7, #0x50]\\n\"\n                    \"fmla z24.s, z20.s, z0.s[0]\\n\"\n                    \"fmla z25.s, z20.s, z1.s[0]\\n\"\n                    \"fmla z26.s, z20.s, z2.s[0]\\n\"\n                    \"fmla z27.s, z20.s, z3.s[0]\\n\"\n                    \"fmla z28.s, z20.s, z4.s[0]\\n\"\n                    \"fmla z29.s, z20.s, z5.s[0]\\n\"\n                    \"fmla z30.s, z20.s, z6.s[0]\\n\"\n                    \"fmla z31.s, z20.s, z7.s[0]\\n\"\n                    \"fmla z24.s, z21.s, z0.s[1]\\n\"\n                    \"fmla z25.s, z21.s, z1.s[1]\\n\"\n                    \"fmla z26.s, z21.s, z2.s[1]\\n\"\n                    \"fmla z27.s, z21.s, z3.s[1]\\n\"\n                    \"fmla z28.s, z21.s, z4.s[1]\\n\"\n                    \"fmla z29.s, z21.s, z5.s[1]\\n\"\n                    \"fmla z30.s, z21.s, z6.s[1]\\n\"\n                    \"fmla z31.s, z21.s, z7.s[1]\\n\"\n                    \"fmla z24.s, z22.s, z0.s[2]\\n\"\n                    \"fmla z25.s, z22.s, z1.s[2]\\n\"\n                    \"fmla z26.s, z22.s, z2.s[2]\\n\"\n                    \"fmla z27.s, z22.s, z3.s[2]\\n\"\n                    \"fmla z28.s, z22.s, z4.s[2]\\n\"\n                    \"fmla z29.s, z22.s, z5.s[2]\\n\"\n                    \"fmla z30.s, z22.s, z6.s[2]\\n\"\n                    \"fmla z31.s, z22.s, z7.s[2]\\n\"\n                    \"fmla z24.s, z23.s, z0.s[3]\\n\"\n                    \"fmla z25.s, z23.s, z1.s[3]\\n\"\n                    \"fmla z26.s, z23.s, z2.s[3]\\n\"\n                    \"fmla z27.s, z23.s, z3.s[3]\\n\"\n                    \"fmla z28.s, z23.s, z4.s[3]\\n\"\n                    \"fmla z29.s, z23.s, z5.s[3]\\n\"\n                    \"fmla z30.s, z23.s, z6.s[3]\\n\"\n                    \"fmla z31.s, z23.s, z7.s[3]\\n\"\n                    \"5:\\n\"\n                    \"ld1rw z22.s, p7\/z, [%[minptr]]\\n\"\n                    \"ld1rw z23.s, p7\/z, [%[maxptr]]\\n\"\n                    \"fmax z24.s, p7\/m, z24.s, z22.s\\n\"\n                    \"fmax z25.s, p7\/m, z25.s, z22.s\\n\"\n                    \"fmax z26.s, p7\/m, z26.s, z22.s\\n\"\n                    \"fmax z27.s, p7\/m, z27.s, z22.s\\n\"\n                    \"fmin z24.s, p7\/m, z24.s, z23.s\\n\"\n                    \"fmin z25.s, p7\/m, z25.s, z23.s\\n\"\n                    \"fmin z26.s, p7\/m, z26.s, z23.s\\n\"\n                    \"fmin z27.s, p7\/m, z27.s, z23.s\\n\"\n                    \"st1w z24.s, p0, [%[c_ptr0]]\\n\"\n                    \"fmax z28.s, p7\/m, z28.s, z22.s\\n\"\n                    \"addvl %[c_ptr0], %[c_ptr0], #1\\n\"\n                    \"fmax z29.s, p7\/m, z29.s, z22.s\\n\"\n                    \"st1w z25.s, p0, [c_ptr1]\\n\"\n                    \"fmax z30.s, p7\/m, z30.s, z22.s\\n\"\n                    \"fmin z28.s, p7\/m, z28.s, z23.s\\n\"\n                    \"fmax z31.s, p7\/m, z31.s, z22.s\\n\"\n                    \"st1w z26.s, p0, [c_ptr2]\\n\"\n                    \"fmin z29.s, p7\/m, z29.s, z23.s\\n\"\n                    \"fmin z30.s, p7\/m, z30.s, z23.s\\n\"\n                    \"fmin z31.s, p7\/m, z31.s, z23.s\\n\"\n                    \"st1w z27.s, p0, [c_ptr3]\\n\"\n                    \"st1w z28.s, p0, [c_ptr4]\\n\"\n                    \"st1w z29.s, p0, [c_ptr5]\\n\"\n                    \"st1w z30.s, p0, [c_ptr6]\\n\"\n                    \"st1w z31.s, p0, [c_ptr7]\\n\"\n                    \".unreq a_ptr1\\n\"\n                    \".unreq a_ptr2\\n\"\n                    \".unreq a_ptr3\\n\"\n                    \".unreq a_ptr4\\n\"\n                    \".unreq a_ptr5\\n\"\n                    \".unreq a_ptr6\\n\"\n                    \".unreq a_ptr7\\n\"\n                    \".unreq c_ptr1\\n\"\n                    \".unreq c_ptr2\\n\"\n                    \".unreq c_ptr3\\n\"\n                    \".unreq c_ptr4\\n\"\n                    \".unreq c_ptr5\\n\"\n                    \".unreq c_ptr6\\n\"\n                    \".unreq c_ptr7\\n\"\n                    : [a_ptr0] \"+r\" (a_ptr0), [b_ptr0] \"+r\" (b_ptr0), [c_ptr0] \"+r\" (c_ptr0), [loops] \"+r\" (loops), [oob_rows] \"+r\" (oob_rows), [temp] \"+r\" (temp), [biasptr] \"+r\" (biasptr)\n                    : [lda] \"r\" (ldab), [ldc] \"r\" (ldcb), [odd_depth] \"r\" (odd_depth), [last_width] \"r\" (last_width), [biasinc] \"r\" (biasinc), [minptr] \"r\" (minptr), [maxptr] \"r\" (maxptr)\n                    : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\", \"x10\", \"x11\", \"x12\", \"x13\", \"z0\", \"z1\", \"z2\", \"z3\", \"z4\", \"z5\", \"z6\", \"z7\", \"z8\", \"z9\", \"z10\", \"z11\", \"z12\", \"z13\", \"z14\", \"z15\", \"z16\", \"z17\", \"z18\", \"z19\", \"z20\", \"z21\", \"z22\", \"z23\", \"z24\", \"z25\", \"z26\", \"z27\", \"z28\", \"z29\", \"z30\", \"z31\", \"cc\", \"memory\"\n                );\n                break;\n        }\n    }\n}\n\n} \/\/ namespace arm_gemm\n\n#endif \/\/ __ARM_FEATURE_SVE\n","avg_line_length":52.3804232242,"max_line_length":338,"alphanum_fraction":0.34733158,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3539,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"Camera3D.h\"\n\n#include \"Object3D.h\"\n#include \"Scene3D.h\"\n#include \"Transform3D.h\"\n\n#include <iostream>\n\nusing StylizedRunner::Camera3D;\nusing StylizedRunner::Object3D;\nusing StylizedRunner::Scene3D;\n\nCamera3D::Camera3D() {\n    SetRotation({ 0, 0, 0 });\n    SetRadius(1);\n    SetFov(60);\n\n    SetObject(nullptr);\n    SetScene(nullptr);\n}\n\nCamera3D::Camera3D(Camera3D const& other) {\n    SetRotation(other.rotation);\n    SetRadius(other.radius);\n    SetFov(other.fov);\n\n    SetObject(nullptr);\n    SetScene(nullptr);\n}\n\nvoid Camera3D::UpdateActive(float dt, float f, int mods) {\n    if (!IsActive()) {\n        return;\n    }\n\n    if (object) {\n        UpdateModel();\n    }\n}\n\nvoid Camera3D::MouseMove(int dx, int dy) {\n    using namespace glm;\n\n    if (!IsControllable()) return;\n\n    SetRotation({\n        GetRotation().x + 0.1f * radians(static_cast<float>(dy)),\n        GetRotation().y - 0.1f * radians(static_cast<float>(dx)),\n        GetRotation().z,\n    });\n}\n\nvoid Camera3D::MouseScroll(int ox, int oy) {\n    if (!IsControllable()) return;\n\n    SetRadius(GetRadius() - oy);\n}\n\nglm::vec3 Camera3D::GetRotation() const {\n    return rotation;\n}\n\nvoid Camera3D::SetRotation(glm::vec3 rotation) {\n    this->rotation = rotation;\n\n    UpdateModel();\n}\n\nvoid Camera3D::SetRotationX(float rotation) {\n    SetRotation({ rotation, GetRotation().y, GetRotation().z });\n}\n\nvoid Camera3D::SetRotationY(float rotation) {\n    SetRotation({ GetRotation().x, rotation, GetRotation().z });\n}\n\nvoid Camera3D::SetRotationZ(float rotation) {\n    SetRotation({ GetRotation().x, GetRotation().y, rotation });\n}\n\nfloat Camera3D::GetRadius() const {\n    return radius;\n}\n\nvoid Camera3D::SetRadius(float radius) {\n    this->radius = radius;\n\n    UpdateModel();\n}\n\nfloat Camera3D::GetFov() const {\n    return fov;\n}\n\nvoid Camera3D::SetFov(float fov) {\n    this->fov = fov;\n\n    UpdateProjection();\n}\n\nglm::vec3 Camera3D::GetPosition() const {\n    return position;\n}\n\nvoid Camera3D::SetPosition(glm::vec3 position) {\n    this->position = position;\n}\n\nglm::mat4 Camera3D::GetModel() const {\n    return model;\n}\n\nvoid Camera3D::UpdateModel() {\n    using namespace Transform3D;\n\n    mat4 m = RotateY(rotation.y) * RotateX(rotation.x) * RotateZ(rotation.z);\n\n    right   = -m[0];\n    up      =  m[1];\n    forward =  m[2];\n\n    SetPosition((object ? object->GetPosition() : vec3 { 0 }) - radius * forward);\n\n    model = mat4 {\n        vec4 { right,    0 },\n        vec4 { up,       0 },\n        vec4 { forward,  0 },\n        vec4 { position, 1 },\n    };\n\n    UpdateView();\n}\n\nglm::mat4 Camera3D::GetView() const {\n    return view;\n}\n\nvoid Camera3D::UpdateView() {\n    view = glm::lookAt(position, position + forward, up);\n}\n\nglm::mat4 Camera3D::GetProjection() const {\n    return projection;\n}\n\nvoid Camera3D::UpdateProjection() {\n    if (!scene) return;\n\n    float ar = scene->window->props.aspectRatio;\n\n    if (glm::isnan(ar)) {\n        std::cerr << \"Window dimensions are invalid.\"  << std::endl;\n\n        return;\n    }\n\n    projection = glm::perspective(\n        glm::radians(fov),\n        scene->window->props.aspectRatio,\n        0.01f, 200.0f\n    );\n}\n\nObject3D* Camera3D::GetObject() const {\n    return object;\n}\n\nvoid Camera3D::SetObject(Object3D* object) {\n    this->object = object;\n\n    if (object && object->GetCamera() != this) {\n        object->SetCamera(this);\n    }\n\n    UpdateModel();\n}\n\nScene3D* Camera3D::GetScene() const {\n    return scene;\n}\n\nvoid Camera3D::SetScene(Scene3D* scene) {\n    this->scene = scene;\n\n    UpdateProjection();\n}\n","avg_line_length":18.9251336898,"max_line_length":82,"alphanum_fraction":0.6233399265,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1316,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":225.0,"content":"#include <iostream>\nusing namespace std;\nint queue[100], n = 100, front = - 1, rear = - 1;\nvoid Insert() {\n   int val;\n   if (rear == n - 1)\n   cout<<\"Queue Overflow\"<<endl;\n   else {\n      if (front == - 1)\n      front = 0;\n      cout<<\"Insert the element in queue : \"<<endl;\n      cin>>val;\n      rear++;\n      queue[rear] = val;\n   }\n}\nvoid Delete() {\n   if (front == - 1 || front > rear) {\n      cout<<\"Queue Underflow \";\n      return ;\n   } else {\n      cout<<\"Element deleted from queue is : \"<< queue[front] <<endl;\n      front++;;\n   }\n}\nvoid Display() {\n   if (front == - 1)\n   cout<<\"Queue is empty\"<<endl;\n   else {\n      cout<<\"Queue elements are : \";\n      for (int i = front; i <= rear; i++)\n      cout<<queue[i]<<\" \";\n         cout<<endl;\n   }\n}\nint main() {\n   int ch;\n   cout<<\"1) Insert element to queue\"<<endl;\n   cout<<\"2) Delete element from queue\"<<endl;\n   cout<<\"3) Display all the elements of queue\"<<endl;\n   cout<<\"4) Exit\"<<endl;\n   do {\n      cout<<\"Enter your choice : \"<<endl;\n      cin<<ch;\n      switch (ch) {\n         case 1: Insert();\n         break;\n         case 2: Delete();\n         break;\n         case 3: Display();\n         break;\n         case 4: cout<<\"Exit\"<<endl;\n         break;\n         default: cout<<\"Invalid choice\"<<endl;\n      }\n   } while(ch!=4);\n   return 0;\n}\n","avg_line_length":22.3050847458,"max_line_length":69,"alphanum_fraction":0.4939209726,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":32237,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-3.0"],"max_stars_count":null,"content":"\/**********************************************************************\n\n  Audacity: A Digital Audio Editor\n\n  TranscriptionToolBar.cpp\n\n  Shane T. Mueller\n  Leland Lucius\n\n*******************************************************************\/\/**\n\n\\class TranscriptionToolBar\n\\brief A kind of ToolBar used to help with analysing voice recordings.\n\n*\/\/*******************************************************************\/\n\n\n#include \"TranscriptionToolBar.h\"\n#include \"ToolManager.h\"\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include <wx\/wxprec.h>\n\n#ifndef WX_PRECOMP\n#include <wx\/choice.h>\n#include <wx\/defs.h>\n#include <wx\/brush.h>\n#include <wx\/image.h>\n#include <wx\/intl.h>\n#endif \/\/ WX_PRECOMP\n\n#include \"..\/Envelope.h\"\n\n#include \"..\/AllThemeResources.h\"\n#include \"..\/AudioIO.h\"\n#include \"..\/ImageManipulation.h\"\n#include \"..\/KeyboardCapture.h\"\n#include \"Project.h\"\n#include \"..\/ProjectAudioManager.h\"\n#include \"..\/ProjectSettings.h\"\n#include \"..\/Envelope.h\"\n#include \"ViewInfo.h\"\n#include \"..\/WaveTrack.h\"\n#include \"..\/widgets\/AButton.h\"\n#include \"..\/widgets\/ASlider.h\"\n#include \"..\/tracks\/ui\/Scrubbing.h\"\n#include \"Prefs.h\"\n\n#ifdef EXPERIMENTAL_VOICE_DETECTION\n#include \"..\/VoiceKey.h\"\n#include \"..\/ProjectWindow.h\"\n#endif\n\nIMPLEMENT_CLASS(TranscriptionToolBar, ToolBar);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/  Methods for TranscriptionToolBar\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nBEGIN_EVENT_TABLE(TranscriptionToolBar, ToolBar)\n   EVT_CHAR(TranscriptionToolBar::OnKeyEvent)\n   EVT_COMMAND(wxID_ANY, EVT_CAPTURE_KEY, TranscriptionToolBar::OnCaptureKey)\n\n   EVT_COMMAND_RANGE(TTB_PlaySpeed, TTB_PlaySpeed,\n                     wxEVT_COMMAND_BUTTON_CLICKED, TranscriptionToolBar::OnPlaySpeed)\n   EVT_SLIDER(TTB_PlaySpeedSlider, TranscriptionToolBar::OnSpeedSlider)\n\n#ifdef EXPERIMENTAL_VOICE_DETECTION\n   EVT_COMMAND_RANGE(TTB_StartOn, TTB_StartOn,\n                     wxEVT_COMMAND_BUTTON_CLICKED, TranscriptionToolBar::OnStartOn)\n   EVT_COMMAND_RANGE(TTB_StartOff, TTB_StartOff,\n                     wxEVT_COMMAND_BUTTON_CLICKED, TranscriptionToolBar::OnStartOff)\n   EVT_COMMAND_RANGE(TTB_EndOn, TTB_EndOn,\n                     wxEVT_COMMAND_BUTTON_CLICKED, TranscriptionToolBar::OnEndOn)\n   EVT_COMMAND_RANGE(TTB_EndOff, TTB_EndOff,\n                     wxEVT_COMMAND_BUTTON_CLICKED, TranscriptionToolBar::OnEndOff)\n   EVT_COMMAND_RANGE(TTB_SelectSound, TTB_SelectSound,\n                     wxEVT_COMMAND_BUTTON_CLICKED, TranscriptionToolBar::OnSelectSound)\n   EVT_COMMAND_RANGE(TTB_SelectSilence, TTB_SelectSilence,\n                     wxEVT_COMMAND_BUTTON_CLICKED, TranscriptionToolBar::OnSelectSilence)\n   EVT_COMMAND_RANGE(TTB_AutomateSelection, TTB_AutomateSelection,\n                     wxEVT_COMMAND_BUTTON_CLICKED, TranscriptionToolBar::OnAutomateSelection)\n   EVT_COMMAND_RANGE(TTB_MakeLabel, TTB_MakeLabel,\n                     wxEVT_COMMAND_BUTTON_CLICKED, TranscriptionToolBar::OnMakeLabel)\n   EVT_COMMAND_RANGE(TTB_Calibrate, TTB_Calibrate,\n                     wxEVT_COMMAND_BUTTON_CLICKED, TranscriptionToolBar::OnCalibrate)\n   EVT_SLIDER(TTB_SensitivitySlider, TranscriptionToolBar::OnSensitivitySlider)\n\n   EVT_CHOICE(TTB_KeyType, TranscriptionToolBar::SetKeyType)\n#endif\nEND_EVENT_TABLE()\n   ;   \/\/semicolon enforces  proper automatic indenting in emacs.\n\n\/\/\/\/Standard Constructor\nTranscriptionToolBar::TranscriptionToolBar( AudacityProject &project )\n: ToolBar( project,\n   TranscriptionBarID, XO(\"Play-at-Speed\"), wxT(\"Transcription\"), true )\n{\n   SetPlaySpeed( 1.0 * 100.0 );\n#ifdef EXPERIMENTAL_VOICE_DETECTION\n   mVk = std::make_unique<VoiceKey>();\n#endif\n}\n\nTranscriptionToolBar::~TranscriptionToolBar()\n{\n}\n\nTranscriptionToolBar &TranscriptionToolBar::Get( AudacityProject &project )\n{\n   auto &toolManager = ToolManager::Get( project );\n   return *static_cast<TranscriptionToolBar*>( toolManager.GetToolBar(TranscriptionBarID) );\n}\n\nconst TranscriptionToolBar &TranscriptionToolBar::Get( const AudacityProject &project )\n{\n   return Get( const_cast<AudacityProject&>( project )) ;\n}\n\nvoid TranscriptionToolBar::Create(wxWindow * parent)\n{\n   ToolBar::Create(parent);\n\n   mBackgroundHeight = 0;\n   mBackgroundWidth = 0;\n\n#ifdef EXPERIMENTAL_VOICE_DETECTION\n   mButtons[TTB_StartOn]->Disable();\n   mButtons[TTB_StartOff]->Disable();\n   mButtons[TTB_EndOn]->Disable();\n   mButtons[TTB_EndOff]->Disable();\n   mButtons[TTB_SelectSound]->Disable();\n   mButtons[TTB_SelectSilence]->Disable();\n   mButtons[TTB_Calibrate]->Enable();\n   mButtons[TTB_AutomateSelection]->Disable();\n   mButtons[TTB_MakeLabel]->Enable();\n#endif\n\n   \/\/Old code...\n   \/\/Process a dummy event to set up mPlaySpeed\n   \/\/wxCommandEvent dummy;\n   \/\/OnSpeedSlider(dummy);\n\n   \/\/JKC: Set speed this way is better, as we don't\n   \/\/then stop Audio if it is playing, so we can be playing\n   \/\/audio and open a second project.\n   SetPlaySpeed( (mPlaySpeedSlider->Get()) * 100 );\n\n   \/\/ Simulate a size event to set initial placement\/size\n   wxSizeEvent event(GetSize(), GetId());\n   event.SetEventObject(this);\n   GetEventHandler()->ProcessEvent(event);\n}\n\nvoid TranscriptionToolBar::SetPlaySpeed( double value )\n{\n   mPlaySpeed = value;\n   ProjectSettings::Get( mProject ).SetPlaySpeed( GetPlaySpeed() );\n}\n\n\/\/\/ This is a convenience function that allows for button creation in\n\/\/\/ MakeButtons() with fewer arguments\n\/\/\/ Very similar to code in ControlToolBar...\nAButton *TranscriptionToolBar::AddButton(\n   TranscriptionToolBar *pBar,\n   teBmps eFore, teBmps eDisabled,\n   int id,\n   const TranslatableString &label)\n{\n   AButton *&r = pBar->mButtons[id];\n\n   r = ToolBar::MakeButton(pBar,\n      bmpRecoloredUpSmall, bmpRecoloredDownSmall, bmpRecoloredUpHiliteSmall,bmpRecoloredHiliteSmall,\n      eFore, eFore, eDisabled,\n      wxWindowID(id),\n      wxDefaultPosition,\n      false,\n      theTheme.ImageSize( bmpRecoloredUpSmall ));\n\n   r->SetLabel(label);\n\/\/ JKC: Unlike ControlToolBar, does not have a focus rect.  Shouldn't it?\n\/\/ r->SetFocusRect( r->GetRect().Deflate( 4, 4 ) );\n\n   pBar->Add( r, 0, wxALIGN_CENTER );\n\n   return r;\n}\n\nvoid TranscriptionToolBar::MakeAlternateImages(\n   teBmps eFore, teBmps eDisabled,\n   int id, unsigned altIdx)\n{\n   ToolBar::MakeAlternateImages(*mButtons[id], altIdx,\n      bmpRecoloredUpSmall, bmpRecoloredDownSmall, bmpRecoloredUpHiliteSmall,bmpRecoloredHiliteSmall,\n      eFore, eFore, eDisabled,\n      theTheme.ImageSize( bmpRecoloredUpSmall ));\n}\n\nvoid TranscriptionToolBar::Populate()\n{\n   SetBackgroundColour( theTheme.Colour( clrMedium  ) );\n\/\/ Very similar to code in ControlToolBar...\n\/\/ Very similar to code in EditToolBar\n   MakeButtonBackgroundsSmall();\n\n   AddButton(this, bmpPlay,     bmpPlayDisabled,   TTB_PlaySpeed,\n      XO(\"Play at selected speed\"));\n   MakeAlternateImages(bmpLoop, bmpLoopDisabled, TTB_PlaySpeed, 1);\n   MakeAlternateImages(bmpCutPreview, bmpCutPreviewDisabled, TTB_PlaySpeed, 2);\n   mButtons[TTB_PlaySpeed]->FollowModifierKeys();\n\n   \/\/Add a slider that controls the speed of playback.\n   const int SliderWidth=100;\n   mPlaySpeedSlider = safenew ASlider(this,\n      TTB_PlaySpeedSlider,\n      XO(\"Playback Speed\"),\n      wxDefaultPosition,\n      wxSize(SliderWidth,25),\n      ASlider::Options{}\n         .Style( SPEED_SLIDER )\n         \/\/  6 steps using page up\/down, and 60 using arrow keys\n         .Line( 0.16667f )\n         .Page( 1.6667f )\n   );\n   mPlaySpeedSlider->SetSizeHints(wxSize(100, 25), wxSize(2000, 25));\n   mPlaySpeedSlider->Set(mPlaySpeed \/ 100.0);\n   mPlaySpeedSlider->SetLabel(_(\"Playback Speed\"));\n   Add( mPlaySpeedSlider, 1, wxALIGN_CENTER );\n   mPlaySpeedSlider->Bind(wxEVT_SET_FOCUS,\n                 &TranscriptionToolBar::OnFocus,\n                 this);\n   mPlaySpeedSlider->Bind(wxEVT_KILL_FOCUS,\n                 &TranscriptionToolBar::OnFocus,\n                 this);\n\n#ifdef EXPERIMENTAL_VOICE_DETECTION\n\/\/ If we need these strings translated, then search and replace\n\/\/ YO by XO and remove this #define.\n#define YO( x ) Verbatim( x )\n   AddButton(this, bmpTnStartOn,     bmpTnStartOnDisabled,  TTB_StartOn,\n      YO(\"Adjust left selection to next onset\"));\n   AddButton(this, bmpTnEndOn,       bmpTnEndOnDisabled,   TTB_EndOn,\n      YO(\"Adjust right selection to previous offset\"));\n   AddButton(this, bmpTnStartOff,    bmpTnStartOffDisabled,  TTB_StartOff,\n      YO(\"Adjust left selection to next offset\"));\n   AddButton(this, bmpTnEndOff,      bmpTnEndOffDisabled,    TTB_EndOff,\n      YO(\"Adjust right selection to previous onset\"));\n   AddButton(this, bmpTnSelectSound, bmpTnSelectSoundDisabled, TTB_SelectSound,\n      YO(\"Select region of sound around cursor\"));\n   AddButton(this, bmpTnSelectSilence, bmpTnSelectSilenceDisabled, TTB_SelectSilence,\n      YO(\"Select region of silence around cursor\"));\n   AddButton(this, bmpTnAutomateSelection,   bmpTnAutomateSelectionDisabled,  TTB_AutomateSelection,\n      YO(\"Automatically make labels from words\"));\n   AddButton(this, bmpTnMakeTag, bmpTnMakeTagDisabled,  TTB_MakeLabel,\n      YO(\"Add label at selection\"));\n   AddButton(this, bmpTnCalibrate, bmpTnCalibrateDisabled, TTB_Calibrate,\n      YO(\"Calibrate voicekey\"));\n\n   mSensitivitySlider = safenew ASlider(this,\n                                    TTB_SensitivitySlider,\n                                    YO(\"Adjust Sensitivity\"),\n                                    wxDefaultPosition,\n                                    wxSize(SliderWidth,25),\n                                    ASlider::Options{}\n                                       .Style( SPEED_SLIDER ));\n   mSensitivitySlider->Set(.5);\n   mSensitivitySlider->SetLabel(YO(\"Sensitivity\").Translation());\n   Add( mSensitivitySlider, 0, wxALIGN_CENTER );\n\n   TranslatableStrings choices {\n      YO(\"Energy\"),\n      YO(\"Sign Changes (Low Threshold)\"),\n      YO(\"Sign Changes (High Threshold)\"),\n      YO(\"Direction Changes (Low Threshold)\"),\n      YO(\"Direction Changes (High Threshold)\")\n   };\n\n   mKeyTypeChoice = safenew wxChoice(this, TTB_KeyType,\n      wxDefaultPosition,\n      wxDefaultSize,\n      transform_container<wxArrayStringEx>( choices,\n         std::mem_fn( &TranslatableString::Translation ) ) );\n   mKeyTypeChoice->SetName(YO(\"Key type\").Translation());\n   mKeyTypeChoice->SetSelection(0);\n   Add( mKeyTypeChoice, 0, wxALIGN_CENTER );\n#endif\n\n   \/\/ Add a little space\n   Add(2, -1);\n\n   UpdatePrefs();\n}\n\nvoid TranscriptionToolBar::EnableDisableButtons()\n{\n   AudacityProject *p = &mProject;\n\n   auto gAudioIO = AudioIO::Get();\n   bool canStopAudioStream = (!gAudioIO->IsStreamActive() ||\n           gAudioIO->IsMonitoring() ||\n           gAudioIO->GetOwningProject().get() == p );\n   bool recording = gAudioIO->GetNumCaptureChannels() > 0;\n\n   \/\/ Only interested in audio type tracks\n   bool tracks = p && TrackList::Get( *p ).Any<AudioTrack>(); \/\/ PRL:  PlayableTrack ?\n   SetEnabled( canStopAudioStream && tracks && !recording );\n\n#ifdef EXPERIMENTAL_VOICE_DETECTION\n   if (!p)\n      return;\n   \/\/ Is anything selected?\n   const auto &selectedRegion = ViewInfo::Get( *p ).selectedRegion;\n   auto selection = !selectedRegion.isPoint() &&\n      !TrackList::Get( *p ).Selected().empty();\n\n   mButtons[TTB_Calibrate]->SetEnabled(selection);\n#endif\n}\n\nvoid TranscriptionToolBar::UpdatePrefs()\n{\n   RegenerateTooltips();\n\n   \/\/ Set label to pull in language change\n   SetLabel(XO(\"Play-at-Speed\"));\n\n   \/\/ Give base class a chance\n   ToolBar::UpdatePrefs();\n}\n\nvoid TranscriptionToolBar::RegenerateTooltips()\n{\n   \/\/ We could also mention the shift- and ctrl-modified versions in the\n   \/\/ tool tip... but it would get long\n\n   static const struct Entry {\n      int tool;\n      CommandID commandName;\n      TranslatableString untranslatedLabel;\n      CommandID commandName2;\n      TranslatableString untranslatedLabel2;\n   } table[] = {\n      { TTB_PlaySpeed,   wxT(\"PlayAtSpeed\"),    XO(\"Play-at-Speed\"),\n      wxT(\"PlayAtSpeedLooped\"),    XO(\"Looped-Play-at-Speed\")\n      },\n   };\n\n   for (const auto &entry : table) {\n      ComponentInterfaceSymbol commands[] = {\n         { entry.commandName,  entry.untranslatedLabel  },\n         { entry.commandName2, entry.untranslatedLabel2 },\n      };\n      ToolBar::SetButtonToolTip( mProject,\n         *mButtons[entry.tool], commands, 2u );\n   }\n\n#ifdef EXPERIMENTAL_VOICE_DETECTION\n   mButtons[TTB_StartOn]->SetToolTip(YO(\"Left-to-On\"));\n   mButtons[TTB_EndOn]->SetToolTip(   YO(\"Right-to-Off\"));\n   mButtons[TTB_StartOff]->SetToolTip(   YO(\"Left-to-Off\"));\n   mButtons[TTB_EndOff]->SetToolTip(   YO(\"Right-to-On\"));\n   mButtons[TTB_SelectSound]->SetToolTip(   YO(\"Select-Sound\"));\n   mButtons[TTB_SelectSilence]->SetToolTip(   YO(\"Select-Silence\"));\n   mButtons[TTB_AutomateSelection]->SetToolTip(   YO(\"Make Labels\"));\n   mButtons[TTB_MakeLabel]->SetToolTip(   YO(\"Add Label\"));\n   mButtons[TTB_Calibrate]->SetToolTip(   YO(\"Calibrate\"));\n\n   mSensitivitySlider->SetToolTip(YO(\"Sensitivity\").Translation());\n   mKeyTypeChoice->SetToolTip(YO(\"Key type\").Translation());\n#endif\n}\n\nvoid TranscriptionToolBar::OnFocus(wxFocusEvent &event)\n{\n   KeyboardCapture::OnFocus( *this, event );\n}\n\nvoid TranscriptionToolBar::OnCaptureKey(wxCommandEvent &event)\n{\n   wxKeyEvent *kevent = (wxKeyEvent *)event.GetEventObject();\n   int keyCode = kevent->GetKeyCode();\n\n   \/\/ Pass LEFT\/RIGHT\/UP\/DOWN\/PAGEUP\/PAGEDOWN through for input\/output sliders\n   if (FindFocus() == mPlaySpeedSlider && (keyCode == WXK_LEFT || keyCode == WXK_RIGHT\n                                    || keyCode == WXK_UP || keyCode == WXK_DOWN\n                                    || keyCode == WXK_PAGEUP || keyCode == WXK_PAGEDOWN)) {\n      return;\n   }\n\n   event.Skip();\n\n   return;\n}\n\n\/\/This handles key-stroke events????\nvoid TranscriptionToolBar::OnKeyEvent(wxKeyEvent & event)\n{\n   if (event.ControlDown()) {\n      event.Skip();\n      return;\n   }\n\n   if (event.GetKeyCode() == WXK_SPACE) {\n      auto gAudioIO = AudioIOBase::Get();\n      if (gAudioIO->IsBusy()) {\n         \/*Do Stuff Here*\/\n      }\n      else {\n         \/*Do other stuff Here*\/\n      }\n   }\n}\n\n\n\n\/\/This changes the state of the various buttons\nvoid TranscriptionToolBar::SetButton(bool down, AButton* button)\n{\n   if (down) {\n      button->PushDown();\n   }\n   else {\n      button->PopUp();\n   }\n}\n\nvoid TranscriptionToolBar::GetSamples(\n   const WaveTrack *t, sampleCount *s0, sampleCount *slen)\n{\n   \/\/ GetSamples attempts to translate the start and end selection markers into sample indices\n   \/\/ These selection numbers are doubles.\n\n   AudacityProject *p = &mProject;\n   if (!p) {\n      return;\n   }\n\n   \/\/First, get the current selection. It is part of the mViewInfo, which is\n   \/\/part of the project\n\n   const auto &selectedRegion = ViewInfo::Get( *p ).selectedRegion;\n   double start = selectedRegion.t0();\n   double end = selectedRegion.t1();\n\n   auto ss0 = sampleCount( (start - t->GetOffset()) * t->GetRate() );\n   auto ss1 = sampleCount( (end - t->GetOffset()) * t->GetRate() );\n\n   if (start < t->GetOffset()) {\n      ss0 = 0;\n   }\n\n#if 0\n   \/\/This adjusts the right samplecount to the maximum sample.\n   if (ss1 >= t->GetNumSamples()) {\n      ss1 = t->GetNumSamples();\n   }\n#endif\n\n   if (ss1 < ss0) {\n      ss1 = ss0;\n   }\n\n   *s0 = ss0;\n   *slen = ss1 - ss0;\n}\n\n\/\/ PRL: duplicating constants from TimeTrack.cpp\n\/\/TODO-MB: are these sensible values?\n#define TIMETRACK_MIN 0.01\n#define TIMETRACK_MAX 10.0\n\n\/\/ Come here from button clicks, or commands\nvoid TranscriptionToolBar::PlayAtSpeed(bool looped, bool cutPreview)\n{\n   \/\/ Can't do anything without an active project\n   AudacityProject *p = &mProject;\n   if (!p) {\n      return;\n   }\n\n   auto &projectAudioManager = ProjectAudioManager::Get( mProject );\n\n   \/\/ Fixed speed play is the old method, that uses a time track.\n   \/\/ VariSpeed play reuses Scrubbing.\n   bool bFixedSpeedPlay = !gPrefs->ReadBool(wxT(\"\/AudioIO\/VariSpeedPlay\"), true);\n   \/\/ Scrubbing doesn't support note tracks, but the fixed-speed method using time tracks does.\n   if ( TrackList::Get( *p ).Any< NoteTrack >() )\n      bFixedSpeedPlay = true;\n\n   \/\/ Scrubbing only supports straight through play.\n   \/\/ So if looped or cutPreview, we have to fall back to fixed speed.\n   if (looped)\n      cutPreview = false;\n   bFixedSpeedPlay = bFixedSpeedPlay || looped || cutPreview;\n   if (bFixedSpeedPlay)\n   {\n      \/\/ Create a BoundedEnvelope if we haven't done so already\n      if (!mEnvelope) {\n         mEnvelope =\n            std::make_unique<BoundedEnvelope>(\n               true, TIMETRACK_MIN, TIMETRACK_MAX, 1.0);\n         \/\/ values as in the constructor for TimeTrack\n         mEnvelope->SetRangeLower( 0.9 );\n         mEnvelope->SetRangeUpper( 1.1 );\n      }\n      \/\/ Set the speed range\n      \/\/mTimeTrack->SetRangeUpper((double)mPlaySpeed \/ 100.0);\n      \/\/mTimeTrack->SetRangeLower((double)mPlaySpeed \/ 100.0);\n      mEnvelope->Flatten((double)mPlaySpeed \/ 100.0);\n   }\n\n   \/\/ Pop up the button\n   SetButton(false, mButtons[TTB_PlaySpeed]);\n\n   \/\/ If IO is busy, abort immediately\n   auto gAudioIO = AudioIOBase::Get();\n   if (gAudioIO->IsBusy())\n      projectAudioManager.Stop();\n\n   \/\/ Get the current play region\n   const auto &viewInfo = ViewInfo::Get( *p );\n   const auto &playRegion = viewInfo.playRegion;\n\n   \/\/ Start playing\n   if (playRegion.GetStart() < 0)\n      return;\n   if (bFixedSpeedPlay)\n   {\n      auto options = DefaultPlayOptions( *p, looped );\n      \/\/ No need to set cutPreview options.\n      options.envelope = mEnvelope.get();\n      auto mode =\n         cutPreview ? PlayMode::cutPreviewPlay\n         : looped ? PlayMode::loopedPlay\n         : PlayMode::normalPlay;\n      projectAudioManager.PlayPlayRegion(\n         SelectedRegion(playRegion.GetStart(), playRegion.GetEnd()),\n            options,\n            mode);\n   }\n   else\n   {\n      auto &scrubber = Scrubber::Get( *p );\n      scrubber.StartSpeedPlay(GetPlaySpeed(),\n         playRegion.GetStart(), playRegion.GetEnd());\n   }\n}\n\n\/\/ Come here from button clicks only\nvoid TranscriptionToolBar::OnPlaySpeed(wxCommandEvent & WXUNUSED(event))\n{\n   auto button = mButtons[TTB_PlaySpeed];\n\n   \/\/ Let control have precedence over shift\n   const bool cutPreview = mButtons[TTB_PlaySpeed]->WasControlDown();\n   const bool looped = !cutPreview &&\n      button->WasShiftDown();\n   PlayAtSpeed(looped, cutPreview);\n}\n\nvoid TranscriptionToolBar::OnSpeedSlider(wxCommandEvent& WXUNUSED(event))\n{\n   SetPlaySpeed( (mPlaySpeedSlider->Get()) * 100 );\n   RegenerateTooltips();\n\n   \/\/ If IO is busy, abort immediately\n   \/\/ AWD: This is disabled to work around a hang on Linux when PulseAudio is\n   \/\/ used.  If we figure that one out we can re-enable this code.\n   \/\/ auto gAudioIO = AudioIOBase::Get();\n   \/\/if (gAudioIO->IsBusy()) {\n   \/\/   OnPlaySpeed(event);\n   \/\/}\n}\n\n#ifdef EXPERIMENTAL_VOICE_DETECTION\nvoid TranscriptionToolBar::OnStartOn(wxCommandEvent & WXUNUSED(event))\n{\n   \/\/If IO is busy, abort immediately\n   auto gAudioIO = AudioIOBase::Get();\n   if (gAudioIO->IsBusy()){\n      SetButton(false,mButtons[TTB_StartOn]);\n      return;\n   }\n\n   mVk->AdjustThreshold(GetSensitivity());\n\n   auto t = *TrackList::Get( mProject ).Any< const WaveTrack >().begin();\n   if(t ) {\n      auto wt = static_cast<const WaveTrack*>(t);\n      sampleCount start, len;\n      GetSamples(wt, &start, &len);\n\n      \/\/Adjust length to end if selection is null\n      \/\/if(len == 0)\n      \/\/len = wt->GetSequence()->GetNumSamples()-start;\n\n      auto newstart = mVk->OnForward(*wt, start, len);\n      double newpos = newstart.as_double() \/ wt->GetRate();\n\n      auto &selectedRegion = ViewInfo::Get( mProject ).selectedRegion;\n      selectedRegion.setT0( newpos );\n      ProjectWindow::Get( mProject ).RedrawProject();\n\n      SetButton(false, mButtons[TTB_StartOn]);\n   }\n}\n\nvoid TranscriptionToolBar::OnStartOff(wxCommandEvent & WXUNUSED(event))\n{\n   \/\/If IO is busy, abort immediately\n   auto gAudioIO = AudioIOBase::Get();\n   if (gAudioIO->IsBusy()){\n      SetButton(false,mButtons[TTB_StartOff]);\n      return;\n   }\n   mVk->AdjustThreshold(GetSensitivity());\n   AudacityProject *p = &mProject;\n\n   SetButton(false, mButtons[TTB_StartOff]);\n   auto t = *TrackList::Get( mProject ).Any< const WaveTrack >().begin();\n   if(t) {\n      auto wt = static_cast<const WaveTrack*>(t);\n      sampleCount start, len;\n      GetSamples(wt, &start, &len);\n\n      \/\/Adjust length to end if selection is null\n      \/\/if(len == 0)\n      \/\/len = wt->GetSequence()->GetNumSamples()-start;\n\n      auto newstart = mVk->OffForward(*wt, start, len);\n      double newpos = newstart.as_double() \/ wt->GetRate();\n\n      auto &selectedRegion = ViewInfo::Get( mProject ).selectedRegion;\n      selectedRegion.setT0( newpos );\n      ProjectWindow::Get( mProject ).RedrawProject();\n\n      SetButton(false, mButtons[TTB_StartOn]);\n   }\n}\n\nvoid TranscriptionToolBar::OnEndOn(wxCommandEvent & WXUNUSED(event))\n{\n\n   \/\/If IO is busy, abort immediately\n   auto gAudioIO = AudioIOBase::Get();\n   if (gAudioIO->IsBusy()){\n      SetButton(false,mButtons[TTB_EndOn]);\n      return;\n   }\n\n   mVk->AdjustThreshold(GetSensitivity());\n   AudacityProject *p = &mProject;\n   auto t = *TrackList::Get( mProject ).Any< const WaveTrack >().begin();\n   if(t) {\n      auto wt = static_cast<const WaveTrack*>(t);\n      sampleCount start, len;\n      GetSamples(wt, &start, &len);\n\n      \/\/Adjust length to end if selection is null\n      if(len == 0)\n         {\n            len = start;\n            start = 0;\n         }\n      auto newEnd = mVk->OnBackward(*wt, start + len, len);\n      double newpos = newEnd.as_double() \/ wt->GetRate();\n\n      auto &selectedRegion = ViewInfo::Get( mProject ).selectedRegion;\n      selectedRegion.setT1( newpos );\n      ProjectWindow::Get( mProject ).RedrawProject();\n\n      SetButton(false, mButtons[TTB_EndOn]);\n   }\n}\n\n\n\nvoid TranscriptionToolBar::OnEndOff(wxCommandEvent & WXUNUSED(event))\n{\n\n   \/\/If IO is busy, abort immediately\n   auto gAudioIO = AudioIOBase::Get();\n   if (gAudioIO->IsBusy()){\n      SetButton(false,mButtons[TTB_EndOff]);\n      return;\n   }\n   mVk->AdjustThreshold(GetSensitivity());\n   AudacityProject *p = &mProject;\n\n   auto t = *TrackList::Get( mProject ).Any< const WaveTrack >().begin();\n   if(t) {\n      auto wt = static_cast<const WaveTrack*>(t);\n      sampleCount start, len;\n      GetSamples(wt, &start, &len);\n\n      \/\/Adjust length to end if selection is null\n      if(len == 0) {\n         len = start;\n         start = 0;\n      }\n      auto newEnd = mVk->OffBackward(*wt, start + len, len);\n      double newpos = newEnd.as_double() \/ wt->GetRate();\n\n      auto &selectedRegion = ViewInfo::Get( mProject ).selectedRegion;\n      selectedRegion.setT1( newpos );\n      ProjectWindow::Get( mProject ).RedrawProject();\n\n      SetButton(false, mButtons[TTB_EndOff]);\n   }\n}\n\n\n\nvoid TranscriptionToolBar::OnSelectSound(wxCommandEvent & WXUNUSED(event))\n{\n\n   \/\/If IO is busy, abort immediately\n   auto gAudioIO = AudioIOBase::Get();\n   if (gAudioIO->IsBusy()){\n      SetButton(false,mButtons[TTB_SelectSound]);\n      return;\n   }\n\n\n   mVk->AdjustThreshold(GetSensitivity());\n\n\n   TrackList *tl = &TrackList::Get( mProject );\n   if(auto wt = *tl->Any<const WaveTrack>().begin()) {\n      sampleCount start, len;\n      GetSamples(wt, &start, &len);\n\n      \/\/Adjust length to end if selection is null\n      \/\/if(len == 0)\n      \/\/len = wt->GetSequence()->GetNumSamples()-start;\n\n      double rate =  wt->GetRate();\n      auto newstart = mVk->OffBackward(*wt, start, start);\n      auto newend   =\n      mVk->OffForward(*wt, start + len, (int)(tl->GetEndTime() * rate));\n\n      \/\/reset the selection bounds.\n      auto &selectedRegion = ViewInfo::Get( mProject ).selectedRegion;\n      selectedRegion.setTimes(\n         newstart.as_double() \/ rate, newend.as_double() \/  rate );\n      ProjectWindow::Get( mProject ).RedrawProject();\n\n   }\n\n   SetButton(false,mButtons[TTB_SelectSound]);\n}\n\nvoid TranscriptionToolBar::OnSelectSilence(wxCommandEvent & WXUNUSED(event))\n{\n\n   \/\/If IO is busy, abort immediately\n   auto gAudioIO = AudioIOBase::Get();\n   if (gAudioIO->IsBusy()){\n      SetButton(false,mButtons[TTB_SelectSilence]);\n      return;\n   }\n\n   mVk->AdjustThreshold(GetSensitivity());\n\n\n   TrackList *tl = &TrackList::Get( mProject );\n   if(auto wt = *tl->Any<const WaveTrack>().begin()) {\n      sampleCount start, len;\n      GetSamples(wt, &start, &len);\n\n      \/\/Adjust length to end if selection is null\n      \/\/if(len == 0)\n      \/\/len = wt->GetSequence()->GetNumSamples()-start;\n      double rate =  wt->GetRate();\n      auto newstart = mVk->OnBackward(*wt, start, start);\n      auto newend   =\n      mVk->OnForward(*wt, start + len, (int)(tl->GetEndTime() * rate));\n\n      \/\/reset the selection bounds.\n      auto &selectedRegion = ViewInfo::Get( mProject ).selectedRegion;\n      selectedRegion.setTimes(\n         newstart.as_double() \/ rate, newend.as_double() \/ rate);\n      ProjectWindow::Get( mProject ).RedrawProject();\n\n   }\n\n   SetButton(false,mButtons[TTB_SelectSilence]);\n\n}\n\n\n\nvoid TranscriptionToolBar::OnCalibrate(wxCommandEvent & WXUNUSED(event))\n{\n   \/\/If IO is busy, abort immediately\n   auto gAudioIO = AudioIOBase::Get();\n   if (gAudioIO->IsBusy()){\n      SetButton(false,mButtons[TTB_Calibrate]);\n      return;\n   }\n\n\n   TrackList *tl = &TrackList::Get( mProject );\n   if(auto wt = *tl->Any<const WaveTrack>().begin()) {\n      sampleCount start, len;\n      GetSamples(wt, &start, &len);\n\n      mVk->CalibrateNoise(*wt, start, len);\n      mVk->AdjustThreshold(3);\n\n      mButtons[TTB_StartOn]->Enable();\n      mButtons[TTB_StartOff]->Enable();\n      mButtons[TTB_EndOn]->Enable();\n      mButtons[TTB_EndOff]->Enable();\n      \/\/mThresholdSensitivity->Set(3);\n\n      SetButton(false,mButtons[TTB_Calibrate]);\n   }\n\n   mButtons[TTB_StartOn]->Enable();\n   mButtons[TTB_StartOff]->Enable();\n   mButtons[TTB_EndOn]->Enable();\n   mButtons[TTB_EndOff]->Enable();\n   mButtons[TTB_SelectSound]->Enable();\n   mButtons[TTB_SelectSilence]->Enable();\n   mButtons[TTB_AutomateSelection]->Enable();\n\n   \/\/Make the sensitivity slider set the sensitivity by processing an event.\n   wxCommandEvent dummy;\n   OnSensitivitySlider(dummy);\n\n}\n\n#include \"..\/LabelTrack.h\"\n#include \"..\/ProjectHistory.h\"\n#include \"..\/TrackPanel.h\"\n#include \"..\/TrackPanelAx.h\"\n#include \"..\/tracks\/labeltrack\/ui\/LabelTrackView.h\"\nnamespace {\nint DoAddLabel(\n   AudacityProject &project, const SelectedRegion &region )\n{\n   auto &tracks = TrackList::Get( project );\n   auto &trackFocus = TrackFocus::Get( project );\n   auto &trackPanel = TrackPanel::Get( project );\n   auto &window = ProjectWindow::Get( project );\n\n   wxString title;      \/\/ of label\n\n   \/\/ If the focused track is a label track, use that\n   const auto pFocusedTrack = trackFocus.Get();\n\n   \/\/ Look for a label track at or after the focused track\n   auto iter = pFocusedTrack\n      ? tracks.Find(pFocusedTrack)\n      : tracks.Any().begin();\n   auto lt = * iter.Filter< LabelTrack >();\n\n   \/\/ If none found, start a NEW label track and use it\n   if (!lt)\n      lt = tracks.Add( std::make_shared<LabelTrack>() );\n\n\/\/ LLL: Commented as it seemed a little forceful to remove users\n\/\/      selection when adding the label.  This does not happen if\n\/\/      you select several tracks and the last one of those is a\n\/\/      label track...typing a label will not clear the selections.\n\/\/\n\/\/   SelectNone();\n   lt->SetSelected(true);\n\n   int index;\n   int focusTrackNumber = -1;\n   index =\n      LabelTrackView::Get( *lt ).AddLabel(region, title, focusTrackNumber);\n\n   ProjectHistory::Get( project )\n      .PushState(XO(\"Added label\"), XO(\"Label\"));\n\n   TrackFocus::Get(project).Set(lt);\n   lt->EnsureVisible();\n\n   trackPanel.SetFocus();\n\n   return index;\n}\n}\n\n\/\/This automates selection through a selected region,\n\/\/selecting its best guess for words and creating labels at those points.\n\nvoid TranscriptionToolBar::OnAutomateSelection(wxCommandEvent & WXUNUSED(event))\n{\n\n\n   \/\/If IO is busy, abort immediately\n   auto gAudioIO = AudioIOBase::Get();\n   if (gAudioIO->IsBusy())\n   {\n      SetButton(false,mButtons[TTB_EndOff]);\n      return;\n   }\n\n   wxBusyCursor busy;\n\n   mVk->AdjustThreshold(GetSensitivity());\n   TrackList *tl = &TrackList::Get( mProject );\n   if(auto wt = *tl->Any<const WaveTrack>().begin()) {\n      sampleCount start, len;\n      GetSamples(wt, &start, &len);\n\n      \/\/Adjust length to end if selection is null\n      if(len == 0)\n      {\n         len = start;\n         start = 0;\n      }\n      sampleCount lastlen = 0;\n      double newStartPos, newEndPos;\n\n      \/\/This is the minimum word size in samples (.05 is 50 ms)\n      int minWordSize = (int)(wt->GetRate() * .05);\n\n      \/\/Continue until we have processed the entire\n      \/\/region, or we are making no progress.\n      while(len > 0 && lastlen != len)\n      {\n\n         lastlen = len;\n\n         auto newStart = mVk->OnForward(*wt, start, len);\n\n         \/\/JKC: If no start found then don't add any labels.\n         if( newStart==start)\n            break;\n\n         \/\/Adjust len by the NEW start position\n         len -= (newStart - start);\n\n         \/\/Adjust len by the minimum word size\n         len -= minWordSize;\n\n\n\n         \/\/OK, now we have found a NEW starting point.  A 'word' should be at least\n         \/\/50 ms long, so jump ahead minWordSize\n\n         auto newEnd   =\n         mVk->OffForward(*wt, newStart + minWordSize, len);\n\n         \/\/If newEnd didn't move, we should give up, because\n         \/\/ there isn't another end before the end of the selection.\n         if(newEnd == (newStart + minWordSize))\n            break;\n\n\n         \/\/Adjust len by the NEW word end\n         len -= (newEnd - newStart);\n\n         \/\/Calculate the start and end of the words, in seconds\n         newStartPos = newStart.as_double() \/ wt->GetRate();\n         newEndPos = newEnd.as_double() \/ wt->GetRate();\n\n\n         \/\/Increment\n         start = newEnd;\n\n         DoAddLabel(mProject, SelectedRegion(newStartPos, newEndPos));\n      ProjectWindow::Get( mProject ).RedrawProject();\n      }\n      SetButton(false, mButtons[TTB_AutomateSelection]);\n   }\n}\n\nvoid TranscriptionToolBar::OnMakeLabel(wxCommandEvent & WXUNUSED(event))\n{\n   SetButton(false, mButtons[TTB_MakeLabel]);\n   DoAddLabel( mProject, ViewInfo::Get( mProject ).selectedRegion );\n}\n\n\/\/This returns a double z-score between 0 and 10.\ndouble TranscriptionToolBar::GetSensitivity()\n{\n   return (double)mSensitivity;\n}\n\nvoid TranscriptionToolBar::OnSensitivitySlider(wxCommandEvent & WXUNUSED(event))\n{\n   mSensitivity = (mSensitivitySlider->Get());\n}\n\nvoid TranscriptionToolBar::SetKeyType(wxCommandEvent & WXUNUSED(event))\n{\n   int value = mKeyTypeChoice->GetSelection();\n\n   \/\/Only use one key type at a time.\n   switch(value)\n      {\n      case 0:\n         mVk->SetKeyType(true,0,0,0,0);\n         break;\n      case 1:\n         mVk->SetKeyType(0,true,0,0,0);\n         break;\n      case 2:\n         mVk->SetKeyType(0,0,true,0,0);\n         break;\n      case 3:\n         mVk->SetKeyType(0,0,0,true,0);\n         break;\n      case 4:\n         mVk->SetKeyType(0,0,0,0,true);\n         break;\n      }\n\n}\n#endif\n\nvoid TranscriptionToolBar::ShowPlaySpeedDialog()\n{\n   mPlaySpeedSlider->ShowDialog();\n   mPlaySpeedSlider->Refresh();\n   wxCommandEvent e;\n   OnSpeedSlider(e);\n}\n\nvoid TranscriptionToolBar::SetEnabled(bool enabled)\n{\n   mButtons[TTB_PlaySpeed]->SetEnabled(enabled);\n}\n\nvoid TranscriptionToolBar::SetPlaying(bool down, bool looped, bool cutPreview)\n{\n   AButton *const button = mButtons[TTB_PlaySpeed];\n   if (down) {\n      button->SetAlternateIdx(cutPreview ? 2 : looped ? 1 : 0);\n      button->PushDown();\n   }\n   else {\n      button->SetAlternateIdx(0);\n      button->PopUp();\n   }\n}\n\nvoid TranscriptionToolBar::AdjustPlaySpeed(float adj)\n{\n   if (adj < 0) {\n      mPlaySpeedSlider->Decrease(-adj);\n   }\n   else {\n      mPlaySpeedSlider->Increase(adj);\n   }\n   wxCommandEvent e;\n   OnSpeedSlider(e);\n}\n\nstatic RegisteredToolbarFactory factory{ TranscriptionBarID,\n   []( AudacityProject &project ){\n      return ToolBar::Holder{ safenew TranscriptionToolBar{ project } }; }\n};\n\nnamespace {\nAttachedToolBarMenuItem sAttachment{\n   \/* i18n-hint: Clicking this menu item shows the toolbar\n      for transcription (currently just vary play speed) *\/\n   TranscriptionBarID, wxT(\"ShowTranscriptionTB\"), XXO(\"Pla&y-at-Speed Toolbar\")\n};\n}\n\n","avg_line_length":30.1280373832,"max_line_length":100,"alphanum_fraction":0.6602041133,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1312,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/* \n * File:   Activation.cpp\n * Author: heshan\n * \n * Created on June 7, 2018, 11:17 AM\n *\/\n\n#include \"Activation.hpp\"\n#include <iostream>\n\nActivation::Activation() { }\n\nActivation::Activation(const Activation& orig) { }\n\nActivation::~Activation() { }\n\ndouble Activation::sigmoid(double x) {\n    return 1.0\/(1.0 + std::exp(-x));\n}\n    \nEigen::MatrixXd Activation::sigmoid(Eigen::MatrixXd mat){\n    for(int x = 0; x < mat.cols(); x++){\n        for(int y = 0; y < mat.rows(); y++){\n            mat(y,x) = 1.0\/(1.0 + std::exp(-mat(y,x)));\n        }\n    }\n    return mat;\n}\n\ndouble Activation::sigmoidDeriv(double x) {\n    return sigmoid(x) * (1-sigmoid(x));\n}\n    \nEigen::MatrixXd Activation::sigmoidDeriv(Eigen::MatrixXd mat){\n    for(int x = 0; x < mat.cols(); x++){\n        for(int y = 0; y < mat.rows(); y++){\n            mat(y,x) = (sigmoid(mat(y,x)) * (1-mat(y,x)));\n        }\n    }\n    return mat;\n}\n\nEigen::MatrixXd Activation::maxPoolDelta(\n    double poolOutVal, \n    double deltaVal, \n    Eigen::MatrixXd poolBlock,\n    int poolDim1,\n    int poolDim2\n) {\n    \n    for (int i = 0; i < poolDim1; i++) {\n        for (int j = 0; j < poolDim2; j++) {\n            if ( poolBlock(i,j) < poolOutVal ) poolBlock(i,j) = 0;\n            else poolBlock(i,j) = deltaVal;\n        }\n    }\n    \n    return poolBlock;\n}\n\n","avg_line_length":21.5081967213,"max_line_length":66,"alphanum_fraction":0.5457317073,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11912,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"Providers\/Array.hpp\"\n\nusing namespace NWNXLib;\nusing namespace NWNXLib::API;\nusing namespace NWNXLib::Services;\n\nnamespace Data {\n\nenum class ArrayType\n{\n    FLOAT = 0,\n    INTEGER,\n    OBJECT,\n    STRING\n};\n\nstruct CommonArgs\n{\n    ArrayType type;\n    ObjectID oid;\n    std::string tag;\n};\n\nCommonArgs ExtractCommonArgs(Events::ArgumentStack& args)\n{\n    ArrayType type = static_cast<ArrayType>(Events::ExtractArgument<int32_t>(args));\n    ObjectID oid = Events::ExtractArgument<ObjectID>(args);\n    std::string tag = Events::ExtractArgument<std::string>(args);\n    return { std::move(type), std::move(oid), std::move(tag) };\n}\n\nArray::Array()\n{\n    Events::RegisterEvent(\"NWNX_Data\", \"ArrayAt\", &Array::ArrayAt);\n    Events::RegisterEvent(\"NWNX_Data\", \"ArrayClear\", &Array::ArrayClear);\n    Events::RegisterEvent(\"NWNX_Data\", \"ArrayContains\", &Array::ArrayContains);\n    Events::RegisterEvent(\"NWNX_Data\", \"ArrayCopy\", &Array::ArrayCopy);\n    Events::RegisterEvent(\"NWNX_Data\", \"ArrayErase\", &Array::ArrayErase);\n    Events::RegisterEvent(\"NWNX_Data\", \"ArrayFind\", &Array::ArrayFind);\n    Events::RegisterEvent(\"NWNX_Data\", \"ArrayInsert\", &Array::ArrayInsert);\n    Events::RegisterEvent(\"NWNX_Data\", \"ArrayPushBack\", &Array::ArrayPushBack);\n    Events::RegisterEvent(\"NWNX_Data\", \"ArrayResize\", &Array::ArrayResize);\n    Events::RegisterEvent(\"NWNX_Data\", \"ArrayShuffle\", &Array::ArrayShuffle);\n    Events::RegisterEvent(\"NWNX_Data\", \"ArraySize\", &Array::ArraySize);\n    Events::RegisterEvent(\"NWNX_Data\", \"ArraySortAscending\", &Array::ArraySortAscending);\n    Events::RegisterEvent(\"NWNX_Data\", \"ArraySortDescending\", &Array::ArraySortDescending);\n    Events::RegisterEvent(\"NWNX_Data\", \"ArraySet\", &Array::ArraySet);\n}\n\nEvents::ArgumentStack Array::ArrayAt(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n    const int32_t index = Events::ExtractArgument<int32_t>(rawArgs);\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT:   return Events::Arguments(ArrayImpl<float>::At(args.oid, args.tag, index));\n        case ArrayType::INTEGER: return Events::Arguments(ArrayImpl<int32_t>::At(args.oid, args.tag, index));\n        case ArrayType::OBJECT:  return Events::Arguments(ArrayImpl<ObjectID>::At(args.oid, args.tag, index));\n        case ArrayType::STRING:  return Events::Arguments(ArrayImpl<std::string>::At(args.oid, args.tag, index));\n        default: ASSERT_FAIL();  return Events::Arguments();\n    }\n\n}\n\nEvents::ArgumentStack Array::ArrayClear(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT: ArrayImpl<float>::Clear(args.oid, args.tag); break;\n        case ArrayType::INTEGER: ArrayImpl<int32_t>::Clear(args.oid, args.tag); break;\n        case ArrayType::OBJECT: ArrayImpl<ObjectID>::Clear(args.oid, args.tag); break;\n        case ArrayType::STRING: ArrayImpl<std::string>::Clear(args.oid, args.tag); break;\n        default: ASSERT_FAIL(); break;\n    }\n\n    return Events::Arguments();\n}\n\nEvents::ArgumentStack Array::ArrayContains(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n    bool containsElement = false;\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT: containsElement = ArrayImpl<float>::Contains(args.oid, args.tag, Events::ExtractArgument<float>(rawArgs)); break;\n        case ArrayType::INTEGER: containsElement = ArrayImpl<int32_t>::Contains(args.oid, args.tag, Events::ExtractArgument<int32_t>(rawArgs)); break;\n        case ArrayType::OBJECT: containsElement = ArrayImpl<ObjectID>::Contains(args.oid, args.tag, Events::ExtractArgument<ObjectID>(rawArgs)); break;\n        case ArrayType::STRING: containsElement = ArrayImpl<std::string>::Contains(args.oid, args.tag, Events::ExtractArgument<std::string>(rawArgs)); break;\n        default: ASSERT_FAIL(); break;\n    }\n\n    return Events::Arguments(containsElement ? 1 : 0);\n}\n\nEvents::ArgumentStack Array::ArrayCopy(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n    std::string otherTag = Events::ExtractArgument<std::string>(rawArgs);\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT: ArrayImpl<float>::Copy(args.oid, args.tag, std::move(otherTag)); break;\n        case ArrayType::INTEGER: ArrayImpl<int32_t>::Copy(args.oid, args.tag, std::move(otherTag)); break;\n        case ArrayType::OBJECT: ArrayImpl<ObjectID>::Copy(args.oid, args.tag, std::move(otherTag)); break;\n        case ArrayType::STRING: ArrayImpl<std::string>::Copy(args.oid, args.tag, std::move(otherTag)); break;\n        default: ASSERT_FAIL(); break;\n    }\n\n    return Events::Arguments();\n}\n\nEvents::ArgumentStack Array::ArrayErase(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n    const int32_t index = Events::ExtractArgument<int32_t>(rawArgs);\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT: ArrayImpl<float>::Erase(args.oid, args.tag, index); break;\n        case ArrayType::INTEGER: ArrayImpl<int32_t>::Erase(args.oid, args.tag, index); break;\n        case ArrayType::OBJECT: ArrayImpl<ObjectID>::Erase(args.oid, args.tag, index); break;\n        case ArrayType::STRING: ArrayImpl<std::string>::Erase(args.oid, args.tag, index); break;\n        default: ASSERT_FAIL(); break;\n    }\n\n    return Events::Arguments();\n}\n\nEvents::ArgumentStack Array::ArrayFind(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT:   return Events::Arguments(ArrayImpl<float>::Find(args.oid, args.tag, Events::ExtractArgument<float>(rawArgs)));\n        case ArrayType::INTEGER: return Events::Arguments(ArrayImpl<int32_t>::Find(args.oid, args.tag, Events::ExtractArgument<int32_t>(rawArgs)));\n        case ArrayType::OBJECT:  return Events::Arguments(ArrayImpl<ObjectID>::Find(args.oid, args.tag, Events::ExtractArgument<ObjectID>(rawArgs)));\n        case ArrayType::STRING:  return Events::Arguments(ArrayImpl<std::string>::Find(args.oid, args.tag, Events::ExtractArgument<std::string>(rawArgs)));\n        default: ASSERT_FAIL();  return Events::Arguments();\n    }\n}\n\nEvents::ArgumentStack Array::ArrayInsert(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n    const int32_t index = Events::ExtractArgument<int32_t>(rawArgs);\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT: ArrayImpl<float>::Insert(args.oid, args.tag, index, Events::ExtractArgument<float>(rawArgs)); break;\n        case ArrayType::INTEGER: ArrayImpl<int32_t>::Insert(args.oid, args.tag, index, Events::ExtractArgument<int32_t>(rawArgs)); break;\n        case ArrayType::OBJECT: ArrayImpl<ObjectID>::Insert(args.oid, args.tag, index, Events::ExtractArgument<ObjectID>(rawArgs)); break;\n        case ArrayType::STRING: ArrayImpl<std::string>::Insert(args.oid, args.tag, index, Events::ExtractArgument<std::string>(rawArgs)); break;\n        default: ASSERT_FAIL(); break;\n    }\n\n    return Events::Arguments();\n}\n\nEvents::ArgumentStack Array::ArrayPushBack(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT: ArrayImpl<float>::PushBack(args.oid, args.tag, Events::ExtractArgument<float>(rawArgs)); break;\n        case ArrayType::INTEGER: ArrayImpl<int32_t>::PushBack(args.oid, args.tag, Events::ExtractArgument<int32_t>(rawArgs)); break;\n        case ArrayType::OBJECT: ArrayImpl<ObjectID>::PushBack(args.oid, args.tag, Events::ExtractArgument<ObjectID>(rawArgs)); break;\n        case ArrayType::STRING: ArrayImpl<std::string>::PushBack(args.oid, args.tag, Events::ExtractArgument<std::string>(rawArgs)); break;\n        default: ASSERT_FAIL(); break;\n    }\n\n    return Events::Arguments();\n}\n\nEvents::ArgumentStack Array::ArrayResize(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n    const int32_t size = Events::ExtractArgument<int32_t>(rawArgs);\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT: ArrayImpl<float>::Resize(args.oid, args.tag, size); break;\n        case ArrayType::INTEGER: ArrayImpl<int32_t>::Resize(args.oid, args.tag, size); break;\n        case ArrayType::OBJECT: ArrayImpl<ObjectID>::Resize(args.oid, args.tag, size); break;\n        case ArrayType::STRING: ArrayImpl<std::string>::Resize(args.oid, args.tag, size); break;\n        default: ASSERT_FAIL(); break;\n    }\n\n    return Events::Arguments();\n}\n\nEvents::ArgumentStack Array::ArrayShuffle(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT: ArrayImpl<float>::Shuffle(args.oid, args.tag); break;\n        case ArrayType::INTEGER: ArrayImpl<int32_t>::Shuffle(args.oid, args.tag); break;\n        case ArrayType::OBJECT: ArrayImpl<ObjectID>::Shuffle(args.oid, args.tag); break;\n        case ArrayType::STRING: ArrayImpl<std::string>::Shuffle(args.oid, args.tag); break;\n        default: ASSERT_FAIL(); break;\n    }\n\n    return Events::Arguments();\n}\n\nEvents::ArgumentStack Array::ArraySize(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n    int32_t size = 0;\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT: size = ArrayImpl<float>::Size(args.oid, args.tag); break;\n        case ArrayType::INTEGER: size = ArrayImpl<int32_t>::Size(args.oid, args.tag); break;\n        case ArrayType::OBJECT: size = ArrayImpl<ObjectID>::Size(args.oid, args.tag); break;\n        case ArrayType::STRING: size = ArrayImpl<std::string>::Size(args.oid, args.tag); break;\n        default: ASSERT_FAIL(); break;\n    }\n\n    return Events::Arguments(size);\n}\n\nEvents::ArgumentStack Array::ArraySortAscending(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT: ArrayImpl<float>::SortAscending(args.oid, args.tag); break;\n        case ArrayType::INTEGER: ArrayImpl<int32_t>::SortAscending(args.oid, args.tag); break;\n        case ArrayType::OBJECT: ArrayImpl<ObjectID>::SortAscending(args.oid, args.tag); break;\n        case ArrayType::STRING: ArrayImpl<std::string>::SortAscending(args.oid, args.tag); break;\n        default: ASSERT_FAIL(); break;\n    }\n\n    return Events::Arguments();\n}\n\nEvents::ArgumentStack Array::ArraySortDescending(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT: ArrayImpl<float>::SortDescending(args.oid, args.tag); break;\n        case ArrayType::INTEGER: ArrayImpl<int32_t>::SortDescending(args.oid, args.tag); break;\n        case ArrayType::OBJECT: ArrayImpl<ObjectID>::SortDescending(args.oid, args.tag); break;\n        case ArrayType::STRING: ArrayImpl<std::string>::SortDescending(args.oid, args.tag); break;\n        default: ASSERT_FAIL(); break;\n    }\n\n    return Events::Arguments();\n}\n\nEvents::ArgumentStack Array::ArraySet(Events::ArgumentStack&& rawArgs)\n{\n    const CommonArgs args = ExtractCommonArgs(rawArgs);\n    const int32_t index = Events::ExtractArgument<int32_t>(rawArgs);\n\n    switch (args.type)\n    {\n        case ArrayType::FLOAT: ArrayImpl<float>::Set(args.oid, args.tag, index, Events::ExtractArgument<float>(rawArgs)); break;\n        case ArrayType::INTEGER: ArrayImpl<int32_t>::Set(args.oid, args.tag, index, Events::ExtractArgument<int32_t>(rawArgs)); break;\n        case ArrayType::OBJECT: ArrayImpl<ObjectID>::Set(args.oid, args.tag, index, Events::ExtractArgument<ObjectID>(rawArgs)); break;\n        case ArrayType::STRING: ArrayImpl<std::string>::Set(args.oid, args.tag, index, Events::ExtractArgument<std::string>(rawArgs)); break;\n        default: ASSERT_FAIL(); break;\n    }\n\n    return Events::Arguments();\n}\n\n}\n","avg_line_length":42.5428571429,"max_line_length":157,"alphanum_fraction":0.6992948287,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10237,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":7.0,"content":"\/*\n * Copyright (c) 2017, University of Kaiserslautern\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its\n *    contributors may be used to endorse or promote products derived from\n *    this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Omar Naji,\n *          Matthias Jung,\n *          Christian Weis,\n *          Kamal Haddad,\n *          Andre Lucas Chinazzo\n *\/\n\n\n\n#ifndef BANKTEST_CPP\n#define BANKTEST_CPP\n\n#include <boost\/test\/included\/unit_test.hpp>\n\n#include \"..\/..\/core\/Bank.h\"\n\nBOOST_AUTO_TEST_SUITE( testBank )\n\nBOOST_AUTO_TEST_CASE( checkBank_real_input )\n{\n    int sim_argc = 5;\n    char* sim_argv[] = {\".\/executable\",\n                        \"-t\",\n                        \"technology_input\/test_technology.json\",\n                        \"-p\",\n                        \"architecture_input\/test_architecture.json\"};\n\n    ArgumentsParser inputFileName(sim_argc, sim_argv);\n\n    string exceptionMsg(\"Empty\");\n    try {\n        inputFileName.runArgParser();\n    }catch (string exceptionMsgThrown){\n        exceptionMsg = exceptionMsgThrown;\n    }\n    string expectedMsg(\"Empty\");\n    if ( exceptionMsg != expectedMsg ) {\n        BOOST_FAIL( exceptionMsg );\n    }\n\n    Bank bank;\n    try {\n        bank = Bank(inputFileName.technologyFileName[0],\n                    inputFileName.architectureFileName[0]);\n    }catch (string exceptionMsgThrown){\n        exceptionMsg = exceptionMsgThrown;\n    }\n    expectedMsg = string(\"Empty\");\n    if ( exceptionMsg != expectedMsg ) {\n        BOOST_FAIL( exceptionMsg );\n    }\n\n\n    BOOST_CHECK_MESSAGE( bank.bankStorage == 134217728*drs::bits,\n                        \"Bank storage size different from the expected.\"\n                        << \"\\nExpected: \" << 134217728*drs::bits\n                        << \"\\nGot: \" << bank.bankStorage);\n\n    BOOST_CHECK_MESSAGE( ceil(bank.bankWidth) == 2799*drs::micrometer,\n                        \"Width of bank different from the expected.\"\n                        << \"\\nExpected: \" << 2799*drs::micrometer\n                        << \"\\nGot: \" << ceil(bank.bankWidth));\n\n    BOOST_CHECK_MESSAGE( ceil(bank.bankHeight) == 2324*drs::micrometer,\n                        \"Height of bank different from the expected.\"\n                        << \"\\nExpected: \" << 2324*drs::micrometer\n                        << \"\\nGot: \" << ceil(bank.bankHeight));\n\n    BOOST_CHECK_MESSAGE( bank.nBankLogicalRows == 8192,\n                        \"Number logical rows in a bank\"\n                        << \"different from the expected.\"\n                        << \"\\nExpected: \" << 8192\n                        << \"\\nGot: \" << bank.nBankLogicalRows);\n\n    BOOST_CHECK_MESSAGE( bank.nRowAddressLines == 13,\n                        \"Number of lines for row addressing \"\n                        << \"different from the expected.\"\n                        << \"\\nExpected: \" << 13\n                        << \"\\nGot: \" << bank.nRowAddressLines);\n\n    BOOST_CHECK_MESSAGE( bank.nBankLogicalColumns == 1024,\n                        \"Number logical columns in a bank\"\n                        << \"different from the expected.\"\n                        << \"\\nExpected: \" << 1024\n                        << \"\\nGot: \" << bank.nBankLogicalColumns);\n\n    BOOST_CHECK_MESSAGE( bank.nColumnAddressLines == 10,\n                        \"Number of lines for column addressing \"\n                        << \"different from the expected.\"\n                        << \"\\nExpected: \" << 10\n                        << \"\\nGot: \" << bank.nColumnAddressLines);\n\n}\n\nBOOST_AUTO_TEST_CASE( checkBank_dummy_input )\n{\n    int sim_argc = 5;\n    char* sim_argv[] = {\".\/executable\",\n                        \"-t\",\n                        \"technology_input\/tech_dummy_input.json\",\n                        \"-p\",\n                        \"architecture_input\/arch_dummy_input.json\"};\n\n    ArgumentsParser inputFileName(sim_argc, sim_argv);\n\n    string exceptionMsg(\"Empty\");\n    try {\n        inputFileName.runArgParser();\n    }catch (string exceptionMsgThrown){\n        exceptionMsg = exceptionMsgThrown;\n    }\n    string expectedMsg(\"Empty\");\n    if ( exceptionMsg != expectedMsg ) {\n        BOOST_FAIL( exceptionMsg );\n    }\n\n    Bank bank;\n    try {\n        bank = Bank(inputFileName.technologyFileName[0],\n                    inputFileName.architectureFileName[0]);\n    }catch (string exceptionMsgThrown){\n        exceptionMsg = exceptionMsgThrown;\n    }\n    expectedMsg = \"[ERROR] Architecture must have \";\n    expectedMsg.append(\"1, 2 or 4 tile per bank.\");\n    BOOST_CHECK_MESSAGE( exceptionMsg == expectedMsg,\n                        \"Error message different from what was expected.\"\n                        << \"\\nExpected: \" << expectedMsg\n                        << \"\\nGot: \" << exceptionMsg);\n\n}\n\nBOOST_AUTO_TEST_CASE( checkBank_different_tile_configs )\n{\n    int sim_argc = 5;\n    char* sim_argv[] = {\".\/executable\",\n                        \"-t\",\n                        \"technology_input\/test_technology.json\",\n                        \"-p\",\n                        \"architecture_input\/test_architecture.json\"};\n\n    ArgumentsParser inputFileName(sim_argc, sim_argv);\n\n    string exceptionMsg(\"Empty\");\n    try {\n        inputFileName.runArgParser();\n    }catch (string exceptionMsgThrown){\n        exceptionMsg = exceptionMsgThrown;\n    }\n    string expectedMsg(\"Empty\");\n    if ( exceptionMsg != expectedMsg ) {\n        BOOST_FAIL( exceptionMsg );\n    }\n\n    Bank bank;\n    try {\n        bank = Bank(inputFileName.technologyFileName[0],\n                    inputFileName.architectureFileName[0]);\n    }catch (string exceptionMsgThrown){\n        exceptionMsg = exceptionMsgThrown;\n    }\n    expectedMsg = string(\"Empty\");\n    if ( exceptionMsg != expectedMsg ) {\n        BOOST_FAIL( exceptionMsg );\n    }\n\n\n    bank.nTilesPerBank = 1.0;\n    bank.pageSpanningFactor = 1;\n    try {\n        bank.tileCompute();\n    }catch (string exceptionMsgThrown){\n        cerr << exceptionMsgThrown << endl;\n    }\n    bank.bankCompute();\n\n    BOOST_CHECK_MESSAGE( bank.bankStorage == 134217728*drs::bits,\n                        \"Bank storage size different from the expected.\"\n                        << \"\\nExpected: \" << 134217728*drs::bits\n                        << \"\\nGot: \" << bank.bankStorage);\n\n    BOOST_CHECK_MESSAGE( ceil(bank.bankWidth) == 2550*drs::micrometer,\n                        \"Width of bank different from the expected.\"\n                        << \"\\nExpected: \" << 2550*drs::micrometer\n                        << \"\\nGot: \" << ceil(bank.bankWidth));\n\n    BOOST_CHECK_MESSAGE( ceil(bank.bankHeight) == 2324*drs::micrometer,\n                        \"Height of bank different from the expected.\"\n                        << \"\\nExpected: \" << 2324*drs::micrometer\n                        << \"\\nGot: \" << ceil(bank.bankHeight));\n\n    bank.nTilesPerBank = 2.0;\n    bank.pageSpanningFactor = 1;\n    try {\n        bank.tileCompute();\n    }catch (string exceptionMsgThrown){\n        cerr << exceptionMsgThrown << endl;\n    }\n    bank.bankCompute();\n\n    BOOST_CHECK_MESSAGE( bank.bankStorage == 134217728*drs::bits,\n                        \"Bank storage size different from the expected.\"\n                        << \"\\nExpected: \" << 134217728*drs::bits\n                        << \"\\nGot: \" << bank.bankStorage);\n\n    BOOST_CHECK_MESSAGE( ceil(bank.bankWidth) == 5099*drs::micrometer,\n                        \"Width of bank different from the expected.\"\n                        << \"\\nExpected: \" << 5099*drs::micrometer\n                        << \"\\nGot: \" << ceil(bank.bankWidth));\n\n    BOOST_CHECK_MESSAGE( ceil(bank.bankHeight) == 1409*drs::micrometer,\n                        \"Height of bank different from the expected.\"\n                        << \"\\nExpected: \" << 1409*drs::micrometer\n                        << \"\\nGot: \" << ceil(bank.bankHeight));\n\n    bank.nTilesPerBank = 4.0;\n    bank.pageSpanningFactor = 1;\n    try {\n        bank.tileCompute();\n    }catch (string exceptionMsgThrown){\n        cerr << exceptionMsgThrown << endl;\n    }\n    bank.bankCompute();\n\n    BOOST_CHECK_MESSAGE( bank.bankStorage == 134217728*drs::bits,\n                        \"Bank storage size different from the expected.\"\n                        << \"\\nExpected: \" << 134217728*drs::bits\n                        << \"\\nGot: \" << bank.bankStorage);\n\n    BOOST_CHECK_MESSAGE( ceil(bank.bankWidth) == 5099*drs::micrometer,\n                        \"Width of bank different from the expected.\"\n                        << \"\\nExpected: \" << 5099*drs::micrometer\n                        << \"\\nGot: \" << ceil(bank.bankWidth));\n\n    BOOST_CHECK_MESSAGE( ceil(bank.bankHeight) == 1704*drs::micrometer,\n                        \"Height of bank different from the expected.\"\n                        << \"\\nExpected: \" << 1704*drs::micrometer\n                        << \"\\nGot: \" << ceil(bank.bankHeight));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n#endif \/\/ BANKTEST_CPP\n","avg_line_length":37.2254545455,"max_line_length":77,"alphanum_fraction":0.5753638761,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8415,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include \"UTF8String.h\"\n\n\nUTF8String::UTF8String() {\n}\n\n\n\n\n\nUTF8String::UTF8String( const int & i ) :\n\tStringASCII( i ) {\n\n}\n\nUTF8String::UTF8String( const unsigned int & ui ) :\n\tStringASCII( ui ) {\n\n}\n\nUTF8String::UTF8String( const long & l ) :\n\tStringASCII( l ) {\n\n}\n\nUTF8String::UTF8String( const unsigned long & ul ) :\n\tStringASCII( ul ) {\n\n}\n\nUTF8String::UTF8String( const long long & ll ) :\n\tStringASCII( ll ) {\n\n}\n\nUTF8String::UTF8String( const unsigned long long & ull ) :\n\tStringASCII( ull ) {\n\n}\n\nUTF8String::UTF8String( const double & d ) :\n\tStringASCII( d ) {\n\n}\n\nUTF8String::UTF8String( const float & f ) :\n\tStringASCII( f ) {\n\n}\n\nUTF8String::UTF8String( const bool & b ) :\n\tStringASCII( b ) {\n\n}\n\nUTF8String::UTF8String( const char & c ) :\n\tStringASCII( c ) {\n\n}\n\nUTF8String::UTF8String( const StringASCII & str ) :\n\tStringASCII( str ) {\n}\n\nUTF8String::UTF8String( const std::string & str ) :\n\tStringASCII( str ) {\n}\n\nUTF8String::UTF8String( const UTF8String & str ) :\n\tStringASCII( str ) {\n}\n\nUTF8String::UTF8String( UTF8String && str ) :\n\tStringASCII( Utility::toRValue( str ) ) {\n}\n\nUTF8String::UTF8String( const char * str, Size size ) :\n\tStringASCII( str, size ) {\n}\n\nUTF8String::UTF8String( const char * str ) :\n\tStringASCII( str) {\n}\n\n\n\n\/*\nUTF8String::UTF8String( const CodePoint & codePoint ) : StringASCII( ctor::null ) {\n\t_allocateNoNullDelete(5);\n\tthis -> size = codePoint2Chars( codePoint , this -> dataTable);\n\tthis -> dataTable[this -> size] = char( '\\0' );\n\t_updateIterators();\n}\n*\/\n\nUTF8String & UTF8String::operator=( const StringASCII & str ) {\n\tStringASCII::operator=( str );\n\treturn *this;\n}\n\nUTF8String & UTF8String::operator=( const UTF8String & str ) {\n\tStringASCII::operator=( str );\n\treturn *this;\n}\n\nUTF8String & UTF8String::operator=( UTF8String && str ) {\n\tStringASCII::operator=( Utility::toRValue( str ) );\n\treturn *this;\n}\n\n\nUTF8String & UTF8String::operator=( const char * str ) {\n\tStringASCII::operator=( str );\n\treturn *this;\n}\n\nUTF8String & UTF8String::operator=( const std::string & str ) {\n\tStringASCII::operator=( str );\n\treturn *this;\n}\n\nUTF8String & UTF8String::operator+=( const UTF8String & str ) {\n\tStringASCII::operator+=( str );\n\treturn *this;\n}\n\nUTF8String & UTF8String::operator+=( const StringASCII & str ) {\n\tconcat( str );\n\treturn *this;\n}\n\n\n\nUTF8String::~UTF8String() {\n}\n\n\n\nUTF8String UTF8String::getSubStr( Size index, Size size ) const  {\n\tauto beginIt( getBegin() );\n\tfor ( ; index && this -> iterate( &beginIt ); index-- );\n\n\tauto endIt( beginIt );\n\tfor ( ; size && this -> iterate( &endIt ); size-- );\n\n\treturn UTF8String( beginIt, endIt );\n}\n\n\nUTF8String UTF8String::getSubStr( typename UTF8String::Iterator beginIt, Size size ) const {\n\tif ( beginIt >= getEnd() )\n\t\treturn UTF8String();\n\tif ( beginIt < getBegin() )\n\t\tbeginIt = getBegin();\n\n\n\tauto endIt( beginIt );\n\tfor ( ; this -> iterate( &endIt ); );\n\n\treturn UTF8String( beginIt, endIt );\n}\n\nUTF8String UTF8String::getSubStr( typename UTF8String::Iterator beginIt, typename UTF8String::Iterator endIt ) const {\n\tif ( beginIt >= getEnd() || endIt < getBegin() )\n\t\treturn UTF8String();\n\tif ( beginIt < getBegin() )\n\t\tbeginIt = getBegin();\n\tif ( endIt > getEnd() )\n\t\tendIt = getEnd();\n\n\treturn UTF8String( beginIt, endIt );\n}\n\nUTF8String::CodePoint UTF8String::getCodePoint( char charTmp[4] ) {\n\tif ( charTmp[0] & 0x80 ) {\t\t\t\t\/\/1100 0000\n\t\tif ( charTmp[1] & 0x20 ) {\t\t\t\/\/1110 0000\n\t\t\tif ( charTmp[2] & 0x10 )\t\t\/\/1111 0000\n\t\t\t\treturn ( ( charTmp[0] & 0x7 ) << 18 ) | ( ( charTmp[1] & 0x3F ) << 12 ) | ( ( charTmp[2] & 0x3F ) << 6 ) | ( charTmp[3] & 0x3F );\n\n\t\t\telse  \/\/If the code point is on THREE Bytes ONLY !\n\t\t\t\treturn ( ( charTmp[0] & 0xF ) << 12 ) | ( ( charTmp[1] & 0x3F ) << 6 ) | ( charTmp[2] & 0x3F );\n\n\t\t} else  \/\/If the code point is on TWO Bytes ONLY !\n\t\t\treturn ( ( charTmp[0] & 0x1F ) << 6 ) | ( charTmp[1] & 0x3F );\n\t} else   \/\/If the code point is on ONE Byte ONLY !\n\t\treturn ( CodePoint ) charTmp[0];\n}\n\n\n\nbool UTF8String::iterate( typename UTF8String::Iterator * i ) const {\n\tchar & c = **i;\n\tif ( c & 0x80 ) {\t\t\t\t\/\/1000 0000\n\t\tif ( c & 0x20 ) {\t\t\t\/\/1110 0000\n\t\t\tif ( c & 0x10 ) {\t\t\/\/1111 0000\n\t\t\t\t*i += 4;\n\t\t\t} else { \/\/If the code point is on THREE Bytes ONLY \n\t\t\t\t*i += 3;\n\t\t\t}\n\t\t} else { \/\/If the code point is on TWO Bytes ONLY !\n\t\t\t*i += 2;\n\t\t}\n\t} else {  \/\/If the code point is on ONE Byte ONLY !\n\t\tif ( c != '\\0' ) {\n\t\t\t*i += 1;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n\n\n\nbool UTF8String::iterate( typename UTF8String::Iterator * i, CodePoint * codePoint ) const {\n\tchar & c = **i;\n\tif ( c & 0x80 ) {\t\t\t\t\/\/1100 0000\n\t\tchar & c1 = *( *i + 1 );\n\t\tif ( c & 0x20 ) {\t\t\t\/\/1110 0000\n\t\t\tchar & c2 = *( *i + 2 );\n\t\t\tif ( c & 0x10 ) {\t\t\/\/1111 0000\n\t\t\t\tchar & c3 = *( *i + 3 );\n\t\t\t\t*codePoint = ( ( c & 0x7 ) << 18 ) | ( ( c1 & 0x3F ) << 12 ) | ( ( c2 & 0x3F ) << 6 ) | ( c3 & 0x3F );\n\t\t\t\t*i += 4;\n\t\t\t\treturn true;\n\t\t\t} else {  \/\/If the code point is on THREE Bytes ONLY !\n\t\t\t\t*codePoint = ( ( c & 0xF ) << 12 ) | ( ( c1 & 0x3F ) << 6 ) | ( c2 & 0x3F );\n\t\t\t\t*i += 3;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} else {  \/\/If the code point is on TWO Bytes ONLY !\n\t\t\t*codePoint = ( ( c & 0x1F ) << 6 ) | ( c1 & 0x3F );\n\t\t\t*i += 2;\n\t\t\treturn true;\n\t\t}\n\t} else {  \/\/If the code point is on ONE Byte ONLY !\n\t\t*codePoint = ( CodePoint ) c;\n\t\tif ( c != '\\0' ) {\n\t\t\t*i += 1;\n\t\t\treturn true;\n\t\t} else\n\t\t\treturn false;\n\t}\n}\n\n\n\n\nbool UTF8String::cmp( typename UTF8String::Iterator it, const UTF8String & otherStr, typename UTF8String::Iterator anotherIt, Size size ) const {\n\treturn cmp( &it, otherStr, &anotherIt, size );\n}\n\n\nbool UTF8String::cmp( typename UTF8String::Iterator * it, const UTF8String & otherStr, typename UTF8String::Iterator * anotherIt, Size size ) const {\n\tUCodePoint codePointThis;\n\tUCodePoint codePointOther;\n\twhile ( size ) {\n\t\tif ( !this -> iterate( it, &codePointThis ) ) {\n\t\t\tif ( !otherStr.iterate( anotherIt, &codePointOther ) ) return true;\n\t\t\telse return false;\n\t\t}\n\t\tif ( !otherStr.iterate( anotherIt, &codePointOther ) ) return false;\n\t\tif ( codePointThis != codePointOther ) return false;\n\t\tsize--;\n\t}\n\treturn true;\n}\n\n\nbool UTF8String::cmp( typename UTF8String::Iterator it, const  BasicString<char> & otherStr, typename BasicString<char>::Iterator anotherIt, Size size ) const {\n\treturn cmp( &it, otherStr, &anotherIt, size );\n}\n\n\nbool UTF8String::cmp( typename UTF8String::Iterator * it, const  BasicString<char> & otherStr, typename BasicString<char>::Iterator * anotherIt, Size size ) const {\n\twhile ( size ) {\n\t\tif ( ( **it ) == ( **anotherIt ) ) {\n\t\t\tif ( ( **it ) == char( '\\0' ) ) return true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t\tsize--;\n\t\t( *it )++;\n\t\t( *anotherIt )++;\n\t}\n\treturn true;\n}\n\nUTF8String::Size UTF8String::getSizeUTF8() const {\n\tSize numChar = 0;\n\tfor ( auto it = getBegin(); iterate( &it );) numChar++;\n\treturn numChar;\n}\n\ntypename StringASCII::Size UTF8String::codePoint2Chars( const CodePoint & codePoint, char charBuffer[4] ) {\n\tif ( codePoint > 127 ) {\n\t\tif ( codePoint > 2047 ) {\n\t\t\tif ( codePoint > 65535 ) {\n\t\t\t\tcharBuffer[0] = ( codePoint >> 18 ) | 0xF0;\n\t\t\t\tcharBuffer[1] = ( ( codePoint >> 12 ) & 0x3F ) | 0xC0;\n\t\t\t\tcharBuffer[2] = ( ( codePoint >> 6 ) & 0x3F ) | 0xC0;\n\t\t\t\tcharBuffer[3] = ( codePoint & 0x3F ) | 0x80;\n\t\t\t\treturn StringASCII::Size( 4 );\n\t\t\t} else {\t\/\/If the code point is on THREE Bytes ONLY !\n\t\t\t\tcharBuffer[0] = ( codePoint >> 12 ) | 0xE0;\n\t\t\t\tcharBuffer[1] = ( ( codePoint >> 6 ) & 0x3F ) | 0xC0;\n\t\t\t\tcharBuffer[2] = ( codePoint & 0x3F ) | 0x80;\n\t\t\t\treturn StringASCII::Size( 3 );\n\t\t\t}\n\t\t} else {\t\/\/If the code point is on TWO Bytes ONLY !\n\t\t\tcharBuffer[0] = ( codePoint >> 6 ) | 0xC0;\n\t\t\tcharBuffer[1] = ( codePoint & 0x3F ) | 0x80;\n\t\t\treturn StringASCII::Size( 2 );\n\t\t}\n\t} else {\t\t\/\/If the code point is on ONE Byte ONLY !\n\t\tcharBuffer[0] = codePoint;\n\t\treturn StringASCII::Size( 1 );\n\t}\n}\n\n\nUTF8String UTF8String::codePoint2String( const CodePoint & codePoint ) {\n\tUTF8String result(ctor::null);\n\tresult._allocateNoNullDelete( 5 );\n\tresult.size = codePoint2Chars( codePoint, result.dataTable );\n\tresult.dataTable[result.size] = char( '\\0' );\n\tresult._updateIterators();\n\treturn result;\n}\n\n\nvoid UTF8String::concat( const UTF8String & str ) {\n\tStringASCII::concat( str );\n}\n\nvoid UTF8String::concat( const StringASCII & str ) {\n\tStringASCII::concat( str.data(), str.getSize() );\n}\n\nvoid UTF8String::concat( const char * buffer, const Size & bufferSize ) {\n\tStringASCII::concat( buffer, bufferSize );\n}\n\n","avg_line_length":24.3913043478,"max_line_length":164,"alphanum_fraction":0.6187759952,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4935,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/*\n *  Copyright (c) 2014, Facebook, Inc.\n *  All rights reserved.\n *\n *  This source code is licensed under the BSD-style license found in the\n *  LICENSE file in the root directory of this source tree. An additional grant\n *  of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n#include <proxygen\/lib\/http\/HTTPConnector.h>\n\n#include <folly\/experimental\/wangle\/ssl\/SSLUtil.h>\n#include <proxygen\/lib\/http\/codec\/HTTP1xCodec.h>\n#include <proxygen\/lib\/http\/codec\/SPDYCodec.h>\n#include <proxygen\/lib\/http\/session\/HTTPTransaction.h>\n#include <proxygen\/lib\/http\/session\/HTTPUpstreamSession.h>\n#include <thrift\/lib\/cpp\/async\/TAsyncSSLSocket.h>\n\nusing namespace apache::thrift::async;\nusing namespace apache::thrift::transport;\nusing namespace folly;\nusing namespace std;\n\nnamespace proxygen {\n\nnamespace {\n\nunique_ptr<HTTPCodec> makeCodec(const string& chosenProto,\n                                bool forceHTTP1xCodecTo1_1) {\n  auto spdyVersion = SPDYCodec::getVersion(chosenProto);\n  if (spdyVersion) {\n    return folly::make_unique<SPDYCodec>(TransportDirection::UPSTREAM,\n                                         *spdyVersion);\n  } else {\n    if (!chosenProto.empty() &&\n        !HTTP1xCodec::supportsNextProtocol(chosenProto)) {\n      LOG(ERROR) << \"Chosen upstream protocol \" <<\n        \"\\\"\" << chosenProto << \"\\\" is unimplemented. \" <<\n        \"Attempting to use HTTP\/1.1\";\n    }\n\n    return folly::make_unique<HTTP1xCodec>(TransportDirection::UPSTREAM,\n                                           forceHTTP1xCodecTo1_1);\n  }\n}\n\n}\n\nHTTPConnector::HTTPConnector(\n  Callback* callback,\n  AsyncTimeoutSet* timeoutSet,\n  const string& plaintextProtocol,\n  bool forceHTTP1xCodecTo1_1):\n    cb_(CHECK_NOTNULL(callback)),\n    timeoutSet_(timeoutSet),\n    plaintextProtocol_(plaintextProtocol),\n    forceHTTP1xCodecTo1_1_(forceHTTP1xCodecTo1_1) {}\n\nHTTPConnector::~HTTPConnector() {\n  reset();\n}\n\nvoid HTTPConnector::reset() {\n  if (socket_) {\n    auto cb = cb_;\n    cb_ = nullptr;\n    socket_.reset(); \/\/ This invokes connectError() but will be ignored\n    cb_ = cb;\n  }\n}\n\nvoid HTTPConnector::connect(\n  EventBase* eventBase,\n  const folly::SocketAddress& connectAddr,\n  chrono::milliseconds timeoutMs,\n  const TAsyncSocket::OptionMap& socketOptions,\n  const folly::SocketAddress& bindAddr) {\n\n  DCHECK(!isBusy());\n  transportInfo_ = TransportInfo();\n  transportInfo_.ssl = false;\n  socket_.reset(new TAsyncSocket(eventBase));\n  connectStart_ = getCurrentTime();\n  socket_->connect(this, connectAddr, timeoutMs.count(),\n                   socketOptions, bindAddr);\n}\n\nvoid HTTPConnector::connectSSL(\n  EventBase* eventBase,\n  const folly::SocketAddress& connectAddr,\n  const shared_ptr<SSLContext>& context,\n  SSL_SESSION* session,\n  chrono::milliseconds timeoutMs,\n  const TAsyncSocket::OptionMap& socketOptions,\n  const folly::SocketAddress& bindAddr) {\n\n  DCHECK(!isBusy());\n  transportInfo_ = TransportInfo();\n  transportInfo_.ssl = true;\n  auto sslSock = new TAsyncSSLSocket(context, eventBase);\n  if (session) {\n    sslSock->setSSLSession(session, true \/* take ownership *\/);\n  }\n  socket_.reset(sslSock);\n  connectStart_ = getCurrentTime();\n  socket_->connect(this, connectAddr, timeoutMs.count(),\n                   socketOptions, bindAddr);\n}\n\nstd::chrono::milliseconds HTTPConnector::timeElapsed() {\n  if (timePointInitialized(connectStart_)) {\n    return millisecondsSince(connectStart_);\n  }\n  return std::chrono::milliseconds(0);\n}\n\n\/\/ Callback interface\n\nvoid HTTPConnector::connectSuccess() noexcept {\n  if (!cb_) {\n    return;\n  }\n\n  folly::SocketAddress localAddress;\n  folly::SocketAddress peerAddress;\n  socket_->getLocalAddress(&localAddress);\n  socket_->getPeerAddress(&peerAddress);\n\n  std::unique_ptr<HTTPCodec> codec;\n\n  transportInfo_.acceptTime = getCurrentTime();\n  if (transportInfo_.ssl) {\n    TAsyncSSLSocket* sslSocket = static_cast<TAsyncSSLSocket*>(socket_.get());\n\n    const char* npnProto;\n    unsigned npnProtoLen;\n    sslSocket->getSelectedNextProtocol(\n      reinterpret_cast<const unsigned char**>(&npnProto), &npnProtoLen);\n\n    transportInfo_.sslNextProtocol = string(npnProto, npnProtoLen);\n    transportInfo_.sslSetupTime = millisecondsSince(connectStart_);\n    transportInfo_.sslCipher = sslSocket->getNegotiatedCipherName();\n    transportInfo_.sslVersion = sslSocket->getSSLVersion();\n    transportInfo_.sslResume = SSLUtil::getResumeState(sslSocket);\n\n    codec = makeCodec(transportInfo_.sslNextProtocol, forceHTTP1xCodecTo1_1_);\n  } else {\n    codec = makeCodec(plaintextProtocol_, forceHTTP1xCodecTo1_1_);\n  }\n\n  HTTPUpstreamSession* session = new HTTPUpstreamSession(\n    timeoutSet_,\n    std::move(socket_), localAddress, peerAddress,\n    std::move(codec), transportInfo_, nullptr);\n\n  cb_->connectSuccess(session);\n}\n\nvoid HTTPConnector::connectError(const TTransportException& ex) noexcept {\n  socket_.reset();\n  if (cb_) {\n    cb_->connectError(ex);\n  }\n}\n\n}\n","avg_line_length":29.5508982036,"max_line_length":79,"alphanum_fraction":0.714893617,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":17784,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/\/\n\/\/ Created by Alan Freitas on 2020-07-06.\n\/\/\n\n#include <string>\n#include <iostream>\n#include <matplot\/core\/line_spec.h>\n#include <matplot\/util\/colors.h>\n#include <matplot\/util\/common.h>\n#include <matplot\/util\/handle_types.h>\n\nnamespace matplot {\n    line_spec::line_spec() = default;\n\n    line_spec::line_spec(const std::string& expr) : marker_style_(marker_style::none) {\n        parse_string(expr);\n    }\n\n    void line_spec::parse_string(const std::string& expr) {\n        for (size_t expr_pos = 0; expr_pos != expr.size(); ++expr_pos) {\n            size_t chars_left = expr.size() - expr_pos;\n            switch (expr[expr_pos]) {\n                case '-':\n                    if (chars_left != 1 && expr[expr_pos + 1] == '-') {\n                        \/\/ \"--\"\n                        line_style_ = line_style::dashed_line;\n                        ++expr_pos;\n                    } else if (chars_left != 1 && expr[expr_pos + 1] == '.') {\n                        \/\/ \"-.\"\n                        line_style_ = line_style::dash_dot_line;\n                        ++expr_pos;\n                    } else {\n                        line_style_ = line_style::solid_line;\n                    }\n                    break;\n                case ':':\n                    line_style_ = line_style::dotted_line;\n                    break;\n                case '+':\n                    marker_style_ = marker_style::plus_sign;\n                    break;\n                case 'o':\n                    marker_style_ = marker_style::circle;\n                    break;\n                case '*':\n                    marker_style_ = marker_style::asterisk;\n                    break;\n                case '.':\n                    marker_style_ = marker_style::point;\n                    break;\n                case 'x':\n                    marker_style_ = marker_style::cross;\n                    break;\n                case 's':\n                    marker_style_ = marker_style::square;\n                    if (expr.substr(expr_pos,6) == \"square\") {\n                        expr_pos += 5;\n                    }\n                    break;\n                case 'd':\n                    marker_style_ = marker_style::diamond;\n                    if (expr.substr(expr_pos,7) == \"diamond\") {\n                        expr_pos += 6;\n                    }\n                    break;\n                case '^':\n                    marker_style_ = marker_style::upward_pointing_triangle;\n                    break;\n                case 'V':\n                case 'v':\n                    marker_style_ = marker_style::downward_pointing_triangle;\n                    break;\n                case '>':\n                    marker_style_ = marker_style::custom;\n                    custom_marker_ = u8\"\u25b6\";\n                    break;\n                case '<':\n                    marker_style_ = marker_style::custom;\n                    custom_marker_ = u8\"\u25c0\";\n                    break;\n                case 'p':\n                    marker_style_ = marker_style::pentagram;\n                    if (expr.substr(expr_pos,9) == \"pentagram\") {\n                        expr_pos += 8;\n                    }\n                    break;\n                case 'h':\n                    marker_style_ = marker_style::hexagram;\n                    if (expr.substr(expr_pos,8) == \"hexagram\") {\n                        expr_pos += 7;\n                    }\n                    break;\n                case 'f':\n                    marker_face_ = true;\n                    if (marker_style_ == marker_style::none && line_style_ == line_style::none) {\n                        marker_style_ = marker_style::circle;\n                        line_style_ = line_style::solid_line;\n                    }\n                    if (expr.substr(expr_pos,6) == \"filled\") {\n                        expr_pos += 5;\n                    }\n                    break;\n                case 'b':\n                case 'k':\n                case 'r':\n                case 'g':\n                case 'y':\n                case 'c':\n                case 'm':\n                case 'w':\n                    color_ = to_array(char_to_color(expr[expr_pos]));\n                    marker_color_ = color_;\n                    marker_face_color_ = color_;\n                    user_color_ = true;\n                    marker_user_color_ = true;\n                    marker_face_user_color_ = true;\n                    break;\n            }\n        }\n        if (!has_line() && !has_non_custom_marker()) {\n            line_style_ = line_style::solid_line;\n        }\n    }\n\n    std::string line_spec::plot_string(style_to_plot sty, bool include_style) {\n        \/\/ plot cos(x) with linespoints linecolor rgb \"#000000\" dashtype 3 linewidth 3 linetype 4\n        std::string res;\n        if (include_style) {\n            switch (sty) {\n                case style_to_plot::plot_line_and_marker:\n                    res += \" with linespoints\";\n                    break;\n                case style_to_plot::plot_line_only:\n                    res += \" with line\";\n                    break;\n                case style_to_plot::plot_marker_only:\n                case style_to_plot::plot_marker_face_only:\n                    res += \" with points\";\n                    break;\n            }\n        }\n\n        switch (sty) {\n            case style_to_plot::plot_line_and_marker:\n            case style_to_plot::plot_line_only:\n                res += \" linecolor rgb \\\"\" + to_string(color_) + \"\\\"\";\n                break;\n            case style_to_plot::plot_marker_only:\n                res += \" linecolor rgb \\\"\" + to_string(marker_color_) + \"\\\"\";\n                break;\n            case style_to_plot::plot_marker_face_only:\n                res += \" linecolor rgb \\\"\" + to_string(marker_face_color_) + \"\\\"\";\n                break;\n        }\n\n        const bool is_plotting_line = sty == style_to_plot::plot_line_and_marker || sty == style_to_plot::plot_line_only;\n        if (is_plotting_line) {\n            switch (line_style_) {\n                case line_style::solid_line:\n                    res += \" dashtype 1\";\n                    break;\n                case line_style::dashed_line:\n                    res += \" dashtype '--'\";\n                    break;\n                case line_style::dotted_line:\n                    res += \" dashtype '.'\";\n                    break;\n                case line_style::dash_dot_line:\n                    res += \" dashtype '-.'\";\n                    break;\n                default:\n                    break;\n            }\n            res += \" linewidth \" + num2str(line_width_);\n        }\n\n        switch (sty) {\n            case style_to_plot::plot_line_and_marker:\n            case style_to_plot::plot_marker_only:\n                res += \" pointsize \" + num2str(marker_size_\/6.);\n                break;\n            case style_to_plot::plot_line_only:\n                break;\n            case style_to_plot::plot_marker_face_only:\n                res += \" pointsize \" + num2str(marker_size_\/10.);\n                break;\n        }\n\n        std::string marker_type_key;\n        switch (sty) {\n            case style_to_plot::plot_line_only:\n                marker_type_key = \" linetype\";\n                break;\n            case style_to_plot::plot_line_and_marker:\n            case style_to_plot::plot_marker_only:\n            case style_to_plot::plot_marker_face_only:\n                marker_type_key = \" pointtype\";\n                break;\n        }\n\n        switch (marker_style_) {\n            case marker_style::plus_sign:\n                res += marker_type_key + \" 1\";\n                break;\n            case marker_style::circle:\n                res += marker_type_key + (!marker_face_ ? \" 6\" : \" 7\");\n                break;\n            case marker_style::asterisk:\n                res += marker_type_key + \" 3\";\n                break;\n            case marker_style::point:\n                res += marker_type_key + \" 7\";\n                break;\n            case marker_style::cross:\n                res += marker_type_key + \" 2\";\n                break;\n            case marker_style::square:\n                res += marker_type_key + (!marker_face_ ? \" 4\" : \" 5\");\n                break;\n            case marker_style::diamond:\n                res += marker_type_key + (!marker_face_ ? \" 12\" : \" 13\");\n                break;\n            case marker_style::upward_pointing_triangle:\n                res += marker_type_key + (!marker_face_ ? \" 8\" : \" 9\");\n                break;\n            case marker_style::downward_pointing_triangle:\n                res += marker_type_key + (!marker_face_ ? \" 10\" : \" 11\");\n                break;\n            case marker_style::pentagram:\n                res += marker_type_key + (!marker_face_ ? \" 14\" : \" 15\");\n                break;\n            default:\n                \/\/ if none or custom, we have to plot the markers as labels\n                \/\/ the labels should come before the plot command,\n                \/\/ so there is nothing to do here\n                res += marker_type_key + \" -1\";\n                break;\n        }\n        return res;\n    }\n\n    bool line_spec::can_plot_line_and_marker_together() {\n        return has_line() && has_non_custom_marker() && line_and_marker_are_the_same_color() ;\n    }\n\n\n    bool line_spec::has_line() {\n        return line_style_ != line_style::none;\n    }\n\n\n    bool line_spec::has_non_custom_marker() {\n        return marker_style_ != marker_style::none && marker_style_ != marker_style::custom;\n    }\n\n    bool line_spec::has_marker_face() {\n        return has_non_custom_marker() && marker_face_;\n    }\n\n    bool line_spec::line_and_marker_are_the_same_color() const {\n        return\n        std::equal(color_.begin(), color_.end(), marker_color_.begin()) &&\n                marker_and_face_are_the_same_color();\n    }\n\n    bool line_spec::marker_and_face_are_the_same_color() const {\n        return std::equal(marker_color_.begin(), marker_color_.end(), marker_face_color_.begin());\n    }\n\n    void line_spec::touch() {\n        if (touch_function_) {\n            touch_function_();\n        }\n    }\n\n    const std::array<float, 4>& line_spec::color() const {\n        return color_;\n    }\n\n    const float line_spec::alpha() const {\n        return color_[0];\n    }\n\n    void line_spec::color(const std::array<float, 3> &color) {\n        color_ = {0,color[0],color[1],color[2]};\n        touch();\n    }\n\n    void line_spec::color(const std::array<float, 4> &color) {\n        color_ = color;\n        user_color_ = true;\n        if (!marker_user_color_) {\n            marker_color_ = color;\n        }\n        if (!marker_face_user_color_) {\n            marker_face_color_ = color;\n        }\n        touch();\n    }\n\n    void line_spec::color(std::initializer_list<float> il) {\n        if (il.size() == 4) {\n            std::array<float, 4> a{};\n            std::copy(il.begin(), il.end(), a.begin());\n            color(a);\n        } else {\n            std::array<float, 3> a{};\n            std::copy(il.begin(), il.end(), a.begin());\n            color(a);\n        }\n    }\n\n    void line_spec::color(const std::string& c) {\n        color(to_array(string_to_color(c)));\n    }\n\n    void line_spec::color(enum color c) {\n        color(to_array(c));\n    }\n\n    void line_spec::alpha(float alpha) {\n        color_[0] = alpha;\n        touch();\n    }\n\n    bool line_spec::user_color() const {\n        return user_color_;\n    }\n\n    void line_spec::user_color(bool user_color) {\n        user_color_ = user_color;\n        touch();\n    }\n\n    enum line_spec::line_style line_spec::line_style() const {\n        return line_style_;\n    }\n\n    void line_spec::line_style(enum line_spec::line_style line_style) {\n        line_style_ = line_style;\n        touch();\n    }\n\n    float line_spec::line_width() const {\n        return line_width_;\n    }\n\n    void line_spec::line_width(float line_width) {\n        line_width_ = line_width;\n        touch();\n    }\n\n    enum line_spec::marker_style line_spec::marker_style() const {\n        return marker_style_;\n    }\n\n    void line_spec::marker_style(enum line_spec::marker_style marker_style) {\n        marker_style_ = marker_style;\n        touch();\n    }\n\n    void line_spec::marker_style(const std::string& marker_style) {\n        switch (marker_style[0]) {\n            case '+':\n                marker_style_ = marker_style::plus_sign;\n                break;\n            case 'O':\n            case 'o':\n                marker_style_ = marker_style::circle;\n                break;\n            case '*':\n                marker_style_ = marker_style::asterisk;\n                break;\n            case '.':\n                marker_style_ = marker_style::point;\n                break;\n            case 'X':\n            case 'x':\n                marker_style_ = marker_style::cross;\n                break;\n            case 'S':\n            case 's':\n                marker_style_ = marker_style::square;\n                break;\n            case 'D':\n            case 'd':\n                marker_style_ = marker_style::diamond;\n                break;\n            case '^':\n                marker_style_ = marker_style::upward_pointing_triangle;\n                break;\n            case 'V':\n            case 'v':\n                marker_style_ = marker_style::downward_pointing_triangle;\n                break;\n            case '>':\n                marker_style_ = marker_style::custom;\n                custom_marker_ = u8\"\u25b6\";\n                break;\n            case '<':\n                marker_style_ = marker_style::custom;\n                custom_marker_ = u8\"\u25c0\";\n                break;\n            case 'P':\n            case 'p':\n                marker_style_ = marker_style::pentagram;\n                break;\n            case 'H':\n            case 'h':\n                marker_style_ = marker_style::hexagram;\n                break;\n            default:\n                return;\n        }\n        touch();\n    }\n\n    enum line_spec::marker_style line_spec::marker() const {\n        return marker_style();\n    }\n\n    const std::string &line_spec::custom_marker() const {\n        return custom_marker_;\n    }\n\n    void line_spec::custom_marker(const std::string &custom_marker) {\n        custom_marker_ = custom_marker;\n        touch();\n    }\n\n    float line_spec::marker_size() const {\n        return marker_size_;\n    }\n\n    void line_spec::marker_size(float marker_size) {\n        marker_size_ = marker_size;\n        touch();\n    }\n\n    const std::array<float, 4> &line_spec::marker_color() const {\n        return marker_color_;\n    }\n\n    const float line_spec::marker_alpha() const {\n        return marker_color_[0];\n    }\n\n    void line_spec::marker_color(const std::array<float, 3> &color) {\n        marker_color(std::array<float,4>({0,color[0],color[1],color[2]}));\n    }\n\n    void line_spec::marker_color(const std::array<float, 4> &marker_color) {\n        marker_color_ = marker_color;\n        marker_user_color_ = true;\n        if (!marker_face_user_color_) {\n            marker_face_color_ = marker_color_;\n        }\n        touch();\n    }\n\n    void line_spec::marker_color(std::initializer_list<float> il) {\n        if (il.size() == 3) {\n            std::array<float,3> ar{};\n            std::copy(il.begin(),il.end(),ar.begin());\n            marker_color(ar);\n        } else if (il.size() == 4) {\n            std::array<float,4> ar{};\n            std::copy(il.begin(),il.end(),ar.begin());\n            marker_color(ar);\n        }\n\n    }\n\n    void line_spec::marker_color(const std::string &m){\n        marker_color_ = to_array(string_to_color(m));\n        touch();\n    }\n\n    void line_spec::marker_color(enum color m){\n        marker_color_ = to_array(m);\n        touch();\n    }\n\n    void line_spec::marker_alpha(float alpha) {\n        marker_color_[0] = alpha;\n        touch();\n    }\n\n    bool line_spec::marker_user_color() const {\n        return marker_user_color_;\n    }\n\n    void line_spec::marker_user_color(bool user_color) {\n        marker_user_color_ = user_color;\n    }\n\n    const std::array<float, 4>& line_spec::marker_face_color() const {\n        return marker_face_color_;\n    }\n\n    float line_spec::marker_face_alpha() const {\n        return marker_face_color_[0];\n    }\n\n    void line_spec::marker_face_color(std::initializer_list<float> color) {\n        if (color.size() == 3) {\n            std::array<float,3> ar{};\n            std::copy(color.begin(), color.end(), ar.begin());\n            marker_face_color(ar);\n        } else {\n            std::array<float,3> ar{};\n            std::copy(color.begin(), color.end(), ar.begin());\n            marker_face_color(ar);\n        }\n    }\n\n    void line_spec::marker_face_color(const std::string& color) {\n        marker_face_color(to_array(color));\n    }\n\n    void line_spec::marker_face_color(enum color c) {\n        marker_face_color(to_array(c));\n    }\n\n    void line_spec::marker_face_alpha(float alpha) {\n        marker_face_color_[0] = alpha;\n    }\n\n    bool line_spec::marker_face_user_color() const {\n        return marker_face_user_color_;\n    }\n\n    void line_spec::marker_face_user_color(bool user_color) {\n        marker_face_user_color_ = user_color;\n    }\n\n    bool line_spec::marker_face() const {\n        return marker_face_;\n    }\n\n    void line_spec::marker_face(bool marker_face) {\n        marker_face_ = marker_face;\n        touch();\n    }\n\n    void line_spec::marker_face_color(const std::array<float, 4> &marker_face_color) {\n        marker_face_color_ = marker_face_color;\n        marker_face_user_color_ = true;\n        marker_face_ = true;\n        touch();\n    }\n\n    void line_spec::marker_face_color(const std::array<float, 3> &color) {\n        marker_face_color(std::array<float,4>({0,color[0],color[1],color[2]}));\n    }\n\n\n}","avg_line_length":31.8709677419,"max_line_length":121,"alphanum_fraction":0.4968511021,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":35924,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\n#include \"repository\/ISwiftMtParser.h\"\n#include \"SwiftMtMessage.pb.h\"\n#include <vector>\n#include <string>\n#include \"BaseErrorListener.h\"\n#include \"SwiftMtParser_MT700Lexer.h\"\n\n\n\/\/ Generated from C:\/programming\/message-converter-c\/message\/generation\/swift-mt-generation\/repository\/SR2018\/grammars\/SwiftMtParser_MT700.g4 by ANTLR 4.7.2\n\n\n#include \"SwiftMtParser_MT700Listener.h\"\n\n#include \"SwiftMtParser_MT700Parser.h\"\n\n\nusing namespace antlrcpp;\nusing namespace message::definition::swift::mt::parsers::sr2018;\nusing namespace antlr4;\n\nSwiftMtParser_MT700Parser::SwiftMtParser_MT700Parser(TokenStream *input) : Parser(input) {\n  _interpreter = new atn::ParserATNSimulator(this, _atn, _decisionToDFA, _sharedContextCache);\n}\n\nSwiftMtParser_MT700Parser::~SwiftMtParser_MT700Parser() {\n  delete _interpreter;\n}\n\nstd::string SwiftMtParser_MT700Parser::getGrammarFileName() const {\n  return \"SwiftMtParser_MT700.g4\";\n}\n\nconst std::vector<std::string>& SwiftMtParser_MT700Parser::getRuleNames() const {\n  return _ruleNames;\n}\n\ndfa::Vocabulary& SwiftMtParser_MT700Parser::getVocabulary() const {\n  return _vocabulary;\n}\n\n\n\/\/----------------- MessageContext ------------------------------------------------------------------\n\nSwiftMtParser_MT700Parser::MessageContext::MessageContext(ParserRuleContext *parent, size_t invokingState)\n  : ParserRuleContext(parent, invokingState) {\n}\n\nSwiftMtParser_MT700Parser::BhContext* SwiftMtParser_MT700Parser::MessageContext::bh() {\n  return getRuleContext<SwiftMtParser_MT700Parser::BhContext>(0);\n}\n\nSwiftMtParser_MT700Parser::AhContext* SwiftMtParser_MT700Parser::MessageContext::ah() {\n  return getRuleContext<SwiftMtParser_MT700Parser::AhContext>(0);\n}\n\nSwiftMtParser_MT700Parser::MtContext* SwiftMtParser_MT700Parser::MessageContext::mt() {\n  return getRuleContext<SwiftMtParser_MT700Parser::MtContext>(0);\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::MessageContext::EOF() {\n  return getToken(SwiftMtParser_MT700Parser::EOF, 0);\n}\n\nSwiftMtParser_MT700Parser::UhContext* SwiftMtParser_MT700Parser::MessageContext::uh() {\n  return getRuleContext<SwiftMtParser_MT700Parser::UhContext>(0);\n}\n\nSwiftMtParser_MT700Parser::TrContext* SwiftMtParser_MT700Parser::MessageContext::tr() {\n  return getRuleContext<SwiftMtParser_MT700Parser::TrContext>(0);\n}\n\n\nsize_t SwiftMtParser_MT700Parser::MessageContext::getRuleIndex() const {\n  return SwiftMtParser_MT700Parser::RuleMessage;\n}\n\nvoid SwiftMtParser_MT700Parser::MessageContext::enterRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->enterMessage(this);\n}\n\nvoid SwiftMtParser_MT700Parser::MessageContext::exitRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->exitMessage(this);\n}\n\nSwiftMtParser_MT700Parser::MessageContext* SwiftMtParser_MT700Parser::message() {\n  MessageContext *_localctx = _tracker.createInstance<MessageContext>(_ctx, getState());\n  enterRule(_localctx, 0, SwiftMtParser_MT700Parser::RuleMessage);\n  size_t _la = 0;\n\n  auto onExit = finally([=] {\n    exitRule();\n  });\n  try {\n    enterOuterAlt(_localctx, 1);\n    setState(24);\n    bh();\n    setState(25);\n    ah();\n    setState(27);\n    _errHandler->sync(this);\n\n    _la = _input->LA(1);\n    if (_la == SwiftMtParser_MT700Parser::TAG_UH) {\n      setState(26);\n      uh();\n    }\n    setState(29);\n    mt();\n    setState(31);\n    _errHandler->sync(this);\n\n    _la = _input->LA(1);\n    if (_la == SwiftMtParser_MT700Parser::TAG_TR) {\n      setState(30);\n      tr();\n    }\n    setState(33);\n    match(SwiftMtParser_MT700Parser::EOF);\n   \n  }\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n\n  return _localctx;\n}\n\n\/\/----------------- BhContext ------------------------------------------------------------------\n\nSwiftMtParser_MT700Parser::BhContext::BhContext(ParserRuleContext *parent, size_t invokingState)\n  : ParserRuleContext(parent, invokingState) {\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::BhContext::TAG_BH() {\n  return getToken(SwiftMtParser_MT700Parser::TAG_BH, 0);\n}\n\nSwiftMtParser_MT700Parser::Bh_contentContext* SwiftMtParser_MT700Parser::BhContext::bh_content() {\n  return getRuleContext<SwiftMtParser_MT700Parser::Bh_contentContext>(0);\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::BhContext::RBRACE() {\n  return getToken(SwiftMtParser_MT700Parser::RBRACE, 0);\n}\n\n\nsize_t SwiftMtParser_MT700Parser::BhContext::getRuleIndex() const {\n  return SwiftMtParser_MT700Parser::RuleBh;\n}\n\nvoid SwiftMtParser_MT700Parser::BhContext::enterRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->enterBh(this);\n}\n\nvoid SwiftMtParser_MT700Parser::BhContext::exitRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->exitBh(this);\n}\n\nSwiftMtParser_MT700Parser::BhContext* SwiftMtParser_MT700Parser::bh() {\n  BhContext *_localctx = _tracker.createInstance<BhContext>(_ctx, getState());\n  enterRule(_localctx, 2, SwiftMtParser_MT700Parser::RuleBh);\n\n  auto onExit = finally([=] {\n    exitRule();\n  });\n  try {\n    enterOuterAlt(_localctx, 1);\n    setState(35);\n    match(SwiftMtParser_MT700Parser::TAG_BH);\n    setState(36);\n    bh_content();\n    setState(37);\n    match(SwiftMtParser_MT700Parser::RBRACE);\n   \n  }\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n\n  return _localctx;\n}\n\n\/\/----------------- Bh_contentContext ------------------------------------------------------------------\n\nSwiftMtParser_MT700Parser::Bh_contentContext::Bh_contentContext(ParserRuleContext *parent, size_t invokingState)\n  : ParserRuleContext(parent, invokingState) {\n}\n\nstd::vector<tree::TerminalNode *> SwiftMtParser_MT700Parser::Bh_contentContext::RBRACE() {\n  return getTokens(SwiftMtParser_MT700Parser::RBRACE);\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::Bh_contentContext::RBRACE(size_t i) {\n  return getToken(SwiftMtParser_MT700Parser::RBRACE, i);\n}\n\n\nsize_t SwiftMtParser_MT700Parser::Bh_contentContext::getRuleIndex() const {\n  return SwiftMtParser_MT700Parser::RuleBh_content;\n}\n\nvoid SwiftMtParser_MT700Parser::Bh_contentContext::enterRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->enterBh_content(this);\n}\n\nvoid SwiftMtParser_MT700Parser::Bh_contentContext::exitRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->exitBh_content(this);\n}\n\nSwiftMtParser_MT700Parser::Bh_contentContext* SwiftMtParser_MT700Parser::bh_content() {\n  Bh_contentContext *_localctx = _tracker.createInstance<Bh_contentContext>(_ctx, getState());\n  enterRule(_localctx, 4, SwiftMtParser_MT700Parser::RuleBh_content);\n  size_t _la = 0;\n\n  auto onExit = finally([=] {\n    exitRule();\n  });\n  try {\n    enterOuterAlt(_localctx, 1);\n    setState(40); \n    _errHandler->sync(this);\n    _la = _input->LA(1);\n    do {\n      setState(39);\n      _la = _input->LA(1);\n      if (_la == 0 || _la == Token::EOF || (_la == SwiftMtParser_MT700Parser::RBRACE)) {\n      _errHandler->recoverInline(this);\n      }\n      else {\n        _errHandler->reportMatch(this);\n        consume();\n      }\n      setState(42); \n      _errHandler->sync(this);\n      _la = _input->LA(1);\n    } while ((((_la & ~ 0x3fULL) == 0) &&\n      ((1ULL << _la) & ((1ULL << SwiftMtParser_MT700Parser::TAG_BH)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_AH)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_UH)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_MT)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_TR)\n      | (1ULL << SwiftMtParser_MT700Parser::MT_END)\n      | (1ULL << SwiftMtParser_MT700Parser::LBRACE)\n      | (1ULL << SwiftMtParser_MT700Parser::COLON)\n      | (1ULL << SwiftMtParser_MT700Parser::START_OF_FIELD)\n      | (1ULL << SwiftMtParser_MT700Parser::ANY))) != 0));\n   \n  }\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n\n  return _localctx;\n}\n\n\/\/----------------- AhContext ------------------------------------------------------------------\n\nSwiftMtParser_MT700Parser::AhContext::AhContext(ParserRuleContext *parent, size_t invokingState)\n  : ParserRuleContext(parent, invokingState) {\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::AhContext::TAG_AH() {\n  return getToken(SwiftMtParser_MT700Parser::TAG_AH, 0);\n}\n\nSwiftMtParser_MT700Parser::Ah_contentContext* SwiftMtParser_MT700Parser::AhContext::ah_content() {\n  return getRuleContext<SwiftMtParser_MT700Parser::Ah_contentContext>(0);\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::AhContext::RBRACE() {\n  return getToken(SwiftMtParser_MT700Parser::RBRACE, 0);\n}\n\n\nsize_t SwiftMtParser_MT700Parser::AhContext::getRuleIndex() const {\n  return SwiftMtParser_MT700Parser::RuleAh;\n}\n\nvoid SwiftMtParser_MT700Parser::AhContext::enterRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->enterAh(this);\n}\n\nvoid SwiftMtParser_MT700Parser::AhContext::exitRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->exitAh(this);\n}\n\nSwiftMtParser_MT700Parser::AhContext* SwiftMtParser_MT700Parser::ah() {\n  AhContext *_localctx = _tracker.createInstance<AhContext>(_ctx, getState());\n  enterRule(_localctx, 6, SwiftMtParser_MT700Parser::RuleAh);\n\n  auto onExit = finally([=] {\n    exitRule();\n  });\n  try {\n    enterOuterAlt(_localctx, 1);\n    setState(44);\n    match(SwiftMtParser_MT700Parser::TAG_AH);\n    setState(45);\n    ah_content();\n    setState(46);\n    match(SwiftMtParser_MT700Parser::RBRACE);\n   \n  }\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n\n  return _localctx;\n}\n\n\/\/----------------- Ah_contentContext ------------------------------------------------------------------\n\nSwiftMtParser_MT700Parser::Ah_contentContext::Ah_contentContext(ParserRuleContext *parent, size_t invokingState)\n  : ParserRuleContext(parent, invokingState) {\n}\n\nstd::vector<tree::TerminalNode *> SwiftMtParser_MT700Parser::Ah_contentContext::RBRACE() {\n  return getTokens(SwiftMtParser_MT700Parser::RBRACE);\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::Ah_contentContext::RBRACE(size_t i) {\n  return getToken(SwiftMtParser_MT700Parser::RBRACE, i);\n}\n\n\nsize_t SwiftMtParser_MT700Parser::Ah_contentContext::getRuleIndex() const {\n  return SwiftMtParser_MT700Parser::RuleAh_content;\n}\n\nvoid SwiftMtParser_MT700Parser::Ah_contentContext::enterRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->enterAh_content(this);\n}\n\nvoid SwiftMtParser_MT700Parser::Ah_contentContext::exitRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->exitAh_content(this);\n}\n\nSwiftMtParser_MT700Parser::Ah_contentContext* SwiftMtParser_MT700Parser::ah_content() {\n  Ah_contentContext *_localctx = _tracker.createInstance<Ah_contentContext>(_ctx, getState());\n  enterRule(_localctx, 8, SwiftMtParser_MT700Parser::RuleAh_content);\n  size_t _la = 0;\n\n  auto onExit = finally([=] {\n    exitRule();\n  });\n  try {\n    enterOuterAlt(_localctx, 1);\n    setState(49); \n    _errHandler->sync(this);\n    _la = _input->LA(1);\n    do {\n      setState(48);\n      _la = _input->LA(1);\n      if (_la == 0 || _la == Token::EOF || (_la == SwiftMtParser_MT700Parser::RBRACE)) {\n      _errHandler->recoverInline(this);\n      }\n      else {\n        _errHandler->reportMatch(this);\n        consume();\n      }\n      setState(51); \n      _errHandler->sync(this);\n      _la = _input->LA(1);\n    } while ((((_la & ~ 0x3fULL) == 0) &&\n      ((1ULL << _la) & ((1ULL << SwiftMtParser_MT700Parser::TAG_BH)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_AH)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_UH)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_MT)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_TR)\n      | (1ULL << SwiftMtParser_MT700Parser::MT_END)\n      | (1ULL << SwiftMtParser_MT700Parser::LBRACE)\n      | (1ULL << SwiftMtParser_MT700Parser::COLON)\n      | (1ULL << SwiftMtParser_MT700Parser::START_OF_FIELD)\n      | (1ULL << SwiftMtParser_MT700Parser::ANY))) != 0));\n   \n  }\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n\n  return _localctx;\n}\n\n\/\/----------------- UhContext ------------------------------------------------------------------\n\nSwiftMtParser_MT700Parser::UhContext::UhContext(ParserRuleContext *parent, size_t invokingState)\n  : ParserRuleContext(parent, invokingState) {\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::UhContext::TAG_UH() {\n  return getToken(SwiftMtParser_MT700Parser::TAG_UH, 0);\n}\n\nSwiftMtParser_MT700Parser::Sys_blockContext* SwiftMtParser_MT700Parser::UhContext::sys_block() {\n  return getRuleContext<SwiftMtParser_MT700Parser::Sys_blockContext>(0);\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::UhContext::RBRACE() {\n  return getToken(SwiftMtParser_MT700Parser::RBRACE, 0);\n}\n\n\nsize_t SwiftMtParser_MT700Parser::UhContext::getRuleIndex() const {\n  return SwiftMtParser_MT700Parser::RuleUh;\n}\n\nvoid SwiftMtParser_MT700Parser::UhContext::enterRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->enterUh(this);\n}\n\nvoid SwiftMtParser_MT700Parser::UhContext::exitRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->exitUh(this);\n}\n\nSwiftMtParser_MT700Parser::UhContext* SwiftMtParser_MT700Parser::uh() {\n  UhContext *_localctx = _tracker.createInstance<UhContext>(_ctx, getState());\n  enterRule(_localctx, 10, SwiftMtParser_MT700Parser::RuleUh);\n\n  auto onExit = finally([=] {\n    exitRule();\n  });\n  try {\n    enterOuterAlt(_localctx, 1);\n    setState(53);\n    match(SwiftMtParser_MT700Parser::TAG_UH);\n    setState(54);\n    sys_block();\n    setState(55);\n    match(SwiftMtParser_MT700Parser::RBRACE);\n   \n  }\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n\n  return _localctx;\n}\n\n\/\/----------------- TrContext ------------------------------------------------------------------\n\nSwiftMtParser_MT700Parser::TrContext::TrContext(ParserRuleContext *parent, size_t invokingState)\n  : ParserRuleContext(parent, invokingState) {\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::TrContext::TAG_TR() {\n  return getToken(SwiftMtParser_MT700Parser::TAG_TR, 0);\n}\n\nSwiftMtParser_MT700Parser::Sys_blockContext* SwiftMtParser_MT700Parser::TrContext::sys_block() {\n  return getRuleContext<SwiftMtParser_MT700Parser::Sys_blockContext>(0);\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::TrContext::RBRACE() {\n  return getToken(SwiftMtParser_MT700Parser::RBRACE, 0);\n}\n\n\nsize_t SwiftMtParser_MT700Parser::TrContext::getRuleIndex() const {\n  return SwiftMtParser_MT700Parser::RuleTr;\n}\n\nvoid SwiftMtParser_MT700Parser::TrContext::enterRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->enterTr(this);\n}\n\nvoid SwiftMtParser_MT700Parser::TrContext::exitRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->exitTr(this);\n}\n\nSwiftMtParser_MT700Parser::TrContext* SwiftMtParser_MT700Parser::tr() {\n  TrContext *_localctx = _tracker.createInstance<TrContext>(_ctx, getState());\n  enterRule(_localctx, 12, SwiftMtParser_MT700Parser::RuleTr);\n\n  auto onExit = finally([=] {\n    exitRule();\n  });\n  try {\n    enterOuterAlt(_localctx, 1);\n    setState(57);\n    match(SwiftMtParser_MT700Parser::TAG_TR);\n    setState(58);\n    sys_block();\n    setState(59);\n    match(SwiftMtParser_MT700Parser::RBRACE);\n   \n  }\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n\n  return _localctx;\n}\n\n\/\/----------------- Sys_blockContext ------------------------------------------------------------------\n\nSwiftMtParser_MT700Parser::Sys_blockContext::Sys_blockContext(ParserRuleContext *parent, size_t invokingState)\n  : ParserRuleContext(parent, invokingState) {\n}\n\nstd::vector<SwiftMtParser_MT700Parser::Sys_elementContext *> SwiftMtParser_MT700Parser::Sys_blockContext::sys_element() {\n  return getRuleContexts<SwiftMtParser_MT700Parser::Sys_elementContext>();\n}\n\nSwiftMtParser_MT700Parser::Sys_elementContext* SwiftMtParser_MT700Parser::Sys_blockContext::sys_element(size_t i) {\n  return getRuleContext<SwiftMtParser_MT700Parser::Sys_elementContext>(i);\n}\n\n\nsize_t SwiftMtParser_MT700Parser::Sys_blockContext::getRuleIndex() const {\n  return SwiftMtParser_MT700Parser::RuleSys_block;\n}\n\nvoid SwiftMtParser_MT700Parser::Sys_blockContext::enterRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->enterSys_block(this);\n}\n\nvoid SwiftMtParser_MT700Parser::Sys_blockContext::exitRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->exitSys_block(this);\n}\n\nSwiftMtParser_MT700Parser::Sys_blockContext* SwiftMtParser_MT700Parser::sys_block() {\n  Sys_blockContext *_localctx = _tracker.createInstance<Sys_blockContext>(_ctx, getState());\n  enterRule(_localctx, 14, SwiftMtParser_MT700Parser::RuleSys_block);\n  size_t _la = 0;\n\n  auto onExit = finally([=] {\n    exitRule();\n  });\n  try {\n    enterOuterAlt(_localctx, 1);\n    setState(62); \n    _errHandler->sync(this);\n    _la = _input->LA(1);\n    do {\n      setState(61);\n      sys_element();\n      setState(64); \n      _errHandler->sync(this);\n      _la = _input->LA(1);\n    } while (_la == SwiftMtParser_MT700Parser::LBRACE);\n   \n  }\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n\n  return _localctx;\n}\n\n\/\/----------------- Sys_elementContext ------------------------------------------------------------------\n\nSwiftMtParser_MT700Parser::Sys_elementContext::Sys_elementContext(ParserRuleContext *parent, size_t invokingState)\n  : ParserRuleContext(parent, invokingState) {\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::Sys_elementContext::LBRACE() {\n  return getToken(SwiftMtParser_MT700Parser::LBRACE, 0);\n}\n\nSwiftMtParser_MT700Parser::Sys_element_keyContext* SwiftMtParser_MT700Parser::Sys_elementContext::sys_element_key() {\n  return getRuleContext<SwiftMtParser_MT700Parser::Sys_element_keyContext>(0);\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::Sys_elementContext::COLON() {\n  return getToken(SwiftMtParser_MT700Parser::COLON, 0);\n}\n\nSwiftMtParser_MT700Parser::Sys_element_contentContext* SwiftMtParser_MT700Parser::Sys_elementContext::sys_element_content() {\n  return getRuleContext<SwiftMtParser_MT700Parser::Sys_element_contentContext>(0);\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::Sys_elementContext::RBRACE() {\n  return getToken(SwiftMtParser_MT700Parser::RBRACE, 0);\n}\n\n\nsize_t SwiftMtParser_MT700Parser::Sys_elementContext::getRuleIndex() const {\n  return SwiftMtParser_MT700Parser::RuleSys_element;\n}\n\nvoid SwiftMtParser_MT700Parser::Sys_elementContext::enterRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->enterSys_element(this);\n}\n\nvoid SwiftMtParser_MT700Parser::Sys_elementContext::exitRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->exitSys_element(this);\n}\n\nSwiftMtParser_MT700Parser::Sys_elementContext* SwiftMtParser_MT700Parser::sys_element() {\n  Sys_elementContext *_localctx = _tracker.createInstance<Sys_elementContext>(_ctx, getState());\n  enterRule(_localctx, 16, SwiftMtParser_MT700Parser::RuleSys_element);\n\n  auto onExit = finally([=] {\n    exitRule();\n  });\n  try {\n    enterOuterAlt(_localctx, 1);\n    setState(66);\n    match(SwiftMtParser_MT700Parser::LBRACE);\n    setState(67);\n    sys_element_key();\n    setState(68);\n    match(SwiftMtParser_MT700Parser::COLON);\n    setState(69);\n    sys_element_content();\n    setState(70);\n    match(SwiftMtParser_MT700Parser::RBRACE);\n   \n  }\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n\n  return _localctx;\n}\n\n\/\/----------------- Sys_element_keyContext ------------------------------------------------------------------\n\nSwiftMtParser_MT700Parser::Sys_element_keyContext::Sys_element_keyContext(ParserRuleContext *parent, size_t invokingState)\n  : ParserRuleContext(parent, invokingState) {\n}\n\nstd::vector<tree::TerminalNode *> SwiftMtParser_MT700Parser::Sys_element_keyContext::COLON() {\n  return getTokens(SwiftMtParser_MT700Parser::COLON);\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::Sys_element_keyContext::COLON(size_t i) {\n  return getToken(SwiftMtParser_MT700Parser::COLON, i);\n}\n\nstd::vector<tree::TerminalNode *> SwiftMtParser_MT700Parser::Sys_element_keyContext::RBRACE() {\n  return getTokens(SwiftMtParser_MT700Parser::RBRACE);\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::Sys_element_keyContext::RBRACE(size_t i) {\n  return getToken(SwiftMtParser_MT700Parser::RBRACE, i);\n}\n\n\nsize_t SwiftMtParser_MT700Parser::Sys_element_keyContext::getRuleIndex() const {\n  return SwiftMtParser_MT700Parser::RuleSys_element_key;\n}\n\nvoid SwiftMtParser_MT700Parser::Sys_element_keyContext::enterRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->enterSys_element_key(this);\n}\n\nvoid SwiftMtParser_MT700Parser::Sys_element_keyContext::exitRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->exitSys_element_key(this);\n}\n\nSwiftMtParser_MT700Parser::Sys_element_keyContext* SwiftMtParser_MT700Parser::sys_element_key() {\n  Sys_element_keyContext *_localctx = _tracker.createInstance<Sys_element_keyContext>(_ctx, getState());\n  enterRule(_localctx, 18, SwiftMtParser_MT700Parser::RuleSys_element_key);\n  size_t _la = 0;\n\n  auto onExit = finally([=] {\n    exitRule();\n  });\n  try {\n    enterOuterAlt(_localctx, 1);\n    setState(73); \n    _errHandler->sync(this);\n    _la = _input->LA(1);\n    do {\n      setState(72);\n      _la = _input->LA(1);\n      if (_la == 0 || _la == Token::EOF || (_la == SwiftMtParser_MT700Parser::RBRACE\n\n      || _la == SwiftMtParser_MT700Parser::COLON)) {\n      _errHandler->recoverInline(this);\n      }\n      else {\n        _errHandler->reportMatch(this);\n        consume();\n      }\n      setState(75); \n      _errHandler->sync(this);\n      _la = _input->LA(1);\n    } while ((((_la & ~ 0x3fULL) == 0) &&\n      ((1ULL << _la) & ((1ULL << SwiftMtParser_MT700Parser::TAG_BH)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_AH)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_UH)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_MT)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_TR)\n      | (1ULL << SwiftMtParser_MT700Parser::MT_END)\n      | (1ULL << SwiftMtParser_MT700Parser::LBRACE)\n      | (1ULL << SwiftMtParser_MT700Parser::START_OF_FIELD)\n      | (1ULL << SwiftMtParser_MT700Parser::ANY))) != 0));\n   \n  }\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n\n  return _localctx;\n}\n\n\/\/----------------- Sys_element_contentContext ------------------------------------------------------------------\n\nSwiftMtParser_MT700Parser::Sys_element_contentContext::Sys_element_contentContext(ParserRuleContext *parent, size_t invokingState)\n  : ParserRuleContext(parent, invokingState) {\n}\n\nstd::vector<tree::TerminalNode *> SwiftMtParser_MT700Parser::Sys_element_contentContext::RBRACE() {\n  return getTokens(SwiftMtParser_MT700Parser::RBRACE);\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::Sys_element_contentContext::RBRACE(size_t i) {\n  return getToken(SwiftMtParser_MT700Parser::RBRACE, i);\n}\n\n\nsize_t SwiftMtParser_MT700Parser::Sys_element_contentContext::getRuleIndex() const {\n  return SwiftMtParser_MT700Parser::RuleSys_element_content;\n}\n\nvoid SwiftMtParser_MT700Parser::Sys_element_contentContext::enterRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->enterSys_element_content(this);\n}\n\nvoid SwiftMtParser_MT700Parser::Sys_element_contentContext::exitRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->exitSys_element_content(this);\n}\n\nSwiftMtParser_MT700Parser::Sys_element_contentContext* SwiftMtParser_MT700Parser::sys_element_content() {\n  Sys_element_contentContext *_localctx = _tracker.createInstance<Sys_element_contentContext>(_ctx, getState());\n  enterRule(_localctx, 20, SwiftMtParser_MT700Parser::RuleSys_element_content);\n  size_t _la = 0;\n\n  auto onExit = finally([=] {\n    exitRule();\n  });\n  try {\n    enterOuterAlt(_localctx, 1);\n    setState(78); \n    _errHandler->sync(this);\n    _la = _input->LA(1);\n    do {\n      setState(77);\n      _la = _input->LA(1);\n      if (_la == 0 || _la == Token::EOF || (_la == SwiftMtParser_MT700Parser::RBRACE)) {\n      _errHandler->recoverInline(this);\n      }\n      else {\n        _errHandler->reportMatch(this);\n        consume();\n      }\n      setState(80); \n      _errHandler->sync(this);\n      _la = _input->LA(1);\n    } while ((((_la & ~ 0x3fULL) == 0) &&\n      ((1ULL << _la) & ((1ULL << SwiftMtParser_MT700Parser::TAG_BH)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_AH)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_UH)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_MT)\n      | (1ULL << SwiftMtParser_MT700Parser::TAG_TR)\n      | (1ULL << SwiftMtParser_MT700Parser::MT_END)\n      | (1ULL << SwiftMtParser_MT700Parser::LBRACE)\n      | (1ULL << SwiftMtParser_MT700Parser::COLON)\n      | (1ULL << SwiftMtParser_MT700Parser::START_OF_FIELD)\n      | (1ULL << SwiftMtParser_MT700Parser::ANY))) != 0));\n   \n  }\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n\n  return _localctx;\n}\n\n\/\/----------------- MtContext ------------------------------------------------------------------\n\nSwiftMtParser_MT700Parser::MtContext::MtContext(ParserRuleContext *parent, size_t invokingState)\n  : ParserRuleContext(parent, invokingState) {\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::MtContext::TAG_MT() {\n  return getToken(SwiftMtParser_MT700Parser::TAG_MT, 0);\n}\n\ntree::TerminalNode* SwiftMtParser_MT700Parser::MtContext::MT_END() {\n  return getToken(SwiftMtParser_MT700Parser::MT_END, 0);\n}\n\n\nsize_t SwiftMtParser_MT700Parser::MtContext::getRuleIndex() const {\n  return SwiftMtParser_MT700Parser::RuleMt;\n}\n\nvoid SwiftMtParser_MT700Parser::MtContext::enterRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->enterMt(this);\n}\n\nvoid SwiftMtParser_MT700Parser::MtContext::exitRule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast<SwiftMtParser_MT700Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener->exitMt(this);\n}\n\nSwiftMtParser_MT700Parser::MtContext* SwiftMtParser_MT700Parser::mt() {\n  MtContext *_localctx = _tracker.createInstance<MtContext>(_ctx, getState());\n  enterRule(_localctx, 22, SwiftMtParser_MT700Parser::RuleMt);\n\n  auto onExit = finally([=] {\n    exitRule();\n  });\n  try {\n    enterOuterAlt(_localctx, 1);\n    setState(82);\n    match(SwiftMtParser_MT700Parser::TAG_MT);\n    setState(83);\n    match(SwiftMtParser_MT700Parser::MT_END);\n   _ctx->stop = _input->LT(-1);\n     _message_builder.mutable_msg_text()->MergeFrom(_localctx->elem); \n  }\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n\n  return _localctx;\n}\n\n\/\/ Static vars and initialization.\nstd::vector<dfa::DFA> SwiftMtParser_MT700Parser::_decisionToDFA;\natn::PredictionContextCache SwiftMtParser_MT700Parser::_sharedContextCache;\n\n\/\/ We own the ATN which in turn owns the ATN states.\natn::ATN SwiftMtParser_MT700Parser::_atn;\nstd::vector<uint16_t> SwiftMtParser_MT700Parser::_serializedATN;\n\nstd::vector<std::string> SwiftMtParser_MT700Parser::_ruleNames = {\n  \"message\", \"bh\", \"bh_content\", \"ah\", \"ah_content\", \"uh\", \"tr\", \"sys_block\", \n  \"sys_element\", \"sys_element_key\", \"sys_element_content\", \"mt\"\n};\n\nstd::vector<std::string> SwiftMtParser_MT700Parser::_literalNames = {\n  \"\", \"'{1:'\", \"'{2:'\", \"'{3:'\", \"'{4:'\", \"'{5:'\", \"'-}'\", \"'{'\", \"'}'\", \n  \"':'\"\n};\n\nstd::vector<std::string> SwiftMtParser_MT700Parser::_symbolicNames = {\n  \"\", \"TAG_BH\", \"TAG_AH\", \"TAG_UH\", \"TAG_MT\", \"TAG_TR\", \"MT_END\", \"LBRACE\", \n  \"RBRACE\", \"COLON\", \"START_OF_FIELD\", \"ANY\"\n};\n\ndfa::Vocabulary SwiftMtParser_MT700Parser::_vocabulary(_literalNames, _symbolicNames);\n\nstd::vector<std::string> SwiftMtParser_MT700Parser::_tokenNames;\n\nSwiftMtParser_MT700Parser::Initializer::Initializer() {\n\tfor (size_t i = 0; i < _symbolicNames.size(); ++i) {\n\t\tstd::string name = _vocabulary.getLiteralName(i);\n\t\tif (name.empty()) {\n\t\t\tname = _vocabulary.getSymbolicName(i);\n\t\t}\n\n\t\tif (name.empty()) {\n\t\t\t_tokenNames.push_back(\"<INVALID>\");\n\t\t} else {\n      _tokenNames.push_back(name);\n    }\n\t}\n\n  _serializedATN = {\n    0x3, 0x608b, 0xa72a, 0x8133, 0xb9ed, 0x417c, 0x3be7, 0x7786, 0x5964, \n    0x3, 0xd, 0x58, 0x4, 0x2, 0x9, 0x2, 0x4, 0x3, 0x9, 0x3, 0x4, 0x4, 0x9, \n    0x4, 0x4, 0x5, 0x9, 0x5, 0x4, 0x6, 0x9, 0x6, 0x4, 0x7, 0x9, 0x7, 0x4, \n    0x8, 0x9, 0x8, 0x4, 0x9, 0x9, 0x9, 0x4, 0xa, 0x9, 0xa, 0x4, 0xb, 0x9, \n    0xb, 0x4, 0xc, 0x9, 0xc, 0x4, 0xd, 0x9, 0xd, 0x3, 0x2, 0x3, 0x2, 0x3, \n    0x2, 0x5, 0x2, 0x1e, 0xa, 0x2, 0x3, 0x2, 0x3, 0x2, 0x5, 0x2, 0x22, 0xa, \n    0x2, 0x3, 0x2, 0x3, 0x2, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, \n    0x4, 0x6, 0x4, 0x2b, 0xa, 0x4, 0xd, 0x4, 0xe, 0x4, 0x2c, 0x3, 0x5, 0x3, \n    0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x6, 0x6, 0x6, 0x34, 0xa, 0x6, 0xd, 0x6, \n    0xe, 0x6, 0x35, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x8, 0x3, \n    0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x9, 0x6, 0x9, 0x41, 0xa, 0x9, 0xd, 0x9, \n    0xe, 0x9, 0x42, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, \n    0xa, 0x3, 0xb, 0x6, 0xb, 0x4c, 0xa, 0xb, 0xd, 0xb, 0xe, 0xb, 0x4d, 0x3, \n    0xc, 0x6, 0xc, 0x51, 0xa, 0xc, 0xd, 0xc, 0xe, 0xc, 0x52, 0x3, 0xd, 0x3, \n    0xd, 0x3, 0xd, 0x3, 0xd, 0x2, 0x2, 0xe, 0x2, 0x4, 0x6, 0x8, 0xa, 0xc, \n    0xe, 0x10, 0x12, 0x14, 0x16, 0x18, 0x2, 0x4, 0x3, 0x2, 0xa, 0xa, 0x3, \n    0x2, 0xa, 0xb, 0x2, 0x52, 0x2, 0x1a, 0x3, 0x2, 0x2, 0x2, 0x4, 0x25, \n    0x3, 0x2, 0x2, 0x2, 0x6, 0x2a, 0x3, 0x2, 0x2, 0x2, 0x8, 0x2e, 0x3, 0x2, \n    0x2, 0x2, 0xa, 0x33, 0x3, 0x2, 0x2, 0x2, 0xc, 0x37, 0x3, 0x2, 0x2, 0x2, \n    0xe, 0x3b, 0x3, 0x2, 0x2, 0x2, 0x10, 0x40, 0x3, 0x2, 0x2, 0x2, 0x12, \n    0x44, 0x3, 0x2, 0x2, 0x2, 0x14, 0x4b, 0x3, 0x2, 0x2, 0x2, 0x16, 0x50, \n    0x3, 0x2, 0x2, 0x2, 0x18, 0x54, 0x3, 0x2, 0x2, 0x2, 0x1a, 0x1b, 0x5, \n    0x4, 0x3, 0x2, 0x1b, 0x1d, 0x5, 0x8, 0x5, 0x2, 0x1c, 0x1e, 0x5, 0xc, \n    0x7, 0x2, 0x1d, 0x1c, 0x3, 0x2, 0x2, 0x2, 0x1d, 0x1e, 0x3, 0x2, 0x2, \n    0x2, 0x1e, 0x1f, 0x3, 0x2, 0x2, 0x2, 0x1f, 0x21, 0x5, 0x18, 0xd, 0x2, \n    0x20, 0x22, 0x5, 0xe, 0x8, 0x2, 0x21, 0x20, 0x3, 0x2, 0x2, 0x2, 0x21, \n    0x22, 0x3, 0x2, 0x2, 0x2, 0x22, 0x23, 0x3, 0x2, 0x2, 0x2, 0x23, 0x24, \n    0x7, 0x2, 0x2, 0x3, 0x24, 0x3, 0x3, 0x2, 0x2, 0x2, 0x25, 0x26, 0x7, \n    0x3, 0x2, 0x2, 0x26, 0x27, 0x5, 0x6, 0x4, 0x2, 0x27, 0x28, 0x7, 0xa, \n    0x2, 0x2, 0x28, 0x5, 0x3, 0x2, 0x2, 0x2, 0x29, 0x2b, 0xa, 0x2, 0x2, \n    0x2, 0x2a, 0x29, 0x3, 0x2, 0x2, 0x2, 0x2b, 0x2c, 0x3, 0x2, 0x2, 0x2, \n    0x2c, 0x2a, 0x3, 0x2, 0x2, 0x2, 0x2c, 0x2d, 0x3, 0x2, 0x2, 0x2, 0x2d, \n    0x7, 0x3, 0x2, 0x2, 0x2, 0x2e, 0x2f, 0x7, 0x4, 0x2, 0x2, 0x2f, 0x30, \n    0x5, 0xa, 0x6, 0x2, 0x30, 0x31, 0x7, 0xa, 0x2, 0x2, 0x31, 0x9, 0x3, \n    0x2, 0x2, 0x2, 0x32, 0x34, 0xa, 0x2, 0x2, 0x2, 0x33, 0x32, 0x3, 0x2, \n    0x2, 0x2, 0x34, 0x35, 0x3, 0x2, 0x2, 0x2, 0x35, 0x33, 0x3, 0x2, 0x2, \n    0x2, 0x35, 0x36, 0x3, 0x2, 0x2, 0x2, 0x36, 0xb, 0x3, 0x2, 0x2, 0x2, \n    0x37, 0x38, 0x7, 0x5, 0x2, 0x2, 0x38, 0x39, 0x5, 0x10, 0x9, 0x2, 0x39, \n    0x3a, 0x7, 0xa, 0x2, 0x2, 0x3a, 0xd, 0x3, 0x2, 0x2, 0x2, 0x3b, 0x3c, \n    0x7, 0x7, 0x2, 0x2, 0x3c, 0x3d, 0x5, 0x10, 0x9, 0x2, 0x3d, 0x3e, 0x7, \n    0xa, 0x2, 0x2, 0x3e, 0xf, 0x3, 0x2, 0x2, 0x2, 0x3f, 0x41, 0x5, 0x12, \n    0xa, 0x2, 0x40, 0x3f, 0x3, 0x2, 0x2, 0x2, 0x41, 0x42, 0x3, 0x2, 0x2, \n    0x2, 0x42, 0x40, 0x3, 0x2, 0x2, 0x2, 0x42, 0x43, 0x3, 0x2, 0x2, 0x2, \n    0x43, 0x11, 0x3, 0x2, 0x2, 0x2, 0x44, 0x45, 0x7, 0x9, 0x2, 0x2, 0x45, \n    0x46, 0x5, 0x14, 0xb, 0x2, 0x46, 0x47, 0x7, 0xb, 0x2, 0x2, 0x47, 0x48, \n    0x5, 0x16, 0xc, 0x2, 0x48, 0x49, 0x7, 0xa, 0x2, 0x2, 0x49, 0x13, 0x3, \n    0x2, 0x2, 0x2, 0x4a, 0x4c, 0xa, 0x3, 0x2, 0x2, 0x4b, 0x4a, 0x3, 0x2, \n    0x2, 0x2, 0x4c, 0x4d, 0x3, 0x2, 0x2, 0x2, 0x4d, 0x4b, 0x3, 0x2, 0x2, \n    0x2, 0x4d, 0x4e, 0x3, 0x2, 0x2, 0x2, 0x4e, 0x15, 0x3, 0x2, 0x2, 0x2, \n    0x4f, 0x51, 0xa, 0x2, 0x2, 0x2, 0x50, 0x4f, 0x3, 0x2, 0x2, 0x2, 0x51, \n    0x52, 0x3, 0x2, 0x2, 0x2, 0x52, 0x50, 0x3, 0x2, 0x2, 0x2, 0x52, 0x53, \n    0x3, 0x2, 0x2, 0x2, 0x53, 0x17, 0x3, 0x2, 0x2, 0x2, 0x54, 0x55, 0x7, \n    0x6, 0x2, 0x2, 0x55, 0x56, 0x7, 0x8, 0x2, 0x2, 0x56, 0x19, 0x3, 0x2, \n    0x2, 0x2, 0x9, 0x1d, 0x21, 0x2c, 0x35, 0x42, 0x4d, 0x52, \n  };\n\n  atn::ATNDeserializer deserializer;\n  _atn = deserializer.deserialize(_serializedATN);\n\n  size_t count = _atn.getNumberOfDecisions();\n  _decisionToDFA.reserve(count);\n  for (size_t i = 0; i < count; i++) { \n    _decisionToDFA.emplace_back(_atn.getDecisionState(i), i);\n  }\n}\n\nSwiftMtParser_MT700Parser::Initializer SwiftMtParser_MT700Parser::_init;\n","avg_line_length":35.780876494,"max_line_length":156,"alphanum_fraction":0.7042923951,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1537,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":4.0,"content":"#include <iostream>\n#include <netinet\/in.h>\n\n#include \"net_asio\/message.h\"\n\nconst int endian = 1;\n\n#define is_bigendian() ( (*(char*) &endian) == 0 )\n\n#define is_littlendbian() ( (*(char*) &endian) == 1 )\n\nint main()\n{\n\tif (is_littlendbian())\n\t{\n\t\tstd::cout << \"little endian\" << std::endl;\n\t}\n\telse\n\t{\n\t\tstd::cout << \"little endian\" << std::endl;\n\t}\n\n\t\/\/ \u672c\u5730\u5b57\u8282\u5e8f\n\tuint32 bodysize = 0x12345678;\n\tMessageHeader mh;\n\tmh.size = bodysize;\n\n\t{\n\t\tuint8* bin =(uint8*)&mh;\n\n\t\tstd::cout << \"[0] - \" << std::hex << (int)bin[0] << std::endl;\n\t\tstd::cout << \"[1] - \" << std::hex << (int)bin[1] << std::endl;\n\t\tstd::cout << \"[2] - \" << std::hex << (int)bin[2] << std::endl;\n\t\tstd::cout << \"[3] - \" << std::hex << (int)bin[3] << std::endl;\n\t\tstd::cout << std::hex << mh.size << std::endl;\n\t}\n\n\n\t{\n\t\tuint8* bin =(uint8*)&bodysize;\n\n\t\tstd::cout << \"[0] - \" << std::hex << (int)bin[0] << std::endl;\n\t\tstd::cout << \"[1] - \" << std::hex << (int)bin[1] << std::endl;\n\t\tstd::cout << \"[2] - \" << std::hex << (int)bin[2] << std::endl;\n\t\tstd::cout << \"[3] - \" << std::hex << (int)bin[3] << std::endl;\n\t\tstd::cout << std::hex << mh.size << std::endl;\n\t}\n\n\t\/\/ \u7f51\u7edc\u5b57\u8282\u5e8f(Big Endian)\n\t\/\/uint32 netbodysize = htonl(bodysize);\n\t{\n\t\tMessageHeader mh;\n\t\tmh.size = htonl(bodysize);\n\t\tuint8* bin =(uint8*)&mh;\n\n\t\tstd::cout << \"[0] - \" << std::hex << (int)bin[0] << std::endl;\n\t\tstd::cout << \"[1] - \" << std::hex << (int)bin[1] << std::endl;\n\t\tstd::cout << \"[2] - \" << std::hex << (int)bin[2] << std::endl;\n\t\tstd::cout << \"[3] - \" << std::hex << (int)bin[3] << std::endl;\n\t}\n\n}","avg_line_length":24.7903225806,"max_line_length":64,"alphanum_fraction":0.5113858165,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2958,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":17.0,"content":"#include \"gridsearcher.h\"\r\n\r\n#include <algorithm>\r\n#include <unordered_set>\r\n\r\n#include \"hexgrid\/hexgrid.h\"\r\n#include \"utils\/channel.h\"\r\n#include \"algorithms\/searchalgorithms.h\"\r\n\r\n\/\/define a hash function for QPoint\r\nnamespace std {\r\n\ttemplate <> struct hash < QPoint >\r\n\t{\r\n\t\tsize_t operator()(const QPoint &point) const\r\n\t\t{\r\n\t\t\tint hashSize = sizeof(size_t);\r\n\r\n\t\t\tsize_t a = std::hash<int>()(point.x());\r\n\t\t\tsize_t b = std::hash<int>()(point.y());\r\n\r\n\t\t\tsize_t c = (b << (hashSize \/ 2)) | (b >> (hashSize \/ 2));\r\n\r\n\t\t\treturn a ^ c;\r\n\t\t}\r\n\t};\r\n}\r\n\r\n\r\nGridSearcher::GridSearcher(HexGrid &grid) :\r\n\tgrid(grid)\r\n{\r\n}\r\n\r\nvoid GridSearcher::search(std::shared_ptr<Channel<GridSearchEvent>> outputChannel)\r\n{\r\n\r\n\tstd::vector<QPoint> startStates;\r\n\tstd::unordered_set<QPoint> goalStates;\r\n\r\n\t\/\/find all end states and start states in the grid\r\n\tfor (const auto& cell : grid.getCells())\r\n\t{\r\n\t\tconst GridEntry& entry = grid.getEntry(cell);\r\n\r\n\t\tif (entry.type == GridEntry::Start)\r\n\t\t{\r\n\t\t\tstartStates.push_back(cell);\r\n\t\t}\r\n\t\telse if (entry.type == GridEntry::End)\r\n\t\t{\r\n\t\t\tgoalStates.insert(cell);\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/define a function that returns true if the given state is a goal state\r\n\tauto goalFunction = [&goalStates](const QPoint &currentState)\r\n\t{\r\n\t\treturn bool(goalStates.count(currentState));\r\n\t};\r\n\r\n\t\/\/define a function that \"processes\" the given state when it's reached\r\n\tauto stateFunction = [&outputChannel](const QPoint &currentState, const QPoint &parentState)\r\n\t{\r\n        Q_UNUSED(parentState)\r\n\t\toutputChannel->push(GridSearchEvent(GridSearchEvent::EXPAND, currentState));\r\n\t};\r\n\r\n\t\/\/define a function that returns the neighbors and associated costs for the given state\r\n\tauto neighborFunction = [this](const QPoint &currentState)\r\n\t{\r\n\t\tQVector<QPoint> neighbors = grid.getNeighbors(currentState);\r\n\t\tstd::vector<std::pair<QPoint, float>> result;\r\n\t\tfor (const QPoint &n : neighbors)\r\n\t\t{\r\n\t\t\tif (grid.getEntry(n).type != GridEntry::Wall)\r\n\t\t\t{\r\n\t\t\t\tresult.emplace_back(n, 1.0f);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t};\r\n\r\n\t\/\/define a function that returns the heuristic for the given state\r\n\tauto heuristicFunction = [&](const QPoint &currentState)\r\n\t{\r\n\t\tfloat minDistance = grid.manhattanDistance(currentState, *(goalStates.begin()));\r\n\r\n\t\tfor (const QPoint &p : goalStates)\r\n\t\t{\r\n\t\t\tfloat d = grid.manhattanDistance(currentState, p);\r\n\t\t\tminDistance = qMin(minDistance, d);\r\n\t\t}\r\n\r\n\t\treturn minDistance;\r\n\t};\r\n\r\n\t\/\/perform the search\r\n\tstd::vector<QPoint> result = SearchAlgorithms::aStar<QPoint>(startStates, goalFunction, stateFunction, neighborFunction, heuristicFunction);\r\n\r\n\t\/\/put out a search event for each item in the final route, in reversed order, to simulate backtracing the result\r\n\tstd::reverse(result.begin(), result.end());\r\n\tfor (const QPoint& item : result)\r\n\t{\r\n\t\toutputChannel->push(GridSearchEvent(GridSearchEvent::BACKTRACE, item));\r\n\t}\r\n\r\n\t\/\/close the output channel to wrap things up\r\n\toutputChannel->closeBack();\r\n}\r\n","avg_line_length":26.6486486486,"max_line_length":142,"alphanum_fraction":0.6818796484,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4770,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/*\n * Copyright 2019 Xilinx, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*\/\n\/\/================================== End Lic =================================================\n#define TEST_2D_FFT_\n#ifdef TEST_2D_FFT_\n#include <math.h>\n#include <string>\n#include <assert.h>\n#include <stdio.h>\n#include \"top_2d_fft_test.hpp\"\n#include \"mVerificationUtlityFunctions.hpp\"\n#include \"vitis_fft\/hls_ssr_fft_2d_modeling_utilities.hpp\"\n\nint main(int argc, char** argv) {\n    \/\/ 2d input matrix\n    T_elemType l_inMat[k_fftKernelSize][k_fftKernelSize];\n    T_outType l_outMat[k_fftKernelSize][k_fftKernelSize];\n    T_outType l_data2d_golden[k_fftKernelSize][k_fftKernelSize];\n\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ File Paths for stimulus files\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    std::string root_path = \"\";\n    std::string inputStimulusDataVerifFileName;\n    std::stringstream strStream;\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Log Stream for writing output messages\/\/\/\/\/\/\/\/\n    std::ofstream logStreamBB;\n    std::string blockBoxFilename = root_path + \"2d_fft_verification_log.log\";\n    logStreamBB.open(blockBoxFilename.c_str(), std::fstream::out);\n\n    strStream << root_path << \"fft2DStimulusIn_L\" << k_fftKernelSize * k_fftKernelSize << \".verif\";\n    inputStimulusDataVerifFileName = strStream.str();\n    std::cout << \"The Stimulus file and constructed path: \" << inputStimulusDataVerifFileName << \"\\n\";\n\n    std::stringstream strStream1;\n    std::string goldenOutputDataVerifFileName;\n    strStream1 << root_path << \"fft2DGoldenOut_L\" << k_fftKernelSize * k_fftKernelSize << \".verif\";\n    goldenOutputDataVerifFileName = strStream1.str();\n\n    \/\/ Data Arrays to read stimulus data from file\n    T_compleFloat* l_fileData = new T_compleFloat[k_fftKernelSize * k_fftKernelSize];\n\n    \/\/ readComplexArrayFromFile<T_innerFloat>(logStreamBB, \"din_file\", inputStimulusDataVerifFileName, &l_inMat[0][0],\n    \/\/ k_fftKernelSize*k_fftKernelSize);\n    readComplexArrayFromFile<T_innerFloat>(logStreamBB, \"din_file\", inputStimulusDataVerifFileName, l_fileData,\n                                           k_fftKernelSize * k_fftKernelSize);\n\n    \/\/ init input matrix with stimuls, this loop will also take care of casting if types doesnt match\n    int k = 0;\n    for (int r = 0; r < k_fftKernelSize; ++r) {\n        for (int c = 0; c < k_fftKernelSize; ++c) {\n            l_inMat[r][c] = l_fileData[k];\n            k++;\n        }\n    }\n    delete l_fileData;\n    \/\/ Wide Stream for reading and streaming a 2-d matrix\n    MemWideIFStreamTypeIn l_matToStream(\"matrixToStreaming\");\n    MemWideIFStreamTypeOut fftOutputStream(\"fftOutputStream\");\n    \/\/ Pass same data stream multiple times to measure the II correctly\n    for (int runs = 0; runs < 5; ++runs) {\n        stream2DMatrix<k_fftKernelSize, k_fftKernelSize, k_memWidth, T_elemType, MemWideIFTypeIn>(l_inMat,\n                                                                                                  l_matToStream);\n        top_fft2d(l_matToStream, fftOutputStream);\n\n        \/\/ printMatStream<k_fftKernelSize, k_fftKernelSize, k_memWidth>(fftOutputStream, \"2D FFT Output Natural\n        \/\/ Order...\");\n        streamToMatrix<k_fftKernelSize, k_fftKernelSize, k_memWidth, T_elemType, MemWideIFTypeOut>(fftOutputStream,\n                                                                                                   l_outMat);\n    } \/\/ runs loop\n    l_fileData = new T_compleFloat[k_fftKernelSize * k_fftKernelSize];\n    k = 0;\n    for (int r = 0; r < k_fftKernelSize; ++r) {\n        for (int c = 0; c < k_fftKernelSize; ++c) {\n            l_fileData[k] = l_outMat[r][c];\n            k++;\n        }\n    }\n    std::ofstream logStream;\n    VerificationResults verif_res_cpp_float_vs_octave;\n    verif_res_cpp_float_vs_octave = verifyArrayOutput_with_snr<T_innerFloat>(\n        logStream, \"Golden Output\", goldenOutputDataVerifFileName, l_fileData, 10, 5,\n        k_fftKernelSize * k_fftKernelSize); \/\/ error given in %\n\n    std::cout << \"================================================================\" << std::endl;\n    std::cout << verif_res_cpp_float_vs_octave << std::endl;\n    std::cout << \"================================================================\" << std::endl;\n    return verif_res_cpp_float_vs_octave.m_statusFlag;\n}\n#endif\n","avg_line_length":46.7647058824,"max_line_length":118,"alphanum_fraction":0.6352201258,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":549,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":39.0,"content":"#include \"utilityfunc.h\"\n\nusing namespace std;\n\nint argmax(vector<double> & x) {\n  int maxind=0;\n  for(int i=1;i<(int)x.size();i++) \n    if(x[i]>x[maxind]) maxind=i;\n  return(maxind);\n}\n\n\nint which_max(int *x,int n) {\n  int maxidx = 0;\n  int maxval = x[maxidx];\n  for(int i=0;i<n;i++) {\n    if(x[i]>maxval) {\n      maxidx = i;\n      maxval = x[i];\n    }\n  }\n  return maxidx;\n}\n\n\n\nbool fileexists(string fname){\n  ifstream ifile(fname.c_str());\n  return ifile.good();\n}\n\nvoid die(const string & err) {\n  cerr << \"ERROR: \"<< err << endl;\n  exit(1);\n}\n","avg_line_length":15.25,"max_line_length":35,"alphanum_fraction":0.5737704918,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4056,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":18396.0,"content":"\/\/\n\/\/ Copyright (c) 2013-2021 Winlin\n\/\/\n\/\/ SPDX-License-Identifier: MIT\n\/\/\n\n#include <srs_kernel_error.hpp>\n\n#include <srs_kernel_log.hpp>\n\n#include <errno.h>\n#include <sstream>\n#include <stdarg.h>\n#include <unistd.h>\nusing namespace std;\n\nbool srs_is_system_control_error(srs_error_t err)\n{\n    int error_code = srs_error_code(err);\n    return error_code == ERROR_CONTROL_RTMP_CLOSE\n        || error_code == ERROR_CONTROL_REPUBLISH\n        || error_code == ERROR_CONTROL_REDIRECT;\n}\n\nbool srs_is_client_gracefully_close(srs_error_t err)\n{\n    int error_code = srs_error_code(err);\n    return error_code == ERROR_SOCKET_READ\n        || error_code == ERROR_SOCKET_READ_FULLY\n        || error_code == ERROR_SOCKET_WRITE;\n}\n\nbool srs_is_server_gracefully_close(srs_error_t err)\n{\n    int code = srs_error_code(err);\n    return code == ERROR_HTTP_STREAM_EOF;\n}\n\nSrsCplxError::SrsCplxError()\n{\n    code = ERROR_SUCCESS;\n    wrapped = NULL;\n    rerrno = line = 0;\n}\n\nSrsCplxError::~SrsCplxError()\n{\n    srs_freep(wrapped);\n}\n\nstd::string SrsCplxError::description() {\n    if (desc.empty()) {\n        stringstream ss;\n        ss << \"code=\" << code;\n\n        SrsCplxError* next = this;\n        while (next) {\n            ss << \" : \" << next->msg;\n            next = next->wrapped;\n        }\n        ss << endl;\n\n        next = this;\n        while (next) {\n            ss << \"thread [\" << getpid() << \"][\" << next->cid.c_str() << \"]: \"\n            << next->func << \"() [\" << next->file << \":\" << next->line << \"]\"\n            << \"[errno=\" << next->rerrno << \"]\";\n\n            next = next->wrapped;\n\n            if (next) {\n                ss << endl;\n            }\n        }\n\n        desc = ss.str();\n    }\n\n    return desc;\n}\n\nstd::string SrsCplxError::summary() {\n    if (_summary.empty()) {\n        stringstream ss;\n\n        SrsCplxError* next = this;\n        while (next) {\n            ss << \" : \" << next->msg;\n            next = next->wrapped;\n        }\n\n        _summary = ss.str();\n    }\n\n    return _summary;\n}\n\nSrsCplxError* SrsCplxError::create(const char* func, const char* file, int line, int code, const char* fmt, ...) {\n    int rerrno = (int)errno;\n\n    va_list ap;\n    va_start(ap, fmt);\n    static char buffer[4096];\n    vsnprintf(buffer, sizeof(buffer), fmt, ap);\n    va_end(ap);\n    \n    SrsCplxError* err = new SrsCplxError();\n    \n    err->func = func;\n    err->file = file;\n    err->line = line;\n    err->code = code;\n    err->rerrno = rerrno;\n    err->msg = buffer;\n    err->wrapped = NULL;\n    if (_srs_context) {\n        err->cid = _srs_context->get_id();\n    }\n    \n    return err;\n}\n\nSrsCplxError* SrsCplxError::wrap(const char* func, const char* file, int line, SrsCplxError* v, const char* fmt, ...) {\n    int rerrno = (int)errno;\n    \n    va_list ap;\n    va_start(ap, fmt);\n    static char buffer[4096];\n    vsnprintf(buffer, sizeof(buffer), fmt, ap);\n    va_end(ap);\n    \n    SrsCplxError* err = new SrsCplxError();\n    \n    err->func = func;\n    err->file = file;\n    err->line = line;\n    if (v) {\n        err->code = v->code;\n    }\n    err->rerrno = rerrno;\n    err->msg = buffer;\n    err->wrapped = v;\n    if (_srs_context) {\n        err->cid = _srs_context->get_id();\n    }\n    \n    return err;\n}\n\nSrsCplxError* SrsCplxError::success() {\n    return NULL;\n}\n\nSrsCplxError* SrsCplxError::copy(SrsCplxError* from)\n{\n    if (from == srs_success) {\n        return srs_success;\n    }\n    \n    SrsCplxError* err = new SrsCplxError();\n    \n    err->code = from->code;\n    err->wrapped = srs_error_copy(from->wrapped);\n    err->msg = from->msg;\n    err->func = from->func;\n    err->file = from->file;\n    err->line = from->line;\n    err->cid = from->cid;\n    err->rerrno = from->rerrno;\n    err->desc = from->desc;\n    \n    return err;\n}\n\nstring SrsCplxError::description(SrsCplxError* err)\n{\n    return err? err->description() : \"Success\";\n}\n\nstring SrsCplxError::summary(SrsCplxError* err)\n{\n    return err? err->summary() : \"Success\";\n}\n\nint SrsCplxError::error_code(SrsCplxError* err)\n{\n    return err? err->code : ERROR_SUCCESS;\n}\n\n","avg_line_length":21.3473684211,"max_line_length":119,"alphanum_fraction":0.5749506903,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":723,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":" class Solution {\npublic:\n    bool XXX(TreeNode* root) {\n        if (root == NULL) return true;\n        stack<TreeNode*> st;\n        st.push(root->left);\n        st.push(root->right);\n        while (!st.empty()) {\n            TreeNode* leftNode = st.top(); st.pop();\n            TreeNode* rightNode = st.top(); st.pop();\n            if (!leftNode && !rightNode) {\n                continue;\n            }\n            if ((!leftNode || !rightNode || (leftNode->val != rightNode->val))) {\n                return false;\n            }\n            st.push(leftNode->left);\n            st.push(rightNode->right);\n            st.push(leftNode->right);\n            st.push(rightNode->left);\n        }\n        return true;\n    }\n};\n\n","avg_line_length":27.8076923077,"max_line_length":81,"alphanum_fraction":0.4605809129,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":369,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"Audio.h\"\n#include \"SDL_mixer.h\"\n\nvoid CAudio::PlaySound(std::weak_ptr<CSound> pSound, int nChannel)\n{\n\tif (pSound.expired()) return;\n\tMix_PlayChannel(nChannel, pSound.lock()->GetChunk(), 0);\n}\n\nvoid CAudio::AllocateChannels(int nCount)\n{\n\tMix_AllocateChannels(nCount);\n}\n\nvoid CAudio::SetVolume(int nChannel, int nVolume)\n{\n\tMix_Volume(nChannel, nVolume);\n}\n\n","avg_line_length":18.45,"max_line_length":66,"alphanum_fraction":0.7371273713,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":730,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0","Apache-2.0"],"max_stars_count":null,"content":"#include <mbgl\/style\/conversion\/geojson.hpp>\n#include <mbgl\/style\/conversion\/json.hpp>\n#include <mbgl\/util\/rapidjson.hpp>\n\n#include <mapbox\/geojson.hpp>\n#include <mapbox\/geojson\/rapidjson.hpp>\n\nnamespace mbgl {\nnamespace style {\nnamespace conversion {\n\noptional<GeoJSON> Converter<GeoJSON>::operator()(const std::string& value, Error& error) const {\n    return convertJSON<GeoJSON>(value, error);\n}\n\ntemplate <>\noptional<GeoJSON> Converter<GeoJSON>::operator()(const JSValue& value, Error& error) const {\n    try {\n        return mapbox::geojson::convert(value);\n    } catch (const std::exception& ex) {\n        error = { ex.what() };\n        return {};\n    }\n}\n\n} \/\/ namespace conversion\n} \/\/ namespace style\n} \/\/ namespace mbgl\n","avg_line_length":25.1724137931,"max_line_length":96,"alphanum_fraction":0.6904109589,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2393,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":4054.0,"content":"\/\/ Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include <vespa\/vespalib\/testkit\/test_kit.h>\n#include <vespa\/eval\/eval\/tensor_function.h>\n#include <vespa\/eval\/instruction\/dense_tensor_create_function.h>\n#include <vespa\/eval\/eval\/test\/gen_spec.h>\n#include <vespa\/eval\/eval\/test\/eval_fixture.h>\n\n#include <vespa\/vespalib\/util\/stringfmt.h>\n#include <vespa\/vespalib\/util\/stash.h>\n\nusing namespace vespalib;\nusing namespace vespalib::eval;\nusing namespace vespalib::eval::test;\nusing namespace vespalib::eval::tensor_function;\n\nconst ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get();\n\nEvalFixture::ParamRepo make_params() {\n    return EvalFixture::ParamRepo()\n        .add(\"a\", GenSpec(1.0))\n        .add(\"b\", GenSpec(2.0))\n        .add(\"c\", GenSpec(3.0));\n}\nEvalFixture::ParamRepo param_repo = make_params();\n\nvoid verify(const vespalib::string &expr, size_t expect_optimized_cnt, size_t expect_not_optimized_cnt) {\n    EvalFixture fixture(prod_factory, expr, param_repo, true);\n    EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo));\n    auto info = fixture.find_all<DenseTensorCreateFunction>();\n    EXPECT_EQUAL(info.size(), expect_optimized_cnt);\n    for (size_t i = 0; i < info.size(); ++i) {\n        EXPECT_TRUE(info[i]->result_is_mutable());\n    }\n    EXPECT_EQUAL(fixture.find_all<Create>().size(), expect_not_optimized_cnt);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nTEST(\"require that tensor create can be optimized\") {\n    TEST_DO(verify(\"tensor(x[3]):{{x:0}:1,{x:1}:2,{x:2}:3}\", 0, 0)); \/\/ NB: const value\n    TEST_DO(verify(\"tensor(x[3]):{{x:0}:a,{x:1}:b,{x:2}:c}\", 1, 0));\n    TEST_DO(verify(\"tensor<float>(x[3]):{{x:0}:a,{x:1}:b,{x:2}:c}\", 1, 0));\n    TEST_DO(verify(\"tensor(x[3]):{{x:0}:a+b,{x:1}:b-c,{x:2}:c*a}\", 1, 0));\n}\n\nTEST(\"require that tensor create can be optimized with missing cells (padded with 0.0)\") {\n    TEST_DO(verify(\"tensor(x[3],y[5]):{{x:0,y:1}:a,{x:1,y:3}:b,{x:2,y:4}:c}\", 1, 0));\n}\n\nTEST(\"require that tensor create in not optimized for sparse tensor\") {\n    TEST_DO(verify(\"tensor(x{}):{{x:0}:a,{x:1}:b,{x:2}:c}\", 0, 1));\n}\n\nTEST(\"require that tensor create in not optimized for mixed tensor\") {\n    TEST_DO(verify(\"tensor(x{},y[3]):{{x:a,y:0}:a,{x:a,y:1}:b,{x:a,y:2}:c}\", 0, 1));\n}\n\nTEST_MAIN() { TEST_RUN_ALL(); }\n","avg_line_length":39.8833333333,"max_line_length":112,"alphanum_fraction":0.651901379,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3921,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":41.0,"content":"#include \"FanSysfs.hpp\"\n\nfc::FanSysfs::FanSysfs(string label_, const path &adapter_path_, SysfsID id_)\n    : Fan(move(label_)), pwm_path(get_pwm_path(adapter_path_, id_)), rpm_path(get_rpm_path(adapter_path_, id_)),\n      enable_path(get_enable_path(adapter_path_, id_)) {\n  if (is_faulty(adapter_path_, id_)) {\n    LOG(llvl::warning) << *this << \": is faulty, ignoring\";\n    ignore = true;\n    return;\n  }\n\n  \/\/ Enable the fan sensor\n  const auto sensor_ep = get_sensor_enable_path(adapter_path_, id_);\n  if (sensor_ep)\n    Util::write(*sensor_ep, 1);\n}\n\nfc::FanSysfs::~FanSysfs() {\n  if (enabled)\n    fc::FanSysfs::disable_control();\n}\n\nbool fc::FanSysfs::enable_control() {\n  const bool success = !(exists(enable_path)) || Util::write(enable_path, manual_flag);\n  if (success)\n    enabled = true;\n\n  return success;\n}\n\nbool fc::FanSysfs::disable_control() {\n  const bool success = !(exists(enable_path)) || Util::write(enable_path, driver_flag);\n  if (success)\n    enabled = false;\n\n  return true;\n}\n\nbool fc::FanSysfs::test(ObservableNumber<int> &status) {\n  test_driver_enable_flag();\n  return fc::Fan::test(status);\n}\n\nvoid fc::FanSysfs::from(const fc_pb::Fan &f, const SensorMap &sensor_map) {\n  fc::Fan::from(f, sensor_map);\n  pwm_path = f.pwm_path();\n  rpm_path = f.rpm_path();\n  enable_path = f.enable_path();\n  driver_flag = f.driver_flag();\n}\n\nvoid fc::FanSysfs::to(fc_pb::Fan &f) const {\n  fc::Fan::to(f);\n  f.set_type(type());\n  f.set_pwm_path(pwm_path);\n  f.set_rpm_path(rpm_path);\n  f.set_enable_path(enable_path);\n  f.set_driver_flag(driver_flag);\n}\n\nbool fc::FanSysfs::valid() const {\n  const bool pe = fs::exists(pwm_path), re = fs::exists(rpm_path);\n  if (pe && re)\n    return true;\n\n  LOG(llvl::warning) << *this << \": invalid, \" << Util::join({{!pe, \"pwm_path\"}, {!re, \"rpm_path\"}})\n                     << \" not configured or doesn't exist\";\n  return pe && re;\n}\n\nstring fc::FanSysfs::hw_id() const { return pwm_path.c_str(); }\n\nDevType fc::FanSysfs::type() const { return DevType::SYS; }\n\nbool fc::FanSysfs::set_pwm(const Pwm pwm) {\n  if (!Util::write(pwm_path, pwm) && !Fan::recover_control())\n    return false;\n\n  return Fan::set_pwm(pwm);\n}\n\nPwm fc::FanSysfs::get_pwm() const {\n  const auto pwm = Util::read<Pwm>(pwm_path);\n  if (pwm) {\n    return *pwm;\n  } else {\n    LOG(llvl::error) << *this << \": failed to get pwm\";\n    return 0;\n  }\n}\n\nRpm fc::FanSysfs::get_rpm() const {\n  const auto rpm = Util::read<Rpm>(rpm_path);\n  if (rpm) {\n    return *rpm;\n  } else {\n    LOG(llvl::error) << *this << \": failed to get rpm\";\n    return 0;\n  }\n}\n\nvoid fc::FanSysfs::test_driver_enable_flag() {\n  if (exists(enable_path)) {\n    \/\/ 0: no fan speed control (i.e. fan at full speed)\n    \/\/ 1: manual fan speed control enabled\n    \/\/ 2+: automatic fan speed control enabled\n    const auto mode = Util::read<control_flag_t>(enable_path);\n    if (mode && *mode != 0 && *mode != manual_flag)\n      driver_flag = *mode;\n  }\n}\n\npath fc::FanSysfs::get_pwm_path(const path &adapter_path, SysfsID dev_id) {\n  const auto p = adapter_path \/ path(string(\"pwm\") + to_string(dev_id));\n  return Util::real_path(p).value_or(\"\");\n}\n\npath fc::FanSysfs::get_rpm_path(const path &adapter_path, SysfsID dev_id) {\n  const auto p = adapter_path \/ path(\"fan\" + to_string(dev_id) + \"_input\");\n  return Util::real_path(p).value_or(\"\");\n}\n\npath fc::FanSysfs::get_enable_path(const path &adapter_path, SysfsID dev_id) {\n  const path p = get_pwm_path(adapter_path, dev_id).string() + \"_enable\";\n  return Util::real_path(p).value_or(\"\");\n}\n\noptional<path> fc::FanSysfs::get_sensor_enable_path(const path &adapter_path, SysfsID dev_id) {\n  return Util::real_path(adapter_path \/ path(\"fan\" + to_string(dev_id) + \"_enable\"));\n}\n\nbool fc::FanSysfs::is_faulty(const path &adapter_path, SysfsID dev_id) {\n  const path fault_p{adapter_path \/ path(\"fan\" + to_string(dev_id) + \"_fault\")};\n  return Util::read<int>(fault_p).value_or(0) > 0;\n}\n","avg_line_length":28.8308823529,"max_line_length":112,"alphanum_fraction":0.6648814078,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":81192,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-3.0","Apache-2.0","MIT"],"max_stars_count":null,"content":"\/*************************************************************************\/\n\/*  script_editor_debugger.cpp                                           *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"script_editor_debugger.h\"\n\n#include \"core\/io\/marshalls.h\"\n#include \"core\/project_settings.h\"\n#include \"core\/ustring.h\"\n#include \"editor\/editor_log.h\"\n#include \"editor\/editor_network_profiler.h\"\n#include \"editor\/editor_visual_profiler.h\"\n#include \"editor\/plugins\/canvas_item_editor_plugin.h\"\n#include \"editor\/plugins\/spatial_editor_plugin.h\"\n#include \"editor_node.h\"\n#include \"editor_profiler.h\"\n#include \"editor_scale.h\"\n#include \"editor_settings.h\"\n#include \"main\/performance.h\"\n#include \"property_editor.h\"\n#include \"scene\/gui\/dialogs.h\"\n#include \"scene\/gui\/label.h\"\n#include \"scene\/gui\/line_edit.h\"\n#include \"scene\/gui\/margin_container.h\"\n#include \"scene\/gui\/rich_text_label.h\"\n#include \"scene\/gui\/separator.h\"\n#include \"scene\/gui\/split_container.h\"\n#include \"scene\/gui\/tab_container.h\"\n#include \"scene\/gui\/texture_button.h\"\n#include \"scene\/gui\/tree.h\"\n#include \"scene\/resources\/packed_scene.h\"\n\nclass ScriptEditorDebuggerVariables : public Object {\n\n\tGDCLASS(ScriptEditorDebuggerVariables, Object);\n\n\tList<PropertyInfo> props;\n\tMap<StringName, Variant> values;\n\nprotected:\n\tbool _set(const StringName &p_name, const Variant &p_value) {\n\n\t\treturn false;\n\t}\n\n\tbool _get(const StringName &p_name, Variant &r_ret) const {\n\n\t\tif (!values.has(p_name))\n\t\t\treturn false;\n\t\tr_ret = values[p_name];\n\t\treturn true;\n\t}\n\tvoid _get_property_list(List<PropertyInfo> *p_list) const {\n\n\t\tfor (const List<PropertyInfo>::Element *E = props.front(); E; E = E->next())\n\t\t\tp_list->push_back(E->get());\n\t}\n\npublic:\n\tvoid clear() {\n\n\t\tprops.clear();\n\t\tvalues.clear();\n\t}\n\n\tString get_var_value(const String &p_var) const {\n\n\t\tfor (Map<StringName, Variant>::Element *E = values.front(); E; E = E->next()) {\n\t\t\tString v = E->key().operator String().get_slice(\"\/\", 1);\n\t\t\tif (v == p_var)\n\t\t\t\treturn E->get();\n\t\t}\n\n\t\treturn \"\";\n\t}\n\n\tvoid add_property(const String &p_name, const Variant &p_value, const PropertyHint &p_hint, const String p_hint_string) {\n\n\t\tPropertyInfo pinfo;\n\t\tpinfo.name = p_name;\n\t\tpinfo.type = p_value.get_type();\n\t\tpinfo.hint = p_hint;\n\t\tpinfo.hint_string = p_hint_string;\n\t\tprops.push_back(pinfo);\n\t\tvalues[p_name] = p_value;\n\t}\n\n\tvoid update() {\n\t\t_change_notify();\n\t}\n\n\tScriptEditorDebuggerVariables() {\n\t}\n};\n\nclass ScriptEditorDebuggerInspectedObject : public Object {\n\n\tGDCLASS(ScriptEditorDebuggerInspectedObject, Object);\n\nprotected:\n\tbool _set(const StringName &p_name, const Variant &p_value) {\n\n\t\tif (!prop_values.has(p_name) || String(p_name).begins_with(\"Constants\/\"))\n\t\t\treturn false;\n\n\t\tprop_values[p_name] = p_value;\n\t\temit_signal(\"value_edited\", p_name, p_value);\n\t\treturn true;\n\t}\n\n\tbool _get(const StringName &p_name, Variant &r_ret) const {\n\n\t\tif (!prop_values.has(p_name))\n\t\t\treturn false;\n\n\t\tr_ret = prop_values[p_name];\n\t\treturn true;\n\t}\n\n\tvoid _get_property_list(List<PropertyInfo> *p_list) const {\n\n\t\tp_list->clear(); \/\/sorry, no want category\n\t\tfor (const List<PropertyInfo>::Element *E = prop_list.front(); E; E = E->next()) {\n\t\t\tp_list->push_back(E->get());\n\t\t}\n\t}\n\n\tstatic void _bind_methods() {\n\n\t\tClassDB::bind_method(D_METHOD(\"get_title\"), &ScriptEditorDebuggerInspectedObject::get_title);\n\t\tClassDB::bind_method(D_METHOD(\"get_variant\"), &ScriptEditorDebuggerInspectedObject::get_variant);\n\t\tClassDB::bind_method(D_METHOD(\"clear\"), &ScriptEditorDebuggerInspectedObject::clear);\n\t\tClassDB::bind_method(D_METHOD(\"get_remote_object_id\"), &ScriptEditorDebuggerInspectedObject::get_remote_object_id);\n\n\t\tADD_SIGNAL(MethodInfo(\"value_edited\"));\n\t}\n\npublic:\n\tString type_name;\n\tObjectID remote_object_id;\n\tList<PropertyInfo> prop_list;\n\tMap<StringName, Variant> prop_values;\n\n\tObjectID get_remote_object_id() {\n\t\treturn remote_object_id;\n\t}\n\n\tString get_title() {\n\t\tif (remote_object_id)\n\t\t\treturn TTR(\"Remote \") + String(type_name) + \": \" + itos(remote_object_id);\n\t\telse\n\t\t\treturn \"<null>\";\n\t}\n\tVariant get_variant(const StringName &p_name) {\n\n\t\tVariant var;\n\t\t_get(p_name, var);\n\t\treturn var;\n\t}\n\n\tvoid clear() {\n\n\t\tprop_list.clear();\n\t\tprop_values.clear();\n\t}\n\tvoid update() {\n\t\t_change_notify();\n\t}\n\tvoid update_single(const char *p_prop) {\n\t\t_change_notify(p_prop);\n\t}\n\n\tScriptEditorDebuggerInspectedObject() {\n\t\tremote_object_id = 0;\n\t}\n};\n\nvoid ScriptEditorDebugger::debug_copy() {\n\tString msg = reason->get_text();\n\tif (msg == \"\") return;\n\tOS::get_singleton()->set_clipboard(msg);\n}\n\nvoid ScriptEditorDebugger::debug_skip_breakpoints() {\n\tskip_breakpoints_value = !skip_breakpoints_value;\n\tif (skip_breakpoints_value)\n\t\tskip_breakpoints->set_icon(get_icon(\"DebugSkipBreakpointsOn\", \"EditorIcons\"));\n\telse\n\t\tskip_breakpoints->set_icon(get_icon(\"DebugSkipBreakpointsOff\", \"EditorIcons\"));\n\n\tif (connection.is_valid()) {\n\t\tArray msg;\n\t\tmsg.push_back(\"set_skip_breakpoints\");\n\t\tmsg.push_back(skip_breakpoints_value);\n\t\tppeer->put_var(msg);\n\t}\n}\n\nvoid ScriptEditorDebugger::debug_next() {\n\n\tERR_FAIL_COND(!breaked);\n\tERR_FAIL_COND(connection.is_null());\n\tERR_FAIL_COND(!connection->is_connected_to_host());\n\tArray msg;\n\tmsg.push_back(\"next\");\n\tppeer->put_var(msg);\n\t_clear_execution();\n\tstack_dump->clear();\n}\nvoid ScriptEditorDebugger::debug_step() {\n\n\tERR_FAIL_COND(!breaked);\n\tERR_FAIL_COND(connection.is_null());\n\tERR_FAIL_COND(!connection->is_connected_to_host());\n\n\tArray msg;\n\tmsg.push_back(\"step\");\n\tppeer->put_var(msg);\n\t_clear_execution();\n\tstack_dump->clear();\n}\n\nvoid ScriptEditorDebugger::debug_break() {\n\n\tERR_FAIL_COND(breaked);\n\tERR_FAIL_COND(connection.is_null());\n\tERR_FAIL_COND(!connection->is_connected_to_host());\n\n\tArray msg;\n\tmsg.push_back(\"break\");\n\tppeer->put_var(msg);\n}\n\nvoid ScriptEditorDebugger::debug_continue() {\n\n\tERR_FAIL_COND(!breaked);\n\tERR_FAIL_COND(connection.is_null());\n\tERR_FAIL_COND(!connection->is_connected_to_host());\n\n\tOS::get_singleton()->enable_for_stealing_focus(EditorNode::get_singleton()->get_child_process_id());\n\n\tArray msg;\n\t_clear_execution();\n\tmsg.push_back(\"continue\");\n\tppeer->put_var(msg);\n}\n\nvoid ScriptEditorDebugger::_scene_tree_folded(Object *obj) {\n\n\tif (updating_scene_tree) {\n\n\t\treturn;\n\t}\n\tTreeItem *item = Object::cast_to<TreeItem>(obj);\n\n\tif (!item)\n\t\treturn;\n\n\tObjectID id = item->get_metadata(0);\n\tif (unfold_cache.has(id)) {\n\t\tunfold_cache.erase(id);\n\t} else {\n\t\tunfold_cache.insert(id);\n\t}\n}\n\nvoid ScriptEditorDebugger::_scene_tree_selected() {\n\n\tif (updating_scene_tree) {\n\n\t\treturn;\n\t}\n\tTreeItem *item = inspect_scene_tree->get_selected();\n\tif (!item) {\n\n\t\treturn;\n\t}\n\n\tinspected_object_id = item->get_metadata(0);\n\n\tArray msg;\n\tmsg.push_back(\"inspect_object\");\n\tmsg.push_back(inspected_object_id);\n\tppeer->put_var(msg);\n}\n\nvoid ScriptEditorDebugger::_scene_tree_rmb_selected(const Vector2 &p_position) {\n\n\tTreeItem *item = inspect_scene_tree->get_item_at_position(p_position);\n\tif (!item)\n\t\treturn;\n\n\titem->select(0);\n\n\titem_menu->clear();\n\titem_menu->add_icon_item(get_icon(\"CreateNewSceneFrom\", \"EditorIcons\"), TTR(\"Save Branch as Scene\"), ITEM_MENU_SAVE_REMOTE_NODE);\n\titem_menu->add_icon_item(get_icon(\"CopyNodePath\", \"EditorIcons\"), TTR(\"Copy Node Path\"), ITEM_MENU_COPY_NODE_PATH);\n\titem_menu->set_global_position(get_global_mouse_position());\n\titem_menu->popup();\n}\n\nvoid ScriptEditorDebugger::_file_selected(const String &p_file) {\n\tswitch (file_dialog_mode) {\n\t\tcase SAVE_NODE: {\n\t\t\tArray msg;\n\t\t\tmsg.push_back(\"save_node\");\n\t\t\tmsg.push_back(inspected_object_id);\n\t\t\tmsg.push_back(p_file);\n\t\t\tppeer->put_var(msg);\n\t\t} break;\n\t\tcase SAVE_CSV: {\n\t\t\tError err;\n\t\t\tFileAccessRef file = FileAccess::open(p_file, FileAccess::WRITE, &err);\n\n\t\t\tif (err != OK) {\n\t\t\t\tERR_PRINT(\"Failed to open \" + p_file);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tVector<String> line;\n\t\t\tline.resize(Performance::MONITOR_MAX);\n\n\t\t\t\/\/ signatures\n\t\t\tfor (int i = 0; i < Performance::MONITOR_MAX; i++) {\n\t\t\t\tline.write[i] = Performance::get_singleton()->get_monitor_name(Performance::Monitor(i));\n\t\t\t}\n\t\t\tfile->store_csv_line(line);\n\n\t\t\t\/\/ values\n\t\t\tList<Vector<float> >::Element *E = perf_history.back();\n\t\t\twhile (E) {\n\n\t\t\t\tVector<float> &perf_data = E->get();\n\t\t\t\tfor (int i = 0; i < perf_data.size(); i++) {\n\n\t\t\t\t\tline.write[i] = String::num_real(perf_data[i]);\n\t\t\t\t}\n\t\t\t\tfile->store_csv_line(line);\n\t\t\t\tE = E->prev();\n\t\t\t}\n\t\t\tfile->store_string(\"\\n\");\n\n\t\t\tVector<Vector<String> > profiler_data = profiler->get_data_as_csv();\n\t\t\tfor (int i = 0; i < profiler_data.size(); i++) {\n\t\t\t\tfile->store_csv_line(profiler_data[i]);\n\t\t\t}\n\n\t\t} break;\n\t}\n}\n\nvoid ScriptEditorDebugger::_scene_tree_property_value_edited(const String &p_prop, const Variant &p_value) {\n\n\tArray msg;\n\tmsg.push_back(\"set_object_property\");\n\tmsg.push_back(inspected_object_id);\n\tmsg.push_back(p_prop);\n\tmsg.push_back(p_value);\n\tppeer->put_var(msg);\n\tinspect_edited_object_timeout = 0.7; \/\/avoid annoyance, don't request soon after editing\n}\n\nvoid ScriptEditorDebugger::_scene_tree_property_select_object(ObjectID p_object) {\n\n\tinspected_object_id = p_object;\n\tArray msg;\n\tmsg.push_back(\"inspect_object\");\n\tmsg.push_back(inspected_object_id);\n\tppeer->put_var(msg);\n}\n\nvoid ScriptEditorDebugger::_scene_tree_request() {\n\n\tERR_FAIL_COND(connection.is_null());\n\tERR_FAIL_COND(!connection->is_connected_to_host());\n\n\tArray msg;\n\tmsg.push_back(\"request_scene_tree\");\n\tppeer->put_var(msg);\n}\n\n\/\/\/ Populates inspect_scene_tree recursively given data in nodes.\n\/\/\/ Nodes is an array containing 4 elements for each node, it follows this pattern:\n\/\/\/ nodes[i] == number of direct children of this node\n\/\/\/ nodes[i + 1] == node name\n\/\/\/ nodes[i + 2] == node class\n\/\/\/ nodes[i + 3] == node instance id\n\/\/\/\n\/\/\/ Returns the number of items parsed in nodes from current_index.\n\/\/\/\n\/\/\/ Given a nodes array like [R,A,B,C,D,E] the following Tree will be generated, assuming\n\/\/\/ filter is an empty String, R and A child count are 2, B is 1 and C, D and E are 0.\n\/\/\/\n\/\/\/ R\n\/\/\/ |-A\n\/\/\/ | |-B\n\/\/\/ | | |-C\n\/\/\/ | |\n\/\/\/ | |-D\n\/\/\/ |\n\/\/\/ |-E\n\/\/\/\nint ScriptEditorDebugger::_update_scene_tree(TreeItem *parent, const Array &nodes, int current_index) {\n\tString filter = EditorNode::get_singleton()->get_scene_tree_dock()->get_filter();\n\tString item_text = nodes[current_index + 1];\n\tString item_type = nodes[current_index + 2];\n\tbool keep = filter.is_subsequence_ofi(item_text);\n\n\tTreeItem *item = inspect_scene_tree->create_item(parent);\n\titem->set_text(0, item_text);\n\titem->set_tooltip(0, TTR(\"Type:\") + \" \" + item_type);\n\tObjectID id = ObjectID(nodes[current_index + 3]);\n\tRef<Texture2D> icon = EditorNode::get_singleton()->get_class_icon(nodes[current_index + 2], \"\");\n\tif (icon.is_valid()) {\n\t\titem->set_icon(0, icon);\n\t}\n\titem->set_metadata(0, id);\n\n\tif (id == inspected_object_id) {\n\t\tTreeItem *cti = item->get_parent();\n\t\twhile (cti) {\n\t\t\tcti->set_collapsed(false);\n\t\t\tcti = cti->get_parent();\n\t\t}\n\t\titem->select(0);\n\t}\n\n\t\/\/ Set current item as collapsed if necessary\n\tif (parent) {\n\t\tif (!unfold_cache.has(id)) {\n\t\t\titem->set_collapsed(true);\n\t\t}\n\t}\n\n\tint children_count = nodes[current_index];\n\t\/\/ Tracks the total number of items parsed in nodes, this is used to skips nodes that\n\t\/\/ are not direct children of the current node since we can't know in advance the total\n\t\/\/ number of children, direct and not, of a node without traversing the nodes array previously.\n\t\/\/ Keeping track of this allows us to build our remote scene tree by traversing the node\n\t\/\/ array just once.\n\tint items_count = 1;\n\tfor (int i = 0; i < children_count; i++) {\n\t\t\/\/ Called for each direct child of item.\n\t\t\/\/ Direct children of current item might not be adjacent so items_count must\n\t\t\/\/ be incremented by the number of items parsed until now, otherwise we would not\n\t\t\/\/ be able to access the next child of the current item.\n\t\t\/\/ items_count is multiplied by 4 since that's the number of elements in the nodes\n\t\t\/\/ array needed to represent a single node.\n\t\titems_count += _update_scene_tree(item, nodes, current_index + items_count * 4);\n\t}\n\n\t\/\/ If item has not children and should not be kept delete it\n\tif (!keep && !item->get_children() && parent) {\n\t\tparent->remove_child(item);\n\t\tmemdelete(item);\n\t}\n\n\treturn items_count;\n}\n\nvoid ScriptEditorDebugger::_video_mem_request() {\n\n\tif (connection.is_null() || !connection->is_connected_to_host()) {\n\t\t\/\/ Video RAM usage is only available while a project is being debugged.\n\t\treturn;\n\t}\n\n\tArray msg;\n\tmsg.push_back(\"request_video_mem\");\n\tppeer->put_var(msg);\n}\n\nSize2 ScriptEditorDebugger::get_minimum_size() const {\n\n\tSize2 ms = MarginContainer::get_minimum_size();\n\tms.y = MAX(ms.y, 250 * EDSCALE);\n\treturn ms;\n}\n\nvoid ScriptEditorDebugger::_parse_message(const String &p_msg, const Array &p_data) {\n\n\tif (p_msg == \"debug_enter\") {\n\t\tArray msg;\n\t\tmsg.push_back(\"get_stack_dump\");\n\t\tppeer->put_var(msg);\n\t\tERR_FAIL_COND(p_data.size() != 2);\n\t\tbool can_continue = p_data[0];\n\t\tString error = p_data[1];\n\t\tstep->set_disabled(!can_continue);\n\t\tnext->set_disabled(!can_continue);\n\t\t_set_reason_text(error, MESSAGE_ERROR);\n\t\tcopy->set_disabled(false);\n\t\tbreaked = true;\n\t\tdobreak->set_disabled(true);\n\t\tdocontinue->set_disabled(false);\n\t\temit_signal(\"breaked\", true, can_continue);\n\t\tOS::get_singleton()->move_window_to_foreground();\n\t\tif (error != \"\") {\n\t\t\ttabs->set_current_tab(0);\n\t\t}\n\t\tprofiler->set_enabled(false);\n\t\tEditorNode::get_singleton()->get_pause_button()->set_pressed(true);\n\t\tEditorNode::get_singleton()->make_bottom_panel_item_visible(this);\n\t\t_clear_remote_objects();\n\n\t} else if (p_msg == \"debug_exit\") {\n\n\t\tbreaked = false;\n\t\t_clear_execution();\n\t\tcopy->set_disabled(true);\n\t\tstep->set_disabled(true);\n\t\tnext->set_disabled(true);\n\t\treason->set_text(\"\");\n\t\treason->set_tooltip(\"\");\n\t\tback->set_disabled(true);\n\t\tforward->set_disabled(true);\n\t\tdobreak->set_disabled(false);\n\t\tdocontinue->set_disabled(true);\n\t\temit_signal(\"breaked\", false, false, Variant());\n\t\tprofiler->set_enabled(true);\n\t\tprofiler->disable_seeking();\n\t\tEditorNode::get_singleton()->get_pause_button()->set_pressed(false);\n\t} else if (p_msg == \"message:click_ctrl\") {\n\n\t\tclicked_ctrl->set_text(p_data[0]);\n\t\tclicked_ctrl_type->set_text(p_data[1]);\n\n\t} else if (p_msg == \"message:scene_tree\") {\n\n\t\tinspect_scene_tree->clear();\n\t\tMap<int, TreeItem *> lv;\n\n\t\tupdating_scene_tree = true;\n\n\t\t_update_scene_tree(NULL, p_data, 0);\n\n\t\tupdating_scene_tree = false;\n\n\t\tle_clear->set_disabled(false);\n\t\tle_set->set_disabled(false);\n\t} else if (p_msg == \"message:inspect_object\") {\n\n\t\tScriptEditorDebuggerInspectedObject *debugObj = NULL;\n\n\t\tObjectID id = p_data[0];\n\t\tString type = p_data[1];\n\t\tArray properties = p_data[2];\n\n\t\tif (remote_objects.has(id)) {\n\t\t\tdebugObj = remote_objects[id];\n\t\t} else {\n\t\t\tdebugObj = memnew(ScriptEditorDebuggerInspectedObject);\n\t\t\tdebugObj->remote_object_id = id;\n\t\t\tdebugObj->type_name = type;\n\t\t\tremote_objects[id] = debugObj;\n\t\t\tdebugObj->connect(\"value_edited\", this, \"_scene_tree_property_value_edited\");\n\t\t}\n\n\t\tint old_prop_size = debugObj->prop_list.size();\n\n\t\tdebugObj->prop_list.clear();\n\t\tint new_props_added = 0;\n\t\tSet<String> changed;\n\t\tfor (int i = 0; i < properties.size(); i++) {\n\n\t\t\tArray prop = properties[i];\n\t\t\tif (prop.size() != 6)\n\t\t\t\tcontinue;\n\n\t\t\tPropertyInfo pinfo;\n\t\t\tpinfo.name = prop[0];\n\t\t\tpinfo.type = Variant::Type(int(prop[1]));\n\t\t\tpinfo.hint = PropertyHint(int(prop[2]));\n\t\t\tpinfo.hint_string = prop[3];\n\t\t\tpinfo.usage = PropertyUsageFlags(int(prop[4]));\n\t\t\tVariant var = prop[5];\n\n\t\t\tif (pinfo.type == Variant::OBJECT) {\n\t\t\t\tif (var.is_zero()) {\n\t\t\t\t\tvar = RES();\n\t\t\t\t} else if (var.get_type() == Variant::STRING) {\n\t\t\t\t\tString path = var;\n\t\t\t\t\tif (path.find(\"::\") != -1) {\n\t\t\t\t\t\t\/\/ built-in resource\n\t\t\t\t\t\tString base_path = path.get_slice(\"::\", 0);\n\t\t\t\t\t\tif (ResourceLoader::get_resource_type(base_path) == \"PackedScene\") {\n\t\t\t\t\t\t\tif (!EditorNode::get_singleton()->is_scene_open(base_path)) {\n\t\t\t\t\t\t\t\tEditorNode::get_singleton()->load_scene(base_path);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tEditorNode::get_singleton()->load_resource(base_path);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tvar = ResourceLoader::load(path);\n\n\t\t\t\t\tif (pinfo.hint_string == \"Script\") {\n\t\t\t\t\t\tif (debugObj->get_script() != var) {\n\t\t\t\t\t\t\tdebugObj->set_script(RefPtr());\n\t\t\t\t\t\t\tRef<Script> script(var);\n\t\t\t\t\t\t\tif (!script.is_null()) {\n\t\t\t\t\t\t\t\tScriptInstance *script_instance = script->placeholder_instance_create(debugObj);\n\t\t\t\t\t\t\t\tdebugObj->set_script_and_instance(var, script_instance);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (var.get_type() == Variant::OBJECT) {\n\t\t\t\t\tif (((Object *)var)->is_class(\"EncodedObjectAsID\")) {\n\t\t\t\t\t\tvar = Object::cast_to<EncodedObjectAsID>(var)->get_object_id();\n\t\t\t\t\t\tpinfo.type = var.get_type();\n\t\t\t\t\t\tpinfo.hint = PROPERTY_HINT_OBJECT_ID;\n\t\t\t\t\t\tpinfo.hint_string = \"Object\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/always add the property, since props may have been added or removed\n\t\t\tdebugObj->prop_list.push_back(pinfo);\n\n\t\t\tif (!debugObj->prop_values.has(pinfo.name)) {\n\t\t\t\tnew_props_added++;\n\t\t\t\tdebugObj->prop_values[pinfo.name] = var;\n\t\t\t} else {\n\n\t\t\t\tif (bool(Variant::evaluate(Variant::OP_NOT_EQUAL, debugObj->prop_values[pinfo.name], var))) {\n\t\t\t\t\tdebugObj->prop_values[pinfo.name] = var;\n\t\t\t\t\tchanged.insert(pinfo.name);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (editor->get_editor_history()->get_current() != debugObj->get_instance_id()) {\n\t\t\teditor->push_item(debugObj, \"\");\n\t\t} else {\n\n\t\t\tif (old_prop_size == debugObj->prop_list.size() && new_props_added == 0) {\n\t\t\t\t\/\/only some may have changed, if so, then update those, if exist\n\t\t\t\tfor (Set<String>::Element *E = changed.front(); E; E = E->next()) {\n\t\t\t\t\tEditorNode::get_singleton()->get_inspector()->update_property(E->get());\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/full update, because props were added or removed\n\t\t\t\tdebugObj->update();\n\t\t\t}\n\t\t}\n\t} else if (p_msg == \"message:video_mem\") {\n\n\t\tvmem_tree->clear();\n\t\tTreeItem *root = vmem_tree->create_item();\n\n\t\tint total = 0;\n\n\t\tfor (int i = 0; i < p_data.size(); i += 4) {\n\n\t\t\tTreeItem *it = vmem_tree->create_item(root);\n\t\t\tString type = p_data[i + 1];\n\t\t\tint bytes = p_data[i + 3].operator int();\n\t\t\tit->set_text(0, p_data[i + 0]); \/\/path\n\t\t\tit->set_text(1, type); \/\/type\n\t\t\tit->set_text(2, p_data[i + 2]); \/\/type\n\t\t\tit->set_text(3, String::humanize_size(bytes)); \/\/type\n\t\t\ttotal += bytes;\n\n\t\t\tif (has_icon(type, \"EditorIcons\"))\n\t\t\t\tit->set_icon(0, get_icon(type, \"EditorIcons\"));\n\t\t}\n\n\t\tvmem_total->set_tooltip(TTR(\"Bytes:\") + \" \" + itos(total));\n\t\tvmem_total->set_text(String::humanize_size(total));\n\n\t} else if (p_msg == \"stack_dump\") {\n\n\t\tstack_dump->clear();\n\t\tTreeItem *r = stack_dump->create_item();\n\n\t\tfor (int i = 0; i < p_data.size(); i++) {\n\n\t\t\tDictionary d = p_data[i];\n\t\t\tERR_CONTINUE(!d.has(\"function\"));\n\t\t\tERR_CONTINUE(!d.has(\"file\"));\n\t\t\tERR_CONTINUE(!d.has(\"line\"));\n\t\t\tERR_CONTINUE(!d.has(\"id\"));\n\t\t\tTreeItem *s = stack_dump->create_item(r);\n\t\t\td[\"frame\"] = i;\n\t\t\ts->set_metadata(0, d);\n\n\t\t\tString line = itos(i) + \" - \" + String(d[\"file\"]) + \":\" + itos(d[\"line\"]) + \" - at function: \" + d[\"function\"];\n\t\t\ts->set_text(0, line);\n\n\t\t\tif (i == 0)\n\t\t\t\ts->select(0);\n\t\t}\n\t} else if (p_msg == \"stack_frame_vars\") {\n\n\t\tvariables->clear();\n\n\t\tint ofs = 0;\n\t\tint mcount = p_data[ofs];\n\t\tofs++;\n\t\tfor (int i = 0; i < mcount; i++) {\n\n\t\t\tString n = p_data[ofs + i * 2 + 0];\n\t\t\tVariant v = p_data[ofs + i * 2 + 1];\n\n\t\t\tPropertyHint h = PROPERTY_HINT_NONE;\n\t\t\tString hs = String();\n\n\t\t\tif (v.get_type() == Variant::OBJECT) {\n\t\t\t\tv = Object::cast_to<EncodedObjectAsID>(v)->get_object_id();\n\t\t\t\th = PROPERTY_HINT_OBJECT_ID;\n\t\t\t\ths = \"Object\";\n\t\t\t}\n\n\t\t\tvariables->add_property(\"Locals\/\" + n, v, h, hs);\n\t\t}\n\n\t\tofs += mcount * 2;\n\t\tmcount = p_data[ofs];\n\t\tofs++;\n\t\tfor (int i = 0; i < mcount; i++) {\n\n\t\t\tString n = p_data[ofs + i * 2 + 0];\n\t\t\tVariant v = p_data[ofs + i * 2 + 1];\n\t\t\tPropertyHint h = PROPERTY_HINT_NONE;\n\t\t\tString hs = String();\n\n\t\t\tif (v.get_type() == Variant::OBJECT) {\n\t\t\t\tv = Object::cast_to<EncodedObjectAsID>(v)->get_object_id();\n\t\t\t\th = PROPERTY_HINT_OBJECT_ID;\n\t\t\t\ths = \"Object\";\n\t\t\t}\n\n\t\t\tvariables->add_property(\"Members\/\" + n, v, h, hs);\n\n\t\t\tif (n == \"self\") {\n\t\t\t\t_scene_tree_property_select_object(v);\n\t\t\t}\n\t\t}\n\n\t\tofs += mcount * 2;\n\t\tmcount = p_data[ofs];\n\t\tofs++;\n\t\tfor (int i = 0; i < mcount; i++) {\n\n\t\t\tString n = p_data[ofs + i * 2 + 0];\n\t\t\tVariant v = p_data[ofs + i * 2 + 1];\n\t\t\tPropertyHint h = PROPERTY_HINT_NONE;\n\t\t\tString hs = String();\n\n\t\t\tif (v.get_type() == Variant::OBJECT) {\n\t\t\t\tv = Object::cast_to<EncodedObjectAsID>(v)->get_object_id();\n\t\t\t\th = PROPERTY_HINT_OBJECT_ID;\n\t\t\t\ths = \"Object\";\n\t\t\t}\n\n\t\t\tvariables->add_property(\"Globals\/\" + n, v, h, hs);\n\t\t}\n\n\t\tvariables->update();\n\t\tinspector->edit(variables);\n\n\t} else if (p_msg == \"output\") {\n\n\t\t\/\/OUT\n\t\tfor (int i = 0; i < p_data.size(); i++) {\n\n\t\t\tString t = p_data[i];\n\t\t\t\/\/LOG\n\n\t\t\tif (!EditorNode::get_log()->is_visible()) {\n\t\t\t\tif (EditorNode::get_singleton()->are_bottom_panels_hidden()) {\n\t\t\t\t\tif (EDITOR_GET(\"run\/output\/always_open_output_on_play\")) {\n\t\t\t\t\t\tEditorNode::get_singleton()->make_bottom_panel_item_visible(EditorNode::get_log());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tEditorNode::get_log()->add_message(t);\n\t\t}\n\n\t} else if (p_msg == \"performance\") {\n\t\tArray arr = p_data[0];\n\t\tVector<float> p;\n\t\tp.resize(arr.size());\n\t\tfor (int i = 0; i < arr.size(); i++) {\n\t\t\tp.write[i] = arr[i];\n\t\t\tif (i < perf_items.size()) {\n\n\t\t\t\tconst float value = p[i];\n\t\t\t\tString label = rtos(value);\n\t\t\t\tString tooltip = label;\n\t\t\t\tswitch (Performance::MonitorType((int)perf_items[i]->get_metadata(1))) {\n\t\t\t\t\tcase Performance::MONITOR_TYPE_MEMORY: {\n\t\t\t\t\t\tlabel = String::humanize_size(value);\n\t\t\t\t\t\ttooltip = label;\n\t\t\t\t\t} break;\n\t\t\t\t\tcase Performance::MONITOR_TYPE_TIME: {\n\t\t\t\t\t\tlabel = rtos(value * 1000).pad_decimals(2) + \" ms\";\n\t\t\t\t\t\ttooltip = label;\n\t\t\t\t\t} break;\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\ttooltip += \" \" + perf_items[i]->get_text(0);\n\t\t\t\t\t} break;\n\t\t\t\t}\n\n\t\t\t\tperf_items[i]->set_text(1, label);\n\t\t\t\tperf_items[i]->set_tooltip(1, tooltip);\n\t\t\t\tif (p[i] > perf_max[i])\n\t\t\t\t\tperf_max.write[i] = p[i];\n\t\t\t}\n\t\t}\n\t\tperf_history.push_front(p);\n\t\tperf_draw->update();\n\t} else if (p_msg == \"visual_profile\") {\n\t\tuint64_t frame = p_data[0];\n\t\tPoolVector<String> names = p_data[1];\n\t\tPoolVector<real_t> values = p_data[2];\n\n\t\tEditorVisualProfiler::Metric metric;\n\t\tmetric.areas.resize(names.size());\n\t\tmetric.frame_number = frame;\n\t\tmetric.valid = true;\n\n\t\t{\n\t\t\tEditorVisualProfiler::Metric::Area *areas_ptr = metric.areas.ptrw();\n\t\t\tint metric_count = names.size();\n\n\t\t\tPoolVector<String>::Read rs = names.read();\n\t\t\tPoolVector<real_t>::Read rr = values.read();\n\n\t\t\tfor (int i = 0; i < metric_count; i++) {\n\n\t\t\t\tareas_ptr[i].name = rs[i];\n\t\t\t\tareas_ptr[i].cpu_time = rr[i * 2 + 0];\n\t\t\t\tareas_ptr[i].gpu_time = rr[i * 2 + 1];\n\t\t\t}\n\t\t}\n\n\t\tvisual_profiler->add_frame_metric(metric);\n\n\t} else if (p_msg == \"error\") {\n\n\t\t\/\/ Should have at least two elements, error array and stack items count.\n\t\tERR_FAIL_COND_MSG(p_data.size() < 2, \"Malformed error message from script debugger.\");\n\n\t\t\/\/ Error or warning data.\n\t\tArray err = p_data[0];\n\t\tERR_FAIL_COND_MSG(err.size() < 10, \"Malformed error message from script debugger.\");\n\n\t\t\/\/ Format time.\n\t\tArray time_vals;\n\t\ttime_vals.push_back(err[0]);\n\t\ttime_vals.push_back(err[1]);\n\t\ttime_vals.push_back(err[2]);\n\t\ttime_vals.push_back(err[3]);\n\t\tbool e;\n\t\tString time = String(\"%d:%02d:%02d.%03d\").sprintf(time_vals, &e);\n\n\t\t\/\/ Rest of the error data.\n\t\tString method = err[4];\n\t\tString source_file = err[5];\n\t\tString source_line = err[6];\n\t\tString error_cond = err[7];\n\t\tString error_msg = err[8];\n\t\tbool is_warning = err[9];\n\t\tbool has_method = !method.empty();\n\t\tbool has_error_msg = !error_msg.empty();\n\t\tbool source_is_project_file = source_file.begins_with(\"res:\/\/\");\n\n\t\t\/\/ Metadata to highlight error line in scripts.\n\t\tArray source_meta;\n\t\tsource_meta.push_back(source_file);\n\t\tsource_meta.push_back(source_line);\n\n\t\t\/\/ Create error tree to display above error or warning details.\n\t\tTreeItem *r = error_tree->get_root();\n\t\tif (!r) {\n\t\t\tr = error_tree->create_item();\n\t\t}\n\n\t\t\/\/ Also provide the relevant details as tooltip to quickly check without\n\t\t\/\/ uncollapsing the tree.\n\t\tString tooltip = is_warning ? TTR(\"Warning:\") : TTR(\"Error:\");\n\n\t\tTreeItem *error = error_tree->create_item(r);\n\t\terror->set_collapsed(true);\n\n\t\terror->set_icon(0, get_icon(is_warning ? \"Warning\" : \"Error\", \"EditorIcons\"));\n\t\terror->set_text(0, time);\n\t\terror->set_text_align(0, TreeItem::ALIGN_LEFT);\n\n\t\tString error_title;\n\t\t\/\/ Include method name, when given, in error title.\n\t\tif (has_method)\n\t\t\terror_title += method + \": \";\n\t\t\/\/ If we have a (custom) error message, use it as title, and add a C++ Error\n\t\t\/\/ item with the original error condition.\n\t\terror_title += error_msg.empty() ? error_cond : error_msg;\n\t\terror->set_text(1, error_title);\n\t\ttooltip += \" \" + error_title + \"\\n\";\n\n\t\tif (has_error_msg) {\n\t\t\t\/\/ Add item for C++ error condition.\n\t\t\tTreeItem *cpp_cond = error_tree->create_item(error);\n\t\t\tcpp_cond->set_text(0, \"<\" + TTR(\"C++ Error\") + \">\");\n\t\t\tcpp_cond->set_text(1, error_cond);\n\t\t\tcpp_cond->set_text_align(0, TreeItem::ALIGN_LEFT);\n\t\t\ttooltip += TTR(\"C++ Error:\") + \" \" + error_cond + \"\\n\";\n\t\t\tif (source_is_project_file)\n\t\t\t\tcpp_cond->set_metadata(0, source_meta);\n\t\t}\n\n\t\t\/\/ Source of the error.\n\t\tString source_txt = (source_is_project_file ? source_file.get_file() : source_file) + \":\" + source_line;\n\t\tif (has_method)\n\t\t\tsource_txt += \" @ \" + method + \"()\";\n\n\t\tTreeItem *cpp_source = error_tree->create_item(error);\n\t\tcpp_source->set_text(0, \"<\" + (source_is_project_file ? TTR(\"Source\") : TTR(\"C++ Source\")) + \">\");\n\t\tcpp_source->set_text(1, source_txt);\n\t\tcpp_source->set_text_align(0, TreeItem::ALIGN_LEFT);\n\t\ttooltip += (source_is_project_file ? TTR(\"Source:\") : TTR(\"C++ Source:\")) + \" \" + source_txt + \"\\n\";\n\n\t\t\/\/ Set metadata to highlight error line in scripts.\n\t\tif (source_is_project_file) {\n\t\t\terror->set_metadata(0, source_meta);\n\t\t\tcpp_source->set_metadata(0, source_meta);\n\t\t}\n\n\t\terror->set_tooltip(0, tooltip);\n\t\terror->set_tooltip(1, tooltip);\n\n\t\t\/\/ Format stack trace.\n\t\t\/\/ stack_items_count is the number of elements to parse, with 3 items per frame\n\t\t\/\/ of the stack trace (script, method, line).\n\t\tint stack_items_count = p_data[1];\n\n\t\tfor (int i = 0; i < stack_items_count; i += 3) {\n\t\t\tString script = p_data[2 + i];\n\t\t\tString method2 = p_data[3 + i];\n\t\t\tint line = p_data[4 + i];\n\t\t\tTreeItem *stack_trace = error_tree->create_item(error);\n\n\t\t\tArray meta;\n\t\t\tmeta.push_back(script);\n\t\t\tmeta.push_back(line);\n\t\t\tstack_trace->set_metadata(0, meta);\n\n\t\t\tif (i == 0) {\n\t\t\t\tstack_trace->set_text(0, \"<\" + TTR(\"Stack Trace\") + \">\");\n\t\t\t\tstack_trace->set_text_align(0, TreeItem::ALIGN_LEFT);\n\t\t\t\terror->set_metadata(0, meta);\n\t\t\t}\n\t\t\tstack_trace->set_text(1, script.get_file() + \":\" + itos(line) + \" @ \" + method2 + \"()\");\n\t\t}\n\n\t\tif (is_warning)\n\t\t\twarning_count++;\n\t\telse\n\t\t\terror_count++;\n\n\t} else if (p_msg == \"profile_sig\") {\n\t\t\/\/cache a signature\n\t\tprofiler_signature[p_data[1]] = p_data[0];\n\n\t} else if (p_msg == \"profile_frame\" || p_msg == \"profile_total\") {\n\n\t\tEditorProfiler::Metric metric;\n\t\tmetric.valid = true;\n\t\tmetric.frame_number = p_data[0];\n\t\tmetric.frame_time = p_data[1];\n\t\tmetric.idle_time = p_data[2];\n\t\tmetric.physics_time = p_data[3];\n\t\tmetric.physics_frame_time = p_data[4];\n\t\tint frame_data_amount = p_data[6];\n\t\tint frame_function_amount = p_data[7];\n\n\t\tif (frame_data_amount) {\n\t\t\tEditorProfiler::Metric::Category frame_time;\n\t\t\tframe_time.signature = \"category_frame_time\";\n\t\t\tframe_time.name = \"Frame Time\";\n\t\t\tframe_time.total_time = metric.frame_time;\n\n\t\t\tEditorProfiler::Metric::Category::Item item;\n\t\t\titem.calls = 1;\n\t\t\titem.line = 0;\n\n\t\t\titem.name = \"Physics Time\";\n\t\t\titem.total = metric.physics_time;\n\t\t\titem.self = item.total;\n\t\t\titem.signature = \"physics_time\";\n\n\t\t\tframe_time.items.push_back(item);\n\n\t\t\titem.name = \"Idle Time\";\n\t\t\titem.total = metric.idle_time;\n\t\t\titem.self = item.total;\n\t\t\titem.signature = \"idle_time\";\n\n\t\t\tframe_time.items.push_back(item);\n\n\t\t\titem.name = \"Physics Frame Time\";\n\t\t\titem.total = metric.physics_frame_time;\n\t\t\titem.self = item.total;\n\t\t\titem.signature = \"physics_frame_time\";\n\n\t\t\tframe_time.items.push_back(item);\n\n\t\t\tmetric.categories.push_back(frame_time);\n\t\t}\n\n\t\tint idx = 8;\n\t\tfor (int i = 0; i < frame_data_amount; i++) {\n\n\t\t\tEditorProfiler::Metric::Category c;\n\t\t\tString name = p_data[idx++];\n\t\t\tArray values = p_data[idx++];\n\t\t\tc.name = name.capitalize();\n\t\t\tc.items.resize(values.size() \/ 2);\n\t\t\tc.total_time = 0;\n\t\t\tc.signature = \"categ::\" + name;\n\t\t\tfor (int j = 0; j < values.size(); j += 2) {\n\n\t\t\t\tEditorProfiler::Metric::Category::Item item;\n\t\t\t\titem.calls = 1;\n\t\t\t\titem.line = 0;\n\t\t\t\titem.name = values[j];\n\t\t\t\titem.self = values[j + 1];\n\t\t\t\titem.total = item.self;\n\t\t\t\titem.signature = \"categ::\" + name + \"::\" + item.name;\n\t\t\t\titem.name = item.name.capitalize();\n\t\t\t\tc.total_time += item.total;\n\t\t\t\tc.items.write[j \/ 2] = item;\n\t\t\t}\n\t\t\tmetric.categories.push_back(c);\n\t\t}\n\n\t\tEditorProfiler::Metric::Category funcs;\n\t\tfuncs.total_time = p_data[5]; \/\/script time\n\t\tfuncs.items.resize(frame_function_amount);\n\t\tfuncs.name = \"Script Functions\";\n\t\tfuncs.signature = \"script_functions\";\n\t\tfor (int i = 0; i < frame_function_amount; i++) {\n\n\t\t\tint signature = p_data[idx++];\n\t\t\tint calls = p_data[idx++];\n\t\t\tfloat total = p_data[idx++];\n\t\t\tfloat self = p_data[idx++];\n\n\t\t\tEditorProfiler::Metric::Category::Item item;\n\t\t\tif (profiler_signature.has(signature)) {\n\n\t\t\t\titem.signature = profiler_signature[signature];\n\n\t\t\t\tString name = profiler_signature[signature];\n\t\t\t\tVector<String> strings = name.split(\"::\");\n\t\t\t\tif (strings.size() == 3) {\n\t\t\t\t\titem.name = strings[2];\n\t\t\t\t\titem.script = strings[0];\n\t\t\t\t\titem.line = strings[1].to_int();\n\t\t\t\t} else if (strings.size() == 4) { \/\/Built-in scripts have an :: in their name\n\t\t\t\t\titem.name = strings[3];\n\t\t\t\t\titem.script = strings[0] + \"::\" + strings[1];\n\t\t\t\t\titem.line = strings[2].to_int();\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\titem.name = \"SigErr \" + itos(signature);\n\t\t\t}\n\n\t\t\titem.calls = calls;\n\t\t\titem.self = self;\n\t\t\titem.total = total;\n\t\t\tfuncs.items.write[i] = item;\n\t\t}\n\n\t\tmetric.categories.push_back(funcs);\n\n\t\tif (p_msg == \"profile_frame\")\n\t\t\tprofiler->add_frame_metric(metric, false);\n\t\telse\n\t\t\tprofiler->add_frame_metric(metric, true);\n\t} else if (p_msg == \"network_profile\") {\n\t\tint frame_size = 6;\n\t\tfor (int i = 0; i < p_data.size(); i += frame_size) {\n\t\t\tMultiplayerAPI::ProfilingInfo pi;\n\t\t\tpi.node = p_data[i + 0];\n\t\t\tpi.node_path = p_data[i + 1];\n\t\t\tpi.incoming_rpc = p_data[i + 2];\n\t\t\tpi.incoming_rset = p_data[i + 3];\n\t\t\tpi.outgoing_rpc = p_data[i + 4];\n\t\t\tpi.outgoing_rset = p_data[i + 5];\n\t\t\tnetwork_profiler->add_node_frame_data(pi);\n\t\t}\n\t} else if (p_msg == \"network_bandwidth\") {\n\t\tnetwork_profiler->set_bandwidth(p_data[0], p_data[1]);\n\t} else if (p_msg == \"kill_me\") {\n\n\t\teditor->call_deferred(\"stop_child_process\");\n\t}\n}\n\nvoid ScriptEditorDebugger::_set_reason_text(const String &p_reason, MessageType p_type) {\n\tswitch (p_type) {\n\t\tcase MESSAGE_ERROR:\n\t\t\treason->add_color_override(\"font_color\", get_color(\"error_color\", \"Editor\"));\n\t\t\tbreak;\n\t\tcase MESSAGE_WARNING:\n\t\t\treason->add_color_override(\"font_color\", get_color(\"warning_color\", \"Editor\"));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treason->add_color_override(\"font_color\", get_color(\"success_color\", \"Editor\"));\n\t}\n\treason->set_text(p_reason);\n\treason->set_tooltip(p_reason.word_wrap(80));\n}\n\nvoid ScriptEditorDebugger::_performance_select() {\n\n\tperf_draw->update();\n}\n\nvoid ScriptEditorDebugger::_performance_draw() {\n\n\tVector<int> which;\n\tfor (int i = 0; i < perf_items.size(); i++) {\n\n\t\tif (perf_items[i]->is_checked(0))\n\t\t\twhich.push_back(i);\n\t}\n\n\tif (which.empty()) {\n\t\tinfo_message->show();\n\t\treturn;\n\t}\n\n\tinfo_message->hide();\n\n\tRef<StyleBox> graph_sb = get_stylebox(\"normal\", \"TextEdit\");\n\tRef<Font> graph_font = get_font(\"font\", \"TextEdit\");\n\n\tint cols = Math::ceil(Math::sqrt((float)which.size()));\n\tint rows = Math::ceil((float)which.size() \/ cols);\n\tif (which.size() == 1)\n\t\trows = 1;\n\n\tint margin = 3;\n\tint point_sep = 5;\n\tSize2i s = Size2i(perf_draw->get_size()) \/ Size2i(cols, rows);\n\tfor (int i = 0; i < which.size(); i++) {\n\n\t\tPoint2i p(i % cols, i \/ cols);\n\t\tRect2i r(p * s, s);\n\t\tr.position += Point2(margin, margin);\n\t\tr.size -= Point2(margin, margin) * 2.0;\n\t\tperf_draw->draw_style_box(graph_sb, r);\n\t\tr.position += graph_sb->get_offset();\n\t\tr.size -= graph_sb->get_minimum_size();\n\t\tint pi = which[i];\n\t\tColor c = get_color(\"accent_color\", \"Editor\");\n\t\tfloat h = (float)which[i] \/ (float)(perf_items.size());\n\t\t\/\/ Use a darker color on light backgrounds for better visibility\n\t\tfloat value_multiplier = EditorSettings::get_singleton()->is_dark_theme() ? 1.4 : 0.55;\n\t\tc.set_hsv(Math::fmod(h + 0.4, 0.9), c.get_s() * 0.9, c.get_v() * value_multiplier);\n\n\t\tc.a = 0.6;\n\t\tperf_draw->draw_string(graph_font, r.position + Point2(0, graph_font->get_ascent()), perf_items[pi]->get_text(0), c, r.size.x);\n\t\tc.a = 0.9;\n\t\tperf_draw->draw_string(graph_font, r.position + Point2(0, graph_font->get_ascent() + graph_font->get_height()), perf_items[pi]->get_text(1), c, r.size.y);\n\n\t\tfloat spacing = point_sep \/ float(cols);\n\t\tfloat from = r.size.width;\n\n\t\tList<Vector<float> >::Element *E = perf_history.front();\n\t\tfloat prev = -1;\n\t\twhile (from >= 0 && E) {\n\n\t\t\tfloat m = perf_max[pi];\n\t\t\tif (m == 0)\n\t\t\t\tm = 0.00001;\n\t\t\tfloat h2 = E->get()[pi] \/ m;\n\t\t\th2 = (1.0 - h2) * r.size.y;\n\n\t\t\tif (E != perf_history.front())\n\t\t\t\tperf_draw->draw_line(r.position + Point2(from, h2), r.position + Point2(from + spacing, prev), c, Math::round(EDSCALE));\n\t\t\tprev = h2;\n\t\t\tE = E->next();\n\t\t\tfrom -= spacing;\n\t\t}\n\t}\n}\n\nvoid ScriptEditorDebugger::_notification(int p_what) {\n\n\tswitch (p_what) {\n\n\t\tcase NOTIFICATION_ENTER_TREE: {\n\n\t\t\tinspector->edit(variables);\n\t\t\tskip_breakpoints->set_icon(get_icon(\"DebugSkipBreakpointsOff\", \"EditorIcons\"));\n\t\t\tcopy->set_icon(get_icon(\"ActionCopy\", \"EditorIcons\"));\n\n\t\t\tstep->set_icon(get_icon(\"DebugStep\", \"EditorIcons\"));\n\t\t\tnext->set_icon(get_icon(\"DebugNext\", \"EditorIcons\"));\n\t\t\tback->set_icon(get_icon(\"Back\", \"EditorIcons\"));\n\t\t\tforward->set_icon(get_icon(\"Forward\", \"EditorIcons\"));\n\t\t\tdobreak->set_icon(get_icon(\"Pause\", \"EditorIcons\"));\n\t\t\tdocontinue->set_icon(get_icon(\"DebugContinue\", \"EditorIcons\"));\n\t\t\tle_set->connect(\"pressed\", this, \"_live_edit_set\");\n\t\t\tle_clear->connect(\"pressed\", this, \"_live_edit_clear\");\n\t\t\terror_tree->connect(\"item_selected\", this, \"_error_selected\");\n\t\t\terror_tree->connect(\"item_activated\", this, \"_error_activated\");\n\t\t\tvmem_refresh->set_icon(get_icon(\"Reload\", \"EditorIcons\"));\n\n\t\t\treason->add_color_override(\"font_color\", get_color(\"error_color\", \"Editor\"));\n\n\t\t} break;\n\t\tcase NOTIFICATION_PROCESS: {\n\n\t\t\tif (connection.is_valid()) {\n\n\t\t\t\tinspect_scene_tree_timeout -= get_process_delta_time();\n\t\t\t\tif (inspect_scene_tree_timeout < 0) {\n\t\t\t\t\tinspect_scene_tree_timeout = EditorSettings::get_singleton()->get(\"debugger\/remote_scene_tree_refresh_interval\");\n\t\t\t\t\tif (inspect_scene_tree->is_visible_in_tree()) {\n\t\t\t\t\t\t_scene_tree_request();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tinspect_edited_object_timeout -= get_process_delta_time();\n\t\t\t\tif (inspect_edited_object_timeout < 0) {\n\t\t\t\t\tinspect_edited_object_timeout = EditorSettings::get_singleton()->get(\"debugger\/remote_inspect_refresh_interval\");\n\t\t\t\t\tif (inspected_object_id) {\n\t\t\t\t\t\tif (ScriptEditorDebuggerInspectedObject *obj = Object::cast_to<ScriptEditorDebuggerInspectedObject>(ObjectDB::get_instance(editor->get_editor_history()->get_current()))) {\n\t\t\t\t\t\t\tif (obj->remote_object_id == inspected_object_id) {\n\t\t\t\t\t\t\t\t\/\/take the chance and re-inspect selected object\n\t\t\t\t\t\t\t\tArray msg;\n\t\t\t\t\t\t\t\tmsg.push_back(\"inspect_object\");\n\t\t\t\t\t\t\t\tmsg.push_back(inspected_object_id);\n\t\t\t\t\t\t\t\tppeer->put_var(msg);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (camera_override == OVERRIDE_2D) {\n\t\t\t\t\tCanvasItemEditor *editor = CanvasItemEditor::get_singleton();\n\n\t\t\t\t\tDictionary state = editor->get_state();\n\t\t\t\t\tfloat zoom = state[\"zoom\"];\n\t\t\t\t\tPoint2 offset = state[\"ofs\"];\n\t\t\t\t\tTransform2D transform;\n\n\t\t\t\t\ttransform.scale_basis(Size2(zoom, zoom));\n\t\t\t\t\ttransform.elements[2] = -offset * zoom;\n\n\t\t\t\t\tArray msg;\n\t\t\t\t\tmsg.push_back(\"override_camera_2D:transform\");\n\t\t\t\t\tmsg.push_back(transform);\n\t\t\t\t\tppeer->put_var(msg);\n\n\t\t\t\t} else if (camera_override >= OVERRIDE_3D_1) {\n\t\t\t\t\tint viewport_idx = camera_override - OVERRIDE_3D_1;\n\t\t\t\t\tSpatialEditorViewport *viewport = SpatialEditor::get_singleton()->get_editor_viewport(viewport_idx);\n\t\t\t\t\tCamera *const cam = viewport->get_camera();\n\n\t\t\t\t\tArray msg;\n\t\t\t\t\tmsg.push_back(\"override_camera_3D:transform\");\n\t\t\t\t\tmsg.push_back(cam->get_camera_transform());\n\t\t\t\t\tif (cam->get_projection() == Camera::PROJECTION_ORTHOGONAL) {\n\t\t\t\t\t\tmsg.push_back(false);\n\t\t\t\t\t\tmsg.push_back(cam->get_size());\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmsg.push_back(true);\n\t\t\t\t\t\tmsg.push_back(cam->get_fov());\n\t\t\t\t\t}\n\t\t\t\t\tmsg.push_back(cam->get_znear());\n\t\t\t\t\tmsg.push_back(cam->get_zfar());\n\t\t\t\t\tppeer->put_var(msg);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (error_count != last_error_count || warning_count != last_warning_count) {\n\n\t\t\t\tif (error_count == 0 && warning_count == 0) {\n\t\t\t\t\terrors_tab->set_name(TTR(\"Errors\"));\n\t\t\t\t\tdebugger_button->set_text(TTR(\"Debugger\"));\n\t\t\t\t\tdebugger_button->set_icon(Ref<Texture2D>());\n\t\t\t\t\ttabs->set_tab_icon(errors_tab->get_index(), Ref<Texture2D>());\n\t\t\t\t} else {\n\t\t\t\t\terrors_tab->set_name(TTR(\"Errors\") + \" (\" + itos(error_count + warning_count) + \")\");\n\t\t\t\t\tdebugger_button->set_text(TTR(\"Debugger\") + \" (\" + itos(error_count + warning_count) + \")\");\n\t\t\t\t\tif (error_count == 0) {\n\t\t\t\t\t\tdebugger_button->set_icon(get_icon(\"Warning\", \"EditorIcons\"));\n\t\t\t\t\t\ttabs->set_tab_icon(errors_tab->get_index(), get_icon(\"Warning\", \"EditorIcons\"));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdebugger_button->set_icon(get_icon(\"Error\", \"EditorIcons\"));\n\t\t\t\t\t\ttabs->set_tab_icon(errors_tab->get_index(), get_icon(\"Error\", \"EditorIcons\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlast_error_count = error_count;\n\t\t\t\tlast_warning_count = warning_count;\n\t\t\t}\n\n\t\t\tif (server->is_connection_available()) {\n\t\t\t\tif (connection.is_valid()) {\n\t\t\t\t\t\/\/ We already have a valid connection. Disconnecting any new connecting client to prevent it from hanging.\n\t\t\t\t\t\/\/ (If we don't keep a reference to the connection it will be destroyed and disconnect_from_host will be called internally)\n\t\t\t\t\tserver->take_connection();\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ We just got the first connection.\n\t\t\t\t\tconnection = server->take_connection();\n\t\t\t\t\tif (connection.is_null())\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tEditorNode::get_log()->add_message(\"--- Debugging process started ---\", EditorLog::MSG_TYPE_EDITOR);\n\n\t\t\t\t\tppeer->set_stream_peer(connection);\n\n\t\t\t\t\t\/\/EditorNode::get_singleton()->make_bottom_panel_item_visible(this);\n\t\t\t\t\t\/\/emit_signal(\"show_debugger\",true);\n\n\t\t\t\t\tdobreak->set_disabled(false);\n\t\t\t\t\ttabs->set_current_tab(0);\n\n\t\t\t\t\t_set_reason_text(TTR(\"Child process connected.\"), MESSAGE_SUCCESS);\n\t\t\t\t\tprofiler->clear();\n\n\t\t\t\t\tinspect_scene_tree->clear();\n\t\t\t\t\tle_set->set_disabled(true);\n\t\t\t\t\tle_clear->set_disabled(false);\n\t\t\t\t\tvmem_refresh->set_disabled(false);\n\t\t\t\t\terror_tree->clear();\n\t\t\t\t\terror_count = 0;\n\t\t\t\t\twarning_count = 0;\n\t\t\t\t\tprofiler_signature.clear();\n\t\t\t\t\t\/\/live_edit_root->set_text(\"\/root\");\n\n\t\t\t\t\tEditorNode::get_singleton()->get_pause_button()->set_pressed(false);\n\t\t\t\t\tEditorNode::get_singleton()->get_pause_button()->set_disabled(false);\n\n\t\t\t\t\tupdate_live_edit_root();\n\t\t\t\t\tif (profiler->is_profiling()) {\n\t\t\t\t\t\t_profiler_activate(true);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (network_profiler->is_profiling()) {\n\t\t\t\t\t\t_network_profiler_activate(true);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (connection.is_null())\n\t\t\t\tbreak;\n\n\t\t\tif (!connection->is_connected_to_host()) {\n\t\t\t\tstop();\n\t\t\t\teditor->notify_child_process_exited(); \/\/somehow, exited\n\t\t\t\tbreak;\n\t\t\t};\n\n\t\t\tif (ppeer->get_available_packet_count() <= 0) {\n\t\t\t\tbreak;\n\t\t\t};\n\n\t\t\tconst uint64_t until = OS::get_singleton()->get_ticks_msec() + 20;\n\n\t\t\twhile (ppeer->get_available_packet_count() > 0) {\n\n\t\t\t\tif (pending_in_queue) {\n\n\t\t\t\t\tint todo = MIN(ppeer->get_available_packet_count(), pending_in_queue);\n\n\t\t\t\t\tfor (int i = 0; i < todo; i++) {\n\n\t\t\t\t\t\tVariant cmd;\n\t\t\t\t\t\tError ret = ppeer->get_var(cmd);\n\t\t\t\t\t\tif (ret != OK) {\n\t\t\t\t\t\t\tstop();\n\t\t\t\t\t\t\tERR_FAIL_COND(ret != OK);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tmessage.push_back(cmd);\n\t\t\t\t\t\tpending_in_queue--;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (pending_in_queue == 0) {\n\t\t\t\t\t\t_parse_message(message_type, message);\n\t\t\t\t\t\tmessage.clear();\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\tif (ppeer->get_available_packet_count() >= 2) {\n\n\t\t\t\t\t\tVariant cmd;\n\t\t\t\t\t\tError ret = ppeer->get_var(cmd);\n\t\t\t\t\t\tif (ret != OK) {\n\t\t\t\t\t\t\tstop();\n\t\t\t\t\t\t\tERR_FAIL_COND(ret != OK);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (cmd.get_type() != Variant::STRING) {\n\t\t\t\t\t\t\tstop();\n\t\t\t\t\t\t\tERR_FAIL_COND(cmd.get_type() != Variant::STRING);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tmessage_type = cmd;\n\n\t\t\t\t\t\tret = ppeer->get_var(cmd);\n\t\t\t\t\t\tif (ret != OK) {\n\t\t\t\t\t\t\tstop();\n\t\t\t\t\t\t\tERR_FAIL_COND(ret != OK);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (cmd.get_type() != Variant::INT) {\n\t\t\t\t\t\t\tstop();\n\t\t\t\t\t\t\tERR_FAIL_COND(cmd.get_type() != Variant::INT);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpending_in_queue = cmd;\n\n\t\t\t\t\t\tif (pending_in_queue == 0) {\n\t\t\t\t\t\t\t_parse_message(message_type, Array());\n\t\t\t\t\t\t\tmessage.clear();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (OS::get_singleton()->get_ticks_msec() > until)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} break;\n\t\tcase EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {\n\n\t\t\tadd_constant_override(\"margin_left\", -EditorNode::get_singleton()->get_gui_base()->get_stylebox(\"BottomPanelDebuggerOverride\", \"EditorStyles\")->get_margin(MARGIN_LEFT));\n\t\t\tadd_constant_override(\"margin_right\", -EditorNode::get_singleton()->get_gui_base()->get_stylebox(\"BottomPanelDebuggerOverride\", \"EditorStyles\")->get_margin(MARGIN_RIGHT));\n\n\t\t\ttabs->add_style_override(\"panel\", editor->get_gui_base()->get_stylebox(\"DebuggerPanel\", \"EditorStyles\"));\n\t\t\ttabs->add_style_override(\"tab_fg\", editor->get_gui_base()->get_stylebox(\"DebuggerTabFG\", \"EditorStyles\"));\n\t\t\ttabs->add_style_override(\"tab_bg\", editor->get_gui_base()->get_stylebox(\"DebuggerTabBG\", \"EditorStyles\"));\n\n\t\t\tcopy->set_icon(get_icon(\"ActionCopy\", \"EditorIcons\"));\n\t\t\tstep->set_icon(get_icon(\"DebugStep\", \"EditorIcons\"));\n\t\t\tnext->set_icon(get_icon(\"DebugNext\", \"EditorIcons\"));\n\t\t\tback->set_icon(get_icon(\"Back\", \"EditorIcons\"));\n\t\t\tforward->set_icon(get_icon(\"Forward\", \"EditorIcons\"));\n\t\t\tdobreak->set_icon(get_icon(\"Pause\", \"EditorIcons\"));\n\t\t\tdocontinue->set_icon(get_icon(\"DebugContinue\", \"EditorIcons\"));\n\t\t\tvmem_refresh->set_icon(get_icon(\"Reload\", \"EditorIcons\"));\n\t\t} break;\n\t}\n}\n\nvoid ScriptEditorDebugger::_clear_execution() {\n\tTreeItem *ti = stack_dump->get_selected();\n\tif (!ti)\n\t\treturn;\n\n\tDictionary d = ti->get_metadata(0);\n\n\tstack_script = ResourceLoader::load(d[\"file\"]);\n\temit_signal(\"clear_execution\", stack_script);\n\tstack_script.unref();\n}\n\nvoid ScriptEditorDebugger::start() {\n\n\tstop();\n\n\tif (is_visible_in_tree()) {\n\t\tEditorNode::get_singleton()->make_bottom_panel_item_visible(this);\n\t}\n\n\tperf_history.clear();\n\tfor (int i = 0; i < Performance::MONITOR_MAX; i++) {\n\n\t\tperf_max.write[i] = 0;\n\t}\n\n\tint remote_port = (int)EditorSettings::get_singleton()->get(\"network\/debug\/remote_port\");\n\tif (server->listen(remote_port) != OK) {\n\t\tEditorNode::get_log()->add_message(String(\"Error listening on port \") + itos(remote_port), EditorLog::MSG_TYPE_ERROR);\n\t\treturn;\n\t}\n\n\tEditorNode::get_singleton()->get_scene_tree_dock()->show_tab_buttons();\n\tauto_switch_remote_scene_tree = (bool)EditorSettings::get_singleton()->get(\"debugger\/auto_switch_to_remote_scene_tree\");\n\tif (auto_switch_remote_scene_tree) {\n\t\tEditorNode::get_singleton()->get_scene_tree_dock()->show_remote_tree();\n\t}\n\n\tset_process(true);\n\tbreaked = false;\n\tcamera_override = OVERRIDE_NONE;\n}\n\nvoid ScriptEditorDebugger::pause() {\n}\n\nvoid ScriptEditorDebugger::unpause() {\n}\n\nvoid ScriptEditorDebugger::stop() {\n\n\tset_process(false);\n\tbreaked = false;\n\t_clear_execution();\n\n\tserver->stop();\n\t_clear_remote_objects();\n\tppeer->set_stream_peer(Ref<StreamPeer>());\n\n\tif (connection.is_valid()) {\n\t\tEditorNode::get_log()->add_message(\"--- Debugging process stopped ---\", EditorLog::MSG_TYPE_EDITOR);\n\t\tconnection.unref();\n\n\t\treason->set_text(\"\");\n\t\treason->set_tooltip(\"\");\n\t}\n\n\tpending_in_queue = 0;\n\tmessage.clear();\n\n\tnode_path_cache.clear();\n\tres_path_cache.clear();\n\tprofiler_signature.clear();\n\tle_clear->set_disabled(false);\n\tle_set->set_disabled(true);\n\tprofiler->set_enabled(true);\n\tvmem_refresh->set_disabled(true);\n\n\tinspect_scene_tree->clear();\n\tinspector->edit(NULL);\n\tEditorNode::get_singleton()->get_pause_button()->set_pressed(false);\n\tEditorNode::get_singleton()->get_pause_button()->set_disabled(true);\n\tEditorNode::get_singleton()->get_scene_tree_dock()->hide_remote_tree();\n\tEditorNode::get_singleton()->get_scene_tree_dock()->hide_tab_buttons();\n\n\tif (hide_on_stop) {\n\t\tif (is_visible_in_tree())\n\t\t\tEditorNode::get_singleton()->hide_bottom_panel();\n\t\temit_signal(\"show_debugger\", false);\n\t}\n}\n\nvoid ScriptEditorDebugger::_profiler_activate(bool p_enable) {\n\n\tif (!connection.is_valid())\n\t\treturn;\n\n\tif (p_enable) {\n\t\tprofiler_signature.clear();\n\t\tArray msg;\n\t\tmsg.push_back(\"start_profiling\");\n\t\tint max_funcs = EditorSettings::get_singleton()->get(\"debugger\/profiler_frame_max_functions\");\n\t\tmax_funcs = CLAMP(max_funcs, 16, 512);\n\t\tmsg.push_back(max_funcs);\n\t\tppeer->put_var(msg);\n\t\tprint_verbose(\"Starting profiling.\");\n\n\t} else {\n\t\tArray msg;\n\t\tmsg.push_back(\"stop_profiling\");\n\t\tppeer->put_var(msg);\n\t\tprint_verbose(\"Ending profiling.\");\n\t}\n}\n\nvoid ScriptEditorDebugger::_visual_profiler_activate(bool p_enable) {\n\n\tif (!connection.is_valid())\n\t\treturn;\n\n\tif (p_enable) {\n\t\tprofiler_signature.clear();\n\t\tArray msg;\n\t\tmsg.push_back(\"start_visual_profiling\");\n\t\tppeer->put_var(msg);\n\t\tprint_verbose(\"Starting visual profiling.\");\n\n\t} else {\n\t\tArray msg;\n\t\tmsg.push_back(\"stop_visual_profiling\");\n\t\tppeer->put_var(msg);\n\t\tprint_verbose(\"Ending visual profiling.\");\n\t}\n}\n\nvoid ScriptEditorDebugger::_network_profiler_activate(bool p_enable) {\n\n\tif (!connection.is_valid())\n\t\treturn;\n\n\tif (p_enable) {\n\t\tprofiler_signature.clear();\n\t\tArray msg;\n\t\tmsg.push_back(\"start_network_profiling\");\n\t\tppeer->put_var(msg);\n\t\tprint_verbose(\"Starting network profiling.\");\n\n\t} else {\n\t\tArray msg;\n\t\tmsg.push_back(\"stop_network_profiling\");\n\t\tppeer->put_var(msg);\n\t\tprint_verbose(\"Ending network profiling.\");\n\t}\n}\n\nvoid ScriptEditorDebugger::_profiler_seeked() {\n\n\tif (!connection.is_valid() || !connection->is_connected_to_host())\n\t\treturn;\n\n\tif (breaked)\n\t\treturn;\n\tdebug_break();\n}\n\nvoid ScriptEditorDebugger::_stack_dump_frame_selected() {\n\n\tTreeItem *ti = stack_dump->get_selected();\n\tif (!ti)\n\t\treturn;\n\n\tDictionary d = ti->get_metadata(0);\n\n\tstack_script = ResourceLoader::load(d[\"file\"]);\n\temit_signal(\"goto_script_line\", stack_script, int(d[\"line\"]) - 1);\n\temit_signal(\"set_execution\", stack_script, int(d[\"line\"]) - 1);\n\tstack_script.unref();\n\n\tif (connection.is_valid() && connection->is_connected_to_host()) {\n\t\tArray msg;\n\t\tmsg.push_back(\"get_stack_frame_vars\");\n\t\tmsg.push_back(d[\"frame\"]);\n\t\tppeer->put_var(msg);\n\t} else {\n\t\tinspector->edit(NULL);\n\t}\n}\n\nvoid ScriptEditorDebugger::_output_clear() {\n\n\t\/\/output->clear();\n\t\/\/output->push_color(Color(0,0,0));\n}\n\nvoid ScriptEditorDebugger::_export_csv() {\n\n\tfile_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE);\n\tfile_dialog->set_access(EditorFileDialog::ACCESS_FILESYSTEM);\n\tfile_dialog_mode = SAVE_CSV;\n\tfile_dialog->popup_centered_ratio();\n}\n\nString ScriptEditorDebugger::get_var_value(const String &p_var) const {\n\tif (!breaked)\n\t\treturn String();\n\treturn variables->get_var_value(p_var);\n}\n\nint ScriptEditorDebugger::_get_node_path_cache(const NodePath &p_path) {\n\n\tconst int *r = node_path_cache.getptr(p_path);\n\tif (r)\n\t\treturn *r;\n\n\tlast_path_id++;\n\n\tnode_path_cache[p_path] = last_path_id;\n\tArray msg;\n\tmsg.push_back(\"live_node_path\");\n\tmsg.push_back(p_path);\n\tmsg.push_back(last_path_id);\n\tppeer->put_var(msg);\n\n\treturn last_path_id;\n}\n\nint ScriptEditorDebugger::_get_res_path_cache(const String &p_path) {\n\n\tMap<String, int>::Element *E = res_path_cache.find(p_path);\n\n\tif (E)\n\t\treturn E->get();\n\n\tlast_path_id++;\n\n\tres_path_cache[p_path] = last_path_id;\n\tArray msg;\n\tmsg.push_back(\"live_res_path\");\n\tmsg.push_back(p_path);\n\tmsg.push_back(last_path_id);\n\tppeer->put_var(msg);\n\n\treturn last_path_id;\n}\n\nvoid ScriptEditorDebugger::_method_changed(Object *p_base, const StringName &p_name, VARIANT_ARG_DECLARE) {\n\n\tif (!p_base || !live_debug || !connection.is_valid() || !editor->get_edited_scene())\n\t\treturn;\n\n\tNode *node = Object::cast_to<Node>(p_base);\n\n\tVARIANT_ARGPTRS\n\n\tfor (int i = 0; i < VARIANT_ARG_MAX; i++) {\n\t\t\/\/no pointers, sorry\n\t\tif (argptr[i] && (argptr[i]->get_type() == Variant::OBJECT || argptr[i]->get_type() == Variant::_RID))\n\t\t\treturn;\n\t}\n\n\tif (node) {\n\n\t\tNodePath path = editor->get_edited_scene()->get_path_to(node);\n\t\tint pathid = _get_node_path_cache(path);\n\n\t\tArray msg;\n\t\tmsg.push_back(\"live_node_call\");\n\t\tmsg.push_back(pathid);\n\t\tmsg.push_back(p_name);\n\t\tfor (int i = 0; i < VARIANT_ARG_MAX; i++) {\n\t\t\t\/\/no pointers, sorry\n\t\t\tmsg.push_back(*argptr[i]);\n\t\t}\n\t\tppeer->put_var(msg);\n\n\t\treturn;\n\t}\n\n\tResource *res = Object::cast_to<Resource>(p_base);\n\n\tif (res && res->get_path() != String()) {\n\n\t\tString respath = res->get_path();\n\t\tint pathid = _get_res_path_cache(respath);\n\n\t\tArray msg;\n\t\tmsg.push_back(\"live_res_call\");\n\t\tmsg.push_back(pathid);\n\t\tmsg.push_back(p_name);\n\t\tfor (int i = 0; i < VARIANT_ARG_MAX; i++) {\n\t\t\t\/\/no pointers, sorry\n\t\t\tmsg.push_back(*argptr[i]);\n\t\t}\n\t\tppeer->put_var(msg);\n\n\t\treturn;\n\t}\n}\n\nvoid ScriptEditorDebugger::_property_changed(Object *p_base, const StringName &p_property, const Variant &p_value) {\n\n\tif (!p_base || !live_debug || !connection.is_valid() || !editor->get_edited_scene())\n\t\treturn;\n\n\tNode *node = Object::cast_to<Node>(p_base);\n\n\tif (node) {\n\n\t\tNodePath path = editor->get_edited_scene()->get_path_to(node);\n\t\tint pathid = _get_node_path_cache(path);\n\n\t\tif (p_value.is_ref()) {\n\t\t\tRef<Resource> res = p_value;\n\t\t\tif (res.is_valid() && res->get_path() != String()) {\n\n\t\t\t\tArray msg;\n\t\t\t\tmsg.push_back(\"live_node_prop_res\");\n\t\t\t\tmsg.push_back(pathid);\n\t\t\t\tmsg.push_back(p_property);\n\t\t\t\tmsg.push_back(res->get_path());\n\t\t\t\tppeer->put_var(msg);\n\t\t\t}\n\t\t} else {\n\n\t\t\tArray msg;\n\t\t\tmsg.push_back(\"live_node_prop\");\n\t\t\tmsg.push_back(pathid);\n\t\t\tmsg.push_back(p_property);\n\t\t\tmsg.push_back(p_value);\n\t\t\tppeer->put_var(msg);\n\t\t}\n\n\t\treturn;\n\t}\n\n\tResource *res = Object::cast_to<Resource>(p_base);\n\n\tif (res && res->get_path() != String()) {\n\n\t\tString respath = res->get_path();\n\t\tint pathid = _get_res_path_cache(respath);\n\n\t\tif (p_value.is_ref()) {\n\t\t\tRef<Resource> res2 = p_value;\n\t\t\tif (res2.is_valid() && res2->get_path() != String()) {\n\n\t\t\t\tArray msg;\n\t\t\t\tmsg.push_back(\"live_res_prop_res\");\n\t\t\t\tmsg.push_back(pathid);\n\t\t\t\tmsg.push_back(p_property);\n\t\t\t\tmsg.push_back(res2->get_path());\n\t\t\t\tppeer->put_var(msg);\n\t\t\t}\n\t\t} else {\n\n\t\t\tArray msg;\n\t\t\tmsg.push_back(\"live_res_prop\");\n\t\t\tmsg.push_back(pathid);\n\t\t\tmsg.push_back(p_property);\n\t\t\tmsg.push_back(p_value);\n\t\t\tppeer->put_var(msg);\n\t\t}\n\n\t\treturn;\n\t}\n}\n\nvoid ScriptEditorDebugger::_method_changeds(void *p_ud, Object *p_base, const StringName &p_name, VARIANT_ARG_DECLARE) {\n\n\tScriptEditorDebugger *sed = (ScriptEditorDebugger *)p_ud;\n\tsed->_method_changed(p_base, p_name, VARIANT_ARG_PASS);\n}\n\nvoid ScriptEditorDebugger::_property_changeds(void *p_ud, Object *p_base, const StringName &p_property, const Variant &p_value) {\n\n\tScriptEditorDebugger *sed = (ScriptEditorDebugger *)p_ud;\n\tsed->_property_changed(p_base, p_property, p_value);\n}\n\nvoid ScriptEditorDebugger::set_live_debugging(bool p_enable) {\n\n\tlive_debug = p_enable;\n}\n\nvoid ScriptEditorDebugger::_live_edit_set() {\n\n\tif (!connection.is_valid())\n\t\treturn;\n\n\tTreeItem *ti = inspect_scene_tree->get_selected();\n\tif (!ti)\n\t\treturn;\n\tString path;\n\n\twhile (ti) {\n\t\tString lp = ti->get_text(0);\n\t\tpath = \"\/\" + lp + path;\n\t\tti = ti->get_parent();\n\t}\n\n\tNodePath np = path;\n\n\teditor->get_editor_data().set_edited_scene_live_edit_root(np);\n\n\tupdate_live_edit_root();\n}\n\nvoid ScriptEditorDebugger::_live_edit_clear() {\n\n\tNodePath np = NodePath(\"\/root\");\n\teditor->get_editor_data().set_edited_scene_live_edit_root(np);\n\n\tupdate_live_edit_root();\n}\n\nvoid ScriptEditorDebugger::update_live_edit_root() {\n\n\tNodePath np = editor->get_editor_data().get_edited_scene_live_edit_root();\n\n\tif (connection.is_valid()) {\n\t\tArray msg;\n\t\tmsg.push_back(\"live_set_root\");\n\t\tmsg.push_back(np);\n\t\tif (editor->get_edited_scene())\n\t\t\tmsg.push_back(editor->get_edited_scene()->get_filename());\n\t\telse\n\t\t\tmsg.push_back(\"\");\n\t\tppeer->put_var(msg);\n\t}\n\tlive_edit_root->set_text(np);\n}\n\nvoid ScriptEditorDebugger::live_debug_create_node(const NodePath &p_parent, const String &p_type, const String &p_name) {\n\n\tif (live_debug && connection.is_valid()) {\n\t\tArray msg;\n\t\tmsg.push_back(\"live_create_node\");\n\t\tmsg.push_back(p_parent);\n\t\tmsg.push_back(p_type);\n\t\tmsg.push_back(p_name);\n\t\tppeer->put_var(msg);\n\t}\n}\n\nvoid ScriptEditorDebugger::live_debug_instance_node(const NodePath &p_parent, const String &p_path, const String &p_name) {\n\n\tif (live_debug && connection.is_valid()) {\n\t\tArray msg;\n\t\tmsg.push_back(\"live_instance_node\");\n\t\tmsg.push_back(p_parent);\n\t\tmsg.push_back(p_path);\n\t\tmsg.push_back(p_name);\n\t\tppeer->put_var(msg);\n\t}\n}\nvoid ScriptEditorDebugger::live_debug_remove_node(const NodePath &p_at) {\n\n\tif (live_debug && connection.is_valid()) {\n\t\tArray msg;\n\t\tmsg.push_back(\"live_remove_node\");\n\t\tmsg.push_back(p_at);\n\t\tppeer->put_var(msg);\n\t}\n}\nvoid ScriptEditorDebugger::live_debug_remove_and_keep_node(const NodePath &p_at, ObjectID p_keep_id) {\n\n\tif (live_debug && connection.is_valid()) {\n\t\tArray msg;\n\t\tmsg.push_back(\"live_remove_and_keep_node\");\n\t\tmsg.push_back(p_at);\n\t\tmsg.push_back(p_keep_id);\n\t\tppeer->put_var(msg);\n\t}\n}\nvoid ScriptEditorDebugger::live_debug_restore_node(ObjectID p_id, const NodePath &p_at, int p_at_pos) {\n\n\tif (live_debug && connection.is_valid()) {\n\t\tArray msg;\n\t\tmsg.push_back(\"live_restore_node\");\n\t\tmsg.push_back(p_id);\n\t\tmsg.push_back(p_at);\n\t\tmsg.push_back(p_at_pos);\n\t\tppeer->put_var(msg);\n\t}\n}\nvoid ScriptEditorDebugger::live_debug_duplicate_node(const NodePath &p_at, const String &p_new_name) {\n\n\tif (live_debug && connection.is_valid()) {\n\t\tArray msg;\n\t\tmsg.push_back(\"live_duplicate_node\");\n\t\tmsg.push_back(p_at);\n\t\tmsg.push_back(p_new_name);\n\t\tppeer->put_var(msg);\n\t}\n}\nvoid ScriptEditorDebugger::live_debug_reparent_node(const NodePath &p_at, const NodePath &p_new_place, const String &p_new_name, int p_at_pos) {\n\n\tif (live_debug && connection.is_valid()) {\n\t\tArray msg;\n\t\tmsg.push_back(\"live_reparent_node\");\n\t\tmsg.push_back(p_at);\n\t\tmsg.push_back(p_new_place);\n\t\tmsg.push_back(p_new_name);\n\t\tmsg.push_back(p_at_pos);\n\t\tppeer->put_var(msg);\n\t}\n}\n\nScriptEditorDebugger::CameraOverride ScriptEditorDebugger::get_camera_override() const {\n\treturn camera_override;\n}\n\nvoid ScriptEditorDebugger::set_camera_override(CameraOverride p_override) {\n\n\tif (p_override == OVERRIDE_2D && camera_override != OVERRIDE_2D) {\n\t\tif (connection.is_valid()) {\n\t\t\tArray msg;\n\t\t\tmsg.push_back(\"override_camera_2D:set\");\n\t\t\tmsg.push_back(true);\n\t\t\tppeer->put_var(msg);\n\t\t}\n\t} else if (p_override != OVERRIDE_2D && camera_override == OVERRIDE_2D) {\n\t\tif (connection.is_valid()) {\n\t\t\tArray msg;\n\t\t\tmsg.push_back(\"override_camera_2D:set\");\n\t\t\tmsg.push_back(false);\n\t\t\tppeer->put_var(msg);\n\t\t}\n\t} else if (p_override >= OVERRIDE_3D_1 && camera_override < OVERRIDE_3D_1) {\n\t\tif (connection.is_valid()) {\n\t\t\tArray msg;\n\t\t\tmsg.push_back(\"override_camera_3D:set\");\n\t\t\tmsg.push_back(true);\n\t\t\tppeer->put_var(msg);\n\t\t}\n\t} else if (p_override < OVERRIDE_3D_1 && camera_override >= OVERRIDE_3D_1) {\n\t\tif (connection.is_valid()) {\n\t\t\tArray msg;\n\t\t\tmsg.push_back(\"override_camera_3D:set\");\n\t\t\tmsg.push_back(false);\n\t\t\tppeer->put_var(msg);\n\t\t}\n\t}\n\n\tcamera_override = p_override;\n}\n\nvoid ScriptEditorDebugger::set_breakpoint(const String &p_path, int p_line, bool p_enabled) {\n\n\tif (connection.is_valid()) {\n\t\tArray msg;\n\t\tmsg.push_back(\"breakpoint\");\n\t\tmsg.push_back(p_path);\n\t\tmsg.push_back(p_line);\n\t\tmsg.push_back(p_enabled);\n\t\tppeer->put_var(msg);\n\t}\n}\n\nvoid ScriptEditorDebugger::reload_scripts() {\n\n\tif (connection.is_valid()) {\n\t\tArray msg;\n\t\tmsg.push_back(\"reload_scripts\");\n\t\tppeer->put_var(msg);\n\t}\n}\n\nbool ScriptEditorDebugger::is_skip_breakpoints() {\n\treturn skip_breakpoints_value;\n}\n\nvoid ScriptEditorDebugger::_error_activated() {\n\tTreeItem *selected = error_tree->get_selected();\n\n\tTreeItem *ci = selected->get_children();\n\tif (ci) {\n\t\tselected->set_collapsed(!selected->is_collapsed());\n\t}\n}\n\nvoid ScriptEditorDebugger::_error_selected() {\n\tTreeItem *selected = error_tree->get_selected();\n\n\tArray meta = selected->get_metadata(0);\n\n\tif (meta.size() == 0) {\n\t\treturn;\n\t}\n\n\tRef<Script> s = ResourceLoader::load(meta[0]);\n\temit_signal(\"goto_script_line\", s, int(meta[1]) - 1);\n}\n\nvoid ScriptEditorDebugger::_expand_errors_list() {\n\n\tTreeItem *root = error_tree->get_root();\n\tif (!root)\n\t\treturn;\n\n\tTreeItem *item = root->get_children();\n\twhile (item) {\n\t\titem->set_collapsed(false);\n\t\titem = item->get_next();\n\t}\n}\n\nvoid ScriptEditorDebugger::_collapse_errors_list() {\n\n\tTreeItem *root = error_tree->get_root();\n\tif (!root)\n\t\treturn;\n\n\tTreeItem *item = root->get_children();\n\twhile (item) {\n\t\titem->set_collapsed(true);\n\t\titem = item->get_next();\n\t}\n}\n\nvoid ScriptEditorDebugger::set_hide_on_stop(bool p_hide) {\n\n\thide_on_stop = p_hide;\n}\n\nbool ScriptEditorDebugger::get_debug_with_external_editor() const {\n\n\treturn enable_external_editor;\n}\n\nvoid ScriptEditorDebugger::set_debug_with_external_editor(bool p_enabled) {\n\n\tenable_external_editor = p_enabled;\n}\n\nRef<Script> ScriptEditorDebugger::get_dump_stack_script() const {\n\n\treturn stack_script;\n}\n\nvoid ScriptEditorDebugger::_paused() {\n\n\tERR_FAIL_COND(connection.is_null());\n\tERR_FAIL_COND(!connection->is_connected_to_host());\n\n\tif (!breaked && EditorNode::get_singleton()->get_pause_button()->is_pressed()) {\n\t\tdebug_break();\n\t}\n\n\tif (breaked && !EditorNode::get_singleton()->get_pause_button()->is_pressed()) {\n\t\tdebug_continue();\n\t}\n}\n\nvoid ScriptEditorDebugger::_set_remote_object(ObjectID p_id, ScriptEditorDebuggerInspectedObject *p_obj) {\n\n\tif (remote_objects.has(p_id))\n\t\tmemdelete(remote_objects[p_id]);\n\tremote_objects[p_id] = p_obj;\n}\n\nvoid ScriptEditorDebugger::_clear_remote_objects() {\n\n\tfor (Map<ObjectID, ScriptEditorDebuggerInspectedObject *>::Element *E = remote_objects.front(); E; E = E->next()) {\n\t\tif (editor->get_editor_history()->get_current() == E->value()->get_instance_id()) {\n\t\t\teditor->push_item(NULL);\n\t\t}\n\t\tmemdelete(E->value());\n\t}\n\tremote_objects.clear();\n}\n\nvoid ScriptEditorDebugger::_clear_errors_list() {\n\n\terror_tree->clear();\n\terror_count = 0;\n\twarning_count = 0;\n\t_notification(NOTIFICATION_PROCESS);\n}\n\n\/\/ Right click on specific file(s) or folder(s).\nvoid ScriptEditorDebugger::_error_tree_item_rmb_selected(const Vector2 &p_pos) {\n\n\titem_menu->clear();\n\titem_menu->set_size(Size2(1, 1));\n\n\tif (error_tree->is_anything_selected()) {\n\t\titem_menu->add_icon_item(get_icon(\"ActionCopy\", \"EditorIcons\"), TTR(\"Copy Error\"), ITEM_MENU_COPY_ERROR);\n\t}\n\n\tif (item_menu->get_item_count() > 0) {\n\t\titem_menu->set_position(error_tree->get_global_position() + p_pos);\n\t\titem_menu->popup();\n\t}\n}\n\nvoid ScriptEditorDebugger::_item_menu_id_pressed(int p_option) {\n\n\tswitch (p_option) {\n\n\t\tcase ITEM_MENU_COPY_ERROR: {\n\t\t\tTreeItem *ti = error_tree->get_selected();\n\t\t\twhile (ti->get_parent() != error_tree->get_root())\n\t\t\t\tti = ti->get_parent();\n\n\t\t\tString type;\n\n\t\t\tif (ti->get_icon(0) == get_icon(\"Warning\", \"EditorIcons\")) {\n\t\t\t\ttype = \"W \";\n\t\t\t} else if (ti->get_icon(0) == get_icon(\"Error\", \"EditorIcons\")) {\n\t\t\t\ttype = \"E \";\n\t\t\t}\n\n\t\t\tString text = ti->get_text(0) + \"   \";\n\t\t\tint rpad_len = text.length();\n\n\t\t\ttext = type + text + ti->get_text(1) + \"\\n\";\n\t\t\tTreeItem *ci = ti->get_children();\n\t\t\twhile (ci) {\n\t\t\t\ttext += \"  \" + ci->get_text(0).rpad(rpad_len) + ci->get_text(1) + \"\\n\";\n\t\t\t\tci = ci->get_next();\n\t\t\t}\n\n\t\t\tOS::get_singleton()->set_clipboard(text);\n\n\t\t} break;\n\t\tcase ITEM_MENU_SAVE_REMOTE_NODE: {\n\n\t\t\tfile_dialog->set_access(EditorFileDialog::ACCESS_RESOURCES);\n\t\t\tfile_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE);\n\t\t\tfile_dialog_mode = SAVE_NODE;\n\n\t\t\tList<String> extensions;\n\t\t\tRef<PackedScene> sd = memnew(PackedScene);\n\t\t\tResourceSaver::get_recognized_extensions(sd, &extensions);\n\t\t\tfile_dialog->clear_filters();\n\t\t\tfor (int i = 0; i < extensions.size(); i++) {\n\t\t\t\tfile_dialog->add_filter(\"*.\" + extensions[i] + \" ; \" + extensions[i].to_upper());\n\t\t\t}\n\n\t\t\tfile_dialog->popup_centered_ratio();\n\t\t} break;\n\t\tcase ITEM_MENU_COPY_NODE_PATH: {\n\n\t\t\tTreeItem *ti = inspect_scene_tree->get_selected();\n\t\t\tString text = ti->get_text(0);\n\n\t\t\tif (ti->get_parent() == NULL) {\n\t\t\t\ttext = \".\";\n\t\t\t} else if (ti->get_parent()->get_parent() == NULL) {\n\t\t\t\ttext = \".\";\n\t\t\t} else {\n\t\t\t\twhile (ti->get_parent()->get_parent() != inspect_scene_tree->get_root()) {\n\t\t\t\t\tti = ti->get_parent();\n\t\t\t\t\ttext = ti->get_text(0) + \"\/\" + text;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tOS::get_singleton()->set_clipboard(text);\n\t\t} break;\n\t}\n}\n\nvoid ScriptEditorDebugger::_tab_changed(int p_tab) {\n\tif (tabs->get_tab_title(p_tab) == TTR(\"Video RAM\")) {\n\t\t\/\/ \"Video RAM\" tab was clicked, refresh the data it's dislaying when entering the tab.\n\t\t_video_mem_request();\n\t}\n}\n\nvoid ScriptEditorDebugger::_bind_methods() {\n\n\tClassDB::bind_method(D_METHOD(\"_stack_dump_frame_selected\"), &ScriptEditorDebugger::_stack_dump_frame_selected);\n\n\tClassDB::bind_method(D_METHOD(\"debug_skip_breakpoints\"), &ScriptEditorDebugger::debug_skip_breakpoints);\n\tClassDB::bind_method(D_METHOD(\"debug_copy\"), &ScriptEditorDebugger::debug_copy);\n\n\tClassDB::bind_method(D_METHOD(\"debug_next\"), &ScriptEditorDebugger::debug_next);\n\tClassDB::bind_method(D_METHOD(\"debug_step\"), &ScriptEditorDebugger::debug_step);\n\tClassDB::bind_method(D_METHOD(\"debug_break\"), &ScriptEditorDebugger::debug_break);\n\tClassDB::bind_method(D_METHOD(\"debug_continue\"), &ScriptEditorDebugger::debug_continue);\n\tClassDB::bind_method(D_METHOD(\"_output_clear\"), &ScriptEditorDebugger::_output_clear);\n\tClassDB::bind_method(D_METHOD(\"_export_csv\"), &ScriptEditorDebugger::_export_csv);\n\tClassDB::bind_method(D_METHOD(\"_performance_draw\"), &ScriptEditorDebugger::_performance_draw);\n\tClassDB::bind_method(D_METHOD(\"_performance_select\"), &ScriptEditorDebugger::_performance_select);\n\tClassDB::bind_method(D_METHOD(\"_scene_tree_request\"), &ScriptEditorDebugger::_scene_tree_request);\n\tClassDB::bind_method(D_METHOD(\"_video_mem_request\"), &ScriptEditorDebugger::_video_mem_request);\n\tClassDB::bind_method(D_METHOD(\"_live_edit_set\"), &ScriptEditorDebugger::_live_edit_set);\n\tClassDB::bind_method(D_METHOD(\"_live_edit_clear\"), &ScriptEditorDebugger::_live_edit_clear);\n\n\tClassDB::bind_method(D_METHOD(\"_error_selected\"), &ScriptEditorDebugger::_error_selected);\n\tClassDB::bind_method(D_METHOD(\"_error_activated\"), &ScriptEditorDebugger::_error_activated);\n\tClassDB::bind_method(D_METHOD(\"_expand_errors_list\"), &ScriptEditorDebugger::_expand_errors_list);\n\tClassDB::bind_method(D_METHOD(\"_collapse_errors_list\"), &ScriptEditorDebugger::_collapse_errors_list);\n\tClassDB::bind_method(D_METHOD(\"_profiler_activate\"), &ScriptEditorDebugger::_profiler_activate);\n\tClassDB::bind_method(D_METHOD(\"_visual_profiler_activate\"), &ScriptEditorDebugger::_visual_profiler_activate);\n\tClassDB::bind_method(D_METHOD(\"_network_profiler_activate\"), &ScriptEditorDebugger::_network_profiler_activate);\n\tClassDB::bind_method(D_METHOD(\"_profiler_seeked\"), &ScriptEditorDebugger::_profiler_seeked);\n\tClassDB::bind_method(D_METHOD(\"_clear_errors_list\"), &ScriptEditorDebugger::_clear_errors_list);\n\n\tClassDB::bind_method(D_METHOD(\"_error_tree_item_rmb_selected\"), &ScriptEditorDebugger::_error_tree_item_rmb_selected);\n\tClassDB::bind_method(D_METHOD(\"_item_menu_id_pressed\"), &ScriptEditorDebugger::_item_menu_id_pressed);\n\tClassDB::bind_method(D_METHOD(\"_tab_changed\"), &ScriptEditorDebugger::_tab_changed);\n\n\tClassDB::bind_method(D_METHOD(\"_paused\"), &ScriptEditorDebugger::_paused);\n\n\tClassDB::bind_method(D_METHOD(\"_scene_tree_selected\"), &ScriptEditorDebugger::_scene_tree_selected);\n\tClassDB::bind_method(D_METHOD(\"_scene_tree_folded\"), &ScriptEditorDebugger::_scene_tree_folded);\n\tClassDB::bind_method(D_METHOD(\"_scene_tree_rmb_selected\"), &ScriptEditorDebugger::_scene_tree_rmb_selected);\n\tClassDB::bind_method(D_METHOD(\"_file_selected\"), &ScriptEditorDebugger::_file_selected);\n\n\tClassDB::bind_method(D_METHOD(\"live_debug_create_node\"), &ScriptEditorDebugger::live_debug_create_node);\n\tClassDB::bind_method(D_METHOD(\"live_debug_instance_node\"), &ScriptEditorDebugger::live_debug_instance_node);\n\tClassDB::bind_method(D_METHOD(\"live_debug_remove_node\"), &ScriptEditorDebugger::live_debug_remove_node);\n\tClassDB::bind_method(D_METHOD(\"live_debug_remove_and_keep_node\"), &ScriptEditorDebugger::live_debug_remove_and_keep_node);\n\tClassDB::bind_method(D_METHOD(\"live_debug_restore_node\"), &ScriptEditorDebugger::live_debug_restore_node);\n\tClassDB::bind_method(D_METHOD(\"live_debug_duplicate_node\"), &ScriptEditorDebugger::live_debug_duplicate_node);\n\tClassDB::bind_method(D_METHOD(\"live_debug_reparent_node\"), &ScriptEditorDebugger::live_debug_reparent_node);\n\tClassDB::bind_method(D_METHOD(\"_scene_tree_property_select_object\"), &ScriptEditorDebugger::_scene_tree_property_select_object);\n\tClassDB::bind_method(D_METHOD(\"_scene_tree_property_value_edited\"), &ScriptEditorDebugger::_scene_tree_property_value_edited);\n\n\tADD_SIGNAL(MethodInfo(\"goto_script_line\"));\n\tADD_SIGNAL(MethodInfo(\"set_execution\", PropertyInfo(\"script\"), PropertyInfo(Variant::INT, \"line\")));\n\tADD_SIGNAL(MethodInfo(\"clear_execution\", PropertyInfo(\"script\")));\n\tADD_SIGNAL(MethodInfo(\"breaked\", PropertyInfo(Variant::BOOL, \"reallydid\"), PropertyInfo(Variant::BOOL, \"can_debug\")));\n\tADD_SIGNAL(MethodInfo(\"show_debugger\", PropertyInfo(Variant::BOOL, \"reallydid\")));\n}\n\nScriptEditorDebugger::ScriptEditorDebugger(EditorNode *p_editor) {\n\n\tadd_constant_override(\"margin_left\", -EditorNode::get_singleton()->get_gui_base()->get_stylebox(\"BottomPanelDebuggerOverride\", \"EditorStyles\")->get_margin(MARGIN_LEFT));\n\tadd_constant_override(\"margin_right\", -EditorNode::get_singleton()->get_gui_base()->get_stylebox(\"BottomPanelDebuggerOverride\", \"EditorStyles\")->get_margin(MARGIN_RIGHT));\n\n\tppeer = Ref<PacketPeerStream>(memnew(PacketPeerStream));\n\tppeer->set_input_buffer_max_size((1024 * 1024 * 8) - 4); \/\/ 8 MiB should be enough, minus 4 bytes for separator.\n\teditor = p_editor;\n\teditor->get_inspector()->connect(\"object_id_selected\", this, \"_scene_tree_property_select_object\");\n\n\ttabs = memnew(TabContainer);\n\ttabs->set_tab_align(TabContainer::ALIGN_LEFT);\n\ttabs->add_style_override(\"panel\", editor->get_gui_base()->get_stylebox(\"DebuggerPanel\", \"EditorStyles\"));\n\ttabs->add_style_override(\"tab_fg\", editor->get_gui_base()->get_stylebox(\"DebuggerTabFG\", \"EditorStyles\"));\n\ttabs->add_style_override(\"tab_bg\", editor->get_gui_base()->get_stylebox(\"DebuggerTabBG\", \"EditorStyles\"));\n\ttabs->connect(\"tab_changed\", this, \"_tab_changed\");\n\n\tadd_child(tabs);\n\n\t{ \/\/debugger\n\t\tVBoxContainer *vbc = memnew(VBoxContainer);\n\t\tvbc->set_name(TTR(\"Debugger\"));\n\t\tControl *dbg = vbc;\n\n\t\tHBoxContainer *hbc = memnew(HBoxContainer);\n\t\tvbc->add_child(hbc);\n\n\t\treason = memnew(Label);\n\t\treason->set_text(\"\");\n\t\thbc->add_child(reason);\n\t\treason->set_h_size_flags(SIZE_EXPAND_FILL);\n\t\treason->set_autowrap(true);\n\t\treason->set_max_lines_visible(3);\n\t\treason->set_mouse_filter(Control::MOUSE_FILTER_PASS);\n\n\t\thbc->add_child(memnew(VSeparator));\n\n\t\tskip_breakpoints = memnew(ToolButton);\n\t\thbc->add_child(skip_breakpoints);\n\t\tskip_breakpoints->set_tooltip(TTR(\"Skip Breakpoints\"));\n\t\tskip_breakpoints->connect(\"pressed\", this, \"debug_skip_breakpoints\");\n\n\t\thbc->add_child(memnew(VSeparator));\n\n\t\tcopy = memnew(ToolButton);\n\t\thbc->add_child(copy);\n\t\tcopy->set_tooltip(TTR(\"Copy Error\"));\n\t\tcopy->connect(\"pressed\", this, \"debug_copy\");\n\n\t\thbc->add_child(memnew(VSeparator));\n\n\t\tstep = memnew(ToolButton);\n\t\thbc->add_child(step);\n\t\tstep->set_tooltip(TTR(\"Step Into\"));\n\t\tstep->set_shortcut(ED_GET_SHORTCUT(\"debugger\/step_into\"));\n\t\tstep->connect(\"pressed\", this, \"debug_step\");\n\n\t\tnext = memnew(ToolButton);\n\t\thbc->add_child(next);\n\t\tnext->set_tooltip(TTR(\"Step Over\"));\n\t\tnext->set_shortcut(ED_GET_SHORTCUT(\"debugger\/step_over\"));\n\t\tnext->connect(\"pressed\", this, \"debug_next\");\n\n\t\thbc->add_child(memnew(VSeparator));\n\n\t\tdobreak = memnew(ToolButton);\n\t\thbc->add_child(dobreak);\n\t\tdobreak->set_tooltip(TTR(\"Break\"));\n\t\tdobreak->set_shortcut(ED_GET_SHORTCUT(\"debugger\/break\"));\n\t\tdobreak->connect(\"pressed\", this, \"debug_break\");\n\n\t\tdocontinue = memnew(ToolButton);\n\t\thbc->add_child(docontinue);\n\t\tdocontinue->set_tooltip(TTR(\"Continue\"));\n\t\tdocontinue->set_shortcut(ED_GET_SHORTCUT(\"debugger\/continue\"));\n\t\tdocontinue->connect(\"pressed\", this, \"debug_continue\");\n\n\t\tback = memnew(Button);\n\t\thbc->add_child(back);\n\t\tback->set_tooltip(TTR(\"Inspect Previous Instance\"));\n\t\tback->hide();\n\n\t\tforward = memnew(Button);\n\t\thbc->add_child(forward);\n\t\tforward->set_tooltip(TTR(\"Inspect Next Instance\"));\n\t\tforward->hide();\n\n\t\tHSplitContainer *sc = memnew(HSplitContainer);\n\t\tvbc->add_child(sc);\n\t\tsc->set_v_size_flags(SIZE_EXPAND_FILL);\n\n\t\tstack_dump = memnew(Tree);\n\t\tstack_dump->set_allow_reselect(true);\n\t\tstack_dump->set_columns(1);\n\t\tstack_dump->set_column_titles_visible(true);\n\t\tstack_dump->set_column_title(0, TTR(\"Stack Frames\"));\n\t\tstack_dump->set_h_size_flags(SIZE_EXPAND_FILL);\n\t\tstack_dump->set_hide_root(true);\n\t\tstack_dump->connect(\"cell_selected\", this, \"_stack_dump_frame_selected\");\n\t\tsc->add_child(stack_dump);\n\n\t\tinspector = memnew(EditorInspector);\n\t\tinspector->set_h_size_flags(SIZE_EXPAND_FILL);\n\t\tinspector->set_enable_capitalize_paths(false);\n\t\tinspector->set_read_only(true);\n\t\tinspector->connect(\"object_id_selected\", this, \"_scene_tree_property_select_object\");\n\t\tsc->add_child(inspector);\n\n\t\tserver.instance();\n\n\t\tpending_in_queue = 0;\n\n\t\tvariables = memnew(ScriptEditorDebuggerVariables);\n\n\t\tbreaked = false;\n\n\t\ttabs->add_child(dbg);\n\t}\n\n\t{ \/\/errors\n\t\terrors_tab = memnew(VBoxContainer);\n\t\terrors_tab->set_name(TTR(\"Errors\"));\n\n\t\tHBoxContainer *errhb = memnew(HBoxContainer);\n\t\terrors_tab->add_child(errhb);\n\n\t\tButton *expand_all = memnew(Button);\n\t\texpand_all->set_text(TTR(\"Expand All\"));\n\t\texpand_all->connect(\"pressed\", this, \"_expand_errors_list\");\n\t\terrhb->add_child(expand_all);\n\n\t\tButton *collapse_all = memnew(Button);\n\t\tcollapse_all->set_text(TTR(\"Collapse All\"));\n\t\tcollapse_all->connect(\"pressed\", this, \"_collapse_errors_list\");\n\t\terrhb->add_child(collapse_all);\n\n\t\tControl *space = memnew(Control);\n\t\tspace->set_h_size_flags(SIZE_EXPAND_FILL);\n\t\terrhb->add_child(space);\n\n\t\tclearbutton = memnew(Button);\n\t\tclearbutton->set_text(TTR(\"Clear\"));\n\t\tclearbutton->set_h_size_flags(0);\n\t\tclearbutton->connect(\"pressed\", this, \"_clear_errors_list\");\n\t\terrhb->add_child(clearbutton);\n\n\t\terror_tree = memnew(Tree);\n\t\terror_tree->set_columns(2);\n\n\t\terror_tree->set_column_expand(0, false);\n\t\terror_tree->set_column_min_width(0, 140);\n\n\t\terror_tree->set_column_expand(1, true);\n\n\t\terror_tree->set_select_mode(Tree::SELECT_ROW);\n\t\terror_tree->set_hide_root(true);\n\t\terror_tree->set_v_size_flags(SIZE_EXPAND_FILL);\n\t\terror_tree->set_allow_rmb_select(true);\n\t\terror_tree->connect(\"item_rmb_selected\", this, \"_error_tree_item_rmb_selected\");\n\t\terrors_tab->add_child(error_tree);\n\n\t\titem_menu = memnew(PopupMenu);\n\t\titem_menu->connect(\"id_pressed\", this, \"_item_menu_id_pressed\");\n\t\terror_tree->add_child(item_menu);\n\n\t\ttabs->add_child(errors_tab);\n\t}\n\n\t{ \/\/ remote scene tree\n\n\t\tinspect_scene_tree = memnew(Tree);\n\t\tEditorNode::get_singleton()->get_scene_tree_dock()->add_remote_tree_editor(inspect_scene_tree);\n\t\tEditorNode::get_singleton()->get_scene_tree_dock()->connect(\"remote_tree_selected\", this, \"_scene_tree_selected\");\n\t\tinspect_scene_tree->set_v_size_flags(SIZE_EXPAND_FILL);\n\t\tinspect_scene_tree->connect(\"cell_selected\", this, \"_scene_tree_selected\");\n\t\tinspect_scene_tree->connect(\"item_collapsed\", this, \"_scene_tree_folded\");\n\t\tinspect_scene_tree->set_allow_rmb_select(true);\n\t\tinspect_scene_tree->connect(\"item_rmb_selected\", this, \"_scene_tree_rmb_selected\");\n\t\tauto_switch_remote_scene_tree = EDITOR_DEF(\"debugger\/auto_switch_to_remote_scene_tree\", false);\n\t\tinspect_scene_tree_timeout = EDITOR_DEF(\"debugger\/remote_scene_tree_refresh_interval\", 1.0);\n\t\tinspect_edited_object_timeout = EDITOR_DEF(\"debugger\/remote_inspect_refresh_interval\", 0.2);\n\t\tinspected_object_id = 0;\n\t\tupdating_scene_tree = false;\n\t}\n\n\t{ \/\/ File dialog\n\t\tfile_dialog = memnew(EditorFileDialog);\n\t\tfile_dialog->connect(\"file_selected\", this, \"_file_selected\");\n\t\tadd_child(file_dialog);\n\t}\n\n\t{ \/\/profiler\n\t\tprofiler = memnew(EditorProfiler);\n\t\tprofiler->set_name(TTR(\"Profiler\"));\n\t\ttabs->add_child(profiler);\n\t\tprofiler->connect(\"enable_profiling\", this, \"_profiler_activate\");\n\t\tprofiler->connect(\"break_request\", this, \"_profiler_seeked\");\n\t}\n\n\t{ \/\/frame profiler\n\t\tvisual_profiler = memnew(EditorVisualProfiler);\n\t\tvisual_profiler->set_name(TTR(\"Visual Profiler\"));\n\t\ttabs->add_child(visual_profiler);\n\t\tvisual_profiler->connect(\"enable_profiling\", this, \"_visual_profiler_activate\");\n\t\tvisual_profiler->connect(\"break_request\", this, \"_profiler_seeked\");\n\t}\n\n\t{ \/\/network profiler\n\t\tnetwork_profiler = memnew(EditorNetworkProfiler);\n\t\tnetwork_profiler->set_name(TTR(\"Network Profiler\"));\n\t\ttabs->add_child(network_profiler);\n\t\tnetwork_profiler->connect(\"enable_profiling\", this, \"_network_profiler_activate\");\n\t\tnetwork_profiler->connect(\"break_request\", this, \"_profiler_seeked\");\n\t}\n\n\t{ \/\/monitors\n\n\t\tHSplitContainer *hsp = memnew(HSplitContainer);\n\n\t\tperf_monitors = memnew(Tree);\n\t\tperf_monitors->set_columns(2);\n\t\tperf_monitors->set_column_title(0, TTR(\"Monitor\"));\n\t\tperf_monitors->set_column_title(1, TTR(\"Value\"));\n\t\tperf_monitors->set_column_titles_visible(true);\n\t\tperf_monitors->connect(\"item_edited\", this, \"_performance_select\");\n\t\thsp->add_child(perf_monitors);\n\n\t\tperf_draw = memnew(Control);\n\t\tperf_draw->set_clip_contents(true);\n\t\tperf_draw->connect(\"draw\", this, \"_performance_draw\");\n\t\thsp->add_child(perf_draw);\n\n\t\thsp->set_name(TTR(\"Monitors\"));\n\t\thsp->set_split_offset(340 * EDSCALE);\n\t\ttabs->add_child(hsp);\n\t\tperf_max.resize(Performance::MONITOR_MAX);\n\n\t\tMap<String, TreeItem *> bases;\n\t\tTreeItem *root = perf_monitors->create_item();\n\t\tperf_monitors->set_hide_root(true);\n\t\tfor (int i = 0; i < Performance::MONITOR_MAX; i++) {\n\n\t\t\tString n = Performance::get_singleton()->get_monitor_name(Performance::Monitor(i));\n\t\t\tPerformance::MonitorType mtype = Performance::get_singleton()->get_monitor_type(Performance::Monitor(i));\n\t\t\tString base = n.get_slice(\"\/\", 0);\n\t\t\tString name = n.get_slice(\"\/\", 1);\n\t\t\tif (!bases.has(base)) {\n\t\t\t\tTreeItem *b = perf_monitors->create_item(root);\n\t\t\t\tb->set_text(0, base.capitalize());\n\t\t\t\tb->set_editable(0, false);\n\t\t\t\tb->set_selectable(0, false);\n\t\t\t\tb->set_expand_right(0, true);\n\t\t\t\tbases[base] = b;\n\t\t\t}\n\n\t\t\tTreeItem *it = perf_monitors->create_item(bases[base]);\n\t\t\tit->set_metadata(1, mtype);\n\t\t\tit->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);\n\t\t\tit->set_editable(0, true);\n\t\t\tit->set_selectable(0, false);\n\t\t\tit->set_selectable(1, false);\n\t\t\tit->set_text(0, name.capitalize());\n\t\t\tperf_items.push_back(it);\n\t\t\tperf_max.write[i] = 0;\n\t\t}\n\n\t\tinfo_message = memnew(Label);\n\t\tinfo_message->set_text(TTR(\"Pick one or more items from the list to display the graph.\"));\n\t\tinfo_message->set_valign(Label::VALIGN_CENTER);\n\t\tinfo_message->set_align(Label::ALIGN_CENTER);\n\t\tinfo_message->set_autowrap(true);\n\t\tinfo_message->set_custom_minimum_size(Size2(100 * EDSCALE, 0));\n\t\tinfo_message->set_anchors_and_margins_preset(PRESET_WIDE, PRESET_MODE_KEEP_SIZE, 8 * EDSCALE);\n\t\tperf_draw->add_child(info_message);\n\t}\n\n\t{ \/\/vmem inspect\n\t\tVBoxContainer *vmem_vb = memnew(VBoxContainer);\n\t\tHBoxContainer *vmem_hb = memnew(HBoxContainer);\n\t\tLabel *vmlb = memnew(Label(TTR(\"List of Video Memory Usage by Resource:\") + \" \"));\n\t\tvmlb->set_h_size_flags(SIZE_EXPAND_FILL);\n\t\tvmem_hb->add_child(vmlb);\n\t\tvmem_hb->add_child(memnew(Label(TTR(\"Total:\") + \" \")));\n\t\tvmem_total = memnew(LineEdit);\n\t\tvmem_total->set_editable(false);\n\t\tvmem_total->set_custom_minimum_size(Size2(100, 0) * EDSCALE);\n\t\tvmem_hb->add_child(vmem_total);\n\t\tvmem_refresh = memnew(ToolButton);\n\t\tvmem_refresh->set_disabled(true);\n\t\tvmem_hb->add_child(vmem_refresh);\n\t\tvmem_vb->add_child(vmem_hb);\n\t\tvmem_refresh->connect(\"pressed\", this, \"_video_mem_request\");\n\n\t\tVBoxContainer *vmmc = memnew(VBoxContainer);\n\t\tvmem_tree = memnew(Tree);\n\t\tvmem_tree->set_v_size_flags(SIZE_EXPAND_FILL);\n\t\tvmem_tree->set_h_size_flags(SIZE_EXPAND_FILL);\n\t\tvmmc->add_child(vmem_tree);\n\t\tvmmc->set_v_size_flags(SIZE_EXPAND_FILL);\n\t\tvmem_vb->add_child(vmmc);\n\n\t\tvmem_vb->set_name(TTR(\"Video RAM\"));\n\t\tvmem_tree->set_columns(4);\n\t\tvmem_tree->set_column_titles_visible(true);\n\t\tvmem_tree->set_column_title(0, TTR(\"Resource Path\"));\n\t\tvmem_tree->set_column_expand(0, true);\n\t\tvmem_tree->set_column_expand(1, false);\n\t\tvmem_tree->set_column_title(1, TTR(\"Type\"));\n\t\tvmem_tree->set_column_min_width(1, 100 * EDSCALE);\n\t\tvmem_tree->set_column_expand(2, false);\n\t\tvmem_tree->set_column_title(2, TTR(\"Format\"));\n\t\tvmem_tree->set_column_min_width(2, 150 * EDSCALE);\n\t\tvmem_tree->set_column_expand(3, false);\n\t\tvmem_tree->set_column_title(3, TTR(\"Usage\"));\n\t\tvmem_tree->set_column_min_width(3, 80 * EDSCALE);\n\t\tvmem_tree->set_hide_root(true);\n\n\t\ttabs->add_child(vmem_vb);\n\t}\n\n\t{ \/\/ misc\n\t\tVBoxContainer *misc = memnew(VBoxContainer);\n\t\tmisc->set_name(TTR(\"Misc\"));\n\t\ttabs->add_child(misc);\n\n\t\tGridContainer *info_left = memnew(GridContainer);\n\t\tinfo_left->set_columns(2);\n\t\tmisc->add_child(info_left);\n\t\tclicked_ctrl = memnew(LineEdit);\n\t\tclicked_ctrl->set_h_size_flags(SIZE_EXPAND_FILL);\n\t\tinfo_left->add_child(memnew(Label(TTR(\"Clicked Control:\"))));\n\t\tinfo_left->add_child(clicked_ctrl);\n\t\tclicked_ctrl_type = memnew(LineEdit);\n\t\tinfo_left->add_child(memnew(Label(TTR(\"Clicked Control Type:\"))));\n\t\tinfo_left->add_child(clicked_ctrl_type);\n\n\t\tlive_edit_root = memnew(LineEdit);\n\t\tlive_edit_root->set_h_size_flags(SIZE_EXPAND_FILL);\n\n\t\t{\n\t\t\tHBoxContainer *lehb = memnew(HBoxContainer);\n\t\t\tLabel *l = memnew(Label(TTR(\"Live Edit Root:\")));\n\t\t\tinfo_left->add_child(l);\n\t\t\tlehb->add_child(live_edit_root);\n\t\t\tle_set = memnew(Button(TTR(\"Set From Tree\")));\n\t\t\tlehb->add_child(le_set);\n\t\t\tle_clear = memnew(Button(TTR(\"Clear\")));\n\t\t\tlehb->add_child(le_clear);\n\t\t\tinfo_left->add_child(lehb);\n\t\t\tle_set->set_disabled(true);\n\t\t\tle_clear->set_disabled(true);\n\t\t}\n\n\t\tmisc->add_child(memnew(VSeparator));\n\n\t\tHBoxContainer *buttons = memnew(HBoxContainer);\n\n\t\texport_csv = memnew(Button(TTR(\"Export measures as CSV\")));\n\t\texport_csv->connect(\"pressed\", this, \"_export_csv\");\n\t\tbuttons->add_child(export_csv);\n\n\t\tmisc->add_child(buttons);\n\t}\n\n\tmsgdialog = memnew(AcceptDialog);\n\tadd_child(msgdialog);\n\n\tp_editor->get_undo_redo()->set_method_notify_callback(_method_changeds, this);\n\tp_editor->get_undo_redo()->set_property_notify_callback(_property_changeds, this);\n\tlive_debug = true;\n\tcamera_override = OVERRIDE_NONE;\n\tlast_path_id = false;\n\terror_count = 0;\n\twarning_count = 0;\n\thide_on_stop = true;\n\tenable_external_editor = false;\n\tlast_error_count = 0;\n\tlast_warning_count = 0;\n\n\tEditorNode::get_singleton()->get_pause_button()->connect(\"pressed\", this, \"_paused\");\n}\n\nScriptEditorDebugger::~ScriptEditorDebugger() {\n\n\tmemdelete(variables);\n\n\tppeer->set_stream_peer(Ref<StreamPeer>());\n\n\tserver->stop();\n\t_clear_remote_objects();\n}\n","avg_line_length":30.0822526862,"max_line_length":177,"alphanum_fraction":0.6948098335,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6900,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/* Copyright (C) 2014 InfiniDB, Inc.\n\n   This program is free software; you can redistribute it and\/or\n   modify it under the terms of the GNU General Public License\n   as published by the Free Software Foundation; version 2 of\n   the License.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n   MA 02110-1301, USA. *\/\n\n\/****************************************************************************\n* $Id: func_conv.cpp 3923 2013-06-19 21:43:06Z bwilkinson $\n*\n*\n****************************************************************************\/\n\n#include <cstdlib>\n#include <string>\n#include <unistd.h>\n#include <limits.h>\nusing namespace std;\n\n#include \"functor_str.h\"\n#include \"functioncolumn.h\"\nusing namespace execplan;\n\n#include \"rowgroup.h\"\nusing namespace rowgroup;\n\nnamespace\n{\nint64_t convStrToNum(const string& str, int base, bool unsignedFlag)\n{\n    int negative;\n    uint64_t cutoff, cutlim, i, j, save;\n    int overflow;\n\n    \/\/ to skip the leading spaces.\n    for (i = 0; i < str.length() && str.c_str()[i] == ' '; i++)\n    {}\n\n    if (i == str.length())\n    {\n        return 0L;\n    }\n\n    if (str.c_str()[i] == '-')\n    {\n        negative = 1;\n        ++i;\n    }\n    else if (str.c_str()[i] == '+')\n    {\n        negative = 0;\n        ++i;\n    }\n    else\n        negative = 0;\n\n    save = i;\n\n    cutoff = (~(uint64_t) 0) \/ (uint64_t) base;\n    cutlim = (uint32_t) ((~(uint64_t) 0) % (uint64_t) base);\n\n    overflow = 0;\n    j = 0;\n\n    for (; i < str.length(); i++)\n    {\n        unsigned char c = str.c_str()[i];\n\n        if (c >= '0' && c <= '9')\n            c -= '0';\n        else if (c >= 'A' && c <= 'Z')\n            c = c - 'A' + 10;\n        else if (c >= 'a' && c <= 'z')\n            c = c - 'a' + 10;\n        else\n            break;\n\n        if (c >= base)\n            break;\n\n        if (j > cutoff || (j == cutoff && c > cutlim))\n            overflow = 1;\n        else\n        {\n            j *= (uint64_t) base;\n            j += c;\n        }\n    }\n\n    if (i == save)\n        return 0L;\n\n    if (!unsignedFlag)\n    {\n        if (negative)\n        {\n            if (j  > (uint64_t) numeric_limits<int64_t>::min())\n                overflow = 1;\n        }\n        else if (j > (uint64_t) numeric_limits<int64_t>::max())\n        {\n            overflow = 1;\n        }\n    }\n\n    if (overflow)\n    {\n        if (unsignedFlag)\n            return (~(uint64_t) 0);\n\n        return negative ? numeric_limits<int64_t>::min() : numeric_limits<int64_t>::max();\n    }\n\n    return (negative ? -((int64_t) j) : (int64_t) j);\n}\n}\n\nnamespace funcexp\n{\nnamespace helpers\n{\nconst char* convNumToStr(int64_t val, char* dst, int radix)\n{\n    if (radix == 16 || radix == -16)\n        sprintf(dst, \"%llX\", (long long)val);\n\n    else if (radix == 8 || radix == -8)\n        sprintf(dst, \"%llo\", (long long)val);\n\n    else if (radix == 10)\n    {\n        sprintf(dst, \"%llu\", (unsigned long long)val);\n    }\n    else if (radix == -10)\n        sprintf(dst, \"%lld\", (long long)val);\n\n    else if (radix == 2 || radix == -2)\n    {\n        char tmp[65];\n        char* ptr = &tmp[64];\n        *ptr-- = 0;\n\n        for (int i = 0; i < 64; i++)\n        {\n            if (val & 1)\n                *ptr-- = '1';\n            else\n                *ptr-- = '0';\n\n            val >>= 1;\n        }\n\n        ptr = strchr(tmp, '1');\n\n        if (ptr == 0)\n            strcpy(dst, &tmp[63]);\n        else\n            strcpy(dst, ptr);\n    }\n    else if (radix == 4 || radix == -4)\n    {\n        char tmp[33];\n        char* ptr = &tmp[32];\n        *ptr-- = 0;\n\n        for (int i = 0; i < 32; i++)\n        {\n            *ptr-- = '0' + (val & 3);\n            val >>= 2;\n        }\n\n        ptr = strpbrk(tmp, \"123\");\n\n        if (ptr == 0)\n            strcpy(dst, &tmp[31]);\n        else\n            strcpy(dst, ptr);\n    }\n\n#if 0\n    else if (radix == 8 || radix == -8)\n    {\n        char tmp[23];\n        char* ptr = &tmp[22];\n        *ptr-- = 0;\n\n        for (int i = 0; i < 22; i++)\n        {\n            *ptr-- = '0' + (val & 7);\n            val >>= 3;\n        }\n\n        ptr = strpbrk(tmp, \"1234567\");\n\n        if (ptr == 0)\n            strcpy(dst, &tmp[21]);\n        else\n            strcpy(dst, ptr);\n    }\n    else if (radix == 16 || radix == -16)\n    {\n        char tmp[17];\n        char* ptr = &tmp[16];\n        *ptr-- = 0;\n\n        for (int i = 0; i < 16; i++)\n        {\n            int v = val & 0xf;\n\n            if (v > 9)\n                *ptr-- = 'A' + v - 10;\n            else\n                *ptr-- = '0' + v;\n\n            val >>= 4;\n        }\n\n        ptr = strpbrk(tmp, \"123456789ABCDEF\");\n\n        if (ptr == 0)\n            strcpy(dst, &tmp[15]);\n        else\n            strcpy(dst, ptr);\n    }\n\n#endif\n    else if (radix == 32 || radix == -32)\n    {\n        char tmp[14];\n        char* ptr = &tmp[13];\n        *ptr-- = 0;\n\n        for (int i = 0; i < 13; i++)\n        {\n            int v = val & 0x1f;\n\n            if (v > 9)\n                *ptr-- = 'A' + v - 10;\n            else\n                *ptr-- = '0' + v;\n\n            val >>= 5;\n        }\n\n        ptr = strpbrk(tmp, \"123456789ABCDEFGHIJKLMNOPQRSTUV\");\n\n        if (ptr == 0)\n            strcpy(dst, &tmp[12]);\n        else\n            strcpy(dst, ptr);\n    }\n    else\n        *dst = 0;\n\n    return dst;\n}\n} \/\/namespace funcexp::helpers\n\nCalpontSystemCatalog::ColType Func_conv::operationType(FunctionParm& fp, CalpontSystemCatalog::ColType& resultType)\n{\n    \/\/ operation type is not used by this functor\n    return fp[0]->data()->resultType();\n}\n\n\nstring Func_conv::getStrVal(rowgroup::Row& row,\n                            FunctionParm& parm,\n                            bool& isNull,\n                            CalpontSystemCatalog::ColType& op_ct)\n{\n    const string& res = parm[0]->data()->getStrVal(row, isNull);\n    string str;\n    char ans[65];\n    int64_t dec;\n    int64_t from_base = parm[1]->data()->getIntVal(row, isNull);\n    int64_t to_base = parm[2]->data()->getIntVal(row, isNull);\n\n    if (isNull || abs(static_cast<int>(to_base)) > 36 || abs(static_cast<int>(to_base)) < 2 ||\n            abs(static_cast<int>(from_base)) > 36 || abs(static_cast<int>(from_base)) < 2 || !(res.length()))\n    {\n        isNull = true;\n        return \"\";\n    }\n\n    if (from_base < 0)\n        dec = convStrToNum(res, -from_base, false);\n    else\n        dec = (int64_t) convStrToNum( res, from_base, true);\n\n    str = helpers::convNumToStr(dec, ans, to_base);\n\n    isNull = str.empty();\n\n    return str;\n}\n\n\n} \/\/ namespace funcexp\n\/\/ vim:ts=4 sw=4:\n","avg_line_length":22.2580645161,"max_line_length":115,"alphanum_fraction":0.46,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6398,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include \"manager.h\"\n\n#include \"settingsdialog.h\"\n\n#include <pb_decode.h>\n#include <pb_encode.h>\n#include <protocol\/messages\/sliderbar.pb.h>\n#include <protocol\/protocol_definition.h>\n\n#include \"serialinterface.h\"\n\n#include <QDebug>\n\nnamespace sliderbar {\n\nManager::Manager(QWidget* parent)\n    : m_parent(parent)\n{\n    m_pluginManager = new PluginManager;\n    m_settings      = new Settings(this);\n    m_dataInterface = new SerialInterface;\n\n    setTransmitter(m_dataInterface);\n    m_dataInterface->setReceiver(this);\n}\n\nvoid Manager::initialiseConnections()\n{\n    QObject::connect(m_dataInterface, &SerialInterface::connected,\n                     this, &Manager::handleConnected);\n    QObject::connect(m_dataInterface, &SerialInterface::disconnected,\n                     this, &Manager::handleDisconnected);\n\n    if (m_settings->autoconnect())\n        connect();\n}\n\nvoid Manager::connect()\n{\n    m_dataInterface->connect();\n}\n\nvoid Manager::disconnect()\n{\n    m_dataInterface->disconnect();\n}\n\nSettings* Manager::settings()\n{\n    return m_settings;\n}\n\nvoid Manager::managePlugins()\n{\n}\n\nvoid Manager::receive(uint8_t* buf, const uint16_t& len)\n{\n    m_dataBuffer.append(buf, len);\n\n    \/\/ Makes sure buffer contains at least 1 startflag & 1 endflag\n    if (!m_dataBuffer.contains(protocol::startflag) || !m_dataBuffer.contains(protocol::endflag)) {\n        m_dataBuffer.clear();\n        return;\n    }\n\n    \/\/ Makes sure buffer starts with the first startflag\n    m_dataBuffer.mid(m_dataBuffer.indexOf(protocol::startflag));\n\n    \/\/ Makes sure buffer ends with the last endflag\n    m_dataBuffer.resize(m_dataBuffer.lastIndexOf(protocol::endflag) + 1);\n\n    \/\/ Packet is complete -- remove startflag and endflag\n    \/\/ TODO: Assume that there are multiple command packets in one buffer: split\n    \/\/ the buffer with start\/end flags and process each buffer independantly.\n    m_dataBuffer.mid(1);\n    m_dataBuffer.chop(1);\n\n    \/\/ The buffer now contains:\n    \/\/ - message\n    \/\/ - crc\n\n    \/\/ Decode packet using nanopb:\n    Response decoded    = Response_init_zero;\n    pb_istream_t stream = pb_istream_from_buffer(m_dataBuffer.data(), m_dataBuffer.size() - 4);\n    bool status         = pb_decode(&stream, Response_fields, &decoded);\n\n    if (!status) {\n        m_dataBuffer.clear();\n        return;\n    }\n\n    process(decoded);\n\n    m_dataBuffer.clear();\n}\n\nbool Manager::transmit(uint8_t* buf, const uint16_t& len)\n{\n    if (!m_connected)\n        connect();\n    return transmitter->transmit(buf, len);\n}\n\nvoid Manager::transmit(const Request& request)\n{\n    uint8_t dataBuffer[64];\n    pb_ostream_t stream = pb_ostream_from_buffer(dataBuffer, sizeof(dataBuffer));\n\n    bool status = pb_encode(&stream, Request_fields, &request);\n\n    if (!status)\n        return;\n\n    const size_t message_length = stream.bytes_written;\n\n    \/\/ Create the data packet\n    uint8_t buf[6 + message_length];\n\n    \/\/ Append startflag\n    buf[0] = protocol::startflag;\n    \/\/ Append encoded message\n    memcpy(buf + 1, dataBuffer, message_length);\n    \/\/ Compute CRC32 over dataBuffer\n    uint32_t crc = 1;\n    \/\/ Append CRC32, from MSB to LSB\n    buf[message_length + 1] = (crc >> 24);\n    buf[message_length + 2] = (crc >> 16);\n    buf[message_length + 3] = (crc >> 8);\n    buf[message_length + 4] = (crc >> 0);\n    \/\/ Append endflag\n    buf[message_length + 5] = protocol::endflag;\n\n    \/\/ Send buffer\n    transmit(buf, 6 + message_length);\n}\n\nvoid Manager::setCalibration(const protocol::CalibrationData& data)\n{\n    \/\/ Create calibration request\n    Request calReq       = Request_init_zero;\n    calReq.which_payload = Request_calibration_tag;\n    calReq.ack           = true;\n\n    \/\/ Set SetCalibration request\n    calReq.payload.calibration.which_request           = Request_Calibration_set_tag;\n    calReq.payload.calibration.request.set.minPosition = data.minimumPosition;\n    calReq.payload.calibration.request.set.maxPosition = data.maximumPosition;\n    calReq.payload.calibration.request.set.minVelocity = data.minimumVelocity;\n    calReq.payload.calibration.request.set.maxVelocity = data.maximumVeloicty;\n\n    \/\/ Send request\n    transmit(calReq);\n}\n\nvoid Manager::requestCalibration()\n{\n    \/\/ Create calibration request\n    Request calReq       = Request_init_zero;\n    calReq.which_payload = Request_calibration_tag;\n    calReq.ack           = true;\n\n    \/\/ Set GetCalibration request\n    calReq.payload.calibration.which_request = Request_Calibration_get_tag;\n\n    \/\/ Send request\n    transmit(calReq);\n}\n\nvoid Manager::requestPing()\n{\n    \/\/ Create ping request\n    Request pingRequest       = Request_init_zero;\n    pingRequest.which_payload = Request_ping_tag;\n\n    \/\/ Send request\n    m_pingTime.start();\n    transmit(pingRequest);\n}\n\nvoid Manager::handleConnected()\n{\n    emit connected();\n    m_connected = true;\n}\n\nvoid Manager::handleDisconnected()\n{\n    emit disconnected();\n    m_connected = false;\n}\n\nQWidget* Manager::getParent()\n{\n    return m_parent;\n}\n\nbool Manager::isConnected()\n{\n    return m_connected;\n}\n\nstd::vector<Plugin*> Manager::getPlugins()\n{\n    return m_pluginManager->getPlugins();\n}\n\nvoid Manager::process(const Response& response)\n{\n    switch (response.which_payload) {\n    case Response_calibrationData_tag:\n        process(response.payload.calibrationData);\n        break;\n    case Response_value_tag:\n        process(response.payload.value);\n        break;\n\n    case Response_nack_tag: {\n    } break;\n    case Response_ping_tag: {\n        emit pingTime(m_pingTime.elapsed());\n    } break;\n\n    default:\n        break;\n    }\n}\n\nvoid Manager::process(const Response_CalibrationData& value)\n{\n    m_calibrationData.minimumPosition = value.minPosition;\n    m_calibrationData.maximumPosition = value.maxPosition;\n    m_calibrationData.minimumVelocity = value.minVelocity;\n    m_calibrationData.maximumVeloicty = value.maxVelocity;\n\n    emit calibrationData(m_calibrationData);\n}\n\nvoid Manager::process(const Response_Value& value)\n{\n    switch (value.which_parameter) {\n    case Response_Value_position_tag: {\n        \/\/ Got a new position\n        \/\/ Send the new position to the plugins\n        float position = 100.f * value.parameter.position \/ m_calibrationData.maximumPosition;\n        m_pluginManager->processPosition(position);\n    } break;\n    case Response_Value_velocity_tag:\n        \/\/ Got a new velocity\n        break;\n    }\n}\n\n} \/\/ namespace SliderBar\n","avg_line_length":25.0901960784,"max_line_length":99,"alphanum_fraction":0.6881838074,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6337,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":null,"content":"\/\/----------------------------------------------------------------------------\n\/\/\n\/\/ TSDuck - The MPEG Transport Stream Toolkit\n\/\/ Copyright (c) 2005-2020, Thierry Lelegard\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/    this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/    notice, this list of conditions and the following disclaimer in the\n\/\/    documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n\/\/ THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/----------------------------------------------------------------------------\n\n#include \"tsStreamEventDescriptor.h\"\n#include \"tsDescriptor.h\"\n#include \"tsTablesDisplay.h\"\n#include \"tsPSIRepository.h\"\n#include \"tsPSIBuffer.h\"\n#include \"tsDuckContext.h\"\n#include \"tsxmlElement.h\"\nTSDUCK_SOURCE;\n\n#define MY_XML_NAME u\"stream_event_descriptor\"\n#define MY_CLASS ts::StreamEventDescriptor\n#define MY_DID ts::DID_STREAM_EVENT\n#define MY_STD ts::Standards::MPEG\n\nTS_REGISTER_DESCRIPTOR(MY_CLASS, ts::EDID::Standard(MY_DID), MY_XML_NAME, MY_CLASS::DisplayDescriptor);\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Constructors\n\/\/----------------------------------------------------------------------------\n\nts::StreamEventDescriptor::StreamEventDescriptor(uint16_t id, uint64_t npt) :\n    AbstractDescriptor(MY_DID, MY_XML_NAME, MY_STD, 0),\n    event_id(id),\n    event_NPT(npt),\n    private_data()\n{\n}\n\nvoid ts::StreamEventDescriptor::clearContent()\n{\n    event_id = 0;\n    event_NPT = 0;\n    private_data.clear();\n}\n\nts::StreamEventDescriptor::StreamEventDescriptor(DuckContext& duck, const Descriptor& desc) :\n    StreamEventDescriptor()\n{\n    deserialize(duck, desc);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Serialization\n\/\/----------------------------------------------------------------------------\n\nvoid ts::StreamEventDescriptor::serializePayload(PSIBuffer& buf) const\n{\n    buf.putUInt16(event_id);\n    buf.putBits(0xFFFFFFFF, 31);\n    buf.putBits(event_NPT, 33);\n    buf.putBytes(private_data);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Deserialization\n\/\/----------------------------------------------------------------------------\n\nvoid ts::StreamEventDescriptor::deserializePayload(PSIBuffer& buf)\n{\n    event_id = buf.getUInt16();\n    buf.skipBits(31);\n    buf.getBits(event_NPT, 33);\n    buf.getBytes(private_data);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Check if all bytes in private part are ASCII characters.\n\/\/----------------------------------------------------------------------------\n\nbool ts::StreamEventDescriptor::asciiPrivate() const\n{\n    bool ascii = !private_data.empty();\n    for (size_t i = 0; ascii && i < private_data.size(); ++i) {\n        ascii = private_data[i] >= 0x20 && private_data[i] < 0x80;\n    }\n    return ascii;\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Static method to display a descriptor.\n\/\/----------------------------------------------------------------------------\n\nvoid ts::StreamEventDescriptor::DisplayDescriptor(TablesDisplay& disp, PSIBuffer& buf, const UString& margin, DID did, TID tid, PDS pds)\n{\n    if (buf.canReadBytes(10)) {\n        disp << margin << UString::Format(u\"Event id: 0x%X (%<d)\", {buf.getUInt16()});\n        buf.skipBits(31);\n        disp << UString::Format(u\", NPT: 0x%09X (%<d)\", {buf.getBits<uint64_t>(33)}) << std::endl;\n        disp.displayPrivateData(u\"Private data\", buf, NPOS, margin);\n    }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ XML serialization\n\/\/----------------------------------------------------------------------------\n\nvoid ts::StreamEventDescriptor::buildXML(DuckContext& duck, xml::Element* root) const\n{\n    root->setIntAttribute(u\"event_id\", event_id, true);\n    root->setIntAttribute(u\"event_NPT\", event_NPT, true);\n    if (!private_data.empty()) {\n        if (asciiPrivate()) {\n            root->addElement(u\"private_text\")->addText(UString::FromUTF8(reinterpret_cast<const char*>(private_data.data()), private_data.size()));\n        }\n        else {\n            root->addHexaTextChild(u\"private_data\", private_data);\n        }\n    }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ XML deserialization\n\/\/----------------------------------------------------------------------------\n\nbool ts::StreamEventDescriptor::analyzeXML(DuckContext& duck, const xml::Element* element)\n{\n    UString text;\n    bool ok =\n        element->getIntAttribute(event_id, u\"event_id\", true, 0, 0x0000, 0xFFFF) &&\n        element->getIntAttribute(event_NPT, u\"event_NPT\", true, 0, 0, TS_UCONST64(0x00000001FFFFFFFF)) &&\n        element->getHexaTextChild(private_data, u\"private_data\", false, 0, MAX_DESCRIPTOR_SIZE - 10) &&\n        element->getTextChild(text, u\"private_text\", false, false, UString(), 0, MAX_DESCRIPTOR_SIZE - 10);\n\n    if (ok && !text.empty()) {\n        if (private_data.empty()) {\n            private_data.appendUTF8(text);\n        }\n        else {\n            element->report().error(u\"In <%s> at line %d, <private_data> and <private_text> are mutually exclusive\", {element->name(), element->lineNumber()});\n        }\n    }\n    return ok;\n}\n","avg_line_length":37.2764705882,"max_line_length":159,"alphanum_fraction":0.5652516964,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6652,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Zlib"],"max_stars_count":2.0,"content":"\n#include \"libs.h\"\n\n#include <windows.h>\n\nint bcc_ver;\nint lnk_ver;\nint run_ver;\nint dbg_ver;\n\nstring home;\nLinker *linkerLib;\nRuntime *runtimeLib;\n\nModule *runtimeModule;\nEnviron *runtimeEnviron;\nvector<string> keyWords;\nvector<UserFunc> userFuncs;\n\nstatic HMODULE linkerHMOD,runtimeHMOD;\n\nstatic Type *typeof( int c ){\n\tswitch( c ){\n\tcase '%':return Type::int_type;\n\tcase '#':return Type::float_type;\n\tcase '$':return Type::string_type;\n\t}\n\treturn Type::void_type;\n}\n\nstatic int curr;\nstatic string text;\n\nstatic int next( istream &in ){\n\n\ttext=\"\";\n\n\tint t=0;\n\n\tfor(;;){\n\t\twhile( isspace( in.peek() ) ) in.get();\n\t\tif( in.eof() ) return curr=0;\n\t\tt=in.get();if( t!=';' ) break;\n\t\twhile( !in.eof() && in.get()!='\\n' ){}\n\t}\n\n\tif( isalpha(t) ){\n\t\ttext+=(char)t;\n\t\twhile( isalnum( in.peek() ) || in.peek()=='_' ) text+=(char)in.get();\n\t\treturn curr=-1;\n\t}\n\tif( t=='\\\"' ){\n\t\twhile( in.peek()!='\\\"' ) text=text+(char)in.get();\n\t\tin.get();\n\t\treturn curr=-2;\n\t}\n\n\treturn curr=t;\n}\n\nstatic const char *linkRuntime(){\n\n\twhile( const char *sym=runtimeLib->nextSym() ){\n\n\t\tstring s( sym );\n\n\t\tint pc=runtimeLib->symValue(sym);\n\n\t\t\/\/internal?\n\t\tif( s[0]=='_' ){\n\t\t\truntimeModule->addSymbol( (\"_\"+s).c_str(),pc );\n\t\t\tcontinue;\n\t\t}\n\n\t\tbool cfunc=false;\n\n\t\tif( s[0]=='!' ){\n\t\t\tcfunc=true;\n\t\t\ts=s.substr(1);\n\t\t}\n\n\t\tkeyWords.push_back( s );\n\n\t\t\/\/global!\n\t\tint start=0,end,k;\n\t\tType *t=Type::void_type;\n\t\tif( !isalpha( s[0] ) ){ start=1;t=typeof( s[0] ); }\n\t\tfor( k=1;k<s.size();++k ){\n\t\t\tif( !isalnum( s[k] ) && s[k]!='_' ) break;\n\t\t}\n\t\tend=k;\n\t\tDeclSeq *params=d_new DeclSeq();\n\t\tstring n=s.substr( start,end-start );\n\t\twhile( k<s.size() ){\n\t\t\tType *t=typeof(s[k++]);\n\t\t\tint from=k;\n\t\t\tfor( ;isalnum(s[k])||s[k]=='_';++k ){}\n\t\t\tstring str=s.substr( from,k-from );\n\t\t\tConstType *defType=0;\n\t\t\tif( s[k]=='=' ){\n\t\t\t\tint from=++k;\n\t\t\t\tif( s[k]=='\\\"' ){\n\t\t\t\t\tfor( ++k;s[k]!='\\\"';++k ){}\n\t\t\t\t\tstring t=s.substr( from+1,k-from-1 );\n\t\t\t\t\tdefType=d_new ConstType( t );++k;\n\t\t\t\t}else{\n\t\t\t\t\tif( s[k]=='-' ) ++k;\n\t\t\t\t\tfor( ;isdigit( s[k] );++k ){}\n\t\t\t\t\tif( t==Type::int_type ){\n\t\t\t\t\t\tint n=atoi( s.substr( from,k-from ) );\n\t\t\t\t\t\tdefType=d_new ConstType( n );\n\t\t\t\t\t}else{\n\t\t\t\t\t\tfloat n=atof( s.substr( from,k-from ) );\n\t\t\t\t\t\tdefType=d_new ConstType( n );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tDecl *d=params->insertDecl( str,t,DECL_PARAM,defType );\n\t\t}\n\n\t\tFuncType *f=d_new FuncType( t,params,false,cfunc );\n\t\tn=tolower(n);\n\t\truntimeEnviron->funcDecls->insertDecl( n,f,DECL_FUNC );\n\t\truntimeModule->addSymbol( (\"_f\"+n).c_str(),pc );\n\t}\n\treturn 0;\n}\n\nstatic set<string> _ulibkws;\n\nstatic const char *loadUserLib( const string &userlib ){\n\n\tstring t=home+\"\/userlibs\/\"+userlib;\n\n\tstring lib=\"\";\n\tifstream in(t.c_str());\n\n\tnext(in);\n\twhile( curr ){\n\n\t\tif( curr=='.' ){\n\n\t\t\tif( next(in)!=-1 ) return \"expecting identifier after '.'\";\n\n\t\t\tif( text==\"lib\" ){\n\t\t\t\tif( next(in)!=-2 ) return \"expecting string after lib directive\";\n\t\t\t\tlib=text;\n\n\t\t\t}else{\n\t\t\t\treturn \"unknown decl directive\";\n\t\t\t}\n\t\t\tnext( in );\n\n\t\t}else if( curr==-1 ){\n\n\t\t\tif( !lib.size() ) return \"function decl without lib directive\";\n\n\t\t\tstring id=text;\n\t\t\tstring lower_id=tolower(id);\n\n\t\t\tif( _ulibkws.count( lower_id ) ) return \"duplicate identifier\";\n\t\t\t_ulibkws.insert( lower_id );\n\n\t\t\tType *ty=0;\n\t\t\tswitch( next(in) ){\n\t\t\tcase '%':ty=Type::int_type;break;\n\t\t\tcase '#':ty=Type::float_type;break;\n\t\t\tcase '$':ty=Type::string_type;break;\n\t\t\t}\n\t\t\tif( ty ) next(in);\n\t\t\telse ty=Type::void_type;\n\n\t\t\tDeclSeq *params=d_new DeclSeq();\n\n\t\t\tif( curr!='(' ) return \"expecting '(' after function identifier\";\n\t\t\tnext(in);\n\t\t\tif( curr!=')' ){\n\t\t\t\tfor(;;){\n\t\t\t\t\tif( curr!=-1 ) break;\n\t\t\t\t\tstring arg=text;\n\n\t\t\t\t\tType *ty=0;\n\t\t\t\t\tswitch( next(in) ){\n\t\t\t\t\tcase '%':ty=Type::int_type;break;\n\t\t\t\t\tcase '#':ty=Type::float_type;break;\n\t\t\t\t\tcase '$':ty=Type::string_type;break;\n\t\t\t\t\tcase '*':ty=Type::null_type;break;\n\t\t\t\t\t}\n\t\t\t\t\tif( ty ) next(in);\n\t\t\t\t\telse ty=Type::int_type;\n\n\t\t\t\t\tConstType *defType=0;\n\n\t\t\t\t\tDecl *d=params->insertDecl( arg,ty,DECL_PARAM,defType );\n\n\t\t\t\t\tif( curr!=',' ) break;\n\t\t\t\t\tnext(in);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif( curr!=')' ) return \"expecting ')' after function decl\";\n\n\t\t\tkeyWords.push_back( id );\n\n\t\t\tFuncType *fn=d_new FuncType( ty,params,true,true );\n\n\t\t\truntimeEnviron->funcDecls->insertDecl( lower_id,fn,DECL_FUNC );\n\n\t\t\tif( next(in)==':' ){\t\/\/real name?\n\t\t\t\tnext(in);\n\t\t\t\tif( curr!=-1 && curr!=-2 ) return \"expecting identifier or string after alias\";\n\t\t\t\tid=text;\n\t\t\t\tnext(in);\n\t\t\t}\n\n\t\t\tuserFuncs.push_back( UserFunc( lower_id,id,lib ) );\n\t\t}\n\t}\n\treturn 0;\n}\n\nstatic const char *linkUserLibs(){\n\n\t_ulibkws.clear();\n\n\tWIN32_FIND_DATA fd;\n\n\tHANDLE h=FindFirstFile( (home+\"\/userlibs\/*.decls\").c_str(),&fd );\n\n\tif( h==INVALID_HANDLE_VALUE ) return 0;\n\n\tconst char *err=0;\n\n\tdo{\n\t\tif( err=loadUserLib( fd.cFileName ) ){\n\t\t\tstatic char buf[64];\n\t\t\tsprintf( buf,\"Error in userlib '%s' - %s\",fd.cFileName,err );\n\t\t\terr=buf;break;\n\t\t}\n\n\t}while( FindNextFile( h,&fd ) );\n\n\tFindClose( h );\n\n\t_ulibkws.clear();\n\n\treturn err;\n}\n\nconst char *openLibs(){\n\t\n\tchar *p=getenv( \"blitzpath\" );\n\tif (!p) {\n\t\tchar workingDir[128];\n\t\tGetCurrentDirectory(128, workingDir);\n\t\thome = workingDir; home+=\"\\\\\\\\..\";\n\t\tputenv( (string(\"blitzpath=\")+home).c_str() );\n\t} else {\n\t\thome=string(p);\n\t}\n\n\tlinkerHMOD=LoadLibrary( (home+\"\/bin\/linker.dll\").c_str() );\n\tif( !linkerHMOD ) return \"Unable to open linker.dll\";\n\n\ttypedef Linker *(_cdecl*GetLinker)();\n\tGetLinker gl=(GetLinker)GetProcAddress( linkerHMOD,\"linkerGetLinker\" );\n\tif( !gl ) return \"Error in linker.dll\";\n\tlinkerLib=gl();\n\n\truntimeHMOD=LoadLibrary( (home+\"\/bin\/runtime.dll\").c_str() );\n\tif( !runtimeHMOD ) return \"Unable to open runtime.dll\";\n\n\ttypedef Runtime *(_cdecl*GetRuntime)();\n\tGetRuntime gr=(GetRuntime)GetProcAddress( runtimeHMOD,\"runtimeGetRuntime\" );\n\tif( !gr ) return \"Error in runtime.dll\";\n\truntimeLib=gr();\n\n\tbcc_ver=VERSION;\n\tlnk_ver=linkerLib->version();\n\trun_ver=runtimeLib->version();\n\n\tif( (lnk_ver>>16)!=(bcc_ver>>16) ||\n\t\t(run_ver>>16)!=(bcc_ver>>16) ||\n\t\t(lnk_ver>>16)!=(bcc_ver>>16) ) return \"Library version error\";\n\n\truntimeLib->startup( GetModuleHandle(0) );\n\n\truntimeModule=linkerLib->createModule();\n\truntimeEnviron=d_new Environ( \"\",Type::int_type,0,0 );\n\n\tkeyWords.clear();\n\tuserFuncs.clear();\n\n\treturn 0;\n}\n\nconst char *linkLibs(){\n\n\tif( const char *p=linkRuntime() ) return p;\n\n\tif( const char *p=linkUserLibs() ) return p;\n\n\treturn 0;\n}\n\nvoid closeLibs(){\n\n\tdelete runtimeEnviron;\n\tif( linkerLib ) linkerLib->deleteModule( runtimeModule );\n\tif( runtimeLib ) runtimeLib->shutdown();\n\tif( runtimeHMOD ) FreeLibrary( runtimeHMOD );\n\tif( linkerHMOD ) FreeLibrary( linkerHMOD );\n\n\truntimeEnviron=0;\n\tlinkerLib=0;\n\truntimeLib=0;\n\truntimeHMOD=0;\n\tlinkerHMOD=0;\n}\n","avg_line_length":20.8526645768,"max_line_length":83,"alphanum_fraction":0.6115453999,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1261,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\n\/*\nInputs:\n-Number of test cases\n-Number of non-empty plates\n-Space seperated customers with pancake amounts\nOutputs:\nCase #x: y\nwhere x is the test case and y is the number of minutes to eat all the pancakes (including moving them time).\n*\/\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n\tunsigned int testCases = 0;\n\tcin >> testCases;\n\n\tvector<unsigned int> time;\n\n\tfor (unsigned int tc = 0; tc < testCases; tc += 1)\n\t{\n\t\tunsigned int filledPlates = 0;\n\t\tcin >> filledPlates;\n\n\t\tvector<unsigned int> pancakes;\n\n\t\tfor (unsigned int plates = 0; plates < filledPlates; plates += 1)\n\t\t{\n\t\t\tunsigned int pancake = 0;\n\t\t\tcin >> pancake;\n\n\t\t\tpancakes.push_back(pancake);\n\t\t}\n\n\t\tconst unsigned int maxPancakes = *max_element(pancakes.begin(), pancakes.end());\n\t\tunsigned int totalTime = maxPancakes;\n\n\t\tfor (unsigned int x = 1; x < maxPancakes; x += 1)\n\t\t{\n\t\t\tunsigned int totalMoves = 0;\n\n\t\t\tfor (const int pancake : pancakes)\n\t\t\t{\n\t\t\t\ttotalMoves += (pancake - 1) \/ x;\n\t\t\t}\n\t\t\ttotalTime = min(totalTime, totalMoves + x);\n\t\t}\n\n\t\ttime.push_back(totalTime);\n\t}\n\tfor (unsigned int tc = 0; tc < testCases; tc += 1)\n\t{\n\t\tcout << \"Case #\" << tc + 1 << \": \" << time[tc] << endl;\n\t}\n}\n\n","avg_line_length":20.3387096774,"max_line_length":109,"alphanum_fraction":0.6534496431,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":20183,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n * YoloObjectDetector.cpp\n *\n *  Created on: Dec 19, 2016\n *      Author: Marko Bjelonic\n *   Institute: ETH Zurich, Robotic Systems Lab\n *\/\n\n\/\/ yolo object detector\n#include \"darknet_ros\/YoloObjectDetector.hpp\"\n\n\/\/ Check for xServer\n#include <X11\/Xlib.h>\n\n#ifdef DARKNET_FILE_PATH\nstd::string darknetFilePath_ = DARKNET_FILE_PATH;\n#else\n#error Path of darknet repository is not defined in CMakeLists.txt.\n#endif\n\n\nvoid get_image_cv(image p, IplImage *disp)\n{\n  int x,y,k;\n  if(p.c == 3) rgbgr_image(p);\n  char buff[256];\n  int step = disp->widthStep;\n  for(y = 0; y < p.h; ++y){\n    for(x = 0; x < p.w; ++x){\n      for(k= 0; k < p.c; ++k){\n        disp->imageData[y*step + x*p.c + k] = (unsigned char)(p.data[k*p.h*p.w + y*p.w + x]*255);\n      }\n    }\n  }\n}\n\nnamespace darknet_ros {\n\nchar *cfg;\nchar *weights;\nchar *data;\nchar **detectionNames;\n\nYoloObjectDetector::YoloObjectDetector(ros::NodeHandle nh)\n    : nodeHandle_(nh),\n      imageTransport_(nodeHandle_),\n      numClasses_(0),\n      classLabels_(0),\n      rosBoxes_(0),\n      rosBoxCounter_(0)\n{\n  ROS_INFO(\"[YoloObjectDetector] Node started.\");\n\n  \/\/ Read parameters from config file.\n  if (!readParameters()) {\n    ros::requestShutdown();\n  }\n\n  init();\n}\n\nYoloObjectDetector::~YoloObjectDetector()\n{\n  {\n    boost::unique_lock<boost::shared_mutex> lockNodeStatus(mutexNodeStatus_);\n    isNodeRunning_ = false;\n  }\n  yoloThread_.join();\n}\n\nbool YoloObjectDetector::readParameters()\n{\n  \/\/ Load common parameters.\n  nodeHandle_.param(\"image_view\/enable_opencv\", viewImage_, true);\n  nodeHandle_.param(\"image_view\/wait_key_delay\", waitKeyDelay_, 3);\n  nodeHandle_.param(\"image_view\/enable_console_output\", enableConsoleOutput_, false);\n\n  \/\/ Check if Xserver is running on Linux.\n  if (XOpenDisplay(NULL)) {\n    \/\/ Do nothing!\n    ROS_INFO(\"[YoloObjectDetector] Xserver is running.\");\n  } else {\n    ROS_INFO(\"[YoloObjectDetector] Xserver is not running.\");\n    viewImage_ = false;\n  }\n\n  \/\/ Set vector sizes.\n  nodeHandle_.param(\"yolo_model\/detection_classes\/names\", classLabels_,\n                    std::vector<std::string>(0));\n  numClasses_ = classLabels_.size();\n  rosBoxes_ = std::vector<std::vector<RosBox_> >(numClasses_);\n  rosBoxCounter_ = std::vector<int>(numClasses_);\n\n  return true;\n}\n\nvoid YoloObjectDetector::init()\n{\n  ROS_INFO(\"[YoloObjectDetector] init().\");\n\n  \/\/ Initialize deep network of darknet.\n  std::string weightsPath;\n  std::string configPath;\n  std::string dataPath;\n  std::string configModel;\n  std::string weightsModel;\n\n  \/\/ Threshold of object detection.\n  float thresh;\n  nodeHandle_.param(\"yolo_model\/threshold\/value\", thresh, (float) 0.3);\n\n  \/\/ Path to weights file.\n  nodeHandle_.param(\"yolo_model\/weight_file\/name\", weightsModel, std::string(\"yolov2-tiny.weights\"));\n  nodeHandle_.param(\"weights_path\", weightsPath, std::string(\"\/default\"));\n  weightsPath += \"\/\" + weightsModel;\n  weights = new char[weightsPath.length() + 1];\n  strcpy(weights, weightsPath.c_str());\n\n  \/\/ Path to config file.\n  nodeHandle_.param(\"yolo_model\/config_file\/name\", configModel, std::string(\"yolov2-tiny.cfg\"));\n  nodeHandle_.param(\"config_path\", configPath, std::string(\"\/default\"));\n  configPath += \"\/\" + configModel;\n  cfg = new char[configPath.length() + 1];\n  strcpy(cfg, configPath.c_str());\n\n  \/\/ Path to data folder.\n  dataPath = darknetFilePath_;\n  dataPath += \"\/data\";\n  data = new char[dataPath.length() + 1];\n  strcpy(data, dataPath.c_str());\n\n  \/\/ Get classes.\n  detectionNames = (char**) realloc((void*) detectionNames, (numClasses_ + 1) * sizeof(char*));\n  for (int i = 0; i < numClasses_; i++) {\n    detectionNames[i] = new char[classLabels_[i].length() + 1];\n    strcpy(detectionNames[i], classLabels_[i].c_str());\n  }\n\n  \/\/ Load network.\n  setupNetwork(cfg, weights, data, thresh, detectionNames, numClasses_,\n                0, 0, 1, 0.5, 0, 0, 0, 0);\n  yoloThread_ = std::thread(&YoloObjectDetector::yolo, this);\n\n  \/\/ Initialize publisher and subscriber.\n  std::string cameraTopicName;\n  int cameraQueueSize;\n  std::string objectDetectorTopicName;\n  int objectDetectorQueueSize;\n  bool objectDetectorLatch;\n  std::string boundingBoxesTopicName;\n  int boundingBoxesQueueSize;\n  bool boundingBoxesLatch;\n  std::string detectionImageTopicName;\n  int detectionImageQueueSize;\n  bool detectionImageLatch;\n  bool doContinuousDetection;\n\n  nodeHandle_.param(\"subscribers\/camera_reading\/topic\", cameraQueueSize, 1);\n  nodeHandle_.param(\"subscribers\/camera_reading\/queue_size\", cameraQueueSize, 1);\n  nodeHandle_.param(\"publishers\/object_detector\/topic\", objectDetectorTopicName, std::string(\"found_object\"));\n  nodeHandle_.param(\"publishers\/object_detector\/queue_size\", objectDetectorQueueSize, 1);\n  nodeHandle_.param(\"publishers\/object_detector\/latch\", objectDetectorLatch, false);\n  nodeHandle_.param(\"publishers\/bounding_boxes\/topic\", boundingBoxesTopicName, std::string(\"bounding_boxes\"));\n  nodeHandle_.param(\"publishers\/bounding_boxes\/queue_size\", boundingBoxesQueueSize, 1);\n  nodeHandle_.param(\"publishers\/bounding_boxes\/latch\", boundingBoxesLatch, false);\n  nodeHandle_.param(\"publishers\/detection_image\/topic\", detectionImageTopicName, std::string(\"detection_image\"));\n  nodeHandle_.param(\"publishers\/detection_image\/queue_size\", detectionImageQueueSize, 1);\n  nodeHandle_.param(\"publishers\/detection_image\/latch\", detectionImageLatch, true);\n  nodeHandle_.param(\"continuous_detection\", doContinuousDetection, false);\n\n  if (doContinuousDetection)\n    imageSubscriber_ = imageTransport_.subscribe(cameraTopicName, 1, &YoloObjectDetector::cameraCallback, this);\n  objectPublisher_ = nodeHandle_.advertise<std_msgs::Int8>(objectDetectorTopicName, objectDetectorQueueSize, objectDetectorLatch);\n  boundingBoxesPublisher_ = nodeHandle_.advertise<darknet_ros_msgs::BoundingBoxes>(boundingBoxesTopicName, boundingBoxesQueueSize, boundingBoxesLatch);\n  detectionImagePublisher_ = nodeHandle_.advertise<sensor_msgs::Image>(detectionImageTopicName, detectionImageQueueSize, detectionImageLatch);\n\n  \/\/ Action servers.\n  std::string checkForObjectsActionName;\n  nodeHandle_.param(\"actions\/camera_reading\/topic\", checkForObjectsActionName, std::string(\"check_for_objects\"));\n  checkForObjectsActionServer_.reset(new CheckForObjectsActionServer(nodeHandle_, checkForObjectsActionName, false));\n  checkForObjectsActionServer_->registerGoalCallback(boost::bind(&YoloObjectDetector::checkForObjectsActionGoalCB, this));\n  checkForObjectsActionServer_->registerPreemptCallback(boost::bind(&YoloObjectDetector::checkForObjectsActionPreemptCB, this));\n  checkForObjectsActionServer_->start();\n}\n\nvoid YoloObjectDetector::cameraCallback(const sensor_msgs::ImageConstPtr& msg)\n{\n  ROS_DEBUG(\"[YoloObjectDetector] USB image received.\");\n\n  cv_bridge::CvImagePtr cam_image;\n\n  try {\n    cam_image = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);\n  } catch (cv_bridge::Exception& e) {\n    ROS_ERROR(\"cv_bridge exception: %s\", e.what());\n    return;\n  }\n\n  if (cam_image) {\n    {\n      boost::unique_lock<boost::shared_mutex> lockImageCallback(mutexImageCallback_);\n      imageHeader_ = msg->header;\n      camImageCopy_ = cam_image->image.clone();\n    }\n    {\n      boost::unique_lock<boost::shared_mutex> lockImageStatus(mutexImageStatus_);\n      imageStatus_ = true;\n    }\n    frameWidth_ = cam_image->image.size().width;\n    frameHeight_ = cam_image->image.size().height;\n  }\n  return;\n}\n\nvoid YoloObjectDetector::checkForObjectsActionGoalCB()\n{\n  ROS_DEBUG(\"[YoloObjectDetector] Start check for objects action.\");\n\n  boost::shared_ptr<const darknet_ros_msgs::CheckForObjectsGoal> imageActionPtr =\n      checkForObjectsActionServer_->acceptNewGoal();\n  sensor_msgs::Image imageAction = imageActionPtr->image;\n\n  cv_bridge::CvImagePtr cam_image;\n\n  try {\n    cam_image = cv_bridge::toCvCopy(imageAction, sensor_msgs::image_encodings::BGR8);\n  } catch (cv_bridge::Exception& e) {\n    ROS_ERROR(\"cv_bridge exception: %s\", e.what());\n    return;\n  }\n\n  if (cam_image) {\n    {\n      boost::unique_lock<boost::shared_mutex> lockImageCallback(mutexImageCallback_);\n      camImageCopy_ = cam_image->image.clone();\n    }\n    {\n      boost::unique_lock<boost::shared_mutex> lockImageCallback(mutexActionStatus_);\n      actionId_ = imageActionPtr->id;\n    }\n    {\n      boost::unique_lock<boost::shared_mutex> lockImageStatus(mutexImageStatus_);\n      imageStatus_ = true;\n    }\n    frameWidth_ = cam_image->image.size().width;\n    frameHeight_ = cam_image->image.size().height;\n  }\n  return;\n}\n\nvoid YoloObjectDetector::checkForObjectsActionPreemptCB()\n{\n  ROS_DEBUG(\"[YoloObjectDetector] Preempt check for objects action.\");\n  checkForObjectsActionServer_->setPreempted();\n}\n\nbool YoloObjectDetector::isCheckingForObjects() const\n{\n  return (ros::ok() && checkForObjectsActionServer_->isActive()\n      && !checkForObjectsActionServer_->isPreemptRequested());\n}\n\nbool YoloObjectDetector::publishDetectionImage(const cv::Mat& detectionImage)\n{\n  if (detectionImagePublisher_.getNumSubscribers() < 1)\n    return false;\n  cv_bridge::CvImage cvImage;\n  cvImage.header.stamp = ros::Time::now();\n  cvImage.header.frame_id = \"detection_image\";\n  cvImage.encoding = sensor_msgs::image_encodings::BGR8;\n  cvImage.image = detectionImage;\n  detectionImagePublisher_.publish(*cvImage.toImageMsg());\n  ROS_DEBUG(\"Detection image has been published.\");\n  return true;\n}\n\nint YoloObjectDetector::sizeNetwork(network *net)\n{\n  int i;\n  int count = 0;\n  for(i = 0; i < net->n; ++i){\n    layer l = net->layers[i];\n    if(l.type == YOLO || l.type == REGION || l.type == DETECTION){\n      count += l.outputs;\n    }\n  }\n  return count;\n}\n\nvoid YoloObjectDetector::rememberNetwork(network *net)\n{\n  int i;\n  int count = 0;\n  for(i = 0; i < net->n; ++i){\n    layer l = net->layers[i];\n    if(l.type == YOLO || l.type == REGION || l.type == DETECTION){\n      memcpy(predictions_[demoIndex_] + count, net->layers[i].output, sizeof(float) * l.outputs);\n      count += l.outputs;\n    }\n  }\n}\n\ndetection *YoloObjectDetector::avgPredictions(network *net, int *nboxes)\n{\n  int i, j;\n  int count = 0;\n  fill_cpu(demoTotal_, 0, avg_, 1);\n  for(j = 0; j < demoFrame_; ++j){\n    axpy_cpu(demoTotal_, 1.\/demoFrame_, predictions_[j], 1, avg_, 1);\n  }\n  for(i = 0; i < net->n; ++i){\n    layer l = net->layers[i];\n    if(l.type == YOLO || l.type == REGION || l.type == DETECTION){\n      memcpy(l.output, avg_ + count, sizeof(float) * l.outputs);\n      count += l.outputs;\n    }\n  }\n  detection *dets = get_network_boxes(net, buff_[0].w, buff_[0].h, demoThresh_, demoHier_, 0, 1, nboxes);\n  return dets;\n}\n\nvoid *YoloObjectDetector::detectInThread()\n{\n  running_ = 1;\n  float nms = .4;\n\n  layer l = net_->layers[net_->n - 1];\n  float *X = buffLetter_[(buffIndex_ + 2) % 3].data;\n  float *prediction = network_predict(net_, X);\n\n  rememberNetwork(net_);\n  detection *dets = 0;\n  int nboxes = 0;\n  dets = avgPredictions(net_, &nboxes);\n\n  if (nms > 0) do_nms_obj(dets, nboxes, l.classes, nms);\n\n  if (enableConsoleOutput_) {\n    printf(\"\\033[2J\");\n    printf(\"\\033[1;1H\");\n    printf(\"\\nFPS:%.1f\\n\",fps_);\n    printf(\"Objects:\\n\\n\");\n  }\n  image display = buff_[(buffIndex_+2) % 3];\n  draw_detections(display, dets, nboxes, demoThresh_, demoNames_, demoAlphabet_, demoClasses_);\n\n  \/\/ extract the bounding boxes and send them to ROS\n  int i, j;\n  int count = 0;\n  for (i = 0; i < nboxes; ++i) {\n    float xmin = dets[i].bbox.x - dets[i].bbox.w \/ 2.;\n    float xmax = dets[i].bbox.x + dets[i].bbox.w \/ 2.;\n    float ymin = dets[i].bbox.y - dets[i].bbox.h \/ 2.;\n    float ymax = dets[i].bbox.y + dets[i].bbox.h \/ 2.;\n\n    if (xmin < 0)\n      xmin = 0;\n    if (ymin < 0)\n      ymin = 0;\n    if (xmax > 1)\n      xmax = 1;\n    if (ymax > 1)\n      ymax = 1;\n\n    \/\/ iterate through possible boxes and collect the bounding boxes\n    for (j = 0; j < demoClasses_; ++j) {\n      if (dets[i].prob[j]) {\n        float x_center = (xmin + xmax) \/ 2;\n        float y_center = (ymin + ymax) \/ 2;\n        float BoundingBox_width = xmax - xmin;\n        float BoundingBox_height = ymax - ymin;\n\n        \/\/ define bounding box\n        \/\/ BoundingBox must be 1% size of frame (3.2x2.4 pixels)\n        if (BoundingBox_width > 0.01 && BoundingBox_height > 0.01) {\n          roiBoxes_[count].x = x_center;\n          roiBoxes_[count].y = y_center;\n          roiBoxes_[count].w = BoundingBox_width;\n          roiBoxes_[count].h = BoundingBox_height;\n          roiBoxes_[count].Class = j;\n          roiBoxes_[count].prob = dets[i].prob[j];\n          count++;\n        }\n      }\n    }\n  }\n\n  \/\/ create array to store found bounding boxes\n  \/\/ if no object detected, make sure that ROS knows that num = 0\n  if (count == 0) {\n    roiBoxes_[0].num = 0;\n  } else {\n    roiBoxes_[0].num = count;\n  }\n\n  free_detections(dets, nboxes);\n  demoIndex_ = (demoIndex_ + 1) % demoFrame_;\n  running_ = 0;\n  return 0;\n}\n\nvoid *YoloObjectDetector::fetchInThread()\n{\n  IplImageWithHeader_ imageAndHeader = getIplImageWithHeader();\n  IplImage* ROS_img = imageAndHeader.image;\n  ipl_into_image(ROS_img, buff_[buffIndex_]);\n  headerBuff_[buffIndex_] = imageAndHeader.header;\n  {\n    boost::shared_lock<boost::shared_mutex> lock(mutexImageCallback_);\n    buffId_[buffIndex_] = actionId_;\n  }\n  rgbgr_image(buff_[buffIndex_]);\n  letterbox_image_into(buff_[buffIndex_], net_->w, net_->h, buffLetter_[buffIndex_]);\n  return 0;\n}\n\nvoid *YoloObjectDetector::displayInThread(void *ptr)\n{\n  show_image_cv(buff_[(buffIndex_ + 1)%3], \"YOLO V3\", ipl_);\n  int c = cvWaitKey(waitKeyDelay_);\n  if (c != -1) c = c%256;\n  if (c == 27) {\n      demoDone_ = 1;\n      return 0;\n  } else if (c == 82) {\n      demoThresh_ += .02;\n  } else if (c == 84) {\n      demoThresh_ -= .02;\n      if(demoThresh_ <= .02) demoThresh_ = .02;\n  } else if (c == 83) {\n      demoHier_ += .02;\n  } else if (c == 81) {\n      demoHier_ -= .02;\n      if(demoHier_ <= .0) demoHier_ = .0;\n  }\n  return 0;\n}\n\nvoid *YoloObjectDetector::displayLoop(void *ptr)\n{\n  while (1) {\n    displayInThread(0);\n  }\n}\n\nvoid *YoloObjectDetector::detectLoop(void *ptr)\n{\n  while (1) {\n    detectInThread();\n  }\n}\n\nvoid YoloObjectDetector::setupNetwork(char *cfgfile, char *weightfile, char *datafile, float thresh,\n                                      char **names, int classes,\n                                      int delay, char *prefix, int avg_frames, float hier, int w, int h,\n                                      int frames, int fullscreen)\n{\n  demoPrefix_ = prefix;\n  demoDelay_ = delay;\n  demoFrame_ = avg_frames;\n  image **alphabet = load_alphabet_with_file(datafile);\n  demoNames_ = names;\n  demoAlphabet_ = alphabet;\n  demoClasses_ = classes;\n  demoThresh_ = thresh;\n  demoHier_ = hier;\n  fullScreen_ = fullscreen;\n  printf(\"YOLO V3\\n\");\n  net_ = load_network(cfgfile, weightfile, 0);\n  set_batch_network(net_, 1);\n}\n\nvoid YoloObjectDetector::yolo()\n{\n  const auto wait_duration = std::chrono::milliseconds(2000);\n  while (!getImageStatus()) {\n    printf(\"Waiting for image.\\n\");\n    if (!isNodeRunning()) {\n      return;\n    }\n    std::this_thread::sleep_for(wait_duration);\n  }\n\n  std::thread detect_thread;\n  std::thread fetch_thread;\n\n  srand(2222222);\n\n  int i;\n  demoTotal_ = sizeNetwork(net_);\n  predictions_ = (float **) calloc(demoFrame_, sizeof(float*));\n  for (i = 0; i < demoFrame_; ++i){\n      predictions_[i] = (float *) calloc(demoTotal_, sizeof(float));\n  }\n  avg_ = (float *) calloc(demoTotal_, sizeof(float));\n\n  layer l = net_->layers[net_->n - 1];\n  roiBoxes_ = (darknet_ros::RosBox_ *) calloc(l.w * l.h * l.n, sizeof(darknet_ros::RosBox_));\n\n  IplImageWithHeader_ imageAndHeader = getIplImageWithHeader();\n  IplImage* ROS_img = imageAndHeader.image;\n  buff_[0] = ipl_to_image(ROS_img);\n  buff_[1] = copy_image(buff_[0]);\n  buff_[2] = copy_image(buff_[0]);\n  headerBuff_[0] = imageAndHeader.header;\n  headerBuff_[1] = headerBuff_[0];\n  headerBuff_[2] = headerBuff_[0];\n  buffLetter_[0] = letterbox_image(buff_[0], net_->w, net_->h);\n  buffLetter_[1] = letterbox_image(buff_[0], net_->w, net_->h);\n  buffLetter_[2] = letterbox_image(buff_[0], net_->w, net_->h);\n  ipl_ = cvCreateImage(cvSize(buff_[0].w, buff_[0].h), IPL_DEPTH_8U, buff_[0].c);\n\n  int count = 0;\n\n  if (!demoPrefix_ && viewImage_) {\n    cvNamedWindow(\"YOLO V3\", CV_WINDOW_NORMAL);\n    if (fullScreen_) {\n      cvSetWindowProperty(\"YOLO V3\", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);\n    } else {\n      cvMoveWindow(\"YOLO V3\", 0, 0);\n      cvResizeWindow(\"YOLO V3\", 640, 480);\n    }\n  }\n\n  demoTime_ = what_time_is_it_now();\n\n  while (!demoDone_) {\n    buffIndex_ = (buffIndex_ + 1) % 3;\n    fetch_thread = std::thread(&YoloObjectDetector::fetchInThread, this);\n    detect_thread = std::thread(&YoloObjectDetector::detectInThread, this);\n    if (!demoPrefix_) {\n      fps_ = 1.\/(what_time_is_it_now() - demoTime_);\n      demoTime_ = what_time_is_it_now();\n      if (viewImage_) {\n        displayInThread(0);\n      } else {\n        get_image_cv(buff_[(buffIndex_ + 1)%3], ipl_);\n      }\n      publishInThread();\n    } else {\n      char name[256];\n      sprintf(name, \"%s_%08d\", demoPrefix_, count);\n      save_image(buff_[(buffIndex_ + 1) % 3], name);\n    }\n    fetch_thread.join();\n    detect_thread.join();\n    ++count;\n    if (!isNodeRunning()) {\n      demoDone_ = true;\n    }\n  }\n\n}\n\nIplImageWithHeader_ YoloObjectDetector::getIplImageWithHeader()\n{\n  boost::shared_lock<boost::shared_mutex> lock(mutexImageCallback_);\n  IplImage* ROS_img = new IplImage(camImageCopy_);\n  IplImageWithHeader_ header = {.image = ROS_img, .header = imageHeader_};\n  return header;\n}\n\nbool YoloObjectDetector::getImageStatus(void)\n{\n  boost::shared_lock<boost::shared_mutex> lock(mutexImageStatus_);\n  return imageStatus_;\n}\n\nbool YoloObjectDetector::isNodeRunning(void)\n{\n  boost::shared_lock<boost::shared_mutex> lock(mutexNodeStatus_);\n  return isNodeRunning_;\n}\n\nvoid *YoloObjectDetector::publishInThread()\n{\n  \/\/ Publish image.\n  cv::Mat cvImage = cv::cvarrToMat(ipl_);\n  if (!publishDetectionImage(cv::Mat(cvImage))) {\n    ROS_DEBUG(\"Detection image has not been broadcasted.\");\n  }\n\n  \/\/ Publish bounding boxes and detection result.\n  int num = roiBoxes_[0].num;\n  if (num > 0 && num <= 100) {\n    for (int i = 0; i < num; i++) {\n      for (int j = 0; j < numClasses_; j++) {\n        if (roiBoxes_[i].Class == j) {\n          rosBoxes_[j].push_back(roiBoxes_[i]);\n          rosBoxCounter_[j]++;\n        }\n      }\n    }\n\n    std_msgs::Int8 msg;\n    msg.data = num;\n    objectPublisher_.publish(msg);\n\n    for (int i = 0; i < numClasses_; i++) {\n      if (rosBoxCounter_[i] > 0) {\n        darknet_ros_msgs::BoundingBox boundingBox;\n\n        for (int j = 0; j < rosBoxCounter_[i]; j++) {\n          int xmin = (rosBoxes_[i][j].x - rosBoxes_[i][j].w \/ 2) * frameWidth_;\n          int ymin = (rosBoxes_[i][j].y - rosBoxes_[i][j].h \/ 2) * frameHeight_;\n          int xmax = (rosBoxes_[i][j].x + rosBoxes_[i][j].w \/ 2) * frameWidth_;\n          int ymax = (rosBoxes_[i][j].y + rosBoxes_[i][j].h \/ 2) * frameHeight_;\n\n          boundingBox.Class = classLabels_[i];\n          boundingBox.probability = rosBoxes_[i][j].prob;\n          boundingBox.xmin = xmin;\n          boundingBox.ymin = ymin;\n          boundingBox.xmax = xmax;\n          boundingBox.ymax = ymax;\n          boundingBoxesResults_.bounding_boxes.push_back(boundingBox);\n        }\n      }\n    }\n    boundingBoxesResults_.header.stamp = ros::Time::now();\n    boundingBoxesResults_.header.frame_id = \"detection\";\n    boundingBoxesResults_.image_header = headerBuff_[(buffIndex_ + 1) % 3];\n    boundingBoxesPublisher_.publish(boundingBoxesResults_);\n  } else {\n    std_msgs::Int8 msg;\n    msg.data = 0;\n    objectPublisher_.publish(msg);\n  }\n  if (isCheckingForObjects()) {\n    ROS_DEBUG(\"[YoloObjectDetector] check for objects in image.\");\n    darknet_ros_msgs::CheckForObjectsResult objectsActionResult;\n    objectsActionResult.id = buffId_[0];\n    objectsActionResult.bounding_boxes = boundingBoxesResults_;\n    checkForObjectsActionServer_->setSucceeded(objectsActionResult, \"Send bounding boxes.\");\n  }\n  boundingBoxesResults_.bounding_boxes.clear();\n  for (int i = 0; i < numClasses_; i++) {\n    rosBoxes_[i].clear();\n    rosBoxCounter_[i] = 0;\n  }\n\n  return 0;\n}\n\n\n} \/* namespace darknet_ros*\/\n","avg_line_length":31.2430340557,"max_line_length":151,"alphanum_fraction":0.6756676411,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":30627,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/\/ Soli Deo gloria\n#ifdef WITH_CRASHRPT\n#include <tchar.h>\n#endif\n\n\/\/ Tnz6 includes\n#include \"mainwindow.h\"\n#include \"flipbook.h\"\n#include \"tapp.h\"\n#include \"iocommand.h\"\n#include \"previewfxmanager.h\"\n#include \"cleanupsettingspopup.h\"\n#include \"filebrowsermodel.h\"\n#include \"expressionreferencemanager.h\"\n#include \"startuppopup.h\"\n\n\/\/ TnzTools includes\n#include \"tools\/tool.h\"\n#include \"tools\/toolcommandids.h\"\n\n\/\/ TnzQt includes\n#include \"toonzqt\/dvdialog.h\"\n#include \"toonzqt\/menubarcommand.h\"\n#include \"toonzqt\/tmessageviewer.h\"\n#include \"toonzqt\/icongenerator.h\"\n#include \"toonzqt\/gutil.h\"\n#include \"toonzqt\/pluginloader.h\"\n\n\/\/ TnzStdfx includes\n#include \"stdfx\/shaderfx.h\"\n\n\/\/ TnzLib includes\n#include \"toonz\/preferences.h\"\n#include \"toonz\/toonzfolders.h\"\n#include \"toonz\/tproject.h\"\n#include \"toonz\/studiopalette.h\"\n#include \"toonz\/stylemanager.h\"\n#include \"toonz\/tscenehandle.h\"\n#include \"toonz\/txshsimplelevel.h\"\n#include \"toonz\/tproject.h\"\n#include \"toonz\/scriptengine.h\"\n\n\/\/ TnzSound includes\n#include \"tnzsound.h\"\n\n\/\/ TnzImage includes\n#include \"tnzimage.h\"\n\n\/\/ TnzBase includes\n#include \"permissionsmanager.h\"\n#include \"tenv.h\"\n#include \"tcli.h\"\n\n\/\/ TnzCore includes\n#include \"tsystem.h\"\n#include \"tthread.h\"\n#include \"tthreadmessage.h\"\n#include \"tundo.h\"\n#include \"tconvert.h\"\n#include \"tiio_std.h\"\n#include \"timagecache.h\"\n#include \"tofflinegl.h\"\n#include \"tpluginmanager.h\"\n#include \"tsimplecolorstyles.h\"\n#include \"toonz\/imagestyles.h\"\n#include \"tvectorbrushstyle.h\"\n#include \"tfont.h\"\n\n#include \"kis_tablet_support_win8.h\"\n\n#ifdef WITH_CRASHRPT\n#include \"CrashRpt.h\"\n#endif\n\n#ifdef MACOSX\n#include \"tipc.h\"\n#endif\n\n\/\/ Qt includes\n#include <QApplication>\n#include <QAbstractEventDispatcher>\n#include <QAbstractNativeEventFilter>\n#include <QSplashScreen>\n#include <QGLPixelBuffer>\n#include <QTranslator>\n#include <QFileInfo>\n#include <QSettings>\n#include <QLibraryInfo>\n#include <QHash>\n#include <QPainterPath>\n\n#ifdef _WIN32\n#ifndef x64\n#include <float.h>\n#endif\n#include <QtPlatformHeaders\/QWindowsWindowFunctions>\n#endif\n\nusing namespace DVGui;\n\nTEnv::IntVar EnvSoftwareCurrentFontSize(\"SoftwareCurrentFontSize\", 12);\n\nconst char *rootVarName     = \"TAHOMA2DROOT\";\nconst char *systemVarPrefix = \"TAHOMA2D\";\n\n#ifdef MACOSX\n#include \"tthread.h\"\nvoid postThreadMsg(TThread::Message *) {}\nvoid qt_mac_set_menubar_merge(bool enable);\n#endif\n\n\/\/ Modifica per toonz (non servono questo tipo di licenze)\n#define NO_LICENSE\n\/\/-----------------------------------------------------------------------------\n\nstatic void fatalError(QString msg) {\n  DVGui::MsgBoxInPopup(\n      CRITICAL,\n      msg + \"\\n\" +\n          QObject::tr(\"Installing %1 again could fix the problem.\")\n              .arg(QString::fromStdString(TEnv::getApplicationFullName())));\n  exit(0);\n}\n\/\/-----------------------------------------------------------------------------\n\nstatic void lastWarningError(QString msg) {\n  DVGui::error(msg);\n  \/\/ exit(0);\n}\n\/\/-----------------------------------------------------------------------------\n\nstatic void toonzRunOutOfContMemHandler(unsigned long size) {\n#ifdef _WIN32\n  static bool firstTime = true;\n  if (firstTime) {\n    MessageBox(NULL, (LPCWSTR)L\"Run out of contiguous physical memory: please save all and restart Tahoma2D!\",\n\t\t\t\t   (LPCWSTR)L\"Warning\", MB_OK | MB_SYSTEMMODAL);\n    firstTime = false;\n  }\n#endif\n}\n\n\/\/-----------------------------------------------------------------------------\n\n\/\/ todo.. da mettere in qualche .h\nDV_IMPORT_API void initStdFx();\nDV_IMPORT_API void initColorFx();\n\n\/\/-----------------------------------------------------------------------------\n\n\/\/! Inizializzaza l'Environment di Toonz\n\/*! In particolare imposta la projectRoot e\n    la stuffDir, controlla se la directory di outputs esiste (e provvede a\n    crearla in caso contrario) verifica inoltre che stuffDir esista.\n*\/\nstatic void initToonzEnv(QHash<QString, QString> &argPathValues) {\n  StudioPalette::enable(true);\n  TEnv::setRootVarName(rootVarName);\n  TEnv::setSystemVarPrefix(systemVarPrefix);\n\n  QHash<QString, QString>::const_iterator i = argPathValues.constBegin();\n  while (i != argPathValues.constEnd()) {\n    if (!TEnv::setArgPathValue(i.key().toStdString(), i.value().toStdString()))\n      DVGui::error(\n          QObject::tr(\"The qualifier %1 is not a valid key name. Skipping.\")\n              .arg(i.key()));\n    ++i;\n  }\n\n  QCoreApplication::setOrganizationName(\"Tahoma2D\");\n  QCoreApplication::setOrganizationDomain(\"\");\n  QCoreApplication::setApplicationName(\n      QString::fromStdString(TEnv::getApplicationName()));\n\n  \/*-- TOONZROOT\u306ePath\u306e\u78ba\u8a8d --*\/\n  \/\/ controllo se la xxxroot e' definita e corrisponde ad un folder esistente\n\n  \/*-- ENGLISH: Confirm TOONZROOT Path\n        Check if the xxxroot is defined and corresponds to an existing folder\n  --*\/\n\n  TFilePath stuffDir = TEnv::getStuffDir();\n  if (stuffDir == TFilePath())\n    fatalError(\"Undefined or empty: \\\"\" + toQString(TEnv::getRootVarPath()) +\n               \"\\\"\");\n  else if (!TFileStatus(stuffDir).isDirectory())\n    fatalError(\"Folder \\\"\" + toQString(stuffDir) +\n               \"\\\" not found or not readable\");\n\n  Tiio::defineStd();\n  initImageIo();\n  initSoundIo();\n  initStdFx();\n  initColorFx();\n\n  \/\/ TPluginManager::instance()->loadStandardPlugins();\n\n  TFilePath library = ToonzFolder::getLibraryFolder();\n\n  TRasterImagePatternStrokeStyle::setRootDir(library);\n  TVectorImagePatternStrokeStyle::setRootDir(library);\n  TVectorBrushStyle::setRootDir(library);\n\n  \/\/ sembra indispensabile nella lettura dei .tab 2.2:\n  TPalette::setRootDir(library);\n  TImageStyle::setLibraryDir(library);\n\n  \/\/ TProjectManager::instance()->enableTabMode(true);\n\n  TProjectManager *projectManager = TProjectManager::instance();\n\n  \/*--\n   * TOONZPROJECTS\u306e\u30d1\u30b9\u30bb\u30c3\u30c8\u3092\u53d6\u5f97\u3059\u308b\u3002\uff08TOONZPROJECTS\u306f\u30bb\u30df\u30b3\u30ed\u30f3\u3067\u533a\u5207\u3063\u3066\u8907\u6570\u8a2d\u5b9a\u53ef\u80fd\uff09\n   * --*\/\n  \/\/ TFilePathSet projectsRoots = ToonzFolder::getProjectsFolders();\n  \/\/ TFilePathSet::iterator it;\n  \/\/ for (it = projectsRoots.begin(); it != projectsRoots.end(); ++it)\n  \/\/  projectManager->addProjectsRoot(*it);\n\n  \/*-- \u3082\u3057\u307e\u3060\u7121\u3051\u308c\u3070\u3001TOONZROOT\/sandbox\u306bsandbox\u30d7\u30ed\u30b8\u30a7\u30af\u30c8\u3092\u4f5c\u308b --*\/\n  projectManager->createSandboxIfNeeded();\n\n  \/*\nTProjectP project = projectManager->getCurrentProject();\nNon dovrebbe servire per Tab:\nproject->setFolder(TProject::Drawings, TFilePath(\"$scenepath\"));\nproject->setFolder(TProject::Extras, TFilePath(\"$scenepath\"));\nproject->setUseScenePath(TProject::Drawings, false);\nproject->setUseScenePath(TProject::Extras, false);\n*\/\n  \/\/ Imposto la rootDir per ImageCache\n\n  \/*-- TOONZCACHEROOT\u306e\u8a2d\u5b9a  --*\/\n  TFilePath cacheDir               = ToonzFolder::getCacheRootFolder();\n  if (cacheDir.isEmpty()) cacheDir = TEnv::getStuffDir() + \"cache\";\n  TImageCache::instance()->setRootDir(cacheDir);\n\n  TFilePath favoritesDir = ToonzFolder::getMyFavoritesFolder();\n  if (!TFileStatus(favoritesDir).doesExist()) TSystem::mkDir(favoritesDir);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nstatic void script_output(int type, const QString &value) {\n  if (type == ScriptEngine::ExecutionError ||\n      type == ScriptEngine::SyntaxError ||\n      type == ScriptEngine::UndefinedEvaluationResult ||\n      type == ScriptEngine::Warning)\n    std::cerr << value.toStdString() << std::endl;\n  else\n    std::cout << value.toStdString() << std::endl;\n}\n\n\/\/-----------------------------------------------------------------------------\n#ifdef WITH_CRASHRPT\nLPCWSTR convertToLPCWSTR(std::string str) {\n  std::wstring stemp = std::wstring(str.begin(), str.end());\n  return stemp.c_str();\n}\n#endif\n\nint main(int argc, char *argv[]) {\n#ifdef Q_OS_WIN\n  \/\/  Enable standard input\/output on Windows Platform for debug\n  BOOL consoleAttached = ::AttachConsole(ATTACH_PARENT_PROCESS);\n  if (consoleAttached) {\n    freopen(\"CON\", \"r\", stdin);\n    freopen(\"CON\", \"w\", stdout);\n    freopen(\"CON\", \"w\", stderr);\n  }\n#endif\n\n  \/\/ parsing arguments and qualifiers\n  TFilePath loadFilePath;\n  QString argumentLayoutFileName = \"\";\n  QHash<QString, QString> argumentPathValues;\n  if (argc > 1) {\n    TCli::Usage usage(argv[0]);\n    TCli::UsageLine usageLine;\n    TCli::FilePathArgument loadFileArg(\n        \"filePath\", \"Source scene file to open or script file to run\");\n    TCli::StringQualifier layoutFileQual(\n        \"-layout filename\",\n        \"Custom layout file to be used, it should be saved in \"\n        \"$TOONZPROFILES\\\\layouts\\\\personal\\\\[CurrentLayoutName].[UserName]\\\\. \"\n        \"layouts.txt is used by default.\");\n    usageLine = usageLine + layoutFileQual;\n\n    \/\/ system path qualifiers\n    std::map<QString, std::unique_ptr<TCli::QualifierT<TFilePath>>>\n        systemPathQualMap;\n    QString qualKey  = QString(\"%1ROOT\").arg(systemVarPrefix);\n    QString qualName = QString(\"-%1 folderpath\").arg(qualKey);\n    QString qualHelp =\n        QString(\n            \"%1 path. It will automatically set other system paths to %1 \"\n            \"unless individually specified with other qualifiers.\")\n            .arg(qualKey);\n    systemPathQualMap[qualKey].reset(new TCli::QualifierT<TFilePath>(\n        qualName.toStdString(), qualHelp.toStdString()));\n    usageLine = usageLine + *systemPathQualMap[qualKey];\n\n    const std::map<std::string, std::string> &spm = TEnv::getSystemPathMap();\n    for (auto itr = spm.begin(); itr != spm.end(); ++itr) {\n      qualKey = QString(\"%1%2\")\n                    .arg(systemVarPrefix)\n                    .arg(QString::fromStdString((*itr).first));\n      qualName = QString(\"-%1 folderpath\").arg(qualKey);\n      qualHelp = QString(\"%1 path.\").arg(qualKey);\n      systemPathQualMap[qualKey].reset(new TCli::QualifierT<TFilePath>(\n          qualName.toStdString(), qualHelp.toStdString()));\n      usageLine = usageLine + *systemPathQualMap[qualKey];\n    }\n    usage.add(usageLine);\n    usage.add(usageLine + loadFileArg);\n\n    if (!usage.parse(argc, argv)) exit(1);\n\n    loadFilePath = loadFileArg.getValue();\n    if (layoutFileQual.isSelected())\n      argumentLayoutFileName =\n          QString::fromStdString(layoutFileQual.getValue());\n    for (auto q_itr = systemPathQualMap.begin();\n         q_itr != systemPathQualMap.end(); ++q_itr) {\n      if (q_itr->second->isSelected())\n        argumentPathValues.insert(q_itr->first,\n                                  q_itr->second->getValue().getQString());\n    }\n\n    argc = 1;\n  }\n\n  \/\/ Enables high-DPI scaling. This attribute must be set before QApplication is\n  \/\/ constructed. Available from Qt 5.6.\n#if QT_VERSION >= 0x050600\n  QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);\n#endif\n\n  QApplication a(argc, argv);\n\n#ifdef MACOSX\n\/\/ This workaround is to avoid missing left button problem on Qt5.6.0.\n\/\/ To invalidate m_rightButtonClicked in Qt\/qnsview.mm, sending\n\/\/ NSLeftButtonDown event before NSLeftMouseDragged event propagated to\n\/\/ QApplication. See more details in ..\/mousedragfilter\/mousedragfilter.mm.\n\n#include \"mousedragfilter.h\"\n\n  class OSXMouseDragFilter final : public QAbstractNativeEventFilter {\n    bool leftButtonPressed = false;\n\n  public:\n    bool nativeEventFilter(const QByteArray &eventType, void *message,\n                           long *) Q_DECL_OVERRIDE {\n      if (IsLeftMouseDown(message)) {\n        leftButtonPressed = true;\n      }\n      if (IsLeftMouseUp(message)) {\n        leftButtonPressed = false;\n      }\n\n      if (eventType == \"mac_generic_NSEvent\") {\n        if (IsLeftMouseDragged(message) && !leftButtonPressed) {\n          std::cout << \"force mouse press event\" << std::endl;\n          SendLeftMousePressEvent();\n          return true;\n        }\n      }\n      return false;\n    }\n  };\n\n  a.installNativeEventFilter(new OSXMouseDragFilter);\n#endif\n\n#ifdef Q_OS_WIN\n  \/\/\tSince currently Tahoma does not work with OpenGL of software or\n  \/\/ angle,\tforce Qt to use desktop OpenGL\n  \/\/ FIXME: This options should be called before constructing the application.\n  \/\/ Thus, ANGLE seems to be enabled as of now.\n  a.setAttribute(Qt::AA_UseDesktopOpenGL, true);\n#endif\n\n  \/\/ Some Qt objects are destroyed badly without a living qApp. So, we must\n  \/\/ enforce a way to either\n  \/\/ postpone the application destruction until the very end, OR ensure that\n  \/\/ sensible objects are\n  \/\/ destroyed before.\n\n  \/\/ Using a static QApplication only worked on Windows, and in any case C++\n  \/\/ respects the statics destruction\n  \/\/ order ONLY within the same library. On MAC, it made the app crash on exit\n  \/\/ o_o. So, nope.\n\n  std::unique_ptr<QObject> mainScope(new QObject(\n      &a));  \/\/ A QObject destroyed before the qApp is therefore explicitly\n  mainScope->setObjectName(\"mainScope\");  \/\/ provided. It can be accessed by\n                                          \/\/ looking in the qApp's children.\n\n#ifdef _WIN32\n#ifndef x64\n  \/\/ Store the floating point control word. It will be re-set before Toonz\n  \/\/ initialization\n  \/\/ has ended.\n  unsigned int fpWord = 0;\n  _controlfp_s(&fpWord, 0, 0);\n#endif\n#endif\n\n#ifdef _WIN32\n  \/\/ At least on windows, Qt's 4.5.2 native windows feature tend to create\n  \/\/ weird flickering effects when dragging panel separators.\n  a.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);\n#endif\n\n  \/\/ Enable to render smooth icons on high dpi monitors\n  a.setAttribute(Qt::AA_UseHighDpiPixmaps);\n#if defined(_WIN32) && QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)\n  \/\/ Compress tablet events with application attributes instead of implementing\n  \/\/ the delay-timer by ourselves\n  a.setAttribute(Qt::AA_CompressHighFrequencyEvents);\n  a.setAttribute(Qt::AA_CompressTabletEvents);\n#endif\n\n#ifdef _WIN32\n  \/\/ This attribute is set to make menubar icon to be always (16 x devPixRatio).\n  \/\/ Without this attribute the menu bar icon size becomes the same as tool bar\n  \/\/ when Windows scale is in 125%. Currently hiding the menu bar icon is done\n  \/\/ by setting transparent pixmap only in menu bar icon size. So the size must\n  \/\/ be different between for menu bar and for tool bar.\n  a.setAttribute(Qt::AA_Use96Dpi);\n#endif\n\n \/\/ Set the app's locale for numeric stuff to standard C. This is important for\n  \/\/ atof() and similar\n  \/\/ calls that are locale-dependent.\n  setlocale(LC_NUMERIC, \"C\");\n\n\/\/ Set current directory to the bundle\/application path - this is needed to have\n\/\/ correct relative paths\n#ifdef MACOSX\n  {\n    QDir appDir(QApplication::applicationDirPath());\n    appDir.cdUp(), appDir.cdUp(), appDir.cdUp();\n\n    bool ret = QDir::setCurrent(appDir.absolutePath());\n    assert(ret);\n  }\n#endif\n\n  \/\/ Set icon theme search paths\n  QStringList themeSearchPathsList = {\":\/icons\"};\n  QIcon::setThemeSearchPaths(themeSearchPathsList);\n  \/\/ qDebug() << \"All icon theme search paths:\" << QIcon::themeSearchPaths();\n\n  \/\/ Set show icons in menus flag (use iconVisibleInMenu to disable selectively)\n  QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus, true);\n\n  TEnv::setApplicationFileName(argv[0]);\n\n  \/\/ splash screen\n  QPixmap splashPixmap =\n      QIcon(\":Resources\/tahoma2d_splash.svg\").pixmap(QSize(344, 344));\n\n#ifdef _WIN32\n  QFont font(\"Segoe UI\", -1);\n#else\n  QFont font(\"Helvetica\", -1);\n#endif\n  font.setPixelSize(10);\n  font.setWeight(50);\n  a.setFont(font);\n\n  QString offsetStr(\"\\n\\n\\n\\n\\n\\n\\n\\n\");\n\n  TSystem::hasMainLoop(true);\n\n  TMessageRepository::instance();\n\n  bool isRunScript = (loadFilePath.getType() == \"toonzscript\");\n\n  QSplashScreen splash(splashPixmap);\n  QPainterPath path;\n  path.addRoundedRect(splash.rect(), 7, 7);\n  QRegion mask = QRegion(path.toFillPolygon().toPolygon());\n  splash.setMask(mask);\n  if (!isRunScript) splash.show();\n  a.processEvents();\n\n  splash.showMessage(offsetStr + \"Initializing QGLFormat...\",\n                     Qt::AlignRight | Qt::AlignBottom, Qt::black);\n  a.processEvents();\n\n  \/\/ OpenGL\n  QGLFormat fmt;\n  fmt.setAlpha(true);\n  fmt.setStencil(true);\n  QGLFormat::setDefaultFormat(fmt);\n\n  glutInit(&argc, argv);\n\n  splash.showMessage(offsetStr + \"Initializing environment...\",\n                     Qt::AlignRight | Qt::AlignBottom, Qt::black);\n  a.processEvents();\n\n  \/\/ Install run out of contiguous memory callback\n  TBigMemoryManager::instance()->setRunOutOfContiguousMemoryHandler(\n      &toonzRunOutOfContMemHandler);\n\n  \/\/ Toonz environment\n  initToonzEnv(argumentPathValues);\n\n#ifdef WITH_CRASHRPT\n  CR_INSTALL_INFO pInfo;\n  memset(&pInfo, 0, sizeof(CR_INSTALL_INFO));\n  pInfo.cb = sizeof(CR_INSTALL_INFO);\n  pInfo.pszAppName = convertToLPCWSTR(TEnv::getApplicationName());\n  pInfo.pszAppVersion = convertToLPCWSTR(TEnv::getApplicationVersion());\n  TFilePath crashrptCache =\n    ToonzFolder::getCacheRootFolder() + TFilePath(\"crashrpt\");\n  pInfo.pszErrorReportSaveDir =\n    convertToLPCWSTR(crashrptCache.getQString().toStdString());\n  \/\/ Install all available exception handlers.\n  \/\/ Don't send reports automaticall, store locally\n  pInfo.dwFlags |= CR_INST_ALL_POSSIBLE_HANDLERS | CR_INST_DONT_SEND_REPORT;\n\n  crInstall(&pInfo);\n#endif\n\n  \/\/ prepare for 30bit display\n  if (Preferences::instance()->is30bitDisplayEnabled()) {\n    QSurfaceFormat sFmt = QSurfaceFormat::defaultFormat();\n    sFmt.setRedBufferSize(10);\n    sFmt.setGreenBufferSize(10);\n    sFmt.setBlueBufferSize(10);\n    sFmt.setAlphaBufferSize(2);\n    QSurfaceFormat::setDefaultFormat(sFmt);\n  }\n\n  \/\/ Initialize thread components\n  TThread::init();\n\n  TProjectManager *projectManager = TProjectManager::instance();\n  if (Preferences::instance()->isSVNEnabled()) {\n    \/\/ Read Version Control repositories and add it to project manager as\n    \/\/ \"special\" svn project root\n    VersionControl::instance()->init();\n    QList<SVNRepository> repositories =\n        VersionControl::instance()->getRepositories();\n    int count = repositories.size();\n    for (int i = 0; i < count; i++) {\n      SVNRepository r = repositories.at(i);\n\n      TFilePath localPath(r.m_localPath.toStdWString());\n      if (!TFileStatus(localPath).doesExist()) {\n        try {\n          TSystem::mkDir(localPath);\n        } catch (TException &e) {\n          fatalError(QString::fromStdWString(e.getMessage()));\n        }\n      }\n      projectManager->addSVNProjectsRoot(localPath);\n    }\n  }\n\n#if defined(MACOSX) && defined(__LP64__)\n\n  \/\/ Load the shared memory settings\n  int shmmax = Preferences::instance()->getShmMax();\n  int shmseg = Preferences::instance()->getShmSeg();\n  int shmall = Preferences::instance()->getShmAll();\n  int shmmni = Preferences::instance()->getShmMni();\n\n  if (shmall <\n      0)  \/\/ Make sure that at least 100 MB of shared memory are available\n    shmall = (tipc::shm_maxSharedPages() < (100 << 8)) ? (100 << 8) : -1;\n\n  tipc::shm_set(shmmax, shmseg, shmall, shmmni);\n\n#endif\n\n  \/\/ DVDirModel must be instantiated after Version Control initialization...\n  FolderListenerManager::instance()->addListener(DvDirModel::instance());\n\n  splash.showMessage(offsetStr + \"Loading Translator...\",\n                     Qt::AlignRight | Qt::AlignBottom, Qt::black);\n  a.processEvents();\n\n  \/\/ Carico la traduzione contenuta in toonz.qm (se \u00ef\u00bf\u00bd presente)\n  QString languagePathString =\n      QString::fromStdString(::to_string(TEnv::getConfigDir() + \"loc\"));\n#ifndef WIN32\n  \/\/ the merge of menu on osx can cause problems with different languages with\n  \/\/ the Preferences menu\n  \/\/ qt_mac_set_menubar_merge(false);\n  languagePathString += \"\/\" + Preferences::instance()->getCurrentLanguage();\n#else\n  languagePathString += \"\\\\\" + Preferences::instance()->getCurrentLanguage();\n#endif\n  QTranslator translator;\n  translator.load(\"toonz\", languagePathString);\n\n  \/\/ La installo\n  a.installTranslator(&translator);\n\n  \/\/ Carico la traduzione contenuta in toonzqt.qm (se e' presente)\n  QTranslator translator2;\n  translator2.load(\"toonzqt\", languagePathString);\n  a.installTranslator(&translator2);\n\n  \/\/ Carico la traduzione contenuta in tnzcore.qm (se e' presente)\n  QTranslator tnzcoreTranslator;\n  tnzcoreTranslator.load(\"tnzcore\", languagePathString);\n  qApp->installTranslator(&tnzcoreTranslator);\n\n  \/\/ Carico la traduzione contenuta in toonzlib.qm (se e' presente)\n  QTranslator toonzlibTranslator;\n  toonzlibTranslator.load(\"toonzlib\", languagePathString);\n  qApp->installTranslator(&toonzlibTranslator);\n\n  \/\/ Carico la traduzione contenuta in colorfx.qm (se e' presente)\n  QTranslator colorfxTranslator;\n  colorfxTranslator.load(\"colorfx\", languagePathString);\n  qApp->installTranslator(&colorfxTranslator);\n\n  \/\/ Carico la traduzione contenuta in tools.qm\n  QTranslator toolTranslator;\n  toolTranslator.load(\"tnztools\", languagePathString);\n  qApp->installTranslator(&toolTranslator);\n\n  \/\/ load translation for file writers properties\n  QTranslator imageTranslator;\n  imageTranslator.load(\"image\", languagePathString);\n  qApp->installTranslator(&imageTranslator);\n\n  QTranslator qtTranslator;\n  qtTranslator.load(\"qt_\" + QLocale::system().name(),\n                    QLibraryInfo::location(QLibraryInfo::TranslationsPath));\n  a.installTranslator(&qtTranslator);\n\n  \/\/ Aggiorno la traduzione delle properties di tutti i tools\n  TTool::updateToolsPropertiesTranslation();\n  \/\/ Apply translation to file writers properties\n  Tiio::updateFileWritersPropertiesTranslation();\n\n  \/\/ Force to have left-to-right layout direction in any language environment.\n  \/\/ This function has to be called after installTranslator().\n  a.setLayoutDirection(Qt::LeftToRight);\n\n  splash.showMessage(offsetStr + \"Loading styles...\",\n                     Qt::AlignRight | Qt::AlignBottom, Qt::black);\n  a.processEvents();\n\n  \/\/ Set default start icon theme\n  QIcon::setThemeName(Preferences::instance()->getIconTheme() ? \"dark\"\n                                                              : \"light\");\n  \/\/ qDebug() << \"Icon theme name:\" << QIcon::themeName();\n\n  \/\/ stile\n  QApplication::setStyle(\"windows\");\n\n  IconGenerator::setFilmstripIconSize(Preferences::instance()->getIconSize());\n\n  splash.showMessage(offsetStr + \"Loading shaders...\",\n                     Qt::AlignRight | Qt::AlignBottom, Qt::black);\n  a.processEvents();\n\n  loadShaderInterfaces(ToonzFolder::getLibraryFolder() + TFilePath(\"shaders\"));\n\n  splash.showMessage(offsetStr + \"Initializing Tahoma2D...\",\n                     Qt::AlignRight | Qt::AlignBottom, Qt::black);\n  a.processEvents();\n\n  TTool::setApplication(TApp::instance());\n  TApp::instance()->init();\n\n  splash.showMessage(offsetStr + \"Loading Plugins...\",\n                     Qt::AlignRight | Qt::AlignBottom, Qt::black);\n  a.processEvents();\n  \/* poll the thread ends:\n   \u7d76\u5bfe\u306b\u5fc5\u8981\u306a\u308f\u3051\u3067\u306f\u306a\u3044\u304c PluginLoader \u306f\u4e2d\u3067 setup\n   \u30cf\u30f3\u30c9\u30e9\u304c\u5e38\u306b\u56fa\u6709\u306e\u30b9\u30ec\u30c3\u30c9\u3067\u547c\u3070\u308c\u308b\u3088\u3046 main thread queue \u306e blocking\n   \u3092\u3057\u3066\u3044\u308b\u306e\u3067\n   processEvents \u3092\u884c\u3046\u5fc5\u8981\u304c\u3042\u308b\n*\/\n  while (!PluginLoader::load_entries(\"\")) {\n    a.processEvents();\n  }\n\n  splash.showMessage(offsetStr + \"Creating main window...\",\n                     Qt::AlignRight | Qt::AlignBottom, Qt::black);\n  a.processEvents();\n\n  \/*-- Layout\u30d5\u30a1\u30a4\u30eb\u540d\u3092MainWindow\u306ector\u306b\u6e21\u3059 --*\/\n  MainWindow w(argumentLayoutFileName);\n\n  TFilePath fp = ToonzFolder::getModuleFile(\"mainwindow.ini\");\n  QSettings settings(toQString(fp), QSettings::IniFormat);\n  w.restoreGeometry(settings.value(\"MainWindowGeometry\").toByteArray());\n\n  if (isRunScript) {\n    \/\/ load script\n    if (TFileStatus(loadFilePath).doesExist()) {\n      \/\/ find project for this script file\n      TProjectManager *pm    = TProjectManager::instance();\n      TProjectP sceneProject = pm->loadSceneProject(loadFilePath);\n      TFilePath oldProjectPath;\n      if (!sceneProject) {\n        std::cerr << QObject::tr(\n                         \"It is not possible to load the scene %1 because it \"\n                         \"does not \"\n                         \"belong to any project.\")\n                         .arg(loadFilePath.getQString())\n                         .toStdString()\n                  << std::endl;\n        return 1;\n      }\n      if (sceneProject && !sceneProject->isCurrent()) {\n        oldProjectPath = pm->getCurrentProjectPath();\n        pm->setCurrentProjectPath(sceneProject->getProjectPath());\n      }\n      ScriptEngine engine;\n      QObject::connect(&engine, &ScriptEngine::output, script_output);\n      QString s = QString::fromStdWString(loadFilePath.getWideString())\n                      .replace(\"\\\\\", \"\\\\\\\\\")\n                      .replace(\"\\\"\", \"\\\\\\\"\");\n      QString cmd = QString(\"run(\\\"%1\\\")\").arg(s);\n      engine.evaluate(cmd);\n      engine.wait();\n      if (!oldProjectPath.isEmpty()) pm->setCurrentProjectPath(oldProjectPath);\n      return 1;\n    } else {\n      std::cerr << QObject::tr(\"Script file %1 does not exists.\")\n                       .arg(loadFilePath.getQString())\n                       .toStdString()\n                << std::endl;\n      return 1;\n    }\n  }\n\n#ifdef _WIN32\n  \/\/ http:\/\/doc.qt.io\/qt-5\/windows-issues.html#fullscreen-opengl-based-windows\n  if (w.windowHandle())\n    QWindowsWindowFunctions::setHasBorderInFullScreen(w.windowHandle(), true);\n#endif\n\n    \/\/ Qt have started to support Windows Ink from 5.12.\n    \/\/ Unlike WinTab API used in Qt 5.9 the tablet behaviors are different and\n    \/\/ are (at least, for OT) problematic. The customized Qt5.15.2 are made with\n    \/\/ cherry-picking the WinTab feature to be officially introduced from 6.0.\n    \/\/ See https:\/\/github.com\/shun-iwasawa\/qt5\/releases\/tag\/v5.15.2_wintab for\n    \/\/ details. The following feature can only be used with the customized Qt,\n    \/\/ with WITH_WINTAB build option, and in Windows-x64 build.\n\n#ifdef WITH_WINTAB\n  bool useQtNativeWinInk = Preferences::instance()->isQtNativeWinInkEnabled();\n  QWindowsWindowFunctions::setWinTabEnabled(!useQtNativeWinInk);\n#endif\n\n  splash.showMessage(offsetStr + \"Loading style sheet...\",\n                     Qt::AlignRight | Qt::AlignBottom, Qt::black);\n  a.processEvents();\n\n  \/\/ Carico lo styleSheet\n  QString currentStyle = Preferences::instance()->getCurrentStyleSheetPath();\n  a.setStyleSheet(currentStyle);\n\n  \/\/ Perspective grid tool - custom grid\n  splash.showMessage(offsetStr + \"Loading Perspective Grid...\",\n                     Qt::AlignRight | Qt::AlignBottom, Qt::black);\n  a.processEvents();\n\n  TTool *perspectiveTool =\n      TTool::getTool(T_PerspectiveGrid, TTool::VectorImage);\n  if (perspectiveTool) perspectiveTool->loadTool();\n\n  w.setWindowTitle(QString::fromStdString(TEnv::getApplicationFullName()));\n  if (TEnv::getIsPortable()) {\n    splash.showMessage(offsetStr + \"Starting Tahoma2D...\",\n                       Qt::AlignRight | Qt::AlignBottom, Qt::black);\n  } else {\n    splash.showMessage(offsetStr + \"Starting main window...\",\n                       Qt::AlignRight | Qt::AlignBottom, Qt::black);\n  }\n  a.processEvents();\n\n  ExpressionReferenceManager::instance()->init();\n\n#ifndef MACOSX\n  \/\/ Workaround for the maximized window case: Qt delivers two resize events,\n  \/\/ one in the normal geometry, before\n  \/\/ maximizing (why!?), the second afterwards - all inside the following show()\n  \/\/ call. This makes troublesome for\n  \/\/ the docking system to correctly restore the saved geometry. Fortunately,\n  \/\/ MainWindow::showEvent(..) gets called\n  \/\/ just between the two, so we can disable the currentRoom layout right before\n  \/\/ showing and re-enable it after\n  \/\/ the normal resize has happened.\n  if (w.isMaximized()) w.getCurrentRoom()->layout()->setEnabled(false);\n#endif\n\n  QRect splashGeometry = splash.geometry();\n  splash.finish(&w);\n\n  a.setQuitOnLastWindowClosed(false);\n  \/\/ a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));\n  if (Preferences::instance()->isLatestVersionCheckEnabled())\n    w.checkForUpdates();\n  DvDirModel::instance()->forceRefresh();\n\n  w.show();\n\n  \/\/ Show floating panels only after the main window has been shown\n  w.startupFloatingPanels();\n\n  if (Preferences::instance()->isStartupPopupEnabled()) {\n    StartupPopup *startupPopup = new StartupPopup();\n    startupPopup->show();\n    startupPopup->raise();\n    startupPopup->activateWindow();\n  }\n\n  CommandManager::instance()->execute(T_Hand);\n  if (!loadFilePath.isEmpty()) {\n    splash.showMessage(\n        QString(\"Loading file '\") + loadFilePath.getQString() + \"'...\",\n        Qt::AlignRight | Qt::AlignBottom, Qt::black);\n    loadFilePath = loadFilePath.withType(\"tnz\");\n    if (TFileStatus(loadFilePath).doesExist()) IoCmd::loadScene(loadFilePath);\n  }\n\n  QFont *myFont;\n  QString fontName  = Preferences::instance()->getInterfaceFont();\n  QString fontStyle = Preferences::instance()->getInterfaceFontStyle();\n\n  TFontManager *fontMgr = TFontManager::instance();\n  std::vector<std::wstring> typefaces;\n  bool isBold = false, isItalic = false, hasKerning = false;\n  try {\n    fontMgr->loadFontNames();\n    fontMgr->setFamily(fontName.toStdWString());\n    fontMgr->getAllTypefaces(typefaces);\n    isBold     = fontMgr->isBold(fontName, fontStyle);\n    isItalic   = fontMgr->isItalic(fontName, fontStyle);\n    hasKerning = fontMgr->hasKerning();\n  } catch (TFontCreationError &) {\n    \/\/ Do nothing. A default font should load\n  }\n\n  myFont = new QFont(fontName);\n  myFont->setPixelSize(EnvSoftwareCurrentFontSize);\n  myFont->setBold(isBold);\n  myFont->setItalic(isItalic);\n  myFont->setKerning(hasKerning);\n\n  a.setFont(*myFont);\n\n  QAction *action = CommandManager::instance()->getAction(\"MI_OpenTMessage\");\n  if (action)\n    QObject::connect(TMessageRepository::instance(),\n                     SIGNAL(openMessageCenter()), action, SLOT(trigger()));\n\n  QObject::connect(TUndoManager::manager(), SIGNAL(somethingChanged()),\n                   TApp::instance()->getCurrentScene(), SLOT(setDirtyFlag()));\n\n#ifdef _WIN32\n#ifndef x64\n  \/\/ On 32-bit architecture, there could be cases in which initialization could\n  \/\/ alter the\n  \/\/ FPU floating point control word. I've seen this happen when loading some\n  \/\/ AVI coded (VFAPI),\n  \/\/ where 80-bit internal precision was used instead of the standard 64-bit\n  \/\/ (much faster and\n  \/\/ sufficient - especially considering that x86 truncates to 64-bit\n  \/\/ representation anyway).\n  \/\/ IN ANY CASE, revert to the original control word.\n  \/\/ In the x64 case these precision changes simply should not take place up to\n  \/\/ _controlfp_s\n  \/\/ documentation.\n  _controlfp_s(0, fpWord, -1);\n#endif\n#endif\n\n\/\/ Windows Ink Support was introduce into Qt 5.12 so disable\n\/\/ our version when compiling with it\n#if defined(_WIN32) && QT_VERSION < QT_VERSION_CHECK(5, 12, 0)\n  if (Preferences::instance()->isWinInkEnabled()) {\n    KisTabletSupportWin8 *penFilter = new KisTabletSupportWin8();\n    if (penFilter->init()) {\n      a.installNativeEventFilter(penFilter);\n    } else {\n      delete penFilter;\n    }\n  }\n#endif\n\n  a.installEventFilter(TApp::instance());\n\n  int ret = a.exec();\n\n  TUndoManager::manager()->reset();\n  PreviewFxManager::instance()->reset();\n\n#ifdef _WIN32\n  if (consoleAttached) {\n    ::FreeConsole();\n  }\n#endif\n\n#ifdef WITH_CRASHRPT\n  crUninstall();\n#endif\n\n  return ret;\n}\n","avg_line_length":33.4355895197,"max_line_length":110,"alphanum_fraction":0.6810004245,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1805,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":51.0,"content":"\/\/\n\/\/ Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n\/\/ Official repository: https:\/\/github.com\/CPPAlliance\/url\n\/\/\n\n\/\/ Test that header file is self-contained.\n#include <boost\/url\/rfc\/userinfo_bnf.hpp>\n\n#include <boost\/url\/bnf\/parse.hpp>\n#include \"test_suite.hpp\"\n#include \"test_bnf.hpp\"\n\nnamespace boost {\nnamespace urls {\n\nclass userinfo_bnf_test\n{\npublic:\n    void\n    check(\n        string_view s,\n        string_view s1,\n        string_view s2,\n        bool check_s2 = true)\n    {\n        userinfo_bnf t;\n        error_code ec;\n        if(! BOOST_TEST(\n            bnf::parse_string(s, ec, t)))\n            return;\n        if(! BOOST_TEST(! ec))\n            return;\n        BOOST_TEST(t.user.str == s1);\n        if(check_s2)\n        {\n            BOOST_TEST(\n                t.has_password &&\n                t.password.str == s2);\n        }\n        else\n        {\n            BOOST_TEST(! t.has_password);\n        }\n    }\n\n    void\n    run()\n    {\n        using T = userinfo_bnf;\n\n        bad<T> (\"@\");\n\n        good<T>(\"\");\n        good<T>(\"x\");\n        good<T>(\"xy\");\n        good<T>(\"x:\");\n        good<T>(\"x:y\");\n        good<T>(\"x:y:\");\n        good<T>(\"x:y:z\");\n        good<T>(\"%41\");\n\n        check(\"x\",      \"x\",  \"\", false);\n        check(\"x:\",     \"x\",  \"\");\n        check(\":\",      \"\",   \"\");\n        check(\"::\",     \"\",   \":\");\n        check(\":x\",     \"\",   \"x\");\n        check(\"x:y\",    \"x\",  \"y\");\n        check(\"xy:zz:\", \"xy\", \"zz:\");\n        check(\n            \"%41%42:%43%44\", \"%41%42\", \"%43%44\");\n    }\n};\n\nTEST_SUITE(\n    userinfo_bnf_test,\n    \"boost.url.userinfo_bnf\");\n\n} \/\/ urls\n} \/\/ boost\n","avg_line_length":21.4880952381,"max_line_length":79,"alphanum_fraction":0.4770083102,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1404,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\ufeff\/*\n* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\").\n* You may not use this file except in compliance with the License.\n* A copy of the License is located at\n*\n*  http:\/\/aws.amazon.com\/apache2.0\n*\n* or in the \"license\" file accompanying this file. This file is distributed\n* on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n* express or implied. See the License for the specific language governing\n* permissions and limitations under the License.\n*\/\n\n#include <aws\/kms\/model\/CancelKeyDeletionResult.h>\n#include <aws\/core\/utils\/json\/JsonSerializer.h>\n#include <aws\/core\/AmazonWebServiceResult.h>\n#include <aws\/core\/utils\/StringUtils.h>\n#include <aws\/core\/utils\/UnreferencedParam.h>\n\n#include <utility>\n\nusing namespace Aws::KMS::Model;\nusing namespace Aws::Utils::Json;\nusing namespace Aws::Utils;\nusing namespace Aws;\n\nCancelKeyDeletionResult::CancelKeyDeletionResult()\n{\n}\n\nCancelKeyDeletionResult::CancelKeyDeletionResult(const Aws::AmazonWebServiceResult<JsonValue>& result)\n{\n  *this = result;\n}\n\nCancelKeyDeletionResult& CancelKeyDeletionResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)\n{\n  const JsonValue& jsonValue = result.GetPayload();\n  if(jsonValue.ValueExists(\"KeyId\"))\n  {\n    m_keyId = jsonValue.GetString(\"KeyId\");\n\n  }\n\n\n\n  return *this;\n}\n","avg_line_length":27.5294117647,"max_line_length":114,"alphanum_fraction":0.7621082621,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":265,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include<iostream>\nusing namespace std;\nint main()\n{\nchar x;\ncout<<\"give your alphabet\";\ncin>>x;\nif(x=='a'||x=='e'||x=='i'||x=='o'||x=='u'||x=='A'||x=='E'||x=='I'||x=='O'||x=='U')\ncout<<\"your alphabet is vowel\";\nelse\ncout<<\"your alphabet is consonent\";\nreturn 0;\n}\n","avg_line_length":18.9285714286,"max_line_length":82,"alphanum_fraction":0.5698113208,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":937,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include<bits\/stdc++.h>\nusing namespace std;\n\n#define fori(i,a,b) for (long int i = a; i <= b ; ++i)\n#define ford(i,a,b) for(long int i = a;i >= b ; --i)\n#define mk make_pair\n#define mod 1000000007\n#define pb push_back\n#define ll long long\n#define rnd mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count())\n#define pi pair<int,int>\n\nll dp[25][1001];\n\nint main()\n{\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL);\n\n  int n, m;\n  cin >> n >> m;\n  \/\/dp[i][n1] -- means no of ways to construct upto array[i] ending with n1\n  \/\/dp[i][n1] = sigma(dp[i-1][n1]+dp[i-1][n1-1]+......)\n  \/\/dp[1][n1] = 1\n\n  fori(i,1,n) {\n    dp[1][i] = 1;\n  }\n\n  fori(i,2,2*m) {\n    fori(j,1,n) {\n      fori(k,1,j) {\n        dp[i][j] = (dp[i][j]+dp[i-1][k])%mod;\n      }\n    }\n  }\n\n  ll ans = 0;\n  fori(i,1,n) {\n    \/\/ cout << i << \" \" << dp[2*m][i] << endl;\n    ans = (ans+dp[2*m][i])%mod;\n  }\n  cout << ans%mod << endl;\n  return 0;\n}\n","avg_line_length":20.3695652174,"max_line_length":91,"alphanum_fraction":0.5400213447,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11726,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Copyright (C) 2010 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <inttypes.h>\n\n\/\/#define LOG_NDEBUG 0\n#define LOG_TAG \"CameraSourceTimeLapse\"\n\n#include <binder\/IPCThreadState.h>\n#include <binder\/MemoryBase.h>\n#include <binder\/MemoryHeapBase.h>\n#include <media\/stagefright\/foundation\/ADebug.h>\n#include <media\/stagefright\/CameraSource.h>\n#include <media\/stagefright\/CameraSourceTimeLapse.h>\n#include <media\/stagefright\/MetaData.h>\n#include <camera\/Camera.h>\n#include <camera\/CameraParameters.h>\n#include <utils\/String8.h>\n#include <utils\/Vector.h>\n\nnamespace android {\n\n\/\/ static\nCameraSourceTimeLapse *CameraSourceTimeLapse::CreateFromCamera(\n        const sp<hardware::ICamera> &camera,\n        const sp<ICameraRecordingProxy> &proxy,\n        int32_t cameraId,\n        const String16& clientName,\n        uid_t clientUid,\n        pid_t clientPid,\n        Size videoSize,\n        int32_t videoFrameRate,\n        const sp<IGraphicBufferProducer>& surface,\n        int64_t timeBetweenFrameCaptureUs,\n        bool storeMetaDataInVideoBuffers) {\n\n    CameraSourceTimeLapse *source = new\n            CameraSourceTimeLapse(camera, proxy, cameraId,\n                clientName, clientUid, clientPid,\n                videoSize, videoFrameRate, surface,\n                timeBetweenFrameCaptureUs,\n                storeMetaDataInVideoBuffers);\n\n    if (source != NULL) {\n        if (source->initCheck() != OK) {\n            delete source;\n            return NULL;\n        }\n    }\n    return source;\n}\n\nCameraSourceTimeLapse::CameraSourceTimeLapse(\n        const sp<hardware::ICamera>& camera,\n        const sp<ICameraRecordingProxy>& proxy,\n        int32_t cameraId,\n        const String16& clientName,\n        uid_t clientUid,\n        pid_t clientPid,\n        Size videoSize,\n        int32_t videoFrameRate,\n        const sp<IGraphicBufferProducer>& surface,\n        int64_t timeBetweenFrameCaptureUs,\n        bool storeMetaDataInVideoBuffers)\n      : CameraSource(camera, proxy, cameraId, clientName, clientUid, clientPid,\n                videoSize, videoFrameRate, surface,\n                storeMetaDataInVideoBuffers),\n      mTimeBetweenTimeLapseVideoFramesUs(1E6\/videoFrameRate),\n      mLastTimeLapseFrameRealTimestampUs(0),\n      mSkipCurrentFrame(false) {\n\n    mTimeBetweenFrameCaptureUs = timeBetweenFrameCaptureUs;\n    ALOGD(\"starting time lapse mode: %\" PRId64 \" us\",\n        mTimeBetweenFrameCaptureUs);\n\n    mVideoWidth = videoSize.width;\n    mVideoHeight = videoSize.height;\n\n    if (OK == mInitCheck && !trySettingVideoSize(videoSize.width, videoSize.height)) {\n        releaseCamera();\n        mInitCheck = NO_INIT;\n    }\n\n    \/\/ Initialize quick stop variables.\n    mQuickStop = false;\n    mForceRead = false;\n    mLastReadBufferCopy = NULL;\n    mStopWaitingForIdleCamera = false;\n}\n\nCameraSourceTimeLapse::~CameraSourceTimeLapse() {\n    if (mLastReadBufferCopy) {\n        mLastReadBufferCopy->release();\n        mLastReadBufferCopy = NULL;\n    }\n}\n\nvoid CameraSourceTimeLapse::startQuickReadReturns() {\n    ALOGV(\"startQuickReadReturns\");\n    Mutex::Autolock autoLock(mQuickStopLock);\n\n    \/\/ Enable quick stop mode.\n    mQuickStop = true;\n\n    \/\/ Force dataCallbackTimestamp() coming from the video camera to\n    \/\/ not skip the next frame as we want read() to get a get a frame\n    \/\/ right away.\n    mForceRead = true;\n}\n\nbool CameraSourceTimeLapse::trySettingVideoSize(\n        int32_t width, int32_t height) {\n\n    ALOGV(\"trySettingVideoSize\");\n    int64_t token = IPCThreadState::self()->clearCallingIdentity();\n    String8 s = mCamera->getParameters();\n\n    CameraParameters params(s);\n    Vector<Size> supportedSizes;\n    params.getSupportedVideoSizes(supportedSizes);\n    bool videoOutputSupported = false;\n    if (supportedSizes.size() == 0) {\n        params.getSupportedPreviewSizes(supportedSizes);\n    } else {\n        videoOutputSupported = true;\n    }\n\n    bool videoSizeSupported = false;\n    for (size_t i = 0; i < supportedSizes.size(); ++i) {\n        int32_t pictureWidth = supportedSizes[i].width;\n        int32_t pictureHeight = supportedSizes[i].height;\n\n        if ((pictureWidth == width) && (pictureHeight == height)) {\n            videoSizeSupported = true;\n        }\n    }\n\n    bool isSuccessful = false;\n    if (videoSizeSupported) {\n        ALOGV(\"Video size (%d, %d) is supported\", width, height);\n        if (videoOutputSupported) {\n            params.setVideoSize(width, height);\n        } else {\n            params.setPreviewSize(width, height);\n        }\n        if (mCamera->setParameters(params.flatten()) == OK) {\n            isSuccessful = true;\n        } else {\n            ALOGE(\"Failed to set preview size to %dx%d\", width, height);\n            isSuccessful = false;\n        }\n    }\n\n    IPCThreadState::self()->restoreCallingIdentity(token);\n    return isSuccessful;\n}\n\nvoid CameraSourceTimeLapse::signalBufferReturned(MediaBufferBase* buffer) {\n    ALOGV(\"signalBufferReturned\");\n    Mutex::Autolock autoLock(mQuickStopLock);\n    if (mQuickStop && (buffer == mLastReadBufferCopy)) {\n        buffer->setObserver(NULL);\n        buffer->release();\n    } else {\n        return CameraSource::signalBufferReturned(buffer);\n    }\n}\n\nvoid createMediaBufferCopy(\n        const MediaBufferBase& sourceBuffer,\n        int64_t frameTime,\n        MediaBufferBase **newBuffer) {\n\n    ALOGV(\"createMediaBufferCopy\");\n    size_t sourceSize = sourceBuffer.size();\n    void* sourcePointer = sourceBuffer.data();\n\n    (*newBuffer) = new MediaBuffer(sourceSize);\n    memcpy((*newBuffer)->data(), sourcePointer, sourceSize);\n\n    (*newBuffer)->meta_data().setInt64(kKeyTime, frameTime);\n}\n\nvoid CameraSourceTimeLapse::fillLastReadBufferCopy(MediaBufferBase& sourceBuffer) {\n    ALOGV(\"fillLastReadBufferCopy\");\n    int64_t frameTime;\n    CHECK(sourceBuffer.meta_data().findInt64(kKeyTime, &frameTime));\n    createMediaBufferCopy(sourceBuffer, frameTime, &mLastReadBufferCopy);\n    mLastReadBufferCopy->add_ref();\n    mLastReadBufferCopy->setObserver(this);\n}\n\nstatus_t CameraSourceTimeLapse::read(\n        MediaBufferBase **buffer, const ReadOptions *options) {\n    ALOGV(\"read\");\n    if (mLastReadBufferCopy == NULL) {\n        mLastReadStatus = CameraSource::read(buffer, options);\n\n        \/\/ mQuickStop may have turned to true while read was blocked.\n        \/\/ Make a copy of the buffer in that case.\n        Mutex::Autolock autoLock(mQuickStopLock);\n        if (mQuickStop && *buffer) {\n            fillLastReadBufferCopy(**buffer);\n        }\n        return mLastReadStatus;\n    } else {\n        (*buffer) = mLastReadBufferCopy;\n        (*buffer)->add_ref();\n        return mLastReadStatus;\n    }\n}\n\nsp<IMemory> CameraSourceTimeLapse::createIMemoryCopy(\n        const sp<IMemory> &source_data) {\n\n    ALOGV(\"createIMemoryCopy\");\n    size_t source_size = source_data->size();\n    void* source_pointer = source_data->pointer();\n\n    sp<MemoryHeapBase> newMemoryHeap = new MemoryHeapBase(source_size);\n    sp<MemoryBase> newMemory = new MemoryBase(newMemoryHeap, 0, source_size);\n    memcpy(newMemory->pointer(), source_pointer, source_size);\n    return newMemory;\n}\n\nbool CameraSourceTimeLapse::skipCurrentFrame(int64_t \/* timestampUs *\/) {\n    ALOGV(\"skipCurrentFrame\");\n    if (mSkipCurrentFrame) {\n        mSkipCurrentFrame = false;\n        return true;\n    } else {\n        return false;\n    }\n}\n\nbool CameraSourceTimeLapse::skipFrameAndModifyTimeStamp(int64_t *timestampUs) {\n    ALOGV(\"skipFrameAndModifyTimeStamp\");\n    if (mLastTimeLapseFrameRealTimestampUs == 0) {\n        \/\/ First time lapse frame. Initialize mLastTimeLapseFrameRealTimestampUs\n        \/\/ to current time (timestampUs) and save frame data.\n        ALOGV(\"dataCallbackTimestamp timelapse: initial frame\");\n\n        mLastTimeLapseFrameRealTimestampUs = *timestampUs;\n        return false;\n    }\n\n    {\n        Mutex::Autolock autoLock(mQuickStopLock);\n\n        \/\/ mForceRead may be set to true by startQuickReadReturns(). In that\n        \/\/ case don't skip this frame.\n        if (mForceRead) {\n            ALOGV(\"dataCallbackTimestamp timelapse: forced read\");\n            mForceRead = false;\n            *timestampUs =\n                mLastFrameTimestampUs + mTimeBetweenTimeLapseVideoFramesUs;\n\n            \/\/ Really make sure that this video recording frame will not be dropped.\n            if (*timestampUs < mStartTimeUs) {\n                ALOGI(\"set timestampUs to start time stamp %\" PRId64 \" us\", mStartTimeUs);\n                *timestampUs = mStartTimeUs;\n            }\n            return false;\n        }\n    }\n\n    \/\/ Workaround to bypass the first 2 input frames for skipping.\n    \/\/ The first 2 output frames from the encoder are: decoder specific info and\n    \/\/ the compressed video frame data for the first input video frame.\n    if (mNumFramesEncoded >= 1 && *timestampUs <\n        (mLastTimeLapseFrameRealTimestampUs + mTimeBetweenFrameCaptureUs)) {\n        \/\/ Skip all frames from last encoded frame until\n        \/\/ sufficient time (mTimeBetweenFrameCaptureUs) has passed.\n        \/\/ Tell the camera to release its recording frame and return.\n        ALOGV(\"dataCallbackTimestamp timelapse: skipping intermediate frame\");\n        return true;\n    } else {\n        \/\/ Desired frame has arrived after mTimeBetweenFrameCaptureUs time:\n        \/\/ - Reset mLastTimeLapseFrameRealTimestampUs to current time.\n        \/\/ - Artificially modify timestampUs to be one frame time (1\/framerate) ahead\n        \/\/ of the last encoded frame's time stamp.\n        ALOGV(\"dataCallbackTimestamp timelapse: got timelapse frame\");\n\n        mLastTimeLapseFrameRealTimestampUs = *timestampUs;\n        *timestampUs = mLastFrameTimestampUs + mTimeBetweenTimeLapseVideoFramesUs;\n        return false;\n    }\n    return false;\n}\n\nvoid CameraSourceTimeLapse::dataCallbackTimestamp(int64_t timestampUs, int32_t msgType,\n            const sp<IMemory> &data) {\n    ALOGV(\"dataCallbackTimestamp\");\n    mSkipCurrentFrame = skipFrameAndModifyTimeStamp(&timestampUs);\n    CameraSource::dataCallbackTimestamp(timestampUs, msgType, data);\n}\n\nvoid CameraSourceTimeLapse::recordingFrameHandleCallbackTimestamp(int64_t timestampUs,\n            native_handle_t* handle) {\n    ALOGV(\"recordingFrameHandleCallbackTimestamp\");\n    mSkipCurrentFrame = skipFrameAndModifyTimeStamp(&timestampUs);\n    CameraSource::recordingFrameHandleCallbackTimestamp(timestampUs, handle);\n}\n\nvoid CameraSourceTimeLapse::recordingFrameHandleCallbackTimestampBatch(\n        const std::vector<int64_t>& timestampsUs,\n        const std::vector<native_handle_t*>& handles) {\n    ALOGV(\"recordingFrameHandleCallbackTimestampBatch\");\n    int n = timestampsUs.size();\n    for (int i = 0; i < n; i++) {\n        \/\/ Don't do batching for CameraSourceTimeLapse for now\n        recordingFrameHandleCallbackTimestamp(timestampsUs[i], handles[i]);\n    }\n}\n\nvoid CameraSourceTimeLapse::processBufferQueueFrame(BufferItem& buffer) {\n    ALOGV(\"processBufferQueueFrame\");\n    int64_t timestampUs = buffer.mTimestamp \/ 1000;\n    mSkipCurrentFrame = skipFrameAndModifyTimeStamp(&timestampUs);\n    buffer.mTimestamp = timestampUs * 1000;\n    CameraSource::processBufferQueueFrame(buffer);\n}\n\n}  \/\/ namespace android\n","avg_line_length":34.6923076923,"max_line_length":90,"alphanum_fraction":0.6857410882,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4418,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-3.0"],"max_stars_count":10.0,"content":"\/**********************************************************************\n\n  Audacity: A Digital Audio Editor\n\n  TracksBehaviorsPrefs.cpp\n\n  Steve Daulton\n\n\n*******************************************************************\/\/**\n\n\\class TracksBehaviorsPrefs\n\\brief A PrefsPanel for Tracks Behaviors settings.\n\n*\/\/*******************************************************************\/\n\n#include \"..\/Audacity.h\"\n#include \"TracksBehaviorsPrefs.h\"\n\n#include \"..\/Prefs.h\"\n#include \"..\/ShuttleGui.h\"\n\nTracksBehaviorsPrefs::TracksBehaviorsPrefs(wxWindow * parent, wxWindowID winid)\n\/* i18n-hint: i.e. the behaviors of tracks *\/\n:  PrefsPanel(parent, winid, XO(\"Tracks Behaviors\"))\n{\n   Populate();\n}\n\nTracksBehaviorsPrefs::~TracksBehaviorsPrefs()\n{\n}\n\nComponentInterfaceSymbol TracksBehaviorsPrefs::GetSymbol()\n{\n   return TRACKS_BEHAVIORS_PREFS_PLUGIN_SYMBOL;\n}\n\nTranslatableString TracksBehaviorsPrefs::GetDescription()\n{\n   return XO(\"Preferences for TracksBehaviors\");\n}\n\nwxString TracksBehaviorsPrefs::HelpPageName()\n{\n   return \"Tracks_Behaviors_Preferences\";\n}\n\nconst wxChar *TracksBehaviorsPrefs::ScrollingPreferenceKey()\n{\n   static auto string = wxT(\"\/GUI\/ScrollBeyondZero\");\n   return string;\n}\n\nvoid TracksBehaviorsPrefs::Populate()\n{\n   \/\/------------------------- Main section --------------------\n   \/\/ Now construct the GUI itself.\n   ShuttleGui S(this, eIsCreatingFromPrefs);\n   PopulateOrExchange(S);\n   \/\/ ----------------------- End of main section --------------\n}\n\nChoiceSetting TracksBehaviorsSolo{\n   wxT(\"\/GUI\/Solo\"),\n   {\n      ByColumns,\n      { XO(\"Simple\"),  XO(\"Multi-track\"), XO(\"None\") },\n      { wxT(\"Simple\"), wxT(\"Multi\"),      wxT(\"None\") }\n   },\n   0, \/\/ \"Simple\"\n};\n\nvoid TracksBehaviorsPrefs::PopulateOrExchange(ShuttleGui & S)\n{\n   S.SetBorder(2);\n   S.StartScroller();\n\n   S.StartStatic(XO(\"Behaviors\"));\n   {\n      S.TieCheckBox(XXO(\"&Select all audio, if selection required\"),\n                    {wxT(\"\/GUI\/SelectAllOnNone\"),\n                     false});\n      \/* i18n-hint: Cut-lines are lines that can expand to show the cut audio.*\/\n      S.TieCheckBox(XXO(\"Enable cut &lines\"),\n                    {wxT(\"\/GUI\/EnableCutLines\"),\n                     false});\n      S.TieCheckBox(XXO(\"Enable &dragging selection edges\"),\n                    {wxT(\"\/GUI\/AdjustSelectionEdges\"),\n                     true});\n      S.TieCheckBox(XXO(\"Editing a clip can &move other clips\"),\n                    {wxT(\"\/GUI\/EditClipCanMove\"),\n                     true});\n      S.TieCheckBox(XXO(\"\\\"Move track focus\\\" c&ycles repeatedly through tracks\"),\n                    {wxT(\"\/GUI\/CircularTrackNavigation\"),\n                     false});\n      S.TieCheckBox(XXO(\"&Type to create a label\"),\n                    {wxT(\"\/GUI\/TypeToCreateLabel\"),\n                     false});\n      S.TieCheckBox(XXO(\"Use dialog for the &name of a new label\"),\n                    {wxT(\"\/GUI\/DialogForNameNewLabel\"),\n                     false});\n#ifdef EXPERIMENTAL_SCROLLING_LIMITS\n      S.TieCheckBox(XXO(\"Enable scrolling left of &zero\"),\n                    {ScrollingPreferenceKey(),\n                     ScrollingPreferenceDefault()});\n#endif\n      S.TieCheckBox(XXO(\"Advanced &vertical zooming\"),\n                    {wxT(\"\/GUI\/VerticalZooming\"),\n                     false});\n\n      S.AddSpace(10);\n\n      S.StartMultiColumn(2);\n      {\n         S.TieChoice( XXO(\"Solo &Button:\"), TracksBehaviorsSolo);\n      }\n      S.EndMultiColumn();\n   }\n   S.EndStatic();\n   S.EndScroller();\n}\n\nbool TracksBehaviorsPrefs::Commit()\n{\n   ShuttleGui S(this, eIsSavingToPrefs);\n   PopulateOrExchange(S);\n\n   return true;\n}\n\nnamespace{\nPrefsPanel::Registration sAttachment{ \"TracksBehaviors\",\n   [](wxWindow *parent, wxWindowID winid, AudacityProject *)\n   {\n      wxASSERT(parent); \/\/ to justify safenew\n      return safenew TracksBehaviorsPrefs(parent, winid);\n   },\n   false,\n   \/\/ Place it at a lower tree level\n   { \"Tracks\" }\n};\n}\n\n\/\/ Bug 825 is essentially that SyncLock requires EditClipsCanMove.\n\/\/ SyncLock needs rethinking, but meanwhile this function\n\/\/ fixes the issues of Bug 825 by allowing clips to move when in\n\/\/ SyncLock.\nbool GetEditClipsCanMove()\n{\n   bool mIsSyncLocked;\n   gPrefs->Read(wxT(\"\/GUI\/SyncLockTracks\"), &mIsSyncLocked, false);\n   if( mIsSyncLocked )\n      return true;\n   bool editClipsCanMove;\n   gPrefs->Read(wxT(\"\/GUI\/EditClipCanMove\"), &editClipsCanMove, true);\n   return editClipsCanMove;\n}\n","avg_line_length":27.786163522,"max_line_length":82,"alphanum_fraction":0.5916704391,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":551,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*** Copyright (c), The Regents of the University of California            ***\n *** For more information please refer to files in the COPYRIGHT directory ***\/\n\/* This is script-generated code.  *\/\n\/* See dataPut.h for a description of this API call.*\/\n\n#include \"dataPut.hpp\"\n\nint\nrcDataPut( rcComm_t *conn, dataOprInp_t *dataPutInp,\n           portalOprOut_t **portalOprOut ) {\n    int status;\n    status = procApiRequest( conn, DATA_PUT_AN,  dataPutInp, NULL,\n                             ( void ** ) portalOprOut, NULL );\n\n    return ( status );\n}\n","avg_line_length":32.4117647059,"max_line_length":79,"alphanum_fraction":0.6333938294,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":631,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"#include <bits\/stdc++.h>\nusing namespace std;\n\n\nvector<string> res;\nchar E[] = \"ACGT\", str[17];\nvoid dfs(int idx, int cnt) {\n    if (!str[idx] || !cnt) {\n        res.push_back(str);\n        return;\n    }\n\n    char o = str[idx];\n    for (int i=0; i<4; ++i) {\n        str[idx] = E[i];\n        dfs(idx+1, cnt - (E[i] != o));\n    }\n    str[idx] = o;\n}\n\nint main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);\n\n    int T, n, c;\n    cin >> T;\n    while (T-- && cin >> n >> c >> str) {\n        res.clear();\n        dfs(0, c);\n        cout << res.size() << '\\n';\n        for (const string &s: res)\n            cout << s << '\\n';\n    }\n}\n","avg_line_length":18.5588235294,"max_line_length":44,"alphanum_fraction":0.4342313788,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4678,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-4.0"],"max_stars_count":null,"content":"\/\/ Copyright 2021 Tkachev Alexey\n\n#include <gtest\/gtest.h>\n\n#include <vector>\n#include <string>\n\n#include \"include\/app_connectivity_components.h\"\n\nTEST(Tkachev_connectivity_comp_app, creating) {\n    ASSERT_NO_THROW(AppConnComponents());\n}\n\nTEST(Tkachev_connectivity_comp_app, no_args) {\n    std::vector<const char*> argv {};\n    const int argc = static_cast<int>(argv.size());\n\n    AppConnComponents app;\n\n    const std::string true_result = AppConnComponents::help();\n\n    ASSERT_EQ(true_result, app(argc, argv.data()));\n}\n\nTEST(Tkachev_connectivity_comp_app, only_arg) {\n    std::vector<const char*> argv {\n        \"app\"\n    };\n    const int argc = static_cast<int>(argv.size());\n\n    AppConnComponents app;\n\n    const std::string true_result = AppConnComponents::help();\n\n    ASSERT_EQ(true_result, app(argc, argv.data()));\n}\n\nTEST(Tkachev_connectivity_comp_app, invalid_arg) {\n    std::vector<const char*> argv {\n        \"app\",\n        \"something_wrong\"\n    };\n    const int argc = static_cast<int>(argv.size());\n\n    AppConnComponents app;\n\n    const std::string true_result = \"invalid arguments\";\n\n    ASSERT_EQ(true_result, app(argc, argv.data()));\n}\n\nTEST(Tkachev_connectivity_comp_app, invalid_arg_number) {\n    std::vector<const char*> argv = {\n            \"app\",\n            \"set\", \"- 1+\", \"2\", \"3\"\n    };\n    const int argc = static_cast<int>(argv.size());\n\n    AppConnComponents app;\n\n    const std::string true_result = \"invalid arguments\";\n\n    ASSERT_EQ(true_result, app(argc, argv.data()));\n}\n\nTEST(Tkachev_connectivity_comp_app, create_set_get) {\n    std::vector<const char*> argv {\n        \"app\",\n        \"create\", \"3\",\n        \"set\",  \"1\", \"1\", \"2\",\n        \"get\", \"1\", \"2\"\n    };\n    const int argc = static_cast<int>(argv.size());\n\n    AppConnComponents app;\n\n    const std::string true_result = \"1\";\n\n    ASSERT_EQ(true_result, app(argc, argv.data()));\n}\n\n\nTEST(Tkachev_connectivity_comp_app, set_get_false) {\n    std::vector<const char*> argv {\n            \"app\",\n            \"create\", \"3\",\n            \"set\",  \"0\", \"1\", \"2\",\n            \"get\", \"1\", \"2\"\n    };\n    const int argc = static_cast<int>(argv.size());\n\n    AppConnComponents app;\n\n    const std::string false_result = \"1\";\n\n    ASSERT_EQ(false, false_result == app(argc, argv.data()));\n}\n\nTEST(Tkachev_connectivity_comp_app, many_set) {\n    std::vector<const char*> argv {\n            \"app\",\n            \"create\", \"5\",\n            \"set\",  \"1\", \"1\", \"2\",\n            \"set\", \"0\", \"1\", \"2\",\n            \"get\", \"1\", \"2\",\n    };\n    const int argc = static_cast<int>(argv.size());\n\n    AppConnComponents app;\n\n    const std::string false_result = \"0\";\n\n    ASSERT_EQ(false_result, app(argc, argv.data()));\n}\n\nTEST(Tkachev_connectivity_components_app, get_count_comp) {\n    \/\/ analog of Pestreev's some_simple_graph test\n\n    std::vector<const char*> argv {\n            \"app\",\n            \"create\", \"7\",\n            \"set\",  \"1\", \"0\", \"2\",\n            \"set\",  \"1\", \"0\", \"3\",\n            \"set\",  \"1\", \"1\", \"3\",\n            \"set\",  \"1\", \"2\", \"0\",\n            \"set\",  \"1\", \"3\", \"0\",\n            \"set\",  \"1\", \"3\", \"1\",\n            \"set\",  \"1\", \"4\", \"6\",\n            \"set\",  \"1\", \"6\", \"4\",\n            \"getcountcomps\"\n    };\n\n    const int argc = static_cast<int>(argv.size());\n\n    AppConnComponents app;\n    const std::string result = app(argc, argv.data());\n    const std::string true_result = \"3\";\n\n    ASSERT_EQ(true_result, result);\n}\n\nTEST(Tkachev_connectivity_components_app, append_n_get_size) {\n    \/\/ analog of Pestreev's some_simple_graph test\n\n    std::vector<const char*> argv {\n            \"app\",\n            \"create\", \"5\",\n            \"append\",\n            \"size\"\n    };\n\n    const int argc = static_cast<int>(argv.size());\n\n    AppConnComponents app;\n\n    const std::string result = app(argc, argv.data());\n    const std::string true_result = \"6\";\n\n    ASSERT_EQ(true_result, result);\n}\n\nTEST(Tkachev_connectivity_components_app, multi_graph) {\n    \/\/ analog of Pestreev's some_simple_graph test\n    \/\/ but with multi nodes;\n    \/\/ count_components NEED TO BE the same;\n\n    std::vector<const char*> argv {\n            \"app\",\n            \"create\", \"7\",\n            \"set\",  \"2\", \"0\", \"2\",\n            \"set\",  \"1\", \"0\", \"3\",\n            \"set\",  \"2\", \"1\", \"3\",\n            \"set\",  \"1\", \"2\", \"0\",\n            \"set\",  \"2\", \"3\", \"0\",\n            \"set\",  \"1\", \"3\", \"1\",\n            \"set\",  \"2\", \"4\", \"6\",\n            \"set\",  \"1\", \"6\", \"4\",\n            \"getcountcomps\"\n    };\n\n    const int argc = static_cast<int>(argv.size());\n\n    AppConnComponents app;\n    const std::string result = app(argc, argv.data());\n    const std::string true_result = \"3\";\n\n    ASSERT_EQ(true_result, result);\n}\n\n\n\n\n","avg_line_length":24.2383419689,"max_line_length":62,"alphanum_fraction":0.5566481402,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":26917,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT","Apache-2.0","CC-BY-4.0","Unlicense"],"max_stars_count":null,"content":"\/*************************************************************************\/\n\/*  line_builder.cpp                                                     *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"line_builder.h\"\n\n\/\/----------------------------------------------------------------------------\n\/\/ Util\n\/\/----------------------------------------------------------------------------\n\n#define PUSH_BACK_IF(nm, op)                             \\\n\ttemplate <typename T>                                \\\n\tvoid push_back_if_##nm(Vector<T> &p_arr, T p_elem) { \\\n\t\tif (p_elem op)                                   \\\n\t\t\tp_arr.push_back(p_elem);                     \\\n\t}\n\nPUSH_BACK_IF(gtzero, > 0);\nPUSH_BACK_IF(nonzero, != 0);\nPUSH_BACK_IF(lezero, < 0);\n\nenum SegmentIntersectionResult {\n\tSEGMENT_PARALLEL = 0,\n\tSEGMENT_NO_INTERSECT = 1,\n\tSEGMENT_INTERSECT = 2\n};\n\nstatic SegmentIntersectionResult segment_intersection(\n\t\tVector2 a, Vector2 b, Vector2 c, Vector2 d,\n\t\tVector2 *out_intersection) {\n\t\/\/ http:\/\/paulbourke.net\/geometry\/pointlineplane\/ <-- Good stuff\n\tVector2 cd = d - c;\n\tVector2 ab = b - a;\n\tfloat div = cd.y * ab.x - cd.x * ab.y;\n\n\tif (Math::abs(div) > 0.001f) {\n\t\tfloat ua = (cd.x * (a.y - c.y) - cd.y * (a.x - c.x)) \/ div;\n\t\tfloat ub = (ab.x * (a.y - c.y) - ab.y * (a.x - c.x)) \/ div;\n\t\t*out_intersection = a + ua * ab;\n\t\tif (ua >= 0.f && ua <= 1.f &&\n\t\t\t\tub >= 0.f && ub <= 1.f) {\n\t\t\treturn SEGMENT_INTERSECT;\n\t\t}\n\t\treturn SEGMENT_NO_INTERSECT;\n\t}\n\n\treturn SEGMENT_PARALLEL;\n}\n\nstatic Vector2 Failed(NAN, NAN);\n\nstatic Vector2 find_intersection(const Vector2 &p0, const Vector2 &p1, const Vector2 &p2, const Vector2 &p3) {\n\tconst real_t s10_x = p1.x - p0.x;\n\tconst real_t s10_y = p1.y - p0.y;\n\tconst real_t s32_x = p3.x - p2.x;\n\tconst real_t s32_y = p3.y - p2.y;\n\n\tconst real_t denom = s10_x * s32_y - s32_x * s10_y;\n\n\tif (denom == 0)\n\t\treturn Failed; \/\/ collinear\n\n\tconst bool denom_is_positive = denom > 0;\n\n\tconst real_t s02_x = p0.x - p2.x;\n\tconst real_t s02_y = p0.y - p2.y;\n\n\tconst real_t s_numer = s10_x * s02_y - s10_y * s02_x;\n\n\tif ((s_numer < 0) == denom_is_positive)\n\t\treturn Failed; \/\/ no collision\n\n\tconst real_t t_numer = s32_x * s02_y - s32_y * s02_x;\n\n\tif ((t_numer < 0) == denom_is_positive)\n\t\treturn Failed; \/\/ no collision\n\tif ((s_numer > denom) == denom_is_positive || (t_numer > denom) == denom_is_positive)\n\t\treturn Failed; \/\/ no collision\n\n\t\/\/ collision detected\n\n\tconst real_t t = t_numer \/ denom;\n\treturn Vector2(p0.x + (t * s10_x), p0.y + (t * s10_y));\n}\n\n\/\/ TODO I'm pretty sure there is an even faster way to swap things\ntemplate <typename T>\nstatic inline void swap(T &a, T &b) {\n\tT tmp = a;\n\ta = b;\n\tb = tmp;\n}\n\nstatic float calculate_total_distance(const Vector<Vector2> &points) {\n\tfloat d = 0.f;\n\tfor (int i = 1; i < points.size(); ++i) {\n\t\td += points[i].distance_to(points[i - 1]);\n\t}\n\treturn d;\n}\n\nstatic inline Vector2 rotate90(const Vector2 &v) {\n\t\/\/ Note: the 2D referential is X-right, Y-down\n\treturn Vector2(v.y, -v.x);\n}\n\nstatic inline Vector2 interpolate(const Rect2 &r, const Vector2 &v) {\n\treturn Vector2(\n\t\t\tMath::lerp(r.position.x, r.position.x + r.get_size().x, v.x),\n\t\t\tMath::lerp(r.position.y, r.position.y + r.get_size().y, v.y));\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ LineBuilder\n\/\/----------------------------------------------------------------------------\n\nLineBuilder::LineBuilder() {\n\tjoint_mode = Line2D::LINE_JOINT_SHARP;\n\twidth = 10;\n\tcurve = nullptr;\n\tdefault_color = Color(0.4, 0.5, 1);\n\tgradient = nullptr;\n\tsharp_limit = 2.f;\n\tround_precision = 8;\n\tbegin_cap_mode = Line2D::LINE_CAP_NONE;\n\tend_cap_mode = Line2D::LINE_CAP_NONE;\n\ttile_aspect = 1.f;\n\ttile_region = Rect2(0, 0, 1.f, 1.f);\n\n\t_interpolate_color = false;\n\t_last_index[0] = 0;\n\t_last_index[1] = 0;\n}\n\nvoid LineBuilder::clear_output() {\n\tvertices.clear();\n\tcolors.clear();\n\tindices.clear();\n\tuvs.clear();\n}\n\nvoid LineBuilder::build() {\n\t\/\/ Need at least 2 points to draw a line\n\tif (points.size() < 2) {\n\t\tclear_output();\n\t\treturn;\n\t}\n\n\tERR_FAIL_COND(tile_aspect <= 0.f);\n\n\tconst float hw = width \/ 2.f;\n\tconst float hw_sq = hw * hw;\n\tconst float sharp_limit_sq = sharp_limit * sharp_limit;\n\tconst int len = points.size();\n\n\t\/\/ Initial values\n\n\tVector2 pos0 = points[0];\n\tVector2 pos1 = points[1];\n\tVector2 f0 = (pos1 - pos0).normalized();\n\tVector2 u0 = rotate90(f0);\n\tVector2 pos_up0 = pos0;\n\tVector2 pos_down0 = pos0;\n\n\tColor color0;\n\tColor color1;\n\n\tfloat current_distance0 = 0.f;\n\tfloat current_distance1 = 0.f;\n\tfloat total_distance = 0.f;\n\tfloat width_factor = 1.f;\n\t_interpolate_color = gradient != nullptr;\n\t_repeat_segment = tile_region != Rect2(0, 0, 1.f, 1.f);\n\t_last_uvx = 0;\n\tbool retrieve_curve = curve != nullptr;\n\tbool distance_required = _interpolate_color ||\n\t\t\tretrieve_curve ||\n\t\t\ttexture_mode == Line2D::LINE_TEXTURE_TILE ||\n\t\t\ttexture_mode == Line2D::LINE_TEXTURE_STRETCH;\n\tif (distance_required) {\n\t\ttotal_distance = calculate_total_distance(points);\n\t\t\/\/ Adjust totalDistance.\n\t\t\/\/ The line's outer length will be a little higher due to begin and end caps\n\t\tif (begin_cap_mode == Line2D::LINE_CAP_BOX || begin_cap_mode == Line2D::LINE_CAP_ROUND) {\n\t\t\tif (retrieve_curve) {\n\t\t\t\ttotal_distance += width * curve->interpolate_baked(0.f) * 0.5f;\n\t\t\t} else {\n\t\t\t\ttotal_distance += width * 0.5f;\n\t\t\t}\n\t\t}\n\t\tif (end_cap_mode == Line2D::LINE_CAP_BOX || end_cap_mode == Line2D::LINE_CAP_ROUND) {\n\t\t\tif (retrieve_curve) {\n\t\t\t\ttotal_distance += width * curve->interpolate_baked(1.f) * 0.5f;\n\t\t\t} else {\n\t\t\t\ttotal_distance += width * 0.5f;\n\t\t\t}\n\t\t}\n\t}\n\tif (_interpolate_color) {\n\t\tcolor0 = gradient->get_color(0);\n\t} else {\n\t\tcolors.push_back(default_color);\n\t}\n\n\tfloat uvx0 = 0.f;\n\tfloat uvx1 = 0.f;\n\n\tif (retrieve_curve) {\n\t\twidth_factor = curve->interpolate_baked(0.f);\n\t}\n\n\tpos_up0 += u0 * hw * width_factor;\n\tpos_down0 -= u0 * hw * width_factor;\n\n\t\/\/ Begin cap\n\tif (begin_cap_mode == Line2D::LINE_CAP_BOX) {\n\t\t\/\/ Push back first vertices a little bit\n\t\tpos_up0 -= f0 * hw * width_factor;\n\t\tpos_down0 -= f0 * hw * width_factor;\n\n\t\tcurrent_distance0 += hw * width_factor;\n\t\tcurrent_distance1 = current_distance0;\n\t} else if (begin_cap_mode == Line2D::LINE_CAP_ROUND) {\n\t\tif (texture_mode == Line2D::LINE_TEXTURE_TILE) {\n\t\t\tuvx0 = width_factor * 0.5f \/ tile_aspect;\n\t\t} else if (texture_mode == Line2D::LINE_TEXTURE_STRETCH) {\n\t\t\tuvx0 = width * width_factor \/ total_distance;\n\t\t}\n\t\tnew_arc(pos0, pos_up0 - pos0, -Math_PI, color0, Rect2(0.f, 0.f, uvx0 * 2, 1.f));\n\t\tcurrent_distance0 += hw * width_factor;\n\t\tcurrent_distance1 = current_distance0;\n\t}\n\n\tstrip_begin(pos_up0, pos_down0, color0, uvx0);\n\n\t\/*\n\t *  pos_up0 ------------- pos_up1 --------------------\n\t *     |                     |\n\t *   pos0 - - - - - - - - - pos1 - - - - - - - - - pos2\n\t *     |                     |\n\t * pos_down0 ------------ pos_down1 ------------------\n\t *\n\t *   i-1                     i                      i+1\n\t *\/\n\n\t\/\/ http:\/\/labs.hyperandroid.com\/tag\/opengl-lines\n\t\/\/ (not the same implementation but visuals help a lot)\n\n\t\/\/ For each additional segment\n\tfor (int i = 1; i < len - 1; ++i) {\n\t\tpos1 = points[i];\n\t\tVector2 pos2 = points[i + 1];\n\n\t\tVector2 f1 = (pos2 - pos1).normalized();\n\t\tVector2 u1 = rotate90(f1);\n\n\t\t\/\/ Determine joint orientation\n\t\tconst float dp = u0.dot(f1);\n\t\tconst Orientation orientation = (dp > 0.f ? UP : DOWN);\n\n\t\tif (distance_required) {\n\t\t\tcurrent_distance1 += pos0.distance_to(pos1);\n\t\t}\n\t\tif (_interpolate_color) {\n\t\t\tcolor1 = gradient->get_color_at_offset(current_distance1 \/ total_distance);\n\t\t}\n\t\tif (retrieve_curve) {\n\t\t\twidth_factor = curve->interpolate_baked(current_distance1 \/ total_distance);\n\t\t}\n\n\t\tVector2 inner_normal0, inner_normal1;\n\t\tif (orientation == UP) {\n\t\t\tinner_normal0 = u0 * hw * width_factor;\n\t\t\tinner_normal1 = u1 * hw * width_factor;\n\t\t} else {\n\t\t\tinner_normal0 = -u0 * hw * width_factor;\n\t\t\tinner_normal1 = -u1 * hw * width_factor;\n\t\t}\n\n\t\t\/*\n\t\t * ---------------------------\n\t\t *                        \/\n\t\t * 0                     \/    1\n\t\t *                      \/          \/\n\t\t * --------------------x------    \/\n\t\t *                    \/          \/    (here shown with orientation == DOWN)\n\t\t *                   \/          \/\n\t\t *                  \/          \/\n\t\t *                 \/          \/\n\t\t *                     2     \/\n\t\t *                          \/\n\t\t *\/\n\n\t\t\/\/ Find inner intersection at the joint\n\t\tVector2 corner_pos_in, corner_pos_out;\n\t\tSegmentIntersectionResult intersection_result = segment_intersection(\n\t\t\t\tpos0 + inner_normal0, pos1 + inner_normal0,\n\t\t\t\tpos1 + inner_normal1, pos2 + inner_normal1,\n\t\t\t\t&corner_pos_in);\n\n\t\tif (intersection_result == SEGMENT_INTERSECT) {\n\t\t\t\/\/ Inner parts of the segments intersect\n\t\t\tcorner_pos_out = 2.f * pos1 - corner_pos_in;\n\t\t} else {\n\t\t\t\/\/ No intersection, segments are either parallel or too sharp\n\t\t\tcorner_pos_in = pos1 + inner_normal0;\n\t\t\tcorner_pos_out = pos1 - inner_normal0;\n\t\t}\n\n\t\tVector2 corner_pos_up, corner_pos_down;\n\t\tif (orientation == UP) {\n\t\t\tcorner_pos_up = corner_pos_in;\n\t\t\tcorner_pos_down = corner_pos_out;\n\t\t} else {\n\t\t\tcorner_pos_up = corner_pos_out;\n\t\t\tcorner_pos_down = corner_pos_in;\n\t\t}\n\n\t\tLine2D::LineJointMode current_joint_mode = joint_mode;\n\n\t\tVector2 pos_up1, pos_down1;\n\t\tif (intersection_result == SEGMENT_INTERSECT) {\n\t\t\t\/\/ Fallback on bevel if sharp angle is too high (because it would produce very long miters)\n\t\t\tfloat width_factor_sq = width_factor * width_factor;\n\t\t\tif (current_joint_mode == Line2D::LINE_JOINT_SHARP && corner_pos_out.distance_squared_to(pos1) \/ (hw_sq * width_factor_sq) > sharp_limit_sq) {\n\t\t\t\tcurrent_joint_mode = Line2D::LINE_JOINT_BEVEL;\n\t\t\t}\n\t\t\tif (current_joint_mode == Line2D::LINE_JOINT_SHARP) {\n\t\t\t\t\/\/ In this case, we won't create joint geometry,\n\t\t\t\t\/\/ The previous and next line quads will directly share an edge.\n\t\t\t\tpos_up1 = corner_pos_up;\n\t\t\t\tpos_down1 = corner_pos_down;\n\t\t\t} else {\n\t\t\t\t\/\/ Bevel or round\n\t\t\t\tif (orientation == UP) {\n\t\t\t\t\tpos_up1 = corner_pos_up;\n\t\t\t\t\tpos_down1 = pos1 - u0 * hw * width_factor;\n\t\t\t\t} else {\n\t\t\t\t\tpos_up1 = pos1 + u0 * hw * width_factor;\n\t\t\t\t\tpos_down1 = corner_pos_down;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ No intersection: fallback\n\t\t\tif (current_joint_mode == Line2D::LINE_JOINT_SHARP) {\n\t\t\t\t\/\/ There is no fallback implementation for LINE_JOINT_SHARP so switch to the LINE_JOINT_BEVEL\n\t\t\t\tcurrent_joint_mode = Line2D::LINE_JOINT_BEVEL;\n\t\t\t}\n\t\t\tpos_up1 = corner_pos_up;\n\t\t\tpos_down1 = corner_pos_down;\n\t\t}\n\n\t\t\/\/ Add current line body quad\n\t\t\/\/ Triangles are clockwise\n\t\tif (texture_mode == Line2D::LINE_TEXTURE_TILE) {\n\t\t\tuvx1 = current_distance1 \/ (width * tile_aspect);\n\t\t} else if (texture_mode == Line2D::LINE_TEXTURE_STRETCH) {\n\t\t\tuvx1 = current_distance1 \/ total_distance;\n\t\t}\n\n\t\tstrip_add_quad(pos_up1, pos_down1, color1, uvx1);\n\n\t\t\/\/ Swap vars for use in the next line\n\t\tcolor0 = color1;\n\t\tu0 = u1;\n\t\tf0 = f1;\n\t\tpos0 = pos1;\n\t\tif (intersection_result == SEGMENT_INTERSECT) {\n\t\t\tif (current_joint_mode == Line2D::LINE_JOINT_SHARP) {\n\t\t\t\tpos_up0 = pos_up1;\n\t\t\t\tpos_down0 = pos_down1;\n\t\t\t} else {\n\t\t\t\tif (orientation == UP) {\n\t\t\t\t\tpos_up0 = corner_pos_up;\n\t\t\t\t\tpos_down0 = pos1 - u1 * hw * width_factor;\n\t\t\t\t} else {\n\t\t\t\t\tpos_up0 = pos1 + u1 * hw * width_factor;\n\t\t\t\t\tpos_down0 = corner_pos_down;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tpos_up0 = pos1 + u1 * hw * width_factor;\n\t\t\tpos_down0 = pos1 - u1 * hw * width_factor;\n\t\t}\n\t\t\/\/ From this point, bu0 and bd0 concern the next segment\n\n\t\t\/\/ Add joint geometry\n\t\tif (current_joint_mode != Line2D::LINE_JOINT_SHARP) {\n\t\t\t\/* ________________ cbegin\n\t\t\t *               \/ \\\n\t\t\t *              \/   \\\n\t\t\t * ____________\/_ _ _\\ cend\n\t\t\t *             |     |\n\t\t\t *             |     |\n\t\t\t *             |     |\n\t\t\t *\/\n\n\t\t\tVector2 cbegin, cend;\n\t\t\tif (orientation == UP) {\n\t\t\t\tcbegin = pos_down1;\n\t\t\t\tcend = pos_down0;\n\t\t\t} else {\n\t\t\t\tcbegin = pos_up1;\n\t\t\t\tcend = pos_up0;\n\t\t\t}\n\n\t\t\tif (current_joint_mode == Line2D::LINE_JOINT_BEVEL) {\n\t\t\t\tstrip_add_tri(cend, orientation);\n\t\t\t} else if (current_joint_mode == Line2D::LINE_JOINT_ROUND) {\n\t\t\t\tVector2 vbegin = cbegin - pos1;\n\t\t\t\tVector2 vend = cend - pos1;\n\t\t\t\tstrip_add_arc(pos1, vbegin.angle_to(vend), orientation);\n\t\t\t}\n\n\t\t\tif (intersection_result != SEGMENT_INTERSECT) {\n\t\t\t\t\/\/ In this case the joint is too corrputed to be re-used,\n\t\t\t\t\/\/ start again the strip with fallback points\n\t\t\t\tstrip_begin(pos_up0, pos_down0, color1, uvx1);\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Last (or only) segment\n\tpos1 = points[points.size() - 1];\n\n\tif (distance_required) {\n\t\tcurrent_distance1 += pos0.distance_to(pos1);\n\t}\n\tif (_interpolate_color) {\n\t\tcolor1 = gradient->get_color(gradient->get_points_count() - 1);\n\t}\n\tif (retrieve_curve) {\n\t\twidth_factor = curve->interpolate_baked(1.f);\n\t}\n\n\tVector2 pos_up1 = pos1 + u0 * hw * width_factor;\n\tVector2 pos_down1 = pos1 - u0 * hw * width_factor;\n\n\t\/\/ End cap (box)\n\tif (end_cap_mode == Line2D::LINE_CAP_BOX) {\n\t\tpos_up1 += f0 * hw * width_factor;\n\t\tpos_down1 += f0 * hw * width_factor;\n\t}\n\n\tif (texture_mode == Line2D::LINE_TEXTURE_TILE) {\n\t\tuvx1 = current_distance1 \/ (width * tile_aspect);\n\t} else if (texture_mode == Line2D::LINE_TEXTURE_STRETCH) {\n\t\tuvx1 = current_distance1 \/ total_distance;\n\t}\n\n\tstrip_add_quad(pos_up1, pos_down1, color1, uvx1);\n\n\t\/\/ End cap (round)\n\tif (end_cap_mode == Line2D::LINE_CAP_ROUND) {\n\t\t\/\/ Note: color is not used in case we don't interpolate...\n\t\tColor color = _interpolate_color ? gradient->get_color(gradient->get_points_count() - 1) : Color(0, 0, 0);\n\t\tfloat dist = 0;\n\t\tif (texture_mode == Line2D::LINE_TEXTURE_TILE) {\n\t\t\tdist = width_factor \/ tile_aspect;\n\t\t} else if (texture_mode == Line2D::LINE_TEXTURE_STRETCH) {\n\t\t\tdist = width * width_factor \/ total_distance;\n\t\t}\n\t\tnew_arc(pos1, pos_up1 - pos1, Math_PI, color, Rect2(uvx1 - 0.5f * dist, 0.f, dist, 1.f));\n\t}\n\n\tif (!_repeat_segment)\n\t\treturn;\n\n\tconst real_t sx = tile_region.position.x;\n\tconst real_t sy = tile_region.position.y;\n\tconst real_t sw = tile_region.size.x;\n\tconst real_t sh = tile_region.size.y;\n\t\/\/ rescale uvs values\n\tfor (int i = 0; i < uvs.size(); i++) {\n\t\tuvs.write[i] = Vector2(sx + uvs[i].x * sw, sy + uvs[i].y * sh);\n\t}\n}\n\nvoid LineBuilder::strip_begin(Vector2 up, Vector2 down, Color color, float uvx) {\n\tint vi = vertices.size();\n\n\tvertices.push_back(up, down);\n\n\tif (_interpolate_color) {\n\t\tcolors.push_back(color, color);\n\t}\n\n\tif (texture_mode != Line2D::LINE_TEXTURE_NONE) {\n\t\tuvs.push_back(Vector2(uvx, 0.f), Vector2(uvx, 1.f));\n\t}\n\n\t_last_index[UP] = vi;\n\t_last_index[DOWN] = vi + 1;\n}\n\nvoid LineBuilder::strip_new_quad(Vector2 up, Vector2 down, Color color, float uvx) {\n\tint vi = vertices.size();\n\n\tvertices.push_back(vertices[_last_index[UP]], vertices[_last_index[DOWN]]);\n\tvertices.push_back(up, down);\n\n\tif (_interpolate_color) {\n\t\tcolors.push_multi(4, color);\n\t}\n\n\tif (texture_mode != Line2D::LINE_TEXTURE_NONE) {\n\t\tuvs.push_back(uvs[_last_index[UP]], uvs[_last_index[DOWN]]);\n\t\tuvs.push_back(Vector2(uvx, UP), Vector2(uvx, DOWN));\n\t}\n\n\tindices.push_back(vi, vi + 3, vi + 1);\n\tindices.push_back(vi, vi + 2, vi + 3);\n\n\t_last_index[UP] = vi + 2;\n\t_last_index[DOWN] = vi + 3;\n}\n\nvoid LineBuilder::strip_add_quad(Vector2 up, Vector2 down, Color color, float uvx) {\n\tint vi = vertices.size();\n\n\tif (uvx > 1 && _repeat_segment && vertices.size() && texture_mode == Line2D::LINE_TEXTURE_TILE) {\n\t\tconst float last_remainings = ceil(_last_uvx) - _last_uvx; \/\/ remainings of the last tile\n\t\tconst float dist = uvx - _last_uvx;\n\n\t\t\/\/ split dist (excluding remaining part of the last tile) on texture tile, eg:\n\t\t\/\/ [0,1] ................ [2,2] ................ [3,3]\n\t\t\/\/ [0,1] .. 1|0 .. 1|0 .. [0,2] .. 1|0 .. 1|0 .. [0.3]\n\t\tVector2 prev_down = vertices.last(0);\n\t\tVector2 prev_up = vertices.last(1);\n\t\tVector2 step_down = (down - prev_down) \/ dist;\n\t\tVector2 step_up = (up - prev_up) \/ dist;\n\t\tColor prev_color = _interpolate_color ? colors.last() : Color();\n\n\t\tconst bool is_last_remains = last_remainings > 0;\n\t\tconst int segs = floor(dist - last_remainings) + is_last_remains;\n\t\tconst Vector2 full_quad[] = { Vector2(1.f, 0.f), Vector2(1.f, 1.f), Vector2(0.f, 0.f), Vector2(0.f, 1.f) };\n\n\t\tfor (int s = 0; s < segs; s++) {\n\t\t\tif (s == 0 && is_last_remains) {\n\t\t\t\tprev_up += step_up * last_remainings;\n\t\t\t\tprev_down += step_down * last_remainings;\n\t\t\t} else {\n\t\t\t\tprev_up += step_up;\n\t\t\t\tprev_down += step_down;\n\t\t\t}\n\t\t\tvertices.push_back(prev_up, prev_down, prev_up, prev_down);\n\t\t\tif (_interpolate_color) {\n\t\t\t\tconst float t = s \/ dist;\n\t\t\t\tColor curr_color = prev_color.linear_interpolate(color, t);\n\t\t\t\tcolors.push_multi(4, curr_color);\n\t\t\t}\n\n\t\t\tuvs.append_array(4, full_quad);\n\n\t\t\tindices.push_back(_last_index[UP], vi + 1, _last_index[DOWN]);\n\t\t\tindices.push_back(_last_index[UP], vi, vi + 1);\n\n\t\t\t_last_index[UP] = vi;\n\t\t\t_last_index[DOWN] = vi + 1;\n\n\t\t\tvi += 2;\n\n\t\t\tindices.push_back(_last_index[UP], vi + 1, _last_index[DOWN]);\n\t\t\tindices.push_back(_last_index[UP], vi, vi + 1);\n\n\t\t\t_last_index[UP] = vi;\n\t\t\t_last_index[DOWN] = vi + 1;\n\n\t\t\tvi += 2;\n\t\t}\n\t\t_last_uvx = uvx;\n\n\t\t\/\/ remaining part\n\t\tuvx -= floor(uvx);\n\t\t\/\/ nothing left to drawn\n\t\tif (uvx == 0)\n\t\t\treturn;\n\t}\n\n\tvertices.push_back(up, down);\n\n\tif (_interpolate_color) {\n\t\tcolors.push_multi(2, color);\n\t}\n\n\tif (texture_mode != Line2D::LINE_TEXTURE_NONE) {\n\t\tuvs.push_back(Vector2(uvx, 0.f), Vector2(uvx, 1.f));\n\t}\n\n\tindices.push_back(_last_index[UP], vi + 1, _last_index[DOWN]);\n\tindices.push_back(_last_index[UP], vi, vi + 1);\n\n\t_last_index[UP] = vi;\n\t_last_index[DOWN] = vi + 1;\n}\n\nvoid LineBuilder::strip_add_tri(Vector2 up, Orientation orientation) {\n\tint vi = vertices.size();\n\n\tvertices.push_back(up);\n\n\tif (_interpolate_color) {\n\t\tcolors.push_back(colors[colors.size() - 1]);\n\t}\n\n\tOrientation opposite_orientation = orientation == UP ? DOWN : UP;\n\n\tif (texture_mode != Line2D::LINE_TEXTURE_NONE) {\n\t\t\/\/ UVs are just one slice of the texture all along\n\t\t\/\/ (otherwise we can't share the bottom vertice)\n\t\tuvs.push_back(uvs[_last_index[opposite_orientation]]);\n\t}\n\n\tindices.push_back(_last_index[opposite_orientation], vi, _last_index[orientation]);\n\n\t_last_index[opposite_orientation] = vi;\n}\n\nvoid LineBuilder::strip_add_arc(Vector2 center, float angle_delta, Orientation orientation) {\n\t\/\/ Take the two last vertices and extrude an arc made of triangles\n\t\/\/ that all share one of the initial vertices\n\n\tOrientation opposite_orientation = orientation == UP ? DOWN : UP;\n\tVector2 vbegin = vertices[_last_index[opposite_orientation]] - center;\n\tfloat radius = vbegin.length();\n\tfloat angle_step = Math_PI \/ static_cast<float>(round_precision);\n\tfloat steps = Math::abs(angle_delta) \/ angle_step;\n\n\tif (angle_delta < 0.f) {\n\t\tangle_step = -angle_step;\n\t}\n\n\tfloat t = Vector2(1, 0).angle_to(vbegin);\n\tfloat end_angle = t + angle_delta;\n\tVector2 rpos(0, 0);\n\n\t\/\/ Arc vertices\n\tfor (int ti = 0; ti < steps; ++ti, t += angle_step) {\n\t\trpos = center + Vector2(Math::cos(t), Math::sin(t)) * radius;\n\t\tstrip_add_tri(rpos, orientation);\n\t}\n\n\t\/\/ Last arc vertice\n\trpos = center + Vector2(Math::cos(end_angle), Math::sin(end_angle)) * radius;\n\tstrip_add_tri(rpos, orientation);\n}\n\nvoid LineBuilder::new_arc(Vector2 center, Vector2 vbegin, float angle_delta, Color color, Rect2 uv_rect) {\n\tif (_repeat_segment && texture_mode == Line2D::LINE_TEXTURE_TILE) {\n\t\tnew_arc_tiled_geometry(center, vbegin, angle_delta, color, uv_rect);\n\t} else {\n\t\tnew_arc_tiled_texture(center, vbegin, angle_delta, color, uv_rect);\n\t}\n}\n\nvoid LineBuilder::new_arc_tiled_texture(Vector2 center, Vector2 vbegin, float angle_delta, Color color, Rect2 uv_rect) {\n\t\/\/ Make a standalone arc that doesn't use existing vertices,\n\t\/\/ with undistorted UVs from within a square section\n\n\tfloat radius = vbegin.length();\n\tfloat angle_step = Math_PI \/ static_cast<float>(round_precision);\n\tfloat steps = Math::abs(angle_delta) \/ angle_step;\n\n\tif (angle_delta < 0.f) {\n\t\tangle_step = -angle_step;\n\t}\n\n\tfloat t = Vector2(1, 0).angle_to(vbegin);\n\tfloat end_angle = t + angle_delta;\n\tfloat tt_begin = -Math_PI \/ 2.f;\n\tfloat tt = tt_begin;\n\n\t\/\/ Center vertice\n\tint vi = vertices.size();\n\tvertices.push_back(center);\n\tif (_interpolate_color) {\n\t\tcolors.push_back(color);\n\t}\n\tif (texture_mode != Line2D::LINE_TEXTURE_NONE) {\n\t\tuvs.push_back(interpolate(uv_rect, Vector2(0.5f, 0.5f)));\n\t}\n\n\t\/\/ Arc vertices\n\tfor (int ti = 0; ti < steps; ++ti, t += angle_step) {\n\t\tVector2 sc = Vector2(Math::cos(t), Math::sin(t));\n\t\tVector2 rpos = center + sc * radius;\n\n\t\tvertices.push_back(rpos);\n\t\tif (_interpolate_color) {\n\t\t\tcolors.push_back(color);\n\t\t}\n\t\tif (texture_mode != Line2D::LINE_TEXTURE_NONE) {\n\t\t\tVector2 tsc = Vector2(Math::cos(tt), Math::sin(tt));\n\t\t\tuvs.push_back(interpolate(uv_rect, 0.5f * (tsc + Vector2(1.f, 1.f))));\n\t\t\ttt += angle_step;\n\t\t}\n\t}\n\n\t\/\/ Last arc vertice\n\tVector2 sc = Vector2(Math::cos(end_angle), Math::sin(end_angle));\n\tVector2 rpos = center + sc * radius;\n\tvertices.push_back(rpos);\n\tif (_interpolate_color) {\n\t\tcolors.push_back(color);\n\t}\n\tif (texture_mode != Line2D::LINE_TEXTURE_NONE) {\n\t\ttt = tt_begin + angle_delta;\n\t\tVector2 tsc = Vector2(Math::cos(tt), Math::sin(tt));\n\t\tuvs.push_back(interpolate(uv_rect, 0.5f * (tsc + Vector2(1.f, 1.f))));\n\t}\n\n\t\/\/ Make up triangles\n\tint vi0 = vi;\n\tfor (int ti = 0; ti < steps; ++ti) {\n\t\tindices.push_back(vi0);\n\t\tindices.push_back(++vi);\n\t\tindices.push_back(vi + 1);\n\t}\n}\n\nvoid LineBuilder::new_arc_tiled_geometry(Vector2 center, Vector2 vbegin, float angle_delta, Color color, Rect2 uv_rect) {\n\t\/\/ Make a standalone arc that doesn't use existing vertices,\n\t\/\/ build with stripes not triangle fans,\n\t\/\/ with undistorted UVs from within a square section (possible spans across\n\t\/\/ multiple tiles)\n\n\t\/\/               *  stop\n\t\/\/              \/|\n\t\/\/             \/ |\n\t\/\/            \/  |\n\t\/\/           +---+- 0\n\t\/\/          +----+- 1\n\t\/\/         \/     |\n\t\/\/        \/      |\n\t\/\/       \/       |\n\t\/\/      +--------+- 0\n\t\/\/     +---------+- 1\n\t\/\/    \/          |\n\t\/\/   \/           |\n\t\/\/  \/            |\n\t\/\/ +-------------+- start\n\t\/\/ R             C\n\n\tfloat radius = vbegin.length();\n\tfloat angle_step = Math_PI \/ static_cast<float>(round_precision);\n\tfloat steps = Math::abs(angle_delta) \/ angle_step;\n\n\tif (angle_delta < 0.f)\n\t\tangle_step = -angle_step;\n\n\tfloat t = Vector2(1, 0).angle_to(vbegin);\n\tconst float half_angle = angle_delta \/ 2;\n\tconst float tt_begin = -Math_PI \/ 2.f;\n\n\tVector<float> uv_segs;\n\t\/\/ get the number of repeated segments and\n\t\/\/ split texture for each segment\n\tconst float uv0 = uv_rect.position.x;\n\tconst float uv1 = uv_rect.position.x + uv_rect.size.width;\n\tpush_back_if_gtzero(uv_segs, Math::ceil(uv0) - uv0);\n\tint uv = ceil(uv0);\n\twhile (++uv <= uv1)\n\t\tuv_segs.push_back(1);\n\tpush_back_if_gtzero(uv_segs, uv1 - Math::floor(uv1));\n\n\t\/\/ Center vertice\n\tint vi = vertices.size();\n\tvertices.push_back(center);\n\tif (_interpolate_color)\n\t\tcolors.push_back(color);\n\tif (texture_mode != Line2D::LINE_TEXTURE_NONE)\n\t\tuvs.push_back(interpolate(uv_rect, Vector2(0.5f, 0.5f)));\n\n\t\/\/ Radius weights\n\tVector<float> segs;\n\t\/\/ divide radius for repeated segments + fractional begin\/end:\n\t\/\/ | . | ... | ... | .. |\n\tconst float step = radius \/ uv_rect.size.width;\n\tfloat dist = 0;\n\tfor (int s = 0; s < uv_segs.size(); ++s) {\n\t\tdist += uv_segs[s];\n\t\tsegs.push_back(dist * step);\n\t}\n\tfor (int s = 0; s < segs.size(); ++s) {\n\t\tprint_line(vformat(\"%d segs: %f\", s, segs[s]));\n\t}\n\n\tauto add_vertex = [=](float tt, const Vector2 &v, const Color &vc) {\n\t\tvertices.push_back(v);\n\t\tif (_interpolate_color)\n\t\t\tcolors.push_back(vc);\n\t\tif (texture_mode != Line2D::LINE_TEXTURE_NONE) {\n\t\t\tVector2 tsc = Vector2(Math::cos(tt_begin + tt), Math::sin(tt_begin + tt));\n\t\t\tuvs.push_back(interpolate(uv_rect, 0.5f * (tsc + Vector2(1.f, 1.f))));\n\t\t}\n\t};\n\n\tconst Vector2 ho = Vector2(cos(half_angle), sin(half_angle)); \/\/ half arc unit vector\n\n\t\/\/ First arc vertice\n\tVector2 last_so = center + Vector2(Math::cos(t), Math::sin(t)) * radius;\n\tadd_vertex(t, last_so, color);\n\n\tt += angle_step;\n\n\tconst int sc = segs.size();\n\tconst int seg_last = sc - 1;\n\n\tint seg_index = 0, seg_step = 1;\n\tVector2 half_s = center + ho * segs[seg_index]; \/\/ band along the half arc\n\tfor (int ti = 1; ti < steps + 1; ++ti, t += angle_step) {\n\t\tconst Vector2 so = center + Vector2(Math::cos(t), Math::sin(t)) * radius;\n\t\tconst Vector2 ro(radius * seg_step, 0); \/\/ -radius or radius vector\n\t\tconst Vector2 edge = find_intersection(half_s, half_s + ro, last_so, so);\n\t\tif (edge != Failed) {\n\t\t\tadd_vertex(t, center + so * radius, color);\n\t\t\t\/\/ next band up or down\n\t\t\tseg_index += seg_step;\n\t\t\tif (seg_index == seg_last) {\n\t\t\t\tseg_step = -1;\n\t\t\t\tseg_index += seg_step;\n\t\t\t}\n\t\t\thalf_s = center + ho * segs[seg_index];\n\t\t}\n\t\tadd_vertex(t, half_s, color);\n\t\tadd_vertex(t, half_s, color);\n\t\tlast_so = so;\n\t}\n\n\tconst int vi0 = vi++;\n\tconst int st = sc * 2 - 1;\n\tfor (int ti = 0; ti < steps; ++ti, vi += st) {\n\t\tindices.push_back(vi0, vi, vi + st);\n\t\tfor (int si = 0; si < sc - 1; ++si) {\n\t\t\tindices.push_back(vi + si + 1, vi + si + 2, vi + si + st + 2);\n\t\t\tindices.push_back(vi + si + 1, vi + si + st + 2, vi + si + st + 1);\n\t\t}\n\t}\n}\n","avg_line_length":31.1179190751,"max_line_length":145,"alphanum_fraction":0.6187910986,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":41220,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/===--- OperandOwnership.cpp ---------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/SIL\/ApplySite.h\"\n#include \"swift\/SIL\/OwnershipUtils.h\"\n#include \"swift\/SIL\/SILBuiltinVisitor.h\"\n#include \"swift\/SIL\/SILInstruction.h\"\n#include \"swift\/SIL\/SILValue.h\"\n#include \"swift\/SIL\/SILVisitor.h\"\n\nusing namespace swift;\n\n\/\/\/ Return true if all OperandOwnership invariants hold.\nbool swift::checkOperandOwnershipInvariants(const Operand *operand) {\n  OperandOwnership opOwnership = operand->getOperandOwnership();\n  if (opOwnership == OperandOwnership::Borrow) {\n    \/\/ Must be a valid BorrowingOperand.\n    return bool(BorrowingOperand(const_cast<Operand *>(operand)));\n  }\n  return true;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                         OperandOwnershipClassifier\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\n\nclass OperandOwnershipClassifier\n  : public SILInstructionVisitor<OperandOwnershipClassifier, OperandOwnership> {\n  LLVM_ATTRIBUTE_UNUSED SILModule &mod;\n\n  const Operand &op;\n\npublic:\n  \/\/\/ Create a new OperandOwnershipClassifier.\n  \/\/\/\n  \/\/\/ In most cases, one should only pass in \\p Op and \\p BaseValue will be set\n  \/\/\/ to Op.get(). In cases where one is trying to verify subobjects, Op.get()\n  \/\/\/ should be the subobject and Value should be the parent object. An example\n  \/\/\/ of where one would want to do this is in the case of value projections\n  \/\/\/ like struct_extract.\n  OperandOwnershipClassifier(SILModule &mod, const Operand &op)\n      : mod(mod), op(op) {}\n\n  SILValue getValue() const { return op.get(); }\n\n  ValueOwnershipKind getOwnershipKind() const {\n    return op.get().getOwnershipKind();\n  }\n\n  unsigned getOperandIndex() const { return op.getOperandNumber(); }\n\n  SILType getType() const { return op.get()->getType(); }\n\n  bool compatibleWithOwnership(ValueOwnershipKind kind) const {\n    return getOwnershipKind().isCompatibleWith(kind);\n  }\n\n  bool hasExactOwnership(ValueOwnershipKind kind) const {\n    return getOwnershipKind() == kind;\n  }\n\n  OperandOwnership visitFullApply(FullApplySite apply);\n\n\/\/ Create declarations for all instructions, so we get a warning at compile\n\/\/ time if any instructions do not have an implementation.\n#define INST(Id, Parent) OperandOwnership visit##Id(Id *);\n#include \"swift\/SIL\/SILNodes.def\"\n};\n\n} \/\/ end anonymous namespace\n\n\/\/\/ Implementation for instructions that we should never visit since they are\n\/\/\/ not valid in ossa or do not have operands. Since we should never visit\n\/\/\/ these, we just assert.\n#define SHOULD_NEVER_VISIT_INST(INST)                                          \\\n  OperandOwnership OperandOwnershipClassifier::visit##INST##Inst(              \\\n      INST##Inst *i) {                                                         \\\n    llvm::errs() << \"Unhandled inst: \" << *i;                                  \\\n    llvm::report_fatal_error(                                                  \\\n        \"Visited instruction that should never be visited?!\");                 \\\n  }\nSHOULD_NEVER_VISIT_INST(AllocBox)\nSHOULD_NEVER_VISIT_INST(AllocExistentialBox)\nSHOULD_NEVER_VISIT_INST(AllocGlobal)\nSHOULD_NEVER_VISIT_INST(AllocStack)\nSHOULD_NEVER_VISIT_INST(DifferentiabilityWitnessFunction)\nSHOULD_NEVER_VISIT_INST(FloatLiteral)\nSHOULD_NEVER_VISIT_INST(FunctionRef)\nSHOULD_NEVER_VISIT_INST(DynamicFunctionRef)\nSHOULD_NEVER_VISIT_INST(PreviousDynamicFunctionRef)\nSHOULD_NEVER_VISIT_INST(GlobalAddr)\nSHOULD_NEVER_VISIT_INST(GlobalValue)\nSHOULD_NEVER_VISIT_INST(BaseAddrForOffset)\nSHOULD_NEVER_VISIT_INST(IntegerLiteral)\nSHOULD_NEVER_VISIT_INST(Metatype)\nSHOULD_NEVER_VISIT_INST(ObjCProtocol)\nSHOULD_NEVER_VISIT_INST(RetainValue)\nSHOULD_NEVER_VISIT_INST(RetainValueAddr)\nSHOULD_NEVER_VISIT_INST(StringLiteral)\nSHOULD_NEVER_VISIT_INST(StrongRetain)\nSHOULD_NEVER_VISIT_INST(Unreachable)\nSHOULD_NEVER_VISIT_INST(Unwind)\nSHOULD_NEVER_VISIT_INST(ReleaseValue)\nSHOULD_NEVER_VISIT_INST(ReleaseValueAddr)\nSHOULD_NEVER_VISIT_INST(StrongRelease)\nSHOULD_NEVER_VISIT_INST(GetAsyncContinuation)\n\n#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)            \\\n  SHOULD_NEVER_VISIT_INST(StrongRetain##Name)                                  \\\n  SHOULD_NEVER_VISIT_INST(Name##Retain)\n#include \"swift\/AST\/ReferenceStorage.def\"\n#undef SHOULD_NEVER_VISIT_INST\n\n\/\/ FIXME: The assert should be moved to the verifier.\n#define OPERAND_OWNERSHIP(OWNERSHIP, INST)                                     \\\n  OperandOwnership                                                             \\\n  OperandOwnershipClassifier::visit##INST##Inst(INST##Inst *i) {               \\\n    assert(i->getNumOperands() && \"Expected to have non-zero operands\");       \\\n    return OperandOwnership::OWNERSHIP;                                        \\\n  }\n\n\/\/ Instructions that require trivial operands.\nOPERAND_OWNERSHIP(TrivialUse, AwaitAsyncContinuation)\nOPERAND_OWNERSHIP(TrivialUse, AddressToPointer)\nOPERAND_OWNERSHIP(TrivialUse, AllocRef)        \/\/ with tail operand\nOPERAND_OWNERSHIP(TrivialUse, AllocRefDynamic) \/\/ with tail operand\nOPERAND_OWNERSHIP(TrivialUse, BeginAccess)\nOPERAND_OWNERSHIP(TrivialUse, BeginUnpairedAccess)\nOPERAND_OWNERSHIP(TrivialUse, BindMemory)\nOPERAND_OWNERSHIP(TrivialUse, CheckedCastAddrBranch)\nOPERAND_OWNERSHIP(TrivialUse, CondBranch)\nOPERAND_OWNERSHIP(TrivialUse, CondFail)\nOPERAND_OWNERSHIP(TrivialUse, CopyAddr)\nOPERAND_OWNERSHIP(TrivialUse, DeallocStack)\nOPERAND_OWNERSHIP(TrivialUse, DeinitExistentialAddr)\nOPERAND_OWNERSHIP(TrivialUse, DestroyAddr)\nOPERAND_OWNERSHIP(TrivialUse, EndAccess)\nOPERAND_OWNERSHIP(TrivialUse, EndUnpairedAccess)\nOPERAND_OWNERSHIP(TrivialUse, GetAsyncContinuationAddr)\nOPERAND_OWNERSHIP(TrivialUse, IndexAddr)\nOPERAND_OWNERSHIP(TrivialUse, IndexRawPointer)\nOPERAND_OWNERSHIP(TrivialUse, InitBlockStorageHeader)\nOPERAND_OWNERSHIP(TrivialUse, InitEnumDataAddr)\nOPERAND_OWNERSHIP(TrivialUse, InitExistentialAddr)\nOPERAND_OWNERSHIP(TrivialUse, InitExistentialMetatype)\nOPERAND_OWNERSHIP(TrivialUse, InjectEnumAddr)\nOPERAND_OWNERSHIP(TrivialUse, IsUnique)\nOPERAND_OWNERSHIP(TrivialUse, Load)\nOPERAND_OWNERSHIP(TrivialUse, LoadBorrow)\nOPERAND_OWNERSHIP(TrivialUse, MarkFunctionEscape)\nOPERAND_OWNERSHIP(TrivialUse, ObjCExistentialMetatypeToObject)\nOPERAND_OWNERSHIP(TrivialUse, ObjCMetatypeToObject)\nOPERAND_OWNERSHIP(TrivialUse, ObjCToThickMetatype)\nOPERAND_OWNERSHIP(TrivialUse, OpenExistentialAddr)\nOPERAND_OWNERSHIP(TrivialUse, OpenExistentialMetatype)\nOPERAND_OWNERSHIP(TrivialUse, PointerToAddress)\nOPERAND_OWNERSHIP(TrivialUse, PointerToThinFunction)\nOPERAND_OWNERSHIP(TrivialUse, ProjectBlockStorage)\nOPERAND_OWNERSHIP(TrivialUse, RawPointerToRef)\nOPERAND_OWNERSHIP(TrivialUse, SelectEnumAddr)\nOPERAND_OWNERSHIP(TrivialUse, StructElementAddr)\nOPERAND_OWNERSHIP(TrivialUse, SwitchEnumAddr)\nOPERAND_OWNERSHIP(TrivialUse, SwitchValue)\nOPERAND_OWNERSHIP(TrivialUse, TailAddr)\nOPERAND_OWNERSHIP(TrivialUse, ThickToObjCMetatype)\nOPERAND_OWNERSHIP(TrivialUse, ThinFunctionToPointer)\nOPERAND_OWNERSHIP(TrivialUse, ThinToThickFunction)\nOPERAND_OWNERSHIP(TrivialUse, TupleElementAddr)\nOPERAND_OWNERSHIP(TrivialUse, UncheckedAddrCast)\nOPERAND_OWNERSHIP(TrivialUse, UncheckedRefCastAddr)\nOPERAND_OWNERSHIP(TrivialUse, UncheckedTakeEnumDataAddr)\nOPERAND_OWNERSHIP(TrivialUse, UnconditionalCheckedCastAddr)\n\n\/\/ Use an owned or guaranteed value only for the duration of the operation.\nOPERAND_OWNERSHIP(InstantaneousUse, ExistentialMetatype)\nOPERAND_OWNERSHIP(InstantaneousUse, FixLifetime)\nOPERAND_OWNERSHIP(InstantaneousUse, WitnessMethod)\nOPERAND_OWNERSHIP(InstantaneousUse, DynamicMethodBranch)\nOPERAND_OWNERSHIP(InstantaneousUse, ValueMetatype)\nOPERAND_OWNERSHIP(InstantaneousUse, IsEscapingClosure)\nOPERAND_OWNERSHIP(InstantaneousUse, ClassMethod)\nOPERAND_OWNERSHIP(InstantaneousUse, SuperMethod)\nOPERAND_OWNERSHIP(InstantaneousUse, ClassifyBridgeObject)\nOPERAND_OWNERSHIP(InstantaneousUse, SetDeallocating)\n#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)            \\\n  OPERAND_OWNERSHIP(InstantaneousUse, StrongCopy##Name##Value)\n#define UNCHECKED_REF_STORAGE(Name, ...)                                       \\\n  OPERAND_OWNERSHIP(InstantaneousUse, StrongCopy##Name##Value)\n#include \"swift\/AST\/ReferenceStorage.def\"\n\n\/\/ Unowned uses ignore the value's ownership\nOPERAND_OWNERSHIP(UnownedInstantaneousUse, DebugValue)\nOPERAND_OWNERSHIP(UnownedInstantaneousUse, CopyBlock)\nOPERAND_OWNERSHIP(UnownedInstantaneousUse, CopyValue)\nOPERAND_OWNERSHIP(UnownedInstantaneousUse, ObjCMethod)\nOPERAND_OWNERSHIP(UnownedInstantaneousUse, ObjCSuperMethod)\nOPERAND_OWNERSHIP(UnownedInstantaneousUse, UnmanagedRetainValue)\nOPERAND_OWNERSHIP(UnownedInstantaneousUse, UnmanagedReleaseValue)\nOPERAND_OWNERSHIP(UnownedInstantaneousUse, UnmanagedAutoreleaseValue)\n\n\/\/ These act as a form of conversion that does not imply ownership. Thus from an\n\/\/ operand perspective we treat them as a pointer escape and from a value\n\/\/ perspective, they return a value with OwnershipKind::Unowned.\n#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)            \\\n  OPERAND_OWNERSHIP(PointerEscape, RefTo##Name)                                \\\n  OPERAND_OWNERSHIP(PointerEscape, Name##ToRef)\n#define UNCHECKED_REF_STORAGE(Name, ...)                                       \\\n  OPERAND_OWNERSHIP(PointerEscape, RefTo##Name)\n#include \"swift\/AST\/ReferenceStorage.def\"\n\n\/\/ Instructions that currently violate structural ownership requirements,\n\/\/ and therefore completely defeat canonicalization and optimization of any\n\/\/ OSSA value that they use.\nOPERAND_OWNERSHIP(PointerEscape, ProjectBox) \/\/ The result is a T*.\nOPERAND_OWNERSHIP(PointerEscape, ProjectExistentialBox)\nOPERAND_OWNERSHIP(PointerEscape, UncheckedOwnershipConversion)\nOPERAND_OWNERSHIP(PointerEscape, ConvertEscapeToNoEscape)\n\n\/\/ Instructions that escape reference bits with unenforced lifetime.\n\/\/ TODO: verify that BitwiseEscape results always have a trivial type.\nOPERAND_OWNERSHIP(BitwiseEscape, UncheckedBitwiseCast)\nOPERAND_OWNERSHIP(BitwiseEscape, ValueToBridgeObject)\nOPERAND_OWNERSHIP(BitwiseEscape, RefToRawPointer)\nOPERAND_OWNERSHIP(BitwiseEscape, UncheckedTrivialBitCast)\nOPERAND_OWNERSHIP(BitwiseEscape, BridgeObjectToWord)\n\n\/\/ Instructions that end the lifetime of an owned value.\nOPERAND_OWNERSHIP(DestroyingConsume, AutoreleaseValue)\nOPERAND_OWNERSHIP(DestroyingConsume, DeallocBox)\nOPERAND_OWNERSHIP(DestroyingConsume, DeallocExistentialBox)\nOPERAND_OWNERSHIP(DestroyingConsume, DeallocRef)\nOPERAND_OWNERSHIP(DestroyingConsume, DestroyValue)\nOPERAND_OWNERSHIP(DestroyingConsume, EndLifetime)\nOPERAND_OWNERSHIP(DestroyingConsume, BeginCOWMutation)\nOPERAND_OWNERSHIP(DestroyingConsume, EndCOWMutation)\n\n\/\/ TODO: Should this be a forwarding consume.\nOPERAND_OWNERSHIP(DestroyingConsume, MoveValue)\n\n\/\/ Instructions that move an owned value.\nOPERAND_OWNERSHIP(ForwardingConsume, CheckedCastValueBranch)\nOPERAND_OWNERSHIP(ForwardingConsume, UnconditionalCheckedCastValue)\nOPERAND_OWNERSHIP(ForwardingConsume, InitExistentialValue)\nOPERAND_OWNERSHIP(ForwardingConsume, DeinitExistentialValue)\nOPERAND_OWNERSHIP(ForwardingConsume, MarkUninitialized)\nOPERAND_OWNERSHIP(ForwardingConsume, Throw)\n\n\/\/ Instructions that expose a pointer within a borrow scope.\nOPERAND_OWNERSHIP(InteriorPointer, RefElementAddr)\nOPERAND_OWNERSHIP(InteriorPointer, RefTailAddr)\nOPERAND_OWNERSHIP(InteriorPointer, OpenExistentialBox)\n\/\/ FIXME: HopToExecutorInst should be an instantaneous use.\nOPERAND_OWNERSHIP(InteriorPointer, HopToExecutor)\nOPERAND_OWNERSHIP(InteriorPointer, ExtractExecutor)\n\n\/\/ Instructions that propagate a value value within a borrow scope.\nOPERAND_OWNERSHIP(ForwardingBorrow, TupleExtract)\nOPERAND_OWNERSHIP(ForwardingBorrow, StructExtract)\nOPERAND_OWNERSHIP(ForwardingBorrow, DifferentiableFunctionExtract)\nOPERAND_OWNERSHIP(ForwardingBorrow, LinearFunctionExtract)\n\/\/ FIXME: OpenExistential[Box]Value should be able to take owned values too by\n\/\/ using getForwardingOperandOwnership.\nOPERAND_OWNERSHIP(ForwardingBorrow, OpenExistentialValue)\nOPERAND_OWNERSHIP(ForwardingBorrow, OpenExistentialBoxValue)\n\nOPERAND_OWNERSHIP(EndBorrow, EndBorrow)\n\n\/\/ The begin_apply token represents the borrow scope of all owned and guaranteed\n\/\/ call arguments. Although SILToken is (currently) trivially typed, it must\n\/\/ have guaranteed ownership so end_apply and abort_apply will be recognized\n\/\/ as lifetime-ending uses.\nOPERAND_OWNERSHIP(EndBorrow, EndApply)\nOPERAND_OWNERSHIP(EndBorrow, AbortApply)\n\n#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...)                          \\\n  OPERAND_OWNERSHIP(TrivialUse, Load##Name)\n#define ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, ...)                         \\\n  OPERAND_OWNERSHIP(DestroyingConsume, Name##Release)\n#define SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)                      \\\n  NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, \"...\")                              \\\n  ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, \"...\")\n#define UNCHECKED_REF_STORAGE(Name, ...)                                       \\\n  OPERAND_OWNERSHIP(TrivialUse, Name##ToRef)\n#include \"swift\/AST\/ReferenceStorage.def\"\n\n#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...)                          \\\n  OPERAND_OWNERSHIP(InstantaneousUse, Store##Name)\n#define SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)                      \\\n  NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, \"...\")\n#include \"swift\/AST\/ReferenceStorage.def\"\n\n#undef OPERAND_OWNERSHIP\n\n\/\/ Forwarding operations are conditionally either ForwardingConsumes or\n\/\/ ForwardingBorrows, depending on the instruction's constant ownership\n\/\/ attribute.\n#define FORWARDING_OWNERSHIP(INST)                                             \\\n  OperandOwnership OperandOwnershipClassifier::visit##INST##Inst(              \\\n      INST##Inst *i) {                                                         \\\n    return i->getForwardingOwnershipKind().getForwardingOperandOwnership(      \\\n        \/*allowUnowned*\/ false);                                               \\\n  }\nFORWARDING_OWNERSHIP(Object)\nFORWARDING_OWNERSHIP(OpenExistentialRef)\nFORWARDING_OWNERSHIP(ConvertFunction)\nFORWARDING_OWNERSHIP(RefToBridgeObject)\nFORWARDING_OWNERSHIP(BridgeObjectToRef)\nFORWARDING_OWNERSHIP(UnconditionalCheckedCast)\nFORWARDING_OWNERSHIP(InitExistentialRef)\nFORWARDING_OWNERSHIP(DifferentiableFunction)\nFORWARDING_OWNERSHIP(LinearFunction)\n#undef FORWARDING_OWNERSHIP\n\n\/\/ Arbitrary value casts are forwarding instructions that are also allowed to\n\/\/ propagate Unowned values.\n#define FORWARDING_ANY_OWNERSHIP(INST)                                         \\\n  OperandOwnership OperandOwnershipClassifier::visit##INST##Inst(              \\\n      INST##Inst *i) {                                                         \\\n    return i->getForwardingOwnershipKind().getForwardingOperandOwnership(      \\\n        \/*allowUnowned*\/ true);                                                \\\n  }\nFORWARDING_ANY_OWNERSHIP(Upcast)\nFORWARDING_ANY_OWNERSHIP(UncheckedRefCast)\nFORWARDING_ANY_OWNERSHIP(UncheckedValueCast)\nFORWARDING_ANY_OWNERSHIP(CheckedCastBranch)\n#undef FORWARDING_ANY_OWNERSHIP\n\n\/\/ Any valid ownership kind can be combined with values of None ownership, but\n\/\/ they cannot be combined with each other. An aggregates result ownership is\n\/\/ the meet of its operands' ownership. A destructured member has the same\n\/\/ ownership as its aggregate unless its type gives it None ownership.\n\/\/\n\/\/ TODO: Aggregate operations should be Reborrows, not ForwardingBorrows,\n\/\/ because the borrowed value is different on either side of the operation and\n\/\/ the lifetimes of borrowed members could differ.\n#define AGGREGATE_OWNERSHIP(INST)                                              \\\n  OperandOwnership OperandOwnershipClassifier::visit##INST##Inst(              \\\n      INST##Inst *i) {                                                         \\\n    return i->getForwardingOwnershipKind().getForwardingOperandOwnership(      \\\n        \/*allowUnowned*\/ true);                                                \\\n  }\nAGGREGATE_OWNERSHIP(Tuple)\nAGGREGATE_OWNERSHIP(Struct)\nAGGREGATE_OWNERSHIP(DestructureStruct)\nAGGREGATE_OWNERSHIP(DestructureTuple)\nAGGREGATE_OWNERSHIP(Enum)\nAGGREGATE_OWNERSHIP(UncheckedEnumData)\nAGGREGATE_OWNERSHIP(SwitchEnum)\n#undef AGGREGATE_OWNERSHIP\n\n\/\/ A begin_borrow is conditionally nested.\nOperandOwnership\nOperandOwnershipClassifier::visitBeginBorrowInst(BeginBorrowInst *borrow) {\n  return OperandOwnership::Borrow;\n}\n\n\/\/ MARK: Instructions whose use ownership depends on the operand in question.\n\nOperandOwnership OperandOwnershipClassifier::\nvisitDeallocPartialRefInst(DeallocPartialRefInst *i) {\n  if (getValue() == i->getInstance()) {\n    return OperandOwnership::DestroyingConsume;\n  }\n  return OperandOwnership::TrivialUse;\n}\n\nOperandOwnership\nOperandOwnershipClassifier::visitSelectEnumInst(SelectEnumInst *i) {\n  if (getValue() == i->getEnumOperand()) {\n    return OperandOwnership::InstantaneousUse;\n  }\n  return getOwnershipKind().getForwardingOperandOwnership(\n    \/*allowUnowned*\/true);\n}\n\nOperandOwnership\nOperandOwnershipClassifier::visitSelectValueInst(SelectValueInst *i) {\n  if (getValue() == i->getDefaultResult())\n    return OperandOwnership::ForwardingBorrow;\n\n  for (unsigned idx = 0, endIdx = i->getNumCases(); idx < endIdx; ++idx) {\n    SILValue casevalue;\n    SILValue result;\n    std::tie(casevalue, result) = i->getCase(idx);\n\n    if (getValue() == casevalue) {\n      return OperandOwnership::ForwardingBorrow;\n    }\n  }\n  return OperandOwnership::TrivialUse;\n}\n\nOperandOwnership OperandOwnershipClassifier::visitBranchInst(BranchInst *bi) {\n  ValueOwnershipKind destBlockArgOwnershipKind =\n      bi->getDestBB()->getArgument(getOperandIndex())->getOwnershipKind();\n\n  \/\/ FIXME: remove this special case once all aggregate operations behave just\n  \/\/ like phis.\n  if (destBlockArgOwnershipKind == OwnershipKind::Guaranteed) {\n    return OperandOwnership::Reborrow;\n  }\n  return destBlockArgOwnershipKind.getForwardingOperandOwnership(\n    \/*allowUnowned*\/true);\n}\n\nOperandOwnership\nOperandOwnershipClassifier::visitStoreBorrowInst(StoreBorrowInst *i) {\n  if (getValue() == i->getSrc()) {\n    return OperandOwnership::InteriorPointer;\n  }\n  return OperandOwnership::TrivialUse;\n}\n\n\/\/ Get the OperandOwnership for instaneous apply, yield, and return uses.\n\/\/ This does not apply to uses that begin an explicit borrow scope in the\n\/\/ caller, such as begin_apply.\nstatic OperandOwnership getFunctionArgOwnership(SILArgumentConvention argConv,\n                                                bool hasScopeInCaller) {\n\n  switch (argConv) {\n  case SILArgumentConvention::Indirect_In:\n  case SILArgumentConvention::Direct_Owned:\n    return OperandOwnership::ForwardingConsume;\n\n  \/\/ A guaranteed argument is forwarded into the callee. If the call itself has\n  \/\/ no scope (i.e. it is a single apply, try_apply or yield), then from the\n  \/\/ caller's point of view it looks like an instantaneous use. Consequently,\n  \/\/ owned values may be passed to guaranteed arguments without an explicit\n  \/\/ borrow scope in the caller. In contrast, a begin_apply \/does\/ have an\n  \/\/ explicit borrow scope in the caller so we must treat arguments passed to it\n  \/\/ as being borrowed for the entire region of coroutine execution.\n  case SILArgumentConvention::Indirect_In_Constant:\n  case SILArgumentConvention::Indirect_In_Guaranteed:\n  case SILArgumentConvention::Direct_Guaranteed:\n    \/\/ For an apply that begins a borrow scope, its arguments are borrowed\n    \/\/ throughout the caller's borrow scope.\n    return hasScopeInCaller ? OperandOwnership::Borrow\n                            : OperandOwnership::InstantaneousUse;\n\n  case SILArgumentConvention::Direct_Unowned:\n    return OperandOwnership::UnownedInstantaneousUse;\n\n  case SILArgumentConvention::Indirect_Out:\n  case SILArgumentConvention::Indirect_Inout:\n  case SILArgumentConvention::Indirect_InoutAliasable:\n    llvm_unreachable(\"Illegal convention for non-address types\");\n  }\n  llvm_unreachable(\"covered switch\");\n}\n\nOperandOwnership\nOperandOwnershipClassifier::visitFullApply(FullApplySite apply) {\n  \/\/ Before considering conventions, filter all (trivial) indirect\n  \/\/ arguments. This also rules out result arguments.\n  if (getValue()->getType().isAddress()) {\n    return OperandOwnership::TrivialUse;\n  }\n  SILArgumentConvention argConv = apply.isCalleeOperand(op)\n    ? SILArgumentConvention(apply.getSubstCalleeType()->getCalleeConvention())\n    : apply.getArgumentConvention(op);\n\n  auto argOwnership = getFunctionArgOwnership(\n    argConv, \/*hasScopeInCaller*\/ apply.beginsCoroutineEvaluation());\n\n  \/\/ OSSA cleanup needs to handle each of these callee ownership cases.\n  \/\/\n  \/\/ OperandOwnership::ForwardingConsume is only for thick @callee_owned.\n  \/\/\n  \/\/ OperandOwnership::Borrow would only happen for a coroutine closure, which\n  \/\/ isn't yet possible.\n  if (apply.isCalleeOperand(op)) {\n    assert((argOwnership == OperandOwnership::TrivialUse\n            || argOwnership == OperandOwnership::UnownedInstantaneousUse\n            || argOwnership == OperandOwnership::InstantaneousUse\n            || argOwnership == OperandOwnership::ForwardingConsume\n            || argOwnership == OperandOwnership::Borrow) &&\n           \"unsupported callee ownership\");\n  }\n  return argOwnership;\n}\n\nOperandOwnership\nOperandOwnershipClassifier::visitBeginApplyInst(BeginApplyInst *i) {\n  return visitFullApply(i);\n}\n\nOperandOwnership OperandOwnershipClassifier::visitApplyInst(ApplyInst *i) {\n  return visitFullApply(i);\n}\n\nOperandOwnership\nOperandOwnershipClassifier::visitTryApplyInst(TryApplyInst *i) {\n  return visitFullApply(i);\n}\n\nOperandOwnership\nOperandOwnershipClassifier::visitPartialApplyInst(PartialApplyInst *i) {\n  \/\/ partial_apply [stack] does not take ownership of its operands.\n  if (i->isOnStack()) {\n    return OperandOwnership::InstantaneousUse;\n  }\n  \/\/ All non-trivial types should be captured.\n  return OperandOwnership::ForwardingConsume;\n}\n\nOperandOwnership OperandOwnershipClassifier::visitYieldInst(YieldInst *i) {\n  \/\/ Before considering conventions, filter all indirect arguments.\n  if (getValue()->getType().isAddress()) {\n    return OperandOwnership::TrivialUse;\n  }\n  auto fnType = i->getFunction()->getLoweredFunctionType();\n  SILArgumentConvention argConv(\n    fnType->getYields()[getOperandIndex()].getConvention());\n  return getFunctionArgOwnership(argConv, \/*hasScopeInCaller*\/ false);\n}\n\nOperandOwnership OperandOwnershipClassifier::visitReturnInst(ReturnInst *i) {\n  switch (i->getOwnershipKind()) {\n  case OwnershipKind::Any:\n  case OwnershipKind::Guaranteed:\n    llvm_unreachable(\"invalid value ownership\");\n  case OwnershipKind::None:\n    return OperandOwnership::TrivialUse;\n  case OwnershipKind::Unowned:\n    return OperandOwnership::UnownedInstantaneousUse;\n  case OwnershipKind::Owned:\n    return OperandOwnership::ForwardingConsume;\n  }\n  llvm_unreachable(\"covered switch\");\n}\n\nOperandOwnership OperandOwnershipClassifier::visitAssignInst(AssignInst *i) {\n  if (getValue() != i->getSrc()) {\n    return OperandOwnership::TrivialUse;\n  }\n  return OperandOwnership::DestroyingConsume;\n}\n\nOperandOwnership\nOperandOwnershipClassifier::visitAssignByWrapperInst(AssignByWrapperInst *i) {\n  if (getValue() == i->getSrc()) {\n    return OperandOwnership::DestroyingConsume;\n  }\n  if (getValue() == i->getDest()) {\n    return OperandOwnership::TrivialUse;\n  }\n  return OperandOwnership::InstantaneousUse; \/\/ initializer\/setter closure\n}\n\nOperandOwnership OperandOwnershipClassifier::visitStoreInst(StoreInst *i) {\n  if (getValue() != i->getSrc()) {\n    return OperandOwnership::TrivialUse;\n  }\n  return OperandOwnership::DestroyingConsume;\n}\n\nOperandOwnership OperandOwnershipClassifier::visitCopyBlockWithoutEscapingInst(\n    CopyBlockWithoutEscapingInst *i) {\n  \/\/ Consumes the closure parameter.\n  if (getValue() == i->getClosure()) {\n    return OperandOwnership::ForwardingConsume;\n  }\n  return OperandOwnership::UnownedInstantaneousUse;\n}\n\nOperandOwnership\nOperandOwnershipClassifier::visitMarkDependenceInst(MarkDependenceInst *mdi) {\n  \/\/ If we are analyzing \"the value\", we forward ownership.\n  if (getValue() == mdi->getValue()) {\n    return getOwnershipKind().getForwardingOperandOwnership(\n      \/*allowUnowned*\/true);\n  }\n  \/\/ FIXME: Add an end_dependence instruction so we can treat mark_dependence as\n  \/\/ a borrow of the base (mark_dependence %base -> end_dependence is analogous\n  \/\/ to a borrow scope).\n  return OperandOwnership::PointerEscape;\n}\n\nOperandOwnership OperandOwnershipClassifier::visitKeyPathInst(KeyPathInst *I) {\n  \/\/ KeyPath moves the value in memory out of address operands, but the\n  \/\/ ownership checker doesn't reason about that yet.\n  return OperandOwnership::ForwardingConsume;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                            Builtin Use Checker\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\n\nstruct OperandOwnershipBuiltinClassifier\n    : SILBuiltinVisitor<OperandOwnershipBuiltinClassifier, OperandOwnership> {\n  using Map = OperandOwnership;\n      \n  const Operand &op;\n  OperandOwnershipBuiltinClassifier(const Operand &op) : op(op) {}\n\n  OperandOwnership visitLLVMIntrinsic(BuiltinInst *bi, llvm::Intrinsic::ID id) {\n    \/\/ LLVM intrinsics do not traffic in ownership, so if we have a result, it\n    \/\/ must be trivial.\n    return OperandOwnership::TrivialUse;\n  }\n\n  \/\/ BUILTIN_TYPE_CHECKER_OPERATION does not live past the type checker.\n#define BUILTIN_TYPE_CHECKER_OPERATION(ID, NAME)\n\n#define BUILTIN(ID, NAME, ATTRS)                                               \\\n  OperandOwnership visit##ID(BuiltinInst *bi, StringRef attr);\n#include \"swift\/AST\/Builtins.def\"\n\n  OperandOwnership check(BuiltinInst *bi) { return visit(bi); }\n};\n\n} \/\/ end anonymous namespace\n\n#define BUILTIN_OPERAND_OWNERSHIP(OWNERSHIP, ID)                               \\\n  OperandOwnership                                                             \\\n  OperandOwnershipBuiltinClassifier::visit##ID(BuiltinInst *, StringRef) {     \\\n    return OperandOwnership::OWNERSHIP;                                        \\\n  }\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ErrorInMain)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, UnexpectedError)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, WillThrow)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AShr)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericAShr)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Add)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericAdd)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Alignof)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AllocRaw)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, And)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericAnd)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AssertConf)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AssignCopyArrayNoAlias)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AssignCopyArrayFrontToBack)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AssignCopyArrayBackToFront)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AssignTakeArray)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AssumeNonNegative)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AssumeTrue)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AtomicLoad)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AtomicRMW)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AtomicStore)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, BitCast)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, CanBeObjCClass)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, CondFailMessage)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, CmpXChg)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, CondUnreachable)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, CopyArray)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, DeallocRaw)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, DestroyArray)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ExactSDiv)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericExactSDiv)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ExactUDiv)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericExactUDiv)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ExtractElement)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FAdd)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericFAdd)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_OEQ)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_OGE)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_OGT)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_OLE)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_OLT)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_ONE)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_ORD)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_UEQ)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_UGE)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_UGT)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_ULE)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_ULT)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_UNE)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FCMP_UNO)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FDiv)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericFDiv)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FMul)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericFMul)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FNeg)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FPExt)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FPToSI)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FPToUI)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FPTrunc)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FRem)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericFRem)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, FSub)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericFSub)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Fence)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Ifdef)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GetObjCTypeEncoding)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ICMP_EQ)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ICMP_NE)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ICMP_SGE)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ICMP_SGT)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ICMP_SLE)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ICMP_SLT)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ICMP_UGE)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ICMP_UGT)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ICMP_ULE)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ICMP_ULT)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, InsertElement)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, IntToFPWithOverflow)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, IntToPtr)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, IsOptionalType)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, IsPOD)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, IsConcrete)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, IsBitwiseTakable)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, IsSameMetatype)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, LShr)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericLShr)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Mul)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericMul)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, OnFastPath)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Once)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, OnceWithContext)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Or)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericOr)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, PtrToInt)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, SAddOver)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, SDiv)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericSDiv)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, SExt)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, SExtOrBitCast)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, SIToFP)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, SMulOver)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, SRem)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericSRem)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, SSubOver)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, StackAlloc)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, StackDealloc)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, SToSCheckedTrunc)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, SToUCheckedTrunc)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Expect)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Shl)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericShl)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ShuffleVector)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Sizeof)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, StaticReport)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Strideof)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, StringObjectOr)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Sub)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericSub)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, TakeArrayNoAlias)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, TakeArrayBackToFront)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, TakeArrayFrontToBack)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Trunc)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, TruncOrBitCast)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, TSanInoutAccess)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, UAddOver)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, UDiv)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericUDiv)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, UIToFP)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, UMulOver)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, URem)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericURem)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, USubOver)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, UToSCheckedTrunc)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, UToUCheckedTrunc)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Unreachable)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, UnsafeGuaranteedEnd)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Xor)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericXor)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ZExt)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ZExtOrBitCast)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, ZeroInitializer)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, Swift3ImplicitObjCEntrypoint)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, PoundAssert)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GlobalStringTablePointer)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, TypePtrAuthDiscriminator)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, IntInstrprofIncrement)\nBUILTIN_OPERAND_OWNERSHIP(DestroyingConsume, StartAsyncLet)\nBUILTIN_OPERAND_OWNERSHIP(DestroyingConsume, EndAsyncLet)\nBUILTIN_OPERAND_OWNERSHIP(DestroyingConsume, StartAsyncLetWithLocalBuffer)\nBUILTIN_OPERAND_OWNERSHIP(DestroyingConsume, EndAsyncLetLifetime)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, CreateTaskGroup)\nBUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, DestroyTaskGroup)\n\nBUILTIN_OPERAND_OWNERSHIP(ForwardingConsume, COWBufferForReading)\nBUILTIN_OPERAND_OWNERSHIP(ForwardingConsume, UnsafeGuaranteed)\n\nconst int PARAMETER_INDEX_CREATE_ASYNC_TASK_FUTURE_FUNCTION = 2;\nconst int PARAMETER_INDEX_CREATE_ASYNC_TASK_GROUP_FUTURE_FUNCTION = 3;\n\nOperandOwnership\nOperandOwnershipBuiltinClassifier::visitCreateAsyncTask(BuiltinInst *bi,\n                                                        StringRef attr) {\n  \/\/ The function operand is consumed by the new task.\n  if (&op == &bi->getOperandRef(PARAMETER_INDEX_CREATE_ASYNC_TASK_FUTURE_FUNCTION))\n    return OperandOwnership::DestroyingConsume;\n  \n  \/\/ FIXME: These are considered InteriorPointer because they may propagate a\n  \/\/ pointer into a borrowed values. If they do not propagate an interior pointer,\n  \/\/ then they should be InstantaneousUse instead and should not require a\n  \/\/ guaranteed value.\n  return OperandOwnership::InteriorPointer;\n}\n\nOperandOwnership\nOperandOwnershipBuiltinClassifier::visitCreateAsyncTaskInGroup(BuiltinInst *bi,\n                                                               StringRef attr) {\n  \/\/ The function operand is consumed by the new task.\n  if (&op == &bi->getOperandRef(PARAMETER_INDEX_CREATE_ASYNC_TASK_GROUP_FUTURE_FUNCTION))\n    return OperandOwnership::DestroyingConsume;\n  \n  \/\/ FIXME: These are considered InteriorPointer because they may propagate a\n  \/\/ pointer into a borrowed values. If they do not propagate an interior pointer,\n  \/\/ then they should be InstantaneousUse instead and should not require a\n  \/\/ guaranteed value.\n  return OperandOwnership::InteriorPointer;\n}\n\nOperandOwnership OperandOwnershipBuiltinClassifier::\nvisitResumeNonThrowingContinuationReturning(BuiltinInst *bi, StringRef attr) {\n  \/\/ The value operand is consumed.\n  if (&op == &bi->getOperandRef(1))\n    return OperandOwnership::DestroyingConsume;\n\n  return OperandOwnership::TrivialUse;\n}\n\nOperandOwnership OperandOwnershipBuiltinClassifier::\nvisitResumeThrowingContinuationReturning(BuiltinInst *bi, StringRef attr) {\n  \/\/ The value operand is consumed.\n  if (&op == &bi->getOperandRef(1))\n    return OperandOwnership::DestroyingConsume;\n\n  return OperandOwnership::TrivialUse;\n}\n\nOperandOwnership OperandOwnershipBuiltinClassifier::\nvisitResumeThrowingContinuationThrowing(BuiltinInst *bi, StringRef attr) {\n  \/\/ The value operand is consumed.\n  if (&op == &bi->getOperandRef(1))\n    return OperandOwnership::DestroyingConsume;\n\n  return OperandOwnership::TrivialUse;\n}\n\nBUILTIN_OPERAND_OWNERSHIP(InteriorPointer, CancelAsyncTask)\nBUILTIN_OPERAND_OWNERSHIP(InteriorPointer, InitializeDefaultActor)\nBUILTIN_OPERAND_OWNERSHIP(InteriorPointer, DestroyDefaultActor)\n\nBUILTIN_OPERAND_OWNERSHIP(InteriorPointer, InitializeDistributedRemoteActor)\n\n\/\/ FIXME: Why do these reqiuire a borrowed value at all?\nBUILTIN_OPERAND_OWNERSHIP(ForwardingBorrow, AutoDiffAllocateSubcontext)\nBUILTIN_OPERAND_OWNERSHIP(ForwardingBorrow, AutoDiffProjectTopLevelSubcontext)\n\n\/\/ FIXME: ConvertTaskToJob is documented as taking NativePointer. It's operand's\n\/\/ ownership should be 'TrivialUse'.\nBUILTIN_OPERAND_OWNERSHIP(ForwardingConsume, ConvertTaskToJob)\n\nBUILTIN_OPERAND_OWNERSHIP(BitwiseEscape, BuildOrdinarySerialExecutorRef)\nBUILTIN_OPERAND_OWNERSHIP(BitwiseEscape, BuildDefaultActorExecutorRef)\nBUILTIN_OPERAND_OWNERSHIP(BitwiseEscape, BuildMainActorExecutorRef)\n\nBUILTIN_OPERAND_OWNERSHIP(TrivialUse, AutoDiffCreateLinearMapContext)\n\n#undef BUILTIN_OPERAND_OWNERSHIP\n\n#define SHOULD_NEVER_VISIT_BUILTIN(ID)                                         \\\n  OperandOwnership                                                             \\\n  OperandOwnershipBuiltinClassifier::visit##ID(BuiltinInst *, StringRef) {     \\\n    llvm_unreachable(                                                          \\\n        \"Builtin should never be visited! E.x.: It may not have arguments\");   \\\n  }\nSHOULD_NEVER_VISIT_BUILTIN(GetCurrentAsyncTask)\nSHOULD_NEVER_VISIT_BUILTIN(GetCurrentExecutor)\n#undef SHOULD_NEVER_VISIT_BUILTIN\n\n\/\/ Builtins that should be lowered to SIL instructions so we should never see\n\/\/ them.\n#define BUILTIN_SIL_OPERATION(ID, NAME, CATEGORY)                              \\\n  OperandOwnership                                                             \\\n  OperandOwnershipBuiltinClassifier::visit##ID(BuiltinInst *, StringRef) {     \\\n    llvm_unreachable(\"Builtin should have been lowered to SIL instruction?!\"); \\\n  }\n#define BUILTIN(X, Y, Z)\n#include \"swift\/AST\/Builtins.def\"\n\nOperandOwnership OperandOwnershipClassifier::visitBuiltinInst(BuiltinInst *bi) {\n  return OperandOwnershipBuiltinClassifier(op).check(bi);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                            Top Level Entrypoint\n\/\/===----------------------------------------------------------------------===\/\/\n\nOperandOwnership Operand::getOperandOwnership() const {\n  \/\/ A type-dependent operant is a NonUse (as opposed to say an\n  \/\/ InstantaneousUse) because it does not require liveness.\n  if (isTypeDependent())\n    return OperandOwnership::NonUse;\n\n  \/\/ If we do not have ownership enabled, just return any. This ensures that we\n  \/\/ do not have any consuming uses and everything from an ownership perspective\n  \/\/ is just a liveness use short-circuiting many of the optimizations.\n  \/\/\n  \/\/ We do not ever call this function when an instruction isn't in a block.\n  assert(getUser()->getParent() &&\n         \"Can not lookup ownership constraint unless inserted into block\");\n  if (auto *block = getUser()->getParent()) {\n    auto *func = block->getParent();\n    \/\/ If we don't have a function, then we must have a SILGlobalVariable. In\n    \/\/ that case, we act as if we aren't in ownership.\n    if (!func || !func->hasOwnership()) {\n      return OperandOwnership(OperandOwnership::InstantaneousUse);\n    }\n  }\n\n  OperandOwnershipClassifier classifier(getUser()->getModule(), *this);\n  return classifier.visit(const_cast<SILInstruction *>(getUser()));\n}\n","avg_line_length":44.7557003257,"max_line_length":89,"alphanum_fraction":0.7760067928,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10300,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-3.0","Apache-2.0","MIT"],"max_stars_count":8.0,"content":"\/*************************************************************************\/\n\/*  skeleton_2d.cpp                                                      *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md).   *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"skeleton_2d.h\"\n#include \"core\/method_bind.h\"\n#include \"core\/translation_helpers.h\"\n#include \"servers\/rendering_server.h\"\n#include \"EASTL\/sort.h\"\n\nIMPL_GDCLASS(Bone2D)\nIMPL_GDCLASS(Skeleton2D)\n\nvoid Bone2D::_notification(int p_what) {\n\n    if (p_what == NOTIFICATION_ENTER_TREE) {\n        Node *parent = get_parent();\n        parent_bone = object_cast<Bone2D>(parent);\n        skeleton = nullptr;\n        while (parent) {\n            skeleton = object_cast<Skeleton2D>(parent);\n            if (skeleton)\n                break;\n            if (!object_cast<Bone2D>(parent))\n                break; \/\/skeletons must be chained to Bone2Ds.\n\n            parent = parent->get_parent();\n        }\n\n        if (skeleton) {\n            Skeleton2D::Bone bone;\n            bone.bone = this;\n            skeleton->bones.push_back(bone);\n            skeleton->_make_bone_setup_dirty();\n        }\n    }\n    if (p_what == NOTIFICATION_LOCAL_TRANSFORM_CHANGED) {\n        if (skeleton) {\n            skeleton->_make_transform_dirty();\n        }\n    }\n    if (p_what == NOTIFICATION_MOVED_IN_PARENT) {\n        if (skeleton) {\n            skeleton->_make_bone_setup_dirty();\n        }\n    }\n\n    if (p_what == NOTIFICATION_EXIT_TREE) {\n        if (skeleton) {\n            for (int i = 0; i < skeleton->bones.size(); i++) {\n                if (skeleton->bones[i].bone == this) {\n                    skeleton->bones.erase_at(i);\n                    break;\n                }\n            }\n            skeleton->_make_bone_setup_dirty();\n            skeleton = nullptr;\n        }\n        parent_bone = nullptr;\n    }\n}\nvoid Bone2D::_bind_methods() {\n\n    MethodBinder::bind_method(D_METHOD(\"set_rest\", {\"rest\"}), &Bone2D::set_rest);\n    MethodBinder::bind_method(D_METHOD(\"get_rest\"), &Bone2D::get_rest);\n    MethodBinder::bind_method(D_METHOD(\"apply_rest\"), &Bone2D::apply_rest);\n    MethodBinder::bind_method(D_METHOD(\"get_skeleton_rest\"), &Bone2D::get_skeleton_rest);\n    MethodBinder::bind_method(D_METHOD(\"get_index_in_skeleton\"), &Bone2D::get_index_in_skeleton);\n\n    MethodBinder::bind_method(D_METHOD(\"set_default_length\", {\"default_length\"}), &Bone2D::set_default_length);\n    MethodBinder::bind_method(D_METHOD(\"get_default_length\"), &Bone2D::get_default_length);\n\n    ADD_PROPERTY(PropertyInfo(VariantType::TRANSFORM2D, \"rest\"), \"set_rest\", \"get_rest\");\n    ADD_PROPERTY(PropertyInfo(VariantType::FLOAT, \"default_length\", PropertyHint::Range, \"1,1024,1\"), \"set_default_length\", \"get_default_length\");\n}\n\nvoid Bone2D::set_rest(const Transform2D &p_rest) {\n    rest = p_rest;\n    if (skeleton)\n        skeleton->_make_bone_setup_dirty();\n\n    update_configuration_warning();\n}\n\nTransform2D Bone2D::get_rest() const {\n    return rest;\n}\n\nTransform2D Bone2D::get_skeleton_rest() const {\n\n    if (parent_bone) {\n        return parent_bone->get_skeleton_rest() * rest;\n    } else {\n        return rest;\n    }\n}\n\nvoid Bone2D::apply_rest() {\n    set_transform(rest);\n}\n\nvoid Bone2D::set_default_length(float p_length) {\n\n    default_length = p_length;\n}\n\nfloat Bone2D::get_default_length() const {\n    return default_length;\n}\n\nint Bone2D::get_index_in_skeleton() const {\n    ERR_FAIL_COND_V(!skeleton, -1);\n    skeleton->_update_bone_setup();\n    return skeleton_index;\n}\nString Bone2D::get_configuration_warning() const {\n\n    String warning(Node2D::get_configuration_warning());\n    if (!skeleton) {\n        if (!warning.empty()) {\n            warning += \"\\n\\n\";\n        }\n        if (parent_bone) {\n            warning += TTR(\"This Bone2D chain should end at a Skeleton2D node.\");\n        } else {\n            warning += TTR(\"A Bone2D only works with a Skeleton2D or another Bone2D as parent node.\");\n        }\n    }\n\n    if (rest == Transform2D(0, 0, 0, 0, 0, 0)) {\n        if (!warning.empty()) {\n            warning += \"\\n\\n\";\n        }\n        warning += TTR(\"This bone lacks a proper REST pose. Go to the Skeleton2D node and set one.\");\n    }\n\n    return warning;\n}\n\nBone2D::Bone2D() {\n    skeleton = nullptr;\n    parent_bone = nullptr;\n    skeleton_index = -1;\n    default_length = 16;\n    set_notify_local_transform(true);\n    \/\/this is a clever hack so the bone knows no rest has been set yet, allowing to show an error.\n    for (int i = 0; i < 3; i++) {\n        rest[i] = Vector2(0, 0);\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Skeleton2D::_make_bone_setup_dirty() {\n\n    if (bone_setup_dirty)\n        return;\n    bone_setup_dirty = true;\n    if (is_inside_tree()) {\n        call_deferred([this]() { _update_bone_setup(); });\n    }\n}\n\nvoid Skeleton2D::_update_bone_setup() {\n\n    if (!bone_setup_dirty)\n        return;\n\n    bone_setup_dirty = false;\n    RenderingServer::get_singleton()->skeleton_allocate(skeleton, bones.size(), true);\n    eastl::sort(bones.begin(), bones.end()); \/\/sorty so they are always in the same order\/index\n\n    for (int i = 0; i < bones.size(); i++) {\n        bones[i].rest_inverse = bones[i].bone->get_skeleton_rest().affine_inverse(); \/\/bind pose\n        bones[i].bone->skeleton_index = i;\n        Bone2D *parent_bone = object_cast<Bone2D>(bones[i].bone->get_parent());\n        if (parent_bone) {\n            bones[i].parent_index = parent_bone->skeleton_index;\n        } else {\n            bones[i].parent_index = -1;\n        }\n    }\n\n    transform_dirty = true;\n    _update_transform();\n    emit_signal(\"bone_setup_changed\");\n}\n\nvoid Skeleton2D::_make_transform_dirty() {\n\n    if (transform_dirty)\n        return;\n    transform_dirty = true;\n    if (is_inside_tree()) {\n        call_deferred([this]() { _update_transform(); });\n    }\n}\n\nvoid Skeleton2D::_update_transform() {\n\n    if (bone_setup_dirty) {\n        _update_bone_setup();\n        return; \/\/above will update transform anyway\n    }\n    if (!transform_dirty)\n        return;\n\n    transform_dirty = false;\n\n    for (int i = 0; i < bones.size(); i++) {\n\n        ERR_CONTINUE(bones[i].parent_index >= i);\n        if (bones[i].parent_index >= 0) {\n            bones[i].accum_transform = bones[bones[i].parent_index].accum_transform * bones[i].bone->get_transform();\n        } else {\n            bones[i].accum_transform = bones[i].bone->get_transform();\n        }\n    }\n\n    for (int i = 0; i < bones.size(); i++) {\n\n        Transform2D final_xform = bones[i].accum_transform * bones[i].rest_inverse;\n        RenderingServer::get_singleton()->skeleton_bone_set_transform_2d(skeleton, i, final_xform);\n    }\n}\n\nint Skeleton2D::get_bone_count() const {\n\n    ERR_FAIL_COND_V(!is_inside_tree(), 0);\n\n    if (bone_setup_dirty) {\n        const_cast<Skeleton2D *>(this)->_update_bone_setup();\n    }\n\n    return bones.size();\n}\n\nBone2D *Skeleton2D::get_bone(int p_idx) {\n\n    ERR_FAIL_COND_V(!is_inside_tree(), nullptr);\n    ERR_FAIL_INDEX_V(p_idx, bones.size(), nullptr);\n\n    return bones[p_idx].bone;\n}\n\nvoid Skeleton2D::_notification(int p_what) {\n\n    if (p_what == NOTIFICATION_READY) {\n\n        if (bone_setup_dirty)\n            _update_bone_setup();\n        if (transform_dirty)\n            _update_transform();\n\n        request_ready();\n    }\n\n    if (p_what == NOTIFICATION_TRANSFORM_CHANGED) {\n        RenderingServer::get_singleton()->skeleton_set_base_transform_2d(skeleton, get_global_transform());\n    }\n}\n\nRID Skeleton2D::get_skeleton() const {\n    return skeleton;\n}\nvoid Skeleton2D::_bind_methods() {\n\n    MethodBinder::bind_method(D_METHOD(\"_update_bone_setup\"), &Skeleton2D::_update_bone_setup);\n    MethodBinder::bind_method(D_METHOD(\"_update_transform\"), &Skeleton2D::_update_transform);\n\n    MethodBinder::bind_method(D_METHOD(\"get_bone_count\"), &Skeleton2D::get_bone_count);\n    MethodBinder::bind_method(D_METHOD(\"get_bone\", {\"idx\"}), &Skeleton2D::get_bone);\n\n    MethodBinder::bind_method(D_METHOD(\"get_skeleton\"), &Skeleton2D::get_skeleton);\n\n    ADD_SIGNAL(MethodInfo(\"bone_setup_changed\"));\n}\n\nSkeleton2D::Skeleton2D() {\n    bone_setup_dirty = true;\n    transform_dirty = true;\n\n    skeleton = RenderingServer::get_singleton()->skeleton_create();\n    set_notify_transform(true);\n}\n\nSkeleton2D::~Skeleton2D() {\n\n    RenderingServer::get_singleton()->free_rid(skeleton);\n}\n","avg_line_length":32.4921135647,"max_line_length":146,"alphanum_fraction":0.5924271845,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10855,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":19.0,"content":"#include \"networkPowerStream.hpp\"\n\n#include \"Config.hpp\"          \/\/ for Config\n#include \"StageFactory.hpp\"    \/\/ for REGISTER_KOTEKAN_STAGE, StageMakerTemplate\n#include \"buffer.h\"            \/\/ for mark_frame_empty, wait_for_full_frame, register_consumer\n#include \"bufferContainer.hpp\" \/\/ for bufferContainer\n#include \"kotekanLogging.hpp\"  \/\/ for ERROR, INFO\n\n#include <arpa\/inet.h>  \/\/ for inet_addr, inet_aton\n#include <exception>    \/\/ for exception\n#include <functional>   \/\/ for _Bind_helper<>::type, bind, function\n#include <netinet\/in.h> \/\/ for sockaddr_in, htons, IPPROTO_TCP, IPPROTO_UDP, in_addr\n#include <regex>        \/\/ for match_results<>::_Base_type\n#include <stdexcept>    \/\/ for runtime_error\n#include <stdlib.h>     \/\/ for free, malloc\n#include <string.h>     \/\/ for memcpy, memset\n#include <string>       \/\/ for string, allocator, operator==\n#include <sys\/socket.h> \/\/ for send, socket, AF_INET, connect, sendto, setsockopt, SOCK_...\n#include <sys\/time.h>   \/\/ for timeval, gettimeofday\n#include <sys\/types.h>  \/\/ for uint\n#include <unistd.h>     \/\/ for close\n#include <vector>       \/\/ for vector\n\n\nusing kotekan::bufferContainer;\nusing kotekan::Config;\nusing kotekan::Stage;\n\nREGISTER_KOTEKAN_STAGE(networkPowerStream);\n\nnetworkPowerStream::networkPowerStream(Config& config, const std::string& unique_name,\n                                       bufferContainer& buffer_container) :\n    Stage(config, unique_name, buffer_container,\n          std::bind(&networkPowerStream::main_thread, this)) {\n\n    in_buf = get_buffer(\"in_buf\");\n    register_consumer(in_buf, unique_name.c_str());\n\n    \/\/ PER BUFFER\n    times = config.get<int>(unique_name, \"samples_per_data_set\")\n            \/ config.get<int>(unique_name, \"power_integration_length\");\n    freqs = config.get<int>(unique_name, \"num_freq\");\n    elems = config.get<int>(unique_name, \"num_elements\");\n\n    freq0 = config.get_default<float>(unique_name, \"freq\", 600.) * 1e6;\n    sample_bw = config.get_default<float>(unique_name, \"sample_bw\", 200.) * 1e6;\n\n    dest_port = config.get<uint32_t>(unique_name, \"destination_port\");\n    dest_server_ip = config.get<std::string>(unique_name, \"destination_ip\");\n    dest_protocol = config.get<std::string>(unique_name, \"destination_protocol\");\n\n    atomic_flag_clear(&socket_lock);\n\n    header.packet_length = freqs * sizeof(float);\n    header.header_length = sizeof(IntensityPacketHeader);\n    header.samples_per_packet = freqs;\n    header.sample_type = 4;                       \/\/ uint32\n    header.raw_cadence = 1 \/ (sample_bw \/ freqs); \/\/ 2.56e-6;\n    header.num_freqs = freqs;\n    header.num_elems = elems;\n    header.samples_summed = config.get<int>(unique_name, \"power_integration_length\");\n    header.handshake_idx = -1;\n    header.handshake_utc = -1;\n\n    frame_idx = 0;\n\n    \/\/ Prevent SIGPIPE on send failure.\n    \/\/ This is used for MacOS, since linux doesn't have SO_NOSIGPIPE\n#ifdef SO_NOSIGPIPE\n    int set = 1;\n    if (setsockopt(socket_fd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int)) < 0) {\n        ERROR(\"bufferSend: setsockopt() NOSIGPIPE \");\n    }\n#endif\n}\n\nnetworkPowerStream::~networkPowerStream() {}\n\nvoid networkPowerStream::main_thread() {\n    int frame_id = 0;\n    uint8_t* frame = nullptr;\n    uint packet_length = freqs * sizeof(float) + sizeof(IntensityPacketHeader);\n    void* packet_buffer = malloc(packet_length);\n    IntensityPacketHeader* packet_header = (IntensityPacketHeader*)packet_buffer;\n    float* local_data = (float*)((char*)packet_buffer + sizeof(IntensityPacketHeader));\n    struct timeval tv;\n\n    if (dest_protocol == \"UDP\") {\n        \/\/ UDP variables\n        struct sockaddr_in saddr_remote; \/* the libc network address data structure *\/\n        socket_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);\n        if (socket_fd == -1) {\n            ERROR(\"Could not create UDP socket for output stream\");\n            return;\n        }\n\n        memset((char*)&saddr_remote, 0, sizeof(sockaddr_in));\n        saddr_remote.sin_family = AF_INET;\n        saddr_remote.sin_port = htons(dest_port);\n        if (inet_aton(dest_server_ip.c_str(), &saddr_remote.sin_addr) == 0) {\n            ERROR(\"Invalid address given for remote server\");\n            return;\n        }\n        INFO(\"{:d} {:s}\", dest_port, dest_server_ip);\n\n        while (!stop_thread) {\n            \/\/ Wait for a full buffer.\n            frame = wait_for_full_frame(in_buf, unique_name.c_str(), frame_id);\n            if (frame == nullptr)\n                break;\n\n            for (int t = 0; t < times; t++) {\n                packet_header->frame_idx = frame_idx++;\n                for (int p = 0; p < elems; p++) {\n                    packet_header->elem_idx = p;\n                    packet_header->samples_summed =\n                        ((uint*)frame)[t * elems * (freqs + 1) + p * (freqs + 1) + freqs];\n                    memcpy(local_data, frame + (t * elems + p) * (freqs + 1) * sizeof(uint),\n                           freqs * sizeof(uint));\n                    \/\/ Send data to remote server.\n                    uint32_t bytes_sent =\n                        sendto(socket_fd, packet_buffer, packet_length, 0,\n                               (struct sockaddr*)&saddr_remote, sizeof(sockaddr_in));\n                    if (bytes_sent != packet_length)\n                        ERROR(\"SOMETHING WENT WRONG IN UDP TRANSMIT\");\n                }\n            }\n\n            \/\/ Mark buffer as empty.\n            mark_frame_empty(in_buf, unique_name.c_str(), frame_id);\n            frame_id = (frame_id + 1) % in_buf->num_frames;\n        }\n    } else if (dest_protocol == \"TCP\") {\n        \/\/ TCP variables\n        while (!stop_thread) {\n            \/\/ Wait for a full buffer.\n            frame = wait_for_full_frame(in_buf, unique_name.c_str(), frame_id);\n            if (frame == nullptr)\n                break;\n\n            while (atomic_flag_test_and_set(&socket_lock)) {\n            }\n            if (tcp_connected) {\n                atomic_flag_clear(&socket_lock);\n                for (int t = 0; t < times; t++) {\n                    packet_header->frame_idx = frame_idx++;\n                    for (int p = 0; p < elems; p++) {\n                        packet_header->elem_idx = p;\n                        packet_header->samples_summed =\n                            ((uint*)frame)[t * elems * (freqs + 1) + p * (freqs + 1) + freqs];\n                        memcpy(local_data, frame + (t * elems + p) * (freqs + 1) * sizeof(uint),\n                               freqs * sizeof(uint));\n                        uint32_t bytes_sent = send(socket_fd, packet_buffer, packet_length, 0);\n                        if (bytes_sent != packet_length) {\n                            ERROR(\"Lost TCP connection!\");\n                            while (atomic_flag_test_and_set(&socket_lock)) {\n                            }\n                            close(socket_fd);\n                            tcp_connected = false;\n                            atomic_flag_clear(&socket_lock);\n                            break;\n                        }\n                    }\n                }\n            } else if (!tcp_connecting) {\n                frame_idx += times;\n                handshake_idx = frame_idx;\n                gettimeofday(&tv, nullptr);\n                handshake_utc = tv.tv_sec + tv.tv_usec \/ 1e6;\n                tcp_connecting = true;\n                atomic_flag_clear(&socket_lock);\n                std::thread(&networkPowerStream::tcpConnect, this).detach();\n            } else {\n                frame_idx += times;\n                atomic_flag_clear(&socket_lock);\n            }\n            \/\/ Mark buffer as empty.\n            mark_frame_empty(in_buf, unique_name.c_str(), frame_id);\n            frame_id = (frame_id + 1) % in_buf->num_frames;\n        }\n\n    } else\n        ERROR(\"Bad protocol: {:s}\\n\", dest_protocol);\n\n    free(packet_buffer);\n}\n\nvoid networkPowerStream::tcpConnect() {\n    \/\/    INFO(\"Connecting TCP Power Stream!\");\n    struct sockaddr_in address;\n    address.sin_addr.s_addr = inet_addr(dest_server_ip.c_str());\n    address.sin_port = htons(dest_port);\n    address.sin_family = AF_INET;\n\n    socket_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n    if (socket_fd == -1) {\n        ERROR(\"Could not create TCP socket for output stream\");\n        return;\n    }\n\n    \/\/ TODO: handle errors, make dynamic\n    struct timeval timeout;\n    timeout.tv_sec = 0;\n    timeout.tv_usec = 200000;\n\n    if (connect(socket_fd, (struct sockaddr*)&address, sizeof(address)) != 0) {\n        while (atomic_flag_test_and_set(&socket_lock)) {\n        }\n        tcp_connecting = false;\n        close(socket_fd);\n        atomic_flag_clear(&socket_lock);\n        return;\n    }\n    setsockopt(socket_fd, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout, sizeof(timeout));\n\n    { \/\/ put together handshake\n        while (atomic_flag_test_and_set(&socket_lock)) {\n        }\n        header.handshake_idx = handshake_idx;\n        header.handshake_utc = handshake_utc;\n        atomic_flag_clear(&socket_lock);\n        int bytes_sent = send(socket_fd, (void*)&header, sizeof(header), 0);\n        if (bytes_sent != sizeof(header)) {\n            ERROR(\"Could not send TCP header for output stream\");\n            while (atomic_flag_test_and_set(&socket_lock)) {\n            }\n            close(socket_fd);\n            tcp_connected = false;\n            atomic_flag_clear(&socket_lock);\n            return;\n        }\n        \/\/ FIXME: remove hardcoding of freq & Stokes\n        int info_size = freqs * 2 * sizeof(float) + elems * sizeof(char);\n        void* info = malloc(info_size);\n        for (int f = 0; f < freqs; f++) {\n            ((float*)info)[2 * f] = freq0 - sample_bw \/ 2 + sample_bw \/ freqs * ((float)f);\n            ((float*)info)[2 * f + 1] = freq0 - sample_bw \/ 2 + sample_bw \/ freqs * ((float)f + 1);\n            \/\/            ((float*)info)[2*f]   = 800e6 - 400e6* f   \/1024;\n            \/\/            ((float*)info)[2*f+1] = 800e6 - 400e6*(f+1)\/1024;\n        }\n        \/\/ - description of stream (e.g. V \/ H pol, Stokes-I \/ Q \/ U \/ V)\n        \/\/  -8  -7  -6  -5  -4  -3  -2  -1  1   2   3   4\n        \/\/  YX  XY  YY  XX  LR  RL  LL  RR  I   Q   U   V\n        for (int e = 0; e < elems; e++)\n            ((char*)((char*)info + info_size - elems * sizeof(char)))[e] = -5 - e;\n        bytes_sent = send(socket_fd, info, info_size, 0);\n        free(info);\n        if (bytes_sent != info_size) {\n            ERROR(\"Could not send TCP header for output stream\");\n            while (atomic_flag_test_and_set(&socket_lock)) {\n            }\n            close(socket_fd);\n            tcp_connected = false;\n            atomic_flag_clear(&socket_lock);\n            return;\n        }\n    }\n    while (atomic_flag_test_and_set(&socket_lock)) {\n    }\n    tcp_connected = true;\n    tcp_connecting = false;\n    atomic_flag_clear(&socket_lock);\n}\n","avg_line_length":41.1174242424,"max_line_length":99,"alphanum_fraction":0.5709811147,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2071,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":1.0,"content":"\/**\n * 2022 SuperBart, this is an absolutely free software released under\n * SuperBart Public Domain Software License.\n * You may gain a copy of this from https:\/\/benderblog.github.io\/License.html\n *\n * This header file is a part of College ID Card and College Bus Simulation Program.\n *\n * bus_process.cpp\n * Description:\n *      Implemention of bus_process.hpp. I think code them separately is better.\n *\n *\/\n\n#include \"bus_process.hpp\"\nusing namespace maggie;\n\nvoid bus_process::add_bus()\n{\n    uint b_num, b_size;\n    string b_driver;\n    cout << \"\u65b0\u5efa\u73ed\u8f66\u4fe1\u606f\\n\u4f9d\u6b21\u8f93\u5165\u9a7e\u9a76\u5458\u59d3\u540d\u3001\u7f16\u53f7\u3001\u8f7d\u4e58\u4eba(30\u621650)\\n\";\n    cout << \"\u8f93\u5165\u201c0 0 0\u201d\u9000\u51fa\u65b0\u5efa\u73ed\u8f66\\n\";\n    while (cin >> b_driver >> b_num >> b_size && b_num != 0)\n    {\n        bool isbig = false;\n        if (b_size == 50)\n            isbig = true;\n        bus toappend(b_driver, b_num, isbig);\n        station.push_back(toappend);\n    }\n}\n\nvoid bus_process::bus_management()\n{\n    uint choose;\n    cout << \"1. \u65b0\u5efa\u73ed\u8f66\\n2. \u67e5\u770b\u73ed\u8f66\\n0. \u9000\u51fa\\n\";\n    while (cin >> choose)\n    {\n        switch (choose)\n        {\n        case 1:\n            add_bus();\n            break;\n        case 2:\n            list_bus(station);\n            break;\n        case 0:\n            return;\n        default:\n            cout << \"\u8f93\u5165\u9519\u8bef\uff0c\u8bf7\u91cd\u65b0\u8f93\u5165\\n\";\n            break;\n        }\n        cout << \"1. \u65b0\u5efa\u73ed\u8f66\\n2. \u67e5\u770b\u73ed\u8f66\\n0. \u9000\u51fa\\n\";\n    }\n}\n\nvoid bus_process::list_bus(vector<bus> &list)\n{\n    for (auto &i : list)\n    {\n        cout << i.print();\n    }\n}\n\nvoid bus_process::read_station()\n{\n    cout << \"Reading bus...\\n\";\n    ifstream fin(\"bus.txt\");\n    if (!fin)\n    {\n        cout << \"\u6587\u4ef6\u6253\u5f00\u5931\u8d25\\n\";\n        return;\n    }\n    string b_driver;\n    uint b_id;\n    bool b_model;\n    while (fin >> b_driver >> b_id >> b_model)\n    {\n        bus toappend(b_driver, b_id, b_model);\n        station.push_back(toappend);\n    }\n    fin.close();\n}\n\nvoid bus_process::save_station()\n{\n    cout << \"Saving station.\\n\";\n    ofstream fout(\"bus.txt\");\n    if (!fout)\n    {\n        cout << \"\u6587\u4ef6\u6253\u5f00\u5931\u8d25\\n\";\n        return;\n    }\n    for (auto &i : station)\n    {\n        fout << i.print();\n    }\n    fout.close();\n}\n","avg_line_length":20.71,"max_line_length":84,"alphanum_fraction":0.5432158378,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13951,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"CubeMap.h\"\r\n#include \"core\/Engine.h\"\r\n#include \"core\/renderer\/ShaderProgram.h\"\r\n#include \"core\/ResourceHandler.h\"\r\n#include \"core\/util\/FileUtils.h\"\r\n\r\nShaderProgram* CubeMap::s_equirectangularShader = NULL;\r\n\r\nCubeMap::CubeMap(uint32_t width, uint32_t height, TextureFormat format, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap, TextureWrap wWrap):\r\n\tTexture(TextureTarget::TEXTURE_CUBEMAP, format, minFilter, magFilter),\r\n\tm_width(width),\r\n\tm_height(height) {\r\n\r\n\tthis->setSize(width, height);\r\n\tthis->setWrapMode(uWrap, vWrap, wWrap);\r\n\tthis->setFilterMode(minFilter, magFilter);\r\n}\r\n\r\nCubeMap::~CubeMap() {\r\n\tTexture::~Texture();\r\n}\r\n\r\nbool CubeMap::load(CubemapConfiguration config, CubeMap** dstCubemapPtr) {\r\n\tif (!config.equirectangularFilePath.empty()) {\r\n\t\treturn CubeMap::loadEquirectangular(config, dstCubemapPtr);\r\n\t} else {\r\n\t\treturn CubeMap::loadFaces(config, dstCubemapPtr);\r\n\t}\r\n}\r\n\r\nbool CubeMap::loadEquirectangular(CubemapConfiguration config, CubeMap** dstCubemapPtr) {\r\n\tif (config.equirectangularFilePath.empty()) {\r\n\t\treturn false;\r\n\t}\r\n\r\n\tif (dstCubemapPtr == NULL) {\r\n\t\treturn false;\r\n\t}\r\n\r\n\tImage image;\r\n\tif (!FileUtils::loadImage(config.equirectangularFilePath, image, config.verticallyFlip, config.floatingPoint)) {\r\n\t\tinfo(\"Failed to load image file \\\"%s\\\"\\n\", config.equirectangularFilePath.c_str());\r\n\t\treturn false;\r\n\t}\r\n\r\n\t\/\/std::vector<float> floats(data);\r\n\tTextureFormat format = config.floatingPoint ? TextureFormat::R32_G32_B32_FLOAT : TextureFormat::DEFAULT_RGB;\r\n\tswitch (image.channels) {\r\n\t\tcase 1: format = config.floatingPoint ? TextureFormat::R32_FLOAT : TextureFormat::DEFAULT_GRAYSCALE; break;\r\n\t\tcase 2: format = config.floatingPoint ? TextureFormat::R32_G32_FLOAT : TextureFormat::DEFAULT_RG; break;\r\n\t\tcase 3: format = config.floatingPoint ? TextureFormat::R32_G32_B32_FLOAT : TextureFormat::DEFAULT_RGB; break;\r\n\t\tcase 4: format = config.floatingPoint ? TextureFormat::R32_G32_B32_A32_FLOAT : TextureFormat::DEFAULT_RGBA; break;\r\n\t\tdefault:\r\n\t\t\terror(\"Loaded image with unsupported channel configuration\\n\");\r\n\t\t\treturn false;\r\n\t}\r\n\r\n\tCubeMap* dstCubemap = *dstCubemapPtr;\r\n\tuint32_t faceWidth = image.width \/ 4;\r\n\tuint32_t faceHeight = image.height \/ 2;\r\n\r\n\tif (dstCubemap == NULL) {\r\n\t\t*dstCubemapPtr = new CubeMap(faceWidth, faceHeight, format);\r\n\t\tdstCubemap = *dstCubemapPtr;\r\n\t}\r\n\r\n\t\/\/if (dstCubemap->getWidth() < faceWidth || dstCubemap->getHeight() < faceHeight) {\r\n\tdstCubemap->setSize(faceWidth, faceHeight, GL_RGBA);\r\n\t\/\/}\r\n\r\n\tdstCubemap->upload(image.data, image.width, image.height);\r\n\treturn true;\r\n}\r\n\r\nbool CubeMap::loadFaces(CubemapConfiguration config, CubeMap** dstCubemapPtr) {\r\n\tstd::string filePaths[6];\r\n\tfilePaths[(int)CubeMapFace::RIGHT] = config.rightFilePath;\r\n\tfilePaths[(int)CubeMapFace::LEFT] = config.leftFilePath;\r\n\tfilePaths[(int)CubeMapFace::TOP] = config.topFilePath;\r\n\tfilePaths[(int)CubeMapFace::BOTTOM] = config.bottomFilePath;\r\n\tfilePaths[(int)CubeMapFace::BACK] = config.backFilePath;\r\n\tfilePaths[(int)CubeMapFace::FRONT] = config.frontFilePath;\r\n\r\n\tif (dstCubemapPtr == NULL) {\r\n\t\treturn false;\r\n\t}\r\n\r\n\tuint32_t faceWidth;\r\n\tuint32_t faceHeight;\r\n\tuint32_t channels;\r\n\tImage* faceImages[6];\r\n\tvoid* data[6];\r\n\r\n\tfor (int i = 0; i < 6; i++) {\r\n\t\tfaceImages[i] = new Image();\r\n\r\n\t\tif (filePaths[i].empty()) {\r\n\t\t\tinfo(\"Could not load cubemap - face %d was not specified\\n\", i);\r\n\t\t\tfor (int j = 0; j <= i; j++) delete faceImages[j];\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tif (!FileUtils::loadImage(filePaths[i], *faceImages[i], config.verticallyFlip, config.floatingPoint)) {\r\n\t\t\tinfo(\"Failed to load image file \\\"%s\\\"\\n\", filePaths[i].c_str());\r\n\t\t\tinfo(\"Could not load cubemap - face %d was not found\\n\", i);\r\n\t\t\tfor (int j = 0; j <= i; j++) delete faceImages[j];\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tdata[i] = faceImages[i]->data;\r\n\r\n\t\tif (i == 0) {\r\n\t\t\tfaceWidth = faceImages[i]->width;\r\n\t\t\tfaceHeight = faceImages[i]->height;\r\n\t\t\tchannels = faceImages[i]->channels;\r\n\t\t} else {\r\n\t\t\tif (faceImages[i]->width != faceWidth || faceImages[i]->height != faceHeight || faceImages[i]->channels != channels) {\r\n\t\t\t\tinfo(\"Could not load cubemap - size of face %d does not match previous faces\\n\", i);\r\n\t\t\t\tfor (int j = 0; j <= i; j++) delete faceImages[j];\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tTextureFormat format = TextureFormat::DEFAULT_RGB;\r\n\tswitch (channels) {\r\n\t\tcase 1: format = TextureFormat::DEFAULT_GRAYSCALE; break;\r\n\t\tcase 2: format = TextureFormat::DEFAULT_RG; break;\r\n\t\tcase 3: format = TextureFormat::DEFAULT_RGB; break;\r\n\t\tcase 4: format = TextureFormat::DEFAULT_RGBA; break;\r\n\t\tdefault:\r\n\t\t\terror(\"Could not load cubemap - unsupported channel configuration\\n\");\r\n\t\t\treturn false;\r\n\t}\r\n\r\n\tCubeMap* dstCubemap = *dstCubemapPtr;\r\n\r\n\tif (dstCubemap == NULL) {\r\n\t\t*dstCubemapPtr = new CubeMap(faceWidth, faceHeight, format);\r\n\t\tdstCubemap = *dstCubemapPtr;\r\n\t}\r\n\r\n\tif (dstCubemap->getWidth() < faceWidth || dstCubemap->getHeight() < faceHeight) {\r\n\t\tdstCubemap->setSize(faceWidth, faceHeight);\r\n\t}\r\n\r\n\tdstCubemap->upload(data, faceWidth, faceHeight);\r\n\r\n\tfor (int j = 0; j < 6; j++) delete faceImages[j];\r\n}\r\n\r\nvoid CubeMap::upload(void* data, uint32_t width, uint32_t height) {\r\n\tCubeMap::uploadEquirectangular(this, data, width, height);\r\n}\r\n\r\nvoid CubeMap::upload(void* data[6], uint32_t width, uint32_t height) {\r\n\tCubeMap::uploadCubeFaces(this, data, width, height);\r\n}\r\n\r\nvoid CubeMap::bind(uint32_t textureUnit) {\r\n\tOpenGLTextureTarget target = Texture::getOpenGLTextureTarget(m_target);\r\n\tglActiveTexture(GL_TEXTURE0 + textureUnit);\r\n\tglBindTexture(target.target, m_textureName);\r\n}\r\n\r\nvoid CubeMap::unbind() {\r\n\tOpenGLTextureTarget target = Texture::getOpenGLTextureTarget(m_target);\r\n\tglBindTexture(target.target, 0);\r\n}\r\n\r\nuint64_t CubeMap::getMemorySize() const {\r\n\treturn Texture::getPixelSize(m_format) * m_width * m_height * 6;\r\n}\r\n\r\nvoid CubeMap::setSize(uint32_t width, uint32_t height, uint32_t externalFormat) {\r\n\tif (width != m_width || height != m_height || externalFormat != GL_NONE) {\r\n\t\tm_width = width;\r\n\t\tm_height = height;\r\n\t\tOpenGLTextureFormat format = Texture::getOpenGLTextureFormat(m_format, externalFormat);\r\n\r\n\t\tthis->bind();\r\n\t\tfor (int i = 0; i < 6; i++) {\r\n\t\t\tOpenGLTextureTarget target = CubeMap::getOpenGLFaceTarget((CubeMapFace)i);\r\n\t\t\tglTexImage2D(target.target, 0, format.internalFormat, width, height, 0, format.externalFormat, format.type, NULL);\r\n\t\t}\r\n\t\tthis->unbind();\r\n\t}\r\n}\r\n\r\nbool CubeMap::setWrapMode(TextureWrap u, TextureWrap v, TextureWrap w) {\r\n\tif (u != m_uWrap || v != m_vWrap || w != m_wWrap) {\r\n\t\tOpenGLTextureTarget target = Texture::getOpenGLTextureTarget(m_target);\r\n\t\tOpenGLTextureWrap wrap = Texture::getOpenGLTextureWrap(u, v, w);\r\n\t\tif (wrap.u == GL_NONE || wrap.v == GL_NONE || wrap.w == GL_NONE) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tm_uWrap = u;\r\n\t\tm_vWrap = v;\r\n\t\tm_wWrap = w;\r\n\r\n\t\tthis->bind();\r\n\t\tglTexParameteri(target.target, GL_TEXTURE_WRAP_S, wrap.u);\r\n\t\tglTexParameteri(target.target, GL_TEXTURE_WRAP_T, wrap.v);\r\n\t\tglTexParameteri(target.target, GL_TEXTURE_WRAP_R, wrap.w);\r\n\t\tthis->unbind();\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/CubemapFaceTexture* CubeMap::getFaceTexture(CubeMapFace face) const {\r\n\/\/\treturn m_faces[(int) face];\r\n\/\/}\r\n\r\nTextureWrap CubeMap::getUWrapFilterMode() const {\r\n\treturn m_uWrap;\r\n}\r\n\r\nTextureWrap CubeMap::getVWrapFilterMode() const {\r\n\treturn m_vWrap;\r\n}\r\n\r\nTextureWrap CubeMap::getWWrapFilterMode() const {\r\n\treturn m_wWrap;\r\n}\r\n\r\nuint32_t CubeMap::getWidth() const {\r\n\treturn m_width;\r\n}\r\n\r\nuint32_t CubeMap::getHeight() const {\r\n\treturn m_height;\r\n}\r\n\r\nTextureTarget CubeMap::getFaceTarget(CubeMapFace index) {\r\n\tswitch (index) {\r\n\t\tcase CubeMapFace::POSITIVE_X: return TextureTarget::TEXTURE_CUBEMAP_POSITIVE_X;\r\n\t\tcase CubeMapFace::NEGATIVE_X: return TextureTarget::TEXTURE_CUBEMAP_NEGATIVE_X;\r\n\t\tcase CubeMapFace::POSITIVE_Y: return TextureTarget::TEXTURE_CUBEMAP_POSITIVE_Y;\r\n\t\tcase CubeMapFace::NEGATIVE_Y: return TextureTarget::TEXTURE_CUBEMAP_NEGATIVE_Y;\r\n\t\tcase CubeMapFace::POSITIVE_Z: return TextureTarget::TEXTURE_CUBEMAP_POSITIVE_Z;\r\n\t\tcase CubeMapFace::NEGATIVE_Z: return TextureTarget::TEXTURE_CUBEMAP_NEGATIVE_Z;\r\n\t\tdefault: assert(false); \/\/ shouldnt be possible\r\n\t}\r\n}\r\n\r\nOpenGLTextureTarget CubeMap::getOpenGLFaceTarget(CubeMapFace index) {\r\n\treturn Texture::getOpenGLTextureTarget(CubeMap::getFaceTarget(index));\r\n}\r\n\r\nvoid CubeMap::uploadEquirectangular(Texture* texture, void* data, uint32_t width, uint32_t height) {\r\n\tif (s_equirectangularShader == NULL) {\r\n\t\ts_equirectangularShader = new ShaderProgram();\r\n\t\ts_equirectangularShader->addShader(GL_COMPUTE_SHADER, \"shaders\/compute\/equirectangular\/comp.glsl\");\r\n\t\ts_equirectangularShader->completeProgram();\r\n\t}\r\n\r\n\tOpenGLTextureFormat format = Texture::getOpenGLTextureFormat(texture->getFormat());\r\n\r\n\tuint32_t tempTextureHandle = 0; \/\/ Build temp texture storing the equirectangular data as RGBA32F\r\n\tglGenTextures(1, &tempTextureHandle);\r\n\tglBindTexture(GL_TEXTURE_2D, tempTextureHandle);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, format.externalFormat, format.type, data);\r\n\r\n\tint faceWidth = width \/ 4;\r\n\tint faceHeight = height \/ 2;\r\n\tShaderProgram::use(s_equirectangularShader);\r\n\ts_equirectangularShader->setUniform(\"faceSize\", faceWidth, faceHeight);\r\n\tglBindImageTexture(0, tempTextureHandle, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA32F);\r\n\tglBindImageTexture(1, texture->getTextureName(), 0, GL_TRUE, 0, GL_WRITE_ONLY, format.internalFormat);\r\n\tglDispatchCompute((int)ceil(faceWidth \/ 16), (int)ceil(faceHeight \/ 16), 1);\r\n\tShaderProgram::use(NULL);\r\n\r\n\tglDeleteTextures(1, &tempTextureHandle);\r\n}\r\n\r\nvoid CubeMap::uploadCubeFaces(Texture* texture, void* data[6], uint32_t width, uint32_t height) {\r\n\tOpenGLTextureFormat format = Texture::getOpenGLTextureFormat(texture->getFormat());\r\n\r\n\ttexture->bind();\r\n\tfor (int i = 0; i < 6; i++) {\r\n\t\tOpenGLTextureTarget target = CubeMap::getOpenGLFaceTarget((CubeMapFace)i);\r\n\t\tglTexImage2D(target.target, 0, format.internalFormat, width, height, 0, format.externalFormat, format.type, data[i]);\r\n\t}\r\n\ttexture->unbind();\r\n}\r\n\r\n\r\n\r\n\r\nCubeMapArray::CubeMapArray(uint32_t width, uint32_t height, uint32_t layers, TextureFormat format, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap, TextureWrap wWrap):\r\n\tTexture(TextureTarget::TEXTURE_CUBEMAP, format, minFilter, magFilter),\r\n\tm_width(width),\r\n\tm_height(height) {\r\n\tthis->setSize(width, height, layers);\r\n\tthis->setWrapMode(uWrap, vWrap, wWrap);\r\n\tthis->setFilterMode(minFilter, magFilter);\r\n}\r\n\r\nCubeMapArray::~CubeMapArray() {\r\n\tTexture::~Texture();\r\n}\r\n\r\nvoid CubeMapArray::upload(std::vector<void*> data, uint32_t width, uint32_t height) {\r\n\tfor (int i = 0; i < data.size(); i++) {\r\n\t\tthis->upload(data[i], width, height);\r\n\t}\r\n}\r\n\r\nvoid CubeMapArray::upload(void* data, uint32_t layer, uint32_t width, uint32_t height) {\r\n\tassert(false); \/\/ unsupported\r\n\t\/\/CubeMap::uploadEquirectangular(this, data, width, height);\r\n}\r\n\r\nvoid CubeMapArray::upload(std::vector<void*> data[6], uint32_t width, uint32_t height) {\r\n\tuint32_t size = data[0].size();\r\n\r\n\t\/\/for (int i = 0; i < 6; i++) {\r\n\t\/\/\tassert(data[i].size() == size);\r\n\t\/\/}\r\n\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\tvoid* layerData[6] { data[0][i], data[1][i], data[2][i], data[3][i], data[4][i], data[5][i] };\r\n\t\tthis->upload(layerData, width, height);\r\n\t}\r\n}\r\n\r\nvoid CubeMapArray::upload(void* data[6], uint32_t layer, uint32_t width, uint32_t height) {\r\n\tassert(false); \/\/ unsupported\r\n\t\/\/CubeMap::uploadCubeFaces(this, data, width, height);\r\n\r\n\t\/\/ texSubImage3D into the layer-face\r\n}\r\n\r\nvoid CubeMapArray::bind(uint32_t textureUnit) {\r\n\tOpenGLTextureTarget target = Texture::getOpenGLTextureTarget(m_target);\r\n\tglActiveTexture(GL_TEXTURE0 + textureUnit);\r\n\tglBindTexture(target.target, m_textureName);\r\n}\r\n\r\nvoid CubeMapArray::unbind() {\r\n\tOpenGLTextureTarget target = Texture::getOpenGLTextureTarget(m_target);\r\n\tglBindTexture(target.target, 0);\r\n}\r\n\r\nuint64_t CubeMapArray::getMemorySize() const {\r\n\treturn Texture::getPixelSize(m_format) * m_width * m_height * m_layers * 6;\r\n}\r\n\r\nvoid CubeMapArray::setSize(uint32_t width, uint32_t height, uint32_t layers, uint32_t externalFormat) {\r\n\tif (width != m_width || height != m_height || layers != m_layers || externalFormat != GL_NONE) {\r\n\t\tm_width = width;\r\n\t\tm_height = height;\r\n\t\tm_layers = layers;\r\n\t\tOpenGLTextureFormat format = Texture::getOpenGLTextureFormat(m_format, externalFormat);\r\n\r\n\t\tthis->bind();\r\n\t\tOpenGLTextureTarget target = Texture::getOpenGLTextureTarget(m_target);\r\n\t\tglTexImage3D(target.target, 0, format.internalFormat, width, height, layers * 6, 0, format.externalFormat, format.type, NULL);\r\n\t\tthis->unbind();\r\n\t}\r\n}\r\n\r\nbool CubeMapArray::setWrapMode(TextureWrap u, TextureWrap v, TextureWrap w) {\r\n\tif (u != m_uWrap || v != m_vWrap || w != m_wWrap) {\r\n\t\tOpenGLTextureTarget target = Texture::getOpenGLTextureTarget(m_target);\r\n\t\tOpenGLTextureWrap wrap = Texture::getOpenGLTextureWrap(u, v, w);\r\n\t\tif (wrap.u == GL_NONE || wrap.v == GL_NONE || wrap.w == GL_NONE) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tm_uWrap = u;\r\n\t\tm_vWrap = v;\r\n\t\tm_wWrap = w;\r\n\r\n\t\tthis->bind();\r\n\t\tglTexParameteri(target.target, GL_TEXTURE_WRAP_S, wrap.u);\r\n\t\tglTexParameteri(target.target, GL_TEXTURE_WRAP_T, wrap.v);\r\n\t\tglTexParameteri(target.target, GL_TEXTURE_WRAP_R, wrap.w);\r\n\t\tthis->unbind();\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\nTextureWrap CubeMapArray::getUWrapFilterMode() const {\r\n\treturn m_uWrap;\r\n}\r\n\r\nTextureWrap CubeMapArray::getVWrapFilterMode() const {\r\n\treturn m_vWrap;\r\n}\r\n\r\nTextureWrap CubeMapArray::getWWrapFilterMode() const {\r\n\treturn m_wWrap;\r\n}\r\n\r\nuint32_t CubeMapArray::getWidth() const {\r\n\treturn m_width;\r\n}\r\n\r\nuint32_t CubeMapArray::getHeight() const {\r\n\treturn m_height;\r\n}\r\n\r\nuint32_t CubeMapArray::getLayers() const {\r\n\treturn m_layers;\r\n}\r\n","avg_line_length":33.8616504854,"max_line_length":207,"alphanum_fraction":0.7158626622,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":18913,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":15.0,"content":"#include <oac\/chain\/apply_context.hpp>\n#include <oac\/chain\/transaction_context.hpp>\n#include <oac\/chain\/authorization_manager.hpp>\n#include <oac\/chain\/exceptions.hpp>\n#include <oac\/chain\/resource_limits.hpp>\n#include <oac\/chain\/generated_transaction_object.hpp>\n#include <oac\/chain\/transaction_object.hpp>\n#include <oac\/chain\/global_property_object.hpp>\n\nnamespace oac { namespace chain {\n\n   transaction_context::transaction_context( controller& c,\n                                             const signed_transaction& t,\n                                             const transaction_id_type& trx_id,\n                                             fc::time_point s )\n   :control(c)\n   ,trx(t)\n   ,id(trx_id)\n   ,undo_session(c.db().start_undo_session(true))\n   ,trace(std::make_shared<transaction_trace>())\n   ,start(s)\n   ,net_usage(trace->net_usage)\n   ,pseudo_start(s)\n   {\n      trace->id = id;\n      executed.reserve( trx.total_actions() );\n      FC_ASSERT( trx.transaction_extensions.size() == 0, \"we don't support any extensions yet\" );\n   }\n\n   void transaction_context::init(uint64_t initial_net_usage )\n   {\n      FC_ASSERT( !is_initialized, \"cannot initialize twice\" );\n      const static int64_t large_number_no_overflow = std::numeric_limits<int64_t>::max()\/2;\n\n      const auto& cfg = control.get_global_properties().configuration;\n      auto& rl = control.get_mutable_resource_limits_manager();\n\n      net_limit = rl.get_block_net_limit();\n\n      objective_duration_limit = fc::microseconds( rl.get_block_cpu_limit() );\n      _deadline = start + objective_duration_limit;\n\n      \/\/ Possibly lower net_limit to the maximum net usage a transaction is allowed to be billed\n      if( cfg.max_transaction_net_usage <= net_limit ) {\n         net_limit = cfg.max_transaction_net_usage;\n         net_limit_due_to_block = false;\n      }\n\n      \/\/ Possibly lower objective_duration_limit to the maximum cpu usage a transaction is allowed to be billed\n      if( cfg.max_transaction_cpu_usage <= objective_duration_limit.count() ) {\n         objective_duration_limit = fc::microseconds(cfg.max_transaction_cpu_usage);\n         billing_timer_exception_code = tx_cpu_usage_exceeded::code_value;\n         _deadline = start + objective_duration_limit;\n      }\n\n      \/\/ Possibly lower net_limit to optional limit set in the transaction header\n      uint64_t trx_specified_net_usage_limit = static_cast<uint64_t>(trx.max_net_usage_words.value) * 8;\n      if( trx_specified_net_usage_limit > 0 && trx_specified_net_usage_limit <= net_limit ) {\n         net_limit = trx_specified_net_usage_limit;\n         net_limit_due_to_block = false;\n      }\n\n      \/\/ Possibly lower objective_duration_limit to optional limit set in transaction header\n      if( trx.max_cpu_usage_ms > 0 ) {\n         auto trx_specified_cpu_usage_limit = fc::milliseconds(trx.max_cpu_usage_ms);\n         if( trx_specified_cpu_usage_limit <= objective_duration_limit ) {\n            objective_duration_limit = trx_specified_cpu_usage_limit;\n            billing_timer_exception_code = tx_cpu_usage_exceeded::code_value;\n            _deadline = start + objective_duration_limit;\n         }\n      }\n\n      if( billed_cpu_time_us > 0 )\n         validate_cpu_usage_to_bill( billed_cpu_time_us, false ); \/\/ Fail early if the amount to be billed is too high\n\n      \/\/ Record accounts to be billed for network and CPU usage\n      for( const auto& act : trx.actions ) {\n         for( const auto& auth : act.authorization ) {\n            bill_to_accounts.insert( auth.actor );\n         }\n      }\n      validate_ram_usage.reserve( bill_to_accounts.size() );\n\n      \/\/ Update usage values of accounts to reflect new time\n      rl.update_account_usage( bill_to_accounts, block_timestamp_type(control.pending_block_time()).slot );\n\n      \/\/ Calculate the highest network usage and CPU time that all of the billed accounts can afford to be billed\n      int64_t account_net_limit = large_number_no_overflow;\n      int64_t account_cpu_limit = large_number_no_overflow;\n      for( const auto& a : bill_to_accounts ) {\n         auto net_limit = rl.get_account_net_limit(a);\n         if( net_limit >= 0 )\n            account_net_limit = std::min( account_net_limit, net_limit );\n         auto cpu_limit = rl.get_account_cpu_limit(a);\n         if( cpu_limit >= 0 )\n            account_cpu_limit = std::min( account_cpu_limit, cpu_limit );\n      }\n\n      eager_net_limit = net_limit;\n\n      \/\/ Possible lower eager_net_limit to what the billed accounts can pay plus some (objective) leeway\n      auto new_eager_net_limit = std::min( eager_net_limit, static_cast<uint64_t>(account_net_limit + cfg.net_usage_leeway) );\n      if( new_eager_net_limit < eager_net_limit ) {\n         eager_net_limit = new_eager_net_limit;\n         net_limit_due_to_block = false;\n      }\n\n      \/\/ Possibly limit deadline if the duration accounts can be billed for (+ a subjective leeway) does not exceed current delta\n      if( (fc::microseconds(account_cpu_limit) + leeway) <= (_deadline - start) ) {\n         _deadline = start + fc::microseconds(account_cpu_limit) + leeway;\n         billing_timer_exception_code = leeway_deadline_exception::code_value;\n      }\n\n      billing_timer_duration_limit = _deadline - start;\n\n      \/\/ Check if deadline is limited by caller-set deadline (only change deadline if billed_cpu_time_us is not set)\n      if( billed_cpu_time_us > 0 || deadline < _deadline ) {\n         _deadline = deadline;\n         deadline_exception_code = deadline_exception::code_value;\n      } else {\n         deadline_exception_code = billing_timer_exception_code;\n      }\n\n      eager_net_limit = (eager_net_limit\/8)*8; \/\/ Round down to nearest multiple of word size (8 bytes) so check_net_usage can be efficient\n\n      if( initial_net_usage > 0 )\n         add_net_usage( initial_net_usage );  \/\/ Fail early if current net usage is already greater than the calculated limit\n\n      checktime(); \/\/ Fail early if deadline has already been exceeded\n\n      is_initialized = true;\n   }\n\n   void transaction_context::init_for_implicit_trx( uint64_t initial_net_usage  )\n   {\n      published = control.pending_block_time();\n      init( initial_net_usage );\n   }\n\n   void transaction_context::init_for_input_trx( uint64_t packed_trx_unprunable_size,\n                                                 uint64_t packed_trx_prunable_size,\n                                                 uint32_t num_signatures              )\n   {\n      const auto& cfg = control.get_global_properties().configuration;\n\n      uint64_t discounted_size_for_pruned_data = packed_trx_prunable_size;\n      if( cfg.context_free_discount_net_usage_den > 0\n          && cfg.context_free_discount_net_usage_num < cfg.context_free_discount_net_usage_den )\n      {\n         discounted_size_for_pruned_data *= cfg.context_free_discount_net_usage_num;\n         discounted_size_for_pruned_data =  ( discounted_size_for_pruned_data + cfg.context_free_discount_net_usage_den - 1)\n                                                                                    \/ cfg.context_free_discount_net_usage_den; \/\/ rounds up\n      }\n\n      uint64_t initial_net_usage = static_cast<uint64_t>(cfg.base_per_transaction_net_usage)\n                                    + packed_trx_unprunable_size + discounted_size_for_pruned_data;\n\n\n      if( trx.delay_sec.value > 0 ) {\n          \/\/ If delayed, also charge ahead of time for the additional net usage needed to retire the delayed transaction\n          \/\/ whether that be by successfully executing, soft failure, hard failure, or expiration.\n         initial_net_usage += static_cast<uint64_t>(cfg.base_per_transaction_net_usage)\n                               + static_cast<uint64_t>(config::transaction_id_net_usage);\n      }\n\n      published = control.pending_block_time();\n      is_input = true;\n      control.validate_expiration( trx );\n      control.validate_tapos( trx );\n      control.validate_referenced_accounts( trx );\n      init( initial_net_usage );\n      record_transaction( id, trx.expiration ); \/\/\/ checks for dupes\n   }\n\n   void transaction_context::init_for_deferred_trx( fc::time_point p )\n   {\n      published = p;\n      trace->scheduled = true;\n      apply_context_free = false;\n      init( 0 );\n   }\n\n   void transaction_context::exec() {\n      FC_ASSERT( is_initialized, \"must first initialize\" );\n\n      if( apply_context_free ) {\n         for( const auto& act : trx.context_free_actions ) {\n            trace->action_traces.emplace_back();\n            dispatch_action( trace->action_traces.back(), act, true );\n         }\n      }\n\n      if( delay == fc::microseconds() ) {\n         for( const auto& act : trx.actions ) {\n            trace->action_traces.emplace_back();\n            dispatch_action( trace->action_traces.back(), act );\n         }\n      } else {\n         schedule_transaction();\n      }\n   }\n\n   void transaction_context::finalize() {\n      FC_ASSERT( is_initialized, \"must first initialize\" );\n      const static int64_t large_number_no_overflow = std::numeric_limits<int64_t>::max()\/2;\n\n      if( is_input ) {\n         auto& am = control.get_mutable_authorization_manager();\n         for( const auto& act : trx.actions ) {\n            for( const auto& auth : act.authorization ) {\n               am.update_permission_usage( am.get_permission(auth) );\n            }\n         }\n      }\n\n      auto& rl = control.get_mutable_resource_limits_manager();\n      for( auto a : validate_ram_usage ) {\n         rl.verify_account_ram_usage( a );\n      }\n\n      \/\/ Calculate the new highest network usage and CPU time that all of the billed accounts can afford to be billed\n      int64_t account_net_limit = large_number_no_overflow;\n      int64_t account_cpu_limit = large_number_no_overflow;\n      for( const auto& a : bill_to_accounts ) {\n         auto net_limit = rl.get_account_net_limit(a);\n         if( net_limit >= 0 )\n            account_net_limit = std::min( account_net_limit, net_limit );\n         auto cpu_limit = rl.get_account_cpu_limit(a);\n         if( cpu_limit >= 0 )\n            account_cpu_limit = std::min( account_cpu_limit, cpu_limit );\n      }\n\n      \/\/ Possibly lower net_limit to what the billed accounts can pay\n      if( static_cast<uint64_t>(account_net_limit) <= net_limit ) {\n         net_limit = static_cast<uint64_t>(account_net_limit);\n         net_limit_due_to_block = false;\n      }\n\n      \/\/ Possibly lower objective_duration_limit to what the billed accounts can pay\n      if( account_cpu_limit <= objective_duration_limit.count() ) {\n         objective_duration_limit = fc::microseconds(account_cpu_limit);\n         billing_timer_exception_code = tx_cpu_usage_exceeded::code_value;\n      }\n\n      net_usage = ((net_usage + 7)\/8)*8; \/\/ Round up to nearest multiple of word size (8 bytes)\n\n      eager_net_limit = net_limit;\n      check_net_usage();\n\n      auto now = fc::time_point::now();\n      trace->elapsed = now - start;\n\n      if( billed_cpu_time_us == 0 ) {\n         const auto& cfg = control.get_global_properties().configuration;\n         billed_cpu_time_us = std::max( (now - pseudo_start).count(), static_cast<int64_t>(cfg.min_transaction_cpu_usage) );\n      }\n\n      validate_cpu_usage_to_bill( billed_cpu_time_us );\n\n      rl.add_transaction_usage( bill_to_accounts, static_cast<uint64_t>(billed_cpu_time_us), net_usage,\n                                block_timestamp_type(control.pending_block_time()).slot ); \/\/ Should never fail\n   }\n\n   void transaction_context::squash() {\n      undo_session.squash();\n   }\n\n\n   void transaction_context::check_net_usage()const {\n      if( BOOST_UNLIKELY(net_usage > eager_net_limit) ) {\n         if( net_limit_due_to_block ) {\n            OAC_THROW( block_net_usage_exceeded,\n                       \"not enough space left in block: ${net_usage} > ${net_limit}\",\n                       (\"net_usage\", net_usage)(\"net_limit\", eager_net_limit) );\n         } else {\n            OAC_THROW( tx_net_usage_exceeded,\n                       \"net usage of transaction is too high: ${net_usage} > ${net_limit}\",\n                       (\"net_usage\", net_usage)(\"net_limit\", eager_net_limit) );\n         }\n      }\n   }\n\n   void transaction_context::checktime()const {\n      auto now = fc::time_point::now();\n      if( BOOST_UNLIKELY( now > _deadline ) ) {\n         \/\/ edump((now-start)(now-pseudo_start));\n         if( billed_cpu_time_us > 0 || deadline_exception_code == deadline_exception::code_value ) {\n            OAC_THROW( deadline_exception, \"deadline exceeded\", (\"now\", now)(\"deadline\", _deadline)(\"start\", start) );\n         } else if( deadline_exception_code == block_cpu_usage_exceeded::code_value ) {\n            OAC_THROW( block_cpu_usage_exceeded,\n                       \"not enough time left in block to complete executing transaction\",\n                       (\"now\", now)(\"deadline\", _deadline)(\"start\", start)(\"billing_timer\", now - pseudo_start) );\n         } else if( deadline_exception_code == tx_cpu_usage_exceeded::code_value ) {\n            OAC_THROW( tx_cpu_usage_exceeded,\n                       \"transaction was executing for too long\",\n                       (\"now\", now)(\"deadline\", _deadline)(\"start\", start)(\"billing_timer\", now - pseudo_start) );\n         } else if( deadline_exception_code == leeway_deadline_exception::code_value ) {\n            OAC_THROW( leeway_deadline_exception,\n                       \"the transaction was unable to complete by deadline, \"\n                       \"but it is possible it could have succeeded if it were allowed to run to completion\",\n                       (\"now\", now)(\"deadline\", _deadline)(\"start\", start)(\"billing_timer\", now - pseudo_start) );\n         }\n         FC_ASSERT( false, \"unexpected deadline exception code\" );\n      }\n   }\n\n   void transaction_context::pause_billing_timer() {\n      if( billed_cpu_time_us > 0 || pseudo_start == fc::time_point() ) return; \/\/ either irrelevant or already paused\n\n      auto now = fc::time_point::now();\n      billed_time = now - pseudo_start;\n      deadline_exception_code = deadline_exception::code_value; \/\/ Other timeout exceptions cannot be thrown while billable timer is paused.\n      pseudo_start = fc::time_point();\n   }\n\n   void transaction_context::resume_billing_timer() {\n      if( billed_cpu_time_us > 0 || pseudo_start != fc::time_point() ) return; \/\/ either irrelevant or already running\n\n      auto now = fc::time_point::now();\n      pseudo_start = now - billed_time;\n      if( (pseudo_start + billing_timer_duration_limit) <= deadline ) {\n         _deadline = pseudo_start + billing_timer_duration_limit;\n         deadline_exception_code = billing_timer_exception_code;\n      } else {\n         _deadline = deadline;\n         deadline_exception_code = deadline_exception::code_value;\n      }\n   }\n\n   void transaction_context::validate_cpu_usage_to_bill( int64_t billed_us, bool check_minimum )const {\n      if( check_minimum ) {\n         const auto& cfg = control.get_global_properties().configuration;\n         OAC_ASSERT( billed_us >= cfg.min_transaction_cpu_usage, transaction_exception,\n                     \"cannot bill CPU time less than the minimum of ${min_billable} us\",\n                     (\"min_billable\", cfg.min_transaction_cpu_usage)(\"billed_cpu_time_us\", billed_us)\n                   );\n      }\n\n      if( billing_timer_exception_code == block_cpu_usage_exceeded::code_value ) {\n         OAC_ASSERT( billed_us <= objective_duration_limit.count(),\n                     block_cpu_usage_exceeded,\n                     \"billed CPU time (${billed} us) is greater than the billable CPU time left in the block (${billable} us)\",\n                     (\"billed\", billed_us)(\"billable\", objective_duration_limit.count())\n                   );\n      } else {\n         OAC_ASSERT( billed_us <= objective_duration_limit.count(),\n                     tx_cpu_usage_exceeded,\n                     \"billed CPU time (${billed} us) is greater than the maximum billable CPU time for the transaction (${billable} us)\",\n                     (\"billed\", billed_us)(\"billable\", objective_duration_limit.count())\n                   );\n      }\n   }\n\n   void transaction_context::add_ram_usage( account_name account, int64_t ram_delta ) {\n      auto& rl = control.get_mutable_resource_limits_manager();\n      rl.add_pending_ram_usage( account, ram_delta );\n      if( ram_delta > 0 ) {\n         validate_ram_usage.insert( account );\n      }\n   }\n\n   void transaction_context::dispatch_action( action_trace& trace, const action& a, account_name receiver, bool context_free, uint32_t recurse_depth ) {\n      apply_context  acontext( control, *this, a, recurse_depth );\n      acontext.context_free = context_free;\n      acontext.receiver     = receiver;\n\n      try {\n         acontext.exec();\n      } catch( ... ) {\n         trace = move(acontext.trace);\n         throw;\n      }\n\n      trace = move(acontext.trace);\n   }\n\n   void transaction_context::schedule_transaction() {\n      \/\/ Charge ahead of time for the additional net usage needed to retire the delayed transaction\n      \/\/ whether that be by successfully executing, soft failure, hard failure, or expiration.\n      if( trx.delay_sec.value == 0 ) { \/\/ Do not double bill. Only charge if we have not already charged for the delay.\n         const auto& cfg = control.get_global_properties().configuration;\n         add_net_usage( static_cast<uint64_t>(cfg.base_per_transaction_net_usage)\n                         + static_cast<uint64_t>(config::transaction_id_net_usage) ); \/\/ Will exit early if net usage cannot be payed.\n      }\n\n      auto first_auth = trx.first_authorizor();\n\n      uint32_t trx_size = 0;\n      const auto& cgto = control.db().create<generated_transaction_object>( [&]( auto& gto ) {\n        gto.trx_id      = id;\n        gto.payer       = first_auth;\n        gto.sender      = account_name(); \/\/\/ delayed transactions have no sender\n        gto.sender_id   = transaction_id_to_sender_id( gto.trx_id );\n        gto.published   = control.pending_block_time();\n        gto.delay_until = gto.published + delay;\n        gto.expiration  = gto.delay_until + fc::seconds(control.get_global_properties().configuration.deferred_trx_expiration_window);\n        trx_size = gto.set( trx );\n      });\n\n      add_ram_usage( cgto.payer, (config::billable_size_v<generated_transaction_object> + trx_size) );\n   }\n\n   void transaction_context::record_transaction( const transaction_id_type& id, fc::time_point_sec expire ) {\n      try {\n          control.db().create<transaction_object>([&](transaction_object& transaction) {\n              transaction.trx_id = id;\n              transaction.expiration = expire;\n          });\n      } catch( const boost::interprocess::bad_alloc& ) {\n         throw;\n      } catch ( ... ) {\n          OAC_ASSERT( false, tx_duplicate,\n                     \"duplicate transaction ${id}\", (\"id\", id ) );\n      }\n   } \/\/\/ record_transaction\n\n\n} } \/\/\/ oac::chain\n","avg_line_length":45.138424821,"max_line_length":152,"alphanum_fraction":0.6539417332,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8489,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this file,\n * You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#ifdef MOZILLA_INTERNAL_API\n\n#  include \"mozilla\/Assertions.h\"\n#  include \"mozilla\/UniquePtr.h\"\n\n#  include \"ICUUtils.h\"\n#  include \"mozilla\/StaticPrefs_dom.h\"\n#  include \"mozilla\/intl\/LocaleService.h\"\n#  include \"nsIContent.h\"\n#  include \"mozilla\/dom\/Document.h\"\n#  include \"nsString.h\"\n#  include \"unicode\/uloc.h\"\n#  include \"unicode\/unum.h\"\n\nusing namespace mozilla;\nusing mozilla::intl::LocaleService;\n\nclass NumberFormatDeleter {\n public:\n  void operator()(UNumberFormat* aPtr) {\n    MOZ_ASSERT(aPtr != nullptr,\n               \"UniquePtr deleter shouldn't be called for nullptr\");\n    unum_close(aPtr);\n  }\n};\n\nusing UniqueUNumberFormat = UniquePtr<UNumberFormat, NumberFormatDeleter>;\n\nvoid ICUUtils::LanguageTagIterForContent::GetNext(nsACString& aBCP47LangTag) {\n  if (mCurrentFallbackIndex < 0) {\n    mCurrentFallbackIndex = 0;\n    \/\/ Try the language specified by a 'lang'\/'xml:lang' attribute on mContent\n    \/\/ or any ancestor, if such an attribute is specified:\n    nsAutoString lang;\n    mContent->GetLang(lang);\n    if (!lang.IsEmpty()) {\n      CopyUTF16toUTF8(lang, aBCP47LangTag);\n      return;\n    }\n  }\n\n  if (mCurrentFallbackIndex < 1) {\n    mCurrentFallbackIndex = 1;\n    \/\/ Else try the language specified by any Content-Language HTTP header or\n    \/\/ pragma directive:\n    nsAutoString lang;\n    mContent->OwnerDoc()->GetContentLanguage(lang);\n    if (!lang.IsEmpty()) {\n      CopyUTF16toUTF8(lang, aBCP47LangTag);\n      return;\n    }\n  }\n\n  if (mCurrentFallbackIndex < 2) {\n    mCurrentFallbackIndex = 2;\n    \/\/ Else take the app's locale:\n\n    nsAutoCString appLocale;\n    LocaleService::GetInstance()->GetAppLocaleAsBCP47(aBCP47LangTag);\n    return;\n  }\n\n  \/\/ TODO: Probably not worth it, but maybe have a fourth fallback to using\n  \/\/ the OS locale?\n\n  aBCP47LangTag.Truncate();  \/\/ Signal iterator exhausted\n}\n\n\/* static *\/\nbool ICUUtils::LocalizeNumber(double aValue,\n                              LanguageTagIterForContent& aLangTags,\n                              nsAString& aLocalizedValue) {\n  MOZ_ASSERT(aLangTags.IsAtStart(), \"Don't call Next() before passing\");\n\n  static const int32_t kBufferSize = 256;\n\n  UChar buffer[kBufferSize];\n\n  nsAutoCString langTag;\n  aLangTags.GetNext(langTag);\n  while (!langTag.IsEmpty()) {\n    UErrorCode status = U_ZERO_ERROR;\n    UniqueUNumberFormat format(\n        unum_open(UNUM_DECIMAL, nullptr, 0, langTag.get(), nullptr, &status));\n    \/\/ Since unum_setAttribute have no UErrorCode parameter, we have to\n    \/\/ check error status.\n    if (U_FAILURE(status)) {\n      aLangTags.GetNext(langTag);\n      continue;\n    }\n    unum_setAttribute(format.get(), UNUM_GROUPING_USED,\n                      StaticPrefs::dom_forms_number_grouping());\n    \/\/ ICU default is a maximum of 3 significant fractional digits. We don't\n    \/\/ want that limit, so we set it to the maximum that a double can represent\n    \/\/ (14-16 decimal fractional digits).\n    unum_setAttribute(format.get(), UNUM_MAX_FRACTION_DIGITS, 16);\n    int32_t length = unum_formatDouble(format.get(), aValue, buffer,\n                                       kBufferSize, nullptr, &status);\n    NS_ASSERTION(length < kBufferSize && status != U_BUFFER_OVERFLOW_ERROR &&\n                     status != U_STRING_NOT_TERMINATED_WARNING,\n                 \"Need a bigger buffer?!\");\n    if (U_SUCCESS(status)) {\n      ICUUtils::AssignUCharArrayToString(buffer, length, aLocalizedValue);\n      return true;\n    }\n    aLangTags.GetNext(langTag);\n  }\n  return false;\n}\n\n\/* static *\/\ndouble ICUUtils::ParseNumber(nsAString& aValue,\n                             LanguageTagIterForContent& aLangTags) {\n  MOZ_ASSERT(aLangTags.IsAtStart(), \"Don't call Next() before passing\");\n\n  if (aValue.IsEmpty()) {\n    return std::numeric_limits<float>::quiet_NaN();\n  }\n\n  uint32_t length = aValue.Length();\n\n  nsAutoCString langTag;\n  aLangTags.GetNext(langTag);\n  while (!langTag.IsEmpty()) {\n    UErrorCode status = U_ZERO_ERROR;\n    UniqueUNumberFormat format(\n        unum_open(UNUM_DECIMAL, nullptr, 0, langTag.get(), nullptr, &status));\n    if (!StaticPrefs::dom_forms_number_grouping()) {\n      unum_setAttribute(format.get(), UNUM_GROUPING_USED, UBool(0));\n    }\n    int32_t parsePos = 0;\n    static_assert(sizeof(UChar) == 2 && sizeof(nsAString::char_type) == 2,\n                  \"Unexpected character size - the following cast is unsafe\");\n    double val = unum_parseDouble(format.get(),\n                                  (const UChar*)PromiseFlatString(aValue).get(),\n                                  length, &parsePos, &status);\n    if (U_SUCCESS(status) && parsePos == (int32_t)length) {\n      return val;\n    }\n    aLangTags.GetNext(langTag);\n  }\n  return std::numeric_limits<float>::quiet_NaN();\n}\n\n\/* static *\/\nvoid ICUUtils::AssignUCharArrayToString(UChar* aICUString, int32_t aLength,\n                                        nsAString& aMozString) {\n  \/\/ Both ICU's UnicodeString and Mozilla's nsAString use UTF-16, so we can\n  \/\/ cast here.\n\n  static_assert(sizeof(UChar) == 2 && sizeof(nsAString::char_type) == 2,\n                \"Unexpected character size - the following cast is unsafe\");\n\n  aMozString.Assign((const nsAString::char_type*)aICUString, aLength);\n\n  NS_ASSERTION((int32_t)aMozString.Length() == aLength, \"Conversion failed\");\n}\n\n\/* static *\/\nnsresult ICUUtils::UErrorToNsResult(const UErrorCode aErrorCode) {\n  if (U_SUCCESS(aErrorCode)) {\n    return NS_OK;\n  }\n\n  switch (aErrorCode) {\n    case U_ILLEGAL_ARGUMENT_ERROR:\n      return NS_ERROR_INVALID_ARG;\n\n    case U_MEMORY_ALLOCATION_ERROR:\n      return NS_ERROR_OUT_OF_MEMORY;\n\n    default:\n      return NS_ERROR_FAILURE;\n  }\n}\n\n#  if 0\n\/* static *\/\nLocale\nICUUtils::BCP47CodeToLocale(const nsAString& aBCP47Code)\n{\n  MOZ_ASSERT(!aBCP47Code.IsEmpty(), \"Don't pass an empty BCP 47 code\");\n\n  Locale locale;\n  locale.setToBogus();\n\n  \/\/ BCP47 codes are guaranteed to be ASCII, so lossy conversion is okay\n  NS_LossyConvertUTF16toASCII bcp47code(aBCP47Code);\n\n  UErrorCode status = U_ZERO_ERROR;\n  int32_t needed;\n\n  char localeID[256];\n  needed = uloc_forLanguageTag(bcp47code.get(), localeID,\n                               PR_ARRAY_SIZE(localeID) - 1, nullptr,\n                               &status);\n  MOZ_ASSERT(needed < int32_t(PR_ARRAY_SIZE(localeID)) - 1,\n             \"Need a bigger buffer\");\n  if (needed <= 0 || U_FAILURE(status)) {\n    return locale;\n  }\n\n  char lang[64];\n  needed = uloc_getLanguage(localeID, lang, PR_ARRAY_SIZE(lang) - 1,\n                            &status);\n  MOZ_ASSERT(needed < int32_t(PR_ARRAY_SIZE(lang)) - 1,\n             \"Need a bigger buffer\");\n  if (needed <= 0 || U_FAILURE(status)) {\n    return locale;\n  }\n\n  char country[64];\n  needed = uloc_getCountry(localeID, country, PR_ARRAY_SIZE(country) - 1,\n                           &status);\n  MOZ_ASSERT(needed < int32_t(PR_ARRAY_SIZE(country)) - 1,\n             \"Need a bigger buffer\");\n  if (needed > 0 && U_SUCCESS(status)) {\n    locale = Locale(lang, country);\n  }\n\n  if (locale.isBogus()) {\n    \/\/ Using the country resulted in a bogus Locale, so try with only the lang\n    locale = Locale(lang);\n  }\n\n  return locale;\n}\n\n\/* static *\/\nvoid\nICUUtils::ToMozString(UnicodeString& aICUString, nsAString& aMozString)\n{\n  \/\/ Both ICU's UnicodeString and Mozilla's nsAString use UTF-16, so we can\n  \/\/ cast here.\n\n  static_assert(sizeof(UChar) == 2 && sizeof(nsAString::char_type) == 2,\n                \"Unexpected character size - the following cast is unsafe\");\n\n  const nsAString::char_type* buf =\n    (const nsAString::char_type*)aICUString.getTerminatedBuffer();\n  aMozString.Assign(buf);\n\n  NS_ASSERTION(aMozString.Length() == (uint32_t)aICUString.length(),\n               \"Conversion failed\");\n}\n\n\/* static *\/\nvoid\nICUUtils::ToICUString(nsAString& aMozString, UnicodeString& aICUString)\n{\n  \/\/ Both ICU's UnicodeString and Mozilla's nsAString use UTF-16, so we can\n  \/\/ cast here.\n\n  static_assert(sizeof(UChar) == 2 && sizeof(nsAString::char_type) == 2,\n                \"Unexpected character size - the following cast is unsafe\");\n\n  aICUString.setTo((UChar*)PromiseFlatString(aMozString).get(),\n                   aMozString.Length());\n\n  NS_ASSERTION(aMozString.Length() == (uint32_t)aICUString.length(),\n               \"Conversion failed\");\n}\n#  endif\n\n#endif \/* MOZILLA_INTERNAL_API *\/\n","avg_line_length":31.4407407407,"max_line_length":80,"alphanum_fraction":0.6610908234,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2611,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2017-2019 The Bitkincoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <consensus\/tx_check.h>\n\n#include <primitives\/transaction.h>\n#include <consensus\/validation.h>\n\nbool CheckTransaction(const CTransaction& tx, TxValidationState& state)\n{\n    \/\/ Basic checks that don't depend on any context\n    if (tx.vin.empty())\n        return state.Invalid(TxValidationResult::TX_CONSENSUS, \"bad-txns-vin-empty\");\n    if (tx.vout.empty())\n        return state.Invalid(TxValidationResult::TX_CONSENSUS, \"bad-txns-vout-empty\");\n    \/\/ Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability)\n    if (::GetSerializeSize(tx, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)\n        return state.Invalid(TxValidationResult::TX_CONSENSUS, \"bad-txns-oversize\");\n\n    \/\/ Check for negative or overflow output values (see CVE-2010-5139)\n    CAmount nValueOut = 0;\n    for (const auto& txout : tx.vout)\n    {\n        if (txout.nValue < 0)\n            return state.Invalid(TxValidationResult::TX_CONSENSUS, \"bad-txns-vout-negative\");\n        if (txout.nValue > MAX_MONEY)\n            return state.Invalid(TxValidationResult::TX_CONSENSUS, \"bad-txns-vout-toolarge\");\n        nValueOut += txout.nValue;\n        if (!MoneyRange(nValueOut))\n            return state.Invalid(TxValidationResult::TX_CONSENSUS, \"bad-txns-txouttotal-toolarge\");\n    }\n\n    \/\/ Check for duplicate inputs (see CVE-2018-17144)\n    \/\/ While Consensus::CheckTxInputs does check if all inputs of a tx are available, and UpdateCoins marks all inputs\n    \/\/ of a tx as spent, it does not check if the tx has duplicate inputs.\n    \/\/ Failure to run this check will result in either a crash or an inflation bug, depending on the implementation of\n    \/\/ the underlying coins database.\n    std::set<COutPoint> vInOutPoints;\n    for (const auto& txin : tx.vin) {\n        if (!vInOutPoints.insert(txin.prevout).second)\n            return state.Invalid(TxValidationResult::TX_CONSENSUS, \"bad-txns-inputs-duplicate\");\n    }\n\n    if (tx.IsCoinBase())\n    {\n        if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)\n            return state.Invalid(TxValidationResult::TX_CONSENSUS, \"bad-cb-length\");\n    }\n    else\n    {\n        for (const auto& txin : tx.vin)\n            if (txin.prevout.IsNull())\n                return state.Invalid(TxValidationResult::TX_CONSENSUS, \"bad-txns-prevout-null\");\n    }\n\n    return true;\n}\n","avg_line_length":44.2542372881,"max_line_length":126,"alphanum_fraction":0.6893910379,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":33644,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["ECL-2.0","Apache-2.0"],"max_stars_count":1.0,"content":"\/*\n  Q Light Controller Plus\n  rgbmatrix.cpp\n\n  Copyright (c) Heikki Junnila\n                Massimo Callegari\n\n  Licensed under the Apache License, Version 2.0 (the \"License\");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n      http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*\/\n\n#include <QXmlStreamReader>\n#include <QXmlStreamWriter>\n#include <QCoreApplication>\n#include <QElapsedTimer>\n#include <QDebug>\n#include <cmath>\n#include <QDir>\n\n#include \"qlcfixturehead.h\"\n#include \"fixturegroup.h\"\n#include \"genericfader.h\"\n#include \"fadechannel.h\"\n#include \"rgbmatrix.h\"\n#include \"qlcmacros.h\"\n#include \"rgbaudio.h\"\n#include \"rgbscriptscache.h\"\n#include \"doc.h\"\n\n#define KXMLQLCRGBMatrixStartColor \"MonoColor\"\n#define KXMLQLCRGBMatrixEndColor \"EndColor\"\n#define KXMLQLCRGBMatrixFixtureGroup \"FixtureGroup\"\n#define KXMLQLCRGBMatrixDimmerControl \"DimmerControl\"\n\n#define KXMLQLCRGBMatrixProperty \"Property\"\n#define KXMLQLCRGBMatrixPropertyName \"Name\"\n#define KXMLQLCRGBMatrixPropertyValue \"Value\"\n\n#define KXMLQLCRGBMatrixControlMode \"ControlMode\"\n#define KXMLQLCRGBMatrixControlModeRgb \"RGB\"\n#define KXMLQLCRGBMatrixControlModeAmber \"Amber\"\n#define KXMLQLCRGBMatrixControlModeWhite \"White\"\n#define KXMLQLCRGBMatrixControlModeUV \"UV\"\n#define KXMLQLCRGBMatrixControlModeDimmer \"Dimmer\"\n#define KXMLQLCRGBMatrixControlModeShutter \"Shutter\"\n\n\/****************************************************************************\n * Initialization\n ****************************************************************************\/\n\nRGBMatrix::RGBMatrix(Doc* doc)\n    : Function(doc, Function::RGBMatrixType)\n    , m_dimmerControl(false)\n    , m_fixtureGroupID(FixtureGroup::invalidId())\n    , m_group(NULL)\n    , m_algorithm(NULL)\n    , m_algorithmMutex(QMutex::Recursive)\n    , m_startColor(Qt::red)\n    , m_endColor(QColor())\n    , m_stepHandler(new RGBMatrixStep())\n    , m_roundTime(new QElapsedTimer())\n    , m_stepsCount(0)\n    , m_stepBeatDuration(0)\n    , m_controlMode(RGBMatrix::ControlModeRgb)\n{\n    setName(tr(\"New RGB Matrix\"));\n    setDuration(500);\n\n    RGBScript scr = doc->rgbScriptsCache()->script(\"Stripes\");\n    setAlgorithm(scr.clone());\n}\n\nRGBMatrix::~RGBMatrix()\n{\n    delete m_algorithm;\n    delete m_roundTime;\n    delete m_stepHandler;\n}\n\nQIcon RGBMatrix::getIcon() const\n{\n    return QIcon(\":\/rgbmatrix.png\");\n}\n\nvoid RGBMatrix::setTotalDuration(quint32 msec)\n{\n    QMutexLocker algorithmLocker(&m_algorithmMutex);\n\n    if (m_algorithm == NULL)\n        return;\n\n    FixtureGroup* grp = doc()->fixtureGroup(fixtureGroup());\n    if (grp == NULL)\n        return;\n\n    int steps = m_algorithm->rgbMapStepCount(grp->size());\n    setDuration(msec \/ steps);\n}\n\nquint32 RGBMatrix::totalDuration()\n{\n    QMutexLocker algorithmLocker(&m_algorithmMutex);\n\n    if (m_algorithm == NULL)\n        return 0;\n\n    FixtureGroup* grp = doc()->fixtureGroup(fixtureGroup());\n    if (grp == NULL)\n        return 0;\n\n    qDebug () << \"Algorithm steps:\" << m_algorithm->rgbMapStepCount(grp->size());\n    return m_algorithm->rgbMapStepCount(grp->size()) * duration();\n}\n\nvoid RGBMatrix::setDimmerControl(bool dimmerControl)\n{\n    m_dimmerControl = dimmerControl;\n}\n\nbool RGBMatrix::dimmerControl() const\n{\n    return m_dimmerControl;\n}\n\n\/****************************************************************************\n * Copying\n ****************************************************************************\/\n\nFunction* RGBMatrix::createCopy(Doc* doc, bool addToDoc)\n{\n    Q_ASSERT(doc != NULL);\n\n    Function* copy = new RGBMatrix(doc);\n    if (copy->copyFrom(this) == false)\n    {\n        delete copy;\n        copy = NULL;\n    }\n    if (addToDoc == true && doc->addFunction(copy) == false)\n    {\n        delete copy;\n        copy = NULL;\n    }\n\n    return copy;\n}\n\nbool RGBMatrix::copyFrom(const Function* function)\n{\n    const RGBMatrix* mtx = qobject_cast<const RGBMatrix*> (function);\n    if (mtx == NULL)\n        return false;\n\n    setDimmerControl(mtx->dimmerControl());\n    setFixtureGroup(mtx->fixtureGroup());\n    if (mtx->algorithm() != NULL)\n        setAlgorithm(mtx->algorithm()->clone());\n    else\n        setAlgorithm(NULL);\n    setStartColor(mtx->startColor());\n    setEndColor(mtx->endColor());\n\n    return Function::copyFrom(function);\n}\n\n\/****************************************************************************\n * Fixtures\n ****************************************************************************\/\n\nquint32 RGBMatrix::fixtureGroup() const\n{\n    return m_fixtureGroupID;\n}\n\nvoid RGBMatrix::setFixtureGroup(quint32 id)\n{\n    m_fixtureGroupID = id;\n    {\n        QMutexLocker algoLocker(&m_algorithmMutex);\n        m_group = doc()->fixtureGroup(m_fixtureGroupID);\n    }\n    m_stepsCount = stepsCount();\n}\n\nQList<quint32> RGBMatrix::components()\n{\n    if (m_group != NULL)\n        return m_group->fixtureList();\n\n    return QList<quint32>();\n}\n\n\/****************************************************************************\n * Algorithm\n ****************************************************************************\/\n\nvoid RGBMatrix::setAlgorithm(RGBAlgorithm* algo)\n{\n    {\n        QMutexLocker algorithmLocker(&m_algorithmMutex);\n        delete m_algorithm;\n        m_algorithm = algo;\n\n        \/** If there's been a change of Script algorithm \"on the fly\",\n         *  then re-apply the properties currently set in this RGBMatrix *\/\n        if (m_algorithm != NULL && m_algorithm->type() == RGBAlgorithm::Script)\n        {\n            RGBScript *script = static_cast<RGBScript*> (m_algorithm);\n            QHashIterator<QString, QString> it(m_properties);\n            while(it.hasNext())\n            {\n                it.next();\n                if (script->setProperty(it.key(), it.value()) == false)\n                {\n                    \/** If the new algorithm doesn't expose a property,\n                     *  then remove it from the cached list, otherwise\n                     *  it would be carried around forever (and saved on XML) *\/\n                    m_properties.take(it.key());\n                }\n            }\n        }\n    }\n    m_stepsCount = stepsCount();\n\n    emit changed(id());\n}\n\nRGBAlgorithm* RGBMatrix::algorithm() const\n{\n    return m_algorithm;\n}\n\nQMutex& RGBMatrix::algorithmMutex()\n{\n    return m_algorithmMutex;\n}\n\nint RGBMatrix::stepsCount()\n{\n    QMutexLocker algorithmLocker(&m_algorithmMutex);\n\n    if (m_algorithm == NULL)\n        return 0;\n\n    FixtureGroup* grp = doc()->fixtureGroup(fixtureGroup());\n    if (grp != NULL)\n        return m_algorithm->rgbMapStepCount(grp->size());\n\n    return 0;\n}\n\nvoid RGBMatrix::previewMap(int step, RGBMatrixStep *handler)\n{\n    QMutexLocker algorithmLocker(&m_algorithmMutex);\n    if (m_algorithm == NULL || handler == NULL)\n        return;\n\n    if (m_group == NULL)\n        m_group = doc()->fixtureGroup(fixtureGroup());\n\n    if (m_group != NULL)\n        m_algorithm->rgbMap(m_group->size(), handler->stepColor().rgb(), step, handler->m_map);\n}\n\n\/****************************************************************************\n * Color\n ****************************************************************************\/\n\nvoid RGBMatrix::setStartColor(const QColor& c)\n{\n    m_startColor = c;\n    {\n        QMutexLocker algorithmLocker(&m_algorithmMutex);\n        if (m_algorithm != NULL)\n        {\n            m_algorithm->setColors(m_startColor, m_endColor);\n            updateColorDelta();\n        }\n    }\n    emit changed(id());\n}\n\nQColor RGBMatrix::startColor() const\n{\n    return m_startColor;\n}\n\nvoid RGBMatrix::setEndColor(const QColor &c)\n{\n    m_endColor = c;\n    {\n        QMutexLocker algorithmLocker(&m_algorithmMutex);\n        if (m_algorithm != NULL)\n        {\n            m_algorithm->setColors(m_startColor, m_endColor);\n            updateColorDelta();\n        }\n    }\n    emit changed(id());\n}\n\nQColor RGBMatrix::endColor() const\n{\n    return m_endColor;\n}\n\nvoid RGBMatrix::updateColorDelta()\n{\n    m_stepHandler->calculateColorDelta(m_startColor, m_endColor);\n}\n\n\/************************************************************************\n * Properties\n ************************************************************************\/\n\nvoid RGBMatrix::setProperty(QString propName, QString value)\n{\n    QMutexLocker algoLocker(&m_algorithmMutex);\n    m_properties[propName] = value;\n    if (m_algorithm != NULL && m_algorithm->type() == RGBAlgorithm::Script)\n    {\n        RGBScript *script = static_cast<RGBScript*> (m_algorithm);\n        script->setProperty(propName, value);\n    }\n    m_stepsCount = stepsCount();\n}\n\nQString RGBMatrix::property(QString propName)\n{\n    QMutexLocker algoLocker(&m_algorithmMutex);\n\n    \/** If the property is cached, then return it right away *\/\n    if (m_properties.contains(propName))\n        return m_properties[propName];\n\n    \/** Otherwise, let's retrieve it from the Script *\/\n    if (m_algorithm != NULL && m_algorithm->type() == RGBAlgorithm::Script)\n    {\n        RGBScript *script = static_cast<RGBScript*> (m_algorithm);\n        return script->property(propName);\n    }\n\n    return QString();\n}\n\n\/****************************************************************************\n * Load & Save\n ****************************************************************************\/\n\nbool RGBMatrix::loadXML(QXmlStreamReader &root)\n{\n    if (root.name() != KXMLQLCFunction)\n    {\n        qWarning() << Q_FUNC_INFO << \"Function node not found\";\n        return false;\n    }\n\n    if (root.attributes().value(KXMLQLCFunctionType).toString() != typeToString(Function::RGBMatrixType))\n    {\n        qWarning() << Q_FUNC_INFO << \"Function is not an RGB matrix\";\n        return false;\n    }\n\n    \/* Load matrix contents *\/\n    while (root.readNextStartElement())\n    {\n        if (root.name() == KXMLQLCFunctionSpeed)\n        {\n            loadXMLSpeed(root);\n        }\n        else if (root.name() == KXMLQLCRGBAlgorithm)\n        {\n            setAlgorithm(RGBAlgorithm::loader(doc(), root));\n        }\n        else if (root.name() == KXMLQLCRGBMatrixFixtureGroup)\n        {\n            setFixtureGroup(root.readElementText().toUInt());\n        }\n        else if (root.name() == KXMLQLCFunctionDirection)\n        {\n            loadXMLDirection(root);\n        }\n        else if (root.name() == KXMLQLCFunctionRunOrder)\n        {\n            loadXMLRunOrder(root);\n        }\n        else if (root.name() == KXMLQLCRGBMatrixStartColor)\n        {\n            setStartColor(QColor::fromRgb(QRgb(root.readElementText().toUInt())));\n        }\n        else if (root.name() == KXMLQLCRGBMatrixEndColor)\n        {\n            setEndColor(QColor::fromRgb(QRgb(root.readElementText().toUInt())));\n        }\n        else if (root.name() == KXMLQLCRGBMatrixControlMode)\n        {\n            setControlMode(stringToControlMode(root.readElementText()));\n        }\n        else if (root.name() == KXMLQLCRGBMatrixProperty)\n        {\n            QString name = root.attributes().value(KXMLQLCRGBMatrixPropertyName).toString();\n            QString value = root.attributes().value(KXMLQLCRGBMatrixPropertyValue).toString();\n            setProperty(name, value);\n            root.skipCurrentElement();\n        }\n        else if (root.name() == KXMLQLCRGBMatrixDimmerControl)\n        {\n            setDimmerControl(root.readElementText().toInt());\n        }\n        else\n        {\n            qWarning() << Q_FUNC_INFO << \"Unknown RGB matrix tag:\" << root.name();\n            root.skipCurrentElement();\n        }\n    }\n\n    return true;\n}\n\nbool RGBMatrix::saveXML(QXmlStreamWriter *doc)\n{\n    Q_ASSERT(doc != NULL);\n\n    \/* Function tag *\/\n    doc->writeStartElement(KXMLQLCFunction);\n\n    \/* Common attributes *\/\n    saveXMLCommon(doc);\n\n    \/* Speeds *\/\n    saveXMLSpeed(doc);\n\n    \/* Direction *\/\n    saveXMLDirection(doc);\n\n    \/* Run order *\/\n    saveXMLRunOrder(doc);\n\n    \/* Algorithm *\/\n    if (m_algorithm != NULL)\n        m_algorithm->saveXML(doc);\n\n    \/* LEGACY - Dimmer Control *\/\n    if (dimmerControl())\n        doc->writeTextElement(KXMLQLCRGBMatrixDimmerControl, QString::number(dimmerControl()));\n\n    \/* Start Color *\/\n    doc->writeTextElement(KXMLQLCRGBMatrixStartColor, QString::number(startColor().rgb()));\n\n    \/* End Color *\/\n    if (endColor().isValid())\n        doc->writeTextElement(KXMLQLCRGBMatrixEndColor, QString::number(endColor().rgb()));\n\n    \/* Control Mode *\/\n    doc->writeTextElement(KXMLQLCRGBMatrixControlMode, RGBMatrix::controlModeToString(m_controlMode));\n\n    \/* Fixture Group *\/\n    doc->writeTextElement(KXMLQLCRGBMatrixFixtureGroup, QString::number(fixtureGroup()));\n\n    \/* Properties *\/\n    QHashIterator<QString, QString> it(m_properties);\n    while(it.hasNext())\n    {\n        it.next();\n        doc->writeStartElement(KXMLQLCRGBMatrixProperty);\n        doc->writeAttribute(KXMLQLCRGBMatrixPropertyName, it.key());\n        doc->writeAttribute(KXMLQLCRGBMatrixPropertyValue, it.value());\n        doc->writeEndElement();\n    }\n\n    \/* End the <Function> tag *\/\n    doc->writeEndElement();\n\n    return true;\n}\n\n\/****************************************************************************\n * Running\n ****************************************************************************\/\n\nvoid RGBMatrix::tap()\n{\n    if (stopped() == false)\n    {\n        FixtureGroup* grp = doc()->fixtureGroup(fixtureGroup());\n        \/\/ Filter out taps that are too close to each other\n        if (grp != NULL && uint(m_roundTime->elapsed()) >= (duration() \/ 4))\n        {\n            roundCheck();\n            resetElapsed();\n        }\n    }\n}\n\nvoid RGBMatrix::preRun(MasterTimer *timer)\n{\n    {\n        QMutexLocker algorithmLocker(&m_algorithmMutex);\n\n        m_group = doc()->fixtureGroup(m_fixtureGroupID);\n        if (m_group == NULL)\n        {\n            \/\/ No fixture group to control\n            stop(FunctionParent::master());\n            return;\n        }\n\n        if (m_algorithm != NULL)\n        {\n            \/\/ Copy direction from parent class direction\n            m_stepHandler->initializeDirection(direction(), m_startColor, m_endColor, m_stepsCount);\n\n            if (m_algorithm->type() == RGBAlgorithm::Script)\n            {\n                RGBScript *script = static_cast<RGBScript*> (m_algorithm);\n                QHashIterator<QString, QString> it(m_properties);\n                while(it.hasNext())\n                {\n                    it.next();\n                    script->setProperty(it.key(), it.value());\n                }\n            }\n        }\n    }\n\n    m_roundTime->restart();\n\n    Function::preRun(timer);\n}\n\nvoid RGBMatrix::write(MasterTimer *timer, QList<Universe *> universes)\n{\n    Q_UNUSED(timer);\n\n    {\n        QMutexLocker algorithmLocker(&m_algorithmMutex);\n        if (m_group == NULL)\n        {\n            \/\/ No fixture group to control\n            stop(FunctionParent::master());\n            return;\n        }\n\n        \/\/ No time to do anything.\n        if (duration() == 0)\n            return;\n\n        \/\/ Invalid\/nonexistent script\n        if (m_algorithm == NULL || m_algorithm->apiVersion() == 0)\n            return;\n\n        if (isPaused() == false)\n        {\n            \/\/ Get a new map every time elapsed is reset to zero\n            if (elapsed() < MasterTimer::tick())\n            {\n                if (tempoType() == Beats)\n                    m_stepBeatDuration = beatsToTime(duration(), timer->beatTimeDuration());\n\n                \/\/qDebug() << \"RGBMatrix step\" << m_stepHandler->currentStepIndex() << \", color:\" << QString::number(m_stepHandler->stepColor().rgb(), 16);\n                m_algorithm->rgbMap(m_group->size(), m_stepHandler->stepColor().rgb(),\n                                    m_stepHandler->currentStepIndex(), m_stepHandler->m_map);\n                updateMapChannels(m_stepHandler->m_map, m_group, universes);\n            }\n        }\n    }\n\n    if (isPaused() == false)\n    {\n        \/\/ Increment the ms elapsed time\n        incrementElapsed();\n\n        \/* Check if we need to change direction, stop completely or go to next step\n         * The cases are:\n         * 1- time tempo type: act normally, on ms elapsed time\n         * 2- beat tempo type, beat occurred: check if the elapsed beats is a multiple of\n         *    the step beat duration. If so, proceed to the next step\n         * 3- beat tempo type, not beat: if the ms elapsed time reached the step beat\n         *    duration in ms, and the ms time to the next beat is not less than 1\/16 of\n         *    the step beat duration in ms, then proceed to the next step. If the ms time to the\n         *    next beat is less than 1\/16 of the step beat duration in ms, then defer the step\n         *    change to case #2, to resync the matrix to the next beat\n         *\/\n        if (tempoType() == Time && elapsed() >= duration())\n        {\n            roundCheck();\n        }\n        else if (tempoType() == Beats)\n        {\n            if (timer->isBeat())\n            {\n                incrementElapsedBeats();\n                qDebug() << \"Elapsed beats:\" << elapsedBeats() << \", time elapsed:\" << elapsed() << \", step time:\" << m_stepBeatDuration;\n                if (elapsedBeats() % duration() == 0)\n                {\n                    roundCheck();\n                    resetElapsed();\n                }\n            }\n            else if (elapsed() >= m_stepBeatDuration && (uint)timer->timeToNextBeat() > m_stepBeatDuration \/ 16)\n            {\n                qDebug() << \"Elapsed exceeded\";\n                roundCheck();\n            }\n        }\n    }\n}\n\nvoid RGBMatrix::postRun(MasterTimer *timer, QList<Universe *> universes)\n{\n    uint fadeout = overrideFadeOutSpeed() == defaultSpeed() ? fadeOutSpeed() : overrideFadeOutSpeed();\n\n    \/* If no fade out is needed, dismiss all the requested faders.\n     * Otherwise, set all the faders to fade out and let Universe dismiss them\n     * when done *\/\n    if (fadeout == 0)\n    {\n        dismissAllFaders();\n    }\n    else\n    {\n        if (tempoType() == Beats)\n            fadeout = beatsToTime(fadeout, timer->beatTimeDuration());\n\n        foreach (QSharedPointer<GenericFader> fader, m_fadersMap.values())\n        {\n            if (!fader.isNull())\n                fader->setFadeOut(true, fadeout);\n        }\n    }\n\n    m_fadersMap.clear();\n\n    {\n        QMutexLocker algorithmLocker(&m_algorithmMutex);\n        if (m_algorithm != NULL)\n            m_algorithm->postRun();\n    }\n\n    Function::postRun(timer, universes);\n}\n\nvoid RGBMatrix::roundCheck()\n{\n    QMutexLocker algorithmLocker(&m_algorithmMutex);\n    if (m_algorithm == NULL)\n        return;\n\n    if (m_stepHandler->checkNextStep(runOrder(), m_startColor, m_endColor, m_stepsCount) == false)\n        stop(FunctionParent::master());\n\n    m_roundTime->restart();\n\n    if (tempoType() == Beats)\n        roundElapsed(m_stepBeatDuration);\n    else\n        roundElapsed(duration());\n}\n\nFadeChannel *RGBMatrix::getFader(QList<Universe *> universes, quint32 universeID, quint32 fixtureID, quint32 channel)\n{\n    \/\/ get the universe Fader first. If doesn't exist, create it\n    QSharedPointer<GenericFader> fader = m_fadersMap.value(universeID, QSharedPointer<GenericFader>());\n    if (fader.isNull())\n    {\n        fader = universes[universeID]->requestFader();\n        fader->adjustIntensity(getAttributeValue(Intensity));\n        fader->setBlendMode(blendMode());\n        fader->setName(name());\n        fader->setParentFunctionID(id());\n        m_fadersMap[universeID] = fader;\n    }\n\n    return fader->getChannelFader(doc(), universes[universeID], fixtureID, channel);\n}\n\nvoid RGBMatrix::updateFaderValues(FadeChannel *fc, uchar value, uint fadeTime)\n{\n    fc->setStart(fc->current());\n    fc->setTarget(value);\n    fc->setElapsed(0);\n    fc->setReady(false);\n    \/\/ fade in\/out depends on target value\n    if (value == 0)\n        fc->setFadeTime(fadeOutSpeed());\n    else\n        fc->setFadeTime(fadeTime);\n}\n\nvoid RGBMatrix::updateMapChannels(const RGBMap& map, const FixtureGroup *grp, QList<Universe *> universes)\n{\n    uint fadeTime = (overrideFadeInSpeed() == defaultSpeed()) ? fadeInSpeed() : overrideFadeInSpeed();\n\n    \/\/ Create\/modify fade channels for ALL heads in the group\n    QMapIterator<QLCPoint, GroupHead> it(grp->headsMap());\n    while (it.hasNext())\n    {\n        it.next();\n        QLCPoint pt = it.key();\n        GroupHead grpHead = it.value();\n        Fixture *fxi = doc()->fixture(grpHead.fxi);\n        if (fxi == NULL)\n            continue;\n\n        QLCFixtureHead head = fxi->head(grpHead.head);\n\n        if (pt.y() >= map.count() || pt.x() >= map[pt.y()].count())\n            continue;\n\n        uint col = map[pt.y()][pt.x()];\n\n        if (m_controlMode == ControlModeRgb)\n        {\n            QVector <quint32> rgb = head.rgbChannels();\n            QVector <quint32> cmy = head.cmyChannels();\n\n            if (rgb.size() == 3)\n            {\n                \/\/ RGB color mixing\n                FadeChannel *fc = getFader(universes, fxi->universe(), grpHead.fxi, rgb.at(0));\n                updateFaderValues(fc, qRed(col), fadeTime);\n\n                fc = getFader(universes, fxi->universe(), grpHead.fxi, rgb.at(1));\n                updateFaderValues(fc, qGreen(col), fadeTime);\n\n                fc = getFader(universes, fxi->universe(), grpHead.fxi, rgb.at(2));\n                updateFaderValues(fc, qBlue(col), fadeTime);\n            }\n            else if (cmy.size() == 3)\n            {\n                \/\/ CMY color mixing\n                QColor cmyCol(col);\n\n                FadeChannel *fc = getFader(universes, fxi->universe(), grpHead.fxi, cmy.at(0));\n                updateFaderValues(fc, cmyCol.cyan(), fadeTime);\n\n                fc = getFader(universes, fxi->universe(), grpHead.fxi, cmy.at(1));\n                updateFaderValues(fc, cmyCol.magenta(), fadeTime);\n\n                fc = getFader(universes, fxi->universe(), grpHead.fxi, cmy.at(2));\n                updateFaderValues(fc, cmyCol.yellow(), fadeTime);\n            }\n        }\n        else if (m_controlMode == ControlModeWhite)\n        {\n            quint32 white = head.channelNumber(QLCChannel::White, QLCChannel::MSB);\n\n            if (white != QLCChannel::invalid())\n            {\n                FadeChannel *fc = getFader(universes, fxi->universe(), grpHead.fxi, white);\n                updateFaderValues(fc, rgbToGrey(col), fadeTime);\n            }\n        }\n        else if (m_controlMode == ControlModeAmber)\n        {\n            quint32 amber = head.channelNumber(QLCChannel::Amber, QLCChannel::MSB);\n\n            if (amber != QLCChannel::invalid())\n            {\n                FadeChannel *fc = getFader(universes, fxi->universe(), grpHead.fxi, amber);\n                updateFaderValues(fc, rgbToGrey(col), fadeTime);\n            }\n        }\n        else if (m_controlMode == ControlModeUV)\n        {\n            quint32 uv = head.channelNumber(QLCChannel::UV, QLCChannel::MSB);\n\n            if (uv != QLCChannel::invalid())\n            {\n                FadeChannel *fc = getFader(universes, fxi->universe(), grpHead.fxi, uv);\n                updateFaderValues(fc, rgbToGrey(col), fadeTime);\n            }\n        }\n        else if (m_controlMode == ControlModeShutter)\n        {\n            QVector <quint32> shutters = head.shutterChannels();\n\n            if (shutters.size())\n            {\n                FadeChannel *fc = getFader(universes, fxi->universe(), grpHead.fxi, shutters.first());\n                updateFaderValues(fc, rgbToGrey(col), fadeTime);\n            }\n        }\n\n        if (m_controlMode == ControlModeDimmer || m_dimmerControl)\n        {\n            quint32 masterDim = fxi->masterIntensityChannel();\n            quint32 headDim = head.channelNumber(QLCChannel::Intensity, QLCChannel::MSB);\n            QVector <quint32> dimmers;\n\n            \/\/ Collect all dimmers that affect current head:\n            \/\/ They are the master dimmer (affects whole fixture)\n            \/\/ and per-head dimmer.\n            \/\/\n            \/\/ If there are no RGB or CMY channels, the least important* dimmer channel\n            \/\/ is used to create grayscale image.\n            \/\/\n            \/\/ The rest of the dimmer channels are set to full if dimmer control is\n            \/\/ enabled and target color is > 0 (see\n            \/\/ http:\/\/www.qlcplus.org\/forum\/viewtopic.php?f=29&t=11090)\n            \/\/\n            \/\/ Note: If there is only one head, and only one dimmer channel,\n            \/\/ make it a master dimmer in fixture definition.\n            \/\/\n            \/\/ *least important - per head dimmer if present,\n            \/\/ otherwise per fixture dimmer if present\n\n            if (masterDim != QLCChannel::invalid())\n                dimmers << masterDim;\n\n            if (headDim != QLCChannel::invalid())\n                dimmers << headDim;\n\n            if (dimmers.size())\n            {\n                \/\/ Set dimmer to value of the color (e.g. for PARs)\n                FadeChannel *fc = getFader(universes, fxi->universe(), grpHead.fxi, dimmers.last());\n                updateFaderValues(fc, rgbToGrey(col), fadeTime);\n                dimmers.pop_back();\n            }\n\n            \/\/ Set the rest of the dimmer channels to full on\n            foreach (quint32 ch, dimmers)\n            {\n                FadeChannel *fc = getFader(universes, fxi->universe(), grpHead.fxi, ch);\n                updateFaderValues(fc, col == 0 ? 0 : 255, fadeTime);\n            }\n        }\n    }\n}\n\nuchar RGBMatrix::rgbToGrey(uint col)\n{\n    \/\/ the weights are taken from\n    \/\/ https:\/\/en.wikipedia.org\/wiki\/YUV#SDTV_with_BT.601\n    return (0.299 * qRed(col) + 0.587 * qGreen(col) + 0.114 * qBlue(col));\n}\n\n\/*********************************************************************\n * Attributes\n *********************************************************************\/\n\nint RGBMatrix::adjustAttribute(qreal fraction, int attributeId)\n{\n    int attrIndex = Function::adjustAttribute(fraction, attributeId);\n\n    if (attrIndex == Intensity)\n    {\n        foreach (QSharedPointer<GenericFader> fader, m_fadersMap.values())\n        {\n            if (!fader.isNull())\n                fader->adjustIntensity(getAttributeValue(Function::Intensity));\n        }\n    }\n\n    return attrIndex;\n}\n\n\/*************************************************************************\n * Blend mode\n *************************************************************************\/\n\nvoid RGBMatrix::setBlendMode(Universe::BlendMode mode)\n{\n    if (mode == blendMode())\n        return;\n\n    foreach (QSharedPointer<GenericFader> fader, m_fadersMap.values())\n    {\n        if (!fader.isNull())\n            fader->setBlendMode(mode);\n    }\n\n    Function::setBlendMode(mode);\n    emit changed(id());\n}\n\n\/*************************************************************************\n * Control Mode\n *************************************************************************\/\n\nRGBMatrix::ControlMode RGBMatrix::controlMode() const\n{\n    return m_controlMode;\n}\n\nvoid RGBMatrix::setControlMode(RGBMatrix::ControlMode mode)\n{\n    m_controlMode = mode;\n    emit changed(id());\n}\n\nRGBMatrix::ControlMode RGBMatrix::stringToControlMode(QString mode)\n{\n    if (mode == KXMLQLCRGBMatrixControlModeRgb)\n        return ControlModeRgb;\n    else if (mode == KXMLQLCRGBMatrixControlModeAmber)\n        return ControlModeAmber;\n    else if (mode == KXMLQLCRGBMatrixControlModeWhite)\n        return ControlModeWhite;\n    else if (mode == KXMLQLCRGBMatrixControlModeUV)\n        return ControlModeUV;\n    else if (mode == KXMLQLCRGBMatrixControlModeDimmer)\n        return ControlModeDimmer;\n    else if (mode == KXMLQLCRGBMatrixControlModeShutter)\n        return ControlModeShutter;\n\n    return ControlModeRgb;\n}\n\nQString RGBMatrix::controlModeToString(RGBMatrix::ControlMode mode)\n{\n    switch(mode)\n    {\n        default:\n        case ControlModeRgb:\n            return QString(KXMLQLCRGBMatrixControlModeRgb);\n        break;\n        case ControlModeAmber:\n            return QString(KXMLQLCRGBMatrixControlModeAmber);\n        break;\n        case ControlModeWhite:\n            return QString(KXMLQLCRGBMatrixControlModeWhite);\n        break;\n        case ControlModeUV:\n            return QString(KXMLQLCRGBMatrixControlModeUV);\n        break;\n        case ControlModeDimmer:\n            return QString(KXMLQLCRGBMatrixControlModeDimmer);\n        break;\n        case ControlModeShutter:\n            return QString(KXMLQLCRGBMatrixControlModeShutter);\n        break;\n    }\n}\n\n\n\/*************************************************************************\n *************************************************************************\n *                          RGBMatrixStep class\n *************************************************************************\n *************************************************************************\/\n\nRGBMatrixStep::RGBMatrixStep()\n    : m_direction(Function::Forward)\n    , m_currentStepIndex(0)\n    , m_stepColor(QColor())\n    , m_crDelta(0)\n    , m_cgDelta(0)\n    , m_cbDelta(0)\n{\n\n}\n\nvoid RGBMatrixStep::setCurrentStepIndex(int index)\n{\n    m_currentStepIndex = index;\n}\n\nint RGBMatrixStep::currentStepIndex() const\n{\n    return m_currentStepIndex;\n}\n\nvoid RGBMatrixStep::calculateColorDelta(QColor startColor, QColor endColor)\n{\n    m_crDelta = 0;\n    m_cgDelta = 0;\n    m_cbDelta = 0;\n\n    if (endColor.isValid())\n    {\n        m_crDelta = endColor.red() - startColor.red();\n        m_cgDelta = endColor.green() - startColor.green();\n        m_cbDelta = endColor.blue() - startColor.blue();\n\n        \/\/qDebug() << \"Color deltas:\" << m_crDelta << m_cgDelta << m_cbDelta;\n    }\n}\n\nvoid RGBMatrixStep::setStepColor(QColor color)\n{\n    m_stepColor = color;\n}\n\nQColor RGBMatrixStep::stepColor()\n{\n    return m_stepColor;\n}\n\nvoid RGBMatrixStep::updateStepColor(int stepIndex, QColor startColor, int stepsCount)\n{\n    if (stepsCount <= 0)\n        return;\n\n    if (stepsCount == 1)\n    {\n        m_stepColor = startColor;\n    }\n    else\n    {\n        m_stepColor.setRed(startColor.red() + (m_crDelta * stepIndex \/ (stepsCount - 1)));\n        m_stepColor.setGreen(startColor.green() + (m_cgDelta * stepIndex \/ (stepsCount - 1)));\n        m_stepColor.setBlue(startColor.blue() + (m_cbDelta * stepIndex \/ (stepsCount - 1)));\n    }\n\n    \/\/qDebug() << \"RGBMatrix step\" << stepIndex << \", color:\" << QString::number(m_stepColor.rgb(), 16);\n}\n\nvoid RGBMatrixStep::initializeDirection(Function::Direction direction, QColor startColor, QColor endColor, int stepsCount)\n{\n    m_direction = direction;\n\n    if (m_direction == Function::Forward)\n    {\n        setCurrentStepIndex(0);\n        setStepColor(startColor);\n    }\n    else\n    {\n        setCurrentStepIndex(stepsCount - 1);\n\n        if (endColor.isValid())\n            setStepColor(endColor);\n        else\n            setStepColor(startColor);\n    }\n\n    calculateColorDelta(startColor, endColor);\n}\n\nbool RGBMatrixStep::checkNextStep(Function::RunOrder order,\n                                  QColor startColor, QColor endColor, int stepsNumber)\n{\n    if (order == Function::PingPong)\n    {\n        if (m_direction == Function::Forward && (m_currentStepIndex + 1) == stepsNumber)\n        {\n            m_direction = Function::Backward;\n            m_currentStepIndex = stepsNumber - 2;\n            if (endColor.isValid())\n                m_stepColor = endColor;\n\n            updateStepColor(m_currentStepIndex, startColor, stepsNumber);\n        }\n        else if (m_direction == Function::Backward && (m_currentStepIndex - 1) < 0)\n        {\n            m_direction = Function::Forward;\n            m_currentStepIndex = 1;\n            m_stepColor = startColor;\n            updateStepColor(m_currentStepIndex, startColor, stepsNumber);\n        }\n        else\n        {\n            if (m_direction == Function::Forward)\n                m_currentStepIndex++;\n            else\n                m_currentStepIndex--;\n            updateStepColor(m_currentStepIndex, startColor, stepsNumber);\n        }\n    }\n    else if (order == Function::SingleShot)\n    {\n        if (m_direction == Function::Forward)\n        {\n            if (m_currentStepIndex >= stepsNumber - 1)\n                return false;\n            else\n            {\n                m_currentStepIndex++;\n                updateStepColor(m_currentStepIndex, startColor, stepsNumber);\n            }\n        }\n        else\n        {\n            if (m_currentStepIndex <= 0)\n                return false;\n            else\n            {\n                m_currentStepIndex--;\n                updateStepColor(m_currentStepIndex, startColor, stepsNumber);\n            }\n        }\n    }\n    else\n    {\n        if (m_direction == Function::Forward)\n        {\n            if (m_currentStepIndex >= stepsNumber - 1)\n            {\n                m_currentStepIndex = 0;\n                m_stepColor = startColor;\n            }\n            else\n            {\n                m_currentStepIndex++;\n                updateStepColor(m_currentStepIndex, startColor, stepsNumber);\n            }\n        }\n        else\n        {\n            if (m_currentStepIndex <= 0)\n            {\n                m_currentStepIndex = stepsNumber - 1;\n                if (endColor.isValid())\n                    m_stepColor = endColor;\n            }\n            else\n            {\n                m_currentStepIndex--;\n                updateStepColor(m_currentStepIndex, startColor, stepsNumber);\n            }\n        }\n    }\n\n    return true;\n}\n\n","avg_line_length":29.8262411348,"max_line_length":155,"alphanum_fraction":0.5632802283,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":15899,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":28.0,"content":"\/*++\nCopyright (c) 2012 Microsoft Corporation\n\nModule Name:\n\n    api_quant.cpp\n\nAbstract:\n    API for models\n\nAuthor:\n\n    Leonardo de Moura (leonardo) 2012-02-29.\n\nRevision History:\n\n--*\/\n#include \"api\/z3.h\"\n#include \"api\/api_log_macros.h\"\n#include \"api\/api_context.h\"\n#include \"api\/api_model.h\"\n#include \"api\/api_ast_vector.h\"\n#include \"ast\/array_decl_plugin.h\"\n#include \"model\/model.h\"\n#include \"model\/model_v2_pp.h\"\n#include \"model\/model_smt2_pp.h\"\n#include \"model\/model_params.hpp\"\n#include \"model\/model_evaluator_params.hpp\"\n\nextern \"C\" {\n\n    Z3_model Z3_API Z3_mk_model(Z3_context c) {\n        Z3_TRY;\n        LOG_Z3_mk_model(c);\n        RESET_ERROR_CODE();\n        Z3_model_ref * m_ref = alloc(Z3_model_ref, *mk_c(c)); \n        m_ref->m_model = alloc(model, mk_c(c)->m());\n        mk_c(c)->save_object(m_ref);\n        RETURN_Z3(of_model(m_ref));\n        Z3_CATCH_RETURN(nullptr);\n    }\n\n    void Z3_API Z3_model_inc_ref(Z3_context c, Z3_model m) {\n        Z3_TRY;\n        LOG_Z3_model_inc_ref(c, m);\n        RESET_ERROR_CODE();\n        if (m) {\n            to_model(m)->inc_ref();\n        }\n        Z3_CATCH;\n    }\n\n    void Z3_API Z3_model_dec_ref(Z3_context c, Z3_model m) {\n        Z3_TRY;\n        LOG_Z3_model_dec_ref(c, m);\n        RESET_ERROR_CODE();\n        if (m) {\n            to_model(m)->dec_ref();\n        }\n        Z3_CATCH;\n    }\n\n    Z3_ast_opt Z3_API Z3_model_get_const_interp(Z3_context c, Z3_model m, Z3_func_decl a) {\n        Z3_TRY;\n        LOG_Z3_model_get_const_interp(c, m, a);\n        RESET_ERROR_CODE();\n        CHECK_NON_NULL(m, nullptr);\n        expr * r = to_model_ref(m)->get_const_interp(to_func_decl(a));\n        if (!r) {\n            RETURN_Z3(nullptr);\n        }\n        mk_c(c)->save_ast_trail(r);\n        RETURN_Z3(of_expr(r));\n        Z3_CATCH_RETURN(nullptr);\n    }\n\n    bool Z3_API Z3_model_has_interp(Z3_context c, Z3_model m, Z3_func_decl a) {\n        Z3_TRY;\n        LOG_Z3_model_has_interp(c, m, a);\n        CHECK_NON_NULL(m, 0);\n        return to_model_ref(m)->has_interpretation(to_func_decl(a));\n        Z3_CATCH_RETURN(false);\n    }\n\n    Z3_func_interp Z3_API Z3_model_get_func_interp(Z3_context c, Z3_model m, Z3_func_decl f) {\n        Z3_TRY;\n        LOG_Z3_model_get_func_interp(c, m, f);\n        RESET_ERROR_CODE();\n        CHECK_NON_NULL(m, nullptr);\n        func_interp * _fi       = to_model_ref(m)->get_func_interp(to_func_decl(f));\n        if (!_fi) {\n            SET_ERROR_CODE(Z3_INVALID_ARG, nullptr);\n            RETURN_Z3(nullptr);\n        }\n        Z3_func_interp_ref * fi = alloc(Z3_func_interp_ref, *mk_c(c), to_model_ref(m));\n        fi->m_func_interp       = _fi;\n        mk_c(c)->save_object(fi);\n        RETURN_Z3(of_func_interp(fi));\n        Z3_CATCH_RETURN(nullptr);\n    }\n\n    unsigned Z3_API Z3_model_get_num_consts(Z3_context c, Z3_model m) {\n        Z3_TRY;\n        LOG_Z3_model_get_num_consts(c, m);\n        RESET_ERROR_CODE();\n        CHECK_NON_NULL(m, 0);\n        return to_model_ref(m)->get_num_constants();\n        Z3_CATCH_RETURN(0);\n    }\n\n    Z3_func_decl Z3_API Z3_model_get_const_decl(Z3_context c, Z3_model m, unsigned i) {\n        Z3_TRY;\n        LOG_Z3_model_get_const_decl(c, m, i);\n        RESET_ERROR_CODE();\n        CHECK_NON_NULL(m, nullptr);\n        model * _m = to_model_ref(m);\n        if (i < _m->get_num_constants()) {\n            RETURN_Z3(of_func_decl(_m->get_constant(i))); \n        }\n        else {\n            SET_ERROR_CODE(Z3_IOB, nullptr);\n            RETURN_Z3(nullptr);\n        }\n        Z3_CATCH_RETURN(nullptr);\n    }\n    \n    unsigned Z3_API Z3_model_get_num_funcs(Z3_context c, Z3_model m) {\n        Z3_TRY;\n        LOG_Z3_model_get_num_funcs(c, m);\n        RESET_ERROR_CODE();\n        CHECK_NON_NULL(m, 0);\n        return to_model_ref(m)->get_num_functions();\n        Z3_CATCH_RETURN(0);\n    }\n\n    Z3_func_decl get_model_func_decl_core(Z3_context c, Z3_model m, unsigned i) {\n        CHECK_NON_NULL(m, nullptr);\n        model * _m = to_model_ref(m);\n        if (i >= _m->get_num_functions()) {\n            SET_ERROR_CODE(Z3_IOB, nullptr);\n            return nullptr;\n        }\n        return of_func_decl(_m->get_function(i));\n    }\n    \n    Z3_func_decl Z3_API Z3_model_get_func_decl(Z3_context c, Z3_model m, unsigned i) {\n        Z3_TRY;\n        LOG_Z3_model_get_func_decl(c, m, i);\n        RESET_ERROR_CODE();\n        Z3_func_decl r = get_model_func_decl_core(c, m, i);\n        RETURN_Z3(r);\n        Z3_CATCH_RETURN(nullptr);\n    }\n    \n    bool Z3_API Z3_model_eval(Z3_context c, Z3_model m, Z3_ast t, bool model_completion, Z3_ast * v) {\n        Z3_TRY;\n        LOG_Z3_model_eval(c, m, t, model_completion, v);\n        if (v) *v = nullptr;\n        RESET_ERROR_CODE();\n        CHECK_NON_NULL(m, false);\n        CHECK_IS_EXPR(t, false);\n        model * _m = to_model_ref(m);\n        params_ref p;\n        ast_manager& mgr = mk_c(c)->m();\n        _m->set_solver(alloc(api::seq_expr_solver, mgr, p));\n        expr_ref result(mgr);\n        model::scoped_model_completion _scm(*_m, model_completion);\n        result = (*_m)(to_expr(t));\n        mk_c(c)->save_ast_trail(result.get());\n        *v = of_ast(result.get());\n        RETURN_Z3_model_eval true;\n        Z3_CATCH_RETURN(0);\n    }\n\n    unsigned Z3_API Z3_model_get_num_sorts(Z3_context c, Z3_model m) {\n        Z3_TRY;\n        LOG_Z3_model_get_num_sorts(c, m);\n        RESET_ERROR_CODE();\n        return to_model_ref(m)->get_num_uninterpreted_sorts();\n        Z3_CATCH_RETURN(0);\n    }\n\n    Z3_sort Z3_API Z3_model_get_sort(Z3_context c, Z3_model m, unsigned i) {\n        Z3_TRY;\n        LOG_Z3_model_get_sort(c, m, i);\n        RESET_ERROR_CODE();\n        if (i >= to_model_ref(m)->get_num_uninterpreted_sorts()) {\n            SET_ERROR_CODE(Z3_IOB, nullptr);\n            RETURN_Z3(nullptr);\n        }\n        sort * s = to_model_ref(m)->get_uninterpreted_sort(i);\n        RETURN_Z3(of_sort(s));\n        Z3_CATCH_RETURN(nullptr);\n    }\n\n    Z3_ast_vector Z3_API Z3_model_get_sort_universe(Z3_context c, Z3_model m, Z3_sort s) {\n        Z3_TRY;\n        LOG_Z3_model_get_sort_universe(c, m, s);\n        RESET_ERROR_CODE();\n        if (!to_model_ref(m)->has_uninterpreted_sort(to_sort(s))) {\n            SET_ERROR_CODE(Z3_INVALID_ARG, nullptr);\n            RETURN_Z3(nullptr);\n        }\n        ptr_vector<expr> const & universe = to_model_ref(m)->get_universe(to_sort(s));\n        Z3_ast_vector_ref * v = alloc(Z3_ast_vector_ref, *mk_c(c), mk_c(c)->m());\n        mk_c(c)->save_object(v);\n        for (expr * e : universe) {\n            v->m_ast_vector.push_back(e);\n        }\n        RETURN_Z3(of_ast_vector(v));\n        Z3_CATCH_RETURN(nullptr);\n    }\n\n    Z3_model Z3_API Z3_model_translate(Z3_context c, Z3_model m, Z3_context target) {\n        Z3_TRY;\n        LOG_Z3_model_translate(c, m, target);\n        RESET_ERROR_CODE();\n        Z3_model_ref* dst = alloc(Z3_model_ref, *mk_c(target));\n        ast_translation tr(mk_c(c)->m(), mk_c(target)->m());\n        dst->m_model = to_model_ref(m)->translate(tr);\n        mk_c(target)->save_object(dst);\n        RETURN_Z3(of_model(dst));\n        Z3_CATCH_RETURN(nullptr);\n    }\n    \n    bool Z3_API Z3_is_as_array(Z3_context c, Z3_ast a) {\n        Z3_TRY;\n        LOG_Z3_is_as_array(c, a);\n        RESET_ERROR_CODE();\n        return a && is_expr(to_ast(a)) && is_app_of(to_expr(a), mk_c(c)->get_array_fid(), OP_AS_ARRAY);\n        Z3_CATCH_RETURN(false);\n    }\n    \n    Z3_func_decl Z3_API Z3_get_as_array_func_decl(Z3_context c, Z3_ast a) {\n        Z3_TRY;\n        LOG_Z3_get_as_array_func_decl(c, a);\n        RESET_ERROR_CODE();\n        if (a && is_expr(to_ast(a)) && is_app_of(to_expr(a), mk_c(c)->get_array_fid(), OP_AS_ARRAY)) {\n            RETURN_Z3(of_func_decl(to_func_decl(to_app(a)->get_decl()->get_parameter(0).get_ast())));\n        }\n        else {\n            SET_ERROR_CODE(Z3_INVALID_ARG, nullptr);\n            RETURN_Z3(nullptr);\n        }\n        Z3_CATCH_RETURN(nullptr);\n    }\n\n    Z3_func_interp Z3_API Z3_add_func_interp(Z3_context c, Z3_model m, Z3_func_decl f, Z3_ast else_val) {\n        Z3_TRY;\n        LOG_Z3_add_func_interp(c, m, f, else_val);\n        RESET_ERROR_CODE();\n\t\tCHECK_NON_NULL(f, nullptr);\n        func_decl* d = to_func_decl(f);\n        model* mdl = to_model_ref(m);\n        Z3_func_interp_ref * f_ref = alloc(Z3_func_interp_ref, *mk_c(c), mdl); \n        f_ref->m_func_interp = alloc(func_interp, mk_c(c)->m(), d->get_arity());\n        mk_c(c)->save_object(f_ref);\n        mdl->register_decl(d, f_ref->m_func_interp);\n        f_ref->m_func_interp->set_else(to_expr(else_val));\n        RETURN_Z3(of_func_interp(f_ref));\n        Z3_CATCH_RETURN(nullptr);\n    }\n\n    void Z3_API Z3_add_const_interp(Z3_context c, Z3_model m, Z3_func_decl f, Z3_ast a) {\n        Z3_TRY;\n        LOG_Z3_add_const_interp(c, m, f, a);\n        RESET_ERROR_CODE();\n        func_decl* d = to_func_decl(f);\n        if (!d || d->get_arity() != 0) {\n            SET_ERROR_CODE(Z3_INVALID_ARG, nullptr);\n        }\n        else {\n            model* mdl = to_model_ref(m);\n            mdl->register_decl(d, to_expr(a));\n        }\n        Z3_CATCH;\n    }\n\n    void Z3_API Z3_func_interp_inc_ref(Z3_context c, Z3_func_interp f) {\n        Z3_TRY;\n        LOG_Z3_func_interp_inc_ref(c, f);\n        RESET_ERROR_CODE();\n        if (f) {\n            to_func_interp(f)->inc_ref();\n        }\n        Z3_CATCH;\n    }\n\n    void Z3_API Z3_func_interp_dec_ref(Z3_context c, Z3_func_interp f) {\n        Z3_TRY;\n        LOG_Z3_func_interp_dec_ref(c, f);\n        RESET_ERROR_CODE();\n        if (f) {\n            to_func_interp(f)->dec_ref();\n        }\n        Z3_CATCH;\n    }\n    \n    unsigned Z3_API Z3_func_interp_get_num_entries(Z3_context c, Z3_func_interp f) {\n        Z3_TRY;\n        LOG_Z3_func_interp_get_num_entries(c, f);\n        RESET_ERROR_CODE();\n        CHECK_NON_NULL(f, 0);\n        return to_func_interp_ref(f)->num_entries();\n        Z3_CATCH_RETURN(0);\n    }\n\n    Z3_func_entry Z3_API Z3_func_interp_get_entry(Z3_context c, Z3_func_interp f, unsigned i) {\n        Z3_TRY;\n        LOG_Z3_func_interp_get_entry(c, f, i);\n        RESET_ERROR_CODE();\n        CHECK_NON_NULL(f, nullptr);\n        if (i >= to_func_interp_ref(f)->num_entries()) {\n            SET_ERROR_CODE(Z3_IOB, nullptr);\n            RETURN_Z3(nullptr);\n        }\n        Z3_func_entry_ref * e = alloc(Z3_func_entry_ref, *mk_c(c), to_func_interp(f)->m_model.get());\n        e->m_func_interp = to_func_interp_ref(f);\n        e->m_func_entry  = to_func_interp_ref(f)->get_entry(i);\n        mk_c(c)->save_object(e);\n        RETURN_Z3(of_func_entry(e));\n        Z3_CATCH_RETURN(nullptr);\n    }\n    \n    Z3_ast Z3_API Z3_func_interp_get_else(Z3_context c, Z3_func_interp f) {\n        Z3_TRY;\n        LOG_Z3_func_interp_get_else(c, f);\n        RESET_ERROR_CODE();\n        CHECK_NON_NULL(f, nullptr);\n        expr * e = to_func_interp_ref(f)->get_else();\n        if (e) {\n            mk_c(c)->save_ast_trail(e);\n        }\n        RETURN_Z3(of_expr(e));\n        Z3_CATCH_RETURN(nullptr);\n    }\n\n    void Z3_API Z3_func_interp_set_else(Z3_context c, Z3_func_interp f, Z3_ast else_value) {\n        Z3_TRY;\n        LOG_Z3_func_interp_set_else(c, f, else_value);\n        RESET_ERROR_CODE();\n        \/\/ CHECK_NON_NULL(f, 0);\n        to_func_interp_ref(f)->set_else(to_expr(else_value));\n        Z3_CATCH;\n    }\n\n    unsigned Z3_API Z3_func_interp_get_arity(Z3_context c, Z3_func_interp f) {\n        Z3_TRY;\n        LOG_Z3_func_interp_get_arity(c, f);\n        RESET_ERROR_CODE();\n        CHECK_NON_NULL(f, 0);\n        return to_func_interp_ref(f)->get_arity();\n        Z3_CATCH_RETURN(0);\n    }\n\n    void Z3_API Z3_func_interp_add_entry(Z3_context c, Z3_func_interp fi, Z3_ast_vector args, Z3_ast value) {\n        Z3_TRY;\n        LOG_Z3_func_interp_add_entry(c, fi, args, value);\n        \/\/CHECK_NON_NULL(fi, void);\n        \/\/CHECK_NON_NULL(args, void);\n        \/\/CHECK_NON_NULL(value, void);\n        func_interp* _fi = to_func_interp_ref(fi);\n        expr* _value = to_expr(value);\n        if (to_ast_vector_ref(args).size() != _fi->get_arity()) {\n            SET_ERROR_CODE(Z3_IOB, nullptr);\n            return;\n        }\n        \/\/ check sorts of value\n        expr* const* _args = (expr* const*) to_ast_vector_ref(args).c_ptr();\n        _fi->insert_entry(_args, _value);\n        Z3_CATCH;\n    }\n\n    void Z3_API Z3_func_entry_inc_ref(Z3_context c, Z3_func_entry e) {\n        Z3_TRY;\n        LOG_Z3_func_entry_inc_ref(c, e);\n        RESET_ERROR_CODE();\n        if (e) {\n            to_func_entry(e)->inc_ref();\n        }\n        Z3_CATCH;\n    }\n\n    void Z3_API Z3_func_entry_dec_ref(Z3_context c, Z3_func_entry e) {\n        Z3_TRY;\n        LOG_Z3_func_entry_dec_ref(c, e);\n        RESET_ERROR_CODE();\n        if (e) {\n            to_func_entry(e)->dec_ref();\n        }\n        Z3_CATCH;\n    }\n    \n    Z3_ast Z3_API Z3_func_entry_get_value(Z3_context c, Z3_func_entry e) {\n        Z3_TRY;\n        LOG_Z3_func_entry_get_value(c, e);\n        RESET_ERROR_CODE();\n        expr * v = to_func_entry_ref(e)->get_result();\n        mk_c(c)->save_ast_trail(v);\n        RETURN_Z3(of_expr(v));\n        Z3_CATCH_RETURN(nullptr);\n    }\n\n    unsigned Z3_API Z3_func_entry_get_num_args(Z3_context c, Z3_func_entry e) {\n        Z3_TRY;\n        LOG_Z3_func_entry_get_num_args(c, e);\n        RESET_ERROR_CODE();\n        return to_func_entry(e)->m_func_interp->get_arity();\n        Z3_CATCH_RETURN(0);\n    }\n    \n    Z3_ast Z3_API Z3_func_entry_get_arg(Z3_context c, Z3_func_entry e, unsigned i) {\n        Z3_TRY;\n        LOG_Z3_func_entry_get_arg(c, e, i);\n        RESET_ERROR_CODE();\n        if (i >= to_func_entry(e)->m_func_interp->get_arity()) {\n            SET_ERROR_CODE(Z3_IOB, nullptr);\n            RETURN_Z3(nullptr);\n        }\n        expr * r = to_func_entry(e)->m_func_entry->get_arg(i);\n        RETURN_Z3(of_expr(r));\n        Z3_CATCH_RETURN(nullptr);\n    }    \n\n    unsigned get_model_func_num_entries_core(Z3_context c, Z3_model m, unsigned i) {\n        RESET_ERROR_CODE();\n        CHECK_NON_NULL(m, 0);\n        Z3_func_decl d = get_model_func_decl_core(c, m, i);\n        if (d) {\n            model * _m = to_model_ref(m);            \n            func_interp * g = _m->get_func_interp(to_func_decl(d));\n            if (g) {\n                return g->num_entries();\n            }\n            SET_ERROR_CODE(Z3_IOB, nullptr);\n            return 0;\n        }\n        return 0;\n    }\n    \n\n    unsigned get_model_func_entry_num_args_core(Z3_context c,\n                                                Z3_model m,\n                                                unsigned i,\n                                                unsigned j) {\n        RESET_ERROR_CODE();\n        CHECK_NON_NULL(m, 0);\n        if (j >= get_model_func_num_entries_core(c, m, i)) {\n            SET_ERROR_CODE(Z3_IOB, nullptr);\n            return 0;\n        }\n        Z3_func_decl d = get_model_func_decl_core(c, m, i);\n        if (d) {\n            model * _m = to_model_ref(m);\n            func_interp * g = _m->get_func_interp(to_func_decl(d));\n            return g->get_arity();\n        }\n        return 0;\n    }\n    \n\n    Z3_API char const * Z3_model_to_string(Z3_context c, Z3_model m) {\n        Z3_TRY;\n        LOG_Z3_model_to_string(c, m);\n        RESET_ERROR_CODE();\n        CHECK_NON_NULL(m, nullptr);\n        std::ostringstream buffer;\n        std::string result;\n        if (mk_c(c)->get_print_mode() == Z3_PRINT_SMTLIB2_COMPLIANT) {\n            model_smt2_pp(buffer, mk_c(c)->m(), *(to_model_ref(m)), 0);\n            \/\/ Hack for removing the trailing '\\n'\n            result = buffer.str();\n            if (!result.empty())\n                result.resize(result.size()-1);\n        }\n        else {\n            model_params p;\n            model_v2_pp(buffer, *(to_model_ref(m)), p.partial());\n            result = buffer.str();\n        }\n        return mk_c(c)->mk_external_string(std::move(result));\n        Z3_CATCH_RETURN(nullptr);\n    }\n\n};\n","avg_line_length":32.7139917695,"max_line_length":109,"alphanum_fraction":0.5956978426,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":573,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"#include \"Tools.hpp\"\n\nchar *Tools::getValueFromString(char *data, char separator, int index)\n{\n    String _data = data;\n    int found = 0;\n    int strIndex[] = {0, -1};\n    int maxIndex = _data.length() - 1;\n\n    for (int i = 0; i <= maxIndex && found <= index; i++)\n    {\n        if (_data.charAt(i) == separator || i == maxIndex)\n        {\n            found++;\n            strIndex[0] = strIndex[1] + 1;\n            strIndex[1] = (i == maxIndex) ? i + 1 : i;\n        }\n    }\n\n    return strdup((found > index ? _data.substring(strIndex[0], strIndex[1]) : \"\").c_str());\n}\n","avg_line_length":26.0454545455,"max_line_length":92,"alphanum_fraction":0.5148342059,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2802,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * License); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/*\n * Copyright (c) 2017, Open AI Lab\n * Author: haitao@openailab.com\n *\/\n#include \"operator.hpp\"\n#include \"operator\/convolution.hpp\"\n#include \"operator\/input_op.hpp\"\n#include \"operator\/pooling.hpp\"\n#include \"operator\/softmax.hpp\"\n#include \"operator\/prelu.hpp\"\n\n\nusing namespace TEngine;\n\n\n#define PRINT_PARAM_ENTRY(param,e) std::cout<<#e<<\":  \"<<param->e <<std::endl;\n\nextern \"C\" {\n\n   int tengine_plugin_init(void);\n}\n\nint main(void)\n{\n\n   tengine_plugin_init();\n\n    Convolution op;\n\n   op.Input({\"weight:float32\",\"bias:float32\",\"input:float32\"})\n   .Output({\"output:float32\"})\n   .SetLayout(\"NCHW\")\n   .SetDoc(R\"DOC(This is a test)DOC\")\n   .SetAttr(\"kernel_h\",3);\n\n\n\n   Convolution * conv_op=dynamic_cast<Convolution*>(CREATE_OPERATOR(\"Convolution\"));\n\n   std::cout<<conv_op->GetDoc()<<std::endl;\n\n   std::cout<<any_cast<int>((*conv_op)[\"kernel_h\"])<<std::endl;\n\n   (*conv_op)[\"kernel_h\"]=100;\n\n   conv_op->ParseDefParam();\n\n   ConvParam *p_param=conv_op->GetParam();\n\n   PRINT_PARAM_ENTRY(p_param,kernel_h);\n   PRINT_PARAM_ENTRY(p_param,stride_h);\n   PRINT_PARAM_ENTRY(p_param,pad_w);\n   PRINT_PARAM_ENTRY(p_param,output_channel);\n\n\n   Pooling * pool_op=dynamic_cast<Pooling*>(CREATE_OPERATOR(\"Pooling\"));\n\n   std::cout<<pool_op->GetDoc()<<std::endl;\n\n   PoolParam * pool_param=pool_op->GetParam();\n\n   (*pool_op)[\"method\"]=\"avg\";\n\n   pool_op->ParseDefParam();\n\n   PRINT_PARAM_ENTRY(pool_param,method);\n   PRINT_PARAM_ENTRY(pool_param,alg);\n   PRINT_PARAM_ENTRY(pool_param,kernel_h);\n  \n   \n   SoftMax * softmax_op=dynamic_cast<SoftMax *>(CREATE_OPERATOR(\"SoftMax\"));\n\n   std::cout<<\"INPUT NUMBER: \"<<softmax_op->GetInputNum()<<std::endl;\n\n   InputOp * input_op=dynamic_cast<InputOp*>(CREATE_OPERATOR(\"InputOp\"));\n\n   std::cout<<\"DataLayout: \"<<input_op->GetLayout()<<std::endl;\n\n   \/\/prelu\n   PReLU * prelu_op=dynamic_cast<PReLU*>(CREATE_OPERATOR(\"PReLU\"));\n   std::cout<<prelu_op->GetDoc()<<std::endl;\n   std::cout<<\"PReLU INPUT NUMBER: \"<<prelu_op->GetInputNum()<<std::endl;\n  return 0;\n}\n","avg_line_length":26.9423076923,"max_line_length":84,"alphanum_fraction":0.7087794433,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":88936,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":2.0,"content":"\/\/ SPDX-License-Identifier: BSD-3-Clause\n\/\/ Copyright Contributors to the OpenColorIO Project.\n\n\n#include \"CPUProcessor.cpp\"\n\n#include \"ops\/lut1d\/Lut1DOp.h\"\n#include \"ops\/lut1d\/Lut1DOpData.h\"\n#include \"ScanlineHelper.h\"\n#include \"testutils\/UnitTest.h\"\n#include \"UnitTestUtils.h\"\n\nnamespace OCIO = OCIO_NAMESPACE;\n\n\nOCIO_ADD_TEST(CPUProcessor, flag_composition)\n{\n    \/\/ The test validates the build of a custom optimization flag.\n\n    OCIO::OptimizationFlags customFlags = OCIO::OPTIMIZATION_LOSSLESS;\n\n    OCIO_CHECK_EQUAL((customFlags & OCIO::OPTIMIZATION_COMP_LUT1D),\n                     OCIO::OPTIMIZATION_NONE);\n\n    customFlags\n        = OCIO::OptimizationFlags(customFlags | OCIO::OPTIMIZATION_COMP_LUT1D);\n\n    OCIO_CHECK_EQUAL((customFlags & OCIO::OPTIMIZATION_COMP_LUT1D),\n                     OCIO::OPTIMIZATION_COMP_LUT1D);\n}\n\n\n\/\/ TODO: CPUProcessor being part of the OCIO public API limits the ability\n\/\/       to inspect the CPUProcessor instance content i.e. the list of CPUOps.\n\/\/       Even a successful apply could hide a major performance hit because of\n\/\/       a missing\/partial optimization.\n\n\ntemplate<OCIO::BitDepth inBD, OCIO::BitDepth outBD, unsigned line>\nOCIO::ConstCPUProcessorRcPtr ComputeValues(OCIO::ConstProcessorRcPtr processor,\n                                           const void * inImg,\n                                           OCIO::ChannelOrdering inChans,\n                                           const void * resImg,\n                                           OCIO::ChannelOrdering outChans,\n                                           long numPixels,\n                                           \/\/ Default value to nan to break any float comparisons\n                                           \/\/ as a valid error threshold is mandatory in that case.\n                                           float absErrorThreshold\n                                                = std::numeric_limits<float>::quiet_NaN())\n{\n    typedef typename OCIO::BitDepthInfo<inBD>::Type inType;\n    typedef typename OCIO::BitDepthInfo<outBD>::Type outType;\n\n    OCIO::ConstCPUProcessorRcPtr cpuProcessor;\n\n    OCIO_CHECK_NO_THROW_FROM(cpuProcessor\n        = processor->getOptimizedCPUProcessor(inBD, outBD,\n                                              OCIO::OPTIMIZATION_DEFAULT), line);\n\n    size_t numChannels = 4;\n    if(outChans==OCIO::CHANNEL_ORDERING_RGB || outChans==OCIO::CHANNEL_ORDERING_BGR)\n    {\n        numChannels = 3;\n    }\n    const size_t numValues = size_t(numPixels * numChannels);\n\n    const OCIO::PackedImageDesc srcImgDesc((void *)inImg, numPixels, 1,\n                                           inChans,\n                                           inBD,\n                                           sizeof(inType),\n                                           OCIO::AutoStride,\n                                           OCIO::AutoStride);\n\n    std::vector<outType> out(numValues);\n    OCIO::PackedImageDesc dstImgDesc(&out[0], numPixels, 1,\n                                     outChans,\n                                     outBD,\n                                     sizeof(outType),\n                                     OCIO::AutoStride,\n                                     OCIO::AutoStride);\n\n    OCIO_CHECK_NO_THROW_FROM(cpuProcessor->apply(srcImgDesc, dstImgDesc), line);\n\n    const outType * res = reinterpret_cast<const outType*>(resImg);\n\n    for(size_t idx=0; idx<numValues; ++idx)\n    {\n        if(OCIO::BitDepthInfo<outBD>::isFloat)\n        {\n            OCIO_CHECK_CLOSE_FROM(out[idx], res[idx], absErrorThreshold, line);\n        }\n        else\n        {\n            OCIO_CHECK_EQUAL_FROM(out[idx], res[idx], line);\n        }\n    }\n\n    return cpuProcessor;\n}\n\nOCIO_ADD_TEST(CPUProcessor, with_one_matrix)\n{\n    \/\/ The unit test validates that pixel formats are correctly\n    \/\/ processed when the op list contains only one arbitrary Op\n    \/\/ (except a 1D LUT one which has dedicated optimizations).\n\n    OCIO::ConfigRcPtr config = OCIO::Config::Create();\n\n    OCIO::MatrixTransformRcPtr transform = OCIO::MatrixTransform::Create();\n    constexpr double offset4[4] = { 1.4002, 0.4005, 0.0807, 0.5 };\n    transform->setOffset( offset4 );\n\n    OCIO::ConstProcessorRcPtr processor;\n    OCIO_CHECK_NO_THROW(processor = config->getProcessor(transform));\n\n    constexpr unsigned NB_PIXELS = 3;\n\n    const std::vector<float> f_inImg =\n        {  -1.0000f, -0.8000f, -0.1000f,  0.0f,\n            0.1023f,  0.5045f,  1.5089f,  1.0f,\n            1.0000f,  1.2500f,  1.9900f,  0.0f  };\n\n    {\n        const std::vector<float> resImg\n            = { 0.4002f, -0.3995f, -0.0193f,  0.5000f,\n                1.5025f,  0.9050f,  1.5896f,  1.5000f,\n                2.4002f,  1.6505f,  2.0707f,  0.5000f };\n\n        ComputeValues<OCIO::BIT_DEPTH_F32,\n                      OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                     &f_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                     &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                     NB_PIXELS,\n                                                     1e-5f);\n    }\n\n    {\n        const std::vector<float> resImg\n            = { -0.9193f,   -0.3995f,  1.3002f,  0.5000f,\n                 0.182999f,  0.9050f,  2.9091f,  1.5000f,\n                 1.0807f,    1.6505f,  3.3902f,  0.5000f };\n\n        ComputeValues<OCIO::BIT_DEPTH_F32,\n                      OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                     &f_inImg[0], OCIO::CHANNEL_ORDERING_BGRA,\n                                                     &resImg[0],  OCIO::CHANNEL_ORDERING_BGRA,\n                                                     NB_PIXELS,\n                                                     1e-5f);\n    }\n\n    {\n        const std::vector<float> resImg\n            = {  -0.500000f, -0.719300f, 0.300500f, 1.400200f,\n                  0.602300f,  0.585199f, 1.909399f, 2.400200f,\n                  1.500000f,  1.330700f, 2.390500f, 1.400200f  };\n\n        ComputeValues<OCIO::BIT_DEPTH_F32,\n                      OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                     &f_inImg[0], OCIO::CHANNEL_ORDERING_ABGR,\n                                                     &resImg[0],  OCIO::CHANNEL_ORDERING_ABGR,\n                                                     NB_PIXELS,\n                                                     1e-5f);\n    }\n\n    {\n        const std::vector<float> resImg\n            = { -0.0193f, -0.3995f,  0.4002f,  0.5000f,\n                 1.5896f,  0.9050f,  1.5025f,  1.5000f,\n                 2.0707f,  1.6505f,  2.4002f,  0.5000f };\n\n        ComputeValues<OCIO::BIT_DEPTH_F32,\n                      OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                     &f_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                     &resImg[0],  OCIO::CHANNEL_ORDERING_BGRA,\n                                                     NB_PIXELS,\n                                                     1e-5f);\n    }\n\n    {\n        const std::vector<float> resImg\n            = { 0.5000f, -0.0193f, -0.3995f, 0.4002f,\n                1.5000f,  1.5896f,  0.9050f, 1.5025f,\n                0.5000f,  2.0707f,  1.6505f, 2.4002f  };\n\n        ComputeValues<OCIO::BIT_DEPTH_F32,\n                      OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                     &f_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                     &resImg[0],  OCIO::CHANNEL_ORDERING_ABGR,\n                                                     NB_PIXELS,\n                                                     1e-5f);\n    }\n\n    {\n        const std::vector<float> inImg =\n            {  -1.0000f, -0.8000f, -0.1000f,\n                0.1023f,  0.5045f,  1.5089f,\n                1.0000f,  1.2500f,  1.9900f  };\n\n        const std::vector<float> resImg\n            = { 0.4002f, -0.3995f, -0.0193f,\n                1.5025f,  0.9050f,  1.5896f,\n                2.4002f,  1.6505f,  2.0707f };\n\n        ComputeValues<OCIO::BIT_DEPTH_F32,\n                      OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                     &inImg[0],  OCIO::CHANNEL_ORDERING_RGB,\n                                                     &resImg[0], OCIO::CHANNEL_ORDERING_RGB,\n                                                     NB_PIXELS,\n                                                     1e-5f);\n    }\n\n    {\n        const std::vector<float> inImg =\n            {    -1.0000f,    -0.8000f, -0.1000f,\n                   0.1023f,    0.5045f,  1.5089f,\n                   1.0000f,    1.2500f,  1.9900f  };\n\n        const std::vector<float> resImg\n            = { -0.919300f, -0.399500f,  1.300199f,\n                 0.182999f,  0.905000f,  2.909100f,\n                 1.080700f,  1.650500f,  3.390200f };\n\n        ComputeValues<OCIO::BIT_DEPTH_F32,\n                      OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                     &inImg[0],  OCIO::CHANNEL_ORDERING_BGR,\n                                                     &resImg[0], OCIO::CHANNEL_ORDERING_BGR,\n                                                     NB_PIXELS,\n                                                     1e-5f);\n    }\n\n    {\n        const std::vector<float> inImg =\n            {  -1.0000f, -0.8000f, -0.1000f,\n                0.1023f,  0.5045f,  1.5089f,\n                1.0000f,  1.2500f,  1.9900f  };\n\n        const std::vector<float> resImg\n            = { -0.01929f,  -0.3995f,  0.4002f,\n                 1.58960f,   0.9050f,  1.5025f,\n                 2.070699f,  1.6505f,  2.4002f };\n\n        ComputeValues<OCIO::BIT_DEPTH_F32,\n                      OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                     &inImg[0],  OCIO::CHANNEL_ORDERING_RGB,\n                                                     &resImg[0], OCIO::CHANNEL_ORDERING_BGR,\n                                                     NB_PIXELS,\n                                                     1e-5f);\n    }\n\n    {\n        const std::vector<float> inImg =\n            {  -1.0000f, -0.8000f, -0.1000f,\n                0.1023f,  0.5045f,  1.5089f,\n                1.0000f,  1.2500f,  1.9900f  };\n\n        const std::vector<float> resImg\n            = { -0.01929f,  -0.3995f,  0.4002f, 0.5f,\n                 1.58960f,   0.9050f,  1.5025f, 0.5f,\n                 2.070699f,  1.6505f,  2.4002f, 0.5f   };\n\n        ComputeValues<OCIO::BIT_DEPTH_F32,\n                      OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                     &inImg[0],  OCIO::CHANNEL_ORDERING_RGB,\n                                                     &resImg[0], OCIO::CHANNEL_ORDERING_BGRA,\n                                                     NB_PIXELS,\n                                                     1e-5f);\n    }\n\n    {\n        const std::vector<float> inImg =\n            {  -1.0000f, -0.8000f, -0.1000f,  0.0f,\n                0.1023f,  0.5045f,  1.5089f,  1.0f,\n                1.0000f,  1.2500f,  1.9900f,  0.0f  };\n\n        const std::vector<float> resImg\n            = { -0.01929f,  -0.3995f,  0.4002f,\n                 1.58960f,   0.9050f,  1.5025f,\n                 2.070699f,  1.6505f,  2.4002f   };\n\n        ComputeValues<OCIO::BIT_DEPTH_F32,\n                      OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                     &inImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                     &resImg[0], OCIO::CHANNEL_ORDERING_BGR,\n                                                     NB_PIXELS,\n                                                     1e-5f);\n    }\n\n    const std::vector<uint16_t> ui16_inImg =\n        {    0,      8,    32,  0,\n            64,    128,   256,  0,\n          5120,  20140, 65535,  0  };\n\n    {\n        const std::vector<float> resImg\n            = { 1.40020000f,  0.40062206f,  0.08118829f,  0.5f,\n                1.40117657f,  0.40245315f,  0.08460631f,  0.5f,\n                1.47832620f,  0.70781672f,  1.08070004f,  0.5f };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                     &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                     &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                     NB_PIXELS,\n                                                     1e-5f);\n    }\n\n    {\n        const std::vector<uint16_t> resImg\n            = { 65535, 26255,  5321, 32768,\n                65535, 26375,  5545, 32768,\n                65535, 46387, 65535, 32768 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n    }\n\n    {\n        const std::vector<uint16_t> resImg\n            = {  5321, 26255, 65535, 32768,\n                 5545, 26375, 65535, 32768,\n                65535, 46387, 65535, 32768 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &resImg[0],  OCIO::CHANNEL_ORDERING_BGRA,\n                                                        NB_PIXELS);\n    }\n\n    {\n        const std::vector<uint16_t> resImg\n            = {  5321, 26255, 65535,\n                 5545, 26375, 65535,\n                65535, 46387, 65535 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &resImg[0],  OCIO::CHANNEL_ORDERING_BGR,\n                                                        NB_PIXELS);\n    }\n\n    {\n        const std::vector<uint8_t> resImg\n            = { 255, 102,  21, 128,\n                255, 103,  22, 128,\n                255, 180, 255, 128 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT8, __LINE__>(processor,\n                                                       &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                       &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                       NB_PIXELS);\n    }\n\n    {\n        const std::vector<uint8_t> resImg\n            = {  21, 102, 255,\n                 22, 103, 255,\n                255, 180, 255 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT8, __LINE__>(processor,\n                                                       &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                       &resImg[0],  OCIO::CHANNEL_ORDERING_BGR,\n                                                       NB_PIXELS);\n    }\n\n    {\n        const std::vector<uint8_t> resImg\n            = { 128,  21, 102, 255,\n                128,  22, 103, 255,\n                128, 255, 180, 255 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT8, __LINE__>(processor,\n                                                       &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                       &resImg[0],  OCIO::CHANNEL_ORDERING_ABGR,\n                                                       NB_PIXELS);\n    }\n\n    \/\/ Test OCIO::BIT_DEPTH_UINT10.\n\n    {\n        const std::vector<uint16_t> ui10_resImg\n            = { 1023,  410,   83,  512,\n                1023,  412,   87,  512,\n                1023,  724, 1023,  512 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT10, __LINE__>(processor,\n                                                        &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &ui10_resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n\n        const std::vector<uint16_t> ui10_inImg\n            = {    0,    8,   12,  256,\n                 128,   16,   64,  512,\n                1023,   32,   96,  512 };\n\n        const std::vector<uint16_t> ui16_resImg\n            = { 65535, 26759,  6057, 49167,\n                65535, 27272,  9389, 65535,\n                65535, 28297, 11439, 65535 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT10,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &ui10_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &ui16_resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n    }\n\n    \/\/ Test OCIO::BIT_DEPTH_UINT12.\n\n    {\n        const std::vector<uint16_t> ui12_resImg\n            = { 4095, 1641,  332, 2048,\n                4095, 1648,  346, 2048,\n                4095, 2899, 4095, 2048 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT12, __LINE__>(processor,\n                                                        &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &ui12_resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n\n        const std::vector<uint16_t> ui12_inImg\n            = {     0,    8,    12,   1024,\n                 2048,   16,    64,   2048,\n                 4095,   32,    96,   4095 };\n\n        const std::vector<uint16_t> ui16_resImg\n            = { 65535, 26375,  5481, 49155,\n                65535, 26503,  6313, 65535,\n                65535, 26759,  6825, 65535 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT12,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &ui12_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &ui16_resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n    }\n}\n\nOCIO_ADD_TEST(CPUProcessor, with_one_1d_lut)\n{\n    \/\/ The unit test validates that pixel formats are correctly\n    \/\/ processed when the op list only contains one 1D LUT because it\n    \/\/ has a dedicated optimization when the input bit-depth is an integer type.\n\n    const std::string filePath = OCIO::GetTestFilesDir() + \"\/lut1d_5.spi1d\";\n\n    OCIO::FileTransformRcPtr transform = OCIO::FileTransform::Create();\n    transform->setDirection(OCIO::TRANSFORM_DIR_FORWARD);\n    transform->setSrc(filePath.c_str());\n    transform->setInterpolation(OCIO::INTERP_LINEAR);\n\n    OCIO::ConfigRcPtr config = OCIO::Config::Create();\n\n    OCIO::ConstProcessorRcPtr processor;\n    OCIO_CHECK_NO_THROW(processor = config->getProcessor(transform));\n\n    constexpr unsigned NB_PIXELS = 4;\n\n    const std::vector<float> f_inImg =\n        {  -1.0000f, -0.8000f, -0.1000f,  0.0f,\n            0.1002f,  0.2509f,  0.5009f,  1.0f,\n            0.5505f,  0.7090f,  0.9099f,  1.0f,\n            1.0000f,  1.2500f,  1.9900f,  0.0f  };\n\n    {\n        const std::vector<float> resImg\n            = {  0,            0,            0,            0,\n                 0.03728949f,  0.10394855f,  0.24695572f,  1,\n                 0.29089212f,  0.50935059f,  1.91091322f,  1,\n                64,           64,           64,            0 };\n\n        ComputeValues<OCIO::BIT_DEPTH_F32,\n                      OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                     &f_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                     &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                     NB_PIXELS,\n                                                     1e-7f);\n    }\n\n    {\n        const std::vector<uint16_t> resImg\n            = {     0,     0,     0,     0,\n                 2444,  6812, 16184, 65535,\n                19064, 33380, 65535, 65535,\n                65535, 65535, 65535,     0 };\n\n        ComputeValues<OCIO::BIT_DEPTH_F32,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &f_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n    }\n\n    const std::vector<uint16_t> ui16_inImg =\n        {    0,      8,    32,     0,\n            64,    128,   256,    32,\n           512,   1024,  2048,    64,\n          5120,  20480, 65535,   512 };\n\n    {\n        const std::vector<float> resImg\n            = {  0,           0.00036166f, 0.00144666f, 0,\n                 0.00187417f, 0.00271759f, 0.00408672f, 0.00048828f,\n                 0.00601041f, 0.00912247f, 0.01456576f, 0.00097657f,\n                 0.03030112f, 0.13105739f, 64,          0.00781261f };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                     &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                     &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                     NB_PIXELS, 1e-7f);\n    }\n\n    {\n        const std::vector<uint16_t> resImg\n            = {     0,    24,    95,     0,\n                  123,   178,   268,    32,\n                  394,   598,   955,    64,\n                 1986,  8589, 65535,   512 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n    }\n\n    {\n        const std::vector<uint16_t> resImg\n            = {    95,    24,     0,     0,\n                  268,   178,   123,    32,\n                  955,   598,   394,    64,\n                65535,  8589,  1986,   512 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &ui16_inImg[0], OCIO::CHANNEL_ORDERING_BGRA,\n                                                        &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n    }\n\n    {\n        const std::vector<uint16_t> resImg\n            = {    95,    24,     0,     0,\n                  268,   178,   123,    32,\n                  955,   598,   394,    64,\n                65535,  8589,  1986,   512 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &resImg[0],  OCIO::CHANNEL_ORDERING_BGRA,\n                                                        NB_PIXELS);\n    }\n\n    {\n        const std::vector<uint16_t> resImg\n            = {    95,    24,     0,\n                  268,   178,   123,\n                  955,   598,   394,\n                65535,  8589,  1986 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &resImg[0],  OCIO::CHANNEL_ORDERING_BGR,\n                                                        NB_PIXELS);\n    }\n\n    {\n        const std::vector<uint16_t> resImg\n            = {     0,    24,    95,     0,\n                  123,   178,   268,    32,\n                  394,   598,   955,    64,\n                 1986,  8589, 65535,    512 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &ui16_inImg[0], OCIO::CHANNEL_ORDERING_BGRA,\n                                                        &resImg[0],  OCIO::CHANNEL_ORDERING_BGRA,\n                                                        NB_PIXELS);\n    }\n\n    {\n        const std::vector<uint16_t> my_i_inImg =\n            {    0,      8,    32,\n                64,    128,   256,\n               512,   1024,  2048,\n              5120,  20480, 65535  };\n\n        const std::vector<uint16_t> resImg\n            = {    95,    24,     0,     0,\n                  268,   178,   123,     0,\n                  955,   598,   394,     0,\n                65535,  8589,  1986,     0 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &my_i_inImg[0], OCIO::CHANNEL_ORDERING_RGB,\n                                                        &resImg[0],  OCIO::CHANNEL_ORDERING_BGRA,\n                                                        NB_PIXELS);\n    }\n\n    \/\/ Test OCIO::BIT_DEPTH_UINT10.\n\n    {\n        const std::vector<uint16_t> ui10_resImg\n            = {     0,     0,     1,     0,\n                    2,     3,     4,     0,\n                    6,     9,    15,     1,\n                   31,   134,  1023,     8 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT10, __LINE__>(processor,\n                                                        &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &ui10_resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n    }\n\n    {\n        const std::vector<uint16_t> ui10_inImg\n            = {     0,     8,    32,\n                   64,   128,   256,\n                   96,   256,   512,\n                  128,  1023,   640  };\n\n        const std::vector<uint16_t> ui10_resImg\n            = {     0,     6,    15,   0,\n                   26,    48,   106,   0,\n                   36,   106,   252,   0,\n                   48,  1023,   384,   0 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT10,\n                      OCIO::BIT_DEPTH_UINT10, __LINE__>(processor,\n                                                        &ui10_inImg[0], OCIO::CHANNEL_ORDERING_RGB,\n                                                        &ui10_resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n\n        const std::vector<uint16_t> ui16_resImg\n            = {     0,   394,   955,   0,\n                 1656,  3092,  6794,   0,\n                 2301,  6794, 16162,   0,\n                 3092, 65535, 24593,   0 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT10,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &ui10_inImg[0], OCIO::CHANNEL_ORDERING_RGB,\n                                                        &ui16_resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n    }\n\n    \/\/ Test OCIO::BIT_DEPTH_UINT12.\n\n    {\n        const std::vector<uint16_t> ui12_resImg\n            = {     0,     1,     6,     0,\n                    8,    11,    17,     2,\n                   25,    37,    60,     4,\n                  124,   537,  4095,    32 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                      OCIO::BIT_DEPTH_UINT12, __LINE__>(processor,\n                                                        &ui16_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &ui12_resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n    }\n\n    {\n        const std::vector<uint16_t> ui12_inImg\n            = {     0,     8,    32,\n                   64,   128,   256,\n                   96,   256,   512,\n                 1024,  2048,  4095  };\n\n        const std::vector<uint16_t> ui12_resImg\n            = {     0,    11,    25,   0,\n                   37,    60,   103,   0,\n                   49,   103,   193,   0,\n                  424,  1009,  4095,   0 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT12,\n                      OCIO::BIT_DEPTH_UINT12, __LINE__>(processor,\n                                                        &ui12_inImg[0], OCIO::CHANNEL_ORDERING_RGB,\n                                                        &ui12_resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n        const std::vector<uint16_t> ui16_resImg\n            = {     0,   178,   394,   0,\n                  598,   955,  1655,   0,\n                  779,  1655,  3089,   0,\n                 6789, 16143, 65535,   0 };\n\n        ComputeValues<OCIO::BIT_DEPTH_UINT12,\n                      OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                        &ui12_inImg[0], OCIO::CHANNEL_ORDERING_RGB,\n                                                        &ui16_resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS);\n    }\n\n}\n\nOCIO_ADD_TEST(CPUProcessor, with_several_ops)\n{\n    \/\/ The unit test validates that pixel formats are correctly\n    \/\/ processed when the op list starts or ends with a 1D LUT because it\n    \/\/ has a dedicated optimization when the input bit-depth is an integer type.\n\n    const std::string SIMPLE_PROFILE =\n        \"ocio_profile_version: 2\\n\"\n        \"\\n\"\n        \"search_path: \" + OCIO::GetTestFilesDir() + \"\\n\"\n        \"strictparsing: true\\n\"\n        \"luma: [0.2126, 0.7152, 0.0722]\\n\"\n        \"\\n\"\n        \"roles:\\n\"\n        \"  default: cs1\\n\"\n        \"  scene_linear: cs2\\n\"\n        \"\\n\"\n        \"displays:\\n\"\n        \"  sRGB:\\n\"\n        \"    - !<View> {name: Raw, colorspace: cs1}\\n\"\n        \"\\n\"\n        \"colorspaces:\\n\"\n        \"  - !<ColorSpace>\\n\"\n        \"    name: cs1\\n\"\n        \"    allocation: uniform\\n\"\n        \"\\n\"\n        \"  - !<ColorSpace>\\n\"\n        \"    name: cs2\\n\"\n        \"    allocation: uniform\\n\";\n\n    \/\/ Step 1: The 1D LUT is the last Op.\n\n    {\n        const std::string strEnd =\n            \"    from_reference: !<GroupTransform>\\n\"\n            \"      children:\\n\"\n            \"        - !<MatrixTransform> { offset: [-0.19, 0.19, -0.00019, 0] }\\n\"\n            \"        - !<FileTransform>   { src: lut1d_5.spi1d, interpolation: linear }\\n\";\n\n        const std::string str = SIMPLE_PROFILE + strEnd;\n\n        std::istringstream is;\n        is.str(str);\n\n        OCIO::ConstConfigRcPtr config;\n        OCIO_CHECK_NO_THROW(config = OCIO::Config::CreateFromStream(is));\n        OCIO_CHECK_NO_THROW(config->validate());\n\n        OCIO::ConstProcessorRcPtr processor;\n        OCIO_CHECK_NO_THROW(processor = config->getProcessor(\"cs1\", \"cs2\"));\n\n        constexpr unsigned NB_PIXELS = 4;\n\n        const std::vector<float> f_inImg =\n            {  -1.0000f, -0.8000f, -0.1000f,  0.0f,\n                0.1002f,  0.2509f,  0.5009f,  1.0f,\n                0.5505f,  0.7090f,  0.9099f,  1.0f,\n                1.0000f,  1.2500f,  1.9900f,  0.0f  };\n\n        {\n            const std::vector<float> resImg\n                = {  0.0f,         0.0f,         0.0f,         0.0f,\n                     0.0f,         0.20273837f,  0.24680146f,  1.0f,\n                     0.15488569f,  1.69210147f,  1.90666747f,  1.0f,\n                     0.81575858f, 64.0f,        64.0f,         0.0f };\n\n            ComputeValues<OCIO::BIT_DEPTH_F32,\n                          OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                         &f_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                         &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                         NB_PIXELS, 1e-7f);\n        }\n\n        {\n            const std::vector<uint16_t> resImg\n                = {     0,     0,     0,     0,\n                        0, 13286, 16174, 65535,\n                    10150, 65535, 65535, 65535,\n                    53461, 65535, 65535,     0 };\n\n            ComputeValues<OCIO::BIT_DEPTH_F32,\n                          OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                            &f_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                            &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                            NB_PIXELS);\n        }\n\n        const std::vector<uint16_t> i_inImg =\n            {    0,      8,    32,  0,\n                64,    128,   256,  65535,\n               512,   1024,  2048,  0,\n              5120,  20480, 65535,  65535  };\n\n        {\n            const std::vector<float> resImg\n                = {  0.0f,  0.07789713f,  0.00088374f,  0.0f,\n                     0.0f,  0.07871927f,  0.00396248f,  1.0f,\n                     0.0f,  0.08474064f,  0.01450117f,  0.0f,\n                     0.0f,  0.24826171f, 56.39490891f,  1.0f };\n\n            auto cpuProcessor = ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                                              OCIO::BIT_DEPTH_F32,\n                                              __LINE__>(processor,\n                                                        &i_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                        &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                        NB_PIXELS, 1e-7f);\n\n            const std::string cacheID{ cpuProcessor->getCacheID() };\n\n            const std::string expectedID(\"CPU Processor: from 16ui to 32f oFlags 263995331 ops\"\n                \": <Lut1D $a57d7444e629d796d2234c18a0539c74 forward default standard domain none>\");\n\n            \/\/ Test integer optimization. The ops should be optimized into a single LUT\n            \/\/ when finalizing with an integer input bit-depth.\n            OCIO_CHECK_EQUAL(cacheID, expectedID);\n        }\n\n        {\n            const std::vector<uint16_t> resImg\n                = {     0,  5105,    58,     0,\n                        0,  5159,   260,     65535,\n                        0,  5553,   950,     0,\n                        0, 16270, 65535,     65535 };\n\n            ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                          OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                            &i_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                            &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                            NB_PIXELS);\n        }\n\n        {\n            const std::vector<uint16_t> resImg\n                = {     0,  5105,     0,     0,\n                        0,  5159,   112,     65535,\n                        0,  5553,   388,     0,\n                    53461, 16270,  1982,     65535 };\n\n            ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                          OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                            &i_inImg[0], OCIO::CHANNEL_ORDERING_BGRA,\n                                                            &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                            NB_PIXELS);\n        }\n\n        {\n            const std::vector<uint16_t> resImg\n                = {    58,  5105,     0,     0,\n                      260,  5159,     0,     65535,\n                      950,  5553,     0,     0,\n                    65535, 16270,     0,     65535 };\n\n            ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                          OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                            &i_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                            &resImg[0],  OCIO::CHANNEL_ORDERING_BGRA,\n                                                            NB_PIXELS);\n        }\n\n        {\n            const std::vector<uint16_t> resImg\n                = {     0,  5105,     0,     0,\n                      112,  5159,     0,     65535,\n                      388,  5553,     0,     0,\n                     1982, 16270, 53461,     65535 };\n\n            ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                          OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                            &i_inImg[0], OCIO::CHANNEL_ORDERING_BGRA,\n                                                            &resImg[0],  OCIO::CHANNEL_ORDERING_BGRA,\n                                                            NB_PIXELS);\n        }\n    }\n\n    \/\/ Step 2: The 1D LUT is the first Op.\n\n    {\n        const std::string strEnd =\n            \"    from_reference: !<GroupTransform>\\n\"\n            \"      children:\\n\"\n            \"        - !<FileTransform>   { src: lut1d_5.spi1d, interpolation: linear }\\n\"\n            \"        - !<MatrixTransform> { offset: [-0.19, 0.19, -0.00019, 0] }\\n\";\n\n        const std::string str = SIMPLE_PROFILE + strEnd;\n\n        std::istringstream is;\n        is.str(str);\n\n        OCIO::ConstConfigRcPtr config;\n        OCIO_CHECK_NO_THROW(config = OCIO::Config::CreateFromStream(is));\n        OCIO_CHECK_NO_THROW(config->validate());\n\n        OCIO::ConstProcessorRcPtr processor;\n        OCIO_CHECK_NO_THROW(processor = config->getProcessor(\"cs1\", \"cs2\"));\n\n        const unsigned NB_PIXELS = 4;\n\n        const std::vector<float> f_inImg =\n            {  -1.0000f, -0.8000f, -0.1000f,  0.0f,\n                0.1002f,  0.2509f,  0.5009f,  1.0f,\n                0.5505f,  0.7090f,  0.9099f,  1.0f,\n                1.0000f,  1.2500f,  1.9900f,  0.0f  };\n\n        {\n            const std::vector<float> resImg\n                = { -0.18999999f,  0.18999999f, -0.00019000f,  0.0f,\n                    -0.15271049f,  0.29394856f,  0.24676571f,  1.0f,\n                     0.10089212f,  0.69935059f,  1.91072320f,  1.0f,\n                    63.81000137f, 64.19000244f, 63.99980927f,  0.0f };\n\n            ComputeValues<OCIO::BIT_DEPTH_F32,\n                          OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                         &f_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                         &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                         NB_PIXELS, 1e-7f);\n        }\n\n        {\n            const std::vector<uint16_t> resImg\n                = {     0, 12452,     0,     0,\n                        0, 19264, 16172, 65535,\n                     6612, 45832, 65535, 65535,\n                    65535, 65535, 65535,     0 };\n\n            ComputeValues<OCIO::BIT_DEPTH_F32,\n                          OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                            &f_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                            &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                            NB_PIXELS);\n        }\n\n        const std::vector<uint16_t> i_inImg =\n            {    0,      8,    32,  0,\n                64,    128,   256,  0,\n               512,   1024,  2048,  0,\n              5120,  20480, 65535,  0  };\n        {\n            const std::vector<float> resImg\n                = { -0.18999999f, 0.19036166f,  0.00125666f,  0.0f,\n                    -0.18812581f, 0.19271758f,  0.00389672f,  0.0f,\n                    -0.18398958f, 0.19912247f,  0.01437576f,  0.0f,\n                    -0.15969887f, 0.32105737f, 63.99980927f,  0.0f };\n\n            ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                          OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                         &i_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                         &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                         NB_PIXELS, 1e-7f);\n        }\n\n        {\n            const std::vector<uint16_t> resImg\n                = {     0, 12475,     0,     0,\n                      110, 12630,     0,     0,\n                      381, 13049,     0,     0,\n                     1973, 21040, 65535,     0 };\n\n            ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                          OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                            &i_inImg[0], OCIO::CHANNEL_ORDERING_BGRA,\n                                                            &resImg[0],  OCIO::CHANNEL_ORDERING_BGRA,\n                                                            NB_PIXELS);\n        }\n    }\n\n    \/\/ Step 3: The 1D LUT is the first and the last Op.\n\n    {\n\n        const std::string strEnd =\n            \"    from_reference: !<GroupTransform>\\n\"\n            \"      children:\\n\"\n            \"        - !<FileTransform>   { src: lut1d_5.spi1d, interpolation: linear }\\n\"\n            \"        - !<MatrixTransform> { offset: [-0.19, 0.19, -0.00019, 0] }\\n\"\n            \"        - !<FileTransform>   { src: lut1d_4.spi1d, interpolation: linear }\\n\";\n\n        const std::string str = SIMPLE_PROFILE + strEnd;\n\n        std::istringstream is;\n        is.str(str);\n\n        OCIO::ConstConfigRcPtr config;\n        OCIO_CHECK_NO_THROW(config = OCIO::Config::CreateFromStream(is));\n        OCIO_CHECK_NO_THROW(config->validate());\n\n        OCIO::ConstProcessorRcPtr processor;\n        OCIO_CHECK_NO_THROW(processor = config->getProcessor(\"cs1\", \"cs2\"));\n\n        const unsigned NB_PIXELS = 4;\n\n        const std::vector<float> f_inImg =\n            {  -1.0000f, -0.8000f, -0.1000f,  0.0f,\n                0.1002f,  0.2509f,  0.5009f,  1.0f,\n                0.5505f,  0.7090f,  0.9099f,  1.0f,\n                1.0000f,  1.2500f,  1.9900f,  0.0f  };\n\n        {\n            const std::vector<float> resImg\n                = { -0.79690927f, -0.06224250f, -0.42994320f,  0.0f,\n                    -0.72481626f,  0.13872468f,  0.04750441f,  1.0f,\n                    -0.23451784f,  0.92250210f,  3.26448941f,  1.0f,\n                     3.43709063f,  3.43709063f,  3.43709063f,  0.0f };\n\n            ComputeValues<OCIO::BIT_DEPTH_F32,\n                          OCIO::BIT_DEPTH_F32, __LINE__>(processor,\n                                                         &f_inImg[0], OCIO::CHANNEL_ORDERING_RGBA,\n                                                         &resImg[0],  OCIO::CHANNEL_ORDERING_RGBA,\n                                                         NB_PIXELS, 1e-7f);\n        }\n\n        const std::vector<uint16_t> i_inImg =\n            {    0,      8,    32,  0,\n                64,    128,   256,  0,\n               512,   1024,  2048,  0,\n              5120,  20480, 65535,  0  };\n\n        {\n            const std::vector<uint16_t> resImg\n                = {     0,     0,     0,     0,\n                        0,     0,     0,     0,\n                        0,     0,     0,     0,\n                        0, 12526, 65535,     0 };\n\n            ComputeValues<OCIO::BIT_DEPTH_UINT16,\n                          OCIO::BIT_DEPTH_UINT16, __LINE__>(processor,\n                                                            &i_inImg[0], OCIO::CHANNEL_ORDERING_BGRA,\n                                                            &resImg[0],  OCIO::CHANNEL_ORDERING_BGRA,\n                                                            NB_PIXELS);\n        }\n    }\n}\n\nOCIO_ADD_TEST(CPUProcessor, image_desc)\n{\n    \/\/ The tests validate the image description types when using the same buffer image.\n\n    const std::string SIMPLE_PROFILE =\n        \"ocio_profile_version: 2\\n\"\n        \"\\n\"\n        \"search_path: \" + OCIO::GetTestFilesDir() + \"\\n\"\n        \"strictparsing: true\\n\"\n        \"luma: [0.2126, 0.7152, 0.0722]\\n\"\n        \"\\n\"\n        \"roles:\\n\"\n        \"  default: cs1\\n\"\n        \"  scene_linear: cs2\\n\"\n        \"\\n\"\n        \"displays:\\n\"\n        \"  sRGB:\\n\"\n        \"    - !<View> {name: Raw, colorspace: cs1}\\n\"\n        \"\\n\"\n        \"colorspaces:\\n\"\n        \"  - !<ColorSpace>\\n\"\n        \"    name: cs1\\n\"\n        \"    allocation: uniform\\n\"\n        \"\\n\"\n        \"  - !<ColorSpace>\\n\"\n        \"    name: cs2\\n\"\n        \"    allocation: uniform\\n\";\n\n    const std::string strEnd =\n        \"    from_reference: !<GroupTransform>\\n\"\n        \"      children:\\n\"\n        \"        - !<MatrixTransform> { offset: [-0.19, 0.19, -0.00019, 0.5] }\\n\"\n        \"        - !<FileTransform>   { src: lut1d_5.spi1d, interpolation: linear }\\n\";\n\n    const std::string str = SIMPLE_PROFILE + strEnd;\n\n    std::istringstream is;\n    is.str(str);\n\n    OCIO::ConstConfigRcPtr config;\n    OCIO_CHECK_NO_THROW(config = OCIO::Config::CreateFromStream(is));\n    OCIO_CHECK_NO_THROW(config->validate());\n\n    OCIO::ConstProcessorRcPtr processor;\n    OCIO_CHECK_NO_THROW(processor = config->getProcessor(\"cs1\", \"cs2\"));\n\n    const std::vector<float> f_rInImg =\n        {  -1.0000f,\n            0.1002f,\n            0.5505f,\n            1.0000f,  };\n\n    const std::vector<float> f_gInImg =\n        {            -0.8000f,\n                      0.2509f,\n                      0.7090f,\n                      1.2500f  };\n\n    const std::vector<float> f_bInImg =\n        {                       -0.1000f,\n                                 0.5009f,\n                                 0.9099f,\n                                 1.9900f  };\n\n    const std::vector<float> f_aInImg =\n        {                                   0.0f,\n                                            1.0f,\n                                            0.5f,\n                                            0.0f  };\n\n    const std::vector<float> f_rOutImg\n        = {  0.0f,\n             0.0f,\n             0.15488569f,\n             0.81575858f };\n\n    const std::vector<float> f_gOutImg\n        = {                0.0f,\n                           0.20273837f,\n                           1.69210147f,\n                          64.0f };\n\n    const std::vector<float> f_bOutImg\n        = {                              0.0f,\n                                         0.24680146f,\n                                         1.90666747f,\n                                        64.0f };\n\n    const std::vector<float> f_aOutImg\n        = {                                            0.5f,\n                                                       1.5f,\n                                                       1.0f,\n                                                       0.5f };\n\n    {\n        \/\/ Packed Image Description with RGBA image.\n\n        std::vector<float> img =\n            {  f_rInImg[0], f_gInImg[0], f_bInImg[0], f_aInImg[0],\n               f_rInImg[1], f_gInImg[1], f_bInImg[1], f_aInImg[1],\n               f_rInImg[2], f_gInImg[2], f_bInImg[2], f_aInImg[2],\n               f_rInImg[3], f_gInImg[3], f_bInImg[3], f_aInImg[3] };\n\n        const std::vector<float> res\n            {  f_rOutImg[0], f_gOutImg[0], f_bOutImg[0], f_aOutImg[0],\n               f_rOutImg[1], f_gOutImg[1], f_bOutImg[1], f_aOutImg[1],\n               f_rOutImg[2], f_gOutImg[2], f_bOutImg[2], f_aOutImg[2],\n               f_rOutImg[3], f_gOutImg[3], f_bOutImg[3], f_aOutImg[3] };\n\n        OCIO::ConstCPUProcessorRcPtr cpu;\n        OCIO_CHECK_NO_THROW(cpu = processor->getDefaultCPUProcessor());\n\n        OCIO::PackedImageDesc desc(&img[0], 2, 2, 4);\n        OCIO_CHECK_NO_THROW(cpu->apply(desc));\n\n        for(size_t idx=0; idx<img.size(); ++idx)\n        {\n            OCIO_CHECK_CLOSE(img[idx], res[idx], 1e-7f);\n        }\n    }\n\n    {\n        \/\/ Packed Image Description with RGB image.\n\n        std::vector<float> img =\n            {  f_rInImg[0], f_gInImg[0], f_bInImg[0],\n               f_rInImg[1], f_gInImg[1], f_bInImg[1],\n               f_rInImg[2], f_gInImg[2], f_bInImg[2],\n               f_rInImg[3], f_gInImg[3], f_bInImg[3] };\n\n        const std::vector<float> res\n            {  f_rOutImg[0], f_gOutImg[0], f_bOutImg[0],\n               f_rOutImg[1], f_gOutImg[1], f_bOutImg[1],\n               f_rOutImg[2], f_gOutImg[2], f_bOutImg[2],\n               f_rOutImg[3], f_gOutImg[3], f_bOutImg[3] };\n\n        OCIO::ConstCPUProcessorRcPtr cpu;\n        OCIO_CHECK_NO_THROW(cpu = processor->getDefaultCPUProcessor());\n\n        OCIO::PackedImageDesc desc(&img[0], 4, 1, 3);\n        OCIO_CHECK_NO_THROW(cpu->apply(desc));\n\n        for(size_t idx=0; idx<img.size(); ++idx)\n        {\n            OCIO_CHECK_CLOSE(img[idx], res[idx], 1e-7f);\n        }\n    }\n\n    {\n        \/\/ Planar Image Description with R\/G\/B\/A.\n\n        std::vector<float> imgRed   = f_rInImg;\n        std::vector<float> imgGreen = f_gInImg;\n        std::vector<float> imgBlue  = f_bInImg;\n        std::vector<float> imgAlpha = f_aInImg;\n\n        OCIO::ConstCPUProcessorRcPtr cpu;\n        OCIO_CHECK_NO_THROW(cpu = processor->getDefaultCPUProcessor());\n\n        OCIO::PlanarImageDesc desc(&imgRed[0], &imgGreen[0], &imgBlue[0], &imgAlpha[0], 2, 2);\n        OCIO_CHECK_NO_THROW(cpu->apply(desc));\n\n        for(size_t idx=0; idx<imgRed.size(); ++idx)\n        {\n            OCIO_CHECK_CLOSE(imgRed[idx],   f_rOutImg[idx], 1e-7f);\n            OCIO_CHECK_CLOSE(imgGreen[idx], f_gOutImg[idx], 1e-7f);\n            OCIO_CHECK_CLOSE(imgBlue[idx],  f_bOutImg[idx], 1e-7f);\n            OCIO_CHECK_CLOSE(imgAlpha[idx], f_aOutImg[idx], 1e-7f);\n        }\n    }\n\n    {\n        \/\/ Planar Image Description with R\/G\/B.\n\n        std::vector<float> imgRed   = f_rInImg;\n        std::vector<float> imgGreen = f_gInImg;\n        std::vector<float> imgBlue  = f_bInImg;\n\n        OCIO::ConstCPUProcessorRcPtr cpu;\n        OCIO_CHECK_NO_THROW(cpu = processor->getDefaultCPUProcessor());\n\n        OCIO::PlanarImageDesc desc(&imgRed[0], &imgGreen[0], &imgBlue[0], nullptr, 1, 4);\n        OCIO_CHECK_NO_THROW(cpu->apply(desc));\n\n        for(size_t idx=0; idx<imgRed.size(); ++idx)\n        {\n            OCIO_CHECK_CLOSE(imgRed[idx],   f_rOutImg[idx], 1e-7f);\n            OCIO_CHECK_CLOSE(imgGreen[idx], f_gOutImg[idx], 1e-7f);\n            OCIO_CHECK_CLOSE(imgBlue[idx],  f_bOutImg[idx], 1e-7f);\n        }\n    }\n}\n\nnamespace\n{\n\nconstexpr unsigned NB_PIXELS = 6;\n\nstd::vector<float> inImgR =\n    {  -1.000012f,\n       -0.500012f,\n        0.100012f,\n        0.600012f,\n        1.102312f,\n        1.700012f  };\n\nstd::vector<float> inImgG =\n    {              -0.800012f,\n                   -0.300012f,\n                    0.250012f,\n                    0.800012f,\n                    1.204512f,\n                    1.800012f };\n\nstd::vector<float> inImgB =\n    {                          -0.600012f,\n                               -0.100012f,\n                                0.450012f,\n                                0.900012f,\n                                1.508912f,\n                                1.990012f };\n\nstd::vector<float> inImgA =\n    {                                       0.005005f,\n                                            0.405005f,\n                                            0.905005f,\n                                            0.005005f,\n                                            1.005005f,\n                                            0.095005f  };\n\nstd::vector<float> inImg =\n    { inImgR[0], inImgG[0], inImgB[0], inImgA[0],\n      inImgR[1], inImgG[1], inImgB[1], inImgA[1],\n      inImgR[2], inImgG[2], inImgB[2], inImgA[2],\n      inImgR[3], inImgG[3], inImgB[3], inImgA[3],\n      inImgR[4], inImgG[4], inImgB[4], inImgA[4],\n      inImgR[5], inImgG[5], inImgB[5], inImgA[5] };\n\nconst std::vector<float> resImgR =\n    {  0.4001879692f,\n       0.9001880288f,\n       1.500211954f,\n       2.000211954f,\n       2.502511978f,\n       3.100212097f };\n\nconst std::vector<float> resImgG =\n    {                 -0.3995119929f,\n                       0.1004880071f,\n                       0.6505119801f,\n                       1.200511932f,\n                       1.60501194f,\n                       2.200511932f };\n\nconst std::vector<float> resImgB =\n    {                                 0.2006880045f,\n                                      0.7006880045f,\n                                      1.250712037f,\n                                      1.700711966f,\n                                      2.309612036f,\n                                      2.790712118f };\n\nconst std::vector<float> resImgA =\n    {                                                0.5057050f,\n                                                     0.9057050f,\n                                                     1.4057050f,\n                                                     0.5057050f,\n                                                     1.5057050f,\n                                                     0.5957050f  };\n\nconst std::vector<float> resImg =\n    { resImgR[0], resImgG[0], resImgB[0], resImgA[0],\n      resImgR[1], resImgG[1], resImgB[1], resImgA[1],\n      resImgR[2], resImgG[2], resImgB[2], resImgA[2],\n      resImgR[3], resImgG[3], resImgB[3], resImgA[3],\n      resImgR[4], resImgG[4], resImgB[4], resImgA[4],\n      resImgR[5], resImgG[5], resImgB[5], resImgA[5] };\n\n\nOCIO::ConstCPUProcessorRcPtr BuildCPUProcessor(OCIO::TransformDirection dir)\n{\n    OCIO::ConfigRcPtr config = OCIO::Config::Create();\n\n    OCIO::MatrixTransformRcPtr transform = OCIO::MatrixTransform::Create();\n    constexpr double offset4[4] = { 1.4002, 0.4005, 0.8007, 0.5007 };\n    transform->setOffset(offset4);\n    transform->setDirection(dir);\n\n    OCIO::ConstProcessorRcPtr processor = config->getProcessor(transform);\n    return processor->getDefaultCPUProcessor();\n}\n\nvoid Validate(const OCIO::PackedImageDesc & imgDesc, unsigned lineNo)\n{\n    const float * outImg = reinterpret_cast<float*>(imgDesc.getData());\n    for(size_t pxl=0; pxl<NB_PIXELS; ++pxl)\n    {\n        OCIO_CHECK_CLOSE_FROM(outImg[4*pxl+0], resImg[4*pxl+0], 1e-7f, lineNo);\n        OCIO_CHECK_CLOSE_FROM(outImg[4*pxl+1], resImg[4*pxl+1], 1e-7f, lineNo);\n        OCIO_CHECK_CLOSE_FROM(outImg[4*pxl+2], resImg[4*pxl+2], 1e-7f, lineNo);\n        OCIO_CHECK_CLOSE_FROM(outImg[4*pxl+3], resImg[4*pxl+3], 1e-7f, lineNo);\n    }\n}\n\nvoid Process(const OCIO::ConstCPUProcessorRcPtr & cpuProcessor,\n             const OCIO::PackedImageDesc & srcImgDesc,\n             OCIO::PackedImageDesc & dstImgDesc,\n             unsigned lineNo)\n{\n    OCIO_CHECK_NO_THROW_FROM(cpuProcessor->apply(srcImgDesc, dstImgDesc), lineNo);\n    Validate(dstImgDesc, lineNo);\n}\n\nvoid Process(const OCIO::ConstCPUProcessorRcPtr & cpuProcessor,\n             OCIO::PackedImageDesc & imgDesc,\n             unsigned lineNo)\n{\n    OCIO_CHECK_NO_THROW_FROM(cpuProcessor->apply(imgDesc), lineNo);\n    Validate(imgDesc, lineNo);\n}\n\nvoid Process(const OCIO::ConstCPUProcessorRcPtr & cpuProcessor,\n             const OCIO::PlanarImageDesc & srcImgDesc,\n             OCIO::PlanarImageDesc & dstImgDesc,\n             unsigned lineNo)\n{\n    OCIO_CHECK_NO_THROW_FROM(cpuProcessor->apply(srcImgDesc, dstImgDesc), lineNo);\n\n    const float * outImgR = reinterpret_cast<float*>(dstImgDesc.getRData());\n    const float * outImgG = reinterpret_cast<float*>(dstImgDesc.getGData());\n    const float * outImgB = reinterpret_cast<float*>(dstImgDesc.getBData());\n    const float * outImgA = reinterpret_cast<float*>(dstImgDesc.getAData());\n\n    for(size_t pxl=0; pxl<NB_PIXELS; ++pxl)\n    {\n        OCIO_CHECK_CLOSE_FROM(outImgR[pxl], resImg[4*pxl+0], 1e-7f, lineNo);\n        OCIO_CHECK_CLOSE_FROM(outImgG[pxl], resImg[4*pxl+1], 1e-7f, lineNo);\n        OCIO_CHECK_CLOSE_FROM(outImgB[pxl], resImg[4*pxl+2], 1e-7f, lineNo);\n        if(outImgA)\n        {\n            OCIO_CHECK_CLOSE_FROM(outImgA[pxl], resImg[4*pxl+3], 1e-7f, lineNo);\n        }\n    }\n}\n\n} \/\/ anon\n\n\nOCIO_ADD_TEST(CPUProcessor, planar_vs_packed)\n{\n    \/\/ The unit test validates different types for input and output imageDesc.\n\n    OCIO::ConstCPUProcessorRcPtr cpuProcessor;\n    OCIO_CHECK_NO_THROW(cpuProcessor = BuildCPUProcessor(OCIO::TRANSFORM_DIR_FORWARD));\n\n    \/\/ 1. Process from Packed to Planar Image Desc using the forward transform.\n\n    OCIO::PackedImageDesc srcImgDesc((void*)&inImg[0], NB_PIXELS, 1, 4);\n\n    std::vector<float> outR(NB_PIXELS), outG(NB_PIXELS), outB(NB_PIXELS), outA(NB_PIXELS);\n    OCIO::PlanarImageDesc dstImgDesc((void*)&outR[0], (void*)&outG[0],\n                                     (void*)&outB[0], (void*)&outA[0],\n                                     NB_PIXELS, 1);\n\n    OCIO_CHECK_NO_THROW(cpuProcessor->apply(srcImgDesc, dstImgDesc));\n\n    for(size_t idx=0; idx<NB_PIXELS; ++idx)\n    {\n        OCIO_CHECK_CLOSE(outR[idx], resImg[4*idx+0], 1e-7f);\n        OCIO_CHECK_CLOSE(outG[idx], resImg[4*idx+1], 1e-7f);\n        OCIO_CHECK_CLOSE(outB[idx], resImg[4*idx+2], 1e-7f);\n        OCIO_CHECK_CLOSE(outA[idx], resImg[4*idx+3], 1e-7f);\n    }\n\n    \/\/ 2. Process from Planar to Packed Image Desc using the inverse transform.\n\n    OCIO_CHECK_NO_THROW(cpuProcessor = BuildCPUProcessor(OCIO::TRANSFORM_DIR_INVERSE));\n\n    std::vector<float> outImg(NB_PIXELS*4, -1.0f);\n    OCIO::PackedImageDesc dstImgDesc2((void*)&outImg[0], NB_PIXELS, 1, 4);\n\n    OCIO_CHECK_NO_THROW(cpuProcessor->apply(dstImgDesc, dstImgDesc2));\n\n    for(size_t idx=0; idx<(NB_PIXELS*4); ++idx)\n    {\n        OCIO_CHECK_CLOSE(outImg[idx], inImg[idx], 1e-6f);\n    }\n}\n\nOCIO_ADD_TEST(CPUProcessor, scanline_helper_packed)\n{\n    \/\/ Test the packed image description.\n\n    OCIO::ConstCPUProcessorRcPtr cpuProcessor;\n    OCIO_CHECK_NO_THROW(cpuProcessor = BuildCPUProcessor(OCIO::TRANSFORM_DIR_FORWARD));\n\n    std::vector<float> outImg(NB_PIXELS*4);\n\n    {\n        OCIO::PackedImageDesc srcImgDesc(&inImg[0], NB_PIXELS, 1, 4);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], NB_PIXELS, 1, 4);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PackedImageDesc srcImgDesc(&inImg[0], 1, NB_PIXELS, 4);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 1, NB_PIXELS, 4);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PackedImageDesc srcImgDesc(&inImg[0], 2, 3, 4);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 2, 3, 4);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PackedImageDesc srcImgDesc(&inImg[0], 3, 2, 4);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 3, 2, 4);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PackedImageDesc srcImgDesc(&inImg[0], 2, 3, 4);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 2, 3,\n                                         OCIO::CHANNEL_ORDERING_RGBA,\n                                         OCIO::BIT_DEPTH_F32,\n                                         OCIO::AutoStride,\n                                         OCIO::AutoStride,\n                                         OCIO::AutoStride);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PackedImageDesc srcImgDesc(&inImg[0], 2, 3, 4);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 2, 3,\n                                         OCIO::CHANNEL_ORDERING_RGBA,\n                                         OCIO::BIT_DEPTH_F32,\n                                         sizeof(float),\n                                         OCIO::AutoStride,\n                                         OCIO::AutoStride);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PackedImageDesc srcImgDesc(&inImg[0], 2, 3, 4);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 2, 3,\n                                         OCIO::CHANNEL_ORDERING_RGBA,\n                                         OCIO::BIT_DEPTH_F32,\n                                         sizeof(float),\n                                         4*sizeof(float),\n                                         OCIO::AutoStride);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PackedImageDesc srcImgDesc(&inImg[0], 2, 3, 4);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 2, 3,\n                                         4, \/\/ Number of channels\n                                         OCIO::BIT_DEPTH_F32,\n                                         sizeof(float),\n                                         4*sizeof(float),\n                                         OCIO::AutoStride);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PackedImageDesc srcImgDesc(&inImg[0], 2, 3, 4);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 2, 3,\n                                         4, \/\/ Number of channels\n                                         OCIO::BIT_DEPTH_F32,\n                                         OCIO::AutoStride,\n                                         4*sizeof(float),\n                                         OCIO::AutoStride);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PackedImageDesc srcImgDesc(&inImg[0], 2, 3, 4);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 2, 3,\n                                         4, \/\/ Number of channels\n                                         OCIO::BIT_DEPTH_F32,\n                                         OCIO::AutoStride,\n                                         4*sizeof(float),\n                                         2*4*sizeof(float));\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PackedImageDesc srcImgDesc(&inImg[0], 2, 3, 4);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 2, 3,\n                                         4, \/\/ Number of channels\n                                         OCIO::BIT_DEPTH_F32,\n                                         OCIO::AutoStride,\n                                         OCIO::AutoStride,\n                                         2*4*sizeof(float));\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n}\n\nOCIO_ADD_TEST(CPUProcessor, scanline_helper_packed_one_buffer)\n{\n    \/\/ Now that the previous unit test covers all cases with different buffers,\n    \/\/ let's test some cases using the same in and out buffer.\n\n    OCIO::ConstCPUProcessorRcPtr cpuProcessor;\n    OCIO_CHECK_NO_THROW(cpuProcessor = BuildCPUProcessor(OCIO::TRANSFORM_DIR_FORWARD));\n\n    std::vector<float> processingImg(NB_PIXELS*4);\n\n    {\n        processingImg = inImg;\n\n        OCIO::PackedImageDesc imgDesc(&processingImg[0], NB_PIXELS, 1, 4);\n\n        Process(cpuProcessor, imgDesc, __LINE__);\n    }\n\n    {\n        processingImg = inImg;\n\n        OCIO::PackedImageDesc imgDesc(&processingImg[0], 3, 2, 4);\n\n        Process(cpuProcessor, imgDesc, __LINE__);\n    }\n\n    {\n        processingImg = inImg;\n\n        OCIO::PackedImageDesc imgDesc(&processingImg[0], 1, NB_PIXELS, 4);\n\n        Process(cpuProcessor, imgDesc, __LINE__);\n    }\n}\n\nOCIO_ADD_TEST(CPUProcessor, scanline_helper_planar)\n{\n    \/\/ Test the planar image description.\n\n    OCIO::ConstCPUProcessorRcPtr cpuProcessor;\n    OCIO_CHECK_NO_THROW(cpuProcessor = BuildCPUProcessor(OCIO::TRANSFORM_DIR_FORWARD));\n\n    std::vector<float> outImgR(NB_PIXELS);\n    std::vector<float> outImgG(NB_PIXELS);\n    std::vector<float> outImgB(NB_PIXELS);\n    std::vector<float> outImgA(NB_PIXELS);\n\n    {\n        OCIO::PlanarImageDesc srcImgDesc(&inImgR[0], &inImgG[0], &inImgB[0], &inImgA[0], NB_PIXELS, 1);\n        OCIO::PlanarImageDesc dstImgDesc(&outImgR[0], &outImgG[0], &outImgB[0], &outImgA[0], NB_PIXELS, 1);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PlanarImageDesc srcImgDesc(&inImgR[0], &inImgG[0], &inImgB[0], &inImgA[0], NB_PIXELS, 1);\n        OCIO::PlanarImageDesc dstImgDesc(&outImgR[0], &outImgG[0], &outImgB[0], &outImgA[0], NB_PIXELS, 1);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PlanarImageDesc srcImgDesc(&inImgR[0], &inImgG[0], &inImgB[0], &inImgA[0], NB_PIXELS, 1);\n        OCIO::PlanarImageDesc dstImgDesc(&outImgR[0], &outImgG[0], &outImgB[0], &outImgA[0], NB_PIXELS, 1);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PlanarImageDesc srcImgDesc(&inImgR[0], &inImgG[0], &inImgB[0], &inImgA[0], 3, 2);\n        OCIO::PlanarImageDesc dstImgDesc(&outImgR[0], &outImgG[0], &outImgB[0], &outImgA[0], 3, 2);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PlanarImageDesc srcImgDesc(&inImgR[0], &inImgG[0], &inImgB[0], &inImgA[0], 2, 3);\n        OCIO::PlanarImageDesc dstImgDesc(&outImgR[0], &outImgG[0], &outImgB[0], &outImgA[0],\n                                         2, 3,\n                                         OCIO::BIT_DEPTH_F32,\n                                         sizeof(float),\n                                         OCIO::AutoStride);\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PlanarImageDesc srcImgDesc(&inImgR[0], &inImgG[0], &inImgB[0], &inImgA[0], 2, 3);\n        OCIO::PlanarImageDesc dstImgDesc(&outImgR[0], &outImgG[0], &outImgB[0], &outImgA[0],\n                                         2, 3,\n                                         OCIO::BIT_DEPTH_F32,\n                                         sizeof(float),\n                                         2*sizeof(float));\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PlanarImageDesc srcImgDesc(&inImgR[0], &inImgG[0], &inImgB[0], &inImgA[0], 2, 3);\n        OCIO::PlanarImageDesc dstImgDesc(&outImgR[0], &outImgG[0], &outImgB[0], &outImgA[0],\n                                         2, 3,\n                                         OCIO::BIT_DEPTH_F32,\n                                         OCIO::AutoStride,\n                                         2*sizeof(float));\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PlanarImageDesc srcImgDesc(&inImgR[0], &inImgG[0], &inImgB[0], &inImgA[0],\n                                         2, 3,\n                                         OCIO::BIT_DEPTH_F32,\n                                         OCIO::AutoStride,\n                                         2*sizeof(float));\n\n        OCIO::PlanarImageDesc dstImgDesc(&outImgR[0], &outImgG[0], &outImgB[0], &outImgA[0],\n                                         2, 3,\n                                         OCIO::BIT_DEPTH_F32,\n                                         OCIO::AutoStride,\n                                         2*sizeof(float));\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PlanarImageDesc srcImgDesc(&inImgR[0], &inImgG[0], &inImgB[0], &inImgA[0],\n                                         2, 3,\n                                         OCIO::BIT_DEPTH_F32,\n                                         sizeof(float),\n                                         2*sizeof(float));\n\n        OCIO::PlanarImageDesc dstImgDesc(&outImgR[0], &outImgG[0], &outImgB[0], &outImgA[0],\n                                         2, 3,\n                                         OCIO::BIT_DEPTH_F32,\n                                         OCIO::AutoStride,\n                                         2*sizeof(float));\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PlanarImageDesc srcImgDesc(&inImgR[0], &inImgG[0], &inImgB[0], &inImgA[0],\n                                         2, 3,\n                                         OCIO::BIT_DEPTH_F32,\n                                         sizeof(float),\n                                         2*sizeof(float));\n\n        OCIO::PlanarImageDesc dstImgDesc(&outImgR[0], &outImgG[0], &outImgB[0], nullptr,\n                                         2, 3,\n                                         OCIO::BIT_DEPTH_F32,\n                                         OCIO::AutoStride,\n                                         2*sizeof(float));\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        OCIO::PlanarImageDesc srcImgDesc(&inImgR[0], &inImgG[0], &inImgB[0], nullptr,\n                                         2, 3,\n                                         OCIO::BIT_DEPTH_F32,\n                                         sizeof(float),\n                                         2*sizeof(float));\n\n        OCIO::PlanarImageDesc dstImgDesc(&outImgR[0], &outImgG[0], &outImgB[0], nullptr,\n                                         2, 3,\n                                         OCIO::BIT_DEPTH_F32,\n                                         OCIO::AutoStride,\n                                         2*sizeof(float));\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n}\n\nOCIO_ADD_TEST(CPUProcessor, scanline_helper_tile)\n{\n    \/\/ Process tiles.\n\n    OCIO::ConstCPUProcessorRcPtr cpuProcessor;\n    OCIO_CHECK_NO_THROW(cpuProcessor = BuildCPUProcessor(OCIO::TRANSFORM_DIR_FORWARD));\n\n    std::vector<float> outImg(NB_PIXELS*4);\n\n    {\n        \/\/ Pixels are { 1, 2, 3,\n        \/\/              4, 5, 6  }\n\n        \/\/ Copy the 1st pixel which should be untouched.\n        outImg[(0 * 4) + 0] = resImg[(0 * 4) + 0];\n        outImg[(0 * 4) + 1] = resImg[(0 * 4) + 1];\n        outImg[(0 * 4) + 2] = resImg[(0 * 4) + 2];\n        outImg[(0 * 4) + 3] = resImg[(0 * 4) + 3];\n        \/\/ Copy the 4th pixel which should be untouched.\n        outImg[(3 * 4) + 0] = resImg[(3 * 4) + 0];\n        outImg[(3 * 4) + 1] = resImg[(3 * 4) + 1];\n        outImg[(3 * 4) + 2] = resImg[(3 * 4) + 2];\n        outImg[(3 * 4) + 3] = resImg[(3 * 4) + 3];\n\n        \/\/ Only process the pixels = { 2, 3,\n        \/\/                             5, 6  }\n\n        OCIO::PackedImageDesc srcImgDesc(&inImg[4],\n                                         2, 2, 4,   \/\/ width=2, height=2, and nchannels=4\n                                         OCIO::BIT_DEPTH_F32,\n                                         sizeof(float),\n                                         4*sizeof(float),\n                                         3*4*sizeof(float));\n\n        OCIO::PackedImageDesc dstImgDesc(&outImg[4],\n                                         2, 2, 4,   \/\/ width=2, height=2, and nchannels=4\n                                         OCIO::BIT_DEPTH_F32,\n                                         sizeof(float),\n                                         4*sizeof(float),\n                                         3*4*sizeof(float));\n\n        OCIO_CHECK_NO_THROW(cpuProcessor->apply(srcImgDesc, dstImgDesc));\n\n        for(size_t pxl=0; pxl<NB_PIXELS; ++pxl)\n        {\n            OCIO_CHECK_CLOSE(outImg[4*pxl+0], resImg[4*pxl+0], 1e-7f);\n            OCIO_CHECK_CLOSE(outImg[4*pxl+1], resImg[4*pxl+1], 1e-7f);\n            OCIO_CHECK_CLOSE(outImg[4*pxl+2], resImg[4*pxl+2], 1e-7f);\n            OCIO_CHECK_CLOSE(outImg[4*pxl+3], resImg[4*pxl+3], 1e-7f);\n        }\n    }\n\n    {\n        \/\/ Pixels are { 1, 2, 3,\n        \/\/              4, 5, 6  }\n\n        \/\/ Copy the 3rd pixel which should be untouched.\n        outImg[(2 * 4) + 0] = resImg[(2 * 4) + 0];\n        outImg[(2 * 4) + 1] = resImg[(2 * 4) + 1];\n        outImg[(2 * 4) + 2] = resImg[(2 * 4) + 2];\n        outImg[(2 * 4) + 3] = resImg[(2 * 4) + 3];\n        \/\/ Copy the 6th pixel which should be untouched.\n        outImg[(5 * 4) + 0] = resImg[(5 * 4) + 0];\n        outImg[(5 * 4) + 1] = resImg[(5 * 4) + 1];\n        outImg[(5 * 4) + 2] = resImg[(5 * 4) + 2];\n        outImg[(5 * 4) + 3] = resImg[(5 * 4) + 3];\n\n        \/\/ Only process the pixels = { 1, 2,\n        \/\/                             4, 5 }\n\n        OCIO::PackedImageDesc srcImgDesc(&inImg[0],\n                                         2, 2, 4,   \/\/ width=2, height=2, and nchannels=4\n                                         OCIO::BIT_DEPTH_F32,\n                                         sizeof(float),\n                                         4*sizeof(float),\n                                         3*4*sizeof(float));\n\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0],\n                                         2, 2, 4,   \/\/ width=2, height=2, and nchannels=4\n                                         OCIO::BIT_DEPTH_F32,\n                                         sizeof(float),\n                                         4*sizeof(float),\n                                         3*4*sizeof(float));\n\n        Process(cpuProcessor, srcImgDesc, dstImgDesc, __LINE__);\n    }\n\n    {\n        \/\/ Pixels are { 1, 2, 3,\n        \/\/              4, 5, 6  }\n\n        outImg = inImg; \/\/ Use an in-place image buffer.\n\n        \/\/ Copy the 3rd pixel which should be untouched.\n        outImg[(2 * 4) + 0] = resImg[(2 * 4) + 0];\n        outImg[(2 * 4) + 1] = resImg[(2 * 4) + 1];\n        outImg[(2 * 4) + 2] = resImg[(2 * 4) + 2];\n        outImg[(2 * 4) + 3] = resImg[(2 * 4) + 3];\n        \/\/ Copy the 6th pixel which should be untouched.\n        outImg[(5 * 4) + 0] = resImg[(5 * 4) + 0];\n        outImg[(5 * 4) + 1] = resImg[(5 * 4) + 1];\n        outImg[(5 * 4) + 2] = resImg[(5 * 4) + 2];\n        outImg[(5 * 4) + 3] = resImg[(5 * 4) + 3];\n\n        \/\/ Only process the pixels = { 1, 2,\n        \/\/                             4, 5 }\n\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0],\n                                         2, 2, 4,   \/\/ width=2, height=2, and nchannels=4\n                                         OCIO::BIT_DEPTH_F32,\n                                         sizeof(float),\n                                         4*sizeof(float),\n                                         3*4*sizeof(float));\n\n        Process(cpuProcessor, dstImgDesc, dstImgDesc, __LINE__);\n    }\n\n}\n\n\nOCIO_ADD_TEST(CPUProcessor, custom_scanlines)\n{\n    \/\/ Cases testing custom xStrideBytes and yStrideBytes values.\n\n    const float magicNumber = 12345.6789f;\n\n    OCIO::ConstCPUProcessorRcPtr cpuProcessor;\n    OCIO_CHECK_NO_THROW(cpuProcessor = BuildCPUProcessor(OCIO::TRANSFORM_DIR_FORWARD));\n\n    {\n        \/\/ Pixels are { RGBA, RGBA, RGBA, x,\n        \/\/              RGBA, RGBA, RGBA, x  } where x is not a color channel.\n\n        std::vector<float> img\n            = { inImg[ 0], inImg[ 1], inImg[ 2], inImg[ 3],\n                inImg[ 4], inImg[ 5], inImg[ 6], inImg[ 7],\n                inImg[ 8], inImg[ 9], inImg[10], inImg[11],\n                magicNumber,\n                inImg[12], inImg[13], inImg[14], inImg[15],\n                inImg[16], inImg[17], inImg[18], inImg[19],\n                inImg[20], inImg[21], inImg[22], inImg[23],\n                magicNumber };\n\n        OCIO::PackedImageDesc srcImgDesc(&img[0],\n                                         3, 2, 4,\n                                         OCIO::BIT_DEPTH_F32,\n                                         OCIO::AutoStride,\n                                         OCIO::AutoStride,\n                                         \/\/ Bytes to the next line.\n                                         3*4*sizeof(float)+sizeof(float));\n\n        std::vector<float> outImg(NB_PIXELS*4);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 3, 2, 4);\n\n        OCIO_CHECK_NO_THROW(cpuProcessor->apply(srcImgDesc, dstImgDesc));\n\n        for(size_t pxl=0; pxl<NB_PIXELS; ++pxl)\n        {\n            OCIO_CHECK_CLOSE(outImg[4*pxl+0], resImg[4*pxl+0], 1e-7f);\n            OCIO_CHECK_CLOSE(outImg[4*pxl+1], resImg[4*pxl+1], 1e-7f);\n            OCIO_CHECK_CLOSE(outImg[4*pxl+2], resImg[4*pxl+2], 1e-7f);\n            OCIO_CHECK_CLOSE(outImg[4*pxl+3], resImg[4*pxl+3], 1e-7f);\n        }\n    }\n\n    {\n        \/\/ Pixels are { RxGxBxAx, RxGxBxAx, RxGxBxAx,\n        \/\/              RxGxBxAx, RxGxBxAx, RxGxBxAx  } where x is not a color channel.\n\n        std::vector<float> img\n            = { inImg[ 0], magicNumber, inImg[ 1], magicNumber, inImg[ 2], magicNumber, inImg[ 3], magicNumber,\n                inImg[ 4], magicNumber, inImg[ 5], magicNumber, inImg[ 6], magicNumber, inImg[ 7], magicNumber,\n                inImg[ 8], magicNumber, inImg[ 9], magicNumber, inImg[10], magicNumber, inImg[11], magicNumber,\n                inImg[12], magicNumber, inImg[13], magicNumber, inImg[14], magicNumber, inImg[15], magicNumber,\n                inImg[16], magicNumber, inImg[17], magicNumber, inImg[18], magicNumber, inImg[19], magicNumber,\n                inImg[20], magicNumber, inImg[21], magicNumber, inImg[22], magicNumber, inImg[23], magicNumber };\n\n        OCIO::PackedImageDesc srcImgDesc(&img[0],  3, 2, 4,\n                                         OCIO::BIT_DEPTH_F32,\n                                         \/\/ Bytes to the next channel.\n                                         sizeof(float)+sizeof(float),\n                                         OCIO::AutoStride,\n                                         OCIO::AutoStride);\n\n        std::vector<float> outImg(NB_PIXELS*3);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 3, 2, 3);\n\n        OCIO_CHECK_NO_THROW(cpuProcessor->apply(srcImgDesc, dstImgDesc));\n\n        for(size_t pxl=0; pxl<NB_PIXELS; ++pxl)\n        {\n            OCIO_CHECK_CLOSE(outImg[3*pxl+0], resImg[4*pxl+0], 1e-7f);\n            OCIO_CHECK_CLOSE(outImg[3*pxl+1], resImg[4*pxl+1], 1e-7f);\n            OCIO_CHECK_CLOSE(outImg[3*pxl+2], resImg[4*pxl+2], 1e-7f);\n        }\n    }\n\n    {\n        \/\/ Pixels are { RGBAx, RGBAx, RGBAx,\n        \/\/              RGBAx, RGBAx, RGBAx  } where x is not a color channel.\n\n        std::vector<float> img\n            = { inImg[ 0], inImg[ 1], inImg[ 2], inImg[ 3], magicNumber,\n                inImg[ 4], inImg[ 5], inImg[ 6], inImg[ 7], magicNumber,\n                inImg[ 8], inImg[ 9], inImg[10], inImg[11], magicNumber,\n                inImg[12], inImg[13], inImg[14], inImg[15], magicNumber,\n                inImg[16], inImg[17], inImg[18], inImg[19], magicNumber,\n                inImg[20], inImg[21], inImg[22], inImg[23], magicNumber };\n\n        OCIO::PackedImageDesc srcImgDesc(&img[0], 3, 2, 4,\n                                         OCIO::BIT_DEPTH_F32,\n                                         OCIO::AutoStride,\n                                         \/\/ Bytes to the next pixel.\n                                         4*sizeof(float)+sizeof(float),\n                                         OCIO::AutoStride);\n\n        std::vector<float> outImg(NB_PIXELS*3);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 3, 2, 3);\n\n        OCIO_CHECK_NO_THROW(cpuProcessor->apply(srcImgDesc, dstImgDesc));\n\n        for(size_t pxl=0; pxl<NB_PIXELS; ++pxl)\n        {\n            OCIO_CHECK_CLOSE(outImg[3*pxl+0], resImg[4*pxl+0], 1e-7f);\n            OCIO_CHECK_CLOSE(outImg[3*pxl+1], resImg[4*pxl+1], 1e-7f);\n            OCIO_CHECK_CLOSE(outImg[3*pxl+2], resImg[4*pxl+2], 1e-7f);\n        }\n    }\n\n    {\n        \/\/ Pixels are { RGBAx, RGBAx, RGBAx, x\n        \/\/              RGBAx, RGBAx, RGBAx, x  } where x is not a color channel.\n\n        std::vector<float> img\n            = { inImg[ 0], inImg[ 1], inImg[ 2], inImg[ 3], magicNumber,\n                inImg[ 4], inImg[ 5], inImg[ 6], inImg[ 7], magicNumber,\n                inImg[ 8], inImg[ 9], inImg[10], inImg[11], magicNumber,\n                magicNumber,\n                inImg[12], inImg[13], inImg[14], inImg[15], magicNumber,\n                inImg[16], inImg[17], inImg[18], inImg[19], magicNumber,\n                inImg[20], inImg[21], inImg[22], inImg[23], magicNumber,\n                magicNumber };\n\n        OCIO::PackedImageDesc srcImgDesc(&img[0],\n                                         3, 2, 4,\n                                         OCIO::BIT_DEPTH_F32,\n                                         OCIO::AutoStride,\n                                         \/\/ Bytes to the next pixel.\n                                         4*sizeof(float)+sizeof(float),\n                                         \/\/ Bytes to the next line.\n                                         3*(4*sizeof(float)+sizeof(float))+sizeof(float));\n\n        std::vector<float> outImg(NB_PIXELS*3);\n        OCIO::PackedImageDesc dstImgDesc(&outImg[0], 3, 2, 3);\n\n        OCIO_CHECK_NO_THROW(cpuProcessor->apply(srcImgDesc, dstImgDesc));\n\n        for(size_t pxl=0; pxl<NB_PIXELS; ++pxl)\n        {\n            OCIO_CHECK_CLOSE(outImg[3*pxl+0], resImg[4*pxl+0], 1e-7f);\n            OCIO_CHECK_CLOSE(outImg[3*pxl+1], resImg[4*pxl+1], 1e-7f);\n            OCIO_CHECK_CLOSE(outImg[3*pxl+2], resImg[4*pxl+2], 1e-7f);\n        }\n    }\n\n}\n\nOCIO_ADD_TEST(CPUProcessor, one_pixel)\n{\n    OCIO::ConstCPUProcessorRcPtr cpuProcessor;\n    OCIO_CHECK_NO_THROW(cpuProcessor = BuildCPUProcessor(OCIO::TRANSFORM_DIR_FORWARD));\n\n    \/\/ The CPU Processor only includes a Matrix with offset:\n    \/\/   const float offset4[4] = { 1.4002f, 0.4005f, 0.8007f, 0.5007f };\n\n    {\n        float pixel[4]{ 0.1f, 0.3f, 0.9f, 1.0f };\n\n        OCIO_CHECK_NO_THROW(cpuProcessor->applyRGBA(pixel));\n\n        OCIO_CHECK_EQUAL(pixel[0], 0.1f + 1.4002f);\n        OCIO_CHECK_EQUAL(pixel[1], 0.3f + 0.4005f);\n        OCIO_CHECK_EQUAL(pixel[2], 0.9f + 0.8007f);\n        OCIO_CHECK_EQUAL(pixel[3], 1.0f + 0.5007f);\n    }\n\n    {\n        float pixel[3]{ 0.1f, 0.3f, 0.9f };\n\n        OCIO_CHECK_NO_THROW(cpuProcessor->applyRGB(pixel));\n\n        OCIO_CHECK_EQUAL(pixel[0], 0.1f + 1.4002f);\n        OCIO_CHECK_EQUAL(pixel[1], 0.3f + 0.4005f);\n        OCIO_CHECK_EQUAL(pixel[2], 0.9f + 0.8007f);\n    }\n}\n\nnamespace\n{\n\ntemplate<OCIO::BitDepth inBD, OCIO::BitDepth outBD>\nvoid ComputeImage(unsigned width, unsigned height, unsigned nChannels,\n                   const void * inBuf, void * outBuf,\n                   unsigned line)\n{\n    typedef typename OCIO::BitDepthInfo<inBD>::Type InType;\n    typedef typename OCIO::BitDepthInfo<outBD>::Type OutType;\n\n    OCIO::ConfigRcPtr config = OCIO::Config::Create();\n\n    OCIO::MatrixTransformRcPtr transform = OCIO::MatrixTransform::Create();\n    constexpr double offset4[4] = { 1.2002, 0.4005, 0.8007, 0.5 };\n    transform->setOffset( offset4 );\n\n    OCIO::ConstProcessorRcPtr processor;\n    OCIO_CHECK_NO_THROW(processor = config->getProcessor(transform));\n\n    OCIO::ConstCPUProcessorRcPtr cpuProcessor;\n    OCIO_CHECK_NO_THROW(cpuProcessor\n        = processor->getOptimizedCPUProcessor(inBD, outBD,\n                                              OCIO::OPTIMIZATION_DEFAULT));\n\n    const OCIO::PackedImageDesc srcImgDesc((void *)inBuf,\n                                           width, height, nChannels,\n                                           inBD,\n                                           OCIO::AutoStride,\n                                           OCIO::AutoStride,\n                                           OCIO::AutoStride);\n\n    OCIO::PackedImageDesc dstImgDesc(outBuf,\n                                     width, height, nChannels,\n                                     outBD,\n                                     sizeof(OutType),\n                                     OCIO::AutoStride,\n                                     OCIO::AutoStride);\n\n    OCIO_CHECK_NO_THROW(cpuProcessor->apply(srcImgDesc, dstImgDesc));\n\n\n    const InType * inValues  = (const InType *)inBuf;\n    OutType * outValues = (OutType *)outBuf;\n\n    const float inScale = float(GetBitDepthMaxValue(OCIO::BIT_DEPTH_F32)\n                                    \/ GetBitDepthMaxValue(inBD));\n\n    const float outScale = float( GetBitDepthMaxValue(outBD)\n                                    \/ GetBitDepthMaxValue(OCIO::BIT_DEPTH_F32));\n\n    for(size_t idx=0; idx<(width*height);)\n    {\n        \/\/ Manual computation of the results.\n\n        const float pxl[4]{ (float(inValues[idx+0]) * inScale + (float)offset4[0]) * outScale,\n                            (float(inValues[idx+1]) * inScale + (float)offset4[1]) * outScale,\n                            (float(inValues[idx+2]) * inScale + (float)offset4[2]) * outScale,\n                            nChannels==4\n                                ? ((float(inValues[idx+3]) * inScale + (float)offset4[3]) * outScale)\n                                : 0.0f\n                          };\n\n        \/\/ Validate all the results.\n\n        if(OCIO::BitDepthInfo<outBD>::isFloat)\n        {\n            OCIO_CHECK_CLOSE_FROM(outValues[idx+0], pxl[0], 1e-6f, line);\n            OCIO_CHECK_CLOSE_FROM(outValues[idx+1], pxl[1], 1e-6f, line);\n            OCIO_CHECK_CLOSE_FROM(outValues[idx+2], pxl[2], 1e-6f, line);\n            if(nChannels==4)\n            {\n                OCIO_CHECK_CLOSE_FROM(outValues[idx+3], pxl[3], 1e-6f, line);\n            }\n        }\n        else\n        {\n            OCIO_CHECK_EQUAL_FROM(outValues[idx+0], OCIO::Converter<outBD>::CastValue(pxl[0]), line);\n            OCIO_CHECK_EQUAL_FROM(outValues[idx+1], OCIO::Converter<outBD>::CastValue(pxl[1]), line);\n            OCIO_CHECK_EQUAL_FROM(outValues[idx+2], OCIO::Converter<outBD>::CastValue(pxl[2]), line);\n            if(nChannels==4)\n            {\n                OCIO_CHECK_EQUAL_FROM(outValues[idx+3], OCIO::Converter<outBD>::CastValue(pxl[3]), line);\n            }\n        }\n\n        idx += nChannels;\n    }\n}\n\n}; \/\/anon\n\nOCIO_ADD_TEST(CPUProcessor, optimizations)\n{\n    \/\/ The unit test validates some 'optimization' paths now implemented\n    \/\/ by the ScanlineHelper class. To fully validate these paths a 'normal' image\n    \/\/ must be used (i.e. 'few pixels' image is not enough).\n\n    constexpr unsigned width     = 640;\n    constexpr unsigned height    = 480;\n    constexpr unsigned nChannels = 4;\n\n    \/\/ Input and Output are not packed RGBA i.e no optimizations.\n    {\n        std::vector<uint16_t> inBuf(width*height*3);\n        for(size_t idx=0; idx<inBuf.size(); ++idx)\n        {\n            inBuf[idx] = uint16_t(idx % OCIO::BitDepthInfo<OCIO::BIT_DEPTH_UINT16>::maxValue);\n        }\n\n        std::vector<uint16_t> outBuf(width*height*3);\n\n        ComputeImage<OCIO::BIT_DEPTH_UINT16, OCIO::BIT_DEPTH_UINT16>(width, height, 3,\n                                                                     &inBuf[0], &outBuf[0],\n                                                                     __LINE__);\n    }\n\n    \/\/ Input and Output are packed RGBA but not F32.\n    {\n        std::vector<uint16_t> inBuf(width*height*nChannels);\n        for(size_t idx=0; idx<inBuf.size(); ++idx)\n        {\n            inBuf[idx] = uint16_t(idx % OCIO::BitDepthInfo<OCIO::BIT_DEPTH_UINT16>::maxValue);\n        }\n\n        std::vector<uint16_t> outBuf(width*height*nChannels);\n\n        ComputeImage<OCIO::BIT_DEPTH_UINT16, OCIO::BIT_DEPTH_UINT16>(width, height, nChannels,\n                                                                     &inBuf[0], &outBuf[0],\n                                                                     __LINE__);\n    }\n\n    \/\/ Input is packed RGBA but not F32, and output is packed RGBA F32.\n    {\n        std::vector<uint16_t> inBuf(width*height*nChannels);\n        for(size_t idx=0; idx<inBuf.size(); ++idx)\n        {\n            inBuf[idx] = uint16_t(idx % OCIO::BitDepthInfo<OCIO::BIT_DEPTH_UINT16>::maxValue);\n        }\n\n        std::vector<float> outBuf(width*height*nChannels);\n\n        ComputeImage<OCIO::BIT_DEPTH_UINT16, OCIO::BIT_DEPTH_F32>(width, height, nChannels,\n                                                                  &inBuf[0], &outBuf[0],\n                                                                  __LINE__);\n    }\n\n    \/\/ Input is packed RGBA F32, and output is packed RGBA but not F32.\n    {\n        std::vector<float> inBuf(width*height*nChannels);\n        for(size_t idx=0; idx<inBuf.size(); ++idx)\n        {\n            inBuf[idx] = float(idx) \/ float(inBuf.size());\n        }\n\n        std::vector<uint16_t> outBuf(width*height*nChannels);\n\n        ComputeImage<OCIO::BIT_DEPTH_F32, OCIO::BIT_DEPTH_UINT16>(width, height, nChannels,\n                                                                  &inBuf[0], &outBuf[0],\n                                                                  __LINE__);\n    }\n\n    \/\/ Input and output are both packed RGBA F32.\n    {\n        std::vector<float> inBuf(width*height*nChannels);\n        for(size_t idx=0; idx<inBuf.size(); ++idx)\n        {\n            inBuf[idx] = float(idx) \/ float(inBuf.size());\n        }\n\n        std::vector<float> outBuf(width*height*nChannels);\n\n        ComputeImage<OCIO::BIT_DEPTH_F32, OCIO::BIT_DEPTH_F32>(width, height, nChannels,\n                                                               &inBuf[0], &outBuf[0],\n                                                               __LINE__);\n    }\n}\n\n","avg_line_length":40.4070876874,"max_line_length":113,"alphanum_fraction":0.4547989566,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11159,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause","Apache-2.0"],"max_stars_count":7.0,"content":"\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2017 Intel Corporation. All Rights Reserved.\n\n#include <librealsense2\/rs.hpp>\n#include \"..\/example.hpp\"\n#include <imgui.h>\n#include \"imgui_impl_glfw.h\"\n\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <cstring>\n\nvoid render_slider(rect location, float& clipping_dist);\nvoid remove_background(rs2::video_frame& other, const rs2::depth_frame& depth_frame, float depth_scale, float clipping_dist);\nfloat get_depth_scale(rs2::device dev);\nrs2_stream find_stream_to_align(const std::vector<rs2::stream_profile>& streams);\nbool profile_changed(const std::vector<rs2::stream_profile>& current, const std::vector<rs2::stream_profile>& prev);\n\nint main(int argc, char * argv[]) try\n{\n    \/\/ Create and initialize GUI related objects\n    window app(1280, 720, \"CPP - Align Example\"); \/\/ Simple window handling\n    ImGui_ImplGlfw_Init(app, false);      \/\/ ImGui library intializition\n    rs2::colorizer c;                          \/\/ Helper to colorize depth images\n    texture renderer;                     \/\/ Helper for renderig images\n\n    \/\/ Create a pipeline to easily configure and start the camera\n    rs2::pipeline pipe;\n    \/\/Calling pipeline's start() without any additional parameters will start the first device\n    \/\/ with its default streams.\n    \/\/The start function returns the pipeline profile which the pipeline used to start the device\n    rs2::pipeline_profile profile = pipe.start();\n\n    \/\/ Each depth camera might have different units for depth pixels, so we get it here\n    \/\/ Using the pipeline's profile, we can retrieve the device that the pipeline uses\n    float depth_scale = get_depth_scale(profile.get_device());\n\n    \/\/Pipeline could choose a device that does not have a color stream\n    \/\/If there is no color stream, choose to align depth to another stream\n    rs2_stream align_to = find_stream_to_align(profile.get_streams());\n\n    \/\/ Create a rs2::align object.\n    \/\/ rs2::align allows us to perform alignment of depth frames to others frames\n    \/\/The \"align_to\" is the stream type to which we plan to align depth frames.\n    rs2::align align(align_to);\n\n    \/\/ Define a variable for controlling the distance to clip\n    float depth_clipping_distance = 1.f;\n\n    while (app) \/\/ Application still alive?\n    {\n        \/\/ Using the align object, we block the application until a frameset is available\n        rs2::frameset frameset = pipe.wait_for_frames();\n\n        \/\/ rs2::pipeline::wait_for_frames() can replace the device it uses in case of device error or disconnection.\n        \/\/ Since rs2::align is aligning depth to some other stream, we need to make sure that the stream was not changed\n        \/\/  after the call to wait_for_frames();\n        if (profile_changed(pipe.get_active_profile().get_streams(), profile.get_streams()))\n        {\n            \/\/If the profile was changed, update the align object, and also get the new device's depth scale\n            profile = pipe.get_active_profile();\n            align_to = find_stream_to_align(profile.get_streams());\n            align = rs2::align(align_to);\n            depth_scale = get_depth_scale(profile.get_device());\n        }\n\n        \/\/Get processed aligned frame\n        auto processed = align.process(frameset);\n\n        \/\/ Trying to get both other and aligned depth frames\n        rs2::video_frame other_frame = processed.first(align_to);\n        rs2::depth_frame aligned_depth_frame = processed.get_depth_frame();\n\n        \/\/If one of them is unavailable, continue iteration\n        if (!aligned_depth_frame || !other_frame)\n        {\n            continue;\n        }\n        \/\/ Passing both frames to remove_background so it will \"strip\" the background\n        \/\/ NOTE: in this example, we alter the buffer of the other frame, instead of copying it and altering the copy\n        \/\/       This behavior is not recommended in real application since the other frame could be used elsewhere\n        remove_background(other_frame, aligned_depth_frame, depth_scale, depth_clipping_distance);\n\n        \/\/ Taking dimensions of the window for rendering purposes\n        float w = static_cast<float>(app.width());\n        float h = static_cast<float>(app.height());\n\n        \/\/ At this point, \"other_frame\" is an altered frame, stripped form its background\n        \/\/ Calculating the position to place the frame in the window\n        rect altered_other_frame_rect{ 0, 0, w, h };\n        altered_other_frame_rect = altered_other_frame_rect.adjust_ratio({ static_cast<float>(other_frame.get_width()),static_cast<float>(other_frame.get_height()) });\n\n        \/\/ Render aligned image\n        renderer.render(other_frame, altered_other_frame_rect);\n\n        \/\/ The example also renders the depth frame, as a picture-in-picture\n        \/\/ Calculating the position to place the depth frame in the window\n        rect pip_stream{ 0, 0, w \/ 5, h \/ 5 };\n        pip_stream = pip_stream.adjust_ratio({ static_cast<float>(aligned_depth_frame.get_width()),static_cast<float>(aligned_depth_frame.get_height()) });\n        pip_stream.x = altered_other_frame_rect.x + altered_other_frame_rect.w - pip_stream.w - (std::max(w, h) \/ 25);\n        pip_stream.y = altered_other_frame_rect.y + altered_other_frame_rect.h - pip_stream.h - (std::max(w, h) \/ 25);\n\n        \/\/ Render depth (as picture in pipcture)\n        renderer.upload(c(aligned_depth_frame));\n        renderer.show(pip_stream);\n\n        \/\/ Using ImGui library to provide a slide controller to select the depth clipping distance\n        ImGui_ImplGlfw_NewFrame(1);\n        render_slider({ 5.f, 0, w, h }, depth_clipping_distance);\n        ImGui::Render();\n\n    }\n    return EXIT_SUCCESS;\n}\ncatch (const rs2::error & e)\n{\n    std::cerr << \"RealSense error calling \" << e.get_failed_function() << \"(\" << e.get_failed_args() << \"):\\n    \" << e.what() << std::endl;\n    return EXIT_FAILURE;\n}\ncatch (const std::exception & e)\n{\n    std::cerr << e.what() << std::endl;\n    return EXIT_FAILURE;\n}\n\nfloat get_depth_scale(rs2::device dev)\n{\n    \/\/ Go over the device's sensors\n    for (rs2::sensor& sensor : dev.query_sensors())\n    {\n        \/\/ Check if the sensor if a depth sensor\n        if (rs2::depth_sensor dpt = sensor.as<rs2::depth_sensor>())\n        {\n            return dpt.get_depth_scale();\n        }\n    }\n    throw std::runtime_error(\"Device does not have a depth sensor\");\n}\n\nvoid render_slider(rect location, float& clipping_dist)\n{\n    \/\/ Some trickery to display the control nicely\n    static const int flags = ImGuiWindowFlags_NoCollapse\n        | ImGuiWindowFlags_NoScrollbar\n        | ImGuiWindowFlags_NoSavedSettings\n        | ImGuiWindowFlags_NoTitleBar\n        | ImGuiWindowFlags_NoResize\n        | ImGuiWindowFlags_NoMove;\n    const int pixels_to_buttom_of_stream_text = 25;\n    const float slider_window_width = 30;\n\n    ImGui::SetNextWindowPos({ location.x, location.y + pixels_to_buttom_of_stream_text });\n    ImGui::SetNextWindowSize({ slider_window_width + 20, location.h - (pixels_to_buttom_of_stream_text * 2) });\n\n    \/\/Render the vertical slider\n    ImGui::Begin(\"slider\", nullptr, flags);\n    ImGui::PushStyleColor(ImGuiCol_FrameBg, ImColor(215.f \/ 255, 215.0f \/ 255, 215.0f \/ 255));\n    ImGui::PushStyleColor(ImGuiCol_SliderGrab, ImColor(215.f \/ 255, 215.0f \/ 255, 215.0f \/ 255));\n    ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, ImColor(215.f \/ 255, 215.0f \/ 255, 215.0f \/ 255));\n    auto slider_size = ImVec2(slider_window_width \/ 2, location.h - (pixels_to_buttom_of_stream_text * 2) - 20);\n    ImGui::VSliderFloat(\"\", slider_size, &clipping_dist, 0.0f, 6.0f, \"\", 1.0f, true);\n    if (ImGui::IsItemHovered())\n        ImGui::SetTooltip(\"Depth Clipping Distance: %.3f\", clipping_dist);\n    ImGui::PopStyleColor(3);\n\n    \/\/Display bars next to slider\n    float bars_dist = (slider_size.y \/ 6.0f);\n    for (int i = 0; i <= 6; i++)\n    {\n        ImGui::SetCursorPos({ slider_size.x, i * bars_dist });\n        std::string bar_text = \"- \" + std::to_string(6-i) + \"m\";\n        ImGui::Text(\"%s\", bar_text.c_str());\n    }\n    ImGui::End();\n}\n\nvoid remove_background(rs2::video_frame& other_frame, const rs2::depth_frame& depth_frame, float depth_scale, float clipping_dist)\n{\n    const uint16_t* p_depth_frame = reinterpret_cast<const uint16_t*>(depth_frame.get_data());\n    uint8_t* p_other_frame = reinterpret_cast<uint8_t*>(const_cast<void*>(other_frame.get_data()));\n\n    int width = other_frame.get_width();\n    int height = other_frame.get_height();\n    int other_bpp = other_frame.get_bytes_per_pixel();\n\n    #pragma omp parallel for schedule(dynamic) \/\/Using OpenMP to try to parallelise the loop\n    for (int y = 0; y < height; y++)\n    {\n        auto depth_pixel_index = y * width;\n        for (int x = 0; x < width; x++, ++depth_pixel_index)\n        {\n            \/\/ Get the depth value of the current pixel\n            auto pixels_distance = depth_scale * p_depth_frame[depth_pixel_index];\n\n            \/\/ Check if the depth value is invalid (<=0) or greater than the threashold\n            if (pixels_distance <= 0.f || pixels_distance > clipping_dist)\n            {\n                \/\/ Calculate the offset in other frame's buffer to current pixel\n                auto offset = depth_pixel_index * other_bpp;\n\n                \/\/ Set pixel to \"background\" color (0x999999)\n                std::memset(&p_other_frame[offset], 0x99, other_bpp);\n            }\n        }\n    }\n}\n\nrs2_stream find_stream_to_align(const std::vector<rs2::stream_profile>& streams)\n{\n    \/\/Given a vector of streams, we try to find a depth stream and another stream to align depth with.\n    \/\/We prioritize color streams to make the view look better.\n    \/\/If color is not available, we take another stream that (other than depth)\n    rs2_stream align_to = RS2_STREAM_ANY;\n    bool depth_stream_found = false;\n    bool color_stream_found = false;\n    for (rs2::stream_profile sp : streams)\n    {\n        rs2_stream profile_stream = sp.stream_type();\n        if (profile_stream != RS2_STREAM_DEPTH)\n        {\n            if (!color_stream_found)         \/\/Prefer color\n                align_to = profile_stream;\n\n            if (profile_stream == RS2_STREAM_COLOR)\n            {\n                color_stream_found = true;\n            }\n        }\n        else\n        {\n            depth_stream_found = true;\n        }\n    }\n\n    if(!depth_stream_found)\n        throw std::runtime_error(\"No Depth stream available\");\n\n    if (align_to == RS2_STREAM_ANY)\n        throw std::runtime_error(\"No stream found to align with Depth\");\n\n    return align_to;\n}\n\nbool profile_changed(const std::vector<rs2::stream_profile>& current, const std::vector<rs2::stream_profile>& prev)\n{\n    for (auto&& sp : prev)\n    {\n        \/\/If previous profile is in current (maybe just added another)\n        auto itr = std::find_if(std::begin(current), std::end(current), [&sp](const rs2::stream_profile& current_sp) { return sp.unique_id() == current_sp.unique_id(); });\n        if (itr == std::end(current)) \/\/If it previous stream wasn't found in current\n        {\n            return true;\n        }\n    }\n    return false;\n}\n","avg_line_length":43.0849420849,"max_line_length":171,"alphanum_fraction":0.6700421185,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1610,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":4054.0,"content":"\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <time.h>\n#include <fcntl.h>\n#include <vespa\/vespalib\/net\/socket_address.h>\n#include <cstdlib>\n\nvoid error(const char *msg)\n{\n    perror(msg);\n    std::_Exit(1);\n}\n\nint main(int \/*argc*\/, char ** \/*argv*\/)\n{\n    auto handle = vespalib::SocketAddress::select_local(0).listen();\n    if (!handle) {\n        error(\"ERROR: could not listen to server port\");\n    }\n    int portno = vespalib::SocketAddress::address_of(handle.get()).port();\n    printf(\"Got port %d\", portno);\n    int fd = open(\"logserver.port\", O_CREAT | O_WRONLY,\n                  S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n    char out[6];\n    sprintf(out, \"%d\\n\", portno);\n    ssize_t writeRes = write(fd, out, sizeof(out));\n    close(fd);\n    if (writeRes != sizeof(out)) {\n        error(\"ERROR: could not write port number\");\n    }\n    sockaddr_storage cli_addr;\n    socklen_t clilen = sizeof(cli_addr);\n    int newsockfd = accept(handle.get(),\n                           (struct sockaddr *) &cli_addr,\n                           &clilen);\n    if (newsockfd < 0)\n        error(\"ERROR on accept\");\n    char buffer[1024];\n    while (true) {\n        ssize_t n = read(newsockfd, buffer, sizeof(buffer));\n        if (n < 0) error(\"ERROR reading from socket\");\n        struct timespec t;\n        t.tv_sec  = 0;\n        t.tv_nsec = 200000000;\n        nanosleep(&t, 0);\n    }\n    return 0;\n}\n","avg_line_length":29.2727272727,"max_line_length":104,"alphanum_fraction":0.598757764,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4306,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\/\/\n\/\/ Created by \u0130hsan Demir on 19\/05\/15.\n\/\/\n\n#include <gtest\/gtest.h>\n\n#include \"hazelcast\/client\/internal\/socket\/TcpSocket.h\"\n#include \"hazelcast\/client\/protocol\/ClientMessage.h\"\n\nnamespace hazelcast {\n    namespace client {\n        namespace test {\n            namespace protocol {\n                class ClientMessageTest : public ::testing::Test {\n                protected:\n                    class SocketStub : public internal::socket::TcpSocket {\n                    public:\n                        virtual int send(const void *buf, int size, int flag = MSG_WAITALL) {\n                            if (size <= 100) {\n                                numBytes = size;\n                                memcpy(buffer, buf, (size_t)numBytes);\n                            } else {\n                                numBytes = 0;\n                            }\n                            return numBytes;\n                        }\n\n                        virtual ~SocketStub() {}\n\n                        SocketStub() : internal::socket::TcpSocket(-1), numBytes(0) {\n                            memset(buffer, 0, 100);\n                        }\n\n                        int getNumBytes() const {\n                            return numBytes;\n                        }\n\n                        const byte *getBuffer() const {\n                            return buffer;\n                        }\n\n                    private:\n                        int numBytes;\n                        byte buffer[100];\n                    };\n                };\n\n                TEST_F(ClientMessageTest, testMessageFields) {\n                    std::auto_ptr<client::protocol::ClientMessage> msg =\n                            client::protocol::ClientMessage::createForEncode(22);\n                    ASSERT_EQ(0, msg->getDataSize());\n\n                    ASSERT_FALSE(msg->isRetryable());\n\n                    ASSERT_EQ(22, msg->getFrameLength());\n\n                    msg->setRetryable(true);\n                    msg->setCorrelationId(0xABCDEF12);\n                    msg->addFlag(0x05);\n                    msg->setMessageType(0xABCD);\n                    msg->setPartitionId(0x8ABCDEF1);\n                    msg->setVersion(4);\n                    msg->updateFrameLength();\n\n                    ASSERT_TRUE(msg->isRetryable());\n                    ASSERT_EQ(0xABCDEF12, msg->getCorrelationId());\n                    ASSERT_FALSE(msg->isFlagSet(2));\n                    ASSERT_TRUE(msg->isFlagSet(4));\n                    ASSERT_TRUE(msg->isFlagSet(0x05));\n                    ASSERT_EQ(0xABCD, msg->getMessageType());\n                    ASSERT_EQ((int32_t)0x8ABCDEF1, msg->getPartitionId());\n                    ASSERT_EQ(4, msg->getVersion());\n                    ASSERT_EQ(22, msg->getFrameLength());\n                    ASSERT_EQ(0, msg->getDataSize());\n\n                    SocketStub sock;\n                    ASSERT_EQ(22, msg->writeTo(sock, 0, 22));\n\n                    ASSERT_EQ(22, sock.getNumBytes());\n\n                    byte expectedBytes[22] = {\n                            0x16, 0x0, 0x0, 0x0, \/\/ Frame length\n                            0x04, \/\/ Version\n                            0x05 | client::protocol::ClientMessage::BEGIN_AND_END_FLAGS, \/\/ Flags\n                            0xCD, 0xAB, \/\/ Message Type\n                            0x12, 0xEF, 0xCD, 0xAB, 0x00, 0x00, 0x00, 0x00, \/\/ Correlation Id\n                            0xF1, 0xDE, 0xBC, 0x8A, \/\/ Partition Id\n                            0x16, 0x0 \/\/ Data Offset\n                    };\n\n                    ASSERT_EQ(0, memcmp(expectedBytes, sock.getBuffer(), 22));\n                }\n\n            }\n        }\n    }\n}\n","avg_line_length":38.1061946903,"max_line_length":97,"alphanum_fraction":0.4712029726,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":75788,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/\/ =-=-=-=-=-=-=-\n\/\/ irods includes\n#include \"msParam.h\"\n#include \"generalAdmin.h\"\n#include \"physPath.hpp\"\n#include \"reIn2p3SysRule.hpp\"\n#include \"miscServerFunct.hpp\"\n#include \"dataObjRepl.h\"\n#include \"rsDataObjOpen.hpp\"\n#include \"rsDataObjClose.hpp\"\n#include \"rsFileStageToCache.hpp\"\n#include \"rsFileSyncToArch.hpp\"\n#include \"dataObjOpr.hpp\"\n\n\/\/ =-=-=-=-=-=-=-\n#include \"irods_resource_plugin.hpp\"\n#include \"irods_file_object.hpp\"\n#include \"irods_physical_object.hpp\"\n#include \"irods_collection_object.hpp\"\n#include \"irods_string_tokenize.hpp\"\n#include \"irods_hierarchy_parser.hpp\"\n#include \"irods_logger.hpp\"\n#include \"irods_resource_redirect.hpp\"\n#include \"irods_stacktrace.hpp\"\n#include \"irods_kvp_string_parser.hpp\"\n#include \"irods_lexical_cast.hpp\"\n#include \"irods_random.hpp\"\n#include \"irods_at_scope_exit.hpp\"\n\n\/\/ =-=-=-=-=-=-=-\n\/\/ stl includes\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <string>\n#include <string_view>\n\n\/\/ =-=-=-=-=-=-=-\n\/\/ boost includes\n#include <boost\/lexical_cast.hpp>\n#include <boost\/function.hpp>\n#include <boost\/any.hpp>\n\n#include <fmt\/format.h>\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief constant to reference the operation type for\n\/\/\/         file modification\nconst std::string OPERATION_TYPE( \"operation_type\" );\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief constant to index the cache child resource\nconst std::string CACHE_CONTEXT_TYPE( \"cache\" );\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief constant to index the archive child resource\nconst std::string ARCHIVE_CONTEXT_TYPE( \"archive\" );\n\n\/\/\/ @brief constant indicating the automatic replication policy\nconst std::string AUTO_REPL_POLICY( \"auto_repl\" );\n\n\/\/\/ @brief constant indicating the replication policy is enabled\nconst std::string AUTO_REPL_POLICY_ENABLED( \"on\" );\n\nnamespace\n{\n    auto get_archive_replica_number(\n        const irods::file_object_ptr _obj,\n        const std::string_view _archive_resource_name) -> int\n    {\n        const auto& replicas = _obj->replicas();\n        const auto itr = std::find_if(\n            replicas.cbegin(), replicas.cend(),\n            [&_archive_resource_name] (const auto& _replica)\n            {\n                return _archive_resource_name == resc_mgr.resc_id_to_name(_replica.resc_id());\n            }\n        );\n\n        if (replicas.cend() == itr) {\n            THROW(SYS_REPLICA_DOES_NOT_EXIST, fmt::format(\n                \"no replica found for [{}] on archive resource [{}]\",\n                _obj->logical_path(), _archive_resource_name));\n        }\n\n        return itr->repl_num();\n    } \/\/ get_archive_replica_number\n} \/\/ anonymous namespace\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief Check the general parameters passed in to most plugin functions\ntemplate< typename DEST_TYPE >\ninline irods::error compound_check_param(\n    irods::plugin_context& _ctx ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ ask the context if it is valid\n    irods::error ret = _ctx.valid< DEST_TYPE >();\n    if ( !ret.ok() ) {\n        return PASSMSG( \"resource context is invalid\", ret );\n\n    }\n\n    return SUCCESS();\n\n} \/\/ compound_check_param\n\n\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief helper function to get the next child in the hier string\n\/\/\/        for use when forwarding an operation\ntemplate< typename DEST_TYPE >\nirods::error get_next_child(\n    irods::plugin_context& _ctx,\n    irods::resource_ptr&   _resc ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< DEST_TYPE >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the resource name\n    std::string name;\n    ret = _ctx.prop_map().get< std::string >( irods::RESOURCE_NAME, name );\n    if ( !ret.ok() ) {\n        PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the resource after this resource\n    irods::hierarchy_parser parser;\n    boost::shared_ptr< DEST_TYPE > dst_obj = boost::dynamic_pointer_cast< DEST_TYPE >( _ctx.fco() );\n    parser.set_string( dst_obj->resc_hier() );\n    std::string child;\n    ret = parser.next( name, child );\n    if ( !ret.ok() ) {\n        PASS( ret );\n    }\n\n    irods::resource_child_map* cmap_ref;\n    _ctx.prop_map().get< irods::resource_child_map* >(\n            irods::RESC_CHILD_MAP_PROP,\n            cmap_ref );\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ extract the next resource from the child map\n    if ( cmap_ref->has_entry( child ) ) {\n        std::pair< std::string, irods::resource_ptr > resc_pair;\n        ret = cmap_ref->get( child, resc_pair );\n        if ( !ret.ok() ) {\n            return PASS( ret );\n        }\n        else {\n            _resc = resc_pair.second;\n            return SUCCESS();\n        }\n\n    }\n    else {\n        std::stringstream msg;\n        msg << \"child not found [\" << child << \"]\";\n        return ERROR( SYS_INVALID_INPUT_PARAM, msg.str() );\n\n    }\n\n} \/\/ get_next_child\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief helper function to get the cache resource\nirods::error get_cache(\n    irods::plugin_context& _ctx,\n    irods::resource_ptr&            _resc ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the cache name\n    std::string resc_name;\n    ret = _ctx.prop_map().get< std::string >( CACHE_CONTEXT_TYPE, resc_name );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ extract the resource from the child map\n    irods::resource_child_map* cmap_ref;\n    _ctx.prop_map().get< irods::resource_child_map* >(\n            irods::RESC_CHILD_MAP_PROP,\n            cmap_ref );\n\n    std::pair< std::string, irods::resource_ptr > resc_pair;\n    ret = cmap_ref->get( resc_name, resc_pair );\n    if ( !ret.ok() ) {\n        std::stringstream msg;\n        msg << \"failed to get child resource [\" << resc_name << \"]\";\n        return PASSMSG( msg.str(), ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ assign the resource to the out variable\n    _resc = resc_pair.second;\n\n    return SUCCESS();\n\n} \/\/ get_cache\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief helper function to get the archive resource\nirods::error get_archive(\n    irods::plugin_context& _ctx,\n    irods::resource_ptr&   _resc ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the archive name\n    std::string resc_name;\n    ret = _ctx.prop_map().get< std::string >( ARCHIVE_CONTEXT_TYPE, resc_name );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ extract the resource from the child map\n    irods::resource_child_map* cmap_ref;\n    _ctx.prop_map().get< irods::resource_child_map* >(\n            irods::RESC_CHILD_MAP_PROP,\n            cmap_ref );\n    std::pair< std::string, irods::resource_ptr > resc_pair;\n    ret = cmap_ref->get( resc_name, resc_pair );\n    if ( !ret.ok() ) {\n        std::stringstream msg;\n        msg << \"failed to get child resource [\" << resc_name << \"]\";\n        return PASSMSG( msg.str(), ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ assign the resource to the out variable\n    _resc = resc_pair.second;\n    return SUCCESS();\n\n} \/\/ get_archive\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief Returns the cache resource making sure it corresponds to the fco resc hier\ntemplate< typename DEST_TYPE >\nirods::error get_cache_resc(\n    irods::plugin_context& _ctx,\n    irods::resource_ptr&            _resc ) {\n    irods::error result = SUCCESS();\n    irods::error ret;\n    irods::resource_ptr next_resc;\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the cache resource\n    if ( !( ret = get_cache( _ctx, _resc ) ).ok() ) {\n        std::stringstream msg;\n        msg << \"Failed to get cache resource.\";\n        result = PASSMSG( msg.str(), ret );\n    }\n\n    \/\/ get the next child resource in the hierarchy\n    else if ( !( ret = get_next_child< DEST_TYPE >( _ctx, next_resc ) ).ok() ) {\n        std::stringstream msg;\n        msg << \"Failed to get next child resource.\";\n        result = PASSMSG( msg.str(), ret );\n    }\n\n    \/\/ Make sure the file object came from the cache resource\n    else if ( _resc != next_resc ) {\n        boost::shared_ptr< DEST_TYPE > obj = boost::dynamic_pointer_cast< DEST_TYPE >( _ctx.fco() );\n        std::stringstream msg;\n        msg << \"Cannot open data object: \\\"\";\n        msg << obj->physical_path();\n        msg << \"\\\" It is stored in an archive resource which is not directly accessible.\";\n        result = ERROR( DIRECT_ARCHIVE_ACCESS, msg.str() );\n    }\n\n    return result;\n\n} \/\/ get_cache_resc\n\n\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief helper function to take a rule result, find a keyword and then\n\/\/\/        parse it for the value\nirods::error get_stage_policy(\n    const std::string& _results,\n    std::string& _policy ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get a map of the key value pairs\n    irods::kvp_map_t kvp;\n    irods::error kvp_err = irods::parse_kvp_string(\n                               _results,\n                               kvp );\n    if ( !kvp_err.ok() ) {\n        return PASS( kvp_err );\n    }\n\n    std::string value = kvp[ irods::RESOURCE_STAGE_TO_CACHE_POLICY ];\n    if ( value.empty() ) {\n        return ERROR(\n                   SYS_INVALID_INPUT_PARAM,\n                   \"stage policy value not found\" );\n    }\n    _policy = value;\n\n    return SUCCESS();\n\n} \/\/ get_stage_policy\n\n\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief start up operation - determine which child is the cache and which is the\n\/\/\/        archive.  cache those names in local variables for ease of use\n\/\/\/        must use C linkage for delay_load\nirods::error compound_start_operation(\n    irods::plugin_property_map& _prop_map ) {\n\n    irods::resource_child_map* cmap_ref;\n    _prop_map.get< irods::resource_child_map* >(\n            irods::RESC_CHILD_MAP_PROP,\n            cmap_ref );\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ trap invalid number of children\n    if ( cmap_ref->size() == 0 || cmap_ref->size() > 2 ) {\n        std::stringstream msg;\n        msg << \"compound resource: invalid number of children [\";\n        msg << cmap_ref->size() << \"]\";\n        return ERROR( SYS_INVALID_INPUT_PARAM, msg.str() );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ child map is indexed by name, get first name\n    std::string first_child_name;\n    irods::resource_child_map::iterator itr = cmap_ref->begin();\n    if ( itr == cmap_ref->end() ) {\n        return ERROR( -1, \"child map is empty\" );\n    }\n\n    std::string           first_child_ctx  = itr->second.first;\n    irods::resource_ptr& first_child_resc = itr->second.second;\n    irods::error get_err = first_child_resc->get_property<std::string>( irods::RESOURCE_NAME, first_child_name );\n    if ( !get_err.ok() ) {\n        return PASS( get_err );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get second name\n    std::string second_child_name;\n    itr++;\n    if ( itr == cmap_ref->end() ) {\n        return ERROR( SYS_INVALID_INPUT_PARAM, \"child map has only one entry\" );\n    }\n\n    std::string          second_child_ctx  = itr->second.first;\n    irods::resource_ptr second_child_resc = itr->second.second;\n    get_err = second_child_resc->get_property<std::string>( irods::RESOURCE_NAME, second_child_name );\n    if ( !get_err.ok() ) {\n        return PASS( get_err );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ now if first name is a cache, store that name as such\n    \/\/ otherwise it is the archive\n    \/\/ cmap is a hash map whose payload is a pair< string, resource_ptr >\n    \/\/ the first of which is the parent-child context string denoting\n    \/\/ that either the child is a cache or archive\n    if ( first_child_ctx == CACHE_CONTEXT_TYPE ) {\n        _prop_map[ CACHE_CONTEXT_TYPE ] = first_child_name;\n\n    }\n    else if ( first_child_ctx == ARCHIVE_CONTEXT_TYPE ) {\n        _prop_map[ ARCHIVE_CONTEXT_TYPE ] = first_child_name;\n\n    }\n    else {\n        return ERROR( INVALID_RESC_CHILD_CONTEXT, first_child_ctx );\n\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ do the same for the second resource\n    if ( second_child_ctx == CACHE_CONTEXT_TYPE ) {\n        _prop_map[ CACHE_CONTEXT_TYPE ] = second_child_name;\n\n    }\n    else if ( second_child_ctx == ARCHIVE_CONTEXT_TYPE ) {\n        _prop_map[ ARCHIVE_CONTEXT_TYPE ] = second_child_name;\n\n    }\n    else {\n        return ERROR( INVALID_RESC_CHILD_CONTEXT, second_child_ctx );\n\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ if both context strings match, this is also an error\n    if ( first_child_ctx == second_child_ctx ) {\n        std::stringstream msg;\n        msg << \"matching child context strings :: \";\n        msg << \"[\" << first_child_ctx  << \"] vs \";\n        msg << \"[\" << second_child_ctx << \"]\";\n        return ERROR( INVALID_RESC_CHILD_CONTEXT, msg.str() );\n\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ and... were done.\n    return SUCCESS();\n\n} \/\/ compound_start_operation\n\nnamespace {\n\n    using log = irods::experimental::log;\n\n    int open_source_replica(\n        irods::plugin_context& _ctx,\n        irods::file_object_ptr obj,\n        const std::string& src_hier)\n    {\n        \/\/ Open source replica\n        dataObjInp_t source_data_obj_inp{};\n        rstrcpy( source_data_obj_inp.objPath, obj->logical_path().c_str(), MAX_NAME_LEN );\n        copyKeyVal( ( keyValPair_t* )&obj->cond_input(), &source_data_obj_inp.condInput );\n\n        \/\/ When staging a replica to cache, the source is the archive -- need some special sauce\n        char* stage = getValByKey( ( keyValPair_t* )&obj->cond_input(), STAGE_OBJ_KW );\n        if ( stage ) {\n            addKeyVal( &source_data_obj_inp.condInput, STAGE_OBJ_KW, \"\" );\n            addKeyVal( &source_data_obj_inp.condInput, NO_OPEN_FLAG_KW, \"\" );\n            if (getValByKey(&source_data_obj_inp.condInput, PURGE_CACHE_KW)) {\n                rmKeyVal(&source_data_obj_inp.condInput, PURGE_CACHE_KW);\n            }\n        }\n\n        source_data_obj_inp.oprType = REPLICATE_SRC;\n        source_data_obj_inp.openFlags = O_RDONLY;\n        addKeyVal( &source_data_obj_inp.condInput, RESC_HIER_STR_KW, src_hier.c_str() );\n        int source_l1descInx = rsDataObjOpen(_ctx.comm(), &source_data_obj_inp);\n        if ( source_l1descInx < 0 ) {\n            std::stringstream msg;\n            msg << \"Failed to open source for [\" << obj->logical_path() << \"] \";\n            irods::log(LOG_ERROR, msg.str());\n            THROW(source_l1descInx, msg.str());\n        }\n        return source_l1descInx;\n    } \/\/ open_source_replica\n\n    int open_destination_replica(\n        irods::plugin_context& _ctx,\n        irods::file_object_ptr obj,\n        const int _source_l1_desc_inx,\n        const std::string& dst_hier)\n    {\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ create a data obj input struct to call rsDataObjRepl which given\n        \/\/ the _stage_sync_kw will either stage or sync the data object\n        dataObjInp_t destination_data_obj_inp{};\n        rstrcpy( destination_data_obj_inp.objPath, obj->logical_path().c_str(), MAX_NAME_LEN );\n        destination_data_obj_inp.createMode = obj->mode();\n\n        copyKeyVal( ( keyValPair_t* )&obj->cond_input(), &destination_data_obj_inp.condInput );\n        rmKeyVal( &destination_data_obj_inp.condInput, PURGE_CACHE_KW ); \/\/ do not want to accidentally purge\n\n        char* no_chk = getValByKey( ( keyValPair_t* )&obj->cond_input(), NO_CHK_COPY_LEN_KW );\n        if ( no_chk ) {\n            addKeyVal( &destination_data_obj_inp.condInput, NO_CHK_COPY_LEN_KW, no_chk );\n        }\n\n        \/\/ When syncing a replica to archive, the destination is the archive -- need some special sauce\n        char* sync = getValByKey( ( keyValPair_t* )&obj->cond_input(), SYNC_OBJ_KW );\n        if ( sync ) {\n            addKeyVal( &destination_data_obj_inp.condInput, SYNC_OBJ_KW, \"\" );\n            addKeyVal( &destination_data_obj_inp.condInput, NO_OPEN_FLAG_KW, \"\" );\n            if (getValByKey(&destination_data_obj_inp.condInput, PURGE_CACHE_KW)) {\n                rmKeyVal(&destination_data_obj_inp.condInput, PURGE_CACHE_KW);\n            }\n        }\n\n        addKeyVal( &destination_data_obj_inp.condInput, RESC_HIER_STR_KW, dst_hier.c_str() );\n\n        addKeyVal(&destination_data_obj_inp.condInput, REG_REPL_KW, \"\");\n        addKeyVal(&destination_data_obj_inp.condInput, FORCE_FLAG_KW, \"\");\n        addKeyVal(&destination_data_obj_inp.condInput, SOURCE_L1_DESC_KW, std::to_string(_source_l1_desc_inx).c_str());\n        destination_data_obj_inp.oprType = REPLICATE_DEST;\n        destination_data_obj_inp.openFlags = O_CREAT | O_RDWR;\n\n        int destination_l1descInx = rsDataObjOpen(_ctx.comm(), &destination_data_obj_inp);\n        if ( destination_l1descInx < 0 ) {\n            THROW(destination_l1descInx,\n                  (boost::format(\"Failed to open destination for [%s]\") %\n                   destination_data_obj_inp.objPath).str().c_str());\n        }\n        return destination_l1descInx;\n    } \/\/ open_destination_replica\n\n    int close_replica(\n        irods::plugin_context& _ctx,\n        const int l1descInx) {\n        openedDataObjInp_t data_obj_close_inp{};\n        data_obj_close_inp.l1descInx = l1descInx;\n        L1desc[data_obj_close_inp.l1descInx].oprStatus = l1descInx;\n        addKeyVal(&data_obj_close_inp.condInput, IN_PDMO_KW, L1desc[l1descInx].dataObjInfo->rescHier);\n        int close_status = rsDataObjClose( _ctx.comm(), &data_obj_close_inp);\n        if (close_status < 0) {\n            rodsLog(LOG_ERROR, \"[%s] - rsDataObjClose failed with [%d]\", __FUNCTION__, close_status);\n        }\n        clearKeyVal( &data_obj_close_inp.condInput );\n        return close_status;\n    }\n}\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief replicate a given object for either a sync or a stage\nirods::error repl_object(\n    irods::plugin_context& _ctx,\n    const irods::hierarchy_parser& _hier_from_root_to_compound,\n    const std::string_view _stage_sync_kw)\n{\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ error check incoming params\n    if (_stage_sync_kw.empty()) {\n        return ERROR(SYS_INVALID_INPUT_PARAM, \"empty _stage_sync_kw.\");\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the parent name\n    std::string parent_id_str;\n    irods::error ret = _ctx.prop_map().get< std::string >( irods::RESOURCE_PARENT, parent_id_str );\n    if (!ret.ok()) {\n        return PASSMSG(\"Failed to get the parent name.\", ret);\n    }\n\n    std::string parent_name;\n    ret = resc_mgr.resc_id_to_name(\n            parent_id_str,\n            parent_name );\n    if(!ret.ok()) {\n        return PASS(ret);\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the cache name\n    std::string cache_name;\n    ret = _ctx.prop_map().get< std::string >( CACHE_CONTEXT_TYPE, cache_name );\n    if (!ret.ok()) {\n        return PASSMSG(\"Failed to get the cache name.\", ret);\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the archive name\n    std::string arch_name;\n    ret = _ctx.prop_map().get< std::string >( ARCHIVE_CONTEXT_TYPE, arch_name );\n    if (!ret.ok()) {\n        return PASSMSG(\"Failed to get the archive name.\", ret);\n    } \/\/ if arch_name\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ manufacture a resc hier to either the archive or the cache resc\n    std::string keyword  = _stage_sync_kw.data();\n    std::string inp_hier = _hier_from_root_to_compound.str();\n\n    std::string tgt_name, src_name;\n    if ( keyword == STAGE_OBJ_KW ) {\n        tgt_name = cache_name;\n        src_name = arch_name;\n    }\n    else if ( keyword == SYNC_OBJ_KW ) {\n        tgt_name = arch_name;\n        src_name = cache_name;\n    }\n    else {\n        std::stringstream msg;\n        msg << \"stage_sync_kw value is unexpected [\" << _stage_sync_kw.data() << \"]\";\n        return ERROR( SYS_INVALID_INPUT_PARAM, msg.str() );\n    }\n\n    std::string current_name;\n    ret = _ctx.prop_map().get<std::string>( irods::RESOURCE_NAME, current_name );\n    if (!ret.ok()) {\n        return PASSMSG(\"Failed to get the resource name.\", ret);\n    } \/\/ if current_name\n\n    size_t pos = inp_hier.find( parent_name );\n    if ( std::string::npos == pos ) {\n        std::stringstream msg;\n        msg << \"parent resc [\"\n            << parent_name\n            << \"] not in fco resc hier [\"\n            << inp_hier\n            << \"]\";\n        return ERROR(\n                SYS_INVALID_INPUT_PARAM,\n                msg.str() );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ Generate src and tgt hiers\n    std::string dst_hier = inp_hier.substr( 0, pos + parent_name.size() );\n    if ( !dst_hier.empty() ) {\n        dst_hier += irods::hierarchy_parser::delimiter();\n    }\n    dst_hier += current_name +\n        irods::hierarchy_parser::delimiter() +\n        tgt_name;\n\n    std::string src_hier = inp_hier.substr( 0, pos + parent_name.size() );\n    if ( !src_hier.empty() ) {\n        src_hier += irods::hierarchy_parser::delimiter();\n    }\n    src_hier += current_name + irods::hierarchy_parser::delimiter() + src_name;\n\n    irods::file_object_ptr obj = boost::dynamic_pointer_cast< irods::file_object >( _ctx.fco() );\n    addKeyVal((keyValPair_t*)&obj->cond_input(), _stage_sync_kw.data(), \"\");\n\n    int source_l1descInx{};\n    int destination_l1descInx{};\n    const irods::at_scope_exit close_l1_descriptors{\n        [&]()\n        {\n            if (destination_l1descInx > 0) {\n                close_replica(_ctx, destination_l1descInx);\n            }\n            if (source_l1descInx > 0) {\n                close_replica(_ctx, source_l1descInx);\n            }\n        }\n    };\n    if (STAGE_OBJ_KW == keyword) {\n        try {\n            source_l1descInx = open_source_replica(_ctx, obj, src_hier);\n            destination_l1descInx = open_destination_replica(_ctx, obj, source_l1descInx, dst_hier);\n            L1desc[destination_l1descInx].srcL1descInx = source_l1descInx;\n        }\n        catch (const irods::exception& _e) {\n            irods::log(_e);\n            return irods::error(_e);\n        }\n\n        irods::resource_ptr resc;\n        ret = get_archive( _ctx, resc );\n        if ( !ret.ok() ) {\n            std::stringstream msg;\n            msg << \"failed to get child resource [\" << current_name << \"]\";\n            return PASSMSG( msg.str(), ret );\n        }\n\n        irods::file_object_ptr file_obj(\n                new irods::file_object(\n                    _ctx.comm(),\n                    obj->logical_path().c_str(),\n                    L1desc[source_l1descInx].dataObjInfo->filePath, \"\", 0,\n                    getDefFileMode(),\n                    L1desc[source_l1descInx].dataObjInfo->flags ) );\n        file_obj->resc_hier( src_hier );\n\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ pass condInput\n        file_obj->cond_input( L1desc[destination_l1descInx].dataObjInp->condInput );\n\n        \/\/ set object id if provided\n        char *id_str = getValByKey(&file_obj->cond_input(), DATA_ID_KW);\n        if (id_str) {\n            file_obj->id(strtol(id_str, NULL, 10));\n        }\n\n        dataObjInfo_t* destDataObjInfo = L1desc[destination_l1descInx].dataObjInfo;\n        dataObjInfo_t* srcDataObjInfo = L1desc[source_l1descInx].dataObjInfo;\n\n        fileStageSyncInp_t file_stage{};\n        rstrcpy( file_stage.cacheFilename, destDataObjInfo->filePath, MAX_NAME_LEN );\n        rstrcpy( file_stage.rescHier,      destDataObjInfo->rescHier, MAX_NAME_LEN );\n        rstrcpy( file_stage.filename,      srcDataObjInfo->filePath,  MAX_NAME_LEN );\n        rstrcpy( file_stage.objPath,       srcDataObjInfo->objPath,   MAX_NAME_LEN );\n        file_stage.dataSize = srcDataObjInfo->dataSize;\n        file_stage.mode = getFileMode(L1desc[destination_l1descInx].dataObjInp);\n\n        int status = rsFileStageToCache(_ctx.comm(), &file_stage);\n        if (status < 0) {\n            ret = ERROR(status, \"rsFileStageToCache failed\");\n        }\n    }\n    else if (SYNC_OBJ_KW == keyword) {\n        try {\n            source_l1descInx = open_source_replica(_ctx, obj, src_hier);\n            destination_l1descInx = open_destination_replica(_ctx, obj, source_l1descInx, dst_hier);\n            L1desc[destination_l1descInx].srcL1descInx = source_l1descInx;\n        }\n        catch (const irods::exception& _e) {\n            irods::log(_e);\n            return irods::error(_e);\n        }\n\n        irods::resource_ptr resc;\n        ret = get_archive( _ctx, resc );\n        if ( !ret.ok() ) {\n            std::stringstream msg;\n            msg << \"failed to get child resource [\" << current_name << \"]\";\n            return PASSMSG( msg.str(), ret );\n        }\n\n        irods::file_object_ptr file_obj(\n                new irods::file_object(\n                    _ctx.comm(),\n                    obj->logical_path().c_str(),\n                    L1desc[destination_l1descInx].dataObjInfo->filePath, \"\", 0,\n                    getDefFileMode(),\n                    L1desc[destination_l1descInx].dataObjInfo->flags ) );\n        file_obj->resc_hier( L1desc[destination_l1descInx].dataObjInfo->rescHier );\n\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ pass condInput\n        file_obj->cond_input( L1desc[destination_l1descInx].dataObjInp->condInput );\n\n        \/\/ set object id if provided\n        char *id_str = getValByKey(&file_obj->cond_input(), DATA_ID_KW);\n        if (id_str) {\n            file_obj->id(strtol(id_str, NULL, 10));\n        }\n\n        \/\/ret = resc->call<const char*>( _ctx.comm(), irods::RESOURCE_OP_SYNCTOARCH, file_obj, L1desc[source_l1descInx].dataObjInfo->filePath );\n\n        \/\/ Sync to archive!\n        int dst_create_path = 0;\n        irods::error err = resc->get_property<int>(irods::RESOURCE_CREATE_PATH, dst_create_path);\n        if (!err.ok()) {\n            irods::log(PASS(err));\n        }\n\n        dataObjInfo_t* destDataObjInfo = L1desc[destination_l1descInx].dataObjInfo;\n        dataObjInfo_t* srcDataObjInfo = L1desc[source_l1descInx].dataObjInfo;\n        if (CREATE_PATH == dst_create_path) {\n            dataObjInfo_t tmpDataObjInfo{};\n            int status = chkOrphanFile(\n                _ctx.comm(),\n                destDataObjInfo->filePath,\n                destDataObjInfo->rescName,\n                &tmpDataObjInfo);\n            if ( status == 0 && tmpDataObjInfo.dataId != destDataObjInfo->dataId ) {\n                \/* someone is using it *\/\n                char tmp_str[MAX_NAME_LEN]{};\n                snprintf(tmp_str, MAX_NAME_LEN, \"%s.%-u\", destDataObjInfo->filePath, irods::getRandom<unsigned int>());\n                rstrcpy(destDataObjInfo->filePath, tmp_str, MAX_NAME_LEN);\n            }\n        }\n\n        fileStageSyncInp_t inp{};\n        inp.dataSize = srcDataObjInfo->dataSize;\n\n        rstrcpy( inp.filename,      destDataObjInfo->filePath,  MAX_NAME_LEN );\n        rstrcpy( inp.rescHier,      destDataObjInfo->rescHier,  MAX_NAME_LEN );\n        rstrcpy( inp.objPath,       srcDataObjInfo->objPath,    MAX_NAME_LEN );\n        rstrcpy( inp.cacheFilename, srcDataObjInfo->filePath,   MAX_NAME_LEN );\n\n        \/\/ add object id keyword to pass down to resource plugins\n        const std::string object_id = boost::lexical_cast<std::string>(srcDataObjInfo->dataId);\n        addKeyVal(&inp.condInput, DATA_ID_KW, object_id.c_str());\n\n        inp.mode = getFileMode(L1desc[destination_l1descInx].dataObjInp);\n        fileSyncOut_t* sync_out = 0;\n        int status = rsFileSyncToArch(_ctx.comm(), &inp, &sync_out );\n\n        \/\/ Need to update the physical path with whatever the archive resource came up with\n        if (status >= 0 && CREATE_PATH == dst_create_path) {\n            rstrcpy( destDataObjInfo->filePath, sync_out->file_name, MAX_NAME_LEN );\n        }\n    }\n\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    if ( destination_l1descInx < 0 ) {\n        std::stringstream msg;\n        msg << \"Failed to replicate the data object [\" << obj->logical_path() << \"] \";\n        msg << \"for operation [\" << _stage_sync_kw.data() << \"]\";\n        irods::log(LOG_ERROR, msg.str());\n        return ERROR( destination_l1descInx, msg.str() );\n    }\n\n    return SUCCESS();\n} \/\/ repl_object\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX create\nirods::error compound_file_create(\n    irods::plugin_context& _ctx ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the next child resource\n    irods::resource_ptr resc;\n    ret = get_next_child< irods::file_object >( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call( _ctx.comm(), irods::RESOURCE_OP_CREATE, _ctx.fco() );\n\n} \/\/ compound_file_create\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX Open\nirods::error compound_file_open(\n    irods::plugin_context& _ctx ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the cache resource\n    irods::resource_ptr cache_resc;\n    if ( !( ret = get_cache_resc< irods::file_object >( _ctx, cache_resc ) ).ok() ) {\n        std::stringstream msg;\n        msg << \"Failed to get cache resource.\";\n        return PASSMSG( msg.str(), ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return cache_resc->call( _ctx.comm(), irods::RESOURCE_OP_OPEN, _ctx.fco() );\n\n} \/\/ compound_file_open\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX Read\nirods::error compound_file_read(\n    irods::plugin_context& _ctx,\n    void*                  _buf,\n    const int              _len ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the cache resource\n    irods::resource_ptr resc;\n    ret = get_cache( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"Unable to get cache resource.\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call< void*, const int >( _ctx.comm(), irods::RESOURCE_OP_READ, _ctx.fco(), _buf, _len );\n\n} \/\/ compound_file_read\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX Write\nirods::error compound_file_write(\n    irods::plugin_context& _ctx,\n    const void*            _buf,\n    const int              _len ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the cache resource\n    irods::resource_ptr resc;\n    ret = get_cache( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call< const void*, const int >( _ctx.comm(), irods::RESOURCE_OP_WRITE, _ctx.fco(), _buf, _len );\n\n} \/\/ compound_file_write\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX Close\nirods::error compound_file_close(\n    irods::plugin_context& _ctx ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the cache resource\n    irods::resource_ptr resc;\n    ret = get_cache( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    ret = resc->call( _ctx.comm(), irods::RESOURCE_OP_CLOSE, _ctx.fco() );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n\n    }\n\n    return SUCCESS();\n\n} \/\/ compound_file_close\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX Unlink\nirods::error compound_file_unlink(\n    irods::plugin_context& _ctx ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::data_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the next child resource\n    irods::resource_ptr resc;\n    ret = get_next_child< irods::data_object >( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call( _ctx.comm(), irods::RESOURCE_OP_UNLINK, _ctx.fco() );\n\n} \/\/ compound_file_unlink\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX Stat\nirods::error compound_file_stat(\n    irods::plugin_context& _ctx,\n    struct stat*                     _statbuf ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::data_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the next child resource\n    irods::resource_ptr resc;\n    ret = get_next_child< irods::data_object >( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call< struct stat* >( _ctx.comm(), irods::RESOURCE_OP_STAT, _ctx.fco(), _statbuf );\n\n} \/\/ compound_file_stat\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX lseek\nirods::error compound_file_lseek(\n    irods::plugin_context& _ctx,\n    const long long        _offset,\n    const int              _whence ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the next child resource\n    irods::resource_ptr resc;\n    ret = get_next_child< irods::file_object >( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call< const long long, const int >( _ctx.comm(), irods::RESOURCE_OP_LSEEK, _ctx.fco(), _offset, _whence );\n\n} \/\/ compound_file_lseek\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX mkdir\nirods::error compound_file_mkdir(\n    irods::plugin_context& _ctx ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::collection_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the next child resource\n    irods::resource_ptr resc;\n    ret = get_next_child< irods::collection_object >( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call( _ctx.comm(), irods::RESOURCE_OP_MKDIR, _ctx.fco() );\n\n} \/\/ compound_file_mkdir\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX rmdir\nirods::error compound_file_rmdir(\n    irods::plugin_context& _ctx ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::collection_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the next child resource\n    irods::resource_ptr resc;\n    ret = get_next_child< irods::collection_object >( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call( _ctx.comm(), irods::RESOURCE_OP_RMDIR, _ctx.fco() );\n\n} \/\/ compound_file_rmdir\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX opendir\nirods::error compound_file_opendir(\n    irods::plugin_context& _ctx ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::collection_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the next child resource\n    irods::resource_ptr resc;\n    ret = get_next_child< irods::collection_object >( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call( _ctx.comm(), irods::RESOURCE_OP_OPENDIR, _ctx.fco() );\n\n} \/\/ compound_file_opendir\n\n\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX closedir\nirods::error compound_file_closedir(\n    irods::plugin_context& _ctx ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::collection_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the next child resource\n    irods::resource_ptr resc;\n    ret = get_next_child< irods::collection_object >( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call( _ctx.comm(), irods::RESOURCE_OP_CLOSEDIR, _ctx.fco() );\n\n} \/\/ compound_file_closedir\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX readdir\nirods::error compound_file_readdir(\n    irods::plugin_context& _ctx,\n    struct rodsDirent**                 _dirent_ptr ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::collection_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the next child resource\n    irods::resource_ptr resc;\n    ret = get_next_child< irods::collection_object >( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call< struct rodsDirent** >( _ctx.comm(), irods::RESOURCE_OP_READDIR, _ctx.fco(), _dirent_ptr );\n\n} \/\/ compound_file_readdir\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX rename\nirods::error compound_file_rename(\n    irods::plugin_context& _ctx,\n    const char*                      _new_file_name ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::data_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the next child resource\n    irods::resource_ptr resc;\n    ret = get_next_child< irods::data_object >( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call<const char*>( _ctx.comm(), irods::RESOURCE_OP_RENAME, _ctx.fco(), _new_file_name );\n\n} \/\/ compound_file_rename\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface for POSIX truncate\nirods::error compound_file_truncate(\n    irods::plugin_context& _ctx ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::data_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the next child resource\n    irods::resource_ptr resc;\n    ret = get_next_child< irods::data_object >( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call( _ctx.comm(), irods::RESOURCE_OP_TRUNCATE, _ctx.fco() );\n\n} \/\/ compound_file_truncate\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface to determine free space on a device given a path\nirods::error compound_file_getfs_freespace(\n    irods::plugin_context& _ctx ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context for validity\n    irods::error ret = compound_check_param< irods::data_object >( _ctx );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"invalid resource context\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the next child resource\n    irods::resource_ptr resc;\n    ret = get_next_child< irods::data_object >( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call\n    return resc->call(\n               _ctx.comm(),\n               irods::RESOURCE_OP_FREESPACE,\n               _ctx.fco() );\n\n} \/\/ compound_file_getfs_freespace\n\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief Move data from the archive leaf node to a local cache leaf node\n\/\/\/        This routine is not supported from a coordinating node's perspective\n\/\/\/        the coordinating node would be calling this on a leaf when necessary\nirods::error compound_file_stage_to_cache(\n    irods::plugin_context& _ctx,\n    const char*                      _cache_file_name ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ Check the operation parameters and update the physical path\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if ( !ret.ok() ) {\n        std::stringstream msg;\n        msg << \"Invalid resource context\";\n        return PASSMSG( msg.str(), ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the archive resource\n    irods::resource_ptr resc;\n    ret = get_archive( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call to the archive\n    return resc->call< const char* >( _ctx.comm(), irods::RESOURCE_OP_STAGETOCACHE, _ctx.fco(), _cache_file_name );\n\n} \/\/ compound_file_stage_to_cache\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief Move data from a local cache leaf node to the archive leaf node\n\/\/\/        This routine is not supported from a coordinating node's perspective\n\/\/\/        the coordinating node would be calling this on a leaf when necessary\nirods::error compound_file_sync_to_arch(\n    irods::plugin_context& _ctx,\n    const char*                      _cache_file_name ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ Check the operation parameters and update the physical path\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if ( !ret.ok() ) {\n        std::stringstream msg;\n        msg << \"Invalid resource context\";\n        return PASSMSG( msg.str(), ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the archive resource\n    irods::resource_ptr resc;\n    get_archive( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward the call to the archive\n    return resc->call< const char* >( _ctx.comm(), irods::RESOURCE_OP_SYNCTOARCH, _ctx.fco(), _cache_file_name );\n\n} \/\/ compound_file_sync_to_arch\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface to notify of a file registration\nirods::error compound_file_registered(\n    irods::plugin_context& _ctx ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ Check the operation parameters and update the physical path\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if ( !ret.ok() ) {\n        std::stringstream msg;\n        msg << \"Invalid resource context\";\n        return PASSMSG( msg.str(), ret );\n    }\n\n    return SUCCESS();\n\n} \/\/ compound_file_registered\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface to notify of a file unregistration\nirods::error compound_file_unregistered(\n    irods::plugin_context& _ctx ) {\n    \/\/ Check the operation parameters and update the physical path\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if ( !ret.ok() ) {\n        std::stringstream msg;\n        msg << \"Invalid resource context\";\n        return PASSMSG( msg.str(), ret );\n    }\n    \/\/ NOOP\n    return SUCCESS();\n\n} \/\/ compound_file_unregistered\n\nstatic bool auto_replication_is_enabled(\n    irods::plugin_context& _ctx ) {\n    std::string auto_repl;\n    irods::error ret = _ctx.prop_map().get<std::string>(\n                           AUTO_REPL_POLICY,\n                           auto_repl );\n    if( ret.ok() ) {\n        if( AUTO_REPL_POLICY_ENABLED != auto_repl ) {\n            return false;\n        }\n    }\n    return true;\n} \/\/ auto_replication_is_enabled\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface to notify of a file modification - this happens\n\/\/\/        after the close operation and the icat should be up to date\n\/\/\/        at this point\nirods::error compound_file_modified(\n    irods::plugin_context& _ctx ) {\n    irods::error result = SUCCESS();\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ Check the operation parameters and update the physical path\n    if(!auto_replication_is_enabled(_ctx)) {\n        return SUCCESS();\n    }\n\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if (!ret.ok()) {\n        return PASSMSG(\"Invalid resource context.\", ret);\n    }\n\n    std::string name{};\n    ret = _ctx.prop_map().get<std::string>( irods::RESOURCE_NAME, name );\n    if (!ret.ok()) {\n        return PASSMSG(\"Failed to get the resource name.\", ret);\n    }\n\n    irods::file_object_ptr file_obj = boost::dynamic_pointer_cast<irods::file_object>(_ctx.fco());\n    irods::hierarchy_parser sub_parser;\n    sub_parser.set_string( file_obj->in_pdmo() );\n    if ( !sub_parser.resc_in_hier( name ) ) {\n        irods::hierarchy_parser parser{file_obj->resc_hier()};\n        result = repl_object( _ctx, parser, SYNC_OBJ_KW );\n    }\n    return result;\n\n} \/\/ compound_file_modified\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief interface to notify of a file operation\nirods::error compound_file_notify(\n    irods::plugin_context& _ctx,\n    const std::string*               _opr ) {\n    irods::error result = SUCCESS();\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ Check the operation parameters and update the physical path\n    irods::error ret = compound_check_param< irods::file_object >( _ctx );\n    if ( ( result = ASSERT_PASS( ret, \"Invalid resource context.\" ) ).ok() ) {\n        std::string operation;\n        ret = _ctx.prop_map().get< std::string >( OPERATION_TYPE, operation );\n        if ( ret.ok() ) {\n            rodsLog(\n                LOG_DEBUG,\n                \"compound_file_notify - oper [%s] changed to [%s]\",\n                _opr->c_str(),\n                operation.c_str() );\n        } \/\/ if ret ok\n        if ( irods::WRITE_OPERATION == ( *_opr ) ||\n                irods::CREATE_OPERATION == ( *_opr ) ) {\n            _ctx.prop_map().set< std::string >( OPERATION_TYPE, ( *_opr ) );\n        }\n        else {\n            rodsLog(\n                LOG_DEBUG,\n                \"compound_file_notify - skipping [%s]\",\n                _opr->c_str() );\n        }\n\n    } \/\/ if valid\n\n    return result;\n\n} \/\/ compound_file_notify\n\n\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief - code to determine redirection for create operation\nirods::error compound_file_redirect_create(\n    irods::plugin_context& _ctx,\n    const std::string&               _operation,\n    const std::string*               _curr_host,\n    irods::hierarchy_parser*        _out_parser,\n    float*                           _out_vote ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ determine if the resource is down\n    int resc_status = 0;\n    irods::error ret = _ctx.prop_map().get< int >( irods::RESOURCE_STATUS, resc_status );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"failed to get 'status' property\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ if the status is down, vote no.\n    if ( INT_RESC_STATUS_DOWN == resc_status ) {\n        ( *_out_vote ) = 0.0;\n        return SUCCESS();\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the cache resource\n    irods::resource_ptr resc;\n    ret = get_cache( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ ask the cache if it is willing to accept a new file, politely\n    ret = resc->call < const std::string*, const std::string*,\n    irods::hierarchy_parser*, float* > (\n        _ctx.comm(), irods::RESOURCE_OP_RESOLVE_RESC_HIER, _ctx.fco(),\n        &_operation, _curr_host,\n        _out_parser, _out_vote );\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ set the operation type to signal that we need to do some work\n    \/\/ in file modified\n    _ctx.prop_map().set< std::string >( OPERATION_TYPE, _operation );\n\n    return ret;\n\n} \/\/ compound_file_redirect_create\n\n\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief - code to determine redirection for unlink operation\nirods::error compound_file_redirect_unlink(\n    irods::plugin_context& _ctx,\n    const std::string&               _operation,\n    const std::string*               _curr_host,\n    irods::hierarchy_parser*         _out_parser,\n    float*                           _out_vote ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ determine if the resource is down\n    int resc_status = 0;\n    irods::error ret = _ctx.prop_map().get< int >( irods::RESOURCE_STATUS, resc_status );\n    if ( !ret.ok() ) {\n        return PASSMSG( \"failed to get 'status' property\", ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ if the status is down, vote no.\n    if ( INT_RESC_STATUS_DOWN == resc_status ) {\n        ( *_out_vote ) = 0.0;\n        return SUCCESS();\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the cache resource\n    irods::resource_ptr resc;\n    ret = get_cache( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    std::string cache_name;\n    _ctx.prop_map().get< std::string >( CACHE_CONTEXT_TYPE, cache_name );\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ ask the cache if it is willing to accept a new file, politely\n    ret = resc->call < const std::string*, const std::string*,\n    irods::hierarchy_parser*, float* > (\n        _ctx.comm(), irods::RESOURCE_OP_RESOLVE_RESC_HIER, _ctx.fco(),\n        &_operation, _curr_host,\n        _out_parser, _out_vote );\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ if cache votes non zero we're done\n    if (*_out_vote > 0.0) {\n        return SUCCESS();\n    }\n\n    \/\/ unixfilesystem adds itself to the hierarchy - remove here as it voted 0\n    \/\/ TODO: hierarchies as a cache\/archive would break here\n    _out_parser->remove_resource(cache_name);\n\n    std::string archive_name;\n    _ctx.prop_map().get< std::string >( ARCHIVE_CONTEXT_TYPE, archive_name );\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ otherwise try the archive\n    ret = get_archive( _ctx, resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ ask the archive if it is willing to accept a new file, politely\n    ret = resc->call<const std::string*, const std::string*, irods::hierarchy_parser*, float*> (\n        _ctx.comm(), irods::RESOURCE_OP_RESOLVE_RESC_HIER, _ctx.fco(),\n        &_operation, _curr_host, _out_parser, _out_vote );\n\n    return ret;\n\n} \/\/ compound_file_redirect_unlink\n\n\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief - handler for prefer archive policy\nirods::error open_for_prefer_archive_policy(\n    irods::plugin_context& _ctx,\n    const std::string&               _curr_host,\n    irods::hierarchy_parser&        _out_parser,\n    float&                           _out_vote ) {\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the archive resource\n    irods::resource_ptr arch_resc;\n    irods::error ret = get_archive( _ctx, arch_resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the archive resource\n    irods::resource_ptr cache_resc;\n    ret = get_cache( _ctx, cache_resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    std::string operation{irods::OPEN_OPERATION};\n    ret = _ctx.prop_map().get<std::string>(OPERATION_TYPE, operation);\n    if (!ret.ok()) {\n        rodsLog(LOG_NOTICE, \"[%s] - operation not found in property map; using open.\", __FUNCTION__);\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ repave the repl requested temporarily\n    irods::file_object_ptr f_ptr = boost::dynamic_pointer_cast< irods::file_object >( _ctx.fco() );\n    int repl_requested = f_ptr->repl_requested();\n    const irods::at_scope_exit restore_repl_requested{[&] { f_ptr->repl_requested(repl_requested); }};\n\n    float                    arch_check_vote   = 0.0;\n    irods::hierarchy_parser arch_check_parser = _out_parser;\n\n    try {\n        std::string archive_name;\n        _ctx.prop_map().get<std::string>(ARCHIVE_CONTEXT_TYPE, archive_name);\n        f_ptr->repl_requested(get_archive_replica_number(f_ptr, archive_name));\n\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ ask the archive if it has the data object in question, politely\n        ret = arch_resc->call < const std::string*, const std::string*,\n        irods::hierarchy_parser*, float* > (\n            _ctx.comm(), irods::RESOURCE_OP_RESOLVE_RESC_HIER, _ctx.fco(),\n            &operation, &_curr_host,\n            &arch_check_parser, &arch_check_vote );\n    }\n    catch (const irods::exception& e) {\n        \/\/ continue to the cache vote because failed vote isn't necessarily an error\n        arch_check_vote = 0.0;\n        irods::log(LOG_DEBUG, fmt::format(\"[{}:{}] - [{}]\", __FUNCTION__, __LINE__, e.what()));\n    }\n\n    if ( !ret.ok() || 0.0 == arch_check_vote ) {\n        rodsLog(\n            LOG_DEBUG,\n            \"replica not found in archive for [%s]\",\n            f_ptr->logical_path().c_str() );\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ the archive query redirect failed, something terrible happened\n        \/\/ or mounted collection hijinks are afoot.  ask the cache if it\n        \/\/ has the data object in question, politely as a fallback\n        float                    cache_check_vote   = 0.0;\n        irods::hierarchy_parser cache_check_parser = _out_parser;\n        ret = cache_resc->call < const std::string*, const std::string*,\n        irods::hierarchy_parser*, float* > (\n            _ctx.comm(), irods::RESOURCE_OP_RESOLVE_RESC_HIER, _ctx.fco(),\n            &operation, &_curr_host,\n            &cache_check_parser, &cache_check_vote );\n        if ( !ret.ok() ) {\n            return PASS( ret );\n        }\n\n        if( 0.0 == cache_check_vote ) {\n            _out_vote = 0.0;\n            return SUCCESS();\n        }\n\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ set the vote and hier parser\n        _out_parser = cache_check_parser;\n        _out_vote   = cache_check_vote;\n\n        return SUCCESS();\n\n    }\n\n    irods::data_object_ptr d_ptr = boost::dynamic_pointer_cast <\n                                   irods::data_object > ( f_ptr );\n    add_key_val(\n        d_ptr,\n        NO_CHK_COPY_LEN_KW,\n        \"prefer_archive_policy\" );\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ if the vote is 0 then we do a wholesale stage, not an update\n    \/\/ otherwise it is an update operation for the stage to cache\n    ret = repl_object( _ctx, _out_parser, STAGE_OBJ_KW );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    remove_key_val(\n        d_ptr,\n        NO_CHK_COPY_LEN_KW );\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the parent name\n    std::string parent_id_str;\n    ret = _ctx.prop_map().get< std::string >( irods::RESOURCE_PARENT, parent_id_str );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    std::string parent_name;\n    ret = resc_mgr.resc_id_to_name(\n             parent_id_str,\n             parent_name );\n    if(!ret.ok()) {\n        return PASS(ret);\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get this resc name\n    std::string current_name;\n    ret = _ctx.prop_map().get<std::string>( irods::RESOURCE_NAME, current_name );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the cache name\n    std::string cache_name;\n    ret = _ctx.prop_map().get< std::string >( CACHE_CONTEXT_TYPE, cache_name );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the current hier\n    std::string inp_hier = _out_parser.str();\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ find the parent in the hier\n    \/\/ TODO: the input hierarchy is some other hierarchy\n    size_t pos = inp_hier.find( parent_name );\n    if ( std::string::npos == pos ) {\n        return ERROR(\n                   SYS_INVALID_INPUT_PARAM,\n                   \"parent resc not in fco resc hier\" );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ create the new resc hier\n    std::string dst_hier = inp_hier.substr( 0, pos + parent_name.size() );\n    if ( !dst_hier.empty() ) {\n        dst_hier += irods::hierarchy_parser::delimiter();\n    }\n    dst_hier += current_name +\n                irods::hierarchy_parser::delimiter() +\n                cache_name;\n    rodsLog(LOG_DEBUG, \"[%s:%d] - inp_hier:[%s],dst_hier:[%s]\",\n        __FUNCTION__, __LINE__,\n        inp_hier.c_str(), dst_hier.c_str());\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ set the vote and hier parser\n    _out_parser.set_string( dst_hier );\n    _out_vote = arch_check_vote;\n\n    return SUCCESS();\n\n} \/\/ open_for_prefer_archive_policy\n\n\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief - handler for prefer cache policy\nirods::error open_for_prefer_cache_policy(\n    irods::plugin_context& _ctx,\n    const std::string*               _opr,\n    const std::string*               _curr_host,\n    irods::hierarchy_parser*        _out_parser,\n    float*                           _out_vote )\n{\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check incoming parameters\n    if ( !_curr_host ) {\n        return ERROR( SYS_INVALID_INPUT_PARAM, \"null operation\" );\n    }\n    if ( !_out_parser ) {\n        return ERROR( SYS_INVALID_INPUT_PARAM, \"null outgoing hier parser\" );\n    }\n    if ( !_out_vote ) {\n        return ERROR( SYS_INVALID_INPUT_PARAM, \"null outgoing vote\" );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the archive resource\n    irods::resource_ptr arch_resc;\n    irods::error ret = get_archive( _ctx, arch_resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ If resource hierarchy is provided and it is the archive, use it for open\n    std::string archive_resc_name{};\n    ret = arch_resc->get_property<std::string>(\n            irods::RESOURCE_NAME,\n            archive_resc_name );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    irods::file_object_ptr obj = boost::dynamic_pointer_cast<irods::file_object>(_ctx.fco());\n    const char* hier = getValByKey((keyValPair_t*)&obj->cond_input(), RESC_HIER_STR_KW);\n    if (hier) {\n        irods::hierarchy_parser parser;\n        parser.set_string(hier);\n        if (parser.resc_in_hier(archive_resc_name)) {\n            *_out_vote = 1.0;\n            *_out_parser = parser;\n            return SUCCESS();\n        }\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the cache resource\n    irods::resource_ptr cache_resc;\n    ret = get_cache( _ctx, cache_resc );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    std::string cache_resc_name;\n    ret = cache_resc->get_property<std::string>(\n            irods::RESOURCE_NAME,\n            cache_resc_name );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    std::string operation{irods::OPEN_OPERATION};\n    ret = _ctx.prop_map().get<std::string>(OPERATION_TYPE, operation);\n    if (!ret.ok()) {\n        rodsLog(LOG_NOTICE, \"[%s] - operation not found in property map; using open.\", __FUNCTION__);\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ ask the cache if it has the data object in question, politely\n    float                    cache_check_vote   = 0.0;\n    irods::hierarchy_parser cache_check_parser = ( *_out_parser );\n    ret = cache_resc->call < const std::string*, const std::string*, irods::hierarchy_parser*, float* > (\n        _ctx.comm(), irods::RESOURCE_OP_RESOLVE_RESC_HIER, _ctx.fco(),\n        &operation, _curr_host,\n        &cache_check_parser, &cache_check_vote );\n    if ( !ret.ok() ) {\n        irods::log(ret);\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ if the vote is 0 then the cache doesnt have it so it will need be staged\n    if ( 0.0 == cache_check_vote ) {\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ repave the repl requested temporarily\n        irods::file_object_ptr f_ptr = boost::dynamic_pointer_cast< irods::file_object >( _ctx.fco() );\n        int repl_requested = f_ptr->repl_requested();\n        f_ptr->repl_requested( -1 );\n\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ ask the archive if it has the data object in question, politely\n        float                    arch_check_vote   = 0.0;\n        irods::hierarchy_parser arch_check_parser = ( *_out_parser );\n        ret = arch_resc->call < const std::string*, const std::string*,\n        irods::hierarchy_parser*, float* > (\n            _ctx.comm(), irods::RESOURCE_OP_RESOLVE_RESC_HIER, _ctx.fco(),\n            &operation, _curr_host,\n            &arch_check_parser, &arch_check_vote );\n        if ( !ret.ok() ) {\n            irods::log(ret);\n            return PASS( ret );\n        }\n\n        if( 0.0 == arch_check_vote ) {\n            *_out_vote = 0.0;\n            return SUCCESS();\n        }\n\n        if( irods::UNLINK_OPERATION == ( *_opr ) ) {\n            ( *_out_parser ) = arch_check_parser;\n            ( *_out_vote )   = arch_check_vote;\n            return SUCCESS();\n        }\n\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ repave the resc hier with the archive hier which guarantees that\n        \/\/ we are in the hier for the repl to do its magic. this is a hack,\n        \/\/ and will need refactored later with an improved object model\n        std::string arch_hier;\n        arch_check_parser.str( arch_hier );\n        f_ptr->resc_hier( arch_hier );\n\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ if the archive has it, then replicate\n        ret = repl_object( _ctx, arch_check_parser, STAGE_OBJ_KW );\n        if ( !ret.ok() ) {\n            return PASS( ret );\n        }\n\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ restore repl requested\n        f_ptr->repl_requested( repl_requested );\n\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ now that the repl happened, we will assume that the\n        \/\/ object is in the cache as to not hit the DB again\n        \/\/ the first vote was zero so we must add the name to\n        \/\/ the resource hierarchy\n        ( *_out_parser ) = cache_check_parser;\n        ( *_out_vote ) = arch_check_vote;\n        std::string hier;\n        cache_check_parser.str(hier);\n    }\n    else {\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ else it is in the cache so assign the parser\n        ( *_out_vote )   = cache_check_vote;\n        ( *_out_parser ) = cache_check_parser;\n    }\n\n    return SUCCESS();\n\n} \/\/ open_for_prefer_cache_policy\n\n\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief - code to determine redirection for the open operation\n\/\/\/          determine the user set policy for staging to cache\n\/\/\/          otherwise the default is to compare checksum\nirods::error compound_file_redirect_open(\n    irods::plugin_context& _ctx,\n    const std::string*               _opr,\n    const std::string*               _curr_host,\n    irods::hierarchy_parser*        _out_parser,\n    float*                           _out_vote )\n{\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check incoming parameters\n    if ( !_curr_host ) {\n        return ERROR( SYS_INVALID_INPUT_PARAM, \"null operation\" );\n    }\n    if ( !_out_parser ) {\n        return ERROR( SYS_INVALID_INPUT_PARAM, \"null outgoing hier parser\" );\n    }\n    if ( !_out_vote ) {\n        return ERROR( SYS_INVALID_INPUT_PARAM, \"null outgoing vote\" );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ determine if the resource is down\n    int resc_status = 0;\n    irods::error ret = _ctx.prop_map().get< int >( irods::RESOURCE_STATUS, resc_status );\n    if ( !ret.ok() ) {\n        return PASS( ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ if the status is down, vote no.\n    if ( INT_RESC_STATUS_DOWN == resc_status ) {\n        ( *_out_vote ) = 0.0;\n        return SUCCESS();\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ acquire the value of the stage policy from the results string\n    std::string policy;\n    ret = get_stage_policy( _ctx.rule_results(), policy );\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ if the policy is prefer cache then if the cache has the object\n    \/\/ return an upvote\n    if ( policy.empty() || irods::RESOURCE_STAGE_PREFER_CACHE == policy ) {\n        return open_for_prefer_cache_policy( _ctx, _opr, _curr_host, _out_parser, _out_vote );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ if the policy is always, then if the archive has it\n    \/\/ stage from archive to cache and return an upvote\n    else if ( irods::RESOURCE_STAGE_PREFER_ARCHIVE == policy ) {\n        return open_for_prefer_archive_policy( _ctx, *_curr_host, *_out_parser, *_out_vote );\n    }\n    else {\n        std::stringstream msg;\n        msg << \"invalid stage policy [\" << policy << \"]\";\n        irods::log(LOG_ERROR, msg.str());\n        return ERROR( SYS_INVALID_INPUT_PARAM, msg.str() );\n    }\n\n    return SUCCESS();\n\n} \/\/ compound_file_redirect_open\n\nvoid replace_archive_for_replica(\n    irods::plugin_context& ctx,\n    const irods::hierarchy_parser& voted_hier)\n{\n    irods::resource_ptr arch_resc;\n    get_archive(ctx, arch_resc);\n    std::string archive_resc_name{};\n    arch_resc->get_property<std::string>(irods::RESOURCE_NAME, archive_resc_name);\n\n    irods::file_object_ptr file_obj = boost::dynamic_pointer_cast<irods::file_object>(ctx.fco());\n    for (auto& r : file_obj->replicas()) {\n        rodsLog(LOG_DEBUG,\n            \"[%s:%d] - vote:[%f],voted_hier:[%s],hier:[%s],arch:[%s]\",\n            __FUNCTION__, __LINE__,\n            r.vote(),\n            voted_hier.str().c_str(),\n            r.resc_hier().c_str(),\n            archive_resc_name.c_str());\n        if (irods::hierarchy_parser{r.resc_hier()}.last_resc() == archive_resc_name) {\n            r.resc_hier(voted_hier.str());\n            break;\n        }\n    }\n} \/\/ replace_archive_for_replica\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief - used to allow the resource to determine which host\n\/\/\/          should provide the requested operation\nirods::error compound_file_resolve_hierarchy(\n    irods::plugin_context& _ctx,\n    const std::string*                  _opr,\n    const std::string*                  _curr_host,\n    irods::hierarchy_parser*           _out_parser,\n    float*                              _out_vote ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check the context validity\n\n    irods::error ret = _ctx.valid< irods::file_object >();\n    if ( !ret.ok() ) {\n        std::stringstream msg;\n        msg << \"resource context is invalid\";\n        return PASSMSG( msg.str(), ret );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ check incoming parameters\n    if ( !_opr ) {\n        return ERROR( SYS_INVALID_INPUT_PARAM, \"null operation\" );\n    }\n    if ( !_curr_host ) {\n        return ERROR( SYS_INVALID_INPUT_PARAM, \"null operation\" );\n    }\n    if ( !_out_parser ) {\n        return ERROR( SYS_INVALID_INPUT_PARAM, \"null outgoing hier parser\" );\n    }\n    if ( !_out_vote ) {\n        return ERROR( SYS_INVALID_INPUT_PARAM, \"null outgoing vote\" );\n    }\n\n    ( *_out_vote ) = 0.0f;\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ get the name of this resource\n    std::string resc_name;\n    ret = _ctx.prop_map().get< std::string >( irods::RESOURCE_NAME, resc_name );\n    if ( !ret.ok() ) {\n        std::stringstream msg;\n        msg << \"failed in get property for name\";\n        return ERROR( SYS_INVALID_INPUT_PARAM, msg.str() );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ add ourselves to the hierarchy parser by default\n    _out_parser->add_child( resc_name );\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ test the operation to determine which choices to make\n    if (irods::OPEN_OPERATION == *_opr || irods::WRITE_OPERATION == *_opr) {\n        _ctx.prop_map().set< std::string >( OPERATION_TYPE, ( *_opr ) );\n        \/\/ If the hierarchy contains the archive, just vote 1.0 and return, don't get the cache\n        auto ret = compound_file_redirect_open( _ctx, _opr, _curr_host, _out_parser, _out_vote );\n        if (ret.ok()) {\n            replace_archive_for_replica(_ctx, *_out_parser);\n        }\n        return ret;\n    }\n    else if ( irods::CREATE_OPERATION == ( *_opr )) {\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ call redirect determination for 'create' operation\n        return compound_file_redirect_create( _ctx, ( *_opr ), _curr_host, _out_parser, _out_vote );\n    }\n    else if ( irods::UNLINK_OPERATION == ( *_opr )) {\n        \/\/ =-=-=-=-=-=-=-\n        \/\/ call redirect determination for 'unlink' operation\n        return compound_file_redirect_unlink( _ctx, ( *_opr ), _curr_host, _out_parser, _out_vote );\n    }\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ must have been passed a bad operation\n    std::stringstream msg;\n    msg << \"operation not supported [\";\n    msg << ( *_opr ) << \"]\";\n    return ERROR( -1, msg.str() );\n\n} \/\/ compound_file_resolve_hierarchy\n\n\/\/\/ =-=-=-=-=-=-=-\n\/\/\/ @brief - code which would rebalance the subtree\nirods::error compound_file_rebalance(\n    irods::plugin_context& _ctx ) {\n    irods::resource_child_map* cmap_ref;\n    _ctx.prop_map().get< irods::resource_child_map* >(\n            irods::RESC_CHILD_MAP_PROP,\n            cmap_ref );\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ forward request for rebalance to children\n    irods::error result = SUCCESS();\n    irods::resource_child_map::iterator itr = cmap_ref->begin();\n    for ( ; itr != cmap_ref->end(); ++itr ) {\n        irods::error ret = itr->second.second->call(\n                               _ctx.comm(),\n                               irods::RESOURCE_OP_REBALANCE,\n                               _ctx.fco() );\n        if ( !ret.ok() ) {\n            irods::log( PASS( ret ) );\n            result = ret;\n        }\n    }\n\n    if ( !result.ok() ) {\n        return PASS( result );\n    }\n\n    return SUCCESS();\n\n} \/\/ compound_file_rebalance\n\n\n\/\/ =-=-=-=-=-=-=-\n\/\/ 3. create derived class to handle universal mss resources\n\/\/    context string will hold the script to be called.\nclass compound_resource : public irods::resource {\n    public:\n        compound_resource( const std::string& _inst_name,\n                           const std::string& _context ) :\n            irods::resource( _inst_name, _context ) {\n            \/\/ =-=-=-=-=-=-=-\n            \/\/ set the start operation to identify the cache and archive children\n            set_start_operation( compound_start_operation );\n\n            \/\/ =-=-=-=-=-=-=-\n            \/\/ parse context string into property pairs assuming a ; as a separator\n            std::vector< std::string > props;\n            irods::kvp_map_t kvp;\n            irods::error ret = irods::parse_kvp_string(\n                                   _context,\n                                   kvp );\n            if(!ret.ok()) {\n                rodsLog(\n                    LOG_ERROR,\n                    \"libcompound: invalid context [%s]\",\n                    _context.c_str() );\n            }\n\n            \/\/ =-=-=-=-=-=-=-\n            \/\/ copy the properties from the context to the prop map\n            irods::kvp_map_t::iterator itr = kvp.begin();\n            for( ; itr != kvp.end(); ++itr ) {\n                properties_.set< std::string >(\n                    itr->first,\n                    itr->second );\n            } \/\/ for itr\n\n            std::string parent_id_str;\n            ret = properties_.get< std::string >( irods::RESOURCE_PARENT, parent_id_str );\n\n        }\n\n        \/\/ =-=-=-=-=-=-\n        \/\/ override from plugin_base\n        irods::error need_post_disconnect_maintenance_operation( bool& _flg ) {\n            _flg = false;\n            return SUCCESS();\n        }\n\n        \/\/ =-=-=-=-=-=-\n        \/\/ override from plugin_base\n        irods::error post_disconnect_maintenance_operation( irods::pdmo_type& ) {\n            return ERROR( -1, \"nop\" );\n        }\n\n}; \/\/ class compound_resource\n\n\/\/ =-=-=-=-=-=-=-\n\/\/ 4. create the plugin factory function which will return a dynamically\n\/\/    instantiated object of the previously defined derived resource.  use\n\/\/    the add_operation member to associate a 'call name' to the interfaces\n\/\/    defined above.  for resource plugins these call names are standardized\n\/\/    as used by the irods facing interface defined in\n\/\/    server\/drivers\/src\/fileDriver.cpp\nextern \"C\"\nirods::resource* plugin_factory( const std::string& _inst_name,\n                                 const std::string& _context ) {\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ 4a. create compound_resource object\n    compound_resource* resc = new compound_resource( _inst_name, _context );\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ 4b. map function names to operations.  this map will be used to load\n    \/\/     the symbols from the shared object in the delay_load stage of\n    \/\/     plugin loading.\n\n    using namespace irods;\n    using namespace std;\n    resc->add_operation(\n        RESOURCE_OP_CREATE,\n        function<error(plugin_context&)>(\n            compound_file_create ) );\n\n    resc->add_operation(\n        irods::RESOURCE_OP_OPEN,\n        function<error(plugin_context&)>(\n            compound_file_open ) );\n\n    resc->add_operation<void*,const int>(\n        irods::RESOURCE_OP_READ,\n        std::function<\n            error(irods::plugin_context&,void*,const int)>(\n                compound_file_read ) );\n\n    resc->add_operation<const void*,const int>(\n        irods::RESOURCE_OP_WRITE,\n        function<error(plugin_context&,const void*,const int)>(\n            compound_file_write ) );\n\n    resc->add_operation(\n        RESOURCE_OP_CLOSE,\n        function<error(plugin_context&)>(\n            compound_file_close ) );\n\n    resc->add_operation(\n        irods::RESOURCE_OP_UNLINK,\n        function<error(plugin_context&)>(\n            compound_file_unlink ) );\n\n    resc->add_operation<struct stat*>(\n        irods::RESOURCE_OP_STAT,\n        function<error(plugin_context&, struct stat*)>(\n            compound_file_stat ) );\n\n    resc->add_operation(\n        irods::RESOURCE_OP_MKDIR,\n        function<error(plugin_context&)>(\n            compound_file_mkdir ) );\n\n    resc->add_operation(\n        irods::RESOURCE_OP_OPENDIR,\n        function<error(plugin_context&)>(\n            compound_file_opendir ) );\n\n    resc->add_operation<struct rodsDirent**>(\n        irods::RESOURCE_OP_READDIR,\n        function<error(plugin_context&,struct rodsDirent**)>(\n            compound_file_readdir ) );\n\n    resc->add_operation<const char*>(\n        irods::RESOURCE_OP_RENAME,\n        function<error(plugin_context&, const char*)>(\n            compound_file_rename ) );\n\n    resc->add_operation(\n        irods::RESOURCE_OP_FREESPACE,\n        function<error(plugin_context&)>(\n            compound_file_getfs_freespace ) );\n\n    resc->add_operation<const long long, const int>(\n        irods::RESOURCE_OP_LSEEK,\n        function<error(plugin_context&, const long long, const int)>(\n            compound_file_lseek ) );\n\n    resc->add_operation(\n        irods::RESOURCE_OP_RMDIR,\n        function<error(plugin_context&)>(\n            compound_file_rmdir ) );\n\n    resc->add_operation(\n        irods::RESOURCE_OP_CLOSEDIR,\n        function<error(plugin_context&)>(\n            compound_file_closedir ) );\n\n    resc->add_operation<const char*>(\n        irods::RESOURCE_OP_STAGETOCACHE,\n        function<error(plugin_context&, const char*)>(\n            compound_file_stage_to_cache ) );\n\n    resc->add_operation<const char*>(\n        irods::RESOURCE_OP_SYNCTOARCH,\n        function<error(plugin_context&, const char*)>(\n            compound_file_sync_to_arch ) );\n\n    resc->add_operation(\n        irods::RESOURCE_OP_REGISTERED,\n        function<error(plugin_context&)>(\n            compound_file_registered ) );\n\n    resc->add_operation(\n        irods::RESOURCE_OP_UNREGISTERED,\n        function<error(plugin_context&)>(\n            compound_file_unregistered ) );\n\n    resc->add_operation(\n        irods::RESOURCE_OP_MODIFIED,\n        function<error(plugin_context&)>(\n            compound_file_modified ) );\n\n    resc->add_operation<const std::string*>(\n        irods::RESOURCE_OP_NOTIFY,\n        function<error(plugin_context&, const std::string*)>(\n            compound_file_notify ) );\n\n    resc->add_operation(\n        irods::RESOURCE_OP_TRUNCATE,\n        function<error(plugin_context&)>(\n            compound_file_truncate ) );\n\n    resc->add_operation<const std::string*, const std::string*, irods::hierarchy_parser*, float*>(\n        irods::RESOURCE_OP_RESOLVE_RESC_HIER,\n        function<error(plugin_context&,const std::string*, const std::string*, irods::hierarchy_parser*, float*)>(\n            compound_file_resolve_hierarchy ) );\n\n    resc->add_operation(\n        irods::RESOURCE_OP_REBALANCE,\n        function<error(plugin_context&)>(\n            compound_file_rebalance ) );\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ set some properties necessary for backporting to iRODS legacy code\n    resc->set_property< int >( irods::RESOURCE_CHECK_PATH_PERM, 2 );\/\/DO_CHK_PATH_PERM );\n    resc->set_property< int >( irods::RESOURCE_CREATE_PATH,     1 );\/\/CREATE_PATH );\n\n    \/\/ =-=-=-=-=-=-=-\n    \/\/ 4c. return the pointer through the generic interface of an\n    \/\/     irods::resource pointer\n    return dynamic_cast<irods::resource*>( resc );\n\n} \/\/ plugin_factory\n","avg_line_length":33.4752650177,"max_line_length":144,"alphanum_fraction":0.5830606428,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3238,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":8.0,"content":"#include \"EdgeOperations2d.h\"\n\n#include <wmtk\/TriMesh.h>\n#include <wmtk\/utils\/VectorUtils.h>\n#include <wmtk\/ExecutionScheduler.hpp>\n#include <wmtk\/utils\/TupleUtils.hpp>\n\n#include <Eigen\/Core>\n#include <Eigen\/Geometry>\n\nusing namespace wmtk;\nusing namespace Edge2d;\n\nbool Edge2d::EdgeOperations2d::swap_edge_after(const TriMesh::Tuple& t)\n{\n    std::vector<TriMesh::Tuple> tris;\n    tris.push_back(t);\n    tris.push_back(t.switch_edge(*this));\n    return true;\n}\n\nbool Edge2d::EdgeOperations2d::collapse_edge_after(const TriMesh::Tuple& t)\n{\n    const Eigen::Vector3d p = (position_cache.local().v1p + position_cache.local().v2p) \/ 2.0;\n    auto vid = t.vid(*this);\n    vertex_attrs[vid].pos = p;\n\n    return true;\n}\n\nbool Edge2d::EdgeOperations2d::split_edge_after(const TriMesh::Tuple& t)\n{\n    const Eigen::Vector3d p = (position_cache.local().v1p + position_cache.local().v2p) \/ 2.0;\n    auto vid = t.vid(*this);\n    vertex_attrs[vid].pos = p;\n\n    return true;\n}\n\nstd::vector<TriMesh::Tuple> Edge2d::EdgeOperations2d::new_edges_after(\n    const std::vector<TriMesh::Tuple>& tris) const\n{\n    std::vector<TriMesh::Tuple> new_edges;\n    std::vector<size_t> one_ring_fid;\n\n    for (auto t : tris) {\n        for (auto j = 0; j < 3; j++) {\n            new_edges.push_back(tuple_from_edge(t.fid(*this), j));\n        }\n    }\n    wmtk::unique_edge_tuples(*this, new_edges);\n    return new_edges;\n}\n\nbool Edge2d::EdgeOperations2d::collapse_shortest(int target_operation_count)\n{\n    size_t initial_size = get_vertices().size();\n    auto collect_all_ops = std::vector<std::pair<std::string, Tuple>>();\n    for (auto& loc : get_edges()) collect_all_ops.emplace_back(\"edge_collapse\", loc);\n\n    auto renew = [](auto& m, auto op, auto& tris) {\n        auto edges = m.new_edges_after(tris);\n        auto optup = std::vector<std::pair<std::string, Tuple>>();\n        for (auto& e : edges) optup.emplace_back(\"edge_collapse\", e);\n        return optup;\n    };\n    auto measure_len2 = [](auto& m, auto op, const Tuple& new_e) {\n        auto len2 =\n            (m.vertex_attrs[new_e.vid(m)].pos - m.vertex_attrs[new_e.switch_vertex(m).vid(m)].pos)\n                .squaredNorm();\n        return -len2;\n    };\n    auto setup_and_execute = [&](auto executor) {\n        executor.num_threads = NUM_THREADS;\n        executor.renew_neighbor_tuples = renew;\n        executor.priority = measure_len2;\n        executor.lock_vertices = [](auto& m, const auto& e, int task_id) -> bool {\n            return m.try_set_edge_mutex_two_ring(e, task_id);\n        };\n        executor.stopping_criterion_checking_frequency = target_operation_count > 0\n                                                             ? target_operation_count + 1\n                                                             : std::numeric_limits<int>::max();\n        executor.stopping_criterion = [](auto& m) { return true; };\n        executor(*this, collect_all_ops);\n    };\n\n    if (NUM_THREADS > 0) {\n        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kSeq>();\n        setup_and_execute(executor);\n    } else {\n        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kPartition>();\n        setup_and_execute(executor);\n    }\n    return true;\n}","avg_line_length":34.0842105263,"max_line_length":98,"alphanum_fraction":0.6349598518,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7004,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":49.0,"content":"\/*****************************************************************************\/\n\/* Csv.h                                  Copyright (c) Ladislav Zezula 2018 *\/\n\/*---------------------------------------------------------------------------*\/\n\/* Implementation for the CSV handler class                                  *\/\n\/*---------------------------------------------------------------------------*\/\n\/*   Date    Ver   Who  Comment                                              *\/\n\/* --------  ----  ---  -------                                              *\/\n\/* 30.06.18  1.00  Lad  Created                                              *\/\n\/*****************************************************************************\/\n\n#define __CASCLIB_SELF__\n#include \"..\/CascLib.h\"\n#include \"..\/CascCommon.h\"\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Local defines\n\n#define INVALID_COLUMNS  ((size_t)-1)\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Constructor and destructor\n\nCASC_CSV::CASC_CSV()\n{\n    memset(this, 0, sizeof(CASC_CSV));\n    nColumns = INVALID_COLUMNS;\n}\n\nCASC_CSV::~CASC_CSV()\n{\n    nColumns = INVALID_COLUMNS;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Loading headers\n\nsize_t CASC_CSV::LoadElements(PCSV_ELEMENT pElements, size_t nMaxElements, const char * szLinePtr, const char * szLineEnd)\n{\n    size_t nCount = 0;\n\n    \/\/ Parse the entire line\n    while (szLinePtr < szLineEnd)\n    {\n        const char * szString = szLinePtr;\n\n        \/\/ Verify overflow\n        if (nCount >= nMaxElements)\n            return 0;\n\n        \/\/ Find the end of the element\n        while (szLinePtr < szLineEnd && szLinePtr[0] != '|')\n            szLinePtr++;\n\n        \/\/ Put the pointer and length of the element\n        pElements[nCount].szString = szString;\n        pElements[nCount].nLength = (szLinePtr - szString);\n        nCount++;\n\n        \/\/ Skip the end of the element\n        if (szLinePtr < szLineEnd && szLinePtr[0] == '|')\n            szLinePtr++;\n    }\n\n    \/\/ Save the number of elements, if not done yet\n    if (nColumns == INVALID_COLUMNS)\n        nColumns = nCount;\n    return nCount;\n}\n\nsize_t CASC_CSV::LoadHeader(const char * szLinePtr, const char * szLineEnd)\n{\n    return LoadElements(Headers, MAX_CSV_ELEMENTS, szLinePtr, szLineEnd);\n}\n\nsize_t CASC_CSV::LoadHeader(void * pvListFile)\n{\n    const char * szLineBegin;\n    const char * szLineEnd;\n    size_t nCount = 0;\n\n    ListFile_GetNextLine(pvListFile, &szLineBegin, &szLineEnd);\n    if (szLineBegin < szLineEnd)\n    {\n        nCount = LoadHeader(szLineBegin, szLineEnd);\n    }\n\n    return nCount;\n}\n\nbool CASC_CSV::GetColumnIndices(size_t * Indices, ...)\n{\n    const char * szColumnName;\n    va_list argList;\n    bool bResult = true;\n\n    va_start(argList, Indices);\n    while ((szColumnName = va_arg(argList, const char *)) != NULL)\n    {\n        size_t nLength = strlen(szColumnName);\n        size_t nIndex = INVALID_COLUMNS;\n\n        \/\/ Search the array of fields\n        for (size_t i = 0; i < nColumns; i++)\n        {\n            if (nLength == Headers[i].nLength && _strnicmp(Headers[i].szString, szColumnName, nLength) == 0)\n            {\n                nIndex = i;\n                break;\n            }\n        }\n\n        \/\/ Fill the index\n        if (nIndex == INVALID_COLUMNS)\n            bResult = false;\n        *Indices++ = nIndex;\n    }\n    va_end(argList);\n    return bResult;\n}\n\nsize_t CASC_CSV::LoadNextLine(const char * szLinePtr, const char * szLineEnd)\n{\n    size_t nCount;\n\n    \/\/ Retrieve as much items as possible\n    nCount = LoadElements(Columns, MAX_CSV_ELEMENTS, szLinePtr, szLineEnd);\n\n    \/\/ If there are some missing, we need to set them as 0\n    if (nColumns != INVALID_COLUMNS)\n    {\n        while (nCount < nColumns)\n        {\n            Columns[nCount].szString = szLineEnd;\n            Columns[nCount].nLength = 0;\n            nCount++;\n        }\n    }\n\n    return (nCount == nColumns) ? nColumns : 0;\n}\n\nsize_t CASC_CSV::LoadNextLine(void * pvListFile)\n{\n    const char * szLineBegin;\n    const char * szLineEnd;\n    size_t nCount = 0;\n\n    if (ListFile_GetNextLine(pvListFile, &szLineBegin, &szLineEnd))\n    {\n        nCount = LoadNextLine(szLineBegin, szLineEnd);\n    }\n\n    return nCount;\n}\n\nint CASC_CSV::GetString(char * szBufferPtr, size_t nMaxChars, size_t Index)\n{\n    const char * szStringPtr;\n    const char * szStringEnd;\n    char * szBufferEnd = szBufferPtr + nMaxChars - 1;\n\n    \/\/ Check for index overflow and buffer overflow\n    if (Index >= nColumns)\n        return ERROR_INSUFFICIENT_BUFFER;\n    if (Columns[Index].nLength > nMaxChars - 1)\n        return ERROR_INSUFFICIENT_BUFFER;\n    \n    \/\/ Get the source string\n    szStringPtr = Columns[Index].szString;\n    szStringEnd = szStringPtr + Columns[Index].nLength;\n\n    \/\/ Copy the string\n    while (szStringPtr < szStringEnd && szBufferPtr < szBufferEnd)\n        *szBufferPtr++ = *szStringPtr++;\n    szBufferPtr[0] = 0;\n    return ERROR_SUCCESS;\n}\n\nTCHAR * CASC_CSV::GetString(size_t Index)\n{\n    TCHAR * szString;\n    size_t nLength;\n\n    \/\/ Check for index overflow\n    if (Index >= nColumns)\n        return NULL;\n    nLength = Columns[Index].nLength;\n\n    \/\/ Allocate buffer for string. Make it double-zero-terminated\n    \/\/ in order to be multi-SZ as well\n    szString = CASC_ALLOC(TCHAR, nLength + 2);\n    if (szString != NULL)\n    {\n        CopyString(szString, Columns[Index].szString, nLength);\n        szString[nLength + 1] = 0;\n    }\n\n    return szString;\n}\n\nint CASC_CSV::GetBinary(LPBYTE pbBuffer, size_t nMaxBytes, size_t Index)\n{\n    \/\/ Check for index overflow and buffer overflow\n    if (Index >= nColumns)\n        return ERROR_INSUFFICIENT_BUFFER;\n    if (Columns[Index].nLength != nMaxBytes * 2)\n        return ERROR_INSUFFICIENT_BUFFER;\n\n    \/\/ Convert the string to binary\n    return ConvertStringToBinary(Columns[Index].szString, nMaxBytes * 2, pbBuffer);\n}\n\nint CASC_CSV::GetData(QUERY_KEY & Key, size_t Index, bool bHexaValue)\n{\n    \/\/ Check for index overflow\n    if (Index >= nColumns)\n        return ERROR_INSUFFICIENT_BUFFER;\n\n    \/\/ Allocate space for the blob\n    if (bHexaValue)\n    {\n        \/\/ Allocate space\n        Key.pbData = CASC_ALLOC(BYTE, Columns[Index].nLength \/ 2);\n        if (Key.pbData == NULL)\n            return ERROR_NOT_ENOUGH_MEMORY;\n\n        \/\/ Convert the hexa string to binary string\n        Key.cbData = Columns[Index].nLength \/ 2;\n        return ConvertStringToBinary(Columns[Index].szString, Columns[Index].nLength, Key.pbData);\n    }\n    else\n    {\n        size_t nLength = Columns[Index].nLength;\n\n        \/\/ Initialize the blob\n        Key.pbData = CASC_ALLOC(BYTE, nLength + 1);\n        if (Key.pbData == NULL)\n            return ERROR_NOT_ENOUGH_MEMORY;\n\n        \/\/ Copy the string\n        memcpy(Key.pbData, Columns[Index].szString, nLength);\n        Key.pbData[nLength] = 0;\n        Key.cbData = nLength;\n        return ERROR_SUCCESS;\n    }\n}\n","avg_line_length":28.3562753036,"max_line_length":122,"alphanum_fraction":0.5563963449,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5442,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":6.0,"content":"#include \"VoxelShader.hpp\"\n\n#include \"Library.hpp\"\n#include \"Camera.hpp\"\n#include \"Model\/Mesh.hpp\"\n\n#include \"glm\/gtc\/matrix_transform.hpp\"\n\nVoxelShader::VoxelShader(int dimension, const std::string &r, const std::string &v, const std::string &f) :\n    Shader(r, v, f) {\n    int numVoxels = dimension * dimension * dimension;\n\n    \/* Init voxel CPU vectors \n     * Extra position for bounds *\/\n    this->voxelPositions.resize(numVoxels + 1);\n    this->voxelData.resize(numVoxels);\n\n    \/* Create instanced cube mesh *\/\n    this->cube = Library::createCube();\n\n    \/* Voxel positions vbo *\/\n    CHECK_GL_CALL(glBindVertexArray(cube->vaoId));\n    CHECK_GL_CALL(glGenBuffers(1, &cubePositionVBO));\n    CHECK_GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, cubePositionVBO));\n    CHECK_GL_CALL(glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * voxelPositions.size(), nullptr, GL_DYNAMIC_DRAW));\n    CHECK_GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, 0)); \n    CHECK_GL_CALL(glEnableVertexAttribArray(2));\n    CHECK_GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, cubePositionVBO));\n    CHECK_GL_CALL(glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0));\n    CHECK_GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, 0));\t\n    CHECK_GL_CALL(glVertexAttribDivisor(2, 1)); \n\n    \/* Voxel data vbo *\/\n    CHECK_GL_CALL(glGenBuffers(1, &cubeDataVBO));\n    CHECK_GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, cubeDataVBO));\n    CHECK_GL_CALL(glBufferData(GL_ARRAY_BUFFER, sizeof(float) * voxelData.size(), nullptr, GL_DYNAMIC_DRAW));\n    CHECK_GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, 0));\n    CHECK_GL_CALL(glEnableVertexAttribArray(3));\n    CHECK_GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, cubeDataVBO));\n    CHECK_GL_CALL(glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, sizeof(float), (void*)0));\n    CHECK_GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, 0));\t\n    CHECK_GL_CALL(glVertexAttribDivisor(3, 1));\n\n    CHECK_GL_CALL(glBindVertexArray(0));\n}\n\n\/* Visualize voxels *\/\nvoid VoxelShader::render(const CloudVolume *volume, const glm::mat4 &P, const glm::mat4 &V) {\n    updateVoxelData(volume);\n\n    \/* Bind projeciton, view matrices *\/\n    loadMatrix(getUniform(\"P\"), &P);\n    loadMatrix(getUniform(\"V\"), &V);\n\n    \/* Bind mesh *\/\n    CHECK_GL_CALL(glBindVertexArray(cube->vaoId));\n    CHECK_GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cube->eleBufId));\n\n    \/* Reupload voxel positions *\/\n    CHECK_GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, cubePositionVBO));\n    CHECK_GL_CALL(glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * voxelPositions.size(), &voxelPositions[0], GL_DYNAMIC_DRAW));\n\n    \/* Reupload voxel data *\/\n    CHECK_GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, cubeDataVBO));\n    CHECK_GL_CALL(glBufferData(GL_ARRAY_BUFFER, sizeof(float) * voxelData.size(), &voxelData[0], GL_DYNAMIC_DRAW));\n\n    \/* Individual voxels *\/\n    loadFloat(getUniform(\"alpha\"), alpha);\n    loadVector(getUniform(\"voxelSize\"), volume->voxelSize);\n\n    \/* Render voxels *\/\n    if (!disableWhite) {\n        loadBool(getUniform(\"isOutline\"), false);\n        CHECK_GL_CALL(glDrawElementsInstanced(GL_TRIANGLES, (int)cube->eleBuf.size(), GL_UNSIGNED_INT, 0, voxelPositions.size()));\n    }\n\n    \/* Render voxel outlines and bounds *\/\n    loadBool(getUniform(\"isOutline\"), true);\n    CHECK_GL_CALL(glPolygonMode(GL_FRONT_AND_BACK, GL_LINE));\n \n    \/* Individual voxels *\/\n    if (!disableWhite && useOutline) {\n       CHECK_GL_CALL(glDrawElementsInstanced(GL_TRIANGLES, (int)cube->eleBuf.size(), GL_UNSIGNED_INT, 0, voxelPositions.size()));\n    }\n\n    \/* Bounds *\/\n    if (!disableBounds) {\n        glm::vec3 min(volume->xBounds.x, volume->yBounds.x, volume->zBounds.x);\n        glm::vec3 max(volume->xBounds.y, volume->yBounds.y, volume->zBounds.y);\n        loadVector(getUniform(\"voxelSize\"), max - min);\n        CHECK_GL_CALL(glDrawElementsInstancedBaseInstance(GL_TRIANGLES, (int)cube->eleBuf.size(), GL_UNSIGNED_INT, 0, 1, voxelPositions.size() - 1));\n    }\n\n    CHECK_GL_CALL(glPolygonMode(GL_FRONT_AND_BACK, GL_FILL));\n\n    \/* Clean up *\/\n    CHECK_GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, 0));\n    CHECK_GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));\n    CHECK_GL_CALL(glBindVertexArray(0));\n}\n\nvoid VoxelShader::updateVoxelData(const CloudVolume *volume) {\n    \/* Pull volume data out of GPU *\/\n    std::vector<float> buffer(voxelData.size());\n    CHECK_GL_CALL(glBindTexture(GL_TEXTURE_3D, volume->volId));\n    CHECK_GL_CALL(glGetTexImage(GL_TEXTURE_3D, 0, GL_RED, GL_FLOAT, buffer.data()));\n    CHECK_GL_CALL(glBindTexture(GL_TEXTURE_3D, 0));\n\n    \/* Size of voxels in world-space *\/\n    activeVoxels = 0;\n    for (unsigned int i = 0; i < voxelData.size(); i++) {\n        \/* Update voxel data if data exists *\/\n        float r = buffer[i];\n        if (r) {\n            activeVoxels++;\n            glm::ivec3 voxelIndex = volume->get3DIndices(i);\n            voxelPositions[i] = volume->position + volume->reverseVoxelIndex(voxelIndex);\n            voxelData[i] = r;\n        }\n        \/* Otherwise reset data *\/\n        else {\n            voxelPositions[i].x = 0.f;\n            voxelPositions[i].y = 1000000.f; \/\/ ensures instanced voxels won't be rendered\n            voxelPositions[i].z = 0.f;\n            voxelData[i] = 0.f;\n        }\n    }\n\n    \/* Update bounds position *\/\n    glm::vec3 min(volume->xBounds.x, volume->yBounds.x, volume->zBounds.x);\n    glm::vec3 max(volume->xBounds.y, volume->yBounds.y, volume->zBounds.y);\n    voxelPositions.back() = volume->position + (max + min) \/ 2.f;\n}","avg_line_length":40.9172932331,"max_line_length":149,"alphanum_fraction":0.6894524072,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":910,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":26.0,"content":"#include <bsl_cstddef.h>\n#include <cstddef>\n#ifdef std\n#   error std was not expected to be a macro\n#endif\nnamespace std { }\nint main() { return 0; }\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2013 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n","avg_line_length":37.9166666667,"max_line_length":79,"alphanum_fraction":0.6153846154,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6417,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"#include \"FKRealmConnectionManager.h\"\n\n#include \"FKRealm.h\"\n#include \"FKMessage.h\"\n#include \"FKBasicEvent.h\"\n#include \"FKEventObject.h\"\n\n#include \"FKLogger.h\"\n#include \"FKBasicEventSubjects.h\"\n\n\/*!\n\\class FKRealmConnectionManager\n\\brief This class used to process guest connectors at realm-side\n*\/\n\n\/*!\n * \\brief Create manager for \\i connector at \\i realm with \\i parent\n *\/\n\nFKRealmConnectionManager::FKRealmConnectionManager(FKRealm* realm,FKConnector* connector,QObject *parent):\n        FKConnectionManager(connector,parent),_realm(realm){\n    FK_CBEGIN\n    FK_CEND\n}\n\n\/*!\n * \\brief Deletes manager\n *\/\n\nFKRealmConnectionManager::~FKRealmConnectionManager(){\n    FK_DBEGIN\n    FK_DEND\n}\n\nvoid FKRealmConnectionManager::processMessage(FKMessage* msg){\n    FK_MLOGV(\"Unexpected message from guest to realm\",msg->subject())\n    msg->deleteLater();\n    realm()->stopGuestConnection(this);\n}\n\nvoid FKRealmConnectionManager::processGuestEvent(FKBasicEvent* ev){\n    const QString subject=ev->subject();\n    const QVariant value=ev->value();\n    ev->deleteLater();\n    if(subject==FKBasicEventSubject::login){\n        realm()->ausvise(this,value);\n    }else{\n        FK_MLOGV(\"Unexpected guest event subject from guest to realm\",subject)\n        realm()->stopGuestConnection(this);\n    }\n}\n\nvoid FKRealmConnectionManager::processBasicEvent(FKBasicEvent* ev){\n    FK_MLOGV(\"Unexpected basic event from guest to realm\",ev->subject())\n    ev->deleteLater();\n    realm()->stopGuestConnection(this);\n}\n\nvoid FKRealmConnectionManager::processEvent(FKEventObject* ev){\n    FK_MLOGV(\"Unexpected event from guest to realm\",ev->subject())\n    ev->deleteLater();\n    realm()->stopGuestConnection(this);\n}\n\nvoid FKRealmConnectionManager::incomeMessageError(const QString& msgType, const QString& reason){\n    FK_MLOGV(QString(\"Income message error from guest to realm: \")+reason,msgType)\n    realm()->stopGuestConnection(this);\n}\n\n\/*!\n * \\fn FKRealm* FKRealmConnectionManager::realm()const\n * \\brief Returns realm object reference\n *\/\n\n\/*!\n\\class FKRealmConnectionManagerC\n\\brief This class used to process connectors from clients at realm-side\n*\/\n\n\/*!\n * \\brief Create manager for \\i connector at \\i realm with \\i parent\n *\/\n\nFKRealmConnectionManagerC::FKRealmConnectionManagerC(const QString& id,FKRealm* realm, FKConnector* connector, QObject* parent):\n        FKRealmConnectionManager(realm,connector,parent),_id(id){\n    FK_CBEGIN\n    FK_CEND\n}\n\n\/*!\n * \\brief Deletes manager\n *\/\n\nFKRealmConnectionManagerC::~FKRealmConnectionManagerC(){\n    FK_DBEGIN\n    FK_DEND\n}\n\nvoid FKRealmConnectionManagerC::processMessage(FKMessage* msg){\n    FK_MLOGV(\"Unexpected message from client to realm\",msg->subject())\n    msg->deleteLater();\n    realm()->stopClientConnection(_id);\n}\n\nvoid FKRealmConnectionManagerC::processGuestEvent(FKBasicEvent* ev){\n    FK_MLOGV(\"Unexpected guest event from client to realm\",ev->subject())\n    ev->deleteLater();\n    realm()->stopClientConnection(_id);\n}\n\nvoid FKRealmConnectionManagerC::processBasicEvent(FKBasicEvent* ev){\n    const QString subject=ev->subject();\n    const QVariant value=ev->value();\n    ev->deleteLater();\n    if(subject==FKBasicEventSubject::roomList){\n        todo;\/\/realm()->refreshRoomList(_id,value);\n    }else if(subject==FKBasicEventSubject::createUser){\n        realm()->createUser(_id,value);\n    }else if(subject==FKBasicEventSubject::deleteUser){\n        realm()->deleteUser(_id,value);\n    }else if(subject==FKBasicEventSubject::createRoom){\n        realm()->createRoomRequested(_id,value);\n    }else if(subject==FKBasicEventSubject::joinRoom){\n        realm()->joinRoomRequested(_id,value);\n    }else{\n        FK_MLOGV(\"Unexpected basic event subject from client to realm\",subject)\n        realm()->stopClientConnection(_id);\n    }\n}\n\nvoid FKRealmConnectionManagerC::processEvent(FKEventObject* ev){\n    FK_MLOGV(\"Unexpected event from client to realm\",ev->subject())\n    ev->deleteLater();\n    realm()->stopClientConnection(_id);\n}\n\nvoid FKRealmConnectionManagerC::incomeMessageError(const QString& msgType, const QString& reason){\n    FK_MLOGV(QString(\"Income message error from client to realm: \")+reason,msgType)\n    realm()->stopClientConnection(_id);\n}\n\n\n\/*!\n\\class FKRealmConnectionManagerS\n\\brief This class used to process connectors from servers at realm-side\n*\/\n\n\/*!\n * \\brief Create manager for \\i connector at \\i realm with \\i parent\n *\/\n\nFKRealmConnectionManagerS::FKRealmConnectionManagerS(const qint32 id,FKRealm* realm, FKConnector* connector, QObject* parent):\n        FKRealmConnectionManager(realm,connector,parent),_id(id){\n    FK_CBEGIN\n    FK_CEND\n}\n\n\/*!\n * \\brief Deletes manager\n *\/\n\nFKRealmConnectionManagerS::~FKRealmConnectionManagerS(){\n    FK_DBEGIN\n    FK_DEND\n}\n\nvoid FKRealmConnectionManagerS::processMessage(FKMessage* msg){\n    FK_MLOGV(\"Unexpected message from server to realm\",msg->subject())\n    msg->deleteLater();\n    realm()->stopServerConnection(_id);\n}\n\nvoid FKRealmConnectionManagerS::processGuestEvent(FKBasicEvent* ev){\n    FK_MLOGV(\"Unexpected guest event from server to realm\",ev->subject())\n    ev->deleteLater();\n    realm()->stopServerConnection(_id);\n}\n\nvoid FKRealmConnectionManagerS::processBasicEvent(FKBasicEvent* ev){\n    const QString subject=ev->subject();\n    const QVariant value=ev->value();\n    ev->deleteLater();\n    if(subject==FKBasicEventSubject::roomData){\n        realm()->refreshRoomData(_id,value);\n    }else if(subject==FKBasicEventSubject::registerRoomType){\n        realm()->registerServerRoomType(_id,value);\n    }else if(subject==FKBasicEventSubject::removeRoomType){\n        realm()->removeServerRoomType(_id,value);\n    }else if(subject==FKBasicEventSubject::dropClient){\n        realm()->clientDisonnectedFromServer(_id,value);\n    }else if(subject==FKBasicEventSubject::stopRoom){\n        realm()->roomStopped(_id,value);\n    }else{\n        FK_MLOGV(\"Unexpected basic event subject from server to realm\",subject)\n        realm()->stopServerConnection(_id);\n    }\n}\n\nvoid FKRealmConnectionManagerS::processEvent(FKEventObject* ev){\n    FK_MLOGV(\"Unexpected event from server to realm\",ev->subject())\n    ev->deleteLater();\n    realm()->stopServerConnection(_id);\n}\n\nvoid FKRealmConnectionManagerS::incomeMessageError(const QString& msgType, const QString& reason){\n    FK_MLOGV(QString(\"Income message error from server to realm: \")+reason,msgType)\n    realm()->stopServerConnection(_id);\n}\n","avg_line_length":30.7033492823,"max_line_length":128,"alphanum_fraction":0.7280660745,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1634,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"CappedResource.h\"\n#include \"Net\/UnrealNetwork.h\"\n\nclass UCappedResource;\nclass UObject;\n\nfloat UCappedResource::TransferAll(UCappedResource* Receiver) {\n    return 0.0f;\n}\n\nfloat UCappedResource::Transfer(float Amount, UCappedResource* Receiver) {\n    return 0.0f;\n}\n\nvoid UCappedResource::OnRep_FullFlag(int32 OldValue) {\n}\n\nvoid UCappedResource::OnRep_CurrentAmount(float OldAmount) {\n}\n\nbool UCappedResource::IsObjectiveResource(UObject* WorldContext, bool& IsCompleted) const {\n    return false;\n}\n\nbool UCappedResource::IsFull() const {\n    return false;\n}\n\nbool UCappedResource::isEmpty() const {\n    return false;\n}\n\nbool UCappedResource::IsCraftingResource() const {\n    return false;\n}\n\nFText UCappedResource::GetTitle() const {\n    return FText::GetEmpty();\n}\n\nFColor UCappedResource::GetColor() const {\n    return FColor{};\n}\n\nfloat UCappedResource::GetCapacityPct() const {\n    return 0.0f;\n}\n\nfloat UCappedResource::Deduct(float Amount) {\n    return 0.0f;\n}\n\nfloat UCappedResource::Add(float Amount) {\n    return 0.0f;\n}\n\nvoid UCappedResource::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const {\n    Super::GetLifetimeReplicatedProps(OutLifetimeProps);\n    \n    DOREPLIFETIME(UCappedResource, Data);\n    DOREPLIFETIME(UCappedResource, currentAmount);\n    DOREPLIFETIME(UCappedResource, MaxAmount);\n    DOREPLIFETIME(UCappedResource, TotalCollected);\n    DOREPLIFETIME(UCappedResource, FullFlag);\n}\n\nUCappedResource::UCappedResource() {\n    this->Data = NULL;\n    this->currentAmount = 0.00f;\n    this->MaxAmount = 50.00f;\n    this->TotalCollected = 0.00f;\n    this->FullFlag = 0;\n}\n\n","avg_line_length":21.7866666667,"max_line_length":101,"alphanum_fraction":0.7399020808,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":71999,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":26.0,"content":"\/\/===-- ExceptionDemo.cpp - An example using llvm Exceptions --------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Demo program which implements an example LLVM exception implementation, and\n\/\/ shows several test cases including the handling of foreign exceptions.\n\/\/ It is run with type info types arguments to throw. A test will\n\/\/ be run for each given type info type. While type info types with the value\n\/\/ of -1 will trigger a foreign C++ exception to be thrown; type info types\n\/\/ <= 6 and >= 1 will cause the associated generated exceptions to be thrown\n\/\/ and caught by generated test functions; and type info types > 6\n\/\/ will result in exceptions which pass through to the test harness. All other\n\/\/ type info types are not supported and could cause a crash. In all cases,\n\/\/ the \"finally\" blocks of every generated test functions will executed\n\/\/ regardless of whether or not that test function ignores or catches the\n\/\/ thrown exception.\n\/\/\n\/\/ examples:\n\/\/\n\/\/ ExceptionDemo\n\/\/\n\/\/     causes a usage to be printed to stderr\n\/\/\n\/\/ ExceptionDemo 2 3 7 -1\n\/\/\n\/\/     results in the following cases:\n\/\/         - Value 2 causes an exception with a type info type of 2 to be\n\/\/           thrown and caught by an inner generated test function.\n\/\/         - Value 3 causes an exception with a type info type of 3 to be\n\/\/           thrown and caught by an outer generated test function.\n\/\/         - Value 7 causes an exception with a type info type of 7 to be\n\/\/           thrown and NOT be caught by any generated function.\n\/\/         - Value -1 causes a foreign C++ exception to be thrown and not be\n\/\/           caught by any generated function\n\/\/\n\/\/     Cases -1 and 7 are caught by a C++ test harness where the validity of\n\/\/         of a C++ catch(...) clause catching a generated exception with a\n\/\/         type info type of 7 is explained by: example in rules 1.6.4 in\n\/\/         http:\/\/mentorembedded.github.com\/cxx-abi\/abi-eh.html (v1.22)\n\/\/\n\/\/ This code uses code from the llvm compiler-rt project and the llvm\n\/\/ Kaleidoscope project.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/ExecutionEngine\/MCJIT.h\"\n#include \"llvm\/ExecutionEngine\/SectionMemoryManager.h\"\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/DerivedTypes.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/IR\/Intrinsics.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/Support\/Dwarf.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n\n\/\/ FIXME: Although all systems tested with (Linux, OS X), do not need this\n\/\/        header file included. A user on ubuntu reported, undefined symbols\n\/\/        for stderr, and fprintf, and the addition of this include fixed the\n\/\/        issue for them. Given that LLVM's best practices include the goal\n\/\/        of reducing the number of redundant header files included, the\n\/\/        correct solution would be to find out why these symbols are not\n\/\/        defined for the system in question, and fix the issue by finding out\n\/\/        which LLVM header file, if any, would include these symbols.\n#include <cstdio>\n\n#include <sstream>\n#include <stdexcept>\n\n\n#ifndef USE_GLOBAL_STR_CONSTS\n#define USE_GLOBAL_STR_CONSTS true\n#endif\n\n\/\/ System C++ ABI unwind types from:\n\/\/     http:\/\/mentorembedded.github.com\/cxx-abi\/abi-eh.html (v1.22)\n\nextern \"C\" {\n\n  typedef enum {\n    _URC_NO_REASON = 0,\n    _URC_FOREIGN_EXCEPTION_CAUGHT = 1,\n    _URC_FATAL_PHASE2_ERROR = 2,\n    _URC_FATAL_PHASE1_ERROR = 3,\n    _URC_NORMAL_STOP = 4,\n    _URC_END_OF_STACK = 5,\n    _URC_HANDLER_FOUND = 6,\n    _URC_INSTALL_CONTEXT = 7,\n    _URC_CONTINUE_UNWIND = 8\n  } _Unwind_Reason_Code;\n\n  typedef enum {\n    _UA_SEARCH_PHASE = 1,\n    _UA_CLEANUP_PHASE = 2,\n    _UA_HANDLER_FRAME = 4,\n    _UA_FORCE_UNWIND = 8,\n    _UA_END_OF_STACK = 16\n  } _Unwind_Action;\n\n  struct _Unwind_Exception;\n\n  typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,\n                                                struct _Unwind_Exception *);\n\n  struct _Unwind_Exception {\n    uint64_t exception_class;\n    _Unwind_Exception_Cleanup_Fn exception_cleanup;\n\n    uintptr_t private_1;\n    uintptr_t private_2;\n\n    \/\/ @@@ The IA-64 ABI says that this structure must be double-word aligned.\n    \/\/  Taking that literally does not make much sense generically.  Instead\n    \/\/  we provide the maximum alignment required by any type for the machine.\n  } __attribute__((__aligned__));\n\n  struct _Unwind_Context;\n  typedef struct _Unwind_Context *_Unwind_Context_t;\n\n  extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);\n  extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);\n  extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);\n  extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);\n  extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);\n  extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);\n\n} \/\/ extern \"C\"\n\n\/\/\n\/\/ Example types\n\/\/\n\n\/\/\/ This is our simplistic type info\nstruct OurExceptionType_t {\n  \/\/\/ type info type\n  int type;\n};\n\n\n\/\/\/ This is our Exception class which relies on a negative offset to calculate\n\/\/\/ pointers to its instances from pointers to its unwindException member.\n\/\/\/\n\/\/\/ Note: The above unwind.h defines struct _Unwind_Exception to be aligned\n\/\/\/       on a double word boundary. This is necessary to match the standard:\n\/\/\/       http:\/\/mentorembedded.github.com\/cxx-abi\/abi-eh.html\nstruct OurBaseException_t {\n  struct OurExceptionType_t type;\n\n  \/\/ Note: This is properly aligned in unwind.h\n  struct _Unwind_Exception unwindException;\n};\n\n\n\/\/ Note: Not needed since we are C++\ntypedef struct OurBaseException_t OurException;\ntypedef struct _Unwind_Exception OurUnwindException;\n\n\/\/\n\/\/ Various globals used to support typeinfo and generatted exceptions in\n\/\/ general\n\/\/\n\nstatic std::map<std::string, llvm::Value*> namedValues;\n\nint64_t ourBaseFromUnwindOffset;\n\nconst unsigned char ourBaseExcpClassChars[] =\n{'o', 'b', 'j', '\\0', 'b', 'a', 's', '\\0'};\n\n\nstatic uint64_t ourBaseExceptionClass = 0;\n\nstatic std::vector<std::string> ourTypeInfoNames;\nstatic std::map<int, std::string> ourTypeInfoNamesIndex;\n\nstatic llvm::StructType *ourTypeInfoType;\nstatic llvm::StructType *ourCaughtResultType;\nstatic llvm::StructType *ourExceptionType;\nstatic llvm::StructType *ourUnwindExceptionType;\n\nstatic llvm::ConstantInt *ourExceptionNotThrownState;\nstatic llvm::ConstantInt *ourExceptionThrownState;\nstatic llvm::ConstantInt *ourExceptionCaughtState;\n\ntypedef std::vector<std::string> ArgNames;\ntypedef std::vector<llvm::Type*> ArgTypes;\n\n\/\/\n\/\/ Code Generation Utilities\n\/\/\n\n\/\/\/ Utility used to create a function, both declarations and definitions\n\/\/\/ @param module for module instance\n\/\/\/ @param retType function return type\n\/\/\/ @param theArgTypes function's ordered argument types\n\/\/\/ @param theArgNames function's ordered arguments needed if use of this\n\/\/\/        function corresponds to a function definition. Use empty\n\/\/\/        aggregate for function declarations.\n\/\/\/ @param functName function name\n\/\/\/ @param linkage function linkage\n\/\/\/ @param declarationOnly for function declarations\n\/\/\/ @param isVarArg function uses vararg arguments\n\/\/\/ @returns function instance\nllvm::Function *createFunction(llvm::Module &module,\n                               llvm::Type *retType,\n                               const ArgTypes &theArgTypes,\n                               const ArgNames &theArgNames,\n                               const std::string &functName,\n                               llvm::GlobalValue::LinkageTypes linkage,\n                               bool declarationOnly,\n                               bool isVarArg) {\n  llvm::FunctionType *functType =\n    llvm::FunctionType::get(retType, theArgTypes, isVarArg);\n  llvm::Function *ret =\n    llvm::Function::Create(functType, linkage, functName, &module);\n  if (!ret || declarationOnly)\n    return(ret);\n\n  namedValues.clear();\n  unsigned i = 0;\n  for (llvm::Function::arg_iterator argIndex = ret->arg_begin();\n       i != theArgNames.size();\n       ++argIndex, ++i) {\n\n    argIndex->setName(theArgNames[i]);\n    namedValues[theArgNames[i]] = argIndex;\n  }\n\n  return(ret);\n}\n\n\n\/\/\/ Create an alloca instruction in the entry block of\n\/\/\/ the parent function.  This is used for mutable variables etc.\n\/\/\/ @param function parent instance\n\/\/\/ @param varName stack variable name\n\/\/\/ @param type stack variable type\n\/\/\/ @param initWith optional constant initialization value\n\/\/\/ @returns AllocaInst instance\nstatic llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,\n                                                const std::string &varName,\n                                                llvm::Type *type,\n                                                llvm::Constant *initWith = 0) {\n  llvm::BasicBlock &block = function.getEntryBlock();\n  llvm::IRBuilder<> tmp(&block, block.begin());\n  llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());\n\n  if (initWith)\n    tmp.CreateStore(initWith, ret);\n\n  return(ret);\n}\n\n\n\/\/\n\/\/ Code Generation Utilities End\n\/\/\n\n\/\/\n\/\/ Runtime C Library functions\n\/\/\n\n\/\/ Note: using an extern \"C\" block so that static functions can be used\nextern \"C\" {\n\n\/\/ Note: Better ways to decide on bit width\n\/\/\n\/\/\/ Prints a 32 bit number, according to the format, to stderr.\n\/\/\/ @param intToPrint integer to print\n\/\/\/ @param format printf like format to use when printing\nvoid print32Int(int intToPrint, const char *format) {\n  if (format) {\n    \/\/ Note: No NULL check\n    fprintf(stderr, format, intToPrint);\n  }\n  else {\n    \/\/ Note: No NULL check\n    fprintf(stderr, \"::print32Int(...):NULL arg.\\n\");\n  }\n}\n\n\n\/\/ Note: Better ways to decide on bit width\n\/\/\n\/\/\/ Prints a 64 bit number, according to the format, to stderr.\n\/\/\/ @param intToPrint integer to print\n\/\/\/ @param format printf like format to use when printing\nvoid print64Int(long int intToPrint, const char *format) {\n  if (format) {\n    \/\/ Note: No NULL check\n    fprintf(stderr, format, intToPrint);\n  }\n  else {\n    \/\/ Note: No NULL check\n    fprintf(stderr, \"::print64Int(...):NULL arg.\\n\");\n  }\n}\n\n\n\/\/\/ Prints a C string to stderr\n\/\/\/ @param toPrint string to print\nvoid printStr(char *toPrint) {\n  if (toPrint) {\n    fprintf(stderr, \"%s\", toPrint);\n  }\n  else {\n    fprintf(stderr, \"::printStr(...):NULL arg.\\n\");\n  }\n}\n\n\n\/\/\/ Deletes the true previosly allocated exception whose address\n\/\/\/ is calculated from the supplied OurBaseException_t::unwindException\n\/\/\/ member address. Handles (ignores), NULL pointers.\n\/\/\/ @param expToDelete exception to delete\nvoid deleteOurException(OurUnwindException *expToDelete) {\n#ifdef DEBUG\n  fprintf(stderr,\n          \"deleteOurException(...).\\n\");\n#endif\n\n  if (expToDelete &&\n      (expToDelete->exception_class == ourBaseExceptionClass)) {\n\n    free(((char*) expToDelete) + ourBaseFromUnwindOffset);\n  }\n}\n\n\n\/\/\/ This function is the struct _Unwind_Exception API mandated delete function\n\/\/\/ used by foreign exception handlers when deleting our exception\n\/\/\/ (OurException), instances.\n\/\/\/ @param reason See @link http:\/\/mentorembedded.github.com\/cxx-abi\/abi-eh.html\n\/\/\/ @unlink\n\/\/\/ @param expToDelete exception instance to delete\nvoid deleteFromUnwindOurException(_Unwind_Reason_Code reason,\n                                  OurUnwindException *expToDelete) {\n#ifdef DEBUG\n  fprintf(stderr,\n          \"deleteFromUnwindOurException(...).\\n\");\n#endif\n\n  deleteOurException(expToDelete);\n}\n\n\n\/\/\/ Creates (allocates on the heap), an exception (OurException instance),\n\/\/\/ of the supplied type info type.\n\/\/\/ @param type type info type\nOurUnwindException *createOurException(int type) {\n  size_t size = sizeof(OurException);\n  OurException *ret = (OurException*) memset(malloc(size), 0, size);\n  (ret->type).type = type;\n  (ret->unwindException).exception_class = ourBaseExceptionClass;\n  (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;\n\n  return(&(ret->unwindException));\n}\n\n\n\/\/\/ Read a uleb128 encoded value and advance pointer\n\/\/\/ See Variable Length Data in:\n\/\/\/ @link http:\/\/dwarfstd.org\/Dwarf3.pdf @unlink\n\/\/\/ @param data reference variable holding memory pointer to decode from\n\/\/\/ @returns decoded value\nstatic uintptr_t readULEB128(const uint8_t **data) {\n  uintptr_t result = 0;\n  uintptr_t shift = 0;\n  unsigned char byte;\n  const uint8_t *p = *data;\n\n  do {\n    byte = *p++;\n    result |= (byte & 0x7f) << shift;\n    shift += 7;\n  }\n  while (byte & 0x80);\n\n  *data = p;\n\n  return result;\n}\n\n\n\/\/\/ Read a sleb128 encoded value and advance pointer\n\/\/\/ See Variable Length Data in:\n\/\/\/ @link http:\/\/dwarfstd.org\/Dwarf3.pdf @unlink\n\/\/\/ @param data reference variable holding memory pointer to decode from\n\/\/\/ @returns decoded value\nstatic uintptr_t readSLEB128(const uint8_t **data) {\n  uintptr_t result = 0;\n  uintptr_t shift = 0;\n  unsigned char byte;\n  const uint8_t *p = *data;\n\n  do {\n    byte = *p++;\n    result |= (byte & 0x7f) << shift;\n    shift += 7;\n  }\n  while (byte & 0x80);\n\n  *data = p;\n\n  if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {\n    result |= (~0 << shift);\n  }\n\n  return result;\n}\n\nunsigned getEncodingSize(uint8_t Encoding) {\n  if (Encoding == llvm::dwarf::DW_EH_PE_omit)\n    return 0;\n\n  switch (Encoding & 0x0F) {\n  case llvm::dwarf::DW_EH_PE_absptr:\n    return sizeof(uintptr_t);\n  case llvm::dwarf::DW_EH_PE_udata2:\n    return sizeof(uint16_t);\n  case llvm::dwarf::DW_EH_PE_udata4:\n    return sizeof(uint32_t);\n  case llvm::dwarf::DW_EH_PE_udata8:\n    return sizeof(uint64_t);\n  case llvm::dwarf::DW_EH_PE_sdata2:\n    return sizeof(int16_t);\n  case llvm::dwarf::DW_EH_PE_sdata4:\n    return sizeof(int32_t);\n  case llvm::dwarf::DW_EH_PE_sdata8:\n    return sizeof(int64_t);\n  default:\n    \/\/ not supported\n    abort();\n  }\n}\n\n\/\/\/ Read a pointer encoded value and advance pointer\n\/\/\/ See Variable Length Data in:\n\/\/\/ @link http:\/\/dwarfstd.org\/Dwarf3.pdf @unlink\n\/\/\/ @param data reference variable holding memory pointer to decode from\n\/\/\/ @param encoding dwarf encoding type\n\/\/\/ @returns decoded value\nstatic uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {\n  uintptr_t result = 0;\n  const uint8_t *p = *data;\n\n  if (encoding == llvm::dwarf::DW_EH_PE_omit)\n    return(result);\n\n  \/\/ first get value\n  switch (encoding & 0x0F) {\n    case llvm::dwarf::DW_EH_PE_absptr:\n      result = *((uintptr_t*)p);\n      p += sizeof(uintptr_t);\n      break;\n    case llvm::dwarf::DW_EH_PE_uleb128:\n      result = readULEB128(&p);\n      break;\n      \/\/ Note: This case has not been tested\n    case llvm::dwarf::DW_EH_PE_sleb128:\n      result = readSLEB128(&p);\n      break;\n    case llvm::dwarf::DW_EH_PE_udata2:\n      result = *((uint16_t*)p);\n      p += sizeof(uint16_t);\n      break;\n    case llvm::dwarf::DW_EH_PE_udata4:\n      result = *((uint32_t*)p);\n      p += sizeof(uint32_t);\n      break;\n    case llvm::dwarf::DW_EH_PE_udata8:\n      result = *((uint64_t*)p);\n      p += sizeof(uint64_t);\n      break;\n    case llvm::dwarf::DW_EH_PE_sdata2:\n      result = *((int16_t*)p);\n      p += sizeof(int16_t);\n      break;\n    case llvm::dwarf::DW_EH_PE_sdata4:\n      result = *((int32_t*)p);\n      p += sizeof(int32_t);\n      break;\n    case llvm::dwarf::DW_EH_PE_sdata8:\n      result = *((int64_t*)p);\n      p += sizeof(int64_t);\n      break;\n    default:\n      \/\/ not supported\n      abort();\n      break;\n  }\n\n  \/\/ then add relative offset\n  switch (encoding & 0x70) {\n    case llvm::dwarf::DW_EH_PE_absptr:\n      \/\/ do nothing\n      break;\n    case llvm::dwarf::DW_EH_PE_pcrel:\n      result += (uintptr_t)(*data);\n      break;\n    case llvm::dwarf::DW_EH_PE_textrel:\n    case llvm::dwarf::DW_EH_PE_datarel:\n    case llvm::dwarf::DW_EH_PE_funcrel:\n    case llvm::dwarf::DW_EH_PE_aligned:\n    default:\n      \/\/ not supported\n      abort();\n      break;\n  }\n\n  \/\/ then apply indirection\n  if (encoding & llvm::dwarf::DW_EH_PE_indirect) {\n    result = *((uintptr_t*)result);\n  }\n\n  *data = p;\n\n  return result;\n}\n\n\n\/\/\/ Deals with Dwarf actions matching our type infos\n\/\/\/ (OurExceptionType_t instances). Returns whether or not a dwarf emitted\n\/\/\/ action matches the supplied exception type. If such a match succeeds,\n\/\/\/ the resultAction argument will be set with > 0 index value. Only\n\/\/\/ corresponding llvm.eh.selector type info arguments, cleanup arguments\n\/\/\/ are supported. Filters are not supported.\n\/\/\/ See Variable Length Data in:\n\/\/\/ @link http:\/\/dwarfstd.org\/Dwarf3.pdf @unlink\n\/\/\/ Also see @link http:\/\/mentorembedded.github.com\/cxx-abi\/abi-eh.html @unlink\n\/\/\/ @param resultAction reference variable which will be set with result\n\/\/\/ @param classInfo our array of type info pointers (to globals)\n\/\/\/ @param actionEntry index into above type info array or 0 (clean up).\n\/\/\/        We do not support filters.\n\/\/\/ @param exceptionClass exception class (_Unwind_Exception::exception_class)\n\/\/\/        of thrown exception.\n\/\/\/ @param exceptionObject thrown _Unwind_Exception instance.\n\/\/\/ @returns whether or not a type info was found. False is returned if only\n\/\/\/          a cleanup was found\nstatic bool handleActionValue(int64_t *resultAction,\n                              uint8_t TTypeEncoding,\n                              const uint8_t *ClassInfo,\n                              uintptr_t actionEntry,\n                              uint64_t exceptionClass,\n                              struct _Unwind_Exception *exceptionObject) {\n  bool ret = false;\n\n  if (!resultAction ||\n      !exceptionObject ||\n      (exceptionClass != ourBaseExceptionClass))\n    return(ret);\n\n  struct OurBaseException_t *excp = (struct OurBaseException_t*)\n  (((char*) exceptionObject) + ourBaseFromUnwindOffset);\n  struct OurExceptionType_t *excpType = &(excp->type);\n  int type = excpType->type;\n\n#ifdef DEBUG\n  fprintf(stderr,\n          \"handleActionValue(...): exceptionObject = <%p>, \"\n          \"excp = <%p>.\\n\",\n          exceptionObject,\n          excp);\n#endif\n\n  const uint8_t *actionPos = (uint8_t*) actionEntry,\n  *tempActionPos;\n  int64_t typeOffset = 0,\n  actionOffset;\n\n  for (int i = 0; true; ++i) {\n    \/\/ Each emitted dwarf action corresponds to a 2 tuple of\n    \/\/ type info address offset, and action offset to the next\n    \/\/ emitted action.\n    typeOffset = readSLEB128(&actionPos);\n    tempActionPos = actionPos;\n    actionOffset = readSLEB128(&tempActionPos);\n\n#ifdef DEBUG\n    fprintf(stderr,\n            \"handleActionValue(...):typeOffset: <%lld>, \"\n            \"actionOffset: <%lld>.\\n\",\n            typeOffset,\n            actionOffset);\n#endif\n    assert((typeOffset >= 0) &&\n           \"handleActionValue(...):filters are not supported.\");\n\n    \/\/ Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector\n    \/\/       argument has been matched.\n    if (typeOffset > 0) {\n#ifdef DEBUG\n      fprintf(stderr,\n              \"handleActionValue(...):actionValue <%d> found.\\n\",\n              i);\n#endif\n      unsigned EncSize = getEncodingSize(TTypeEncoding);\n      const uint8_t *EntryP = ClassInfo - typeOffset * EncSize;\n      uintptr_t P = readEncodedPointer(&EntryP, TTypeEncoding);\n      struct OurExceptionType_t *ThisClassInfo =\n        reinterpret_cast<struct OurExceptionType_t *>(P);\n      if (ThisClassInfo->type == type) {\n        *resultAction = i + 1;\n        ret = true;\n        break;\n      }\n    }\n\n#ifdef DEBUG\n    fprintf(stderr,\n            \"handleActionValue(...):actionValue not found.\\n\");\n#endif\n    if (!actionOffset)\n      break;\n\n    actionPos += actionOffset;\n  }\n\n  return(ret);\n}\n\n\n\/\/\/ Deals with the Language specific data portion of the emitted dwarf code.\n\/\/\/ See @link http:\/\/mentorembedded.github.com\/cxx-abi\/abi-eh.html @unlink\n\/\/\/ @param version unsupported (ignored), unwind version\n\/\/\/ @param lsda language specific data area\n\/\/\/ @param _Unwind_Action actions minimally supported unwind stage\n\/\/\/        (forced specifically not supported)\n\/\/\/ @param exceptionClass exception class (_Unwind_Exception::exception_class)\n\/\/\/        of thrown exception.\n\/\/\/ @param exceptionObject thrown _Unwind_Exception instance.\n\/\/\/ @param context unwind system context\n\/\/\/ @returns minimally supported unwinding control indicator\nstatic _Unwind_Reason_Code handleLsda(int version,\n                                      const uint8_t *lsda,\n                                      _Unwind_Action actions,\n                                      uint64_t exceptionClass,\n                                    struct _Unwind_Exception *exceptionObject,\n                                      _Unwind_Context_t context) {\n  _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;\n\n  if (!lsda)\n    return(ret);\n\n#ifdef DEBUG\n  fprintf(stderr,\n          \"handleLsda(...):lsda is non-zero.\\n\");\n#endif\n\n  \/\/ Get the current instruction pointer and offset it before next\n  \/\/ instruction in the current frame which threw the exception.\n  uintptr_t pc = _Unwind_GetIP(context)-1;\n\n  \/\/ Get beginning current frame's code (as defined by the\n  \/\/ emitted dwarf code)\n  uintptr_t funcStart = _Unwind_GetRegionStart(context);\n  uintptr_t pcOffset = pc - funcStart;\n  const uint8_t *ClassInfo = NULL;\n\n  \/\/ Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding\n  \/\/       dwarf emission\n\n  \/\/ Parse LSDA header.\n  uint8_t lpStartEncoding = *lsda++;\n\n  if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {\n    readEncodedPointer(&lsda, lpStartEncoding);\n  }\n\n  uint8_t ttypeEncoding = *lsda++;\n  uintptr_t classInfoOffset;\n\n  if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {\n    \/\/ Calculate type info locations in emitted dwarf code which\n    \/\/ were flagged by type info arguments to llvm.eh.selector\n    \/\/ intrinsic\n    classInfoOffset = readULEB128(&lsda);\n    ClassInfo = lsda + classInfoOffset;\n  }\n\n  \/\/ Walk call-site table looking for range that\n  \/\/ includes current PC.\n\n  uint8_t         callSiteEncoding = *lsda++;\n  uint32_t        callSiteTableLength = readULEB128(&lsda);\n  const uint8_t   *callSiteTableStart = lsda;\n  const uint8_t   *callSiteTableEnd = callSiteTableStart +\n  callSiteTableLength;\n  const uint8_t   *actionTableStart = callSiteTableEnd;\n  const uint8_t   *callSitePtr = callSiteTableStart;\n\n  while (callSitePtr < callSiteTableEnd) {\n    uintptr_t start = readEncodedPointer(&callSitePtr,\n                                         callSiteEncoding);\n    uintptr_t length = readEncodedPointer(&callSitePtr,\n                                          callSiteEncoding);\n    uintptr_t landingPad = readEncodedPointer(&callSitePtr,\n                                              callSiteEncoding);\n\n    \/\/ Note: Action value\n    uintptr_t actionEntry = readULEB128(&callSitePtr);\n\n    if (exceptionClass != ourBaseExceptionClass) {\n      \/\/ We have been notified of a foreign exception being thrown,\n      \/\/ and we therefore need to execute cleanup landing pads\n      actionEntry = 0;\n    }\n\n    if (landingPad == 0) {\n#ifdef DEBUG\n      fprintf(stderr,\n              \"handleLsda(...): No landing pad found.\\n\");\n#endif\n\n      continue; \/\/ no landing pad for this entry\n    }\n\n    if (actionEntry) {\n      actionEntry += ((uintptr_t) actionTableStart) - 1;\n    }\n    else {\n#ifdef DEBUG\n      fprintf(stderr,\n              \"handleLsda(...):No action table found.\\n\");\n#endif\n    }\n\n    bool exceptionMatched = false;\n\n    if ((start <= pcOffset) && (pcOffset < (start + length))) {\n#ifdef DEBUG\n      fprintf(stderr,\n              \"handleLsda(...): Landing pad found.\\n\");\n#endif\n      int64_t actionValue = 0;\n\n      if (actionEntry) {\n        exceptionMatched = handleActionValue(&actionValue,\n                                             ttypeEncoding,\n                                             ClassInfo,\n                                             actionEntry,\n                                             exceptionClass,\n                                             exceptionObject);\n      }\n\n      if (!(actions & _UA_SEARCH_PHASE)) {\n#ifdef DEBUG\n        fprintf(stderr,\n                \"handleLsda(...): installed landing pad \"\n                \"context.\\n\");\n#endif\n\n        \/\/ Found landing pad for the PC.\n        \/\/ Set Instruction Pointer to so we re-enter function\n        \/\/ at landing pad. The landing pad is created by the\n        \/\/ compiler to take two parameters in registers.\n        _Unwind_SetGR(context,\n                      __builtin_eh_return_data_regno(0),\n                      (uintptr_t)exceptionObject);\n\n        \/\/ Note: this virtual register directly corresponds\n        \/\/       to the return of the llvm.eh.selector intrinsic\n        if (!actionEntry || !exceptionMatched) {\n          \/\/ We indicate cleanup only\n          _Unwind_SetGR(context,\n                        __builtin_eh_return_data_regno(1),\n                        0);\n        }\n        else {\n          \/\/ Matched type info index of llvm.eh.selector intrinsic\n          \/\/ passed here.\n          _Unwind_SetGR(context,\n                        __builtin_eh_return_data_regno(1),\n                        actionValue);\n        }\n\n        \/\/ To execute landing pad set here\n        _Unwind_SetIP(context, funcStart + landingPad);\n        ret = _URC_INSTALL_CONTEXT;\n      }\n      else if (exceptionMatched) {\n#ifdef DEBUG\n        fprintf(stderr,\n                \"handleLsda(...): setting handler found.\\n\");\n#endif\n        ret = _URC_HANDLER_FOUND;\n      }\n      else {\n        \/\/ Note: Only non-clean up handlers are marked as\n        \/\/       found. Otherwise the clean up handlers will be\n        \/\/       re-found and executed during the clean up\n        \/\/       phase.\n#ifdef DEBUG\n        fprintf(stderr,\n                \"handleLsda(...): cleanup handler found.\\n\");\n#endif\n      }\n\n      break;\n    }\n  }\n\n  return(ret);\n}\n\n\n\/\/\/ This is the personality function which is embedded (dwarf emitted), in the\n\/\/\/ dwarf unwind info block. Again see: JITDwarfEmitter.cpp.\n\/\/\/ See @link http:\/\/mentorembedded.github.com\/cxx-abi\/abi-eh.html @unlink\n\/\/\/ @param version unsupported (ignored), unwind version\n\/\/\/ @param _Unwind_Action actions minimally supported unwind stage\n\/\/\/        (forced specifically not supported)\n\/\/\/ @param exceptionClass exception class (_Unwind_Exception::exception_class)\n\/\/\/        of thrown exception.\n\/\/\/ @param exceptionObject thrown _Unwind_Exception instance.\n\/\/\/ @param context unwind system context\n\/\/\/ @returns minimally supported unwinding control indicator\n_Unwind_Reason_Code ourPersonality(int version,\n                                   _Unwind_Action actions,\n                                   uint64_t exceptionClass,\n                                   struct _Unwind_Exception *exceptionObject,\n                                   _Unwind_Context_t context) {\n#ifdef DEBUG\n  fprintf(stderr,\n          \"We are in ourPersonality(...):actions is <%d>.\\n\",\n          actions);\n\n  if (actions & _UA_SEARCH_PHASE) {\n    fprintf(stderr, \"ourPersonality(...):In search phase.\\n\");\n  }\n  else {\n    fprintf(stderr, \"ourPersonality(...):In non-search phase.\\n\");\n  }\n#endif\n\n  const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);\n\n#ifdef DEBUG\n  fprintf(stderr,\n          \"ourPersonality(...):lsda = <%p>.\\n\",\n          lsda);\n#endif\n\n  \/\/ The real work of the personality function is captured here\n  return(handleLsda(version,\n                    lsda,\n                    actions,\n                    exceptionClass,\n                    exceptionObject,\n                    context));\n}\n\n\n\/\/\/ Generates our _Unwind_Exception class from a given character array.\n\/\/\/ thereby handling arbitrary lengths (not in standard), and handling\n\/\/\/ embedded \\0s.\n\/\/\/ See @link http:\/\/mentorembedded.github.com\/cxx-abi\/abi-eh.html @unlink\n\/\/\/ @param classChars char array to encode. NULL values not checkedf\n\/\/\/ @param classCharsSize number of chars in classChars. Value is not checked.\n\/\/\/ @returns class value\nuint64_t genClass(const unsigned char classChars[], size_t classCharsSize)\n{\n  uint64_t ret = classChars[0];\n\n  for (unsigned i = 1; i < classCharsSize; ++i) {\n    ret <<= 8;\n    ret += classChars[i];\n  }\n\n  return(ret);\n}\n\n} \/\/ extern \"C\"\n\n\/\/\n\/\/ Runtime C Library functions End\n\/\/\n\n\/\/\n\/\/ Code generation functions\n\/\/\n\n\/\/\/ Generates code to print given constant string\n\/\/\/ @param context llvm context\n\/\/\/ @param module code for module instance\n\/\/\/ @param builder builder instance\n\/\/\/ @param toPrint string to print\n\/\/\/ @param useGlobal A value of true (default) indicates a GlobalValue is\n\/\/\/        generated, and is used to hold the constant string. A value of\n\/\/\/        false indicates that the constant string will be stored on the\n\/\/\/        stack.\nvoid generateStringPrint(llvm::LLVMContext &context,\n                         llvm::Module &module,\n                         llvm::IRBuilder<> &builder,\n                         std::string toPrint,\n                         bool useGlobal = true) {\n  llvm::Function *printFunct = module.getFunction(\"printStr\");\n\n  llvm::Value *stringVar;\n  llvm::Constant *stringConstant =\n  llvm::ConstantDataArray::getString(context, toPrint);\n\n  if (useGlobal) {\n    \/\/ Note: Does not work without allocation\n    stringVar =\n    new llvm::GlobalVariable(module,\n                             stringConstant->getType(),\n                             true,\n                             llvm::GlobalValue::PrivateLinkage,\n                             stringConstant,\n                             \"\");\n  }\n  else {\n    stringVar = builder.CreateAlloca(stringConstant->getType());\n    builder.CreateStore(stringConstant, stringVar);\n  }\n\n  llvm::Value *cast = builder.CreatePointerCast(stringVar,\n                                                builder.getInt8PtrTy());\n  builder.CreateCall(printFunct, cast);\n}\n\n\n\/\/\/ Generates code to print given runtime integer according to constant\n\/\/\/ string format, and a given print function.\n\/\/\/ @param context llvm context\n\/\/\/ @param module code for module instance\n\/\/\/ @param builder builder instance\n\/\/\/ @param printFunct function used to \"print\" integer\n\/\/\/ @param toPrint string to print\n\/\/\/ @param format printf like formating string for print\n\/\/\/ @param useGlobal A value of true (default) indicates a GlobalValue is\n\/\/\/        generated, and is used to hold the constant string. A value of\n\/\/\/        false indicates that the constant string will be stored on the\n\/\/\/        stack.\nvoid generateIntegerPrint(llvm::LLVMContext &context,\n                          llvm::Module &module,\n                          llvm::IRBuilder<> &builder,\n                          llvm::Function &printFunct,\n                          llvm::Value &toPrint,\n                          std::string format,\n                          bool useGlobal = true) {\n  llvm::Constant *stringConstant =\n    llvm::ConstantDataArray::getString(context, format);\n  llvm::Value *stringVar;\n\n  if (useGlobal) {\n    \/\/ Note: Does not seem to work without allocation\n    stringVar =\n    new llvm::GlobalVariable(module,\n                             stringConstant->getType(),\n                             true,\n                             llvm::GlobalValue::PrivateLinkage,\n                             stringConstant,\n                             \"\");\n  }\n  else {\n    stringVar = builder.CreateAlloca(stringConstant->getType());\n    builder.CreateStore(stringConstant, stringVar);\n  }\n\n  llvm::Value *cast = builder.CreateBitCast(stringVar,\n                                            builder.getInt8PtrTy());\n  builder.CreateCall2(&printFunct, &toPrint, cast);\n}\n\n\n\/\/\/ Generates code to handle finally block type semantics: always runs\n\/\/\/ regardless of whether a thrown exception is passing through or the\n\/\/\/ parent function is simply exiting. In addition to printing some state\n\/\/\/ to stderr, this code will resume the exception handling--runs the\n\/\/\/ unwind resume block, if the exception has not been previously caught\n\/\/\/ by a catch clause, and will otherwise execute the end block (terminator\n\/\/\/ block). In addition this function creates the corresponding function's\n\/\/\/ stack storage for the exception pointer and catch flag status.\n\/\/\/ @param context llvm context\n\/\/\/ @param module code for module instance\n\/\/\/ @param builder builder instance\n\/\/\/ @param toAddTo parent function to add block to\n\/\/\/ @param blockName block name of new \"finally\" block.\n\/\/\/ @param functionId output id used for printing\n\/\/\/ @param terminatorBlock terminator \"end\" block\n\/\/\/ @param unwindResumeBlock unwind resume block\n\/\/\/ @param exceptionCaughtFlag reference exception caught\/thrown status storage\n\/\/\/ @param exceptionStorage reference to exception pointer storage\n\/\/\/ @param caughtResultStorage reference to landingpad result storage\n\/\/\/ @returns newly created block\nstatic llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,\n                                            llvm::Module &module,\n                                            llvm::IRBuilder<> &builder,\n                                            llvm::Function &toAddTo,\n                                            std::string &blockName,\n                                            std::string &functionId,\n                                            llvm::BasicBlock &terminatorBlock,\n                                            llvm::BasicBlock &unwindResumeBlock,\n                                            llvm::Value **exceptionCaughtFlag,\n                                            llvm::Value **exceptionStorage,\n                                            llvm::Value **caughtResultStorage) {\n  assert(exceptionCaughtFlag &&\n         \"ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag \"\n         \"is NULL\");\n  assert(exceptionStorage &&\n         \"ExceptionDemo::createFinallyBlock(...):exceptionStorage \"\n         \"is NULL\");\n  assert(caughtResultStorage &&\n         \"ExceptionDemo::createFinallyBlock(...):caughtResultStorage \"\n         \"is NULL\");\n\n  *exceptionCaughtFlag = createEntryBlockAlloca(toAddTo,\n                                         \"exceptionCaught\",\n                                         ourExceptionNotThrownState->getType(),\n                                         ourExceptionNotThrownState);\n\n  llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();\n  *exceptionStorage = createEntryBlockAlloca(toAddTo,\n                                             \"exceptionStorage\",\n                                             exceptionStorageType,\n                                             llvm::ConstantPointerNull::get(\n                                               exceptionStorageType));\n  *caughtResultStorage = createEntryBlockAlloca(toAddTo,\n                                              \"caughtResultStorage\",\n                                              ourCaughtResultType,\n                                              llvm::ConstantAggregateZero::get(\n                                                ourCaughtResultType));\n\n  llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,\n                                                   blockName,\n                                                   &toAddTo);\n\n  builder.SetInsertPoint(ret);\n\n  std::ostringstream bufferToPrint;\n  bufferToPrint << \"Gen: Executing finally block \"\n    << blockName << \" in \" << functionId << \"\\n\";\n  generateStringPrint(context,\n                      module,\n                      builder,\n                      bufferToPrint.str(),\n                      USE_GLOBAL_STR_CONSTS);\n\n  llvm::SwitchInst *theSwitch = builder.CreateSwitch(builder.CreateLoad(\n                                                       *exceptionCaughtFlag),\n                                                     &terminatorBlock,\n                                                     2);\n  theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);\n  theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);\n\n  return(ret);\n}\n\n\n\/\/\/ Generates catch block semantics which print a string to indicate type of\n\/\/\/ catch executed, sets an exception caught flag, and executes passed in\n\/\/\/ end block (terminator block).\n\/\/\/ @param context llvm context\n\/\/\/ @param module code for module instance\n\/\/\/ @param builder builder instance\n\/\/\/ @param toAddTo parent function to add block to\n\/\/\/ @param blockName block name of new \"catch\" block.\n\/\/\/ @param functionId output id used for printing\n\/\/\/ @param terminatorBlock terminator \"end\" block\n\/\/\/ @param exceptionCaughtFlag exception caught\/thrown status\n\/\/\/ @returns newly created block\nstatic llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,\n                                          llvm::Module &module,\n                                          llvm::IRBuilder<> &builder,\n                                          llvm::Function &toAddTo,\n                                          std::string &blockName,\n                                          std::string &functionId,\n                                          llvm::BasicBlock &terminatorBlock,\n                                          llvm::Value &exceptionCaughtFlag) {\n\n  llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,\n                                                   blockName,\n                                                   &toAddTo);\n\n  builder.SetInsertPoint(ret);\n\n  std::ostringstream bufferToPrint;\n  bufferToPrint << \"Gen: Executing catch block \"\n  << blockName\n  << \" in \"\n  << functionId\n  << std::endl;\n  generateStringPrint(context,\n                      module,\n                      builder,\n                      bufferToPrint.str(),\n                      USE_GLOBAL_STR_CONSTS);\n  builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);\n  builder.CreateBr(&terminatorBlock);\n\n  return(ret);\n}\n\n\n\/\/\/ Generates a function which invokes a function (toInvoke) and, whose\n\/\/\/ unwind block will \"catch\" the type info types correspondingly held in the\n\/\/\/ exceptionTypesToCatch argument. If the toInvoke function throws an\n\/\/\/ exception which does not match any type info types contained in\n\/\/\/ exceptionTypesToCatch, the generated code will call _Unwind_Resume\n\/\/\/ with the raised exception. On the other hand the generated code will\n\/\/\/ normally exit if the toInvoke function does not throw an exception.\n\/\/\/ The generated \"finally\" block is always run regardless of the cause of\n\/\/\/ the generated function exit.\n\/\/\/ The generated function is returned after being verified.\n\/\/\/ @param module code for module instance\n\/\/\/ @param builder builder instance\n\/\/\/ @param fpm a function pass manager holding optional IR to IR\n\/\/\/        transformations\n\/\/\/ @param toInvoke inner function to invoke\n\/\/\/ @param ourId id used to printing purposes\n\/\/\/ @param numExceptionsToCatch length of exceptionTypesToCatch array\n\/\/\/ @param exceptionTypesToCatch array of type info types to \"catch\"\n\/\/\/ @returns generated function\nstatic llvm::Function *createCatchWrappedInvokeFunction(\n    llvm::Module &module, llvm::IRBuilder<> &builder,\n    llvm::legacy::FunctionPassManager &fpm, llvm::Function &toInvoke,\n    std::string ourId, unsigned numExceptionsToCatch,\n    unsigned exceptionTypesToCatch[]) {\n\n  llvm::LLVMContext &context = module.getContext();\n  llvm::Function *toPrint32Int = module.getFunction(\"print32Int\");\n\n  ArgTypes argTypes;\n  argTypes.push_back(builder.getInt32Ty());\n\n  ArgNames argNames;\n  argNames.push_back(\"exceptTypeToThrow\");\n\n  llvm::Function *ret = createFunction(module,\n                                       builder.getVoidTy(),\n                                       argTypes,\n                                       argNames,\n                                       ourId,\n                                       llvm::Function::ExternalLinkage,\n                                       false,\n                                       false);\n\n  \/\/ Block which calls invoke\n  llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,\n                                                          \"entry\",\n                                                          ret);\n  \/\/ Normal block for invoke\n  llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,\n                                                           \"normal\",\n                                                           ret);\n  \/\/ Unwind block for invoke\n  llvm::BasicBlock *exceptionBlock = llvm::BasicBlock::Create(context,\n                                                              \"exception\",\n                                                              ret);\n\n  \/\/ Block which routes exception to correct catch handler block\n  llvm::BasicBlock *exceptionRouteBlock = llvm::BasicBlock::Create(context,\n                                                             \"exceptionRoute\",\n                                                             ret);\n\n  \/\/ Foreign exception handler\n  llvm::BasicBlock *externalExceptionBlock = llvm::BasicBlock::Create(context,\n                                                          \"externalException\",\n                                                          ret);\n\n  \/\/ Block which calls _Unwind_Resume\n  llvm::BasicBlock *unwindResumeBlock = llvm::BasicBlock::Create(context,\n                                                               \"unwindResume\",\n                                                               ret);\n\n  \/\/ Clean up block which delete exception if needed\n  llvm::BasicBlock *endBlock = llvm::BasicBlock::Create(context, \"end\", ret);\n\n  std::string nextName;\n  std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);\n  llvm::Value *exceptionCaughtFlag = NULL;\n  llvm::Value *exceptionStorage = NULL;\n  llvm::Value *caughtResultStorage = NULL;\n\n  \/\/ Finally block which will branch to unwindResumeBlock if\n  \/\/ exception is not caught. Initializes\/allocates stack locations.\n  llvm::BasicBlock *finallyBlock = createFinallyBlock(context,\n                                                      module,\n                                                      builder,\n                                                      *ret,\n                                                      nextName = \"finally\",\n                                                      ourId,\n                                                      *endBlock,\n                                                      *unwindResumeBlock,\n                                                      &exceptionCaughtFlag,\n                                                      &exceptionStorage,\n                                                      &caughtResultStorage\n                                                      );\n\n  for (unsigned i = 0; i < numExceptionsToCatch; ++i) {\n    nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];\n\n    \/\/ One catch block per type info to be caught\n    catchBlocks[i] = createCatchBlock(context,\n                                      module,\n                                      builder,\n                                      *ret,\n                                      nextName,\n                                      ourId,\n                                      *finallyBlock,\n                                      *exceptionCaughtFlag);\n  }\n\n  \/\/ Entry Block\n\n  builder.SetInsertPoint(entryBlock);\n\n  std::vector<llvm::Value*> args;\n  args.push_back(namedValues[\"exceptTypeToThrow\"]);\n  builder.CreateInvoke(&toInvoke,\n                       normalBlock,\n                       exceptionBlock,\n                       args);\n\n  \/\/ End Block\n\n  builder.SetInsertPoint(endBlock);\n\n  generateStringPrint(context,\n                      module,\n                      builder,\n                      \"Gen: In end block: exiting in \" + ourId + \".\\n\",\n                      USE_GLOBAL_STR_CONSTS);\n  llvm::Function *deleteOurException = module.getFunction(\"deleteOurException\");\n\n  \/\/ Note: function handles NULL exceptions\n  builder.CreateCall(deleteOurException,\n                     builder.CreateLoad(exceptionStorage));\n  builder.CreateRetVoid();\n\n  \/\/ Normal Block\n\n  builder.SetInsertPoint(normalBlock);\n\n  generateStringPrint(context,\n                      module,\n                      builder,\n                      \"Gen: No exception in \" + ourId + \"!\\n\",\n                      USE_GLOBAL_STR_CONSTS);\n\n  \/\/ Finally block is always called\n  builder.CreateBr(finallyBlock);\n\n  \/\/ Unwind Resume Block\n\n  builder.SetInsertPoint(unwindResumeBlock);\n\n  builder.CreateResume(builder.CreateLoad(caughtResultStorage));\n\n  \/\/ Exception Block\n\n  builder.SetInsertPoint(exceptionBlock);\n\n  llvm::Function *personality = module.getFunction(\"ourPersonality\");\n\n  llvm::LandingPadInst *caughtResult =\n    builder.CreateLandingPad(ourCaughtResultType,\n                             personality,\n                             numExceptionsToCatch,\n                             \"landingPad\");\n\n  caughtResult->setCleanup(true);\n\n  for (unsigned i = 0; i < numExceptionsToCatch; ++i) {\n    \/\/ Set up type infos to be caught\n    caughtResult->addClause(module.getGlobalVariable(\n                             ourTypeInfoNames[exceptionTypesToCatch[i]]));\n  }\n\n  llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);\n  llvm::Value *retTypeInfoIndex = builder.CreateExtractValue(caughtResult, 1);\n\n  \/\/ FIXME: Redundant storage which, beyond utilizing value of\n  \/\/        caughtResultStore for unwindException storage, may be alleviated\n  \/\/        altogether with a block rearrangement\n  builder.CreateStore(caughtResult, caughtResultStorage);\n  builder.CreateStore(unwindException, exceptionStorage);\n  builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);\n\n  \/\/ Retrieve exception_class member from thrown exception\n  \/\/ (_Unwind_Exception instance). This member tells us whether or not\n  \/\/ the exception is foreign.\n  llvm::Value *unwindExceptionClass =\n      builder.CreateLoad(builder.CreateStructGEP(\n          ourUnwindExceptionType,\n          builder.CreatePointerCast(unwindException,\n                                    ourUnwindExceptionType->getPointerTo()),\n          0));\n\n  \/\/ Branch to the externalExceptionBlock if the exception is foreign or\n  \/\/ to a catch router if not. Either way the finally block will be run.\n  builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,\n                            llvm::ConstantInt::get(builder.getInt64Ty(),\n                                                   ourBaseExceptionClass)),\n                       exceptionRouteBlock,\n                       externalExceptionBlock);\n\n  \/\/ External Exception Block\n\n  builder.SetInsertPoint(externalExceptionBlock);\n\n  generateStringPrint(context,\n                      module,\n                      builder,\n                      \"Gen: Foreign exception received.\\n\",\n                      USE_GLOBAL_STR_CONSTS);\n\n  \/\/ Branch to the finally block\n  builder.CreateBr(finallyBlock);\n\n  \/\/ Exception Route Block\n\n  builder.SetInsertPoint(exceptionRouteBlock);\n\n  \/\/ Casts exception pointer (_Unwind_Exception instance) to parent\n  \/\/ (OurException instance).\n  \/\/\n  \/\/ Note: ourBaseFromUnwindOffset is usually negative\n  llvm::Value *typeInfoThrown = builder.CreatePointerCast(\n                                  builder.CreateConstGEP1_64(unwindException,\n                                                       ourBaseFromUnwindOffset),\n                                  ourExceptionType->getPointerTo());\n\n  \/\/ Retrieve thrown exception type info type\n  \/\/\n  \/\/ Note: Index is not relative to pointer but instead to structure\n  \/\/       unlike a true getelementptr (GEP) instruction\n  typeInfoThrown = builder.CreateStructGEP(ourExceptionType, typeInfoThrown, 0);\n\n  llvm::Value *typeInfoThrownType =\n      builder.CreateStructGEP(builder.getInt8PtrTy(), typeInfoThrown, 0);\n\n  generateIntegerPrint(context,\n                       module,\n                       builder,\n                       *toPrint32Int,\n                       *(builder.CreateLoad(typeInfoThrownType)),\n                       \"Gen: Exception type <%d> received (stack unwound) \"\n                       \" in \" +\n                       ourId +\n                       \".\\n\",\n                       USE_GLOBAL_STR_CONSTS);\n\n  \/\/ Route to matched type info catch block or run cleanup finally block\n  llvm::SwitchInst *switchToCatchBlock = builder.CreateSwitch(retTypeInfoIndex,\n                                                          finallyBlock,\n                                                          numExceptionsToCatch);\n\n  unsigned nextTypeToCatch;\n\n  for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {\n    nextTypeToCatch = i - 1;\n    switchToCatchBlock->addCase(llvm::ConstantInt::get(\n                                   llvm::Type::getInt32Ty(context), i),\n                                catchBlocks[nextTypeToCatch]);\n  }\n\n  llvm::verifyFunction(*ret);\n  fpm.run(*ret);\n\n  return(ret);\n}\n\n\n\/\/\/ Generates function which throws either an exception matched to a runtime\n\/\/\/ determined type info type (argument to generated function), or if this\n\/\/\/ runtime value matches nativeThrowType, throws a foreign exception by\n\/\/\/ calling nativeThrowFunct.\n\/\/\/ @param module code for module instance\n\/\/\/ @param builder builder instance\n\/\/\/ @param fpm a function pass manager holding optional IR to IR\n\/\/\/        transformations\n\/\/\/ @param ourId id used to printing purposes\n\/\/\/ @param nativeThrowType a runtime argument of this value results in\n\/\/\/        nativeThrowFunct being called to generate\/throw exception.\n\/\/\/ @param nativeThrowFunct function which will throw a foreign exception\n\/\/\/        if the above nativeThrowType matches generated function's arg.\n\/\/\/ @returns generated function\nstatic llvm::Function *\ncreateThrowExceptionFunction(llvm::Module &module, llvm::IRBuilder<> &builder,\n                             llvm::legacy::FunctionPassManager &fpm,\n                             std::string ourId, int32_t nativeThrowType,\n                             llvm::Function &nativeThrowFunct) {\n  llvm::LLVMContext &context = module.getContext();\n  namedValues.clear();\n  ArgTypes unwindArgTypes;\n  unwindArgTypes.push_back(builder.getInt32Ty());\n  ArgNames unwindArgNames;\n  unwindArgNames.push_back(\"exceptTypeToThrow\");\n\n  llvm::Function *ret = createFunction(module,\n                                       builder.getVoidTy(),\n                                       unwindArgTypes,\n                                       unwindArgNames,\n                                       ourId,\n                                       llvm::Function::ExternalLinkage,\n                                       false,\n                                       false);\n\n  \/\/ Throws either one of our exception or a native C++ exception depending\n  \/\/ on a runtime argument value containing a type info type.\n  llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,\n                                                          \"entry\",\n                                                          ret);\n  \/\/ Throws a foreign exception\n  llvm::BasicBlock *nativeThrowBlock = llvm::BasicBlock::Create(context,\n                                                                \"nativeThrow\",\n                                                                ret);\n  \/\/ Throws one of our Exceptions\n  llvm::BasicBlock *generatedThrowBlock = llvm::BasicBlock::Create(context,\n                                                             \"generatedThrow\",\n                                                             ret);\n  \/\/ Retrieved runtime type info type to throw\n  llvm::Value *exceptionType = namedValues[\"exceptTypeToThrow\"];\n\n  \/\/ nativeThrowBlock block\n\n  builder.SetInsertPoint(nativeThrowBlock);\n\n  \/\/ Throws foreign exception\n  builder.CreateCall(&nativeThrowFunct, exceptionType);\n  builder.CreateUnreachable();\n\n  \/\/ entry block\n\n  builder.SetInsertPoint(entryBlock);\n\n  llvm::Function *toPrint32Int = module.getFunction(\"print32Int\");\n  generateIntegerPrint(context,\n                       module,\n                       builder,\n                       *toPrint32Int,\n                       *exceptionType,\n                       \"\\nGen: About to throw exception type <%d> in \" +\n                       ourId +\n                       \".\\n\",\n                       USE_GLOBAL_STR_CONSTS);\n\n  \/\/ Switches on runtime type info type value to determine whether or not\n  \/\/ a foreign exception is thrown. Defaults to throwing one of our\n  \/\/ generated exceptions.\n  llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,\n                                                     generatedThrowBlock,\n                                                     1);\n\n  theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),\n                                            nativeThrowType),\n                     nativeThrowBlock);\n\n  \/\/ generatedThrow block\n\n  builder.SetInsertPoint(generatedThrowBlock);\n\n  llvm::Function *createOurException = module.getFunction(\"createOurException\");\n  llvm::Function *raiseOurException = module.getFunction(\n                                        \"_Unwind_RaiseException\");\n\n  \/\/ Creates exception to throw with runtime type info type.\n  llvm::Value *exception = builder.CreateCall(createOurException,\n                                              namedValues[\"exceptTypeToThrow\"]);\n\n  \/\/ Throw generated Exception\n  builder.CreateCall(raiseOurException, exception);\n  builder.CreateUnreachable();\n\n  llvm::verifyFunction(*ret);\n  fpm.run(*ret);\n\n  return(ret);\n}\n\nstatic void createStandardUtilityFunctions(unsigned numTypeInfos,\n                                           llvm::Module &module,\n                                           llvm::IRBuilder<> &builder);\n\n\/\/\/ Creates test code by generating and organizing these functions into the\n\/\/\/ test case. The test case consists of an outer function setup to invoke\n\/\/\/ an inner function within an environment having multiple catch and single\n\/\/\/ finally blocks. This inner function is also setup to invoke a throw\n\/\/\/ function within an evironment similar in nature to the outer function's\n\/\/\/ catch and finally blocks. Each of these two functions catch mutually\n\/\/\/ exclusive subsets (even or odd) of the type info types configured\n\/\/\/ for this this. All generated functions have a runtime argument which\n\/\/\/ holds a type info type to throw that each function takes and passes it\n\/\/\/ to the inner one if such a inner function exists. This type info type is\n\/\/\/ looked at by the generated throw function to see whether or not it should\n\/\/\/ throw a generated exception with the same type info type, or instead call\n\/\/\/ a supplied a function which in turn will throw a foreign exception.\n\/\/\/ @param module code for module instance\n\/\/\/ @param builder builder instance\n\/\/\/ @param fpm a function pass manager holding optional IR to IR\n\/\/\/        transformations\n\/\/\/ @param nativeThrowFunctName name of external function which will throw\n\/\/\/        a foreign exception\n\/\/\/ @returns outermost generated test function.\nllvm::Function *\ncreateUnwindExceptionTest(llvm::Module &module, llvm::IRBuilder<> &builder,\n                          llvm::legacy::FunctionPassManager &fpm,\n                          std::string nativeThrowFunctName) {\n  \/\/ Number of type infos to generate\n  unsigned numTypeInfos = 6;\n\n  \/\/ Initialze intrisics and external functions to use along with exception\n  \/\/ and type info globals.\n  createStandardUtilityFunctions(numTypeInfos,\n                                 module,\n                                 builder);\n  llvm::Function *nativeThrowFunct = module.getFunction(nativeThrowFunctName);\n\n  \/\/ Create exception throw function using the value ~0 to cause\n  \/\/ foreign exceptions to be thrown.\n  llvm::Function *throwFunct = createThrowExceptionFunction(module,\n                                                            builder,\n                                                            fpm,\n                                                            \"throwFunct\",\n                                                            ~0,\n                                                            *nativeThrowFunct);\n  \/\/ Inner function will catch even type infos\n  unsigned innerExceptionTypesToCatch[] = {6, 2, 4};\n  size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) \/\n                                    sizeof(unsigned);\n\n  \/\/ Generate inner function.\n  llvm::Function *innerCatchFunct = createCatchWrappedInvokeFunction(module,\n                                                    builder,\n                                                    fpm,\n                                                    *throwFunct,\n                                                    \"innerCatchFunct\",\n                                                    numExceptionTypesToCatch,\n                                                    innerExceptionTypesToCatch);\n\n  \/\/ Outer function will catch odd type infos\n  unsigned outerExceptionTypesToCatch[] = {3, 1, 5};\n  numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) \/\n  sizeof(unsigned);\n\n  \/\/ Generate outer function\n  llvm::Function *outerCatchFunct = createCatchWrappedInvokeFunction(module,\n                                                    builder,\n                                                    fpm,\n                                                    *innerCatchFunct,\n                                                    \"outerCatchFunct\",\n                                                    numExceptionTypesToCatch,\n                                                    outerExceptionTypesToCatch);\n\n  \/\/ Return outer function to run\n  return(outerCatchFunct);\n}\n\nnamespace {\n\/\/\/ Represents our foreign exceptions\nclass OurCppRunException : public std::runtime_error {\npublic:\n  OurCppRunException(const std::string reason) :\n  std::runtime_error(reason) {}\n\n  OurCppRunException (const OurCppRunException &toCopy) :\n  std::runtime_error(toCopy) {}\n\n  OurCppRunException &operator = (const OurCppRunException &toCopy) {\n    return(reinterpret_cast<OurCppRunException&>(\n                                 std::runtime_error::operator=(toCopy)));\n  }\n\n  ~OurCppRunException(void) throw() override {}\n};\n} \/\/ end anonymous namespace\n\n\/\/\/ Throws foreign C++ exception.\n\/\/\/ @param ignoreIt unused parameter that allows function to match implied\n\/\/\/        generated function contract.\nextern \"C\"\nvoid throwCppException (int32_t ignoreIt) {\n  throw(OurCppRunException(\"thrown by throwCppException(...)\"));\n}\n\ntypedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);\n\n\/\/\/ This is a test harness which runs test by executing generated\n\/\/\/ function with a type info type to throw. Harness wraps the execution\n\/\/\/ of generated function in a C++ try catch clause.\n\/\/\/ @param engine execution engine to use for executing generated function.\n\/\/\/        This demo program expects this to be a JIT instance for demo\n\/\/\/        purposes.\n\/\/\/ @param function generated test function to run\n\/\/\/ @param typeToThrow type info type of generated exception to throw, or\n\/\/\/        indicator to cause foreign exception to be thrown.\nstatic\nvoid runExceptionThrow(llvm::ExecutionEngine *engine,\n                       llvm::Function *function,\n                       int32_t typeToThrow) {\n\n  \/\/ Find test's function pointer\n  OurExceptionThrowFunctType functPtr =\n    reinterpret_cast<OurExceptionThrowFunctType>(\n       reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));\n\n  try {\n    \/\/ Run test\n    (*functPtr)(typeToThrow);\n  }\n  catch (OurCppRunException exc) {\n    \/\/ Catch foreign C++ exception\n    fprintf(stderr,\n            \"\\nrunExceptionThrow(...):In C++ catch OurCppRunException \"\n            \"with reason: %s.\\n\",\n            exc.what());\n  }\n  catch (...) {\n    \/\/ Catch all exceptions including our generated ones. This latter\n    \/\/ functionality works according to the example in rules 1.6.4 of\n    \/\/ http:\/\/mentorembedded.github.com\/cxx-abi\/abi-eh.html (v1.22),\n    \/\/ given that these will be exceptions foreign to C++\n    \/\/ (the _Unwind_Exception::exception_class should be different from\n    \/\/ the one used by C++).\n    fprintf(stderr,\n            \"\\nrunExceptionThrow(...):In C++ catch all.\\n\");\n  }\n}\n\n\/\/\n\/\/ End test functions\n\/\/\n\ntypedef llvm::ArrayRef<llvm::Type*> TypeArray;\n\n\/\/\/ This initialization routine creates type info globals and\n\/\/\/ adds external function declarations to module.\n\/\/\/ @param numTypeInfos number of linear type info associated type info types\n\/\/\/        to create as GlobalVariable instances, starting with the value 1.\n\/\/\/ @param module code for module instance\n\/\/\/ @param builder builder instance\nstatic void createStandardUtilityFunctions(unsigned numTypeInfos,\n                                           llvm::Module &module,\n                                           llvm::IRBuilder<> &builder) {\n\n  llvm::LLVMContext &context = module.getContext();\n\n  \/\/ Exception initializations\n\n  \/\/ Setup exception catch state\n  ourExceptionNotThrownState =\n    llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),\n  ourExceptionThrownState =\n    llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),\n  ourExceptionCaughtState =\n    llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),\n\n\n\n  \/\/ Create our type info type\n  ourTypeInfoType = llvm::StructType::get(context,\n                                          TypeArray(builder.getInt32Ty()));\n\n  llvm::Type *caughtResultFieldTypes[] = {\n    builder.getInt8PtrTy(),\n    builder.getInt32Ty()\n  };\n\n  \/\/ Create our landingpad result type\n  ourCaughtResultType = llvm::StructType::get(context,\n                                            TypeArray(caughtResultFieldTypes));\n\n  \/\/ Create OurException type\n  ourExceptionType = llvm::StructType::get(context,\n                                           TypeArray(ourTypeInfoType));\n\n  \/\/ Create portion of _Unwind_Exception type\n  \/\/\n  \/\/ Note: Declaring only a portion of the _Unwind_Exception struct.\n  \/\/       Does this cause problems?\n  ourUnwindExceptionType =\n    llvm::StructType::get(context,\n                    TypeArray(builder.getInt64Ty()));\n\n  struct OurBaseException_t dummyException;\n\n  \/\/ Calculate offset of OurException::unwindException member.\n  ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -\n                            ((uintptr_t) &(dummyException.unwindException));\n\n#ifdef DEBUG\n  fprintf(stderr,\n          \"createStandardUtilityFunctions(...):ourBaseFromUnwindOffset \"\n          \"= %lld, sizeof(struct OurBaseException_t) - \"\n          \"sizeof(struct _Unwind_Exception) = %lu.\\n\",\n          ourBaseFromUnwindOffset,\n          sizeof(struct OurBaseException_t) -\n          sizeof(struct _Unwind_Exception));\n#endif\n\n  size_t numChars = sizeof(ourBaseExcpClassChars) \/ sizeof(char);\n\n  \/\/ Create our _Unwind_Exception::exception_class value\n  ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);\n\n  \/\/ Type infos\n\n  std::string baseStr = \"typeInfo\", typeInfoName;\n  std::ostringstream typeInfoNameBuilder;\n  std::vector<llvm::Constant*> structVals;\n\n  llvm::Constant *nextStruct;\n\n  \/\/ Generate each type info\n  \/\/\n  \/\/ Note: First type info is not used.\n  for (unsigned i = 0; i <= numTypeInfos; ++i) {\n    structVals.clear();\n    structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));\n    nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);\n\n    typeInfoNameBuilder.str(\"\");\n    typeInfoNameBuilder << baseStr << i;\n    typeInfoName = typeInfoNameBuilder.str();\n\n    \/\/ Note: Does not seem to work without allocation\n    new llvm::GlobalVariable(module,\n                             ourTypeInfoType,\n                             true,\n                             llvm::GlobalValue::ExternalLinkage,\n                             nextStruct,\n                             typeInfoName);\n\n    ourTypeInfoNames.push_back(typeInfoName);\n    ourTypeInfoNamesIndex[i] = typeInfoName;\n  }\n\n  ArgNames argNames;\n  ArgTypes argTypes;\n  llvm::Function *funct = NULL;\n\n  \/\/ print32Int\n\n  llvm::Type *retType = builder.getVoidTy();\n\n  argTypes.clear();\n  argTypes.push_back(builder.getInt32Ty());\n  argTypes.push_back(builder.getInt8PtrTy());\n\n  argNames.clear();\n\n  createFunction(module,\n                 retType,\n                 argTypes,\n                 argNames,\n                 \"print32Int\",\n                 llvm::Function::ExternalLinkage,\n                 true,\n                 false);\n\n  \/\/ print64Int\n\n  retType = builder.getVoidTy();\n\n  argTypes.clear();\n  argTypes.push_back(builder.getInt64Ty());\n  argTypes.push_back(builder.getInt8PtrTy());\n\n  argNames.clear();\n\n  createFunction(module,\n                 retType,\n                 argTypes,\n                 argNames,\n                 \"print64Int\",\n                 llvm::Function::ExternalLinkage,\n                 true,\n                 false);\n\n  \/\/ printStr\n\n  retType = builder.getVoidTy();\n\n  argTypes.clear();\n  argTypes.push_back(builder.getInt8PtrTy());\n\n  argNames.clear();\n\n  createFunction(module,\n                 retType,\n                 argTypes,\n                 argNames,\n                 \"printStr\",\n                 llvm::Function::ExternalLinkage,\n                 true,\n                 false);\n\n  \/\/ throwCppException\n\n  retType = builder.getVoidTy();\n\n  argTypes.clear();\n  argTypes.push_back(builder.getInt32Ty());\n\n  argNames.clear();\n\n  createFunction(module,\n                 retType,\n                 argTypes,\n                 argNames,\n                 \"throwCppException\",\n                 llvm::Function::ExternalLinkage,\n                 true,\n                 false);\n\n  \/\/ deleteOurException\n\n  retType = builder.getVoidTy();\n\n  argTypes.clear();\n  argTypes.push_back(builder.getInt8PtrTy());\n\n  argNames.clear();\n\n  createFunction(module,\n                 retType,\n                 argTypes,\n                 argNames,\n                 \"deleteOurException\",\n                 llvm::Function::ExternalLinkage,\n                 true,\n                 false);\n\n  \/\/ createOurException\n\n  retType = builder.getInt8PtrTy();\n\n  argTypes.clear();\n  argTypes.push_back(builder.getInt32Ty());\n\n  argNames.clear();\n\n  createFunction(module,\n                 retType,\n                 argTypes,\n                 argNames,\n                 \"createOurException\",\n                 llvm::Function::ExternalLinkage,\n                 true,\n                 false);\n\n  \/\/ _Unwind_RaiseException\n\n  retType = builder.getInt32Ty();\n\n  argTypes.clear();\n  argTypes.push_back(builder.getInt8PtrTy());\n\n  argNames.clear();\n\n  funct = createFunction(module,\n                         retType,\n                         argTypes,\n                         argNames,\n                         \"_Unwind_RaiseException\",\n                         llvm::Function::ExternalLinkage,\n                         true,\n                         false);\n\n  funct->setDoesNotReturn();\n\n  \/\/ _Unwind_Resume\n\n  retType = builder.getInt32Ty();\n\n  argTypes.clear();\n  argTypes.push_back(builder.getInt8PtrTy());\n\n  argNames.clear();\n\n  funct = createFunction(module,\n                         retType,\n                         argTypes,\n                         argNames,\n                         \"_Unwind_Resume\",\n                         llvm::Function::ExternalLinkage,\n                         true,\n                         false);\n\n  funct->setDoesNotReturn();\n\n  \/\/ ourPersonality\n\n  retType = builder.getInt32Ty();\n\n  argTypes.clear();\n  argTypes.push_back(builder.getInt32Ty());\n  argTypes.push_back(builder.getInt32Ty());\n  argTypes.push_back(builder.getInt64Ty());\n  argTypes.push_back(builder.getInt8PtrTy());\n  argTypes.push_back(builder.getInt8PtrTy());\n\n  argNames.clear();\n\n  createFunction(module,\n                 retType,\n                 argTypes,\n                 argNames,\n                 \"ourPersonality\",\n                 llvm::Function::ExternalLinkage,\n                 true,\n                 false);\n\n  \/\/ llvm.eh.typeid.for intrinsic\n\n  getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Main test driver code.\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ Demo main routine which takes the type info types to throw. A test will\n\/\/\/ be run for each given type info type. While type info types with the value\n\/\/\/ of -1 will trigger a foreign C++ exception to be thrown; type info types\n\/\/\/ <= 6 and >= 1 will be caught by test functions; and type info types > 6\n\/\/\/ will result in exceptions which pass through to the test harness. All other\n\/\/\/ type info types are not supported and could cause a crash.\nint main(int argc, char *argv[]) {\n  if (argc == 1) {\n    fprintf(stderr,\n            \"\\nUsage: ExceptionDemo <exception type to throw> \"\n            \"[<type 2>...<type n>].\\n\"\n            \"   Each type must have the value of 1 - 6 for \"\n            \"generated exceptions to be caught;\\n\"\n            \"   the value -1 for foreign C++ exceptions to be \"\n            \"generated and thrown;\\n\"\n            \"   or the values > 6 for exceptions to be ignored.\\n\"\n            \"\\nTry: ExceptionDemo 2 3 7 -1\\n\"\n            \"   for a full test.\\n\\n\");\n    return(0);\n  }\n\n  \/\/ If not set, exception handling will not be turned on\n  llvm::TargetOptions Opts;\n\n  llvm::InitializeNativeTarget();\n  llvm::InitializeNativeTargetAsmPrinter();\n  llvm::LLVMContext &context = llvm::getGlobalContext();\n  llvm::IRBuilder<> theBuilder(context);\n\n  \/\/ Make the module, which holds all the code.\n  std::unique_ptr<llvm::Module> Owner =\n      llvm::make_unique<llvm::Module>(\"my cool jit\", context);\n  llvm::Module *module = Owner.get();\n\n  std::unique_ptr<llvm::RTDyldMemoryManager> MemMgr(new llvm::SectionMemoryManager());\n\n  \/\/ Build engine with JIT\n  llvm::EngineBuilder factory(std::move(Owner));\n  factory.setEngineKind(llvm::EngineKind::JIT);\n  factory.setTargetOptions(Opts);\n  factory.setMCJITMemoryManager(std::move(MemMgr));\n  llvm::ExecutionEngine *executionEngine = factory.create();\n\n  {\n    llvm::legacy::FunctionPassManager fpm(module);\n\n    \/\/ Set up the optimizer pipeline.\n    \/\/ Start with registering info about how the\n    \/\/ target lays out data structures.\n    module->setDataLayout(*executionEngine->getDataLayout());\n\n    \/\/ Optimizations turned on\n#ifdef ADD_OPT_PASSES\n\n    \/\/ Basic AliasAnslysis support for GVN.\n    fpm.add(llvm::createBasicAliasAnalysisPass());\n\n    \/\/ Promote allocas to registers.\n    fpm.add(llvm::createPromoteMemoryToRegisterPass());\n\n    \/\/ Do simple \"peephole\" optimizations and bit-twiddling optzns.\n    fpm.add(llvm::createInstructionCombiningPass());\n\n    \/\/ Reassociate expressions.\n    fpm.add(llvm::createReassociatePass());\n\n    \/\/ Eliminate Common SubExpressions.\n    fpm.add(llvm::createGVNPass());\n\n    \/\/ Simplify the control flow graph (deleting unreachable\n    \/\/ blocks, etc).\n    fpm.add(llvm::createCFGSimplificationPass());\n#endif  \/\/ ADD_OPT_PASSES\n\n    fpm.doInitialization();\n\n    \/\/ Generate test code using function throwCppException(...) as\n    \/\/ the function which throws foreign exceptions.\n    llvm::Function *toRun =\n    createUnwindExceptionTest(*module,\n                              theBuilder,\n                              fpm,\n                              \"throwCppException\");\n\n    executionEngine->finalizeObject();\n\n    fprintf(stderr, \"\\nBegin module dump:\\n\\n\");\n\n    module->dump();\n\n    fprintf(stderr, \"\\nEnd module dump:\\n\");\n\n    fprintf(stderr, \"\\n\\nBegin Test:\\n\");\n\n    for (int i = 1; i < argc; ++i) {\n      \/\/ Run test for each argument whose value is the exception\n      \/\/ type to throw.\n      runExceptionThrow(executionEngine,\n                        toRun,\n                        (unsigned) strtoul(argv[i], NULL, 10));\n    }\n\n    fprintf(stderr, \"\\nEnd Test:\\n\\n\");\n  }\n\n  delete executionEngine;\n\n  return 0;\n}\n","avg_line_length":35.3629666012,"max_line_length":86,"alphanum_fraction":0.6044945069,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8720,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["RSA-MD"],"max_stars_count":1.0,"content":"\/***********************************************************************\n!!!!!! DO NOT MODIFY !!!!!!\n\nSource: ..\/Resources\/Codegen\/BindComplex.txt\n\nThis file is generated by Workflow compiler\nhttps:\/\/github.com\/vczh-libraries\n***********************************************************************\/\n\n#include \"BindComplex.h\"\n\n#if defined( _MSC_VER)\n#pragma warning(push)\n#pragma warning(disable:4250)\n#elif defined(__GNUC__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wparentheses-equality\"\n#elif defined(__clang__)\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wparentheses-equality\"\n#endif\n\n#define GLOBAL_SYMBOL ::vl_workflow_global::BindComplex::\n#define GLOBAL_NAME ::vl_workflow_global::BindComplex::Instance().\n#define GLOBAL_OBJ &::vl_workflow_global::BindComplex::Instance()\n\n\/***********************************************************************\nGlobal Variables\n***********************************************************************\/\n\nBEGIN_GLOBAL_STORAGE_CLASS(vl_workflow_global_BindComplex)\n\tvl_workflow_global::BindComplex instance;\n\tINITIALIZE_GLOBAL_STORAGE_CLASS\n\n\t\tinstance.s = ::vl::WString(L\"\", false);\n\tFINALIZE_GLOBAL_STORAGE_CLASS\n\n\t\tinstance.s = ::vl::WString::Empty;\nEND_GLOBAL_STORAGE_CLASS(vl_workflow_global_BindComplex)\n\nnamespace vl_workflow_global\n{\n\/***********************************************************************\nGlobal Functions\n***********************************************************************\/\n\n\tvoid BindComplex::Callback(const ::vl::reflection::description::Value& value)\n\t{\n\t\t(GLOBAL_NAME s = ((((::vl::WString(L\"\", false) + GLOBAL_NAME s) + ::vl::WString(L\"[\", false)) + ::vl::__vwsn::ToString(::vl::__vwsn::Unbox<::vl::vint>(value))) + ::vl::WString(L\"]\", false)));\n\t}\n\n\t::vl::WString BindComplex::main()\n\t{\n\t\tauto x = ::vl::Ptr<::test::ObservableValue>(new ::test::ObservableValue());\n\t\tauto y = ::vl::Ptr<::test::ObservableValue>(new ::test::ObservableValue());\n\t\tauto z = ::vl::Ptr<::test::ObservableValue>(new ::test::ObservableValue());\n\t\tauto subscription = ::vl::Ptr<::vl::reflection::description::IValueSubscription>(new ::vl_workflow_global::__vwsnc1_BindComplex_main__vl_reflection_description_IValueSubscription(x, y, z));\n\t\t::vl::__vwsn::This(subscription.Obj())->Open();\n\t\t::vl::__vwsn::EventAttach(::vl::__vwsn::This(subscription.Obj())->ValueChanged, ::vl::Func<void(const ::vl::reflection::description::Value&)>(GLOBAL_OBJ, &GLOBAL_SYMBOL Callback));\n\t\t::vl::__vwsn::This(x.Obj())->SetValue(static_cast<::vl::vint>(10));\n\t\t::vl::__vwsn::This(y.Obj())->SetValue(static_cast<::vl::vint>(20));\n\t\t::vl::__vwsn::This(z.Obj())->SetValue(static_cast<::vl::vint>(30));\n\t\t::vl::__vwsn::This(subscription.Obj())->Close();\n\t\treturn GLOBAL_NAME s;\n\t}\n\n\tBindComplex& BindComplex::Instance()\n\t{\n\t\treturn Getvl_workflow_global_BindComplex().instance;\n\t}\n\n\/***********************************************************************\nClosures\n***********************************************************************\/\n\n\t\/\/-------------------------------------------------------------------\n\n\t__vwsnc1_BindComplex_main__vl_reflection_description_IValueSubscription::__vwsnc1_BindComplex_main__vl_reflection_description_IValueSubscription(::vl::Ptr<::test::ObservableValue> __vwsnctor_x, ::vl::Ptr<::test::ObservableValue> __vwsnctor_y, ::vl::Ptr<::test::ObservableValue> __vwsnctor_z)\n\t\t:x(__vwsnctor_x)\n\t\t, y(__vwsnctor_y)\n\t\t, z(__vwsnctor_z)\n\t{\n\t\tthis->__vwsn_bind_cache_0 = ::vl::Ptr<::test::ObservableValue>();\n\t\tthis->__vwsn_bind_cache_1 = ::vl::Ptr<::test::ObservableValue>();\n\t\tthis->__vwsn_bind_cache_2 = ::vl::Ptr<::test::ObservableValue>();\n\t\tthis->__vwsn_bind_handler_0_0 = ::vl::Ptr<::vl::reflection::description::IEventHandler>();\n\t\tthis->__vwsn_bind_handler_1_0 = ::vl::Ptr<::vl::reflection::description::IEventHandler>();\n\t\tthis->__vwsn_bind_handler_2_0 = ::vl::Ptr<::vl::reflection::description::IEventHandler>();\n\t\tthis->__vwsn_bind_opened_ = false;\n\t\tthis->__vwsn_bind_closed_ = false;\n\t}\n\n\tvoid __vwsnc1_BindComplex_main__vl_reflection_description_IValueSubscription::__vwsn_bind_activator_()\n\t{\n\t\tauto __vwsn_bind_activator_result_ = (::vl::__vwsn::This(__vwsn_bind_cache_0.Obj())->GetValue() + (::vl::__vwsn::This(__vwsn_bind_cache_1.Obj())->GetValue() + ::vl::__vwsn::This(__vwsn_bind_cache_2.Obj())->GetValue()));\n\t\t::vl::__vwsn::EventInvoke(this->ValueChanged)(::vl::__vwsn::Box(__vwsn_bind_activator_result_));\n\t}\n\n\tvoid __vwsnc1_BindComplex_main__vl_reflection_description_IValueSubscription::__vwsn_bind_callback_0_0(::vl::vint __vwsn_bind_callback_argument_0, ::vl::vint __vwsn_bind_callback_argument_1)\n\t{\n\t\tthis->__vwsn_bind_activator_();\n\t}\n\n\tvoid __vwsnc1_BindComplex_main__vl_reflection_description_IValueSubscription::__vwsn_bind_callback_1_0(::vl::vint __vwsn_bind_callback_argument_0, ::vl::vint __vwsn_bind_callback_argument_1)\n\t{\n\t\tthis->__vwsn_bind_activator_();\n\t}\n\n\tvoid __vwsnc1_BindComplex_main__vl_reflection_description_IValueSubscription::__vwsn_bind_callback_2_0(::vl::vint __vwsn_bind_callback_argument_0, ::vl::vint __vwsn_bind_callback_argument_1)\n\t{\n\t\tthis->__vwsn_bind_activator_();\n\t}\n\n\tbool __vwsnc1_BindComplex_main__vl_reflection_description_IValueSubscription::Open()\n\t{\n\t\tif ((! __vwsn_bind_opened_))\n\t\t{\n\t\t\t(__vwsn_bind_opened_ = true);\n\t\t\t(__vwsn_bind_cache_0 = [&](){ try{ return this->x; } catch(...){ return ::vl::Ptr<::test::ObservableValue>(); } }());\n\t\t\t(__vwsn_bind_cache_1 = [&](){ try{ return this->y; } catch(...){ return ::vl::Ptr<::test::ObservableValue>(); } }());\n\t\t\t(__vwsn_bind_cache_2 = [&](){ try{ return this->z; } catch(...){ return ::vl::Ptr<::test::ObservableValue>(); } }());\n\t\t\t(__vwsn_bind_handler_0_0 = [&](){ try{ return ::vl::__vwsn::EventAttach(::vl::__vwsn::This(__vwsn_bind_cache_0.Obj())->ValueChanged, ::vl::Func<void(::vl::vint, ::vl::vint)>(this, &__vwsnc1_BindComplex_main__vl_reflection_description_IValueSubscription::__vwsn_bind_callback_0_0)); } catch(...){ return ::vl::Ptr<::vl::reflection::description::IEventHandler>(); } }());\n\t\t\t(__vwsn_bind_handler_1_0 = [&](){ try{ return ::vl::__vwsn::EventAttach(::vl::__vwsn::This(__vwsn_bind_cache_1.Obj())->ValueChanged, ::vl::Func<void(::vl::vint, ::vl::vint)>(this, &__vwsnc1_BindComplex_main__vl_reflection_description_IValueSubscription::__vwsn_bind_callback_1_0)); } catch(...){ return ::vl::Ptr<::vl::reflection::description::IEventHandler>(); } }());\n\t\t\t(__vwsn_bind_handler_2_0 = [&](){ try{ return ::vl::__vwsn::EventAttach(::vl::__vwsn::This(__vwsn_bind_cache_2.Obj())->ValueChanged, ::vl::Func<void(::vl::vint, ::vl::vint)>(this, &__vwsnc1_BindComplex_main__vl_reflection_description_IValueSubscription::__vwsn_bind_callback_2_0)); } catch(...){ return ::vl::Ptr<::vl::reflection::description::IEventHandler>(); } }());\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool __vwsnc1_BindComplex_main__vl_reflection_description_IValueSubscription::Update()\n\t{\n\t\tif ((__vwsn_bind_opened_ && (! __vwsn_bind_closed_)))\n\t\t{\n\t\t\tthis->__vwsn_bind_activator_();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool __vwsnc1_BindComplex_main__vl_reflection_description_IValueSubscription::Close()\n\t{\n\t\tif ((! __vwsn_bind_closed_))\n\t\t{\n\t\t\t(__vwsn_bind_closed_ = true);\n\t\t\tif (static_cast<bool>(__vwsn_bind_handler_0_0))\n\t\t\t{\n\t\t\t\t::vl::__vwsn::EventDetach(::vl::__vwsn::This(__vwsn_bind_cache_0.Obj())->ValueChanged, __vwsn_bind_handler_0_0);\n\t\t\t\t(__vwsn_bind_handler_0_0 = ::vl::Ptr<::vl::reflection::description::IEventHandler>());\n\t\t\t}\n\t\t\tif (static_cast<bool>(__vwsn_bind_handler_1_0))\n\t\t\t{\n\t\t\t\t::vl::__vwsn::EventDetach(::vl::__vwsn::This(__vwsn_bind_cache_1.Obj())->ValueChanged, __vwsn_bind_handler_1_0);\n\t\t\t\t(__vwsn_bind_handler_1_0 = ::vl::Ptr<::vl::reflection::description::IEventHandler>());\n\t\t\t}\n\t\t\tif (static_cast<bool>(__vwsn_bind_handler_2_0))\n\t\t\t{\n\t\t\t\t::vl::__vwsn::EventDetach(::vl::__vwsn::This(__vwsn_bind_cache_2.Obj())->ValueChanged, __vwsn_bind_handler_2_0);\n\t\t\t\t(__vwsn_bind_handler_2_0 = ::vl::Ptr<::vl::reflection::description::IEventHandler>());\n\t\t\t}\n\t\t\t(__vwsn_bind_cache_0 = ::vl::Ptr<::test::ObservableValue>());\n\t\t\t(__vwsn_bind_cache_1 = ::vl::Ptr<::test::ObservableValue>());\n\t\t\t(__vwsn_bind_cache_2 = ::vl::Ptr<::test::ObservableValue>());\n\t\t\t(__vwsn_bind_handler_0_0 = ::vl::Ptr<::vl::reflection::description::IEventHandler>());\n\t\t\t(__vwsn_bind_handler_1_0 = ::vl::Ptr<::vl::reflection::description::IEventHandler>());\n\t\t\t(__vwsn_bind_handler_2_0 = ::vl::Ptr<::vl::reflection::description::IEventHandler>());\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n}\n\n#undef GLOBAL_SYMBOL\n#undef GLOBAL_NAME\n#undef GLOBAL_OBJ\n\n#if defined( _MSC_VER)\n#pragma warning(pop)\n#elif defined(__GNUC__)\n#pragma GCC diagnostic pop\n#elif defined(__clang__)\n#pragma clang diagnostic pop\n#endif\n","avg_line_length":47.3913043478,"max_line_length":372,"alphanum_fraction":0.6799311927,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3735,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n * Copyright 2016 - 2019  Angelo Matni, Simone Campanoni\n *\n * 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:\n\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\n * 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. \n * 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.\n *\/\n#include \"noelle\/core\/LoopsSummary.hpp\"\n\nusing namespace llvm;\nusing namespace llvm::noelle;\n      \nLoopsSummary::LoopsSummary (\n  Loop *loop\n  ) {\n  std::unordered_map<Loop *, LoopStructure *> loopToSummary;\n  loopToSummary[loop->getParentLoop()] = nullptr;\n\n  \/*\n   * NOTE(angelo): subloops only include 1-level deep loops\n   *  entirely contained within the top level loop\n   *\/\n  std::queue<Loop *> toSummarize;\n  toSummarize.push(loop);\n\n  while (!toSummarize.empty()) {\n\n    \/*\n     * Fetch the current loop.\n     *\/\n    auto l = toSummarize.front();\n    toSummarize.pop();\n\n    \/*\n     * Fetch the parent loop.\n     *\/\n    auto parent = l->getParentLoop();\n    assert(loopToSummary.find(parent) != loopToSummary.end());\n\n    \/*\n     * Create the summary of the current loop.\n     *\/\n    auto parentStructure = loopToSummary[parent];\n    auto childStructure = this->createSummary(l, parentStructure);\n    loopToSummary[l] = childStructure;\n\n    if (parentStructure) {\n      parentStructure->addChild(childStructure);\n    }\n\n    \/*\n     * Iterate over the subloops of the current loop.\n     *\/\n    for (auto subLoop : l->getSubLoops()) {\n      toSummarize.push(subLoop);\n    }\n  }\n\n  \/*\n   * Set the root of the tree\n   *\/\n  assert(loopToSummary.find(loop) != loopToSummary.end());\n  this->topLoop = loopToSummary[loop];\n\n  return ;\n}\n\nLoopStructure * LoopsSummary::getLoop (Instruction &instIncludedInLoop) const {\n  auto instBB = instIncludedInLoop.getParent();\n  auto l = this->getLoop(*instBB);\n  return l;\n}\n\nLoopStructure * LoopsSummary::getLoop (BasicBlock &bbIncludedInLoop) const {\n  auto lIter = this->bbToLoop.find(&bbIncludedInLoop);\n  if (lIter == this->bbToLoop.end()){\n    return nullptr;\n  }\n  auto l = this->bbToLoop.at(&bbIncludedInLoop);\n  return l;\n}\n\nLoopStructure * LoopsSummary::createSummary (\n  Loop *l, \n  LoopStructure *parentLoop\n  ) {\n\n  \/*\n   * Fetch the loop header.\n   *\/\n  auto header = l->getHeader();\n\n  \/*\n   * Allocate the LoopStructure\n   *\/\n  std::shared_ptr<LoopStructure> lSummary;\n  lSummary = std::make_shared<LoopStructure>(l, parentLoop);\n\n  \/*\n   * Create the map from basic blocks to loop.\n   *\/\n  auto lPtr = lSummary.get();\n  for (auto bb : l->blocks()) {\n    this->bbToLoop[bb] = lPtr;\n  }\n  auto ls = this->loops.insert(std::move(lSummary)).first->get();\n\n  return ls;\n}\n      \nvoid LoopsSummary::print (raw_ostream &stream) const {\n  stream << \"Loop summaries:\\n\";\n  for (auto &loop : loops) {\n    loop->print(stream);\n  }\n\n  return ;\n}\n      \nLoopStructure * LoopsSummary::getLoopNestingTreeRoot (void) const {\n  assert(this->topLoop != nullptr);\n\n  return this->topLoop;\n}\n","avg_line_length":29.1796875,"max_line_length":435,"alphanum_fraction":0.6921017403,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1453,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":6.0,"content":"\/\/==================================================================================================\n\/*!\n\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http:\/\/boost.org\/LICENSE_1_0.txt)\n*\/\n\/\/==================================================================================================\n#include <boost\/simd\/function\/scalar\/ror.hpp>\n#include <scalar_test.hpp>\n#include <boost\/simd\/detail\/dispatch\/meta\/as_integer.hpp>\n#include <boost\/simd\/function\/bitwise_cast.hpp>\n\nSTF_CASE_TPL (\" rorinteger\", STF_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::ror;\n  STF_EXPR_IS( ror(T(), T()), T);\n\n  T w = sizeof(T)*CHAR_BIT;\n\n  for(T i=0;i<w;++i)\n  {\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n    STF_EQUAL(ror(T(1),i), T(T(1)<<((w-i) & (w-1))));\n  }\n\n\/*\n  STF_ASSERT(ror(T(1),T(-1)));\n  STF_ASSERT(ror(T(1),T(w+1)));\n*\/\n}\n\nSTF_CASE_TPL (\" rorreal\", STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::ror;\n  using bs::bitwise_cast;\n  using iT = bd::as_integer_t<T> ;\n\n  STF_EXPR_IS( ror(T(), iT()), T);\n\n  iT w = sizeof(T)*CHAR_BIT;\n\n  for(iT i=0;i<w;++i)\n    STF_EQUAL( ror(bitwise_cast<T>(iT(1)),i)\n                  , bitwise_cast<T>(iT(1)<<((w-i) & (w-1)))\n                  );\n\/*\n  STF_ASSERT(ror(T(1),iT(-1)));\n  STF_ASSERT(ror(T(1),iT(w+1)));\n*\/\n}\n","avg_line_length":25.0517241379,"max_line_length":100,"alphanum_fraction":0.5333792154,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":9343,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":171.0,"content":"\/\/ RUN: %clang_cc1 -verify -fopenmp %s\n\n\/\/ RUN: %clang_cc1 -verify -fopenmp-simd %s\n\nvoid foo() {\n}\n\nbool foobool(int argc) {\n  return argc;\n}\n\nstruct S1; \/\/ expected-note 2 {{declared here}} expected-note 2 {{forward declaration of 'S1'}}\nextern S1 a;\nclass S2 {\n  mutable int a;\n\npublic:\n  S2() : a(0) {}\n  S2(S2 &s2) : a(s2.a) {}\n  const S2 &operator =(const S2&) const;\n  S2 &operator =(const S2&);\n  static float S2s; \/\/ expected-note {{static data member is predetermined as shared}}\n  static const float S2sc; \/\/ expected-note {{static data member is predetermined as shared}}\n};\nconst float S2::S2sc = 0;\nconst S2 b;\nconst S2 ba[5];\nclass S3 {\n  int a;\n  S3 &operator=(const S3 &s3); \/\/ expected-note {{implicitly declared private here}}\n\npublic:\n  S3() : a(0) {}\n  S3(S3 &s3) : a(s3.a) {}\n};\nconst S3 c;         \/\/ expected-note {{global variable is predetermined as shared}}\nconst S3 ca[5];     \/\/ expected-note {{global variable is predetermined as shared}}\nextern const int f; \/\/ expected-note {{global variable is predetermined as shared}}\nclass S4 {\n  int a;\n  S4();             \/\/ expected-note 3 {{implicitly declared private here}}\n  S4(const S4 &s4);\n\npublic:\n  S4(int v) : a(v) {}\n};\nclass S5 {\n  int a;\n  S5() : a(0) {} \/\/ expected-note {{implicitly declared private here}}\n\npublic:\n  S5(const S5 &s5) : a(s5.a) {}\n  S5(int v) : a(v) {}\n};\nclass S6 {\n  int a;\n  S6() : a(0) {} \/\/ expected-note {{implicitly declared private here}}\n\npublic:\n  S6(const S6 &s6) : a(s6.a) {}\n  S6(int v) : a(v) {}\n};\n\nS3 h;\n#pragma omp threadprivate(h) \/\/ expected-note 2 {{defined as threadprivate or thread local}}\n\ntemplate <class I, class C>\nint foomain(int argc, char **argv) {\n  I e(4);\n  I g(5);\n  int i;\n  int &j = i;\n#pragma omp target teams distribute simd lastprivate \/\/ expected-error {{expected '(' after 'lastprivate'}}\n  for (int k = 0; k < argc; ++k) ++k;\n\n#pragma omp target teams distribute simd lastprivate( \/\/ expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}\n  for (int k = 0; k < argc; ++k) ++k;\n\n#pragma omp target teams distribute simd lastprivate() \/\/ expected-error {{expected expression}}\n  for (int k = 0; k < argc; ++k) ++k;\n\n#pragma omp target teams distribute simd lastprivate(argc \/\/ expected-error {{expected ')'}} expected-note {{to match this '('}}\n  for (int k = 0; k < argc; ++k) ++k;\n\n#pragma omp target teams distribute simd lastprivate(argc, \/\/ expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}\n  for (int k = 0; k < argc; ++k) ++k;\n\n#pragma omp target teams distribute simd lastprivate(argc > 0 ? argv[1] : argv[2]) \/\/ expected-error {{expected variable name}}\n  for (int k = 0; k < argc; ++k) ++k;\n\n#pragma omp target teams distribute simd lastprivate(argc)\n  for (int k = 0; k < argc; ++k) ++k;\n\n#pragma omp target teams distribute simd lastprivate(S1) \/\/ expected-error {{'S1' does not refer to a value}}\n  for (int k = 0; k < argc; ++k) ++k;\n\n#pragma omp target teams distribute simd lastprivate(a, b) \/\/ expected-error {{lastprivate variable with incomplete type 'S1'}}\n  for (int k = 0; k < argc; ++k) ++k;\n\n#pragma omp target teams distribute simd lastprivate(argv[1]) \/\/ expected-error {{expected variable name}}\n  for (int k = 0; k < argc; ++k) ++k;\n\n#pragma omp target teams distribute simd lastprivate(e, g) \/\/ expected-error 2 {{calling a private constructor of class 'S4'}}\n  for (int k = 0; k < argc; ++k) ++k;\n\n#pragma omp target teams distribute simd lastprivate(h) \/\/ expected-error {{threadprivate or thread local variable cannot be lastprivate}}\n  for (int k = 0; k < argc; ++k) ++k;\n\n  int v = 0;\n#pragma omp target teams distribute simd lastprivate(i)\n  for (int k = 0; k < argc; ++k) {\n    i = k;\n    v += i;\n  }\n\n#pragma omp target teams distribute simd lastprivate(j) private(i)\n  for (int k = 0; k < argc; ++k) ++k;\n\n#pragma omp target teams distribute simd lastprivate(i)\n  for (int k = 0; k < argc; ++k) ++k;\n\n  return 0;\n}\n\nvoid bar(S4 a[2]) {\n#pragma omp target teams distribute simd lastprivate(a)\n  for (int i = 0; i < 2; ++i) foo();\n}\n\nnamespace A {\ndouble x;\n#pragma omp threadprivate(x) \/\/ expected-note {{defined as threadprivate or thread local}}\n}\nnamespace B {\nusing A::x;\n}\n\nint main(int argc, char **argv) {\n  const int d = 5;       \/\/ expected-note {{constant variable is predetermined as shared}}\n  const int da[5] = {0}; \/\/ expected-note {{constant variable is predetermined as shared}}\n  S4 e(4);\n  S5 g(5);\n  S3 m;\n  S6 n(2);\n  int i;\n  int &j = i;\n  float k;\n#pragma omp target teams distribute simd lastprivate \/\/ expected-error {{expected '(' after 'lastprivate'}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate( \/\/ expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate() \/\/ expected-error {{expected expression}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(argc \/\/ expected-error {{expected ')'}} expected-note {{to match this '('}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(argc, \/\/ expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(argc > 0 ? argv[1] : argv[2]) \/\/ expected-error {{expected variable name}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(argc)\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(S1) \/\/ expected-error {{'S1' does not refer to a value}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(a, b, c, d, f) \/\/ expected-error {{lastprivate variable with incomplete type 'S1'}} expected-error 3 {{shared variable cannot be lastprivate}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(argv[1]) \/\/ expected-error {{expected variable name}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(2 * 2) \/\/ expected-error {{expected variable name}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(ba)\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(ca) \/\/ expected-error {{shared variable cannot be lastprivate}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(da) \/\/ expected-error {{shared variable cannot be lastprivate}}\n  for (i = 0; i < argc; ++i) foo();\n\n  int xa;\n#pragma omp target teams distribute simd lastprivate(xa) \/\/ OK\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(S2::S2s) \/\/ expected-error {{shared variable cannot be lastprivate}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(S2::S2sc) \/\/ expected-error {{shared variable cannot be lastprivate}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(e, g) \/\/ expected-error {{calling a private constructor of class 'S4'}} expected-error {{calling a private constructor of class 'S5'}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(m) \/\/ expected-error {{'operator=' is a private member of 'S3'}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(h) \/\/ expected-error {{threadprivate or thread local variable cannot be lastprivate}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(B::x) \/\/ expected-error {{threadprivate or thread local variable cannot be lastprivate}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd private(xa), lastprivate(xa) \/\/ expected-error {{private variable cannot be lastprivate}} expected-note {{defined as private}}\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(xa)\n  for (i = 0; i < argc; ++i) foo();\n\n#pragma omp target teams distribute simd lastprivate(j)\n  for (i = 0; i < argc; ++i) foo();\n\n\/\/ expected-error@+1 {{firstprivate variable cannot be lastprivate}} expected-note@+1 {{defined as firstprivate}}\n#pragma omp target teams distribute simd firstprivate(m) lastprivate(m)\n  for (i = 0; i < argc; ++i) foo();\n\n\/\/ expected-error@+1 {{lastprivate variable cannot be firstprivate}} expected-note@+1 {{defined as lastprivate}}\n#pragma omp target teams distribute simd lastprivate(n) firstprivate(n) \/\/ expected-error {{calling a private constructor of class 'S6'}}\n  for (i = 0; i < argc; ++i) foo();\n\n  static int si;\n#pragma omp target teams distribute simd lastprivate(si) \/\/ OK\n  for (i = 0; i < argc; ++i) si = i + 1;\n\n#pragma omp target teams distribute simd lastprivate(k) map(k) \/\/ expected-error {{lastprivate variable cannot be in a map clause in '#pragma omp target teams distribute simd' directive}} expected-note {{defined as lastprivate}}\n  for (i = 0; i < argc; ++i) foo();\n\n  return foomain<S4, S5>(argc, argv); \/\/ expected-note {{in instantiation of function template specialization 'foomain<S4, S5>' requested here}}\n}\n","avg_line_length":39.256302521,"max_line_length":228,"alphanum_fraction":0.6626351279,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":20600,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ \r\n\/\/ Notice Regarding Standards.  AMD does not provide a license or sublicense to\r\n\/\/ any Intellectual Property Rights relating to any standards, including but not\r\n\/\/ limited to any audio and\/or video codec technologies such as MPEG-2, MPEG-4;\r\n\/\/ AVC\/H.264; HEVC\/H.265; AAC decode\/FFMPEG; AAC encode\/FFMPEG; VC-1; and MP3\r\n\/\/ (collectively, the \"Media Technologies\"). For clarity, you will pay any\r\n\/\/ royalties due for such third party technologies, which may include the Media\r\n\/\/ Technologies that are owed as a result of AMD providing the Software to you.\r\n\/\/ \r\n\/\/ MIT license \r\n\/\/ \r\n\/\/ Copyright (c) 2018 Advanced Micro Devices, Inc. All rights reserved.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include <climits>\r\n#include \"PropertyStorageExImpl.h\"\r\n#include \"PropertyStorageImpl.h\"\r\n#include \"TraceAdapter.h\"\r\n\r\n#pragma warning(disable: 4996)\r\n\r\nusing namespace amf;\r\n\r\n#define AMF_FACILITY L\"AMFPropertyStorageExImpl\"\r\n#ifdef __clang__\r\n    #pragma clang diagnostic push\r\n    #pragma clang diagnostic ignored \"-Wexit-time-destructors\"\r\n    #pragma clang diagnostic ignored \"-Wglobal-constructors\"\r\n#endif\r\n\r\namf::AMFCriticalSection amf::ms_csAMFPropertyStorageExImplMaps;\r\n#ifdef __clang__\r\n    #pragma clang diagnostic pop\r\n#endif\r\n\r\n\/\/-------------------------------------------------------------------------------------------------\r\nAMF_RESULT amf::CastVariantToAMFProperty(amf::AMFVariantStruct* pDest, const amf::AMFVariantStruct* pSrc, amf::AMF_VARIANT_TYPE eType,\r\n        amf::AMF_PROPERTY_CONTENT_TYPE \/*contentType*\/,\r\n        const amf::AMFEnumDescriptionEntry* pEnumDescription)\r\n{\r\n    AMF_RETURN_IF_INVALID_POINTER(pDest);\r\n\r\n    AMF_RESULT err = AMF_OK;\r\n    switch (eType)\r\n    {\r\n    case AMF_VARIANT_INTERFACE:\r\n        if (pSrc->type == eType)\r\n        {\r\n            err = AMFVariantCopy(pDest, pSrc);\r\n        }\r\n        else\r\n        {\r\n            pDest->type = AMF_VARIANT_INTERFACE;\r\n            pDest->pInterface = nullptr;\r\n        }\r\n        break;\r\n\r\n    case AMF_VARIANT_INT64:\r\n    {\r\n        if(pEnumDescription)\r\n        {\r\n            const AMFEnumDescriptionEntry* pEnumDescriptionCache = pEnumDescription;\r\n            err = AMFVariantChangeType(pDest, pSrc, AMF_VARIANT_INT64);\r\n            bool found = false;\r\n            if(err == AMF_OK)\r\n            {\r\n                \/\/mean numeric came. validating\r\n                while(pEnumDescriptionCache->name)\r\n                {\r\n                    if(pEnumDescriptionCache->value == AMFVariantGetInt64(pDest))\r\n                    {\r\n                        AMFVariantAssignInt64(pDest, pEnumDescriptionCache->value);\r\n                        found = true;\r\n                        break;\r\n                    }\r\n                    pEnumDescriptionCache++;\r\n                }\r\n                err = found ? AMF_OK : AMF_INVALID_ARG;\r\n            }\r\n            if(!found)\r\n            {\r\n                pEnumDescriptionCache = pEnumDescription;\r\n                err = AMFVariantChangeType(pDest, pSrc, AMF_VARIANT_WSTRING);\r\n                if(err == AMF_OK)\r\n                {\r\n                    \/\/string came. validating and assigning numeric\r\n                    found = false;\r\n                    while(pEnumDescriptionCache->name)\r\n                    {\r\n                        if(amf_wstring(pEnumDescriptionCache->name) == AMFVariantGetWString(pDest))\r\n                        {\r\n                            AMFVariantAssignInt64(pDest, pEnumDescriptionCache->value);\r\n                            found = true;\r\n                            break;\r\n                        }\r\n                        pEnumDescriptionCache++;\r\n                    }\r\n                    err = found ? AMF_OK : AMF_INVALID_ARG;\r\n                }\r\n            }\r\n        }\r\n        else\r\n        {\r\n            err = AMFVariantChangeType(pDest, pSrc, AMF_VARIANT_INT64);\r\n        }\r\n    }\r\n    break;\r\n\r\n    default:\r\n        err = AMFVariantChangeType(pDest, pSrc, eType);\r\n    break;\r\n    }\r\n    return err;\r\n}\r\n\/\/-------------------------------------------------------------------------------------------------\r\nAMFPropertyInfoImpl::AMFPropertyInfoImpl(const wchar_t* name, const wchar_t* desc, AMF_VARIANT_TYPE type, AMF_PROPERTY_CONTENT_TYPE contentType,\r\n        AMFVariantStruct defaultValue, AMFVariantStruct minValue, AMFVariantStruct maxValue, bool allowChangeInRuntime,\r\n        const AMFEnumDescriptionEntry* pEnumDescription) : m_name(), m_desc()\r\n{\r\n    AMF_PROPERTY_ACCESS_TYPE accessTypeTmp = allowChangeInRuntime ? AMF_PROPERTY_ACCESS_FULL : AMF_PROPERTY_ACCESS_READ_WRITE;\r\n    Init(name, desc, type, contentType, defaultValue, minValue, maxValue, accessTypeTmp, pEnumDescription);\r\n}\r\n\/\/-------------------------------------------------------------------------------------------------\r\nAMFPropertyInfoImpl::AMFPropertyInfoImpl(const wchar_t* name, const wchar_t* desc, AMF_VARIANT_TYPE type, AMF_PROPERTY_CONTENT_TYPE contentType,\r\n        AMFVariantStruct defaultValue, AMFVariantStruct minValue, AMFVariantStruct maxValue, AMF_PROPERTY_ACCESS_TYPE accessType,\r\n        const AMFEnumDescriptionEntry* pEnumDescription) : m_name(), m_desc()\r\n{\r\n    Init(name, desc, type, contentType, defaultValue, minValue, maxValue, accessType, pEnumDescription);\r\n}\r\n\/\/-------------------------------------------------------------------------------------------------\r\nAMFPropertyInfoImpl::AMFPropertyInfoImpl() : m_name(), m_desc()\r\n{\r\n    AMFVariantInit(&this->defaultValue);\r\n    AMFVariantInit(&this->minValue);\r\n    AMFVariantInit(&this->maxValue);\r\n\r\n    name = L\"\";\r\n    desc = L\"\";\r\n    type = AMF_VARIANT_EMPTY;\r\n    contentType = AMF_PROPERTY_CONTENT_TYPE(-1);\r\n    accessType = AMF_PROPERTY_ACCESS_FULL;\r\n}\r\n\/\/-------------------------------------------------------------------------------------------------\r\nvoid AMFPropertyInfoImpl::Init(const wchar_t* name_, const wchar_t* desc_, AMF_VARIANT_TYPE type_, AMF_PROPERTY_CONTENT_TYPE contentType_,\r\n        AMFVariantStruct defaultValue_, AMFVariantStruct minValue_, AMFVariantStruct maxValue_, AMF_PROPERTY_ACCESS_TYPE accessType_,\r\n        const AMFEnumDescriptionEntry* pEnumDescription_)\r\n{\r\n    m_name = name_;\r\n    name = m_name.c_str();\r\n\r\n    m_desc = desc_;\r\n    desc = m_desc.c_str();\r\n\r\n    type = type_;\r\n    contentType = contentType_;\r\n    accessType = accessType_;\r\n    AMFVariantInit(&defaultValue);\r\n    AMFVariantInit(&minValue);\r\n    AMFVariantInit(&maxValue);\r\n    pEnumDescription = pEnumDescription_;\r\n\r\n    switch(type)\r\n    {\r\n    case AMF_VARIANT_BOOL:\r\n    {\r\n        if(CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignBool(&defaultValue, false);\r\n        }\r\n    }\r\n    break;\r\n    case AMF_VARIANT_RECT:\r\n    {\r\n        if(CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignRect(&defaultValue, AMFConstructRect(0, 0, 0, 0));\r\n        }\r\n    }\r\n    break;\r\n    case AMF_VARIANT_SIZE:\r\n    {\r\n        if(CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignSize(&defaultValue, AMFConstructSize(0, 0));\r\n        }\r\n        if (CastVariantToAMFProperty(&minValue, &minValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignSize(&minValue, AMFConstructSize(INT_MIN, INT_MIN));\r\n        }\r\n        if (CastVariantToAMFProperty(&maxValue, &maxValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignSize(&maxValue, AMFConstructSize(INT_MAX, INT_MAX));\r\n        }\r\n    }\r\n    break;\r\n    case AMF_VARIANT_POINT:\r\n    {\r\n        if(CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignPoint(&defaultValue, AMFConstructPoint(0, 0));\r\n        }\r\n        if (CastVariantToAMFProperty(&minValue, &minValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignPoint(&minValue, AMFConstructPoint(INT_MIN, INT_MIN));\r\n        }\r\n        if (CastVariantToAMFProperty(&maxValue, &maxValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignPoint(&maxValue, AMFConstructPoint(INT_MAX, INT_MAX));\r\n        }\r\n    }\r\n    break;\r\n    case AMF_VARIANT_RATE:\r\n    {\r\n        if(CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignRate(&defaultValue, AMFConstructRate(0, 0));\r\n        }\r\n        if (CastVariantToAMFProperty(&this->minValue, &minValue, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignRate(&this->minValue, AMFConstructRate(0, 1));\r\n        }\r\n        if (CastVariantToAMFProperty(&this->maxValue, &maxValue, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignRate(&this->maxValue, AMFConstructRate(INT_MAX, INT_MAX));\r\n        }\r\n    }\r\n    break;\r\n    case AMF_VARIANT_RATIO:\r\n    {\r\n        if(CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignRatio(&defaultValue, AMFConstructRatio(0, 0));\r\n        }\r\n    }\r\n    break;\r\n    case AMF_VARIANT_COLOR:\r\n    {\r\n        if(CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignColor(&defaultValue, AMFConstructColor(0, 0, 0, 255));\r\n        }\r\n    }\r\n    break;\r\n\r\n    case AMF_VARIANT_INT64:\r\n    {\r\n        if(pEnumDescription)\r\n        {\r\n            if(CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n            {\r\n                AMFVariantAssignInt64(&defaultValue, pEnumDescription->value);\r\n            }\r\n        }\r\n        else \/\/AMF_PROPERTY_CONTENT_DEFAULT\r\n        {\r\n            if(CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n            {\r\n                AMFVariantAssignInt64(&defaultValue, 0);\r\n            }\r\n            if(CastVariantToAMFProperty(&minValue, &minValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n            {\r\n                AMFVariantAssignInt64(&minValue, INT_MIN);\r\n            }\r\n            if(CastVariantToAMFProperty(&maxValue, &maxValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n            {\r\n                AMFVariantAssignInt64(&maxValue, INT_MAX);\r\n            }\r\n        }\r\n    }\r\n    break;\r\n\r\n    case AMF_VARIANT_DOUBLE:\r\n    {\r\n        if(CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignDouble(&defaultValue, 0);\r\n        }\r\n        if(CastVariantToAMFProperty(&minValue, &minValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignDouble(&minValue, DBL_MIN);\r\n        }\r\n        if(CastVariantToAMFProperty(&maxValue, &maxValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignDouble(&maxValue, DBL_MAX);\r\n        }\r\n    }\r\n    break;\r\n\r\n    case AMF_VARIANT_STRING:\r\n    {\r\n        if(CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignString(&maxValue, \"\");\r\n        }\r\n    }\r\n    break;\r\n\r\n    case AMF_VARIANT_WSTRING:\r\n    {\r\n        if(CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignWString(&maxValue, L\"\");\r\n        }\r\n    }\r\n    break;\r\n\r\n    case AMF_VARIANT_INTERFACE:\r\n        if(CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignWString(&maxValue, L\"\");\r\n        }\r\n        break;\r\n    case AMF_VARIANT_FLOAT:\r\n    {\r\n        if (CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloat(&defaultValue, 0);\r\n        }\r\n        if (CastVariantToAMFProperty(&minValue, &minValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloat(&minValue, FLT_MIN);\r\n        }\r\n        if (CastVariantToAMFProperty(&maxValue, &maxValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloat(&maxValue, FLT_MAX);\r\n        }\r\n    }\r\n    break;\r\n    case AMF_VARIANT_FLOAT_SIZE:\r\n    {\r\n        if (CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloatSize(&defaultValue, AMFConstructFloatSize(0, 0));\r\n        }\r\n        if (CastVariantToAMFProperty(&minValue, &minValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloatSize(&minValue, AMFConstructFloatSize(FLT_MIN, FLT_MIN));\r\n        }\r\n        if (CastVariantToAMFProperty(&maxValue, &maxValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloatSize(&maxValue, AMFConstructFloatSize(FLT_MAX, FLT_MAX));\r\n        }\r\n    }\r\n    break;\r\n    case AMF_VARIANT_FLOAT_POINT2D:\r\n    {\r\n        if (CastVariantToAMFProperty(&defaultValue, &defaultValue, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloatPoint2D(&defaultValue, AMFConstructFloatPoint2D(0, 0));\r\n        }\r\n        if (CastVariantToAMFProperty(&minValue, &minValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloatPoint2D(&minValue, AMFConstructFloatPoint2D(FLT_MIN, FLT_MIN));\r\n        }\r\n        if (CastVariantToAMFProperty(&maxValue, &maxValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloatPoint2D(&maxValue, AMFConstructFloatPoint2D(FLT_MAX, FLT_MAX));\r\n        }\r\n    }\r\n    break;\r\n    case AMF_VARIANT_FLOAT_POINT3D:\r\n    {\r\n        if (CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloatPoint3D(&defaultValue, AMFConstructFloatPoint3D(0, 0, 0));\r\n        }\r\n        if (CastVariantToAMFProperty(&minValue, &minValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloatPoint3D(&minValue, AMFConstructFloatPoint3D(FLT_MIN, FLT_MIN, FLT_MIN));\r\n        }\r\n        if (CastVariantToAMFProperty(&maxValue, &maxValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloatPoint3D(&maxValue, AMFConstructFloatPoint3D(FLT_MAX, FLT_MAX, FLT_MAX));\r\n        }\r\n    }\r\n    break;\r\n    case AMF_VARIANT_FLOAT_VECTOR4D:\r\n    {\r\n        if (CastVariantToAMFProperty(&defaultValue, &defaultValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloatVector4D(&defaultValue, AMFConstructFloatVector4D(0, 0, 0, 0));\r\n        }\r\n        if (CastVariantToAMFProperty(&minValue, &minValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloatVector4D(&minValue, AMFConstructFloatVector4D(FLT_MIN, FLT_MIN, FLT_MIN, FLT_MIN));\r\n        }\r\n        if (CastVariantToAMFProperty(&maxValue, &maxValue_, type, contentType, pEnumDescription) != AMF_OK)\r\n        {\r\n            AMFVariantAssignFloatVector4D(&maxValue, AMFConstructFloatVector4D(FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX));\r\n        }\r\n    }\r\n    break;\r\n    default:\r\n        break;\r\n    }\r\n\r\n    value = defaultValue;\r\n}\r\n\r\nAMFPropertyInfoImpl::AMFPropertyInfoImpl(const AMFPropertyInfoImpl& propertyInfo) : AMFPropertyInfo(), m_name(), m_desc()\r\n{\r\n    Init(propertyInfo.name, propertyInfo.desc, propertyInfo.type, propertyInfo.contentType, propertyInfo.defaultValue, propertyInfo.minValue, propertyInfo.maxValue, propertyInfo.accessType, propertyInfo.pEnumDescription);\r\n}\r\n\/\/-------------------------------------------------------------------------------------------------\r\nAMFPropertyInfoImpl& AMFPropertyInfoImpl::operator=(const AMFPropertyInfoImpl& propertyInfo)\r\n{\r\n    \/\/ store name and desc inside instance in m_sName and m_sDesc recpectively;\r\n    \/\/ m_pName and m_pDesc are pointed to our local copies\r\n    this->m_name = propertyInfo.name;\r\n    this->m_desc = propertyInfo.desc;\r\n    this->name = m_name.c_str();\r\n    this->desc = m_desc.c_str();\r\n\r\n    this->type = propertyInfo.type;\r\n    this->contentType = propertyInfo.contentType;\r\n    this->accessType = propertyInfo.accessType;\r\n    AMFVariantCopy(&this->defaultValue, &propertyInfo.defaultValue);\r\n    AMFVariantCopy(&this->minValue, &propertyInfo.minValue);\r\n    AMFVariantCopy(&this->maxValue, &propertyInfo.maxValue);\r\n    this->pEnumDescription = propertyInfo.pEnumDescription;\r\n\r\n    this->value = propertyInfo.value;\r\n    this->userModified = propertyInfo.userModified;\r\n\r\n    return *this;\r\n}\r\n\/\/-------------------------------------------------------------------------------------------------\r\nAMFPropertyInfoImpl::~AMFPropertyInfoImpl()\r\n{\r\n    AMFVariantClear(&this->defaultValue);\r\n    AMFVariantClear(&this->minValue);\r\n    AMFVariantClear(&this->maxValue);\r\n}\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------------------\r\n","avg_line_length":43.5517970402,"max_line_length":222,"alphanum_fraction":0.555,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":47163,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":8.0,"content":"#include \"Server.h\"\n\n#include <memory>\n#include <sys\/resource.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <errno.h>\n#include <pwd.h>\n#include <unistd.h>\n#include <Poco\/Version.h>\n#include <Poco\/DirectoryIterator.h>\n#include <Poco\/Net\/HTTPServer.h>\n#include <Poco\/Net\/NetException.h>\n#include <Poco\/Util\/HelpFormatter.h>\n#include <ext\/scope_guard.h>\n#include <common\/logger_useful.h>\n#include <common\/phdr_cache.h>\n#include <common\/ErrorHandlers.h>\n#include <common\/getMemoryAmount.h>\n#include <common\/errnoToString.h>\n#include <common\/coverage.h>\n#include <Common\/ClickHouseRevision.h>\n#include <Common\/DNSResolver.h>\n#include <Common\/CurrentMetrics.h>\n#include <Common\/Macros.h>\n#include <Common\/StringUtils\/StringUtils.h>\n#include <Common\/ZooKeeper\/ZooKeeper.h>\n#include <Common\/ZooKeeper\/ZooKeeperNodeCache.h>\n#include <common\/getFQDNOrHostName.h>\n#include <Common\/getMultipleKeysFromConfig.h>\n#include <Common\/getNumberOfPhysicalCPUCores.h>\n#include <Common\/getExecutablePath.h>\n#include <Common\/ThreadProfileEvents.h>\n#include <Common\/ThreadStatus.h>\n#include <IO\/HTTPCommon.h>\n#include <IO\/UseSSL.h>\n#include <Interpreters\/AsynchronousMetrics.h>\n#include <Interpreters\/DDLWorker.h>\n#include <Interpreters\/ExternalDictionariesLoader.h>\n#include <Interpreters\/ExternalModelsLoader.h>\n#include <Interpreters\/ProcessList.h>\n#include <Interpreters\/loadMetadata.h>\n#include <Interpreters\/DatabaseCatalog.h>\n#include <Interpreters\/DNSCacheUpdater.h>\n#include <Interpreters\/SystemLog.cpp>\n#include <Interpreters\/ExternalLoaderXMLConfigRepository.h>\n#include <Access\/AccessControlManager.h>\n#include <Storages\/StorageReplicatedMergeTree.h>\n#include <Storages\/System\/attachSystemTables.h>\n#include <AggregateFunctions\/registerAggregateFunctions.h>\n#include <Functions\/registerFunctions.h>\n#include <TableFunctions\/registerTableFunctions.h>\n#include <Storages\/registerStorages.h>\n#include <Dictionaries\/registerDictionaries.h>\n#include <Disks\/registerDisks.h>\n#include <Common\/Config\/ConfigReloader.h>\n#include <Server\/HTTPHandlerFactory.h>\n#include \"MetricsTransmitter.h\"\n#include <Common\/StatusFile.h>\n#include <Server\/TCPHandlerFactory.h>\n#include <Common\/SensitiveDataMasker.h>\n#include <Common\/ThreadFuzzer.h>\n#include <Server\/MySQLHandlerFactory.h>\n#include <Server\/PostgreSQLHandlerFactory.h>\n\n\n#if !defined(ARCADIA_BUILD)\n#   include \"config_core.h\"\n#   include \"Common\/config_version.h\"\n#   if USE_OPENCL\n#       include \"Common\/BitonicSort.h\" \/\/ Y_IGNORE\n#   endif\n#endif\n\n#if defined(OS_LINUX)\n#    include <sys\/mman.h>\n#    include <Common\/hasLinuxCapability.h>\n#endif\n\n#if USE_SSL\n#    include <Poco\/Net\/Context.h>\n#    include <Poco\/Net\/SecureServerSocket.h>\n#endif\n\nnamespace CurrentMetrics\n{\n    extern const Metric Revision;\n    extern const Metric VersionInteger;\n    extern const Metric MemoryTracking;\n}\n\nnamespace\n{\n\nvoid setupTmpPath(Poco::Logger * log, const std::string & path)\n{\n    LOG_DEBUG(log, \"Setting up {} to store temporary data in it\", path);\n\n    Poco::File(path).createDirectories();\n\n    \/\/\/ Clearing old temporary files.\n    Poco::DirectoryIterator dir_end;\n    for (Poco::DirectoryIterator it(path); it != dir_end; ++it)\n    {\n        if (it->isFile() && startsWith(it.name(), \"tmp\"))\n        {\n            LOG_DEBUG(log, \"Removing old temporary file {}\", it->path());\n            it->remove();\n        }\n        else\n            LOG_DEBUG(log, \"Skipped file in temporary path {}\", it->path());\n    }\n}\n\n}\n\nnamespace DB\n{\n\nnamespace ErrorCodes\n{\n    extern const int NO_ELEMENTS_IN_CONFIG;\n    extern const int SUPPORT_IS_DISABLED;\n    extern const int ARGUMENT_OUT_OF_BOUND;\n    extern const int EXCESSIVE_ELEMENT_IN_CONFIG;\n    extern const int INVALID_CONFIG_PARAMETER;\n    extern const int SYSTEM_ERROR;\n    extern const int FAILED_TO_GETPWUID;\n    extern const int MISMATCHING_USERS_FOR_PROCESS_AND_DATA;\n    extern const int NETWORK_ERROR;\n}\n\n\nstatic std::string getCanonicalPath(std::string && path)\n{\n    Poco::trimInPlace(path);\n    if (path.empty())\n        throw Exception(\"path configuration parameter is empty\", ErrorCodes::INVALID_CONFIG_PARAMETER);\n    if (path.back() != '\/')\n        path += '\/';\n    return std::move(path);\n}\n\nstatic std::string getUserName(uid_t user_id)\n{\n    \/\/\/ Try to convert user id into user name.\n    auto buffer_size = sysconf(_SC_GETPW_R_SIZE_MAX);\n    if (buffer_size <= 0)\n        buffer_size = 1024;\n    std::string buffer;\n    buffer.reserve(buffer_size);\n\n    struct passwd passwd_entry;\n    struct passwd * result = nullptr;\n    const auto error = getpwuid_r(user_id, &passwd_entry, buffer.data(), buffer_size, &result);\n\n    if (error)\n        throwFromErrno(\"Failed to find user name for \" + toString(user_id), ErrorCodes::FAILED_TO_GETPWUID, error);\n    else if (result)\n        return result->pw_name;\n    return toString(user_id);\n}\n\nvoid Server::uninitialize()\n{\n    logger().information(\"shutting down\");\n    BaseDaemon::uninitialize();\n}\n\nint Server::run()\n{\n    if (config().hasOption(\"help\"))\n    {\n        Poco::Util::HelpFormatter help_formatter(Server::options());\n        std::stringstream header;\n        header << commandName() << \" [OPTION] [-- [ARG]...]\\n\";\n        header << \"positional arguments can be used to rewrite config.xml properties, for example, --http_port=8010\";\n        help_formatter.setHeader(header.str());\n        help_formatter.format(std::cout);\n        return 0;\n    }\n    if (config().hasOption(\"version\"))\n    {\n        std::cout << DBMS_NAME << \" server version \" << VERSION_STRING << VERSION_OFFICIAL << \".\" << std::endl;\n        return 0;\n    }\n    return Application::run(); \/\/ NOLINT\n}\n\nvoid Server::initialize(Poco::Util::Application & self)\n{\n    BaseDaemon::initialize(self);\n    logger().information(\"starting up\");\n}\n\nstd::string Server::getDefaultCorePath() const\n{\n    return getCanonicalPath(config().getString(\"path\", DBMS_DEFAULT_PATH)) + \"cores\";\n}\n\nvoid Server::defineOptions(Poco::Util::OptionSet & options)\n{\n    options.addOption(\n        Poco::Util::Option(\"help\", \"h\", \"show help and exit\")\n            .required(false)\n            .repeatable(false)\n            .binding(\"help\"));\n    options.addOption(\n        Poco::Util::Option(\"version\", \"V\", \"show version and exit\")\n            .required(false)\n            .repeatable(false)\n            .binding(\"version\"));\n    BaseDaemon::defineOptions(options);\n}\n\n\nvoid checkForUsersNotInMainConfig(\n    const Poco::Util::AbstractConfiguration & config,\n    const std::string & config_path,\n    const std::string & users_config_path,\n    Poco::Logger * log)\n{\n    if (config.getBool(\"skip_check_for_incorrect_settings\", false))\n        return;\n\n    if (config.has(\"users\") || config.has(\"profiles\") || config.has(\"quotas\"))\n    {\n        \/\/\/ We cannot throw exception here, because we have support for obsolete 'conf.d' directory\n        \/\/\/ (that does not correspond to config.d or users.d) but substitute configuration to both of them.\n\n        LOG_ERROR(log, \"The <users>, <profiles> and <quotas> elements should be located in users config file: {} not in main config {}.\"\n            \" Also note that you should place configuration changes to the appropriate *.d directory like 'users.d'.\",\n            users_config_path, config_path);\n    }\n}\n\n\nint Server::main(const std::vector<std::string> & \/*args*\/)\n{\n    Poco::Logger * log = &logger();\n    UseSSL use_ssl;\n\n    ThreadStatus thread_status;\n\n    registerFunctions();\n    registerAggregateFunctions();\n    registerTableFunctions();\n    registerStorages();\n    registerDictionaries();\n    registerDisks();\n\n#if !defined(ARCADIA_BUILD)\n#if USE_OPENCL\n    BitonicSort::getInstance().configure();\n#endif\n#endif\n\n    CurrentMetrics::set(CurrentMetrics::Revision, ClickHouseRevision::get());\n    CurrentMetrics::set(CurrentMetrics::VersionInteger, ClickHouseRevision::getVersionInteger());\n\n    if (ThreadFuzzer::instance().isEffective())\n        LOG_WARNING(log, \"ThreadFuzzer is enabled. Application will run slowly and unstable.\");\n\n#if !defined(NDEBUG) || !defined(__OPTIMIZE__)\n    LOG_WARNING(log, \"Server was built in debug mode. It will work slowly.\");\n#endif\n\n#if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) || defined(MEMORY_SANITIZER)\n    LOG_WARNING(log, \"Server was built with sanitizer. It will work slowly.\");\n#endif\n\n    \/** Context contains all that query execution is dependent:\n      *  settings, available functions, data types, aggregate functions, databases, ...\n      *\/\n    auto shared_context = Context::createShared();\n    auto global_context = std::make_unique<Context>(Context::createGlobal(shared_context.get()));\n    global_context_ptr = global_context.get();\n\n    global_context->makeGlobalContext();\n    global_context->setApplicationType(Context::ApplicationType::SERVER);\n\n    bool has_zookeeper = config().has(\"zookeeper\");\n\n    zkutil::ZooKeeperNodeCache main_config_zk_node_cache([&] { return global_context->getZooKeeper(); });\n    zkutil::EventPtr main_config_zk_changed_event = std::make_shared<Poco::Event>();\n    if (loaded_config.has_zk_includes)\n    {\n        auto old_configuration = loaded_config.configuration;\n        ConfigProcessor config_processor(config_path);\n        loaded_config = config_processor.loadConfigWithZooKeeperIncludes(\n            main_config_zk_node_cache, main_config_zk_changed_event, \/* fallback_to_preprocessed = *\/ true);\n        config_processor.savePreprocessedConfig(loaded_config, config().getString(\"path\", DBMS_DEFAULT_PATH));\n        config().removeConfiguration(old_configuration.get());\n        config().add(loaded_config.configuration.duplicate(), PRIO_DEFAULT, false);\n    }\n\n    Settings::checkNoSettingNamesAtTopLevel(config(), config_path);\n\n    const auto memory_amount = getMemoryAmount();\n\n#if defined(OS_LINUX)\n    std::string executable_path = getExecutablePath();\n    if (executable_path.empty())\n        executable_path = \"\/usr\/bin\/clickhouse\";    \/\/\/ It is used for information messages.\n\n    \/\/\/ After full config loaded\n    {\n        if (config().getBool(\"mlock_executable\", false))\n        {\n            if (hasLinuxCapability(CAP_IPC_LOCK))\n            {\n                LOG_TRACE(log, \"Will mlockall to prevent executable memory from being paged out. It may take a few seconds.\");\n                if (0 != mlockall(MCL_CURRENT))\n                    LOG_WARNING(log, \"Failed mlockall: {}\", errnoToString(ErrorCodes::SYSTEM_ERROR));\n                else\n                    LOG_TRACE(log, \"The memory map of clickhouse executable has been mlock'ed\");\n            }\n            else\n            {\n                LOG_INFO(log, \"It looks like the process has no CAP_IPC_LOCK capability, binary mlock will be disabled.\"\n                    \" It could happen due to incorrect ClickHouse package installation.\"\n                    \" You could resolve the problem manually with 'sudo setcap cap_ipc_lock=+ep {}'.\"\n                    \" Note that it will not work on 'nosuid' mounted filesystems.\", executable_path);\n            }\n        }\n    }\n#endif\n\n    global_context->setRemoteHostFilter(config());\n\n    std::string path = getCanonicalPath(config().getString(\"path\", DBMS_DEFAULT_PATH));\n    std::string default_database = config().getString(\"default_database\", \"default\");\n\n    \/\/\/ Check that the process user id matches the owner of the data.\n    const auto effective_user_id = geteuid();\n    struct stat statbuf;\n    if (stat(path.c_str(), &statbuf) == 0 && effective_user_id != statbuf.st_uid)\n    {\n        const auto effective_user = getUserName(effective_user_id);\n        const auto data_owner = getUserName(statbuf.st_uid);\n        std::string message = \"Effective user of the process (\" + effective_user +\n            \") does not match the owner of the data (\" + data_owner + \").\";\n        if (effective_user_id == 0)\n        {\n            message += \" Run under 'sudo -u \" + data_owner + \"'.\";\n            throw Exception(message, ErrorCodes::MISMATCHING_USERS_FOR_PROCESS_AND_DATA);\n        }\n        else\n        {\n            LOG_WARNING(log, message);\n        }\n    }\n\n    global_context->setPath(path);\n\n    StatusFile status{path + \"status\", StatusFile::write_full_info};\n\n    SCOPE_EXIT({\n        \/** Ask to cancel background jobs all table engines,\n          *  and also query_log.\n          * It is important to do early, not in destructor of Context, because\n          *  table engines could use Context on destroy.\n          *\/\n        LOG_INFO(log, \"Shutting down storages.\");\n\n        global_context->shutdown();\n\n        LOG_DEBUG(log, \"Shut down storages.\");\n\n        \/** Explicitly destroy Context. It is more convenient than in destructor of Server, because logger is still available.\n          * At this moment, no one could own shared part of Context.\n          *\/\n        global_context_ptr = nullptr;\n        global_context.reset();\n        shared_context.reset();\n        LOG_DEBUG(log, \"Destroyed global context.\");\n    });\n\n    \/\/\/ Try to increase limit on number of open files.\n    {\n        rlimit rlim;\n        if (getrlimit(RLIMIT_NOFILE, &rlim))\n            throw Poco::Exception(\"Cannot getrlimit\");\n\n        if (rlim.rlim_cur == rlim.rlim_max)\n        {\n            LOG_DEBUG(log, \"rlimit on number of file descriptors is {}\", rlim.rlim_cur);\n        }\n        else\n        {\n            rlim_t old = rlim.rlim_cur;\n            rlim.rlim_cur = config().getUInt(\"max_open_files\", rlim.rlim_max);\n            int rc = setrlimit(RLIMIT_NOFILE, &rlim);\n            if (rc != 0)\n                LOG_WARNING(log, \"Cannot set max number of file descriptors to {}. Try to specify max_open_files according to your system limits. error: {}\", rlim.rlim_cur, strerror(errno));\n            else\n                LOG_DEBUG(log, \"Set max number of file descriptors to {} (was {}).\", rlim.rlim_cur, old);\n        }\n    }\n\n    static ServerErrorHandler error_handler;\n    Poco::ErrorHandler::set(&error_handler);\n\n    \/\/\/ Initialize DateLUT early, to not interfere with running time of first query.\n    LOG_DEBUG(log, \"Initializing DateLUT.\");\n    DateLUT::instance();\n    LOG_TRACE(log, \"Initialized DateLUT with time zone '{}'.\", DateLUT::instance().getTimeZone());\n\n    \/\/\/ Initialize global thread pool\n    GlobalThreadPool::initialize(config().getUInt(\"max_thread_pool_size\", 10000));\n\n    \/\/\/ Storage with temporary data for processing of heavy queries.\n    {\n        std::string tmp_path = config().getString(\"tmp_path\", path + \"tmp\/\");\n        std::string tmp_policy = config().getString(\"tmp_policy\", \"\");\n        const VolumePtr & volume = global_context->setTemporaryStorage(tmp_path, tmp_policy);\n        for (const DiskPtr & disk : volume->getDisks())\n            setupTmpPath(log, disk->getPath());\n    }\n\n    \/** Directory with 'flags': files indicating temporary settings for the server set by system administrator.\n      * Flags may be cleared automatically after being applied by the server.\n      * Examples: do repair of local data; clone all replicated tables from replica.\n      *\/\n    {\n        Poco::File(path + \"flags\/\").createDirectories();\n        global_context->setFlagsPath(path + \"flags\/\");\n    }\n\n    \/** Directory with user provided files that are usable by 'file' table function.\n      *\/\n    {\n\n        std::string user_files_path = config().getString(\"user_files_path\", path + \"user_files\/\");\n        global_context->setUserFilesPath(user_files_path);\n        Poco::File(user_files_path).createDirectories();\n    }\n\n    {\n        std::string dictionaries_lib_path = config().getString(\"dictionaries_lib_path\", path + \"dictionaries_lib\/\");\n        global_context->setDictionariesLibPath(dictionaries_lib_path);\n        Poco::File(dictionaries_lib_path).createDirectories();\n    }\n\n    {\n        Poco::File(path + \"data\/\").createDirectories();\n        Poco::File(path + \"metadata\/\").createDirectories();\n\n        \/\/\/ Directory with metadata of tables, which was marked as dropped by Atomic database\n        Poco::File(path + \"metadata_dropped\/\").createDirectories();\n    }\n\n    if (config().has(\"interserver_http_port\") && config().has(\"interserver_https_port\"))\n        throw Exception(\"Both http and https interserver ports are specified\", ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG);\n\n    static const auto interserver_tags =\n    {\n        std::make_tuple(\"interserver_http_host\", \"interserver_http_port\", \"http\"),\n        std::make_tuple(\"interserver_https_host\", \"interserver_https_port\", \"https\")\n    };\n\n    for (auto [host_tag, port_tag, scheme] : interserver_tags)\n    {\n        if (config().has(port_tag))\n        {\n            String this_host = config().getString(host_tag, \"\");\n\n            if (this_host.empty())\n            {\n                this_host = getFQDNOrHostName();\n                LOG_DEBUG(log, \"Configuration parameter '{}' doesn't exist or exists and empty. Will use '{}' as replica host.\",\n                    host_tag, this_host);\n            }\n\n            String port_str = config().getString(port_tag);\n            int port = parse<int>(port_str);\n\n            if (port < 0 || port > 0xFFFF)\n                throw Exception(\"Out of range '\" + String(port_tag) + \"': \" + toString(port), ErrorCodes::ARGUMENT_OUT_OF_BOUND);\n\n            global_context->setInterserverIOAddress(this_host, port);\n            global_context->setInterserverScheme(scheme);\n        }\n    }\n\n    if (config().has(\"interserver_http_credentials\"))\n    {\n        String user = config().getString(\"interserver_http_credentials.user\", \"\");\n        String password = config().getString(\"interserver_http_credentials.password\", \"\");\n\n        if (user.empty())\n            throw Exception(\"Configuration parameter interserver_http_credentials user can't be empty\", ErrorCodes::NO_ELEMENTS_IN_CONFIG);\n\n        global_context->setInterserverCredentials(user, password);\n    }\n\n    if (config().has(\"macros\"))\n        global_context->setMacros(std::make_unique<Macros>(config(), \"macros\"));\n\n    \/\/\/ Initialize main config reloader.\n    std::string include_from_path = config().getString(\"include_from\", \"\/etc\/metrika.xml\");\n\n    if (config().has(\"query_masking_rules\"))\n    {\n        SensitiveDataMasker::setInstance(std::make_unique<SensitiveDataMasker>(config(), \"query_masking_rules\"));\n    }\n\n    auto main_config_reloader = std::make_unique<ConfigReloader>(\n        config_path,\n        include_from_path,\n        config().getString(\"path\", \"\"),\n        std::move(main_config_zk_node_cache),\n        main_config_zk_changed_event,\n        [&](ConfigurationPtr config)\n        {\n            Settings::checkNoSettingNamesAtTopLevel(*config, config_path);\n\n            \/\/ FIXME logging-related things need synchronization -- see the 'Logger * log' saved\n            \/\/ in a lot of places. For now, disable updating log configuration without server restart.\n            \/\/setTextLog(global_context->getTextLog());\n            \/\/buildLoggers(*config, logger());\n            global_context->setClustersConfig(config);\n            global_context->setMacros(std::make_unique<Macros>(*config, \"macros\"));\n            global_context->setExternalAuthenticatorsConfig(*config);\n\n            \/\/\/ Setup protection to avoid accidental DROP for big tables (that are greater than 50 GB by default)\n            if (config->has(\"max_table_size_to_drop\"))\n                global_context->setMaxTableSizeToDrop(config->getUInt64(\"max_table_size_to_drop\"));\n\n            if (config->has(\"max_partition_size_to_drop\"))\n                global_context->setMaxPartitionSizeToDrop(config->getUInt64(\"max_partition_size_to_drop\"));\n\n            global_context->updateStorageConfiguration(*config);\n        },\n        \/* already_loaded = *\/ true);\n\n    auto & access_control = global_context->getAccessControlManager();\n    if (config().has(\"custom_settings_prefixes\"))\n        access_control.setCustomSettingsPrefixes(config().getString(\"custom_settings_prefixes\"));\n\n    \/\/\/ Initialize access storages.\n    access_control.addStoragesFromMainConfig(config(), config_path, [&] { return global_context->getZooKeeper(); });\n\n    \/\/\/ Reload config in SYSTEM RELOAD CONFIG query.\n    global_context->setConfigReloadCallback([&]()\n    {\n        main_config_reloader->reload();\n        access_control.reloadUsersConfigs();\n    });\n\n    \/\/\/ Limit on total number of concurrently executed queries.\n    global_context->getProcessList().setMaxSize(config().getInt(\"max_concurrent_queries\", 0));\n\n    \/\/\/ Set up caches.\n\n    \/\/\/ Lower cache size on low-memory systems.\n    double cache_size_to_ram_max_ratio = config().getDouble(\"cache_size_to_ram_max_ratio\", 0.5);\n    size_t max_cache_size = memory_amount * cache_size_to_ram_max_ratio;\n\n    \/\/\/ Size of cache for uncompressed blocks. Zero means disabled.\n    size_t uncompressed_cache_size = config().getUInt64(\"uncompressed_cache_size\", 0);\n    if (uncompressed_cache_size > max_cache_size)\n    {\n        uncompressed_cache_size = max_cache_size;\n        LOG_INFO(log, \"Uncompressed cache size was lowered to {} because the system has low amount of memory\",\n            formatReadableSizeWithBinarySuffix(uncompressed_cache_size));\n    }\n    global_context->setUncompressedCache(uncompressed_cache_size);\n\n    \/\/\/ Load global settings from default_profile and system_profile.\n    global_context->setDefaultProfiles(config());\n    const Settings & settings = global_context->getSettingsRef();\n\n    \/\/\/ Size of cache for marks (index of MergeTree family of tables). It is mandatory.\n    size_t mark_cache_size = config().getUInt64(\"mark_cache_size\");\n    if (!mark_cache_size)\n        LOG_ERROR(log, \"Too low mark cache size will lead to severe performance degradation.\");\n    if (mark_cache_size > max_cache_size)\n    {\n        mark_cache_size = max_cache_size;\n        LOG_INFO(log, \"Mark cache size was lowered to {} because the system has low amount of memory\",\n            formatReadableSizeWithBinarySuffix(mark_cache_size));\n    }\n    global_context->setMarkCache(mark_cache_size);\n\n#if USE_EMBEDDED_COMPILER\n    size_t compiled_expression_cache_size = config().getUInt64(\"compiled_expression_cache_size\", 500);\n    if (compiled_expression_cache_size)\n        global_context->setCompiledExpressionCache(compiled_expression_cache_size);\n#endif\n\n    \/\/\/ Set path for format schema files\n    auto format_schema_path = Poco::File(config().getString(\"format_schema_path\", path + \"format_schemas\/\"));\n    global_context->setFormatSchemaPath(format_schema_path.path());\n    format_schema_path.createDirectories();\n\n    \/\/\/ Check sanity of MergeTreeSettings on server startup\n    global_context->getMergeTreeSettings().sanityCheck(settings);\n\n    \/\/\/ Limit on total memory usage\n    size_t max_server_memory_usage = config().getUInt64(\"max_server_memory_usage\", 0);\n\n    double max_server_memory_usage_to_ram_ratio = config().getDouble(\"max_server_memory_usage_to_ram_ratio\", 0.9);\n    size_t default_max_server_memory_usage = memory_amount * max_server_memory_usage_to_ram_ratio;\n\n    if (max_server_memory_usage == 0)\n    {\n        max_server_memory_usage = default_max_server_memory_usage;\n        LOG_INFO(log, \"Setting max_server_memory_usage was set to {}\"\n            \" ({} available * {:.2f} max_server_memory_usage_to_ram_ratio)\",\n            formatReadableSizeWithBinarySuffix(max_server_memory_usage),\n            formatReadableSizeWithBinarySuffix(memory_amount),\n            max_server_memory_usage_to_ram_ratio);\n    }\n    else if (max_server_memory_usage > default_max_server_memory_usage)\n    {\n        max_server_memory_usage = default_max_server_memory_usage;\n        LOG_INFO(log, \"Setting max_server_memory_usage was lowered to {}\"\n            \" because the system has low amount of memory. The amount was\"\n            \" calculated as {} available\"\n            \" * {:.2f} max_server_memory_usage_to_ram_ratio\",\n            formatReadableSizeWithBinarySuffix(max_server_memory_usage),\n            formatReadableSizeWithBinarySuffix(memory_amount),\n            max_server_memory_usage_to_ram_ratio);\n    }\n\n    total_memory_tracker.setOrRaiseHardLimit(max_server_memory_usage);\n    total_memory_tracker.setDescription(\"(total)\");\n    total_memory_tracker.setMetric(CurrentMetrics::MemoryTracking);\n\n    LOG_INFO(log, \"Loading metadata from {}\", path);\n\n    try\n    {\n        loadMetadataSystem(*global_context);\n        \/\/\/ After attaching system databases we can initialize system log.\n        global_context->initializeSystemLogs();\n        \/\/\/ After the system database is created, attach virtual system tables (in addition to query_log and part_log)\n        attachSystemTablesServer(*DatabaseCatalog::instance().getSystemDatabase(), has_zookeeper);\n        \/\/\/ Then, load remaining databases\n        loadMetadata(*global_context, default_database);\n        DatabaseCatalog::instance().loadDatabases();\n    }\n    catch (...)\n    {\n        tryLogCurrentException(log, \"Caught exception while loading metadata\");\n        throw;\n    }\n    LOG_DEBUG(log, \"Loaded metadata.\");\n\n    \/\/\/ Init trace collector only after trace_log system table was created\n    \/\/\/ Disable it if we collect test coverage information, because it will work extremely slow.\n    \/\/\/\n    \/\/\/ It also cannot work with sanitizers.\n    \/\/\/ Sanitizers are using quick \"frame walking\" stack unwinding (this implies -fno-omit-frame-pointer)\n    \/\/\/ And they do unwinding frequently (on every malloc\/free, thread\/mutex operations, etc).\n    \/\/\/ They change %rbp during unwinding and it confuses libunwind if signal comes during sanitizer unwinding\n    \/\/\/  and query profiler decide to unwind stack with libunwind at this moment.\n    \/\/\/\n    \/\/\/ Symptoms: you'll get silent Segmentation Fault - without sanitizer message and without usual ClickHouse diagnostics.\n    \/\/\/\n    \/\/\/ Look at compiler-rt\/lib\/sanitizer_common\/sanitizer_stacktrace.h\n    \/\/\/\n#if USE_UNWIND && !WITH_COVERAGE && !defined(SANITIZER)\n    \/\/\/ Profilers cannot work reliably with any other libunwind or without PHDR cache.\n    if (hasPHDRCache())\n    {\n        global_context->initializeTraceCollector();\n\n        \/\/\/ Set up server-wide memory profiler (for total memory tracker).\n        UInt64 total_memory_profiler_step = config().getUInt64(\"total_memory_profiler_step\", 0);\n        if (total_memory_profiler_step)\n        {\n            total_memory_tracker.setOrRaiseProfilerLimit(total_memory_profiler_step);\n            total_memory_tracker.setProfilerStep(total_memory_profiler_step);\n        }\n\n        double total_memory_tracker_sample_probability = config().getDouble(\"total_memory_tracker_sample_probability\", 0);\n        if (total_memory_tracker_sample_probability)\n        {\n            total_memory_tracker.setSampleProbability(total_memory_tracker_sample_probability);\n        }\n    }\n#endif\n\n    \/\/\/ Describe multiple reasons when query profiler cannot work.\n\n#if !USE_UNWIND\n    LOG_INFO(log, \"Query Profiler and TraceCollector are disabled because they cannot work without bundled unwind (stack unwinding) library.\");\n#endif\n\n#if WITH_COVERAGE\n    LOG_INFO(log, \"Query Profiler and TraceCollector are disabled because they work extremely slow with test coverage.\");\n#endif\n\n#if defined(SANITIZER)\n    LOG_INFO(log, \"Query Profiler and TraceCollector are disabled because they cannot work under sanitizers\"\n        \" when two different stack unwinding methods will interfere with each other.\");\n#endif\n\n    if (!hasPHDRCache())\n        LOG_INFO(log, \"Query Profiler and TraceCollector are disabled because they require PHDR cache to be created\"\n            \" (otherwise the function 'dl_iterate_phdr' is not lock free and not async-signal safe).\");\n\n    global_context->setCurrentDatabase(default_database);\n\n    if (has_zookeeper && config().has(\"distributed_ddl\"))\n    {\n        \/\/\/ DDL worker should be started after all tables were loaded\n        String ddl_zookeeper_path = config().getString(\"distributed_ddl.path\", \"\/clickhouse\/task_queue\/ddl\/\");\n        global_context->setDDLWorker(std::make_unique<DDLWorker>(ddl_zookeeper_path, *global_context, &config(), \"distributed_ddl\"));\n    }\n\n    std::unique_ptr<DNSCacheUpdater> dns_cache_updater;\n    if (config().has(\"disable_internal_dns_cache\") && config().getInt(\"disable_internal_dns_cache\"))\n    {\n        \/\/\/ Disable DNS caching at all\n        DNSResolver::instance().setDisableCacheFlag();\n    }\n    else\n    {\n        \/\/\/ Initialize a watcher periodically updating DNS cache\n        dns_cache_updater = std::make_unique<DNSCacheUpdater>(*global_context, config().getInt(\"dns_cache_update_period\", 15));\n    }\n\n#if defined(OS_LINUX)\n    if (!TasksStatsCounters::checkIfAvailable())\n    {\n        LOG_INFO(log, \"It looks like this system does not have procfs mounted at \/proc location,\"\n            \" neither clickhouse-server process has CAP_NET_ADMIN capability.\"\n            \" 'taskstats' performance statistics will be disabled.\"\n            \" It could happen due to incorrect ClickHouse package installation.\"\n            \" You can try to resolve the problem manually with 'sudo setcap cap_net_admin=+ep {}'.\"\n            \" Note that it will not work on 'nosuid' mounted filesystems.\"\n            \" It also doesn't work if you run clickhouse-server inside network namespace as it happens in some containers.\",\n            executable_path);\n    }\n\n    if (!hasLinuxCapability(CAP_SYS_NICE))\n    {\n        LOG_INFO(log, \"It looks like the process has no CAP_SYS_NICE capability, the setting 'os_thread_priority' will have no effect.\"\n            \" It could happen due to incorrect ClickHouse package installation.\"\n            \" You could resolve the problem manually with 'sudo setcap cap_sys_nice=+ep {}'.\"\n            \" Note that it will not work on 'nosuid' mounted filesystems.\",\n            executable_path);\n    }\n#else\n    LOG_INFO(log, \"TaskStats is not implemented for this OS. IO accounting will be disabled.\");\n#endif\n\n    {\n        Poco::Timespan keep_alive_timeout(config().getUInt(\"keep_alive_timeout\", 10), 0);\n\n        Poco::ThreadPool server_pool(3, config().getUInt(\"max_connections\", 1024));\n        Poco::Net::HTTPServerParams::Ptr http_params = new Poco::Net::HTTPServerParams;\n        http_params->setTimeout(settings.http_receive_timeout);\n        http_params->setKeepAliveTimeout(keep_alive_timeout);\n\n        std::vector<std::unique_ptr<Poco::Net::TCPServer>> servers;\n\n        std::vector<std::string> listen_hosts = DB::getMultipleValuesFromConfig(config(), \"\", \"listen_host\");\n\n        bool listen_try = config().getBool(\"listen_try\", false);\n        if (listen_hosts.empty())\n        {\n            listen_hosts.emplace_back(\"::1\");\n            listen_hosts.emplace_back(\"127.0.0.1\");\n            listen_try = true;\n        }\n\n        auto make_socket_address = [&](const std::string & host, UInt16 port)\n        {\n            Poco::Net::SocketAddress socket_address;\n            try\n            {\n                socket_address = Poco::Net::SocketAddress(host, port);\n            }\n            catch (const Poco::Net::DNSException & e)\n            {\n                const auto code = e.code();\n                if (code == EAI_FAMILY\n#if defined(EAI_ADDRFAMILY)\n                    || code == EAI_ADDRFAMILY\n#endif\n                    )\n                {\n                    LOG_ERROR(log, \"Cannot resolve listen_host ({}), error {}: {}. \"\n                        \"If it is an IPv6 address and your host has disabled IPv6, then consider to \"\n                        \"specify IPv4 address to listen in <listen_host> element of configuration \"\n                        \"file. Example: <listen_host>0.0.0.0<\/listen_host>\",\n                        host, e.code(), e.message());\n                }\n\n                throw;\n            }\n            return socket_address;\n        };\n\n        auto socket_bind_listen = [&](auto & socket, const std::string & host, UInt16 port, [[maybe_unused]] bool secure = false)\n        {\n               auto address = make_socket_address(host, port);\n#if !defined(POCO_CLICKHOUSE_PATCH) || POCO_VERSION < 0x01090100\n               if (secure)\n                   \/\/\/ Bug in old (<1.9.1) poco, listen() after bind() with reusePort param will fail because have no implementation in SecureServerSocketImpl\n                   \/\/\/ https:\/\/github.com\/pocoproject\/poco\/pull\/2257\n                   socket.bind(address, \/* reuseAddress = *\/ true);\n               else\n#endif\n#if POCO_VERSION < 0x01080000\n                   socket.bind(address, \/* reuseAddress = *\/ true);\n#else\n                   socket.bind(address, \/* reuseAddress = *\/ true, \/* reusePort = *\/ config().getBool(\"listen_reuse_port\", false));\n#endif\n\n               socket.listen(\/* backlog = *\/ config().getUInt(\"listen_backlog\", 64));\n\n               return address;\n        };\n\n        \/\/\/ This object will periodically calculate some metrics.\n        AsynchronousMetrics async_metrics(*global_context,\n            config().getUInt(\"asynchronous_metrics_update_period_s\", 60));\n        attachSystemTablesAsync(*DatabaseCatalog::instance().getSystemDatabase(), async_metrics);\n\n        for (const auto & listen_host : listen_hosts)\n        {\n            auto create_server = [&](const char * port_name, auto && func)\n            {\n                \/\/\/ For testing purposes, user may omit tcp_port or http_port or https_port in configuration file.\n                if (!config().has(port_name))\n                    return;\n\n                auto port = config().getInt(port_name);\n                try\n                {\n                    func(port);\n                }\n                catch (const Poco::Exception &)\n                {\n                    std::string message = \"Listen [\" + listen_host + \"]:\" + std::to_string(port) + \" failed: \" + getCurrentExceptionMessage(false);\n\n                    if (listen_try)\n                    {\n                        LOG_WARNING(log, \"{}. If it is an IPv6 or IPv4 address and your host has disabled IPv6 or IPv4, then consider to \"\n                            \"specify not disabled IPv4 or IPv6 address to listen in <listen_host> element of configuration \"\n                            \"file. Example for disabled IPv6: <listen_host>0.0.0.0<\/listen_host> .\"\n                            \" Example for disabled IPv4: <listen_host>::<\/listen_host>\",\n                            message);\n                    }\n                    else\n                    {\n                        throw Exception{message, ErrorCodes::NETWORK_ERROR};\n                    }\n                }\n            };\n\n            \/\/\/ HTTP\n            create_server(\"http_port\", [&](UInt16 port)\n            {\n                Poco::Net::ServerSocket socket;\n                auto address = socket_bind_listen(socket, listen_host, port);\n                socket.setReceiveTimeout(settings.http_receive_timeout);\n                socket.setSendTimeout(settings.http_send_timeout);\n\n                servers.emplace_back(std::make_unique<Poco::Net::HTTPServer>(\n                    createHandlerFactory(*this, async_metrics, \"HTTPHandler-factory\"), server_pool, socket, http_params));\n\n                LOG_INFO(log, \"Listening for http:\/\/{}\", address.toString());\n            });\n\n            \/\/\/ HTTPS\n            create_server(\"https_port\", [&](UInt16 port)\n            {\n#if USE_SSL\n                Poco::Net::SecureServerSocket socket;\n                auto address = socket_bind_listen(socket, listen_host, port, \/* secure = *\/ true);\n                socket.setReceiveTimeout(settings.http_receive_timeout);\n                socket.setSendTimeout(settings.http_send_timeout);\n                servers.emplace_back(std::make_unique<Poco::Net::HTTPServer>(\n                    createHandlerFactory(*this, async_metrics, \"HTTPSHandler-factory\"), server_pool, socket, http_params));\n\n                LOG_INFO(log, \"Listening for https:\/\/{}\", address.toString());\n#else\n                UNUSED(port);\n                throw Exception{\"HTTPS protocol is disabled because Poco library was built without NetSSL support.\",\n                    ErrorCodes::SUPPORT_IS_DISABLED};\n#endif\n            });\n\n            \/\/\/ TCP\n            create_server(\"tcp_port\", [&](UInt16 port)\n            {\n                Poco::Net::ServerSocket socket;\n                auto address = socket_bind_listen(socket, listen_host, port);\n                socket.setReceiveTimeout(settings.receive_timeout);\n                socket.setSendTimeout(settings.send_timeout);\n                servers.emplace_back(std::make_unique<Poco::Net::TCPServer>(\n                    new TCPHandlerFactory(*this),\n                    server_pool,\n                    socket,\n                    new Poco::Net::TCPServerParams));\n\n                LOG_INFO(log, \"Listening for connections with native protocol (tcp): {}\", address.toString());\n            });\n\n            \/\/\/ TCP with SSL\n            create_server(\"tcp_port_secure\", [&](UInt16 port)\n            {\n#if USE_SSL\n                Poco::Net::SecureServerSocket socket;\n                auto address = socket_bind_listen(socket, listen_host, port, \/* secure = *\/ true);\n                socket.setReceiveTimeout(settings.receive_timeout);\n                socket.setSendTimeout(settings.send_timeout);\n                servers.emplace_back(std::make_unique<Poco::Net::TCPServer>(\n                    new TCPHandlerFactory(*this, \/* secure= *\/ true),\n                    server_pool,\n                    socket,\n                    new Poco::Net::TCPServerParams));\n                LOG_INFO(log, \"Listening for connections with secure native protocol (tcp_secure): {}\", address.toString());\n#else\n                UNUSED(port);\n                throw Exception{\"SSL support for TCP protocol is disabled because Poco library was built without NetSSL support.\",\n                    ErrorCodes::SUPPORT_IS_DISABLED};\n#endif\n            });\n\n            \/\/\/ Interserver IO HTTP\n            create_server(\"interserver_http_port\", [&](UInt16 port)\n            {\n                Poco::Net::ServerSocket socket;\n                auto address = socket_bind_listen(socket, listen_host, port);\n                socket.setReceiveTimeout(settings.http_receive_timeout);\n                socket.setSendTimeout(settings.http_send_timeout);\n                servers.emplace_back(std::make_unique<Poco::Net::HTTPServer>(\n                    createHandlerFactory(*this, async_metrics, \"InterserverIOHTTPHandler-factory\"), server_pool, socket, http_params));\n\n                LOG_INFO(log, \"Listening for replica communication (interserver): http:\/\/{}\", address.toString());\n            });\n\n            create_server(\"interserver_https_port\", [&](UInt16 port)\n            {\n#if USE_SSL\n                Poco::Net::SecureServerSocket socket;\n                auto address = socket_bind_listen(socket, listen_host, port, \/* secure = *\/ true);\n                socket.setReceiveTimeout(settings.http_receive_timeout);\n                socket.setSendTimeout(settings.http_send_timeout);\n                servers.emplace_back(std::make_unique<Poco::Net::HTTPServer>(\n                    createHandlerFactory(*this, async_metrics, \"InterserverIOHTTPSHandler-factory\"), server_pool, socket, http_params));\n\n                LOG_INFO(log, \"Listening for secure replica communication (interserver): https:\/\/{}\", address.toString());\n#else\n                UNUSED(port);\n                throw Exception{\"SSL support for TCP protocol is disabled because Poco library was built without NetSSL support.\",\n                        ErrorCodes::SUPPORT_IS_DISABLED};\n#endif\n            });\n\n            create_server(\"mysql_port\", [&](UInt16 port)\n            {\n                Poco::Net::ServerSocket socket;\n                auto address = socket_bind_listen(socket, listen_host, port, \/* secure = *\/ true);\n                socket.setReceiveTimeout(Poco::Timespan());\n                socket.setSendTimeout(settings.send_timeout);\n                servers.emplace_back(std::make_unique<Poco::Net::TCPServer>(\n                    new MySQLHandlerFactory(*this),\n                    server_pool,\n                    socket,\n                    new Poco::Net::TCPServerParams));\n\n                LOG_INFO(log, \"Listening for MySQL compatibility protocol: {}\", address.toString());\n            });\n\n            create_server(\"postgresql_port\", [&](UInt16 port)\n            {\n                Poco::Net::ServerSocket socket;\n                auto address = socket_bind_listen(socket, listen_host, port, \/* secure = *\/ true);\n                socket.setReceiveTimeout(Poco::Timespan());\n                socket.setSendTimeout(settings.send_timeout);\n                servers.emplace_back(std::make_unique<Poco::Net::TCPServer>(\n                    new PostgreSQLHandlerFactory(*this),\n                    server_pool,\n                    socket,\n                    new Poco::Net::TCPServerParams));\n\n                LOG_INFO(log, \"Listening for PostgreSQL compatibility protocol: \" + address.toString());\n            });\n\n            \/\/\/ Prometheus (if defined and not setup yet with http_port)\n            create_server(\"prometheus.port\", [&](UInt16 port)\n            {\n                Poco::Net::ServerSocket socket;\n                auto address = socket_bind_listen(socket, listen_host, port);\n                socket.setReceiveTimeout(settings.http_receive_timeout);\n                socket.setSendTimeout(settings.http_send_timeout);\n                servers.emplace_back(std::make_unique<Poco::Net::HTTPServer>(\n                    createHandlerFactory(*this, async_metrics, \"PrometheusHandler-factory\"), server_pool, socket, http_params));\n\n                LOG_INFO(log, \"Listening for Prometheus: http:\/\/{}\", address.toString());\n            });\n        }\n\n        if (servers.empty())\n             throw Exception(\"No servers started (add valid listen_host and 'tcp_port' or 'http_port' to configuration file.)\",\n                ErrorCodes::NO_ELEMENTS_IN_CONFIG);\n\n        global_context->enableNamedSessions();\n\n        for (auto & server : servers)\n            server->start();\n\n        {\n            String level_str = config().getString(\"text_log.level\", \"\");\n            int level = level_str.empty() ? INT_MAX : Poco::Logger::parseLevel(level_str);\n            setTextLog(global_context->getTextLog(), level);\n        }\n        buildLoggers(config(), logger());\n\n        main_config_reloader->start();\n        access_control.startPeriodicReloadingUsersConfigs();\n        if (dns_cache_updater)\n            dns_cache_updater->start();\n\n        {\n            LOG_INFO(log, \"Available RAM: {}; physical cores: {}; logical cores: {}.\",\n                formatReadableSizeWithBinarySuffix(memory_amount),\n                getNumberOfPhysicalCPUCores(),  \/\/ on ARM processors it can show only enabled at current moment cores\n                std::thread::hardware_concurrency());\n        }\n\n        LOG_INFO(log, \"Ready for connections.\");\n\n        SCOPE_EXIT({\n            LOG_DEBUG(log, \"Received termination signal.\");\n            LOG_DEBUG(log, \"Waiting for current connections to close.\");\n\n            is_cancelled = true;\n\n            int current_connections = 0;\n            for (auto & server : servers)\n            {\n                server->stop();\n                current_connections += server->currentConnections();\n            }\n\n            if (current_connections)\n                LOG_INFO(log, \"Closed all listening sockets. Waiting for {} outstanding connections.\", current_connections);\n            else\n                LOG_INFO(log, \"Closed all listening sockets.\");\n\n            \/\/\/ Killing remaining queries.\n            global_context->getProcessList().killAllQueries();\n\n            if (current_connections)\n            {\n                const int sleep_max_ms = 1000 * config().getInt(\"shutdown_wait_unfinished\", 5);\n                const int sleep_one_ms = 100;\n                int sleep_current_ms = 0;\n                while (sleep_current_ms < sleep_max_ms)\n                {\n                    current_connections = 0;\n                    for (auto & server : servers)\n                        current_connections += server->currentConnections();\n                    if (!current_connections)\n                        break;\n                    sleep_current_ms += sleep_one_ms;\n                    std::this_thread::sleep_for(std::chrono::milliseconds(sleep_one_ms));\n                }\n            }\n\n            if (current_connections)\n                LOG_INFO(log, \"Closed connections. But {} remain.\"\n                    \" Tip: To increase wait time add to config: <shutdown_wait_unfinished>60<\/shutdown_wait_unfinished>\", current_connections);\n            else\n                LOG_INFO(log, \"Closed connections.\");\n\n            dns_cache_updater.reset();\n            main_config_reloader.reset();\n\n            if (current_connections)\n            {\n                \/\/\/ There is no better way to force connections to close in Poco.\n                \/\/\/ Otherwise connection handlers will continue to live\n                \/\/\/ (they are effectively dangling objects, but they use global thread pool\n                \/\/\/  and global thread pool destructor will wait for threads, preventing server shutdown).\n\n                \/\/\/ Dump coverage here, because std::atexit callback would not be called.\n                dumpCoverageReportIfPossible();\n                LOG_INFO(log, \"Will shutdown forcefully.\");\n                _exit(Application::EXIT_OK);\n            }\n        });\n\n        \/\/\/ try to load dictionaries immediately, throw on error and die\n        ext::scope_guard dictionaries_xmls, models_xmls;\n        try\n        {\n            if (!config().getBool(\"dictionaries_lazy_load\", true))\n            {\n                global_context->tryCreateEmbeddedDictionaries();\n                global_context->getExternalDictionariesLoader().enableAlwaysLoadEverything(true);\n            }\n            dictionaries_xmls = global_context->getExternalDictionariesLoader().addConfigRepository(\n                std::make_unique<ExternalLoaderXMLConfigRepository>(config(), \"dictionaries_config\"));\n            models_xmls = global_context->getExternalModelsLoader().addConfigRepository(\n                std::make_unique<ExternalLoaderXMLConfigRepository>(config(), \"models_config\"));\n        }\n        catch (...)\n        {\n            LOG_ERROR(log, \"Caught exception while loading dictionaries.\");\n            throw;\n        }\n\n        std::vector<std::unique_ptr<MetricsTransmitter>> metrics_transmitters;\n        for (const auto & graphite_key : DB::getMultipleKeysFromConfig(config(), \"\", \"graphite\"))\n        {\n            metrics_transmitters.emplace_back(std::make_unique<MetricsTransmitter>(\n                global_context->getConfigRef(), graphite_key, async_metrics));\n        }\n\n        waitForTerminationRequest();\n    }\n\n    return Application::EXIT_OK;\n}\n}\n\n#pragma GCC diagnostic ignored \"-Wunused-function\"\n#pragma GCC diagnostic ignored \"-Wmissing-declarations\"\n\nint mainEntryClickHouseServer(int argc, char ** argv)\n{\n    DB::Server app;\n    try\n    {\n        return app.run(argc, argv);\n    }\n    catch (...)\n    {\n        std::cerr << DB::getCurrentExceptionMessage(true) << \"\\n\";\n        auto code = DB::getCurrentExceptionCode();\n        return code ? code : 1;\n    }\n}\n","avg_line_length":41.2263986014,"max_line_length":190,"alphanum_fraction":0.6438521723,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7944,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include \"Geometry.hpp\"\n\n#include <glm\/ext\/matrix_transform.hpp>\n\n#include <core\/Entity.hpp>\n\n#include <physics\/volumes\/Sphere.hpp>\n#include <physics\/volumes\/AABB.hpp>\n#include <physics\/volumes\/OBB.hpp>\n#include <physics\/Plane.hpp>\n\nnamespace slaggy\n{\n\tfloat Geometry::epsilon = 0.00001f;\n\t\n\tbool Geometry::sphereTest(const Shape& lhs, const Shape& rhs)\n\t{\n\t\treturn glm::distance(lhs.center(), rhs.center()) <= lhs.radius() + rhs.radius();\n\t}\n\n\tbool Geometry::aabbTest(const AABB& lhs, const AABB& rhs)\n\t{\n\t\tconst glm::vec3 lmin = lhs.min();\n\t\tconst glm::vec3 lmax = lhs.max();\n\t\tconst glm::vec3 rmin = rhs.min();\n\t\tconst glm::vec3 rmax = rhs.max();\n\n\t\treturn lmax.x > rmin.x && lmin.x < rmax.x\n\t\t\t&& lmax.y > rmin.y && lmin.y < rmax.y\n\t\t\t&& lmax.z > rmin.z && lmin.z < rmax.z;\n\t}\n\n\tbool Geometry::intersects(const Plane& lhs, const Plane& rhs)\n\t{\n\t\tconst glm::vec3 direction = glm::cross(lhs.normal, rhs.normal);\n\t\treturn magnitudeSqr(direction) > epsilon;\n\t}\n\n\tbool Geometry::intersects(const Sphere& one, const Sphere& other)\n\t{\n\t\treturn sphereTest(one, other);\n\t}\n\n\tbool Geometry::intersects(const Sphere& sphere, const Plane& plane)\n\t{\n\t\tconst float sphereRadius = sphere.radius();\n\t\tconst glm::vec3 sphereCenter = sphere.center();\n\n\t\tconst glm::vec3 closestPoint = plane.closestPointTo(sphereCenter);\n\t\tconst float distanceSq = distanceSqr(sphereCenter, closestPoint);\n\n\t\treturn sphereRadius * sphereRadius > distanceSq;\n\t}\n\n\tbool Geometry::intersects(const AABB& aabb, const Plane& plane)\n\t{\n\t\tconst float length = glm::dot(aabb.size(), Geometry::fabsf(plane.normal));\n\n\t\tconst float dot = glm::dot(plane.normal, aabb.center());\n\t\tconst float dist = dot - plane.distance();\n\n\t\treturn std::fabsf(dist) <= length;\n\t}\n\n\tbool Geometry::intersects(const OBB& obb, const Plane& plane)\n\t{\n\t\tconst glm::mat3 rotationalMatrix = glm::mat3(obb.transformationMatrix());\n\t\tconst glm::vec3 projectedPlaneNormal = glm::vec3\n\t\t(\n\t\t\tglm::dot(plane.normal, rotationalMatrix[0]),\n\t\t\tglm::dot(plane.normal, rotationalMatrix[1]),\n\t\t\tglm::dot(plane.normal, rotationalMatrix[2])\n\t\t);\n\n\t\tconst float length = glm::dot(obb.size(), Geometry::fabsf(projectedPlaneNormal));\n\n\t\tconst float dot = glm::dot(plane.normal, obb.center());\n\t\tconst float dist = dot - plane.distance();\n\n\t\treturn std::fabsf(dist) <= length;\n\t}\n\n\tbool Geometry::intersects(const Sphere& sphere, const AABB& aabb)\n\t{\n\t\tconst bool radiusCheck = sphereTest(sphere, aabb);\n\t\tif (!radiusCheck) return false;\n\n\t\t\/\/ Jim Arvo\n\n\t\tconst float sr = sphere.radius();\n\t\tconst glm::vec3 sc = sphere.center();\n\t\tconst glm::vec3 bmin = aabb.min();\n\t\tconst glm::vec3 bmax = aabb.max();\n\n\t\tfloat distance, squareDistance = 0;\n\n\t\t\/\/find the square of the distance\n\t\t\/\/from the sphere to the box\n\t\tfor (unsigned i = 0; i < 3; i++)\n\t\t{\n\t\t\tif (sc[i] < bmin[i])\n\t\t\t{\n\t\t\t\tdistance = sc[i] - bmin[i];\n\t\t\t\tsquareDistance += distance * distance;\n\t\t\t}\n\t\t\telse if (sc[i] > bmax[i])\n\t\t\t{\n\t\t\t\tdistance = sc[i] - bmax[i];\n\t\t\t\tsquareDistance += distance * distance;\n\t\t\t}\n\t\t}\n\n\t\treturn squareDistance <= sr * sr;\n\t}\n\n\tbool Geometry::intersects(const Sphere& sphere, const OBB& obb)\n\t{\n\t\tconst glm::vec3 spherePosition = sphere.center();\n\t\tconst glm::vec3 closest = obb.closestPointTo(spherePosition);\n\t\tconst float radius = sphere.radius();\n\n\t\treturn distanceSqr(spherePosition, closest) < radius * radius;\n\t}\n\n\tbool Geometry::intersects(const AABB& lhs, const AABB& rhs)\n\t{\n\t\treturn sphereTest(lhs, rhs) && aabbTest(lhs, rhs);\n\t}\n\n\tbool Geometry::intersects(const AABB& aabb, const OBB& obb)\n\t{\n\t\tconst bool radiusCheck = sphereTest(aabb, obb);\n\t\tif (!radiusCheck) return false;\n\n\t\treturn satTest(aabb, obb);\n\t}\n\n\tbool Geometry::intersects(const OBB& lhs, const OBB& rhs)\n\t{\n\t\tconst bool radiusCheck = sphereTest(lhs, rhs);\n\t\tif (!radiusCheck) return false;\n\n\t\treturn satTest(lhs, rhs);\n\t}\n\n\tbool Geometry::satTest(const Box& lhs, const Box& rhs)\n\t{\n\t\t\/\/ Separating Axis Theorem\n\n\t\tconst glm::vec3 lhsCenter = lhs.center(); \/\/ object's pos = collider center\n\t\tconst glm::vec3 rhsCenter = rhs.center();\n\t\tconst glm::mat4 lhsTransform = glm::scale(lhs.transformationMatrix(), lhs.halfSize()); \/\/ scaling for halfsize\n\t\tconst glm::mat4 rhsTransform = glm::scale(rhs.transformationMatrix(), rhs.halfSize()); \/\/ scaling for halfsize\n\n\t\tfor (unsigned a = 0; a < 3; a++)\n\t\t{\n\t\t\tconst glm::vec3 l = glm::vec3(lhsTransform[a]); \/\/ one axis to project on\n\t\t\tconst float tl = std::abs(glm::dot(l, rhsCenter) - glm::dot(l, lhsCenter)); \/\/ center distance\n\n\t\t\tconst float ra = std::abs(glm::dot(l, glm::vec3(lhsTransform[0])))\n\t\t\t\t+ std::abs(glm::dot(l, glm::vec3(lhsTransform[1])))\n\t\t\t\t+ std::abs(glm::dot(l, glm::vec3(lhsTransform[2])));\n\n\t\t\tconst float rb = std::abs(glm::dot(l, glm::vec3(rhsTransform[0])))\n\t\t\t\t+ std::abs(glm::dot(l, glm::vec3(rhsTransform[1])))\n\t\t\t\t+ std::abs(glm::dot(l, glm::vec3(rhsTransform[2])));\n\n\t\t\tconst float penetration = ra + rb - tl;\n\t\t\tif (penetration <= 0)\n\t\t\t{ \/\/ no overlap\n\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (unsigned b = 0; b < 3; b++)\n\t\t{\n\t\t\tconst glm::vec3 l = glm::vec3(rhsTransform[b]); \/\/ rhs axis to project on\n\t\t\tconst float tl = std::abs(glm::dot(l, rhsCenter) - glm::dot(l, lhsCenter)); \/\/ center distance\n\n\t\t\tconst float ra = std::abs(glm::dot(l, glm::vec3(lhsTransform[0])))\n\t\t\t\t+ std::abs(glm::dot(l, glm::vec3(lhsTransform[1])))\n\t\t\t\t+ std::abs(glm::dot(l, glm::vec3(lhsTransform[2])));\n\n\t\t\tconst float rb = std::abs(glm::dot(l, glm::vec3(rhsTransform[0])))\n\t\t\t\t+ std::abs(glm::dot(l, glm::vec3(rhsTransform[1])))\n\t\t\t\t+ std::abs(glm::dot(l, glm::vec3(rhsTransform[2])));\n\n\t\t\tconst float penetration = ra + rb - tl;\n\t\t\tif (penetration <= 0)\n\t\t\t{ \/\/ no overlap\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (unsigned a = 0; a < 3; a++)\n\t\t{\n\t\t\tconst glm::vec3 aAxis = glm::vec3(lhsTransform[a]);\n\t\t\tfor (unsigned b = 0; b < 3; b++)\n\t\t\t{\n\t\t\t\tconst glm::vec3 bAxis = glm::vec3(rhsTransform[b]);\n\t\t\t\tif (aAxis != bAxis)\n\t\t\t\t{\n\t\t\t\t\tconst glm::vec3 l = glm::cross(aAxis, bAxis); \/\/ has flaw when axis are same, result in (0,0,0), solved by if\n\t\t\t\t\tconst float tl = std::abs(glm::dot(l, rhsCenter) - glm::dot(l, lhsCenter)); \/\/ center distance\n\n\t\t\t\t\tconst float ra = std::abs(glm::dot(l, glm::vec3(lhsTransform[0])))\n\t\t\t\t\t\t+ std::abs(glm::dot(l, glm::vec3(lhsTransform[1])))\n\t\t\t\t\t\t+ std::abs(glm::dot(l, glm::vec3(lhsTransform[2])));\n\n\t\t\t\t\tconst float rb = std::abs(glm::dot(l, glm::vec3(rhsTransform[0])))\n\t\t\t\t\t\t+ std::abs(glm::dot(l, glm::vec3(rhsTransform[1])))\n\t\t\t\t\t\t+ std::abs(glm::dot(l, glm::vec3(rhsTransform[2])));\n\n\t\t\t\t\tconst float penetration = ra + rb - tl;\n\t\t\t\t\tif (penetration <= 0)\n\t\t\t\t\t{ \/\/ no overlap\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tfloat Geometry::distanceSqr(const glm::vec3& lhs, const glm::vec3& rhs)\n\t{\n\t\treturn magnitudeSqr(lhs - rhs);\n\t}\n\n\tfloat Geometry::magnitudeSqr(const glm::vec3& v)\n\t{\n\t\treturn v.x * v.x + v.y * v.y + v.z * v.z;\n\t}\n\n\tglm::vec3 Geometry::fabsf(const glm::vec3& v)\n\t{\n\t\treturn glm::vec3\n\t\t(\n\t\t\tstd::fabsf(v.x),\n\t\t\tstd::fabsf(v.y),\n\t\t\tstd::fabsf(v.z)\n\t\t);\n\t}\n\n\tvoid Geometry::reflectVelocity(const glm::vec3& centerLhs, const glm::vec3& centerRhs, glm::vec3& velocityLhs, glm::vec3& velocityRhs)\n\t{\n\t\tconst glm::vec3 total = velocityLhs - velocityRhs;\n\t\tvelocityLhs = velocityLhs - total;\n\t\tvelocityRhs = velocityLhs + total;\n\t\treturn;\n\n\t\t\/\/ https:\/\/en.wikipedia.org\/wiki\/Elastic_collision#Two-dimensional_collision_with_two_moving_objects\n\t\t\/\/ assuming masses are equal\n\n\t\tconst glm::vec3 centerDistanceLR = centerLhs - centerRhs;\n\t\tconst glm::vec3 centerDistanceRL = -centerDistanceLR;\n\n\t\tvelocityLhs = velocityLhs - glm::dot(velocityLhs - velocityRhs, centerDistanceLR) \/ magnitudeSqr(centerDistanceLR) * centerDistanceLR;\n\t\tvelocityRhs = velocityRhs - glm::dot(velocityRhs - velocityLhs, centerDistanceRL) \/ magnitudeSqr(centerDistanceRL) * centerDistanceRL;\n\t}\n\n\t\/\/void Geometry::reflectVelocity(glm::vec3& lhs, glm::vec3& rhs)\n\t\/\/{\n\t\/\/\tconst glm::vec3 total = lhs - rhs;\n\t\/\/\tlhs = lhs - total;\n\t\/\/\trhs = lhs + total;\n\t\/\/}\n}\n","avg_line_length":29.3136531365,"max_line_length":136,"alphanum_fraction":0.6560926485,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8330,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n$info$\ntags: LinuxSyscalls|syscalls-x86-32\n$end_info$\n*\/\n\n#include \"Tests\/LinuxSyscalls\/Syscalls.h\"\n#include \"Tests\/LinuxSyscalls\/x32\/Syscalls.h\"\n#include \"Tests\/LinuxSyscalls\/x32\/Types.h\"\n\n#include \"Tests\/LinuxSyscalls\/x64\/Syscalls.h\"\n\n#include <stdint.h>\n#include <syscall.h>\n#include <sys\/stat.h>\n#include <sys\/time.h>\n#include <sys\/timex.h>\n#include <time.h>\n#include <unistd.h>\n#include <utime.h>\n\nARG_TO_STR(FEX::HLE::x32::compat_ptr<FEX::HLE::x32::timespec32>, \"%lx\")\nARG_TO_STR(FEX::HLE::x32::compat_ptr<FEX::HLE::x32::timex32>, \"%lx\")\n\nstruct timespec;\nnamespace FEXCore::Core {\n  struct CpuStateFrame;\n}\n\nnamespace FEX::HLE::x32 {\n  void RegisterTime() {\n\n    REGISTER_SYSCALL_IMPL_X32(time, [](FEXCore::Core::CpuStateFrame *Frame, FEX::HLE::x32::old_time32_t *tloc) -> uint64_t {\n      time_t Host{};\n      uint64_t Result = ::time(&Host);\n\n      if (tloc) {\n        \/\/ On 32-bit this truncates\n        *tloc = (FEX::HLE::x32::old_time32_t)Host;\n      }\n\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(times, [](FEXCore::Core::CpuStateFrame *Frame, struct FEX::HLE::x32::compat_tms *buf) -> uint64_t {\n      struct tms Host{};\n      uint64_t Result = ::times(&Host);\n      if (buf) {\n        *buf = Host;\n      }\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(utime, [](FEXCore::Core::CpuStateFrame *Frame, char* filename, const FEX::HLE::x32::old_utimbuf32* times) -> uint64_t {\n      struct utimbuf Host{};\n      struct utimbuf *Host_p{};\n      if (times) {\n        Host = *times;\n        Host_p = &Host;\n      }\n      uint64_t Result = ::utime(filename, Host_p);\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(gettimeofday, [](FEXCore::Core::CpuStateFrame *Frame, timeval32 *tv, struct timezone *tz) -> uint64_t {\n      struct timeval tv64{};\n      struct timeval *tv_ptr{};\n      if (tv) {\n        tv_ptr = &tv64;\n      }\n\n      uint64_t Result = ::gettimeofday(tv_ptr, tz);\n\n      if (tv) {\n        *tv = tv64;\n      }\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(settimeofday, [](FEXCore::Core::CpuStateFrame *Frame, const timeval32 *tv, const struct timezone *tz) -> uint64_t {\n      struct timeval tv64{};\n      struct timeval *tv_ptr{};\n      if (tv) {\n        tv64 = *tv;\n        tv_ptr = &tv64;\n      }\n\n      const uint64_t Result = ::settimeofday(tv_ptr, tz);\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(nanosleep, [](FEXCore::Core::CpuStateFrame *Frame, const timespec32 *req, timespec32 *rem) -> uint64_t {\n      struct timespec rem64{};\n      struct timespec *rem64_ptr{};\n\n      if (rem) {\n        rem64 = *rem;\n        rem64_ptr = &rem64;\n      }\n\n      uint64_t Result = 0;\n      if (req) {\n        const struct timespec req64 = *req;\n        Result = ::nanosleep(&req64, rem64_ptr);\n      } else {\n        Result = ::nanosleep(nullptr, rem64_ptr);\n      }\n\n      if (rem) {\n        *rem = rem64;\n      }\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(clock_gettime, [](FEXCore::Core::CpuStateFrame *Frame, clockid_t clk_id, timespec32 *tp) -> uint64_t {\n      struct timespec tp64{};\n      uint64_t Result = ::clock_gettime(clk_id, &tp64);\n      if (tp) {\n        *tp = tp64;\n      }\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(clock_getres, [](FEXCore::Core::CpuStateFrame *Frame, clockid_t clk_id, timespec32 *tp) -> uint64_t {\n      struct timespec tp64{};\n      uint64_t Result = ::clock_getres(clk_id, &tp64);\n      if (tp) {\n        *tp = tp64;\n      }\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(clock_nanosleep, [](FEXCore::Core::CpuStateFrame *Frame, clockid_t clockid, int flags, const timespec32 *request, timespec32 *remain) -> uint64_t {\n      struct timespec rem64{};\n      struct timespec *rem64_ptr{};\n\n      if (remain) {\n        rem64 = *remain;\n        rem64_ptr = &rem64;\n      }\n\n      uint64_t Result = 0;\n      if (request) {\n        const struct timespec req64 = *request;\n        Result = ::clock_nanosleep(clockid, flags, &req64, rem64_ptr);\n      } else {\n        Result = ::clock_nanosleep(clockid, flags, nullptr, rem64_ptr);\n      }\n\n      if (remain) {\n        *remain = rem64;\n      }\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(clock_settime, [](FEXCore::Core::CpuStateFrame *Frame, clockid_t clockid, const timespec32 *tp) -> uint64_t {\n      uint64_t Result = 0;\n      if (tp) {\n        const struct timespec tp64 = *tp;\n        Result = ::clock_settime(clockid, &tp64);\n      } else {\n        Result = ::clock_settime(clockid, nullptr);\n      }\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(futimesat, [](FEXCore::Core::CpuStateFrame *Frame, int dirfd, const char *pathname, const timeval32 times[2]) -> uint64_t {\n      uint64_t Result = 0;\n      if (times) {\n        struct timeval times64[2]{};\n        times64[0] = times[0];\n        times64[1] = times[1];\n        Result = ::futimesat(dirfd, pathname, times64);\n      } else {\n        Result = ::futimesat(dirfd, pathname, nullptr);\n      }\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(utimensat, [](FEXCore::Core::CpuStateFrame *Frame, int dirfd, const char *pathname, const compat_ptr<timespec32> times, int flags) -> uint64_t {\n      uint64_t Result = 0;\n      if (times) {\n        timespec times64[2]{};\n        times64[0] = times[0];\n        times64[1] = times[1];\n        Result = ::syscall(SYSCALL_DEF(utimensat), dirfd, pathname, times64, flags);\n      } else {\n        Result = ::syscall(SYSCALL_DEF(utimensat), dirfd, pathname, nullptr, flags);\n      }\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32_PASS_MANUAL(clock_gettime64, clock_gettime, [](FEXCore::Core::CpuStateFrame *Frame, clockid_t clk_id, timespec *tp) -> uint64_t {\n      uint64_t Result = ::clock_gettime(clk_id, tp);\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32_PASS_MANUAL(clock_adjtime64, clock_adjtime, [](FEXCore::Core::CpuStateFrame *Frame, clockid_t clk_id, struct timex *buf) -> uint64_t {\n      uint64_t Result = ::clock_adjtime(clk_id, buf);\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32_PASS_MANUAL(clock_settime64, clock_settime, [](FEXCore::Core::CpuStateFrame *Frame, clockid_t clockid, const struct timespec *tp) -> uint64_t {\n      uint64_t Result = ::clock_settime(clockid, tp);\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32_PASS_MANUAL(clock_getres_time64, clock_getres, [](FEXCore::Core::CpuStateFrame *Frame, clockid_t clk_id, timespec *tp) -> uint64_t {\n      uint64_t Result = ::clock_getres(clk_id, tp);\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32_PASS_MANUAL(clock_nanosleep_time64, clock_nanosleep, [](FEXCore::Core::CpuStateFrame *Frame, clockid_t clockid, int flags, const struct timespec *request, struct timespec *remain) -> uint64_t {\n      uint64_t Result = ::clock_nanosleep(clockid, flags, request, remain);\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32_PASS_MANUAL(utimensat_time64, utimensat, [](FEXCore::Core::CpuStateFrame *Frame, int dirfd, const char *pathname, const struct timespec times[2], int flags) -> uint64_t {\n      uint64_t Result = ::utimensat(dirfd, pathname, times, flags);\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(utimes, [](FEXCore::Core::CpuStateFrame *Frame, const char *filename, const timeval32 times[2]) -> uint64_t {\n      uint64_t Result = 0;\n      if (times) {\n        struct timeval times64[2]{};\n        times64[0] = times[0];\n        times64[1] = times[1];\n        Result = ::utimes(filename, times64);\n      } else {\n        Result = ::utimes(filename, nullptr);\n      }\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(adjtimex, [](FEXCore::Core::CpuStateFrame *Frame, compat_ptr<FEX::HLE::x32::timex32> buf) -> uint64_t {\n      struct timex Host{};\n      Host = *buf;\n      uint64_t Result = ::adjtimex(&Host);\n      if (Result != -1) {\n        *buf = Host;\n      }\n      SYSCALL_ERRNO();\n    });\n\n    REGISTER_SYSCALL_IMPL_X32(clock_adjtime, [](FEXCore::Core::CpuStateFrame *Frame, clockid_t clk_id, compat_ptr<FEX::HLE::x32::timex32> buf) -> uint64_t {\n      struct timex Host{};\n      Host = *buf;\n      uint64_t Result = ::clock_adjtime(clk_id, &Host);\n      if (Result != -1) {\n        *buf = Host;\n      }\n      SYSCALL_ERRNO();\n    });\n  }\n}\n","avg_line_length":32.4124513619,"max_line_length":223,"alphanum_fraction":0.6236494598,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8920,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <memory>\n#include <vector>\n\n#include \"benchmark\/benchmark.h\"\n#include \"common\/strong_typedef.h\"\n#include \"storage\/data_table.h\"\n#include \"storage\/storage_util.h\"\n#include \"transaction\/transaction_context.h\"\n#include \"transaction\/transaction_manager.h\"\n#include \"util\/storage_test_util.h\"\n#include \"util\/test_thread_pool.h\"\n\nnamespace terrier {\n\n\/\/ This benchmark simulates a key-value store inserting a large number of tuples. This provides a good baseline and\n\/\/ reference to other fast data structures (indexes) to compare against. We are interested in the DataTable's raw\n\/\/ performance, so the tuple's contents are intentionally left garbage and we don't verify correctness. That's the job\n\/\/ of the Google Tests.\n\nclass DataTableBenchmark : public benchmark::Fixture {\n public:\n  void SetUp(const benchmark::State &state) final {\n    \/\/ generate a random redo ProjectedRow to Insert\n    redo_buffer_ = common::AllocationUtil::AllocateAligned(initializer_.ProjectedRowSize());\n    redo_ = initializer_.InitializeRow(redo_buffer_);\n    StorageTestUtil::PopulateRandomRow(redo_, layout_, 0, &generator_);\n\n    \/\/ generate a ProjectedRow buffer to Read\n    read_buffer_ = common::AllocationUtil::AllocateAligned(initializer_.ProjectedRowSize());\n    read_ = initializer_.InitializeRow(read_buffer_);\n\n    \/\/ generate a vector of ProjectedRow buffers for concurrent reads\n    for (uint32_t i = 0; i < num_threads_; ++i) {\n      \/\/ Create read buffer\n      byte *read_buffer = common::AllocationUtil::AllocateAligned(initializer_.ProjectedRowSize());\n      storage::ProjectedRow *read = initializer_.InitializeRow(read_buffer);\n      read_buffers_.emplace_back(read_buffer);\n      reads_.emplace_back(read);\n    }\n  }\n\n  void TearDown(const benchmark::State &state) final {\n    delete[] redo_buffer_;\n    delete[] read_buffer_;\n    for (uint32_t i = 0; i < num_threads_; ++i) delete[] read_buffers_[i];\n    \/\/ google benchmark might run benchmark several iterations. We need to clear vectors.\n    read_buffers_.clear();\n    reads_.clear();\n  }\n\n  \/\/ Tuple layout\n  const uint8_t column_size_ = 8;\n  const storage::BlockLayout layout_{{column_size_, column_size_, column_size_}};\n\n  \/\/ Tuple properties\n  const storage::ProjectedRowInitializer initializer_{layout_, StorageTestUtil::ProjectionListAllColumns(layout_)};\n\n  \/\/ Workload\n  const uint32_t num_inserts_ = 10000000;\n  const uint32_t num_reads_ = 10000000;\n  const uint32_t num_threads_ = 4;\n  const uint64_t buffer_pool_reuse_limit_ = 10000000;\n\n  \/\/ Test infrastructure\n  std::default_random_engine generator_;\n  storage::BlockStore block_store_{1000, 1000};\n  storage::RecordBufferSegmentPool buffer_pool_{num_inserts_, buffer_pool_reuse_limit_};\n\n  \/\/ Insert buffer pointers\n  byte *redo_buffer_;\n  storage::ProjectedRow *redo_;\n\n  \/\/ Read buffer pointers;\n  byte *read_buffer_;\n  storage::ProjectedRow *read_;\n\n  \/\/ Read buffers pointers for concurrent reads\n  std::vector<byte *> read_buffers_;\n  std::vector<storage::ProjectedRow *> reads_;\n};\n\n\/\/ Insert the num_inserts_ of tuples into a DataTable in a single thread\n\/\/ NOLINTNEXTLINE\nBENCHMARK_DEFINE_F(DataTableBenchmark, SimpleInsert)(benchmark::State &state) {\n  \/\/ NOLINTNEXTLINE\n  for (auto _ : state) {\n    storage::DataTable table(&block_store_, layout_, storage::layout_version_t(0));\n    \/\/ We can use dummy timestamps here since we're not invoking concurrency control\n    transaction::TransactionContext txn(transaction::timestamp_t(0), transaction::timestamp_t(0), &buffer_pool_,\n                                        LOGGING_DISABLED);\n    for (uint32_t i = 0; i < num_inserts_; ++i) {\n      table.Insert(&txn, *redo_);\n    }\n  }\n\n  state.SetItemsProcessed(state.iterations() * num_inserts_);\n}\n\n\/\/ Insert the num_inserts_ of tuples into a DataTable concurrently\n\/\/ NOLINTNEXTLINE\nBENCHMARK_DEFINE_F(DataTableBenchmark, ConcurrentInsert)(benchmark::State &state) {\n  TestThreadPool thread_pool;\n  \/\/ NOLINTNEXTLINE\n  for (auto _ : state) {\n    storage::DataTable table(&block_store_, layout_, storage::layout_version_t(0));\n    auto workload = [&](uint32_t id) {\n      \/\/ We can use dummy timestamps here since we're not invoking concurrency control\n      transaction::TransactionContext txn(transaction::timestamp_t(0), transaction::timestamp_t(0), &buffer_pool_,\n                                          LOGGING_DISABLED);\n      for (uint32_t i = 0; i < num_inserts_ \/ num_threads_; i++) table.Insert(&txn, *redo_);\n    };\n    thread_pool.RunThreadsUntilFinish(num_threads_, workload);\n  }\n\n  state.SetItemsProcessed(state.iterations() * num_inserts_);\n}\n\n\/\/ Read the num_reads_ of tuples in a sequential order from a DataTable in a single thread\n\/\/ NOLINTNEXTLINE\nBENCHMARK_DEFINE_F(DataTableBenchmark, SequentialRead)(benchmark::State &state) {\n  storage::DataTable read_table(&block_store_, layout_, storage::layout_version_t(0));\n  \/\/ Populate read_table by inserting tuples\n  \/\/ We can use dummy timestamps here since we're not invoking concurrency control\n  transaction::TransactionContext txn(transaction::timestamp_t(0), transaction::timestamp_t(0), &buffer_pool_,\n                                      LOGGING_DISABLED);\n  std::vector<storage::TupleSlot> read_order;\n  for (uint32_t i = 0; i < num_reads_; ++i) {\n    read_order.emplace_back(read_table.Insert(&txn, *redo_));\n  }\n  \/\/ NOLINTNEXTLINE\n  for (auto _ : state) {\n    for (uint32_t i = 0; i < num_reads_; ++i) {\n      read_table.Select(&txn, read_order[i], read_);\n    }\n  }\n\n  state.SetItemsProcessed(state.iterations() * num_reads_);\n}\n\n\/\/ Read the num_reads_ of tuples in a random order from a DataTable in a single thread\n\/\/ NOLINTNEXTLINE\nBENCHMARK_DEFINE_F(DataTableBenchmark, RandomRead)(benchmark::State &state) {\n  storage::DataTable read_table(&block_store_, layout_, storage::layout_version_t(0));\n  \/\/ Populate read_table_ by inserting tuples\n  \/\/ We can use dummy timestamps here since we're not invoking concurrency control\n  transaction::TransactionContext txn(transaction::timestamp_t(0), transaction::timestamp_t(0), &buffer_pool_,\n                                      LOGGING_DISABLED);\n  std::vector<storage::TupleSlot> read_order;\n  for (uint32_t i = 0; i < num_reads_; ++i) {\n    read_order.emplace_back(read_table.Insert(&txn, *redo_));\n  }\n  \/\/ Create random reads\n  std::shuffle(read_order.begin(), read_order.end(), generator_);\n  \/\/ NOLINTNEXTLINE\n  for (auto _ : state) {\n    for (uint32_t i = 0; i < num_reads_; ++i) {\n      read_table.Select(&txn, read_order[i], read_);\n    }\n  }\n\n  state.SetItemsProcessed(state.iterations() * num_reads_);\n}\n\n\/\/ Read the num_reads_ of tuples in a random order from a DataTable concurrently\n\/\/ NOLINTNEXTLINE\nBENCHMARK_DEFINE_F(DataTableBenchmark, ConcurrentRandomRead)(benchmark::State &state) {\n  TestThreadPool thread_pool;\n  storage::DataTable read_table(&block_store_, layout_, storage::layout_version_t(0));\n  \/\/ populate read_table_ by inserting tuples\n  \/\/ We can use dummy timestamps here since we're not invoking concurrency control\n  transaction::TransactionContext txn(transaction::timestamp_t(0), transaction::timestamp_t(0), &buffer_pool_,\n                                      LOGGING_DISABLED);\n  std::vector<storage::TupleSlot> read_order;\n  for (uint32_t i = 0; i < num_reads_; ++i) {\n    read_order.emplace_back(read_table.Insert(&txn, *redo_));\n  }\n  \/\/ Generate random read orders and read buffer for each thread\n  std::shuffle(read_order.begin(), read_order.end(), generator_);\n  std::uniform_int_distribution<uint32_t> rand_start(0, static_cast<uint32_t>(read_order.size() - 1));\n  std::vector<uint32_t> rand_read_offsets;\n  for (uint32_t i = 0; i < num_threads_; ++i) {\n    \/\/ Create random reads\n    rand_read_offsets.emplace_back(rand_start(generator_));\n  }\n  \/\/ NOLINTNEXTLINE\n  for (auto _ : state) {\n    auto workload = [&](uint32_t id) {\n      \/\/ We can use dummy timestamps here since we're not invoking concurrency control\n      transaction::TransactionContext txn(transaction::timestamp_t(0), transaction::timestamp_t(0), &buffer_pool_,\n                                          LOGGING_DISABLED);\n      for (uint32_t i = 0; i < num_reads_ \/ num_threads_; i++)\n        read_table.Select(&txn, read_order[(rand_read_offsets[id] + i) % read_order.size()], reads_[id]);\n    };\n    thread_pool.RunThreadsUntilFinish(num_threads_, workload);\n  }\n\n  state.SetItemsProcessed(state.iterations() * num_reads_);\n}\n\nBENCHMARK_REGISTER_F(DataTableBenchmark, SimpleInsert)->Unit(benchmark::kMillisecond);\n\nBENCHMARK_REGISTER_F(DataTableBenchmark, ConcurrentInsert)->Unit(benchmark::kMillisecond)->UseRealTime();\n\nBENCHMARK_REGISTER_F(DataTableBenchmark, SequentialRead)->Unit(benchmark::kMillisecond);\n\nBENCHMARK_REGISTER_F(DataTableBenchmark, RandomRead)->Unit(benchmark::kMillisecond);\n\nBENCHMARK_REGISTER_F(DataTableBenchmark, ConcurrentRandomRead)->Unit(benchmark::kMillisecond)->UseRealTime();\n}  \/\/ namespace terrier\n","avg_line_length":42.4761904762,"max_line_length":118,"alphanum_fraction":0.7286995516,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2037,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/===----------------------------------------------------------------------===\/\/\r\n\/\/\r\n\/\/                         BusTub\r\n\/\/\r\n\/\/ seq_scan_executor.cpp\r\n\/\/\r\n\/\/ Identification: src\/execution\/seq_scan_executor.cpp\r\n\/\/\r\n\/\/ Copyright (c) 2015-2021, Carnegie Mellon University Database Group\r\n\/\/\r\n\/\/===----------------------------------------------------------------------===\/\/\r\n\r\n#include \"execution\/executors\/seq_scan_executor.h\"\r\n\r\nnamespace bustub {\r\n\r\nSeqScanExecutor::SeqScanExecutor(ExecutorContext *exec_ctx, const SeqScanPlanNode *plan) : AbstractExecutor(exec_ctx),plan_(plan) {}\r\n\r\nvoid SeqScanExecutor::Init() {\r\n    auto *bpm = exec_ctx_->GetBufferPoolManager();\r\n    auto table_id = plan_->GetTableOid();\r\n    auto *table_info = GetExecutorContext()->GetCatalog()->GetTable(table_id);\r\n    auto *meta = table_info->table_.get();\r\n    auto first_page_id = meta->GetFirstPageId();\r\n    page_ = static_cast<TablePage *>(bpm->FetchPage(first_page_id));\r\n    RID *rid = new RID();\r\n    page_->GetFirstTupleRid(rid);\r\n    cur_rid = rid;\r\n}\r\n\/\/\u52a0\u4e0a\u6709index\u7684\u60c5\u51b5\uff0c\u5373\u6709where\u5b50\u53e5\u6216\u8005\u5176\u4ed6\u5224\u65ad\u65f6\uff0c\u68c0\u67e5where\u5b50\u53e5\u4e2d\u7684\u5224\u65ad\u6761\u4ef6\u662f\u5426\u6709\u5bf9\u5e94\u7684\u7d22\u5f15\uff0c\u7136\u540e\u6839\u636e\u7d22\u5f15\u627e\u5230\r\n\/\/\u5bf9\u5e94tuple\uff0c\u800c\u4e0d\u662f\u76f4\u63a5\u904d\u5386\u30023.\r\nbool SeqScanExecutor::Next(Tuple *tuple, RID *rid) {\r\n     if (page_->GetTuple(*cur_rid,tuple,exec_ctx_->GetTransaction(),exec_ctx_->GetLockManager())){\r\n         if(!page_->GetNextTupleRid(*cur_rid,rid)) {\r\n             auto next_page_id = page_->GetNextPageId();\r\n             auto *bpm = exec_ctx_->GetBufferPoolManager();\r\n             bpm->UnpinPage(page_->GetPageId(), false);\r\n             page_ = static_cast<TablePage *>(bpm->FetchPage(next_page_id));\r\n             rid->Set(next_page_id,0);\r\n         }\r\n         cur_rid = rid;\r\n         auto predicate = plan_->GetPredicate();\r\n         if (predicate == nullptr)  return true;\r\n         if ( predicate->Evaluate(tuple,plan_->OutputSchema()).ToString() == \"false\"){\r\n\r\n             if(Next(tuple, rid)) return true;\r\n             else return false;\r\n         }\r\n         return true;\r\n     }\r\n    \r\n    return false; \r\n}\r\n\r\n}  \/\/ namespace bustub\r\n","avg_line_length":36.375,"max_line_length":133,"alphanum_fraction":0.5797741777,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10606,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":13885.0,"content":"\/\/ Copyright (c) 2021 Mostafa Ashraf\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"source\/fuzz\/transformation_swap_function_variables.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"source\/fuzz\/fuzzer_util.h\"\n#include \"source\/fuzz\/instruction_descriptor.h\"\n#include \"test\/fuzz\/fuzz_test_util.h\"\n\nnamespace spvtools {\nnamespace fuzz {\nnamespace {\n\nTEST(TransformationSwapFunctionVariables, NotApplicable) {\n  std::string shader = R\"(\n               OpCapability Shader\n          %1 = OpExtInstImport \"GLSL.std.450\"\n               OpMemoryModel Logical GLSL450\n               OpEntryPoint Fragment %4 \"main\"\n               OpExecutionMode %4 OriginUpperLeft\n               OpSource ESSL 320\n          %2 = OpTypeVoid\n          %3 = OpTypeFunction %2\n          %6 = OpTypeInt 32 1\n          %7 = OpTypePointer Function %6\n          %8 = OpTypeFloat 32\n          %9 = OpTypePointer Function %8\n         %10 = OpTypeVector %8 2\n         %11 = OpTypePointer Function %10\n         %12 = OpTypeVector %8 3\n         %13 = OpTypeMatrix %12 3\n         %14 = OpTypePointer Function %13\n         %15 = OpTypeFunction %2 %7 %9 %11 %14 %7 %7\n          %4 = OpFunction %2 None %3\n          %5 = OpLabel\n         %24 = OpVariable %7 Function\n         %25 = OpVariable %9 Function\n         %26 = OpVariable %11 Function\n         %27 = OpVariable %14 Function\n         %28 = OpVariable %7 Function\n         %29 = OpVariable %7 Function\n         %30 = OpVariable %7 Function\n         %32 = OpVariable %9 Function\n         %34 = OpVariable %11 Function\n         %36 = OpVariable %14 Function\n         %38 = OpVariable %7 Function\n         %40 = OpVariable %7 Function\n         %31 = OpLoad %6 %24\n               OpStore %30 %31\n         %33 = OpLoad %8 %25\n               OpStore %32 %33\n         %35 = OpLoad %10 %26\n               OpStore %34 %35\n         %37 = OpLoad %13 %27\n               OpStore %36 %37\n         %39 = OpLoad %6 %28\n               OpStore %38 %39\n         %41 = OpLoad %6 %29\n               OpStore %40 %41\n         %42 = OpFunctionCall %2 %22 %30 %32 %34 %36 %38 %40\n               OpReturn\n               OpFunctionEnd\n         %22 = OpFunction %2 None %15\n         %16 = OpFunctionParameter %7\n         %17 = OpFunctionParameter %9\n         %18 = OpFunctionParameter %11\n         %19 = OpFunctionParameter %14\n         %20 = OpFunctionParameter %7\n         %21 = OpFunctionParameter %7\n         %23 = OpLabel\n               OpReturn\n               OpFunctionEnd\n)\";\n\n  const auto env = SPV_ENV_UNIVERSAL_1_5;\n  const auto consumer = nullptr;\n  const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);\n  spvtools::ValidatorOptions validator_options;\n\n  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,\n                                               kConsoleMessageConsumer));\n  TransformationContext transformation_context(\n      MakeUnique<FactManager>(context.get()), validator_options);\n\n#ifndef NDEBUG\n  \/\/ Can't swap variable with itself.\n  ASSERT_DEATH(TransformationSwapFunctionVariables(7, 7).IsApplicable(\n                   context.get(), transformation_context),\n               \"Two results ids are equal\");\n#endif\n\n  \/\/ Invalid because 200 is not the id of an instruction.\n  ASSERT_FALSE(TransformationSwapFunctionVariables(1, 200).IsApplicable(\n      context.get(), transformation_context));\n  \/\/ Invalid because 5 is not the id of an instruction.\n  ASSERT_FALSE(TransformationSwapFunctionVariables(5, 24).IsApplicable(\n      context.get(), transformation_context));\n  \/\/ Can't swap two instructions from two different blocks.\n  ASSERT_FALSE(TransformationSwapFunctionVariables(16, 26).IsApplicable(\n      context.get(), transformation_context));\n}\n\nTEST(TransformationSwapFunctionVariables, IsApplicable) {\n  std::string shader = R\"(\n               OpCapability Shader\n          %1 = OpExtInstImport \"GLSL.std.450\"\n               OpMemoryModel Logical GLSL450\n               OpEntryPoint Fragment %4 \"main\"\n               OpExecutionMode %4 OriginUpperLeft\n               OpSource ESSL 320\n          %2 = OpTypeVoid\n          %3 = OpTypeFunction %2\n          %6 = OpTypeInt 32 1\n          %7 = OpTypePointer Function %6\n          %8 = OpTypeFloat 32\n          %9 = OpTypePointer Function %8\n         %10 = OpTypeVector %8 2\n         %11 = OpTypePointer Function %10\n         %12 = OpTypeVector %8 3\n         %13 = OpTypeMatrix %12 3\n         %14 = OpTypePointer Function %13\n         %15 = OpTypeFunction %2 %7 %9 %11 %14 %7 %7\n          %4 = OpFunction %2 None %3\n          %5 = OpLabel\n         %24 = OpVariable %7 Function\n         %25 = OpVariable %9 Function\n         %26 = OpVariable %11 Function\n         %27 = OpVariable %14 Function\n         %28 = OpVariable %7 Function\n         %29 = OpVariable %7 Function\n         %30 = OpVariable %7 Function\n         %32 = OpVariable %9 Function\n         %34 = OpVariable %11 Function\n         %36 = OpVariable %14 Function\n         %38 = OpVariable %7 Function\n         %40 = OpVariable %7 Function\n         %31 = OpLoad %6 %24\n               OpStore %30 %31\n         %33 = OpLoad %8 %25\n               OpStore %32 %33\n         %35 = OpLoad %10 %26\n               OpStore %34 %35\n         %37 = OpLoad %13 %27\n               OpStore %36 %37\n         %39 = OpLoad %6 %28\n               OpStore %38 %39\n         %41 = OpLoad %6 %29\n               OpStore %40 %41\n         %42 = OpFunctionCall %2 %22 %30 %32 %34 %36 %38 %40\n               OpReturn\n               OpFunctionEnd\n         %22 = OpFunction %2 None %15\n         %16 = OpFunctionParameter %7\n         %17 = OpFunctionParameter %9\n         %18 = OpFunctionParameter %11\n         %19 = OpFunctionParameter %14\n         %20 = OpFunctionParameter %7\n         %21 = OpFunctionParameter %7\n         %23 = OpLabel\n               OpReturn\n               OpFunctionEnd\n)\";\n\n  const auto env = SPV_ENV_UNIVERSAL_1_5;\n  const auto consumer = nullptr;\n  \/\/ Get Unique pointer of IRContext.\n  const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);\n  spvtools::ValidatorOptions validator_options;\n\n  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,\n                                               kConsoleMessageConsumer));\n  TransformationContext transformation_context(\n      MakeUnique<FactManager>(context.get()), validator_options);\n\n  \/\/ Successful transformations\n  {\n    auto first_instruction = context->get_def_use_mgr()->GetDef(24);\n    auto second_instruction = context->get_def_use_mgr()->GetDef(28);\n    \/\/ Swap two OpVariable instructions in the same function.\n    TransformationSwapFunctionVariables transformation(24, 28);\n\n    ASSERT_TRUE(\n        transformation.IsApplicable(context.get(), transformation_context));\n\n    ApplyAndCheckFreshIds(transformation, context.get(),\n                          &transformation_context);\n\n    ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(\n        context.get(), validator_options, kConsoleMessageConsumer));\n\n    ASSERT_EQ(first_instruction, context->get_def_use_mgr()->GetDef(24));\n    ASSERT_EQ(second_instruction, context->get_def_use_mgr()->GetDef(28));\n  }\n  {\n    auto first_instruction = context->get_def_use_mgr()->GetDef(38);\n    auto second_instruction = context->get_def_use_mgr()->GetDef(40);\n    \/\/ Swap two OpVariable instructions in the same function.\n    TransformationSwapFunctionVariables transformation(38, 40);\n\n    ASSERT_TRUE(\n        transformation.IsApplicable(context.get(), transformation_context));\n\n    ApplyAndCheckFreshIds(transformation, context.get(),\n                          &transformation_context);\n\n    ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(\n        context.get(), validator_options, kConsoleMessageConsumer));\n\n    ASSERT_EQ(first_instruction, context->get_def_use_mgr()->GetDef(38));\n    ASSERT_EQ(second_instruction, context->get_def_use_mgr()->GetDef(40));\n  }\n  std::string after_transformation = R\"(\n               OpCapability Shader\n          %1 = OpExtInstImport \"GLSL.std.450\"\n               OpMemoryModel Logical GLSL450\n               OpEntryPoint Fragment %4 \"main\"\n               OpExecutionMode %4 OriginUpperLeft\n               OpSource ESSL 320\n          %2 = OpTypeVoid\n          %3 = OpTypeFunction %2\n          %6 = OpTypeInt 32 1\n          %7 = OpTypePointer Function %6\n          %8 = OpTypeFloat 32\n          %9 = OpTypePointer Function %8\n         %10 = OpTypeVector %8 2\n         %11 = OpTypePointer Function %10\n         %12 = OpTypeVector %8 3\n         %13 = OpTypeMatrix %12 3\n         %14 = OpTypePointer Function %13\n         %15 = OpTypeFunction %2 %7 %9 %11 %14 %7 %7\n          %4 = OpFunction %2 None %3\n          %5 = OpLabel\n         %28 = OpVariable %7 Function\n         %25 = OpVariable %9 Function\n         %26 = OpVariable %11 Function\n         %27 = OpVariable %14 Function\n         %24 = OpVariable %7 Function\n         %29 = OpVariable %7 Function\n         %30 = OpVariable %7 Function\n         %32 = OpVariable %9 Function\n         %34 = OpVariable %11 Function\n         %36 = OpVariable %14 Function\n         %40 = OpVariable %7 Function\n         %38 = OpVariable %7 Function\n         %31 = OpLoad %6 %24\n               OpStore %30 %31\n         %33 = OpLoad %8 %25\n               OpStore %32 %33\n         %35 = OpLoad %10 %26\n               OpStore %34 %35\n         %37 = OpLoad %13 %27\n               OpStore %36 %37\n         %39 = OpLoad %6 %28\n               OpStore %38 %39\n         %41 = OpLoad %6 %29\n               OpStore %40 %41\n         %42 = OpFunctionCall %2 %22 %30 %32 %34 %36 %38 %40\n               OpReturn\n               OpFunctionEnd\n         %22 = OpFunction %2 None %15\n         %16 = OpFunctionParameter %7\n         %17 = OpFunctionParameter %9\n         %18 = OpFunctionParameter %11\n         %19 = OpFunctionParameter %14\n         %20 = OpFunctionParameter %7\n         %21 = OpFunctionParameter %7\n         %23 = OpLabel\n               OpReturn\n               OpFunctionEnd\n)\";\n  ASSERT_TRUE(IsEqual(env, after_transformation, context.get()));\n}\n\n}  \/\/ namespace\n}  \/\/ namespace fuzz\n}  \/\/ namespace spvtools\n","avg_line_length":36.6989619377,"max_line_length":80,"alphanum_fraction":0.5985291345,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2276,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include <boost\/program_options.hpp>\n\nusing namespace boost;\nnamespace po = boost::program_options;\n\n#include <iostream>\n#include <algorithm>\n#include <iterator>\nusing namespace std;\n\n\n\/\/ A helper function to simplify the main part.\ntemplate<class T>\nostream& operator<<(ostream& os, const vector<T>& v)\n{\n    copy(v.begin(), v.end(), ostream_iterator<T>(os, \" \"));\n    return os;\n}\n\nint main(int ac, char* av[])\n{\n    try {\n        int opt;\n        int portnum;\n        po::options_description desc(\"Allowed options\");\n        desc.add_options()\n            (\"help\", \"produce help message\")\n            (\"optimization\", po::value<int>(&opt)->default_value(10),\n                  \"optimization level\")\n            (\"verbose,v\", po::value<int>()->implicit_value(1),\n                  \"enable verbosity (optionally specify level)\")\n            (\"listen,l\", po::value<int>(&portnum)->implicit_value(1001)\n                  ->default_value(0,\"no\"),\n                  \"listen on a port.\")\n            (\"include-path,I\", po::value< vector<string> >(),\n                  \"include path\")\n            (\"input-file\", po::value< vector<string> >(), \"input file\")\n        ;\n\n        po::positional_options_description p;\n        p.add(\"input-file\", -1);\n\n        po::variables_map vm;\n        po::store(po::command_line_parser(ac, av).\n                  options(desc).positional(p).run(), vm);\n        po::notify(vm);\n\n        if (vm.count(\"help\")) {\n            cout << \"Usage: options_description [options]\\n\";\n            cout << desc;\n            return 0;\n        }\n\n        if (vm.count(\"include-path\"))\n        {\n            cout << \"Include paths are: \"\n                 << vm[\"include-path\"].as< vector<string> >() << \"\\n\";\n        }\n\n        if (vm.count(\"input-file\"))\n        {\n            cout << \"Input files are: \"\n                 << vm[\"input-file\"].as< vector<string> >() << \"\\n\";\n        }\n\n        if (vm.count(\"verbose\")) {\n            cout << \"Verbosity enabled.  Level is \" << vm[\"verbose\"].as<int>()\n                 << \"\\n\";\n        }\n\n        cout << \"Optimization level is \" << opt << \"\\n\";\n\n        cout << \"Listen port is \" << portnum << \"\\n\";\n    }\n    catch(std::exception& e)\n    {\n        cout << e.what() << \"\\n\";\n        return 1;\n    }\n    return 0;\n}\n","avg_line_length":27.756097561,"max_line_length":78,"alphanum_fraction":0.4995606327,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3408,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright \u00a9 Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root\n\/\/ for more information.\n\n#include <NovelRT.Interop\/Ecs\/NrtEcs.h>\n#include <NovelRT.h>\n#include <atomic>\n#include <gtest\/gtest.h>\n\nusing namespace NovelRT;\nusing namespace NovelRT::Ecs;\nusing namespace NovelRT::Timing;\n\nclass InteropSystemSchedulerTest : public testing::Test\n{\npublic:\n    NrtSystemScheduler scheduler = nullptr;\n    std::atomic_bool sysOneBool = true;\n    std::atomic_bool sysTwoBool = true;\n    std::atomic_bool sysThreeBool = true;\n    std::function<void(Timestamp, Catalogue)> sysOne;\n    std::function<void(Timestamp, Catalogue)> sysTwo;\n    std::function<void(Timestamp, Catalogue)> sysThree;\n\nprotected:\n    void SetUp() override\n    {\n        sysOneBool = true;\n        sysTwoBool = true;\n        sysThreeBool = true;\n\n        if (scheduler == nullptr)\n        {\n            auto cppScheduler = new SystemScheduler();\n\n            cppScheduler->SpinThreads();\n\n            sysOne = [&](Timestamp delta, Catalogue) { sysOneBool = false; };\n            sysTwo = [&](Timestamp delta, Catalogue) { sysTwoBool = false; };\n            sysThree = [&](Timestamp delta, Catalogue) { sysThreeBool = false; };\n\n            cppScheduler->RegisterSystem(sysOne);\n            cppScheduler->RegisterSystem(sysTwo);\n            cppScheduler->RegisterSystem(sysThree);\n            scheduler = reinterpret_cast<NrtSystemScheduler>(cppScheduler);\n        }\n    }\n\n    void TearDown() override\n    {\n        if (scheduler != nullptr)\n        {\n            Nrt_SystemScheduler_Destroy(scheduler);\n            scheduler = nullptr;\n        }\n    }\n};\n\nTEST_F(InteropSystemSchedulerTest, IndependentSystemsCanRun)\n{\n    EXPECT_EQ(Nrt_SystemScheduler_ExecuteIteration(scheduler, 0), NRT_SUCCESS);\n}\n\nTEST_F(InteropSystemSchedulerTest, IndependentSystemsCanModifyValues)\n{\n    ASSERT_EQ(Nrt_SystemScheduler_ExecuteIteration(scheduler, 0), NRT_SUCCESS);\n\n    EXPECT_FALSE(sysOneBool);\n    EXPECT_FALSE(sysTwoBool);\n    EXPECT_FALSE(sysThreeBool);\n}\n\nTEST_F(InteropSystemSchedulerTest, IndependentSystemsObtainValidCatalogue)\n{\n    EntityId entity = Atom::getNextEntityId();\n\n    auto cache = Nrt_SystemScheduler_GetComponentCache(scheduler);\n    reinterpret_cast<SystemScheduler*>(scheduler)->GetComponentCache().RegisterComponentType<int32_t>(-1);\n\n    NrtComponentBufferMemoryContainer container = nullptr;\n    ASSERT_EQ(Nrt_ComponentCache_GetComponentBufferById(cache, GetComponentTypeId<int32_t>(), &container), NRT_SUCCESS);\n\n    int32_t data = 10;\n    Nrt_ComponentBufferMemoryContainer_PushComponentUpdateInstruction(container, 0, entity, &data);\n\n    ASSERT_EQ(Nrt_SystemScheduler_ExecuteIteration(scheduler, 0), NRT_SUCCESS);\n\n    Nrt_SystemScheduler_RegisterSystem(scheduler, [](auto delta, auto catalogue) {\n        auto intSystem = reinterpret_cast<Catalogue*>(catalogue)->GetComponentView<int32_t>();\n\n        for (auto [entity, component] : intSystem)\n        {\n            intSystem.PushComponentUpdateInstruction(entity, 10);\n        }\n    });\n\n    ASSERT_EQ(Nrt_SystemScheduler_ExecuteIteration(scheduler, 0), NRT_SUCCESS);\n    ASSERT_EQ(Nrt_SystemScheduler_ExecuteIteration(scheduler, 0), NRT_SUCCESS);\n    EXPECT_EQ(\n        reinterpret_cast<SystemScheduler*>(scheduler)->GetComponentCache().GetComponentBuffer<int32_t>().GetComponent(\n            entity),\n        20);\n}","avg_line_length":33.4117647059,"max_line_length":120,"alphanum_fraction":0.7074530516,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":688,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":4.0,"content":"#include <cstdio>\n#include <iostream>\nusing namespace std;\n\nint N, M;\nint IT[300001];\nint find(int s, int e, int S, int E, int p) {\n\tif (s > E || e < S) return 1e9;\n\tif (s >= S && e <= E) return IT[p];\n\treturn min(find(s, (s+e)\/2, S, E, p*2), find((s+e)\/2+1, e, S, E, p*2+1));\n}\nint main() {\n\tscanf(\"%d %d\", &N, &M);\n\tfor (int i = 0; i < 300001; i++) IT[i] = 1e9;\n\n\tint P = 1;\n\twhile (P < N) P *= 2;\n\n\tfor (int i = P; i < P + N; i++) {\n\t\tscanf(\"%d\", &IT[i]);\n\n\t\tint curr = i;\n\t\twhile (curr \/ 2 > 1) {\n\t\t\tIT[curr\/2] = min(IT[curr\/2], IT[curr]);\n\t\t\tcurr \/= 2;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < M; i++) {\n\t\tint a, b; scanf(\"%d %d\", &a, &b);\n\t\tprintf(\"%d\\n\", find(1, P, a, b, 1));\n\t}\n\treturn 0;\n}\n","avg_line_length":19.6571428571,"max_line_length":74,"alphanum_fraction":0.4680232558,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1802,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2009-2014 The Alphapay Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"config\/bitcoin-config.h\"\n#endif\n\n#include <cstddef>\n\n#if defined(HAVE_SYS_SELECT_H)\n#include <sys\/select.h>\n#endif\n\nextern \"C\" void* memcpy(void* a, const void* b, size_t c);\nvoid* memcpy_int(void* a, const void* b, size_t c)\n{\n    return memcpy(a, b, c);\n}\n\nnamespace\n{\n\/\/ trigger: Use the memcpy_int wrapper which calls our internal memcpy.\n\/\/   A direct call to memcpy may be optimized away by the compiler.\n\/\/ test: Fill an array with a sequence of integers. memcpy to a new empty array.\n\/\/   Verify that the arrays are equal. Use an odd size to decrease the odds of\n\/\/   the call being optimized away.\ntemplate <unsigned int T>\nbool sanity_test_memcpy()\n{\n    unsigned int memcpy_test[T];\n    unsigned int memcpy_verify[T] = {};\n    for (unsigned int i = 0; i != T; ++i)\n        memcpy_test[i] = i;\n\n    memcpy_int(memcpy_verify, memcpy_test, sizeof(memcpy_test));\n\n    for (unsigned int i = 0; i != T; ++i) {\n        if (memcpy_verify[i] != i)\n            return false;\n    }\n    return true;\n}\n\n#if defined(HAVE_SYS_SELECT_H)\n\/\/ trigger: Call FD_SET to trigger __fdelt_chk. FORTIFY_SOURCE must be defined\n\/\/   as >0 and optimizations must be set to at least -O2.\n\/\/ test: Add a file descriptor to an empty fd_set. Verify that it has been\n\/\/   correctly added.\nbool sanity_test_fdelt()\n{\n    fd_set fds;\n    FD_ZERO(&fds);\n    FD_SET(0, &fds);\n    return FD_ISSET(0, &fds);\n}\n#endif\n\n} \/\/ anon namespace\n\nbool glibc_sanity_test()\n{\n#if defined(HAVE_SYS_SELECT_H)\n    if (!sanity_test_fdelt())\n        return false;\n#endif\n    return sanity_test_memcpy<1025>();\n}\n","avg_line_length":26.115942029,"max_line_length":80,"alphanum_fraction":0.6892341842,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":756,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) Microsoft Corporation. All rights reserved.\r\n\/\/ Licensed under the MIT License.\r\n\r\n#include \"pch.h\"\r\n#include \"ReactInstance.h\"\r\n#if __has_include(\"Bridge.ReactInstance.g.cpp\")\r\n#include \"Bridge.ReactInstance.g.cpp\"\r\n#endif\r\n\r\n#include \"ReactSupport.h\"\r\n\r\nnamespace winrt::Microsoft::ReactNative::Bridge::implementation {\r\nvoid ReactInstance::InvokeFunction(\r\n    hstring const &moduleName,\r\n    hstring const &method,\r\n    IVectorView<IInspectable> const &arguments) {\r\n  folly::dynamic args =\r\n      Microsoft::ReactNative::Bridge::ConvertToDynamic(arguments);\r\n\r\n  m_instance->CallJsFunction(\r\n      to_string(moduleName), to_string(method), std::move(args));\r\n}\r\n\r\n} \/\/ namespace winrt::Microsoft::ReactNative::Bridge::implementation\r\n","avg_line_length":30.24,"max_line_length":69,"alphanum_fraction":0.7275132275,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":68,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <QtCore>\n\nint main(int argc, char *argv[])\n{\n\treturn 0;\n}\n\n","avg_line_length":8.5,"max_line_length":32,"alphanum_fraction":0.6176470588,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10907,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/***************************************************************************\n * Copyright 1998-2018 by authors (see AUTHORS.txt)                        *\n *                                                                         *\n *   This file is part of LuxCoreRender.                                   *\n *                                                                         *\n * Licensed under the Apache License, Version 2.0 (the \"License\");         *\n * you may not use this file except in compliance with the License.        *\n * You may obtain a copy of the License at                                 *\n *                                                                         *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                          *\n *                                                                         *\n * Unless required by applicable law or agreed to in writing, software     *\n * distributed under the License is distributed on an \"AS IS\" BASIS,       *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*\n * See the License for the specific language governing permissions and     *\n * limitations under the License.                                          *\n ***************************************************************************\/\n\n#if !defined(LUXRAYS_DISABLE_OPENCL)\n\n#include <boost\/lexical_cast.hpp>\n#include <boost\/algorithm\/string\/replace.hpp>\n\n#include \"luxrays\/core\/geometry\/transform.h\"\n#include \"luxrays\/utils\/ocl.h\"\n#include \"luxrays\/core\/oclintersectiondevice.h\"\n#include \"luxrays\/kernels\/kernels.h\"\n\n#include \"luxcore\/cfg.h\"\n\n#include \"slg\/slg.h\"\n#include \"slg\/kernels\/kernels.h\"\n#include \"slg\/renderconfig.h\"\n#include \"slg\/engines\/pathoclbase\/pathoclbase.h\"\n#include \"slg\/samplers\/sobol.h\"\n\nusing namespace std;\nusing namespace luxrays;\nusing namespace slg;\n\n\/\/------------------------------------------------------------------------------\n\/\/ PathOCLBaseOCLRenderThread\n\/\/------------------------------------------------------------------------------\n\nPathOCLBaseOCLRenderThread::PathOCLBaseOCLRenderThread(const u_int index,\n\t\tOpenCLIntersectionDevice *device, PathOCLBaseRenderEngine *re) {\n\tthreadIndex = index;\n\tintersectionDevice = device;\n\trenderEngine = re;\n\n\trenderThread = NULL;\n\tstarted = false;\n\teditMode = false;\n\tthreadDone = false;\n\n\tkernelSrcHash = \"\";\n\tfilmClearKernel = NULL;\n\n\t\/\/ Scene buffers\n\tmaterialsBuff = NULL;\n\ttexturesBuff = NULL;\n\tmeshDescsBuff = NULL;\n\tscnObjsBuff = NULL;\n\tlightsBuff = NULL;\n\tenvLightIndicesBuff = NULL;\n\tlightsDistributionBuff = NULL;\n\tinfiniteLightSourcesDistributionBuff = NULL;\n\tdlscAllEntriesBuff = NULL;\n\tdlscDistributionIndexToLightIndexBuff = NULL;\n\tdlscDistributionsBuff = NULL;\n\tdlscBVHNodesBuff = NULL;\n\tenvLightDistributionsBuff = NULL;\n\tvertsBuff = NULL;\n\tnormalsBuff = NULL;\n\tuvsBuff = NULL;\n\tcolsBuff = NULL;\n\talphasBuff = NULL;\n\ttrianglesBuff = NULL;\n\tcameraBuff = NULL;\n\tlightIndexOffsetByMeshIndexBuff = NULL;\n\tlightIndexByTriIndexBuff = NULL;\n\timageMapDescsBuff = NULL;\n\t\/\/ OpenCL memory buffers\n\traysBuff = NULL;\n\thitsBuff = NULL;\n\ttasksBuff = NULL;\n\ttasksDirectLightBuff = NULL;\n\ttasksStateBuff = NULL;\n\tsamplerSharedDataBuff = NULL;\n\tsamplesBuff = NULL;\n\tsampleDataBuff = NULL;\n\ttaskStatsBuff = NULL;\n\tpathVolInfosBuff = NULL;\n\tdirectLightVolInfosBuff = NULL;\n\tpixelFilterBuff = NULL;\n\n\t\/\/ Check the kind of kernel cache to use\n\tstring type = renderEngine->renderConfig->cfg.Get(Property(\"opencl.kernelcache\")(\"PERSISTENT\")).Get<string>();\n\tif (type == \"PERSISTENT\")\n\t\tkernelCache = new oclKernelPersistentCache(\"LUXCORE_\" LUXCORE_VERSION_MAJOR \".\" LUXCORE_VERSION_MINOR);\n\telse if (type == \"VOLATILE\")\n\t\tkernelCache = new oclKernelVolatileCache();\n\telse if (type == \"NONE\")\n\t\tkernelCache = new oclKernelDummyCache();\n\telse\n\t\tthrow runtime_error(\"Unknown opencl.kernelcache type: \" + type);\n\t\n\t\/\/ OpenCL kernels\n\tinitSeedKernel = NULL;\n\tinitKernel = NULL;\n\tadvancePathsKernel_MK_RT_NEXT_VERTEX = NULL;\n\tadvancePathsKernel_MK_HIT_NOTHING = NULL;\n\tadvancePathsKernel_MK_HIT_OBJECT = NULL;\n\tadvancePathsKernel_MK_RT_DL = NULL;\n\tadvancePathsKernel_MK_DL_ILLUMINATE = NULL;\n\tadvancePathsKernel_MK_DL_SAMPLE_BSDF = NULL;\n\tadvancePathsKernel_MK_GENERATE_NEXT_VERTEX_RAY = NULL;\n\tadvancePathsKernel_MK_SPLAT_SAMPLE = NULL;\n\tadvancePathsKernel_MK_NEXT_SAMPLE = NULL;\n\tadvancePathsKernel_MK_GENERATE_CAMERA_RAY = NULL;\n\n\tinitKernelArgsCount  = 0;\n\n\tgpuTaskStats = NULL;\n}\n\nPathOCLBaseOCLRenderThread::~PathOCLBaseOCLRenderThread() {\n\tif (editMode)\n\t\tEndSceneEdit(EditActionList());\n\tif (started)\n\t\tStop();\n\n\tFreeThreadFilms();\n\n\tdelete filmClearKernel;\n\tdelete kernelCache;\n\tdelete initSeedKernel;\n\tdelete initKernel;\n\tdelete advancePathsKernel_MK_RT_NEXT_VERTEX;\n\tdelete advancePathsKernel_MK_HIT_NOTHING;\n\tdelete advancePathsKernel_MK_HIT_OBJECT;\n\tdelete advancePathsKernel_MK_RT_DL;\n\tdelete advancePathsKernel_MK_DL_ILLUMINATE;\n\tdelete advancePathsKernel_MK_DL_SAMPLE_BSDF;\n\tdelete advancePathsKernel_MK_GENERATE_NEXT_VERTEX_RAY;\n\tdelete advancePathsKernel_MK_SPLAT_SAMPLE;\n\tdelete advancePathsKernel_MK_NEXT_SAMPLE;\n\tdelete advancePathsKernel_MK_GENERATE_CAMERA_RAY;\n\n\tdelete[] gpuTaskStats;\n}\n\nvoid PathOCLBaseOCLRenderThread::Start() {\n\tstarted = true;\n\n\tInitRender();\n\tStartRenderThread();\n}\n\nvoid PathOCLBaseOCLRenderThread::Interrupt() {\n\tif (renderThread)\n\t\trenderThread->interrupt();\n}\n\nvoid PathOCLBaseOCLRenderThread::Stop() {\n\tStopRenderThread();\n\n\t\/\/ Transfer the films\n\tTransferThreadFilms(intersectionDevice->GetOpenCLQueue());\n\tFreeThreadFilmsOCLBuffers();\n\n\t\/\/ Scene buffers\n\tFreeOCLBuffer(&materialsBuff);\n\tFreeOCLBuffer(&texturesBuff);\n\tFreeOCLBuffer(&meshDescsBuff);\n\tFreeOCLBuffer(&scnObjsBuff);\n\tFreeOCLBuffer(&normalsBuff);\n\tFreeOCLBuffer(&uvsBuff);\n\tFreeOCLBuffer(&colsBuff);\n\tFreeOCLBuffer(&alphasBuff);\n\tFreeOCLBuffer(&trianglesBuff);\n\tFreeOCLBuffer(&vertsBuff);\n\tFreeOCLBuffer(&lightsBuff);\n\tFreeOCLBuffer(&envLightIndicesBuff);\n\tFreeOCLBuffer(&lightsDistributionBuff);\n\tFreeOCLBuffer(&infiniteLightSourcesDistributionBuff);\n\tFreeOCLBuffer(&dlscAllEntriesBuff);\n\tFreeOCLBuffer(&dlscDistributionIndexToLightIndexBuff);\n\tFreeOCLBuffer(&dlscDistributionsBuff);\n\tFreeOCLBuffer(&dlscBVHNodesBuff);\n\tFreeOCLBuffer(&envLightDistributionsBuff);\n\tFreeOCLBuffer(&cameraBuff);\n\tFreeOCLBuffer(&lightIndexOffsetByMeshIndexBuff);\n\tFreeOCLBuffer(&lightIndexByTriIndexBuff);\n\tFreeOCLBuffer(&imageMapDescsBuff);\n\tfor (u_int i = 0; i < imageMapsBuff.size(); ++i)\n\t\tFreeOCLBuffer(&imageMapsBuff[i]);\n\timageMapsBuff.resize(0);\n\tFreeOCLBuffer(&raysBuff);\n\tFreeOCLBuffer(&hitsBuff);\n\tFreeOCLBuffer(&tasksBuff);\n\tFreeOCLBuffer(&tasksDirectLightBuff);\n\tFreeOCLBuffer(&tasksStateBuff);\n\tFreeOCLBuffer(&samplerSharedDataBuff);\n\tFreeOCLBuffer(&samplesBuff);\n\tFreeOCLBuffer(&sampleDataBuff);\n\tFreeOCLBuffer(&taskStatsBuff);\n\tFreeOCLBuffer(&pathVolInfosBuff);\n\tFreeOCLBuffer(&directLightVolInfosBuff);\n\tFreeOCLBuffer(&pixelFilterBuff);\n\n\tstarted = false;\n\n\t\/\/ Film is deleted in the destructor to allow image saving after\n\t\/\/ the rendering is finished\n}\n\nvoid PathOCLBaseOCLRenderThread::StartRenderThread() {\n\tthreadDone = false;\n\n\t\/\/ Create the thread for the rendering\n\trenderThread = new boost::thread(&PathOCLBaseOCLRenderThread::RenderThreadImpl, this);\n}\n\nvoid PathOCLBaseOCLRenderThread::StopRenderThread() {\n\tif (renderThread) {\n\t\trenderThread->interrupt();\n\t\trenderThread->join();\n\t\tdelete renderThread;\n\t\trenderThread = NULL;\n\t}\n}\n\nvoid PathOCLBaseOCLRenderThread::BeginSceneEdit() {\n\tStopRenderThread();\n}\n\nvoid PathOCLBaseOCLRenderThread::EndSceneEdit(const EditActionList &editActions) {\n\t\/\/--------------------------------------------------------------------------\n\t\/\/ Update OpenCL buffers\n\t\/\/\n\t\/\/ Note: if you edit this, you have probably to edit\n\t\/\/ RTPathOCLRenderThread::UpdateOCLBuffers().\n\t\/\/--------------------------------------------------------------------------\n\n\tCompiledScene *cscene = renderEngine->compiledScene;\n\n\tif (cscene->wasCameraCompiled) {\n\t\t\/\/ Update Camera\n\t\tInitCamera();\n\t}\n\n\tif (cscene->wasGeometryCompiled) {\n\t\t\/\/ Update Scene Geometry\n\t\tInitGeometry();\n\t}\n\n\tif (cscene->wasImageMapsCompiled) {\n\t\t\/\/ Update Image Maps\n\t\tInitImageMaps();\n\t}\n\n\tif (cscene->wasMaterialsCompiled) {\n\t\t\/\/ Update Scene Textures and Materials\n\t\tInitTextures();\n\t\tInitMaterials();\n\t}\n\n\tif (cscene->wasSceneObjectsCompiled) {\n\t\t\/\/ Update Mesh <=> Material relation\n\t\tInitSceneObjects();\n\t}\n\n\tif  (cscene->wasLightsCompiled) {\n\t\t\/\/ Update Scene Lights\n\t\tInitLights();\n\t}\n\n\t\/\/ A material types edit can enable\/disable PARAM_HAS_PASSTHROUGH parameter\n\t\/\/ and change the size of the structure allocated\n\tif (editActions.Has(MATERIAL_TYPES_EDIT))\n\t\tAdditionalInit();\n\n\t\/\/--------------------------------------------------------------------------\n\t\/\/ Recompile Kernels if required\n\t\/\/--------------------------------------------------------------------------\n\n\t\/\/ The following actions can require a kernel re-compilation:\n\t\/\/ - Dynamic code generation of textures and materials;\n\t\/\/ - Material types edit;\n\t\/\/ - Light types edit;\n\t\/\/ - Image types edit;\n\t\/\/ - Geometry type edit;\n\t\/\/ - etc.\n\tInitKernels();\n\n\tif (editActions.HasAnyAction()) {\n\t\tSetKernelArgs();\n\n\t\t\/\/----------------------------------------------------------------------\n\t\t\/\/ Execute initialization kernels\n\t\t\/\/----------------------------------------------------------------------\n\n\t\tcl::CommandQueue &oclQueue = intersectionDevice->GetOpenCLQueue();\n\n\t\t\/\/ Clear the frame buffers\n\t\tClearThreadFilms(oclQueue);\n\t}\n\n\t\/\/ Reset statistics in order to be more accurate\n\tintersectionDevice->ResetPerformaceStats();\n\n\tStartRenderThread();\n}\n\nbool PathOCLBaseOCLRenderThread::HasDone() const {\n\treturn (renderThread == NULL) || threadDone;\n}\n\nvoid PathOCLBaseOCLRenderThread::WaitForDone() const {\n\tif (renderThread)\n\t\trenderThread->join();\n}\n\nvoid PathOCLBaseOCLRenderThread::IncThreadFilms() {\n\tthreadFilms.push_back(new ThreadFilm(this));\n\n\t\/\/ Initialize the new thread film\n\tu_int threadFilmWidth, threadFilmHeight, threadFilmSubRegion[4];\n\tGetThreadFilmSize(&threadFilmWidth, &threadFilmHeight, threadFilmSubRegion);\n\n\tthreadFilms.back()->Init(renderEngine->film, threadFilmWidth, threadFilmHeight,\n\t\t\tthreadFilmSubRegion);\n}\n\nvoid PathOCLBaseOCLRenderThread::ClearThreadFilms(cl::CommandQueue &oclQueue) {\n\t\/\/ Clear all thread films\n\tBOOST_FOREACH(ThreadFilm *threadFilm, threadFilms)\n\t\tthreadFilm->ClearFilm(oclQueue, *filmClearKernel, filmClearWorkGroupSize);\n}\n\nvoid PathOCLBaseOCLRenderThread::TransferThreadFilms(cl::CommandQueue &oclQueue) {\n\t\/\/ Clear all thread films\n\tBOOST_FOREACH(ThreadFilm *threadFilm, threadFilms)\n\t\tthreadFilm->RecvFilm(oclQueue);\n}\n\nvoid PathOCLBaseOCLRenderThread::FreeThreadFilmsOCLBuffers() {\n\tBOOST_FOREACH(ThreadFilm *threadFilm, threadFilms)\n\t\tthreadFilm->FreeAllOCLBuffers();\n}\n\nvoid PathOCLBaseOCLRenderThread::FreeThreadFilms() {\n\tBOOST_FOREACH(ThreadFilm *threadFilm, threadFilms)\n\t\tdelete threadFilm;\n\tthreadFilms.clear();\n}\n\n#endif\n","avg_line_length":30.2972222222,"max_line_length":111,"alphanum_fraction":0.6868066379,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":702,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#define CATCH_CONFIG_MAIN  \/\/ This tells Catch to provide a main() - only do this in one cpp file\r\n#include \"catch.hpp\"\r\n#include \"decisions.h\"\r\n\r\nTEST_CASE(\"Verify Test Configuration\", \"verification\") {\r\n\tREQUIRE(true == true);\r\n}\r\n\r\nTEST_CASE(\"Verify get_grade_points function\")\r\n{\r\n\tREQUIRE(get_grade_points(\"A\") == 4);\r\n\tREQUIRE(get_grade_points(\"B\") == 3);\r\n\tREQUIRE(get_grade_points(\"C\") == 2);\r\n\tREQUIRE(get_grade_points(\"D\") == 1);\r\n\tREQUIRE(get_grade_points(\"F\") == 0);\r\n}\r\n\r\nTEST_CASE(\"Verify calculate_gpa function\")\r\n{\r\n\tREQUIRE(calculate_gpa(12, 45) == 3.75);\r\n\tREQUIRE(calculate_gpa(120, 390) == 3.25);\r\n\tREQUIRE(calculate_gpa(90, 180) == 2.00);\r\n\tREQUIRE(calculate_gpa(0, 180) == -1);\r\n}","avg_line_length":29.25,"max_line_length":98,"alphanum_fraction":0.6737891738,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":31343,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\n#ifndef _USE_MATH_DEFINES\n\t#define _USE_MATH_DEFINES\n#endif\n#include <cmath>\n#include <stdlib.h>    \n#include <time.h>    \n#include \"JadeLookAndFeel.h\"\n#include \"Spectrogram.h\"\n#include \"PluginEditor.h\"\n\n\n#ifndef M_PI\n\t#define M_PI 3.14159265358979323846\n#endif\nSpectrogram::Spectrogram()\n:SynchronBlockProcessor(), m_fs(48000.0),m_channels(2), m_feed_percent (100.0), m_feed_samples(1024), m_memsize_s(1.0),\nm_fftsize(1024),m_feedcounter(0),m_inCounter(0),m_feedblocks(1),m_newEntryCounter(100000000000),\nm_memCounter(0),m_fft(1024), m_PauseMode(false)\n{\n    m_mode = Spectrogram::ChannelMixMode::AbsMean;\n    m_windowChoice = Spectrogram::Windows::Hann;\n    buildmem();\n}\nvoid Spectrogram::prepareParameter(std::unique_ptr<AudioProcessorValueTreeState>& vts)\n{\n    m_SpecParameter.m_DisplayMinFreq = vts->getRawParameterValue(paramDisplayMinFreq.ID);\n\tm_SpecParameter.m_DisplayMinFreqOld = paramDisplayMinFreq.defaultValue;\n    m_SpecParameter.m_DisplayMaxFreq = vts->getRawParameterValue(paramDisplayMaxFreq.ID);\n\tm_SpecParameter.m_DisplayMaxFreqOld = paramDisplayMaxFreq.defaultValue;\n    m_SpecParameter.m_DisplayMinColor = vts->getRawParameterValue(paramDisplayMinColor.ID);\n\tm_SpecParameter.m_DisplayMinColorOld = paramDisplayMinColor.defaultValue;\n    m_SpecParameter.m_DisplayMaxColor = vts->getRawParameterValue(paramDisplayMaxColor.ID);\n\tm_SpecParameter.m_DisplayMaxColorOld = paramDisplayMaxColor.defaultValue;\n}\nfloat g_minValForLogSpectrogram(0.00000000001f);\nint Spectrogram::processSynchronBlock(std::vector <std::vector<float>>& data, juce::MidiBuffer& midiMessages)\n{\n    juce::ignoreUnused(midiMessages);\n    m_protect.enter();\n    for (size_t kk = 0; kk < m_fftsize ; ++kk) \/\/ copy in block to internal mem\n    {\n        for (size_t cc = 0 ; cc < m_channels ; ++cc)\n        {\n            m_indatamem[cc][m_inCounter] = data[cc][kk];\n        }\n        m_inCounter++;\n    }\n\n    for (int bb = 0; bb < m_feedblocks; bb++)\n    {\n        for (size_t cc = 0 ; cc < m_channels ; ++cc)\n        {\n            for (size_t kk = 0; kk < m_fftsize ; ++kk)\n                m_intime[kk] = m_indatamem[cc][kk+m_feed_samples*bb];\n        \n            \/\/ FFT\n            computePowerSpectrum(m_intime,m_power[cc]);\n        }\n\n        \/\/ Hier Auswahl\n\n        \/\/ start with a simple solution\n        for (size_t kk = 0; kk < m_freqsize ; ++kk)\n        {\n            switch (m_mode)\n            {\n                case Spectrogram::ChannelMixMode::AbsMean:\n                    m_powerfinal[kk] = 0.0;\n                    for (size_t cc = 0 ; cc < m_channels ; ++cc)\n                    {\n                        m_powerfinal[kk] += m_power[cc][kk];\n                    }\n                    m_powerfinal[kk] \/= m_channels;\n                \n                    break;\n                case Spectrogram::ChannelMixMode::Max:\n                    m_powerfinal[kk] = 0.0;\n                    for (size_t cc = 0 ; cc < m_channels ; ++cc)\n                    {\n                        if (m_power[cc][kk] > m_powerfinal[kk] )\n                            m_powerfinal[kk] = m_power[cc][kk];\n                    }\n                    break;\n                case Spectrogram::ChannelMixMode::Min:\n                    m_powerfinal[kk] = 1000000.0;\n                    for (size_t cc = 0 ; cc < m_channels ; ++cc)\n                    {\n                        if (m_power[cc][kk] < m_powerfinal[kk] )\n                            m_powerfinal[kk] = m_power[cc][kk];\n                    }\n                    break;\n                case Spectrogram::ChannelMixMode::Left:\n                    m_powerfinal[kk] = m_power[0][kk];\n                    \n                    break;\n                case Spectrogram::ChannelMixMode::Right:\n                    if (m_channels>0)\n                        m_powerfinal[kk] = m_power[1][kk];\n                    else\n                    {\n                        m_powerfinal[kk] = m_power[0][kk];\n                    }\n                    \n                    break;\n            }\n            m_powerfinal[kk] = 10.0*log10(m_powerfinal[kk] + g_minValForLogSpectrogram);\n        }\n        \/\/ save into mem\n        \n        if (!m_PauseMode)\n        {\n            m_newEntryCounter++;\n            m_mem.at(m_memCounter) = m_powerfinal;\n            m_memCounter++;\n            if (m_memCounter == m_memsize_blocks)\n                m_memCounter = 0;\n        }\n\n    }\n    if (m_inCounter == 2*m_fftsize) \/\/ copy data to the beginning\n    {\n        m_inCounter = m_fftsize;\n        for (size_t kk = 0; kk < m_fftsize ; ++kk)\n        {\n            for (size_t cc = 0 ; cc < m_channels ; ++cc)\n            {\n                m_indatamem[cc][kk] = m_indatamem[cc][kk+m_fftsize];\n            }\n        }\n    }\n    m_protect.exit();\n\n    return 0;\n}\n\nvoid Spectrogram::computePowerSpectrum(std::vector<float>& in, std::vector<float>& power)\n{\n    \/\/ FFT\n    for (size_t kk = 0; kk < m_fftsize ; ++kk)\n        in[kk] *= m_window[kk];\n\n    float *invec = in.data();\n    m_fft.power(invec, power);  \n}\n\n\/\/ setter\nvoid Spectrogram::setSamplerate(float samplerate)\n{\n    m_fs = samplerate;\n    buildmem();\n}\nvoid Spectrogram::setchannels(size_t newchannels)\n{\n    m_channels = newchannels;\n    buildmem();\n}\n\n\nvoid Spectrogram::setFFTSize(size_t newFFTSize)\n{\n    m_protect.enter();\n    m_fftsize = newFFTSize;\n    setDesiredBlockSizeSamples(m_fftsize);\n    buildmem();\n    setWindowFkt();\n    m_protect.exit();\n    m_newEntryCounter = 100000000000;\n\n}\nsize_t Spectrogram::getnextpowerof2(float fftsize_ms)\n{\n    float firstguessFFTSize = (fftsize_ms*0.001*m_fs);\n    int nextpowerof2 = int(log(firstguessFFTSize)\/log(2.f))+1;\n    return size_t(pow(2.f,nextpowerof2));\n}\nvoid Spectrogram::setclosestFFTSize_ms(float fftsize_ms)\n{\n    m_fftsize = getnextpowerof2(fftsize_ms);\n    setDesiredBlockSizeSamples(m_fftsize);    \n    buildmem();\n    setWindowFkt();\n}\nvoid Spectrogram::setmemoryTime_s (float memsize_s)\n{\n    m_memsize_s = memsize_s;\n    buildmem();\n}\nvoid Spectrogram::setfeed_percent (FeedPercentage feed)\n{\n    switch (feed)\n    {\n        case Spectrogram::FeedPercentage::perc100:\n            m_feed_percent = 100.0;    \n            m_feedblocks = 1;\n            break;\n        case Spectrogram::FeedPercentage::perc50:\n            m_feed_percent = 50.0;    \n            m_feedblocks = 2;\n            break;\n        case Spectrogram::FeedPercentage::perc25:\n            m_feed_percent = 25.0;  \n            m_feedblocks = 4;  \n            break;\n        case Spectrogram::FeedPercentage::perc10:\n            m_feed_percent = 10.0; \n            m_feedblocks = 10;   \n            break;\n    }\n    buildmem();\n}\n\nvoid Spectrogram::buildmem()\n{\n    m_fft.setFFTSize(m_fftsize);\n    m_feed_samples = int(m_feed_percent*0.01*m_fftsize+0.5);\n    m_memsize_blocks = int(m_memsize_s*m_fs\/m_feed_samples + 0.5);\n    m_freqsize = m_fftsize\/2+1;\n    m_mem.resize(m_memsize_blocks);\n    for (auto kk = 0 ; kk< m_memsize_blocks; kk++)\n    {\n        m_mem.at(kk).resize(m_freqsize);\n        std::fill(m_mem.at(kk).begin(),m_mem.at(kk).end(),-120.0); \/\/ fill with -120 dB = silence\n    }\n    m_intime.resize(m_fftsize);\n    m_powerfinal.resize(m_freqsize);\n    m_power.resize(m_channels);\n    m_indatamem.resize(m_channels);\n    for (size_t cc = 0 ; cc < m_channels ; ++cc)\n    {\n        m_power.at(cc).resize(m_freqsize);\n        m_indatamem.at(cc).resize(2*m_fftsize);\n        std::fill(m_indatamem.at(cc).begin(),m_indatamem.at(cc).end(),0.0);\n    }\n    m_inCounter = m_fftsize;\n    m_newEntryCounter = 100000000000;\n    m_memCounter = 0;\n}\nvoid Spectrogram::setWindowFkt()\n{\n    m_window.resize(m_fftsize);\n    float normalizeFactor = 0.f;\n    for (size_t kk = 0; kk < m_fftsize ; kk++)\n    {\n        float a0;\n        float a1;\n        float a2;\n        float a3;\n        float a4;\n        switch (m_windowChoice)\n        {\n            case Spectrogram::Windows::Rect:\n                m_window[kk] = 1.f;\n            break;\n            case Spectrogram::Windows::Hann:\n                m_window[kk] = 0.5f*(1.f-cos(2.0*M_PI*kk\/m_fftsize));\n                break;\n            case Spectrogram::Windows::Hamming:\n                m_window[kk] = 25.0\/46.0-(1.0-25.0\/46.0)*cos(2.0*M_PI*kk\/m_fftsize);\n                break;\n            case Spectrogram::Windows::BlackmanHarris:\n                a0 = 0.35875;\n                a1 = 0.48829;\n                a2 = 0.14128;\n                a3 = 0.01168;\n                m_window[kk] = a0 - a1*cos(2.0*M_PI*kk\/m_fftsize) + a2*cos(4.0*M_PI*kk\/m_fftsize) - a3*cos(6.0*M_PI*kk\/m_fftsize);\n                break;\n            case Spectrogram::Windows::FlatTop:\n                a0 = 0.21557895;\n                a1 = 0.41663158;\n                a2 = 0.277263158;\n                a3 = 0.083578947;\n                a4 = 0.006947368;\n                m_window[kk] = a0 - a1*cos(2.0*M_PI*kk\/m_fftsize) + a2*cos(4.0*M_PI*kk\/m_fftsize) \n                             - a3*cos(6.0*M_PI*kk\/m_fftsize) + a4*cos(8.0*M_PI*kk\/m_fftsize);\n                break;\n            case Spectrogram::Windows::HannPoisson:\n                float alpha = 2.0;\n                m_window[kk] = 0.5f*(1.f-cos(2.0*M_PI*kk\/m_fftsize))\n                                *exp(-alpha*fabs(m_fftsize-2*kk)\/m_fftsize);\n                break;\n        }\n        normalizeFactor += m_window[kk]*m_window[kk];\n    }\n    normalizeFactor\/= m_fftsize;\n    normalizeFactor = sqrt(normalizeFactor);\n    for (size_t kk = 0; kk < m_fftsize ; kk++)\n    {\n        m_window[kk] \/= normalizeFactor;\n        \n    }\n\n}\n\nint Spectrogram::getMem(std::vector<std::vector<float >>& mem, int& pos)\n{\n    if (mem.size() != m_mem.size())\n        return -1;\n    \n    if (m_newEntryCounter>=mem.size())\n    {\n        for (size_t kk = 0; kk < mem.size(); kk++)\n            std::copy(m_mem.at(kk).begin(),m_mem.at(kk).end(),mem.at(kk).begin());\n    }\n    else\n    {\n        int startpos = m_memCounter-m_newEntryCounter;\n        if (startpos>=0)\n        {\n            for (size_t kk = startpos; kk < m_memCounter ; kk++)\n                std::copy(m_mem.at(kk).begin(),m_mem.at(kk).end(),mem.at(kk).begin());\n        }\n        else\n        {\n            for (size_t kk = 0; kk < m_memCounter ; kk++)\n                std::copy(m_mem.at(kk).begin(),m_mem.at(kk).end(),mem.at(kk).begin());\n\n            for (size_t kk = mem.size()+startpos; kk < mem.size() ; kk++)\n                std::copy(m_mem.at(kk).begin(),m_mem.at(kk).end(),mem.at(kk).begin());\n        }\n       \n    }\n    \n\n\n\n    int newVals = m_newEntryCounter;\n    m_newEntryCounter = 0;\n    pos = m_memCounter;\n    return newVals;\n}\n\nSpectrogramComponent::SpectrogramComponent(AudioProcessorValueTreeState& vts, Spectrogram& spectrogram, JadeSpectrogramAudioProcessorEditor& editor)\n:m_scaleFactor(1.f),m_spectrogram(spectrogram),m_vts(vts),\nm_internalImg(Image::RGB,1,1,true),m_internalWidth(1),\nm_internalHeight(1), m_recomputeAll(true),m_maxColorVal(g_maxColorVal),m_minColorVal(g_minColorVal),\nm_colorpalette(256,6),m_maxDisplayFreq(20000.f),m_minDisplayFreq(0.f),somethingChanged(nullptr),\nm_isPaused(false),m_isRunningDisplay(true),m_hideFFTSizeCombobox(false),m_editor(editor)\n{\n    startTimer(40) ;\n    srand (time(NULL));\n    m_colorpalette.setValueRange(m_minColorVal,m_maxColorVal);\n\n\/\/ UI Elements\n\tm_DisplayMinFreqLabel.setText(\"Freq.\", NotificationType::dontSendNotification);\n\tm_DisplayMinFreqLabel.setJustificationType(Justification::centred);\n\t\/\/m_DisplayMinFreqLabel.attachToComponent (&m_DisplayMinFreqSlider, false);\n\t\/\/addAndMakeVisible(m_DisplayMinFreqLabel);\n\tm_DisplayMinFreqSlider.setSliderStyle(Slider::SliderStyle::LinearVertical);\n\tm_DisplayMinFreqAttachment = std::make_unique<AudioProcessorValueTreeState::SliderAttachment>(m_vts, paramDisplayMinFreq.ID, m_DisplayMinFreqSlider);\n\taddAndMakeVisible(m_DisplayMinFreqSlider);\n\tm_DisplayMinFreqSlider.onValueChange = [this]() {if (somethingChanged != nullptr) somethingChanged(); };\n\n\tm_DisplayMaxFreqLabel.setText(\"Freq.\", NotificationType::dontSendNotification);\n\tm_DisplayMaxFreqLabel.setJustificationType(Justification::centred);\n\t\/\/m_DisplayMaxFreqLabel.attachToComponent (&m_DisplayMaxFreqSlider, false);\n\t\/\/addAndMakeVisible(m_DisplayMaxFreqLabel);\n\tm_DisplayMaxFreqSlider.setSliderStyle(Slider::SliderStyle::LinearVertical);\n\tm_DisplayMaxFreqAttachment = std::make_unique<AudioProcessorValueTreeState::SliderAttachment>(m_vts, paramDisplayMaxFreq.ID, m_DisplayMaxFreqSlider);\n\taddAndMakeVisible(m_DisplayMaxFreqSlider);\n\tm_DisplayMaxFreqSlider.onValueChange = [this]() {if (somethingChanged != nullptr) somethingChanged(); };\n\n\tm_DisplayMinColorLabel.setText(\"Color.\", NotificationType::dontSendNotification);\n\tm_DisplayMinColorLabel.setJustificationType(Justification::centred);\n\t\/\/m_DisplayMinColorLabel.attachToComponent (&m_DisplayMinColorSlider, false);\n\t\/\/addAndMakeVisible(m_DisplayMinColorLabel);\n\tm_DisplayMinColorSlider.setSliderStyle(Slider::SliderStyle::LinearVertical);\n\tm_DisplayMinColorAttachment = std::make_unique<AudioProcessorValueTreeState::SliderAttachment>(m_vts, paramDisplayMinColor.ID, m_DisplayMinColorSlider);\n\taddAndMakeVisible(m_DisplayMinColorSlider);\n\tm_DisplayMinColorSlider.onValueChange = [this]() {m_recomputeAll = true; if (somethingChanged != nullptr) somethingChanged(); };\n\n\tm_DisplayMaxColorLabel.setText(\"Color.\", NotificationType::dontSendNotification);\n\tm_DisplayMaxColorLabel.setJustificationType(Justification::centred);\n\t\/\/m_DisplayMaxColorLabel.attachToComponent (&m_DisplayMaxColorSlider, false);\n\t\/\/addAndMakeVisible(m_DisplayMaxColorLabel);\n\tm_DisplayMaxColorSlider.setSliderStyle(Slider::SliderStyle::LinearVertical);\n\tm_DisplayMaxColorAttachment = std::make_unique<AudioProcessorValueTreeState::SliderAttachment>(m_vts, paramDisplayMaxColor.ID, m_DisplayMaxColorSlider);\n\taddAndMakeVisible(m_DisplayMaxColorSlider);\n\tm_DisplayMaxColorSlider.onValueChange = [this]() { m_recomputeAll = true; if (somethingChanged != nullptr) somethingChanged(); };\n\n    m_pauseButton.setButtonText(\"Pause\");\n    m_pauseButton.setToggleState(false,NotificationType::dontSendNotification);\n    m_pauseButton.onClick = [this](){pauseClicked();};\n    addAndMakeVisible(m_pauseButton);\n\n    m_runModeButton.setButtonText(\"Fix\");\n    m_runModeButton.setToggleState(false,NotificationType::dontSendNotification);\n    m_runModeButton.onClick = [this](){runClicked();};\n    addAndMakeVisible(m_runModeButton);\n\n    m_colorScheme.addItem(\"Mono\",1);\n    m_colorScheme.addItem(\"BW\",2);\n    m_colorScheme.addItem(\"Hot\",3);\n    m_colorScheme.addItem(\"Rainbow\",4);\n    m_colorScheme.addItem(\"Viridis\",5);\n    m_colorScheme.addItem(\"Plasma\",6);\n    m_colorScheme.addItem(\"Jade\",7);\n    m_colorScheme.setSelectedItemIndex(6,NotificationType::dontSendNotification);\n    m_colorScheme.setColour(juce::ComboBox::ColourIds::backgroundColourId,JadeTeal);\n    m_colorScheme.onChange = [this](){m_recomputeAll = true; m_colorpalette.setColorSceme(m_colorScheme.getSelectedItemIndex());};\n    addAndMakeVisible(m_colorScheme);\n    m_windowFktCombo.addItem(\"Rectangular\",1);\n    m_windowFktCombo.addItem(\"Hann\",2);\n    m_windowFktCombo.addItem(\"Hamming\",3);\n    m_windowFktCombo.addItem(\"BlackmanHarris\",4);\n    m_windowFktCombo.addItem(\"FlatTop\",5);\n    m_windowFktCombo.addItem(\"HannPoisson\",6);\n    m_windowFktCombo.setColour(juce::ComboBox::ColourIds::backgroundColourId,JadeTeal);\n    m_windowFktCombo.onChange = [this](){m_spectrogram.setWindow(static_cast<Spectrogram::Windows> (m_windowFktCombo.getSelectedItemIndex()));};\n    m_windowFktCombo.setSelectedItemIndex(1,NotificationType::dontSendNotification);\n    addAndMakeVisible(m_windowFktCombo);\n\n    m_fftSizeCombo.addItem(\"512\",1);\n    m_fftSizeCombo.addItem(\"1024\",2);\n    m_fftSizeCombo.addItem(\"2048\",3);\n    m_fftSizeCombo.addItem(\"4096\",4);\n    m_fftSizeCombo.addItem(\"8192\",5);\n    m_fftSizeCombo.setColour(juce::ComboBox::ColourIds::backgroundColourId,JadeTeal);\n    m_fftSizeCombo.onChange = [this](){changeFFTSize();};\n\n    m_fftSizeCombo.setSelectedItemIndex(2,NotificationType::dontSendNotification);\n    addAndMakeVisible(m_fftSizeCombo);\n\n    m_FreqLabel.setText(\"Analysis\",juce::NotificationType::dontSendNotification);\n    m_FreqLabel.setJustificationType(juce::Justification::centred);\n    m_FreqLabel.setColour(Label::ColourIds::outlineColourId,JadeTeal);\n    m_FreqLabel.setColour(Label::ColourIds::textColourId,juce::Colours::white);\n    m_FreqLabel.setColour(Label::ColourIds::backgroundColourId,JadeTeal);\n    addAndMakeVisible(m_FreqLabel);\n}\n\nvoid SpectrogramComponent::paint(Graphics& g)\n{\n    g.fillAll (getLookAndFeel().findColour (juce::ResizableWindow::backgroundColourId).darker(0.2));\n\n    int w = getWidth();\n    int h = getHeight();\n\n    float fs = m_spectrogram.getSamplerate();\n    \n    m_minDisplayFreq = exp(m_DisplayMinFreqSlider.getValue());\n    m_maxDisplayFreq = exp(m_DisplayMaxFreqSlider.getValue());\n\n    if (m_minDisplayFreq >= fs*0.5)\n        m_minDisplayFreq = 0.9*fs*0.5;\n    if (m_maxDisplayFreq >= fs*0.5)\n        m_maxDisplayFreq = fs*0.5;\n\n    if (m_minDisplayFreq >= m_maxDisplayFreq)\n    {\n        m_minDisplayFreq = 0.9*m_maxDisplayFreq;\n        m_DisplayMinFreqSlider.setValue(log(m_minDisplayFreq));\n    }\n\n    int displayStartPixel = int(2.0*m_minDisplayFreq\/fs *m_internalHeight+0.5);\n    int displayEndPixel = int(2.0*m_maxDisplayFreq\/fs *m_internalHeight + 0.5);\n    int heightInterval = int(2.0*m_maxDisplayFreq\/fs *m_internalHeight -2.0*m_minDisplayFreq\/fs *m_internalHeight+0.5);\n\n    int hStart = m_internalHeight - displayEndPixel;\n\n    int wStartPic = m_scaleFactor*(g_SliderWidth + g_FreqMeter);\n\n    g.drawImage(m_internalImg,wStartPic,0,0.8*w,int(float(h)-m_scaleFactor*g_menuHeight+0.5),\n                0,hStart,m_internalWidth,heightInterval);\n    \n    \/\/ Add frequency scale\n    int nrOfYTicks = 11;\n    float RangePerTick = float(m_maxDisplayFreq - m_minDisplayFreq)\/(nrOfYTicks-1);\n    int TextHeight = 20;\n    g.setFont(0.8*m_scaleFactor*TextHeight);\n    for (auto kk = 0; kk < nrOfYTicks; ++kk)\n    {\n        float newExaktFreq = int(m_minDisplayFreq + RangePerTick*kk + 0.5);\n        String OutText;\n        if (newExaktFreq >= 1000.f)\n        {\n            newExaktFreq = int(newExaktFreq*0.01 +0.5)*100;\n            OutText += String(newExaktFreq\/1000);\n            OutText += \"k\";\n        }\n        else\n        {\n            if (newExaktFreq >= 150.f)\n            {\n                newExaktFreq = int(newExaktFreq*0.1 +0.5)*10;\n                OutText += String(newExaktFreq);\n            }\n            else\n            {\n                 OutText += String(newExaktFreq);\n            }\n        }\n        \n        \n\n\n        int ydelta = (h-m_scaleFactor*g_menuHeight)* (newExaktFreq-m_minDisplayFreq)\/(m_maxDisplayFreq - m_minDisplayFreq);\n        int x = wStartPic-g_FreqMeter*m_scaleFactor;\n        int y ;\n        if (kk < nrOfYTicks-1)\n            y = h-m_scaleFactor*g_menuHeight-0.5*TextHeight*m_scaleFactor - ydelta;\n        else\n        {\n            y = h-m_scaleFactor*g_menuHeight - ydelta;\n        }\n        g.drawText(OutText,x,y,g_FreqMeter*m_scaleFactor,m_scaleFactor*TextHeight,\n                juce::Justification::centred,true);\n    }\n\n    \/\/ Plot Colorbar\n    int cbHeight = h-m_scaleFactor*g_menuHeight;\n    Image colorbar(Image::RGB,1,cbHeight,true);\n    for (int kk = 0; kk < cbHeight; kk++)\n    {   \n        float val = float(kk)\/cbHeight*(g_maxColorVal - g_minColorVal) + g_minColorVal;\n        int color = m_colorpalette.getRGBColor(val);\n        color = color|0xFF000000; \/\/ kein alpha blending\n        colorbar.setPixelAt(0,cbHeight-1-kk,juce::Colour(color));\n    }\n    g.drawImage(colorbar,w-m_scaleFactor*(g_colorbar_width+g_FreqMeter + g_SliderWidth),0,m_scaleFactor*g_colorbar_width,h-m_scaleFactor*g_menuHeight,\n                0,0,1,cbHeight);\n\n    \/\/ draw scale\n    \/\/ Add colorbar scale\n    nrOfYTicks = 11;\n    RangePerTick = float(g_maxColorVal - g_minColorVal)\/(nrOfYTicks-1);\n    for (auto kk = 0; kk < nrOfYTicks; ++kk)\n    {\n        float newExaktFreq = int((g_minColorVal + RangePerTick*kk)*0.1 )*10;\n        String OutText;\n        OutText += String(newExaktFreq);\n\n        int ydelta = (h-m_scaleFactor*g_menuHeight)* (newExaktFreq-g_minColorVal)\/(g_maxColorVal - g_minColorVal);\n        int x = w - (g_FreqMeter + g_SliderWidth + g_SliderMaxFreq_x) *m_scaleFactor;\n        int y ;\n        if (kk < nrOfYTicks-1)\n            y = h-m_scaleFactor*g_menuHeight-0.5*TextHeight*m_scaleFactor - ydelta;\n        else\n        {\n            y = h-m_scaleFactor*g_menuHeight - ydelta;\n        }\n        \n        g.drawText(OutText,x,y,g_FreqMeter*m_scaleFactor,m_scaleFactor*TextHeight,\n                juce::Justification::centred,true);\n    }\n\n\/*    if (m_hideFFTSizeCombobox == false)\n        m_fftSizeCombo.setVisible(true);\n    else\n    {\n        m_fftSizeCombo.setVisible(false);\n    }\n  \/\/*\/  \n\n}\nvoid SpectrogramComponent::resized() \n{\n    m_DisplayMaxFreqSlider.setBounds(m_scaleFactor*g_SliderMaxFreq_x,m_scaleFactor*g_SliderMaxFreq_y,\n            m_scaleFactor*g_SliderWidth,m_scaleFactor*g_SliderHeight);\n    m_DisplayMinFreqSlider.setBounds(m_scaleFactor*g_SliderMinFreq_x,m_scaleFactor*g_SliderMinFreq_y,\n            m_scaleFactor*g_SliderWidth,m_scaleFactor*g_SliderHeight);\n\n    m_DisplayMaxColorSlider.setBounds(m_scaleFactor*g_SliderMaxColor_x,m_scaleFactor*g_SliderMaxColor_y,\n            m_scaleFactor*g_SliderWidth,m_scaleFactor*g_SliderHeight);\n    m_DisplayMinColorSlider.setBounds(m_scaleFactor*g_SliderMinColor_x,m_scaleFactor*g_SliderMinColor_y,\n            m_scaleFactor*g_SliderWidth,m_scaleFactor*g_SliderHeight);\n\n    m_pauseButton.setBounds(m_scaleFactor*g_PauseButton_x, m_scaleFactor*g_PauseButton_y,\n                    m_scaleFactor*g_ButtonWidth,m_scaleFactor*g_ButtonHeight);\n\n    int w = getWidth();\n    int x = m_scaleFactor*(g_SliderWidth + g_FreqMeter) + 0.8*w - m_scaleFactor*g_ButtonWidth;\n\n    m_runModeButton.setBounds(x, m_scaleFactor*g_PauseButton_y,\n                    m_scaleFactor*g_ButtonWidth,m_scaleFactor*g_ButtonHeight);\n\n    m_colorScheme.setBounds(w-m_scaleFactor*(g_colorbar_width+g_FreqMeter + g_SliderWidth), m_scaleFactor*g_PauseButton_y,\n                    m_scaleFactor*g_colorbar_width, m_scaleFactor*g_ButtonHeight);\n\n    x = m_scaleFactor*(g_SliderWidth + g_FreqMeter) + 0.4*w - m_scaleFactor*0.5*100;\n    m_FreqLabel.setBounds(x ,m_scaleFactor*g_PauseButton_y,m_scaleFactor*100,m_scaleFactor*g_ButtonHeight );                    \n\n    x = m_scaleFactor*(g_SliderWidth + g_FreqMeter) + 0.2*w - m_scaleFactor*0.5*100;\n    m_windowFktCombo.setBounds(x,m_scaleFactor*g_PauseButton_y,m_scaleFactor*100,m_scaleFactor*g_ButtonHeight);\n\n    x = m_scaleFactor*(g_SliderWidth + g_FreqMeter) + 0.6*w - m_scaleFactor*0.5*100;\n    m_fftSizeCombo.setBounds(x,m_scaleFactor*g_PauseButton_y,m_scaleFactor*100,m_scaleFactor*g_ButtonHeight);\n\n}\nvoid SpectrogramComponent::timerCallback()\n{\n    int wData = m_spectrogram.getMemorySize();\n    int hData = m_spectrogram.getSpectrumSize();\n    \n    if (wData != m_internalWidth || hData != m_internalHeight)\n    {\n        m_internalWidth = wData;\n        m_internalHeight = hData;\n        m_internalImg = m_internalImg.rescaled(m_internalWidth,m_internalHeight);\n        m_displaymem.resize(wData);\n        for (size_t kk = 0; kk < m_displaymem.size(); ++kk)\n        {\n            m_displaymem.at(kk).resize(hData);\n        }\n    }\n\n    int pos;\n    int newVals = m_spectrogram.getMem(m_displaymem,pos);\n    \n    if (newVals > m_internalWidth)\n    {\n        m_recomputeAll = true;\n    }\n    float maxValColor = m_DisplayMaxColorSlider.getValue();\n    float minValColor = m_DisplayMinColorSlider.getValue();\n\n    m_colorpalette.setValueRange(minValColor,maxValColor);\n\n    CriticalSection crit;\n    crit.enter();\n    const Image::BitmapData destData (m_internalImg, 0, 0, m_internalWidth, m_internalHeight, Image::BitmapData::writeOnly);\n\n    if (m_recomputeAll == true)\n    {\n        m_recomputeAll = false;\n        int newwstart = m_internalWidth-pos;\n        for (size_t ww = 0; ww < m_internalWidth; ++ww)\n        {\n            int neww = ww+newwstart;\n            if (neww>=m_internalWidth)\n                neww -= m_internalWidth;\n            for (size_t hh = 0; hh < m_internalHeight; ++hh)\n            {\n                float val = m_displaymem.at(ww).at(hh);\n\n                int color = m_colorpalette.getRGBColor(val);\n                color = color|0xFF000000; \/\/ kein alpha blending\n\n                if (m_isRunningDisplay)\n                {\n                    \/\/m_internalImg.setPixelAt(neww,m_internalHeight-1-hh,juce::Colour(color));\n                    destData.setPixelColour (neww,m_internalHeight-1-hh,juce::Colour(color));\n                }\n                else\n                {\n                    destData.setPixelColour(ww,m_internalHeight-1-hh,juce::Colour(color));\n                }\n            }\n        }\n        if (!m_isRunningDisplay) \/\/ redline at end\n        {\n            for (size_t hh = 0; hh < m_internalHeight; ++hh)\n            {\n                destData.setPixelColour(pos,m_internalHeight-1-hh,juce::Colours::red);\n            }\n        }\n    }\n    else\n    {\n        \/\/ int newwstart = m_internalWidth-pos;\n        int startread = pos - newVals;\n        \/\/ copy image \n        if (m_isRunningDisplay)\n        {\n            m_internalImg.moveImageSection(0,0,newVals,0,m_internalWidth-newVals,m_internalHeight);\n            for (size_t ww = m_internalWidth-newVals ; ww < m_internalWidth; ++ww)\n            {\n                int readpos;\n                if (startread < 0)\n                    readpos = wData+(startread);\n                else\n                    readpos = startread;\n                for (size_t hh = 0; hh < m_internalHeight; ++hh)\n                {\n                    float val = m_displaymem.at(readpos).at(hh);\n\n                    int color = m_colorpalette.getRGBColor(val);\n                    color = color|0xFF000000; \/\/ kein alpha blending\n                    destData.setPixelColour(ww,m_internalHeight-1-hh,juce::Colour(color));\n                }\n                startread++;\n            }\n        }\n        else\n        {\n            for (size_t ww = 0 ; ww < newVals; ++ww)\n            {\n                int readpos;\n                if (startread < 0)\n                    readpos = wData+(startread);\n                else\n                    readpos = startread;\n                for (size_t hh = 0; hh < m_internalHeight; ++hh)\n                {\n                    float val = m_displaymem.at(readpos).at(hh);\n\n                    int color = m_colorpalette.getRGBColor(val);\n                    color = color|0xFF000000; \/\/ kein alpha blending\n                    destData.setPixelColour(readpos,m_internalHeight-1-hh,juce::Colour(color));\n                }\n                startread++;\n            }\n            int drawwidth = 1;\n            if (m_internalHeight < 2048)\n                drawwidth++;\n\n            if (m_internalHeight < 1024)\n                drawwidth +=2 ;\n            for (size_t hh = 0; hh < m_internalHeight; ++hh)\n            {\n\n                for (int dd = 0 ; dd < drawwidth ;++dd)\n                {\n                    int drawpos = pos+dd;\n                    if (drawpos == m_internalWidth)\n                        drawpos -= m_internalWidth;\n                    destData.setPixelColour(drawpos,m_internalHeight-1-hh,juce::Colours::red);\n\n                }\n            }\n\n        }\n        \n    }\n    \n    crit.exit();\n\n    m_hideFFTSizeCombobox = m_editor.getRunningStatus();\n    \n    repaint();\n}\nvoid SpectrogramComponent::pauseClicked()\n{\n    m_isPaused = !m_isPaused;\n    m_spectrogram.setPauseMode(m_isPaused);\n    if (m_isPaused)\n    {\n        m_pauseButton.setToggleState(true,NotificationType::dontSendNotification);\n    }\n    else\n    {\n        m_pauseButton.setToggleState(false,NotificationType::dontSendNotification);\n    }\n}\nvoid SpectrogramComponent::runClicked()\n{\n    m_isRunningDisplay = !m_isRunningDisplay;\n    \n    if (m_isRunningDisplay)\n    {\n        m_runModeButton.setButtonText(\"Fix\");\n        m_runModeButton.setToggleState(false,NotificationType::dontSendNotification);\n    }\n    else\n    {\n        m_runModeButton.setButtonText(\"Run\");\n        m_runModeButton.setToggleState(true,NotificationType::dontSendNotification);\n    }\n}\nvoid SpectrogramComponent::changeFFTSize()\n{\n    auto FFTSizeIndex = m_fftSizeCombo.getSelectedItemIndex();\n    int fftSize = pow(2.0,9+FFTSizeIndex);\n    \n    \/\/DBG(String(fftSize));\n    stopTimer();\n    m_spectrogram.setFFTSize(fftSize);\n    startTimer(40);\n}\n\nvoid SpectrogramComponent::mouseMove (const MouseEvent& event)\n{\n    int x = event.getMouseDownX();\n    int y = event.getMouseDownY();\n\n    int w = getWidth();\n    int h = getHeight();\n    int wstart = m_scaleFactor*(g_FreqMeter+g_SliderMaxFreq_x+g_SliderWidth);\n    if (y < h-m_scaleFactor*g_ButtonHeight && x > wstart && x < wstart + 0.8*w)\n    {\n        float freq = (1.0-float(y)\/(float(h)-m_scaleFactor*g_ButtonHeight))*(m_maxDisplayFreq - m_minDisplayFreq)+m_minDisplayFreq;\n        MidiMessage msg;\n        int midinotenumber =  int(log(freq\/440.0)\/log(2) * 12 + 69 + 0.5);\n        String midiNoteName = msg.getMidiNoteName(midinotenumber,true,true,4);\n\n        m_FreqLabel.setText(String(int(freq+0.5)) + String(\" Hz | \") + midiNoteName,juce::NotificationType::dontSendNotification);\n\n    }\n\n\n}\n\nint SpectrogramParameter::addParameter(std::vector < std::unique_ptr<RangedAudioParameter>>& paramVector)\n{\n       \tparamVector.push_back(std::make_unique<AudioParameterFloat>(paramDisplayMinFreq.ID,\n\t\tparamDisplayMinFreq.name,\n\t\tNormalisableRange<float>(paramDisplayMinFreq.minValue, paramDisplayMinFreq.maxValue),\n\t\tparamDisplayMinFreq.defaultValue,\n\t\tparamDisplayMinFreq.unitName,\n\t\tAudioProcessorParameter::genericParameter,\n\t\t[](float value, int MaxLen) { return (String(0.1*int(exp(value)*10 + 0.5), MaxLen)); },\n\t\t[](const String& text) {return text.getFloatValue(); }));\n\n       \tparamVector.push_back(std::make_unique<AudioParameterFloat>(paramDisplayMaxFreq.ID,\n\t\tparamDisplayMaxFreq.name,\n\t\tNormalisableRange<float>(paramDisplayMaxFreq.minValue, paramDisplayMaxFreq.maxValue),\n\t\tparamDisplayMaxFreq.defaultValue,\n\t\tparamDisplayMaxFreq.unitName,\n\t\tAudioProcessorParameter::genericParameter,\n\t\t[](float value, int MaxLen) { return (String(0.1*int(exp(value)*10 + 0.5), MaxLen)); },\n\t\t[](const String& text) {return text.getFloatValue(); }));\n\n       \tparamVector.push_back(std::make_unique<AudioParameterFloat>(paramDisplayMinColor.ID,\n\t\tparamDisplayMinColor.name,\n\t\tNormalisableRange<float>(paramDisplayMinColor.minValue, paramDisplayMinColor.maxValue),\n\t\tparamDisplayMinColor.defaultValue,\n\t\tparamDisplayMinColor.unitName,\n\t\tAudioProcessorParameter::genericParameter,\n\t\t[](float value, int MaxLen) { return (String(1.0*int((value) + 0.5), MaxLen)); },\n\t\t[](const String& text) {return text.getFloatValue(); }));\n\n       \tparamVector.push_back(std::make_unique<AudioParameterFloat>(paramDisplayMaxColor.ID,\n\t\tparamDisplayMaxColor.name,\n\t\tNormalisableRange<float>(paramDisplayMaxColor.minValue, paramDisplayMaxColor.maxValue),\n\t\tparamDisplayMaxColor.defaultValue,\n\t\tparamDisplayMaxColor.unitName,\n\t\tAudioProcessorParameter::genericParameter,\n\t\t[](float value, int MaxLen) { return (String(1.0*int((value) + 0.5), MaxLen)); },\n\t\t[](const String& text) {return text.getFloatValue(); }));\n\/\/*\/\n    return 0;\n}\n","avg_line_length":37.6266506603,"max_line_length":153,"alphanum_fraction":0.6418019973,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1988,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ TestEngine.cpp : \ucf58\uc194 \uc751\uc6a9 \ud504\ub85c\uadf8\ub7a8\uc5d0 \ub300\ud55c \uc9c4\uc785\uc810\uc744 \uc815\uc758\ud569\ub2c8\ub2e4.\n\/\/\n\n#include \"stdafx.h\"\n#include <stdio.h> \n#include <windows.h> \n#include \"SkyMockInterface.h\"\n#include \"I_Compress.h\"\n#include <iostream>\n\nextern SKY_FILE_Interface g_FileInterface;\nextern SKY_ALLOC_Interface g_allocInterface;\nextern SKY_Print_Interface g_printInterface;\n\ntypedef void (*PSetSkyMockInterface)(SKY_ALLOC_Interface, SKY_FILE_Interface, SKY_Print_Interface);\ntypedef I_Compress* (*PGetZlibCompress)();\n\n\nvoid* GetModuleFunction(HINSTANCE handle, const char* func_name)\n{\n\treturn (void*)GetProcAddress(handle, func_name);\n}\n\nint main()\n{\n\tHINSTANCE dllHandle = NULL;\n\n\t\/\/\ub514\ubc84\uadf8\uc5d4\uc9c4 \ubaa8\ub4c8\uc744 \ub85c\ub4dc\ud55c\ub2e4.\n\tdllHandle = LoadLibrary(\"zlib128.dll\");\n\n\tPSetSkyMockInterface SetSkyMockInterface = (PSetSkyMockInterface)GetModuleFunction(dllHandle, \"SetSkyMockInterface\");\n\tPGetZlibCompress GetZlibCompress = (PGetZlibCompress)GetModuleFunction(dllHandle, \"GetZlibCompress\");\n\n\t\/\/SetSkyMockInterface \ud568\uc218\ub97c \uc0ac\uc6a9\ud574\uc11c \ub514\ubc84\uadf8\uc5d4\uc9c4 \ubaa8\ub4c8\uc5d0 \ud30c\uc77c\uc778\ud130\ud398\uc774\uc2a4\uc640 \uc785\ucd9c\ub825, \ud654\uba74\ucd9c\ub825 \uc778\ud130\ud398\uc774\uc2a4\ub97c \uc81c\uacf5\ud55c\ub2e4.\n\tSetSkyMockInterface(g_allocInterface, g_FileInterface, g_printInterface);\n\tI_Compress* pCompress = GetZlibCompress();\n\n\tconst  int BUF = 1024;\n\tconst  int DBUF = BUF * 2 + 13;\n\n\tbyte raw_data[] = \"Hello Zlib 1.28!!!\";\n\tbyte deflate_data[DBUF];\n\n\tunsigned long raw_size = strlen((const  char*)raw_data);\n\tunsigned long deflate_size = DBUF;\n\n\t\/\/compress \uc0ac\uc6a9\ud558\uae30\n\t{\n\t\tpCompress->Compress(deflate_data, (long*)&deflate_size, raw_data, raw_size);\n\t\tstd::cout << \"Raw Data Size:\" << raw_size << std::endl;\n\t\tstd::cout << \"Deflate Data Size:\" << deflate_size << std::endl;\n\t}\n\n\tbyte inflate_data[BUF];\n\tunsigned long inflate_size = BUF;\n\t\/\/uncompress \uc0ac\uc6a9\ud558\uae30\n\t{\n\t\tpCompress->Decompress(inflate_data, (long*)&inflate_size, deflate_data, deflate_size);\n\t\tstd::cout << \"Deflate Data Size:\" << deflate_size << std::endl;\n\t\tstd::cout << \"Inflate Size:\" << inflate_size << std::endl;\n\t\tinflate_data[inflate_size] = NULL;\n\t\tstd::cout << \"original data : \" << (const  char*)inflate_data << std::endl;\n\t}\n\n\n\treturn 0;\n}\n\n","avg_line_length":28.8115942029,"max_line_length":118,"alphanum_fraction":0.7414486922,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4223,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":10.0,"content":"\/\/\n\/\/ Created by salmon on 17-10-23.\n\/\/\n#include \"Axis.h\"\n#include <simpla\/data\/Serializable.h>\nnamespace simpla {\nnamespace geometry {\nAxis::Axis(Axis const &other) : data::Configurable(other), m_Origin_(other.m_Origin_), m_axis_(other.m_axis_) {}\nvoid Axis::Mirror(const point_type &p) { UNIMPLEMENTED; }\nvoid Axis::Mirror(const Axis &a1) { UNIMPLEMENTED; }\nvoid Axis::Rotate(const Axis &a1, Real angle) { UNIMPLEMENTED; }\nvoid Axis::Rotate(vector_type const &u, Real angle) {\n    Real ux = u[0];\n    Real uy = u[1];\n    Real uz = u[2];\n    Real cosA = std::cos(angle);\n    Real sinA = std::sin(angle);\n    Real i_u2 = 1.0 \/ dot(u, u);\n    \/** @ref https:\/\/en.wikipedia.org\/wiki\/Rotation_matrix\n     *  Rotation matrix from axis and angle\n     *  \\f[\n     *  {\\displaystyle R={\\begin{bmatrix}\\cos \\theta +u_{x}^{2}\\left(1-\\cos \\theta \\right)&u_{x}u_{y}\\left(1-\\cos\n     * \\theta\n     * \\right)-u_{z}\\sin \\theta &u_{x}u_{z}\\left(1-\\cos \\theta \\right)+u_{y}\\sin \\theta \\\\u_{y}u_{x}\\left(1-\\cos\n     * \\theta\n     * \\right)+u_{z}\\sin \\theta &\\cos \\theta +u_{y}^{2}\\left(1-\\cos \\theta \\right)&u_{y}u_{z}\\left(1-\\cos \\theta\n     * \\right)-u_{x}\\sin \\theta \\\\u_{z}u_{x}\\left(1-\\cos \\theta \\right)-u_{y}\\sin \\theta &u_{z}u_{y}\\left(1-\\cos\n     * \\theta\n     * \\right)+u_{x}\\sin \\theta &\\cos \\theta +u_{z}^{2}\\left(1-\\cos \\theta \\right)\\end{bmatrix}}.}\n     *  \\f]\n     *\/\n    \/\/    Matrix<Real, 3, 3> R = {\n    \/\/        {cosA + ux * ux * (1 - cosA), ux * uy * (1 - cosA) - uz * sinA, ux * uz * (1 - cosA) + uy * sinA},\n    \/\/        {uy * ux * (1 - cosA) + uz * sinA, cosA + uy * uy * (1 - cosA), uy * uz * (1 - cosA) - ux * sinA},\n    \/\/        {uz * ux * (1 - cosA) - uy * sinA, uz * uy * (1 - cosA) + ux * sinA, cosA + uz * uz * (1 - cosA)}};\n    \/\/    R \/= ux * ux + uy * uy + uz * uz;\n    \/\/    m_axis_[0] = point_type{dot(m_axis_[0], R[0]), dot(m_axis_[0], R[1]), dot(m_axis_[0], R[2])};\n    \/\/    m_axis_[1] = point_type{dot(m_axis_[1], R[0]), dot(m_axis_[1], R[1]), dot(m_axis_[1], R[2])};\n    \/\/    m_axis_[2] = point_type{dot(m_axis_[2], R[0]), dot(m_axis_[2], R[1]), dot(m_axis_[2], R[2])};\n\n    m_axis_[0] = (cosA * m_axis_[0] + sinA * cross(u, m_axis_[0]) + (1 - cosA) * dot(u, m_axis_[0]) * u) * i_u2;\n    m_axis_[1] = (cosA * m_axis_[1] + sinA * cross(u, m_axis_[1]) + (1 - cosA) * dot(u, m_axis_[1]) * u) * i_u2;\n    m_axis_[2] = (cosA * m_axis_[2] + sinA * cross(u, m_axis_[2]) + (1 - cosA) * dot(u, m_axis_[2]) * u) * i_u2;\n}\n\nvoid Axis::Scale(Real s, int dir) {\n    if (dir < 0) {\n        m_axis_ *= s;\n    } else {\n        m_axis_[dir % 3] *= s;\n    }\n}\nvoid Axis::Translate(const vector_type &v) { m_Origin_ += v; }\nvoid Axis::Translate(Axis const &other) {\n    m_Origin_ += other.m_Origin_;\n    matrix_type t_axis = m_axis_;\n    m_axis_[0] = other.m_axis_[0][0] * t_axis[0] + other.m_axis_[0][1] * t_axis[1] + other.m_axis_[0][2] * t_axis[2];\n    m_axis_[1] = other.m_axis_[1][0] * t_axis[1] + other.m_axis_[1][1] * t_axis[1] + other.m_axis_[1][2] * t_axis[2];\n    m_axis_[2] = other.m_axis_[2][0] * t_axis[2] + other.m_axis_[2][1] * t_axis[1] + other.m_axis_[2][2] * t_axis[2];\n}\nvoid Axis::Shift(const point_type &o_uvw) { m_Origin_ += xyz(o_uvw); }\nAxis Axis::Shifted(const point_type &o_uvw) const {\n    Axis res(*this);\n    res.Shift(o_uvw);\n    return std::move(res);\n}\nvoid Axis::Move(const point_type &o_xyz) { m_Origin_ = o_xyz; }\nAxis Axis::Moved(const point_type &o_xyz) const {\n    Axis res(*this);\n    res.Move(o_xyz);\n    return std::move(res);\n}\n\n\/\/\n\/\/ std::shared_ptr<spPlane> Axis::GetPlane(int n) const {\n\/\/    return spPlane::New(Axis{o, m_axis_[(n + 1) % 3], m_axis_[(n + 2) % 3]});\n\/\/}\n\/\/ std::shared_ptr<spPlane> Axis::GetPlaneXY() const { return GetPlane(2); }\n\/\/ std::shared_ptr<spPlane> Axis::GetPlaneYZ() const { return GetPlane(1); }\n\/\/ std::shared_ptr<spPlane> Axis::GetPlaneZX() const { return GetPlane(0); }\n\/\/ std::shared_ptr<spLine> Axis::GetAxe(int n) const { return spLine::New(Axis{o, m_axis_[n]}); }\n\/\/ std::shared_ptr<spLine> Axis::GetPlaneX() const { return GetAxe(0); }\n\/\/ std::shared_ptr<spLine> Axis::GetPlaneY() const { return GetAxe(0); }\n\/\/ std::shared_ptr<spLine> Axis::GetPlaneZ() const { return GetAxe(0); }\n\n}  \/\/ namespace geometry{\n}  \/\/ namespace simpla{","avg_line_length":48.5402298851,"max_line_length":117,"alphanum_fraction":0.5860762491,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":598,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Frontend constructs\n\n#include \"frontend.h\"\n#include \"taichi\/program\/program.h\"\n\nTLANG_NAMESPACE_BEGIN\n\nvoid layout(const std::function<void()> &body) {\n  get_current_program().layout(body);\n}\n\nExpr global_new(Expr id_expr, DataType dt) {\n  TI_ASSERT(id_expr.is<IdExpression>());\n  auto ret = Expr(std::make_shared<GlobalVariableExpression>(\n      dt, id_expr.cast<IdExpression>()->id));\n  return ret;\n}\n\nExpr global_new(DataType dt, std::string name) {\n  auto id_expr = std::make_shared<IdExpression>(name);\n  return Expr::make<GlobalVariableExpression>(dt, id_expr->id);\n}\n\nTLANG_NAMESPACE_END\n","avg_line_length":23.92,"max_line_length":63,"alphanum_fraction":0.7391304348,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":409,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Zlib"],"max_stars_count":null,"content":"#include \"tgaimage.h\"\n\nconst TGAColor white = TGAColor(255, 255, 255, 255);\nconst TGAColor red   = TGAColor(255, 0,   0,   255);\n\nint main(int argc, char** argv) {\n        TGAImage image(100, 100, TGAImage::RGB);\n        image.set(52, 41, red);\n        image.flip_vertically(); \/\/ i want to have the origin at the left bottom corner of the image\n        image.write_tga_file(\"output.tga\");\n        return 0;\n}","avg_line_length":34.0833333333,"max_line_length":100,"alphanum_fraction":0.6332518337,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":20440,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/******************************************************************************\\\nCopyright (c) 2005-2019, Intel Corporation\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. 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.\n\n3. 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.\n\nTHIS 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.\n\nThis sample was distributed or derived from the Intel's Media Samples package.\nThe original version of this sample may be obtained from https:\/\/software.intel.com\/en-us\/intel-media-server-studio\nor https:\/\/software.intel.com\/en-us\/media-client-solutions-support.\n\\**********************************************************************************\/\n\n#include \"auxiliary_interfaces.h\"\n\n#ifndef MFX_VERSION\n#error MFX_VERSION not defined\n#endif\n\nMFX_VppInterface::MFX_VppInterface(MFXVideoSession* session, mfxU32 allocId, AppConfig* config)\n    : m_pmfxSession(session)\n    , m_pmfxVPP(new MFXVideoVPP(*session))\n    , m_allocId(allocId)\n    , m_pAppConfig(config)\n    , m_SyncPoint(0)\n{\n    MSDK_ZERO_MEMORY(m_videoParams);\n\n    m_InitExtParams.reserve(1);\n}\n\nMFX_VppInterface::~MFX_VppInterface()\n{\n    MSDK_SAFE_DELETE(m_pmfxVPP);\n\n    for (mfxU32 i = 0; i < m_InitExtParams.size(); ++i)\n    {\n        switch (m_InitExtParams[i]->BufferId)\n        {\n        case MFX_EXTBUFF_VPP_DONOTUSE:\n            mfxExtVPPDoNotUse* ptr = reinterpret_cast<mfxExtVPPDoNotUse*>(m_InitExtParams[i]);\n            MSDK_SAFE_DELETE_ARRAY(ptr->AlgList);\n            MSDK_SAFE_DELETE(ptr);\n            break;\n        }\n    }\n    m_InitExtParams.clear();\n\n    m_pAppConfig->PipelineCfg.pVppVideoParam = NULL;\n}\n\nmfxStatus MFX_VppInterface::Init()\n{\n    return m_pmfxVPP->Init(&m_videoParams);\n}\n\nmfxStatus MFX_VppInterface::Close()\n{\n    return m_pmfxVPP->Close();\n}\n\nmfxVideoParam* MFX_VppInterface::GetCommonVideoParams()\n{\n    return &m_videoParams;\n}\n\nmfxStatus MFX_VppInterface::Reset(mfxU16 width, mfxU16 height, mfxU16 crop_w, mfxU16 crop_h)\n{\n    if (width && height && crop_w && crop_h)\n    {\n        m_videoParams.vpp.Out.Width  = width;\n        m_videoParams.vpp.Out.Height = height;\n        m_videoParams.vpp.Out.CropW  = crop_w;\n        m_videoParams.vpp.Out.CropH  = crop_h;\n    }\n    return m_pmfxVPP->Reset(&m_videoParams);\n}\n\nmfxStatus MFX_VppInterface::QueryIOSurf(mfxFrameAllocRequest* request)\n{\n    return m_pmfxVPP->QueryIOSurf(&m_videoParams, request);\n}\n\nmfxStatus MFX_VppInterface::FillParameters()\n{\n    mfxStatus sts = MFX_ERR_NONE;\n\n    \/* Share VPP video parameters with other interfaces *\/\n    m_pAppConfig->PipelineCfg.pVppVideoParam = &m_videoParams;\n\n    m_videoParams.AllocId   = m_allocId;\n    \/\/ specify memory type\n    m_videoParams.IOPattern = mfxU16(m_pAppConfig->bUseHWmemory ? (MFX_IOPATTERN_IN_VIDEO_MEMORY | MFX_IOPATTERN_OUT_VIDEO_MEMORY)\n        : (MFX_IOPATTERN_IN_SYSTEM_MEMORY | MFX_IOPATTERN_OUT_SYSTEM_MEMORY));\n    m_videoParams.AsyncDepth = 1;\n\n    if (m_pAppConfig->bDECODE)\n    {\n        \/* Decoder present in pipeline *\/\n        MSDK_MEMCPY_VAR(m_videoParams.vpp.In, &m_pAppConfig->PipelineCfg.pDecodeVideoParam->mfx.FrameInfo, sizeof(mfxFrameInfo));\n        m_videoParams.vpp.In.PicStruct = m_pAppConfig->nPicStruct;\n    }\n    else\n    {\n        \/* No other instances before PreENC DownSampling. Fill VideoParams *\/\n\n        \/\/ input frame info\n        m_videoParams.vpp.In.FourCC       = MFX_FOURCC_NV12;\n        m_videoParams.vpp.In.ChromaFormat = MFX_CHROMAFORMAT_YUV420;\n        m_videoParams.vpp.In.PicStruct    = m_pAppConfig->nPicStruct;\n\n        sts = ConvertFrameRate(m_pAppConfig->dFrameRate, &m_videoParams.vpp.In.FrameRateExtN, &m_videoParams.vpp.In.FrameRateExtD);\n        MSDK_CHECK_STATUS(sts, \"ConvertFrameRate failed\");\n\n        \/\/ width must be a multiple of 16\n        \/\/ height must be a multiple of 16 in case of frame picture and a multiple of 32 in case of field picture\n        m_videoParams.vpp.In.Width = MSDK_ALIGN16(m_pAppConfig->nWidth);\n        m_videoParams.vpp.In.Height = (MFX_PICSTRUCT_PROGRESSIVE & m_videoParams.vpp.In.PicStruct) ?\n            MSDK_ALIGN16(m_pAppConfig->nHeight) : MSDK_ALIGN32(m_pAppConfig->nHeight);\n\n        \/\/ set crops in input mfxFrameInfo for correct work of file reader\n        \/\/ VPP itself ignores crops at initialization\n        m_videoParams.vpp.In.CropX = m_videoParams.vpp.In.CropY = 0;\n        m_videoParams.vpp.In.CropW = m_pAppConfig->nWidth;\n        m_videoParams.vpp.In.CropH = m_pAppConfig->nHeight;\n    }\n\n    \/\/ fill output frame info\n    MSDK_MEMCPY_VAR(m_videoParams.vpp.Out, &m_videoParams.vpp.In, sizeof(mfxFrameInfo));\n\n    \/\/ only resizing is supported\n    m_videoParams.vpp.Out.CropX = m_videoParams.vpp.Out.CropY = 0;\n    m_videoParams.vpp.Out.Width = MSDK_ALIGN16(m_pAppConfig->nDstWidth);\n    m_videoParams.vpp.Out.Height = (MFX_PICSTRUCT_PROGRESSIVE & m_videoParams.vpp.Out.PicStruct) ?\n        MSDK_ALIGN16(m_pAppConfig->nDstHeight) : MSDK_ALIGN32(m_pAppConfig->nDstHeight);\n    m_videoParams.vpp.Out.CropW = m_pAppConfig->nDstWidth;\n    m_videoParams.vpp.Out.CropH = m_pAppConfig->nDstHeight;\n\n\n\n    \/\/ configure and attach external parameters\n    mfxExtVPPDoNotUse* m_VppDoNotUse = new mfxExtVPPDoNotUse;\n    MSDK_ZERO_MEMORY(*m_VppDoNotUse);\n    m_VppDoNotUse->Header.BufferId = MFX_EXTBUFF_VPP_DONOTUSE;\n    m_VppDoNotUse->Header.BufferSz = sizeof(mfxExtVPPDoNotUse);\n    m_VppDoNotUse->NumAlg = 4;\n\n    m_VppDoNotUse->AlgList = new mfxU32[m_VppDoNotUse->NumAlg];\n    m_VppDoNotUse->AlgList[0] = MFX_EXTBUFF_VPP_DENOISE;        \/\/ turn off denoising (on by default)\n    m_VppDoNotUse->AlgList[1] = MFX_EXTBUFF_VPP_SCENE_ANALYSIS; \/\/ turn off scene analysis (on by default)\n    m_VppDoNotUse->AlgList[2] = MFX_EXTBUFF_VPP_DETAIL;         \/\/ turn off detail enhancement (on by default)\n    m_VppDoNotUse->AlgList[3] = MFX_EXTBUFF_VPP_PROCAMP;        \/\/ turn off processing amplified (on by default)\n    m_InitExtParams.push_back(reinterpret_cast<mfxExtBuffer *>(m_VppDoNotUse));\n\n    m_videoParams.ExtParam    = &m_InitExtParams[0]; \/\/ vector is stored linearly in memory\n    m_videoParams.NumExtParam = (mfxU16)m_InitExtParams.size();\n\n    return sts;\n}\n\nmfxStatus MFX_VppInterface::VPPoneFrame(mfxFrameSurface1* pSurf_in, mfxFrameSurface1* pSurf_out)\n{\n    mfxStatus sts = MFX_ERR_NONE;\n\n    \/\/ VPP DS goes below\n    for (;;)\n    {\n        sts = m_pmfxVPP->RunFrameVPPAsync(pSurf_in, pSurf_out, NULL, &m_SyncPoint);\n        MSDK_CHECK_WRN(sts, \"WRN during RunFrameVPPAsync\");\n\n        if (MFX_ERR_NONE < sts && !m_SyncPoint)\n        {\n            \/\/ Repeat the call if warning and no output\n\n            if (MFX_WRN_DEVICE_BUSY == sts){\n                WaitForDeviceToBecomeFree(*m_pmfxSession, m_SyncPoint, sts);\n            }\n        }\n        else if (MFX_ERR_NONE < sts && m_SyncPoint)\n        {\n            sts = m_pmfxSession->SyncOperation(m_SyncPoint, MSDK_WAIT_INTERVAL);\n            MSDK_CHECK_ERR_NONE_STATUS(sts, MFX_ERR_ABORTED, \"VPP: SyncOperation failed\");\n            mdprintf(stderr, \"VPP synced : %d\\n\", sts);\n\n            break;\n        }\n        else\n        {\n            \/\/ Break if error\n            MSDK_BREAK_ON_ERROR(sts);\n\n            if (m_SyncPoint)\n            {\n                sts = m_pmfxSession->SyncOperation(m_SyncPoint, MSDK_WAIT_INTERVAL);\n                MSDK_CHECK_ERR_NONE_STATUS(sts, MFX_ERR_ABORTED, \"VPP: SyncOperation failed\");\n                mdprintf(stderr, \"VPP synced : %d\\n\", sts);\n            }\n\n            break;\n        }\n    }\n\n    return sts;\n}\n\n\nMFX_DecodeInterface::MFX_DecodeInterface(MFXVideoSession* session, mfxU32 allocId, AppConfig* config, ExtSurfPool* surf_pool)\n    : m_pmfxSession(session)\n    , m_pmfxDECODE(new MFXVideoDECODE(*session))\n    , m_allocId(allocId)\n    , m_pAppConfig(config)\n    , m_SyncPoint(0)\n    , m_pSurfPool(surf_pool)\n    , m_bEndOfFile(false)\n    , m_DecStremout_out(NULL)\n{\n    MSDK_ZERO_MEMORY(m_mfxBS);\n    MSDK_ZERO_MEMORY(m_videoParams);\n\n    m_InitExtParams.reserve(1);\n}\n\nMFX_DecodeInterface::~MFX_DecodeInterface()\n{\n    MSDK_SAFE_DELETE(m_pmfxDECODE);\n\n    for (mfxU32 i = 0; i < m_InitExtParams.size(); ++i)\n    {\n        switch (m_InitExtParams[i]->BufferId)\n        {\n        case MFX_EXTBUFF_FEI_PARAM:\n            mfxExtFeiParam* ptr = reinterpret_cast<mfxExtFeiParam*>(m_InitExtParams[i]);\n            MSDK_SAFE_DELETE(ptr);\n            break;\n        }\n    }\n    m_InitExtParams.clear();\n\n    WipeMfxBitstream(&m_mfxBS);\n\n    SAFE_FCLOSE(m_DecStremout_out);\n\n    m_pAppConfig->PipelineCfg.pDecodeVideoParam = NULL;\n}\n\nmfxStatus MFX_DecodeInterface::Init()\n{\n    return m_pmfxDECODE->Init(&m_videoParams);\n}\n\nmfxStatus MFX_DecodeInterface::Close()\n{\n    return m_pmfxDECODE->Close();\n}\n\nmfxStatus MFX_DecodeInterface::Reset()\n{\n    return m_pmfxDECODE->Reset(&m_videoParams);\n}\n\nmfxStatus MFX_DecodeInterface::QueryIOSurf(mfxFrameAllocRequest* request)\n{\n    return m_pmfxDECODE->QueryIOSurf(&m_videoParams, request);\n}\n\nmfxVideoParam* MFX_DecodeInterface::GetCommonVideoParams()\n{\n    return &m_videoParams;\n}\n\nmfxStatus MFX_DecodeInterface::UpdateVideoParam()\n{\n    return m_pmfxDECODE->GetVideoParam(&m_videoParams);\n}\n\nmfxStatus MFX_DecodeInterface::FillParameters()\n{\n    mfxStatus sts = MFX_ERR_NONE;\n\n    \/* Share DECODE video parameters with other interfaces *\/\n    m_pAppConfig->PipelineCfg.pDecodeVideoParam = &m_videoParams;\n\n    m_videoParams.AsyncDepth = 1;\n    m_videoParams.AllocId = m_allocId;\n\n    \/\/ set video type in parameters\n    m_videoParams.mfx.CodecId = m_pAppConfig->DecodeId;\n    m_videoParams.mfx.DecodedOrder = mfxU16(m_pAppConfig->DecodedOrder);\n\n    sts = m_BSReader.Init(m_pAppConfig->strSrcFile);\n    MSDK_CHECK_STATUS(sts, \"m_BSReader.Init failed\");\n\n    sts = InitMfxBitstream(&m_mfxBS, 1024 * 1024);\n    MSDK_CHECK_STATUS(sts, \"InitMfxBitstream failed\");\n\n    \/\/ read a portion of data for DecodeHeader function\n    sts = m_BSReader.ReadNextFrame(&m_mfxBS);\n    if (MFX_ERR_MORE_DATA == sts)\n        return sts;\n    MSDK_CHECK_STATUS(sts, \"m_BSReader.ReadNextFrame failed\");\n\n    \/\/ try to find a sequence header in the stream\n    \/\/ if header is not found this function exits with error (e.g. if device was lost and there's no header in the remaining stream)\n    for (;;)\n    {\n        \/\/ parse bit stream and fill mfx params\n        sts = m_pmfxDECODE->DecodeHeader(&m_mfxBS, &m_videoParams);\n\n        if (MFX_ERR_MORE_DATA == sts)\n        {\n            if (m_mfxBS.MaxLength == m_mfxBS.DataLength)\n            {\n                sts = ExtendMfxBitstream(&m_mfxBS, m_mfxBS.MaxLength * 2);\n                MSDK_CHECK_STATUS(sts, \"ExtendMfxBitstream failed\");\n            }\n\n            \/\/ read a portion of data for DecodeHeader function\n            sts = m_BSReader.ReadNextFrame(&m_mfxBS);\n            if (MFX_ERR_MORE_DATA == sts)\n                return sts;\n            MSDK_CHECK_STATUS(sts, \"m_BSReader.ReadNextFrame failed\");\n\n            continue;\n        }\n        else\n            break;\n    }\n\n    \/\/ if input stream header doesn't contain valid values use default (30.0)\n    if (0 == (m_videoParams.mfx.FrameInfo.FrameRateExtN * m_videoParams.mfx.FrameInfo.FrameRateExtD))\n    {\n        m_videoParams.mfx.FrameInfo.FrameRateExtN = 30;\n        m_videoParams.mfx.FrameInfo.FrameRateExtD = 1;\n    }\n\n    if (m_pAppConfig->nPicStruct == MFX_PICSTRUCT_UNKNOWN)\n    {\n        \/\/ In this case we acquire picture structure from the input stream\n        m_videoParams.mfx.ExtendedPicStruct = 1;\n    }\n\n    \/\/ specify memory type\n    m_videoParams.IOPattern = MFX_IOPATTERN_OUT_VIDEO_MEMORY;\n\n    if (m_pAppConfig->bDECODESTREAMOUT)\n    {\n        mfxExtFeiParam* decStreamoutParams = new mfxExtFeiParam;\n        MSDK_ZERO_MEMORY(*decStreamoutParams);\n        decStreamoutParams->Header.BufferId = MFX_EXTBUFF_FEI_PARAM;\n        decStreamoutParams->Header.BufferSz = sizeof(mfxExtFeiParam);\n        decStreamoutParams->Func = MFX_FEI_FUNCTION_DEC;\n        decStreamoutParams->SingleFieldProcessing = MFX_CODINGOPTION_OFF;\n\n        m_InitExtParams.push_back(reinterpret_cast<mfxExtBuffer*>(decStreamoutParams));\n\n        m_videoParams.NumExtParam = (mfxU16)m_InitExtParams.size();\n        m_videoParams.ExtParam = &m_InitExtParams[0];\n    }\n\n    if (m_pAppConfig->decodestreamoutFile)\n    {\n        MSDK_FOPEN(m_DecStremout_out, m_pAppConfig->decodestreamoutFile, MSDK_CHAR(\"wb\"));\n        if (m_DecStremout_out == NULL) {\n            mdprintf(stderr, \"Can't open file %s\\n\", m_pAppConfig->decodestreamoutFile);\n            exit(-1);\n        }\n    }\n\n    return sts;\n}\n\nmfxStatus MFX_DecodeInterface::GetOneFrame(mfxFrameSurface1* & pSurf)\n{\n    MFX_ITT_TASK(\"GetOneFrame\");\n\n    mfxStatus sts = MFX_ERR_NONE;\n\n    for (;;)\n    {\n        if (!m_bEndOfFile)\n        {\n            sts = DecodeOneFrame(pSurf);\n            if (MFX_ERR_MORE_DATA == sts)\n            {\n                sts = DecodeLastFrame(pSurf);\n                m_bEndOfFile = true;\n            }\n        }\n        else\n        {\n            sts = DecodeLastFrame(pSurf);\n        }\n        MSDK_CHECK_WRN(sts, \"WRN during Decode<One|Last>Frame\");\n\n        if (MFX_ERR_NONE < sts && !m_SyncPoint)\n        {\n            \/\/ Repeat the call if warning and no output\n\n            if (MFX_WRN_DEVICE_BUSY == sts){\n                WaitForDeviceToBecomeFree(*m_pmfxSession, m_SyncPoint, sts);\n            }\n        }\n        else if (MFX_ERR_NONE < sts && m_SyncPoint)\n        {\n            sts = m_pmfxSession->SyncOperation(m_SyncPoint, MSDK_WAIT_INTERVAL);\n            MSDK_CHECK_ERR_NONE_STATUS(sts, MFX_ERR_ABORTED, \"Decode: SyncOperation failed\");\n            mdprintf(stderr, \"DECODE synced : %d\\n\", sts);\n\n            break;\n        }\n        else if (sts == MFX_ERR_MORE_DATA && m_pAppConfig->nTimeout)\n        {\n            \/\/ Infinite loop mode, need to proceed from the beginning\n            return MFX_ERR_MORE_DATA;\n        }\n        else\n        {\n            \/\/ Break if error\n            MSDK_BREAK_ON_ERROR(sts);\n\n            if (m_SyncPoint)\n            {\n                sts = m_pmfxSession->SyncOperation(m_SyncPoint, MSDK_WAIT_INTERVAL);\n                MSDK_CHECK_ERR_NONE_STATUS(sts, MFX_ERR_ABORTED, \"Decode: SyncOperation failed\");\n                mdprintf(stderr, \"DECODE synced : %d\\n\", sts);\n            }\n\n            break;\n        }\n    }\n    if (sts == MFX_ERR_MORE_DATA)\n    {\n        return sts;\n    }\n    MSDK_CHECK_STATUS(sts, \"Decode<One|Last>Frame failed\");\n\n    if (m_pAppConfig->bDECODESTREAMOUT)\n    {\n        sts = FlushOutput(pSurf);\n        MSDK_CHECK_STATUS(sts, \"DECODE: FlushOutput failed\");\n    }\n\n    return sts;\n}\n\nmfxStatus MFX_DecodeInterface::DecodeOneFrame(mfxFrameSurface1 * & pSurf_out)\n{\n    MFX_ITT_TASK(\"DecodeOneFrame\");\n\n    mfxStatus sts = MFX_ERR_MORE_SURFACE;\n    mfxFrameSurface1 *pDecSurf = NULL;\n\n    while (MFX_ERR_MORE_DATA == sts || MFX_ERR_MORE_SURFACE == sts || MFX_ERR_NONE < sts)\n    {\n        switch (sts)\n        {\n        case MFX_WRN_DEVICE_BUSY:\n            WaitForDeviceToBecomeFree(*m_pmfxSession, m_SyncPoint, sts);\n            break;\n\n        case MFX_ERR_MORE_DATA:\n            sts = m_BSReader.ReadNextFrame(&m_mfxBS); \/\/ read more data to input bit stream\n            if (sts == MFX_ERR_MORE_DATA) { return sts; } \/\/ Reached end of bitstream\n            break;\n\n        case MFX_ERR_MORE_SURFACE:\n            \/\/ find free surface for decoder input\n            pDecSurf = m_pSurfPool->GetFreeSurface_FEI();\n            MSDK_CHECK_POINTER(pDecSurf, MFX_ERR_MEMORY_ALLOC); \/\/ return an error if a free surface wasn't found\n            break;\n\n        default:\n            break;\n        }\n\n        sts = m_pmfxDECODE->DecodeFrameAsync(&m_mfxBS, pDecSurf, &pSurf_out, &m_SyncPoint);\n\n        if (MFX_ERR_NONE < sts && m_SyncPoint)\n        {\n            \/\/ Ignore warnings if output is available\n            break;\n        }\n\n    } \/\/ while (MFX_ERR_MORE_DATA == sts || MFX_ERR_MORE_SURFACE == sts || MFX_ERR_NONE < sts)\n\n    return sts;\n}\n\nmfxStatus MFX_DecodeInterface::DecodeLastFrame(mfxFrameSurface1 * & pSurf_out)\n{\n    MFX_ITT_TASK(\"DecodeLastFrame\");\n\n    mfxFrameSurface1 *pDecSurf = NULL;\n    mfxStatus sts = MFX_ERR_MORE_SURFACE;\n\n    \/\/ retrieve the buffered decoded frames\n    while (MFX_ERR_MORE_SURFACE == sts || MFX_WRN_DEVICE_BUSY == sts)\n    {\n        if (MFX_WRN_DEVICE_BUSY == sts)\n        {\n            WaitForDeviceToBecomeFree(*m_pmfxSession, m_SyncPoint, sts);\n        }\n        \/\/ find free surface for decoder input\n        pDecSurf = m_pSurfPool->GetFreeSurface_FEI();\n        MSDK_CHECK_POINTER(pDecSurf, MFX_ERR_MEMORY_ALLOC); \/\/ return an error if a free surface wasn't found\n\n        sts = m_pmfxDECODE->DecodeFrameAsync(NULL, pDecSurf, &pSurf_out, &m_SyncPoint);\n    }\n    return sts;\n}\n\nmfxStatus MFX_DecodeInterface::FlushOutput(mfxFrameSurface1* pSurf)\n{\n    MSDK_CHECK_POINTER(pSurf, MFX_ERR_NULL_PTR);\n\n    mfxStatus sts = MFX_ERR_NONE;\n\n    for (int i = 0; i < pSurf->Data.NumExtParam; ++i)\n        if (pSurf->Data.ExtParam[i]->BufferId == MFX_EXTBUFF_FEI_DEC_STREAM_OUT)\n        {\n            mfxExtFeiDecStreamOut* decodeStreamout = reinterpret_cast<mfxExtFeiDecStreamOut*>(pSurf->Data.ExtParam[i]);\n            MSDK_CHECK_POINTER(decodeStreamout, MFX_ERR_NULL_PTR);\n\n            if (m_DecStremout_out)\n            {\n                \/* NOTE: streamout holds data for both fields in MB array (first NumMBAlloc for first field data, second NumMBAlloc for second field) *\/\n                SAFE_FWRITE(decodeStreamout->MB, sizeof(mfxFeiDecStreamOutMBCtrl)*decodeStreamout->NumMBAlloc, 1, m_DecStremout_out, MFX_ERR_MORE_DATA);\n            }\n            break;\n        }\n\n    return sts;\n}\n\nmfxStatus MFX_DecodeInterface::ResetState()\n{\n    mfxStatus sts = MFX_ERR_NONE;\n\n    \/\/ mark sync point as free\n    m_SyncPoint = NULL;\n\n    \/\/ prepare bit stream\n    m_mfxBS.DataOffset = 0;\n    m_mfxBS.DataLength = 0;\n\n    sts = m_BSReader.Init(m_pAppConfig->strSrcFile);\n    MSDK_CHECK_STATUS(sts, \"m_BSReader.Init failed\");\n\n    m_bEndOfFile = false;\n\n    SAFE_FSEEK(m_DecStremout_out, 0, SEEK_SET, MFX_ERR_MORE_DATA);\n\n    return sts;\n}\n\n\nmfxStatus YUVreader::GetOneFrame(mfxFrameSurface1* & pSurf)\n{\n    MFX_ITT_TASK(\"GetOneFrame\");\n    mfxStatus res = MFX_ERR_NONE;\n\n    \/\/ point pSurf to encoder surface\n    pSurf = m_pSurfPool->GetFreeSurface_FEI();\n    MSDK_CHECK_POINTER(pSurf, MFX_ERR_MEMORY_ALLOC);\n\n    \/\/ load frame from file to surface data\n    \/\/ if we share allocator with Media SDK we need to call Lock to access surface data and...\n    if (m_bExternalAlloc)\n    {\n        \/\/ get YUV pointers\n        mfxStatus sts = m_pMFXAllocator->Lock(m_pMFXAllocator->pthis, pSurf->Data.MemId, &(pSurf->Data));\n        MSDK_CHECK_STATUS(sts, \"m_pMFXAllocator->Lock failed\");\n    }\n\n    res = m_FileReader.LoadNextFrame(pSurf);\n\n    \/\/ ... after we're done call Unlock\n    if (m_bExternalAlloc)\n    {\n        mfxStatus sts = m_pMFXAllocator->Unlock(m_pMFXAllocator->pthis, pSurf->Data.MemId, &(pSurf->Data));\n        MSDK_CHECK_STATUS(sts, \"m_pMFXAllocator->Unlock failed\");\n    }\n\n    if (res == MFX_ERR_MORE_DATA && m_pAppConfig->nTimeout)\n    {\n        \/\/ infinite loop mode, need to proceed from the beginning\n        return MFX_ERR_MORE_DATA;\n    }\n    MSDK_CHECK_PARSE_RESULT(res, MFX_ERR_NONE, res);\n\n    return res;\n}\n","avg_line_length":34.1235392321,"max_line_length":755,"alphanum_fraction":0.6721135029,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":25097,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/ Copyright (c) 2015-2017 The PIVX developers\n\/\/ Copyright (c) 2017 The MakeMyCoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"paymentserver.h\"\n\n#include \"bitcoinunits.h\"\n#include \"guiutil.h\"\n#include \"optionsmodel.h\"\n\n#include \"base58.h\"\n#include \"chainparams.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n#include \"wallet.h\"\n\n#include <cstdlib>\n\n#include <openssl\/x509.h>\n#include <openssl\/x509_vfy.h>\n\n#include <QApplication>\n#include <QByteArray>\n#include <QDataStream>\n#include <QDateTime>\n#include <QDebug>\n#include <QFile>\n#include <QFileOpenEvent>\n#include <QHash>\n#include <QList>\n#include <QLocalServer>\n#include <QLocalSocket>\n#include <QNetworkAccessManager>\n#include <QNetworkProxy>\n#include <QNetworkReply>\n#include <QNetworkRequest>\n#include <QSslCertificate>\n#include <QSslError>\n#include <QSslSocket>\n#include <QStringList>\n#include <QTextDocument>\n\n#if QT_VERSION < 0x050000\n#include <QUrl>\n#else\n#include <QUrlQuery>\n#endif\n\nusing namespace boost;\nusing namespace std;\n\nconst int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; \/\/ milliseconds\nconst QString BITCOIN_IPC_PREFIX(\"MakeMyCoin:\");\n\/\/ BIP70 payment protocol messages\nconst char* BIP70_MESSAGE_PAYMENTACK = \"PaymentACK\";\nconst char* BIP70_MESSAGE_PAYMENTREQUEST = \"PaymentRequest\";\n\/\/ BIP71 payment protocol media types\nconst char* BIP71_MIMETYPE_PAYMENT = \"application\/MakeMyCoin-payment\";\nconst char* BIP71_MIMETYPE_PAYMENTACK = \"application\/MakeMyCoin-paymentack\";\nconst char* BIP71_MIMETYPE_PAYMENTREQUEST = \"application\/MakeMyCoin-paymentrequest\";\n\/\/ BIP70 max payment request size in bytes (DoS protection)\nconst qint64 BIP70_MAX_PAYMENTREQUEST_SIZE = 50000;\n\nstruct X509StoreDeleter {\n      void operator()(X509_STORE* b) {\n          X509_STORE_free(b);\n      }\n};\n\nstruct X509Deleter {\n      void operator()(X509* b) { X509_free(b); }\n};\n\nnamespace \/\/ Anon namespace\n{\n\n    std::unique_ptr<X509_STORE, X509StoreDeleter> certStore;\n}\n\n\/\/\n\/\/ Create a name that is unique for:\n\/\/  testnet \/ non-testnet\n\/\/  data directory\n\/\/\nstatic QString ipcServerName()\n{\n    QString name(\"MakeMyCoinQt\");\n\n    \/\/ Append a simple hash of the datadir\n    \/\/ Note that GetDataDir(true) returns a different path\n    \/\/ for -testnet versus main net\n    QString ddir(QString::fromStdString(GetDataDir(true).string()));\n    name.append(QString::number(qHash(ddir)));\n\n    return name;\n}\n\n\/\/\n\/\/ We store payment URIs and requests received before\n\/\/ the main GUI window is up and ready to ask the user\n\/\/ to send payment.\n\nstatic QList<QString> savedPaymentRequests;\n\nstatic void ReportInvalidCertificate(const QSslCertificate& cert)\n{\n    qDebug() << \"ReportInvalidCertificate : Payment server found an invalid certificate: \" << cert.subjectInfo(QSslCertificate::CommonName);\n}\n\n\/\/\n\/\/ Load OpenSSL's list of root certificate authorities\n\/\/\nvoid PaymentServer::LoadRootCAs(X509_STORE* _store)\n{\n    \/\/ Unit tests mostly use this, to pass in fake root CAs:\n    if (_store) {\n        certStore.reset(_store);\n        return;\n    }\n\n    \/\/ Normal execution, use either -rootcertificates or system certs:\n    certStore.reset(X509_STORE_new());\n\n    \/\/ Note: use \"-system-\" default here so that users can pass -rootcertificates=\"\"\n    \/\/ and get 'I don't like X.509 certificates, don't trust anybody' behavior:\n    QString certFile = QString::fromStdString(GetArg(\"-rootcertificates\", \"-system-\"));\n\n    if (certFile.isEmpty())\n        return; \/\/ Empty store\n\n    QList<QSslCertificate> certList;\n\n    if (certFile != \"-system-\") {\n        certList = QSslCertificate::fromPath(certFile);\n        \/\/ Use those certificates when fetching payment requests, too:\n        QSslSocket::setDefaultCaCertificates(certList);\n    } else\n        certList = QSslSocket::systemCaCertificates();\n\n    int nRootCerts = 0;\n    const QDateTime currentTime = QDateTime::currentDateTime();\n    foreach (const QSslCertificate& cert, certList) {\n        if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) {\n            ReportInvalidCertificate(cert);\n            continue;\n        }\n#if QT_VERSION >= 0x050000\n        if (cert.isBlacklisted()) {\n            ReportInvalidCertificate(cert);\n            continue;\n        }\n#endif\n        QByteArray certData = cert.toDer();\n        const unsigned char* data = (const unsigned char*)certData.data();\n\n        std::unique_ptr<X509, X509Deleter> x509(d2i_X509(0, &data, certData.size()));\n        if (x509 && X509_STORE_add_cert(certStore.get(), x509.get())) {\n            \/\/ Note: X509_STORE increases the reference count to the X509 object,\n            \/\/ we still have to release our reference to it.\n            ++nRootCerts;\n        } else {\n            ReportInvalidCertificate(cert);\n            continue;\n        }\n    }\n    qWarning() << \"PaymentServer::LoadRootCAs : Loaded \" << nRootCerts << \" root certificates\";\n\n    \/\/ Project for another day:\n    \/\/ Fetch certificate revocation lists, and add them to certStore.\n    \/\/ Issues to consider:\n    \/\/   performance (start a thread to fetch in background?)\n    \/\/   privacy (fetch through tor\/proxy so IP address isn't revealed)\n    \/\/   would it be easier to just use a compiled-in blacklist?\n    \/\/    or use Qt's blacklist?\n    \/\/   \"certificate stapling\" with server-side caching is more efficient\n}\n\n\/\/\n\/\/ Sending to the server is done synchronously, at startup.\n\/\/ If the server isn't already running, startup continues,\n\/\/ and the items in savedPaymentRequest will be handled\n\/\/ when uiReady() is called.\n\/\/\n\/\/ Warning: ipcSendCommandLine() is called early in init,\n\/\/ so don't use \"emit message()\", but \"QMessageBox::\"!\n\/\/\nvoid PaymentServer::ipcParseCommandLine(int argc, char* argv[])\n{\n    for (int i = 1; i < argc; i++) {\n        QString arg(argv[i]);\n        if (arg.startsWith(\"-\"))\n            continue;\n\n        \/\/ If the MakeMyCoin: URI contains a payment request, we are not able to detect the\n        \/\/ network as that would require fetching and parsing the payment request.\n        \/\/ That means clicking such an URI which contains a testnet payment request\n        \/\/ will start a mainnet instance and throw a \"wrong network\" error.\n        if (arg.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) \/\/ MakeMyCoin: URI\n        {\n            savedPaymentRequests.append(arg);\n\n            SendCoinsRecipient r;\n            if (GUIUtil::parseBitcoinURI(arg, &r) && !r.address.isEmpty()) {\n                CBitcoinAddress address(r.address.toStdString());\n\n                if (address.IsValid(Params(CBaseChainParams::MAIN))) {\n                    SelectParams(CBaseChainParams::MAIN);\n                } else if (address.IsValid(Params(CBaseChainParams::TESTNET))) {\n                    SelectParams(CBaseChainParams::TESTNET);\n                }\n            }\n        } else if (QFile::exists(arg)) \/\/ Filename\n        {\n            savedPaymentRequests.append(arg);\n\n            PaymentRequestPlus request;\n            if (readPaymentRequestFromFile(arg, request)) {\n                if (request.getDetails().network() == \"main\") {\n                    SelectParams(CBaseChainParams::MAIN);\n                } else if (request.getDetails().network() == \"test\") {\n                    SelectParams(CBaseChainParams::TESTNET);\n                }\n            }\n        } else {\n            \/\/ Printing to debug.log is about the best we can do here, the\n            \/\/ GUI hasn't started yet so we can't pop up a message box.\n            qWarning() << \"PaymentServer::ipcSendCommandLine : Payment request file does not exist: \" << arg;\n        }\n    }\n}\n\n\/\/\n\/\/ Sending to the server is done synchronously, at startup.\n\/\/ If the server isn't already running, startup continues,\n\/\/ and the items in savedPaymentRequest will be handled\n\/\/ when uiReady() is called.\n\/\/\nbool PaymentServer::ipcSendCommandLine()\n{\n    bool fResult = false;\n    foreach (const QString& r, savedPaymentRequests) {\n        QLocalSocket* socket = new QLocalSocket();\n        socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);\n        if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) {\n            delete socket;\n            socket = NULL;\n            return false;\n        }\n\n        QByteArray block;\n        QDataStream out(&block, QIODevice::WriteOnly);\n        out.setVersion(QDataStream::Qt_4_0);\n        out << r;\n        out.device()->seek(0);\n\n        socket->write(block);\n        socket->flush();\n        socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT);\n        socket->disconnectFromServer();\n\n        delete socket;\n        socket = NULL;\n        fResult = true;\n    }\n\n    return fResult;\n}\n\nPaymentServer::PaymentServer(QObject* parent, bool startLocalServer) : QObject(parent),\n                                                                       saveURIs(true),\n                                                                       uriServer(0),\n                                                                       netManager(0),\n                                                                       optionsModel(0)\n{\n    \/\/ Verify that the version of the library that we linked against is\n    \/\/ compatible with the version of the headers we compiled against.\n    GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n    \/\/ Install global event filter to catch QFileOpenEvents\n    \/\/ on Mac: sent when you click MakeMyCoin: links\n    \/\/ other OSes: helpful when dealing with payment request files (in the future)\n    if (parent)\n        parent->installEventFilter(this);\n\n    QString name = ipcServerName();\n\n    \/\/ Clean up old socket leftover from a crash:\n    QLocalServer::removeServer(name);\n\n    if (startLocalServer) {\n        uriServer = new QLocalServer(this);\n\n        if (!uriServer->listen(name)) {\n            \/\/ constructor is called early in init, so don't use \"emit message()\" here\n            QMessageBox::critical(0, tr(\"Payment request error\"),\n                tr(\"Cannot start MakeMyCoin: click-to-pay handler\"));\n        } else {\n            connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection()));\n            connect(this, SIGNAL(receivedPaymentACK(QString)), this, SLOT(handlePaymentACK(QString)));\n        }\n    }\n}\n\nPaymentServer::~PaymentServer()\n{\n    google::protobuf::ShutdownProtobufLibrary();\n}\n\n\/\/\n\/\/ OSX-specific way of handling MakeMyCoin: URIs and\n\/\/ PaymentRequest mime types\n\/\/\nbool PaymentServer::eventFilter(QObject* object, QEvent* event)\n{\n    \/\/ clicking on MakeMyCoin: URIs creates FileOpen events on the Mac\n    if (event->type() == QEvent::FileOpen) {\n        QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event);\n        if (!fileEvent->file().isEmpty())\n            handleURIOrFile(fileEvent->file());\n        else if (!fileEvent->url().isEmpty())\n            handleURIOrFile(fileEvent->url().toString());\n\n        return true;\n    }\n\n    return QObject::eventFilter(object, event);\n}\n\nvoid PaymentServer::initNetManager()\n{\n    if (!optionsModel)\n        return;\n    if (netManager != NULL)\n        delete netManager;\n\n    \/\/ netManager is used to fetch paymentrequests given in MakeMyCoin: URIs\n    netManager = new QNetworkAccessManager(this);\n\n    QNetworkProxy proxy;\n\n    \/\/ Query active SOCKS5 proxy\n    if (optionsModel->getProxySettings(proxy)) {\n        netManager->setProxy(proxy);\n\n        qDebug() << \"PaymentServer::initNetManager : Using SOCKS5 proxy\" << proxy.hostName() << \":\" << proxy.port();\n    } else\n        qDebug() << \"PaymentServer::initNetManager : No active proxy server found.\";\n\n    connect(netManager, SIGNAL(finished(QNetworkReply*)),\n        this, SLOT(netRequestFinished(QNetworkReply*)));\n    connect(netManager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&)),\n        this, SLOT(reportSslErrors(QNetworkReply*, const QList<QSslError>&)));\n}\n\nvoid PaymentServer::uiReady()\n{\n    initNetManager();\n\n    saveURIs = false;\n    foreach (const QString& s, savedPaymentRequests) {\n        handleURIOrFile(s);\n    }\n    savedPaymentRequests.clear();\n}\n\nvoid PaymentServer::handleURIOrFile(const QString& s)\n{\n    if (saveURIs) {\n        savedPaymentRequests.append(s);\n        return;\n    }\n\n    if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) \/\/ MakeMyCoin: URI\n    {\n#if QT_VERSION < 0x050000\n        QUrl uri(s);\n#else\n        QUrlQuery uri((QUrl(s)));\n#endif\n        if (uri.hasQueryItem(\"r\")) \/\/ payment request URI\n        {\n            QByteArray temp;\n            temp.append(uri.queryItemValue(\"r\"));\n            QString decoded = QUrl::fromPercentEncoding(temp);\n            QUrl fetchUrl(decoded, QUrl::StrictMode);\n\n            if (fetchUrl.isValid()) {\n                qDebug() << \"PaymentServer::handleURIOrFile : fetchRequest(\" << fetchUrl << \")\";\n                fetchRequest(fetchUrl);\n            } else {\n                qWarning() << \"PaymentServer::handleURIOrFile : Invalid URL: \" << fetchUrl;\n                emit message(tr(\"URI handling\"),\n                    tr(\"Payment request fetch URL is invalid: %1\").arg(fetchUrl.toString()),\n                    CClientUIInterface::ICON_WARNING);\n            }\n\n            return;\n        } else \/\/ normal URI\n        {\n            SendCoinsRecipient recipient;\n            if (GUIUtil::parseBitcoinURI(s, &recipient)) {\n                CBitcoinAddress address(recipient.address.toStdString());\n                if (!address.IsValid()) {\n                    emit message(tr(\"URI handling\"), tr(\"Invalid payment address %1\").arg(recipient.address),\n                        CClientUIInterface::MSG_ERROR);\n                } else\n                    emit receivedPaymentRequest(recipient);\n            } else\n                emit message(tr(\"URI handling\"),\n                    tr(\"URI cannot be parsed! This can be caused by an invalid MakeMyCoin address or malformed URI parameters.\"),\n                    CClientUIInterface::ICON_WARNING);\n\n            return;\n        }\n    }\n\n    if (QFile::exists(s)) \/\/ payment request file\n    {\n        PaymentRequestPlus request;\n        SendCoinsRecipient recipient;\n        if (!readPaymentRequestFromFile(s, request)) {\n            emit message(tr(\"Payment request file handling\"),\n                tr(\"Payment request file cannot be read! This can be caused by an invalid payment request file.\"),\n                CClientUIInterface::ICON_WARNING);\n        } else if (processPaymentRequest(request, recipient))\n            emit receivedPaymentRequest(recipient);\n\n        return;\n    }\n}\n\nvoid PaymentServer::handleURIConnection()\n{\n    QLocalSocket* clientConnection = uriServer->nextPendingConnection();\n\n    while (clientConnection->bytesAvailable() < (int)sizeof(quint32))\n        clientConnection->waitForReadyRead();\n\n    connect(clientConnection, SIGNAL(disconnected()),\n        clientConnection, SLOT(deleteLater()));\n\n    QDataStream in(clientConnection);\n    in.setVersion(QDataStream::Qt_4_0);\n    if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) {\n        return;\n    }\n    QString msg;\n    in >> msg;\n\n    handleURIOrFile(msg);\n}\n\n\/\/\n\/\/ Warning: readPaymentRequestFromFile() is used in ipcSendCommandLine()\n\/\/ so don't use \"emit message()\", but \"QMessageBox::\"!\n\/\/\nbool PaymentServer::readPaymentRequestFromFile(const QString& filename, PaymentRequestPlus& request)\n{\n    QFile f(filename);\n    if (!f.open(QIODevice::ReadOnly)) {\n        qWarning() << QString(\"PaymentServer::%1: Failed to open %2\").arg(__func__).arg(filename);\n        return false;\n    }\n\n    \/\/ BIP70 DoS protection\n    if (f.size() > BIP70_MAX_PAYMENTREQUEST_SIZE) {\n        qWarning() << QString(\"PaymentServer::%1: Payment request %2 is too large (%3 bytes, allowed %4 bytes).\")\n                          .arg(__func__)\n                          .arg(filename)\n                          .arg(f.size())\n                          .arg(BIP70_MAX_PAYMENTREQUEST_SIZE);\n        return false;\n    }\n\n    QByteArray data = f.readAll();\n\n    return request.parse(data);\n}\n\nbool PaymentServer::processPaymentRequest(PaymentRequestPlus& request, SendCoinsRecipient& recipient)\n{\n    if (!optionsModel)\n        return false;\n\n    if (request.IsInitialized()) {\n        const payments::PaymentDetails& details = request.getDetails();\n\n        \/\/ Payment request network matches client network?\n        if (details.network() != Params().NetworkIDString()) {\n            emit message(tr(\"Payment request rejected\"), tr(\"Payment request network doesn't match client network.\"),\n                CClientUIInterface::MSG_ERROR);\n\n            return false;\n        }\n\n        \/\/ Expired payment request?\n        if (details.has_expires() && (int64_t)details.expires() < GetTime()) {\n            emit message(tr(\"Payment request rejected\"), tr(\"Payment request has expired.\"),\n                CClientUIInterface::MSG_ERROR);\n\n            return false;\n        }\n    } else {\n        emit message(tr(\"Payment request error\"), tr(\"Payment request is not initialized.\"),\n            CClientUIInterface::MSG_ERROR);\n\n        return false;\n    }\n\n    recipient.paymentRequest = request;\n    recipient.message = GUIUtil::HtmlEscape(request.getDetails().memo());\n\n    request.getMerchant(certStore.get(), recipient.authenticatedMerchant);\n\n    QList<std::pair<CScript, CAmount> > sendingTos = request.getPayTo();\n    QStringList addresses;\n\n    foreach (const PAIRTYPE(CScript, CAmount) & sendingTo, sendingTos) {\n        \/\/ Extract and check destination addresses\n        CTxDestination dest;\n        if (ExtractDestination(sendingTo.first, dest)) {\n            \/\/ Append destination address\n            addresses.append(QString::fromStdString(CBitcoinAddress(dest).ToString()));\n        } else if (!recipient.authenticatedMerchant.isEmpty()) {\n            \/\/ Insecure payments to custom MakeMyCoin addresses are not supported\n            \/\/ (there is no good way to tell the user where they are paying in a way\n            \/\/ they'd have a chance of understanding).\n            emit message(tr(\"Payment request rejected\"),\n                tr(\"Unverified payment requests to custom payment scripts are unsupported.\"),\n                CClientUIInterface::MSG_ERROR);\n            return false;\n        }\n\n        \/\/ Extract and check amounts\n        CTxOut txOut(sendingTo.second, sendingTo.first);\n        if (txOut.IsDust(::minRelayTxFee)) {\n            emit message(tr(\"Payment request error\"), tr(\"Requested payment amount of %1 is too small (considered dust).\").arg(BitcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), sendingTo.second)),\n                CClientUIInterface::MSG_ERROR);\n\n            return false;\n        }\n\n        recipient.amount += sendingTo.second;\n    }\n    \/\/ Store addresses and format them to fit nicely into the GUI\n    recipient.address = addresses.join(\"<br \/>\");\n\n    if (!recipient.authenticatedMerchant.isEmpty()) {\n        qDebug() << \"PaymentServer::processPaymentRequest : Secure payment request from \" << recipient.authenticatedMerchant;\n    } else {\n        qDebug() << \"PaymentServer::processPaymentRequest : Insecure payment request to \" << addresses.join(\", \");\n    }\n\n    return true;\n}\n\nvoid PaymentServer::fetchRequest(const QUrl& url)\n{\n    QNetworkRequest netRequest;\n    netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTREQUEST);\n    netRequest.setUrl(url);\n    netRequest.setRawHeader(\"User-Agent\", CLIENT_NAME.c_str());\n    netRequest.setRawHeader(\"Accept\", BIP71_MIMETYPE_PAYMENTREQUEST);\n    netManager->get(netRequest);\n}\n\nvoid PaymentServer::fetchPaymentACK(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction)\n{\n    const payments::PaymentDetails& details = recipient.paymentRequest.getDetails();\n    if (!details.has_payment_url())\n        return;\n\n    QNetworkRequest netRequest;\n    netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTACK);\n    netRequest.setUrl(QString::fromStdString(details.payment_url()));\n    netRequest.setHeader(QNetworkRequest::ContentTypeHeader, BIP71_MIMETYPE_PAYMENT);\n    netRequest.setRawHeader(\"User-Agent\", CLIENT_NAME.c_str());\n    netRequest.setRawHeader(\"Accept\", BIP71_MIMETYPE_PAYMENTACK);\n\n    payments::Payment payment;\n    payment.set_merchant_data(details.merchant_data());\n    payment.add_transactions(transaction.data(), transaction.size());\n\n    \/\/ Create a new refund address, or re-use:\n    QString account = tr(\"Refund from %1\").arg(recipient.authenticatedMerchant);\n    std::string strAccount = account.toStdString();\n    set<CTxDestination> refundAddresses = wallet->GetAccountAddresses(strAccount);\n    if (!refundAddresses.empty()) {\n        CScript s = GetScriptForDestination(*refundAddresses.begin());\n        payments::Output* refund_to = payment.add_refund_to();\n        refund_to->set_script(&s[0], s.size());\n    } else {\n        CPubKey newKey;\n        if (wallet->GetKeyFromPool(newKey)) {\n            CKeyID keyID = newKey.GetID();\n            wallet->SetAddressBook(keyID, strAccount, \"refund\");\n\n            CScript s = GetScriptForDestination(keyID);\n            payments::Output* refund_to = payment.add_refund_to();\n            refund_to->set_script(&s[0], s.size());\n        } else {\n            \/\/ This should never happen, because sending coins should have\n            \/\/ just unlocked the wallet and refilled the keypool.\n            qWarning() << \"PaymentServer::fetchPaymentACK : Error getting refund key, refund_to not set\";\n        }\n    }\n\n    int length = payment.ByteSize();\n    netRequest.setHeader(QNetworkRequest::ContentLengthHeader, length);\n    QByteArray serData(length, '\\0');\n    if (payment.SerializeToArray(serData.data(), length)) {\n        netManager->post(netRequest, serData);\n    } else {\n        \/\/ This should never happen, either.\n        qWarning() << \"PaymentServer::fetchPaymentACK : Error serializing payment message\";\n    }\n}\n\nvoid PaymentServer::netRequestFinished(QNetworkReply* reply)\n{\n    reply->deleteLater();\n\n    \/\/ BIP70 DoS protection\n    if (reply->size() > BIP70_MAX_PAYMENTREQUEST_SIZE) {\n        QString msg = tr(\"Payment request %1 is too large (%2 bytes, allowed %3 bytes).\")\n                          .arg(reply->request().url().toString())\n                          .arg(reply->size())\n                          .arg(BIP70_MAX_PAYMENTREQUEST_SIZE);\n\n        qWarning() << QString(\"PaymentServer::%1:\").arg(__func__) << msg;\n        emit message(tr(\"Payment request DoS protection\"), msg, CClientUIInterface::MSG_ERROR);\n        return;\n    }\n\n    if (reply->error() != QNetworkReply::NoError) {\n        QString msg = tr(\"Error communicating with %1: %2\")\n                          .arg(reply->request().url().toString())\n                          .arg(reply->errorString());\n\n        qWarning() << \"PaymentServer::netRequestFinished: \" << msg;\n        emit message(tr(\"Payment request error\"), msg, CClientUIInterface::MSG_ERROR);\n        return;\n    }\n\n    QByteArray data = reply->readAll();\n\n    QString requestType = reply->request().attribute(QNetworkRequest::User).toString();\n    if (requestType == BIP70_MESSAGE_PAYMENTREQUEST) {\n        PaymentRequestPlus request;\n        SendCoinsRecipient recipient;\n        if (!request.parse(data)) {\n            qWarning() << \"PaymentServer::netRequestFinished : Error parsing payment request\";\n            emit message(tr(\"Payment request error\"),\n                tr(\"Payment request cannot be parsed!\"),\n                CClientUIInterface::MSG_ERROR);\n        } else if (processPaymentRequest(request, recipient))\n            emit receivedPaymentRequest(recipient);\n\n        return;\n    } else if (requestType == BIP70_MESSAGE_PAYMENTACK) {\n        payments::PaymentACK paymentACK;\n        if (!paymentACK.ParseFromArray(data.data(), data.size())) {\n            QString msg = tr(\"Bad response from server %1\")\n                              .arg(reply->request().url().toString());\n\n            qWarning() << \"PaymentServer::netRequestFinished : \" << msg;\n            emit message(tr(\"Payment request error\"), msg, CClientUIInterface::MSG_ERROR);\n        } else {\n            emit receivedPaymentACK(GUIUtil::HtmlEscape(paymentACK.memo()));\n        }\n    }\n}\n\nvoid PaymentServer::reportSslErrors(QNetworkReply* reply, const QList<QSslError>& errs)\n{\n    Q_UNUSED(reply);\n\n    QString errString;\n    foreach (const QSslError& err, errs) {\n        qWarning() << \"PaymentServer::reportSslErrors : \" << err;\n        errString += err.errorString() + \"\\n\";\n    }\n    emit message(tr(\"Network request error\"), errString, CClientUIInterface::MSG_ERROR);\n}\n\nvoid PaymentServer::setOptionsModel(OptionsModel* optionsModel)\n{\n    this->optionsModel = optionsModel;\n}\n\nvoid PaymentServer::handlePaymentACK(const QString& paymentACKMsg)\n{\n    \/\/ currently we don't futher process or store the paymentACK message\n    emit message(tr(\"Payment acknowledged\"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL);\n}\n\nX509_STORE* PaymentServer::getCertStore()\n{\n    return certStore.get();\n}\n","avg_line_length":35.6491477273,"max_line_length":207,"alphanum_fraction":0.6436227438,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2482,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":2.0,"content":"\/\/@HEADER\n\/\/ ************************************************************************\n\/\/ \n\/\/                        Kokkos v. 2.0\n\/\/              Copyright (2014) Sandia Corporation\n\/\/ \n\/\/ Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n\/\/ the U.S. Government retains certain rights in this software.\n\/\/\n\/\/ Kokkos is licensed under 3-clause BSD terms of use:\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ 3. Neither the name of the Corporation nor the names of the\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION \"AS IS\" AND ANY\n\/\/ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ Questions? Contact Christian R. Trott (crtrott@sandia.gov)\n\/\/ \n\/\/ ************************************************************************\n\/\/@HEADER\n\n#define KOKKOS_IMPL_COMPILING_LIBRARY true\n#include<Kokkos_Core.hpp>\nnamespace Kokkos {\nnamespace Impl {\nKOKKOS_IMPL_VIEWCOPY_ETI_INST(float********,LayoutLeft,LayoutRight, Experimental::HPX,int)\nKOKKOS_IMPL_VIEWCOPY_ETI_INST(float********,LayoutLeft,LayoutLeft,  Experimental::HPX,int)\nKOKKOS_IMPL_VIEWCOPY_ETI_INST(float********,LayoutLeft,LayoutStride,Experimental::HPX,int)\nKOKKOS_IMPL_VIEWFILL_ETI_INST(float********,LayoutLeft,Experimental::HPX,int)\n\n}\n}\n","avg_line_length":45.1272727273,"max_line_length":90,"alphanum_fraction":0.7119258662,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2558,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <benchmark\/benchmark.h>\n\n#include <vector>\n#include <memory>\n#include <string>\n\n#include <fmt\/format.h>\n\nclass X_Impl {\n    private:\n    std::string i;\n    std::string j;\n    std::string k;\n    std::string l;\n};\n\n\nclass X_NoRuleOf0_MemberInit\n{\npublic:\n   X_NoRuleOf0_MemberInit() : impl{std::make_shared<X_Impl>()} {}\n\n   \/\/ break performance for the fun of it!!\n   virtual ~X_NoRuleOf0_MemberInit() {}\n  private:\n    std::shared_ptr<X_Impl> impl;\n};\n\n\/\/ this example shows what happens if you break the rule of 0\n\/\/ by providing an empty destructor\nstatic void WithNoRuleOf0MemberInit(benchmark::State& state) {\n\n  struct MyEntry {\n    MyEntry(X_NoRuleOf0_MemberInit t_x) : x(std::move(t_x)) {  };\n    X_NoRuleOf0_MemberInit x;\n\n    \/\/ break performance for the fun of it!!\n    ~MyEntry() {}\n  };\n\n  std::vector<MyEntry> newSurfaces1;\n  for (int64_t i = 0; i < state.range(0); ++i) {\n    newSurfaces1.emplace_back(X_NoRuleOf0_MemberInit{});\n  }\n\n  \/\/ size_t vecSize = 1 + state.range(0);\n\n  MyEntry surface(X_NoRuleOf0_MemberInit{});\n\n  \/\/ Code inside this loop is measured repeatedly\n  for (auto _ : state) {\n    std::vector<MyEntry> vec;\n    vec.push_back(surface);\n    vec.insert(vec.end(), newSurfaces1.begin(), newSurfaces1.end());\n  }\n\n  state.SetComplexityN(state.range(0));\n\n}\n\/\/ Register the function as a benchmark\n\nstatic void WithNoRuleOf0MemberInit_reserve(benchmark::State& state) {\n\n  struct MyEntry {\n    \/\/ 0 copies in this version, but one move per object's construction\n    MyEntry(X_NoRuleOf0_MemberInit t_x) : x(std::move(t_x)) {  };\n    X_NoRuleOf0_MemberInit x;\n  };\n\n\n  std::vector<MyEntry> newSurfaces1;\n  for (int64_t i = 0; i < state.range(0); ++i) {\n    newSurfaces1.emplace_back(X_NoRuleOf0_MemberInit{});\n  }\n\n\/*\n *  std::vector<MyEntry> newSurfaces2;\n *  for (int64_t i = 0; i < state.range(0); ++i) {\n *    newSurfaces1.emplace_back(X_NoRuleOf0_MemberInit{});\n *  }\n *\n *\/\n  size_t vecSize = 1 + state.range(0);\n\n  MyEntry surface(X_NoRuleOf0_MemberInit{});\n\n  \/\/ Code inside this loop is measured repeatedly\n  for (auto _ : state) {\n    std::vector<MyEntry> vec;\n    \/\/ by reserving ahead of time we know that there will be no data moves or copies\n    vec.reserve(vecSize);\n    vec.push_back(surface);\n    vec.insert(vec.end(), newSurfaces1.begin(), newSurfaces1.end());\n  }\n\n  state.SetComplexityN(state.range(0));\n}\n\/\/ Register the function as a benchmark\n\nBENCHMARK(WithNoRuleOf0MemberInit)\n  ->Range(8, 8<<10)\n  ->Complexity();\n\nBENCHMARK(WithNoRuleOf0MemberInit_reserve)\n  ->Range(8, 8<<10)\n  ->Complexity();\n","avg_line_length":23.9065420561,"max_line_length":84,"alphanum_fraction":0.6810007819,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":28431,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/\/ Tencent is pleased to support the open source community by making ncnn available.\n\/\/\n\/\/ Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.\n\/\/\n\/\/ Licensed under the BSD 3-Clause License (the \"License\"); you may not use this file except\n\/\/ in compliance with the License. You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/opensource.org\/licenses\/BSD-3-Clause\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software distributed\n\/\/ under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n\/\/ CONDITIONS OF ANY KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations under the License.\n\n#include \"command.h\"\n\n#if NCNN_VULKAN\n\n#include <stdio.h>\n\nnamespace ncnn {\n\nCommand::Command(const VulkanDevice* _vkdev, uint32_t _queue_index) : vkdev(_vkdev), queue_index(_queue_index)\n{\n    \/\/ get queue\n    vkGetDeviceQueue(vkdev->vkdevice(), queue_index, 0, &queue);\n\n    create_command_pool();\n\n    create_command_buffer();\n\n    \/\/ create fence\n    VkFenceCreateInfo fenceCreateInfo;\n    fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;\n    fenceCreateInfo.pNext = 0;\n    fenceCreateInfo.flags = 0;\n\n    VkResult ret = vkCreateFence(vkdev->vkdevice(), &fenceCreateInfo, 0, &fence);\n    if (ret != VK_SUCCESS)\n    {\n        fprintf(stderr, \"vkCreateFence failed %d\\n\", ret);\n    }\n}\n\nCommand::~Command()\n{\n    vkDestroyFence(vkdev->vkdevice(), fence, 0);\n\n    vkFreeCommandBuffers(vkdev->vkdevice(), command_pool, 1, &command_buffer);\n\n    vkDestroyCommandPool(vkdev->vkdevice(), command_pool, 0);\n}\n\nint Command::create_command_pool()\n{\n    VkCommandPoolCreateInfo commandPoolCreateInfo;\n    commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;\n    commandPoolCreateInfo.pNext = 0;\n    commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;\n    commandPoolCreateInfo.queueFamilyIndex = queue_index;\n\n    VkResult ret = vkCreateCommandPool(vkdev->vkdevice(), &commandPoolCreateInfo, 0, &command_pool);\n    if (ret != VK_SUCCESS)\n    {\n        fprintf(stderr, \"vkCreateCommandPool failed %d\\n\", ret);\n        return -1;\n    }\n\n    return 0;\n}\n\nint Command::create_command_buffer()\n{\n    VkCommandBufferAllocateInfo commandBufferAllocateInfo;\n    commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;\n    commandBufferAllocateInfo.pNext = 0;\n    commandBufferAllocateInfo.commandPool = command_pool;\n    commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;\n    commandBufferAllocateInfo.commandBufferCount = 1;\n\n    VkResult ret = vkAllocateCommandBuffers(vkdev->vkdevice(), &commandBufferAllocateInfo, &command_buffer);\n    if (ret != VK_SUCCESS)\n    {\n        fprintf(stderr, \"vkAllocateCommandBuffers failed %d\\n\", ret);\n        return -1;\n    }\n\n    return 0;\n}\n\nint Command::begin_command_buffer()\n{\n\/\/     fprintf(stderr, \"==================== begin\\n\");\n\n    VkCommandBufferBeginInfo commandBufferBeginInfo;\n    commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;\n    commandBufferBeginInfo.pNext = 0;\n    commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;\n    commandBufferBeginInfo.pInheritanceInfo = 0;\n\n    VkResult ret = vkBeginCommandBuffer(command_buffer, &commandBufferBeginInfo);\n    if (ret != VK_SUCCESS)\n    {\n        fprintf(stderr, \"vkBeginCommandBuffer failed %d\\n\", ret);\n        return -1;\n    }\n\n    return 0;\n}\n\nint Command::end_command_buffer()\n{\n\/\/     fprintf(stderr, \"==================== end\\n\");\n\n    VkResult ret = vkEndCommandBuffer(command_buffer);\n    if (ret != VK_SUCCESS)\n    {\n        fprintf(stderr, \"vkEndCommandBuffer failed %d\\n\", ret);\n        return -1;\n    }\n\n    return 0;\n}\n\nint Command::queue_submit()\n{\n\/\/     fprintf(stderr, \"==================== submit\\n\");\n\n    VkSubmitInfo submitInfo;\n    submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;\n    submitInfo.pNext = 0;\n    submitInfo.waitSemaphoreCount = 0;\n    submitInfo.pWaitSemaphores = 0;\n    submitInfo.pWaitDstStageMask = 0;\n    submitInfo.commandBufferCount = 1;\n    submitInfo.pCommandBuffers = &command_buffer;\n    submitInfo.signalSemaphoreCount = 0;\n    submitInfo.pSignalSemaphores = 0;\n\n    VkResult ret = vkQueueSubmit(queue, 1, &submitInfo, fence);\n    if (ret != VK_SUCCESS)\n    {\n        fprintf(stderr, \"vkQueueSubmit failed %d\\n\", ret);\n        return -1;\n    }\n\n    return 0;\n}\n\nint Command::wait_fence()\n{\n\/\/     fprintf(stderr, \"==================== wait\\n\");\n\n    VkResult ret = vkWaitForFences(vkdev->vkdevice(), 1, &fence, VK_TRUE, UINT64_MAX);\n    if (ret != VK_SUCCESS)\n    {\n        fprintf(stderr, \"vkWaitForFences failed %d\\n\", ret);\n        return -1;\n    }\n\n    return 0;\n}\n\nVkCompute::VkCompute(const VulkanDevice* _vkdev) : Command(_vkdev, _vkdev->info.compute_queue_index)\n{\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n    {\n        begin_command_buffer();\n    }\n}\n\nVkCompute::~VkCompute()\n{\n    if (!vkdev->info.support_VK_KHR_push_descriptor)\n    {\n        for (size_t i=0; i<descriptorsets.size(); i++)\n        {\n            vkFreeDescriptorSets(vkdev->vkdevice(), descriptor_pools[i], 1, &descriptorsets[i]);\n            vkDestroyDescriptorPool(vkdev->vkdevice(), descriptor_pools[i], 0);\n        }\n    }\n}\n\nvoid VkCompute::record_upload(const VkMat& m)\n{\n    if (m.allocator->mappable)\n        return;\n\n    record_prepare_transfer_barrier(m);\n\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n        return copy_buffer(m.staging_buffer(), 0, m.buffer(), m.buffer_offset(), m.total() * m.elemsize);\n\n    record_type r;\n    r.type = 0;\n    r.copy.src = m.staging_buffer();\n    r.copy.src_offset = 0;\n    r.copy.dst = m.buffer();\n    r.copy.dst_offset = m.buffer_offset();\n    r.copy.size = m.total() * m.elemsize;\n    delayed_records.push_back(r);\n}\n\nvoid VkCompute::record_download(const VkMat& m)\n{\n    if (m.allocator->mappable)\n        return;\n\n    record_prepare_transfer_barrier(m);\n\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n        return copy_buffer(m.buffer(), m.buffer_offset(), m.staging_buffer(), 0, m.total() * m.elemsize);\n\n    record_type r;\n    r.type = 0;\n    r.copy.src = m.buffer();\n    r.copy.src_offset = m.buffer_offset();\n    r.copy.dst = m.staging_buffer();\n    r.copy.dst_offset = 0;\n    r.copy.size = m.total() * m.elemsize;\n    delayed_records.push_back(r);\n}\n\nvoid VkCompute::record_clone(const VkMat& src, const VkMat& dst)\n{\n    record_prepare_transfer_barrier(src);\n\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n        return copy_buffer(src.buffer(), src.buffer_offset(), dst.buffer(), dst.buffer_offset(), src.total() * src.elemsize);\n\n    record_type r;\n    r.type = 0;\n    r.copy.src = src.buffer();\n    r.copy.src_offset = src.buffer_offset();\n    r.copy.dst = dst.buffer();\n    r.copy.dst_offset = dst.buffer_offset();\n    r.copy.size = src.total() * src.elemsize;\n    delayed_records.push_back(r);\n}\n\nvoid VkCompute::record_copy_region(const VkMat& src, const VkMat& dst, const VkBufferCopy& region)\n{\n    std::vector<VkBufferCopy> regions(1);\n    regions[0] = region;\n\n    record_copy_regions(src, dst, regions);\n}\n\nvoid VkCompute::record_copy_regions(const VkMat& src, const VkMat& dst, const std::vector<VkBufferCopy>& regions)\n{\n    record_prepare_transfer_barrier(src);\n\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n        return copy_buffer_regions(src.buffer(), dst.buffer(), regions);\n\n    record_type r;\n    r.type = 1;\n    r.copy_regions.src = src.buffer();\n    r.copy_regions.dst = dst.buffer();\n    r.regions = regions;\n    delayed_records.push_back(r);\n}\n\nvoid VkCompute::record_pipeline(const Pipeline* pipeline, const std::vector<VkMat>& bindings, const std::vector<vk_constant_type>& constants, const VkMat& m)\n{\n    const int binding_count = bindings.size();\n    for (int i=0; i<binding_count; i++)\n    {\n        \/\/ skip readonly weight blob\n        if (bindings[i].data->state == 4)\n            continue;\n\n        record_prepare_compute_barrier(bindings[i]);\n    }\n\n    record_bind_pipeline(pipeline->pipeline);\n\n    record_update_bindings(pipeline->pipeline_layout, pipeline->descriptorset_layout, pipeline->descriptor_update_template, bindings);\n\n    record_push_constants(pipeline->pipeline_layout, constants);\n\n    uint32_t group_count_xyz[3];\n    group_count_xyz[0] = (m.w + pipeline->local_size_x - 1) \/ pipeline->local_size_x;\n    group_count_xyz[1] = (m.h + pipeline->local_size_y - 1) \/ pipeline->local_size_y;\n    group_count_xyz[2] = (m.c + pipeline->local_size_z - 1) \/ pipeline->local_size_z;\n\n    record_dispatch(group_count_xyz);\n}\n\nvoid VkCompute::record_bind_pipeline(VkPipeline pipeline)\n{\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n        return bind_pipeline(pipeline);\n\n    record_type r;\n    r.type = 2;\n    r.bind_pipeline.pipeline = pipeline;\n    delayed_records.push_back(r);\n}\n\nvoid VkCompute::record_update_bindings(VkPipelineLayout pipeline_layout, VkDescriptorSetLayout descriptorset_layout, VkDescriptorUpdateTemplateKHR descriptor_update_template, const std::vector<VkMat>& bindings)\n{\n    const int binding_count = bindings.size();\n\n    if (binding_count == 0)\n        return;\n\n    std::vector<VkDescriptorBufferInfo> descriptorBufferInfos(binding_count);\n    for (int i=0; i<binding_count; i++)\n    {\n        descriptorBufferInfos[i].buffer = bindings[i].buffer();\n        descriptorBufferInfos[i].offset = bindings[i].buffer_offset();\n        descriptorBufferInfos[i].range = bindings[i].total() * bindings[i].elemsize;\n    }\n\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n        return update_bindings(pipeline_layout, descriptor_update_template, descriptorBufferInfos);\n\n    \/\/ create new descriptor_pool and descriptorset\n    VkDescriptorPool descriptor_pool;\n    {\n        VkDescriptorPoolSize poolSize;\n        poolSize.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;\n        poolSize.descriptorCount = binding_count;\n\n        VkDescriptorPoolCreateInfo descriptorPoolCreateInfo;\n        descriptorPoolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;\n        descriptorPoolCreateInfo.pNext = 0;\n        descriptorPoolCreateInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;\n        descriptorPoolCreateInfo.maxSets = 1;\n        descriptorPoolCreateInfo.poolSizeCount = 1;\n        descriptorPoolCreateInfo.pPoolSizes = &poolSize;\n\n        VkResult ret = vkCreateDescriptorPool(vkdev->vkdevice(), &descriptorPoolCreateInfo, 0, &descriptor_pool);\n        if (ret != VK_SUCCESS)\n        {\n            fprintf(stderr, \"vkCreateDescriptorPool failed %d\\n\", ret);\n            return;\n        }\n    }\n    descriptor_pools.push_back(descriptor_pool);\n\n    VkDescriptorSet descriptorset;\n    {\n        VkDescriptorSetAllocateInfo descriptorSetAllocateInfo;\n        descriptorSetAllocateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;\n        descriptorSetAllocateInfo.pNext = 0;\n        descriptorSetAllocateInfo.descriptorPool = descriptor_pool;\n        descriptorSetAllocateInfo.descriptorSetCount = 1;\n        descriptorSetAllocateInfo.pSetLayouts = &descriptorset_layout;\n\n        VkResult ret = vkAllocateDescriptorSets(vkdev->vkdevice(), &descriptorSetAllocateInfo, &descriptorset);\n        if (ret != VK_SUCCESS)\n        {\n            fprintf(stderr, \"vkAllocateDescriptorSets failed %d\\n\", ret);\n            return;\n        }\n    }\n    descriptorsets.push_back(descriptorset);\n\n\/\/     fprintf(stderr, \"update descriptorset %p\\n\", descriptorset);\n\n    if (vkdev->info.support_VK_KHR_descriptor_update_template)\n    {\n        vkdev->vkUpdateDescriptorSetWithTemplateKHR(vkdev->vkdevice(), descriptorset, descriptor_update_template, descriptorBufferInfos.data());\n    }\n    else\n    {\n        std::vector<VkWriteDescriptorSet> writeDescriptorSets(binding_count);\n        for (int i=0; i<binding_count; i++)\n        {\n            writeDescriptorSets[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;\n            writeDescriptorSets[i].pNext = 0;\n            writeDescriptorSets[i].dstSet = descriptorset;\n            writeDescriptorSets[i].dstBinding = i;\n            writeDescriptorSets[i].dstArrayElement = 0;\n            writeDescriptorSets[i].descriptorCount = 1;\n            writeDescriptorSets[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;\n            writeDescriptorSets[i].pImageInfo = 0;\n            writeDescriptorSets[i].pBufferInfo = &descriptorBufferInfos[i];\n            writeDescriptorSets[i].pTexelBufferView = 0;\n        }\n\n        vkUpdateDescriptorSets(vkdev->vkdevice(), binding_count, writeDescriptorSets.data(), 0, 0);\n    }\n\n    record_type r;\n    r.type = 3;\n    r.bind_descriptorset.pipeline_layout = pipeline_layout;\n    r.bind_descriptorset.descriptorset = descriptorset;\n    delayed_records.push_back(r);\n}\n\nvoid VkCompute::record_push_constants(VkPipelineLayout pipeline_layout, const std::vector<vk_constant_type>& constants)\n{\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n        return push_constants(pipeline_layout, constants);\n\n    record_type r;\n    r.type = 4;\n    r.push_constants.pipeline_layout = pipeline_layout;\n    r.constants = constants;\n    delayed_records.push_back(r);\n}\n\nvoid VkCompute::record_dispatch(const uint32_t* group_count_xyz)\n{\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n        return dispatch(group_count_xyz);\n\n    record_type r;\n    r.type = 5;\n    r.dispatch.group_count_xyz[0] = group_count_xyz[0];\n    r.dispatch.group_count_xyz[1] = group_count_xyz[1];\n    r.dispatch.group_count_xyz[2] = group_count_xyz[2];\n    delayed_records.push_back(r);\n}\n\nvoid VkCompute::record_transfer_compute_barrier(const VkMat& m)\n{\n    m.data->state = 3;\n\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n        return transfer_compute_barrier(m.buffer(), m.buffer_offset(), m.total() * m.elemsize);\n\n    record_type r;\n    r.type = 6;\n    r.transfer_compute_barrier.buffer = m.buffer();\n    r.transfer_compute_barrier.offset = m.buffer_offset();\n    r.transfer_compute_barrier.size = m.total() * m.elemsize;\n    delayed_records.push_back(r);\n}\n\nvoid VkCompute::record_compute_transfer_barrier(const VkMat& m)\n{\n    m.data->state = 2;\n\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n        return compute_transfer_barrier(m.buffer(), m.buffer_offset(), m.total() * m.elemsize);\n\n    record_type r;\n    r.type = 7;\n    r.compute_transfer_barrier.buffer = m.buffer();\n    r.compute_transfer_barrier.offset = m.buffer_offset();\n    r.compute_transfer_barrier.size = m.total() * m.elemsize;\n    delayed_records.push_back(r);\n}\n\nvoid VkCompute::record_compute_compute_barrier(const VkMat& m)\n{\n    m.data->state = 3;\n\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n        return compute_compute_barrier(m.buffer(), m.buffer_offset(), m.total() * m.elemsize);\n\n    record_type r;\n    r.type = 8;\n    r.compute_compute_barrier.buffer = m.buffer();\n    r.compute_compute_barrier.offset = m.buffer_offset();\n    r.compute_compute_barrier.size = m.total() * m.elemsize;\n    delayed_records.push_back(r);\n}\n\nvoid VkCompute::record_transfer_transfer_barrier(const VkMat& m)\n{\n    m.data->state = 2;\n\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n        return transfer_transfer_barrier(m.buffer(), m.buffer_offset(), m.total() * m.elemsize);\n\n    record_type r;\n    r.type = 9;\n    r.transfer_transfer_barrier.buffer = m.buffer();\n    r.transfer_transfer_barrier.offset = m.buffer_offset();\n    r.transfer_transfer_barrier.size = m.total() * m.elemsize;\n    delayed_records.push_back(r);\n}\n\nvoid VkCompute::record_prepare_transfer_barrier(const VkMat& m)\n{\n    if (m.data->state == 2)\n        return record_transfer_transfer_barrier(m);\n\n    if (m.data->state == 3)\n        return record_compute_transfer_barrier(m);\n\n    m.data->state = 2;\n}\n\nvoid VkCompute::record_prepare_compute_barrier(const VkMat& m)\n{\n    if (m.data->state == 2)\n        return record_transfer_compute_barrier(m);\n\n    if (m.data->state == 3)\n        return record_compute_compute_barrier(m);\n\n    m.data->state = 3;\n}\n\nint VkCompute::submit()\n{\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n    {\n        end_command_buffer();\n\n        return queue_submit();\n    }\n\n    begin_command_buffer();\n\n    \/\/ handle delayed records\n    for (size_t i=0; i<delayed_records.size(); i++)\n    {\n        const record_type& r = delayed_records[i];\n\n        switch (r.type)\n        {\n        case 0:\n            copy_buffer(r.copy.src, r.copy.src_offset, r.copy.dst, r.copy.dst_offset, r.copy.size);\n            break;\n        case 1:\n            copy_buffer_regions(r.copy_regions.src, r.copy_regions.dst, r.regions);\n            break;\n        case 2:\n            bind_pipeline(r.bind_pipeline.pipeline);\n            break;\n        case 3:\n            bind_descriptorset(r.bind_descriptorset.pipeline_layout, r.bind_descriptorset.descriptorset);\n            break;\n        case 4:\n            push_constants(r.push_constants.pipeline_layout, r.constants);\n            break;\n        case 5:\n            dispatch(r.dispatch.group_count_xyz);\n            break;\n        case 6:\n            transfer_compute_barrier(r.transfer_compute_barrier.buffer, r.transfer_compute_barrier.offset, r.transfer_compute_barrier.size);\n            break;\n        case 7:\n            compute_transfer_barrier(r.compute_transfer_barrier.buffer, r.compute_transfer_barrier.offset, r.compute_transfer_barrier.size);\n            break;\n        case 8:\n            compute_compute_barrier(r.compute_compute_barrier.buffer, r.compute_compute_barrier.offset, r.compute_compute_barrier.size);\n            break;\n        case 9:\n            transfer_transfer_barrier(r.compute_compute_barrier.buffer, r.compute_compute_barrier.offset, r.compute_compute_barrier.size);\n            break;\n        }\n    }\n\n    end_command_buffer();\n\n    delayed_records.clear();\n\n    return queue_submit();\n}\n\nint VkCompute::wait()\n{\n    return wait_fence();\n}\n\nint VkCompute::reset()\n{\n\/\/     fprintf(stderr, \"cmd reset\\n\");\n\n    VkResult ret = vkResetCommandBuffer(command_buffer, 0);\n    if (ret != VK_SUCCESS)\n    {\n        fprintf(stderr, \"vkResetCommandBuffer failed %d\\n\", ret);\n        return -1;\n    }\n\n    ret = vkResetFences(vkdev->vkdevice(), 1, &fence);\n    if (ret != VK_SUCCESS)\n    {\n        fprintf(stderr, \"vkResetFences failed %d\\n\", ret);\n        return -1;\n    }\n\n    if (vkdev->info.support_VK_KHR_push_descriptor)\n    {\n        begin_command_buffer();\n    }\n\n    return 0;\n}\n\nvoid VkCompute::copy_buffer(VkBuffer src, size_t src_offset, VkBuffer dst, size_t dst_offset, size_t size)\n{\n\/\/     fprintf(stderr, \"cmd copy %p to %p\\n\", src, dst);\n\n    VkBufferCopy region;\n    region.srcOffset = src_offset;\n    region.dstOffset = dst_offset;\n    region.size = size;\n\n    vkCmdCopyBuffer(command_buffer, src, dst, 1, &region);\n}\n\nvoid VkCompute::copy_buffer_regions(VkBuffer src, VkBuffer dst, const std::vector<VkBufferCopy>& regions)\n{\n\/\/     fprintf(stderr, \"cmd copy regions %p to %p\\n\", src, dst);\n\n    vkCmdCopyBuffer(command_buffer, src, dst, regions.size(), regions.data());\n}\n\nvoid VkCompute::bind_pipeline(VkPipeline pipeline)\n{\n\/\/     fprintf(stderr, \"cmd bind_pipeline %p\\n\", pipeline);\n\n    vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);\n}\n\nvoid VkCompute::bind_descriptorset(VkPipelineLayout pipeline_layout, VkDescriptorSet descriptorset)\n{\n\/\/     fprintf(stderr, \"cmd bind_descriptorset %p %p\\n\", pipeline_layout, descriptorset);\n\n    vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_layout, 0, 1, &descriptorset, 0, 0);\n}\n\nvoid VkCompute::update_bindings(VkPipelineLayout pipeline_layout, VkDescriptorUpdateTemplateKHR descriptor_update_template, const std::vector<VkDescriptorBufferInfo>& descriptorBufferInfos)\n{\n\/\/     fprintf(stderr, \"cmd update_bindings %p %p\\n\", pipeline_layout, descriptor_update_template);\n\n    vkdev->vkCmdPushDescriptorSetWithTemplateKHR(command_buffer, descriptor_update_template, pipeline_layout, 0, descriptorBufferInfos.data());\n}\n\nvoid VkCompute::push_constants(VkPipelineLayout pipeline_layout, const std::vector<vk_constant_type>& constants)\n{\n\/\/     fprintf(stderr, \"cmd push_constants %p\\n\", pipeline_layout);\n\n    vkCmdPushConstants(command_buffer, pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, constants.size() * sizeof(vk_constant_type), constants.data());\n}\n\nvoid VkCompute::dispatch(const uint32_t* group_count_xyz)\n{\n\/\/     fprintf(stderr, \"cmd dispatch %d %d %d\\n\", group_count_xyz[0], group_count_xyz[1], group_count_xyz[2]);\n\n    vkCmdDispatch(command_buffer, group_count_xyz[0], group_count_xyz[1], group_count_xyz[2]);\n}\n\nvoid VkCompute::transfer_compute_barrier(VkBuffer buffer, size_t offset, size_t size)\n{\n\/\/     fprintf(stderr, \"cmd transfer_compute_barrier %p\\n\", buffer);\n\n    VkBufferMemoryBarrier bufferBarrier;\n    bufferBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;\n    bufferBarrier.pNext = 0;\n    bufferBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;\n    bufferBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;\n    bufferBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    bufferBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    bufferBarrier.buffer = buffer;\n    bufferBarrier.offset = offset;\n    bufferBarrier.size = size;\n\n    VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;\n    VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;\n\n    vkCmdPipelineBarrier(command_buffer, srcStageMask, dstStageMask, 0, 0, 0, 1, &bufferBarrier, 0, 0);\n}\n\nvoid VkCompute::compute_transfer_barrier(VkBuffer buffer, size_t offset, size_t size)\n{\n\/\/     fprintf(stderr, \"cmd compute_transfer_barrier %p\\n\", buffer);\n\n    VkBufferMemoryBarrier bufferBarrier;\n    bufferBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;\n    bufferBarrier.pNext = 0;\n    bufferBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;\n    bufferBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;\n    bufferBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    bufferBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    bufferBarrier.buffer = buffer;\n    bufferBarrier.offset = offset;\n    bufferBarrier.size = size;\n\n    VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;\n    VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;\n\n    vkCmdPipelineBarrier(command_buffer, srcStageMask, dstStageMask, 0, 0, 0, 1, &bufferBarrier, 0, 0);\n}\n\nvoid VkCompute::compute_compute_barrier(VkBuffer buffer, size_t offset, size_t size)\n{\n\/\/     fprintf(stderr, \"cmd compute_compute_barrier %p\\n\", buffer);\n\n    VkBufferMemoryBarrier bufferBarrier;\n    bufferBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;\n    bufferBarrier.pNext = 0;\n    bufferBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;\n    bufferBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;\n    bufferBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    bufferBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    bufferBarrier.buffer = buffer;\n    bufferBarrier.offset = offset;\n    bufferBarrier.size = size;\n\n    VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;\n    VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;\n\n    vkCmdPipelineBarrier(command_buffer, srcStageMask, dstStageMask, 0, 0, 0, 1, &bufferBarrier, 0, 0);\n}\n\nvoid VkCompute::transfer_transfer_barrier(VkBuffer buffer, size_t offset, size_t size)\n{\n\/\/     fprintf(stderr, \"cmd transfer_transfer_barrier %p\\n\", buffer);\n\n    VkBufferMemoryBarrier bufferBarrier;\n    bufferBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;\n    bufferBarrier.pNext = 0;\n    bufferBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;\n    bufferBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;\n    bufferBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    bufferBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n    bufferBarrier.buffer = buffer;\n    bufferBarrier.offset = offset;\n    bufferBarrier.size = size;\n\n    VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;\n    VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;\n\n    vkCmdPipelineBarrier(command_buffer, srcStageMask, dstStageMask, 0, 0, 0, 1, &bufferBarrier, 0, 0);\n}\n\nVkTransfer::VkTransfer(const VulkanDevice* _vkdev) : Command(_vkdev, _vkdev->info.transfer_queue_index)\n{\n    buffer_offset_alignment = vkdev->info.buffer_offset_alignment;\n    staging_data = 0;\n}\n\nVkTransfer::~VkTransfer()\n{\n}\n\nvoid VkTransfer::record_upload(const Mat& src, VkMat& dst)\n{\n    dst.create_like(src, weight_vkallocator, staging_vkallocator);\n\n    \/\/ set weight blob as readonly\n    dst.data->state = 4;\n\n    if (dst.allocator->mappable)\n    {\n        dst.upload(src);\n        return;\n    }\n\n    record_type r;\n    r.type = 0;\n    r.size = src.total() * src.elemsize;\n    r.mat = src;\n    r.vkmat = dst;\n    delayed_records.push_back(r);\n}\n\nvoid VkTransfer::record_download(const VkMat& src, Mat& dst)\n{\n    dst.create_like(src);\/\/ TODO respect blob allocator\n\n    if (src.allocator->mappable)\n    {\n        src.download(dst);\n        return;\n    }\n\n    record_type r;\n    r.type = 1;\n    r.size = src.total() * src.elemsize;\n    r.mat = dst;\n    r.vkmat = src;\n    delayed_records.push_back(r);\n}\n\nint VkTransfer::submit()\n{\n    if (delayed_records.empty())\n        return 0;\n\n    int transfer_count = delayed_records.size();\n\n    \/\/ solve staging buffer size\n    size_t staging_buffer_size = 0;\n    for (int i=0; i<transfer_count; i++)\n    {\n        const record_type& r = delayed_records[i];\n        staging_buffer_size += alignSize(r.size, buffer_offset_alignment);\n    }\n\n    \/\/ TODO sperated staging buffer for upload and download ?\n    \/\/ allocate staging buffer\n    staging_data = staging_vkallocator->fastMalloc(staging_buffer_size);\n\n    \/\/ copy upload data\n    size_t mapped_ptr_offset = 0;\n    for (int i=0; i<transfer_count; i++)\n    {\n        const record_type& r = delayed_records[i];\n        if (r.type == 0)\n        {\n            memcpy((unsigned char*)staging_data->mapped_ptr + mapped_ptr_offset, r.mat.data, r.size);\n        }\n\n        mapped_ptr_offset += alignSize(r.size, buffer_offset_alignment);\n    }\n\n    begin_command_buffer();\n\n\/\/     fprintf(stderr, \"cmd transfer %p %lu\\n\", staging_data->buffer, staging_buffer_size);\n\n    \/\/ handle delayed records\n    size_t staging_buffer_offset = 0;\n    for (int i=0; i<transfer_count; i++)\n    {\n        const record_type& r = delayed_records[i];\n\n        switch (r.type)\n        {\n        case 0:\n            copy_buffer(staging_data->buffer, staging_buffer_offset, r.vkmat.buffer(), r.vkmat.buffer_offset(), r.size);\n            break;\n        case 1:\n            copy_buffer(r.vkmat.buffer(), r.vkmat.buffer_offset(), staging_data->buffer, staging_buffer_offset, r.size);\n            break;\n        }\n\n        staging_buffer_offset += alignSize(r.size, buffer_offset_alignment);\n    }\n\n    end_command_buffer();\n\n    return queue_submit();\n}\n\nint VkTransfer::wait()\n{\n    if (delayed_records.empty())\n        return 0;\n\n    int ret = wait_fence();\n\n    int transfer_count = delayed_records.size();\n\n    \/\/ copy download data\n    size_t mapped_ptr_offset = 0;\n    for (int i=0; i<transfer_count; i++)\n    {\n        const record_type& r = delayed_records[i];\n        if (r.type == 1)\n        {\n            memcpy(r.mat.data, (unsigned char*)staging_data->mapped_ptr + mapped_ptr_offset, r.size);\n        }\n\n        mapped_ptr_offset += alignSize(r.size, buffer_offset_alignment);\n    }\n\n    \/\/ deallocate staging buffer\n    staging_vkallocator->fastFree(staging_data);\n\n    staging_data = 0;\n\n    delayed_records.clear();\n\n    return ret;\n}\n\nvoid VkTransfer::copy_buffer(VkBuffer src, size_t src_offset, VkBuffer dst, size_t dst_offset, size_t size)\n{\n\/\/     fprintf(stderr, \"cmd copy %p to %p\\n\", src, dst);\n\n    VkBufferCopy region;\n    region.srcOffset = src_offset;\n    region.dstOffset = dst_offset;\n    region.size = size;\n\n    vkCmdCopyBuffer(command_buffer, src, dst, 1, &region);\n}\n\nvoid VkTransfer::copy_buffer_regions(VkBuffer src, VkBuffer dst, const std::vector<VkBufferCopy>& regions)\n{\n\/\/     fprintf(stderr, \"cmd copy regions %p to %p\\n\", src, dst);\n\n    vkCmdCopyBuffer(command_buffer, src, dst, regions.size(), regions.data());\n}\n\n} \/\/ namespace ncnn\n\n#endif \/\/ NCNN_VULKAN\n","avg_line_length":31.9090909091,"max_line_length":210,"alphanum_fraction":0.7027188632,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2346,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/* Copyright 2017 R. Thomas\n * Copyright 2017 Quarkslab\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <string>\n#include <sstream>\n\n#include \"LIEF\/MachO\/hash.hpp\"\n#include \"LIEF\/MachO\/LoadCommand.hpp\"\n\n#include \"pyMachO.hpp\"\n\nnamespace LIEF {\nnamespace MachO {\n\ntemplate<class T>\nusing getter_t = T (LoadCommand::*)(void) const;\n\ntemplate<class T>\nusing setter_t = void (LoadCommand::*)(T);\n\n\ntemplate<>\nvoid create<LoadCommand>(py::module& m) {\n\n  py::class_<LoadCommand, LIEF::Object>(m, \"LoadCommand\")\n    .def(py::init<>())\n\n    .def_property(\"command\",\n        static_cast<getter_t<LOAD_COMMAND_TYPES>>(&LoadCommand::command),\n        static_cast<setter_t<LOAD_COMMAND_TYPES>>(&LoadCommand::command),\n        \"Command type ( \" RST_CLASS_REF(lief.MachO.LOAD_COMMAND_TYPES) \")\"\n        )\n\n    .def_property(\"size\",\n        static_cast<getter_t<uint32_t>>(&LoadCommand::size),\n        static_cast<setter_t<uint32_t>>(&LoadCommand::size),\n        \"Command size\")\n\n    .def_property(\"data\",\n        static_cast<getter_t<const std::vector<uint8_t>&>>(&LoadCommand::data),\n        static_cast<setter_t<const std::vector<uint8_t>&>>(&LoadCommand::data),\n        \"Command's data\")\n\n    .def_property(\"command_offset\",\n        static_cast<getter_t<uint64_t>>(&LoadCommand::command_offset),\n        static_cast<setter_t<uint64_t>>(&LoadCommand::command_offset),\n        \"Offset to the comand\")\n\n    .def(\"__eq__\", &LoadCommand::operator==)\n    .def(\"__ne__\", &LoadCommand::operator!=)\n    .def(\"__hash__\",\n        [] (const LoadCommand& load_command) {\n          return Hash::hash(load_command);\n        })\n\n    .def(\"__str__\",\n        [] (const LoadCommand& command)\n        {\n          std::ostringstream stream;\n          stream << command;\n          std::string str = stream.str();\n          return str;\n        });\n}\n\n\n}\n}\n","avg_line_length":28.962962963,"max_line_length":79,"alphanum_fraction":0.663256607,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":15425,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/ Concord\n\/\/\n\/\/ Copyright (c) 2019 VMware, Inc. All Rights Reserved.\n\/\/\n\/\/ This product is licensed to you under the Apache 2.0 license (the \"License\").\n\/\/ You may not use this product except in compliance with the Apache 2.0 License.\n\/\/\n\/\/ This product may include a number of subcomponents with separate copyright\n\/\/ notices and license terms. Your use of these subcomponents is subject to the\n\/\/ terms and conditions of the sub-component's license, as noted in the\n\/\/ LICENSE file.\n\n#include \"PersistentStorageImp.hpp\"\n#include \"threshsign\/IThresholdSigner.h\"\n#include \"threshsign\/IThresholdVerifier.h\"\n#include \"..\/simpleStorage\/FileStorage.hpp\"\n#include \"..\/..\/src\/bftengine\/PersistentStorage.hpp\"\n#include \"..\/..\/src\/bftengine\/PersistentStorageWindows.hpp\"\n#include \"Logger.hpp\"\n#include \"Serializable.h\"\n#include <string>\n#include <cassert>\n\nusing namespace std;\nusing namespace bftEngine;\nusing namespace bftEngine::impl;\nusing namespace concord::serialize;\n\nvoid printRawBuf(const UniquePtrToChar &buf, int64_t bufSize) {\n  for (int i = 0; i < bufSize; ++i) {\n    char c = buf.get()[i];\n    if (c >= 48 && c <= 57)\n      printf(\"%d\\n\", c);\n    else\n      printf(\"%c\\n\", c);\n  }\n}\n\nuint16_t fVal = 2;\nuint16_t cVal = 1;\n\nconst uint16_t msgsNum = 2 * fVal + 2 * cVal + 1;\n\ntypedef pair<uint16_t, string> IdToKeyPair;\n\nReplicaConfig &config = ReplicaConfig::instance();\nbftEngine::impl::PersistentStorageImp *persistentStorageImp = nullptr;\nunique_ptr<MetadataStorage> metadataStorage;\n\nSeqNum lastExecutedSeqNum = 0;\nSeqNum primaryLastUsedSeqNum = 0;\nSeqNum strictLowerBoundOfSeqNums = 0;\nViewNum lastViewTransferredSeqNum = 0;\nSeqNum lastStableSeqNum = 0;\n\nDescriptorOfLastExitFromView *descriptorOfLastExitFromView = nullptr;\nDescriptorOfLastNewView *descriptorOfLastNewView = nullptr;\nDescriptorOfLastExecution *descriptorOfLastExecution = nullptr;\n\nSeqNumWindow seqNumWindow{1};\nCheckWindow checkWindow{0};\n\nvoid testInit() {\n  ConcordAssert(persistentStorageImp->getStoredVersion() == persistentStorageImp->getCurrentVersion());\n  ConcordAssert(persistentStorageImp->getLastExecutedSeqNum() == lastExecutedSeqNum);\n  ConcordAssert(persistentStorageImp->getPrimaryLastUsedSeqNum() == primaryLastUsedSeqNum);\n  ConcordAssert(persistentStorageImp->getStrictLowerBoundOfSeqNums() == strictLowerBoundOfSeqNums);\n  ConcordAssert(persistentStorageImp->getLastViewThatTransferredSeqNumbersFullyExecuted() == lastViewTransferredSeqNum);\n  ConcordAssert(persistentStorageImp->getLastStableSeqNum() == lastStableSeqNum);\n\n  DescriptorOfLastExitFromView lastExitFromView = persistentStorageImp->getAndAllocateDescriptorOfLastExitFromView();\n  ConcordAssert(lastExitFromView.equals(*descriptorOfLastExitFromView));\n  bool descHasSet = persistentStorageImp->hasDescriptorOfLastExitFromView();\n  ConcordAssert(!descHasSet);\n\n  DescriptorOfLastNewView lastNewView = persistentStorageImp->getAndAllocateDescriptorOfLastNewView();\n  ConcordAssert(lastNewView.equals(*descriptorOfLastNewView));\n  descHasSet = persistentStorageImp->hasDescriptorOfLastNewView();\n  ConcordAssert(!descHasSet);\n\n  DescriptorOfLastExecution lastExecution = persistentStorageImp->getDescriptorOfLastExecution();\n  ConcordAssert(lastExecution.equals(*descriptorOfLastExecution));\n  descHasSet = persistentStorageImp->hasDescriptorOfLastExecution();\n  ConcordAssert(!descHasSet);\n\n  descriptorOfLastExitFromView->clean();\n  lastExitFromView.clean();\n  descriptorOfLastNewView->clean();\n  lastNewView.clean();\n\n  SharedPtrCheckWindow storedCheckWindow = persistentStorageImp->getCheckWindow();\n  ConcordAssert(storedCheckWindow.get()->equals(checkWindow));\n\n  SharedPtrSeqNumWindow storedSeqNumWindow = persistentStorageImp->getSeqNumWindow();\n  ConcordAssert(storedSeqNumWindow.get()->equals(seqNumWindow));\n}\n\nvoid testCheckWindowSetUp(const SeqNum shift, bool toSet) {\n  const SeqNum checkpointSeqNum0 = 0;\n  const SeqNum checkpointSeqNum1 = 150;\n  const SeqNum checkpointSeqNum2 = 300;\n\n  ReplicaId sender = 3;\n  Digest stateDigest;\n  const bool stateIsStable = true;\n  CheckpointMsg checkpointInitialMsg0(sender, checkpointSeqNum0, stateDigest, stateIsStable);\n  CheckpointMsg checkpointInitialMsg1(sender, checkpointSeqNum1, stateDigest, stateIsStable);\n  CheckpointMsg checkpointInitialMsg2(sender, checkpointSeqNum2, stateDigest, stateIsStable);\n\n  const bool completed = true;\n\n  if (toSet) {\n    persistentStorageImp->beginWriteTran();\n    persistentStorageImp->setCheckpointMsgInCheckWindow(checkpointSeqNum0, &checkpointInitialMsg0);\n    persistentStorageImp->setCompletedMarkInCheckWindow(checkpointSeqNum0, completed);\n    persistentStorageImp->setCheckpointMsgInCheckWindow(checkpointSeqNum1, &checkpointInitialMsg1);\n    persistentStorageImp->setCompletedMarkInCheckWindow(checkpointSeqNum1, completed);\n    persistentStorageImp->setCheckpointMsgInCheckWindow(checkpointSeqNum2, &checkpointInitialMsg2);\n    persistentStorageImp->setCompletedMarkInCheckWindow(checkpointSeqNum2, completed);\n    persistentStorageImp->endWriteTran();\n  }\n\n  auto checkWindowPtr = persistentStorageImp->getCheckWindow();\n  CheckData &element0 = checkWindowPtr.get()->getByRealIndex(0);\n  CheckData &element1 = checkWindowPtr.get()->getByRealIndex(1);\n  CheckData &element2 = checkWindowPtr.get()->getByRealIndex(2);\n\n  if (!shift) {\n    ConcordAssert(element0.getCheckpointMsg()->equals(checkpointInitialMsg0));\n    ConcordAssert(completed == element0.getCompletedMark());\n  } else\n    ConcordAssert(element0.equals(CheckData()));\n\n  ConcordAssert(element1.getCheckpointMsg()->equals(checkpointInitialMsg1));\n  ConcordAssert(element2.getCheckpointMsg()->equals(checkpointInitialMsg2));\n\n  ConcordAssert(completed == element1.getCompletedMark());\n  ConcordAssert(completed == element2.getCompletedMark());\n}\n\nvoid testSeqNumWindowSetUp(const SeqNum shift, bool toSet) {\n  const SeqNum prePrepareMsgSeqNum = 4;\n  ReplicaId sender = 2;\n  ViewNum view = 6;\n  CommitPath firstPath = CommitPath::FAST_WITH_THRESHOLD;\n  PrePrepareMsg prePrepareNullMsg(sender, view, prePrepareMsgSeqNum, firstPath, 0);\n\n  const SeqNum slowStartedSeqNum = 144;\n  bool slowStarted = true;\n\n  const SeqNum prePrepareFullSeqNum = 101;\n  PrepareFullMsg *prePrepareFullInitialMsg = PrepareFullMsg::create(view, prePrepareFullSeqNum, sender, nullptr, 0);\n\n  const SeqNum fullCommitProofSeqNum = 160;\n  FullCommitProofMsg fullCommitProofInitialMsg(sender, view, fullCommitProofSeqNum, nullptr, 0);\n\n  const bool forceCompleted = true;\n\n  const SeqNum commitFullSeqNum = 240;\n  CommitFullMsg *commitFullInitialMsg = CommitFullMsg::create(view, commitFullSeqNum, sender, nullptr, 0);\n\n  if (toSet) {\n    persistentStorageImp->beginWriteTran();\n    persistentStorageImp->setPrePrepareMsgInSeqNumWindow(prePrepareMsgSeqNum, &prePrepareNullMsg);\n    persistentStorageImp->setSlowStartedInSeqNumWindow(slowStartedSeqNum, slowStarted);\n    persistentStorageImp->setFullCommitProofMsgInSeqNumWindow(fullCommitProofSeqNum, &fullCommitProofInitialMsg);\n    persistentStorageImp->setForceCompletedInSeqNumWindow(commitFullSeqNum, forceCompleted);\n    persistentStorageImp->setPrepareFullMsgInSeqNumWindow(prePrepareFullSeqNum, prePrepareFullInitialMsg);\n    persistentStorageImp->setCommitFullMsgInSeqNumWindow(commitFullSeqNum, commitFullInitialMsg);\n    persistentStorageImp->endWriteTran();\n  }\n\n  const SeqNum prePrepareMsgSeqNumShifted = prePrepareMsgSeqNum + shift;\n  const SeqNum prePrepareFullSeqNumShifted = prePrepareFullSeqNum + shift;\n  const SeqNum fullCommitProofSeqNumShifted = fullCommitProofSeqNum + shift;\n  const SeqNum commitFullSeqNumShifted = commitFullSeqNum + shift;\n  const SeqNum slowStartedSeqNumShifted = slowStartedSeqNum + shift;\n\n  auto seqNumWindowPtr = persistentStorageImp->getSeqNumWindow();\n  SeqNum shiftedSeqNum = shift;\n  const SeqNumData emptySeqNumData;\n  for (SeqNum i = 0; i < kWorkWindowSize; ++i) {\n    ++shiftedSeqNum;\n    SeqNumData &element = seqNumWindowPtr.get()->getByRealIndex(i);\n    PrePrepareMsg *prePrepareMsg = element.getPrePrepareMsg();\n    FullCommitProofMsg *fullCommitProofMsg = element.getFullCommitProofMsg();\n    PrepareFullMsg *prepareFullMsg = element.getPrepareFullMsg();\n    CommitFullMsg *commitFullMsg = element.getCommitFullMsg();\n\n    if (!shift) {\n      if (prePrepareMsgSeqNumShifted == shiftedSeqNum - 1) {\n        ConcordAssert(prePrepareMsg->equals(prePrepareNullMsg));\n      } else\n        ConcordAssert(!prePrepareMsg);\n\n      if (prePrepareFullSeqNumShifted == shiftedSeqNum - 1) {\n        ConcordAssert(prepareFullMsg->equals(*prePrepareFullInitialMsg));\n      } else\n        ConcordAssert(!prepareFullMsg);\n\n      if (commitFullSeqNumShifted == shiftedSeqNum - 1) ConcordAssert(forceCompleted == element.getForceCompleted());\n      if (slowStartedSeqNumShifted == shiftedSeqNum - 1) ConcordAssert(slowStarted == element.getSlowStarted());\n    } else {\n      if ((fullCommitProofSeqNumShifted != shiftedSeqNum - 1) && (commitFullSeqNumShifted != shiftedSeqNum - 1))\n        ConcordAssert(element.equals(emptySeqNumData));\n    }\n    if (fullCommitProofSeqNumShifted == shiftedSeqNum - 1) {\n      ConcordAssert(fullCommitProofMsg->equals(fullCommitProofInitialMsg));\n    } else\n      ConcordAssert(!fullCommitProofMsg);\n\n    if (commitFullSeqNumShifted == shiftedSeqNum - 1) {\n      ConcordAssert(commitFullMsg->equals(*commitFullInitialMsg));\n    } else\n      ConcordAssert(!commitFullMsg);\n  }\n\n  delete prePrepareFullInitialMsg;\n  delete commitFullInitialMsg;\n}\n\nvoid testWindows(bool init) {\n  testCheckWindowSetUp(0, init);\n  testSeqNumWindowSetUp(0, init);\n}\n\nvoid testWindowsAdvance() {\n  const SeqNum moveToSeqNum = 150;\n  persistentStorageImp->beginWriteTran();\n  persistentStorageImp->setLastStableSeqNum(moveToSeqNum);\n  persistentStorageImp->endWriteTran();\n\n  ConcordAssert(moveToSeqNum == persistentStorageImp->getLastStableSeqNum());\n  testCheckWindowSetUp(moveToSeqNum, false);\n  testSeqNumWindowSetUp(moveToSeqNum, false);\n}\n\nvoid testSetDescriptors(bool toSet) {\n  SeqNum lastExecutionSeqNum = 33;\n  Bitmap requests(100);\n  DescriptorOfLastExecution lastExecutionDesc(lastExecutionSeqNum, requests);\n\n  ViewNum viewNum = 0;\n  SeqNum lastExitExecNum = 65;\n  PrevViewInfoElements elements;\n  ViewsManager::PrevViewInfo element;\n  ReplicaId senderId = 1;\n  element.hasAllRequests = true;\n  element.prePrepare = new PrePrepareMsg(senderId, viewNum, lastExitExecNum, CommitPath::OPTIMISTIC_FAST, 0);\n  element.prepareFull = PrepareFullMsg::create(viewNum, lastExitExecNum, senderId, nullptr, 0);\n  for (uint32_t i = 0; i < kWorkWindowSize; ++i) {\n    elements.push_back(element);\n  }\n  SeqNum lastExitStableNum = 60;\n  SeqNum lastExitStableLowerBound = 50;\n  SeqNum lastStable = 48;\n  auto *viewChangeMsg = new ViewChangeMsg(senderId, viewNum + 1, lastStable);\n  DescriptorOfLastExitFromView lastExitFromViewDesc(\n      viewNum, lastExitStableNum, lastExitExecNum, elements, viewChangeMsg, lastExitStableLowerBound);\n\n  ViewChangeMsgsVector msgs;\n  ViewNum newViewNum = 1;\n  for (auto i = 1; i <= msgsNum; i++) msgs.push_back(new ViewChangeMsg(i, newViewNum, lastExitStableNum));\n  SeqNum maxSeqNum = 200;\n  auto *newViewMsg = new NewViewMsg(0x01234, newViewNum);\n  SeqNum lastNewViewStableLowerBound = 51;\n  auto *lastNewViewViewChangeMsg = new ViewChangeMsg(senderId, newViewNum, lastStable + 2);\n  DescriptorOfLastNewView lastNewViewDesc(\n      newViewNum, newViewMsg, msgs, lastNewViewViewChangeMsg, lastNewViewStableLowerBound, maxSeqNum);\n\n  if (toSet) {\n    persistentStorageImp->beginWriteTran();\n    persistentStorageImp->setDescriptorOfLastExecution(lastExecutionDesc);\n    persistentStorageImp->setDescriptorOfLastExitFromView(lastExitFromViewDesc);\n    persistentStorageImp->setDescriptorOfLastNewView(lastNewViewDesc);\n    persistentStorageImp->endWriteTran();\n  }\n\n  DescriptorOfLastExecution lastExecution = persistentStorageImp->getDescriptorOfLastExecution();\n  ConcordAssert(lastExecution.equals(lastExecutionDesc));\n  bool descHasSet = persistentStorageImp->hasDescriptorOfLastExecution();\n  ConcordAssert(descHasSet);\n\n  DescriptorOfLastNewView lastNewView = persistentStorageImp->getAndAllocateDescriptorOfLastNewView();\n  ConcordAssert(lastNewView.equals(lastNewViewDesc));\n  descHasSet = persistentStorageImp->hasDescriptorOfLastNewView();\n  ConcordAssert(descHasSet);\n\n  DescriptorOfLastExitFromView lastExitFromView = persistentStorageImp->getAndAllocateDescriptorOfLastExitFromView();\n  ConcordAssert(lastExitFromView.equals(lastExitFromViewDesc));\n  descHasSet = persistentStorageImp->hasDescriptorOfLastExitFromView();\n  ConcordAssert(descHasSet);\n\n  for (auto *v : msgs) {\n    delete v;\n  }\n  delete element.prePrepare;\n  delete element.prepareFull;\n  lastExitFromView.clean();\n  lastNewView.clean();\n  delete viewChangeMsg;\n  delete newViewMsg;\n  delete lastNewViewViewChangeMsg;\n}\n\nvoid testSetSimpleParams(bool toSet) {\n  SeqNum lastExecSeqNum = 32;\n  SeqNum lastUsedSeqNum = 212;\n  SeqNum lowBoundSeqNum = 102;\n  ViewNum view = 800;\n\n  if (toSet) {\n    persistentStorageImp->beginWriteTran();\n    persistentStorageImp->setLastExecutedSeqNum(lastExecSeqNum);\n    persistentStorageImp->setPrimaryLastUsedSeqNum(lastUsedSeqNum);\n    persistentStorageImp->setStrictLowerBoundOfSeqNums(lowBoundSeqNum);\n    persistentStorageImp->setLastViewThatTransferredSeqNumbersFullyExecuted(view);\n    persistentStorageImp->endWriteTran();\n  }\n\n  ConcordAssert(persistentStorageImp->getLastExecutedSeqNum() == lastExecSeqNum);\n  ConcordAssert(persistentStorageImp->getPrimaryLastUsedSeqNum() == lastUsedSeqNum);\n  ConcordAssert(persistentStorageImp->getStrictLowerBoundOfSeqNums() == lowBoundSeqNum);\n  ConcordAssert(persistentStorageImp->getLastViewThatTransferredSeqNumbersFullyExecuted() == view);\n}\n\nint main() {\n  DescriptorOfLastNewView::setViewChangeMsgsNum(fVal, cVal);\n  descriptorOfLastExitFromView = new DescriptorOfLastExitFromView();\n  descriptorOfLastNewView = new DescriptorOfLastNewView();\n  descriptorOfLastExecution = new DescriptorOfLastExecution();\n\n  persistentStorageImp = new PersistentStorageImp(fVal, cVal);\n  logging::Logger logger = logging::getLogger(\"testSerialization.replica\");\n  \/\/ uncomment if needed\n  \/\/ log4cplus::Logger::getInstance( LOG4CPLUS_TEXT(\"serializable\")).setLogLevel(log4cplus::TRACE_LOG_LEVEL);\n  const string dbFile = \"testPersistency.txt\";\n  remove(dbFile.c_str());  \/\/ Required for the init testing.\n\n  PersistentStorageImp persistentStorage(fVal, cVal);\n  metadataStorage.reset(new FileStorage(logger, dbFile));\n  uint16_t numOfObjects = 0;\n  ObjectDescUniquePtr objectDescArray = persistentStorage.getDefaultMetadataObjectDescriptors(numOfObjects);\n  metadataStorage->initMaxSizeOfObjects(objectDescArray.get(), numOfObjects);\n  persistentStorageImp->init(move(metadataStorage));\n\n  testInit();\n\n  bool init = true;\n  for (auto i = 1; i <= 2; ++i) {\n    if (!init) {\n      \/\/ Re-open existing DB file\n      metadataStorage.reset();\n      metadataStorage.reset(new FileStorage(logger, dbFile));\n      metadataStorage->initMaxSizeOfObjects(objectDescArray.get(), numOfObjects);\n      persistentStorageImp->init(move(metadataStorage));\n    }\n    testSetSimpleParams(init);\n    testSetDescriptors(init);\n    testWindows(init);\n    if (!init) testWindowsAdvance();\n    init = false;\n  }\n\n  delete descriptorOfLastExitFromView;\n  delete descriptorOfLastNewView;\n  delete descriptorOfLastExecution;\n  delete persistentStorageImp;\n\n  return 0;\n}\n","avg_line_length":41.4650537634,"max_line_length":120,"alphanum_fraction":0.7876175041,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":269,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":102.0,"content":"\/\/ Copyright (c) 2013, Ruslan Baratov\n\/\/ All rights reserved.\n\n#include \"B.hpp\"\n\n#include \"A.hpp\"\n\ndouble B::foo(int x, int y) {\n#if defined(A_TARGET_MACRO)\n  A a;\n  a.foo();\n#endif\n  return 3.14159 + x + y;\n}\n\ndouble B::hacky_method(int x) {\n  return 7.0 + (x - x);\n}\n","avg_line_length":14.1578947368,"max_line_length":37,"alphanum_fraction":0.6133828996,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5814,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/*\r\n *  magicdraw.cpp\r\n *    2017.10.31  Takata\r\n *    Special thanks to Nakamura\r\n *\/\r\n\r\n\/* include files *\/\r\n#include \"DxLib.h\"\r\n#include <math.h>\r\n\r\n\/* define *\/\r\n#define WindowX 600\r\n#define WindowY 200\r\n#define Thickness 1\r\n\r\n\/* global variables *\/\r\nconst double PI = 3.14159265;\r\nint MouseX, MouseY;\r\nint MouseX_old, MouseY_old;\r\nint charSize = 200;\r\nint spaceSize = 100;\r\nint length_hen = 80;\r\nint OX = 60, OY = 20;\r\nunsigned int Cr;\r\nunsigned int RED;\r\n\r\n\/* function *\/\r\nvoid Convert1( double *length, double *angle );\r\nvoid Convert2( double length, double angle, int &x, int &y );\r\nvoid getPoint( int *x, int *y, int times, int devid, double length, double angle );\r\nvoid DrawDebug();\r\nvoid draw_1_ta( double length, double angle, bool flag );\r\nvoid draw_2_ka( double length, double angle, bool flag );\r\nvoid draw_3_ta( double length, double angle, bool flag );\r\n\r\n\/* main *\/\r\nint WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )\r\n{\r\n  double length, angle;\r\n  RED = GetColor( 255, 0, 0 );\r\n\r\n  SetOutApplicationLogValidFlag( FALSE );\r\n  SetGraphMode( WindowX , WindowY , 32 );\r\n  SetMainWindowText( \"MagicDraw\" );\r\n  ChangeWindowMode( TRUE );\r\n\r\n  if( DxLib_Init() == -1 ){ return -1; }\r\n\r\n  SetDrawScreen( DX_SCREEN_BACK );\r\n  GetMousePoint( &MouseX, &MouseY );\r\n  Convert1( &length, &angle );\r\n\r\n  while( ProcessMessage() == 0 && CheckHitKey( KEY_INPUT_ESCAPE ) == 0 )\r\n  {\r\n    \/\/ Color\r\n    Cr = GetColor( rand() % 256, rand() % 256, rand() % 256 );\r\n\r\n    \/\/ Mouse\r\n    MouseX_old = MouseX;\r\n    MouseY_old = MouseY;\r\n    GetMousePoint( &MouseX, &MouseY );\r\n\r\n    \/\/ Convert1\r\n    Convert1( &length, &angle );\r\n\r\n    \/\/ Draw\r\n    \/\/DrawDebug();\r\n    DrawLine( 70, 20, 70 - length_hen \/ sqrt( 2.0 ), 100, RED );\r\n    if( ( GetMouseInput() & MOUSE_INPUT_LEFT ) != 0 )\r\n    {\r\n      DrawLine( MouseX_old, MouseY_old, MouseX, MouseY, Cr, Thickness );\r\n      draw_1_ta( length, angle, true );\r\n      draw_2_ka( length, angle, true );\r\n      draw_3_ta( length, angle, true );\r\n    }\r\n    else\r\n    {\r\n      draw_1_ta( length, angle, false );\r\n      draw_2_ka( length, angle, false );\r\n      draw_3_ta( length, angle, false );\r\n    }\r\n\r\n    \/\/ Refresh\r\n    if( CheckHitKey(KEY_INPUT_SPACE) == 1 ){ ClearDrawScreen(); }\r\n\r\n    \/\/ Display\r\n    ScreenFlip();\r\n  }\r\n\r\n  DxLib_End();\r\n\r\n  return 0;\r\n}\r\n\r\n\/* comversion( Rect -> Pol ) *\/\r\nvoid Convert1( double *length, double *angle )\r\n{\r\n  double x = (double)MouseX - (double)OX;\r\n  double y = (double)MouseY - (double)OY;\r\n  *length = sqrt( x * x + y * y );\r\n  *angle  = atan2( y, x );\r\n}\r\n\r\n\/* conversion( Pol -> Rect ) *\/\r\nvoid Convert2( double length, double angle, int *x, int *y )\r\n{\r\n  *x =  length * cos( angle );\r\n  *y = -length * sin( angle );\r\n}\r\n\r\n\/* get rect-position *\/\r\nvoid getPoint( int *x, int *y, int times, int devid, double length, double angle )\r\n{\r\n  angle += PI * times \/ devid;\r\n  Convert2( length, angle, x, y );\r\n}\r\n\r\n\/* for adjustment *\/\r\nvoid DrawDebug()\r\n{\r\n  DrawLine( charSize,     0, charSize,     WindowY, RED );\r\n  DrawLine( charSize * 2, 0, charSize * 2, WindowY, RED );\r\n}\r\n\r\n\/* draw Ta(1) *\/\r\nvoid draw_1_ta( double length, double angle, bool flag )\r\n{\r\n  static const int stroke = 4;\r\n  int x[stroke], y[stroke];\r\n  static int x_old[stroke] = {0}, y_old[stroke] = {0};\r\n  static bool drawflag = false;\r\n  int i;\r\n  if( !flag )\r\n  {\r\n    drawflag = false;\r\n    return;\r\n  }\r\n\r\n  getPoint( &x[0], &y[0], -3, 4, length, angle );\r\n  x[0] += 80; y[0] += 20;\r\n  getPoint( &x[1], &y[1], 3, 5, length, angle );\r\n  x[1] += 180; y[1] += 50;\r\n  getPoint( &x[2], &y[2], 3, 5, length, angle );\r\n  x[2] += 130; y[2] += 120;\r\n  getPoint( &x[3], &y[3], -3, 4, length, angle );\r\n  x[3] += 40; y[3] += 70;\r\n\r\n  if( drawflag )\r\n  {\r\n    for( i = 0; i < stroke; i++ )\r\n    {\r\n      DrawLine( x_old[i], y_old[i], x[i], y[i], Cr, Thickness );\r\n    }\r\n  }\r\n  for( i = 0; i < stroke; i++ )\r\n  {\r\n    x_old[i] = x[i];\r\n    y_old[i] = y[i];\r\n  }\r\n  drawflag = true;\r\n}\r\n\r\n\/* draw Ka(2) *\/\r\nvoid draw_2_ka( double length, double angle, bool flag )\r\n{\r\n  static const int stroke = 4;\r\n  int x[stroke], y[stroke];\r\n  static int x_old[stroke] = {0}, y_old[stroke] = {0};\r\n  static bool drawflag = false;\r\n  int i;\r\n  if( !flag )\r\n  {\r\n    drawflag = false;\r\n    return;\r\n  }\r\n\r\n  getPoint( &x[0], &y[0], -11, 16, length, angle );\r\n  x[0] += 250; y[0] += 70;\r\n  getPoint( &x[1], &y[1], 7, 10, length, angle );\r\n  x[1] += 350; y[1] += 80;\r\n  getPoint( &x[2], &y[2], 7, 10, length, angle );\r\n  x[2] += 310; y[2] += 20;\r\n  getPoint( &x[3], &y[3], 7, 10, length, angle );\r\n  x[3] += 290; y[3] += 80;\r\n \r\n\r\n  if( drawflag )\r\n  {\r\n    for( i = 0; i < stroke; i++ )\r\n    {\r\n      DrawLine( x_old[i], y_old[i], x[i], y[i], Cr, Thickness );\r\n    }\r\n  }\r\n  for( i = 0; i < stroke; i++ )\r\n  {\r\n    x_old[i] = x[i];\r\n    y_old[i] = y[i];\r\n  }\r\n  drawflag = true;\r\n}\r\n\r\n\/* draw Ta(3) *\/\r\nvoid draw_3_ta( double length, double angle, bool flag )\r\n{\r\n  static const int stroke = 5;\r\n  int x[stroke], y[stroke];\r\n  static int x_old[stroke] = {0}, y_old[stroke] = {0};\r\n  static bool drawflag = false;\r\n  int i;\r\n  if( !flag )\r\n  {\r\n    drawflag = false;\r\n    return;\r\n  }\r\n\r\n  getPoint( &x[0], &y[0], 3, 5, length, angle );\r\n  x[0] += 480; y[0] += 30;\r\n  getPoint( &x[1], &y[1], -3, 4, length, angle );\r\n  x[1] += 480; y[1] += 20;\r\n  getPoint( &x[2], &y[2], 3, 5, length, angle );\r\n  x[2] += 580; y[2] += 50;\r\n  getPoint( &x[3], &y[3], 3, 5, length, angle );\r\n  x[3] += 530; y[3] += 120;\r\n  getPoint( &x[4], &y[4], -3, 4, length, angle );\r\n  x[4] += 440; y[4] += 70;\r\n\r\n  if( drawflag )\r\n  {\r\n    for( i = 0; i < stroke; i++ )\r\n    {\r\n      DrawLine( x_old[i], y_old[i], x[i], y[i], Cr, Thickness );\r\n    }\r\n  }\r\n  for( i = 0; i < stroke; i++ )\r\n  {\r\n    x_old[i] = x[i];\r\n    y_old[i] = y[i];\r\n  }\r\n  drawflag = true;\r\n}\r\n","avg_line_length":24.1244813278,"max_line_length":98,"alphanum_fraction":0.5404196766,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1893,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Fill out your copyright notice in the Description page of Project Settings.\n\n\n#include \"EditorGameMode.h\"\n\n#include \"MapGenerator\/MapActor.h\"\n\n#include \"Editor.h\"\n#include \"Kismet\/GameplayStatics.h\"\n\n\nUEditorGameMode* UEditorGameMode::EditorGameMode = nullptr;\n\n\nUEditorGameMode::UEditorGameMode() {\n}\n\nUEditorGameMode::~UEditorGameMode() {\n\t\n}\n\nvoid UEditorGameMode::Init() {\n\tMapActor = nullptr;\n\tMapActor = GetMapActor();\n\t\/\/SettingsObject = GetSettingsObject();\n}\n\nvoid UEditorGameMode::Delete() {\n\tMapActor->Destroy();\n\tMapActor = nullptr;\n\t\/\/SettingsObject = nullptr;\n}\n\nbool UEditorGameMode::IsInEditor() {\n\t\/\/TODO\n\treturn true;\n}\n\n\nAMapActor * UEditorGameMode::GetMapActor() {\n\tif(MapActor == nullptr) {\n\t\tMapActor = FindMapActorInMap();\n\t}\n\treturn MapActor;\n}\nAMapActor * UEditorGameMode::FindMapActorInMap() const {\n\n\tAMapActor* _MapActor = nullptr;\n\tTArray<AActor*> Out = TArray<AActor*>();\n\tUGameplayStatics::GetAllActorsOfClass(GetWorld(), AMapActor::StaticClass(), Out);\n\tif (Out.Num() > 0) {\n\t\t_MapActor = Cast<AMapActor>(Out[0]);\n\t}\n\tif(_MapActor == nullptr) {\n\t\tconst FVector Location = FVector(0.0f, 0.0f, 0.0f);\n\t\tconst FRotator Rotation = FRotator(0.0f, 0.0f, 0.0f);\n\t\t_MapActor = GetWorld()->SpawnActor<AMapActor>(AMapActor::StaticClass(), Location, Rotation);\n\t}\n\t_MapActor->Init();\n\treturn _MapActor;\n}\n\n\nUEditorGameMode * UEditorGameMode::Get() {\n\tif (EditorGameMode == nullptr) {\n\t\tEditorGameMode = new UEditorGameMode();\n\t\tEditorGameMode->Init();\n\t}\n\treturn EditorGameMode;\n}\n\nvoid UEditorGameMode::Destroy() {\n\tEditorGameMode->Delete();\n\tdelete EditorGameMode;\n\tEditorGameMode = nullptr;\n}\n\nUWorld * UEditorGameMode::GetWorld() {\n\tUWorld* World = nullptr;\n\tif (GEditor->bIsSimulatingInEditor) {\n\t\tWorld = GEditor->GetPIEWorldContext()->World();\n\t}\n\telse {\n\t\tWorld = GEditor->GetEditorWorldContext().World();\n\t}\n\tif(World == nullptr) {\n\t\t\/\/TODO\n\t}\n\treturn World;\n}","avg_line_length":21.0333333333,"max_line_length":94,"alphanum_fraction":0.7142102483,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":999,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":29.0,"content":"\/*\n\nName: Velvet\nAuthor: Alvy Piper <alvycat@protonmail.com>\nCSGO adaptation: aixxe <aixxe@skyenet.org>\nCopyright: 2015\nUsage: More complex than GreenTea and also SDKless. A simple internal cheat with bunnyhop and norecoil, written for CSPromod BETA 1.10b for fun.\nUsing content created by: Casual_Hacker ( http:\/\/www.unknowncheats.me\/forum\/member239231.html ), NanoCat, and Valve.\n\nAny content creator that wants their work removed can contact me on UnknownCheats for now. ( http:\/\/www.unknowncheats.me\/forum\/members\/334125.html )\n\nFeel free to redistribute, modify, and share. Please give credit where it is due, though.\n\n*\/\n\n#include \"velvet.h\"\n\nusing namespace velvet;\n\nvoid inject() \/\/TODO: Change this with init::finalize in DLLMain.\n{\n\tinit::finalize();\n}\n\nbool __stdcall entry(HINSTANCE inst, DWORD reason, LPVOID reserved)\n{\n\tif (reason == 1)\n\t{\n\t\tDisableThreadLibraryCalls(inst);\n\t\tCreateThread(0, 0, (LPTHREAD_START_ROUTINE) inject, 0, 0, 0);\n\t}\n\tTerminateThread(inject, 0);\n\treturn 1;\n}\n","avg_line_length":28.5428571429,"max_line_length":148,"alphanum_fraction":0.7537537538,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":16366,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":5.0,"content":"\/\/ Copyright (c) 2011-2015 The Bitcoin developers\n\/\/ Copyright (c) 2016-2018 The PIVX developers\n\/\/ Copyright (c) 2018 The Phore developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"walletview.h\"\n\n#include \"addressbookpage.h\"\n#include \"askpassphrasedialog.h\"\n#include \"bip38tooldialog.h\"\n#include \"bitcoingui.h\"\n#include \"blockexplorer.h\"\n#include \"clientmodel.h\"\n#include \"guiutil.h\"\n#include \"masternode\/masternodeconfig.h\"\n#include \"multisenddialog.h\"\n#include \"multisigdialog.h\"\n#include \"optionsmodel.h\"\n#include \"overviewpage.h\"\n#include \"receivecoinsdialog.h\"\n#include \"sendcoinsdialog.h\"\n#include \"signverifymessagedialog.h\"\n#include \"transactiontablemodel.h\"\n#include \"transactionview.h\"\n#include \"walletmodel.h\"\n#include \"proposallist.h\"\n\n#include \"ui_interface.h\"\n\n#include <QAction>\n#include <QActionGroup>\n#include <QFileDialog>\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QProgressDialog>\n#include <QPushButton>\n#include <QSettings>\n#include <QVBoxLayout>\n\nWalletView::WalletView(QWidget* parent) : QStackedWidget(parent),\n                                          clientModel(0),\n                                          walletModel(0)\n{   \n    \/\/ Create tabs\n    overviewPage = new OverviewPage();\n    explorerWindow = new BlockExplorer(this);\n    transactionsPage = new QWidget(this);\n\n    \/\/ Create Header with the same names as the other forms to be CSS-Id compatible\n    QFrame *frame_Header = new QFrame(transactionsPage);\n    frame_Header->setObjectName(QStringLiteral(\"frame_Header\"));\n\n    QVBoxLayout* verticalLayout_8 = new QVBoxLayout(frame_Header);\n    verticalLayout_8->setObjectName(QStringLiteral(\"verticalLayout_8\"));\n    verticalLayout_8->setContentsMargins(0, 0, 0, 0);\n\n    QHBoxLayout* horizontalLayout_Header = new QHBoxLayout();\n    horizontalLayout_Header->setObjectName(QStringLiteral(\"horizontalLayout_Header\"));\n\n    QLabel* labelOverviewHeaderLeft = new QLabel(frame_Header);\n    labelOverviewHeaderLeft->setObjectName(QStringLiteral(\"labelOverviewHeaderLeft\"));\n    labelOverviewHeaderLeft->setMinimumSize(QSize(464, 60));\n    labelOverviewHeaderLeft->setMaximumSize(QSize(16777215, 60));\n    labelOverviewHeaderLeft->setText(tr(\"HISTORY\"));\n    QFont fontHeaderLeft;\n    fontHeaderLeft.setPointSize(20);\n    fontHeaderLeft.setBold(true);\n    fontHeaderLeft.setWeight(75);\n    labelOverviewHeaderLeft->setFont(fontHeaderLeft);\n\n    horizontalLayout_Header->addWidget(labelOverviewHeaderLeft);\n    QSpacerItem* horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);\n    horizontalLayout_Header->addItem(horizontalSpacer_3);\n\n    QLabel* labelOverviewHeaderRight = new QLabel(frame_Header);\n    labelOverviewHeaderRight->setObjectName(QStringLiteral(\"labelOverviewHeaderRight\"));\n    labelOverviewHeaderRight->setMinimumSize(QSize(464, 60));\n    labelOverviewHeaderRight->setMaximumSize(QSize(16777215, 60));\n    labelOverviewHeaderRight->setText(QString());\n    QFont fontHeaderRight;\n    fontHeaderRight.setPointSize(14);\n    labelOverviewHeaderRight->setFont(fontHeaderRight);\n    labelOverviewHeaderRight->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);\n\n    horizontalLayout_Header->addWidget(labelOverviewHeaderRight);\n    horizontalLayout_Header->setStretch(0, 1);\n    horizontalLayout_Header->setStretch(2, 1);\n    verticalLayout_8->addLayout(horizontalLayout_Header);\n\n    QVBoxLayout* vbox = new QVBoxLayout();\n    QHBoxLayout* hbox_buttons = new QHBoxLayout();\n    vbox->addWidget(frame_Header);\n\n    transactionView = new TransactionView(this);\n    vbox->addWidget(transactionView);\n    QPushButton* exportButton = new QPushButton(tr(\"&Export\"), this);\n    exportButton->setToolTip(tr(\"Export the data in the current tab to a file\"));\n#ifndef Q_OS_MAC \/\/ Icons on push buttons are very uncommon on Mac\n    exportButton->setIcon(QIcon(\":\/icons\/export\"));\n#endif\n    hbox_buttons->addStretch();\n\n    \/\/ Sum of selected transactions\n    QLabel* transactionSumLabel = new QLabel();                \/\/ Label\n    transactionSumLabel->setObjectName(\"transactionSumLabel\"); \/\/ Label ID as CSS-reference\n    transactionSumLabel->setText(tr(\"Selected amount:\"));\n    hbox_buttons->addWidget(transactionSumLabel);\n\n    transactionSum = new QLabel();                   \/\/ Amount\n    transactionSum->setObjectName(\"transactionSum\"); \/\/ Label ID as CSS-reference\n    transactionSum->setMinimumSize(200, 8);\n    transactionSum->setTextInteractionFlags(Qt::TextSelectableByMouse);\n    hbox_buttons->addWidget(transactionSum);\n\n    hbox_buttons->addWidget(exportButton);\n    vbox->addLayout(hbox_buttons);\n    transactionsPage->setLayout(vbox);\n\n    receiveCoinsPage = new ReceiveCoinsDialog();\n    sendCoinsPage = new SendCoinsDialog();\n\n    addWidget(overviewPage);\n    addWidget(transactionsPage);\n    addWidget(receiveCoinsPage);\n    addWidget(sendCoinsPage);\n    addWidget(explorerWindow);\n\n    QSettings settings;\n    if (settings.value(\"fShowMasternodesTab\").toBool()) {\n        masternodeListPage = new MasternodeList();\n        addWidget(masternodeListPage);\n    }\n\t    \n    QVBoxLayout* vbox_2 = new QVBoxLayout();\n    proposalList = new ProposalList(this);\n    vbox_2->addWidget(proposalList);\n    vbox_2->setStretch(1, 1);\n    proposalListPage = new QWidget(this);\n    proposalListPage->setLayout(vbox_2);\n    addWidget(proposalListPage);\n\n    \/\/ Clicking on a transaction on the overview pre-selects the transaction on the transaction history page\n    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));\n\n    \/\/ Double-clicking on a transaction on the transaction history page shows details\n    connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));\n\n    \/\/ Update wallet with sum of selected transactions\n    connect(transactionView, SIGNAL(trxAmount(QString)), this, SLOT(trxAmount(QString)));\n\n    \/\/ Clicking on \"Export\" allows to export the transaction list\n    connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked()));\n\n    \/\/ Pass through messages from sendCoinsPage\n    connect(sendCoinsPage, SIGNAL(message(QString, QString, unsigned int)), this, SIGNAL(message(QString, QString, unsigned int)));\n\n    \/\/ Pass through messages from transactionView\n    connect(transactionView, SIGNAL(message(QString, QString, unsigned int)), this, SIGNAL(message(QString, QString, unsigned int)));\n}\n\nWalletView::~WalletView()\n{\n}\n\nvoid WalletView::setBitcoinGUI(BitcoinGUI* gui)\n{\n    if (gui) {\n        \/\/ Clicking on a transaction on the overview page simply sends you to transaction history page\n        connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), gui, SLOT(gotoHistoryPage()));\n\n        \/\/ Receive and report messages\n        connect(this, SIGNAL(message(QString, QString, unsigned int)), gui, SLOT(message(QString, QString, unsigned int)));\n\n        \/\/ Pass through encryption status changed signals\n        connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int)));\n\n        \/\/ Pass through transaction notifications\n        connect(this, SIGNAL(incomingTransaction(QString, int, CAmount, QString, QString)), gui, SLOT(incomingTransaction(QString, int, CAmount, QString, QString)));\n\n        \/\/ Connect HD enabled state signal\n        connect(this, SIGNAL(hdEnabledStatusChanged(int)), gui, SLOT(setHDStatus(int)));\n    }\n}\n\nvoid WalletView::setClientModel(ClientModel* clientModel)\n{\n    this->clientModel = clientModel;\n\n    overviewPage->setClientModel(clientModel);\n    sendCoinsPage->setClientModel(clientModel);\n    QSettings settings;\n    if (settings.value(\"fShowMasternodesTab\").toBool()) {\n        masternodeListPage->setClientModel(clientModel);\n    }\n}\n\nvoid WalletView::setWalletModel(WalletModel* walletModel)\n{\n    this->walletModel = walletModel;\n\n    \/\/ Put transaction list in tabs\n    transactionView->setModel(walletModel);\n    overviewPage->setWalletModel(walletModel);\n    QSettings settings;\n    if (settings.value(\"fShowMasternodesTab\").toBool()) {\n        masternodeListPage->setWalletModel(walletModel);\n    }\n    receiveCoinsPage->setModel(walletModel);\n    sendCoinsPage->setModel(walletModel);\n\n    if (walletModel) {\n        \/\/ Receive and pass through messages from wallet model\n        connect(walletModel, SIGNAL(message(QString, QString, unsigned int)), this, SIGNAL(message(QString, QString, unsigned int)));\n\n        \/\/ Handle changes in encryption status\n        connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int)));\n        updateEncryptionStatus();\n\n        \/\/ update HD status\n        Q_EMIT hdEnabledStatusChanged(walletModel->hdEnabled());\n\n        \/\/ Balloon pop-up for new transaction\n        connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex, int, int)),\n            this, SLOT(processNewTransaction(QModelIndex, int, int)));\n\n        \/\/ Ask for passphrase if needed\n        connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));\n\n        \/\/ Show progress dialog\n        connect(walletModel, SIGNAL(showProgress(QString, int)), this, SLOT(showProgress(QString, int)));\n    }\n}\n\nvoid WalletView::processNewTransaction(const QModelIndex& parent, int start, int \/*end*\/)\n{\n    \/\/ Prevent balloon-spam when initial block download is in progress\n    if (!walletModel || !clientModel || clientModel->inInitialBlockDownload())\n        return;\n\n    TransactionTableModel* ttm = walletModel->getTransactionTableModel();\n    if (!ttm || ttm->processingQueuedTransactions())\n        return;\n\n    QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString();\n    qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong();\n    QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString();\n    QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString();\n\n    emit incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address);\n}\n\nvoid WalletView::gotoOverviewPage()\n{\n    setCurrentWidget(overviewPage);\n    \/\/ Refresh UI-elements in case coins were locked\/unlocked in CoinControl\n    walletModel->emitBalanceChanged();\n}\n\nvoid WalletView::gotoHistoryPage()\n{\n    setCurrentWidget(transactionsPage);\n}\n\n\nvoid WalletView::gotoBlockExplorerPage()\n{\n    setCurrentWidget(explorerWindow);\n}\n\nvoid WalletView::gotoMasternodePage()\n{\n    QSettings settings;\n    if (settings.value(\"fShowMasternodesTab\").toBool()) {\n        setCurrentWidget(masternodeListPage);\n    }\n}\n\nvoid WalletView::gotoReceiveCoinsPage()\n{\n    setCurrentWidget(receiveCoinsPage);\n}\n\nvoid WalletView::gotoProposalPage()\n{\n    setCurrentWidget(proposalListPage);\n}\n\nvoid WalletView::gotoSendCoinsPage(QString addr)\n{\n    setCurrentWidget(sendCoinsPage);\n\n    if (!addr.isEmpty())\n        sendCoinsPage->setAddress(addr);\n}\n\nvoid WalletView::gotoSignMessageTab(QString addr)\n{\n    \/\/ calls show() in showTab_SM()\n    SignVerifyMessageDialog* signVerifyMessageDialog = new SignVerifyMessageDialog(this);\n    signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose);\n    signVerifyMessageDialog->setModel(walletModel);\n    signVerifyMessageDialog->showTab_SM(true);\n\n    if (!addr.isEmpty())\n        signVerifyMessageDialog->setAddress_SM(addr);\n}\n\nvoid WalletView::gotoVerifyMessageTab(QString addr)\n{\n    \/\/ calls show() in showTab_VM()\n    SignVerifyMessageDialog* signVerifyMessageDialog = new SignVerifyMessageDialog(this);\n    signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose);\n    signVerifyMessageDialog->setModel(walletModel);\n    signVerifyMessageDialog->showTab_VM(true);\n\n    if (!addr.isEmpty())\n        signVerifyMessageDialog->setAddress_VM(addr);\n}\n\nvoid WalletView::gotoBip38Tool()\n{\n    Bip38ToolDialog* bip38ToolDialog = new Bip38ToolDialog(this);\n    \/\/bip38ToolDialog->setAttribute(Qt::WA_DeleteOnClose);\n    bip38ToolDialog->setModel(walletModel);\n    bip38ToolDialog->showTab_ENC(true);\n}\n\nvoid WalletView::gotoMultiSendDialog()\n{\n    MultiSendDialog* multiSendDialog = new MultiSendDialog(this);\n    multiSendDialog->setModel(walletModel);\n    multiSendDialog->show();\n}\n\nvoid WalletView::gotoMultisigDialog(int index)\n{\n    MultisigDialog* multisig = new MultisigDialog(this);\n    multisig->setModel(walletModel);\n    multisig->showTab(index);\n}\n\nbool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient)\n{\n    return sendCoinsPage->handlePaymentRequest(recipient);\n}\n\nvoid WalletView::showOutOfSyncWarning(bool fShow)\n{\n    overviewPage->showOutOfSyncWarning(fShow);\n}\n\nvoid WalletView::updateEncryptionStatus()\n{\n    emit encryptionStatusChanged(walletModel->getEncryptionStatus());\n}\n\nvoid WalletView::encryptWallet(bool status)\n{\n    if (!walletModel)\n        return;\n    AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this, walletModel);\n    dlg.exec();\n\n    updateEncryptionStatus();\n}\n\nvoid WalletView::backupWallet()\n{\n    QString filename = GUIUtil::getSaveFileName(this,\n        tr(\"Backup Wallet\"), QString(),\n        tr(\"Wallet Data (*.dat)\"), NULL);\n\n    if (filename.isEmpty())\n        return;\n\n    if (!walletModel->backupWallet(filename)) {\n        emit message(tr(\"Backup Failed\"), tr(\"There was an error trying to save the wallet data to %1.\").arg(filename),\n            CClientUIInterface::MSG_ERROR);\n    } else {\n        emit message(tr(\"Backup Successful\"), tr(\"The wallet data was successfully saved to %1.\").arg(filename),\n            CClientUIInterface::MSG_INFORMATION);\n    }\n}\n\nvoid WalletView::changePassphrase()\n{\n    AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this, walletModel);\n    dlg.exec();\n}\n\nvoid WalletView::unlockWallet()\n{\n    if (!walletModel)\n        return;\n    \/\/ Unlock wallet when requested by wallet model\n\n    if (walletModel->getEncryptionStatus() == WalletModel::Locked || walletModel->getEncryptionStatus() == WalletModel::UnlockedForAnonymizationOnly) {\n        AskPassphraseDialog dlg(AskPassphraseDialog::UnlockAnonymize, this, walletModel);\n        dlg.exec();\n    }\n}\n\nvoid WalletView::lockWallet()\n{\n    if (!walletModel)\n        return;\n\n    walletModel->setWalletLocked(true);\n}\n\nvoid WalletView::toggleLockWallet()\n{\n    if (!walletModel)\n        return;\n\n    WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus();\n\n    \/\/ Unlock the wallet when requested\n    if (encStatus == walletModel->Locked) {\n        AskPassphraseDialog dlg(AskPassphraseDialog::UnlockAnonymize, this, walletModel);\n        dlg.exec();\n    }\n\n    else if (encStatus == walletModel->Unlocked || encStatus == walletModel->UnlockedForAnonymizationOnly) {\n            walletModel->setWalletLocked(true);\n    }\n}\n\nvoid WalletView::usedSendingAddresses()\n{\n    if (!walletModel)\n        return;\n    AddressBookPage* dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab, this);\n    dlg->setAttribute(Qt::WA_DeleteOnClose);\n    dlg->setModel(walletModel->getAddressTableModel());\n    dlg->show();\n}\n\nvoid WalletView::usedReceivingAddresses()\n{\n    if (!walletModel)\n        return;\n    AddressBookPage* dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this);\n    dlg->setAttribute(Qt::WA_DeleteOnClose);\n    dlg->setModel(walletModel->getAddressTableModel());\n    dlg->show();\n}\n\nvoid WalletView::showProgress(const QString& title, int nProgress)\n{\n    if (nProgress == 0) {\n        progressDialog = new QProgressDialog(title, \"\", 0, 100);\n        progressDialog->setWindowModality(Qt::ApplicationModal);\n        progressDialog->setMinimumDuration(0);\n        progressDialog->setCancelButton(0);\n        progressDialog->setAutoClose(false);\n        progressDialog->setValue(0);\n    } else if (nProgress == 100) {\n        if (progressDialog) {\n            progressDialog->close();\n            progressDialog->deleteLater();\n        }\n    } else if (progressDialog)\n        progressDialog->setValue(nProgress);\n}\n\n\/** Update wallet with the sum of the selected transactions *\/\nvoid WalletView::trxAmount(QString amount)\n{\n    transactionSum->setText(amount);\n}\n","avg_line_length":34.600422833,"max_line_length":165,"alphanum_fraction":0.7262617622,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7329,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"..\/client.h\"\n#include \"..\/messagesessionhandler.h\"\n#include \"..\/messageeventhandler.h\"\n#include \"..\/messageeventfilter.h\"\n#include \"..\/chatstatehandler.h\"\n#include \"..\/chatstatefilter.h\"\n#include \"..\/connectionlistener.h\"\n#include \"..\/disco.h\"\n#include \"..\/message.h\"\n#include \"..\/gloox.h\"\n#include \"..\/lastactivity.h\"\n#include \"..\/loghandler.h\"\n#include \"..\/logsink.h\"\n#include \"..\/connectiontcpclient.h\"\n#include \"..\/connectionsocks5proxy.h\"\n#include \"..\/connectionhttpproxy.h\"\n#include \"..\/messagehandler.h\"\n#include \"..\/pubsubmanager.h\"\n#include \"..\/pubsubresulthandler.h\"\nusing namespace gloox;\n\n#include <unistd.h>\n#include <stdio.h>\n#include <string>\n\n#if defined( WIN32 ) || defined( _WIN32 )\n# include <windows.h>\n#endif\n\/*\nclass PubsubExample : public MessageSessionHandler, ConnectionListener, LogHandler,\n                    MessageEventHandler, MessageHandler, ChatStateHandler, PubSub::ResultHandler\n{\n  public:\n    PubsubExample() : m_session( 0 ), m_messageEventFilter( 0 ), m_chatStateFilter( 0 ) {}\n\n    virtual ~PubsubExample() {}\n\n    void start()\n    {\n\n      JID jid( \"hurkhurk@example.net\/gloox\" );\n      j = new Client( jid, \"hurkhurks\" );\n      j->registerConnectionListener( this );\n      j->registerMessageSessionHandler( this, 0 );\n      j->disco()->setVersion( \"PubsubExample\", GLOOX_VERSION, \"Linux\" );\n      j->disco()->setIdentity( \"client\", \"bot\" );\n      j->disco()->addFeature( XMLNS_CHAT_STATES );\n      StringList ca;\n      ca.push_back( \"\/path\/to\/cacert.crt\" );\n      j->setCACerts( ca );\n\n      pubsub = new PubSub::Manager( j );\n\n      j->logInstance().registerLogHandler( LogLevelDebug, LogAreaAll, this );\n\n\/\/\n\/\/ this code connects to a jabber server through a SOCKS5 proxy\n\/\/\n\/\/       ConnectionSOCKS5Proxy* conn = new ConnectionSOCKS5Proxy( j,\n\/\/                                   new ConnectionTCP( j->logInstance(),\n\/\/                                                      \"sockshost\", 1080 ),\n\/\/                                   j->logInstance(), \"example.net\" );\n\/\/       conn->setProxyAuth( \"socksuser\", \"sockspwd\" );\n\/\/       j->setConnectionImpl( conn );\n\n\/\/\n\/\/ this code connects to a jabber server through a HTTP proxy through a SOCKS5 proxy\n\/\/\n\/\/       ConnectionTCP* conn0 = new ConnectionTCP( j->logInstance(), \"old\", 1080 );\n\/\/       ConnectionSOCKS5Proxy* conn1 = new ConnectionSOCKS5Proxy( conn0, j->logInstance(), \"old\", 8080 );\n\/\/       conn1->setProxyAuth( \"socksuser\", \"sockspwd\" );\n\/\/       ConnectionHTTPProxy* conn2 = new ConnectionHTTPProxy( j, conn1, j->logInstance(), \"jabber.cc\" );\n\/\/       conn2->setProxyAuth( \"httpuser\", \"httppwd\" );\n\/\/       j->setConnectionImpl( conn2 );\n\n\n      j->connect( true );\n\n      delete( j );\n    }\n\n    virtual void onConnect()\n    {\n      printf( \"connected!!!\\n\" );\n    }\n\n    virtual void onDisconnect( ConnectionError e )\n    {\n      printf( \"PubsubExample: disconnected: %d\\n\", e );\n      if( e == ConnAuthenticationFailed )\n        printf( \"auth failed. reason: %d\\n\", j->authError() );\n    }\n\n    virtual bool onTLSConnect( const CertInfo& info )\n    {\n      time_t from( info.date_from );\n      time_t to( info.date_to );\n\n      printf( \"status: %d\\nissuer: %s\\npeer: %s\\nprotocol: %s\\nmac: %s\\ncipher: %s\\ncompression: %s\\n\"\n              \"from: %s\\nto: %s\\n\",\n              info.status, info.issuer.c_str(), info.server.c_str(),\n              info.protocol.c_str(), info.mac.c_str(), info.cipher.c_str(),\n              info.compression.c_str(), ctime( &from ), ctime( &to ) );\n      return true;\n    }\n\n    virtual void handleMessage( Message* msg, MessageSession * session )\n    {\n      if( msg->body() == \"quit\" )\n        j->disconnect();\n      else if( msg->body() == \"create\" )\n        pubsub->createCollectionNode( JID( \"pubsub.jabber.ru\" ), \"blah\", this, \"blubb\", \"pubsub\/nodes\" );\n    }\n\n    virtual void handleMessageEvent( const JID& from, MessageEventType event )\n    {\n      printf( \"received event: %d from: %s\\n\", event, from.full().c_str() );\n    }\n\n    virtual void handleChatState( const JID& from, ChatStateType state )\n    {\n      printf( \"received state: %d from: %s\\n\", state, from.full().c_str() );\n    }\n\n    virtual void handleMessageSession( MessageSession *session )\n    {\n      printf( \"got new session\\n\");\n      \/\/ this example can handle only one session. so we get rid of the old session\n      j->disposeMessageSession( m_session );\n      m_session = session;\n      m_session->registerMessageHandler( this );\n      m_messageEventFilter = new MessageEventFilter( m_session );\n      m_messageEventFilter->registerMessageEventHandler( this );\n      m_chatStateFilter = new ChatStateFilter( m_session );\n      m_chatStateFilter->registerChatStateHandler( this );\n    }\n\n    virtual void handleLog( LogLevel level, LogArea area, const std::string& message )\n    {\n      printf(\"log: level: %d, area: %d, %s\\n\", level, area, message.c_str() );\n    }\n\n    virtual void handleNodeCreationResult( const JID& service,\n                                            const std::string& node,\n                                            const Error& e )\n    {\n      printf( \"created node '%s' on '%s'\\n\", node.c_str(), service.bare().c_str() );\n    }\n\n    virtual void handleNodeDeletationResult( const JID& service,\n                                              const std::string& node,\n                                              const Error& e ) {}\n\n    virtual void handleNodePurgeResult( const JID& service,\n                                        const std::string& node,\n                                        const Error& e ) {}\n\n    virtual void handleSubscriptionOptions( const JID& service, const JID& jid,\n                                            const std::string& node,\n                                            const DataForm& options ) {}\n\n    virtual void handleSubscriptionOptionsResult( const JID& service,\n                                                  \/\/const JID& jid,\n                                                  const std::string& node,\n                                                  const Error& e ) {}\n\n    virtual void handleSubscriberList( const JID& service, const std::string& node,\n                                        const PubSub::SubscriberList& list ) {}\n\n    virtual void handleSubscriberListResult( const JID& service, const std::string& node,\n                                              const Error& e ) {}\n\n    virtual void handleAffiliateList( const JID& service, const std::string& node,\n                                      const PubSub::AffiliateList& list ) {}\n\n    virtual void handleAffiliateListResult( const JID& service, const std::string& node,\n                                            const Error& e ) {}\n\n    virtual void handleNodeConfig( const JID& service, const std::string& node,\n                                    const DataForm& config ) {}\n\n    virtual void handleNodeConfigResult( const JID& service, const std::string& node,\n                                          const Error& e ) {}\n\n  private:\n    Client *j;\n    MessageSession *m_session;\n    MessageEventFilter *m_messageEventFilter;\n    ChatStateFilter *m_chatStateFilter;\n    PubSub::Manager *pubsub;\n};\n*\/\nint main( int \/*argc*\/, char** \/*argv*\/ )\n{\n  \/\/PubsubExample *r = new PubsubExample();\n  \/\/r->start();\n  \/\/delete( r );\n  return 0;\n}\n","avg_line_length":36.645,"max_line_length":106,"alphanum_fraction":0.5762041206,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2278,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"#include \"ros\/ros.h\"\n#include <iostream>\n#include \"geometry_msgs\/PoseStamped.h\"\n\n#include <tf2\/LinearMath\/Quaternion.h>\n#include <tf2_ros\/transform_broadcaster.h>\n#include <geometry_msgs\/TransformStamped.h>\n#include <tf2_ros\/static_transform_broadcaster.h>\n\/\/ started with this https:\/\/github.com\/dominikbelter\/opencv_example\n\nvoid imuCallback(const geometry_msgs::PoseStampedConstPtr& imu_msg)\n{\ngeometry_msgs::PoseStamped current_imu = *imu_msg;\n\n  static tf2_ros::TransformBroadcaster br;\n \n  geometry_msgs::TransformStamped transformStamped;\n  \n  transformStamped.header.stamp = ros::Time::now();\n  transformStamped.header.frame_id = \"world\";\n  transformStamped.child_frame_id = \"body_mavros\";\n  transformStamped.transform.translation.x = current_imu.pose.position.x;\n  transformStamped.transform.translation.y = current_imu.pose.position.y;\n  transformStamped.transform.translation.z = current_imu.pose.position.z;\n  \/\/tf2::Quaternion q;\n  \/\/q.setRPY(0, 0, msg->theta);\n  transformStamped.transform.rotation.x = current_imu.pose.orientation.x;\n  transformStamped.transform.rotation.y = current_imu.pose.orientation.y;\n  transformStamped.transform.rotation.z = current_imu.pose.orientation.z;\n  transformStamped.transform.rotation.w = current_imu.pose.orientation.w;\n\n \/\/static tf2_ros::TransformBroadcaster br_world_flu;\n  br.sendTransform(transformStamped);\n  \/\/transformStamped.header.stamp = ros::Time::now();\n  \/\/transformStamped.header.frame_id = \"world\";\n  \/\/transformStamped.child_frame_id = \"world_FLU\";\n  \/\/transformStamped.transform.translation.x = 0.0;\n  \/\/transformStamped.transform.translation.y = 0.0;\n  \/\/transformStamped.transform.translation.z = 0.0;\n  \/\/tf2::Quaternion q;\n  \/\/q.setRPY(0, 0, 1.57);\n  \/\/q.normalize();\n  \/\/transformStamped.transform.rotation.x = q[0];\n  \/\/transformStamped.transform.rotation.y = q[1];\n  \/\/transformStamped.transform.rotation.z = q[2];\n  \/\/transformStamped.transform.rotation.w = q[3];\n\n  \/\/br_world_flu.sendTransform(transformStamped);\n}\n\nint main(int argc, char **argv)\n{\n  \/\/initialize node\n  ros::init(argc, argv, \"mavros_body_pos\");\n\n  \/\/ node handler\n  ros::NodeHandle n;\n  \n  \/\/ subsribe topic\n  ros::Subscriber imu_sub = n.subscribe(\"\/mavros\/local_position\/pose\", 1000, imuCallback);\n\n  ros::spin();\n\n  return 0;\n}\n","avg_line_length":34.5151515152,"max_line_length":90,"alphanum_fraction":0.7585601405,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1045,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0","OpenSSL"],"max_stars_count":3.0,"content":"#include \"yaml-cpp\/exceptions.h\"\n\n\/\/ This is here for compatibility with older versions of Visual Studio\n\/\/ which don't support noexcept\n#ifdef _MSC_VER\n    #define YAML_CPP_NOEXCEPT \n#else\n    #define YAML_CPP_NOEXCEPT noexcept\n#endif\n\nnamespace YAML {\n\n\/\/ These destructors are defined out-of-line so the vtable is only emitted once.\nException::~Exception() YAML_CPP_NOEXCEPT {}\nParserException::~ParserException() YAML_CPP_NOEXCEPT {}\nRepresentationException::~RepresentationException() YAML_CPP_NOEXCEPT {}\nInvalidScalar::~InvalidScalar() YAML_CPP_NOEXCEPT {}\nKeyNotFound::~KeyNotFound() YAML_CPP_NOEXCEPT {}\nInvalidNode::~InvalidNode() YAML_CPP_NOEXCEPT {}\nBadConversion::~BadConversion() YAML_CPP_NOEXCEPT {}\nBadDereference::~BadDereference() YAML_CPP_NOEXCEPT {}\nBadSubscript::~BadSubscript() YAML_CPP_NOEXCEPT {}\nBadPushback::~BadPushback() YAML_CPP_NOEXCEPT {}\nBadInsert::~BadInsert() YAML_CPP_NOEXCEPT {}\nEmitterException::~EmitterException() YAML_CPP_NOEXCEPT {}\nBadFile::~BadFile() YAML_CPP_NOEXCEPT {}\n}\n\n#undef YAML_CPP_NOEXCEPT\n\n\n","avg_line_length":32.65625,"max_line_length":80,"alphanum_fraction":0.7933014354,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5245,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":561.0,"content":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2016, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/      * Redistributions of source code must retain the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer.\n\/\/\n\/\/      * Redistributions in binary form must reproduce the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer in the documentation and\/or other materials provided with\n\/\/        the distribution.\n\/\/\n\/\/      * Neither the name of John Haddon nor the names of\n\/\/        any other contributors to this software may be used to endorse or\n\/\/        promote products derived from this software without specific prior\n\/\/        written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferTest\/DownstreamIteratorTest.h\"\n\n#include \"GafferTest\/Assert.h\"\n\n#include \"Gaffer\/DownstreamIterator.h\"\n#include \"Gaffer\/Random.h\"\n\nusing namespace Gaffer;\n\nvoid GafferTest::testDownstreamIterator()\n{\n\n\t\/\/   a\n\t\/\/   |\n\t\/\/   b\n\t\/\/  \/ \\.\n\t\/\/ c   d\n\t\/\/      \\.\n\t\/\/\t\t e\n\n\tRandom::Ptr a = new Random( \"a\" );\n\tRandom::Ptr b = new Random( \"b\" );\n\tRandom::Ptr c = new Random( \"c\" );\n\tRandom::Ptr d = new Random( \"d\" );\n\tRandom::Ptr e = new Random( \"e\" );\n\n\tb->floatRangePlug()->getChild( 0 )->setInput( a->outFloatPlug() );\n\tc->floatRangePlug()->getChild( 0 )->setInput( b->outFloatPlug() );\n\td->floatRangePlug()->getChild( 0 )->setInput( b->outFloatPlug() );\n\te->floatRangePlug()->getChild( 0 )->setInput( d->outFloatPlug() );\n\n\tDownstreamIterator it1( a->floatRangePlug()->getChild( 0 ) );\n\tDownstreamIterator it2( a->floatRangePlug()->getChild( 0 ) );\n\n\tGAFFERTEST_ASSERT( &*it1 == a->outFloatPlug() );\n\tGAFFERTEST_ASSERT( &*it2 == a->outFloatPlug() );\n\tGAFFERTEST_ASSERT( it1.upstream() == a->floatRangePlug()->getChild( 0 ) );\n\tGAFFERTEST_ASSERT( it2.upstream() == a->floatRangePlug()->getChild( 0 ) );\n\tGAFFERTEST_ASSERT( it1 == it2 );\n\tGAFFERTEST_ASSERT( !it1.done() );\n\tGAFFERTEST_ASSERT( !it2.done() );\n\n\tit1++;\n\n\tGAFFERTEST_ASSERT( &*it1 == b->floatRangePlug()->getChild( 0 ) );\n\tGAFFERTEST_ASSERT( &*it2 == a->outFloatPlug() );\n\tGAFFERTEST_ASSERT( it1.upstream() == a->outFloatPlug() );\n\tGAFFERTEST_ASSERT( it2.upstream() == a->floatRangePlug()->getChild( 0 ) );\n\tGAFFERTEST_ASSERT( it1 != it2 );\n\tGAFFERTEST_ASSERT( !it1.done() );\n\tGAFFERTEST_ASSERT( !it2.done() );\n\n\tit2 = it1;\n\n\tGAFFERTEST_ASSERT( &*it1 == b->floatRangePlug()->getChild( 0 ) );\n\tGAFFERTEST_ASSERT( &*it2 == b->floatRangePlug()->getChild( 0 ) );\n\tGAFFERTEST_ASSERT( it1.upstream() == a->outFloatPlug() );\n\tGAFFERTEST_ASSERT( it2.upstream() == a->outFloatPlug() );\n\tGAFFERTEST_ASSERT( it1 == it2 );\n\tGAFFERTEST_ASSERT( !it1.done() );\n\tGAFFERTEST_ASSERT( !it2.done() );\n\n\tstd::vector<const Plug *> visited;\n\tfor( DownstreamIterator it( a->floatRangePlug()->getChild( 0 ) ); !it.done(); ++it )\n\t{\n\t\tvisited.push_back( &*it );\n\t}\n\n\tGAFFERTEST_ASSERT( visited.size() == 9 );\n\tGAFFERTEST_ASSERT( visited[0] == a->outFloatPlug() );\n\tGAFFERTEST_ASSERT( visited[1] == b->floatRangePlug()->getChild( 0 ) );\n\tGAFFERTEST_ASSERT( visited[2] == b->outFloatPlug() );\n\tGAFFERTEST_ASSERT( visited[3] == c->floatRangePlug()->getChild( 0 ) );\n\tGAFFERTEST_ASSERT( visited[4] == c->outFloatPlug() );\n\tGAFFERTEST_ASSERT( visited[5] == d->floatRangePlug()->getChild( 0 ) );\n\tGAFFERTEST_ASSERT( visited[6] == d->outFloatPlug() );\n\tGAFFERTEST_ASSERT( visited[7] == e->floatRangePlug()->getChild( 0 ) );\n\tGAFFERTEST_ASSERT( visited[8] == e->outFloatPlug() );\n\n\t\/\/ test pruning\n\n\tvisited.clear();\n\tfor( DownstreamIterator it( a->floatRangePlug()->getChild( 0 ) ); !it.done(); ++it )\n\t{\n\t\tvisited.push_back( &*it );\n\t\tif( &*it == d->floatRangePlug()->getChild( 0 ) || &*it == c->outFloatPlug() )\n\t\t{\n\t\t\tit.prune();\n\t\t}\n\t}\n\n\tGAFFERTEST_ASSERT( visited.size() == 6 );\n\tGAFFERTEST_ASSERT( visited[0] == a->outFloatPlug() );\n\tGAFFERTEST_ASSERT( visited[1] == b->floatRangePlug()->getChild( 0 ) );\n\tGAFFERTEST_ASSERT( visited[2] == b->outFloatPlug() );\n\tGAFFERTEST_ASSERT( visited[3] == c->floatRangePlug()->getChild( 0 ) );\n\tGAFFERTEST_ASSERT( visited[4] == c->outFloatPlug() );\n\tGAFFERTEST_ASSERT( visited[5] == d->floatRangePlug()->getChild( 0 ) );\n\n}\n","avg_line_length":38.2846715328,"max_line_length":85,"alphanum_fraction":0.6589132507,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4005,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/* file: bacon_batch.cpp *\/\n\/*******************************************************************************\n* Copyright 2014-2020 Intel Corporation\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*******************************************************************************\/\n\n#include <jni.h>\/* Header for class com_intel_daal_algorithms_bacon_outlier_detection_Batch *\/\n\n#include \"daal.h\"\n#include \"com_intel_daal_algorithms_bacon_outlier_detection_Batch.h\"\n\n#include \"common_helpers.h\"\n\nUSING_COMMON_NAMESPACES()\nusing namespace daal::algorithms::bacon_outlier_detection;\n\n\/*\n * Class:     com_intel_daal_algorithms_bacon_outlier_detection_Batch\n * Method:    cInit\n * Signature:(II)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_bacon_1outlier_1detection_Batch_cInit(JNIEnv * env, jobject thisObj, jint prec, jint method)\n{\n    return jniBatch<bacon_outlier_detection::Method, Batch, defaultDense>::newObj(prec, method);\n}\n\n\/*\n * Class:     com_intel_daal_algorithms_bacon_outlier_detection_Batch\n * Method:    cInitParameter\n * Signature:(JII)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_bacon_1outlier_1detection_Batch_cInitParameter(JNIEnv * env, jobject thisObj, jlong algAddr,\n                                                                                                      jint prec, jint method)\n{\n    return jniBatch<bacon_outlier_detection::Method, Batch, defaultDense>::getParameter(prec, method, algAddr);\n}\n\n\/*\n * Class:     com_intel_daal_algorithms_bacon_outlier_detection_Batch\n * Method:    cGetInput\n * Signature:(JII)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_bacon_1outlier_1detection_Batch_cGetInput(JNIEnv * env, jobject thisObj, jlong algAddr,\n                                                                                                 jint prec, jint method)\n{\n    return jniBatch<bacon_outlier_detection::Method, Batch, defaultDense>::getInput(prec, method, algAddr);\n}\n\n\/*\n * Class:     com_intel_daal_algorithms_bacon_outlier_detection_Batch\n * Method:    cGetResult\n * Signature:(JII)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_bacon_1outlier_1detection_Batch_cGetResult(JNIEnv * env, jobject thisObj, jlong algAddr,\n                                                                                                  jint prec, jint method)\n{\n    return jniBatch<bacon_outlier_detection::Method, Batch, defaultDense>::getResult(prec, method, algAddr);\n}\n\n\/*\n * Class:     com_intel_daal_algorithms_bacon_outlier_detection_Batch\n * Method:    cSetResult\n * Signature: (JIIJ)V\n *\/\nJNIEXPORT void JNICALL Java_com_intel_daal_algorithms_bacon_1outlier_1detection_Batch_cSetResult(JNIEnv * env, jobject thisObj, jlong algAddr,\n                                                                                                 jint prec, jint method, jlong resultAddr)\n{\n    jniBatch<bacon_outlier_detection::Method, Batch, defaultDense>::setResult<bacon_outlier_detection::Result>(prec, method, algAddr, resultAddr);\n}\n\n\/*\n * Class:     com_intel_daal_algorithms_bacon_outlier_detection_Batch\n * Method:    cClone\n * Signature:(JII)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_bacon_1outlier_1detection_Batch_cClone(JNIEnv * env, jobject thisObj, jlong algAddr, jint prec,\n                                                                                              jint method)\n{\n    return jniBatch<bacon_outlier_detection::Method, Batch, defaultDense>::getClone(prec, method, algAddr);\n}\n","avg_line_length":43.5326086957,"max_line_length":150,"alphanum_fraction":0.6651685393,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":356,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"#include <iostream>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nvector<int> vp;\r\n\r\nint main(void) {\r\n    for(int i = 1; i <= 500; i++) vp.push_back((int)(i*(i + 1))\/2);\r\n    cin >> n;\r\n    if(binary_search(vp.begin(), vp.end(),n)) {\r\n        cout << \"YES\\n\";\r\n    } else {\r\n        cout << \"NO\\n\";\r\n    }\r\n    return 0;\r\n}\r\n","avg_line_length":17.8,"max_line_length":68,"alphanum_fraction":0.4943820225,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":365,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"basebuilder.h\"\n\nTxtModelBuilder::TxtModelBuilder(shared_ptr<BuilderImp> _imp) : BaseModelBuilder(_imp)\n{\n\n}\n\nvoid TxtModelBuilder::loadNodes(std::ifstream &f)\n{\n    imp->loadNodes(f);\n}\n\nvoid TxtModelBuilder::loadEdges(std::ifstream &f)\n{\n    imp->loadEdges(f);\n}\n\nshared_ptr<BaseObject> TxtModelBuilder::getProduct()\n{\n    return imp->returnProduct();\n}\n","avg_line_length":16.5909090909,"max_line_length":86,"alphanum_fraction":0.7287671233,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1177,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\ufeff\/*! ***********************************************************************************************\n *\n * \\file        main.cpp\n * \\brief       The main file of CPU consumer.\n *\n * \\version     0.1\n * \\date        2015\/07\/02\n *\n * \\author      Roy QIU (karoyqiu@gmail.com)\n * \\copyright   \u00a9 Roy QIU. MIT license.\n *\n **************************************************************************************************\/\n#include <iostream>\n\n#if defined(HAVE_BOOST)\n#include <boost\/thread.hpp>\n#elif defined(HAVE_OPENMP)\n#include <omp.h>\n#else\n#error \"You must have Boost 1.56+ or OpenMP.\"\n#endif\n\n\nstatic void prompt_eating(int index)\n{\n    std::cout << \"[\" << index << \"]: Eating CPU...\" << std::endl;\n}\n\n\nstatic void eat_cpu()\n{\n    for (int i = 0; ; i++);\n}\n\n\nint main(int argc, char *argv[])\n{\n#if defined(HAVE_BOOST)\n\n    boost::thread_group tg;\n\n    for (unsigned i = 0; i < boost::thread::hardware_concurrency(); i++)\n    {\n        prompt_eating(i);\n        tg.create_thread(eat_cpu);\n    }\n\n    tg.join_all();\n\n#elif defined(HAVE_OPENMP)\n\n#pragma omp parallel\n{\n    #pragma omp critical\n    prompt_eating(omp_get_thread_num());\n\n    eat_cpu();\n}\n\n#endif\n\n    return 0;\n}\n","avg_line_length":18.390625,"max_line_length":100,"alphanum_fraction":0.4978759558,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4143,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2338.0,"content":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <random>\n\n\/\/ template<class Engine, size_t k>\n\/\/ class shuffle_order_engine\n\n\/\/ template<class Sseq> explicit shuffle_order_engine(Sseq& q);\n\n\/\/ Serializing\/deserializing the state of the RNG requires iostreams\n\/\/ UNSUPPORTED: libcpp-has-no-localization\n\n#include <random>\n#include <sstream>\n#include <cassert>\n\n#include \"test_macros.h\"\n\nvoid\ntest1()\n{\n    const char* a = \"1894661934 884942216 1899568837 1561547157 525417712 \"\n        \"242729120 1476874187 1208468883 1983666902 1953485886 1507290666 \"\n        \"1317123450 632390874 696850315 1734917114 218976032 1690682513 \"\n        \"1944862534 456017951 2072049961 1348874775 1700965693 828093387 \"\n        \"2071522749 1077957279 1055942061 413360419 238964088 475007126 \"\n        \"1248050783 1516729632 1044035134 9617501 580065782 1737324341 \"\n        \"2022534575 219953662 941840747 415472792 1381878747 200458524 \"\n        \"1852054372 1849850586 1318041283 1026024576 101363422 660501483 \"\n        \"705453438 298717379 1873705814 673416290 868766340 614560427 \"\n        \"1668238166 532360730 969915708 1972423626 1966307090 97417947 \"\n        \"920896215 588041576 495024338 522400288 1068491480 878048146 \"\n        \"1995051285 17282737 560668414 2143274709 127339385 1299331283 \"\n        \"99667038 66663006 1566161755 773555006 272986904 1065825536 \"\n        \"1168683925 1185292013 1144552919 1489883454 811887358 279732868 \"\n        \"628609193 1562647158 1833265343 1742736292 639398211 357562689 \"\n        \"896869717 501615326 1775469607 1032409784 43371928 955037563 \"\n        \"1023543663 1354331571 1071539244 562210166 138213162 1518791327 \"\n        \"1335204647 1727874626 2114964448 1058152392 1055171537 348065433 \"\n        \"190278003 399246038 1389247438 1639480282 382424917 2144508195 \"\n        \"1531185764 1342593547 1359065400 1176108308 1412845568 968776497 \"\n        \"5573525 1332437854 323541262 329396230 2097079291 1110029273 \"\n        \"1071549822 739994612 1011644107 1074473050 478563727 894301674 \"\n        \"290189565 280656618 1121689914 1630931232 579945916 1870220126 \"\n        \"71516543 1535179528 1893792038 1107650479 1893348357 93154853 \"\n        \"138035708 683805596 1535656875 1326628479 1469623399 1751042846 \"\n        \"661214234 1947241260 1780560187 690441964 1403944207 1687457460 \"\n        \"1428487938 1877084153 1618585041 1383427538 461185097 869443256 \"\n        \"1254069404 1739961370 1245924391 138197640 1257913073 1915996843 \"\n        \"641653536 1755587965 1889101622 1732723706 2009073422 1611621773 \"\n        \"315899200 738279016 94909546 1711873548 1620302377 181922632 \"\n        \"1704446343 1345319468 2076463060 357902023 157605314 1025175647 \"\n        \"865799248 138769064 124418006 1591838311 675218651 1096276609 \"\n        \"1858759850 732186041 769493777 735387805 894450150 638142050 \"\n        \"720101232 1671055379 636619387 898507955 118193981 63865192 \"\n        \"1787942091 204050966 2100684950 1580797970 1951284753 1020070334 \"\n        \"960149537 1041144801 823914651 558983501 1742229329 708805658 \"\n        \"804904097 1023665826 1260041465 1180659188 590074436 301564006 \"\n        \"324841922 714752380 1967212989 290476911 815113546 815183409 \"\n        \"1989370850 1182975807 870784323 171062356 1711897606 2024645183 \"\n        \"1333203966 314683764 1785282634 603713754 1904315050 1874254109 \"\n        \"1298675767 1967311508 1946285744 753588304 1847558969 1457540010 \"\n        \"528986741 97857407 1864449494 1868752281 1171249392 1353422942 \"\n        \"832597170 457192338 335135800 1925268166 1845956613 296546482 \"\n        \"1894661934\";\n    unsigned as[] = {3, 5, 7};\n    std::seed_seq sseq(as, as+3);\n    std::knuth_b e1(sseq);\n    std::ostringstream os;\n    os << e1;\n    assert(os.str() == a);\n}\n\nint main(int, char**)\n{\n    test1();\n\n  return 0;\n}\n","avg_line_length":48.1744186047,"max_line_length":80,"alphanum_fraction":0.7212165098,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":99182,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-4.0"],"max_stars_count":3.0,"content":"\/\/========= Copyright Valve Corporation, All rights reserved. ============\/\/\n\/\/\n\/\/ Purpose: \n\/\/\n\/\/=============================================================================\/\/\n\n#include \"cbase.h\"\n\n#include \"ai_behavior_actbusy.h\"\n\n#include \"ai_navigator.h\"\n#include \"ai_hint.h\"\n#include \"ai_behavior_follow.h\"\n#include \"KeyValues.h\"\n#include \"filesystem.h\"\n#include \"eventqueue.h\"\n#include \"ai_playerally.h\"\n#include \"SoundEmitterSystem\/isoundemittersystembase.h\"\n#include \"entityblocker.h\"\n#include \"npcevent.h\"\n\n\/\/ memdbgon must be the last include file in a .cpp file!!!\n#include \"tier0\/memdbgon.h\"\n\n#define ACTBUSY_SEE_ENTITY_TIMEOUT\t1.0f\n\n#define ACTBUSY_COMBAT_PLAYER_MAX_DIST\t720.0f\t\/\/ NPCs in combat actbusy should try to stay within this distance of the player.\n\nConVar\tai_actbusy_search_time( \"ai_actbusy_search_time\",\"10.0\" );\nConVar  ai_debug_actbusy( \"ai_debug_actbusy\", \"0\", FCVAR_CHEAT, \"Used to debug actbusy behavior. Usage:\\n\\\n1: Constantly draw lines from NPCs to the actbusy nodes they've chosen to actbusy at.\\n\\\n2: Whenever an NPC makes a decision to use an actbusy, show which actbusy they've chosen.\\n\\\n3: Selected NPCs (with npc_select) will report why they're not choosing actbusy nodes.\\n\\\n4: Display debug output of actbusy logic.\\n\\\n5: Display safe zone volumes and info.\\n\\\n\");\n\n\/\/ Anim events\nstatic int AE_ACTBUSY_WEAPON_FIRE_ON;\nstatic int AE_ACTBUSY_WEAPON_FIRE_OFF;\n\nBEGIN_DATADESC( CAI_ActBusyBehavior )\n\tDEFINE_FIELD( m_bEnabled, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_bForceActBusy, FIELD_BOOLEAN ),\n\tDEFINE_CUSTOM_FIELD( m_ForcedActivity, ActivityDataOps() ),\n\tDEFINE_FIELD( m_bTeleportToBusy, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_bUseNearestBusy, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_bLeaving, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_bVisibleOnly, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_bUseRenderBoundsForCollision, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_flForcedMaxTime, FIELD_FLOAT ),\n\tDEFINE_FIELD( m_bBusy, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_bMovingToBusy, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_bNeedsToPlayExitAnim, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_flNextBusySearchTime, FIELD_TIME ),\n\tDEFINE_FIELD( m_flEndBusyAt, FIELD_TIME ),\n\tDEFINE_FIELD( m_flBusySearchRange, FIELD_FLOAT ),\n\tDEFINE_FIELD( m_bInQueue, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_iCurrentBusyAnim, FIELD_INTEGER ),\n\tDEFINE_FIELD( m_hActBusyGoal, FIELD_EHANDLE ),\n\tDEFINE_FIELD( m_bNeedToSetBounds, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_hSeeEntity, FIELD_EHANDLE ),\n\tDEFINE_FIELD( m_fTimeLastSawSeeEntity, FIELD_TIME ),\n\tDEFINE_FIELD( m_bExitedBusyToDueLostSeeEntity, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_bExitedBusyToDueSeeEnemy, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_iNumConsecutivePathFailures, FIELD_INTEGER ),\n\tDEFINE_FIELD( m_bAutoFireWeapon, FIELD_BOOLEAN ),\n\tDEFINE_FIELD( m_flDeferUntil, FIELD_TIME ),\n\tDEFINE_FIELD( m_iNumEnemiesInSafeZone, FIELD_INTEGER ),\nEND_DATADESC();\n\nenum\n{\n\tACTBUSY_SIGHT_METHOD_FULL\t= 0,\t\/\/ LOS and Viewcone\n\tACTBUSY_SIGHT_METHOD_LOS_ONLY,\n};\n\n\/\/=============================================================================\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Gamesystem that parses the act busy anim file\n\/\/-----------------------------------------------------------------------------\nclass CActBusyAnimData : public CAutoGameSystem\n{\npublic:\n\tCActBusyAnimData( void ) : CAutoGameSystem( \"CActBusyAnimData\" )\n\t{\n\t}\n\n\t\/\/ Inherited from IAutoServerSystem\n\tvirtual void LevelInitPostEntity( void );\n\tvirtual void LevelShutdownPostEntity( void );\n\n\t\/\/ Read in the data from the anim data file\n\tvoid ParseAnimDataFile( void );\n\n\t\/\/ Parse a keyvalues section into an act busy anim\n\tbool ParseActBusyFromKV( busyanim_t *pAnim, KeyValues *pSection );\n\n\t\/\/ Purpose: Returns the index of the busyanim data for the specified activity or sequence\n\tint FindBusyAnim( Activity iActivity, const char *pSequence );\n\n\tbusyanim_t *GetBusyAnim( int iIndex ) { return &m_ActBusyAnims[iIndex]; }\n\nprotected:\n\tCUtlVector<busyanim_t>\tm_ActBusyAnims;\n};\n\nCActBusyAnimData g_ActBusyAnimDataSystem;\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Inherited from IAutoServerSystem\n\/\/-----------------------------------------------------------------------------\nvoid CActBusyAnimData::LevelInitPostEntity( void )\n{\n\tParseAnimDataFile();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CActBusyAnimData::LevelShutdownPostEntity( void )\n{\n\tm_ActBusyAnims.Purge();\n\t\/\/pKVAnimData->deleteThis();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Clear out the stats + their history\n\/\/-----------------------------------------------------------------------------\nvoid CActBusyAnimData::ParseAnimDataFile( void )\n{\n\tKeyValues *pKVAnimData = new KeyValues( \"ActBusyAnimDatafile\" );\n\tif ( pKVAnimData->LoadFromFile( filesystem, \"scripts\/actbusy.txt\" ) )\n\t{\n\t\t\/\/ Now try and parse out each act busy anim\n\t\tKeyValues *pKVAnim = pKVAnimData->GetFirstSubKey();\n\t\twhile ( pKVAnim )\n\t\t{\n\t\t\t\/\/ Create a new anim and add it to our list\n\t\t\tint index = m_ActBusyAnims.AddToTail();\n\t\t\tbusyanim_t *pAnim = &m_ActBusyAnims[index];\n\t\t\tif ( !ParseActBusyFromKV( pAnim, pKVAnim ) )\n\t\t\t{\n\t\t\t\tm_ActBusyAnims.Remove( index );\n\t\t\t}\n\n\t\t\tpKVAnim = pKVAnim->GetNextKey();\n\t\t}\n\t}\n\tpKVAnimData->deleteThis();\n}\t\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Parse a keyvalues section into the prop\n\/\/-----------------------------------------------------------------------------\nbool CActBusyAnimData::ParseActBusyFromKV( busyanim_t *pAnim, KeyValues *pSection )\n{\n\tpAnim->iszName = AllocPooledString( pSection->GetName() );\n\n\t\/\/ Activities\n\tpAnim->iActivities[BA_BUSY] = (Activity)CAI_BaseNPC::GetActivityID( pSection->GetString( \"busy_anim\", \"ACT_INVALID\" ) );\n\tpAnim->iActivities[BA_ENTRY] = (Activity)CAI_BaseNPC::GetActivityID( pSection->GetString( \"entry_anim\", \"ACT_INVALID\" ) );\n\tpAnim->iActivities[BA_EXIT] = (Activity)CAI_BaseNPC::GetActivityID( pSection->GetString( \"exit_anim\", \"ACT_INVALID\" ) );\n\n\t\/\/ Sequences\n\tpAnim->iszSequences[BA_BUSY] = AllocPooledString( pSection->GetString( \"busy_sequence\", NULL ) );\n\tpAnim->iszSequences[BA_ENTRY] = AllocPooledString( pSection->GetString( \"entry_sequence\", NULL ) );\n\tpAnim->iszSequences[BA_EXIT] = AllocPooledString( pSection->GetString( \"exit_sequence\", NULL ) );\n\n\t\/\/ Sounds\n\tpAnim->iszSounds[BA_BUSY] = AllocPooledString( pSection->GetString( \"busy_sound\", NULL ) );\n\tpAnim->iszSounds[BA_ENTRY] = AllocPooledString( pSection->GetString( \"entry_sound\", NULL ) );\n\tpAnim->iszSounds[BA_EXIT] = AllocPooledString( pSection->GetString( \"exit_sound\", NULL ) );\n\t\n\t\/\/ Times\n\tpAnim->flMinTime = pSection->GetFloat( \"min_time\", 10.0 );\n\tpAnim->flMaxTime = pSection->GetFloat( \"max_time\", 20.0 );\n\n\tpAnim->bUseAutomovement = pSection->GetInt( \"use_automovement\", 0 ) != 0;\n\n\tconst char *sInterrupt = pSection->GetString( \"interrupts\", \"BA_INT_DANGER\" );\n\tif ( !strcmp( sInterrupt, \"BA_INT_PLAYER\" ) )\n\t{\n\t\tpAnim->iBusyInterruptType = BA_INT_PLAYER;\n\t}\n\telse if ( !strcmp( sInterrupt, \"BA_INT_DANGER\" ) )\n\t{\n\t\tpAnim->iBusyInterruptType = BA_INT_DANGER;\n\t}\n\telse if ( !strcmp( sInterrupt, \"BA_INT_AMBUSH\" ) )\n\t{\n\t\tpAnim->iBusyInterruptType = BA_INT_AMBUSH;\n\t}\n\telse if ( !strcmp( sInterrupt, \"BA_INT_COMBAT\" ) )\n\t{\n\t\tpAnim->iBusyInterruptType = BA_INT_COMBAT;\n\t}\n\telse if ( !strcmp( sInterrupt, \"BA_INT_ZOMBIESLUMP\" ))\n\t{\n\t\tpAnim->iBusyInterruptType = BA_INT_ZOMBIESLUMP;\n\t}\n\telse if ( !strcmp( sInterrupt, \"BA_INT_SIEGE_DEFENSE\" ))\n\t{\n\t\tpAnim->iBusyInterruptType = BA_INT_SIEGE_DEFENSE;\n\t}\n\telse\n\t{\n\t\tpAnim->iBusyInterruptType = BA_INT_NONE;\n\t}\n\n\treturn true;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Returns the busyanim data for the specified activity\n\/\/-----------------------------------------------------------------------------\nint CActBusyAnimData::FindBusyAnim( Activity iActivity, const char *pSequence )\n{\n\tint iCount = m_ActBusyAnims.Count();\n\tfor ( int i = 0; i < iCount; i++ )\n\t{\n\t\tbusyanim_t *pBusyAnim = &m_ActBusyAnims[i];\n\t\tAssert( pBusyAnim );\n\n\t\tif ( pSequence && pBusyAnim->iszName != NULL_STRING && !Q_stricmp( STRING(pBusyAnim->iszName), pSequence ) )\n\t\t\treturn i;\n\n\t\tif ( iActivity != ACT_INVALID && pBusyAnim->iActivities[BA_BUSY] == iActivity )\n\t\t\treturn i;\n\t}\n\n\tif ( pSequence )\n\t{\n\t\tWarning(\"Specified '%s' as a busy anim name, and it's not in the act busy anim list.\\n\", pSequence );\n\t}\n\telse if ( iActivity != ACT_INVALID )\n\t{\n\t\tWarning(\"Tried to use Activity %d as a busy anim, and it's not in the act busy anim list.\\n\", iActivity );\n\t}\n\n\treturn -1;\n}\n\n\/\/=============================================================================================================\n\/\/=============================================================================================================\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nCAI_ActBusyBehavior::CAI_ActBusyBehavior()\n{\n\t\/\/ Disabled by default. Enabled by map entity.\n\tm_bEnabled = false;\n\tm_bUseRenderBoundsForCollision = false;\n\tm_flDeferUntil = 0;\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::Enable( CAI_ActBusyGoal *pGoal, float flRange, bool bVisibleOnly )\n{\n\tNotifyBusyEnding();\n\n\tif ( pGoal )\n\t{\n\t\tm_hActBusyGoal = pGoal;\n\t}\n\tm_bEnabled = true;\n\tm_bBusy = false;\n\tm_bMovingToBusy = false;\n\tm_bNeedsToPlayExitAnim = false;\n\tm_bLeaving = false;\n\tm_flNextBusySearchTime = gpGlobals->curtime + ai_actbusy_search_time.GetFloat();\n\tm_flEndBusyAt = 0;\n\tm_bVisibleOnly = bVisibleOnly;\n\tm_bInQueue = dynamic_cast<CAI_ActBusyQueueGoal*>(m_hActBusyGoal.Get()) != NULL;\n\tm_ForcedActivity = ACT_INVALID;\n\tm_hSeeEntity = NULL;\n\tm_bExitedBusyToDueLostSeeEntity = false;\n\tm_bExitedBusyToDueSeeEnemy = false;\n\tm_iNumConsecutivePathFailures = 0;\n\n\tSetBusySearchRange( flRange );\n\n\tif ( ai_debug_actbusy.GetInt() == 4 )\n\t{\n\t\tMsg(\"ACTBUSY: behavior enabled on NPC %s (%s)\\n\", GetOuter()->GetClassname(), GetOuter()->GetDebugName() );\n\t}\n\n\tif( IsCombatActBusy() )\n\t{\n\t\tCollectSafeZoneVolumes( pGoal );\n\t}\n\n\t\/\/ Robin: Due to ai goal entities delaying their EnableGoal call on each\n\t\/\/ of their target Actors, NPCs that are spawned with active actbusies\n\t\/\/ will have their SelectSchedule() called before their behavior has been\n\t\/\/ enabled. To fix this, if we're enabled while in a schedule that can be\n\t\/\/ overridden, immediately act busy.\n\tif ( IsCurScheduleOverridable() )\n\t{\n\t\t\/\/ Force search time to be now.\n\t\tm_flNextBusySearchTime = gpGlobals->curtime;\n\t\tGetOuter()->ClearSchedule( \"Enabling act busy\" );\n\t}\n\n\tClearCondition( COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::OnRestore()\n{\n\tif ( m_bEnabled && m_hActBusyGoal != NULL && IsCombatActBusy() )\n\t{\n\t\tCollectSafeZoneVolumes( m_hActBusyGoal );\n\t}\n\n\tBaseClass::OnRestore();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::SetBusySearchRange( float flRange )\n{\n\tm_flBusySearchRange = flRange;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::Disable( void )\n{\n\tif ( ai_debug_actbusy.GetInt() == 4 )\n\t{\n\t\tMsg(\"ACTBUSY: behavior disabled on NPC %s (%s)\\n\", GetOuter()->GetClassname(), GetOuter()->GetDebugName() );\n\t}\n\n\tif ( m_bEnabled )\n\t{\n\t\tSetCondition( COND_PROVOKED );\n\t}\n\n\tStopBusying();\n\tm_bEnabled = false;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::ForceActBusy( CAI_ActBusyGoal *pGoal, CAI_Hint *pHintNode, float flMaxTime, bool bVisibleOnly, bool bTeleportToBusy, bool bUseNearestBusy, CBaseEntity *pSeeEntity, Activity activity )\n{\n\tAssert( !m_bLeaving );\n\n\tif ( m_bNeedsToPlayExitAnim )\n\t{\n\t\t\/\/ If we hit this, the mapmaker's told this NPC to actbusy somewhere while it's still in an actbusy.\n\t\t\/\/ Right now, we don't support this. We could support it with a bit of work.\n\t\tif ( HasAnimForActBusy( m_iCurrentBusyAnim, BA_EXIT ) )\n\t\t{\n\t\t\tWarning(\"ACTBUSY: %s(%s) was told to actbusy while inside an actbusy that needs to exit first. IGNORING.\\n\", GetOuter()->GetDebugName(), GetOuter()->GetClassname() );\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif ( ai_debug_actbusy.GetInt() == 4 )\n\t{\n\t\tMsg(\"ACTBUSY: ForceActBusy on NPC %s (%s): \", GetOuter()->GetClassname(), GetOuter()->GetDebugName() );\n\t\tif ( pHintNode )\n\t\t{\n\t\t\tMsg(\"Hintnode %s\", pHintNode->GetDebugName());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tMsg(\"No Hintnode specified\");\n\t\t}\n\t\tMsg(\"\\n\");\n\t}\n\n\tEnable( pGoal, m_flBusySearchRange, bVisibleOnly );\n\tm_bForceActBusy = true;\n\tm_flForcedMaxTime = flMaxTime;\n\tm_bTeleportToBusy = bTeleportToBusy;\n\tm_bUseNearestBusy = bUseNearestBusy;\n\tm_ForcedActivity = activity;\n\tm_hSeeEntity = pSeeEntity;\n\n\tif ( pHintNode )\n\t{\n\t\tif ( GetHintNode() && GetHintNode() != pHintNode )\n\t\t{\n\t\t\tGetHintNode()->Unlock();\n\t\t}\n\n\t\tif ( pHintNode->Lock( GetOuter() ) )\n\t\t{\n\t\t\tSetHintNode( pHintNode );\n\t\t}\n\t}\n\n\tSetCondition( COND_PROVOKED );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Force the NPC to find an exit node and leave\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::ForceActBusyLeave( bool bVisibleOnly )\n{\n\tif ( ai_debug_actbusy.GetInt() == 4 )\n\t{\n\t\tMsg(\"ACTBUSY: ForceActBusyLeave on NPC %s (%s)\\n\", GetOuter()->GetClassname(), GetOuter()->GetDebugName() );\n\t}\n\n\tEnable( NULL, m_flBusySearchRange, bVisibleOnly );\n\tm_bForceActBusy = true;\n\tm_bLeaving = true;\n\tm_ForcedActivity = ACT_INVALID;\n\tm_hSeeEntity = NULL;\n\n\tSetCondition( COND_PROVOKED );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Break the NPC out of the current busy state, but don't disable busying\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::StopBusying( void )\n{\n\tif ( !GetOuter() )\n\t\treturn;\n\n\t\/\/ Make sure we turn this off unconditionally!\n\tm_bAutoFireWeapon = false;\n\n\tif ( ai_debug_actbusy.GetInt() == 4 )\n\t{\n\t\tMsg(\"ACTBUSY: StopBusying on NPC %s (%s)\\n\", GetOuter()->GetClassname(), GetOuter()->GetDebugName() );\n\t}\n\n\tif ( m_bBusy || m_bMovingToBusy )\n\t{\n\t\tSetCondition( COND_PROVOKED );\n\t}\n\n\tm_flEndBusyAt = gpGlobals->curtime;\n\tm_bForceActBusy = false;\n\tm_bTeleportToBusy = false;\n\tm_bUseNearestBusy = false;\n\tm_bLeaving = false;\n\tm_bMovingToBusy = false;\n\tm_ForcedActivity = ACT_INVALID;\n\tm_hSeeEntity = NULL;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::IsStopBusying()\n{\n\treturn IsCurSchedule(SCHED_ACTBUSY_STOP_BUSYING);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Find a general purpose, suitable Hint Node for me to Act Busy.\n\/\/-----------------------------------------------------------------------------\nCAI_Hint *CAI_ActBusyBehavior::FindActBusyHintNode()\n{\n\tAssert( !IsCombatActBusy() );\n\n\tint iBits = bits_HINT_NODE_USE_GROUP;\n\tif ( m_bVisibleOnly )\n\t{\n\t\tiBits |= bits_HINT_NODE_VISIBLE;\n\t}\n\n\tif ( ai_debug_actbusy.GetInt() == 3 && GetOuter()->m_debugOverlays & OVERLAY_NPC_SELECTED_BIT )\n\t{\n\t\tiBits |= bits_HINT_NODE_REPORT_FAILURES;\n\t}\n\n\tif ( m_bUseNearestBusy )\n\t{\n\t\tiBits |= bits_HINT_NODE_NEAREST;\n\t}\n\telse\n\t{\n\t\tiBits |= bits_HINT_NODE_RANDOM;\n\t}\n\n\tCAI_Hint *pNode = CAI_HintManager::FindHint( GetOuter(), HINT_WORLD_WORK_POSITION, iBits, m_flBusySearchRange );\n\n\treturn pNode;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Find a node for me to combat act busy.\n\/\/\n\/\/ Right now, all of this work assumes the actbusier is a player ally and\n\/\/ wants to fight near the player a'la Alyx in ep2_outland_10.\n\/\/-----------------------------------------------------------------------------\nCAI_Hint *CAI_ActBusyBehavior::FindCombatActBusyHintNode()\n{\n\tAssert( IsCombatActBusy() );\n\n\t#ifdef SecobMod__Enable_Fixed_Multiplayer_AI\n\t\tCBasePlayer *pPlayer = UTIL_GetNearestPlayer(GetAbsOrigin()); \n\t#else\n\t\tCBasePlayer *pPlayer = AI_GetSinglePlayer();\n\t#endif \/\/SecobMod__Enable_Fixed_Multiplayer_AI\n\n\tif( !pPlayer )\n\t\treturn NULL;\n\n\tCHintCriteria criteria;\n\n\t\/\/ Ok, find a hint node THAT:\n\t\/\/\t-Is in my hint group\n\t\/\/\t-Is Visible (if specified by designer)\n\t\/\/\t-Is Closest to me (if specified by designer)\n\t\/\/\t-The player can see\n\t\/\/\t-Is within the accepted max dist from player\n\tint iBits = bits_HINT_NODE_USE_GROUP;\n\t\n\tif ( m_bVisibleOnly )\n\t\tiBits |= bits_HINT_NODE_VISIBLE;\n\t\n\tif ( ai_debug_actbusy.GetInt() == 3 && GetOuter()->m_debugOverlays & OVERLAY_NPC_SELECTED_BIT )\n\t\tiBits |= bits_HINT_NODE_REPORT_FAILURES;\n\t\n\tif ( m_bUseNearestBusy )\n\t\tiBits |= bits_HINT_NODE_NEAREST;\n\telse\n\t\tiBits |= bits_HINT_NODE_RANDOM;\n\n\tiBits |= bits_HAS_EYEPOSITION_LOS_TO_PLAYER;\n\n\tcriteria.AddHintType( HINT_WORLD_WORK_POSITION );\n\tcriteria.SetFlag( iBits );\n\tcriteria.AddIncludePosition( pPlayer->GetAbsOrigin(), ACTBUSY_COMBAT_PLAYER_MAX_DIST );\n\n\tCAI_Hint *pNode = CAI_HintManager::FindHint( GetOuter(), criteria );\n\n\treturn pNode;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Find a suitable combat actbusy node to teleport to. That is, find\n\/\/\t\t\tone that the player is not going to see me appear at.\n\/\/-----------------------------------------------------------------------------\nCAI_Hint *CAI_ActBusyBehavior::FindCombatActBusyTeleportHintNode()\n{\n\tAssert( IsCombatActBusy() );\n\n\t#ifdef SecobMod__Enable_Fixed_Multiplayer_AI\n\t\tCBasePlayer *pPlayer = UTIL_GetNearestPlayer(GetAbsOrigin()); \n\t#else\n\t\tCBasePlayer *pPlayer = AI_GetSinglePlayer();\n\t#endif \/\/SecobMod__Enable_Fixed_Multiplayer_AI\n\n\tif( !pPlayer )\n\t\treturn NULL;\n\n\tCHintCriteria criteria;\n\n\t\/\/ Ok, find a hint node THAT:\n\t\/\/\t-Is in my hint group\n\t\/\/\t-The player CAN NOT see so that they don't see me teleport\n\tint iBits = bits_HINT_NODE_USE_GROUP;\n\n\tif ( ai_debug_actbusy.GetInt() == 3 && GetOuter()->m_debugOverlays & OVERLAY_NPC_SELECTED_BIT )\n\t\tiBits |= bits_HINT_NODE_REPORT_FAILURES;\n\n\tiBits |= bits_HINT_NODE_RANDOM;\n\tiBits |= bits_HINT_NODE_NOT_VISIBLE_TO_PLAYER;\n\n\tcriteria.AddHintType( HINT_WORLD_WORK_POSITION );\n\tcriteria.SetFlag( iBits );\n\tcriteria.AddIncludePosition( pPlayer->GetAbsOrigin(), ACTBUSY_COMBAT_PLAYER_MAX_DIST * 1.1f );\n\n\tCAI_Hint *pNode = CAI_HintManager::FindHint( GetOuter(), criteria );\n\n\treturn pNode;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::FValidateHintType( CAI_Hint *pHint )\n{\n\tif ( pHint->HintType() != HINT_WORLD_WORK_POSITION && pHint->HintType() != HINT_NPC_EXIT_POINT )\n\t\treturn false;\n\n\t\/\/ If the node doesn't want to be teleported to, we need to check for clear\n\tconst char *pSequenceOrActivity = STRING(pHint->HintActivityName());\n\tconst char *cSpace = strchr( pSequenceOrActivity, ' ' );\n\tif ( cSpace )\n\t{\n\t\tif ( !Q_strncmp( cSpace+1, \"teleport\", 8 ) )\n\t\t{\n\t\t\t\/\/ Node is a teleport node, so it's good\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t\/\/ Check for clearance\n\ttrace_t tr;\n\tAI_TraceHull( pHint->GetAbsOrigin(), pHint->GetAbsOrigin(), GetOuter()->WorldAlignMins(), GetOuter()->WorldAlignMaxs(), MASK_SOLID, GetOuter(), COLLISION_GROUP_NONE, &tr );\n\tif ( tr.fraction == 1.0 )\n\t\treturn true;\n\n\t\/\/ Report failures\n\tif ( ai_debug_actbusy.GetInt() == 3 && GetOuter()->m_debugOverlays & OVERLAY_NPC_SELECTED_BIT )\n\t{\n\t\tNDebugOverlay::Text( pHint->GetAbsOrigin(), \"Node isn't clear.\", false, 60 );\n\t\tNDebugOverlay::Box( pHint->GetAbsOrigin(), GetOuter()->WorldAlignMins(), GetOuter()->WorldAlignMaxs(), 255,0,0, 8, 2.0 );\n\t}\n\n\treturn false;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::CanSelectSchedule( void )\n{\n\t\/\/ Always active when we're busy\n\tif ( m_bBusy || m_bForceActBusy || m_bNeedsToPlayExitAnim )\n\t\treturn true;\n\n\tif ( !m_bEnabled )\n\t\treturn false;\n\n\tif ( m_flDeferUntil > gpGlobals->curtime )\n\t\treturn false;\n\n\tif ( CountEnemiesInSafeZone() > 0 )\n\t{\n\t\t\/\/ I have enemies left in the safe zone. Actbusy isn't appropriate. \n\t\t\/\/ I should be off fighting them.\n\t\treturn false;\n\t}\n\n\tif ( !IsCurScheduleOverridable() )\n\t\treturn false;\n\n\t\/\/ Don't select actbusy if we're not going to search for a node anyway\n\treturn (m_flNextBusySearchTime < gpGlobals->curtime);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Return true if the current schedule is one that ActBusy is allowed to override\n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::IsCurScheduleOverridable( void )\n{\n\tif( IsCombatActBusy() )\n\t{\n\t\t\/\/ The whole point of a combat actbusy is that it can run in any state (including combat)\n\t\t\/\/ the only exception is SCRIPT (sjb)\n\t\treturn (GetOuter()->GetState() != NPC_STATE_SCRIPT);\n\t}\n\n\t\/\/ Act busies are not valid inside of a vehicle\n\tif ( GetOuter()->IsInAVehicle() )\n\t\treturn false;\n\n\t\/\/ Only if we're about to idle (or SCHED_NONE to catch newly spawned guys)\t\t\n\treturn ( IsCurSchedule( SCHED_IDLE_STAND ) || IsCurSchedule( SCHED_NONE ) );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : *pSound - \n\/\/ Output : Returns true on success, false on failure.\n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::ShouldIgnoreSound( CSound *pSound )\n{\n\t\/\/ If we're busy in an actbusy anim that's an ambush, stay mum as long as we can\n\tif ( m_bBusy )\n\t{\n\t\tbusyanim_t *pBusyAnim = g_ActBusyAnimDataSystem.GetBusyAnim( m_iCurrentBusyAnim );\n\n\t\tif( pBusyAnim && pBusyAnim->iBusyInterruptType == BA_INT_ZOMBIESLUMP )\n\t\t{\n\t\t\t\/\/ Slumped zombies are deaf.\n\t\t\treturn true;\n\t\t}\n\n\t\tif ( pBusyAnim && ( ( pBusyAnim->iBusyInterruptType == BA_INT_AMBUSH ) || ( pBusyAnim->iBusyInterruptType == BA_INT_COMBAT ) ) )\n\t\t{\n\t\t\t\/*\n\t\t\t\/\/ Robin: First version ignored sounds in front of the NPC.\n\t\t\tVector vecToSound = (pSound->GetSoundReactOrigin() - GetAbsOrigin());\n\t\t\tvecToSound.z = 0;\n\t\t\tVectorNormalize( vecToSound );\n\t\t\tVector facingDir = GetOuter()->EyeDirection2D();\n\t\t\tif ( DotProduct( vecToSound, facingDir ) > 0 )\n\t\t\t\treturn true;\n\t\t\t*\/\n\n\t\t\t\/\/ Ignore sounds that aren't visible\n\t\t\tif ( !GetOuter()->FVisible( pSound->GetSoundReactOrigin() ) )\n\t\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn BaseClass::ShouldIgnoreSound( pSound );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::OnFriendDamaged( CBaseCombatCharacter *pSquadmate, CBaseEntity *pAttacker )\n{\n\tif( IsCombatActBusy() && pSquadmate->IsPlayer() && IsInSafeZone( pAttacker ) )\n\t{\n\t\tSetCondition( COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE ); \/\/ Break the actbusy, if we're running it.\n\t\tm_flDeferUntil = gpGlobals->curtime + 4.0f;\t\/\/ Stop actbusying and go deal with that enemy!!\n\t}\n\n\tBaseClass::OnFriendDamaged( pSquadmate, pAttacker );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Count the number of enemies of mine that are inside my safe zone\n\/\/\t\t\tvolume.\n\/\/\n\/\/\t\t\tNOTE: We keep this count to prevent the NPC re-entering combat \n\/\/\t\t\tactbusy whilst too many enemies are present in the safe zone.\n\/\/\t\t\tThis count does not automatically alert the NPC that there are\n\/\/\t\t\tenemies in the safe zone. \n\/\/\t\t\tYou must set COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE to let\n\/\/\t\t\tthe NPC know.\n\/\/-----------------------------------------------------------------------------\nint CAI_ActBusyBehavior::CountEnemiesInSafeZone()\n{\n\tif( !IsCombatActBusy() )\n\t{\n\t\treturn 0;\n\t}\n\n\t\/\/ Grovel the AI list and count the enemies in the zone. By enemies, I mean\n\t\/\/ anyone that I would fight if I saw. \n\tCAI_BaseNPC **\tppAIs \t= g_AI_Manager.AccessAIs();\n\tint \t\t\tnAIs \t= g_AI_Manager.NumAIs();\n\tint\t\t\t\tcount = 0;\n\n\tfor ( int i = 0; i < nAIs; i++ )\n\t{\n\t\tif( GetOuter()->IRelationType(ppAIs[i]) < D_LI )\n\t\t{\n\t\t\tif( IsInSafeZone(ppAIs[i]) )\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn count;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nint\tCAI_ActBusyBehavior::OnTakeDamage_Alive( const CTakeDamageInfo &info )\n{\n\tif( IsCombatActBusy() && info.GetAttacker() && IsInSafeZone( info.GetAttacker() ) )\n\t{\n\t\tSetCondition( COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE ); \/\/ Break the actbusy, if we're running it.\n\t\tm_flDeferUntil = gpGlobals->curtime + 4.0f;\t\/\/ Stop actbusying and go deal with that enemy!!\n\t}\n\n\treturn BaseClass::OnTakeDamage_Alive( info );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::GatherConditions( void )\n{\n\t\/\/ Clear this condition before we call up, since the look sensing code will run and\n\t\/\/ set this condition if it is relevant.\n\tif( !IsCurSchedule(SCHED_ACTBUSY_BUSY, false) )\n\t{\n\t\t\/\/ Only clear this condition when we aren't busying. We want it to be sticky \n\t\t\/\/ during that time so that schedule selection works properly (sjb)\n\t\tClearCondition( COND_ACTBUSY_ENEMY_TOO_CLOSE );\n\t}\n\n\tBaseClass::GatherConditions();\n\n\tbool bCheckLOS = true;\n\tbool bCheckFOV = true;\n\n\tif( m_hActBusyGoal && m_hActBusyGoal->m_iSightMethod == ACTBUSY_SIGHT_METHOD_LOS_ONLY )\n\t{\n\t\tbCheckFOV = false;\n\t}\n\n\t\/\/ If we have a see entity, make sure we can still see it\n\tif ( m_hSeeEntity && m_bBusy )\n\t{\n\t\tif ( (!bCheckFOV||GetOuter()->FInViewCone(m_hSeeEntity)) && GetOuter()->QuerySeeEntity(m_hSeeEntity) && (!bCheckLOS||GetOuter()->FVisible(m_hSeeEntity)) )\n\t\t{\n\t\t\tm_fTimeLastSawSeeEntity = gpGlobals->curtime;\n\t\t\tClearCondition( COND_ACTBUSY_LOST_SEE_ENTITY );\n\t\t}\n\t\telse if( m_hActBusyGoal )\n\t\t{\n\t\t\tfloat fDelta = gpGlobals->curtime - m_fTimeLastSawSeeEntity;\n\t\t\tif( fDelta >= m_hActBusyGoal->m_flSeeEntityTimeout )\n\t\t\t{\n\t\t\t\tSetCondition( COND_ACTBUSY_LOST_SEE_ENTITY );\n\t\t\t\tm_hActBusyGoal->NPCLostSeeEntity( GetOuter() );\n\n\t\t\t\tif( IsCombatActBusy() && (GetOuter()->Classify() == CLASS_PLAYER_ALLY_VITAL && m_hSeeEntity->IsPlayer()) )\n\t\t\t\t{\n\t\t\t\t\t\/\/ Defer any actbusying for several seconds. This serves as a heuristic for waiting\n\t\t\t\t\t\/\/ for the player to settle after moving out of the room. This helps Alyx pick a more\n\t\t\t\t\t\/\/ pertinent Actbusy near the player's new location.\n\t\t\t\t\tm_flDeferUntil = gpGlobals->curtime + 4.0f;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tClearCondition( COND_ACTBUSY_LOST_SEE_ENTITY );\n\t}\n\n\t\/\/ If we're busy, ignore sounds depending on our actbusy break rules\n\tif ( m_bBusy )\n\t{\n\t\tbusyanim_t *pBusyAnim = g_ActBusyAnimDataSystem.GetBusyAnim( m_iCurrentBusyAnim );\n\t\tif ( pBusyAnim )\n\t\t{\n\t\t\tswitch( pBusyAnim->iBusyInterruptType )\n\t\t\t{\n\t\t\tcase BA_INT_DANGER:\n\t\t\t\tbreak;\n\n\t\t\tcase BA_INT_AMBUSH:\n\t\t\t\tbreak;\n\n\t\t\tcase BA_INT_ZOMBIESLUMP:\n\t\t\t\t{\n\t\t\t\t\tClearCondition( COND_HEAR_PLAYER );\n\t\t\t\t\tClearCondition( COND_SEE_ENEMY );\n\t\t\t\t\tClearCondition( COND_NEW_ENEMY );\n\n\t\t\t\t\t#ifdef SecobMod__Enable_Fixed_Multiplayer_AI\n\t\t\t\t\t\tCBasePlayer *pPlayer = UTIL_GetNearestPlayer(GetAbsOrigin()); \n\t\t\t\t\t#else\n\t\t\t\t\t\tCBasePlayer *pPlayer = UTIL_PlayerByIndex(1);\n\t\t\t\t\t#endif \/\/SecobMod__Enable_Fixed_Multiplayer_AI\n\n\t\t\t\t\tif( pPlayer )\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat flDist = pPlayer->GetAbsOrigin().DistTo( GetAbsOrigin() );\n\n\t\t\t\t\t\tif( flDist <= 60 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tStopBusying();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase BA_INT_COMBAT:\n\t\t\t\t\/\/ Ignore the player unless he shoots at us\n\t\t\t\tClearCondition( COND_HEAR_PLAYER );\n\t\t\t\tClearCondition( COND_SEE_ENEMY );\n\t\t\t\tClearCondition( COND_NEW_ENEMY );\n\t\t\t\tbreak;\n\n\t\t\tcase BA_INT_PLAYER:\n\t\t\t\t\/\/ Clear all but player.\n\t\t\t\tClearCondition( COND_HEAR_DANGER );\n\t\t\t\tClearCondition( COND_HEAR_COMBAT );\n\t\t\t\tClearCondition( COND_HEAR_WORLD  );\n\t\t\t\tClearCondition( COND_HEAR_BULLET_IMPACT );\n\t\t\t\tbreak;\n\n\t\t\tcase BA_INT_SIEGE_DEFENSE:\n\t\t\t\tClearCondition( COND_HEAR_PLAYER );\n\t\t\t\tClearCondition( COND_SEE_ENEMY );\n\t\t\t\tClearCondition( COND_NEW_ENEMY );\n\t\t\t\tClearCondition( COND_HEAR_COMBAT );\n\t\t\t\tClearCondition( COND_HEAR_WORLD  );\n\t\t\t\tClearCondition( COND_HEAR_BULLET_IMPACT );\n\t\t\t\tbreak;\n\n\t\t\tcase BA_INT_NONE:\n\t\t\t\t\/\/ Clear all\n\t\t\t\tClearCondition( COND_HEAR_DANGER );\n\t\t\t\tClearCondition( COND_HEAR_COMBAT );\n\t\t\t\tClearCondition( COND_HEAR_WORLD  );\n\t\t\t\tClearCondition( COND_HEAR_BULLET_IMPACT );\n\t\t\t\tClearCondition( COND_HEAR_PLAYER );\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif( m_bAutoFireWeapon && random->RandomInt(0, 5) <= 3 )\n\t{\n\t\tCBaseCombatWeapon *pWeapon = GetOuter()->GetActiveWeapon();\n\n\t\tif( pWeapon )\n\t\t{\n\t\t\tpWeapon->Operator_ForceNPCFire( GetOuter(), false );\n\t\t}\n\t}\n\n\tif( ai_debug_actbusy.GetInt() == 5 )\n\t{\n\t\t\/\/ Visualize them there Actbusy safe volumes\n\t\tfor( int i = 0 ; i < m_SafeZones.Count() ; i++ )\n\t\t{\n\t\t\tbusysafezone_t *pSafeZone = &m_SafeZones[i];\n\n\t\t\tVector vecBoxOrigin = (pSafeZone->vecMins + pSafeZone->vecMaxs) * 0.5f;\n\t\t\tVector vecBoxMins = vecBoxOrigin - pSafeZone->vecMins;\n\t\t\tVector vecBoxMaxs = vecBoxOrigin - pSafeZone->vecMaxs;\n\t\t\tNDebugOverlay::Box( vecBoxOrigin, vecBoxMins, vecBoxMaxs, 255, 0, 255, 64, 0.2f );\n\t\t}\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::EndScheduleSelection( void )\n{\n\tNotifyBusyEnding();\n\n\tCheckAndCleanupOnExit();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : nActivity - \n\/\/-----------------------------------------------------------------------------\nActivity CAI_ActBusyBehavior::NPC_TranslateActivity( Activity nActivity )\n{\n\t\/\/ Find out what the base class wants to do with the activity\n\tActivity nNewActivity = BaseClass::NPC_TranslateActivity( nActivity );\n\n\tif( nActivity == ACT_RUN )\n\t{\n\t\t\/\/ FIXME: Forcing STIMULATED here is illegal if the entity doesn't support it as an activity\n\t\tCAI_PlayerAlly *pAlly = dynamic_cast<CAI_PlayerAlly*>(GetOuter());\n\t\tif ( pAlly )\n\t\t\treturn ACT_RUN_STIMULATED;\n\t}\n\n\t\/\/ Else stay with the base class' decision.\n\treturn nNewActivity;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::HandleAnimEvent( animevent_t *pEvent )\n{\n\tif( pEvent->event == AE_ACTBUSY_WEAPON_FIRE_ON )\n\t{\n\t\tm_bAutoFireWeapon = true;\n\t\treturn;\n\t}\n\telse if( pEvent->event == AE_ACTBUSY_WEAPON_FIRE_OFF )\n\t{\n\t\tm_bAutoFireWeapon = false;\n\t\treturn;\n\t}\n\n\n\treturn BaseClass::HandleAnimEvent( pEvent );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Actbusy's ending, ensure we haven't left NPC in broken state.\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::CheckAndCleanupOnExit( void )\n{\n\tif ( m_bNeedsToPlayExitAnim && !GetOuter()->IsMarkedForDeletion() && GetOuter()->IsAlive() )\n\t{\n\t\tWarning(\"NPC %s(%s) left actbusy without playing exit anim.\\n\", GetOuter()->GetDebugName(), GetOuter()->GetClassname() );\n\t\tm_bNeedsToPlayExitAnim = false;\n\t}\n\n\tGetOuter()->RemoveFlag( FL_FLY );\n\n\t\/\/ If we're supposed to use render bounds while inside the busy anim, restore normal now\n\tif ( m_bUseRenderBoundsForCollision )\n\t{\n\t\tGetOuter()->SetHullSizeNormal( true );\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::BuildScheduleTestBits( void )\n{\n\tBaseClass::BuildScheduleTestBits();\n\n\t\/\/ When going to an actbusy, we can't be interrupted during the entry anim\n\tif ( IsCurSchedule(SCHED_ACTBUSY_START_BUSYING) )\n\t{\n\t\tif ( GetOuter()->GetTask()->iTask == TASK_ACTBUSY_PLAY_ENTRY )\n\t\t\treturn;\n\n\t\tGetOuter()->SetCustomInterruptCondition( COND_PROVOKED );\n\n\t\tif( IsCombatActBusy() )\n\t\t{\n\t\t\tGetOuter()->SetCustomInterruptCondition( GetClassScheduleIdSpace()->ConditionLocalToGlobal(COND_ACTBUSY_ENEMY_TOO_CLOSE) );\n\t\t}\n\t}\n\n\t\/\/ If we're in a queue, or leaving, we have no extra conditions\n\tif ( m_bInQueue || IsCurSchedule( SCHED_ACTBUSY_LEAVE ) )\n\t\treturn;\n\n\t\/\/ If we're not busy, or we're exiting a busy, we have no extra conditions\n\tif ( !m_bBusy || IsCurSchedule( SCHED_ACTBUSY_STOP_BUSYING ) )\n\t\treturn;\n\n\tbusyanim_t *pBusyAnim = g_ActBusyAnimDataSystem.GetBusyAnim( m_iCurrentBusyAnim );\n\tif ( pBusyAnim )\n\t{\n\t\tswitch( pBusyAnim->iBusyInterruptType )\n\t\t{\n\t\t\tcase BA_INT_ZOMBIESLUMP:\n\t\t\t{\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_LIGHT_DAMAGE );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_HEAVY_DAMAGE );\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase BA_INT_SIEGE_DEFENSE:\n\t\t\t{\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_HEAR_DANGER );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( GetClassScheduleIdSpace()->ConditionLocalToGlobal(COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE) );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( GetClassScheduleIdSpace()->ConditionLocalToGlobal(COND_ACTBUSY_ENEMY_TOO_CLOSE) );\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase BA_INT_AMBUSH:\n\t\t\tcase BA_INT_DANGER:\n\t\t\t{\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_LIGHT_DAMAGE );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_HEAVY_DAMAGE );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_HEAR_DANGER );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_HEAR_COMBAT );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_HEAR_BULLET_IMPACT );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_NEW_ENEMY );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_SEE_ENEMY );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_PLAYER_ADDED_TO_SQUAD );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_RECEIVED_ORDERS );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase BA_INT_PLAYER:\n\t\t\t{\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_LIGHT_DAMAGE );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_HEAVY_DAMAGE );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_HEAR_DANGER );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_HEAR_COMBAT );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_HEAR_BULLET_IMPACT );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_NEW_ENEMY );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_PLAYER_ADDED_TO_SQUAD );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_RECEIVED_ORDERS );\n\n\t\t\t\t\/\/ The player can interrupt us\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_SEE_PLAYER );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase BA_INT_COMBAT:\n\t\t\t{\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_LIGHT_DAMAGE );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_HEAVY_DAMAGE );\n\t\t\t\tGetOuter()->SetCustomInterruptCondition( COND_HEAR_DANGER );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase BA_INT_NONE:\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nint\tCAI_ActBusyBehavior::SelectScheduleForLeaving( void )\n{\n\t\/\/ Are we already near an exit node?\n\tif ( GetHintNode() )\n\t{\n\t\tif ( GetHintNode()->HintType() == HINT_NPC_EXIT_POINT )\n\t\t{\n\t\t\t\/\/ Are we near it? If so, we're done. If not, move to it.\n\t\t\tif ( UTIL_DistApprox( GetHintNode()->GetAbsOrigin(), GetAbsOrigin() ) < 64 )\n\t\t\t{\n\t\t\t\tif ( !GetOuter()->IsMarkedForDeletion() )\n\t\t\t\t{\n\t\t\t\t\tCBaseEntity *pOwner = GetOuter()->GetOwnerEntity();\n\t\t\t\t\tif ( pOwner )\n\t\t\t\t\t{\n\t\t\t\t\t\tpOwner->DeathNotice( GetOuter() );\n\t\t\t\t\t\tGetOuter()->SetOwnerEntity( NULL );\n\t\t\t\t\t}\n\t\t\t\t\tGetOuter()->SetThink( &CBaseEntity::SUB_Remove); \/\/SUB_Remove) ; \/\/GetOuter()->SUB_Remove );\n\t\t\t\t\tGetOuter()->SetNextThink( gpGlobals->curtime + 0.1 );\n\n\t\t\t\t\tif ( m_hActBusyGoal )\n\t\t\t\t\t{\n\t\t\t\t\t\tm_hActBusyGoal->NPCLeft( GetOuter() );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn SCHED_IDLE_STAND;\n\t\t\t}\n\n\t\t\treturn SCHED_ACTBUSY_LEAVE;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Clear the node, it's no use to us\n\t\t\tGetHintNode()->NPCStoppedUsing( GetOuter() );\n\t\t\tGetHintNode()->Unlock();\n\t\t\tSetHintNode( NULL );\n\t\t}\n\t}\n\n\t\/\/ Find an exit node\n\tCHintCriteria\thintCriteria;\n\thintCriteria.SetHintType( HINT_NPC_EXIT_POINT );\n\thintCriteria.SetFlag( bits_HINT_NODE_RANDOM | bits_HINT_NODE_CLEAR | bits_HINT_NODE_USE_GROUP );\n\tCAI_Hint *pNode = CAI_HintManager::FindHintRandom( GetOuter(), GetOuter()->GetAbsOrigin(), hintCriteria );\n\tif ( pNode )\n\t{\n\t\tSetHintNode( pNode );\n\t\treturn SCHED_ACTBUSY_LEAVE;\n\t}\n\n\t\/\/ We've been told to leave, but we can't find an exit node. What to do?\n\treturn SCHED_IDLE_STAND;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nint CAI_ActBusyBehavior::SelectScheduleWhileNotBusy( int iBase )\n{\n\t\/\/ Randomly act busy (unless we're being forced, in which case we should search immediately)\n\tif ( m_bForceActBusy || m_flNextBusySearchTime < gpGlobals->curtime )\n\t{\n\t\t\/\/ If we're being forced, think again quickly\n\t\tif ( m_bForceActBusy || IsCombatActBusy() )\n\t\t{\n\t\t\tm_flNextBusySearchTime = gpGlobals->curtime + 2.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_flNextBusySearchTime = gpGlobals->curtime + RandomFloat(ai_actbusy_search_time.GetFloat(), ai_actbusy_search_time.GetFloat()*2);\n\t\t}\n\n\t\t\/\/ We may already have a node\n\t\tbool bForceTeleport = false;\n\t\tCAI_Hint *pNode = GetHintNode();\n\t\tif ( !pNode )\n\t\t{\n\t\t\tif( IsCombatActBusy() )\n\t\t\t{\n\t\t\t\t#ifdef SecobMod__Enable_Fixed_Multiplayer_AI\n\t\t\t\t\tCBasePlayer *pPlayer = UTIL_GetNearestVisiblePlayer(GetOuter()); \n\t\t\t\t\tif ( m_hActBusyGoal->IsCombatActBusyTeleportAllowed() && m_iNumConsecutivePathFailures >= 2 && !pPlayer->FInViewCone(GetOuter()) )  \n\t\t\t\t#else\n\t\t\t\t\tif ( m_hActBusyGoal->IsCombatActBusyTeleportAllowed() && m_iNumConsecutivePathFailures >= 2 && !AI_GetSinglePlayer()->FInViewCone(GetOuter()) )\n\t\t\t\t#endif \/\/SecobMod__Enable_Fixed_Multiplayer_AI\n\t\t\t\t{\n\t\t\t\t\t\/\/ Looks like I've tried several times to find a path to a valid hint node and\n\t\t\t\t\t\/\/ haven't been able to. This means I'm on a patch of node graph that simply\n\t\t\t\t\t\/\/ does not connect to any hint nodes that match my criteria. So try to find\n\t\t\t\t\t\/\/ a node that's safe to teleport to. (sjb) ep2_outland_10 (Alyx)\n\t\t\t\t\t\/\/ (Also, I must not be in the player's viewcone)\n\t\t\t\t\tpNode = FindCombatActBusyTeleportHintNode();\n\t\t\t\t\tbForceTeleport = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpNode = FindCombatActBusyHintNode();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpNode = FindActBusyHintNode();\n\t\t\t}\n\t\t}\n\t\tif ( pNode )\n\t\t{\n\t\t\t\/\/ Ensure we've got a sequence for the node\n\t\t\tconst char *pSequenceOrActivity = STRING(pNode->HintActivityName());\n\t\t\tActivity iNodeActivity;\n\t\t\tint iBusyAnim;\n\n\t\t\t\/\/ See if the node specifies that we should teleport to it\n\t\t\tconst char *cSpace = strchr( pSequenceOrActivity, ' ' );\n\t\t\tif ( cSpace )\n\t\t\t{\n\t\t\t\tif ( !Q_strncmp( cSpace+1, \"teleport\", 8 ) )\n\t\t\t\t{\n\t\t\t\t\tm_bTeleportToBusy = true;\n\t\t\t\t}\n\n\t\t\t\tchar sActOrSeqName[512];\n\t\t\t\tQ_strncpy( sActOrSeqName, pSequenceOrActivity, (cSpace-pSequenceOrActivity)+1 );\n\t\t\t\tiNodeActivity = (Activity)CAI_BaseNPC::GetActivityID( sActOrSeqName ); \n\t\t\t\tiBusyAnim = g_ActBusyAnimDataSystem.FindBusyAnim( iNodeActivity, sActOrSeqName );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tiNodeActivity = (Activity)CAI_BaseNPC::GetActivityID( pSequenceOrActivity ); \n\t\t\t\tiBusyAnim = g_ActBusyAnimDataSystem.FindBusyAnim( iNodeActivity, pSequenceOrActivity );\n\t\t\t}\n\n\t\t\t\/\/ Does this NPC have the activity or sequence for this node?\n\t\t\tif ( HasAnimForActBusy( iBusyAnim, BA_BUSY ) )\n\t\t\t{\n\t\t\t\tif ( HasCondition(COND_ACTBUSY_LOST_SEE_ENTITY) )\n\t\t\t\t{\n\t\t\t\t\t\/\/ We've lost our see entity, which means we can't continue.\n\t\t\t\t\tif ( m_bForceActBusy )\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ We were being told to act busy, which we can't do now that we've lost the see entity.\n\t\t\t\t\t\t\/\/ Abort, and assume that the mapmaker will make us retry.\n\t\t\t\t\t\tStopBusying();\n\t\t\t\t\t}\n\t\t\t\t\treturn iBase;\n\t\t\t\t}\n\n\t\t\t\tm_iCurrentBusyAnim = iBusyAnim;\n\t\t\t\tif ( m_iCurrentBusyAnim == -1 )\n\t\t\t\t\treturn iBase;\n\n\t\t\t\tif ( ai_debug_actbusy.GetInt() == 4 )\n\t\t\t\t{\n\t\t\t\t\tMsg(\"ACTBUSY: NPC %s (%s) found Actbusy node %s \\n\", GetOuter()->GetClassname(), GetOuter()->GetDebugName(), pNode->GetDebugName() );\n\t\t\t\t}\n\n\t\t\t\tif ( GetHintNode() )\n\t\t\t\t{\n\t\t\t\t\tGetHintNode()->Unlock();\n\t\t\t\t}\n\n\t\t\t\tSetHintNode( pNode );\n\t\t\t\tif ( GetHintNode() && GetHintNode()->Lock( GetOuter() ) )\n\t\t\t\t{\n\t\t\t\t\tif ( ai_debug_actbusy.GetInt() == 2 )\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Show which actbusy we're moving towards\n\t\t\t\t\t\tNDebugOverlay::Line( GetOuter()->WorldSpaceCenter(), pNode->GetAbsOrigin(), 0, 255, 0, true, 5.0 );\n\t\t\t\t\t\tNDebugOverlay::Box( pNode->GetAbsOrigin(), GetOuter()->WorldAlignMins(), GetOuter()->WorldAlignMaxs(), 0, 255, 0, 64, 5.0 );\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Let our act busy know we're moving to a node\n\t\t\t\t\tif ( m_hActBusyGoal )\n\t\t\t\t\t{\n\t\t\t\t\t\tm_hActBusyGoal->NPCMovingToBusy( GetOuter() );\n\t\t\t\t\t}\n\n\t\t\t\t\tm_bMovingToBusy = true;\n\n\t\t\t\t\tif( m_hActBusyGoal && m_hActBusyGoal->m_iszSeeEntityName != NULL_STRING )\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Set the see entity Handle if we have one.\n\t\t\t\t\t\tm_hSeeEntity.Set( gEntList.FindEntityByName(NULL, m_hActBusyGoal->m_iszSeeEntityName) );\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ At this point we know we're starting. \n\t\t\t\t\tClearCondition( COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE );\n\n\t\t\t\t\t\/\/ If we're supposed to teleport, do that instead\n\t\t\t\t\tif ( m_bTeleportToBusy )\n\t\t\t\t\t{\n\t\t\t\t\t\treturn SCHED_ACTBUSY_TELEPORT_TO_BUSY;\n\t\t\t\t\t}\n\t\t\t\t\telse if( bForceTeleport )\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ We found a place to go, so teleport there and forget that we ever had trouble.\n\t\t\t\t\t\tm_iNumConsecutivePathFailures = 0;\n\t\t\t\t\t\treturn SCHED_ACTBUSY_TELEPORT_TO_BUSY;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn SCHED_ACTBUSY_START_BUSYING;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ WE DIDN'T FIND A NODE!\n\t\t\tif( IsCombatActBusy() )\n\t\t\t{\n\t\t\t\t\/\/ Don't try again right away, not enough state will have changed.\n\t\t\t\t\/\/ Just go do something useful for a few seconds.\n\t\t\t\tm_flNextBusySearchTime = gpGlobals->curtime + 10.0;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn SCHED_NONE;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nint\tCAI_ActBusyBehavior::SelectScheduleWhileBusy( void )\n{\n\t\/\/ Are we supposed to stop on our current actbusy, but stay in the actbusy state?\n\tif ( !ActBusyNodeStillActive() || (m_flEndBusyAt && gpGlobals->curtime >= m_flEndBusyAt) )\n\t{\n\t\tif ( ai_debug_actbusy.GetInt() == 4 )\n\t\t{\n\t\t\tMsg(\"ACTBUSY: NPC %s (%s) ending actbusy.\\n\", GetOuter()->GetClassname(), GetOuter()->GetDebugName() );\n\t\t}\n\n\t\tStopBusying();\n\t\treturn SCHED_ACTBUSY_STOP_BUSYING;\n\t}\n\n\tif( IsCombatActBusy() && (HasCondition(COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE) || HasCondition(COND_ACTBUSY_ENEMY_TOO_CLOSE)) )\n\t{\n\t\treturn SCHED_ACTBUSY_STOP_BUSYING;\n\t}\n\n\treturn SCHED_ACTBUSY_BUSY;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nint CAI_ActBusyBehavior::SelectSchedule()\n{\n\tint iBase = BaseClass::SelectSchedule();\n\n\t\/\/ Only do something if the base ai doesn't want to do anything\n\tif ( !IsCombatActBusy() && !m_bForceActBusy && iBase != SCHED_IDLE_STAND )\n\t{\n\t\t\/\/ If we're busy, we need to get out of it first\n\t\tif ( m_bBusy )\n\t\t\treturn SCHED_ACTBUSY_STOP_BUSYING;\n\n\t\tCheckAndCleanupOnExit();\n\t\treturn iBase;\n\t}\n\n\t\/\/ If we're supposed to be leaving, find a leave node and exit\n\tif ( m_bLeaving )\n\t\treturn SelectScheduleForLeaving();\n\n\t\/\/ NPCs should not be busy if the actbusy behaviour has been disabled, or if they've received player squad commands\n\tbool bShouldNotBeBusy = (!m_bEnabled || HasCondition( COND_PLAYER_ADDED_TO_SQUAD ) || HasCondition( COND_RECEIVED_ORDERS ) );\n\tif ( bShouldNotBeBusy )\n\t{\n\t\tif ( !GetOuter()->IsMarkedForDeletion() && GetOuter()->IsAlive() )\n\t\t\treturn SCHED_ACTBUSY_STOP_BUSYING;\n\t}\n\telse\n\t{\n\t\tif ( m_bBusy )\n\t\t\treturn SelectScheduleWhileBusy();\n\n\t\t\/\/ I'm not busy, and I'm supposed to be\n\t\tint schedule = SelectScheduleWhileNotBusy( iBase );\n\t\tif ( schedule != SCHED_NONE )\n\t\t\treturn schedule;\n\t}\n\n\tCheckAndCleanupOnExit();\n\treturn iBase;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::ActBusyNodeStillActive( void )\n{\n\tif ( !GetHintNode() )\n\t\treturn false;\n\t\n\treturn ( GetHintNode()->IsDisabled() == false );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Output : Returns true on success, false on failure.\n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::IsInterruptable( void )\n{\n\tif ( IsActive() )\n\t\treturn false;\n\n\treturn BaseClass::IsInterruptable();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Output : Returns true on success, false on failure.\n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::CanFlinch( void )\n{\n\tif ( m_bNeedsToPlayExitAnim )\n\t\treturn false;\n\n\treturn BaseClass::CanFlinch();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::CanRunAScriptedNPCInteraction( bool bForced )\n{\n\t\/\/ Prevent interactions during actbusy modes\n\tif ( IsActive() )\n\t\treturn false;\n\n\treturn BaseClass::CanRunAScriptedNPCInteraction( bForced );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::OnScheduleChange()\n{\n\tif( IsCurSchedule(SCHED_ACTBUSY_BUSY, false) )\n\t{\n\t\tif( HasCondition(COND_SEE_ENEMY) )\n\t\t{\n\t\t\tm_bExitedBusyToDueSeeEnemy = true;\n\t\t}\n\n\t\tif( HasCondition(COND_ACTBUSY_LOST_SEE_ENTITY) )\n\t\t{\n\t\t\tm_bExitedBusyToDueLostSeeEntity = true;\n\t\t}\n\t}\n\n\tBaseClass::OnScheduleChange();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::QueryHearSound( CSound *pSound )\n{\n\t\/\/ Ignore friendly created combat sounds while in an actbusy.\n\t\/\/ Fixes friendly NPCs going in & out of actbusies when the \n\t\/\/ player fires shots at their feet.\n\tif ( pSound->IsSoundType( SOUND_COMBAT ) || pSound->IsSoundType( SOUND_BULLET_IMPACT ) )\n\t{\n\t\tif ( GetOuter()->IRelationType( pSound->m_hOwner ) == D_LI )\n\t\t\treturn false;\n\t}\n\n\treturn BaseClass::QueryHearSound( pSound );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Because none of the startbusy schedules break on COND_NEW_ENEMY\n\/\/\t\t\twe have to do this distance check against all enemy NPCs we\n\/\/\t\t\tsee as we're traveling to an ACTBUSY node\n\/\/-----------------------------------------------------------------------------\n#define ACTBUSY_ENEMY_TOO_CLOSE_DIST_SQR\tSquare(240)\t\/\/ 20 feet\nvoid CAI_ActBusyBehavior::OnSeeEntity( CBaseEntity *pEntity )\n{\n\tBaseClass::OnSeeEntity( pEntity );\n\n\tif( IsCombatActBusy() && GetOuter()->IRelationType(pEntity) < D_LI )\n\t{\n\t\tif( pEntity->GetAbsOrigin().DistToSqr( GetAbsOrigin() ) <= ACTBUSY_ENEMY_TOO_CLOSE_DIST_SQR )\n\t\t{\n\t\t\tSetCondition( COND_ACTBUSY_ENEMY_TOO_CLOSE );\n\t\t}\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Output : Returns true on success, false on failure.\n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::ShouldPlayerAvoid( void )\n{\n\tif( IsCombatActBusy() )\n\t{\n\t\t\/\/ Alyx is only allowed to push if she's getting into or out of an actbusy\n\t\t\/\/ animation. She isn't allowed to shove you around while she's running around\n\t\tif ( IsCurSchedule(SCHED_ACTBUSY_START_BUSYING) )\n\t\t{\n\t\t\tif ( GetCurTask() && GetCurTask()->iTask == TASK_ACTBUSY_PLAY_ENTRY )\n\t\t\t\treturn true;\n\t\t}\n\t\telse if ( IsCurSchedule(SCHED_ACTBUSY_STOP_BUSYING) )\n\t\t{\n\t\t\tif ( GetCurTask() && GetCurTask()->iTask == TASK_ACTBUSY_PLAY_EXIT )\n\t\t\t\treturn true;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif ( IsCurSchedule ( SCHED_ACTBUSY_START_BUSYING ) )\n\t\t{\n\t\t\tif ( ( GetCurTask() && GetCurTask()->iTask == TASK_WAIT_FOR_MOVEMENT ) || GetOuter()->GetTask()->iTask == TASK_ACTBUSY_PLAY_ENTRY )\n\t\t\t\treturn true;\n\t\t}\n\t\telse if ( IsCurSchedule(SCHED_ACTBUSY_STOP_BUSYING) )\n\t\t{\n\t\t\tif ( GetCurTask() && GetCurTask()->iTask == TASK_ACTBUSY_PLAY_EXIT )\n\t\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn BaseClass::ShouldPlayerAvoid();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::ComputeAndSetRenderBounds()\n{\n\tVector mins, maxs;\n\tif ( GetOuter()->ComputeHitboxSurroundingBox( &mins, &maxs ) )\n\t{\n\t\tUTIL_SetSize( GetOuter(), mins - GetAbsOrigin(), maxs - GetAbsOrigin());\n\t\tif ( GetOuter()->VPhysicsGetObject() )\n\t\t{\n\t\t\tGetOuter()->SetupVPhysicsHull();\n\t\t}\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Returns true if the current NPC is acting busy, or moving to an actbusy\n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::IsActive( void )\n{\n\treturn ( m_bBusy || m_bForceActBusy || m_bNeedsToPlayExitAnim || m_bLeaving );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::IsCombatActBusy()\n{\n\tif( m_hActBusyGoal != NULL )\n\t\treturn (m_hActBusyGoal->GetType() == ACTBUSY_TYPE_COMBAT);\n\n\treturn false;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::CollectSafeZoneVolumes( CAI_ActBusyGoal *pActBusyGoal )\n{\n\t\/\/ Reset these, so we don't use a volume from a previous actbusy goal.\n\tm_SafeZones.RemoveAll();\n\n\tif( pActBusyGoal->m_iszSafeZoneVolume != NULL_STRING )\n\t{\n\t\tCBaseEntity *pVolume = gEntList.FindEntityByName( NULL, pActBusyGoal->m_iszSafeZoneVolume );\n\n\t\twhile( pVolume != NULL )\n\t\t{\n\t\t\tbusysafezone_t newSafeZone;\n\t\t\tpVolume->CollisionProp()->WorldSpaceAABB( &newSafeZone.vecMins, &newSafeZone.vecMaxs );\n\t\t\tm_SafeZones.AddToTail( newSafeZone );\n\t\t\tpVolume = gEntList.FindEntityByName( pVolume, pActBusyGoal->m_iszSafeZoneVolume );\n\t\t}\n\t}\n\n\tif( ai_debug_actbusy.GetInt() == 5 )\n\t{\n\t\tMsg( \"Actbusy collected %d safe zones\\n\", m_SafeZones.Count() );\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::IsInSafeZone( CBaseEntity *pEntity )\n{\n\tVector vecLocation = pEntity->WorldSpaceCenter();\n\n\tfor( int i = 0 ; i < m_SafeZones.Count() ; i++ )\n\t{\n\t\tbusysafezone_t *pSafeZone = &m_SafeZones[i];\n\n\t\tif( vecLocation.x > pSafeZone->vecMins.x\t\t&&\n\t\t\tvecLocation.y > pSafeZone->vecMins.y\t\t&&\n\t\t\tvecLocation.z > pSafeZone->vecMins.z\t\t&&\n\n\t\t\tvecLocation.x < pSafeZone->vecMaxs.x\t\t&&\n\t\t\tvecLocation.y < pSafeZone->vecMaxs.y\t\t&&\n\t\t\tvecLocation.z < pSafeZone->vecMaxs.z\t)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Return true if this NPC has the anims required to use the specified actbusy hint\n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::HasAnimForActBusy( int iActBusy, busyanimparts_t AnimPart )\n{\n\tif ( iActBusy == -1 )\n\t\treturn false;\n\n\tbusyanim_t *pBusyAnim = g_ActBusyAnimDataSystem.GetBusyAnim( iActBusy );\n\tif ( !pBusyAnim )\n\t\treturn false;\n\n\t\/\/ Try and play the sequence first\n\tif ( pBusyAnim->iszSequences[AnimPart] != NULL_STRING )\n\t\treturn (GetOuter()->LookupSequence( (char*)STRING(pBusyAnim->iszSequences[AnimPart]) ) != ACTIVITY_NOT_AVAILABLE);\n\n\t\/\/ Try and play the activity second\n\tif ( pBusyAnim->iActivities[AnimPart] != ACT_INVALID )\n\t\treturn GetOuter()->HaveSequenceForActivity( pBusyAnim->iActivities[AnimPart] );\n\n\treturn false;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Play the sound associated with the specified part of the current actbusy, if any\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::PlaySoundForActBusy( busyanimparts_t AnimPart )\n{\n\tbusyanim_t *pBusyAnim = g_ActBusyAnimDataSystem.GetBusyAnim( m_iCurrentBusyAnim );\n\tif ( !pBusyAnim )\n\t\treturn;\n\n\t\/\/ Play the sound\n\tif ( pBusyAnim->iszSounds[AnimPart] != NULL_STRING )\n\t{\n\t\t\/\/ See if we can treat it as a game sound name\n\t\tCSoundParameters params;\n\t\tif ( GetOuter()->GetParametersForSound( STRING(pBusyAnim->iszSounds[AnimPart]), params, STRING(GetOuter()->GetModelName()) ) )\n\t\t{\n\t\t\tCPASAttenuationFilter filter( GetOuter() );\n\t\t\tGetOuter()->EmitSound( filter, GetOuter()->entindex(), params );\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Assume it's a response concept, and try to speak it\n\t\t\tCAI_Expresser *pExpresser = GetOuter()->GetExpresser();\n\t\t\tif ( pExpresser )\n\t\t\t{\n\t\t\t\tconst char *concept = STRING(pBusyAnim->iszSounds[AnimPart]);\n\n\t\t\t\t\/\/ Must be able to speak the concept\n\t\t\t\tif ( !pExpresser->IsSpeaking() && pExpresser->CanSpeakConcept( concept ) )\n\t\t\t\t{\n\t\t\t\t\tpExpresser->Speak( concept );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Play a sequence or activity for the current actbusy\n\/\/-----------------------------------------------------------------------------\nbool CAI_ActBusyBehavior::PlayAnimForActBusy( busyanimparts_t AnimPart )\n{\n\tbusyanim_t *pBusyAnim = g_ActBusyAnimDataSystem.GetBusyAnim( m_iCurrentBusyAnim );\n\tif ( !pBusyAnim )\n\t\treturn false;\n\n\t\/\/ Try and play the sequence first\n\tif ( pBusyAnim->iszSequences[AnimPart] != NULL_STRING )\n\t{\n\t\tGetOuter()->SetSequenceByName( (char*)STRING(pBusyAnim->iszSequences[AnimPart]) );\n\t\tGetOuter()->SetIdealActivity( ACT_DO_NOT_DISTURB );\n\t\treturn true;\n\t}\n\n\t\/\/ Try and play the activity second\n\tif ( pBusyAnim->iActivities[AnimPart] != ACT_INVALID )\n\t{\n\t\tGetOuter()->SetIdealActivity( pBusyAnim->iActivities[AnimPart] );\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::StartTask( const Task_t *pTask )\n{\n\tswitch ( pTask->iTask )\n\t{\n\tcase TASK_ACTBUSY_PLAY_BUSY_ANIM:\n\t\t{\n\t\t\t\/\/ If we're not enabled here, it's due to the actbusy being deactivated during\n\t\t\t\/\/ the NPC's entry animation. We can't abort in the middle of the entry, so we\n\t\t\t\/\/ arrive here with a disabled actbusy behaviour. Exit gracefully.\n\t\t\tif ( !m_bEnabled )\n\t\t\t{\n\t\t\t\tTaskComplete();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ Set the flag to remind the code to recompute the NPC's box from render bounds.\n\t\t\t\/\/ This is used to delay the process so that we don't get a box built from render bounds\n\t\t\t\/\/ when a character is still interpolating to their busy pose.\n\t\t\tm_bNeedToSetBounds = true;\n\n\t\t\t\/\/ Get the busyanim for the specified activity\n\t\t\tbusyanim_t *pBusyAnim = g_ActBusyAnimDataSystem.GetBusyAnim( m_iCurrentBusyAnim );\n\n\t\t\t\/\/ We start \"flying\" so we don't collide with the world, in case the level\n\t\t\t\/\/ designer has us sitting on a chair, etc.\n\t\t\tif( !pBusyAnim || !pBusyAnim->bUseAutomovement )\n\t\t\t{\n\t\t\t\tGetOuter()->AddFlag( FL_FLY );\n\t\t\t}\n\n\t\t\tGetOuter()->SetGroundEntity( NULL );\n\n\t\t\t\/\/ Fail if we're not on the node & facing the correct way\n\t\t\t\/\/ We only do this check if we're still moving to the busy. This will only\n\t\t\t\/\/ be true if there was no entry animation for this busy. We do it this way\n\t\t\t\/\/ because the entry code contains this same check, and so we assume we're\n\t\t\t\/\/ valid even if we're off now, because some entry animations move the \n\t\t\t\/\/ character off the node.\n\t\t\tif ( m_bMovingToBusy )\n\t\t\t{\n\t\t\t\tif ( UTIL_DistApprox( GetHintNode()->GetAbsOrigin(), GetAbsOrigin() ) > 16 || !GetOuter()->FacingIdeal() )\n\t\t\t\t{\n\t\t\t\t\tTaskFail( \"Not correctly on hintnode\" );\n\t\t\t\t\tm_flEndBusyAt = gpGlobals->curtime;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm_bMovingToBusy = false;\n\n\t\t\tif ( !ActBusyNodeStillActive() )\n\t\t\t{\n\t\t\t\tTaskFail( FAIL_NO_HINT_NODE );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ Have we just started using this node?\n\t\t\tif ( !m_bBusy )\n\t\t\t{\n\t\t\t\tm_bBusy = true;\n\n\t\t\t\tGetHintNode()->NPCStartedUsing( GetOuter() );\n\t\t\t\tif ( m_hActBusyGoal )\n\t\t\t\t{\n\t\t\t\t\tm_hActBusyGoal->NPCStartedBusy( GetOuter() );\n\t\t\t\t}\n\n\t\t\t\tif ( pBusyAnim )\n\t\t\t\t{\n\t\t\t\t\tfloat flMaxTime = pBusyAnim->flMaxTime;\n\t\t\t\t\tfloat flMinTime = pBusyAnim->flMinTime;\n\n\t\t\t\t\t\/\/ Mapmaker input may have specified it's own max time\n\t\t\t\t\tif ( m_bForceActBusy && m_flForcedMaxTime != NO_MAX_TIME )\n\t\t\t\t\t{\n\t\t\t\t\t\tflMaxTime = m_flForcedMaxTime;\n\n\t\t\t\t\t\t\/\/ Don't let non-unlimited time amounts be less than the mintime\n\t\t\t\t\t\tif ( flMaxTime && flMaxTime < flMinTime )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tflMinTime = flMaxTime;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ If we have no max time, or we're in a queue, we loop forever.\n\t\t\t\t\tif ( !flMaxTime || m_bInQueue )\n\t\t\t\t\t{\n\t\t\t\t\t\tm_flEndBusyAt = 0;\n\t\t\t\t\t\tGetOuter()->SetWait( 99999 );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat flTime = RandomFloat(flMinTime, flMaxTime);\n\t\t\t\t\t\tm_flEndBusyAt = gpGlobals->curtime + flTime;\n\t\t\t\t\t\tGetOuter()->SetWait( flTime );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Start playing the act busy\n\t\t\tPlayAnimForActBusy( BA_BUSY );\n\t\t\tPlaySoundForActBusy( BA_BUSY );\n\n\t\t\t\/\/ Now that we're busy, we don't need to be forced anymore\n\t\t\tm_bForceActBusy = false;\n\t\t\tm_bTeleportToBusy = false;\n\t\t\tm_bUseNearestBusy = false;\n\t\t\tm_ForcedActivity = ACT_INVALID;\n\n\t\t\t\/\/ If we're supposed to use render bounds while inside the busy anim, do so\n\t\t\tif ( m_bUseRenderBoundsForCollision )\n\t\t\t{\n\t\t\t\tComputeAndSetRenderBounds();\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase TASK_ACTBUSY_PLAY_ENTRY:\n\t\t{\n\t\t\t\/\/ We start \"flying\" so we don't collide with the world, in case the level\n\t\t\t\/\/ designer has us sitting on a chair, etc.\n\n\t\t\t\/\/ Get the busyanim for the specified activity\n\t\t\tbusyanim_t *pBusyAnim = g_ActBusyAnimDataSystem.GetBusyAnim( m_iCurrentBusyAnim );\n\n\t\t\t\/\/ We start \"flying\" so we don't collide with the world, in case the level\n\t\t\t\/\/ designer has us sitting on a chair, etc.\n\t\t\tif( !pBusyAnim || !pBusyAnim->bUseAutomovement )\n\t\t\t{\n\t\t\t\tGetOuter()->AddFlag( FL_FLY );\n\t\t\t}\n\n\t\t\tGetOuter()->SetGroundEntity( NULL );\n\n\t\t\tm_bMovingToBusy = false;\n\t\t\tm_bNeedsToPlayExitAnim = HasAnimForActBusy( m_iCurrentBusyAnim, BA_EXIT );\n\n\t\t\tif ( !ActBusyNodeStillActive() )\n\t\t\t{\n\t\t\t\tTaskFail( FAIL_NO_HINT_NODE );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ Fail if we're not on the node & facing the correct way\n\t\t\tif ( UTIL_DistApprox( GetHintNode()->GetAbsOrigin(), GetAbsOrigin() ) > 16 || !GetOuter()->FacingIdeal() )\n\t\t\t{\n\t\t\t\tm_bBusy = false;\n\t\t\t\tTaskFail( \"Not correctly on hintnode\" );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tPlaySoundForActBusy( BA_ENTRY );\n\n\t\t\t\/\/ Play the entry animation. If it fails, we don't have an entry anim, so complete immediately.\n\t\t\tif ( !PlayAnimForActBusy( BA_ENTRY ) )\n\t\t\t{\n\t\t\t\tTaskComplete();\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase TASK_ACTBUSY_VERIFY_EXIT:\n\t\t{\n\t\t\t\/\/ NPC's that changed their bounding box must ensure that they can restore their regular box\n\t\t\t\/\/ before they exit their actbusy. This task is designed to delay until that time if necessary.\n\t\t\tif( !m_bUseRenderBoundsForCollision )\n\t\t\t{\n\t\t\t\t\/\/ Don't bother if we didn't alter our BBox. \n\t\t\t\tTaskComplete();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ Set up a timer to check immediately.\n\t\t\tGetOuter()->SetWait( 0 );\t\t\t\n\t\t}\n\t\tbreak;\n\n\tcase TASK_ACTBUSY_PLAY_EXIT:\n\t\t{\n\t\t\t\/\/ If we're supposed to use render bounds while inside the busy anim, restore normal now\n\t\t\tif ( m_bUseRenderBoundsForCollision )\n\t\t\t{\n\t\t\t\tGetOuter()->SetHullSizeNormal( true );\n\t\t\t}\n\n\t\t\tif ( m_hActBusyGoal )\n\t\t\t{\n\t\t\t\tm_hActBusyGoal->NPCStartedLeavingBusy( GetOuter() );\n\t\t\t}\n\n\t\t\tPlaySoundForActBusy( BA_EXIT );\n\n\t\t\t\/\/ Play the exit animation. If it fails, we don't have an entry anim, so complete immediately.\n\t\t\tif ( !PlayAnimForActBusy( BA_EXIT ) )\n\t\t\t{\n\t\t\t\tm_bNeedsToPlayExitAnim = false;\n\t\t\t\tGetOuter()->RemoveFlag( FL_FLY );\n\t\t\t\tNotifyBusyEnding();\n\t\t\t\tTaskComplete();\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase TASK_ACTBUSY_TELEPORT_TO_BUSY:\n\t\t{\n\t\t\tif ( !ActBusyNodeStillActive() )\n\t\t\t{\n\t\t\t\tTaskFail( FAIL_NO_HINT_NODE );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tVector vecAbsOrigin = GetHintNode()->GetAbsOrigin();\n\t\t\tQAngle vecAbsAngles = GetHintNode()->GetAbsAngles();\n\t\t\tGetOuter()->Teleport( &vecAbsOrigin, &vecAbsAngles, NULL );\n\t\t\tGetOuter()->GetMotor()->SetIdealYaw( vecAbsAngles.y );\n\n\t\t\tTaskComplete();\n\t\t}\n\t\tbreak;\n\n\tcase TASK_ACTBUSY_WALK_PATH_TO_BUSY:\n\t\t{\n\t\t\t\/\/ If we have a forced activity, use that. Otherwise, walk.\n\t\t\tif ( m_ForcedActivity != ACT_INVALID && m_ForcedActivity != ACT_RESET )\n\t\t\t{\n\t\t\t\tGetNavigator()->SetMovementActivity( m_ForcedActivity );\n\n\t\t\t\t\/\/ Cover is void once I move\n\t\t\t\tForget( bits_MEMORY_INCOVER );\n\n\t\t\t\tTaskComplete();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif( IsCombatActBusy() )\n\t\t\t\t{\n\t\t\t\t\tChainStartTask( TASK_RUN_PATH );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tChainStartTask( TASK_WALK_PATH );\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\tcase TASK_ACTBUSY_GET_PATH_TO_ACTBUSY:\n\t\t{\n\t\t\tChainStartTask( TASK_GET_PATH_TO_HINTNODE );\n\n\t\t\tif ( !HasCondition(COND_TASK_FAILED) )\n\t\t\t{\n\t\t\t\t\/\/ We successfully built a path, so stop counting consecutive failures.\n\t\t\t\tm_iNumConsecutivePathFailures = 0;\n\n\t\t\t\t\/\/ Set the arrival sequence for the actbusy to be the busy sequence, if we don't have an entry animation\n\t\t\t\tbusyanim_t *pBusyAnim = g_ActBusyAnimDataSystem.GetBusyAnim( m_iCurrentBusyAnim );\n\t\t\t\tif ( pBusyAnim && pBusyAnim->iszSequences[BA_ENTRY] == NULL_STRING && pBusyAnim->iActivities[BA_ENTRY] == ACT_INVALID )\n\t\t\t\t{\n\t\t\t\t\t\/\/ Try and play the sequence first\n\t\t\t\t\tif ( pBusyAnim->iszSequences[BA_BUSY] != NULL_STRING )\n\t\t\t\t\t{\n\t\t\t\t\t\tGetNavigator()->SetArrivalSequence( GetOuter()->LookupSequence( STRING(pBusyAnim->iszSequences[BA_BUSY]) ) );\n\t\t\t\t\t}\n\t\t\t\t\telse if ( pBusyAnim->iActivities[BA_BUSY] != ACT_INVALID )\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Try and play the activity second\n\t\t\t\t\t\tGetNavigator()->SetArrivalActivity( pBusyAnim->iActivities[BA_BUSY] );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ Robin: Set the arrival sequence \/ activity to be the entry animation.\n\t\t\t\t\tif ( pBusyAnim->iszSequences[BA_ENTRY] != NULL_STRING )\n\t\t\t\t\t{\n\t\t\t\t\t\tGetNavigator()->SetArrivalSequence( GetOuter()->LookupSequence( STRING(pBusyAnim->iszSequences[BA_ENTRY]) ) );\n\t\t\t\t\t}\n\t\t\t\t\telse if ( pBusyAnim->iActivities[BA_ENTRY] != ACT_INVALID )\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Try and play the activity second\n\t\t\t\t\t\tGetNavigator()->SetArrivalActivity( pBusyAnim->iActivities[BA_ENTRY] );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_iNumConsecutivePathFailures++;\n\n\t\t\t\tif ( ai_debug_actbusy.GetInt() == 1 )\n\t\t\t\t{\n\t\t\t\t\tif ( GetHintNode() )\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Show which actbusy we're moving towards\n\t\t\t\t\t\tNDebugOverlay::Line( GetOuter()->WorldSpaceCenter(), GetHintNode()->GetAbsOrigin(), 255, 0, 0, true, 1.0 );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\n\tdefault:\n\t\tBaseClass::StartTask( pTask);\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::RunTask( const Task_t *pTask )\t\t\n{ \n\tswitch ( pTask->iTask )\n\t{\n\tcase TASK_WAIT_FOR_MOVEMENT:\n\t\t{\n\t\t\t\/\/ Ensure the hint node hasn't been disabled\n\t\t\tif ( IsCurSchedule( SCHED_ACTBUSY_START_BUSYING ) )\n\t\t\t{\n\t\t\t\tif ( !ActBusyNodeStillActive() )\n\t\t\t\t{\n\t\t\t\t\tTaskFail(FAIL_NO_HINT_NODE);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( ai_debug_actbusy.GetInt() == 1 )\n\t\t\t{\n\t\t\t\tif ( GetHintNode() )\n\t\t\t\t{\n\t\t\t\t\t\/\/ Show which actbusy we're moving towards\n\t\t\t\t\tNDebugOverlay::Line( GetOuter()->WorldSpaceCenter(), GetHintNode()->GetAbsOrigin(), 0, 255, 0, true, 0.2 );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tBaseClass::RunTask( pTask );\n\t\t\tbreak;\n\t\t}\n\n\tcase TASK_ACTBUSY_PLAY_BUSY_ANIM:\n\t\t{\n\t\t\tif( m_bUseRenderBoundsForCollision )\n\t\t\t{\n\t\t\t\tif( GetOuter()->IsSequenceFinished() && m_bNeedToSetBounds )\n\t\t\t\t{\n\t\t\t\t\tComputeAndSetRenderBounds();\n\t\t\t\t\tm_bNeedToSetBounds = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif( IsCombatActBusy() )\n\t\t\t{\n\t\t\t\tif( GetEnemy() != NULL && !HasCondition(COND_ENEMY_OCCLUDED) )\n\t\t\t\t{\n\t\t\t\t\t\/\/ Break a combat actbusy if an enemy gets very close.\n\t\t\t\t\t\/\/ I'll probably go to hell for not doing this with conditions like I should. (sjb)\n\t\t\t\t\tfloat flDistSqr = GetAbsOrigin().DistToSqr( GetEnemy()->GetAbsOrigin() );\n\n\t\t\t\t\tif( flDistSqr < Square(12.0f * 15.0f) )\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ End now.\n\t\t\t\t\t\tm_flEndBusyAt = gpGlobals->curtime;\n\t\t\t\t\t\tTaskComplete();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tGetOuter()->AutoMovement();\n\t\t\t\/\/ Stop if the node's been disabled\n\t\t\tif ( !ActBusyNodeStillActive() || GetOuter()->IsWaitFinished() )\n\t\t\t{\n\t\t\t\tTaskComplete();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCAI_PlayerAlly *pAlly = dynamic_cast<CAI_PlayerAlly*>(GetOuter());\n\t\t\t\tif ( pAlly )\n\t\t\t\t{\n\t\t\t\t\tpAlly->SelectInterjection();\n\t\t\t\t}\n\n\t\t\t\tif( HasCondition(COND_ACTBUSY_LOST_SEE_ENTITY) )\n\t\t\t\t{\n\t\t\t\t\tStopBusying();\n\t\t\t\t\tTaskComplete();\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\tcase TASK_ACTBUSY_PLAY_ENTRY:\n\t\t{\n\t\t\tGetOuter()->AutoMovement();\n\t\t\tif ( !ActBusyNodeStillActive() || GetOuter()->IsSequenceFinished() )\n\t\t\t{\n\t\t\t\tTaskComplete();\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase TASK_ACTBUSY_VERIFY_EXIT:\n\t\t{\n\t\t\tif( GetOuter()->IsWaitFinished() )\n\t\t\t{\n\t\t\t\t\/\/ Trace my normal hull over this spot to see if I'm able to stand up right now.\n\t\t\t\ttrace_t tr;\n\t\t\t\tCTraceFilterOnlyNPCsAndPlayer filter( GetOuter(), COLLISION_GROUP_NONE );\n\t\t\t\tUTIL_TraceHull( GetOuter()->GetAbsOrigin(), GetOuter()->GetAbsOrigin(), NAI_Hull::Mins( HULL_HUMAN ), NAI_Hull::Maxs( HULL_HUMAN ), MASK_NPCSOLID, &filter, &tr );\n\n\t\t\t\tif( tr.startsolid )\n\t\t\t\t{\n\t\t\t\t\t\/\/ Blocked. Try again later.\n\t\t\t\t\tGetOuter()->SetWait( 1.0f );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ Put an entity blocker here for a moment until I get into my bounding box.\n\t\t\t\t\tCBaseEntity *pBlocker = CEntityBlocker::Create( GetOuter()->GetAbsOrigin(), NAI_Hull::Mins( HULL_HUMAN ), NAI_Hull::Maxs( HULL_HUMAN ), GetOuter(), true );\n\t\t\t\t\tg_EventQueue.AddEvent( pBlocker, \"Kill\", 1.0, GetOuter(), GetOuter() );\n\t\t\t\t\tTaskComplete();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase TASK_ACTBUSY_PLAY_EXIT:\n\t\t{\n\t\t\tGetOuter()->AutoMovement();\n\t\t\tif ( GetOuter()->IsSequenceFinished() )\n\t\t\t{\n\t\t\t\tm_bNeedsToPlayExitAnim = false;\n\t\t\t\tGetOuter()->RemoveFlag( FL_FLY );\n\t\t\t\tNotifyBusyEnding();\n\t\t\t\tTaskComplete();\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tBaseClass::RunTask( pTask);\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyBehavior::NotifyBusyEnding( void )\n{\n\t\/\/ Be sure to disable autofire\n\tm_bAutoFireWeapon = false;\n\n\t\/\/ Clear the hintnode if we're done with it\n\tif ( GetHintNode() )\n\t{\n\t\tif ( m_bBusy || m_bMovingToBusy )\n\t\t{\n\t\t\tGetHintNode()->NPCStoppedUsing( GetOuter() );\n\t\t}\n\n\t\tGetHintNode()->Unlock();\n\n\t\tif( IsCombatActBusy() )\n\t\t{\n\t\t\t\/\/ Don't allow anyone to use this node for a bit. This is so the tactical position\n\t\t\t\/\/ doesn't get re-occupied the moment I leave it.\n\t\t\tGetHintNode()->DisableForSeconds( random->RandomFloat( 10, 15) );\n\t\t}\n\n\t\tSetHintNode( NULL );\n\t}\n\n\t\/\/ Then, if we were busy, stop being busy\n \tif ( m_bBusy )\n\t{\n\t\tm_bBusy = false;\n\n\t\tif ( m_hActBusyGoal )\n\t\t{\n\t\t\tm_hActBusyGoal->NPCFinishedBusy( GetOuter() );\n\n\t\t\tif ( m_bExitedBusyToDueLostSeeEntity )\n\t\t\t{\n\t\t\t\tm_hActBusyGoal->NPCLostSeeEntity( GetOuter() );\n\t\t\t\tm_bExitedBusyToDueLostSeeEntity = false;\n\t\t\t}\n\n\t\t\tif ( m_bExitedBusyToDueSeeEnemy )\n\t\t\t{\n\t\t\t\tm_hActBusyGoal->NPCSeeEnemy( GetOuter() );\n\t\t\t\tm_bExitedBusyToDueSeeEnemy = false;\n\t\t\t}\n\t\t}\n\t}\n\telse if ( m_bMovingToBusy && m_hActBusyGoal )\n\t{\n\t\t\/\/ Or if we were just on our way to be busy, let the goal know\n\t\tm_hActBusyGoal->NPCAbortedMoveTo( GetOuter() );\n\t}\n\n\t\/\/ Don't busy again for a while\n\tm_flEndBusyAt = 0;\n\n\tif( IsCombatActBusy() )\n\t{\n\t\t\/\/ Actbusy again soon. Real soon.\n\t\tm_flNextBusySearchTime = gpGlobals->curtime;\n\t}\n\telse\n\t{\n\t\tm_flNextBusySearchTime = gpGlobals->curtime + (RandomFloat(ai_actbusy_search_time.GetFloat(), ai_actbusy_search_time.GetFloat()*2));\n\t}\n}\n\n\/\/-------------------------------------\n\nAI_BEGIN_CUSTOM_SCHEDULE_PROVIDER( CAI_ActBusyBehavior )\n\n\tDECLARE_CONDITION( COND_ACTBUSY_LOST_SEE_ENTITY )\n\tDECLARE_CONDITION( COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE )\n\tDECLARE_CONDITION( COND_ACTBUSY_ENEMY_TOO_CLOSE )\n\n\tDECLARE_TASK( TASK_ACTBUSY_PLAY_BUSY_ANIM )\n\tDECLARE_TASK( TASK_ACTBUSY_PLAY_ENTRY )\n\tDECLARE_TASK( TASK_ACTBUSY_PLAY_EXIT )\n\tDECLARE_TASK( TASK_ACTBUSY_TELEPORT_TO_BUSY )\n\tDECLARE_TASK( TASK_ACTBUSY_WALK_PATH_TO_BUSY )\n\tDECLARE_TASK( TASK_ACTBUSY_GET_PATH_TO_ACTBUSY )\n\tDECLARE_TASK( TASK_ACTBUSY_VERIFY_EXIT )\n\n\tDECLARE_ANIMEVENT( AE_ACTBUSY_WEAPON_FIRE_ON )\n\tDECLARE_ANIMEVENT( AE_ACTBUSY_WEAPON_FIRE_OFF )\n\n\t\/\/---------------------------------\n\n\tDEFINE_SCHEDULE\n\t( \n\t\tSCHED_ACTBUSY_START_BUSYING,\n\n\t\t\"\tTasks\"\n\t\t\"\t\tTASK_SET_TOLERANCE_DISTANCE\t\t\t4\"\n\t\t\"\t\tTASK_ACTBUSY_GET_PATH_TO_ACTBUSY\t0\"\n\t\t\"\t\tTASK_ACTBUSY_WALK_PATH_TO_BUSY\t\t0\"\n\t\t\"\t\tTASK_WAIT_FOR_MOVEMENT\t\t\t\t0\"\n\t\t\"\t\tTASK_STOP_MOVING\t\t\t\t\t0\"\n\t\t\"\t\tTASK_FACE_HINTNODE\t\t\t\t\t0\"\n\t\t\"\t\tTASK_ACTBUSY_PLAY_ENTRY\t\t\t\t0\"\n\t\t\"\t\tTASK_SET_SCHEDULE\t\t\t\t\tSCHEDULE:SCHED_ACTBUSY_BUSY\"\n\t\t\"\"\n\t\t\"\tInterrupts\"\n\t\t\"\t\tCOND_ACTBUSY_LOST_SEE_ENTITY\"\n\t)\n\n\tDEFINE_SCHEDULE\n\t( \n\t\tSCHED_ACTBUSY_BUSY,\n\n\t\t\"\tTasks\"\n\t\t\"\t\tTASK_ACTBUSY_PLAY_BUSY_ANIM\t\t0\"\n\t\t\"\"\n\t\t\"\tInterrupts\"\n\t\t\"\t\tCOND_PROVOKED\"\n\t)\n\n\tDEFINE_SCHEDULE\n\t( \n\t\tSCHED_ACTBUSY_STOP_BUSYING,\n\n\t\t\"\tTasks\"\n\t\t\"\t\tTASK_ACTBUSY_VERIFY_EXIT\t\t0\"\n\t\t\"\t\tTASK_ACTBUSY_PLAY_EXIT\t\t\t0\"\n\t\t\"\t\tTASK_WAIT\t\t\t\t\t\t0.1\"\n\t\t\"\"\n\t\t\"\tInterrupts\"\n\t\t\"\t\tCOND_NO_CUSTOM_INTERRUPTS\"\n\t)\n\n\tDEFINE_SCHEDULE\n\t( \n\t\tSCHED_ACTBUSY_LEAVE,\n\n\t\t\"\tTasks\"\n\t\t\"\t\tTASK_SET_TOLERANCE_DISTANCE\t\t\t4\"\n\t\t\"\t\tTASK_ACTBUSY_GET_PATH_TO_ACTBUSY\t0\"\n\t\t\"\t\tTASK_ACTBUSY_WALK_PATH_TO_BUSY\t\t0\"\n\t\t\"\t\tTASK_WAIT_FOR_MOVEMENT\t\t\t\t0\"\n\t\t\"\"\n\t\t\"\tInterrupts\"\n\t\t\"\t\tCOND_PROVOKED\"\n\t)\n\n\tDEFINE_SCHEDULE\n\t( \n\t\tSCHED_ACTBUSY_TELEPORT_TO_BUSY,\n\n\t\t\"\tTasks\"\n\t\t\"\t\tTASK_ACTBUSY_TELEPORT_TO_BUSY\t0\"\n\t\t\"\t\tTASK_ACTBUSY_PLAY_ENTRY\t\t\t0\"\n\t\t\"\t\tTASK_SET_SCHEDULE\t\t\t\tSCHEDULE:SCHED_ACTBUSY_BUSY\"\n\t\t\"\"\n\t\t\"\tInterrupts\"\n\t\t\"\t\tCOND_PROVOKED\"\n\t)\n\nAI_END_CUSTOM_SCHEDULE_PROVIDER()\n\n\n\/\/==========================================================================================================\n\/\/ ACT BUSY GOALS\n\/\/==========================================================================================================\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: A level tool to control the actbusy behavior.\n\/\/-----------------------------------------------------------------------------\nLINK_ENTITY_TO_CLASS( ai_goal_actbusy, CAI_ActBusyGoal );\n\nBEGIN_DATADESC( CAI_ActBusyGoal )\n\tDEFINE_KEYFIELD( m_flBusySearchRange, FIELD_FLOAT, \"busysearchrange\" ),\n\tDEFINE_KEYFIELD( m_bVisibleOnly, FIELD_BOOLEAN, \"visibleonly\" ),\n\tDEFINE_KEYFIELD( m_iType, FIELD_INTEGER, \"type\" ),\n\tDEFINE_KEYFIELD( m_bAllowCombatActBusyTeleport, FIELD_BOOLEAN, \"allowteleport\" ),\n\tDEFINE_KEYFIELD( m_iszSeeEntityName, FIELD_STRING, \"SeeEntity\" ),\n\tDEFINE_KEYFIELD( m_flSeeEntityTimeout, FIELD_FLOAT, \"SeeEntityTimeout\" ),\n\tDEFINE_KEYFIELD( m_iszSafeZoneVolume, FIELD_STRING, \"SafeZone\" ),\n\tDEFINE_KEYFIELD( m_iSightMethod, FIELD_INTEGER, \"sightmethod\" ),\n\n\t\/\/ Inputs\n\tDEFINE_INPUTFUNC( FIELD_FLOAT, \"SetBusySearchRange\", InputSetBusySearchRange ),\n\tDEFINE_INPUTFUNC( FIELD_STRING, \"ForceNPCToActBusy\", InputForceNPCToActBusy ),\n\tDEFINE_INPUTFUNC( FIELD_EHANDLE, \"ForceThisNPCToActBusy\", InputForceThisNPCToActBusy ),\n\tDEFINE_INPUTFUNC( FIELD_EHANDLE, \"ForceThisNPCToLeave\", InputForceThisNPCToLeave ),\n\n\t\/\/ Outputs\n\tDEFINE_OUTPUT( m_OnNPCStartedBusy, \"OnNPCStartedBusy\" ),\n\tDEFINE_OUTPUT( m_OnNPCFinishedBusy, \"OnNPCFinishedBusy\" ),\n\tDEFINE_OUTPUT( m_OnNPCLeft, \"OnNPCLeft\" ),\n\tDEFINE_OUTPUT( m_OnNPCLostSeeEntity, \"OnNPCLostSeeEntity\" ),\n\tDEFINE_OUTPUT( m_OnNPCSeeEnemy, \"OnNPCSeeEnemy\" ),\nEND_DATADESC()\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nCAI_ActBusyBehavior *CAI_ActBusyGoal::GetBusyBehaviorForNPC( CBaseEntity *pEntity, const char *sInputName )\n{\n\tCAI_BaseNPC *pActor = dynamic_cast<CAI_BaseNPC*>(pEntity);\n\tif ( !pActor )\n\t{\n\t\tMsg(\"ai_goal_actbusy input %s fired targeting an entity that isn't an NPC.\\n\", sInputName);\n\t\treturn NULL;\n\t}\n\n\t\/\/ Get the NPC's behavior\n\tCAI_ActBusyBehavior *pBehavior;\n\tif ( !pActor->GetBehavior( &pBehavior ) )\n\t{\n\t\tMsg(\"ai_goal_actbusy input %s fired on an NPC that doesn't support ActBusy behavior.\\n\", sInputName );\n\t\treturn NULL;\n\t}\n\n\treturn pBehavior;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nCAI_ActBusyBehavior *CAI_ActBusyGoal::GetBusyBehaviorForNPC( const char *pszActorName, CBaseEntity *pActivator, CBaseEntity *pCaller, const char *sInputName )\n{\n\tCBaseEntity *pEntity = gEntList.FindEntityByName( NULL, MAKE_STRING(pszActorName), NULL, pActivator, pCaller );\n\tif ( !pEntity )\n\t{\n\t\tMsg(\"ai_goal_actbusy input %s fired targeting a non-existant entity (%s).\\n\", sInputName, pszActorName );\n\t\treturn NULL;\n\t}\n\n\treturn GetBusyBehaviorForNPC( pEntity, sInputName );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : &inputdata - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::EnableGoal( CAI_BaseNPC *pAI )\n{\n\tBaseClass::EnableGoal( pAI );\n\n\t\/\/ Now use this actor to lookup the Behavior\n\tCAI_ActBusyBehavior *pBehavior;\n\tif ( pAI->GetBehavior( &pBehavior ) )\n\t{\n\t\t\/\/ Some NPCs may already be active due to a ForceActBusy input.\n\t\tif ( !pBehavior->IsEnabled() )\n\t\t{\n\t\t\tpBehavior->Enable( this, m_flBusySearchRange, m_bVisibleOnly );\n\t\t}\n\t}\n\telse\n\t{\n\t\tDevMsg( \"ActBusy goal entity activated for an NPC (%s) that doesn't have the ActBusy behavior\\n\", pAI->GetDebugName() );\n\t\treturn;\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : &inputdata - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::InputActivate( inputdata_t &inputdata )\n{\n\tif ( ai_debug_actbusy.GetInt() == 4 )\n\t{\n\t\tMsg(\"ACTBUSY: Actbusy goal %s (%s) activated.\\n\", GetClassname(), GetDebugName() );\n\t}\n\n\tBaseClass::InputActivate( inputdata );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : &inputdata - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::InputDeactivate( inputdata_t &inputdata )\n{\n\tif ( ai_debug_actbusy.GetInt() == 4 )\n\t{\n\t\tMsg(\"ACTBUSY: Actbusy goal %s (%s) disabled.\\n\", GetClassname(), GetDebugName() );\n\t}\n\n\tBaseClass::InputDeactivate( inputdata );\n\n\tfor( int i = 0 ; i < NumActors() ; i++ )\n\t{\n\t\tCAI_BaseNPC *pActor = GetActor( i );\n\n\t\tif ( pActor )\n\t\t{\n\t\t\t\/\/ Now use this actor to lookup the Behavior\n\t\t\tCAI_ActBusyBehavior *pBehavior;\n\t\t\tif ( pActor->GetBehavior( &pBehavior ) )\n\t\t\t{\n\t\t\t\tpBehavior->Disable();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tDevMsg( \"ActBusy goal entity deactivated for an NPC that doesn't have the ActBusy behavior\\n\" );\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::InputSetBusySearchRange( inputdata_t &inputdata )\n{\n\tm_flBusySearchRange = inputdata.value.Float();\n\n\tfor( int i = 0 ; i < NumActors() ; i++ )\n\t{\n\t\tCAI_BaseNPC *pActor = GetActor( i );\n\n\t\tif ( pActor )\n\t\t{\n\t\t\t\/\/ Now use this actor to lookup the Behavior\n\t\t\tCAI_ActBusyBehavior *pBehavior;\n\t\t\tif ( pActor->GetBehavior( &pBehavior ) )\n\t\t\t{\n\t\t\t\tpBehavior->SetBusySearchRange( m_flBusySearchRange );\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::InputForceNPCToActBusy( inputdata_t &inputdata )\n{\n\tchar parseString[255];\n\tQ_strncpy(parseString, inputdata.value.String(), sizeof(parseString));\n\n\tCAI_Hint *pHintNode = NULL;\n\tfloat flMaxTime = NO_MAX_TIME;\n\tbool bTeleport = false;\n\tbool bUseNearestBusy = false;\n\tCBaseEntity *pSeeEntity = NULL;\n\n\t\/\/ Get NPC name\n \tchar *pszParam = strtok(parseString,\" \");\n\tCAI_ActBusyBehavior *pBehavior = GetBusyBehaviorForNPC( pszParam, inputdata.pActivator, inputdata.pCaller, \"InputForceNPCToActBusy\" );\n\tif ( !pBehavior )\n\t\treturn;\n\n\t\/\/ Wrapped this bugfix so that it doesn't break HL2.\n\tbool bEpisodicBugFix = hl2_episodic.GetBool();\n\n\t\/\/ Do we have a specified node too?\n\tpszParam = strtok(NULL,\" \");\n\tif ( pszParam )\n\t{\t\n\t\t\/\/ Find the specified hintnode\n\t\tCBaseEntity *pEntity = gEntList.FindEntityByName( NULL, pszParam, NULL, inputdata.pActivator, inputdata.pCaller );\n\t\tif ( pEntity )\n\t\t{\n\t\t\tpHintNode = dynamic_cast<CAI_Hint*>(pEntity);\n\t\t\tif ( !pHintNode )\n\t\t\t{\n\t\t\t\tMsg(\"ai_goal_actbusy input ForceNPCToActBusy fired targeting an entity that isn't a hintnode.\\n\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif ( bEpisodicBugFix )\n\t\t\t{\n\t\t\t\tpszParam = strtok(NULL,\" \");\n\t\t\t}\n\t\t}\n\t}\n\n\tActivity activity = ACT_INVALID;\n\n\tif ( !bEpisodicBugFix )\n\t{\n \t\tpszParam = strtok(NULL,\" \");\n\t}\n\n\twhile ( pszParam )\n\t{\n\t\t\/\/ Teleport?\n \t\tif ( !Q_strncmp( pszParam, \"teleport\", 8 ) )\n\t\t{\n\t\t\tbTeleport = true;\n\t\t}\n\t\telse if ( !Q_strncmp( pszParam, \"nearest\", 8 ) )\n\t\t{\n\t\t\tbUseNearestBusy = true;\n\t\t}\n\t\telse if ( !Q_strncmp( pszParam, \"see:\", 4 ) )\n\t\t{\n\t\t\tpSeeEntity = gEntList.FindEntityByName( NULL, pszParam+4 );\n\t\t}\n\t\telse if ( pszParam[0] == '$' )\n\t\t{\n\t\t\t\/\/ $ signs prepend custom movement sequences \/ activities\n\t\t\tconst char *pAnimName = pszParam+1;\n\t\t\t\/\/ Try and resolve it as an activity name\n\t\t\tactivity = (Activity)ActivityList_IndexForName( pAnimName );\n\t\t\tif ( activity == ACT_INVALID )\n\t\t\t{\n\t\t\t\t\/\/ Try it as sequence name\n\t\t\t\tpBehavior->GetOuter()->m_iszSceneCustomMoveSeq = AllocPooledString( pAnimName );\n\t\t\t\tactivity = ACT_SCRIPT_CUSTOM_MOVE;\n\t\t\t}\n\t\t}\n\t\telse \n\t\t{\n\t\t\t\/\/ Do we have a specified time?\n\t\t\tflMaxTime = atof( pszParam );\n\t\t}\n\n\t\tpszParam = strtok(NULL,\" \");\n\t}\n\n\tif ( ai_debug_actbusy.GetInt() == 4 )\n\t{\n\t\tMsg(\"ACTBUSY: Actbusy goal %s (%s) ForceNPCToActBusy input with data: %s.\\n\", GetClassname(), GetDebugName(), parseString );\n\t}\n\n\t\/\/ Tell the NPC to immediately act busy\n\tpBehavior->SetBusySearchRange( m_flBusySearchRange );\n\tpBehavior->ForceActBusy( this, pHintNode, flMaxTime, m_bVisibleOnly, bTeleport, bUseNearestBusy, pSeeEntity, activity );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Force the passed in NPC to actbusy\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::InputForceThisNPCToActBusy( inputdata_t &inputdata )\n{\n\tCAI_ActBusyBehavior *pBehavior = GetBusyBehaviorForNPC( inputdata.value.Entity(), \"InputForceThisNPCToActBusy\" );\n\tif ( !pBehavior )\n\t\treturn;\n\n\t\/\/ Tell the NPC to immediately act busy\n\tpBehavior->SetBusySearchRange( m_flBusySearchRange );\n\tpBehavior->ForceActBusy( this );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Force the passed in NPC to walk to a point and vanish\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::InputForceThisNPCToLeave( inputdata_t &inputdata )\n{\n\tCAI_ActBusyBehavior *pBehavior = GetBusyBehaviorForNPC( inputdata.value.Entity(), \"InputForceThisNPCToLeave\" );\n\tif ( !pBehavior )\n\t\treturn;\n\n\t\/\/ Tell the NPC to find a leave point and move to it\n\tpBehavior->SetBusySearchRange( m_flBusySearchRange );\n\tpBehavior->ForceActBusyLeave();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : *pNPC - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::NPCMovingToBusy( CAI_BaseNPC *pNPC )\n{\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : *pNPC - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::NPCStartedBusy( CAI_BaseNPC *pNPC )\n{\n\tm_OnNPCStartedBusy.Set( pNPC, pNPC, this );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::NPCStartedLeavingBusy( CAI_BaseNPC *pNPC )\n{\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : *pNPC - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::NPCAbortedMoveTo( CAI_BaseNPC *pNPC )\n{\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : *pNPC - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::NPCFinishedBusy( CAI_BaseNPC *pNPC )\n{\n\tm_OnNPCFinishedBusy.Set( pNPC, pNPC, this );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : *pNPC - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::NPCLeft( CAI_BaseNPC *pNPC )\n{\n\tm_OnNPCLeft.Set( pNPC, pNPC, this );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::NPCLostSeeEntity( CAI_BaseNPC *pNPC )\n{\n\tm_OnNPCLostSeeEntity.Set( pNPC, pNPC, this );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyGoal::NPCSeeEnemy( CAI_BaseNPC *pNPC )\n{\n\tm_OnNPCSeeEnemy.Set( pNPC, pNPC, this );\n}\n\n\/\/==========================================================================================================\n\/\/ ACT BUSY QUEUE\n\/\/==========================================================================================================\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: A level tool to control the actbusy behavior to create NPC queues \n\/\/-----------------------------------------------------------------------------\nLINK_ENTITY_TO_CLASS( ai_goal_actbusy_queue, CAI_ActBusyQueueGoal );\n\nBEGIN_DATADESC( CAI_ActBusyQueueGoal )\n\t\/\/ Keys\n\tDEFINE_FIELD( m_iCurrentQueueCount, FIELD_INTEGER ),\n\tDEFINE_ARRAY( m_hNodes, FIELD_EHANDLE, MAX_QUEUE_NODES ),\n\tDEFINE_ARRAY( m_bPlayerBlockedNodes, FIELD_BOOLEAN, MAX_QUEUE_NODES ),\n\tDEFINE_FIELD( m_hExitNode, FIELD_EHANDLE ),\n\tDEFINE_FIELD( m_hExitingNPC, FIELD_EHANDLE ),\n\tDEFINE_KEYFIELD( m_bForceReachFront, FIELD_BOOLEAN, \"mustreachfront\" ),\n\t\/\/ DEFINE_ARRAY( m_iszNodes, FIELD_STRING, MAX_QUEUE_NODES ), \/\/ Silence Classcheck!\n\tDEFINE_KEYFIELD( m_iszNodes[0], FIELD_STRING, \"node01\"),\n\tDEFINE_KEYFIELD( m_iszNodes[1], FIELD_STRING, \"node02\"),\n\tDEFINE_KEYFIELD( m_iszNodes[2], FIELD_STRING, \"node03\"),\n\tDEFINE_KEYFIELD( m_iszNodes[3], FIELD_STRING, \"node04\"),\n\tDEFINE_KEYFIELD( m_iszNodes[4], FIELD_STRING, \"node05\"),\n\tDEFINE_KEYFIELD( m_iszNodes[5], FIELD_STRING, \"node06\"),\n\tDEFINE_KEYFIELD( m_iszNodes[6], FIELD_STRING, \"node07\"),\n\tDEFINE_KEYFIELD( m_iszNodes[7], FIELD_STRING, \"node08\"),\n\tDEFINE_KEYFIELD( m_iszNodes[8], FIELD_STRING, \"node09\"),\n\tDEFINE_KEYFIELD( m_iszNodes[9], FIELD_STRING, \"node10\"),\n\tDEFINE_KEYFIELD( m_iszNodes[10], FIELD_STRING, \"node11\"),\n\tDEFINE_KEYFIELD( m_iszNodes[11], FIELD_STRING, \"node12\"),\n\tDEFINE_KEYFIELD( m_iszNodes[12], FIELD_STRING, \"node13\"),\n\tDEFINE_KEYFIELD( m_iszNodes[13], FIELD_STRING, \"node14\"),\n\tDEFINE_KEYFIELD( m_iszNodes[14], FIELD_STRING, \"node15\"),\n\tDEFINE_KEYFIELD( m_iszNodes[15], FIELD_STRING, \"node16\"),\n\tDEFINE_KEYFIELD( m_iszNodes[16], FIELD_STRING, \"node17\"),\n\tDEFINE_KEYFIELD( m_iszNodes[17], FIELD_STRING, \"node18\"),\n\tDEFINE_KEYFIELD( m_iszNodes[18], FIELD_STRING, \"node19\"),\n\tDEFINE_KEYFIELD( m_iszNodes[19], FIELD_STRING, \"node20\"),\n\tDEFINE_KEYFIELD( m_iszExitNode, FIELD_STRING, \"node_exit\"),\n\n\t\/\/ Inputs\n\tDEFINE_INPUTFUNC( FIELD_INTEGER, \"PlayerStartedBlocking\", InputPlayerStartedBlocking ),\n\tDEFINE_INPUTFUNC( FIELD_INTEGER, \"PlayerStoppedBlocking\", InputPlayerStoppedBlocking ),\n\tDEFINE_INPUTFUNC( FIELD_VOID, \"MoveQueueUp\", InputMoveQueueUp ),\n\n\t\/\/ Outputs\n\tDEFINE_OUTPUT( m_OnQueueMoved, \"OnQueueMoved\" ),\n\tDEFINE_OUTPUT( m_OnNPCLeftQueue, \"OnNPCLeftQueue\" ),\n\tDEFINE_OUTPUT( m_OnNPCStartedLeavingQueue, \"OnNPCStartedLeavingQueue\" ),\n\n\tDEFINE_THINKFUNC( QueueThink ),\n\tDEFINE_THINKFUNC( MoveQueueUpThink ),\n\nEND_DATADESC()\n\n#define QUEUE_THINK_CONTEXT\t\t\t\"ActBusyQueueThinkContext\"\n#define QUEUE_MOVEUP_THINK_CONTEXT\t\"ActBusyQueueMoveUpThinkContext\"\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::Spawn( void )\n{\n\tBaseClass::Spawn();\n\n\tRegisterThinkContext( QUEUE_MOVEUP_THINK_CONTEXT );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::DrawDebugGeometryOverlays( void )\n{\n\tBaseClass::DrawDebugGeometryOverlays();\n\n\t\/\/ Debug for reservers\n\tfor ( int i = 0; i < MAX_QUEUE_NODES; i++ )\n\t{\n\t\tif ( !m_hNodes[i] )\n\t\t\tcontinue;\n\t\tif ( m_bPlayerBlockedNodes[i] )\n\t\t{\n\t\t\tNDebugOverlay::Box( m_hNodes[i]->GetAbsOrigin(), -Vector(5,5,5), Vector(5,5,5), 255, 0, 0, 0, 0.1 );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tNDebugOverlay::Box( m_hNodes[i]->GetAbsOrigin(), -Vector(5,5,5), Vector(5,5,5), 255, 255, 255, 0, 0.1 );\n\t\t}\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::InputActivate( inputdata_t &inputdata )\n{\n\tif ( !IsActive() )\n\t{\n\t\t\/\/ Find all our nodes\n\t\tfor ( int i = 0; i < MAX_QUEUE_NODES; i++ )\n\t\t{\n\t\t\tif ( m_iszNodes[i] == NULL_STRING )\n\t\t\t{\n\t\t\t\tm_hNodes[i] = NULL;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tCBaseEntity *pEntity = gEntList.FindEntityByName( NULL, m_iszNodes[i] );\n\t\t\tif ( !pEntity )\n\t\t\t{\n\t\t\t\tWarning( \"Unable to find ai_goal_actbusy_queue %s's node %d: %s\\n\", STRING(GetEntityName()), i, STRING(m_iszNodes[i]) );\n\t\t\t\tUTIL_Remove( this );\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tm_hNodes[i] = dynamic_cast<CAI_Hint*>(pEntity);\n\t\t\tif ( !m_hNodes[i] )\n\t\t\t{\n\t\t\t\tWarning( \"ai_goal_actbusy_queue %s's node %d: '%s' is not an ai_hint.\\n\", STRING(GetEntityName()), i, STRING(m_iszNodes[i]) );\n\t\t\t\tUTIL_Remove( this );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ Disable all but the first node\n\t\t\tif ( i == 0 )\n\t\t\t{\n\t\t\t\tm_hNodes[i]->SetDisabled( false );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_hNodes[i]->SetDisabled( true );\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Find the exit node\n\t\tm_hExitNode = gEntList.FindEntityByName( NULL, m_iszExitNode );\n\t\tif ( !m_hExitNode )\n\t\t{\n\t\t\tWarning( \"Unable to find ai_goal_actbusy_queue %s's exit node: %s\\n\", STRING(GetEntityName()), STRING(m_iszExitNode) );\n\t\t\tUTIL_Remove( this );\n\t\t\treturn;\n\t\t}\n\n\t\tRecalculateQueueCount();\n\n\t\tSetContextThink( &CAI_ActBusyQueueGoal::QueueThink, gpGlobals->curtime + 5, QUEUE_THINK_CONTEXT );\n\t}\n\n\tBaseClass::InputActivate( inputdata );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : iCount - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::RecalculateQueueCount( void )\n{\n\t\/\/ First, find the highest unused node in the queue\n\tint iCount = 0;\n\tfor ( int i = 0; i < MAX_QUEUE_NODES; i++ )\n\t{\n\t\tif ( NodeIsOccupied(i) || m_bPlayerBlockedNodes[i] )\n\t\t{\n\t\t\tiCount = i+1;\n\t\t}\n\t}\n\n\t\/\/Msg(\"Count: %d (OLD %d)\\n\", iCount, m_iCurrentQueueCount );\n\n\t\/\/ Queue hasn't changed?\n\tif ( iCount == m_iCurrentQueueCount )\n\t\treturn;\n\n\tfor ( int i = 0; i < MAX_QUEUE_NODES; i++ )\n\t{\n\t\tif ( m_hNodes[i] )\n\t\t{\n\t\t\t\/\/ Disable nodes beyond 1 past the end of the queue\n\t\t\tif ( i > iCount )\n\t\t\t{\n\t\t\t\tm_hNodes[i]->SetDisabled( true );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_hNodes[i]->SetDisabled( false );\n\n\t\t\t\t\/\/ To prevent NPCs outside the queue moving directly to nodes within the queue, only\n\t\t\t\t\/\/ have the entry node be a valid actbusy node.\n\t\t\t\tif ( i == iCount )\n\t\t\t\t{\n\t\t\t\t\tm_hNodes[i]->SetHintType( HINT_WORLD_WORK_POSITION );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tm_hNodes[i]->SetHintType( HINT_NONE );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tm_iCurrentQueueCount = iCount;\n\tm_OnQueueMoved.Set( m_iCurrentQueueCount, this, this);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : &inputdata - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::InputPlayerStartedBlocking( inputdata_t &inputdata )\n{\n\tint iNode = inputdata.value.Int() - 1;\n\tAssert( iNode >= 0 && iNode < MAX_QUEUE_NODES );\n\n\tm_bPlayerBlockedNodes[iNode] = true;\n\n\t\/*\n\t\/\/ First, find all NPCs heading to points in front of the player's blocked spot\n\tfor ( int i = 0; i < iNode; i++ )\n\t{\n\t\tCAI_BaseNPC *pNPC = GetNPCOnNode(i);\n\t\tif ( !pNPC )\n\t\t\tcontinue;\n\n\t\tCAI_ActBusyBehavior *pBehavior = GetQueueBehaviorForNPC( pNPC );\n\t\tif ( pBehavior->IsMovingToBusy() )\n\t\t{\n\t\t\t\/\/ We may be ahead of the player in the queue, which means we can safely \n\t\t\t\/\/ be left alone to reach the node. Make sure we're not closer to it than the player is\n\t\t\tfloat flPlayerDistToNode = (inputdata.pActivator->GetAbsOrigin() - m_hNodes[i]->GetAbsOrigin()).LengthSqr();\n\t\t\tif ( (pNPC->GetAbsOrigin() - m_hNodes[i]->GetAbsOrigin()).LengthSqr() < flPlayerDistToNode )\n\t\t\t\tcontinue;\n\n\t\t\t\/\/ We're an NPC heading to a node past the player, and yet the player's in our way.\n\t\t\tpBehavior->StopBusying();\n\t\t}\n\t}\n\t*\/\n\n\t\/\/ If an NPC was heading towards this node, tell him to go elsewhere\n\tCAI_BaseNPC *pNPC = GetNPCOnNode(iNode);\n\tPushNPCBackInQueue( pNPC, iNode );\n\n\tRecalculateQueueCount();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Find a node back in the queue to move to, and push all NPCs beyond that backwards\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::PushNPCBackInQueue( CAI_BaseNPC *pNPC, int iStartingNode )\n{\n\t\/\/ Push this guy back, and tell everyone behind him to move back too, until we find a gap\n\twhile ( pNPC )\n\t{\n\t\tCAI_ActBusyBehavior *pBehavior = GetQueueBehaviorForNPC( pNPC );\n\t\tpBehavior->StopBusying();\n\n\t\t\/\/ Find any node farther back in the queue that isn't player blocked\n\t\tfor ( int iNext = iStartingNode+1; iNext < MAX_QUEUE_NODES; iNext++ )\n\t\t{\n\t\t\tif ( !m_bPlayerBlockedNodes[iNext] )\n\t\t\t{\n\t\t\t\t\/\/ Kick off any NPCs on the node we're about to steal\n\t\t\t\tCAI_BaseNPC *pTargetNPC = GetNPCOnNode(iNext);\n\t\t\t\tif ( pTargetNPC )\n\t\t\t\t{\n\t\t\t\t\tCAI_ActBusyBehavior *pTargetBehavior = GetQueueBehaviorForNPC( pTargetNPC );\n\t\t\t\t\tpTargetBehavior->StopBusying();\n\t\t\t\t}\n\n\t\t\t\t\/\/ Force the NPC to move up to the empty slot\n\t\t\t\tpBehavior->ForceActBusy( this, m_hNodes[iNext] );\n\n\t\t\t\t\/\/ Now look for a spot for the npc who's spot we've just stolen\n\t\t\t\tpNPC = pTargetNPC;\n\t\t\t\tiStartingNode = iNext;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : &inputdata - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::InputPlayerStoppedBlocking( inputdata_t &inputdata )\n{\n\tint iNode = inputdata.value.Int() - 1;\n\tAssert( iNode >= 0 && iNode < MAX_QUEUE_NODES );\n\n\tm_bPlayerBlockedNodes[iNode] = false;\n\n\tRecalculateQueueCount();\n\tMoveQueueUp();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : &inputdata - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::InputMoveQueueUp( inputdata_t &inputdata )\n{\n\t\/\/ Find the first NPC in the queue\n\tCAI_BaseNPC *pNPC = NULL;\n\tfor ( int i = 0; i < MAX_QUEUE_NODES; i++ )\n\t{\n\t\tpNPC = GetNPCOnNode(i);\n\t\tif ( pNPC )\n\t\t{\n\t\t\tCAI_ActBusyBehavior *pBehavior = GetQueueBehaviorForNPC( pNPC );\n\t\t\t\/\/ If we're still en-route, we're only allowed to leave if the queue\n\t\t\t\/\/ is allowed to send NPCs away that haven't reached the front.\n\t\t\tif ( !pBehavior->IsMovingToBusy() || !m_bForceReachFront )\n\t\t\t\tbreak;\n\n\t\t\tpNPC = NULL;\n\t\t}\n\n\t\t\/\/ If queue members have to reach the front of the queue,\n\t\t\/\/ break after trying the first node.\n\t\tif ( m_bForceReachFront )\n\t\t\tbreak;\n\t}\n\n\t\/\/ Did we find an NPC?\n\tif ( pNPC )\n\t{\n\t\t\/\/ Make them leave the actbusy\n\t\tCAI_ActBusyBehavior *pBehavior = GetQueueBehaviorForNPC( pNPC );\n\t\tpBehavior->Disable();\n\t\tm_hExitingNPC = pNPC;\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : *pNPC - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::NPCMovingToBusy( CAI_BaseNPC *pNPC )\n{\n\tBaseClass::NPCMovingToBusy( pNPC );\n\tRecalculateQueueCount();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : *pNPC - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::NPCStartedBusy( CAI_BaseNPC *pNPC )\n{\n\tBaseClass::NPCStartedBusy( pNPC );\n\tMoveQueueUp();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Start a short timer that'll clean up holes in the queue\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::MoveQueueUp( void )\n{\n\t\/\/ Find the node the NPC has arrived at, and tell the guy behind him to move forward\n\tif ( GetNextThink( QUEUE_MOVEUP_THINK_CONTEXT ) < gpGlobals->curtime )\n\t{\n\t\tfloat flTime = gpGlobals->curtime + RandomFloat( 0.3, 0.5 );\n\t\tSetContextThink( &CAI_ActBusyQueueGoal::MoveQueueUpThink, flTime, QUEUE_MOVEUP_THINK_CONTEXT );\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::MoveQueueUpThink( void )\n{\n\t\/\/ Find empty holes in the queue, and move NPCs past them forward\n\tfor ( int iEmptyNode = 0; iEmptyNode < (MAX_QUEUE_NODES-1); iEmptyNode++ )\n\t{\n\t\tif ( !NodeIsOccupied(iEmptyNode) && !m_bPlayerBlockedNodes[iEmptyNode] )\n\t\t{\n\t\t\t\/\/ Look for NPCs farther down the queue, but not on the other side of a player\n\t\t\tfor ( int iNext = iEmptyNode+1; iNext < MAX_QUEUE_NODES; iNext++ )\n\t\t\t{\n\t\t\t\t\/\/ Is the player blocking this node? If so, we're done\n\t\t\t\tif ( m_bPlayerBlockedNodes[iNext] )\n\t\t\t\t\tbreak;\n\n\t\t\t\tCAI_BaseNPC *pNPC = GetNPCOnNode(iNext);\n\t\t\t\tif ( pNPC )\n\t\t\t\t{\n\t\t\t\t\tCAI_ActBusyBehavior *pBehavior = GetQueueBehaviorForNPC( pNPC );\n\n\t\t\t\t\t\/\/ Force the NPC to move up to the empty slot\n\t\t\t\t\tpBehavior->ForceActBusy( this, m_hNodes[iEmptyNode] );\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : *pNPC - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::NPCAbortedMoveTo( CAI_BaseNPC *pNPC )\n{\n\tBaseClass::NPCAbortedMoveTo( pNPC );\n\n\tRemoveNPCFromQueue( pNPC );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : *pNPC - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::NPCFinishedBusy( CAI_BaseNPC *pNPC )\n{\n\tBaseClass::NPCFinishedBusy( pNPC );\n\n\t\/\/ If this NPC was at the head of the line, move him to the exit node\n\tif ( m_hExitingNPC == pNPC )\n\t{\n\t\tpNPC->ScheduledMoveToGoalEntity( SCHED_IDLE_WALK, m_hExitNode, ACT_WALK );\n\t\tm_OnNPCLeftQueue.Set( pNPC, pNPC, this );\n\t\tm_hExitingNPC = NULL;\n\t}\n\n\tRemoveNPCFromQueue( pNPC );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : *pNPC - \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::NPCStartedLeavingBusy( CAI_BaseNPC *pNPC )\n{\n\tBaseClass::NPCStartedLeavingBusy( pNPC );\n\n\t\/\/ If this NPC it at the head of the line, fire the output\n\tif ( m_hExitingNPC == pNPC )\n\t{\n\t\tm_OnNPCStartedLeavingQueue.Set( pNPC, pNPC, this );\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::RemoveNPCFromQueue( CAI_BaseNPC *pNPC )\n{\n\tRecalculateQueueCount();\n\n\t\/\/ Find the node the NPC was heading to, and tell the guy behind him to move forward\n\tMoveQueueUp();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: Move the first NPC out of the queue\n\/\/-----------------------------------------------------------------------------\nvoid CAI_ActBusyQueueGoal::QueueThink( void )\n{\n\tif ( !GetNPCOnNode(0) )\n\t{\n\t\tMoveQueueUp();\n\t}\n\n\tSetContextThink( &CAI_ActBusyQueueGoal::QueueThink, gpGlobals->curtime + 5, QUEUE_THINK_CONTEXT );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/-----------------------------------------------------------------------------\ninline bool\tCAI_ActBusyQueueGoal::NodeIsOccupied( int i ) \n{ \n\treturn ( m_hNodes[i] && !m_hNodes[i]->IsDisabled() && m_hNodes[i]->IsLocked() ); \n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : iNode - \n\/\/ Output : CAI_BaseNPC\n\/\/-----------------------------------------------------------------------------\nCAI_BaseNPC *CAI_ActBusyQueueGoal::GetNPCOnNode( int iNode )\n{\n\tif ( !m_hNodes[iNode] )\n\t\treturn NULL;\n\n\treturn dynamic_cast<CAI_BaseNPC *>(m_hNodes[iNode]->User());\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Purpose: \n\/\/ Input  : iNode - \n\/\/ Output : CAI_ActBusyBehavior\n\/\/-----------------------------------------------------------------------------\nCAI_ActBusyBehavior *CAI_ActBusyQueueGoal::GetQueueBehaviorForNPC( CAI_BaseNPC *pNPC )\n{\n\tCAI_ActBusyBehavior *pBehavior;\n\tpNPC->GetBehavior( &pBehavior );\n\tAssert( pBehavior );\n\treturn pBehavior;\n}\n\n","avg_line_length":31.2876971609,"max_line_length":209,"alphanum_fraction":0.59244621,"low_alphanum":false,"long_lines":false,"lexable":false}
{"size":792,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/*\r\n\tResolucao:\r\n\t\tCalcula a diferenca em minutos, entre a hora atual\r\n\t\te o horario do despertador\r\n\t\tSe o horario do despertador for menor que a hora atual\r\n\t\tsignifica que o despertador somente tocara no dia seguinte\r\n\t\tEntao e somado um dia em minutos para o horario do despertador\r\n\t\te subtraido do horario atual\r\n*\/\r\n\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    ios::sync_with_stdio(false);\r\n    int h1, m1, h2, m2;\r\n    for (cin >> h1 >> m1 >> h2 >> m2; h1 != 0 || h2 != 0 || m1 != 0 || m2 != 0; cin >> h1 >> m1 >> h2 >> m2)\r\n        if (h1 >= h2 || h2 >= h1) {\r\n            m1 = m1 + (60 * h1);\r\n            m2 = m2 + (60 * h2);\r\n            if (m2 < m1)\r\n                m2 = m2 + (24 * 60);\r\n            cout << m2 - m1 << \"\\n\";\r\n        }\r\n    return 0;\r\n}\r\n","avg_line_length":27.3103448276,"max_line_length":109,"alphanum_fraction":0.5138888889,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6505,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":96.0,"content":"\/\/------------------------------------------------------------------------------\n\/\/\n\/\/   Copyright 2018-2020 Fetch.AI Limited\n\/\/\n\/\/   Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/   you may not use this file except in compliance with the License.\n\/\/   You may obtain a copy of the License at\n\/\/\n\/\/       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/   Unless required by applicable law or agreed to in writing, software\n\/\/   distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/   See the License for the specific language governing permissions and\n\/\/   limitations under the License.\n\/\/\n\/\/------------------------------------------------------------------------------\n\n#include \"muddle.hpp\"\n\n#include \"core\/byte_array\/decoders.hpp\"\n#include \"crypto\/ecdsa.hpp\"\n#include \"muddle\/rpc\/client.hpp\"\n#include \"muddle\/rpc\/server.hpp\"\n#include \"network\/management\/network_manager.hpp\"\n#include \"network\/peer.hpp\"\n#include \"network\/service\/protocol.hpp\"\n\n#include \"gtest\/gtest.h\"\n\n#include <atomic>\n#include <chrono>\n#include <cstddef>\n#include <cstdint>\n#include <memory>\n#include <thread>\n\nusing fetch::byte_array::ByteArray;\nusing fetch::byte_array::ConstByteArray;\nusing fetch::byte_array::FromBase64;\nusing fetch::muddle::NetworkId;\nusing std::chrono::seconds;\nusing std::this_thread::sleep_for;\n\nclass TestProtocol : public fetch::service::Protocol\n{\npublic:\n  enum\n  {\n    EXCHANGE = 0xEF\n  };\n\n  TestProtocol()\n  {\n    Expose(EXCHANGE, this, &TestProtocol::Exchange);\n  }\n\nprivate:\n  ConstByteArray Exchange(ConstByteArray const &value)\n  {\n    return value;\n  }\n};\n\nstatic constexpr uint16_t SERVICE = 10;\nstatic constexpr uint16_t CHANNEL = 12;\n\nclass MuddleRpcStressTests : public ::testing::Test\n{\nprotected:\n  static constexpr char const *NETWORK_A_PUBLIC_KEY =\n      \"rOA3MfBt0DdRtZRSo\/gBFP2aD\/YQTsd9lOh\/Oc\/Pzchrzz1wfhTUMpf9z8cc1kRltUpdlWznGzwroO8\/rbdPXA==\";\n  static constexpr char const *NETWORK_A_PRIVATE_KEY =\n      \"BEb+rF65Dg+59XQyKcu9HLl5tJc9wAZDX+V0ud07iDQ=\";\n  static constexpr char const *NETWORK_B_PUBLIC_KEY =\n      \"646y3U97FbC8Q5MYTO+elrKOFWsMqwqpRGieAC7G0qZUeRhJN+xESV\/PJ4NeDXtkp6KkVLzoqRmNKTXshBIftA==\";\n  static constexpr char const *NETWORK_B_PRIVATE_KEY =\n      \"4DW\/sW8JLey8Z9nqi2yJJHaGzkLXIqaYc\/fwHfK0w0Y=\";\n\n  using NetworkManager    = fetch::network::NetworkManager;\n  using NetworkManagerPtr = std::unique_ptr<NetworkManager>;\n  using Muddle            = fetch::muddle::Muddle;\n  using MuddlePtr         = std::shared_ptr<Muddle>;\n  using MuddleEndpoint    = fetch::muddle::MuddleEndpoint;\n  using CertificatePtr    = Muddle::CertificatePtr;\n  using Peer              = fetch::network::Peer;\n  using Uri               = Muddle::Uri;\n  using UriList           = Muddle::UriList;\n  using RpcServer         = fetch::muddle::rpc::Server;\n  using RpcClient         = fetch::muddle::rpc::Client;\n  using Flag              = std::atomic<bool>;\n  using Promise           = fetch::service::Promise;\n\n  static CertificatePtr LoadIdentity(char const *private_key)\n  {\n    using Signer = fetch::crypto::ECDSASigner;\n\n    \/\/ load the key\n    auto signer = std::make_unique<Signer>();\n    signer->Load(FromBase64(private_key));\n\n    return signer;\n  }\n\n  void SetUp() override\n  {\n    managerA_ = std::make_unique<NetworkManager>(\"NetMgrA\", 1);\n    networkA_ = std::make_shared<Muddle>(NetworkId{\"Test\"}, LoadIdentity(NETWORK_A_PRIVATE_KEY),\n                                         *managerA_);\n\n    managerB_ = std::make_unique<NetworkManager>(\"NetMgrB\", 1);\n    networkB_ = std::make_shared<Muddle>(NetworkId{\"Test\"}, LoadIdentity(NETWORK_B_PRIVATE_KEY),\n                                         *managerB_);\n\n    managerA_->Start();\n    managerB_->Start();\n\n    networkA_->Start({8000});\n    networkB_->Start({\"tcp:\/\/127.0.0.1:8000\"}, {9000});\n\n    sleep_for(seconds{1});\n  }\n\n  void TearDown() override\n  {\n    networkB_->Stop();\n    networkA_->Stop();\n    managerB_->Stop();\n    managerA_->Stop();\n\n    networkB_.reset();\n    managerB_.reset();\n\n    networkA_.reset();\n    managerA_.reset();\n  }\n\n  static ConstByteArray GenerateData(std::size_t length, uint8_t fill)\n  {\n    ByteArray buffer;\n    buffer.Resize(length);\n    for (std::size_t i = 0; i < length; ++i)\n    {\n      buffer[i] = fill;\n    }\n    return {std::move(buffer)};\n  }\n\n  static void ClientServer(MuddleEndpoint &endpoint, char const *target)\n  {\n    static constexpr std::size_t NUM_MESSAGES   = 200;\n    static constexpr std::size_t PAYLOAD_LENGTH = 5;\n    static constexpr uint64_t    PROTOCOL       = 0xEF;\n\n    \/\/ create the server\n    TestProtocol protocol;\n    auto         server = std::make_shared<RpcServer>(endpoint, SERVICE, CHANNEL);\n    server->Add(PROTOCOL, &protocol);\n\n    \/\/ create the client\n    auto client = std::make_shared<RpcClient>(\"Client\", endpoint, SERVICE, CHANNEL);\n\n    if (NETWORK_A_PUBLIC_KEY == target)\n    {\n      sleep_for(seconds{2});\n    }\n\n    std::vector<Promise> pending;\n    for (std::size_t loop = 0; loop < NUM_MESSAGES; ++loop)\n    {\n      \/\/ generate a big load of data\n      auto const           fill = static_cast<uint8_t>(loop);\n      ConstByteArray const data = GenerateData(PAYLOAD_LENGTH, fill);\n\n      Promise promise =\n          client->CallSpecificAddress(FromBase64(target), PROTOCOL, TestProtocol::EXCHANGE, data);\n      promise->WithHandlers()\n          .Then([promise, fill]() {\n            ConstByteArray result{};\n            ASSERT_TRUE(promise->GetResult(result));\n            EXPECT_EQ(PAYLOAD_LENGTH, result.size());\n\n            ConstByteArray const &result_ref{result};\n            for (std::size_t i = 0; i < result.size(); ++i)\n            {\n              EXPECT_EQ(result_ref[i], fill);\n            }\n          })\n          .Catch([]() { FAIL(); });\n\n      pending.push_back(promise);\n    }\n\n    while (!pending.empty())\n    {\n      if (!pending.back()->IsWaiting())\n      {\n        pending.pop_back();\n        continue;\n      }\n\n      sleep_for(seconds{1});\n    }\n\n    sleep_for(seconds{5});\n  }\n\n  NetworkManagerPtr managerA_;\n  MuddlePtr         networkA_;\n\n  NetworkManagerPtr managerB_;\n  MuddlePtr         networkB_;\n};\n\nTEST_F(MuddleRpcStressTests, DISABLED_ContinuousBiDirectionalTraffic)\n{\n  std::thread nodeA([this]() { ClientServer(networkA_->GetEndpoint(), NETWORK_B_PUBLIC_KEY); });\n  std::thread nodeB([this]() { ClientServer(networkB_->GetEndpoint(), NETWORK_A_PUBLIC_KEY); });\n\n  nodeB.join();\n  nodeA.join();\n}\n","avg_line_length":29.1704035874,"max_line_length":98,"alphanum_fraction":0.6435049962,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":978,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/*\n * LaplacianCentrality.cpp\n *\n *  Created on: 08.03.2018\n *      Author: Kolja Esders\n *\/\n\n#include \"LaplacianCentrality.h\"\n\nnamespace NetworKit {\n\nLaplacianCentrality::LaplacianCentrality(const Graph& G, bool normalized): Centrality(G, normalized) {\n}\n\nvoid LaplacianCentrality::run() {\n\tscoreData = std::vector<double>(G.upperNodeIdBound(), 0.0);\n\tdouble totalLaplacianEnergy = 0.0;\n\n\tG.parallelForNodes([&](node u) {\n\t\tcount degreeU = G.weightedDegree(u);\n\t\tdouble energyLossOnNodeDrop = degreeU * degreeU;\n#pragma omp atomic\n\t\ttotalLaplacianEnergy += degreeU * degreeU;\n\n\t\tG.forNeighborsOf(u, [&](node v, edgeweight ew) {\n\t\t\tenergyLossOnNodeDrop += ew * (ew + 2 * G.weightedDegree(v));\n#pragma omp atomic\n\t\t\ttotalLaplacianEnergy += ew * ew;\n\t\t});\n\n\t\tscoreData[u] = energyLossOnNodeDrop;\n\t});\n\n\tif (!normalized) {\n\t\thasRun = true;\n\t\treturn;\n\t}\n\n\tG.parallelForNodes([&](node u) {\n\t\tscoreData[u] \/= totalLaplacianEnergy;\n\t});\n\n\thasRun = true;\n}\n\n} \/* namespace NetworKit *\/\n","avg_line_length":20.8085106383,"max_line_length":102,"alphanum_fraction":0.6871165644,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5368,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":20.0,"content":"\/*\n *  Copyright (c) 2018 str2num. All Rights Reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree.\n *\/ \n \n\/**\n * @file event_loop.cpp\n * @author str2num\n * @brief \n *  \n **\/\n\n#include <assert.h>\n#include <ev.h>\n\n#include \"logging.h\"\n#include \"time_utils.h\"\n#include \"event_loop.h\"\n\nnamespace rtcbase {\n\n\/* translate to\/from libev mask *\/\n#define TRANS_TO_EV_MASK(mask)                                          \\\n    (((mask)&EventLoop::READ?EV_READ:EV_NONE) | ((mask)&EventLoop::WRITE?EV_WRITE:EV_NONE))\n#define TRANS_FROM_EV_MASK(ev_mask)                                     \\\n    (((ev_mask)&EV_READ?EventLoop::READ:EventLoop::NONE) | ((ev_mask)&EV_WRITE?EventLoop::WRITE:EventLoop::NONE))\n\nEventLoop* EventLoop::_default_loop = NULL;\n\nunsigned long EventLoop::current_time() {\n    if (_default_loop) {\n        return _default_loop->now();\n    } else {\n        return (unsigned long)unix_time_micros();\n    }\n}\n\nEventLoop::EventLoop(void* el_owner, bool use_default) \n    : owner(el_owner), _loop(NULL)\n{\n    if (use_default) {\n        _loop = EV_DEFAULT;\n        _default_loop = this;\n    } else {\n        _loop = ev_loop_new(EVFLAG_AUTO);\n    }\n    ev_set_userdata(_loop, (void*)this);\n}\n\nEventLoop::~EventLoop() {\n    if (_loop) {\n        stop();\n        \/\/ Only destroy the loop created with ev_loop_new\n        if (!ev_is_default_loop(_loop)) {\n            ev_loop_destroy(_loop);\n        }\n    }\n}\n\nvoid EventLoop::run() {\n    ev_run(_loop);\n}\n\nvoid EventLoop::suspend() {\n    ev_suspend(_loop);\n}\n\nvoid EventLoop::resume() {\n    ev_resume(_loop);\n}\n\nvoid EventLoop::stop() {\n    ev_break(_loop, EVBREAK_ALL);\n}\n\nvoid EventLoop::sleep(unsigned long usec) {\n    ev_sleep(usec \/ 1000000.0);\n}\n\nunsigned long EventLoop::now() {\n    return (unsigned long)(ev_now(_loop)*1000000);\n}\n\nclass TimerWatcher {\npublic:\n    struct ev_timer timer;\n    timer_cb_t cb;\n    EventLoop* el;\n    void* data;\n    bool need_repeat;\n    TimerWatcher(EventLoop* el, timer_cb_t cb, void* priv_data, bool repeat);\n};\n\nTimerWatcher::TimerWatcher(EventLoop *eventloop, timer_cb_t callback, \n        void *priv_data, bool repeat) : \n    cb(callback), el(eventloop), data(priv_data), need_repeat(repeat) \n{\n    timer.data = (void*)this;\n}\n\nvoid generic_timer_cb(struct ev_loop* el, struct ev_timer* w, int revents) {\n    (void)el;\n    (void)revents;\n    TimerWatcher* watcher = (TimerWatcher*)w;\n    watcher->cb(watcher->el, watcher, watcher->data);\n}\n\nTimerWatcher* EventLoop::create_timer(timer_cb_t cb, void* priv_data,\n        bool repeat) \n{\n    TimerWatcher* w = new TimerWatcher(this, cb, priv_data, repeat);\n    ev_init(&(w->timer), generic_timer_cb);\n    return w;\n}\n\nvoid EventLoop::start_timer(TimerWatcher* w, unsigned long usec) {\n    struct ev_timer* timer = &(w->timer);\n    float sec = (float)usec \/ 1000000;\n    if (!w->need_repeat) {\n        ev_timer_stop(_loop, timer);\n        ev_timer_set(timer, sec, 0);\n        ev_timer_start(_loop, timer);\n    } else {\n        \/\/ We can change the timeout on the fly\n        timer->repeat = sec;\n        ev_timer_again(_loop, timer);\n    }\n}\n\nvoid EventLoop::stop_timer(TimerWatcher* w) {\n    struct ev_timer* timer = &(w->timer);\n    ev_timer_stop(_loop, timer);\n}\n\nvoid EventLoop::delete_timer(TimerWatcher* w) {\n    stop_timer(w);\n    delete w;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ IOWatcher \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass IOWatcher {\npublic:\n    ev_io io;\n    io_cb_t cb;\n    EventLoop* el;\n    void* data;\n    IOWatcher(EventLoop* el, io_cb_t cb, void* priv_data);\n};\n\nIOWatcher::IOWatcher(EventLoop* eventloop, io_cb_t callback, void* priv_data)\n    : cb(callback), el(eventloop), data(priv_data)\n{\n    io.data = (void*)this;\n}\n\nvoid generic_io_cb(struct ev_loop* el, struct ev_io* w, int revents) {\n    (void)el;\n    IOWatcher* watcher = (IOWatcher*)(w->data);\n    watcher->cb(watcher->el, watcher, w->fd,\n            TRANS_FROM_EV_MASK(revents), watcher->data);\n}\n\nIOWatcher* EventLoop::create_io_event(io_cb_t cb, void* data) {\n    IOWatcher* w = new IOWatcher(this, cb, data);\n    ev_init(&(w->io), generic_io_cb);\n    return w;\n}\n\nvoid EventLoop::start_io_event(IOWatcher* w, int fd, int mask) {\n    struct ev_io* io = &(w->io);\n    \/* If there's no change on the events, just return *\/\n    if (ev_is_active(io)) {\n        int active_events = TRANS_FROM_EV_MASK(io->events);\n        int events = active_events | mask;\n        if (active_events == events) {\n            return;\n        }\n        events = TRANS_TO_EV_MASK(events);\n        ev_io_stop(_loop, io);\n        ev_io_set(io, fd, events);\n        ev_io_start(_loop, io);\n    } else {\n        int events = TRANS_TO_EV_MASK(mask);\n        ev_io_set(io, fd, events);\n        ev_io_start(_loop, io);\n    }\n}\n\nvoid EventLoop::stop_io_event(IOWatcher* w, int fd, int mask) {\n    struct ev_io* io = &(w->io);\n    int active_events = TRANS_FROM_EV_MASK(io->events);\n    int events = active_events & (~mask);\n    if (active_events == events) {\n        return;\n    }\n    events = TRANS_TO_EV_MASK(events);\n    ev_io_stop(_loop, io);\n    if (events != EV_NONE) {\n        ev_io_set(io, fd, events);\n        ev_io_start(_loop, io);\n    }\n}\n\nvoid EventLoop::delete_io_event(IOWatcher* w) {\n    struct ev_io* io = &(w->io);\n    ev_io_stop(_loop, io);\n    delete w;\n}\n\n} \/\/ namespace rtcbase\n\n\n","avg_line_length":24.7373271889,"max_line_length":113,"alphanum_fraction":0.6257451565,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3800,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*\/\n\n#include \"berryTemporaryObjectManager.h\"\n\n#include \"berryRegistryObjectManager.h\"\n#include \"berryExtensionHandle.h\"\n#include \"berryExtensionPointHandle.h\"\n#include \"berryInvalidRegistryObjectException.h\"\n#include \"berryRegistryObject.h\"\n#include \"berryThirdLevelConfigurationElementHandle.h\"\n\nnamespace berry {\n\nTemporaryObjectManager::TemporaryObjectManager(const QHash<int, SmartPointer<RegistryObject> >& actualObjects,\n                       RegistryObjectManager* parent)\n  : actualObjects(actualObjects), parent(parent)\n{\n}\n\nSmartPointer<Handle> TemporaryObjectManager::GetHandle(int id, short type) const\n{\n  Handle::Pointer handle;\n  switch (type)\n  {\n  case RegistryObjectManager::EXTENSION_POINT :\n    handle = new ExtensionPointHandle(IObjectManager::ConstPointer(this), id);\n    return handle;\n\n  case RegistryObjectManager::EXTENSION :\n    handle = new ExtensionHandle(IObjectManager::ConstPointer(this), id);\n    return handle;\n\n  case RegistryObjectManager::CONFIGURATION_ELEMENT :\n    handle = new ConfigurationElementHandle(IObjectManager::ConstPointer(this), id);\n    return handle;\n\n    case RegistryObjectManager::THIRDLEVEL_CONFIGURATION_ELEMENT :\n    default : \/\/avoid compiler error, type should always be known\n      handle = new ThirdLevelConfigurationElementHandle(IObjectManager::ConstPointer(this), id);\n      return handle;\n  }\n}\n\nQList<SmartPointer<Handle> > TemporaryObjectManager::GetHandles(const QList<int>& ids, short type) const\n{\n  QList<Handle::Pointer> results;\n  switch (type)\n  {\n    case RegistryObjectManager::EXTENSION_POINT :\n      for (int i = 0; i < ids.size(); i++)\n      {\n        Handle::Pointer handle(new ExtensionPointHandle(IObjectManager::ConstPointer(this), ids[i]));\n        results.push_back(handle);\n      }\n      break;\n\n    case RegistryObjectManager::EXTENSION :\n      for (int i = 0; i < ids.size(); i++)\n      {\n        Handle::Pointer handle(new ExtensionHandle(IObjectManager::ConstPointer(this), ids[i]));\n        results.push_back(handle);\n      }\n      break;\n\n    case RegistryObjectManager::CONFIGURATION_ELEMENT :\n      for (int i = 0; i < ids.size(); i++)\n      {\n        Handle::Pointer handle(new ConfigurationElementHandle(IObjectManager::ConstPointer(this), ids[i]));\n        results.push_back(handle);\n      }\n      break;\n\n    case RegistryObjectManager::THIRDLEVEL_CONFIGURATION_ELEMENT :\n      for (int i = 0; i < ids.size(); i++)\n      {\n        Handle::Pointer handle(new ThirdLevelConfigurationElementHandle(IObjectManager::ConstPointer(this), ids[i]));\n        results.push_back(handle);\n      }\n      break;\n  }\n  return results;\n}\n\nSmartPointer<RegistryObject> TemporaryObjectManager::GetObject(int id, short type) const\n{\n  QMutexLocker l(&mutex);\n  RegistryObject::Pointer result;\n  try\n  {\n    result = parent->GetObject(id, type);\n  }\n  catch (const InvalidRegistryObjectException& \/*e*\/)\n  {\n    result = actualObjects.value(id);\n  }\n  if (result.IsNull())\n    throw InvalidRegistryObjectException();\n  return result;\n}\n\nQList<SmartPointer<RegistryObject> > TemporaryObjectManager::GetObjects(const QList<int>& values, short type) const\n{\n  QMutexLocker l(&mutex);\n\n  QList<RegistryObject::Pointer> results;\n  for (int i = 0; i < values.size(); i++)\n  {\n    results.push_back(GetObject(values[i], type));\n  }\n  return results;\n}\n\nvoid TemporaryObjectManager::Close()\n{\n  QMutexLocker l(&mutex);\n  actualObjects.clear();\n}\n\n}\n","avg_line_length":29.2307692308,"max_line_length":117,"alphanum_fraction":0.6839473684,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":102580,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["RSA-MD"],"max_stars_count":null,"content":"\/*\n * Copyright (c)2019 ZeroTier, Inc.\n *\n * Use of this software is governed by the Business Source License included\n * in the LICENSE.TXT file in the project's root directory.\n *\n * Change Date: 2023-01-01\n *\n * On the date above, in accordance with the Business Source License, use\n * of this software will be governed by version 2.0 of the Apache License.\n *\/\n\/****\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n\n#include <string>\n#include <map>\n#include <vector>\n#include <algorithm>\n#include <list>\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n\n#include \"..\/version.h\"\n#include \"..\/include\/ZeroTierOne.h\"\n\n#include \"..\/node\/Constants.hpp\"\n#include \"..\/node\/Mutex.hpp\"\n#include \"..\/node\/Node.hpp\"\n#include \"..\/node\/Utils.hpp\"\n#include \"..\/node\/InetAddress.hpp\"\n#include \"..\/node\/MAC.hpp\"\n#include \"..\/node\/Identity.hpp\"\n#include \"..\/node\/World.hpp\"\n#include \"..\/node\/Salsa20.hpp\"\n#include \"..\/node\/Poly1305.hpp\"\n#include \"..\/node\/SHA512.hpp\"\n\n#include \"..\/osdep\/Phy.hpp\"\n#include \"..\/osdep\/Thread.hpp\"\n#include \"..\/osdep\/OSUtils.hpp\"\n#include \"..\/osdep\/Http.hpp\"\n#include \"..\/osdep\/PortMapper.hpp\"\n#include \"..\/osdep\/Binder.hpp\"\n#include \"..\/osdep\/ManagedRoute.hpp\"\n#include \"..\/osdep\/BlockingQueue.hpp\"\n\n#include \"OneService.hpp\"\n#include \"SoftwareUpdater.hpp\"\n\n#ifdef __WINDOWS__\n#include <WinSock2.h>\n#include <Windows.h>\n#include <ShlObj.h>\n#include <netioapi.h>\n#include <iphlpapi.h>\n\/\/#include <unistd.h>\n#define stat _stat\n#else\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <sys\/stat.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#include <ifaddrs.h>\n#endif\n\n#ifdef ZT_USE_SYSTEM_HTTP_PARSER\n#include <http_parser.h>\n#else\n#include \"..\/ext\/http-parser\/http_parser.h\"\n#endif\n\n#if ZT_VAULT_SUPPORT\nextern \"C\" {\n#include <curl\/curl.h>\n}\n#endif\n\n#include \"..\/ext\/json\/json.hpp\"\n\nusing json = nlohmann::json;\n\n#include \"..\/controller\/EmbeddedNetworkController.hpp\"\n#include \"..\/controller\/RabbitMQ.hpp\"\n#include \"..\/osdep\/EthernetTap.hpp\"\n#ifdef __WINDOWS__\n#include \"..\/osdep\/WindowsEthernetTap.hpp\"\n#endif\n\n#ifndef ZT_SOFTWARE_UPDATE_DEFAULT\n#define ZT_SOFTWARE_UPDATE_DEFAULT \"disable\"\n#endif\n\n\/\/ Sanity limits for HTTP\n#define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)\n#define ZT_MAX_HTTP_CONNECTIONS 65536\n\n\/\/ Interface metric for ZeroTier taps -- this ensures that if we are on WiFi and also\n\/\/ bridged via ZeroTier to the same LAN traffic will (if the OS is sane) prefer WiFi.\n#define ZT_IF_METRIC 5000\n\n\/\/ How often to check for new multicast subscriptions on a tap device\n#define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000\n\n\/\/ TCP fallback relay (run by ZeroTier, Inc. -- this will eventually go away)\n#ifndef ZT_SDK\n#define ZT_TCP_FALLBACK_RELAY \"192.168.159.137\/9993\"\n#endif\n\n\/\/ Frequency at which we re-resolve the TCP fallback relay\n#define ZT_TCP_FALLBACK_RERESOLVE_DELAY 86400000\n\n\/\/ Attempt to engage TCP fallback after this many ms of no reply to packets sent to global-scope IPs\n#define ZT_TCP_FALLBACK_AFTER 60000\n\n\/\/ How often to check for local interface addresses\n#define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 60000\n\n\/\/ Maximum write buffer size for outgoing TCP connections (sanity limit)\n#define ZT_TCP_MAX_WRITEQ_SIZE 33554432\n\n\/\/ TCP activity timeout\n#define ZT_TCP_ACTIVITY_TIMEOUT 60000\n\n#if ZT_VAULT_SUPPORT\nsize_t curlResponseWrite(void *ptr, size_t size, size_t nmemb, std::string *data)\n{\n\tdata->append((char*)ptr, size * nmemb);\n\treturn size * nmemb;\n}\n#endif\n\nnamespace ZeroTier {\n\nnamespace {\n\nstatic const InetAddress NULL_INET_ADDR;\n\n\/\/ Fake TLS hello for TCP tunnel outgoing connections (TUNNELED mode)\nstatic const char ZT_TCP_TUNNEL_HELLO[9] = { 0x17,0x03,0x03,0x00,0x04,(char)ZEROTIER_ONE_VERSION_MAJOR,(char)ZEROTIER_ONE_VERSION_MINOR,(char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff),(char)(ZEROTIER_ONE_VERSION_REVISION & 0xff) };\n\nstatic std::string _trimString(const std::string &s)\n{\n\tunsigned long end = (unsigned long)s.length();\n\twhile (end) {\n\t\tchar c = s[end - 1];\n\t\tif ((c == ' ')||(c == '\\r')||(c == '\\n')||(!c)||(c == '\\t'))\n\t\t\t--end;\n\t\telse break;\n\t}\n\tunsigned long start = 0;\n\twhile (start < end) {\n\t\tchar c = s[start];\n\t\tif ((c == ' ')||(c == '\\r')||(c == '\\n')||(!c)||(c == '\\t'))\n\t\t\t++start;\n\t\telse break;\n\t}\n\treturn s.substr(start,end - start);\n}\n\nstatic void _networkToJson(nlohmann::json &nj,const ZT_VirtualNetworkConfig *nc,const std::string &portDeviceName,const OneService::NetworkSettings &localSettings)\n{\n\tchar tmp[256];\n\n\tconst char *nstatus = \"\",*ntype = \"\";\n\tswitch(nc->status) {\n\t\tcase ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION: nstatus = \"REQUESTING_CONFIGURATION\"; break;\n\t\tcase ZT_NETWORK_STATUS_OK:                       nstatus = \"OK\"; break;\n\t\tcase ZT_NETWORK_STATUS_ACCESS_DENIED:            nstatus = \"ACCESS_DENIED\"; break;\n\t\tcase ZT_NETWORK_STATUS_NOT_FOUND:                nstatus = \"NOT_FOUND\"; break;\n\t\tcase ZT_NETWORK_STATUS_PORT_ERROR:               nstatus = \"PORT_ERROR\"; break;\n\t\tcase ZT_NETWORK_STATUS_CLIENT_TOO_OLD:           nstatus = \"CLIENT_TOO_OLD\"; break;\n\t}\n\tswitch(nc->type) {\n\t\tcase ZT_NETWORK_TYPE_PRIVATE:                    ntype = \"PRIVATE\"; break;\n\t\tcase ZT_NETWORK_TYPE_PUBLIC:                     ntype = \"PUBLIC\"; break;\n\t}\n\n\tOSUtils::ztsnprintf(tmp,sizeof(tmp),\"%.16llx\",nc->nwid);\n\tnj[\"id\"] = tmp;\n\tnj[\"nwid\"] = tmp;\n\tOSUtils::ztsnprintf(tmp,sizeof(tmp),\"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\",(unsigned int)((nc->mac >> 40) & 0xff),(unsigned int)((nc->mac >> 32) & 0xff),(unsigned int)((nc->mac >> 24) & 0xff),(unsigned int)((nc->mac >> 16) & 0xff),(unsigned int)((nc->mac >> 8) & 0xff),(unsigned int)(nc->mac & 0xff));\n\tnj[\"mac\"] = tmp;\n\tnj[\"name\"] = nc->name;\n\tnj[\"status\"] = nstatus;\n\tnj[\"type\"] = ntype;\n\tnj[\"mtu\"] = nc->mtu;\n\tnj[\"dhcp\"] = (bool)(nc->dhcp != 0);\n\tnj[\"bridge\"] = (bool)(nc->bridge != 0);\n\tnj[\"broadcastEnabled\"] = (bool)(nc->broadcastEnabled != 0);\n\tnj[\"portError\"] = nc->portError;\n\tnj[\"netconfRevision\"] = nc->netconfRevision;\n\tnj[\"portDeviceName\"] = portDeviceName;\n\tnj[\"allowManaged\"] = localSettings.allowManaged;\n\tnj[\"allowGlobal\"] = localSettings.allowGlobal;\n\tnj[\"allowDefault\"] = localSettings.allowDefault;\n\n\tnlohmann::json aa = nlohmann::json::array();\n\tfor(unsigned int i=0;i<nc->assignedAddressCount;++i) {\n\t\taa.push_back(reinterpret_cast<const InetAddress *>(&(nc->assignedAddresses[i]))->toString(tmp));\n\t}\n\tnj[\"assignedAddresses\"] = aa;\n\n\tnlohmann::json ra = nlohmann::json::array();\n\tfor(unsigned int i=0;i<nc->routeCount;++i) {\n\t\tnlohmann::json rj;\n\t\trj[\"target\"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].target))->toString(tmp);\n\t\tif (nc->routes[i].via.ss_family == nc->routes[i].target.ss_family)\n\t\t\trj[\"via\"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].via))->toIpString(tmp);\n\t\telse rj[\"via\"] = nlohmann::json();\n\t\trj[\"flags\"] = (int)nc->routes[i].flags;\n\t\trj[\"metric\"] = (int)nc->routes[i].metric;\n\t\tra.push_back(rj);\n\t}\n\tnj[\"routes\"] = ra;\n\n\tnlohmann::json mca = nlohmann::json::array();\n\tfor(unsigned int i=0;i<nc->multicastSubscriptionCount;++i) {\n\t\tnlohmann::json m;\n\t\tm[\"mac\"] = MAC(nc->multicastSubscriptions[i].mac).toString(tmp);\n\t\tm[\"adi\"] = nc->multicastSubscriptions[i].adi;\n\t\tmca.push_back(m);\n\t}\n\tnj[\"multicastSubscriptions\"] = mca;\n}\n\nstatic void _peerToJson(nlohmann::json &pj,const ZT_Peer *peer)\n{\n\tchar tmp[256];\n\n\tconst char *prole = \"\";\n\tswitch(peer->role) {\n\t\tcase ZT_PEER_ROLE_LEAF: prole = \"LEAF\"; break;\n\t\tcase ZT_PEER_ROLE_MOON: prole = \"MOON\"; break;\n\t\tcase ZT_PEER_ROLE_PLANET: prole = \"PLANET\"; break;\n\t}\n\n\tOSUtils::ztsnprintf(tmp,sizeof(tmp),\"%.10llx\",peer->address);\n\tpj[\"address\"] = tmp;\n\tpj[\"versionMajor\"] = peer->versionMajor;\n\tpj[\"versionMinor\"] = peer->versionMinor;\n\tpj[\"versionRev\"] = peer->versionRev;\n\tOSUtils::ztsnprintf(tmp,sizeof(tmp),\"%d.%d.%d\",peer->versionMajor,peer->versionMinor,peer->versionRev);\n\tpj[\"version\"] = tmp;\n\tpj[\"latency\"] = peer->latency;\n\tpj[\"role\"] = prole;\n\n\tnlohmann::json pa = nlohmann::json::array();\n\tfor(unsigned int i=0;i<peer->pathCount;++i) {\n\t\tint64_t lastSend = peer->paths[i].lastSend;\n\t\tint64_t lastReceive = peer->paths[i].lastReceive;\n\t\tnlohmann::json j;\n\t\tj[\"address\"] = reinterpret_cast<const InetAddress *>(&(peer->paths[i].address))->toString(tmp);\n\t\tj[\"lastSend\"] = (lastSend < 0) ? 0 : lastSend;\n\t\tj[\"lastReceive\"] = (lastReceive < 0) ? 0 : lastReceive;\n\t\tj[\"trustedPathId\"] = peer->paths[i].trustedPathId;\n\t\tj[\"active\"] = (bool)(peer->paths[i].expired == 0);\n\t\tj[\"expired\"] = (bool)(peer->paths[i].expired != 0);\n\t\tj[\"preferred\"] = (bool)(peer->paths[i].preferred != 0);\n\t\tpa.push_back(j);\n\t}\n\tpj[\"paths\"] = pa;\n}\n\nstatic void _peerAggregateLinkToJson(nlohmann::json &pj,const ZT_Peer *peer)\n{\n\tchar tmp[256];\n\tOSUtils::ztsnprintf(tmp,sizeof(tmp),\"%.10llx\",peer->address);\n\tpj[\"aggregateLinkLatency\"] = peer->latency;\n\n\tnlohmann::json pa = nlohmann::json::array();\n\tfor(unsigned int i=0;i<peer->pathCount;++i) {\n\t\tint64_t lastSend = peer->paths[i].lastSend;\n\t\tint64_t lastReceive = peer->paths[i].lastReceive;\n\t\tnlohmann::json j;\n\t\tj[\"address\"] = reinterpret_cast<const InetAddress *>(&(peer->paths[i].address))->toString(tmp);\n\t\tj[\"lastSend\"] = (lastSend < 0) ? 0 : lastSend;\n\t\tj[\"lastReceive\"] = (lastReceive < 0) ? 0 : lastReceive;\n\t\t\/\/j[\"trustedPathId\"] = peer->paths[i].trustedPathId;\n\t\t\/\/j[\"active\"] = (bool)(peer->paths[i].expired == 0);\n\t\t\/\/j[\"expired\"] = (bool)(peer->paths[i].expired != 0);\n\t\t\/\/j[\"preferred\"] = (bool)(peer->paths[i].preferred != 0);\n\t\tj[\"latency\"] = peer->paths[i].latency;\n\t\tj[\"pdv\"] = peer->paths[i].packetDelayVariance;\n\t\t\/\/j[\"throughputDisturbCoeff\"] = peer->paths[i].throughputDisturbCoeff;\n\t\t\/\/j[\"packetErrorRatio\"] = peer->paths[i].packetErrorRatio;\n\t\t\/\/j[\"packetLossRatio\"] = peer->paths[i].packetLossRatio;\n\t\tj[\"stability\"] = peer->paths[i].stability;\n\t\tj[\"throughput\"] = peer->paths[i].throughput;\n\t\t\/\/j[\"maxThroughput\"] = peer->paths[i].maxThroughput;\n\t\tj[\"allocation\"] = peer->paths[i].allocation;\n\t\tj[\"ifname\"] = peer->paths[i].ifname;\n\t\tpa.push_back(j);\n\t}\n\tpj[\"paths\"] = pa;\n}\n\nstatic void _moonToJson(nlohmann::json &mj,const World &world)\n{\n\tchar tmp[4096];\n\tOSUtils::ztsnprintf(tmp,sizeof(tmp),\"%.16llx\",world.id());\n\tmj[\"id\"] = tmp;\n\tmj[\"timestamp\"] = world.timestamp();\n\tmj[\"signature\"] = Utils::hex(world.signature().data,ZT_C25519_SIGNATURE_LEN,tmp);\n\tmj[\"updatesMustBeSignedBy\"] = Utils::hex(world.updatesMustBeSignedBy().data,ZT_C25519_PUBLIC_KEY_LEN,tmp);\n\tnlohmann::json ra = nlohmann::json::array();\n\tfor(std::vector<World::Root>::const_iterator r(world.roots().begin());r!=world.roots().end();++r) {\n\t\tnlohmann::json rj;\n\t\trj[\"identity\"] = r->identity.toString(false,tmp);\n\t\tnlohmann::json eps = nlohmann::json::array();\n\t\tfor(std::vector<InetAddress>::const_iterator a(r->stableEndpoints.begin());a!=r->stableEndpoints.end();++a)\n\t\t\teps.push_back(a->toString(tmp));\n\t\trj[\"stableEndpoints\"] = eps;\n\t\tra.push_back(rj);\n\t}\n\tmj[\"roots\"] = ra;\n\tmj[\"waiting\"] = false;\n}\n\nclass OneServiceImpl;\n\nstatic int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);\nstatic void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData);\nstatic void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len);\nstatic int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen);\nstatic int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,void *tptr,int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl);\nstatic void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);\nstatic int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr);\nstatic int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result);\nstatic void StapFrameHandler(void *uptr,void *tptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);\n\nstatic int ShttpOnMessageBegin(http_parser *parser);\nstatic int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);\n#if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)\nstatic int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);\n#else\nstatic int ShttpOnStatus(http_parser *parser);\n#endif\nstatic int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);\nstatic int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);\nstatic int ShttpOnHeadersComplete(http_parser *parser);\nstatic int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);\nstatic int ShttpOnMessageComplete(http_parser *parser);\n\n#if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 1)\nstatic const struct http_parser_settings HTTP_PARSER_SETTINGS = {\n\tShttpOnMessageBegin,\n\tShttpOnUrl,\n\tShttpOnStatus,\n\tShttpOnHeaderField,\n\tShttpOnValue,\n\tShttpOnHeadersComplete,\n\tShttpOnBody,\n\tShttpOnMessageComplete\n};\n#else\nstatic const struct http_parser_settings HTTP_PARSER_SETTINGS = {\n\tShttpOnMessageBegin,\n\tShttpOnUrl,\n\tShttpOnHeaderField,\n\tShttpOnValue,\n\tShttpOnHeadersComplete,\n\tShttpOnBody,\n\tShttpOnMessageComplete\n};\n#endif\n\n\/**\n * A TCP connection and related state and buffers\n *\/\nstruct TcpConnection\n{\n\tenum {\n\t\tTCP_UNCATEGORIZED_INCOMING, \/\/ uncategorized incoming connection\n\t\tTCP_HTTP_INCOMING,\n\t\tTCP_HTTP_OUTGOING,\n\t\tTCP_TUNNEL_OUTGOING \/\/ TUNNELED mode proxy outbound connection\n\t} type;\n\n\tOneServiceImpl *parent;\n\tPhySocket *sock;\n\tInetAddress remoteAddr;\n\tuint64_t lastReceive;\n\n\t\/\/ Used for inbound HTTP connections\n\thttp_parser parser;\n\tunsigned long messageSize;\n\tstd::string currentHeaderField;\n\tstd::string currentHeaderValue;\n\tstd::string url;\n\tstd::string status;\n\tstd::map< std::string,std::string > headers;\n\n\tstd::string readq;\n\tstd::string writeq;\n\tMutex writeq_m;\n};\n\nstruct OneServiceIncomingPacket\n{\n\tuint64_t now;\n\tint64_t sock;\n\tstruct sockaddr_storage from;\n\tunsigned int size;\n\tuint8_t data[ZT_MAX_MTU];\n};\n\nclass OneServiceImpl : public OneService\n{\npublic:\n\t\/\/ begin member variables --------------------------------------------------\n\n\tconst std::string _homePath;\n\tstd::string _authToken;\n\tstd::string _controllerDbPath;\n\tconst std::string _networksPath;\n\tconst std::string _moonsPath;\n\n\tEmbeddedNetworkController *_controller;\n\tPhy<OneServiceImpl *> _phy;\n\tNode *_node;\n\tSoftwareUpdater *_updater;\n\tPhySocket *_localControlSocket4;\n\tPhySocket *_localControlSocket6;\n\tbool _updateAutoApply;\n\tbool _allowTcpFallbackRelay;\n\tbool _allowSecondaryPort;\n\tunsigned int _multipathMode;\n\tunsigned int _primaryPort;\n\tunsigned int _secondaryPort;\n\tunsigned int _tertiaryPort;\n\tvolatile unsigned int _udpPortPickerCounter;\n\n\t\/\/ Local configuration and memo-ized information from it\n\tjson _localConfig;\n\tHashtable< uint64_t,std::vector<InetAddress> > _v4Hints;\n\tHashtable< uint64_t,std::vector<InetAddress> > _v6Hints;\n\tHashtable< uint64_t,std::vector<InetAddress> > _v4Blacklists;\n\tHashtable< uint64_t,std::vector<InetAddress> > _v6Blacklists;\n\tstd::vector< InetAddress > _globalV4Blacklist;\n\tstd::vector< InetAddress > _globalV6Blacklist;\n\tstd::vector< InetAddress > _allowManagementFrom;\n\tstd::vector< std::string > _interfacePrefixBlacklist;\n\tMutex _localConfig_m;\n\n\tstd::vector<InetAddress> explicitBind;\n\n\t\/*\n\t * To attempt to handle NAT\/gateway craziness we use three local UDP ports:\n\t *\n\t * [0] is the normal\/default port, usually 9993\n\t * [1] is a port derived from our ZeroTier address\n\t * [2] is a port computed from the normal\/default for use with uPnP\/NAT-PMP mappings\n\t *\n\t * [2] exists because on some gateways trying to do regular NAT-t interferes\n\t * destructively with uPnP port mapping behavior in very weird buggy ways.\n\t * It's only used if uPnP\/NAT-PMP is enabled in this build.\n\t *\/\n\tunsigned int _ports[3];\n\tBinder _binder;\n\n\t\/\/ Time we last received a packet from a global address\n\tuint64_t _lastDirectReceiveFromGlobal;\n#ifdef ZT_TCP_FALLBACK_RELAY\n\tuint64_t _lastSendToGlobalV4;\n#endif\n\n\t\/\/ Last potential sleep\/wake event\n\tuint64_t _lastRestart;\n\n\t\/\/ Deadline for the next background task service function\n\tvolatile int64_t _nextBackgroundTaskDeadline;\n\n\t\/\/ Configured networks\n\tstruct NetworkState\n\t{\n\t\tNetworkState() :\n\t\t\ttap((EthernetTap *)0)\n\t\t{\n\t\t\t\/\/ Real defaults are in network 'up' code in network event handler\n\t\t\tsettings.allowManaged = true;\n\t\t\tsettings.allowGlobal = false;\n\t\t\tsettings.allowDefault = false;\n\t\t}\n\n\t\tstd::shared_ptr<EthernetTap> tap;\n\t\tZT_VirtualNetworkConfig config; \/\/ memcpy() of raw config from core\n\t\tstd::vector<InetAddress> managedIps;\n\t\tstd::list< SharedPtr<ManagedRoute> > managedRoutes;\n\t\tNetworkSettings settings;\n\t};\n\tstd::map<uint64_t,NetworkState> _nets;\n\tMutex _nets_m;\n\n\t\/\/ Active TCP\/IP connections\n\tstd::vector< TcpConnection * > _tcpConnections;\n\tMutex _tcpConnections_m;\n\tTcpConnection *_tcpFallbackTunnel;\n\n\t\/\/ Termination status information\n\tReasonForTermination _termReason;\n\tstd::string _fatalErrorMessage;\n\tMutex _termReason_m;\n\n\t\/\/ uPnP\/NAT-PMP port mapper if enabled\n\tbool _portMappingEnabled; \/\/ local.conf settings\n#ifdef ZT_USE_MINIUPNPC\n\tPortMapper *_portMapper;\n#endif\n\n\t\/\/ HashiCorp Vault Settings\n#if ZT_VAULT_SUPPORT\n\tbool _vaultEnabled;\n\tstd::string _vaultURL;\n\tstd::string _vaultToken;\n\tstd::string _vaultPath; \/\/ defaults to cubbyhole\/zerotier\/identity.secret for per-access key storage\n#endif\n\n\t\/\/ Set to false to force service to stop\n\tvolatile bool _run;\n\tMutex _run_m;\n\n\tMQConfig *_mqc;\n\n\t\/\/ end member variables ----------------------------------------------------\n\n\tOneServiceImpl(const char *hp,unsigned int port) :\n\t\t_homePath((hp) ? hp : \".\")\n\t\t,_controllerDbPath(_homePath + ZT_PATH_SEPARATOR_S \"controller.d\")\n\t\t,_networksPath(_homePath + ZT_PATH_SEPARATOR_S \"networks.d\")\n\t\t,_moonsPath(_homePath + ZT_PATH_SEPARATOR_S \"moons.d\")\n\t\t,_controller((EmbeddedNetworkController *)0)\n\t\t,_phy(this,false,true)\n\t\t,_node((Node *)0)\n\t\t,_updater((SoftwareUpdater *)0)\n\t\t,_localControlSocket4((PhySocket *)0)\n\t\t,_localControlSocket6((PhySocket *)0)\n\t\t,_updateAutoApply(false)\n\t\t,_primaryPort(port)\n\t\t,_udpPortPickerCounter(0)\n\t\t,_lastDirectReceiveFromGlobal(0)\n#ifdef ZT_TCP_FALLBACK_RELAY\n\t\t,_lastSendToGlobalV4(0)\n#endif\n\t\t,_lastRestart(0)\n\t\t,_nextBackgroundTaskDeadline(0)\n\t\t,_tcpFallbackTunnel((TcpConnection *)0)\n\t\t,_termReason(ONE_STILL_RUNNING)\n\t\t,_portMappingEnabled(true)\n#ifdef ZT_USE_MINIUPNPC\n\t\t,_portMapper((PortMapper *)0)\n#endif\n#ifdef ZT_VAULT_SUPPORT\n\t\t,_vaultEnabled(false)\n\t\t,_vaultURL()\n\t\t,_vaultToken()\n\t\t,_vaultPath(\"cubbyhole\/zerotier\")\n#endif\n\t\t,_run(true)\n\t\t,_mqc(NULL)\n\t{\n\t\t_ports[0] = 0;\n\t\t_ports[1] = 0;\n\t\t_ports[2] = 0;\n\n#if ZT_VAULT_SUPPORT\n\t\tcurl_global_init(CURL_GLOBAL_DEFAULT);\n#endif\n\t}\n\n\tvirtual ~OneServiceImpl()\n\t{\n\t\t_binder.closeAll(_phy);\n\t\t_phy.close(_localControlSocket4);\n\t\t_phy.close(_localControlSocket6);\n\n#if ZT_VAULT_SUPPORT\n\t\tcurl_global_cleanup();\n#endif\n\n#ifdef ZT_USE_MINIUPNPC\n\t\tdelete _portMapper;\n#endif\n\t\tdelete _controller;\n\t\tdelete _mqc;\n\t}\n\n\tvirtual ReasonForTermination run()\n\t{\n\t\ttry {\n\t\t\t{\n\t\t\t\tconst std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S \"authtoken.secret\");\n\t\t\t\tif (!OSUtils::readFile(authTokenPath.c_str(),_authToken)) {\n\t\t\t\t\tunsigned char foo[24];\n\t\t\t\t\tUtils::getSecureRandom(foo,sizeof(foo));\n\t\t\t\t\t_authToken = \"\";\n\t\t\t\t\tfor(unsigned int i=0;i<sizeof(foo);++i)\n\t\t\t\t\t\t_authToken.push_back(\"abcdefghijklmnopqrstuvwxyz0123456789\"[(unsigned long)foo[i] % 36]);\n\t\t\t\t\tif (!OSUtils::writeFile(authTokenPath.c_str(),_authToken)) {\n\t\t\t\t\t\tMutex::Lock _l(_termReason_m);\n\t\t\t\t\t\t_termReason = ONE_UNRECOVERABLE_ERROR;\n\t\t\t\t\t\t_fatalErrorMessage = \"authtoken.secret could not be written\";\n\t\t\t\t\t\treturn _termReason;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tOSUtils::lockDownFile(authTokenPath.c_str(),false);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t_authToken = _trimString(_authToken);\n\t\t\t}\n\n\t\t\t{\n\t\t\t\tstruct ZT_Node_Callbacks cb;\n\t\t\t\tcb.version = 0;\n\t\t\t\tcb.stateGetFunction = SnodeStateGetFunction;\n\t\t\t\tcb.statePutFunction = SnodeStatePutFunction;\n\t\t\t\tcb.wirePacketSendFunction = SnodeWirePacketSendFunction;\n\t\t\t\tcb.virtualNetworkFrameFunction = SnodeVirtualNetworkFrameFunction;\n\t\t\t\tcb.virtualNetworkConfigFunction = SnodeVirtualNetworkConfigFunction;\n\t\t\t\tcb.eventCallback = SnodeEventCallback;\n\t\t\t\tcb.pathCheckFunction = SnodePathCheckFunction;\n\t\t\t\tcb.pathLookupFunction = SnodePathLookupFunction;\n\t\t\t\t_node = new Node(this,(void *)0,&cb,OSUtils::now());\n\t\t\t}\n\n\t\t\t\/\/ local.conf\n\t\t\treadLocalSettings();\n\t\t\tapplyLocalConfig();\n\n\t\t\t\/\/ Make sure we can use the primary port, and hunt for one if configured to do so\n\t\t\tconst int portTrials = (_primaryPort == 0) ? 256 : 1; \/\/ if port is 0, pick random\n\t\t\tfor(int k=0;k<portTrials;++k) {\n\t\t\t\tif (_primaryPort == 0) {\n\t\t\t\t\tunsigned int randp = 0;\n\t\t\t\t\tUtils::getSecureRandom(&randp,sizeof(randp));\n\t\t\t\t\t_primaryPort = 20000 + (randp % 45500);\n\t\t\t\t}\n\t\t\t\tif (_trialBind(_primaryPort)) {\n\t\t\t\t\t_ports[0] = _primaryPort;\n\t\t\t\t} else {\n\t\t\t\t\t_primaryPort = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (_ports[0] == 0) {\n\t\t\t\tMutex::Lock _l(_termReason_m);\n\t\t\t\t_termReason = ONE_UNRECOVERABLE_ERROR;\n\t\t\t\t_fatalErrorMessage = \"cannot bind to local control interface port\";\n\t\t\t\treturn _termReason;\n\t\t\t}\n\n\t\t\t\/\/ Bind TCP control socket to 127.0.0.1 and ::1 as well for loopback TCP control socket queries\n\t\t\t{\n\t\t\t\tstruct sockaddr_in lo4;\n\t\t\t\tmemset(&lo4,0,sizeof(lo4));\n\t\t\t\tlo4.sin_family = AF_INET;\n\t\t\t\tlo4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001);\n\t\t\t\tlo4.sin_port = Utils::hton((uint16_t)_ports[0]);\n\t\t\t\t_localControlSocket4 = _phy.tcpListen((const struct sockaddr *)&lo4);\n\t\t\t\tstruct sockaddr_in6 lo6;\n\t\t\t\tmemset(&lo6,0,sizeof(lo6));\n\t\t\t\tlo6.sin6_family = AF_INET6;\n\t\t\t\tlo6.sin6_addr.s6_addr[15] = 1;\n\t\t\t\tlo6.sin6_port = lo4.sin_port;\n\t\t\t\t_localControlSocket6 = _phy.tcpListen((const struct sockaddr *)&lo6);\n\t\t\t}\n\n\t\t\t\/\/ Save primary port to a file so CLIs and GUIs can learn it easily\n\t\t\tchar portstr[64];\n\t\t\tOSUtils::ztsnprintf(portstr,sizeof(portstr),\"%u\",_ports[0]);\n\t\t\tOSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S \"zerotier-one.port\").c_str(),std::string(portstr));\n\n\t\t\t\/\/ Attempt to bind to a secondary port chosen from our ZeroTier address.\n\t\t\t\/\/ This exists because there are buggy NATs out there that fail if more\n\t\t\t\/\/ than one device behind the same NAT tries to use the same internal\n\t\t\t\/\/ private address port number. Buggy NATs are a running theme.\n\t\t\tif (_allowSecondaryPort) {\n\t\t\t\t_ports[1] = (_secondaryPort == 0) ? 20000 + ((unsigned int)_node->address() % 45500) : _secondaryPort;\n\t\t\t\tfor(int i=0;;++i) {\n\t\t\t\t\tif (i > 1000) {\n\t\t\t\t\t\t_ports[1] = 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (++_ports[1] >= 65536) {\n\t\t\t\t\t\t_ports[1] = 20000;\n\t\t\t\t\t}\n\t\t\t\t\tif (_trialBind(_ports[1]))\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n#ifdef ZT_USE_MINIUPNPC\n\t\t\tif (_portMappingEnabled) {\n\t\t\t\t\/\/ If we're running uPnP\/NAT-PMP, bind a *third* port for that. We can't\n\t\t\t\t\/\/ use the other two ports for that because some NATs do really funky\n\t\t\t\t\/\/ stuff with ports that are explicitly mapped that breaks things.\n\t\t\t\tif (_ports[1]) {\n\t\t\t\t\t_ports[2] = (_tertiaryPort == 0) ? _ports[1] : _tertiaryPort;\n\t\t\t\t\tfor(int i=0;;++i) {\n\t\t\t\t\t\tif (i > 1000) {\n\t\t\t\t\t\t\t_ports[2] = 0;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else if (++_ports[2] >= 65536) {\n\t\t\t\t\t\t\t_ports[2] = 20000;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (_trialBind(_ports[2]))\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (_ports[2]) {\n\t\t\t\t\t\tchar uniqueName[64];\n\t\t\t\t\t\tOSUtils::ztsnprintf(uniqueName,sizeof(uniqueName),\"ZeroTier\/%.10llx@%u\",_node->address(),_ports[2]);\n\t\t\t\t\t\t_portMapper = new PortMapper(_ports[2],uniqueName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n#endif\n\n\t\t\t\/\/ Delete legacy iddb.d if present (cleanup)\n\t\t\tOSUtils::rmDashRf((_homePath + ZT_PATH_SEPARATOR_S \"iddb.d\").c_str());\n\n\t\t\t\/\/ Network controller is now enabled by default for desktop and server\n\t\t\t_controller = new EmbeddedNetworkController(_node,_homePath.c_str(),_controllerDbPath.c_str(),_ports[0], _mqc);\n\t\t\t_node->setNetconfMaster((void *)_controller);\n\n\t\t\t\/\/ Join existing networks in networks.d\n\t\t\t{\n\t\t\t\tstd::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S \"networks.d\").c_str()));\n\t\t\t\tfor(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {\n\t\t\t\t\tstd::size_t dot = f->find_last_of('.');\n\t\t\t\t\tif ((dot == 16)&&(f->substr(16) == \".conf\"))\n\t\t\t\t\t\t_node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0,(void *)0);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Orbit existing moons in moons.d\n\t\t\t{\n\t\t\t\tstd::vector<std::string> moonsDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S \"moons.d\").c_str()));\n\t\t\t\tfor(std::vector<std::string>::iterator f(moonsDotD.begin());f!=moonsDotD.end();++f) {\n\t\t\t\t\tstd::size_t dot = f->find_last_of('.');\n\t\t\t\t\tif ((dot == 16)&&(f->substr(16) == \".moon\"))\n\t\t\t\t\t\t_node->orbit((void *)0,Utils::hexStrToU64(f->substr(0,dot).c_str()),0);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Main I\/O loop\n\t\t\t_nextBackgroundTaskDeadline = 0;\n\t\t\tint64_t clockShouldBe = OSUtils::now();\n\t\t\t_lastRestart = clockShouldBe;\n\t\t\tint64_t lastTapMulticastGroupCheck = 0;\n\t\t\tint64_t lastBindRefresh = 0;\n\t\t\tint64_t lastUpdateCheck = clockShouldBe;\n\t\t\tint64_t lastMultipathModeUpdate = 0;\n\t\t\tint64_t lastCleanedPeersDb = 0;\n\t\t\tint64_t lastLocalInterfaceAddressCheck = (clockShouldBe - ZT_LOCAL_INTERFACE_CHECK_INTERVAL) + 15000; \/\/ do this in 15s to give portmapper time to configure and other things time to settle\n\t\t\tint64_t lastLocalConfFileCheck = OSUtils::now();\n\t\t\tfor(;;) {\n\t\t\t\t_run_m.lock();\n\t\t\t\tif (!_run) {\n\t\t\t\t\t_run_m.unlock();\n\t\t\t\t\t_termReason_m.lock();\n\t\t\t\t\t_termReason = ONE_NORMAL_TERMINATION;\n\t\t\t\t\t_termReason_m.unlock();\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\t_run_m.unlock();\n\t\t\t\t}\n\n\t\t\t\tconst int64_t now = OSUtils::now();\n\n\t\t\t\t\/\/ Attempt to detect sleep\/wake events by detecting delay overruns\n\t\t\t\tbool restarted = false;\n\t\t\t\tif ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) {\n\t\t\t\t       \/\/_lastRestart = now;\n\t\t\t\t\trestarted = true;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Check for updates (if enabled)\n\t\t\t\tif ((_updater)&&((now - lastUpdateCheck) > 10000)) {\n\t\t\t\t\tlastUpdateCheck = now;\n\t\t\t\t\tif (_updater->check(now) && _updateAutoApply)\n\t\t\t\t\t\t_updater->apply();\n\t\t\t\t}\n\n\t\t\t\t\/\/ Reload local.conf if anything changed recently\n\t\t\t\tif ((now - lastLocalConfFileCheck) >= ZT_LOCAL_CONF_FILE_CHECK_INTERVAL) {\n\t\t\t\t\tlastLocalConfFileCheck = now;\n\t\t\t\t\tstruct stat result;\n\t\t\t\t\tif(stat((_homePath + ZT_PATH_SEPARATOR_S \"local.conf\").c_str(), &result)==0) {\n\t\t\t\t\t\tint64_t mod_time = result.st_mtime * 1000;\n\t\t\t\t\t\tif ((now - mod_time) <= ZT_LOCAL_CONF_FILE_CHECK_INTERVAL) {\n\t\t\t\t\t\t\treadLocalSettings();\n\t\t\t\t\t\t\tapplyLocalConfig();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)\n\t\t\t\tif (((now - lastBindRefresh) >= (_multipathMode ? ZT_BINDER_REFRESH_PERIOD \/ 8 : ZT_BINDER_REFRESH_PERIOD))||(restarted)) {\n\t\t\t\t\tlastBindRefresh = now;\n\t\t\t\t\tunsigned int p[3];\n\t\t\t\t\tunsigned int pc = 0;\n\t\t\t\t\tfor(int i=0;i<3;++i) {\n\t\t\t\t\t\tif (_ports[i])\n\t\t\t\t\t\t\tp[pc++] = _ports[i];\n\t\t\t\t\t}\n\t\t\t\t\t_binder.refresh(_phy,p,pc,explicitBind,*this);\n\t\t\t\t\t{\n\t\t\t\t\t\tMutex::Lock _l(_nets_m);\n\t\t\t\t\t\tfor(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n) {\n\t\t\t\t\t\t\tif (n->second.tap)\n\t\t\t\t\t\t\t\tsyncManagedStuff(n->second,false,true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ Update multipath mode (if needed)\n\t\t\t\tif (((now - lastMultipathModeUpdate) >= ZT_BINDER_REFRESH_PERIOD \/ 8)||(restarted)) {\n\t\t\t\t\tlastMultipathModeUpdate = now;\n\t\t\t\t\t_node->setMultipathMode(_multipathMode);\n\t\t\t\t}\n\n\t\t\t\t\/\/ Run background task processor in core if it's time to do so\n\t\t\t\tint64_t dl = _nextBackgroundTaskDeadline;\n\t\t\t\tif (dl <= now) {\n\t\t\t\t\t_node->processBackgroundTasks((void *)0,now,&_nextBackgroundTaskDeadline);\n\t\t\t\t\tdl = _nextBackgroundTaskDeadline;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Close TCP fallback tunnel if we have direct UDP\n\t\t\t\tif ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER \/ 2)))\n\t\t\t\t\t_phy.close(_tcpFallbackTunnel->sock);\n\n\t\t\t\t\/\/ Sync multicast group memberships\n\t\t\t\tif ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {\n\t\t\t\t\tlastTapMulticastGroupCheck = now;\n\t\t\t\t\tstd::vector< std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > > > mgChanges;\n\t\t\t\t\t{\n\t\t\t\t\t\tMutex::Lock _l(_nets_m);\n\t\t\t\t\t\tmgChanges.reserve(_nets.size() + 1);\n\t\t\t\t\t\tfor(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {\n\t\t\t\t\t\t\tif (n->second.tap) {\n\t\t\t\t\t\t\t\tmgChanges.push_back(std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > >(n->first,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> >()));\n\t\t\t\t\t\t\t\tn->second.tap->scanMulticastGroups(mgChanges.back().second.first,mgChanges.back().second.second);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor(std::vector< std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > > >::iterator c(mgChanges.begin());c!=mgChanges.end();++c) {\n\t\t\t\t\t\tfor(std::vector<MulticastGroup>::iterator m(c->second.first.begin());m!=c->second.first.end();++m)\n\t\t\t\t\t\t\t_node->multicastSubscribe((void *)0,c->first,m->mac().toInt(),m->adi());\n\t\t\t\t\t\tfor(std::vector<MulticastGroup>::iterator m(c->second.second.begin());m!=c->second.second.end();++m)\n\t\t\t\t\t\t\t_node->multicastUnsubscribe(c->first,m->mac().toInt(),m->adi());\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ Sync information about physical network interfaces\n\t\t\t\tif ((now - lastLocalInterfaceAddressCheck) >= (_multipathMode ? ZT_LOCAL_INTERFACE_CHECK_INTERVAL \/ 8 : ZT_LOCAL_INTERFACE_CHECK_INTERVAL)) {\n\t\t\t\t\tlastLocalInterfaceAddressCheck = now;\n\n\t\t\t\t\t_node->clearLocalInterfaceAddresses();\n\n#ifdef ZT_USE_MINIUPNPC\n\t\t\t\t\tif (_portMapper) {\n\t\t\t\t\t\tstd::vector<InetAddress> mappedAddresses(_portMapper->get());\n\t\t\t\t\t\tfor(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)\n\t\t\t\t\t\t\t_node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));\n\t\t\t\t\t}\n#endif\n\n\t\t\t\t\tstd::vector<InetAddress> boundAddrs(_binder.allBoundLocalInterfaceAddresses());\n\t\t\t\t\tfor(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)\n\t\t\t\t\t\t_node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));\n\t\t\t\t}\n\n\t\t\t\t\/\/ Clean peers.d periodically\n\t\t\t\tif ((now - lastCleanedPeersDb) >= 3600000) {\n\t\t\t\t\tlastCleanedPeersDb = now;\n\t\t\t\t\tOSUtils::cleanDirectory((_homePath + ZT_PATH_SEPARATOR_S \"peers.d\").c_str(),now - 2592000000LL); \/\/ delete older than 30 days\n\t\t\t\t}\n\n\t\t\t\tconst unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;\n\t\t\t\tclockShouldBe = now + (uint64_t)delay;\n\t\t\t\t_phy.poll(delay);\n\t\t\t}\n\t\t} catch (std::exception &e) {\n\t\t\tMutex::Lock _l(_termReason_m);\n\t\t\t_termReason = ONE_UNRECOVERABLE_ERROR;\n\t\t\t_fatalErrorMessage = std::string(\"unexpected exception in main thread: \")+e.what();\n\t\t} catch ( ... ) {\n\t\t\tMutex::Lock _l(_termReason_m);\n\t\t\t_termReason = ONE_UNRECOVERABLE_ERROR;\n\t\t\t_fatalErrorMessage = \"unexpected exception in main thread: unknown exception\";\n\t\t}\n\n\t\ttry {\n\t\t\tMutex::Lock _l(_tcpConnections_m);\n\t\t\twhile (!_tcpConnections.empty())\n\t\t\t\t_phy.close((*_tcpConnections.begin())->sock);\n\t\t} catch ( ... ) {}\n\n\t\t{\n\t\t\tMutex::Lock _l(_nets_m);\n\t\t\t_nets.clear();\n\t\t}\n\n\t\tdelete _updater;\n\t\t_updater = (SoftwareUpdater *)0;\n\t\tdelete _node;\n\t\t_node = (Node *)0;\n\n\t\treturn _termReason;\n\t}\n\n\tvoid readLocalSettings()\n\t{\n\t\t\/\/ Read local configuration\n\t\tstd::map<InetAddress,ZT_PhysicalPathConfiguration> ppc;\n\n\t\t\/\/ LEGACY: support old \"trustedpaths\" flat file\n\t\tFILE *trustpaths = fopen((_homePath + ZT_PATH_SEPARATOR_S \"trustedpaths\").c_str(),\"r\");\n\t\tif (trustpaths) {\n\t\t\tfprintf(stderr,\"WARNING: 'trustedpaths' flat file format is deprecated in favor of path definitions in local.conf\" ZT_EOL_S);\n\t\t\tchar buf[1024];\n\t\t\twhile (fgets(buf,sizeof(buf),trustpaths)) {\n\t\t\t\tint fno = 0;\n\t\t\t\tchar *saveptr = (char *)0;\n\t\t\t\tuint64_t trustedPathId = 0;\n\t\t\t\tInetAddress trustedPathNetwork;\n\t\t\t\tfor(char *f=Utils::stok(buf,\"=\\r\\n \\t\",&saveptr);(f);f=Utils::stok((char *)0,\"=\\r\\n \\t\",&saveptr)) {\n\t\t\t\t\tif (fno == 0) {\n\t\t\t\t\t\ttrustedPathId = Utils::hexStrToU64(f);\n\t\t\t\t\t} else if (fno == 1) {\n\t\t\t\t\t\ttrustedPathNetwork = InetAddress(f);\n\t\t\t\t\t} else break;\n\t\t\t\t\t++fno;\n\t\t\t\t}\n\t\t\t\tif ( (trustedPathId != 0) && ((trustedPathNetwork.ss_family == AF_INET)||(trustedPathNetwork.ss_family == AF_INET6)) && (trustedPathNetwork.netmaskBits() > 0) ) {\n\t\t\t\t\tppc[trustedPathNetwork].trustedPathId = trustedPathId;\n\t\t\t\t\tppc[trustedPathNetwork].mtu = 0; \/\/ use default\n\t\t\t\t}\n\t\t\t}\n\t\t\tfclose(trustpaths);\n\t\t}\n\n\t\t\/\/ Read local config file\n\t\tMutex::Lock _l2(_localConfig_m);\n\t\tstd::string lcbuf;\n\t\tif (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S \"local.conf\").c_str(),lcbuf)) {\n\t\t\tif (lcbuf.length() > 0) {\n\t\t\t\ttry {\n\t\t\t\t\t_localConfig = OSUtils::jsonParse(lcbuf);\n\t\t\t\t\tif (!_localConfig.is_object()) {\n\t\t\t\t\t\tfprintf(stderr,\"ERROR: unable to parse local.conf (root element is not a JSON object)\" ZT_EOL_S);\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t} catch ( ... ) {\n\t\t\t\t\tfprintf(stderr,\"ERROR: unable to parse local.conf (invalid JSON)\" ZT_EOL_S);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Get any trusted paths in local.conf (we'll parse the rest of physical[] elsewhere)\n\t\tjson &physical = _localConfig[\"physical\"];\n\t\tif (physical.is_object()) {\n\t\t\tfor(json::iterator phy(physical.begin());phy!=physical.end();++phy) {\n\t\t\t\tInetAddress net(OSUtils::jsonString(phy.key(),\"\").c_str());\n\t\t\t\tif (net) {\n\t\t\t\t\tif (phy.value().is_object()) {\n\t\t\t\t\t\tuint64_t tpid;\n\t\t\t\t\t\tif ((tpid = OSUtils::jsonInt(phy.value()[\"trustedPathId\"],0ULL)) != 0ULL) {\n\t\t\t\t\t\t\tif ((net.ss_family == AF_INET)||(net.ss_family == AF_INET6))\n\t\t\t\t\t\t\t\tppc[net].trustedPathId = tpid;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tppc[net].mtu = (int)OSUtils::jsonInt(phy.value()[\"mtu\"],0ULL); \/\/ 0 means use default\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tjson &settings = _localConfig[\"settings\"];\n\t\tif (settings.is_object()) {\n\t\t\t\/\/ Allow controller DB path to be put somewhere else\n\t\t\tconst std::string cdbp(OSUtils::jsonString(settings[\"controllerDbPath\"],\"\"));\n\t\t\tif (cdbp.length() > 0)\n\t\t\t\t_controllerDbPath = cdbp;\n\n\t\t\tjson &rmq = settings[\"rabbitmq\"];\n\t\t\tif (rmq.is_object() && _mqc == NULL) {\n\t\t\t\tfprintf(stderr, \"Reading RabbitMQ Config\\n\");\n\t\t\t\t_mqc = new MQConfig;\n\t\t\t\t_mqc->port = rmq[\"port\"];\n\t\t\t\t_mqc->host = OSUtils::jsonString(rmq[\"host\"], \"\").c_str();\n\t\t\t\t_mqc->username = OSUtils::jsonString(rmq[\"username\"], \"\").c_str();\n\t\t\t\t_mqc->password = OSUtils::jsonString(rmq[\"password\"], \"\").c_str();\n\t\t\t}\n\n\t\t\t\/\/ Bind to wildcard instead of to specific interfaces (disables full tunnel capability)\n\t\t\tjson &bind = settings[\"bind\"];\n\t\t\tif (bind.is_array()) {\n\t\t\t\tfor(unsigned long i=0;i<bind.size();++i) {\n\t\t\t\t\tconst std::string ips(OSUtils::jsonString(bind[i],\"\"));\n\t\t\t\t\tif (ips.length() > 0) {\n\t\t\t\t\t\tInetAddress ip(ips.c_str());\n\t\t\t\t\t\tif ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6))\n\t\t\t\t\t\t\texplicitBind.push_back(ip);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Set trusted paths if there are any\n\t\tif (ppc.size() > 0) {\n\t\t\tfor(std::map<InetAddress,ZT_PhysicalPathConfiguration>::iterator i(ppc.begin());i!=ppc.end();++i)\n\t\t\t\t_node->setPhysicalPathConfiguration(reinterpret_cast<const struct sockaddr_storage *>(&(i->first)),&(i->second));\n\t\t}\n\t}\n\n\tvirtual ReasonForTermination reasonForTermination() const\n\t{\n\t\tMutex::Lock _l(_termReason_m);\n\t\treturn _termReason;\n\t}\n\n\tvirtual std::string fatalErrorMessage() const\n\t{\n\t\tMutex::Lock _l(_termReason_m);\n\t\treturn _fatalErrorMessage;\n\t}\n\n\tvirtual std::string portDeviceName(uint64_t nwid) const\n\t{\n\t\tMutex::Lock _l(_nets_m);\n\t\tstd::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));\n\t\tif ((n != _nets.end())&&(n->second.tap))\n\t\t\treturn n->second.tap->deviceName();\n\t\telse return std::string();\n\t}\n\n#ifdef ZT_SDK\n\tvirtual std::string givenHomePath()\n\t{\n\t\treturn _homePath;\n\t}\n\n\tvoid getRoutes(uint64_t nwid, void *routeArray, unsigned int *numRoutes)\n\t{\n\t\tMutex::Lock _l(_nets_m);\n\t\tNetworkState &n = _nets[nwid];\n\t\t*numRoutes = *numRoutes < n.config.routeCount ? *numRoutes : n.config.routeCount;\n\t\tfor(unsigned int i=0; i<*numRoutes; i++) {\n\t\t\tZT_VirtualNetworkRoute *vnr = (ZT_VirtualNetworkRoute*)routeArray;\n\t\t\tmemcpy(&vnr[i], &(n.config.routes[i]), sizeof(ZT_VirtualNetworkRoute));\n\t\t}\n\t}\n\n\tvirtual Node *getNode()\n\t{\n\t\treturn _node;\n\t}\n#endif \/\/ ZT_SDK\n\n\tvirtual void terminate()\n\t{\n\t\t_run_m.lock();\n\t\t_run = false;\n\t\t_run_m.unlock();\n\t\t_phy.whack();\n\t}\n\n\tvirtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const\n\t{\n\t\tMutex::Lock _l(_nets_m);\n\t\tstd::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));\n\t\tif (n == _nets.end())\n\t\t\treturn false;\n\t\tsettings = n->second.settings;\n\t\treturn true;\n\t}\n\n\tvirtual bool setNetworkSettings(const uint64_t nwid,const NetworkSettings &settings)\n\t{\n\t\tMutex::Lock _l(_nets_m);\n\n\t\tstd::map<uint64_t,NetworkState>::iterator n(_nets.find(nwid));\n\t\tif (n == _nets.end())\n\t\t\treturn false;\n\t\tn->second.settings = settings;\n\n\t\tchar nlcpath[4096];\n\t\tOSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),\"%s\" ZT_PATH_SEPARATOR_S \"%.16llx.local.conf\",_networksPath.c_str(),nwid);\n\t\tFILE *out = fopen(nlcpath,\"w\");\n\t\tif (out) {\n\t\t\tfprintf(out,\"allowManaged=%d\\n\",(int)n->second.settings.allowManaged);\n\t\t\tfprintf(out,\"allowGlobal=%d\\n\",(int)n->second.settings.allowGlobal);\n\t\t\tfprintf(out,\"allowDefault=%d\\n\",(int)n->second.settings.allowDefault);\n\t\t\tfclose(out);\n\t\t}\n\n\t\tif (n->second.tap)\n\t\t\tsyncManagedStuff(n->second,true,true);\n\n\t\treturn true;\n\t}\n\n\t\/\/ =========================================================================\n\t\/\/ Internal implementation methods for control plane, route setup, etc.\n\t\/\/ =========================================================================\n\n\tinline unsigned int handleControlPlaneHttpRequest(\n\t\tconst InetAddress &fromAddress,\n\t\tunsigned int httpMethod,\n\t\tconst std::string &path,\n\t\tconst std::map<std::string,std::string> &headers,\n\t\tconst std::string &body,\n\t\tstd::string &responseBody,\n\t\tstd::string &responseContentType)\n\t{\n\t\tchar tmp[256];\n\t\tunsigned int scode = 404;\n\t\tjson res;\n\t\tstd::vector<std::string> ps(OSUtils::split(path.c_str(),\"\/\",\"\",\"\"));\n\t\tstd::map<std::string,std::string> urlArgs;\n\n\t\t\/* Note: this is kind of restricted in what it'll take. It does not support\n\t\t * URL encoding, and \/'s in URL args will screw it up. But the only URL args\n\t\t * it really uses in ?jsonp=funcionName, and otherwise it just takes simple\n\t\t * paths to simply-named resources. *\/\n\t\tif (ps.size() > 0) {\n\t\t\tstd::size_t qpos = ps[ps.size() - 1].find('?');\n\t\t\tif (qpos != std::string::npos) {\n\t\t\t\tstd::string args(ps[ps.size() - 1].substr(qpos + 1));\n\t\t\t\tps[ps.size() - 1] = ps[ps.size() - 1].substr(0,qpos);\n\t\t\t\tstd::vector<std::string> asplit(OSUtils::split(args.c_str(),\"&\",\"\",\"\"));\n\t\t\t\tfor(std::vector<std::string>::iterator a(asplit.begin());a!=asplit.end();++a) {\n\t\t\t\t\tstd::size_t eqpos = a->find('=');\n\t\t\t\t\tif (eqpos == std::string::npos)\n\t\t\t\t\t\turlArgs[*a] = \"\";\n\t\t\t\t\telse urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn 404;\n\t\t}\n\n\t\tbool isAuth = false;\n\t\t{\n\t\t\tstd::map<std::string,std::string>::const_iterator ah(headers.find(\"x-zt1-auth\"));\n\t\t\tif ((ah != headers.end())&&(_authToken == ah->second)) {\n\t\t\t\tisAuth = true;\n\t\t\t} else {\n\t\t\t\tah = urlArgs.find(\"auth\");\n\t\t\t\tif ((ah != urlArgs.end())&&(_authToken == ah->second))\n\t\t\t\t\tisAuth = true;\n\t\t\t}\n\t\t}\n\n#ifdef __SYNOLOGY__\n\t\t\/\/ Authenticate via Synology's built-in cgi script\n\t\tif (!isAuth) {\n\t\t\tint synotoken_pos = path.find(\"SynoToken\");\n\t\t\tint argpos = path.find(\"?\");\n\t\t\tif(synotoken_pos != std::string::npos && argpos != std::string::npos) {\n\t\t\t\tstd::string cookie = path.substr(argpos+1, synotoken_pos-(argpos+1));\n\t\t\t\tstd::string synotoken = path.substr(synotoken_pos);\n\t\t\t\tstd::string cookie_val = cookie.substr(cookie.find(\"=\")+1);\n\t\t\t\tstd::string synotoken_val = synotoken.substr(synotoken.find(\"=\")+1);\n\t\t\t\t\/\/ Set necessary env for auth script\n\t\t\t\tstd::map<std::string,std::string>::const_iterator ah2(headers.find(\"x-forwarded-for\"));\n\t\t\t\tsetenv(\"HTTP_COOKIE\", cookie_val.c_str(), true);\n\t\t\t\tsetenv(\"HTTP_X_SYNO_TOKEN\", synotoken_val.c_str(), true);\n\t\t\t\tsetenv(\"REMOTE_ADDR\", ah2->second.c_str(),true);\n\t\t\t\tchar user[256], buf[1024];\n\t\t\t\tFILE *fp = NULL;\n\t\t\t\tbzero(user, 256);\n\t\t\t\tfp = popen(\"\/usr\/syno\/synoman\/webman\/modules\/authenticate.cgi\", \"r\");\n\t\t\t\tif(!fp)\n\t\t\t\t\tisAuth = false;\n\t\t\t\telse {\n\t\t\t\t\tbzero(buf, sizeof(buf));\n\t\t\t\t\tfread(buf, 1024, 1, fp);\n\t\t\t\t\tif(strlen(buf) > 0) {\n\t\t\t\t\t\tsnprintf(user, 256, \"%s\", buf);\n\t\t\t\t\t\tisAuth = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpclose(fp);\n\t\t\t}\n\t\t}\n#endif\n\n\t\tif (httpMethod == HTTP_GET) {\n\t\t\tif (isAuth) {\n\t\t\t\tif (ps[0] == \"status\") {\n\t\t\t\t\tZT_NodeStatus status;\n\t\t\t\t\t_node->status(&status);\n\n\t\t\t\t\tOSUtils::ztsnprintf(tmp,sizeof(tmp),\"%.10llx\",status.address);\n\t\t\t\t\tres[\"address\"] = tmp;\n\t\t\t\t\tres[\"publicIdentity\"] = status.publicIdentity;\n\t\t\t\t\tres[\"online\"] = (bool)(status.online != 0);\n\t\t\t\t\tres[\"tcpFallbackActive\"] = (_tcpFallbackTunnel != (TcpConnection *)0);\n\t\t\t\t\tres[\"versionMajor\"] = ZEROTIER_ONE_VERSION_MAJOR;\n\t\t\t\t\tres[\"versionMinor\"] = ZEROTIER_ONE_VERSION_MINOR;\n\t\t\t\t\tres[\"versionRev\"] = ZEROTIER_ONE_VERSION_REVISION;\n\t\t\t\t\tres[\"versionBuild\"] = ZEROTIER_ONE_VERSION_BUILD;\n\t\t\t\t\tOSUtils::ztsnprintf(tmp,sizeof(tmp),\"%d.%d.%d\",ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);\n\t\t\t\t\tres[\"version\"] = tmp;\n\t\t\t\t\tres[\"clock\"] = OSUtils::now();\n\n\t\t\t\t\t{\n\t\t\t\t\t\tMutex::Lock _l(_localConfig_m);\n\t\t\t\t\t\tres[\"config\"] = _localConfig;\n\t\t\t\t\t}\n\t\t\t\t\tjson &settings = res[\"config\"][\"settings\"];\n\t\t\t\t\tsettings[\"primaryPort\"] = OSUtils::jsonInt(settings[\"primaryPort\"],(uint64_t)_primaryPort) & 0xffff;\n\t\t\t\t\tsettings[\"allowTcpFallbackRelay\"] = OSUtils::jsonBool(settings[\"allowTcpFallbackRelay\"],_allowTcpFallbackRelay);\n\n\t\t\t\t\tif (_multipathMode) {\n\t\t\t\t\t\tjson &multipathConfig = res[\"multipath\"];\n\t\t\t\t\t\tZT_PeerList *pl = _node->peers();\n\t\t\t\t\t\tchar peerAddrStr[256];\n\t\t\t\t\t\tif (pl) {\n\t\t\t\t\t\t\tfor(unsigned long i=0;i<pl->peerCount;++i) {\n\t\t\t\t\t\t\t\tif (pl->peers[i].hadAggregateLink) {\n\t\t\t\t\t\t\t\t\tnlohmann::json pj;\n\t\t\t\t\t\t\t\t\t_peerAggregateLinkToJson(pj,&(pl->peers[i]));\n\t\t\t\t\t\t\t\t\tOSUtils::ztsnprintf(peerAddrStr,sizeof(peerAddrStr),\"%.10llx\",pl->peers[i].address);\n\t\t\t\t\t\t\t\t\tmultipathConfig[peerAddrStr] = (pj);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n#ifdef ZT_USE_MINIUPNPC\n\t\t\t\t\tsettings[\"portMappingEnabled\"] = OSUtils::jsonBool(settings[\"portMappingEnabled\"],true);\n#else\n\t\t\t\t\tsettings[\"portMappingEnabled\"] = false; \/\/ not supported in build\n#endif\n#ifndef ZT_SDK\n\t\t\t\t\tsettings[\"softwareUpdate\"] = OSUtils::jsonString(settings[\"softwareUpdate\"],ZT_SOFTWARE_UPDATE_DEFAULT);\n\t\t\t\t\tsettings[\"softwareUpdateChannel\"] = OSUtils::jsonString(settings[\"softwareUpdateChannel\"],ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL);\n#endif\n\t\t\t\t\tconst World planet(_node->planet());\n\t\t\t\t\tres[\"planetWorldId\"] = planet.id();\n\t\t\t\t\tres[\"planetWorldTimestamp\"] = planet.timestamp();\n\n\t\t\t\t\tscode = 200;\n\t\t\t\t} else if (ps[0] == \"moon\") {\n\t\t\t\t\tstd::vector<World> moons(_node->moons());\n\t\t\t\t\tif (ps.size() == 1) {\n\t\t\t\t\t\t\/\/ Return [array] of all moons\n\n\t\t\t\t\t\tres = json::array();\n\t\t\t\t\t\tfor(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {\n\t\t\t\t\t\t\tjson mj;\n\t\t\t\t\t\t\t_moonToJson(mj,*m);\n\t\t\t\t\t\t\tres.push_back(mj);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tscode = 200;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ Return a single moon by ID\n\n\t\t\t\t\t\tconst uint64_t id = Utils::hexStrToU64(ps[1].c_str());\n\t\t\t\t\t\tfor(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {\n\t\t\t\t\t\t\tif (m->id() == id) {\n\t\t\t\t\t\t\t\t_moonToJson(res,*m);\n\t\t\t\t\t\t\t\tscode = 200;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t} else if (ps[0] == \"network\") {\n\t\t\t\t\tZT_VirtualNetworkList *nws = _node->networks();\n\t\t\t\t\tif (nws) {\n\t\t\t\t\t\tif (ps.size() == 1) {\n\t\t\t\t\t\t\t\/\/ Return [array] of all networks\n\n\t\t\t\t\t\t\tres = nlohmann::json::array();\n\t\t\t\t\t\t\tfor(unsigned long i=0;i<nws->networkCount;++i) {\n\t\t\t\t\t\t\t\tOneService::NetworkSettings localSettings;\n\t\t\t\t\t\t\t\tgetNetworkSettings(nws->networks[i].nwid,localSettings);\n\t\t\t\t\t\t\t\tnlohmann::json nj;\n\t\t\t\t\t\t\t\t_networkToJson(nj,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);\n\t\t\t\t\t\t\t\tres.push_back(nj);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tscode = 200;\n\t\t\t\t\t\t} else if (ps.size() == 2) {\n\t\t\t\t\t\t\t\/\/ Return a single network by ID or 404 if not found\n\n\t\t\t\t\t\t\tconst uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());\n\t\t\t\t\t\t\tfor(unsigned long i=0;i<nws->networkCount;++i) {\n\t\t\t\t\t\t\t\tif (nws->networks[i].nwid == wantnw) {\n\t\t\t\t\t\t\t\t\tOneService::NetworkSettings localSettings;\n\t\t\t\t\t\t\t\t\tgetNetworkSettings(nws->networks[i].nwid,localSettings);\n\t\t\t\t\t\t\t\t\t_networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);\n\t\t\t\t\t\t\t\t\tscode = 200;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} else scode = 404;\n\t\t\t\t\t\t_node->freeQueryResult((void *)nws);\n\t\t\t\t\t} else scode = 500;\n\t\t\t\t} else if (ps[0] == \"peer\") {\n\t\t\t\t\tZT_PeerList *pl = _node->peers();\n\t\t\t\t\tif (pl) {\n\t\t\t\t\t\tif (ps.size() == 1) {\n\t\t\t\t\t\t\t\/\/ Return [array] of all peers\n\n\t\t\t\t\t\t\tres = nlohmann::json::array();\n\t\t\t\t\t\t\tfor(unsigned long i=0;i<pl->peerCount;++i) {\n\t\t\t\t\t\t\t\tnlohmann::json pj;\n\t\t\t\t\t\t\t\t_peerToJson(pj,&(pl->peers[i]));\n\t\t\t\t\t\t\t\tres.push_back(pj);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tscode = 200;\n\t\t\t\t\t\t} else if (ps.size() == 2) {\n\t\t\t\t\t\t\t\/\/ Return a single peer by ID or 404 if not found\n\n\t\t\t\t\t\t\tuint64_t wantp = Utils::hexStrToU64(ps[1].c_str());\n\t\t\t\t\t\t\tfor(unsigned long i=0;i<pl->peerCount;++i) {\n\t\t\t\t\t\t\t\tif (pl->peers[i].address == wantp) {\n\t\t\t\t\t\t\t\t\t_peerToJson(res,&(pl->peers[i]));\n\t\t\t\t\t\t\t\t\tscode = 200;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} else scode = 404;\n\t\t\t\t\t\t_node->freeQueryResult((void *)pl);\n\t\t\t\t\t} else scode = 500;\n\t\t\t\t} else {\n\t\t\t\t\tif (_controller) {\n\t\t\t\t\t\tscode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);\n\t\t\t\t\t} else scode = 404;\n\t\t\t\t}\n\n\t\t\t} else scode = 401; \/\/ isAuth == false\n\t\t} else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {\n\t\t\tif (isAuth) {\n\n\t\t\t\tif (ps[0] == \"moon\") {\n\t\t\t\t\tif (ps.size() == 2) {\n\n\t\t\t\t\t\tuint64_t seed = 0;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tjson j(OSUtils::jsonParse(body));\n\t\t\t\t\t\t\tif (j.is_object()) {\n\t\t\t\t\t\t\t\tseed = Utils::hexStrToU64(OSUtils::jsonString(j[\"seed\"],\"0\").c_str());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (std::exception &exc) {\n\t\t\t\t\t\t} catch ( ... ) {\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstd::vector<World> moons(_node->moons());\n\t\t\t\t\t\tconst uint64_t id = Utils::hexStrToU64(ps[1].c_str());\n\t\t\t\t\t\tfor(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {\n\t\t\t\t\t\t\tif (m->id() == id) {\n\t\t\t\t\t\t\t\t_moonToJson(res,*m);\n\t\t\t\t\t\t\t\tscode = 200;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ((scode != 200)&&(seed != 0)) {\n\t\t\t\t\t\t\tchar tmp[64];\n\t\t\t\t\t\t\tOSUtils::ztsnprintf(tmp,sizeof(tmp),\"%.16llx\",id);\n\t\t\t\t\t\t\tres[\"id\"] = tmp;\n\t\t\t\t\t\t\tres[\"roots\"] = json::array();\n\t\t\t\t\t\t\tres[\"timestamp\"] = 0;\n\t\t\t\t\t\t\tres[\"signature\"] = json();\n\t\t\t\t\t\t\tres[\"updatesMustBeSignedBy\"] = json();\n\t\t\t\t\t\t\tres[\"waiting\"] = true;\n\t\t\t\t\t\t\t_node->orbit((void *)0,id,seed);\n\t\t\t\t\t\t\tscode = 200;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else scode = 404;\n\t\t\t\t} else if (ps[0] == \"network\") {\n\t\t\t\t\tif (ps.size() == 2) {\n\n\t\t\t\t\t\tuint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());\n\t\t\t\t\t\t_node->join(wantnw,(void *)0,(void *)0); \/\/ does nothing if we are a member\n\t\t\t\t\t\tZT_VirtualNetworkList *nws = _node->networks();\n\t\t\t\t\t\tif (nws) {\n\t\t\t\t\t\t\tfor(unsigned long i=0;i<nws->networkCount;++i) {\n\t\t\t\t\t\t\t\tif (nws->networks[i].nwid == wantnw) {\n\t\t\t\t\t\t\t\t\tOneService::NetworkSettings localSettings;\n\t\t\t\t\t\t\t\t\tgetNetworkSettings(nws->networks[i].nwid,localSettings);\n\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tjson j(OSUtils::jsonParse(body));\n\t\t\t\t\t\t\t\t\t\tif (j.is_object()) {\n\t\t\t\t\t\t\t\t\t\t\tjson &allowManaged = j[\"allowManaged\"];\n\t\t\t\t\t\t\t\t\t\t\tif (allowManaged.is_boolean()) localSettings.allowManaged = (bool)allowManaged;\n\t\t\t\t\t\t\t\t\t\t\tjson &allowGlobal = j[\"allowGlobal\"];\n\t\t\t\t\t\t\t\t\t\t\tif (allowGlobal.is_boolean()) localSettings.allowGlobal = (bool)allowGlobal;\n\t\t\t\t\t\t\t\t\t\t\tjson &allowDefault = j[\"allowDefault\"];\n\t\t\t\t\t\t\t\t\t\t\tif (allowDefault.is_boolean()) localSettings.allowDefault = (bool)allowDefault;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} catch (std::exception &exc) {\n\t\t\t\t\t\t\t\t\t} catch ( ... ) {\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tsetNetworkSettings(nws->networks[i].nwid,localSettings);\n\t\t\t\t\t\t\t\t\t_networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);\n\n\t\t\t\t\t\t\t\t\tscode = 200;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t_node->freeQueryResult((void *)nws);\n\t\t\t\t\t\t} else scode = 500;\n\n\t\t\t\t\t} else scode = 404;\n\t\t\t\t} else {\n\t\t\t\t\tif (_controller)\n\t\t\t\t\t\tscode = _controller->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);\n\t\t\t\t\telse scode = 404;\n\t\t\t\t}\n\n\t\t\t} else scode = 401; \/\/ isAuth == false\n\t\t} else if (httpMethod == HTTP_DELETE) {\n\t\t\tif (isAuth) {\n\n\t\t\t\tif (ps[0] == \"moon\") {\n\t\t\t\t\tif (ps.size() == 2) {\n\t\t\t\t\t\t_node->deorbit((void *)0,Utils::hexStrToU64(ps[1].c_str()));\n\t\t\t\t\t\tres[\"result\"] = true;\n\t\t\t\t\t\tscode = 200;\n\t\t\t\t\t} \/\/ else 404\n\t\t\t\t} else if (ps[0] == \"network\") {\n\t\t\t\t\tZT_VirtualNetworkList *nws = _node->networks();\n\t\t\t\t\tif (nws) {\n\t\t\t\t\t\tif (ps.size() == 2) {\n\t\t\t\t\t\t\tuint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());\n\t\t\t\t\t\t\tfor(unsigned long i=0;i<nws->networkCount;++i) {\n\t\t\t\t\t\t\t\tif (nws->networks[i].nwid == wantnw) {\n\t\t\t\t\t\t\t\t\t_node->leave(wantnw,(void **)0,(void *)0);\n\t\t\t\t\t\t\t\t\tres[\"result\"] = true;\n\t\t\t\t\t\t\t\t\tscode = 200;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} \/\/ else 404\n\t\t\t\t\t\t_node->freeQueryResult((void *)nws);\n\t\t\t\t\t} else scode = 500;\n\t\t\t\t} else {\n\t\t\t\t\tif (_controller)\n\t\t\t\t\t\tscode = _controller->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);\n\t\t\t\t\telse scode = 404;\n\t\t\t\t}\n\n\t\t\t} else scode = 401; \/\/ isAuth = false\n\t\t} else {\n\t\t\tscode = 400;\n\t\t}\n\n\t\tif (responseBody.length() == 0) {\n\t\t\tif ((res.is_object())||(res.is_array()))\n\t\t\t\tresponseBody = OSUtils::jsonDump(res);\n\t\t\telse responseBody = \"{}\";\n\t\t\tresponseContentType = \"application\/json\";\n\t\t}\n\n\t\t\/\/ Wrap result in jsonp function call if the user included a jsonp= url argument.\n\t\t\/\/ Also double-check isAuth since forbidding this without auth feels safer.\n\t\tstd::map<std::string,std::string>::const_iterator jsonp(urlArgs.find(\"jsonp\"));\n\t\tif ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == \"application\/json\")) {\n\t\t\tif (responseBody.length() > 0)\n\t\t\t\tresponseBody = jsonp->second + \"(\" + responseBody + \");\";\n\t\t\telse responseBody = jsonp->second + \"(null);\";\n\t\t\tresponseContentType = \"application\/javascript\";\n\t\t}\n\n\t\treturn scode;\n\t}\n\n\t\/\/ Must be called after _localConfig is read or modified\n\tvoid applyLocalConfig()\n\t{\n\t\tMutex::Lock _l(_localConfig_m);\n\t\tjson lc(_localConfig);\n\n\t\t_v4Hints.clear();\n\t\t_v6Hints.clear();\n\t\t_v4Blacklists.clear();\n\t\t_v6Blacklists.clear();\n\t\tjson &virt = lc[\"virtual\"];\n\t\tif (virt.is_object()) {\n\t\t\tfor(json::iterator v(virt.begin());v!=virt.end();++v) {\n\t\t\t\tconst std::string nstr = v.key();\n\t\t\t\tif ((nstr.length() == ZT_ADDRESS_LENGTH_HEX)&&(v.value().is_object())) {\n\t\t\t\t\tconst Address ztaddr(Utils::hexStrToU64(nstr.c_str()));\n\t\t\t\t\tif (ztaddr) {\n\t\t\t\t\t\tconst uint64_t ztaddr2 = ztaddr.toInt();\n\t\t\t\t\t\tstd::vector<InetAddress> &v4h = _v4Hints[ztaddr2];\n\t\t\t\t\t\tstd::vector<InetAddress> &v6h = _v6Hints[ztaddr2];\n\t\t\t\t\t\tstd::vector<InetAddress> &v4b = _v4Blacklists[ztaddr2];\n\t\t\t\t\t\tstd::vector<InetAddress> &v6b = _v6Blacklists[ztaddr2];\n\n\t\t\t\t\t\tjson &tryAddrs = v.value()[\"try\"];\n\t\t\t\t\t\tif (tryAddrs.is_array()) {\n\t\t\t\t\t\t\tfor(unsigned long i=0;i<tryAddrs.size();++i) {\n\t\t\t\t\t\t\t\tconst InetAddress ip(OSUtils::jsonString(tryAddrs[i],\"\").c_str());\n\t\t\t\t\t\t\t\tif (ip.ss_family == AF_INET)\n\t\t\t\t\t\t\t\t\tv4h.push_back(ip);\n\t\t\t\t\t\t\t\telse if (ip.ss_family == AF_INET6)\n\t\t\t\t\t\t\t\t\tv6h.push_back(ip);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tjson &blAddrs = v.value()[\"blacklist\"];\n\t\t\t\t\t\tif (blAddrs.is_array()) {\n\t\t\t\t\t\t\tfor(unsigned long i=0;i<blAddrs.size();++i) {\n\t\t\t\t\t\t\t\tconst InetAddress ip(OSUtils::jsonString(blAddrs[i],\"\").c_str());\n\t\t\t\t\t\t\t\tif (ip.ss_family == AF_INET)\n\t\t\t\t\t\t\t\t\tv4b.push_back(ip);\n\t\t\t\t\t\t\t\telse if (ip.ss_family == AF_INET6)\n\t\t\t\t\t\t\t\t\tv6b.push_back(ip);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (v4h.empty()) _v4Hints.erase(ztaddr2);\n\t\t\t\t\t\tif (v6h.empty()) _v6Hints.erase(ztaddr2);\n\t\t\t\t\t\tif (v4b.empty()) _v4Blacklists.erase(ztaddr2);\n\t\t\t\t\t\tif (v6b.empty()) _v6Blacklists.erase(ztaddr2);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t_globalV4Blacklist.clear();\n\t\t_globalV6Blacklist.clear();\n\t\tjson &physical = lc[\"physical\"];\n\t\tif (physical.is_object()) {\n\t\t\tfor(json::iterator phy(physical.begin());phy!=physical.end();++phy) {\n\t\t\t\tconst InetAddress net(OSUtils::jsonString(phy.key(),\"\").c_str());\n\t\t\t\tif ((net)&&(net.netmaskBits() > 0)) {\n\t\t\t\t\tif (phy.value().is_object()) {\n\t\t\t\t\t\tif (OSUtils::jsonBool(phy.value()[\"blacklist\"],false)) {\n\t\t\t\t\t\t\tif (net.ss_family == AF_INET)\n\t\t\t\t\t\t\t\t_globalV4Blacklist.push_back(net);\n\t\t\t\t\t\t\telse if (net.ss_family == AF_INET6)\n\t\t\t\t\t\t\t\t_globalV6Blacklist.push_back(net);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t_allowManagementFrom.clear();\n\t\t_interfacePrefixBlacklist.clear();\n\n\t\tjson &settings = lc[\"settings\"];\n\n\t\t_primaryPort = (unsigned int)OSUtils::jsonInt(settings[\"primaryPort\"],(uint64_t)_primaryPort) & 0xffff;\n\t\t_allowTcpFallbackRelay = OSUtils::jsonBool(settings[\"allowTcpFallbackRelay\"],true);\n\t\t_allowSecondaryPort = OSUtils::jsonBool(settings[\"allowSecondaryPort\"],true);\n\t\t_secondaryPort = (unsigned int)OSUtils::jsonInt(settings[\"secondaryPort\"],0);\n\t\t_tertiaryPort = (unsigned int)OSUtils::jsonInt(settings[\"tertiaryPort\"],0);\n\t\tif (_secondaryPort != 0 || _tertiaryPort != 0) {\n\t\t\tfprintf(stderr,\"WARNING: using manually-specified ports. This can cause NAT issues.\" ZT_EOL_S);\n\t\t}\n\t\t_multipathMode = (unsigned int)OSUtils::jsonInt(settings[\"multipathMode\"],0);\n\t\tif (_multipathMode != 0 && _allowTcpFallbackRelay) {\n\t\t\tfprintf(stderr,\"WARNING: multipathMode cannot be used with allowTcpFallbackRelay. Disabling allowTcpFallbackRelay\" ZT_EOL_S);\n\t\t\t_allowTcpFallbackRelay = false;\n\t\t}\n\t\t_portMappingEnabled = OSUtils::jsonBool(settings[\"portMappingEnabled\"],true);\n\n#ifndef ZT_SDK\n\t\tconst std::string up(OSUtils::jsonString(settings[\"softwareUpdate\"],ZT_SOFTWARE_UPDATE_DEFAULT));\n\t\tconst bool udist = OSUtils::jsonBool(settings[\"softwareUpdateDist\"],false);\n\t\tif (((up == \"apply\")||(up == \"download\"))||(udist)) {\n\t\t\tif (!_updater)\n\t\t\t\t_updater = new SoftwareUpdater(*_node,_homePath);\n\t\t\t_updateAutoApply = (up == \"apply\");\n\t\t\t_updater->setUpdateDistribution(udist);\n\t\t\t_updater->setChannel(OSUtils::jsonString(settings[\"softwareUpdateChannel\"],ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL));\n\t\t} else {\n\t\t\tdelete _updater;\n\t\t\t_updater = (SoftwareUpdater *)0;\n\t\t\t_updateAutoApply = false;\n\t\t}\n#endif\n\n\t\tjson &ignoreIfs = settings[\"interfacePrefixBlacklist\"];\n\t\tif (ignoreIfs.is_array()) {\n\t\t\tfor(unsigned long i=0;i<ignoreIfs.size();++i) {\n\t\t\t\tconst std::string tmp(OSUtils::jsonString(ignoreIfs[i],\"\"));\n\t\t\t\tif (tmp.length() > 0)\n\t\t\t\t\t_interfacePrefixBlacklist.push_back(tmp);\n\t\t\t}\n\t\t}\n\n\t\tjson &amf = settings[\"allowManagementFrom\"];\n\t\tif (amf.is_array()) {\n\t\t\tfor(unsigned long i=0;i<amf.size();++i) {\n\t\t\t\tconst InetAddress nw(OSUtils::jsonString(amf[i],\"\").c_str());\n\t\t\t\tif (nw)\n\t\t\t\t\t_allowManagementFrom.push_back(nw);\n\t\t\t}\n\t\t}\n\t}\n\n#if ZT_VAULT_SUPPORT\n\t\tjson &vault = settings[\"vault\"];\n\t\tif (vault.is_object()) {\n\t\t\tconst std::string url(OSUtils::jsonString(vault[\"vaultURL\"], \"\").c_str());\n\t\t\tif (!url.empty()) {\n\t\t\t\t_vaultURL = url;\n\t\t\t}\n\n\t\t\tconst std::string token(OSUtils::jsonString(vault[\"vaultToken\"], \"\").c_str());\n\t\t\tif (!token.empty()) {\n\t\t\t\t_vaultToken = token;\n\t\t\t}\n\n\t\t\tconst std::string path(OSUtils::jsonString(vault[\"vaultPath\"], \"\").c_str());\n\t\t\tif (!path.empty()) {\n\t\t\t\t_vaultPath = path;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ also check environment variables for values.  Environment variables\n\t\t\/\/ will override local.conf variables\n\t\tconst std::string envURL(getenv(\"VAULT_ADDR\"));\n\t\tif (!envURL.empty()) {\n\t\t\t_vaultURL = envURL;\n\t\t}\n\n\t\tconst std::string envToken(getenv(\"VAULT_TOKEN\"));\n\t\tif (!envToken.empty()) {\n\t\t\t_vaultToken = envToken;\n\t\t}\n\n\t\tconst std::string envPath(getenv(\"VAULT_PATH\"));\n\t\tif (!envPath.empty()) {\n\t\t\t_vaultPath = envPath;\n\t\t}\n\n\t\tif (!_vaultURL.empty() && !_vaultToken.empty()) {\n\t\t\t_vaultEnabled = true;\n\t\t}\n#endif\n\n\t\/\/ Checks if a managed IP or route target is allowed\n\tbool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &target)\n\t{\n\t\tif (!n.settings.allowManaged)\n\t\t\treturn false;\n\n\t\tif (n.settings.allowManagedWhitelist.size() > 0) {\n\t\t\tbool allowed = false;\n\t\t\tfor (InetAddress addr : n.settings.allowManagedWhitelist) {\n\t\t\t\tif (addr.containsAddress(target) && addr.netmaskBits() <= target.netmaskBits()) {\n\t\t\t\t\tallowed = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!allowed) return false;\n\t\t}\n\n\t\tif (target.isDefaultRoute())\n\t\t\treturn n.settings.allowDefault;\n\t\tswitch(target.ipScope()) {\n\t\t\tcase InetAddress::IP_SCOPE_NONE:\n\t\t\tcase InetAddress::IP_SCOPE_MULTICAST:\n\t\t\tcase InetAddress::IP_SCOPE_LOOPBACK:\n\t\t\tcase InetAddress::IP_SCOPE_LINK_LOCAL:\n\t\t\t\treturn false;\n\t\t\tcase InetAddress::IP_SCOPE_GLOBAL:\n\t\t\t\treturn n.settings.allowGlobal;\n\t\t\tdefault:\n\t\t\t\treturn true;\n\t\t}\n\t}\n\n\t\/\/ Match only an IP from a vector of IPs -- used in syncManagedStuff()\n\tbool matchIpOnly(const std::vector<InetAddress> &ips,const InetAddress &ip) const\n\t{\n\t\tfor(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {\n\t\t\tif (i->ipsEqual(ip))\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t\/\/ Apply or update managed IPs for a configured network (be sure n.tap exists)\n\tvoid syncManagedStuff(NetworkState &n,bool syncIps,bool syncRoutes)\n\t{\n\t\tchar ipbuf[64];\n\n\t\t\/\/ assumes _nets_m is locked\n\t\tif (syncIps) {\n\t\t\tstd::vector<InetAddress> newManagedIps;\n\t\t\tnewManagedIps.reserve(n.config.assignedAddressCount);\n\t\t\tfor(unsigned int i=0;i<n.config.assignedAddressCount;++i) {\n\t\t\t\tconst InetAddress *ii = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[i]));\n\t\t\t\tif (checkIfManagedIsAllowed(n,*ii))\n\t\t\t\t\tnewManagedIps.push_back(*ii);\n\t\t\t}\n\t\t\tstd::sort(newManagedIps.begin(),newManagedIps.end());\n\t\t\tnewManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end());\n\n\t\t\tfor(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {\n\t\t\t\tif (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) {\n\t\t\t\t\tif (!n.tap->removeIp(*ip))\n\t\t\t\t\t\tfprintf(stderr,\"ERROR: unable to remove ip address %s\" ZT_EOL_S, ip->toString(ipbuf));\n\t\t\t\t}\n\t\t\t}\n#ifdef __SYNOLOGY__\n\t\t\tif (!n.tap->addIps(newManagedIps)) {\n\t\t\t\tfprintf(stderr,\"ERROR: unable to add ip addresses to ifcfg\" ZT_EOL_S);\n\t\t\t}\n#else\n\t\t\tfor(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {\n\t\t\t\tif (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) {\n\t\t\t\t\tif (!n.tap->addIp(*ip))\n\t\t\t\t\t\tfprintf(stderr,\"ERROR: unable to add ip address %s\" ZT_EOL_S, ip->toString(ipbuf));\n\t\t\t\t}\n\t\t\t}\n#endif\n\t\t\tn.managedIps.swap(newManagedIps);\n\t\t}\n\n\t\tif (syncRoutes) {\n\t\t\tchar tapdev[64];\n#if defined(__WINDOWS__) && !defined(ZT_SDK)\n\t\t\tOSUtils::ztsnprintf(tapdev,sizeof(tapdev),\"%.16llx\",(unsigned long long)((WindowsEthernetTap *)(n.tap.get()))->luid().Value);\n#else\n\t\t\tUtils::scopy(tapdev,sizeof(tapdev),n.tap->deviceName().c_str());\n#endif\n\n\t\t\tstd::vector<InetAddress> myIps(n.tap->ips());\n\n\t\t\t\/\/ Nuke applied routes that are no longer in n.config.routes[] and\/or are not allowed\n\t\t\tfor(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();) {\n\t\t\t\tbool haveRoute = false;\n\t\t\t\tif ( (checkIfManagedIsAllowed(n,(*mr)->target())) && (((*mr)->via().ss_family != (*mr)->target().ss_family)||(!matchIpOnly(myIps,(*mr)->via()))) ) {\n\t\t\t\t\tfor(unsigned int i=0;i<n.config.routeCount;++i) {\n\t\t\t\t\t\tconst InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));\n\t\t\t\t\t\tconst InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));\n\t\t\t\t\t\tif ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (strcmp(tapdev,(*mr)->device())==0) ) ) {\n\t\t\t\t\t\t\thaveRoute = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (haveRoute) {\n\t\t\t\t\t++mr;\n\t\t\t\t} else {\n\t\t\t\t\tn.managedRoutes.erase(mr++);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Apply routes in n.config.routes[] that we haven't applied yet, and sync those we have in case shadow routes need to change\n\t\t\tfor(unsigned int i=0;i<n.config.routeCount;++i) {\n\t\t\t\tconst InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));\n\t\t\t\tconst InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));\n\n\t\t\t\tconst InetAddress *src = NULL;\n\t\t\t\tfor (unsigned int j=0; j<n.config.assignedAddressCount; ++j) {\n\t\t\t\t\tconst InetAddress *const tmp = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[j]));\n\t\t\t\t\tif (target->isV4() && tmp->isV4()) {\n\t\t\t\t\t\tsrc = reinterpret_cast<InetAddress *>(&(n.config.assignedAddresses[j]));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (target->isV6() && tmp->isV6()) {\n\t\t\t\t\t\tsrc = reinterpret_cast<InetAddress *>(&(n.config.assignedAddresses[j]));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!src)\n\t\t\t\t\tsrc = &NULL_INET_ADDR;\n\n\t\t\t\tif ( (!checkIfManagedIsAllowed(n,*target)) || ((via->ss_family == target->ss_family)&&(matchIpOnly(myIps,*via))) )\n\t\t\t\t\tcontinue;\n\n\t\t\t\tbool haveRoute = false;\n\n\t\t\t\t\/\/ Ignore routes implied by local managed IPs since adding the IP adds the route\n#ifndef __APPLE__\n\t\t\t\tfor(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {\n\t\t\t\t\tif ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {\n\t\t\t\t\t\thaveRoute = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n#endif\n\t\t\t\tif (haveRoute)\n\t\t\t\t\tcontinue;\n#ifndef ZT_SDK\n\t\t\t\t\/\/ If we've already applied this route, just sync it and continue\n\t\t\t\tfor(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();++mr) {\n\t\t\t\t\tif ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {\n\t\t\t\t\t\thaveRoute = true;\n\t\t\t\t\t\t(*mr)->sync();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (haveRoute)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t\/\/ Add and apply new routes\n\t\t\t\tn.managedRoutes.push_back(SharedPtr<ManagedRoute>(new ManagedRoute(*target,*via,*src,tapdev)));\n\t\t\t\tif (!n.managedRoutes.back()->sync())\n\t\t\t\t\tn.managedRoutes.pop_back();\n#endif\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ =========================================================================\n\t\/\/ Handlers for Node and Phy<> callbacks\n\t\/\/ =========================================================================\n\n\tinline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)\n\t{\n\t\tconst uint64_t now = OSUtils::now();\n\t\tif ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))\n\t\t\t_lastDirectReceiveFromGlobal = now;\n\t\tconst ZT_ResultCode rc = _node->processWirePacket(nullptr,now,reinterpret_cast<int64_t>(sock),reinterpret_cast<const struct sockaddr_storage *>(from),data,len,&_nextBackgroundTaskDeadline);\n\t\tif (ZT_ResultCode_isFatal(rc)) {\n\t\t\tchar tmp[256];\n\t\t\tOSUtils::ztsnprintf(tmp,sizeof(tmp),\"fatal error code from processWirePacket: %d\",(int)rc);\n\t\t\tMutex::Lock _l(_termReason_m);\n\t\t\t_termReason = ONE_UNRECOVERABLE_ERROR;\n\t\t\t_fatalErrorMessage = tmp;\n\t\t\tthis->terminate();\n\t\t}\n\t}\n\n\tinline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)\n\t{\n\t\tif (!success) {\n\t\t\tphyOnTcpClose(sock,uptr);\n\t\t\treturn;\n\t\t}\n\n\t\tTcpConnection *const tc = reinterpret_cast<TcpConnection *>(*uptr);\n\t\tif (!tc) { \/\/ sanity check\n\t\t\t_phy.close(sock,true);\n\t\t\treturn;\n\t\t}\n\t\ttc->sock = sock;\n\n\t\tif (tc->type == TcpConnection::TCP_TUNNEL_OUTGOING) {\n\t\t\tif (_tcpFallbackTunnel)\n\t\t\t\t_phy.close(_tcpFallbackTunnel->sock);\n\t\t\t_tcpFallbackTunnel = tc;\n\t\t\t_phy.streamSend(sock,ZT_TCP_TUNNEL_HELLO,sizeof(ZT_TCP_TUNNEL_HELLO));\n\t\t} else {\n\t\t\t_phy.close(sock,true);\n\t\t}\n\t}\n\n\tinline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)\n\t{\n\t\tif (!from) {\n\t\t\t_phy.close(sockN,false);\n\t\t\treturn;\n\t\t} else {\n#ifdef ZT_SDK\n\t\t\t\/\/ Immediately close new local connections. The intention is to prevent the backplane from being accessed when operating as libzt\n\t\t\tif (!allowHttpBackplaneManagement && ((InetAddress*)from)->ipScope() == InetAddress::IP_SCOPE_LOOPBACK) {\n\t\t\t\t_phy.close(sockN,false);\n\t\t\t\treturn;\n\t\t\t}\n#endif\n\t\t\tTcpConnection *tc = new TcpConnection();\n\t\t\t{\n\t\t\t\tMutex::Lock _l(_tcpConnections_m);\n\t\t\t\t_tcpConnections.push_back(tc);\n\t\t\t}\n\n\t\t\ttc->type = TcpConnection::TCP_UNCATEGORIZED_INCOMING;\n\t\t\ttc->parent = this;\n\t\t\ttc->sock = sockN;\n\t\t\ttc->remoteAddr = from;\n\t\t\ttc->lastReceive = OSUtils::now();\n\t\t\thttp_parser_init(&(tc->parser),HTTP_REQUEST);\n\t\t\ttc->parser.data = (void *)tc;\n\t\t\ttc->messageSize = 0;\n\n\t\t\t*uptrN = (void *)tc;\n\t\t}\n\t}\n\n\tvoid phyOnTcpClose(PhySocket *sock,void **uptr)\n\t{\n\t\tTcpConnection *tc = (TcpConnection *)*uptr;\n\t\tif (tc) {\n\t\t\tif (tc == _tcpFallbackTunnel) {\n\t\t\t\t_tcpFallbackTunnel = (TcpConnection *)0;\n\t\t\t}\n\t\t\t{\n\t\t\t\tMutex::Lock _l(_tcpConnections_m);\n\t\t\t\t_tcpConnections.erase(std::remove(_tcpConnections.begin(),_tcpConnections.end(),tc),_tcpConnections.end());\n\t\t\t}\n\t\t\tdelete tc;\n\t\t}\n\t}\n\n\tvoid phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)\n\t{\n\t\ttry {\n\t\t\tif (!len) return; \/\/ sanity check, should never happen\n\t\t\tTcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);\n\t\t\ttc->lastReceive = OSUtils::now();\n\t\t\tswitch(tc->type) {\n\n\t\t\t\tcase TcpConnection::TCP_UNCATEGORIZED_INCOMING:\n\t\t\t\t\tswitch(reinterpret_cast<uint8_t *>(data)[0]) {\n\t\t\t\t\t\t\/\/ HTTP: GET, PUT, POST, HEAD, DELETE\n\t\t\t\t\t\tcase 'G':\n\t\t\t\t\t\tcase 'P':\n\t\t\t\t\t\tcase 'D':\n\t\t\t\t\t\tcase 'H': {\n\t\t\t\t\t\t\t\/\/ This is only allowed from IPs permitted to access the management\n\t\t\t\t\t\t\t\/\/ backplane, which is just 127.0.0.1\/::1 unless otherwise configured.\n\t\t\t\t\t\t\tbool allow;\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tMutex::Lock _l(_localConfig_m);\n\t\t\t\t\t\t\t\tif (_allowManagementFrom.size() == 0) {\n\t\t\t\t\t\t\t\t\tallow = (tc->remoteAddr.ipScope() == InetAddress::IP_SCOPE_LOOPBACK);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tallow = false;\n\t\t\t\t\t\t\t\t\tfor(std::vector<InetAddress>::const_iterator i(_allowManagementFrom.begin());i!=_allowManagementFrom.end();++i) {\n\t\t\t\t\t\t\t\t\t\tif (i->containsAddress(tc->remoteAddr)) {\n\t\t\t\t\t\t\t\t\t\t\tallow = true;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (allow) {\n\t\t\t\t\t\t\t\ttc->type = TcpConnection::TCP_HTTP_INCOMING;\n\t\t\t\t\t\t\t\tphyOnTcpData(sock,uptr,data,len);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t_phy.close(sock);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\tbreak;\n\n\t\t\t\t\t\t\/\/ default tunnel \n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\ttc->type = TcpConnection::TCP_TUNNEL_OUTGOING;\n\t\t\t\t\t\t\tphyOnTcpData(sock,uptr,data,len);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\n\t\t\t\tcase TcpConnection::TCP_HTTP_INCOMING:\n\t\t\t\tcase TcpConnection::TCP_HTTP_OUTGOING:\n\t\t\t\t\thttp_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);\n\t\t\t\t\tif ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK))\n\t\t\t\t\t\t_phy.close(sock);\n\t\t\t\t\treturn;\n\n\t\t\t\tcase TcpConnection::TCP_TUNNEL_OUTGOING:\n\t\t\t\t\ttc->readq.append((const char *)data,len);\n\t\t\t\t\twhile (tc->readq.length() >= 5) {\n\t\t\t\t\t\tconst char *data = tc->readq.data();\n\t\t\t\t\t\tconst unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );\n\t\t\t\t\t\tif (tc->readq.length() >= (mlen + 5)) {\n\t\t\t\t\t\t\tInetAddress from;\n\n\t\t\t\t\t\tunsigned long plen = mlen; \/\/ payload length, modified if there's an IP header\n\t\t\t\t\t\t\tdata += 5; \/\/ skip forward past pseudo-TLS junk and mlen\n\t\t\t\t\t\t\tif (plen == 4) {\n\t\t\t\t\t\t\t\t\/\/ Hello message, which isn't sent by proxy and would be ignored by client\n\t\t\t\t\t\t\t} else if (plen) {\n\t\t\t\t\t\t\t\t\/\/ Messages should contain IPv4 or IPv6 source IP address data\n\t\t\t\t\t\t\t\tswitch(data[0]) {\n\t\t\t\t\t\t\t\t\tcase 4: \/\/ IPv4\n\t\t\t\t\t\t\t\t\t\tif (plen >= 7) {\n\t\t\t\t\t\t\t\t\t\t\tfrom.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));\n\t\t\t\t\t\t\t\t\t\t\tdata += 7; \/\/ type + 4 byte IP + 2 byte port\n\t\t\t\t\t\t\t\t\t\t\tplen -= 7;\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t_phy.close(sock);\n\t\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase 6: \/\/ IPv6\n\t\t\t\t\t\t\t\t\t\tif (plen >= 19) {\n\t\t\t\t\t\t\t\t\t\t\tfrom.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));\n\t\t\t\t\t\t\t\t\t\t\tdata += 19; \/\/ type + 16 byte IP + 2 byte port\n\t\t\t\t\t\t\t\t\t\t\tplen -= 19;\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t_phy.close(sock);\n\t\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase 0: \/\/ none\/omitted\n\t\t\t\t\t\t\t\t\t\t++data;\n\t\t\t\t\t\t\t\t\t\t--plen;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tdefault: \/\/ invalid address type\n\t\t\t\t\t\t\t\t\t\t_phy.close(sock);\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (from) {\n\t\t\t\t\t\t\t\t\tInetAddress fakeTcpLocalInterfaceAddress((uint32_t)0xffffffff,0xffff);\n\t\t\t\t\t\t\t\t\tconst ZT_ResultCode rc = _node->processWirePacket(\n\t\t\t\t\t\t\t\t\t\t(void *)0,\n\t\t\t\t\t\t\t\t\t\tOSUtils::now(),\n\t\t\t\t\t\t\t\t\t\treinterpret_cast<int64_t>(sock),\n\t\t\t\t\t\t\t\t\t\treinterpret_cast<struct sockaddr_storage *>(&from),\n\t\t\t\t\t\t\t\t\t\tdata,\n\t\t\t\t\t\t\t\t\t\tplen,\n\t\t\t\t\t\t\t\t\t\t&_nextBackgroundTaskDeadline);\n\t\t\t\t\t\t\t\t\tif (ZT_ResultCode_isFatal(rc)) {\n\t\t\t\t\t\t\t\t\t\tchar tmp[256];\n\t\t\t\t\t\t\t\t\t\tOSUtils::ztsnprintf(tmp,sizeof(tmp),\"fatal error code from processWirePacket: %d\",(int)rc);\n\t\t\t\t\t\t\t\t\t\tMutex::Lock _l(_termReason_m);\n\t\t\t\t\t\t\t\t\t\t_termReason = ONE_UNRECOVERABLE_ERROR;\n\t\t\t\t\t\t\t\t\t\t_fatalErrorMessage = tmp;\n\t\t\t\t\t\t\t\t\t\tthis->terminate();\n\t\t\t\t\t\t\t\t\t\t_phy.close(sock);\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (tc->readq.length() > (mlen + 5))\n\t\t\t\t\t\t\t\ttc->readq.erase(tc->readq.begin(),tc->readq.begin() + (mlen + 5));\n\t\t\t\t\t\t\telse tc->readq.clear();\n\t\t\t\t\t\t} else break;\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\n\t\t\t}\n\t\t} catch (std::exception &exc) {\n\t\t\t_phy.close(sock);\n\t\t} catch ( ... ) {\n\t\t\t_phy.close(sock);\n\t\t}\n\t}\n\n\tinline void phyOnTcpWritable(PhySocket *sock,void **uptr)\n\t{\n\t\tTcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);\n\t\tbool closeit = false;\n\t\t{\n\t\t\tMutex::Lock _l(tc->writeq_m);\n\t\t\tif (tc->writeq.length() > 0) {\n\t\t\t\tlong sent = (long)_phy.streamSend(sock,tc->writeq.data(),(unsigned long)tc->writeq.length(),true);\n\t\t\t\tif (sent > 0) {\n\t\t\t\t\tif ((unsigned long)sent >= (unsigned long)tc->writeq.length()) {\n\t\t\t\t\t\ttc->writeq.clear();\n\t\t\t\t\t\t_phy.setNotifyWritable(sock,false);\n\n\t\t\t\t\t\tif (tc->type == TcpConnection::TCP_HTTP_INCOMING)\n\t\t\t\t\t\t\tcloseit = true; \/\/ HTTP keep alive not supported\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttc->writeq.erase(tc->writeq.begin(),tc->writeq.begin() + sent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t_phy.setNotifyWritable(sock,false);\n\t\t\t}\n\t\t}\n\t\tif (closeit)\n\t\t\t_phy.close(sock);\n\t}\n\n\tinline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}\n\tinline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}\n\tinline void phyOnUnixClose(PhySocket *sock,void **uptr) {}\n\tinline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}\n\tinline void phyOnUnixWritable(PhySocket *sock,void **uptr) {}\n\n\tinline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)\n\t{\n\t\tMutex::Lock _l(_nets_m);\n\t\tNetworkState &n = _nets[nwid];\n\n\t\tswitch(op) {\n\n\t\t\tcase ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:\n\t\t\t\tif (!n.tap) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tchar friendlyName[128];\n\t\t\t\t\t\tOSUtils::ztsnprintf(friendlyName,sizeof(friendlyName),\"ZeroTier One [%.16llx]\",nwid);\n\n\t\t\t\t\t\tn.tap = EthernetTap::newInstance(\n\t\t\t\t\t\t\tnullptr,\n\t\t\t\t\t\t\t_homePath.c_str(),\n\t\t\t\t\t\t\tMAC(nwc->mac),\n\t\t\t\t\t\t\tnwc->mtu,\n\t\t\t\t\t\t\t(unsigned int)ZT_IF_METRIC,\n\t\t\t\t\t\t\tnwid,\n\t\t\t\t\t\t\tfriendlyName,\n\t\t\t\t\t\t\tStapFrameHandler,\n\t\t\t\t\t\t\t(void *)this);\n\t\t\t\t\t\t*nuptr = (void *)&n;\n\n\t\t\t\t\t\tchar nlcpath[256];\n\t\t\t\t\t\tOSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),\"%s\" ZT_PATH_SEPARATOR_S \"networks.d\" ZT_PATH_SEPARATOR_S \"%.16llx.local.conf\",_homePath.c_str(),nwid);\n\t\t\t\t\t\tstd::string nlcbuf;\n\t\t\t\t\t\tif (OSUtils::readFile(nlcpath,nlcbuf)) {\n\t\t\t\t\t\t\tDictionary<4096> nc;\n\t\t\t\t\t\t\tnc.load(nlcbuf.c_str());\n\t\t\t\t\t\t\tBuffer<1024> allowManaged;\n\t\t\t\t\t\t\tif (nc.get(\"allowManaged\", allowManaged) && allowManaged.size() != 0) {\n\t\t\t\t\t\t\t\tstd::string addresses (allowManaged.begin(), allowManaged.size());\n\t\t\t\t\t\t\t\tif (allowManaged.size() <= 5) { \/\/ untidy parsing for backward compatibility\n\t\t\t\t\t\t\t\t\tif (allowManaged[0] == '1' || allowManaged[0] == 't' || allowManaged[0] == 'T') {\n\t\t\t\t\t\t\t\t\t\tn.settings.allowManaged = true;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tn.settings.allowManaged = false;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\/\/ this should be a list of IP addresses\n\t\t\t\t\t\t\t\t\tn.settings.allowManaged = true;\n\t\t\t\t\t\t\t\t\tsize_t pos = 0;\n\t\t\t\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\t\t\t\tsize_t nextPos = addresses.find(',', pos);\n\t\t\t\t\t\t\t\t\t\tstd::string address = addresses.substr(pos, (nextPos == std::string::npos ? addresses.size() : nextPos) - pos);\n\t\t\t\t\t\t\t\t\t\tn.settings.allowManagedWhitelist.push_back(InetAddress(address.c_str()));\n\t\t\t\t\t\t\t\t\t\tif (nextPos == std::string::npos) break;\n\t\t\t\t\t\t\t\t\t\tpos = nextPos + 1;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tn.settings.allowManaged = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tn.settings.allowGlobal = nc.getB(\"allowGlobal\", false);\n\t\t\t\t\t\t\tn.settings.allowDefault = nc.getB(\"allowDefault\", false);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (std::exception &exc) {\n#ifdef __WINDOWS__\n\t\t\t\t\t\tFILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S\"port_error_log.txt\").c_str(),\"a\");\n\t\t\t\t\t\tif (tapFailLog) {\n\t\t\t\t\t\t\tfprintf(tapFailLog,\"%.16llx: %s\" ZT_EOL_S,(unsigned long long)nwid,exc.what());\n\t\t\t\t\t\t\tfclose(tapFailLog);\n\t\t\t\t\t\t}\n#else\n\t\t\t\t\t\tfprintf(stderr,\"ERROR: unable to configure virtual network port: %s\" ZT_EOL_S,exc.what());\n#endif\n\t\t\t\t\t\t_nets.erase(nwid);\n\t\t\t\t\t\treturn -999;\n\t\t\t\t\t} catch (int exc) {\n\t\t\t\t\t\treturn -999;\n\t\t\t\t\t} catch ( ... ) {\n\t\t\t\t\t\treturn -999; \/\/ tap init failed\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...\n\n\t\t\tcase ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:\n\t\t\t\tmemcpy(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));\n\t\t\t\tif (n.tap) { \/\/ sanity check\n#if defined(__WINDOWS__) && !defined(ZT_SDK)\n\t\t\t\t\t\/\/ wait for up to 5 seconds for the WindowsEthernetTap to actually be initialized\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/ without WindowsEthernetTap::isInitialized() returning true, the won't actually\n\t\t\t\t\t\/\/ be online yet and setting managed routes on it will fail.\n\t\t\t\t\tconst int MAX_SLEEP_COUNT = 500;\n\t\t\t\t\tfor (int i = 0; !((WindowsEthernetTap *)(n.tap.get()))->isInitialized() && i < MAX_SLEEP_COUNT; i++) {\n\t\t\t\t\t\tSleep(10);\n\t\t\t\t\t}\n#endif\n\t\t\t\t\tsyncManagedStuff(n,true,true);\n\t\t\t\t\tn.tap->setMtu(nwc->mtu);\n\t\t\t\t} else {\n\t\t\t\t\t_nets.erase(nwid);\n\t\t\t\t\treturn -999; \/\/ tap init failed\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:\n\t\t\tcase ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:\n\t\t\t\tif (n.tap) { \/\/ sanity check\n#if defined(__WINDOWS__) && !defined(ZT_SDK)\n\t\t\t\t\tstd::string winInstanceId(((WindowsEthernetTap *)(n.tap.get()))->instanceId());\n#endif\n\t\t\t\t\t*nuptr = (void *)0;\n\t\t\t\t\tn.tap.reset();\n\t\t\t\t\t_nets.erase(nwid);\n#if defined(__WINDOWS__) && !defined(ZT_SDK)\n\t\t\t\t\tif ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))\n\t\t\t\t\t\tWindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());\n#endif\n\t\t\t\t\tif (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) {\n\t\t\t\t\t\tchar nlcpath[256];\n\t\t\t\t\t\tOSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),\"%s\" ZT_PATH_SEPARATOR_S \"networks.d\" ZT_PATH_SEPARATOR_S \"%.16llx.local.conf\",_homePath.c_str(),nwid);\n\t\t\t\t\t\tOSUtils::rm(nlcpath);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t_nets.erase(nwid);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t}\n\t\treturn 0;\n\t}\n\n\tinline void nodeEventCallback(enum ZT_Event event,const void *metaData)\n\t{\n\t\tswitch(event) {\n\t\t\tcase ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {\n\t\t\t\tMutex::Lock _l(_termReason_m);\n\t\t\t\t_termReason = ONE_IDENTITY_COLLISION;\n\t\t\t\t_fatalErrorMessage = \"identity\/address collision\";\n\t\t\t\tthis->terminate();\n\t\t\t}\tbreak;\n\n\t\t\tcase ZT_EVENT_TRACE: {\n\t\t\t\tif (metaData) {\n\t\t\t\t\t::fprintf(stderr,\"%s\" ZT_EOL_S,(const char *)metaData);\n\t\t\t\t\t::fflush(stderr);\n\t\t\t\t}\n\t\t\t}\tbreak;\n\n\t\t\tcase ZT_EVENT_USER_MESSAGE: {\n\t\t\t\tconst ZT_UserMessage *um = reinterpret_cast<const ZT_UserMessage *>(metaData);\n\t\t\t\tif ((um->typeId == ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE)&&(_updater)) {\n\t\t\t\t\t_updater->handleSoftwareUpdateUserMessage(um->origin,um->data,um->length);\n\t\t\t\t}\n\t\t\t}\tbreak;\n\n\t\t\tcase ZT_EVENT_REMOTE_TRACE: {\n\t\t\t\tconst ZT_RemoteTrace *rt = reinterpret_cast<const ZT_RemoteTrace *>(metaData);\n\t\t\t\tif ((rt)&&(rt->len > 0)&&(rt->len <= ZT_MAX_REMOTE_TRACE_SIZE)&&(rt->data))\n\t\t\t\t\t_controller->handleRemoteTrace(*rt);\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n#if ZT_VAULT_SUPPORT\n\tinline bool nodeVaultPutIdentity(enum ZT_StateObjectType type, const void *data, int len)\n\t{\n\t\tbool retval = false;\n\t\tif (type != ZT_STATE_OBJECT_IDENTITY_PUBLIC && type != ZT_STATE_OBJECT_IDENTITY_SECRET) {\n\t\t\treturn retval;\n\t\t}\n\n\t\tCURL *curl = curl_easy_init();\n\t\tif (curl) {\n\t\t\tchar token[512] = { 0 };\n\t\t\tsnprintf(token, sizeof(token), \"X-Vault-Token: %s\", _vaultToken.c_str());\n\n\t\t\tstruct curl_slist *chunk = NULL;\n\t\t\tchunk = curl_slist_append(chunk, token);\n\n\n\t\t\tchar content_type[512] = { 0 };\n\t\t\tsnprintf(content_type, sizeof(content_type), \"Content-Type: application\/json\");\n\n\t\t\tchunk = curl_slist_append(chunk, content_type);\n\n\t\t\tcurl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);\n\n\t\t\tchar url[2048] = { 0 };\n\t\t\tsnprintf(url, sizeof(url), \"%s\/v1\/%s\", _vaultURL.c_str(), _vaultPath.c_str());\n\n\t\t\tcurl_easy_setopt(curl, CURLOPT_URL, url);\n\n\t\t\tjson d = json::object();\n\t\t\tif (type == ZT_STATE_OBJECT_IDENTITY_PUBLIC) {\n\t\t\t\tstd::string key((const char*)data, len);\n\t\t\t\td[\"public\"] = key;\n\t\t\t}\n\t\t\telse if (type == ZT_STATE_OBJECT_IDENTITY_SECRET) {\n\t\t\t\tstd::string key((const char*)data, len);\n\t\t\t\td[\"secret\"] = key;\n\t\t\t}\n\n\t\t\tif (!d.empty()) {\n\t\t\t\tstd::string post = d.dump();\n\n\t\t\t\tif (!post.empty()) {\n\t\t\t\t\tcurl_easy_setopt(curl, CURLOPT_POSTFIELDS, post.c_str());\n\t\t\t\t\tcurl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, post.length());\n\n#ifndef NDEBUG\n\t\t\t\t\tcurl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);\n#endif\n\n\t\t\t\t\tCURLcode res = curl_easy_perform(curl);\n\t\t\t\t\tif (res == CURLE_OK) {\n\t\t\t\t\t\tlong response_code = 0;\n\t\t\t\t\t\tcurl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);\n\t\t\t\t\t\tif (response_code == 200 || response_code == 204) {\n\t\t\t\t\t\t\tretval = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurl_easy_cleanup(curl);\n\t\t\tcurl = NULL;\n\t\t\tcurl_slist_free_all(chunk);\n\t\t\tchunk = NULL;\n\t\t}\n\n\t\treturn retval;\n\t}\n#endif\n\n\tinline void nodeStatePutFunction(enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)\n\t{\n#if ZT_VAULT_SUPPORT\n\t\tif (_vaultEnabled && (type == ZT_STATE_OBJECT_IDENTITY_SECRET || type == ZT_STATE_OBJECT_IDENTITY_PUBLIC)) {\n\t\t\tif (nodeVaultPutIdentity(type, data, len)) {\n\t\t\t\t\/\/ value successfully written to Vault\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\/\/ else fallback to disk\n\t\t}\n#endif\n\t\tchar p[1024];\n\t\tFILE *f;\n\t\tbool secure = false;\n\t\tchar dirname[1024];\n\t\tdirname[0] = 0;\n\n\t\tswitch(type) {\n\t\t\tcase ZT_STATE_OBJECT_IDENTITY_PUBLIC:\n\t\t\t\tOSUtils::ztsnprintf(p,sizeof(p),\"%s\" ZT_PATH_SEPARATOR_S \"identity.public\",_homePath.c_str());\n\t\t\t\tbreak;\n\t\t\tcase ZT_STATE_OBJECT_IDENTITY_SECRET:\n\t\t\t\tOSUtils::ztsnprintf(p,sizeof(p),\"%s\" ZT_PATH_SEPARATOR_S \"identity.secret\",_homePath.c_str());\n\t\t\t\tsecure = true;\n\t\t\t\tbreak;\n\t\t\tcase ZT_STATE_OBJECT_PLANET:\n\t\t\t\tOSUtils::ztsnprintf(p,sizeof(p),\"%s\" ZT_PATH_SEPARATOR_S \"planet\",_homePath.c_str());\n\t\t\t\tbreak;\n\t\t\tcase ZT_STATE_OBJECT_MOON:\n\t\t\t\tOSUtils::ztsnprintf(dirname,sizeof(dirname),\"%s\" ZT_PATH_SEPARATOR_S \"moons.d\",_homePath.c_str());\n\t\t\t\tOSUtils::ztsnprintf(p,sizeof(p),\"%s\" ZT_PATH_SEPARATOR_S \"%.16llx.moon\",dirname,(unsigned long long)id[0]);\n\t\t\t\tbreak;\n\t\t\tcase ZT_STATE_OBJECT_NETWORK_CONFIG:\n\t\t\t\tOSUtils::ztsnprintf(dirname,sizeof(dirname),\"%s\" ZT_PATH_SEPARATOR_S \"networks.d\",_homePath.c_str());\n\t\t\t\tOSUtils::ztsnprintf(p,sizeof(p),\"%s\" ZT_PATH_SEPARATOR_S \"%.16llx.conf\",dirname,(unsigned long long)id[0]);\n\t\t\t\tsecure = true;\n\t\t\t\tbreak;\n\t\t\tcase ZT_STATE_OBJECT_PEER:\n\t\t\t\tOSUtils::ztsnprintf(dirname,sizeof(dirname),\"%s\" ZT_PATH_SEPARATOR_S \"peers.d\",_homePath.c_str());\n\t\t\t\tOSUtils::ztsnprintf(p,sizeof(p),\"%s\" ZT_PATH_SEPARATOR_S \"%.10llx.peer\",dirname,(unsigned long long)id[0]);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn;\n\t\t}\n\n\t\tif ((len >= 0)&&(data)) {\n\t\t\t\/\/ Check to see if we've already written this first. This reduces\n\t\t\t\/\/ redundant writes and I\/O overhead on most platforms and has\n\t\t\t\/\/ little effect on others.\n\t\t\tf = fopen(p,\"rb\");\n\t\t\tif (f) {\n\t\t\t\tchar *const buf = (char *)malloc(len*4);\n\t\t\t\tif (buf) {\n\t\t\t\t\tlong l = (long)fread(buf,1,(size_t)(len*4),f);\n\t\t\t\t\tfclose(f);\n\t\t\t\t\tif ((l == (long)len)&&(memcmp(data,buf,l) == 0)) {\n\t\t\t\t\t\tfree(buf);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tfree(buf);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tf = fopen(p,\"wb\");\n\t\t\tif ((!f)&&(dirname[0])) { \/\/ create subdirectory if it does not exist\n\t\t\t\tOSUtils::mkdir(dirname);\n\t\t\t\tf = fopen(p,\"wb\");\n\t\t\t}\n\t\t\tif (f) {\n\t\t\t\tif (fwrite(data,len,1,f) != 1)\n\t\t\t\t\tfprintf(stderr,\"WARNING: unable to write to file: %s (I\/O error)\" ZT_EOL_S,p);\n\t\t\t\tfclose(f);\n\t\t\t\tif (secure)\n\t\t\t\t\tOSUtils::lockDownFile(p,false);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr,\"WARNING: unable to write to file: %s (unable to open)\" ZT_EOL_S,p);\n\t\t\t}\n\t\t} else {\n\t\t\tOSUtils::rm(p);\n\t\t}\n\t}\n\n#if ZT_VAULT_SUPPORT\n\tinline int nodeVaultGetIdentity(enum ZT_StateObjectType type, void *data, unsigned int maxlen)\n\t{\n\t\tif (type != ZT_STATE_OBJECT_IDENTITY_SECRET && type != ZT_STATE_OBJECT_IDENTITY_PUBLIC) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tint ret = -1;\n\t\tCURL *curl = curl_easy_init();\n\t\tif (curl) {\n\t\t\tchar token[512] = { 0 };\n\t\t\tsnprintf(token, sizeof(token), \"X-Vault-Token: %s\", _vaultToken.c_str());\n\n\t\t\tstruct curl_slist *chunk = NULL;\n\t\t\tchunk = curl_slist_append(chunk, token);\n\t\t\tcurl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);\n\n\t\t\tchar url[2048] = { 0 };\n\t\t\tsnprintf(url, sizeof(url), \"%s\/v1\/%s\", _vaultURL.c_str(), _vaultPath.c_str());\n\n\t\t\tcurl_easy_setopt(curl, CURLOPT_URL, url);\n\n\t\t\tstd::string response;\n\t\t\tstd::string res_headers;\n\n\t\t\tcurl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &curlResponseWrite);\n\t\t\tcurl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);\n\t\t\tcurl_easy_setopt(curl, CURLOPT_HEADERDATA, &res_headers);\n\n#ifndef NDEBUG\n\t\t\tcurl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);\n#endif\n\n\t\t\tCURLcode res = curl_easy_perform(curl);\n\n\t\t\tif (res == CURLE_OK) {\n\t\t\t\tlong response_code = 0;\n\t\t\t\tcurl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);\n\t\t\t\tif (response_code == 200) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tjson payload = json::parse(response);\n\t\t\t\t\t\tif (!payload[\"data\"].is_null()) {\n\t\t\t\t\t\t\tjson &d = payload[\"data\"];\n\t\t\t\t\t\t\tif (type == ZT_STATE_OBJECT_IDENTITY_SECRET) {\n\t\t\t\t\t\t\t\tstd::string secret = OSUtils::jsonString(d[\"secret\"],\"\");\n\n\t\t\t\t\t\t\t\tif (!secret.empty()) {\n\t\t\t\t\t\t\t\t\tret = (int)secret.length();\n\t\t\t\t\t\t\t\t\tmemcpy(data, secret.c_str(), ret);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (type == ZT_STATE_OBJECT_IDENTITY_PUBLIC) {\n\t\t\t\t\t\t\t\tstd::string pub = OSUtils::jsonString(d[\"public\"],\"\");\n\n\t\t\t\t\t\t\t\tif (!pub.empty()) {\n\t\t\t\t\t\t\t\t\tret = (int)pub.length();\n\t\t\t\t\t\t\t\t\tmemcpy(data, pub.c_str(), ret);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (...) {\n\t\t\t\t\t\tret = -1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurl_easy_cleanup(curl);\n\t\t\tcurl = NULL;\n\t\t\tcurl_slist_free_all(chunk);\n\t\t\tchunk = NULL;\n\t\t}\n\t\treturn ret;\n\t}\n#endif\n\n\tinline int nodeStateGetFunction(enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)\n\t{\n#if ZT_VAULT_SUPPORT\n\t\tif (_vaultEnabled && (type == ZT_STATE_OBJECT_IDENTITY_SECRET || type == ZT_STATE_OBJECT_IDENTITY_PUBLIC) ) {\n\t\t\tint retval = nodeVaultGetIdentity(type, data, maxlen);\n\t\t\tif (retval >= 0)\n\t\t\t\treturn retval;\n\n\t\t\t\/\/ else continue file based lookup\n\t\t}\n#endif\n\t\tchar p[4096];\n\t\tswitch(type) {\n\t\t\tcase ZT_STATE_OBJECT_IDENTITY_PUBLIC:\n\t\t\t\tOSUtils::ztsnprintf(p,sizeof(p),\"%s\" ZT_PATH_SEPARATOR_S \"identity.public\",_homePath.c_str());\n\t\t\t\tbreak;\n\t\t\tcase ZT_STATE_OBJECT_IDENTITY_SECRET:\n\t\t\t\tOSUtils::ztsnprintf(p,sizeof(p),\"%s\" ZT_PATH_SEPARATOR_S \"identity.secret\",_homePath.c_str());\n\t\t\t\tbreak;\n\t\t\tcase ZT_STATE_OBJECT_PLANET:\n\t\t\t\tOSUtils::ztsnprintf(p,sizeof(p),\"%s\" ZT_PATH_SEPARATOR_S \"planet\",_homePath.c_str());\n\t\t\t\tbreak;\n\t\t\tcase ZT_STATE_OBJECT_MOON:\n\t\t\t\tOSUtils::ztsnprintf(p,sizeof(p),\"%s\" ZT_PATH_SEPARATOR_S \"moons.d\" ZT_PATH_SEPARATOR_S \"%.16llx.moon\",_homePath.c_str(),(unsigned long long)id[0]);\n\t\t\t\tbreak;\n\t\t\tcase ZT_STATE_OBJECT_NETWORK_CONFIG:\n\t\t\t\tOSUtils::ztsnprintf(p,sizeof(p),\"%s\" ZT_PATH_SEPARATOR_S \"networks.d\" ZT_PATH_SEPARATOR_S \"%.16llx.conf\",_homePath.c_str(),(unsigned long long)id[0]);\n\t\t\t\tbreak;\n\t\t\tcase ZT_STATE_OBJECT_PEER:\n\t\t\t\tOSUtils::ztsnprintf(p,sizeof(p),\"%s\" ZT_PATH_SEPARATOR_S \"peers.d\" ZT_PATH_SEPARATOR_S \"%.10llx.peer\",_homePath.c_str(),(unsigned long long)id[0]);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn -1;\n\t\t}\n\t\tFILE *f = fopen(p,\"rb\");\n\t\tif (f) {\n\t\t\tint n = (int)fread(data,1,maxlen,f);\n\t\t\tfclose(f);\n#if ZT_VAULT_SUPPORT\n\t\t\tif (_vaultEnabled && (type == ZT_STATE_OBJECT_IDENTITY_SECRET || type == ZT_STATE_OBJECT_IDENTITY_PUBLIC)) {\n\t\t\t\t\/\/ If we've gotten here while Vault is enabled, Vault does not know the key and it's been\n\t\t\t\t\/\/ read from disk instead.\n\t\t\t\t\/\/\n\t\t\t\t\/\/ We should put the value in Vault and remove the local file.\n\t\t\t\tif (nodeVaultPutIdentity(type, data, n)) {\n\t\t\t\t\tunlink(p);\n\t\t\t\t}\n\t\t\t}\n#endif\n\t\t\tif (n >= 0)\n\t\t\t\treturn n;\n\t\t}\n\t\treturn -1;\n\t}\n\n\tinline int nodeWirePacketSendFunction(const int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)\n\t{\n\t\tint ret = 0;\n#ifdef ZT_TCP_FALLBACK_RELAY\n\t\t\n\t\tif(_allowTcpFallbackRelay) {\n\t\t\tif (addr->ss_family == AF_INET) {\n\t\t\t\t\/\/ TCP fallback tunnel support, currently IPv4 only\n\t\t\t\tif (len >= 16) {\n\t\t\t\t\/\/if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {\n\t\t\t\t\t\/\/ Engage TCP tunnel fallback if we haven't received anything valid from a global\n\t\t\t\t\t\/\/ IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting\n\t\t\t\t\t\/\/ valid direct traffic we'll stop using it and close the socket after a while.\n\t\t\t\t\tconst int64_t now = OSUtils::now();\n\t\t\t\t\tif (1) {\n\t\t\t\t\t\tif (_tcpFallbackTunnel) {\n\t\t\t\t\t\t\tbool flushNow = false;\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tMutex::Lock _l(_tcpFallbackTunnel->writeq_m);\n\t\t\t\t\t\t\t\tif (_tcpFallbackTunnel->writeq.size() < (1024 * 64)) {\n\t\t\t\t\t\t\t\t\tif (_tcpFallbackTunnel->writeq.length() == 0) {\n\t\t\t\t\t\t\t\t\t\t_phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);\n\t\t\t\t\t\t\t\t\t\tflushNow = true;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tconst unsigned long mlen = len + 7;\n\t\t\t\t\t\t\t\t\t_tcpFallbackTunnel->writeq.push_back((char)0x17);\n\t\t\t\t\t\t\t\t\t_tcpFallbackTunnel->writeq.push_back((char)0x03);\n\t\t\t\t\t\t\t\t\t_tcpFallbackTunnel->writeq.push_back((char)0x03); \/\/ fake TLS 1.2 header\n\t\t\t\t\t\t\t\t\t_tcpFallbackTunnel->writeq.push_back((char)((mlen >> 8) & 0xff));\n\t\t\t\t\t\t\t\t\t_tcpFallbackTunnel->writeq.push_back((char)(mlen & 0xff));\n\t\t\t\t\t\t\t\t\t_tcpFallbackTunnel->writeq.push_back((char)4); \/\/ IPv4\n\t\t\t\t\t\t\t\t\t_tcpFallbackTunnel->writeq.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);\n\t\t\t\t\t\t\t\t\t_tcpFallbackTunnel->writeq.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);\n\t\t\t\t\t\t\t\t\t_tcpFallbackTunnel->writeq.append((const char *)data,len);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (flushNow) {\n\t\t\t\t\t\t\t\tvoid *tmpptr = (void *)_tcpFallbackTunnel;\n\t\t\t\t\t\t\t\tif ((localSocket != -1)&&(localSocket != 0)) {\n\t\t\t\t\t\t\t\t\tphyOnTcpWritable((PhySocket *)localSocket,&tmpptr);\n\t\t\t\t\t\t\t\t\t}else {\n\t\t\t\t\t\t\t\t\tphyOnTcpWritable(_tcpFallbackTunnel->sock,&tmpptr);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL \/ 2))) {\n\t\t\t\t\t\t\tconst InetAddress addr(ZT_TCP_FALLBACK_RELAY);\n\t\t\t\t\t\t\tTcpConnection *tc = new TcpConnection();\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tMutex::Lock _l(_tcpConnections_m);\n\t\t\t\t\t\t\t\t_tcpConnections.push_back(tc);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttc->type = TcpConnection::TCP_TUNNEL_OUTGOING;\n\t\t\t\t\t\t\ttc->remoteAddr = addr;\n\t\t\t\t\t\t\ttc->lastReceive = OSUtils::now();\n\t\t\t\t\t\t\ttc->parent = this;\n\t\t\t\t\t\t\ttc->sock = (PhySocket *)0; \/\/ set in connect handler\n\t\t\t\t\t\t\ttc->messageSize = 0;\n\t\t\t\t\t\t\tbool connected = false;\n\t\t\t\t\t\t\tret = _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected,(void *)tc,true) ? 0 : -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t_lastSendToGlobalV4 = now;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#endif \/\/ ZT_TCP_FALLBACK_RELAY\n\t\treturn ret;\n\t\t\/\/ Even when relaying we still send via UDP. This way if UDP starts\n\t\t\/\/ working we can instantly \"fail forward\" to it and stop using TCP\n\t\t\/\/ proxy fallback, which is slow.\n\n\t\t\/*if ((localSocket != -1)&&(localSocket != 0)&&(_binder.isUdpSocketValid((PhySocket *)((uintptr_t)localSocket)))) {\n\t\t\tif ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),ttl);\n\t\t\tconst bool r = _phy.udpSend((PhySocket *)((uintptr_t)localSocket),(const struct sockaddr *)addr,data,len);\n\t\t\tif ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),255);\n\t\t\treturn ((r) ? 0 : -1);\n\t\t} else {\n\t\t\treturn ((_binder.udpSendAll(_phy,addr,data,len,ttl)) ? 0 : -1);\n\t\t}*\/\n\t}\n\n\tinline void nodeVirtualNetworkFrameFunction(uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)\n\t{\n\t\tNetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);\n\t\tif ((!n)||(!n->tap))\n\t\t\treturn;\n\t\tn->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);\n\t}\n\n\tinline int nodePathCheckFunction(uint64_t ztaddr,const int64_t localSocket,const struct sockaddr_storage *remoteAddr)\n\t{\n\t\t\/\/ Make sure we're not trying to do ZeroTier-over-ZeroTier\n\t\t{\n\t\t\tMutex::Lock _l(_nets_m);\n\t\t\tfor(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {\n\t\t\t\tif (n->second.tap) {\n\t\t\t\t\tstd::vector<InetAddress> ips(n->second.tap->ips());\n\t\t\t\t\tfor(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {\n\t\t\t\t\t\tif (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {\n\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/* Note: I do not think we need to scan for overlap with managed routes\n\t\t * because of the \"route forking\" and interface binding that we do. This\n\t\t * ensures (we hope) that ZeroTier traffic will still take the physical\n\t\t * path even if its managed routes override this for other traffic. Will\n\t\t * revisit if we see recursion problems. *\/\n\n\t\t\/\/ Check blacklists\n\t\tconst Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;\n\t\tconst std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;\n\t\tif (remoteAddr->ss_family == AF_INET) {\n\t\t\tblh = &_v4Blacklists;\n\t\t\tgbl = &_globalV4Blacklist;\n\t\t} else if (remoteAddr->ss_family == AF_INET6) {\n\t\t\tblh = &_v6Blacklists;\n\t\t\tgbl = &_globalV6Blacklist;\n\t\t}\n\t\tif (blh) {\n\t\t\tMutex::Lock _l(_localConfig_m);\n\t\t\tconst std::vector<InetAddress> *l = blh->get(ztaddr);\n\t\t\tif (l) {\n\t\t\t\tfor(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {\n\t\t\t\t\tif (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))\n\t\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (gbl) {\n\t\t\tfor(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {\n\t\t\t\tif (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\treturn 1;\n\t}\n\n\tinline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result)\n\t{\n\t\tconst Hashtable< uint64_t,std::vector<InetAddress> > *lh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;\n\t\tif (family < 0)\n\t\t\tlh = (_node->prng() & 1) ? &_v4Hints : &_v6Hints;\n\t\telse if (family == AF_INET)\n\t\t\tlh = &_v4Hints;\n\t\telse if (family == AF_INET6)\n\t\t\tlh = &_v6Hints;\n\t\telse return 0;\n\t\tconst std::vector<InetAddress> *l = lh->get(ztaddr);\n\t\tif ((l)&&(l->size() > 0)) {\n\t\t\tmemcpy(result,&((*l)[(unsigned long)_node->prng() % l->size()]),sizeof(struct sockaddr_storage));\n\t\t\treturn 1;\n\t\t} else return 0;\n\t}\n\n\tinline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)\n\t{\n\t\t_node->processVirtualNetworkFrame((void *)0,OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);\n\t}\n\n\tinline void onHttpRequestToServer(TcpConnection *tc)\n\t{\n\t\tchar tmpn[4096];\n\t\tstd::string data;\n\t\tstd::string contentType(\"text\/plain\"); \/\/ default if not changed in handleRequest()\n\t\tunsigned int scode = 404;\n\n\t\t\/\/ Note that we check allowed IP ranges when HTTP connections are first detected in\n\t\t\/\/ phyOnTcpData(). If we made it here the source IP is okay.\n\n\t\ttry {\n\t\t\tscode = handleControlPlaneHttpRequest(tc->remoteAddr,tc->parser.method,tc->url,tc->headers,tc->readq,data,contentType);\n\t\t} catch (std::exception &exc) {\n\t\t\tfprintf(stderr,\"WARNING: unexpected exception processing control HTTP request: %s\" ZT_EOL_S,exc.what());\n\t\t\tscode = 500;\n\t\t} catch ( ... ) {\n\t\t\tfprintf(stderr,\"WARNING: unexpected exception processing control HTTP request: unknown exception\" ZT_EOL_S);\n\t\t\tscode = 500;\n\t\t}\n\n\t\tconst char *scodestr;\n\t\tswitch(scode) {\n\t\t\tcase 200: scodestr = \"OK\"; break;\n\t\t\tcase 400: scodestr = \"Bad Request\"; break;\n\t\t\tcase 401: scodestr = \"Unauthorized\"; break;\n\t\t\tcase 403: scodestr = \"Forbidden\"; break;\n\t\t\tcase 404: scodestr = \"Not Found\"; break;\n\t\t\tcase 500: scodestr = \"Internal Server Error\"; break;\n\t\t\tcase 501: scodestr = \"Not Implemented\"; break;\n\t\t\tcase 503: scodestr = \"Service Unavailable\"; break;\n\t\t\tdefault: scodestr = \"Error\"; break;\n\t\t}\n\n\t\tOSUtils::ztsnprintf(tmpn,sizeof(tmpn),\"HTTP\/1.1 %.3u %s\\r\\nCache-Control: no-cache\\r\\nPragma: no-cache\\r\\nContent-Type: %s\\r\\nContent-Length: %lu\\r\\nConnection: close\\r\\n\\r\\n\",\n\t\t\tscode,\n\t\t\tscodestr,\n\t\t\tcontentType.c_str(),\n\t\t\t(unsigned long)data.length());\n\t\t{\n\t\t\tMutex::Lock _l(tc->writeq_m);\n\t\t\ttc->writeq = tmpn;\n\t\t\tif (tc->parser.method != HTTP_HEAD)\n\t\t\t\ttc->writeq.append(data);\n\t\t}\n\n\t\t_phy.setNotifyWritable(tc->sock,true);\n\t}\n\n\tinline void onHttpResponseFromClient(TcpConnection *tc)\n\t{\n\t\t_phy.close(tc->sock);\n\t}\n\n\tbool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)\n\t{\n#if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)\n\t\tif ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; \/\/ loopback\n\t\tif ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; \/\/ sanity check: zt#\n\t\tif ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; \/\/ tun# is probably an OpenVPN tunnel or similar\n\t\tif ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; \/\/ tap# is probably an OpenVPN tunnel or similar\n#endif\n\n#ifdef __APPLE__\n\t\tif ((ifname[0] == 'f')&&(ifname[1] == 'e')&&(ifname[2] == 't')&&(ifname[3] == 'h')) return false; \/\/ ... as is feth#\n\t\tif ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; \/\/ loopback\n\t\tif ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; \/\/ sanity check: zt#\n\t\tif ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; \/\/ tun# is probably an OpenVPN tunnel or similar\n\t\tif ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; \/\/ tap# is probably an OpenVPN tunnel or similar\n\t\tif ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; \/\/ ... as is utun#\n#endif\n\n\t\t{\n\t\t\tMutex::Lock _l(_localConfig_m);\n\t\t\tfor(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {\n\t\t\t\tif (!strncmp(p->c_str(),ifname,p->length()))\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t{\n\t\t\t\/\/ Check global blacklists\n\t\t\tconst std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;\n\t\t\tif (ifaddr.ss_family == AF_INET) {\n\t\t\t\tgbl = &_globalV4Blacklist;\n\t\t\t} else if (ifaddr.ss_family == AF_INET6) {\n\t\t\t\tgbl = &_globalV6Blacklist;\n\t\t\t}\n\t\t\tif (gbl) {\n\t\t\t\tMutex::Lock _l(_localConfig_m);\n\t\t\t\tfor(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {\n\t\t\t\t\tif (a->containsAddress(ifaddr))\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t{\n\t\t\tMutex::Lock _l(_nets_m);\n\t\t\tfor(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {\n\t\t\t\tif (n->second.tap) {\n\t\t\t\t\tstd::vector<InetAddress> ips(n->second.tap->ips());\n\t\t\t\t\tfor(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {\n\t\t\t\t\t\tif (i->ipsEqual(ifaddr))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool _trialBind(unsigned int port)\n\t{\n\t\tstruct sockaddr_in in4;\n\t\tstruct sockaddr_in6 in6;\n\t\tPhySocket *tb;\n\n\t\tmemset(&in4,0,sizeof(in4));\n\t\tin4.sin_family = AF_INET;\n\t\tin4.sin_port = Utils::hton((uint16_t)port);\n\t\ttb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);\n\t\tif (tb) {\n\t\t\t_phy.close(tb,false);\n\t\t\ttb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);\n\t\t\tif (tb) {\n\t\t\t\t_phy.close(tb,false);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tmemset(&in6,0,sizeof(in6));\n\t\tin6.sin6_family = AF_INET6;\n\t\tin6.sin6_port = Utils::hton((uint16_t)port);\n\t\ttb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);\n\t\tif (tb) {\n\t\t\t_phy.close(tb,false);\n\t\t\ttb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);\n\t\t\tif (tb) {\n\t\t\t\t_phy.close(tb,false);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n};\n\nstatic int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)\n{ return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }\nstatic void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData)\n{ reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }\nstatic void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)\n{ reinterpret_cast<OneServiceImpl *>(uptr)->nodeStatePutFunction(type,id,data,len); }\nstatic int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)\n{ return reinterpret_cast<OneServiceImpl *>(uptr)->nodeStateGetFunction(type,id,data,maxlen); }\nstatic int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,void *tptr,int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)\n{ return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localSocket,addr,data,len,ttl); }\nstatic void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)\n{ reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }\nstatic int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr)\n{ return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localSocket,remoteAddr); }\nstatic int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)\n{ return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }\nstatic void StapFrameHandler(void *uptr,void *tptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)\n{ reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }\n\nstatic int ShttpOnMessageBegin(http_parser *parser)\n{\n\tTcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);\n\ttc->currentHeaderField = \"\";\n\ttc->currentHeaderValue = \"\";\n\ttc->messageSize = 0;\n\ttc->url.clear();\n\ttc->status.clear();\n\ttc->headers.clear();\n\ttc->readq.clear();\n\treturn 0;\n}\nstatic int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)\n{\n\tTcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);\n\ttc->messageSize += (unsigned long)length;\n\tif (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)\n\t\treturn -1;\n\ttc->url.append(ptr,length);\n\treturn 0;\n}\n#if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)\nstatic int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)\n#else\nstatic int ShttpOnStatus(http_parser *parser)\n#endif\n{ return 0; }\nstatic int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)\n{\n\tTcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);\n\ttc->messageSize += (unsigned long)length;\n\tif (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)\n\t\treturn -1;\n\tif ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {\n\t\ttc->headers[tc->currentHeaderField] = tc->currentHeaderValue;\n\t\ttc->currentHeaderField = \"\";\n\t\ttc->currentHeaderValue = \"\";\n\t}\n\tfor(size_t i=0;i<length;++i)\n\t\ttc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));\n\treturn 0;\n}\nstatic int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)\n{\n\tTcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);\n\ttc->messageSize += (unsigned long)length;\n\tif (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)\n\t\treturn -1;\n\ttc->currentHeaderValue.append(ptr,length);\n\treturn 0;\n}\nstatic int ShttpOnHeadersComplete(http_parser *parser)\n{\n\tTcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);\n\tif ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))\n\t\ttc->headers[tc->currentHeaderField] = tc->currentHeaderValue;\n\treturn 0;\n}\nstatic int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)\n{\n\tTcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);\n\ttc->messageSize += (unsigned long)length;\n\tif (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)\n\t\treturn -1;\n\ttc->readq.append(ptr,length);\n\treturn 0;\n}\nstatic int ShttpOnMessageComplete(http_parser *parser)\n{\n\tTcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);\n\tif (tc->type == TcpConnection::TCP_HTTP_INCOMING) {\n\t\ttc->parent->onHttpRequestToServer(tc);\n\t} else {\n\t\ttc->parent->onHttpResponseFromClient(tc);\n\t}\n\treturn 0;\n}\n\n} \/\/ anonymous namespace\n\nstd::string OneService::platformDefaultHomePath()\n{\n\treturn OSUtils::platformDefaultHomePath();\n}\n\nOneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }\nOneService::~OneService() {}\n\n} \/\/ namespace ZeroTier\n","avg_line_length":34.8792927576,"max_line_length":295,"alphanum_fraction":0.661084032,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2703,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["IJG","FSFAP"],"max_stars_count":21.0,"content":"#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE imgimport\n#include \"frame.h\"\n#include \"pictureimport.h\"\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/log\/trivial.hpp>\n#include <dirent.h>\n#include <iostream>\n#include <fstream>\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include \"benchmark.h\"\n#include \"metadata_input.h\"\n#include \"metadata_reader.h\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace boost;\n\nBOOST_AUTO_TEST_CASE(picture_test){\n    string telemetry_path=boost::unit_test::framework::master_test_suite().argv[2];\n    telemetry_path+=\"\/test_csv.csv\";\n    string filePath=boost::unit_test::framework::master_test_suite().argv[1];\n\n    int count = 0;\n    DIR * dirp;\n    struct dirent * entry;\n\n    dirp = opendir(filePath.c_str());\n    while ((entry = readdir(dirp)) != NULL) {\n        if (entry->d_type == DT_REG) {\n             count++;\n        }\n    }\n    closedir(dirp);\n\n    BOOST_REQUIRE(count > 0);\n\n    MetadataInput* mdin = new MetadataInput();\n    mdin->add_source(new MetadataReader(*mdin, telemetry_path));\n    Camera camera = Camera::TestCamera();\n    PictureImport PI(filePath, mdin, camera);\n    DIR* dr=opendir(filePath.c_str());\n    struct dirent* drnt;\n    vector<Frame *> frames;\n    while(1){\n        Frame* show=PI.next_frame();\n        if(show==NULL){\n            break;\n        }\n        frames.push_back(show);\n    }\n\n    Metadata m = mdin->get_metadata(131017.4);\n    BOOST_CHECK(abs(m.time - 131017.3984375) < 0.00001);\n    BOOST_CHECK(abs(m.lat - 48.5107879638672) < 0.00001);\n    BOOST_CHECK(abs(m.lon - -71.6448364257812) < 0.00001);\n    BOOST_CHECK(abs(m.heading - 305) < 0.00001);\n    BOOST_CHECK(abs(m.altitude - 84.5625) < 0.01);\n    BOOST_TEST_MESSAGE(\"Altitude \" << m.altitude);\n\n    benchmark_function(\"Metadata Lookup\", [&]() { m = mdin->get_metadata((rand() % 255) + 130906); }, 1000);\n\n    BOOST_REQUIRE(frames.size() == count);\n\n    \/\/ Ensure that order is preserved when adding non-chronological data\n    mdin->add_source(new MetadataReader(*mdin, telemetry_path));\n    BOOST_REQUIRE(mdin->check_data_order() == 0);\n\n    for (Frame * show : frames) {\n        Mat picture_stored=show->get_img();\n        Mat original_picture;\n        while(original_picture.empty()){\n            drnt=readdir(dr);\n            string true_path=filePath+'\/'+drnt->d_name;\n            original_picture=imread(true_path,CV_LOAD_IMAGE_COLOR);\n        }\n        Mat diff;\n        compare(picture_stored,original_picture,diff,cv::CMP_NE);\n        Mat grey;\n        cvtColor(diff,grey,CV_BGR2GRAY);\n        int nz=countNonZero(grey);\n        BOOST_CHECK(nz==0);\n    }\n    delete mdin;\n}\n\n","avg_line_length":30.3707865169,"max_line_length":108,"alphanum_fraction":0.6544580096,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7985,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":11.0,"content":"\/\/===- unittests\/broker\/test_gc.cpp ---------------------------------------===\/\/\n\/\/*              *\n\/\/*   __ _  ___  *\n\/\/*  \/ _` |\/ __| *\n\/\/* | (_| | (__  *\n\/\/*  \\__, |\\___| *\n\/\/*  |___\/       *\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/github.com\/SNSystems\/pstore\/blob\/master\/LICENSE.txt for license\n\/\/ information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"pstore\/broker\/gc.hpp\"\n\n#include <cstring>\n#include <initializer_list>\n#include <thread>\n#include <vector>\n\n#include <gmock\/gmock.h>\n\n#include \"pstore\/support\/error.hpp\"\n\nusing testing::_;\nusing testing::ElementsAre;\nusing testing::Eq;\nusing testing::Expectation;\nusing testing::Return;\nusing testing::StrEq;\n\nnamespace {\n\n    using czstring = pstore::gsl::czstring;\n    using process_identifier = pstore::broker::process_identifier;\n\n    class test_watch_thread : public pstore::broker::gc_watch_thread {\n    public:\n        test_watch_thread () = default;\n\n        \/\/ No copying or assignment.\n        test_watch_thread (test_watch_thread const &) = delete;\n        test_watch_thread (test_watch_thread &&) = delete;\n        test_watch_thread & operator= (test_watch_thread const &) = delete;\n        test_watch_thread & operator= (test_watch_thread &&) = delete;\n\n        MOCK_METHOD1 (spawn, process_identifier (std::initializer_list<czstring>));\n        MOCK_METHOD1 (kill, void (process_identifier const &));\n    };\n\n    class Gc : public ::testing::Test {\n    protected:\n        static std::string const vacuum_exe;\n\n        using spawn_params = std::tuple<std::string, process_identifier>;\n\n        \/\/\/ Creates a platform-specific fake process identifier.\n        \/\/\/ \\param index  A value used to make unique process IDs.\n        static process_identifier make_process_id (int index = 0);\n\n        \/\/\/ Creates expectations of calls on the test_watch_thread mock that a GC process for the\n        \/\/\/ file at \\p path will be spawned and later killed.\n        \/\/\/\n        \/\/\/ \\param gc  A GC watch-thread instance.\n        \/\/\/ \\param path The (fake) path of the process executable being created.\n        \/\/\/ \\param pid  The pid used to identify the (fake) process.\n        static void expect_call (test_watch_thread & gc, std::string const & path,\n                                 process_identifier pid);\n        \/\/\/ Creates expectations of calls on the test_watch_thread mock that a GC process for the\n        \/\/\/ file at \\p path will be spawned and later killed.\n        \/\/\/\n        \/\/\/ \\param gc  A GC watch-thread instance.\n        \/\/\/ \\param params A tuple containing both the path of the file to be garbage-collected and\n        \/\/\/ the fake process ID.\n        static void expect_call (test_watch_thread & gc, spawn_params const & params);\n\n        \/\/\/ Creates a series of \\p num expectations that multiple GC requests will be performed.\n        \/\/\/ Each will spawn a GC process for it to be later killed when the gc-watcher thread exits.\n        \/\/\/\n        \/\/\/ \\param gc  A GC watch-thread instance.\n        \/\/\/ \\param num The number of processes that will be created.\n        static auto expect_spawn_calls (test_watch_thread & gc, unsigned num)\n            -> std::vector<spawn_params>;\n\n        static spawn_params call_params (int count);\n    };\n\n    std::string const Gc::vacuum_exe = test_watch_thread::vacuumd_path ();\n\n    \/\/ make_process_id\n    \/\/ ~~~~~~~~~~~~~~~\n    process_identifier Gc::make_process_id (int index) {\n        int const id = 7919 + index; \/\/ No significance to this number: it's just the 1000th prime\n#ifdef _WIN32\n        HANDLE event = ::CreateEventW (nullptr, \/\/ event attributes\n                                       false,   \/\/ manual reset\n                                       false,   \/\/ initial state\n                                       nullptr  \/\/ name\n        );\n        if (event == nullptr) {\n            raise (pstore::win32_erc{::GetLastError ()}, \"CreateEventW\");\n        }\n        return std::make_shared<pstore::broker::win32::process_pair> (event, id);\n#else\n        return id;\n#endif \/\/ _WIN32\n    }\n\n    \/\/ call_params\n    \/\/ ~~~~~~~~~~~\n    auto Gc::call_params (int count) -> spawn_params {\n        return spawn_params{\"path\" + std::to_string (count), make_process_id (count)};\n    }\n\n    \/\/ expect_call\n    \/\/ ~~~~~~~~~~~\n    void Gc::expect_call (test_watch_thread & gc, std::string const & path,\n                          process_identifier pid) {\n        Expectation const exp =\n            EXPECT_CALL (gc,\n                         spawn (ElementsAre (StrEq (vacuum_exe.c_str ()), StrEq (path), nullptr)))\n                .WillOnce (Return (pid));\n        EXPECT_CALL (gc, kill (Eq (pid))).Times (1).After (exp);\n    }\n\n    void Gc::expect_call (test_watch_thread & gc, spawn_params const & params) {\n        expect_call (gc, std::get<std::string> (params), std::get<process_identifier> (params));\n    }\n\n    \/\/ expect_spawn_calls\n    \/\/ ~~~~~~~~~~~~~~~~~~\n    auto Gc::expect_spawn_calls (test_watch_thread & gc, unsigned num)\n        -> std::vector<spawn_params> {\n        std::vector<spawn_params> calls;\n        calls.reserve (num);\n\n        PSTORE_ASSERT (num <= static_cast<unsigned> (std::numeric_limits<int>::max ()));\n        for (auto count = 0; count < static_cast<int> (num); ++count) {\n            calls.push_back (call_params (static_cast<int> (count)));\n            expect_call (gc, calls.back ());\n        }\n\n        return calls;\n    }\n\n} \/\/ end anonymous namespace\n\nTEST_F (Gc, Nothing) {\n    test_watch_thread gc;\n    EXPECT_CALL (gc, spawn (_)).Times (0);\n    EXPECT_CALL (gc, kill (_)).Times (0);\n\n    std::thread thread{[&gc] () { gc.watcher (); }};\n    gc.stop ();\n    thread.join ();\n}\n\nTEST_F (Gc, SpawnOne) {\n    constexpr auto path = \"db-path\";\n\n    test_watch_thread gc;\n    expect_call (gc, path, make_process_id ());\n\n    std::thread thread{[&gc] () { gc.watcher (); }};\n    \/\/ Initiate garbage collection of the pstore file at path.\n    gc.start_vacuum (path);\n    \/\/ Our simulation never indicates that the GC process has exited. Therefore a second GC\n    \/\/ request should be ignored.\n    gc.start_vacuum (path);\n\n    gc.stop ();\n    thread.join ();\n}\n\nTEST_F (Gc, SpawnTwo) {\n    auto call0 = call_params (0);\n    auto call1 = call_params (1);\n\n    test_watch_thread gc;\n    expect_call (gc, call0);\n    expect_call (gc, call1);\n\n    std::thread thread{[&gc] () { gc.watcher (); }};\n\n    gc.start_vacuum (std::get<std::string> (call0));\n    gc.start_vacuum (std::get<std::string> (call1));\n    gc.start_vacuum (std::get<std::string> (call0));\n    gc.start_vacuum (std::get<std::string> (call1));\n\n    gc.stop ();\n    thread.join ();\n}\n\nTEST_F (Gc, SpawnMax) {\n    test_watch_thread gc;\n\n    auto const sp = expect_spawn_calls (gc, pstore::broker::gc_watch_thread::max_gc_processes);\n    std::thread thread{[&gc] () { gc.watcher (); }};\n    for (auto const & c : sp) {\n        gc.start_vacuum (std::get<std::string> (c));\n    }\n    gc.stop ();\n    thread.join ();\n}\n\nTEST_F (Gc, SpawnMaxPlus1) {\n    test_watch_thread gc;\n\n    auto const sp = expect_spawn_calls (gc, pstore::broker::gc_watch_thread::max_gc_processes);\n    std::thread thread{[&gc] () { gc.watcher (); }};\n    for (auto const & c : sp) {\n        gc.start_vacuum (std::get<std::string> (c));\n    }\n    gc.start_vacuum (\"one-extra-call\");\n    gc.stop ();\n    thread.join ();\n}\n\nTEST_F (Gc, StartAndKill) {\n    constexpr auto path = \"path0\";\n    auto call0 = call_params (0);\n\n    test_watch_thread gc;\n    expect_call (gc, call0);\n\n    std::thread thread{[&gc] () { gc.watcher (); }};\n    gc.start_vacuum (path);\n    EXPECT_EQ (gc.size (), 1U);\n    gc.stop_vacuum (path);\n    EXPECT_EQ (gc.size (), 0U);\n    gc.stop_vacuum (path);\n    EXPECT_EQ (gc.size (), 0U);\n    gc.stop ();\n    thread.join ();\n}\n","avg_line_length":33.5504201681,"max_line_length":100,"alphanum_fraction":0.5921102066,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":397,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"up.h\"\r\n#include <cstring>\r\n#include <sstream> \/\/cout\uacfc \uac19\uc74c \ubb38\uc790\uc5f4\ub85c \ucd9c\ub825\r\n\r\n\r\n\r\nUp::Up()\r\n{\r\n\tcommand = new char[strlen(\"up 20\")+1];\r\n\tstrcpy(command, \"up 20\");\r\n}\r\n\r\nUp::Up(int _value)\r\n{\r\n\tstd::stringstream sstream;\r\n\tsstream << \"up \" << _value;\r\n\tcommand = new char[strlen(sstream.str().c_str())+1];\r\n\tstrcpy(command, sstream.str().c_str());\r\n\r\n}\r\n\r\ndouble Up::get_delay()\r\n{ \r\n\treturn 5; \r\n}","avg_line_length":15.88,"max_line_length":54,"alphanum_fraction":0.5919395466,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":781,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#define d 256\n\nvoid KarpRabinSearch(char text[], char pattern[], int q)    \/\/ q is a prime number for hashing.\n{\n    int N = strlen(text), M = strlen(pattern);\n    int i, j;\n    int ht = 0, hp = 0, h = 1;\n\n    for (i = 0; i < M - 1; i++)\n        h = (d * h) % q;\n\n    for (i = 0; i < M; i++) {\n        hp = (d * hp + pattern[i]) % q;\n        ht = (d * ht + pattern[i]) % q;\n    }\n\n    for (i = 0; i < N - M; i++) {\n        if (hp == ht)    \/\/possible match, compare char by char.\n        {\n            for (j = 0; j < M; j++)\n                if (pattern[j] != text[i + j]) break;\n            if (j == M)\n                printf(\"Found a match at index %d\", i);\n        }\n        ht = (d * (ht[i] - (text[i] * h)) + text[i + M]) % q;\n\n        if (ht < 0)\n            ht += q;\n    }\n}","avg_line_length":26.0333333333,"max_line_length":95,"alphanum_fraction":0.3854033291,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2595,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n * Copyright (c) 2018 David 'Mokon' Bond <mokon@mokon.net>\n * Author: David 'Mokon' Bond <mokon@mokon.net>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <cassert>\n#include <Diagnostics.hpp>\n#include <linux\/ExitHandler.hpp>\n\nnamespace apm {\n\nExitHandler*\nExitHandler::getInstance()\n{\n    allowExitTimeDestruction(static ExitHandler instance;);\n    return &instance;\n}\n\nvoid\nExitHandler::setEventMonitor(EventMonitor& _eventMonitor)\n{\n    assert(eventMonitor == nullptr);\n    eventMonitor = &_eventMonitor;\n}\n\nExitHandler::ExitHandler()\n{\n    for (auto sig : signals)\n    {\n        registerSignal(sig);\n    }\n}\n\nExitHandler::~ExitHandler()\n{\n    for (auto sig : signals)\n    {\n        unregisterSignal(sig);\n    }\n}\n\nvoid\nExitHandler::registerSignal(int sig)\n{\n    struct sigaction action\n    {\n    };\n    action.sa_sigaction = &signalHandler;\n    action.sa_flags     = SA_SIGINFO;\n\n    if (sigaction(sig, &action, nullptr) < 0)\n    {\n        throw std::system_error(errno, std::generic_category());\n    }\n}\n\nvoid\nExitHandler::unregisterSignal(int sig)\n{\n    struct sigaction action\n    {\n    };\n    action.sa_handler = SIG_DFL;\n\n    if (sigaction(sig, &action, nullptr) < 0)\n    {\n        std::perror(\"failed to unregister signal\");\n    }\n}\n\nvoid\nExitHandler::signalHandler(int sig, siginfo_t* siginfo, void* context)\n{\n    (void)sig;\n    (void)siginfo;\n    (void)context;\n    assert(getInstance() != nullptr);\n\n    if (getInstance()->eventMonitor.load() != nullptr)\n    {\n        getInstance()->eventMonitor.load()->stop();\n    }\n}\n\n} \/\/ namespace apm\n","avg_line_length":25.1941747573,"max_line_length":83,"alphanum_fraction":0.6959537572,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11800,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include \"bgspch.h\"\n\n#include \"mat4.h\"\n\n#include <sstream>\n\n#include \"quaternion.h\"\n\nnamespace BIGOS {\n\tnamespace math {\n\n\t\tmat4::mat4()\n\t\t{\n\t\t\tmemset(elements, 0, 4 * 4 * sizeof(float));\n\t\t}\n\n\t\tmat4::mat4(float diagonal)\n\t\t{\n\t\t\tmemset(elements, 0, 4 * 4 * sizeof(float));\n\t\t\telements[0 + 0 * 4] = diagonal;\n\t\t\telements[1 + 1 * 4] = diagonal;\n\t\t\telements[2 + 2 * 4] = diagonal;\n\t\t\telements[3 + 3 * 4] = diagonal;\n\t\t}\n\n\t\tmat4::mat4(float* elements)\n\t\t{\n\t\t\tmemcpy(this->elements, elements, 4 * 4 * sizeof(float));\n\t\t}\n\n\t\tmat4::mat4(const vec4& row0, const vec4& row1, const vec4& row2, const vec4& row3)\n\t\t{\n\t\t\trows[0] = row0;\n\t\t\trows[1] = row1;\n\t\t\trows[2] = row2;\n\t\t\trows[3] = row3;\n\t\t}\n\n\t\tmat4 mat4::Identity()\n\t\t{\n\t\t\treturn mat4(1.0f);\n\t\t}\n\n\t\tmat4& mat4::Multiply(const mat4& other)\n\t\t{\n\t\t\tfloat data[16];\n\t\t\tfor (uint32_t row = 0; row < 4; row++)\n\t\t\t{\n\t\t\t\tfor (uint32_t col = 0; col < 4; col++)\n\t\t\t\t{\n\t\t\t\t\tfloat sum = 0.0f;\n\t\t\t\t\tfor (uint32_t e = 0; e < 4; e++)\n\t\t\t\t\t{\n\t\t\t\t\t\tsum += elements[e + row * 4] * other.elements[col + e * 4];\n\t\t\t\t\t}\n\t\t\t\t\tdata[col + row * 4] = sum;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmemcpy(elements, data, 4 * 4 * sizeof(float));\n\t\t\treturn *this;\n\t\t}\n\n\t\tvec3 mat4::Multiply(const vec3& other) const\n\t\t{\n\t\t\treturn other.Multiply(*this);\n\t\t}\n\n\t\tvec4 mat4::Multiply(const vec4& other) const\n\t\t{\n\t\t\treturn other.Multiply(*this);\n\t\t}\n\n\t\tmat4 operator*(mat4 left, const mat4& right)\n\t\t{\n\t\t\treturn left.Multiply(right);\n\t\t}\n\n\t\tmat4& mat4::operator*=(const mat4& other)\n\t\t{\n\t\t\treturn Multiply(other);\n\t\t}\n\n\t\tvec3 operator*(const mat4& left, const vec3& right)\n\t\t{\n\t\t\treturn left.Multiply(right);\n\t\t}\n\n\t\tvec4 operator*(const mat4& left, const vec4& right)\n\t\t{\n\t\t\treturn left.Multiply(right);\n\t\t}\n\n\t\tmat4& mat4::Invert()\n\t\t{\n\t\t\tfloat temp[16];\n\n\t\t\ttemp[0] = elements[5] * elements[10] * elements[15] -\n\t\t\t\telements[5] * elements[11] * elements[14] -\n\t\t\t\telements[9] * elements[6] * elements[15] +\n\t\t\t\telements[9] * elements[7] * elements[14] +\n\t\t\t\telements[13] * elements[6] * elements[11] -\n\t\t\t\telements[13] * elements[7] * elements[10];\n\n\t\t\ttemp[4] = -elements[4] * elements[10] * elements[15] +\n\t\t\t\telements[4] * elements[11] * elements[14] +\n\t\t\t\telements[8] * elements[6] * elements[15] -\n\t\t\t\telements[8] * elements[7] * elements[14] -\n\t\t\t\telements[12] * elements[6] * elements[11] +\n\t\t\t\telements[12] * elements[7] * elements[10];\n\n\t\t\ttemp[8] = elements[4] * elements[9] * elements[15] -\n\t\t\t\telements[4] * elements[11] * elements[13] -\n\t\t\t\telements[8] * elements[5] * elements[15] +\n\t\t\t\telements[8] * elements[7] * elements[13] +\n\t\t\t\telements[12] * elements[5] * elements[11] -\n\t\t\t\telements[12] * elements[7] * elements[9];\n\n\t\t\ttemp[12] = -elements[4] * elements[9] * elements[14] +\n\t\t\t\telements[4] * elements[10] * elements[13] +\n\t\t\t\telements[8] * elements[5] * elements[14] -\n\t\t\t\telements[8] * elements[6] * elements[13] -\n\t\t\t\telements[12] * elements[5] * elements[10] +\n\t\t\t\telements[12] * elements[6] * elements[9];\n\n\t\t\ttemp[1] = -elements[1] * elements[10] * elements[15] +\n\t\t\t\telements[1] * elements[11] * elements[14] +\n\t\t\t\telements[9] * elements[2] * elements[15] -\n\t\t\t\telements[9] * elements[3] * elements[14] -\n\t\t\t\telements[13] * elements[2] * elements[11] +\n\t\t\t\telements[13] * elements[3] * elements[10];\n\n\t\t\ttemp[5] = elements[0] * elements[10] * elements[15] -\n\t\t\t\telements[0] * elements[11] * elements[14] -\n\t\t\t\telements[8] * elements[2] * elements[15] +\n\t\t\t\telements[8] * elements[3] * elements[14] +\n\t\t\t\telements[12] * elements[2] * elements[11] -\n\t\t\t\telements[12] * elements[3] * elements[10];\n\n\t\t\ttemp[9] = -elements[0] * elements[9] * elements[15] +\n\t\t\t\telements[0] * elements[11] * elements[13] +\n\t\t\t\telements[8] * elements[1] * elements[15] -\n\t\t\t\telements[8] * elements[3] * elements[13] -\n\t\t\t\telements[12] * elements[1] * elements[11] +\n\t\t\t\telements[12] * elements[3] * elements[9];\n\n\t\t\ttemp[13] = elements[0] * elements[9] * elements[14] -\n\t\t\t\telements[0] * elements[10] * elements[13] -\n\t\t\t\telements[8] * elements[1] * elements[14] +\n\t\t\t\telements[8] * elements[2] * elements[13] +\n\t\t\t\telements[12] * elements[1] * elements[10] -\n\t\t\t\telements[12] * elements[2] * elements[9];\n\n\t\t\ttemp[2] = elements[1] * elements[6] * elements[15] -\n\t\t\t\telements[1] * elements[7] * elements[14] -\n\t\t\t\telements[5] * elements[2] * elements[15] +\n\t\t\t\telements[5] * elements[3] * elements[14] +\n\t\t\t\telements[13] * elements[2] * elements[7] -\n\t\t\t\telements[13] * elements[3] * elements[6];\n\n\t\t\ttemp[6] = -elements[0] * elements[6] * elements[15] +\n\t\t\t\telements[0] * elements[7] * elements[14] +\n\t\t\t\telements[4] * elements[2] * elements[15] -\n\t\t\t\telements[4] * elements[3] * elements[14] -\n\t\t\t\telements[12] * elements[2] * elements[7] +\n\t\t\t\telements[12] * elements[3] * elements[6];\n\n\t\t\ttemp[10] = elements[0] * elements[5] * elements[15] -\n\t\t\t\telements[0] * elements[7] * elements[13] -\n\t\t\t\telements[4] * elements[1] * elements[15] +\n\t\t\t\telements[4] * elements[3] * elements[13] +\n\t\t\t\telements[12] * elements[1] * elements[7] -\n\t\t\t\telements[12] * elements[3] * elements[5];\n\n\t\t\ttemp[14] = -elements[0] * elements[5] * elements[14] +\n\t\t\t\telements[0] * elements[6] * elements[13] +\n\t\t\t\telements[4] * elements[1] * elements[14] -\n\t\t\t\telements[4] * elements[2] * elements[13] -\n\t\t\t\telements[12] * elements[1] * elements[6] +\n\t\t\t\telements[12] * elements[2] * elements[5];\n\n\t\t\ttemp[3] = -elements[1] * elements[6] * elements[11] +\n\t\t\t\telements[1] * elements[7] * elements[10] +\n\t\t\t\telements[5] * elements[2] * elements[11] -\n\t\t\t\telements[5] * elements[3] * elements[10] -\n\t\t\t\telements[9] * elements[2] * elements[7] +\n\t\t\t\telements[9] * elements[3] * elements[6];\n\n\t\t\ttemp[7] = elements[0] * elements[6] * elements[11] -\n\t\t\t\telements[0] * elements[7] * elements[10] -\n\t\t\t\telements[4] * elements[2] * elements[11] +\n\t\t\t\telements[4] * elements[3] * elements[10] +\n\t\t\t\telements[8] * elements[2] * elements[7] -\n\t\t\t\telements[8] * elements[3] * elements[6];\n\n\t\t\ttemp[11] = -elements[0] * elements[5] * elements[11] +\n\t\t\t\telements[0] * elements[7] * elements[9] +\n\t\t\t\telements[4] * elements[1] * elements[11] -\n\t\t\t\telements[4] * elements[3] * elements[9] -\n\t\t\t\telements[8] * elements[1] * elements[7] +\n\t\t\t\telements[8] * elements[3] * elements[5];\n\n\t\t\ttemp[15] = elements[0] * elements[5] * elements[10] -\n\t\t\t\telements[0] * elements[6] * elements[9] -\n\t\t\t\telements[4] * elements[1] * elements[10] +\n\t\t\t\telements[4] * elements[2] * elements[9] +\n\t\t\t\telements[8] * elements[1] * elements[6] -\n\t\t\t\telements[8] * elements[2] * elements[5];\n\n\t\t\tfloat determinant = elements[0] * temp[0] + elements[1] * temp[4] + elements[2] * temp[8] + elements[3] * temp[12];\n\t\t\tdeterminant = 1.0f \/ determinant;\n\n\t\t\tfor (uint32_t i = 0; i < 4 * 4; i++)\n\t\t\t\telements[i] = temp[i] * determinant;\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tvec4 mat4::GetColumn(int index) const\n\t\t{\n\t\t\treturn vec4(elements[index + 0 * 4], elements[index + 1 * 4], elements[index + 2 * 4], elements[index + 3 * 4]);\n\t\t}\n\n\t\tvoid mat4::SetColumn(uint32_t index, const vec4& column)\n\t\t{\n\t\t\telements[index + 0 * 4] = column.x;\n\t\t\telements[index + 1 * 4] = column.y;\n\t\t\telements[index + 2 * 4] = column.z;\n\t\t\telements[index + 3 * 4] = column.w;\n\t\t}\n\n\t\tmat4 mat4::Orthographic(float left, float right, float bottom, float top, float nearClip, float farClip)\n\t\t{\n\t\t\tmat4 result(1.0f);\n\n\t\t\tresult.elements[0 + 0 * 4] = 2.0f \/ (right - left);\n\n\t\t\tresult.elements[1 + 1 * 4] = 2.0f \/ (top - bottom);\n\n\t\t\tresult.elements[2 + 2 * 4] = 2.0f \/ (nearClip - farClip);\n\n\t\t\tresult.elements[3 + 0 * 4] = (left + right) \/ (left - right);\n\t\t\tresult.elements[3 + 1 * 4] = (bottom + top) \/ (bottom - top);\n\t\t\tresult.elements[3 + 2 * 4] = (farClip + nearClip) \/ (farClip - nearClip);\n\n\t\t\treturn result;\n\t\t}\n\n\t\tmat4 mat4::Perspective(float fov, float aspectRatio, float nearClip, float farClip)\n\t\t{\n\t\t\tmat4 result(1.0f);\n\n\t\t\tfloat q = 1.0f \/ tan(toRadians(0.5f * fov));\n\t\t\tfloat a = q \/ aspectRatio;\n\n\t\t\tfloat b = (nearClip + farClip) \/ (nearClip - farClip);\n\t\t\tfloat c = (2.0f * nearClip * farClip) \/ (nearClip - farClip);\n\n\t\t\tresult.elements[0 + 0 * 4] = a;\n\t\t\tresult.elements[1 + 1 * 4] = q;\n\t\t\tresult.elements[2 + 2 * 4] = b;\n\t\t\tresult.elements[2 + 3 * 4] = -1.0f;\n\t\t\tresult.elements[3 + 2 * 4] = c;\n\n\t\t\treturn result;\n\t\t}\n\n\t\tmat4 mat4::LookAt(const vec3& camera, const vec3& object, const vec3& up)\n\t\t{\n\t\t\tmat4 result = Identity();\n\t\t\tvec3 f = (object - camera).Normalize();\n\t\t\tvec3 s = f.Cross(up.Normalize());\n\t\t\tvec3 u = s.Cross(f);\n\n\t\t\tresult.elements[0 + 0 * 4] = s.x;\n\t\t\tresult.elements[0 + 1 * 4] = s.y;\n\t\t\tresult.elements[0 + 2 * 4] = s.z;\n\n\t\t\tresult.elements[1 + 0 * 4] = u.x;\n\t\t\tresult.elements[1 + 1 * 4] = u.y;\n\t\t\tresult.elements[1 + 2 * 4] = u.z;\n\n\t\t\tresult.elements[2 + 0 * 4] = -f.x;\n\t\t\tresult.elements[2 + 1 * 4] = -f.y;\n\t\t\tresult.elements[2 + 2 * 4] = -f.z;\n\n\t\t\treturn result * Translate(vec3(-camera.x, -camera.y, -camera.z));\n\t\t}\n\n\t\tmat4 mat4::Translate(const vec3& translation)\n\t\t{\n\t\t\tmat4 result(1.0f);\n\n\t\t\tresult.elements[3 + 0 * 4] = translation.x;\n\t\t\tresult.elements[3 + 1 * 4] = translation.y;\n\t\t\tresult.elements[3 + 2 * 4] = translation.z;\n\n\t\t\treturn result;\n\t\t}\n\n\t\tmat4 mat4::Rotate(float angle, const vec3& axis)\n\t\t{\n\t\t\tmat4 result(1.0f);\n\n\t\t\tfloat r = toRadians(angle);\n\t\t\tfloat c = cos(r);\n\t\t\tfloat s = sin(r);\n\t\t\tfloat omc = 1.0f - c;\n\n\t\t\tfloat x = axis.x;\n\t\t\tfloat y = axis.y;\n\t\t\tfloat z = axis.z;\n\n\t\t\tresult.elements[0 + 0 * 4] = x * x * omc + c;\n\t\t\tresult.elements[0 + 1 * 4] = y * x * omc + z * s;\n\t\t\tresult.elements[0 + 2 * 4] = x * z * omc - y * s;\n\n\t\t\tresult.elements[1 + 0 * 4] = x * y * omc - z * s;\n\t\t\tresult.elements[1 + 1 * 4] = y * y * omc + c;\n\t\t\tresult.elements[1 + 2 * 4] = y * z * omc + x * s;\n\n\t\t\tresult.elements[2 + 0 * 4] = x * z * omc + y * s;\n\t\t\tresult.elements[2 + 1 * 4] = y * z * omc - x * s;\n\t\t\tresult.elements[2 + 2 * 4] = z * z * omc + c;\n\n\t\t\treturn result;\n\t\t}\n\n\t\tmat4 mat4::Rotate(const quat& quaternion)\n\t\t{\n\t\t\tmat4 result = Identity();\n\n\t\t\tfloat qx, qy, qz, qw, qx2, qy2, qz2, qxqx2, qyqy2, qzqz2, qxqy2, qyqz2, qzqw2, qxqz2, qyqw2, qxqw2;\n\t\t\tqx = quaternion.x;\n\t\t\tqy = quaternion.y;\n\t\t\tqz = quaternion.z;\n\t\t\tqw = quaternion.w;\n\t\t\tqx2 = (qx + qx);\n\t\t\tqy2 = (qy + qy);\n\t\t\tqz2 = (qz + qz);\n\t\t\tqxqx2 = (qx * qx2);\n\t\t\tqxqy2 = (qx * qy2);\n\t\t\tqxqz2 = (qx * qz2);\n\t\t\tqxqw2 = (qw * qx2);\n\t\t\tqyqy2 = (qy * qy2);\n\t\t\tqyqz2 = (qy * qz2);\n\t\t\tqyqw2 = (qw * qy2);\n\t\t\tqzqz2 = (qz * qz2);\n\t\t\tqzqw2 = (qw * qz2);\n\n\t\t\tresult.rows[0] = vec4(((1.0f - qyqy2) - qzqz2), (qxqy2 - qzqw2), (qxqz2 + qyqw2), 0.0f);\n\t\t\tresult.rows[1] = vec4((qxqy2 + qzqw2), ((1.0f - qxqx2) - qzqz2), (qyqz2 - qxqw2), 0.0f);\n\t\t\tresult.rows[2] = vec4((qxqz2 - qyqw2), (qyqz2 + qxqw2), ((1.0f - qxqx2) - qyqy2), 0.0f);\n\t\t\treturn result;\n\t\t}\n\n\t\tmat4 mat4::Scale(const vec3& scale)\n\t\t{\n\t\t\tmat4 result(1.0f);\n\n\t\t\tresult.elements[0 + 0 * 4] = scale.x;\n\t\t\tresult.elements[1 + 1 * 4] = scale.y;\n\t\t\tresult.elements[2 + 2 * 4] = scale.z;\n\n\t\t\treturn result;\n\t\t}\n\n\t\tmat4 mat4::Invert(const mat4& matrix)\n\t\t{\n\t\t\tmat4 result = matrix;\n\t\t\treturn result.Invert();\n\t\t}\n\n\t\tmat4 mat4::Transpose(const mat4& matrix)\n\t\t{\n\t\t\treturn mat4(\n\t\t\t\tvec4(matrix.rows[0].x, matrix.rows[1].x, matrix.rows[2].x, matrix.rows[3].x),\n\t\t\t\tvec4(matrix.rows[0].y, matrix.rows[1].y, matrix.rows[2].y, matrix.rows[3].y),\n\t\t\t\tvec4(matrix.rows[0].z, matrix.rows[1].z, matrix.rows[2].z, matrix.rows[3].z),\n\t\t\t\tvec4(matrix.rows[0].w, matrix.rows[1].w, matrix.rows[2].w, matrix.rows[3].w)\n\t\t\t);\n\t\t}\n\n\t\tstd::string mat4::ToString() const\n\t\t{\n\t\t\tstd::stringstream result;\n\t\t\tresult << \"mat4: (\" << rows[0].x << \", \" << rows[1].x << \", \" << rows[2].x << \", \" << rows[3].x << \"), \";\n\t\t\tresult << \"(\" << rows[0].y << \", \" << rows[1].y << \", \" << rows[2].y << \", \" << rows[3].y << \"), \";\n\t\t\tresult << \"(\" << rows[0].z << \", \" << rows[1].z << \", \" << rows[2].z << \", \" << rows[3].z << \"), \";\n\t\t\tresult << \"(\" << rows[0].w << \", \" << rows[1].w << \", \" << rows[2].w << \", \" << rows[3].w << \")\";\n\t\t\treturn result.str();\n\t\t}\n\n\t}\n}","avg_line_length":29.9492385787,"max_line_length":118,"alphanum_fraction":0.5694915254,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2291,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":21.0,"content":"#include \"p3ui.h\"\n#include \"numpy.h\"\n\n#include <p3\/Texture.h>\n#include <fmt\/format.h>\n\n\nnamespace p3::python\n{\n\n    namespace\n    {\n        void copy(p3::Texture& texture, py::array_t<std::uint8_t> const& data)\n        {\n            auto in = data.request();\n            if (in.shape.size() != 3)\n                throw std::invalid_argument(fmt::format(\"array has wrong shape dimension of {}\", in.shape.size()));\n            auto depth = in.shape[2];\n            if (depth != 4)\n                throw std::invalid_argument(fmt::format(\"only rgba is supported, but image has {} channels\", depth));\n            auto height = in.shape[0];\n            auto width = in.shape[1];\n            if (width * height == 0)\n                return;\n            if (width != texture.width() || height != texture.height())\n                texture.resize(width, height);\n            auto src = reinterpret_cast<std::uint8_t*>(in.ptr);\n            std::memcpy(texture.data(), in.ptr, width * height * depth);\n        }\n    }\n\n    void Definition<Texture>::apply(py::module& module)\n    {\n        auto texture = py::class_<Texture, std::shared_ptr<Texture>>(module, \"Texture\");\n\n        texture.def(py::init<>([](std::size_t width, std::size_t height) {\n            return std::make_shared<Texture>(width, height);\n        })).def(py::init<>([]() {\n            return std::make_shared<Texture>(0, 0);\n        })).def(py::init<>([](py::array_t<std::uint8_t> data) {\n            auto texture = std::make_shared<Texture>(0, 0);\n            copy(*texture, data);\n            texture->update();\n            return texture;\n        }));\n\n        texture.def_property(\"data\", [](std::shared_ptr<Texture> texture) {\n            decltype(texture->lock()) guard;\n            {\n                py::gil_scoped_release release;\n                guard = texture->lock();\n            }\n            return wrap<std::uint8_t>(texture->data(), texture->height(), texture->width(), 4).attr(\"copy\")();\n        }, [](std::shared_ptr<Texture> texture, py::array_t<std::uint8_t> data) {\n            decltype(texture->lock()) guard;\n            {\n                py::gil_scoped_release release;\n                guard = texture->lock();\n            }\n            copy(*texture, data);\n            texture->update();\n        });\n    }\n\n}","avg_line_length":35.2461538462,"max_line_length":117,"alphanum_fraction":0.5202968136,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":19449,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#ifdef HAVE_CONFIG_H\n#include \"config\/executecoin-config.h\"\n#endif\n\n#include \"netaddress.h\"\n#include \"netbase.h\"\n#include \"hash.h\"\n#include \"utilstrencodings.h\"\n#include \"tinyformat.h\"\n\nstatic const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };\nstatic const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};\n\nbool fAllowPrivateNet = DEFAULT_ALLOWPRIVATENET;\n\nvoid CNetAddr::Init()\n{\n    memset(ip, 0, sizeof(ip));\n    scopeId = 0;\n}\n\nvoid CNetAddr::SetIP(const CNetAddr& ipIn)\n{\n    memcpy(ip, ipIn.ip, sizeof(ip));\n}\n\nvoid CNetAddr::SetRaw(Network network, const uint8_t *ip_in)\n{\n    switch(network)\n    {\n        case NET_IPV4:\n            memcpy(ip, pchIPv4, 12);\n            memcpy(ip+12, ip_in, 4);\n            break;\n        case NET_IPV6:\n            memcpy(ip, ip_in, 16);\n            break;\n        default:\n            assert(!\"invalid network\");\n    }\n}\n\nbool CNetAddr::SetSpecial(const std::string &strName)\n{\n    if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == \".onion\") {\n        std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());\n        if (vchAddr.size() != 16-sizeof(pchOnionCat))\n            return false;\n        memcpy(ip, pchOnionCat, sizeof(pchOnionCat));\n        for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)\n            ip[i + sizeof(pchOnionCat)] = vchAddr[i];\n        return true;\n    }\n    return false;\n}\n\nCNetAddr::CNetAddr()\n{\n    Init();\n}\n\nCNetAddr::CNetAddr(const struct in_addr& ipv4Addr)\n{\n    SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);\n}\n\nCNetAddr::CNetAddr(const struct in6_addr& ipv6Addr, const uint32_t scope)\n{\n    SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);\n    scopeId = scope;\n}\n\nunsigned int CNetAddr::GetByte(int n) const\n{\n    return ip[15-n];\n}\n\nbool CNetAddr::IsIPv4() const\n{\n    return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);\n}\n\nbool CNetAddr::IsIPv6() const\n{\n    return (!IsIPv4() && !IsTor());\n}\n\nbool CNetAddr::IsRFC1918() const\n{\n    return IsIPv4() && (\n        GetByte(3) == 10 ||\n        (GetByte(3) == 192 && GetByte(2) == 168) ||\n        (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));\n}\n\nbool CNetAddr::IsRFC2544() const\n{\n    return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);\n}\n\nbool CNetAddr::IsRFC3927() const\n{\n    return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);\n}\n\nbool CNetAddr::IsRFC6598() const\n{\n    return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;\n}\n\nbool CNetAddr::IsRFC5737() const\n{\n    return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) ||\n        (GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) ||\n        (GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113));\n}\n\nbool CNetAddr::IsRFC3849() const\n{\n    return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;\n}\n\nbool CNetAddr::IsRFC3964() const\n{\n    return (GetByte(15) == 0x20 && GetByte(14) == 0x02);\n}\n\nbool CNetAddr::IsRFC6052() const\n{\n    static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};\n    return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);\n}\n\nbool CNetAddr::IsRFC4380() const\n{\n    return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);\n}\n\nbool CNetAddr::IsRFC4862() const\n{\n    static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};\n    return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);\n}\n\nbool CNetAddr::IsRFC4193() const\n{\n    return ((GetByte(15) & 0xFE) == 0xFC);\n}\n\nbool CNetAddr::IsRFC6145() const\n{\n    static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};\n    return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);\n}\n\nbool CNetAddr::IsRFC4843() const\n{\n    return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);\n}\n\nbool CNetAddr::IsTor() const\n{\n    return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);\n}\n\nbool CNetAddr::IsLocal() const\n{\n    \/\/ IPv4 loopback\n   if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))\n       return true;\n\n   \/\/ IPv6 loopback (::1\/128)\n   static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};\n   if (memcmp(ip, pchLocal, 16) == 0)\n       return true;\n\n   return false;\n}\n\nbool CNetAddr::IsMulticast() const\n{\n    return    (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)\n           || (GetByte(15) == 0xFF);\n}\n\nbool CNetAddr::IsValid() const\n{\n    \/\/ Cleanup 3-byte shifted addresses caused by garbage in size field\n    \/\/ of addr messages from versions before 0.2.9 checksum.\n    \/\/ Two consecutive addr messages look like this:\n    \/\/ header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...\n    \/\/ so if the first length field is garbled, it reads the second batch\n    \/\/ of addr misaligned by 3 bytes.\n    if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)\n        return false;\n\n    \/\/ unspecified IPv6 address (::\/128)\n    unsigned char ipNone6[16] = {};\n    if (memcmp(ip, ipNone6, 16) == 0)\n        return false;\n\n    \/\/ documentation IPv6 address\n    if (IsRFC3849())\n        return false;\n\n    if (IsIPv4())\n    {\n        \/\/ INADDR_NONE\n        uint32_t ipNone = INADDR_NONE;\n        if (memcmp(ip+12, &ipNone, 4) == 0)\n            return false;\n\n        \/\/ 0\n        ipNone = 0;\n        if (memcmp(ip+12, &ipNone, 4) == 0)\n            return false;\n    }\n\n    return true;\n}\n\nbool CNetAddr::IsRoutable() const\n{\n    if (!IsValid())\n        return false;\n    if (!fAllowPrivateNet && IsRFC1918())\n        return false;\n    return !(IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());\n}\n\nenum Network CNetAddr::GetNetwork() const\n{\n    if (!IsRoutable())\n        return NET_UNROUTABLE;\n\n    if (IsIPv4())\n        return NET_IPV4;\n\n    if (IsTor())\n        return NET_TOR;\n\n    return NET_IPV6;\n}\n\nstd::string CNetAddr::ToStringIP(bool fUseGetnameinfo) const\n{\n    if (IsTor())\n        return EncodeBase32(&ip[6], 10) + \".onion\";\n    if (fUseGetnameinfo)\n    {\n        CService serv(*this, 0);\n        struct sockaddr_storage sockaddr;\n        socklen_t socklen = sizeof(sockaddr);\n        if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {\n            char name[1025] = \"\";\n            if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))\n                return std::string(name);\n        }\n    }\n    if (IsIPv4())\n        return strprintf(\"%u.%u.%u.%u\", GetByte(3), GetByte(2), GetByte(1), GetByte(0));\n    else\n        return strprintf(\"%x:%x:%x:%x:%x:%x:%x:%x\",\n                         GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),\n                         GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),\n                         GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),\n                         GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));\n}\n\nstd::string CNetAddr::ToString() const\n{\n    return ToStringIP();\n}\n\nbool operator==(const CNetAddr& a, const CNetAddr& b)\n{\n    return (memcmp(a.ip, b.ip, 16) == 0);\n}\n\nbool operator!=(const CNetAddr& a, const CNetAddr& b)\n{\n    return (memcmp(a.ip, b.ip, 16) != 0);\n}\n\nbool operator<(const CNetAddr& a, const CNetAddr& b)\n{\n    return (memcmp(a.ip, b.ip, 16) < 0);\n}\n\nbool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const\n{\n    if (!IsIPv4())\n        return false;\n    memcpy(pipv4Addr, ip+12, 4);\n    return true;\n}\n\nbool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const\n{\n    memcpy(pipv6Addr, ip, 16);\n    return true;\n}\n\n\/\/ get canonical identifier of an address' group\n\/\/ no two connections will be attempted to addresses with the same group\nstd::vector<unsigned char> CNetAddr::GetGroup() const\n{\n    std::vector<unsigned char> vchRet;\n    int nClass = NET_IPV6;\n    int nStartByte = 0;\n    int nBits = 16;\n\n    \/\/ all local addresses belong to the same group\n    if (IsLocal())\n    {\n        nClass = 255;\n        nBits = 0;\n    }\n\n    \/\/ all unroutable addresses belong to the same group\n    if (!IsRoutable())\n    {\n        nClass = NET_UNROUTABLE;\n        nBits = 0;\n    }\n    \/\/ for IPv4 addresses, '1' + the 16 higher-order bits of the IP\n    \/\/ includes mapped IPv4, SIIT translated IPv4, and the well-known prefix\n    else if (IsIPv4() || IsRFC6145() || IsRFC6052())\n    {\n        nClass = NET_IPV4;\n        nStartByte = 12;\n    }\n    \/\/ for 6to4 tunnelled addresses, use the encapsulated IPv4 address\n    else if (IsRFC3964())\n    {\n        nClass = NET_IPV4;\n        nStartByte = 2;\n    }\n    \/\/ for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address\n    else if (IsRFC4380())\n    {\n        vchRet.push_back(NET_IPV4);\n        vchRet.push_back(GetByte(3) ^ 0xFF);\n        vchRet.push_back(GetByte(2) ^ 0xFF);\n        return vchRet;\n    }\n    else if (IsTor())\n    {\n        nClass = NET_TOR;\n        nStartByte = 6;\n        nBits = 4;\n    }\n    \/\/ for he.net, use \/36 groups\n    else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)\n        nBits = 36;\n    \/\/ for the rest of the IPv6 network, use \/32 groups\n    else\n        nBits = 32;\n\n    vchRet.push_back(nClass);\n    while (nBits >= 8)\n    {\n        vchRet.push_back(GetByte(15 - nStartByte));\n        nStartByte++;\n        nBits -= 8;\n    }\n    if (nBits > 0)\n        vchRet.push_back(GetByte(15 - nStartByte) | ((1 << (8 - nBits)) - 1));\n\n    return vchRet;\n}\n\nuint64_t CNetAddr::GetHash() const\n{\n    uint256 hash = Hash(&ip[0], &ip[16]);\n    uint64_t nRet;\n    memcpy(&nRet, &hash, sizeof(nRet));\n    return nRet;\n}\n\n\/\/ private extensions to enum Network, only returned by GetExtNetwork,\n\/\/ and only used in GetReachabilityFrom\nstatic const int NET_UNKNOWN = NET_MAX + 0;\nstatic const int NET_TEREDO  = NET_MAX + 1;\nint static GetExtNetwork(const CNetAddr *addr)\n{\n    if (addr == NULL)\n        return NET_UNKNOWN;\n    if (addr->IsRFC4380())\n        return NET_TEREDO;\n    return addr->GetNetwork();\n}\n\n\/** Calculates a metric for how reachable (*this) is from a given partner *\/\nint CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const\n{\n    enum Reachability {\n        REACH_UNREACHABLE,\n        REACH_DEFAULT,\n        REACH_TEREDO,\n        REACH_IPV6_WEAK,\n        REACH_IPV4,\n        REACH_IPV6_STRONG,\n        REACH_PRIVATE\n    };\n\n    if (!IsRoutable())\n        return REACH_UNREACHABLE;\n\n    int ourNet = GetExtNetwork(this);\n    int theirNet = GetExtNetwork(paddrPartner);\n    bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();\n\n    switch(theirNet) {\n    case NET_IPV4:\n        switch(ourNet) {\n        default:       return REACH_DEFAULT;\n        case NET_IPV4: return REACH_IPV4;\n        }\n    case NET_IPV6:\n        switch(ourNet) {\n        default:         return REACH_DEFAULT;\n        case NET_TEREDO: return REACH_TEREDO;\n        case NET_IPV4:   return REACH_IPV4;\n        case NET_IPV6:   return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; \/\/ only prefer giving our IPv6 address if it's not tunnelled\n        }\n    case NET_TOR:\n        switch(ourNet) {\n        default:         return REACH_DEFAULT;\n        case NET_IPV4:   return REACH_IPV4; \/\/ Tor users can connect to IPv4 as well\n        case NET_TOR:    return REACH_PRIVATE;\n        }\n    case NET_TEREDO:\n        switch(ourNet) {\n        default:          return REACH_DEFAULT;\n        case NET_TEREDO:  return REACH_TEREDO;\n        case NET_IPV6:    return REACH_IPV6_WEAK;\n        case NET_IPV4:    return REACH_IPV4;\n        }\n    case NET_UNKNOWN:\n    case NET_UNROUTABLE:\n    default:\n        switch(ourNet) {\n        default:          return REACH_DEFAULT;\n        case NET_TEREDO:  return REACH_TEREDO;\n        case NET_IPV6:    return REACH_IPV6_WEAK;\n        case NET_IPV4:    return REACH_IPV4;\n        case NET_TOR:     return REACH_PRIVATE; \/\/ either from Tor, or don't care about our address\n        }\n    }\n}\n\nvoid CService::Init()\n{\n    port = 0;\n}\n\nCService::CService()\n{\n    Init();\n}\n\nCService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)\n{\n}\n\nCService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)\n{\n}\n\nCService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)\n{\n}\n\nCService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))\n{\n    assert(addr.sin_family == AF_INET);\n}\n\nCService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr, addr.sin6_scope_id), port(ntohs(addr.sin6_port))\n{\n   assert(addr.sin6_family == AF_INET6);\n}\n\nbool CService::SetSockAddr(const struct sockaddr *paddr)\n{\n    switch (paddr->sa_family) {\n    case AF_INET:\n        *this = CService(*(const struct sockaddr_in*)paddr);\n        return true;\n    case AF_INET6:\n        *this = CService(*(const struct sockaddr_in6*)paddr);\n        return true;\n    default:\n        return false;\n    }\n}\n\nunsigned short CService::GetPort() const\n{\n    return port;\n}\n\nbool operator==(const CService& a, const CService& b)\n{\n    return (CNetAddr)a == (CNetAddr)b && a.port == b.port;\n}\n\nbool operator!=(const CService& a, const CService& b)\n{\n    return (CNetAddr)a != (CNetAddr)b || a.port != b.port;\n}\n\nbool operator<(const CService& a, const CService& b)\n{\n    return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);\n}\n\nbool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const\n{\n    if (IsIPv4()) {\n        if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))\n            return false;\n        *addrlen = sizeof(struct sockaddr_in);\n        struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;\n        memset(paddrin, 0, *addrlen);\n        if (!GetInAddr(&paddrin->sin_addr))\n            return false;\n        paddrin->sin_family = AF_INET;\n        paddrin->sin_port = htons(port);\n        return true;\n    }\n    if (IsIPv6()) {\n        if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))\n            return false;\n        *addrlen = sizeof(struct sockaddr_in6);\n        struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;\n        memset(paddrin6, 0, *addrlen);\n        if (!GetIn6Addr(&paddrin6->sin6_addr))\n            return false;\n        paddrin6->sin6_scope_id = scopeId;\n        paddrin6->sin6_family = AF_INET6;\n        paddrin6->sin6_port = htons(port);\n        return true;\n    }\n    return false;\n}\n\nstd::vector<unsigned char> CService::GetKey() const\n{\n     std::vector<unsigned char> vKey;\n     vKey.resize(18);\n     memcpy(&vKey[0], ip, 16);\n     vKey[16] = port \/ 0x100;\n     vKey[17] = port & 0x0FF;\n     return vKey;\n}\n\nstd::string CService::ToStringPort() const\n{\n    return strprintf(\"%u\", port);\n}\n\nstd::string CService::ToStringIPPort(bool fUseGetnameinfo) const\n{\n    if (IsIPv4() || IsTor()) {\n        return ToStringIP(fUseGetnameinfo) + \":\" + ToStringPort();\n    } else {\n        return \"[\" + ToStringIP(fUseGetnameinfo) + \"]:\" + ToStringPort();\n    }\n}\n\nstd::string CService::ToString(bool fUseGetnameinfo) const\n{\n    return ToStringIPPort(fUseGetnameinfo);\n}\n\nvoid CService::SetPort(unsigned short portIn)\n{\n    port = portIn;\n}\n\nCSubNet::CSubNet():\n    valid(false)\n{\n    memset(netmask, 0, sizeof(netmask));\n}\n\nCSubNet::CSubNet(const CNetAddr &addr, int32_t mask)\n{\n    valid = true;\n    network = addr;\n    \/\/ Default to \/32 (IPv4) or \/128 (IPv6), i.e. match single address\n    memset(netmask, 255, sizeof(netmask));\n\n    \/\/ IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n\n    const int astartofs = network.IsIPv4() ? 12 : 0;\n\n    int32_t n = mask;\n    if(n >= 0 && n <= (128 - astartofs*8)) \/\/ Only valid if in range of bits of address\n    {\n        n += astartofs*8;\n        \/\/ Clear bits [n..127]\n        for (; n < 128; ++n)\n            netmask[n>>3] &= ~(1<<(7-(n&7)));\n    } else\n        valid = false;\n\n    \/\/ Normalize network according to netmask\n    for(int x=0; x<16; ++x)\n        network.ip[x] &= netmask[x];\n}\n\nCSubNet::CSubNet(const CNetAddr &addr, const CNetAddr &mask)\n{\n    valid = true;\n    network = addr;\n    \/\/ Default to \/32 (IPv4) or \/128 (IPv6), i.e. match single address\n    memset(netmask, 255, sizeof(netmask));\n\n    \/\/ IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n\n    const int astartofs = network.IsIPv4() ? 12 : 0;\n\n    for(int x=astartofs; x<16; ++x)\n        netmask[x] = mask.ip[x];\n\n    \/\/ Normalize network according to netmask\n    for(int x=0; x<16; ++x)\n        network.ip[x] &= netmask[x];\n}\n\nCSubNet::CSubNet(const CNetAddr &addr):\n    valid(addr.IsValid())\n{\n    memset(netmask, 255, sizeof(netmask));\n    network = addr;\n}\n\nbool CSubNet::Match(const CNetAddr &addr) const\n{\n    if (!valid || !addr.IsValid())\n        return false;\n    for(int x=0; x<16; ++x)\n        if ((addr.ip[x] & netmask[x]) != network.ip[x])\n            return false;\n    return true;\n}\n\nstatic inline int NetmaskBits(uint8_t x)\n{\n    switch(x) {\n    case 0x00: return 0; break;\n    case 0x80: return 1; break;\n    case 0xc0: return 2; break;\n    case 0xe0: return 3; break;\n    case 0xf0: return 4; break;\n    case 0xf8: return 5; break;\n    case 0xfc: return 6; break;\n    case 0xfe: return 7; break;\n    case 0xff: return 8; break;\n    default: return -1; break;\n    }\n}\n\nstd::string CSubNet::ToString() const\n{\n    \/* Parse binary 1{n}0{N-n} to see if mask can be represented as \/n *\/\n    int cidr = 0;\n    bool valid_cidr = true;\n    int n = network.IsIPv4() ? 12 : 0;\n    for (; n < 16 && netmask[n] == 0xff; ++n)\n        cidr += 8;\n    if (n < 16) {\n        int bits = NetmaskBits(netmask[n]);\n        if (bits < 0)\n            valid_cidr = false;\n        else\n            cidr += bits;\n        ++n;\n    }\n    for (; n < 16 && valid_cidr; ++n)\n        if (netmask[n] != 0x00)\n            valid_cidr = false;\n\n    \/* Format output *\/\n    std::string strNetmask;\n    if (valid_cidr) {\n        strNetmask = strprintf(\"%u\", cidr);\n    } else {\n        if (network.IsIPv4())\n            strNetmask = strprintf(\"%u.%u.%u.%u\", netmask[12], netmask[13], netmask[14], netmask[15]);\n        else\n            strNetmask = strprintf(\"%x:%x:%x:%x:%x:%x:%x:%x\",\n                             netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3],\n                             netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7],\n                             netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11],\n                             netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]);\n    }\n\n    return network.ToString() + \"\/\" + strNetmask;\n}\n\nbool CSubNet::IsValid() const\n{\n    return valid;\n}\n\nbool operator==(const CSubNet& a, const CSubNet& b)\n{\n    return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);\n}\n\nbool operator!=(const CSubNet& a, const CSubNet& b)\n{\n    return !(a==b);\n}\n\nbool operator<(const CSubNet& a, const CSubNet& b)\n{\n    return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0));\n}\n","avg_line_length":26.7524071527,"max_line_length":143,"alphanum_fraction":0.5976656898,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":33555,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"include\/core\/SkMatrix44.h\"\n#include <type_traits>\n#include <utility>\n\n\/\/ Copying SkMatrix44 byte-wise is performance-critical to Blink. This class is\n\/\/ contained in several Transform classes, which are copied multiple times\n\/\/ during the rendering life cycle. See crbug.com\/938563 for reference.\n#if defined(SK_BUILD_FOR_WIN) || defined(SK_BUILD_FOR_MAC)\n\/\/ std::is_trivially_copyable is not supported for some older clang versions,\n\/\/ which (at least as of this patch) are in use for Chromecast.\nstatic_assert(std::is_trivially_copyable<SkMatrix44>::value,\n              \"SkMatrix44 must be trivially copyable\");\n#endif\n\nstatic inline bool eq4(const SkMScalar* SK_RESTRICT a,\n                      const SkMScalar* SK_RESTRICT b) {\n    return (a[0] == b[0]) & (a[1] == b[1]) & (a[2] == b[2]) & (a[3] == b[3]);\n}\n\nbool SkMatrix44::operator==(const SkMatrix44& other) const {\n    if (this == &other) {\n        return true;\n    }\n\n    if (this->isIdentity() && other.isIdentity()) {\n        return true;\n    }\n\n    const SkMScalar* SK_RESTRICT a = &fMat[0][0];\n    const SkMScalar* SK_RESTRICT b = &other.fMat[0][0];\n\n#if 0\n    for (int i = 0; i < 16; ++i) {\n        if (a[i] != b[i]) {\n            return false;\n        }\n    }\n    return true;\n#else\n    \/\/ to reduce branch instructions, we compare 4 at a time.\n    \/\/ see bench\/Matrix44Bench.cpp for test.\n    if (!eq4(&a[0], &b[0])) {\n        return false;\n    }\n    if (!eq4(&a[4], &b[4])) {\n        return false;\n    }\n    if (!eq4(&a[8], &b[8])) {\n        return false;\n    }\n    return eq4(&a[12], &b[12]);\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SkMatrix44::recomputeTypeMask() {\n    if (0 != perspX() || 0 != perspY() || 0 != perspZ() || 1 != fMat[3][3]) {\n        fTypeMask = kTranslate_Mask | kScale_Mask | kAffine_Mask | kPerspective_Mask;\n        return;\n    }\n\n    TypeMask mask = kIdentity_Mask;\n    if (0 != transX() || 0 != transY() || 0 != transZ()) {\n        mask |= kTranslate_Mask;\n    }\n\n    if (1 != scaleX() || 1 != scaleY() || 1 != scaleZ()) {\n        mask |= kScale_Mask;\n    }\n\n    if (0 != fMat[1][0] || 0 != fMat[0][1] || 0 != fMat[0][2] ||\n        0 != fMat[2][0] || 0 != fMat[1][2] || 0 != fMat[2][1]) {\n            mask |= kAffine_Mask;\n    }\n    fTypeMask = mask;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkMatrix44::asColMajorf(float dst[]) const {\n    const SkMScalar* src = &fMat[0][0];\n#ifdef SK_MSCALAR_IS_DOUBLE\n    for (int i = 0; i < 16; ++i) {\n        dst[i] = SkMScalarToFloat(src[i]);\n    }\n#elif defined SK_MSCALAR_IS_FLOAT\n    memcpy(dst, src, 16 * sizeof(float));\n#endif\n}\n\nvoid SkMatrix44::as3x4RowMajorf(float dst[]) const {\n    dst[0] = fMat[0][0]; dst[1] = fMat[1][0]; dst[2]  = fMat[2][0]; dst[3]  = fMat[3][0];\n    dst[4] = fMat[0][1]; dst[5] = fMat[1][1]; dst[6]  = fMat[2][1]; dst[7]  = fMat[3][1];\n    dst[8] = fMat[0][2]; dst[9] = fMat[1][2]; dst[10] = fMat[2][2]; dst[11] = fMat[3][2];\n}\n\nvoid SkMatrix44::asColMajord(double dst[]) const {\n    const SkMScalar* src = &fMat[0][0];\n#ifdef SK_MSCALAR_IS_DOUBLE\n    memcpy(dst, src, 16 * sizeof(double));\n#elif defined SK_MSCALAR_IS_FLOAT\n    for (int i = 0; i < 16; ++i) {\n        dst[i] = SkMScalarToDouble(src[i]);\n    }\n#endif\n}\n\nvoid SkMatrix44::asRowMajorf(float dst[]) const {\n    const SkMScalar* src = &fMat[0][0];\n    for (int i = 0; i < 4; ++i) {\n        dst[0] = SkMScalarToFloat(src[0]);\n        dst[4] = SkMScalarToFloat(src[1]);\n        dst[8] = SkMScalarToFloat(src[2]);\n        dst[12] = SkMScalarToFloat(src[3]);\n        src += 4;\n        dst += 1;\n    }\n}\n\nvoid SkMatrix44::asRowMajord(double dst[]) const {\n    const SkMScalar* src = &fMat[0][0];\n    for (int i = 0; i < 4; ++i) {\n        dst[0] = SkMScalarToDouble(src[0]);\n        dst[4] = SkMScalarToDouble(src[1]);\n        dst[8] = SkMScalarToDouble(src[2]);\n        dst[12] = SkMScalarToDouble(src[3]);\n        src += 4;\n        dst += 1;\n    }\n}\n\nvoid SkMatrix44::setColMajorf(const float src[]) {\n    SkMScalar* dst = &fMat[0][0];\n#ifdef SK_MSCALAR_IS_DOUBLE\n    for (int i = 0; i < 16; ++i) {\n        dst[i] = SkMScalarToFloat(src[i]);\n    }\n#elif defined SK_MSCALAR_IS_FLOAT\n    memcpy(dst, src, 16 * sizeof(float));\n#endif\n\n    this->recomputeTypeMask();\n}\n\nvoid SkMatrix44::setColMajord(const double src[]) {\n    SkMScalar* dst = &fMat[0][0];\n#ifdef SK_MSCALAR_IS_DOUBLE\n    memcpy(dst, src, 16 * sizeof(double));\n#elif defined SK_MSCALAR_IS_FLOAT\n    for (int i = 0; i < 16; ++i) {\n        dst[i] = SkDoubleToMScalar(src[i]);\n    }\n#endif\n\n    this->recomputeTypeMask();\n}\n\nvoid SkMatrix44::setRowMajorf(const float src[]) {\n    SkMScalar* dst = &fMat[0][0];\n    for (int i = 0; i < 4; ++i) {\n        dst[0] = SkMScalarToFloat(src[0]);\n        dst[4] = SkMScalarToFloat(src[1]);\n        dst[8] = SkMScalarToFloat(src[2]);\n        dst[12] = SkMScalarToFloat(src[3]);\n        src += 4;\n        dst += 1;\n    }\n    this->recomputeTypeMask();\n}\n\nvoid SkMatrix44::setRowMajord(const double src[]) {\n    SkMScalar* dst = &fMat[0][0];\n    for (int i = 0; i < 4; ++i) {\n        dst[0] = SkDoubleToMScalar(src[0]);\n        dst[4] = SkDoubleToMScalar(src[1]);\n        dst[8] = SkDoubleToMScalar(src[2]);\n        dst[12] = SkDoubleToMScalar(src[3]);\n        src += 4;\n        dst += 1;\n    }\n    this->recomputeTypeMask();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst SkMatrix44& SkMatrix44::I() {\n    static constexpr SkMatrix44 gIdentity44(kIdentity_Constructor);\n    return gIdentity44;\n}\n\nvoid SkMatrix44::setIdentity() {\n    fMat[0][0] = 1;\n    fMat[0][1] = 0;\n    fMat[0][2] = 0;\n    fMat[0][3] = 0;\n    fMat[1][0] = 0;\n    fMat[1][1] = 1;\n    fMat[1][2] = 0;\n    fMat[1][3] = 0;\n    fMat[2][0] = 0;\n    fMat[2][1] = 0;\n    fMat[2][2] = 1;\n    fMat[2][3] = 0;\n    fMat[3][0] = 0;\n    fMat[3][1] = 0;\n    fMat[3][2] = 0;\n    fMat[3][3] = 1;\n    this->setTypeMask(kIdentity_Mask);\n}\n\nvoid SkMatrix44::set3x3(SkMScalar m_00, SkMScalar m_10, SkMScalar m_20,\n                        SkMScalar m_01, SkMScalar m_11, SkMScalar m_21,\n                        SkMScalar m_02, SkMScalar m_12, SkMScalar m_22) {\n    fMat[0][0] = m_00; fMat[0][1] = m_10; fMat[0][2] = m_20; fMat[0][3] = 0;\n    fMat[1][0] = m_01; fMat[1][1] = m_11; fMat[1][2] = m_21; fMat[1][3] = 0;\n    fMat[2][0] = m_02; fMat[2][1] = m_12; fMat[2][2] = m_22; fMat[2][3] = 0;\n    fMat[3][0] = 0;    fMat[3][1] = 0;    fMat[3][2] = 0;    fMat[3][3] = 1;\n    this->recomputeTypeMask();\n}\n\nvoid SkMatrix44::set3x3RowMajorf(const float src[]) {\n    fMat[0][0] = src[0]; fMat[0][1] = src[3]; fMat[0][2] = src[6]; fMat[0][3] = 0;\n    fMat[1][0] = src[1]; fMat[1][1] = src[4]; fMat[1][2] = src[7]; fMat[1][3] = 0;\n    fMat[2][0] = src[2]; fMat[2][1] = src[5]; fMat[2][2] = src[8]; fMat[2][3] = 0;\n    fMat[3][0] = 0;      fMat[3][1] = 0;      fMat[3][2] = 0;      fMat[3][3] = 1;\n    this->recomputeTypeMask();\n}\n\nvoid SkMatrix44::set3x4RowMajorf(const float src[]) {\n    fMat[0][0] = src[0]; fMat[1][0] = src[1]; fMat[2][0] = src[2];  fMat[3][0] = src[3];\n    fMat[0][1] = src[4]; fMat[1][1] = src[5]; fMat[2][1] = src[6];  fMat[3][1] = src[7];\n    fMat[0][2] = src[8]; fMat[1][2] = src[9]; fMat[2][2] = src[10]; fMat[3][2] = src[11];\n    fMat[0][3] = 0;      fMat[1][3] = 0;      fMat[2][3] = 0;       fMat[3][3] = 1;\n    this->recomputeTypeMask();\n}\n\nvoid SkMatrix44::set4x4(SkMScalar m_00, SkMScalar m_10, SkMScalar m_20, SkMScalar m_30,\n                SkMScalar m_01, SkMScalar m_11, SkMScalar m_21, SkMScalar m_31,\n                SkMScalar m_02, SkMScalar m_12, SkMScalar m_22, SkMScalar m_32,\n                SkMScalar m_03, SkMScalar m_13, SkMScalar m_23, SkMScalar m_33) {\n    fMat[0][0] = m_00; fMat[0][1] = m_10; fMat[0][2] = m_20; fMat[0][3] = m_30;\n    fMat[1][0] = m_01; fMat[1][1] = m_11; fMat[1][2] = m_21; fMat[1][3] = m_31;\n    fMat[2][0] = m_02; fMat[2][1] = m_12; fMat[2][2] = m_22; fMat[2][3] = m_32;\n    fMat[3][0] = m_03; fMat[3][1] = m_13; fMat[3][2] = m_23; fMat[3][3] = m_33;\n    this->recomputeTypeMask();\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkMatrix44& SkMatrix44::setTranslate(SkMScalar dx, SkMScalar dy, SkMScalar dz) {\n    this->setIdentity();\n\n    if (!dx && !dy && !dz) {\n        return *this;\n    }\n\n    fMat[3][0] = dx;\n    fMat[3][1] = dy;\n    fMat[3][2] = dz;\n    this->setTypeMask(kTranslate_Mask);\n    return *this;\n}\n\nSkMatrix44& SkMatrix44::preTranslate(SkMScalar dx, SkMScalar dy, SkMScalar dz) {\n    if (!dx && !dy && !dz) {\n        return *this;\n    }\n\n    for (int i = 0; i < 4; ++i) {\n        fMat[3][i] = fMat[0][i] * dx + fMat[1][i] * dy + fMat[2][i] * dz + fMat[3][i];\n    }\n    this->recomputeTypeMask();\n    return *this;\n}\n\nSkMatrix44& SkMatrix44::postTranslate(SkMScalar dx, SkMScalar dy, SkMScalar dz) {\n    if (!dx && !dy && !dz) {\n        return *this;\n    }\n\n    if (this->getType() & kPerspective_Mask) {\n        for (int i = 0; i < 4; ++i) {\n            fMat[i][0] += fMat[i][3] * dx;\n            fMat[i][1] += fMat[i][3] * dy;\n            fMat[i][2] += fMat[i][3] * dz;\n        }\n    } else {\n        fMat[3][0] += dx;\n        fMat[3][1] += dy;\n        fMat[3][2] += dz;\n        this->recomputeTypeMask();\n    }\n    return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkMatrix44& SkMatrix44::setScale(SkMScalar sx, SkMScalar sy, SkMScalar sz) {\n    this->setIdentity();\n\n    if (1 == sx && 1 == sy && 1 == sz) {\n        return *this;\n    }\n\n    fMat[0][0] = sx;\n    fMat[1][1] = sy;\n    fMat[2][2] = sz;\n    this->setTypeMask(kScale_Mask);\n    return *this;\n}\n\nSkMatrix44& SkMatrix44::preScale(SkMScalar sx, SkMScalar sy, SkMScalar sz) {\n    if (1 == sx && 1 == sy && 1 == sz) {\n        return *this;\n    }\n\n    \/\/ The implementation matrix * pureScale can be shortcut\n    \/\/ by knowing that pureScale components effectively scale\n    \/\/ the columns of the original matrix.\n    for (int i = 0; i < 4; i++) {\n        fMat[0][i] *= sx;\n        fMat[1][i] *= sy;\n        fMat[2][i] *= sz;\n    }\n    this->recomputeTypeMask();\n    return *this;\n}\n\nSkMatrix44& SkMatrix44::postScale(SkMScalar sx, SkMScalar sy, SkMScalar sz) {\n    if (1 == sx && 1 == sy && 1 == sz) {\n        return *this;\n    }\n\n    for (int i = 0; i < 4; i++) {\n        fMat[i][0] *= sx;\n        fMat[i][1] *= sy;\n        fMat[i][2] *= sz;\n    }\n    this->recomputeTypeMask();\n    return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkMatrix44::setRotateAbout(SkMScalar x, SkMScalar y, SkMScalar z,\n                                SkMScalar radians) {\n    double len2 = (double)x * x + (double)y * y + (double)z * z;\n    if (1 != len2) {\n        if (0 == len2) {\n            this->setIdentity();\n            return;\n        }\n        double scale = 1 \/ sqrt(len2);\n        x = SkDoubleToMScalar(x * scale);\n        y = SkDoubleToMScalar(y * scale);\n        z = SkDoubleToMScalar(z * scale);\n    }\n    this->setRotateAboutUnit(x, y, z, radians);\n}\n\nvoid SkMatrix44::setRotateAboutUnit(SkMScalar x, SkMScalar y, SkMScalar z,\n                                    SkMScalar radians) {\n    double c = cos(radians);\n    double s = sin(radians);\n    double C = 1 - c;\n    double xs = x * s;\n    double ys = y * s;\n    double zs = z * s;\n    double xC = x * C;\n    double yC = y * C;\n    double zC = z * C;\n    double xyC = x * yC;\n    double yzC = y * zC;\n    double zxC = z * xC;\n\n    \/\/ if you're looking at wikipedia, remember that we're column major.\n    this->set3x3(SkDoubleToMScalar(x * xC + c),     \/\/ scale x\n                 SkDoubleToMScalar(xyC + zs),       \/\/ skew x\n                 SkDoubleToMScalar(zxC - ys),       \/\/ trans x\n\n                 SkDoubleToMScalar(xyC - zs),       \/\/ skew y\n                 SkDoubleToMScalar(y * yC + c),     \/\/ scale y\n                 SkDoubleToMScalar(yzC + xs),       \/\/ trans y\n\n                 SkDoubleToMScalar(zxC + ys),       \/\/ persp x\n                 SkDoubleToMScalar(yzC - xs),       \/\/ persp y\n                 SkDoubleToMScalar(z * zC + c));    \/\/ persp 2\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic bool bits_isonly(int value, int mask) {\n    return 0 == (value & ~mask);\n}\n\nvoid SkMatrix44::setConcat(const SkMatrix44& a, const SkMatrix44& b) {\n    const SkMatrix44::TypeMask a_mask = a.getType();\n    const SkMatrix44::TypeMask b_mask = b.getType();\n\n    if (kIdentity_Mask == a_mask) {\n        *this = b;\n        return;\n    }\n    if (kIdentity_Mask == b_mask) {\n        *this = a;\n        return;\n    }\n\n    bool useStorage = (this == &a || this == &b);\n    SkMScalar storage[16];\n    SkMScalar* result = useStorage ? storage : &fMat[0][0];\n\n    \/\/ Both matrices are at most scale+translate\n    if (bits_isonly(a_mask | b_mask, kScale_Mask | kTranslate_Mask)) {\n        result[0] = a.fMat[0][0] * b.fMat[0][0];\n        result[1] = result[2] = result[3] = result[4] = 0;\n        result[5] = a.fMat[1][1] * b.fMat[1][1];\n        result[6] = result[7] = result[8] = result[9] = 0;\n        result[10] = a.fMat[2][2] * b.fMat[2][2];\n        result[11] = 0;\n        result[12] = a.fMat[0][0] * b.fMat[3][0] + a.fMat[3][0];\n        result[13] = a.fMat[1][1] * b.fMat[3][1] + a.fMat[3][1];\n        result[14] = a.fMat[2][2] * b.fMat[3][2] + a.fMat[3][2];\n        result[15] = 1;\n    } else {\n        for (int j = 0; j < 4; j++) {\n            for (int i = 0; i < 4; i++) {\n                double value = 0;\n                for (int k = 0; k < 4; k++) {\n                    value += SkMScalarToDouble(a.fMat[k][i]) * b.fMat[j][k];\n                }\n                *result++ = SkDoubleToMScalar(value);\n            }\n        }\n    }\n\n    if (useStorage) {\n        memcpy(fMat, storage, sizeof(storage));\n    }\n    this->recomputeTypeMask();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/** We always perform the calculation in doubles, to avoid prematurely losing\n    precision along the way. This relies on the compiler automatically\n    promoting our SkMScalar values to double (if needed).\n *\/\ndouble SkMatrix44::determinant() const {\n    if (this->isIdentity()) {\n        return 1;\n    }\n    if (this->isScaleTranslate()) {\n        return fMat[0][0] * fMat[1][1] * fMat[2][2] * fMat[3][3];\n    }\n\n    double a00 = fMat[0][0];\n    double a01 = fMat[0][1];\n    double a02 = fMat[0][2];\n    double a03 = fMat[0][3];\n    double a10 = fMat[1][0];\n    double a11 = fMat[1][1];\n    double a12 = fMat[1][2];\n    double a13 = fMat[1][3];\n    double a20 = fMat[2][0];\n    double a21 = fMat[2][1];\n    double a22 = fMat[2][2];\n    double a23 = fMat[2][3];\n    double a30 = fMat[3][0];\n    double a31 = fMat[3][1];\n    double a32 = fMat[3][2];\n    double a33 = fMat[3][3];\n\n    double b00 = a00 * a11 - a01 * a10;\n    double b01 = a00 * a12 - a02 * a10;\n    double b02 = a00 * a13 - a03 * a10;\n    double b03 = a01 * a12 - a02 * a11;\n    double b04 = a01 * a13 - a03 * a11;\n    double b05 = a02 * a13 - a03 * a12;\n    double b06 = a20 * a31 - a21 * a30;\n    double b07 = a20 * a32 - a22 * a30;\n    double b08 = a20 * a33 - a23 * a30;\n    double b09 = a21 * a32 - a22 * a31;\n    double b10 = a21 * a33 - a23 * a31;\n    double b11 = a22 * a33 - a23 * a32;\n\n    \/\/ Calculate the determinant\n    return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic bool is_matrix_finite(const SkMatrix44& matrix) {\n    SkMScalar accumulator = 0;\n    for (int row = 0; row < 4; ++row) {\n        for (int col = 0; col < 4; ++col) {\n            accumulator *= matrix.get(row, col);\n        }\n    }\n    return accumulator == 0;\n}\n\nbool SkMatrix44::invert(SkMatrix44* storage) const {\n    if (this->isIdentity()) {\n        if (storage) {\n            storage->setIdentity();\n        }\n        return true;\n    }\n\n    if (this->isTranslate()) {\n        if (storage) {\n            storage->setTranslate(-fMat[3][0], -fMat[3][1], -fMat[3][2]);\n        }\n        return true;\n    }\n\n    SkMatrix44 tmp;\n    \/\/ Use storage if it's available and distinct from this matrix.\n    SkMatrix44* inverse = (storage && storage != this) ? storage : &tmp;\n    if (this->isScaleTranslate()) {\n        if (0 == fMat[0][0] * fMat[1][1] * fMat[2][2]) {\n            return false;\n        }\n\n        double invXScale = 1 \/ fMat[0][0];\n        double invYScale = 1 \/ fMat[1][1];\n        double invZScale = 1 \/ fMat[2][2];\n\n        inverse->fMat[0][0] = SkDoubleToMScalar(invXScale);\n        inverse->fMat[0][1] = 0;\n        inverse->fMat[0][2] = 0;\n        inverse->fMat[0][3] = 0;\n\n        inverse->fMat[1][0] = 0;\n        inverse->fMat[1][1] = SkDoubleToMScalar(invYScale);\n        inverse->fMat[1][2] = 0;\n        inverse->fMat[1][3] = 0;\n\n        inverse->fMat[2][0] = 0;\n        inverse->fMat[2][1] = 0;\n        inverse->fMat[2][2] = SkDoubleToMScalar(invZScale);\n        inverse->fMat[2][3] = 0;\n\n        inverse->fMat[3][0] = SkDoubleToMScalar(-fMat[3][0] * invXScale);\n        inverse->fMat[3][1] = SkDoubleToMScalar(-fMat[3][1] * invYScale);\n        inverse->fMat[3][2] = SkDoubleToMScalar(-fMat[3][2] * invZScale);\n        inverse->fMat[3][3] = 1;\n\n        inverse->setTypeMask(this->getType());\n\n        if (!is_matrix_finite(*inverse)) {\n            return false;\n        }\n        if (storage && inverse != storage) {\n            *storage = *inverse;\n        }\n        return true;\n    }\n\n    double a00 = fMat[0][0];\n    double a01 = fMat[0][1];\n    double a02 = fMat[0][2];\n    double a03 = fMat[0][3];\n    double a10 = fMat[1][0];\n    double a11 = fMat[1][1];\n    double a12 = fMat[1][2];\n    double a13 = fMat[1][3];\n    double a20 = fMat[2][0];\n    double a21 = fMat[2][1];\n    double a22 = fMat[2][2];\n    double a23 = fMat[2][3];\n    double a30 = fMat[3][0];\n    double a31 = fMat[3][1];\n    double a32 = fMat[3][2];\n    double a33 = fMat[3][3];\n\n    if (!(this->getType() & kPerspective_Mask)) {\n        \/\/ If we know the matrix has no perspective, then the perspective\n        \/\/ component is (0, 0, 0, 1). We can use this information to save a lot\n        \/\/ of arithmetic that would otherwise be spent to compute the inverse\n        \/\/ of a general matrix.\n\n        SkASSERT(a03 == 0);\n        SkASSERT(a13 == 0);\n        SkASSERT(a23 == 0);\n        SkASSERT(a33 == 1);\n\n        double b00 = a00 * a11 - a01 * a10;\n        double b01 = a00 * a12 - a02 * a10;\n        double b03 = a01 * a12 - a02 * a11;\n        double b06 = a20 * a31 - a21 * a30;\n        double b07 = a20 * a32 - a22 * a30;\n        double b08 = a20;\n        double b09 = a21 * a32 - a22 * a31;\n        double b10 = a21;\n        double b11 = a22;\n\n        \/\/ Calculate the determinant\n        double det = b00 * b11 - b01 * b10 + b03 * b08;\n\n        double invdet = sk_ieee_double_divide(1.0, det);\n        \/\/ If det is zero, we want to return false. However, we also want to return false\n        \/\/ if 1\/det overflows to infinity (i.e. det is denormalized). Both of these are\n        \/\/ handled by checking that 1\/det is finite.\n        if (!sk_float_isfinite(sk_double_to_float(invdet))) {\n            return false;\n        }\n\n        b00 *= invdet;\n        b01 *= invdet;\n        b03 *= invdet;\n        b06 *= invdet;\n        b07 *= invdet;\n        b08 *= invdet;\n        b09 *= invdet;\n        b10 *= invdet;\n        b11 *= invdet;\n\n        inverse->fMat[0][0] = SkDoubleToMScalar(a11 * b11 - a12 * b10);\n        inverse->fMat[0][1] = SkDoubleToMScalar(a02 * b10 - a01 * b11);\n        inverse->fMat[0][2] = SkDoubleToMScalar(b03);\n        inverse->fMat[0][3] = 0;\n        inverse->fMat[1][0] = SkDoubleToMScalar(a12 * b08 - a10 * b11);\n        inverse->fMat[1][1] = SkDoubleToMScalar(a00 * b11 - a02 * b08);\n        inverse->fMat[1][2] = SkDoubleToMScalar(-b01);\n        inverse->fMat[1][3] = 0;\n        inverse->fMat[2][0] = SkDoubleToMScalar(a10 * b10 - a11 * b08);\n        inverse->fMat[2][1] = SkDoubleToMScalar(a01 * b08 - a00 * b10);\n        inverse->fMat[2][2] = SkDoubleToMScalar(b00);\n        inverse->fMat[2][3] = 0;\n        inverse->fMat[3][0] = SkDoubleToMScalar(a11 * b07 - a10 * b09 - a12 * b06);\n        inverse->fMat[3][1] = SkDoubleToMScalar(a00 * b09 - a01 * b07 + a02 * b06);\n        inverse->fMat[3][2] = SkDoubleToMScalar(a31 * b01 - a30 * b03 - a32 * b00);\n        inverse->fMat[3][3] = 1;\n\n        inverse->setTypeMask(this->getType());\n        if (!is_matrix_finite(*inverse)) {\n            return false;\n        }\n        if (storage && inverse != storage) {\n            *storage = *inverse;\n        }\n        return true;\n    }\n\n    double b00 = a00 * a11 - a01 * a10;\n    double b01 = a00 * a12 - a02 * a10;\n    double b02 = a00 * a13 - a03 * a10;\n    double b03 = a01 * a12 - a02 * a11;\n    double b04 = a01 * a13 - a03 * a11;\n    double b05 = a02 * a13 - a03 * a12;\n    double b06 = a20 * a31 - a21 * a30;\n    double b07 = a20 * a32 - a22 * a30;\n    double b08 = a20 * a33 - a23 * a30;\n    double b09 = a21 * a32 - a22 * a31;\n    double b10 = a21 * a33 - a23 * a31;\n    double b11 = a22 * a33 - a23 * a32;\n\n    \/\/ Calculate the determinant\n    double det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n    double invdet = sk_ieee_double_divide(1.0, det);\n    \/\/ If det is zero, we want to return false. However, we also want to return false\n    \/\/ if 1\/det overflows to infinity (i.e. det is denormalized). Both of these are\n    \/\/ handled by checking that 1\/det is finite.\n    if (!sk_float_isfinite(sk_double_to_float(invdet))) {\n        return false;\n    }\n\n    b00 *= invdet;\n    b01 *= invdet;\n    b02 *= invdet;\n    b03 *= invdet;\n    b04 *= invdet;\n    b05 *= invdet;\n    b06 *= invdet;\n    b07 *= invdet;\n    b08 *= invdet;\n    b09 *= invdet;\n    b10 *= invdet;\n    b11 *= invdet;\n\n    inverse->fMat[0][0] = SkDoubleToMScalar(a11 * b11 - a12 * b10 + a13 * b09);\n    inverse->fMat[0][1] = SkDoubleToMScalar(a02 * b10 - a01 * b11 - a03 * b09);\n    inverse->fMat[0][2] = SkDoubleToMScalar(a31 * b05 - a32 * b04 + a33 * b03);\n    inverse->fMat[0][3] = SkDoubleToMScalar(a22 * b04 - a21 * b05 - a23 * b03);\n    inverse->fMat[1][0] = SkDoubleToMScalar(a12 * b08 - a10 * b11 - a13 * b07);\n    inverse->fMat[1][1] = SkDoubleToMScalar(a00 * b11 - a02 * b08 + a03 * b07);\n    inverse->fMat[1][2] = SkDoubleToMScalar(a32 * b02 - a30 * b05 - a33 * b01);\n    inverse->fMat[1][3] = SkDoubleToMScalar(a20 * b05 - a22 * b02 + a23 * b01);\n    inverse->fMat[2][0] = SkDoubleToMScalar(a10 * b10 - a11 * b08 + a13 * b06);\n    inverse->fMat[2][1] = SkDoubleToMScalar(a01 * b08 - a00 * b10 - a03 * b06);\n    inverse->fMat[2][2] = SkDoubleToMScalar(a30 * b04 - a31 * b02 + a33 * b00);\n    inverse->fMat[2][3] = SkDoubleToMScalar(a21 * b02 - a20 * b04 - a23 * b00);\n    inverse->fMat[3][0] = SkDoubleToMScalar(a11 * b07 - a10 * b09 - a12 * b06);\n    inverse->fMat[3][1] = SkDoubleToMScalar(a00 * b09 - a01 * b07 + a02 * b06);\n    inverse->fMat[3][2] = SkDoubleToMScalar(a31 * b01 - a30 * b03 - a32 * b00);\n    inverse->fMat[3][3] = SkDoubleToMScalar(a20 * b03 - a21 * b01 + a22 * b00);\n    inverse->setTypeMask(this->getType());\n    if (!is_matrix_finite(*inverse)) {\n        return false;\n    }\n    if (storage && inverse != storage) {\n        *storage = *inverse;\n    }\n    return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkMatrix44::transpose() {\n    if (!this->isIdentity()) {\n        using std::swap;\n        swap(fMat[0][1], fMat[1][0]);\n        swap(fMat[0][2], fMat[2][0]);\n        swap(fMat[0][3], fMat[3][0]);\n        swap(fMat[1][2], fMat[2][1]);\n        swap(fMat[1][3], fMat[3][1]);\n        swap(fMat[2][3], fMat[3][2]);\n        this->recomputeTypeMask();\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkMatrix44::mapScalars(const SkScalar src[4], SkScalar dst[4]) const {\n    SkScalar storage[4];\n    SkScalar* result = (src == dst) ? storage : dst;\n\n    for (int i = 0; i < 4; i++) {\n        SkMScalar value = 0;\n        for (int j = 0; j < 4; j++) {\n            value += fMat[j][i] * src[j];\n        }\n        result[i] = SkMScalarToScalar(value);\n    }\n\n    if (storage == result) {\n        memcpy(dst, storage, sizeof(storage));\n    }\n}\n\n#ifdef SK_MSCALAR_IS_DOUBLE\n\nvoid SkMatrix44::mapMScalars(const SkMScalar src[4], SkMScalar dst[4]) const {\n    SkMScalar storage[4];\n    SkMScalar* result = (src == dst) ? storage : dst;\n\n    for (int i = 0; i < 4; i++) {\n        SkMScalar value = 0;\n        for (int j = 0; j < 4; j++) {\n            value += fMat[j][i] * src[j];\n        }\n        result[i] = value;\n    }\n\n    if (storage == result) {\n        memcpy(dst, storage, sizeof(storage));\n    }\n}\n\n#endif\n\ntypedef void (*Map2Procf)(const SkMScalar mat[][4], const float src2[], int count, float dst4[]);\ntypedef void (*Map2Procd)(const SkMScalar mat[][4], const double src2[], int count, double dst4[]);\n\nstatic void map2_if(const SkMScalar mat[][4], const float* SK_RESTRICT src2,\n                    int count, float* SK_RESTRICT dst4) {\n    for (int i = 0; i < count; ++i) {\n        dst4[0] = src2[0];\n        dst4[1] = src2[1];\n        dst4[2] = 0;\n        dst4[3] = 1;\n        src2 += 2;\n        dst4 += 4;\n    }\n}\n\nstatic void map2_id(const SkMScalar mat[][4], const double* SK_RESTRICT src2,\n                    int count, double* SK_RESTRICT dst4) {\n    for (int i = 0; i < count; ++i) {\n        dst4[0] = src2[0];\n        dst4[1] = src2[1];\n        dst4[2] = 0;\n        dst4[3] = 1;\n        src2 += 2;\n        dst4 += 4;\n    }\n}\n\nstatic void map2_tf(const SkMScalar mat[][4], const float* SK_RESTRICT src2,\n                    int count, float* SK_RESTRICT dst4) {\n    const float mat30 = SkMScalarToFloat(mat[3][0]);\n    const float mat31 = SkMScalarToFloat(mat[3][1]);\n    const float mat32 = SkMScalarToFloat(mat[3][2]);\n    for (int n = 0; n < count; ++n) {\n        dst4[0] = src2[0] + mat30;\n        dst4[1] = src2[1] + mat31;\n        dst4[2] = mat32;\n        dst4[3] = 1;\n        src2 += 2;\n        dst4 += 4;\n    }\n}\n\nstatic void map2_td(const SkMScalar mat[][4], const double* SK_RESTRICT src2,\n                    int count, double* SK_RESTRICT dst4) {\n    for (int n = 0; n < count; ++n) {\n        dst4[0] = src2[0] + mat[3][0];\n        dst4[1] = src2[1] + mat[3][1];\n        dst4[2] = mat[3][2];\n        dst4[3] = 1;\n        src2 += 2;\n        dst4 += 4;\n    }\n}\n\nstatic void map2_sf(const SkMScalar mat[][4], const float* SK_RESTRICT src2,\n                    int count, float* SK_RESTRICT dst4) {\n    const float mat32 = SkMScalarToFloat(mat[3][2]);\n    for (int n = 0; n < count; ++n) {\n        dst4[0] = SkMScalarToFloat(mat[0][0] * src2[0] + mat[3][0]);\n        dst4[1] = SkMScalarToFloat(mat[1][1] * src2[1] + mat[3][1]);\n        dst4[2] = mat32;\n        dst4[3] = 1;\n        src2 += 2;\n        dst4 += 4;\n    }\n}\n\nstatic void map2_sd(const SkMScalar mat[][4], const double* SK_RESTRICT src2,\n                    int count, double* SK_RESTRICT dst4) {\n    for (int n = 0; n < count; ++n) {\n        dst4[0] = mat[0][0] * src2[0] + mat[3][0];\n        dst4[1] = mat[1][1] * src2[1] + mat[3][1];\n        dst4[2] = mat[3][2];\n        dst4[3] = 1;\n        src2 += 2;\n        dst4 += 4;\n    }\n}\n\nstatic void map2_af(const SkMScalar mat[][4], const float* SK_RESTRICT src2,\n                    int count, float* SK_RESTRICT dst4) {\n    SkMScalar r;\n    for (int n = 0; n < count; ++n) {\n        SkMScalar sx = SkFloatToMScalar(src2[0]);\n        SkMScalar sy = SkFloatToMScalar(src2[1]);\n        r = mat[0][0] * sx + mat[1][0] * sy + mat[3][0];\n        dst4[0] = SkMScalarToFloat(r);\n        r = mat[0][1] * sx + mat[1][1] * sy + mat[3][1];\n        dst4[1] = SkMScalarToFloat(r);\n        r = mat[0][2] * sx + mat[1][2] * sy + mat[3][2];\n        dst4[2] = SkMScalarToFloat(r);\n        dst4[3] = 1;\n        src2 += 2;\n        dst4 += 4;\n    }\n}\n\nstatic void map2_ad(const SkMScalar mat[][4], const double* SK_RESTRICT src2,\n                    int count, double* SK_RESTRICT dst4) {\n    for (int n = 0; n < count; ++n) {\n        double sx = src2[0];\n        double sy = src2[1];\n        dst4[0] = mat[0][0] * sx + mat[1][0] * sy + mat[3][0];\n        dst4[1] = mat[0][1] * sx + mat[1][1] * sy + mat[3][1];\n        dst4[2] = mat[0][2] * sx + mat[1][2] * sy + mat[3][2];\n        dst4[3] = 1;\n        src2 += 2;\n        dst4 += 4;\n    }\n}\n\nstatic void map2_pf(const SkMScalar mat[][4], const float* SK_RESTRICT src2,\n                    int count, float* SK_RESTRICT dst4) {\n    SkMScalar r;\n    for (int n = 0; n < count; ++n) {\n        SkMScalar sx = SkFloatToMScalar(src2[0]);\n        SkMScalar sy = SkFloatToMScalar(src2[1]);\n        for (int i = 0; i < 4; i++) {\n            r = mat[0][i] * sx + mat[1][i] * sy + mat[3][i];\n            dst4[i] = SkMScalarToFloat(r);\n        }\n        src2 += 2;\n        dst4 += 4;\n    }\n}\n\nstatic void map2_pd(const SkMScalar mat[][4], const double* SK_RESTRICT src2,\n                    int count, double* SK_RESTRICT dst4) {\n    for (int n = 0; n < count; ++n) {\n        double sx = src2[0];\n        double sy = src2[1];\n        for (int i = 0; i < 4; i++) {\n            dst4[i] = mat[0][i] * sx + mat[1][i] * sy + mat[3][i];\n        }\n        src2 += 2;\n        dst4 += 4;\n    }\n}\n\nvoid SkMatrix44::map2(const float src2[], int count, float dst4[]) const {\n    static const Map2Procf gProc[] = {\n        map2_if, map2_tf, map2_sf, map2_sf, map2_af, map2_af, map2_af, map2_af\n    };\n\n    TypeMask mask = this->getType();\n    Map2Procf proc = (mask & kPerspective_Mask) ? map2_pf : gProc[mask];\n    proc(fMat, src2, count, dst4);\n}\n\nvoid SkMatrix44::map2(const double src2[], int count, double dst4[]) const {\n    static const Map2Procd gProc[] = {\n        map2_id, map2_td, map2_sd, map2_sd, map2_ad, map2_ad, map2_ad, map2_ad\n    };\n\n    TypeMask mask = this->getType();\n    Map2Procd proc = (mask & kPerspective_Mask) ? map2_pd : gProc[mask];\n    proc(fMat, src2, count, dst4);\n}\n\nbool SkMatrix44::preserves2dAxisAlignment (SkMScalar epsilon) const {\n\n    \/\/ Can't check (mask & kPerspective_Mask) because Z isn't relevant here.\n    if (0 != perspX() || 0 != perspY()) return false;\n\n    \/\/ A matrix with two non-zeroish values in any of the upper right\n    \/\/ rows or columns will skew.  If only one value in each row or\n    \/\/ column is non-zeroish, we get a scale plus perhaps a 90-degree\n    \/\/ rotation.\n    int col0 = 0;\n    int col1 = 0;\n    int row0 = 0;\n    int row1 = 0;\n\n    \/\/ Must test against epsilon, not 0, because we can get values\n    \/\/ around 6e-17 in the matrix that \"should\" be 0.\n\n    if (SkMScalarAbs(fMat[0][0]) > epsilon) {\n        col0++;\n        row0++;\n    }\n    if (SkMScalarAbs(fMat[0][1]) > epsilon) {\n        col1++;\n        row0++;\n    }\n    if (SkMScalarAbs(fMat[1][0]) > epsilon) {\n        col0++;\n        row1++;\n    }\n    if (SkMScalarAbs(fMat[1][1]) > epsilon) {\n        col1++;\n        row1++;\n    }\n    if (col0 > 1 || col1 > 1 || row0 > 1 || row1 > 1) {\n        return false;\n    }\n\n    return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkMatrix44::dump() const {\n    static const char* format = \"|%g %g %g %g|\\n\"\n                                \"|%g %g %g %g|\\n\"\n                                \"|%g %g %g %g|\\n\"\n                                \"|%g %g %g %g|\\n\";\n    SkDebugf(format,\n             fMat[0][0], fMat[1][0], fMat[2][0], fMat[3][0],\n             fMat[0][1], fMat[1][1], fMat[2][1], fMat[3][1],\n             fMat[0][2], fMat[1][2], fMat[2][2], fMat[3][2],\n             fMat[0][3], fMat[1][3], fMat[2][3], fMat[3][3]);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void initFromMatrix(SkMScalar dst[4][4], const SkMatrix& src) {\n    dst[0][0] = SkScalarToMScalar(src[SkMatrix::kMScaleX]);\n    dst[1][0] = SkScalarToMScalar(src[SkMatrix::kMSkewX]);\n    dst[2][0] = 0;\n    dst[3][0] = SkScalarToMScalar(src[SkMatrix::kMTransX]);\n    dst[0][1] = SkScalarToMScalar(src[SkMatrix::kMSkewY]);\n    dst[1][1] = SkScalarToMScalar(src[SkMatrix::kMScaleY]);\n    dst[2][1] = 0;\n    dst[3][1] = SkScalarToMScalar(src[SkMatrix::kMTransY]);\n    dst[0][2] = 0;\n    dst[1][2] = 0;\n    dst[2][2] = 1;\n    dst[3][2] = 0;\n    dst[0][3] = SkScalarToMScalar(src[SkMatrix::kMPersp0]);\n    dst[1][3] = SkScalarToMScalar(src[SkMatrix::kMPersp1]);\n    dst[2][3] = 0;\n    dst[3][3] = SkScalarToMScalar(src[SkMatrix::kMPersp2]);\n}\n\nSkMatrix44::SkMatrix44(const SkMatrix& src) {\n    this->operator=(src);\n}\n\nSkMatrix44& SkMatrix44::operator=(const SkMatrix& src) {\n    initFromMatrix(fMat, src);\n\n    if (src.isIdentity()) {\n        this->setTypeMask(kIdentity_Mask);\n    } else {\n        this->recomputeTypeMask();\n    }\n    return *this;\n}\n\nSkMatrix44::operator SkMatrix() const {\n    SkMatrix dst;\n\n    dst[SkMatrix::kMScaleX] = SkMScalarToScalar(fMat[0][0]);\n    dst[SkMatrix::kMSkewX]  = SkMScalarToScalar(fMat[1][0]);\n    dst[SkMatrix::kMTransX] = SkMScalarToScalar(fMat[3][0]);\n\n    dst[SkMatrix::kMSkewY]  = SkMScalarToScalar(fMat[0][1]);\n    dst[SkMatrix::kMScaleY] = SkMScalarToScalar(fMat[1][1]);\n    dst[SkMatrix::kMTransY] = SkMScalarToScalar(fMat[3][1]);\n\n    dst[SkMatrix::kMPersp0] = SkMScalarToScalar(fMat[0][3]);\n    dst[SkMatrix::kMPersp1] = SkMScalarToScalar(fMat[1][3]);\n    dst[SkMatrix::kMPersp2] = SkMScalarToScalar(fMat[3][3]);\n\n    return dst;\n}\n","avg_line_length":32.2954764196,"max_line_length":99,"alphanum_fraction":0.5202205335,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1810,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"#include <iostream>\n#include <cmath>\n#include \"halfedge.h\"\n#include \"triangle.h\"\n#include \"vertex.h\"\n\n\nHalfEdge::HalfEdge(Mesh* mesh_in, Vertex* v0_in, Vertex* v1_in,\n        Triangle* triangle_in,\n        unsigned id_on_tri_of_v0) : MeshAttribute( mesh_in, id_on_tri_of_v0) {\n    mesh->n_halfedges++;\n    v0 = v0_in;\n    v1 = v1_in;\n    triangle = triangle_in;\n    halfedge = v1->halfedge_to_vertex(v0);\n    switch (id_on_tri_of_v0) {\n        case 0:\n            v0_tri_i = 0;\n            v1_tri_i = 1;\n            v2_tri_i = 2;\n            v2 = triangle->v2;\n            break;\n        case 1:\n            v0_tri_i = 1;\n            v1_tri_i = 2;\n            v2_tri_i = 0;\n            v2 = triangle->v0;\n            break;\n        case 2:\n            v0_tri_i = 2;\n            v1_tri_i = 0;\n            v2_tri_i = 1;\n            v2 = triangle->v1;\n            break;\n    }\n    if (halfedge != NULL) {\n        \/\/ setting opposite halfedge to me\n        halfedge->halfedge = this;\n        mesh->n_fulledges++;\n    }\n    else {\n        \/\/ first time weve encountered this\n        mesh_in->add_edge(this);\n    }\n}\n\nHalfEdge::~HalfEdge(){}\n\nbool HalfEdge::part_of_fulledge() {\n    if (halfedge != NULL) {\n        return true;\n    }\n    else {\n        return false;\n    }\n}\n\nHalfEdge* HalfEdge::ccw_around_tri() {\n    HalfEdge* he = NULL;\n    if (v1->id == triangle->v0->id) {\n        he = triangle->e0;\n    }\n    else if (v1->id == triangle->v1->id) {\n        he = triangle->e1;\n    }\n    else if (v1->id == triangle->v2->id) {\n        he = triangle->e2;\n    }\n    else {\n        std::cout << \"ERROR: cannot find HE!\" << std::endl;\n    }\n    return he;\n}\n\ndouble HalfEdge::length() {\n    \/\/ TODO actually calcuate this\n    std::cout << \"This isn't actually calculating the length\" << std::endl;\n    return 1.0;\n}\n\n","avg_line_length":22.3456790123,"max_line_length":78,"alphanum_fraction":0.520441989,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":12738,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":6989.0,"content":"#include \"calc_metrics.h\"\n\n#include <catboost\/libs\/data\/cb_dsv_loader.h>\n#include <catboost\/libs\/data\/proceed_pool_in_blocks.h>\n#include <catboost\/private\/libs\/target\/data_providers.h>\n\n\nnamespace NCB {\n\n    class TCalcMetricDataProvider {\n    public:\n        explicit TCalcMetricDataProvider(const TDataProviderPtr datasetPart)\n            : DataProvider(datasetPart)\n            {}\n\n        TVector<TVector<double>> GetApproxes(NPar::TLocalExecutor* localExecutor) const;\n        TVector<TSharedVector<float>> GetLabels(NPar::TLocalExecutor* localExecutor) const;\n        const TWeights<float>& GetWeights() const;\n        TMaybe<TSharedVector<TQueryInfo>> GetQueriesInfo() const;\n\n        void ExtractApproxesToBackOfVector(TVector<TVector<double>>* approxesPtr, NPar::TLocalExecutor* localExecutor) const;\n\n    private:\n        const TDataProviderPtr DataProvider;\n    };\n\n    static TVector<TSharedVector<float>> ConvertTargetForCalcMetric(\n        TMaybeData<TConstArrayRef<TRawTarget>> maybeRawTarget,\n        bool isClass,\n        bool isMultiClass,\n        bool isMultiLabel,\n        NPar::ILocalExecutor* localExecutor)\n    {\n        TVector<NJson::TJsonValue> outputClassLabels;\n        return ConvertTarget(\n            maybeRawTarget,\n            ERawTargetType::Float,\n            \/* isRealTarget *\/ true,\n            isClass,\n            isMultiClass,\n            isMultiLabel,\n            \/* targetBorder *\/ Nothing(),\n            \/* classCountUnknown *\/ true,\n            \/* inputClassLabels *\/ {},\n            &outputClassLabels,\n            localExecutor,\n            \/* classCount *\/ nullptr\n        );\n    }\n\n    void TCalcMetricDataProvider::ExtractApproxesToBackOfVector(\n        TVector<TVector<double>>* approxesPtr,\n        NPar::TLocalExecutor* localExecutor\n    ) const {\n        const TRawObjectsDataProvider& rawObjectsData = dynamic_cast<TRawObjectsDataProvider& >(\n            *(DataProvider->ObjectsData)\n        );\n        size_t approxDimension = DataProvider.Get()->ObjectsData->GetFeaturesLayout()->GetFloatFeatureCount();\n        if (approxesPtr->empty()) {\n            approxesPtr->resize(approxDimension);\n        } else {\n            Y_ASSERT(approxDimension == approxesPtr->size());\n        }\n        for (auto i : xrange(approxesPtr->size())) {\n            auto maybeFactorData = rawObjectsData.GetFloatFeature(i);\n            Y_ASSERT(maybeFactorData);\n            auto factorData = maybeFactorData.GetRef()->ExtractValues(localExecutor);\n            auto objectCount = DataProvider->GetObjectCount();\n            (*approxesPtr)[i].insert(\n                (*approxesPtr)[i].end(),\n                factorData.begin(),\n                factorData.begin() + objectCount\n            );\n        }\n    }\n\n    TVector<TVector<double>> TCalcMetricDataProvider::GetApproxes(\n        NPar::TLocalExecutor* localExecutor\n    ) const {\n        TVector<TVector<double>> approx;\n        ExtractApproxesToBackOfVector(&approx, localExecutor);\n        return approx;\n    }\n\n    TVector<TSharedVector<float>> TCalcMetricDataProvider::GetLabels(\n        NPar::TLocalExecutor* localExecutor\n    ) const {\n        const auto& targetData = DataProvider->RawTargetData;\n        return ConvertTargetForCalcMetric(\n            targetData.GetTarget(),\n            \/* isClass *\/ false,\n            \/* isMultiClass *\/ false,\n            \/* isMultiLabel *\/ false,\n            localExecutor\n        );\n    }\n\n    const TWeights<float>& TCalcMetricDataProvider::GetWeights() const {\n        return DataProvider->RawTargetData.GetWeights();\n    }\n\n    TMaybe<TSharedVector<TQueryInfo>> TCalcMetricDataProvider::GetQueriesInfo() const {\n        const auto& targetData = DataProvider->RawTargetData;\n        if (DataProvider->ObjectsData->GetGroupIds().Defined()) {\n            return MakeGroupInfos(\n                *targetData.GetObjectsGrouping(),\n                DataProvider->ObjectsData->GetSubgroupIds(),\n                targetData.GetWeights(),\n                \/* pairs *\/ Nothing()\n            );\n        }\n        return Nothing();\n    }\n\n    TVector<THolder<IMetric>> ConstructMetric(\n        const TVector<TColumn>& columnsDescription,\n        const TVector<TString>& metricNamesList\n    ) {\n        size_t approxDimension = 0;\n        for (auto& column : columnsDescription) {\n            if (column.Type == EColumn::Num) {\n                approxDimension += 1;\n            }\n        }\n        return CreateMetricsFromDescription(metricNamesList, approxDimension);\n    }\n\n    TVector<double> GetMetricResultsFromMetricHolder(\n        const TVector<TMetricHolder>& stats,\n        const TVector<THolder<IMetric>>& metrics\n    ) {\n        TVector<double> metricResults;\n        metricResults.reserve(metrics.size());\n        for (auto metricIdx : xrange(metrics.size())) {\n            metricResults.push_back(metrics[metricIdx]->GetFinalError(stats[metricIdx]));\n        }\n        return metricResults;\n    }\n\n    TVector<TMetricHolder> ConsumeCalcMetricsData(\n        const TVector<const IMetric*>& metrics,\n        const TDataProviderPtr dataProviderPtr,\n        NPar::TLocalExecutor* localExecutor\n    ) {\n        for (const auto& metric : metrics) {\n            CB_ENSURE_INTERNAL(metric->IsAdditiveMetric(), \"ConsumeCalcMetricsData function supports only additive metrics\");\n        }\n\n        TCalcMetricDataProvider dataProvider(dataProviderPtr);\n\n        TVector<TVector<double>> approx = dataProvider.GetApproxes(localExecutor);\n        TVector<TSharedVector<float>> labels = dataProvider.GetLabels(localExecutor);\n\n        auto& weights = dataProvider.GetWeights();\n        TMaybe<TSharedVector<TQueryInfo>> queriesInfo = dataProvider.GetQueriesInfo();\n        TConstArrayRef<TQueryInfo> queriesInfoRef;\n        if (queriesInfo.Defined()) {\n            queriesInfoRef = *queriesInfo->Get();\n        }\n\n        TVector<TConstArrayRef<float>> labelRef(labels.size());\n        for (auto targetIdx : xrange(labels.size())) {\n            labelRef[targetIdx] = *labels[targetIdx].Get();\n        }\n\n        return EvalErrorsWithCaching(\n            approx,\n            \/*approxDelts*\/{},\n            \/*isExpApprox*\/false,\n            labelRef,\n            weights.IsTrivial() ? TConstArrayRef<float>() : weights.GetNonTrivialData(),\n            queriesInfoRef,\n            metrics,\n            localExecutor\n        );\n    }\n\n    void TNonAdditiveMetricData::SaveProcessedData(\n        const TDataProviderPtr dataProviderPtr,\n        NPar::TLocalExecutor *localExecutor\n    ) {\n        TCalcMetricDataProvider dataProvider(dataProviderPtr);\n        dataProvider.ExtractApproxesToBackOfVector(&Approxes, localExecutor);\n\n        TVector<TSharedVector<float>> labels = dataProvider.GetLabels(localExecutor);\n        auto& weights = dataProvider.GetWeights();\n        if (!weights.IsTrivial()) {\n            Weights.insert(\n                Weights.end(),\n                weights.GetNonTrivialData().begin(),\n                weights.GetNonTrivialData().end()\n            );\n        }\n\n        if (Target.empty()) {\n            Target.resize(labels.size());\n        } else {\n            Y_ASSERT(Target.size() == labels.size());\n        }\n        for (auto targetIdx : xrange(labels.size())) {\n            Target[targetIdx].insert(\n                Target[targetIdx].end(),\n                labels[targetIdx]->begin(),\n                labels[targetIdx]->end());\n        }\n    }\n\n    TVector<TMetricHolder> CalculateNonAdditiveMetrics(\n        const TNonAdditiveMetricData& nonAdditiveMetricData,\n        const TVector<const IMetric*>& nonAdditiveMetrics,\n        NPar::TLocalExecutor *localExecutor\n    ) {\n        for (const auto& metric : nonAdditiveMetrics) {\n            Y_ASSERT(!metric->IsAdditiveMetric());\n        }\n        if (!nonAdditiveMetrics.empty()) {\n            return EvalErrorsWithCaching(\n                nonAdditiveMetricData.Approxes,\n                \/*approxDelts*\/{},\n                \/*isExpApprox*\/false,\n                To2DConstArrayRef<float>(nonAdditiveMetricData.Target),\n                nonAdditiveMetricData.Weights,\n                {},\n                nonAdditiveMetrics,\n                localExecutor\n            );\n        }\n        return {};\n    }\n\n    TVector<double> CalcMetricsSingleHost(\n        const NCatboostOptions::TDatasetReadingParams& datasetReadingParams,\n        const TVector<THolder<IMetric>>& metrics,\n        const TVector<TColumn>& columnsDescription,\n        size_t threadCount\n    ) {\n        auto inputPath = datasetReadingParams.PoolPath;\n        CB_ENSURE(inputPath.Scheme.Contains(\"dsv\") || inputPath.Scheme == \"\", \/\/ \"\" is \"dsv\"\n                  \"Local metrics evaluation supports \\\"dsv\\\" and \\\"yt-dsv\\\" input file schemas.\");\n\n        NPar::TLocalExecutor executor;\n        executor.RunAdditionalThreads(threadCount - 1);\n\n        const int blockSize = 150000;\n        TVector<TMetricHolder> additiveStats;\n\n        TNonAdditiveMetricData nonAdditiveMetricData;\n\n        TVector<const IMetric*> additiveMetrics;\n        TVector<const IMetric*> nonAdditiveMetrics;\n\n        for (const auto& metric : metrics) {\n            if (metric->IsAdditiveMetric()) {\n                additiveMetrics.push_back(metric.Get());\n            } else {\n                nonAdditiveMetrics.push_back(metric.Get());\n            }\n        }\n\n        ReadAndProceedPoolInBlocks(\n            datasetReadingParams,\n            blockSize,\n            [&](const NCB::TDataProviderPtr datasetPart) {\n                TSetLoggingVerbose inThisScope;\n                auto subStats = ConsumeCalcMetricsData(\n                    additiveMetrics,\n                    datasetPart,\n                    &executor);\n                if (!nonAdditiveMetrics.empty()) {\n                    nonAdditiveMetricData.SaveProcessedData(datasetPart, &executor);\n                }\n                if (additiveStats.empty()) {\n                    additiveStats = std::move(subStats);\n                } else {\n                    Y_ASSERT(additiveStats.size() == subStats.size());\n                    for (auto ind : xrange(additiveStats.size())) {\n                        additiveStats[ind].Add(subStats[ind]);\n                    }\n                }\n            },\n            &executor,\n            MakeCdProviderFromArray(columnsDescription)\n        );\n\n        auto nonAdditiveStats = CalculateNonAdditiveMetrics(\n            nonAdditiveMetricData,\n            nonAdditiveMetrics,\n            &executor\n        );\n\n        TVector<TMetricHolder> stats;\n        auto additiveStatsPtr = additiveStats.begin();\n        auto nonAdditiveStatsPtr = nonAdditiveStats.begin();\n        for (const auto& metric : metrics) {\n            if (metric->IsAdditiveMetric()) {\n                stats.emplace_back(std::move(*(additiveStatsPtr++)));\n            } else {\n                stats.emplace_back(std::move(*(nonAdditiveStatsPtr++)));\n            }\n        }\n        Y_ASSERT(additiveStatsPtr == additiveStats.end());\n        Y_ASSERT(nonAdditiveStatsPtr == nonAdditiveStats.end());\n\n        auto metricResults = GetMetricResultsFromMetricHolder(stats, metrics);\n        return metricResults;\n    }\n\n    THashMap<TString, double> TOpenSourceCalcMetricsImplementation::CalcMetrics(\n        const TPathWithScheme& inputPath,\n        const TVector<TString>& metricNamesList,\n        const NCB::TDsvFormatOptions& dsvFormat,\n        const THashMap<int, EColumn>& nonAuxiliaryColumnsDescription,\n        ui32 threadCount\n    ) const {\n        NCatboostOptions::TDatasetReadingParams datasetReadingParams;\n        datasetReadingParams.PoolPath = inputPath;\n        datasetReadingParams.ColumnarPoolFormatParams.DsvFormat = dsvFormat;\n\n        Y_ASSERT(inputPath.Scheme == \"dsv\" || inputPath.Scheme == \"\");\n        ui32 columnCount = GetDsvColumnCount(inputPath, dsvFormat);\n\n        TVector<TColumn> columnsDescription;\n        columnsDescription.resize(columnCount, {EColumn::Auxiliary, TString()});\n        for (auto [ind, column] : nonAuxiliaryColumnsDescription) {\n            columnsDescription[ind] = TColumn{column, \"\"};\n        }\n\n        auto metrics = ConstructMetric(columnsDescription, metricNamesList);\n\n        TVector<double> calculatedMetrics = CalcMetricsSingleHost(\n            datasetReadingParams,\n            metrics,\n            columnsDescription,\n            threadCount\n        );\n        THashMap<TString, double> metricResults;\n        for (auto ind : xrange(metrics.size())) {\n            metricResults.insert({metrics[ind]->GetDescription(), calculatedMetrics[ind]});\n        }\n        return metricResults;\n    }\n\n    namespace {\n        TCalcMetricsImplementationFactory::TRegistrator<TOpenSourceCalcMetricsImplementation>\n            OpenSourceCalcMetricsImplementationReg(\"dsv\");\n    }\n}\n","avg_line_length":36.6034482759,"max_line_length":125,"alphanum_fraction":0.6119485005,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":36759,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":53.0,"content":"\/*\nwww.sourceforge.net\/projects\/tinyxml\nOriginal code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com)\n\nThis software is provided 'as-is', without any express or implied\nwarranty. In no event will the authors be held liable for any\ndamages arising from the use of this software.\n\nPermission is granted to anyone to use this software for any\npurpose, including commercial applications, and to alter it and\nredistribute it freely, subject to the following restrictions:\n\n1. The origin of this software must not be misrepresented; you must\nnot claim that you wrote the original software. If you use this\nsoftware in a product, an acknowledgment in the product documentation\nwould be appreciated but is not required.\n\n2. Altered source versions must be plainly marked as such, and\nmust not be misrepresented as being the original software.\n\n3. This notice may not be removed or altered from any source\ndistribution.\n*\/\n\n#include <ctype.h>\n\n#ifdef TIXML_USE_STL\n#include <sstream>\n#include <iostream>\n#endif\n\n#include \"tinyxml.h\"\n\n\nbool TiXmlBase::condenseWhiteSpace = true;\n\n\/\/ Microsoft compiler security\nFILE* TiXmlFOpen( const char* filename, const char* mode )\n{\n\/*\n\t#if defined(_MSC_VER) && (_MSC_VER >= 1400 )\n\t\tFILE* fp = 0;\n\t\terrno_t err = fopen_s( &fp, filename, mode );\n\t\tif ( !err && fp )\n\t\t\treturn fp;\n\t\treturn 0;\n\t#else\n\t*\/\n\t\treturn fopen( filename, mode );\n\t\/*\n\t#endif\n\t*\/\n}\n\nvoid TiXmlBase::EncodeString( const TIXML_STRING& str, TIXML_STRING* outString )\n{\n\tint i=0;\n\n\twhile( i<(int)str.length() )\n\t{\n\t\tunsigned char c = (unsigned char) str[i];\n\n\t\tif (    c == '&' \n\t\t     && i < ( (int)str.length() - 2 )\n\t\t\t && str[i+1] == '#'\n\t\t\t && str[i+2] == 'x' )\n\t\t{\n\t\t\t\/\/ Hexadecimal character reference.\n\t\t\t\/\/ Pass through unchanged.\n\t\t\t\/\/ &#xA9;\t-- copyright symbol, for example.\n\t\t\t\/\/\n\t\t\t\/\/ The -1 is a bug fix from Rob Laveaux. It keeps\n\t\t\t\/\/ an overflow from happening if there is no ';'.\n\t\t\t\/\/ There are actually 2 ways to exit this loop -\n\t\t\t\/\/ while fails (error case) and break (semicolon found).\n\t\t\t\/\/ However, there is no mechanism (currently) for\n\t\t\t\/\/ this function to return an error.\n\t\t\twhile ( i<(int)str.length()-1 )\n\t\t\t{\n\t\t\t\toutString->append( str.c_str() + i, 1 );\n\t\t\t\t++i;\n\t\t\t\tif ( str[i] == ';' )\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse if ( c == '&' )\n\t\t{\n\t\t\toutString->append( entity[0].str, entity[0].strLength );\n\t\t\t++i;\n\t\t}\n\t\telse if ( c == '<' )\n\t\t{\n\t\t\toutString->append( entity[1].str, entity[1].strLength );\n\t\t\t++i;\n\t\t}\n\t\telse if ( c == '>' )\n\t\t{\n\t\t\toutString->append( entity[2].str, entity[2].strLength );\n\t\t\t++i;\n\t\t}\n\t\telse if ( c == '\\\"' )\n\t\t{\n\t\t\toutString->append( entity[3].str, entity[3].strLength );\n\t\t\t++i;\n\t\t}\n\t\telse if ( c == '\\'' )\n\t\t{\n\t\t\toutString->append( entity[4].str, entity[4].strLength );\n\t\t\t++i;\n\t\t}\n\t\telse if ( c < 32 )\n\t\t{\n\t\t\t\/\/ Easy pass at non-alpha\/numeric\/symbol\n\t\t\t\/\/ Below 32 is symbolic.\n\t\t\tchar buf[ 32 ];\n\t\t\t\n\t\t\t#if defined(TIXML_SNPRINTF)\t\t\n\t\t\t\tTIXML_SNPRINTF( buf, sizeof(buf), \"&#x%02X;\", (unsigned) ( c & 0xff ) );\n\t\t\t#else\n\t\t\t\tsprintf( buf, \"&#x%02X;\", (unsigned) ( c & 0xff ) );\n\t\t\t#endif\t\t\n\n\t\t\t\/\/*ME:\twarning C4267: convert 'size_t' to 'int'\n\t\t\t\/\/*ME:\tInt-Cast to make compiler happy ...\n\t\t\toutString->append( buf, (int)strlen( buf ) );\n\t\t\t++i;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/char realc = (char) c;\n\t\t\t\/\/outString->append( &realc, 1 );\n\t\t\t*outString += (char) c;\t\/\/ somewhat more efficient function call.\n\t\t\t++i;\n\t\t}\n\t}\n}\n\n\nTiXmlNode::TiXmlNode( NodeType _type ) : TiXmlBase()\n{\n\tparent = 0;\n\ttype = _type;\n\tfirstChild = 0;\n\tlastChild = 0;\n\tprev = 0;\n\tnext = 0;\n}\n\n\nTiXmlNode::~TiXmlNode()\n{\n\tTiXmlNode* node = firstChild;\n\tTiXmlNode* temp = 0;\n\n\twhile ( node )\n\t{\n\t\ttemp = node;\n\t\tnode = node->next;\n\t\tdelete temp;\n\t}\t\n}\n\n\nvoid TiXmlNode::CopyTo( TiXmlNode* target ) const\n{\n\ttarget->SetValue (value.c_str() );\n\ttarget->userData = userData; \n}\n\n\nvoid TiXmlNode::Clear()\n{\n\tTiXmlNode* node = firstChild;\n\tTiXmlNode* temp = 0;\n\n\twhile ( node )\n\t{\n\t\ttemp = node;\n\t\tnode = node->next;\n\t\tdelete temp;\n\t}\t\n\n\tfirstChild = 0;\n\tlastChild = 0;\n}\n\n\nTiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node )\n{\n\tassert( node->parent == 0 || node->parent == this );\n\tassert( node->GetDocument() == 0 || node->GetDocument() == this->GetDocument() );\n\n\tif ( node->Type() == TiXmlNode::DOCUMENT )\n\t{\n\t\tdelete node;\n\t\tif ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN );\n\t\treturn 0;\n\t}\n\n\tnode->parent = this;\n\n\tnode->prev = lastChild;\n\tnode->next = 0;\n\n\tif ( lastChild )\n\t\tlastChild->next = node;\n\telse\n\t\tfirstChild = node;\t\t\t\/\/ it was an empty list.\n\n\tlastChild = node;\n\treturn node;\n}\n\n\nTiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis )\n{\n\tif ( addThis.Type() == TiXmlNode::DOCUMENT )\n\t{\n\t\tif ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN );\n\t\treturn 0;\n\t}\n\tTiXmlNode* node = addThis.Clone();\n\tif ( !node )\n\t\treturn 0;\n\n\treturn LinkEndChild( node );\n}\n\n\nTiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis )\n{\t\n\tif ( !beforeThis || beforeThis->parent != this ) {\n\t\treturn 0;\n\t}\n\tif ( addThis.Type() == TiXmlNode::DOCUMENT )\n\t{\n\t\tif ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN );\n\t\treturn 0;\n\t}\n\n\tTiXmlNode* node = addThis.Clone();\n\tif ( !node )\n\t\treturn 0;\n\tnode->parent = this;\n\n\tnode->next = beforeThis;\n\tnode->prev = beforeThis->prev;\n\tif ( beforeThis->prev )\n\t{\n\t\tbeforeThis->prev->next = node;\n\t}\n\telse\n\t{\n\t\tassert( firstChild == beforeThis );\n\t\tfirstChild = node;\n\t}\n\tbeforeThis->prev = node;\n\treturn node;\n}\n\n\nTiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis )\n{\n\tif ( !afterThis || afterThis->parent != this ) {\n\t\treturn 0;\n\t}\n\tif ( addThis.Type() == TiXmlNode::DOCUMENT )\n\t{\n\t\tif ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN );\n\t\treturn 0;\n\t}\n\n\tTiXmlNode* node = addThis.Clone();\n\tif ( !node )\n\t\treturn 0;\n\tnode->parent = this;\n\n\tnode->prev = afterThis;\n\tnode->next = afterThis->next;\n\tif ( afterThis->next )\n\t{\n\t\tafterThis->next->prev = node;\n\t}\n\telse\n\t{\n\t\tassert( lastChild == afterThis );\n\t\tlastChild = node;\n\t}\n\tafterThis->next = node;\n\treturn node;\n}\n\n\nTiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis )\n{\n\tif ( replaceThis->parent != this )\n\t\treturn 0;\n\n\tTiXmlNode* node = withThis.Clone();\n\tif ( !node )\n\t\treturn 0;\n\n\tnode->next = replaceThis->next;\n\tnode->prev = replaceThis->prev;\n\n\tif ( replaceThis->next )\n\t\treplaceThis->next->prev = node;\n\telse\n\t\tlastChild = node;\n\n\tif ( replaceThis->prev )\n\t\treplaceThis->prev->next = node;\n\telse\n\t\tfirstChild = node;\n\n\tdelete replaceThis;\n\tnode->parent = this;\n\treturn node;\n}\n\n\nbool TiXmlNode::RemoveChild( TiXmlNode* removeThis )\n{\n\tif ( removeThis->parent != this )\n\t{\t\n\t\tassert( 0 );\n\t\treturn false;\n\t}\n\n\tif ( removeThis->next )\n\t\tremoveThis->next->prev = removeThis->prev;\n\telse\n\t\tlastChild = removeThis->prev;\n\n\tif ( removeThis->prev )\n\t\tremoveThis->prev->next = removeThis->next;\n\telse\n\t\tfirstChild = removeThis->next;\n\n\tdelete removeThis;\n\treturn true;\n}\n\nconst TiXmlNode* TiXmlNode::FirstChild( const char * _value ) const\n{\n\tconst TiXmlNode* node;\n\tfor ( node = firstChild; node; node = node->next )\n\t{\n\t\tif ( strcmp( node->Value(), _value ) == 0 )\n\t\t\treturn node;\n\t}\n\treturn 0;\n}\n\n\nconst TiXmlNode* TiXmlNode::LastChild( const char * _value ) const\n{\n\tconst TiXmlNode* node;\n\tfor ( node = lastChild; node; node = node->prev )\n\t{\n\t\tif ( strcmp( node->Value(), _value ) == 0 )\n\t\t\treturn node;\n\t}\n\treturn 0;\n}\n\n\nconst TiXmlNode* TiXmlNode::IterateChildren( const TiXmlNode* previous ) const\n{\n\tif ( !previous )\n\t{\n\t\treturn FirstChild();\n\t}\n\telse\n\t{\n\t\tassert( previous->parent == this );\n\t\treturn previous->NextSibling();\n\t}\n}\n\n\nconst TiXmlNode* TiXmlNode::IterateChildren( const char * val, const TiXmlNode* previous ) const\n{\n\tif ( !previous )\n\t{\n\t\treturn FirstChild( val );\n\t}\n\telse\n\t{\n\t\tassert( previous->parent == this );\n\t\treturn previous->NextSibling( val );\n\t}\n}\n\n\nconst TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const \n{\n\tconst TiXmlNode* node;\n\tfor ( node = next; node; node = node->next )\n\t{\n\t\tif ( strcmp( node->Value(), _value ) == 0 )\n\t\t\treturn node;\n\t}\n\treturn 0;\n}\n\n\nconst TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) const\n{\n\tconst TiXmlNode* node;\n\tfor ( node = prev; node; node = node->prev )\n\t{\n\t\tif ( strcmp( node->Value(), _value ) == 0 )\n\t\t\treturn node;\n\t}\n\treturn 0;\n}\n\n\nvoid TiXmlElement::RemoveAttribute( const char * name )\n{\n    #ifdef TIXML_USE_STL\n\tTIXML_STRING str( name );\n\tTiXmlAttribute* node = attributeSet.Find( str );\n\t#else\n\tTiXmlAttribute* node = attributeSet.Find( name );\n\t#endif\n\tif ( node )\n\t{\n\t\tattributeSet.Remove( node );\n\t\tdelete node;\n\t}\n}\n\nconst TiXmlElement* TiXmlNode::FirstChildElement() const\n{\n\tconst TiXmlNode* node;\n\n\tfor (\tnode = FirstChild();\n\t\t\tnode;\n\t\t\tnode = node->NextSibling() )\n\t{\n\t\tif ( node->ToElement() )\n\t\t\treturn node->ToElement();\n\t}\n\treturn 0;\n}\n\n\nconst TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) const\n{\n\tconst TiXmlNode* node;\n\n\tfor (\tnode = FirstChild( _value );\n\t\t\tnode;\n\t\t\tnode = node->NextSibling( _value ) )\n\t{\n\t\tif ( node->ToElement() )\n\t\t\treturn node->ToElement();\n\t}\n\treturn 0;\n}\n\n\nconst TiXmlElement* TiXmlNode::NextSiblingElement() const\n{\n\tconst TiXmlNode* node;\n\n\tfor (\tnode = NextSibling();\n\t\t\tnode;\n\t\t\tnode = node->NextSibling() )\n\t{\n\t\tif ( node->ToElement() )\n\t\t\treturn node->ToElement();\n\t}\n\treturn 0;\n}\n\n\nconst TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) const\n{\n\tconst TiXmlNode* node;\n\n\tfor (\tnode = NextSibling( _value );\n\t\t\tnode;\n\t\t\tnode = node->NextSibling( _value ) )\n\t{\n\t\tif ( node->ToElement() )\n\t\t\treturn node->ToElement();\n\t}\n\treturn 0;\n}\n\n\nconst TiXmlDocument* TiXmlNode::GetDocument() const\n{\n\tconst TiXmlNode* node;\n\n\tfor( node = this; node; node = node->parent )\n\t{\n\t\tif ( node->ToDocument() )\n\t\t\treturn node->ToDocument();\n\t}\n\treturn 0;\n}\n\n\nTiXmlElement::TiXmlElement (const char * _value)\n\t: TiXmlNode( TiXmlNode::ELEMENT )\n{\n\tfirstChild = lastChild = 0;\n\tvalue = _value;\n}\n\n\n#ifdef TIXML_USE_STL\nTiXmlElement::TiXmlElement( const std::string& _value ) \n\t: TiXmlNode( TiXmlNode::ELEMENT )\n{\n\tfirstChild = lastChild = 0;\n\tvalue = _value;\n}\n#endif\n\n\nTiXmlElement::TiXmlElement( const TiXmlElement& copy)\n\t: TiXmlNode( TiXmlNode::ELEMENT )\n{\n\tfirstChild = lastChild = 0;\n\tcopy.CopyTo( this );\t\n}\n\n\nvoid TiXmlElement::operator=( const TiXmlElement& base )\n{\n\tClearThis();\n\tbase.CopyTo( this );\n}\n\n\nTiXmlElement::~TiXmlElement()\n{\n\tClearThis();\n}\n\n\nvoid TiXmlElement::ClearThis()\n{\n\tClear();\n\twhile( attributeSet.First() )\n\t{\n\t\tTiXmlAttribute* node = attributeSet.First();\n\t\tattributeSet.Remove( node );\n\t\tdelete node;\n\t}\n}\n\n\nconst char* TiXmlElement::Attribute( const char* name ) const\n{\n\tconst TiXmlAttribute* node = attributeSet.Find( name );\n\tif ( node )\n\t\treturn node->Value();\n\treturn 0;\n}\n\n\n#ifdef TIXML_USE_STL\nconst std::string* TiXmlElement::Attribute( const std::string& name ) const\n{\n\tconst TiXmlAttribute* node = attributeSet.Find( name );\n\tif ( node )\n\t\treturn &node->ValueStr();\n\treturn 0;\n}\n#endif\n\n\nconst char* TiXmlElement::Attribute( const char* name, int* i ) const\n{\n\tconst char* s = Attribute( name );\n\tif ( i )\n\t{\n\t\tif ( s ) {\n\t\t\t*i = atoi( s );\n\t\t}\n\t\telse {\n\t\t\t*i = 0;\n\t\t}\n\t}\n\treturn s;\n}\n\n\n#ifdef TIXML_USE_STL\nconst std::string* TiXmlElement::Attribute( const std::string& name, int* i ) const\n{\n\tconst std::string* s = Attribute( name );\n\tif ( i )\n\t{\n\t\tif ( s ) {\n\t\t\t*i = atoi( s->c_str() );\n\t\t}\n\t\telse {\n\t\t\t*i = 0;\n\t\t}\n\t}\n\treturn s;\n}\n#endif\n\n\nconst char* TiXmlElement::Attribute( const char* name, double* d ) const\n{\n\tconst char* s = Attribute( name );\n\tif ( d )\n\t{\n\t\tif ( s ) {\n\t\t\t*d = atof( s );\n\t\t}\n\t\telse {\n\t\t\t*d = 0;\n\t\t}\n\t}\n\treturn s;\n}\n\n\n#ifdef TIXML_USE_STL\nconst std::string* TiXmlElement::Attribute( const std::string& name, double* d ) const\n{\n\tconst std::string* s = Attribute( name );\n\tif ( d )\n\t{\n\t\tif ( s ) {\n\t\t\t*d = atof( s->c_str() );\n\t\t}\n\t\telse {\n\t\t\t*d = 0;\n\t\t}\n\t}\n\treturn s;\n}\n#endif\n\n\nint TiXmlElement::QueryIntAttribute( const char* name, int* ival ) const\n{\n\tconst TiXmlAttribute* node = attributeSet.Find( name );\n\tif ( !node )\n\t\treturn TIXML_NO_ATTRIBUTE;\n\treturn node->QueryIntValue( ival );\n}\n\n\n#ifdef TIXML_USE_STL\nint TiXmlElement::QueryIntAttribute( const std::string& name, int* ival ) const\n{\n\tconst TiXmlAttribute* node = attributeSet.Find( name );\n\tif ( !node )\n\t\treturn TIXML_NO_ATTRIBUTE;\n\treturn node->QueryIntValue( ival );\n}\n#endif\n\n\nint TiXmlElement::QueryDoubleAttribute( const char* name, double* dval ) const\n{\n\tconst TiXmlAttribute* node = attributeSet.Find( name );\n\tif ( !node )\n\t\treturn TIXML_NO_ATTRIBUTE;\n\treturn node->QueryDoubleValue( dval );\n}\n\n\n#ifdef TIXML_USE_STL\nint TiXmlElement::QueryDoubleAttribute( const std::string& name, double* dval ) const\n{\n\tconst TiXmlAttribute* node = attributeSet.Find( name );\n\tif ( !node )\n\t\treturn TIXML_NO_ATTRIBUTE;\n\treturn node->QueryDoubleValue( dval );\n}\n#endif\n\n\nvoid TiXmlElement::SetAttribute( const char * name, int val )\n{\t\n\tchar buf[64];\n\t#if defined(TIXML_SNPRINTF)\t\t\n\t\tTIXML_SNPRINTF( buf, sizeof(buf), \"%d\", val );\n\t#else\n\t\tsprintf( buf, \"%d\", val );\n\t#endif\n\tSetAttribute( name, buf );\n}\n\n\n#ifdef TIXML_USE_STL\nvoid TiXmlElement::SetAttribute( const std::string& name, int val )\n{\t\n   std::ostringstream oss;\n   oss << val;\n   SetAttribute( name, oss.str() );\n}\n#endif\n\n\nvoid TiXmlElement::SetDoubleAttribute( const char * name, double val )\n{\t\n\tchar buf[256];\n\t#if defined(TIXML_SNPRINTF)\t\t\n\t\tTIXML_SNPRINTF( buf, sizeof(buf), \"%f\", val );\n\t#else\n\t\tsprintf( buf, \"%f\", val );\n\t#endif\n\tSetAttribute( name, buf );\n}\n\n\nvoid TiXmlElement::SetAttribute( const char * cname, const char * cvalue )\n{\n    #ifdef TIXML_USE_STL\n\tTIXML_STRING _name( cname );\n\tTIXML_STRING _value( cvalue );\n\t#else\n\tconst char* _name = cname;\n\tconst char* _value = cvalue;\n\t#endif\n\n\tTiXmlAttribute* node = attributeSet.Find( _name );\n\tif ( node )\n\t{\n\t\tnode->SetValue( _value );\n\t\treturn;\n\t}\n\n\tTiXmlAttribute* attrib = new TiXmlAttribute( cname, cvalue );\n\tif ( attrib )\n\t{\n\t\tattributeSet.Add( attrib );\n\t}\n\telse\n\t{\n\t\tTiXmlDocument* document = GetDocument();\n\t\tif ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN );\n\t}\n}\n\n\n#ifdef TIXML_USE_STL\nvoid TiXmlElement::SetAttribute( const std::string& name, const std::string& _value )\n{\n\tTiXmlAttribute* node = attributeSet.Find( name );\n\tif ( node )\n\t{\n\t\tnode->SetValue( _value );\n\t\treturn;\n\t}\n\n\tTiXmlAttribute* attrib = new TiXmlAttribute( name, _value );\n\tif ( attrib )\n\t{\n\t\tattributeSet.Add( attrib );\n\t}\n\telse\n\t{\n\t\tTiXmlDocument* document = GetDocument();\n\t\tif ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN );\n\t}\n}\n#endif\n\n\nvoid TiXmlElement::Print( FILE* cfile, int depth ) const\n{\n\tint i;\n\tassert( cfile );\n\tfor ( i=0; i<depth; i++ ) {\n\t\tfprintf( cfile, \"    \" );\n\t}\n\n\tfprintf( cfile, \"<%s\", value.c_str() );\n\n\tconst TiXmlAttribute* attrib;\n\tfor ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() )\n\t{\n\t\tfprintf( cfile, \" \" );\n\t\tattrib->Print( cfile, depth );\n\t}\n\n\t\/\/ There are 3 different formatting approaches:\n\t\/\/ 1) An element without children is printed as a <foo \/> node\n\t\/\/ 2) An element with only a text child is printed as <foo> text <\/foo>\n\t\/\/ 3) An element with children is printed on multiple lines.\n\tTiXmlNode* node;\n\tif ( !firstChild )\n\t{\n\t\tfprintf( cfile, \" \/>\" );\n\t}\n\telse if ( firstChild == lastChild && firstChild->ToText() )\n\t{\n\t\tfprintf( cfile, \">\" );\n\t\tfirstChild->Print( cfile, depth + 1 );\n\t\tfprintf( cfile, \"<\/%s>\", value.c_str() );\n\t}\n\telse\n\t{\n\t\tfprintf( cfile, \">\" );\n\n\t\tfor ( node = firstChild; node; node=node->NextSibling() )\n\t\t{\n\t\t\tif ( !node->ToText() )\n\t\t\t{\n\t\t\t\tfprintf( cfile, \"\\n\" );\n\t\t\t}\n\t\t\tnode->Print( cfile, depth+1 );\n\t\t}\n\t\tfprintf( cfile, \"\\n\" );\n\t\tfor( i=0; i<depth; ++i ) {\n\t\t\tfprintf( cfile, \"    \" );\n\t\t}\n\t\tfprintf( cfile, \"<\/%s>\", value.c_str() );\n\t}\n}\n\n\nvoid TiXmlElement::CopyTo( TiXmlElement* target ) const\n{\n\t\/\/ superclass:\n\tTiXmlNode::CopyTo( target );\n\n\t\/\/ Element class: \n\t\/\/ Clone the attributes, then clone the children.\n\tconst TiXmlAttribute* attribute = 0;\n\tfor(\tattribute = attributeSet.First();\n\tattribute;\n\tattribute = attribute->Next() )\n\t{\n\t\ttarget->SetAttribute( attribute->Name(), attribute->Value() );\n\t}\n\n\tTiXmlNode* node = 0;\n\tfor ( node = firstChild; node; node = node->NextSibling() )\n\t{\n\t\ttarget->LinkEndChild( node->Clone() );\n\t}\n}\n\nbool TiXmlElement::Accept( TiXmlVisitor* visitor ) const\n{\n\tif ( visitor->VisitEnter( *this, attributeSet.First() ) ) \n\t{\n\t\tfor ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() )\n\t\t{\n\t\t\tif ( !node->Accept( visitor ) )\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn visitor->VisitExit( *this );\n}\n\n\nTiXmlNode* TiXmlElement::Clone() const\n{\n\tTiXmlElement* clone = new TiXmlElement( Value() );\n\tif ( !clone )\n\t\treturn 0;\n\n\tCopyTo( clone );\n\treturn clone;\n}\n\n\nconst char* TiXmlElement::GetText() const\n{\n\tconst TiXmlNode* child = this->FirstChild();\n\tif ( child ) {\n\t\tconst TiXmlText* childText = child->ToText();\n\t\tif ( childText ) {\n\t\t\treturn childText->Value();\n\t\t}\n\t}\n\treturn 0;\n}\n\n\nTiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::DOCUMENT )\n{\n\ttabsize = 4;\n\tuseMicrosoftBOM = false;\n\tClearError();\n}\n\nTiXmlDocument::TiXmlDocument( const char * documentName ) : TiXmlNode( TiXmlNode::DOCUMENT )\n{\n\ttabsize = 4;\n\tuseMicrosoftBOM = false;\n\tvalue = documentName;\n\tClearError();\n}\n\n\n#ifdef TIXML_USE_STL\nTiXmlDocument::TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::DOCUMENT )\n{\n\ttabsize = 4;\n\tuseMicrosoftBOM = false;\n    value = documentName;\n\tClearError();\n}\n#endif\n\n\nTiXmlDocument::TiXmlDocument( const TiXmlDocument& copy ) : TiXmlNode( TiXmlNode::DOCUMENT )\n{\n\tcopy.CopyTo( this );\n}\n\n\nvoid TiXmlDocument::operator=( const TiXmlDocument& copy )\n{\n\tClear();\n\tcopy.CopyTo( this );\n}\n\n\nbool TiXmlDocument::LoadFile( TiXmlEncoding encoding )\n{\n\t\/\/ See STL_STRING_BUG below.\n\t\/\/StringToBuffer buf( value );\n\n\treturn LoadFile( Value(), encoding );\n}\n\n\nbool TiXmlDocument::SaveFile() const\n{\n\t\/\/ See STL_STRING_BUG below.\n\/\/\tStringToBuffer buf( value );\n\/\/\n\/\/\tif ( buf.buffer && SaveFile( buf.buffer ) )\n\/\/\t\treturn true;\n\/\/\n\/\/\treturn false;\n\treturn SaveFile( Value() );\n}\n\nbool TiXmlDocument::LoadFile( const char* _filename, TiXmlEncoding encoding )\n{\n\t\/\/ There was a really terrifying little bug here. The code:\n\t\/\/\t\tvalue = filename\n\t\/\/ in the STL case, cause the assignment method of the std::string to\n\t\/\/ be called. What is strange, is that the std::string had the same\n\t\/\/ address as it's c_str() method, and so bad things happen. Looks\n\t\/\/ like a bug in the Microsoft STL implementation.\n\t\/\/ Add an extra string to avoid the crash.\n\tTIXML_STRING filename( _filename );\n\tvalue = filename;\n\n\t\/\/ reading in binary mode so that tinyxml can normalize the EOL\n\tFILE* file = TiXmlFOpen( value.c_str (), \"rb\" );\t\n\n\tif ( file )\n\t{\n\t\tbool result = LoadFile( file, encoding );\n\t\tfclose( file );\n\t\treturn result;\n\t}\n\telse\n\t{\n\t\tSetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );\n\t\treturn false;\n\t}\n}\n\nbool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding )\n{\n\tif ( !file ) \n\t{\n\t\tSetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );\n\t\treturn false;\n\t}\n\n\t\/\/ Delete the existing data:\n\tClear();\n\tlocation.Clear();\n\n\t\/\/ Get the file size, so we can pre-allocate the string. HUGE speed impact.\n\tlong length = 0;\n\tfseek( file, 0, SEEK_END );\n\tlength = ftell( file );\n\tfseek( file, 0, SEEK_SET );\n\n\t\/\/ Strange case, but good to handle up front.\n\tif ( length <= 0 )\n\t{\n\t\tSetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );\n\t\treturn false;\n\t}\n\n\t\/\/ If we have a file, assume it is all one big XML file, and read it in.\n\t\/\/ The document parser may decide the document ends sooner than the entire file, however.\n\tTIXML_STRING data;\n\tdata.reserve( length );\n\n\t\/\/ Subtle bug here. TinyXml did use fgets. But from the XML spec:\n\t\/\/ 2.11 End-of-Line Handling\n\t\/\/ <snip>\n\t\/\/ <quote>\n\t\/\/ ...the XML processor MUST behave as if it normalized all line breaks in external \n\t\/\/ parsed entities (including the document entity) on input, before parsing, by translating \n\t\/\/ both the two-character sequence #xD #xA and any #xD that is not followed by #xA to \n\t\/\/ a single #xA character.\n\t\/\/ <\/quote>\n\t\/\/\n\t\/\/ It is not clear fgets does that, and certainly isn't clear it works cross platform. \n\t\/\/ Generally, you expect fgets to translate from the convention of the OS to the c\/unix\n\t\/\/ convention, and not work generally.\n\n\t\/*\n\twhile( fgets( buf, sizeof(buf), file ) )\n\t{\n\t\tdata += buf;\n\t}\n\t*\/\n\n\tchar* buf = new char[ length+1 ];\n\tbuf[0] = 0;\n\n\tif ( fread( buf, length, 1, file ) != 1 ) {\n\t\tdelete [] buf;\n\t\tSetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );\n\t\treturn false;\n\t}\n\n\tconst char* lastPos = buf;\n\tconst char* p = buf;\n\n\tbuf[length] = 0;\n\twhile( *p ) {\n\t\tassert( p < (buf+length) );\n\t\tif ( *p == 0xa ) {\n\t\t\t\/\/ Newline character. No special rules for this. Append all the characters\n\t\t\t\/\/ since the last string, and include the newline.\n\t\t\tdata.append( lastPos, (p-lastPos+1) );\t\/\/ append, include the newline\n\t\t\t++p;\t\t\t\t\t\t\t\t\t\/\/ move past the newline\n\t\t\tlastPos = p;\t\t\t\t\t\t\t\/\/ and point to the new buffer (may be 0)\n\t\t\tassert( p <= (buf+length) );\n\t\t}\n\t\telse if ( *p == 0xd ) {\n\t\t\t\/\/ Carriage return. Append what we have so far, then\n\t\t\t\/\/ handle moving forward in the buffer.\n\t\t\tif ( (p-lastPos) > 0 ) {\n\t\t\t\tdata.append( lastPos, p-lastPos );\t\/\/ do not add the CR\n\t\t\t}\n\t\t\tdata += (char)0xa;\t\t\t\t\t\t\/\/ a proper newline\n\n\t\t\tif ( *(p+1) == 0xa ) {\n\t\t\t\t\/\/ Carriage return - new line sequence\n\t\t\t\tp += 2;\n\t\t\t\tlastPos = p;\n\t\t\t\tassert( p <= (buf+length) );\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/ it was followed by something else...that is presumably characters again.\n\t\t\t\t++p;\n\t\t\t\tlastPos = p;\n\t\t\t\tassert( p <= (buf+length) );\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t++p;\n\t\t}\n\t}\n\t\/\/ Handle any left over characters.\n\tif ( p-lastPos ) {\n\t\tdata.append( lastPos, p-lastPos );\n\t}\t\t\n\tdelete [] buf;\n\tbuf = 0;\n\n\tParse( data.c_str(), 0, encoding );\n\n\tif (  Error() )\n        return false;\n    else\n\t\treturn true;\n}\n\n\nbool TiXmlDocument::SaveFile( const char * filename ) const\n{\n\t\/\/ The old c stuff lives on...\n\tFILE* fp = TiXmlFOpen( filename, \"w\" );\n\tif ( fp )\n\t{\n\t\tbool result = SaveFile( fp );\n\t\tfclose( fp );\n\t\treturn result;\n\t}\n\treturn false;\n}\n\n\nbool TiXmlDocument::SaveFile( FILE* fp ) const\n{\n\tif ( useMicrosoftBOM ) \n\t{\n\t\tconst unsigned char TIXML_UTF_LEAD_0 = 0xefU;\n\t\tconst unsigned char TIXML_UTF_LEAD_1 = 0xbbU;\n\t\tconst unsigned char TIXML_UTF_LEAD_2 = 0xbfU;\n\n\t\tfputc( TIXML_UTF_LEAD_0, fp );\n\t\tfputc( TIXML_UTF_LEAD_1, fp );\n\t\tfputc( TIXML_UTF_LEAD_2, fp );\n\t}\n\tPrint( fp, 0 );\n\treturn (ferror(fp) == 0);\n}\n\n\nvoid TiXmlDocument::CopyTo( TiXmlDocument* target ) const\n{\n\tTiXmlNode::CopyTo( target );\n\n\ttarget->error = error;\n\ttarget->errorId = errorId;\n\ttarget->errorDesc = errorDesc;\n\ttarget->tabsize = tabsize;\n\ttarget->errorLocation = errorLocation;\n\ttarget->useMicrosoftBOM = useMicrosoftBOM;\n\n\tTiXmlNode* node = 0;\n\tfor ( node = firstChild; node; node = node->NextSibling() )\n\t{\n\t\ttarget->LinkEndChild( node->Clone() );\n\t}\t\n}\n\n\nTiXmlNode* TiXmlDocument::Clone() const\n{\n\tTiXmlDocument* clone = new TiXmlDocument();\n\tif ( !clone )\n\t\treturn 0;\n\n\tCopyTo( clone );\n\treturn clone;\n}\n\n\nvoid TiXmlDocument::Print( FILE* cfile, int depth ) const\n{\n\tassert( cfile );\n\tfor ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() )\n\t{\n\t\tnode->Print( cfile, depth );\n\t\tfprintf( cfile, \"\\n\" );\n\t}\n}\n\n\nbool TiXmlDocument::Accept( TiXmlVisitor* visitor ) const\n{\n\tif ( visitor->VisitEnter( *this ) )\n\t{\n\t\tfor ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() )\n\t\t{\n\t\t\tif ( !node->Accept( visitor ) )\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn visitor->VisitExit( *this );\n}\n\n\nconst TiXmlAttribute* TiXmlAttribute::Next() const\n{\n\t\/\/ We are using knowledge of the sentinel. The sentinel\n\t\/\/ have a value or name.\n\tif ( next->value.empty() && next->name.empty() )\n\t\treturn 0;\n\treturn next;\n}\n\n\/*\nTiXmlAttribute* TiXmlAttribute::Next()\n{\n\t\/\/ We are using knowledge of the sentinel. The sentinel\n\t\/\/ have a value or name.\n\tif ( next->value.empty() && next->name.empty() )\n\t\treturn 0;\n\treturn next;\n}\n*\/\n\nconst TiXmlAttribute* TiXmlAttribute::Previous() const\n{\n\t\/\/ We are using knowledge of the sentinel. The sentinel\n\t\/\/ have a value or name.\n\tif ( prev->value.empty() && prev->name.empty() )\n\t\treturn 0;\n\treturn prev;\n}\n\n\/*\nTiXmlAttribute* TiXmlAttribute::Previous()\n{\n\t\/\/ We are using knowledge of the sentinel. The sentinel\n\t\/\/ have a value or name.\n\tif ( prev->value.empty() && prev->name.empty() )\n\t\treturn 0;\n\treturn prev;\n}\n*\/\n\nvoid TiXmlAttribute::Print( FILE* cfile, int \/*depth*\/, TIXML_STRING* str ) const\n{\n\tTIXML_STRING n, v;\n\n\tEncodeString( name, &n );\n\tEncodeString( value, &v );\n\n\tif ( cfile ) {\n\t\tfprintf (cfile, \"%s=\\\"%s\\\"\", n.c_str(), v.c_str() );\n\t}\n\tif ( str ) {\n\t\t(*str) += n; (*str) += \"=\\\"\"; (*str) += v; (*str) += \"\\\"\";\n\t}\n}\n\n\nint TiXmlAttribute::QueryIntValue( int* ival ) const\n{\n\tif ( TIXML_SSCANF( value.c_str(), \"%d\", ival ) == 1 )\n\t\treturn TIXML_SUCCESS;\n\treturn TIXML_WRONG_TYPE;\n}\n\nint TiXmlAttribute::QueryDoubleValue( double* dval ) const\n{\n\tif ( TIXML_SSCANF( value.c_str(), \"%lf\", dval ) == 1 )\n\t\treturn TIXML_SUCCESS;\n\treturn TIXML_WRONG_TYPE;\n}\n\nvoid TiXmlAttribute::SetIntValue( int _value )\n{\n\tchar buf [64];\n\t#if defined(TIXML_SNPRINTF)\t\t\n\t\tTIXML_SNPRINTF(buf, sizeof(buf), \"%d\", _value);\n\t#else\n\t\tsprintf (buf, \"%d\", _value);\n\t#endif\n\tSetValue (buf);\n}\n\nvoid TiXmlAttribute::SetDoubleValue( double _value )\n{\n\tchar buf [256];\n\t#if defined(TIXML_SNPRINTF)\t\t\n\t\tTIXML_SNPRINTF( buf, sizeof(buf), \"%lf\", _value);\n\t#else\n\t\tsprintf (buf, \"%lf\", _value);\n\t#endif\n\tSetValue (buf);\n}\n\nint TiXmlAttribute::IntValue() const\n{\n\treturn atoi (value.c_str ());\n}\n\ndouble  TiXmlAttribute::DoubleValue() const\n{\n\treturn atof (value.c_str ());\n}\n\n\nTiXmlComment::TiXmlComment( const TiXmlComment& copy ) : TiXmlNode( TiXmlNode::COMMENT )\n{\n\tcopy.CopyTo( this );\n}\n\n\nvoid TiXmlComment::operator=( const TiXmlComment& base )\n{\n\tClear();\n\tbase.CopyTo( this );\n}\n\n\nvoid TiXmlComment::Print( FILE* cfile, int depth ) const\n{\n\tassert( cfile );\n\tfor ( int i=0; i<depth; i++ )\n\t{\n\t\tfprintf( cfile,  \"    \" );\n\t}\n\tfprintf( cfile, \"<!--%s-->\", value.c_str() );\n}\n\n\nvoid TiXmlComment::CopyTo( TiXmlComment* target ) const\n{\n\tTiXmlNode::CopyTo( target );\n}\n\n\nbool TiXmlComment::Accept( TiXmlVisitor* visitor ) const\n{\n\treturn visitor->Visit( *this );\n}\n\n\nTiXmlNode* TiXmlComment::Clone() const\n{\n\tTiXmlComment* clone = new TiXmlComment();\n\n\tif ( !clone )\n\t\treturn 0;\n\n\tCopyTo( clone );\n\treturn clone;\n}\n\n\nvoid TiXmlText::Print( FILE* cfile, int depth ) const\n{\n\tassert( cfile );\n\tif ( cdata )\n\t{\n\t\tint i;\n\t\tfprintf( cfile, \"\\n\" );\n\t\tfor ( i=0; i<depth; i++ ) {\n\t\t\tfprintf( cfile, \"    \" );\n\t\t}\n\t\tfprintf( cfile, \"<![CDATA[%s]]>\\n\", value.c_str() );\t\/\/ unformatted output\n\t}\n\telse\n\t{\n\t\tTIXML_STRING buffer;\n\t\tEncodeString( value, &buffer );\n\t\tfprintf( cfile, \"%s\", buffer.c_str() );\n\t}\n}\n\n\nvoid TiXmlText::CopyTo( TiXmlText* target ) const\n{\n\tTiXmlNode::CopyTo( target );\n\ttarget->cdata = cdata;\n}\n\n\nbool TiXmlText::Accept( TiXmlVisitor* visitor ) const\n{\n\treturn visitor->Visit( *this );\n}\n\n\nTiXmlNode* TiXmlText::Clone() const\n{\t\n\tTiXmlText* clone = 0;\n\tclone = new TiXmlText( \"\" );\n\n\tif ( !clone )\n\t\treturn 0;\n\n\tCopyTo( clone );\n\treturn clone;\n}\n\n\nTiXmlDeclaration::TiXmlDeclaration( const char * _version,\n\t\t\t\t\t\t\t\t\tconst char * _encoding,\n\t\t\t\t\t\t\t\t\tconst char * _standalone )\n\t: TiXmlNode( TiXmlNode::DECLARATION )\n{\n\tversion = _version;\n\tencoding = _encoding;\n\tstandalone = _standalone;\n}\n\n\n#ifdef TIXML_USE_STL\nTiXmlDeclaration::TiXmlDeclaration(\tconst std::string& _version,\n\t\t\t\t\t\t\t\t\tconst std::string& _encoding,\n\t\t\t\t\t\t\t\t\tconst std::string& _standalone )\n\t: TiXmlNode( TiXmlNode::DECLARATION )\n{\n\tversion = _version;\n\tencoding = _encoding;\n\tstandalone = _standalone;\n}\n#endif\n\n\nTiXmlDeclaration::TiXmlDeclaration( const TiXmlDeclaration& copy )\n\t: TiXmlNode( TiXmlNode::DECLARATION )\n{\n\tcopy.CopyTo( this );\t\n}\n\n\nvoid TiXmlDeclaration::operator=( const TiXmlDeclaration& copy )\n{\n\tClear();\n\tcopy.CopyTo( this );\n}\n\n\nvoid TiXmlDeclaration::Print( FILE* cfile, int \/*depth*\/, TIXML_STRING* str ) const\n{\n\tif ( cfile ) fprintf( cfile, \"<?xml \" );\n\tif ( str )\t (*str) += \"<?xml \";\n\n\tif ( !version.empty() ) {\n\t\tif ( cfile ) fprintf (cfile, \"version=\\\"%s\\\" \", version.c_str ());\n\t\tif ( str ) { (*str) += \"version=\\\"\"; (*str) += version; (*str) += \"\\\" \"; }\n\t}\n\tif ( !encoding.empty() ) {\n\t\tif ( cfile ) fprintf (cfile, \"encoding=\\\"%s\\\" \", encoding.c_str ());\n\t\tif ( str ) { (*str) += \"encoding=\\\"\"; (*str) += encoding; (*str) += \"\\\" \"; }\n\t}\n\tif ( !standalone.empty() ) {\n\t\tif ( cfile ) fprintf (cfile, \"standalone=\\\"%s\\\" \", standalone.c_str ());\n\t\tif ( str ) { (*str) += \"standalone=\\\"\"; (*str) += standalone; (*str) += \"\\\" \"; }\n\t}\n\tif ( cfile ) fprintf( cfile, \"?>\" );\n\tif ( str )\t (*str) += \"?>\";\n}\n\n\nvoid TiXmlDeclaration::CopyTo( TiXmlDeclaration* target ) const\n{\n\tTiXmlNode::CopyTo( target );\n\n\ttarget->version = version;\n\ttarget->encoding = encoding;\n\ttarget->standalone = standalone;\n}\n\n\nbool TiXmlDeclaration::Accept( TiXmlVisitor* visitor ) const\n{\n\treturn visitor->Visit( *this );\n}\n\n\nTiXmlNode* TiXmlDeclaration::Clone() const\n{\t\n\tTiXmlDeclaration* clone = new TiXmlDeclaration();\n\n\tif ( !clone )\n\t\treturn 0;\n\n\tCopyTo( clone );\n\treturn clone;\n}\n\n\nvoid TiXmlUnknown::Print( FILE* cfile, int depth ) const\n{\n\tfor ( int i=0; i<depth; i++ )\n\t\tfprintf( cfile, \"    \" );\n\tfprintf( cfile, \"<%s>\", value.c_str() );\n}\n\n\nvoid TiXmlUnknown::CopyTo( TiXmlUnknown* target ) const\n{\n\tTiXmlNode::CopyTo( target );\n}\n\n\nbool TiXmlUnknown::Accept( TiXmlVisitor* visitor ) const\n{\n\treturn visitor->Visit( *this );\n}\n\n\nTiXmlNode* TiXmlUnknown::Clone() const\n{\n\tTiXmlUnknown* clone = new TiXmlUnknown();\n\n\tif ( !clone )\n\t\treturn 0;\n\n\tCopyTo( clone );\n\treturn clone;\n}\n\n\nTiXmlAttributeSet::TiXmlAttributeSet()\n{\n\tsentinel.next = &sentinel;\n\tsentinel.prev = &sentinel;\n}\n\n\nTiXmlAttributeSet::~TiXmlAttributeSet()\n{\n\tassert( sentinel.next == &sentinel );\n\tassert( sentinel.prev == &sentinel );\n}\n\n\nvoid TiXmlAttributeSet::Add( TiXmlAttribute* addMe )\n{\n    #ifdef TIXML_USE_STL\n\tassert( !Find( TIXML_STRING( addMe->Name() ) ) );\t\/\/ Shouldn't be multiply adding to the set.\n\t#else\n\tassert( !Find( addMe->Name() ) );\t\/\/ Shouldn't be multiply adding to the set.\n\t#endif\n\n\taddMe->next = &sentinel;\n\taddMe->prev = sentinel.prev;\n\n\tsentinel.prev->next = addMe;\n\tsentinel.prev      = addMe;\n}\n\nvoid TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe )\n{\n\tTiXmlAttribute* node;\n\n\tfor( node = sentinel.next; node != &sentinel; node = node->next )\n\t{\n\t\tif ( node == removeMe )\n\t\t{\n\t\t\tnode->prev->next = node->next;\n\t\t\tnode->next->prev = node->prev;\n\t\t\tnode->next = 0;\n\t\t\tnode->prev = 0;\n\t\t\treturn;\n\t\t}\n\t}\n\tassert( 0 );\t\t\/\/ we tried to remove a non-linked attribute.\n}\n\n\n#ifdef TIXML_USE_STL\nconst TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) const\n{\n\tfor( const TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next )\n\t{\n\t\tif ( node->name == name )\n\t\t\treturn node;\n\t}\n\treturn 0;\n}\n\n\/*\nTiXmlAttribute*\tTiXmlAttributeSet::Find( const std::string& name )\n{\n\tfor( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next )\n\t{\n\t\tif ( node->name == name )\n\t\t\treturn node;\n\t}\n\treturn 0;\n}\n*\/\n#endif\n\n\nconst TiXmlAttribute* TiXmlAttributeSet::Find( const char* name ) const\n{\n\tfor( const TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next )\n\t{\n\t\tif ( strcmp( node->name.c_str(), name ) == 0 )\n\t\t\treturn node;\n\t}\n\treturn 0;\n}\n\n\/*\nTiXmlAttribute*\tTiXmlAttributeSet::Find( const char* name )\n{\n\tfor( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next )\n\t{\n\t\tif ( strcmp( node->name.c_str(), name ) == 0 )\n\t\t\treturn node;\n\t}\n\treturn 0;\n}\n*\/\n\n#ifdef TIXML_USE_STL\t\nstd::istream& operator>> (std::istream & in, TiXmlNode & base)\n{\n\tTIXML_STRING tag;\n\ttag.reserve( 8 * 1000 );\n\tbase.StreamIn( &in, &tag );\n\n\tbase.Parse( tag.c_str(), 0, TIXML_DEFAULT_ENCODING );\n\treturn in;\n}\n#endif\n\n\n#ifdef TIXML_USE_STL\t\nstd::ostream& operator<< (std::ostream & out, const TiXmlNode & base)\n{\n\tTiXmlPrinter printer;\n\tprinter.SetStreamPrinting();\n\tbase.Accept( &printer );\n\tout << printer.Str();\n\n\treturn out;\n}\n\n\nstd::string& operator<< (std::string& out, const TiXmlNode& base )\n{\n\tTiXmlPrinter printer;\n\tprinter.SetStreamPrinting();\n\tbase.Accept( &printer );\n\tout.append( printer.Str() );\n\n\treturn out;\n}\n#endif\n\n\nTiXmlHandle TiXmlHandle::FirstChild() const\n{\n\tif ( node )\n\t{\n\t\tTiXmlNode* child = node->FirstChild();\n\t\tif ( child )\n\t\t\treturn TiXmlHandle( child );\n\t}\n\treturn TiXmlHandle( 0 );\n}\n\n\nTiXmlHandle TiXmlHandle::FirstChild( const char * value ) const\n{\n\tif ( node )\n\t{\n\t\tTiXmlNode* child = node->FirstChild( value );\n\t\tif ( child )\n\t\t\treturn TiXmlHandle( child );\n\t}\n\treturn TiXmlHandle( 0 );\n}\n\n\nTiXmlHandle TiXmlHandle::FirstChildElement() const\n{\n\tif ( node )\n\t{\n\t\tTiXmlElement* child = node->FirstChildElement();\n\t\tif ( child )\n\t\t\treturn TiXmlHandle( child );\n\t}\n\treturn TiXmlHandle( 0 );\n}\n\n\nTiXmlHandle TiXmlHandle::FirstChildElement( const char * value ) const\n{\n\tif ( node )\n\t{\n\t\tTiXmlElement* child = node->FirstChildElement( value );\n\t\tif ( child )\n\t\t\treturn TiXmlHandle( child );\n\t}\n\treturn TiXmlHandle( 0 );\n}\n\n\nTiXmlHandle TiXmlHandle::Child( int count ) const\n{\n\tif ( node )\n\t{\n\t\tint i;\n\t\tTiXmlNode* child = node->FirstChild();\n\t\tfor (\ti=0;\n\t\t\t\tchild && i<count;\n\t\t\t\tchild = child->NextSibling(), ++i )\n\t\t{\n\t\t\t\/\/ nothing\n\t\t}\n\t\tif ( child )\n\t\t\treturn TiXmlHandle( child );\n\t}\n\treturn TiXmlHandle( 0 );\n}\n\n\nTiXmlHandle TiXmlHandle::Child( const char* value, int count ) const\n{\n\tif ( node )\n\t{\n\t\tint i;\n\t\tTiXmlNode* child = node->FirstChild( value );\n\t\tfor (\ti=0;\n\t\t\t\tchild && i<count;\n\t\t\t\tchild = child->NextSibling( value ), ++i )\n\t\t{\n\t\t\t\/\/ nothing\n\t\t}\n\t\tif ( child )\n\t\t\treturn TiXmlHandle( child );\n\t}\n\treturn TiXmlHandle( 0 );\n}\n\n\nTiXmlHandle TiXmlHandle::ChildElement( int count ) const\n{\n\tif ( node )\n\t{\n\t\tint i;\n\t\tTiXmlElement* child = node->FirstChildElement();\n\t\tfor (\ti=0;\n\t\t\t\tchild && i<count;\n\t\t\t\tchild = child->NextSiblingElement(), ++i )\n\t\t{\n\t\t\t\/\/ nothing\n\t\t}\n\t\tif ( child )\n\t\t\treturn TiXmlHandle( child );\n\t}\n\treturn TiXmlHandle( 0 );\n}\n\n\nTiXmlHandle TiXmlHandle::ChildElement( const char* value, int count ) const\n{\n\tif ( node )\n\t{\n\t\tint i;\n\t\tTiXmlElement* child = node->FirstChildElement( value );\n\t\tfor (\ti=0;\n\t\t\t\tchild && i<count;\n\t\t\t\tchild = child->NextSiblingElement( value ), ++i )\n\t\t{\n\t\t\t\/\/ nothing\n\t\t}\n\t\tif ( child )\n\t\t\treturn TiXmlHandle( child );\n\t}\n\treturn TiXmlHandle( 0 );\n}\n\n\nbool TiXmlPrinter::VisitEnter( const TiXmlDocument& )\n{\n\treturn true;\n}\n\nbool TiXmlPrinter::VisitExit( const TiXmlDocument& )\n{\n\treturn true;\n}\n\nbool TiXmlPrinter::VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute )\n{\n\tDoIndent();\n\tbuffer += \"<\";\n\tbuffer += element.Value();\n\n\tfor( const TiXmlAttribute* attrib = firstAttribute; attrib; attrib = attrib->Next() )\n\t{\n\t\tbuffer += \" \";\n\t\tattrib->Print( 0, 0, &buffer );\n\t}\n\n\tif ( !element.FirstChild() ) \n\t{\n\t\tbuffer += \" \/>\";\n\t\tDoLineBreak();\n\t}\n\telse \n\t{\n\t\tbuffer += \">\";\n\t\tif (    element.FirstChild()->ToText()\n\t\t\t  && element.LastChild() == element.FirstChild()\n\t\t\t  && element.FirstChild()->ToText()->CDATA() == false )\n\t\t{\n\t\t\tsimpleTextPrint = true;\n\t\t\t\/\/ no DoLineBreak()!\n\t\t}\n\t\telse\n\t\t{\n\t\t\tDoLineBreak();\n\t\t}\n\t}\n\t++depth;\t\n\treturn true;\n}\n\n\nbool TiXmlPrinter::VisitExit( const TiXmlElement& element )\n{\n\t--depth;\n\tif ( !element.FirstChild() ) \n\t{\n\t\t\/\/ nothing.\n\t}\n\telse \n\t{\n\t\tif ( simpleTextPrint )\n\t\t{\n\t\t\tsimpleTextPrint = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tDoIndent();\n\t\t}\n\t\tbuffer += \"<\/\";\n\t\tbuffer += element.Value();\n\t\tbuffer += \">\";\n\t\tDoLineBreak();\n\t}\n\treturn true;\n}\n\n\nbool TiXmlPrinter::Visit( const TiXmlText& text )\n{\n\tif ( text.CDATA() )\n\t{\n\t\tDoIndent();\n\t\tbuffer += \"<![CDATA[\";\n\t\tbuffer += text.Value();\n\t\tbuffer += \"]]>\";\n\t\tDoLineBreak();\n\t}\n\telse if ( simpleTextPrint )\n\t{\n\t\tTIXML_STRING str;\n\t\tTiXmlBase::EncodeString( text.ValueTStr(), &str );\n\t\tbuffer += str;\n\t}\n\telse\n\t{\n\t\tDoIndent();\n\t\tTIXML_STRING str;\n\t\tTiXmlBase::EncodeString( text.ValueTStr(), &str );\n\t\tbuffer += str;\n\t\tDoLineBreak();\n\t}\n\treturn true;\n}\n\n\nbool TiXmlPrinter::Visit( const TiXmlDeclaration& declaration )\n{\n\tDoIndent();\n\tdeclaration.Print( 0, 0, &buffer );\n\tDoLineBreak();\n\treturn true;\n}\n\n\nbool TiXmlPrinter::Visit( const TiXmlComment& comment )\n{\n\tDoIndent();\n\tbuffer += \"<!--\";\n\tbuffer += comment.Value();\n\tbuffer += \"-->\";\n\tDoLineBreak();\n\treturn true;\n}\n\n\nbool TiXmlPrinter::Visit( const TiXmlUnknown& unknown )\n{\n\tDoIndent();\n\tbuffer += \"<\";\n\tbuffer += unknown.Value();\n\tbuffer += \">\";\n\tDoLineBreak();\n\treturn true;\n}\n\n","avg_line_length":19.5215082315,"max_line_length":110,"alphanum_fraction":0.6462907043,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1198,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":null,"content":"#include <dlib\/python.h>\n#include \"dlib\/pixel.h\"\n#include <dlib\/image_transforms.h>\n\nusing namespace dlib;\nusing namespace std;\n\nnamespace py = pybind11;\n\n\/\/ ----------------------------------------------------------------------------------------\n\nstring print_rgb_pixel_str(const rgb_pixel& p)\n{\n    std::ostringstream sout;\n    sout << \"red: \"<< (int)p.red\n         << \", green: \"<< (int)p.green\n         << \", blue: \"<< (int)p.blue;\n    return sout.str();\n}\n\nstring print_rgb_pixel_repr(const rgb_pixel& p)\n{\n    std::ostringstream sout;\n    sout << \"rgb_pixel(\" << (int)p.red << \",\" << (int)p.green << \",\" << (int)p.blue << \")\";\n    return sout.str();\n}\n\n\/\/ ----------------------------------------------------------------------------------------\n\nvoid bind_image_classes(py::module& m)\n{\n    py::class_<rgb_pixel>(m, \"rgb_pixel\")\n        .def(py::init<unsigned char,unsigned char,unsigned char>(), py::arg(\"red\"), py::arg(\"green\"), py::arg(\"blue\"))\n        .def(\"__str__\", &print_rgb_pixel_str)\n        .def(\"__repr__\", &print_rgb_pixel_repr)\n        .def_readwrite(\"red\", &rgb_pixel::red)\n        .def_readwrite(\"green\", &rgb_pixel::green)\n        .def_readwrite(\"blue\", &rgb_pixel::blue);\n}\n","avg_line_length":29.95,"max_line_length":118,"alphanum_fraction":0.5183639399,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2370,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":28.0,"content":"\/\/\n\/\/ Created by Pedro Tacla Yamada on 27\/4\/21.\n\/\/\n\n#include <boost\/filesystem.hpp>\n#include <catch2\/catch.hpp>\n#include <fmt\/format.h>\n#include <lfilesaver\/models\/FileEntry.h>\n#include <lfilesaver\/services\/settings\/SettingsService.h>\n#include <lfilesaver\/services\/storage\/LevelDbFactory.h>\n#include <unordered_set>\n\nTEST_CASE (\"LevelDbFactory - can return DB paths in the settings path\")\n{\n    using namespace filesaver;\n    using namespace filesaver::services;\n    using namespace filesaver::services::settings;\n\n    boost::filesystem::remove_all (\"\/tmp\/filesaver-settings\");\n    boost::filesystem::create_directories (\"\/tmp\/filesaver-settings\");\n    SettingsService settingsService{\"\/tmp\/filesaver-settings\/settings.yml\"};\n    LevelDbFactory factory{&settingsService};\n\n    leveldb::Options options;\n    options.create_if_missing = true;\n\n    std::string databaseTag = \"test-db-1234\";\n    leveldb::DB* databasePtr = nullptr;\n    auto dbPath = factory.getPathForTag (databaseTag);\n    REQUIRE (dbPath == \"\/tmp\/filesaver-settings\/test-db-1234.db\");\n    auto status = factory.openDatabase (options, databaseTag, &databasePtr);\n\n    INFO (fmt::format (\"DB open: {}\", status.ToString ()));\n    REQUIRE (status.ok ());\n    REQUIRE (databasePtr != nullptr);\n    databasePtr->Put ({}, \"test-key\", \"test-value\");\n    std::string value;\n    status = databasePtr->Get ({}, \"test-key\", &value);\n\n    INFO (fmt::format (\"DB get: {}\", status.ToString ()));\n    REQUIRE (status.ok ());\n    REQUIRE (value == \"test-value\");\n\n    auto fileEntry = FileEntry::fromPath (\"\/tmp\/filesaver-settings\/\");\n    const auto& childrenVector = fileEntry->children ();\n    REQUIRE (childrenVector.size () == 1);\n    std::vector<std::string> childrenVectorStrs{childrenVector.size ()};\n    std::transform (childrenVector.begin (),\n                    childrenVector.end (),\n                    childrenVectorStrs.begin (),\n                    [] (boost::filesystem::path path) -> std::string { return path.filename ().string (); });\n    std::unordered_set<std::string> children{childrenVectorStrs.begin (), childrenVectorStrs.end ()};\n\n    for (auto c : childrenVectorStrs)\n    {\n        INFO (fmt::format (\"Child directory {}\", c));\n    }\n\n    REQUIRE (children.find (\"test-db-1234.db\") != children.end ());\n\n    INFO (\"Cleaning-up\")\n    boost::filesystem::remove_all (\"\/tmp\/filesaver-settings\");\n}\n","avg_line_length":37.03125,"max_line_length":109,"alphanum_fraction":0.6683544304,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4498,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The OpenAirInterface Software Alliance licenses this file to You under\n * the OAI Public License, Version 1.1  (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the\n * License at\n *\n *      http:\/\/www.openairinterface.org\/?page_id=698\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *-------------------------------------------------------------------------------\n * For more information about the OpenAirInterface (OAI) Software Alliance:\n *      contact@openairinterface.org\n *\/\n\/**\n * Nudm_UECM\n * Nudm Context Management Service. \ufffd 2020, 3GPP Organizational Partners (ARIB,\n * ATIS, CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved.\n *\n * The version of the OpenAPI document: 1.1.2\n *\n *\n * NOTE: This class is auto generated by OpenAPI Generator\n * (https:\/\/openapi-generator.tech). https:\/\/openapi-generator.tech Do not edit\n * the class manually.\n *\/\n\n#include \"ParameterUpdateInTheAMFRegistrationForNon3GPPAccessApi.h\"\n\n#include \"Helpers.h\"\n#include \"udm_config.hpp\"\n\nextern oai::udm::config::udm_config udm_cfg;\n\nnamespace oai::udm::api {\n\nusing namespace oai::udm::helpers;\nusing namespace oai::udm::model;\nusing namespace oai::udm::config;\n\nParameterUpdateInTheAMFRegistrationForNon3GPPAccessApi::\n    ParameterUpdateInTheAMFRegistrationForNon3GPPAccessApi(\n        std::shared_ptr<Pistache::Rest::Router> rtr) {\n  router = rtr;\n}\n\nvoid ParameterUpdateInTheAMFRegistrationForNon3GPPAccessApi::init() {\n  setupRoutes();\n}\n\nvoid ParameterUpdateInTheAMFRegistrationForNon3GPPAccessApi::setupRoutes() {\n  using namespace Pistache::Rest;\n\n  Routes::Patch(\n      *router,\n      base + udm_cfg.sbi.api_version +\n          \"\/:ueId\/registrations\/amf-non-3gpp-access\",\n      Routes::bind(\n          &ParameterUpdateInTheAMFRegistrationForNon3GPPAccessApi::\n              update_non3_gpp_registration_handler,\n          this));\n\n  \/\/ Default handler, called when a route is not found\n  router->addCustomHandler(Routes::bind(\n      &ParameterUpdateInTheAMFRegistrationForNon3GPPAccessApi::\n          parameter_update_in_the_amf_registration_for_non3_gpp_access_api_default_handler,\n      this));\n}\n\nvoid ParameterUpdateInTheAMFRegistrationForNon3GPPAccessApi::\n    update_non3_gpp_registration_handler(\n        const Pistache::Rest::Request& request,\n        Pistache::Http::ResponseWriter response) {\n  \/\/ Getting the path params\n  auto ueId = request.param(\":ueId\").as<std::string>();\n\n  \/\/ Getting the body param\n\n  AmfNon3GppAccessRegistrationModification\n      amfNon3GppAccessRegistrationModification;\n\n  \/\/ Getting the query params\n  auto supportedFeaturesQuery = request.query().get(\"supported-features\");\n  Pistache::Optional<std::string> supportedFeatures;\n  if (!supportedFeaturesQuery.isEmpty()) {\n    std::string valueQuery_instance;\n    if (fromStringValue(supportedFeaturesQuery.get(), valueQuery_instance)) {\n      supportedFeatures = Pistache::Some(valueQuery_instance);\n    }\n  }\n\n  try {\n    nlohmann::json::parse(request.body())\n        .get_to(amfNon3GppAccessRegistrationModification);\n    this->update_non3_gpp_registration(\n        ueId, amfNon3GppAccessRegistrationModification, supportedFeatures,\n        response);\n  } catch (nlohmann::detail::exception& e) {\n    \/\/ send a 400 error\n    response.send(Pistache::Http::Code::Bad_Request, e.what());\n    return;\n  } catch (Pistache::Http::HttpError& e) {\n    response.send(static_cast<Pistache::Http::Code>(e.code()), e.what());\n    return;\n  } catch (std::exception& e) {\n    \/\/ send a 500 error\n    response.send(Pistache::Http::Code::Internal_Server_Error, e.what());\n    return;\n  }\n}\n\nvoid ParameterUpdateInTheAMFRegistrationForNon3GPPAccessApi::\n    parameter_update_in_the_amf_registration_for_non3_gpp_access_api_default_handler(\n        const Pistache::Rest::Request&,\n        Pistache::Http::ResponseWriter response) {\n  response.send(\n      Pistache::Http::Code::Not_Found, \"The requested method does not exist\");\n}\n\n}  \/\/ namespace oai::udm::api\n","avg_line_length":35.4173228346,"max_line_length":91,"alphanum_fraction":0.725655847,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8774,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\n#include \"Astronaut.h\"\n\nusing namespace std;\n\nAstronaut::Astronaut() : Person('A')\n{\n  amount_moonstones = 0;\n  amount_oxygen = 20;\n  there = false; \/\/ see explanation in update() under state 'l'\n  depot = NULL;\n  home = NULL;\n  cout << \"Astronaut default constructed.\" << endl;\n}\n\nAstronaut::Astronaut(int in_id, Cart_Point in_loc) : Person(in_loc, in_id, 'A')\n{\n  amount_moonstones = 0;\n  amount_oxygen = 20;\n  there = false; \/\/ see explanation in update() under state 'l'\n  depot = NULL;\n  home = NULL;\n  cout << \"Astronaut constructed.\" << endl;\n}\n\nAstronaut::~Astronaut()\n{\n  cout << \"Astronaut destructed.\" << endl;\n}\n\nbool Astronaut::update()\n{\n  bool arrive; \/\/ checks if object has arrived at location\n  double extract; \/\/ amount extracted and received by astronaut\n  if (state == 'x')\n  {\n    return false;\n  }\n  else\n  {\n    if (health < 3)\n    {\n      display_code = tolower(display_code);\n    }\n    switch (state)\n    {\n      case 's':\n      {\n        return false; \/\/ Nothing changes, nothing arrives, so return false\n        break;\n      }\n      case 'm':\n      {\n        arrive = Person::update_location(); \/\/ updates location of moving astronaut and advances one step\n        if (arrive) \/\/ once it arrives, the state changes to stopped\n        {\n          state = 's';\n          return true;\n        }\n        else\n        {\n          amount_oxygen--; \/\/ if it hasn't arrived yet, oxygen decreases\n          if (amount_oxygen <= 0) \/\/ if the astronaut runs out of oxygen, it is locked\n          {\n            state = 'x';\n            cout << \"I'm out of oxygen. I'm dying!\" << endl;\n            return true;\n          }\n          else\n          {\n            amount_moonstones++; \/\/ otherwise, moonstones increments\n          }\n          return false;\n        }\n        break;\n      }\n      case 'o':\n      {\n        arrive = Person::update_location(); \/\/ updates astronaut's progress towards oxygen depot\n        if (arrive)\n        {\n          state = 'g';\n          return true;\n        }\n        else\n        {\n          amount_oxygen--;\n\n          if (amount_oxygen <= 0)\n          {\n            state = 'x';\n            cout << \"I'm out of oxygen. I'm dying!\" << endl;\n            return true;\n          }\n          else\n          {\n            amount_moonstones++;\n          }\n          return false;\n        }\n        break;\n      }\n      case 'g':\n      {\n        extract = depot -> extract_oxygen();\n        amount_oxygen += extract;\n        cout << display_code << id_num << \": Got \" << extract << \" more oxygen.\" << endl;\n        state = 's';\n        return true;\n        break;\n      }\n      case 'i':\n      {\n        arrive = Person::update_location();\n        if (arrive)\n        {\n          state = 'd';\n          return true;\n        }\n        else\n        {\n          amount_oxygen--;\n          if (amount_oxygen <= 0)\n          {\n            state = 'x';\n            cout << \"I'm out of oxygen. I'm dying!\" << endl;\n            return true;\n          }\n          else\n          {\n            amount_moonstones++;\n          }\n          return false;\n        }\n        break;\n      }\n      case 'd':\n      {\n        cout << display_code << id_num << \": Deposit \" << amount_moonstones << \" moon stones.\" << endl;\n        home -> deposit_moonstones(amount_moonstones);\n        amount_moonstones = 0;\n        state = 's';\n        return true;\n        break;\n      }\n      case 'a': \/\/ EXTRA CREDIT: Astronauts now attack aliens too\n      {\n        Cart_Point AstroLoc = get_location();\n        Cart_Point AlienLoc = target -> get_location();\n        double dist = cart_distance(AlienLoc, AstroLoc);\n        if (dist > range)\n        {\n          cout << display_code << id_num << \": Target is out of range\" << endl;\n          cout << display_code << id_num << \": Chaaaaarge.\" << endl;\n          state = 's';\n          return true;\n        }\n        else\n        {\n          if (target -> is_alive())\n          {\n            cout << display_code << id_num << \": Take that!\" << endl;\n            target -> take_hit(attack_strength);\n            return false;\n          }\n          else\n          {\n            cout << display_code << id_num << \": I win.\" << endl;\n            state = 's';\n            return true;\n          }\n        }\n      }\n      case 'l':\n      {\n        if (amount_oxygen <= 0)\n        {\n          return false; \/\/ if it is out of oxygen, nothing happens\n        }\n        else\n        {\n          Cart_Point dest = home -> get_location();\n          arrive = Person::update_location();\n\n          \/\/ Initial idea was to check if astronaut's location was already at destination of Space station, and if so, there's no need to update location or add astronauts because the astronaut would've already done so when it first arrived. However, this idea fails if the astronaut is already at the station (say, just having finished depositing moonstones), and THEN the lock command is called. This changes the state to 'l', and the destination and space station's location are the same. There is no way to differentiate between an astronaut that has just \"arrived\" at a space station ready to lock in or one tht has been locked in at that station for several turns. Both cases have a state of 'l' and the same location, and update_location() returns true for both as well. So, the additional member \"there\" provides the difference we need to differentiate between treatment of the first \"arrival\" versus just being at the station.\n\n          \/\/ It is initially set to false because the astronaut is NOT there (at the station) and is not locked in. Once the astronaut locks in, this bool is set to true, so the following calls to update will not add more astronauts even though there is only one waiting and locked in.\n\n          if (arrive && !there)\n          {\n            home -> add_astronaut(); \/\/ if astronaut has arrived, the astronaut is locked in to the space station\n            there = true;\n            return true;\n          }\n          else\n          {\n            return false;\n          }\n        }\n        break;\n      }\n      default:\n      {\n        return false;\n      }\n    }\n  }\n}\n\nvoid Astronaut::start_supplying(Oxygen_Depot* inputDepot)\n{\n  if (state == 'x')\n  {\n    cout << \"I can't move, I'm dead.\" << endl;\n  }\n  else\n  {\n    depot = inputDepot; \/\/ assigns pointer\n    Person::setup_destination(inputDepot -> get_location());\n    state = 'o';\n    cout << \"Astronaut \" << get_id() << \" supplying from Oxygen Depot \" << inputDepot -> get_id() << endl;\n    cout << display_code << get_id() << \": Yes, my lord.\" << endl;\n  }\n}\n\nvoid Astronaut::start_depositing(Space_Station* inputStation)\n{\n  if (state == 'x')\n  {\n    cout << \"I can't move, I'm dead.\" << endl;\n  }\n  else\n  {\n    home = inputStation; \/\/ assigns pointer\n    Person::setup_destination(inputStation -> get_location());\n    state = 'i';\n    cout << \"Astronaut \" << get_id() << \" depositing to Space Station \" << inputStation -> get_id() << endl;\n    cout << display_code << get_id() << \": Yes, my lord.\" << endl;\n  }\n}\n\nvoid Astronaut::go_to_station(Space_Station* inputStation)\n{\n  if (state == 'x')\n  {\n    cout << \"I can't move, I'm dead.\" << endl;\n  }\n  else\n  {\n    home = inputStation; \/\/ assigns pointer\n    state = 'l';\n    Person::setup_destination(inputStation -> get_location());\n    cout << \"Astronaut \" << get_id() << \" locking in at Space Station \" << inputStation -> get_id() << endl;\n  }\n}\n\nvoid Astronaut::show_status()\n{\n  cout << \"Astronaut status: \";\n  Person::show_status(); \/\/ calls Person show_status to call Game_Object show_status() and to print person info like destination, delta and speed if necessary\n  switch (state)\n  {\n    case 's':\n    {\n      cout << \" stopped with \" << amount_oxygen << \" oxygen and \" << amount_moonstones << \" moon stones.\" << endl;\n      break;\n    }\n    case 'm':\n    {\n      cout << endl; \/\/ all info is printed by Person show_status()\n      break;\n    }\n    case 'o':\n    {\n      cout << \" is outbound to a Depot with \" << amount_oxygen << \" oxygen and \" << amount_moonstones << \" moon stones.\" << endl;\n      break;\n    }\n    case 'g':\n    {\n      cout << \" is getting oxygen from the depot\" << endl;\n      break;\n    }\n    case 'i':\n    {\n      cout << \" is inbound to home with load: \" << amount_moonstones << \" moon stones and \" << amount_oxygen << \" oxygen\" << endl;\n      break;\n    }\n    case 'd':\n    {\n      cout << \" depositing \" << amount_moonstones << \" moon stones\" << endl;\n      break;\n    }\n    case 'l':\n    {\n      cout << \" is locked at Space Station.\" << endl;\n      break;\n    }\n    case 'a': \/\/ EXTRA CREDIT\n    {\n      cout << \" attacking alien X\" << target -> get_id();\n    }\n    case 'x':\n    {\n      cout << endl;\n      break;\n    }\n  }\n}\n","avg_line_length":28.3948220065,"max_line_length":935,"alphanum_fraction":0.5429678596,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1076,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"Compass.hpp\"\n\natomic<int> compass_degree;\n\nRTIMUBNO055 *compass;\nRTIMUSettings settings;\nRTFusionRTQF *fusion;\nRTIMU_DATA data;\n\natomic<int> compass_zero;\natomic<bool> ext_compass_reset;\n\nint error_codes;\nint degree;\n\nvoid init_compass() {\n    thread compass_thread(update_compass);\n    compass_thread.detach();\n}\n\nvoid compass_reset() {\n\tcompass = (RTIMUBNO055 *)RTIMU::createIMU(&settings);\n\n\tif ((error_codes = compass->IMUInit()) < 0) {\n\t\tcout << FAIL_MSG << endl;\n\t} else {\n\t\tcout << BNO055 << SUCCESS_MSG << endl;\n\t}\n\n\tcompass->setSlerpPower(0.02);\n    compass->setGyroEnable(true);\n    compass->setAccelEnable(true);\n    compass->setCompassEnable(true);\n}\n\nvoid update_compass() {\n\n\tcompass_reset();\n\n\tcompass_zero.store(0);\n\text_compass_reset.store(0);\n\n\twhile (true) {\n\t\tif(ext_compass_reset.load()){\n\t\t\tcompass_reset();\n\t\t\text_compass_reset.store(0);\n\t\t}\n\t\tcompass->IMURead();\n\t\tRTIMU_DATA imuData = compass->getIMUData();\n\t\tdegree = (imuData.fusionPose.z() * RTMATH_RAD_TO_DEGREE);\n\n\t\tcompass_degree.store((degree-compass_zero.load()+360) % 360);\n\t}\n}\n\n\n\n","avg_line_length":18.5517241379,"max_line_length":63,"alphanum_fraction":0.7063197026,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":220,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <cstdint>\n#include <chrono>\n#include <sstream>\n#include <bitset>\n#include \"zpack.h\"\n\nint main(int argc, char **argv) {\n    ZPack zp;\n    std::cout << \"ZPack version \" << zp.version << std::endl;\n\n    return 0;\n}","avg_line_length":18.3333333333,"max_line_length":61,"alphanum_fraction":0.6272727273,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6507,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/*\n * Copyright (c) 2021 Huawei Device Co., Ltd.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"runtime\/dyn_class_linker_extension.h\"\n#include \"runtime\/include\/class_linker-inl.h\"\n#include \"runtime\/include\/class_linker.h\"\n#include \"runtime\/include\/coretypes\/array.h\"\n#include \"runtime\/include\/coretypes\/class.h\"\n#include \"runtime\/include\/coretypes\/dyn_objects.h\"\n#include \"runtime\/include\/coretypes\/native_pointer.h\"\n#include \"runtime\/include\/panda_vm.h\"\n\nnamespace panda {\nusing Array = coretypes::Array;\nusing NativePointer = coretypes::NativePointer;\n\nusing Type = panda_file::Type;\nusing SourceLang = panda_file::SourceLang;\n\nDynamicClassLinkerExtension::~DynamicClassLinkerExtension()\n{\n    if (!IsInitialized()) {\n        return;\n    }\n\n    FreeLoadedClasses();\n}\n\nbool DynamicClassLinkerExtension::InitializeImpl([[maybe_unused]] bool cmpStrEnabled)\n{\n    LanguageContext ctx = Runtime::GetCurrent()->GetLanguageContext(GetLanguage());\n\n    auto *classClass = CreateClass(ctx.GetClassClassDescriptor(), GetClassVTableSize(ClassRoot::CLASS),\n                                   GetClassIMTSize(ClassRoot::CLASS), GetClassSize(ClassRoot::CLASS));\n    coretypes::Class::FromRuntimeClass(classClass)->SetClass(classClass);\n    classClass->SetSourceLang(SourceLang::ECMASCRIPT);\n    classClass->SetState(Class::State::LOADED);\n    classClass->SetLoadContext(GetBootContext());\n    GetClassLinker()->AddClassRoot(ClassRoot::CLASS, classClass);\n\n    auto *objClass = CreateClass(ctx.GetObjectClassDescriptor(), GetClassVTableSize(ClassRoot::OBJECT),\n                                 GetClassIMTSize(ClassRoot::OBJECT), GetClassSize(ClassRoot::OBJECT));\n    objClass->SetObjectSize(ObjectHeader::ObjectHeaderSize());\n    objClass->SetSourceLang(SourceLang::ECMASCRIPT);\n    classClass->SetBase(objClass);\n    objClass->SetState(Class::State::LOADED);\n    objClass->SetLoadContext(GetBootContext());\n    GetClassLinker()->AddClassRoot(ClassRoot::OBJECT, objClass);\n    return true;\n}\n\nvoid DynamicClassLinkerExtension::InitializeArrayClass(Class *arrayClass, Class *componentClass)\n{\n    ASSERT(IsInitialized());\n\n    auto *objectClass = GetClassRoot(ClassRoot::OBJECT);\n    arrayClass->SetBase(objectClass);\n    arrayClass->SetComponentType(componentClass);\n    uint32_t access_flags = componentClass->GetAccessFlags() & ACC_FILE_MASK;\n    access_flags &= ~ACC_INTERFACE;\n    access_flags |= ACC_FINAL | ACC_ABSTRACT;\n    arrayClass->SetAccessFlags(access_flags);\n    arrayClass->SetState(Class::State::INITIALIZED);\n}\n\nvoid DynamicClassLinkerExtension::InitializePrimitiveClass(Class *primitiveClass)\n{\n    ASSERT(IsInitialized());\n\n    primitiveClass->SetAccessFlags(ACC_PUBLIC | ACC_FINAL | ACC_ABSTRACT);\n    primitiveClass->SetState(Class::State::INITIALIZED);\n}\n\nsize_t DynamicClassLinkerExtension::GetClassVTableSize([[maybe_unused]] ClassRoot root)\n{\n    ASSERT(IsInitialized());\n    return 0;\n}\n\nsize_t DynamicClassLinkerExtension::GetClassIMTSize([[maybe_unused]] ClassRoot root)\n{\n    ASSERT(IsInitialized());\n    return 0;\n}\n\nsize_t DynamicClassLinkerExtension::GetClassSize(ClassRoot root)\n{\n    ASSERT(IsInitialized());\n\n    switch (root) {\n        case ClassRoot::U1:\n        case ClassRoot::I8:\n        case ClassRoot::U8:\n        case ClassRoot::I16:\n        case ClassRoot::U16:\n        case ClassRoot::I32:\n        case ClassRoot::U32:\n        case ClassRoot::I64:\n        case ClassRoot::U64:\n        case ClassRoot::F32:\n        case ClassRoot::F64:\n        case ClassRoot::TAGGED:\n            return ClassHelper::ComputeClassSize(GetClassVTableSize(root), GetClassIMTSize(root), 0, 0, 0, 0, 0, 0);\n        case ClassRoot::ARRAY_U1:\n        case ClassRoot::ARRAY_I8:\n        case ClassRoot::ARRAY_U8:\n        case ClassRoot::ARRAY_I16:\n        case ClassRoot::ARRAY_U16:\n        case ClassRoot::ARRAY_I32:\n        case ClassRoot::ARRAY_U32:\n        case ClassRoot::ARRAY_I64:\n        case ClassRoot::ARRAY_U64:\n        case ClassRoot::ARRAY_F32:\n        case ClassRoot::ARRAY_F64:\n        case ClassRoot::ARRAY_TAGGED:\n        case ClassRoot::ARRAY_CLASS:\n        case ClassRoot::ARRAY_STRING:\n            return GetArrayClassSize();\n        case ClassRoot::OBJECT:\n        case ClassRoot::CLASS:\n        case ClassRoot::STRING:\n            return ClassHelper::ComputeClassSize(GetClassVTableSize(root), GetClassIMTSize(root), 0, 0, 0, 0, 0, 0);\n        default: {\n            UNREACHABLE();\n            break;\n        }\n    }\n\n    return 0;\n}\n\nsize_t DynamicClassLinkerExtension::GetArrayClassVTableSize()\n{\n    ASSERT(IsInitialized());\n\n    return GetClassVTableSize(ClassRoot::OBJECT);\n}\n\nsize_t DynamicClassLinkerExtension::GetArrayClassSize()\n{\n    ASSERT(IsInitialized());\n\n    return GetClassSize(ClassRoot::OBJECT);\n}\n\nClass *DynamicClassLinkerExtension::CreateClass(const uint8_t *descriptor, size_t vtableSize, size_t imt_size,\n                                                size_t size)\n{\n    ASSERT(IsInitialized());\n\n    auto vm = Thread::GetCurrent()->GetVM();\n    auto *heap_manager = vm->GetHeapManager();\n    auto object_header =\n        heap_manager->AllocateNonMovableObject(GetClassRoot(ClassRoot::CLASS), coretypes::Class::GetSize(size));\n    \/\/ CODECHECK-NOLINTNEXTLINE(CPP_RULE_ID_SMARTPOINTER_INSTEADOF_ORIGINPOINTER)\n    auto *res = reinterpret_cast<coretypes::Class *>(object_header);\n    res->InitClass(descriptor, vtableSize, imt_size, size);\n    auto *klass = res->GetRuntimeClass();\n    klass->SetManagedObject(res);\n    klass->SetSourceLang(GetLanguage());\n    return klass;\n}\n\nvoid DynamicClassLinkerExtension::FreeClass(Class *klass)\n{\n    ASSERT(IsInitialized());\n\n    auto *cls = coretypes::Class::FromRuntimeClass(klass);\n    auto allocator = GetClassLinker()->GetAllocator();\n    allocator->Free(cls);\n}\n\nvoid DynamicClassLinkerExtension::ErrorHandler::OnError([[maybe_unused]] ClassLinker::Error error,\n                                                        [[maybe_unused]] const PandaString &message)\n{\n}\n}  \/\/ namespace panda\n","avg_line_length":34.2473684211,"max_line_length":116,"alphanum_fraction":0.7037037037,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":14244,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":7.0,"content":"#include <iostream>\n#include <string>\n#include <vector> \n#include <chrono>\n#include <cmath>\n#include <fstream>\n\n#include <..\/arena\/arena.hpp>\n#include <..\/robot\/robot_astar.hpp>\n#include <..\/robot\/robot_dj.hpp>\n#include <..\/robot\/robot_pqdj.hpp>\n\nusing namespace std;\n\nconst int ALPHA = 10;\nconst string TEST_PATH_PREFIX = \"tests\/grids\/moving_ai\/game_dragon_age_origins\/alpha10\/\";\nconst string application = \"game_dragon_age_origins\/\";\nconst string SCENE_PATH_PREFIX = \"datasets\/grids\/moving_ai\/game_dragon_age_origins\/benchmark-probems\/\";\n\nconst string scene_list[] = {  \n    \"arena2.map.scen\",\n    \"arena.map.scen\",\n    \"brc000d.map.scen\",\n    \"brc100d.map.scen\",\n    \"brc101d.map.scen\",\n    \"brc200d.map.scen\",\n    \"brc201d.map.scen\",\n    \"brc202d.map.scen\",\n    \"brc203d.map.scen\",\n    \"brc204d.map.scen\",\n    \"brc300d.map.scen\",\n    \"brc501d.map.scen\",\n    \"brc502d.map.scen\",\n    \"brc503d.map.scen\",\n    \"brc504d.map.scen\",\n    \"brc505d.map.scen\",\n    \"brc997d.map.scen\",\n    \"brc999d.map.scen\",\n    \"combat2.map.scen\",\n    \"combat.map.scen\",\n    \"den000d.map.scen\",\n    \"den001d.map.scen\",\n    \"den005d.map.scen\",\n    \"den009d.map.scen\",\n    \"den011d.map.scen\",\n    \"den012d.map.scen\",\n    \"den020d.map.scen\",\n    \"den101d.map.scen\",\n    \"den200d.map.scen\",\n    \"den200n.map.scen\",\n    \"den201d.map.scen\",\n    \"den202d.map.scen\",\n    \"den203d.map.scen\",\n    \"den204d.map.scen\",\n    \"den206d.map.scen\",\n    \"den207d.map.scen\",\n    \"den308d.map.scen\",\n    \"den312d.map.scen\",\n    \"den400d.map.scen\",\n    \"den401d.map.scen\",\n    \"den403d.map.scen\",\n    \"den404d.map.scen\",\n    \"den405d.map.scen\",\n    \"den407d.map.scen\",\n    \"den408d.map.scen\",\n    \"den500d.map.scen\",\n    \"den501d.map.scen\",\n    \"den502d.map.scen\",\n    \"den504d.map.scen\",\n    \"den505d.map.scen\",\n    \"den510d.map.scen\",\n    \"den520d.map.scen\",\n    \"den600d.map.scen\",\n    \"den601d.map.scen\",\n    \"den602d.map.scen\",\n    \"den900d.map.scen\",\n    \"den901d.map.scen\",\n    \"den998d.map.scen\",\n    \"hrt000d.map.scen\",\n    \"hrt001d.map.scen\",\n    \"hrt002d.map.scen\",\n    \"hrt201d.map.scen\",\n    \"hrt201n.map.scen\",\n    \"isound1.map.scen\",\n    \"lak100c.map.scen\",\n    \"lak100d.map.scen\",\n    \"lak100n.map.scen\",\n    \"lak101d.map.scen\",\n    \"lak102d.map.scen\",\n    \"lak103d.map.scen\",\n    \"lak104d.map.scen\",\n    \"lak105d.map.scen\",\n    \"lak106d.map.scen\",\n    \"lak107d.map.scen\",\n    \"lak108d.map.scen\",\n    \"lak109d.map.scen\",\n    \"lak110d.map.scen\",\n    \"lak200d.map.scen\",\n    \"lak201d.map.scen\",\n    \"lak202d.map.scen\",\n    \"lak203d.map.scen\",\n    \"lak250d.map.scen\",\n    \"lak300d.map.scen\",\n    \"lak302d.map.scen\",\n    \"lak303d.map.scen\",\n    \"lak304d.map.scen\",\n    \"lak307d.map.scen\",\n    \"lak308d.map.scen\",\n    \"lak400d.map.scen\",\n    \"lak401d.map.scen\",\n    \"lak403d.map.scen\",\n    \"lak404d.map.scen\",\n    \"lak405d.map.scen\",\n    \"lak503d.map.scen\",\n    \"lak504d.map.scen\",\n    \"lak505d.map.scen\",\n    \"lak506d.map.scen\",\n    \"lak507d.map.scen\",\n    \"lak510d.map.scen\",\n    \"lak511d.map.scen\",\n    \"lak512d.map.scen\",\n    \"lak513d.map.scen\",\n    \"lak514d.map.scen\",\n    \"lak515d.map.scen\",\n    \"lak519d.map.scen\",\n    \"lak526d.map.scen\",\n    \"lgt101d.map.scen\",\n    \"lgt300d.map.scen\",\n    \"lgt600d.map.scen\",\n    \"lgt601d.map.scen\",\n    \"lgt602d.map.scen\",\n    \"lgt603d.map.scen\",\n    \"lgt604d.map.scen\",\n    \"lgt605d.map.scen\",\n    \"orz000d.map.scen\",\n    \"orz100d.map.scen\",\n    \"orz101d.map.scen\",\n    \"orz102d.map.scen\",\n    \"orz103d.map.scen\",\n    \"orz105d.map.scen\",\n    \"orz106d.map.scen\",\n    \"orz107d.map.scen\",\n    \"orz200d.map.scen\",\n    \"orz201d.map.scen\",\n    \"orz203d.map.scen\",\n    \"orz300d.map.scen\",\n    \"orz301d.map.scen\",\n    \"orz302d.map.scen\",\n    \"orz303d.map.scen\",\n    \"orz304d.map.scen\",\n    \"orz500d.map.scen\",\n    \"orz601d.map.scen\",\n    \"orz700d.map.scen\",\n    \"orz701d.map.scen\",\n    \"orz702d.map.scen\",\n    \"orz703d.map.scen\",\n    \"orz704d.map.scen\",\n    \"orz800d.map.scen\",\n    \"orz900d.map.scen\",\n    \"orz901d.map.scen\",\n    \"orz999d.map.scen\",\n    \"ost000a.map.scen\",\n    \"ost000t.map.scen\",\n    \"ost001d.map.scen\",\n    \"ost002d.map.scen\",\n    \"ost003d.map.scen\",\n    \"ost004d.map.scen\",\n    \"ost100d.map.scen\",\n    \"ost101d.map.scen\",\n    \"ost102d.map.scen\",\n    \"oth000d.map.scen\",\n    \"oth001d.map.scen\",\n    \"oth999d.map.scen\",\n    \"rmtst01.map.scen\",\n    \"rmtst03.map.scen\",\n    \"rmtst.map.scen\"\n};\nconst int scene_list_count = sizeof(scene_list) \/ sizeof(scene_list[0]);\n\nint get_scene_tests_count(string scenepath) {\n    ifstream scenefile(scenepath);\n    string line;\n    int tests = 0;\n\n    \/\/ skip version line\n    getline(scenefile, line);\n\n    \/\/ count tests\n    while(getline(scenefile, line)) tests++;\n\n    return tests;\n}\n\nvoid solve_map_astar(string scenepath, string root, string map_name, ofstream &output_file) {\n    int test_count = get_scene_tests_count(scenepath);\n\n    for(int test_index=0; test_index<test_count; test_index++) {\n        arena env = arena(scenepath, root, test_index, ARENA_MOVING_AI);\n        robot_astar bot = robot_astar(env);\n\n        int path_length;\n        vector<cell> path;\n        \n        bot.set_pos(env.start);\n        auto start_time = chrono::steady_clock::now();\n        path = bot.move(env.destination);\n        auto end_time = chrono::steady_clock::now();\n        auto diff_time = end_time - start_time;\n        path_length = path.size();\n\n        output_file << env.bucket << \", \" << map_name << \", \" << path_length << \", \" << chrono::duration <double, milli> (diff_time).count() << '\\n';\n        cout << \"a_star: \" << (test_index+1) <<\"\/\" << test_count << \" \" << env.bucket << \", \" << map_name << \", \" << path_length << \", \" << chrono::duration <double, milli> (diff_time).count() << '\\n';\n        \n        env.clear();\n    }\n}\n\nvoid solve_map_astar_segmented(string scenepath, string root, string map_name, ofstream &output_file) {\n    int test_count = get_scene_tests_count(scenepath);\n\n    for(int test_index=0; test_index<test_count; test_index++) {\n        arena env = arena(scenepath, root, test_index, ARENA_MOVING_AI);\n        robot_astar bot = robot_astar(env);\n\n        int path_length;\n        vector<cell> path;\n        \n        bot.set_pos(env.start);\n        auto start_time = chrono::steady_clock::now();\n        path = bot.move_segmented(env.destination, ALPHA);\n        auto end_time = chrono::steady_clock::now();\n        auto diff_time = end_time - start_time;\n        path_length = path.size();\n\n        output_file << env.bucket << \", \" << map_name << \", \" << path_length << \", \" << chrono::duration <double, milli> (diff_time).count() << '\\n';\n        cout << \"a_star_segmented: \" << (test_index+1) <<\"\/\" << test_count << \" \" << env.bucket << \", \" << map_name << \", \" << path_length << \", \" << chrono::duration <double, milli> (diff_time).count() << '\\n';\n\n        env.clear();\n    }\n}\n\nvoid solve_map_dijkstra(string scenepath, string root, string map_name, ofstream &output_file) {\n    int test_count = get_scene_tests_count(scenepath);\n\n    for(int test_index=0; test_index<test_count; test_index++) {\n        arena env = arena(scenepath, root, test_index, ARENA_MOVING_AI);\n        robot_dj bot = robot_dj(env);\n\n        int path_length;\n        vector<cell> path;\n        \n        bot.set_pos(env.start);\n        auto start_time = chrono::steady_clock::now();\n        path = bot.move(env.destination);\n        auto end_time = chrono::steady_clock::now();\n        auto diff_time = end_time - start_time;\n        path_length = path.size();\n\n        output_file << env.bucket << \", \" << map_name << \", \" << path_length << \", \" << chrono::duration <double, milli> (diff_time).count() << '\\n';\n        cout << \"dijkstra: \" << (test_index+1) <<\"\/\" << test_count << \" \" << env.bucket << \", \" << map_name << \", \" << path_length << \", \" << chrono::duration <double, milli> (diff_time).count() << '\\n';\n\n        env.clear();\n    }\n}\n\nvoid solve_map_dijkstra_segmented(string scenepath, string root, string map_name, ofstream &output_file) {\n    int test_count = get_scene_tests_count(scenepath);\n\n    for(int test_index=0; test_index<test_count; test_index++) {\n        arena env = arena(scenepath, root, test_index, ARENA_MOVING_AI);\n        robot_dj bot = robot_dj(env);\n\n        int path_length;\n        vector<cell> path;\n        \n        bot.set_pos(env.start);\n        auto start_time = chrono::steady_clock::now();\n        path = bot.move_segmented(env.destination, ALPHA);\n        auto end_time = chrono::steady_clock::now();\n        auto diff_time = end_time - start_time;\n        path_length = path.size();\n\n        output_file << env.bucket << \", \" << map_name << \", \" << path_length << \", \" << chrono::duration <double, milli> (diff_time).count() << '\\n';\n        cout << \"dijkstra_segmented: \" << (test_index+1) <<\"\/\" << test_count << \" \" << env.bucket << \", \" << map_name << \", \" << path_length << \", \" << chrono::duration <double, milli> (diff_time).count() << '\\n';\n\n        env.clear();\n    }\n}\n\nvoid solve_map_pqdj(string scenepath, string root, string map_name, ofstream &output_file) {\n    int test_count = get_scene_tests_count(scenepath);\n\n    for(int test_index=0; test_index<test_count; test_index++) {\n        arena env = arena(scenepath, root, test_index, ARENA_MOVING_AI);\n        robot_pqdj bot = robot_pqdj(env);\n\n        int path_length;\n        vector<cell> path;\n        \n        bot.set_pos(env.start);\n        auto start_time = chrono::steady_clock::now();\n        path = bot.move(env.destination);\n        auto end_time = chrono::steady_clock::now();\n        auto diff_time = end_time - start_time;\n        path_length = path.size();\n\n        output_file << env.bucket << \", \" << map_name << \", \" << path_length << \", \" << chrono::duration <double, milli> (diff_time).count() << '\\n';\n        cout << \"pq_dijkstra: \" << (test_index+1) <<\"\/\" << test_count << \" \" << env.bucket << \", \" << map_name << \", \" << path_length << \", \" << chrono::duration <double, milli> (diff_time).count() << '\\n';\n\n        env.clear();\n    }\n}\n\nvoid solve_map_pqdj_segmented(string scenepath, string root, string map_name, ofstream &output_file) {\n    int test_count = get_scene_tests_count(scenepath);\n\n    for(int test_index=0; test_index<test_count; test_index++) {\n        arena env = arena(scenepath, root, test_index, ARENA_MOVING_AI);\n        robot_pqdj bot = robot_pqdj(env);\n\n        int path_length;\n        vector<cell> path;\n        \n        bot.set_pos(env.start);\n        auto start_time = chrono::steady_clock::now();\n        path = bot.move_segmented(env.destination, ALPHA);\n        auto end_time = chrono::steady_clock::now();\n        auto diff_time = end_time - start_time;\n        path_length = path.size();\n\n        output_file << env.bucket << \", \" << map_name << \", \" << path_length << \", \" << chrono::duration <double, milli> (diff_time).count() << '\\n';\n        cout << \"pq_dijkstra_segmented: \" << (test_index+1) <<\"\/\" << test_count << \" \" << env.bucket << \", \" << map_name << \", \" << path_length << \", \" << chrono::duration <double, milli> (diff_time).count() << '\\n';\n\n        env.clear();\n    }\n}\n\nvoid test_a_star() {\n    string output_path;\n    ofstream output_file;\n\n    output_path = TEST_PATH_PREFIX + \"a_star.csv\";\n    output_file.open(output_path);\n    output_file << \"Bucket, Map Name, Path Length, Time(ms)\" << endl;\n    for(int i=0;i<scene_list_count;i++) {\n        string map = scene_list[i];\n        string scenepath = SCENE_PATH_PREFIX + map;\n        solve_map_astar(scenepath, application, map, output_file);\n    }\n\n    output_file.flush();\n    output_file.close();\n}\n\nvoid test_a_star_segmented() {\n    string output_path;\n    ofstream output_file;\n\n    output_path = TEST_PATH_PREFIX + \"a_star_segmented.csv\";\n    output_file.open(output_path);\n    output_file << \"Bucket, Map Name, Path Length, Time(ms)\" << endl;\n    for(int i=0;i<scene_list_count;i++) {\n        string map = scene_list[i];\n        string scenepath = SCENE_PATH_PREFIX + map;\n        solve_map_astar_segmented(scenepath, application, map, output_file);\n    }\n\n    output_file.flush();\n    output_file.close();\n}\n\nvoid test_dijkstra() {\n    string output_path;\n    ofstream output_file;\n\n    output_path = TEST_PATH_PREFIX + \"dijkstra.csv\";\n    output_file.open(output_path);\n    output_file << \"Bucket, Map Name, Path Length, Time(ms)\" << endl;\n    for(int i=0;i<scene_list_count;i++) {\n        string map = scene_list[i];\n        string scenepath = SCENE_PATH_PREFIX + map;\n        solve_map_dijkstra(scenepath, application, map, output_file);\n    }\n\n    output_file.flush();\n    output_file.close();\n}\n\nvoid test_dijkstra_segmented() {\n    string output_path;\n    ofstream output_file;\n\n    output_path = TEST_PATH_PREFIX + \"dijkstra_segmented.csv\";\n    output_file.open(output_path);\n    output_file << \"Bucket, Map Name, Path Length, Time(ms)\" << endl;\n    for(int i=0;i<scene_list_count;i++) {\n        string map = scene_list[i];\n        string scenepath = SCENE_PATH_PREFIX + map;\n        solve_map_dijkstra_segmented(scenepath, application, map, output_file);\n    }\n\n    output_file.flush();\n    output_file.close();\n}\n\nvoid test_pqdj() {\n    string output_path;\n    ofstream output_file;\n\n    output_path = TEST_PATH_PREFIX + \"pq_dijkstra.csv\";\n    output_file.open(output_path);\n    output_file << \"Bucket, Map Name, Path Length, Time(ms)\" << endl;\n    for(int i=0;i<scene_list_count;i++) {\n        string map = scene_list[i];\n        string scenepath = SCENE_PATH_PREFIX + map;\n        solve_map_pqdj(scenepath, application, map, output_file);\n    }\n\n    output_file.flush();\n    output_file.close();\n}\n\nvoid test_pqdj_segmented() {\n    string output_path;\n    ofstream output_file;\n\n    output_path = TEST_PATH_PREFIX + \"pq_dijkstra_segmented_0.csv\";\n    output_file.open(output_path);\n    output_file << \"Bucket, Map Name, Path Length, Time(ms)\" << endl;\n    for(int i=0;i<scene_list_count;i++) {\n        string map = scene_list[i];\n        string scenepath = SCENE_PATH_PREFIX + map;\n        solve_map_pqdj_segmented(scenepath, application, map, output_file);\n    }\n    output_file.flush();\n    output_file.close();\n}\n\nint main(int argc, char *argv[]) {\n    test_a_star();\n    test_a_star_segmented();\n    test_dijkstra();\n    test_dijkstra_segmented();\n    test_pqdj();\n    test_pqdj_segmented();\n    \n    return 0;\n}","avg_line_length":31.7946428571,"max_line_length":216,"alphanum_fraction":0.6194889076,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":9505,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["blessing"],"max_stars_count":null,"content":"\/**********************************************************************\r\n*  Copyright (c) 2008-2013, Alliance for Sustainable Energy.\r\n*  All rights reserved.\r\n*\r\n*  This library is free software; you can redistribute it and\/or\r\n*  modify it under the terms of the GNU Lesser General Public\r\n*  License as published by the Free Software Foundation; either\r\n*  version 2.1 of the License, or (at your option) any later version.\r\n*\r\n*  This library is distributed in the hope that it will be useful,\r\n*  but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n*  Lesser General Public License for more details.\r\n*\r\n*  You should have received a copy of the GNU Lesser General Public\r\n*  License along with this library; if not, write to the Free Software\r\n*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\r\n**********************************************************************\/\r\n\r\n#include <openstudio_lib\/ModelObjectVectorController.hpp>\r\n#include <openstudio_lib\/OSAppBase.hpp>\r\n#include <openstudio_lib\/OSDocument.hpp>\r\n\r\n#include <model\/ModelObject_Impl.hpp>\r\n#include <model\/Model.hpp>\r\n#include <model\/Model_Impl.hpp>\r\n\r\n#include <utilities\/core\/Assert.hpp>\r\n\r\n\r\nnamespace openstudio {\r\n\r\n\r\nvoid ModelObjectVectorController::attach(const model::ModelObject& modelObject)\r\n{\r\n  detach();\r\n\r\n  m_modelObject = modelObject;\r\n\r\n  attachModel(modelObject.model());\r\n\r\n  bool isConnected = false;\r\n  isConnected = connect(m_model->getImpl<model::detail::Model_Impl>().get(),\r\n                        SIGNAL(addWorkspaceObject(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),\r\n                        this,\r\n                        SLOT(objectAdded(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),\r\n                        Qt::QueuedConnection);\r\n  OS_ASSERT(isConnected);\r\n\r\n  isConnected = connect(m_model->getImpl<model::detail::Model_Impl>().get(),\r\n                        SIGNAL(removeWorkspaceObject(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),\r\n                        this,\r\n                        SLOT(objectRemoved(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),\r\n                        Qt::QueuedConnection);\r\n  OS_ASSERT(isConnected);\r\n\r\n  isConnected = connect(m_modelObject->getImpl<model::detail::ModelObject_Impl>().get(),\r\n                        SIGNAL(onRelationshipChange(int, Handle, Handle)),\r\n                        this,\r\n                        SLOT(changeRelationship(int, Handle, Handle)));\r\n  OS_ASSERT(isConnected);\r\n\r\n  isConnected = connect(m_modelObject->getImpl<model::detail::ModelObject_Impl>().get(),\r\n                        SIGNAL(onDataChange()),\r\n                        this,\r\n                        SLOT(dataChange()));\r\n  OS_ASSERT(isConnected);\r\n\r\n  isConnected = connect(m_modelObject->getImpl<model::detail::ModelObject_Impl>().get(),\r\n                        SIGNAL(onChange()),\r\n                        this,\r\n                        SLOT(change()));\r\n  OS_ASSERT(isConnected);\r\n}\r\n\r\nvoid ModelObjectVectorController::attachModel(const model::Model& model)\r\n{\r\n  if (m_model){\r\n    disconnect(m_model->getImpl<model::detail::Model_Impl>().get());\r\n    m_model.reset();\r\n  }\r\n  \r\n  m_model = model;\r\n\r\n  bool isConnected = false;\r\n  isConnected = connect(m_model->getImpl<model::detail::Model_Impl>().get(),\r\n                        SIGNAL(addWorkspaceObject(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),\r\n                        this,\r\n                        SLOT(objectAdded(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),\r\n                        Qt::QueuedConnection);\r\n  OS_ASSERT(isConnected);\r\n\r\n  isConnected = connect(m_model->getImpl<model::detail::Model_Impl>().get(),\r\n                        SIGNAL(removeWorkspaceObject(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),\r\n                        this,\r\n                        SLOT(objectRemoved(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),\r\n                        Qt::QueuedConnection);\r\n  OS_ASSERT(isConnected);\r\n}\r\n\r\nvoid ModelObjectVectorController::attachOtherModelObject(const model::ModelObject& modelObject)\r\n{\r\n  \/\/ check not already connected\r\n  BOOST_FOREACH(const model::ModelObject& currentModelObject, m_otherModelObjects){\r\n    if (modelObject.handle() == currentModelObject.handle()){\r\n      return;\r\n    }\r\n  }\r\n\r\n  m_otherModelObjects.push_back(modelObject);\r\n\r\n  bool isConnected = false;\r\n  isConnected = connect(modelObject.getImpl<model::detail::ModelObject_Impl>().get(),\r\n                        SIGNAL(onRelationshipChange(int, Handle, Handle)),\r\n                        this,\r\n                        SLOT(changeRelationship(int, Handle, Handle)));\r\n  OS_ASSERT(isConnected);\r\n}\r\n\r\nvoid ModelObjectVectorController::detach()\r\n{\r\n  if (m_modelObject){\r\n    disconnect(m_modelObject->getImpl<model::detail::ModelObject_Impl>().get());\r\n    m_modelObject.reset();\r\n  }\r\n\r\n  if (m_model){\r\n    disconnect(m_model->getImpl<model::detail::Model_Impl>().get());\r\n    m_model.reset();\r\n  }\r\n\r\n  detachOtherModelObjects();\r\n}\r\n\r\nvoid ModelObjectVectorController::detachOtherModelObject(const model::ModelObject& modelObject)\r\n{\r\n  std::vector<model::ModelObject>::const_iterator it = m_otherModelObjects.begin();\r\n  std::vector<model::ModelObject>::const_iterator itend = m_otherModelObjects.end();\r\n  std::vector<model::ModelObject> newVector;\r\n  for (; it != itend; ++it){\r\n    if (it->handle() == modelObject.handle()){\r\n      disconnect(modelObject.getImpl<model::detail::ModelObject_Impl>().get());\r\n    }else{\r\n      newVector.push_back(*it);\r\n    }\r\n  }\r\n  m_otherModelObjects.swap(newVector);\r\n}\r\n\r\nvoid ModelObjectVectorController::detachOtherModelObjects()\r\n{\r\n  BOOST_FOREACH(const model::ModelObject& modelObject, m_otherModelObjects){\r\n    disconnect(modelObject.getImpl<model::detail::ModelObject_Impl>().get());\r\n  }\r\n  m_otherModelObjects.clear();\r\n}\r\n\r\nvoid ModelObjectVectorController::changeRelationship(int index, Handle newHandle, Handle oldHandle)\r\n{\r\n  if (newHandle != oldHandle){\r\n    model::detail::ModelObject_Impl* impl = qobject_cast<model::detail::ModelObject_Impl*>(this->sender());\r\n    if (impl){\r\n      onChangeRelationship(impl->getObject<model::ModelObject>(), index, newHandle, oldHandle);\r\n    }\r\n  }\r\n}\r\n\r\nvoid ModelObjectVectorController::dataChange()\r\n{\r\n  QObject* sender = this->sender();\r\n  model::detail::ModelObject_Impl* impl = qobject_cast<model::detail::ModelObject_Impl*>(sender);\r\n  if (impl){\r\n    onDataChange(impl->getObject<model::ModelObject>());\r\n  }\r\n}\r\n\r\nvoid ModelObjectVectorController::change()\r\n{\r\n  QObject* sender = this->sender();\r\n  model::detail::ModelObject_Impl* impl = qobject_cast<model::detail::ModelObject_Impl*>(sender);\r\n  if (impl){\r\n    onChange(impl->getObject<model::ModelObject>());\r\n  }\r\n}\r\n\r\nvoid ModelObjectVectorController::objectAdded(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl> impl, const openstudio::IddObjectType& iddObjectType, const openstudio::UUID& handle)\r\n{\r\n  onObjectAdded(impl->getObject<model::ModelObject>(), iddObjectType, handle);\r\n}\r\n\r\nvoid ModelObjectVectorController::objectRemoved(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl> impl, const openstudio::IddObjectType& iddObjectType, const openstudio::UUID& handle)\r\n{\r\n  onObjectRemoved(impl->getObject<model::ModelObject>(), iddObjectType, handle);\r\n}\r\n\r\nvoid ModelObjectVectorController::onChangeRelationship(const openstudio::model::ModelObject& modelObject, int index, Handle newHandle, Handle oldHandle)\r\n{\r\n}\r\n\r\nvoid ModelObjectVectorController::onDataChange(const openstudio::model::ModelObject& modelObject)\r\n{\r\n}\r\n\r\nvoid ModelObjectVectorController::onChange(const openstudio::model::ModelObject& modelObject)\r\n{\r\n}\r\n\r\nvoid ModelObjectVectorController::onObjectAdded(const openstudio::model::ModelObject& modelObject, const openstudio::IddObjectType& iddObjectType, const openstudio::UUID& handle)\r\n{\r\n}\r\n\r\nvoid ModelObjectVectorController::onObjectRemoved(const openstudio::model::ModelObject& modelObject, const openstudio::IddObjectType& iddObjectType, const openstudio::UUID& handle)\r\n{\r\n  detachOtherModelObject(modelObject);\r\n}\r\n\r\nbool ModelObjectVectorController::fromModel(const OSItemId& itemId) const\r\n{\r\n  return OSAppBase::instance()->currentDocument()->fromModel(itemId);\r\n}\r\n\r\nbool ModelObjectVectorController::fromComponentLibrary(const OSItemId& itemId) const\r\n{\r\n  return OSAppBase::instance()->currentDocument()->fromComponentLibrary(itemId);\r\n}\r\n\r\nboost::optional<model::ModelObject> ModelObjectVectorController::getModelObject(const OSItemId& itemId) const\r\n{\r\n  return OSAppBase::instance()->currentDocument()->getModelObject(itemId);\r\n}\r\n\r\nboost::optional<model::Component> ModelObjectVectorController::getComponent(const OSItemId& itemId) const\r\n{\r\n  return OSAppBase::instance()->currentDocument()->getComponent(itemId);\r\n}\r\n\r\n\r\n} \/\/ openstudio\r\n\r\n","avg_line_length":39.6041666667,"max_line_length":194,"alphanum_fraction":0.6830089427,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":163,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["ISC"],"max_stars_count":41.0,"content":"#include \"vecops.h\"\n\ndouble length(const QPointF& p) {\n  return sqrt(p.x()*p.x()+p.y()*p.y());\n}\n\nQPointF normalize(const QPointF& p) {\n  return p \/ length(p);\n}\n\n","avg_line_length":14.8181818182,"max_line_length":39,"alphanum_fraction":0.6134969325,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6311,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/****************************\nCopyright \u00a9 2006-2015 Luke Salisbury\nThis software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.\n\nPermission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:\n\n1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.\n2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.\n3. This notice may not be removed or altered from any source distribution.\n****************************\/\n\n#include \"map_screen.h\"\n#include \"display\/display.h\"\n\nnamespace colour {\n\textern LuxColour white;\n\textern LuxColour black;\n\textern LuxColour red;\n\textern LuxColour blue;\n\textern LuxColour green;\n\textern LuxColour yellow;\n}\n\n\nMokoiMapScreen::MokoiMapScreen( uint32_t x, uint32_t y, uint32_t width, uint32_t height )\n{\n\tthis->_x = x;\n\tthis->_y = y;\n\tthis->_width = width;\n\tthis->_height = height;\n\tthis->_offset_x = width * x;\n\tthis->_offset_y = height * y;\n\tthis->initialised = false;\n\tthis->_mask = NULL;\n}\n\nMokoiMapScreen::~MokoiMapScreen()\n{\n\tthis->Close();\n}\n\nbool MokoiMapScreen::Init()\n{\n\tif ( this->initialised )\n\t\treturn false;\n\n\tthis->initialised = true;\n\tif ( !this->_mask )\n\t\tthis->_mask = Lux_Mask_New( (this->_width), (this->_height) );\n\n\tMapObject * object = NULL;\n\tLuxSprite * current = NULL;\n\tstd::list<MapObject *>::iterator p;\n\n\tif ( this->_objects.size() )\n\t{\n\t\tfor ( p = this->_objects.begin(); p != this->_objects.end(); p++ )\n\t\t{\n\t\t\tobject = (*p);\n\t\t\tobject->SetData( object->type);\n\t\t\tif ( (object->type == OBJECT_SPRITE) && object->has_data )\n\t\t\t{\n\t\t\t\tcurrent = (LuxSprite *)object->GetData();\n\t\t\t\tif ( current->mask_value )\n\t\t\t\t{\n\t\t\t\t\tif ( object->effects.flip_image == 1 || object->effects.flip_image == 3 )\n\t\t\t\t\t\tthis->FillMask( object->position.x, object->position.y, ( object->position.h ? object->position.h : current->sheet_area.h), ( (*p)->position.w ? object->position.w : current->sheet_area.w), current->mask_value);\n\t\t\t\t\telse\n\t\t\t\t\t\tthis->FillMask( object->position.x, object->position.y, ( object->position.w ? object->position.w : current->sheet_area.w), ( object->position.h ? object->position.h : current->sheet_area.h), current->mask_value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( !lux::display->AddObjectToLayer(object->layer, object, true) )\n\t\t\t{\n\t\t\t\tlux::core->SystemStreamMessage(SYSTEM_MESSAGE_ERROR) << object->TypeName() << \" (\" << object->sprite << \") add failed\" << std::endl;\n\t\t\t\tobject->type = 0;\n\t\t\t}\n\n\t\t}\n\t}\n\treturn true;\n}\n\nbool MokoiMapScreen::Close()\n{\n\tthis->initialised = false;\n\tstd::list<MapObject *>::iterator p;\n\tfor ( p = this->_objects.begin(); p != this->_objects.end(); p++ )\n\t{\n\t\tif ( lux::display->RemoveObject((*p)->layer, (*p)) )\n\t\t{\n\t\t\t(*p)->FreeData();\n\t\t}\n\t}\n\tLux_Mask_Free(this->_mask);\n\tthis->_mask = NULL;\n\n\treturn true;\n}\n\n\/* Masks *\/\nuint16_t MokoiMapScreen::GetMaskValue(uint16_t x, uint16_t y)\n{\n\tif ( !this->initialised )\n\t\treturn 0xFFFF;\n\n\tif ( this->_mask )\n\t{\n\t\treturn Lux_Mask_GetValue(this->_mask, x - this->_offset_x, y - this->_offset_y);\n\t}\n\treturn 0xFFFF;\n}\n\nvoid MokoiMapScreen::FillMask(uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint8_t value)\n{\n\tif ( !this->initialised )\n\t\treturn;\n\tif ( this->_mask )\n\t{\n\t\tLuxRect r;\n\t\tr.x = x - this->_offset_x;\n\t\tr.y = y - this->_offset_y;\n\t\tr.w = width;\n\t\tr.h = height;\n\t\tif ( r.x < 0 )\n\t\t{\n\t\t\tr.w += r.x;\n\t\t\tr.x = 0;\n\t\t}\n\t\tif ( r.y < 0 )\n\t\t{\n\t\t\tr.h += r.y;\n\t\t\tr.y = 0;\n\t\t}\n\t\tLux_Mask_FillArea( this->_mask, (uint16_t)r.x, (uint16_t)r.y, r.w, r.h, value );\n\t}\n}\n\nvoid MokoiMapScreen::BuildMask()\n{\n\tLuxSprite * current = NULL;\n\tstd::list<MapObject *>::iterator p;\n\tfor ( p = this->_objects.begin(); p != this->_objects.end(); p++ )\n\t{\n\t\t(*p)->SetData((*p)->type);\n\t\tif ( ((*p)->type == OBJECT_SPRITE) && (*p)->has_data )\n\t\t{\n\t\t\tcurrent = (LuxSprite *)(*p)->GetData();\n\t\t\tif ( (*p)->effects.flip_image == 1 || (*p)->effects.flip_image == 3 )\n\t\t\t\tthis->FillMask( (*p)->position.x, (*p)->position.y, ( (*p)->position.h ? (*p)->position.h : current->sheet_area.h), ( (*p)->position.w ? (*p)->position.w : current->sheet_area.w), current->mask_value);\n\t\t\telse\n\t\t\t\tthis->FillMask( (*p)->position.x, (*p)->position.y, ( (*p)->position.w ? (*p)->position.w : current->sheet_area.w), ( (*p)->position.h ? (*p)->position.h : current->sheet_area.h), current->mask_value);\n\t\t}\n\t}\n\n\t\/\/Lux_Mask * sprite_mask = Lux_Mask_New(0, 0);\n\t\/\/Lux_Mask_Load(\"test.mask\", sprite_mask);\n\t\/\/Lux_Mask_CopyArea(sprite_mask, map_mask, 10, 10);\n\t\/\/Lux_Mask_FillArea(map_mask, 5, 0, 10, 20, 69);\n}\n\nvoid MokoiMapScreen::DrawMask( fixed position[3] )\n{\n\tLuxRect rect = {0,0,2,2, 7000};\n\tObjectEffect mask_colour;\n\n\tint32_t y = this->_offset_y - MAKE_FIXED_INT(position[1]);\n\tint32_t x = this->_offset_x - MAKE_FIXED_INT(position[0]);\n\n\tmask_colour.primary_colour = colour::red;\n\n\tif ( this->_mask )\n\t{\n\t\tlux::core->SystemStreamMessage(SYSTEM_MESSAGE_DEBUG) << \"Mask Memory:\" << this->_mask->length  << \"bytes. Offset:\" << this->_offset_x << \"x\" << this->_offset_y << std::endl;\n\t\tlux::core->SystemStreamMessage(SYSTEM_MESSAGE_DEBUG) << this->_mask->width << \"x\" << this->_mask->height << std::endl;\n\n\t\tfor( uint32_t i = 0; i < this->_mask->length; i += 2 )\n\t\t{\n\t\t\tif ( this->_mask->data[i] )\n\t\t\t{\n\t\t\t\trect.y = (i \/ this->_mask->width);\n\t\t\t\trect.x = i - ( rect.y * this->_mask->width );\n\n\t\t\t\trect.y += y;\n\t\t\t\trect.x += x;\n\t\t\t\tmask_colour.primary_colour.a = 128;\n\t\t\t\tmask_colour.primary_colour.r = this->_mask->data[i];\n\n\t\t\t\tlux::display->graphics.DrawRect( rect, mask_colour );\n\t\t\t}\n\t\t}\n\n\n\t}\n}\n\n\/\/bool MapObjectSort(MapObject * a, MapObject * b )\n\/\/{\n\/\/\tif ( a->layer < b->layer )\n\/\/\t\treturn true;\n\/\/\tif ( a->position.z < b->position.z )\n\/\/\t\treturn true;\n\/\/\tif ( a->position.y < b->position.y )\n\/\/\t\treturn true;\n\/\/\tif ( a->position.x < b->position.x )\n\/\/\t\treturn true;\n\n\/\/\treturn false;\n\/\/}\n\nbool ObjectSort(MapObject * a, MapObject * b );\nvoid MokoiMapScreen::SortObjects()\n{\n\tthis->_objects.sort( ObjectSort );\n}\n\n","avg_line_length":29.0829493088,"max_line_length":243,"alphanum_fraction":0.6437965457,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5746,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC0-1.0"],"max_stars_count":87.0,"content":"#include \"vmcsolver.h\"\n#include \"lib.h\"\n\n#include <armadillo>\n#include <iostream>\n\nusing namespace arma;\nusing namespace std;\n\nVMCSolver::VMCSolver() :\n    nDimensions(3),\n    charge(2),\n    nParticles(2),\n    h(0.001),\n    h2(1000000),\n    idum(-1),\n    alpha(0.5*charge),\n    nCycles(1000000),\n    timestep(0.05),\n    D(0.5)\n{\n}\n\nvoid VMCSolver::runMonteCarloIntegration()\n{\n  rOld = zeros<mat>(nParticles, nDimensions);\n  rNew = zeros<mat>(nParticles, nDimensions);\n  QForceOld = zeros<mat>(nParticles, nDimensions);\n  QForceNew = zeros<mat>(nParticles, nDimensions);\n\n  double waveFunctionOld = 0;\n  double waveFunctionNew = 0;\n\n  double energySum = 0;\n  double energySquaredSum = 0;\n\n  double deltaE;\n\n  \/\/ initial trial positions\n  for(int i = 0; i < nParticles; i++) {\n    for(int j = 0; j < nDimensions; j++) {\n      rOld(i,j) = GaussianDeviate(&idum)*sqrt(timestep);\n    }\n  }\n  rNew = rOld;\n\n  \/\/ loop over Monte Carlo cycles\n  for(int cycle = 0; cycle < nCycles; cycle++) {\n\n    \/\/ Store the current value of the wave function\n    waveFunctionOld = waveFunction(rOld);\n    QuantumForce(rOld, QForceOld); QForceOld = QForceOld*h\/waveFunctionOld;\n    \/\/ New position to test\n    for(int i = 0; i < nParticles; i++) {\n      for(int j = 0; j < nDimensions; j++) {\n\trNew(i,j) = rOld(i,j) + GaussianDeviate(&idum)*sqrt(timestep)+QForceOld(i,j)*timestep*D;\n      }\n      \/\/  for the other particles we need to set the position to the old position since\n      \/\/  we move only one particle at the time\n      for (int k = 0; k < nParticles; k++) {\n\tif ( k != i) {\n\t  for (int j=0; j < nDimensions; j++) {\n\t    rNew(k,j) = rOld(k,j);\n\t  }\n\t} \n      }\n      \/\/ Recalculate the value of the wave function and the quantum force\n      waveFunctionNew = waveFunction(rNew);\n      QuantumForce(rNew,QForceNew) = QForceNew*h\/waveFunctionNew;\n      \/\/  we compute the log of the ratio of the greens functions to be used in the \n      \/\/  Metropolis-Hastings algorithm\n      GreensFunction = 0.0;            \n      for (int j=0; j < nDimensions; j++) {\n\tGreensFunction += 0.5*(QForceOld(i,j)+QForceNew(i,j))*\n\t  (D*timestep*0.5*(QForceOld(i,j)-QForceNew(i,j))-rNew(i,j)+rOld(i,j));\n      }\n      GreensFunction = exp(GreensFunction);\n\n      \/\/ The Metropolis test is performed by moving one particle at the time\n      if(ran2(&idum) <= GreensFunction*(waveFunctionNew*waveFunctionNew) \/ (waveFunctionOld*waveFunctionOld)) {\n\tfor(int j = 0; j < nDimensions; j++) {\n\t  rOld(i,j) = rNew(i,j);\n\t  QForceOld(i,j) = QForceNew(i,j);\n\t  waveFunctionOld = waveFunctionNew;\n\t}\n      } else {\n\tfor(int j = 0; j < nDimensions; j++) {\n\t  rNew(i,j) = rOld(i,j);\n\t  QForceNew(i,j) = QForceOld(i,j);\n\t}\n      }\n      \/\/ update energies\n      deltaE = localEnergy(rNew);\n      energySum += deltaE;\n      energySquaredSum += deltaE*deltaE;\n    }\n  }\n  double energy = energySum\/(nCycles * nParticles);\n  double energySquared = energySquaredSum\/(nCycles * nParticles);\n  cout << \"Energy: \" << energy << \" Energy (squared sum): \" << energySquared << endl;\n}\n\ndouble VMCSolver::localEnergy(const mat &r)\n{\n    mat rPlus = zeros<mat>(nParticles, nDimensions);\n    mat rMinus = zeros<mat>(nParticles, nDimensions);\n\n    rPlus = rMinus = r;\n\n    double waveFunctionMinus = 0;\n    double waveFunctionPlus = 0;\n\n    double waveFunctionCurrent = waveFunction(r);\n\n    \/\/ Kinetic energy\n\n    double kineticEnergy = 0;\n    for(int i = 0; i < nParticles; i++) {\n        for(int j = 0; j < nDimensions; j++) {\n            rPlus(i,j) += h;\n            rMinus(i,j) -= h;\n            waveFunctionMinus = waveFunction(rMinus);\n            waveFunctionPlus = waveFunction(rPlus);\n            kineticEnergy -= (waveFunctionMinus + waveFunctionPlus - 2 * waveFunctionCurrent);\n            rPlus(i,j) = r(i,j);\n            rMinus(i,j) = r(i,j);\n        }\n    }\n    kineticEnergy = 0.5 * h2 * kineticEnergy \/ waveFunctionCurrent;\n\n    \/\/ Potential energy\n    double potentialEnergy = 0;\n    double rSingleParticle = 0;\n    for(int i = 0; i < nParticles; i++) {\n        rSingleParticle = 0;\n        for(int j = 0; j < nDimensions; j++) {\n            rSingleParticle += r(i,j)*r(i,j);\n        }\n        potentialEnergy -= charge \/ sqrt(rSingleParticle);\n    }\n    \/\/ Contribution from electron-electron potential\n    double r12 = 0;\n    for(int i = 0; i < nParticles; i++) {\n        for(int j = i + 1; j < nParticles; j++) {\n            r12 = 0;\n            for(int k = 0; k < nDimensions; k++) {\n                r12 += (r(i,k) - r(j,k)) * (r(i,k) - r(j,k));\n            }\n            potentialEnergy += 1 \/ sqrt(r12);\n        }\n    }\n\n    return kineticEnergy + potentialEnergy;\n}\n\ndouble VMCSolver::waveFunction(const mat &r)\n{\n    double argument = 0;\n    for(int i = 0; i < nParticles; i++) {\n        double rSingleParticle = 0;\n        for(int j = 0; j < nDimensions; j++) {\n            rSingleParticle += r(i,j) * r(i,j);\n        }\n        argument += sqrt(rSingleParticle);\n    }\n    return exp(-argument * alpha);\n}\n\n\n\ndouble VMCSolver::QuantumForce(const mat &r, mat &QForce)\n{\n    mat rPlus = zeros<mat>(nParticles, nDimensions);\n    mat rMinus = zeros<mat>(nParticles, nDimensions);\n\n    rPlus = rMinus = r;\n\n    double waveFunctionMinus = 0;\n    double waveFunctionPlus = 0;\n\n    double waveFunctionCurrent = waveFunction(r);\n\n    \/\/ Kinetic energy\n\n    double kineticEnergy = 0;\n    for(int i = 0; i < nParticles; i++) {\n        for(int j = 0; j < nDimensions; j++) {\n            rPlus(i,j) += h;\n            rMinus(i,j) -= h;\n            waveFunctionMinus = waveFunction(rMinus);\n            waveFunctionPlus = waveFunction(rPlus);\n            QForce(i,j) =  (waveFunctionPlus-waveFunctionMinus);\n            rPlus(i,j) = r(i,j);\n            rMinus(i,j) = r(i,j);\n        }\n    }\n}\n","avg_line_length":29.0202020202,"max_line_length":111,"alphanum_fraction":0.5910198399,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3669,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n * This file is part of liblcf. Copyright (c) 2017 liblcf authors.\n * https:\/\/github.com\/EasyRPG\/liblcf - https:\/\/easyrpg.org\n *\n * liblcf is Free\/Libre Open Source Software, released under the MIT License.\n * For the full copyright and license information, please view the COPYING\n * file that was distributed with this source code.\n *\/\n\n#include <ostream>\n\n#include \"writer_lcf.h\"\n\nLcfWriter::LcfWriter(std::ostream& filestream, std::string encoding) :\n\tencoding(encoding),\n\tstream(filestream)\n{\n}\n\nLcfWriter::~LcfWriter() {\n\n}\n\nvoid LcfWriter::Write(const void *ptr, size_t size, size_t nmemb) {\n#ifdef NDEBUG\n\tstream.write(reinterpret_cast<const char*>(ptr), size*nmemb);\n#else\n\tassert(stream.write(reinterpret_cast<const char*>(ptr), size*nmemb).good());\n#endif\n}\n\ntemplate <>\nvoid LcfWriter::Write<uint8_t>(uint8_t val) {\n\tWrite(&val, 1, 1);\n}\n\ntemplate <>\nvoid LcfWriter::Write<int16_t>(int16_t val) {\n\tSwapByteOrder(val);\n\tWrite(&val, 2, 1);\n}\n\ntemplate <>\nvoid LcfWriter::Write<uint32_t>(uint32_t val) {\n\tSwapByteOrder(val);\n\tWrite(&val, 4, 1);\n}\n\nvoid LcfWriter::WriteInt(int val) {\n\tuint32_t value = (uint32_t) val;\n\tfor (int i = 28; i >= 0; i -= 7)\n\t\tif (value >= (1U << i) || i == 0)\n\t\t\tWrite<uint8_t>((uint8_t)(((value >> i) & 0x7F) | (i > 0 ? 0x80 : 0)));\n}\n\ntemplate <>\nvoid LcfWriter::Write<int32_t>(int32_t val) {\n\tWriteInt(val);\n}\n\ntemplate <>\nvoid LcfWriter::Write<bool>(bool val) {\n\tuint8_t x = val ? 1 : 0;\n\tWrite(x);\n}\n\ntemplate <>\nvoid LcfWriter::Write<double>(double val) {\n\tSwapByteOrder(val);\n\tWrite(&val, 8, 1);\n}\n\ntemplate <>\nvoid LcfWriter::Write<bool>(const std::vector<bool>& buffer) {\n\tstd::vector<bool>::const_iterator it;\n\tfor (it = buffer.begin(); it != buffer.end(); it++) {\n\t\tuint8_t val = *it ? 1 : 0;\n\t\tWrite(val);\n\t}\n}\n\ntemplate <>\nvoid LcfWriter::Write<uint8_t>(const std::vector<uint8_t>& buffer) {\n\tWrite(&buffer.front(), 1, buffer.size());\n}\n\ntemplate <>\nvoid LcfWriter::Write<int16_t>(const std::vector<int16_t>& buffer) {\n\tstd::vector<int16_t>::const_iterator it;\n\tfor (it = buffer.begin(); it != buffer.end(); it++)\n\t\tWrite(*it);\n}\n\ntemplate <>\nvoid LcfWriter::Write<int32_t>(const std::vector<int32_t>& buffer) {\n\tstd::vector<int32_t>::const_iterator it;\n\tfor (it = buffer.begin(); it != buffer.end(); it++) {\n\t\tint32_t val = *it;\n\t\tSwapByteOrder(val);\n\t\t\/\/ Write<int32_t> writes a compressed integer\n\t\tWrite(&val, 4, 1);\n\t}\n}\n\ntemplate <>\nvoid LcfWriter::Write<uint32_t>(const std::vector<uint32_t>& buffer) {\n\tstd::vector<uint32_t>::const_iterator it;\n\tfor (it = buffer.begin(); it != buffer.end(); it++)\n\t\tWrite(*it);\n}\n\nvoid LcfWriter::Write(const std::string& _str) {\n\tstd::string str = Decode(_str);\n\tif (!str.empty()) {\n\t\tWrite(&*str.begin(), 1, str.size());\n\t}\n}\n\nbool LcfWriter::IsOk() const {\n\treturn (stream.good());\n}\n\nstd::string LcfWriter::Decode(const std::string& str_to_encode) {\n\treturn ReaderUtil::Recode(str_to_encode, \"UTF-8\", encoding);\n}\n\n#ifdef WORDS_BIGENDIAN\nvoid LcfWriter::SwapByteOrder(uint16_t& us)\n{\n\tus =\t(us >> 8) |\n\t\t\t(us << 8);\n}\n\nvoid LcfWriter::SwapByteOrder(uint32_t& ui)\n{\n\tui =\t(ui >> 24) |\n\t\t\t((ui<<8) & 0x00FF0000) |\n\t\t\t((ui>>8) & 0x0000FF00) |\n\t\t\t(ui << 24);\n}\n\nvoid LcfWriter::SwapByteOrder(double& d)\n{\n\tuint32_t *p = reinterpret_cast<uint32_t *>(&d);\n\tSwapByteOrder(p[0]);\n\tSwapByteOrder(p[1]);\n\tuint32_t tmp = p[0];\n\tp[0] = p[1];\n\tp[1] = tmp;\n}\n#else\nvoid LcfWriter::SwapByteOrder(uint16_t& \/* us *\/) {}\nvoid LcfWriter::SwapByteOrder(uint32_t& \/* ui *\/) {}\nvoid LcfWriter::SwapByteOrder(double& \/* d *\/) {}\n#endif\n\nvoid LcfWriter::SwapByteOrder(int16_t& s)\n{\n\tSwapByteOrder((uint16_t&) s);\n}\n\nvoid LcfWriter::SwapByteOrder(int32_t& s)\n{\n\tSwapByteOrder((uint32_t&) s);\n}\n","avg_line_length":22.1024096386,"max_line_length":77,"alphanum_fraction":0.6620332516,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2109,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":18.0,"content":"\/\/ Copyright \u00a9 2016 Venture Media Labs.\n\/\/\n\/\/ This file is part of mxml. The full mxml copyright notice, including\n\/\/ terms governing use, modification, and redistribution, is contained in the\n\/\/ file LICENSE at the root of the source code distribution tree.\n\n#include <lxml\/lxml.h>\n#include <mxml\/EventFactory.h>\n#include <mxml\/JumpFactory.h>\n#include <mxml\/LoopFactory.h>\n#include <mxml\/parsing\/ScoreHandler.h>\n\n#include <boost\/test\/unit_test.hpp>\n#include <fstream>\n#include <unistd.h>\n\n\nusing namespace mxml;\nusing namespace mxml::parsing;\n\nstatic const char* kLoopsFileName = \"loops.xml\";\nstatic const char* kRepeatsFileName = \"repeats.xml\";\n\nBOOST_AUTO_TEST_CASE(loops) {\n    ScoreHandler handler;\n    std::ifstream is(kLoopsFileName);\n    lxml::parse(is, kLoopsFileName, handler);\n\n    const dom::Score& score = *handler.result();\n    LoopFactory loopFactory(score);\n    auto loops = loopFactory.build();\n\n    BOOST_CHECK_EQUAL(loops.size(), 2);\n\n    \/\/ First loop starts at measure 1 and ends at measure 3 (measures 1 and 2 are repeated)\n    BOOST_CHECK_EQUAL(loops[0].begin(), 1);\n    BOOST_CHECK_EQUAL(loops[0].end(), 3);\n    BOOST_CHECK_EQUAL(loops[0].count(), 1);\n    BOOST_CHECK(!loops[0].isSkipped(0, 1));\n    BOOST_CHECK(!loops[0].isSkipped(0, 2));\n\n    \/\/ The second loops has endings. The order should be 3, 4, 3, 5\n    BOOST_CHECK_EQUAL(loops[1].begin(), 3);\n    BOOST_CHECK_EQUAL(loops[1].end(), 5);\n    BOOST_CHECK_EQUAL(loops[1].count(), 1);\n    BOOST_CHECK(loops[1].isSkipped(0, 5));\n    BOOST_CHECK(loops[1].isSkipped(1, 4));\n}\n\nBOOST_AUTO_TEST_CASE(repeats) {\n    ScoreHandler handler;\n    std::ifstream is(kRepeatsFileName);\n    lxml::parse(is, kRepeatsFileName, handler);\n\n    const dom::Score& score = *handler.result();\n    JumpFactory jumpFactory(score);\n    auto jumps = jumpFactory.build();\n\n    BOOST_CHECK_EQUAL(jumps.size(), 2);\n\n    \/\/ To coda jump from measure 2 to 4\n    BOOST_CHECK_EQUAL(jumps[0].from, 2);\n    BOOST_CHECK_EQUAL(jumps[0].to, 4);\n\n    \/\/ Dal segno jump from measure 5 to 0\n    BOOST_CHECK_EQUAL(jumps[1].from, 5);\n    BOOST_CHECK_EQUAL(jumps[1].to, 0);\n}\n","avg_line_length":30.5652173913,"max_line_length":91,"alphanum_fraction":0.6993835941,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4385,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <config.h>\n#include <rsspp_internal.h>\n#include <utils.h>\n#include <cstring>\n\nusing namespace newsboat;\n\nnamespace rsspp {\n\nvoid rss_20_parser::parse_feed(feed& f, xmlNode * rootNode) {\n\tif (!rootNode)\n\t\tthrow exception(_(\"XML root node is NULL\"));\n\n\tif (rootNode->ns) {\n\t\tconst char * ns = (const char *)rootNode->ns->href;\n\t\tif (strcmp(ns, RSS20USERLAND_URI) == 0) {\n\t\t\tthis->ns = strdup(ns);\n\t\t}\n\t}\n\n\trss_09x_parser::parse_feed(f, rootNode);\n}\n\nvoid rss_09x_parser::parse_feed(feed& f, xmlNode * rootNode) {\n\tif (!rootNode)\n\t\tthrow exception(_(\"XML root node is NULL\"));\n\n\tglobalbase = get_prop(rootNode, \"base\", XML_URI);\n\n\txmlNode * channel = rootNode->children;\n\twhile (channel && strcmp((const char *)channel->name, \"channel\")!=0)\n\t\tchannel = channel->next;\n\n\tif (!channel)\n\t\tthrow exception(_(\"no RSS channel found\"));\n\n\tfor (xmlNode * node = channel->children; node != nullptr; node = node->next) {\n\t\tif (node_is(node, \"title\", ns)) {\n\t\t\tf.title = get_content(node);\n\t\t\tf.title_type = \"text\";\n\t\t} else if (node_is(node, \"link\", ns)) {\n\t\t\tf.link = utils::absolute_url(globalbase, get_content(node));\n\t\t} else if (node_is(node, \"description\", ns)) {\n\t\t\tf.description = get_content(node);\n\t\t} else if (node_is(node, \"language\", ns)) {\n\t\t\tf.language = get_content(node);\n\t\t} else if (node_is(node, \"managingEditor\", ns)) {\n\t\t\tf.managingeditor = get_content(node);\n\t\t} else if (node_is(node, \"item\", ns)) {\n\t\t\tf.items.push_back(parse_item(node));\n\t\t}\n\t}\n}\n\nitem rss_09x_parser::parse_item(xmlNode * itemNode) {\n\titem it;\n\tstd::string author;\n\tstd::string dc_date;\n\n\tstd::string base = get_prop(itemNode, \"base\", XML_URI);\n\tif (base.empty())\n\t\tbase = globalbase;\n\n\tfor (xmlNode * node = itemNode->children; node != nullptr; node = node->next) {\n\t\tif (node_is(node, \"title\", ns)) {\n\t\t\tit.title = get_content(node);\n\t\t\tit.title_type = \"text\";\n\t\t} else if (node_is(node, \"link\", ns)) {\n\t\t\tit.link = utils::absolute_url(base, get_content(node));\n\t\t} else if (node_is(node, \"description\", ns)) {\n\t\t\tit.base = get_prop(node, \"base\", XML_URI);\n\t\t\tif (it.base.empty())\n\t\t\t\tit.base = base;\n\t\t\tit.description = get_content(node);\n\t\t} else if (node_is(node, \"encoded\", CONTENT_URI)) {\n\t\t\tit.content_encoded = get_content(node);\n\t\t} else if (node_is(node, \"summary\", ITUNES_URI)) {\n\t\t\tit.itunes_summary = get_content(node);\n\t\t} else if (node_is(node, \"guid\", ns)) {\n\t\t\tit.guid = get_content(node);\n\t\t\tif (get_prop(node, \"isPermaLink\") == \"false\") {\n\t\t\t\tit.guid_isPermaLink = false;\n\t\t\t} else {\n\t\t\t\tit.guid_isPermaLink = true;\n\t\t\t\tit.guid = utils::absolute_url(base, it.guid);\n\t\t\t}\n\t\t} else if (node_is(node, \"pubDate\", ns)) {\n\t\t\tit.pubDate = get_content(node);\n\t\t} else if (node_is(node, \"date\", DC_URI)) {\n\t\t\tdc_date = w3cdtf_to_rfc822(get_content(node));\n\t\t} else if (node_is(node, \"author\", ns)) {\n\t\t\tstd::string authorfield = get_content(node);\n\t\t\tif (authorfield[authorfield.length()-1] == ')') {\n\t\t\t\tit.author_email = utils::tokenize(authorfield, \" \")[0];\n\t\t\t\tunsigned int start, end;\n\t\t\t\tend = authorfield.length()-2;\n\t\t\t\tfor (start = end; start > 0 && authorfield[start] != '('; start--) { }\n\t\t\t\tit.author = authorfield.substr(start+1, end-start);\n\t\t\t} else {\n\t\t\t\tit.author_email = authorfield;\n\t\t\t\tit.author = authorfield;\n\t\t\t}\n\t\t} else if (node_is(node, \"creator\", DC_URI)) {\n\t\t\tauthor = get_content(node);\n\t\t} else if (node_is(node, \"enclosure\", ns)) {\n\t\t\tconst std::string type = get_prop(node, \"type\");\n\t\t\tif (utils::is_valid_podcast_type(type)) {\n\t\t\t\tit.enclosure_url = get_prop(node, \"url\");\n\t\t\t\tit.enclosure_type = std::move(type);\n\t\t\t}\n\t\t} else if (node_is(node, \"content\", MEDIA_RSS_URI)) {\n\t\t\tconst std::string type = get_prop(node, \"type\");\n\t\t\tif (utils::is_valid_podcast_type(type)) {\n\t\t\t\tit.enclosure_url = get_prop(node, \"url\");\n\t\t\t\tit.enclosure_type = std::move(type);\n\t\t\t}\n\t\t} else if (node_is(node, \"group\", MEDIA_RSS_URI)) {\n\t\t\tfor (xmlNode * mnode = node->children; mnode != nullptr; mnode = mnode->next) {\n\t\t\t\tif (node_is(mnode, \"content\", MEDIA_RSS_URI)) {\n\t\t\t\t\tconst std::string type = get_prop(mnode, \"type\");\n\t\t\t\t\tif (utils::is_valid_podcast_type(type)) {\n\t\t\t\t\t\tit.enclosure_url = get_prop(mnode, \"url\");\n\t\t\t\t\t\tit.enclosure_type = std::move(type);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (it.author == \"\") {\n\t\tit.author = author;\n\t}\n\n\tif (it.pubDate == \"\") {\n\t\tit.pubDate = dc_date;\n\t}\n\n\treturn it;\n}\n\nrss_09x_parser::~rss_09x_parser() {\n\tfree((void *)ns);\n}\n\n}\n","avg_line_length":30.0342465753,"max_line_length":82,"alphanum_fraction":0.6401368301,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11129,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Copyright 2014-present Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <gtest\/gtest.h>\n\n#include <memory>\n#include <folly\/Format.h>\n#include <thrift\/lib\/cpp2\/test\/gen-cpp2\/TestService.h>\n#include <thrift\/lib\/cpp2\/protocol\/Serializer.h>\n\nusing namespace std;\nusing namespace folly;\nusing namespace apache::thrift;\nusing namespace apache::thrift::test;\n\nTestStruct makeTestStruct() {\n  TestStruct s;\n  s.s = \"test\";\n  s.i = 48;\n  return s;\n}\n\nTEST(SerializationTest, CompactSerializerRoundtripPasses) {\n  auto s = makeTestStruct();\n\n  folly::IOBufQueue q;\n  CompactSerializer::serialize(s, &q);\n\n  TestStruct out;\n  CompactSerializer::deserialize(q.front(), out);\n\n  EXPECT_EQ(out, s);\n}\n\nTEST(SerializationTest, BinarySerializerRoundtripPasses) {\n  auto s = makeTestStruct();\n\n  folly::IOBufQueue q;\n  BinarySerializer::serialize(s, &q);\n\n  TestStruct out;\n  BinarySerializer::deserialize(q.front(), out);\n\n  EXPECT_EQ(out, s);\n}\n\nTEST(SerializationTest, SimpleJSONSerializerRoundtripPasses) {\n  auto s = makeTestStruct();\n\n  folly::IOBufQueue q;\n  SimpleJSONSerializer::serialize(s, &q);\n\n  TestStruct out;\n  SimpleJSONSerializer::deserialize(q.front(), out);\n\n  EXPECT_EQ(out, s);\n}\n\nTEST(SerializationTest, MixedRoundtripFails) {\n  auto s = makeTestStruct();\n\n  folly::IOBufQueue q;\n  CompactSerializer::serialize(s, &q);\n\n  try {\n    TestStruct out;\n    BinarySerializer::deserialize(q.front(), out);\n    FAIL();\n  } catch (...) {\n    \/\/ Should underflow\n  }\n}\n\nTEST(SerializationTest, DeserializeReturningObjGivenCursor) {\n  using serializer = SimpleJSONSerializer;\n\n  auto s = makeTestStruct();\n  auto q = serializer::serialize<IOBufQueue>(s);\n\n  Cursor cursor{q.front()};\n  auto out = serializer::deserialize<TestStruct>(cursor);\n  EXPECT_EQ(s, out);\n  EXPECT_TRUE(cursor.isAtEnd());\n}\n\nTEST(SerializationTest, DeserializeReturningObjGivenCursorToMiddleOfBuffer) {\n  using serializer = SimpleJSONSerializer;\n\n  auto s = makeTestStruct();\n  auto str = serializer::serialize<std::string>(s);\n  \/\/ Copy the serialized data into an IOBuf, with 4 extra bytes on either end.\n  IOBuf buf{IOBuf::CREATE, str.size() + (sizeof(uint32_t) * 2)};\n  folly::io::Appender appender(&buf, 0);\n  appender.writeBE<uint32_t>(12);\n  appender(str);\n  appender.writeBE<uint32_t>(34);\n\n  \/\/ Create a Cursor pointing to the location of the serialized data\n  \/\/ in the buffer.\n  folly::io::Cursor cursor(&buf);\n  cursor.skip(sizeof(uint32_t));\n\n  auto out = serializer::deserialize<TestStruct>(cursor);\n  EXPECT_EQ(s, out);\n  cursor.skip(sizeof(uint32_t));\n  EXPECT_TRUE(cursor.isAtEnd());\n}\n\nTEST(SerializationTest, DeserializeReturningObjGivenIOBuf) {\n  using serializer = SimpleJSONSerializer;\n\n  auto s = makeTestStruct();\n  IOBufQueue q;\n  serializer::serialize(s, &q);\n  auto b = q.move();\n\n  auto out = serializer::deserialize<TestStruct>(b.get());\n  EXPECT_EQ(s, out);\n}\n\nTEST(SerializationTest, DeserializeReturningObjGivenByteRange) {\n  using serializer = SimpleJSONSerializer;\n\n  auto s = makeTestStruct();\n  IOBufQueue q;\n  serializer::serialize(s, &q);\n  auto b = q.move();\n\n  auto out = serializer::deserialize<TestStruct>(ByteRange(b->coalesce()));\n  EXPECT_EQ(s, out);\n}\n\nTEST(SerializationTest, DeserializeReturningObjGivenStringPiece) {\n  using serializer = SimpleJSONSerializer;\n\n  auto s = makeTestStruct();\n  IOBufQueue q;\n  serializer::serialize(s, &q);\n  auto b = q.move();\n\n  auto out = serializer::deserialize<TestStruct>(StringPiece(b->coalesce()));\n  EXPECT_EQ(s, out);\n}\n\nTEST(SerializationTest, SerializeReturningIOBufQueue) {\n  using serializer = SimpleJSONSerializer;\n  auto s = makeTestStruct();\n  string expected;\n  serializer::serialize(s, &expected);\n  auto actual = serializer::serialize<IOBufQueue>(s);\n  EXPECT_EQ(expected, StringPiece(actual.move()->coalesce()));\n}\n\nTEST(SerializationTest, SerializeAppendsToString) {\n  using Serializer = SimpleJSONSerializer;\n  auto s = makeTestStruct();\n  string prefix = \"existing_text\";\n\n  string target = prefix;\n  Serializer::serialize(s, &target);\n\n  folly::StringPiece source = target;\n  EXPECT_TRUE(source.removePrefix(prefix));\n  TestStruct check;\n  Serializer::deserialize(source, check);\n  EXPECT_EQ(check, s);\n}\n\nTEST(SerializationTest, SerializeAppendsToFBString) {\n  using Serializer = SimpleJSONSerializer;\n  auto s = makeTestStruct();\n  for (fbstring prefix = \"An existing string. \"; prefix.size() < 2000;\n       prefix += prefix) {\n    fbstring target = prefix;\n    Serializer::serialize(s, &target);\n\n    folly::StringPiece source = target;\n    EXPECT_TRUE(source.removePrefix(prefix));\n    TestStruct check;\n    Serializer::deserialize(source, check);\n    EXPECT_EQ(check, s);\n  }\n}\n\nTEST(SerializationTest, SerializeReturningString) {\n  using serializer = SimpleJSONSerializer;\n  auto s = makeTestStruct();\n  string expected;\n  serializer::serialize(s, &expected);\n  auto actual = serializer::serialize<string>(s);\n  EXPECT_EQ(expected, actual);\n}\n\nTEST(SerializationTest, SerializeReturningFBString) {\n  using serializer = SimpleJSONSerializer;\n  auto s = makeTestStruct();\n  fbstring expected;\n  serializer::serialize(s, &expected);\n  auto actual = serializer::serialize<fbstring>(s);\n  EXPECT_EQ(expected, actual);\n}\n\nTestStructRecursive makeTestStructRecursive(size_t levels) {\n  unique_ptr<TestStructRecursive> s;\n  for (size_t i = levels; i > 0; --i) {\n    auto t = make_unique<TestStructRecursive>();\n    t->tag = sformat(\"level-{}\", i);\n    t->cdr = std::move(s);\n    s = std::move(t);\n  }\n  TestStructRecursive ret;\n  ret.tag = \"level-0\";\n  ret.cdr = std::move(s);\n  return ret;\n}\n\nsize_t getRecDepth(const TestStructRecursive& s) {\n  auto p = &s;\n  size_t depth = 0;\n  while ((p = p->cdr.get())) {\n    ++depth;\n  }\n  return depth;\n}\n\nTEST(SerializationTest, RecursiveNoDepthCompactSerializerRoundtripPasses) {\n  auto s = makeTestStructRecursive(0);\n\n  folly::IOBufQueue q;\n  CompactSerializer::serialize(s, &q);\n\n  TestStructRecursive out;\n  CompactSerializer::deserialize(q.front(), out);\n\n  EXPECT_EQ(s, out);\n}\n\nTEST(SerializationTest, RecursiveDeepCompactSerializerRoundtripPasses) {\n  auto s = makeTestStructRecursive(6);\n  EXPECT_EQ(6, getRecDepth(s));\n\n  folly::IOBufQueue q;\n  CompactSerializer::serialize(s, &q);\n\n  TestStructRecursive out;\n  CompactSerializer::deserialize(q.front(), out);\n\n  EXPECT_EQ(s, out);\n}\n\nTEST(SerializationTest, RecursiveNoDepthBinarySerializerRoundtripPasses) {\n  auto s = makeTestStructRecursive(0);\n\n  folly::IOBufQueue q;\n  BinarySerializer::serialize(s, &q);\n\n  TestStructRecursive out;\n  BinarySerializer::deserialize(q.front(), out);\n\n  EXPECT_EQ(s, out);\n}\n\nTEST(SerializationTest, RecursiveDeepBinarySerializerRoundtripPasses) {\n  auto s = makeTestStructRecursive(6);\n  EXPECT_EQ(6, getRecDepth(s));\n\n  folly::IOBufQueue q;\n  BinarySerializer::serialize(s, &q);\n\n  TestStructRecursive out;\n  BinarySerializer::deserialize(q.front(), out);\n\n  EXPECT_EQ(s, out);\n}\n\nTEST(SerializationTest, RecursiveNoDepthSimpleJSONSerializerRoundtripPasses) {\n  auto s = makeTestStructRecursive(0);\n\n  folly::IOBufQueue q;\n  SimpleJSONSerializer::serialize(s, &q);\n\n  TestStructRecursive out;\n  SimpleJSONSerializer::deserialize(q.front(), out);\n\n  EXPECT_EQ(s, out);\n}\n\nTEST(SerializationTest, RecursiveDeepSimpleJSONSerializerRoundtripPasses) {\n  auto s = makeTestStructRecursive(6);\n  EXPECT_EQ(6, getRecDepth(s));\n\n  folly::IOBufQueue q;\n  SimpleJSONSerializer::serialize(s, &q);\n\n  TestStructRecursive out;\n  SimpleJSONSerializer::deserialize(q.front(), out);\n\n  EXPECT_EQ(s, out);\n}\n\nTEST(SerializationTest, StringOverloads) {\n  auto s = makeTestStruct();\n\n  std::string str;\n  CompactSerializer::serialize(s, &str);\n\n  {\n    TestStruct out;\n    CompactSerializer::deserialize(str, out);\n    EXPECT_EQ(out, s);\n  }\n}\n\nnamespace {\n\/\/ Large enough to ensure externally allocated buffer and to make sure\n\/\/ IOBufQueue::insert doesn't copy instead of linking\nconstexpr size_t kBufSize = 8192;\n\ntemplate <class Serializer>\nvoid testIOBufSharingUnmanagedBuffer() {\n  char tmp[kBufSize];\n  memcpy(tmp, \"hello\", 5);\n  TestStructIOBuf s;\n  s.buf = folly::IOBuf(folly::IOBuf::WRAP_BUFFER, tmp, sizeof(tmp));\n\n  for (unsigned int i = 0; i < 4; ++i) {\n    ExternalBufferSharing serializationSharing =\n      i & 1 ? SHARE_EXTERNAL_BUFFER : COPY_EXTERNAL_BUFFER;\n    ExternalBufferSharing deserializationSharing =\n      i & 2 ? SHARE_EXTERNAL_BUFFER : COPY_EXTERNAL_BUFFER;\n\n    folly::IOBufQueue q;\n    Serializer::serialize(s, &q, serializationSharing);\n\n    TestStructIOBuf s2;\n    Serializer::deserialize(q.front(), s2, deserializationSharing);\n\n    size_t size = 0;\n    for (auto& br : s2.buf) {\n      if (br.empty()) {\n        continue;\n      }\n      if (i == 3) {\n        \/\/ Expect only one non-empty buffer, which must be ours\n        EXPECT_EQ(size, 0);\n        EXPECT_EQ(s.buf.data(), br.data());\n        EXPECT_EQ(s.buf.length(), br.size());\n      } else {\n        EXPECT_NE(s.buf.data(), br.data());\n      }\n      size += br.size();\n    }\n    EXPECT_EQ(s.buf.length(), size);\n    s2.buf.coalesce();\n    EXPECT_EQ(0, memcmp(s2.buf.data(), s.buf.data(), s.buf.length()));\n  }\n}\n\ntemplate <class Serializer>\nvoid testIOBufSharingManagedBuffer() {\n  TestStructIOBuf s;\n  s.buf = folly::IOBuf(folly::IOBuf::CREATE, kBufSize);\n  memcpy(s.buf.writableTail(), \"hello\", 5);\n  s.buf.append(kBufSize);\n\n  for (unsigned int i = 0; i < 4; ++i) {\n    ExternalBufferSharing serializationSharing =\n      i & 1 ? SHARE_EXTERNAL_BUFFER : COPY_EXTERNAL_BUFFER;\n    ExternalBufferSharing deserializationSharing =\n      i & 2 ? SHARE_EXTERNAL_BUFFER : COPY_EXTERNAL_BUFFER;\n\n    folly::IOBufQueue q;\n    Serializer::serialize(s, &q, serializationSharing);\n\n    TestStructIOBuf s2;\n    Serializer::deserialize(q.front(), s2, deserializationSharing);\n\n    size_t size = 0;\n    for (auto& br : s2.buf) {\n      if (br.empty()) {\n        continue;\n      }\n      \/\/ Expect only one non-empty buffer, which must be ours\n      EXPECT_EQ(size, 0);\n      EXPECT_EQ(s.buf.data(), br.data());\n      EXPECT_EQ(s.buf.length(), br.size());\n      size += br.size();\n    }\n  }\n}\n\n}  \/\/ namespace\n\nTEST(SerializationTest, CompactSerializerIOBufSharingUnmanagedBuffer) {\n  testIOBufSharingUnmanagedBuffer<CompactSerializer>();\n}\n\nTEST(SerializationTest, BinarySerializerIOBufSharingUnmanagedBuffer) {\n  testIOBufSharingUnmanagedBuffer<BinarySerializer>();\n}\n\nTEST(SerializationTest, CompactSerializerIOBufSharingManagedBuffer) {\n  testIOBufSharingManagedBuffer<CompactSerializer>();\n}\n\nTEST(SerializationTest, BinarySerializerIOBufSharingManagedBuffer) {\n  testIOBufSharingManagedBuffer<BinarySerializer>();\n}\n","avg_line_length":26.4346793349,"max_line_length":78,"alphanum_fraction":0.7134513433,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1230,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"\n\/*\n    Olimp\u00edada Brasileira de Inform\u00e1tica\n    Seletiva para a IOI, 2002\n    Problema: Biblioteca \u00d3tima\n    \n    Data de submiss\u00e3o: 22\/05\/2012\n    Autor da solu\u00e7\u00e3o: Luiz Rodrigo <@lurodrigo> <luizrodri.go@hotmail.com>\n    Tags: programacao-dinamica\n    Complexidade: O(n\u00b3)\n*\/\n\n#include <iostream>\n#include <cstdio>\nusing namespace std;\n\nint s[62], c[62], m[62][62];\n\nint sum(int i, int j) {\n    if ( i > j ) return 0;\n    return s[j] - s[i-1];\n}\n\nint mincost(int n) {\n    int i, j, k, l;\n    \n    for (i = 1; i <= n+1; i++)\n        for (j = 0; j <= n; j++)\n            m[i][j] = 0;\n            \n    for (i = 1; i <= j; i++)\n        s[i] = s[i-1] + c[i];\n    \n    for (l = 2; l <= n; l++)\n        for (i = 1, j = i+l-1; j <= n; i++, j++)\n            for (m[i][j] = 1 << 28, k = i; k <= j; k++)\n                m[i][j] = min(m[i][j], m[i][k-1] + sum(i, k-1) +\n                    m[k+1][j] + sum(k+1, j));\n         \n    return m[1][n];\n}\n\nint main() {\n\n    int i, n, teste=1;\n    \n    while (true) {\n        cin >> n;\n        \n        if ( n == 0 )\n            break;\n            \n        for (i = 1; i <= n; i++)\n            cin >> c[i];\n           \n        printf(\"Teste %d\\n%d\\n\\n\", teste++, mincost(n));\n    }\n\n    return 0;\n}\n","avg_line_length":20.1639344262,"max_line_length":74,"alphanum_fraction":0.4105691057,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":422245,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":325.0,"content":"#include <cassert>\r\n#include <algorithm>\r\n#include <set>\r\n\r\n#include <wiz\/compiler\/compiler.h>\r\n\r\n#include <wiz\/ast\/expression.h>\r\n#include <wiz\/ast\/statement.h>\r\n#include <wiz\/ast\/type_expression.h>\r\n#include <wiz\/compiler\/bank.h>\r\n#include <wiz\/compiler\/config.h>\r\n#include <wiz\/compiler\/ir_node.h>\r\n#include <wiz\/compiler\/builtins.h>\r\n#include <wiz\/compiler\/definition.h>\r\n#include <wiz\/compiler\/symbol_table.h>\r\n#include <wiz\/compiler\/operations.h>\r\n#include <wiz\/parser\/token.h>\r\n#include <wiz\/utility\/misc.h>\r\n#include <wiz\/utility\/text.h>\r\n#include <wiz\/utility\/reader.h>\r\n#include <wiz\/utility\/report.h>\r\n#include <wiz\/utility\/writer.h>\r\n#include <wiz\/utility\/scope_guard.h>\r\n#include <wiz\/utility\/import_manager.h>\r\n\r\nnamespace wiz {\r\n    Compiler::Compiler(\r\n        FwdUniquePtr<const Statement> program,\r\n        Platform* platform,\r\n        StringPool* stringPool,\r\n        Config* config,\r\n        ImportManager* importManager,\r\n        Report* report,\r\n        std::unordered_map<StringView, FwdUniquePtr<const Expression>> defines)\r\n    : program(std::move(program)),\r\n    platform(platform),\r\n    stringPool(stringPool),\r\n    config(config),\r\n    importManager(importManager),\r\n    report(report),\r\n    builtins(stringPool, platform, std::move(defines)) {\r\n        currentInlineSite = &defaultInlineSite;\r\n    }\r\n\r\n    Compiler::~Compiler() {}\r\n\r\n    bool Compiler::compile() {\r\n        return reserveDefinitions(program.get())\r\n        && resolveDefinitionTypes()\r\n        && reserveStorage(program.get())\r\n        && emitStatementIr(program.get())\r\n        && generateCode();\r\n    }\r\n\r\n    Report* Compiler::getReport() const {\r\n        return report;\r\n    }\r\n\r\n    const Statement* Compiler::getProgram() const {\r\n        return program.get();\r\n    }\r\n\r\n    std::vector<const Bank*> Compiler::getRegisteredBanks() const {\r\n        std::vector<const Bank*> results;\r\n        results.reserve(registeredBanks.size());\r\n\r\n        for (const auto& bank : registeredBanks) {\r\n            results.push_back(bank.get());\r\n        }\r\n        return results;\r\n    }\r\n\r\n    std::vector<const Definition*> Compiler::getRegisteredDefinitions() const {\r\n        std::vector<const Definition*> results;\r\n\r\n        results.reserve(definitionPool.size());\r\n        for (const auto& definition : definitionPool) {\r\n            results.push_back(definition.get());\r\n        }\r\n\r\n        for (const auto& scope : registeredScopes) {\r\n            scope->getDefinitions(results);\r\n        }\r\n\r\n        std::sort(results.begin(), results.end(),\r\n            [](const Definition* a, const Definition* b) {\r\n                if (a->name.getLength() > 0 && (a->name[0] == '$' || a->name[0] == '%')\r\n                && b->name.getLength() > 0 && (b->name[0] != '$' && b->name[0] != '%')) {\r\n                    return false;\r\n                } else if (a->name.getLength() > 0 && (a->name[0] != '$' && a->name[0] != '%')\r\n                && b->name.getLength() > 0 && (b->name[0] == '$' || b->name[0] == '%')) {\r\n                    return true;\r\n                } else if (a->name != b->name) {\r\n                    return a->name < b->name;\r\n                } else {\r\n                    return a < b;\r\n                }\r\n            });\r\n\r\n        return results;\r\n    }\r\n\r\n    const Builtins& Compiler::getBuiltins() const {\r\n        return builtins;\r\n    }\r\n\r\n    std::uint32_t Compiler::getModeFlags() const {\r\n        return modeFlags;\r\n    }\r\n\r\n    SymbolTable* Compiler::getOrCreateStatementScope(StringView name, const Statement* statement, SymbolTable* parentScope) {\r\n        auto& statementScopes = currentInlineSite->statementScopes;\r\n        const auto match = statementScopes.find(statement);\r\n        if (match == statementScopes.end()) {\r\n            const auto scope = registeredScopes.addNew(parentScope, name);\r\n            statementScopes[statement] = scope;\r\n            return scope;\r\n        } else {\r\n            return match->second;\r\n        }\r\n    }\r\n\r\n    SymbolTable* Compiler::findStatementScope(const Statement* statement) const {\r\n        return currentInlineSite->statementScopes.find(statement)->second;\r\n    }\r\n\r\n    SymbolTable* Compiler::bindStatementScope(const Statement* statement, SymbolTable* scope) {\r\n        currentInlineSite->statementScopes[statement] = scope;\r\n        return scope;\r\n    }\r\n\r\n    SymbolTable* Compiler::findModuleScope(StringView path) const {\r\n        const auto scope = moduleScopes.find(path);\r\n        if (scope != moduleScopes.end()) {\r\n            return scope->second;\r\n        }\r\n        return nullptr;\r\n    }\r\n\r\n    SymbolTable* Compiler::bindModuleScope(StringView path, SymbolTable* scope) {\r\n        moduleScopes[path] = scope;\r\n        return scope;\r\n    }\r\n\r\n    void Compiler::enterScope(SymbolTable* nextScope) {\r\n        scopeStack.push_back(currentScope);\r\n        currentScope = nextScope;\r\n    }\r\n\r\n    void Compiler::exitScope() {\r\n        if (scopeStack.size() > 0) {\r\n            currentScope = scopeStack.back();\r\n            scopeStack.pop_back();\r\n        } else {\r\n            currentScope = nullptr;\r\n        }\r\n    }\r\n\r\n    void Compiler::enterInlineSite(InlineSite* nextInlineSite) {\r\n        inlineSiteStack.push_back(currentInlineSite);\r\n        currentInlineSite = nextInlineSite;\r\n    }\r\n\r\n    void Compiler::exitInlineSite() {\r\n        if (inlineSiteStack.size() > 0) {\r\n            currentInlineSite = inlineSiteStack.back();\r\n            inlineSiteStack.pop_back();\r\n        } else {\r\n            currentInlineSite = &defaultInlineSite;\r\n        }\r\n    }\r\n\r\n    bool Compiler::enterLetExpression(StringView name, SourceLocation location) {  \r\n        if (letExpressionStack.size() >= MaxLetRecursionDepth) {\r\n            report->error(\"stack overflow encountered during `let` expression evaluation\", location, ReportErrorFlags::Continued);\r\n            report->error(\"internal recursion limit is \" + std::to_string(MaxLetRecursionDepth), location, ReportErrorFlags::Continued);\r\n            report->error(\"stack trace:\", location, ReportErrorFlags::Continued);\r\n            for (std::size_t i = 0; i != letExpressionStack.size(); ++i) {\r\n                const auto& item = letExpressionStack[i];\r\n                report->log(\"#\" + std::to_string(i + 1) + \" - \" + item.location.toString() + \" in expression `\" + item.name.toString() + \"`\");\r\n            }\r\n            report->error(\"stopping compilation due to previous error\", location, ReportErrorFlags::Fatal);\r\n            return false;\r\n        }\r\n\r\n        letExpressionStack.emplace_back(name, location);\r\n        return true;\r\n    }\r\n\r\n    void Compiler::exitLetExpression() {\r\n        letExpressionStack.pop_back();    \r\n    }\r\n\r\n    Definition* Compiler::createAnonymousLabelDefinition(StringView prefix) {\r\n        const auto suffix = ++labelSuffixes[prefix];\r\n        const auto labelId = stringPool->intern(prefix.toString() + std::to_string(suffix));\r\n        const auto result = definitionPool.addNew(Definition::Func(true, false, false, BranchKind::None, builtins.getUnitTuple(), currentScope, nullptr), labelId, nullptr);\r\n        auto& func = result->func;\r\n        func.resolvedSignatureType = makeFwdUnique<const TypeExpression>(TypeExpression::Function(false, {}, func.returnTypeExpression->clone()), func.returnTypeExpression->location);\r\n        return result;\r\n    }\r\n\r\n    void Compiler::raiseUnresolvedIdentifierError(const std::vector<StringView>& pieces, std::size_t pieceIndex, SourceLocation location) {\r\n        report->error(\r\n            \"could not resolve identifier `\" + text::join(pieces.begin(), pieces.begin() + pieceIndex + 1, \".\") + \"`\"\r\n            + (pieceIndex < pieces.size() - 1\r\n                ? \" (of `\" + text::join(pieces.begin(), pieces.end(), \".\") + \"`)\"\r\n                : \"\"),\r\n            location);\r\n    }\r\n    \r\n    std::pair<Definition*, std::size_t> Compiler::resolveIdentifier(const std::vector<StringView>& pieces, SourceLocation location) {\r\n        if (pieces.empty()) {\r\n            raiseUnresolvedIdentifierError(pieces, 0, location);\r\n            return {nullptr, 0};\r\n        }\r\n\r\n        auto& previousResults = resolveIdentifierTempState.previousResults;\r\n        auto& results = resolveIdentifierTempState.results;\r\n        previousResults.clear();\r\n        results.clear();\r\n\r\n        std::size_t pieceIndex;\r\n        for (pieceIndex = 0; pieceIndex != pieces.size(); ++pieceIndex) {\r\n            const auto piece = pieces[pieceIndex];\r\n\r\n            if (previousResults.empty()) {\r\n                currentScope->findUnqualifiedDefinitions(piece, results);\r\n            } else {\r\n                for (const auto definition : previousResults) {\r\n                    if (const auto ns = definition->tryGet<Definition::Namespace>()) {\r\n                        ns->environment->findMemberDefinitions(piece, results);\r\n                    }\r\n                }\r\n            }\r\n\r\n            if (results.size() == 0) {\r\n                break;\r\n            }\r\n\r\n            const auto firstMatch = *results.begin();\r\n\r\n            if (pieceIndex == pieces.size() - 1 || firstMatch->kind != DefinitionKind::Namespace) {\r\n                if (results.size() == 1) {\r\n                    return {firstMatch, pieceIndex};\r\n                } else {\r\n                    const auto partiallyQualifiedName = text::join(pieces.begin(), pieces.begin() + pieceIndex + 1, \".\");\r\n\r\n                    report->error(\r\n                        \"identifier `\" + partiallyQualifiedName + \"`\"\r\n                        + (pieceIndex < pieces.size() - 1\r\n                            ? \" (of `\" + text::join(pieces.begin(), pieces.end(), \".\") + \"`)\"\r\n                            : \"\")\r\n                        + \" is ambiguous\",\r\n                        location,\r\n                        ReportErrorFlags::Continued);\r\n\r\n                    for (const auto result : results) {\r\n                        report->error(\"`\" + partiallyQualifiedName + \"` is defined here, by \" + result->declaration->getDescription().toString(), result->declaration->location, ReportErrorFlags::Continued);\r\n                    }\r\n\r\n                    report->error(\"identifier must be manually disambiguated\\n\", location);\r\n                    return {nullptr, pieceIndex};\r\n                }\r\n            }\r\n\r\n            previousResults.swap(results);\r\n            results.clear();\r\n        }\r\n\r\n        raiseUnresolvedIdentifierError(pieces, pieceIndex, location);\r\n        return {nullptr, pieceIndex};\r\n    }\r\n\r\n    FwdUniquePtr<const TypeExpression> Compiler::reduceTypeExpression(const TypeExpression* typeExpression) {\r\n        switch (typeExpression->kind) {\r\n            case TypeExpressionKind::Array: {\r\n                const auto& arrayType = typeExpression->array;\r\n                auto reducedElementType = reduceTypeExpression(arrayType.elementType.get());\r\n                auto reducedSize = arrayType.size != nullptr ? reduceExpression(arrayType.size.get()) : nullptr;\r\n                if (reducedElementType != nullptr && (arrayType.size == nullptr || reducedSize != nullptr)) {\r\n                    if (reducedSize != nullptr) {\r\n                        if (const auto sizeLiteral = reducedSize->tryGet<Expression::IntegerLiteral>()) {\r\n                            if (sizeLiteral->value.isNegative()) {\r\n                                report->error(\"array size must be a non-negative integer, but got size of `\" + sizeLiteral->value.toString() + \"` instead\", reducedSize->location);\r\n                                return nullptr;\r\n                            }\r\n                        } else {\r\n                            report->error(\"array size must be a compile-time integer literal\", reducedSize->location);\r\n                            return nullptr;\r\n                        }\r\n                    }\r\n                    return makeFwdUnique<const TypeExpression>(TypeExpression::Array(std::move(reducedElementType), std::move(reducedSize)), typeExpression->location);\r\n                } else {\r\n                    return nullptr;\r\n                }\r\n            }\r\n            case TypeExpressionKind::DesignatedStorage: {\r\n                const auto& designatedStorageType = typeExpression->designatedStorage;\r\n                auto reducedElementType = reduceTypeExpression(designatedStorageType.elementType.get());\r\n                auto reducedHolder = reduceExpression(designatedStorageType.holder.get());\r\n\r\n                if (reducedElementType != nullptr && reducedHolder != nullptr) {\r\n                    const auto elementSize = calculateStorageSize(reducedElementType.get(), \"designated storage element type\"_sv);\r\n                    const auto holderSize = calculateStorageSize(reducedHolder->info->type.get(), \"designated storage holder\"_sv);\r\n\r\n                    if (!elementSize.hasValue() || !holderSize.hasValue() || *elementSize != *holderSize) {\r\n                        report->error(\"holder expression of type `\"\r\n                            + getTypeName(reducedHolder->info->type.get())\r\n                            + \"` is not compatible with element type `\"\r\n                            + getTypeName(reducedElementType.get())\r\n                            + \"` of designated storage type `\"\r\n\t\t\t\t\t\t\t+ getTypeName(typeExpression) + \"`\",\r\n                            reducedHolder->location);\r\n                        return nullptr;\r\n                    }\r\n\r\n                    if ((reducedHolder->info->qualifiers & Qualifiers::LValue) == Qualifiers::None) {\r\n                        report->error(\"holder for designated storage type must be valid L-value\", reducedHolder->location);\r\n                        return nullptr;\r\n                    }\r\n                    if ((reducedHolder->info->qualifiers & Qualifiers::Const) != Qualifiers::None) {\r\n                        report->error(\"holder for designated storage type cannot be `const`\", reducedHolder->location);\r\n                        return nullptr;\r\n                    }\r\n                    if ((reducedHolder->info->qualifiers & Qualifiers::WriteOnly) != Qualifiers::None) {\r\n                        report->error(\"holder for designated storage type cannot be `writeonly`\", reducedHolder->location);\r\n                        return nullptr;\r\n                    }\r\n\r\n                    return makeFwdUnique<const TypeExpression>(TypeExpression::DesignatedStorage(std::move(reducedElementType), std::move(reducedHolder)), typeExpression->location);\r\n                }\r\n                return nullptr;\r\n            }\r\n            case TypeExpressionKind::Function: {\r\n                const auto& funcType = typeExpression->function;\r\n                auto reducedReturnType = reduceTypeExpression(funcType.returnType.get());\r\n                if (reducedReturnType == nullptr) {\r\n                    return nullptr;\r\n                }\r\n\r\n                std::vector<UniquePtr<const TypeExpression::Function::Parameter>> reducedParameters;\r\n                reducedParameters.reserve(funcType.parameters.size());\r\n                for (const auto& parameter : funcType.parameters) {\r\n                    auto reducedParameterType = reduceTypeExpression(parameter->parameterType.get());\r\n                    if (reducedParameterType == nullptr) {\r\n                        return nullptr;\r\n                    }\r\n                    reducedParameters.push_back(makeUnique<TypeExpression::Function::Parameter>(parameter->name, std::move(reducedParameterType)));\r\n                }\r\n                return makeFwdUnique<const TypeExpression>(TypeExpression::Function(funcType.far, std::move(reducedParameters), std::move(reducedReturnType)), typeExpression->location);\r\n            }\r\n            case TypeExpressionKind::Identifier: {\r\n                const auto& identifierType = typeExpression->identifier;\r\n                const auto& pieces = identifierType.pieces;\r\n                const auto resolveResult = resolveIdentifier(pieces, typeExpression->location);\r\n\r\n                if (resolveResult.first == nullptr) {\r\n                    return nullptr;\r\n                }\r\n                if (resolveResult.second < pieces.size() - 1) {\r\n                    raiseUnresolvedIdentifierError(pieces, resolveResult.second, typeExpression->location);\r\n                    return nullptr;\r\n                }\r\n\r\n                const auto definition = resolveResult.first;\r\n\r\n                if (isTypeDefinition(definition)) {\r\n                    return makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(definition, pieces), typeExpression->location); \r\n                } else if (const auto typeAlias = definition->tryGet<Definition::TypeAlias>()) {                  \r\n                    if (typeAlias->resolvedType == nullptr) {\r\n                        report->error(\"encountered a reference to typealias `\" + text::join(pieces.begin(), pieces.end(), \".\") + \"` before its underlying type was known\", typeExpression->location);\r\n                        return nullptr;\r\n                    } else {\r\n                        return typeAlias->resolvedType->clone(); \r\n                    }\r\n                } else {\r\n                    report->error(\"`\" + text::join(pieces.begin(), pieces.end(), \".\") + \"` is not a valid type\", typeExpression->location);\r\n                    return nullptr;\r\n                }\r\n            }\r\n            case TypeExpressionKind::Pointer: {\r\n                const auto& pointerType = typeExpression->pointer;\r\n                auto reducedElementType = reduceTypeExpression(pointerType.elementType.get());\r\n                if (reducedElementType != nullptr) { \r\n                    return makeFwdUnique<const TypeExpression>(TypeExpression::Pointer(std::move(reducedElementType), pointerType.qualifiers), typeExpression->location);\r\n                } else {\r\n                    return nullptr;\r\n                }\r\n            }\r\n            case TypeExpressionKind::ResolvedIdentifier: {\r\n                const auto& resolvedIdentifier = typeExpression->resolvedIdentifier;\r\n                return makeFwdUnique<const TypeExpression>(resolvedIdentifier, typeExpression->location);\r\n            }\r\n            case TypeExpressionKind::Tuple: {\r\n                const auto& tupleType = typeExpression->tuple;\r\n                std::vector<FwdUniquePtr<const TypeExpression>> reducedElementTypes;\r\n                reducedElementTypes.reserve(tupleType.elementTypes.size());\r\n                for (const auto& elementType : tupleType.elementTypes) {\r\n                    auto reducedElementType = reduceTypeExpression(elementType.get());\r\n                    if (reducedElementType == nullptr) {\r\n                        return nullptr;\r\n                    }                    \r\n                    reducedElementTypes.push_back(std::move(reducedElementType));\r\n                }\r\n                return makeFwdUnique<const TypeExpression>(TypeExpression::Tuple(std::move(reducedElementTypes)), typeExpression->location);            \r\n            }\r\n            case TypeExpressionKind::TypeOf: {\r\n                const auto& typeOf = typeExpression->typeOf;\r\n                auto reducedExpression = reduceExpression(typeOf.expression.get());    \r\n                if (reducedExpression == nullptr) {\r\n                    return nullptr;\r\n                }\r\n                return reducedExpression->info->type->clone();\r\n            }\r\n            default: std::abort(); return nullptr;\r\n        }\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::reduceExpression(const Expression* expression) {\r\n        switch (expression->kind) {\r\n            case ExpressionKind::ArrayComprehension: {\r\n                const auto& arrayComprehension = expression->arrayComprehension;\r\n                auto reducedSequence = reduceExpression(arrayComprehension.sequence.get());\r\n                if (reducedSequence == nullptr) {\r\n                    return nullptr;\r\n                }\r\n\r\n                const auto length = tryGetSequenceLiteralLength(reducedSequence.get());\r\n                if (!length.hasValue()) {\r\n                    report->error(\"source for array comprehension must be a valid compile-time sequence\", expression->location);\r\n                    return nullptr;\r\n                }\r\n\r\n                std::vector<FwdUniquePtr<const Expression>> computedItems;\r\n                computedItems.reserve(*length);\r\n\r\n                auto scope = std::make_unique<SymbolTable>(currentScope, StringView());\r\n                auto tempDeclaration = statementPool.addNew(Statement::InternalDeclaration(), expression->location);\r\n                auto tempDefinition = scope->createDefinition(report, Definition::Let({}, nullptr), arrayComprehension.name, tempDeclaration);\r\n                auto& tempLetDefinition = tempDefinition->let;\r\n\r\n                const TypeExpression* elementType = nullptr;\r\n\r\n                for (std::size_t i = 0; i != *length; ++i) {\r\n                    auto sourceItem = getSequenceLiteralItem(reducedSequence.get(), i);\r\n                    tempLetDefinition.expression = sourceItem.get();\r\n\r\n                    enterScope(scope.get());\r\n                    auto computedItem = reduceExpression(arrayComprehension.expression.get());\r\n                    exitScope();\r\n\r\n                    if (computedItem != nullptr) {\r\n                        if (elementType == nullptr) {\r\n                            elementType = computedItem->info->type.get();\r\n                        } else if (!isTypeEquivalent(computedItem->info->type.get(), elementType)) {\r\n                            if (!canNarrowExpression(computedItem.get(), elementType)) {\r\n                                report->error(\"array element of type `\" + getTypeName(computedItem->info->type.get()) + \"` at iteration \" + std::to_string(i) + \" does not match first element type `\" + getTypeName(elementType) + \"` in comprehension\", computedItem->location);\r\n                                return nullptr;\r\n                            }\r\n\r\n                            computedItem = createConvertedExpression(computedItem.get(), elementType);\r\n                        }\r\n\r\n                        computedItems.push_back(std::move(computedItem));\r\n                    } else {\r\n                        return nullptr;\r\n                    }\r\n                }\r\n\r\n                return createArrayLiteralExpression(std::move(computedItems), elementType, expression->location);\r\n            }\r\n            case ExpressionKind::ArrayPadLiteral: {\r\n                const auto& arrayPadLiteral = expression->arrayPadLiteral;\r\n                auto reducedValueExpression = reduceExpression(arrayPadLiteral.valueExpression.get());\r\n                auto reducedSizeExpression = reduceExpression(arrayPadLiteral.sizeExpression.get());\r\n\r\n                if (reducedValueExpression == nullptr || reducedSizeExpression == nullptr) {\r\n                    return nullptr;\r\n                }\r\n\r\n                const auto reducedSizeLiteral = reducedSizeExpression->tryGet<Expression::IntegerLiteral>();\r\n                if (reducedSizeLiteral == nullptr) {\r\n                    report->error(\"array pad size must be a compile-time integer literal\", expression->location);\r\n                    return nullptr;\r\n                }\r\n                if (reducedSizeLiteral->value >= Int128(SIZE_MAX)) {\r\n                    report->error(\"array pad size of `\" + reducedSizeLiteral->value.toString() + \"` is too big.\", expression->location);\r\n                    return nullptr;\r\n                }\r\n\r\n                const auto length = static_cast<std::size_t>(reducedSizeLiteral->value);\r\n                std::vector<FwdUniquePtr<const Expression>> items;\r\n                items.reserve(length);\r\n\r\n                const TypeExpression* elementType = reducedValueExpression->info->type.get();\r\n                if (length > 0) {\r\n                    for (std::size_t i = 0; i != length - 1; ++i) {\r\n                        items.push_back(reducedValueExpression->clone());\r\n                    }\r\n\r\n                    items.push_back(std::move(reducedValueExpression));\r\n                }\r\n\r\n                return createArrayLiteralExpression(std::move(items), elementType, expression->location);\r\n            }\r\n            case ExpressionKind::ArrayLiteral: {\r\n                const auto& arrayLiteral = expression->arrayLiteral;\r\n                const auto& items = arrayLiteral.items;\r\n\r\n                std::vector<FwdUniquePtr<const Expression>> reducedItems;\r\n                reducedItems.reserve(items.size());\r\n\r\n                const TypeExpression* elementType = nullptr;\r\n\r\n                for (std::size_t i = 0; i != items.size(); ++i) {\r\n                    const auto& item = items[i];\r\n                    auto reducedItem = reduceExpression(item.get());\r\n\r\n                    if (reducedItem != nullptr) {\r\n                        if (elementType == nullptr) {\r\n                            elementType = reducedItem->info->type.get();\r\n                        } else if (!isTypeEquivalent(reducedItem->info->type.get(), elementType)) {\r\n                            if (!canNarrowExpression(reducedItem.get(), elementType)) {\r\n                                report->error(\"array element of type `\" + getTypeName(reducedItem->info->type.get()) + \"` at index \" + std::to_string(i) + \" does not match first element type `\" + getTypeName(elementType) + \"`\", reducedItem->location);\r\n                                return nullptr;\r\n                            }\r\n\r\n                            reducedItem = createConvertedExpression(reducedItem.get(), elementType);\r\n                        }\r\n\r\n                        reducedItems.push_back(std::move(reducedItem));\r\n                    } else {\r\n                        return nullptr;\r\n                    }\r\n                }\r\n\r\n                return createArrayLiteralExpression(std::move(reducedItems), elementType, expression->location);\r\n            }\r\n            case ExpressionKind::BinaryOperator: {\r\n                const auto& binaryOperator = expression->binaryOperator;\r\n                const auto op = binaryOperator.op;\r\n                auto left = reduceExpression(binaryOperator.left.get());\r\n                auto right = reduceExpression(binaryOperator.right.get());\r\n                if (!left || !right) {\r\n                    return nullptr;\r\n                }\r\n\r\n                if (op == BinaryOperatorKind::Indexing || op == BinaryOperatorKind::BitIndexing || op == BinaryOperatorKind::UnalignedIndexing) {\r\n                    if ((right->info->qualifiers & Qualifiers::WriteOnly) != Qualifiers::None) {\r\n                        report->error(\"subscript of \" + getBinaryOperatorName(op).toString() + \" cannot be `writeonly`\", right->location);\r\n                        return nullptr;\r\n                    }\r\n                } else if (op == BinaryOperatorKind::Assignment) {\r\n                    if ((right->info->qualifiers & Qualifiers::WriteOnly) != Qualifiers::None) {\r\n                        report->error(\"right-hand side of assignment `=` cannot be `writeonly`\", right->location);\r\n                        return nullptr;\r\n                    }\r\n                } else {\r\n                    if ((left->info->qualifiers & Qualifiers::WriteOnly) != Qualifiers::None) {\r\n                        report->error(\"left operand to \" + getBinaryOperatorName(op).toString() + \" cannot be `writeonly`\", expression->location);                                               \r\n                        return nullptr;\r\n                    } else if ((right->info->qualifiers & Qualifiers::WriteOnly) != Qualifiers::None) {\r\n                        report->error(\"right operand to \" + getBinaryOperatorName(op).toString() + \" cannot be `writeonly`\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n                }\r\n\r\n                \/\/ attempt to reduce expression if possible, and return expression if typed.\r\n                switch (op) {\r\n                    default: case BinaryOperatorKind::None: std::abort(); return nullptr;\r\n\r\n                    \/\/ Run-time assignment. (T, T) -> T (returns left-hand side lvalue)\r\n                    case BinaryOperatorKind::Assignment: {\r\n                        if ((left->info->qualifiers & Qualifiers::LValue) == Qualifiers::None) {\r\n                            report->error(\"left-hand side of assignment `=` must be valid L-value\", expression->location);\r\n                            return nullptr;\r\n                        }\r\n                        if ((left->info->qualifiers & Qualifiers::Const) != Qualifiers::None) {\r\n                            report->error(\"left-hand side of assignment `=` cannot be `const`\", expression->location);\r\n                            return nullptr;\r\n                        }\r\n\r\n                        if (const auto resultType = findCompatibleAssignmentType(right.get(), left->info->type.get())) {\r\n                            const auto qualifiers = left->info->qualifiers;\r\n                            return makeFwdUnique<const Expression>(\r\n                                Expression::BinaryOperator(op, std::move(left), createConvertedExpression(right.get(), resultType)), expression->location,\r\n                                ExpressionInfo(EvaluationContext::RunTime, resultType->clone(), qualifiers));\r\n                        }\r\n\r\n                        report->error(\"left-hand side of type `\" + getTypeName(left->info->type.get()) + \"` cannot be assigned `\" + getTypeName(right->info->type.get()) + \"` expression\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n\r\n                    \/\/ Run-time arithmetic. (integer, integer) -> integer\r\n                    case BinaryOperatorKind::AdditionWithCarry:\r\n                    case BinaryOperatorKind::SubtractionWithCarry:\r\n                    case BinaryOperatorKind::LeftRotateWithCarry:\r\n                    case BinaryOperatorKind::RightRotateWithCarry: {\r\n                        if (const auto resultType = findCompatibleBinaryArithmeticExpressionType(left.get(), right.get())) {\r\n                            return makeFwdUnique<const Expression>(\r\n                                Expression::BinaryOperator(op, std::move(left), std::move(right)),\r\n                                expression->location,\r\n                                ExpressionInfo(EvaluationContext::RunTime, resultType->clone(), Qualifiers::None));\r\n                        } else {\r\n                            report->error(getBinaryOperatorName(op).toString() + \" is not defined between provided operand types `\" + getTypeName(left->info->type.get()) + \"` and `\" + getTypeName(right->info->type.get()) + \"`\", expression->location);\r\n                            return nullptr;\r\n                        }\r\n                    }\r\n    \r\n                    \/\/ Arithmetic.\r\n                    \/\/ (integer, integer) -> integer\r\n                    \/\/ (bool, bool) -> bool\r\n                    case BinaryOperatorKind::Addition:\r\n                    case BinaryOperatorKind::BitwiseAnd:\r\n                    case BinaryOperatorKind::BitwiseOr:\r\n                    case BinaryOperatorKind::BitwiseXor:\r\n                    case BinaryOperatorKind::Division:\r\n                    case BinaryOperatorKind::Modulo:\r\n                    case BinaryOperatorKind::Multiplication:\r\n                    case BinaryOperatorKind::LeftShift:\r\n                    case BinaryOperatorKind::RightShift:\r\n                    case BinaryOperatorKind::Subtraction:\r\n                    case BinaryOperatorKind::LogicalLeftShift:\r\n                    case BinaryOperatorKind::LogicalRightShift: {\r\n                        if (isBooleanType(left->info->type.get()) && isBooleanType(right->info->type.get())) {\r\n                            return simplifyBinaryLogicalExpression(expression, op, std::move(left), std::move(right));\r\n                        }\r\n\r\n                        return simplifyBinaryArithmeticExpression(expression, op, std::move(left), std::move(right));\r\n                    }\r\n\r\n                    \/\/ Array concatenation. ([T; m], [T; n]) -> [T; m + n]\r\n                    case BinaryOperatorKind::Concatenation: {\r\n                        if (const auto resultType = findCompatibleConcatenationExpressionType(left.get(), right.get())) {\r\n                            bool isLeftArray = left->kind == ExpressionKind::ArrayLiteral;\r\n                            bool isLeftString = left->kind == ExpressionKind::StringLiteral;\r\n                            bool isRightArray = right->kind == ExpressionKind::ArrayLiteral;\r\n                            bool isRightString = right->kind == ExpressionKind::StringLiteral;\r\n\r\n                            \/\/ NOTE: Assumes if compatible type was found, it must be [u8], because string literals are [u8]. Hopefully this is always true!\r\n                            if (isLeftString && isRightArray) {\r\n                                const auto leftValue = left->stringLiteral.value;\r\n                                const auto leftLength = leftValue.getLength();\r\n                                const auto& rightItems = right->arrayLiteral.items;\r\n                                const auto rightLength = rightItems.size();\r\n\r\n                                std::string result(leftLength + rightLength, 0);\r\n                                for (std::size_t i = 0; i != leftLength; ++i) {\r\n                                    result[i] = leftValue.getData()[i];\r\n                                }\r\n                                for (std::size_t i = 0; i != rightLength; ++i) {\r\n                                    const auto& rightItem = rightItems[i];\r\n                                    result[leftLength + i] = static_cast<std::uint8_t>(rightItem->integerLiteral.value);\r\n                                }\r\n\r\n                                return createStringLiteralExpression(stringPool->intern(result), expression->location);\r\n                            } else if (isLeftArray && isRightString) {\r\n                                const auto& leftItems = left->arrayLiteral.items;\r\n                                const auto leftLength = leftItems.size();\r\n                                const auto rightValue = right->stringLiteral.value;\r\n                                const auto rightLength = rightValue.getLength();\r\n\r\n                                std::string result(leftLength + rightLength, 0);\r\n                                for (std::size_t i = 0; i != leftLength; ++i) {\r\n                                    const auto& leftItem = leftItems[i];\r\n                                    result[i] = static_cast<std::uint8_t>(leftItem->integerLiteral.value);\r\n                                }\r\n                                for (std::size_t i = 0; i != rightLength; ++i) {\r\n                                    result[leftLength + i] = rightValue.getData()[i];\r\n                                }\r\n\r\n                                return createStringLiteralExpression(stringPool->intern(result), expression->location);\r\n                            }\r\n                            \r\n                            if (isLeftString && isRightString) {\r\n                                const auto result = stringPool->intern(\r\n                                    left->stringLiteral.value.toString()\r\n                                    + right->stringLiteral.value.toString());\r\n\r\n                                return createStringLiteralExpression(result, expression->location);\r\n                            } else if (isLeftArray && isRightArray) {\r\n                                const auto& leftItems = left->arrayLiteral.items;\r\n                                const auto& rightItems = right->arrayLiteral.items;\r\n                                const auto elementType = resultType->array.elementType.get();\r\n\r\n                                std::vector<FwdUniquePtr<const Expression>> reducedItems;\r\n                                reducedItems.reserve(leftItems.size() + rightItems.size());\r\n\r\n                                for (const auto& item : leftItems) {\r\n                                    reducedItems.push_back(createConvertedExpression(item.get(), elementType));\r\n                                }\r\n                                for (const auto& item : rightItems) {\r\n                                    reducedItems.push_back(createConvertedExpression(item.get(), elementType));\r\n                                }\r\n\r\n                                return createArrayLiteralExpression(std::move(reducedItems), elementType, expression->location);\r\n                            } else {\r\n                                report->error(getBinaryOperatorName(op).toString() + \" is only defined between compile-time array literals\", expression->location);\r\n                                return nullptr;\r\n                            }\r\n                        }\r\n                        \r\n                        report->error(getBinaryOperatorName(op).toString() + \" is not defined between provided operand types `\" + getTypeName(left->info->type.get()) + \"` and `\" + getTypeName(right->info->type.get()) + \"`\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n\r\n                    \/\/ Fixed bit-width arithmetic. (integer, integer) -> integer, where integer bit count is bounded.\r\n                    case BinaryOperatorKind::LeftRotate:\r\n                    case BinaryOperatorKind::RightRotate:{\r\n                         return simplifyBinaryRotateExpression(expression, op, std::move(left), std::move(right));\r\n                    }\r\n                                                        \r\n                    \/\/ Indexing.\r\n                    \/\/ ([T; n], integer i) -> T\r\n                    \/\/ ((T_1, T_2, ... T_n), integer i) -> T_i\r\n                    case BinaryOperatorKind::Indexing: {\r\n                        if (isIntegerType(right->info->type.get())) {\r\n                            const auto qualifiers = left->info->qualifiers & (Qualifiers::LValue | Qualifiers::Const | Qualifiers::WriteOnly | Qualifiers::Far);\r\n\r\n                            if (left->info->type->kind == TypeExpressionKind::Array) {\r\n                                if (right->kind == ExpressionKind::IntegerLiteral) {\r\n                                    const auto indexValue = right->integerLiteral.value;\r\n\r\n                                    if (left->kind == ExpressionKind::ArrayLiteral) {\r\n                                        const auto& items = left->arrayLiteral.items;\r\n\r\n                                        if (indexValue.isNegative()) {\r\n                                            report->error(\"indexing by negative integer `\" + indexValue.toString() + \"`\", expression->location);\r\n                                            return nullptr;\r\n                                        }\r\n                                        if (indexValue >= Int128(items.size())) {\r\n                                            report->error(\"indexing by `\" + indexValue.toString() + \"` exceeds array length of `\" + std::to_string(items.size()) + \"`\", expression->location);\r\n                                            return nullptr;\r\n                                        }\r\n\r\n                                        std::size_t index = static_cast<std::size_t>(indexValue);\r\n                                        return items[index]->clone();\r\n                                    } else if (left->kind == ExpressionKind::StringLiteral) {\r\n                                        const auto stringLiteral = left->stringLiteral.value;\r\n\r\n                                        if (indexValue.isNegative()) {\r\n                                            report->error(\"indexing by negative integer `\" + indexValue.toString() + \"`\", expression->location);\r\n                                            return nullptr;\r\n                                        }\r\n                                        if (indexValue >= Int128(stringLiteral.getLength())) {\r\n                                            report->error(\"indexing by `\" + indexValue.toString() + \"` exceeds array length of `\" + std::to_string(stringLiteral.getLength()) + \"`\", expression->location);\r\n                                            return nullptr;\r\n                                        }\r\n\r\n                                        std::size_t index = static_cast<std::size_t>(indexValue);\r\n                                        return makeFwdUnique<const Expression>(Expression::IntegerLiteral(Int128(static_cast<std::uint8_t>(stringLiteral[index]))), expression->location,\r\n                                            ExpressionInfo(EvaluationContext::CompileTime,\r\n                                                makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), expression->location),\r\n                                                Qualifiers::None));\r\n                                    } else if (const auto resolvedIdentifier = left->tryGet<Expression::ResolvedIdentifier>()) {\r\n                                        if (const auto varDefinition = resolvedIdentifier->definition->tryGet<Definition::Var>()) {\r\n                                            if (varDefinition->address.hasValue() && varDefinition->address->absolutePosition.hasValue()) {\r\n                                                auto resultType = left->info->type->array.elementType->clone();\r\n                                                auto addressType = makeFwdUnique<const TypeExpression>(\r\n                                                    TypeExpression::Pointer(\r\n                                                        left->info->type->array.elementType->clone(),\r\n                                                        left->info->qualifiers & (Qualifiers::Const | Qualifiers::WriteOnly | Qualifiers::Far)),\r\n                                                    resultType->location);\r\n                                                const auto pointerSizedType = (left->info->qualifiers & Qualifiers::Far) != Qualifiers::None ? platform->getFarPointerSizedType() : platform->getPointerSizedType();\r\n                                                const auto mask = Int128((1U << (8U * pointerSizedType->builtinIntegerType.size)) - 1);\r\n\r\n                                                if (const auto elementSize = calculateStorageSize(resultType.get(), \"operand\"_sv)) {\r\n                                                    return makeFwdUnique<const Expression>(\r\n                                                        Expression::UnaryOperator(\r\n                                                            UnaryOperatorKind::Indirection,\r\n                                                            makeFwdUnique<const Expression>(\r\n                                                                Expression::IntegerLiteral((Int128(varDefinition->address->absolutePosition.get()) + indexValue * Int128(*elementSize)) & mask), expression->location,\r\n                                                                ExpressionInfo(EvaluationContext::CompileTime, std::move(addressType), Qualifiers::None))),\r\n                                                        expression->location,\r\n                                                        ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), qualifiers));\r\n                                                }\r\n                                            }\r\n                                        }\r\n                                    } else if (const auto addressLiteral = left->tryGet<Expression::IntegerLiteral>()) {\r\n                                        auto resultType = left->info->type->array.elementType->clone();\r\n                                        auto addressType = makeFwdUnique<const TypeExpression>(\r\n                                            TypeExpression::Pointer(\r\n                                                left->info->type->array.elementType->clone(),\r\n                                                left->info->qualifiers & (Qualifiers::Const | Qualifiers::WriteOnly | Qualifiers::Far)),\r\n                                            resultType->location);\r\n                                        const auto pointerSizedType = (left->info->qualifiers & Qualifiers::Far) != Qualifiers::None ? platform->getFarPointerSizedType() : platform->getPointerSizedType();\r\n                                        const auto mask = Int128((1U << (8U * pointerSizedType->builtinIntegerType.size)) - 1);\r\n\r\n                                        if (const auto elementSize = calculateStorageSize(resultType.get(), \"operand\"_sv)) {\r\n                                            return makeFwdUnique<const Expression>(\r\n                                                Expression::UnaryOperator(\r\n                                                    UnaryOperatorKind::Indirection,\r\n                                                    makeFwdUnique<const Expression>(\r\n                                                        Expression::IntegerLiteral((addressLiteral->value + indexValue * Int128(*elementSize)) & mask), expression->location,\r\n                                                        ExpressionInfo(EvaluationContext::CompileTime, std::move(addressType), Qualifiers::None))),\r\n                                                expression->location,\r\n                                                ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), qualifiers));\r\n                                        }\r\n                                    }\r\n                                }\r\n\r\n                                if (left->info->type->array.elementType == nullptr) {\r\n                                    report->error(\"array has unknown element type\", expression->location);\r\n                                    return nullptr;\r\n                                }\r\n\r\n                                auto resultType = left->info->type->array.elementType->clone();\r\n\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::BinaryOperator(op, std::move(left), std::move(right)),\r\n                                    expression->location,\r\n                                    ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), qualifiers));                            \r\n                            } else if (left->info->type->kind == TypeExpressionKind::Tuple) {\r\n                                if (left->kind == ExpressionKind::TupleLiteral && right->kind == ExpressionKind::IntegerLiteral) {\r\n                                    const auto& items = left->tupleLiteral.items;\r\n                                    const auto indexValue = right->integerLiteral.value;\r\n\r\n                                    if (indexValue.isNegative()) {\r\n                                        report->error(\"indexing by negative integer `\" + indexValue.toString() + \"`\", expression->location);\r\n                                        return nullptr;\r\n                                    }\r\n                                    if (indexValue >= Int128(items.size())) {\r\n                                        report->error(\"indexing by `\" + indexValue.toString() + \"` exceeds tuple length of `\" + std::to_string(items.size()) + \"`\", expression->location);\r\n                                        return nullptr;\r\n                                    }\r\n\r\n                                    std::size_t index = static_cast<std::size_t>(indexValue);\r\n                                    return items[index]->clone();\r\n                                }\r\n\r\n                                report->error(\"tuple index must be a compile-time integer literal\", expression->location);\r\n                                return nullptr;\r\n                            } else if (const auto pointerType = left->info->type->tryGet<TypeExpression::Pointer>()) {\r\n                                const auto qualifiers = Qualifiers::LValue | (pointerType->qualifiers & (Qualifiers::Const | Qualifiers::WriteOnly | Qualifiers::Far));\r\n                                auto resultType = pointerType->elementType->clone();\r\n\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::BinaryOperator(op, std::move(left), std::move(right)),\r\n                                    expression->location,\r\n                                    ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), qualifiers));\r\n                            } else if (const auto typeDefinition = tryGetResolvedIdentifierTypeDefinition(left->info->type.get())) {\r\n                                if (typeDefinition->kind == DefinitionKind::BuiltinRangeType) {\r\n                                    if (const auto length = tryGetSequenceLiteralLength(left.get())) {\r\n                                        if (const auto indexLiteral = right->tryGet<Expression::IntegerLiteral>()) {\r\n                                            const auto indexValue = indexLiteral->value;\r\n                                            if (indexValue.isNegative()) {\r\n                                                report->error(\"indexing by negative integer `\" + indexValue.toString() + \"`\", expression->location);\r\n                                                return nullptr;\r\n                                            }\r\n                                            if (indexValue >= Int128(*length)) {\r\n                                                report->error(\"indexing by `\" + indexValue.toString() + \"` exceeds range length of `\" + std::to_string(*length) + \"`\", expression->location);\r\n                                                return nullptr;\r\n                                            }\r\n                                            return getSequenceLiteralItem(left.get(), static_cast<std::size_t>(indexValue));\r\n                                        } else {\r\n                                            report->error(\"range index must be a compile-time integer literal\", expression->location);\r\n                                            return nullptr;\r\n                                        }\r\n                                    } else {\r\n                                        report->error(\"range must known at compile-time\", expression->location);\r\n                                        return nullptr;\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                           \r\n                        report->error(getBinaryOperatorName(op).toString() + \" is not defined between provided operand types `\" + getTypeName(left->info->type.get()) + \"` and `\" + getTypeName(right->info->type.get()) + \"`\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n\r\n                    \/\/ Unaligned indexing.\r\n                    \/\/ ([T; n], integer i) -> T. in unaligned indexing, integer is an offet in bytes, not elements.\r\n                    \/\/\r\n                    \/\/ NOTE: the term being indexed must be an array or pointer type, and must have an address and size.\r\n                    \/\/ - Compile-time literals (string literals, array literals, etc) cannot be indexed in an unaligned way, because they do not have addresses.\r\n                    \/\/ - Tuples and ranges also cannot be indexed in an unaligned way, because tuples are heterogenous, and ranges are in terms of iexpr (an unsized integer).\r\n                    \/\/ - I don't want to write the compile-time version of unaligned array\/tuple access atm, even though these cases could be possible.\r\n                    case BinaryOperatorKind::UnalignedIndexing: {\r\n                        if (isIntegerType(right->info->type.get())) {\r\n                            const auto qualifiers = left->info->qualifiers & (Qualifiers::LValue | Qualifiers::Const | Qualifiers::WriteOnly | Qualifiers::Far);\r\n\r\n                            if (left->kind == ExpressionKind::ArrayLiteral) {\r\n                                report->error(\"array literals cannot be used with unaligned indexing\", expression->location);\r\n                            } else if (left->kind == ExpressionKind::StringLiteral) {\r\n                                report->error(\"string literals cannot be used with unaligned indexing\", expression->location);\r\n                            } else if (left->info->type->kind == TypeExpressionKind::Tuple) {\r\n                                report->error(\"tuples cannot be used with unaligned indexing\", expression->location);\r\n                                return nullptr;\r\n                            } else if (const auto typeDefinition = tryGetResolvedIdentifierTypeDefinition(left->info->type.get())) {\r\n                                if (typeDefinition->kind == DefinitionKind::BuiltinRangeType) {\r\n                                    report->error(\"ranges cannot be used with unaligned indexing\", expression->location);\r\n                                    return nullptr;\r\n                                }\r\n                            } else if (left->info->type->kind == TypeExpressionKind::Array) {\r\n                                if (right->kind == ExpressionKind::IntegerLiteral) {\r\n                                    const auto indexValue = right->integerLiteral.value;\r\n\r\n                                    if (const auto resolvedIdentifier = left->tryGet<Expression::ResolvedIdentifier>()) {\r\n                                        if (const auto varDefinition = resolvedIdentifier->definition->tryGet<Definition::Var>()) {\r\n                                            if (varDefinition->address.hasValue() && varDefinition->address->absolutePosition.hasValue()) {\r\n                                                auto resultType = left->info->type->array.elementType->clone();\r\n                                                auto addressType = makeFwdUnique<const TypeExpression>(\r\n                                                    TypeExpression::Pointer(\r\n                                                        left->info->type->array.elementType->clone(),\r\n                                                        left->info->qualifiers & (Qualifiers::Const | Qualifiers::WriteOnly | Qualifiers::Far)),\r\n                                                    resultType->location);\r\n                                                const auto pointerSizedType = (left->info->qualifiers & Qualifiers::Far) != Qualifiers::None ? platform->getFarPointerSizedType() : platform->getPointerSizedType();\r\n                                                const auto mask = Int128((1U << (8U * pointerSizedType->builtinIntegerType.size)) - 1);\r\n\r\n                                                return makeFwdUnique<const Expression>(\r\n                                                    Expression::UnaryOperator(\r\n                                                        UnaryOperatorKind::Indirection,\r\n                                                        makeFwdUnique<const Expression>(\r\n                                                            Expression::IntegerLiteral((Int128(varDefinition->address->absolutePosition.get()) + indexValue) & mask), expression->location,\r\n                                                            ExpressionInfo(EvaluationContext::CompileTime, std::move(addressType), Qualifiers::None))),\r\n                                                    expression->location,\r\n                                                    ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), qualifiers));\r\n                                            }\r\n                                        }\r\n                                    } else if (const auto addressLiteral = left->tryGet<Expression::IntegerLiteral>()) {\r\n                                        auto resultType = left->info->type->array.elementType->clone();\r\n                                        auto addressType = makeFwdUnique<const TypeExpression>(\r\n                                            TypeExpression::Pointer(\r\n                                                left->info->type->array.elementType->clone(),\r\n                                                left->info->qualifiers & (Qualifiers::Const | Qualifiers::WriteOnly | Qualifiers::Far)),\r\n                                            resultType->location);\r\n                                        const auto pointerSizedType = (left->info->qualifiers & Qualifiers::Far) != Qualifiers::None ? platform->getFarPointerSizedType() : platform->getPointerSizedType();\r\n                                        const auto mask = Int128((1U << (8U * pointerSizedType->builtinIntegerType.size)) - 1);\r\n\r\n                                        return makeFwdUnique<const Expression>(\r\n                                            Expression::UnaryOperator(\r\n                                                UnaryOperatorKind::Indirection,\r\n                                                makeFwdUnique<const Expression>(\r\n                                                    Expression::IntegerLiteral((addressLiteral->value + indexValue) & mask), expression->location,\r\n                                                    ExpressionInfo(EvaluationContext::CompileTime, std::move(addressType), Qualifiers::None))),\r\n                                            expression->location,\r\n                                            ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), qualifiers));\r\n                                    }\r\n                                }\r\n\r\n                                if (left->info->type->array.elementType == nullptr) {\r\n                                    report->error(\"array has unknown element type\", expression->location);\r\n                                    return nullptr;\r\n                                }\r\n\r\n                                auto resultType = left->info->type->array.elementType->clone();\r\n\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::BinaryOperator(op, std::move(left), std::move(right)),\r\n                                    expression->location,\r\n                                    ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), qualifiers));                            \r\n                            } else if (const auto pointerType = left->info->type->tryGet<TypeExpression::Pointer>()) {\r\n                                const auto qualifiers = Qualifiers::LValue | (pointerType->qualifiers & (Qualifiers::Const | Qualifiers::WriteOnly | Qualifiers::Far));\r\n                                auto resultType = pointerType->elementType->clone();\r\n\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::BinaryOperator(op, std::move(left), std::move(right)),\r\n                                    expression->location,\r\n                                    ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), qualifiers));\r\n                            }\r\n                        }\r\n                           \r\n                        report->error(getBinaryOperatorName(op).toString() + \" is not defined between provided operand types `\" + getTypeName(left->info->type.get()) + \"` and `\" + getTypeName(right->info->type.get()) + \"`\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n\r\n                    \/\/ Bit Indexing. (integer, integer) -> bool\r\n                    case BinaryOperatorKind::BitIndexing: {\r\n                        if (const auto compatibleType = findCompatibleBinaryArithmeticExpressionType(left.get(), right.get())) {\r\n                            static_cast<void>(compatibleType);\r\n\r\n                            const auto leftContext = left->info->context;\r\n                            const auto rightContext = right->info->context;\r\n\r\n                            auto resultType = makeFwdUnique<const TypeExpression>(\r\n                                TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Bool)),\r\n                                expression->location);\r\n\r\n                            if (leftContext == EvaluationContext::RunTime || rightContext == EvaluationContext::RunTime) {\r\n                                const auto qualifiers = left->info->qualifiers;\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::BinaryOperator(op, std::move(left), std::move(right)),\r\n                                    expression->location,\r\n                                    ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), qualifiers));\r\n                            } else if (leftContext == EvaluationContext::LinkTime || rightContext == EvaluationContext::LinkTime) {\r\n                                const auto qualifiers = left->info->qualifiers;\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::BinaryOperator(op, std::move(left), std::move(right)),\r\n                                    expression->location,\r\n                                    ExpressionInfo(EvaluationContext::LinkTime, std::move(resultType), qualifiers));\r\n                            } else {\r\n                                const auto leftValue = left->integerLiteral.value;\r\n                                const auto rightValue = right->integerLiteral.value;\r\n                                std::size_t bits = rightValue > Int128(SIZE_MAX) ? SIZE_MAX : static_cast<std::size_t>(rightValue);\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::BooleanLiteral(leftValue.getBit(bits)),\r\n                                    expression->location,\r\n                                    ExpressionInfo(EvaluationContext::CompileTime, std::move(resultType), Qualifiers::None));\r\n                            }\r\n                        }\r\n                           \r\n                        report->error(getBinaryOperatorName(op).toString() + \" is not defined between provided operand types `\" + getTypeName(left->info->type.get()) + \"` and `\" + getTypeName(right->info->type.get()) + \"`\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n\r\n                    \/\/ Comparisons. (T, T) -> bool\r\n                    case BinaryOperatorKind::Equal:\r\n                    case BinaryOperatorKind::GreaterThan:\r\n                    case BinaryOperatorKind::GreaterThanOrEqual:\r\n                    case BinaryOperatorKind::NotEqual:\r\n                    case BinaryOperatorKind::LessThan:\r\n                    case BinaryOperatorKind::LessThanOrEqual: {\r\n                        return simplifyBinaryComparisonExpression(expression, op, std::move(left), std::move(right));\r\n                    }\r\n\r\n                    \/\/ Logical operators.\r\n                    \/\/ (bool, bool) -> bool                    \r\n                    case BinaryOperatorKind::LogicalAnd:\r\n                    case BinaryOperatorKind::LogicalOr: {\r\n                        return simplifyBinaryLogicalExpression(expression, op, std::move(left), std::move(right));\r\n                    }\r\n                }\r\n            }\r\n            case ExpressionKind::BooleanLiteral: {\r\n                const auto& booleanLiteral = expression->booleanLiteral;\r\n                return makeFwdUnique<const Expression>(Expression::BooleanLiteral(booleanLiteral.value), expression->location,\r\n                    ExpressionInfo(EvaluationContext::CompileTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Bool)), expression->location),\r\n                        Qualifiers::None));\r\n            }\r\n            case ExpressionKind::Call: {\r\n                const auto& call = expression->call;\r\n                auto function = reduceExpression(call.function.get());\r\n                if (!function) {\r\n                    return nullptr;\r\n                }\r\n\r\n                if ((function->info->qualifiers & Qualifiers::WriteOnly) != Qualifiers::None) {\r\n                    report->error(\"operand of function call cannot be `writeonly`\", function->location);\r\n                    return nullptr;\r\n                }\r\n\r\n                std::vector<FwdUniquePtr<const Expression>> reducedArguments;\r\n                reducedArguments.reserve(call.arguments.size());\r\n\r\n                auto& callArguments = call.arguments;\r\n                for (std::size_t i = 0; i != callArguments.size(); ++i) {\r\n                    auto& argument = callArguments[i];\r\n                    if (!argument) {\r\n                        return nullptr;\r\n                    }\r\n\r\n                    auto reducedArgument = reduceExpression(argument.get());\r\n                    if (!reducedArgument) {\r\n                        return nullptr;\r\n                    }\r\n\r\n                    if ((reducedArgument->info->qualifiers & Qualifiers::WriteOnly) != Qualifiers::None) {\r\n                        report->error(\"argument #\" + std::to_string(i) + \" of function call cannot be `writeonly`\", reducedArgument->location);\r\n                        return nullptr;\r\n                    }\r\n\r\n                    reducedArguments.push_back(std::move(reducedArgument));\r\n                }\r\n\r\n                if (const auto resolvedIdentifier = function->tryGet<Expression::ResolvedIdentifier>()) {\r\n                    const auto definition = resolvedIdentifier->definition;\r\n                    if (const auto letDefinition = definition->tryGet<Definition::Let>()) {\r\n                        if (call.inlined) {\r\n                            report->error(\"`inline` keyword cannot be applied to a `let` function call.\", expression->location);\r\n                            return nullptr;\r\n                        }\r\n\r\n                        const auto& parameters = letDefinition->parameters;\r\n                        if (reducedArguments.size() != parameters.size()) {\r\n                            auto expected = letDefinition->parameters.size();\r\n                            auto got = reducedArguments.size();\r\n\r\n                            report->error(\"`let` function `\" + definition->name.toString()\r\n                                + \"` expects exactly \" + std::to_string(expected)\r\n                                + \" argument\" + (expected != 1 ? \"s\" : \"\")\r\n                                + \", but got \" + std::to_string(got)\r\n                                + \" argument\" + (got != 1 ? \"s\" : \"\")\r\n                                + \" instead\", expression->location);\r\n\r\n                            return nullptr;\r\n                        }\r\n\r\n                        FwdUniquePtr<const Expression> result;\r\n\r\n                        if (definition == builtins.getDefinition(Builtins::DefinitionType::HasDef)) {\r\n                            if (const auto key = reducedArguments[0]->tryGet<Expression::StringLiteral>()) {\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::BooleanLiteral(builtins.getDefineExpression(key->value) != nullptr),\r\n                                    expression->location,\r\n                                    ExpressionInfo(EvaluationContext::CompileTime,\r\n                                        makeFwdUnique<TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Bool)), expression->location),\r\n                                        Qualifiers::None));\r\n                            } else {\r\n                                report->error(\"`\" + definition->name.toString() + \"` argument #1 must be a compile-time string literal\", expression->location);\r\n                                return nullptr;\r\n                            }\r\n                        } else if (definition == builtins.getDefinition(Builtins::DefinitionType::GetDef)) {\r\n                            if (const auto key = reducedArguments[0]->tryGet<Expression::StringLiteral>()) {\r\n                                if (const auto define = builtins.getDefineExpression(key->value)) {\r\n                                    if (enterLetExpression(definition->name, expression->location)) {\r\n                                        result = reduceExpression(define);\r\n                                        exitLetExpression();\r\n                                    }\r\n                                } else {\r\n                                    return std::move(reducedArguments[1]);\r\n                                }\r\n                            } else {\r\n                                report->error(\"`\" + definition->name.toString() + \"` argument #1 must be a compile-time string literal\", expression->location);\r\n                                return nullptr;\r\n                            }\r\n                        } else {\r\n                            \/\/ Create a temporary scope with a bunch of temporary let declarations representing the arguments.\r\n                            \/\/ This scope will be cleaned up at the end of this function.\r\n                            auto scope = std::make_unique<SymbolTable>(definition->parentScope, StringView());\r\n\r\n                            std::vector<FwdUniquePtr<const Statement>> argumentBindings;\r\n                            argumentBindings.reserve(parameters.size());\r\n\r\n                            for (std::size_t i = 0; i != parameters.size(); ++i) {\r\n                                if (scope->createDefinition(report, Definition::Let({}, reducedArguments[i].get()), parameters[i], definition->declaration) == nullptr) {\r\n                                    return nullptr;\r\n                                }\r\n                            }\r\n\r\n                            \/\/ Use temporary scope to evaluate let function, and return the result.\r\n                            enterScope(scope.get());\r\n                            if (enterLetExpression(definition->name, expression->location)) {                            \r\n                                result = reduceExpression(letDefinition->expression);\r\n                                exitLetExpression();\r\n                            }\r\n                            exitScope();\r\n                        }\r\n\r\n                        return result;\r\n                    } else if (const auto funcDefinition = definition->tryGet<Definition::Func>()) {\r\n                        auto& functionType = funcDefinition->resolvedSignatureType->function;\r\n                        auto resultType = functionType.returnType->clone();\r\n\r\n                        if (functionType.parameters.size() != reducedArguments.size()) {\r\n                            auto expected = functionType.parameters.size();\r\n                            auto got = reducedArguments.size();\r\n\r\n                            report->error(\"`func \" + definition->name.toString()\r\n                                + \"` expects exactly \" + std::to_string(expected)\r\n                                + \" argument\" + (expected != 1 ? \"s\" : \"\")\r\n                                + \", but got \" + std::to_string(got)\r\n                                + \" argument\" + (got != 1 ? \"s\" : \"\")\r\n                                + \" instead\", expression->location);\r\n                        }\r\n\r\n                        for (std::size_t i = 0; i != reducedArguments.size(); ++i) {\r\n                            const auto& reducedArgument = reducedArguments[i];\r\n                            const auto& parameterType = functionType.parameters[i]->parameterType;\r\n\r\n                            if (const auto resultType = findCompatibleAssignmentType(reducedArgument.get(), parameterType.get())) {\r\n                                reducedArguments[i] = createConvertedExpression(reducedArgument.get(), resultType);\r\n                            } else {\r\n                                const auto parameterName = functionType.parameters[i]->name;\r\n                                report->error(\"argument \" + (parameterName.getLength() != 0 ? \"`\" + parameterName.toString() + \"`\" : \"\")\r\n                                    + \" of type `\" + getTypeName(parameterType.get())\r\n                                    + \"` cannot be assigned `\" + getTypeName(reducedArgument->info->type.get()) + \"` expression\",\r\n                                    expression->location);\r\n                                return nullptr;\r\n                            }\r\n                        }\r\n\r\n                        return makeFwdUnique<const Expression>(\r\n                            Expression::Call(call.inlined, std::move(function), std::move(reducedArguments)),\r\n                            expression->location,\r\n                            ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), Qualifiers::None));\r\n                    } else if (const auto loadIntrinsic = definition->tryGet<Definition::BuiltinLoadIntrinsic>()) {\r\n                        if (call.inlined) {\r\n                            report->error(\"`inline` keyword is not valid for instrinsics.\", expression->location);\r\n                            return nullptr;\r\n                        }\r\n\r\n                        return makeFwdUnique<const Expression>(\r\n                            Expression::Call(call.inlined, std::move(function), std::move(reducedArguments)),\r\n                            expression->location,\r\n                            ExpressionInfo(EvaluationContext::RunTime,\r\n                                makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(loadIntrinsic->type), expression->location),\r\n                                Qualifiers::None));\r\n                    } else if (definition->kind == DefinitionKind::BuiltinVoidIntrinsic) {\r\n                        if (call.inlined) {\r\n                            report->error(\"`inline` keyword is not valid for instrinsics.\", expression->location);\r\n                            return nullptr;\r\n                        }\r\n\r\n                        return makeFwdUnique<const Expression>(\r\n                            Expression::Call(call.inlined, std::move(function), std::move(reducedArguments)),\r\n                            expression->location,\r\n                            ExpressionInfo(EvaluationContext::RunTime,\r\n                                makeFwdUnique<const TypeExpression>(TypeExpression::Tuple({}), expression->location),\r\n                                Qualifiers::None));\r\n                    } else {\r\n                        report->error(\"expression is not callable\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n                } else {\r\n                    if (const auto functionType = function->info->type->tryGet<TypeExpression::Function>()) {\r\n                        auto resultType = functionType->returnType->clone();\r\n\r\n                        if (call.inlined) {\r\n                            report->error(\"`inline` keyword cannot be used on function expressions, only functions themselves.\", expression->location);\r\n                            return nullptr;\r\n                        }\r\n\r\n                        if (functionType->parameters.size() != reducedArguments.size()) {\r\n                            const auto expected = functionType->parameters.size();\r\n                            const auto got = reducedArguments.size();\r\n\r\n                            report->error(\"`func` expects exactly \"\r\n                                + std::to_string(expected)\r\n                                + \" argument\" + (expected != 1 ? \"s\" : \"\")\r\n                                + \", but got \" + std::to_string(got)\r\n                                + \" argument\" + (got != 1 ? \"s\" : \"\")\r\n                                + \" instead\", expression->location);\r\n                        }\r\n\r\n                        for (std::size_t i = 0; i != reducedArguments.size(); ++i) {\r\n                            const auto& reducedArgument = reducedArguments[i];\r\n                            const auto& parameterType = functionType->parameters[i]->parameterType;\r\n\r\n                            if (const auto resultType = findCompatibleAssignmentType(reducedArgument.get(), parameterType.get())) {\r\n                                reducedArguments[i] = createConvertedExpression(reducedArgument.get(), resultType);\r\n                            } else {\r\n                                const auto parameterName = functionType->parameters[i]->name;\r\n                                report->error(\"argument \" + (parameterName.getLength() != 0 ? \"`\" + parameterName.toString() + \"`\" : \"\")\r\n                                    + \" of type `\" + getTypeName(parameterType.get())\r\n                                    + \"` cannot be assigned `\" + getTypeName(reducedArgument->info->type.get()) + \"` expression\",\r\n                                    expression->location);\r\n                                return nullptr;\r\n                            }\r\n                        }\r\n\r\n                        return makeFwdUnique<const Expression>(\r\n                            Expression::Call(call.inlined, std::move(function), std::move(reducedArguments)),\r\n                            expression->location,\r\n                            ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), Qualifiers::None));\r\n                    }\r\n\r\n                    report->error(\"expression is not callable\", expression->location);\r\n                    return nullptr;\r\n                }\r\n\r\n            }\r\n            case ExpressionKind::Cast: {\r\n                const auto& cast = expression->cast;\r\n                auto operand = reduceExpression(cast.operand.get());\r\n                auto destType = reduceTypeExpression(cast.type.get());\r\n\r\n                if (operand == nullptr || destType == nullptr) {\r\n                    return nullptr;\r\n                }\r\n\r\n                \/\/ TODO: bool -> integer type cast.\r\n                const auto& sourceType = operand->info->type;\r\n\r\n                Optional<Int128> integerValue;\r\n\r\n                if (const auto integerLiteral = operand->tryGet<Expression::IntegerLiteral>()) {\r\n                    integerValue = integerLiteral->value;\r\n                }\r\n\r\n                if (const auto resolvedIdentifier = operand->tryGet<Expression::ResolvedIdentifier>()) {\r\n                    if (const auto funcDefinition = resolvedIdentifier->definition->tryGet<Definition::Func>()) {\r\n                        if (funcDefinition->inlined) {\r\n                            report->error(\"`\" + resolvedIdentifier->definition->name.toString() + \"` is an `inline func` so it cannot be casted\", expression->location);\r\n                            return nullptr;\r\n                        }\r\n\r\n                        if (funcDefinition->address.hasValue() && funcDefinition->address.get().absolutePosition.hasValue()) {\r\n                            integerValue = Int128(funcDefinition->address.get().absolutePosition.get()); \r\n                        }\r\n                    }\r\n                }\r\n\r\n                bool validCast = false;\r\n\r\n                if (isIntegerType(sourceType.get()) || isEnumType(sourceType.get()) || isPointerLikeType(sourceType.get())) {\r\n                    if (const auto destTypeDefinition = tryGetResolvedIdentifierTypeDefinition(destType.get())) {\r\n                        if (const auto destBuiltinIntegerType = destTypeDefinition->tryGet<Definition::BuiltinIntegerType>()) {\r\n                            validCast = true;\r\n\r\n                            if (validCast && integerValue.hasValue()) {\r\n                                const auto mask = Int128((1U << (8U * destBuiltinIntegerType->size)) - 1);\r\n                                const auto result = *integerValue & mask;\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::IntegerLiteral(result),\r\n                                    expression->location,\r\n                                    ExpressionInfo(EvaluationContext::CompileTime, std::move(destType), Qualifiers::None));\r\n                            }\r\n                        } else if (destTypeDefinition->kind == DefinitionKind::BuiltinIntegerExpressionType || destTypeDefinition->kind == DefinitionKind::Enum) {\r\n                            validCast = true;\r\n\r\n                            if (validCast && integerValue.hasValue()) {\r\n                                return makeFwdUnique<const Expression>(Expression::IntegerLiteral(*integerValue),\r\n                                    expression->location,\r\n                                    ExpressionInfo(EvaluationContext::CompileTime, std::move(destType), Qualifiers::None));\r\n                            }\r\n                        } else {\r\n                            report->error(\"TODO: integer literal cast from `\" + getTypeName(sourceType.get()) + \"` to `\" + getTypeName(destType.get()) + \"`\", expression->location);\r\n                            return nullptr;\r\n                        }\r\n                    } else if (isPointerLikeType(destType.get())) {\r\n                        const auto destFar = isFarType(destType.get());\r\n                        const auto sourceFar = isFarType(sourceType.get());\r\n\r\n                        validCast = !destFar || !isPointerLikeType(sourceType.get()) || sourceFar == destFar;\r\n\r\n                        if (validCast && integerValue.hasValue()) {\r\n                            const auto pointerSizedType = destFar ? platform->getFarPointerSizedType() : platform->getPointerSizedType();\r\n\r\n                            return makeFwdUnique<const Expression>(\r\n                                Expression::IntegerLiteral(*integerValue & Int128((1U << (8U * pointerSizedType->builtinIntegerType.size)) - 1)),\r\n                                expression->location,\r\n                                ExpressionInfo(EvaluationContext::CompileTime, std::move(destType), destFar ? Qualifiers::Far : Qualifiers::None));\r\n                        }\r\n                    }\r\n                }\r\n\r\n                if (validCast) {\r\n                    const auto context = operand->info->context;\r\n                    const auto destFar = isFarType(destType.get());\r\n                    auto destTypeClone = destType->clone();\r\n                    return makeFwdUnique<const Expression>(\r\n                        Expression::Cast(std::move(operand), std::move(destType)),\r\n                        expression->location,\r\n                        ExpressionInfo(context, std::move(destTypeClone), destFar ? Qualifiers::Far : Qualifiers::None));\r\n                }\r\n\r\n                report->error(\"cannot cast expression from `\" + getTypeName(sourceType.get()) + \"` to `\" + getTypeName(destType.get()) + \"`\", expression->location);\r\n                return nullptr;\r\n            }\r\n            case ExpressionKind::Embed: {\r\n                const auto& embed = expression->embed;\r\n                Optional<StringView> data;\r\n                StringView displayPath;\r\n                StringView canonicalPath;\r\n                std::unique_ptr<Reader> reader;\r\n\r\n                importManager->setCurrentPath(expression->location.canonicalPath);\r\n                const auto result = importManager->importModule(embed.originalPath, ImportOptions {}, displayPath, canonicalPath, reader);\r\n\r\n                switch (result) {\r\n                    case ImportResult::JustImported: {\r\n                        if (reader && reader->isOpen()) {\r\n                            data = stringPool->intern(reader->readFully());\r\n                            embedCache[canonicalPath] = *data;\r\n                        }\r\n                        break;\r\n                    }\r\n                    case ImportResult::AlreadyImported: {\r\n                        const auto match = embedCache.find(canonicalPath);\r\n                        if (match != embedCache.end()) {\r\n                            data = match->second;\r\n                        }\r\n                        break;\r\n                    }\r\n                    default:\r\n                    case ImportResult::Failed: {\r\n                        break;\r\n                    }\r\n                }\r\n\r\n                if (data.hasValue()) {\r\n                    return createStringLiteralExpression(*data, expression->location);\r\n                } else {\r\n                    report->error(\"could not open file \\\"\" + text::escape(embed.originalPath, '\\\"') + \"\\\" referenced by `embed` expression\", expression->location);\r\n                    return nullptr;\r\n                }\r\n            }\r\n            case ExpressionKind::FieldAccess: {\r\n                const auto& fieldAccess = expression->fieldAccess;\r\n                auto operand = reduceExpression(fieldAccess.operand.get());\r\n                if (operand == nullptr) {\r\n                    return nullptr;\r\n                }\r\n                if (const auto typeOf = operand->tryGet<Expression::TypeOf>()) {\r\n                    const auto& typeExpression = typeOf->expression->info->type;\r\n                    if (auto member = resolveTypeMemberExpression(typeExpression.get(), fieldAccess.field)) {\r\n                        return member;\r\n                    } else {\r\n                        return nullptr;\r\n                    }\r\n                } else {\r\n                    if (auto member = resolveValueMemberExpression(operand.get(), fieldAccess.field)) {\r\n                        return member;\r\n                    } else {\r\n                        return nullptr;\r\n                    }\r\n                }\r\n            }\r\n            case ExpressionKind::Identifier: {\r\n                const auto& identifier = expression->identifier;\r\n                const auto& pieces = identifier.pieces;\r\n                const auto resolveResult = resolveIdentifier(pieces, expression->location);\r\n                const auto definition = resolveResult.first;\r\n                auto pieceIndex = resolveResult.second;\r\n\r\n                if (definition == nullptr) {\r\n                    return nullptr;\r\n                }\r\n\r\n                FwdUniquePtr<const Expression> currentExpression;\r\n\r\n                if (isTypeDefinition(definition) && pieceIndex < pieces.size() - 1) {\r\n                    ++pieceIndex;\r\n\r\n                    auto resolvedType = makeFwdUnique<TypeExpression>(TypeExpression::ResolvedIdentifier(definition), expression->location);\r\n\r\n                    const auto field = pieces[pieceIndex];\r\n                    if (auto member = resolveTypeMemberExpression(resolvedType.get(), field)) {\r\n                        currentExpression = std::move(member);\r\n                    } else {\r\n                        return nullptr;\r\n                    }\r\n\r\n                    if (pieceIndex == pieces.size() - 1) {\r\n                        return currentExpression;\r\n                    }\r\n                } else {\r\n                    currentExpression = resolveDefinitionExpression(definition, pieces, expression->location);\r\n                }\r\n\r\n                if (currentExpression == nullptr) {\r\n                    return nullptr;\r\n                } else if (pieceIndex < pieces.size() - 1) {\r\n                    ++pieceIndex;\r\n                    for (; pieceIndex < pieces.size(); ++pieceIndex) {\r\n                        if (auto member = resolveValueMemberExpression(currentExpression.get(), pieces[pieceIndex])) {\r\n                            currentExpression = std::move(member);\r\n                        } else {\r\n                            return nullptr;\r\n                        }\r\n                    }\r\n                }\r\n\r\n                return currentExpression;\r\n            }\r\n            case ExpressionKind::IntegerLiteral: {\r\n                const auto& integerLiteral = expression->integerLiteral;\r\n                if (expression->info.hasValue()) {\r\n                    return expression->clone();\r\n                }\r\n\r\n                Definition* typeDefinition = nullptr;\r\n                if (integerLiteral.suffix.getLength() > 0) {\r\n                    typeDefinition = builtins.getBuiltinScope()->findLocalMemberDefinition(integerLiteral.suffix);\r\n                    if (typeDefinition == nullptr || typeDefinition->kind != DefinitionKind::BuiltinIntegerType) {\r\n                        report->error(\"unrecognized integer literal suffix `\" + integerLiteral.suffix.toString() + \"`\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n\r\n                    const auto& builtinIntegerType = typeDefinition->builtinIntegerType;\r\n                    if (integerLiteral.value < builtinIntegerType.min || integerLiteral.value > builtinIntegerType.max) {\r\n                        report->error(\"integer literal `\" + integerLiteral.value.toString() + \"` with `\" + integerLiteral.suffix.toString() + \"` suffix is outside valid range `\" + builtinIntegerType.min.toString() + \"` .. `\" + builtinIntegerType.max.toString() + \"`\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n                } else {\r\n                    typeDefinition = builtins.getDefinition(Builtins::DefinitionType::IExpr);               \r\n                }\r\n                \r\n                return makeFwdUnique<const Expression>(Expression::IntegerLiteral(integerLiteral.value), expression->location,\r\n                    ExpressionInfo(EvaluationContext::CompileTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(typeDefinition), expression->location),\r\n                        Qualifiers::None));\r\n            }\r\n            case ExpressionKind::OffsetOf: {\r\n                const auto& offsetOf = expression->offsetOf;\r\n                const auto reducedTypeExpression = reduceTypeExpression(offsetOf.type.get());\r\n                if (!reducedTypeExpression) {\r\n                    return nullptr;\r\n                }\r\n                if (const auto resolvedIdentifierType = reducedTypeExpression->tryGet<TypeExpression::ResolvedIdentifier>()) {\r\n                    if (const auto structDefinition = resolvedIdentifierType->definition->tryGet<Definition::Struct>()) {\r\n                        if (const auto memberDefinition = structDefinition->environment->findLocalMemberDefinition(offsetOf.field)) {\r\n                            const auto& structMemberDefinition = memberDefinition->structMember;\r\n\r\n                            if (structMemberDefinition.offset.hasValue()) {\r\n                                return makeFwdUnique<const Expression>(Expression::IntegerLiteral(Int128(*structMemberDefinition.offset)), expression->location,\r\n                                    ExpressionInfo(EvaluationContext::CompileTime,\r\n                                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), expression->location),\r\n                                        Qualifiers::None));\r\n                            } else {\r\n                                report->error(\"offset of field `\" + offsetOf.field.toString() + \"` in type `\" + getTypeName(reducedTypeExpression.get()) + \"` could not be resolved yet\", expression->location);\r\n                                return nullptr;                \r\n                            }\r\n                        } else {\r\n                            report->error(\"`\" + getTypeName(reducedTypeExpression.get()) + \"` has no field named `\" + offsetOf.field.toString() + \"`\", expression->location);\r\n                            return nullptr;                \r\n                        }\r\n                    }\r\n                }\r\n\r\n                report->error(\"type `\" + getTypeName(reducedTypeExpression.get()) + \"` passed to `offsetof` is not a `struct` or `union` type\", expression->location);\r\n\r\n                return nullptr;                \r\n            }\r\n            case ExpressionKind::RangeLiteral: {\r\n                const auto& rangeLiteral = expression->rangeLiteral;\r\n                auto reducedStart = reduceExpression(rangeLiteral.start.get());\r\n                auto reducedEnd = reduceExpression(rangeLiteral.end.get());\r\n                auto reducedStep = rangeLiteral.step != nullptr\r\n                    ? reduceExpression(rangeLiteral.step.get())\r\n                    : makeFwdUnique<const Expression>(Expression::IntegerLiteral(Int128(1)), expression->location,\r\n                        ExpressionInfo(EvaluationContext::CompileTime,\r\n                            makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), expression->location),\r\n                            Qualifiers::None));\r\n                if (!reducedStart || !reducedEnd || !reducedStep) {\r\n                    return nullptr;\r\n                }\r\n                if (reducedStart->kind != ExpressionKind::IntegerLiteral) {\r\n                    report->error(\"range start must be a compile-time integer literal\", reducedStart->location);\r\n                    return nullptr;\r\n                }\r\n                if (reducedEnd->kind != ExpressionKind::IntegerLiteral) {\r\n                    report->error(\"range end must be a compile-time integer literal\", reducedEnd->location);\r\n                    return nullptr;\r\n                }\r\n                if (reducedStep->kind != ExpressionKind::IntegerLiteral) {\r\n                    report->error(\"range step must be a compile-time integer literal\", reducedStep->location);\r\n                    return nullptr;\r\n                }\r\n                return makeFwdUnique<const Expression>(Expression::RangeLiteral(std::move(reducedStart), std::move(reducedEnd), std::move(reducedStep)), expression->location,\r\n                    ExpressionInfo(EvaluationContext::CompileTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Range)), expression->location),\r\n                        Qualifiers::None));\r\n            }\r\n            case ExpressionKind::ResolvedIdentifier: return expression->clone();\r\n            case ExpressionKind::SideEffect: {\r\n                const auto& sideEffect = expression->sideEffect;\r\n                auto reducedResult = reduceExpression(sideEffect.result.get());\r\n                if (reducedResult == nullptr) {\r\n                    return nullptr;\r\n                }\r\n                auto resultType = reducedResult->info->type->clone();\r\n\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::SideEffect(sideEffect.statement->clone(), std::move(reducedResult)), expression->location,\r\n                    ExpressionInfo(EvaluationContext::RunTime, std::move(resultType),\r\n                    Qualifiers::None));\r\n            }\r\n            case ExpressionKind::StringLiteral: {\r\n                const auto& stringLiteral = expression->stringLiteral;\r\n                return createStringLiteralExpression(stringLiteral.value, expression->location);\r\n            }\r\n            case ExpressionKind::StructLiteral: {\r\n                const auto& structLiteral = expression->structLiteral;\r\n                auto reducedTypeExpression = reduceTypeExpression(structLiteral.type.get());\r\n                if (reducedTypeExpression == nullptr) {\r\n                    return nullptr;\r\n                }\r\n\r\n                Definition* definition = nullptr;\r\n                if (const auto resolvedTypeIdentifier = reducedTypeExpression->tryGet<TypeExpression::ResolvedIdentifier>()) {\r\n                    if (resolvedTypeIdentifier->definition->kind == DefinitionKind::Struct) {\r\n                        definition = resolvedTypeIdentifier->definition;\r\n                    }\r\n                }\r\n                if (definition == nullptr) {\r\n                    report->error(\"struct literal is invalid for non-struct type `\" + getTypeName(reducedTypeExpression.get()) + \"`\", expression->location);\r\n                    return nullptr;                    \r\n                }\r\n                \r\n                const auto& structDefinition = definition->struct_;\r\n                std::unordered_map<StringView, std::unique_ptr<const Expression::StructLiteral::Item>> reducedItems;\r\n\r\n                bool invalidLiteral = false;\r\n                auto context = EvaluationContext::CompileTime;\r\n\r\n                for (const auto& it : structLiteral.items) {\r\n                    const auto& name = it.first;\r\n                    const auto& item = it.second;\r\n\r\n                    if (const auto memberDefinition = structDefinition.environment->findLocalMemberDefinition(name)) {\r\n                        const auto& structMemberDefinition = memberDefinition->structMember;\r\n\r\n                        auto reducedValue = reduceExpression(item->value.get());\r\n                        if (reducedValue != nullptr) {\r\n                            if (const auto compatibleInitializerType = findCompatibleAssignmentType(reducedValue.get(), structMemberDefinition.resolvedType.get())) {\r\n                                reducedValue = createConvertedExpression(reducedValue.get(), compatibleInitializerType);\r\n                                switch (reducedValue->info->context) {\r\n                                    case EvaluationContext::CompileTime: break;\r\n                                    case EvaluationContext::LinkTime: {\r\n                                        if (context == EvaluationContext::CompileTime) {\r\n                                            context = reducedValue->info->context;\r\n                                        }\r\n                                        break;\r\n                                    }\r\n                                    case EvaluationContext::RunTime: {\r\n                                        if (context == EvaluationContext::CompileTime\r\n                                        || context == EvaluationContext::LinkTime) {\r\n                                            context = reducedValue->info->context;\r\n                                        }\r\n                                        break;\r\n                                    }\r\n                                    default: std::abort(); break;\r\n                                }\r\n\r\n                                reducedItems[name] = std::make_unique<const Expression::StructLiteral::Item>(std::move(reducedValue), item->location);\r\n                            } else {\r\n                                report->error(\"field `\" + name.toString() + \"` of type `\" + getTypeName(structMemberDefinition.resolvedType.get()) + \"` cannot be initialized with `\" + getTypeName(reducedValue->info->type.get()) + \"` expression\", reducedValue->location);\r\n                                invalidLiteral = true;\r\n                            }\r\n                        } else {\r\n                            invalidLiteral = true;\r\n                        }\r\n                    } else {\r\n                        report->error(\"`\" + getTypeName(reducedTypeExpression.get()) + \"` has no field named `\" + name.toString() + \"`\", item->location);\r\n                        invalidLiteral = true;\r\n                    }\r\n                }\r\n\r\n                if (invalidLiteral) {\r\n                    return nullptr;\r\n                }\r\n\r\n                if (structDefinition.kind == StructKind::Struct) {\r\n                    for (const auto& member : structDefinition.members) {\r\n                        if (reducedItems.find(member->name) == reducedItems.end()) {\r\n                            report->error(\"missing value for `\" + member->name.toString() + \"` in `\" + getTypeName(reducedTypeExpression.get()) + \"` literal\", expression->location);\r\n                        }\r\n                    }\r\n                } else if (structDefinition.kind == StructKind::Union) {\r\n                    if (structDefinition.members.size() != 1) {\r\n                        report->error(\"`\" + getTypeName(reducedTypeExpression.get()) + \"` literal must use exactly one field because it is a `union`, but \" + std::to_string(structDefinition.members.size()) + \" fields were given\", expression->location);\r\n                    }\r\n                }\r\n\r\n                auto reducedTypeExpressionClone = reducedTypeExpression->clone();\r\n\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::StructLiteral(std::move(reducedTypeExpressionClone), std::move(reducedItems)),\r\n                    expression->location,\r\n                    ExpressionInfo(context,\r\n                        std::move(reducedTypeExpression),\r\n                        Qualifiers::None));                \r\n            }\r\n            case ExpressionKind::TupleLiteral: {\r\n                const auto& tupleLiteral = expression->tupleLiteral;\r\n                std::vector<FwdUniquePtr<const Expression>> reducedItems;\r\n                std::vector<FwdUniquePtr<const TypeExpression>> reducedItemTypes;\r\n\r\n                reducedItems.reserve(tupleLiteral.items.size());\r\n                reducedItemTypes.reserve(tupleLiteral.items.size());\r\n\r\n                for (const auto& item : tupleLiteral.items) {\r\n                    auto reducedItem = reduceExpression(item.get());\r\n                    reducedItemTypes.push_back(reducedItem->info->type->clone());\r\n\r\n                    if (reducedItem != nullptr) {\r\n                        reducedItems.push_back(std::move(reducedItem));\r\n                    } else {\r\n                        return nullptr;\r\n                    }\r\n                }\r\n\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::TupleLiteral(std::move(reducedItems)),\r\n                    expression->location,\r\n                    ExpressionInfo(EvaluationContext::CompileTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::Tuple(std::move(reducedItemTypes)), expression->location),\r\n                        Qualifiers::None));\r\n            }\r\n            case ExpressionKind::TypeOf: {\r\n                const auto& typeOf = expression->typeOf;\r\n                auto reducedExpression = reduceExpression(typeOf.expression.get());\r\n                if (!reducedExpression) {\r\n                    return nullptr;\r\n                }\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::TypeOf(std::move(reducedExpression)),\r\n                    expression->location,\r\n                    ExpressionInfo(EvaluationContext::CompileTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::TypeOf)), expression->location),\r\n                        Qualifiers::None));\r\n            }\r\n            case ExpressionKind::TypeQuery: {\r\n                const auto& typeQuery = expression->typeQuery;\r\n                auto reducedType = reduceTypeExpression(typeQuery.type.get());\r\n                if (!reducedType) {\r\n                    return nullptr;\r\n                }    \r\n                switch (typeQuery.kind) {\r\n                    case TypeQueryKind::None: default: std::abort(); return nullptr;\r\n                    case TypeQueryKind::SizeOf: {\r\n                        const auto storageSize = calculateStorageSize(reducedType.get(), \"`sizeof`\"_sv);\r\n                        if (storageSize.hasValue()) {\r\n                            return makeFwdUnique<const Expression>(Expression::IntegerLiteral(Int128(*storageSize)), expression->location,\r\n                                ExpressionInfo(EvaluationContext::CompileTime,\r\n                                    makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), expression->location),\r\n                                    Qualifiers::None));\r\n                        }\r\n                        return nullptr;\r\n                    }\r\n                    case TypeQueryKind::AlignOf: {\r\n                        report->error(\"TODO: alignof support.\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n                }\r\n            }\r\n            case ExpressionKind::UnaryOperator: {\r\n                const auto& unaryOperator = expression->unaryOperator;\r\n                const auto op = unaryOperator.op;\r\n                auto operand = reduceExpression(unaryOperator.operand.get());\r\n                if (!operand) {\r\n                    return nullptr;\r\n                }\r\n\r\n                switch (op) {\r\n                    case UnaryOperatorKind::Indirection: break;\r\n                    case UnaryOperatorKind::Grouping: break;\r\n                    case UnaryOperatorKind::AddressOf: break;\r\n                    case UnaryOperatorKind::FarAddressOf: break;\r\n                    case UnaryOperatorKind::LowByte: break;\r\n                    case UnaryOperatorKind::HighByte: break;\r\n                    case UnaryOperatorKind::LowWord: break;\r\n                    case UnaryOperatorKind::MidWord: break;\r\n                    case UnaryOperatorKind::HighWord: break;\r\n                    default: {\r\n                        if ((operand->info->qualifiers & Qualifiers::WriteOnly) != Qualifiers::None) {\r\n                            report->error(\"operand to \" + getUnaryOperatorName(op).toString() + \" cannot be `writeonly`\", operand->location);\r\n                            return nullptr;\r\n                        }\r\n                        break;\r\n                    }\r\n                }\r\n\r\n                switch (op) {\r\n                    default: case UnaryOperatorKind::None: std::abort(); return nullptr;\r\n                    \r\n                    \/\/ Increment operations.\r\n                    \/\/ T -> T\r\n                    \/\/ T is either an integer or pointer type.\r\n                    case UnaryOperatorKind::PostDecrement: \r\n                    case UnaryOperatorKind::PostIncrement:\r\n                    case UnaryOperatorKind::PreDecrement:\r\n                    case UnaryOperatorKind::PreIncrement: {\r\n                        auto resultType = operand->info->type->clone();\r\n                        return makeFwdUnique<const Expression>(\r\n                            Expression::UnaryOperator(unaryOperator.op, std::move(operand)), expression->location,\r\n                            ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), Qualifiers::None));\r\n                    }\r\n                    \r\n                    \/\/ Indirection. Run-time.\r\n                    \/\/ *T -> T\r\n                    case UnaryOperatorKind::Indirection: {\r\n                        if (const auto& pointerType = operand->info->type->tryGet<TypeExpression::Pointer>()) {\r\n                            const auto qualifiers = Qualifiers::LValue | (pointerType->qualifiers & (Qualifiers::Const | Qualifiers::WriteOnly | Qualifiers::Far));\r\n                            auto resultType = pointerType->elementType->clone();\r\n\r\n                            return makeFwdUnique<const Expression>(\r\n                                Expression::UnaryOperator(unaryOperator.op, std::move(operand)), expression->location,\r\n                                ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), qualifiers));\r\n                        }\r\n\r\n                        report->error(getUnaryOperatorName(unaryOperator.op).toString() + \" is not defined for provided operand type `\" + getTypeName(operand->info->type.get()) + \"`\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n\r\n                    \/\/ Address-of operator. Compile-time or link-time.\r\n                    \/\/ T -> *T\r\n                    \/\/ If the operand is an indirection, cancels it out.\r\n                    \/\/ If the operand has a known address at the time of evaluation, it is compile-time. Otherwise, it is link-time.\r\n                    case UnaryOperatorKind::AddressOf:\r\n                    case UnaryOperatorKind::FarAddressOf: {\r\n                        if (const auto nestedUnaryOperator = operand->tryGet<Expression::UnaryOperator>()) {\r\n                            if (nestedUnaryOperator->op == UnaryOperatorKind::Indirection) {\r\n                                if (const auto pointerType = nestedUnaryOperator->operand->info->type->tryGet<TypeExpression::Pointer>()) {\r\n                                    if (((pointerType->qualifiers & Qualifiers::Far) != Qualifiers::None) != (op == UnaryOperatorKind::FarAddressOf)) {\r\n                                        report->error(getUnaryOperatorName(unaryOperator.op).toString() + \" is not defined for provided operand type `\" + getTypeName(operand->info->type.get()) + \"`\", expression->location);\r\n                                    }\r\n\r\n                                    return nestedUnaryOperator->operand->clone();\r\n                                }\r\n                            }\r\n                        } else if (const auto binaryOperator = operand->tryGet<Expression::BinaryOperator>()) {\r\n                            if (binaryOperator->op == BinaryOperatorKind::Indexing || binaryOperator->op == BinaryOperatorKind::UnalignedIndexing) {\r\n                                const auto left = binaryOperator->left.get();\r\n                                const auto right = binaryOperator->right.get();\r\n                                auto context = left->info->context;\r\n                                auto qualifiers = Qualifiers::None;\r\n\r\n                                if (right->info->context == EvaluationContext::RunTime) {\r\n                                    context = right->info->context;\r\n                                }\r\n\r\n                                if (const auto pointerType = binaryOperator->left->info->type->tryGet<TypeExpression::Pointer>()) {\r\n                                    if (((pointerType->qualifiers & Qualifiers::Far) != Qualifiers::None) != (op == UnaryOperatorKind::FarAddressOf)) {\r\n                                        if (op == UnaryOperatorKind::AddressOf) {\r\n                                            report->error(getUnaryOperatorName(unaryOperator.op).toString() + \" is not defined for provided operand type `\" + getTypeName(operand->info->type.get()) + \"`. use `far &` instead\", expression->location);\r\n                                        } else {\r\n                                            report->error(getUnaryOperatorName(unaryOperator.op).toString() + \" is not defined for provided far operand type `\" + getTypeName(operand->info->type.get()) + \"`. use `&` (without `far`) instead\", expression->location);\r\n                                        }\r\n                                    }\r\n                                }\r\n\r\n                                auto resultType = makeFwdUnique<const TypeExpression>(\r\n                                    TypeExpression::Pointer(operand->info->type->clone(), qualifiers),\r\n                                    operand->info->type->location);\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::UnaryOperator(unaryOperator.op, std::move(operand)), expression->location,\r\n                                    ExpressionInfo(context, std::move(resultType), Qualifiers::None));\r\n                            }\r\n                        } else if (const auto resolvedIdentifier = operand->tryGet<Expression::ResolvedIdentifier>()) {\r\n                            const auto pointerSizedType = op == UnaryOperatorKind::FarAddressOf ? platform->getFarPointerSizedType() : platform->getPointerSizedType();\r\n                            const auto mask = Int128((1U << (8U * pointerSizedType->builtinIntegerType.size)) - 1);\r\n                            const auto farQualifier = op == UnaryOperatorKind::FarAddressOf ? Qualifiers::Far : Qualifiers::None;\r\n\r\n                            if (const auto varDefinition = resolvedIdentifier->definition->tryGet<Definition::Var>()) {\r\n                                auto resultType = makeFwdUnique<const TypeExpression>(\r\n                                    TypeExpression::Pointer(\r\n                                        operand->info->type->clone(),\r\n                                        ((operand->info->qualifiers & (Qualifiers::Const | Qualifiers::WriteOnly)) | farQualifier)),\r\n                                    operand->info->type->location);\r\n\r\n                                if (varDefinition->address.hasValue() && varDefinition->address->absolutePosition.hasValue()) {\r\n                                    return makeFwdUnique<const Expression>(\r\n                                        Expression::IntegerLiteral(Int128(varDefinition->address->absolutePosition.get()) & mask), expression->location,\r\n                                        ExpressionInfo(EvaluationContext::CompileTime, std::move(resultType), farQualifier));\r\n                                } else {\r\n                                    return makeFwdUnique<const Expression>(\r\n                                        Expression::UnaryOperator(unaryOperator.op, std::move(operand)), expression->location,\r\n                                        ExpressionInfo(EvaluationContext::LinkTime, std::move(resultType), farQualifier));\r\n                                }\r\n                            } else if (const auto funcDefinition = resolvedIdentifier->definition->tryGet<Definition::Func>()) {\r\n                                if (funcDefinition->inlined) {\r\n                                    report->error(\"`\" + resolvedIdentifier->definition->name.toString() + \"` is an `inline func` so it has no address that can be taken with \" + getUnaryOperatorName(unaryOperator.op).toString(), expression->location);\r\n                                    return nullptr;\r\n                                }\r\n\r\n                                auto resultType = makeFwdUnique<const TypeExpression>(\r\n                                    TypeExpression::Pointer(\r\n                                        operand->info->type->clone(), \r\n                                        Qualifiers::Const | farQualifier),\r\n                                    operand->info->type->location);\r\n\r\n                                if (funcDefinition->address.hasValue() && funcDefinition->address.get().absolutePosition.hasValue()) {\r\n                                    return makeFwdUnique<const Expression>(\r\n                                        Expression::IntegerLiteral(Int128(funcDefinition->address->absolutePosition.get()) & mask), expression->location,\r\n                                        ExpressionInfo(EvaluationContext::CompileTime, std::move(resultType), farQualifier));\r\n                                } else {\r\n                                    return makeFwdUnique<const Expression>(\r\n                                        Expression::UnaryOperator(unaryOperator.op, std::move(operand)), expression->location,\r\n                                        ExpressionInfo(EvaluationContext::LinkTime, std::move(resultType), farQualifier));\r\n                                }\r\n                            }\r\n                        }\r\n                        report->error(getUnaryOperatorName(unaryOperator.op).toString() + \" cannot be used on provided expression\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n\r\n                    \/\/ Bitwise negation:\r\n                    \/\/ integer -> integer\r\n                    case UnaryOperatorKind::BitwiseNegation: {\r\n                        const auto resultType = operand->info->type.get();\r\n\r\n                        if (isBooleanType(resultType)) {\r\n                            return simplifyLogicalNotExpression(expression, std::move(operand));\r\n                        } else if (isIntegerType(resultType)) {\r\n                            if (operand->info->context == EvaluationContext::RunTime) {\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::UnaryOperator(unaryOperator.op, std::move(operand)), expression->location,\r\n                                    ExpressionInfo(EvaluationContext::RunTime, resultType->clone(), Qualifiers::None));\r\n                            } else if (operand->info->context == EvaluationContext::LinkTime) {\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::UnaryOperator(unaryOperator.op, std::move(operand)), expression->location,\r\n                                    ExpressionInfo(EvaluationContext::LinkTime, resultType->clone(), Qualifiers::None));\r\n                            } else {\r\n                                if (const auto integerLiteral = operand->tryGet<Expression::IntegerLiteral>()) {\r\n                                    if (const auto typeDefinition = tryGetResolvedIdentifierTypeDefinition(resultType)) {\r\n                                        if (const auto builtinIntegerType = typeDefinition->tryGet<Definition::BuiltinIntegerType>()) {\r\n                                            const auto mask = Int128((1U << (8U * builtinIntegerType->size)) - 1);\r\n                                            const auto result = ~integerLiteral->value & mask;\r\n                                            return makeFwdUnique<const Expression>(\r\n                                                Expression::IntegerLiteral(result),\r\n                                                expression->location,\r\n                                                ExpressionInfo(EvaluationContext::CompileTime, resultType->clone(), Qualifiers::None));\r\n                                        } else if (typeDefinition->kind == DefinitionKind::BuiltinIntegerExpressionType) {\r\n                                            return makeFwdUnique<const Expression>(\r\n                                                Expression::IntegerLiteral(~integerLiteral->value), expression->location,\r\n                                                ExpressionInfo(EvaluationContext::CompileTime, resultType->clone(), Qualifiers::None));\r\n                                        }\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                           \r\n                        report->error(getUnaryOperatorName(unaryOperator.op).toString() + \" is not defined for provided operand type `\" + getTypeName(resultType) + \"`\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n\r\n                    \/\/ Expression grouping. Returns the operand directly and removes itself from the tree.\r\n                    case UnaryOperatorKind::Grouping: return operand;\r\n\r\n                    \/\/ Logical negation.\r\n                    \/\/ bool -> bool\r\n                    case UnaryOperatorKind::LogicalNegation: {\r\n                        return simplifyLogicalNotExpression(expression, std::move(operand));\r\n                    }\r\n\r\n                    \/\/ Signed negation.\r\n                    \/\/ integer -> integer\r\n                    case UnaryOperatorKind::SignedNegation: {\r\n                        const auto resultType = operand->info->type.get();\r\n\r\n                        if (isIntegerType(resultType)) {\r\n                            if (operand->info->context == EvaluationContext::RunTime) {\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::UnaryOperator(unaryOperator.op, std::move(operand)), expression->location,\r\n                                    ExpressionInfo(EvaluationContext::RunTime, resultType->clone(), Qualifiers::None));\r\n                            } else if (operand->info->context == EvaluationContext::LinkTime) {\r\n                                return makeFwdUnique<const Expression>(\r\n                                    Expression::UnaryOperator(unaryOperator.op, std::move(operand)), expression->location,\r\n                                    ExpressionInfo(EvaluationContext::LinkTime, resultType->clone(), Qualifiers::None));\r\n                            } else {\r\n                                const auto operandValue = operand->integerLiteral.value;\r\n                                const auto result = Int128().checkedSubtract(operandValue);\r\n                                if (result.first == Int128::CheckedArithmeticResult::Success) {\r\n                                    const auto value = result.second;\r\n\r\n                                    if (const auto typeDefinition = tryGetResolvedIdentifierTypeDefinition(resultType)) {\r\n                                        if (const auto builtinIntegerType = typeDefinition->tryGet<Definition::BuiltinIntegerType>()) {\r\n                                            if (value < builtinIntegerType->min || value > builtinIntegerType->max) {\r\n                                                report->error(getUnaryOperatorName(unaryOperator.op).toString() + \" resulted in `\" + getTypeName(resultType) + \"` value of `\" + value.toString() + \"` outside valid range `\" + builtinIntegerType->min.toString() + \"` .. `\" + builtinIntegerType->max.toString() + \"`\", expression->location);\r\n                                                return nullptr;\r\n                                            }\r\n                                        }\r\n                                    }\r\n\r\n                                    return makeFwdUnique<const Expression>(\r\n                                        Expression::IntegerLiteral(value), expression->location,\r\n                                        ExpressionInfo(EvaluationContext::CompileTime, resultType->clone(), Qualifiers::None));\r\n                                } else {\r\n                                    report->error(getUnaryOperatorName(unaryOperator.op).toString() + \" resulted in overflow\", expression->location);\r\n                                    return nullptr;\r\n                                }\r\n                            }\r\n                        }\r\n                           \r\n                        report->error(getUnaryOperatorName(unaryOperator.op).toString() + \" is not defined for provided operand type `\" + getTypeName(operand->info->type.get()) + \"`\", expression->location);\r\n                        return nullptr;\r\n                    }\r\n\r\n                    \/\/ Byte\/word access operators.\r\n                    \/\/ T -> u8 or u16, where offset < sizeof(T) or T is iexpr.\r\n                    \/\/ TODO: disallow \"mid-word\" unaligned accesss if 16-bit accesses require alignment.\r\n                    case UnaryOperatorKind::LowByte:\r\n                    case UnaryOperatorKind::HighByte:\r\n                    case UnaryOperatorKind::BankByte:\r\n                    case UnaryOperatorKind::LowWord:\r\n                    case UnaryOperatorKind::MidWord:\r\n                    case UnaryOperatorKind::HighWord: {\r\n                        const auto sourceType = operand->info->type.get();\r\n\r\n                        std::size_t offset;\r\n                        std::size_t mask;\r\n                        Builtins::DefinitionType definitionType;\r\n                        switch (unaryOperator.op) {\r\n                            case UnaryOperatorKind::LowByte: offset = 0; definitionType = Builtins::DefinitionType::U8; mask = 0xFF; break;\r\n                            case UnaryOperatorKind::HighByte: offset = 1; definitionType = Builtins::DefinitionType::U8; mask = 0xFF; break;\r\n                            case UnaryOperatorKind::BankByte: offset = 2; definitionType = Builtins::DefinitionType::U8; mask = 0xFF; break;\r\n                            case UnaryOperatorKind::LowWord: offset = 0; definitionType = Builtins::DefinitionType::U16; mask = 0xFFFF; break;\r\n                            case UnaryOperatorKind::MidWord: offset = 1; definitionType = Builtins::DefinitionType::U16; mask = 0xFFFF; break;\r\n                            case UnaryOperatorKind::HighWord: offset = 2; definitionType = Builtins::DefinitionType::U16; mask = 0xFFFF; break;\r\n                            default: std::abort(); return nullptr;\r\n                        }\r\n\r\n                        Optional<std::size_t> storageSize;\r\n                        bool needsStorageSizeCheck = true;\r\n\r\n                        if (const auto typeDefinition = tryGetResolvedIdentifierTypeDefinition(sourceType)) {\r\n                            needsStorageSizeCheck = typeDefinition != builtins.getDefinition(Builtins::DefinitionType::IExpr);\r\n                        }\r\n\r\n                        if (needsStorageSizeCheck) {\r\n                            storageSize = calculateStorageSize(sourceType, \"operand\"_sv);\r\n                            if (!storageSize.hasValue()) {\r\n                                return nullptr;\r\n                            }\r\n                        }\r\n\r\n                        if ((!isIntegerType(sourceType) && !isEnumType(sourceType) && !isPointerLikeType(sourceType))\r\n                        || (storageSize.hasValue() && offset >= *storageSize)) {\r\n                            report->error(getUnaryOperatorName(unaryOperator.op).toString() + \" is not defined for provided operand type `\" + getTypeName(operand->info->type.get()) + \"`\", expression->location);\r\n                            return nullptr;\r\n                        }\r\n\r\n                        auto resultType = makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(definitionType)), expression->location);\r\n\r\n                        bool simplify = false;\r\n                        auto context = operand->info->context;\r\n                        Optional<Int128> absolutePosition;\r\n                    \r\n                        if (const auto integerLiteral = operand->tryGet<Expression::IntegerLiteral>()) {\r\n                            return makeFwdUnique<const Expression>(\r\n                                Expression::IntegerLiteral(integerLiteral->value.logicalRightShift(8 * offset) & Int128(mask)), expression->location,\r\n                                ExpressionInfo(EvaluationContext::CompileTime, std::move(resultType), Qualifiers::None));\r\n                        } else if (const auto resolvedIdentifier = operand->tryGet<Expression::ResolvedIdentifier>()) {\r\n                            const auto definition = resolvedIdentifier->definition;\r\n                            if (const auto registerDefinition = definition->tryGet<Definition::BuiltinRegister>()) {\r\n                                if (definitionType != Builtins::DefinitionType::U8) {\r\n                                    if (registerDefinition->type->kind == DefinitionKind::BuiltinIntegerType\r\n                                    && resultType->resolvedIdentifier.definition->builtinIntegerType.size == registerDefinition->type->builtinIntegerType.size) {\r\n                                        return makeFwdUnique<const Expression>(Expression::ResolvedIdentifier(definition, {}), expression->location,\r\n                                            ExpressionInfo(EvaluationContext::RunTime,\r\n                                                makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(registerDefinition->type), expression->location),\r\n                                                Qualifiers::LValue));\r\n                                    } else {\r\n                                        report->error(\"register decomposition is currently only supported for `u8` quantities, so it cannot be used with \" + getUnaryOperatorName(unaryOperator.op).toString(), expression->location);\r\n                                    }\r\n                                }\r\n\r\n                                const auto subRegisters = builtins.findRegisterDecomposition(definition);\r\n                                if (subRegisters.getLength() == 0) {\r\n                                    report->error(\"`\" + definition->name.toString() + \"` cannot be split into smaller registers, so it cannot be used with \" + getUnaryOperatorName(unaryOperator.op).toString(), expression->location);\r\n                                    return nullptr;\r\n                                } else if (offset >= subRegisters.getLength()) {\r\n                                    report->error(\"`\" + definition->name.toString() + \"` is only made of \" + std::to_string(subRegisters.getLength()) + \" registers, so it cannot be used with \" + getUnaryOperatorName(unaryOperator.op).toString(), expression->location);\r\n                                    return nullptr;\r\n                                } else {\r\n                                    const auto subRegister = subRegisters[offset];\r\n                                    const auto& subRegisterDefinition = subRegisters[offset]->builtinRegister;\r\n\r\n                                    return makeFwdUnique<const Expression>(Expression::ResolvedIdentifier(subRegister, {}), expression->location,\r\n                                        ExpressionInfo(EvaluationContext::RunTime,\r\n                                            makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(subRegisterDefinition.type), expression->location),\r\n                                            Qualifiers::LValue));\r\n                                }\r\n                            } else if (const auto varDefinition = definition->tryGet<Definition::Var>()) {\r\n                                simplify = true;\r\n\r\n                                if (varDefinition->address.hasValue() && varDefinition->address->absolutePosition.hasValue()) {\r\n                                    absolutePosition = varDefinition->address->absolutePosition.get();\r\n                                }\r\n                            } else if (const auto funcDefinition = definition->tryGet<Definition::Func>()) {\r\n                                if (funcDefinition->inlined) {\r\n                                    report->error(\"`\" + definition->name.toString() + \"` is an `inline func` so it cannot be used with \" + getUnaryOperatorName(unaryOperator.op).toString(), expression->location);\r\n                                    return nullptr;\r\n                                }\r\n\r\n                                if (funcDefinition->address.hasValue() && funcDefinition->address.get().absolutePosition.hasValue()) {\r\n                                    return makeFwdUnique<const Expression>(\r\n                                        Expression::IntegerLiteral(Int128(funcDefinition->address->absolutePosition.get()).logicalRightShift(8 * offset) & Int128(mask)), expression->location,\r\n                                        ExpressionInfo(EvaluationContext::CompileTime, std::move(resultType), Qualifiers::None));\r\n                                }\r\n                            }\r\n                        } else if (const auto nestedUnaryOperator = operand->tryGet<Expression::UnaryOperator>()) {\r\n                            const auto& nestedOperand = nestedUnaryOperator->operand;\r\n                            if (nestedUnaryOperator->op == UnaryOperatorKind::Indirection) {\r\n                                simplify = true;\r\n                                context = nestedUnaryOperator->operand->info->context;\r\n\r\n                                if (const auto integerLiteral = nestedOperand->tryGet<Expression::IntegerLiteral>()) {\r\n                                    absolutePosition = integerLiteral->value;\r\n                                }\r\n                            }\r\n                        } else if (const auto binaryOperator = operand->tryGet<Expression::BinaryOperator>()) {\r\n                            if (binaryOperator->op == BinaryOperatorKind::Indexing\r\n                            || binaryOperator->op == BinaryOperatorKind::UnalignedIndexing) {\r\n                                simplify = true;\r\n                            }\r\n                        }\r\n\r\n                        if (simplify) {\r\n                            return simplifyIndirectionOffsetExpression(std::move(resultType), operand.get(), context, absolutePosition, Int128(offset));\r\n                        }\r\n\r\n                        const auto qualifiers = operand->info->qualifiers;\r\n                        return makeFwdUnique<const Expression>(\r\n                            Expression::UnaryOperator(unaryOperator.op, std::move(operand)), expression->location,\r\n                            ExpressionInfo(context, std::move(resultType), qualifiers));\r\n                    }\r\n\r\n                    \/\/ Address reserve operator `@`\r\n                    \/\/ Reserves an address for some data, and returns the pointer to that data.\r\n                    \/\/ The data will be located immediately after the expression that references it.\r\n                    \/\/ T -> *const T\r\n                    case UnaryOperatorKind::AddressReserve: {\r\n                        if (!allowReservedConstants) {\r\n                            report->error(\"cannot use \" + getUnaryOperatorName(unaryOperator.op).toString() + \" here\", expression->location);\r\n                            return nullptr;\r\n                        }\r\n\r\n                        if (operand->info->context == EvaluationContext::CompileTime\r\n                        || operand->info->context == EvaluationContext::LinkTime) {\r\n                            const auto constType = operand->info->type.get();\r\n                            const auto constName = stringPool->intern(\"$data\" + std::to_string(definitionPool.size()));\r\n                            auto constDeclaration = statementPool.addNew(Statement::InternalDeclaration(), expression->location);\r\n                            auto definition = definitionPool.addNew(Definition::Var(Qualifiers::Const, currentFunction, nullptr, nullptr, 0), constName, constDeclaration);\r\n                            auto& constDefinition = definition->var;\r\n\r\n                            constDefinition.resolvedType = constType;\r\n                            constDefinition.initializerExpression = std::move(operand);\r\n\r\n                            const auto elementTypePtr =\r\n                                constType->kind == TypeExpressionKind::Array\r\n                                ? constType->array.elementType.get()\r\n                                : constType;\r\n\r\n                            const auto elementStorageSize = calculateStorageSize(elementTypePtr, \"\"_sv);\r\n                            if (!elementStorageSize.hasValue()) {\r\n                                report->error(\"operand of \" + getUnaryOperatorName(unaryOperator.op).toString() + \" cannot be of type \" + getTypeName(constType) + \" because it has unknown size\", expression->location);\r\n                                return nullptr;\r\n                            }\r\n\r\n                            reservedConstants.push_back(definition);\r\n\r\n                            auto pointerToElementType = makeFwdUnique<const TypeExpression>(\r\n                                TypeExpression::Pointer(elementTypePtr->clone(), Qualifiers::Const),\r\n                                expression->location);\r\n                            const auto pointerToElementTypePtr = pointerToElementType.get();\r\n\r\n                            \/\/ &data as *U\r\n                            return makeFwdUnique<const Expression>(\r\n                                Expression::Cast(\r\n                                    makeFwdUnique<const Expression>(\r\n                                        Expression::UnaryOperator(\r\n                                            UnaryOperatorKind::AddressOf,\r\n                                            makeFwdUnique<const Expression>(\r\n                                                Expression::ResolvedIdentifier(definition, {constName}),\r\n                                                expression->location,\r\n                                                ExpressionInfo(EvaluationContext::LinkTime,\r\n                                                    constType->clone(),\r\n                                                    Qualifiers::LValue | Qualifiers::Const))),\r\n                                        expression->location,\r\n                                        ExpressionInfo(\r\n                                            EvaluationContext::LinkTime,\r\n                                            makeFwdUnique<const TypeExpression>(\r\n                                                TypeExpression::Pointer(constType->clone(), Qualifiers::Const),\r\n                                                expression->location),\r\n                                            Qualifiers::None)),\r\n                                std::move(pointerToElementType)),\r\n                                expression->location,\r\n                                ExpressionInfo(\r\n                                    EvaluationContext::LinkTime,\r\n                                    pointerToElementTypePtr->clone(),\r\n                                    Qualifiers::None));\r\n                        } else {\r\n                            report->error(\"operand of \" + getUnaryOperatorName(unaryOperator.op).toString() + \" must be a link-time expression.\", expression->location);\r\n                            return nullptr;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n            default: std::abort(); return nullptr;\r\n        }\r\n    }\r\n\r\n    Optional<std::size_t> Compiler::tryGetSequenceLiteralLength(const Expression* expression) const {\r\n        if (const auto arrayLiteral = expression->tryGet<Expression::ArrayLiteral>()) {\r\n            return arrayLiteral->items.size();\r\n        } else if (const auto stringLiteral = expression->tryGet<Expression::StringLiteral>()) {\r\n            return stringLiteral->value.getLength();\r\n        } else if (const auto rangeLiteral = expression->tryGet<Expression::RangeLiteral>()) {\r\n            const auto rangeStartLiteral = rangeLiteral->start->tryGet<Expression::IntegerLiteral>();\r\n            const auto rangeEndLiteral = rangeLiteral->end->tryGet<Expression::IntegerLiteral>();\r\n            const auto rangeStepLiteral = rangeLiteral->step->tryGet<Expression::IntegerLiteral>();\r\n\r\n            if (rangeStartLiteral == nullptr || rangeEndLiteral == nullptr || rangeStepLiteral == nullptr) {\r\n                return Optional<std::size_t>();\r\n            }\r\n\r\n            if (rangeStepLiteral->value.isZero()) {\r\n                return Optional<std::size_t>();\r\n            } else {\r\n                const auto low = rangeStepLiteral->value.isNegative() ? rangeEndLiteral->value : rangeStartLiteral->value;\r\n                const auto high = rangeStepLiteral->value.isNegative() ? rangeStartLiteral->value : rangeEndLiteral->value;\r\n                if (low > high) {\r\n                    return 0;\r\n                }\r\n\r\n                const auto step = rangeStepLiteral->value;\r\n\r\n                return (high - low) \/ (step.isNegative() ? -step : step) + Int128(1);\r\n            }\r\n        }\r\n\r\n        return Optional<std::size_t>();\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::getSequenceLiteralItem(const Expression* expression, std::size_t index) const {\r\n        if (const auto arrayLiteral = expression->tryGet<Expression::ArrayLiteral>()) {\r\n            return arrayLiteral->items[index]->clone();\r\n        } else if (const auto stringLiteral = expression->tryGet<Expression::StringLiteral>()) {\r\n            return makeFwdUnique<const Expression>(Expression::IntegerLiteral(Int128(static_cast<std::uint8_t>(stringLiteral->value[index]))), expression->location,\r\n                ExpressionInfo(EvaluationContext::CompileTime,\r\n                    makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), expression->location),\r\n                    Qualifiers::None));\r\n        } else if (const auto rangeLiteral = expression->tryGet<Expression::RangeLiteral>()) {\r\n            const auto rangeStartLiteral = rangeLiteral->start->tryGet<Expression::IntegerLiteral>();\r\n            const auto rangeEndLiteral = rangeLiteral->end->tryGet<Expression::IntegerLiteral>();\r\n            const auto rangeStepLiteral = rangeLiteral->step->tryGet<Expression::IntegerLiteral>();\r\n\r\n            if (rangeStartLiteral == nullptr || rangeEndLiteral == nullptr || rangeStepLiteral == nullptr) {\r\n                return nullptr;\r\n            }\r\n\r\n            if (rangeStepLiteral->value.isZero()) {\r\n                std::abort();\r\n                return nullptr;\r\n            } else {\r\n                return makeFwdUnique<const Expression>(Expression::IntegerLiteral(Int128(rangeStartLiteral->value + rangeStepLiteral->value * Int128(index))), expression->location,\r\n                    ExpressionInfo(EvaluationContext::CompileTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), expression->location),\r\n                        Qualifiers::None));\r\n            }  \r\n        }\r\n\r\n        std::abort();\r\n        return nullptr;\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::createStringLiteralExpression(StringView data, SourceLocation location) const {\r\n        return makeFwdUnique<const Expression>(Expression::StringLiteral(data), location,\r\n            ExpressionInfo(EvaluationContext::CompileTime,\r\n                makeFwdUnique<const TypeExpression>(TypeExpression::Array(\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::U8)), location), \r\n                        makeFwdUnique<const Expression>(Expression::IntegerLiteral(Int128(data.getLength())), location, \r\n                            ExpressionInfo(EvaluationContext::CompileTime,\r\n                                makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), location),\r\n                                Qualifiers::None))),\r\n                    location),\r\n                Qualifiers::None));\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::createArrayLiteralExpression(std::vector<FwdUniquePtr<const Expression>> items, const TypeExpression* elementType, SourceLocation location) const {\r\n        const auto size = items.size();\r\n\r\n        auto context = EvaluationContext::CompileTime;\r\n        for (const auto& item : items) {\r\n            if (item->info->context == EvaluationContext::LinkTime) {\r\n                context = item->info->context;\r\n            }\r\n        }\r\n\r\n        return makeFwdUnique<const Expression>(Expression::ArrayLiteral(std::move(items)), location,\r\n            ExpressionInfo(context,\r\n                makeFwdUnique<const TypeExpression>(TypeExpression::Array(\r\n                        elementType ? elementType->clone() : nullptr, \r\n                        makeFwdUnique<const Expression>(Expression::IntegerLiteral(Int128(size)), location,\r\n                            ExpressionInfo(EvaluationContext::CompileTime,\r\n                                makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), location),\r\n                                Qualifiers::None))),\r\n                    location),\r\n                Qualifiers::None));\r\n    }\r\n\r\n    std::string Compiler::getResolvedIdentifierName(Definition* definition, const std::vector<StringView>& pieces) const {\r\n        if (pieces.size() > 0) {\r\n            return text::join(pieces.begin(), pieces.end(), \".\");\r\n        } else {\r\n            return definition->name.toString();\r\n        }\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::resolveDefinitionExpression(Definition* definition, const std::vector<StringView>& pieces, SourceLocation location) {\r\n        if (const auto letDefinition = definition->tryGet<Definition::Let>()) {\r\n            if (letDefinition->parameters.size() == 0) {\r\n                FwdUniquePtr<const Expression> result;\r\n\r\n                enterScope(definition->parentScope);\r\n                if (enterLetExpression(definition->name, location)) {\r\n                    result = reduceExpression(letDefinition->expression);\r\n                    exitLetExpression();\r\n                }\r\n                exitScope();\r\n\r\n                return result != nullptr\r\n                    ? result->clone(location, ExpressionInfo(result->info->context, result->info->type->clone(), result->info->qualifiers))\r\n                    : nullptr;\r\n            } else {\r\n                return makeFwdUnique<const Expression>(Expression::ResolvedIdentifier(definition, pieces), location,\r\n                    ExpressionInfo(EvaluationContext::CompileTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Let)), location),\r\n                        Qualifiers::None));\r\n            }\r\n        } else if (const auto varDefinition = definition->tryGet<Definition::Var>()) {\r\n            if (varDefinition->resolvedType == nullptr) {\r\n                report->error(\"encountered a reference to `\" + std::string(\r\n                    ((varDefinition->qualifiers & Qualifiers::Const) != Qualifiers::None) ? \"const\"\r\n                    : ((varDefinition->qualifiers & Qualifiers::WriteOnly) != Qualifiers::None) ? \"writeonly\"\r\n                    : \"var\") + \" \" + getResolvedIdentifierName(definition, pieces) + \"` before its type was known\", location);\r\n                return nullptr;\r\n            }\r\n            if (const auto designatedStorageType = varDefinition->resolvedType->tryGet<TypeExpression::DesignatedStorage>()) {\r\n                return designatedStorageType->holder->clone(location, ExpressionInfo(\r\n                    EvaluationContext::RunTime,\r\n                    designatedStorageType->elementType->clone(),\r\n                    designatedStorageType->holder->info->qualifiers\r\n                ));\r\n            }\r\n            return makeFwdUnique<const Expression>(Expression::ResolvedIdentifier(definition, pieces), location,\r\n                ExpressionInfo(\r\n                    varDefinition->resolvedType->kind == TypeExpressionKind::Array ? EvaluationContext::LinkTime : EvaluationContext::RunTime,\r\n                    varDefinition->resolvedType->clone(),\r\n                    Qualifiers::LValue | (varDefinition->qualifiers & (Qualifiers::Const | Qualifiers::WriteOnly))));\r\n        } else if (const auto registerDefinition = definition->tryGet<Definition::BuiltinRegister>()) {\r\n            return makeFwdUnique<const Expression>(Expression::ResolvedIdentifier(definition, pieces), location,\r\n                ExpressionInfo(EvaluationContext::RunTime,\r\n                    makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(registerDefinition->type), location),\r\n                    Qualifiers::LValue));\r\n        } else if (const auto funcDefinition = definition->tryGet<Definition::Func>()) {\r\n            if (funcDefinition->resolvedSignatureType == nullptr) {\r\n                report->error(\"encountered a reference to func `\" + getResolvedIdentifierName(definition, pieces) + \"` before its type was known\", location);\r\n                return nullptr;\r\n            }\r\n\r\n            auto context = EvaluationContext::LinkTime;\r\n            if (funcDefinition->address.hasValue() && funcDefinition->address->absolutePosition.hasValue()) {\r\n                context = EvaluationContext::CompileTime;\r\n            }\r\n\r\n            return makeFwdUnique<const Expression>(Expression::ResolvedIdentifier(definition, pieces),\r\n                location,\r\n                ExpressionInfo(\r\n                    context,\r\n                    funcDefinition->resolvedSignatureType->clone(),\r\n                    (funcDefinition->far ? Qualifiers::Far : Qualifiers::None)));\r\n        } else if (definition->kind == DefinitionKind::BuiltinVoidIntrinsic) {\r\n            return makeFwdUnique<const Expression>(Expression::ResolvedIdentifier(definition, pieces), location,\r\n                ExpressionInfo(EvaluationContext::RunTime,\r\n                    makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Intrinsic)), location),\r\n                Qualifiers::None));\r\n        } else if (definition->kind == DefinitionKind::BuiltinLoadIntrinsic) {\r\n            return makeFwdUnique<const Expression>(Expression::ResolvedIdentifier(definition, pieces), location,\r\n                ExpressionInfo(EvaluationContext::RunTime,\r\n                    makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Intrinsic)), location),\r\n                Qualifiers::None));\r\n        } else if (const auto enumMemberDefinition = definition->tryGet<Definition::EnumMember>()) {\r\n            if (enumMemberDefinition->reducedExpression == nullptr) {\r\n                report->error(\"encountered a reference to enum value `\" + getResolvedIdentifierName(definition, pieces) + \"` before its value was known\", location);\r\n                return nullptr;\r\n            }\r\n            return enumMemberDefinition->reducedExpression->clone();\r\n        }\r\n\r\n        report->error(\"`\" + getResolvedIdentifierName(definition, pieces) + \"` cannot be used as an expression\", location);\r\n        return nullptr;\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::resolveTypeMemberExpression(const TypeExpression* typeExpression, StringView name) {\r\n        if (const auto resolvedTypeIdentifier = tryGetResolvedIdentifierTypeDefinition(typeExpression)) {\r\n            if (const auto enumDefinition = resolvedTypeIdentifier->tryGet<Definition::Enum>()) {\r\n                if (const auto enumMemberDefinition = enumDefinition->environment->findLocalMemberDefinition(name)) {\r\n                    return resolveDefinitionExpression(enumMemberDefinition, {}, typeExpression->location);\r\n                }\r\n            } else {\r\n                const auto prop = builtins.findPropertyByName(name);\r\n\r\n                if (const auto builtinIntegerType = resolvedTypeIdentifier->tryGet<Definition::BuiltinIntegerType>()) {\r\n                    switch (prop) {\r\n                        case Builtins::Property::MinValue: {\r\n                            return makeFwdUnique<const Expression>(Expression::IntegerLiteral(Int128(builtinIntegerType->min)), typeExpression->location,\r\n                                ExpressionInfo(EvaluationContext::CompileTime,\r\n                                    makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(resolvedTypeIdentifier), typeExpression->location),\r\n                                Qualifiers::None));\r\n                        }\r\n                        case Builtins::Property::MaxValue: {\r\n                            return makeFwdUnique<const Expression>(Expression::IntegerLiteral(Int128(builtinIntegerType->max)), typeExpression->location,\r\n                                ExpressionInfo(EvaluationContext::CompileTime,\r\n                                    makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(resolvedTypeIdentifier), typeExpression->location),\r\n                                Qualifiers::None));\r\n                        }\r\n                        default: break;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        report->error(\"`\" + getTypeName(typeExpression) + \"` has no member named `\" + name.toString() + \"`\", typeExpression->location);\r\n        return nullptr;\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::resolveValueMemberExpression(const Expression* expression, StringView name) {\r\n        const auto typeExpression = expression->info->type.get();\r\n\r\n        if (const auto resolvedTypeIdentifier = tryGetResolvedIdentifierTypeDefinition(typeExpression)) {\r\n            if (const auto structDefinition = resolvedTypeIdentifier->tryGet<Definition::Struct>()) {\r\n                if (const auto memberDefinition = structDefinition->environment->findLocalMemberDefinition(name)) {\r\n                    const auto& structMemberDefinition = memberDefinition->structMember;\r\n                    auto resultType = structMemberDefinition.resolvedType->clone();\r\n\r\n                    bool simplify = false;\r\n                    auto context = expression->info->context;\r\n                    Optional<Int128> absolutePosition;\r\n                    \r\n                    if (const auto structLiteral = expression->tryGet<Expression::StructLiteral>()) {\r\n                        const auto& match = structLiteral->items.find(name);\r\n                        return match->second->value->clone();\r\n                    } else if (const auto resolvedExpressionIdentifier = expression->tryGet<Expression::ResolvedIdentifier>()) {\r\n                        if (const auto varDefinition = resolvedExpressionIdentifier->definition->tryGet<Definition::Var>()) {\r\n                            simplify = true;\r\n\r\n                            if (varDefinition->address.hasValue() && varDefinition->address->absolutePosition.hasValue()) {\r\n                                absolutePosition = varDefinition->address->absolutePosition.get();\r\n                            }\r\n                        }\r\n                    } else if (const auto unaryOperator = expression->tryGet<Expression::UnaryOperator>()) {\r\n                        const auto& operand = unaryOperator->operand;\r\n                        if (unaryOperator->op == UnaryOperatorKind::Indirection) {\r\n                            simplify = true;\r\n                            context = unaryOperator->operand->info->context;\r\n\r\n                            if (const auto integerLiteral = operand->tryGet<Expression::IntegerLiteral>()) {\r\n                                absolutePosition = integerLiteral->value;\r\n                            }\r\n                        }\r\n                    } else if (const auto binaryOperator = expression->tryGet<Expression::BinaryOperator>()) {\r\n                        if (binaryOperator->op == BinaryOperatorKind::Indexing\r\n                        || binaryOperator->op == BinaryOperatorKind::UnalignedIndexing) {\r\n                            simplify = true;\r\n                        }\r\n                    }\r\n\r\n                    if (simplify) {\r\n                        return simplifyIndirectionOffsetExpression(std::move(resultType), expression, context, absolutePosition, Int128(*structMemberDefinition.offset));\r\n                    }\r\n\r\n                    return makeFwdUnique<const Expression>(\r\n                        Expression::FieldAccess(expression->clone(), memberDefinition->name),\r\n                        expression->location,\r\n                        ExpressionInfo(\r\n                            EvaluationContext::RunTime,\r\n                            std::move(resultType),\r\n                            expression->info->qualifiers & (Qualifiers::LValue | Qualifiers::Const | Qualifiers::WriteOnly | Qualifiers::Far)));\r\n                }\r\n            }\r\n        } else if (const auto functionType = typeExpression->tryGet<TypeExpression::Function>()) {\r\n            for (const auto& parameter : functionType->parameters) {\r\n                if (parameter->name == name) {                    \r\n                    if (const auto designatedStorage = parameter->parameterType->tryGet<TypeExpression::DesignatedStorage>()) {\r\n                        auto reducedHolder = reduceExpression(designatedStorage->holder.get());\r\n                        return reducedHolder;\r\n                    }\r\n                }\r\n            }\r\n        } else if (const auto& pointerType = typeExpression->tryGet<TypeExpression::Pointer>()) {\r\n            const auto qualifiers = Qualifiers::LValue | (pointerType->qualifiers & (Qualifiers::Const | Qualifiers::WriteOnly | Qualifiers::Far));\r\n            auto resultType = pointerType->elementType->clone();\r\n            auto indirection = makeFwdUnique<const Expression>(\r\n                Expression::UnaryOperator(UnaryOperatorKind::Indirection, expression->clone()), expression->location,\r\n                ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), qualifiers));\r\n            auto member = resolveValueMemberExpression(indirection.get(), name);\r\n            return member;\r\n        } else {\r\n            const auto prop = builtins.findPropertyByName(name);\r\n            switch (prop) {\r\n                case Builtins::Property::Len: {\r\n                     if (const auto& arrayType = typeExpression->tryGet<TypeExpression::Array>()) {\r\n                         if (const auto& sizeLiteral = arrayType->size->tryGet<Expression::IntegerLiteral>()) {\r\n                             return makeFwdUnique<const Expression>(Expression::IntegerLiteral(Int128(sizeLiteral->value)), expression->location,\r\n                                 ExpressionInfo(EvaluationContext::CompileTime,\r\n                                     makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), expression->location),\r\n                                 Qualifiers::None));\r\n                         } else {\r\n                             report->error(\"`\" + getTypeName(typeExpression) + \"` expression has unknown length\", expression->location);\r\n                         }\r\n                     } else if (const auto len = tryGetSequenceLiteralLength(expression)) {\r\n                        return makeFwdUnique<const Expression>(Expression::IntegerLiteral(Int128(*len)), expression->location,\r\n                            ExpressionInfo(EvaluationContext::CompileTime,\r\n                                makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), expression->location),\r\n                            Qualifiers::None));\r\n                    } else {\r\n                        report->error(\"`\" + getTypeName(typeExpression) + \"` expression has unknown length\", expression->location);\r\n                    }\r\n                }\r\n                default: break;\r\n            }\r\n        }\r\n\r\n        report->error(\"`\" + getTypeName(typeExpression) + \"` has no field named `\" + name.toString() + \"`\", expression->location);\r\n        return nullptr;\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::simplifyIndirectionOffsetExpression(FwdUniquePtr<const TypeExpression> resultType, const Expression* expression, EvaluationContext context, Optional<Int128> absolutePosition, Int128 offset) {\r\n        const auto qualifiers = expression->info->qualifiers & (Qualifiers::LValue | Qualifiers::Const | Qualifiers::WriteOnly | Qualifiers::Far);\r\n        auto addressType = makeFwdUnique<const TypeExpression>(\r\n            TypeExpression::Pointer(\r\n                resultType->clone(),\r\n                qualifiers & (Qualifiers::Const | Qualifiers::WriteOnly | Qualifiers::Far)),\r\n            expression->info->type->location);\r\n\r\n        if (absolutePosition.hasValue()) {\r\n            if (resultType->kind == TypeExpressionKind::Array) {\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::IntegerLiteral(Int128(absolutePosition.get()) + offset),\r\n                    expression->location,\r\n                    ExpressionInfo(EvaluationContext::CompileTime, std::move(resultType), qualifiers));\r\n            } else {\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::UnaryOperator(\r\n                        UnaryOperatorKind::Indirection,\r\n                        makeFwdUnique<const Expression>(\r\n                            Expression::IntegerLiteral(Int128(absolutePosition.get()) + offset),\r\n                            expression->location,\r\n                            ExpressionInfo(EvaluationContext::CompileTime, std::move(addressType), Qualifiers::None))),\r\n                    expression->location,\r\n                    ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), qualifiers));\r\n            }\r\n        } else {\r\n            if (resultType->kind == TypeExpressionKind::Array) {\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::BinaryOperator(\r\n                        BinaryOperatorKind::Addition,\r\n                        expression->clone(),\r\n                        makeFwdUnique<const Expression>(\r\n                            Expression::IntegerLiteral(offset),\r\n                            expression->location,\r\n                            ExpressionInfo(\r\n                                EvaluationContext::CompileTime,\r\n                                makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), expression->location),\r\n                                Qualifiers::None))),\r\n                    expression->location,\r\n                    ExpressionInfo(context, std::move(resultType), qualifiers));\r\n            } else {\r\n                const auto pointerSizedType = (qualifiers & Qualifiers::Far) != Qualifiers::None ? platform->getFarPointerSizedType() : platform->getPointerSizedType();\r\n                const auto addressOfOp = (qualifiers & Qualifiers::Far) != Qualifiers::None ? UnaryOperatorKind::FarAddressOf : UnaryOperatorKind::AddressOf;\r\n                auto addressOf = makeFwdUnique<const Expression>(Expression::UnaryOperator(addressOfOp, expression->clone()), expression->location, Optional<ExpressionInfo>());\r\n                auto reducedAddressOf = reduceExpression(addressOf.get());\r\n\r\n                if (!reducedAddressOf) {\r\n                    return nullptr;\r\n                }\r\n\r\n                \/\/ If there are nested struct member accesses, fold together the constant offset part.\r\n                if (const auto cast = reducedAddressOf->tryGet<Expression::Cast>()) {\r\n                    const auto& castOperand = cast->operand;\r\n\r\n                    if (const auto binaryOperator = castOperand->tryGet<Expression::BinaryOperator>()) {\r\n                        if (binaryOperator->op == BinaryOperatorKind::Addition) {\r\n                            const auto& left = binaryOperator->left;\r\n                            const auto& right = binaryOperator->right;\r\n\r\n                            if (const auto offsetLiteral = right->tryGet<Expression::IntegerLiteral>()) {\r\n                                reducedAddressOf = left->clone();\r\n                                offset += offsetLiteral->value;\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::UnaryOperator(\r\n                        UnaryOperatorKind::Indirection,\r\n                        makeFwdUnique<const Expression>(\r\n                            Expression::Cast(\r\n                                makeFwdUnique<const Expression>(\r\n                                    Expression::BinaryOperator(\r\n                                        BinaryOperatorKind::Addition,\r\n                                        makeFwdUnique<const Expression>(\r\n                                            Expression::Cast(\r\n                                                std::move(reducedAddressOf),\r\n                                                makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(pointerSizedType), expression->location)),\r\n                                            expression->location,\r\n                                            ExpressionInfo(\r\n                                                context, \r\n                                                makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(pointerSizedType), expression->location),\r\n                                                Qualifiers::None)),\r\n                                        makeFwdUnique<const Expression>(\r\n                                            Expression::IntegerLiteral(offset),\r\n                                            expression->location,\r\n                                            ExpressionInfo(\r\n                                                EvaluationContext::CompileTime,\r\n                                                makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), expression->location),\r\n                                                Qualifiers::None))),\r\n                                    expression->location,\r\n                                    ExpressionInfo(\r\n                                        context,\r\n                                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(pointerSizedType), expression->location),\r\n                                        Qualifiers::None)),\r\n                            addressType->clone()),\r\n                            expression->location,\r\n                            ExpressionInfo(context, addressType->clone(), Qualifiers::None))),\r\n                        expression->location,\r\n                        ExpressionInfo(EvaluationContext::RunTime, std::move(resultType), qualifiers));\r\n            }\r\n        }\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::simplifyLogicalNotExpression(const Expression* expression, FwdUniquePtr<const Expression> operand) {\r\n        const auto resultType = operand->info->type.get();\r\n\r\n        if (isBooleanType(resultType)) {\r\n            if (operand->info->context == EvaluationContext::RunTime) {\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::UnaryOperator(UnaryOperatorKind::LogicalNegation, std::move(operand)), expression->location,\r\n                    ExpressionInfo(EvaluationContext::RunTime, resultType->clone(), Qualifiers::None));\r\n            } else if (operand->info->context == EvaluationContext::LinkTime) {\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::UnaryOperator(UnaryOperatorKind::LogicalNegation, std::move(operand)), expression->location,\r\n                    ExpressionInfo(EvaluationContext::LinkTime, resultType->clone(), Qualifiers::None));\r\n            } else {\r\n                const auto operandValue = operand->booleanLiteral.value;\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::BooleanLiteral(!operandValue), expression->location,\r\n                    ExpressionInfo(EvaluationContext::CompileTime, resultType->clone(), Qualifiers::None));\r\n            }\r\n        }\r\n                           \r\n        report->error(getUnaryOperatorName(UnaryOperatorKind::LogicalNegation).toString() + \" is not defined for provided operand type `\" + getTypeName(resultType) + \"`\", expression->location);\r\n        return nullptr;\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::simplifyBinaryArithmeticExpression(const Expression* expression, BinaryOperatorKind op, FwdUniquePtr<const Expression> left, FwdUniquePtr<const Expression> right) {\r\n        if (const auto resultType = findCompatibleBinaryArithmeticExpressionType(left.get(), right.get())) {\r\n            const auto leftContext = left->info->context;\r\n            const auto rightContext = right->info->context;\r\n            if (leftContext == EvaluationContext::RunTime || rightContext == EvaluationContext::RunTime) {\r\n                return makeFwdUnique<const Expression>(Expression::BinaryOperator(op, std::move(left), std::move(right)), expression->location,\r\n                    ExpressionInfo(EvaluationContext::RunTime, resultType->clone(), Qualifiers::None));\r\n            } else if (leftContext == EvaluationContext::LinkTime || rightContext == EvaluationContext::LinkTime) {\r\n                return makeFwdUnique<const Expression>(Expression::BinaryOperator(op, std::move(left), std::move(right)), expression->location,\r\n                    ExpressionInfo(EvaluationContext::LinkTime, resultType->clone(), Qualifiers::None));\r\n            } else {\r\n                const auto leftValue = left->integerLiteral.value;\r\n                const auto rightValue = right->integerLiteral.value;\r\n                const auto result = applyIntegerArithmeticOp(op, leftValue, rightValue);\r\n\r\n                switch (result.first) {\r\n                    case Int128::CheckedArithmeticResult::Success: {\r\n                        const auto& value = result.second;\r\n                        if (const auto typeDefinition = tryGetResolvedIdentifierTypeDefinition(resultType)) {\r\n                            if (const auto builtinIntegerType = typeDefinition->tryGet<Definition::BuiltinIntegerType>()) {\r\n                                if (value < builtinIntegerType->min || value > builtinIntegerType->max) {\r\n                                    report->error(getBinaryOperatorName(op).toString() + \" resulted in `\" + getTypeName(resultType) + \"` value of `\" + value.toString() + \"` outside valid range `\" + builtinIntegerType->min.toString() + \"` .. `\" + builtinIntegerType->max.toString() + \"`\", expression->location);\r\n                                    return nullptr;\r\n                                }\r\n                            }\r\n                        }\r\n                        return makeFwdUnique<const Expression>(Expression::IntegerLiteral(result.second), expression->location, \r\n                            ExpressionInfo(EvaluationContext::CompileTime, resultType->clone(), Qualifiers::None));\r\n                    }\r\n                    case Int128::CheckedArithmeticResult::OverflowError: {\r\n                        report->error(getBinaryOperatorName(op).toString() + \" resulted in overflow\", right->location);\r\n                        return nullptr;\r\n                    }\r\n                    case Int128::CheckedArithmeticResult::DivideByZeroError: {\r\n                        report->error(getBinaryOperatorName(op).toString() + \" by zero\", right->location);\r\n                        return nullptr;\r\n                    }\r\n                    default: std::abort();\r\n                }\r\n            }\r\n        }\r\n        report->error(getBinaryOperatorName(op).toString() + \" is not defined between provided operand types `\" + getTypeName(left->info->type.get()) + \"` and `\" + getTypeName(right->info->type.get()) + \"`\", expression->location);\r\n        return nullptr;\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::simplifyBinaryLogicalExpression(const Expression* expression, BinaryOperatorKind op, FwdUniquePtr<const Expression> left, FwdUniquePtr<const Expression> right) {\r\n        if (isBooleanType(left->info->type.get()) && isBooleanType(right->info->type.get())) {\r\n            bool isValidOperator = false;\r\n            switch (op) {\r\n                case BinaryOperatorKind::LogicalAnd:\r\n                case BinaryOperatorKind::LogicalOr:\r\n                case BinaryOperatorKind::BitwiseAnd:\r\n                case BinaryOperatorKind::BitwiseOr:\r\n                case BinaryOperatorKind::BitwiseXor:\r\n                    isValidOperator = true;\r\n                default: break;\r\n            }\r\n\r\n            if (isValidOperator) {\r\n                const auto leftLiteral = left->tryGet<Expression::BooleanLiteral>();\r\n                const auto rightLiteral = right->tryGet<Expression::BooleanLiteral>();\r\n\r\n                if (leftLiteral != nullptr && rightLiteral != nullptr) {\r\n                    bool result = false;\r\n                    switch (op) {\r\n                        case BinaryOperatorKind::LogicalAnd: result = leftLiteral->value && rightLiteral->value;  break;\r\n                        case BinaryOperatorKind::LogicalOr: result = leftLiteral->value || rightLiteral->value; break;\r\n                        case BinaryOperatorKind::BitwiseAnd: result = leftLiteral->value && rightLiteral->value; break;\r\n                        case BinaryOperatorKind::BitwiseOr: result = leftLiteral->value || rightLiteral->value; break;\r\n                        case BinaryOperatorKind::BitwiseXor: result = leftLiteral->value != rightLiteral->value; break;\r\n                        default: std::abort(); break;\r\n                    }\r\n\r\n                    return makeFwdUnique<const Expression>(\r\n                        Expression::BooleanLiteral(result), expression->location,\r\n                        ExpressionInfo(EvaluationContext::CompileTime,\r\n                            makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Bool)), expression->location),\r\n                            Qualifiers::None));\r\n                } else if (op == BinaryOperatorKind::LogicalAnd)  {\r\n                    if ((leftLiteral != nullptr && !leftLiteral->value) || (rightLiteral != nullptr && !rightLiteral->value)) {\r\n                        return makeFwdUnique<const Expression>(\r\n                            Expression::BooleanLiteral(false), expression->location,\r\n                            ExpressionInfo(EvaluationContext::CompileTime,\r\n                                makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Bool)), expression->location),\r\n                                Qualifiers::None));\r\n                    } else if (leftLiteral != nullptr && leftLiteral->value) {\r\n                        return right;\r\n                    } else if (rightLiteral != nullptr && rightLiteral->value) {\r\n                        return left;\r\n                    }\r\n                } else if (op == BinaryOperatorKind::LogicalOr)  {\r\n                    if ((leftLiteral != nullptr && leftLiteral->value) || (rightLiteral != nullptr && rightLiteral->value)) {\r\n                        return makeFwdUnique<const Expression>(\r\n                            Expression::BooleanLiteral(true), expression->location,\r\n                            ExpressionInfo(EvaluationContext::CompileTime,\r\n                                makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Bool)), expression->location),\r\n                                Qualifiers::None));\r\n                    } else if (leftLiteral != nullptr && !leftLiteral->value) {\r\n                        return right;\r\n                    } else if (rightLiteral != nullptr && !rightLiteral->value) {\r\n                        return left;\r\n                    }\r\n                }\r\n\r\n                const auto isRuntime = left->info->context == EvaluationContext::RunTime || right->info->context == EvaluationContext::RunTime;\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::BinaryOperator(op, std::move(left), std::move(right)),\r\n                    expression->location,\r\n                    ExpressionInfo(isRuntime ? EvaluationContext::RunTime : EvaluationContext::LinkTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Bool)), expression->location),\r\n                        Qualifiers::None));\r\n            }\r\n        }\r\n\r\n        report->error(getBinaryOperatorName(op).toString() + \" is not defined between provided operand types `\" + getTypeName(left->info->type.get()) + \"` and `\" + getTypeName(right->info->type.get()) + \"`\", expression->location);\r\n        return nullptr;\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::simplifyBinaryRotateExpression(const Expression* expression, BinaryOperatorKind op, FwdUniquePtr<const Expression> left, FwdUniquePtr<const Expression> right) {\r\n        if (const auto resultType = findCompatibleBinaryArithmeticExpressionType(left.get(), right.get())) {\r\n            if (const auto resultTypeDefinition = tryGetResolvedIdentifierTypeDefinition(resultType)) {\r\n                if (const auto resultBuiltinIntegerType = resultTypeDefinition->tryGet<Definition::BuiltinIntegerType>()) {\r\n                    const auto leftContext = left->info->context;\r\n                    const auto rightContext = right->info->context;\r\n                    if (leftContext == EvaluationContext::RunTime || rightContext == EvaluationContext::RunTime) {\r\n                        return makeFwdUnique<const Expression>(Expression::BinaryOperator(op, std::move(left), std::move(right)), expression->location,\r\n                            ExpressionInfo(EvaluationContext::RunTime, resultType->clone(), Qualifiers::None));            \r\n                    } else if (leftContext == EvaluationContext::LinkTime || rightContext == EvaluationContext::LinkTime) {\r\n                        return makeFwdUnique<const Expression>(Expression::BinaryOperator(op, std::move(left), std::move(right)), expression->location,\r\n                            ExpressionInfo(EvaluationContext::LinkTime, resultType->clone(), Qualifiers::None));\r\n                    } else {\r\n                        const auto value = left->integerLiteral.value;\r\n                        std::size_t bits = right->integerLiteral.value >= Int128(SIZE_MAX)\r\n                            ? SIZE_MAX\r\n                            : static_cast<size_t>(right->integerLiteral.value);\r\n\r\n                        bits %= 8 * resultBuiltinIntegerType->size;\r\n\r\n                        switch (op) {\r\n                            case BinaryOperatorKind::LeftRotate: {\r\n                                const auto result = value.logicalLeftShift(bits) | value.logicalRightShift(8 * resultBuiltinIntegerType->size - bits);\r\n                                return makeFwdUnique<const Expression>(Expression::IntegerLiteral(result), expression->location, \r\n                                    ExpressionInfo(EvaluationContext::CompileTime, resultType->clone(), Qualifiers::None));\r\n                            }\r\n                            case BinaryOperatorKind::RightRotate: {\r\n                                const auto result = value.logicalRightShift(bits) | value.logicalLeftShift(8 * resultBuiltinIntegerType->size - bits);\r\n                                return makeFwdUnique<const Expression>(Expression::IntegerLiteral(result), expression->location, \r\n                                    ExpressionInfo(EvaluationContext::CompileTime, resultType->clone(), Qualifiers::None));\r\n                            }\r\n                            default: std::abort();\r\n                        }\r\n                    }\r\n                }\r\n            }            \r\n        }\r\n        report->error(getBinaryOperatorName(op).toString() + \" is not defined between provided operand types `\" + getTypeName(left->info->type.get()) + \"` and `\" + getTypeName(right->info->type.get()) + \"`\", expression->location);\r\n        return nullptr;\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::simplifyBinaryComparisonExpression(const Expression* expression, BinaryOperatorKind op, FwdUniquePtr<const Expression> left, FwdUniquePtr<const Expression> right) {\r\n        const auto leftContext = left->info->context;\r\n        const auto rightContext = right->info->context;\r\n\r\n        if (const auto commonType = findCompatibleBinaryArithmeticExpressionType(left.get(), right.get())) {\r\n            static_cast<void>(commonType);\r\n\r\n            if (leftContext == EvaluationContext::RunTime || rightContext == EvaluationContext::RunTime) {\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::BinaryOperator(op, std::move(left), std::move(right)), expression->location,\r\n                    ExpressionInfo(EvaluationContext::RunTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Bool)), expression->location),\r\n                        Qualifiers::None));\r\n            } else if (leftContext == EvaluationContext::LinkTime || rightContext == EvaluationContext::LinkTime) {\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::BinaryOperator(op, std::move(left), std::move(right)), expression->location,\r\n                    ExpressionInfo(EvaluationContext::LinkTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Bool)), expression->location),\r\n                        Qualifiers::None));\r\n            } else {\r\n                const auto leftValue = left->integerLiteral.value;\r\n                const auto rightValue = right->integerLiteral.value;\r\n                const auto result = applyIntegerComparisonOp(op, leftValue, rightValue);\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::BooleanLiteral(result), expression->location,\r\n                    ExpressionInfo(EvaluationContext::CompileTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Bool)), expression->location),\r\n                        Qualifiers::None));\r\n            }\r\n        } else if (isBooleanType(left->info->type.get()) && isBooleanType(right->info->type.get())) {\r\n            if (leftContext == EvaluationContext::RunTime || rightContext == EvaluationContext::RunTime) {\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::BinaryOperator(op, std::move(left), std::move(right)), expression->location,\r\n                    ExpressionInfo(EvaluationContext::RunTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Bool)), expression->location),\r\n                        Qualifiers::None));\r\n            } else if (leftContext == EvaluationContext::LinkTime || rightContext == EvaluationContext::LinkTime) {\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::BinaryOperator(op, std::move(left), std::move(right)), expression->location,\r\n                    ExpressionInfo(EvaluationContext::LinkTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Bool)), expression->location),\r\n                        Qualifiers::None));\r\n            } else {\r\n                const auto leftValue = left->booleanLiteral.value;\r\n                const auto rightValue = right->booleanLiteral.value;                   \r\n                const auto result = applyBooleanComparisonOp(op, leftValue, rightValue);\r\n                return makeFwdUnique<const Expression>(\r\n                    Expression::BooleanLiteral(result), expression->location,\r\n                    ExpressionInfo(EvaluationContext::CompileTime,\r\n                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::Bool)), expression->location),\r\n                        Qualifiers::None));\r\n            }\r\n        }\r\n\r\n        report->error(getBinaryOperatorName(op).toString() + \" is not defined between provided operand types `\" + getTypeName(left->info->type.get()) + \"` and `\" + getTypeName(right->info->type.get()) + \"`\", expression->location);\r\n        return nullptr;\r\n    }\r\n\r\n    bool Compiler::isSimpleCast(const Expression* expression) const {\r\n        if (const auto cast = expression->tryGet<Expression::Cast>()) {\r\n            const auto originalSize = calculateStorageSize(cast->operand->info->type.get(), \"\"_sv);\r\n            const auto castedSize = calculateStorageSize(expression->info->type.get(), \"\"_sv);\r\n            if (originalSize.hasValue() && castedSize.hasValue() && *originalSize == *castedSize) {\r\n                return true;\r\n            }\r\n        }\r\n\r\n        return false;\r\n    }\r\n\r\n    bool Compiler::isTypeDefinition(const Definition* definition) const {\r\n        if (definition->kind == DefinitionKind::BuiltinBankType\r\n        || definition->kind == DefinitionKind::BuiltinBoolType\r\n        || definition->kind == DefinitionKind::BuiltinIntegerType\r\n        || definition->kind == DefinitionKind::BuiltinIntegerExpressionType\r\n        || definition->kind == DefinitionKind::BuiltinRangeType\r\n        || definition->kind == DefinitionKind::Enum\r\n        || definition->kind == DefinitionKind::Struct) {\r\n            return true;\r\n        }\r\n        return false;\r\n    }\r\n\r\n    Definition* Compiler::tryGetResolvedIdentifierTypeDefinition(const TypeExpression* typeExpression) const {\r\n        if (typeExpression != nullptr) {\r\n            if (const auto resolvedDefinitionType = typeExpression->tryGet<TypeExpression::ResolvedIdentifier>()) {\r\n                const auto definition = resolvedDefinitionType->definition;\r\n                if (isTypeDefinition(definition)) {\r\n                    return definition;\r\n                }\r\n            }\r\n        }\r\n\r\n        return nullptr;\r\n    }\r\n\r\n    bool Compiler::isIntegerType(const TypeExpression* typeExpression) const {\r\n        const auto definition = tryGetResolvedIdentifierTypeDefinition(typeExpression);\r\n        if (definition != nullptr) {\r\n            return definition->kind == DefinitionKind::BuiltinIntegerExpressionType\r\n            || definition->kind == DefinitionKind::BuiltinIntegerType;\r\n        } else {\r\n            return false;\r\n        }\r\n    }\r\n\r\n    bool Compiler::isBooleanType(const TypeExpression* typeExpression) const {\r\n        const auto definition = tryGetResolvedIdentifierTypeDefinition(typeExpression);\r\n        return definition != nullptr && definition->kind == DefinitionKind::BuiltinBoolType;\r\n    }\r\n\r\n    bool Compiler::isEmptyTupleType(const TypeExpression* typeExpression) const {\r\n        if (const auto tupleReturnType = typeExpression->tryGet<TypeExpression::Tuple>()) {\r\n            if (tupleReturnType->elementTypes.size() == 0) {\r\n                return true;\r\n            }\r\n        }\r\n        return false;\r\n    }\r\n\r\n    bool Compiler::isEnumType(const TypeExpression* typeExpression) const {\r\n        const auto definition = tryGetResolvedIdentifierTypeDefinition(typeExpression);\r\n        if (definition != nullptr) {\r\n            return definition->kind == DefinitionKind::Enum;\r\n        } else {\r\n            return false;\r\n        }\r\n    }\r\n\r\n    bool Compiler::isPointerLikeType(const TypeExpression* typeExpression) const {\r\n        return typeExpression->kind == TypeExpressionKind::Pointer || typeExpression->kind == TypeExpressionKind::Function;\r\n    }\r\n\r\n    bool Compiler::isFarType(const TypeExpression* typeExpression) const {\r\n        if (const auto pointerType = typeExpression->tryGet<TypeExpression::Pointer>()) {\r\n            return (pointerType->qualifiers & Qualifiers::Far) == Qualifiers::Far;\r\n        } else if (const auto functionType = typeExpression->tryGet<TypeExpression::Function>()) {\r\n            return functionType->far;\r\n        } \r\n        return false;\r\n    }\r\n\r\n    const TypeExpression* Compiler::getDesignatedStorageElementType(const TypeExpression* typeExpression) const {\r\n        while (typeExpression->kind == TypeExpressionKind::DesignatedStorage) {\r\n            typeExpression = typeExpression->designatedStorage.elementType.get();\r\n        }\r\n        return typeExpression;\r\n    }\r\n\r\n    const TypeExpression* Compiler::findCompatibleBinaryArithmeticExpressionType(const Expression* left, const Expression* right) const {\r\n        if (left == nullptr || right == nullptr || left->info->type == nullptr || right->info->type == nullptr) {\r\n            return nullptr;\r\n        }\r\n\r\n        \/\/ Check both left and right have integral types.\r\n        const auto leftDefinition = tryGetResolvedIdentifierTypeDefinition(left->info->type.get());\r\n        const auto rightDefinition = tryGetResolvedIdentifierTypeDefinition(right->info->type.get());\r\n        if (leftDefinition != nullptr && rightDefinition != nullptr) {\r\n            if (isIntegerType(left->info->type.get()) && isIntegerType(right->info->type.get())) {\r\n                \/\/ If left type and right type are same type, return that type.\r\n                if (leftDefinition == rightDefinition) {\r\n                    return left->info->type.get();\r\n                }\r\n                \/\/ If left type is iexpr and right side isn't, attempt to narrow to right side type.\r\n                if (leftDefinition->kind == DefinitionKind::BuiltinIntegerExpressionType\r\n                && rightDefinition->kind == DefinitionKind::BuiltinIntegerType\r\n                && canNarrowIntegerExpression(left, rightDefinition)) {\r\n                    return right->info->type.get();\r\n                }\r\n                \/\/ If right type is iexpr and left side isn't, attempt to narrow to right side type.\r\n                if (rightDefinition->kind == DefinitionKind::BuiltinIntegerExpressionType\r\n                && leftDefinition->kind == DefinitionKind::BuiltinIntegerType\r\n                && canNarrowIntegerExpression(right, leftDefinition)) {\r\n                    return left->info->type.get();\r\n                }\r\n            }\r\n        }\r\n\r\n        \/\/ Otherwise, failure to find a common type.\r\n        return nullptr;\r\n    }\r\n\r\n    const TypeExpression* Compiler::findCompatibleConcatenationExpressionType(const Expression* left, const Expression* right) const {\r\n        if (left == nullptr || right == nullptr || left->info->type == nullptr || right->info->type == nullptr) {\r\n            return nullptr;\r\n        }\r\n\r\n        if (const auto leftArrayType = left->info->type->tryGet<TypeExpression::Array>()) {\r\n            if (const auto rightArrayType = right->info->type->tryGet<TypeExpression::Array>()) {\r\n                const auto leftElementType = leftArrayType->elementType.get();\r\n                const auto rightElementType = rightArrayType->elementType.get();\r\n\r\n                if (isTypeEquivalent(leftElementType, rightElementType)) {\r\n                    return left->info->type.get();\r\n                }\r\n\r\n                if (const auto leftArray = left->tryGet<Expression::ArrayLiteral>()) {\r\n                    bool success = true;\r\n                    for (const auto& item : leftArray->items) {\r\n                        if (!canNarrowExpression(item.get(), rightElementType)) {\r\n                            success = false;\r\n                            break;\r\n                        }\r\n                    }\r\n                    if (success) {\r\n                        return right->info->type.get();\r\n                    }\r\n                }\r\n\r\n                if (const auto rightArray = left->tryGet<Expression::ArrayLiteral>()) {\r\n                    bool success = true;\r\n                    for (const auto& item : rightArray->items) {\r\n                        if (!canNarrowExpression(item.get(), leftElementType)) {\r\n                            success = false;\r\n                            break;\r\n                        }\r\n                    }\r\n                    if (success) {\r\n                        return left->info->type.get();\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        return nullptr;\r\n    }\r\n\r\n\r\n    const TypeExpression* Compiler::findCompatibleAssignmentType(const Expression* initializer, const TypeExpression* declarationType) const {\r\n        \/\/ TODO: prevent declaring anything as iexpr, [iexpr], etc or any other type without a guaranteed size after compilation.\r\n        \/\/ TODO: probably need to recurse array types to handle complex cases like, [[[iexpr]]] -> [[[integer type]]]\r\n        \/\/ TODO: if declaration type is an array with no explicit size, use initializer's known size.\r\n\r\n        if (initializer == nullptr || declarationType == nullptr) {\r\n            return nullptr;\r\n        }\r\n\r\n        if (canNarrowExpression(initializer, declarationType)) {\r\n            const auto& initializerType = initializer->info->type;\r\n\r\n            if (const auto sourceArrayType = initializerType->tryGet<TypeExpression::Array>()) {\r\n                if (const auto destinationArrayType = declarationType->tryGet<TypeExpression::Array>()) {\r\n                    if (sourceArrayType->size && destinationArrayType->size) {\r\n                        const auto sourceSize = sourceArrayType->size->integerLiteral.value;\r\n                        const auto destinationSize = destinationArrayType->size->integerLiteral.value;\r\n\r\n                        if (sourceSize != destinationSize) {\r\n                            return nullptr;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            return declarationType;\r\n        }\r\n\r\n        return nullptr;\r\n    }\r\n\r\n    bool Compiler::canNarrowExpression(const Expression* sourceExpression, const TypeExpression* destinationType) const {\r\n        if (sourceExpression == nullptr || destinationType == nullptr) {\r\n            return false;\r\n        }\r\n\r\n        const auto sourceExpressionType = sourceExpression->info->type.get();\r\n\r\n        if (const auto destinationArrayType = destinationType->tryGet<TypeExpression::Array>()) {\r\n            if (const auto sourceArrayType = sourceExpressionType->tryGet<TypeExpression::Array>()) {\r\n                if (destinationArrayType->size != nullptr && sourceArrayType->size->integerLiteral.value != destinationArrayType->size->integerLiteral.value) {\r\n                    return false;\r\n                }\r\n\r\n                const auto sourceElementType = sourceArrayType->elementType.get();\r\n                const auto destinationElementType = destinationArrayType->elementType.get();\r\n\r\n                if (isTypeEquivalent(destinationElementType, sourceElementType)) {\r\n                    return true;\r\n                }\r\n\r\n                if (const auto sourceArray = sourceExpression->tryGet<Expression::ArrayLiteral>()) {\r\n                    for (const auto& item : sourceArray->items) {\r\n                        if (!canNarrowExpression(item.get(), destinationElementType)) {\r\n                            return false;\r\n                        }\r\n                    }\r\n\r\n                    return true;\r\n                }\r\n            }\r\n        }\r\n\r\n        if (destinationType->kind == TypeExpressionKind::DesignatedStorage) {\r\n            return canNarrowExpression(sourceExpression, getDesignatedStorageElementType(destinationType));\r\n        }\r\n\r\n        if (const auto destinationPointerType = destinationType->tryGet<TypeExpression::Pointer>()) {\r\n            if (const auto sourcePointerType = sourceExpressionType->tryGet<TypeExpression::Pointer>()) {\r\n                const auto destinationElementType = destinationPointerType->elementType.get();\r\n                const auto sourceElementType = sourcePointerType->elementType.get();\r\n\r\n                if (isTypeEquivalent(destinationElementType, sourceElementType)\r\n                && (((sourcePointerType->qualifiers & Qualifiers::WriteOnly) == Qualifiers::None\r\n                        && (destinationPointerType->qualifiers & Qualifiers::Const) != Qualifiers::None)\r\n                    || ((sourcePointerType->qualifiers & Qualifiers::Const) == Qualifiers::None\r\n                        && (destinationPointerType->qualifiers & Qualifiers::WriteOnly) != Qualifiers::None))\r\n                && ((sourcePointerType->qualifiers & Qualifiers::Far) == (destinationPointerType->qualifiers & Qualifiers::Far)\r\n                    || (destinationPointerType->qualifiers & Qualifiers::Far) == Qualifiers::None)) {\r\n                    return true;\r\n                }\r\n            }\r\n        }\r\n\r\n        if (const auto destinationTypeDefinition = tryGetResolvedIdentifierTypeDefinition(destinationType)) {\r\n            if (const auto sourceExpressionTypeDefinition = tryGetResolvedIdentifierTypeDefinition(sourceExpressionType)) {\r\n                \/\/ If source expression type and definition type are same type, return that type.\r\n                if (sourceExpressionTypeDefinition == destinationTypeDefinition) {\r\n                    return true;\r\n                }\r\n\r\n                \/\/ Are they different types, but both integers?\r\n                if (isIntegerType(sourceExpressionType) && isIntegerType(destinationType)) {\r\n                    \/\/ If source expression type is iexpr and destination type is some bounded integer type, attempt to narrow to destination type.\r\n                    if (sourceExpressionTypeDefinition->kind == DefinitionKind::BuiltinIntegerExpressionType) {\r\n                        return canNarrowIntegerExpression(sourceExpression, destinationTypeDefinition);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        return isTypeEquivalent(sourceExpressionType, destinationType);\r\n    }\r\n\r\n    bool Compiler::canNarrowIntegerExpression(const Expression* expression, const Definition* integerTypeDefinition) const {\r\n        if (const auto integerLiteral = expression->tryGet<Expression::IntegerLiteral>()) {\r\n            if (const auto builtinIntegerType = integerTypeDefinition->tryGet<Definition::BuiltinIntegerType>()) {            \r\n                if (integerLiteral->value >= builtinIntegerType->min\r\n                && integerLiteral->value <= builtinIntegerType->max) {\r\n                    return true;\r\n                }\r\n            }\r\n        }\r\n\r\n        return false;\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::createConvertedExpression(const Expression* sourceExpression, const TypeExpression* destinationType) const {\r\n        if (sourceExpression == nullptr || destinationType == nullptr) {\r\n            return nullptr;\r\n        }\r\n\r\n        const auto sourceExpressionType = sourceExpression->info->type.get();\r\n\r\n        if (const auto destinationArrayType = destinationType->tryGet<TypeExpression::Array>()) {\r\n            if (const auto sourceArrayType = sourceExpressionType->tryGet<TypeExpression::Array>()) {\r\n                const auto destinationElementType = destinationArrayType->elementType.get();\r\n\r\n                if (isTypeEquivalent(destinationElementType, sourceArrayType->elementType.get())) {\r\n                    return sourceExpression->clone();\r\n                }\r\n\r\n                if (const auto sourceArray = sourceExpression->tryGet<Expression::ArrayLiteral>()) {\r\n                    std::vector<FwdUniquePtr<const Expression>> convertedItems;\r\n                    convertedItems.reserve(sourceArray->items.size());\r\n\r\n                    for (const auto& item : sourceArray->items) {\r\n                        convertedItems.push_back(createConvertedExpression(item.get(), destinationElementType));\r\n                    }\r\n\r\n                    return createArrayLiteralExpression(std::move(convertedItems), destinationElementType, sourceExpression->location);\r\n                }\r\n            }\r\n        }\r\n\r\n        if (isTypeEquivalent(sourceExpressionType, destinationType)) {\r\n            return sourceExpression->clone();\r\n        }\r\n\r\n        if (destinationType->kind == TypeExpressionKind::DesignatedStorage) {\r\n            return createConvertedExpression(sourceExpression, getDesignatedStorageElementType(destinationType));\r\n        }\r\n\r\n        \/\/ Adding const or writeonly to expression that didn't have it.\r\n        if (const auto destinationPointerType = destinationType->tryGet<TypeExpression::Pointer>()) {\r\n            if (const auto sourcePointerType = sourceExpressionType->tryGet<TypeExpression::Pointer>()) {\r\n                const auto destinationElementType = destinationPointerType->elementType.get();\r\n                const auto sourceElementType = sourcePointerType->elementType.get();\r\n\r\n                if (isTypeEquivalent(destinationElementType, sourceElementType)\r\n                && (((sourcePointerType->qualifiers & Qualifiers::WriteOnly) == Qualifiers::None\r\n                        && (destinationPointerType->qualifiers & Qualifiers::Const) != Qualifiers::None)\r\n                    || ((sourcePointerType->qualifiers & Qualifiers::Const) == Qualifiers::None\r\n                        && (destinationPointerType->qualifiers & Qualifiers::WriteOnly) != Qualifiers::None))\r\n                && ((sourcePointerType->qualifiers & Qualifiers::Far) == (destinationPointerType->qualifiers & Qualifiers::Far)\r\n                    || (destinationPointerType->qualifiers & Qualifiers::Far) == Qualifiers::None)) {\r\n                    return sourceExpression->clone(\r\n                        sourceExpression->location,\r\n                        ExpressionInfo(\r\n                            sourceExpression->info->context,\r\n                            destinationType->clone(),\r\n                            sourceExpression->info->qualifiers));\r\n                }\r\n            }\r\n        }\r\n\r\n        if (const auto destinationTypeDefinition = tryGetResolvedIdentifierTypeDefinition(destinationType)) {\r\n            if (const auto sourceExpressionTypeDefinition = tryGetResolvedIdentifierTypeDefinition(sourceExpressionType)) {\r\n                \/\/ If source expression type and definition type are same type, return that type.\r\n                if (sourceExpressionTypeDefinition == destinationTypeDefinition) {\r\n                    return sourceExpression->clone();\r\n                }\r\n\r\n                \/\/ Are they different types, but both integers?\r\n                if (isIntegerType(sourceExpressionType) && isIntegerType(destinationType)) {\r\n                    \/\/ If source expression type is iexpr and destination type is some bounded integer type, attempt to narrow to destination type.\r\n                    if (sourceExpressionTypeDefinition->kind == DefinitionKind::BuiltinIntegerExpressionType) {\r\n                        if (const auto integerLiteral = sourceExpression->tryGet<Expression::IntegerLiteral>()) {\r\n                            if (const auto builtinIntegerType = destinationTypeDefinition->tryGet<Definition::BuiltinIntegerType>()) {            \r\n                                if (integerLiteral->value >= builtinIntegerType->min\r\n                                && integerLiteral->value <= builtinIntegerType->max) {\r\n                                    return makeFwdUnique<const Expression>(Expression::IntegerLiteral(integerLiteral->value), sourceExpression->location,\r\n                                        ExpressionInfo(EvaluationContext::CompileTime, destinationType->clone(), Qualifiers::None));\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        return nullptr;\r\n    }\r\n\r\n    bool Compiler::isTypeEquivalent(const TypeExpression* leftTypeExpression, const TypeExpression* rightTypeExpression) const {\r\n        if (leftTypeExpression == nullptr || rightTypeExpression == nullptr) {\r\n            return false;\r\n        }\r\n\r\n        if (rightTypeExpression->kind == TypeExpressionKind::DesignatedStorage) {\r\n            const auto leftSize = calculateStorageSize(getDesignatedStorageElementType(leftTypeExpression), \"\"_sv);\r\n            const auto rightSize = calculateStorageSize(getDesignatedStorageElementType(rightTypeExpression), \"\"_sv);\r\n\r\n            return leftSize.hasValue() && rightSize.hasValue() && *leftSize == *rightSize;\r\n        }\r\n\r\n        switch (leftTypeExpression->kind) {\r\n            case TypeExpressionKind::Array: {\r\n                const auto& leftArrayType = leftTypeExpression->array;\r\n                if (const auto rightArrayType = rightTypeExpression->tryGet<TypeExpression::Array>()) {\r\n\r\n                    if (leftArrayType.size && rightArrayType->size) {\r\n                        const auto leftSize = leftArrayType.size->integerLiteral.value;\r\n                        const auto rightSize = rightArrayType->size->integerLiteral.value;\r\n\r\n                        if (leftSize != rightSize) {\r\n                            return false;\r\n                        }\r\n                    }\r\n                    return isTypeEquivalent(leftArrayType.elementType.get(), rightArrayType->elementType.get());\r\n                }\r\n                return false;\r\n            }\r\n            case TypeExpressionKind::DesignatedStorage: {\r\n                const auto leftSize = calculateStorageSize(getDesignatedStorageElementType(leftTypeExpression), \"\"_sv);\r\n                const auto rightSize = calculateStorageSize(getDesignatedStorageElementType(rightTypeExpression), \"\"_sv);\r\n\r\n                return leftSize.hasValue() && rightSize.hasValue() && *leftSize == *rightSize;\r\n            }\r\n            case TypeExpressionKind::Function: {\r\n                const auto& leftFunctionType = leftTypeExpression->function;\r\n                if (const auto rightFunctionType = rightTypeExpression->tryGet<TypeExpression::Function>()) {\r\n                    const auto& leftParameters = leftFunctionType.parameters;\r\n                    const auto& rightParameters = rightFunctionType->parameters;\r\n\r\n                    if (!isTypeEquivalent(leftFunctionType.returnType.get(), rightFunctionType->returnType.get())) {\r\n                        return false;\r\n                    }\r\n                    if (leftParameters.size() != rightParameters.size()) {\r\n                        return false;\r\n                    }\r\n                    for (std::size_t i = 0; i != leftParameters.size(); ++i) {\r\n                        if (!isTypeEquivalent(leftParameters[i]->parameterType.get(), rightParameters[i]->parameterType.get())) {\r\n                            return false;\r\n                        }\r\n                    }\r\n                    return true;\r\n                }\r\n                return false;\r\n            }\r\n            case TypeExpressionKind::Identifier: std::abort(); return false;\r\n            case TypeExpressionKind::Pointer: {\r\n                const auto& leftPointerType = leftTypeExpression->pointer;\r\n                if (const auto rightPointerType = rightTypeExpression->tryGet<TypeExpression::Pointer>()) {\r\n                    return isTypeEquivalent(leftPointerType.elementType.get(), rightPointerType->elementType.get())\r\n                        && leftPointerType.qualifiers == rightPointerType->qualifiers;\r\n                }\r\n                return false;\r\n            }\r\n            case TypeExpressionKind::ResolvedIdentifier: {\r\n                const auto& leftResolvedIdentifierType = leftTypeExpression->resolvedIdentifier;\r\n                if (const auto rightResolvedIdentifierType = rightTypeExpression->tryGet<TypeExpression::ResolvedIdentifier>()) {\r\n                    return leftResolvedIdentifierType.definition == rightResolvedIdentifierType->definition;\r\n                }\r\n                return false;\r\n            }\r\n            case TypeExpressionKind::Tuple: {\r\n                const auto& leftTuple = leftTypeExpression->tuple;\r\n                if (const auto rightTuple = rightTypeExpression->tryGet<TypeExpression::Tuple>()) {\r\n                    const auto& leftElementTypes = leftTuple.elementTypes;\r\n                    const auto& rightElementTypes = rightTuple->elementTypes;\r\n\r\n                    if (leftElementTypes.size() != rightElementTypes.size()) {\r\n                        return false;\r\n                    }\r\n                    for (std::size_t i = 0; i != leftElementTypes.size(); ++i) {\r\n                        if (!isTypeEquivalent(leftElementTypes[i].get(), rightElementTypes[i].get())) {\r\n                            return false;\r\n                        }\r\n                    }\r\n                    return true;\r\n                }\r\n                return false;\r\n            }\r\n            case TypeExpressionKind::TypeOf:  return false;\r\n            default: std::abort(); return false;\r\n        }\r\n    }\r\n\r\n    std::string Compiler::getTypeName(const TypeExpression* typeExpression) const {\r\n        if (typeExpression == nullptr) {\r\n            return \"<unknown type>\";\r\n        }\r\n\r\n        switch (typeExpression->kind) {\r\n            case TypeExpressionKind::Array: {\r\n                const auto& arrayType = typeExpression->array;\r\n                std::string result = \"[\" + getTypeName(arrayType.elementType.get());\r\n                if (arrayType.size != nullptr) {\r\n                    result += \"; \";\r\n                    if (arrayType.size->kind == ExpressionKind::IntegerLiteral) {\r\n                        result += arrayType.size->integerLiteral.value.toString();\r\n                    } else {\r\n                        result += \"...\";\r\n                    }\r\n                }\r\n                return result + \"]\";\r\n            }\r\n            case TypeExpressionKind::DesignatedStorage: {\r\n                const auto& designatedStorageType = typeExpression->designatedStorage;\r\n\r\n\t\t\t\tstd::string result = getTypeName(designatedStorageType.elementType.get()) + \" in \";\r\n\t\t\t\tif (const auto& holder = designatedStorageType.holder) {\r\n\t\t\t\t\tif (const auto& resolvedIdentifier = holder->tryGet<Expression::ResolvedIdentifier>()) {\r\n\t\t\t\t\t\tresult += getResolvedIdentifierName(resolvedIdentifier->definition, resolvedIdentifier->pieces);\r\n\t\t\t\t\t\treturn result;\r\n\t\t\t\t\t} else if (const auto& identifier = holder->tryGet<Expression::Identifier>()) {\r\n\t\t\t\t\t\tconst auto& pieces = identifier->pieces;\r\n\t\t\t\t\t\tresult += text::join(pieces.begin(), pieces.end(), \".\");\r\n\t\t\t\t\t\treturn result;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tresult += \"<designated storage>\"; \r\n\t\t\t\treturn result;\r\n            }\r\n            case TypeExpressionKind::Function: {\r\n                const auto& functionType = typeExpression->function;\r\n                auto result = std::string(functionType.far ? \"far \" : \"\") + \"func\";\r\n                const auto& parameters = functionType.parameters;\r\n                if (parameters.size() > 0) {\r\n                    result += \"(\";\r\n                    for (std::size_t i = 0; i != parameters.size(); ++i) {\r\n                        result += (i != 0 ? \", \" : \"\") + getTypeName(parameters[i]->parameterType.get());\r\n                    }\r\n                    result += \")\";\r\n                }\r\n\r\n                const auto& returnType = functionType.returnType;\r\n                if (returnType->kind != TypeExpressionKind::Tuple\r\n                || returnType->tuple.elementTypes.size() != 0) {\r\n                    result += \" : \" + getTypeName(functionType.returnType.get());\r\n                }\r\n                return result;\r\n            }\r\n            case TypeExpressionKind::Identifier: {\r\n                const auto& identifierType = typeExpression->identifier;\r\n                const auto& pieces = identifierType.pieces;\r\n                return text::join(pieces.begin(), pieces.end(), \".\");\r\n            }\r\n            case TypeExpressionKind::Pointer: {\r\n                const auto& pointerType = typeExpression->pointer;\r\n                return \r\n                    std::string(((pointerType.qualifiers & Qualifiers::Far) != Qualifiers::None) ? \"far \" : \"\")\r\n                    + \"*\"\r\n                    + std::string(\r\n                        ((pointerType.qualifiers & Qualifiers::Const) != Qualifiers::None) ? \"const \"\r\n                        : ((pointerType.qualifiers & Qualifiers::WriteOnly) != Qualifiers::None) ? \"writeonly \"\r\n                        : \"\")\r\n                    + getTypeName(pointerType.elementType.get());\r\n            }\r\n            case TypeExpressionKind::ResolvedIdentifier: {\r\n                const auto& resolvedIdentifierType = typeExpression->resolvedIdentifier;\r\n                const auto& pieces = resolvedIdentifierType.pieces;\r\n                if (pieces.size() > 0) {\r\n                    return text::join(pieces.begin(), pieces.end(), \".\");\r\n                }\r\n                return resolvedIdentifierType.definition->name.toString();\r\n            }\r\n            case TypeExpressionKind::Tuple: {\r\n                const auto& tupleType = typeExpression->tuple;\r\n                std::string result = \"(\";\r\n                const auto& elementTypes = tupleType.elementTypes;\r\n                for (std::size_t i = 0; i != elementTypes.size(); ++i) {\r\n                    result += (i != 0 ? \", \" : \"\") + getTypeName(elementTypes[i].get());\r\n                }\r\n                result += \")\";\r\n                return result;\r\n            }\r\n            case TypeExpressionKind::TypeOf: return \"`typeof`\";\r\n            default: std::abort(); return \"\";\r\n        }\r\n    }\r\n\r\n    Optional<std::size_t> Compiler::calculateStorageSize(const TypeExpression* typeExpression, StringView description) const {\r\n        if (typeExpression == nullptr) {\r\n            return Optional<std::size_t>();\r\n        }\r\n\r\n        switch (typeExpression->kind) {\r\n            case TypeExpressionKind::Array: {\r\n                const auto& arrayType = typeExpression->array;\r\n                if (arrayType.size != nullptr) {\r\n                    const auto elementSize = calculateStorageSize(arrayType.elementType.get(), description);\r\n                    if (elementSize.hasValue()) {\r\n                        const auto arraySize = arrayType.size->integerLiteral.value;\r\n\r\n                        if (arraySize >= Int128(0) && arraySize <= Int128(SIZE_MAX)) {\r\n                            const auto checkedArraySize = static_cast<std::size_t>(arraySize);\r\n\r\n                            if (checkedArraySize == 0 || elementSize.get() * SIZE_MAX \/ checkedArraySize) {\r\n                                return Optional<std::size_t>(elementSize.get() * checkedArraySize);\r\n                            }\r\n                        }\r\n\r\n                        if (description.getLength() > 0) {\r\n                            report->error(\"array length of `\" + arraySize.toString() + \"` is too large to be used for \" + description.toString(), typeExpression->location);\r\n                        }\r\n                    }\r\n                } else {\r\n                    if (description.getLength() > 0) {\r\n                        report->error(\"could not resolve length for implicitly-sized array used for \" + description.toString(), typeExpression->location);\r\n                    }\r\n                }\r\n                return Optional<std::size_t>();\r\n            }\r\n            case TypeExpressionKind::DesignatedStorage: return Optional<std::size_t>();\r\n            case TypeExpressionKind::Function: {\r\n                const auto& functionType = typeExpression->function;\r\n                const auto pointerSizedType = functionType.far ? platform->getFarPointerSizedType() : platform->getPointerSizedType();\r\n                return Optional<std::size_t>(pointerSizedType->builtinIntegerType.size);\r\n            }\r\n            case TypeExpressionKind::Identifier: std::abort(); return Optional<std::size_t>();\r\n            case TypeExpressionKind::Pointer: {\r\n                const auto& pointerType = typeExpression->pointer;\r\n                const auto pointerSizedType = (pointerType.qualifiers & Qualifiers::Far) != Qualifiers::None ? platform->getFarPointerSizedType() : platform->getPointerSizedType();\r\n                return Optional<std::size_t>(pointerSizedType->builtinIntegerType.size);\r\n            }\r\n            case TypeExpressionKind::ResolvedIdentifier: {\r\n                const auto& resolvedIdentifierType = typeExpression->resolvedIdentifier;\r\n                const auto definition = resolvedIdentifierType.definition;\r\n                if (resolvedIdentifierType.definition->kind == DefinitionKind::BuiltinBoolType) {\r\n                    return Optional<std::size_t>(1);\r\n                } else if (const auto builtinIntegerType = resolvedIdentifierType.definition->tryGet<Definition::BuiltinIntegerType>()) {\r\n                    return Optional<std::size_t>(builtinIntegerType->size);\r\n                } else if (const auto enumType = resolvedIdentifierType.definition->tryGet<Definition::Enum>()) {\r\n                    if (enumType->resolvedUnderlyingType != nullptr) {\r\n                        return calculateStorageSize(enumType->resolvedUnderlyingType.get(), description);\r\n                    }\r\n                } else if (const auto structType = resolvedIdentifierType.definition->tryGet<Definition::Struct>()) {\r\n                    if (structType->size) {\r\n                        return Optional<std::size_t>(structType->size);\r\n                    }\r\n                }\r\n\r\n                if (description.getLength() > 0) {\r\n                    report->error(\"type `\" + definition->name.toString() + \"` has unknown storage size, so it cannot be used for \" + description.toString(), typeExpression->location);\r\n                }\r\n                return Optional<std::size_t>();\r\n            }\r\n            case TypeExpressionKind::Tuple: {\r\n                const auto& tupleType = typeExpression->tuple;\r\n                std::size_t result = 0;\r\n                const auto& elementTypes = tupleType.elementTypes;\r\n\r\n                for (std::size_t i = 0; i != elementTypes.size(); ++i) {\r\n                    auto elementSize = calculateStorageSize(elementTypes[i].get(), description);\r\n                    if (elementSize.hasValue()) {\r\n                        if (SIZE_MAX - result < elementSize.get()) {\r\n                            if (description.getLength() > 0) {\r\n                                report->error(\"tuple size is too large to be calculated for \" + description.toString(), typeExpression->location);\r\n                            }\r\n                            return Optional<std::size_t>();\r\n                        } else {\r\n                            result += elementSize.get();\r\n                        }\r\n                    } else {\r\n                        return Optional<std::size_t>();\r\n                    }\r\n                }\r\n\r\n                return Optional<std::size_t>(result);\r\n            }\r\n            case TypeExpressionKind::TypeOf: return Optional<std::size_t>();\r\n            default: std::abort(); return Optional<std::size_t>();\r\n        }\r\n    }\r\n\r\n    Optional<std::size_t> Compiler::resolveExplicitAddressExpression(const Expression* expression) {\r\n        if (expression != nullptr) {\r\n            if (const auto reducedAddressExpression = reduceExpression(expression)) {\r\n                if (const auto addressLiteral = reducedAddressExpression->tryGet<Expression::IntegerLiteral>()) {\r\n                    if (addressLiteral->value.isNegative()) {\r\n                        report->error(\"address must be a non-negative integer, but got `\" + addressLiteral->value.toString() + \"` instead\", reducedAddressExpression->location);\r\n                    } else {\r\n                        const auto maxPointerSizedType = platform->getFarPointerSizedType();\r\n                        const auto addressMax = Int128((1U << (8U * maxPointerSizedType->builtinIntegerType.size)) - 1);\r\n                        if (addressLiteral->value > addressMax) {\r\n                            report->error(\"address of `0x\" + addressLiteral->value.toString(16) + \"` is outside the valid address range `0` .. `0x\" + addressMax.toString(16) + \"` supported by this platform.\", reducedAddressExpression->location);\r\n                        } else {\r\n                            return static_cast<std::size_t>(addressLiteral->value);\r\n                        }\r\n                    }\r\n                } else {\r\n                    report->error(\"address must be a compile-time integer literal\", reducedAddressExpression->location);\r\n                }\r\n            }\r\n        }\r\n\r\n        return Optional<std::size_t>();\r\n    }\r\n\r\n    bool Compiler::serializeInteger(Int128 value, std::size_t size, std::vector<std::uint8_t>& result) const {\r\n        \/\/ TODO: handle big-endian\r\n        switch (size) {\r\n            case 1: {\r\n                result.push_back(static_cast<std::uint8_t>(value));\r\n                return true;                            \r\n            }\r\n            case 2: {\r\n                auto x = static_cast<std::uint16_t>(value);\r\n                result.push_back(x & 0xFF);\r\n                x >>= 8; result.push_back(x & 0xFF);\r\n                return true;                            \r\n            }\r\n            case 4: {\r\n                auto x = static_cast<std::uint32_t>(value);\r\n                result.push_back(x & 0xFF);\r\n                x >>= 8; result.push_back(x & 0xFF);\r\n                x >>= 8; result.push_back(x & 0xFF);\r\n                x >>= 8; result.push_back(x & 0xFF);\r\n                return true;\r\n            }\r\n            case 8: {\r\n                auto x = static_cast<std::uint64_t>(value);\r\n                result.push_back(x & 0xFF);\r\n                x >>= 8; result.push_back(x & 0xFF);\r\n                x >>= 8; result.push_back(x & 0xFF);\r\n                x >>= 8; result.push_back(x & 0xFF);\r\n                x >>= 8; result.push_back(x & 0xFF);\r\n                x >>= 8; result.push_back(x & 0xFF);\r\n                x >>= 8; result.push_back(x & 0xFF);\r\n                x >>= 8; result.push_back(x & 0xFF);\r\n                return true;                            \r\n            }\r\n            default: return false;\r\n        }\r\n    }\r\n\r\n\r\n    bool Compiler::serializeConstantInitializer(const Expression* expression, std::vector<std::uint8_t>& result) const {\r\n        \/\/ NOTE: this requires a fully-reduced literal value expression.\r\n        \/\/ All identifiers, operators, embeds, etc. must be substituted with a reduced literal values.\r\n        \/\/ Otherwise, it cannot be serialized.\r\n        switch (expression->kind) {\r\n            case ExpressionKind::ArrayComprehension: return false;\r\n            case ExpressionKind::ArrayPadLiteral: return false;\r\n            case ExpressionKind::ArrayLiteral: {\r\n                const auto& arrayLiteral = expression->arrayLiteral;\r\n                for (const auto& item : arrayLiteral.items) {\r\n                    if (!serializeConstantInitializer(item.get(), result)) {\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            case ExpressionKind::BinaryOperator: return false;\r\n            case ExpressionKind::BooleanLiteral: {\r\n                const auto& booleanLiteral = expression->booleanLiteral;\r\n                return serializeInteger(Int128(booleanLiteral.value ? 1 : 0), 1, result);\r\n            }\r\n            case ExpressionKind::Call: return false;\r\n            case ExpressionKind::Cast: return false;\r\n            case ExpressionKind::Embed: return false;\r\n            case ExpressionKind::FieldAccess: return false;\r\n            case ExpressionKind::Identifier: std::abort(); return false;\r\n            case ExpressionKind::IntegerLiteral: {\r\n                const auto& integerLiteral = expression->integerLiteral;\r\n                if (const auto storageSize = calculateStorageSize(expression->info->type.get(), \"integer literal\"_sv)) {\r\n                    return serializeInteger(integerLiteral.value, *storageSize, result);\r\n                }\r\n                return false;\r\n            }\r\n            case ExpressionKind::OffsetOf: std::abort(); return false;\r\n            case ExpressionKind::RangeLiteral: return false;\r\n            case ExpressionKind::ResolvedIdentifier: {\r\n                const auto& resolvedIdentifier = expression->resolvedIdentifier;\r\n                const auto definition = resolvedIdentifier.definition;\r\n\r\n                Optional<std::size_t> absolutePosition;\r\n                if (const auto funcDefinition = definition->tryGet<Definition::Func>()) {\r\n                    if (funcDefinition->inlined) {\r\n                        report->error(\"`inline func` has no address so it cannot be used as a constant initializer\", expression->location);\r\n                    } else {\r\n                        if (const auto address = funcDefinition->address.tryGet()) {\r\n                            absolutePosition = address->absolutePosition;\r\n                        }\r\n                    }\r\n                }\r\n\r\n                if (absolutePosition.hasValue()) {\r\n                    return serializeInteger(Int128(*absolutePosition), platform->getPointerSizedType()->builtinIntegerType.size, result);\r\n                }\r\n                return false;\r\n            }\r\n            case ExpressionKind::SideEffect: return false;\r\n            case ExpressionKind::StringLiteral: {\r\n                const auto& stringLiteral = expression->stringLiteral;\r\n                const auto data = stringLiteral.value.getData();\r\n                const auto len = stringLiteral.value.getLength();\r\n                for (std::size_t i = 0; i != len; ++i) {\r\n                    result.push_back(data[i]);\r\n                }\r\n                return true;\r\n            }\r\n            case ExpressionKind::StructLiteral: {\r\n                const auto& structLiteral = expression->structLiteral;\r\n                const auto definition = structLiteral.type->resolvedIdentifier.definition;\r\n                const auto& structDefinition = definition->struct_;                \r\n                const auto sizeBefore = result.size();\r\n\r\n\r\n                if (structDefinition.kind == StructKind::Union) {\r\n                    const auto& item = structLiteral.items.begin();\r\n                    if (!serializeConstantInitializer(item->second->value.get(), result)) {\r\n                        return false;\r\n                    }\r\n\r\n                    const auto sizeAfter = result.size();\r\n\r\n                    \/\/ Pad unions to the size of their largest element.\r\n                    if (structLiteral.items.size() > sizeAfter - sizeBefore) {\r\n                        const auto trailingPadding = structLiteral.items.size() - (sizeAfter - sizeBefore);\r\n\r\n                        for (std::size_t i = 0; i != trailingPadding; ++i) {\r\n                            result.push_back(0);\r\n                        }\r\n                    }\r\n                } else {\r\n                    for (const auto& member : structDefinition.members) {\r\n                        const auto& item = structLiteral.items.find(member->name);\r\n                        if (!serializeConstantInitializer(item->second->value.get(), result)) {\r\n                            return false;\r\n                        }\r\n                    }\r\n                    \/\/ TODO: alignment\/padding as required for structs.                    \r\n                }\r\n\r\n                return true;\r\n            }\r\n            case ExpressionKind::TupleLiteral: {\r\n                const auto& tupleLiteral = expression->tupleLiteral;\r\n                \/\/ TODO: alignment\/padding as required for tuples.\r\n                for (const auto& item : tupleLiteral.items) {\r\n                    if (!serializeConstantInitializer(item.get(), result)) {\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            case ExpressionKind::TypeOf: return false;\r\n            case ExpressionKind::TypeQuery: std::abort(); return false;\r\n            case ExpressionKind::UnaryOperator: return false;\r\n            default: std::abort(); return false;\r\n        }\r\n    }\r\n\r\n\r\n    std::pair<bool, Optional<std::size_t>> Compiler::handleInStatement(const std::vector<StringView>& bankIdentifierPieces, const Expression* dest, SourceLocation location) {\r\n        const auto resolveResult = resolveIdentifier(bankIdentifierPieces, location);\r\n        if (resolveResult.first == nullptr) {\r\n            return {false, Optional<std::size_t>()};\r\n        }\r\n        if (resolveResult.second < bankIdentifierPieces.size() - 1) {\r\n            raiseUnresolvedIdentifierError(bankIdentifierPieces, resolveResult.second, location);\r\n            return {false, Optional<std::size_t>()};\r\n        }\r\n\r\n        if (const auto definition = resolveResult.first) {\r\n            if (auto bankDefinition = definition->tryGet<Definition::Bank>()) {\r\n                currentBank = bankDefinition->bank;\r\n\r\n                if (dest != nullptr) {\r\n                    if (const auto reducedAddressExpression = reduceExpression(dest)) {\r\n                        if (const auto addressLiteral = reducedAddressExpression->tryGet<Expression::IntegerLiteral>()) {\r\n                            if (addressLiteral->value.isNegative()) {\r\n                                report->error(\"address must be a non-negative integer, but got `\" + addressLiteral->value.toString() + \"` instead\", reducedAddressExpression->location);\r\n                            } else {\r\n                                const auto oldPosition = currentBank->getAddress().absolutePosition;\r\n                                const auto maxPointerSizedType = platform->getFarPointerSizedType();\r\n                                const auto addressMax = Int128((1U << (8U * maxPointerSizedType->builtinIntegerType.size)) - 1);\r\n\r\n                                if (addressLiteral->value > addressMax) {\r\n                                    report->error(\"address of `0x\" + addressLiteral->value.toString(16) + \"` is outside the address range `0` .. `0x\" + addressMax.toString(16) + \"` supported by this platform.\", reducedAddressExpression->location);\r\n                                } else if (!oldPosition.hasValue() && addressLiteral->value + Int128(currentBank->getCapacity() - 1) > addressMax) {\r\n                                    report->error(\"bank start address of `0x\" + addressLiteral->value.toString(16) + \"` with size `\" + Int128(currentBank->getCapacity()).toString() + \"` will cause upper address `0x\" + (addressLiteral->value + Int128(currentBank->getCapacity() - 1)).toString(16) + \"` to be outside the valid address range `0` .. `0x\" + addressMax.toString(16) + \"` supported by this platform.\", reducedAddressExpression->location);\r\n                                } else {\r\n                                    currentBank->absoluteSeek(report, static_cast<std::size_t>(addressLiteral->value), reducedAddressExpression->location);\r\n                                    return {true, static_cast<std::size_t>(addressLiteral->value)};\r\n                                }\r\n                            }\r\n                        } else {\r\n                            report->error(\"address must be a compile-time integer literal\", reducedAddressExpression->location);\r\n                            return {false, Optional<std::size_t>()};\r\n                        }\r\n                    }\r\n                } else {\r\n                    return {true, Optional<std::size_t>()};\r\n                }\r\n            } else {\r\n                report->error(getResolvedIdentifierName(definition, bankIdentifierPieces) + \" is not a valid bank\", definition->name);\r\n                return {false, Optional<std::size_t>()};\r\n            }\r\n        }\r\n        return {false, Optional<std::size_t>()};\r\n    }\r\n\r\n    void Compiler::pushAttributeList(CompiledAttributeList* attributeList) {\r\n        modeFlagsStack.push_back(modeFlags);\r\n        attributeListStack.push_back(attributeList);\r\n\r\n        for (const auto& attribute : attributeList->attributes) {\r\n            attributeStack.push_back(attribute.get());\r\n\r\n            const auto attributeName = attribute->name;\r\n            const auto modeIndex = builtins.findModeAttributeByName(attributeName);\r\n            if (modeIndex != SIZE_MAX) {\r\n                const auto modeAttribute = builtins.getModeAttribute(modeIndex);\r\n\r\n                for (std::size_t otherModeIndex = 0, modeCount = builtins.getModeAttributeCount(); otherModeIndex != modeCount; ++otherModeIndex) {\r\n                    if ((modeFlags & (1U << otherModeIndex)) != 0) {\r\n                        const auto otherModeAttribute = builtins.getModeAttribute(otherModeIndex);\r\n                        if (otherModeAttribute->groupIndex == modeAttribute->groupIndex) {\r\n                            modeFlags &= ~(1U << otherModeIndex);\r\n                        }\r\n                    }\r\n                }\r\n\r\n                modeFlags |= (1U << modeIndex);\r\n            }\r\n        }\r\n    }\r\n\r\n    void Compiler::popAttributeList() {\r\n        modeFlags = modeFlagsStack.back();\r\n        modeFlagsStack.pop_back();\r\n\r\n        const auto attributeList = attributeListStack.back();\r\n        attributeListStack.pop_back();\r\n\r\n        for (std::size_t i = 0, size = attributeList->attributes.size(); i != size; ++i) {\r\n            attributeStack.pop_back();\r\n        }\r\n    }\r\n\r\n    bool Compiler::checkConditionalCompilationAttributes() {\r\n        for (const auto& attribute : attributeStack) {\r\n            if (attribute->name == \"compile_if\"_sv) {\r\n                if (attribute->arguments.size() == 1) {\r\n                    if (const auto booleanLiteral = attribute->arguments[0]->tryGet<Expression::BooleanLiteral>()) {\r\n                        if (booleanLiteral->value == false) {\r\n                            return false;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        return true;\r\n    }\r\n\r\n    bool Compiler::reserveDefinitions(const Statement* statement) {\r\n        switch (statement->kind) {\r\n            case StatementKind::Attribution: {\r\n                const auto& attributedStatement = statement->attribution;\r\n                const auto body = attributedStatement.body.get();\r\n\r\n                auto attributeList = attributeLists.addNew();\r\n                statementAttributeLists[statement] = attributeList;\r\n\r\n                for (const auto& attribute : attributedStatement.attributes) {\r\n                    std::vector<FwdUniquePtr<const Expression>> reducedArguments;\r\n\r\n                    bool foundAttribute = false;\r\n                    bool validAttributeName = false;\r\n                    std::size_t attributeRequiredArgumentCount = 0;\r\n\r\n                    const auto modeAttribute = builtins.findModeAttributeByName(attribute->name);\r\n                    const auto declarationAttribute = builtins.findDeclarationAttributeByName(attribute->name);\r\n\r\n                    if (modeAttribute != SIZE_MAX) {\r\n                        foundAttribute = true;\r\n                        validAttributeName = true;\r\n                        attributeRequiredArgumentCount = 0;\r\n                    } else if (declarationAttribute != Builtins::DeclarationAttribute::None) {\r\n                        foundAttribute = true;\r\n                        validAttributeName = builtins.isDeclarationAttributeValid(declarationAttribute, body);\r\n                        attributeRequiredArgumentCount = builtins.getDeclarationAttributeArgumentCount(declarationAttribute);\r\n                    } else {\r\n                        if (attribute->name == \"compile_if\"_sv) {\r\n                            foundAttribute = true;\r\n                            validAttributeName = true;\r\n                            attributeRequiredArgumentCount = 1;\r\n                        }\r\n                    }\r\n\r\n                    bool validAttributeArguments = true;\r\n\r\n                    if (foundAttribute && attribute->arguments.size() != attributeRequiredArgumentCount) {\r\n                        report->error(\"attribute `\" + attribute->name.toString()\r\n                            + \"` expects exactly \" + std::to_string(attributeRequiredArgumentCount)\r\n                            + \" argument\" + (attributeRequiredArgumentCount != 1 ? \"s\" : \"\")\r\n                            + \", but got \" + std::to_string(attribute->arguments.size())\r\n                            + \" argument\" + (attribute->arguments.size() != 1 ? \"s\" : \"\")\r\n                            + \" instead\", attribute->location);\r\n\r\n                        validAttributeArguments = false;\r\n                    }\r\n\r\n                    if (validAttributeArguments && attribute->arguments.size() > 0) {\r\n                        for (const auto& argument : attribute->arguments) {\r\n                            if (auto reducedArgument = reduceExpression(argument.get())) {\r\n                                reducedArguments.push_back(std::move(reducedArgument));\r\n                            } else {\r\n                                validAttributeArguments = false;\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    if (validAttributeName && validAttributeArguments) {\r\n                        if (attribute->name == \"compile_if\"_sv) {\r\n                            if (attribute->arguments.size() == 1) {\r\n                                if (reducedArguments[0]->kind != ExpressionKind::BooleanLiteral) {\r\n                                    report->error(\"attribute `\" + attribute->name.toString() + \"` requires a compile-time boolean conditional.\", attribute->location);\r\n                                }\r\n                            }\r\n                        }\r\n\r\n                        attributeList->attributes.addNew(body, attribute->name, std::move(reducedArguments), attribute->location);\r\n                    } else {\r\n                        if (foundAttribute) {\r\n                            if (!validAttributeName) {\r\n                                report->error(\"attribute `\" + attribute->name.toString() + \"` is not valid here.\", attribute->location);\r\n                            }\r\n                        } else {\r\n                            report->error(\"could not resolve attribute `\" + attribute->name.toString() + \"`\", attribute->location);\r\n                        }\r\n                    }\r\n                }\r\n\r\n                pushAttributeList(attributeList);\r\n                if (checkConditionalCompilationAttributes()) {\r\n                    reserveDefinitions(attributedStatement.body.get());\r\n                }\r\n                popAttributeList();\r\n                break;\r\n            }\r\n            case StatementKind::Bank: {\r\n                const auto& bankDeclaration = statement->bank;\r\n                const auto& names = bankDeclaration.names;\r\n                const auto& addresses = bankDeclaration.addresses;\r\n                const auto typeExpression = bankDeclaration.typeExpression.get();\r\n                for (std::size_t i = 0, size = names.size(); i != size; ++i) {\r\n                    definitionsToResolve.push_back(currentScope->createDefinition(report, Definition::Bank(addresses[i].get(), typeExpression), names[i], statement));\r\n                }\r\n                break;\r\n            }\r\n            case StatementKind::Block: {\r\n                const auto& blockStatement = statement->block;\r\n                enterScope(getOrCreateStatementScope(stringPool->intern(SymbolTable::generateBlockName()), statement, currentScope));\r\n                for (const auto& item : blockStatement.items) {\r\n                    reserveDefinitions(item.get());\r\n                }\r\n                exitScope();\r\n                break;\r\n            }\r\n            case StatementKind::Config: break;\r\n            case StatementKind::DoWhile: {\r\n                const auto& doWhileStatement = statement->doWhile;\r\n                reserveDefinitions(doWhileStatement.body.get());\r\n                break;\r\n            }\r\n            case StatementKind::Enum: {\r\n                const auto& enumDeclaration = statement->enum_;\r\n                const auto scope = getOrCreateStatementScope(StringView(), statement, currentScope);\r\n\r\n                auto definition = currentScope->createDefinition(report, Definition::Enum(enumDeclaration.underlyingTypeExpression.get(), scope), enumDeclaration.name, statement);\r\n\r\n                if (definition == nullptr) {\r\n                    break;\r\n                }\r\n\r\n                definitionsToResolve.push_back(definition);\r\n\r\n                auto& enumDefinition = definition->enum_;\r\n\r\n                enterScope(scope);\r\n\r\n                const Expression* previousExpression = nullptr;\r\n                std::size_t offset = 0;\r\n\r\n                for (const auto& item : enumDeclaration.items) {\r\n                    const Expression* expression = nullptr;\r\n\r\n                    if (const auto enumExpression = item->value.get()) {\r\n                        expression = enumExpression;\r\n                        previousExpression = enumExpression;\r\n                        offset = 0;\r\n                    } else {\r\n                        expression = previousExpression;\r\n                    }\r\n\r\n                    auto enumMemberDefinition = currentScope->createDefinition(report, Definition::EnumMember(expression, offset), item->name, statement);\r\n                    enumDefinition.members.push_back(enumMemberDefinition);\r\n                    ++offset;\r\n                }\r\n\r\n                exitScope();\r\n                break;\r\n            }\r\n            case StatementKind::ExpressionStatement: break;\r\n            case StatementKind::File: {\r\n                const auto& file = statement->file;\r\n                const auto outerScope = currentScope;\r\n                enterScope(getOrCreateStatementScope(StringView(), statement, builtins.getBuiltinScope()));\r\n                bindModuleScope(file.expandedPath, currentScope);\r\n                for (const auto& item : file.items) {\r\n                    reserveDefinitions(item.get());\r\n                }\r\n                if (outerScope != nullptr) {\r\n                    outerScope->addRecursiveImport(currentScope);\r\n                }\r\n                exitScope();\r\n                break;\r\n            }\r\n            case StatementKind::For: {\r\n                const auto& forStatement = statement->for_;\r\n                reserveDefinitions(forStatement.body.get());\r\n                break;\r\n            }\r\n            case StatementKind::Func: {\r\n                const auto& funcDeclaration = statement->func;\r\n                const auto oldFunction = currentFunction;\r\n                const auto onExit = makeScopeGuard([&]() {\r\n                    currentFunction = oldFunction;\r\n                });\r\n\r\n                bool fallthrough = false;\r\n                BranchKind returnKind = funcDeclaration.far ? BranchKind::FarReturn : BranchKind::Return;\r\n                for (const auto& attribute : attributeStack) {\r\n                    if (attribute->statement == statement) {\r\n                        const auto functionAttribute = builtins.findDeclarationAttributeByName(attribute->name);\r\n                        switch (functionAttribute) {\r\n                            case Builtins::DeclarationAttribute::Irq: returnKind = BranchKind::IrqReturn; break;\r\n                            case Builtins::DeclarationAttribute::Nmi: returnKind = BranchKind::NmiReturn; break;\r\n                            case Builtins::DeclarationAttribute::Fallthrough: fallthrough = true; break;\r\n                            case Builtins::DeclarationAttribute::None: break;\r\n                            default: std::abort(); break;\r\n                        }\r\n                    }\r\n                }\r\n\r\n                if (funcDeclaration.inlined) {\r\n                    if (returnKind != BranchKind::Return) {\r\n                        report->error(\"`inline func` cannot have an attribute that changes its return convention\", statement->location);    \r\n                    }\r\n\r\n                    returnKind = BranchKind::None;\r\n                }\r\n\r\n                auto body = funcDeclaration.body.get();\r\n                auto definition = currentScope->createDefinition(report, Definition::Func(fallthrough, funcDeclaration.inlined, funcDeclaration.far, returnKind, funcDeclaration.returnTypeExpression.get(), currentScope, body), funcDeclaration.name, statement);\r\n                definitionsToResolve.push_back(definition);\r\n\r\n                if (definition == nullptr) {\r\n                    break;\r\n                }\r\n\r\n                auto& funcDefinition = definition->func;\r\n\r\n                enterScope(getOrCreateStatementScope(stringPool->intern(SymbolTable::generateBlockName()), body, currentScope));\r\n                funcDefinition.environment = currentScope;\r\n                for (const auto& parameter : funcDeclaration.parameters) {\r\n                    auto parameterDefinition = currentScope->createDefinition(report, Definition::Var(Qualifiers::None, definition, nullptr, parameter->typeExpression.get(), 0), parameter->name, statement);\r\n                    parameterDefinition->var.isParameter = true;\r\n                    funcDefinition.parameters.push_back(parameterDefinition);\r\n                }\r\n                exitScope();\r\n\r\n                currentFunction = definition;\r\n                reserveDefinitions(body);\r\n                break;\r\n            }\r\n            case StatementKind::If: {\r\n                const auto& ifStatement = statement->if_;\r\n                reserveDefinitions(ifStatement.body.get());\r\n                if (ifStatement.alternative) {\r\n                    reserveDefinitions(ifStatement.alternative.get());\r\n                }\r\n                break;\r\n            }\r\n            case StatementKind::In: {\r\n                const auto& inStatement = statement->in;\r\n                bindStatementScope(inStatement.body.get(), currentScope);\r\n                reserveDefinitions(inStatement.body.get());\r\n                break;\r\n            }\r\n            case StatementKind::InlineFor: break;\r\n            case StatementKind::ImportReference: {\r\n                const auto& importReference = statement->importReference;\r\n                if (currentScope != nullptr) {                    \r\n                    if (const auto moduleScope = findModuleScope(importReference.expandedPath)) {\r\n                        currentScope->addRecursiveImport(moduleScope);\r\n                    } else {\r\n                        report->error(\"import reference appeared before a file node actually registered the module\", statement->location, ReportErrorFlags::InternalError);\r\n                    }\r\n                }\r\n                break;\r\n            }\r\n            case StatementKind::InternalDeclaration: break;\r\n            case StatementKind::Branch: break;\r\n            case StatementKind::Label: {\r\n                const auto& labelDeclaration = statement->label;\r\n                auto definition = currentScope->createDefinition(report, Definition::Func(true, false, labelDeclaration.far, BranchKind::None, builtins.getUnitTuple(), currentScope, nullptr), labelDeclaration.name, statement);\r\n\r\n                if (definition == nullptr) {\r\n                    break;\r\n                }\r\n\r\n                auto& func = definition->func;\r\n                func.resolvedSignatureType = makeFwdUnique<const TypeExpression>(TypeExpression::Function(labelDeclaration.far, {}, func.returnTypeExpression->clone()), func.returnTypeExpression->location);\r\n                break;\r\n            }\r\n            case StatementKind::Let: {\r\n                const auto& letDeclaration = statement->let;\r\n                currentScope->createDefinition(report, Definition::Let(letDeclaration.parameters, letDeclaration.value.get()), letDeclaration.name, statement);\r\n                break;\r\n            }\r\n            case StatementKind::Namespace: {\r\n                const auto& namespaceDeclaration = statement->namespace_;\r\n                SymbolTable* scope = nullptr;\r\n                if (const auto definition = currentScope->findLocalMemberDefinition(namespaceDeclaration.name)) {\r\n                    if (const auto ns = definition->tryGet<Definition::Namespace>()) {\r\n                        \/\/ Reuse scope if it already exists.\r\n                        scope = ns->environment;\r\n                    } else {\r\n                        \/\/ If another symbol with the same name exists, but it is not a namespace, trigger a duplicate key error.\r\n                        currentScope->createDefinition(report, Definition::Namespace(nullptr), namespaceDeclaration.name, statement);\r\n                        break;\r\n                    }\r\n                } else {\r\n                    scope = getOrCreateStatementScope(namespaceDeclaration.name, statement, currentScope);\r\n                    currentScope->createDefinition(report, Definition::Namespace(scope), namespaceDeclaration.name, statement);\r\n\r\n                    tempImportedDefinitions.clear();\r\n                    currentScope->findImportedMemberDefinitions(namespaceDeclaration.name, tempImportedDefinitions);\r\n                    for (const auto importedDefinition : tempImportedDefinitions) {\r\n                        if (const auto ns = importedDefinition->tryGet<Definition::Namespace>()) {\r\n                            scope->addRecursiveImport(ns->environment);\r\n                        }\r\n                    }\r\n                }\r\n\r\n                enterScope(scope);\r\n                bindStatementScope(namespaceDeclaration.body.get(), scope);\r\n                reserveDefinitions(namespaceDeclaration.body.get());\r\n                exitScope();\r\n                break;\r\n            }\r\n            case StatementKind::Struct: {\r\n                const auto& structDeclaration = statement->struct_;\r\n                const auto scope = getOrCreateStatementScope(StringView(), statement, currentScope);\r\n\r\n                auto definition = currentScope->createDefinition(report, Definition::Struct(structDeclaration.kind, scope), structDeclaration.name, statement);\r\n                definitionsToResolve.push_back(definition);\r\n\r\n                if (definition == nullptr) {\r\n                    break;\r\n                }\r\n\r\n                auto& structDefinition = definition->struct_;\r\n\r\n                enterScope(scope);\r\n\r\n                for (const auto& item : structDeclaration.items) {\r\n                    auto structMemberDefinition = currentScope->createDefinition(report, Definition::StructMember(item->typeExpression.get()), item->name, statement);\r\n                    structDefinition.members.push_back(structMemberDefinition);\r\n                }\r\n\r\n                exitScope();\r\n                break;\r\n            }\r\n            case StatementKind::TypeAlias: {\r\n                const auto& typeAliasDeclaration = statement->typeAlias;\r\n                definitionsToResolve.push_back(currentScope->createDefinition(report, Definition::TypeAlias(typeAliasDeclaration.typeExpression.get()), typeAliasDeclaration.name, statement));\r\n                break;\r\n            }\r\n            case StatementKind::Var: {\r\n                const auto& varDeclaration = statement->var;\r\n                const auto& names = varDeclaration.names;\r\n                const auto& addresses = varDeclaration.addresses;\r\n                const auto typeExpression = varDeclaration.typeExpression.get();\r\n\r\n                std::size_t alignment = 0;\r\n\r\n                for (const auto& attribute : attributeStack) {\r\n                    if (attribute->statement == statement) {\r\n                        const auto functionAttribute = builtins.findDeclarationAttributeByName(attribute->name);\r\n                        switch (functionAttribute) {\r\n                            case Builtins::DeclarationAttribute::Align: {\r\n                                if (const auto integerLiteral = attribute->arguments[0]->tryGet<Expression::IntegerLiteral>()) {\r\n                                    const auto& value = integerLiteral->value;\r\n                                    if (!value.isNegative() && value <= Int128(SIZE_MAX) && value.isPowerOfTwo()) {\r\n                                        alignment = static_cast<std::size_t>(value);\r\n                                    } else {\r\n                                        report->error(\"invalid value \" + value.toString() + \" provided to `align` attribute. must be a positive power-of-two, or zero.\", statement->location);\r\n                                    }\r\n                                }\r\n                                break;\r\n                            }\r\n                            case Builtins::DeclarationAttribute::None: break;\r\n                            default: std::abort(); break;\r\n                        }\r\n                    }\r\n                }\r\n\r\n                for (std::size_t i = 0, size = names.size(); i != size; ++i) {\r\n                    definitionsToResolve.push_back(currentScope->createDefinition(report, Definition::Var(varDeclaration.qualifiers, currentFunction, addresses[i].get(), typeExpression, alignment), names[i], statement));\r\n                }\r\n                break;\r\n            }\r\n            case StatementKind::While: {\r\n                const auto& whileStatement = statement->while_;\r\n                reserveDefinitions(whileStatement.body.get());\r\n                break;\r\n            }\r\n            default: std::abort(); return false;\r\n        }\r\n\r\n        return statement == program.get() ? report->validate() : report->alive();\r\n    }\r\n\r\n    bool Compiler::resolveDefinitionTypes() {\r\n        for (auto& definition : definitionsToResolve) {\r\n            if (auto enumDefinition = definition->tryGet<Definition::Enum>()) {\r\n                enterScope(definition->parentScope);\r\n\r\n                if (const auto underlyingTypeExpression = enumDefinition->underlyingTypeExpression) {\r\n                    auto resolvedUnderlyingTypeExpression = reduceTypeExpression(underlyingTypeExpression);\r\n\r\n                    if (resolvedUnderlyingTypeExpression != nullptr) {\r\n                        if (isIntegerType(resolvedUnderlyingTypeExpression.get())) {\r\n                            enumDefinition->resolvedUnderlyingType = std::move(resolvedUnderlyingTypeExpression);\r\n                        } else {\r\n                            report->error(\"underlying type for `enum` must be an integer type, not `\" + getTypeName(resolvedUnderlyingTypeExpression.get()) + \"`\", resolvedUnderlyingTypeExpression->location);\r\n                        }\r\n                    }\r\n                }\r\n\r\n                Int128 previousValue;\r\n                const Expression* previousExpression = nullptr;                \r\n                FwdUniquePtr<const TypeExpression> enumTypeExpression = makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(definition, {definition->name}), definition->declaration->location);\r\n\r\n                enterScope(enumDefinition->environment);\r\n                for (auto member : enumDefinition->members) {\r\n                    auto& enumMemberDefinition = member->enumMember;\r\n\r\n                    if (enumMemberDefinition.expression == previousExpression) {\r\n                        enumMemberDefinition.reducedExpression = makeFwdUnique<const Expression>(\r\n                            Expression::IntegerLiteral(previousValue + Int128(enumMemberDefinition.offset)),\r\n                            previousExpression != nullptr ? previousExpression->location : enumTypeExpression->location,\r\n                            ExpressionInfo(EvaluationContext::CompileTime, enumTypeExpression->clone(), Qualifiers::None));\r\n                    } else {\r\n                        if (auto reducedExpression = reduceExpression(enumMemberDefinition.expression)) {\r\n                            previousExpression = enumMemberDefinition.expression;\r\n\r\n                            if (const auto lit = reducedExpression->tryGet<Expression::IntegerLiteral>()) {\r\n                                previousValue = lit->value;\r\n\r\n                                enumMemberDefinition.reducedExpression = makeFwdUnique<const Expression>(\r\n                                    Expression::IntegerLiteral(previousValue + Int128(enumMemberDefinition.offset)),\r\n                                    reducedExpression->location,\r\n                                    ExpressionInfo(EvaluationContext::CompileTime, enumTypeExpression->clone(), Qualifiers::None));\r\n                            } else {\r\n                                report->error(\"`enum` value must be a compile-time integer literal\", enumMemberDefinition.expression->location);\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n                exitScope();\r\n                exitScope();\r\n            } else if (auto structDefinition = definition->tryGet<Definition::Struct>()) {\r\n                const auto description = structDefinition->kind == StructKind::Struct ? \"`struct` member\"_sv : \"`union` member\"_sv;\r\n\r\n                enterScope(definition->parentScope);\r\n                enterScope(structDefinition->environment);\r\n\r\n                std::size_t offset = 0;\r\n                std::size_t totalSize = 0;\r\n                for (auto member : structDefinition->members) {\r\n                    auto& structMemberDefinition = member->structMember;\r\n                    structMemberDefinition.offset = offset;\r\n\r\n                    if (auto resolvedType = reduceTypeExpression(structMemberDefinition.typeExpression)) {\r\n\r\n                        if (const auto resolvedSize = calculateStorageSize(resolvedType.get(), description)) {\r\n                            if (structDefinition->kind == StructKind::Struct) {\r\n                                offset += *resolvedSize;\r\n                                totalSize += *resolvedSize;\r\n                            } else {\r\n                                totalSize = std::max(totalSize, *resolvedSize);\r\n                            }\r\n                        }\r\n                        structMemberDefinition.resolvedType = std::move(resolvedType);\r\n                    }\r\n                }\r\n                structDefinition->size = totalSize;\r\n\r\n                exitScope();\r\n                exitScope();\r\n            } else if (auto typeAliasDefinition = definition->tryGet<Definition::TypeAlias>()) {\r\n                enterScope(definition->parentScope);\r\n                typeAliasDefinition->resolvedType = reduceTypeExpression(typeAliasDefinition->typeExpression);\r\n                exitScope();\r\n            }\r\n        }\r\n\r\n        for (auto& definition : definitionsToResolve) {\r\n            if (auto varDefinition = definition->tryGet<Definition::Var>()) {\r\n                enterScope(definition->parentScope);\r\n                if (const auto typeExpression = varDefinition->typeExpression) {\r\n                    varDefinition->reducedTypeExpression = reduceTypeExpression(typeExpression);\r\n                    varDefinition->resolvedType = varDefinition->reducedTypeExpression.get();\r\n                }\r\n                exitScope();\r\n            } else if (auto funcDefinition = definition->tryGet<Definition::Func>()) {\r\n                enterScope(definition->parentScope);\r\n\r\n                bool valid = true;\r\n\r\n                auto returnType = reduceTypeExpression(funcDefinition->returnTypeExpression);\r\n\r\n                if (!returnType) {\r\n                    valid = false;\r\n                }\r\n\r\n                std::vector<UniquePtr<const TypeExpression::Function::Parameter>> parameters;\r\n                parameters.reserve(funcDefinition->parameters.size());\r\n\r\n                for (const auto& parameter : funcDefinition->parameters) {\r\n                    auto& parameterDefinition = parameter->var;\r\n                    if (auto parameterType = reduceTypeExpression(parameterDefinition.typeExpression)) {\r\n                        parameterDefinition.reducedTypeExpression = parameterType->clone();\r\n                        parameterDefinition.resolvedType = parameterDefinition.reducedTypeExpression.get();\r\n                        parameters.push_back(makeUnique<const TypeExpression::Function::Parameter>(parameter->name, std::move(parameterType)));\r\n                    } else {\r\n                        valid = false;\r\n                    }\r\n                }\r\n\r\n                if (valid) {\r\n                    funcDefinition->resolvedSignatureType = makeFwdUnique<const TypeExpression>(TypeExpression::Function(funcDefinition->far, std::move(parameters), std::move(returnType)), definition->declaration->location);\r\n                }\r\n                exitScope();\r\n            } else if (auto bankDefinition = definition->tryGet<Definition::Bank>()) {\r\n                enterScope(definition->parentScope);\r\n                bankDefinition->resolvedType = reduceTypeExpression(bankDefinition->typeExpression);\r\n\r\n                const auto origin = resolveExplicitAddressExpression(bankDefinition->addressExpression);\r\n\r\n                if (const auto resolvedType = bankDefinition->resolvedType.get()) {\r\n                    bool validBankType = false;\r\n\r\n                    if (const auto arrayType = resolvedType->tryGet<TypeExpression::Array>()) {\r\n                        if (const auto elementType = arrayType->elementType->tryGet<TypeExpression::ResolvedIdentifier>()) {\r\n                            if (const auto bankType = elementType->definition->tryGet<Definition::BuiltinBankType>()) {\r\n                                if (arrayType->size) {\r\n                                    if (auto reducedSizeExpression = reduceExpression(arrayType->size.get())) {\r\n                                        if (const auto sizeLiteral = reducedSizeExpression->tryGet<Expression::IntegerLiteral>()) {\r\n                                            validBankType = true;\r\n                                            if (!sizeLiteral->value.isPositive()) {\r\n                                                report->error(\"bank size must be greater than zero, but got `\" + sizeLiteral->value.toString() + \"` instead\", reducedSizeExpression->location);\r\n                                            } else {\r\n                                                const auto maxPointerSizedType = platform->getFarPointerSizedType();\r\n                                                const auto addressEnd = Int128(1U << (8U * maxPointerSizedType->builtinIntegerType.size));\r\n\r\n                                                if (sizeLiteral->value > addressEnd) {\r\n                                                    report->error(\"bank size of `\" + sizeLiteral->value.toString() + \"` will cause an upper address outside the valid address range `0` .. `0x\" + (addressEnd - Int128::one()).toString(16) + \"` supported by this platform.\", reducedSizeExpression->location);\r\n                                                } else if (origin.hasValue() && Int128(origin.get()) + sizeLiteral->value > addressEnd) {\r\n                                                    report->error(\"bank size of `\" + sizeLiteral->value.toString() + \"` will cause upper address `0x\" + (Int128(origin.get() - 1) + sizeLiteral->value).toString(16) + \"` to be outside the valid address range `0` .. `0x\" + (addressEnd - Int128::one()).toString(16) + \"` supported by this platform.\", reducedSizeExpression->location);\r\n                                                } else {\r\n                                                    bankDefinition->bank = registeredBanks.addNew(\r\n                                                        definition->name,\r\n                                                        bankType->kind,\r\n                                                        origin,\r\n                                                        static_cast<std::size_t>(sizeLiteral->value),\r\n                                                        Bank::DefaultPadValue);\r\n                                                }\r\n                                            }\r\n                                        } else {\r\n                                            report->error(\"invalid size expression in bank type\", resolvedType->location);\r\n                                        }\r\n                                    }\r\n                                } else {\r\n                                    validBankType = true;\r\n                                    report->error(\"bank type `\" + getTypeName(resolvedType) + \"` must have a known size\", resolvedType->location);\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    if (!validBankType) {\r\n                        report->error(\"invalid bank type `\" + getTypeName(resolvedType) + \"`\", resolvedType->location);\r\n                    }\r\n                }\r\n\r\n                exitScope();\r\n            }\r\n        }\r\n\r\n        if (!report->validate()) {\r\n            return false;\r\n        }\r\n\r\n        definitionsToResolve.clear();\r\n        return true;\r\n    }\r\n\r\n    bool Compiler::reserveStorage(const Statement* statement) {\r\n        switch (statement->kind) {\r\n            case StatementKind::Attribution: {\r\n                const auto& attributedStatement = statement->attribution;\r\n                pushAttributeList(statementAttributeLists[statement]);\r\n                if (checkConditionalCompilationAttributes()) {\r\n                    reserveStorage(attributedStatement.body.get());\r\n                }\r\n                popAttributeList();\r\n                break;\r\n            }\r\n            case StatementKind::Bank: break;\r\n            case StatementKind::Block: {\r\n                const auto& blockStatement = statement->block;\r\n                enterScope(getOrCreateStatementScope(StringView(), statement, currentScope));\r\n                for (const auto& item : blockStatement.items) {\r\n                    reserveStorage(item.get());\r\n                }\r\n                exitScope();\r\n                break;\r\n            }\r\n            case StatementKind::Config: break;\r\n            case StatementKind::DoWhile: {\r\n                const auto& doWhileStatement = statement->doWhile;\r\n                reserveStorage(doWhileStatement.body.get());\r\n                break;\r\n            }\r\n            case StatementKind::Enum: break;\r\n            case StatementKind::ExpressionStatement: break;\r\n            case StatementKind::File: {\r\n                const auto& file = statement->file;\r\n                enterScope(findStatementScope(statement));\r\n                for (const auto& item : file.items) {\r\n                    reserveStorage(item.get());\r\n                }\r\n                exitScope();\r\n                break;\r\n            }\r\n            case StatementKind::For: {\r\n                const auto& forStatement = statement->for_;\r\n                reserveStorage(forStatement.body.get());\r\n                break;\r\n            }\r\n            case StatementKind::Func: {\r\n                const auto& funcDeclaration = statement->func;\r\n\r\n                auto definition = currentScope->findLocalMemberDefinition(funcDeclaration.name);\r\n                auto& funcDefinition = definition->func;    \r\n                \r\n                const auto oldFunction = currentFunction;\r\n                const auto onExit = makeScopeGuard([&]() {\r\n                    currentFunction = oldFunction;\r\n                });\r\n\r\n                for (auto& parameter : funcDefinition.parameters) {\r\n                    auto& parameterVarDefinition = parameter->var;\r\n\r\n                    if (parameterVarDefinition.enclosingFunction != nullptr) {\r\n                        if (parameterVarDefinition.typeExpression->kind != TypeExpressionKind::DesignatedStorage) {\r\n                            report->error(\"function parameter `\" + parameter->name.toString() + \"` must have a designated storage type\", statement->location);\r\n                            break;\r\n                        }\r\n                    }\r\n                }\r\n\r\n                currentFunction = definition;\r\n                reserveStorage(funcDeclaration.body.get());\r\n                break;\r\n            }\r\n            case StatementKind::If: {\r\n                const auto& ifStatement = statement->if_;\r\n                reserveStorage(ifStatement.body.get());\r\n                if (ifStatement.alternative) {\r\n                    reserveStorage(ifStatement.alternative.get());\r\n                }\r\n                break;\r\n            }\r\n            case StatementKind::In: {\r\n                const auto& inStatement = statement->in;\r\n                bankStack.push_back(currentBank);\r\n\r\n                const auto result = handleInStatement(inStatement.pieces, inStatement.dest.get(), statement->location);\r\n                if (result.first) {\r\n                    reserveStorage(inStatement.body.get());\r\n                }\r\n\r\n                currentBank = bankStack.back();\r\n                bankStack.pop_back();\r\n                break;\r\n            }\r\n            case StatementKind::InlineFor: break;\r\n            case StatementKind::ImportReference: break;\r\n            case StatementKind::InternalDeclaration: break;\r\n            case StatementKind::Branch: break;\r\n            case StatementKind::Label: break;\r\n            case StatementKind::Let: break;\r\n            case StatementKind::Namespace: {\r\n                const auto& namespaceDeclaration = statement->namespace_;\r\n                enterScope(findStatementScope(namespaceDeclaration.body.get()));\r\n                reserveStorage(namespaceDeclaration.body.get());\r\n                exitScope();\r\n                break;\r\n            }\r\n            case StatementKind::Struct: break;\r\n            case StatementKind::TypeAlias: break;\r\n            case StatementKind::Var: {\r\n                const auto& varDeclaration = statement->var;\r\n                const auto& names = varDeclaration.names;\r\n                const auto description = statement->getDescription();\r\n                const auto location = statement->location;\r\n\r\n                if (varDeclaration.value != nullptr) {\r\n                    if (names.size() != 1) {\r\n                        report->error(description.toString() + \" with initializer must contain exactly one declaration.\", location);\r\n                        break;\r\n                    }\r\n\r\n                    if (!resolveVariableInitializer(currentScope->findLocalMemberDefinition(varDeclaration.names[0]), varDeclaration.value.get(), description, location)) {\r\n                        break;\r\n                    }\r\n                }\r\n\r\n                for (std::size_t i = 0, size = names.size(); i != size; ++i) {\r\n                    if (!reserveVariableStorage(currentScope->findLocalMemberDefinition(names[i]), description, location)) {\r\n                        break;\r\n                    }\r\n                }\r\n\r\n                break;\r\n            }\r\n            case StatementKind::While: {\r\n                const auto& whileStatement = statement->while_;\r\n                reserveStorage(whileStatement.body.get());\r\n                break;\r\n            }\r\n            default: std::abort(); return false;\r\n        }\r\n\r\n        return statement == program.get() ? report->validate() : report->alive();\r\n    }\r\n\r\n    bool Compiler::resolveVariableInitializer(Definition* definition, const Expression* initializer, StringView description, SourceLocation location) {\r\n        auto& varDefinition = definition->var;\r\n\r\n        if (currentBank == nullptr || !isBankKindStored(currentBank->getKind())) {\r\n            report->error(description.toString() + \" with initializer \" + (currentBank == nullptr ? \"must be inside an `in` statement\" : \"is not allowed in bank `\" + currentBank->getName().toString() + \"`\"), location);\r\n            return false;\r\n        }\r\n\r\n        allowReservedConstants = true;\r\n\r\n        if (auto reducedValue = reduceExpression(initializer)) {\r\n            if (const auto declarationType = varDefinition.reducedTypeExpression.get()) {\r\n                if (const auto compatibleInitializerType = findCompatibleAssignmentType(reducedValue.get(), declarationType)) {\r\n                    varDefinition.initializerExpression = createConvertedExpression(reducedValue.get(), compatibleInitializerType);\r\n                } else {\r\n                    report->error(description.toString() + \" of type `\" + getTypeName(varDefinition.reducedTypeExpression.get()) + \"` cannot be initialized with `\" + getTypeName(reducedValue->info->type.get()) + \"` expression\", location);\r\n                    return false;\r\n                }\r\n            } else {\r\n                varDefinition.initializerExpression = std::move(reducedValue);\r\n            }\r\n\r\n            if (varDefinition.initializerExpression != nullptr) {\r\n                if (const auto arrayType = varDefinition.initializerExpression->info->type->tryGet<TypeExpression::Array>()) {\r\n                    if (arrayType->elementType == nullptr) {\r\n                        report->error(\"array has unknown element type\", location);\r\n                        return false;\r\n                    }\r\n                }\r\n            }\r\n\r\n            if (varDefinition.reducedTypeExpression != nullptr && varDefinition.reducedTypeExpression->kind == TypeExpressionKind::DesignatedStorage) {\r\n                varDefinition.resolvedType = varDefinition.reducedTypeExpression.get();\r\n            } else {\r\n                varDefinition.resolvedType = varDefinition.initializerExpression->info->type.get();\r\n            }\r\n        }\r\n\r\n        allowReservedConstants = false;\r\n        varDefinition.nestedConstants.insert(varDefinition.nestedConstants.end(), reservedConstants.begin(), reservedConstants.end());\r\n        reservedConstants.clear();\r\n\r\n        return true;\r\n    }\r\n\r\n    bool Compiler::reserveVariableStorage(Definition* definition, StringView description, SourceLocation location) {\r\n        auto& varDefinition = definition->var;\r\n        const auto name = definition->name;\r\n\r\n        if (!varDefinition.resolvedType) {\r\n            report->error(\"could not resolve declaration type\", location);\r\n            return false;\r\n        }\r\n\r\n        if (varDefinition.resolvedType->kind == TypeExpressionKind::DesignatedStorage) {\r\n            if ((varDefinition.qualifiers & (Qualifiers::Extern | Qualifiers::Const | Qualifiers::WriteOnly)) != Qualifiers::None) {\r\n                report->error(((varDefinition.qualifiers & Qualifiers::Extern) != Qualifiers::None ? \"extern \" : \"\") + description.toString() + \" of `\" + name.toString() + \"` cannot have designated storage type\", location);\r\n            }\r\n        } else {\r\n            const auto storageSize = calculateStorageSize(varDefinition.resolvedType, description);\r\n            if (!storageSize.hasValue()) {\r\n                return false;\r\n            }\r\n\r\n            varDefinition.storageSize = storageSize;\r\n\r\n            if (varDefinition.addressExpression != nullptr) {\r\n                if ((varDefinition.qualifiers & Qualifiers::Extern) != Qualifiers::None || varDefinition.enclosingFunction != nullptr || currentBank == nullptr || !isBankKindStored(currentBank->getKind())) {\r\n                    \/\/ Variable definitions with explicit addresses can be placed at any absolute address.\r\n                    \/\/ (They don't have relative addresses because of the explcit address can be outside of the current bank.)\r\n                    varDefinition.address = Address(Optional<std::size_t>(), resolveExplicitAddressExpression(varDefinition.addressExpression), nullptr);\r\n                }\r\n            } else {\r\n                if ((varDefinition.qualifiers & Qualifiers::Extern) != Qualifiers::None) {\r\n                    report->error(\"extern \" + description.toString() + \" of `\" + name.toString() + \"` must have an explicit address\", location);\r\n                } else if (varDefinition.enclosingFunction == nullptr) {\r\n                    if (currentBank == nullptr) {\r\n                        report->error(description.toString() + \" of `\" + name.toString() + \"` must be inside an `in` statement, have an explicit address `@`, or have a designated storage type\", location);\r\n                        return false;\r\n                    }\r\n\r\n                    if (!isBankKindStored(currentBank->getKind())) {\r\n                        \/\/ FIXME: natural alignment requirements\r\n                        const auto alignment = varDefinition.alignment != 0 ? varDefinition.alignment : 1;\r\n                        if (alignment > 1) {\r\n                            const auto unalignedAddress = currentBank->getAddress().absolutePosition.get();\r\n                            currentBank->absoluteSeek(report, (unalignedAddress + alignment - 1) \/ alignment * alignment, location);\r\n                        }\r\n\r\n                        varDefinition.address = currentBank->getAddress();\r\n\r\n                        if (!currentBank->reserveRam(report, description, definition->declaration, location, storageSize.get())) {\r\n                            return false;\r\n                        }\r\n                    }\r\n                } else {\r\n                    report->error(\"local \" + description.toString() + \" of `\" + name.toString() + \"` must have an explicit address, or have a designated storage type\", location);\r\n                    return false;\r\n                }\r\n            }\r\n        }\r\n\r\n        for (auto& nestedConstant : varDefinition.nestedConstants) {\r\n            reserveVariableStorage(nestedConstant, \"nested constant\"_sv, nestedConstant->declaration->location);\r\n        }\r\n\r\n        return true;\r\n    }\r\n\r\n    FwdUniquePtr<InstructionOperand> Compiler::createPlaceholderFromResolvedTypeDefinition(const Definition* resolvedTypeDefinition) const {\r\n        if (const auto builtinIntegerType = resolvedTypeDefinition->tryGet<Definition::BuiltinIntegerType>()) {\r\n            const auto placeholder = platform->getPlaceholderValue();\r\n            const auto mask = Int128((1U << (8U * builtinIntegerType->size)) - 1);\r\n            return makeFwdUnique<InstructionOperand>(InstructionOperand::Integer(placeholder & mask, true));\r\n        } else if (resolvedTypeDefinition->kind == DefinitionKind::BuiltinBoolType) {\r\n            return makeFwdUnique<InstructionOperand>(InstructionOperand::Boolean(false, true));\r\n        } \r\n        return nullptr;\r\n    }\r\n\r\n    FwdUniquePtr<InstructionOperand> Compiler::createPlaceholderFromTypeExpression(const TypeExpression* typeExpression) const {\r\n        if (const auto resolvedTypeDefinition = tryGetResolvedIdentifierTypeDefinition(typeExpression)) {\r\n            return createPlaceholderFromResolvedTypeDefinition(resolvedTypeDefinition);\r\n        } else if (isPointerLikeType(typeExpression)) {\r\n            return createPlaceholderFromResolvedTypeDefinition(isFarType(typeExpression) ? platform->getFarPointerSizedType() : platform->getPointerSizedType());\r\n        }\r\n        return nullptr;\r\n    }\r\n\r\n    FwdUniquePtr<InstructionOperand> Compiler::createOperandFromResolvedIdentifier(const Expression* expression, const Definition* definition) const {\r\n        const auto far = (expression->info->qualifiers & Qualifiers::Far) != Qualifiers::None;\r\n        const auto pointerSizedType = far ? platform->getFarPointerSizedType() : platform->getPointerSizedType();\r\n        bool isAddressableOperand = false;\r\n        bool isFunctionLiteral = false;\r\n        Optional<std::size_t> absolutePosition;\r\n\r\n        if (const auto varDefinition = definition->tryGet<Definition::Var>()) {\r\n            isAddressableOperand = true;\r\n            if (const auto address = varDefinition->address.tryGet()) {\r\n                absolutePosition = address->absolutePosition;\r\n            }\r\n        } else if (const auto funcDefinition = definition->tryGet<Definition::Func>()) {\r\n            if (funcDefinition->inlined) {\r\n                return nullptr;\r\n            }\r\n\r\n            isAddressableOperand = true;\r\n            isFunctionLiteral = true;\r\n\r\n            if (const auto address = funcDefinition->address.tryGet()) {\r\n                absolutePosition = address->absolutePosition;\r\n            }\r\n        }\r\n\r\n        if (isAddressableOperand) {\r\n            FwdUniquePtr<InstructionOperand> operand;\r\n            if (absolutePosition.hasValue()) {\r\n                const auto mask = Int128((1U << (8U * pointerSizedType->builtinIntegerType.size)) - 1);\r\n                operand = makeFwdUnique<InstructionOperand>(InstructionOperand::Integer(Int128(*absolutePosition) & mask));\r\n            } else {\r\n                operand = createPlaceholderFromResolvedTypeDefinition(pointerSizedType);\r\n            }\r\n\r\n            const auto expressionType = expression->info->type.get();\r\n\r\n            if (expressionType->kind != TypeExpressionKind::Array\r\n            && (!isFunctionLiteral || expressionType->kind != TypeExpressionKind::Function)) {\r\n                if (const auto indirectionSize = calculateStorageSize(expressionType, \"operand\"_sv)) {\r\n                    return makeFwdUnique<InstructionOperand>(InstructionOperand::Dereference(far, std::move(operand), *indirectionSize));\r\n                }\r\n                return nullptr;\r\n            } else {\r\n                return operand;\r\n            }\r\n        }\r\n\r\n        if (definition->kind == DefinitionKind::BuiltinRegister) {\r\n            return makeFwdUnique<InstructionOperand>(InstructionOperand::Register(definition));\r\n        }\r\n\r\n        return nullptr;\r\n    }\r\n\r\n    FwdUniquePtr<InstructionOperand> Compiler::createOperandFromLinkTimeExpression(const Expression* expression, bool quiet) const {\r\n        static_cast<void>(quiet);\r\n        if (const auto integerLiteral = expression->tryGet<Expression::IntegerLiteral>()) {\r\n            return makeFwdUnique<InstructionOperand>(InstructionOperand::Integer(integerLiteral->value));\r\n        } else if (const auto booleanLiteral = expression->tryGet<Expression::BooleanLiteral>()) {\r\n            return makeFwdUnique<InstructionOperand>(InstructionOperand::Boolean(booleanLiteral->value));\r\n        } else if (const auto resolvedIdentifier = expression->tryGet<Expression::ResolvedIdentifier>()) {\r\n            return createOperandFromResolvedIdentifier(expression, resolvedIdentifier->definition);\r\n        }\r\n\r\n        return createPlaceholderFromTypeExpression(expression->info->type.get());\r\n    }\r\n\r\n    FwdUniquePtr<InstructionOperand> Compiler::createOperandFromRunTimeExpression(const Expression* expression, bool quiet) const {\r\n        switch (expression->kind){\r\n            case ExpressionKind::ArrayComprehension: return nullptr;\r\n            case ExpressionKind::ArrayPadLiteral: return nullptr;\r\n            case ExpressionKind::BinaryOperator: {\r\n                const auto& binaryOperator = expression->binaryOperator;\r\n                if (binaryOperator.op == BinaryOperatorKind::Indexing\r\n                || binaryOperator.op == BinaryOperatorKind::UnalignedIndexing) {\r\n                    const auto indexLiteral = binaryOperator.right->tryGet<Expression::IntegerLiteral>();\r\n\r\n                    if (binaryOperator.left->info->context == EvaluationContext::LinkTime && indexLiteral != nullptr) {\r\n                        if (const auto indirectionSize = calculateStorageSize(expression->info->type.get(), \"operand\"_sv)) {\r\n                            const auto far = (binaryOperator.left->info->qualifiers & Qualifiers::Far) != Qualifiers::None;\r\n\r\n                            return makeFwdUnique<InstructionOperand>(InstructionOperand::Dereference(\r\n                                far,\r\n                                createPlaceholderFromResolvedTypeDefinition(far ? platform->getFarPointerSizedType() : platform->getPointerSizedType()),\r\n                                *indirectionSize));\r\n                        }\r\n                        return nullptr;\r\n                    }\r\n                    if (const auto indirectionSize = calculateStorageSize(expression->info->type.get(), \"operand\"_sv)) {\r\n                        if (auto operand = createOperandFromExpression(binaryOperator.left.get(), quiet)) {\r\n                            if (auto subscript = createOperandFromExpression(binaryOperator.right.get(), quiet)) {\r\n                                const auto far = (binaryOperator.left->info->qualifiers & Qualifiers::Far) != Qualifiers::None;\r\n\r\n                                if (operand->kind == InstructionOperandKind::Integer && subscript->kind == InstructionOperandKind::Integer) {\r\n                                    auto reducedOperand = makeFwdUnique<InstructionOperand>(InstructionOperand::Integer(operand->integer.value\r\n                                        + Int128(binaryOperator.op == BinaryOperatorKind::UnalignedIndexing ? 1 : *indirectionSize) * subscript->integer.value));\r\n                                    return makeFwdUnique<InstructionOperand>(InstructionOperand::Dereference(\r\n                                        far,\r\n                                        std::move(reducedOperand),\r\n                                        *indirectionSize));                                    \r\n                                }\r\n\r\n                                return makeFwdUnique<InstructionOperand>(InstructionOperand::Index(\r\n                                    far,\r\n                                    std::move(operand),\r\n                                    std::move(subscript),\r\n                                    binaryOperator.op == BinaryOperatorKind::UnalignedIndexing ? 1 : *indirectionSize,\r\n                                    *indirectionSize));\r\n                            }\r\n                        }\r\n                    }\r\n                    return nullptr;\r\n                } else if (binaryOperator.op == BinaryOperatorKind::BitIndexing) {\r\n                    auto operand = createOperandFromExpression(binaryOperator.left.get(), quiet);\r\n                    auto subscript = createOperandFromExpression(binaryOperator.right.get(), quiet);\r\n                    if (operand && subscript) {\r\n                        return makeFwdUnique<InstructionOperand>(InstructionOperand::BitIndex(std::move(operand), std::move(subscript)));\r\n                    }\r\n                } else if (binaryOperator.op != BinaryOperatorKind::Assignment) {\r\n                    auto left = createOperandFromExpression(binaryOperator.left.get(), quiet);\r\n                    auto right = createOperandFromExpression(binaryOperator.right.get(), quiet);\r\n                    if (left && right) {\r\n                        const auto leftIntegerOperand = left->tryGet<InstructionOperand::Integer>();\r\n                        const auto rightIntegerOperand = right->tryGet<InstructionOperand::Integer>();\r\n\r\n                        if (leftIntegerOperand != nullptr && rightIntegerOperand != nullptr) {\r\n                            if (leftIntegerOperand->placeholder) {\r\n                                return left->clone();\r\n                            } else if (rightIntegerOperand->placeholder) {\r\n                                return right->clone();\r\n                            }\r\n                        }\r\n\r\n                        return makeFwdUnique<InstructionOperand>(InstructionOperand::Binary(binaryOperator.op, std::move(left), std::move(right)));\r\n                    }\r\n                }\r\n\r\n                return nullptr;\r\n            }\r\n            case ExpressionKind::BooleanLiteral: {\r\n                const auto& booleanLiteral = expression->booleanLiteral;\r\n                return makeFwdUnique<InstructionOperand>(InstructionOperand::Boolean(booleanLiteral.value));\r\n            }\r\n            case ExpressionKind::Call: return nullptr;\r\n            case ExpressionKind::Cast: {\r\n                const auto& cast = expression->cast;\r\n                const auto sourceType = cast.operand->info->type.get();\r\n                const auto destType = expression->info->type.get();\r\n                if (const auto sourceExpressionSize = calculateStorageSize(sourceType, \"left-hand side of cast expression\"_sv)) {\r\n                    if (const auto destTypeSize = calculateStorageSize(destType, \"right-hand side of cast expression\"_sv)) {\r\n                        bool validRuntimeCast = false;\r\n\r\n                        if (sourceExpressionSize.get() == destTypeSize.get()) {\r\n                            validRuntimeCast = true;\r\n                        } else {\r\n                            if (const auto resolvedIdentifier = cast.operand->tryGet<Expression::ResolvedIdentifier>()) {\r\n                                if (resolvedIdentifier->definition->kind == DefinitionKind::BuiltinRegister) {\r\n                                    validRuntimeCast = true;\r\n                                }\r\n                            }\r\n                        }\r\n\r\n                        if (validRuntimeCast) {\r\n                            return createOperandFromExpression(cast.operand.get(), quiet);\r\n                        } else {\r\n                            if (!quiet) {\r\n                                report->error(\"run-time cast from `\" + getTypeName(sourceType) + \"` to `\" + getTypeName(destType) + \"` is not possible because it would require a temporary\", expression->location, ReportErrorFlags::Continued);\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n                return nullptr;\r\n            }\r\n            case ExpressionKind::Embed: return nullptr;\r\n            case ExpressionKind::FieldAccess: return nullptr;\r\n            case ExpressionKind::Identifier: return nullptr;\r\n            case ExpressionKind::IntegerLiteral: {\r\n                const auto& integerLiteral = expression->integerLiteral;\r\n                return makeFwdUnique<InstructionOperand>(InstructionOperand::Integer(integerLiteral.value));\r\n            }\r\n            case ExpressionKind::OffsetOf: return nullptr;\r\n            case ExpressionKind::RangeLiteral: return nullptr;\r\n            case ExpressionKind::ResolvedIdentifier: {\r\n                const auto& resolvedIdentifier = expression->resolvedIdentifier;\r\n                return createOperandFromResolvedIdentifier(expression, resolvedIdentifier.definition);\r\n            }\r\n            case ExpressionKind::SideEffect: return nullptr;\r\n            case ExpressionKind::StringLiteral: return nullptr;\r\n            case ExpressionKind::StructLiteral: return nullptr;\r\n            case ExpressionKind::TupleLiteral: return nullptr;\r\n            case ExpressionKind::TypeOf: return nullptr;\r\n            case ExpressionKind::TypeQuery: return nullptr;\r\n            case ExpressionKind::UnaryOperator: {\r\n                const auto& unaryOperator = expression->unaryOperator;\r\n                if (auto operand = createOperandFromExpression(unaryOperator.operand.get(), quiet)) {\r\n                    switch (unaryOperator.op) {\r\n                        case UnaryOperatorKind::Indirection: {\r\n                            const auto far = (unaryOperator.operand->info->qualifiers & Qualifiers::Far) != Qualifiers::None;\r\n\r\n                            if (const auto indirectionSize = calculateStorageSize(expression->info->type.get(), \"operand\"_sv)) {\r\n                                if (const auto bin = operand->tryGet<InstructionOperand::Binary>()) {\r\n                                    if (bin->kind == BinaryOperatorKind::Addition) {\r\n                                        return makeFwdUnique<InstructionOperand>(InstructionOperand::Index(\r\n                                            far,\r\n                                            bin->left->clone(),\r\n                                            bin->right->clone(),\r\n                                            1,\r\n                                            *indirectionSize));\r\n                                    } else if (bin->kind == BinaryOperatorKind::Subtraction) {\r\n                                        if (const auto rightIntegerOperand = bin->right->tryGet<InstructionOperand::Integer>()) {\r\n                                            if (rightIntegerOperand->placeholder) {\r\n                                                return makeFwdUnique<InstructionOperand>(InstructionOperand::Index(\r\n                                                    far,\r\n                                                    bin->left->clone(),\r\n                                                    bin->right->clone(),\r\n                                                    1,\r\n                                                    *indirectionSize));\r\n                                            } else {\r\n                                                return makeFwdUnique<InstructionOperand>(InstructionOperand::Index(\r\n                                                    far,\r\n                                                    bin->left->clone(),\r\n                                                    makeFwdUnique<InstructionOperand>(InstructionOperand::Integer(-rightIntegerOperand->value)),\r\n                                                    1,\r\n                                                    *indirectionSize));\r\n                                            }\r\n                                        }\r\n                                    }\r\n                                }\r\n                                return makeFwdUnique<InstructionOperand>(InstructionOperand::Dereference(\r\n                                    far,\r\n                                    std::move(operand),\r\n                                    *indirectionSize));\r\n                            }\r\n                            return nullptr;\r\n                        }\r\n                        default: {\r\n                            return makeFwdUnique<InstructionOperand>(InstructionOperand::Unary(unaryOperator.op, std::move(operand)));\r\n                        }\r\n                    }\r\n                }\r\n                return nullptr;\r\n            }\r\n            default: std::abort(); return nullptr;\r\n        }\r\n    }\r\n\r\n    FwdUniquePtr<InstructionOperand> Compiler::createOperandFromExpression(const Expression* expression, bool quiet) const {\r\n        if (expression->info->context == EvaluationContext::RunTime) {\r\n            return createOperandFromRunTimeExpression(expression, quiet);\r\n        } else {\r\n            return createOperandFromLinkTimeExpression(expression, quiet);\r\n        }\r\n    }\r\n\r\n    bool Compiler::isLeafExpression(const Expression* expression) const {\r\n        if (expression->info->context == EvaluationContext::RunTime) {\r\n            switch (expression->kind){\r\n                case ExpressionKind::ArrayComprehension: return true;\r\n                case ExpressionKind::ArrayPadLiteral: return true;\r\n                case ExpressionKind::ArrayLiteral: return true;\r\n                case ExpressionKind::BinaryOperator: {\r\n                    const auto& binaryOperator = expression->binaryOperator;\r\n                    const auto op = binaryOperator.op;\r\n                    if (op == BinaryOperatorKind::BitIndexing                    \r\n                    || op == BinaryOperatorKind::Indexing\r\n                    || op == BinaryOperatorKind::UnalignedIndexing) {\r\n                        return true;\r\n                    }\r\n                    return false;\r\n                }\r\n                case ExpressionKind::BooleanLiteral: return true;\r\n                case ExpressionKind::Call: return false;\r\n                case ExpressionKind::Cast: return true;\r\n                case ExpressionKind::Embed: return true;\r\n                case ExpressionKind::FieldAccess: return true;\r\n                case ExpressionKind::Identifier: return true;\r\n                case ExpressionKind::IntegerLiteral: return true;\r\n                case ExpressionKind::OffsetOf: return true;\r\n                case ExpressionKind::RangeLiteral: return true;\r\n                case ExpressionKind::ResolvedIdentifier: return true;\r\n                case ExpressionKind::SideEffect: return false;\r\n                case ExpressionKind::StringLiteral: return true;\r\n                case ExpressionKind::StructLiteral: return true;\r\n                case ExpressionKind::TupleLiteral: return true;\r\n                case ExpressionKind::TypeOf: return true;\r\n                case ExpressionKind::TypeQuery: return true;\r\n                case ExpressionKind::UnaryOperator: {\r\n                    const auto& unaryOperator = expression->unaryOperator;\r\n                    if (unaryOperator.op == UnaryOperatorKind::Indirection) {\r\n                        return true;\r\n                    }\r\n                    return false;\r\n                }\r\n                default: std::abort(); return false;\r\n            }\r\n        } else {\r\n            return true;\r\n        }\r\n    }\r\n\r\n    bool Compiler::hasNestedAssignment(const Expression* expression) const {\r\n        if (expression->info->context == EvaluationContext::RunTime) {\r\n            switch (expression->kind){\r\n                case ExpressionKind::ArrayComprehension: return false;\r\n                case ExpressionKind::ArrayPadLiteral: return false;\r\n                case ExpressionKind::ArrayLiteral: return false;\r\n                case ExpressionKind::BinaryOperator: {\r\n                    const auto& binaryOperator = expression->binaryOperator;\r\n                    return binaryOperator.op == BinaryOperatorKind::Assignment\r\n                        || hasNestedAssignment(binaryOperator.left.get())\r\n                        || hasNestedAssignment(binaryOperator.right.get());\r\n                }\r\n                case ExpressionKind::BooleanLiteral: return false;\r\n                case ExpressionKind::Call: {\r\n                    const auto& call = expression->call;\r\n                    return !call.inlined && hasNestedAssignment(call.function.get());\r\n                }\r\n                case ExpressionKind::Cast: {\r\n                    const auto& cast = expression->cast;\r\n                    return hasNestedAssignment(cast.operand.get());\r\n                }\r\n                case ExpressionKind::Embed: return false;\r\n                case ExpressionKind::FieldAccess: return false;\r\n                case ExpressionKind::Identifier: return false;\r\n                case ExpressionKind::IntegerLiteral: return false;\r\n                case ExpressionKind::OffsetOf: return false;\r\n                case ExpressionKind::RangeLiteral: return false;\r\n                case ExpressionKind::ResolvedIdentifier: return false;\r\n                case ExpressionKind::SideEffect: return false;\r\n                case ExpressionKind::StringLiteral: return false;\r\n                case ExpressionKind::StructLiteral: return false;\r\n                case ExpressionKind::TupleLiteral: return false;\r\n                case ExpressionKind::TypeOf: return false;\r\n                case ExpressionKind::TypeQuery: return false;\r\n                case ExpressionKind::UnaryOperator: {\r\n                    const auto& unaryOperator = expression->unaryOperator;\r\n                    return isUnaryIncrementOperator(unaryOperator.op)\r\n                        || hasNestedAssignment(unaryOperator.operand.get());\r\n                }\r\n                default: std::abort(); return false;\r\n            }\r\n        } else {\r\n            return false;\r\n        }\r\n    }\r\n\r\n    bool Compiler::emitNestedAssignmentIr(const Expression* expression, bool pre, bool post) {\r\n        if (expression->info->context == EvaluationContext::RunTime) {\r\n            switch (expression->kind){\r\n                case ExpressionKind::ArrayComprehension: return true;\r\n                case ExpressionKind::ArrayPadLiteral: return true;\r\n                case ExpressionKind::ArrayLiteral: return true;\r\n                case ExpressionKind::BinaryOperator: {\r\n                    const auto& binaryOperator = expression->binaryOperator;\r\n                    const auto left = binaryOperator.left.get();\r\n                    const auto right = binaryOperator.right.get();\r\n\r\n                    if (binaryOperator.op == BinaryOperatorKind::Assignment) {\r\n                        return pre\r\n                            ? emitAssignmentExpressionIr(left, right, left->location)\r\n                            : true;\r\n                    } else {\r\n                        return emitNestedAssignmentIr(left, pre, post)\r\n                            && emitNestedAssignmentIr(right, pre, post);\r\n                    }\r\n                }\r\n                case ExpressionKind::BooleanLiteral: return true;\r\n                case ExpressionKind::Call: {\r\n                    const auto& call = expression->call;\r\n                    if (!call.inlined) {\r\n                        return emitNestedAssignmentIr(call.function.get(), pre, post);\r\n                    } else {\r\n                        return true;\r\n                    }\r\n                }\r\n                case ExpressionKind::Cast: {\r\n                    const auto& cast = expression->cast;\r\n                    return emitNestedAssignmentIr(cast.operand.get(), pre, post);\r\n                }\r\n                case ExpressionKind::Embed: return true;\r\n                case ExpressionKind::FieldAccess: return true;\r\n                case ExpressionKind::Identifier: return true;\r\n                case ExpressionKind::IntegerLiteral: return true;\r\n                case ExpressionKind::OffsetOf: return true;\r\n                case ExpressionKind::RangeLiteral: return true;\r\n                case ExpressionKind::ResolvedIdentifier: return true;\r\n                case ExpressionKind::SideEffect: return true;\r\n                case ExpressionKind::StringLiteral: return true;\r\n                case ExpressionKind::StructLiteral: return true;\r\n                case ExpressionKind::TupleLiteral: return true;\r\n                case ExpressionKind::TypeOf: return true;\r\n                case ExpressionKind::TypeQuery: return true;\r\n                case ExpressionKind::UnaryOperator: {\r\n                    const auto& unaryOperator = expression->unaryOperator;\r\n                    const auto& op = unaryOperator.op;\r\n                    const auto operand = unaryOperator.operand.get();\r\n\r\n                    if (isUnaryPreIncrementOperator(op)) {\r\n                        if (pre && !emitUnaryExpressionIr(operand, op, operand, operand->location)) {\r\n                            raiseEmitUnaryExpressionError(operand, UnaryOperatorKind::PreIncrement, operand, operand->location);\r\n                            return false;\r\n                        }\r\n                        return true;\r\n                    } else if (isUnaryPostIncrementOperator(op)) {\r\n                        if (post && !emitUnaryExpressionIr(operand, getUnaryPreIncrementEquivalent(op), operand, operand->location)) {\r\n                            raiseEmitUnaryExpressionError(operand, op, operand, operand->location);\r\n                            return false;\r\n                        }\r\n                        return true;\r\n                    } else {\r\n                        return emitNestedAssignmentIr(operand, pre, post);\r\n                    }\r\n                }\r\n                default: std::abort(); return false;\r\n            }\r\n        } else {\r\n            return true;\r\n        }\r\n    }\r\n\r\n    FwdUniquePtr<const Expression> Compiler::stripNestedAssignment(const Expression* expression) const {\r\n        if (expression->info->context == EvaluationContext::RunTime) {\r\n            switch (expression->kind){\r\n                case ExpressionKind::ArrayComprehension: return expression->clone();\r\n                case ExpressionKind::ArrayPadLiteral: return expression->clone();\r\n                case ExpressionKind::ArrayLiteral: return expression->clone();\r\n                case ExpressionKind::BinaryOperator: {\r\n                    const auto& binaryOperator = expression->binaryOperator;\r\n                    const auto op = binaryOperator.op;\r\n                    const auto left = binaryOperator.left.get();\r\n                    const auto right = binaryOperator.right.get();\r\n\r\n                    auto strippedLeft = stripNestedAssignment(left);\r\n\r\n                    if (op == BinaryOperatorKind::Assignment) {\r\n                        return strippedLeft;\r\n                    } else {\r\n                        auto strippedRight = stripNestedAssignment(right);\r\n\r\n                        return makeFwdUnique<const Expression>(\r\n                            Expression::BinaryOperator(op, std::move(strippedLeft), std::move(strippedRight)),\r\n                            expression->location,\r\n                            expression->info->clone());\r\n                    }\r\n                }\r\n                case ExpressionKind::BooleanLiteral: return expression->clone();\r\n                case ExpressionKind::Call: {\r\n                    const auto& call = expression->call;\r\n\r\n                    if (!call.inlined) {\r\n                        const auto function = call.function.get();\r\n                        const auto& arguments = call.arguments;\r\n\r\n                        auto strippedFunction = stripNestedAssignment(function);\r\n                        std::vector<FwdUniquePtr<const Expression>> clonedArguments;\r\n                        for (auto& argument : arguments) {\r\n                            clonedArguments.push_back(argument->clone());\r\n                        }\r\n\r\n                        return makeFwdUnique<const Expression>(\r\n                            Expression::Call(false, std::move(strippedFunction), std::move(clonedArguments)),\r\n                            expression->location,\r\n                            expression->info->clone());\r\n                    } else {\r\n                        return expression->clone();\r\n                    }\r\n                }\r\n                case ExpressionKind::Cast: {\r\n                    const auto& cast = expression->cast;\r\n                    const auto& operand = cast.operand.get();\r\n                    auto strippedOperand = stripNestedAssignment(operand);\r\n\r\n                    return makeFwdUnique<const Expression>(\r\n                        Expression::Cast(std::move(strippedOperand), cast.type->clone()),\r\n                        expression->location,\r\n                        expression->info->clone());\r\n                }\r\n                case ExpressionKind::Embed: return expression->clone();\r\n                case ExpressionKind::FieldAccess: return expression->clone();\r\n                case ExpressionKind::Identifier: return expression->clone();\r\n                case ExpressionKind::IntegerLiteral: return expression->clone();\r\n                case ExpressionKind::OffsetOf: return expression->clone();\r\n                case ExpressionKind::RangeLiteral: return expression->clone();\r\n                case ExpressionKind::ResolvedIdentifier: return expression->clone();\r\n                case ExpressionKind::SideEffect: return expression->clone();\r\n                case ExpressionKind::StringLiteral: return expression->clone();\r\n                case ExpressionKind::StructLiteral: return expression->clone();\r\n                case ExpressionKind::TupleLiteral: return expression->clone();\r\n                case ExpressionKind::TypeOf: return expression->clone();\r\n                case ExpressionKind::TypeQuery: return expression->clone();\r\n                case ExpressionKind::UnaryOperator: {\r\n                    const auto& unaryOperator = expression->unaryOperator;\r\n                    const auto op = unaryOperator.op;\r\n                    const auto operand = unaryOperator.operand.get();\r\n\r\n                    auto strippedOperand = stripNestedAssignment(operand);\r\n\r\n                    if (isUnaryIncrementOperator(op)) {\r\n                        return strippedOperand;\r\n                    } else {\r\n                        return makeFwdUnique<const Expression>(\r\n                            Expression::UnaryOperator(op, std::move(strippedOperand)),\r\n                            expression->location,\r\n                            expression->info->clone());\r\n                    }\r\n                }\r\n                default: std::abort(); return nullptr;\r\n            }\r\n        } else {\r\n            return expression->clone();\r\n        }\r\n    }\r\n\r\n    bool Compiler::emitLoadExpressionIr(const Expression* dest, const Expression* source, SourceLocation location) {\r\n        auto destOperand = createOperandFromExpression(dest, true);\r\n        auto sourceOperand = createOperandFromExpression(source, true);\r\n\r\n        if (!destOperand || !sourceOperand) {\r\n            return false;\r\n        }\r\n\r\n        if (*destOperand == *sourceOperand) {\r\n            return true;\r\n        }\r\n\r\n        std::vector<InstructionOperandRoot> operandRoots;\r\n        operandRoots.reserve(2);\r\n        operandRoots.push_back(InstructionOperandRoot(dest, std::move(destOperand)));\r\n        operandRoots.push_back(InstructionOperandRoot(source, std::move(sourceOperand)));\r\n\r\n        if (const auto instruction = builtins.selectInstruction(InstructionType(BinaryOperatorKind::Assignment), modeFlags, operandRoots)) {\r\n            irNodes.addNew(IrNode::Code(instruction, std::move(operandRoots)), location);\r\n            return true;\r\n        } else {\r\n            return false;\r\n        }\r\n    }\r\n\r\n    bool Compiler::emitUnaryExpressionIr(const Expression* dest, UnaryOperatorKind op, const Expression* source, SourceLocation location) {\r\n        auto destOperand = createOperandFromExpression(dest, true);\r\n        auto sourceOperand = createOperandFromExpression(source, true);\r\n\r\n        if (!destOperand || !sourceOperand) {\r\n            return false;\r\n        }\r\n\r\n        std::vector<InstructionOperandRoot> operandRoots;\r\n\r\n        if (*destOperand == *sourceOperand) {\r\n            \/\/ dest = -dest; or ++dest; instruction\r\n            operandRoots.reserve(1);\r\n            operandRoots.push_back(InstructionOperandRoot(dest, std::move(destOperand)));\r\n        } else {\r\n            \/\/ dest = -source; instruction\r\n            operandRoots.reserve(2);\r\n            operandRoots.push_back(InstructionOperandRoot(dest, std::move(destOperand)));\r\n            operandRoots.push_back(InstructionOperandRoot(source, std::move(sourceOperand)));\r\n        }            \r\n\r\n        if (const auto instruction = builtins.selectInstruction(InstructionType(op), modeFlags, operandRoots)) {\r\n            irNodes.addNew(IrNode::Code(instruction, std::move(operandRoots)), location);\r\n            return true;\r\n        } else {\r\n            return false;\r\n        }\r\n    }\r\n\r\n    bool Compiler::emitBinaryExpressionIr(const Expression* dest, BinaryOperatorKind op, const Expression* left, const Expression* right, SourceLocation location) {\r\n        auto destOperand = createOperandFromExpression(dest, true);\r\n        auto leftOperand = createOperandFromExpression(left, true);\r\n        auto rightOperand = createOperandFromExpression(right, true);\r\n\r\n        if (!destOperand || !leftOperand || !rightOperand) {\r\n            return false;\r\n        }\r\n\r\n        std::vector<InstructionOperandRoot> operandRoots;\r\n\r\n        if (*destOperand == *leftOperand) {\r\n            \/\/ dest += right; instruction\r\n            operandRoots.reserve(2);\r\n            operandRoots.push_back(InstructionOperandRoot(dest, std::move(destOperand)));\r\n            operandRoots.push_back(InstructionOperandRoot(right, std::move(rightOperand)));\r\n        } else {\r\n            \/\/ dest = left + right; instruction\r\n            operandRoots.reserve(3);\r\n            operandRoots.push_back(InstructionOperandRoot(dest, std::move(destOperand)));\r\n            operandRoots.push_back(InstructionOperandRoot(left, std::move(leftOperand)));\r\n            operandRoots.push_back(InstructionOperandRoot(right, std::move(rightOperand)));\r\n        }\r\n\r\n        if (const auto instruction = builtins.selectInstruction(InstructionType(op), modeFlags, operandRoots)) {\r\n            irNodes.addNew(\r\n                IrNode::Code(instruction, std::move(operandRoots)),\r\n                location);\r\n            return true;\r\n        } else {\r\n            return false;\r\n        }\r\n    }\r\n\r\n    bool Compiler::emitArgumentPassIr(const TypeExpression* functionTypeExpression, const std::vector<Definition*>& parameters, const std::vector<FwdUniquePtr<const Expression>>& arguments, SourceLocation location) {\r\n        static_cast<void>(location);\r\n\r\n        auto& functionType = functionTypeExpression->function;\r\n\r\n        if (functionType.parameters.size() != arguments.size()) {\r\n            return false;\r\n        }\r\n\r\n        for (std::size_t i = 0; i != arguments.size(); ++i) {\r\n            const auto& parameterType = functionType.parameters[i]->parameterType;\r\n            const auto& argument = arguments[i];\r\n            if (auto designatedStorageType = parameterType->tryGet<TypeExpression::DesignatedStorage>()) {\r\n                emitAssignmentExpressionIr(designatedStorageType->holder.get(), argument.get(), argument->location);\r\n\r\n            } else {\r\n                report->error(\r\n                    \"could not generate initializer for argument `\"\r\n                        + (parameters.size() != 0 ? \"argument `\" + parameters[i]->name.toString() + \"`\" : \"argument #\" + std::to_string(i))\r\n                        + \"` of type `\" + getTypeName(parameterType.get()) + \"`\",\r\n                    argument->location);\r\n                return false;\r\n            }\r\n        }\r\n\r\n        return true;\r\n    }\r\n\r\n    bool Compiler::emitCallExpressionIr(std::size_t distanceHint, bool inlined, bool tailCall, const Expression* resultDestination, const Expression* function, const std::vector<FwdUniquePtr<const Expression>>& arguments, SourceLocation location) {\r\n        if (const auto resolvedIdentifier = function->tryGet<Expression::ResolvedIdentifier>()) {\r\n            const auto definition = resolvedIdentifier->definition;\r\n\r\n            if (const auto funcDefinition = definition->tryGet<Definition::Func>()) {\r\n                auto& functionType = funcDefinition->resolvedSignatureType->function;\r\n\r\n                if (!emitArgumentPassIr(funcDefinition->resolvedSignatureType.get(), funcDefinition->parameters, arguments, location)) {\r\n                    return false;\r\n                }\r\n\r\n                if (inlined || funcDefinition->inlined) {\r\n                    tailCall = false;\r\n                    static_cast<void>(tailCall);\r\n\r\n                    auto oldReturnKind = funcDefinition->returnKind;\r\n                    auto oldInlined = funcDefinition->inlined;\r\n                    funcDefinition->returnKind = BranchKind::None;\r\n                    funcDefinition->inlined = true;\r\n\r\n                    const auto oldContinueLabel = continueLabel;\r\n                    const auto oldBreakLabel = breakLabel;\r\n                    const auto onExit = makeScopeGuard([&]() {\r\n                        continueLabel = oldContinueLabel;\r\n                        breakLabel = oldBreakLabel;\r\n                    });\r\n\r\n                    continueLabel = nullptr;\r\n                    breakLabel = nullptr;\r\n\r\n                    enterInlineSite(registeredInlineSites.addNew());\r\n\r\n                    const auto funcDeclaration = definition->declaration;\r\n                    enterScope(getOrCreateStatementScope(stringPool->intern(SymbolTable::generateBlockName()), funcDeclaration, funcDefinition->enclosingScope));\r\n\r\n                    bool valid = reserveDefinitions(funcDeclaration) && resolveDefinitionTypes() && reserveStorage(funcDeclaration);\r\n\r\n                    if (valid) {\r\n                        \/\/ TODO: templating on type or expression???\r\n                        valid = emitFunctionIr(definition, function->location);\r\n                        static_cast<void>(valid);\r\n                    }\r\n\r\n                    exitScope();\r\n                    exitInlineSite();\r\n                    funcDefinition->returnKind = oldReturnKind;\r\n                    funcDefinition->inlined = oldInlined;\r\n\r\n                } else {\r\n                    auto destOperand = createOperandFromExpression(function, true);\r\n\r\n                    if (!destOperand) {\r\n                        return false;\r\n                    }\r\n\r\n                    std::vector<InstructionOperandRoot> operandRoots;\r\n                    operandRoots.reserve(2);\r\n                    operandRoots.push_back(InstructionOperandRoot(nullptr, makeFwdUnique<InstructionOperand>(InstructionOperand::Integer(Int128(distanceHint)))));\r\n                    operandRoots.push_back(InstructionOperandRoot(function, std::move(destOperand)));\r\n\r\n                    bool far = functionType.far;\r\n                    BranchKind kind = BranchKind::None;\r\n\r\n                    if (tailCall) {\r\n                        kind = far ? BranchKind::FarGoto : BranchKind::Goto;\r\n                    } else {\r\n                        kind = far ? BranchKind::FarCall : BranchKind::Call;\r\n                    }\r\n\r\n                    if (const auto instruction = builtins.selectInstruction(InstructionType(kind), modeFlags, operandRoots)) {\r\n                        irNodes.addNew(IrNode::Code(instruction, std::move(operandRoots)), function->location);\r\n                    } else {\r\n                        return false;\r\n                    }\r\n                }\r\n\r\n                if (resultDestination != nullptr) {\r\n                    const auto returnType = functionType.returnType.get();\r\n\r\n\t\t\t\t\tif (const auto designatedStorageType = returnType->tryGet<TypeExpression::DesignatedStorage>()) {\r\n\t\t\t\t\t\tauto destOperand = createOperandFromExpression(resultDestination, true);\r\n\t\t\t\t\t\tauto sourceOperand = createOperandFromExpression(designatedStorageType->holder.get(), true);\r\n\r\n\t\t\t\t\t\tif (destOperand == nullptr || sourceOperand == nullptr || *destOperand != *sourceOperand) {\r\n\t\t\t\t\t\t\treport->error(\"could not generate assignment for `func \" + definition->name.toString() + \"` result of type `\" + getTypeName(returnType) + \"`\", location);\r\n\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n                return true;\r\n            } else if (definition->kind == DefinitionKind::BuiltinVoidIntrinsic) {\r\n                if (resultDestination != nullptr) {\r\n                    report->error(\"void intrinsic `\" + definition->name.toString() + \"` has no return value so its result cannot be stored.\", location);\r\n                    return false;\r\n                }\r\n\r\n                std::vector<InstructionOperandRoot> operandRoots;\r\n                operandRoots.reserve(arguments.size());\r\n\r\n                for (const auto& argument : arguments) {\r\n                    const Expression* expression = nullptr;\r\n                    FwdUniquePtr<InstructionOperand> operand;\r\n\r\n                    expression = argument.get();\r\n                    operand = createOperandFromExpression(argument.get(), true);\r\n                    if (!operand) {\r\n                        if (const auto binaryOperator = argument->tryGet<Expression::BinaryOperator>()) {\r\n                            if (binaryOperator->op == BinaryOperatorKind::Assignment) {\r\n                                if (!emitAssignmentExpressionIr(binaryOperator->left.get(), binaryOperator->right.get(), binaryOperator->left->location)) {\r\n                                    return false;\r\n                                }\r\n                                expression = binaryOperator->left.get();\r\n                                operand = createOperandFromExpression(expression, true);\r\n                            }\r\n                        } else if (const auto unaryOperator = argument->tryGet<Expression::UnaryOperator>()) {\r\n                            const auto term = unaryOperator->operand.get();\r\n                            const auto op = unaryOperator->op;\r\n                            if (op == UnaryOperatorKind::PreIncrement || op == UnaryOperatorKind::PreDecrement) {\r\n                                if (!emitUnaryExpressionIr(term, op, term, term->location)) {\r\n                                    raiseEmitUnaryExpressionError(term, op, term, term->location);\r\n                                    return false;\r\n                                }\r\n                                expression = term;\r\n                                operand = createOperandFromExpression(term, true);\r\n                            } else {\r\n                                expression = nullptr;\r\n                                operand = nullptr;\r\n                            }\r\n                        }\r\n                    }\r\n                        \r\n                    operandRoots.push_back(InstructionOperandRoot(expression, std::move(operand)));\r\n                }\r\n\r\n                if (const auto instruction = builtins.selectInstruction(\r\n                    InstructionType(InstructionType::VoidIntrinsic(definition)),\r\n                    modeFlags,\r\n                    operandRoots)\r\n                ) {\r\n                    irNodes.addNew(IrNode::Code(instruction, std::move(operandRoots)), function->location);\r\n                    return true;\r\n                } else {\r\n                    raiseEmitIntrinsicError(InstructionType(InstructionType::VoidIntrinsic(definition)), operandRoots, location);\r\n                    return false;\r\n                }\r\n            } else if (definition->kind == DefinitionKind::BuiltinLoadIntrinsic) {\r\n                if (resultDestination == nullptr) {\r\n                    report->error(\"load intrinsic `\" + definition->name.toString() + \"` must have its result stored somewhere.\", location);\r\n                    return false;\r\n                }\r\n\r\n                std::vector<InstructionOperandRoot> operandRoots;\r\n                operandRoots.reserve(arguments.size() + 1);\r\n\r\n                operandRoots.push_back(InstructionOperandRoot(resultDestination, createOperandFromExpression(resultDestination, true)));\r\n\r\n                for (const auto& argument : arguments) {\r\n                    const Expression* expression = nullptr;\r\n                    FwdUniquePtr<InstructionOperand> operand;\r\n\r\n                    expression = argument.get();\r\n                    operand = createOperandFromExpression(argument.get(), true);\r\n\r\n                    if (!operand) {\r\n                        if (const auto binaryOperator = argument->tryGet<Expression::BinaryOperator>()) {\r\n                            if (binaryOperator->op == BinaryOperatorKind::Assignment) {\r\n                                if (!emitAssignmentExpressionIr(binaryOperator->left.get(), binaryOperator->right.get(), binaryOperator->left->location)) {\r\n                                    return false;\r\n                                }\r\n                                expression = binaryOperator->left.get();\r\n                                operand = createOperandFromExpression(expression, true);\r\n                            }\r\n                        } else if (const auto unaryOperator = argument->tryGet<Expression::UnaryOperator>()) {\r\n                            const auto term = unaryOperator->operand.get();\r\n                            const auto op = unaryOperator->op;\r\n                            if (op == UnaryOperatorKind::PreIncrement || op == UnaryOperatorKind::PreDecrement) {\r\n                                if (!emitUnaryExpressionIr(term, op, term, term->location)) {\r\n                                    raiseEmitUnaryExpressionError(term, op, term, term->location);\r\n                                    return false;\r\n                                }\r\n                                expression = term;\r\n                                operand = createOperandFromExpression(term, true);\r\n                            } else {\r\n                                expression = nullptr;\r\n                                operand = nullptr;\r\n                            }\r\n                        }\r\n                    }\r\n                    \r\n                    operandRoots.push_back(InstructionOperandRoot(expression, std::move(operand)));\r\n                }\r\n                \r\n                if (const auto instruction = builtins.selectInstruction(\r\n                    InstructionType(InstructionType::LoadIntrinsic(definition)),\r\n                    modeFlags,\r\n                    operandRoots)\r\n                ) {\r\n                    irNodes.addNew(IrNode::Code(instruction, std::move(operandRoots)), location);\r\n                    return true;\r\n                } else {\r\n                    raiseEmitIntrinsicError(InstructionType(InstructionType::LoadIntrinsic(definition)), operandRoots, location);\r\n                    return false;\r\n                }\r\n            }\r\n        } else if (const auto functionType = function->info->type->tryGet<TypeExpression::Function>()) {\r\n            auto destOperand = createOperandFromExpression(function, true);\r\n\r\n            if (!destOperand) {\r\n                return false;\r\n            }\r\n\r\n            std::vector<InstructionOperandRoot> operandRoots;\r\n            operandRoots.reserve(2);\r\n            operandRoots.push_back(InstructionOperandRoot(nullptr, makeFwdUnique<InstructionOperand>(InstructionOperand::Integer(Int128(0)))));\r\n            operandRoots.push_back(InstructionOperandRoot(function, std::move(destOperand)));\r\n\r\n            if (!emitArgumentPassIr(function->info->type.get(), {}, arguments, location)) {\r\n                return false;\r\n            }\r\n\r\n            bool far = functionType->far;\r\n            BranchKind kind = BranchKind::None;\r\n\r\n            if (tailCall) {\r\n                kind = far ? BranchKind::FarGoto : BranchKind::Goto;\r\n            } else {\r\n                kind = far ? BranchKind::FarCall : BranchKind::Call;\r\n            }\r\n\r\n            if (const auto instruction = builtins.selectInstruction(InstructionType(kind), modeFlags, operandRoots)) {\r\n                irNodes.addNew(IrNode::Code(instruction, std::move(operandRoots)), function->location);\r\n\r\n                if (resultDestination != nullptr) {\r\n                    const auto returnType = functionType->returnType.get();\r\n\r\n                    if (auto designatedStorageType = returnType->tryGet<TypeExpression::DesignatedStorage>()) {\r\n                        emitAssignmentExpressionIr(resultDestination, designatedStorageType->holder.get(), location);\r\n                    } else {\r\n                        report->error(\"could not generate assignment for `func` result of type `\" + getTypeName(returnType) + \"`\", location);\r\n                    }\r\n                }\r\n\r\n                return true;\r\n            } else {\r\n                return false;\r\n            }\r\n        }\r\n\r\n        report->error(\"unhandled call expression\", location, ReportErrorFlags::InternalError);\r\n        return false;\r\n    }\r\n\r\n    std::string Compiler::getModeFlagString(std::uint32_t modeFlags) {\r\n        std::string result = \"\";\r\n        for (std::size_t modeIndex = 0, modeCount = builtins.getModeAttributeCount(); modeIndex != modeCount; ++modeIndex) {\r\n            if ((modeFlags & (1U << modeIndex)) != 0) {\r\n                const auto modeAttribute = builtins.getModeAttribute(modeIndex);\r\n                result += (result.size() > 0 ? \", \" : \"\") + modeAttribute->name.toString();\r\n            }\r\n        }\r\n        return result;\r\n    }\r\n\r\n    void Compiler::raiseEmitLoadError(const Expression* dest, const Expression* source, SourceLocation location) {\r\n        const auto candidates = builtins.findAllInstructionsByType(InstructionType(BinaryOperatorKind::Assignment));\r\n        report->error(\"could not generate code for \" + getBinaryOperatorName(BinaryOperatorKind::Assignment).toString(), source->location, ReportErrorFlags::Continued);\r\n\r\n        auto destOperand = createOperandFromExpression(dest, false);\r\n        auto sourceOperand = createOperandFromExpression(source, false);\r\n\r\n        if (destOperand == nullptr) {\r\n            report->error(\"could not create an instruction operand for destination of \" + getBinaryOperatorName(BinaryOperatorKind::Assignment).toString(), location);\r\n            return;\r\n        }\r\n        if (sourceOperand == nullptr) {\r\n            report->error(\"could not create an instruction operand for source of \" + getBinaryOperatorName(BinaryOperatorKind::Assignment).toString(), location);\r\n            return;\r\n        }\r\n\r\n        {\r\n            auto message = \"got: `\"\r\n                + destOperand->toString()\r\n                + \" = \" + sourceOperand->toString()\r\n                + \"`\";\r\n            if (modeFlags != 0) {\r\n                message += \" (\" + getModeFlagString(modeFlags) + \")\";\r\n            }\r\n\r\n            report->error(message, source->location, ReportErrorFlags::Continued);\r\n        }\r\n\r\n        if (candidates.size() > 0) {\r\n            std::size_t optionCount = 0;\r\n            for (const auto candidate : candidates) {\r\n                switch (candidate->signature.operandPatterns.size()) {\r\n                    case 2: {\r\n                        if (candidate->signature.operandPatterns[0]->matches(*destOperand)) {\r\n                            if (optionCount == 0) {\r\n                                report->error(\"possible options:\", source->location, ReportErrorFlags::Continued);\r\n                            }\r\n                            ++optionCount;\r\n\r\n                            auto message = \"  `\"\r\n                                + candidate->signature.operandPatterns[0]->toString()\r\n                                + \" = \" + candidate->signature.operandPatterns[1]->toString()\r\n                                + \"`\";\r\n                            if (candidate->signature.requiredModeFlags != 0) {\r\n                                message += \" (\" + getModeFlagString(candidate->signature.requiredModeFlags) + \")\";\r\n                            }\r\n\r\n                            report->log(message);\r\n                        }\r\n                        break;\r\n                    }\r\n                    default: {\r\n                        std::abort();\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        report->error(\"assignment must be rewritten some other way\\n\", source->location);\r\n    }\r\n\r\n    void Compiler::raiseEmitUnaryExpressionError(const Expression* dest, UnaryOperatorKind op, const Expression* source, SourceLocation location) {\r\n        const auto candidates = builtins.findAllInstructionsByType(InstructionType(op));\r\n        report->error(\"could not generate code for \" + getUnaryOperatorName(op).toString(), source->location, ReportErrorFlags::Continued);\r\n\r\n        auto destOperand = createOperandFromExpression(dest, false);\r\n        auto sourceOperand = createOperandFromExpression(source, false);\r\n\r\n        if (destOperand == nullptr) {\r\n            report->error(\"could not create an instruction operand for destination of \" + getUnaryOperatorName(op).toString(), location);\r\n            return;\r\n        }\r\n        if (sourceOperand == nullptr) {\r\n            report->error(\"could not create an instruction operand for source of \" + getUnaryOperatorName(op).toString(), location);\r\n            return;\r\n        }\r\n\r\n        bool isIncrement = isUnaryIncrementOperator(op);\r\n        op = getUnaryPreIncrementEquivalent(op);\r\n\r\n        if (isIncrement && *destOperand == *sourceOperand) {\r\n            auto message = \"got: `\"\r\n                + getUnaryOperatorSymbol(op).toString()\r\n                + destOperand->toString()\r\n                + \"`\";\r\n            if (modeFlags != 0) {\r\n                message += \" (\" + getModeFlagString(modeFlags) + \")\";\r\n            }\r\n\r\n            report->error(message, source->location, ReportErrorFlags::Continued);\r\n        } else {\r\n            auto message = \"got: `\"\r\n                + destOperand->toString()\r\n                + \" = \"\r\n                + getUnaryOperatorSymbol(op).toString()\r\n                + sourceOperand->toString()\r\n                + \"`\";\r\n            if (modeFlags != 0) {\r\n                message += \" (\" + getModeFlagString(modeFlags) + \")\";\r\n            }\r\n\r\n            report->error(message, source->location, ReportErrorFlags::Continued);\r\n        }\r\n\r\n        if (candidates.size() > 0) {\r\n            report->error(\"possible options:\", source->location, ReportErrorFlags::Continued);\r\n            for (const auto candidate : candidates) {\r\n                switch (candidate->signature.operandPatterns.size()) {\r\n                    case 1: {\r\n                        std::string message;\r\n                        if (isIncrement) {\r\n                            message += \"  `\"\r\n                                + getUnaryOperatorSymbol(op).toString()\r\n                                + candidate->signature.operandPatterns[0]->toString()\r\n                                + \"`\";\r\n                        } else {\r\n                            message += \"  `\"\r\n                                + candidate->signature.operandPatterns[0]->toString()\r\n                                + \" = \"\r\n                                + getUnaryOperatorSymbol(op).toString()\r\n                                + candidate->signature.operandPatterns[0]->toString()\r\n                                + \"`\";\r\n                        }\r\n                        if (candidate->signature.requiredModeFlags != 0) {\r\n                            message += \" (\" + getModeFlagString(candidate->signature.requiredModeFlags) + \")\";\r\n                        }\r\n\r\n                        report->log(message);\r\n\r\n                        break;\r\n                    }\r\n                    case 2: {\r\n                        auto message = \"  `\"\r\n                            + candidate->signature.operandPatterns[0]->toString()\r\n                            + \" = \"\r\n                            + getUnaryOperatorSymbol(op).toString()\r\n                            + candidate->signature.operandPatterns[1]->toString()\r\n                            + \"`\";\r\n                        if (candidate->signature.requiredModeFlags != 0) {\r\n                            message += \" (\" + getModeFlagString(candidate->signature.requiredModeFlags) + \")\";\r\n                        }\r\n\r\n                        report->log(message);\r\n                        break;\r\n                    }\r\n                    default: {\r\n                        std::abort();\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        report->error(\"expression must be rewritten some other way\\n\", source->location);\r\n    }\r\n\r\n    void Compiler::raiseEmitBinaryExpressionError(const Expression* dest, BinaryOperatorKind op, const Expression* left, const Expression* right, SourceLocation location) {\r\n        const auto candidates = builtins.findAllInstructionsByType(InstructionType(op));\r\n        report->error(\"could not generate code for \" + getBinaryOperatorName(op).toString(), right->location, ReportErrorFlags::Continued);\r\n\r\n        auto destOperand = createOperandFromExpression(dest, false);\r\n        auto leftOperand = createOperandFromExpression(left, false);\r\n        auto rightOperand = createOperandFromExpression(right, false);\r\n\r\n        if (destOperand == nullptr) {\r\n            report->error(\"could not create an instruction operand for assignment destination of \" + getBinaryOperatorName(op).toString(), location);\r\n            return;\r\n        }\r\n        if (leftOperand == nullptr) {\r\n            report->error(\"could not create an instruction operand for left-hand side of \" + getBinaryOperatorName(op).toString(), location);\r\n            return;\r\n        }\r\n        if (rightOperand == nullptr) {\r\n            report->error(\"could not create an instruction operand for right-hand side of \" + getBinaryOperatorName(op).toString(), location);\r\n            return;\r\n        }\r\n\r\n        if (*destOperand == *leftOperand) {\r\n            auto message = \"got: `\"\r\n                + destOperand->toString()\r\n                + \" \" + getBinaryOperatorSymbol(op).toString() + \"= \"\r\n                + rightOperand->toString()\r\n                + \"`\";\r\n            if (modeFlags != 0) {\r\n                message += \" (\" + getModeFlagString(modeFlags) + \")\";\r\n            }\r\n\r\n            report->error(message, right->location, ReportErrorFlags::Continued);\r\n        } else {\r\n            auto message = \"got: `\"\r\n                + destOperand->toString()\r\n                + \" \" + leftOperand->toString()\r\n                + \" \" + getBinaryOperatorSymbol(op).toString()\r\n                + \" \" + rightOperand->toString()\r\n                + \"`\";\r\n            if (modeFlags != 0) {\r\n                message += \" (\" + getModeFlagString(modeFlags) + \")\";\r\n            }\r\n\r\n            report->error(message, right->location, ReportErrorFlags::Continued);\r\n        }\r\n\r\n        if (candidates.size() > 0) {\r\n            report->error(\"possible options:\", right->location, ReportErrorFlags::Continued);\r\n            for (const auto candidate : candidates) {\r\n                switch (candidate->signature.operandPatterns.size()) {\r\n                    case 2: {\r\n                        auto message = \"  `\"\r\n                            + candidate->signature.operandPatterns[0]->toString()\r\n                            + \" \" + getBinaryOperatorSymbol(op).toString()\r\n                            + \"= \" + candidate->signature.operandPatterns[1]->toString()\r\n                            + \"`\";\r\n                        if (candidate->signature.requiredModeFlags != 0) {\r\n                            message += \" (\" + getModeFlagString(candidate->signature.requiredModeFlags) + \")\";\r\n                        }\r\n\r\n                        report->log(message);\r\n                        break;\r\n                    }\r\n                    case 3: {\r\n                        auto message = \"  `\"\r\n                            + candidate->signature.operandPatterns[0]->toString()\r\n                            + \" = \" + candidate->signature.operandPatterns[1]->toString()\r\n                            + \" \" + getBinaryOperatorSymbol(op).toString()\r\n                            + \" \" + candidate->signature.operandPatterns[2]->toString()\r\n                            + \"`\";\r\n                        if (candidate->signature.requiredModeFlags != 0) {\r\n                            message += \" (\" + getModeFlagString(candidate->signature.requiredModeFlags) + \")\";\r\n                        }\r\n\r\n                        report->log(message);\r\n                        break;\r\n                    }\r\n                    default: {\r\n                        std::abort();\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        report->error(\"expression must be rewritten some other way\\n\", right->location);\r\n    }\r\n\r\n    void Compiler::raiseEmitIntrinsicError(const InstructionType& instructionType, const std::vector<InstructionOperandRoot>& operandRoots, SourceLocation location) {\r\n        std::string intrinsicName;\r\n        bool isLoadIntrinsic = false;\r\n        if (const auto voidIntrinsic = instructionType.tryGet<InstructionType::VoidIntrinsic>()) {\r\n            intrinsicName = voidIntrinsic->definition->name.toString();\r\n        } else if (const auto loadIntrinsic = instructionType.tryGet<InstructionType::LoadIntrinsic>()) {\r\n            intrinsicName = loadIntrinsic->definition->name.toString();\r\n            isLoadIntrinsic = true;\r\n        } else {\r\n            std::abort();\r\n            return;\r\n        }\r\n\r\n        const auto candidates = builtins.findAllInstructionsByType(instructionType);\r\n        report->error(\"could not generate code for intrinsic `\" + intrinsicName + \"`\", location, ReportErrorFlags::Continued);\r\n\r\n        for (std::size_t i = 0; i != operandRoots.size(); ++i) {\r\n            const auto& operand = operandRoots[i].operand;\r\n            if (operand == nullptr) {\r\n                if (isLoadIntrinsic && i == 0) {\r\n                    report->error(\"could not create an instruction operand for assignment destination of instrinsic `\" + intrinsicName + \"`\", location);\r\n                } else {\r\n                    report->error(\"could not create an instruction operand for argument #\" + std::to_string(i - (isLoadIntrinsic ? 1 : 0) + 1) + \" to instrinsic `\" + intrinsicName + \"`\", location);\r\n                }\r\n                return;\r\n            }\r\n        }\r\n\r\n        {\r\n            std::string message = \"got: `\"\r\n                + (isLoadIntrinsic ? operandRoots[0].operand->toString() + \" = \" : \"\")\r\n                + intrinsicName + \"(\";\r\n            bool comma = false;\r\n            for (const auto& argument : operandRoots) {\r\n                if (!isLoadIntrinsic || argument.operand != operandRoots[0].operand) {\r\n                    message += (comma ? \", \" : \"\") + argument.operand->toString();\r\n                    comma = true;\r\n                }\r\n            }\r\n            message += \")`\";\r\n            if (modeFlags != 0) {\r\n                message += \" (\" + getModeFlagString(modeFlags) + \")\";\r\n            }\r\n\r\n            report->error(message, location, ReportErrorFlags::Continued);\r\n        }\r\n\r\n        if (candidates.size() > 0) {\r\n            report->error(\"possible options:\", location, ReportErrorFlags::Continued);\r\n            for (const auto candidate : candidates) {\r\n                std::string message = \"  `\"\r\n                    + (isLoadIntrinsic ? candidate->signature.operandPatterns[0]->toString() + \" = \" : \"\")\r\n                    + intrinsicName + \"(\";\r\n                bool comma = false;\r\n                for (const auto operandPattern : candidate->signature.operandPatterns) {\r\n                    if (!isLoadIntrinsic || operandPattern != candidate->signature.operandPatterns[0]) {\r\n                        message += (comma ? \", \" : \"\") + operandPattern->toString();\r\n                        comma = true;\r\n                    }\r\n                }\r\n                message += \")`\";\r\n                if (candidate->signature.requiredModeFlags != 0) {\r\n                    message += \" (\" + getModeFlagString(candidate->signature.requiredModeFlags) + \")\";\r\n                }\r\n\r\n                report->log(message);\r\n            }\r\n        }\r\n\r\n        report->error(\"expression must be rewritten some other way\\n\", location);\r\n    }\r\n\r\n    bool Compiler::emitAssignmentExpressionIr(const Expression* dest, const Expression* source, SourceLocation location) {\r\n        \/\/ TODO: figure out a more general way to handle nested assigments and increments.\r\n\r\n        if (isLeafExpression(source)) {\r\n            if (isSimpleCast(source)) {\r\n                return emitAssignmentExpressionIr(dest, source->cast.operand.get(), location);\r\n            } \r\n\r\n            if (!emitLoadExpressionIr(dest, source, dest->location)) {\r\n                if (hasNestedAssignment(source)) {\r\n                    auto strippedSource = expressionPool.add(stripNestedAssignment(source));\r\n                    return emitNestedAssignmentIr(source, true, false)\r\n                        && emitAssignmentExpressionIr(dest, strippedSource, location)\r\n                        && emitNestedAssignmentIr(source, false, true);\r\n                } else if (hasNestedAssignment(dest)) {\r\n                    auto strippedDest = expressionPool.add(stripNestedAssignment(dest));\r\n                    return emitNestedAssignmentIr(dest, true, false)\r\n                        && emitAssignmentExpressionIr(strippedDest, source, location)\r\n                        && emitNestedAssignmentIr(dest, false, true);\r\n                } else {\r\n                    raiseEmitLoadError(dest, source, dest->location);\r\n                    return false;\r\n                }\r\n            }\r\n            return true;\r\n        } else if (const auto binaryOperator = source->tryGet<Expression::BinaryOperator>()) {\r\n            const auto left = binaryOperator->left.get();\r\n            const auto right = binaryOperator->right.get();\r\n            const auto op = binaryOperator->op;\r\n            if (op == BinaryOperatorKind::Assignment) {\r\n                if(!emitAssignmentExpressionIr(left, right, left->location)) {\r\n                    return false;\r\n                }\r\n                if (!emitAssignmentExpressionIr(dest, left, dest->location)) {\r\n                    return false;\r\n                }\r\n                return true;\r\n            } else {\r\n                if (emitBinaryExpressionIr(dest, op, left, right, dest->location)) {\r\n                    return true;\r\n                } else {\r\n                    if (!emitAssignmentExpressionIr(dest, left, left->location)) {\r\n                        return false;\r\n                    }\r\n\r\n                    bool tempRequired = true;\r\n\r\n                    if (isLeafExpression(right)) {\r\n                        if (!emitBinaryExpressionIr(dest, op, dest, right, right->location)) {\r\n                            if (hasNestedAssignment(right)) {\r\n                                auto strippedRight = expressionPool.add(stripNestedAssignment(right));\r\n                                if (!emitNestedAssignmentIr(right, true, false)) {\r\n                                    return false;\r\n                                }\r\n                                if (!emitBinaryExpressionIr(dest, op, dest, strippedRight, right->location)) {\r\n                                    raiseEmitBinaryExpressionError(dest, op, dest, strippedRight, right->location);\r\n                                    return false;\r\n                                }\r\n                                if (!emitNestedAssignmentIr(right, false, true)) {\r\n                                    return false;\r\n                                }\r\n                            } else {\r\n                                raiseEmitBinaryExpressionError(dest, op, dest, right, right->location);\r\n                                return false;\r\n                            }\r\n                        }\r\n\r\n                        tempRequired = false;\r\n                    } else if (hasNestedAssignment(right)) {\r\n                        auto strippedRight = expressionPool.add(stripNestedAssignment(right));\r\n                        if (!emitNestedAssignmentIr(right, true, false)) {\r\n                            return false;\r\n                        }\r\n                        if (!emitBinaryExpressionIr(dest, op, dest, strippedRight, right->location)) {\r\n                            raiseEmitBinaryExpressionError(dest, op, dest, strippedRight, right->location);\r\n                            return false;\r\n                        }\r\n                        if (!emitNestedAssignmentIr(right, false, true)) {\r\n                            return false;\r\n                        }\r\n\r\n                        tempRequired = false;\r\n                    }\r\n\r\n                    if ((dest->info->qualifiers & Qualifiers::WriteOnly) != Qualifiers::None) {\r\n                        report->error(getBinaryOperatorName(op).toString() + \" expression cannot be done in-place because destination is `writeonly`, so it would require a temporary\", right->location);\r\n                        return false;\r\n                    }\r\n\r\n                    if (tempRequired) {\r\n                        report->error(getBinaryOperatorName(op).toString() + \" expression would require a temporary\", right->location);\r\n                        return false;\r\n                    } else {\r\n                        return true;\r\n                    }\r\n                }\r\n            }\r\n        } else if (const auto unaryOperator = source->tryGet<Expression::UnaryOperator>()) {\r\n            const auto operand = unaryOperator->operand.get();\r\n            const auto op = unaryOperator->op;\r\n            if (emitUnaryExpressionIr(dest, op, operand, dest->location)) {\r\n                return true;\r\n            } else {\r\n                \/\/ Incrementation of the source must happen on the source operand directly.\r\n                if (isUnaryIncrementOperator(op)) {\r\n                    if (isUnaryPostIncrementOperator(op)) {\r\n                        if (!emitAssignmentExpressionIr(dest, operand, operand->location)) {\r\n                            return false;\r\n                        }\r\n                        if (!emitUnaryExpressionIr(operand, getUnaryPreIncrementEquivalent(op), operand, operand->location)) {\r\n                            raiseEmitUnaryExpressionError(operand, op, operand, operand->location);\r\n                            return false;\r\n                        }\r\n                    } else if (isUnaryPreIncrementOperator(op)) {\r\n                        if (!emitUnaryExpressionIr(operand, op, operand, operand->location)) {\r\n                            raiseEmitUnaryExpressionError(operand, op, operand, operand->location);\r\n                            return false;\r\n                        }\r\n                        if (!emitAssignmentExpressionIr(dest, operand, operand->location)) {\r\n                            raiseEmitUnaryExpressionError(operand, op, operand, operand->location);\r\n                            return false;\r\n                        }\r\n                    }\r\n                \/\/ Other unary operations can have their operand loaded into the destination first and then be computed on the destination.\r\n                } else {\r\n                    if (!emitAssignmentExpressionIr(dest, operand, operand->location)) {\r\n                        return false;\r\n                    }\r\n                    if (!emitUnaryExpressionIr(dest, op, dest, operand->location)) {\r\n                        raiseEmitUnaryExpressionError(dest, op, dest, operand->location);\r\n                        return false;\r\n                    }\r\n                }\r\n\r\n                if ((dest->info->qualifiers & Qualifiers::WriteOnly) != Qualifiers::None) {\r\n                    report->error(getUnaryOperatorName(op).toString() + \" expression cannot be done in-place because destination is `writeonly`, so it would require a temporary\", operand->location);\r\n                    return false;\r\n                }\r\n\r\n                return true;\r\n            }\r\n        } else if (const auto call = source->tryGet<Expression::Call>()) {\r\n            return emitCallExpressionIr(0, call->inlined, false, dest, call->function.get(), call->arguments, location);\r\n        }\r\n\r\n        return false;\r\n    }\r\n\r\n    bool Compiler::emitExpressionStatementIr(const Expression* expression, SourceLocation location) {\r\n        if (const auto binaryOperator = expression->tryGet<Expression::BinaryOperator>()) {\r\n            switch (binaryOperator->op) {\r\n                case BinaryOperatorKind::Assignment: {\r\n                    return emitAssignmentExpressionIr(binaryOperator->left.get(), binaryOperator->right.get(), binaryOperator->left->location);\r\n                }\r\n                default:\r\n                    break;\r\n            }\r\n        } else if (const auto unaryOperator = expression->tryGet<Expression::UnaryOperator>()) {\r\n            const auto operand = unaryOperator->operand.get();\r\n            const auto op = unaryOperator->op;\r\n            switch (op) {\r\n                case UnaryOperatorKind::PreIncrement:\r\n                case UnaryOperatorKind::PostIncrement: {\r\n                    if (!emitUnaryExpressionIr(operand, UnaryOperatorKind::PreIncrement, operand, operand->location)) {\r\n                        raiseEmitUnaryExpressionError(operand, UnaryOperatorKind::PreIncrement, operand, operand->location);\r\n                        return false;\r\n                    }\r\n                    return true;\r\n                }\r\n                case UnaryOperatorKind::PreDecrement:\r\n                case UnaryOperatorKind::PostDecrement: {\r\n                    if (!emitUnaryExpressionIr(operand, UnaryOperatorKind::PreDecrement, operand, operand->location)) {\r\n                        raiseEmitUnaryExpressionError(operand, UnaryOperatorKind::PreDecrement, operand, operand->location);\r\n                    }\r\n                    return true;\r\n                }\r\n                default: break;\r\n            }\r\n        } else if (const auto call = expression->tryGet<Expression::Call>()) {\r\n            return emitCallExpressionIr(0, call->inlined, false, nullptr, call->function.get(), call->arguments, location);\r\n        }\r\n\r\n        report->error(\"expression provided cannot be used as a statement\", location);\r\n        return false;\r\n    }\r\n\r\n    bool Compiler::emitReturnAssignmentIr(std::size_t distanceHint, const TypeExpression* returnType, const Expression* returnValue, SourceLocation location) {\r\n        if (const auto designatedStorageType = returnType->tryGet<TypeExpression::DesignatedStorage>()) {\r\n            const auto holderExpression = designatedStorageType->holder.get();\r\n\r\n            if (const auto call = returnValue->tryGet<Expression::Call>()) {\r\n                return emitCallExpressionIr(distanceHint, call->inlined, true, holderExpression, call->function.get(), call->arguments, location);\r\n            } else {\r\n                return emitAssignmentExpressionIr(holderExpression, returnValue, returnValue->location);\r\n            }\r\n        } else {\r\n            report->error(\"could not generate initializer for return value of type `\" + getTypeName(returnType) + \"`\", location);\r\n            return false;\r\n        }\r\n        return false;\r\n    }\r\n\r\n    std::unique_ptr<PlatformTestAndBranch> Compiler::getTestAndBranch(BinaryOperatorKind op, const Expression* left, const Expression* right, std::size_t distanceHint) const {\r\n        auto innerLeft = left;\r\n        auto innerRight = right;\r\n        while (isSimpleCast(innerLeft)) {\r\n            innerLeft = left->cast.operand.get();\r\n        }\r\n        while (isSimpleCast(innerRight)) {\r\n            innerRight = right->cast.operand.get();\r\n        } \r\n        \r\n        if (const auto commonType = findCompatibleBinaryArithmeticExpressionType(left, right)) {\r\n            const auto definition = tryGetResolvedIdentifierTypeDefinition(commonType);\r\n            return platform->getTestAndBranch(*this, definition, op, innerLeft, innerRight, distanceHint);\r\n        } else if (isBooleanType(left->info->type.get()) && isBooleanType(right->info->type.get())) {\r\n            const auto definition = tryGetResolvedIdentifierTypeDefinition(left->info->type.get());\r\n            return platform->getTestAndBranch(*this, definition, op, innerLeft, innerRight, distanceHint);\r\n        } else {\r\n            return nullptr;\r\n        }\r\n    }\r\n\r\n    bool Compiler::emitBranchIr(std::size_t distanceHint, BranchKind kind, const Expression* destination, const Expression* returnValue, bool negated, const Expression* condition, SourceLocation location) {\r\n        switch (kind) {\r\n            case BranchKind::Continue: {\r\n                if (breakLabel != nullptr) {                    \r\n                    const auto labelReferenceExpresison = expressionPool.add(resolveDefinitionExpression(continueLabel, {}, location));\r\n                    return emitBranchIr(distanceHint, BranchKind::Goto, labelReferenceExpresison, returnValue, negated, condition, location);\r\n                } else {\r\n                    report->error(\"`continue` cannot be used outside of a loop\", location);\r\n                    return false;\r\n                }\r\n            }\r\n            case BranchKind::Break: {\r\n                if (breakLabel != nullptr) {\r\n                    const auto labelReferenceExpresison = expressionPool.add(resolveDefinitionExpression(breakLabel, {}, location));\r\n                    return emitBranchIr(distanceHint, BranchKind::Goto, labelReferenceExpresison, returnValue, negated, condition, location);\r\n                } else {\r\n                    report->error(\"`break` cannot be used outside of a loop\", location);\r\n                    return false;\r\n                }\r\n            }\r\n            case BranchKind::Return: {\r\n                if (currentFunction != nullptr) {\r\n                    const auto& funcDefinition = currentFunction->func;\r\n                    const auto returnType = funcDefinition.resolvedSignatureType->function.returnType.get();\r\n                    bool isVoid = isEmptyTupleType(returnType);\r\n                    bool needsIntermediateBranch = false;\r\n\r\n                    if (returnValue != nullptr) {\r\n                        if (condition != nullptr) {\r\n                            needsIntermediateBranch = true;\r\n\r\n                            if (const auto designatedStorageType = returnType->tryGet<TypeExpression::DesignatedStorage>()) {\r\n                                auto destOperand = createOperandFromExpression(designatedStorageType->holder.get(), true);\r\n                                auto sourceOperand = createOperandFromExpression(returnValue, true);\r\n\r\n                                if (destOperand != nullptr && sourceOperand != nullptr && *destOperand == *sourceOperand) {\r\n                                    needsIntermediateBranch = false;\r\n                                }\r\n                            }\r\n                        }\r\n\r\n                        if (isVoid) {\r\n                            if (const auto call = returnValue->tryGet<Expression::Call>()) {\r\n                                return emitCallExpressionIr(distanceHint, call->inlined, true, nullptr, call->function.get(), call->arguments, location);\r\n                            } else {\r\n                                report->error(\"`return` value of `func` returning `()` can only be a function call\", location);\r\n                                return false;\r\n                            }\r\n                        } else if (!needsIntermediateBranch) {\r\n                            if (!emitReturnAssignmentIr(distanceHint, returnType, returnValue, location)) {\r\n                                return false;\r\n                            }\r\n                        }\r\n                    } else if (returnValue == nullptr) {\r\n                        if (!isVoid) {\r\n                            report->error(\"expected `return` value of type `\" + getTypeName(returnType) + \"` but got empty `return;` nstead.\", location);\r\n                            return false;\r\n                        }\r\n                    }\r\n\r\n                    \/\/ If a function has a different return convention use that instead of normal return.\r\n                    const auto returnKind = funcDefinition.returnKind;\r\n\r\n                    if (needsIntermediateBranch) {\r\n                        const auto oldFunction = currentFunction;\r\n                        currentFunction = nullptr;\r\n\r\n                        const auto failureLabelDefinition = createAnonymousLabelDefinition(\"$skip\"_sv);\r\n                        const auto failureReferenceExpression = expressionPool.add(resolveDefinitionExpression(failureLabelDefinition, {}, location));\r\n\r\n                        bool result = emitBranchIr(distanceHint, BranchKind::Goto, failureReferenceExpression, nullptr, !negated, condition, condition->location)\r\n                            && emitReturnAssignmentIr(distanceHint, returnType, returnValue, location)\r\n                            && emitBranchIr(distanceHint, returnKind, nullptr, nullptr, false, nullptr, location);\r\n\r\n                        currentFunction = oldFunction;\r\n                        irNodes.addNew(IrNode::Label(failureLabelDefinition), location);\r\n                        return result;\r\n                    } else if (returnKind != BranchKind::Return) {\r\n                        if (returnLabel != nullptr) {\r\n                            \/\/ inline functions should jump to a \"return label\" instead of actually returning.\r\n                            const auto labelReferenceExpresison = expressionPool.add(resolveDefinitionExpression(returnLabel, {}, location));\r\n                            return emitBranchIr(distanceHint, BranchKind::Goto, labelReferenceExpresison, returnValue, negated, condition, location);\r\n                        } else {\r\n                            return emitBranchIr(distanceHint, returnKind, nullptr, returnValue, negated, condition, location);\r\n                        }\r\n                    }\r\n                }\r\n                break;\r\n            }\r\n            case BranchKind::None: return true;\r\n            default: break;\r\n        }\r\n\r\n        if (destination) {\r\n            if (destination->info->type->kind != TypeExpressionKind::Function) {\r\n                report->error(\"branch destination must be a label or function, but got expression of type `\" + getTypeName(destination->info->type.get()) + \"`\", destination->location);\r\n                return false;\r\n            }\r\n        }\r\n\r\n        if (condition) {\r\n            if (!isBooleanType(condition->info->type.get())) {\r\n                report->error(\"branch conditional must be a boolean expression, but got expression of type `\" + getTypeName(condition->info->type.get()) + \"`\", condition->location);\r\n                return false;\r\n            }\r\n\r\n            if (const auto unaryOperator = condition->tryGet<Expression::UnaryOperator>()) {\r\n                const auto op = unaryOperator->op;\r\n                if (op == UnaryOperatorKind::LogicalNegation) {\r\n                    return emitBranchIr(distanceHint, kind, destination, returnValue, !negated, unaryOperator->operand.get(), condition->location);\r\n                } else {\r\n                    report->error(getUnaryOperatorName(op).toString() + \" operator is not allowed in conditional\", condition->location);\r\n                }\r\n            } else if (const auto binaryOperator = condition->tryGet<Expression::BinaryOperator>()) {\r\n                const auto preNegated = negated && getBinaryOperatorLogicalNegation(binaryOperator->op) != BinaryOperatorKind::None;\r\n                const auto op = preNegated ? getBinaryOperatorLogicalNegation(binaryOperator->op) : binaryOperator->op;\r\n                const auto left = binaryOperator->left.get();\r\n                const auto right = binaryOperator->right.get();\r\n\r\n                auto testAndBranch = getTestAndBranch(op, left, right, distanceHint);\r\n\r\n                \/\/ If failed to find a test-and-branch, try \"flipping\" the comparison.\r\n                \/\/ a == b -> b == a, a < b -> b > a, a <= b -> b >= a.\r\n                if (testAndBranch == nullptr) {\r\n                    switch (op) {\r\n                        case BinaryOperatorKind::Equal:\r\n                        case BinaryOperatorKind::NotEqual:\r\n                        {\r\n                            testAndBranch = getTestAndBranch(op, right, left, distanceHint);\r\n                            break;\r\n                        }\r\n                        case BinaryOperatorKind::LessThan:\r\n                        case BinaryOperatorKind::GreaterThan:\r\n                        {\r\n                            testAndBranch = getTestAndBranch(op == BinaryOperatorKind::LessThan ? BinaryOperatorKind::GreaterThan : BinaryOperatorKind::LessThan, right, left, distanceHint);\r\n                            break;\r\n                        }\r\n                        case BinaryOperatorKind::LessThanOrEqual:\r\n                        case BinaryOperatorKind::GreaterThanOrEqual:\r\n                        {\r\n                            testAndBranch = getTestAndBranch(op == BinaryOperatorKind::LessThanOrEqual ? BinaryOperatorKind::GreaterThanOrEqual : BinaryOperatorKind::LessThanOrEqual, right, left, distanceHint);\r\n                            break;\r\n                        }\r\n                        default: break;\r\n                    }\r\n                }\r\n\r\n                if (testAndBranch != nullptr) {\r\n                    std::vector<InstructionOperandRoot> operandRoots;\r\n                    operandRoots.reserve(testAndBranch->testOperands.size() + (testAndBranch->branches.size() == 0 ? 1 : 0));\r\n\r\n                    for (const auto testOperand : testAndBranch->testOperands) {\r\n                        auto operand = createOperandFromExpression(testOperand, true);\r\n                        operandRoots.push_back(InstructionOperandRoot(testOperand, std::move(operand)));\r\n                    }\r\n\r\n                    if (testAndBranch->branches.size() == 0) {\r\n                        if (kind == BranchKind::Goto || kind == BranchKind::FarGoto) {\r\n                            if (destination != nullptr) {\r\n                                auto operand = createOperandFromExpression(destination, true);\r\n                                if (!operand) {\r\n                                    return false;\r\n                                }\r\n\r\n                                operandRoots.push_back(InstructionOperandRoot(destination, std::move(operand)));\r\n                            }\r\n\r\n                            if (const auto instruction = builtins.selectInstruction(testAndBranch->testInstructionType, modeFlags, operandRoots)) {\r\n                                irNodes.addNew(IrNode::Code(instruction, std::move(operandRoots)), location);\r\n                                return true;\r\n                            }\r\n                        }\r\n\r\n                        return false;\r\n                    } else {\r\n                        if (const auto testInstruction = builtins.selectInstruction(testAndBranch->testInstructionType, modeFlags, operandRoots)) {\r\n                            irNodes.addNew(IrNode::Code(testInstruction, std::move(operandRoots)), location);\r\n                        } else {\r\n                            return false;\r\n                        }\r\n\r\n                        const auto failureLabelDefinition = createAnonymousLabelDefinition(\"$skip\"_sv);\r\n                        const auto failureReferenceExpression = expressionPool.add(resolveDefinitionExpression(failureLabelDefinition, {}, location));\r\n\r\n                        for (const auto& branch : testAndBranch->branches) {\r\n                            const auto flagReferenceExpression = expressionPool.add(resolveDefinitionExpression(branch.flag, {}, condition->location));\r\n\r\n                            if (!emitBranchIr(distanceHint, kind, branch.success ? destination : failureReferenceExpression, returnValue, (preNegated ? !negated : negated) ? branch.value : !branch.value, flagReferenceExpression, condition->location)) {\r\n                                return false;\r\n                            }\r\n                        }\r\n\r\n                        irNodes.addNew(IrNode::Label(failureLabelDefinition), location);\r\n                        return true;\r\n                    }\r\n                }\r\n\r\n                switch (op) {\r\n                    case BinaryOperatorKind::LogicalAnd: {\r\n                        if (!negated) {\r\n                            const auto failureLabelDefinition = createAnonymousLabelDefinition(\"$skip\"_sv);\r\n                            const auto failureLabelReferenceExpression = expressionPool.add(resolveDefinitionExpression(failureLabelDefinition, {}, condition->location));\r\n\r\n                            if (!emitBranchIr(distanceHint, kind, failureLabelReferenceExpression, returnValue, true, binaryOperator->left.get(), condition->location)\r\n                            || !emitBranchIr(distanceHint, kind, destination, returnValue, false, binaryOperator->right.get(), condition->location)) {\r\n                                return false;\r\n                            }\r\n\r\n                            irNodes.addNew(IrNode::Label(failureLabelDefinition), location);\r\n                            return true;\r\n                        } else {\r\n                            return emitBranchIr(distanceHint, kind, destination, returnValue, true, binaryOperator->left.get(), condition->location)\r\n                            && emitBranchIr(distanceHint, kind, destination, returnValue, true, binaryOperator->right.get(), condition->location);\r\n                        }\r\n                    }\r\n                    case BinaryOperatorKind::LogicalOr: {\r\n                        if (!negated) {\r\n                            return emitBranchIr(distanceHint, kind, destination, returnValue, false, binaryOperator->left.get(), condition->location)\r\n                            && emitBranchIr(distanceHint, kind, destination, returnValue, false, binaryOperator->right.get(), condition->location);\r\n                        } else {\r\n                            const auto failureLabelDefinition = createAnonymousLabelDefinition(\"$skip\"_sv);                        \r\n                            const auto failureLabelReferenceExpression = expressionPool.add(resolveDefinitionExpression(failureLabelDefinition, {}, condition->location));\r\n\r\n                            if (!emitBranchIr(distanceHint, kind, failureLabelReferenceExpression, returnValue, false, binaryOperator->left.get(), condition->location)\r\n                            || !emitBranchIr(distanceHint, kind, destination, returnValue, true, binaryOperator->right.get(), condition->location)) {\r\n                                return false;\r\n                            }\r\n\r\n                            irNodes.addNew(IrNode::Label(failureLabelDefinition), location);\r\n                            return true;\r\n                        }\r\n                    }\r\n                    default: {\r\n                        const auto failingOperator = negated ? getBinaryOperatorLogicalNegation(op) : op;\r\n                        report->error(getBinaryOperatorName(failingOperator).toString() + \" operator is not allowed in conditional\", condition->location);\r\n                    }\r\n                }\r\n            } else if (const auto booleanLiteral = condition->tryGet<Expression::BooleanLiteral>()) {\r\n                if (booleanLiteral->value != negated) {\r\n                    return emitBranchIr(distanceHint, kind, destination, returnValue, false, nullptr, condition->location);\r\n                } else {\r\n                    \/\/ condition is known to be false, no branch generated.\r\n                    return true;\r\n                }\r\n            } else if (const auto resolvedIdentifier = condition->tryGet<Expression::ResolvedIdentifier>()) {\r\n                if (const auto builtinRegister = resolvedIdentifier->definition->tryGet<Definition::BuiltinRegister>()) {\r\n                    static_cast<void>(builtinRegister);\r\n                    \r\n                    std::vector<InstructionOperandRoot> operandRoots;\r\n                    operandRoots.reserve((destination != nullptr ? 1 : 0) + 3);\r\n\r\n                    operandRoots.push_back(InstructionOperandRoot(nullptr, makeFwdUnique<InstructionOperand>(InstructionOperand::Integer(Int128(distanceHint)))));\r\n\r\n                    if (destination != nullptr) {\r\n                        auto operand = createOperandFromExpression(destination, true);\r\n                        if (!operand) {\r\n                            return false;\r\n                        }\r\n\r\n                        operandRoots.push_back(InstructionOperandRoot(destination, std::move(operand)));\r\n                    }\r\n\r\n                    operandRoots.push_back(InstructionOperandRoot(nullptr, makeFwdUnique<InstructionOperand>(InstructionOperand::Register(resolvedIdentifier->definition))));\r\n                    operandRoots.push_back(InstructionOperandRoot(nullptr, makeFwdUnique<InstructionOperand>(InstructionOperand::Boolean(!negated))));                    \r\n\r\n                    if (const auto instruction = builtins.selectInstruction(InstructionType(kind), modeFlags, operandRoots)) {\r\n                        irNodes.addNew(IrNode::Code(instruction, std::move(operandRoots)), location);\r\n                        return true;\r\n                    } else {\r\n                        \/\/ If that fails, try to branch-on-opposite around a return.\r\n                        const auto oldFunction = currentFunction;\r\n                        currentFunction = nullptr;\r\n\r\n                        const auto failureLabelDefinition = createAnonymousLabelDefinition(\"$skip\"_sv);\r\n                        const auto failureReferenceExpression = expressionPool.add(resolveDefinitionExpression(failureLabelDefinition, {}, location));\r\n\r\n                        bool result = emitBranchIr(distanceHint, BranchKind::Goto, failureReferenceExpression, nullptr, !negated, condition, condition->location)\r\n                            && emitBranchIr(distanceHint, kind, nullptr, nullptr, false, nullptr, location);\r\n\r\n                        currentFunction = oldFunction;\r\n\r\n                        if (result) {\r\n                            irNodes.addNew(IrNode::Label(failureLabelDefinition), location);\r\n                            return true;\r\n                        }\r\n\r\n                        return false;\r\n                    }\r\n                } else {\r\n                    report->error(\"`\" + getResolvedIdentifierName(resolvedIdentifier->definition, resolvedIdentifier->pieces) + \"` cannot be used as conditional term\", condition->location);\r\n                    return false;\r\n                }\r\n            } else if (const auto sideEffect = condition->tryGet<Expression::SideEffect>()) {\r\n                return emitStatementIr(sideEffect->statement.get())\r\n                    && emitBranchIr(distanceHint, kind, destination, returnValue, negated, sideEffect->result.get(), location);\r\n            }\r\n        } else {\r\n            std::vector<InstructionOperandRoot> operandRoots;\r\n            operandRoots.reserve((destination != nullptr ? 1 : 0) + 1);\r\n\r\n            operandRoots.push_back(InstructionOperandRoot(nullptr, makeFwdUnique<InstructionOperand>(InstructionOperand::Integer(Int128(distanceHint)))));\r\n\r\n            if (destination != nullptr) {\r\n                auto operand = createOperandFromExpression(destination, true);\r\n                if (!operand) {\r\n                    return false;\r\n                }\r\n\r\n                operandRoots.push_back(InstructionOperandRoot(destination, std::move(operand)));\r\n\r\n                if ((destination->info->qualifiers & Qualifiers::Far) != Qualifiers::None) {\r\n                    switch (kind) {\r\n                        case BranchKind::Goto: kind = BranchKind::FarGoto; break;\r\n                        case BranchKind::Call: kind = BranchKind::FarCall; break;\r\n                        default: break;\r\n                    }\r\n                }\r\n            }\r\n\r\n            if (const auto instruction = builtins.selectInstruction(InstructionType(kind), modeFlags, operandRoots)) {\r\n                irNodes.addNew(IrNode::Code(instruction, std::move(operandRoots)), location);\r\n                return true;\r\n            } else {\r\n                return false;\r\n            }\r\n        }\r\n\r\n        return false;\r\n    }\r\n\r\n    bool Compiler::hasUnconditionalReturn(const Statement* statement) const {\r\n        switch (statement->kind) {\r\n            case StatementKind::Block: {\r\n                const auto& block = statement->block;\r\n                const auto& items = block.items;\r\n                return items.size() != 0 && hasUnconditionalReturn(items.back().get());\r\n            }\r\n            case StatementKind::Branch: {\r\n                const auto& branch = statement->branch;\r\n                switch (branch.kind) {\r\n                    case BranchKind::Goto:\r\n                    case BranchKind::FarGoto:\r\n                    case BranchKind::Return:\r\n                    case BranchKind::IrqReturn:\r\n                    case BranchKind::NmiReturn:\r\n                    case BranchKind::FarReturn:\r\n                        return branch.condition == nullptr;\r\n                    default: return false;\r\n                }\r\n            }\r\n            case StatementKind::If: {\r\n                const auto& if_ = statement->if_;\r\n                return if_.body != nullptr\r\n                && if_.alternative != nullptr\r\n                && hasUnconditionalReturn(if_.body.get())\r\n                && hasUnconditionalReturn(if_.alternative.get());\r\n            }\r\n            default: return false;\r\n        }\r\n    }\r\n\r\n    bool Compiler::emitFunctionIr(Definition* definition, SourceLocation location) {\r\n        auto& funcDefinition = definition->func;\r\n\r\n        const auto oldFunction = currentFunction;\r\n        const auto oldReturnLabel = returnLabel;\r\n        const auto onExit = makeScopeGuard([&]() {\r\n            currentFunction = oldFunction;\r\n            returnLabel = oldReturnLabel;\r\n        });        \r\n\r\n        currentFunction = definition;\r\n        const auto returnKind = funcDefinition.returnKind;\r\n        const auto returnType = funcDefinition.resolvedSignatureType->function.returnType.get();\r\n\r\n        returnLabel = nullptr;\r\n        if (returnKind == BranchKind::None) {\r\n            returnLabel = createAnonymousLabelDefinition(\"$ret\"_sv);\r\n        }\r\n\r\n        if (!funcDefinition.inlined) {\r\n            irNodes.addNew(IrNode::Label(currentFunction), location);\r\n        }\r\n\r\n        funcDefinition.hasUnconditionalReturn = funcDefinition.hasUnconditionalReturn || hasUnconditionalReturn(funcDefinition.body);\r\n\r\n        if (!emitStatementIr(funcDefinition.body)) {\r\n            return false;\r\n        }\r\n\r\n        \/\/ TODO: omit trailing return if the function is determined to never reach the return statement (nothing breaks the loop)\r\n        \/\/ TODO: error if there is no return at end of non-void func unless it is marked #[fallthrough] (and we determined an implicit return would have been needed)\r\n\r\n        if (!funcDefinition.hasUnconditionalReturn && !isEmptyTupleType(returnType)) {\r\n            report->error(\"`\" + definition->name.toString() + \"` is missing return value of type `\" + getTypeName(returnType) + \"`\", location);\r\n        }\r\n\r\n        if (!funcDefinition.fallthrough && returnKind != BranchKind::None && isEmptyTupleType(returnType) && !funcDefinition.hasUnconditionalReturn) {\r\n            if (!emitBranchIr(0, returnKind, nullptr, nullptr, false, nullptr, location)) {\r\n                report->error(\"could not generate return instruction for \" + definition->declaration->getDescription().toString(), location);\r\n                return false;\r\n            }\r\n        }\r\n\r\n        if (returnLabel != nullptr) {\r\n            irNodes.addNew(IrNode::Label(returnLabel), location);\r\n        }\r\n\r\n        return true;\r\n    }\r\n\r\n    bool Compiler::emitStatementIr(const Statement* statement) {\r\n        switch (statement->kind) {\r\n            case StatementKind::Attribution: {\r\n                const auto& attributedStatement = statement->attribution;\r\n                pushAttributeList(statementAttributeLists[statement]);\r\n                if (checkConditionalCompilationAttributes()) {\r\n                    emitStatementIr(attributedStatement.body.get());\r\n                }\r\n                popAttributeList();\r\n                break;\r\n            }\r\n            case StatementKind::Bank: break;\r\n            case StatementKind::Block: {\r\n                const auto& blockStatement = statement->block;\r\n                enterScope(getOrCreateStatementScope(StringView(), statement, currentScope));\r\n                for (const auto& item : blockStatement.items) {\r\n                    emitStatementIr(item.get());\r\n                }\r\n                exitScope();\r\n                break;\r\n            }\r\n            case StatementKind::Config: {\r\n                const auto& configStatement = statement->config;\r\n                for (const auto& item : configStatement.items) {\r\n                    if (auto reducedValue = reduceExpression(item->value.get())) {\r\n                        config->add(report, item->name, std::move(reducedValue));\r\n                    }\r\n                }\r\n                break;\r\n            }\r\n            case StatementKind::DoWhile: {\r\n                const auto& doWhileStatement = statement->doWhile;\r\n                if (currentBank == nullptr) {\r\n                    report->error(statement->getDescription().toString() + \" must be inside an `in` statement\", statement->location);\r\n                    break;\r\n                }\r\n\r\n                const auto oldContinueLabel = continueLabel;\r\n                const auto oldBreakLabel = breakLabel;\r\n                const auto onExit = makeScopeGuard([&]() {\r\n                    continueLabel = oldContinueLabel;\r\n                    breakLabel = oldBreakLabel;\r\n                });\r\n\r\n                const auto reducedCondition = expressionPool.add(reduceExpression(doWhileStatement.condition.get()));\r\n                if (!reducedCondition) {\r\n                    break;\r\n                }\r\n\r\n                const auto beginLabelDefinition = createAnonymousLabelDefinition(\"$loop\"_sv);                \r\n                const auto beginLabelReferenceExpression = expressionPool.add(resolveDefinitionExpression(beginLabelDefinition, {}, statement->location));\r\n                const auto continueLabelDefinition = createAnonymousLabelDefinition(\"$continue\"_sv);\r\n                const auto endLabelDefinition = createAnonymousLabelDefinition(\"$endloop\"_sv);\r\n\r\n                continueLabel = continueLabelDefinition;\r\n                breakLabel = endLabelDefinition;\r\n\r\n                irNodes.addNew(IrNode::Label(beginLabelDefinition), statement->location);\r\n                emitStatementIr(doWhileStatement.body.get());\r\n                irNodes.addNew(IrNode::Label(continueLabelDefinition), reducedCondition->location);\r\n                if (!emitBranchIr(doWhileStatement.distanceHint, BranchKind::Goto, beginLabelReferenceExpression, nullptr, false, reducedCondition, reducedCondition->location)) {\r\n                    report->error(\"could not generate branch instruction for \" + statement->getDescription().toString(), statement->location);\r\n                    break;\r\n                }\r\n                irNodes.addNew(IrNode::Label(endLabelDefinition), reducedCondition->location);\r\n                break;\r\n            }\r\n            case StatementKind::Enum: break;\r\n            case StatementKind::ExpressionStatement: {\r\n                const auto& expressionStatement = statement->expressionStatement;\r\n                if (currentBank == nullptr) {\r\n                    report->error(statement->getDescription().toString() + \" must be inside an `in` statement\", statement->location);\r\n                    break;\r\n                }\r\n\r\n                auto reducedExpression = expressionPool.add(reduceExpression(expressionStatement.expression.get()));\r\n                if (!reducedExpression) {\r\n                    break;\r\n                }\r\n\r\n                if (!emitExpressionStatementIr(reducedExpression, reducedExpression->location)) {\r\n                    report->error(\"could not generate code for statement\", statement->location);\r\n                }\r\n                break;\r\n            }\r\n            case StatementKind::File: {\r\n                const auto& file = statement->file;\r\n                enterScope(findStatementScope(statement));\r\n                for (const auto& item : file.items) {\r\n                    emitStatementIr(item.get());\r\n                }\r\n                exitScope();\r\n                break;\r\n            }\r\n            case StatementKind::For: {\r\n                const auto& forStatement = statement->for_;\r\n                if (currentBank == nullptr) {\r\n                    report->error(statement->getDescription().toString() + \" must be inside an `in` statement\", statement->location);\r\n                    break;\r\n                }\r\n\r\n                const auto oldContinueLabel = continueLabel;\r\n                const auto oldBreakLabel = breakLabel;\r\n                const auto onExit = makeScopeGuard([&]() {\r\n                    continueLabel = oldContinueLabel;\r\n                    breakLabel = oldBreakLabel;\r\n                });\r\n\r\n                const auto reducedCounter = expressionPool.add(reduceExpression(forStatement.counter.get()));\r\n                const auto reducedSequence = expressionPool.add(reduceExpression(forStatement.sequence.get()));\r\n                if (!reducedCounter || !reducedSequence) {\r\n                    break;\r\n                }\r\n                if (reducedSequence->kind != ExpressionKind::RangeLiteral || reducedSequence->info->context == EvaluationContext::RunTime) {\r\n                    report->error(\"`for` loop range must be a compile-time range literal.\", statement->location);\r\n                    break;\r\n                }\r\n\r\n                const auto& rangeLiteral = reducedSequence->tryGet<Expression::RangeLiteral>();\r\n                const auto counterResolvedIdentifierType = reducedCounter->info->type->tryGet<TypeExpression::ResolvedIdentifier>();\r\n                const auto counterBuiltinIntegerType = counterResolvedIdentifierType ? counterResolvedIdentifierType->definition->tryGet<Definition::BuiltinIntegerType>() : nullptr;\r\n                if (!counterBuiltinIntegerType) {\r\n                    report->error(\"`for` loop counter start must be a sized integer type.\", statement->location);\r\n                    break;\r\n                }\r\n\r\n                const auto rangeStart = rangeLiteral->start->tryGet<Expression::IntegerLiteral>();\r\n                const auto rangeEnd = rangeLiteral->end->tryGet<Expression::IntegerLiteral>();\r\n                const auto rangeStep = rangeLiteral->step->tryGet<Expression::IntegerLiteral>();\r\n\r\n                if (!rangeStart) {\r\n                    report->error(\"`for` loop range start must be a compile-time integer literal.\", statement->location);\r\n                    break;\r\n                }\r\n                if (!rangeEnd) {\r\n                    report->error(\"`for` loop range end must be a compile-time integer literal.\", statement->location);\r\n                    break;\r\n                }\r\n                if (!rangeStep) {\r\n                    report->error(\"`for` loop range step must be a compile-time integer literal.\", statement->location);\r\n                    break;\r\n                }\r\n                if (rangeStep->value.isZero()) {\r\n                    report->error(\"`for` loop range step must be non-zero.\", statement->location);\r\n                    break;\r\n                }\r\n                \r\n                const auto beginLabelDefinition = createAnonymousLabelDefinition(\"$loop\"_sv);\r\n                const auto beginLabelReferenceExpression = expressionPool.add(resolveDefinitionExpression(beginLabelDefinition, {}, statement->location));\r\n                const auto continueLabelDefinition = createAnonymousLabelDefinition(\"$continue\"_sv);\r\n                const auto endLabelDefinition = createAnonymousLabelDefinition(\"$endloop\"_sv);\r\n\r\n                continueLabel = continueLabelDefinition;\r\n                breakLabel = endLabelDefinition;\r\n\r\n                auto initAssignment = makeFwdUnique<Expression>(\r\n                    Expression::BinaryOperator(BinaryOperatorKind::Assignment, reducedCounter->clone(), rangeLiteral->start->clone()),\r\n                    reducedCounter->location,\r\n                    Optional<ExpressionInfo>());\r\n                auto reducedInitAssignment = expressionPool.add(reduceExpression(initAssignment.get()));\r\n\r\n                bool conditionNegated = false;\r\n                const Expression* reducedCondition = nullptr;\r\n\r\n                const Instruction* incrementInstruction = nullptr;               \r\n                std::vector<InstructionOperandRoot> incrementOperandRoots;\r\n\r\n                if (rangeStep->value == Int128(1) || rangeStep->value == Int128(-1)) {\r\n                    if (auto destOperand = createOperandFromExpression(reducedCounter, true)) {\r\n                        const auto op = rangeStep->value.isPositive() ? UnaryOperatorKind::PreIncrement : UnaryOperatorKind::PreDecrement; \r\n                        incrementOperandRoots.reserve(1);\r\n                        incrementOperandRoots.push_back(InstructionOperandRoot(reducedCounter, std::move(destOperand)));\r\n                        incrementInstruction = builtins.selectInstruction(InstructionType(op), modeFlags, incrementOperandRoots);\r\n                    }\r\n\r\n                    if (incrementInstruction) {\r\n                        if ((rangeStep->value.isPositive() && rangeStart->value > rangeEnd->value)\r\n                        || (rangeStep->value.isNegative() && rangeStart->value < rangeEnd->value)) {\r\n                            break;\r\n                        }\r\n\r\n                        if ((rangeStep->value.isPositive() && rangeEnd->value == counterBuiltinIntegerType->max)\r\n                        || (rangeStep->value.isNegative() && rangeEnd->value == Int128(1))) {\r\n                            if (const auto zeroFlag = platform->getZeroFlag()) {\r\n                                const auto& affectedFlags = incrementInstruction->options.affectedFlags;\r\n                                if (std::find(affectedFlags.begin(), affectedFlags.end(), zeroFlag) != affectedFlags.end()) {\r\n                                    conditionNegated = true;\r\n                                    reducedCondition = expressionPool.add(resolveDefinitionExpression(zeroFlag, {}, statement->location));\r\n                                }\r\n                            }\r\n                            if (!reducedCondition) {\r\n                                auto comparisonValue = makeFwdUnique<Expression>(\r\n                                    Expression::IntegerLiteral(Int128(0)),\r\n                                    reducedSequence->location,\r\n                                    ExpressionInfo(EvaluationContext::CompileTime,\r\n                                        makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), reducedSequence->location),\r\n                                        Qualifiers::None));\r\n                                auto condition = makeFwdUnique<Expression>(Expression::BinaryOperator(BinaryOperatorKind::NotEqual, reducedCounter->clone(), std::move(comparisonValue)), reducedCounter->location, Optional<ExpressionInfo>());\r\n                                reducedCondition = expressionPool.add(reduceExpression(condition.get()));\r\n                            }\r\n                        } else if (rangeEnd->value >= Int128(0) && rangeEnd->value <= counterBuiltinIntegerType->max) {\r\n                            auto comparisonValue = makeFwdUnique<Expression>(\r\n                                Expression::IntegerLiteral(rangeEnd->value + rangeStep->value),\r\n                                reducedSequence->location,\r\n                                ExpressionInfo(EvaluationContext::CompileTime,\r\n                                    makeFwdUnique<const TypeExpression>(TypeExpression::ResolvedIdentifier(builtins.getDefinition(Builtins::DefinitionType::IExpr)), reducedSequence->location),\r\n                                    Qualifiers::None));\r\n                            auto condition = makeFwdUnique<Expression>(Expression::BinaryOperator(BinaryOperatorKind::NotEqual, reducedCounter->clone(), std::move(comparisonValue)), reducedCounter->location, Optional<ExpressionInfo>());\r\n                            reducedCondition = expressionPool.add(reduceExpression(condition.get()));\r\n                        }\r\n                    }\r\n                }\r\n\r\n                if (!reducedCondition) {\r\n                    report->error(\"`for` loop range of `\" + rangeStart->value.toString()\r\n                        + \"` ..  `\" + rangeEnd->value.toString() + \"`\"\r\n                        + (rangeStep->value != Int128(1)\r\n                            ? \" by `\" + rangeStep->value.toString() + \"`\"\r\n                            : \"\")\r\n                        + \" is not supported.\", reducedSequence->location);\r\n                    break;\r\n                }\r\n\r\n                if (!incrementInstruction) {\r\n                    report->error(\"could not generate increment instruction for \" + statement->getDescription().toString(), statement->location);\r\n                    break;\r\n                }               \r\n\r\n                \/\/ TODO: decrement-and-branch optimization if the instruction exists.\r\n\r\n                if (!emitExpressionStatementIr(reducedInitAssignment, reducedInitAssignment->location)) {\r\n                    report->error(\"could not generate initial assignment instruction for \" + statement->getDescription().toString(), statement->location);\r\n                    break;\r\n                }\r\n                irNodes.addNew(IrNode::Label(beginLabelDefinition), statement->location);\r\n                emitStatementIr(forStatement.body.get());\r\n                irNodes.addNew(IrNode::Label(continueLabelDefinition), reducedCondition->location);\r\n                irNodes.addNew(IrNode::Code(incrementInstruction, std::move(incrementOperandRoots)), reducedCondition->location);\r\n                if (!emitBranchIr(forStatement.distanceHint, BranchKind::Goto, beginLabelReferenceExpression, nullptr, conditionNegated, reducedCondition, reducedCondition->location)) {\r\n                    report->error(\"could not generate branch instruction for \" + statement->getDescription().toString(), statement->location);\r\n                    break;\r\n                }\r\n                irNodes.addNew(IrNode::Label(endLabelDefinition), reducedCondition->location);\r\n                break;\r\n            }\r\n            case StatementKind::Func: {\r\n                const auto& funcDeclaration = statement->func;\r\n                auto definition = currentScope->findLocalMemberDefinition(funcDeclaration.name);\r\n                auto& funcDefinition = definition->func;\r\n\r\n                if (funcDefinition.inlined) {\r\n                    \/\/report->error(\"TODO: `inline func`\", statement->location);\r\n                    break;\r\n                } else {\r\n                    emitFunctionIr(definition, statement->location);\r\n                }\r\n                break;\r\n            }\r\n            case StatementKind::If: {\r\n                const auto& ifStatement = statement->if_;\r\n                if (currentBank == nullptr) {\r\n                    report->error(statement->getDescription().toString() + \" must be inside an `in` statement\", statement->location);\r\n                    break;\r\n                }\r\n\r\n                const auto reducedCondition = expressionPool.add(reduceExpression(ifStatement.condition.get()));\r\n                if (!reducedCondition) {\r\n                    break;\r\n                }\r\n\r\n                if (const auto booleanLiteral = reducedCondition->tryGet<Expression::BooleanLiteral>()) {\r\n                    if (booleanLiteral->value) {\r\n                        emitStatementIr(ifStatement.body.get());\r\n                    } else {\r\n                        if (ifStatement.alternative) {\r\n                            emitStatementIr(ifStatement.alternative.get());\r\n                        }\r\n                    }\r\n\r\n                    break;\r\n                }\r\n\r\n                const auto endLabelDefinition = createAnonymousLabelDefinition(\"$endif\"_sv);\r\n                const auto endLabelReferenceExpression = expressionPool.add(resolveDefinitionExpression(endLabelDefinition, {}, statement->location));\r\n                const auto elseLabelDefinition = createAnonymousLabelDefinition(\"$else\"_sv);\r\n                const auto elseLabelReferenceExpression = expressionPool.add(resolveDefinitionExpression(elseLabelDefinition, {}, statement->location));\r\n\r\n                if (!emitBranchIr(ifStatement.distanceHint, BranchKind::Goto, elseLabelReferenceExpression, nullptr, true, reducedCondition, statement->location)) {\r\n                    report->error(\"could not generate branch instruction for \" + statement->getDescription().toString(), statement->location);\r\n                    break;\r\n                }\r\n\r\n                emitStatementIr(ifStatement.body.get());\r\n                if (ifStatement.alternative) {\r\n                    if (!emitBranchIr(ifStatement.distanceHint, BranchKind::Goto, endLabelReferenceExpression, nullptr, false, nullptr, statement->location)) {\r\n                        report->error(\"could not generate branch instruction for \" + statement->getDescription().toString(), statement->location);\r\n                        break;\r\n                    }\r\n                    irNodes.addNew(IrNode::Label(elseLabelDefinition), statement->location);\r\n                    emitStatementIr(ifStatement.alternative.get());\r\n                } else {\r\n                    irNodes.addNew(IrNode::Label(elseLabelDefinition), statement->location);\r\n                }\r\n                irNodes.addNew(IrNode::Label(endLabelDefinition), statement->location);\r\n                break;\r\n            }\r\n            case StatementKind::In: {\r\n                const auto& inStatement = statement->in;\r\n                bankStack.push_back(currentBank);\r\n\r\n                const auto result = handleInStatement(inStatement.pieces, inStatement.dest.get(), statement->location);\r\n                if (result.first) {\r\n                    irNodes.addNew(IrNode::PushRelocation(currentBank, result.second), statement->location);\r\n                    emitStatementIr(inStatement.body.get());\r\n                    irNodes.addNew(IrNode::PopRelocation(), statement->location);\r\n                }\r\n\r\n                currentBank = bankStack.back();\r\n                bankStack.pop_back();\r\n                break;\r\n            }\r\n            case StatementKind::InlineFor: {\r\n                const auto& inlineForStatement = statement->inlineFor;\r\n                if (currentBank == nullptr) {\r\n                    report->error(statement->getDescription().toString() + \" must be inside an `in` statement\", statement->location);\r\n                    break;\r\n                }\r\n\r\n                const auto oldContinueLabel = continueLabel;\r\n                const auto oldBreakLabel = breakLabel;\r\n                const auto onExit = makeScopeGuard([&]() {\r\n                    continueLabel = oldContinueLabel;\r\n                    breakLabel = oldBreakLabel;\r\n                });\r\n\r\n                auto reducedSequence = reduceExpression(inlineForStatement.sequence.get());\r\n                if (reducedSequence == nullptr) {\r\n                    break;\r\n                }\r\n\r\n                const auto length = tryGetSequenceLiteralLength(reducedSequence.get());\r\n                if (!length.hasValue()) {\r\n                    report->error(\"source for array comprehension must be a valid compile-time sequence\", statement->location);\r\n                    break;\r\n                }\r\n\r\n                enterScope(getOrCreateStatementScope(stringPool->intern(SymbolTable::generateBlockName()), statement, currentScope));\r\n                \r\n                const auto beginLabelDefinition = createAnonymousLabelDefinition(\"$loop\"_sv);\r\n                const auto endLabelDefinition = createAnonymousLabelDefinition(\"$endloop\"_sv);\r\n\r\n                breakLabel = endLabelDefinition;\r\n\r\n                irNodes.addNew(IrNode::Label(beginLabelDefinition), statement->location);\r\n\r\n                for (std::size_t i = 0; i != *length; ++i) {\r\n                    enterInlineSite(registeredInlineSites.addNew());\r\n                    enterScope(getOrCreateStatementScope(stringPool->intern(SymbolTable::generateBlockName()), statement, currentScope));\r\n\r\n                    const auto continueLabelDefinition = createAnonymousLabelDefinition(\"$continue\"_sv);\r\n\r\n                    continueLabel = continueLabelDefinition;\r\n                    const auto body = inlineForStatement.body.get();\r\n\r\n                    bool valid = reserveDefinitions(body) && resolveDefinitionTypes() && reserveStorage(body);\r\n\r\n                    if (valid) {\r\n                        auto tempDeclaration = statementPool.addNew(Statement::InternalDeclaration(), statement->location);\r\n                        auto tempDefinition = currentScope->createDefinition(report, Definition::Let({}, nullptr), inlineForStatement.name, tempDeclaration);\r\n                        auto& tempLetDefinition = tempDefinition->let;\r\n\r\n                        auto sourceItem = getSequenceLiteralItem(reducedSequence.get(), i);\r\n                        tempLetDefinition.expression = sourceItem.get();\r\n\r\n                        valid = emitStatementIr(body);\r\n                    }\r\n\r\n                    irNodes.addNew(IrNode::Label(continueLabelDefinition), statement->location);\r\n\r\n                    exitScope();\r\n                    exitInlineSite();\r\n\r\n                    if (!valid) {\r\n                        break;\r\n                    }\r\n                }\r\n\r\n                irNodes.addNew(IrNode::Label(endLabelDefinition), statement->location);\r\n\r\n                exitScope();\r\n                break;\r\n            }\r\n            case StatementKind::ImportReference: break;\r\n            case StatementKind::InternalDeclaration: break;\r\n            case StatementKind::Branch: {\r\n                const auto& branch = statement->branch;\r\n                if (currentBank == nullptr) {\r\n                    report->error(statement->getDescription().toString() + \" must be inside an `in` statement\", statement->location);\r\n                    break;\r\n                }\r\n\r\n                const Expression* reducedDestination = nullptr;\r\n                if (branch.destination) {\r\n                    reducedDestination = expressionPool.add(reduceExpression(branch.destination.get()));\r\n                    if (!reducedDestination) {\r\n                        break;\r\n                    }\r\n                }\r\n\r\n                const Expression* reducedReturnValue = nullptr;\r\n                if (branch.returnValue) {\r\n                    reducedReturnValue = expressionPool.add(reduceExpression(branch.returnValue.get()));\r\n                    if (!reducedReturnValue) {\r\n                        break;\r\n                    }\r\n                }\r\n\r\n                const Expression* reducedCondition = nullptr;\r\n                if (branch.condition) {\r\n                    reducedCondition = expressionPool.add(reduceExpression(branch.condition.get()));\r\n                    if (!reducedCondition) {\r\n                        break;\r\n                    }\r\n                }            \r\n\r\n                if (!emitBranchIr(branch.distanceHint, branch.kind, reducedDestination, reducedReturnValue, false, reducedCondition, statement->location)) {\r\n                    report->error(\"branch instruction could not be generated\", statement->location);\r\n                }\r\n                break;\r\n            }\r\n            case StatementKind::Label: {\r\n                const auto& labelDeclaration = statement->label;\r\n                if (currentBank == nullptr) {\r\n                    report->error(statement->getDescription().toString() + \" must be inside an `in` statement\", statement->location);\r\n                    break;\r\n                }\r\n\r\n                irNodes.addNew(IrNode::Label(currentScope->findLocalMemberDefinition(labelDeclaration.name)), statement->location);\r\n                break;\r\n            }\r\n            case StatementKind::Let: break;\r\n            case StatementKind::Namespace: {\r\n                const auto& namespaceDeclaration = statement->namespace_;\r\n                enterScope(findStatementScope(namespaceDeclaration.body.get()));\r\n                emitStatementIr(namespaceDeclaration.body.get());\r\n                exitScope();\r\n                break;\r\n            }\r\n            case StatementKind::Struct: break;\r\n            case StatementKind::TypeAlias: break;\r\n            case StatementKind::Var: {\r\n                const auto& varDeclaration = statement->var;\r\n                for (const auto& name : varDeclaration.names) {\r\n                    auto definition = currentScope->findLocalMemberDefinition(name);\r\n                    auto& varDefinition = definition->var;\r\n\r\n                    if ((varDefinition.qualifiers & Qualifiers::Extern) == Qualifiers::None) {\r\n                        if (currentBank == nullptr && varDefinition.addressExpression == nullptr) {\r\n                            report->error(statement->getDescription().toString() + \" must be inside an `in` statement\", statement->location);\r\n                            break;\r\n                        }\r\n\r\n                        if (currentBank != nullptr && isBankKindStored(currentBank->getKind())) {\r\n                            if (varDefinition.resolvedType && varDefinition.resolvedType->kind == TypeExpressionKind::DesignatedStorage && varDefinition.initializerExpression != nullptr) {\r\n                                const auto destExpression = expressionPool.add(resolveDefinitionExpression(definition, {}, statement->location));\r\n                                emitAssignmentExpressionIr(destExpression, varDefinition.initializerExpression.get(), statement->location);\r\n                            } else if (varDefinition.enclosingFunction == nullptr) {\r\n                                irNodes.addNew(IrNode::Var(definition), statement->location);\r\n\r\n                                for (auto& nestedConstant : varDefinition.nestedConstants) {\r\n                                    irNodes.addNew(IrNode::Var(nestedConstant), statement->location);\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n                break;\r\n            }\r\n            case StatementKind::While: {\r\n                const auto& whileStatement = statement->while_;\r\n                if (currentBank == nullptr) {\r\n                    report->error(statement->getDescription().toString() + \" must be inside an `in` statement\", statement->location);\r\n                    break;\r\n                }\r\n\r\n                const auto oldContinueLabel = continueLabel;\r\n                const auto oldBreakLabel = breakLabel;\r\n                const auto onExit = makeScopeGuard([&]() {\r\n                    continueLabel = oldContinueLabel;\r\n                    breakLabel = oldBreakLabel;\r\n                });\r\n\r\n                const auto reducedCondition = expressionPool.add(reduceExpression(whileStatement.condition.get()));\r\n                if (!reducedCondition) {\r\n                    report->error(\"could not generate branch instruction for \" + statement->getDescription().toString(), statement->location);\r\n                    break;\r\n                }\r\n\r\n                const auto beginLabelDefinition = createAnonymousLabelDefinition(\"$loop\"_sv);\r\n                const auto beginLabelReferenceExpression = expressionPool.add(resolveDefinitionExpression(beginLabelDefinition, {}, statement->location));\r\n                const auto endLabelDefinition = createAnonymousLabelDefinition(\"$endloop\"_sv);\r\n                const auto endLabelReferenceExpression = expressionPool.add(resolveDefinitionExpression(endLabelDefinition, {}, statement->location));\r\n\r\n                continueLabel = beginLabelDefinition;\r\n                breakLabel = endLabelDefinition;\r\n\r\n                irNodes.addNew(IrNode::Label(beginLabelDefinition), statement->location);\r\n                if (!emitBranchIr(whileStatement.distanceHint, BranchKind::Goto, endLabelReferenceExpression, nullptr, true, reducedCondition, statement->location)) {\r\n                    break;\r\n                }\r\n                emitStatementIr(whileStatement.body.get());\r\n                if (!emitBranchIr(whileStatement.distanceHint, BranchKind::Goto, beginLabelReferenceExpression, nullptr, false, nullptr, statement->location)) {\r\n                    break;\r\n                }\r\n                irNodes.addNew(IrNode::Label(endLabelDefinition), statement->location);\r\n                break;\r\n            }\r\n            default: std::abort(); return false;\r\n        }\r\n\r\n        return statement == program.get() ? report->validate() : report->alive();\r\n    }\r\n\r\n    bool Compiler::generateCode() {\r\n        for (auto& bank : registeredBanks) {\r\n            bank->rewind();\r\n        }\r\n        \r\n        std::vector<std::vector<const InstructionOperand*>> captureLists;\r\n        std::set<std::size_t> irNodeIndexesToRemove;\r\n\r\n        \/\/ First pass: calculate data\/instruction sizes, assign labels.\r\n        for (std::size_t i = 0; i != irNodes.size(); ++i) {\r\n            const auto& irNode = irNodes[i];\r\n            switch (irNode->kind) {\r\n                case IrNodeKind::PushRelocation: {\r\n                    const auto& pushRelocation = irNode->pushRelocation;\r\n                    bankStack.push_back(currentBank);\r\n                    currentBank = pushRelocation.bank;\r\n\r\n                    if (const auto address = pushRelocation.address.tryGet()) {\r\n                        currentBank->absoluteSeek(report, *address, irNode->location);\r\n                    }\r\n                    break;\r\n                }\r\n                case IrNodeKind::PopRelocation: {\r\n                    currentBank = bankStack.back();\r\n                    bankStack.pop_back();\r\n                    break;\r\n                }\r\n                case IrNodeKind::Label: {\r\n                    const auto& label = irNode->label;\r\n                    auto& funcDefinition = label.definition->func;\r\n                    funcDefinition.address = currentBank->getAddress();                    \r\n                    break;\r\n                }\r\n                case IrNodeKind::Code: {\r\n                    const auto& code = irNode->code;\r\n                    const auto& instruction = code.instruction;\r\n                    if (instruction->signature.extract(code.operandRoots, captureLists)) {\r\n                        bool removed = false;\r\n\r\n                        \/\/ Slight optimization: remove redundant jump if the destination label is immediately after this.\r\n                        \/\/ (Also handle a checking multiple labels when defined with no code between)\r\n                        \/\/ TODO: maybe move this optimization till the very end?\r\n                        \/\/ There's some cases this can't catch, but doing this after addresses are calculated will make for a mess.\r\n                        if (const auto branchKind = instruction->signature.type.tryGet<BranchKind>()) {\r\n                            if (*branchKind == BranchKind::Goto) {\r\n                                const auto& patterns = instruction->signature.operandPatterns;\r\n\r\n                                if (patterns.size() >= 2 && patterns[1]->kind == InstructionOperandPatternKind::IntegerRange) {\r\n                                    if (const auto resolvedIdentifier = code.operandRoots[1].expression->tryGet<Expression::ResolvedIdentifier>()) {\r\n                                        std::size_t nextIndex = i + 1;\r\n\r\n                                        while (nextIndex < irNodes.size()) {\r\n                                            const auto& nextIrNode = irNodes[nextIndex];\r\n                                            if (const auto nextLabel = nextIrNode->tryGet<IrNode::Label>()) {\r\n                                                if (resolvedIdentifier->definition == nextLabel->definition) {\r\n                                                    removed = true;\r\n                                                    break;\r\n                                                }\r\n                                            } else {\r\n                                                break;\r\n                                            }\r\n\r\n                                            nextIndex++;\r\n                                        }\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n\r\n                        if (removed) {\r\n                            irNodeIndexesToRemove.insert(i);\r\n                        } else {\r\n                            const auto size = instruction->encoding->calculateSize(instruction->options, captureLists);\r\n                            currentBank->reserveRom(report, \"code\"_sv, irNode.get(), irNode->location, size);\r\n                        }\r\n                    } else {\r\n                        report->error(\"failed to extract instruction capture list during instruction selection pass\", irNode->location, ReportErrorFlags::InternalError);\r\n                    }\r\n                    break;\r\n                }\r\n                case IrNodeKind::Var: {\r\n                    const auto& var = irNode->var;\r\n                    auto& varDefinition = var.definition->var;\r\n\r\n                    Optional<std::size_t> oldPosition;\r\n                    if (varDefinition.addressExpression != nullptr) {\r\n                        enterScope(var.definition->parentScope);\r\n\r\n                        const auto address = resolveExplicitAddressExpression(varDefinition.addressExpression);\r\n                        if (address.hasValue()) {\r\n                            oldPosition = currentBank->getRelativePosition();\r\n                            currentBank->absoluteSeek(report, address.get(), irNode->location);\r\n                        } else {\r\n                            break;\r\n                        }\r\n\r\n                        exitScope();\r\n                    } else {\r\n                        \/\/ FIXME: natural alignment requirements\r\n                        const auto alignment = varDefinition.alignment != 0 ? varDefinition.alignment : 1;\r\n                        if (alignment > 1) {\r\n                            const auto unalignedAddress = currentBank->getAddress().absolutePosition.get();\r\n                            currentBank->absoluteSeek(report, (unalignedAddress + alignment - 1) \/ alignment * alignment, irNode->location);\r\n                        }\r\n                    }\r\n \r\n                    varDefinition.address = currentBank->getAddress();\r\n \r\n                    if (!currentBank->reserveRom(report, \"constant data\"_sv, irNode.get(), irNode->location, varDefinition.storageSize.get())) {\r\n                        break;\r\n                    }\r\n \r\n                    if (oldPosition.hasValue()) {\r\n                        currentBank->setRelativePosition(oldPosition.get());\r\n                    }\r\n                    break;\r\n                }\r\n                default: std::abort(); return false;\r\n            }\r\n        }\r\n\r\n        for (auto it = irNodeIndexesToRemove.rbegin(); it != irNodeIndexesToRemove.rend(); ++it) {\r\n            irNodes.remove(*it);\r\n        }\r\n\r\n        irNodeIndexesToRemove.clear();\r\n\r\n        if (!report->validate()) {\r\n            return false;\r\n        }\r\n\r\n        for (auto& bank : registeredBanks) {\r\n            bank->rewind();\r\n        }\r\n\r\n        std::vector<std::uint8_t> tempBuffer;\r\n        std::vector<FwdUniquePtr<const Expression>> tempExpressions;\r\n        std::vector<InstructionOperandRoot> tempOperandRoots;\r\n\r\n        \/\/ Second pass: resolve all link-time expressions, write the instructions into the correct banks.\r\n        for (const auto& irNode : irNodes) {\r\n            switch (irNode->kind) {\r\n                case IrNodeKind::PushRelocation: {\r\n                    const auto& pushRelocation = irNode->pushRelocation;\r\n                    bankStack.push_back(currentBank);\r\n                    currentBank = pushRelocation.bank;\r\n\r\n                    if (const auto address = pushRelocation.address.tryGet()) {\r\n                        currentBank->absoluteSeek(report, *address, irNode->location);\r\n                    }\r\n                    break;\r\n                }\r\n                case IrNodeKind::PopRelocation: {\r\n                    currentBank = bankStack.back();\r\n                    bankStack.pop_back();\r\n                    break;\r\n                }\r\n                case IrNodeKind::Label: {\r\n                    const auto& label = irNode->label;\r\n                    Address labelAddress;\r\n\r\n                    auto& funcDefinition = label.definition->func;\r\n                    labelAddress = funcDefinition.address.get();\r\n\r\n                    const auto currentBankAddress = currentBank->getAddress();\r\n                    if (labelAddress != currentBankAddress) {\r\n                        std::string message = \"label `\" + label.definition->name.toString() + \"` was supposed to be at \";\r\n\r\n                        if (labelAddress.absolutePosition.hasValue()) {\r\n                            message += \"absolute address 0x\" + Int128(labelAddress.absolutePosition.get()).toString(16);\r\n                        } else {\r\n                            message += \"relative position \" + std::to_string(labelAddress.relativePosition.get());\r\n                        }\r\n\r\n                        message += \", but bank is at \";\r\n\r\n                        if (currentBankAddress.absolutePosition.hasValue()) {\r\n                            message += \"absolute address 0x\" + Int128(currentBankAddress.absolutePosition.get()).toString(16);\r\n                        } else {\r\n                            message += \"relative position \" + std::to_string(currentBankAddress.relativePosition.get());\r\n                        }\r\n\r\n                        report->error(message, irNode->location, ReportErrorFlags::InternalError);\r\n                    }\r\n                    break;\r\n                }\r\n                case IrNodeKind::Code: {\r\n                    const auto& code = irNode->code;\r\n                    const auto& instruction = code.instruction;\r\n\r\n                    tempOperandRoots.clear();\r\n                    tempExpressions.clear();\r\n\r\n                    bool failed = false;\r\n\r\n                    for (std::size_t i = 0; i != code.operandRoots.size() && !failed; ++i) {\r\n                        const auto& operandRoot = code.operandRoots[i];\r\n                        if (const auto expression = operandRoot.expression) {\r\n                            if (auto reducedExpression = reduceExpression(expression)) {\r\n                                if (auto operand = createOperandFromExpression(reducedExpression.get(), true)) {\r\n                                    tempOperandRoots.push_back(InstructionOperandRoot(reducedExpression.get(), std::move(operand)));\r\n                                    tempExpressions.push_back(std::move(reducedExpression));\r\n                                } else {\r\n                                    report->error(\"failed to create operand for reduced expresion\", irNode->location, ReportErrorFlags::InternalError);\r\n                                    failed = true;\r\n                                    break;\r\n                                }\r\n                            } else {\r\n                                failed = true;\r\n                                break;\r\n                            }\r\n                        } else {\r\n                            tempOperandRoots.push_back(InstructionOperandRoot(nullptr, operandRoot.operand->clone()));\r\n                        }\r\n                    }\r\n\r\n                    if (failed) {\r\n                        break;\r\n                    }\r\n\r\n                    if (instruction->signature.extract(tempOperandRoots, captureLists)) {\r\n                        tempBuffer.clear();\r\n                        instruction->encoding->write(report, currentBank, tempBuffer, instruction->options, captureLists, irNode->location);\r\n                        if (!currentBank->write(report, \"code\"_sv, irNode.get(), irNode->location, tempBuffer)) {\r\n                            break;\r\n                        }\r\n                    } else {\r\n                        report->error(\"failed to extract instruction capture list during generation pass\", irNode->location, ReportErrorFlags::InternalError);\r\n                    }\r\n                    break;\r\n                }\r\n                case IrNodeKind::Var: {\r\n                    const auto& var = irNode->var;\r\n                    auto& varDefinition = var.definition->var;\r\n\r\n                    Optional<std::size_t> oldPosition;\r\n                    if (varDefinition.addressExpression != nullptr) {\r\n                        oldPosition = currentBank->getRelativePosition();\r\n                        currentBank->setRelativePosition(varDefinition.address.get().relativePosition.get());\r\n                    } else {\r\n                        \/\/ FIXME: natural alignment requirements\r\n                        const auto alignment = varDefinition.alignment != 0 ? varDefinition.alignment : 1;\r\n                        if (alignment > 1) {\r\n                            const auto unalignedAddress = currentBank->getAddress().absolutePosition.get();\r\n                            currentBank->absoluteSeek(report, (unalignedAddress + alignment - 1) \/ alignment * alignment, irNode->location);\r\n                        }\r\n                    }\r\n\r\n                    FwdUniquePtr<const Expression> tempExpression;\r\n                    const auto hasInitializer = varDefinition.initializerExpression.get() != nullptr;\r\n                    const Expression* finalInitializerExpression = varDefinition.initializerExpression.get();\r\n                    \r\n                    if (hasInitializer && varDefinition.initializerExpression->info->context == EvaluationContext::LinkTime) {\r\n                        if (auto reducedExpression = reduceExpression(varDefinition.initializerExpression.get())) {\r\n                             tempExpression = createConvertedExpression(reducedExpression.get(), varDefinition.resolvedType);\r\n                             finalInitializerExpression = tempExpression.get();\r\n                        }\r\n                    }\r\n \r\n                    tempBuffer.clear();\r\n                    tempBuffer.reserve(varDefinition.storageSize.get());\r\n\r\n                    if (hasInitializer) {\r\n                        if (!finalInitializerExpression || !serializeConstantInitializer(finalInitializerExpression, tempBuffer)) {\r\n                            report->error(\"constant initializer could not be resolved at link-time\", irNode->location, ReportErrorFlags::Fatal);\r\n                            break;\r\n                        }\r\n                    } else {\r\n                        tempBuffer.resize(varDefinition.storageSize.get());\r\n                    }\r\n\r\n                    if (!currentBank->write(report, \"constant data\"_sv, irNode.get(), irNode->location, tempBuffer)) {\r\n                        break;\r\n                    }\r\n \r\n                    if (oldPosition.hasValue()) {\r\n                        currentBank->setRelativePosition(oldPosition.get());\r\n                    }\r\n                    break;\r\n                }\r\n                default: std::abort(); return false;\r\n            }\r\n        }\r\n\r\n        return report->validate();\r\n    }\r\n}","avg_line_length":58.2326575645,"max_line_length":449,"alphanum_fraction":0.5221541996,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5091,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/\/ Copyright (c) 2017-2020 The aRIA Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <random.h>\n\n#include <test\/util\/setup_common.h>\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <algorithm>\n#include <random>\n\nBOOST_FIXTURE_TEST_SUITE(random_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(osrandom_tests)\n{\n    BOOST_CHECK(Random_SanityCheck());\n}\n\nBOOST_AUTO_TEST_CASE(fastrandom_tests)\n{\n    \/\/ Check that deterministic FastRandomContexts are deterministic\n    g_mock_deterministic_tests = true;\n    FastRandomContext ctx1(true);\n    FastRandomContext ctx2(true);\n\n    for (int i = 10; i > 0; --i) {\n        BOOST_CHECK_EQUAL(GetRand(std::numeric_limits<uint64_t>::max()), uint64_t{10393729187455219830U});\n        BOOST_CHECK_EQUAL(GetRandInt(std::numeric_limits<int>::max()), int{769702006});\n        BOOST_CHECK_EQUAL(GetRandMicros(std::chrono::hours{1}).count(), 2917185654);\n        BOOST_CHECK_EQUAL(GetRandMillis(std::chrono::hours{1}).count(), 2144374);\n    }\n    BOOST_CHECK_EQUAL(ctx1.rand32(), ctx2.rand32());\n    BOOST_CHECK_EQUAL(ctx1.rand32(), ctx2.rand32());\n    BOOST_CHECK_EQUAL(ctx1.rand64(), ctx2.rand64());\n    BOOST_CHECK_EQUAL(ctx1.randbits(3), ctx2.randbits(3));\n    BOOST_CHECK(ctx1.randbytes(17) == ctx2.randbytes(17));\n    BOOST_CHECK(ctx1.rand256() == ctx2.rand256());\n    BOOST_CHECK_EQUAL(ctx1.randbits(7), ctx2.randbits(7));\n    BOOST_CHECK(ctx1.randbytes(128) == ctx2.randbytes(128));\n    BOOST_CHECK_EQUAL(ctx1.rand32(), ctx2.rand32());\n    BOOST_CHECK_EQUAL(ctx1.randbits(3), ctx2.randbits(3));\n    BOOST_CHECK(ctx1.rand256() == ctx2.rand256());\n    BOOST_CHECK(ctx1.randbytes(50) == ctx2.randbytes(50));\n\n    \/\/ Check that a nondeterministic ones are not\n    g_mock_deterministic_tests = false;\n    for (int i = 10; i > 0; --i) {\n        BOOST_CHECK(GetRand(std::numeric_limits<uint64_t>::max()) != uint64_t{10393729187455219830U});\n        BOOST_CHECK(GetRandInt(std::numeric_limits<int>::max()) != int{769702006});\n        BOOST_CHECK(GetRandMicros(std::chrono::hours{1}) != std::chrono::microseconds{2917185654});\n        BOOST_CHECK(GetRandMillis(std::chrono::hours{1}) != std::chrono::milliseconds{2144374});\n    }\n    {\n        FastRandomContext ctx3, ctx4;\n        BOOST_CHECK(ctx3.rand64() != ctx4.rand64()); \/\/ extremely unlikely to be equal\n    }\n    {\n        FastRandomContext ctx3, ctx4;\n        BOOST_CHECK(ctx3.rand256() != ctx4.rand256());\n    }\n    {\n        FastRandomContext ctx3, ctx4;\n        BOOST_CHECK(ctx3.randbytes(7) != ctx4.randbytes(7));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(fastrandom_randbits)\n{\n    FastRandomContext ctx1;\n    FastRandomContext ctx2;\n    for (int bits = 0; bits < 63; ++bits) {\n        for (int j = 0; j < 1000; ++j) {\n            uint64_t rangebits = ctx1.randbits(bits);\n            BOOST_CHECK_EQUAL(rangebits >> bits, 0U);\n            uint64_t range = ((uint64_t)1) << bits | rangebits;\n            uint64_t rand = ctx2.randrange(range);\n            BOOST_CHECK(rand < range);\n        }\n    }\n}\n\n\/** Does-it-compile test for compatibility with standard C++11 RNG interface. *\/\nBOOST_AUTO_TEST_CASE(stdrandom_test)\n{\n    FastRandomContext ctx;\n    std::uniform_int_distribution<int> distribution(3, 9);\n    for (int i = 0; i < 100; ++i) {\n        int x = distribution(ctx);\n        BOOST_CHECK(x >= 3);\n        BOOST_CHECK(x <= 9);\n\n        std::vector<int> test{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n        std::shuffle(test.begin(), test.end(), ctx);\n        for (int j = 1; j <= 10; ++j) {\n            BOOST_CHECK(std::find(test.begin(), test.end(), j) != test.end());\n        }\n        Shuffle(test.begin(), test.end(), ctx);\n        for (int j = 1; j <= 10; ++j) {\n            BOOST_CHECK(std::find(test.begin(), test.end(), j) != test.end());\n        }\n    }\n}\n\n\/** Test that Shuffle reaches every permutation with equal probability. *\/\nBOOST_AUTO_TEST_CASE(shuffle_stat_test)\n{\n    FastRandomContext ctx(true);\n    uint32_t counts[5 * 5 * 5 * 5 * 5] = {0};\n    for (int i = 0; i < 12000; ++i) {\n        int data[5] = {0, 1, 2, 3, 4};\n        Shuffle(std::begin(data), std::end(data), ctx);\n        int pos = data[0] + data[1] * 5 + data[2] * 25 + data[3] * 125 + data[4] * 625;\n        ++counts[pos];\n    }\n    unsigned int sum = 0;\n    double chi_score = 0.0;\n    for (int i = 0; i < 5 * 5 * 5 * 5 * 5; ++i) {\n        int i1 = i % 5, i2 = (i \/ 5) % 5, i3 = (i \/ 25) % 5, i4 = (i \/ 125) % 5, i5 = i \/ 625;\n        uint32_t count = counts[i];\n        if (i1 == i2 || i1 == i3 || i1 == i4 || i1 == i5 || i2 == i3 || i2 == i4 || i2 == i5 || i3 == i4 || i3 == i5 || i4 == i5) {\n            BOOST_CHECK(count == 0);\n        } else {\n            chi_score += ((count - 100.0) * (count - 100.0)) \/ 100.0;\n            BOOST_CHECK(count > 50);\n            BOOST_CHECK(count < 150);\n            sum += count;\n        }\n    }\n    BOOST_CHECK(chi_score > 58.1411); \/\/ 99.9999% confidence interval\n    BOOST_CHECK(chi_score < 210.275);\n    BOOST_CHECK_EQUAL(sum, 12000U);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":37.1605839416,"max_line_length":131,"alphanum_fraction":0.6108819485,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":409,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include <stdio.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \n\/\/\/\tSubstitute & to 0 and && to 1.\n\/\/\/ \n\/\/\/ 0 * 0 = 0\n\/\/\/ 0 * 1 = 0\n\/\/\/ 1 * 0 = 0\n\/\/\/ 1 * 1 = 1\n\/\/\/ \n\/\/\/ So: \n\/\/\/ &  &  = &\n\/\/\/ && &  = &\n\/\/\/ &  && = &\n\/\/\/ && && = &&\n\/\/\/ \n\/\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nint main()\n{\n\n}","avg_line_length":16.36,"max_line_length":94,"alphanum_fraction":0.1295843521,"low_alphanum":true,"long_lines":false,"lexable":true}
{"size":95845,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Intel","ISC"],"max_stars_count":38.0,"content":"#include <nall\/nall.hpp>\n#include \"resource.hpp\"\n\nnamespace Resource {\nnamespace Logo {\nconst nall::vector<uint8_t> higan = {  \/\/size: 25128\n  137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,1,143,0,0,0,95,8,6,0,0,0,16,211,75,\n  124,0,0,0,4,103,65,77,65,0,0,177,143,11,252,97,5,0,0,0,32,99,72,82,77,0,0,122,38,0,0,128,\n  132,0,0,250,0,0,0,128,232,0,0,117,48,0,0,234,96,0,0,58,152,0,0,23,112,156,186,81,60,0,0,0,\n  9,112,72,89,115,0,0,0,90,0,0,0,90,0,112,35,184,125,0,0,0,6,98,75,71,68,0,0,0,0,0,0,\n  249,67,187,127,0,0,96,228,73,68,65,84,120,218,237,93,7,120,83,213,251,198,141,19,183,254,0,5,7,226,222,56,\n  81,25,93,180,64,217,101,149,189,247,146,189,247,30,178,135,128,108,17,68,101,168,32,8,162,184,5,65,69,54,50,75,\n  217,123,181,253,254,239,123,114,110,115,146,38,109,146,155,66,225,159,251,60,223,211,54,77,114,207,61,227,219,223,251,101,\n  203,150,5,174,112,80,68,182,108,215,128,238,4,189,0,42,15,234,4,154,134,255,173,10,203,150,109,19,40,177,104,182,\n  108,167,65,23,65,201,160,36,208,121,188,126,28,180,7,239,91,11,90,130,207,124,0,106,12,10,7,229,5,221,84,12,\n  223,31,150,45,116,133,174,208,21,186,66,215,21,125,129,233,103,139,116,8,140,155,64,79,128,170,130,70,131,193,127,143,\n  255,237,5,157,133,32,72,41,118,221,117,82,234,150,91,164,226,221,119,75,141,92,185,164,193,163,143,74,147,252,249,165,\n  233,147,79,42,106,148,47,159,212,205,147,71,226,31,120,64,202,231,200,33,37,110,186,73,34,175,185,70,194,28,130,133,\n  66,101,19,190,231,115,124,119,23,80,81,208,253,90,72,133,174,208,21,186,66,87,232,186,82,174,8,7,93,7,122,12,\n  84,23,140,253,83,90,13,180,34,40,40,42,221,115,143,180,122,238,57,25,30,19,35,243,26,52,144,239,123,244,144,141,\n  163,70,201,238,143,62,146,67,31,127,44,199,23,44,144,83,95,124,33,167,23,46,84,116,242,243,207,229,232,252,249,114,\n  96,214,44,217,49,105,146,172,27,50,68,150,181,107,39,31,197,199,75,175,119,223,149,122,143,60,34,165,111,189,85,34,\n  32,80,104,181,224,94,127,226,190,195,65,145,180,114,250,104,171,39,116,133,174,208,21,186,66,87,22,187,34,157,66,227,\n  22,80,17,208,120,48,241,29,160,228,146,217,179,43,235,97,108,217,178,242,125,247,238,178,123,234,84,57,179,104,145,164,\n  44,95,46,178,114,165,131,190,253,214,65,43,86,164,79,124,143,241,153,164,165,75,229,24,4,11,133,207,23,205,154,73,\n  79,8,147,42,247,223,47,145,215,94,171,4,9,132,198,15,24,75,27,208,227,160,107,67,214,72,232,10,93,161,43,116,\n  101,129,171,136,83,104,220,6,42,5,102,189,16,76,251,68,20,44,140,218,15,63,44,227,32,48,254,24,52,72,78,124,\n  246,153,164,124,243,141,92,252,250,107,87,161,65,129,192,191,237,144,33,84,248,253,123,167,77,147,175,222,127,95,186,189,\n  253,182,148,187,227,14,186,183,146,65,219,49,190,193,160,231,35,29,86,81,232,10,93,161,43,116,133,174,203,113,145,1,\n  67,88,220,136,159,17,90,104,156,46,126,227,141,242,254,139,47,202,151,173,91,203,193,57,115,28,130,98,213,42,217,63,\n  107,150,140,140,141,149,54,248,95,239,66,133,100,78,157,58,178,118,240,96,57,50,111,158,36,67,168,164,90,31,118,5,\n  9,73,11,146,243,95,125,37,155,198,140,145,9,21,42,72,245,255,253,79,194,29,113,146,189,218,165,245,108,120,200,18,\n  9,93,161,43,116,133,174,75,119,209,69,21,229,16,30,79,131,38,130,33,31,139,190,225,6,105,247,242,203,178,186,91,\n  55,21,167,72,181,42,64,140,95,116,125,243,77,50,110,41,5,138,6,241,247,152,155,110,146,58,121,243,202,224,168,40,\n  249,26,150,194,206,201,147,229,252,151,95,58,5,73,48,172,18,124,15,5,24,173,145,105,213,170,73,181,7,31,84,247,\n  134,224,216,133,177,247,4,61,28,153,45,20,19,9,93,161,43,116,133,174,76,183,54,180,139,170,1,24,238,86,6,169,\n  27,231,203,167,2,216,20,18,105,92,81,96,222,140,71,148,188,245,86,105,4,171,100,229,189,247,202,87,247,220,35,19,\n  238,184,67,218,101,207,46,149,174,189,86,34,201,204,241,179,194,221,119,75,167,215,95,87,65,244,127,71,143,86,113,145,\n  212,88,72,48,132,8,198,181,107,234,84,21,123,41,151,35,7,133,72,74,132,35,184,94,29,116,107,200,10,9,93,161,\n  43,116,133,174,76,176,54,116,157,70,126,208,44,48,222,243,229,239,188,83,101,60,29,154,59,215,187,165,0,97,242,251,\n  192,129,18,5,203,164,231,45,183,200,182,255,253,47,149,54,129,126,190,255,126,249,244,174,187,100,0,132,75,157,235,175,\n  151,24,109,149,148,186,237,54,105,253,252,243,50,187,118,109,21,96,15,138,59,75,11,145,164,111,190,145,245,195,134,73,\n  167,215,94,19,198,102,240,92,103,241,76,115,232,202,10,211,2,50,116,133,174,208,21,186,66,87,112,172,13,198,7,98,\n  192,104,55,208,218,96,92,131,12,56,217,10,88,167,195,172,55,143,29,43,165,110,191,93,154,195,242,248,231,193,7,101,\n  11,132,134,69,91,181,32,225,207,63,31,120,64,89,37,35,241,222,38,120,111,73,45,72,234,228,201,35,155,199,141,11,\n  94,76,68,11,181,147,176,148,62,169,95,95,226,96,241,240,62,120,190,205,186,22,229,198,144,0,9,93,161,43,116,133,\n  46,251,130,131,69,126,77,193,96,15,150,200,158,93,198,151,47,47,71,230,207,119,184,168,124,200,132,58,245,249,231,210,\n  252,153,103,84,188,227,219,123,239,85,194,98,139,7,218,106,88,37,127,67,200,44,199,123,59,221,124,51,83,110,101,46,\n  152,188,79,247,243,51,75,139,174,44,10,193,22,24,95,184,67,128,156,4,13,2,221,19,161,45,174,44,180,14,215,233,\n  234,252,187,188,208,157,25,80,14,208,29,30,136,175,223,28,113,5,89,93,28,103,49,199,207,155,211,153,143,64,230,40,\n  117,174,176,31,174,15,41,17,161,43,116,5,206,176,110,7,245,131,224,56,83,137,241,138,247,223,151,139,75,151,250,23,\n  204,134,197,48,163,70,13,165,221,143,134,85,225,77,120,184,211,246,156,57,101,248,109,183,41,166,206,251,6,93,120,24,\n  86,72,226,156,57,50,48,34,194,114,99,37,227,153,23,128,30,229,28,68,101,141,117,32,213,1,253,134,121,252,221,11,\n  241,127,191,122,161,95,64,63,131,126,114,39,124,231,47,160,133,160,87,178,146,192,244,97,78,238,5,205,192,122,253,145,\n  206,156,248,58,63,169,132,239,251,53,194,65,253,181,112,13,93,161,43,116,249,121,56,169,129,141,193,129,186,88,55,111,\n  94,85,175,17,80,6,20,131,230,163,71,43,215,21,221,81,127,185,185,174,188,209,70,188,175,5,222,31,11,1,194,0,\n  122,80,221,86,30,198,120,122,209,34,153,82,165,138,20,135,117,165,173,144,239,65,47,134,95,102,134,170,215,130,214,193,\n  247,209,215,95,47,213,238,191,95,106,60,240,32,232,129,52,84,29,255,243,70,213,238,187,79,81,252,189,247,73,213,123,\n  238,149,170,119,223,45,149,114,228,144,168,107,175,229,179,146,126,3,229,139,184,114,246,103,73,208,185,114,216,87,53,31,\n  244,60,31,129,204,79,89,162,21,56,230,227,34,5,72,168,46,40,116,133,46,255,14,230,93,58,13,55,137,248,82,91,\n  236,196,28,32,112,152,57,213,234,249,231,37,54,3,215,149,233,194,90,131,3,93,254,154,107,164,97,190,124,10,178,36,\n  40,169,187,25,140,243,2,172,170,79,27,53,146,88,48,16,45,64,214,129,94,191,156,46,29,125,239,183,139,102,203,118,\n  172,237,179,207,202,158,161,195,228,192,176,225,114,96,232,80,57,48,68,147,254,61,97,200,16,73,24,60,196,241,211,250,\n  93,211,254,193,131,101,255,160,193,178,183,255,0,217,222,179,167,108,234,210,69,22,87,174,44,37,33,160,53,179,60,13,\n  42,28,113,5,236,207,162,142,159,163,40,248,62,175,89,83,14,141,24,33,137,3,7,73,226,128,129,94,233,0,9,207,\n  158,224,78,253,250,203,222,62,125,100,71,207,94,178,173,87,47,233,83,160,128,21,3,35,45,181,92,122,161,43,116,133,\n  174,140,25,21,77,245,177,20,28,140,5,176,254,194,182,214,143,207,79,134,86,207,67,57,21,218,110,70,194,131,255,159,\n  123,215,93,234,0,143,40,81,34,115,133,134,155,0,97,54,214,162,22,45,84,198,151,22,32,127,93,46,1,98,184,172,\n  186,112,44,115,43,85,18,249,112,178,164,140,28,37,2,134,233,160,15,52,225,247,225,25,83,18,132,202,201,190,253,228,\n  240,128,1,242,97,177,98,214,51,138,78,91,126,32,226,202,216,163,15,98,47,109,160,21,69,97,40,156,15,8,70,23,\n  130,48,241,72,110,239,75,129,80,57,215,163,167,28,237,218,85,118,116,238,44,245,114,229,50,133,71,151,43,41,22,20,\n  186,66,215,229,60,148,12,142,247,167,171,138,22,71,80,4,135,142,43,252,216,187,183,68,93,127,189,116,191,229,150,12,\n  93,86,180,60,250,209,125,0,205,114,121,199,142,153,23,239,240,34,64,88,245,78,172,172,88,140,85,51,215,181,116,97,\n  233,170,250,75,189,38,183,227,158,223,150,165,251,174,115,23,135,16,232,211,87,164,87,111,175,148,146,206,255,46,118,237,\n  38,199,218,182,147,93,109,219,74,203,199,30,51,25,229,168,232,44,206,40,195,156,115,18,67,84,230,62,111,188,33,23,\n  41,56,96,61,8,44,7,129,16,240,151,146,49,31,39,91,182,146,196,198,77,100,121,185,242,82,252,134,27,172,249,56,\n  70,139,47,36,56,66,87,232,202,152,73,93,163,179,170,206,48,198,177,101,252,248,160,66,134,236,153,54,77,42,222,123,\n  175,212,131,0,217,240,224,131,74,64,120,19,28,252,127,61,28,98,22,14,254,55,101,74,230,198,59,188,89,32,203,150,\n  201,199,117,235,74,244,141,55,90,2,100,181,21,68,15,191,180,235,82,0,140,242,240,251,79,61,37,167,41,56,168,105,\n  7,192,36,73,41,221,123,200,185,118,237,229,72,147,38,242,99,92,69,41,115,243,205,214,179,157,3,197,102,245,128,57,\n  231,189,184,99,78,70,16,252,242,171,90,181,68,62,24,233,16,140,1,206,201,197,142,157,228,72,195,70,178,191,70,77,\n  25,241,194,139,166,48,253,65,199,253,66,87,232,10,93,25,184,70,162,217,140,137,89,85,42,56,30,76,134,173,227,30,\n  45,158,125,86,202,226,96,254,112,223,125,94,133,7,93,86,43,241,127,166,246,182,126,225,5,57,187,120,177,189,120,7,\n  171,203,97,73,164,88,184,87,126,140,153,248,88,227,202,149,83,22,144,102,40,159,90,105,188,151,130,81,234,117,121,159,\n  12,126,102,153,178,34,163,70,139,244,238,19,48,163,76,238,214,93,78,183,106,45,137,181,235,200,228,215,94,51,93,86,\n  27,65,185,174,16,151,213,253,216,167,235,170,220,115,143,236,162,208,24,60,36,96,171,131,194,244,44,172,176,131,117,234,\n  200,230,184,56,105,128,125,103,8,143,222,33,151,85,232,10,93,25,31,200,252,96,36,235,89,199,161,210,98,51,33,56,\n  77,6,174,210,97,113,48,23,225,224,111,75,71,120,204,190,243,78,197,216,200,184,109,141,69,215,113,240,190,4,102,220,\n  48,124,184,3,136,209,215,239,196,251,142,127,246,153,116,123,235,45,139,169,48,141,119,96,248,37,40,36,180,32,238,113,\n  175,175,75,223,114,139,252,213,161,131,200,176,225,1,51,74,165,101,119,238,34,199,97,117,252,87,185,138,180,113,245,237,\n  79,188,18,26,104,233,57,137,130,37,118,166,87,129,2,114,97,228,72,135,203,42,80,97,74,151,85,139,150,114,0,86,\n  199,138,200,72,41,9,107,215,168,247,41,28,18,28,161,43,116,165,127,24,137,235,52,131,149,227,44,0,244,187,142,195,\n  15,11,96,186,174,247,152,150,78,208,156,22,201,32,102,59,97,60,223,144,97,6,26,239,192,51,176,137,84,147,39,159,\n  84,133,134,188,111,89,220,119,70,245,234,114,226,243,207,125,183,66,240,62,186,206,8,226,24,230,100,44,85,51,91,43,\n  213,223,255,34,198,158,216,34,223,19,114,146,130,99,192,64,219,46,171,195,245,234,203,207,197,139,75,57,167,203,234,2,\n  168,66,86,168,105,241,209,66,30,194,78,146,139,177,151,132,194,195,134,37,118,177,83,103,57,218,168,145,236,175,86,77,\n  70,195,202,53,132,233,175,151,202,194,12,93,161,235,74,118,87,53,32,86,85,27,28,158,195,243,230,165,109,188,20,44,\n  132,91,124,215,210,182,109,21,195,26,145,78,177,32,235,59,90,222,116,147,202,118,218,52,118,108,224,238,51,220,239,167,\n  62,125,164,24,180,201,54,248,190,73,119,220,33,149,88,4,120,237,181,202,146,240,43,25,0,239,251,174,91,55,51,128,\n  190,9,244,92,102,197,63,140,181,105,174,50,212,74,198,138,176,214,133,129,114,187,46,171,154,181,100,122,129,215,44,38,\n  73,218,2,202,115,133,88,29,247,178,224,175,18,99,97,180,192,108,186,172,206,41,151,85,93,217,86,177,162,52,126,224,\n  1,83,120,12,10,15,185,172,66,87,232,74,247,48,62,131,67,178,153,32,135,235,134,14,77,21,20,103,22,47,86,152,\n  84,108,249,186,125,226,68,213,10,54,197,18,40,54,132,199,47,253,250,169,140,171,222,96,194,91,189,88,29,127,224,16,\n  199,131,193,215,122,248,97,57,252,201,39,129,11,46,140,117,82,165,74,169,150,206,142,156,57,85,141,9,5,147,194,204,\n  130,37,193,12,176,12,241,185,52,177,107,225,152,50,101,204,56,193,44,221,57,49,179,214,38,59,251,164,196,102,207,46,\n  235,32,116,85,150,149,157,192,112,231,46,114,172,73,83,217,85,165,170,180,127,232,33,147,81,78,139,184,2,10,225,244,\n  156,132,195,18,59,213,253,149,87,228,252,7,35,37,5,251,41,24,46,171,239,138,21,147,82,206,196,136,211,186,133,113,\n  232,10,93,161,203,203,65,188,81,251,186,101,106,213,170,169,1,229,132,89,179,164,215,123,239,41,205,159,153,70,116,245,\n  208,245,51,9,218,217,63,35,71,202,133,175,190,10,204,149,132,207,48,230,192,10,238,206,55,223,44,155,189,5,203,193,\n  224,89,76,216,161,64,1,71,127,15,155,133,137,12,188,175,212,133,137,164,117,16,78,131,248,108,120,189,52,172,17,130,\n  35,158,93,178,36,99,193,168,231,166,129,51,189,245,172,134,115,15,186,134,106,9,118,48,202,125,77,30,125,84,142,15,\n  29,230,168,81,8,144,81,10,180,236,243,237,59,40,151,213,111,37,74,74,156,211,130,74,2,197,95,33,130,131,52,128,\n  238,213,207,43,87,145,164,33,67,229,2,4,0,93,79,129,16,3,229,135,235,55,144,253,241,213,100,252,75,47,155,74,\n  1,11,67,239,15,9,143,208,21,186,188,31,196,72,54,114,106,252,196,19,114,208,130,85,7,147,100,220,131,204,177,254,\n  13,55,72,87,48,249,166,20,32,142,46,124,82,250,246,219,165,79,225,194,42,27,235,194,215,95,251,103,137,224,189,132,\n  25,97,111,15,246,242,216,228,69,120,44,184,251,110,213,227,67,21,7,218,176,58,232,242,162,112,104,140,231,48,33,81,\n  182,106,56,248,25,176,182,42,192,194,33,92,252,176,152,24,57,68,43,199,7,1,178,172,125,123,137,118,214,2,172,11,\n  182,203,39,210,213,157,152,50,49,58,90,82,70,143,177,229,178,74,161,203,170,117,107,73,172,85,75,102,191,241,166,48,\n  102,160,199,191,83,247,119,191,18,246,236,61,96,240,191,196,97,77,255,129,197,112,162,93,123,57,214,184,137,28,107,212,\n  216,111,58,10,58,84,183,158,236,171,26,47,219,227,42,74,115,236,7,195,18,251,32,50,228,178,10,93,161,203,235,65,\n  188,21,7,241,11,50,193,165,237,218,165,50,77,166,197,82,91,47,141,67,180,74,167,211,18,70,125,53,126,31,143,67,\n  91,87,51,77,194,119,12,142,140,148,109,19,38,56,220,89,190,48,121,220,131,239,87,189,58,110,186,201,171,240,152,236,\n  104,212,164,106,44,2,14,150,227,115,179,235,212,81,223,243,129,151,248,10,159,237,235,123,238,81,245,36,124,31,59,33,\n  238,152,52,41,125,1,130,231,36,6,86,231,55,222,48,153,77,207,98,65,100,54,150,85,136,245,153,95,2,243,244,107,\n  171,214,142,10,114,27,46,171,36,102,89,53,109,42,187,97,97,118,206,147,215,28,251,199,160,27,174,16,225,81,4,227,\n  62,217,52,247,67,242,27,172,133,223,203,149,151,223,98,99,229,183,146,129,209,175,197,75,200,111,160,37,69,138,74,25,\n  204,179,81,239,82,34,36,56,66,87,232,114,187,98,156,7,49,150,61,199,201,48,85,7,64,205,252,207,81,120,188,240,\n  130,148,113,171,197,48,93,62,211,160,177,215,209,12,183,10,254,158,223,176,161,227,59,124,208,218,201,156,203,64,8,17,\n  240,240,95,15,0,137,188,199,80,194,130,64,51,94,17,104,101,57,238,179,29,247,169,249,208,67,82,154,223,147,14,150,\n  22,95,255,233,254,251,165,3,44,44,62,79,189,71,30,81,113,158,116,133,33,99,55,253,251,155,193,115,106,239,207,4,\n  89,120,60,129,241,236,106,144,39,143,28,225,120,108,184,172,82,44,151,85,253,6,178,54,182,148,84,118,194,174,164,104,\n  164,222,44,173,101,27,150,114,55,10,188,226,215,95,47,229,49,247,229,177,102,193,160,210,16,28,70,242,192,223,160,156,\n  33,225,17,186,66,151,231,131,120,51,152,199,231,49,96,224,171,186,117,115,97,208,140,123,12,141,142,86,110,163,249,119,\n  221,149,134,233,90,61,55,126,135,208,96,211,166,178,44,158,187,238,58,233,254,246,219,25,87,130,51,229,117,242,100,41,\n  11,225,211,12,247,222,232,5,93,151,174,50,198,90,214,14,30,236,191,240,192,61,18,63,254,88,218,189,242,138,18,6,\n  67,192,40,55,251,0,133,178,30,99,97,55,67,214,160,196,227,247,140,16,132,25,139,233,249,238,187,42,5,216,202,206,\n  9,70,157,132,193,40,107,224,187,147,71,135,71,56,92,86,125,251,217,116,89,181,145,131,181,235,200,188,183,11,74,148,\n  211,101,181,7,244,84,86,103,148,70,177,100,121,208,145,8,71,15,250,160,146,33,60,198,135,93,1,245,46,161,43,116,\n  93,46,225,81,152,8,173,172,222,54,173,14,75,171,94,214,161,131,170,168,238,1,237,110,115,58,12,151,63,151,65,171,\n  111,161,179,151,234,63,246,152,108,32,56,159,55,1,130,215,217,67,188,60,132,82,83,15,93,5,73,180,70,90,226,127,\n  140,85,208,197,229,111,76,133,117,29,61,223,121,71,141,135,214,196,122,8,185,173,190,244,14,209,113,144,97,90,43,111,\n  156,63,191,28,181,210,150,189,165,1,247,237,43,37,156,240,237,59,116,139,222,96,172,207,245,248,206,89,49,176,238,126,\n  108,222,220,190,203,170,75,87,57,209,178,149,236,173,91,79,122,228,203,103,186,172,22,233,126,45,116,91,93,175,161,199,\n  175,197,207,107,113,255,107,240,243,26,186,227,170,128,74,102,141,125,203,110,150,181,64,63,131,254,200,4,34,4,127,161,\n  75,84,191,163,106,106,162,29,116,141,73,81,174,2,211,133,66,215,229,87,100,120,54,194,29,103,36,168,100,157,189,140,\n  40,194,113,255,107,180,146,163,246,76,100,102,239,19,227,0,142,37,148,245,146,86,173,210,106,246,96,150,137,179,103,171,\n  52,89,194,161,51,214,177,45,3,244,91,186,178,8,98,72,107,133,174,162,141,163,70,121,102,250,120,141,253,200,137,87,\n  213,4,140,209,147,240,80,152,86,215,95,47,149,239,191,95,18,102,206,244,171,14,131,176,237,253,139,22,149,48,140,155,\n  2,237,55,124,199,214,12,44,14,171,107,225,55,16,130,108,84,213,80,187,227,136,237,117,8,22,140,87,225,161,99,31,\n  109,95,126,217,180,62,58,218,93,60,253,249,71,48,134,237,117,115,229,150,131,22,250,171,157,170,114,10,143,118,237,228,\n  159,6,13,164,42,4,119,81,167,198,189,3,180,152,177,47,208,103,140,177,128,62,166,224,2,77,7,77,1,77,2,141,\n  7,141,6,125,128,177,13,211,86,86,127,13,223,209,3,212,85,63,123,59,80,19,80,41,13,34,121,143,222,111,193,222,\n  191,57,252,236,30,232,43,221,97,199,122,116,235,246,248,4,232,93,93,124,217,8,212,1,212,7,52,84,207,229,68,61,\n  183,147,245,60,155,52,89,255,207,164,9,160,113,236,175,131,159,163,244,90,12,215,235,49,152,13,219,64,189,244,90,240,\n  94,205,65,213,64,97,160,199,232,109,136,178,177,55,13,97,246,6,139,52,121,127,208,136,96,144,126,142,161,62,16,159,\n  117,136,126,222,129,122,15,246,213,243,218,75,187,53,249,236,45,64,53,137,68,160,21,186,219,130,193,84,245,119,60,160,\n  215,240,19,208,220,32,211,28,208,236,12,136,103,115,134,62,159,31,129,166,234,61,243,161,113,86,185,71,70,186,237,141,\n  238,196,45,4,149,6,189,164,27,169,249,158,158,175,31,254,49,48,166,109,181,192,228,15,64,72,120,100,142,120,109,106,\n  124,188,98,50,76,105,245,5,1,151,46,40,106,237,100,162,45,159,123,206,145,185,228,254,221,20,30,31,125,164,132,71,\n  99,15,194,131,223,179,22,130,168,26,4,91,237,60,121,148,21,225,83,32,30,239,97,197,56,3,248,20,28,108,56,197,\n  56,70,122,21,236,164,95,240,30,6,231,105,5,149,208,21,232,12,230,119,124,237,53,135,219,202,135,160,252,194,22,45,\n  204,204,37,86,37,223,23,232,38,125,221,185,70,149,48,247,23,135,23,46,44,201,54,93,86,202,242,160,219,170,91,55,\n  217,12,1,210,12,214,97,28,158,153,84,1,214,29,27,41,17,173,183,12,172,204,82,176,212,88,83,66,42,9,225,91,\n  2,243,82,156,132,181,138,129,64,103,35,170,98,215,93,39,197,152,161,6,226,115,27,207,46,150,59,9,99,191,0,58,\n  20,230,64,34,158,168,25,232,131,87,91,6,19,25,170,214,254,238,214,232,187,45,121,168,217,141,16,207,191,151,245,40,\n  160,36,203,45,198,185,226,252,113,46,57,175,37,82,233,38,227,247,180,100,173,129,90,7,99,45,82,215,3,228,190,30,\n  225,142,253,156,66,24,23,208,174,112,71,95,18,10,150,55,41,72,34,29,99,247,151,113,50,181,127,30,83,165,163,113,\n  207,104,99,28,182,72,63,131,63,20,165,247,160,249,220,30,158,253,28,215,1,127,175,210,12,180,40,21,15,203,178,11,\n  208,157,76,129,156,196,181,224,121,9,38,89,103,47,35,42,169,207,167,58,163,55,221,148,102,159,112,143,152,243,106,205,\n  145,62,155,23,9,178,26,230,200,18,157,12,170,172,49,237,188,43,77,134,230,80,7,31,76,30,83,182,108,186,90,60,\n  153,124,181,92,185,164,92,6,1,103,147,33,83,24,116,209,129,231,153,68,59,245,32,60,246,80,120,220,115,143,87,225,\n  65,134,30,71,1,240,228,147,114,122,225,194,140,133,7,123,164,227,125,195,99,98,84,229,120,67,76,224,26,47,214,146,\n  245,218,247,248,63,219,219,198,99,98,57,214,146,96,156,109,94,124,81,230,212,169,163,82,137,21,16,163,47,22,15,222,\n  179,111,198,12,169,230,76,243,60,167,37,187,93,205,122,10,23,255,187,198,141,109,35,198,166,86,82,227,231,169,129,3,\n  101,95,255,1,178,163,79,95,217,1,129,180,189,79,31,217,138,239,222,2,171,102,19,254,191,17,66,230,239,174,93,101,\n  67,231,206,242,103,199,78,178,182,125,7,249,189,109,59,249,181,205,251,242,115,235,214,178,166,101,75,249,190,121,115,249,\n  174,105,83,89,217,184,137,172,104,216,72,190,169,223,64,190,174,91,79,190,172,93,71,22,213,172,37,159,84,170,36,163,\n  194,195,165,253,179,207,73,60,246,77,177,235,174,87,194,36,220,209,43,164,149,85,63,17,233,255,156,220,170,53,200,91,\n  117,97,38,227,118,217,89,72,25,233,104,35,112,163,166,27,12,186,222,112,199,41,10,79,107,254,251,37,208,162,178,185,\n  64,250,188,67,13,88,11,139,19,248,174,20,30,224,170,44,68,125,226,9,233,247,230,155,194,52,235,79,226,42,202,151,\n  152,155,111,49,87,223,55,105,34,63,65,225,248,13,243,249,7,230,117,237,251,109,101,109,91,77,239,59,232,15,208,239,\n  248,159,147,218,168,247,255,218,170,149,252,140,53,224,231,233,206,92,211,172,153,252,208,180,153,172,198,119,174,196,90,44,\n  175,95,95,150,214,169,43,75,112,175,5,85,171,202,71,165,74,201,128,183,11,74,147,71,30,149,50,26,238,7,99,61,\n  202,120,39,198,93,44,194,15,124,54,11,255,14,159,223,93,7,124,97,37,238,251,99,139,150,178,134,227,176,65,230,115,\n  88,244,125,234,239,77,211,208,247,77,154,202,106,236,61,158,141,85,141,26,201,183,13,27,202,10,88,212,203,49,183,75,\n  235,58,159,125,122,153,50,50,248,221,119,165,249,227,249,164,60,148,36,10,60,10,115,45,72,106,104,235,213,103,1,170,\n  145,36,184,127,102,144,57,47,168,94,93,254,197,185,250,167,83,231,32,81,39,249,27,103,238,175,142,29,211,165,13,160,\n  245,56,151,235,219,183,151,117,80,6,215,225,124,114,239,252,254,190,99,175,252,138,125,242,115,203,86,152,215,22,242,67,\n  51,231,222,88,138,51,58,175,82,101,25,19,17,33,29,158,123,94,117,204,36,143,161,48,9,119,244,43,106,15,250,159,\n  71,11,205,61,253,243,55,48,146,116,131,209,96,202,115,176,24,220,112,44,232,219,232,67,235,88,11,13,151,53,33,245,\n  30,125,84,142,184,199,12,124,176,60,200,216,153,38,76,119,80,134,5,130,218,117,52,42,54,86,9,14,214,165,120,114,\n  179,241,239,205,186,248,144,65,113,214,118,208,170,34,60,252,7,37,75,202,159,67,135,170,130,66,37,48,252,132,98,73,\n  94,182,76,6,193,226,49,92,87,31,134,7,232,170,209,107,244,16,54,244,38,182,85,101,231,59,59,240,27,46,213,212,\n  116,95,65,104,36,225,251,82,62,248,192,129,206,75,184,19,90,54,164,49,99,189,211,88,79,52,206,65,227,198,59,104,\n  252,4,145,9,19,69,38,125,40,201,160,179,227,199,203,94,88,111,43,177,121,7,22,44,8,43,71,165,95,83,11,95,\n  137,103,124,171,136,15,76,219,208,246,170,128,190,195,231,87,131,86,129,86,130,86,128,150,227,251,150,81,171,6,125,5,\n  90,162,221,112,11,201,32,65,11,64,159,130,230,25,110,1,154,253,51,105,33,232,202,250,1,160,135,51,130,153,49,198,\n  194,24,81,121,222,135,113,67,50,165,74,119,221,37,93,160,124,204,46,91,78,126,99,108,9,243,124,138,77,183,172,57,\n  230,79,98,112,81,17,96,252,202,106,204,53,194,141,188,53,240,74,211,244,203,160,15,70,58,137,125,77,232,50,230,61,\n  185,110,227,198,73,18,232,56,222,183,17,74,193,220,138,21,149,80,139,118,184,102,143,107,183,198,125,25,49,81,227,217,\n  107,51,137,99,108,84,49,145,201,83,28,207,101,222,63,168,244,129,151,231,253,32,237,123,249,220,22,113,76,99,198,168,\n  189,153,4,58,137,255,111,197,222,255,162,90,117,233,244,194,11,74,195,39,20,19,158,101,9,91,29,20,247,81,121,208,\n  207,159,23,159,221,90,27,194,243,32,215,133,221,85,135,143,200,28,34,142,157,73,195,51,218,31,25,236,11,189,39,82,\n  48,39,103,49,71,84,34,41,88,134,64,192,86,188,243,78,206,73,50,246,244,26,198,252,194,220,207,130,145,254,185,187,\n  81,190,124,114,236,211,79,211,103,146,248,31,153,127,243,103,158,145,98,96,138,115,112,131,109,62,4,158,25,116,102,1,\n  96,12,136,76,217,69,64,233,152,71,121,47,49,15,126,63,173,28,186,144,136,61,149,196,34,196,116,198,199,170,240,113,\n  176,160,152,237,197,212,225,85,110,130,195,18,26,132,36,233,11,161,193,204,48,186,181,170,231,204,41,147,43,87,150,29,\n  31,126,232,64,216,229,24,3,45,70,196,103,191,133,166,78,243,80,11,143,205,22,51,242,231,50,2,94,101,169,169,15,\n  122,231,29,73,2,83,79,177,129,24,235,145,104,197,16,72,144,196,162,67,77,41,126,82,234,103,97,193,164,144,48,206,\n  20,108,72,118,229,75,97,119,62,110,120,30,228,137,147,228,194,164,73,178,177,123,119,97,227,38,106,59,216,152,219,88,\n  160,154,145,15,222,96,214,223,114,126,43,221,121,151,84,102,223,117,48,107,110,120,229,122,3,81,179,44,127,251,237,202,\n  5,87,14,22,37,221,112,236,67,78,109,155,238,184,210,202,37,231,234,150,163,153,111,184,220,190,160,91,45,34,227,88,\n  70,97,10,13,156,161,179,180,48,218,192,58,94,80,185,138,236,196,188,158,35,83,227,33,229,115,51,70,197,158,43,116,\n  55,114,142,56,215,102,67,46,42,3,234,167,27,153,255,183,40,157,166,94,30,201,88,91,181,46,28,7,83,189,57,54,\n  8,247,227,16,46,95,67,41,172,151,59,55,215,129,169,218,115,173,103,143,76,255,249,111,96,60,140,207,77,203,135,76,\n  41,37,131,134,100,151,156,204,125,109,61,59,215,130,204,21,10,207,25,156,39,90,209,20,34,81,196,184,115,236,195,152,\n  210,62,184,177,244,28,84,164,166,62,172,80,97,37,152,212,247,187,175,215,229,32,127,247,4,149,210,33,67,213,158,184,\n  136,57,217,212,185,139,244,227,217,116,32,74,239,98,25,135,75,83,56,253,240,149,233,131,29,13,147,206,215,162,190,53,\n  189,123,171,138,240,234,56,244,107,50,8,158,91,12,123,152,174,211,72,211,1,144,217,86,83,166,120,205,182,218,166,139,\n  246,8,27,210,175,72,17,5,225,158,94,159,13,10,128,72,140,171,22,200,236,139,110,9,141,229,120,173,15,24,71,25,\n  45,52,24,231,153,85,171,150,236,155,62,221,62,78,151,155,235,170,234,3,15,88,89,87,231,3,113,93,69,58,92,34,\n  244,59,142,35,163,164,11,66,29,120,27,136,177,151,141,172,13,205,205,74,97,66,237,104,226,68,57,13,235,100,38,180,\n  243,18,142,130,60,102,167,69,164,23,200,212,255,123,141,62,218,150,249,243,203,246,129,131,100,247,208,97,178,107,240,96,\n  249,15,76,97,39,254,222,129,239,223,62,96,128,108,199,65,222,214,175,159,108,237,219,87,182,224,190,155,48,111,255,98,\n  12,27,49,150,127,48,166,191,187,247,144,191,186,118,147,181,216,147,191,117,232,32,11,226,227,37,214,89,24,120,70,7,\n  150,189,9,116,198,52,122,64,104,28,164,240,235,240,236,115,242,125,227,198,114,146,144,49,212,236,104,29,82,200,115,173,\n  172,3,157,213,214,3,99,227,90,36,131,145,94,128,6,74,134,209,26,86,136,33,64,238,207,96,29,30,199,243,239,172,\n  135,51,116,120,208,32,123,80,57,151,97,47,42,166,73,171,27,204,242,8,24,231,228,152,24,107,31,146,89,22,143,204,\n  120,31,210,155,240,97,244,117,215,203,170,70,141,109,247,213,201,50,123,2,251,54,25,103,233,8,126,159,22,29,173,226,\n  40,225,142,20,254,146,86,215,78,43,230,49,146,140,105,21,76,88,95,235,39,8,6,56,78,195,149,116,130,230,246,87,\n  58,29,0,45,198,77,196,92,30,74,194,120,184,11,143,244,234,60,248,217,133,26,154,132,112,33,222,130,249,132,140,159,\n  89,179,166,20,195,119,84,195,97,254,198,192,173,218,164,211,135,123,82,227,164,143,23,196,224,59,227,25,204,222,10,154,\n  208,48,136,48,45,93,97,41,25,174,171,161,145,126,6,229,244,6,253,31,230,249,175,106,247,221,47,251,200,140,134,12,\n  201,122,140,40,208,77,10,102,147,2,166,117,126,210,135,50,1,155,52,194,161,245,179,1,213,11,158,92,70,134,171,196,\n  209,8,171,66,156,200,172,217,146,2,33,228,112,167,141,113,163,140,221,109,201,96,244,167,113,80,78,224,224,127,82,165,\n  74,186,168,194,70,186,44,179,166,62,167,203,173,6,20,132,69,213,170,203,201,97,195,28,174,1,106,158,150,192,184,66,\n  214,34,5,227,61,7,70,122,2,235,177,190,77,27,169,233,64,18,78,209,46,44,143,72,3,86,160,152,138,231,200,162,\n  69,37,121,148,61,116,231,203,249,252,201,125,250,200,89,60,255,97,40,25,31,22,43,102,121,12,118,234,204,56,143,214,\n  151,225,78,254,183,6,120,86,194,64,173,185,95,233,103,211,114,105,67,177,58,221,169,179,36,118,232,40,227,10,23,150,\n  72,71,227,59,90,101,5,34,244,4,220,137,135,255,190,34,187,175,77,157,234,59,3,5,179,37,178,45,225,218,35,52,\n  212,199,166,12,172,15,214,135,16,47,138,8,186,238,194,35,189,10,115,50,127,22,38,242,62,116,71,121,18,30,73,176,\n  70,88,209,78,183,88,101,44,252,87,120,30,162,229,254,171,173,22,246,71,47,69,161,129,9,96,186,237,220,122,245,28,\n  89,101,86,60,35,51,90,214,226,123,103,213,174,237,222,190,244,142,8,255,133,71,9,246,229,102,160,245,34,125,148,193,\n  118,89,93,110,198,5,205,55,9,207,181,15,140,171,225,195,15,91,243,69,100,226,236,17,158,231,35,181,17,214,134,110,\n  221,149,245,162,76,110,203,12,79,135,82,210,252,221,91,206,227,128,28,105,213,90,246,117,235,38,157,158,127,222,20,246,\n  31,153,105,139,134,197,241,18,238,255,19,5,93,151,23,94,148,109,44,168,101,236,130,99,176,153,196,112,57,233,34,230,\n  242,4,172,48,50,208,153,177,177,150,251,238,168,101,125,69,120,112,217,49,70,196,44,175,31,154,52,181,93,119,116,57,\n  73,161,45,116,233,42,199,58,117,146,221,160,142,79,63,109,237,195,85,158,172,47,35,209,168,12,246,203,121,229,78,166,\n  98,98,163,21,116,150,35,204,201,133,142,157,228,88,235,54,178,173,69,75,105,2,101,59,204,217,53,245,118,62,252,115,\n  120,248,61,45,159,125,214,17,28,246,199,199,79,64,67,104,119,213,115,229,82,46,37,246,197,216,108,20,10,166,233,61,\n  142,77,198,140,170,93,238,21,231,248,125,107,58,216,86,20,30,115,116,7,193,41,208,12,221,153,61,171,223,151,180,110,\n  173,220,104,113,16,14,139,113,15,90,47,139,96,173,208,42,42,201,116,52,6,206,31,125,84,9,152,131,115,230,4,175,\n  23,73,6,113,143,159,33,40,99,156,96,137,9,254,192,149,132,235,34,188,212,190,220,181,235,92,249,102,177,167,131,11,\n  1,114,142,193,228,161,195,228,163,18,37,44,151,209,49,79,29,251,92,26,97,61,145,95,78,140,27,47,41,54,152,86,\n  106,149,125,227,38,178,174,97,35,169,152,227,78,19,85,184,170,135,130,188,231,241,255,223,233,27,31,94,168,144,28,165,\n  107,138,241,12,106,220,87,184,198,73,6,122,6,140,243,72,231,46,242,119,155,247,165,10,206,143,158,139,169,238,185,255,\n  46,129,98,40,105,137,20,156,87,138,203,42,29,40,254,83,109,219,201,33,60,251,242,10,21,164,164,3,138,159,29,66,\n  27,123,18,158,218,157,60,54,74,185,147,27,92,149,103,83,205,9,44,81,206,201,204,232,24,203,51,112,130,49,88,43,\n  16,123,70,185,131,2,212,174,217,88,41,14,12,187,56,45,3,8,16,50,110,247,0,245,18,252,63,6,255,111,255,234,\n  171,114,142,48,231,158,80,117,161,73,122,66,213,101,149,247,116,71,228,95,197,38,92,172,22,8,0,6,166,9,15,79,\n  33,193,130,190,41,248,189,57,22,158,247,99,208,188,209,19,79,200,130,198,141,29,197,125,151,66,104,184,101,145,85,194,\n  179,235,67,120,145,154,138,159,105,144,236,203,189,86,245,229,198,60,95,77,102,177,75,202,48,181,190,94,189,228,71,172,\n  83,172,179,58,127,144,233,115,46,150,205,173,17,86,233,50,146,50,101,170,10,196,219,5,134,60,80,175,190,204,141,136,\n  52,131,229,59,116,17,157,153,134,155,23,227,250,142,130,124,116,88,184,156,26,62,220,17,215,184,130,173,13,119,162,166,\n  121,4,140,98,47,172,177,182,186,211,38,158,123,171,153,236,17,230,22,40,30,250,222,123,146,204,108,174,43,209,101,229,\n  190,15,219,119,144,67,141,26,203,182,234,53,164,145,179,9,216,42,119,143,129,171,59,249,62,217,219,191,191,200,208,171,\n  244,108,182,107,47,71,90,182,146,95,234,214,85,9,39,250,108,126,204,9,232,204,224,216,188,6,13,108,181,117,253,190,\n  71,15,85,253,205,184,68,55,104,251,76,141,181,24,255,159,88,132,182,96,8,132,54,89,212,178,101,90,55,81,6,253,\n  60,182,27,136,186,46,227,196,125,233,2,163,203,77,213,101,224,224,91,16,241,37,240,61,109,95,122,73,245,93,87,69,\n  133,151,82,104,24,243,194,102,89,77,242,231,55,93,87,157,252,20,30,145,4,170,236,201,30,38,208,108,82,174,38,179,\n  56,149,122,200,121,48,241,163,160,141,208,252,170,58,53,222,111,117,221,132,57,31,169,141,176,214,130,193,49,83,40,37,\n  208,98,73,13,12,121,8,130,99,119,124,53,233,242,216,99,166,203,106,142,229,235,55,178,187,88,193,43,3,223,46,232,\n  136,111,80,104,93,69,130,195,106,12,118,180,69,75,73,128,53,214,215,137,146,112,10,244,94,132,107,109,131,10,20,51,\n  54,176,146,103,18,214,87,178,182,228,124,163,30,138,49,41,50,127,207,128,196,157,130,253,252,170,253,112,99,217,87,173,\n  186,244,207,159,42,60,137,155,246,106,132,23,119,114,95,186,147,25,95,187,42,207,38,20,138,14,29,229,72,243,22,178,\n  185,89,51,169,1,190,174,121,217,110,78,192,52,110,0,50,255,128,133,135,102,148,235,113,160,154,211,87,8,6,206,154,\n  9,6,167,105,9,88,24,87,237,95,121,69,142,45,88,144,150,137,103,208,73,144,150,203,4,88,52,252,142,207,241,0,\n  86,10,237,153,133,11,21,76,124,33,93,5,206,10,203,134,249,242,201,132,242,229,21,2,174,114,195,217,73,183,13,2,\n  49,177,160,199,59,239,152,76,105,170,47,80,23,145,78,191,234,64,106,195,139,160,9,93,141,102,113,234,6,101,55,195,\n  78,157,100,107,135,14,82,203,169,241,109,178,10,148,140,3,171,26,97,53,5,163,63,54,118,172,164,216,40,150,36,19,\n  59,3,38,153,88,171,182,172,43,93,90,42,223,118,187,37,180,232,170,168,109,8,14,174,87,27,140,233,66,155,39,159,\n  146,131,3,6,56,44,192,171,76,112,164,10,143,166,205,36,161,65,67,25,244,194,11,214,190,77,178,122,217,27,235,144,\n  155,129,226,234,88,171,255,48,15,103,160,113,159,126,191,173,114,1,186,211,25,88,50,233,209,89,124,46,13,65,137,176,\n  136,154,175,39,58,15,43,137,113,154,100,43,245,52,8,207,79,188,183,227,124,126,156,183,113,80,62,195,156,251,161,170,\n  249,252,69,181,59,57,202,114,39,143,190,138,207,38,230,249,104,179,230,178,29,243,82,63,103,78,107,78,146,200,160,86,\n  149,2,195,246,138,59,229,167,155,230,224,199,31,203,180,248,120,21,7,137,208,149,218,68,233,37,180,135,215,222,224,96,\n  240,223,128,105,48,141,151,233,188,158,138,249,198,106,225,177,152,150,139,22,114,236,92,56,173,90,53,85,251,193,44,43,\n  10,12,226,88,169,204,169,203,44,52,76,161,58,6,140,201,16,30,203,89,5,237,99,33,220,221,108,114,84,241,206,187,\n  100,7,205,97,166,128,94,101,102,177,137,179,117,156,194,3,76,161,166,83,120,252,71,60,175,136,108,30,26,97,149,40,\n  33,201,116,89,217,40,150,180,24,197,1,48,138,249,16,240,110,168,194,79,26,194,227,45,220,115,47,107,73,254,134,165,\n  34,116,87,93,165,140,66,9,143,198,77,100,31,230,164,159,211,109,37,26,126,195,220,155,165,25,40,166,214,125,24,251,\n  242,32,230,229,64,253,6,146,80,179,86,26,58,64,170,69,170,157,134,40,184,19,107,147,234,40,116,103,69,117,234,168,\n  254,241,138,234,214,85,205,185,20,213,171,167,58,94,42,130,112,59,222,166,141,156,237,219,87,146,70,140,144,100,8,243,\n  148,32,184,205,146,185,39,192,40,217,130,120,146,70,224,214,207,223,38,34,173,59,121,157,195,157,220,247,170,62,155,202,\n  149,217,180,169,108,131,69,86,207,104,142,70,255,229,166,138,56,20,132,7,9,74,214,17,152,37,3,216,108,203,250,93,\n  215,174,178,184,85,43,133,7,117,50,189,190,30,96,244,108,240,196,65,209,61,229,73,120,140,210,105,190,116,67,153,22,\n  18,139,249,168,221,171,239,206,42,2,195,75,243,41,189,9,55,248,130,115,165,55,104,33,28,208,147,93,160,1,157,163,\n  112,191,74,205,226,84,225,1,243,120,99,139,150,166,219,42,85,120,164,105,132,69,38,62,113,146,173,98,73,154,227,236,\n  101,178,167,106,188,244,120,236,113,147,81,46,136,112,64,155,88,238,170,207,25,20,157,87,177,162,164,48,171,234,10,247,\n  237,103,196,40,200,152,57,39,93,30,121,196,154,147,20,93,205,159,45,194,25,243,24,203,53,106,240,240,195,210,7,138,\n  97,239,231,159,151,94,249,243,75,175,199,31,151,222,160,62,143,231,75,165,190,249,158,72,165,254,79,144,242,171,159,3,\n  240,115,96,126,210,147,50,8,130,106,240,83,79,201,144,167,158,150,161,79,63,45,195,158,126,70,134,63,67,122,86,70,\n  60,251,172,124,240,236,115,50,242,185,231,100,52,238,51,22,22,209,248,151,95,150,201,16,248,115,161,152,253,222,22,150,\n  10,139,243,134,217,23,234,94,44,143,84,112,83,143,238,100,22,237,94,197,103,243,60,207,73,163,70,178,9,124,172,198,\n  189,247,186,8,143,3,53,96,37,28,98,187,217,96,50,94,75,251,183,40,131,170,245,49,101,202,168,1,121,234,21,194,\n  191,217,35,132,27,153,125,197,109,185,215,46,131,240,160,0,53,122,67,164,50,68,31,96,31,136,8,42,11,170,84,117,\n  64,133,216,100,90,244,25,51,123,194,95,74,245,83,91,126,231,76,98,90,199,90,181,150,223,106,212,144,178,206,102,90,\n  91,52,56,155,11,134,82,195,188,121,229,48,15,44,139,37,237,184,172,218,188,175,52,223,13,101,202,74,60,44,91,99,\n  141,26,27,247,140,199,61,207,181,7,3,59,193,250,26,102,21,5,81,195,180,214,132,76,139,193,123,171,143,250,133,140,\n  122,173,227,189,252,140,90,159,96,173,137,21,3,130,150,191,163,82,101,105,254,96,170,150,121,193,234,162,104,181,6,208,\n  49,33,245,255,162,54,40,204,38,113,205,136,16,48,181,84,169,160,196,4,85,204,163,113,99,217,95,173,186,12,133,240,\n  50,132,199,251,86,221,145,182,130,7,41,119,50,246,107,176,206,102,32,148,89,177,31,151,128,57,51,208,96,237,173,195,\n  158,136,51,26,198,81,120,156,106,240,232,163,202,221,115,185,180,118,21,23,40,88,80,101,71,45,243,0,182,104,245,47,\n  39,60,9,33,68,254,9,134,139,237,18,10,15,102,131,25,89,60,7,153,30,237,131,240,200,129,69,250,190,60,22,107,\n  19,139,42,149,143,61,240,194,51,50,25,50,134,83,45,91,201,137,230,45,228,36,52,252,180,132,215,241,63,199,255,245,\n  123,90,182,84,159,81,190,107,88,125,244,53,147,209,243,251,130,157,209,113,184,97,35,89,22,29,173,208,97,245,92,253,\n  174,33,209,173,57,169,69,12,165,49,81,197,130,226,178,58,65,247,4,52,204,207,223,123,79,33,2,27,233,212,207,89,\n  174,9,214,115,144,57,253,130,57,81,41,185,193,240,173,107,129,113,17,243,72,159,62,231,151,218,46,221,69,71,49,7,\n  71,44,210,61,213,61,17,123,180,31,199,152,78,65,235,62,135,253,149,204,122,23,187,235,96,8,212,191,203,149,151,106,\n  58,73,69,167,102,190,233,150,178,204,57,250,73,199,3,146,12,74,246,129,82,188,144,4,66,28,35,161,104,182,176,200,\n  217,38,230,155,105,141,118,5,95,52,172,209,250,198,179,223,67,208,203,138,80,116,119,112,63,112,95,216,184,167,58,155,\n  184,47,99,61,103,60,144,183,120,144,138,251,144,240,89,198,12,137,146,157,18,100,36,3,43,149,157,174,197,85,49,49,\n  82,210,89,118,112,156,129,159,139,204,6,58,237,222,252,233,18,198,4,216,120,138,77,150,42,128,193,254,236,165,215,198,\n  38,237,186,226,192,155,193,172,221,239,79,79,143,203,44,60,126,232,217,211,196,184,34,240,220,107,62,8,143,183,9,176,\n  215,230,161,135,100,127,149,42,114,20,154,213,169,138,149,228,124,147,166,146,12,166,147,90,165,237,195,70,177,218,205,146,\n  49,209,28,167,86,69,159,238,129,154,174,148,104,253,94,195,245,181,196,154,181,228,32,24,10,125,209,135,27,52,144,99,\n  205,155,203,153,118,237,20,3,14,218,6,133,213,65,166,53,253,181,215,77,198,176,196,112,31,177,17,214,108,66,75,255,\n  216,166,141,2,90,180,229,178,162,31,183,65,67,217,11,38,209,247,137,39,76,13,115,137,21,147,98,124,133,213,211,44,\n  206,60,79,40,21,155,16,248,138,81,224,89,121,111,62,47,133,0,253,250,156,103,174,203,222,248,106,138,105,237,130,165,\n  249,159,65,187,12,98,175,121,210,30,188,119,63,227,0,152,139,227,88,135,179,12,28,219,212,64,201,196,168,60,112,253,\n  87,67,136,199,58,234,28,56,39,187,172,180,101,55,203,248,81,13,185,83,86,83,57,221,213,177,156,241,183,69,12,184,\n  199,49,189,87,195,125,87,209,84,85,199,83,170,235,94,27,181,116,11,228,186,160,122,92,3,80,67,221,251,164,137,238,\n  61,193,190,28,173,65,109,181,59,233,23,214,82,253,204,6,105,54,98,15,60,39,100,206,140,191,108,171,84,73,26,129,\n  23,133,57,83,236,75,71,184,54,205,59,217,245,229,151,229,28,147,88,104,141,218,216,251,188,39,247,34,247,255,193,218,\n  142,115,118,72,81,93,207,84,183,174,28,198,218,147,142,212,175,47,71,193,19,78,64,193,60,219,167,143,92,28,56,72,\n  146,173,130,217,32,213,121,80,153,60,0,158,49,23,231,192,80,130,55,81,120,164,52,123,234,41,255,11,4,131,88,11,\n  177,127,198,12,149,230,91,23,26,231,6,47,48,39,91,117,115,38,86,169,115,65,251,20,46,156,182,219,97,22,21,30,\n  63,245,238,173,128,255,34,156,105,143,239,68,100,236,178,98,10,181,124,244,250,235,114,168,100,73,217,255,226,139,178,255,\n  201,39,37,225,185,231,228,224,155,111,201,177,152,226,114,6,76,231,34,152,80,10,153,184,9,136,230,169,208,7,218,237,\n  126,48,168,21,69,195,100,220,11,47,200,132,151,94,86,1,193,201,175,190,42,83,10,20,144,143,94,123,77,166,227,94,\n  51,222,120,67,102,97,147,204,121,235,109,153,251,118,65,21,72,254,236,221,247,100,81,161,194,178,52,44,92,86,151,40,\n  169,124,159,71,168,21,117,236,24,20,141,215,242,51,147,121,246,124,236,49,147,145,143,52,25,21,94,223,81,55,247,67,\n  114,112,228,40,73,177,145,121,166,138,225,52,147,248,187,108,57,169,161,107,136,244,61,91,235,251,221,139,249,255,177,244,\n  173,183,202,58,104,227,193,8,136,50,24,75,70,65,161,145,72,44,53,60,239,95,101,202,202,23,239,21,146,145,207,61,\n  47,61,31,127,92,58,229,201,43,109,161,48,180,201,157,91,90,231,202,149,74,109,64,109,241,236,237,31,126,88,58,230,\n  201,163,180,226,222,216,15,163,177,78,63,53,108,40,39,33,72,47,246,238,109,223,101,131,177,37,128,81,204,120,227,77,\n  83,136,175,241,5,25,193,0,138,100,179,175,103,117,101,122,69,45,4,90,234,134,76,221,180,59,182,63,230,119,160,69,\n  186,145,216,16,131,134,249,72,195,9,29,206,76,203,13,176,194,148,229,209,35,112,235,252,20,172,109,10,207,223,98,75,\n  73,5,167,251,244,152,165,240,105,98,147,41,249,12,66,92,65,224,216,112,89,113,206,105,69,238,133,98,176,42,60,2,\n  103,243,69,25,143,179,62,241,165,151,100,18,227,58,56,163,83,94,121,85,166,190,90,64,166,225,156,78,199,57,157,137,\n  115,58,27,231,116,238,91,111,201,167,56,159,11,195,195,101,89,249,10,242,75,147,38,10,21,55,137,89,136,129,54,138,\n  51,120,8,149,212,211,80,22,247,129,215,108,193,189,251,220,123,159,121,78,22,58,132,7,54,225,25,95,122,100,100,18,\n  115,101,139,218,226,55,223,44,237,61,20,8,186,11,16,246,72,39,120,34,43,198,167,98,241,146,150,45,203,242,194,227,\n  71,87,225,113,218,204,153,247,114,0,111,195,166,253,182,12,230,227,151,226,197,229,96,88,152,236,135,208,216,15,33,175,\n  8,235,165,8,22,216,1,108,178,195,96,62,39,202,148,145,179,208,68,146,192,156,82,232,82,50,132,137,181,65,183,197,\n  85,148,166,152,191,34,94,124,199,238,125,187,35,117,163,34,102,33,209,173,19,3,235,137,218,104,61,8,241,101,149,42,\n  203,113,152,202,23,130,96,125,168,60,114,104,94,127,149,45,43,213,157,174,18,209,76,39,21,126,157,86,192,8,204,69,\n  18,93,86,54,138,37,201,196,149,54,85,163,134,44,46,92,68,53,199,209,247,59,4,122,197,0,11,61,223,171,192,107,\n  65,177,58,40,32,153,22,76,223,49,45,191,245,165,203,200,232,231,95,80,207,203,185,13,75,39,30,144,81,220,160,242,\n  93,119,203,90,40,17,201,118,92,54,180,78,219,181,151,131,216,67,180,108,58,59,131,229,164,9,209,30,240,157,12,136,\n  142,236,26,239,168,29,225,238,49,230,127,8,90,201,166,75,204,140,179,246,151,218,75,186,81,147,123,19,167,104,119,242,\n  163,105,20,63,223,0,2,55,145,194,211,134,53,202,56,18,207,73,66,245,234,242,73,193,119,76,45,155,88,107,57,245,\n  179,222,73,136,114,182,18,216,74,75,207,134,43,211,114,215,210,250,220,30,23,39,173,115,230,244,120,54,211,59,159,81,\n  122,78,57,103,4,47,36,42,242,234,166,77,149,114,229,83,246,153,33,44,82,120,158,33,60,207,224,249,169,156,82,73,\n  221,253,204,51,178,9,10,221,111,80,88,234,232,146,11,237,98,236,78,225,113,190,113,190,124,170,152,237,114,9,15,102,\n  80,113,82,60,165,233,122,2,88,36,82,110,21,76,86,9,104,6,43,58,117,202,218,238,43,60,223,234,238,221,77,183,\n  149,47,150,71,1,30,190,22,216,76,123,202,149,147,3,208,48,40,40,82,133,135,73,150,32,33,97,161,19,161,169,28,\n  1,67,60,9,141,250,28,24,213,69,230,209,131,152,222,248,93,84,49,41,229,116,69,4,68,252,44,55,120,67,28,214,\n  93,204,183,183,25,176,181,92,5,52,199,23,65,8,26,140,156,177,161,151,117,154,46,181,217,169,170,17,22,54,183,124,\n  56,217,86,96,84,185,172,160,173,211,210,25,136,57,12,115,77,163,190,85,23,34,126,65,152,241,31,113,16,131,225,211,\n  102,44,129,129,104,186,201,190,44,82,84,234,232,140,178,176,180,115,156,172,155,135,157,209,123,197,157,78,235,255,157,213,\n  72,205,201,252,142,185,96,62,98,179,230,229,116,235,214,42,173,118,61,172,161,42,183,187,212,188,84,55,225,57,222,117,\n  238,83,186,247,138,179,55,10,198,112,136,239,103,241,102,237,255,229,84,24,97,236,120,57,21,86,243,39,21,43,202,66,\n  48,164,175,107,215,150,229,216,135,43,161,40,172,110,220,88,53,192,82,4,134,189,166,73,83,89,211,212,73,63,53,107,\n  238,164,230,38,181,72,75,176,90,183,65,1,73,38,60,74,160,49,41,35,89,128,174,67,90,129,110,5,163,215,235,103,\n  46,136,215,143,119,196,243,157,101,236,213,134,203,202,242,8,208,210,249,169,120,9,41,151,253,230,160,156,205,250,176,78,\n  15,113,92,238,103,196,205,59,145,204,196,12,10,11,40,81,199,75,148,144,67,5,11,202,1,122,56,52,95,217,151,63,\n  191,236,132,108,160,240,88,12,203,183,36,132,148,97,137,133,51,96,126,140,64,129,62,183,118,205,132,152,199,56,48,72,\n  14,106,142,135,76,43,111,2,100,30,222,203,0,122,60,126,39,190,86,150,21,32,172,97,105,223,222,212,98,78,232,126,\n  207,233,117,117,84,136,177,147,94,125,85,14,149,42,37,9,48,95,61,10,142,12,132,73,2,132,9,63,187,23,194,103,\n  103,161,66,50,22,155,193,216,156,59,180,11,161,147,110,67,218,93,187,19,250,232,30,208,131,180,91,128,61,177,199,128,\n  38,233,38,73,236,105,126,56,14,154,215,223,45,91,202,57,155,25,88,202,207,142,13,76,151,218,0,215,74,252,111,172,\n  234,114,66,99,224,245,205,181,176,214,9,35,62,80,240,217,118,92,86,20,86,172,39,248,23,166,126,109,48,241,176,180,\n  189,230,223,80,112,239,79,60,33,39,104,225,216,16,84,86,188,137,150,21,221,84,11,222,121,87,202,233,174,154,198,193,\n  231,97,252,74,175,69,156,238,230,87,68,35,186,22,52,136,74,71,33,221,54,53,66,247,132,255,85,197,129,154,183,176,\n  37,60,204,20,213,207,32,196,141,4,130,189,160,167,204,120,135,78,213,37,234,241,76,38,220,176,223,3,219,24,207,132,\n  53,181,190,45,230,22,140,235,28,251,122,88,13,197,210,107,124,229,169,193,145,39,74,211,232,200,106,112,52,194,225,82,\n  180,9,74,105,5,134,41,60,255,130,226,197,100,1,227,172,52,48,44,224,174,124,253,147,138,149,28,8,205,65,112,89,\n  209,77,56,237,117,151,88,223,110,66,253,235,253,216,69,159,211,30,30,206,39,251,183,143,162,101,168,65,60,231,99,108,\n  7,217,191,102,27,172,8,133,53,102,9,11,38,105,48,176,142,53,62,141,125,120,44,38,70,14,189,253,182,139,176,80,\n  100,240,146,189,248,123,27,132,199,191,88,219,15,156,233,243,86,91,237,251,185,17,118,199,63,240,128,247,190,229,153,76,\n  196,185,98,119,192,88,12,234,91,31,218,218,90,180,89,167,239,242,129,222,167,235,198,83,111,244,44,34,60,62,131,118,\n  101,76,252,97,11,110,60,91,58,136,177,165,96,34,254,24,29,45,7,35,34,92,93,86,126,210,30,48,228,109,88,252,\n  181,80,16,154,184,50,173,209,197,124,236,150,86,84,187,44,34,13,48,188,90,15,62,40,255,117,236,40,231,53,131,180,\n  123,128,20,35,135,66,224,129,145,147,202,179,17,214,96,48,181,139,116,89,217,136,63,152,65,225,175,195,194,164,184,211,\n  157,120,212,200,40,234,206,245,154,91,161,130,131,217,217,8,62,38,165,186,200,106,202,106,88,126,149,96,93,27,207,200,\n  64,236,34,45,12,110,241,7,174,223,20,170,108,255,122,144,105,196,54,92,121,86,150,209,222,248,120,233,231,42,196,23,\n  89,232,198,86,243,39,166,47,179,97,18,49,190,90,130,185,44,175,91,87,142,209,199,206,185,178,24,57,221,71,86,99,\n  48,11,197,216,189,25,81,176,26,29,5,33,187,200,20,158,139,96,49,69,187,102,223,61,111,213,252,176,168,154,204,121,\n  19,93,195,20,98,118,93,86,176,116,254,171,92,69,218,61,244,176,57,231,83,34,124,236,58,26,229,138,189,150,71,41,\n  89,236,54,138,239,79,194,154,210,251,112,178,66,156,28,13,143,144,131,175,191,33,9,176,152,188,9,11,119,218,141,125,\n  176,25,22,216,186,71,30,145,166,58,214,172,199,55,162,184,214,118,215,149,135,148,37,36,250,37,215,222,217,48,105,250,\n  116,21,44,175,141,67,76,12,172,173,62,10,15,190,143,61,68,58,104,134,56,50,54,86,53,130,202,114,2,4,207,248,\n  81,213,170,230,196,83,171,120,60,29,225,241,34,107,111,154,226,217,118,209,101,5,237,128,238,168,64,4,199,62,208,46,\n  108,128,45,216,0,95,131,193,148,118,116,73,179,26,83,149,242,7,26,62,210,13,130,186,255,27,111,200,41,104,228,23,\n  237,194,96,19,116,13,27,252,235,34,69,221,25,249,91,6,52,200,4,186,253,86,16,246,123,242,20,7,252,122,160,194,\n  74,185,172,26,41,43,96,216,51,207,154,235,178,90,7,133,115,56,124,218,58,245,211,70,239,20,203,234,56,4,166,188,\n  189,82,101,48,136,135,204,251,157,211,26,228,157,254,244,110,119,3,38,44,71,161,58,228,189,247,156,29,236,2,205,248,\n  97,138,110,237,218,242,79,185,242,82,211,85,136,183,50,139,52,153,225,132,255,157,96,87,198,105,37,75,202,17,174,5,\n  153,232,149,214,195,196,171,240,76,227,202,252,154,130,93,63,255,235,152,239,35,109,159,126,70,78,211,138,178,129,34,204,\n  68,147,83,173,90,171,76,187,95,75,198,154,193,249,139,58,27,45,144,190,63,142,170,127,8,133,67,113,113,146,8,107,\n  70,241,14,211,181,237,7,239,216,9,203,155,46,171,111,114,231,150,178,158,120,7,251,59,179,98,151,208,30,151,188,248,\n  78,167,177,18,211,138,253,54,182,248,40,56,76,1,242,35,5,15,204,102,54,128,90,200,54,152,89,208,250,24,82,172,\n  152,233,63,101,240,237,129,116,250,3,52,227,198,101,117,235,161,210,165,37,225,149,87,2,182,58,246,97,179,88,62,203,\n  209,78,100,95,107,12,185,2,232,43,66,70,62,134,1,186,165,117,234,168,138,222,20,187,174,130,86,14,63,59,43,138,\n  141,3,251,61,153,184,190,103,78,6,96,171,99,157,247,66,171,77,25,27,184,171,64,185,172,218,182,83,169,144,155,161,\n  141,213,55,170,101,65,61,13,151,213,81,118,5,60,75,151,136,141,0,44,25,4,241,158,14,194,242,92,28,21,101,214,\n  175,144,198,90,76,41,144,158,246,26,91,73,173,197,114,2,19,218,40,84,75,54,172,163,175,138,134,169,196,8,195,74,\n  46,160,133,219,181,122,111,158,174,138,121,91,221,176,161,36,81,104,92,225,61,76,92,83,116,107,123,114,101,182,51,132,\n  103,123,158,161,217,16,176,182,93,86,12,206,55,113,184,172,152,221,104,236,139,237,58,5,218,47,197,46,198,49,190,81,\n  220,15,159,225,251,14,66,161,8,84,233,180,92,86,219,181,203,106,34,214,219,24,31,219,105,63,100,53,131,26,69,127,\n  124,154,238,126,151,40,222,49,161,66,5,181,80,211,125,236,133,238,41,254,193,46,131,236,14,24,135,135,252,147,104,167,\n  89,40,254,113,254,203,47,21,12,125,81,87,13,247,54,47,125,42,20,98,44,11,113,86,67,224,28,138,140,148,253,150,\n  153,25,136,203,74,251,44,255,132,217,217,220,213,236,156,232,11,56,163,135,241,61,136,239,88,95,5,150,234,246,102,205,\n  229,2,180,234,36,48,99,102,105,168,42,87,119,215,130,79,112,232,205,100,75,92,69,169,127,143,11,35,239,101,28,216,\n  146,204,218,233,15,11,236,2,173,14,27,193,107,43,190,66,38,185,60,34,66,74,56,11,158,78,88,25,112,22,220,251,\n  76,182,100,182,217,238,55,137,57,242,152,163,132,118,237,164,143,19,100,144,180,158,238,191,64,4,135,27,182,210,159,100,\n  228,123,216,92,205,134,43,207,74,32,160,53,230,86,85,189,82,195,179,240,126,197,216,110,151,125,226,127,193,154,41,107,\n  195,110,15,147,84,84,221,238,46,136,6,170,218,62,35,226,123,53,234,65,48,240,172,172,236,59,15,174,204,55,244,243,\n  223,138,179,249,77,153,91,111,149,191,137,230,108,167,241,149,17,156,223,85,185,138,116,204,155,215,220,27,51,173,224,124,\n  32,251,161,50,44,194,191,192,55,148,213,225,45,201,198,7,218,173,61,22,235,193,59,218,224,153,141,61,49,45,181,183,\n  11,11,111,216,74,243,163,248,248,75,203,116,53,92,121,83,12,180,12,6,245,157,15,125,208,211,35,162,238,50,117,141,\n  53,43,196,213,202,18,2,4,207,120,100,222,60,169,227,236,192,69,154,237,201,159,105,33,198,226,125,251,26,66,203,222,\n  73,151,85,193,130,182,180,7,203,101,229,102,118,94,176,16,82,3,216,160,197,216,251,133,53,6,9,96,174,7,160,225,\n  36,50,168,255,206,59,114,12,194,238,36,20,129,179,181,235,200,5,8,150,164,118,237,29,245,39,238,89,30,6,179,97,\n  101,236,81,104,205,43,194,35,84,229,170,30,223,73,171,9,84,180,110,145,76,109,234,107,106,215,83,108,186,172,116,29,\n  195,126,48,201,145,16,202,198,154,252,76,16,74,54,247,97,103,60,102,89,253,218,178,149,237,44,43,86,252,158,0,253,\n  7,33,217,208,213,101,245,190,191,110,9,15,107,17,158,138,173,52,102,76,192,243,146,106,141,213,246,104,141,117,179,16,\n  116,89,105,207,121,89,130,185,19,155,24,82,20,22,84,28,200,64,169,241,211,250,100,214,145,3,221,160,185,2,38,164,\n  82,145,74,248,251,132,73,80,0,78,64,32,159,134,0,185,208,19,223,23,12,224,63,203,149,249,172,139,43,243,59,171,\n  190,133,153,127,152,239,131,173,242,63,41,39,63,248,192,25,140,14,164,115,38,219,187,42,52,231,90,242,71,108,41,169,\n  232,236,145,193,204,182,26,188,223,123,254,239,7,133,181,213,5,188,102,63,206,98,130,21,8,15,208,221,253,159,118,89,\n  173,196,190,173,0,97,106,52,72,171,150,186,119,25,172,99,37,115,175,119,223,117,0,12,94,66,151,213,250,225,195,85,\n  3,40,66,182,255,227,214,122,214,170,42,223,228,161,51,161,39,247,21,63,79,215,23,37,248,64,104,149,103,22,47,190,\n  252,46,44,8,176,205,227,198,73,25,71,96,63,197,93,171,246,80,24,88,159,121,241,35,161,165,30,2,115,78,0,99,\n  182,229,178,210,27,96,188,171,217,153,166,47,183,47,155,211,196,243,249,4,86,192,161,152,24,217,143,113,186,248,83,117,\n  237,9,131,114,137,96,106,135,97,58,31,139,142,145,147,113,113,114,182,86,109,85,29,175,234,80,192,56,172,244,85,22,\n  234,141,118,101,228,191,233,34,51,222,239,1,75,187,222,53,120,136,164,140,27,111,203,101,117,78,185,172,234,202,86,88,\n  58,70,245,48,105,64,132,179,37,243,175,188,223,62,222,199,102,103,188,36,208,233,190,125,101,111,159,62,102,123,93,34,\n  12,68,105,235,243,86,29,140,190,73,7,162,175,211,138,5,173,194,107,40,60,115,131,106,120,134,234,87,133,106,159,87,\n  171,166,92,40,129,34,202,154,214,216,138,136,72,83,136,159,176,250,119,131,122,115,236,131,177,238,231,88,75,98,99,13,\n  40,52,8,115,115,12,123,129,53,47,20,90,100,162,68,49,80,200,6,62,80,34,20,137,195,80,4,142,15,30,44,103,\n  88,81,109,71,144,165,239,202,236,97,156,205,86,124,125,90,233,210,14,151,85,122,117,63,30,148,37,101,93,17,66,30,\n  130,242,12,91,96,151,46,35,59,113,62,102,228,203,103,102,98,178,146,255,9,127,93,86,122,63,244,103,151,191,143,95,\n  123,77,14,21,41,34,251,33,4,237,184,172,118,104,119,247,71,186,71,147,129,203,151,47,194,96,12,204,158,217,84,15,\n  230,201,37,77,215,197,125,38,87,169,162,22,138,86,131,187,213,193,222,227,195,97,130,245,133,84,94,239,67,32,157,255,\n  255,21,15,218,0,218,81,36,36,229,28,108,6,34,238,94,246,52,221,14,29,172,198,241,41,90,179,168,226,197,234,32,\n  98,236,60,154,204,223,194,236,60,4,237,193,142,203,202,74,179,163,217,217,202,155,217,233,159,102,163,224,225,43,224,187,\n  254,44,81,66,18,11,21,74,127,131,122,18,42,207,61,167,234,80,152,79,126,152,133,143,16,242,255,98,163,55,214,205,\n  188,244,248,134,24,193,249,40,90,58,189,94,127,67,206,211,234,176,225,42,48,115,234,87,69,21,51,161,55,78,235,180,\n  87,222,47,31,91,50,183,192,188,157,162,118,109,179,87,60,113,134,206,15,24,32,167,71,141,150,73,49,197,85,203,1,\n  194,1,225,89,183,128,126,1,125,135,49,44,99,220,145,117,37,172,151,0,205,5,205,4,125,4,250,16,52,30,52,154,\n  25,46,186,242,122,128,174,206,222,164,240,156,216,135,199,198,188,56,172,177,70,178,31,66,104,52,148,1,99,29,126,209,\n  113,39,38,112,236,169,118,31,172,97,186,39,109,88,56,212,240,105,89,144,81,211,215,207,162,213,31,49,47,172,123,33,\n  190,216,252,119,222,85,168,6,115,32,164,102,189,249,150,66,59,96,10,235,84,48,68,162,32,124,248,202,171,50,17,251,\n  103,2,94,251,48,60,92,214,119,233,162,192,16,147,109,20,112,102,32,60,45,87,230,205,92,35,98,156,173,39,154,179,\n  149,129,231,46,32,232,74,163,128,128,82,68,69,137,10,211,41,60,227,241,226,37,228,8,246,249,65,88,234,44,234,221,\n  141,243,193,44,166,13,56,155,237,93,179,239,230,89,13,200,252,60,155,119,209,50,44,15,229,121,45,230,37,17,247,177,\n  227,178,98,134,230,86,140,239,175,71,31,149,142,80,124,141,241,205,215,73,19,169,55,191,9,55,254,156,48,12,151,12,\n  112,16,130,131,130,170,1,6,88,214,131,203,138,130,224,39,8,130,56,237,106,25,66,112,64,31,227,31,75,193,136,216,\n  199,188,52,30,154,197,121,151,213,125,165,209,130,139,186,166,233,190,226,69,120,60,129,69,218,85,23,154,207,246,114,229,\n  36,241,157,119,108,185,172,44,159,229,10,152,157,229,93,205,206,170,17,129,185,73,222,195,115,156,104,15,179,120,95,217,\n  178,146,16,168,79,149,197,71,160,221,176,138,182,66,179,249,50,103,78,137,117,22,31,177,240,45,218,208,246,6,83,235,\n  249,162,114,21,73,26,61,70,146,192,32,85,245,188,75,124,165,183,79,113,150,84,151,21,152,22,147,17,140,228,129,181,\n  22,68,190,46,0,59,217,23,207,150,52,50,56,109,85,147,33,128,146,112,174,142,128,225,204,174,80,65,218,98,77,89,\n  5,28,143,61,207,202,240,184,28,57,164,60,246,42,179,151,74,227,240,199,102,191,89,74,222,148,93,152,196,82,2,2,\n  142,53,28,49,70,37,53,93,120,212,84,57,254,206,47,190,40,103,70,142,148,148,0,93,40,166,53,182,173,98,37,133,\n  62,96,48,138,65,225,14,11,104,36,53,218,89,165,74,59,226,42,1,8,41,75,112,168,222,41,96,210,59,112,175,121,\n  80,32,136,218,91,6,207,201,180,88,86,74,71,122,40,122,115,39,171,226,154,197,112,99,162,162,36,153,232,202,54,107,\n  45,148,240,140,247,40,60,239,182,250,214,99,95,36,52,123,236,113,57,62,100,136,36,97,174,47,64,17,57,215,176,161,\n  156,169,94,67,78,150,175,160,234,38,88,156,171,4,196,203,47,43,69,73,157,15,55,37,202,242,8,48,16,189,26,214,\n  104,37,167,176,74,49,193,23,253,60,155,170,112,177,109,174,92,178,151,46,43,236,111,59,46,171,93,24,223,102,140,239,\n  123,140,175,178,235,248,26,186,100,6,234,155,119,81,88,45,172,166,189,20,65,115,220,99,101,215,174,42,203,170,99,246,\n  236,202,202,240,132,162,27,205,67,2,42,14,98,64,125,171,143,25,88,179,240,94,34,244,178,33,213,38,102,231,92,14,\n  1,162,1,31,85,103,69,167,203,234,15,203,37,227,193,101,85,3,239,75,30,10,109,254,32,153,51,52,45,187,46,43,\n  110,128,73,96,82,145,174,133,129,143,5,152,162,75,19,94,105,131,135,96,121,4,195,167,202,241,141,116,45,62,98,175,\n  147,7,45,228,82,188,254,91,28,148,154,13,241,241,114,4,116,168,80,97,229,10,59,10,203,236,4,129,34,43,85,118,\n  184,195,32,20,46,226,48,51,120,207,170,217,180,2,166,151,163,55,117,221,122,178,189,82,37,105,246,224,131,46,57,235,\n  69,93,131,243,23,198,64,123,75,177,25,44,79,37,10,60,104,235,252,190,148,9,19,229,12,246,227,145,17,35,36,97,\n  240,16,217,221,191,191,236,232,211,71,182,245,234,37,155,241,222,127,187,117,151,191,187,116,149,245,157,58,201,58,140,247,\n  119,60,207,175,208,98,127,106,213,90,214,180,104,33,171,155,53,147,85,77,154,200,10,48,187,111,26,52,144,157,244,247,\n  219,104,76,229,176,198,28,90,247,247,209,209,82,26,140,92,175,197,25,109,141,61,201,58,176,218,56,83,251,57,143,1,\n  90,98,12,112,43,204,168,154,181,228,223,242,229,165,247,227,249,20,146,64,152,27,220,134,63,164,226,96,181,107,251,87,\n  24,233,86,39,194,88,137,5,15,178,53,46,78,154,184,10,207,129,198,217,108,204,215,199,194,2,58,86,163,134,202,100,\n  98,113,93,130,101,121,187,91,217,233,164,196,154,133,119,211,161,32,27,13,200,88,140,249,116,0,130,67,241,111,133,131,\n  7,161,117,176,104,209,160,185,172,102,98,62,140,241,237,79,131,6,30,225,140,123,156,238,197,124,241,75,16,247,96,6,\n  82,119,104,30,81,236,73,238,165,127,199,8,34,232,98,131,176,133,107,121,48,152,242,108,247,8,171,194,151,160,250,38,\n  253,121,78,40,219,212,38,176,0,242,50,212,176,176,242,93,199,59,146,245,2,76,138,116,203,114,50,16,99,103,49,69,\n  114,25,24,215,33,28,100,21,79,176,153,102,183,1,102,103,91,87,151,213,156,0,51,57,84,113,84,89,8,250,223,160,\n  97,29,12,130,79,117,187,206,2,107,234,90,184,56,86,107,187,188,103,17,236,201,83,29,25,156,175,87,79,18,233,198,\n  163,54,231,201,29,134,177,28,120,225,69,71,240,254,173,183,228,112,225,194,114,20,90,169,18,48,21,43,202,169,106,213,\n  228,72,149,170,202,98,250,174,72,81,147,73,210,210,41,110,28,66,226,89,37,19,82,67,85,68,91,217,68,118,107,23,\n  24,36,197,119,41,33,194,148,120,171,98,122,132,174,148,38,3,100,221,0,5,22,173,255,81,186,34,155,149,217,86,149,\n  54,81,20,232,107,167,50,52,118,156,227,53,90,2,182,181,110,135,53,70,151,80,184,107,54,216,253,172,120,87,76,169,\n  120,241,128,173,14,43,179,136,53,20,204,44,26,132,245,119,195,104,186,160,149,134,249,186,56,110,156,70,53,24,170,25,\n  120,63,198,92,180,242,66,36,132,33,248,236,81,118,240,219,77,161,105,181,3,246,84,72,104,245,84,103,223,19,88,62,\n  140,183,17,142,131,202,198,89,8,140,147,216,19,137,120,182,157,5,223,145,165,216,67,177,78,11,157,174,204,200,8,167,\n  103,230,51,102,230,173,194,158,82,25,144,170,104,247,201,128,61,2,155,181,75,168,179,171,75,232,11,11,65,218,207,179,\n  73,28,188,21,180,224,126,134,224,72,76,15,202,200,15,151,213,223,24,95,87,221,189,213,29,109,218,83,154,215,186,170,\n  144,132,123,166,77,203,92,70,11,171,227,207,161,67,37,22,76,173,1,22,196,83,97,224,70,104,134,12,162,199,194,148,\n  167,43,237,211,198,141,37,10,239,173,71,216,101,47,144,237,158,10,8,187,128,49,209,101,212,187,80,33,57,113,169,177,\n  187,48,135,115,235,215,55,221,69,201,86,166,66,88,218,249,39,98,236,246,90,16,146,91,193,224,18,109,230,104,91,46,\n  171,85,15,61,36,113,206,3,225,210,151,219,207,13,170,138,163,90,194,146,219,131,241,29,128,245,97,119,131,110,195,248,\n  150,229,206,45,101,92,139,143,202,186,35,151,206,198,92,28,169,83,71,14,188,251,110,198,247,244,164,1,130,84,202,50,\n  93,5,16,88,163,176,127,12,198,245,151,213,35,221,104,252,36,83,193,32,88,252,120,161,117,27,229,191,102,230,24,153,\n  15,153,16,153,81,106,243,29,247,138,231,158,189,253,175,142,182,200,170,194,246,70,186,90,59,69,83,106,197,182,205,30,\n  42,212,186,217,248,169,21,214,214,96,20,99,180,229,247,179,42,150,236,208,33,240,88,135,238,17,66,72,255,229,225,17,\n  102,172,137,180,85,187,106,104,109,94,79,11,176,8,40,46,227,44,179,83,61,94,122,89,206,14,28,40,23,9,185,209,\n  172,185,156,107,216,72,101,250,17,122,131,113,134,19,165,74,203,49,40,97,71,138,134,201,97,236,157,131,216,179,140,183,\n  29,128,82,166,44,6,236,37,197,40,161,97,111,4,163,28,1,37,214,24,215,58,45,60,121,191,167,216,130,184,1,44,\n  120,149,1,105,195,157,76,143,128,149,197,244,195,195,15,75,21,167,75,72,52,212,124,32,133,129,175,96,62,14,53,103,\n  81,49,132,155,95,80,70,233,184,172,126,204,147,71,226,93,199,215,42,13,239,48,50,105,134,51,176,251,37,123,37,100,\n  162,235,234,34,44,155,65,56,156,28,212,20,15,45,103,201,248,127,192,66,149,131,185,212,136,216,66,159,125,38,231,96,\n  169,12,197,70,224,230,238,12,129,240,183,23,216,118,247,239,249,13,130,169,25,181,76,124,215,40,104,161,103,151,44,185,\n  52,2,4,247,56,187,120,177,180,195,66,22,117,54,191,97,101,121,126,47,46,43,106,188,23,7,98,67,31,196,6,77,\n  128,121,28,40,115,182,54,40,55,192,84,87,151,85,154,251,251,97,22,183,229,122,125,72,205,30,90,185,93,159,170,26,\n  31,132,199,184,180,197,71,15,155,200,165,229,177,214,235,42,85,146,195,160,64,51,207,172,42,123,206,199,58,15,150,78,\n  49,88,58,134,107,174,18,93,135,140,137,28,198,126,57,80,160,128,242,95,51,115,140,190,236,195,96,28,12,124,210,109,\n  118,12,26,43,25,20,253,221,167,160,81,19,137,148,204,235,28,52,236,243,141,155,200,133,230,45,84,102,13,181,93,37,\n  124,8,220,71,151,90,231,46,202,173,166,92,107,166,32,242,148,165,147,137,100,85,56,51,203,233,167,18,4,229,203,110,\n  10,241,88,221,2,249,84,55,204,197,121,106,247,166,21,230,11,185,193,156,39,212,168,41,195,93,211,96,119,89,0,161,\n  17,254,237,69,38,12,200,92,174,5,211,197,113,86,152,221,103,9,4,23,37,2,235,238,205,157,100,50,202,181,216,23,\n  110,208,61,35,141,61,81,143,110,231,15,112,15,229,78,182,145,1,105,22,222,205,6,111,42,230,116,9,29,240,6,89,\n  228,195,124,180,228,184,199,179,85,3,93,86,54,160,140,246,25,46,171,143,193,99,163,93,27,216,165,137,213,154,131,96,\n  102,203,233,174,48,123,232,86,202,44,109,124,195,240,225,42,152,77,56,146,63,60,88,29,20,38,51,238,188,83,109,100,\n  6,155,173,207,29,252,248,99,229,130,226,195,140,198,231,125,45,32,92,13,6,202,10,116,102,96,77,169,82,229,210,64,\n  152,96,188,127,141,24,33,165,29,45,27,147,244,2,124,226,158,73,161,53,13,166,102,78,161,15,248,75,44,126,106,10,\n  172,205,13,74,179,184,131,107,38,7,51,121,110,12,96,131,50,211,228,43,162,241,174,41,86,44,45,60,124,128,227,91,\n  143,241,185,101,129,77,181,178,192,200,84,84,0,144,57,235,116,89,113,78,2,204,60,51,83,150,151,166,181,116,202,68,\n  184,198,117,138,19,222,97,8,52,203,131,102,117,191,23,139,38,13,83,162,11,141,96,148,96,100,100,104,244,139,39,82,\n  248,128,225,28,100,95,22,156,173,67,5,223,129,38,252,158,114,173,29,193,92,42,65,4,197,232,120,137,146,202,205,118,\n  2,12,74,9,164,138,149,228,52,246,235,233,248,120,57,83,173,186,156,1,243,101,124,135,238,150,115,117,235,41,33,117,\n  174,65,67,57,15,141,155,110,24,10,44,102,248,156,111,218,84,129,223,81,27,167,0,243,70,103,97,205,31,130,150,190,\n  183,76,89,153,10,1,97,8,241,77,26,125,128,21,247,242,41,132,228,5,8,64,222,143,144,255,103,97,5,158,169,85,\n  75,33,177,158,174,86,77,78,87,173,10,225,89,89,105,251,39,203,151,87,173,1,142,199,198,202,113,124,142,181,63,71,\n  194,195,101,63,172,199,237,176,254,187,193,186,49,146,71,22,106,76,175,34,62,80,152,38,34,248,174,35,148,199,90,236,\n  137,68,90,163,54,172,0,11,125,129,251,194,128,238,57,167,133,167,194,241,194,107,159,48,3,114,69,68,132,35,3,210,\n  198,217,180,60,2,116,9,117,119,117,9,125,153,198,37,228,219,217,116,22,21,99,126,15,6,201,101,245,15,198,215,211,\n  117,124,169,32,165,233,165,123,253,80,22,31,218,72,95,107,38,184,174,200,184,251,66,115,227,34,77,246,96,117,88,41,\n  186,236,235,65,184,145,159,250,244,113,90,65,24,207,198,81,163,164,42,36,98,73,47,177,18,111,2,228,27,104,184,241,\n  204,86,193,119,78,135,134,152,233,2,196,89,57,159,162,177,106,146,116,151,52,79,245,29,15,49,85,186,58,4,230,38,\n  186,172,50,74,129,245,97,131,114,3,120,200,228,104,24,160,203,234,121,98,109,53,134,160,255,79,23,6,218,173,92,229,\n  248,190,245,146,5,166,169,27,95,159,94,176,160,28,169,91,87,14,216,112,227,41,151,21,238,71,109,111,236,61,247,152,\n  76,242,223,84,152,5,87,23,192,145,182,152,187,253,88,191,4,155,135,209,103,193,227,73,67,246,20,120,229,88,44,162,\n  144,178,4,21,9,2,61,149,168,137,103,64,123,240,153,45,248,254,13,96,160,173,92,149,140,41,218,143,254,13,253,232,\n  191,66,200,37,190,254,134,99,254,205,251,103,244,140,124,38,16,97,189,119,227,253,255,189,253,182,76,7,227,141,2,147,\n  214,125,72,46,48,13,219,71,58,171,233,92,97,236,229,118,204,248,163,112,183,97,161,91,140,114,35,246,197,24,87,232,\n  158,127,44,232,30,166,110,99,94,254,171,139,255,171,12,72,59,194,202,40,188,83,46,33,87,247,93,235,0,207,230,211,\n  170,168,24,252,109,7,148,144,160,184,172,48,39,63,97,124,213,49,62,99,79,116,240,58,62,227,208,182,81,38,16,209,\n  68,51,9,199,138,77,159,24,235,88,231,197,234,88,5,75,129,233,187,76,227,77,83,119,2,1,194,186,137,18,248,142,\n  170,216,132,43,125,68,225,229,123,24,108,103,15,16,10,16,54,145,162,43,44,83,4,8,59,35,206,156,41,53,161,205,\n  132,57,173,142,127,45,151,140,135,121,47,75,109,183,15,54,115,34,52,183,4,27,176,2,102,22,147,91,38,199,126,221,\n  217,205,231,43,220,45,211,100,12,180,232,67,208,40,237,110,80,203,101,53,217,213,165,182,211,202,2,115,9,206,199,197,\n  201,97,104,223,138,73,216,168,178,231,253,24,156,111,225,10,209,242,97,184,81,233,111,100,120,253,202,90,150,181,176,2,\n  14,70,69,217,210,52,179,42,89,90,55,5,42,83,185,203,185,10,241,138,26,157,245,191,6,56,51,59,96,29,217,201,\n  172,83,214,38,24,238,222,55,222,144,157,37,74,200,39,80,8,134,64,192,209,69,219,31,255,235,155,14,245,211,212,159,\n  239,213,52,16,159,37,116,143,157,181,49,93,86,233,65,247,176,143,9,207,176,75,6,100,128,103,211,116,89,205,117,117,\n  9,177,1,217,171,1,186,172,234,42,151,26,190,63,49,8,30,1,203,101,53,15,227,139,113,142,47,21,109,58,163,1,\n  61,78,184,237,106,96,182,65,13,156,107,152,142,22,88,132,98,244,87,122,177,26,182,106,152,117,106,38,83,9,151,226,\n  129,185,95,92,182,76,38,195,76,102,39,193,102,16,4,191,251,136,196,203,251,125,137,195,64,11,132,46,172,177,216,12,\n  167,216,61,49,216,22,22,190,111,94,195,134,18,225,152,252,11,86,225,91,49,15,86,135,206,44,26,199,180,195,133,208,\n  240,14,219,76,129,181,54,232,223,105,51,57,82,97,181,253,220,160,44,92,92,160,50,77,104,182,211,5,17,4,151,21,\n  93,106,237,92,181,221,185,150,75,207,10,206,183,130,240,221,71,151,21,230,36,96,38,97,184,172,150,227,251,202,57,93,\n  19,23,53,147,204,230,161,47,183,178,122,134,177,160,177,98,69,71,128,212,198,51,103,69,50,173,177,15,33,196,221,64,\n  249,136,62,240,46,93,216,61,242,230,149,4,155,76,41,117,45,104,241,64,112,48,102,118,168,82,37,57,4,5,238,160,\n  69,56,235,105,200,248,255,33,139,152,174,13,101,226,32,207,137,133,24,107,131,81,254,155,22,49,214,132,238,97,6,228,\n  76,51,3,50,33,8,46,43,186,132,122,185,118,203,92,238,9,235,206,135,179,73,151,218,199,116,169,125,131,121,61,72,\n  244,237,32,185,172,250,186,142,239,187,12,91,16,27,77,94,216,83,88,166,85,175,30,52,205,156,149,222,83,8,75,14,\n  134,202,128,247,70,15,80,36,86,133,120,117,44,86,5,102,29,77,152,224,153,177,19,19,235,139,47,132,105,197,124,192,\n  158,208,26,254,241,33,128,110,9,144,101,176,86,106,210,157,3,134,61,144,155,130,125,64,130,40,36,25,155,105,224,232,\n  195,157,172,51,156,18,45,100,82,15,27,224,127,120,223,223,85,233,42,44,83,70,18,33,64,130,225,178,242,144,201,209,\n  220,61,203,203,199,13,154,159,121,254,245,88,184,88,186,116,250,29,13,253,116,169,85,116,106,187,116,169,213,117,71,46,\n  157,252,230,155,114,132,48,14,156,19,27,76,98,155,103,100,208,109,160,71,188,172,201,163,184,255,6,246,83,89,92,180,\n  168,28,134,21,174,48,198,24,115,177,235,194,202,10,86,135,97,141,177,194,185,173,171,16,159,93,200,49,7,85,169,209,\n  142,165,198,109,51,45,219,133,232,94,99,1,29,172,16,182,26,224,188,38,104,226,239,20,212,230,107,169,175,91,132,207,\n  36,96,95,168,88,148,141,49,81,120,110,213,194,115,130,23,232,30,238,15,204,193,182,96,100,64,154,46,171,159,243,228,\n  145,26,174,46,161,142,1,186,172,152,161,185,131,61,112,182,64,177,59,96,7,125,219,176,196,126,193,248,106,57,219,205,\n  166,226,155,69,250,56,168,103,105,178,86,207,153,83,118,127,244,145,125,198,138,207,179,135,119,41,104,194,116,27,173,246,\n  2,128,72,230,63,94,7,105,134,21,47,46,201,233,245,38,103,31,144,25,51,20,168,162,21,64,223,236,7,10,47,93,\n  99,141,244,2,50,35,106,219,196,137,193,17,32,248,142,79,26,52,176,172,142,139,70,32,248,6,47,140,170,4,253,184,\n  61,192,224,14,208,199,110,35,5,214,116,9,185,101,114,80,120,189,20,160,89,92,83,21,46,50,128,28,36,151,21,181,\n  47,111,197,81,26,185,116,25,235,48,126,46,95,94,14,67,225,80,26,166,13,97,181,217,51,50,232,12,79,16,45,134,\n  171,174,34,59,108,86,4,99,165,0,73,140,139,147,131,180,186,94,123,77,105,208,123,177,70,123,245,51,209,186,217,167,\n  127,55,159,53,75,187,172,116,133,179,135,84,238,90,250,249,91,240,181,89,132,146,97,12,206,70,218,184,71,50,99,39,\n  190,82,122,49,151,64,92,153,120,126,238,139,214,174,251,226,35,35,105,163,146,149,1,153,104,51,3,210,116,89,205,7,\n  255,241,203,37,228,118,21,51,50,52,195,56,62,242,142,32,186,172,22,96,124,197,157,227,59,158,94,203,108,79,0,120,\n  116,165,244,227,230,97,123,88,91,248,80,96,166,59,39,79,150,186,88,164,104,110,70,47,85,226,86,95,14,198,49,202,\n  67,146,254,235,75,192,30,255,255,251,131,15,84,0,157,237,104,103,251,88,129,110,9,16,214,139,176,145,20,159,179,38,\n  14,17,161,76,146,248,172,129,90,91,24,15,93,125,53,29,232,169,150,213,113,72,183,15,77,51,207,165,28,63,71,16,\n  106,98,1,180,154,195,54,83,96,173,13,250,79,218,76,142,175,253,237,27,161,55,39,15,209,12,154,237,75,161,125,30,\n  178,217,209,48,29,151,90,106,113,20,145,75,9,251,221,140,189,219,235,214,117,8,172,0,221,120,166,203,202,27,50,104,\n  58,207,206,66,202,86,120,255,41,90,32,116,97,173,195,88,246,195,250,218,135,121,216,5,13,120,39,4,233,78,48,180,\n  157,96,68,20,138,255,225,39,181,55,50,38,139,118,27,63,77,218,99,252,220,163,235,80,72,187,53,153,175,237,161,160,\n  194,253,247,66,104,237,51,211,81,131,224,178,114,3,189,75,77,229,214,61,44,228,19,130,236,101,134,240,200,34,194,51,\n  157,164,141,52,25,144,118,220,201,166,203,170,31,248,148,95,46,33,207,251,147,227,251,144,173,130,151,176,119,7,45,99,\n  59,46,43,109,137,177,222,101,128,235,248,214,88,205,202,252,25,220,99,152,208,191,203,229,200,161,144,111,3,210,202,241,\n  25,182,134,237,88,160,128,26,204,160,116,240,169,248,122,63,104,0,140,117,140,135,198,233,179,192,194,61,86,117,237,170,\n  82,127,89,129,190,216,199,10,116,75,96,173,135,224,25,138,113,81,19,96,65,34,83,121,143,125,250,105,64,207,155,4,\n  75,137,113,20,35,195,74,116,111,225,235,35,188,227,239,175,101,91,210,191,192,148,236,230,104,91,62,75,102,74,84,115,\n  205,228,104,27,160,89,172,218,205,178,171,220,150,82,165,36,49,72,62,213,53,15,63,44,85,61,184,212,204,156,245,9,\n  96,90,71,234,215,151,3,54,92,38,166,203,106,138,107,112,222,21,25,52,29,159,178,22,32,39,56,86,90,33,189,240,\n  125,243,223,121,71,126,137,142,150,127,33,68,182,96,111,111,214,214,13,105,139,69,120,159,73,91,61,208,54,131,182,122,\n  248,93,253,164,70,248,234,171,178,11,123,99,15,238,183,143,110,67,155,241,7,179,194,217,13,244,238,83,11,244,142,77,\n  159,248,204,51,88,215,67,173,54,88,110,171,44,24,239,241,4,221,163,219,251,6,37,3,210,116,89,253,154,55,175,212,\n  118,117,9,117,15,240,108,230,194,119,108,172,70,119,55,214,199,142,203,202,180,196,126,195,248,234,184,142,175,143,95,227,\n  11,119,230,189,55,196,151,92,232,244,250,235,42,198,224,151,70,78,92,167,133,11,101,16,54,60,7,210,54,123,118,175,\n  45,102,201,236,231,131,65,21,199,251,104,161,208,29,229,15,243,78,6,205,111,212,72,101,81,85,135,22,177,210,143,62,\n  232,91,181,224,154,131,77,66,151,90,24,4,16,251,161,175,31,58,84,125,175,207,207,188,114,165,252,58,96,128,5,69,\n  146,164,253,248,59,173,194,159,98,233,225,239,19,126,131,126,117,27,41,176,166,203,202,45,147,227,176,167,120,139,143,27,\n  180,2,211,41,217,207,58,17,194,35,193,166,79,213,114,89,205,241,226,82,211,245,36,139,99,33,88,126,40,83,70,142,\n  84,171,102,203,141,103,49,73,66,180,180,247,18,156,207,230,155,0,137,103,1,163,5,202,199,228,6,246,95,104,129,231,\n  232,15,11,105,28,180,119,106,240,179,240,247,28,204,253,39,220,207,160,207,240,63,210,231,160,133,185,114,201,34,208,98,\n  77,75,64,95,146,114,231,150,175,64,95,107,90,170,105,25,52,226,111,64,203,49,246,85,96,224,107,138,23,151,191,42,\n  87,150,125,176,78,247,219,237,44,233,29,148,175,81,132,107,6,224,197,33,44,90,101,112,154,238,202,171,32,222,99,102,\n  223,41,232,30,183,120,143,165,232,233,231,191,208,215,202,128,12,146,203,234,115,186,132,156,189,209,143,91,144,247,1,184,\n  147,85,131,180,158,224,151,76,104,72,176,129,190,109,22,6,126,129,189,90,194,57,190,212,190,58,129,48,15,194,49,127,\n  193,188,236,121,108,196,227,43,35,101,117,245,146,37,74,11,103,80,154,177,5,111,144,34,219,116,53,121,13,48,125,166,\n  240,174,232,212,201,127,173,31,247,99,221,198,196,184,56,137,192,88,27,226,126,116,129,109,243,179,27,33,227,32,237,32,\n  228,56,113,229,32,76,104,133,28,156,51,199,49,158,244,158,29,255,59,60,111,158,180,130,70,168,173,14,11,138,164,67,\n  97,15,82,219,216,0,3,233,178,154,75,120,114,155,241,4,107,131,50,103,189,183,107,166,196,183,86,39,56,127,214,62,\n  220,234,27,142,245,91,244,222,123,182,59,26,90,62,85,15,197,71,203,172,226,35,130,174,225,245,132,70,96,194,187,234,\n  212,113,20,233,217,112,89,89,218,222,119,94,130,243,225,254,29,214,39,137,240,171,179,145,146,76,116,87,203,130,34,78,\n  27,133,34,137,194,59,198,160,226,22,97,62,75,104,42,169,41,214,160,82,36,236,225,210,154,88,208,88,22,251,185,12,\n  246,101,99,194,246,48,227,199,70,218,114,58,160,124,169,169,220,214,243,18,134,157,245,13,91,89,223,16,30,238,112,169,\n  94,225,238,43,95,226,61,122,239,143,79,205,128,132,224,182,227,178,218,163,93,86,116,9,13,114,117,9,253,196,218,58,\n  127,207,102,148,118,119,115,237,62,37,242,129,77,244,109,211,101,53,216,181,119,253,47,238,32,174,62,93,81,206,77,244,\n  6,179,109,42,98,19,41,247,85,70,176,37,96,164,172,159,152,84,177,162,74,135,173,9,90,149,78,128,124,45,24,69,\n  107,28,12,102,97,81,216,92,12,20,148,81,91,58,131,163,162,212,119,181,132,233,245,155,15,24,88,238,2,132,120,88,\n  44,94,172,76,43,4,223,211,16,147,186,180,109,91,71,74,47,159,221,131,16,161,187,138,5,129,17,78,191,169,197,180,\n  239,139,240,161,55,198,58,186,132,210,9,120,237,203,136,232,39,215,46,33,102,114,212,116,205,228,232,28,32,94,78,78,\n  43,11,236,31,8,54,102,193,236,131,230,181,79,67,74,251,66,123,13,50,199,87,195,75,241,17,53,95,190,62,26,154,\n  245,225,250,245,149,70,181,15,135,194,159,123,90,164,176,179,52,147,156,70,38,233,188,223,30,98,21,5,104,137,93,171,\n  123,75,215,209,90,42,107,119,78,69,56,17,147,253,166,112,31,137,243,82,213,114,81,216,80,50,210,1,229,91,104,165,\n  114,27,22,215,20,42,55,227,176,30,137,76,153,37,212,55,45,65,166,171,114,93,50,72,12,112,223,167,89,198,101,165,\n  247,69,58,241,158,156,193,202,128,52,149,152,223,243,230,149,122,228,117,206,123,246,11,208,101,117,31,246,196,31,149,216,\n  231,168,104,81,57,16,0,92,138,185,46,86,150,21,199,87,223,117,124,3,253,29,159,39,173,139,109,106,207,183,100,222,\n  187,165,137,123,137,63,176,123,223,68,48,82,130,24,86,99,254,177,23,23,146,138,55,64,112,116,213,120,50,93,223,124,\n  211,17,107,176,147,26,140,251,179,168,144,40,188,69,181,171,236,15,31,107,64,204,113,145,190,135,192,99,10,112,9,28,\n  30,62,75,59,28,32,6,212,207,44,90,228,42,68,112,207,229,29,59,74,44,222,27,238,196,176,58,160,97,23,60,166,\n  183,233,57,45,204,190,17,237,97,118,238,193,193,220,251,238,187,178,11,204,217,10,180,254,231,3,81,131,178,200,74,59,\n  116,203,228,56,6,122,219,159,197,47,236,10,211,113,182,27,3,186,149,43,203,46,88,71,12,14,239,192,223,59,112,63,\n  127,201,26,159,183,226,163,212,122,18,54,194,226,129,173,93,91,118,97,79,236,116,123,78,95,136,247,219,166,173,48,186,\n  38,58,185,50,201,207,252,69,46,53,175,34,78,151,46,221,27,57,117,179,160,250,26,245,117,20,104,50,104,186,22,46,\n  243,244,253,190,208,117,54,75,52,12,197,215,218,226,34,228,195,10,173,104,176,87,248,42,29,64,253,94,211,26,77,251,\n  184,159,187,19,170,5,204,34,33,192,152,7,25,133,149,64,224,214,167,129,212,44,194,21,231,142,244,34,254,191,133,53,\n  62,147,96,237,236,138,143,151,195,176,238,15,192,10,221,251,214,91,178,27,66,108,55,198,178,75,187,130,130,77,187,131,\n  76,187,244,222,253,87,239,139,142,110,208,61,70,188,71,185,132,122,224,189,251,160,4,239,129,192,220,173,21,160,64,238,\n  105,237,253,69,57,115,42,75,83,223,239,148,134,91,9,132,39,135,41,180,105,236,135,221,88,139,221,207,63,31,248,60,\n  235,179,98,142,207,189,65,90,192,151,149,62,201,67,193,47,37,160,161,199,246,174,96,162,199,22,44,144,17,37,74,40,\n  215,17,221,80,75,189,4,175,249,26,171,203,187,233,170,206,150,144,234,123,167,79,15,90,170,44,5,28,227,52,252,110,\n  194,156,176,136,208,223,222,232,219,116,44,100,225,221,119,75,43,88,49,212,92,163,241,179,3,164,60,3,244,236,189,46,\n  171,86,201,223,35,71,74,188,163,55,132,213,37,240,162,214,166,175,137,72,95,32,179,21,173,204,164,230,208,168,145,252,\n  7,173,110,219,75,47,201,22,29,23,176,72,5,98,177,184,169,100,189,102,208,38,13,177,240,15,168,191,171,89,252,189,\n  118,61,6,210,110,118,24,205,226,121,68,233,196,248,118,150,44,41,219,192,64,54,227,16,89,247,116,31,67,122,100,141,\n  207,45,211,100,181,53,62,203,77,194,22,160,219,26,54,148,189,53,107,202,86,220,111,19,125,177,238,223,199,215,210,35,\n  222,79,223,115,13,14,152,27,147,108,226,111,189,139,175,233,147,236,57,173,251,130,92,163,173,148,235,180,144,185,33,210,\n  161,201,223,104,81,164,67,128,17,151,232,102,141,105,116,139,62,103,183,234,130,177,219,245,239,143,19,217,150,133,96,95,\n  129,137,217,193,46,50,93,86,110,125,26,18,8,65,227,161,128,149,63,99,240,115,23,93,56,173,115,231,150,133,216,175,\n  27,161,28,254,71,194,158,216,89,164,136,108,135,98,181,21,223,237,146,36,144,78,242,128,183,4,130,140,254,111,151,182,\n  88,123,67,11,79,79,208,61,181,28,207,60,146,115,51,159,150,47,132,199,118,156,249,173,84,128,2,188,39,239,71,26,\n  230,218,183,230,119,208,189,254,34,62,232,179,217,151,22,225,76,40,116,123,162,163,101,27,248,167,47,227,216,234,97,29,\n  182,104,193,198,241,13,119,29,223,90,111,158,19,159,175,48,39,179,123,24,95,188,154,241,15,66,123,40,247,146,161,125,\n  51,69,181,27,54,54,93,61,132,77,95,225,197,226,216,166,83,114,223,215,230,17,43,206,153,202,27,212,42,111,124,87,\n  194,172,89,210,65,103,121,181,193,189,126,241,51,6,98,142,151,8,190,159,220,117,151,52,191,241,70,85,29,207,192,60,\n  1,26,231,214,171,39,77,112,104,194,156,62,83,171,95,70,142,12,210,64,115,16,67,140,90,246,148,183,223,150,47,139,\n  23,151,47,240,243,83,104,2,243,114,229,146,121,184,167,175,52,95,19,127,103,176,182,186,107,150,85,175,0,205,226,123,\n  241,29,191,115,124,163,160,93,206,46,84,72,102,96,46,63,194,1,154,130,251,76,198,92,154,52,5,52,213,7,98,102,\n  139,27,158,79,79,67,152,214,161,0,110,142,247,44,40,92,88,230,193,234,152,3,237,112,54,158,201,162,57,6,125,140,\n  113,88,52,23,244,137,65,214,220,124,202,158,46,56,16,197,210,97,146,89,241,50,52,127,250,155,39,112,94,104,117,236,\n  161,213,97,51,93,212,114,89,117,113,181,198,150,120,2,229,51,138,134,217,239,100,7,223,207,78,134,213,160,0,116,132,\n  197,204,244,101,34,185,78,192,247,77,196,154,76,196,218,113,141,173,253,64,183,16,93,134,211,32,168,166,107,154,161,105,\n  166,166,89,222,214,87,147,185,182,115,141,181,158,235,129,62,241,225,188,88,201,12,195,92,247,197,62,35,222,243,0,232,\n  79,166,167,19,30,101,52,4,245,72,104,228,35,161,8,143,6,141,5,95,35,18,244,120,60,39,159,151,141,214,172,51,\n  240,145,126,86,235,249,102,187,61,139,91,150,213,144,0,207,38,211,102,215,112,124,195,193,131,166,131,127,78,6,207,80,\n  103,81,143,37,149,140,177,165,71,147,245,186,213,116,246,184,33,13,15,15,212,101,229,165,112,170,0,126,223,88,2,204,\n  120,65,227,198,42,157,54,5,2,228,247,129,3,85,108,128,19,67,45,125,141,135,24,135,229,58,162,38,95,7,194,133,\n  66,166,19,52,203,76,235,29,66,1,50,123,182,116,129,182,198,113,53,1,211,250,206,75,236,197,23,87,150,21,15,97,\n  86,216,251,120,198,226,142,94,212,214,102,176,124,222,191,106,159,120,70,27,128,221,184,18,233,111,101,251,205,84,210,193,\n  86,127,41,90,147,113,24,172,254,203,133,2,52,139,159,215,16,204,146,137,148,154,201,161,247,23,251,71,40,31,52,181,\n  62,23,242,240,154,175,115,18,229,58,39,94,153,164,214,252,31,210,248,99,193,38,86,44,231,117,163,71,116,90,232,227,\n  108,63,172,139,36,57,239,111,232,38,68,77,48,47,223,98,143,37,53,2,179,218,0,13,63,209,14,230,153,17,40,246,\n  128,62,208,194,155,53,102,88,162,111,105,119,219,249,112,7,168,97,106,178,128,73,230,26,71,122,161,40,79,228,231,250,\n  218,33,15,251,98,145,17,239,121,90,39,15,136,123,82,68,184,31,207,107,62,83,177,180,103,147,93,26,139,5,120,54,\n  243,107,97,151,153,103,147,13,210,98,172,224,188,237,203,132,109,199,164,237,46,117,235,173,242,89,147,38,74,251,46,7,\n  134,202,201,234,67,48,57,55,23,145,197,120,25,188,102,61,69,44,23,15,140,124,100,108,172,194,186,202,212,166,83,248,\n  110,66,143,244,131,198,198,172,47,186,210,190,128,240,50,133,89,32,66,132,80,40,75,160,133,244,186,229,22,169,8,13,\n  32,194,185,193,216,64,166,158,102,8,42,229,175,164,119,237,97,186,157,64,171,15,244,179,213,127,57,128,117,38,35,29,\n  102,212,170,100,6,165,102,114,88,13,126,116,106,115,102,30,138,86,238,113,40,35,56,60,12,235,183,147,13,185,138,6,\n  159,118,184,209,78,208,127,160,93,160,61,69,29,49,141,3,160,195,132,161,167,191,157,214,6,99,13,93,192,232,255,164,\n  224,96,141,141,205,206,141,94,92,86,76,149,126,49,189,125,82,212,117,223,86,210,29,255,118,105,232,114,185,10,168,185,\n  165,196,132,59,246,194,251,58,38,145,89,247,251,83,91,56,129,156,77,10,185,190,186,157,64,102,142,239,193,160,90,232,\n  102,14,56,38,249,8,133,0,227,27,21,192,152,167,230,200,161,240,170,182,186,49,90,214,118,176,247,56,251,105,132,233,\n  158,226,108,54,117,73,122,106,104,1,194,248,4,179,161,24,179,40,133,67,67,40,147,245,1,196,65,220,221,89,155,117,\n  154,49,33,85,152,142,204,224,58,17,56,195,28,69,104,132,57,40,167,23,33,53,254,209,212,40,16,212,155,128,61,62,\n  62,14,34,205,213,63,43,4,154,41,161,63,119,135,238,108,54,92,11,18,95,104,132,143,196,22,163,197,139,187,238,169,\n  108,58,201,128,45,72,39,25,52,89,67,132,79,209,48,47,31,25,52,93,195,140,88,52,75,7,170,103,107,247,161,57,\n  39,99,181,198,239,81,155,163,66,68,72,148,134,216,23,76,21,110,4,101,199,95,106,232,229,111,66,217,187,83,19,156,\n  149,102,216,63,205,65,45,115,230,148,54,185,115,75,59,8,138,174,172,240,205,159,95,38,189,248,162,172,124,239,61,21,\n  16,77,100,253,143,157,6,63,6,212,182,135,154,151,47,125,69,31,40,225,156,175,155,180,213,20,173,99,72,157,181,139,\n  180,63,104,144,110,31,59,92,175,243,104,61,247,99,245,218,142,215,52,209,203,26,123,90,91,115,93,125,33,127,206,202,\n  24,11,203,42,155,235,243,149,210,202,70,27,93,100,219,65,63,103,55,221,14,183,183,206,150,26,168,83,184,135,233,231,\n  29,165,159,117,130,126,54,62,211,52,253,28,179,245,61,227,189,197,68,253,136,65,55,200,196,179,89,58,208,241,101,36,\n  56,238,213,192,117,71,105,158,177,85,44,51,170,182,26,2,195,2,56,164,64,105,8,161,193,77,90,18,90,250,144,98,\n  197,156,241,141,75,217,14,22,247,186,240,245,215,178,164,85,43,169,172,91,144,114,220,172,70,223,164,199,28,168,16,177,\n  158,121,3,152,193,34,88,53,172,146,103,150,89,49,135,32,161,137,191,65,119,62,123,217,196,82,138,112,6,86,175,203,\n  4,186,54,220,207,244,220,203,125,145,49,9,40,86,195,182,148,210,175,97,14,175,41,170,41,204,49,95,169,20,233,160,\n  107,45,10,119,35,247,57,121,217,205,12,55,98,11,181,9,39,51,232,249,231,229,191,154,53,101,87,92,156,236,42,91,\n  214,39,250,207,162,50,101,188,146,167,207,237,214,196,150,190,123,241,30,246,166,216,207,206,133,37,75,170,158,218,172,171,\n  97,254,190,170,253,177,89,91,225,142,32,107,32,11,187,100,89,93,138,171,148,27,21,119,88,54,105,214,215,92,219,8,\n  15,107,155,30,249,121,86,120,223,140,65,255,252,124,198,50,160,24,189,127,245,243,88,99,187,246,82,206,247,101,189,98,\n  156,62,105,154,75,177,12,154,83,187,142,195,6,28,7,141,155,76,115,7,52,167,45,58,131,106,17,24,242,0,48,208,\n  120,189,65,41,52,122,20,44,40,191,15,24,160,24,120,166,186,169,50,16,32,164,127,199,140,81,105,193,172,65,41,9,\n  6,207,84,97,186,160,24,20,223,102,8,191,173,62,166,244,154,66,147,243,176,29,63,153,30,204,0,59,209,131,203,59,\n  83,243,232,167,172,17,97,244,143,8,93,151,247,50,97,173,99,152,205,20,17,33,137,108,118,69,100,87,236,17,191,136,\n  40,177,94,40,65,147,167,247,19,244,145,69,127,236,19,193,246,166,10,113,150,65,113,22,100,6,161,32,111,159,27,174,\n  210,80,215,62,221,187,116,241,99,232,10,93,153,114,184,174,211,65,60,154,142,39,75,106,72,245,229,176,54,136,11,197,\n  32,52,161,61,24,239,160,107,138,174,155,72,8,142,42,96,160,236,57,190,118,240,96,71,211,165,76,236,137,238,175,27,\n  235,244,194,133,242,101,235,214,42,200,207,88,8,97,81,154,222,120,163,140,189,253,118,213,239,131,153,89,124,54,198,54,\n  54,186,17,95,99,224,156,110,47,198,119,24,203,97,246,24,33,81,190,198,103,63,131,245,49,19,243,65,87,86,95,204,\n  9,227,44,134,47,145,32,137,149,253,45,218,11,93,153,186,191,217,191,102,39,97,183,89,16,182,159,157,226,44,240,193,\n  75,73,153,84,20,103,90,29,196,20,115,195,60,155,228,9,89,56,116,133,46,91,135,74,87,152,63,174,253,151,7,148,\n  235,9,130,129,117,19,12,124,119,129,0,169,11,97,81,22,204,55,202,45,43,161,251,219,111,203,174,41,83,36,69,99,\n  62,101,9,161,225,110,133,104,208,198,133,45,90,200,251,208,244,98,53,44,51,145,127,43,226,57,249,108,204,208,106,126,\n  211,77,202,197,69,106,6,106,140,215,8,127,194,140,49,226,104,17,15,171,2,161,36,8,57,161,51,57,204,76,141,240,\n  180,193,168,165,254,246,42,14,93,153,42,60,170,209,146,30,64,228,90,10,15,27,157,226,178,98,223,14,203,234,216,152,\n  182,5,239,9,157,164,144,45,180,23,67,87,176,15,213,107,17,14,127,125,234,134,83,133,114,96,142,158,112,125,76,42,\n  11,13,158,1,234,196,217,179,189,66,122,100,37,33,194,170,113,66,187,127,92,183,174,244,46,84,72,234,227,160,21,131,\n  112,40,106,60,167,55,242,150,182,231,129,206,105,212,206,198,65,13,70,133,174,128,247,56,214,236,58,208,12,194,110,47,\n  42,82,68,18,138,21,187,170,90,206,154,128,124,63,164,237,73,189,200,194,20,11,93,161,43,216,194,163,162,143,169,120,\n  23,116,94,244,26,29,169,103,48,125,67,56,132,76,35,108,220,21,29,59,58,42,210,179,162,5,98,10,145,85,171,20,\n  237,158,58,85,134,68,69,73,140,14,244,27,100,85,143,95,212,105,114,231,116,9,255,113,237,142,218,167,187,211,49,205,\n  237,7,141,21,52,89,103,100,52,210,185,251,143,132,220,4,89,106,143,171,78,113,213,239,186,75,254,102,192,218,114,89,\n  93,37,61,43,44,76,165,191,53,224,157,91,157,65,153,144,251,52,116,101,214,193,186,89,167,163,157,213,140,243,172,134,\n  247,222,162,49,120,62,212,249,208,37,53,208,220,29,204,144,8,119,186,187,198,226,96,30,143,129,182,195,202,115,22,18,\n  170,244,220,172,102,137,104,235,227,208,220,185,50,191,97,67,169,253,208,67,18,238,90,208,147,162,139,255,234,235,20,182,\n  82,186,128,38,66,227,26,189,166,97,215,89,232,149,91,103,163,221,166,33,41,66,22,70,214,221,223,170,83,28,59,177,\n  245,33,120,35,51,158,174,18,151,21,5,135,149,154,75,119,21,43,237,75,187,102,88,45,244,183,103,118,232,10,93,254,\n  30,176,91,52,163,172,164,253,163,44,38,202,165,205,93,197,24,139,122,255,44,49,124,162,217,82,148,184,248,165,110,185,\n  69,185,132,126,233,215,79,206,90,150,200,229,20,34,16,24,172,142,39,140,201,167,141,26,169,224,121,228,181,215,154,102,\n  189,232,42,235,129,90,40,132,124,195,87,215,222,102,214,219,100,66,206,127,142,125,153,16,29,125,85,184,172,246,106,139,\n  195,194,44,90,158,59,183,59,138,241,33,11,180,51,42,180,21,66,87,86,188,136,206,170,243,232,137,87,95,147,224,110,\n  108,46,83,50,123,118,5,46,184,164,117,107,57,48,123,182,163,99,224,165,16,36,218,194,32,157,91,178,68,54,142,26,\n  165,96,227,107,193,210,136,72,43,52,78,105,68,212,130,158,186,0,134,174,171,66,120,60,196,78,113,241,57,114,200,6,\n  54,186,122,239,189,43,218,101,181,79,247,141,216,169,45,14,75,112,184,65,108,39,107,111,66,200,117,26,186,178,254,21,\n  158,45,53,115,139,21,213,245,240,247,79,16,34,231,169,229,215,196,230,30,6,141,143,80,231,180,0,46,178,14,132,130,\n  132,100,183,144,208,18,22,90,48,49,61,119,203,184,113,202,53,197,182,184,101,53,48,156,7,161,177,88,187,226,110,161,\n  240,11,11,45,225,213,234,178,42,195,34,206,30,249,242,201,30,102,89,217,232,20,119,185,93,84,123,180,181,177,85,119,\n  131,99,61,199,130,255,253,207,29,232,78,52,172,200,61,33,193,17,186,174,168,139,238,173,152,108,169,21,234,172,117,248,\n  50,204,129,227,35,209,215,95,47,213,176,217,89,76,200,140,39,198,71,246,77,159,174,24,126,242,178,101,78,33,224,11,\n  65,112,92,252,234,43,57,54,127,190,108,157,48,65,190,237,212,73,198,149,43,167,96,223,203,221,113,135,138,103,20,77,\n  155,29,149,168,225,44,8,86,118,27,5,94,116,104,201,174,90,225,161,59,197,141,37,204,248,252,119,223,149,132,152,24,\n  217,111,3,173,246,82,90,23,251,180,107,138,2,99,151,182,52,182,106,168,126,90,27,63,230,201,35,195,238,186,75,117,\n  32,116,83,140,150,121,130,103,9,93,161,235,138,178,68,180,59,235,86,221,191,151,184,43,235,177,209,207,90,76,189,248,\n  141,55,74,149,251,238,147,230,208,4,251,20,42,164,210,126,217,6,151,29,253,104,165,252,220,183,175,138,157,144,126,236,\n  221,91,86,118,233,34,139,91,182,148,153,53,107,170,126,34,157,95,127,93,234,61,242,136,18,22,100,16,69,61,167,21,\n  159,212,109,32,187,107,232,144,155,66,7,235,255,141,229,241,32,246,195,95,149,177,63,214,150,46,45,251,10,23,150,61,\n  207,60,227,210,249,208,157,246,100,38,177,225,150,166,244,154,10,89,13,192,88,244,183,77,247,98,216,164,43,199,217,159,\n  98,194,189,247,42,216,239,8,215,189,158,172,27,82,49,211,79,53,179,10,93,161,235,106,57,200,215,104,132,201,24,13,\n  170,198,6,70,135,216,149,47,76,67,63,155,150,2,251,9,68,223,112,131,74,165,37,209,106,137,210,16,32,230,251,61,\n  8,139,139,58,157,118,169,6,55,43,100,245,15,14,9,141,255,119,123,46,154,202,74,103,50,226,170,85,101,199,91,111,\n  201,54,221,182,118,27,59,171,101,6,105,134,239,141,210,109,142,100,54,6,211,25,84,235,160,28,173,130,192,152,253,192,\n  3,170,39,124,85,156,133,200,180,110,216,163,26,87,237,222,208,62,15,93,87,181,69,162,211,124,239,208,89,93,85,53,\n  74,231,103,186,171,213,110,93,83,113,222,104,188,228,78,73,186,254,226,168,134,247,254,69,163,103,246,208,8,183,76,41,\n  190,165,74,182,224,2,161,133,174,43,74,112,100,211,40,168,50,190,64,1,89,31,27,43,191,190,248,162,252,12,102,252,\n  115,222,188,242,147,65,63,154,148,39,143,234,74,184,6,191,255,64,194,239,22,125,111,208,106,131,190,3,115,39,173,50,\n  104,165,65,223,146,30,122,72,86,128,150,131,190,209,180,44,119,110,89,10,250,50,87,46,89,4,250,44,103,78,153,251,\n  224,131,50,253,254,251,101,12,91,1,228,200,33,77,110,190,89,42,56,1,56,221,21,165,115,186,197,109,148,134,155,15,\n  93,161,235,255,207,197,24,201,27,217,82,123,45,220,173,33,160,95,215,113,9,166,14,215,209,197,119,77,116,11,201,90,\n  160,56,93,127,241,138,246,239,230,176,50,75,66,197,80,161,203,128,154,255,129,90,122,197,91,110,145,106,183,221,38,241,\n  217,179,75,213,27,111,84,218,123,21,55,170,108,80,37,131,42,154,4,38,30,7,178,126,90,84,193,160,242,6,17,213,\n  214,162,178,154,202,104,98,61,70,41,88,210,177,32,246,147,46,1,138,209,205,132,34,61,52,40,114,83,158,142,232,132,\n  143,74,186,247,70,200,218,8,93,161,43,116,133,174,32,9,143,155,53,200,167,11,254,88,86,164,12,144,29,146,117,118,\n  224,86,93,244,215,78,23,172,222,18,170,225,8,93,161,43,116,133,174,204,113,91,49,120,188,58,29,198,156,162,153,115,\n  178,118,133,90,176,52,23,180,75,200,162,51,6,157,50,232,132,118,177,146,142,105,55,234,81,141,208,112,88,23,234,29,\n  212,116,64,247,86,79,208,48,63,123,181,139,150,110,215,237,160,127,153,80,162,81,14,86,104,55,238,120,45,44,98,180,\n  69,158,61,50,100,93,135,174,203,112,253,31,97,80,138,245,216,112,190,26,0,0,0,37,116,69,88,116,100,97,116,101,\n  58,99,114,101,97,116,101,0,50,48,49,54,45,48,55,45,50,55,84,50,48,58,50,54,58,51,49,45,48,52,58,48,\n  48,174,172,147,128,0,0,0,37,116,69,88,116,100,97,116,101,58,109,111,100,105,102,121,0,50,48,49,54,45,48,55,\n  45,50,55,84,50,48,58,50,54,58,51,49,45,48,52,58,48,48,223,241,43,60,0,0,0,58,116,69,88,116,115,118,\n  103,58,98,97,115,101,45,117,114,105,0,102,105,108,101,58,47,47,47,99,111,114,101,47,102,105,108,101,115,47,109,101,\n  100,105,97,47,104,105,103,97,110,47,108,111,103,111,47,104,105,103,97,110,46,115,118,103,214,196,144,254,0,0,0,0,\n  73,69,78,68,174,66,96,130,\n};\n}\nnamespace Sprite {\nconst nall::vector<uint8_t> CrosshairRed = {  \/\/size: 342\n  137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,32,8,6,0,0,0,115,122,122,\n  244,0,0,0,4,115,66,73,84,8,8,8,8,124,8,100,136,0,0,0,9,112,72,89,115,0,0,14,196,0,0,14,\n  196,1,149,43,14,27,0,0,0,248,73,68,65,84,88,133,205,87,65,14,196,32,8,132,102,255,255,101,246,176,177,139,\n  148,81,80,27,229,212,70,102,6,212,0,50,229,77,26,107,156,37,139,2,228,241,209,39,11,113,71,156,68,139,106,128,\n  56,255,198,175,203,223,114,16,79,68,253,138,90,99,141,113,112,80,231,131,196,11,83,52,19,43,196,53,135,147,7,38,\n  150,104,244,212,32,86,235,228,236,20,6,200,207,191,117,215,70,12,242,94,139,133,166,236,173,236,67,252,111,139,67,157,\n  237,71,48,27,192,244,142,93,228,23,148,144,184,228,131,96,254,3,164,4,176,213,108,37,52,5,208,53,47,227,81,28,\n  49,153,102,163,88,96,149,68,150,193,21,223,59,128,68,43,69,13,103,4,199,246,8,34,151,240,209,249,38,112,251,47,\n  97,177,209,74,152,246,95,93,9,211,51,160,181,99,142,128,104,115,55,124,59,136,115,7,146,237,51,33,2,71,166,226,\n  94,23,13,77,214,104,44,103,174,163,143,86,189,244,187,224,232,151,81,21,132,39,210,33,91,246,54,132,193,44,226,219,\n  107,95,57,136,120,253,172,254,16,23,0,0,0,0,73,69,78,68,174,66,96,130,\n};\nconst nall::vector<uint8_t> CrosshairGreen = {  \/\/size: 329\n  137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,32,8,6,0,0,0,115,122,122,\n  244,0,0,0,4,115,66,73,84,8,8,8,8,124,8,100,136,0,0,0,9,112,72,89,115,0,0,14,196,0,0,14,\n  196,1,149,43,14,27,0,0,0,235,73,68,65,84,88,133,213,87,65,18,195,32,8,196,78,31,230,211,253,153,61,180,\n  52,18,145,1,193,97,178,39,141,44,139,24,69,11,216,209,133,177,98,117,166,37,92,162,77,176,170,118,223,26,163,78,\n  68,71,145,198,244,169,157,57,35,84,248,43,222,255,109,154,254,113,140,114,102,222,18,239,165,120,251,181,42,0,232,103,\n  114,217,85,226,163,27,124,232,163,87,142,115,153,82,137,71,98,233,247,21,44,228,194,169,217,171,252,159,22,95,234,164,\n  47,129,55,128,144,140,237,166,63,132,151,190,4,247,147,16,103,35,157,90,220,140,119,121,80,224,94,108,0,164,227,119,\n  182,221,229,13,182,82,193,225,176,42,56,59,188,105,9,52,5,3,109,58,243,205,202,203,255,9,17,251,91,202,169,227,\n  205,128,235,198,19,17,64,40,82,171,225,233,32,158,113,33,65,164,222,9,105,16,50,81,55,238,88,210,212,119,1,0,\n  238,241,241,126,143,125,62,216,173,151,209,35,222,134,235,96,98,252,229,226,3,112,72,179,236,202,138,114,18,0,0,0,\n  0,73,69,78,68,174,66,96,130,\n};\nconst nall::vector<uint8_t> CrosshairBlue = {  \/\/size: 332\n  137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,32,8,6,0,0,0,115,122,122,\n  244,0,0,0,4,115,66,73,84,8,8,8,8,124,8,100,136,0,0,0,9,112,72,89,115,0,0,14,196,0,0,14,\n  196,1,149,43,14,27,0,0,0,238,73,68,65,84,88,133,213,87,91,18,195,32,8,196,78,15,232,81,189,161,253,9,\n  25,52,98,121,57,76,246,43,137,44,11,24,69,11,232,209,55,99,69,235,76,74,184,69,107,229,245,91,27,220,137,124,\n  75,140,58,21,165,34,181,246,199,251,100,167,174,200,32,124,137,119,124,134,177,252,116,108,224,44,120,44,190,156,56,102,\n  163,204,228,182,107,173,80,31,93,225,67,30,189,112,124,85,41,145,120,36,88,191,159,96,33,23,78,101,47,242,127,90,\n  156,213,73,159,2,111,0,33,21,179,150,63,132,151,62,5,243,78,136,217,236,118,173,85,198,86,30,20,152,154,13,192,\n  118,251,125,216,90,121,212,118,215,112,86,224,26,142,133,247,152,2,73,195,64,155,190,248,166,229,229,255,132,8,243,146,\n  242,234,120,43,224,58,241,68,4,16,138,212,110,120,58,136,119,28,72,16,169,103,194,33,136,63,68,209,184,103,74,83,\n  239,5,0,215,26,167,231,123,124,103,130,53,221,140,94,113,55,100,131,9,242,151,139,31,79,50,234,237,105,206,30,22,\n  0,0,0,0,73,69,78,68,174,66,96,130,\n};\n}\n}\n","avg_line_length":114.5101553166,"max_line_length":126,"alphanum_fraction":0.7005581929,"low_alphanum":false,"long_lines":true,"lexable":true}
{"size":11109,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":86.0,"content":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Name:        tests\/thread\/misc.cpp\n\/\/ Purpose:     Miscellaneous wxThread test cases\n\/\/ Author:      Francesco Montorsi (extracted from console sample)\n\/\/ Created:     2010-05-10\n\/\/ Copyright:   (c) 2010 wxWidgets team\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ headers\n\/\/ ----------------------------------------------------------------------------\n\n#include \"testprec.h\"\n\n#ifdef __BORLANDC__\n    #pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#endif \/\/ WX_PRECOMP\n\n#include \"wx\/thread.h\"\n#include \"wx\/utils.h\"\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ globals\n\/\/ ----------------------------------------------------------------------------\n\nstatic size_t gs_counter = (size_t)-1;\nstatic wxCriticalSection gs_critsect;\nstatic wxSemaphore gs_cond;\n\nclass MyJoinableThread : public wxThread\n{\npublic:\n    MyJoinableThread(size_t n) : wxThread(wxTHREAD_JOINABLE)\n        { m_n = n; Create(); }\n\n    \/\/ thread execution starts here\n    virtual ExitCode Entry() wxOVERRIDE;\n\nprivate:\n    size_t m_n;\n};\n\nwxThread::ExitCode MyJoinableThread::Entry()\n{\n    wxUIntPtr res = 1;\n    for ( size_t n = 1; n < m_n; n++ )\n    {\n        res *= n;\n\n        \/\/ it's a loooong calculation :-)\n        wxMilliSleep(100);\n    }\n\n    return (ExitCode)res;\n}\n\nclass MyDetachedThread : public wxThread\n{\npublic:\n    MyDetachedThread(size_t n, wxChar ch)\n    {\n        m_n = n;\n        m_ch = ch;\n        m_cancelled = false;\n\n        Create();\n    }\n\n    \/\/ thread execution starts here\n    virtual ExitCode Entry() wxOVERRIDE;\n\n    \/\/ and stops here\n    virtual void OnExit() wxOVERRIDE;\n\nprivate:\n    size_t m_n; \/\/ number of characters to write\n    wxChar m_ch;  \/\/ character to write\n\n    bool m_cancelled;   \/\/ false if we exit normally\n};\n\nwxThread::ExitCode MyDetachedThread::Entry()\n{\n    {\n        wxCriticalSectionLocker lock(gs_critsect);\n        if ( gs_counter == (size_t)-1 )\n            gs_counter = 1;\n        else\n            gs_counter++;\n    }\n\n    for ( size_t n = 0; n < m_n; n++ )\n    {\n        if ( TestDestroy() )\n        {\n            m_cancelled = true;\n\n            break;\n        }\n\n        \/\/wxPutchar(m_ch);\n        \/\/fflush(stdout);\n\n        wxMilliSleep(100);\n    }\n\n    return 0;\n}\n\nvoid MyDetachedThread::OnExit()\n{\n    \/\/wxLogTrace(wxT(\"thread\"), wxT(\"Thread %ld is in OnExit\"), GetId());\n\n    wxCriticalSectionLocker lock(gs_critsect);\n    if ( !--gs_counter && !m_cancelled )\n        gs_cond.Post();\n}\n\nclass MyWaitingThread : public wxThread\n{\npublic:\n    MyWaitingThread( wxMutex *mutex, wxCondition *condition )\n    {\n        m_mutex = mutex;\n        m_condition = condition;\n\n        Create();\n    }\n\n    virtual ExitCode Entry() wxOVERRIDE\n    {\n        \/\/wxPrintf(wxT(\"Thread %lu has started running.\\n\"), GetId());\n        gs_cond.Post();\n\n        \/\/wxPrintf(wxT(\"Thread %lu starts to wait...\\n\"), GetId());\n\n        m_mutex->Lock();\n        m_condition->Wait();\n        m_mutex->Unlock();\n\n        \/\/wxPrintf(wxT(\"Thread %lu finished to wait, exiting.\\n\"), GetId());\n\n        return 0;\n    }\n\nprivate:\n    wxMutex *m_mutex;\n    wxCondition *m_condition;\n};\n\n\/\/ semaphore tests\n#include \"wx\/datetime.h\"\n\nclass MySemaphoreThread : public wxThread\n{\npublic:\n    MySemaphoreThread(int i, wxSemaphore *sem)\n        : wxThread(wxTHREAD_JOINABLE),\n          m_sem(sem),\n          m_i(i)\n    {\n        Create();\n    }\n\n    virtual ExitCode Entry() wxOVERRIDE\n    {\n        wxUnusedVar(m_i);\n\n        \/\/wxPrintf(wxT(\"%s: Thread #%d (%ld) starting to wait for semaphore...\\n\"),\n        \/\/         wxDateTime::Now().FormatTime().c_str(), m_i, (long)GetId());\n\n        m_sem->Wait();\n\n        \/\/wxPrintf(wxT(\"%s: Thread #%d (%ld) acquired the semaphore.\\n\"),\n        \/\/         wxDateTime::Now().FormatTime().c_str(), m_i, (long)GetId());\n\n        Sleep(1000);\n\n        \/\/wxPrintf(wxT(\"%s: Thread #%d (%ld) releasing the semaphore.\\n\"),\n        \/\/         wxDateTime::Now().FormatTime().c_str(), m_i, (long)GetId());\n\n        m_sem->Post();\n\n        return 0;\n    }\n\nprivate:\n    wxSemaphore *m_sem;\n    int m_i;\n};\n\nWX_DEFINE_ARRAY_PTR(wxThread *, ArrayThreads);\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ test class\n\/\/ ----------------------------------------------------------------------------\n\nclass MiscThreadTestCase : public CppUnit::TestCase\n{\npublic:\n    MiscThreadTestCase();\n\nprivate:\n    CPPUNIT_TEST_SUITE( MiscThreadTestCase );\n        CPPUNIT_TEST( TestJoinable );\n        CPPUNIT_TEST( TestDetached );\n        CPPUNIT_TEST( TestThreadSuspend );\n        CPPUNIT_TEST( TestThreadDelete );\n        CPPUNIT_TEST( TestThreadRun );\n        CPPUNIT_TEST( TestThreadConditions );\n        CPPUNIT_TEST( TestSemaphore );\n    CPPUNIT_TEST_SUITE_END();\n\n    void TestJoinable();\n    void TestDetached();\n    void TestSemaphore();\n\n    void TestThreadSuspend();\n    void TestThreadDelete();\n    void TestThreadRun();\n    void TestThreadConditions();\n\n    wxDECLARE_NO_COPY_CLASS(MiscThreadTestCase);\n};\n\n\/\/ register in the unnamed registry so that these tests are run by default\nCPPUNIT_TEST_SUITE_REGISTRATION( MiscThreadTestCase );\n\n\/\/ also include in its own registry so that these tests can be run alone\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION( MiscThreadTestCase, \"MiscThreadTestCase\" );\n\nMiscThreadTestCase::MiscThreadTestCase()\n{\n    int nCPUs = wxThread::GetCPUCount();\n    if ( nCPUs != -1 )\n        wxThread::SetConcurrency(nCPUs);\n}\n\nvoid MiscThreadTestCase::TestJoinable()\n{\n    \/\/ calc 10! in the background\n    MyJoinableThread thread(10);\n    CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, thread.Run() );\n    CPPUNIT_ASSERT_EQUAL( 362880, (wxUIntPtr)thread.Wait() );\n}\n\nvoid MiscThreadTestCase::TestDetached()\n{\n    static const size_t nThreads = 3;\n    MyDetachedThread *threads[nThreads];\n\n    size_t n;\n    for ( n = 0; n < nThreads; n++ )\n    {\n        threads[n] = new MyDetachedThread(10, 'A' + n);\n    }\n\n    threads[0]->SetPriority(wxPRIORITY_MIN);\n    threads[1]->SetPriority(wxPRIORITY_MAX);\n\n    for ( n = 0; n < nThreads; n++ )\n    {\n        CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, threads[n]->Run() );\n    }\n\n    \/\/ wait until all threads terminate\n    CPPUNIT_ASSERT_EQUAL( wxSEMA_NO_ERROR, gs_cond.Wait() );\n}\n\nvoid MiscThreadTestCase::TestSemaphore()\n{\n    static const int SEM_LIMIT = 3;\n\n    wxSemaphore sem(SEM_LIMIT, SEM_LIMIT);\n    ArrayThreads threads;\n\n    for ( int i = 0; i < 3*SEM_LIMIT; i++ )\n    {\n        threads.Add(new MySemaphoreThread(i, &sem));\n        CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, threads.Last()->Run() );\n    }\n\n    for ( size_t n = 0; n < threads.GetCount(); n++ )\n    {\n        CPPUNIT_ASSERT_EQUAL( 0, (wxUIntPtr)threads[n]->Wait() );\n        delete threads[n];\n    }\n}\n\nvoid MiscThreadTestCase::TestThreadSuspend()\n{\n    MyDetachedThread *thread = new MyDetachedThread(15, 'X');\n\n    CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, thread->Run() );\n\n    \/\/ this is for this demo only, in a real life program we'd use another\n    \/\/ condition variable which would be signaled from wxThread::Entry() to\n    \/\/ tell us that the thread really started running - but here just wait a\n    \/\/ bit and hope that it will be enough (the problem is, of course, that\n    \/\/ the thread might still not run when we call Pause() which will result\n    \/\/ in an error)\n    wxMilliSleep(300);\n\n    for ( size_t n = 0; n < 3; n++ )\n    {\n        thread->Pause();\n\n        if ( n > 0 )\n        {\n            \/\/ don't sleep but resume immediately the first time\n            wxMilliSleep(300);\n        }\n\n        CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, thread->Resume() );\n    }\n\n    \/\/ wait until the thread terminates\n    CPPUNIT_ASSERT_EQUAL( wxSEMA_NO_ERROR, gs_cond.Wait() );\n}\n\nvoid MiscThreadTestCase::TestThreadDelete()\n{\n    \/\/ FIXME:\n    \/\/ As above, using Sleep() is only for testing here - we must use some\n    \/\/ synchronisation object instead to ensure that the thread is still\n    \/\/ running when we delete it - deleting a detached thread which already\n    \/\/ terminated will lead to a crash!\n\n    MyDetachedThread *thread0 = new MyDetachedThread(30, 'W');\n    CPPUNIT_ASSERT_EQUAL( wxTHREAD_MISC_ERROR, thread0->Delete() );\n        \/\/ delete a thread which didn't start to run yet.\n\n    MyDetachedThread *thread1 = new MyDetachedThread(30, 'Y');\n    CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, thread1->Run() );\n    wxMilliSleep(300);\n    CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, thread1->Delete() );\n        \/\/ delete a running thread\n\n    MyDetachedThread *thread2 = new MyDetachedThread(30, 'Z');\n    CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, thread2->Run() );\n    wxMilliSleep(300);\n    CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, thread2->Pause() );\n    CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, thread2->Delete() );\n        \/\/ delete a sleeping thread\n\n    MyJoinableThread thread3(20);\n    CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, thread3.Run() );\n    CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, thread3.Delete() );\n        \/\/ delete a joinable running thread\n\n    MyJoinableThread thread4(2);\n    CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, thread4.Run() );\n    wxMilliSleep(300);\n    CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, thread4.Delete() );\n        \/\/ delete a joinable thread which already terminated\n}\n\nvoid MiscThreadTestCase::TestThreadRun()\n{\n    MyJoinableThread thread1(2);\n    CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, thread1.Run() );\n    thread1.Wait();     \/\/ wait until the thread ends\n\n    \/\/ verify that running twice the same thread fails\n    WX_ASSERT_FAILS_WITH_ASSERT( thread1.Run() );\n}\n\nvoid MiscThreadTestCase::TestThreadConditions()\n{\n    wxMutex mutex;\n    wxCondition condition(mutex);\n\n    \/\/ otherwise its difficult to understand which log messages pertain to\n    \/\/ which condition\n    \/\/wxLogTrace(wxT(\"thread\"), wxT(\"Local condition var is %08x, gs_cond = %08x\"),\n    \/\/           condition.GetId(), gs_cond.GetId());\n\n    \/\/ create and launch threads\n    MyWaitingThread *threads[10];\n\n    size_t n;\n    for ( n = 0; n < WXSIZEOF(threads); n++ )\n    {\n        threads[n] = new MyWaitingThread( &mutex, &condition );\n    }\n\n    for ( n = 0; n < WXSIZEOF(threads); n++ )\n    {\n        CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, threads[n]->Run() );\n    }\n\n    \/\/ wait until all threads run\n    \/\/ NOTE: main thread is waiting for the other threads to start\n    size_t nRunning = 0;\n    while ( nRunning < WXSIZEOF(threads) )\n    {\n        CPPUNIT_ASSERT_EQUAL( wxSEMA_NO_ERROR, gs_cond.Wait() );\n\n        nRunning++;\n\n        \/\/ note that main thread is already running\n    }\n\n    wxMilliSleep(500);\n\n#if 1\n    \/\/ now wake one of them up\n    CPPUNIT_ASSERT_EQUAL( wxCOND_NO_ERROR, condition.Signal() );\n#endif\n\n    wxMilliSleep(200);\n\n    \/\/ wake all the (remaining) threads up, so that they can exit\n    CPPUNIT_ASSERT_EQUAL( wxCOND_NO_ERROR, condition.Broadcast() );\n\n    \/\/ give them time to terminate (dirty!)\n    wxMilliSleep(500);\n}\n","avg_line_length":26.3246445498,"max_line_length":83,"alphanum_fraction":0.6038347286,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":9616,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2009-2020 The C1pzo Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <core_io.h>\n\n#include <primitives\/block.h>\n#include <primitives\/transaction.h>\n#include <script\/script.h>\n#include <script\/sign.h>\n#include <serialize.h>\n#include <streams.h>\n#include <univalue.h>\n#include <util\/strencodings.h>\n#include <version.h>\n\n#include <boost\/algorithm\/string\/classification.hpp>\n#include <boost\/algorithm\/string\/split.hpp>\n\n#include <algorithm>\n#include <string>\n\nnamespace {\n\nopcodetype ParseOpCode(const std::string& s)\n{\n    static std::map<std::string, opcodetype> mapOpNames;\n\n    if (mapOpNames.empty())\n    {\n        for (unsigned int op = 0; op <= MAX_OPCODE; op++)\n        {\n            \/\/ Allow OP_RESERVED to get into mapOpNames\n            if (op < OP_NOP && op != OP_RESERVED)\n                continue;\n\n            std::string strName = GetOpName(static_cast<opcodetype>(op));\n            if (strName == \"OP_UNKNOWN\")\n                continue;\n            mapOpNames[strName] = static_cast<opcodetype>(op);\n            \/\/ Convenience: OP_ADD and just ADD are both recognized:\n            if (strName.compare(0, 3, \"OP_\") == 0) {  \/\/ strName starts with \"OP_\"\n                mapOpNames[strName.substr(3)] = static_cast<opcodetype>(op);\n            }\n        }\n    }\n\n    auto it = mapOpNames.find(s);\n    if (it == mapOpNames.end()) throw std::runtime_error(\"script parse error: unknown opcode\");\n    return it->second;\n}\n\n} \/\/ namespace\n\nCScript ParseScript(const std::string& s)\n{\n    CScript result;\n\n    std::vector<std::string> words;\n    boost::algorithm::split(words, s, boost::algorithm::is_any_of(\" \\t\\n\"), boost::algorithm::token_compress_on);\n\n    for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)\n    {\n        if (w->empty())\n        {\n            \/\/ Empty string, ignore. (boost::split given '' will return one word)\n        }\n        else if (std::all_of(w->begin(), w->end(), ::IsDigit) ||\n            (w->front() == '-' && w->size() > 1 && std::all_of(w->begin()+1, w->end(), ::IsDigit)))\n        {\n            \/\/ Number\n            int64_t n = atoi64(*w);\n\n            \/\/limit the range of numbers ParseScript accepts in decimal\n            \/\/since numbers outside -0xFFFFFFFF...0xFFFFFFFF are illegal in scripts\n            if (n > int64_t{0xffffffff} || n < -1 * int64_t{0xffffffff}) {\n                throw std::runtime_error(\"script parse error: decimal numeric value only allowed in the \"\n                                         \"range -0xFFFFFFFF...0xFFFFFFFF\");\n            }\n\n            result << n;\n        }\n        else if (w->substr(0,2) == \"0x\" && w->size() > 2 && IsHex(std::string(w->begin()+2, w->end())))\n        {\n            \/\/ Raw hex data, inserted NOT pushed onto stack:\n            std::vector<unsigned char> raw = ParseHex(std::string(w->begin()+2, w->end()));\n            result.insert(result.end(), raw.begin(), raw.end());\n        }\n        else if (w->size() >= 2 && w->front() == '\\'' && w->back() == '\\'')\n        {\n            \/\/ Single-quoted string, pushed as data. NOTE: this is poor-man's\n            \/\/ parsing, spaces\/tabs\/newlines in single-quoted strings won't work.\n            std::vector<unsigned char> value(w->begin()+1, w->end()-1);\n            result << value;\n        }\n        else\n        {\n            \/\/ opcode, e.g. OP_ADD or ADD:\n            result << ParseOpCode(*w);\n        }\n    }\n\n    return result;\n}\n\n\/\/ Check that all of the input and output scripts of a transaction contains valid opcodes\nstatic bool CheckTxScriptsSanity(const CMutableTransaction& tx)\n{\n    \/\/ Check input scripts for non-coinbase txs\n    if (!CTransaction(tx).IsCoinBase()) {\n        for (unsigned int i = 0; i < tx.vin.size(); i++) {\n            if (!tx.vin[i].scriptSig.HasValidOps() || tx.vin[i].scriptSig.size() > MAX_SCRIPT_SIZE) {\n                return false;\n            }\n        }\n    }\n    \/\/ Check output scripts\n    for (unsigned int i = 0; i < tx.vout.size(); i++) {\n        if (!tx.vout[i].scriptPubKey.HasValidOps() || tx.vout[i].scriptPubKey.size() > MAX_SCRIPT_SIZE) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nstatic bool DecodeTx(CMutableTransaction& tx, const std::vector<unsigned char>& tx_data, bool try_no_witness, bool try_witness)\n{\n    \/\/ General strategy:\n    \/\/ - Decode both with extended serialization (which interprets the 0x0001 tag as a marker for\n    \/\/   the presence of witnesses) and with legacy serialization (which interprets the tag as a\n    \/\/   0-input 1-output incomplete transaction).\n    \/\/   - Restricted by try_no_witness (which disables legacy if false) and try_witness (which\n    \/\/     disables extended if false).\n    \/\/   - Ignore serializations that do not fully consume the hex string.\n    \/\/ - If neither succeeds, fail.\n    \/\/ - If only one succeeds, return that one.\n    \/\/ - If both decode attempts succeed:\n    \/\/   - If only one passes the CheckTxScriptsSanity check, return that one.\n    \/\/   - If neither or both pass CheckTxScriptsSanity, return the extended one.\n\n    CMutableTransaction tx_extended, tx_legacy;\n    bool ok_extended = false, ok_legacy = false;\n\n    \/\/ Try decoding with extended serialization support, and remember if the result successfully\n    \/\/ consumes the entire input.\n    if (try_witness) {\n        CDataStream ssData(tx_data, SER_NETWORK, PROTOCOL_VERSION);\n        try {\n            ssData >> tx_extended;\n            if (ssData.empty()) ok_extended = true;\n        } catch (const std::exception&) {\n            \/\/ Fall through.\n        }\n    }\n\n    \/\/ Optimization: if extended decoding succeeded and the result passes CheckTxScriptsSanity,\n    \/\/ don't bother decoding the other way.\n    if (ok_extended && CheckTxScriptsSanity(tx_extended)) {\n        tx = std::move(tx_extended);\n        return true;\n    }\n\n    \/\/ Try decoding with legacy serialization, and remember if the result successfully consumes the entire input.\n    if (try_no_witness) {\n        CDataStream ssData(tx_data, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);\n        try {\n            ssData >> tx_legacy;\n            if (ssData.empty()) ok_legacy = true;\n        } catch (const std::exception&) {\n            \/\/ Fall through.\n        }\n    }\n\n    \/\/ If legacy decoding succeeded and passes CheckTxScriptsSanity, that's our answer, as we know\n    \/\/ at this point that extended decoding either failed or doesn't pass the sanity check.\n    if (ok_legacy && CheckTxScriptsSanity(tx_legacy)) {\n        tx = std::move(tx_legacy);\n        return true;\n    }\n\n    \/\/ If extended decoding succeeded, and neither decoding passes sanity, return the extended one.\n    if (ok_extended) {\n        tx = std::move(tx_extended);\n        return true;\n    }\n\n    \/\/ If legacy decoding succeeded and extended didn't, return the legacy one.\n    if (ok_legacy) {\n        tx = std::move(tx_legacy);\n        return true;\n    }\n\n    \/\/ If none succeeded, we failed.\n    return false;\n}\n\nbool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness)\n{\n    if (!IsHex(hex_tx)) {\n        return false;\n    }\n\n    std::vector<unsigned char> txData(ParseHex(hex_tx));\n    return DecodeTx(tx, txData, try_no_witness, try_witness);\n}\n\nbool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header)\n{\n    if (!IsHex(hex_header)) return false;\n\n    const std::vector<unsigned char> header_data{ParseHex(hex_header)};\n    CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);\n    try {\n        ser_header >> header;\n    } catch (const std::exception&) {\n        return false;\n    }\n    return true;\n}\n\nbool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)\n{\n    if (!IsHex(strHexBlk))\n        return false;\n\n    std::vector<unsigned char> blockData(ParseHex(strHexBlk));\n    CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);\n    try {\n        ssBlock >> block;\n    }\n    catch (const std::exception&) {\n        return false;\n    }\n\n    return true;\n}\n\nbool ParseHashStr(const std::string& strHex, uint256& result)\n{\n    if ((strHex.size() != 64) || !IsHex(strHex))\n        return false;\n\n    result.SetHex(strHex);\n    return true;\n}\n\nstd::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)\n{\n    std::string strHex;\n    if (v.isStr())\n        strHex = v.getValStr();\n    if (!IsHex(strHex))\n        throw std::runtime_error(strName + \" must be hexadecimal string (not '\" + strHex + \"')\");\n    return ParseHex(strHex);\n}\n\nint ParseSighashString(const UniValue& sighash)\n{\n    int hash_type = SIGHASH_ALL;\n    if (!sighash.isNull()) {\n        static std::map<std::string, int> map_sighash_values = {\n            {std::string(\"ALL\"), int(SIGHASH_ALL)},\n            {std::string(\"ALL|ANYONECANPAY\"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},\n            {std::string(\"NONE\"), int(SIGHASH_NONE)},\n            {std::string(\"NONE|ANYONECANPAY\"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},\n            {std::string(\"SINGLE\"), int(SIGHASH_SINGLE)},\n            {std::string(\"SINGLE|ANYONECANPAY\"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},\n        };\n        std::string strHashType = sighash.get_str();\n        const auto& it = map_sighash_values.find(strHashType);\n        if (it != map_sighash_values.end()) {\n            hash_type = it->second;\n        } else {\n            throw std::runtime_error(strHashType + \" is not a valid sighash parameter.\");\n        }\n    }\n    return hash_type;\n}\n","avg_line_length":34.3428571429,"max_line_length":127,"alphanum_fraction":0.6144966722,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":47494,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/\r\n\/\/ Copyright (c) 2008-2015 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#ifdef URHO3D_PHYSICS\r\n#include \"..\/Physics\/CollisionShape.h\"\r\n#endif\r\n#include \"..\/Core\/Context.h\"\r\n#include \"..\/Graphics\/DebugRenderer.h\"\r\n#include \"..\/Graphics\/Drawable.h\"\r\n#include \"..\/Navigation\/DynamicNavigationMesh.h\"\r\n#include \"..\/Graphics\/Geometry.h\"\r\n#include \"..\/IO\/Log.h\"\r\n#include \"..\/IO\/MemoryBuffer.h\"\r\n#include \"..\/Graphics\/Model.h\"\r\n#include \"..\/Navigation\/NavArea.h\"\r\n#include \"..\/Navigation\/NavBuildData.h\"\r\n#include \"..\/Navigation\/Navigable.h\"\r\n#include \"..\/Navigation\/NavigationEvents.h\"\r\n#include \"..\/Navigation\/NavigationMesh.h\"\r\n#include \"..\/Navigation\/Obstacle.h\"\r\n#include \"..\/Navigation\/OffMeshConnection.h\"\r\n#include \"..\/Core\/Profiler.h\"\r\n#include \"..\/Scene\/Scene.h\"\r\n#include \"..\/Graphics\/StaticModel.h\"\r\n#include \"..\/Graphics\/TerrainPatch.h\"\r\n#include \"..\/IO\/VectorBuffer.h\"\r\n\r\n#include <cfloat>\r\n#include <Detour\/DetourNavMesh.h>\r\n#include <Detour\/DetourNavMeshBuilder.h>\r\n#include <Detour\/DetourNavMeshQuery.h>\r\n#include <Recast\/Recast.h>\r\n\r\n#include \"..\/Navigation\/CrowdAgent.h\"\r\n#include \"..\/Navigation\/DetourCrowdManager.h\"\r\n\r\n#include \"..\/DebugNew.h\"\r\n\r\nnamespace Urho3D\r\n{\r\n\r\nconst char* navmeshPartitionTypeNames[] =\r\n{\r\n    \"watershed\",\r\n    \"monotone\",\r\n    0\r\n};\r\n\r\nconst char* NAVIGATION_CATEGORY = \"Navigation\";\r\n\r\nstatic const int DEFAULT_TILE_SIZE = 128;\r\nstatic const float DEFAULT_CELL_SIZE = 0.3f;\r\nstatic const float DEFAULT_CELL_HEIGHT = 0.2f;\r\nstatic const float DEFAULT_AGENT_HEIGHT = 2.0f;\r\nstatic const float DEFAULT_AGENT_RADIUS = 0.6f;\r\nstatic const float DEFAULT_AGENT_MAX_CLIMB = 0.9f;\r\nstatic const float DEFAULT_AGENT_MAX_SLOPE = 45.0f;\r\nstatic const float DEFAULT_REGION_MIN_SIZE = 8.0f;\r\nstatic const float DEFAULT_REGION_MERGE_SIZE = 20.0f;\r\nstatic const float DEFAULT_EDGE_MAX_LENGTH = 12.0f;\r\nstatic const float DEFAULT_EDGE_MAX_ERROR = 1.3f;\r\nstatic const float DEFAULT_DETAIL_SAMPLE_DISTANCE = 6.0f;\r\nstatic const float DEFAULT_DETAIL_SAMPLE_MAX_ERROR = 1.0f;\r\n\r\nstatic const int MAX_POLYS = 2048;\r\n\r\n\r\n\/\/\/ Temporary data for finding a path.\r\nstruct FindPathData\r\n{\r\n    \/\/ Polygons.\r\n    dtPolyRef polys_[MAX_POLYS];\r\n    \/\/ Polygons on the path.\r\n    dtPolyRef pathPolys_[MAX_POLYS];\r\n    \/\/ Points on the path.\r\n    Vector3 pathPoints_[MAX_POLYS];\r\n    \/\/ Flags on the path.\r\n    unsigned char pathFlags_[MAX_POLYS];\r\n    \/\/ Area Ids on the path.\r\n    unsigned char pathAreras_[MAX_POLYS];\r\n};\r\n\r\nNavigationMesh::NavigationMesh(Context* context) :\r\n    Component(context),\r\n    navMesh_(0),\r\n    navMeshQuery_(0),\r\n    queryFilter_(new dtQueryFilter()),\r\n    pathData_(new FindPathData()),\r\n    tileSize_(DEFAULT_TILE_SIZE),\r\n    cellSize_(DEFAULT_CELL_SIZE),\r\n    cellHeight_(DEFAULT_CELL_HEIGHT),\r\n    agentHeight_(DEFAULT_AGENT_HEIGHT),\r\n    agentRadius_(DEFAULT_AGENT_RADIUS),\r\n    agentMaxClimb_(DEFAULT_AGENT_MAX_CLIMB),\r\n    agentMaxSlope_(DEFAULT_AGENT_MAX_SLOPE),\r\n    regionMinSize_(DEFAULT_REGION_MIN_SIZE),\r\n    regionMergeSize_(DEFAULT_REGION_MERGE_SIZE),\r\n    edgeMaxLength_(DEFAULT_EDGE_MAX_LENGTH),\r\n    edgeMaxError_(DEFAULT_EDGE_MAX_ERROR),\r\n    detailSampleDistance_(DEFAULT_DETAIL_SAMPLE_DISTANCE),\r\n    detailSampleMaxError_(DEFAULT_DETAIL_SAMPLE_MAX_ERROR),\r\n    padding_(Vector3::ONE),\r\n    numTilesX_(0),\r\n    numTilesZ_(0),\r\n    partitionType_(NAVMESH_PARTITION_WATERSHED),\r\n    keepInterResults_(false),\r\n    drawOffMeshConnections_(false),\r\n    drawNavAreas_(false)\r\n{\r\n}\r\n\r\nNavigationMesh::~NavigationMesh()\r\n{\r\n    ReleaseNavigationMesh();\r\n\r\n    delete queryFilter_;\r\n    queryFilter_ = 0;\r\n\r\n    delete pathData_;\r\n    pathData_ = 0;\r\n}\r\n\r\nvoid NavigationMesh::RegisterObject(Context* context)\r\n{\r\n    context->RegisterFactory<NavigationMesh>(NAVIGATION_CATEGORY);\r\n\r\n    ACCESSOR_ATTRIBUTE(\"Tile Size\", GetTileSize, SetTileSize, int, DEFAULT_TILE_SIZE, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Cell Size\", GetCellSize, SetCellSize, float, DEFAULT_CELL_SIZE, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Cell Height\", GetCellHeight, SetCellHeight, float, DEFAULT_CELL_HEIGHT, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Agent Height\", GetAgentHeight, SetAgentHeight, float, DEFAULT_AGENT_HEIGHT, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Agent Radius\", GetAgentRadius, SetAgentRadius, float, DEFAULT_AGENT_RADIUS, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Agent Max Climb\", GetAgentMaxClimb, SetAgentMaxClimb, float, DEFAULT_AGENT_MAX_CLIMB, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Agent Max Slope\", GetAgentMaxSlope, SetAgentMaxSlope, float, DEFAULT_AGENT_MAX_SLOPE, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Region Min Size\", GetRegionMinSize, SetRegionMinSize, float, DEFAULT_REGION_MIN_SIZE, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Region Merge Size\", GetRegionMergeSize, SetRegionMergeSize, float, DEFAULT_REGION_MERGE_SIZE, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Edge Max Length\", GetEdgeMaxLength, SetEdgeMaxLength, float, DEFAULT_EDGE_MAX_LENGTH, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Edge Max Error\", GetEdgeMaxError, SetEdgeMaxError, float, DEFAULT_EDGE_MAX_ERROR, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Detail Sample Distance\", GetDetailSampleDistance, SetDetailSampleDistance, float, DEFAULT_DETAIL_SAMPLE_DISTANCE, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Detail Sample Max Error\", GetDetailSampleMaxError, SetDetailSampleMaxError, float, DEFAULT_DETAIL_SAMPLE_MAX_ERROR, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Bounding Box Padding\", GetPadding, SetPadding, Vector3, Vector3::ONE, AM_DEFAULT);\r\n    MIXED_ACCESSOR_ATTRIBUTE(\"Navigation Data\", GetNavigationDataAttr, SetNavigationDataAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE | AM_NOEDIT);\r\n    ENUM_ACCESSOR_ATTRIBUTE(\"Partition Type\", GetPartitionType, SetPartitionType, NavmeshPartitionType, navmeshPartitionTypeNames, NAVMESH_PARTITION_WATERSHED, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Draw OffMeshConnections\", GetDrawOffMeshConnections, SetDrawOffMeshConnections, bool, false, AM_DEFAULT);\r\n    ACCESSOR_ATTRIBUTE(\"Draw NavAreas\", GetDrawNavAreas, SetDrawNavAreas, bool, false, AM_DEFAULT);\r\n}\r\n\r\nvoid NavigationMesh::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)\r\n{\r\n    if (!debug || !navMesh_ || !node_)\r\n        return;\r\n\r\n    const Matrix3x4& worldTransform = node_->GetWorldTransform();\r\n\r\n    const dtNavMesh* navMesh = navMesh_;\r\n\r\n    for (int z = 0; z < numTilesZ_; ++z)\r\n    {\r\n        for (int x = 0; x < numTilesX_; ++x)\r\n        {\r\n            for (int i = 0; i < 128; ++i)\r\n            {\r\n                const dtMeshTile* tile = navMesh->getTileAt(x, z, i);\r\n                if (!tile)\r\n                    continue;\r\n\r\n                for (int i = 0; i < tile->header->polyCount; ++i)\r\n                {\r\n                    dtPoly* poly = tile->polys + i;\r\n                    for (unsigned j = 0; j < poly->vertCount; ++j)\r\n                    {\r\n                        debug->AddLine(\r\n                            worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[j] * 3]),\r\n                            worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[(j + 1) % poly->vertCount] * 3]),\r\n                            Color::YELLOW,\r\n                            depthTest\r\n                            );\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    Scene* scene = GetScene();\r\n    if (scene)\r\n    {\r\n        \/\/ Draw OffMeshConnection components\r\n        if (drawOffMeshConnections_)\r\n        {\r\n            PODVector<Node*> connections;\r\n            scene->GetChildrenWithComponent<OffMeshConnection>(connections, true);\r\n            for (unsigned i = 0; i < connections.Size(); ++i)\r\n            {\r\n                OffMeshConnection* connection = connections[i]->GetComponent<OffMeshConnection>();\r\n                if (connection && connection->IsEnabledEffective())\r\n                    connection->DrawDebugGeometry(debug, depthTest);\r\n            }\r\n        }\r\n\r\n        \/\/ Draw NavArea components\r\n        if (drawNavAreas_)\r\n        {\r\n            PODVector<Node*> areas;\r\n            scene->GetChildrenWithComponent<NavArea>(areas, true);\r\n            for (unsigned i = 0; i < areas.Size(); ++i)\r\n            {\r\n                NavArea* area = areas[i]->GetComponent<NavArea>();\r\n                if (area && area->IsEnabledEffective())\r\n                    area->DrawDebugGeometry(debug, depthTest);\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nvoid NavigationMesh::SetMeshName(const String& newName)\r\n{\r\n    meshName_ = newName;\r\n}\r\n\r\nvoid NavigationMesh::SetTileSize(int size)\r\n{\r\n    tileSize_ = Max(size, 16);\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid NavigationMesh::SetCellSize(float size)\r\n{\r\n    cellSize_ = Max(size, M_EPSILON);\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid NavigationMesh::SetCellHeight(float height)\r\n{\r\n    cellHeight_ = Max(height, M_EPSILON);\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid NavigationMesh::SetAgentHeight(float height)\r\n{\r\n    agentHeight_ = Max(height, M_EPSILON);\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid NavigationMesh::SetAgentRadius(float radius)\r\n{\r\n    agentRadius_ = Max(radius, M_EPSILON);\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid NavigationMesh::SetAgentMaxClimb(float maxClimb)\r\n{\r\n    agentMaxClimb_ = Max(maxClimb, M_EPSILON);\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid NavigationMesh::SetAgentMaxSlope(float maxSlope)\r\n{\r\n    agentMaxSlope_ = Max(maxSlope, 0.0f);\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid NavigationMesh::SetRegionMinSize(float size)\r\n{\r\n    regionMinSize_ = Max(size, M_EPSILON);\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid NavigationMesh::SetRegionMergeSize(float size)\r\n{\r\n    regionMergeSize_ = Max(size, M_EPSILON);\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid NavigationMesh::SetEdgeMaxLength(float length)\r\n{\r\n    edgeMaxLength_ = Max(length, M_EPSILON);\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid NavigationMesh::SetEdgeMaxError(float error)\r\n{\r\n    edgeMaxError_ = Max(error, M_EPSILON);\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid NavigationMesh::SetDetailSampleDistance(float distance)\r\n{\r\n    detailSampleDistance_ = Max(distance, M_EPSILON);\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid NavigationMesh::SetDetailSampleMaxError(float error)\r\n{\r\n    detailSampleMaxError_ = Max(error, M_EPSILON);\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid NavigationMesh::SetPadding(const Vector3& padding)\r\n{\r\n    padding_ = padding;\r\n\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nbool NavigationMesh::Build()\r\n{\r\n    PROFILE(BuildNavigationMesh);\r\n\r\n    \/\/ Release existing navigation data and zero the bounding box\r\n    ReleaseNavigationMesh();\r\n\r\n    if (!node_)\r\n        return false;\r\n\r\n    if (!node_->GetWorldScale().Equals(Vector3::ONE))\r\n        LOGWARNING(\"Navigation mesh root node has scaling. Agent parameters may not work as intended\");\r\n\r\n    Vector<NavigationGeometryInfo> geometryList;\r\n    CollectGeometries(geometryList);\r\n\r\n    if (geometryList.Empty())\r\n        return true; \/\/ Nothing to do\r\n\r\n    \/\/ Build the combined bounding box\r\n    for (unsigned i = 0; i < geometryList.Size(); ++i)\r\n        boundingBox_.Merge(geometryList[i].boundingBox_);\r\n\r\n    \/\/ Expand bounding box by padding\r\n    boundingBox_.min_ -= padding_;\r\n    boundingBox_.max_ += padding_;\r\n\r\n    {\r\n        PROFILE(BuildNavigationMesh);\r\n\r\n        \/\/ Calculate number of tiles\r\n        int gridW = 0, gridH = 0;\r\n        float tileEdgeLength = (float)tileSize_ * cellSize_;\r\n        rcCalcGridSize(&boundingBox_.min_.x_, &boundingBox_.max_.x_, cellSize_, &gridW, &gridH);\r\n        numTilesX_ = (gridW + tileSize_ - 1) \/ tileSize_;\r\n        numTilesZ_ = (gridH + tileSize_ - 1) \/ tileSize_;\r\n\r\n        \/\/ Calculate max. number of tiles and polygons, 22 bits available to identify both tile & polygon within tile\r\n        unsigned maxTiles = NextPowerOfTwo(numTilesX_ * numTilesZ_);\r\n        unsigned tileBits = 0;\r\n        unsigned temp = maxTiles;\r\n        while (temp > 1)\r\n        {\r\n            temp >>= 1;\r\n            ++tileBits;\r\n        }\r\n\r\n        unsigned maxPolys = 1 << (22 - tileBits);\r\n\r\n        dtNavMeshParams params;\r\n        rcVcopy(params.orig, &boundingBox_.min_.x_);\r\n        params.tileWidth = tileEdgeLength;\r\n        params.tileHeight = tileEdgeLength;\r\n        params.maxTiles = maxTiles;\r\n        params.maxPolys = maxPolys;\r\n\r\n        navMesh_ = dtAllocNavMesh();\r\n        if (!navMesh_)\r\n        {\r\n            LOGERROR(\"Could not allocate navigation mesh\");\r\n            return false;\r\n        }\r\n\r\n        if (dtStatusFailed(navMesh_->init(&params)))\r\n        {\r\n            LOGERROR(\"Could not initialize navigation mesh\");\r\n            ReleaseNavigationMesh();\r\n            return false;\r\n        }\r\n\r\n        \/\/ Build each tile\r\n        unsigned numTiles = 0;\r\n\r\n        for (int z = 0; z < numTilesZ_; ++z)\r\n        {\r\n            for (int x = 0; x < numTilesX_; ++x)\r\n            {\r\n                if (BuildTile(geometryList, x, z))\r\n                    ++numTiles;\r\n            }\r\n        }\r\n\r\n        LOGDEBUG(\"Built navigation mesh with \" + String(numTiles) + \" tiles\");\r\n\r\n        \/\/ Send a notification event to concerned parties that we've been fully rebuilt\r\n        {\r\n            using namespace NavigationMeshRebuilt;\r\n            VariantMap& buildEventParams = GetContext()->GetEventDataMap();\r\n            buildEventParams[P_NODE] = node_;\r\n            buildEventParams[P_MESH] = this;\r\n            SendEvent(E_NAVIGATION_MESH_REBUILT, buildEventParams);\r\n        }\r\n\r\n        return true;\r\n    }\r\n}\r\n\r\nbool NavigationMesh::Build(const BoundingBox& boundingBox)\r\n{\r\n    PROFILE(BuildPartialNavigationMesh);\r\n\r\n    if (!node_)\r\n        return false;\r\n\r\n    if (!navMesh_)\r\n    {\r\n        LOGERROR(\"Navigation mesh must first be built fully before it can be partially rebuilt\");\r\n        return false;\r\n    }\r\n\r\n    if (!node_->GetWorldScale().Equals(Vector3::ONE))\r\n        LOGWARNING(\"Navigation mesh root node has scaling. Agent parameters may not work as intended\");\r\n\r\n    BoundingBox localSpaceBox = boundingBox.Transformed(node_->GetWorldTransform().Inverse());\r\n\r\n    float tileEdgeLength = (float)tileSize_ * cellSize_;\r\n\r\n    Vector<NavigationGeometryInfo> geometryList;\r\n    CollectGeometries(geometryList);\r\n\r\n    int sx = Clamp((int)((localSpaceBox.min_.x_ - boundingBox_.min_.x_) \/ tileEdgeLength), 0, numTilesX_ - 1);\r\n    int sz = Clamp((int)((localSpaceBox.min_.z_ - boundingBox_.min_.z_) \/ tileEdgeLength), 0, numTilesZ_ - 1);\r\n    int ex = Clamp((int)((localSpaceBox.max_.x_ - boundingBox_.min_.x_) \/ tileEdgeLength), 0, numTilesX_ - 1);\r\n    int ez = Clamp((int)((localSpaceBox.max_.z_ - boundingBox_.min_.z_) \/ tileEdgeLength), 0, numTilesZ_ - 1);\r\n\r\n    unsigned numTiles = 0;\r\n\r\n    for (int z = sz; z <= ez; ++z)\r\n    {\r\n        for (int x = sx; x <= ex; ++x)\r\n        {\r\n            if (BuildTile(geometryList, x, z))\r\n                ++numTiles;\r\n        }\r\n    }\r\n\r\n    LOGDEBUG(\"Rebuilt \" + String(numTiles) + \" tiles of the navigation mesh\");\r\n    return true;\r\n}\r\n\r\nVector3 NavigationMesh::FindNearestPoint(const Vector3& point, const Vector3& extents)\r\n{\r\n    if(!InitializeQuery())\r\n        return point;\r\n\r\n    const Matrix3x4& transform = node_->GetWorldTransform();\r\n    Matrix3x4 inverse = transform.Inverse();\r\n\r\n    Vector3 localPoint = inverse * point;\r\n    Vector3 nearestPoint;\r\n\r\n    dtPolyRef pointRef;\r\n    navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, queryFilter_, &pointRef, &nearestPoint.x_);\r\n    if (!pointRef)\r\n        return point;\r\n\r\n    return transform*nearestPoint;\r\n}\r\n\r\nVector3 NavigationMesh::MoveAlongSurface(const Vector3& start, const Vector3& end, const Vector3& extents, int maxVisited)\r\n{\r\n    if (!InitializeQuery())\r\n        return end;\r\n\r\n    const Matrix3x4& transform = node_->GetWorldTransform();\r\n    Matrix3x4 inverse = transform.Inverse();\r\n\r\n    Vector3 localStart = inverse * start;\r\n    Vector3 localEnd = inverse * end;\r\n\r\n    dtPolyRef startRef;\r\n    navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);\r\n    if (!startRef)\r\n        return end;\r\n\r\n    Vector3 resultPos;\r\n    int visitedCount = 0;\r\n    maxVisited = Max(maxVisited, 0);\r\n    PODVector<dtPolyRef> visited(maxVisited);\r\n    navMeshQuery_->moveAlongSurface(startRef, &localStart.x_, &localEnd.x_, queryFilter_, &resultPos.x_, maxVisited ?\r\n        &visited[0] : (dtPolyRef*)0, &visitedCount, maxVisited);\r\n    return transform * resultPos;\r\n}\r\n\r\nvoid NavigationMesh::FindPath(PODVector<Vector3>& dest, const Vector3& start, const Vector3& end, const Vector3& extents)\r\n{\r\n    PROFILE(FindPath);\r\n\r\n    dest.Clear();\r\n\r\n    if (!InitializeQuery())\r\n        return;\r\n\r\n    \/\/ Navigation data is in local space. Transform path points from world to local\r\n    const Matrix3x4& transform = node_->GetWorldTransform();\r\n    Matrix3x4 inverse = transform.Inverse();\r\n\r\n    Vector3 localStart = inverse * start;\r\n    Vector3 localEnd = inverse * end;\r\n\r\n    dtPolyRef startRef;\r\n    dtPolyRef endRef;\r\n    navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);\r\n    navMeshQuery_->findNearestPoly(&localEnd.x_, &extents.x_, queryFilter_, &endRef, 0);\r\n\r\n    if (!startRef || !endRef)\r\n        return;\r\n\r\n    int numPolys = 0;\r\n    int numPathPoints = 0;\r\n\r\n    navMeshQuery_->findPath(startRef, endRef, &localStart.x_, &localEnd.x_, queryFilter_, pathData_->polys_, &numPolys,\r\n        MAX_POLYS);\r\n    if (!numPolys)\r\n        return;\r\n\r\n    Vector3 actualLocalEnd = localEnd;\r\n\r\n    \/\/ If full path was not found, clamp end point to the end polygon\r\n    if (pathData_->polys_[numPolys - 1] != endRef)\r\n        navMeshQuery_->closestPointOnPoly(pathData_->polys_[numPolys - 1], &localEnd.x_, &actualLocalEnd.x_, 0);\r\n\r\n    navMeshQuery_->findStraightPath(&localStart.x_, &actualLocalEnd.x_, pathData_->polys_, numPolys,\r\n        &pathData_->pathPoints_[0].x_, pathData_->pathFlags_, pathData_->pathPolys_, &numPathPoints, MAX_POLYS);\r\n\r\n    \/\/ Transform path result back to world space\r\n    for (int i = 0; i < numPathPoints; ++i)\r\n        dest.Push(transform * pathData_->pathPoints_[i]);\r\n}\r\n\r\nVector3 NavigationMesh::GetRandomPoint()\r\n{\r\n    if (!InitializeQuery())\r\n        return Vector3::ZERO;\r\n\r\n    dtPolyRef polyRef;\r\n    Vector3 point(Vector3::ZERO);\r\n\r\n    navMeshQuery_->findRandomPoint(queryFilter_, Random, &polyRef, &point.x_);\r\n\r\n    return node_->GetWorldTransform() * point;\r\n}\r\n\r\nVector3 NavigationMesh::GetRandomPointInCircle(const Vector3& center, float radius, const Vector3& extents)\r\n{\r\n    if (!InitializeQuery())\r\n        return center;\r\n\r\n    const Matrix3x4& transform = node_->GetWorldTransform();\r\n    Matrix3x4 inverse = transform.Inverse();\r\n    Vector3 localCenter = inverse * center;\r\n\r\n    dtPolyRef startRef;\r\n    navMeshQuery_->findNearestPoly(&localCenter.x_, &extents.x_, queryFilter_, &startRef, 0);\r\n    if (!startRef)\r\n        return center;\r\n\r\n    dtPolyRef polyRef;\r\n    Vector3 point(localCenter);\r\n\r\n    navMeshQuery_->findRandomPointAroundCircle(startRef, &localCenter.x_, radius, queryFilter_, Random, &polyRef, &point.x_);\r\n\r\n    return transform * point;\r\n}\r\n\r\nfloat NavigationMesh::GetDistanceToWall(const Vector3& point, float radius, const Vector3& extents, Vector3* position, Vector3* normal)\r\n{\r\n    if (!InitializeQuery())\r\n        return radius;\r\n\r\n    const Matrix3x4& transform = node_->GetWorldTransform();\r\n    Matrix3x4 inverse = transform.Inverse();\r\n    Vector3 localPoint = inverse * point;\r\n\r\n    dtPolyRef startRef;\r\n    navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, queryFilter_, &startRef, 0);\r\n    if (!startRef)\r\n        return radius;\r\n\r\n    float hitDist = radius;\r\n    Vector3 hitPos;\r\n    Vector3 hitNormal;\r\n\r\n    navMeshQuery_->findDistanceToWall(startRef, &localPoint.x_, radius, queryFilter_, &hitDist, &hitPos.x_, &hitNormal.x_);\r\n\r\n    if (position)\r\n        *position = hitPos;\r\n\r\n    if (normal)\r\n        *normal = hitNormal;\r\n\r\n    return hitDist;\r\n}\r\n\r\nVector3 NavigationMesh::Raycast(const Vector3& start, const Vector3& end, const Vector3& extents)\r\n{\r\n    if (!InitializeQuery())\r\n        return end;\r\n\r\n    const Matrix3x4& transform = node_->GetWorldTransform();\r\n    Matrix3x4 inverse = transform.Inverse();\r\n\r\n    Vector3 localStart = inverse * start;\r\n    Vector3 localEnd = inverse * end;\r\n\r\n    dtPolyRef startRef;\r\n    navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);\r\n    if (!startRef)\r\n        return end;\r\n\r\n    Vector3 localHitNormal;\r\n    float t;\r\n    int numPolys;\r\n\r\n    navMeshQuery_->raycast(startRef, &localStart.x_, &localEnd.x_, queryFilter_, &t, &localHitNormal.x_, pathData_->polys_, &numPolys, MAX_POLYS);\r\n    if (t == FLT_MAX)\r\n        t = 1.0f;\r\n\r\n    return start.Lerp(end, t);\r\n}\r\n\r\nvoid NavigationMesh::DrawDebugGeometry(bool depthTest)\r\n{\r\n    Scene* scene = GetScene();\r\n    if (scene)\r\n    {\r\n        DebugRenderer* debug = scene->GetComponent<DebugRenderer>();\r\n        if (debug)\r\n            DrawDebugGeometry(debug, depthTest);\r\n    }\r\n}\r\n\r\nvoid NavigationMesh::SetAreaCost(unsigned areaID, float cost)\r\n{\r\n    if (queryFilter_)\r\n        queryFilter_->setAreaCost((int)areaID, cost);\r\n}\r\n\r\nBoundingBox NavigationMesh::GetWorldBoundingBox() const\r\n{\r\n    return node_ ? boundingBox_.Transformed(node_->GetWorldTransform()) : boundingBox_;\r\n}\r\n\r\nfloat NavigationMesh::GetAreaCost(unsigned areaID) const\r\n{\r\n    if (queryFilter_)\r\n        return queryFilter_->getAreaCost((int)areaID);\r\n    return 1.0f;\r\n}\r\n\r\nvoid NavigationMesh::SetNavigationDataAttr(const PODVector<unsigned char>& value)\r\n{\r\n    ReleaseNavigationMesh();\r\n\r\n    if (value.Empty())\r\n        return;\r\n\r\n    MemoryBuffer buffer(value);\r\n\r\n    boundingBox_ = buffer.ReadBoundingBox();\r\n    numTilesX_ = buffer.ReadInt();\r\n    numTilesZ_ = buffer.ReadInt();\r\n\r\n    dtNavMeshParams params;\r\n    rcVcopy(params.orig, &boundingBox_.min_.x_);\r\n    params.tileWidth = buffer.ReadFloat();\r\n    params.tileHeight = buffer.ReadFloat();\r\n    params.maxTiles = buffer.ReadInt();\r\n    params.maxPolys = buffer.ReadInt();\r\n\r\n    navMesh_ = dtAllocNavMesh();\r\n    if (!navMesh_)\r\n    {\r\n        LOGERROR(\"Could not allocate navigation mesh\");\r\n        return;\r\n    }\r\n\r\n    if (dtStatusFailed(navMesh_->init(&params)))\r\n    {\r\n        LOGERROR(\"Could not initialize navigation mesh\");\r\n        ReleaseNavigationMesh();\r\n        return;\r\n    }\r\n\r\n    unsigned numTiles = 0;\r\n\r\n    while (!buffer.IsEof())\r\n    {\r\n        \/*int x =*\/ buffer.ReadInt();\r\n        \/*int z =*\/ buffer.ReadInt();\r\n        \/*dtTileRef tileRef =*\/ buffer.ReadUInt();\r\n        unsigned navDataSize = buffer.ReadUInt();\r\n\r\n        unsigned char* navData = (unsigned char*)dtAlloc(navDataSize, DT_ALLOC_PERM);\r\n        if (!navData)\r\n        {\r\n            LOGERROR(\"Could not allocate data for navigation mesh tile\");\r\n            return;\r\n        }\r\n\r\n        buffer.Read(navData, navDataSize);\r\n        if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))\r\n        {\r\n            LOGERROR(\"Failed to add navigation mesh tile\");\r\n            dtFree(navData);\r\n            return;\r\n        }\r\n        else\r\n            ++numTiles;\r\n    }\r\n\r\n    LOGDEBUG(\"Created navigation mesh with \" + String(numTiles) + \" tiles from serialized data\");\r\n}\r\n\r\nPODVector<unsigned char> NavigationMesh::GetNavigationDataAttr() const\r\n{\r\n    VectorBuffer ret;\r\n\r\n    if (navMesh_)\r\n    {\r\n        ret.WriteBoundingBox(boundingBox_);\r\n        ret.WriteInt(numTilesX_);\r\n        ret.WriteInt(numTilesZ_);\r\n\r\n        const dtNavMeshParams* params = navMesh_->getParams();\r\n        ret.WriteFloat(params->tileWidth);\r\n        ret.WriteFloat(params->tileHeight);\r\n        ret.WriteInt(params->maxTiles);\r\n        ret.WriteInt(params->maxPolys);\r\n\r\n        const dtNavMesh* navMesh = navMesh_;\r\n\r\n        for (int z = 0; z < numTilesZ_; ++z)\r\n        {\r\n            for (int x = 0; x < numTilesX_; ++x)\r\n            {\r\n                const dtMeshTile* tile = navMesh->getTileAt(x, z, 0);\r\n                if (!tile)\r\n                    continue;\r\n\r\n                ret.WriteInt(x);\r\n                ret.WriteInt(z);\r\n                ret.WriteUInt(navMesh->getTileRef(tile));\r\n                ret.WriteUInt(tile->dataSize);\r\n                ret.Write(tile->data, tile->dataSize);\r\n            }\r\n        }\r\n    }\r\n\r\n    return ret.GetBuffer();\r\n}\r\n\r\nvoid NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList)\r\n{\r\n    PROFILE(CollectNavigationGeometry);\r\n\r\n    \/\/ Get Navigable components from child nodes, not from whole scene. This makes it possible to partition\r\n    \/\/ the scene into several navigation meshes\r\n    PODVector<Navigable*> navigables;\r\n    node_->GetComponents<Navigable>(navigables, true);\r\n\r\n    HashSet<Node*> processedNodes;\r\n    for (unsigned i = 0; i < navigables.Size(); ++i)\r\n    {\r\n        if (navigables[i]->IsEnabledEffective())\r\n            CollectGeometries(geometryList, navigables[i]->GetNode(), processedNodes, navigables[i]->IsRecursive());\r\n    }\r\n\r\n    \/\/ Get offmesh connections\r\n    Matrix3x4 inverse = node_->GetWorldTransform().Inverse();\r\n    PODVector<OffMeshConnection*> connections;\r\n    node_->GetComponents<OffMeshConnection>(connections, true);\r\n\r\n    for (unsigned i = 0; i < connections.Size(); ++i)\r\n    {\r\n        OffMeshConnection* connection = connections[i];\r\n        if (connection->IsEnabledEffective() && connection->GetEndPoint())\r\n        {\r\n            const Matrix3x4& transform = connection->GetNode()->GetWorldTransform();\r\n\r\n            NavigationGeometryInfo info;\r\n            info.component_ = connection;\r\n            info.boundingBox_ = BoundingBox(Sphere(transform.Translation(), connection->GetRadius())).Transformed(inverse);\r\n\r\n            geometryList.Push(info);\r\n        }\r\n    }\r\n\r\n    \/\/ Get nav area volumes\r\n    PODVector<NavArea*> navAreas;\r\n    node_->GetComponents<NavArea>(navAreas, true);\r\n    for (unsigned i = 0; i < navAreas.Size(); ++i)\r\n    {\r\n        NavArea* area = navAreas[i];\r\n        \/\/ Ignore disabled AND any areas that have no meaningful settings\r\n        if (area->IsEnabledEffective() && area->GetAreaID() != 0)\r\n        {\r\n            NavigationGeometryInfo info;\r\n            info.component_ = area;\r\n            info.boundingBox_ = area->GetWorldBoundingBox();\r\n            geometryList.Push(info);\r\n        }\r\n    }\r\n}\r\n\r\nvoid NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList, Node* node, HashSet<Node*>& processedNodes, bool recursive)\r\n{\r\n    \/\/ Make sure nodes are not included twice\r\n    if (processedNodes.Contains(node))\r\n        return;\r\n    \/\/ Exclude obstacles from consideration\r\n    if (node->HasComponent<Obstacle>())\r\n        return;\r\n    processedNodes.Insert(node);\r\n\r\n    Matrix3x4 inverse = node_->GetWorldTransform().Inverse();\r\n\r\n#ifdef URHO3D_PHYSICS\r\n    \/\/ Prefer compatible physics collision shapes (triangle mesh, convex hull, box) if found.\r\n    \/\/ Then fallback to visible geometry\r\n    PODVector<CollisionShape*> collisionShapes;\r\n    node->GetComponents<CollisionShape>(collisionShapes);\r\n    bool collisionShapeFound = false;\r\n\r\n    for (unsigned i = 0; i < collisionShapes.Size(); ++i)\r\n    {\r\n        CollisionShape* shape = collisionShapes[i];\r\n        if (!shape->IsEnabledEffective())\r\n            continue;\r\n\r\n        ShapeType type = shape->GetShapeType();\r\n        if ((type == SHAPE_BOX || type == SHAPE_TRIANGLEMESH || type == SHAPE_CONVEXHULL) && shape->GetCollisionShape())\r\n        {\r\n            Matrix3x4 shapeTransform(shape->GetPosition(), shape->GetRotation(), shape->GetSize());\r\n\r\n            NavigationGeometryInfo info;\r\n            info.component_ = shape;\r\n            info.transform_ = inverse * node->GetWorldTransform() * shapeTransform;\r\n            info.boundingBox_ = shape->GetWorldBoundingBox().Transformed(inverse);\r\n\r\n            geometryList.Push(info);\r\n            collisionShapeFound = true;\r\n        }\r\n    }\r\n    if (!collisionShapeFound)\r\n#endif\r\n    {\r\n        PODVector<Drawable*> drawables;\r\n        node->GetDerivedComponents<Drawable>(drawables);\r\n\r\n        for (unsigned i = 0; i < drawables.Size(); ++i)\r\n        {\r\n            \/\/\/ \\todo Evaluate whether should handle other types. Now StaticModel & TerrainPatch are supported, others skipped\r\n            Drawable* drawable = drawables[i];\r\n            if (!drawable->IsEnabledEffective())\r\n                continue;\r\n\r\n            NavigationGeometryInfo info;\r\n\r\n            if (drawable->GetType() == StaticModel::GetTypeStatic())\r\n                info.lodLevel_ = static_cast<StaticModel*>(drawable)->GetOcclusionLodLevel();\r\n            else if (drawable->GetType() == TerrainPatch::GetTypeStatic())\r\n                info.lodLevel_ = 0;\r\n            else\r\n                continue;\r\n\r\n            info.component_ = drawable;\r\n            info.transform_ = inverse * node->GetWorldTransform();\r\n            info.boundingBox_ = drawable->GetWorldBoundingBox().Transformed(inverse);\r\n\r\n            geometryList.Push(info);\r\n        }\r\n    }\r\n\r\n    if (recursive)\r\n    {\r\n        const Vector<SharedPtr<Node> >& children = node->GetChildren();\r\n        for(unsigned i = 0; i < children.Size(); ++i)\r\n            CollectGeometries(geometryList, children[i], processedNodes, recursive);\r\n    }\r\n}\r\n\r\nvoid NavigationMesh::GetTileGeometry(NavBuildData* build, Vector<NavigationGeometryInfo>& geometryList, BoundingBox& box)\r\n{\r\n    Matrix3x4 inverse = node_->GetWorldTransform().Inverse();\r\n\r\n    for (unsigned i = 0; i < geometryList.Size(); ++i)\r\n    {\r\n        if (box.IsInsideFast(geometryList[i].boundingBox_) != OUTSIDE)\r\n        {\r\n            const Matrix3x4& transform = geometryList[i].transform_;\r\n\r\n            if (geometryList[i].component_->GetType() == OffMeshConnection::GetTypeStatic())\r\n            {\r\n                OffMeshConnection* connection = static_cast<OffMeshConnection*>(geometryList[i].component_);\r\n                Vector3 start = inverse * connection->GetNode()->GetWorldPosition();\r\n                Vector3 end = inverse * connection->GetEndPoint()->GetWorldPosition();\r\n\r\n                build->offMeshVertices_.Push(start);\r\n                build->offMeshVertices_.Push(end);\r\n                build->offMeshRadii_.Push(connection->GetRadius());\r\n                build->offMeshFlags_.Push(connection->GetMask());\r\n                build->offMeshAreas_.Push((unsigned char)connection->GetAreaID());\r\n                build->offMeshDir_.Push(connection->IsBidirectional() ? DT_OFFMESH_CON_BIDIR : 0);\r\n                continue;\r\n            }\r\n            else if (geometryList[i].component_->GetType() == NavArea::GetTypeStatic())\r\n            {\r\n                NavArea* area = static_cast<NavArea*>(geometryList[i].component_);\r\n                NavAreaStub stub;\r\n                stub.areaID_ = (unsigned char)area->GetAreaID();\r\n                stub.bounds_ = area->GetWorldBoundingBox();\r\n                build->navAreas_.Push(stub);\r\n                continue;\r\n            }\r\n\r\n#ifdef URHO3D_PHYSICS\r\n            CollisionShape* shape = dynamic_cast<CollisionShape*>(geometryList[i].component_);\r\n            if (shape)\r\n            {\r\n                switch (shape->GetShapeType())\r\n                {\r\n                case SHAPE_TRIANGLEMESH:\r\n                    {\r\n                        Model* model = shape->GetModel();\r\n                        if (!model)\r\n                            continue;\r\n\r\n                        unsigned lodLevel = shape->GetLodLevel();\r\n                        for (unsigned j = 0; j < model->GetNumGeometries(); ++j)\r\n                            AddTriMeshGeometry(build, model->GetGeometry(j, lodLevel), transform);\r\n                    }\r\n                    break;\r\n\r\n                case SHAPE_CONVEXHULL:\r\n                    {\r\n                        ConvexData* data = static_cast<ConvexData*>(shape->GetGeometryData());\r\n                        if (!data)\r\n                            continue;\r\n\r\n                        unsigned numVertices = data->vertexCount_;\r\n                        unsigned numIndices = data->indexCount_;\r\n                        unsigned destVertexStart = build->vertices_.Size();\r\n\r\n                        for (unsigned j = 0; j < numVertices; ++j)\r\n                            build->vertices_.Push(transform * data->vertexData_[j]);\r\n\r\n                        for (unsigned j = 0; j < numIndices; ++j)\r\n                            build->indices_.Push(data->indexData_[j] + destVertexStart);\r\n                    }\r\n                    break;\r\n\r\n                case SHAPE_BOX:\r\n                    {\r\n                        unsigned destVertexStart = build->vertices_.Size();\r\n\r\n                        build->vertices_.Push(transform * Vector3(-0.5f, 0.5f, -0.5f));\r\n                        build->vertices_.Push(transform * Vector3(0.5f, 0.5f, -0.5f));\r\n                        build->vertices_.Push(transform * Vector3(0.5f, -0.5f, -0.5f));\r\n                        build->vertices_.Push(transform * Vector3(-0.5f, -0.5f, -0.5f));\r\n                        build->vertices_.Push(transform * Vector3(-0.5f, 0.5f, 0.5f));\r\n                        build->vertices_.Push(transform * Vector3(0.5f, 0.5f, 0.5f));\r\n                        build->vertices_.Push(transform * Vector3(0.5f, -0.5f, 0.5f));\r\n                        build->vertices_.Push(transform * Vector3(-0.5f, -0.5f, 0.5f));\r\n\r\n                        const unsigned indices[] = {\r\n                            0, 1, 2, 0, 2, 3, 1, 5, 6, 1, 6, 2, 4, 5, 1, 4, 1, 0, 5, 4, 7, 5, 7, 6,\r\n                            4, 0, 3, 4, 3, 7, 1, 0, 4, 1, 4, 5\r\n                        };\r\n\r\n                        for (unsigned j = 0; j < 36; ++j)\r\n                            build->indices_.Push(indices[j] + destVertexStart);\r\n                    }\r\n                    break;\r\n\r\n                default:\r\n                    break;\r\n                }\r\n\r\n                continue;\r\n            }\r\n#endif\r\n            Drawable* drawable = dynamic_cast<Drawable*>(geometryList[i].component_);\r\n            if (drawable)\r\n            {\r\n                const Vector<SourceBatch>& batches = drawable->GetBatches();\r\n\r\n                for (unsigned j = 0; j < batches.Size(); ++j)\r\n                    AddTriMeshGeometry(build, drawable->GetLodGeometry(j, geometryList[i].lodLevel_), transform);\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nvoid NavigationMesh::AddTriMeshGeometry(NavBuildData* build, Geometry* geometry, const Matrix3x4& transform)\r\n{\r\n    if (!geometry)\r\n        return;\r\n\r\n    const unsigned char* vertexData;\r\n    const unsigned char* indexData;\r\n    unsigned vertexSize;\r\n    unsigned indexSize;\r\n    unsigned elementMask;\r\n\r\n    geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);\r\n    if (!vertexData || !indexData || (elementMask & MASK_POSITION) == 0)\r\n        return;\r\n\r\n    unsigned srcIndexStart = geometry->GetIndexStart();\r\n    unsigned srcIndexCount = geometry->GetIndexCount();\r\n    unsigned srcVertexStart = geometry->GetVertexStart();\r\n    unsigned srcVertexCount = geometry->GetVertexCount();\r\n\r\n    if (!srcIndexCount)\r\n        return;\r\n\r\n    unsigned destVertexStart = build->vertices_.Size();\r\n\r\n    for (unsigned k = srcVertexStart; k < srcVertexStart + srcVertexCount; ++k)\r\n    {\r\n        Vector3 vertex = transform * *((const Vector3*)(&vertexData[k * vertexSize]));\r\n        build->vertices_.Push(vertex);\r\n    }\r\n\r\n    \/\/ Copy remapped indices\r\n    if (indexSize == sizeof(unsigned short))\r\n    {\r\n        const unsigned short* indices = ((const unsigned short*)indexData) + srcIndexStart;\r\n        const unsigned short* indicesEnd = indices + srcIndexCount;\r\n\r\n        while (indices < indicesEnd)\r\n        {\r\n            build->indices_.Push(*indices - srcVertexStart + destVertexStart);\r\n            ++indices;\r\n        }\r\n    }\r\n    else\r\n    {\r\n        const unsigned* indices = ((const unsigned*)indexData) + srcIndexStart;\r\n        const unsigned* indicesEnd = indices + srcIndexCount;\r\n\r\n        while (indices < indicesEnd)\r\n        {\r\n            build->indices_.Push(*indices - srcVertexStart + destVertexStart);\r\n            ++indices;\r\n        }\r\n    }\r\n}\r\n\r\nbool NavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z)\r\n{\r\n    PROFILE(BuildNavigationMeshTile);\r\n\r\n    \/\/ Remove previous tile (if any)\r\n    navMesh_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);\r\n\r\n    float tileEdgeLength = (float)tileSize_ * cellSize_;\r\n\r\n    BoundingBox tileBoundingBox(Vector3(\r\n        boundingBox_.min_.x_ + tileEdgeLength * (float)x,\r\n        boundingBox_.min_.y_,\r\n        boundingBox_.min_.z_ + tileEdgeLength * (float)z\r\n    ),\r\n    Vector3(\r\n        boundingBox_.min_.x_ + tileEdgeLength * (float)(x + 1),\r\n        boundingBox_.max_.y_,\r\n        boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)\r\n    ));\r\n\r\n    SimpleNavBuildData build;\r\n\r\n    rcConfig cfg;\r\n    memset(&cfg, 0, sizeof cfg);\r\n    cfg.cs = cellSize_;\r\n    cfg.ch = cellHeight_;\r\n    cfg.walkableSlopeAngle = agentMaxSlope_;\r\n    cfg.walkableHeight = (int)ceilf(agentHeight_ \/ cfg.ch);\r\n    cfg.walkableClimb = (int)floorf(agentMaxClimb_ \/ cfg.ch);\r\n    cfg.walkableRadius = (int)ceilf(agentRadius_ \/ cfg.cs);\r\n    cfg.maxEdgeLen = (int)(edgeMaxLength_ \/ cellSize_);\r\n    cfg.maxSimplificationError = edgeMaxError_;\r\n    cfg.minRegionArea = (int)sqrtf(regionMinSize_);\r\n    cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);\r\n    cfg.maxVertsPerPoly = 6;\r\n    cfg.tileSize = tileSize_;\r\n    cfg.borderSize = cfg.walkableRadius + 3; \/\/ Add padding\r\n    cfg.width = cfg.tileSize + cfg.borderSize * 2;\r\n    cfg.height = cfg.tileSize + cfg.borderSize * 2;\r\n    cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;\r\n    cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;\r\n\r\n    rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);\r\n    rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);\r\n    cfg.bmin[0] -= cfg.borderSize * cfg.cs;\r\n    cfg.bmin[2] -= cfg.borderSize * cfg.cs;\r\n    cfg.bmax[0] += cfg.borderSize * cfg.cs;\r\n    cfg.bmax[2] += cfg.borderSize * cfg.cs;\r\n\r\n    BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));\r\n    GetTileGeometry(&build, geometryList, expandedBox);\r\n\r\n    if (build.vertices_.Empty() || build.indices_.Empty())\r\n        return true; \/\/ Nothing to do\r\n\r\n    build.heightField_ = rcAllocHeightfield();\r\n    if (!build.heightField_)\r\n    {\r\n        LOGERROR(\"Could not allocate heightfield\");\r\n        return false;\r\n    }\r\n\r\n    if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,\r\n        cfg.ch))\r\n    {\r\n        LOGERROR(\"Could not create heightfield\");\r\n        return false;\r\n    }\r\n\r\n    unsigned numTriangles = build.indices_.Size() \/ 3;\r\n    SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);\r\n    memset(triAreas.Get(), 0, numTriangles);\r\n\r\n    rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),\r\n        &build.indices_[0], numTriangles, triAreas.Get());\r\n    rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],\r\n        triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);\r\n    rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);\r\n\r\n    rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);\r\n    rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);\r\n\r\n    build.compactHeightField_ = rcAllocCompactHeightfield();\r\n    if (!build.compactHeightField_)\r\n    {\r\n        LOGERROR(\"Could not allocate create compact heightfield\");\r\n        return false;\r\n    }\r\n    if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,\r\n        *build.compactHeightField_))\r\n    {\r\n        LOGERROR(\"Could not build compact heightfield\");\r\n        return false;\r\n    }\r\n    if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))\r\n    {\r\n        LOGERROR(\"Could not erode compact heightfield\");\r\n        return false;\r\n    }\r\n\r\n    \/\/ Mark area volumes\r\n    for (unsigned i = 0; i < build.navAreas_.Size(); ++i)\r\n        rcMarkBoxArea(build.ctx_, &build.navAreas_[i].bounds_.min_.x_, &build.navAreas_[i].bounds_.max_.x_, build.navAreas_[i].areaID_, *build.compactHeightField_);\r\n\r\n    if (this->partitionType_ == NAVMESH_PARTITION_WATERSHED)\r\n    {\r\n        if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))\r\n        {\r\n            LOGERROR(\"Could not build distance field\");\r\n            return false;\r\n        }\r\n        if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,\r\n            cfg.mergeRegionArea))\r\n        {\r\n            LOGERROR(\"Could not build regions\");\r\n            return false;\r\n        }\r\n    }\r\n    else\r\n    {\r\n        if (!rcBuildRegionsMonotone(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))\r\n        {\r\n            LOGERROR(\"Could not build monotone regions\");\r\n            return false;\r\n        }\r\n    }\r\n\r\n    build.contourSet_ = rcAllocContourSet();\r\n    if (!build.contourSet_)\r\n    {\r\n        LOGERROR(\"Could not allocate contour set\");\r\n        return false;\r\n    }\r\n    if (!rcBuildContours(build.ctx_, *build.compactHeightField_, cfg.maxSimplificationError, cfg.maxEdgeLen,\r\n        *build.contourSet_))\r\n    {\r\n        LOGERROR(\"Could not create contours\");\r\n        return false;\r\n    }\r\n\r\n    build.polyMesh_ = rcAllocPolyMesh();\r\n    if (!build.polyMesh_)\r\n    {\r\n        LOGERROR(\"Could not allocate poly mesh\");\r\n        return false;\r\n    }\r\n    if (!rcBuildPolyMesh(build.ctx_, *build.contourSet_, cfg.maxVertsPerPoly, *build.polyMesh_))\r\n    {\r\n        LOGERROR(\"Could not triangulate contours\");\r\n        return false;\r\n    }\r\n\r\n    build.polyMeshDetail_ = rcAllocPolyMeshDetail();\r\n    if (!build.polyMeshDetail_)\r\n    {\r\n        LOGERROR(\"Could not allocate detail mesh\");\r\n        return false;\r\n    }\r\n    if (!rcBuildPolyMeshDetail(build.ctx_, *build.polyMesh_, *build.compactHeightField_, cfg.detailSampleDist,\r\n        cfg.detailSampleMaxError, *build.polyMeshDetail_))\r\n    {\r\n        LOGERROR(\"Could not build detail mesh\");\r\n        return false;\r\n    }\r\n\r\n    \/\/ Set polygon flags\r\n    \/\/\/ \\todo Assignment of flags from navigation areas?\r\n    for (int i = 0; i < build.polyMesh_->npolys; ++i)\r\n    {\r\n        if (build.polyMesh_->areas[i] != RC_NULL_AREA)\r\n            build.polyMesh_->flags[i] = 0x1;\r\n    }\r\n\r\n    unsigned char* navData = 0;\r\n    int navDataSize = 0;\r\n\r\n    dtNavMeshCreateParams params;\r\n    memset(&params, 0, sizeof params);\r\n    params.verts = build.polyMesh_->verts;\r\n    params.vertCount = build.polyMesh_->nverts;\r\n    params.polys = build.polyMesh_->polys;\r\n    params.polyAreas = build.polyMesh_->areas;\r\n    params.polyFlags = build.polyMesh_->flags;\r\n    params.polyCount = build.polyMesh_->npolys;\r\n    params.nvp = build.polyMesh_->nvp;\r\n    params.detailMeshes = build.polyMeshDetail_->meshes;\r\n    params.detailVerts = build.polyMeshDetail_->verts;\r\n    params.detailVertsCount = build.polyMeshDetail_->nverts;\r\n    params.detailTris = build.polyMeshDetail_->tris;\r\n    params.detailTriCount = build.polyMeshDetail_->ntris;\r\n    params.walkableHeight = agentHeight_;\r\n    params.walkableRadius = agentRadius_;\r\n    params.walkableClimb = agentMaxClimb_;\r\n    params.tileX = x;\r\n    params.tileY = z;\r\n    rcVcopy(params.bmin, build.polyMesh_->bmin);\r\n    rcVcopy(params.bmax, build.polyMesh_->bmax);\r\n    params.cs = cfg.cs;\r\n    params.ch = cfg.ch;\r\n    params.buildBvTree = true;\r\n\r\n    \/\/ Add off-mesh connections if have them\r\n    if (build.offMeshRadii_.Size())\r\n    {\r\n        params.offMeshConCount = build.offMeshRadii_.Size();\r\n        params.offMeshConVerts = &build.offMeshVertices_[0].x_;\r\n        params.offMeshConRad = &build.offMeshRadii_[0];\r\n        params.offMeshConFlags = &build.offMeshFlags_[0];\r\n        params.offMeshConAreas = &build.offMeshAreas_[0];\r\n        params.offMeshConDir = &build.offMeshDir_[0];\r\n    }\r\n\r\n    if (!dtCreateNavMeshData(&params, &navData, &navDataSize))\r\n    {\r\n        LOGERROR(\"Could not build navigation mesh tile data\");\r\n        return false;\r\n    }\r\n\r\n    if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))\r\n    {\r\n        LOGERROR(\"Failed to add navigation mesh tile\");\r\n        dtFree(navData);\r\n        return false;\r\n    }\r\n\r\n    \/\/ Send a notification of the rebuild of this tile to anyone interested\r\n    {\r\n        using namespace NavigationAreaRebuilt;\r\n        VariantMap& eventData = GetContext()->GetEventDataMap();\r\n        eventData[P_NODE] = GetNode();\r\n        eventData[P_MESH] = this;\r\n        eventData[P_BOUNDSMIN] = Variant(tileBoundingBox.min_);\r\n        eventData[P_BOUNDSMAX] = Variant(tileBoundingBox.max_);\r\n        SendEvent(E_NAVIGATION_AREA_REBUILT, eventData);\r\n    }\r\n    return true;\r\n}\r\n\r\nbool NavigationMesh::InitializeQuery()\r\n{\r\n    if (!navMesh_ || !node_)\r\n        return false;\r\n\r\n    if (navMeshQuery_)\r\n        return true;\r\n\r\n    navMeshQuery_ = dtAllocNavMeshQuery();\r\n    if (!navMeshQuery_)\r\n    {\r\n        LOGERROR(\"Could not create navigation mesh query\");\r\n        return false;\r\n    }\r\n\r\n    if (dtStatusFailed(navMeshQuery_->init(navMesh_, MAX_POLYS)))\r\n    {\r\n        LOGERROR(\"Could not init navigation mesh query\");\r\n        return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nvoid NavigationMesh::ReleaseNavigationMesh()\r\n{\r\n    dtFreeNavMesh(navMesh_);\r\n    navMesh_ = 0;\r\n\r\n    dtFreeNavMeshQuery(navMeshQuery_);\r\n    navMeshQuery_ = 0;\r\n\r\n    numTilesX_ = 0;\r\n    numTilesZ_ = 0;\r\n    boundingBox_.min_ = boundingBox_.max_ = Vector3::ZERO;\r\n    boundingBox_.defined_ = false;\r\n}\r\n\r\nvoid NavigationMesh::SetPartitionType(NavmeshPartitionType ptype)\r\n{\r\n    partitionType_ = ptype;\r\n    MarkNetworkUpdate();\r\n}\r\n\r\nvoid RegisterNavigationLibrary(Context* context)\r\n{\r\n    Navigable::RegisterObject(context);\r\n    NavigationMesh::RegisterObject(context);\r\n    OffMeshConnection::RegisterObject(context);\r\n    CrowdAgent::RegisterObject(context);\r\n    DetourCrowdManager::RegisterObject(context);\r\n    DynamicNavigationMesh::RegisterObject(context);\r\n    Obstacle::RegisterObject(context);\r\n    NavArea::RegisterObject(context);\r\n}\r\n\r\n}\r\n","avg_line_length":34.3910209993,"max_line_length":173,"alphanum_fraction":0.6286478292,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":9353,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\n\/\/\/ Bevan Cheeseman 2018\n\/\/\/\n\nconst char* usage = R\"(\nForm the APR form image: Takes an uint16_t input tiff image and forms the APR and saves it as hdf5. The hdf5 output of this program\ncan be used with the other apr examples, and also viewed with HDFView.\n\nUsage:\n\n(minimal with auto-parameters)\n\nExample_get_apr -i input_image_tiff -d input_directory [-o name_of_output]\n\nAdditional settings (High Level):\n\n-I_th intensity_threshold  (will ignore areas of image below this threshold, useful for removing camera artifacts or auto-flouresence)\n-SNR_min minimal_snr (minimal ratio of the signal to the standard deviation of the background, set by default to 6)\n\nAdvanced (Direct) Settings:\n\n-lambda lambda_value (directly set the value of the gradient smoothing parameter lambda (reasonable range 0.1-10, default: 3)\n-min_signal min_signal_val (directly sets a minimum absolute signal size relative to the local background, also useful for removing background, otherwise set using estimated background noise estimate and minimal SNR of 6)\n-mask_file mask_file_tiff (takes an input image uint16_t, assumes all zero regions should be ignored by the APR, useful for pre-processing of isolating desired content, or using another channel as a mask)\n-rel_error rel_error_value (Reasonable ranges are from .08-.15), Default: 0.1\n-normalize_input (flag that will rescale the input from the input data range to 80% of the output data type range, useful for float scaled datasets)\n-compress_level (the IO uses BLOSC for lossless compression of the APR, this can be set from 1-9, where higher increases the compression level. Note, this can come at a significant time increase.)\n-compress_type (Default: 0, loss-less compression of partilce intensities, (1,2) WNL (Bal\u00e1zs et al. 2017) - approach compression applied to particles (1 = without prediction, 2 = with)\n\n-neighborhood_optimization_off turns off the neighborhood opetimization (This results in boundary Particle Cells also being increased in resolution after the Pulling Scheme step)\n-output_steps Writes tiff images of the individual steps (gradient magnitude, local intensity scale, and final level of the APR calculation).\n\n)\";\n\n#include <algorithm>\n#include <iostream>\n#include \"ConfigAPR.h\"\n#include \"Example_get_apr.h\"\n\nint main(int argc, char **argv) {\n\n    \/\/input parsing\n    cmdLineOptions options;\n\n    options = read_command_line_options(argc,argv);\n\n    \/\/the apr datastructure\n    APR<uint16_t> apr;\n\n    \/\/read in the command line options into the parameters file\n    apr.parameters.Ip_th = options.Ip_th;\n    apr.parameters.rel_error = options.rel_error;\n    apr.parameters.lambda = options.lambda;\n    apr.parameters.mask_file = options.mask_file;\n    apr.parameters.min_signal = options.min_signal;\n    apr.parameters.SNR_min = options.SNR_min;\n    apr.parameters.normalized_input = options.normalize_input;\n    apr.parameters.neighborhood_optimization = options.neighborhood_optimization;\n    apr.parameters.output_steps = options.output_steps;\n\n    \/\/where things are\n    apr.parameters.input_image_name = options.input;\n    apr.parameters.input_dir = options.directory;\n    apr.parameters.name = options.output;\n    apr.parameters.output_dir = options.output_dir;\n\n    apr.apr_converter.fine_grained_timer.verbose_flag = false;\n    apr.apr_converter.method_timer.verbose_flag = false;\n    apr.apr_converter.computation_timer.verbose_flag = false;\n    apr.apr_converter.allocation_timer.verbose_flag = false;\n    apr.apr_converter.total_timer.verbose_flag = true;\n\n    \/\/Gets the APR\n    if(apr.get_apr()){\n\n        \/\/Below is IO and outputting of the Implied Resolution Function through the Particle Cell level.\n\n        \/\/output\n        std::string save_loc = options.output_dir;\n        std::string file_name = options.output;\n\n        APRTimer timer;\n\n        timer.verbose_flag = true;\n\n        std::cout << std::endl;\n        float original_pixel_image_size = (2.0f*apr.orginal_dimensions(0)*apr.orginal_dimensions(1)*apr.orginal_dimensions(2))\/(1000000.0);\n        std::cout << \"Original image size: \" << original_pixel_image_size << \" MB\" << std::endl;\n\n        timer.start_timer(\"writing output\");\n\n        std::cout << \"Writing the APR to hdf5...\" << std::endl;\n\n        \/\/feel free to change\n        unsigned int blosc_comp_type = BLOSC_ZSTD;\n        unsigned int blosc_comp_level = options.compress_level;\n        unsigned int blosc_shuffle = 1;\n\n        apr.apr_compress.set_compression_type(options.compress_type);\n\n        \/\/write the APR to hdf5 file\n        FileSizeInfo fileSizeInfo = apr.write_apr(save_loc,file_name,blosc_comp_type,blosc_comp_level,blosc_shuffle);\n        float apr_file_size = fileSizeInfo.total_file_size;\n\n        timer.stop_timer();\n\n        float computational_ratio = (1.0f*apr.orginal_dimensions(0)*apr.orginal_dimensions(1)*apr.orginal_dimensions(2))\/(1.0f*apr.total_number_particles());\n\n        std::cout << std::endl;\n        std::cout << \"Computational Ratio (Pixels\/Particles): \" << computational_ratio << std::endl;\n        std::cout << \"Lossy Compression Ratio: \" << original_pixel_image_size\/apr_file_size << std::endl;\n        std::cout << std::endl;\n\n        if(options.output_steps) {\n\n            PixelData<uint16_t> level;\n\n            apr.interp_depth_ds(level);\n\n            std::cout << std::endl;\n\n            std::cout << \"Saving down-sampled Particle Cell level as tiff image\" << std::endl;\n\n            std::string output_path = save_loc + file_name + \"_level.tif\";\n            \/\/write output as tiff\n            TiffUtils::saveMeshAsTiff(output_path, level);\n        }\n\n        } else {\n        std::cout << \"Oops, something went wrong. APR not computed :(.\" << std::endl;\n    }\n\n}\n\n\nbool command_option_exists(char **begin, char **end, const std::string &option)\n{\n    return std::find(begin, end, option) != end;\n}\n\nchar* get_command_option(char **begin, char **end, const std::string &option)\n{\n    char ** itr = std::find(begin, end, option);\n    if (itr != end && ++itr != end)\n    {\n        return *itr;\n    }\n    return 0;\n}\n\ncmdLineOptions read_command_line_options(int argc, char **argv){\n\n    cmdLineOptions result;\n\n    if(argc == 1) {\n        std::cerr << argv[0] << std::endl;\n        std::cerr << \"APR version \" << ConfigAPR::APR_VERSION << std::endl;\n        std::cerr << \"Short usage: \\\"\" << argv[0] << \" -i inputfile [-d directory] [-o outputfile]\\\"\" << std::endl;\n\n        std::cerr << usage << std::endl;\n        exit(1);\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-i\"))\n    {\n        result.input = std::string(get_command_option(argv, argv + argc, \"-i\"));\n    } else {\n        std::cout << \"Input file required\" << std::endl;\n        exit(2);\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-o\"))\n    {\n        result.output = std::string(get_command_option(argv, argv + argc, \"-o\"));\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-d\"))\n    {\n        result.directory = std::string(get_command_option(argv, argv + argc, \"-d\"));\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-od\"))\n    {\n        result.output_dir = std::string(get_command_option(argv, argv + argc, \"-od\"));\n    } else {\n        result.output_dir = result.directory;\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-gt\"))\n    {\n        result.gt_input = std::string(get_command_option(argv, argv + argc, \"-gt\"));\n    } else {\n        result.gt_input = \"\";\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-lambda\"))\n    {\n        result.lambda = std::stof(std::string(get_command_option(argv, argv + argc, \"-lambda\")));\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-I_th\"))\n    {\n        result.Ip_th = std::stof(std::string(get_command_option(argv, argv + argc, \"-I_th\")));\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-SNR_min\"))\n    {\n        result.SNR_min = std::stof(std::string(get_command_option(argv, argv + argc, \"-SNR_min\")));\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-min_signal\"))\n    {\n        result.min_signal = std::stof(std::string(get_command_option(argv, argv + argc, \"-min_signal\")));\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-rel_error\"))\n    {\n        result.rel_error = std::stof(std::string(get_command_option(argv, argv + argc, \"-rel_error\")));\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-mask_file\"))\n    {\n        result.mask_file = std::string(get_command_option(argv, argv + argc, \"-mask_file\"));\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-compress_level\"))\n    {\n        result.compress_level = (unsigned int)std::stoi(std::string(get_command_option(argv, argv + argc, \"-compress_level\")));\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-compress_type\"))\n    {\n        result.compress_type = (unsigned int)std::stoi(std::string(get_command_option(argv, argv + argc, \"-compress_type\")));\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-normalize_input\"))\n    {\n        result.normalize_input = true;\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-neighborhood_optimization_off\"))\n    {\n        result.neighborhood_optimization = false;\n\n    }\n\n    if(command_option_exists(argv, argv + argc, \"-output_steps\"))\n    {\n        result.output_steps = true;\n    }\n\n    return result;\n}","avg_line_length":36.8228346457,"max_line_length":221,"alphanum_fraction":0.6752913504,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4454,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <algorithm>\n\n\/\/ template<InputIterator Iter1, InputIterator Iter2>\n\/\/   requires HasLess<Iter1::value_type, Iter2::value_type>\n\/\/         && HasLess<Iter2::value_type, Iter1::value_type>\n\/\/   constexpr bool             \/\/ constexpr after C++17\n\/\/   includes(Iter1 first1, Iter1 last1, Iter2 first2, Iter2 last2);\n\n#include \"algorithm.h\"\n#include <catch2\/catch.hpp>\n#include <cassert>\n\n#include \"test_macros.h\"\n#include \"test_iterators.h\"\n\nnamespace test_includes\n{\n    template <class Iter1, class Iter2>\n    TEST_CONSTEXPR_CXX20 void test()\n    {\n        int ia[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};\n        const unsigned sa = sizeof(ia) \/ sizeof(ia[0]);\n        int ib[] = {2, 4};\n        const unsigned sb = sizeof(ib) \/ sizeof(ib[0]);\n        int ic[] = {1, 2};\n        const unsigned sc = sizeof(ic) \/ sizeof(ic[0]);\n        ((void)sc);\n        int id[] = {3, 3, 3, 3};\n        const unsigned sd = sizeof(id) \/ sizeof(id[0]);\n        ((void)sd);\n\n        assert(ddstl::includes(Iter1(ia), Iter1(ia), Iter2(ib), Iter2(ib)));\n        assert(!ddstl::includes(Iter1(ia), Iter1(ia), Iter2(ib), Iter2(ib + 1)));\n        assert(ddstl::includes(Iter1(ia), Iter1(ia + 1), Iter2(ib), Iter2(ib)));\n        assert(ddstl::includes(Iter1(ia), Iter1(ia + sa), Iter2(ia), Iter2(ia + sa)));\n\n        assert(ddstl::includes(Iter1(ia), Iter1(ia + sa), Iter2(ib), Iter2(ib + sb)));\n        assert(!ddstl::includes(Iter1(ib), Iter1(ib + sb), Iter2(ia), Iter2(ia + sa)));\n\n        assert(ddstl::includes(Iter1(ia), Iter1(ia + 2), Iter2(ic), Iter2(ic + 2)));\n        assert(!ddstl::includes(Iter1(ia), Iter1(ia + 2), Iter2(ib), Iter2(ib + 2)));\n\n        assert(ddstl::includes(Iter1(ia), Iter1(ia + sa), Iter2(id), Iter2(id + 1)));\n        assert(ddstl::includes(Iter1(ia), Iter1(ia + sa), Iter2(id), Iter2(id + 2)));\n        assert(ddstl::includes(Iter1(ia), Iter1(ia + sa), Iter2(id), Iter2(id + 3)));\n        assert(!ddstl::includes(Iter1(ia), Iter1(ia + sa), Iter2(id), Iter2(id + 4)));\n    }\n\n    TEST_CONSTEXPR_CXX20\n    bool do_tests()\n    {\n        test<input_iterator<const int *>, input_iterator<const int *>>();\n        test<input_iterator<const int *>, forward_iterator<const int *>>();\n        test<input_iterator<const int *>, bidirectional_iterator<const int *>>();\n        test<input_iterator<const int *>, random_access_iterator<const int *>>();\n        test<input_iterator<const int *>, const int *>();\n\n        test<forward_iterator<const int *>, input_iterator<const int *>>();\n        test<forward_iterator<const int *>, forward_iterator<const int *>>();\n        test<forward_iterator<const int *>, bidirectional_iterator<const int *>>();\n        test<forward_iterator<const int *>, random_access_iterator<const int *>>();\n        test<forward_iterator<const int *>, const int *>();\n\n        test<bidirectional_iterator<const int *>, input_iterator<const int *>>();\n        test<bidirectional_iterator<const int *>, forward_iterator<const int *>>();\n        test<bidirectional_iterator<const int *>, bidirectional_iterator<const int *>>();\n        test<bidirectional_iterator<const int *>, random_access_iterator<const int *>>();\n        test<bidirectional_iterator<const int *>, const int *>();\n\n        test<random_access_iterator<const int *>, input_iterator<const int *>>();\n        test<random_access_iterator<const int *>, forward_iterator<const int *>>();\n        test<random_access_iterator<const int *>, bidirectional_iterator<const int *>>();\n        test<random_access_iterator<const int *>, random_access_iterator<const int *>>();\n        test<random_access_iterator<const int *>, const int *>();\n\n        test<const int *, input_iterator<const int *>>();\n        test<const int *, forward_iterator<const int *>>();\n        test<const int *, bidirectional_iterator<const int *>>();\n        test<const int *, random_access_iterator<const int *>>();\n        test<const int *, const int *>();\n\n        return true;\n    }\n}\n\nTEST_CASE(\"test includes pass\")\n{\n    using namespace test_includes;\n    do_tests();\n#if TEST_STD_VER > 17\n    static_assert(do_tests());\n#endif\n}","avg_line_length":44.099009901,"max_line_length":89,"alphanum_fraction":0.605298608,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":228,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"scene\/Bone.h\"\n\nBone::Bone ()\n{\n\n}\n\nBone::~Bone ()\n{\n\n}\n\nBone& Bone::SetOffsetMatrix (const Matrix4f& m)\n{\n    offsetMatrix = m;\n\n    return *this;\n}\n\nMatrix4f Bone::GetOffsetMatrix () const\n{\n    return offsetMatrix;\n}","avg_line_length":9.9130434783,"max_line_length":47,"alphanum_fraction":0.6271929825,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":14480,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":10.0,"content":"\/*BEGIN_LEGAL \r\nIntel Open Source License \r\n\r\nCopyright (c) 2002-2013 Intel Corporation. All rights reserved.\r\n \r\nRedistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions are\r\nmet:\r\n\r\nRedistributions of source code must retain the above copyright notice,\r\nthis list of conditions and the following disclaimer.  Redistributions\r\nin binary form must reproduce the above copyright notice, this list of\r\nconditions and the following disclaimer in the documentation and\/or\r\nother materials provided with the distribution.  Neither the name of\r\nthe Intel Corporation nor the names of its contributors may be used to\r\nendorse or promote products derived from this software without\r\nspecific prior written permission.\r\n \r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR\r\nITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\nEND_LEGAL *\/\r\n\/\/\r\n\/\/ @ORIGINAL_AUTHOR: Greg Lueck\r\n\/\/\r\n\r\n\/*! @file\r\n *\r\n * This file contains a tool that traces all uses and changes to the FS and GS\r\n * segments, which are typically used to implement thread-local storage on x86\r\n * platforms.  Currently, this tool only knows about the segment-related system\r\n * calls on Linux.\r\n *\/\r\n\r\n#include \"pin.H\"\r\n#include \"pending_syscalls.H\"\r\n#include \"disasm_container.H\"\r\n\r\n#include <iostream>\r\n#include <ostream>\r\n#include <fstream>\r\n#include <iomanip>\r\n#include <sstream>\r\n#include <map>\r\n\r\n#if defined(TARGET_LINUX)\r\n#   include <sys\/syscall.h>\r\n#   include <asm\/ldt.h>\r\n#endif\r\n\r\n#if defined(TARGET_LINUX) && defined(TARGET_IA32E)\r\n#   include <asm\/prctl.h>\r\n#endif\r\n\r\n\r\n\/\/ These constants are not defined on old kernels.\r\n\/\/\r\n#ifndef __NR_set_thread_area\r\n#   define __NR_set_thread_area 243\r\n#endif\r\n#ifndef __NR_get_thread_area\r\n#   define __NR_get_thread_area 244\r\n#endif\r\n#ifndef SYS_set_thread_area\r\n#   define SYS_set_thread_area __NR_set_thread_area\r\n#endif\r\n#ifndef SYS_get_thread_area\r\n#   define SYS_get_thread_area __NR_get_thread_area\r\n#endif\r\n#ifndef CLONE_SETTLS\r\n#   define CLONE_SETTLS 0x00080000\r\n#endif\r\n\r\n\/\/ Specifies a segment descriptor entry.  Used with modify_ldt(), etc.\r\n\/\/\r\nstruct USER_DESC\r\n{\r\n    UINT32 entry_number;\r\n    ADDRINT base_addr;\r\n    UINT32 limit;\r\n    UINT32 seg_32bit:1;\r\n    UINT32 contents:2;\r\n    UINT32 read_exec_only:1;\r\n    UINT32 limit_in_pages:1;\r\n    UINT32 seg_not_present:1;\r\n    UINT32 useable:1;\r\n};\r\n\r\nKNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, \"pintool\", \"o\", \"segtrace.out\", \"trace file\");\r\n\r\nstd::ofstream Out;\r\nPENDING_SYSCALLS *PendingSyscalls;  \/\/ Holds syscall information between \"before\" and \"after\" instrumentation\r\nDISASM_CONTAINER *Disassemblies;    \/\/ Holds disassemblies for \"interesting\" instructions\r\n\r\n\r\nstatic VOID Instruction(INS, VOID *);\r\nstatic BOOL WritesSegment(INS, REG *);\r\nstatic VOID OnSegReference(UINT32, ADDRINT, ADDRINT, THREADID);\r\nstatic VOID OnSegWrite(UINT32, ADDRINT, ADDRINT, THREADID);\r\nstatic VOID OnSyscallBefore(ADDRINT, ADDRINT, ADDRINT, ADDRINT, ADDRINT, ADDRINT, ADDRINT, ADDRINT, ADDRINT, THREADID);\r\nstatic VOID OnSyscallAfter(ADDRINT, ADDRINT, ADDRINT, ADDRINT, THREADID);\r\nstatic std::string Header(THREADID, ADDRINT);\r\nstatic std::string PasteDisassembly(const std::string &, const std::string &);\r\nstatic std::string SegName(REG);\r\nstatic std::string SegSelector(ADDRINT);\r\nstatic VOID SyscallEntry(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, VOID *v);\r\nstatic VOID SyscallExit(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, VOID *v);\r\n\r\n#if defined(TARGET_LINUX)\r\n    static std::string UserDesc(USER_DESC *);\r\n#endif\r\n\r\n#if defined(TARGET_LINUX) && defined(TARGET_IA32E)\r\n    static std::string PrctlFunc(ADDRINT);\r\n#endif\r\n\r\n\r\nint main(int argc, char * argv[])\r\n{\r\n    PIN_Init(argc, argv);\r\n\r\n    Out.open(KnobOutputFile.Value().c_str());\r\n    PendingSyscalls = new PENDING_SYSCALLS();\r\n    Disassemblies = new DISASM_CONTAINER();\r\n\r\n    INS_AddInstrumentFunction(Instruction, 0);\r\n    PIN_AddSyscallEntryFunction(SyscallEntry, 0);\r\n    PIN_AddSyscallExitFunction(SyscallExit, 0);\r\n\r\n    PIN_StartProgram();\r\n    return 0;\r\n}\r\n\r\n\r\nstatic VOID Instruction(INS ins, VOID *v)\r\n{\r\n    if (INS_SegmentPrefix(ins))\r\n    {\r\n        INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(OnSegReference), IARG_UINT32, INS_SegmentRegPrefix(ins),\r\n            IARG_REG_VALUE, INS_SegmentRegPrefix(ins), IARG_INST_PTR, IARG_THREAD_ID, IARG_END);\r\n        Disassemblies->Add(INS_Address(ins), INS_Disassemble(ins));\r\n    }\r\n\r\n    REG seg;\r\n    if (WritesSegment(ins, &seg))\r\n    {\r\n        INS_InsertCall(ins, IPOINT_AFTER, AFUNPTR(OnSegWrite), IARG_UINT32, seg, IARG_REG_VALUE, seg,\r\n            IARG_INST_PTR, IARG_THREAD_ID, IARG_END);\r\n        Disassemblies->Add(INS_Address(ins), INS_Disassemble(ins));\r\n    }\r\n\r\n    \/\/ For O\/S's (Mac) that don't support PIN_AddSyscallEntryFunction(),\r\n    \/\/ instrument the system call instruction.\r\n    \/\/\r\n    if (INS_IsSyscall(ins) && INS_HasFallThrough(ins))\r\n    {\r\n        INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(OnSyscallBefore), IARG_SYSCALL_NUMBER, IARG_SYSARG_VALUE, 0,\r\n            IARG_SYSARG_VALUE, 1, IARG_SYSARG_VALUE, 2, IARG_SYSARG_VALUE, 3, IARG_SYSARG_VALUE, 4,\r\n            IARG_REG_VALUE, REG_SEG_FS, IARG_REG_VALUE, REG_SEG_GS, IARG_INST_PTR, IARG_THREAD_ID, IARG_END);\r\n\r\n        INS_InsertCall(ins, IPOINT_AFTER, AFUNPTR(OnSyscallAfter), IARG_SYSRET_VALUE,\r\n            IARG_REG_VALUE, REG_SEG_FS, IARG_REG_VALUE, REG_SEG_GS, IARG_INST_PTR, IARG_THREAD_ID, IARG_END);\r\n    }\r\n}\r\n\r\nstatic BOOL WritesSegment(INS ins, REG *seg)\r\n{\r\n    if (INS_RegWContain(ins, REG_SEG_FS))\r\n    {\r\n        *seg = REG_SEG_FS;\r\n        return TRUE;\r\n    }\r\n    if (INS_RegWContain(ins, REG_SEG_GS))\r\n    {\r\n        *seg = REG_SEG_GS;\r\n        return TRUE;\r\n    }\r\n    if (INS_RegWContain(ins, REG_SEG_ES))\r\n    {\r\n        *seg = REG_SEG_ES;\r\n        return TRUE;\r\n    }\r\n    if (INS_RegWContain(ins, REG_SEG_CS))\r\n    {\r\n        *seg = REG_SEG_CS;\r\n        return TRUE;\r\n    }\r\n    if (INS_RegWContain(ins, REG_SEG_DS))\r\n    {\r\n        *seg = REG_SEG_DS;\r\n        return TRUE;\r\n    }\r\n    if (INS_RegWContain(ins, REG_SEG_SS))\r\n    {\r\n        *seg = REG_SEG_SS;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nstatic VOID OnSegReference(UINT32 ireg, ADDRINT val, ADDRINT pc, THREADID tid)\r\n{\r\n    REG reg = static_cast<REG>(ireg);\r\n    std::ostringstream s;\r\n    s << Header(tid, pc) << \"reference via \" << SegName(reg) << \" \" << SegSelector(val);\r\n    Out << PasteDisassembly(s.str(), Disassemblies->Get(pc)) << std::endl;\r\n}\r\n\r\nstatic VOID OnSegWrite(UINT32 ireg, ADDRINT val, ADDRINT pc, THREADID tid)\r\n{\r\n    REG reg = static_cast<REG>(ireg);\r\n    std::ostringstream s;\r\n    s << Header(tid, pc) << \"modify \" << SegName(reg) << \"=\" << SegSelector(val);\r\n    Out << PasteDisassembly(s.str(), Disassemblies->Get(pc)) << std::endl;\r\n}\r\n\r\nstatic VOID OnSyscallBefore(ADDRINT num, ADDRINT arg1, ADDRINT arg2, ADDRINT arg3, ADDRINT arg4, ADDRINT arg5,\r\n    ADDRINT fs, ADDRINT gs, ADDRINT pc, THREADID tid)\r\n{\r\n    PendingSyscalls->Add(tid, PENDING_SYSCALL(fs, gs, num, arg1, arg2, arg3, arg4, arg5));\r\n\r\n    switch (num)\r\n    {\r\n#if defined(TARGET_LINUX)\r\n      case SYS_modify_ldt:\r\n      {\r\n        int func = static_cast<int>(arg1);\r\n        if (func == 1)\r\n        {\r\n            USER_DESC *tls = reinterpret_cast<USER_DESC *>(arg2);\r\n            Out << Header(tid, pc) << \"modify_ldt(WRITE, \" << UserDesc(tls) << \", 0x\" <<\r\n                std::hex << arg3 << \")\" << std::endl;\r\n        }\r\n        else\r\n        {\r\n            Out << Header(tid, pc) << \"modify_ldt(READ, 0x\" << std::hex << arg2 <<\r\n                \", 0x\" << arg3 << \")\" << std::endl;\r\n        }\r\n        break;\r\n      }\r\n#endif\r\n\r\n#if defined(TARGET_LINUX) && defined(TARGET_IA32E)\r\n      case SYS_arch_prctl:\r\n        Out << Header(tid, pc) << \"arch_prctl(\" << PrctlFunc(arg1) << \", 0x\" << std::hex << arg2 << \")\" << std::endl;\r\n        break;\r\n\r\n      case SYS_clone:\r\n      {\r\n        int flags = static_cast<int>(arg1);\r\n        if (flags & CLONE_SETTLS)\r\n            Out << Header(tid, pc) << \"clone(CLONE_SETTLS, 0x\" << std::hex << arg5 << \")\" << std::endl;\r\n        break;\r\n      }\r\n\r\n      case SYS_set_thread_area:\r\n        Out << Header(tid, pc) << \"UNEXPECTED: set_thread_area\" << std::endl;\r\n        break;\r\n\r\n      case SYS_get_thread_area:\r\n        Out << Header(tid, pc) << \"UNEXPECTED: get_thread_area\" << std::endl;\r\n        break;\r\n#endif\r\n\r\n#if defined(TARGET_LINUX) && defined(TARGET_IA32)\r\n      case SYS_set_thread_area:\r\n      {\r\n        USER_DESC *tls = reinterpret_cast<USER_DESC *>(arg1);\r\n        Out << Header(tid, pc) << \"set_thread_area(\" << UserDesc(tls) << \")\" << std::endl;\r\n        break;\r\n      }\r\n\r\n      case SYS_get_thread_area:\r\n      {\r\n        USER_DESC *tls = reinterpret_cast<USER_DESC *>(arg1);\r\n        Out << Header(tid, pc) << \"get_thread_area([entry_number=0x\" << std::hex << tls->entry_number << \"])\" << std::endl;\r\n        break;\r\n      }\r\n\r\n      case SYS_clone:\r\n      {\r\n        int flags = static_cast<int>(arg1);\r\n        if (flags & CLONE_SETTLS)\r\n        {\r\n            USER_DESC *tls = reinterpret_cast<USER_DESC *>(arg4);\r\n            Out << Header(tid, pc) << \"clone(CLONE_SETTLS, \" << UserDesc(tls) << \")\" << std::endl;\r\n        }\r\n        break;\r\n      }\r\n#endif\r\n    }\r\n}\r\n\r\nstatic VOID OnSyscallAfter(ADDRINT ret, ADDRINT fs, ADDRINT gs, ADDRINT pc, THREADID tid)\r\n{\r\n    PENDING_SYSCALL pend;\r\n    if (!PendingSyscalls->Remove(tid, &pend))\r\n        return;\r\n\r\n    switch (pend._number)\r\n    {\r\n#if defined(TARGET_LINUX)\r\n      case SYS_modify_ldt:\r\n        if (ret == ADDRINT(-1))\r\n            Out << Header(tid, pc) << \"=>modify_ldt(FAILED)\" << std::endl;\r\n        break;\r\n#endif\r\n\r\n#if defined(TARGET_LINUX) && defined(TARGET_IA32E)\r\n      case SYS_arch_prctl:\r\n        if (ret == ADDRINT(-1))\r\n            Out << Header(tid, pc) << \"=>arch_prctl(FAILED)\" << std::endl;\r\n        break;\r\n#endif\r\n\r\n#if defined(TARGET_LINUX) && defined(TARGET_IA32)\r\n      case SYS_set_thread_area:\r\n        if (ret == ADDRINT(-1))\r\n        {\r\n            Out << Header(tid, pc) << \"=>set_thread_area(FAILED)\" << std::endl;\r\n        }\r\n        else\r\n        {\r\n            USER_DESC *tls = reinterpret_cast<USER_DESC *>(pend._arg1);\r\n            Out << Header(tid, pc) << \"=>set_thread_area(\" << UserDesc(tls) << \")\" << std::endl;\r\n        }\r\n        break;\r\n\r\n      case SYS_get_thread_area:\r\n        if (ret == ADDRINT(-1))\r\n        {\r\n            Out << Header(tid, pc) << \"=>get_thread_area(FAILED)\" << std::endl;\r\n        }\r\n        else\r\n        {\r\n            USER_DESC *tls = reinterpret_cast<USER_DESC *>(pend._arg1);\r\n            Out << Header(tid, pc) << \"=>get_thread_area(\" << UserDesc(tls) << \")\" << std::endl;\r\n        }\r\n        break;\r\n#endif\r\n    }\r\n\r\n    if (fs != pend._fs)\r\n        Out << Header(tid, pc) << \"syscall modified FS=\" << SegSelector(fs) << std::endl;\r\n    if (gs != pend._gs)\r\n        Out << Header(tid, pc) << \"syscall modified GS=\" << SegSelector(gs) << std::endl;\r\n}\r\n\r\nstatic VOID SyscallEntry(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, VOID *v)\r\n{\r\n    OnSyscallBefore(PIN_GetSyscallNumber(ctxt, std),\r\n        PIN_GetSyscallArgument(ctxt, std, 0),\r\n        PIN_GetSyscallArgument(ctxt, std, 1),\r\n        PIN_GetSyscallArgument(ctxt, std, 2),\r\n        PIN_GetSyscallArgument(ctxt, std, 3),\r\n        PIN_GetSyscallArgument(ctxt, std, 4),\r\n        PIN_GetContextReg(ctxt, REG_SEG_FS),\r\n        PIN_GetContextReg(ctxt, REG_SEG_GS),\r\n        PIN_GetContextReg(ctxt, REG_INST_PTR),\r\n        threadIndex);\r\n}\r\n\r\nstatic VOID SyscallExit(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, VOID *v)\r\n{\r\n    OnSyscallAfter( PIN_GetSyscallReturn(ctxt, std), \r\n                    PIN_GetContextReg(ctxt, REG_SEG_FS),\r\n                    PIN_GetContextReg(ctxt, REG_SEG_GS),\r\n                    PIN_GetContextReg(ctxt, REG_INST_PTR),\r\n                    threadIndex);\r\n}\r\n\r\nstatic std::string Header(THREADID tid, ADDRINT pc)\r\n{\r\n    std::ostringstream s;\r\n    s << \"tid \" << std::dec << tid << \", pc 0x\" << std::hex << pc << \": \";\r\n    return s.str();\r\n}\r\n\r\nstatic std::string PasteDisassembly(const std::string &body, const std::string &dis)\r\n{\r\n    std::ostringstream s;\r\n    s << std::left << std::setw(70) << body << dis;\r\n    return s.str();\r\n}\r\n\r\nstatic std::string SegName(REG reg)\r\n{\r\n    switch (reg)\r\n    {\r\n      case REG_SEG_FS:\r\n        return \"FS\";\r\n      case REG_SEG_GS:\r\n        return \"GS\";\r\n      case REG_SEG_ES:\r\n        return \"ES\";\r\n      case REG_SEG_CS:\r\n        return \"CS\";\r\n      case REG_SEG_DS:\r\n        return \"DS\";\r\n      case REG_SEG_SS:\r\n        return \"SS\";\r\n      default:\r\n        return \"OTHER\";\r\n    }\r\n}\r\n\r\nstatic std::string SegSelector(ADDRINT val)\r\n{\r\n    std::ostringstream s;\r\n    s << \"[\";\r\n    if (val & 4)\r\n        s << \"LDT\";\r\n    else\r\n        s << \"GDT\";\r\n    s << \" index=\" << std::dec << (val >> 3);\r\n    s << \" priv=\" << std::dec << (val & 3);\r\n    s << \"]\";\r\n    return s.str();\r\n}\r\n\r\n#if defined(TARGET_LINUX)\r\nstatic std::string UserDesc(USER_DESC *tls)\r\n{\r\n    std::ostringstream s;\r\n    s << \"[\";\r\n    s << \"index=\" << std::dec << static_cast<INT32>(tls->entry_number);\r\n    s << \" base=0x\" << std::hex << tls->base_addr;\r\n    s << \"]\";\r\n    return s.str();\r\n}\r\n#endif\r\n\r\n#if defined(TARGET_LINUX) && defined(TARGET_IA32E)\r\nstatic std::string PrctlFunc(ADDRINT fun)\r\n{\r\n    switch (fun)\r\n    {\r\n      case ARCH_SET_GS:\r\n        return \"ARCH_SET_GS\";\r\n      case ARCH_SET_FS:\r\n        return \"ARCH_SET_FS\";\r\n      case ARCH_GET_FS:\r\n        return \"ARCH_GET_FS\";\r\n      case ARCH_GET_GS:\r\n        return \"ARCH_GET_GS\";\r\n      default:\r\n      {\r\n        std::ostringstream s;\r\n        s << \"0x\" << std::hex << fun;\r\n        return s.str();\r\n      }\r\n    }\r\n}\r\n#endif\r\n","avg_line_length":31.2742980562,"max_line_length":124,"alphanum_fraction":0.6218922652,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8109,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":2.0,"content":"#include \"ssdb.h\"\n#include \"slave.h\"\n#include \"leveldb\/env.h\"\n#include \"leveldb\/iterator.h\"\n#include \"leveldb\/cache.h\"\n#include \"leveldb\/filter_policy.h\"\n\n#include \"t_kv.h\"\n#include \"t_hash.h\"\n#include \"t_zset.h\"\n\nSSDB::SSDB(){\n\tdb = NULL;\n\tmeta_db = NULL;\n\tbinlogs = NULL;\n}\n\nSSDB::~SSDB(){\n\tfor(std::vector<Slave *>::iterator it = slaves.begin(); it != slaves.end(); it++){\n\t\tSlave *slave = *it;\n\t\tslave->stop();\n\t\tdelete slave;\n\t}\n\tif(binlogs){\n\t\tdelete binlogs;\n\t}\n\tif(db){\n\t\tdelete db;\n\t}\n\tif(options.block_cache){\n\t\tdelete options.block_cache;\n\t}\n\tif(options.filter_policy){\n\t\tdelete options.filter_policy;\n\t}\n\tif(meta_db){\n\t\tdelete meta_db;\n\t}\n\tlog_debug(\"SSDB finalized\");\n}\n\nSSDB* SSDB::open(const Config &conf, const std::string &base_dir){\n\tstd::string main_db_path = base_dir + \"\/data\";\n\tstd::string meta_db_path = base_dir + \"\/meta\";\n\tint cache_size = conf.get_num(\"leveldb.cache_size\");\n\tint write_buffer_size = conf.get_num(\"leveldb.write_buffer_size\");\n\tint block_size = conf.get_num(\"leveldb.block_size\");\n\tint compaction_speed = conf.get_num(\"leveldb.compaction_speed\");\n\tstd::string compression = conf.get_str(\"leveldb.compression\");\n\n\tstrtolower(&compression);\n\tif(compression != \"yes\"){\n\t\tcompression = \"no\";\n\t}\n\n\tif(cache_size <= 0){\n\t\tcache_size = 8;\n\t}\n\tif(write_buffer_size <= 0){\n\t\twrite_buffer_size = 4;\n\t}\n\tif(block_size <= 0){\n\t\tblock_size = 4;\n\t}\n\n\tlog_info(\"main_db          : %s\", main_db_path.c_str());\n\tlog_info(\"meta_db          : %s\", meta_db_path.c_str());\n\tlog_info(\"cache_size       : %d MB\", cache_size);\n\tlog_info(\"block_size       : %d KB\", block_size);\n\tlog_info(\"write_buffer     : %d MB\", write_buffer_size);\n\tlog_info(\"compaction_speed : %d MB\/s\", compaction_speed);\n\tlog_info(\"compression      : %s\", compression.c_str());\n\n\tSSDB *ssdb = new SSDB();\n\t\/\/\n\tssdb->options.create_if_missing = true;\n\tssdb->options.filter_policy = leveldb::NewBloomFilterPolicy(10);\n\tssdb->options.block_cache = leveldb::NewLRUCache(cache_size * 1048576);\n\tssdb->options.block_size = block_size * 1024;\n\tssdb->options.write_buffer_size = write_buffer_size * 1024 * 1024;\n\tssdb->options.compaction_speed = compaction_speed;\n\tif(compression == \"yes\"){\n\t\tssdb->options.compression = leveldb::kSnappyCompression;\n\t}else{\n\t\tssdb->options.compression = leveldb::kNoCompression;\n\t}\n\n\tleveldb::Status status;\n\t{\n\t\tleveldb::Options options;\n\t\toptions.create_if_missing = true;\n\t\tstatus = leveldb::DB::Open(options, meta_db_path, &ssdb->meta_db);\n\t\tif(!status.ok()){\n\t\t\tgoto err;\n\t\t}\n\t}\n\n\tstatus = leveldb::DB::Open(ssdb->options, main_db_path, &ssdb->db);\n\tif(!status.ok()){\n\t\tlog_error(\"open main_db failed\");\n\t\tgoto err;\n\t}\n\tssdb->binlogs = new BinlogQueue(ssdb->db);\n\n\t{ \/\/ slaves\n\t\tconst Config *repl_conf = conf.get(\"replication\");\n\t\tif(repl_conf != NULL){\n\t\t\tstd::vector<Config *> children = repl_conf->children;\n\t\t\tfor(std::vector<Config *>::iterator it = children.begin(); it != children.end(); it++){\n\t\t\t\tConfig *c = *it;\n\t\t\t\tif(c->key != \"slaveof\"){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstd::string ip = c->get_str(\"ip\");\n\t\t\t\tint port = c->get_num(\"port\");\n\t\t\t\tif(ip == \"\" || port <= 0 || port > 65535){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbool is_mirror = false;\n\t\t\t\tstd::string type = c->get_str(\"type\");\n\t\t\t\tif(type == \"mirror\"){\n\t\t\t\t\tis_mirror = true;\n\t\t\t\t}else{\n\t\t\t\t\ttype = \"sync\";\n\t\t\t\t\tis_mirror = false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstd::string id = c->get_str(\"id\");\n\t\t\t\t\n\t\t\t\tlog_info(\"slaveof: %s:%d, type: %s\", ip.c_str(), port, type.c_str());\n\t\t\t\tSlave *slave = new Slave(ssdb, ssdb->meta_db, ip.c_str(), port, is_mirror);\n\t\t\t\tif(!id.empty()){\n\t\t\t\t\tslave->set_id(id);\n\t\t\t\t}\n\t\t\t\tslave->start();\n\t\t\t\tssdb->slaves.push_back(slave);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ssdb;\nerr:\n\tif(ssdb){\n\t\tdelete ssdb;\n\t}\n\treturn NULL;\n}\n\nIterator* SSDB::iterator(const std::string &start, const std::string &end, uint64_t limit) const{\n\tleveldb::Iterator *it;\n\tleveldb::ReadOptions iterate_options;\n\titerate_options.fill_cache = false;\n\tit = db->NewIterator(iterate_options);\n\tit->Seek(start);\n\tif(it->Valid() && it->key() == start){\n\t\tit->Next();\n\t}\n\treturn new Iterator(it, end, limit);\n}\n\nIterator* SSDB::rev_iterator(const std::string &start, const std::string &end, uint64_t limit) const{\n\tleveldb::Iterator *it;\n\tleveldb::ReadOptions iterate_options;\n\titerate_options.fill_cache = false;\n\tit = db->NewIterator(iterate_options);\n\tit->Seek(start);\n\tif(!it->Valid()){\n\t\tit->SeekToLast();\n\t}else{\n\t\tit->Prev();\n\t}\n\treturn new Iterator(it, end, limit, Iterator::BACKWARD);\n}\n\n\n\/* raw operates *\/\n\nint SSDB::raw_set(const Bytes &key, const Bytes &val) const{\n\tleveldb::WriteOptions write_opts;\n\tleveldb::Status s = db->Put(write_opts, key.Slice(), val.Slice());\n\tif(!s.ok()){\n\t\tlog_error(\"set error: %s\", s.ToString().c_str());\n\t\treturn -1;\n\t}\n\treturn 1;\n}\n\nint SSDB::raw_del(const Bytes &key) const{\n\tleveldb::WriteOptions write_opts;\n\tleveldb::Status s = db->Delete(write_opts, key.Slice());\n\tif(!s.ok()){\n\t\tlog_error(\"del error: %s\", s.ToString().c_str());\n\t\treturn -1;\n\t}\n\treturn 1;\n}\n\nint SSDB::raw_get(const Bytes &key, std::string *val) const{\n\tleveldb::ReadOptions opts;\n\topts.fill_cache = false;\n\tleveldb::Status s = db->Get(opts, key.Slice(), val);\n\tif(s.IsNotFound()){\n\t\treturn 0;\n\t}\n\tif(!s.ok()){\n\t\tlog_error(\"get error: %s\", s.ToString().c_str());\n\t\treturn -1;\n\t}\n\treturn 1;\n}\n\nstd::vector<std::string> SSDB::info() const{\n\t\/\/  \"leveldb.num-files-at-level<N>\" - return the number of files at level <N>,\n\t\/\/     where <N> is an ASCII representation of a level number (e.g. \"0\").\n\t\/\/  \"leveldb.stats\" - returns a multi-line string that describes statistics\n\t\/\/     about the internal operation of the DB.\n\t\/\/  \"leveldb.sstables\" - returns a multi-line string that describes all\n\t\/\/     of the sstables that make up the db contents.\n\tstd::vector<std::string> info;\n\tstd::vector<std::string> keys;\n\t\/*\n\tfor(int i=0; i<7; i++){\n\t\tchar buf[128];\n\t\tsnprintf(buf, sizeof(buf), \"leveldb.num-files-at-level%d\", i);\n\t\tkeys.push_back(buf);\n\t}\n\t*\/\n\tkeys.push_back(\"leveldb.stats\");\n\t\/\/keys.push_back(\"leveldb.sstables\");\n\n\tfor(size_t i=0; i<keys.size(); i++){\n\t\tstd::string key = keys[i];\n\t\tstd::string val;\n\t\tif(db->GetProperty(key, &val)){\n\t\t\tinfo.push_back(key);\n\t\t\tinfo.push_back(val);\n\t\t}\n\t}\n\n\treturn info;\n}\n\nvoid SSDB::compact() const{\n\tdb->CompactRange(NULL, NULL);\n}\n\nint SSDB::key_range(std::vector<std::string> *keys) const{\n\tint ret = 0;\n\tstd::string kstart, kend;\n\tstd::string hstart, hend;\n\tstd::string zstart, zend;\n\t\n\tIterator *it;\n\t\n\tit = this->iterator(encode_kv_key(\"\"), \"\", 1);\n\tif(it->next()){\n\t\tBytes ks = it->key();\n\t\tif(ks.data()[0] == DataType::KV){\n\t\t\tstd::string n;\n\t\t\tif(decode_kv_key(ks, &n) == -1){\n\t\t\t\tret = -1;\n\t\t\t}else{\n\t\t\t\tkstart = n;\n\t\t\t}\n\t\t}\n\t}\n\tdelete it;\n\t\n\tit = this->rev_iterator(encode_kv_key(\"\\xff\"), \"\", 1);\n\tif(it->next()){\n\t\tBytes ks = it->key();\n\t\tif(ks.data()[0] == DataType::KV){\n\t\t\tstd::string n;\n\t\t\tif(decode_kv_key(ks, &n) == -1){\n\t\t\t\tret = -1;\n\t\t\t}else{\n\t\t\t\tkend = n;\n\t\t\t}\n\t\t}\n\t}\n\tdelete it;\n\t\n\tit = this->iterator(encode_hsize_key(\"\"), \"\", 1);\n\tif(it->next()){\n\t\tBytes ks = it->key();\n\t\tif(ks.data()[0] == DataType::HSIZE){\n\t\t\tstd::string n;\n\t\t\tif(decode_hsize_key(ks, &n) == -1){\n\t\t\t\tret = -1;\n\t\t\t}else{\n\t\t\t\thstart = n;\n\t\t\t}\n\t\t}\n\t}\n\tdelete it;\n\t\n\tit = this->rev_iterator(encode_hsize_key(\"\\xff\"), \"\", 1);\n\tif(it->next()){\n\t\tBytes ks = it->key();\n\t\tif(ks.data()[0] == DataType::HSIZE){\n\t\t\tstd::string n;\n\t\t\tif(decode_hsize_key(ks, &n) == -1){\n\t\t\t\tret = -1;\n\t\t\t}else{\n\t\t\t\thend = n;\n\t\t\t}\n\t\t}\n\t}\n\tdelete it;\n\t\n\tit = this->iterator(encode_zsize_key(\"\"), \"\", 1);\n\tif(it->next()){\n\t\tBytes ks = it->key();\n\t\tif(ks.data()[0] == DataType::ZSIZE){\n\t\t\tstd::string n;\n\t\t\tif(decode_hsize_key(ks, &n) == -1){\n\t\t\t\tret = -1;\n\t\t\t}else{\n\t\t\t\tzstart = n;\n\t\t\t}\n\t\t}\n\t}\n\tdelete it;\n\t\n\tit = this->rev_iterator(encode_zsize_key(\"\\xff\"), \"\", 1);\n\tif(it->next()){\n\t\tBytes ks = it->key();\n\t\tif(ks.data()[0] == DataType::ZSIZE){\n\t\t\tstd::string n;\n\t\t\tif(decode_hsize_key(ks, &n) == -1){\n\t\t\t\tret = -1;\n\t\t\t}else{\n\t\t\t\tzend = n;\n\t\t\t}\n\t\t}\n\t}\n\tdelete it;\n\n\tkeys->push_back(kstart);\n\tkeys->push_back(kend);\n\tkeys->push_back(hstart);\n\tkeys->push_back(hend);\n\tkeys->push_back(zstart);\n\tkeys->push_back(zend);\n\t\n\treturn ret;\n}\n","avg_line_length":23.3017241379,"max_line_length":101,"alphanum_fraction":0.6269577013,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":35491,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\n\n#include \"toonzqt\/styleeditor.h\"\n#include \"toonzqt\/colorfield.h\"\n#include \"toonzqt\/dvdialog.h\"\n#include \"toonzqt\/gutil.h\"\n#include \"toonzqt\/menubarcommand.h\"\n#include \"toonz\/cleanupcolorstyles.h\"\n#include \"tconvert.h\"\n#include \"tcolorstyles.h\"\n#include \"trop.h\"\n#include \"toonzqt\/lutcalibrator.h\"\n#include \"styledata.h\"\n\n\/\/ Qt includes\n#include <QApplication>\n#include <QClipboard>\n#include <QLayout>\n#include <QPainter>\n#include <QMouseEvent>\n#include <QLabel>\n\nusing namespace DVGui;\n\nnamespace {\n\nvoid drawChessBoard(QPainter &p) {\n  for (int x = 0; x < 4; x++) {\n    for (int y = 0; y < 4; y++) {\n      QColor col((x + y) % 2 == 0 ? Qt::black : Qt::white);\n      p.fillRect(x * 4, y * 4, 4, 4, col);\n    }\n  }\n}\n\nQPixmap getIconPm(const QColor &color) {\n  QPixmap retPm(16, 16);\n  if (color.alpha() == 255) {\n    retPm.fill(color);\n    return retPm;\n  }\n  QPainter p(&retPm);\n  drawChessBoard(p);\n  p.fillRect(0, 0, 16, 16, color);\n  return retPm;\n}\n\n}  \/\/ namespace\n\n\/\/=============================================================================\n\nCommonChessboard *CommonChessboard::instance() {\n  static CommonChessboard _instance;\n  return &_instance;\n}\n\nCommonChessboard::CommonChessboard() : m_bgRas(40.0, 40.0) { update(); }\n\nvoid CommonChessboard::setChessboardColors(const TPixel32 &col1,\n                                           const TPixel32 &col2) {\n  TRop::checkBoard(m_bgRas, col1, col2,\n                   TDimensionD(m_bgRas->getLx() \/ 8, m_bgRas->getLy() \/ 8),\n                   TPointD(0, 0));\n  QImage img(m_bgRas->getRawData(), m_bgRas->getLx(), m_bgRas->getLy(),\n             QImage::Format_ARGB32);\n  m_bgPix = QPixmap::fromImage(img);\n}\n\nvoid CommonChessboard::update() {\n  TPixel32 col1, col2;\n  Preferences::instance()->getChessboardColors(col1, col2);\n  setChessboardColors(col1, col2);\n}\n\n\/\/=============================================================================\n\/*! \\class DVGui::StyleSample\n                \\brief The StyleSample class provides to view a square color.\n\n                Inherits \\b QWidget.\n\n                By default square color is set to \\b TPixel32(235,235,235,255),\n   you\n                can set other color using setColor(); you can also define\n   current color\n                with a style \\b TColorStyle, \\b getStyle(), using setStyle().\n                You can pass to constructor square size.\n\n                StyleSample permit to manage click event, it's possile to enable\n   this\n                feature setting enableClick(bool on) to true.\n                If it is enable when click in square class emit the signal\n                clicked(const TColorStyle &style).\n*\/\n\/*!\t\\fn void DVGui::StyleSample::clicked(const TColorStyle &style)\n                This signal is emitted when click event is enable and a style is\n   set.\n*\/\n\/*!\t\\fn void DVGui::StyleSample::enableClick(bool on)\n                Set click event enable if \\b is true, disable otherwise.\n                If true setStyle store current style and buttonPress emit signal\n                clicked(const TColorStyle &style).\n*\/\nStyleSample::StyleSample(QWidget *parent, int sizeX, int sizeY)\n    : m_samplePixmap(sizeX, sizeY, QImage::Format_ARGB32)\n    , m_bgRas(sizeX, sizeY)\n    , m_style(0)\n    , m_clickEnabled(false)\n    , m_chessColor1(0, 0, 0)\n    , m_chessColor2(255, 255, 255)\n    , m_sysChessboard(false)\n    , m_stretch(true)\n    , m_isEditing(false) {\n  setMinimumSize(sizeX, sizeY);\n  setColor(TPixel32::Transparent);\n  TRop::checkBoard(m_bgRas, m_chessColor1, m_chessColor2,\n                   TDimensionD(sizeX \/ 8, sizeX \/ 8), TPointD(0, 0));\n  setEnable(true);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nStyleSample::~StyleSample() {\n  if (m_style) delete m_style;\n  m_style = 0;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! Return current StyleSample \\b TColorStyle style.\n *\/\nTColorStyle *StyleSample::getStyle() const { return m_style; }\n\n\/\/-----------------------------------------------------------------------------\n\/*! Update current square colore and, if click event is enable set current\n                StyleSample \\b TColorStyle style to \\b style.\n*\/\nvoid StyleSample::setStyle(TColorStyle &style, int colorParameterIndex) {\n  \/\/ Store current color\n  TPixel32 color = style.getColorParamValue(colorParameterIndex);\n  m_currentColor = QColor(color.r, color.g, color.b, color.m);\n  if (LutManager::instance()->isValid())\n    LutManager::instance()->convert(m_currentColor);\n\n  \/*-- TSolidColorStyle\u306e\u5834\u5408\u306e\u307f\u3001\u5358\u8272\u5857\u308a\u3064\u3076\u3057 --*\/\n  if (style.getTagId() == 3) {\n    setColor(style.getMainColor());\n    m_stretch = true;\n  } else {\n    TDimension iconDim(width(), height());\n\n    \/\/ obtain square icon for the TMyPaintBrushStyle\n    \/\/ so that the checkerboard color will become consistent with solido style\n    \/\/ when the main color is semi-transparent.\n    if (style.getTagId() == 4001) {\n      int d   = std::min(width(), height());\n      iconDim = TDimension(d, d);\n    }\n\n    TRaster32P icon = style.getIcon(iconDim);\n    \/\/ TRaster32P icon =\n    \/\/  style.getIcon(qsize2Dimension(m_samplePixmap.rect().size()));\n    m_samplePixmap = rasterToQImage(icon, false);  \/\/ modified in 6.2\n    m_stretch      = false;\n    update();\n  }\n  if (m_cloneStyle) {\n    if (m_style) delete m_style;  \/\/ avoid memory leak\n    m_style = style.clone();\n  }\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! Update current square colore to \\b TPixel32 \\b color.\n                Useful for efficiency if click event is disable.\n*\/\nvoid StyleSample::setColor(const TPixel32 &pixel) {\n  QColor color(pixel.r, pixel.g, pixel.b, pixel.m);\n  if (LutManager::instance()->isValid()) LutManager::instance()->convert(color);\n\n  m_samplePixmap.fill(color.rgba());\n  update();\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid StyleSample::setChessboardColors(const TPixel32 &col1,\n                                      const TPixel32 &col2) {\n  m_chessColor1 = col1;\n  m_chessColor2 = col2;\n  TRop::checkBoard(m_bgRas, m_chessColor1, m_chessColor2,\n                   TDimensionD(m_bgRas->getLx() \/ 8, m_bgRas->getLy() \/ 8),\n                   TPointD(0, 0));\n  update();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! Paint square color.\n *\/\nvoid StyleSample::paintEvent(QPaintEvent *event) {\n  if (!isEnable()) return;\n  QPainter painter(this);\n  if (m_sysChessboard) {\n    painter.drawTiledPixmap(rect(),\n                            DVGui::CommonChessboard::instance()->getPixmap());\n  } else {\n    QImage img(m_bgRas->getRawData(), m_bgRas->getLx(), m_bgRas->getLy(),\n               QImage::Format_ARGB32);\n    painter.drawImage(0, 0, img.scaled(size()));\n  }\n  if (m_stretch) {\n    painter.drawImage(0, 0, m_samplePixmap.scaled(size()));\n  } else {\n    \/\/ put the icon on the left\n    int x = 0;\n    \/\/ int x = (width() - m_samplePixmap.width()) \/ 2;\n    int y = (height() - m_samplePixmap.height()) \/ 2;\n    painter.fillRect(rect(), m_currentColor);\n    painter.drawImage(x, y, m_samplePixmap);\n  }\n  if (m_isEditing) {\n    \/\/ QRect rect(0,0,m_bgRas->getLx(),m_bgRas->getLy());\n    painter.setPen(Qt::white);\n    painter.drawRect(rect().adjusted(0, 0, -1, -1));\n    painter.drawRect(rect().adjusted(2, 2, -3, -3));\n    painter.setPen(QColor(180, 210, 255));\n    painter.drawRect(rect().adjusted(1, 1, -2, -2));\n  }\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! If exist current style and event click is enable emit signal\n                clicked(const TColorStyle &style).\n*\/\nvoid StyleSample::mousePressEvent(QMouseEvent *event) {\n  if (m_clickEnabled)\n    emit clicked();\n  else\n    event->ignore();\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid StyleSample::mouseDoubleClickEvent(QMouseEvent *event) { event->ignore(); }\n\n\/\/=============================================================================\n\/*! \\class DVGui::ChannelField\n                \\brief The ChannelField class is used to view an object to\n   manage a color\n                                         value, red, green, blue or transparency\n   channel.\n\n                Inherits \\b QWidget.\n\n                The object is composed of grid layout \\b QGridLayout which\n   contains a label\n                in first row, first column, to identify channel, a text field \\b\n   IntLineEdit\n                in first row, second column, and a slider in second row, second\n   column.\n                Texf field and slider are connected, so if you change one the\n   other automatically\n                change. You can set current value getChannel(), using\n   setChannel().\n                This two object is used to manage channel value, them range is\n   fixed to [0,255].\n                This object size is fixed, [50, 2*DVGui::WidgetHeight].\n\n                To know when channel parameter value change class provides a\n   signal, valueChanged(int value);\n                class emit signal when slider value change or when text field is\n   editing,\n                see SLOT: onSliderChanged(int value) and onEditChanged(const\n   QString &str)\n                to know when signal is emitted.\n*\/\n\/*!\t\\fn void DVGui::ChannelField::valueChanged(int value)\n                This signal is emitted when ChannelField, slider or text field,\n   value change;\n                if slider position change or text field is editing.\n                \\sa onEditChanged(const QString &str) and onSliderChanged(int\n   value).\n*\/\nChannelField::ChannelField(QWidget *parent, const QString &string, int value,\n                           int maxValue, bool horizontal, int labelWidth,\n                           int sliderWidth)\n    : QWidget(parent), m_maxValue(maxValue) {\n  assert(maxValue > 0);\n  assert(0 <= value && value <= m_maxValue);\n\n  QLabel *channelName = new QLabel(string, this);\n  m_channelEdit       = new DVGui::IntLineEdit(this, value, 0, maxValue);\n  m_channelSlider     = new QSlider(Qt::Horizontal, this);\n  m_channelSlider->setFocusPolicy(Qt::NoFocus);\n  channelName->setAlignment(Qt::AlignRight | Qt::AlignVCenter);\n  channelName->setFixedWidth(labelWidth);\n\n  m_channelSlider->setRange(0, maxValue);\n  m_channelSlider->setValue(value);\n  if (sliderWidth > 0) m_channelSlider->setFixedWidth(sliderWidth);\n\n  \/\/----layout\n  QGridLayout *mainLayout = new QGridLayout(this);\n  mainLayout->setMargin(0);\n  mainLayout->setSpacing(3);\n  {\n    mainLayout->addWidget(channelName, 0, 0);\n    mainLayout->addWidget(m_channelEdit, 0, 1);\n\n    mainLayout->addWidget(m_channelSlider, horizontal ? 0 : 1,\n                          horizontal ? 2 : 1);\n  }\n  mainLayout->setColumnStretch(0, 0);\n  mainLayout->setColumnStretch(1, 1);\n  mainLayout->setRowStretch(2, 1);\n  setLayout(mainLayout);\n\n  \/\/----singnal-slot connections\n\n  bool ret = connect(m_channelEdit, SIGNAL(textChanged(const QString &)),\n                     SLOT(onEditChanged(const QString &)));\n  ret      = ret && connect(m_channelEdit, SIGNAL(editingFinished()),\n                       SLOT(onEditFinished()));\n  ret      = ret && connect(m_channelSlider, SIGNAL(valueChanged(int)),\n                       SLOT(onSliderChanged(int)));\n  ret      = ret && connect(m_channelSlider, SIGNAL(sliderReleased()),\n                       SLOT(onSliderReleased()));\n  assert(ret);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! Set current value to \\b value.\n                \\sa getChannel()\n*\/\nvoid ChannelField::setChannel(int value) {\n  if (getChannel() == value) return;\n  assert(0 <= value && value <= m_maxValue);\n  m_channelSlider->setValue(value);\n  m_channelEdit->setValue(value);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! Return current channel value.\n                \\sa setChannel()\n*\/\nint ChannelField::getChannel() {\n  int value = m_channelEdit->getValue();\n  assert(m_channelSlider->value() == value);\n  return value;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*!\tSet slider value to new string \\b str value.\n                Verify if value is lower than 255 or greater than 0, range,\n   otherwise set\n                current value to 255 or 0. If slider value is different from\n   value in \\b str\n                emit signal valueChanged(int value).\n*\/\nvoid ChannelField::onEditChanged(const QString &str) {\n  int value = str.toInt();\n  if (value < 0) value = 0;\n  if (value > m_maxValue) value = m_maxValue;\n  assert(0 <= value && value <= m_maxValue);\n  if (str.toInt() != value) m_channelEdit->setValue(value);\n  if (m_channelSlider->value() == value) return;\n  m_channelSlider->setValue(value);\n  emit valueChanged(value, true);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid ChannelField::onEditFinished() {\n  emit valueChanged(m_channelEdit->getValue(), false);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! Set text field value to \\b value. If text field value is different from \\b\n   value\n                emit signal valueChanged(int value).\n*\/\nvoid ChannelField::onSliderChanged(int value) {\n  assert(0 <= value && value <= m_maxValue);\n  if (m_channelEdit->getValue() == value) return;\n  m_channelEdit->setText(QString(std::to_string(value).c_str()));\n  emit valueChanged(value, true);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid ChannelField::onSliderReleased() {\n  emit valueChanged(m_channelSlider->value(), false);\n}\n\n\/\/=============================================================================\n\nColorField::ColorFieldEditorController *ColorField::m_editorController = 0;\n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew\n\/\/ ColorField::ColorFieldEditorController();\n\n\/\/=============================================================================\n\/*! \\class DVGui::ColorField\n                \\brief The ColorField class is used to view an object to manage\n   a color.\n\n                Inherits \\b QWidget.\n\n                The object is composed of a horizontal layout \\b QHBoxLayout\n   which contains\n                a StyleSample, and three or four ChannelField, it depend if\n   transparency is\n                count, to manage color channel.\n                You can pass to constructor current color value, getColor(), or\n   set it\n                calling setColor(). You can also pass to constructor a boolean\n   to know if\n                manage transparency channel or not, and an integer for\n   StyleSample size.\n\n                To know when color value change class provides a signal,\n   colorChanged(const TPixel32 &);\n                class emit signal when one ChannelField value change.\n                See SLOT: onRedChannelChanged(int value),\n   onGreenChannelChanged(int value),\n                onBlueChannelChanged(int value) and onAlphaChannelChanged(int\n   value) to know\n                when signal is emitted.\n\n                \\b Example: initialize a ColorField with transparency channel.\n                \\code\n                        ColorField* colorFld = new\n   ColorField(0,true,TPixel32(0,0,255,255),50);\n                \\endcode\n                \\b Result:\n                        \\image html ColorField.jpg\n*\/\n\/*!\t\\fn void DVGui::ColorField::colorChanged(const TPixel32 &)\n                This signal is emitted when a channel value of current color\n   change.\n*\/\n\/*!\t\\fn TPixel32  DVGui::ColorField::getColor() const\n                Return ColorField current color.\n*\/\nColorField::ColorField(QWidget *parent, bool isAlphaActive, TPixel32 color,\n                       int squareSize, bool useStyleEditor, int sliderWidth)\n    : QWidget(parent)\n    , m_color(color)\n    , m_notifyEditingChange(true)\n    , m_useStyleEditor(useStyleEditor) {\n  setMaximumHeight(squareSize);\n  QHBoxLayout *layout = new QHBoxLayout(this);\n  layout->setMargin(0);\n  layout->setSpacing(5);\n\n  layout->setSizeConstraint(QLayout::SetFixedSize);\n\n  int h = WidgetHeight;\n\n  m_colorSample = new StyleSample(this, squareSize, squareSize);\n  m_colorSample->setColor(m_color);\n  m_redChannel =\n      new ChannelField(this, tr(\"R:\"), m_color.r, 255, false, 13, sliderWidth);\n  connect(m_redChannel, SIGNAL(valueChanged(int, bool)),\n          SLOT(onRedChannelChanged(int, bool)));\n  m_greenChannel =\n      new ChannelField(this, tr(\"G:\"), m_color.g, 255, false, 13, sliderWidth);\n  connect(m_greenChannel, SIGNAL(valueChanged(int, bool)),\n          SLOT(onGreenChannelChanged(int, bool)));\n  m_blueChannel =\n      new ChannelField(this, tr(\"B:\"), m_color.b, 255, false, 13, sliderWidth);\n  connect(m_blueChannel, SIGNAL(valueChanged(int, bool)),\n          SLOT(onBlueChannelChanged(int, bool)));\n  m_alphaChannel =\n      new ChannelField(this, tr(\"A:\"), m_color.m, 255, false, 13, sliderWidth);\n  connect(m_alphaChannel, SIGNAL(valueChanged(int, bool)),\n          SLOT(onAlphaChannelChanged(int, bool)));\n\n  layout->addWidget(m_colorSample);\n  layout->addWidget(m_redChannel);\n  layout->addWidget(m_greenChannel);\n  layout->addWidget(m_blueChannel);\n  layout->addWidget(m_alphaChannel);\n\n  if (!isAlphaActive) m_alphaChannel->hide();\n  setLayout(layout);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! Set ColorField current color to \\b color. Update channel value of\n                \\b ChannelField and \\b StyleSample color.\n*\/\n\nvoid ColorField::setAlphaActive(bool active) {\n  if (active && !m_alphaChannel->isVisibleTo(this)) {\n    m_alphaChannel->show();\n    connect(m_alphaChannel, SIGNAL(valueChanged(int, bool)),\n            SLOT(onAlphaChannelChanged(int, bool)));\n    assert(m_color.m == 255);\n    m_alphaChannel->setChannel(0);\n    m_color.m = 0;\n    m_colorSample->setColor(m_color);\n    emit colorChanged(m_color, false);\n  } else if (!active && m_alphaChannel->isVisibleTo(this)) {\n    m_alphaChannel->hide();\n    disconnect(m_alphaChannel, SIGNAL(valueChanged(int, bool)), this,\n               SLOT(onAlphaChannelChanged(int, bool)));\n    if (m_color.m != 255) {\n      m_alphaChannel->setChannel(255);\n      m_color.m = 255;\n      m_colorSample->setColor(m_color);\n      emit colorChanged(m_color, false);\n    }\n  }\n}\n\n\/\/------------------------------\n\nvoid ColorField::setColor(const TPixel32 &color) {\n  if (m_color == color) return;\n  m_color = color;\n  updateChannels();\n  m_colorSample->setColor(m_color);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! Set all \\b ChannelField channel value to ColorField current color.\n *\/\nvoid ColorField::hideChannelsFields(bool hide) {\n  if (hide) {\n    m_redChannel->hide();\n    m_greenChannel->hide();\n    m_blueChannel->hide();\n    m_alphaChannel->hide();\n    disconnect(m_redChannel, SIGNAL(valueChanged(int, bool)), this,\n               SLOT(onRedChannelChanged(int, bool)));\n    disconnect(m_greenChannel, SIGNAL(valueChanged(int, bool)), this,\n               SLOT(onGreenChannelChanged(int, bool)));\n    disconnect(m_blueChannel, SIGNAL(valueChanged(int, bool)), this,\n               SLOT(onBlueChannelChanged(int, bool)));\n    disconnect(m_alphaChannel, SIGNAL(valueChanged(int, bool)), this,\n               SLOT(onAlphaChannelChanged(int, bool)));\n  } else {\n    m_redChannel->show();\n    m_greenChannel->show();\n    m_blueChannel->show();\n    m_alphaChannel->show();\n    ;\n    connect(m_redChannel, SIGNAL(valueChanged(int, bool)),\n            SLOT(onRedChannelChanged(int, bool)));\n    connect(m_greenChannel, SIGNAL(valueChanged(int, bool)),\n            SLOT(onGreenChannelChanged(int, bool)));\n    connect(m_blueChannel, SIGNAL(valueChanged(int, bool)),\n            SLOT(onBlueChannelChanged(int, bool)));\n    connect(m_alphaChannel, SIGNAL(valueChanged(int, bool)),\n            SLOT(onAlphaChannelChanged(int, bool)));\n  }\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! Set all \\b ChannelField channel value to ColorField current color.\n *\/\nvoid ColorField::updateChannels() {\n  m_redChannel->setChannel(m_color.r);\n  m_greenChannel->setChannel(m_color.g);\n  m_blueChannel->setChannel(m_color.b);\n  m_alphaChannel->setChannel(m_color.m);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid ColorField::mousePressEvent(QMouseEvent *event) {\n  if (event->button() != Qt::LeftButton) return;\n  QPoint p = event->pos();\n  if (!m_colorSample->visibleRegion().contains(p)) return;\n\n  if (!m_useStyleEditor || !getEditorController()) return;\n\n  getEditorController()->edit(this);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid ColorField::mouseDoubleClickEvent(QMouseEvent *event) {\n  QPoint p = event->pos();\n  if (!m_colorSample->visibleRegion().contains(p)) return;\n\n  if (!m_useStyleEditor || !getEditorController()) return;\n\n  CommandManager::instance()->execute(\"MI_OpenStyleControl\");\n  getEditorController()->edit(this);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid ColorField::hideEvent(QHideEvent *) {\n  if (!m_useStyleEditor || !getEditorController()) return;\n\n  getEditorController()->hide();\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid ColorField::contextMenuEvent(QContextMenuEvent *event) {\n  bool hasColor = QApplication::clipboard()->mimeData()->hasColor();\n  const StyleData *data =\n      dynamic_cast<const StyleData *>(QApplication::clipboard()->mimeData());\n\n  QMenu menu(this);\n  if (hasColor) {  \/\/ pasting QColor\n    QColor color = qvariant_cast<QColor>(\n        QApplication::clipboard()->mimeData()->colorData());\n    QAction *action = new QAction(tr(\"Paste Color\"), this);\n    action->setIcon(QIcon(getIconPm(color)));\n    action->setData(color);\n\n    connect(action, SIGNAL(triggered()), this, SLOT(onPasteColor()));\n    menu.addAction(action);\n    menu.addSeparator();\n  } else if (data && data->getStyleCount() > 0) {  \/\/ pasting styles colors\n    \/\/ show 10 styles in maximum\n    int styleCount = std::min(10, data->getStyleCount());\n    for (int i = 0; i < styleCount; i++) {\n      QString styleName = QString::fromStdWString(data->getStyle(i)->getName());\n      TPixel32 color    = data->getStyle(i)->getMainColor();\n      QColor _color(color.r, color.g, color.b, color.m);\n\n      QAction *action =\n          new QAction(tr(\"Paste Color of %1\").arg(styleName), this);\n      action->setIcon(QIcon(getIconPm(_color)));\n      action->setData(_color);\n\n      connect(action, SIGNAL(triggered()), this, SLOT(onPasteColor()));\n      menu.addAction(action);\n    }\n    menu.addSeparator();\n  }\n\n  QAction *copyAction = new QAction(tr(\"Copy Color\"), this);\n  connect(copyAction, SIGNAL(triggered()), this, SLOT(onCopyColor()));\n  menu.addAction(copyAction);\n\n  menu.exec(event->globalPos());\n  event->accept();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! If current red channel value of color is different from \\b value set it,\n                change \\b StyleSample color and emit signal \\b\n   colorChanged(const TPixel32 &).\n*\/\nvoid ColorField::onRedChannelChanged(int value, bool isDragging) {\n  if (m_color.r == value) {\n    if (!isDragging) emit colorChanged(m_color, isDragging);\n    return;\n  }\n  m_color = TPixel32(value, m_color.g, m_color.b, m_color.m);\n  m_colorSample->setColor(m_color);\n  emit colorChanged(m_color, isDragging);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! If current green channel value of color is different from \\b value set it,\n                change \\b StyleSample color and emit signal \\b\n   colorChanged(const TPixel32 &).\n*\/\nvoid ColorField::onGreenChannelChanged(int value, bool isDragging) {\n  if (m_color.g == value) {\n    if (!isDragging) emit colorChanged(m_color, isDragging);\n    return;\n  }\n  m_color = TPixel32(m_color.r, value, m_color.b, m_color.m);\n  m_colorSample->setColor(m_color);\n  emit colorChanged(m_color, isDragging);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! If current blue channel value of color is different from \\b value set it,\n                change \\b StyleSample color and emit signal \\b\n   colorChanged(const TPixel32 &).\n*\/\nvoid ColorField::onBlueChannelChanged(int value, bool isDragging) {\n  if (m_color.b == value) {\n    if (!isDragging) emit colorChanged(m_color, isDragging);\n    return;\n  }\n  m_color = TPixel32(m_color.r, m_color.g, value, m_color.m);\n  m_colorSample->setColor(m_color);\n  emit colorChanged(m_color, isDragging);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/*! If current alpha channel value of color is different from \\b value set it,\n                change \\b StyleSample color and emit signal \\b\n   colorChanged(const TPixel32 &).\n*\/\nvoid ColorField::onAlphaChannelChanged(int value, bool isDragging) {\n  if (m_color.m == value) {\n    if (!isDragging) emit colorChanged(m_color, isDragging);\n    return;\n  }\n  m_color = TPixel32(m_color.r, m_color.g, m_color.b, value);\n  m_colorSample->setColor(m_color);\n  emit colorChanged(m_color, isDragging);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid ColorField::onPasteColor() {\n  QColor color = qobject_cast<QAction *>(sender())->data().value<QColor>();\n\n  m_color = TPixel32(color.red(), color.green(), color.blue(), color.alpha());\n  if (!m_alphaChannel->isVisible()) m_color.m = 255;\n  m_colorSample->setColor(m_color);\n  updateChannels();\n  emit colorChanged(m_color, false);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid ColorField::onCopyColor() {\n  QColor color(m_color.r, m_color.g, m_color.b, m_color.m);\n\n  QMimeData *data = new QMimeData();\n  data->setColorData(color);\n  QApplication::clipboard()->setMimeData(data);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid ColorField::setChessboardColors(const TPixel32 &col1,\n                                     const TPixel32 &col2) {\n  m_colorSample->setChessboardColors(col1, col2);\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid ColorField::setEditorController(\n    ColorFieldEditorController *editorController) {\n  m_editorController = editorController;\n}\n\n\/\/-----------------------------------------------------------------------------\n\nColorField::ColorFieldEditorController *ColorField::getEditorController() {\n  return m_editorController;\n}\n\n\/\/-----------------------------------------------------------------------\n#define SQUARESIZE 50\n\nvoid CleanupColorField::onBrightnessChannelChanged(int value, bool dragging) {\n  m_cleanupStyle->setBrightness(value);\n  m_ph->notifyColorStyleChanged(dragging);\n}\n\n\/\/-----------------------------------------------\n\nvoid CleanupColorField::onContrastChannelChanged(int value, bool dragging) {\n  m_cleanupStyle->setContrast(value);\n  m_ph->notifyColorStyleChanged(dragging);\n}\n\n\/\/-----------------------------------------------\n\nvoid CleanupColorField::onCThresholdChannelChanged(int value, bool dragging) {\n  ((TBlackCleanupStyle *)m_cleanupStyle)->setColorThreshold((double)value);\n  m_ph->notifyColorStyleChanged(dragging);\n}\n\n\/\/-----------------------------------------------\n\nvoid CleanupColorField::onWThresholdChannelChanged(int value, bool dragging) {\n  ((TBlackCleanupStyle *)m_cleanupStyle)->setWhiteThreshold((double)value);\n  m_ph->notifyColorStyleChanged(dragging);\n}\n\nvoid CleanupColorField::onHRangeChannelChanged(int value, bool dragging) {\n  ((TColorCleanupStyle *)m_cleanupStyle)->setHRange(value);\n  m_ph->notifyColorStyleChanged(dragging);\n}\n\n\/\/-----------------------------------------------\n\nvoid CleanupColorField::onLineWidthChannelChanged(int value, bool dragging) {\n  ((TColorCleanupStyle *)m_cleanupStyle)->setLineWidth(value);\n  m_ph->notifyColorStyleChanged(dragging);\n}\n\n\/\/---------------------------------------------------\n\nvoid CleanupColorField::mousePressEvent(QMouseEvent *event) {\n  if (event->button() != Qt::LeftButton) return;\n\n  emit StyleSelected(m_cleanupStyle);\n\n  if (getEditorController()) getEditorController()->edit(this);\n}\n\n\/\/-----------------------------------------------\nCleanupColorField::CleanupColorField(QWidget *parent,\n                                     TCleanupStyle *cleanupStyle,\n                                     TPaletteHandle *ph, bool greyMode)\n    : QWidget(parent)\n    , m_style(cleanupStyle)\n    , m_cleanupStyle(cleanupStyle)\n    , m_ph(ph)\n    , m_greyMode(greyMode)\n    , m_notifyEditingChange(true) {\n  TBlackCleanupStyle *bs = dynamic_cast<TBlackCleanupStyle *>(cleanupStyle);\n  TColorCleanupStyle *cs = dynamic_cast<TColorCleanupStyle *>(cleanupStyle);\n  assert(bs || cs);\n\n  m_colorSample = new StyleSample(this, SQUARESIZE \/ 2, SQUARESIZE);\n  m_brightnessChannel =\n      new ChannelField(this, DVGui::CleanupColorField::tr(\"Brightness:\"),\n                       cleanupStyle->getBrightness(), 100, true, 75, -1);\n  m_contrastChannel =\n      new ChannelField(this, DVGui::CleanupColorField::tr(\"Contrast:\"),\n                       cleanupStyle->getContrast(), 100, true, 75, -1);\n  if (!greyMode) {\n    if (bs) {\n      m_cThresholdChannel =\n          new ChannelField(this, DVGui::CleanupColorField::tr(\"Color Thres\"),\n                           bs->getColorThreshold(), 100, true, 75, -1);\n      m_wThresholdChannel =\n          new ChannelField(this, DVGui::CleanupColorField::tr(\"White Thres\"),\n                           bs->getWhiteThreshold(), 100, true, 75, -1);\n    } else  \/\/ cs\n    {\n      m_hRangeChannel =\n          new ChannelField(this, DVGui::CleanupColorField::tr(\"H Range\"),\n                           cs->getHRange(), 120, true, 75, -1);\n      m_lineWidthChannel =\n          new ChannelField(this, DVGui::CleanupColorField::tr(\"Line Width\"),\n                           cs->getLineWidth(), 100, true, 75, -1);\n    }\n  }\n\n  m_colorSample->setStyle(*cleanupStyle, 0);\n\n  \/\/---- layout\n\n  QHBoxLayout *mainLay = new QHBoxLayout();\n  mainLay->setMargin(8);\n  mainLay->setSpacing(5);\n  {\n    mainLay->addWidget(m_colorSample, 0);\n\n    QVBoxLayout *paramLay = new QVBoxLayout();\n    paramLay->setMargin(0);\n    paramLay->setSpacing(3);\n    {\n      paramLay->addWidget(m_brightnessChannel);\n      paramLay->addWidget(m_contrastChannel);\n      if (!greyMode) {\n        if (bs) {\n          paramLay->addWidget(m_cThresholdChannel);\n          paramLay->addWidget(m_wThresholdChannel);\n        } else {\n          paramLay->addWidget(m_hRangeChannel);\n          paramLay->addWidget(m_lineWidthChannel);\n        }\n      }\n    }\n    mainLay->addLayout(paramLay, 1);\n  }\n  setLayout(mainLay);\n\n  \/\/---- signal-slot connections\n\n  bool ret = true;\n  ret = ret && connect(m_brightnessChannel, SIGNAL(valueChanged(int, bool)),\n                       SLOT(onBrightnessChannelChanged(int, bool)));\n  ret = ret && connect(m_contrastChannel, SIGNAL(valueChanged(int, bool)),\n                       SLOT(onContrastChannelChanged(int, bool)));\n  if (!greyMode) {\n    if (bs) {\n      ret = ret && connect(m_cThresholdChannel, SIGNAL(valueChanged(int, bool)),\n                           SLOT(onCThresholdChannelChanged(int, bool)));\n      ret = ret && connect(m_wThresholdChannel, SIGNAL(valueChanged(int, bool)),\n                           SLOT(onWThresholdChannelChanged(int, bool)));\n    } else {\n      ret = ret && connect(m_hRangeChannel, SIGNAL(valueChanged(int, bool)),\n                           SLOT(onHRangeChannelChanged(int, bool)));\n      ret = ret && connect(m_lineWidthChannel, SIGNAL(valueChanged(int, bool)),\n                           SLOT(onLineWidthChannelChanged(int, bool)));\n    }\n  }\n}\n\n\/\/--------------------------------------------------------------\n\nvoid CleanupColorField::updateColor() {\n  if (m_cleanupStyle->canUpdate()) {\n    m_cleanupStyle->invalidateIcon();\n    m_colorSample->setStyle(*m_cleanupStyle, 0);\n\n    m_brightnessChannel->setChannel(m_cleanupStyle->getBrightness());\n    if (m_cleanupStyle->isContrastEnabled())\n      m_contrastChannel->setChannel(m_cleanupStyle->getContrast());\n\n    TBlackCleanupStyle *bs;\n    TColorCleanupStyle *cs;\n    if ((bs = dynamic_cast<TBlackCleanupStyle *>(m_cleanupStyle)) &&\n        !m_greyMode) {\n      m_cThresholdChannel->setChannel(bs->getColorThreshold());\n      m_wThresholdChannel->setChannel(bs->getWhiteThreshold());\n    } else if ((cs = dynamic_cast<TColorCleanupStyle *>(m_cleanupStyle))) {\n      m_hRangeChannel->setChannel(cs->getHRange());\n      m_lineWidthChannel->setChannel(cs->getLineWidth());\n    }\n  }\n}\n\n\/\/--------------------------------------------------------------\n\nTPixel32 CleanupColorField::getColor() const {\n  return m_cleanupStyle->getMainColor();\n}\n\n\/\/--------------------------------------------------------------\n\nvoid CleanupColorField::setColor(const TPixel32 &color) {\n  if (m_cleanupStyle->getMainColor() == color) return;\n\n  m_cleanupStyle->setMainColor(color);\n  m_cleanupStyle->invalidateIcon();\n  m_colorSample->setStyle(*m_cleanupStyle, 0);\n  m_ph->notifyColorStyleChanged(false);\n}\n\n\/\/------------------------------------------------------------\n\nTPixel32 CleanupColorField::getOutputColor() const {\n  return m_cleanupStyle->getColorParamValue(1);\n}\n\n\/\/------------------------------------------------------------\n\nvoid CleanupColorField::setOutputColor(const TPixel32 &color) {\n  if (getOutputColor() == color) return;\n\n  m_cleanupStyle->setColorParamValue(1, color);\n  m_cleanupStyle->invalidateIcon();\n  m_colorSample->setStyle(*m_cleanupStyle, 0);\n  m_ph->notifyColorStyleChanged();\n}\n\n\/\/------------------------------------------------------------\n\nvoid CleanupColorField::setStyle(TColorStyle *style) {\n  if (getColor() == style->getMainColor() &&\n      getOutputColor() == style->getColorParamValue(1))\n    return;\n\n  m_cleanupStyle->setMainColor(style->getMainColor());\n  m_cleanupStyle->setColorParamValue(1, style->getColorParamValue(1));\n  m_cleanupStyle->invalidateIcon();\n  m_colorSample->setStyle(*m_cleanupStyle, 0);\n  m_ph->notifyColorStyleChanged();\n}\n\n\/\/------------------------------------------------------------\n\nCleanupColorField::CleanupColorFieldEditorController\n    *CleanupColorField::m_editorController = 0;\n\nCleanupColorField::CleanupColorFieldEditorController *\nCleanupColorField::getEditorController() {\n  return m_editorController;\n}\n\n\/\/-----------------------------------------------------------------------------\n\nvoid CleanupColorField::setEditorController(\n    CleanupColorFieldEditorController *editorController) {\n  m_editorController = editorController;\n}\n\n\/\/------------------------------------------------------------------\n\nvoid CleanupColorField::mouseDoubleClickEvent(QMouseEvent *event) {\n  QPoint p = event->pos();\n  if (!m_colorSample->visibleRegion().contains(p)) return;\n  emit StyleSelected(m_cleanupStyle);\n  if (!getEditorController()) return;\n\n  CommandManager::instance()->execute(\"MI_OpenStyleControl\");\n  getEditorController()->edit(this);\n}\n\n\/\/-----------------------------------------------------------\n\nvoid CleanupColorField::hideEvent(QHideEvent *) {\n  if (!getEditorController()) return;\n  getEditorController()->edit(0);\n  getEditorController()->hide();\n  \/\/ setEditorController(0);\n}\n\n\/\/-----------------------------------------------------------\n\nvoid CleanupColorField::setContrastEnabled(bool enable) {\n  m_contrastChannel->setEnabled(enable);\n  m_cleanupStyle->enableContrast(enable);\n}\n","avg_line_length":35.3144278607,"max_line_length":80,"alphanum_fraction":0.5928545265,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3651,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/===- PPUOptimizeVSETVLUses.cpp - Replace uses of VR from VSETVL ----===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Optimization pass to avoid copying between VLR and GPR after using vsetvl\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"PPU.h\"\n#include \"PPUInstrInfo.h\"\n#include \"PPUTargetMachine.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\nusing namespace llvm;\n\n#define DEBUG_TYPE \"ppu-optimize-vsetvl-uses\"\n#define PPU_OPTIMIZE_VSETVL_USES_NAME                       \\\n  \"Optimization pass to avoid copies to GPR when using VSETVL\"\nnamespace {\n\nstruct PPUOptimizeVSETVLUses : public MachineFunctionPass {\n  static char ID;\n  const MachineFunction *MF;\n  bool runOnMachineFunction(MachineFunction &Fn) override;\n\n  PPUOptimizeVSETVLUses() : MachineFunctionPass(ID) {}\n\n  MachineFunctionProperties getRequiredProperties() const override {\n    return MachineFunctionProperties().set(\n        MachineFunctionProperties::Property::IsSSA);\n  }\n\n  StringRef getPassName() const override {\n    return PPU_OPTIMIZE_VSETVL_USES_NAME;\n  }\n};\n} \/\/ end anonymous namespace\n\n\nbool isSameRegisterClass(unsigned Reg1, unsigned Reg2) {\n  return PPU::GPRRegClass.contains(Reg1, Reg2) ||\n         PPU::VLRRegClass.contains(Reg1, Reg2);\n}\n\nbool PPUOptimizeVSETVLUses::runOnMachineFunction(MachineFunction &Fn) {\n  if (skipFunction(Fn.getFunction()))\n    return false;\n  if (!Fn.getSubtarget<PPUSubtarget>().hasStdExtV())\n    return false;\n\n  const MachineRegisterInfo &MRI = Fn.getRegInfo();\n\n  LLVM_DEBUG(dbgs() << \"*** Optimizing VSETVL in \"\n                    << Fn.getFunction().getName() << \" ***\\n\");\n\n   for (MachineBasicBlock &MBB : Fn) {\n    for (MachineInstr &Instr : MBB) {\n      if (Instr.isCopy()) {\n          const auto& CopyDest = Instr.getOperand(0);\n          auto& CopySource = Instr.getOperand(1);\n\t \n          const MachineInstr* MI = MRI.getVRegDef(CopySource.getReg());\n          if (!MI) {\n              \/\/ No definition (e.g., a live-in physical register), can't optimize\n              continue;\n          }\n\n          if (MI->getOpcode() == PPU::VSETVL &&\n                !isSameRegisterClass(CopyDest.getReg(), CopySource.getReg())) {\n              LLVM_DEBUG(dbgs() << \"*** Found COPY instruction from VSETVL\" <<\n                                   \"across register class\" << \" ***\\n\");\n              LLVM_DEBUG(Instr.dump());\n\n              const auto& VSETVLDefGPR = MI->getOperand(0);\n              const auto& VSETVLDefVLR = MI->getOperand(1);\n\n              \/\/Handle both GPR->VLR and VLR->GPR\n              const auto& Replacement = \n                  VSETVLDefGPR.getReg() != CopySource.getReg() ?\n                            VSETVLDefGPR : VSETVLDefVLR;\n\n              \/\/Clear flags on CopySource reg\n              CopySource.setIsKill(false);\n\n              CopySource.setReg(Replacement.getReg());\n              \/\/Remove kill flag on all that use Replacement reg\n              MRI.clearKillFlags(Replacement.getReg());\n          }\n      }\n    }\n  }\n\n  return true;\n}\n\nchar PPUOptimizeVSETVLUses::ID = 0;\nINITIALIZE_PASS(PPUOptimizeVSETVLUses, DEBUG_TYPE,\n                PPU_OPTIMIZE_VSETVL_USES_NAME, false, false)\n\nFunctionPass *llvm::createPPUOptimizeVSETVLUsesPass() {\n  return new PPUOptimizeVSETVLUses();\n}\n","avg_line_length":33.495412844,"max_line_length":82,"alphanum_fraction":0.6157217201,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7791,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":3.0,"content":"\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/  By downloading, copying, installing or using the software you agree to this license.\n\/\/  If you do not agree to this license, do not download, install,\n\/\/  copy or use the software.\n\/\/\n\/\/\n\/\/                           License Agreement\n\/\/                For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (c) 2016-2017 Fabian David Tschopp, all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/   * Redistribution's of source code must retain the above copyright notice,\n\/\/     this list of conditions and the following disclaimer.\n\/\/\n\/\/   * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/     this list of conditions and the following disclaimer in the documentation\n\/\/     and\/or other materials provided with the distribution.\n\/\/\n\/\/   * The name of the copyright holders may not be used to endorse or promote products\n\/\/     derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#include \"..\/..\/precomp.hpp\"\n#include <string>\n#include <vector>\n#include \"..\/include\/common.hpp\"\n#include \"..\/include\/ocl4dnn.hpp\"\n#include \"opencl_kernels_dnn.hpp\"\n\nnamespace cv { namespace dnn { namespace ocl4dnn {\ntemplate<typename Dtype>\nOCL4DNNPool<Dtype>::OCL4DNNPool(OCL4DNNPoolConfig config)\n{\n    int dims = config.in_shape.size();\n    int spatial_dims = 2;\n\n    channels_ = config.channels;\n    pool_method_ = config.pool_method;\n    avePoolPaddedArea = config.avePoolPaddedArea;\n    use_half = config.use_half;\n\n    for (int i = 0; i < spatial_dims; ++i)\n    {\n        kernel_shape_.push_back(i == 0 ? config.kernel.height : config.kernel.width);\n        pad_.push_back(i == 0 ? config.pad.height : config.pad.width);\n        stride_.push_back(i == 0 ? config.stride.height : config.stride.width);\n        im_in_shape_.push_back(config.in_shape[dims - spatial_dims + i]);\n        im_out_shape_.push_back(config.out_shape[dims - spatial_dims + i]);\n    }\n\n    kernel_h_ = kernel_shape_[0];\n    kernel_w_ = kernel_shape_[1];\n    stride_h_ = stride_[0];\n    stride_w_ = stride_[1];\n    pad_h_ = pad_[0];\n    pad_w_ = pad_[1];\n    height_ = im_in_shape_[0];\n    width_ = im_in_shape_[1];\n    pooled_height_ = im_out_shape_[0];\n    pooled_width_ = im_out_shape_[1];\n\n    count_ = 1;\n    for (int i = 0; i < config.out_shape.size(); ++i)\n    {\n        count_ *= config.out_shape[i];\n    }\n}\n\ntemplate<typename Dtype>\nOCL4DNNPool<Dtype>::~OCL4DNNPool()\n{\n    \/\/ nothing\n}\n\ntemplate<typename Dtype>\nbool OCL4DNNPool<Dtype>::Forward(const UMat& bottom,\n                                 UMat& top,\n                                 UMat& top_mask)\n{\n    bool ret = true;\n    size_t global[] = { 128 * 128 };\n    size_t local[] = { 128 };\n\n    \/\/ support 2D case\n    switch (pool_method_)\n    {\n    case LIBDNN_POOLING_METHOD_MAX:\n        {\n            bool haveMask = !top_mask.empty();\n            String kname = haveMask ? \"max_pool_forward_mask\" : \"max_pool_forward\";\n            kname += (use_half) ? \"_half\" : \"_float\";\n            ocl::Kernel oclk_max_pool_forward(\n                kname.c_str(),\n                ocl::dnn::ocl4dnn_pooling_oclsrc,\n                format(\" -D Dtype=%s -D KERNEL_MAX_POOL=1 -D KERNEL_W=%d -D KERNEL_H=%d\"\n                       \" -D STRIDE_W=%d -D STRIDE_H=%d\"\n                       \" -D PAD_W=%d -D PAD_H=%d%s\",\n                       (use_half) ? \"half\" : \"float\",\n                       kernel_w_, kernel_h_,\n                       stride_w_, stride_h_,\n                       pad_w_, pad_h_,\n                       haveMask ? \" -D HAVE_MASK=1\" : \"\"\n                ));\n\n            if (oclk_max_pool_forward.empty())\n                return false;\n\n            oclk_max_pool_forward.args(\n                count_,\n                ocl::KernelArg::PtrReadOnly(bottom),\n                channels_,\n                height_,\n                width_,\n                pooled_height_,\n                pooled_width_,\n                ocl::KernelArg::PtrWriteOnly(top),\n                ocl::KernelArg::PtrWriteOnly(top_mask)\n            );\n\n            ret = oclk_max_pool_forward.run(1, global, local, false);\n        }\n        break;\n    case LIBDNN_POOLING_METHOD_AVE:\n        {\n            CV_Assert(top_mask.empty());\n\n            String kname = format(\"ave_pool_forward_%s\", (use_half) ? \"half\" : \"float\");\n            ocl::Kernel oclk_ave_pool_forward(\n                kname.c_str(),\n                ocl::dnn::ocl4dnn_pooling_oclsrc,\n                format(\" -D Dtype=%s -D KERNEL_AVE_POOL=1 -D KERNEL_W=%d -D KERNEL_H=%d\"\n                       \" -D STRIDE_W=%d -D STRIDE_H=%d\"\n                       \" -D PAD_W=%d -D PAD_H=%d%s\",\n                       (use_half) ? \"half\" : \"float\",\n                       kernel_w_, kernel_h_,\n                       stride_w_, stride_h_,\n                       pad_w_, pad_h_,\n                       avePoolPaddedArea ? \" -D AVE_POOL_PADDING_AREA\" : \"\"\n                ));\n\n            if (oclk_ave_pool_forward.empty())\n                return false;\n\n            oclk_ave_pool_forward.args(\n                count_,\n                ocl::KernelArg::PtrReadOnly(bottom),\n                channels_,\n                height_,\n                width_,\n                pooled_height_,\n                pooled_width_,\n                ocl::KernelArg::PtrWriteOnly(top)\n            );\n\n            ret = oclk_ave_pool_forward.run(1, global, local, false);\n        }\n        break;\n    case LIBDNN_POOLING_METHOD_STO:\n        {\n            CV_Assert(top_mask.empty());\n\n            String kname = format(\"sto_pool_forward_test_%s\", (use_half) ? \"half\" : \"float\");\n            ocl::Kernel oclk_sto_pool_forward(\n                kname.c_str(),\n                ocl::dnn::ocl4dnn_pooling_oclsrc,\n                format(\"-D KERNEL_STO_POOL=1 -D KERNEL_W=%d -D KERNEL_H=%d\"\n                       \" -D STRIDE_W=%d -D STRIDE_H=%d\",\n                       kernel_w_, kernel_h_,\n                       stride_w_, stride_h_\n                ));\n\n\n            if (oclk_sto_pool_forward.empty())\n                return false;\n\n            oclk_sto_pool_forward.args(\n                count_,\n                ocl::KernelArg::PtrReadOnly(bottom),\n                channels_,\n                height_,\n                width_,\n                pooled_height_,\n                pooled_width_,\n                ocl::KernelArg::PtrWriteOnly(top)\n            );\n\n            ret = oclk_sto_pool_forward.run(1, global, local, false);\n        }\n        break;\n    default:\n        {\n            ret = false;\n            LOG(FATAL)<< \"Unknown pooling method.\";\n        }\n    }\n    return ret;\n}\n\ntemplate class OCL4DNNPool<float>;\n\n}}} \/\/ namespace cv::dnn::ocl4dnn\n","avg_line_length":35.2533936652,"max_line_length":93,"alphanum_fraction":0.5687331536,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1896,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":28.0,"content":"\/* TEMPLATE GENERATED TESTCASE FILE\r\nFilename: CWE191_Integer_Underflow__short_fscanf_sub_73b.cpp\r\nLabel Definition File: CWE191_Integer_Underflow.label.xml\r\nTemplate File: sources-sinks-73b.tmpl.cpp\r\n*\/\r\n\/*\r\n * @description\r\n * CWE: 191 Integer Underflow\r\n * BadSource: fscanf Read data from the console using fscanf()\r\n * GoodSource: Set data to a small, non-zero number (negative two)\r\n * Sinks: sub\r\n *    GoodSink: Ensure there will not be an underflow before subtracting 1 from data\r\n *    BadSink : Subtract 1 from data, which can cause an Underflow\r\n * Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files\r\n *\r\n * *\/\r\n\r\n#include \"std_testcase.h\"\r\n#include <list>\r\n\r\nusing namespace std;\r\n\r\nnamespace CWE191_Integer_Underflow__short_fscanf_sub_73\r\n{\r\n\r\n#ifndef OMITBAD\r\n\r\nvoid badSink(list<short> dataList)\r\n{\r\n    \/* copy data out of dataList *\/\r\n    short data = dataList.back();\r\n    {\r\n        \/* POTENTIAL FLAW: Subtracting 1 from data could cause an underflow *\/\r\n        short result = data - 1;\r\n        printIntLine(result);\r\n    }\r\n}\r\n\r\n#endif \/* OMITBAD *\/\r\n\r\n#ifndef OMITGOOD\r\n\r\n\/* goodG2B uses the GoodSource with the BadSink *\/\r\nvoid goodG2BSink(list<short> dataList)\r\n{\r\n    short data = dataList.back();\r\n    {\r\n        \/* POTENTIAL FLAW: Subtracting 1 from data could cause an underflow *\/\r\n        short result = data - 1;\r\n        printIntLine(result);\r\n    }\r\n}\r\n\r\n\/* goodB2G uses the BadSource with the GoodSink *\/\r\nvoid goodB2GSink(list<short> dataList)\r\n{\r\n    short data = dataList.back();\r\n    \/* FIX: Add a check to prevent an underflow from occurring *\/\r\n    if (data > SHRT_MIN)\r\n    {\r\n        short result = data - 1;\r\n        printIntLine(result);\r\n    }\r\n    else\r\n    {\r\n        printLine(\"data value is too large to perform subtraction.\");\r\n    }\r\n}\r\n\r\n#endif \/* OMITGOOD *\/\r\n\r\n} \/* close namespace *\/\r\n","avg_line_length":25.9726027397,"max_line_length":108,"alphanum_fraction":0.6577004219,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":244,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"iArray.h\"\n#pragma once\n\/\/------------------------------------------------------------------------------\n\/**\n    @class Structures::Interfaces::iArray\n    @ingroup Interfaces\n    @brief interface for Procedural Memory inline Array\n*\/\n\n","avg_line_length":24.4,"max_line_length":80,"alphanum_fraction":0.4754098361,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":47453,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Copyright (c) 2016-2020 The PIVX developers\n\/\/ Copyright (c) 2021- The UNO developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"txmempool.h\"\n\n#include \"clientversion.h\"\n#include \"policy\/fees.h\"\n#include \"reverse_iterate.h\"\n#include \"streams.h\"\n#include \"timedata.h\"\n#include \"util.h\"\n#include \"utilmoneystr.h\"\n#include \"utiltime.h\"\n#include \"version.h\"\n#include \"validation.h\"\n\n\n\nCTxMemPoolEntry::CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFee,\n                                 int64_t _nTime, double _entryPriority,\n                                 unsigned int _entryHeight, bool poolHasNoInputsOf, CAmount _inChainInputValue,\n                                 bool _spendsCoinbaseOrCoinstake, unsigned int _sigOps) :\n     tx(MakeTransactionRef(_tx)), nFee(_nFee), nTime(_nTime), entryPriority(_entryPriority), entryHeight(_entryHeight), hadNoDependencies(poolHasNoInputsOf), inChainInputValue(_inChainInputValue), spendsCoinbaseOrCoinstake(_spendsCoinbaseOrCoinstake), sigOpCount(_sigOps)\n{\n    nTxSize = ::GetSerializeSize(*_tx, SER_NETWORK, PROTOCOL_VERSION);\n    nModSize = _tx->CalculateModifiedSize(nTxSize);\n    nUsageSize = _tx->DynamicMemoryUsage();\n    hasZerocoins = _tx->ContainsZerocoins();\n    m_isShielded = _tx->IsShieldedTx();\n\n    nCountWithDescendants = 1;\n    nSizeWithDescendants = nTxSize;\n    nModFeesWithDescendants = nFee;\n    CAmount nValueIn = _tx->GetValueOut()+nFee;\n    assert(inChainInputValue <= nValueIn);\n\n    feeDelta = 0;\n\n    nCountWithAncestors = 1;\n    nSizeWithAncestors = nTxSize;\n    nModFeesWithAncestors = nFee;\n    nSigOpCountWithAncestors = sigOpCount;\n}\n\ndouble CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const\n{\n    double deltaPriority = ((double)(currentHeight - entryHeight) * inChainInputValue) \/ nModSize;\n    double dResult = entryPriority + deltaPriority;\n    if (dResult < 0) \/\/ This should only happen if it was called with a height below entry height\n        dResult = 0;\n    return dResult;\n}\n\nvoid CTxMemPoolEntry::UpdateFeeDelta(int64_t newFeeDelta)\n{\n    nModFeesWithDescendants += newFeeDelta - feeDelta;\n    nModFeesWithAncestors += newFeeDelta - feeDelta;\n    feeDelta = newFeeDelta;\n}\n\n\/\/ Update the given tx for any in-mempool descendants.\n\/\/ Assumes that setMemPoolChildren is correct for the given tx and all\n\/\/ descendants.\nvoid CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set<uint256> &setExclude)\n{\n    setEntries stageEntries, setAllDescendants;\n    stageEntries = GetMemPoolChildren(updateIt);\n\n    while (!stageEntries.empty()) {\n        const txiter cit = *stageEntries.begin();\n        setAllDescendants.insert(cit);\n        stageEntries.erase(cit);\n        const setEntries &setChildren = GetMemPoolChildren(cit);\n        for (const txiter& childEntry : setChildren) {\n            cacheMap::iterator cacheIt = cachedDescendants.find(childEntry);\n            if (cacheIt != cachedDescendants.end()) {\n                \/\/ We've already calculated this one, just add the entries for this set\n                \/\/ but don't traverse again.\n                for (const txiter& cacheEntry : cacheIt->second) {\n                    setAllDescendants.insert(cacheEntry);\n                }\n            } else if (!setAllDescendants.count(childEntry)) {\n                \/\/ Schedule for later processing\n                stageEntries.insert(childEntry);\n            }\n        }\n    }\n    \/\/ setAllDescendants now contains all in-mempool descendants of updateIt.\n    \/\/ Update and add to cached descendant map\n    int64_t modifySize = 0;\n    CAmount modifyFee = 0;\n    int64_t modifyCount = 0;\n    for (const txiter& cit : setAllDescendants) {\n        if (!setExclude.count(cit->GetTx().GetHash())) {\n            modifySize += cit->GetTxSize();\n            modifyFee += cit->GetModifiedFee();\n            modifyCount++;\n            cachedDescendants[updateIt].insert(cit);\n            \/\/ Update ancestor state for each descendant\n            mapTx.modify(cit, update_ancestor_state(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCount()));\n        }\n    }\n    mapTx.modify(updateIt, update_descendant_state(modifySize, modifyFee, modifyCount));\n}\n\n\/\/ vHashesToUpdate is the set of transaction hashes from a disconnected block\n\/\/ which has been re-added to the mempool.\n\/\/ for each entry, look for descendants that are outside hashesToUpdate, and\n\/\/ add fee\/size information for such descendants to the parent.\n\/\/ for each such descendant, also update the ancestor state to include the parent.\nvoid CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate)\n{\n    LOCK(cs);\n    \/\/ For each entry in vHashesToUpdate, store the set of in-mempool, but not\n    \/\/ in-vHashesToUpdate transactions, so that we don't have to recalculate\n    \/\/ descendants when we come across a previously seen entry.\n    cacheMap mapMemPoolDescendantsToUpdate;\n\n    \/\/ Use a set for lookups into vHashesToUpdate (these entries are already\n    \/\/ accounted for in the state of their ancestors)\n    std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());\n\n    \/\/ Iterate in reverse, so that whenever we are looking at at a transaction\n    \/\/ we are sure that all in-mempool descendants have already been processed.\n    \/\/ This maximizes the benefit of the descendant cache and guarantees that\n    \/\/ setMemPoolChildren will be updated, an assumption made in\n    \/\/ UpdateForDescendants.\n    for (const uint256 &hash : reverse_iterate(vHashesToUpdate)) {\n        \/\/ we cache the in-mempool children to avoid duplicate updates\n        setEntries setChildren;\n        \/\/ calculate children from mapNextTx\n        txiter it = mapTx.find(hash);\n        if (it == mapTx.end()) {\n            continue;\n        }\n        auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));\n        \/\/ First calculate the children, and update setMemPoolChildren to\n        \/\/ include them, and update their setMemPoolParents to include this tx.\n        for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {\n            const uint256 &childHash = iter->second->GetHash();\n            txiter childIter = mapTx.find(childHash);\n            assert(childIter != mapTx.end());\n            \/\/ We can skip updating entries we've encountered before or that\n            \/\/ are in the block (which are already accounted for).\n            if (setChildren.insert(childIter).second && !setAlreadyIncluded.count(childHash)) {\n                UpdateChild(it, childIter, true);\n                UpdateParent(childIter, it, true);\n            }\n        }\n        UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded);\n    }\n}\n\nbool CTxMemPool::CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents \/* = true *\/) const\n{\n    setEntries parentHashes;\n    const auto &tx = entry.GetSharedTx();\n\n    if (fSearchForParents) {\n        \/\/ Get parents of this transaction that are in the mempool\n        \/\/ GetMemPoolParents() is only valid for entries in the mempool, so we\n        \/\/ iterate mapTx to find parents.\n        for (unsigned int i = 0; i < tx->vin.size(); i++) {\n            txiter piter = mapTx.find(tx->vin[i].prevout.hash);\n            if (piter != mapTx.end()) {\n                parentHashes.insert(piter);\n                if (parentHashes.size() + 1 > limitAncestorCount) {\n                    errString = strprintf(\"too many unconfirmed parents [limit: %u]\", limitAncestorCount);\n                    return false;\n                }\n            }\n        }\n    } else {\n        \/\/ If we're not searching for parents, we require this to be an\n        \/\/ entry in the mempool already.\n        txiter it = mapTx.iterator_to(entry);\n        parentHashes = GetMemPoolParents(it);\n    }\n\n    size_t totalSizeWithAncestors = entry.GetTxSize();\n\n    while (!parentHashes.empty()) {\n        txiter stageit = *parentHashes.begin();\n\n        setAncestors.insert(stageit);\n        parentHashes.erase(stageit);\n        totalSizeWithAncestors += stageit->GetTxSize();\n\n        if (stageit->GetSizeWithDescendants() + entry.GetTxSize() > limitDescendantSize) {\n            errString = strprintf(\"exceeds descendant size limit for tx %s [limit: %u]\", stageit->GetTx().GetHash().ToString(), limitDescendantSize);\n            return false;\n        } else if (stageit->GetCountWithDescendants() + 1 > limitDescendantCount) {\n            errString = strprintf(\"too many descendants for tx %s [limit: %u]\", stageit->GetTx().GetHash().ToString(), limitDescendantCount);\n            return false;\n        } else if (totalSizeWithAncestors > limitAncestorSize) {\n            errString = strprintf(\"exceeds ancestor size limit [limit: %u]\", limitAncestorSize);\n            return false;\n        }\n\n        const setEntries & setMemPoolParents = GetMemPoolParents(stageit);\n        for (const txiter& phash : setMemPoolParents) {\n            \/\/ If this is a new ancestor, add it.\n            if (setAncestors.count(phash) == 0) {\n                parentHashes.insert(phash);\n            }\n            if (parentHashes.size() + setAncestors.size() + 1 > limitAncestorCount) {\n                errString = strprintf(\"too many unconfirmed ancestors [limit: %u]\", limitAncestorCount);\n                return false;\n            }\n        }\n    }\n\n    return true;\n}\n\nvoid CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)\n{\n    setEntries parentIters = GetMemPoolParents(it);\n    \/\/ add or remove this tx as a child of each parent\n    for (const txiter& piter : parentIters) {\n        UpdateChild(piter, it, add);\n    }\n    const int64_t updateCount = (add ? 1 : -1);\n    const int64_t updateSize = updateCount * it->GetTxSize();\n    const CAmount updateFee = updateCount * it->GetModifiedFee();\n    for (const txiter& ancestorIt : setAncestors) {\n        mapTx.modify(ancestorIt, update_descendant_state(updateSize, updateFee, updateCount));\n    }\n}\n\nvoid CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)\n{\n    int64_t updateCount = setAncestors.size();\n    int64_t updateSize = 0;\n    CAmount updateFee = 0;\n    int updateSigOps = 0;\n    for (const txiter& ancestorIt : setAncestors) {\n        updateSize += ancestorIt->GetTxSize();\n        updateFee += ancestorIt->GetModifiedFee();\n        updateSigOps += ancestorIt->GetSigOpCount();\n    }\n    mapTx.modify(it, update_ancestor_state(updateSize, updateFee, updateCount, updateSigOps));\n}\n\nvoid CTxMemPool::UpdateChildrenForRemoval(txiter it)\n{\n    const setEntries &setMemPoolChildren = GetMemPoolChildren(it);\n    for (const txiter& updateIt : setMemPoolChildren) {\n        UpdateParent(updateIt, it, false);\n    }\n}\n\nvoid CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)\n{\n    \/\/ For each entry, walk back all ancestors and decrement size associated with this\n    \/\/ transaction\n    const uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();\n    if (updateDescendants) {\n        \/\/ updateDescendants should be true whenever we're not recursively\n        \/\/ removing a tx and all its descendants, eg when a transaction is\n        \/\/ confirmed in a block.\n        \/\/ Here we only update statistics and not data in mapLinks (which\n        \/\/ we need to preserve until we're finished with all operations that\n        \/\/ need to traverse the mempool).\n        for (const txiter& removeIt : entriesToRemove) {\n            setEntries setDescendants;\n            CalculateDescendants(removeIt, setDescendants);\n            setDescendants.erase(removeIt); \/\/ don't update state for self\n            int64_t modifySize = -((int64_t)removeIt->GetTxSize());\n            CAmount modifyFee = -removeIt->GetModifiedFee();\n            int modifySigOps = -removeIt->GetSigOpCount();\n            for (const txiter& dit : setDescendants) {\n                mapTx.modify(dit, update_ancestor_state(modifySize, modifyFee, -1, modifySigOps));\n            }\n        }\n    }\n    for (const txiter& removeIt : entriesToRemove) {\n        setEntries setAncestors;\n        const CTxMemPoolEntry &entry = *removeIt;\n        std::string dummy;\n        \/\/ Since this is a tx that is already in the mempool, we can call CMPA\n        \/\/ with fSearchForParents = false.  If the mempool is in a consistent\n        \/\/ state, then using true or false should both be correct, though false\n        \/\/ should be a bit faster.\n        \/\/ However, if we happen to be in the middle of processing a reorg, then\n        \/\/ the mempool can be in an inconsistent state.  In this case, the set\n        \/\/ of ancestors reachable via mapLinks will be the same as the set of\n        \/\/ ancestors whose packages include this transaction, because when we\n        \/\/ add a new transaction to the mempool in addUnchecked(), we assume it\n        \/\/ has no children, and in the case of a reorg where that assumption is\n        \/\/ false, the in-mempool children aren't linked to the in-block tx's\n        \/\/ until UpdateTransactionsFromBlock() is called.\n        \/\/ So if we're being called during a reorg, ie before\n        \/\/ UpdateTransactionsFromBlock() has been called, then mapLinks[] will\n        \/\/ differ from the set of mempool parents we'd calculate by searching,\n        \/\/ and it's important that we use the mapLinks[] notion of ancestor\n        \/\/ transactions as the set of things to update for removal.\n        CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);\n        \/\/ Note that UpdateAncestorsOf severs the child links that point to\n        \/\/ removeIt in the entries for the parents of removeIt.\n        UpdateAncestorsOf(false, removeIt, setAncestors);\n    }\n    \/\/ After updating all the ancestor sizes, we can now sever the link between each\n    \/\/ transaction being removed and any mempool children (ie, update setMemPoolParents\n    \/\/ for each direct child of a transaction being removed).\n    for (const txiter& removeIt : entriesToRemove) {\n        UpdateChildrenForRemoval(removeIt);\n    }\n}\n\nvoid CTxMemPoolEntry::UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)\n{\n    nSizeWithDescendants += modifySize;\n    assert(int64_t(nSizeWithDescendants) > 0);\n    nModFeesWithDescendants += modifyFee;\n    nCountWithDescendants += modifyCount;\n    assert(int64_t(nCountWithDescendants) > 0);\n}\n\nvoid CTxMemPoolEntry::UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int modifySigOps)\n{\n    nSizeWithAncestors += modifySize;\n    assert(int64_t(nSizeWithAncestors) > 0);\n    nModFeesWithAncestors += modifyFee;\n    nCountWithAncestors += modifyCount;\n    assert(int64_t(nCountWithAncestors) > 0);\n    nSigOpCountWithAncestors += modifySigOps;\n    assert(int(nSigOpCountWithAncestors) >= 0);\n}\n\nCTxMemPool::CTxMemPool(const CFeeRate& _minReasonableRelayFee) :\n        nTransactionsUpdated(0)\n{\n    _clear();   \/\/ lock-free clear\n\n    \/\/ Sanity checks off by default for performance, because otherwise\n    \/\/ accepting transactions becomes O(N^2) where N is the number\n    \/\/ of transactions in the pool\n    nCheckFrequency = 0;\n\n    minerPolicyEstimator = new CBlockPolicyEstimator(_minReasonableRelayFee);\n    minReasonableRelayFee = _minReasonableRelayFee;\n}\n\nCTxMemPool::~CTxMemPool()\n{\n    delete minerPolicyEstimator;\n}\n\nbool CTxMemPool::isSpent(const COutPoint& outpoint)\n{\n    LOCK(cs);\n    return mapNextTx.count(outpoint);\n}\n\nunsigned int CTxMemPool::GetTransactionsUpdated() const\n{\n    LOCK(cs);\n    return nTransactionsUpdated;\n}\n\nvoid CTxMemPool::AddTransactionsUpdated(unsigned int n)\n{\n    LOCK(cs);\n    nTransactionsUpdated += n;\n}\n\nbool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool fCurrentEstimate)\n{\n    NotifyEntryAdded(entry.GetSharedTx());\n    \/\/ Add to memory pool without checking anything.\n    \/\/ Used by AcceptToMemoryPool(), which DOES do all the appropriate checks.\n    LOCK(cs);\n    indexed_transaction_set::iterator newit = mapTx.insert(entry).first;\n    mapLinks.insert(make_pair(newit, TxLinks()));\n\n    \/\/ Update transaction for any feeDelta created by PrioritiseTransaction\n    \/\/ TODO: refactor so that the fee delta is calculated before inserting\n    \/\/ into mapTx.\n    std::map<uint256, std::pair<double, CAmount> >::const_iterator pos = mapDeltas.find(hash);\n    if (pos != mapDeltas.end()) {\n        const std::pair<double, CAmount> &deltas = pos->second;\n        if (deltas.second) {\n            mapTx.modify(newit, update_fee_delta(deltas.second));\n        }\n    }\n\n    \/\/ Update cachedInnerUsage to include contained transaction's usage.\n    \/\/ (When we update the entry for in-mempool parents, memory usage will be\n    \/\/ further updated.)\n    cachedInnerUsage += entry.DynamicMemoryUsage();\n\n    const CTransaction& tx = newit->GetTx();\n    std::set<uint256> setParentTransactions;\n    if(!tx.HasZerocoinSpendInputs()) {\n        for (unsigned int i = 0; i < tx.vin.size(); i++) {\n            mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, newit->GetSharedTx()));\n            setParentTransactions.insert(tx.vin[i].prevout.hash);\n        }\n    }\n    \/\/ Don't bother worrying about child transactions of this one.\n    \/\/ Normal case of a new transaction arriving is that there can't be any\n    \/\/ children, because such children would be orphans.\n    \/\/ An exception to that is if a transaction enters that used to be in a block.\n    \/\/ In that case, our disconnect block logic will call UpdateTransactionsFromBlock\n    \/\/ to clean up the mess we're leaving here.\n\n    \/\/ Update ancestors with information about this tx\n    for (const uint256& phash : setParentTransactions) {\n        txiter pit = mapTx.find(phash);\n        if (pit != mapTx.end()) {\n            UpdateParent(newit, pit, true);\n        }\n    }\n    UpdateAncestorsOf(true, newit, setAncestors);\n    UpdateEntryForAncestors(newit, setAncestors);\n\n    \/\/ Save spent nullifiers\n    if (tx.IsShieldedTx()) {\n        for (const SpendDescription& sd : tx.sapData->vShieldedSpend) {\n            mapSaplingNullifiers[sd.nullifier] = newit->GetSharedTx();\n        }\n    }\n\n    nTransactionsUpdated++;\n    totalTxSize += entry.GetTxSize();\n    minerPolicyEstimator->processTransaction(entry, fCurrentEstimate);\n\n    return true;\n}\n\nvoid CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)\n{\n    NotifyEntryRemoved(it->GetSharedTx(), reason);\n    AssertLockHeld(cs);\n    const CTransaction& tx = it->GetTx();\n    for (const CTxIn& txin : tx.vin)\n        mapNextTx.erase(txin.prevout);\n    \/\/ Remove spent nullifiers\n    if (tx.IsShieldedTx()) {\n        for (const SpendDescription& sd : tx.sapData->vShieldedSpend) {\n            mapSaplingNullifiers.erase(sd.nullifier);\n        }\n    }\n    totalTxSize -= it->GetTxSize();\n    cachedInnerUsage -= it->DynamicMemoryUsage();\n    cachedInnerUsage -= memusage::DynamicUsage(mapLinks[it].parents) + memusage::DynamicUsage(mapLinks[it].children);\n    mapLinks.erase(it);\n    mapTx.erase(it);\n    nTransactionsUpdated++;\n    minerPolicyEstimator->removeTx(tx.GetHash());\n}\n\n\/\/ Calculates descendants of entry that are not already in setDescendants, and adds to\n\/\/ setDescendants. Assumes entryit is already a tx in the mempool and setMemPoolChildren\n\/\/ is correct for tx and all descendants.\n\/\/ Also assumes that if an entry is in setDescendants already, then all\n\/\/ in-mempool descendants of it are already in setDescendants as well, so that we\n\/\/ can save time by not iterating over those entries.\nvoid CTxMemPool::CalculateDescendants(txiter entryit, setEntries &setDescendants)\n{\n    setEntries stage;\n    if (setDescendants.count(entryit) == 0) {\n        stage.insert(entryit);\n    }\n    \/\/ Traverse down the children of entry, only adding children that are not\n    \/\/ accounted for in setDescendants already (because those children have either\n    \/\/ already been walked, or will be walked in this iteration).\n    while (!stage.empty()) {\n        txiter it = *stage.begin();\n        setDescendants.insert(it);\n        stage.erase(it);\n\n        const setEntries &setChildren = GetMemPoolChildren(it);\n        for (const txiter& childiter : setChildren) {\n            if (!setDescendants.count(childiter)) {\n                stage.insert(childiter);\n            }\n        }\n    }\n}\n\nvoid CTxMemPool::removeRecursive(const CTransaction& origTx, MemPoolRemovalReason reason)\n{\n    \/\/ Remove transaction from memory pool\n    {\n        LOCK(cs);\n        setEntries txToRemove;\n        txiter origit = mapTx.find(origTx.GetHash());\n        if (origit != mapTx.end()) {\n            txToRemove.insert(origit);\n        } else {\n            \/\/ When recursively removing but origTx isn't in the mempool\n            \/\/ be sure to remove any children that are in the pool. This can\n            \/\/ happen during chain re-orgs if origTx isn't re-accepted into\n            \/\/ the mempool for any reason.\n            for (unsigned int i = 0; i < origTx.vout.size(); i++) {\n                auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));\n                if (it == mapNextTx.end())\n                    continue;\n                txiter nextit = mapTx.find(it->second->GetHash());\n                assert(nextit != mapTx.end());\n                txToRemove.insert(nextit);\n            }\n        }\n        setEntries setAllRemoves;\n        for (const txiter& it : txToRemove) {\n            CalculateDescendants(it, setAllRemoves);\n        }\n\n        RemoveStaged(setAllRemoves, false, reason);\n    }\n}\n\nvoid CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)\n{\n    AssertLockHeld(cs_main);\n    \/\/ Remove transactions spending a coinbase which are now immature and no-longer-final transactions\n    LOCK(cs);\n    setEntries txToRemove;\n    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {\n        const CTransactionRef& tx = it->GetSharedTx();\n        if (!CheckFinalTx(tx, flags)) {\n            txToRemove.insert(it);\n        } else if (it->GetSpendsCoinbaseOrCoinstake()) {\n            for (const CTxIn& txin : tx->vin) {\n                indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);\n                if (it2 != mapTx.end())\n                    continue;\n                const Coin &coin = pcoins->AccessCoin(txin.prevout);\n                if (nCheckFrequency != 0) assert(!coin.IsSpent());\n                if (coin.IsSpent() || ((coin.IsCoinBase() || coin.IsCoinStake()) && ((signed long)nMemPoolHeight) - coin.nHeight < Params().GetConsensus().nCoinbaseMaturity)) {\n                    txToRemove.insert(it);\n                    break;\n                }\n            }\n        }\n    }\n    setEntries setAllRemoves;\n    for (txiter it : txToRemove) {\n        CalculateDescendants(it, setAllRemoves);\n    }\n    RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);\n}\n\nvoid CTxMemPool::removeWithAnchor(const uint256& invalidRoot)\n{\n\n    \/\/ If a block is disconnected from the tip, and the root changed,\n    \/\/ we must invalidate transactions from the mempool which spend\n    \/\/ from that root -- almost as though they were spending coinbases\n    \/\/ which are no longer valid to spend due to coinbase maturity.\n    LOCK(cs);\n    std::list<CTransaction> transactionsToRemove;\n    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {\n        const CTransaction& tx = it->GetTx();\n        if (!tx.IsShieldedTx()) continue;\n        for (const auto& sd : tx.sapData->vShieldedSpend) {\n            if (sd.anchor == invalidRoot) {\n                transactionsToRemove.emplace_back(tx);\n                break;\n            }\n        }\n    }\n    for (const CTransaction& tx : transactionsToRemove) {\n        removeRecursive(tx);\n    }\n}\n\nvoid CTxMemPool::removeConflicts(const CTransaction& tx)\n{\n    \/\/ Remove transactions which depend on inputs of tx, recursively\n    std::list<CTransaction> result;\n    LOCK(cs);\n    for (const CTxIn& txin : tx.vin) {\n        auto it = mapNextTx.find(txin.prevout);\n        if (it != mapNextTx.end()) {\n            const CTransaction& txConflict = *it->second;\n            if (txConflict != tx) {\n                removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT);\n                ClearPrioritisation(txConflict.GetHash());\n            }\n        }\n    }\n    \/\/ Remove txes with conflicting nullifier\n    if (tx.IsShieldedTx()) {\n        for (const SpendDescription& sd : tx.sapData->vShieldedSpend) {\n            const auto& it = mapSaplingNullifiers.find(sd.nullifier);\n            if (it != mapSaplingNullifiers.end()) {\n                const CTransaction& txConflict = *it->second;\n                if (txConflict != tx) {\n                    removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT);\n                    ClearPrioritisation(txConflict.GetHash());\n                }\n            }\n        }\n    }\n}\n\n\/**\n * Called when a block is connected. Removes from mempool and updates the miner fee estimator.\n *\/\nvoid CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight,\n                                bool fCurrentEstimate)\n{\n    LOCK(cs);\n    std::vector<CTxMemPoolEntry> entries;\n    for (const auto& tx : vtx) {\n        uint256 hash = tx->GetHash();\n        indexed_transaction_set::iterator i = mapTx.find(hash);\n        if (i != mapTx.end())\n            entries.push_back(*i);\n    }\n    for (const auto& tx : vtx) {\n        txiter it = mapTx.find(tx->GetHash());\n        if (it != mapTx.end()) {\n            setEntries stage;\n            stage.insert(it);\n            RemoveStaged(stage, true, MemPoolRemovalReason::BLOCK);\n        }\n        removeConflicts(*tx);\n        ClearPrioritisation(tx->GetHash());\n    }\n    \/\/ After the txs in the new block have been removed from the mempool, update policy estimates\n    minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);\n    lastRollingFeeUpdate = GetTime();\n    blockSinceLastRollingFeeBump = true;\n}\n\n\nvoid CTxMemPool::_clear()\n{\n    mapLinks.clear();\n    mapTx.clear();\n    mapNextTx.clear();\n    totalTxSize = 0;\n    cachedInnerUsage = 0;\n    lastRollingFeeUpdate = GetTime();\n    blockSinceLastRollingFeeBump = false;\n    rollingMinimumFeeRate = 0;\n    ++nTransactionsUpdated;\n}\n\nvoid CTxMemPool::clear()\n{\n    LOCK(cs);\n    _clear();\n}\n\nvoid CTxMemPool::check(const CCoinsViewCache* pcoins) const\n{\n    if (nCheckFrequency == 0)\n        return;\n\n    if (GetRand(std::numeric_limits<uint32_t>::max()) >= nCheckFrequency)\n        return;\n\n    LogPrint(BCLog::MEMPOOL, \"Checking mempool with %u transactions and %u inputs\\n\", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());\n\n    uint64_t checkTotal = 0;\n    uint64_t innerUsage = 0;\n\n    CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));\n\n    LOCK(cs);\n    std::list<const CTxMemPoolEntry*> waitingOnDependants;\n    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {\n        unsigned int i = 0;\n        checkTotal += it->GetTxSize();\n        innerUsage += it->DynamicMemoryUsage();\n        const CTransaction& tx = it->GetTx();\n        txlinksMap::const_iterator linksiter = mapLinks.find(it);\n        assert(linksiter != mapLinks.end());\n        const TxLinks &links = linksiter->second;\n        innerUsage += memusage::DynamicUsage(links.parents) + memusage::DynamicUsage(links.children);\n        bool fDependsWait = false;\n        setEntries setParentCheck;\n        int64_t parentSizes = 0;\n        unsigned int parentSigOpCount = 0;\n        bool fHasZerocoinSpends = false;\n        for (const CTxIn& txin : tx.vin) {\n            \/\/ Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.\n            indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);\n            if (it2 != mapTx.end()) {\n                const CTransaction& tx2 = it2->GetTx();\n                assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());\n                fDependsWait = true;\n                if (setParentCheck.insert(it2).second) {\n                    parentSizes += it2->GetTxSize();\n                    parentSigOpCount += it2->GetSigOpCount();\n                }\n            } else if(!txin.IsZerocoinSpend() && !txin.IsZerocoinPublicSpend()) {\n                assert(pcoins->HaveCoin(txin.prevout));\n            } else {\n                fHasZerocoinSpends = true;\n            }\n            \/\/ Check whether its inputs are marked in mapNextTx.\n            if(!fHasZerocoinSpends) {\n                auto it3 = mapNextTx.find(txin.prevout);\n                assert(it3 != mapNextTx.end());\n                assert(it3->first == &txin.prevout);\n                assert(*it3->second == tx);\n            } else {\n                fDependsWait=false;\n            }\n            i++;\n        }\n        \/\/ sapling txes\n        if (tx.IsShieldedTx()) {\n            for (const SpendDescription& sd : tx.sapData->vShieldedSpend) {\n                SaplingMerkleTree tree;\n                assert(pcoins->GetSaplingAnchorAt(sd.anchor, tree));\n                assert(!pcoins->GetNullifier(sd.nullifier));\n            }\n        }\n        assert(setParentCheck == GetMemPoolParents(it));\n        \/\/ Verify ancestor state is correct.\n        setEntries setAncestors;\n        uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();\n        std::string dummy;\n        CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);\n        uint64_t nCountCheck = setAncestors.size() + 1;\n        uint64_t nSizeCheck = it->GetTxSize();\n        CAmount nFeesCheck = it->GetModifiedFee();\n        unsigned int nSigOpCheck = it->GetSigOpCount();\n\n        for (const txiter& ancestorIt : setAncestors) {\n            nSizeCheck += ancestorIt->GetTxSize();\n            nFeesCheck += ancestorIt->GetModifiedFee();\n            nSigOpCheck += ancestorIt->GetSigOpCount();\n        }\n\n        assert(it->GetCountWithAncestors() == nCountCheck);\n        assert(it->GetSizeWithAncestors() == nSizeCheck);\n        assert(it->GetSigOpCountWithAncestors() == nSigOpCheck);\n        assert(it->GetModFeesWithAncestors() == nFeesCheck);\n\n        \/\/ Check children against mapNextTx\n        if (!fHasZerocoinSpends) {\n            CTxMemPool::setEntries setChildrenCheck;\n            auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));\n            int64_t childSizes = 0;\n            for (; iter != mapNextTx.end() && iter->first->hash == tx.GetHash(); ++iter) {\n                txiter childit = mapTx.find(iter->second->GetHash());\n                assert(childit != mapTx.end()); \/\/ mapNextTx points to in-mempool transactions\n                if (setChildrenCheck.insert(childit).second) {\n                    childSizes += childit->GetTxSize();\n                }\n            }\n            assert(setChildrenCheck == GetMemPoolChildren(it));\n            \/\/ Also check to make sure size is greater than sum with immediate children.\n            \/\/ just a sanity check, not definitive that this calc is correct...\n            assert(it->GetSizeWithDescendants() >= childSizes + it->GetTxSize());\n        }\n\n        if (fDependsWait)\n            waitingOnDependants.push_back(&(*it));\n        else {\n            CValidationState state;\n            PrecomputedTransactionData precomTxData(tx);\n            assert(CheckInputs(tx, state, mempoolDuplicate, false, 0, false, precomTxData, NULL));\n            UpdateCoins(tx, mempoolDuplicate, 1000000);\n        }\n    }\n\n    unsigned int stepsSinceLastRemove = 0;\n    while (!waitingOnDependants.empty()) {\n        const CTxMemPoolEntry* entry = waitingOnDependants.front();\n        waitingOnDependants.pop_front();\n        CValidationState state;\n        if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {\n            waitingOnDependants.push_back(entry);\n            stepsSinceLastRemove++;\n            assert(stepsSinceLastRemove < waitingOnDependants.size());\n        } else {\n            PrecomputedTransactionData precomTxData(entry->GetTx());\n            assert(CheckInputs(entry->GetTx(), state, mempoolDuplicate, false, 0, false, precomTxData, NULL));\n            UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);\n            stepsSinceLastRemove = 0;\n        }\n    }\n    for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {\n        const uint256& hash = it->second->GetHash();\n        indexed_transaction_set::const_iterator it2 = mapTx.find(hash);\n        const CTransactionRef& tx = it2->GetSharedTx();\n        assert(it2 != mapTx.end());\n        assert(tx == it->second);\n    }\n\n    \/\/ Consistency check for sapling nullifiers\n    checkNullifiers();\n\n    assert(totalTxSize == checkTotal);\n    assert(innerUsage == cachedInnerUsage);\n}\n\nvoid CTxMemPool::checkNullifiers() const\n{\n    for (const auto& it : mapSaplingNullifiers) {\n        const uint256& hash = it.second->GetHash();\n        const auto& findTx = mapTx.find(hash);\n        assert(findTx != mapTx.end());\n        const CTransactionRef& tx = findTx->GetSharedTx();\n        assert(*tx == *it.second);\n    }\n}\n\nbool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb)\n{\n    LOCK(cs);\n    indexed_transaction_set::const_iterator i = mapTx.find(hasha);\n    if (i == mapTx.end()) return false;\n    indexed_transaction_set::const_iterator j = mapTx.find(hashb);\n    if (j == mapTx.end()) return true;\n    uint64_t counta = i->GetCountWithAncestors();\n    uint64_t countb = j->GetCountWithAncestors();\n    if (counta == countb) {\n        return CompareTxMemPoolEntryByScore()(*i, *j);\n    }\n    return counta < countb;\n}\n\nnamespace {\n    class DepthAndScoreComparator\n    {\n    public:\n        bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b) const\n        {\n            uint64_t counta = a->GetCountWithAncestors();\n            uint64_t countb = b->GetCountWithAncestors();\n            if (counta == countb) {\n                return CompareTxMemPoolEntryByScore()(*a, *b);\n            }\n            return counta < countb;\n        }\n    };\n}\n\nstd::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const\n{\n    std::vector<indexed_transaction_set::const_iterator> iters;\n    AssertLockHeld(cs);\n\n    iters.reserve(mapTx.size());\n\n    for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {\n        iters.push_back(mi);\n    }\n    std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());\n    return iters;\n}\n\nvoid CTxMemPool::queryHashes(std::vector<uint256>& vtxid)\n{\n    LOCK(cs);\n    auto iters = GetSortedDepthAndScore();\n\n    vtxid.clear();\n    vtxid.reserve(mapTx.size());\n\n    for (auto it : iters) {\n        vtxid.emplace_back(it->GetTx().GetHash());\n    }\n}\n\nstatic TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {\n    return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), CFeeRate(it->GetFee(), it->GetTxSize()), it->GetModifiedFee() - it->GetFee()};\n}\n\nstd::vector<TxMempoolInfo> CTxMemPool::infoAll() const\n{\n    LOCK(cs);\n    auto iters = GetSortedDepthAndScore();\n\n    std::vector<TxMempoolInfo> ret;\n    ret.reserve(mapTx.size());\n    for (auto it : iters) {\n        ret.emplace_back(GetInfo(it));\n    }\n\n    return ret;\n}\n\nvoid CTxMemPool::getTransactions(std::set<uint256>& setTxid)\n{\n    setTxid.clear();\n\n    LOCK(cs);\n    for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)\n        setTxid.insert(mi->GetTx().GetHash());\n}\n\nstd::shared_ptr<const CTransaction> CTxMemPool::get(const uint256& hash) const\n{\n    LOCK(cs);\n    indexed_transaction_set::const_iterator i = mapTx.find(hash);\n    if (i == mapTx.end())\n        return nullptr;\n    return i->GetSharedTx();\n}\n\nTxMempoolInfo CTxMemPool::info(const uint256& hash) const\n{\n    LOCK(cs);\n    indexed_transaction_set::const_iterator i = mapTx.find(hash);\n    if (i == mapTx.end())\n        return TxMempoolInfo();\n    return GetInfo(i);\n}\n\nCFeeRate CTxMemPool::estimateFee(int nBlocks) const\n{\n    LOCK(cs);\n    return minerPolicyEstimator->estimateFee(nBlocks);\n}\nCFeeRate CTxMemPool::estimateSmartFee(int nBlocks, int *answerFoundAtBlocks) const\n{\n    LOCK(cs);\n    return minerPolicyEstimator->estimateSmartFee(nBlocks, answerFoundAtBlocks, *this);\n}\ndouble CTxMemPool::estimatePriority(int nBlocks) const\n{\n    LOCK(cs);\n    return minerPolicyEstimator->estimatePriority(nBlocks);\n}\ndouble CTxMemPool::estimateSmartPriority(int nBlocks, int *answerFoundAtBlocks) const\n{\n    LOCK(cs);\n    return minerPolicyEstimator->estimateSmartPriority(nBlocks, answerFoundAtBlocks, *this);\n}\n\nbool CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const\n{\n    try {\n        LOCK(cs);\n        fileout << 4029900;         \/\/ version required to read: 4.2.99\n        fileout << CLIENT_VERSION;  \/\/ version that wrote the file\n        minerPolicyEstimator->Write(fileout);\n    } catch (const std::exception&) {\n        LogPrintf(\"CTxMemPool::WriteFeeEstimates() : unable to write policy estimator data (non-fatal)\");\n        return false;\n    }\n    return true;\n}\n\nbool CTxMemPool::ReadFeeEstimates(CAutoFile& filein)\n{\n    try {\n        int nVersionRequired, nVersionThatWrote;\n        filein >> nVersionRequired >> nVersionThatWrote;\n        if (nVersionRequired > CLIENT_VERSION)\n            return error(\"CTxMemPool::ReadFeeEstimates() : up-version (%d) fee estimate file\", nVersionRequired);\n\n        LOCK(cs);\n        minerPolicyEstimator->Read(filein, nVersionThatWrote);\n    } catch (const std::exception&) {\n        LogPrintf(\"CTxMemPool::ReadFeeEstimates() : unable to read policy estimator data (non-fatal)\");\n        return false;\n    }\n    return true;\n}\n\nvoid CTxMemPool::PrioritiseTransaction(const uint256 hash, const std::string strHash, double dPriorityDelta, const CAmount& nFeeDelta)\n{\n    {\n        LOCK(cs);\n        std::pair<double, CAmount>& deltas = mapDeltas[hash];\n        deltas.first += dPriorityDelta;\n        deltas.second += nFeeDelta;\n        txiter it = mapTx.find(hash);\n        if (it != mapTx.end()) {\n            mapTx.modify(it, update_fee_delta(deltas.second));\n            \/\/ Now update all ancestors' modified fees with descendants\n            setEntries setAncestors;\n            uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();\n            std::string dummy;\n            CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);\n            for (const txiter& ancestorIt : setAncestors) {\n                mapTx.modify(ancestorIt, update_descendant_state(0, nFeeDelta, 0));\n            }\n        }\n    }\n    LogPrintf(\"PrioritiseTransaction: %s priority += %f, fee += %d\\n\", strHash, dPriorityDelta, FormatMoney(nFeeDelta));\n}\n\nvoid CTxMemPool::ApplyDeltas(const uint256 hash, double& dPriorityDelta, CAmount& nFeeDelta) const\n{\n    LOCK(cs);\n    std::map<uint256, std::pair<double, CAmount> >::const_iterator pos = mapDeltas.find(hash);\n    if (pos == mapDeltas.end())\n        return;\n    const std::pair<double, CAmount>& deltas = pos->second;\n    dPriorityDelta += deltas.first;\n    nFeeDelta += deltas.second;\n}\n\nvoid CTxMemPool::ClearPrioritisation(const uint256 hash)\n{\n    LOCK(cs);\n    mapDeltas.erase(hash);\n}\n\nbool CTxMemPool::nullifierExists(const uint256& nullifier) const\n{\n    LOCK(cs);\n    return mapSaplingNullifiers.count(nullifier);\n}\n\nbool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const\n{\n    if (tx.HasZerocoinSpendInputs())\n        return true;\n    for (unsigned int i = 0; i < tx.vin.size(); i++)\n        if (exists(tx.vin[i].prevout.hash))\n            return false;\n    return true;\n}\n\n\nCCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) {}\n\nbool CCoinsViewMemPool::GetCoin(const COutPoint& outpoint, Coin& coin) const\n{\n    \/\/ If an entry in the mempool exists, always return that one, as it's guaranteed to never\n    \/\/ conflict with the underlying cache, and it cannot have pruned entries (as it contains full)\n    \/\/ transactions. First checking the underlying cache risks returning a pruned entry instead.\n    CTransactionRef ptx = mempool.get(outpoint.hash);\n    if (ptx) {\n        if (outpoint.n < ptx->vout.size()) {\n            coin = Coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false, false);\n            return true;\n        } else {\n            return false;\n        }\n    }\n    return (base->GetCoin(outpoint, coin) && !coin.IsSpent());\n}\n\nbool CCoinsViewMemPool::HaveCoin(const COutPoint& outpoint) const\n{\n    return mempool.exists(outpoint) || base->HaveCoin(outpoint);\n}\n\nbool CCoinsViewMemPool::GetNullifier(const uint256& nullifier) const\n{\n    return mempool.nullifierExists(nullifier) || base->GetNullifier(nullifier);\n}\n\nsize_t CTxMemPool::DynamicMemoryUsage() const\n{\n    LOCK(cs);\n    \/\/ Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for\n    \/\/ boost::multi_index_contained is implemented.\n    return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() +\n            memusage::DynamicUsage(mapNextTx) +\n            memusage::DynamicUsage(mapDeltas) +\n            memusage::DynamicUsage(mapLinks) +\n            cachedInnerUsage +\n            memusage::DynamicUsage(mapSaplingNullifiers);\n}\n\nvoid CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason)\n{\n    AssertLockHeld(cs);\n    UpdateForRemoveFromMempool(stage, updateDescendants);\n    for (const txiter& it : stage) {\n        removeUnchecked(it, reason);\n    }\n}\n\nint CTxMemPool::Expire(int64_t time)\n{\n    LOCK(cs);\n    indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();\n    setEntries toremove;\n    while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {\n        toremove.insert(mapTx.project<0>(it));\n        it++;\n    }\n    setEntries stage;\n    for (const txiter& removeit : toremove) {\n        CalculateDescendants(removeit, stage);\n    }\n    RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);\n    return stage.size();\n}\n\nbool CTxMemPool::addUnchecked(const uint256&hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate)\n{\n    LOCK(cs);\n    setEntries setAncestors;\n    uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();\n    std::string dummy;\n    CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);\n    return addUnchecked(hash, entry, setAncestors, fCurrentEstimate);\n}\n\nvoid CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)\n{\n    setEntries s;\n    if (add && mapLinks[entry].children.insert(child).second) {\n        cachedInnerUsage += memusage::IncrementalDynamicUsage(s);\n    } else if (!add && mapLinks[entry].children.erase(child)) {\n        cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);\n    }\n}\n\nvoid CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)\n{\n    setEntries s;\n    if (add && mapLinks[entry].parents.insert(parent).second) {\n        cachedInnerUsage += memusage::IncrementalDynamicUsage(s);\n    } else if (!add && mapLinks[entry].parents.erase(parent)) {\n        cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);\n    }\n}\n\nconst CTxMemPool::setEntries & CTxMemPool::GetMemPoolParents(txiter entry) const\n{\n    assert (entry != mapTx.end());\n    txlinksMap::const_iterator it = mapLinks.find(entry);\n    assert(it != mapLinks.end());\n    return it->second.parents;\n}\n\nconst CTxMemPool::setEntries & CTxMemPool::GetMemPoolChildren(txiter entry) const\n{\n    assert (entry != mapTx.end());\n    txlinksMap::const_iterator it = mapLinks.find(entry);\n    assert(it != mapLinks.end());\n    return it->second.children;\n}\n\nCFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const\n{\n    LOCK(cs);\n    if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)\n        return CFeeRate(rollingMinimumFeeRate);\n\n    int64_t time = GetTime();\n    if (time > lastRollingFeeUpdate + 10) {\n        double halflife = ROLLING_FEE_HALFLIFE;\n        if (DynamicMemoryUsage() < sizelimit \/ 4)\n            halflife \/= 4;\n        else if (DynamicMemoryUsage() < sizelimit \/ 2)\n            halflife \/= 2;\n\n        rollingMinimumFeeRate = rollingMinimumFeeRate \/ pow(2.0, (time - lastRollingFeeUpdate) \/ halflife);\n        lastRollingFeeUpdate = time;\n\n        if (rollingMinimumFeeRate < (double)minReasonableRelayFee.GetFeePerK() \/ 2) {\n            rollingMinimumFeeRate = 0;\n            return CFeeRate(0);\n        }\n    }\n    return std::max(CFeeRate(rollingMinimumFeeRate), minReasonableRelayFee);\n}\n\nvoid CTxMemPool::trackPackageRemoved(const CFeeRate& rate)\n{\n    AssertLockHeld(cs);\n    if (rate.GetFeePerK() > rollingMinimumFeeRate) {\n        rollingMinimumFeeRate = rate.GetFeePerK();\n        blockSinceLastRollingFeeBump = false;\n    }\n}\n\nvoid CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining)\n{\n    LOCK(cs);\n    unsigned nTxnRemoved = 0;\n    CFeeRate maxFeeRateRemoved(0);\n    while (DynamicMemoryUsage() > sizelimit) {\n        indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();\n\n        \/\/ We set the new mempool min fee to the feerate of the removed set, plus the\n        \/\/ \"minimum reasonable fee rate\" (ie some value under which we consider txn\n        \/\/ to have 0 fee). This way, we don't allow txn to enter mempool with feerate\n        \/\/ equal to txn which were removed with no block in between.\n        CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());\n        removed += minReasonableRelayFee;\n        trackPackageRemoved(removed);\n        maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);\n\n        setEntries stage;\n        CalculateDescendants(mapTx.project<0>(it), stage);\n        nTxnRemoved += stage.size();\n\n        std::vector<CTransaction> txn;\n        if (pvNoSpendsRemaining) {\n            txn.reserve(stage.size());\n            for (txiter it: stage)\n                txn.push_back(it->GetTx());\n        }\n        RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);\n        if (pvNoSpendsRemaining) {\n            for (const CTransaction& tx: txn) {\n                for (const CTxIn& txin: tx.vin) {\n                    if (exists(txin.prevout.hash)) continue;\n                    if (!mapNextTx.count(txin.prevout)) {\n                        pvNoSpendsRemaining->push_back(txin.prevout);\n                    }\n                }\n            }\n        }\n    }\n\n    if (maxFeeRateRemoved > CFeeRate(0))\n        LogPrint(BCLog::MEMPOOL, \"Removed %u txn, rolling minimum fee bumped to %s\\n\", nTxnRemoved, maxFeeRateRemoved.ToString());\n}\n\n\nbool CTxMemPool::IsLoaded() const\n{\n    LOCK(cs);\n    return m_is_loaded;\n}\n\nvoid CTxMemPool::SetIsLoaded(bool loaded)\n{\n    LOCK(cs);\n    m_is_loaded = loaded;\n}\n\n","avg_line_length":38.6110659072,"max_line_length":283,"alphanum_fraction":0.6545845363,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13801,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0","MIT"],"max_stars_count":11.0,"content":"\/*\n * Copyright (c) Contributors to the Open 3D Engine Project.\n * For complete copyright and license terms please see the LICENSE at the root of this distribution.\n *\n * SPDX-License-Identifier: Apache-2.0 OR MIT\n *\n *\/\n\n\/\/ include required headers\n#include \"MotionInstancePool.h\"\n#include \"MotionInstance.h\"\n#include <EMotionFX\/Source\/Allocators.h>\n#include <MCore\/Source\/LogManager.h>\n\n\nnamespace EMotionFX\n{\n    AZ_CLASS_ALLOCATOR_IMPL(MotionInstancePool, MotionAllocator, 0)\n\n\n    \/\/ constructor\n    MotionInstancePool::SubPool::SubPool()\n        : m_data(nullptr)\n        , m_numInstances(0)\n        , m_numInUse(0)\n    {\n    }\n\n\n    \/\/ destructor\n    MotionInstancePool::SubPool::~SubPool()\n    {\n        MCore::Free(m_data);\n        m_data = nullptr;\n    }\n\n\n    \/\/--------------------------------------------------------------------------------------------------\n    \/\/ class MotionInstancePool::Pool\n    \/\/--------------------------------------------------------------------------------------------------\n\n    \/\/ constructor\n    MotionInstancePool::Pool::Pool()\n    {\n        m_poolType           = POOLTYPE_DYNAMIC;\n        m_data               = nullptr;\n        m_numInstances       = 0;\n        m_numUsedInstances   = 0;\n        m_subPoolSize        = 0;\n    }\n\n\n    \/\/ destructor\n    MotionInstancePool::Pool::~Pool()\n    {\n        if (m_poolType == POOLTYPE_STATIC)\n        {\n            MCore::Free(m_data);\n            m_data = nullptr;\n            m_freeList.clear();\n        }\n        else\n        if (m_poolType == POOLTYPE_DYNAMIC)\n        {\n            MCORE_ASSERT(m_data == nullptr);\n\n            \/\/ delete all subpools\n            for (SubPool* subPool : m_subPools)\n            {\n                delete subPool;\n            }\n            m_subPools.clear();\n\n            m_freeList.clear();\n        }\n        else\n        {\n            MCORE_ASSERT(false);\n        }\n    }\n\n\n\n    \/\/--------------------------------------------------------------------------------------------------\n    \/\/ class MotionInstancePool\n    \/\/--------------------------------------------------------------------------------------------------\n\n    \/\/ constructor\n    MotionInstancePool::MotionInstancePool()\n        : BaseObject()\n    {\n        m_pool = nullptr;\n    }\n\n\n    \/\/ destructor\n    MotionInstancePool::~MotionInstancePool()\n    {\n        if (m_pool->m_numUsedInstances > 0)\n        {\n            MCore::LogError(\"EMotionFX::~MotionInstancePool() - There are still %d unfreed motion instances, please use the Free function in the MotionInstancePool to free them, just like you would delete the object.\", m_pool->m_numUsedInstances);\n        }\n\n        delete m_pool;\n    }\n\n\n    \/\/ create\n    MotionInstancePool* MotionInstancePool::Create()\n    {\n        return aznew MotionInstancePool();\n    }\n\n\n    \/\/ init the motion instance pool\n    void MotionInstancePool::Init(size_t numInitialInstances, EPoolType poolType, size_t subPoolSize)\n    {\n        if (m_pool)\n        {\n            MCore::LogError(\"EMotionFX::MotionInstancePool::Init() - We have already initialized the pool, ignoring new init call.\");\n            return;\n        }\n\n        \/\/ check if we use numInitialInstances==0 with a static pool, as that isn't allowed of course\n        if (poolType == POOLTYPE_STATIC && numInitialInstances == 0)\n        {\n            MCore::LogError(\"EMotionFX::MotionInstancePool::Init() - The number of initial motion instances cannot be 0 when using a static pool. Please set the dynamic parameter to true, or increase the value of numInitialInstances.\");\n            MCORE_ASSERT(false);\n            return;\n        }\n\n        \/\/ create the subpool\n        m_pool = new Pool();\n        m_pool->m_numInstances    = numInitialInstances;\n        m_pool->m_poolType        = poolType;\n        m_pool->m_subPoolSize     = subPoolSize;\n\n        \/\/ if we have a static pool\n        if (poolType == POOLTYPE_STATIC)\n        {\n            m_pool->m_data    = (uint8*)MCore::Allocate(numInitialInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);\/\/ alloc space\n            m_pool->m_freeList.resize_no_construct(numInitialInstances);\n            for (size_t i = 0; i < numInitialInstances; ++i)\n            {\n                void* memLocation = (void*)(m_pool->m_data + i * sizeof(MotionInstance));\n                m_pool->m_freeList[i].m_address = memLocation;\n                m_pool->m_freeList[i].m_subPool = nullptr;\n            }\n        }\n        else \/\/ if we have a dynamic pool\n        if (poolType == POOLTYPE_DYNAMIC)\n        {\n            m_pool->m_subPools.reserve(32);\n\n            SubPool* subPool = new SubPool();\n            subPool->m_data              = (uint8*)MCore::Allocate(numInitialInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);\/\/ alloc space\n            subPool->m_numInstances      = numInitialInstances;\n\n            m_pool->m_freeList.resize_no_construct(numInitialInstances);\n            for (size_t i = 0; i < numInitialInstances; ++i)\n            {\n                m_pool->m_freeList[i].m_address = (void*)(subPool->m_data + i * sizeof(MotionInstance));\n                m_pool->m_freeList[i].m_subPool = subPool;\n            }\n\n            m_pool->m_subPools.emplace_back(subPool);\n        }\n        else\n        {\n            MCORE_ASSERT(false); \/\/ unhandled pool type\n        }\n    }\n\n\n    \/\/ return a new motion instance\n    MotionInstance* MotionInstancePool::RequestNewWithoutLock(Motion* motion, ActorInstance* actorInstance)\n    {\n        \/\/ check if we already initialized\n        if (m_pool == nullptr)\n        {\n            MCore::LogWarning(\"EMotionFX::MotionInstancePool::RequestNew() - We have not yet initialized the pool, initializing it to a dynamic pool\");\n            Init();\n        }\n\n        \/\/ if there is are free items left\n        if (m_pool->m_freeList.size() > 0)\n        {\n            const MemLocation& location = m_pool->m_freeList.back();\n            MotionInstance* result = MotionInstance::Create(location.m_address, motion, actorInstance);\n\n            if (location.m_subPool)\n            {\n                location.m_subPool->m_numInUse++;\n            }\n            result->SetSubPool(location.m_subPool);\n\n            m_pool->m_freeList.pop_back(); \/\/ remove it from the free list\n            m_pool->m_numUsedInstances++;\n            return result;\n        }\n\n        \/\/ we have no more free attributes left\n        if (m_pool->m_poolType == POOLTYPE_DYNAMIC) \/\/ we're dynamic, so we can just create new ones\n        {\n            const size_t numInstances = m_pool->m_subPoolSize;\n            m_pool->m_numInstances += numInstances;\n\n            SubPool* subPool = new SubPool();\n            subPool->m_data              = (uint8*)MCore::Allocate(numInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);\/\/ alloc space\n            subPool->m_numInstances      = numInstances;\n\n            const size_t startIndex = m_pool->m_freeList.size();\n            if (m_pool->m_freeList.capacity() < m_pool->m_numInstances)\n            {\n                m_pool->m_freeList.reserve(m_pool->m_numInstances + m_pool->m_freeList.capacity() \/ 2);\n            }\n\n            m_pool->m_freeList.resize_no_construct(startIndex + numInstances);\n            for (size_t i = 0; i < numInstances; ++i)\n            {\n                void* memAddress = (void*)(subPool->m_data + i * sizeof(MotionInstance));\n                m_pool->m_freeList[i + startIndex].m_address = memAddress;\n                m_pool->m_freeList[i + startIndex].m_subPool = subPool;\n            }\n\n            m_pool->m_subPools.emplace_back(subPool);\n\n            const MemLocation& location = m_pool->m_freeList.back();\n            MotionInstance* result = MotionInstance::Create(location.m_address, motion, actorInstance);\n            if (location.m_subPool)\n            {\n                location.m_subPool->m_numInUse++;\n            }\n            result->SetSubPool(location.m_subPool);\n            m_pool->m_freeList.pop_back(); \/\/ remove it from the free list\n            m_pool->m_numUsedInstances++;\n            return result;\n        }\n        else \/\/ we are static and ran out of free attributes\n        if (m_pool->m_poolType == POOLTYPE_STATIC)\n        {\n            MCore::LogError(\"EMotionFX::MotionInstancePool::RequestNew() - There are no free motion instance in the static pool. Please increase the size of the pool or make it dynamic when calling Init.\");\n            MCORE_ASSERT(false); \/\/ we ran out of free motion instances\n            return nullptr;\n        }\n        else\n        {\n            MCORE_ASSERT(false); \/\/ unhandled pool type\n            return nullptr;\n        }\n    }\n\n\n    \/\/ free a given motion instance\n    void MotionInstancePool::FreeWithoutLock(MotionInstance* motionInstance)\n    {\n        if (motionInstance == nullptr)\n        {\n            return;\n        }\n\n        if (m_pool == nullptr)\n        {\n            MCore::LogWarning(\"EMotionFX::MotionInstancePool::Free() - The pool has not yet been initialized, please call Init first.\");\n            MCORE_ASSERT(false);\n            return;\n        }\n\n        \/\/ add it back to the free list\n        if (motionInstance->GetSubPool())\n        {\n            motionInstance->GetSubPool()->m_numInUse--;\n        }\n\n        m_pool->m_freeList.emplace_back();\n        m_pool->m_freeList.back().m_address = motionInstance;\n        m_pool->m_freeList.back().m_subPool = motionInstance->GetSubPool();\n        m_pool->m_numUsedInstances--;\n\n        motionInstance->DecreaseReferenceCount();\n        motionInstance->~MotionInstance(); \/\/ call the destructor\n    }\n\n\n    \/\/ log the memory stats\n    void MotionInstancePool::LogMemoryStats()\n    {\n        Lock();\n        MCore::LogInfo(\"EMotionFX::MotionInstancePool::LogMemoryStats() - Logging motion instance pool info\");\n\n        const size_t numFree    = m_pool->m_freeList.size();\n        size_t numUsed          = m_pool->m_numUsedInstances;\n        size_t memUsage         = 0;\n        size_t usedMemUsage     = 0;\n        size_t totalMemUsage    = 0;\n        size_t totalUsedInstancesMemUsage = 0;\n\n        if (m_pool->m_poolType == POOLTYPE_STATIC)\n        {\n            if (m_pool->m_numInstances > 0)\n            {\n                memUsage = m_pool->m_numInstances * sizeof(MotionInstance);\n                usedMemUsage = numUsed * sizeof(MotionInstance);\n            }\n        }\n        else\n        if (m_pool->m_poolType == POOLTYPE_DYNAMIC)\n        {\n            if (m_pool->m_numInstances > 0)\n            {\n                memUsage = m_pool->m_numInstances * sizeof(MotionInstance);\n                usedMemUsage = numUsed * sizeof(MotionInstance);\n            }\n        }\n\n        totalUsedInstancesMemUsage  += usedMemUsage;\n        totalMemUsage += memUsage;\n        totalMemUsage += sizeof(Pool);\n        totalMemUsage += m_pool->m_freeList.capacity() * sizeof(decltype(m_pool->m_freeList)::value_type);\n\n        MCore::LogInfo(\"Pool:\");\n        if (m_pool->m_poolType == POOLTYPE_DYNAMIC)\n        {\n            MCore::LogInfo(\"   - Num SubPools:          %d\", m_pool->m_subPools.size());\n        }\n        MCore::LogInfo(\"   - Num Instances:         %d\", m_pool->m_numInstances);\n        MCore::LogInfo(\"   - Num Free:              %d\", numFree);\n        MCore::LogInfo(\"   - Num Used:              %d\", numUsed);\n        MCore::LogInfo(\"   - PoolType:              %s\", (m_pool->m_poolType == POOLTYPE_STATIC) ? \"Static\" : \"Dynamic\");\n        MCore::LogInfo(\"   - Total Instances Mem:   %d bytes (%d k)\", memUsage, memUsage \/ 1000);\n        MCore::LogInfo(\"   - Used Instances Mem:    %d (%d k)\", totalUsedInstancesMemUsage, totalUsedInstancesMemUsage \/ 1000);\n        MCore::LogInfo(\"   - Total Mem Usage:       %d (%d k)\", totalMemUsage, totalMemUsage \/ 1000);\n        Unlock();\n    }\n\n\n    \/\/ request a new one including lock\n    MotionInstance* MotionInstancePool::RequestNew(Motion* motion, ActorInstance* actorInstance)\n    {\n        Lock();\n        MotionInstance* result = RequestNewWithoutLock(motion, actorInstance);\n        Unlock();\n\n        return result;\n    }\n\n\n    \/\/ free including lock\n    void MotionInstancePool::Free(MotionInstance* motionInstance)\n    {\n        Lock();\n        FreeWithoutLock(motionInstance);\n        Unlock();\n    }\n\n\n    \/\/ wait with execution until we can set the lock\n    void MotionInstancePool::Lock()\n    {\n        m_lock.Lock();\n    }\n\n\n    \/\/ release the lock again\n    void MotionInstancePool::Unlock()\n    {\n        m_lock.Unlock();\n    }\n\n\n    \/\/ shrink the pool\n    void MotionInstancePool::Shrink()\n    {\n        Lock();\n\n        for (size_t i = 0; i < m_pool->m_subPools.size(); )\n        {\n            SubPool* subPool = m_pool->m_subPools[i];\n            if (subPool->m_numInUse == 0)\n            {\n                \/\/ remove all free allocations\n                for (size_t a = 0; a < m_pool->m_freeList.size(); )\n                {\n                    if (m_pool->m_freeList[a].m_subPool == subPool)\n                    {\n                        m_pool->m_freeList.erase(AZStd::next(begin(m_pool->m_freeList), a));\n                    }\n                    else\n                    {\n                        ++a;\n                    }\n                }\n                m_pool->m_numInstances -= subPool->m_numInstances;\n\n                m_pool->m_subPools.erase(AZStd::next(begin(m_pool->m_subPools), i));\n                delete subPool;\n            }\n            else\n            {\n                ++i;\n            }\n        }\n\n        m_pool->m_subPools.shrink_to_fit();\n        if ((m_pool->m_freeList.capacity() - m_pool->m_freeList.size()) > 4096)\n        {\n            m_pool->m_freeList.reserve(m_pool->m_freeList.size() + 4096);\n        }\n\n        Unlock();\n    }\n}   \/\/ namespace MCore\n","avg_line_length":33.416464891,"max_line_length":247,"alphanum_fraction":0.5531483226,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1559,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\ufeff\/*\n* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\").\n* You may not use this file except in compliance with the License.\n* A copy of the License is located at\n*\n*  http:\/\/aws.amazon.com\/apache2.0\n*\n* or in the \"license\" file accompanying this file. This file is distributed\n* on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n* express or implied. See the License for the specific language governing\n* permissions and limitations under the License.\n*\/\n\n#include <aws\/greengrass\/model\/ListConnectorDefinitionsRequest.h>\n#include <aws\/core\/utils\/json\/JsonSerializer.h>\n#include <aws\/core\/http\/URI.h>\n#include <aws\/core\/utils\/memory\/stl\/AWSStringStream.h>\n\n#include <utility>\n\nusing namespace Aws::Greengrass::Model;\nusing namespace Aws::Utils::Json;\nusing namespace Aws::Utils;\nusing namespace Aws::Http;\n\nListConnectorDefinitionsRequest::ListConnectorDefinitionsRequest() : \n    m_maxResultsHasBeenSet(false),\n    m_nextTokenHasBeenSet(false)\n{\n}\n\nAws::String ListConnectorDefinitionsRequest::SerializePayload() const\n{\n  return \"\";\n}\n\nvoid ListConnectorDefinitionsRequest::AddQueryStringParameters(URI& uri) const\n{\n    Aws::StringStream ss;\n    if(m_maxResultsHasBeenSet)\n    {\n      ss << m_maxResults;\n      uri.AddQueryStringParameter(\"MaxResults\", ss.str());\n      ss.str(\"\");\n    }\n\n    if(m_nextTokenHasBeenSet)\n    {\n      ss << m_nextToken;\n      uri.AddQueryStringParameter(\"NextToken\", ss.str());\n      ss.str(\"\");\n    }\n\n}\n\n\n\n","avg_line_length":25.9833333333,"max_line_length":78,"alphanum_fraction":0.7305965362,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4001,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":1.0,"content":"\/*\n * Copyright Nick Thompson, 2019\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n *\/\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <utility>\n#include <random>\n#include <boost\/core\/demangle.hpp>\n#include <boost\/math\/interpolators\/whittaker_shannon.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost\/multiprecision\/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing boost::math::interpolators::whittaker_shannon;\n\ntemplate<class Real>\nvoid test_trivial()\n{\n    Real t0 = 0;\n    Real h = Real(1)\/Real(16);\n    std::vector<Real> v{1.5};\n    std::vector<Real> v_copy = v;\n    auto ws = whittaker_shannon<decltype(v)>(std::move(v), t0, h);\n\n\n    Real expected = 0;\n    if(!CHECK_MOLLIFIED_CLOSE(expected, ws.prime(0), 10*std::numeric_limits<Real>::epsilon())) {\n        std::cerr << \"  Problem occurred at abscissa \" << 0 << \"\\n\";\n    }\n\n    expected = -v_copy[0]\/h;\n    if(!CHECK_MOLLIFIED_CLOSE(expected, ws.prime(h), 10*std::numeric_limits<Real>::epsilon())) {\n        std::cerr << \"  Problem occurred at abscissa \" << 0 << \"\\n\";\n    }\n}\n\ntemplate<class Real>\nvoid test_knots()\n{\n    Real t0 = 0;\n    Real h = Real(1)\/Real(16);\n    size_t n = 512;\n    std::vector<Real> v(n);\n    std::mt19937 gen(323723);\n    std::uniform_real_distribution<Real> dis(1.0, 2.0);\n\n    for(size_t i = 0;  i < n; ++i) {\n      v[i] = static_cast<Real>(dis(gen));\n    }\n    auto ws = whittaker_shannon<decltype(v)>(std::move(v), t0, h);\n\n    size_t i = 0;\n    while (i < n) {\n      Real t = t0 + i*h;\n      Real expected = ws[i];\n      Real computed = ws(t);\n      CHECK_ULP_CLOSE(expected, computed, 16);\n      ++i;\n    }\n}\n\ntemplate<class Real>\nvoid test_bump()\n{\n    using std::exp;\n    using std::abs;\n    using std::sqrt;\n    auto bump = [](Real x) { if (abs(x) >= 1) { return Real(0); } return exp(-Real(1)\/(Real(1)-x*x)); };\n\n    auto bump_prime = [&bump](Real x) { Real z = 1-x*x; return -2*x*bump(x)\/(z*z); };\n\n    Real t0 = -1;\n    size_t n = 2049;\n    Real h = Real(2)\/Real(n-1);\n\n    std::vector<Real> v(n);\n    for(size_t i = 0; i < n; ++i) {\n        Real t = t0 + i*h;\n        v[i] = bump(t);\n    }\n\n\n    std::vector<Real> v_copy = v;\n    auto ws = whittaker_shannon<decltype(v)>(std::move(v), t0, h);\n\n    \/\/ Test the knots:\n    for(size_t i = v_copy.size()\/4; i < 3*v_copy.size()\/4; ++i) {\n        Real t = t0 + i*h;\n        Real expected = v_copy[i];\n        Real computed = ws(t);\n        if(!CHECK_MOLLIFIED_CLOSE(expected, computed, 10*std::numeric_limits<Real>::epsilon())) {\n            std::cerr << \"  Problem occurred at abscissa \" << t << \"\\n\";\n        }\n\n        Real expected_prime = bump_prime(t);\n        Real computed_prime = ws.prime(t);\n        if(!CHECK_MOLLIFIED_CLOSE(expected_prime, computed_prime, 1000*std::numeric_limits<Real>::epsilon())) {\n            std::cerr << \"  Problem occurred at abscissa \" << t << \"\\n\";\n        }\n\n    }\n\n    std::mt19937 gen(323723);\n    std::uniform_real_distribution<long double> dis(-0.85, 0.85);\n\n    size_t i = 0;\n    while (i++ < 1000)\n    {\n        Real t = static_cast<Real>(dis(gen));\n        Real expected = bump(t);\n        Real computed = ws(t);\n        if(!CHECK_MOLLIFIED_CLOSE(expected, computed, 10*std::numeric_limits<Real>::epsilon())) {\n            std::cerr << \"  Problem occurred at abscissa \" << t << \"\\n\";\n        }\n\n        Real expected_prime = bump_prime(t);\n        Real computed_prime = ws.prime(t);\n        if(!CHECK_MOLLIFIED_CLOSE(expected_prime, computed_prime, sqrt(std::numeric_limits<Real>::epsilon()))) {\n            std::cerr << \"  Problem occurred at abscissa \" << t << \"\\n\";\n        }\n    }\n}\n\n\nint main()\n{\n    test_knots<float>();\n    test_knots<double>();\n    test_knots<long double>();\n\n    test_bump<double>();\n    test_bump<long double>();\n\n    test_trivial<float>();\n    test_trivial<double>();\n    return boost::math::test::report_errors();\n}\n","avg_line_length":27.979020979,"max_line_length":112,"alphanum_fraction":0.5926018495,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1828,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":247.0,"content":"#include <bits\/stdc++.h>\nusing namespace std;\n\/\/BIT with 1 based indexing\ntemplate <typename T>\nstruct BIT\n{\n    T N;\n    vector<T> tree;\n    void init(int n)\n    {\n        N = n;\n        tree.assign(n + 1, 0);\n    }\n    \/\/point update in O(log(n))\n    void update(int idx, T val)\n    {\n\n        while (idx <= N)\n        {\n            tree[idx - 1] += val;\n            idx += (idx & (-idx));\n        }\n    }\n    \/\/query in O(log(n))\n    T query(int idx)\n    {\n        T sm = 0;\n        while (idx > 0)\n        {\n            sm += tree[idx - 1];\n            idx -= (idx & (-idx));\n        }\n        return sm;\n    }\n    \/\/sum function to find sum of values [l,r]\n    T sum(int l, int r)\n    {\n        return query(r) - query(l - 1);\n    }\n};\n\nint main()\n{\n\n    int n;\n    cin >> n;\n    vector<int> v(n);\n    for (int i = 0; i < n; i++)\n    {\n        cin >> v[i];\n    }\n    BIT<int> f;\n    f.init(n + 1); \/\/1 base indexing\n    \/\/Building of Fenwick Tree in O(n*(log(n)))\n    for (int i = 0; i < n; i++)\n    {\n        f.update(i + 1, v[i]);\n    }\n    \/\/queries\n    int q;\n    cin >> q;\n    while (q--)\n    {\n        int t;\n        \/\/two types of queries\n        \/\/1) t = 1 change element at index i to u\n        \/\/2) t = 2 print the sum of elements in range [l,r]\n        cin >> t;\n        if (t == 1)\n        {\n            int id, u;\n            cin >> id >> u;\n            id--; \/\/changing to zero base\n            int initial = v[id];\n            f.update(id + 1, u - initial); \/\/updating the delta\n            v[id] = u;\n        }\n        else\n        {\n            int l, r;\n            cin >> l >> r;\n            cout << f.sum(l, r) << endl;\n        }\n    }\n}\n\n\/\/ Time Complexity:\n\/\/ O(nlogn)\n\/\/ Space Complexity:\n\/\/ O(n)\n\n\/\/ Test Cases:\n\/\/ Input:\n\/\/ 5\n\/\/ 1 3 4 7 -15\n\/\/ 3\n\/\/ 2 2 5\n\/\/ 1 3 -5\n\/\/ 2 2 5\n\/\/ Output:\n\/\/ -1\n\/\/ -10\n","avg_line_length":17.7475728155,"max_line_length":63,"alphanum_fraction":0.3993435449,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8539,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["PHP-3.01","Zend-2.0"],"max_stars_count":null,"content":"\/*\n *  Copyright (c) 2015, Facebook, Inc.\n *  All rights reserved.\n *\n *  This source code is licensed under the BSD-style license found in the\n *  LICENSE file in the root directory of this source tree. An additional grant\n *  of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n#include <wangle\/channel\/broadcast\/test\/Mocks.h>\n#include <wangle\/channel\/test\/MockHandler.h>\n\nusing namespace wangle;\nusing namespace folly;\nusing namespace testing;\n\nclass BroadcastHandlerTest : public Test {\n public:\n  class MockBroadcastHandler : public BroadcastHandler<std::string> {\n   public:\n    MOCK_METHOD1(close, folly::Future<folly::Unit>(Context*));\n  };\n\n  void SetUp() override {\n    prevHandler = new StrictMock<MockBytesToBytesHandler>();\n    EXPECT_CALL(*prevHandler, read(_, _))\n        .WillRepeatedly(Invoke([&](MockBytesToBytesHandler::Context* ctx,\n                                   IOBufQueue& q) { ctx->fireRead(q); }));\n\n    decoder = new StrictMock<MockByteToMessageDecoder<std::string>>();\n    handler = new StrictMock<MockBroadcastHandler>();\n\n    pipeline = DefaultPipeline::create();\n    pipeline->addBack(\n        std::shared_ptr<StrictMock<MockBytesToBytesHandler>>(prevHandler));\n    pipeline->addBack(\n        std::shared_ptr<StrictMock<MockByteToMessageDecoder<std::string>>>(\n            decoder));\n    pipeline->addBack(\n        std::shared_ptr<StrictMock<MockBroadcastHandler>>(handler));\n    pipeline->finalize();\n  }\n\n  void TearDown() override {\n    Mock::VerifyAndClear(&subscriber0);\n    Mock::VerifyAndClear(&subscriber1);\n\n    pipeline.reset();\n  }\n\n protected:\n  DefaultPipeline::Ptr pipeline;\n\n  StrictMock<MockBytesToBytesHandler>* prevHandler{nullptr};\n  StrictMock<MockByteToMessageDecoder<std::string>>* decoder{nullptr};\n  StrictMock<MockBroadcastHandler>* handler{nullptr};\n\n  StrictMock<MockSubscriber<std::string>> subscriber0;\n  StrictMock<MockSubscriber<std::string>> subscriber1;\n};\n\nTEST_F(BroadcastHandlerTest, SubscribeUnsubscribe) {\n  \/\/ Test by adding a couple of subscribers and unsubscribing them\n  EXPECT_CALL(*decoder, decode(_, _, _, _))\n      .WillRepeatedly(\n          Invoke([&](MockByteToMessageDecoder<std::string>::Context*,\n                     IOBufQueue& q, std::string& data, size_t&) {\n            auto buf = q.move();\n            if (buf) {\n              buf->coalesce();\n              data = buf->moveToFbString().toStdString();\n              return true;\n            }\n            return false;\n          }));\n\n  InSequence dummy;\n\n  \/\/ Add a subscriber\n  EXPECT_EQ(handler->subscribe(&subscriber0), 0);\n\n  EXPECT_CALL(subscriber0, onNext(\"data1\")).Times(1);\n  EXPECT_CALL(subscriber0, onNext(\"data2\")).Times(1);\n\n  \/\/ Push some data\n  IOBufQueue q;\n  q.append(IOBuf::copyBuffer(\"data1\"));\n  pipeline->read(q);\n  q.clear();\n  q.append(IOBuf::copyBuffer(\"data2\"));\n  pipeline->read(q);\n  q.clear();\n\n  \/\/ Add another subscriber\n  EXPECT_EQ(handler->subscribe(&subscriber1), 1);\n\n  EXPECT_CALL(subscriber0, onNext(\"data3\")).Times(1);\n  EXPECT_CALL(subscriber1, onNext(\"data3\")).Times(1);\n\n  \/\/ Push more data\n  q.append(IOBuf::copyBuffer(\"data3\"));\n  pipeline->read(q);\n  q.clear();\n\n  \/\/ Unsubscribe one of the subscribers\n  handler->unsubscribe(0);\n\n  EXPECT_CALL(subscriber1, onNext(Eq(\"data4\"))).Times(1);\n\n  \/\/ Push more data\n  q.append(IOBuf::copyBuffer(\"data4\"));\n  pipeline->read(q);\n  q.clear();\n\n  EXPECT_CALL(*handler, close(_))\n      .WillOnce(InvokeWithoutArgs([this] {\n        pipeline.reset();\n        return makeFuture();\n      }));\n\n  \/\/ Unsubscribe the other subscriber. The handler should be deleted now.\n  handler->unsubscribe(1);\n}\n\nTEST_F(BroadcastHandlerTest, BufferedRead) {\n  \/\/ Test with decoder that buffers data based on some local logic\n  \/\/ before pushing to subscribers\n  IOBufQueue bufQueue{IOBufQueue::cacheChainLength()};\n  EXPECT_CALL(*decoder, decode(_, _, _, _))\n      .WillRepeatedly(\n          Invoke([&](MockByteToMessageDecoder<std::string>::Context*,\n                     IOBufQueue& q, std::string& data, size_t&) {\n            bufQueue.append(q);\n            if (bufQueue.chainLength() < 5) {\n              return false;\n            }\n            auto buf = bufQueue.move();\n            buf->coalesce();\n            data = buf->moveToFbString().toStdString();\n            return true;\n          }));\n\n  InSequence dummy;\n\n  \/\/ Add a subscriber\n  EXPECT_EQ(handler->subscribe(&subscriber0), 0);\n\n  EXPECT_CALL(subscriber0, onNext(\"data1\")).Times(1);\n\n  \/\/ Push some fragmented data\n  IOBufQueue q;\n  q.append(IOBuf::copyBuffer(\"da\"));\n  pipeline->read(q);\n  q.clear();\n  q.append(IOBuf::copyBuffer(\"ta1\"));\n  pipeline->read(q);\n  q.clear();\n\n  \/\/ Push more fragmented data. onNext shouldn't be called yet.\n  q.append(IOBuf::copyBuffer(\"dat\"));\n  pipeline->read(q);\n  q.clear();\n  q.append(IOBuf::copyBuffer(\"a\"));\n  pipeline->read(q);\n  q.clear();\n\n  \/\/ Add another subscriber\n  EXPECT_EQ(handler->subscribe(&subscriber1), 1);\n\n  EXPECT_CALL(subscriber0, onNext(\"data3data4\")).Times(1);\n  EXPECT_CALL(subscriber1, onNext(\"data3data4\")).Times(1);\n\n  \/\/ Push rest of the fragmented data. The entire data should be pushed\n  \/\/ to both subscribers.\n  q.append(IOBuf::copyBuffer(\"3data4\"));\n  pipeline->read(q);\n  q.clear();\n\n  EXPECT_CALL(subscriber0, onNext(\"data2\")).Times(1);\n  EXPECT_CALL(subscriber1, onNext(\"data2\")).Times(1);\n\n  \/\/ Push some unfragmented data\n  q.append(IOBuf::copyBuffer(\"data2\"));\n  pipeline->read(q);\n  q.clear();\n\n  EXPECT_CALL(*handler, close(_))\n      .WillOnce(InvokeWithoutArgs([this] {\n        pipeline.reset();\n        return makeFuture();\n      }));\n\n  \/\/ Unsubscribe all subscribers. The handler should be deleted now.\n  handler->unsubscribe(0);\n  handler->unsubscribe(1);\n}\n\nTEST_F(BroadcastHandlerTest, OnCompleted) {\n  \/\/ Test with EOF on the handler\n  EXPECT_CALL(*decoder, decode(_, _, _, _))\n      .WillRepeatedly(\n          Invoke([&](MockByteToMessageDecoder<std::string>::Context*,\n                     IOBufQueue& q, std::string& data, size_t&) {\n            auto buf = q.move();\n            if (buf) {\n              buf->coalesce();\n              data = buf->moveToFbString().toStdString();\n              return true;\n            }\n            return false;\n          }));\n\n  InSequence dummy;\n\n  \/\/ Add a subscriber\n  EXPECT_EQ(handler->subscribe(&subscriber0), 0);\n\n  EXPECT_CALL(subscriber0, onNext(\"data1\")).Times(1);\n\n  \/\/ Push some data\n  IOBufQueue q;\n  q.append(IOBuf::copyBuffer(\"data1\"));\n  pipeline->read(q);\n  q.clear();\n\n  \/\/ Add another subscriber\n  EXPECT_EQ(handler->subscribe(&subscriber1), 1);\n\n  EXPECT_CALL(subscriber0, onNext(\"data2\")).Times(1);\n  EXPECT_CALL(subscriber1, onNext(\"data2\")).Times(1);\n\n  \/\/ Push more data\n  q.append(IOBuf::copyBuffer(\"data2\"));\n  pipeline->read(q);\n  q.clear();\n\n  \/\/ Unsubscribe one of the subscribers\n  handler->unsubscribe(0);\n\n  EXPECT_CALL(subscriber1, onCompleted()).Times(1);\n\n  EXPECT_CALL(*handler, close(_))\n      .WillOnce(InvokeWithoutArgs([this] {\n        pipeline.reset();\n        return makeFuture();\n      }));\n\n  \/\/ The handler should be deleted now\n  handler->readEOF(nullptr);\n}\n\nTEST_F(BroadcastHandlerTest, OnError) {\n  \/\/ Test with EOF on the handler\n  EXPECT_CALL(*decoder, decode(_, _, _, _))\n      .WillRepeatedly(\n          Invoke([&](MockByteToMessageDecoder<std::string>::Context*,\n                     IOBufQueue& q, std::string& data, size_t&) {\n            auto buf = q.move();\n            if (buf) {\n              buf->coalesce();\n              data = buf->moveToFbString().toStdString();\n              return true;\n            }\n            return false;\n          }));\n\n  InSequence dummy;\n\n  \/\/ Add a subscriber\n  EXPECT_EQ(handler->subscribe(&subscriber0), 0);\n\n  EXPECT_CALL(subscriber0, onNext(\"data1\")).Times(1);\n\n  \/\/ Push some data\n  IOBufQueue q;\n  q.append(IOBuf::copyBuffer(\"data1\"));\n  pipeline->read(q);\n  q.clear();\n\n  \/\/ Add another subscriber\n  EXPECT_EQ(handler->subscribe(&subscriber1), 1);\n\n  EXPECT_CALL(subscriber0, onNext(\"data2\")).Times(1);\n  EXPECT_CALL(subscriber1, onNext(\"data2\")).Times(1);\n\n  \/\/ Push more data\n  q.append(IOBuf::copyBuffer(\"data2\"));\n  pipeline->read(q);\n  q.clear();\n\n  EXPECT_CALL(subscriber0, onError(_)).Times(1);\n  EXPECT_CALL(subscriber1, onError(_)).Times(1);\n\n  EXPECT_CALL(*handler, close(_))\n      .WillOnce(InvokeWithoutArgs([this] {\n        pipeline.reset();\n        return makeFuture();\n      }));\n\n  \/\/ The handler should be deleted now\n  handler->readException(nullptr, make_exception_wrapper<std::exception>());\n}\n","avg_line_length":28.1815181518,"max_line_length":79,"alphanum_fraction":0.6431666471,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":21995,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <script\/sign.h>\n\n#include <key.h>\n#include <policy\/policy.h>\n#include <primitives\/transaction.h>\n#include <script\/signingprovider.h>\n#include <script\/standard.h>\n#include <uint256.h>\n\ntypedef std::vector<unsigned char> valtype;\n\nMutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn) : txTo(txToIn), nIn(nInIn), nHashType(nHashTypeIn), amount(amountIn), checker(txTo, nIn, amountIn) {}\n\nbool MutableTransactionSignatureCreator::CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const\n{\n    CKey key;\n    if (!provider.GetKey(address, key))\n        return false;\n\n    \/\/ Signing with uncompressed keys is disabled in witness scripts\n    if (sigversion == SigVersion::WITNESS_V0 && !key.IsCompressed())\n        return false;\n\n    uint256 hash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion);\n    if (!key.Sign(hash, vchSig))\n        return false;\n    vchSig.push_back((unsigned char)nHashType);\n    return true;\n}\n\nstatic bool GetCScript(const SigningProvider& provider, const SignatureData& sigdata, const CScriptID& scriptid, CScript& script)\n{\n    if (provider.GetCScript(scriptid, script)) {\n        return true;\n    }\n    \/\/ Look for scripts in SignatureData\n    if (CScriptID(sigdata.redeem_script) == scriptid) {\n        script = sigdata.redeem_script;\n        return true;\n    } else if (CScriptID(sigdata.witness_script) == scriptid) {\n        script = sigdata.witness_script;\n        return true;\n    }\n    return false;\n}\n\nstatic bool GetPubKey(const SigningProvider& provider, const SignatureData& sigdata, const CKeyID& address, CPubKey& pubkey)\n{\n    \/\/ Look for pubkey in all partial sigs\n    const auto it = sigdata.signatures.find(address);\n    if (it != sigdata.signatures.end()) {\n        pubkey = it->second.first;\n        return true;\n    }\n    \/\/ Look for pubkey in pubkey list\n    const auto& pk_it = sigdata.misc_pubkeys.find(address);\n    if (pk_it != sigdata.misc_pubkeys.end()) {\n        pubkey = pk_it->second.first;\n        return true;\n    }\n    \/\/ Query the underlying provider\n    return provider.GetPubKey(address, pubkey);\n}\n\nstatic bool CreateSig(const BaseSignatureCreator& creator, SignatureData& sigdata, const SigningProvider& provider, std::vector<unsigned char>& sig_out, const CPubKey& pubkey, const CScript& scriptcode, SigVersion sigversion)\n{\n    CKeyID keyid = pubkey.GetID();\n    const auto it = sigdata.signatures.find(keyid);\n    if (it != sigdata.signatures.end()) {\n        sig_out = it->second.second;\n        return true;\n    }\n    KeyOriginInfo info;\n    if (provider.GetKeyOrigin(keyid, info)) {\n        sigdata.misc_pubkeys.emplace(keyid, std::make_pair(pubkey, std::move(info)));\n    }\n    if (creator.CreateSig(provider, sig_out, keyid, scriptcode, sigversion)) {\n        auto i = sigdata.signatures.emplace(keyid, SigPair(pubkey, sig_out));\n        assert(i.second);\n        return true;\n    }\n    \/\/ Could not make signature or signature not found, add keyid to missing\n    sigdata.missing_sigs.push_back(keyid);\n    return false;\n}\n\n\/**\n * Sign scriptPubKey using signature made with creator.\n * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),\n * unless whichTypeRet is TxoutType::SCRIPTHASH, in which case scriptSigRet is the redemption script.\n * Returns false if scriptPubKey could not be completely satisfied.\n *\/\nstatic bool SignStep(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey,\n                     std::vector<valtype>& ret, TxoutType& whichTypeRet, SigVersion sigversion, SignatureData& sigdata)\n{\n    CScript scriptRet;\n    uint160 h160;\n    ret.clear();\n    std::vector<unsigned char> sig;\n\n    std::vector<valtype> vSolutions;\n    whichTypeRet = Solver(scriptPubKey, vSolutions);\n\n    switch (whichTypeRet)\n    {\n    case TxoutType::NONSTANDARD:\n    case TxoutType::NULL_DATA:\n    case TxoutType::WITNESS_UNKNOWN:\n    case TxoutType::WITNESS_V1_TAPROOT:\n        return false;\n    case TxoutType::PUBKEY:\n        if (!CreateSig(creator, sigdata, provider, sig, CPubKey(vSolutions[0]), scriptPubKey, sigversion)) return false;\n        ret.push_back(std::move(sig));\n        return true;\n    case TxoutType::PUBKEYHASH: {\n        CKeyID keyID = CKeyID(uint160(vSolutions[0]));\n        CPubKey pubkey;\n        if (!GetPubKey(provider, sigdata, keyID, pubkey)) {\n            \/\/ Pubkey could not be found, add to missing\n            sigdata.missing_pubkeys.push_back(keyID);\n            return false;\n        }\n        if (!CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) return false;\n        ret.push_back(std::move(sig));\n        ret.push_back(ToByteVector(pubkey));\n        return true;\n    }\n    case TxoutType::SCRIPTHASH:\n        h160 = uint160(vSolutions[0]);\n        if (GetCScript(provider, sigdata, CScriptID{h160}, scriptRet)) {\n            ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));\n            return true;\n        }\n        \/\/ Could not find redeemScript, add to missing\n        sigdata.missing_redeem_script = h160;\n        return false;\n\n    case TxoutType::MULTISIG: {\n        size_t required = vSolutions.front()[0];\n        ret.push_back(valtype()); \/\/ workaround CHECKMULTISIG bug\n        for (size_t i = 1; i < vSolutions.size() - 1; ++i) {\n            CPubKey pubkey = CPubKey(vSolutions[i]);\n            \/\/ We need to always call CreateSig in order to fill sigdata with all\n            \/\/ possible signatures that we can create. This will allow further PSBT\n            \/\/ processing to work as it needs all possible signature and pubkey pairs\n            if (CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) {\n                if (ret.size() < required + 1) {\n                    ret.push_back(std::move(sig));\n                }\n            }\n        }\n        bool ok = ret.size() == required + 1;\n        for (size_t i = 0; i + ret.size() < required + 1; ++i) {\n            ret.push_back(valtype());\n        }\n        return ok;\n    }\n    case TxoutType::WITNESS_V0_KEYHASH:\n        ret.push_back(vSolutions[0]);\n        return true;\n\n    case TxoutType::WITNESS_V0_SCRIPTHASH:\n        CRIPEMD160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(h160.begin());\n        if (GetCScript(provider, sigdata, CScriptID{h160}, scriptRet)) {\n            ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));\n            return true;\n        }\n        \/\/ Could not find witnessScript, add to missing\n        sigdata.missing_witness_script = uint256(vSolutions[0]);\n        return false;\n\n    default:\n        return false;\n    }\n}\n\nstatic CScript PushAll(const std::vector<valtype>& values)\n{\n    CScript result;\n    for (const valtype& v : values) {\n        if (v.size() == 0) {\n            result << OP_0;\n        } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {\n            result << CScript::EncodeOP_N(v[0]);\n        } else if (v.size() == 1 && v[0] == 0x81) {\n            result << OP_1NEGATE;\n        } else {\n            result << v;\n        }\n    }\n    return result;\n}\n\nbool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata)\n{\n    if (sigdata.complete) return true;\n\n    std::vector<valtype> result;\n    TxoutType whichType;\n    bool solved = SignStep(provider, creator, fromPubKey, result, whichType, SigVersion::BASE, sigdata);\n    bool P2SH = false;\n    CScript subscript;\n    sigdata.scriptWitness.stack.clear();\n\n    if (solved && whichType == TxoutType::SCRIPTHASH)\n    {\n        \/\/ Solver returns the subscript that needs to be evaluated;\n        \/\/ the final scriptSig is the signatures from that\n        \/\/ and then the serialized subscript:\n        subscript = CScript(result[0].begin(), result[0].end());\n        sigdata.redeem_script = subscript;\n        solved = solved && SignStep(provider, creator, subscript, result, whichType, SigVersion::BASE, sigdata) && whichType != TxoutType::SCRIPTHASH;\n        P2SH = true;\n    }\n\n    if (solved && whichType == TxoutType::WITNESS_V0_KEYHASH)\n    {\n        CScript witnessscript;\n        witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;\n        TxoutType subType;\n        solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata);\n        sigdata.scriptWitness.stack = result;\n        sigdata.witness = true;\n        result.clear();\n    }\n    else if (solved && whichType == TxoutType::WITNESS_V0_SCRIPTHASH)\n    {\n        CScript witnessscript(result[0].begin(), result[0].end());\n        sigdata.witness_script = witnessscript;\n        TxoutType subType;\n        solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata) && subType != TxoutType::SCRIPTHASH && subType != TxoutType::WITNESS_V0_SCRIPTHASH && subType != TxoutType::WITNESS_V0_KEYHASH;\n        result.push_back(std::vector<unsigned char>(witnessscript.begin(), witnessscript.end()));\n        sigdata.scriptWitness.stack = result;\n        sigdata.witness = true;\n        result.clear();\n    } else if (solved && whichType == TxoutType::WITNESS_UNKNOWN) {\n        sigdata.witness = true;\n    }\n\n    if (P2SH) {\n        result.push_back(std::vector<unsigned char>(subscript.begin(), subscript.end()));\n    }\n    sigdata.scriptSig = PushAll(result);\n\n    \/\/ Test solution\n    sigdata.complete = solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker());\n    return sigdata.complete;\n}\n\nnamespace {\nclass SignatureExtractorChecker final : public BaseSignatureChecker\n{\nprivate:\n    SignatureData& sigdata;\n    BaseSignatureChecker& checker;\n\npublic:\n    SignatureExtractorChecker(SignatureData& sigdata, BaseSignatureChecker& checker) : sigdata(sigdata), checker(checker) {}\n    bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override\n    {\n        if (checker.CheckECDSASignature(scriptSig, vchPubKey, scriptCode, sigversion)) {\n            CPubKey pubkey(vchPubKey);\n            sigdata.signatures.emplace(pubkey.GetID(), SigPair(pubkey, scriptSig));\n            return true;\n        }\n        return false;\n    }\n};\n\nstruct Stacks\n{\n    std::vector<valtype> script;\n    std::vector<valtype> witness;\n\n    Stacks() = delete;\n    Stacks(const Stacks&) = delete;\n    explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {\n        EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE);\n    }\n};\n}\n\n\/\/ Extracts signatures and scripts from incomplete scriptSigs. Please do not extend this, use PSBT instead\nSignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout)\n{\n    SignatureData data;\n    assert(tx.vin.size() > nIn);\n    data.scriptSig = tx.vin[nIn].scriptSig;\n    data.scriptWitness = tx.vin[nIn].scriptWitness;\n    Stacks stack(data);\n\n    \/\/ Get signatures\n    MutableTransactionSignatureChecker tx_checker(&tx, nIn, txout.nValue);\n    SignatureExtractorChecker extractor_checker(data, tx_checker);\n    if (VerifyScript(data.scriptSig, txout.scriptPubKey, &data.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, extractor_checker)) {\n        data.complete = true;\n        return data;\n    }\n\n    \/\/ Get scripts\n    std::vector<std::vector<unsigned char>> solutions;\n    TxoutType script_type = Solver(txout.scriptPubKey, solutions);\n    SigVersion sigversion = SigVersion::BASE;\n    CScript next_script = txout.scriptPubKey;\n\n    if (script_type == TxoutType::SCRIPTHASH && !stack.script.empty() && !stack.script.back().empty()) {\n        \/\/ Get the redeemScript\n        CScript redeem_script(stack.script.back().begin(), stack.script.back().end());\n        data.redeem_script = redeem_script;\n        next_script = std::move(redeem_script);\n\n        \/\/ Get redeemScript type\n        script_type = Solver(next_script, solutions);\n        stack.script.pop_back();\n    }\n    if (script_type == TxoutType::WITNESS_V0_SCRIPTHASH && !stack.witness.empty() && !stack.witness.back().empty()) {\n        \/\/ Get the witnessScript\n        CScript witness_script(stack.witness.back().begin(), stack.witness.back().end());\n        data.witness_script = witness_script;\n        next_script = std::move(witness_script);\n\n        \/\/ Get witnessScript type\n        script_type = Solver(next_script, solutions);\n        stack.witness.pop_back();\n        stack.script = std::move(stack.witness);\n        stack.witness.clear();\n        sigversion = SigVersion::WITNESS_V0;\n    }\n    if (script_type == TxoutType::MULTISIG && !stack.script.empty()) {\n        \/\/ Build a map of pubkey -> signature by matching sigs to pubkeys:\n        assert(solutions.size() > 1);\n        unsigned int num_pubkeys = solutions.size()-2;\n        unsigned int last_success_key = 0;\n        for (const valtype& sig : stack.script) {\n            for (unsigned int i = last_success_key; i < num_pubkeys; ++i) {\n                const valtype& pubkey = solutions[i+1];\n                \/\/ We either have a signature for this pubkey, or we have found a signature and it is valid\n                if (data.signatures.count(CPubKey(pubkey).GetID()) || extractor_checker.CheckECDSASignature(sig, pubkey, next_script, sigversion)) {\n                    last_success_key = i + 1;\n                    break;\n                }\n            }\n        }\n    }\n\n    return data;\n}\n\nvoid UpdateInput(CTxIn& input, const SignatureData& data)\n{\n    input.scriptSig = data.scriptSig;\n    input.scriptWitness = data.scriptWitness;\n}\n\nvoid SignatureData::MergeSignatureData(SignatureData sigdata)\n{\n    if (complete) return;\n    if (sigdata.complete) {\n        *this = std::move(sigdata);\n        return;\n    }\n    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {\n        redeem_script = sigdata.redeem_script;\n    }\n    if (witness_script.empty() && !sigdata.witness_script.empty()) {\n        witness_script = sigdata.witness_script;\n    }\n    signatures.insert(std::make_move_iterator(sigdata.signatures.begin()), std::make_move_iterator(sigdata.signatures.end()));\n}\n\nbool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType)\n{\n    assert(nIn < txTo.vin.size());\n\n    MutableTransactionSignatureCreator creator(&txTo, nIn, amount, nHashType);\n\n    SignatureData sigdata;\n    bool ret = ProduceSignature(provider, creator, fromPubKey, sigdata);\n    UpdateInput(txTo.vin.at(nIn), sigdata);\n    return ret;\n}\n\nbool SignSignature(const SigningProvider &provider, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType)\n{\n    assert(nIn < txTo.vin.size());\n    CTxIn& txin = txTo.vin[nIn];\n    assert(txin.prevout.n < txFrom.vout.size());\n    const CTxOut& txout = txFrom.vout[txin.prevout.n];\n\n    return SignSignature(provider, txout.scriptPubKey, txTo, nIn, txout.nValue, nHashType);\n}\n\nbool VerifySignature(const Coin& coin, const uint256 txFromHash, const CTransaction& txTo, unsigned int nIn, unsigned int flags)\n{\n    TransactionSignatureChecker checker(&txTo, nIn, 0);\n\t\n    const CTxIn& txin = txTo.vin[nIn];\n    const CTxOut& txout = coin.out;\n\n    if (txin.prevout.hash != txFromHash)\n        return false;\n\t\t\n    return VerifyScript(txin.scriptSig, txout.scriptPubKey, NULL, flags, checker);\n}\n\nnamespace {\n\/** Dummy signature checker which accepts all signatures. *\/\nclass DummySignatureChecker final : public BaseSignatureChecker\n{\npublic:\n    DummySignatureChecker() {}\n    bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override { return true; }\n};\nconst DummySignatureChecker DUMMY_CHECKER;\n\nclass DummySignatureCreator final : public BaseSignatureCreator {\nprivate:\n    char m_r_len = 32;\n    char m_s_len = 32;\npublic:\n    DummySignatureCreator(char r_len, char s_len) : m_r_len(r_len), m_s_len(s_len) {}\n    const BaseSignatureChecker& Checker() const override { return DUMMY_CHECKER; }\n    bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override\n    {\n        \/\/ Create a dummy signature that is a valid DER-encoding\n        vchSig.assign(m_r_len + m_s_len + 7, '\\000');\n        vchSig[0] = 0x30;\n        vchSig[1] = m_r_len + m_s_len + 4;\n        vchSig[2] = 0x02;\n        vchSig[3] = m_r_len;\n        vchSig[4] = 0x01;\n        vchSig[4 + m_r_len] = 0x02;\n        vchSig[5 + m_r_len] = m_s_len;\n        vchSig[6 + m_r_len] = 0x01;\n        vchSig[6 + m_r_len + m_s_len] = SIGHASH_ALL;\n        return true;\n    }\n};\n\n}\n\nconst BaseSignatureCreator& DUMMY_SIGNATURE_CREATOR = DummySignatureCreator(32, 32);\nconst BaseSignatureCreator& DUMMY_MAXIMUM_SIGNATURE_CREATOR = DummySignatureCreator(33, 32);\n\nbool IsSolvable(const SigningProvider& provider, const CScript& script)\n{\n    \/\/ This check is to make sure that the script we created can actually be solved for and signed by us\n    \/\/ if we were to have the private keys. This is just to make sure that the script is valid and that,\n    \/\/ if found in a transaction, we would still accept and relay that transaction. In particular,\n    \/\/ it will reject witness outputs that require signing with an uncompressed public key.\n    SignatureData sigs;\n    \/\/ Make sure that STANDARD_SCRIPT_VERIFY_FLAGS includes SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, the most\n    \/\/ important property this function is designed to test for.\n    static_assert(STANDARD_SCRIPT_VERIFY_FLAGS & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, \"IsSolvable requires standard script flags to include WITNESS_PUBKEYTYPE\");\n    if (ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, script, sigs)) {\n        \/\/ VerifyScript check is just defensive, and should never fail.\n        bool verified = VerifyScript(sigs.scriptSig, script, &sigs.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, DUMMY_CHECKER);\n        assert(verified);\n        return true;\n    }\n    return false;\n}\n\nbool IsSegWitOutput(const SigningProvider& provider, const CScript& script)\n{\n    std::vector<valtype> solutions;\n    auto whichtype = Solver(script, solutions);\n    if (whichtype == TxoutType::WITNESS_V0_SCRIPTHASH || whichtype == TxoutType::WITNESS_V0_KEYHASH || whichtype == TxoutType::WITNESS_UNKNOWN) return true;\n    if (whichtype == TxoutType::SCRIPTHASH) {\n        auto h160 = uint160(solutions[0]);\n        CScript subscript;\n        if (provider.GetCScript(CScriptID{h160}, subscript)) {\n            whichtype = Solver(subscript, solutions);\n            if (whichtype == TxoutType::WITNESS_V0_SCRIPTHASH || whichtype == TxoutType::WITNESS_V0_KEYHASH || whichtype == TxoutType::WITNESS_UNKNOWN) return true;\n        }\n    }\n    return false;\n}\n\nbool SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, int nHashType, std::map<int, std::string>& input_errors)\n{\n    bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);\n\n    \/\/ Use CTransaction for the constant parts of the\n    \/\/ transaction to avoid rehashing.\n    const CTransaction txConst(mtx);\n    \/\/ Sign what we can:\n    for (unsigned int i = 0; i < mtx.vin.size(); i++) {\n        CTxIn& txin = mtx.vin[i];\n        auto coin = coins.find(txin.prevout);\n        if (coin == coins.end() || coin->second.IsSpent()) {\n            input_errors[i] = \"Input not found or already spent\";\n            continue;\n        }\n        const CScript& prevPubKey = coin->second.out.scriptPubKey;\n        const CAmount& amount = coin->second.out.nValue;\n\n        SignatureData sigdata = DataFromTransaction(mtx, i, coin->second.out);\n        \/\/ Only sign SIGHASH_SINGLE if there's a corresponding output:\n        if (!fHashSingle || (i < mtx.vout.size())) {\n            ProduceSignature(*keystore, MutableTransactionSignatureCreator(&mtx, i, amount, nHashType), prevPubKey, sigdata);\n        }\n\n        UpdateInput(txin, sigdata);\n\n        \/\/ amount must be specified for valid segwit signature\n        if (amount == MAX_MONEY && !txin.scriptWitness.IsNull()) {\n            input_errors[i] = \"Missing amount\";\n            continue;\n        }\n\n        ScriptError serror = SCRIPT_ERR_OK;\n        if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount), &serror)) {\n            if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {\n                \/\/ Unable to sign input and verification failed (possible attempt to partially sign).\n                input_errors[i] = \"Unable to sign input, invalid stack size (possibly missing key)\";\n            } else if (serror == SCRIPT_ERR_SIG_NULLFAIL) {\n                \/\/ Verification failed (possibly due to insufficient signatures).\n                input_errors[i] = \"CHECK(MULTI)SIG failing with non-zero signature (possibly need more signatures)\";\n            } else {\n                input_errors[i] = ScriptErrorString(serror);\n            }\n        } else {\n            \/\/ If this input succeeds, make sure there is no error set for it\n            input_errors.erase(i);\n        }\n    }\n    return input_errors.empty();\n}\n","avg_line_length":41.1121495327,"max_line_length":269,"alphanum_fraction":0.6729256649,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3873,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/**\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include <algorithm>\n#include <cstring>\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/algorithm\/string\/replace.hpp>\n#include <gtest\/gtest.h>\n#include <sstream>\n\n#include \"Debug.h\"\n#include \"VerifyUtil.h\"\n\nDexClass* find_class_named(const DexClasses& classes, const char* name) {\n  auto it = std::find_if(classes.begin(), classes.end(), [&name](DexClass* cls){\n    return !strcmp(name, cls->get_name()->c_str());\n  });\n  return it == classes.end() ? nullptr : *it;\n}\n\nDexMethod* find_vmethod_named(const DexClass& cls, const char* name) {\n  auto vmethods = cls.get_vmethods();\n  auto it =\n      std::find_if(vmethods.begin(), vmethods.end(), [&name](DexMethod* m) {\n        return strcmp(name, m->get_name()->c_str()) == 0;\n      });\n  return it == vmethods.end() ? nullptr : *it;\n}\n\nDexMethod* find_dmethod_named(const DexClass& cls, const char* name) {\n  auto dmethods = cls.get_dmethods();\n  auto it =\n      std::find_if(dmethods.begin(), dmethods.end(), [&name](DexMethod* m) {\n        return strcmp(name, m->get_name()->c_str()) == 0;\n      });\n  return it == dmethods.end() ? nullptr : *it;\n}\n\nDexMethod* find_method_named(const DexClass& cls, const char* name) {\n  auto ret = find_dmethod_named(cls, name);\n  if (ret != nullptr) {\n    return ret;\n  }\n  return find_vmethod_named(cls, name);\n}\n\nDexOpcodeMethod* find_invoke(const DexMethod* m, DexOpcode opcode,\n    const char* target_mname) {\n  auto insns = m->get_dex_code()->get_instructions();\n  return find_invoke(insns.begin(), insns.end(), opcode, target_mname);\n}\n\nDexOpcodeMethod* find_invoke(\n    std::vector<DexInstruction*>::iterator begin,\n    std::vector<DexInstruction*>::iterator end,\n    DexOpcode opcode,\n    const char* target_mname) {\n  auto it = std::find_if(begin, end,\n    [opcode, target_mname](DexInstruction* insn) {\n      if (insn->opcode() != opcode) {\n        return false;\n      }\n      auto mname =\n        static_cast<DexOpcodeMethod*>(insn)->get_method()->get_name();\n      return mname == DexString::get_string(target_mname);\n    });\n  return it == end ? nullptr : static_cast<DexOpcodeMethod*>(*it);\n}\n\n\/\/ Given a semicolon delimited list of extracted files from the APK, return a\n\/\/ map of the original APK's file path to its path on disk.\nResourceFiles decode_resource_paths(const char* location, const char* suffix) {\n  ResourceFiles files;\n  std::istringstream input;\n  input.str(location);\n  for (std::string file_path; std::getline(input, file_path, ':');) {\n    auto pos = file_path.rfind(\"\/\");\n    always_assert(pos >= 0 && pos + 1 < file_path.length());\n    auto directory = file_path.substr(0, pos);\n    if (boost::algorithm::ends_with(directory, suffix)) {\n      auto original_name = file_path.substr(pos + 1);\n      \/\/ Undo simple escaping at buck_imports\/redex_utils\n      boost::replace_all(original_name, \"zC\", \":\");\n      boost::replace_all(original_name, \"zS\", \"\/\");\n      boost::replace_all(original_name, \"zZ\", \"z\");\n      files.emplace(original_name, file_path);\n    }\n  }\n  return files;\n}\n\nDexInstruction* find_instruction(DexMethod* m, DexOpcode opcode) {\n  auto& insns = m->get_dex_code()->get_instructions();\n  auto it =\n      std::find_if(insns.begin(), insns.end(), [opcode](DexInstruction* insn) {\n        return insn->opcode() == opcode;\n      });\n  return it == insns.end() ? nullptr : *it;\n}\n\nvoid verify_type_erased(const DexClass* cls, size_t num_dmethods) {\n  ASSERT_NE(cls, nullptr);\n  auto dmethods = cls->get_dmethods();\n  ASSERT_EQ(dmethods.size(), num_dmethods);\n  for (auto m : dmethods) {\n    ASSERT_FALSE(is_init(m));\n    ASSERT_NE(m->c_str(), \"<init>\");\n  }\n  auto vmethods = cls->get_vmethods();\n  ASSERT_TRUE(vmethods.empty());\n}\n","avg_line_length":33.3879310345,"max_line_length":80,"alphanum_fraction":0.6700232378,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1694,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <unistd.h>\n#include <cstddef>\n#include <set>\n#include <string>\n#include <vector>\n#include <iostream>\n\n#include \"process.h\"\n#include \"processor.h\"\n#include \"system.h\"\n#include \"linux_parser.h\"\n\nusing std::set;\nusing std::size_t;\nusing std::string;\nusing std::vector;\n\n\/\/ TODO: Return the system's CPU\nProcessor& System::Cpu() { \n    return cpu_; \n}\n\n\/\/ TODO: Return a container composed of the system's processes\nvector<Process>& System::Processes() { \n    \/\/ PID list may be diffrent from previous. Empty the container\n    processes_ = {};\n\n    std::vector<int> pids = LinuxParser::Pids();\n\n    for(int pid: pids){\n        processes_.push_back(Process(pid));\n    }\n\n    \/\/ for (int pid: pids){\n    \/\/     std::cout << \"PID: \" << pid << \". \";\n    \/\/ }\n\n\n    std::sort(processes_.begin(), processes_.end(), [](auto &process1, auto &process2){\n        return process1 > process2;\n    });\n\n\n    return processes_; \n}\n\n\/\/ Return the system's kernel identifier (string)\nstd::string System::Kernel() { \n    return LinuxParser::Kernel();\n}\n\n\/\/ Return the system's memory utilization\nfloat System::MemoryUtilization() { \n    return LinuxParser::MemoryUtilization();\n}\n\n\/\/ Return the operating system name\nstd::string System::OperatingSystem() { \n    return LinuxParser::OperatingSystem();\n}\n\n\/\/ Return the number of processes actively running on the system\nint System::RunningProcesses() { \n    return LinuxParser::RunningProcesses();\n}\n\n\/\/ Return the total number of processes on the system\nint System::TotalProcesses() { \n    return LinuxParser::TotalProcesses();\n}\n\n\/\/ Return the number of seconds since the system started running\nlong System::UpTime() { \n    return LinuxParser::UpTime();\n}","avg_line_length":22.5866666667,"max_line_length":87,"alphanum_fraction":0.6759149941,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6282,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/**\n *    Copyright (C) 2012-2014 MongoDB Inc.\n *\n *    This program is free software: you can redistribute it and\/or  modify\n *    it under the terms of the GNU Affero General Public License, version 3,\n *    as published by the Free Software Foundation.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU Affero General Public License for more details.\n *\n *    You should have received a copy of the GNU Affero General Public License\n *    along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *    As a special exception, the copyright holders give permission to link the\n *    code of portions of this program with the OpenSSL library under certain\n *    conditions as described in each individual source file and distribute\n *    linked combinations including the program with the OpenSSL library. You\n *    must comply with the GNU Affero General Public License in all respects for\n *    all of the code used other than as permitted herein. If you modify file(s)\n *    with this exception, you may extend this exception to your version of the\n *    file(s), but you are not obligated to do so. If you do not wish to do so,\n *    delete this exception statement from your version. If you delete this\n *    exception statement from all source files in the program, then also delete\n *    it in the license file.\n *\/\n\n#define MONGO_LOG_DEFAULT_COMPONENT ::mongol::logger::LogComponent::kStorage\n\n#include \"mongol\/platform\/basic.h\"\n\n#include \"mongol\/db\/catalog\/database_holder.h\"\n\n#include \"mongol\/db\/audit.h\"\n#include \"mongol\/db\/auth\/auth_index_d.h\"\n#include \"mongol\/db\/background.h\"\n#include \"mongol\/db\/client.h\"\n#include \"mongol\/db\/clientcursor.h\"\n#include \"mongol\/db\/catalog\/database.h\"\n#include \"mongol\/db\/catalog\/database_catalog_entry.h\"\n#include \"mongol\/db\/service_context.h\"\n#include \"mongol\/db\/operation_context.h\"\n#include \"mongol\/db\/storage\/storage_engine.h\"\n#include \"mongol\/util\/log.h\"\n\nnamespace mongol {\n\nusing std::set;\nusing std::string;\nusing std::stringstream;\n\nnamespace {\n\nStringData _todb(StringData ns) {\n    size_t i = ns.find('.');\n    if (i == std::string::npos) {\n        uassert(13074, \"db name can't be empty\", ns.size());\n        return ns;\n    }\n\n    uassert(13075, \"db name can't be empty\", i > 0);\n\n    const StringData d = ns.substr(0, i);\n    uassert(13280, \"invalid db name: \" + ns.toString(), NamespaceString::validDBName(d));\n\n    return d;\n}\n\n\nDatabaseHolder _dbHolder;\n\n}  \/\/ namespace\n\n\nDatabaseHolder& dbHolder() {\n    return _dbHolder;\n}\n\n\nDatabase* DatabaseHolder::get(OperationContext* txn, StringData ns) const {\n    const StringData db = _todb(ns);\n    invariant(txn->lockState()->isDbLockedForMode(db, MODE_IS));\n\n    stdx::lock_guard<SimpleMutex> lk(_m);\n    DBs::const_iterator it = _dbs.find(db);\n    if (it != _dbs.end()) {\n        return it->second;\n    }\n\n    return NULL;\n}\n\nDatabase* DatabaseHolder::openDb(OperationContext* txn, StringData ns, bool* justCreated) {\n    const StringData dbname = _todb(ns);\n    invariant(txn->lockState()->isDbLockedForMode(dbname, MODE_X));\n\n    Database* db = get(txn, ns);\n    if (db) {\n        if (justCreated) {\n            *justCreated = false;\n        }\n\n        return db;\n    }\n\n    \/\/ Check casing\n    const string duplicate = Database::duplicateUncasedName(dbname.toString());\n    if (!duplicate.empty()) {\n        stringstream ss;\n        ss << \"db already exists with different case already have: [\" << duplicate\n           << \"] trying to create [\" << dbname.toString() << \"]\";\n        uasserted(ErrorCodes::DatabaseDifferCase, ss.str());\n    }\n\n    StorageEngine* storageEngine = getGlobalServiceContext()->getGlobalStorageEngine();\n    invariant(storageEngine);\n\n    DatabaseCatalogEntry* entry = storageEngine->getDatabaseCatalogEntry(txn, dbname);\n    invariant(entry);\n    const bool exists = entry->exists();\n    if (!exists) {\n        audit::logCreateDatabase(&cc(), dbname);\n    }\n\n    if (justCreated) {\n        *justCreated = !exists;\n    }\n\n    \/\/ Do this outside of the scoped lock, because database creation does transactional\n    \/\/ operations which may block. Only one thread can be inside this method for the same DB\n    \/\/ name, because of the requirement for X-lock on the database when we enter. So there is\n    \/\/ no way we can insert two different databases for the same name.\n    db = new Database(txn, dbname, entry);\n\n    stdx::lock_guard<SimpleMutex> lk(_m);\n    _dbs[dbname] = db;\n\n    return db;\n}\n\nvoid DatabaseHolder::close(OperationContext* txn, StringData ns) {\n    \/\/ TODO: This should be fine if only a DB X-lock\n    invariant(txn->lockState()->isW());\n\n    const StringData dbName = _todb(ns);\n\n    stdx::lock_guard<SimpleMutex> lk(_m);\n\n    DBs::const_iterator it = _dbs.find(dbName);\n    if (it == _dbs.end()) {\n        return;\n    }\n\n    it->second->close(txn);\n    delete it->second;\n    _dbs.erase(it);\n\n    getGlobalServiceContext()->getGlobalStorageEngine()->closeDatabase(txn, dbName.toString());\n}\n\nbool DatabaseHolder::closeAll(OperationContext* txn, BSONObjBuilder& result, bool force) {\n    invariant(txn->lockState()->isW());\n\n    stdx::lock_guard<SimpleMutex> lk(_m);\n\n    set<string> dbs;\n    for (DBs::const_iterator i = _dbs.begin(); i != _dbs.end(); ++i) {\n        dbs.insert(i->first);\n    }\n\n    BSONArrayBuilder bb(result.subarrayStart(\"dbs\"));\n    int nNotClosed = 0;\n    for (set<string>::iterator i = dbs.begin(); i != dbs.end(); ++i) {\n        string name = *i;\n\n        LOG(2) << \"DatabaseHolder::closeAll name:\" << name;\n\n        if (!force && BackgroundOperation::inProgForDb(name)) {\n            log() << \"WARNING: can't close database \" << name\n                  << \" because a bg job is in progress - try killOp command\";\n            nNotClosed++;\n            continue;\n        }\n\n        Database* db = _dbs[name];\n        db->close(txn);\n        delete db;\n\n        _dbs.erase(name);\n\n        getGlobalServiceContext()->getGlobalStorageEngine()->closeDatabase(txn, name);\n\n        bb.append(name);\n    }\n\n    bb.done();\n    if (nNotClosed) {\n        result.append(\"nNotClosed\", nNotClosed);\n    }\n\n    return true;\n}\n}\n","avg_line_length":30.643902439,"max_line_length":95,"alphanum_fraction":0.6628462273,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":15598,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":366.0,"content":"#include \"optionsmodel.h\"\n\n#include <QDebug>\n#include <QSettings>\n#include <univalue.h>\n\n#include \"bitcoinunits.h\"\n#include \"guiutil.h\"\n#include \"init.h\"\n#include \"miner.h\"\n#include \"wallet\/walletdb.h\"\n\nOptionsModel::OptionsModel(QObject *parent) :\n    QAbstractListModel(parent)\n{\n    Init();\n}\n\nbool static ApplyProxySettings()\n{\n    QSettings settings;\n    CService addrProxy(settings.value(\"addrProxy\", \"127.0.0.1:9050\").toString().toStdString());\n    if (!settings.value(\"fUseProxy\", false).toBool()) {\n        addrProxy = CService();\n        return false;\n    }\n    if (!addrProxy.IsValid())\n        return false;\n    if (!IsLimited(NET_IPV4))\n        SetProxy(NET_IPV4, addrProxy);\n    if (!IsLimited(NET_IPV6))\n        SetProxy(NET_IPV6, addrProxy);\n    SetNameProxy(addrProxy);\n    \n    return true;\n}\n\nvoid OptionsModel::Init()\n{\n    QSettings settings;\n\n    \/\/ These are Qt-only settings:\n    nDisplayUnit = settings.value(\"nDisplayUnit\", BitcoinUnits::BTC).toInt();\n    fStartAtStartup = settings.value(\"fStartAtStartup\", false).toBool();\n    fStartMin = settings.value(\"fStartMin\", true).toBool();\n    fMinimizeToTray = settings.value(\"fMinimizeToTray\", false).toBool();\n    fDisableTrxNotifications = settings.value(\"fDisableTrxNotifications\", false).toBool();\n    fDisablePollNotifications = settings.value(\"fDisablePollNotifications\", false).toBool();\n    bDisplayAddresses = settings.value(\"bDisplayAddresses\", false).toBool();\n    fMinimizeOnClose = settings.value(\"fMinimizeOnClose\", false).toBool();\n    fConfirmOnClose = settings.value(\"fConfirmOnClose\", false).toBool();\n    fCoinControlFeatures = settings.value(\"fCoinControlFeatures\", false).toBool();\n    fLimitTxnDisplay = settings.value(\"fLimitTxnDisplay\", false).toBool();\n    fMaskValues = settings.value(\"fMaskValues\", false).toBool();\n    limitTxnDate = settings.value(\"limitTxnDate\", QDate()).toDate();\n    nReserveBalance = settings.value(\"nReserveBalance\").toLongLong();\n    language = settings.value(\"language\", \"\").toString();\n    walletStylesheet = settings.value(\"walletStylesheet\", \"dark\").toString();\n\n    \/\/ These are shared with core Bitcoin; we want\n    \/\/ command-line options to override the GUI settings:\n    if (settings.contains(\"fUseUPnP\")) {\n        gArgs.SoftSetBoolArg(\"-upnp\", settings.value(\"fUseUPnP\").toBool());\n    }\n    if (settings.contains(\"addrProxy\") && settings.value(\"fUseProxy\").toBool()) {\n        gArgs.SoftSetArg(\"-proxy\", settings.value(\"addrProxy\").toString().toStdString());\n    }\n    if (!language.isEmpty()) {\n        gArgs.SoftSetArg(\"-lang\", language.toStdString());\n    }\n    if (settings.contains(\"fDisableUpdateCheck\")) {\n        gArgs.SoftSetBoolArg(\"-disableupdatecheck\", settings.value(\"fDisableUpdateCheck\").toBool());\n    }\n    if (settings.contains(\"dataDir\") && dataDir != GUIUtil::getDefaultDataDirectory()) {\n        gArgs.SoftSetArg(\"-datadir\", GUIUtil::qstringToBoostPath(settings.value(\"dataDir\").toString()).string());\n    }\n}\n\nint OptionsModel::rowCount(const QModelIndex & parent) const\n{\n    return OptionIDRowCount;\n}\n\nQVariant OptionsModel::data(const QModelIndex & index, int role) const\n{\n    if(role == Qt::EditRole)\n    {\n        QSettings settings;\n        switch(index.row())\n        {\n        case StartAtStartup:\n            return QVariant(fStartAtStartup);\n        case StartMin:\n            return QVariant(fStartMin);\n        case MinimizeToTray:\n            return QVariant(fMinimizeToTray);\n        case ConfirmOnClose:\n            return QVariant(fConfirmOnClose);\n        case DisableTrxNotifications:\n            return QVariant(fDisableTrxNotifications);\n        case DisablePollNotifications:\n            return QVariant(fDisablePollNotifications);\n        case MapPortUPnP:\n            return settings.value(\"fUseUPnP\", gArgs.GetBoolArg(\"-upnp\", true));\n        case MinimizeOnClose:\n            return QVariant(fMinimizeOnClose);\n        case ProxyUse:\n            return settings.value(\"fUseProxy\", false);\n        case ProxyIP: {\n            proxyType proxy;\n            if (GetProxy(NET_IPV4, proxy))\n                return QVariant(QString::fromStdString(proxy.ToStringIP()));\n            else\n                return QVariant(QString::fromStdString(\"127.0.0.1\"));\n        }\n        case ProxyPort: {\n            proxyType proxy;\n            if (GetProxy(NET_IPV4, proxy))\n                return QVariant(proxy.GetPort());\n            else\n                return QVariant(9050);\n        }\n        case ReserveBalance:\n            return QVariant((qint64) nReserveBalance);\n        case DisplayUnit:\n            return QVariant(nDisplayUnit);\n\t\tcase DisplayAddresses:\n            return QVariant(bDisplayAddresses);\n        case Language:\n            return settings.value(\"language\", \"\");\n        case WalletStylesheet:\n            return settings.value(\"walletStylesheet\", \"dark\");\n        case CoinControlFeatures:\n            return QVariant(fCoinControlFeatures);\n        case LimitTxnDisplay:\n            return QVariant(fLimitTxnDisplay);\n        case MaskValues:\n            return QVariant(fMaskValues);\n        case LimitTxnDate:\n            return QVariant(limitTxnDate);\n        case DisableUpdateCheck:\n            return QVariant(gArgs.GetBoolArg(\"-disableupdatecheck\", false));\n        case DataDir:\n            return settings.value(\"dataDir\", QString::fromStdString(gArgs.GetArg(\"-datadir\", GetDataDir().string())));\n        case EnableStaking:\n            \/\/ This comes from the core and is a read-write setting (see below).\n            return QVariant(gArgs.GetBoolArg(\"-staking\", true));\n        case EnableStakeSplit:\n            \/\/ This comes from the core and is a read-write setting (see below).\n            return QVariant(gArgs.GetBoolArg(\"-enablestakesplit\"));\n        case StakingEfficiency:\n            \/\/ This comes from the core and is a read-write setting (see below).\n            return QVariant((double) gArgs.GetArg(\"-stakingefficiency\", (int64_t) 90));\n        case MinStakeSplitValue:\n            \/\/ This comes from the core and is a read-write setting (see below).\n            return QVariant((qint64) gArgs.GetArg(\"-minstakesplitvalue\", MIN_STAKE_SPLIT_VALUE_GRC));\n        case ContractChangeToInput:\n            \/\/ This comes from the core and is a read-write setting (see below).\n            return QVariant(gArgs.GetBoolArg(\"-contractchangetoinputaddress\", false));\n        default:\n            return QVariant();\n        }\n    }\n    return QVariant();\n}\n\nbool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)\n{\n    bool successful = true; \/* set to false on parse error *\/\n    if(role == Qt::EditRole)\n    {\n        QSettings settings;\n        switch(index.row())\n        {\n        case StartAtStartup:\n            if (fStartAtStartup != value.toBool())\n            {\n                fStartAtStartup = value.toBool();\n                settings.setValue(\"fStartAtStartup\", fStartAtStartup);\n                successful = GUIUtil::SetStartOnSystemStartup(fStartAtStartup, fStartMin);\n            }\n            break;\n        case StartMin:\n            if (fStartMin != value.toBool())\n            {\n                fStartMin = value.toBool();\n                settings.setValue(\"fStartMin\", fStartMin);\n                successful = GUIUtil::SetStartOnSystemStartup(fStartAtStartup, fStartMin);\n            }\n            break;\n        case MinimizeToTray:\n            fMinimizeToTray = value.toBool();\n            settings.setValue(\"fMinimizeToTray\", fMinimizeToTray);\n            break;\n        case ConfirmOnClose:\n            fConfirmOnClose = value.toBool();\n            settings.setValue(\"fConfirmOnClose\", fConfirmOnClose);\n            break;\n        case DisableTrxNotifications:\n            fDisableTrxNotifications = value.toBool();\n            settings.setValue(\"fDisableTrxNotifications\", fDisableTrxNotifications);\n            break;\n        case DisablePollNotifications:\n            fDisablePollNotifications = value.toBool();\n            settings.setValue(\"fDisablePollNotifications\", fDisablePollNotifications);\n            break;\n        case MapPortUPnP:\n            fUseUPnP = value.toBool();\n            settings.setValue(\"fUseUPnP\", fUseUPnP);\n            MapPort();\n            break;\n        case MinimizeOnClose:\n            fMinimizeOnClose = value.toBool();\n            settings.setValue(\"fMinimizeOnClose\", fMinimizeOnClose);\n            break;\n        case ProxyUse:\n            settings.setValue(\"fUseProxy\", value.toBool());\n            ApplyProxySettings();\n            break;\n        case ProxyIP: {\n            proxyType proxy;\n            proxy = CService(\"127.0.0.1\", 9050);\n            GetProxy(NET_IPV4, proxy);\n\n            CNetAddr addr(value.toString().toStdString());\n            proxy.SetIP(addr);\n            settings.setValue(\"addrProxy\", proxy.ToStringIPPort().c_str());\n            successful = ApplyProxySettings();\n        }\n        break;\n        case ProxyPort: {\n            proxyType proxy;\n            proxy = CService(\"127.0.0.1\", 9050);\n            GetProxy(NET_IPV4, proxy);\n\n            proxy.SetPort(value.toInt());\n            settings.setValue(\"addrProxy\", proxy.ToStringIPPort().c_str());\n            successful = ApplyProxySettings();\n        }\n        break;\n        case ReserveBalance:\n            nReserveBalance = value.toLongLong();\n            settings.setValue(\"nReserveBalance\", (qint64) nReserveBalance);\n            emit reserveBalanceChanged(nReserveBalance);\n            break;\n        case DisplayUnit:\n            nDisplayUnit = value.toInt();\n            settings.setValue(\"nDisplayUnit\", nDisplayUnit);\n            emit displayUnitChanged(nDisplayUnit);\n            break;\n\t\tcase DisplayAddresses:\n             bDisplayAddresses = value.toBool();\n             settings.setValue(\"bDisplayAddresses\", bDisplayAddresses);\n             break;\n        case Language:\n            settings.setValue(\"language\", value);\n            break;\n        case WalletStylesheet:\n            walletStylesheet = value.toString();\n            settings.setValue(\"walletStylesheet\", walletStylesheet);\n            emit walletStylesheetChanged(walletStylesheet);\n            break;\n        case CoinControlFeatures: {\n            fCoinControlFeatures = value.toBool();\n            settings.setValue(\"fCoinControlFeatures\", fCoinControlFeatures);\n            emit coinControlFeaturesChanged(fCoinControlFeatures);\n            }\n            break;\n        case LimitTxnDisplay:\n            fLimitTxnDisplay = value.toBool();\n            settings.setValue(\"fLimitTxnDisplay\", fLimitTxnDisplay);\n            emit LimitTxnDisplayChanged(fLimitTxnDisplay);\n            break;\n        case MaskValues:\n            fMaskValues = value.toBool();\n            settings.setValue(\"fMaskValues\", fMaskValues);\n            emit MaskValuesChanged(fMaskValues);\n            break;\n        case LimitTxnDate:\n            limitTxnDate = value.toDate();\n            settings.setValue(\"limitTxnDate\", limitTxnDate);\n            break;\n        case DisableUpdateCheck:\n            gArgs.ForceSetArg(\"-disableupdatecheck\", value.toBool() ? \"1\" : \"0\");\n            settings.setValue(\"fDisableUpdateCheck\", value.toBool());\n            break;\n        case DataDir:\n            \/\/ There is no SetArgument here, because the core data directory cannot\n            \/\/ be changed while the wallet is running.\n            dataDir = value.toString();\n            settings.setValue(\"dataDir\", dataDir);\n            break;\n        case EnableStaking:\n            \/\/ This is a core setting stored in the read-write settings file and once set will override the read-only\n            \/\/config file.\n            gArgs.ForceSetArg(\"-staking\", value.toBool() ? \"1\" : \"0\");\n            updateRwSetting(\"staking\", gArgs.GetBoolArg(\"-staking\", true));\n            break;\n        case EnableStakeSplit:\n            \/\/ This is a core setting stored in the read-write settings file and once set will override the read-only\n            \/\/config file.\n            \/\/fStakeSplitEnabled = value.toBool();\n            gArgs.ForceSetArg(\"-enablestakesplit\", value.toBool() ? \"1\" : \"0\");\n            updateRwSetting(\"enablestakesplit\", gArgs.GetBoolArg(\"-enablestakesplit\"));\n            break;\n        case StakingEfficiency:\n            \/\/ This is a core setting stored in the read-write settings file and once set will override the read-only\n            \/\/config file.\n            gArgs.ForceSetArg(\"-stakingefficiency\", value.toString().toStdString());\n            updateRwSetting(\"stakingefficiency\", gArgs.GetArg(\"-stakingefficiency\", 90));\n            break;\n        case MinStakeSplitValue:\n            \/\/ This is a core setting stored in the read-write settings file and once set will override the read-only\n            \/\/config file.\n            gArgs.ForceSetArg(\"-minstakesplitvalue\", value.toString().toStdString());\n            updateRwSetting(\"minstakesplitvalue\", gArgs.GetArg(\"-minstakesplitvalue\", MIN_STAKE_SPLIT_VALUE_GRC));\n            break;\n        case ContractChangeToInput:\n            \/\/ This is a core setting stored in the read-write settings file and once set will override the read-only\n            \/\/config file.\n            gArgs.ForceSetArg(\"-contractchangetoinputaddress\", value.toBool() ? \"1\" : \"0\");\n            updateRwSetting(\"contractchangetoinputaddress\", gArgs.GetBoolArg(\"contractchangetoinputaddress\"));\n            break;\n        default:\n            break;\n        }\n    }\n    emit dataChanged(index, index);\n\n    return successful;\n}\n\nqint64 OptionsModel::getTransactionFee()\n{\n    return nTransactionFee;\n}\n\nqint64 OptionsModel::getReserveBalance()\n{\n    return nReserveBalance;\n}\n\nbool OptionsModel::getCoinControlFeatures()\n{\n    return fCoinControlFeatures;\n}\n\nvoid OptionsModel::toggleCoinControlFeatures()\n{\n    setData(QAbstractItemModel::createIndex(CoinControlFeatures, 0), !fCoinControlFeatures, Qt::EditRole);\n}\n\nbool OptionsModel::getLimitTxnDisplay()\n{\n    return fLimitTxnDisplay;\n}\n\nbool OptionsModel::getMaskValues()\n{\n    return fMaskValues;\n}\n\nQDate OptionsModel::getLimitTxnDate()\n{\n    return limitTxnDate;\n}\n\nint64_t OptionsModel::getLimitTxnDateTime()\n{\n#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)\n    QDateTime limitTxnDateTime(limitTxnDate);\n#else\n    QDateTime limitTxnDateTime = limitTxnDate.startOfDay();\n#endif\n\n    return limitTxnDateTime.toMSecsSinceEpoch() \/ 1000;\n}\n\nbool OptionsModel::getStartAtStartup()\n{\n    return fStartAtStartup;\n}\n\nbool OptionsModel::getStartMin()\n{\n    return fStartMin;\n}\n\nbool OptionsModel::getMinimizeToTray()\n{\n    return fMinimizeToTray;\n}\n\nbool OptionsModel::getConfirmOnClose()\n{\n    return fConfirmOnClose;\n}\n\nbool OptionsModel::getDisableTrxNotifications()\n{\n    return fDisableTrxNotifications;\n}\n\nbool OptionsModel::getDisablePollNotifications()\n{\n    return fDisablePollNotifications;\n}\n\nbool OptionsModel::getMinimizeOnClose()\n{\n    return fMinimizeOnClose;\n}\n\nint OptionsModel::getDisplayUnit()\n{\n    return nDisplayUnit;\n}\n\nbool OptionsModel::getDisplayAddresses()\n{\n    return bDisplayAddresses;\n}\n\nQString OptionsModel::getCurrentStyle()\n{\n    \/\/ Native stylesheet removed for now:\n    if (walletStylesheet == \"native\") {\n        return \"dark\";\n    }\n\n    return walletStylesheet;\n}\n\nvoid OptionsModel::setCurrentStyle(QString theme)\n{\n    setData(QAbstractItemModel::createIndex(WalletStylesheet, 0), theme, Qt::EditRole);\n}\n\nvoid OptionsModel::setMaskValues(bool privacy_mode)\n{\n    setData(QAbstractItemModel::createIndex(MaskValues, 0), privacy_mode, Qt::EditRole);\n}\n\nQString OptionsModel::getDataDir()\n{\n    return dataDir;\n}\n","avg_line_length":34.8169642857,"max_line_length":118,"alphanum_fraction":0.6375176305,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7299,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <sstream>\n\n#include \"Tools\/Exception\/exception.hpp\"\n#include \"Tools\/general_utils.h\"\n\n#include \"Puncturer_turbo.hpp\"\n\nusing namespace aff3ct;\nusing namespace aff3ct::module;\n\ntemplate <typename B, typename Q>\nPuncturer_turbo<B,Q>\n::Puncturer_turbo(const int &K,\n                  const int &N,\n                  const int &tail_bits,\n                  const std::vector<std::vector<bool>>& pattern_bits,\n                  const bool buff_enc,\n                  const int n_frames)\n: Puncturer<B,Q>(K, N, K * 3 + tail_bits, n_frames),\n  pattern_bits(pattern_bits), buff_enc(buff_enc), tail_bits(tail_bits)\n{\n\tconst std::string name = \"Puncturer_turbo\";\n\tthis->set_name(name);\n\n\tif (tail_bits < 0)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'tail_bits' has to be positive ('tail_bits' = \" << tail_bits << \").\";\n\t\tthrow tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (this->N != compute_N(K, tail_bits, pattern_bits))\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'N' has to be equal to ('K' \/ 'period') * 'bit_count' + 'tail_bits' ('N' = \" << N\n\t\t        << \", 'tail_bits' = \" << tail_bits << \", 'K' = \" << K << \", 'period' = \" << get_period(pattern_bits)\n\t\t        << \", 'pattern' = \" << display_pattern(pattern_bits) << \").\";\n\t\tthrow tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n}\n\ntemplate <typename B, typename Q>\nvoid Puncturer_turbo<B,Q>\n::_puncture(const B *X_N1, B *X_N2, const int frame_id) const\n{\n\tconst auto period = get_period(pattern_bits);\n\n\tauto k = 0;\n\tif (this->buff_enc)\n\t{\n\t\tint off[3] = {0, this->K + this->tail_bits\/4, this->N_cw - (this->K + this->tail_bits\/4)};\n\t\tfor (auto j = 0; j < 3; j++)\n\t\t{\n\t\t\tauto p = 0;\n\t\t\tauto o = off[j];\n\t\t\tfor (auto i = 0; i < this->K; i++)\n\t\t\t{\n\t\t\t\tif (pattern_bits[j][p])\n\t\t\t\t\tX_N2[k++] = X_N1[o +i];\n\t\t\t\tp = (p +1) % period;\n\t\t\t}\n\n\t\t\tif (j == 0)\n\t\t\t{\n\t\t\t\tstd::copy(X_N1 + o + this->K, X_N1 + o + this->K + this->tail_bits\/4, X_N2 + k);\n\t\t\t\tk += this->tail_bits\/4;\n\t\t\t}\n\t\t\telse if (j == 1)\n\t\t\t{\n\t\t\t\tstd::copy(X_N1 + o + this->K, X_N1 + o + this->K + this->tail_bits\/2, X_N2 + k);\n\t\t\t\tk += this->tail_bits\/2;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::copy(X_N1 + o + this->K, X_N1 + o + this->K + this->tail_bits\/4, X_N2 + k);\n\t\t\t\tk += this->tail_bits\/4;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tauto p = 0;\n\t\tfor (auto i = 0; i < this->K; i++)\n\t\t{\n\t\t\tif (pattern_bits[0][p]) X_N2[k++] = X_N1[i * 3 +0];\n\t\t\tif (pattern_bits[1][p]) X_N2[k++] = X_N1[i * 3 +1];\n\t\t\tif (pattern_bits[2][p]) X_N2[k++] = X_N1[i * 3 +2];\n\n\t\t\tp = (p +1) % period;\n\t\t}\n\n\t\tstd::copy(X_N1 + 3 * this->K, X_N1 + 3 * this->K + this->tail_bits, X_N2 + k);\n\t}\n}\n\ntemplate <typename B, typename Q>\nvoid Puncturer_turbo<B,Q>\n::_depuncture(const Q *Y_N1, Q *Y_N2, const int frame_id) const\n{\n\tconst auto period = get_period(pattern_bits);\n\n\tauto k = 0;\n\tif (this->buff_enc)\n\t{\n\t\tint off[3] = {0, this->K + this->tail_bits\/4, this->N_cw - (this->K + this->tail_bits\/4)};\n\t\tfor (auto j = 0; j < 3; j++)\n\t\t{\n\t\t\tauto p = 0;\n\t\t\tauto o = off[j];\n\t\t\tfor (auto i = 0; i < this->K; i++)\n\t\t\t{\n\t\t\t\tY_N2[o +i] = pattern_bits[j][p] ? Y_N1[k++] : (Q)0;\n\t\t\t\tp = (p +1) % period;\n\t\t\t}\n\n\t\t\tif (j == 0)\n\t\t\t{\n\t\t\t\tstd::copy(Y_N1 + k, Y_N1 + k + this->tail_bits\/4, Y_N2 + o + this->K);\n\t\t\t\tk += this->tail_bits\/4;\n\t\t\t}\n\t\t\telse if (j == 1)\n\t\t\t{\n\t\t\t\tstd::copy(Y_N1 + k, Y_N1 + k + this->tail_bits\/2, Y_N2 + o + this->K);\n\t\t\t\tk += this->tail_bits\/2;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::copy(Y_N1 + k, Y_N1 + k + this->tail_bits\/4, Y_N2 + o + this->K);\n\t\t\t\tk += this->tail_bits\/4;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tauto p = 0;\n\t\tfor (auto i = 0; i < this->K; i++)\n\t\t{\n\t\t\tY_N2[i * 3 +0] = pattern_bits[0][p] ? Y_N1[k++] : (Q)0;\n\t\t\tY_N2[i * 3 +1] = pattern_bits[1][p] ? Y_N1[k++] : (Q)0;\n\t\t\tY_N2[i * 3 +2] = pattern_bits[2][p] ? Y_N1[k++] : (Q)0;\n\n\t\t\tp = (p +1) % period;\n\t\t}\n\n\t\tstd::copy(Y_N1 + k, Y_N1 + k + this->tail_bits, Y_N2 + 3 * this->K);\n\t}\n}\n\ntemplate <typename B, typename Q>\nstd::string Puncturer_turbo<B,Q>\n::display_pattern(const std::vector<std::vector<bool>>& pattern_bits)\n{\n\tstd::string m;\n\n\tfor(auto &v : pattern_bits)\n\t{\n\t\tfor(const auto &vb : v)\n\t\t\tm += std::to_string(vb);\n\n\t\tm += \",\";\n\t}\n\n\tif (m.size())\n\t\tm.erase(m.size() -1);\n\n\treturn m;\n}\n\ntemplate <typename B, typename Q>\nunsigned Puncturer_turbo<B,Q>\n::get_period(const std::vector<std::vector<bool>>& pattern_bits)\n{\n\tif (pattern_bits.size() == 0)\n\t\treturn 0;\n\n\treturn (unsigned)pattern_bits.front().size();\n}\n\ntemplate <typename B, typename Q>\nunsigned Puncturer_turbo<B,Q>\n::get_bit_count(const std::vector<std::vector<bool>>& pattern_bits)\n{\n\tunsigned bit_count = 0;\n\tfor (unsigned i = 0; i < pattern_bits.size(); i++)\n\t\tfor (unsigned j = 0; j < pattern_bits[i].size(); j++)\n\t\t\tbit_count += pattern_bits[i][j] ? 1 : 0;\n\n\treturn bit_count;\n}\n\ntemplate <typename B, typename Q>\nvoid Puncturer_turbo<B,Q>\n::check_pattern(const int K, const std::vector<std::vector<bool>>& pattern_bits)\n{\n\tif (pattern_bits.size() != 3) \/\/ pattern_bits[0] == bit systematic, pattern_bits[1] == parity 1, pattern_bits[2] == bit parity 2\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'pattern' should give 3 different set delimited by a comma ('pattern' = \"\n\t\t        << display_pattern(pattern_bits) << \", 'pattern_bits.size()' = \" << pattern_bits.size() << \").\";\n\t\tthrow tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (pattern_bits[0].size() != pattern_bits[1].size() || pattern_bits[0].size() != pattern_bits[2].size())\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'pattern' sets have to contains an equal number of bits ('pattern' = \" << display_pattern(pattern_bits)\n\t\t        << \", 'pattern_bits[0].size()' = \" << pattern_bits[0].size()\n\t\t        << \", 'pattern_bits[1].size()' = \" << pattern_bits[1].size()\n\t\t        << \", 'pattern_bits[2].size()' = \" << pattern_bits[2].size() << \").\";\n\t\tthrow tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tauto period = get_period   (pattern_bits);\n\tbool allone = get_bit_count(pattern_bits) == period * pattern_bits.size();\n\n\tif (!allone && (K % period != 0))\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'period' has to be a multiple of 'K' or all bits must be at '1' ('period' = \" << period\n\t\t        << \", 'K' = \" << K << \", 'pattern' = \" << display_pattern(pattern_bits) << \").\";\n\t\tthrow tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n}\n\ntemplate <typename B, typename Q>\nint Puncturer_turbo<B,Q>\n::compute_N(const int K, const int tail_bits, const std::vector<std::vector<bool>>& pattern_bits)\n{\n\tcheck_pattern(K, pattern_bits);\n\n\tauto period    = get_period   (pattern_bits);\n\tauto bit_count = get_bit_count(pattern_bits);\n\n\tif (period)\n\t\treturn K * bit_count \/ period + tail_bits;\n\telse\n\t\treturn 0;\n}\n\n\/\/ ==================================================================================== explicit template instantiation\n#include \"Tools\/types.h\"\n#ifdef AFF3CT_MULTI_PREC\ntemplate class aff3ct::module::Puncturer_turbo<B_8,Q_8>;\ntemplate class aff3ct::module::Puncturer_turbo<B_16,Q_16>;\ntemplate class aff3ct::module::Puncturer_turbo<B_32,Q_32>;\ntemplate class aff3ct::module::Puncturer_turbo<B_64,Q_64>;\n#else\ntemplate class aff3ct::module::Puncturer_turbo<B,Q>;\n#endif\n\/\/ ==================================================================================== explicit template instantiation\n","avg_line_length":29.0796812749,"max_line_length":129,"alphanum_fraction":0.5917248938,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":518,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include <iostream>\n#include <unordered_map>\n\nusing namespace std;\n\nconst int mod = 1e9+7;\n\nint main(void) {\n\tint k;\n\tcin>>k;\n\tunordered_map<int, int> table;\n\n\twhile(k--) {\n\t\tint x;\n\t\tcin>>x;\n\t\tfor(int i=2; i<=x\/i; i++) {\n\t\t\twhile(x%i==0) {\n\t\t\t\tx = x\/i;\n\t\t\t\ttable[i]++;\n\t\t\t}\n\t\t}\n\t\tif(x>1) {\n\t\t\ttable[x]++;\n\t\t}\n\t}\n\n\tlong long res = 1;\n\tfor(auto prime:table){           \n\t\tint p = prime.first;\n\t\tint a = prime.second;\n\t\tlong long t = 1;\n\t\twhile(a--) {\n\t\t\tt = (t*p+1)%mod;\n\t\t}\n\t\tres = res*t%mod;\n\t}\n\tcout<<res<<endl;\n\n}\n\n","avg_line_length":12.6341463415,"max_line_length":34,"alphanum_fraction":0.5115830116,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3398,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":null,"content":"#include <QDebug>\n#include <QJsonDocument>\n#include <QJsonObject>\n#include <QMap>\n#include <QNetworkReply>\n#include <QString>\n#include <QStringList>\n#include <QUrl>\n#if QT_VERSION >= 0x050000\n#include <QUrlQuery>\n#endif\n\n#include \"o2facebook.h\"\n#include \"o0globals.h\"\n\nstatic const char *FbEndpoint = \"https:\/\/graph.facebook.com\/oauth\/authorize?display=touch\";\nstatic const char *FbTokenUrl = \"https:\/\/graph.facebook.com\/oauth\/access_token\";\nstatic const char *FbExpiresKey = \"expires_in\";\n\nO2Facebook::O2Facebook(QObject *parent): O2(parent) {\n    setRequestUrl(FbEndpoint);\n    setTokenUrl(FbTokenUrl);\n}\n\nvoid O2Facebook::onVerificationReceived(const QMap<QString, QString> response) {\n    qDebug() << \"O2Facebook::onVerificationReceived: Emitting closeBrowser()\";\n    Q_EMIT closeBrowser();\n\n    if (response.contains(\"error\")) {\n        qWarning() << \"O2Facebook::onVerificationReceived: Verification failed\";\n        foreach (QString key, response.keys()) {\n            qWarning() << \"O2Facebook::onVerificationReceived:\" << key << response.value(key);\n        }\n        Q_EMIT linkingFailed();\n        return;\n    }\n\n    \/\/ Save access code\n    setCode(response.value(O2_OAUTH2_GRANT_TYPE_CODE));\n\n    \/\/ Exchange access code for access\/refresh tokens\n    QUrl url(tokenUrl_);\n#if QT_VERSION < 0x050000\n    url.addQueryItem(O2_OAUTH2_CLIENT_ID, clientId_);\n    url.addQueryItem(O2_OAUTH2_CLIENT_SECRET, clientSecret_);\n    url.addQueryItem(O2_OAUTH2_SCOPE, scope_);\n    url.addQueryItem(O2_OAUTH2_GRANT_TYPE_CODE, code());\n    url.addQueryItem(O2_OAUTH2_REDIRECT_URI, redirectUri_);\n#else\n    QUrlQuery query(url);\n    query.addQueryItem(O2_OAUTH2_CLIENT_ID, clientId_);\n    query.addQueryItem(O2_OAUTH2_CLIENT_SECRET, clientSecret_);\n    query.addQueryItem(O2_OAUTH2_SCOPE, scope_);\n    query.addQueryItem(O2_OAUTH2_GRANT_TYPE_CODE, code());\n    query.addQueryItem(O2_OAUTH2_REDIRECT_URI, redirectUri_);\n    url.setQuery(query);\n#endif\n\n    QNetworkRequest tokenRequest(url);\n    QNetworkReply *tokenReply = manager_->get(tokenRequest);\n    timedReplies_.add(tokenReply);\n    connect(tokenReply, SIGNAL(finished()), this, SLOT(onTokenReplyFinished()), Qt::QueuedConnection);\n    connect(tokenReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onTokenReplyError(QNetworkReply::NetworkError)), Qt::QueuedConnection);\n}\n\nvoid O2Facebook::onTokenReplyFinished() {\n    qDebug() << \"O2Facebook::onTokenReplyFinished\";\n\n    QNetworkReply *tokenReply = qobject_cast<QNetworkReply *>(sender());\n    if (tokenReply->error() == QNetworkReply::NoError) {\n        \/\/ Process reply\n        QByteArray replyData = tokenReply->readAll();\n        QJsonDocument doc = QJsonDocument::fromJson(replyData);\n        const QJsonObject rootObject = doc.object();\n\n        QVariantMap reply;\n        for (const QString &key : rootObject.keys()) {\n            reply.insert(key, rootObject[key].toVariant());\n        }\n\n        \/\/ Interpret reply\n        setToken(reply.value(O2_OAUTH2_ACCESS_TOKEN, QString()).toString());\n        setExpires(reply.value(FbExpiresKey).toInt());\n        setRefreshToken(reply.value(O2_OAUTH2_REFRESH_TOKEN, QString()).toString());\n        setExtraTokens(reply);\n        timedReplies_.remove(tokenReply);\n        setLinked(true);\n        Q_EMIT linkingSucceeded();\n    } else {\n        qWarning() << \"O2Facebook::onTokenReplyFinished:\" << tokenReply->errorString();\n    }\n}\n","avg_line_length":36.5376344086,"max_line_length":150,"alphanum_fraction":0.7113007652,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2645,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\ufeff\/*\n* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\").\n* You may not use this file except in compliance with the License.\n* A copy of the License is located at\n*\n*  http:\/\/aws.amazon.com\/apache2.0\n*\n* or in the \"license\" file accompanying this file. This file is distributed\n* on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n* express or implied. See the License for the specific language governing\n* permissions and limitations under the License.\n*\/\n\n#include <aws\/appstream\/model\/SessionState.h>\n#include <aws\/core\/utils\/HashingUtils.h>\n#include <aws\/core\/Globals.h>\n#include <aws\/core\/utils\/EnumParseOverflowContainer.h>\n\nusing namespace Aws::Utils;\n\n\nnamespace Aws\n{\n  namespace AppStream\n  {\n    namespace Model\n    {\n      namespace SessionStateMapper\n      {\n\n        static const int ACTIVE_HASH = HashingUtils::HashString(\"ACTIVE\");\n        static const int PENDING_HASH = HashingUtils::HashString(\"PENDING\");\n        static const int EXPIRED_HASH = HashingUtils::HashString(\"EXPIRED\");\n\n\n        SessionState GetSessionStateForName(const Aws::String& name)\n        {\n          int hashCode = HashingUtils::HashString(name.c_str());\n          if (hashCode == ACTIVE_HASH)\n          {\n            return SessionState::ACTIVE;\n          }\n          else if (hashCode == PENDING_HASH)\n          {\n            return SessionState::PENDING;\n          }\n          else if (hashCode == EXPIRED_HASH)\n          {\n            return SessionState::EXPIRED;\n          }\n          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();\n          if(overflowContainer)\n          {\n            overflowContainer->StoreOverflow(hashCode, name);\n            return static_cast<SessionState>(hashCode);\n          }\n\n          return SessionState::NOT_SET;\n        }\n\n        Aws::String GetNameForSessionState(SessionState enumValue)\n        {\n          switch(enumValue)\n          {\n          case SessionState::ACTIVE:\n            return \"ACTIVE\";\n          case SessionState::PENDING:\n            return \"PENDING\";\n          case SessionState::EXPIRED:\n            return \"EXPIRED\";\n          default:\n            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();\n            if(overflowContainer)\n            {\n              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));\n            }\n\n            return \"\";\n          }\n        }\n\n      } \/\/ namespace SessionStateMapper\n    } \/\/ namespace Model\n  } \/\/ namespace AppStream\n} \/\/ namespace Aws\n","avg_line_length":30.0568181818,"max_line_length":92,"alphanum_fraction":0.6291115312,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":964,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\ufeff\/*\n* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\").\n* You may not use this file except in compliance with the License.\n* A copy of the License is located at\n*\n*  http:\/\/aws.amazon.com\/apache2.0\n*\n* or in the \"license\" file accompanying this file. This file is distributed\n* on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n* express or implied. See the License for the specific language governing\n* permissions and limitations under the License.\n*\/\n\n#include <aws\/chime\/model\/GetRoomRequest.h>\n#include <aws\/core\/utils\/json\/JsonSerializer.h>\n\n#include <utility>\n\nusing namespace Aws::Chime::Model;\nusing namespace Aws::Utils::Json;\nusing namespace Aws::Utils;\n\nGetRoomRequest::GetRoomRequest() : \n    m_accountIdHasBeenSet(false),\n    m_roomIdHasBeenSet(false)\n{\n}\n\nAws::String GetRoomRequest::SerializePayload() const\n{\n  return {};\n}\n\n\n\n\n","avg_line_length":24.7179487179,"max_line_length":78,"alphanum_fraction":0.744813278,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":48237,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"init.h\"\n#include \"util.h\"\n#include \"sync.h\"\n#include \"ui_interface.h\"\n#include \"base58.h\"\n#include \"bitcoinrpc.h\"\n#include \"db.h\"\n\n#undef printf\n#include <boost\/asio.hpp>\n#include <boost\/asio\/ip\/v6_only.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/iostreams\/concepts.hpp>\n#include <boost\/iostreams\/stream.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/asio\/ssl.hpp>\n#include <boost\/filesystem\/fstream.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <list>\n\n#define printf OutputDebugStringF\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::asio;\nusing namespace json_spirit;\n\nvoid ThreadRPCServer2(void* parg);\n\nstatic std::string strRPCUserColonPass;\n\nconst Object emptyobj;\n\nvoid ThreadRPCServer3(void* parg);\n\nstatic inline unsigned short GetDefaultRPCPort()\n{\n    return GetBoolArg(\"-testnet\", false) ? 30501 : 30500;\n}\n\nObject JSONRPCError(int code, const string& message)\n{\n    Object error;\n    error.push_back(Pair(\"code\", code));\n    error.push_back(Pair(\"message\", message));\n    return error;\n}\n\nvoid RPCTypeCheck(const Array& params,\n                  const list<Value_type>& typesExpected,\n                  bool fAllowNull)\n{\n    unsigned int i = 0;\n    BOOST_FOREACH(Value_type t, typesExpected)\n    {\n        if (params.size() <= i)\n            break;\n\n        const Value& v = params[i];\n        if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))\n        {\n            string err = strprintf(\"Expected type %s, got %s\",\n                                   Value_type_name[t], Value_type_name[v.type()]);\n            throw JSONRPCError(RPC_TYPE_ERROR, err);\n        }\n        i++;\n    }\n}\n\nvoid RPCTypeCheck(const Object& o,\n                  const map<string, Value_type>& typesExpected,\n                  bool fAllowNull)\n{\n    BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)\n    {\n        const Value& v = find_value(o, t.first);\n        if (!fAllowNull && v.type() == null_type)\n            throw JSONRPCError(RPC_TYPE_ERROR, strprintf(\"Missing %s\", t.first.c_str()));\n\n        if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))\n        {\n            string err = strprintf(\"Expected type %s for %s, got %s\",\n                                   Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);\n            throw JSONRPCError(RPC_TYPE_ERROR, err);\n        }\n    }\n}\n\nint64_t AmountFromValue(const Value& value)\n{\n    double dAmount = value.get_real();\n    if (dAmount <= 0.0 || dAmount > MAX_MONEY)\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid amount\");\n    int64_t nAmount = roundint64(dAmount * COIN);\n    if (!MoneyRange(nAmount))\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid amount\");\n    return nAmount;\n}\n\nValue ValueFromAmount(int64_t amount)\n{\n    return (double)amount \/ (double)COIN;\n}\n\nstd::string HexBits(unsigned int nBits)\n{\n    union {\n        int32_t nBits;\n        char cBits[4];\n    } uBits;\n    uBits.nBits = htonl((int32_t)nBits);\n    return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));\n}\n\n\n\/\/\n\/\/ Utilities: convert hex-encoded Values\n\/\/ (throws error if not hex).\n\/\/\nuint256 ParseHashV(const Value& v, string strName)\n{\n    string strHex;\n    if (v.type() == str_type)\n        strHex = v.get_str();\n    if (!IsHex(strHex)) \/\/ Note: IsHex(\"\") is false\n        throw JSONRPCError(RPC_INVALID_PARAMETER, strName+\" must be hexadecimal string (not '\"+strHex+\"')\");\n    uint256 result;\n    result.SetHex(strHex);\n    return result;\n}\n\nuint256 ParseHashO(const Object& o, string strKey)\n{\n    return ParseHashV(find_value(o, strKey), strKey);\n}\n\nvector<unsigned char> ParseHexV(const Value& v, string strName)\n{\n    string strHex;\n    if (v.type() == str_type)\n        strHex = v.get_str();\n    if (!IsHex(strHex))\n        throw JSONRPCError(RPC_INVALID_PARAMETER, strName+\" must be hexadecimal string (not '\"+strHex+\"')\");\n    return ParseHex(strHex);\n}\n\nvector<unsigned char> ParseHexO(const Object& o, string strKey)\n{\n    return ParseHexV(find_value(o, strKey), strKey);\n}\n\n\n\/\/\/\n\/\/\/ Note: This interface may still be subject to change.\n\/\/\/\n\nstring CRPCTable::help(string strCommand) const\n{\n    string strRet;\n    set<rpcfn_type> setDone;\n    for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)\n    {\n        const CRPCCommand *pcmd = mi->second;\n        string strMethod = mi->first;\n        \/\/ We already filter duplicates, but these deprecated screw up the sort order\n        if (strMethod.find(\"label\") != string::npos)\n            continue;\n        if (strCommand != \"\" && strMethod != strCommand)\n            continue;\n        try\n        {\n            Array params;\n            rpcfn_type pfn = pcmd->actor;\n            if (setDone.insert(pfn).second)\n                (*pfn)(params, true);\n        }\n        catch (std::exception& e)\n        {\n            \/\/ Help text is returned in an exception\n            string strHelp = string(e.what());\n            if (strCommand == \"\")\n                if (strHelp.find('\\n') != string::npos)\n                    strHelp = strHelp.substr(0, strHelp.find('\\n'));\n            strRet += strHelp + \"\\n\";\n        }\n    }\n    if (strRet == \"\")\n        strRet = strprintf(\"help: unknown command: %s\\n\", strCommand.c_str());\n    strRet = strRet.substr(0,strRet.size()-1);\n    return strRet;\n}\n\nValue help(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() > 1)\n        throw runtime_error(\n            \"help [command]\\n\"\n            \"List commands, or get help for a command.\");\n\n    string strCommand;\n    if (params.size() > 0)\n        strCommand = params[0].get_str();\n\n    return tableRPC.help(strCommand);\n}\n\n\nValue stop(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() > 1)\n        throw runtime_error(\n            \"stop <detach>\\n\"\n            \"<detach> is true or false to detach the database or not for this stop only\\n\"\n            \"Stop maxocoin server (and possibly override the detachdb config value).\");\n    \/\/ Shutdown will take long enough that the response should get back\n    if (params.size() > 0)\n        bitdb.SetDetach(params[0].get_bool());\n    StartShutdown();\n    return \"maxocoin server stopping\";\n}\n\n\n\n\/\/\n\/\/ Call Table\n\/\/\n\n\nstatic const CRPCCommand vRPCCommands[] =\n{ \/\/  name                      function                 safemd  unlocked\n  \/\/  ------------------------  -----------------------  ------  --------\n    { \"help\",                   &help,                   true,   true },\n    { \"stop\",                   &stop,                   true,   true },\n    { \"getbestblockhash\",       &getbestblockhash,       true,   false },\n    { \"getblockcount\",          &getblockcount,          true,   false },\n    { \"getconnectioncount\",     &getconnectioncount,     true,   false },\n    { \"getpeerinfo\",            &getpeerinfo,            true,   false },\n    { \"getdifficulty\",          &getdifficulty,          true,   false },\n    { \"getinfo\",                &getinfo,                true,   false },\n    { \"getsubsidy\",             &getsubsidy,             true,   false },\n    { \"getmininginfo\",          &getmininginfo,          true,   false },\n    { \"getstakinginfo\",         &getstakinginfo,         true,   false },\n    { \"getnewaddress\",          &getnewaddress,          true,   false },\n    { \"getnewpubkey\",           &getnewpubkey,           true,   false },\n    { \"getaccountaddress\",      &getaccountaddress,      true,   false },\n    { \"setaccount\",             &setaccount,             true,   false },\n    { \"getaccount\",             &getaccount,             false,  false },\n    { \"getaddressesbyaccount\",  &getaddressesbyaccount,  true,   false },\n    { \"sendtoaddress\",          &sendtoaddress,          false,  false },\n    { \"getreceivedbyaddress\",   &getreceivedbyaddress,   false,  false },\n    { \"getreceivedbyaccount\",   &getreceivedbyaccount,   false,  false },\n    { \"listreceivedbyaddress\",  &listreceivedbyaddress,  false,  false },\n    { \"listreceivedbyaccount\",  &listreceivedbyaccount,  false,  false },\n    { \"backupwallet\",           &backupwallet,           true,   false },\n    { \"keypoolrefill\",          &keypoolrefill,          true,   false },\n    { \"walletpassphrase\",       &walletpassphrase,       true,   false },\n    { \"walletpassphrasechange\", &walletpassphrasechange, false,  false },\n    { \"walletlock\",             &walletlock,             true,   false },\n    { \"encryptwallet\",          &encryptwallet,          false,  false },\n    { \"validateaddress\",        &validateaddress,        true,   false },\n    { \"validatepubkey\",         &validatepubkey,         true,   false },\n    { \"getbalance\",             &getbalance,             false,  false },\n    { \"move\",                   &movecmd,                false,  false },\n    { \"sendfrom\",               &sendfrom,               false,  false },\n    { \"sendmany\",               &sendmany,               false,  false },\n    { \"addmultisigaddress\",     &addmultisigaddress,     false,  false },\n    { \"addredeemscript\",        &addredeemscript,        false,  false },\n    { \"getrawmempool\",          &getrawmempool,          true,   false },\n    { \"getblock\",               &getblock,               false,  false },\n    { \"getblockbynumber\",       &getblockbynumber,       false,  false },\n    { \"getblockhash\",           &getblockhash,           false,  false },\n    { \"gettransaction\",         &gettransaction,         false,  false },\n    { \"listtransactions\",       &listtransactions,       false,  false },\n    { \"listaddressgroupings\",   &listaddressgroupings,   false,  false },\n    { \"signmessage\",            &signmessage,            false,  false },\n    { \"verifymessage\",          &verifymessage,          false,  false },\n    { \"getwork\",                &getwork,                true,   false },\n    { \"getworkex\",              &getworkex,              true,   false },\n    { \"listaccounts\",           &listaccounts,           false,  false },\n    { \"settxfee\",               &settxfee,               false,  false },\n    { \"getblocktemplate\",       &getblocktemplate,       true,   false },\n    { \"submitblock\",            &submitblock,            false,  false },\n    { \"listsinceblock\",         &listsinceblock,         false,  false },\n    { \"dumpprivkey\",            &dumpprivkey,            false,  false },\n    { \"dumpwallet\",             &dumpwallet,             true,   false },\n    { \"importwallet\",           &importwallet,           false,  false },\n    { \"importprivkey\",          &importprivkey,          false,  false },\n    { \"listunspent\",            &listunspent,            false,  false },\n    { \"getrawtransaction\",      &getrawtransaction,      false,  false },\n    { \"createrawtransaction\",   &createrawtransaction,   false,  false },\n    { \"decoderawtransaction\",   &decoderawtransaction,   false,  false },\n    { \"decodescript\",           &decodescript,           false,  false },\n    { \"signrawtransaction\",     &signrawtransaction,     false,  false },\n    { \"sendrawtransaction\",     &sendrawtransaction,     false,  false },\n    { \"getcheckpoint\",          &getcheckpoint,          true,   false },\n    { \"reservebalance\",         &reservebalance,         false,  true},\n    { \"checkwallet\",            &checkwallet,            false,  true},\n    { \"repairwallet\",           &repairwallet,           false,  true},\n    { \"resendtx\",               &resendtx,               false,  true},\n    { \"makekeypair\",            &makekeypair,            false,  true},\n    { \"sendalert\",              &sendalert,              false,  false},\n};\n\nCRPCTable::CRPCTable()\n{\n    unsigned int vcidx;\n    for (vcidx = 0; vcidx < (sizeof(vRPCCommands) \/ sizeof(vRPCCommands[0])); vcidx++)\n    {\n        const CRPCCommand *pcmd;\n\n        pcmd = &vRPCCommands[vcidx];\n        mapCommands[pcmd->name] = pcmd;\n    }\n}\n\nconst CRPCCommand *CRPCTable::operator[](string name) const\n{\n    map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);\n    if (it == mapCommands.end())\n        return NULL;\n    return (*it).second;\n}\n\n\/\/\n\/\/ HTTP protocol\n\/\/\n\/\/ This ain't Apache.  We're just using HTTP header for the length field\n\/\/ and to be compatible with other JSON-RPC implementations.\n\/\/\n\nstring HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)\n{\n    ostringstream s;\n    s << \"POST \/ HTTP\/1.1\\r\\n\"\n      << \"User-Agent: maxocoin-json-rpc\/\" << FormatFullVersion() << \"\\r\\n\"\n      << \"Host: 127.0.0.1\\r\\n\"\n      << \"Content-Type: application\/json\\r\\n\"\n      << \"Content-Length: \" << strMsg.size() << \"\\r\\n\"\n      << \"Connection: close\\r\\n\"\n      << \"Accept: application\/json\\r\\n\";\n    BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)\n        s << item.first << \": \" << item.second << \"\\r\\n\";\n    s << \"\\r\\n\" << strMsg;\n\n    return s.str();\n}\n\nstring rfc1123Time()\n{\n    char buffer[64];\n    time_t now;\n    time(&now);\n    struct tm* now_gmt = gmtime(&now);\n    string locale(setlocale(LC_TIME, NULL));\n    setlocale(LC_TIME, \"C\"); \/\/ we want POSIX (aka \"C\") weekday\/month strings\n    strftime(buffer, sizeof(buffer), \"%a, %d %b %Y %H:%M:%S +0000\", now_gmt);\n    setlocale(LC_TIME, locale.c_str());\n    return string(buffer);\n}\n\nstatic string HTTPReply(int nStatus, const string& strMsg, bool keepalive)\n{\n    if (nStatus == HTTP_UNAUTHORIZED)\n        return strprintf(\"HTTP\/1.0 401 Authorization Required\\r\\n\"\n            \"Date: %s\\r\\n\"\n            \"Server: maxocoin-json-rpc\/%s\\r\\n\"\n            \"WWW-Authenticate: Basic realm=\\\"jsonrpc\\\"\\r\\n\"\n            \"Content-Type: text\/html\\r\\n\"\n            \"Content-Length: 296\\r\\n\"\n            \"\\r\\n\"\n            \"<!DOCTYPE HTML PUBLIC \\\"-\/\/W3C\/\/DTD HTML 4.01 Transitional\/\/EN\\\"\\r\\n\"\n            \"\\\"http:\/\/www.w3.org\/TR\/1999\/REC-html401-19991224\/loose.dtd\\\">\\r\\n\"\n            \"<HTML>\\r\\n\"\n            \"<HEAD>\\r\\n\"\n            \"<TITLE>Error<\/TITLE>\\r\\n\"\n            \"<META HTTP-EQUIV='Content-Type' CONTENT='text\/html; charset=ISO-8859-1'>\\r\\n\"\n            \"<\/HEAD>\\r\\n\"\n            \"<BODY><H1>401 Unauthorized.<\/H1><\/BODY>\\r\\n\"\n            \"<\/HTML>\\r\\n\", rfc1123Time().c_str(), FormatFullVersion().c_str());\n    const char *cStatus;\n         if (nStatus == HTTP_OK) cStatus = \"OK\";\n    else if (nStatus == HTTP_BAD_REQUEST) cStatus = \"Bad Request\";\n    else if (nStatus == HTTP_FORBIDDEN) cStatus = \"Forbidden\";\n    else if (nStatus == HTTP_NOT_FOUND) cStatus = \"Not Found\";\n    else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = \"Internal Server Error\";\n    else cStatus = \"\";\n    return strprintf(\n            \"HTTP\/1.1 %d %s\\r\\n\"\n            \"Date: %s\\r\\n\"\n            \"Connection: %s\\r\\n\"\n            \"Content-Length: %\"PRIszu\"\\r\\n\"\n            \"Content-Type: application\/json\\r\\n\"\n            \"Server: maxocoin-json-rpc\/%s\\r\\n\"\n            \"\\r\\n\"\n            \"%s\",\n        nStatus,\n        cStatus,\n        rfc1123Time().c_str(),\n        keepalive ? \"keep-alive\" : \"close\",\n        strMsg.size(),\n        FormatFullVersion().c_str(),\n        strMsg.c_str());\n}\n\nint ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)\n{\n    string str;\n    getline(stream, str);\n    vector<string> vWords;\n    boost::split(vWords, str, boost::is_any_of(\" \"));\n    if (vWords.size() < 2)\n        return HTTP_INTERNAL_SERVER_ERROR;\n    proto = 0;\n    const char *ver = strstr(str.c_str(), \"HTTP\/1.\");\n    if (ver != NULL)\n        proto = atoi(ver+7);\n    return atoi(vWords[1].c_str());\n}\n\nint ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)\n{\n    int nLen = 0;\n    while (true)\n    {\n        string str;\n        std::getline(stream, str);\n        if (str.empty() || str == \"\\r\")\n            break;\n        string::size_type nColon = str.find(\":\");\n        if (nColon != string::npos)\n        {\n            string strHeader = str.substr(0, nColon);\n            boost::trim(strHeader);\n            boost::to_lower(strHeader);\n            string strValue = str.substr(nColon+1);\n            boost::trim(strValue);\n            mapHeadersRet[strHeader] = strValue;\n            if (strHeader == \"content-length\")\n                nLen = atoi(strValue.c_str());\n        }\n    }\n    return nLen;\n}\n\nint ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)\n{\n    mapHeadersRet.clear();\n    strMessageRet = \"\";\n\n    \/\/ Read status\n    int nProto = 0;\n    int nStatus = ReadHTTPStatus(stream, nProto);\n\n    \/\/ Read header\n    int nLen = ReadHTTPHeader(stream, mapHeadersRet);\n    if (nLen < 0 || nLen > (int)MAX_SIZE)\n        return HTTP_INTERNAL_SERVER_ERROR;\n\n    \/\/ Read message\n    if (nLen > 0)\n    {\n        vector<char> vch(nLen);\n        stream.read(&vch[0], nLen);\n        strMessageRet = string(vch.begin(), vch.end());\n    }\n\n    string sConHdr = mapHeadersRet[\"connection\"];\n\n    if ((sConHdr != \"close\") && (sConHdr != \"keep-alive\"))\n    {\n        if (nProto >= 1)\n            mapHeadersRet[\"connection\"] = \"keep-alive\";\n        else\n            mapHeadersRet[\"connection\"] = \"close\";\n    }\n\n    return nStatus;\n}\n\nbool HTTPAuthorized(map<string, string>& mapHeaders)\n{\n    string strAuth = mapHeaders[\"authorization\"];\n    if (strAuth.substr(0,6) != \"Basic \")\n        return false;\n    string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);\n    string strUserPass = DecodeBase64(strUserPass64);\n    return TimingResistantEqual(strUserPass, strRPCUserColonPass);\n}\n\n\/\/\n\/\/ JSON-RPC protocol.  Bitcoin speaks version 1.0 for maximum compatibility,\n\/\/ but uses JSON-RPC 1.1\/2.0 standards for parts of the 1.0 standard that were\n\/\/ unspecified (HTTP errors and contents of 'error').\n\/\/\n\/\/ 1.0 spec: http:\/\/json-rpc.org\/wiki\/specification\n\/\/ 1.2 spec: http:\/\/groups.google.com\/group\/json-rpc\/web\/json-rpc-over-http\n\/\/ http:\/\/www.codeproject.com\/KB\/recipes\/JSON_Spirit.aspx\n\/\/\n\nstring JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)\n{\n    Object request;\n    request.push_back(Pair(\"method\", strMethod));\n    request.push_back(Pair(\"params\", params));\n    request.push_back(Pair(\"id\", id));\n    return write_string(Value(request), false) + \"\\n\";\n}\n\nObject JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)\n{\n    Object reply;\n    if (error.type() != null_type)\n        reply.push_back(Pair(\"result\", Value::null));\n    else\n        reply.push_back(Pair(\"result\", result));\n    reply.push_back(Pair(\"error\", error));\n    reply.push_back(Pair(\"id\", id));\n    return reply;\n}\n\nstring JSONRPCReply(const Value& result, const Value& error, const Value& id)\n{\n    Object reply = JSONRPCReplyObj(result, error, id);\n    return write_string(Value(reply), false) + \"\\n\";\n}\n\nvoid ErrorReply(std::ostream& stream, const Object& objError, const Value& id)\n{\n    \/\/ Send error reply from json-rpc error object\n    int nStatus = HTTP_INTERNAL_SERVER_ERROR;\n    int code = find_value(objError, \"code\").get_int();\n    if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;\n    else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;\n    string strReply = JSONRPCReply(Value::null, objError, id);\n    stream << HTTPReply(nStatus, strReply, false) << std::flush;\n}\n\nbool ClientAllowed(const boost::asio::ip::address& address)\n{\n    \/\/ Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses\n    if (address.is_v6()\n     && (address.to_v6().is_v4_compatible()\n      || address.to_v6().is_v4_mapped()))\n        return ClientAllowed(address.to_v6().to_v4());\n\n    if (address == asio::ip::address_v4::loopback()\n     || address == asio::ip::address_v6::loopback()\n     || (address.is_v4()\n         \/\/ Check whether IPv4 addresses match 127.0.0.0\/8 (loopback subnet)\n      && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))\n        return true;\n\n    const string strAddress = address.to_string();\n    const vector<string>& vAllow = mapMultiArgs[\"-rpcallowip\"];\n    BOOST_FOREACH(string strAllow, vAllow)\n        if (WildcardMatch(strAddress, strAllow))\n            return true;\n    return false;\n}\n\n\/\/\n\/\/ IOStream device that speaks SSL but can also speak non-SSL\n\/\/\ntemplate <typename Protocol>\nclass SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {\npublic:\n    SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)\n    {\n        fUseSSL = fUseSSLIn;\n        fNeedHandshake = fUseSSLIn;\n    }\n\n    void handshake(ssl::stream_base::handshake_type role)\n    {\n        if (!fNeedHandshake) return;\n        fNeedHandshake = false;\n        stream.handshake(role);\n    }\n    std::streamsize read(char* s, std::streamsize n)\n    {\n        handshake(ssl::stream_base::server); \/\/ HTTPS servers read first\n        if (fUseSSL) return stream.read_some(asio::buffer(s, n));\n        return stream.next_layer().read_some(asio::buffer(s, n));\n    }\n    std::streamsize write(const char* s, std::streamsize n)\n    {\n        handshake(ssl::stream_base::client); \/\/ HTTPS clients write first\n        if (fUseSSL) return asio::write(stream, asio::buffer(s, n));\n        return asio::write(stream.next_layer(), asio::buffer(s, n));\n    }\n    bool connect(const std::string& server, const std::string& port)\n    {\n        ip::tcp::resolver resolver(stream.get_io_service());\n        ip::tcp::resolver::query query(server.c_str(), port.c_str());\n        ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);\n        ip::tcp::resolver::iterator end;\n        boost::system::error_code error = asio::error::host_not_found;\n        while (error && endpoint_iterator != end)\n        {\n            stream.lowest_layer().close();\n            stream.lowest_layer().connect(*endpoint_iterator++, error);\n        }\n        if (error)\n            return false;\n        return true;\n    }\n\nprivate:\n    bool fNeedHandshake;\n    bool fUseSSL;\n    asio::ssl::stream<typename Protocol::socket>& stream;\n};\n\nclass AcceptedConnection\n{\npublic:\n    virtual ~AcceptedConnection() {}\n\n    virtual std::iostream& stream() = 0;\n    virtual std::string peer_address_to_string() const = 0;\n    virtual void close() = 0;\n};\n\ntemplate <typename Protocol>\nclass AcceptedConnectionImpl : public AcceptedConnection\n{\npublic:\n    AcceptedConnectionImpl(\n            asio::io_service& io_service,\n            ssl::context &context,\n            bool fUseSSL) :\n        sslStream(io_service, context),\n        _d(sslStream, fUseSSL),\n        _stream(_d)\n    {\n    }\n\n    virtual std::iostream& stream()\n    {\n        return _stream;\n    }\n\n    virtual std::string peer_address_to_string() const\n    {\n        return peer.address().to_string();\n    }\n\n    virtual void close()\n    {\n        _stream.close();\n    }\n\n    typename Protocol::endpoint peer;\n    asio::ssl::stream<typename Protocol::socket> sslStream;\n\nprivate:\n    SSLIOStreamDevice<Protocol> _d;\n    iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;\n};\n\nvoid ThreadRPCServer(void* parg)\n{\n    \/\/ Make this thread recognisable as the RPC listener\n    RenameThread(\"maxocoin-rpclist\");\n\n    try\n    {\n        vnThreadsRunning[THREAD_RPCLISTENER]++;\n        ThreadRPCServer2(parg);\n        vnThreadsRunning[THREAD_RPCLISTENER]--;\n    }\n    catch (std::exception& e) {\n        vnThreadsRunning[THREAD_RPCLISTENER]--;\n        PrintException(&e, \"ThreadRPCServer()\");\n    } catch (...) {\n        vnThreadsRunning[THREAD_RPCLISTENER]--;\n        PrintException(NULL, \"ThreadRPCServer()\");\n    }\n    printf(\"ThreadRPCServer exited\\n\");\n}\n\n\/\/ Forward declaration required for RPCListen\ntemplate <typename Protocol, typename SocketAcceptorService>\nstatic void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,\n                             ssl::context& context,\n                             bool fUseSSL,\n                             AcceptedConnection* conn,\n                             const boost::system::error_code& error);\n\n\/**\n * Sets up I\/O resources to accept and handle a new connection.\n *\/\ntemplate <typename Protocol, typename SocketAcceptorService>\nstatic void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,\n                   ssl::context& context,\n                   const bool fUseSSL)\n{\n    \/\/ Accept connection\n    AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);\n\n    acceptor->async_accept(\n            conn->sslStream.lowest_layer(),\n            conn->peer,\n            boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,\n                acceptor,\n                boost::ref(context),\n                fUseSSL,\n                conn,\n                boost::asio::placeholders::error));\n}\n\n\/**\n * Accept and handle incoming connection.\n *\/\ntemplate <typename Protocol, typename SocketAcceptorService>\nstatic void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,\n                             ssl::context& context,\n                             const bool fUseSSL,\n                             AcceptedConnection* conn,\n                             const boost::system::error_code& error)\n{\n    vnThreadsRunning[THREAD_RPCLISTENER]++;\n\n    \/\/ Immediately start accepting new connections, except when we're cancelled or our socket is closed.\n    if (error != asio::error::operation_aborted\n     && acceptor->is_open())\n        RPCListen(acceptor, context, fUseSSL);\n\n    AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);\n\n    \/\/ TODO: Actually handle errors\n    if (error)\n    {\n        delete conn;\n    }\n\n    \/\/ Restrict callers by IP.  It is important to\n    \/\/ do this before starting client thread, to filter out\n    \/\/ certain DoS and misbehaving clients.\n    else if (tcp_conn\n          && !ClientAllowed(tcp_conn->peer.address()))\n    {\n        \/\/ Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.\n        if (!fUseSSL)\n            conn->stream() << HTTPReply(HTTP_FORBIDDEN, \"\", false) << std::flush;\n        delete conn;\n    }\n\n    \/\/ start HTTP client thread\n    else if (!NewThread(ThreadRPCServer3, conn)) {\n        printf(\"Failed to create RPC server client thread\\n\");\n        delete conn;\n    }\n\n    vnThreadsRunning[THREAD_RPCLISTENER]--;\n}\n\nvoid ThreadRPCServer2(void* parg)\n{\n    printf(\"ThreadRPCServer started\\n\");\n\n    strRPCUserColonPass = mapArgs[\"-rpcuser\"] + \":\" + mapArgs[\"-rpcpassword\"];\n    if ((mapArgs[\"-rpcpassword\"] == \"\") ||\n        (mapArgs[\"-rpcuser\"] == mapArgs[\"-rpcpassword\"]))\n    {\n        unsigned char rand_pwd[32];\n        RAND_bytes(rand_pwd, 32);\n        string strWhatAmI = \"To use maxocoind\";\n        if (mapArgs.count(\"-server\"))\n            strWhatAmI = strprintf(_(\"To use the %s option\"), \"\\\"-server\\\"\");\n        else if (mapArgs.count(\"-daemon\"))\n            strWhatAmI = strprintf(_(\"To use the %s option\"), \"\\\"-daemon\\\"\");\n        uiInterface.ThreadSafeMessageBox(strprintf(\n            _(\"%s, you must set a rpcpassword in the configuration file:\\n %s\\n\"\n              \"It is recommended you use the following random password:\\n\"\n              \"rpcuser=maxocoinrpc\\n\"\n              \"rpcpassword=%s\\n\"\n              \"(you do not need to remember this password)\\n\"\n              \"The username and password MUST NOT be the same.\\n\"\n              \"If the file does not exist, create it with owner-readable-only file permissions.\\n\"\n              \"It is also recommended to set alertnotify so you are notified of problems;\\n\"\n              \"for example: alertnotify=echo %%s | mail -s \\\"maxocoin Alert\\\" admin@foo.com\\n\"),\n                strWhatAmI.c_str(),\n                GetConfigFile().string().c_str(),\n                EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),\n            _(\"Error\"), CClientUIInterface::OK | CClientUIInterface::MODAL);\n        StartShutdown();\n        return;\n    }\n\n    const bool fUseSSL = GetBoolArg(\"-rpcssl\");\n\n    asio::io_service io_service;\n\n    ssl::context context(io_service, ssl::context::sslv23);\n    if (fUseSSL)\n    {\n        context.set_options(ssl::context::no_sslv2);\n\n        filesystem::path pathCertFile(GetArg(\"-rpcsslcertificatechainfile\", \"server.cert\"));\n        if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) \/ pathCertFile;\n        if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string());\n        else printf(\"ThreadRPCServer ERROR: missing server certificate file %s\\n\", pathCertFile.string().c_str());\n\n        filesystem::path pathPKFile(GetArg(\"-rpcsslprivatekeyfile\", \"server.pem\"));\n        if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) \/ pathPKFile;\n        if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);\n        else printf(\"ThreadRPCServer ERROR: missing server private key file %s\\n\", pathPKFile.string().c_str());\n\n        string strCiphers = GetArg(\"-rpcsslciphers\", \"TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH\");\n        SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str());\n    }\n\n    \/\/ Try a dual IPv6\/IPv4 socket, falling back to separate IPv4 and IPv6 sockets\n    const bool loopback = !mapArgs.count(\"-rpcallowip\");\n    asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();\n    ip::tcp::endpoint endpoint(bindAddress, GetArg(\"-rpcport\", GetDefaultRPCPort()));\n    boost::system::error_code v6_only_error;\n    boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service));\n\n    boost::signals2::signal<void ()> StopRequests;\n\n    bool fListening = false;\n    std::string strerr;\n    try\n    {\n        acceptor->open(endpoint.protocol());\n        acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));\n\n        \/\/ Try making the socket dual IPv6\/IPv4 (if listening on the \"any\" address)\n        acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);\n\n        acceptor->bind(endpoint);\n        acceptor->listen(socket_base::max_connections);\n\n        RPCListen(acceptor, context, fUseSSL);\n        \/\/ Cancel outstanding listen-requests for this acceptor when shutting down\n        StopRequests.connect(signals2::slot<void ()>(\n                    static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())\n                .track(acceptor));\n\n        fListening = true;\n    }\n    catch(boost::system::system_error &e)\n    {\n        strerr = strprintf(_(\"An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s\"), endpoint.port(), e.what());\n    }\n\n    try {\n        \/\/ If dual IPv6\/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately\n        if (!fListening || loopback || v6_only_error)\n        {\n            bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();\n            endpoint.address(bindAddress);\n\n            acceptor.reset(new ip::tcp::acceptor(io_service));\n            acceptor->open(endpoint.protocol());\n            acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));\n            acceptor->bind(endpoint);\n            acceptor->listen(socket_base::max_connections);\n\n            RPCListen(acceptor, context, fUseSSL);\n            \/\/ Cancel outstanding listen-requests for this acceptor when shutting down\n            StopRequests.connect(signals2::slot<void ()>(\n                        static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())\n                    .track(acceptor));\n\n            fListening = true;\n        }\n    }\n    catch(boost::system::system_error &e)\n    {\n        strerr = strprintf(_(\"An error occurred while setting up the RPC port %u for listening on IPv4: %s\"), endpoint.port(), e.what());\n    }\n\n    if (!fListening) {\n        uiInterface.ThreadSafeMessageBox(strerr, _(\"Error\"), CClientUIInterface::OK | CClientUIInterface::MODAL);\n        StartShutdown();\n        return;\n    }\n\n    vnThreadsRunning[THREAD_RPCLISTENER]--;\n    while (!fShutdown)\n        io_service.run_one();\n    vnThreadsRunning[THREAD_RPCLISTENER]++;\n    StopRequests();\n}\n\nclass JSONRequest\n{\npublic:\n    Value id;\n    string strMethod;\n    Array params;\n\n    JSONRequest() { id = Value::null; }\n    void parse(const Value& valRequest);\n};\n\nvoid JSONRequest::parse(const Value& valRequest)\n{\n    \/\/ Parse request\n    if (valRequest.type() != obj_type)\n        throw JSONRPCError(RPC_INVALID_REQUEST, \"Invalid Request object\");\n    const Object& request = valRequest.get_obj();\n\n    \/\/ Parse id now so errors from here on will have the id\n    id = find_value(request, \"id\");\n\n    \/\/ Parse method\n    Value valMethod = find_value(request, \"method\");\n    if (valMethod.type() == null_type)\n        throw JSONRPCError(RPC_INVALID_REQUEST, \"Missing method\");\n    if (valMethod.type() != str_type)\n        throw JSONRPCError(RPC_INVALID_REQUEST, \"Method must be a string\");\n    strMethod = valMethod.get_str();\n    if (strMethod != \"getwork\" && strMethod != \"getblocktemplate\")\n        printf(\"ThreadRPCServer method=%s\\n\", strMethod.c_str());\n\n    \/\/ Parse params\n    Value valParams = find_value(request, \"params\");\n    if (valParams.type() == array_type)\n        params = valParams.get_array();\n    else if (valParams.type() == null_type)\n        params = Array();\n    else\n        throw JSONRPCError(RPC_INVALID_REQUEST, \"Params must be an array\");\n}\n\nstatic Object JSONRPCExecOne(const Value& req)\n{\n    Object rpc_result;\n\n    JSONRequest jreq;\n    try {\n        jreq.parse(req);\n\n        Value result = tableRPC.execute(jreq.strMethod, jreq.params);\n        rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);\n    }\n    catch (Object& objError)\n    {\n        rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);\n    }\n    catch (std::exception& e)\n    {\n        rpc_result = JSONRPCReplyObj(Value::null,\n                                     JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);\n    }\n\n    return rpc_result;\n}\n\nstatic string JSONRPCExecBatch(const Array& vReq)\n{\n    Array ret;\n    for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)\n        ret.push_back(JSONRPCExecOne(vReq[reqIdx]));\n\n    return write_string(Value(ret), false) + \"\\n\";\n}\n\nstatic CCriticalSection cs_THREAD_RPCHANDLER;\n\nvoid ThreadRPCServer3(void* parg)\n{\n    \/\/ Make this thread recognisable as the RPC handler\n    RenameThread(\"maxocoin-rpchand\");\n\n    {\n        LOCK(cs_THREAD_RPCHANDLER);\n        vnThreadsRunning[THREAD_RPCHANDLER]++;\n    }\n    AcceptedConnection *conn = (AcceptedConnection *) parg;\n\n    bool fRun = true;\n    while (true)\n    {\n        if (fShutdown || !fRun)\n        {\n            conn->close();\n            delete conn;\n            {\n                LOCK(cs_THREAD_RPCHANDLER);\n                --vnThreadsRunning[THREAD_RPCHANDLER];\n            }\n            return;\n        }\n        map<string, string> mapHeaders;\n        string strRequest;\n\n        ReadHTTP(conn->stream(), mapHeaders, strRequest);\n\n        \/\/ Check authorization\n        if (mapHeaders.count(\"authorization\") == 0)\n        {\n            conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, \"\", false) << std::flush;\n            break;\n        }\n        if (!HTTPAuthorized(mapHeaders))\n        {\n            printf(\"ThreadRPCServer incorrect password attempt from %s\\n\", conn->peer_address_to_string().c_str());\n            \/* Deter brute-forcing short passwords.\n               If this results in a DOS the user really\n               shouldn't have their RPC port exposed.*\/\n            if (mapArgs[\"-rpcpassword\"].size() < 20)\n                MilliSleep(250);\n\n            conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, \"\", false) << std::flush;\n            break;\n        }\n        if (mapHeaders[\"connection\"] == \"close\")\n            fRun = false;\n\n        JSONRequest jreq;\n        try\n        {\n            \/\/ Parse request\n            Value valRequest;\n            if (!read_string(strRequest, valRequest))\n                throw JSONRPCError(RPC_PARSE_ERROR, \"Parse error\");\n\n            string strReply;\n\n            \/\/ singleton request\n            if (valRequest.type() == obj_type) {\n                jreq.parse(valRequest);\n\n                Value result = tableRPC.execute(jreq.strMethod, jreq.params);\n\n                \/\/ Send reply\n                strReply = JSONRPCReply(result, Value::null, jreq.id);\n\n            \/\/ array of requests\n            } else if (valRequest.type() == array_type)\n                strReply = JSONRPCExecBatch(valRequest.get_array());\n            else\n                throw JSONRPCError(RPC_PARSE_ERROR, \"Top-level object parse error\");\n\n            conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;\n        }\n        catch (Object& objError)\n        {\n            ErrorReply(conn->stream(), objError, jreq.id);\n            break;\n        }\n        catch (std::exception& e)\n        {\n            ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);\n            break;\n        }\n    }\n\n    delete conn;\n    {\n        LOCK(cs_THREAD_RPCHANDLER);\n        vnThreadsRunning[THREAD_RPCHANDLER]--;\n    }\n}\n\njson_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const\n{\n    \/\/ Find method\n    const CRPCCommand *pcmd = tableRPC[strMethod];\n    if (!pcmd)\n        throw JSONRPCError(RPC_METHOD_NOT_FOUND, \"Method not found\");\n\n    \/\/ Observe safe mode\n    string strWarning = GetWarnings(\"rpc\");\n    if (strWarning != \"\" && !GetBoolArg(\"-disablesafemode\") &&\n        !pcmd->okSafeMode)\n        throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string(\"Safe mode: \") + strWarning);\n\n    try\n    {\n        \/\/ Execute\n        Value result;\n        {\n            if (pcmd->unlocked)\n                result = pcmd->actor(params, false);\n            else {\n                LOCK2(cs_main, pwalletMain->cs_wallet);\n                result = pcmd->actor(params, false);\n            }\n        }\n        return result;\n    }\n    catch (std::exception& e)\n    {\n        throw JSONRPCError(RPC_MISC_ERROR, e.what());\n    }\n}\n\n\nObject CallRPC(const string& strMethod, const Array& params)\n{\n    if (mapArgs[\"-rpcuser\"] == \"\" && mapArgs[\"-rpcpassword\"] == \"\")\n        throw runtime_error(strprintf(\n            _(\"You must set rpcpassword=<password> in the configuration file:\\n%s\\n\"\n              \"If the file does not exist, create it with owner-readable-only file permissions.\"),\n                GetConfigFile().string().c_str()));\n\n    \/\/ Connect to localhost\n    bool fUseSSL = GetBoolArg(\"-rpcssl\");\n    asio::io_service io_service;\n    ssl::context context(io_service, ssl::context::sslv23);\n    context.set_options(ssl::context::no_sslv2);\n    asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);\n    SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);\n    iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);\n    if (!d.connect(GetArg(\"-rpcconnect\", \"127.0.0.1\"), GetArg(\"-rpcport\", itostr(GetDefaultRPCPort()))))\n        throw runtime_error(\"couldn't connect to server\");\n\n    \/\/ HTTP basic authentication\n    string strUserPass64 = EncodeBase64(mapArgs[\"-rpcuser\"] + \":\" + mapArgs[\"-rpcpassword\"]);\n    map<string, string> mapRequestHeaders;\n    mapRequestHeaders[\"Authorization\"] = string(\"Basic \") + strUserPass64;\n\n    \/\/ Send request\n    string strRequest = JSONRPCRequest(strMethod, params, 1);\n    string strPost = HTTPPost(strRequest, mapRequestHeaders);\n    stream << strPost << std::flush;\n\n    \/\/ Receive reply\n    map<string, string> mapHeaders;\n    string strReply;\n    int nStatus = ReadHTTP(stream, mapHeaders, strReply);\n    if (nStatus == HTTP_UNAUTHORIZED)\n        throw runtime_error(\"incorrect rpcuser or rpcpassword (authorization failed)\");\n    else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)\n        throw runtime_error(strprintf(\"server returned HTTP error %d\", nStatus));\n    else if (strReply.empty())\n        throw runtime_error(\"no response from server\");\n\n    \/\/ Parse reply\n    Value valReply;\n    if (!read_string(strReply, valReply))\n        throw runtime_error(\"couldn't parse reply from server\");\n    const Object& reply = valReply.get_obj();\n    if (reply.empty())\n        throw runtime_error(\"expected reply to have result, error and id properties\");\n\n    return reply;\n}\n\n\n\n\ntemplate<typename T>\nvoid ConvertTo(Value& value, bool fAllowNull=false)\n{\n    if (fAllowNull && value.type() == null_type)\n        return;\n    if (value.type() == str_type)\n    {\n        \/\/ reinterpret string as unquoted json value\n        Value value2;\n        string strJSON = value.get_str();\n        if (!read_string(strJSON, value2))\n            throw runtime_error(string(\"Error parsing JSON:\")+strJSON);\n        ConvertTo<T>(value2, fAllowNull);\n        value = value2;\n    }\n    else\n    {\n        value = value.get_value<T>();\n    }\n}\n\n\/\/ Convert strings to command-specific RPC representation\nArray RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)\n{\n    Array params;\n    BOOST_FOREACH(const std::string &param, strParams)\n        params.push_back(param);\n\n    int n = params.size();\n\n    \/\/\n    \/\/ Special case non-string parameter types\n    \/\/\n    if (strMethod == \"stop\"                   && n > 0) ConvertTo<bool>(params[0]);\n    if (strMethod == \"sendtoaddress\"          && n > 1) ConvertTo<double>(params[1]);\n    if (strMethod == \"settxfee\"               && n > 0) ConvertTo<double>(params[0]);\n    if (strMethod == \"getreceivedbyaddress\"   && n > 1) ConvertTo<boost::int64_t>(params[1]);\n    if (strMethod == \"getreceivedbyaccount\"   && n > 1) ConvertTo<boost::int64_t>(params[1]);\n    if (strMethod == \"listreceivedbyaddress\"  && n > 0) ConvertTo<boost::int64_t>(params[0]);\n    if (strMethod == \"listreceivedbyaddress\"  && n > 1) ConvertTo<bool>(params[1]);\n    if (strMethod == \"listreceivedbyaccount\"  && n > 0) ConvertTo<boost::int64_t>(params[0]);\n    if (strMethod == \"listreceivedbyaccount\"  && n > 1) ConvertTo<bool>(params[1]);\n    if (strMethod == \"getbalance\"             && n > 1) ConvertTo<boost::int64_t>(params[1]);\n    if (strMethod == \"getblock\"               && n > 1) ConvertTo<bool>(params[1]);\n    if (strMethod == \"getblockbynumber\"       && n > 0) ConvertTo<boost::int64_t>(params[0]);\n    if (strMethod == \"getblockbynumber\"       && n > 1) ConvertTo<bool>(params[1]);\n    if (strMethod == \"getblockhash\"           && n > 0) ConvertTo<boost::int64_t>(params[0]);\n    if (strMethod == \"move\"                   && n > 2) ConvertTo<double>(params[2]);\n    if (strMethod == \"move\"                   && n > 3) ConvertTo<boost::int64_t>(params[3]);\n    if (strMethod == \"sendfrom\"               && n > 2) ConvertTo<double>(params[2]);\n    if (strMethod == \"sendfrom\"               && n > 3) ConvertTo<boost::int64_t>(params[3]);\n    if (strMethod == \"listtransactions\"       && n > 1) ConvertTo<boost::int64_t>(params[1]);\n    if (strMethod == \"listtransactions\"       && n > 2) ConvertTo<boost::int64_t>(params[2]);\n    if (strMethod == \"listaccounts\"           && n > 0) ConvertTo<boost::int64_t>(params[0]);\n    if (strMethod == \"walletpassphrase\"       && n > 1) ConvertTo<boost::int64_t>(params[1]);\n    if (strMethod == \"walletpassphrase\"       && n > 2) ConvertTo<bool>(params[2]);\n    if (strMethod == \"getblocktemplate\"       && n > 0) ConvertTo<Object>(params[0]);\n    if (strMethod == \"listsinceblock\"         && n > 1) ConvertTo<boost::int64_t>(params[1]);\n\n    if (strMethod == \"sendalert\"              && n > 2) ConvertTo<boost::int64_t>(params[2]);\n    if (strMethod == \"sendalert\"              && n > 3) ConvertTo<boost::int64_t>(params[3]);\n    if (strMethod == \"sendalert\"              && n > 4) ConvertTo<boost::int64_t>(params[4]);\n    if (strMethod == \"sendalert\"              && n > 5) ConvertTo<boost::int64_t>(params[5]);\n    if (strMethod == \"sendalert\"              && n > 6) ConvertTo<boost::int64_t>(params[6]);\n\n    if (strMethod == \"sendmany\"               && n > 1) ConvertTo<Object>(params[1]);\n    if (strMethod == \"sendmany\"               && n > 2) ConvertTo<boost::int64_t>(params[2]);\n    if (strMethod == \"reservebalance\"         && n > 0) ConvertTo<bool>(params[0]);\n    if (strMethod == \"reservebalance\"         && n > 1) ConvertTo<double>(params[1]);\n    if (strMethod == \"addmultisigaddress\"     && n > 0) ConvertTo<boost::int64_t>(params[0]);\n    if (strMethod == \"addmultisigaddress\"     && n > 1) ConvertTo<Array>(params[1]);\n    if (strMethod == \"listunspent\"            && n > 0) ConvertTo<boost::int64_t>(params[0]);\n    if (strMethod == \"listunspent\"            && n > 1) ConvertTo<boost::int64_t>(params[1]);\n    if (strMethod == \"listunspent\"            && n > 2) ConvertTo<Array>(params[2]);\n    if (strMethod == \"getrawtransaction\"      && n > 1) ConvertTo<boost::int64_t>(params[1]);\n    if (strMethod == \"createrawtransaction\"   && n > 0) ConvertTo<Array>(params[0]);\n    if (strMethod == \"createrawtransaction\"   && n > 1) ConvertTo<Object>(params[1]);\n    if (strMethod == \"signrawtransaction\"     && n > 1) ConvertTo<Array>(params[1], true);\n    if (strMethod == \"signrawtransaction\"     && n > 2) ConvertTo<Array>(params[2], true);\n    if (strMethod == \"keypoolrefill\"          && n > 0) ConvertTo<boost::int64_t>(params[0]);\n\n    return params;\n}\n\nint CommandLineRPC(int argc, char *argv[])\n{\n    string strPrint;\n    int nRet = 0;\n    try\n    {\n        \/\/ Skip switches\n        while (argc > 1 && IsSwitchChar(argv[1][0]))\n        {\n            argc--;\n            argv++;\n        }\n\n        \/\/ Method\n        if (argc < 2)\n            throw runtime_error(\"too few parameters\");\n        string strMethod = argv[1];\n\n        \/\/ Parameters default to strings\n        std::vector<std::string> strParams(&argv[2], &argv[argc]);\n        Array params = RPCConvertValues(strMethod, strParams);\n\n        \/\/ Execute\n        Object reply = CallRPC(strMethod, params);\n\n        \/\/ Parse reply\n        const Value& result = find_value(reply, \"result\");\n        const Value& error  = find_value(reply, \"error\");\n\n        if (error.type() != null_type)\n        {\n            \/\/ Error\n            strPrint = \"error: \" + write_string(error, false);\n            int code = find_value(error.get_obj(), \"code\").get_int();\n            nRet = abs(code);\n        }\n        else\n        {\n            \/\/ Result\n            if (result.type() == null_type)\n                strPrint = \"\";\n            else if (result.type() == str_type)\n                strPrint = result.get_str();\n            else\n                strPrint = write_string(result, true);\n        }\n    }\n    catch (std::exception& e)\n    {\n        strPrint = string(\"error: \") + e.what();\n        nRet = 87;\n    }\n    catch (...)\n    {\n        PrintException(NULL, \"CommandLineRPC()\");\n    }\n\n    if (strPrint != \"\")\n    {\n        fprintf((nRet == 0 ? stdout : stderr), \"%s\\n\", strPrint.c_str());\n    }\n    return nRet;\n}\n\n\n\n\n#ifdef TEST\nint main(int argc, char *argv[])\n{\n#ifdef _MSC_VER\n    \/\/ Turn off Microsoft heap dump noise\n    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);\n    _CrtSetReportFile(_CRT_WARN, CreateFile(\"NUL\", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));\n#endif\n    setbuf(stdin, NULL);\n    setbuf(stdout, NULL);\n    setbuf(stderr, NULL);\n\n    try\n    {\n        if (argc >= 2 && string(argv[1]) == \"-server\")\n        {\n            printf(\"server ready\\n\");\n            ThreadRPCServer(NULL);\n        }\n        else\n        {\n            return CommandLineRPC(argc, argv);\n        }\n    }\n    catch (std::exception& e) {\n        PrintException(&e, \"main()\");\n    } catch (...) {\n        PrintException(NULL, \"main()\");\n    }\n    return 0;\n}\n#endif\n\nconst CRPCTable tableRPC;\n","avg_line_length":35.970917226,"max_line_length":159,"alphanum_fraction":0.5939424094,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1811,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/\n\/\/ Copyright (C) 2019 Assured Information Security, Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#pragma GCC diagnostic ignored \"-Wunused-result\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <sys\/mount.h>\n#include <sys\/wait.h>\n#include <time.h>\n\nextern \"C\" uint64_t sse_test(uint64_t);\n\nint main(void)\n{\n    srand(time(0));\n    mount(\"proc\", \"\/proc\", \"proc\", 0, \"\");\n\n    freopen(\"\/dev\/ttyprintk\", \"w\", stdout);\n    freopen(\"\/dev\/ttyprintk\", \"w\", stderr);\n\n    if (fork() == 0) {\n        int64_t val{rand() % 10};\n        printf(\"running sse test with val: %d\\n\", val);\n        while (1) {\n            if (sse_test(val) != val) {\n                asm(\"hlt\");\n            }\n        }\n    }\n    else {\n        wait(NULL);\n    }\n}\n\n","avg_line_length":32.3392857143,"max_line_length":81,"alphanum_fraction":0.6753175041,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3098,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Zlib"],"max_stars_count":3.0,"content":"#define __USE_MINGW_ANSI_STDIO 1\n#include <dns\/name.hpp>\n#include <net\/net.hpp>\n#include <net\/ip.hpp>\n\n#include <algorithm>\n#include <sstream>\n\nnamespace llarp\n{\n  namespace dns\n  {\n    bool\n    DecodeName(llarp_buffer_t* buf, Name_t& name, bool trimTrailingDot)\n    {\n      if(buf->size_left() < 1)\n        return false;\n      std::stringstream ss;\n      size_t l;\n      do\n      {\n        l = *buf->cur;\n        buf->cur++;\n        if(l)\n        {\n          if(buf->size_left() < l)\n            return false;\n\n          ss << Name_t((const char*)buf->cur, l);\n          ss << \".\";\n        }\n        buf->cur = buf->cur + l;\n      } while(l);\n      name = ss.str();\n      \/\/\/ trim off last dot\n      if(trimTrailingDot)\n        name = name.substr(0, name.find_last_of('.'));\n      return true;\n    }\n\n    bool\n    EncodeName(llarp_buffer_t* buf, const Name_t& name)\n    {\n      std::stringstream ss;\n      if(name.size() && name[name.size() - 1] == '.')\n        ss << name.substr(0, name.size() - 1);\n      else\n        ss << name;\n\n      std::string part;\n      while(std::getline(ss, part, '.'))\n      {\n        size_t l = part.length();\n        if(l > 63)\n          return false;\n        *(buf->cur) = l;\n        buf->cur++;\n        if(buf->size_left() < l)\n          return false;\n        if(l)\n        {\n          memcpy(buf->cur, part.data(), l);\n          buf->cur += l;\n        }\n        else\n          break;\n      }\n      *buf->cur = 0;\n      buf->cur++;\n      return true;\n    }\n\n    bool\n    DecodePTR(const Name_t& name, huint128_t& ip)\n    {\n      bool isV6 = false;\n      auto pos  = name.find(\".in-addr.arpa\");\n      if(pos == std::string::npos)\n      {\n        pos  = name.find(\".ip6.arpa\");\n        isV6 = true;\n      }\n      if(pos == std::string::npos)\n        return false;\n      std::string sub    = name.substr(0, pos + 1);\n      const auto numdots = std::count(sub.begin(), sub.end(), '.');\n      if(numdots == 4 && !isV6)\n      {\n        uint8_t a, b, c, d;\n        pos = sub.find('.');\n        d   = atoi(sub.substr(0, pos).c_str());\n        sub = sub.substr(pos + 1);\n        pos = sub.find('.');\n        c   = atoi(sub.substr(0, pos).c_str());\n        sub = sub.substr(pos + 1);\n        pos = sub.find('.');\n        b   = atoi(sub.substr(0, pos).c_str());\n        sub = sub.substr(pos + 1);\n        pos = sub.find('.');\n        a   = atoi(sub.substr(0, pos).c_str());\n        ip  = net::IPPacket::ExpandV4(llarp::ipaddr_ipv4_bits(a, b, c, d));\n        return true;\n      }\n      if(numdots == 32 && isV6)\n      {\n        size_t idx = 0;\n        uint8_t lo, hi;\n        auto* ptr = (uint8_t*)&ip.h;\n        while(idx < 16)\n        {\n          pos      = sub.find('.');\n          lo       = (*sub.substr(0, pos).c_str()) - 'a';\n          sub      = sub.substr(pos + 1);\n          pos      = sub.find('.');\n          hi       = (*sub.substr(0, pos).c_str()) - 'a';\n          sub      = sub.substr(pos + 1);\n          ptr[idx] = lo | (hi << 4);\n          ++idx;\n        }\n        return true;\n      }\n\n      return false;\n    }\n\n  }  \/\/ namespace dns\n}  \/\/ namespace llarp\n","avg_line_length":24.203125,"max_line_length":75,"alphanum_fraction":0.45029051,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4018,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Zlib"],"max_stars_count":5.0,"content":"#include \"..\/..\/..\/include\/odfaeg\/Graphics\/cellMap.h\"\nnamespace odfaeg {\n    namespace graphic {\n        using namespace std;\n\n        CellMap::CellMap (physic::BoundingPolyhedron* bp, math::Vec2f coords) {\n            cellVolume = bp;\n            passable = true;\n            stateChanged = false;\n            traveled = false;\n            this->coords = coords;\n        }\n\n        math::Vec2f CellMap::getCoords () {\n            return coords;\n        }\n\n        void CellMap::addEntity (Entity *entity) {\n            std::unique_ptr<Entity> ptr;\n            ptr.reset(entity);\n            entityInside.push_back(std::move(ptr));\n        }\n        physic::BoundingPolyhedron* CellMap::getCellVolume () {\n            return cellVolume;\n        }\n\n        bool CellMap::isEntityInside () {\n            if (entityInside.size() != 0)\n                    return true;\n            return false;\n        }\n\n        vector<Entity*> CellMap::getEntitiesInside () {\n            vector<Entity*> entitiesInside;\n            for (unsigned int i = 0; i < entityInside.size(); i++)\n                entitiesInside.push_back(entityInside[i].get());\n            return entitiesInside;\n        }\n\n        bool CellMap::removeEntity (Entity *entity) {\n            typename vector<std::unique_ptr<Entity>>::iterator it;\n            for (it = entityInside.begin(); it != entityInside.end();) {\n                if (entity == it->get()) {\n                    it->release();\n                    it = entityInside.erase(it);\n                    return true;\n                } else\n                    it++;\n\n            }\n            return false;\n        }\n        bool CellMap::removeEntity (std::string type) {\n            typename vector<std::unique_ptr<Entity>>::iterator it;\n            for (it = entityInside.begin(); it != entityInside.end();) {\n                if (it->get()->getType() == type) {\n                    it->release();\n                    it = entityInside.erase(it);\n                    return true;\n                } else\n                    it++;\n            }\n            return false;\n        }\n        bool CellMap::deleteEntity (std::string type) {\n            typename vector<std::unique_ptr<Entity>>::iterator it;\n            for (it = entityInside.begin(); it != entityInside.end();) {\n                if (it->get()->getType() == type) {\n                    it->release();\n                    it = entityInside.erase(it);\n                    return true;\n                } else\n                    it++;\n            }\n            return false;\n        }\n        math::Vec2f CellMap::getCenter () {\n            return cellVolume->getCenter();\n        }\n\n        bool CellMap::isTraveled () {\n            return traveled;\n        }\n\n        void CellMap::setTraveled (bool traveled) {\n            this->traveled = traveled;\n        }\n\n        Entity* CellMap::getEntityInside (unsigned int index) {\n            if (index >= 0 && index < entityInside.size()) {\n                Entity* entity = entityInside[index].get();\n                return entity;\n            }\n            return nullptr;\n        }\n        unsigned int CellMap::getNbEntitiesInside() {\n            return entityInside.size();\n        }\n        bool CellMap::containsEntity (Entity *entity) {\n            for (unsigned int i = 0; i < entityInside.size(); i++)\n                if (*entityInside[i] == *entity)\n                    return true;\n            return false;\n        }\n\n        bool CellMap::isPassable () {\n            return passable;\n        }\n\n        void CellMap::setPassable (bool passable) {\n            this->passable = passable;\n        }\n\n        void CellMap::setStateChanged (bool b) {\n            this->stateChanged = b;\n        }\n\n        bool CellMap::isStateChanged () {\n            return stateChanged;\n        }\n\n        bool CellMap::operator== (const CellMap &cellMap) {\n            return *cellVolume== *cellVolume;\n        }\n\n        CellMap::~CellMap () {\n            entityInside.clear();\n        }\n    }\n}\n\n","avg_line_length":30.4393939394,"max_line_length":79,"alphanum_fraction":0.4763563962,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1639,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":147.0,"content":"\/\/ -*- mode: c++; tab-width: 4; indent-tabs-mode: t; c-file-style: \"stroustrup\"; -*-\n\/\/ vi:set ts=4 sts=4 sw=4 noet :\n\/\/ Copyright 2008, The TPIE development team\n\/\/ \n\/\/ This file is part of TPIE.\n\/\/ \n\/\/ TPIE is free software: you can redistribute it and\/or modify it under\n\/\/ the terms of the GNU Lesser General Public License as published by the\n\/\/ Free Software Foundation, either version 3 of the License, or (at your\n\/\/ option) any later version.\n\/\/ \n\/\/ TPIE is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or\n\/\/ FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public\n\/\/ License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with TPIE.  If not, see <http:\/\/www.gnu.org\/licenses\/>\n\n\/\/ Copyright (c) 1999 Octavian Procopiuc\n\/\/\n\/\/ File:         rectangle.cpp\n\/\/ Author:       Octavian Procopiuc <tavi@cs.duke.edu>\n\/\/ Created:      02\/04\/99\n\/\/ Description:  Definition of output operator for rectangle.\n\/\/\n\/\/ $Id: rectangle.cpp,v 1.1 2003-11-21 17:01:09 tavi Exp $\n\/\/\n#include <iostream>\nusing std::ostream;\nusing std::istream;\nusing std::endl;\n#include \"rectangle.h\"\n\nostream& operator<<(ostream& s, const rectangle& r)\n{\n  return s << r.id << \" \" << r.xlo << \" \" << r.ylo << \" \" \n\t   << r.xhi << \" \" << r.yhi << endl;\n}\n\nistream& operator>>(istream& s, rectangle& r) {\n#ifdef SEQUOIA_RECTANGLE \n  \/\/sequoia rectangles have the id on the 1st position.\n  s >> r.id >> r.xlo >> r.ylo >> r.xhi >> r.yhi;\n#else\n  s >> r.xlo >> r.ylo >> r.xhi >> r.yhi >> r.id;\n#endif\n  return s;\n}\n","avg_line_length":32.78,"max_line_length":84,"alphanum_fraction":0.6613788896,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1335,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <Windows.h>\n\n#define\tMAX_SIZE\t400\n\nint main() {\n\tDISPLAY_DEVICE displayDevice{ sizeof displayDevice, };\n\tfor (auto i = 0; EnumDisplayDevices(nullptr, i, &displayDevice, EDD_GET_DEVICE_INTERFACE_NAME); i++)\n\t{\n\t\tWCHAR buf[MAX_SIZE]{ };\n\t\twsprintf(buf,\n\t\t\tL\"\\r\\n\\\nDisplay #%d\\r\\n\\\nDevice name: %s\\r\\n\\\nDevice string: %s\\r\\n\\\nActive: %d\\r\\n\\\nMirroring: %d\\r\\n\\\nModes pruned: %d\\r\\n\\\nPrimary: %d\\r\\n\\\nRemovable: %d\\r\\n\\\nVGA compatible: %d\\r\\n\",\n\t\t\ti,\n\t\t\tdisplayDevice.DeviceName,\n\t\t\tdisplayDevice.DeviceString, \n\t\t\tdisplayDevice.StateFlags & DISPLAY_DEVICE_ACTIVE,\n\t\t\tdisplayDevice.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER,\n\t\t\tdisplayDevice.StateFlags & DISPLAY_DEVICE_MODESPRUNED,\n\t\t\tdisplayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE,\n\t\t\tdisplayDevice.StateFlags & DISPLAY_DEVICE_REMOVABLE,\n\t\t\tdisplayDevice.StateFlags & DISPLAY_DEVICE_VGA_COMPATIBLE);\n\t\tDWORD dwSize{ 0 };\n\t\tWriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), buf, lstrlen(buf), &dwSize, nullptr);\n\n\t\tDEVMODE devMode{ {}, {}, {}, sizeof devMode, 0, };\n\t\tif (EnumDisplaySettings(displayDevice.DeviceName, ENUM_CURRENT_SETTINGS, &devMode))\n\t\t{\n\t\t\twsprintf(buf, L\"Position: {%ld, %ld}\\r\\n\", devMode.dmPosition.x, devMode.dmPosition.y);\n\t\t\tdwSize = 0;\n\t\t\tWriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), buf, lstrlen(buf), &dwSize, nullptr);\n\t\t}\n\t}\n\n\treturn 0;\n}\n","avg_line_length":30.3409090909,"max_line_length":101,"alphanum_fraction":0.7288389513,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2481,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":null,"content":"\/**\nSoftware License Agreement BSD\n\\file      bldc_controller.cpp\n\\copyright Copyright (c) 2017, Chip Robotics, All rights reserved.\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that\nthe following conditions are met:\n* Redistributions of source code must retain the above copyright notice, this list of conditions and the\nfollowing disclaimer.\n* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\nfollowing disclaimer in the documentation and\/or other materials provided with the distribution.\n* Neither the name of NAME nor the names of its contributors may be used to endorse or promote\nproducts derived from this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WAR-\nRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN-\nDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT\nOF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"chip_bldc_driver\/bldc_controller.h\"\n#include <string>\n\nnamespace bldc_controller\n{\n\n\/**\n  * Constructs\n  *\/\nBldcController::BldcController(bldc_serial::BldcSerial *s) : serial(s),\n                                                             nh_(\"~\")\n{\n  sub_cmd_ = nh_.subscribe(\"motor_command\", 1, &BldcController::motorCommand, this);\n  timeout_timer_ = nh_.createTimer(ros::Duration(2), &BldcController::timeoutCallback, this);\n  timeout_timer_.start();\n}\n\nBldcController::~BldcController()\n{\n}\n\nvoid BldcController::motorCommand(const chip_bldc_driver::Command &command)\n{\n  timeout_timer_.stop();\n  timeout_timer_.start();\n  serial->sendMotorCommand(command.motor_command);\n}\n\nvoid BldcController::timeoutCallback(const ros::TimerEvent &)\n{\n  \/\/ In case the motorCommand function is not called the timeout will be called after 2 seconds to stop the motor.\n  serial->sendMotorCommand(0);\n}\n\n} \/\/ namespace bldc_controller","avg_line_length":44.3035714286,"max_line_length":114,"alphanum_fraction":0.771866183,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5304,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/******************************************************************************\n*\n* File name:   MessageTestRemoteMessage.cpp\n* Subsystem:   Platform Services\n* Description: Test Message for Distributed Mailbox functionality \n*\n* Name                 Date       Release\n* -------------------- ---------- ---------------------------------------------\n* Stephen Horton       01\/01\/2014 Initial release\n*\n*\n******************************************************************************\/\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ System include files, includes 3rd party libraries.\n\/\/-----------------------------------------------------------------------------\n\n#include <iostream>\n\nusing namespace std;\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Component includes, includes elements of our system.\n\/\/-----------------------------------------------------------------------------\n\n#include \"MessageTestRemoteMessage.h\"\n\n#include \"platform\/msgmgr\/MessageBuffer.h\"\n\n#include \"platform\/common\/MessageIds.h\"\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Static Declarations.\n\/\/-----------------------------------------------------------------------------\n\n#define VERSION_NUMBER 1\n\n\/\/-----------------------------------------------------------------------------\n\/\/ PUBLIC methods.\n\/\/-----------------------------------------------------------------------------\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Method Type: Constructor\n\/\/ Description: \n\/\/ Design:     \n\/\/-----------------------------------------------------------------------------\nMessageTestRemoteMessage::MessageTestRemoteMessage(const MailboxAddress& sourceAddress,\n                                                   int ourIntValue,\n                                                   string ourStringValue)\n  :MessageBase(sourceAddress, VERSION_NUMBER),\n   ourIntValue_(ourIntValue),\n   ourStringValue_(ourStringValue)\n{\n}\/\/end constructor\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Method Type: Virtual Destructor\n\/\/ Description: \n\/\/ Design:     \n\/\/-----------------------------------------------------------------------------\nMessageTestRemoteMessage::~MessageTestRemoteMessage()\n{\n}\/\/end virtual destructor\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Method Type: INSTANCE\n\/\/ Description: Serialize this message into the supplied message buffer\n\/\/ Design:\n\/\/-----------------------------------------------------------------------------\nint MessageTestRemoteMessage::serialize(MessageBuffer& buffer)\n{\n   \/\/ Perform the serialization\n   buffer << sourceAddress_;\n   buffer << ourIntValue_;\n   buffer << ourStringValue_;\n   return OK;\n}\/\/end serialize\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Method Type: STATIC\n\/\/ Description: Deserialize the supplied message buffer and return a Message ptr\n\/\/ Design:\n\/\/-----------------------------------------------------------------------------\nMessageBase* MessageTestRemoteMessage::deserialize(MessageBuffer* buffer)\n{\n   MailboxAddress sourceAddress;\n   int ourIntValue;\n   string ourStringValue;\n                                                                                                           \n   \/\/ Perform the deserialization\n   *buffer >> sourceAddress;\n   *buffer >> ourIntValue;\n   *buffer >> ourStringValue;\n\n   \/\/ Since this is not a poolable (OPM) message, just create one on the heap\n   \/\/ which will be deleted by the MgrMgr framework\n   MessageTestRemoteMessage* remoteMessage = new MessageTestRemoteMessage(sourceAddress, ourIntValue, ourStringValue);\n   return remoteMessage;\n}\/\/end deserialize\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Method Type: INSTANCE\n\/\/ Description: Return the message Id\n\/\/ Design:\n\/\/-----------------------------------------------------------------------------\nunsigned short MessageTestRemoteMessage::getMessageId() const\n{\n   return MSGMGR_TEST_DISTRIBUTED_MSG_ID;\n}\/\/end getMessageId\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Method Type: INSTANCE\n\/\/ Description: Return the String'ized form of the class contents \n\/\/ Design:     \n\/\/-----------------------------------------------------------------------------\nstring MessageTestRemoteMessage::toString()\n{\n   ostringstream ostr;\n   ostr << \"MessageTestRemoteMessage: OurIntValue=\" << ourIntValue_ \n        << \" OurStringValue=\" << ourStringValue_ \n        << \" Source Address=\" << sourceAddress_.toString()\n        << ends;\n   return (ostr.str());\n}\/\/end toString\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ PROTECTED methods.\n\/\/-----------------------------------------------------------------------------\n\n\/\/-----------------------------------------------------------------------------\n\/\/ PRIVATE methods.\n\/\/-----------------------------------------------------------------------------\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Nested Class Definitions:\n\/\/-----------------------------------------------------------------------------\n\n","avg_line_length":36.3287671233,"max_line_length":118,"alphanum_fraction":0.3866892911,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":374,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":3.0,"content":"#include \"MoCmLanguage.h\"\n\nMO_NAMESPACE_BEGIN\n\n\/\/============================================================\nTCharC* RCharEncoding::Gb2312 = TC(\"GB2312\");\nTCharC* RCharEncoding::Gbk = TC(\"GBK\");\nTCharC* RCharEncoding::Gb18030 = TC(\"GB18030\");\n\n\/\/============================================================\nTCharC* RCharEncoding::Default = TC(\"GB18030\");\n\nMO_NAMESPACE_END\n","avg_line_length":26.7142857143,"max_line_length":62,"alphanum_fraction":0.4919786096,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":49642,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2.0,"content":"#include <Interpreters\/DDLWorker.h>\n#include <Parsers\/ASTAlterQuery.h>\n#include <Parsers\/ASTDropQuery.h>\n#include <Parsers\/ASTOptimizeQuery.h>\n#include <Parsers\/ASTQueryWithOnCluster.h>\n#include <Parsers\/ASTQueryWithTableAndOutput.h>\n#include <Parsers\/ParserQuery.h>\n#include <Parsers\/parseQuery.h>\n#include <Parsers\/queryToString.h>\n#include <IO\/WriteHelpers.h>\n#include <IO\/ReadHelpers.h>\n#include <IO\/Operators.h>\n#include <IO\/ReadBufferFromString.h>\n#include <Storages\/IStorage.h>\n#include <Storages\/StorageDistributed.h>\n#include <DataStreams\/IBlockInputStream.h>\n#include <Interpreters\/executeQuery.h>\n#include <Interpreters\/Cluster.h>\n#include <Interpreters\/AddDefaultDatabaseVisitor.h>\n#include <Interpreters\/Context.h>\n#include <Access\/AccessRightsElement.h>\n#include <Common\/DNSResolver.h>\n#include <Common\/Macros.h>\n#include <common\/getFQDNOrHostName.h>\n#include <Common\/setThreadName.h>\n#include <Common\/Stopwatch.h>\n#include <Common\/randomSeed.h>\n#include <Common\/ZooKeeper\/ZooKeeper.h>\n#include <Common\/ZooKeeper\/KeeperException.h>\n#include <Common\/ZooKeeper\/Lock.h>\n#include <Common\/isLocalAddress.h>\n#include <Common\/quoteString.h>\n#include <DataTypes\/DataTypesNumber.h>\n#include <DataTypes\/DataTypeString.h>\n#include <DataTypes\/DataTypeArray.h>\n#include <Columns\/ColumnsNumber.h>\n#include <Columns\/ColumnString.h>\n#include <Columns\/ColumnArray.h>\n#include <Storages\/StorageReplicatedMergeTree.h>\n#include <Poco\/Timestamp.h>\n#include <common\/sleep.h>\n#include <random>\n#include <pcg_random.hpp>\n#include <Poco\/Net\/NetException.h>\n\n\nnamespace DB\n{\n\nnamespace ErrorCodes\n{\n    extern const int NOT_IMPLEMENTED;\n    extern const int LOGICAL_ERROR;\n    extern const int UNKNOWN_FORMAT_VERSION;\n    extern const int INCONSISTENT_CLUSTER_DEFINITION;\n    extern const int TIMEOUT_EXCEEDED;\n    extern const int UNKNOWN_TYPE_OF_QUERY;\n    extern const int UNFINISHED;\n    extern const int QUERY_IS_PROHIBITED;\n}\n\n\nnamespace\n{\n\nstruct HostID\n{\n    String host_name;\n    UInt16 port;\n\n    HostID() = default;\n\n    explicit HostID(const Cluster::Address & address)\n    : host_name(address.host_name), port(address.port) {}\n\n    static HostID fromString(const String & host_port_str)\n    {\n        HostID res;\n        std::tie(res.host_name, res.port) = Cluster::Address::fromString(host_port_str);\n        return res;\n    }\n\n    String toString() const\n    {\n        return Cluster::Address::toString(host_name, port);\n    }\n\n    String readableString() const\n    {\n        return host_name + \":\" + DB::toString(port);\n    }\n\n    bool isLocalAddress(UInt16 clickhouse_port) const\n    {\n        try\n        {\n            return DB::isLocalAddress(DNSResolver::instance().resolveAddress(host_name, port), clickhouse_port);\n        }\n        catch (const Poco::Net::NetException &)\n        {\n            \/\/\/ Avoid \"Host not found\" exceptions\n            return false;\n        }\n    }\n\n    static String applyToString(const HostID & host_id)\n    {\n        return host_id.toString();\n    }\n};\n\n}\n\n\nstruct DDLLogEntry\n{\n    String query;\n    std::vector<HostID> hosts;\n    String initiator; \/\/ optional\n\n    static constexpr int CURRENT_VERSION = 1;\n\n    String toString()\n    {\n        WriteBufferFromOwnString wb;\n\n        Strings host_id_strings(hosts.size());\n        std::transform(hosts.begin(), hosts.end(), host_id_strings.begin(), HostID::applyToString);\n\n        auto version = CURRENT_VERSION;\n        wb << \"version: \" << version << \"\\n\";\n        wb << \"query: \" << escape << query << \"\\n\";\n        wb << \"hosts: \" << host_id_strings << \"\\n\";\n        wb << \"initiator: \" << initiator << \"\\n\";\n\n        return wb.str();\n    }\n\n    void parse(const String & data)\n    {\n        ReadBufferFromString rb(data);\n\n        int version;\n        rb >> \"version: \" >> version >> \"\\n\";\n\n        if (version != CURRENT_VERSION)\n            throw Exception(\"Unknown DDLLogEntry format version: \" + DB::toString(version), ErrorCodes::UNKNOWN_FORMAT_VERSION);\n\n        Strings host_id_strings;\n        rb >> \"query: \" >> escape >> query >> \"\\n\";\n        rb >> \"hosts: \" >> host_id_strings >> \"\\n\";\n\n        if (!rb.eof())\n            rb >> \"initiator: \" >> initiator >> \"\\n\";\n        else\n            initiator.clear();\n\n        assertEOF(rb);\n\n        hosts.resize(host_id_strings.size());\n        std::transform(host_id_strings.begin(), host_id_strings.end(), hosts.begin(), HostID::fromString);\n    }\n};\n\n\nstruct DDLTask\n{\n    \/\/\/ Stages of task lifetime correspond ordering of these data fields:\n\n    \/\/\/ Stage 1: parse entry\n    String entry_name;\n    String entry_path;\n    DDLLogEntry entry;\n\n    \/\/\/ Stage 2: resolve host_id and check that\n    HostID host_id;\n    String host_id_str;\n\n    \/\/\/ Stage 3.1: parse query\n    ASTPtr query;\n    ASTQueryWithOnCluster * query_on_cluster = nullptr;\n\n    \/\/\/ Stage 3.2: check cluster and find the host in cluster\n    String cluster_name;\n    ClusterPtr cluster;\n    Cluster::Address address_in_cluster;\n    size_t host_shard_num;\n    size_t host_replica_num;\n\n    \/\/\/ Stage 3.3: execute query\n    ExecutionStatus execution_status;\n    bool was_executed = false;\n\n    \/\/\/ Stage 4: commit results to ZooKeeper\n};\n\n\nstatic std::unique_ptr<zkutil::Lock> createSimpleZooKeeperLock(\n    const std::shared_ptr<zkutil::ZooKeeper> & zookeeper, const String & lock_prefix, const String & lock_name, const String & lock_message)\n{\n    auto zookeeper_holder = std::make_shared<zkutil::ZooKeeperHolder>();\n    zookeeper_holder->initFromInstance(zookeeper);\n    return std::make_unique<zkutil::Lock>(std::move(zookeeper_holder), lock_prefix, lock_name, lock_message);\n}\n\n\nstatic bool isSupportedAlterType(int type)\n{\n    static const std::unordered_set<int> unsupported_alter_types{\n        ASTAlterCommand::ATTACH_PARTITION,\n        ASTAlterCommand::REPLACE_PARTITION,\n        ASTAlterCommand::FETCH_PARTITION,\n        ASTAlterCommand::FREEZE_PARTITION,\n        ASTAlterCommand::FREEZE_ALL,\n        ASTAlterCommand::NO_TYPE,\n    };\n\n    return unsupported_alter_types.count(type) == 0;\n}\n\n\nDDLWorker::DDLWorker(const std::string & zk_root_dir, Context & context_, const Poco::Util::AbstractConfiguration * config, const String & prefix)\n    : context(context_), log(&Poco::Logger::get(\"DDLWorker\"))\n{\n    queue_dir = zk_root_dir;\n    if (queue_dir.back() == '\/')\n        queue_dir.resize(queue_dir.size() - 1);\n\n    if (config)\n    {\n        task_max_lifetime = config->getUInt64(prefix + \".task_max_lifetime\", static_cast<UInt64>(task_max_lifetime));\n        cleanup_delay_period = config->getUInt64(prefix + \".cleanup_delay_period\", static_cast<UInt64>(cleanup_delay_period));\n        max_tasks_in_queue = std::max<UInt64>(1, config->getUInt64(prefix + \".max_tasks_in_queue\", max_tasks_in_queue));\n\n        if (config->has(prefix + \".profile\"))\n            context.setSetting(\"profile\", config->getString(prefix + \".profile\"));\n    }\n\n    if (context.getSettingsRef().readonly)\n    {\n        LOG_WARNING(log, \"Distributed DDL worker is run with readonly settings, it will not be able to execute DDL queries Set appropriate system_profile or distributed_ddl.profile to fix this.\");\n    }\n\n    host_fqdn = getFQDNOrHostName();\n    host_fqdn_id = Cluster::Address::toString(host_fqdn, context.getTCPPort());\n\n    main_thread = ThreadFromGlobalPool(&DDLWorker::runMainThread, this);\n    cleanup_thread = ThreadFromGlobalPool(&DDLWorker::runCleanupThread, this);\n}\n\n\nDDLWorker::~DDLWorker()\n{\n    stop_flag = true;\n    queue_updated_event->set();\n    cleanup_event->set();\n    main_thread.join();\n    cleanup_thread.join();\n}\n\n\nDDLWorker::ZooKeeperPtr DDLWorker::tryGetZooKeeper() const\n{\n    std::lock_guard lock(zookeeper_mutex);\n    return current_zookeeper;\n}\n\nDDLWorker::ZooKeeperPtr DDLWorker::getAndSetZooKeeper()\n{\n    std::lock_guard lock(zookeeper_mutex);\n\n    if (!current_zookeeper || current_zookeeper->expired())\n        current_zookeeper = context.getZooKeeper();\n\n    return current_zookeeper;\n}\n\n\nbool DDLWorker::initAndCheckTask(const String & entry_name, String & out_reason, const ZooKeeperPtr & zookeeper)\n{\n    String node_data;\n    String entry_path = queue_dir + \"\/\" + entry_name;\n\n    if (!zookeeper->tryGet(entry_path, node_data))\n    {\n        \/\/\/ It is Ok that node could be deleted just now. It means that there are no current host in node's host list.\n        out_reason = \"The task was deleted\";\n        return false;\n    }\n\n    auto task = std::make_unique<DDLTask>();\n    task->entry_name = entry_name;\n    task->entry_path = entry_path;\n\n    try\n    {\n        task->entry.parse(node_data);\n    }\n    catch (...)\n    {\n        \/\/\/ What should we do if we even cannot parse host name and therefore cannot properly submit execution status?\n        \/\/\/ We can try to create fail node using FQDN if it equal to host name in cluster config attempt will be successful.\n        \/\/\/ Otherwise, that node will be ignored by DDLQueryStatusInputStream.\n\n        tryLogCurrentException(log, \"Cannot parse DDL task \" + entry_name + \", will try to send error status\");\n\n        String status = ExecutionStatus::fromCurrentException().serializeText();\n        try\n        {\n            createStatusDirs(entry_path, zookeeper);\n            zookeeper->tryCreate(entry_path + \"\/finished\/\" + host_fqdn_id, status, zkutil::CreateMode::Persistent);\n        }\n        catch (...)\n        {\n            tryLogCurrentException(log, \"Can't report the task has invalid format\");\n        }\n\n        out_reason = \"Incorrect task format\";\n        return false;\n    }\n\n    bool host_in_hostlist = false;\n    for (const HostID & host : task->entry.hosts)\n    {\n        auto maybe_secure_port = context.getTCPPortSecure();\n\n        \/\/\/ The port is considered local if it matches TCP or TCP secure port that the server is listening.\n        bool is_local_port = (maybe_secure_port && host.isLocalAddress(*maybe_secure_port))\n            || host.isLocalAddress(context.getTCPPort());\n\n        if (!is_local_port)\n            continue;\n\n        if (host_in_hostlist)\n        {\n            \/\/\/ This check could be slow a little bit\n            LOG_WARNING(log, \"There are two the same ClickHouse instances in task {}: {} and {}. Will use the first one only.\", entry_name, task->host_id.readableString(), host.readableString());\n        }\n        else\n        {\n            host_in_hostlist = true;\n            task->host_id = host;\n            task->host_id_str = host.toString();\n        }\n    }\n\n    if (host_in_hostlist)\n        current_task = std::move(task);\n    else\n        out_reason = \"There is no a local address in host list\";\n\n    return host_in_hostlist;\n}\n\n\nstatic void filterAndSortQueueNodes(Strings & all_nodes)\n{\n    all_nodes.erase(std::remove_if(all_nodes.begin(), all_nodes.end(), [] (const String & s) { return !startsWith(s, \"query-\"); }), all_nodes.end());\n    std::sort(all_nodes.begin(), all_nodes.end());\n}\n\n\nvoid DDLWorker::processTasks()\n{\n    LOG_DEBUG(log, \"Processing tasks\");\n    auto zookeeper = tryGetZooKeeper();\n\n    Strings queue_nodes = zookeeper->getChildren(queue_dir, nullptr, queue_updated_event);\n    filterAndSortQueueNodes(queue_nodes);\n    if (queue_nodes.empty())\n        return;\n\n    bool server_startup = last_processed_task_name.empty();\n\n    auto begin_node = server_startup\n        ? queue_nodes.begin()\n        : std::upper_bound(queue_nodes.begin(), queue_nodes.end(), last_processed_task_name);\n\n    for (auto it = begin_node; it != queue_nodes.end(); ++it)\n    {\n        String entry_name = *it;\n\n        if (current_task)\n        {\n            if (current_task->entry_name == entry_name)\n            {\n                LOG_INFO(log, \"Trying to process task {} again\", entry_name);\n            }\n            else\n            {\n                LOG_INFO(log, \"Task {} was deleted from ZooKeeper before current host committed it\", current_task->entry_name);\n                current_task = nullptr;\n            }\n        }\n\n        if (!current_task)\n        {\n            String reason;\n            if (!initAndCheckTask(entry_name, reason, zookeeper))\n            {\n                LOG_DEBUG(log, \"Will not execute task {}: {}\", entry_name, reason);\n                last_processed_task_name = entry_name;\n                continue;\n            }\n        }\n\n        DDLTask & task = *current_task;\n\n        bool already_processed = zookeeper->exists(task.entry_path + \"\/finished\/\" + task.host_id_str);\n        if (!server_startup && !task.was_executed && already_processed)\n        {\n            throw Exception(\n                \"Server expects that DDL task \" + task.entry_name + \" should be processed, but it was already processed according to ZK\",\n                ErrorCodes::LOGICAL_ERROR);\n        }\n\n        if (!already_processed)\n        {\n            try\n            {\n                processTask(task, zookeeper);\n            }\n            catch (const Coordination::Exception & e)\n            {\n                if (server_startup && e.code == Coordination::Error::ZNONODE)\n                {\n                    LOG_WARNING(log, \"ZooKeeper NONODE error during startup. Ignoring entry {} ({}) : {}\", task.entry_name, task.entry.query, getCurrentExceptionMessage(true));\n                }\n                else\n                {\n                     throw;\n                }\n            }\n            catch (...)\n            {\n                LOG_WARNING(log, \"An error occurred while processing task {} ({}) : {}\", task.entry_name, task.entry.query, getCurrentExceptionMessage(true));\n                throw;\n            }\n        }\n        else\n        {\n            LOG_DEBUG(log, \"Task {} ({}) has been already processed\", task.entry_name, task.entry.query);\n        }\n\n        last_processed_task_name = task.entry_name;\n        current_task.reset();\n\n        if (stop_flag)\n            break;\n    }\n}\n\n\n\/\/\/ Parses query and resolves cluster and host in cluster\nvoid DDLWorker::parseQueryAndResolveHost(DDLTask & task)\n{\n    {\n        const char * begin = task.entry.query.data();\n        const char * end = begin + task.entry.query.size();\n\n        ParserQuery parser_query(end);\n        String description;\n        task.query = parseQuery(parser_query, begin, end, description, 0, context.getSettingsRef().max_parser_depth);\n    }\n\n    \/\/ XXX: serious design flaw since `ASTQueryWithOnCluster` is not inherited from `IAST`!\n    if (!task.query || !(task.query_on_cluster = dynamic_cast<ASTQueryWithOnCluster *>(task.query.get())))\n        throw Exception(\"Received unknown DDL query\", ErrorCodes::UNKNOWN_TYPE_OF_QUERY);\n\n    task.cluster_name = task.query_on_cluster->cluster;\n    task.cluster = context.tryGetCluster(task.cluster_name);\n    if (!task.cluster)\n    {\n        throw Exception(\"DDL task \" + task.entry_name + \" contains current host \" + task.host_id.readableString()\n            + \" in cluster \" + task.cluster_name + \", but there are no such cluster here.\", ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION);\n    }\n\n    \/\/\/ Try to find host from task host list in cluster\n    \/\/\/ At the first, try find exact match (host name and ports should be literally equal)\n    \/\/\/ If the attempt fails, try find it resolving host name of each instance\n    const auto & shards = task.cluster->getShardsAddresses();\n\n    bool found_exact_match = false;\n    String default_database;\n    for (size_t shard_num = 0; shard_num < shards.size(); ++shard_num)\n    {\n        for (size_t replica_num = 0; replica_num < shards[shard_num].size(); ++replica_num)\n        {\n            const Cluster::Address & address = shards[shard_num][replica_num];\n\n            if (address.host_name == task.host_id.host_name && address.port == task.host_id.port)\n            {\n                if (found_exact_match)\n                {\n                    if (default_database == address.default_database)\n                    {\n                        throw Exception(\n                            \"There are two exactly the same ClickHouse instances \" + address.readableString() + \" in cluster \"\n                                + task.cluster_name,\n                            ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION);\n                    }\n                    else\n                    {\n                        \/* Circular replication is used.\n                         * It is when every physical node contains\n                         * replicas of different shards of the same table.\n                         * To distinguish one replica from another on the same node,\n                         * every shard is placed into separate database.\n                         * *\/\n                        is_circular_replicated = true;\n                        auto * query_with_table = dynamic_cast<ASTQueryWithTableAndOutput *>(task.query.get());\n                        if (!query_with_table || query_with_table->database.empty())\n                        {\n                            throw Exception(\n                                \"For a distributed DDL on circular replicated cluster its table name must be qualified by database name.\",\n                                ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION);\n                        }\n                        if (default_database == query_with_table->database)\n                            return;\n                    }\n                }\n                found_exact_match = true;\n                task.host_shard_num = shard_num;\n                task.host_replica_num = replica_num;\n                task.address_in_cluster = address;\n                default_database = address.default_database;\n            }\n        }\n    }\n\n    if (found_exact_match)\n        return;\n\n    LOG_WARNING(log, \"Not found the exact match of host {} from task {} in cluster {} definition. Will try to find it using host name resolving.\", task.host_id.readableString(), task.entry_name, task.cluster_name);\n\n    bool found_via_resolving = false;\n    for (size_t shard_num = 0; shard_num < shards.size(); ++shard_num)\n    {\n        for (size_t replica_num = 0; replica_num < shards[shard_num].size(); ++replica_num)\n        {\n            const Cluster::Address & address = shards[shard_num][replica_num];\n\n            if (auto resolved = address.getResolvedAddress();\n                resolved && (isLocalAddress(*resolved, context.getTCPPort())\n                    || (context.getTCPPortSecure() && isLocalAddress(*resolved, *context.getTCPPortSecure()))))\n            {\n                if (found_via_resolving)\n                {\n                    throw Exception(\"There are two the same ClickHouse instances in cluster \" + task.cluster_name + \" : \"\n                        + task.address_in_cluster.readableString() + \" and \" + address.readableString(), ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION);\n                }\n                else\n                {\n                    found_via_resolving = true;\n                    task.host_shard_num = shard_num;\n                    task.host_replica_num = replica_num;\n                    task.address_in_cluster = address;\n                }\n            }\n        }\n    }\n\n    if (!found_via_resolving)\n    {\n        throw Exception(\"Not found host \" + task.host_id.readableString() + \" in definition of cluster \" + task.cluster_name,\n                        ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION);\n    }\n    else\n    {\n        LOG_INFO(log, \"Resolved host {} from task {} as host {} in definition of cluster {}\", task.host_id.readableString(), task.entry_name, task.address_in_cluster.readableString(), task.cluster_name);\n    }\n}\n\n\nbool DDLWorker::tryExecuteQuery(const String & query, const DDLTask & task, ExecutionStatus & status)\n{\n    \/\/\/ Add special comment at the start of query to easily identify DDL-produced queries in query_log\n    String query_prefix = \"\/* ddl_entry=\" + task.entry_name + \" *\/ \";\n    String query_to_execute = query_prefix + query;\n\n    ReadBufferFromString istr(query_to_execute);\n    String dummy_string;\n    WriteBufferFromString ostr(dummy_string);\n\n    try\n    {\n        current_context = std::make_unique<Context>(context);\n        current_context->getClientInfo().query_kind = ClientInfo::QueryKind::SECONDARY_QUERY;\n        current_context->setCurrentQueryId(\"\"); \/\/ generate random query_id\n        executeQuery(istr, ostr, false, *current_context, {});\n    }\n    catch (...)\n    {\n        status = ExecutionStatus::fromCurrentException();\n        tryLogCurrentException(log, \"Query \" + query + \" wasn't finished successfully\");\n\n        return false;\n    }\n\n    status = ExecutionStatus(0);\n    LOG_DEBUG(log, \"Executed query: {}\", query);\n\n    return true;\n}\n\nvoid DDLWorker::attachToThreadGroup()\n{\n    if (thread_group)\n    {\n        \/\/\/ Put all threads to one thread pool\n        CurrentThread::attachToIfDetached(thread_group);\n    }\n    else\n    {\n        CurrentThread::initializeQuery();\n        thread_group = CurrentThread::getGroup();\n    }\n}\n\n\nvoid DDLWorker::processTask(DDLTask & task, const ZooKeeperPtr & zookeeper)\n{\n    LOG_DEBUG(log, \"Processing task {} ({})\", task.entry_name, task.entry.query);\n\n    String dummy;\n    String active_node_path = task.entry_path + \"\/active\/\" + task.host_id_str;\n    String finished_node_path = task.entry_path + \"\/finished\/\" + task.host_id_str;\n\n    auto code = zookeeper->tryCreate(active_node_path, \"\", zkutil::CreateMode::Ephemeral, dummy);\n\n    if (code == Coordination::Error::ZOK || code == Coordination::Error::ZNODEEXISTS)\n    {\n        \/\/ Ok\n    }\n    else if (code == Coordination::Error::ZNONODE)\n    {\n        \/\/\/ There is no parent\n        createStatusDirs(task.entry_path, zookeeper);\n        if (Coordination::Error::ZOK != zookeeper->tryCreate(active_node_path, \"\", zkutil::CreateMode::Ephemeral, dummy))\n            throw Coordination::Exception(code, active_node_path);\n    }\n    else\n        throw Coordination::Exception(code, active_node_path);\n\n    if (!task.was_executed)\n    {\n        try\n        {\n            is_circular_replicated = false;\n            parseQueryAndResolveHost(task);\n\n            ASTPtr rewritten_ast = task.query_on_cluster->getRewrittenASTWithoutOnCluster(task.address_in_cluster.default_database);\n            String rewritten_query = queryToString(rewritten_ast);\n            LOG_DEBUG(log, \"Executing query: {}\", rewritten_query);\n\n            if (auto * query_with_table = dynamic_cast<ASTQueryWithTableAndOutput *>(rewritten_ast.get()); query_with_table)\n            {\n                StoragePtr storage;\n                if (!query_with_table->table.empty())\n                {\n                    \/\/\/ It's not CREATE DATABASE\n                    auto table_id = context.tryResolveStorageID(*query_with_table, Context::ResolveOrdinary);\n                    storage = DatabaseCatalog::instance().tryGetTable(table_id, context);\n                }\n\n                \/\/\/ For some reason we check consistency of cluster definition only\n                \/\/\/ in case of ALTER query, but not in case of CREATE\/DROP etc.\n                \/\/\/ It's strange, but this behaviour exits for a long and we cannot change it.\n                if (storage && query_with_table->as<ASTAlterQuery>())\n                    checkShardConfig(query_with_table->table, task, storage);\n\n                if (storage && taskShouldBeExecutedOnLeader(rewritten_ast, storage)  && !is_circular_replicated)\n                    tryExecuteQueryOnLeaderReplica(task, storage, rewritten_query, task.entry_path, zookeeper);\n                else\n                    tryExecuteQuery(rewritten_query, task, task.execution_status);\n            }\n            else\n                tryExecuteQuery(rewritten_query, task, task.execution_status);\n        }\n        catch (const Coordination::Exception &)\n        {\n            throw;\n        }\n        catch (...)\n        {\n            tryLogCurrentException(log, \"An error occurred before execution of DDL task: \");\n            task.execution_status = ExecutionStatus::fromCurrentException(\"An error occurred before execution\");\n        }\n\n        \/\/\/ We need to distinguish ZK errors occured before and after query executing\n        task.was_executed = true;\n    }\n\n    \/\/\/ FIXME: if server fails right here, the task will be executed twice. We need WAL here.\n\n    \/\/\/ Delete active flag and create finish flag\n    Coordination::Requests ops;\n    ops.emplace_back(zkutil::makeRemoveRequest(active_node_path, -1));\n    ops.emplace_back(zkutil::makeCreateRequest(finished_node_path, task.execution_status.serializeText(), zkutil::CreateMode::Persistent));\n    zookeeper->multi(ops);\n}\n\n\nbool DDLWorker::taskShouldBeExecutedOnLeader(const ASTPtr ast_ddl, const StoragePtr storage)\n{\n    \/\/\/ Pure DROP queries have to be executed on each node separately\n    if (auto * query = ast_ddl->as<ASTDropQuery>(); query && query->kind != ASTDropQuery::Kind::Truncate)\n        return false;\n\n    if (!ast_ddl->as<ASTAlterQuery>() && !ast_ddl->as<ASTOptimizeQuery>() && !ast_ddl->as<ASTDropQuery>())\n        return false;\n\n    return storage->supportsReplication();\n}\n\n\nvoid DDLWorker::checkShardConfig(const String & table, const DDLTask & task, StoragePtr storage) const\n{\n    const auto & shard_info = task.cluster->getShardsInfo().at(task.host_shard_num);\n    bool config_is_replicated_shard = shard_info.hasInternalReplication();\n\n    if (dynamic_cast<const StorageDistributed *>(storage.get()))\n    {\n        LOG_TRACE(log, \"Table {} is distributed, skip checking config.\", backQuote(table));\n        return;\n    }\n\n    if (storage->supportsReplication() && !config_is_replicated_shard)\n    {\n        throw Exception(\"Table \" + backQuote(table) + \" is replicated, but shard #\" + toString(task.host_shard_num + 1) +\n            \" isn't replicated according to its cluster definition.\"\n            \" Possibly <internal_replication>true<\/internal_replication> is forgotten in the cluster config.\",\n            ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION);\n    }\n\n    if (!storage->supportsReplication() && config_is_replicated_shard)\n    {\n        throw Exception(\"Table \" + backQuote(table) + \" isn't replicated, but shard #\" + toString(task.host_shard_num + 1) +\n            \" is replicated according to its cluster definition\", ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION);\n    }\n}\n\n\nbool DDLWorker::tryExecuteQueryOnLeaderReplica(\n    DDLTask & task,\n    StoragePtr storage,\n    const String & rewritten_query,\n    const String & node_path,\n    const ZooKeeperPtr & zookeeper)\n{\n    StorageReplicatedMergeTree * replicated_storage = dynamic_cast<StorageReplicatedMergeTree *>(storage.get());\n\n    \/\/\/ If we will develop new replicated storage\n    if (!replicated_storage)\n        throw Exception(\"Storage type '\" + storage->getName() + \"' is not supported by distributed DDL\", ErrorCodes::NOT_IMPLEMENTED);\n\n    \/\/\/ Generate unique name for shard node, it will be used to execute the query by only single host\n    \/\/\/ Shard node name has format 'replica_name1,replica_name2,...,replica_nameN'\n    \/\/\/ Where replica_name is 'replica_config_host_name:replica_port'\n    auto get_shard_name = [] (const Cluster::Addresses & shard_addresses)\n    {\n        Strings replica_names;\n        for (const Cluster::Address & address : shard_addresses)\n            replica_names.emplace_back(address.readableString());\n        std::sort(replica_names.begin(), replica_names.end());\n\n        String res;\n        for (auto it = replica_names.begin(); it != replica_names.end(); ++it)\n            res += *it + (std::next(it) != replica_names.end() ? \",\" : \"\");\n\n        return res;\n    };\n\n    String shard_node_name = get_shard_name(task.cluster->getShardsAddresses().at(task.host_shard_num));\n    String shard_path = node_path + \"\/shards\/\" + shard_node_name;\n    String is_executed_path = shard_path + \"\/executed\";\n    zookeeper->createAncestors(shard_path + \"\/\");\n\n    auto is_already_executed = [&]() -> bool\n    {\n        String executed_by;\n        if (zookeeper->tryGet(is_executed_path, executed_by))\n        {\n            LOG_DEBUG(log, \"Task {} has already been executed by leader replica ({}) of the same shard.\", task.entry_name, executed_by);\n            return true;\n        }\n\n        return false;\n    };\n\n    pcg64 rng(randomSeed());\n\n    auto lock = createSimpleZooKeeperLock(zookeeper, shard_path, \"lock\", task.host_id_str);\n    static const size_t max_tries = 20;\n    bool executed_by_leader = false;\n    for (size_t num_tries = 0; num_tries < max_tries; ++num_tries)\n    {\n        if (is_already_executed())\n        {\n            executed_by_leader = true;\n            break;\n        }\n\n        StorageReplicatedMergeTree::Status status;\n        replicated_storage->getStatus(status);\n\n        \/\/\/ Leader replica take lock\n        if (status.is_leader && lock->tryLock())\n        {\n            if (is_already_executed())\n            {\n                executed_by_leader = true;\n                break;\n            }\n\n            \/\/\/ If the leader will unexpectedly changed this method will return false\n            \/\/\/ and on the next iteration new leader will take lock\n            if (tryExecuteQuery(rewritten_query, task, task.execution_status))\n            {\n                zookeeper->create(is_executed_path, task.host_id_str, zkutil::CreateMode::Persistent);\n                executed_by_leader = true;\n                break;\n            }\n\n        }\n\n        \/\/\/ Does nothing if wasn't previously locked\n        lock->unlock();\n        std::this_thread::sleep_for(std::chrono::milliseconds(std::uniform_int_distribution<int>(0, 1000)(rng)));\n    }\n\n    \/\/\/ Not executed by leader so was not executed at all\n    if (!executed_by_leader)\n    {\n        task.execution_status = ExecutionStatus(ErrorCodes::NOT_IMPLEMENTED,\n                                                \"Cannot execute replicated DDL query on leader\");\n        return false;\n    }\n    return true;\n}\n\n\nvoid DDLWorker::cleanupQueue(Int64 current_time_seconds, const ZooKeeperPtr & zookeeper)\n{\n    LOG_DEBUG(log, \"Cleaning queue\");\n\n    Strings queue_nodes = zookeeper->getChildren(queue_dir);\n    filterAndSortQueueNodes(queue_nodes);\n\n    size_t num_outdated_nodes = (queue_nodes.size() > max_tasks_in_queue) ? queue_nodes.size() - max_tasks_in_queue : 0;\n    auto first_non_outdated_node = queue_nodes.begin() + num_outdated_nodes;\n\n    for (auto it = queue_nodes.cbegin(); it < queue_nodes.cend(); ++it)\n    {\n        if (stop_flag)\n            return;\n\n        String node_name = *it;\n        String node_path = queue_dir + \"\/\" + node_name;\n        String lock_path = node_path + \"\/lock\";\n\n        Coordination::Stat stat;\n        String dummy;\n\n        try\n        {\n            \/\/\/ Already deleted\n            if (!zookeeper->exists(node_path, &stat))\n                continue;\n\n            \/\/\/ Delete node if its lifetime is expired (according to task_max_lifetime parameter)\n            constexpr UInt64 zookeeper_time_resolution = 1000;\n            Int64 zookeeper_time_seconds = stat.ctime \/ zookeeper_time_resolution;\n            bool node_lifetime_is_expired = zookeeper_time_seconds + task_max_lifetime < current_time_seconds;\n\n            \/\/\/ If too many nodes in task queue (> max_tasks_in_queue), delete oldest one\n            bool node_is_outside_max_window = it < first_non_outdated_node;\n\n            if (!node_lifetime_is_expired && !node_is_outside_max_window)\n                continue;\n\n            \/\/\/ Skip if there are active nodes (it is weak guard)\n            if (zookeeper->exists(node_path + \"\/active\", &stat) && stat.numChildren > 0)\n            {\n                LOG_INFO(log, \"Task {} should be deleted, but there are active workers. Skipping it.\", node_name);\n                continue;\n            }\n\n            \/\/\/ Usage of the lock is not necessary now (tryRemoveRecursive correctly removes node in a presence of concurrent cleaners)\n            \/\/\/ But the lock will be required to implement system.distributed_ddl_queue table\n            auto lock = createSimpleZooKeeperLock(zookeeper, node_path, \"lock\", host_fqdn_id);\n            if (!lock->tryLock())\n            {\n                LOG_INFO(log, \"Task {} should be deleted, but it is locked. Skipping it.\", node_name);\n                continue;\n            }\n\n            if (node_lifetime_is_expired)\n                LOG_INFO(log, \"Lifetime of task {} is expired, deleting it\", node_name);\n            else if (node_is_outside_max_window)\n                LOG_INFO(log, \"Task {} is outdated, deleting it\", node_name);\n\n            \/\/\/ Deleting\n            {\n                Strings childs = zookeeper->getChildren(node_path);\n                for (const String & child : childs)\n                {\n                    if (child != \"lock\")\n                        zookeeper->tryRemoveRecursive(node_path + \"\/\" + child);\n                }\n\n                \/\/\/ Remove the lock node and its parent atomically\n                Coordination::Requests ops;\n                ops.emplace_back(zkutil::makeRemoveRequest(lock_path, -1));\n                ops.emplace_back(zkutil::makeRemoveRequest(node_path, -1));\n                zookeeper->multi(ops);\n\n                lock->unlockAssumeLockNodeRemovedManually();\n            }\n        }\n        catch (...)\n        {\n            LOG_INFO(log, \"An error occured while checking and cleaning task {} from queue: {}\", node_name, getCurrentExceptionMessage(false));\n        }\n    }\n}\n\n\n\/\/\/ Try to create nonexisting \"status\" dirs for a node\nvoid DDLWorker::createStatusDirs(const std::string & node_path, const ZooKeeperPtr & zookeeper)\n{\n    Coordination::Requests ops;\n    {\n        Coordination::CreateRequest request;\n        request.path = node_path + \"\/active\";\n        ops.emplace_back(std::make_shared<Coordination::CreateRequest>(std::move(request)));\n    }\n    {\n        Coordination::CreateRequest request;\n        request.path = node_path + \"\/finished\";\n        ops.emplace_back(std::make_shared<Coordination::CreateRequest>(std::move(request)));\n    }\n    Coordination::Responses responses;\n    Coordination::Error code = zookeeper->tryMulti(ops, responses);\n    if (code != Coordination::Error::ZOK\n        && code != Coordination::Error::ZNODEEXISTS)\n        throw Coordination::Exception(code);\n}\n\n\nString DDLWorker::enqueueQuery(DDLLogEntry & entry)\n{\n    if (entry.hosts.empty())\n        throw Exception(\"Empty host list in a distributed DDL task\", ErrorCodes::LOGICAL_ERROR);\n\n    auto zookeeper = getAndSetZooKeeper();\n\n    String query_path_prefix = queue_dir + \"\/query-\";\n    zookeeper->createAncestors(query_path_prefix);\n\n    String node_path = zookeeper->create(query_path_prefix, entry.toString(), zkutil::CreateMode::PersistentSequential);\n\n    \/\/\/ Optional step\n    try\n    {\n        createStatusDirs(node_path, zookeeper);\n    }\n    catch (...)\n    {\n        LOG_INFO(log, \"An error occurred while creating auxiliary ZooKeeper directories in {} . They will be created later. Error : {}\", node_path, getCurrentExceptionMessage(true));\n    }\n\n    return node_path;\n}\n\n\nvoid DDLWorker::runMainThread()\n{\n    setThreadName(\"DDLWorker\");\n    LOG_DEBUG(log, \"Started DDLWorker thread\");\n\n    bool initialized = false;\n    do\n    {\n        try\n        {\n            auto zookeeper = getAndSetZooKeeper();\n            zookeeper->createAncestors(queue_dir + \"\/\");\n            initialized = true;\n        }\n        catch (const Coordination::Exception & e)\n        {\n            if (!Coordination::isHardwareError(e.code))\n                throw;  \/\/\/ A logical error.\n\n            tryLogCurrentException(__PRETTY_FUNCTION__);\n\n            \/\/\/ Avoid busy loop when ZooKeeper is not available.\n            sleepForSeconds(1);\n        }\n        catch (...)\n        {\n            tryLogCurrentException(log, \"Terminating. Cannot initialize DDL queue.\");\n            return;\n        }\n    }\n    while (!initialized && !stop_flag);\n\n    while (!stop_flag)\n    {\n        try\n        {\n            attachToThreadGroup();\n\n            cleanup_event->set();\n            processTasks();\n\n            LOG_DEBUG(log, \"Waiting a watch\");\n            queue_updated_event->wait();\n        }\n        catch (const Coordination::Exception & e)\n        {\n            if (Coordination::isHardwareError(e.code))\n            {\n                LOG_DEBUG(log, \"Recovering ZooKeeper session after: {}\", getCurrentExceptionMessage(false));\n\n                while (!stop_flag)\n                {\n                    try\n                    {\n                        getAndSetZooKeeper();\n                        break;\n                    }\n                    catch (...)\n                    {\n                        tryLogCurrentException(__PRETTY_FUNCTION__);\n\n                        using namespace std::chrono_literals;\n                        std::this_thread::sleep_for(5s);\n                    }\n                }\n            }\n            else if (e.code == Coordination::Error::ZNONODE)\n            {\n                LOG_ERROR(log, \"ZooKeeper error: {}\", getCurrentExceptionMessage(true));\n            }\n            else\n            {\n                LOG_ERROR(log, \"Unexpected ZooKeeper error: {}. Terminating.\", getCurrentExceptionMessage(true));\n                return;\n            }\n        }\n        catch (...)\n        {\n            tryLogCurrentException(log, \"Unexpected error, will terminate:\");\n            return;\n        }\n    }\n}\n\n\nvoid DDLWorker::runCleanupThread()\n{\n    setThreadName(\"DDLWorkerClnr\");\n    LOG_DEBUG(log, \"Started DDLWorker cleanup thread\");\n\n    Int64 last_cleanup_time_seconds = 0;\n    while (!stop_flag)\n    {\n        try\n        {\n            cleanup_event->wait();\n            if (stop_flag)\n                break;\n\n            Int64 current_time_seconds = Poco::Timestamp().epochTime();\n            if (last_cleanup_time_seconds && current_time_seconds < last_cleanup_time_seconds + cleanup_delay_period)\n            {\n                LOG_TRACE(log, \"Too early to clean queue, will do it later.\");\n                continue;\n            }\n\n            auto zookeeper = tryGetZooKeeper();\n            if (zookeeper->expired())\n                continue;\n\n            cleanupQueue(current_time_seconds, zookeeper);\n            last_cleanup_time_seconds = current_time_seconds;\n        }\n        catch (...)\n        {\n            tryLogCurrentException(log, __PRETTY_FUNCTION__);\n        }\n    }\n}\n\n\nclass DDLQueryStatusInputStream : public IBlockInputStream\n{\npublic:\n\n    DDLQueryStatusInputStream(const String & zk_node_path, const DDLLogEntry & entry, const Context & context_)\n        : node_path(zk_node_path), context(context_), watch(CLOCK_MONOTONIC_COARSE), log(&Poco::Logger::get(\"DDLQueryStatusInputStream\"))\n    {\n        sample = Block{\n            {std::make_shared<DataTypeString>(),    \"host\"},\n            {std::make_shared<DataTypeUInt16>(),    \"port\"},\n            {std::make_shared<DataTypeInt64>(),     \"status\"},\n            {std::make_shared<DataTypeString>(),    \"error\"},\n            {std::make_shared<DataTypeUInt64>(),    \"num_hosts_remaining\"},\n            {std::make_shared<DataTypeUInt64>(),    \"num_hosts_active\"},\n        };\n\n        for (const HostID & host: entry.hosts)\n            waiting_hosts.emplace(host.toString());\n\n        addTotalRowsApprox(entry.hosts.size());\n\n        timeout_seconds = context.getSettingsRef().distributed_ddl_task_timeout;\n    }\n\n    String getName() const override\n    {\n        return \"DDLQueryStatusInputStream\";\n    }\n\n    Block getHeader() const override { return sample; }\n\n    Block readImpl() override\n    {\n        Block res;\n        if (num_hosts_finished >= waiting_hosts.size())\n        {\n            if (first_exception)\n                throw Exception(*first_exception);\n\n            return res;\n        }\n\n        auto zookeeper = context.getZooKeeper();\n        size_t try_number = 0;\n\n        while (res.rows() == 0)\n        {\n            if (isCancelled())\n            {\n                if (first_exception)\n                    throw Exception(*first_exception);\n\n                return res;\n            }\n\n            if (timeout_seconds >= 0 && watch.elapsedSeconds() > timeout_seconds)\n            {\n                size_t num_unfinished_hosts = waiting_hosts.size() - num_hosts_finished;\n                size_t num_active_hosts = current_active_hosts.size();\n\n                std::stringstream msg;\n                msg << \"Watching task \" << node_path << \" is executing longer than distributed_ddl_task_timeout\"\n                    << \" (=\" << timeout_seconds << \") seconds.\"\n                    << \" There are \" << num_unfinished_hosts << \" unfinished hosts\"\n                    << \" (\" << num_active_hosts << \" of them are currently active)\"\n                    << \", they are going to execute the query in background\";\n\n                throw Exception(msg.str(), ErrorCodes::TIMEOUT_EXCEEDED);\n            }\n\n            if (num_hosts_finished != 0 || try_number != 0)\n            {\n                auto current_sleep_for = std::chrono::milliseconds(std::min(static_cast<size_t>(1000), 50 * (try_number + 1)));\n                std::this_thread::sleep_for(current_sleep_for);\n            }\n\n            \/\/\/ TODO: add shared lock\n            if (!zookeeper->exists(node_path))\n            {\n                throw Exception(\"Cannot provide query execution status. The query's node \" + node_path\n                                + \" has been deleted by the cleaner since it was finished (or its lifetime is expired)\",\n                                ErrorCodes::UNFINISHED);\n            }\n\n            Strings new_hosts = getNewAndUpdate(getChildrenAllowNoNode(zookeeper, node_path + \"\/finished\"));\n            ++try_number;\n            if (new_hosts.empty())\n                continue;\n\n            current_active_hosts = getChildrenAllowNoNode(zookeeper, node_path + \"\/active\");\n\n            MutableColumns columns = sample.cloneEmptyColumns();\n            for (const String & host_id : new_hosts)\n            {\n                ExecutionStatus status(-1, \"Cannot obtain error message\");\n                {\n                    String status_data;\n                    if (zookeeper->tryGet(node_path + \"\/finished\/\" + host_id, status_data))\n                        status.tryDeserializeText(status_data);\n                }\n\n                auto [host, port] = Cluster::Address::fromString(host_id);\n\n                if (status.code != 0 && first_exception == nullptr)\n                    first_exception = std::make_unique<Exception>(\"There was an error on [\" + host + \":\" + toString(port) + \"]: \" + status.message, status.code);\n\n                ++num_hosts_finished;\n\n                columns[0]->insert(host);\n                columns[1]->insert(port);\n                columns[2]->insert(status.code);\n                columns[3]->insert(status.message);\n                columns[4]->insert(waiting_hosts.size() - num_hosts_finished);\n                columns[5]->insert(current_active_hosts.size());\n            }\n            res = sample.cloneWithColumns(std::move(columns));\n        }\n\n        return res;\n    }\n\n    Block getSampleBlock() const\n    {\n        return sample.cloneEmpty();\n    }\n\n    ~DDLQueryStatusInputStream() override = default;\n\nprivate:\n\n    static Strings getChildrenAllowNoNode(const std::shared_ptr<zkutil::ZooKeeper> & zookeeper, const String & node_path)\n    {\n        Strings res;\n        Coordination::Error code = zookeeper->tryGetChildren(node_path, res);\n        if (code != Coordination::Error::ZOK && code != Coordination::Error::ZNONODE)\n            throw Coordination::Exception(code, node_path);\n        return res;\n    }\n\n    Strings getNewAndUpdate(const Strings & current_list_of_finished_hosts)\n    {\n        Strings diff;\n        for (const String & host : current_list_of_finished_hosts)\n        {\n            if (!waiting_hosts.count(host))\n            {\n                if (!ignoring_hosts.count(host))\n                {\n                    ignoring_hosts.emplace(host);\n                    LOG_INFO(log, \"Unexpected host {} appeared  in task {}\", host, node_path);\n                }\n                continue;\n            }\n\n            if (!finished_hosts.count(host))\n            {\n                diff.emplace_back(host);\n                finished_hosts.emplace(host);\n            }\n        }\n\n        return diff;\n    }\n\n    String node_path;\n    const Context & context;\n    Stopwatch watch;\n    Poco::Logger * log;\n\n    Block sample;\n\n    NameSet waiting_hosts;  \/\/\/ hosts from task host list\n    NameSet finished_hosts; \/\/\/ finished hosts from host list\n    NameSet ignoring_hosts; \/\/\/ appeared hosts that are not in hosts list\n    Strings current_active_hosts; \/\/\/ Hosts that were in active state at the last check\n    size_t num_hosts_finished = 0;\n\n    \/\/\/ Save the first detected error and throw it at the end of execution\n    std::unique_ptr<Exception> first_exception;\n\n    Int64 timeout_seconds = 120;\n};\n\n\nBlockIO executeDDLQueryOnCluster(const ASTPtr & query_ptr_, const Context & context, AccessRightsElements && query_required_access)\n{\n    \/\/\/ Remove FORMAT <fmt> and INTO OUTFILE <file> if exists\n    ASTPtr query_ptr = query_ptr_->clone();\n    ASTQueryWithOutput::resetOutputASTIfExist(*query_ptr);\n\n    \/\/ XXX: serious design flaw since `ASTQueryWithOnCluster` is not inherited from `IAST`!\n    auto * query = dynamic_cast<ASTQueryWithOnCluster *>(query_ptr.get());\n    if (!query)\n    {\n        throw Exception(\"Distributed execution is not supported for such DDL queries\", ErrorCodes::NOT_IMPLEMENTED);\n    }\n\n    if (!context.getSettingsRef().allow_distributed_ddl)\n        throw Exception(\"Distributed DDL queries are prohibited for the user\", ErrorCodes::QUERY_IS_PROHIBITED);\n\n    if (const auto * query_alter = query_ptr->as<ASTAlterQuery>())\n    {\n        for (const auto & command : query_alter->command_list->commands)\n        {\n            if (!isSupportedAlterType(command->type))\n                throw Exception(\"Unsupported type of ALTER query\", ErrorCodes::NOT_IMPLEMENTED);\n        }\n    }\n\n    query->cluster = context.getMacros()->expand(query->cluster);\n    ClusterPtr cluster = context.getCluster(query->cluster);\n    DDLWorker & ddl_worker = context.getDDLWorker();\n\n    \/\/\/ Enumerate hosts which will be used to send query.\n    Cluster::AddressesWithFailover shards = cluster->getShardsAddresses();\n    std::vector<HostID> hosts;\n    for (const auto & shard : shards)\n    {\n        for (const auto & addr : shard)\n            hosts.emplace_back(addr);\n    }\n\n    if (hosts.empty())\n        throw Exception(\"No hosts defined to execute distributed DDL query\", ErrorCodes::LOGICAL_ERROR);\n\n    \/\/\/ The current database in a distributed query need to be replaced with either\n    \/\/\/ the local current database or a shard's default database.\n    bool need_replace_current_database\n        = (std::find_if(\n               query_required_access.begin(),\n               query_required_access.end(),\n               [](const AccessRightsElement & elem) { return elem.isEmptyDatabase(); })\n           != query_required_access.end());\n\n    if (need_replace_current_database)\n    {\n        bool use_local_default_database = false;\n        Strings shard_default_databases;\n        for (const auto & shard : shards)\n        {\n            for (const auto & addr : shard)\n            {\n                if (!addr.default_database.empty())\n                    shard_default_databases.push_back(addr.default_database);\n                else\n                    use_local_default_database = true;\n            }\n        }\n        std::sort(shard_default_databases.begin(), shard_default_databases.end());\n        shard_default_databases.erase(std::unique(shard_default_databases.begin(), shard_default_databases.end()), shard_default_databases.end());\n        assert(use_local_default_database || !shard_default_databases.empty());\n\n        if (use_local_default_database && !shard_default_databases.empty())\n            throw Exception(\"Mixed local default DB and shard default DB in DDL query\", ErrorCodes::NOT_IMPLEMENTED);\n\n        if (use_local_default_database)\n        {\n            const String & current_database = context.getCurrentDatabase();\n            AddDefaultDatabaseVisitor visitor(current_database);\n            visitor.visitDDL(query_ptr);\n\n            query_required_access.replaceEmptyDatabase(current_database);\n        }\n        else\n        {\n            size_t old_num_elements = query_required_access.size();\n            for (size_t i = 0; i != old_num_elements; ++i)\n            {\n                auto & element = query_required_access[i];\n                if (element.isEmptyDatabase())\n                {\n                    element.setDatabase(shard_default_databases[0]);\n                    for (size_t j = 1; j != shard_default_databases.size(); ++j)\n                    {\n                        query_required_access.push_back(element);\n                        query_required_access.back().setDatabase(shard_default_databases[j]);\n                    }\n                }\n            }\n        }\n    }\n\n    \/\/\/ Check access rights, assume that all servers have the same users config\n    context.checkAccess(query_required_access);\n\n    DDLLogEntry entry;\n    entry.hosts = std::move(hosts);\n    entry.query = queryToString(query_ptr);\n    entry.initiator = ddl_worker.getCommonHostID();\n    String node_path = ddl_worker.enqueueQuery(entry);\n\n    BlockIO io;\n    if (context.getSettingsRef().distributed_ddl_task_timeout == 0)\n        return io;\n\n    auto stream = std::make_shared<DDLQueryStatusInputStream>(node_path, entry, context);\n    io.in = std::move(stream);\n    return io;\n}\n\n\nBlockIO executeDDLQueryOnCluster(const ASTPtr & query_ptr_, const Context & context)\n{\n    return executeDDLQueryOnCluster(query_ptr_, context, {});\n}\n\n}\n","avg_line_length":35.3323843416,"max_line_length":214,"alphanum_fraction":0.614177511,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11645,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0","Apache-2.0"],"max_stars_count":6.0,"content":"#include <mbgl\/renderer\/layers\/render_line_layer.hpp>\n#include <mbgl\/renderer\/buckets\/line_bucket.hpp>\n#include <mbgl\/renderer\/render_tile.hpp>\n#include <mbgl\/renderer\/paint_parameters.hpp>\n#include <mbgl\/renderer\/image_manager.hpp>\n#include <mbgl\/programs\/programs.hpp>\n#include <mbgl\/programs\/line_program.hpp>\n#include <mbgl\/geometry\/line_atlas.hpp>\n#include <mbgl\/tile\/tile.hpp>\n#include <mbgl\/style\/layers\/line_layer_impl.hpp>\n#include <mbgl\/geometry\/feature_index.hpp>\n#include <mbgl\/util\/math.hpp>\n#include <mbgl\/util\/intersection_tests.hpp>\n#include <mbgl\/tile\/geometry_tile.hpp>\n\nnamespace mbgl {\n\nusing namespace style;\n\nRenderLineLayer::RenderLineLayer(Immutable<style::LineLayer::Impl> _impl)\n    : RenderLayer(style::LayerType::Line, _impl),\n      unevaluated(impl().paint.untransitioned()),\n      colorRamp({256, 1}) {\n}\n\nconst style::LineLayer::Impl& RenderLineLayer::impl() const {\n    return static_cast<const style::LineLayer::Impl&>(*baseImpl);\n}\n\nstd::unique_ptr<Bucket> RenderLineLayer::createBucket(const BucketParameters&, const std::vector<const RenderLayer*>&) const {\n    assert(false); \/\/ Should be calling createLayout() instead.\n    return nullptr;\n}\n\nstd::unique_ptr<Layout> RenderLineLayer::createLayout(const BucketParameters& parameters,\n                                                      const std::vector<const RenderLayer*>& group,\n                                                      std::unique_ptr<GeometryTileLayer> layer,\n                                                      GlyphDependencies&,\n                                                      ImageDependencies& imageDependencies) const {\n    return std::make_unique<PatternLayout<LineBucket>>(parameters, group, std::move(layer), imageDependencies);\n}\n\nvoid RenderLineLayer::transition(const TransitionParameters& parameters) {\n    unevaluated = impl().paint.transitioned(parameters, std::move(unevaluated));\n}\n\nvoid RenderLineLayer::evaluate(const PropertyEvaluationParameters& parameters) {\n    style::Properties<LineFloorwidth>::Unevaluated extra(unevaluated.get<style::LineWidth>());\n\n    auto dashArrayParams = parameters;\n    dashArrayParams.useIntegerZoom = true;\n\n    evaluated = RenderLinePaintProperties::PossiblyEvaluated(\n    unevaluated.evaluate(parameters).concat(extra.evaluate(dashArrayParams)));\n\n    crossfade = parameters.getCrossfadeParameters();\n\n    passes = (evaluated.get<style::LineOpacity>().constantOr(1.0) > 0\n              && evaluated.get<style::LineColor>().constantOr(Color::black()).a > 0\n              && evaluated.get<style::LineWidth>().constantOr(1.0) > 0)\n             ? RenderPass::Translucent : RenderPass::None;\n}\n\nbool RenderLineLayer::hasTransition() const {\n    return unevaluated.hasTransition();\n}\n\nbool RenderLineLayer::hasCrossfade() const {\n    return crossfade.t != 1;\n}\n\nvoid RenderLineLayer::render(PaintParameters& parameters, RenderSource*) {\n    if (parameters.pass == RenderPass::Opaque) {\n        return;\n    }\n\n    for (const RenderTile& tile : renderTiles) {\n        auto bucket_ = tile.tile.getBucket<LineBucket>(*baseImpl);\n        if (!bucket_) {\n            continue;\n        }\n        LineBucket& bucket = *bucket_;\n\n        auto draw = [&] (auto& program, auto&& uniformValues, const optional<ImagePosition>& patternPositionA, const optional<ImagePosition>& patternPositionB) {\n            auto& programInstance = program.get(evaluated);\n\n            const auto& paintPropertyBinders = bucket.paintPropertyBinders.at(getID());\n\n            paintPropertyBinders.setPatternParameters(patternPositionA, patternPositionB, crossfade);\n\n            const auto allUniformValues = programInstance.computeAllUniformValues(\n                std::move(uniformValues),\n                paintPropertyBinders,\n                evaluated,\n                parameters.state.getZoom()\n            );\n            const auto allAttributeBindings = programInstance.computeAllAttributeBindings(\n                *bucket.vertexBuffer,\n                paintPropertyBinders,\n                evaluated\n            );\n\n            checkRenderability(parameters, programInstance.activeBindingCount(allAttributeBindings));\n\n            programInstance.draw(\n                parameters.context,\n                gl::Triangles(),\n                parameters.depthModeForSublayer(0, gl::DepthMode::ReadOnly),\n                parameters.stencilModeForClipping(tile.clip),\n                parameters.colorModeForRenderPass(),\n                *bucket.indexBuffer,\n                bucket.segments,\n                allUniformValues,\n                allAttributeBindings,\n                getID()\n            );\n        };\n\n        if (!evaluated.get<LineDasharray>().from.empty()) {\n            const LinePatternCap cap = bucket.layout.get<LineCap>() == LineCapType::Round\n                ? LinePatternCap::Round : LinePatternCap::Square;\n            LinePatternPos posA = parameters.lineAtlas.getDashPosition(evaluated.get<LineDasharray>().from, cap);\n            LinePatternPos posB = parameters.lineAtlas.getDashPosition(evaluated.get<LineDasharray>().to, cap);\n\n            parameters.lineAtlas.bind(parameters.context, 0);\n\n            draw(parameters.programs.lineSDF,\n                 LineSDFProgram::uniformValues(\n                     evaluated,\n                     parameters.pixelRatio,\n                     tile,\n                     parameters.state,\n                     parameters.pixelsToGLUnits,\n                     posA,\n                     posB,\n                     crossfade,\n                     parameters.lineAtlas.getSize().width), {}, {});\n\n        } else if (!unevaluated.get<LinePattern>().isUndefined()) {\n            const auto linePatternValue =  evaluated.get<LinePattern>().constantOr(Faded<std::basic_string<char>>{ \"\", \"\"});\n            assert(dynamic_cast<GeometryTile*>(&tile.tile));\n            GeometryTile& geometryTile = static_cast<GeometryTile&>(tile.tile);\n            parameters.context.bindTexture(*geometryTile.iconAtlasTexture, 0, gl::TextureFilter::Linear);\n            const Size texsize = geometryTile.iconAtlasTexture->size;\n\n            optional<ImagePosition> posA = geometryTile.getPattern(linePatternValue.from);\n            optional<ImagePosition> posB = geometryTile.getPattern(linePatternValue.to);\n\n            draw(parameters.programs.linePattern,\n                 LinePatternProgram::uniformValues(\n                     evaluated,\n                     tile,\n                     parameters.state,\n                     parameters.pixelsToGLUnits,\n                     texsize,\n                     crossfade,\n                     parameters.pixelRatio),\n                     *posA,\n                     *posB);\n        } else if (!unevaluated.get<LineGradient>().getValue().isUndefined()) {\n            if (!colorRampTexture) {\n                colorRampTexture = parameters.context.createTexture(colorRamp);\n            }\n            parameters.context.bindTexture(*colorRampTexture, 0, gl::TextureFilter::Linear);\n\n            draw(parameters.programs.lineGradient,\n                 LineGradientProgram::uniformValues(\n                    evaluated,\n                    tile,\n                    parameters.state,\n                    parameters.pixelsToGLUnits), {}, {});\n        } else {\n            draw(parameters.programs.line,\n                 LineProgram::uniformValues(\n                     evaluated,\n                     tile,\n                     parameters.state,\n                     parameters.pixelsToGLUnits), {}, {});\n        }\n    }\n}\n\noptional<GeometryCollection> offsetLine(const GeometryCollection& rings, const double offset) {\n    if (offset == 0) return {};\n\n    GeometryCollection newRings;\n    Point<double> zero(0, 0);\n    for (const auto& ring : rings) {\n        newRings.emplace_back();\n        auto& newRing = newRings.back();\n\n        for (auto i = ring.begin(); i != ring.end(); i++) {\n            auto& p = *i;\n\n            Point<double> aToB = i == ring.begin() ?\n                                 zero :\n                                 util::perp(util::unit(convertPoint<double>(p - *(i - 1))));\n            Point<double> bToC = i + 1 == ring.end() ?\n                                 zero :\n                                 util::perp(util::unit(convertPoint<double>(*(i + 1) - p)));\n            Point<double> extrude = util::unit(aToB + bToC);\n\n            const double cosHalfAngle = extrude.x * bToC.x + extrude.y * bToC.y;\n            extrude *= (1.0 \/ cosHalfAngle);\n\n            newRing.push_back(convertPoint<int16_t>(extrude * offset) + p);\n        }\n    }\n\n    return newRings;\n}\n\nbool RenderLineLayer::queryIntersectsFeature(\n        const GeometryCoordinates& queryGeometry,\n        const GeometryTileFeature& feature,\n        const float zoom,\n        const TransformState& transformState,\n        const float pixelsToTileUnits,\n        const mat4&) const {\n\n    \/\/ Translate query geometry\n    auto translatedQueryGeometry = FeatureIndex::translateQueryGeometry(\n            queryGeometry,\n            evaluated.get<style::LineTranslate>(),\n            evaluated.get<style::LineTranslateAnchor>(),\n            transformState.getAngle(),\n            pixelsToTileUnits);\n\n    \/\/ Evaluate function\n    auto offset = evaluated.get<style::LineOffset>()\n                          .evaluate(feature, zoom, style::LineOffset::defaultValue()) * pixelsToTileUnits;\n\n    \/\/ Apply offset to geometry\n    auto offsetGeometry = offsetLine(feature.getGeometries(), offset);\n\n    \/\/ Test intersection\n    const float halfWidth = getLineWidth(feature, zoom) \/ 2.0 * pixelsToTileUnits;\n    return util::polygonIntersectsBufferedMultiLine(\n            translatedQueryGeometry.value_or(queryGeometry),\n            offsetGeometry.value_or(feature.getGeometries()),\n            halfWidth);\n}\n\nvoid RenderLineLayer::updateColorRamp() {\n    auto colorValue = unevaluated.get<LineGradient>().getValue();\n    if (colorValue.isUndefined()) {\n        return;\n    }\n\n    const auto length = colorRamp.bytes();\n\n    for (uint32_t i = 0; i < length; i += 4) {\n        const auto color = colorValue.evaluate(static_cast<double>(i) \/ length);\n        colorRamp.data[i] = std::floor(color.r * 255);\n        colorRamp.data[i + 1] = std::floor(color.g * 255);\n        colorRamp.data[i + 2] = std::floor(color.b * 255);\n        colorRamp.data[i + 3] = std::floor(color.a * 255);\n    }\n\n    if (colorRampTexture) {\n        colorRampTexture = nullopt;\n    }\n}\n\nRenderLinePaintProperties::PossiblyEvaluated RenderLineLayer::paintProperties() const {\n    return RenderLinePaintProperties::PossiblyEvaluated {\n        evaluated.get<style::LineOpacity>(),\n        evaluated.get<style::LineColor>(),\n        evaluated.get<style::LineTranslate>(),\n        evaluated.get<style::LineTranslateAnchor>(),\n        evaluated.get<style::LineWidth>(),\n        evaluated.get<style::LineGapWidth>(),\n        evaluated.get<style::LineOffset>(),\n        evaluated.get<style::LineBlur>(),\n        evaluated.get<style::LineDasharray>(),\n        evaluated.get<style::LinePattern>(),\n        evaluated.get<style::LineGradient>(),\n        evaluated.get<LineFloorwidth>()\n\n    };\n}\n\nfloat RenderLineLayer::getLineWidth(const GeometryTileFeature& feature, const float zoom) const {\n    float lineWidth = evaluated.get<style::LineWidth>()\n            .evaluate(feature, zoom, style::LineWidth::defaultValue());\n    float gapWidth = evaluated.get<style::LineGapWidth>()\n            .evaluate(feature, zoom, style::LineGapWidth::defaultValue());\n    if (gapWidth) {\n        return gapWidth + 2 * lineWidth;\n    } else {\n        return lineWidth;\n    }\n}\n\n\n} \/\/ namespace mbgl\n","avg_line_length":39.2087542088,"max_line_length":161,"alphanum_fraction":0.6133963074,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":636,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <iostream>\n\nusing namespace std;\n\nint fact(int n) {\n  if (n <= 1) return 1;\n  return n * fact(n - 1);\n}\n\nint nCr(int n, int r) {\n  return fact(n) \/ (fact (n - r) * fact(r));\n}\n\n\/*\n  Pascal's Triangle (n=5)\n  1\n  1 1\n  1 2 1\n  1 3 3 1\n  1 4 6 4 1\n\n      1\n     1 1\n    1 2 1\n   1 3 3 1\n  1 4 6 4 1\n*\/\nint main() {\n  cout<<\"Please enter number 'n' for Pascal's Triangle\"<<endl;\n  int n;\n  cin>>n;\n  cout<<\"Pascal's Triangle(n = \"<<n<<\")\"<<endl;\n  for (int i = 0; i < n; i++) {\n    for (int j = 1; j <= n - i; j++) {\n      cout<<\" \";\n    }\n    for (int j = 0; j <= i; j++) {\n      cout<<nCr(i, j)<<\" \";\n    }\n    cout<<endl;\n  }\n}","avg_line_length":15.1428571429,"max_line_length":62,"alphanum_fraction":0.4544025157,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11777,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/                                                                            \/\/\n\/\/  Copyright (C) 2011-2015, Armory Technologies, Inc.                        \/\/\n\/\/  Distributed under the GNU Affero General Public License (AGPL v3)         \/\/\n\/\/  See LICENSE-ATI or http:\/\/www.gnu.org\/licenses\/agpl.html                  \/\/\n\/\/                                                                            \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <iostream>\n#include <vector>\n#include <map>\n#include <cmath>\n#include <algorithm>\n#include <thread>\n\n#include \"BinaryData.h\"\n#include \"BtcUtils.h\"\n#include \"BlockObj.h\"\n#include \"lmdb_wrapper.h\"\n\nusing namespace std;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid BlockHeader::unserialize(uint8_t const * ptr, uint32_t size)\n{\n   if (size < HEADER_SIZE)\n      throw BlockDeserializingException();\n   dataCopy_.copyFrom(ptr, HEADER_SIZE);\n   BtcUtils::getHash256(dataCopy_.getPtr(), HEADER_SIZE, thisHash_);\n   difficultyDbl_ = BtcUtils::convertDiffBitsToDouble( \n                              BinaryDataRef(dataCopy_.getPtr()+72, 4));\n   isInitialized_ = true;\n   nextHash_ = BinaryData(0);\n   blockHeight_ = UINT32_MAX;\n   difficultySum_ = -1;\n   isMainBranch_ = false;\n   isOrphan_ = true;\n   numTx_ = UINT32_MAX;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid BlockHeader::unserialize(BinaryDataRef const & str) \n{ \n   unserialize(str.getPtr(), str.getSize()); \n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid BlockHeader::unserialize(BinaryRefReader & brr) \n{ \n   unserialize(brr.get_BinaryDataRef(HEADER_SIZE)); \n}\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid BlockHeader::pprint(ostream & os, int nIndent, bool pBigendian) const\n{\n   string indent = \"\";\n   for(int i=0; i<nIndent; i++)\n      indent = indent + \"   \";\n\n   string endstr = (pBigendian ? \" (BE)\" : \" (LE)\");\n   os << indent << \"Block Information: \" << blockHeight_ << endl;\n   os << indent << \"   Hash:       \" \n                << getThisHash().toHexStr(pBigendian).c_str() << endstr << endl;\n   os << indent << \"   Timestamp:  \" << getTimestamp() << endl;\n   os << indent << \"   Prev Hash:  \" \n                << getPrevHash().toHexStr(pBigendian).c_str() << endstr << endl;\n   os << indent << \"   MerkleRoot: \" \n                << getMerkleRoot().toHexStr(pBigendian).c_str() << endstr << endl;\n   os << indent << \"   Difficulty: \" << (difficultyDbl_)\n                         << \"    (\" << getDiffBits().toHexStr().c_str() << \")\" << endl;\n   os << indent << \"   CumulDiff:  \" << (difficultySum_) << endl;\n   os << indent << \"   Nonce:      \" << getNonce() << endl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid BlockHeader::pprintAlot(ostream & os)\n{\n   cout << \"Header:   \" << getBlockHeight() << endl;\n   cout << \"Hash:     \" << getThisHash().toHexStr(true)  << endl;\n   cout << \"Hash:     \" << getThisHash().toHexStr(false) << endl;\n   cout << \"PrvHash:  \" << getPrevHash().toHexStr(true)  << endl;\n   cout << \"PrvHash:  \" << getPrevHash().toHexStr(false) << endl;\n   cout << \"this*:    \" << this << endl;\n   cout << \"TotSize:  \" << getBlockSize() << endl;\n   cout << \"Tx Count: \" << numTx_ << endl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ DBOutPoint Methods\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBinaryDataRef DBOutPoint::getDBkey() const\n{\n   if (DBkey_.getSize() == 8)\n      return DBkey_;\n\n   if (db_ != nullptr)\n   {\n      DBkey_ = move(db_->getDBKeyForHash(txHash_));\n      if (DBkey_.getSize() == 6)\n      {\n         DBkey_.append(WRITE_UINT16_BE((uint16_t)txOutIndex_));\n         return DBkey_;\n      }\n   }\n\n   return BinaryDataRef();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ TxRef methods\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nuint32_t TxRef::getBlockHeight(void) const\n{\n   if (dbKey6B_.getSize() == 6 &&\n      !dbKey6B_.startsWith(DBUtils::ZeroConfHeader_))\n      return DBUtils::hgtxToHeight(dbKey6B_.getSliceCopy(0, 4));\n   else\n      return UINT32_MAX;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nuint8_t TxRef::getDuplicateID(void) const\n{\n   if (dbKey6B_.getSize() == 6)\n      return DBUtils::hgtxToDupID(dbKey6B_.getSliceCopy(0, 4));\n   else\n      return UINT8_MAX;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nuint16_t TxRef::getBlockTxIndex(void) const\n{\n   if (dbKey6B_.getSize() == 6)\n   {\n      if (!dbKey6B_.startsWith(DBUtils::ZeroConfHeader_))\n         return READ_UINT16_BE(dbKey6B_.getPtr() + 4);\n      else\n         return READ_UINT32_BE(dbKey6B_.getPtr() + 2);\n   }\n   else\n      return UINT16_MAX;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TxRef::pprint(ostream & os, int nIndent) const\n{\n   os << \"TxRef Information:\" << endl;\n   \/\/os << \"   Hash:      \" << getThisHash().toHexStr() << endl;\n   os << \"   Height:    \" << getBlockHeight() << endl;\n   os << \"   BlkIndex:  \" << getBlockTxIndex() << endl;\n   \/\/os << \"   FileIdx:   \" << blkFilePtr_.getFileIndex() << endl;\n   \/\/os << \"   FileStart: \" << blkFilePtr_.getStartByte() << endl;\n   \/\/os << \"   NumBytes:  \" << blkFilePtr_.getNumBytes() << endl;\n   os << \"   ----- \" << endl;\n   os << \"   Read from disk, full tx-info: \" << endl;\n   \/\/getTxCopy().pprint(os, nIndent+1); \n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TxRef::setRef(BinaryDataRef bdr)\n{\n   dbKey6B_ = bdr.copy();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ DBTxRef Methods\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nBinaryData DBTxRef::serialize(void) const \n{ \n   return db_->getFullTxCopy(dbKey6B_).serialize();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTx DBTxRef::getTxCopy(void) const\n{\n   return db_->getFullTxCopy(dbKey6B_);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool DBTxRef::isMainBranch(void) const\n{\n   if(dbKey6B_.getSize() != 6)\n      return false;\n   else\n   {\n      uint8_t dup8 = db_->getValidDupIDForHeight(getBlockHeight());\n      return (getDuplicateID() == dup8);\n   }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nBinaryData DBTxRef::getThisHash(void) const\n{\n   return db_->getTxHashForLdbKey(dbKey6B_);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nuint32_t DBTxRef::getBlockTimestamp() const\n{\n   StoredHeader sbh;\n\n   if(dbKey6B_.getSize() == 6)\n   {\n      db_->getStoredHeader(sbh, getBlockHeight(), getDuplicateID(), false);\n      return READ_UINT32_LE(sbh.dataCopy_.getPtr()+68);\n   }\n   else\n      return UINT32_MAX;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nBinaryData DBTxRef::getBlockHash(void) const\n{\n   StoredHeader sbh;\n   if(dbKey6B_.getSize() == 6)\n   {\n      db_->getStoredHeader(sbh, getBlockHeight(), getDuplicateID(), false);\n      return sbh.thisHash_;\n   }\n   else\n      return BtcUtils::EmptyHash();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTxIn  DBTxRef::getTxInCopy(uint32_t i)  \n{\n   return db_->getTxInCopy( dbKey6B_, i);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTxOut DBTxRef::getTxOutCopy(uint32_t i)\n{\n   return db_->getTxOutCopy(dbKey6B_, i);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ UnspentTxOut Methods\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUnspentTxOut::UnspentTxOut(void) :\n   txHash_(BtcUtils::EmptyHash()),\n   txOutIndex_(0),\n   txHeight_(0),\n   value_(0),\n   script_(BinaryData(0)),\n   isMultisigRef_(false)\n{\n   \/\/ Nothing to do here\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nBinaryData UnspentTxOut::getRecipientScrAddr(void) const\n{\n   return BtcUtils::getTxOutScrAddr(getScript());\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nuint32_t UnspentTxOut::getNumConfirm(uint32_t currBlkNum) const\n{\n   if (txHeight_ == UINT32_MAX)\n      throw runtime_error(\"uninitiliazed UnspentTxOut\");\n   \n   return currBlkNum - txHeight_ + 1;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool UnspentTxOut::CompareNaive(UnspentTxOut const & uto1, \n                                UnspentTxOut const & uto2)\n{\n   float val1 = (float)uto1.getValue();\n   float val2 = (float)uto2.getValue();\n   return (val1*uto1.txHeight_ < val2*uto2.txHeight_);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool UnspentTxOut::CompareTech1(UnspentTxOut const & uto1,\n                                UnspentTxOut const & uto2)\n{\n   float val1 = pow((float)uto1.getValue(), 1.0f\/3.0f);\n   float val2 = pow((float)uto2.getValue(), 1.0f\/3.0f);\n   return (val1*uto1.txHeight_ < val2*uto2.txHeight_);\n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool UnspentTxOut::CompareTech2(UnspentTxOut const & uto1,\n                                UnspentTxOut const & uto2)\n{\n   float val1 = pow(log10((float)uto1.getValue()) + 5, 5);\n   float val2 = pow(log10((float)uto2.getValue()) + 5, 5);\n   return (val1*uto1.txHeight_ < val2*uto2.txHeight_);\n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool UnspentTxOut::CompareTech3(UnspentTxOut const & uto1,\n                                UnspentTxOut const & uto2)\n{\n   float val1 = pow(log10((float)uto1.getValue()) + 5, 4);\n   float val2 = pow(log10((float)uto2.getValue()) + 5, 4);\n   return (val1*uto1.txHeight_ < val2*uto2.txHeight_);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid UnspentTxOut::sortTxOutVect(vector<UnspentTxOut> & utovect, int sortType)\n{\n   switch(sortType)\n   {\n   case 0: sort(utovect.begin(), utovect.end(), CompareNaive); break;\n   case 1: sort(utovect.begin(), utovect.end(), CompareTech1); break;\n   case 2: sort(utovect.begin(), utovect.end(), CompareTech2); break;\n   case 3: sort(utovect.begin(), utovect.end(), CompareTech3); break;\n   default: break; \/\/ do nothing\n   }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid UnspentTxOut::pprintOneLine(uint32_t currBlk)\n{\n   printf(\" Tx:%s:%02d   BTC:%0.3f   nConf:%04d\\n\",\n             txHash_.copySwapEndian().getSliceCopy(0,8).toHexStr().c_str(),\n             txOutIndex_,\n             value_\/1e8,\n             getNumConfirm(currBlk));\n}\n\n\/\/ kate: indent-width 3; replace-tabs on;\n\n","avg_line_length":33.1746478873,"max_line_length":87,"alphanum_fraction":0.432283264,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3590,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0","Zlib","Apache-2.0"],"max_stars_count":1.0,"content":"\/\/ --------------------------------------------------------------------------\n\/\/                   OpenMS -- Open-Source Mass Spectrometry\n\/\/ --------------------------------------------------------------------------\n\/\/ Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n\/\/ ETH Zurich, and Freie Universitaet Berlin 2002-2018.\n\/\/\n\/\/ This software is released under a three-clause BSD license:\n\/\/  * Redistributions of source code must retain the above copyright\n\/\/    notice, this list of conditions and the following disclaimer.\n\/\/  * Redistributions in binary form must reproduce the above copyright\n\/\/    notice, this list of conditions and the following disclaimer in the\n\/\/    documentation and\/or other materials provided with the distribution.\n\/\/  * Neither the name of any author or any participating institution\n\/\/    may be used to endorse or promote products derived from this software\n\/\/    without specific prior written permission.\n\/\/ For a full list of authors, refer to the file AUTHORS.\n\/\/ --------------------------------------------------------------------------\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n\/\/ INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n\/\/ OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n\/\/ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n\/\/ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n\/\/ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ --------------------------------------------------------------------------\n\/\/ $Maintainer: Timo Sachsenberg $\n\/\/ $Authors: $\n\/\/ --------------------------------------------------------------------------\n\n#include <OpenMS\/TRANSFORMATIONS\/FEATUREFINDER\/LevMarqFitter1D.h>\nnamespace OpenMS\n{\n\n    void LevMarqFitter1D::optimize_(Eigen::VectorXd& x_init, GenericFunctor& functor)\n    {\n      \/\/TODO: this function is copy&paste from TraceFitter.h. Make a generic wrapper for\n      \/\/LM optimization\n      int data_count = functor.values();\n      int num_params = functor.inputs();\n\n      \/\/ LM always expects N>=p, cause Jacobian be rectangular M x N with M>=N\n      if (data_count < num_params) throw Exception::UnableToFit(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, \"UnableToFit-FinalSet\", \"Skipping feature, we always expects N>=p\");\n\n      Eigen::LevenbergMarquardt<GenericFunctor> lmSolver (functor);\n      lmSolver.parameters.maxfev = max_iteration_;\n      Eigen::LevenbergMarquardtSpace::Status status = lmSolver.minimize(x_init);\n\n      \/\/the states are poorly documented. after checking the source, we believe that\n      \/\/all states except NotStarted, Running and ImproperInputParameters are good\n      \/\/termination states.\n      if (status <= Eigen::LevenbergMarquardtSpace::ImproperInputParameters)\n      {\n          throw Exception::UnableToFit(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, \"UnableToFit-FinalSet\", \"Could not fit the gaussian to the data: Error \" + String(status));\n      }\n    }\n\n    void LevMarqFitter1D::updateMembers_()\n    {\n      Fitter1D::updateMembers_();\n      max_iteration_ = this->param_.getValue(\"max_iteration\");\n    }\n\n\n} \/\/ namespace OpenMS\n","avg_line_length":51.2857142857,"max_line_length":176,"alphanum_fraction":0.6584958217,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":176,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"#include <fast_factorial.hpp>\n\nint FastFactorialImplementation::operator()(const int n) {\n\tint result = 1;\n\t\n\tfor (int i = 0; i < n; ++i)\n\t\tresult *= (n-i);\n\n\treturn result;\n}\n","avg_line_length":16.0,"max_line_length":58,"alphanum_fraction":0.6363636364,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1474,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#define CATCH_CONFIG_MAIN\n#include \"Catch\/single_include\/catch2\/catch.hpp\"\n\n#include \"uitsl\/debug\/compare_files.hpp\"\n\nTEST_CASE(\"compare_files copy\") {\n\n  REQUIRE(\n    uitsl::compare_files( \"assets\/dali.txt\", \"assets\/dali-copy.txt\" )\n  );\n\n  REQUIRE(\n    uitsl::compare_files( \"assets\/wiley.txt\", \"assets\/wiley-copy.txt\" )\n  );\n\n}\n\n\nTEST_CASE(\"compare_files symlink\") {\n\n  REQUIRE(\n    uitsl::compare_files( \"assets\/dali.txt\", \"assets\/dali.txt.symlink\" )\n  );\n\n  REQUIRE(\n    uitsl::compare_files( \"assets\/wiley.txt\", \"assets\/wiley.txt.symlink\" )\n  );\n\n}\n\nTEST_CASE(\"compare_files same file\") {\n\n  REQUIRE(\n    uitsl::compare_files( \"assets\/dali.txt\", \"assets\/dali.txt\" )\n  );\n\n  REQUIRE(\n    uitsl::compare_files( \"assets\/wiley.txt\", \"assets\/wiley.txt\" )\n  );\n\n}\n\n\nTEST_CASE(\"compare_files same symlink\") {\n\n  REQUIRE(\n    uitsl::compare_files( \"assets\/dali.txt.symlink\", \"assets\/dali.txt.symlink\" )\n  );\n\n  REQUIRE(\n    uitsl::compare_files(\"assets\/wiley.txt.symlink\", \"assets\/wiley.txt.symlink\")\n  );\n\n}\n\n\nTEST_CASE(\"compare_files different files\") {\n\n  REQUIRE(\n    ! uitsl::compare_files( \"assets\/dali.txt\", \"assets\/wiley.txt\" )\n  );\n\n  REQUIRE(\n    ! uitsl::compare_files( \"assets\/wiley.txt\", \"assets\/dali.txt\" )\n  );\n\n}\n\n\nTEST_CASE(\"compare_files different file and symlink\") {\n\n  REQUIRE(\n    ! uitsl::compare_files( \"assets\/dali.txt\", \"assets\/wiley.txt.symlink\" )\n  );\n\n  REQUIRE(\n    ! uitsl::compare_files( \"assets\/wiley.txt.symlink\", \"assets\/dali.txt\" )\n  );\n\n}\n","avg_line_length":18.1975308642,"max_line_length":80,"alphanum_fraction":0.6668928087,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1140,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":36.0,"content":"\/* Adding Behavorial Movements*\/\n\n\n#include <iostream>\nusing namespace std;\nclass Machine\n{\n\tclass State *current;\npublic:\n\tMachine();\n\tvoid setCurrent(State *s)\n\t{\n\t\tcurrent = s;\n\t}\n\tvoid Run();\n\tvoid Walk();\n};\n\nclass State\n{\npublic:\n\tvirtual void Run(Machine *m)\n\t{\n\t\tcout << \"   Already Running\\n\";\n\t}\n\tvirtual void Walk(Machine *m)\n\t{\n\t\tcout << \"   Already Walking\\n\";\n\t}\n};\n\nvoid Machine::Run()\n{\n\tcurrent->Run(this);\n}\n\nvoid Machine::Walk()\n{\n\tcurrent->Walk(this);\n}\n\nclass RUN : public State\n{\npublic:\n\tRUN()\n\t{\n\t\tcout << \"   RUN-ctor \";\n\t};\n\t~RUN()\n\t{\n\t\tcout << \"   dtor-RUN\\n\";\n\t};\n\tvoid Walk(Machine *m);\n};\n\nclass WALK : public State\n{\npublic:\n\tWALK()\n\t{\n\t\tcout << \"   WALK-ctor \";\n\t};\n\t~WALK()\n\t{\n\t\tcout << \"   dtor-WALK\\n\";\n\t};\n\tvoid Run(Machine *m)\n\t{\n\t\tcout << \" Changing behaviour from WALK to RUN\";\n\t\tm->setCurrent(new RUN());\n\t\tdelete this;\n\t}\n};\n\nvoid RUN::Walk(Machine *m)\n{\n\tcout << \"   Changing behaviour RUN to WALK\";\n\tm->setCurrent(new WALK());\n\tdelete this;\n}\n\nMachine::Machine()\n{\n\tcurrent = new WALK();\n\tcout << '\\n';\n}\n\nint main()\n{\n\tMachine m;\n\tm.Run();\n\tm.Walk();\n\tm.Walk();\n\n\tint a;\n\tcin >> a;\n\n\treturn 0;\n}\n","avg_line_length":11.4,"max_line_length":49,"alphanum_fraction":0.5771929825,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2262,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/* Copyright (c) 2018 vesoft inc. All rights reserved.\n *\n * This source code is licensed under Apache 2.0 License,\n * attached with Common Clause Condition 1.0, found in the LICENSES directory.\n *\/\n\n#include \"common\/base\/Base.h\"\n#include \"common\/fs\/TempDir.h\"\n#include <gtest\/gtest.h>\n#include \"meta\/test\/TestUtils.h\"\n#include \"meta\/processors\/admin\/HBProcessor.h\"\n\nDECLARE_bool(hosts_whitelist_enabled);\n\nnamespace nebula {\nnamespace meta {\n\nTEST(HBProcessorTest, HBTest) {\n    fs::TempDir rootPath(\"\/tmp\/HBTest.XXXXXX\");\n    std::unique_ptr<kvstore::KVStore> kv(MockCluster::initMetaKV(rootPath.path()));\n    const ClusterID kClusterId = 10;\n    {\n        for (auto i = 0; i < 5; i++) {\n            cpp2::HBReq req;\n            req.set_role(cpp2::HostRole::STORAGE);\n            req.set_host(HostAddr(std::to_string(i), i));\n            req.set_cluster_id(kClusterId);\n            req.set_role(cpp2::HostRole::STORAGE);\n            auto* processor = HBProcessor::instance(kv.get(), nullptr, kClusterId);\n            auto f = processor->getFuture();\n            processor->process(req);\n            auto resp = std::move(f).get();\n            ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, resp.get_code());\n        }\n\n        auto hostsRet =  ActiveHostsMan::getActiveHosts(kv.get(), 1);;\n        ASSERT_TRUE(nebula::ok(hostsRet));\n        ASSERT_EQ(5, nebula::value(hostsRet).size());\n        sleep(3);\n        hostsRet =  ActiveHostsMan::getActiveHosts(kv.get(), 1);;\n        ASSERT_TRUE(nebula::ok(hostsRet));\n        ASSERT_EQ(0, nebula::value(hostsRet).size());\n\n        LOG(INFO) << \"Test for invalid host!\";\n        cpp2::HBReq req;\n        req.set_host(HostAddr(std::to_string(11), 11));\n        req.set_cluster_id(1);\n        req.set_role(cpp2::HostRole::STORAGE);\n        auto* processor = HBProcessor::instance(kv.get(), nullptr);\n        auto f = processor->getFuture();\n        processor->process(req);\n        auto resp = std::move(f).get();\n        ASSERT_EQ(cpp2::ErrorCode::E_WRONGCLUSTER, resp.get_code());\n    }\n}\n\n}  \/\/ namespace meta\n}  \/\/ namespace nebula\n\n\nint main(int argc, char** argv) {\n    testing::InitGoogleTest(&argc, argv);\n    folly::init(&argc, &argv, true);\n    google::SetStderrLogging(google::INFO);\n    return RUN_ALL_TESTS();\n}\n\n","avg_line_length":33.2647058824,"max_line_length":83,"alphanum_fraction":0.6277630416,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8876,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\r\n * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more\r\n * contributor license agreements.  See the NOTICE file distributed with\r\n * this work for additional information regarding copyright ownership.\r\n * The OpenAirInterface Software Alliance licenses this file to You under\r\n * the OAI Public License, Version 1.1  (the \"License\"); you may not use this\r\n * file except in compliance with the License. You may obtain a copy of the\r\n * License at\r\n *\r\n *      http:\/\/www.openairinterface.org\/?page_id=698\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *-------------------------------------------------------------------------------\r\n * For more information about the OpenAirInterface (OAI) Software Alliance:\r\n *      contact@openairinterface.org\r\n *\/\r\n\r\n#include \"DownlinkRANStatusTransfer.hpp\"\r\n#include \"logger.hpp\"\r\n\r\n#include <iostream>\r\n#include <vector>\r\n\r\nextern \"C\" {\r\n#include \"dynamic_memory_check.h\"\r\n}\r\n\r\nusing namespace std;\r\nnamespace ngap {\r\n\r\n\/\/------------------------------------------------------------------------------\r\nDownlinkRANStatusTransfer::DownlinkRANStatusTransfer() {\r\n  amfUeNgapId                            = nullptr;\r\n  ranUeNgapId                            = nullptr;\r\n  ranStatusTransfer_TransparentContainer = nullptr;\r\n  DownlinkranstatustransferIEs           = nullptr;\r\n  DownlinkranstatustransferPDU           = nullptr;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\nDownlinkRANStatusTransfer::~DownlinkRANStatusTransfer() {}\r\n\r\n\/\/------------------------------------------------------------------------------\r\nvoid DownlinkRANStatusTransfer::setAmfUeNgapId(unsigned long id) {\r\n  if (!amfUeNgapId) amfUeNgapId = new AMF_UE_NGAP_ID();\r\n  amfUeNgapId->setAMF_UE_NGAP_ID(id);\r\n\r\n  Ngap_DownlinkRANStatusTransferIEs_t* ie =\r\n      (Ngap_DownlinkRANStatusTransferIEs_t*) calloc(\r\n          1, sizeof(Ngap_DownlinkRANStatusTransferIEs_t));\r\n  ie->id          = Ngap_ProtocolIE_ID_id_AMF_UE_NGAP_ID;\r\n  ie->criticality = Ngap_Criticality_reject;\r\n  ie->value.present =\r\n      Ngap_DownlinkRANStatusTransferIEs__value_PR_AMF_UE_NGAP_ID;\r\n\r\n  int ret = amfUeNgapId->encode2AMF_UE_NGAP_ID(ie->value.choice.AMF_UE_NGAP_ID);\r\n  if (!ret) {\r\n    Logger::ngap().error(\"Encode AMF_UE_NGAP_ID IE error\");\r\n\r\n    free_wrapper((void**) &ie);\r\n    return;\r\n  }\r\n\r\n  ret = ASN_SEQUENCE_ADD(&DownlinkranstatustransferIEs->protocolIEs.list, ie);\r\n  if (ret != 0) Logger::ngap().error(\"Encode AMF_UE_NGAP_ID IE error\");\r\n  \/\/ free_wrapper((void**) &ie);\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\nvoid DownlinkRANStatusTransfer::setRanUeNgapId(uint32_t id) {\r\n  if (!ranUeNgapId) ranUeNgapId = new RAN_UE_NGAP_ID();\r\n  ranUeNgapId->setRanUeNgapId(id);\r\n\r\n  Ngap_DownlinkRANStatusTransferIEs_t* ie =\r\n      (Ngap_DownlinkRANStatusTransferIEs_t*) calloc(\r\n          1, sizeof(Ngap_DownlinkRANStatusTransferIEs_t));\r\n  ie->id          = Ngap_ProtocolIE_ID_id_RAN_UE_NGAP_ID;\r\n  ie->criticality = Ngap_Criticality_reject;\r\n  ie->value.present =\r\n      Ngap_DownlinkRANStatusTransferIEs__value_PR_RAN_UE_NGAP_ID;\r\n\r\n  int ret = ranUeNgapId->encode2RAN_UE_NGAP_ID(ie->value.choice.RAN_UE_NGAP_ID);\r\n  if (!ret) {\r\n    Logger::ngap().error(\"Encode RAN_UE_NGAP_ID IE error\");\r\n    free_wrapper((void**) &ie);\r\n    return;\r\n  }\r\n\r\n  ret = ASN_SEQUENCE_ADD(&DownlinkranstatustransferIEs->protocolIEs.list, ie);\r\n  if (ret != 0) Logger::ngap().error(\"Encode RAN_UE_NGAP_ID IE error\");\r\n  \/\/ free_wrapper((void**) &ie);\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\nvoid DownlinkRANStatusTransfer::setRANStatusTransfer_TransparentContainer(\r\n    long drb_id, long ul_pcdp, long ul_hfn_pdcp, long dl_pcdp,\r\n    long dl_hfn_pdcp) {\r\n  if (!ranStatusTransfer_TransparentContainer) {\r\n    ranStatusTransfer_TransparentContainer =\r\n        new RANStatusTransferTransparentContainer();\r\n  }\r\n  Ngap_DRB_ID_t* dRB_id = (Ngap_DRB_ID_t*) calloc(1, sizeof(Ngap_DRB_ID_t));\r\n  *dRB_id               = drb_id;\r\n  COUNTValueForPDCP_SN18* UL_value =\r\n      (COUNTValueForPDCP_SN18*) calloc(1, sizeof(COUNTValueForPDCP_SN18));\r\n  UL_value->setvalue(ul_pcdp, ul_hfn_pdcp);\r\n  COUNTValueForPDCP_SN18* DL_value =\r\n      (COUNTValueForPDCP_SN18*) calloc(1, sizeof(COUNTValueForPDCP_SN18));\r\n  DL_value->setvalue(dl_pcdp, dl_hfn_pdcp);\r\n  dRBStatusUL18* UL18 = (dRBStatusUL18*) calloc(1, sizeof(dRBStatusUL18));\r\n  UL18->setcountvalue(UL_value);\r\n  DRBStatusDL18* DL18 = (DRBStatusDL18*) calloc(1, sizeof(DRBStatusDL18));\r\n  DL18->setcountvalue(DL_value);\r\n  dRBStatusDL* DL = (dRBStatusDL*) calloc(1, sizeof(dRBStatusDL));\r\n  DL->setDRBStatusDL18(DL18);\r\n  dRBStatusUL* UL = (dRBStatusUL*) calloc(1, sizeof(dRBStatusUL));\r\n  UL->setdRBStatusUL(UL18);\r\n  dRBSubjectItem* m_item = (dRBSubjectItem*) calloc(1, sizeof(dRBSubjectItem));\r\n  m_item->setdRBSubjectItem(dRB_id, UL, DL);\r\n  dRBSubjectList* m_list = (dRBSubjectList*) calloc(1, sizeof(dRBSubjectList));\r\n  m_list->setdRBSubjectItem(m_item, 1);\r\n  ranStatusTransfer_TransparentContainer->setdRBSubject_list(m_list);\r\n  Ngap_DownlinkRANStatusTransferIEs_t* ie =\r\n      (Ngap_DownlinkRANStatusTransferIEs_t*) calloc(\r\n          1, sizeof(Ngap_DownlinkRANStatusTransferIEs_t));\r\n  ie->id = Ngap_ProtocolIE_ID_id_RANStatusTransfer_TransparentContainer;\r\n  ie->criticality = Ngap_Criticality_reject;\r\n  ie->value.present =\r\n      Ngap_DownlinkRANStatusTransferIEs__value_PR_RANStatusTransfer_TransparentContainer;\r\n  bool ret = ranStatusTransfer_TransparentContainer\r\n                 ->encoderanstatustransfer_transparentcontainer(\r\n                     &ie->value.choice.RANStatusTransfer_TransparentContainer);\r\n  if (!ret) {\r\n    Logger::ngap().error(\r\n        \"Encode RANStatusTransfer_TransparentContainer IE error\");\r\n    \/\/ free_wrapper((void**) &dRB_id);\r\n    free_wrapper((void**) &UL_value);\r\n    free_wrapper((void**) &DL_value);\r\n    free_wrapper((void**) &UL18);\r\n    free_wrapper((void**) &DL18);\r\n    free_wrapper((void**) &DL);\r\n    free_wrapper((void**) &UL);\r\n    free_wrapper((void**) &m_item);\r\n    free_wrapper((void**) &m_list);\r\n    free_wrapper((void**) &ie);\r\n  }\r\n  if (ASN_SEQUENCE_ADD(&DownlinkranstatustransferIEs->protocolIEs.list, ie) !=\r\n      0) {\r\n    Logger::ngap().error(\r\n        \"Encode ranstatustransfer_transparentcontainer IE error\");\r\n  }\r\n  \/* free_wrapper((void**) &dRB_id);\r\n   free_wrapper((void**) &UL_value);\r\n   free_wrapper((void**) &DL_value);\r\n   free_wrapper((void**) &UL18);\r\n   free_wrapper((void**) &DL18);\r\n   free_wrapper((void**) &DL);\r\n   free_wrapper((void**) &UL);\r\n   free_wrapper((void**) &m_list);\r\n   free_wrapper((void**) &m_item);\r\n   free_wrapper((void**) &ie);\r\n   *\/\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\nvoid DownlinkRANStatusTransfer::setmessagetype() {\r\n  if (!DownlinkranstatustransferPDU) {\r\n    DownlinkranstatustransferPDU =\r\n        (Ngap_NGAP_PDU_t*) calloc(1, sizeof(Ngap_NGAP_PDU_t));\r\n  }\r\n  MessageType downlinkranstatustransfermessageIEs;\r\n  downlinkranstatustransfermessageIEs.setProcedureCode(\r\n      Ngap_ProcedureCode_id_DownlinkRANStatusTransfer);\r\n  downlinkranstatustransfermessageIEs.setTypeOfMessage(\r\n      Ngap_NGAP_PDU_PR_initiatingMessage);\r\n  downlinkranstatustransfermessageIEs.setCriticality(Ngap_Criticality_ignore);\r\n  downlinkranstatustransfermessageIEs.setValuePresent(\r\n      Ngap_InitiatingMessage__value_PR_DownlinkRANStatusTransfer);\r\n  if (downlinkranstatustransfermessageIEs.getProcedureCode() ==\r\n          Ngap_ProcedureCode_id_DownlinkRANStatusTransfer &&\r\n      downlinkranstatustransfermessageIEs.getTypeOfMessage() ==\r\n          Ngap_NGAP_PDU_PR_initiatingMessage) {\r\n    downlinkranstatustransfermessageIEs.encode2pdu(\r\n        DownlinkranstatustransferPDU);\r\n    DownlinkranstatustransferIEs =\r\n        &(DownlinkranstatustransferPDU->choice.initiatingMessage->value.choice\r\n              .DownlinkRANStatusTransfer);\r\n  } else {\r\n    Logger::ngap().warn(\r\n        \"This information doesn't refer to DownlinkRANStatusTransfer Message\");\r\n  }\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\nint DownlinkRANStatusTransfer::encodetobuffer(uint8_t* buf, int buf_size) {\r\n  asn_fprint(stderr, &asn_DEF_Ngap_NGAP_PDU, DownlinkranstatustransferPDU);\r\n  asn_enc_rval_t er = aper_encode_to_buffer(\r\n      &asn_DEF_Ngap_NGAP_PDU, NULL, DownlinkranstatustransferPDU, buf,\r\n      buf_size);\r\n  Logger::ngap().debug(\"er.encoded( %d )\", er.encoded);\r\n  return er.encoded;\r\n}\r\n}  \/\/ namespace ngap\r\n","avg_line_length":42.6730769231,"max_line_length":90,"alphanum_fraction":0.6676430825,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":9723,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT","BSD-3-Clause"],"max_stars_count":17337.0,"content":"#include \"steam_defs.h\"\n#pragma push_macro(\"__cdecl\")\n#undef __cdecl\n#include \"steamworks_sdk_140\/steam_api.h\"\n#pragma pop_macro(\"__cdecl\")\n#include \"steamclient_private.h\"\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n#define SDKVER_140\n#include \"struct_converters.h\"\n#include \"cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003.h\"\nbool cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_Init(void *linux_side)\n{\n    return ((ISteamHTMLSurface*)linux_side)->Init();\n}\n\nbool cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_Shutdown(void *linux_side)\n{\n    return ((ISteamHTMLSurface*)linux_side)->Shutdown();\n}\n\nSteamAPICall_t cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_CreateBrowser(void *linux_side, const char * pchUserAgent, const char * pchUserCSS)\n{\n    return ((ISteamHTMLSurface*)linux_side)->CreateBrowser((const char *)pchUserAgent, (const char *)pchUserCSS);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_RemoveBrowser(void *linux_side, HHTMLBrowser unBrowserHandle)\n{\n    ((ISteamHTMLSurface*)linux_side)->RemoveBrowser((HHTMLBrowser)unBrowserHandle);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_LoadURL(void *linux_side, HHTMLBrowser unBrowserHandle, const char * pchURL, const char * pchPostData)\n{\n    ((ISteamHTMLSurface*)linux_side)->LoadURL((HHTMLBrowser)unBrowserHandle, (const char *)pchURL, (const char *)pchPostData);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_SetSize(void *linux_side, HHTMLBrowser unBrowserHandle, uint32 unWidth, uint32 unHeight)\n{\n    ((ISteamHTMLSurface*)linux_side)->SetSize((HHTMLBrowser)unBrowserHandle, (uint32)unWidth, (uint32)unHeight);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_StopLoad(void *linux_side, HHTMLBrowser unBrowserHandle)\n{\n    ((ISteamHTMLSurface*)linux_side)->StopLoad((HHTMLBrowser)unBrowserHandle);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_Reload(void *linux_side, HHTMLBrowser unBrowserHandle)\n{\n    ((ISteamHTMLSurface*)linux_side)->Reload((HHTMLBrowser)unBrowserHandle);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_GoBack(void *linux_side, HHTMLBrowser unBrowserHandle)\n{\n    ((ISteamHTMLSurface*)linux_side)->GoBack((HHTMLBrowser)unBrowserHandle);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_GoForward(void *linux_side, HHTMLBrowser unBrowserHandle)\n{\n    ((ISteamHTMLSurface*)linux_side)->GoForward((HHTMLBrowser)unBrowserHandle);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_AddHeader(void *linux_side, HHTMLBrowser unBrowserHandle, const char * pchKey, const char * pchValue)\n{\n    ((ISteamHTMLSurface*)linux_side)->AddHeader((HHTMLBrowser)unBrowserHandle, (const char *)pchKey, (const char *)pchValue);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_ExecuteJavascript(void *linux_side, HHTMLBrowser unBrowserHandle, const char * pchScript)\n{\n    ((ISteamHTMLSurface*)linux_side)->ExecuteJavascript((HHTMLBrowser)unBrowserHandle, (const char *)pchScript);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_MouseUp(void *linux_side, HHTMLBrowser unBrowserHandle, EHTMLMouseButton eMouseButton)\n{\n    ((ISteamHTMLSurface*)linux_side)->MouseUp((HHTMLBrowser)unBrowserHandle, (ISteamHTMLSurface::EHTMLMouseButton)eMouseButton);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_MouseDown(void *linux_side, HHTMLBrowser unBrowserHandle, EHTMLMouseButton eMouseButton)\n{\n    ((ISteamHTMLSurface*)linux_side)->MouseDown((HHTMLBrowser)unBrowserHandle, (ISteamHTMLSurface::EHTMLMouseButton)eMouseButton);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_MouseDoubleClick(void *linux_side, HHTMLBrowser unBrowserHandle, EHTMLMouseButton eMouseButton)\n{\n    ((ISteamHTMLSurface*)linux_side)->MouseDoubleClick((HHTMLBrowser)unBrowserHandle, (ISteamHTMLSurface::EHTMLMouseButton)eMouseButton);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_MouseMove(void *linux_side, HHTMLBrowser unBrowserHandle, int x, int y)\n{\n    ((ISteamHTMLSurface*)linux_side)->MouseMove((HHTMLBrowser)unBrowserHandle, (int)x, (int)y);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_MouseWheel(void *linux_side, HHTMLBrowser unBrowserHandle, int32 nDelta)\n{\n    ((ISteamHTMLSurface*)linux_side)->MouseWheel((HHTMLBrowser)unBrowserHandle, (int32)nDelta);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_KeyDown(void *linux_side, HHTMLBrowser unBrowserHandle, uint32 nNativeKeyCode, EHTMLKeyModifiers eHTMLKeyModifiers)\n{\n    nNativeKeyCode = manual_convert_nNativeKeyCode(nNativeKeyCode);\n    ((ISteamHTMLSurface*)linux_side)->KeyDown((HHTMLBrowser)unBrowserHandle, (uint32)nNativeKeyCode, (ISteamHTMLSurface::EHTMLKeyModifiers)eHTMLKeyModifiers);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_KeyUp(void *linux_side, HHTMLBrowser unBrowserHandle, uint32 nNativeKeyCode, EHTMLKeyModifiers eHTMLKeyModifiers)\n{\n    nNativeKeyCode = manual_convert_nNativeKeyCode(nNativeKeyCode);\n    ((ISteamHTMLSurface*)linux_side)->KeyUp((HHTMLBrowser)unBrowserHandle, (uint32)nNativeKeyCode, (ISteamHTMLSurface::EHTMLKeyModifiers)eHTMLKeyModifiers);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_KeyChar(void *linux_side, HHTMLBrowser unBrowserHandle, uint32 cUnicodeChar, EHTMLKeyModifiers eHTMLKeyModifiers)\n{\n    ((ISteamHTMLSurface*)linux_side)->KeyChar((HHTMLBrowser)unBrowserHandle, (uint32)cUnicodeChar, (ISteamHTMLSurface::EHTMLKeyModifiers)eHTMLKeyModifiers);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_SetHorizontalScroll(void *linux_side, HHTMLBrowser unBrowserHandle, uint32 nAbsolutePixelScroll)\n{\n    ((ISteamHTMLSurface*)linux_side)->SetHorizontalScroll((HHTMLBrowser)unBrowserHandle, (uint32)nAbsolutePixelScroll);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_SetVerticalScroll(void *linux_side, HHTMLBrowser unBrowserHandle, uint32 nAbsolutePixelScroll)\n{\n    ((ISteamHTMLSurface*)linux_side)->SetVerticalScroll((HHTMLBrowser)unBrowserHandle, (uint32)nAbsolutePixelScroll);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_SetKeyFocus(void *linux_side, HHTMLBrowser unBrowserHandle, bool bHasKeyFocus)\n{\n    ((ISteamHTMLSurface*)linux_side)->SetKeyFocus((HHTMLBrowser)unBrowserHandle, (bool)bHasKeyFocus);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_ViewSource(void *linux_side, HHTMLBrowser unBrowserHandle)\n{\n    ((ISteamHTMLSurface*)linux_side)->ViewSource((HHTMLBrowser)unBrowserHandle);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_CopyToClipboard(void *linux_side, HHTMLBrowser unBrowserHandle)\n{\n    ((ISteamHTMLSurface*)linux_side)->CopyToClipboard((HHTMLBrowser)unBrowserHandle);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_PasteFromClipboard(void *linux_side, HHTMLBrowser unBrowserHandle)\n{\n    ((ISteamHTMLSurface*)linux_side)->PasteFromClipboard((HHTMLBrowser)unBrowserHandle);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_Find(void *linux_side, HHTMLBrowser unBrowserHandle, const char * pchSearchStr, bool bCurrentlyInFind, bool bReverse)\n{\n    ((ISteamHTMLSurface*)linux_side)->Find((HHTMLBrowser)unBrowserHandle, (const char *)pchSearchStr, (bool)bCurrentlyInFind, (bool)bReverse);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_StopFind(void *linux_side, HHTMLBrowser unBrowserHandle)\n{\n    ((ISteamHTMLSurface*)linux_side)->StopFind((HHTMLBrowser)unBrowserHandle);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_GetLinkAtPosition(void *linux_side, HHTMLBrowser unBrowserHandle, int x, int y)\n{\n    ((ISteamHTMLSurface*)linux_side)->GetLinkAtPosition((HHTMLBrowser)unBrowserHandle, (int)x, (int)y);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_SetCookie(void *linux_side, const char * pchHostname, const char * pchKey, const char * pchValue, const char * pchPath, RTime32 nExpires, bool bSecure, bool bHTTPOnly)\n{\n    ((ISteamHTMLSurface*)linux_side)->SetCookie((const char *)pchHostname, (const char *)pchKey, (const char *)pchValue, (const char *)pchPath, (RTime32)nExpires, (bool)bSecure, (bool)bHTTPOnly);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_SetPageScaleFactor(void *linux_side, HHTMLBrowser unBrowserHandle, float flZoom, int nPointX, int nPointY)\n{\n    ((ISteamHTMLSurface*)linux_side)->SetPageScaleFactor((HHTMLBrowser)unBrowserHandle, (float)flZoom, (int)nPointX, (int)nPointY);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_SetBackgroundMode(void *linux_side, HHTMLBrowser unBrowserHandle, bool bBackgroundMode)\n{\n    ((ISteamHTMLSurface*)linux_side)->SetBackgroundMode((HHTMLBrowser)unBrowserHandle, (bool)bBackgroundMode);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_AllowStartRequest(void *linux_side, HHTMLBrowser unBrowserHandle, bool bAllowed)\n{\n    ((ISteamHTMLSurface*)linux_side)->AllowStartRequest((HHTMLBrowser)unBrowserHandle, (bool)bAllowed);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_JSDialogResponse(void *linux_side, HHTMLBrowser unBrowserHandle, bool bResult)\n{\n    ((ISteamHTMLSurface*)linux_side)->JSDialogResponse((HHTMLBrowser)unBrowserHandle, (bool)bResult);\n}\n\nvoid cppISteamHTMLSurface_STEAMHTMLSURFACE_INTERFACE_VERSION_003_FileLoadDialogResponse(void *linux_side, HHTMLBrowser unBrowserHandle, const char ** pchSelectedFiles)\n{\n    ((ISteamHTMLSurface*)linux_side)->FileLoadDialogResponse((HHTMLBrowser)unBrowserHandle, (const char **)pchSelectedFiles);\n}\n\n#ifdef __cplusplus\n}\n#endif\n","avg_line_length":50.378238342,"max_line_length":232,"alphanum_fraction":0.8407898797,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1259,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"\/*  Copyright (c) 2021 Mitya Selivanov\n *\n *  This file is part of the Laplace project.\n *\n *  Laplace is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty\n *  of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See\n *  the MIT License for more details.\n *\/\n\n#include \"protocol\/qw_init.h\"\n#include \"protocol\/qw_launch.h\"\n#include \"protocol\/qw_loading.h\"\n#include \"protocol\/qw_order_move.h\"\n#include \"protocol\/qw_player_name.h\"\n#include \"protocol\/qw_slot_create.h\"\n#include \"protocol\/qw_slot_remove.h\"\n#include \"qw_factory.h\"\n\nnamespace quadwar_app {\n  using namespace protocol;\n\n  auto qw_factory::decode(span_cbyte seq) const\n      -> engine::ptr_prime_impact {\n\n    if (qw_slot_create::scan(seq))\n      return make<qw_slot_create>(seq);\n    if (qw_slot_remove::scan(seq))\n      return make<qw_slot_remove>(seq);\n    if (qw_player_name::scan(seq))\n      return make<qw_player_name>(seq);\n    if (qw_init::scan(seq))\n      return make<qw_init>(seq);\n    if (qw_launch::scan(seq))\n      return make<qw_launch>(seq);\n    if (qw_loading::scan(seq))\n      return make<qw_loading>(seq);\n    if (qw_order_move::scan(seq))\n      return make<qw_order_move>(seq);\n\n    return decode_native(seq);\n  }\n}\n","avg_line_length":28.6136363636,"max_line_length":63,"alphanum_fraction":0.7037331215,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3179,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2018 RISC Software GmbH\n\/\/\n\/\/ This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR\/SC).\n\/\/ Do not edit, all changes are lost when files are re-generated.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\")\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <cassert>\n#include <CCPACSRotorHinge.h>\n#include \"CCPACSRotorBladeAttachment.h\"\n#include \"CPACSRotorHubHinges.h\"\n#include \"CTiglError.h\"\n#include \"CTiglLogging.h\"\n#include \"CTiglUIDManager.h\"\n#include \"TixiHelper.h\"\n\nnamespace tigl\n{\nnamespace generated\n{\n    CPACSRotorHubHinges::CPACSRotorHubHinges(CCPACSRotorBladeAttachment* parent, CTiglUIDManager* uidMgr)\n        : m_uidMgr(uidMgr)\n    {\n        \/\/assert(parent != NULL);\n        m_parent = parent;\n    }\n\n    CPACSRotorHubHinges::~CPACSRotorHubHinges()\n    {\n    }\n\n    const CCPACSRotorBladeAttachment* CPACSRotorHubHinges::GetParent() const\n    {\n        return m_parent;\n    }\n\n    CCPACSRotorBladeAttachment* CPACSRotorHubHinges::GetParent()\n    {\n        return m_parent;\n    }\n\n    CTiglUIDManager& CPACSRotorHubHinges::GetUIDManager()\n    {\n        return *m_uidMgr;\n    }\n\n    const CTiglUIDManager& CPACSRotorHubHinges::GetUIDManager() const\n    {\n        return *m_uidMgr;\n    }\n\n    void CPACSRotorHubHinges::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath)\n    {\n        \/\/ read element hinge\n        if (tixi::TixiCheckElement(tixiHandle, xpath + \"\/hinge\")) {\n            tixi::TixiReadElements(tixiHandle, xpath + \"\/hinge\", m_hinges, 1, tixi::xsdUnbounded, reinterpret_cast<CCPACSRotorHinges*>(this), m_uidMgr);\n        }\n\n    }\n\n    void CPACSRotorHubHinges::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const\n    {\n        \/\/ write element hinge\n        tixi::TixiSaveElements(tixiHandle, xpath + \"\/hinge\", m_hinges);\n\n    }\n\n    const std::vector<std::unique_ptr<CCPACSRotorHinge>>& CPACSRotorHubHinges::GetHinges() const\n    {\n        return m_hinges;\n    }\n\n    std::vector<std::unique_ptr<CCPACSRotorHinge>>& CPACSRotorHubHinges::GetHinges()\n    {\n        return m_hinges;\n    }\n\n    CCPACSRotorHinge& CPACSRotorHubHinges::AddHinge()\n    {\n        m_hinges.push_back(make_unique<CCPACSRotorHinge>(reinterpret_cast<CCPACSRotorHinges*>(this), m_uidMgr));\n        return *m_hinges.back();\n    }\n\n    void CPACSRotorHubHinges::RemoveHinge(CCPACSRotorHinge& ref)\n    {\n        for (std::size_t i = 0; i < m_hinges.size(); i++) {\n            if (m_hinges[i].get() == &ref) {\n                m_hinges.erase(m_hinges.begin() + i);\n                return;\n            }\n        }\n        throw CTiglError(\"Element not found\");\n    }\n\n} \/\/ namespace generated\n} \/\/ namespace tigl\n","avg_line_length":29.7102803738,"max_line_length":152,"alphanum_fraction":0.6759987417,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":19419,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["RSA-MD"],"max_stars_count":1.0,"content":"\/*\n** file_zip.cpp\n**\n**---------------------------------------------------------------------------\n** Copyright 1998-2009 Randy Heit\n** Copyright 2005-2009 Christoph Oelckers\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions\n** are met:\n**\n** 1. Redistributions of source code must retain the above copyright\n**    notice, this list of conditions and the following disclaimer.\n** 2. Redistributions in binary form must reproduce the above copyright\n**    notice, this list of conditions and the following disclaimer in the\n**    documentation and\/or other materials provided with the distribution.\n** 3. The name of the author may not be used to endorse or promote products\n**    derived from this software without specific prior written permission.\n**\n** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**---------------------------------------------------------------------------\n**\n**\n*\/\n\n#include <time.h>\n#include \"file_zip.h\"\n#include \"cmdlib.h\"\n\n#include \"printf.h\"\n#include \"w_zip.h\"\n\n#include \"ancientzip.h\"\n\n#define BUFREADCOMMENT (0x400)\n\n\/\/==========================================================================\n\/\/\n\/\/ Decompression subroutine\n\/\/\n\/\/==========================================================================\n\nstatic bool UncompressZipLump(char *Cache, FileReader &Reader, int Method, int LumpSize, int CompressedSize, int GPFlags)\n{\n\ttry\n\t{\n\t\tswitch (Method)\n\t\t{\n\t\tcase METHOD_STORED:\n\t\t{\n\t\t\tReader.Read(Cache, LumpSize);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase METHOD_DEFLATE:\n\t\tcase METHOD_BZIP2:\n\t\tcase METHOD_LZMA:\n\t\t{\n\t\t\tFileReader frz;\n\t\t\tif (frz.OpenDecompressor(Reader, LumpSize, Method, false, [](const char* err) { I_Error(\"%s\", err); }))\n\t\t\t{\n\t\t\t\tfrz.Read(Cache, LumpSize);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ Fixme: These should also use a stream\n\t\tcase METHOD_IMPLODE:\n\t\t{\n\t\t\tFZipExploder exploder;\n\t\t\texploder.Explode((unsigned char *)Cache, LumpSize, Reader, CompressedSize, GPFlags);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase METHOD_SHRINK:\n\t\t{\n\t\t\tShrinkLoop((unsigned char *)Cache, LumpSize, Reader, CompressedSize);\n\t\t\tbreak;\n\t\t}\n\n\t\tdefault:\n\t\t\tassert(0);\n\t\t\treturn false;\n\t\t}\n\t}\n\tcatch (CRecoverableError &err)\n\t{\n\t\tPrintf(\"%s\\n\", err.GetMessage());\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool FCompressedBuffer::Decompress(char *destbuffer)\n{\n\tFileReader mr;\n\tmr.OpenMemory(mBuffer, mCompressedSize);\n\treturn UncompressZipLump(destbuffer, mr, mMethod, mSize, mCompressedSize, mZipFlags);\n}\n\n\/\/-----------------------------------------------------------------------\n\/\/\n\/\/ Finds the central directory end record in the end of the file.\n\/\/ Taken from Quake3 source but the file in question is not GPL'ed. ;)\n\/\/\n\/\/-----------------------------------------------------------------------\n\nstatic uint32_t Zip_FindCentralDir(FileReader &fin)\n{\n\tunsigned char buf[BUFREADCOMMENT + 4];\n\tuint32_t FileSize;\n\tuint32_t uBackRead;\n\tuint32_t uMaxBack; \/\/ maximum size of global comment\n\tuint32_t uPosFound=0;\n\n\tFileSize = (uint32_t)fin.GetLength();\n\tuMaxBack = min<uint32_t>(0xffff, FileSize);\n\n\tuBackRead = 4;\n\twhile (uBackRead < uMaxBack)\n\t{\n\t\tuint32_t uReadSize, uReadPos;\n\t\tint i;\n\t\tif (uBackRead + BUFREADCOMMENT > uMaxBack) \n\t\t\tuBackRead = uMaxBack;\n\t\telse\n\t\t\tuBackRead += BUFREADCOMMENT;\n\t\tuReadPos = FileSize - uBackRead;\n\n\t\tuReadSize = min<uint32_t>((BUFREADCOMMENT + 4), (FileSize - uReadPos));\n\n\t\tif (fin.Seek(uReadPos, FileReader::SeekSet) != 0) break;\n\n\t\tif (fin.Read(buf, (int32_t)uReadSize) != (int32_t)uReadSize) break;\n\n\t\tfor (i = (int)uReadSize - 3; (i--) > 0;)\n\t\t{\n\t\t\tif (buf[i] == 'P' && buf[i+1] == 'K' && buf[i+2] == 5 && buf[i+3] == 6)\n\t\t\t{\n\t\t\t\tuPosFound = uReadPos + i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (uPosFound != 0)\n\t\t\tbreak;\n\t}\n\treturn uPosFound;\n}\n\n\/\/==========================================================================\n\/\/\n\/\/ Zip file\n\/\/\n\/\/==========================================================================\n\nFZipFile::FZipFile(const char * filename, FileReader &file)\n: FResourceFile(filename, file)\n{\n\tLumps = NULL;\n}\n\nbool FZipFile::Open(bool quiet, LumpFilterInfo* filter)\n{\n\tuint32_t centraldir = Zip_FindCentralDir(Reader);\n\tFZipEndOfCentralDirectory info;\n\tint skipped = 0;\n\n\tLumps = NULL;\n\n\tif (centraldir == 0)\n\t{\n\t\tif (!quiet) Printf(TEXTCOLOR_RED \"\\n%s: ZIP file corrupt!\\n\", FileName.GetChars());\n\t\treturn false;\n\t}\n\n\t\/\/ Read the central directory info.\n\tReader.Seek(centraldir, FileReader::SeekSet);\n\tReader.Read(&info, sizeof(FZipEndOfCentralDirectory));\n\n\t\/\/ No multi-disk zips!\n\tif (info.NumEntries != info.NumEntriesOnAllDisks ||\n\t\tinfo.FirstDisk != 0 || info.DiskNumber != 0)\n\t{\n\t\tif (!quiet) Printf(TEXTCOLOR_RED \"\\n%s: Multipart Zip files are not supported.\\n\", FileName.GetChars());\n\t\treturn false;\n\t}\n\n\tNumLumps = LittleShort(info.NumEntries);\n\tLumps = new FZipLump[NumLumps];\n\n\t\/\/ Load the entire central directory. Too bad that this contains variable length entries...\n\tint dirsize = LittleLong(info.DirectorySize);\n\tvoid *directory = malloc(dirsize);\n\tReader.Seek(LittleLong(info.DirectoryOffset), FileReader::SeekSet);\n\tReader.Read(directory, dirsize);\n\n\tchar *dirptr = (char*)directory;\n\tFZipLump *lump_p = Lumps;\n\n\tFString name0, name1;\n\tbool foundspeciallump = false;\n\tbool foundprefix = false;\n\n\t\/\/ Check if all files have the same prefix so that this can be stripped out.\n\t\/\/ This will only be done if there is either a MAPINFO, ZMAPINFO or GAMEINFO lump in the subdirectory, denoting a ZDoom mod.\n\tif (NumLumps > 1) for (uint32_t i = 0; i < NumLumps; i++)\n\t{\n\t\tFZipCentralDirectoryInfo *zip_fh = (FZipCentralDirectoryInfo *)dirptr;\n\n\t\tint len = LittleShort(zip_fh->NameLength);\n\t\tFString name(dirptr + sizeof(FZipCentralDirectoryInfo), len);\n\n\t\tdirptr += sizeof(FZipCentralDirectoryInfo) +\n\t\t\tLittleShort(zip_fh->NameLength) +\n\t\t\tLittleShort(zip_fh->ExtraLength) +\n\t\t\tLittleShort(zip_fh->CommentLength);\n\n\t\tif (dirptr > ((char*)directory) + dirsize)\t\/\/ This directory entry goes beyond the end of the file.\n\t\t{\n\t\t\tfree(directory);\n\t\t\tif (!quiet) Printf(TEXTCOLOR_RED \"\\n%s: Central directory corrupted.\", FileName.GetChars());\n\t\t\treturn false;\n\t\t}\n\n\t\tname.ToLower();\n\t\tif (name.IndexOf(\"filter\/\") == 0)\n\t\t\tcontinue; \/\/ 'filter' is a reserved name of the file system.\n\t\tif (name.IndexOf(\"__macosx\") == 0) \n\t\t\tcontinue; \/\/ skip Apple garbage. At this stage only the root folder matters.\n\t\tif (!foundprefix)\n\t\t{\n\t\t\t\/\/ check for special names, if one of these gets found this must be treated as a normal zip.\n\t\t\tbool isspecial = name.IndexOf(\"\/\") < 0 || (filter && filter->reservedFolders.Find(name) < filter->reservedFolders.Size());\n\t\t\tif (isspecial) break;\n\t\t\tname0 = name.Left(name.LastIndexOf(\"\/\")+1);\n\t\t\tname1 = name.Left(name.IndexOf(\"\/\") + 1);\n\t\t\tfoundprefix = true;\n\t\t}\n\n\t\tif (name.IndexOf(name0) != 0)\n\t\t{\n\t\t\tif (name1.IsNotEmpty())\n\t\t\t{\n\t\t\t\tname0 = name1;\n\t\t\t\tif (name.IndexOf(name0) != 0)\n\t\t\t\t{\n\t\t\t\t\tname0 = \"\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (name0.IsEmpty()) \n\t\t\t\tbreak;\n\t\t}\n\t\tif (!foundspeciallump && filter)\n\t\t{\n\t\t\t\/\/ at least one of the more common definition lumps must be present.\n\t\t\tfor (auto &p : filter->requiredPrefixes)\n\t\t\t{ \n\t\t\t\tif (name.IndexOf(name0 + p) == 0 || name.LastIndexOf(p) == ptrdiff_t(name.Len() - strlen(p)))\n\t\t\t\t{\n\t\t\t\t\tfoundspeciallump = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ If it ran through the list without finding anything it should not attempt any path remapping.\n\tif (!foundspeciallump) name0 = \"\";\n\n\tdirptr = (char*)directory;\n\tlump_p = Lumps;\n\tfor (uint32_t i = 0; i < NumLumps; i++)\n\t{\n\t\tFZipCentralDirectoryInfo *zip_fh = (FZipCentralDirectoryInfo *)dirptr;\n\n\t\tint len = LittleShort(zip_fh->NameLength);\n\t\tFString name(dirptr + sizeof(FZipCentralDirectoryInfo), len);\n\t\tdirptr += sizeof(FZipCentralDirectoryInfo) + \n\t\t\t\t  LittleShort(zip_fh->NameLength) + \n\t\t\t\t  LittleShort(zip_fh->ExtraLength) + \n\t\t\t\t  LittleShort(zip_fh->CommentLength);\n\n\t\tif (dirptr > ((char*)directory) + dirsize)\t\/\/ This directory entry goes beyond the end of the file.\n\t\t{\n\t\t\tfree(directory);\n\t\t\tif (!quiet) Printf(TEXTCOLOR_RED \"\\n%s: Central directory corrupted.\", FileName.GetChars());\n\t\t\treturn false;\n\t\t}\n\n\t\tif (name.IndexOf(\"__macosx\") == 0 || name.IndexOf(\"__MACOSX\") == 0)\n\t\t{\n\t\t\tskipped++;\n\t\t\tcontinue; \/\/ Weed out Apple's resource fork garbage right here because it interferes with safe operation.\n\t\t}\n\t\tif (name0.IsNotEmpty()) name = name.Mid(name0.Len());\n\n\t\t\/\/ skip Directories\n\t\tif (name.IsEmpty() || (name.Back() == '\/' && LittleLong(zip_fh->UncompressedSize) == 0))\n\t\t{\n\t\t\tskipped++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Ignore unknown compression formats\n\t\tzip_fh->Method = LittleShort(zip_fh->Method);\n\t\tif (zip_fh->Method != METHOD_STORED &&\n\t\t\tzip_fh->Method != METHOD_DEFLATE &&\n\t\t\tzip_fh->Method != METHOD_LZMA &&\n\t\t\tzip_fh->Method != METHOD_BZIP2 &&\n\t\t\tzip_fh->Method != METHOD_IMPLODE &&\n\t\t\tzip_fh->Method != METHOD_SHRINK)\n\t\t{\n\t\t\tif (!quiet) Printf(TEXTCOLOR_YELLOW \"\\n%s: '%s' uses an unsupported compression algorithm (#%d).\\n\", FileName.GetChars(), name.GetChars(), zip_fh->Method);\n\t\t\tskipped++;\n\t\t\tcontinue;\n\t\t}\n\t\t\/\/ Also ignore encrypted entries\n\t\tzip_fh->Flags = LittleShort(zip_fh->Flags);\n\t\tif (zip_fh->Flags & ZF_ENCRYPTED)\n\t\t{\n\t\t\tif (!quiet) Printf(TEXTCOLOR_YELLOW \"\\n%s: '%s' is encrypted. Encryption is not supported.\\n\", FileName.GetChars(), name.GetChars());\n\t\t\tskipped++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tFixPathSeperator(name);\n\t\tname.ToLower();\n\n\t\tlump_p->LumpNameSetup(name);\n\t\tlump_p->LumpSize = LittleLong(zip_fh->UncompressedSize);\n\t\tlump_p->Owner = this;\n\t\t\/\/ The start of the Reader will be determined the first time it is accessed.\n\t\tlump_p->Flags = LUMPF_FULLPATH;\n\t\tlump_p->NeedFileStart = true;\n\t\tlump_p->Method = uint8_t(zip_fh->Method);\n\t\tif (lump_p->Method != METHOD_STORED) lump_p->Flags |= LUMPF_COMPRESSED;\n\t\tlump_p->GPFlags = zip_fh->Flags;\n\t\tlump_p->CRC32 = zip_fh->CRC32;\n\t\tlump_p->CompressedSize = LittleLong(zip_fh->CompressedSize);\n\t\tlump_p->Position = LittleLong(zip_fh->LocalHeaderOffset);\n\t\tlump_p->CheckEmbedded(filter);\n\n\t\tlump_p++;\n\t}\n\t\/\/ Resize the lump record array to its actual size\n\tNumLumps -= skipped;\n\tfree(directory);\n\n\tGenerateHash();\n\tPostProcessArchive(&Lumps[0], sizeof(FZipLump), filter);\n\treturn true;\n}\n\n\/\/==========================================================================\n\/\/\n\/\/ Zip file\n\/\/\n\/\/==========================================================================\n\nFZipFile::~FZipFile()\n{\n\tif (Lumps != NULL) delete [] Lumps;\n}\n\n\/\/==========================================================================\n\/\/\n\/\/\n\/\/\n\/\/==========================================================================\n\nFCompressedBuffer FZipLump::GetRawData()\n{\n\tFCompressedBuffer cbuf = { (unsigned)LumpSize, (unsigned)CompressedSize, Method, GPFlags, CRC32, new char[CompressedSize] };\n\tif (NeedFileStart) SetLumpAddress();\n\tOwner->Reader.Seek(Position, FileReader::SeekSet);\n\tOwner->Reader.Read(cbuf.mBuffer, CompressedSize);\n\treturn cbuf;\n}\n\n\/\/==========================================================================\n\/\/\n\/\/ SetLumpAddress\n\/\/\n\/\/==========================================================================\n\nvoid FZipLump::SetLumpAddress()\n{\n\t\/\/ This file is inside a zip and has not been opened before.\n\t\/\/ Position points to the start of the local file header, which we must\n\t\/\/ read and skip so that we can get to the actual file data.\n\tFZipLocalFileHeader localHeader;\n\tint skiplen;\n\n\tOwner->Reader.Seek(Position, FileReader::SeekSet);\n\tOwner->Reader.Read(&localHeader, sizeof(localHeader));\n\tskiplen = LittleShort(localHeader.NameLength) + LittleShort(localHeader.ExtraLength);\n\tPosition += sizeof(localHeader) + skiplen;\n\tNeedFileStart = false;\n}\n\n\/\/==========================================================================\n\/\/\n\/\/ Get reader (only returns non-NULL if not encrypted)\n\/\/\n\/\/==========================================================================\n\nFileReader *FZipLump::GetReader()\n{\n\t\/\/ Don't return the reader if this lump is encrypted\n\t\/\/ In that case always force caching of the lump\n\tif (Method == METHOD_STORED)\n\t{\n\t\tif (NeedFileStart) SetLumpAddress();\n\t\tOwner->Reader.Seek(Position, FileReader::SeekSet);\n\t\treturn &Owner->Reader;\n\t}\n\telse return NULL;\t\n}\n\n\/\/==========================================================================\n\/\/\n\/\/ Fills the lump cache and performs decompression\n\/\/\n\/\/==========================================================================\n\nint FZipLump::FillCache()\n{\n\tif (NeedFileStart) SetLumpAddress();\n\tconst char *buffer;\n\n\tif (Method == METHOD_STORED && (buffer = Owner->Reader.GetBuffer()) != NULL)\n\t{\n\t\t\/\/ This is an in-memory file so the cache can point directly to the file's data.\n\t\tCache = const_cast<char*>(buffer) + Position;\n\t\tRefCount = -1;\n\t\treturn -1;\n\t}\n\n\tOwner->Reader.Seek(Position, FileReader::SeekSet);\n\tCache = new char[LumpSize];\n\tUncompressZipLump(Cache, Owner->Reader, Method, LumpSize, CompressedSize, GPFlags);\n\tRefCount = 1;\n\treturn 1;\n}\n\n\/\/==========================================================================\n\/\/\n\/\/\n\/\/\n\/\/==========================================================================\n\nint FZipLump::GetFileOffset()\n{\n\tif (Method != METHOD_STORED) return -1;\n\tif (NeedFileStart) SetLumpAddress();\n\treturn Position;\n}\n\n\/\/==========================================================================\n\/\/\n\/\/ File open\n\/\/\n\/\/==========================================================================\n\nFResourceFile *CheckZip(const char *filename, FileReader &file, bool quiet, LumpFilterInfo* filter)\n{\n\tchar head[4];\n\n\tif (file.GetLength() >= (long)sizeof(FZipLocalFileHeader))\n\t{\n\t\tfile.Seek(0, FileReader::SeekSet);\n\t\tfile.Read(&head, 4);\n\t\tfile.Seek(0, FileReader::SeekSet);\n\t\tif (!memcmp(head, \"PK\\x3\\x4\", 4))\n\t\t{\n\t\t\tauto rf = new FZipFile(filename, file);\n\t\t\tif (rf->Open(quiet, filter)) return rf;\n\n\t\t\tfile = std::move(rf->Reader); \/\/ to avoid destruction of reader\n\t\t\tdelete rf;\n\t\t}\n\t}\n\treturn NULL;\n}\n\n\n\n\/\/==========================================================================\n\/\/\n\/\/ time_to_dos\n\/\/\n\/\/ Converts time from struct tm to the DOS format used by zip files.\n\/\/\n\/\/==========================================================================\n\nstatic std::pair<uint16_t, uint16_t> time_to_dos(struct tm *time)\n{\n\tstd::pair<uint16_t, uint16_t> val;\n\tif (time == NULL || time->tm_year < 80)\n\t{\n\t\tval.first = val.second = 0;\n\t}\n\telse\n\t{\n\t\tval.first = (time->tm_year - 80) * 512 + (time->tm_mon + 1) * 32 + time->tm_mday;\n\t\tval.second= time->tm_hour * 2048 + time->tm_min * 32 + time->tm_sec \/ 2;\n\t}\n\treturn val;\n}\n\n\/\/==========================================================================\n\/\/\n\/\/ append_to_zip\n\/\/\n\/\/ Write a given file to the zipFile.\n\/\/ \n\/\/ zipfile: zip object to be written to\n\/\/ \n\/\/ returns: position = success, -1 = error\n\/\/\n\/\/==========================================================================\n\nint AppendToZip(FileWriter *zip_file, const char *filename, FCompressedBuffer &content, std::pair<uint16_t, uint16_t> &dostime)\n{\n\tFZipLocalFileHeader local;\n\tint position;\n\n\tlocal.Magic = ZIP_LOCALFILE;\n\tlocal.VersionToExtract[0] = 20;\n\tlocal.VersionToExtract[1] = 0;\n\tlocal.Flags = content.mMethod == METHOD_DEFLATE ? LittleShort((uint16_t)2) : LittleShort((uint16_t)content.mZipFlags);\n\tlocal.Method = LittleShort((uint16_t)content.mMethod);\n\tlocal.ModDate = LittleShort(dostime.first);\n\tlocal.ModTime = LittleShort(dostime.second);\n\tlocal.CRC32 = content.mCRC32;\n\tlocal.UncompressedSize = LittleLong(content.mSize);\n\tlocal.CompressedSize = LittleLong(content.mCompressedSize);\n\tlocal.NameLength = LittleShort((unsigned short)strlen(filename));\n\tlocal.ExtraLength = 0;\n\n\t\/\/ Fill in local directory header.\n\n\tposition = (int)zip_file->Tell();\n\n\t\/\/ Write out the header, file name, and file data.\n\tif (zip_file->Write(&local, sizeof(local)) != sizeof(local) ||\n\t\tzip_file->Write(filename, strlen(filename)) != strlen(filename) ||\n\t\tzip_file->Write(content.mBuffer, content.mCompressedSize) != content.mCompressedSize)\n\t{\n\t\treturn -1;\n\t}\n\treturn position;\n}\n\n\n\/\/==========================================================================\n\/\/\n\/\/ write_central_dir\n\/\/\n\/\/ Writes the central directory entry for a file.\n\/\/\n\/\/==========================================================================\n\nint AppendCentralDirectory(FileWriter *zip_file, const char *filename, FCompressedBuffer &content, std::pair<uint16_t, uint16_t> &dostime, int position)\n{\n\tFZipCentralDirectoryInfo dir;\n\n\tdir.Magic = ZIP_CENTRALFILE;\n\tdir.VersionMadeBy[0] = 20;\n\tdir.VersionMadeBy[1] = 0;\n\tdir.VersionToExtract[0] = 20;\n\tdir.VersionToExtract[1] = 0;\n\tdir.Flags = content.mMethod == METHOD_DEFLATE ? LittleShort((uint16_t)2) : LittleShort((uint16_t)content.mZipFlags);\n\tdir.Method = LittleShort((uint16_t)content.mMethod);\n\tdir.ModTime = LittleShort(dostime.first);\n\tdir.ModDate = LittleShort(dostime.second);\n\tdir.CRC32 = content.mCRC32;\n\tdir.CompressedSize = LittleLong(content.mCompressedSize);\n\tdir.UncompressedSize = LittleLong(content.mSize);\n\tdir.NameLength = LittleShort((unsigned short)strlen(filename));\n\tdir.ExtraLength = 0;\n\tdir.CommentLength = 0;\n\tdir.StartingDiskNumber = 0;\n\tdir.InternalAttributes = 0;\n\tdir.ExternalAttributes = 0;\n\tdir.LocalHeaderOffset = LittleLong(position);\n\n\tif (zip_file->Write(&dir, sizeof(dir)) != sizeof(dir) ||\n\t\tzip_file->Write(filename,  strlen(filename)) != strlen(filename))\n\t{\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nbool WriteZip(const char *filename, TArray<FString> &filenames, TArray<FCompressedBuffer> &content)\n{\n\t\/\/ try to determine local time\n\tstruct tm *ltime;\n\ttime_t ttime;\n\tttime = time(nullptr);\n\tltime = localtime(&ttime);\n\tauto dostime = time_to_dos(ltime);\n\n\tTArray<int> positions;\n\n\tif (filenames.Size() != content.Size()) return false;\n\n\tauto f = FileWriter::Open(filename);\n\tif (f != nullptr)\n\t{\n\t\tfor (unsigned i = 0; i < filenames.Size(); i++)\n\t\t{\n\t\t\tint pos = AppendToZip(f, filenames[i], content[i], dostime);\n\t\t\tif (pos == -1)\n\t\t\t{\n\t\t\t\tdelete f;\n\t\t\t\tremove(filename);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tpositions.Push(pos);\n\t\t}\n\n\t\tint dirofs = (int)f->Tell();\n\t\tfor (unsigned i = 0; i < filenames.Size(); i++)\n\t\t{\n\t\t\tif (AppendCentralDirectory(f, filenames[i], content[i], dostime, positions[i]) < 0)\n\t\t\t{\n\t\t\t\tdelete f;\n\t\t\t\tremove(filename);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Write the directory terminator.\n\t\tFZipEndOfCentralDirectory dirend;\n\t\tdirend.Magic = ZIP_ENDOFDIR;\n\t\tdirend.DiskNumber = 0;\n\t\tdirend.FirstDisk = 0;\n\t\tdirend.NumEntriesOnAllDisks = dirend.NumEntries = LittleShort((uint16_t)filenames.Size());\n\t\tdirend.DirectoryOffset = LittleLong(dirofs);\n\t\tdirend.DirectorySize = LittleLong((uint32_t)(f->Tell() - dirofs));\n\t\tdirend.ZipCommentLength = 0;\n\t\tif (f->Write(&dirend, sizeof(dirend)) != sizeof(dirend))\n\t\t{\n\t\t\tdelete f;\n\t\t\tremove(filename);\n\t\t\treturn false;\n\t\t}\n\t\tdelete f;\n\t\treturn true;\n\t}\n\treturn false;\n}\n","avg_line_length":29.2015037594,"max_line_length":158,"alphanum_fraction":0.6192903857,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":24067,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":null,"content":"\/*\n * Copyright (C) 2011 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/#define USE_LOG SLAndroidLogLevel_Verbose\n\n#include \"sles_allinclusive.h\"\n\n#include <media\/stagefright\/foundation\/ADebug.h>\n#include <sys\/stat.h>\n#include <inttypes.h>\n\nnamespace android {\n\n\/\/--------------------------------------------------------------------------------------------------\nGenericPlayer::GenericPlayer(const AudioPlayback_Parameters* params) :\n        mDataLocatorType(kDataLocatorNone),\n        mNotifyClient(NULL),\n        mNotifyUser(NULL),\n        mStateFlags(0),\n        mPlaybackParams(*params),\n        mDurationMsec(ANDROID_UNKNOWN_TIME),\n        mPlaybackRatePermille(1000),\n        mCacheStatus(kStatusEmpty),\n        mCacheFill(0),\n        mLastNotifiedCacheFill(0),\n        mCacheFillNotifThreshold(100),\n        mEventFlags(0),\n        mMarkerPositionMs(ANDROID_UNKNOWN_TIME),\n        mPositionUpdatePeriodMs(1000), \/\/ per spec\n        mOneShotGeneration(0),\n        mDeliveredNewPosMs(ANDROID_UNKNOWN_TIME),\n        mObservedPositionMs(ANDROID_UNKNOWN_TIME)\n{\n    SL_LOGD(\"GenericPlayer::GenericPlayer()\");\n\n    mLooper = new android::ALooper();\n\n    \/\/ Post-construction accesses need to be protected by mSettingsLock\n    mAndroidAudioLevels.mFinalVolume[0] = 1.0f;\n    mAndroidAudioLevels.mFinalVolume[1] = 1.0f;\n}\n\n\nGenericPlayer::~GenericPlayer() {\n    SL_LOGV(\"GenericPlayer::~GenericPlayer()\");\n\n    resetDataLocator();\n}\n\n\nvoid GenericPlayer::init(const notif_cbf_t cbf, void* notifUser) {\n    SL_LOGD(\"GenericPlayer::init()\");\n\n    {\n        android::Mutex::Autolock autoLock(mNotifyClientLock);\n        mNotifyClient = cbf;\n        mNotifyUser = notifUser;\n    }\n\n    mLooper->registerHandler(this);\n    mLooper->start(false \/*runOnCallingThread*\/, false \/*canCallJava*\/, PRIORITY_DEFAULT);\n}\n\n\nvoid GenericPlayer::preDestroy() {\n    SL_LOGD(\"GenericPlayer::preDestroy()\");\n    {\n        android::Mutex::Autolock autoLock(mNotifyClientLock);\n        mNotifyClient = NULL;\n        mNotifyUser = NULL;\n    }\n\n    mLooper->stop();\n    mLooper->unregisterHandler(id());\n}\n\n\nvoid GenericPlayer::setDataSource(const char *uri) {\n    SL_LOGV(\"GenericPlayer::setDataSource(uri=%s)\", uri);\n    resetDataLocator();\n\n    mDataLocator.uriRef = uri;\n\n    mDataLocatorType = kDataLocatorUri;\n}\n\n\nvoid GenericPlayer::setDataSource(int fd, int64_t offset, int64_t length, bool closeAfterUse) {\n    SL_LOGV(\"GenericPlayer::setDataSource(fd=%d, offset=%lld, length=%lld, closeAfterUse=%s)\", fd,\n            offset, length, closeAfterUse ? \"true\" : \"false\");\n    resetDataLocator();\n\n    mDataLocator.fdi.fd = fd;\n\n    struct stat sb;\n    int ret = fstat(fd, &sb);\n    if (ret != 0) {\n        SL_LOGE(\"GenericPlayer::setDataSource: fstat(%d) failed: %d, %s\", fd, ret, strerror(errno));\n        return;\n    }\n\n    if (offset >= sb.st_size) {\n        SL_LOGE(\"SfPlayer::setDataSource: invalid offset\");\n        return;\n    }\n    mDataLocator.fdi.offset = offset;\n\n    if (PLAYER_FD_FIND_FILE_SIZE == length) {\n        mDataLocator.fdi.length = sb.st_size;\n    } else if (offset + length > sb.st_size) {\n        mDataLocator.fdi.length = sb.st_size - offset;\n    } else {\n        mDataLocator.fdi.length = length;\n    }\n\n    mDataLocator.fdi.mCloseAfterUse = closeAfterUse;\n\n    mDataLocatorType = kDataLocatorFd;\n}\n\n\nvoid GenericPlayer::prepare() {\n    SL_LOGD(\"GenericPlayer::prepare()\");\n    \/\/ do not attempt prepare more than once\n    if (!(mStateFlags & (kFlagPrepared | kFlagPreparedUnsuccessfully))) {\n        sp<AMessage> msg = new AMessage(kWhatPrepare, this);\n        msg->post();\n    }\n}\n\n\nvoid GenericPlayer::play() {\n    SL_LOGD(\"GenericPlayer::play()\");\n    sp<AMessage> msg = new AMessage(kWhatPlay, this);\n    msg->post();\n}\n\n\nvoid GenericPlayer::pause() {\n    SL_LOGD(\"GenericPlayer::pause()\");\n    sp<AMessage> msg = new AMessage(kWhatPause, this);\n    msg->post();\n}\n\n\nvoid GenericPlayer::stop() {\n    SL_LOGD(\"GenericPlayer::stop()\");\n    (new AMessage(kWhatPause, this))->post();\n\n    \/\/ after a stop, playback should resume from the start.\n    seek(0);\n}\n\n\nvoid GenericPlayer::seek(int64_t timeMsec) {\n    SL_LOGV(\"GenericPlayer::seek %lld\", timeMsec);\n    if (timeMsec < 0 && timeMsec != ANDROID_UNKNOWN_TIME) {\n        SL_LOGE(\"GenericPlayer::seek error, can't seek to negative time %\" PRId64 \"ms\", timeMsec);\n        return;\n    }\n    sp<AMessage> msg = new AMessage(kWhatSeek, this);\n    msg->setInt64(WHATPARAM_SEEK_SEEKTIME_MS, timeMsec);\n    msg->post();\n}\n\n\nvoid GenericPlayer::loop(bool loop) {\n    SL_LOGV(\"GenericPlayer::loop %s\", loop ? \"true\" : \"false\");\n    sp<AMessage> msg = new AMessage(kWhatLoop, this);\n    msg->setInt32(WHATPARAM_LOOP_LOOPING, (int32_t)loop);\n    msg->post();\n}\n\n\nvoid GenericPlayer::setBufferingUpdateThreshold(int16_t thresholdPercent) {\n    SL_LOGV(\"GenericPlayer::setBufferingUpdateThreshold %d\", thresholdPercent);\n    sp<AMessage> msg = new AMessage(kWhatBuffUpdateThres, this);\n    msg->setInt32(WHATPARAM_BUFFERING_UPDATETHRESHOLD_PERCENT, (int32_t)thresholdPercent);\n    msg->post();\n}\n\n\n\/\/--------------------------------------------------\nvoid GenericPlayer::getDurationMsec(int* msec) {\n    Mutex::Autolock _l(mSettingsLock);\n    *msec = mDurationMsec;\n}\n\n\/\/--------------------------------------------------\nvoid GenericPlayer::setVolume(float leftVol, float rightVol)\n{\n    {\n        Mutex::Autolock _l(mSettingsLock);\n        mAndroidAudioLevels.mFinalVolume[0] = leftVol;\n        mAndroidAudioLevels.mFinalVolume[1] = rightVol;\n    }\n    \/\/ send a message for the volume to be updated by the object which implements the volume\n    (new AMessage(kWhatVolumeUpdate, this))->post();\n}\n\n\n\/\/--------------------------------------------------\nvoid GenericPlayer::attachAuxEffect(int32_t effectId)\n{\n    SL_LOGV(\"GenericPlayer::attachAuxEffect(id=%d)\", effectId);\n    sp<AMessage> msg = new AMessage(kWhatAttachAuxEffect, this);\n    msg->setInt32(WHATPARAM_ATTACHAUXEFFECT, effectId);\n    msg->post();\n}\n\n\n\/\/--------------------------------------------------\nvoid GenericPlayer::setAuxEffectSendLevel(float level)\n{\n    SL_LOGV(\"GenericPlayer::setAuxEffectSendLevel(level=%g)\", level);\n    sp<AMessage> msg = new AMessage(kWhatSetAuxEffectSendLevel, this);\n    msg->setFloat(WHATPARAM_SETAUXEFFECTSENDLEVEL, level);\n    msg->post();\n}\n\n\n\/\/--------------------------------------------------\nvoid GenericPlayer::setPlaybackRate(int32_t ratePermille) {\n    SL_LOGV(\"GenericPlayer::setPlaybackRate(ratePermille=%d)\", ratePermille);\n    {\n        Mutex::Autolock _l(mSettingsLock);\n        mPlaybackRatePermille = (int16_t)ratePermille;\n    }\n}\n\n\/\/--------------------------------------------------\n\/\/ Call after changing any of the IPlay settings related to SL_PLAYEVENT_*\nvoid GenericPlayer::setPlayEvents(int32_t eventFlags, int32_t markerPositionMs,\n        int32_t positionUpdatePeriodMs)\n{\n    \/\/ Normalize ms that are within the valid unsigned range, but not in the int32_t range\n    if (markerPositionMs < 0) {\n        markerPositionMs = ANDROID_UNKNOWN_TIME;\n    }\n    if (positionUpdatePeriodMs < 0) {\n        positionUpdatePeriodMs = ANDROID_UNKNOWN_TIME;\n    }\n    \/\/ markers are delivered accurately, but new position updates are limited to every 100 ms\n    if (positionUpdatePeriodMs < 100) {\n        positionUpdatePeriodMs = 100;\n    }\n    sp<AMessage> msg = new AMessage(kWhatSetPlayEvents, this);\n    msg->setInt32(WHATPARAM_SETPLAYEVENTS_FLAGS, eventFlags);\n    msg->setInt32(WHATPARAM_SETPLAYEVENTS_MARKER, markerPositionMs);\n    msg->setInt32(WHATPARAM_SETPLAYEVENTS_UPDATE, positionUpdatePeriodMs);\n    msg->post();\n}\n\n\n\/\/--------------------------------------------------\n\/*\n * post-condition: mDataLocatorType == kDataLocatorNone\n *\n *\/\nvoid GenericPlayer::resetDataLocator() {\n    SL_LOGV(\"GenericPlayer::resetDataLocator()\");\n    if (mDataLocatorType == kDataLocatorFd && mDataLocator.fdi.mCloseAfterUse) {\n        (void) ::close(mDataLocator.fdi.fd);\n        \/\/ would be redundant, as we're about to invalidate the union mDataLocator\n        \/\/mDataLocator.fdi.fd = -1;\n        \/\/mDataLocator.fdi.mCloseAfterUse = false;\n    }\n    mDataLocatorType = kDataLocatorNone;\n}\n\n\nvoid GenericPlayer::notify(const char* event, int data, bool async) {\n    SL_LOGV(\"GenericPlayer::notify(event=%s, data=%d, async=%s)\", event, data,\n            async ? \"true\" : \"false\");\n    sp<AMessage> msg = new AMessage(kWhatNotif, this);\n    msg->setInt32(event, (int32_t)data);\n    if (async) {\n        msg->post();\n    } else {\n        onNotify(msg);\n    }\n}\n\n\nvoid GenericPlayer::notify(const char* event, int data1, int data2, bool async) {\n    SL_LOGV(\"GenericPlayer::notify(event=%s, data1=%d, data2=%d, async=%s)\", event, data1, data2,\n            async ? \"true\" : \"false\");\n    sp<AMessage> msg = new AMessage(kWhatNotif, this);\n    msg->setRect(event, 0, 0, (int32_t)data1, (int32_t)data2);\n    if (async) {\n        msg->post();\n    } else {\n        onNotify(msg);\n    }\n}\n\n\n\/\/--------------------------------------------------\n\/\/ AHandler implementation\nvoid GenericPlayer::onMessageReceived(const sp<AMessage> &msg) {\n    SL_LOGV(\"GenericPlayer::onMessageReceived()\");\n    switch (msg->what()) {\n        case kWhatPrepare:\n            SL_LOGV(\"kWhatPrepare\");\n            onPrepare();\n            break;\n\n        case kWhatNotif:\n            SL_LOGV(\"kWhatNotif\");\n            onNotify(msg);\n            break;\n\n        case kWhatPlay:\n            SL_LOGV(\"kWhatPlay\");\n            onPlay();\n            break;\n\n        case kWhatPause:\n            SL_LOGV(\"kWhatPause\");\n            onPause();\n            break;\n\n        case kWhatSeek:\n            SL_LOGV(\"kWhatSeek\");\n            onSeek(msg);\n            break;\n\n        case kWhatLoop:\n            SL_LOGV(\"kWhatLoop\");\n            onLoop(msg);\n            break;\n\n        case kWhatVolumeUpdate:\n            SL_LOGV(\"kWhatVolumeUpdate\");\n            onVolumeUpdate();\n            break;\n\n        case kWhatSeekComplete:\n            SL_LOGV(\"kWhatSeekComplete\");\n            onSeekComplete();\n            break;\n\n        case kWhatBufferingUpdate:\n            SL_LOGV(\"kWhatBufferingUpdate\");\n            onBufferingUpdate(msg);\n            break;\n\n        case kWhatBuffUpdateThres:\n            SL_LOGV(\"kWhatBuffUpdateThres\");\n            onSetBufferingUpdateThreshold(msg);\n            break;\n\n        case kWhatAttachAuxEffect:\n            SL_LOGV(\"kWhatAttachAuxEffect\");\n            onAttachAuxEffect(msg);\n            break;\n\n        case kWhatSetAuxEffectSendLevel:\n            SL_LOGV(\"kWhatSetAuxEffectSendLevel\");\n            onSetAuxEffectSendLevel(msg);\n            break;\n\n        case kWhatSetPlayEvents:\n            SL_LOGV(\"kWhatSetPlayEvents\");\n            onSetPlayEvents(msg);\n            break;\n\n        case kWhatOneShot:\n            SL_LOGV(\"kWhatOneShot\");\n            onOneShot(msg);\n            break;\n\n        default:\n            SL_LOGE(\"GenericPlayer::onMessageReceived unknown message %d\", msg->what());\n            TRESPASS();\n    }\n}\n\n\n\/\/--------------------------------------------------\n\/\/ Event handlers\n\/\/  it is strictly verboten to call those methods outside of the event loop\n\nvoid GenericPlayer::onPrepare() {\n    SL_LOGV(\"GenericPlayer::onPrepare()\");\n    \/\/ Subclass is responsible for indicating whether prepare was successful or unsuccessful\n    \/\/ by updating mStateFlags accordingly.  It must set exactly one of these two flags.\n    assert(!(mStateFlags & kFlagPrepared) != !(mStateFlags & kFlagPreparedUnsuccessfully));\n    notify(PLAYEREVENT_PREPARED, mStateFlags & kFlagPrepared ? PLAYER_SUCCESS : PLAYER_FAILURE,\n            true \/*async*\/);\n    SL_LOGD(\"GenericPlayer::onPrepare() done, mStateFlags=0x%x\", mStateFlags);\n}\n\n\nvoid GenericPlayer::onNotify(const sp<AMessage> &msg) {\n    SL_LOGV(\"GenericPlayer::onNotify()\");\n    notif_cbf_t notifClient;\n    void*       notifUser;\n    {\n        android::Mutex::Autolock autoLock(mNotifyClientLock);\n        if (NULL == mNotifyClient) {\n            return;\n        } else {\n            notifClient = mNotifyClient;\n            notifUser   = mNotifyUser;\n        }\n    }\n\n    int32_t val1, val2;\n    if (msg->findInt32(PLAYEREVENT_PREFETCHSTATUSCHANGE, &val1)) {\n        SL_LOGV(\"GenericPlayer notifying %s = %d\", PLAYEREVENT_PREFETCHSTATUSCHANGE, val1);\n        notifClient(kEventPrefetchStatusChange, val1, 0, notifUser);\n    \/\/ There is exactly one notification per message, hence \"else if\" instead of \"if\"\n    } else if (msg->findInt32(PLAYEREVENT_PREFETCHFILLLEVELUPDATE, &val1)) {\n        SL_LOGV(\"GenericPlayer notifying %s = %d\", PLAYEREVENT_PREFETCHFILLLEVELUPDATE, val1);\n        notifClient(kEventPrefetchFillLevelUpdate, val1, 0, notifUser);\n    } else if (msg->findInt32(PLAYEREVENT_ENDOFSTREAM, &val1)) {\n        SL_LOGV(\"GenericPlayer notifying %s = %d\", PLAYEREVENT_ENDOFSTREAM, val1);\n        notifClient(kEventEndOfStream, val1, 0, notifUser);\n    } else if (msg->findInt32(PLAYEREVENT_PREPARED, &val1)) {\n        SL_LOGV(\"GenericPlayer notifying %s = %d\", PLAYEREVENT_PREPARED, val1);\n        notifClient(kEventPrepared, val1, 0, notifUser);\n    } else if (msg->findInt32(PLAYEREVENT_CHANNEL_COUNT, &val1)) {\n        SL_LOGV(\"GenericPlayer notifying %s = %d\", PLAYEREVENT_CHANNEL_COUNT, val1);\n        notifClient(kEventChannelCount, val1, 0, notifUser);\n    } else if (msg->findRect(PLAYEREVENT_VIDEO_SIZE_UPDATE, &val1, &val2, &val1, &val2)) {\n        SL_LOGV(\"GenericPlayer notifying %s = %d, %d\", PLAYEREVENT_VIDEO_SIZE_UPDATE, val1, val2);\n        notifClient(kEventHasVideoSize, val1, val2, notifUser);\n    } else if (msg->findInt32(PLAYEREVENT_PLAY, &val1)) {\n        SL_LOGV(\"GenericPlayer notifying %s = %d\", PLAYEREVENT_PLAY, val1);\n        notifClient(kEventPlay, val1, 0, notifUser);\n    } else if (msg->findInt32(PLAYEREVENT_ERRORAFTERPREPARE, &val1)) {\n        SL_LOGV(\"GenericPlayer notifying %s = %d\", PLAYEREVENT_ERRORAFTERPREPARE, val1);\n        notifClient(kEventErrorAfterPrepare, val1, 0, notifUser);\n    } else {\n        SL_LOGV(\"GenericPlayer notifying unknown\");\n    }\n}\n\n\nvoid GenericPlayer::onPlay() {\n    SL_LOGD(\"GenericPlayer::onPlay()\");\n    if ((mStateFlags & (kFlagPrepared | kFlagPlaying)) == kFlagPrepared) {\n        SL_LOGD(\"starting player\");\n        mStateFlags |= kFlagPlaying;\n        updateOneShot();\n    }\n}\n\n\nvoid GenericPlayer::onPause() {\n    SL_LOGD(\"GenericPlayer::onPause()\");\n    if (!(~mStateFlags & (kFlagPrepared | kFlagPlaying))) {\n        SL_LOGV(\"pausing player\");\n        mStateFlags &= ~kFlagPlaying;\n        updateOneShot();\n    }\n}\n\n\nvoid GenericPlayer::onSeek(const sp<AMessage> &msg) {\n    SL_LOGV(\"GenericPlayer::onSeek\");\n}\n\n\nvoid GenericPlayer::onLoop(const sp<AMessage> &msg) {\n    SL_LOGV(\"GenericPlayer::onLoop\");\n}\n\n\nvoid GenericPlayer::onVolumeUpdate() {\n    SL_LOGV(\"GenericPlayer::onVolumeUpdate\");\n}\n\n\nvoid GenericPlayer::onSeekComplete() {\n    SL_LOGD(\"GenericPlayer::onSeekComplete()\");\n    mStateFlags &= ~kFlagSeeking;\n    \/\/ avoid spurious or lost events caused by seeking past a marker\n    mDeliveredNewPosMs = ANDROID_UNKNOWN_TIME;\n    mObservedPositionMs = ANDROID_UNKNOWN_TIME;\n    updateOneShot();\n}\n\n\nvoid GenericPlayer::onBufferingUpdate(const sp<AMessage> &msg) {\n    SL_LOGV(\"GenericPlayer::onBufferingUpdate\");\n}\n\n\nvoid GenericPlayer::onSetBufferingUpdateThreshold(const sp<AMessage> &msg) {\n    SL_LOGV(\"GenericPlayer::onSetBufferingUpdateThreshold\");\n    int32_t thresholdPercent = 0;\n    if (msg->findInt32(WHATPARAM_BUFFERING_UPDATETHRESHOLD_PERCENT, &thresholdPercent)) {\n        Mutex::Autolock _l(mSettingsLock);\n        mCacheFillNotifThreshold = (int16_t)thresholdPercent;\n    }\n}\n\n\nvoid GenericPlayer::onAttachAuxEffect(const sp<AMessage> &msg) {\n    SL_LOGV(\"GenericPlayer::onAttachAuxEffect()\");\n}\n\n\nvoid GenericPlayer::onSetAuxEffectSendLevel(const sp<AMessage> &msg) {\n    SL_LOGV(\"GenericPlayer::onSetAuxEffectSendLevel()\");\n}\n\n\nvoid GenericPlayer::onSetPlayEvents(const sp<AMessage> &msg) {\n    SL_LOGV(\"GenericPlayer::onSetPlayEvents()\");\n    int32_t eventFlags, markerPositionMs, positionUpdatePeriodMs;\n    if (msg->findInt32(WHATPARAM_SETPLAYEVENTS_FLAGS, &eventFlags) &&\n            msg->findInt32(WHATPARAM_SETPLAYEVENTS_MARKER, &markerPositionMs) &&\n            msg->findInt32(WHATPARAM_SETPLAYEVENTS_UPDATE, &positionUpdatePeriodMs)) {\n        mEventFlags = eventFlags;\n        mMarkerPositionMs = markerPositionMs;\n        mPositionUpdatePeriodMs = positionUpdatePeriodMs;\n        updateOneShot();\n    }\n}\n\n\nvoid GenericPlayer::onOneShot(const sp<AMessage> &msg) {\n    SL_LOGV(\"GenericPlayer::onOneShot()\");\n    int32_t generation;\n    if (msg->findInt32(WHATPARAM_ONESHOT_GENERATION, &generation)) {\n        if (generation != mOneShotGeneration) {\n            SL_LOGV(\"GenericPlayer::onOneShot() generation %d cancelled; latest is %d\",\n                    generation, mOneShotGeneration);\n            return;\n        }\n        updateOneShot();\n    }\n}\n\n\n\/\/-------------------------------------------------\nvoid GenericPlayer::notifyStatus() {\n    SL_LOGV(\"GenericPlayer::notifyStatus\");\n    notify(PLAYEREVENT_PREFETCHSTATUSCHANGE, (int32_t)mCacheStatus, true \/*async*\/);\n}\n\n\nvoid GenericPlayer::notifyCacheFill() {\n    SL_LOGV(\"GenericPlayer::notifyCacheFill\");\n    mLastNotifiedCacheFill = mCacheFill;\n    notify(PLAYEREVENT_PREFETCHFILLLEVELUPDATE, (int32_t)mLastNotifiedCacheFill, true\/*async*\/);\n}\n\n\nvoid GenericPlayer::seekComplete() {\n    SL_LOGV(\"GenericPlayer::seekComplete\");\n    sp<AMessage> msg = new AMessage(kWhatSeekComplete, this);\n    msg->post();\n}\n\n\nvoid GenericPlayer::bufferingUpdate(int16_t fillLevelPerMille) {\n    SL_LOGV(\"GenericPlayer::bufferingUpdate\");\n    sp<AMessage> msg = new AMessage(kWhatBufferingUpdate, this);\n    msg->setInt32(WHATPARAM_BUFFERING_UPDATE, fillLevelPerMille);\n    msg->post();\n}\n\n\n\/\/ For the meaning of positionMs, see comment in declaration at android_GenericPlayer.h\nvoid GenericPlayer::updateOneShot(int positionMs)\n{\n    SL_LOGV(\"GenericPlayer::updateOneShot\");\n\n    \/\/ nop until prepared\n    if (!(mStateFlags & kFlagPrepared)) {\n        return;\n    }\n\n    \/\/ cancel any pending one-shot(s)\n    ++mOneShotGeneration;\n\n    \/\/ don't restart one-shot if player is paused or stopped\n    if (!(mStateFlags & kFlagPlaying)) {\n        return;\n    }\n\n    \/\/ get current player position in milliseconds\n    if (positionMs < 0) {\n        positionMs = ANDROID_UNKNOWN_TIME;\n    }\n    if (positionMs == ANDROID_UNKNOWN_TIME) {\n        getPositionMsec(&positionMs);\n        \/\/ normalize it\n        if (positionMs < 0) {\n            positionMs = ANDROID_UNKNOWN_TIME;\n        }\n        if (ANDROID_UNKNOWN_TIME == positionMs) {\n            \/\/ getPositionMsec is not working for some reason, give up\n            \/\/ALOGV(\"Does anyone really know what time it is?\");\n            return;\n        }\n    }\n\n    \/\/ if we observe the player position going backwards, even without without a seek, then recover\n    if (mObservedPositionMs != ANDROID_UNKNOWN_TIME && positionMs < mObservedPositionMs) {\n        mDeliveredNewPosMs = ANDROID_UNKNOWN_TIME;\n        mObservedPositionMs = positionMs;\n    }\n\n    \/\/ delayUs is the expected delay between current position and marker;\n    \/\/ the default is infinity in case there are no upcoming marker(s)\n    int64_t delayUs = -1;\n\n    \/\/ is there a marker?\n    if ((mEventFlags & SL_PLAYEVENT_HEADATMARKER) && (mMarkerPositionMs != ANDROID_UNKNOWN_TIME)) {\n        \/\/ check to see if we have observed the position passing through the marker\n        if (mObservedPositionMs <= mMarkerPositionMs && mMarkerPositionMs <= positionMs) {\n            notify(PLAYEREVENT_PLAY, (int32_t) SL_PLAYEVENT_HEADATMARKER, true \/*async*\/);\n        } else if (positionMs < mMarkerPositionMs) {\n            delayUs = (mMarkerPositionMs - positionMs) * 1000LL;\n        }\n    }\n\n    \/\/ are periodic position updates needed?\n    if ((mEventFlags & SL_PLAYEVENT_HEADATNEWPOS) &&\n            (mPositionUpdatePeriodMs != ANDROID_UNKNOWN_TIME)) {\n        \/\/ check to see if we have observed the position passing through a virtual marker, where the\n        \/\/ virtual marker is at the previously delivered new position plus position update period\n        int32_t virtualMarkerMs;\n        if (mDeliveredNewPosMs != ANDROID_UNKNOWN_TIME) {\n            virtualMarkerMs = mDeliveredNewPosMs + mPositionUpdatePeriodMs;\n        } else if (mObservedPositionMs != ANDROID_UNKNOWN_TIME) {\n            virtualMarkerMs = mObservedPositionMs + mPositionUpdatePeriodMs;\n            \/\/ pretend there has been an update in the past\n            mDeliveredNewPosMs = mObservedPositionMs;\n        } else {\n            virtualMarkerMs = positionMs + mPositionUpdatePeriodMs;\n            \/\/ pretend there has been an update in the past\n            mDeliveredNewPosMs = positionMs;\n        }\n        \/\/ nextVirtualMarkerMs will be set to the position of the next upcoming virtual marker\n        int32_t nextVirtualMarkerMs;\n        if (mObservedPositionMs <= virtualMarkerMs && virtualMarkerMs <= positionMs) {\n            \/\/ we did pass through the virtual marker, now compute the next virtual marker\n            mDeliveredNewPosMs = virtualMarkerMs;\n            nextVirtualMarkerMs = virtualMarkerMs + mPositionUpdatePeriodMs;\n            \/\/ re-synchronize if we missed an update\n            if (nextVirtualMarkerMs <= positionMs) {\n                SL_LOGW(\"Missed SL_PLAYEVENT_HEADATNEWPOS for position %d; current position %d\",\n                        nextVirtualMarkerMs, positionMs);\n                \/\/ try to catch up by setting next goal to current position plus update period\n                mDeliveredNewPosMs = positionMs;\n                nextVirtualMarkerMs = positionMs + mPositionUpdatePeriodMs;\n            }\n            notify(PLAYEREVENT_PLAY, (int32_t) SL_PLAYEVENT_HEADATNEWPOS, true \/*async*\/);\n        } else {\n            \/\/ we did not pass through the virtual marker yet, so use same marker again\n            nextVirtualMarkerMs = virtualMarkerMs;\n        }\n        \/\/ note that if arithmetic overflow occurred, nextVirtualMarkerMs will be negative\n        if (positionMs < nextVirtualMarkerMs) {\n            int64_t trialDelayUs;\n            trialDelayUs = (nextVirtualMarkerMs - positionMs) * 1000LL;\n            if (trialDelayUs > 0 && (delayUs == -1 || trialDelayUs < delayUs)) {\n                delayUs = trialDelayUs;\n            }\n        }\n    }\n\n    \/\/ we have a new observed position\n    mObservedPositionMs = positionMs;\n\n    if (mPlaybackRatePermille == 0) {\n        \/\/ playback is frozen, no update expected (and no division by zero below)\n        return;\n    }\n\n    \/\/ post the new one-shot message if needed\n    if (advancesPositionInRealTime() && delayUs >= 0) {\n        \/\/ scale delay according to playback rate (reported positions won't change, but reported\n        \/\/ time will advance slower or faster depending on rate)\n        {\n            Mutex::Autolock _l(mSettingsLock);\n            delayUs =  delayUs * 1000 \/ mPlaybackRatePermille;\n        }\n\n        \/\/ 20 ms min delay to avoid near busy waiting\n        if (delayUs < 20000LL) {\n            delayUs = 20000LL;\n        }\n        \/\/ 1 minute max delay avoids indefinite memory leaks caused by cancelled one-shots\n        if (delayUs > 60000000LL) {\n            delayUs = 60000000LL;\n        }\n        \/\/SL_LOGI(\"delayUs = %lld\", delayUs);\n        sp<AMessage> msg = new AMessage(kWhatOneShot, this);\n        msg->setInt32(WHATPARAM_ONESHOT_GENERATION, mOneShotGeneration);\n        msg->post(delayUs);\n    }\n\n}\n\n} \/\/ namespace android\n","avg_line_length":33.6131284916,"max_line_length":100,"alphanum_fraction":0.6469854988,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1237,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <preprocessor\/calculator.h>\n\n#include <cassert>\n#include <vector>\n#include <preprocessor\/utility.h>\n\nusing namespace std;\n\nnamespace {\n\nusing namespace pp;\n\nstd::vector<std::string_view> integer_suffixes = {\n\t\"L\",\n\t\"LU\",\n\t\"Lu\",\n\t\"l\",\n\t\"lU\",\n\t\"lu\",\n\t\"LL\",\n\t\"LLU\",\n\t\"LLu\",\n\t\"ll\",\n\t\"llU\",\n\t\"llu\",\n\t\"U\",\n\t\"UL\",\n\t\"ULL\",\n\t\"Ul\",\n\t\"Ull\",\n\t\"u\",\n\t\"uL\",\n\t\"uLL\",\n\t\"ul\",\n\t\"ull\",\n};\n\n}\t\/\/  anonymous namespace\n\nnamespace pp {\n\nvoid init_calculator() {\n\tsort(integer_suffixes.begin(), integer_suffixes.end());\n}\n\nbool parse_int(const std::string& s, target_intmax_t* result) {\n\tassert(result != nullptr);\n\n\t*result = 0;\n\tif (s.empty()) {\n\t\treturn false;\n\t}\n\n\tsize_t i = 0;\n\tif (s[i] == '+' || s[i] == '-') {\n\t\ti++;\n\t}\n\tint base = (s[i] != '0')\n\t\t? 10\n\t\t: ((s.length() >= (i + 2)) && (s[i + 1] == 'x') ? 16 : 8);\n\n\ttry {\n\t\tsize_t next = 0;\n\t\ttarget_intmax_t n = stoul(s, &next, base);\n\t\tif (next != s.length()) {\n\t\t\tstring_view maybe_suffix(&s[next]);\n\t\t\tauto found = binary_find(begin(integer_suffixes), end(integer_suffixes), maybe_suffix);\n\t\t\tif ((found == end(integer_suffixes)) || (next + size(*found) != s.length())) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t*result = n;\n\t\treturn true;\n\t}\n\tcatch (...) {\n\t\treturn false;\n\t}\n}\n\n}   \/\/  namespace pp\n","avg_line_length":15.0853658537,"max_line_length":90,"alphanum_fraction":0.5658852061,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":512,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include \"duckdb\/common\/serializer.hpp\"\n\nnamespace duckdb {\n\ntemplate <>\nstring Deserializer::Read() {\n\tuint32_t size = Read<uint32_t>();\n\tif (size == 0) {\n\t\treturn string();\n\t}\n\tauto buffer = unique_ptr<data_t[]>(new data_t[size]);\n\tReadData(buffer.get(), size);\n\treturn string((char *)buffer.get(), size);\n}\n\nvoid Deserializer::ReadStringVector(vector<string> &list) {\n\tuint32_t sz = Read<uint32_t>();\n\tlist.resize(sz);\n\tfor (idx_t i = 0; i < sz; i++) {\n\t\tlist[i] = Read<string>();\n\t}\n}\n\n} \/\/ namespace duckdb\n","avg_line_length":20.48,"max_line_length":59,"alphanum_fraction":0.654296875,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4838,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["WTFPL"],"max_stars_count":1.0,"content":"#include \"linker.hpp\"\n\n#include \"error.hpp\"\n\nnamespace BASIC {\n\nbinary_code_t linker::link(const object_code_t& obj)\n{\n\tbin.clear();\n\tl2l.clear();\n\tlineno_map.clear();\n\n\tfor (auto& line : obj) {\n\t\tlineno_map[line.first] = bin.size();\n\t\tauto& a = line.second;\n\t\tswitch (a.type) {\n\t\tcase command::BASIC_REM:\n\t\t\tbreak;\n\t\tcase command::BASIC_LET:\n\t\t\texpand_expr(a.expr);\n\t\t\tpop_to_var(a.target_var);\n\t\t\tbreak;\n\t\tcase command::BASIC_PRINT:\n\t\t\texpand_expr(a.expr);\n\t\t\tprogram_print();\n\t\t\tbreak;\n\t\tcase command::BASIC_INPUT:\n\t\t\tinput_variable(a.target_var);\n\t\t\tbreak;\n\t\tcase command::BASIC_GOTO:\n\t\t\tprogram_goto(a.target_lineno);\n\t\t\tbreak;\n\t\tcase command::BASIC_IF:\n\t\t\tif_condition(a.expr, a.expr2, a.cmp, a.target_lineno);\n\t\t\tbreak;\n\t\tcase command::BASIC_END:\n\t\t\tprogram_end();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(0);\n\t\t}\n\t}\n\n\t\/\/ link line numbers\n\tlinkall_lineno();\n\n\treturn bin;\n}\n\nvoid linker::expand_expr(const expr_t& expr)\n{\n\tfor (auto& token : expr) {\n\t\tinstruction ins;\n\t\tstd::memset(&ins, 0, sizeof(ins));\n\t\tswitch (token.type) {\n\t\tcase expr_token::IMMEDIATE:\n\t\t\tins.op_lo = (instruction::OP_PUSH << 4) | 1;\n\t\t\tins.operand[0] = token.num;\n\t\t\tbreak;\n\t\tcase expr_token::VARIABLE:\n\t\t\tins.op_lo = (instruction::OP_PUSH << 4) | 2;\n\t\t\tins.operand[0] = get_var_addr(token.str);\n\t\t\tbreak;\n\t\tcase expr_token::OPERATOR:\n\t\t\tins.op_lo = (get_operator_op(token.str) << 4) | 0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(0);\n\t\t}\n\t\tbin.push_back(std::move(ins));\n\t}\n}\n\nvoid linker::pop_to_var(const std::string& var)\n{\n\tauto addr = get_var_addr(var);\n\tinstruction ins;\n\tstd::memset(&ins, 0, sizeof(ins));\n\tins.op_lo = (instruction::OP_POP << 4) | 2;\n\tins.operand[0] = addr;\n\tbin.push_back(std::move(ins));\n}\n\nvoid linker::program_print()\n{\n\tinstruction ins;\n\tstd::memset(&ins, 0, sizeof(ins));\n\tins.op_lo = (instruction::OP_PRINT << 4) | 0;\n\tbin.push_back(std::move(ins));\n}\n\nvoid linker::input_variable(const std::string& var)\n{\n\tinstruction ins;\n\tstd::memset(&ins, 0, sizeof(ins));\n\tins.op_lo = (instruction::OP_INPUT << 4) | 0;\n\tbin.push_back(std::move(ins));\n\tpop_to_var(var);\n}\n\nvoid linker::program_goto(std::size_t lineno)\n{\n\tinstruction ins;\n\tstd::memset(&ins, 0, sizeof(ins));\n\tins.op_lo = (instruction::OP_JMP << 4) | 8;\n\task_lineno(lineno);\n\tbin.push_back(std::move(ins));\n}\n\nvoid linker::if_condition(const expr_t& exprl, const expr_t& exprr,\n\t\tconst std::string& cmp, std::size_t lineno)\n{\n\tauto do_sub = [this]() {\n\t\tinstruction ins;\n\t\tstd::memset(&ins, 0, sizeof(ins));\n\t\tins.op_lo = (instruction::OP_SUB << 4 | 0);\n\t\tbin.push_back(std::move(ins));\n\t};\n\tinstruction ins;\n\tstd::memset(&ins, 0, sizeof(ins));\n\tif (cmp == \"=\") {\n\t\texpand_expr(exprl);\n\t\texpand_expr(exprr);\n\t\tdo_sub();\n\t\tins.op_lo = (instruction::OP_JZ << 4) | 8;\n\t} else if (cmp == \">\") {\n\t\texpand_expr(exprl);\n\t\texpand_expr(exprr);\n\t\tdo_sub();\n\t\tins.op_lo = (instruction::OP_JP << 4) | 8;\n\t} else if (cmp == \"<\") {\n\t\texpand_expr(exprr);\n\t\texpand_expr(exprl);\n\t\tdo_sub();\n\t\tins.op_lo = (instruction::OP_JP << 4) | 8;\n\t} else {\n\t\tassert(0);\n\t}\n\task_lineno(lineno);\n\tbin.push_back(std::move(ins));\n}\n\nvoid linker::program_end()\n{\n\tinstruction ins;\n\tstd::memset(&ins, 0, sizeof(ins));\n\tins.op_lo = (instruction::OP_HALT << 4) | 0;\n\tbin.push_back(std::move(ins));\n}\n\nvoid linker::push_number(const expr_token& token)\n{\n\tinstruction ins;\n\tstd::memset(&ins, 0, sizeof(ins));\n\tif (token.type == expr_token::IMMEDIATE) {\n\t\tins.op_lo = (instruction::OP_PUSH << 4) | 1;\n\t\tins.operand[0] = token.num;\n\t} else if (token.type == expr_token::VARIABLE) {\n\t\tins.op_lo = (instruction::OP_PUSH << 4) | 2;\n\t\tins.operand[0] = get_var_addr(token.str);\n\t}\n\tbin.push_back(std::move(ins));\n}\n\ninteger_t linker::get_var_addr(const std::string& var)\n{\n\tauto it = _mach.var_map.find(var);\n\tif (it == _mach.var_map.end()) {\n\t\tinteger_t result = _mach.vars.size();\n\t\t_mach.var_map.emplace(var, result);\n\t\t_mach.vars.push_back(std_nullopt);\n\t\treturn result;\n\t} else {\n\t\treturn it->second;\n\t}\n}\n\nshort_t linker::get_operator_op(const std::string& oper)\n{\n\tshort_t result;\n\tswitch (oper[0]) {\n\tcase '+':\n\t\tresult = instruction::OP_ADD;\n\t\tbreak;\n\tcase '-':\n\t\tresult = instruction::OP_SUB;\n\t\tbreak;\n\tcase '*':\n\t\tresult = instruction::OP_MUL;\n\t\tbreak;\n\tcase '\/':\n\t\tresult = instruction::OP_DIV;\n\t\tbreak;\n\tdefault:\n\t\tassert(0);\n\t}\n\treturn result;\n}\n\nvoid linker::ask_lineno(std::size_t lineno)\n{\n\tl2l.push_back({bin.size(), 0, lineno});\n}\n\nvoid linker::linkall_lineno()\n{\n\tfor (auto& entry : l2l) {\n\t\tauto it = lineno_map.find(entry.lineno);\n\t\tauto& ins = bin[entry.id_bin];\n\t\tif (it == lineno_map.end()) {\n\t\t\t\/\/ if not found, replace the instruction with INT 0xff,\n\t\t\t\/\/ which will cause the VM to throw line_number_error.\n\t\t\tstd::memset(&ins, 0, sizeof(ins));\n\t\t\tins.op_lo = (instruction::OP_INT << 4) | 1;\n\t\t\tins.operand[0] = 0xff;\n\t\t} else {\n\t\t\tins.operand[entry.id_operand] = it->second;\n\t\t}\n\t}\n}\n\n} \/\/ namespace BASIC\n","avg_line_length":21.6950672646,"max_line_length":67,"alphanum_fraction":0.651302191,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":27860,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":347.0,"content":"\/*\n * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *  * Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  * Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *  * Neither the name of NVIDIA CORPORATION nor the names of its\n *    contributors may be used to endorse or promote products derived\n *    from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"nvj2k_DecodeTilePartial.h\"\n\ntemplate<typename T>\nint write_image(std::string output_path, std::string filename, const T &imgdesc, int width, int height,\n               uint32_t num_components, uint8_t precision, bool verbose)\n{\n    \/\/ Get the file name, without extension.\n    \/\/ This will be used to rename the output file.\n    size_t position = filename.rfind(separator);\n    std::string sFileName =\n        (std::string::npos == position)\n            ? filename\n            : filename.substr(position + 1, filename.size());\n    position = sFileName.rfind(\".\");\n    sFileName = (std::string::npos == position) ? sFileName\n                                                : sFileName.substr(0, position);\n\n    int err = EXIT_SUCCESS;\n    \n    \/\/ For single component image output as PGM channel\n    if (num_components == 1)\n    {\n        std::string fname(output_path + separator + sFileName + \".pgm\");\n        if (imgdesc.pixel_type == NVJPEG2K_UINT8)\n        {\n            err = writePGM<unsigned char>(fname.c_str(), (unsigned char *)imgdesc.pixel_data[0], \n                imgdesc.pitch_in_bytes[0], width, height, precision);\n        }\n        else if (imgdesc.pixel_type == NVJPEG2K_UINT16)\n        {\n            err = writePGM<unsigned short>(fname.c_str(), (unsigned short *)imgdesc.pixel_data[0],\n                 imgdesc.pitch_in_bytes[0], width, height, precision);\n        }\n        \n        if (err)\n        {\n            std::cout << \"Cannot write output file: \" << fname << std::endl;\n        }\n       \n    }\n    else if (num_components == 3 || num_components == 4)\n    {\n        if(num_components == 4 && verbose)\n        {\n            std::cout<<\"Discarding the alpha channel and writing the 4 component image as a .bmp file\"<<std::endl;\n        }\n        std::string fname(output_path + separator + sFileName + \".bmp\");\n        if (imgdesc.pixel_type == NVJPEG2K_UINT8)\n        {\n            err = writeBMP<unsigned char>(fname.c_str(),\n                     (unsigned char *)imgdesc.pixel_data[0], imgdesc.pitch_in_bytes[0],\n                     (unsigned char *)imgdesc.pixel_data[1], imgdesc.pitch_in_bytes[1],\n                     (unsigned char *)imgdesc.pixel_data[2], imgdesc.pitch_in_bytes[2],\n                     width, height, precision, verbose);\n        }\n        else if (imgdesc.pixel_type == NVJPEG2K_UINT16)\n        {\n            err = writeBMP<unsigned short>(fname.c_str(),\n                     (unsigned short *)imgdesc.pixel_data[0], imgdesc.pitch_in_bytes[0],\n                     (unsigned short *)imgdesc.pixel_data[1], imgdesc.pitch_in_bytes[1],\n                     (unsigned short *)imgdesc.pixel_data[2], imgdesc.pitch_in_bytes[2],\n                     width, height, precision, verbose);\n        }\n        if (err)\n        {\n            std::cout << \"Cannot write output file: \" << fname << std::endl;\n        }\n    }\n    else\n    {\n        std::cout << \"only 1 and 3 channel outputs supported\\n\";\n        return EXIT_FAILURE;\n    }\n    \n    return err;\n}\n\nint prepare_buffers(FileData &file_data, std::vector<size_t> &file_len,\n                    std::vector<int> &img_width, std::vector<int> &img_height,\n                    std::vector<nvjpeg2kImage16u_t> &ibuf,\n                    std::vector<nvjpeg2ksample_img_sz> &isz, \n                    FileNames &current_names,\n                    decode_params_t &params,\n                    double& parse_time) {\n\n    nvjpeg2kImageInfo_t image_info;\n    nvjpeg2kImageComponentInfo_t image_comp_info[NUM_COMPONENTS];\n    parse_time = 0;\n    for (uint32_t i = 0; i < file_data.size(); i++) \n    {\n        double time = Wtime();\n        CHECK_NVJPEG2K(nvjpeg2kStreamParse(params.nvjpeg2k_handle, (unsigned char*)file_data[i].data(), file_len[i],\n                0, 0, params.jpeg2k_streams[i]));\n        parse_time += Wtime() - time;\n        \n        CHECK_NVJPEG2K(nvjpeg2kStreamGetImageInfo(params.jpeg2k_streams[i], &image_info));\n\n        if( image_info.num_components > NUM_COMPONENTS) \n        {\n            std::cout<<\"Num Components > \"<< NUM_COMPONENTS<<\"not supported by this sample\"<<std::endl;\n            return EXIT_FAILURE;\n        }\n        for (uint32_t c = 0; c < image_info.num_components; c++) \n        {\n            CHECK_NVJPEG2K(nvjpeg2kStreamGetImageComponentInfo(params.jpeg2k_streams[i], &image_comp_info[c], c));\n\n            if( image_comp_info[0].precision > MAX_PRECISION)\n            {\n                std::cout<<\"Precision > \"<< MAX_PRECISION<<\" not supported by this sample\"<<std::endl;\n                return EXIT_FAILURE;\n            }\n        }\n        img_width[i] = image_info.image_width;\n        img_height[i] = image_info.image_width;\n        ibuf[i].num_comps = image_info.num_components;\n        ibuf[i].pixel_type = NVJPEG2K_UINT16;\n        \/\/ realloc output buffer if required\n       \n        for (uint32_t c = 0; c < image_info.num_components; c++) \n        {\n            uint32_t bytes_per_element = (MAX_PRECISION\/8);\n            \/\/ for JPEG 2000 bitstreams with 420\/422 subsampling, this sample enables RGB output\n            \/\/ we are allocating assuming that all component dimensions are the same\n            uint32_t aw = bytes_per_element * image_info.image_width;\n            uint32_t ah = image_info.image_height;\n            if(params.partial_decode)\n            {\n                aw = bytes_per_element * (params.win_x1 - params.win_x0);\n                ah = (params.win_y1 - params.win_y0);\n            }\n            uint32_t sz = aw * ah;\n            ibuf[i].pitch_in_bytes[c] = aw;\n            if (sz > isz[i].comp_sz[c]) \n            {\n                if (ibuf[i].pixel_data[c]) \n                {\n                    CHECK_CUDA(cudaFree(ibuf[i].pixel_data[c]));\n                }\n                CHECK_CUDA(cudaMalloc((void**)&ibuf[i].pixel_data[c], sz));\n                isz[i].comp_sz[c] = sz;\n            }\n        }\n    }\n    return EXIT_SUCCESS;\n}\n\nstruct partial_decode_info\n{\n    unsigned int win_tilex0;\n    unsigned int win_tilex1;\n    unsigned int win_tiley0;\n    unsigned int win_tiley1;\n    unsigned int tile_id;\n};\n\nvoid determine_tiles_to_decode(const nvjpeg2kImageInfo_t& image_info, decode_params_t &params,\n    std::vector<partial_decode_info>& tile_window_data)\n{\n    uint32_t tile_id = 0;\n    for(uint32_t tile_y0 = 0; tile_y0 < image_info.image_height; tile_y0 += image_info.tile_height)\n    {\n        for(uint32_t tile_x0 = 0; tile_x0 < image_info.image_width; tile_x0 += image_info.tile_width)\n        {\n            \/\/ include min and max functions in braces for windows builds issues\n            uint32_t tile_y1 = (std::min)(tile_y0 + image_info.tile_height, image_info.image_height);\n            uint32_t tile_x1 = (std::min)(tile_x0 + image_info.tile_width, image_info.image_height);\n\n            if( params.win_x0 < tile_x1 && params.win_x1 > tile_x0 &&\n                params.win_y0 < tile_y1 && params.win_y1 > tile_y0)\n            {\n                partial_decode_info decode_data;\n                decode_data.tile_id = tile_id;\n                decode_data.win_tilex0 = (std::max)(tile_x0, params.win_x0);\n                decode_data.win_tilex1 = (std::min)(tile_x1, params.win_x1);\n                decode_data.win_tiley0 = (std::max)(tile_y0, params.win_y0);\n                decode_data.win_tiley1 = (std::min)(tile_y1, params.win_y1);\n                tile_window_data.push_back(decode_data);\n                \n            }\n            tile_id++;\n            \n        }\n    }\n}\n\nint decode_images_partial(FileNames &current_names, std::vector<nvjpeg2kImage16u_t> &out,\n                  decode_params_t &params, double &time)\n{\n    cudaEvent_t startEvent = NULL, stopEvent = NULL;\n    nvjpeg2kDecodeParams_t decode_params;\n    CHECK_NVJPEG2K(nvjpeg2kDecodeParamsCreate(&decode_params));\n    float loopTime = 0;\n\n    cudaEvent_t pipeline_events[PIPELINE_STAGES];\n\n    for (int p = 0; p < PIPELINE_STAGES; p++)\n    {\n        CHECK_CUDA(cudaEventCreate(&pipeline_events[p]));\n        CHECK_CUDA(cudaEventRecord(pipeline_events[p], params.stream[p]));\n    }\n    CHECK_CUDA(cudaEventCreateWithFlags(&startEvent, cudaEventBlockingSync));\n    CHECK_CUDA(cudaEventCreateWithFlags(&stopEvent, cudaEventBlockingSync));\n\n#if (NVJPEG2K_VER_MAJOR == 0 && NVJPEG2K_VER_MINOR >= 3) \n    \/\/ set RGB  output for the entire batch\n    CHECK_NVJPEG2K(nvjpeg2kDecodeParamsSetRGBOutput(decode_params, 1));\n#endif\n    CHECK_CUDA(cudaEventRecord(startEvent, params.stream[0]));\n    int buffer_index = 0;\n    for(int batch_id = 0; batch_id < params.batch_size; batch_id++)\n    {\n        nvjpeg2kImageInfo_t image_info;\n        CHECK_NVJPEG2K(nvjpeg2kStreamGetImageInfo(params.jpeg2k_streams[batch_id], &image_info));\n\n        std::vector<partial_decode_info> tile_window_data;\n        determine_tiles_to_decode(image_info, params, tile_window_data);\n\n        uint32_t out_width = 0;\n        uint32_t out_height = 0;\n        for( uint32_t i = 0; i < tile_window_data.size(); i++)\n        {\n            \/\/ make sure that the previous stage are done\n            CHECK_CUDA(cudaEventSynchronize(pipeline_events[buffer_index]));\n            nvjpeg2kImage16u_t tile_decode_out;\n            \n            auto& decode_data = tile_window_data[i];\n            tile_decode_out.num_comps = out[batch_id].num_comps;\n            tile_decode_out.pixel_type = out[batch_id].pixel_type;\n            uint32_t bytes_per_comp = sizeof(*tile_decode_out.pixel_data[0]);\n            for(uint32_t c = 0; c < out[batch_id].num_comps; c++)\n            {\n                size_t pitch_in_pixels = out[batch_id].pitch_in_bytes[c]\/bytes_per_comp;\n                tile_decode_out.pixel_data[c] = out[batch_id].pixel_data[c] + out_height * pitch_in_pixels + (out_width);\n                tile_decode_out.pitch_in_bytes[c] = out[batch_id].pitch_in_bytes[c];\n            }\n            out_width += decode_data.win_tilex1 - decode_data.win_tilex0;\n                \n            if( out_width == params.win_x1 - params.win_x0)\n            {\n                out_width = 0;\n                out_height += decode_data.win_tiley1 - decode_data.win_tiley0;\n            }\n\n            nvjpeg2kImage_t nvjpeg2k_out;\n            nvjpeg2k_out.num_components = tile_decode_out.num_comps;\n            nvjpeg2k_out.pixel_data = (void**)tile_decode_out.pixel_data;\n            nvjpeg2k_out.pitch_in_bytes = tile_decode_out.pitch_in_bytes;\n            nvjpeg2k_out.pixel_type = tile_decode_out.pixel_type;\n\n            CHECK_NVJPEG2K(nvjpeg2kDecodeParamsSetDecodeArea(decode_params, decode_data.win_tilex0, decode_data.win_tilex1,\n                decode_data.win_tiley0, decode_data.win_tiley1));\n            CHECK_NVJPEG2K(nvjpeg2kDecodeTile(params.nvjpeg2k_handle, params.nvjpeg2k_decode_states[buffer_index],\n                params.jpeg2k_streams[batch_id], decode_params, decode_data.tile_id, 0,\n                &nvjpeg2k_out, params.stream[buffer_index]));\n            \n            CHECK_CUDA(cudaEventRecord(pipeline_events[buffer_index], params.stream[buffer_index]));\n\n            buffer_index++;\n            buffer_index = buffer_index%PIPELINE_STAGES;\n\n        }\n    }\n    for (int p = 0; p < PIPELINE_STAGES; p++)\n    {\n        CHECK_CUDA(cudaEventSynchronize(pipeline_events[p]));\n    }\n\n    CHECK_CUDA(cudaEventRecord(stopEvent, params.stream[0]));\n    \n    CHECK_CUDA(cudaEventSynchronize(stopEvent));\n    CHECK_CUDA(cudaEventElapsedTime(&loopTime, startEvent, stopEvent));\n    time += static_cast<double>(loopTime\/1000.0); \/\/ loopTime is in milliseconds\n    \n    if (params.write_decoded)\n    {\n        for( int i = 0; i < params.batch_size; i++)\n        {\n            nvjpeg2kImageInfo_t image_info;\n            nvjpeg2kImageComponentInfo_t comp_info;\n            CHECK_NVJPEG2K(nvjpeg2kStreamGetImageInfo(params.jpeg2k_streams[i], &image_info));\n            \/\/ assume all components have the same precision\n            CHECK_NVJPEG2K(nvjpeg2kStreamGetImageComponentInfo(params.jpeg2k_streams[i], &comp_info, 0));\n            write_image(params.output_dir, current_names[i], out[i], params.win_x1 - params.win_x0, \n                params.win_x1 - params.win_x0, image_info.num_components, comp_info.precision,\n                params.verbose);\n        }\n    }\n\n    for(int p = 0; p < PIPELINE_STAGES; p++)\n    {\n        CHECK_CUDA(cudaEventDestroy(pipeline_events[p]));\n    }\n    CHECK_CUDA(cudaEventDestroy(stopEvent));\n    CHECK_CUDA(cudaEventDestroy(startEvent));\n    CHECK_NVJPEG2K(nvjpeg2kDecodeParamsDestroy(decode_params));\n    \n    return EXIT_SUCCESS;\n}\n\n\nint decode_images(FileNames &current_names, std::vector<nvjpeg2kImage16u_t> &out,\n                  decode_params_t &params, double &time)\n{\n    cudaEvent_t startEvent = NULL, stopEvent = NULL;\n    float loopTime = 0;\n\n    cudaEvent_t pipeline_events[PIPELINE_STAGES];\n\n    for (int p = 0; p < PIPELINE_STAGES; p++)\n    {\n        CHECK_CUDA(cudaEventCreate(&pipeline_events[p]));\n        CHECK_CUDA(cudaEventRecord(pipeline_events[p], params.stream[p]));\n    }\n    CHECK_CUDA(cudaEventCreateWithFlags(&startEvent, cudaEventBlockingSync));\n    CHECK_CUDA(cudaEventCreateWithFlags(&stopEvent, cudaEventBlockingSync));\n\n    nvjpeg2kDecodeParams_t decode_params;\n    CHECK_NVJPEG2K(nvjpeg2kDecodeParamsCreate(&decode_params));\n\n#if (NVJPEG2K_VER_MAJOR == 0 && NVJPEG2K_VER_MINOR >= 3) \n    \/\/ set RGB  output for the entire batch\n    CHECK_NVJPEG2K(nvjpeg2kDecodeParamsSetRGBOutput(decode_params, 1));\n#endif\n\n    CHECK_CUDA(cudaEventRecord(startEvent, params.stream[0]));\n    int buffer_index = 0;\n    for(int batch_id = 0; batch_id < params.batch_size; batch_id++)\n    {\n        nvjpeg2kImageInfo_t image_info;\n        CHECK_NVJPEG2K(nvjpeg2kStreamGetImageInfo(params.jpeg2k_streams[batch_id], &image_info));\n\n        uint32_t tile_id = 0;\n        for(uint32_t tile_y0 = 0; tile_y0 < image_info.image_height; tile_y0 += image_info.tile_height)\n        {\n            for(uint32_t tile_x0 = 0; tile_x0 < image_info.image_width; tile_x0 += image_info.tile_width)\n            {\n                \/\/ make sure that the previous stage are done\n                CHECK_CUDA(cudaEventSynchronize(pipeline_events[buffer_index]));\n                nvjpeg2kImage16u_t tile_decode_out;\n                tile_decode_out.num_comps = out[batch_id].num_comps;\n                tile_decode_out.pixel_type = out[batch_id].pixel_type;\n                uint32_t bytes_per_comp = sizeof(*tile_decode_out.pixel_data[0]);\n                for(uint32_t c = 0; c < out[batch_id].num_comps; c++)\n                {\n                    size_t pitch_in_pixels = out[batch_id].pitch_in_bytes[c]\/bytes_per_comp;\n                    tile_decode_out.pixel_data[c] = out[batch_id].pixel_data[c] + tile_y0 * pitch_in_pixels + (tile_x0);\n                    tile_decode_out.pitch_in_bytes[c] = out[batch_id].pitch_in_bytes[c];\n                }\n                \/\/ make sure that the previous stage are done before reusing\n                CHECK_CUDA(cudaEventSynchronize(pipeline_events[buffer_index]));\n            \n                nvjpeg2kImage_t nvjpeg2k_out;\n                nvjpeg2k_out.num_components = tile_decode_out.num_comps;\n                nvjpeg2k_out.pixel_data = (void**)tile_decode_out.pixel_data;\n                nvjpeg2k_out.pitch_in_bytes = tile_decode_out.pitch_in_bytes;\n                nvjpeg2k_out.pixel_type = tile_decode_out.pixel_type;\n\n                CHECK_NVJPEG2K(nvjpeg2kDecodeTile(params.nvjpeg2k_handle, params.nvjpeg2k_decode_states[buffer_index],\n                    params.jpeg2k_streams[batch_id], decode_params, tile_id, 0,\n                    &nvjpeg2k_out, params.stream[buffer_index]));\n                \n                CHECK_CUDA(cudaEventRecord(pipeline_events[buffer_index], params.stream[buffer_index]));\n\n                buffer_index++;\n                buffer_index = buffer_index%PIPELINE_STAGES;\n                tile_id++;\n\n            }\n        }\n    }\n    for (int p = 0; p < PIPELINE_STAGES; p++)\n    {\n        CHECK_CUDA(cudaEventSynchronize(pipeline_events[p]));\n    }\n\n    CHECK_CUDA(cudaEventRecord(stopEvent, params.stream[0]));\n    \n    CHECK_CUDA(cudaEventSynchronize(stopEvent));\n    CHECK_CUDA(cudaEventElapsedTime(&loopTime, startEvent, stopEvent));\n    time += static_cast<double>(loopTime\/1000.0); \/\/ loopTime is in milliseconds\n    \n    if (params.write_decoded)\n    {\n        for( int i = 0; i < params.batch_size; i++)\n        {\n            nvjpeg2kImageInfo_t image_info;\n            nvjpeg2kImageComponentInfo_t comp_info;\n            CHECK_NVJPEG2K(nvjpeg2kStreamGetImageInfo(params.jpeg2k_streams[i], &image_info));\n            \/\/ assume all components have the same precision\n            CHECK_NVJPEG2K(nvjpeg2kStreamGetImageComponentInfo(params.jpeg2k_streams[i], &comp_info, 0));\n            \n            write_image(params.output_dir, current_names[i], out[i], image_info.image_width, \n                image_info.image_height, image_info.num_components, comp_info.precision,\n                params.verbose);\n        }\n    }\n\n    for(int p = 0; p < PIPELINE_STAGES; p++)\n    {\n        CHECK_CUDA(cudaEventDestroy(pipeline_events[p]));\n    }\n    CHECK_CUDA(cudaEventDestroy(stopEvent));\n    CHECK_CUDA(cudaEventDestroy(startEvent));\n    CHECK_NVJPEG2K(nvjpeg2kDecodeParamsDestroy(decode_params));\n\n    return EXIT_SUCCESS;\n}\n\ndouble process_images(FileNames &image_names, decode_params_t &params,\n                      double &total)\n{\n    \/\/ vector for storing raw files and file lengths\n    FileData file_data(params.batch_size);\n    std::vector<size_t> file_len(params.batch_size);\n    FileNames current_names(params.batch_size);\n    std::vector<int> widths(params.batch_size);\n    std::vector<int> heights(params.batch_size);\n    \/\/ we wrap over image files to process total_images of files\n    FileNames::iterator file_iter = image_names.begin();\n   \/\/ output buffers\n   std::vector<nvjpeg2kImage16u_t> iout(params.batch_size);\n  \/\/ output buffer\n   std::vector<nvjpeg2ksample_img_sz> isz(params.batch_size);\n\n    \/\/ stream for decoding\n    for (int p =0; p < PIPELINE_STAGES; p++)\n    {\n        CHECK_CUDA(cudaStreamCreateWithFlags(&params.stream[p], cudaStreamNonBlocking));\n    }\n\n    int total_processed = 0;\n\n    double test_time = 0;\n    int warmup = 0;\n    while (total_processed < params.total_images)\n    {\n        if (read_next_batch(image_names, params.batch_size, file_iter, file_data,\n                            file_len, current_names, params.verbose))\n            return EXIT_FAILURE;\n        double parsetime = 0;\n        if (prepare_buffers(file_data, file_len, widths, heights, iout, isz,\n                        current_names, params, parsetime))\n            return EXIT_FAILURE;\n\n        double time = 0;\n        int ret_val = 0;\n        if (params.partial_decode)\n        {\n            ret_val = decode_images_partial(current_names, iout, params, time);\n        }\n        else\n        {\n            ret_val = decode_images(current_names, iout, params, time);\n        }\n        if(ret_val)\n        {\n            return EXIT_FAILURE;\n        }\n        if (warmup < params.warmup)\n        {\n            warmup++;\n        }\n        else\n        {\n            total_processed += params.batch_size;\n            test_time += time + parsetime;\n        }\n    }\n    total = test_time;\n    for (int p = 0; p < PIPELINE_STAGES; p++)\n    {\n        CHECK_CUDA(cudaStreamDestroy(params.stream[p]));\n    }\n\n    return EXIT_SUCCESS;\n}\n\nint parseDecodeCoordinates(const char* argv, decode_params_t& params)\n{\n    std::istringstream decode_area(argv);\n    std::string temp;\n    int idx = 0;\n    while(getline(decode_area, temp,','))\n    {\n        if( idx == 0)\n        {\n            params.win_x0 = std::stoi(temp);\n        }\n        else if (idx == 1)\n        {\n            params.win_y0 = std::stoi(temp);\n        }\n        else if( idx == 2)\n        {\n            params.win_x1 = std::stoi(temp);\n        }\n        else if (idx == 3)\n        {\n            params.win_y1 = std::stoi(temp);\n        }\n        else\n        {\n            std::cout<<\"invalid decode area here\"<<std::endl;\n            return EXIT_FAILURE;\n        }\n        idx++;\n    }\n    if (params.win_x0 >= params.win_x1 || params.win_y0 >= params.win_y1)\n    {\n        std::cout<<\"invalid decode area here\"<<std::endl;\n        return EXIT_FAILURE;\n    }\n    params.partial_decode = true;\n    return EXIT_SUCCESS;\n}\nint main(int argc, const char *argv[])\n{\n    int pidx;\n\n    if ((pidx = findParamIndex(argv, argc, \"-h\")) != -1 ||\n        (pidx = findParamIndex(argv, argc, \"--help\")) != -1)\n    {\n        std::cout << \"Usage: \" << argv[0]\n                  << \" -i images_dir [-b batch_size] [-t total_images] \"\n                     \"[-w warmup_iterations] [-o output_dir] [-da decode_area_of_interest] [-v verbose]\\n\";\n        std::cout << \"Parameters: \" << std::endl;\n        std::cout << \"\\timages_dir\\t:\\tPath to single image or directory of images\"\n                  << std::endl;\n        std::cout << \"\\tbatch_size\\t:\\tDecode images from input by batches of \"\n                     \"specified size\"\n                  << std::endl;\n        std::cout << \"\\ttotal_images\\t:\\tDecode these many images, if there are \"\n                     \"fewer images \\n\"\n                  << \"\\t\\t\\t\\tin the input than total images, decoder will loop \"\n                     \"over the input\"\n                  << std::endl;\n        std::cout << \"\\twarmup_iterations:\\tRun these many batches first \"\n                     \"without measuring performance\"\n                  << std::endl;\n        std::cout << \"\\tdecode_area_of_interest: Image coordinates specifying an area \"\n                  << \"to be decoded\"\n                  << std::endl;\n        std::cout\n            << \"\\toutput_dir\\t:\\tWrite decoded images in BMP\/PGM format to this directory\"\n            << std::endl;\n        std::cout\n            << \"\\tverbose\\t\\t:\\tLog verbose messages to console\"\n            << std::endl;\n        return EXIT_SUCCESS;\n    }\n\n    decode_params_t params;\n\n    params.input_dir = \".\/\";\n    if ((pidx = findParamIndex(argv, argc, \"-i\")) != -1)\n    {\n        params.input_dir = argv[pidx + 1];\n    }\n    else\n    {\n        \/\/ Search in default paths for input images.\n        int found = getInputDir(params.input_dir, argv[0]);\n        if (!found)\n        {\n            std::cout << \"Please specify input directory with encoded images\" << std::endl;\n            return EXIT_FAILURE;\n        }\n    }\n\n    params.batch_size = 1;\n    if ((pidx = findParamIndex(argv, argc, \"-b\")) != -1)\n    {\n        params.batch_size = std::atoi(argv[pidx + 1]);\n    }\n\n    params.total_images = -1;\n    if ((pidx = findParamIndex(argv, argc, \"-t\")) != -1)\n    {\n        params.total_images = std::atoi(argv[pidx + 1]);\n    }\n\n    params.warmup = 0;\n    if ((pidx = findParamIndex(argv, argc, \"-w\")) != -1)\n    {\n        params.warmup = std::atoi(argv[pidx + 1]);\n    }\n\n    params.write_decoded = false;\n    if ((pidx = findParamIndex(argv, argc, \"-o\")) != -1)\n    {\n        params.output_dir = argv[pidx + 1];\n        params.write_decoded = true;\n    }\n    params.verbose = false;\n    if ((pidx = findParamIndex(argv, argc, \"-v\")) != -1)\n    {\n        params.verbose = true;\n    }\n\n    params.win_x0 = 0;\n    params.win_y0 = 0;\n    params.win_x1 = 0;\n    params.win_y1 = 0;\n    params.partial_decode = false;\n    if ((pidx = findParamIndex(argv, argc, \"-da\")) != -1)\n    {\n        if(parseDecodeCoordinates(argv[pidx + 1], params))\n        {\n            return EXIT_SUCCESS;\n        }\n        \n    }\n\n    if( params.verbose)\n    {\n        if(params.write_decoded) \n        {\n            std::cout << \"3\/4 channel images are written out as bmp files and 1 channels images are written out as .pgm files\"\n                      << std::endl;\n        }\n        cudaDeviceProp props;\n        int dev = 0;\n        cudaGetDevice(&dev);\n        cudaGetDeviceProperties(&props, dev);\n        std::cout<<\"Using GPU - \"<<props.name<<\" with CC \"<<props.major<<\".\"<<props.minor<<std::endl;\n    }\n\n    nvjpeg2kDeviceAllocator_t dev_allocator = {&dev_malloc, &dev_free};\n    nvjpeg2kPinnedAllocator_t pinned_allocator = {&host_malloc, &host_free};\n\n    CHECK_NVJPEG2K(nvjpeg2kCreate(NVJPEG2K_BACKEND_DEFAULT, &dev_allocator,\n                                  &pinned_allocator, &params.nvjpeg2k_handle));\n\n    for(int p = 0; p < PIPELINE_STAGES; p++)\n    {\n        CHECK_NVJPEG2K(\n        nvjpeg2kDecodeStateCreate(params.nvjpeg2k_handle, &params.nvjpeg2k_decode_states[p]));\n    }\n    \n    params.jpeg2k_streams.resize(params.batch_size);\n\n    for(auto& stream : params.jpeg2k_streams)\n    {\n        CHECK_NVJPEG2K(nvjpeg2kStreamCreate(&stream));\n    }\n\n    \/\/ read source images\n    FileNames image_names;\n    readInput(params.input_dir, image_names);\n\n    if (params.total_images == -1)\n    {\n        params.total_images = static_cast<int>(image_names.size());\n    }\n    else if (params.total_images % params.batch_size)\n    {\n        params.total_images =\n            ((params.total_images) \/ params.batch_size) * params.batch_size;\n        std::cout << \"Changing total_images number to \" << params.total_images\n                  << \" to be multiple of batch_size - \" << params.batch_size\n                  << std::endl;\n    }\n\n    std::cout << \"Decoding images in directory: \" << params.input_dir\n              << \", total \" << params.total_images << \", batchsize \"\n              << params.batch_size << std::endl;\n\n    double total;\n    if (process_images(image_names, params, total))\n        return EXIT_FAILURE;\n    std::cout << \"Total decoding time: \" << total << std::endl;\n    std::cout << \"Avg decoding time per image: \" << total \/ params.total_images\n              << std::endl;\n    std::cout << \"Avg decode speed  (in images per sec): \" << params.total_images \/ total\n              << std::endl;\n    std::cout << \"Avg decoding time per batch: \"\n              << total \/ ((params.total_images + params.batch_size - 1) \/\n                          params.batch_size)\n              << std::endl;\n\n    for(auto& stream : params.jpeg2k_streams)\n    {\n        CHECK_NVJPEG2K(nvjpeg2kStreamDestroy(stream));\n    }\n    for(int i =0; i < PIPELINE_STAGES; i++)\n    {\n        CHECK_NVJPEG2K(nvjpeg2kDecodeStateDestroy(params.nvjpeg2k_decode_states[i]));\n    }\n    CHECK_NVJPEG2K(nvjpeg2kDestroy(params.nvjpeg2k_handle));\n\n    return EXIT_SUCCESS;\n}\n","avg_line_length":38.640776699,"max_line_length":126,"alphanum_fraction":0.6136755205,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":23554,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["PHP-3.01","Zend-2.0"],"max_stars_count":1.0,"content":"\/*\n   +----------------------------------------------------------------------+\n   | HipHop for PHP                                                       |\n   +----------------------------------------------------------------------+\n   | Copyright (c) 2010-present Facebook, Inc. (http:\/\/www.facebook.com)  |\n   +----------------------------------------------------------------------+\n   | This source file is subject to version 3.01 of the PHP license,      |\n   | that is bundled with this package in the file LICENSE, and is        |\n   | available through the world-wide-web at the following url:           |\n   | http:\/\/www.php.net\/license\/3_01.txt                                  |\n   | If you did not receive a copy of the PHP license and are unable to   |\n   | obtain it through the world-wide-web, please send a note to          |\n   | license@php.net so we can mail you a copy immediately.               |\n   +----------------------------------------------------------------------+\n*\/\n\n#include \"hphp\/runtime\/vm\/jit\/ir-opcode.h\"\n\n#include \"hphp\/runtime\/base\/string-data.h\"\n#include \"hphp\/runtime\/vm\/jit\/cfg.h\"\n#include \"hphp\/runtime\/vm\/jit\/extra-data.h\"\n#include \"hphp\/runtime\/vm\/jit\/ir-instruction.h\"\n#include \"hphp\/runtime\/vm\/jit\/ir-unit.h\"\n#include \"hphp\/runtime\/vm\/jit\/ssa-tmp.h\"\n#include \"hphp\/runtime\/vm\/jit\/print.h\"\n#include \"hphp\/runtime\/vm\/jit\/type.h\"\n#include \"hphp\/runtime\/vm\/runtime.h\"\n\n#include \"hphp\/util\/trace.h\"\n\nnamespace HPHP { namespace jit {\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTRACE_SET_MOD(hhir);\n\n#define NF     0\n#define PRc    ProducesRC\n#define CRc    ConsumesRC\n#define T      Terminal\n#define B      Branch\n#define P      Passthrough\n#define MProp  MInstrProp\n#define MElem  MInstrElem\n\n#define ND             0\n#define D(n)           HasDest\n#define DofS(n)        HasDest\n#define DRefineS(n)    HasDest\n#define DParamMayRelax(t) HasDest\n#define DParam(t)      HasDest\n#define DLdObjCls      HasDest\n#define DAllocObj      HasDest\n#define DArrElem       HasDest\n#define DVecElem       HasDest\n#define DDictElem      HasDest\n#define DKeysetElem    HasDest\n#define DVecFirstElem     HasDest\n#define DVecLastElem      HasDest\n#define DVecKey           HasDest\n#define DDictFirstElem    HasDest\n#define DDictLastElem     HasDest\n#define DDictFirstKey     HasDest\n#define DDictLastKey      HasDest\n#define DKeysetFirstElem  HasDest\n#define DKeysetLastElem   HasDest\n#define DArrPacked     HasDest\n#define DArrMixed      HasDest\n#define DArrRecord     HasDest\n#define DVArr          HasDest\n#define DVArrOrNull    HasDest\n#define DDArr          HasDest\n#define DStaticDArr    HasDest\n#define DCol           HasDest\n#define DMulti         NaryDest\n#define DSetElem       HasDest\n#define DPtrToParam    HasDest\n#define DBuiltin       HasDest\n#define DCall          HasDest\n#define DGenIter       HasDest\n#define DSubtract(n,t) HasDest\n#define DCns           HasDest\n#define DUnion(...)    HasDest\n#define DMemoKey       HasDest\n#define DLvalOfPtr     HasDest\n#define DPtrIter       HasDest\n#define DPtrIterVal    HasDest\n\nnamespace {\ntemplate<Opcode op, uint64_t flags>\nstruct op_flags {\n  static constexpr uint64_t value =\n    (OpHasExtraData<op>::value ? HasExtra : 0) | flags;\n\n  static_assert(!(value & ProducesRC) ||\n                (value & (HasDest | NaryDest)) == HasDest,\n                \"ProducesRC instructions must have exactly one dest\");\n};\n}\n\nOpInfo g_opInfo[] = {\n#define O(name, dsts, srcs, flags)                    \\\n    { #name,                                          \\\n       op_flags<name, dsts | flags>::value            \\\n    },\n  IR_OPCODES\n#undef O\n  { 0 }\n};\n\n#undef NF\n#undef C\n#undef E\n#undef PRc\n#undef CRc\n#undef Er\n#undef T\n#undef B\n#undef P\n#undef K\n#undef MProp\n#undef MElem\n\n#undef ND\n#undef D\n#undef DofS\n#undef DRefineS\n#undef DParamMayRelax\n#undef DParam\n#undef DLdObjCls\n#undef DArrElem\n#undef DVecElem\n#undef DDictElem\n#undef DKeysetElem\n#undef DVecFirstElem\n#undef DVecLastElem\n#undef DVecKey\n#undef DDictFirstElem\n#undef DDictLastElem\n#undef DDictFirstKey\n#undef DDictLastKey\n#undef DKeysetFirstElem\n#undef DKeysetLastElem\n#undef DArrPacked\n#undef DArrMixed\n#undef DArrRecord\n#undef DVArr\n#undef DVArrOrNull\n#undef DDArr\n#undef DStaticDArr\n#undef DCol\n#undef DAllocObj\n#undef DMulti\n#undef DSetElem\n#undef DPtrToParam\n#undef DBuiltin\n#undef DCall\n#undef DGenIter\n#undef DSubtract\n#undef DCns\n#undef DUnion\n#undef DMemoKey\n#undef DLvalOfPtr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst StringData* findClassName(SSATmp* cls) {\n  assertx(cls->isA(TCls));\n\n  if (cls->hasConstVal()) {\n    return cls->clsVal()->preClass()->name();\n  }\n  \/\/ Try to get the class name from a LdCls\n  IRInstruction* clsInst = cls->inst();\n  if (clsInst->op() == LdCls || clsInst->op() == LdClsCached) {\n    SSATmp* clsName = clsInst->src(0);\n    assertx(clsName->isA(TStr));\n    if (clsName->hasConstVal()) {\n      return clsName->strVal();\n    }\n  }\n  return nullptr;\n}\n\nbool isCallOp(Opcode opc) {\n  \/\/ CallBuiltin doesn't count because it is not a php-level call.  (It will\n  \/\/ call a C++ helper and we can push\/pop around it normally.)\n  switch (opc) {\n  case Call:\n  case CallUnpack:\n  case ContEnter:\n    return true;\n  default:\n    return false;\n  }\n}\n\nbool isGuardOp(Opcode opc) {\n  switch (opc) {\n    case CheckLoc:\n    case CheckStk:\n    case CheckType:\n    case CheckMBase:\n      return true;\n\n    default:\n      return false;\n  }\n}\n\nfolly::Optional<Opcode> negateCmpOp(Opcode opc) {\n  switch (opc) {\n    case GtBool:              return LteBool;\n    case GteBool:             return LtBool;\n    case LtBool:              return GteBool;\n    case LteBool:             return GtBool;\n    case EqBool:              return NeqBool;\n    case NeqBool:             return EqBool;\n\n    case GtInt:               return LteInt;\n    case GteInt:              return LtInt;\n    case LtInt:               return GteInt;\n    case LteInt:              return GtInt;\n    case EqInt:               return NeqInt;\n    case NeqInt:              return EqInt;\n\n    \/\/ Due to NaN only equality comparisons with doubles can be negated.\n    case EqDbl:               return NeqDbl;\n    case NeqDbl:              return EqDbl;\n\n    case GtStr:               return LteStr;\n    case GteStr:              return LtStr;\n    case LtStr:               return GteStr;\n    case LteStr:              return GtStr;\n    case EqStr:               return NeqStr;\n    case NeqStr:              return EqStr;\n    case SameStr:             return NSameStr;\n    case NSameStr:            return SameStr;\n\n    case GtStrInt:            return LteStrInt;\n    case GteStrInt:           return LtStrInt;\n    case LtStrInt:            return GteStrInt;\n    case LteStrInt:           return GtStrInt;\n    case EqStrInt:            return NeqStrInt;\n    case NeqStrInt:           return EqStrInt;\n\n    \/\/ Objects can contain a property with NaN, so only equality comparisons can\n    \/\/ be negated.\n    case EqObj:               return NeqObj;\n    case NeqObj:              return EqObj;\n    case SameObj:             return NSameObj;\n    case NSameObj:            return SameObj;\n\n    \/\/ Arrays\/vec\/dicts can contain an element with NaN, so only equality\n    \/\/ comparisons can be negated.\n    case EqArr:               return NeqArr;\n    case NeqArr:              return EqArr;\n    case SameArr:             return NSameArr;\n    case NSameArr:            return SameArr;\n\n    case EqVec:               return NeqVec;\n    case NeqVec:              return EqVec;\n    case SameVec:             return NSameVec;\n    case NSameVec:            return SameVec;\n\n    case EqDict:              return NeqDict;\n    case NeqDict:             return EqDict;\n    case SameDict:            return NSameDict;\n    case NSameDict:           return SameDict;\n\n    case EqKeyset:            return NeqKeyset;\n    case NeqKeyset:           return EqKeyset;\n    case SameKeyset:          return NSameKeyset;\n    case NSameKeyset:         return SameKeyset;\n\n    case GtRes:               return LteRes;\n    case GteRes:              return LtRes;\n    case LtRes:               return GteRes;\n    case LteRes:              return GtRes;\n    case EqRes:               return NeqRes;\n    case NeqRes:              return EqRes;\n\n    default:                  return folly::none;\n  }\n}\n\nbool opcodeMayRaise(Opcode opc) {\n  switch (opc) {\n  case NSameArr:\n  case SameArr:\n  case NSameDict:\n  case NSameVec:\n  case SameDict:\n  case SameVec:\n    return RuntimeOption::EvalHackArrCompatDVCmpNotices ||\n           RuntimeOption::EvalHackArrCompatCheckCompare ||\n           RuntimeOption::EvalHackArrCompatCheckCompareNonAnyArray;\n\n  case IsTypeStruct:\n    return RuntimeOption::EvalHackArrCompatIsArrayNotices ||\n           RuntimeOption::EvalHackArrCompatTypeHintNotices ||\n           RuntimeOption::EvalIsExprEnableUnresolvedWarning ||\n           RuntimeOption::EvalIsVecNotices;\n\n  case AddElemIntKey:\n  case AddElemStrKey:\n  case AddNewElem:\n  case AddNewElemKeyset:\n  case AFWHPrepareChild:\n  case AKExistsObj:\n  case AllocObj:\n  case AllocObjReified:\n  case ArrayAdd:\n  case ArrayGet:\n  case ArraySet:\n  case BaseG:\n  case Call:\n  case CallBuiltin:\n  case CallUnpack:\n  case CGetElem:\n  case CGetProp:\n  case CGetPropQ:\n  case CheckClsReifiedGenericMismatch:\n  case CheckFunReifiedGenericMismatch:\n  case CheckStackOverflow:\n  case CheckSurpriseAndStack:\n  case CheckSurpriseFlagsEnter:\n  case Clone:\n  case CmpArr:\n  case CmpObj:\n  case CmpVec:\n  case ConcatIntStr:\n  case ConcatStr3:\n  case ConcatStr4:\n  case ConcatStrInt:\n  case ConcatStrStr:\n  case ConstructInstance:\n  case ContEnter:\n  case ConvArrToDict:\n  case ConvArrToKeyset:\n  case ConvArrToVec:\n  case ConvCellToArr:\n  case ConvCellToBool:\n  case ConvCellToDbl:\n  case ConvCellToInt:\n  case ConvCellToStr:\n  case ConvClsMethToArr:\n  case ConvClsMethToDArr:\n  case ConvClsMethToDict:\n  case ConvClsMethToKeyset:\n  case ConvClsMethToVArr:\n  case ConvClsMethToVec:\n  case ConvDictToArr:\n  case ConvDictToDArr:\n  case ConvDictToKeyset:\n  case ConvKeysetToArr:\n  case ConvKeysetToDArr:\n  case ConvObjToArr:\n  case ConvObjToBool:\n  case ConvObjToDArr:\n  case ConvObjToDbl:\n  case ConvObjToDict:\n  case ConvObjToInt:\n  case ConvObjToKeyset:\n  case ConvObjToStr:\n  case ConvObjToVArr:\n  case ConvObjToVec:\n  case ConvResToStr:\n  case ConvVecToKeyset:\n  case Count:\n  case CreateAAWH:\n  case DefCls:\n  case DictAddElemIntKey:\n  case DictAddElemStrKey:\n  case DictGet:\n  case DictSet:\n  case ElemArrayD:\n  case ElemArrayU:\n  case ElemArrayX:\n  case ElemDictD:\n  case ElemDictU:\n  case ElemDictX:\n  case ElemDX:\n  case ElemKeysetU:\n  case ElemKeysetX:\n  case ElemUX:\n  case ElemVecD:\n  case ElemVecU:\n  case ElemX:\n  case EmptyElem:\n  case EmptyProp:\n  case EqArr:\n  case EqDict:\n  case EqObj:\n  case EqVec:\n  case GetMemoKey:\n  case GtArr:\n  case GteArr:\n  case GteObj:\n  case GteVec:\n  case GtObj:\n  case GtVec:\n  case HandleRequestSurprise:\n  case IncDecElem:\n  case IncDecProp:\n  case InitClsCns:\n  case InitProps:\n  case InitSProps:\n  case InterpOne:\n  case IssetElem:\n  case IssetProp:\n  case IterInit:\n  case IterInitK:\n  case IterNext:\n  case IterNextK:\n  case KeysetGet:\n  case LdCls:\n  case LdClsCached:\n  case LdClsCtor:\n  case LdClsPropAddrOrNull:\n  case LdClsPropAddrOrRaise:\n  case LdClsTypeCns:\n  case LdClsTypeCnsClsName:\n  case LdFunc:\n  case LdFuncCached:\n  case LdRecDescCached:\n  case LdObjMethodD:\n  case LdObjMethodS:\n  case LdSSwitchDestSlow:\n  case LdSwitchObjIndex:\n  case LookupClsMethod:\n  case LookupClsMethodCache:\n  case LookupClsMethodFCache:\n  case LookupCnsE:\n  case LookupFuncCached:\n  case LtArr:\n  case LteArr:\n  case LteObj:\n  case LteVec:\n  case LtObj:\n  case LtVec:\n  case MapGet:\n  case MapSet:\n  case NativeImpl:\n  case NeqArr:\n  case NeqDict:\n  case NeqObj:\n  case NeqVec:\n  case NewKeysetArray:\n  case NewRecord:\n  case NewRecordArray:\n  case OODeclExists:\n  case OrdStrIdx:\n  case PrintBool:\n  case PrintInt:\n  case PrintStr:\n  case PropDX:\n  case PropQ:\n  case PropTypeRedefineCheck:\n  case PropX:\n  case RaiseArraySerializeNotice:\n  case RaiseError:\n  case RaiseErrorOnInvalidIsAsExpressionType:\n  case RaiseForbiddenDynCall:\n  case RaiseForbiddenDynConstruct:\n  case RaiseHackArrCompatNotice:\n  case RaiseHackArrParamNotice:\n  case RaiseHackArrPropNotice:\n  case RaiseNotice:\n  case RaiseRxCallViolation:\n  case RaiseStrToClassNotice:\n  case RaiseTooManyArg:\n  case RaiseUndefProp:\n  case RaiseUninitLoc:\n  case RaiseWarning:\n  case RecordReifiedGenericsAndGetTSList:\n  case ResolveTypeStruct:\n  case ReturnHook:\n  case SetElem:\n  case SetNewElem:\n  case SetNewElemArray:\n  case SetNewElemKeyset:\n  case SetNewElemVec:\n  case SetOpCell:\n  case SetOpCellVerify:\n  case SetOpElem:\n  case SetOpProp:\n  case SetProp:\n  case SetRange:\n  case SetRangeRev:\n  case StringGet:\n  case SuspendHookAwaitEF:\n  case SuspendHookAwaitEG:\n  case SuspendHookAwaitR:\n  case SuspendHookCreateCont:\n  case SuspendHookYield:\n  case ThrowArithmeticError:\n  case ThrowAsTypeStructException:\n  case ThrowArrayIndexException:\n  case ThrowArrayKeyException:\n  case ThrowCallReifiedFunctionWithoutGenerics:\n  case ThrowDivisionByZeroError:\n  case ThrowDivisionByZeroException:\n  case ThrowHasThisNeedStatic:\n  case ThrowInvalidArrayKey:\n  case ThrowInvalidOperation:\n  case ThrowLateInitPropError:\n  case ThrowMissingArg:\n  case ThrowMissingThis:\n  case ThrowOutOfBounds:\n  case ThrowParameterWrongType:\n  case ThrowParamInOutMismatch:\n  case ThrowParamInOutMismatchRange:\n  case UnsetElem:\n  case UnsetProp:\n  case VecSet:\n  case VectorSet:\n  case VerifyParamCallable:\n  case VerifyParamCls:\n  case VerifyParamFail:\n  case VerifyParamFailHard:\n  case VerifyProp:\n  case VerifyPropCls:\n  case VerifyPropFail:\n  case VerifyPropFailHard:\n  case VerifyReifiedLocalType:\n  case VerifyReifiedReturnType:\n  case VerifyRetCallable:\n  case VerifyRetCls:\n  case VerifyRetFail:\n  case VerifyRetFailHard:\n  case VerifyParamRecDesc:\n  case VerifyRetRecDesc:\n  case VerifyPropRecDesc:\n    return true;\n\n  case AbsDbl:\n  case AddDbl:\n  case AddInt:\n  case AddIntO:\n  case AddNewElemVec:\n  case AdvanceMixedPtrIter:\n  case AdvancePackedPtrIter:\n  case AFWHBlockOn:\n  case AKExistsArr:\n  case AKExistsDict:\n  case AKExistsKeyset:\n  case AllocPackedArray:\n  case AllocStructArray:\n  case AllocStructDArray:\n  case AllocStructDict:\n  case AllocVArray:\n  case AllocVecArray:\n  case AndInt:\n  case ArrayIdx:\n  case ArrayIsset:\n  case AssertLoc:\n  case AssertMBase:\n  case AssertNonNull:\n  case AssertStk:\n  case AssertType:\n  case AsyncFuncRet:\n  case AsyncFuncRetSlow:\n  case AsyncSwitchFast:\n  case BeginCatch:\n  case BeginInlining:\n  case Ceil:\n  case CheckArrayCOW:\n  case CheckCold:\n  case CheckDArray:\n  case CheckDictOffset:\n  case CheckInit:\n  case CheckInitMem:\n  case CheckIter:\n  case CheckKeysetOffset:\n  case CheckLoc:\n  case CheckMBase:\n  case CheckMixedArrayKeys:\n  case CheckMixedArrayOffset:\n  case CheckNonNull:\n  case CheckNullptr:\n  case CheckPackedArrayDataBounds:\n  case CheckRange:\n  case CheckRDSInitialized:\n  case CheckInOuts:\n  case CheckSmashableClass:\n  case CheckStk:\n  case CheckSubClsCns:\n  case CheckSurpriseFlags:\n  case CheckType:\n  case CheckTypeMem:\n  case CheckVArray:\n  case ChrInt:\n  case CmpBool:\n  case CmpDbl:\n  case CmpInt:\n  case CmpRes:\n  case CmpStr:\n  case CmpStrInt:\n  case ColIsEmpty:\n  case ColIsNEmpty:\n  case Conjure:\n  case ConjureUse:\n  case ConstructClosure:\n  case ContArIncIdx:\n  case ContArIncKey:\n  case ContArUpdateIdx:\n  case ContPreNext:\n  case ContStarted:\n  case ContStartedCheck:\n  case ContValid:\n  case ConvArrToBool:\n  case ConvArrToDArr:\n  case ConvArrToDbl:\n  case ConvArrToNonDVArr:\n  case ConvArrToVArr:\n  case ConvBoolToArr:\n  case ConvBoolToDbl:\n  case ConvBoolToInt:\n  case ConvDblToArr:\n  case ConvDblToBool:\n  case ConvDblToInt:\n  case ConvDblToStr:\n  case ConvDictToVArr:\n  case ConvDictToVec:\n  case ConvFuncToArr:\n  case ConvIntToArr:\n  case ConvIntToBool:\n  case ConvIntToDbl:\n  case ConvIntToStr:\n  case ConvKeysetToDict:\n  case ConvKeysetToVArr:\n  case ConvKeysetToVec:\n  case ConvResToDbl:\n  case ConvResToInt:\n  case ConvStrToArr:\n  case ConvStrToBool:\n  case ConvStrToDbl:\n  case ConvStrToInt:\n  case ConvVecToArr:\n  case ConvVecToDArr:\n  case ConvVecToDict:\n  case ConvVecToVArr:\n  case ConvPtrToLval:\n  case CountArray:\n  case CountArrayFast:\n  case CountCollection:\n  case CountDict:\n  case CountKeyset:\n  case CountVec:\n  case CountWHNotDone:\n  case CreateAFWH:\n  case CreateAFWHNoVV:\n  case CreateAGen:\n  case CreateAGWH:\n  case CreateGen:\n  case CreateSSWH:\n  case DbgAssertFunc:\n  case DbgAssertRefCount:\n  case DbgTraceCall:\n  case DbgTrashFrame:\n  case DbgTrashMem:\n  case DbgTrashRetVal:\n  case DbgTrashStk:\n  case DblAsBits:\n  case DebugBacktrace:\n  case DebugBacktraceFast:\n  case DecRef:\n  case DecRefNZ:\n  case DefCallFlags:\n  case DefCallFunc:\n  case DefCallNumArgs:\n  case DefCallCtx:\n  case DefConst:\n  case DefFP:\n  case DefFuncEntryFP:\n  case DefInlineFP:\n  case DefLabel:\n  case DefFrameRelSP:\n  case DefRegSP:\n  case DictEmptyElem:\n  case DictFirst:\n  case DictFirstKey:\n  case DictGetK:\n  case DictGetQuiet:\n  case DictIdx:\n  case DictIsset:\n  case DictLast:\n  case DictLastKey:\n  case DivDbl:\n  case DivInt:\n  case EagerSyncVMRegs:\n  case ElemDictK:\n  case ElemKeysetK:\n  case ElemMixedArrayK:\n  case EndBlock:\n  case EndCatch:\n  case EndGuards:\n  case EqArrayDataPtr:\n  case EqBool:\n  case EqCls:\n  case EqRecDesc:\n  case EqDbl:\n  case EqFunc:\n  case EqInt:\n  case EqKeyset:\n  case EqPtrIter:\n  case EqRes:\n  case EqStr:\n  case EqStrInt:\n  case EqStrPtr:\n  case ExtendsClass:\n  case FinishMemberOp:\n  case Floor:\n  case FuncCred:\n  case FuncHasAttr:\n  case GenericRetDecRefs:\n  case GetMemoKeyScalar:\n  case GetMixedPtrIter:\n  case GetPackedPtrIter:\n  case GetTime:\n  case GetTimeNs:\n  case GtBool:\n  case GtDbl:\n  case GteBool:\n  case GteDbl:\n  case GteInt:\n  case GteRes:\n  case GteStr:\n  case GteStrInt:\n  case GtInt:\n  case GtRes:\n  case GtStr:\n  case GtStrInt:\n  case HasToString:\n  case IncProfCounter:\n  case IncRef:\n  case IncStat:\n  case InitMixedLayoutArray:\n  case InitObjProps:\n  case InitObjMemoSlots:\n  case InitPackedLayoutArray:\n  case InitPackedLayoutArrayLoop:\n  case InitThrowableFileAndLine:\n  case InlineReturn:\n  case InlineReturnNoFrame:\n  case InlineSuspend:\n  case InstanceOf:\n  case InstanceOfBitmask:\n  case InstanceOfIface:\n  case InstanceOfIfaceVtable:\n  case InstanceOfRecDesc:\n  case InterfaceSupportsArr:\n  case InterfaceSupportsDbl:\n  case InterfaceSupportsDict:\n  case InterfaceSupportsInt:\n  case InterfaceSupportsKeyset:\n  case InterfaceSupportsStr:\n  case InterfaceSupportsVec:\n  case InterpOneCF:\n  case IsCol:\n  case IsDVArray:\n  case IsFunReifiedGenericsMatched:\n  case IsClsDynConstructible:\n  case IsNType:\n  case IsNTypeMem:\n  case IsType:\n  case IsTypeMem:\n  case IsWaitHandle:\n  case IterFree:\n  case Jmp:\n  case JmpNZero:\n  case JmpSSwitchDest:\n  case JmpSwitchDest:\n  case JmpZero:\n  case JmpPlaceholder:\n  case KeysetEmptyElem:\n  case KeysetFirst:\n  case KeysetGetK:\n  case KeysetGetQuiet:\n  case KeysetIdx:\n  case KeysetIsset:\n  case KeysetLast:\n  case KillIter:\n  case LdAFWHActRec:\n  case LdARFlags:\n  case LdARNumParams:\n  case LdBindAddr:\n  case LdClosureCls:\n  case LdClosureThis:\n  case LdClsCachedSafe:\n  case LdRecDescCachedSafe:\n  case LdClsCns:\n  case LdClsCnsVecLen:\n  case LdClsFromClsMeth:\n  case LdClsInitData:\n  case LdClsMethod:\n  case LdClsMethodCacheCls:\n  case LdClsMethodCacheFunc:\n  case LdClsMethodFCacheFunc:\n  case LdClsName:\n  case LdCns:\n  case LdColDict:\n  case LdColVec:\n  case LdContActRec:\n  case LdContArKey:\n  case LdContArValue:\n  case LdContField:\n  case LdContResumeAddr:\n  case LdElem:\n  case LdFuncCls:\n  case LdFrameCls:\n  case LdFrameThis:\n  case LdFuncFromClsMeth:\n  case LdFuncNumParams:\n  case LdFuncName:\n  case LdFuncRxLevel:\n  case LdFuncVecLen:\n  case LdGblAddr:\n  case LdGblAddrDef:\n  case LdIfaceMethod:\n  case LdInitPropAddr:\n  case LdInitRDSAddr:\n  case LdIterBase:\n  case LdIterPos:\n  case LdIterEnd:\n  case LdLoc:\n  case LdLocAddr:\n  case LdLocPseudoMain:\n  case LdMBase:\n  case LdMem:\n  case LdMethCallerName:\n  case LdMIPropStateAddr:\n  case LdMIStateAddr:\n  case LdPtrIterKey:\n  case LdPtrIterVal:\n  case LdRecDesc:\n  case LdObjClass:\n  case LdObjInvoke:\n  case LdOutAddr:\n  case LdPackedArrayDataElemAddr:\n  case LdPackedElem:\n  case LdPairBase:\n  case LdPropAddr:\n  case LdRDSAddr:\n  case LdRetVal:\n  case LdSSwitchDestFast:\n  case LdSmashable:\n  case LdSmashableFunc:\n  case LdStk:\n  case LdStkAddr:\n  case LdStrLen:\n  case LdSubClsCns:\n  case LdSubClsCnsClsName:\n  case LdSwitchDblIndex:\n  case LdSwitchStrIndex:\n  case LdTVAux:\n  case LdTypeCns:\n  case LdUnwinderValue:\n  case LdVecElem:\n  case LdVectorBase:\n  case LdVectorSize:\n  case LdWHNotDone:\n  case LdWHResult:\n  case LdWHState:\n  case LIterInit:\n  case LIterInitK:\n  case LIterNext:\n  case LIterNextK:\n  case LockObj:\n  case LookupClsRDS:\n  case LookupSPropSlot:\n  case Lshr:\n  case LtBool:\n  case LtDbl:\n  case LteBool:\n  case LteDbl:\n  case LteInt:\n  case LteRes:\n  case LteStr:\n  case LteStrInt:\n  case LtInt:\n  case LtRes:\n  case LtStr:\n  case LtStrInt:\n  case MapIsset:\n  case MarkRDSInitialized:\n  case MemoGetInstanceCache:\n  case MemoGetInstanceValue:\n  case MemoGetStaticCache:\n  case MemoGetStaticValue:\n  case MemoGetLSBCache:\n  case MemoGetLSBValue:\n  case MemoSetInstanceCache:\n  case MemoSetInstanceValue:\n  case MemoSetStaticCache:\n  case MemoSetStaticValue:\n  case MemoSetLSBCache:\n  case MemoSetLSBValue:\n  case MethodExists:\n  case MixedArrayGetK:\n  case Mod:\n  case Mov:\n  case MulDbl:\n  case MulInt:\n  case MulIntO:\n  case NeqBool:\n  case NeqDbl:\n  case NeqInt:\n  case NeqKeyset:\n  case NeqRes:\n  case NeqStr:\n  case NeqStrInt:\n  case NewArray:\n  case NewClsMeth:\n  case NewCol:\n  case NewColFromArray:\n  case NewDArray:\n  case NewDictArray:\n  case NewInstanceRaw:\n  case NewLikeArray:\n  case NewMixedArray:\n  case NewPair:\n  case NewStructArray:\n  case NewStructDArray:\n  case NewStructDict:\n  case NInstanceOfBitmask:\n  case Nop:\n  case NSameKeyset:\n  case NSameObj:\n  case NSameStr:\n  case OrdStr:\n  case OrInt:\n  case PairIsset:\n  case ProfileArrayKind:\n  case ProfileCall:\n  case ProfileDecRef:\n  case ProfileDictAccess:\n  case ProfileInstanceCheck:\n  case ProfileKeysetAccess:\n  case ProfileMethod:\n  case ProfileMixedArrayAccess:\n  case ProfileProp:\n  case ProfileSubClsCns:\n  case ProfileSwitchDest:\n  case ProfileType:\n  case RBTraceEntry:\n  case RBTraceMsg:\n  case ReleaseVVAndSkip:\n  case ReqBindJmp:\n  case ReqRetranslate:\n  case ReqRetranslateOpt:\n  case ReservePackedArrayDataNewElem:\n  case RestoreErrorLevel:\n  case RetCtrl:\n  case SameKeyset:\n  case SameObj:\n  case SameStr:\n  case Select:\n  case SetLegacyDict:\n  case SetLegacyVec:\n  case Shl:\n  case Shr:\n  case Sqrt:\n  case StArResumeAddr:\n  case StClosureArg:\n  case StContArKey:\n  case StContArState:\n  case StContArValue:\n  case StElem:\n  case StIterBase:\n  case StIterType:\n  case StIterPos:\n  case StIterEnd:\n  case StLoc:\n  case StLocPseudoMain:\n  case StLocRange:\n  case StMBase:\n  case StMem:\n  case StMIPropState:\n  case StOutValue:\n  case StrictlyIntegerConv:\n  case StringIsset:\n  case StStk:\n  case SubDbl:\n  case SubInt:\n  case SubIntO:\n  case SyncReturnBC:\n  case Unreachable:\n  case UnwindCheckSideExit:\n  case VecFirst:\n  case VecLast:\n  case VectorIsset:\n  case XorBool:\n  case XorInt:\n  case ZeroErrorLevel:\n    return false;\n  }\n  not_reached();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n}}\n","avg_line_length":23.4835493519,"max_line_length":80,"alphanum_fraction":0.6932580453,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7602,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2.0,"content":"\/\/*****************************************************************************\n\/\/ Copyright 2017-2020 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#include \"gtest\/gtest.h\"\n#include \"ngraph\/ngraph.hpp\"\n#include \"ngraph\/runtime\/tensor.hpp\"\n#include \"runtime\/backend.hpp\"\n#include \"util\/all_close.hpp\"\n#include \"util\/all_close_f.hpp\"\n#include \"util\/ndarray.hpp\"\n#include \"util\/test_control.hpp\"\n#include \"util\/test_tools.hpp\"\n\nNGRAPH_SUPPRESS_DEPRECATED_START\n\nusing namespace std;\nusing namespace ngraph;\n\nstatic string s_manifest = \"${MANIFEST}\";\n\nNGRAPH_TEST(${BACKEND_NAME}, tensor_constant)\n{\n    Shape shape{2, 2, 2};\n    auto A = op::Constant::create(element::f32, shape, {1, 2, 3, 4, 5, 6, 7, 8});\n    auto f = make_shared<Function>(A, ParameterVector{});\n\n    auto backend = runtime::Backend::create(\"${BACKEND_NAME}\");\n\n    \/\/ Create some tensors for input\/output\n    auto result = backend->create_tensor(element::f32, shape);\n\n    auto handle = backend->compile(f);\n    handle->call_with_validate({result}, {});\n    EXPECT_TRUE(test::all_close_f((vector<float>{1, 2, 3, 4, 5, 6, 7, 8}),\n                                  read_vector<float>(result),\n                                  MIN_FLOAT_TOLERANCE_BITS));\n}\n\nNGRAPH_TEST(${BACKEND_NAME}, tensor_2constant)\n{\n    Shape shape{2, 2, 2};\n    auto A = op::Constant::create(element::f32, shape, {1, 2, 3, 4, 5, 6, 7, 8});\n    auto f = make_shared<Function>(NodeVector{A, A}, ParameterVector{});\n\n    auto backend = runtime::Backend::create(\"${BACKEND_NAME}\");\n\n    \/\/ Create some tensors for input\/output\n    auto result0 = backend->create_tensor(element::f32, shape);\n    auto result1 = backend->create_tensor(element::f32, shape);\n\n    auto handle = backend->compile(f);\n    handle->call_with_validate({result0, result1}, {});\n    EXPECT_TRUE(test::all_close_f((vector<float>{1, 2, 3, 4, 5, 6, 7, 8}),\n                                  read_vector<float>(result0),\n                                  MIN_FLOAT_TOLERANCE_BITS));\n    EXPECT_TRUE(test::all_close_f((vector<float>{1, 2, 3, 4, 5, 6, 7, 8}),\n                                  read_vector<float>(result1),\n                                  MIN_FLOAT_TOLERANCE_BITS));\n}\n\nNGRAPH_TEST(${BACKEND_NAME}, tensor_constant_with_op)\n{\n    Shape shape{2, 2, 2};\n    auto A = op::Constant::create(element::f32, shape, {-1, 2, 3, -4, 5, -6, -7, 8});\n    auto f = make_shared<Function>(make_shared<op::Abs>(A), ParameterVector{});\n\n    auto backend = runtime::Backend::create(\"${BACKEND_NAME}\");\n\n    \/\/ Create some tensors for input\/output\n    auto result = backend->create_tensor(element::f32, shape);\n\n    auto handle = backend->compile(f);\n    handle->call_with_validate({result}, {});\n    EXPECT_TRUE(test::all_close_f((vector<float>{1, 2, 3, 4, 5, 6, 7, 8}),\n                                  read_vector<float>(result),\n                                  MIN_FLOAT_TOLERANCE_BITS));\n}\n\nNGRAPH_TEST(${BACKEND_NAME}, constant_multi_use)\n{\n    auto A = make_shared<op::Constant>(element::i32, Shape{}, std::vector<std::string>{\"388\"});\n    auto f = make_shared<Function>(A, ParameterVector{});\n    auto backend = runtime::Backend::create(\"${BACKEND_NAME}\");\n\n    std::shared_ptr<runtime::Tensor> r1 = backend->create_tensor(element::i32, Shape{});\n    auto handle = backend->compile(f);\n    handle->call_with_validate({r1}, std::vector<std::shared_ptr<runtime::Tensor>>{});\n    EXPECT_EQ(read_vector<int>(r1), std::vector<int>{388});\n\n    std::shared_ptr<runtime::Tensor> r2 = backend->create_tensor(element::i32, Shape{});\n    handle->call_with_validate({r2}, std::vector<std::shared_ptr<runtime::Tensor>>{});\n    EXPECT_EQ(read_vector<int>(r2), std::vector<int>{388});\n}\n\nNGRAPH_TEST(${BACKEND_NAME}, scalar_constant_float32)\n{\n    auto r = op::Constant::create(element::f32, Shape{}, {4.75});\n    auto f = make_shared<Function>(r, ParameterVector{});\n\n    auto backend = runtime::Backend::create(\"${BACKEND_NAME}\");\n\n    \/\/ Create some tensors for input\/output\n    auto result = backend->create_tensor(element::f32, Shape{});\n\n    auto handle = backend->compile(f);\n    handle->call_with_validate({result}, {});\n    EXPECT_TRUE(test::all_close_f(\n        vector<float>{4.75f}, read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS));\n}\n\nNGRAPH_TEST(${BACKEND_NAME}, scalar_constant_int64)\n{\n    auto r = op::Constant::create(element::i64, Shape{}, {0x4000000000000001});\n    auto f = make_shared<Function>(r, ParameterVector{});\n\n    auto backend = runtime::Backend::create(\"${BACKEND_NAME}\");\n\n    \/\/ Create some tensors for input\/output\n    auto result = backend->create_tensor(element::i64, Shape{});\n\n    auto handle = backend->compile(f);\n    handle->call_with_validate({result}, {});\n    EXPECT_EQ(vector<int64_t>{0x4000000000000001}, read_vector<int64_t>(result));\n}\n\nNGRAPH_TEST(${BACKEND_NAME}, tensor_constant_float32)\n{\n    Shape shape{2, 2};\n    auto r = op::Constant::create(element::f32, shape, {4.75, 4.5, -5.25, 0.0});\n    auto f = make_shared<Function>(r, ParameterVector{});\n\n    auto backend = runtime::Backend::create(\"${BACKEND_NAME}\");\n\n    \/\/ Create some tensors for input\/output\n    auto result = backend->create_tensor(element::f32, shape);\n\n    auto handle = backend->compile(f);\n    handle->call_with_validate({result}, {});\n    EXPECT_TRUE(test::all_close_f((vector<float>{4.75f, 4.5f, -5.25f, 0.0f}),\n                                  read_vector<float>(result),\n                                  MIN_FLOAT_TOLERANCE_BITS));\n}\n\nNGRAPH_TEST(${BACKEND_NAME}, tensor_constant_int64)\n{\n    Shape shape{2};\n    auto r = op::Constant::create(element::i64, shape, {0x4000000000000001, 0x4000000000000002});\n    auto f = make_shared<Function>(r, ParameterVector{});\n    auto backend = runtime::Backend::create(\"${BACKEND_NAME}\");\n    \/\/ Create some tensors for input\/output\n    auto result = backend->create_tensor(element::i64, shape);\n    auto handle = backend->compile(f);\n    handle->call_with_validate({result}, {});\n    EXPECT_EQ((vector<int64_t>{0x4000000000000001, 0x4000000000000002}),\n              read_vector<int64_t>(result));\n}\n\nNGRAPH_TEST(${BACKEND_NAME}, constant_equality_bool)\n{\n    Shape shape{4};\n    \/\/ auto A = make_shared<op::Parameter>(element::boolean, shape);\n    \/\/ auto B = make_shared<op::Parameter>(element::boolean, shape);\n    \/\/ auto f = make_shared<Function>(make_shared<op::Equal>(A, B), ParameterVector{A, B});\n\n    auto A = op::Constant::create(element::boolean, shape, {true, false, true, false});\n    auto B = op::Constant::create(element::boolean, shape, {true, true, true, true});\n    auto f = make_shared<Function>(make_shared<op::Equal>(A, B), ParameterVector{});\n\n    auto backend = runtime::Backend::create(\"${BACKEND_NAME}\");\n\n    \/\/ Create some tensors for input\/output\n    auto result = backend->create_tensor(element::boolean, shape);\n\n    auto handle = backend->compile(f);\n    handle->call_with_validate({result}, {});\n    EXPECT_EQ((vector<char>{true, false, true, false}), read_vector<char>(result));\n}\n","avg_line_length":39.8010471204,"max_line_length":97,"alphanum_fraction":0.6446987635,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2025,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/****************************************************************************************\n*  @author: kzvd4729                                         created: 2019-08-22 11:10:47                      \n*  solution_verdict: Language Error                          language: C++                                     \n*  run_time (ms):                                            memory_used (MB):                                 \n*  problem: https:\/\/vjudge.net\/problem\/SPOJ-LCS\n****************************************************************************************\/\n#include<bits\/stdc++.h>\n#define long long long\nusing namespace std;\nconst int N=2500;\nstruct node\n{\n  int len,link,next[26];\n};\nstruct suffixAutomata\n{\n  int sz,last;node aut[N+N+2];\/\/2*insrt function call\n  suffixAutomata()\n  {\n    sz=0,last=0;aut[0].link=-1;\n  }\n  void insrt(int c)\n  {\n    int now=++sz;aut[now].len=aut[last].len+1;\n    int p,q,cl;\n    for(p=last;p!=-1&&!aut[p].next[c];p=aut[p].link)\n      aut[p].next[c]=now;\n    if(p==-1)\n      aut[now].link=0;\n    else\n    {\n      q=aut[p].next[c];\n      if(aut[p].len+1==aut[q].len)\n        aut[now].link=q;\n      else\n      {\n        cl=++sz;aut[cl].len=aut[p].len+1;\n        aut[cl].link=aut[q].link;\n        memcpy(aut[cl].next,aut[q].next,sizeof(aut[cl].next));\n        for( ;p!=-1&&aut[p].next[c]==q;p=aut[p].link)\n          aut[p].next[c]=cl;\n        aut[now].link=aut[q].link=cl;\n      }\n    }\n    last=now;\n  }\n  int longestCommonSubstring(string s)\n  {\n    int now=0,len=0,mx=0;\n    for(auto x:s)\n    {\n      int c=x-'a',p;\n      if(aut[now].next[c])\n        len++,now=aut[now].next[c];\n      else\n      {\n        for(p=now;p!=-1&&!aut[p].next[c];p=aut[p].link);\n        if(p==-1)now=0,len=0;\n        else len=aut[p].len+1,now=aut[p].next[c];\n      }\n      if(len>mx)mx=len;\n    }\n    return mx;\n  }\n};\nint main()\n{\n  ios_base::sync_with_stdio(0);cin.tie(0);\n  string a,b;cin>>a>>b;suffixAutomata sam;\n  for(auto x:a)sam.insrt(x-'a');\n  cout<<sam.longestCommonSubstring(b)<<endl;\n  return 0;\n}","avg_line_length":27.7397260274,"max_line_length":111,"alphanum_fraction":0.4469135802,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":47359,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <qt\/shitcoingui.h>\n\n#include <qt\/shitcoinunits.h>\n#include <qt\/clientmodel.h>\n#include <qt\/guiconstants.h>\n#include <qt\/guiutil.h>\n#include <qt\/modaloverlay.h>\n#include <qt\/networkstyle.h>\n#include <qt\/notificator.h>\n#include <qt\/openuridialog.h>\n#include <qt\/optionsdialog.h>\n#include <qt\/optionsmodel.h>\n#include <qt\/platformstyle.h>\n#include <qt\/rpcconsole.h>\n#include <qt\/utilitydialog.h>\n\n#ifdef ENABLE_WALLET\n#include <qt\/walletframe.h>\n#include <qt\/walletmodel.h>\n#include <qt\/walletview.h>\n#endif \/\/ ENABLE_WALLET\n\n#ifdef Q_OS_MAC\n#include <qt\/macdockiconhandler.h>\n#endif\n\n#include <chainparams.h>\n#include <interfaces\/handler.h>\n#include <interfaces\/node.h>\n#include <ui_interface.h>\n#include <util.h>\n\n#include <iostream>\n\n#include <QAction>\n#include <QApplication>\n#include <QComboBox>\n#include <QDateTime>\n#include <QDesktopWidget>\n#include <QDragEnterEvent>\n#include <QListWidget>\n#include <QMenuBar>\n#include <QMessageBox>\n#include <QMimeData>\n#include <QProgressDialog>\n#include <QSettings>\n#include <QShortcut>\n#include <QStackedWidget>\n#include <QStatusBar>\n#include <QStyle>\n#include <QTimer>\n#include <QToolBar>\n#include <QUrlQuery>\n#include <QVBoxLayout>\n\nconst std::string ShitcoinGUI::DEFAULT_UIPLATFORM =\n#if defined(Q_OS_MAC)\n        \"macosx\"\n#elif defined(Q_OS_WIN)\n        \"windows\"\n#else\n        \"other\"\n#endif\n        ;\n\nShitcoinGUI::ShitcoinGUI(interfaces::Node& node, const PlatformStyle *_platformStyle, const NetworkStyle *networkStyle, QWidget *parent) :\n    QMainWindow(parent),\n    m_node(node),\n    platformStyle(_platformStyle)\n{\n    QSettings settings;\n    if (!restoreGeometry(settings.value(\"MainWindowGeometry\").toByteArray())) {\n        \/\/ Restore failed (perhaps missing setting), center the window\n        move(QApplication::desktop()->availableGeometry().center() - frameGeometry().center());\n    }\n\n    QString windowTitle = tr(PACKAGE_NAME) + \" - \";\n#ifdef ENABLE_WALLET\n    enableWallet = WalletModel::isWalletEnabled();\n#endif \/\/ ENABLE_WALLET\n    if(enableWallet)\n    {\n        windowTitle += tr(\"Wallet\");\n    } else {\n        windowTitle += tr(\"Node\");\n    }\n    windowTitle += \" \" + networkStyle->getTitleAddText();\n#ifndef Q_OS_MAC\n    QApplication::setWindowIcon(networkStyle->getTrayAndWindowIcon());\n    setWindowIcon(networkStyle->getTrayAndWindowIcon());\n#else\n    MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon());\n#endif\n    setWindowTitle(windowTitle);\n\n    rpcConsole = new RPCConsole(node, _platformStyle, 0);\n    helpMessageDialog = new HelpMessageDialog(node, this, false);\n#ifdef ENABLE_WALLET\n    if(enableWallet)\n    {\n        \/** Create wallet frame and make it the central widget *\/\n        walletFrame = new WalletFrame(_platformStyle, this);\n        setCentralWidget(walletFrame);\n    } else\n#endif \/\/ ENABLE_WALLET\n    {\n        \/* When compiled without wallet or -disablewallet is provided,\n         * the central widget is the rpc console.\n         *\/\n        setCentralWidget(rpcConsole);\n    }\n\n    \/\/ Accept D&D of URIs\n    setAcceptDrops(true);\n\n    \/\/ Create actions for the toolbar, menu bar and tray\/dock icon\n    \/\/ Needs walletFrame to be initialized\n    createActions();\n\n    \/\/ Create application menu bar\n    createMenuBar();\n\n    \/\/ Create the toolbars\n    createToolBars();\n\n    \/\/ Create system tray icon and notification\n    createTrayIcon(networkStyle);\n\n    \/\/ Create status bar\n    statusBar();\n\n    \/\/ Disable size grip because it looks ugly and nobody needs it\n    statusBar()->setSizeGripEnabled(false);\n\n    \/\/ Status bar notification icons\n    QFrame *frameBlocks = new QFrame();\n    frameBlocks->setContentsMargins(0,0,0,0);\n    frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);\n    QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);\n    frameBlocksLayout->setContentsMargins(3,0,3,0);\n    frameBlocksLayout->setSpacing(3);\n    unitDisplayControl = new UnitDisplayStatusBarControl(platformStyle);\n    labelWalletEncryptionIcon = new QLabel();\n    labelWalletHDStatusIcon = new QLabel();\n    labelProxyIcon = new QLabel();\n    connectionsControl = new GUIUtil::ClickableLabel();\n    labelBlocksIcon = new GUIUtil::ClickableLabel();\n    if(enableWallet)\n    {\n        frameBlocksLayout->addStretch();\n        frameBlocksLayout->addWidget(unitDisplayControl);\n        frameBlocksLayout->addStretch();\n        frameBlocksLayout->addWidget(labelWalletEncryptionIcon);\n        frameBlocksLayout->addWidget(labelWalletHDStatusIcon);\n    }\n    frameBlocksLayout->addWidget(labelProxyIcon);\n    frameBlocksLayout->addStretch();\n    frameBlocksLayout->addWidget(connectionsControl);\n    frameBlocksLayout->addStretch();\n    frameBlocksLayout->addWidget(labelBlocksIcon);\n    frameBlocksLayout->addStretch();\n\n    \/\/ Progress bar and label for blocks download\n    progressBarLabel = new QLabel();\n    progressBarLabel->setVisible(false);\n    progressBar = new GUIUtil::ProgressBar();\n    progressBar->setAlignment(Qt::AlignCenter);\n    progressBar->setVisible(false);\n\n    \/\/ Override style sheet for progress bar for styles that have a segmented progress bar,\n    \/\/ as they make the text unreadable (workaround for issue #1071)\n    \/\/ See https:\/\/doc.qt.io\/qt-5\/gallery.html\n    QString curStyle = QApplication::style()->metaObject()->className();\n    if(curStyle == \"QWindowsStyle\" || curStyle == \"QWindowsXPStyle\")\n    {\n        progressBar->setStyleSheet(\"QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }\");\n    }\n\n    statusBar()->addWidget(progressBarLabel);\n    statusBar()->addWidget(progressBar);\n    statusBar()->addPermanentWidget(frameBlocks);\n\n    \/\/ Install event filter to be able to catch status tip events (QEvent::StatusTip)\n    this->installEventFilter(this);\n\n    \/\/ Initially wallet actions should be disabled\n    setWalletActionsEnabled(false);\n\n    \/\/ Subscribe to notifications from core\n    subscribeToCoreSignals();\n\n    connect(connectionsControl, SIGNAL(clicked(QPoint)), this, SLOT(toggleNetworkActive()));\n\n    modalOverlay = new ModalOverlay(this->centralWidget());\n#ifdef ENABLE_WALLET\n    if(enableWallet) {\n        connect(walletFrame, SIGNAL(requestedSyncWarningInfo()), this, SLOT(showModalOverlay()));\n        connect(labelBlocksIcon, SIGNAL(clicked(QPoint)), this, SLOT(showModalOverlay()));\n        connect(progressBar, SIGNAL(clicked(QPoint)), this, SLOT(showModalOverlay()));\n    }\n#endif\n}\n\nShitcoinGUI::~ShitcoinGUI()\n{\n    \/\/ Unsubscribe from notifications from core\n    unsubscribeFromCoreSignals();\n\n    QSettings settings;\n    settings.setValue(\"MainWindowGeometry\", saveGeometry());\n    if(trayIcon) \/\/ Hide tray icon, as deleting will let it linger until quit (on Ubuntu)\n        trayIcon->hide();\n#ifdef Q_OS_MAC\n    delete appMenuBar;\n    MacDockIconHandler::cleanup();\n#endif\n\n    delete rpcConsole;\n}\n\nvoid ShitcoinGUI::createActions()\n{\n    QActionGroup *tabGroup = new QActionGroup(this);\n\n    overviewAction = new QAction(platformStyle->SingleColorIcon(\":\/icons\/overview\"), tr(\"&Overview\"), this);\n    overviewAction->setStatusTip(tr(\"Show general overview of wallet\"));\n    overviewAction->setToolTip(overviewAction->statusTip());\n    overviewAction->setCheckable(true);\n    overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));\n    tabGroup->addAction(overviewAction);\n\n    sendCoinsAction = new QAction(platformStyle->SingleColorIcon(\":\/icons\/send\"), tr(\"&Send\"), this);\n    sendCoinsAction->setStatusTip(tr(\"Send coins to a Shitcoin address\"));\n    sendCoinsAction->setToolTip(sendCoinsAction->statusTip());\n    sendCoinsAction->setCheckable(true);\n    sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));\n    tabGroup->addAction(sendCoinsAction);\n\n    sendCoinsMenuAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/send\"), sendCoinsAction->text(), this);\n    sendCoinsMenuAction->setStatusTip(sendCoinsAction->statusTip());\n    sendCoinsMenuAction->setToolTip(sendCoinsMenuAction->statusTip());\n\n    receiveCoinsAction = new QAction(platformStyle->SingleColorIcon(\":\/icons\/receiving_addresses\"), tr(\"&Receive\"), this);\n    receiveCoinsAction->setStatusTip(tr(\"Request payments (generates QR codes and shitcoin: URIs)\"));\n    receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());\n    receiveCoinsAction->setCheckable(true);\n    receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));\n    tabGroup->addAction(receiveCoinsAction);\n\n    receiveCoinsMenuAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/receiving_addresses\"), receiveCoinsAction->text(), this);\n    receiveCoinsMenuAction->setStatusTip(receiveCoinsAction->statusTip());\n    receiveCoinsMenuAction->setToolTip(receiveCoinsMenuAction->statusTip());\n\n    historyAction = new QAction(platformStyle->SingleColorIcon(\":\/icons\/history\"), tr(\"&Transactions\"), this);\n    historyAction->setStatusTip(tr(\"Browse transaction history\"));\n    historyAction->setToolTip(historyAction->statusTip());\n    historyAction->setCheckable(true);\n    historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));\n    tabGroup->addAction(historyAction);\n\n#ifdef ENABLE_WALLET\n    \/\/ These showNormalIfMinimized are needed because Send Coins and Receive Coins\n    \/\/ can be triggered from the tray menu, and need to show the GUI to be useful.\n    connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\n    connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));\n    connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\n    connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));\n    connect(sendCoinsMenuAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\n    connect(sendCoinsMenuAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));\n    connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\n    connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));\n    connect(receiveCoinsMenuAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\n    connect(receiveCoinsMenuAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));\n    connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\n    connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));\n#endif \/\/ ENABLE_WALLET\n\n    quitAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/quit\"), tr(\"E&xit\"), this);\n    quitAction->setStatusTip(tr(\"Quit application\"));\n    quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));\n    quitAction->setMenuRole(QAction::QuitRole);\n    aboutAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/about\"), tr(\"&About %1\").arg(tr(PACKAGE_NAME)), this);\n    aboutAction->setStatusTip(tr(\"Show information about %1\").arg(tr(PACKAGE_NAME)));\n    aboutAction->setMenuRole(QAction::AboutRole);\n    aboutAction->setEnabled(false);\n    aboutQtAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/about_qt\"), tr(\"About &Qt\"), this);\n    aboutQtAction->setStatusTip(tr(\"Show information about Qt\"));\n    aboutQtAction->setMenuRole(QAction::AboutQtRole);\n    optionsAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/options\"), tr(\"&Options...\"), this);\n    optionsAction->setStatusTip(tr(\"Modify configuration options for %1\").arg(tr(PACKAGE_NAME)));\n    optionsAction->setMenuRole(QAction::PreferencesRole);\n    optionsAction->setEnabled(false);\n    toggleHideAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/about\"), tr(\"&Show \/ Hide\"), this);\n    toggleHideAction->setStatusTip(tr(\"Show or hide the main Window\"));\n\n    encryptWalletAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/lock_closed\"), tr(\"&Encrypt Wallet...\"), this);\n    encryptWalletAction->setStatusTip(tr(\"Encrypt the private keys that belong to your wallet\"));\n    encryptWalletAction->setCheckable(true);\n    backupWalletAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/filesave\"), tr(\"&Backup Wallet...\"), this);\n    backupWalletAction->setStatusTip(tr(\"Backup wallet to another location\"));\n    changePassphraseAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/key\"), tr(\"&Change Passphrase...\"), this);\n    changePassphraseAction->setStatusTip(tr(\"Change the passphrase used for wallet encryption\"));\n    signMessageAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/edit\"), tr(\"Sign &message...\"), this);\n    signMessageAction->setStatusTip(tr(\"Sign messages with your Shitcoin addresses to prove you own them\"));\n    verifyMessageAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/verify\"), tr(\"&Verify message...\"), this);\n    verifyMessageAction->setStatusTip(tr(\"Verify messages to ensure they were signed with specified Shitcoin addresses\"));\n\n    openRPCConsoleAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/debugwindow\"), tr(\"&Debug window\"), this);\n    openRPCConsoleAction->setStatusTip(tr(\"Open debugging and diagnostic console\"));\n    \/\/ initially disable the debug window menu item\n    openRPCConsoleAction->setEnabled(false);\n\n    usedSendingAddressesAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/address-book\"), tr(\"&Sending addresses...\"), this);\n    usedSendingAddressesAction->setStatusTip(tr(\"Show the list of used sending addresses and labels\"));\n    usedReceivingAddressesAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/address-book\"), tr(\"&Receiving addresses...\"), this);\n    usedReceivingAddressesAction->setStatusTip(tr(\"Show the list of used receiving addresses and labels\"));\n\n    openAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/open\"), tr(\"Open &URI...\"), this);\n    openAction->setStatusTip(tr(\"Open a shitcoin: URI or payment request\"));\n\n    showHelpMessageAction = new QAction(platformStyle->TextColorIcon(\":\/icons\/info\"), tr(\"&Command-line options\"), this);\n    showHelpMessageAction->setMenuRole(QAction::NoRole);\n    showHelpMessageAction->setStatusTip(tr(\"Show the %1 help message to get a list with possible Shitcoin command-line options\").arg(tr(PACKAGE_NAME)));\n\n    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));\n    connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));\n    connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));\n    connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));\n    connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));\n    connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked()));\n    connect(openRPCConsoleAction, SIGNAL(triggered()), this, SLOT(showDebugWindow()));\n    \/\/ prevents an open debug window from becoming stuck\/unusable on client shutdown\n    connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide()));\n\n#ifdef ENABLE_WALLET\n    if(walletFrame)\n    {\n        connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));\n        connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));\n        connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));\n        connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));\n        connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));\n        connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses()));\n        connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses()));\n        connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked()));\n    }\n#endif \/\/ ENABLE_WALLET\n\n    new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C), this, SLOT(showDebugWindowActivateConsole()));\n    new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_D), this, SLOT(showDebugWindow()));\n}\n\nvoid ShitcoinGUI::createMenuBar()\n{\n#ifdef Q_OS_MAC\n    \/\/ Create a decoupled menu bar on Mac which stays even if the window is closed\n    appMenuBar = new QMenuBar();\n#else\n    \/\/ Get the main window's menu bar on other platforms\n    appMenuBar = menuBar();\n#endif\n\n    \/\/ Configure the menus\n    QMenu *file = appMenuBar->addMenu(tr(\"&File\"));\n    if(walletFrame)\n    {\n        file->addAction(openAction);\n        file->addAction(backupWalletAction);\n        file->addAction(signMessageAction);\n        file->addAction(verifyMessageAction);\n        file->addSeparator();\n        file->addAction(usedSendingAddressesAction);\n        file->addAction(usedReceivingAddressesAction);\n        file->addSeparator();\n    }\n    file->addAction(quitAction);\n\n    QMenu *settings = appMenuBar->addMenu(tr(\"&Settings\"));\n    if(walletFrame)\n    {\n        settings->addAction(encryptWalletAction);\n        settings->addAction(changePassphraseAction);\n        settings->addSeparator();\n    }\n    settings->addAction(optionsAction);\n\n    QMenu *help = appMenuBar->addMenu(tr(\"&Help\"));\n    if(walletFrame)\n    {\n        help->addAction(openRPCConsoleAction);\n    }\n    help->addAction(showHelpMessageAction);\n    help->addSeparator();\n    help->addAction(aboutAction);\n    help->addAction(aboutQtAction);\n}\n\nvoid ShitcoinGUI::createToolBars()\n{\n    if(walletFrame)\n    {\n        QToolBar *toolbar = addToolBar(tr(\"Tabs toolbar\"));\n        appToolBar = toolbar;\n        toolbar->setContextMenuPolicy(Qt::PreventContextMenu);\n        toolbar->setMovable(false);\n        toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);\n        toolbar->addAction(overviewAction);\n        toolbar->addAction(sendCoinsAction);\n        toolbar->addAction(receiveCoinsAction);\n        toolbar->addAction(historyAction);\n        overviewAction->setChecked(true);\n\n#ifdef ENABLE_WALLET\n        QWidget *spacer = new QWidget();\n        spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n        toolbar->addWidget(spacer);\n\n        m_wallet_selector = new QComboBox();\n        connect(m_wallet_selector, SIGNAL(currentIndexChanged(int)), this, SLOT(setCurrentWalletBySelectorIndex(int)));\n\n        m_wallet_selector_label = new QLabel();\n        m_wallet_selector_label->setText(tr(\"Wallet:\") + \" \");\n        m_wallet_selector_label->setBuddy(m_wallet_selector);\n\n        m_wallet_selector_label_action = appToolBar->addWidget(m_wallet_selector_label);\n        m_wallet_selector_action = appToolBar->addWidget(m_wallet_selector);\n\n        m_wallet_selector_label_action->setVisible(false);\n        m_wallet_selector_action->setVisible(false);\n#endif\n    }\n}\n\nvoid ShitcoinGUI::setClientModel(ClientModel *_clientModel)\n{\n    this->clientModel = _clientModel;\n    if(_clientModel)\n    {\n        \/\/ Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,\n        \/\/ while the client has not yet fully loaded\n        createTrayIconMenu();\n\n        \/\/ Keep up to date with client\n        updateNetworkState();\n        connect(_clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));\n        connect(_clientModel, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));\n\n        modalOverlay->setKnownBestHeight(_clientModel->getHeaderTipHeight(), QDateTime::fromTime_t(_clientModel->getHeaderTipTime()));\n        setNumBlocks(m_node.getNumBlocks(), QDateTime::fromTime_t(m_node.getLastBlockTime()), m_node.getVerificationProgress(), false);\n        connect(_clientModel, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool)));\n\n        \/\/ Receive and report messages from client model\n        connect(_clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int)));\n\n        \/\/ Show progress dialog\n        connect(_clientModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int)));\n\n        rpcConsole->setClientModel(_clientModel);\n\n        updateProxyIcon();\n\n#ifdef ENABLE_WALLET\n        if(walletFrame)\n        {\n            walletFrame->setClientModel(_clientModel);\n        }\n#endif \/\/ ENABLE_WALLET\n        unitDisplayControl->setOptionsModel(_clientModel->getOptionsModel());\n\n        OptionsModel* optionsModel = _clientModel->getOptionsModel();\n        if(optionsModel)\n        {\n            \/\/ be aware of the tray icon disable state change reported by the OptionsModel object.\n            connect(optionsModel,SIGNAL(hideTrayIconChanged(bool)),this,SLOT(setTrayIconVisible(bool)));\n\n            \/\/ initialize the disable state of the tray icon with the current value in the model.\n            setTrayIconVisible(optionsModel->getHideTrayIcon());\n        }\n    } else {\n        \/\/ Disable possibility to show main window via action\n        toggleHideAction->setEnabled(false);\n        if(trayIconMenu)\n        {\n            \/\/ Disable context menu on tray icon\n            trayIconMenu->clear();\n        }\n        \/\/ Propagate cleared model to child objects\n        rpcConsole->setClientModel(nullptr);\n#ifdef ENABLE_WALLET\n        if (walletFrame)\n        {\n            walletFrame->setClientModel(nullptr);\n        }\n#endif \/\/ ENABLE_WALLET\n        unitDisplayControl->setOptionsModel(nullptr);\n    }\n}\n\n#ifdef ENABLE_WALLET\nbool ShitcoinGUI::addWallet(WalletModel *walletModel)\n{\n    if(!walletFrame)\n        return false;\n    const QString name = walletModel->getWalletName();\n    QString display_name = name.isEmpty() ? \"[\"+tr(\"default wallet\")+\"]\" : name;\n    setWalletActionsEnabled(true);\n    m_wallet_selector->addItem(display_name, name);\n    if (m_wallet_selector->count() == 2) {\n        m_wallet_selector_label_action->setVisible(true);\n        m_wallet_selector_action->setVisible(true);\n    }\n    rpcConsole->addWallet(walletModel);\n    return walletFrame->addWallet(walletModel);\n}\n\nbool ShitcoinGUI::removeWallet(WalletModel* walletModel)\n{\n    if (!walletFrame) return false;\n    QString name = walletModel->getWalletName();\n    int index = m_wallet_selector->findData(name);\n    m_wallet_selector->removeItem(index);\n    if (m_wallet_selector->count() == 0) {\n        setWalletActionsEnabled(false);\n    } else if (m_wallet_selector->count() == 1) {\n        m_wallet_selector_label_action->setVisible(false);\n        m_wallet_selector_action->setVisible(false);\n    }\n    rpcConsole->removeWallet(walletModel);\n    return walletFrame->removeWallet(name);\n}\n\nbool ShitcoinGUI::setCurrentWallet(const QString& name)\n{\n    if(!walletFrame)\n        return false;\n    return walletFrame->setCurrentWallet(name);\n}\n\nbool ShitcoinGUI::setCurrentWalletBySelectorIndex(int index)\n{\n    QString internal_name = m_wallet_selector->itemData(index).toString();\n    return setCurrentWallet(internal_name);\n}\n\nvoid ShitcoinGUI::removeAllWallets()\n{\n    if(!walletFrame)\n        return;\n    setWalletActionsEnabled(false);\n    walletFrame->removeAllWallets();\n}\n#endif \/\/ ENABLE_WALLET\n\nvoid ShitcoinGUI::setWalletActionsEnabled(bool enabled)\n{\n    overviewAction->setEnabled(enabled);\n    sendCoinsAction->setEnabled(enabled);\n    sendCoinsMenuAction->setEnabled(enabled);\n    receiveCoinsAction->setEnabled(enabled);\n    receiveCoinsMenuAction->setEnabled(enabled);\n    historyAction->setEnabled(enabled);\n    encryptWalletAction->setEnabled(enabled);\n    backupWalletAction->setEnabled(enabled);\n    changePassphraseAction->setEnabled(enabled);\n    signMessageAction->setEnabled(enabled);\n    verifyMessageAction->setEnabled(enabled);\n    usedSendingAddressesAction->setEnabled(enabled);\n    usedReceivingAddressesAction->setEnabled(enabled);\n    openAction->setEnabled(enabled);\n}\n\nvoid ShitcoinGUI::createTrayIcon(const NetworkStyle *networkStyle)\n{\n#ifndef Q_OS_MAC\n    trayIcon = new QSystemTrayIcon(this);\n    QString toolTip = tr(\"%1 client\").arg(tr(PACKAGE_NAME)) + \" \" + networkStyle->getTitleAddText();\n    trayIcon->setToolTip(toolTip);\n    trayIcon->setIcon(networkStyle->getTrayAndWindowIcon());\n    trayIcon->hide();\n#endif\n\n    notificator = new Notificator(QApplication::applicationName(), trayIcon, this);\n}\n\nvoid ShitcoinGUI::createTrayIconMenu()\n{\n#ifndef Q_OS_MAC\n    \/\/ return if trayIcon is unset (only on non-Mac OSes)\n    if (!trayIcon)\n        return;\n\n    trayIconMenu = new QMenu(this);\n    trayIcon->setContextMenu(trayIconMenu);\n\n    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),\n            this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));\n#else\n    \/\/ Note: On Mac, the dock icon is used to provide the tray's functionality.\n    MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();\n    dockIconHandler->setMainWindow(static_cast<QMainWindow*>(this));\n    trayIconMenu = dockIconHandler->dockMenu();\n#endif\n\n    \/\/ Configuration of the tray icon (or dock icon) icon menu\n    trayIconMenu->addAction(toggleHideAction);\n    trayIconMenu->addSeparator();\n    trayIconMenu->addAction(sendCoinsMenuAction);\n    trayIconMenu->addAction(receiveCoinsMenuAction);\n    trayIconMenu->addSeparator();\n    trayIconMenu->addAction(signMessageAction);\n    trayIconMenu->addAction(verifyMessageAction);\n    trayIconMenu->addSeparator();\n    trayIconMenu->addAction(optionsAction);\n    trayIconMenu->addAction(openRPCConsoleAction);\n#ifndef Q_OS_MAC \/\/ This is built-in on Mac\n    trayIconMenu->addSeparator();\n    trayIconMenu->addAction(quitAction);\n#endif\n}\n\n#ifndef Q_OS_MAC\nvoid ShitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)\n{\n    if(reason == QSystemTrayIcon::Trigger)\n    {\n        \/\/ Click on system tray icon triggers show\/hide of the main window\n        toggleHidden();\n    }\n}\n#endif\n\nvoid ShitcoinGUI::optionsClicked()\n{\n    if(!clientModel || !clientModel->getOptionsModel())\n        return;\n\n    OptionsDialog dlg(this, enableWallet);\n    dlg.setModel(clientModel->getOptionsModel());\n    dlg.exec();\n}\n\nvoid ShitcoinGUI::aboutClicked()\n{\n    if(!clientModel)\n        return;\n\n    HelpMessageDialog dlg(m_node, this, true);\n    dlg.exec();\n}\n\nvoid ShitcoinGUI::showDebugWindow()\n{\n    rpcConsole->showNormal();\n    rpcConsole->show();\n    rpcConsole->raise();\n    rpcConsole->activateWindow();\n}\n\nvoid ShitcoinGUI::showDebugWindowActivateConsole()\n{\n    rpcConsole->setTabFocus(RPCConsole::TAB_CONSOLE);\n    showDebugWindow();\n}\n\nvoid ShitcoinGUI::showHelpMessageClicked()\n{\n    helpMessageDialog->show();\n}\n\n#ifdef ENABLE_WALLET\nvoid ShitcoinGUI::openClicked()\n{\n    OpenURIDialog dlg(this);\n    if(dlg.exec())\n    {\n        Q_EMIT receivedURI(dlg.getURI());\n    }\n}\n\nvoid ShitcoinGUI::gotoOverviewPage()\n{\n    overviewAction->setChecked(true);\n    if (walletFrame) walletFrame->gotoOverviewPage();\n}\n\nvoid ShitcoinGUI::gotoHistoryPage()\n{\n    historyAction->setChecked(true);\n    if (walletFrame) walletFrame->gotoHistoryPage();\n}\n\nvoid ShitcoinGUI::gotoReceiveCoinsPage()\n{\n    receiveCoinsAction->setChecked(true);\n    if (walletFrame) walletFrame->gotoReceiveCoinsPage();\n}\n\nvoid ShitcoinGUI::gotoSendCoinsPage(QString addr)\n{\n    sendCoinsAction->setChecked(true);\n    if (walletFrame) walletFrame->gotoSendCoinsPage(addr);\n}\n\nvoid ShitcoinGUI::gotoSignMessageTab(QString addr)\n{\n    if (walletFrame) walletFrame->gotoSignMessageTab(addr);\n}\n\nvoid ShitcoinGUI::gotoVerifyMessageTab(QString addr)\n{\n    if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);\n}\n#endif \/\/ ENABLE_WALLET\n\nvoid ShitcoinGUI::updateNetworkState()\n{\n    int count = clientModel->getNumConnections();\n    QString icon;\n    switch(count)\n    {\n    case 0: icon = \":\/icons\/connect_0\"; break;\n    case 1: case 2: case 3: icon = \":\/icons\/connect_1\"; break;\n    case 4: case 5: case 6: icon = \":\/icons\/connect_2\"; break;\n    case 7: case 8: case 9: icon = \":\/icons\/connect_3\"; break;\n    default: icon = \":\/icons\/connect_4\"; break;\n    }\n\n    QString tooltip;\n\n    if (m_node.getNetworkActive()) {\n        tooltip = tr(\"%n active connection(s) to Shitcoin network\", \"\", count) + QString(\".<br>\") + tr(\"Click to disable network activity.\");\n    } else {\n        tooltip = tr(\"Network activity disabled.\") + QString(\"<br>\") + tr(\"Click to enable network activity again.\");\n        icon = \":\/icons\/network_disabled\";\n    }\n\n    \/\/ Don't word-wrap this (fixed-width) tooltip\n    tooltip = QString(\"<nobr>\") + tooltip + QString(\"<\/nobr>\");\n    connectionsControl->setToolTip(tooltip);\n\n    connectionsControl->setPixmap(platformStyle->SingleColorIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));\n}\n\nvoid ShitcoinGUI::setNumConnections(int count)\n{\n    updateNetworkState();\n}\n\nvoid ShitcoinGUI::setNetworkActive(bool networkActive)\n{\n    updateNetworkState();\n}\n\nvoid ShitcoinGUI::updateHeadersSyncProgressLabel()\n{\n    int64_t headersTipTime = clientModel->getHeaderTipTime();\n    int headersTipHeight = clientModel->getHeaderTipHeight();\n    int estHeadersLeft = (GetTime() - headersTipTime) \/ Params().GetConsensus().nPowTargetSpacing;\n    if (estHeadersLeft > HEADER_HEIGHT_DELTA_SYNC)\n        progressBarLabel->setText(tr(\"Syncing Headers (%1%)...\").arg(QString::number(100.0 \/ (headersTipHeight+estHeadersLeft)*headersTipHeight, 'f', 1)));\n}\n\nvoid ShitcoinGUI::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool header)\n{\n    if (modalOverlay)\n    {\n        if (header)\n            modalOverlay->setKnownBestHeight(count, blockDate);\n        else\n            modalOverlay->tipUpdate(count, blockDate, nVerificationProgress);\n    }\n    if (!clientModel)\n        return;\n\n    \/\/ Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbled text)\n    statusBar()->clearMessage();\n\n    \/\/ Acquire current block source\n    enum BlockSource blockSource = clientModel->getBlockSource();\n    switch (blockSource) {\n        case BlockSource::NETWORK:\n            if (header) {\n                updateHeadersSyncProgressLabel();\n                return;\n            }\n            progressBarLabel->setText(tr(\"Synchronizing with network...\"));\n            updateHeadersSyncProgressLabel();\n            break;\n        case BlockSource::DISK:\n            if (header) {\n                progressBarLabel->setText(tr(\"Indexing blocks on disk...\"));\n            } else {\n                progressBarLabel->setText(tr(\"Processing blocks on disk...\"));\n            }\n            break;\n        case BlockSource::REINDEX:\n            progressBarLabel->setText(tr(\"Reindexing blocks on disk...\"));\n            break;\n        case BlockSource::NONE:\n            if (header) {\n                return;\n            }\n            progressBarLabel->setText(tr(\"Connecting to peers...\"));\n            break;\n    }\n\n    QString tooltip;\n\n    QDateTime currentDate = QDateTime::currentDateTime();\n    qint64 secs = blockDate.secsTo(currentDate);\n\n    tooltip = tr(\"Processed %n block(s) of transaction history.\", \"\", count);\n\n    \/\/ Set icon state: spinning if catching up, tick otherwise\n    if(secs < 90*60)\n    {\n        tooltip = tr(\"Up to date\") + QString(\".<br>\") + tooltip;\n        labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(\":\/icons\/synced\").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));\n\n#ifdef ENABLE_WALLET\n        if(walletFrame)\n        {\n            walletFrame->showOutOfSyncWarning(false);\n            modalOverlay->showHide(true, true);\n        }\n#endif \/\/ ENABLE_WALLET\n\n        progressBarLabel->setVisible(false);\n        progressBar->setVisible(false);\n    }\n    else\n    {\n        QString timeBehindText = GUIUtil::formatNiceTimeOffset(secs);\n\n        progressBarLabel->setVisible(true);\n        progressBar->setFormat(tr(\"%1 behind\").arg(timeBehindText));\n        progressBar->setMaximum(1000000000);\n        progressBar->setValue(nVerificationProgress * 1000000000.0 + 0.5);\n        progressBar->setVisible(true);\n\n        tooltip = tr(\"Catching up...\") + QString(\"<br>\") + tooltip;\n        if(count != prevBlocks)\n        {\n            labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(QString(\n                \":\/movies\/spinner-%1\").arg(spinnerFrame, 3, 10, QChar('0')))\n                .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));\n            spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;\n        }\n        prevBlocks = count;\n\n#ifdef ENABLE_WALLET\n        if(walletFrame)\n        {\n            walletFrame->showOutOfSyncWarning(true);\n            modalOverlay->showHide();\n        }\n#endif \/\/ ENABLE_WALLET\n\n        tooltip += QString(\"<br>\");\n        tooltip += tr(\"Last received block was generated %1 ago.\").arg(timeBehindText);\n        tooltip += QString(\"<br>\");\n        tooltip += tr(\"Transactions after this will not yet be visible.\");\n    }\n\n    \/\/ Don't word-wrap this (fixed-width) tooltip\n    tooltip = QString(\"<nobr>\") + tooltip + QString(\"<\/nobr>\");\n\n    labelBlocksIcon->setToolTip(tooltip);\n    progressBarLabel->setToolTip(tooltip);\n    progressBar->setToolTip(tooltip);\n}\n\nvoid ShitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret)\n{\n    QString strTitle = tr(\"Shitcoin\"); \/\/ default title\n    \/\/ Default to information icon\n    int nMBoxIcon = QMessageBox::Information;\n    int nNotifyIcon = Notificator::Information;\n\n    QString msgType;\n\n    \/\/ Prefer supplied title over style based title\n    if (!title.isEmpty()) {\n        msgType = title;\n    }\n    else {\n        switch (style) {\n        case CClientUIInterface::MSG_ERROR:\n            msgType = tr(\"Error\");\n            break;\n        case CClientUIInterface::MSG_WARNING:\n            msgType = tr(\"Warning\");\n            break;\n        case CClientUIInterface::MSG_INFORMATION:\n            msgType = tr(\"Information\");\n            break;\n        default:\n            break;\n        }\n    }\n    \/\/ Append title to \"Shitcoin - \"\n    if (!msgType.isEmpty())\n        strTitle += \" - \" + msgType;\n\n    \/\/ Check for error\/warning icon\n    if (style & CClientUIInterface::ICON_ERROR) {\n        nMBoxIcon = QMessageBox::Critical;\n        nNotifyIcon = Notificator::Critical;\n    }\n    else if (style & CClientUIInterface::ICON_WARNING) {\n        nMBoxIcon = QMessageBox::Warning;\n        nNotifyIcon = Notificator::Warning;\n    }\n\n    \/\/ Display message\n    if (style & CClientUIInterface::MODAL) {\n        \/\/ Check for buttons, use OK as default, if none was supplied\n        QMessageBox::StandardButton buttons;\n        if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))\n            buttons = QMessageBox::Ok;\n\n        showNormalIfMinimized();\n        QMessageBox mBox(static_cast<QMessageBox::Icon>(nMBoxIcon), strTitle, message, buttons, this);\n        mBox.setTextFormat(Qt::PlainText);\n        int r = mBox.exec();\n        if (ret != nullptr)\n            *ret = r == QMessageBox::Ok;\n    }\n    else\n        notificator->notify(static_cast<Notificator::Class>(nNotifyIcon), strTitle, message);\n}\n\nvoid ShitcoinGUI::changeEvent(QEvent *e)\n{\n    QMainWindow::changeEvent(e);\n#ifndef Q_OS_MAC \/\/ Ignored on Mac\n    if(e->type() == QEvent::WindowStateChange)\n    {\n        if(clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray())\n        {\n            QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);\n            if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())\n            {\n                QTimer::singleShot(0, this, SLOT(hide()));\n                e->ignore();\n            }\n            else if((wsevt->oldState() & Qt::WindowMinimized) && !isMinimized())\n            {\n                QTimer::singleShot(0, this, SLOT(show()));\n                e->ignore();\n            }\n        }\n    }\n#endif\n}\n\nvoid ShitcoinGUI::closeEvent(QCloseEvent *event)\n{\n#ifndef Q_OS_MAC \/\/ Ignored on Mac\n    if(clientModel && clientModel->getOptionsModel())\n    {\n        if(!clientModel->getOptionsModel()->getMinimizeOnClose())\n        {\n            \/\/ close rpcConsole in case it was open to make some space for the shutdown window\n            rpcConsole->close();\n\n            QApplication::quit();\n        }\n        else\n        {\n            QMainWindow::showMinimized();\n            event->ignore();\n        }\n    }\n#else\n    QMainWindow::closeEvent(event);\n#endif\n}\n\nvoid ShitcoinGUI::showEvent(QShowEvent *event)\n{\n    \/\/ enable the debug window when the main window shows up\n    openRPCConsoleAction->setEnabled(true);\n    aboutAction->setEnabled(true);\n    optionsAction->setEnabled(true);\n}\n\n#ifdef ENABLE_WALLET\nvoid ShitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label, const QString& walletName)\n{\n    \/\/ On new transaction, make an info balloon\n    QString msg = tr(\"Date: %1\\n\").arg(date) +\n                  tr(\"Amount: %1\\n\").arg(ShitcoinUnits::formatWithUnit(unit, amount, true));\n    if (m_node.getWallets().size() > 1 && !walletName.isEmpty()) {\n        msg += tr(\"Wallet: %1\\n\").arg(walletName);\n    }\n    msg += tr(\"Type: %1\\n\").arg(type);\n    if (!label.isEmpty())\n        msg += tr(\"Label: %1\\n\").arg(label);\n    else if (!address.isEmpty())\n        msg += tr(\"Address: %1\\n\").arg(address);\n    message((amount)<0 ? tr(\"Sent transaction\") : tr(\"Incoming transaction\"),\n             msg, CClientUIInterface::MSG_INFORMATION);\n}\n#endif \/\/ ENABLE_WALLET\n\nvoid ShitcoinGUI::dragEnterEvent(QDragEnterEvent *event)\n{\n    \/\/ Accept only URIs\n    if(event->mimeData()->hasUrls())\n        event->acceptProposedAction();\n}\n\nvoid ShitcoinGUI::dropEvent(QDropEvent *event)\n{\n    if(event->mimeData()->hasUrls())\n    {\n        for (const QUrl &uri : event->mimeData()->urls())\n        {\n            Q_EMIT receivedURI(uri.toString());\n        }\n    }\n    event->acceptProposedAction();\n}\n\nbool ShitcoinGUI::eventFilter(QObject *object, QEvent *event)\n{\n    \/\/ Catch status tip events\n    if (event->type() == QEvent::StatusTip)\n    {\n        \/\/ Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff\n        if (progressBarLabel->isVisible() || progressBar->isVisible())\n            return true;\n    }\n    return QMainWindow::eventFilter(object, event);\n}\n\n#ifdef ENABLE_WALLET\nbool ShitcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient)\n{\n    \/\/ URI has to be valid\n    if (walletFrame && walletFrame->handlePaymentRequest(recipient))\n    {\n        showNormalIfMinimized();\n        gotoSendCoinsPage();\n        return true;\n    }\n    return false;\n}\n\nvoid ShitcoinGUI::setHDStatus(int hdEnabled)\n{\n    labelWalletHDStatusIcon->setPixmap(platformStyle->SingleColorIcon(hdEnabled ? \":\/icons\/hd_enabled\" : \":\/icons\/hd_disabled\").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));\n    labelWalletHDStatusIcon->setToolTip(hdEnabled ? tr(\"HD key generation is <b>enabled<\/b>\") : tr(\"HD key generation is <b>disabled<\/b>\"));\n\n    \/\/ eventually disable the QLabel to set its opacity to 50%\n    labelWalletHDStatusIcon->setEnabled(hdEnabled);\n}\n\nvoid ShitcoinGUI::setEncryptionStatus(int status)\n{\n    switch(status)\n    {\n    case WalletModel::Unencrypted:\n        labelWalletEncryptionIcon->hide();\n        encryptWalletAction->setChecked(false);\n        changePassphraseAction->setEnabled(false);\n        encryptWalletAction->setEnabled(true);\n        break;\n    case WalletModel::Unlocked:\n        labelWalletEncryptionIcon->show();\n        labelWalletEncryptionIcon->setPixmap(platformStyle->SingleColorIcon(\":\/icons\/lock_open\").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));\n        labelWalletEncryptionIcon->setToolTip(tr(\"Wallet is <b>encrypted<\/b> and currently <b>unlocked<\/b>\"));\n        encryptWalletAction->setChecked(true);\n        changePassphraseAction->setEnabled(true);\n        encryptWalletAction->setEnabled(false); \/\/ TODO: decrypt currently not supported\n        break;\n    case WalletModel::Locked:\n        labelWalletEncryptionIcon->show();\n        labelWalletEncryptionIcon->setPixmap(platformStyle->SingleColorIcon(\":\/icons\/lock_closed\").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));\n        labelWalletEncryptionIcon->setToolTip(tr(\"Wallet is <b>encrypted<\/b> and currently <b>locked<\/b>\"));\n        encryptWalletAction->setChecked(true);\n        changePassphraseAction->setEnabled(true);\n        encryptWalletAction->setEnabled(false); \/\/ TODO: decrypt currently not supported\n        break;\n    }\n}\n\nvoid ShitcoinGUI::updateWalletStatus()\n{\n    if (!walletFrame) {\n        return;\n    }\n    WalletView * const walletView = walletFrame->currentWalletView();\n    if (!walletView) {\n        return;\n    }\n    WalletModel * const walletModel = walletView->getWalletModel();\n    setEncryptionStatus(walletModel->getEncryptionStatus());\n    setHDStatus(walletModel->wallet().hdEnabled());\n}\n#endif \/\/ ENABLE_WALLET\n\nvoid ShitcoinGUI::updateProxyIcon()\n{\n    std::string ip_port;\n    bool proxy_enabled = clientModel->getProxyInfo(ip_port);\n\n    if (proxy_enabled) {\n        if (labelProxyIcon->pixmap() == 0) {\n            QString ip_port_q = QString::fromStdString(ip_port);\n            labelProxyIcon->setPixmap(platformStyle->SingleColorIcon(\":\/icons\/proxy\").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));\n            labelProxyIcon->setToolTip(tr(\"Proxy is <b>enabled<\/b>: %1\").arg(ip_port_q));\n        } else {\n            labelProxyIcon->show();\n        }\n    } else {\n        labelProxyIcon->hide();\n    }\n}\n\nvoid ShitcoinGUI::showNormalIfMinimized(bool fToggleHidden)\n{\n    if(!clientModel)\n        return;\n\n    \/\/ activateWindow() (sometimes) helps with keyboard focus on Windows\n    if (isHidden())\n    {\n        show();\n        activateWindow();\n    }\n    else if (isMinimized())\n    {\n        showNormal();\n        activateWindow();\n    }\n    else if (GUIUtil::isObscured(this))\n    {\n        raise();\n        activateWindow();\n    }\n    else if(fToggleHidden)\n        hide();\n}\n\nvoid ShitcoinGUI::toggleHidden()\n{\n    showNormalIfMinimized(true);\n}\n\nvoid ShitcoinGUI::detectShutdown()\n{\n    if (m_node.shutdownRequested())\n    {\n        if(rpcConsole)\n            rpcConsole->hide();\n        qApp->quit();\n    }\n}\n\nvoid ShitcoinGUI::showProgress(const QString &title, int nProgress)\n{\n    if (nProgress == 0)\n    {\n        progressDialog = new QProgressDialog(title, \"\", 0, 100);\n        progressDialog->setWindowModality(Qt::ApplicationModal);\n        progressDialog->setMinimumDuration(0);\n        progressDialog->setCancelButton(0);\n        progressDialog->setAutoClose(false);\n        progressDialog->setValue(0);\n    }\n    else if (nProgress == 100)\n    {\n        if (progressDialog)\n        {\n            progressDialog->close();\n            progressDialog->deleteLater();\n        }\n    }\n    else if (progressDialog)\n        progressDialog->setValue(nProgress);\n}\n\nvoid ShitcoinGUI::setTrayIconVisible(bool fHideTrayIcon)\n{\n    if (trayIcon)\n    {\n        trayIcon->setVisible(!fHideTrayIcon);\n    }\n}\n\nvoid ShitcoinGUI::showModalOverlay()\n{\n    if (modalOverlay && (progressBar->isVisible() || modalOverlay->isLayerVisible()))\n        modalOverlay->toggleVisibility();\n}\n\nstatic bool ThreadSafeMessageBox(ShitcoinGUI *gui, const std::string& message, const std::string& caption, unsigned int style)\n{\n    bool modal = (style & CClientUIInterface::MODAL);\n    \/\/ The SECURE flag has no effect in the Qt GUI.\n    \/\/ bool secure = (style & CClientUIInterface::SECURE);\n    style &= ~CClientUIInterface::SECURE;\n    bool ret = false;\n    \/\/ In case of modal message, use blocking connection to wait for user to click a button\n    QMetaObject::invokeMethod(gui, \"message\",\n                               modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,\n                               Q_ARG(QString, QString::fromStdString(caption)),\n                               Q_ARG(QString, QString::fromStdString(message)),\n                               Q_ARG(unsigned int, style),\n                               Q_ARG(bool*, &ret));\n    return ret;\n}\n\nvoid ShitcoinGUI::subscribeToCoreSignals()\n{\n    \/\/ Connect signals to client\n    m_handler_message_box = m_node.handleMessageBox(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));\n    m_handler_question = m_node.handleQuestion(boost::bind(ThreadSafeMessageBox, this, _1, _3, _4));\n}\n\nvoid ShitcoinGUI::unsubscribeFromCoreSignals()\n{\n    \/\/ Disconnect signals from client\n    m_handler_message_box->disconnect();\n    m_handler_question->disconnect();\n}\n\nvoid ShitcoinGUI::toggleNetworkActive()\n{\n    m_node.setNetworkActive(!m_node.getNetworkActive());\n}\n\nUnitDisplayStatusBarControl::UnitDisplayStatusBarControl(const PlatformStyle *platformStyle) :\n    optionsModel(0),\n    menu(0)\n{\n    createContextMenu();\n    setToolTip(tr(\"Unit to show amounts in. Click to select another unit.\"));\n    QList<ShitcoinUnits::Unit> units = ShitcoinUnits::availableUnits();\n    int max_width = 0;\n    const QFontMetrics fm(font());\n    for (const ShitcoinUnits::Unit unit : units)\n    {\n        max_width = qMax(max_width, fm.width(ShitcoinUnits::longName(unit)));\n    }\n    setMinimumSize(max_width, 0);\n    setAlignment(Qt::AlignRight | Qt::AlignVCenter);\n    setStyleSheet(QString(\"QLabel { color : %1 }\").arg(platformStyle->SingleColor().name()));\n}\n\n\/** So that it responds to button clicks *\/\nvoid UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent *event)\n{\n    onDisplayUnitsClicked(event->pos());\n}\n\n\/** Creates context menu, its actions, and wires up all the relevant signals for mouse events. *\/\nvoid UnitDisplayStatusBarControl::createContextMenu()\n{\n    menu = new QMenu(this);\n    for (ShitcoinUnits::Unit u : ShitcoinUnits::availableUnits())\n    {\n        QAction *menuAction = new QAction(QString(ShitcoinUnits::longName(u)), this);\n        menuAction->setData(QVariant(u));\n        menu->addAction(menuAction);\n    }\n    connect(menu,SIGNAL(triggered(QAction*)),this,SLOT(onMenuSelection(QAction*)));\n}\n\n\/** Lets the control know about the Options Model (and its signals) *\/\nvoid UnitDisplayStatusBarControl::setOptionsModel(OptionsModel *_optionsModel)\n{\n    if (_optionsModel)\n    {\n        this->optionsModel = _optionsModel;\n\n        \/\/ be aware of a display unit change reported by the OptionsModel object.\n        connect(_optionsModel,SIGNAL(displayUnitChanged(int)),this,SLOT(updateDisplayUnit(int)));\n\n        \/\/ initialize the display units label with the current value in the model.\n        updateDisplayUnit(_optionsModel->getDisplayUnit());\n    }\n}\n\n\/** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar *\/\nvoid UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits)\n{\n    setText(ShitcoinUnits::longName(newUnits));\n}\n\n\/** Shows context menu with Display Unit options by the mouse coordinates *\/\nvoid UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point)\n{\n    QPoint globalPos = mapToGlobal(point);\n    menu->exec(globalPos);\n}\n\n\/** Tells underlying optionsModel to update its current display unit. *\/\nvoid UnitDisplayStatusBarControl::onMenuSelection(QAction* action)\n{\n    if (action)\n    {\n        optionsModel->setDisplayUnit(action->data());\n    }\n}\n","avg_line_length":36.0967987805,"max_line_length":307,"alphanum_fraction":0.6897316244,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":36321,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/ Copyright (c) 2015-2018 The PIVX developers\n\/\/ Copyright (c) 2019 The Mktcash developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"base58.h\"\n#include \"checkpoints.h\"\n#include \"clientversion.h\"\n#include \"main.h\"\n#include \"rpc\/server.h\"\n#include \"sync.h\"\n#include \"txdb.h\"\n#include \"util.h\"\n#include \"utilmoneystr.h\"\n\n#include <stdint.h>\n#include <univalue.h>\n\nusing namespace std;\n\nextern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);\nvoid ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);\n\ndouble GetDifficulty(const CBlockIndex* blockindex)\n{\n    \/\/ Floating point number that is a multiple of the minimum difficulty,\n    \/\/ minimum difficulty = 1.0.\n    if (blockindex == NULL) {\n        if (chainActive.Tip() == NULL)\n            return 1.0;\n        else\n            blockindex = chainActive.Tip();\n    }\n\n    int nShift = (blockindex->nBits >> 24) & 0xff;\n\n    double dDiff =\n        (double)0x0000ffff \/ (double)(blockindex->nBits & 0x00ffffff);\n\n    while (nShift < 29) {\n        dDiff *= 256.0;\n        nShift++;\n    }\n    while (nShift > 29) {\n        dDiff \/= 256.0;\n        nShift--;\n    }\n\n    return dDiff;\n}\n\nUniValue blockheaderToJSON(const CBlockIndex* blockindex)\n{\n    UniValue result(UniValue::VOBJ);\n    result.push_back(Pair(\"hash\", blockindex->GetBlockHash().GetHex()));\n    int confirmations = -1;\n    \/\/ Only report confirmations if the block is on the main chain\n    if (chainActive.Contains(blockindex))\n        confirmations = chainActive.Height() - blockindex->nHeight + 1;\n    result.push_back(Pair(\"confirmations\", confirmations));\n    result.push_back(Pair(\"height\", blockindex->nHeight));\n    result.push_back(Pair(\"version\", blockindex->nVersion));\n    result.push_back(Pair(\"merkleroot\", blockindex->hashMerkleRoot.GetHex()));\n    result.push_back(Pair(\"time\", (int64_t)blockindex->nTime));\n    result.push_back(Pair(\"mediantime\", (int64_t)blockindex->GetMedianTimePast()));\n    result.push_back(Pair(\"nonce\", (uint64_t)blockindex->nNonce));\n    result.push_back(Pair(\"bits\", strprintf(\"%08x\", blockindex->nBits)));\n    result.push_back(Pair(\"difficulty\", GetDifficulty(blockindex)));\n    result.push_back(Pair(\"chainwork\", blockindex->nChainWork.GetHex()));\n    result.push_back(Pair(\"acc_checkpoint\", blockindex->nAccumulatorCheckpoint.GetHex()));\n\n    if (blockindex->pprev)\n        result.push_back(Pair(\"previousblockhash\", blockindex->pprev->GetBlockHash().GetHex()));\n    CBlockIndex *pnext = chainActive.Next(blockindex);\n    if (pnext)\n        result.push_back(Pair(\"nextblockhash\", pnext->GetBlockHash().GetHex()));\n    return result;\n}\n\nUniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false)\n{\n    UniValue result(UniValue::VOBJ);\n    result.push_back(Pair(\"hash\", block.GetHash().GetHex()));\n    int confirmations = -1;\n    \/\/ Only report confirmations if the block is on the main chain\n    if (chainActive.Contains(blockindex))\n        confirmations = chainActive.Height() - blockindex->nHeight + 1;\n    result.push_back(Pair(\"confirmations\", confirmations));\n    result.push_back(Pair(\"size\", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));\n    result.push_back(Pair(\"height\", blockindex->nHeight));\n    result.push_back(Pair(\"version\", block.nVersion));\n    result.push_back(Pair(\"merkleroot\", block.hashMerkleRoot.GetHex()));\n    result.push_back(Pair(\"acc_checkpoint\", block.nAccumulatorCheckpoint.GetHex()));\n    UniValue txs(UniValue::VARR);\n    BOOST_FOREACH (const CTransaction& tx, block.vtx) {\n        if (txDetails) {\n            UniValue objTx(UniValue::VOBJ);\n            TxToJSON(tx, uint256(0), objTx);\n            txs.push_back(objTx);\n        } else\n            txs.push_back(tx.GetHash().GetHex());\n    }\n    result.push_back(Pair(\"tx\", txs));\n    result.push_back(Pair(\"time\", block.GetBlockTime()));\n    result.push_back(Pair(\"mediantime\", (int64_t)blockindex->GetMedianTimePast()));\n    result.push_back(Pair(\"nonce\", (uint64_t)block.nNonce));\n    result.push_back(Pair(\"bits\", strprintf(\"%08x\", block.nBits)));\n    result.push_back(Pair(\"difficulty\", GetDifficulty(blockindex)));\n    result.push_back(Pair(\"chainwork\", blockindex->nChainWork.GetHex()));\n\n    if (blockindex->pprev)\n        result.push_back(Pair(\"previousblockhash\", blockindex->pprev->GetBlockHash().GetHex()));\n    CBlockIndex* pnext = chainActive.Next(blockindex);\n    if (pnext)\n        result.push_back(Pair(\"nextblockhash\", pnext->GetBlockHash().GetHex()));\n\n    result.push_back(Pair(\"moneysupply\",ValueFromAmount(blockindex->nMoneySupply)));\n\n    return result;\n}\n\nUniValue getblockcount(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() != 0)\n        throw runtime_error(\n            \"getblockcount\\n\"\n            \"\\nReturns the number of blocks in the longest block chain.\\n\"\n\n            \"\\nResult:\\n\"\n            \"n    (numeric) The current block count\\n\"\n\n            \"\\nExamples:\\n\" +\n            HelpExampleCli(\"getblockcount\", \"\") + HelpExampleRpc(\"getblockcount\", \"\"));\n\n    LOCK(cs_main);\n    return chainActive.Height();\n}\n\nUniValue getbestblockhash(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() != 0)\n        throw runtime_error(\n            \"getbestblockhash\\n\"\n            \"\\nReturns the hash of the best (tip) block in the longest block chain.\\n\"\n\n            \"\\nResult\\n\"\n            \"\\\"hex\\\"      (string) the block hash hex encoded\\n\"\n\n            \"\\nExamples\\n\" +\n            HelpExampleCli(\"getbestblockhash\", \"\") + HelpExampleRpc(\"getbestblockhash\", \"\"));\n\n    LOCK(cs_main);\n    return chainActive.Tip()->GetBlockHash().GetHex();\n}\n\nUniValue getdifficulty(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() != 0)\n        throw runtime_error(\n            \"getdifficulty\\n\"\n            \"\\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\\n\"\n\n            \"\\nResult:\\n\"\n            \"n.nnn       (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\\n\"\n\n            \"\\nExamples:\\n\" +\n            HelpExampleCli(\"getdifficulty\", \"\") + HelpExampleRpc(\"getdifficulty\", \"\"));\n\n    LOCK(cs_main);\n    return GetDifficulty();\n}\n\n\nUniValue mempoolToJSON(bool fVerbose = false)\n{\n    if (fVerbose) {\n        LOCK(mempool.cs);\n        UniValue o(UniValue::VOBJ);\n        BOOST_FOREACH (const PAIRTYPE(uint256, CTxMemPoolEntry) & entry, mempool.mapTx) {\n            const uint256& hash = entry.first;\n            const CTxMemPoolEntry& e = entry.second;\n            UniValue info(UniValue::VOBJ);\n            info.push_back(Pair(\"size\", (int)e.GetTxSize()));\n            info.push_back(Pair(\"fee\", ValueFromAmount(e.GetFee())));\n            info.push_back(Pair(\"time\", e.GetTime()));\n            info.push_back(Pair(\"height\", (int)e.GetHeight()));\n            info.push_back(Pair(\"startingpriority\", e.GetPriority(e.GetHeight())));\n            info.push_back(Pair(\"currentpriority\", e.GetPriority(chainActive.Height())));\n            const CTransaction& tx = e.GetTx();\n            set<string> setDepends;\n            BOOST_FOREACH (const CTxIn& txin, tx.vin) {\n                if (mempool.exists(txin.prevout.hash))\n                    setDepends.insert(txin.prevout.hash.ToString());\n            }\n\n            UniValue depends(UniValue::VARR);\n            BOOST_FOREACH(const string& dep, setDepends) {\n                depends.push_back(dep);\n            }\n\n            info.push_back(Pair(\"depends\", depends));\n            o.push_back(Pair(hash.ToString(), info));\n        }\n        return o;\n    } else {\n        vector<uint256> vtxid;\n        mempool.queryHashes(vtxid);\n\n        UniValue a(UniValue::VARR);\n        BOOST_FOREACH (const uint256& hash, vtxid)\n            a.push_back(hash.ToString());\n\n        return a;\n    }\n}\n\nUniValue getrawmempool(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() > 1)\n        throw runtime_error(\n            \"getrawmempool ( verbose )\\n\"\n            \"\\nReturns all transaction ids in memory pool as a json array of string transaction ids.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. verbose           (boolean, optional, default=false) true for a json object, false for array of transaction ids\\n\"\n\n            \"\\nResult: (for verbose = false):\\n\"\n            \"[                     (json array of string)\\n\"\n            \"  \\\"transactionid\\\"     (string) The transaction id\\n\"\n            \"  ,...\\n\"\n            \"]\\n\"\n\n            \"\\nResult: (for verbose = true):\\n\"\n            \"{                           (json object)\\n\"\n            \"  \\\"transactionid\\\" : {       (json object)\\n\"\n            \"    \\\"size\\\" : n,             (numeric) transaction size in bytes\\n\"\n            \"    \\\"fee\\\" : n,              (numeric) transaction fee in mktcash\\n\"\n            \"    \\\"time\\\" : n,             (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\\n\"\n            \"    \\\"height\\\" : n,           (numeric) block height when transaction entered pool\\n\"\n            \"    \\\"startingpriority\\\" : n, (numeric) priority when transaction entered pool\\n\"\n            \"    \\\"currentpriority\\\" : n,  (numeric) transaction priority now\\n\"\n            \"    \\\"depends\\\" : [           (array) unconfirmed transactions used as inputs for this transaction\\n\"\n            \"        \\\"transactionid\\\",    (string) parent transaction id\\n\"\n            \"       ... ]\\n\"\n            \"  }, ...\\n\"\n            \"]\\n\"\n\n            \"\\nExamples\\n\" +\n            HelpExampleCli(\"getrawmempool\", \"true\") + HelpExampleRpc(\"getrawmempool\", \"true\"));\n\n    LOCK(cs_main);\n\n    bool fVerbose = false;\n    if (params.size() > 0)\n        fVerbose = params[0].get_bool();\n\n    return mempoolToJSON(fVerbose);\n}\n\nUniValue getblockhash(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() != 1)\n        throw runtime_error(\n            \"getblockhash index\\n\"\n            \"\\nReturns hash of block in best-block-chain at index provided.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. index         (numeric, required) The block index\\n\"\n\n            \"\\nResult:\\n\"\n            \"\\\"hash\\\"         (string) The block hash\\n\"\n\n            \"\\nExamples:\\n\" +\n            HelpExampleCli(\"getblockhash\", \"1000\") + HelpExampleRpc(\"getblockhash\", \"1000\"));\n\n    LOCK(cs_main);\n\n    int nHeight = params[0].get_int();\n    if (nHeight < 0 || nHeight > chainActive.Height())\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"Block height out of range\");\n\n    CBlockIndex* pblockindex = chainActive[nHeight];\n    return pblockindex->GetBlockHash().GetHex();\n}\n\nUniValue getblock(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() < 1 || params.size() > 2)\n        throw runtime_error(\n            \"getblock \\\"hash\\\" ( verbose )\\n\"\n            \"\\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\\n\"\n            \"If verbose is true, returns an Object with information about block <hash>.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. \\\"hash\\\"          (string, required) The block hash\\n\"\n            \"2. verbose           (boolean, optional, default=true) true for a json object, false for the hex encoded data\\n\"\n\n            \"\\nResult (for verbose = true):\\n\"\n            \"{\\n\"\n            \"  \\\"hash\\\" : \\\"hash\\\",     (string) the block hash (same as provided)\\n\"\n            \"  \\\"confirmations\\\" : n,   (numeric) The number of confirmations, or -1 if the block is not on the main chain\\n\"\n            \"  \\\"size\\\" : n,            (numeric) The block size\\n\"\n            \"  \\\"height\\\" : n,          (numeric) The block height or index\\n\"\n            \"  \\\"version\\\" : n,         (numeric) The block version\\n\"\n            \"  \\\"merkleroot\\\" : \\\"xxxx\\\", (string) The merkle root\\n\"\n            \"  \\\"tx\\\" : [               (array of string) The transaction ids\\n\"\n            \"     \\\"transactionid\\\"     (string) The transaction id\\n\"\n            \"     ,...\\n\"\n            \"  ],\\n\"\n            \"  \\\"time\\\" : ttt,          (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"  \\\"mediantime\\\" : ttt,    (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"  \\\"nonce\\\" : n,           (numeric) The nonce\\n\"\n            \"  \\\"bits\\\" : \\\"1d00ffff\\\", (string) The bits\\n\"\n            \"  \\\"difficulty\\\" : x.xxx,  (numeric) The difficulty\\n\"\n            \"  \\\"previousblockhash\\\" : \\\"hash\\\",  (string) The hash of the previous block\\n\"\n            \"  \\\"nextblockhash\\\" : \\\"hash\\\"       (string) The hash of the next block\\n\"\n            \"  \\\"moneysupply\\\" : \\\"supply\\\"       (numeric) The money supply when this block was added to the blockchain\\n\"\n            \"}\\n\"\n\n            \"\\nResult (for verbose=false):\\n\"\n            \"\\\"data\\\"             (string) A string that is serialized, hex-encoded data for block 'hash'.\\n\"\n\n            \"\\nExamples:\\n\" +\n            HelpExampleCli(\"getblock\", \"\\\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\\\"\") +\n            HelpExampleRpc(\"getblock\", \"\\\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\\\"\"));\n\n    LOCK(cs_main);\n\n    std::string strHash = params[0].get_str();\n    uint256 hash(strHash);\n\n    bool fVerbose = true;\n    if (params.size() > 1)\n        fVerbose = params[1].get_bool();\n\n    if (mapBlockIndex.count(hash) == 0)\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Block not found\");\n\n    CBlock block;\n    CBlockIndex* pblockindex = mapBlockIndex[hash];\n\n    if (!ReadBlockFromDisk(block, pblockindex))\n        throw JSONRPCError(RPC_INTERNAL_ERROR, \"Can't read block from disk\");\n\n    if (!fVerbose) {\n        CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);\n        ssBlock << block;\n        std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());\n        return strHex;\n    }\n\n    return blockToJSON(block, pblockindex);\n}\n\nUniValue getblockheader(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() < 1 || params.size() > 2)\n        throw runtime_error(\n            \"getblockheader \\\"hash\\\" ( verbose )\\n\"\n            \"\\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash' header.\\n\"\n            \"If verbose is true, returns an Object with information about block <hash> header.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. \\\"hash\\\"          (string, required) The block hash\\n\"\n            \"2. verbose           (boolean, optional, default=true) true for a json object, false for the hex encoded data\\n\"\n\n            \"\\nResult (for verbose = true):\\n\"\n            \"{\\n\"\n            \"  \\\"version\\\" : n,         (numeric) The block version\\n\"\n            \"  \\\"previousblockhash\\\" : \\\"hash\\\",  (string) The hash of the previous block\\n\"\n            \"  \\\"merkleroot\\\" : \\\"xxxx\\\", (string) The merkle root\\n\"\n            \"  \\\"time\\\" : ttt,          (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"  \\\"mediantime\\\" : ttt,    (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"  \\\"nonce\\\" : n,           (numeric) The nonce\\n\"\n            \"  \\\"bits\\\" : \\\"1d00ffff\\\", (string) The bits\\n\"\n            \"}\\n\"\n\n            \"\\nResult (for verbose=false):\\n\"\n            \"\\\"data\\\"             (string) A string that is serialized, hex-encoded data for block 'hash' header.\\n\"\n\n            \"\\nExamples:\\n\" +\n            HelpExampleCli(\"getblockheader\", \"\\\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\\\"\") +\n            HelpExampleRpc(\"getblockheader\", \"\\\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\\\"\"));\n\n    std::string strHash = params[0].get_str();\n    uint256 hash(strHash);\n\n    bool fVerbose = true;\n    if (params.size() > 1)\n        fVerbose = params[1].get_bool();\n\n    if (mapBlockIndex.count(hash) == 0)\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Block not found\");\n\n    CBlockIndex* pblockindex = mapBlockIndex[hash];\n\n    if (!fVerbose) {\n        CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);\n        ssBlock << pblockindex->GetBlockHeader();\n        std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());\n        return strHex;\n    }\n\n    return blockheaderToJSON(pblockindex);\n}\n\nUniValue gettxoutsetinfo(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() != 0)\n        throw runtime_error(\n            \"gettxoutsetinfo\\n\"\n            \"\\nReturns statistics about the unspent transaction output set.\\n\"\n            \"Note this call may take some time.\\n\"\n\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"height\\\":n,     (numeric) The current block height (index)\\n\"\n            \"  \\\"bestblock\\\": \\\"hex\\\",   (string) the best block hash hex\\n\"\n            \"  \\\"transactions\\\": n,      (numeric) The number of transactions\\n\"\n            \"  \\\"txouts\\\": n,            (numeric) The number of output transactions\\n\"\n            \"  \\\"bytes_serialized\\\": n,  (numeric) The serialized size\\n\"\n            \"  \\\"hash_serialized\\\": \\\"hash\\\",   (string) The serialized hash\\n\"\n            \"  \\\"total_amount\\\": x.xxx          (numeric) The total amount\\n\"\n            \"}\\n\"\n\n            \"\\nExamples:\\n\" +\n            HelpExampleCli(\"gettxoutsetinfo\", \"\") + HelpExampleRpc(\"gettxoutsetinfo\", \"\"));\n\n    LOCK(cs_main);\n\n    UniValue ret(UniValue::VOBJ);\n\n    CCoinsStats stats;\n    FlushStateToDisk();\n    if (pcoinsTip->GetStats(stats)) {\n        ret.push_back(Pair(\"height\", (int64_t)stats.nHeight));\n        ret.push_back(Pair(\"bestblock\", stats.hashBlock.GetHex()));\n        ret.push_back(Pair(\"transactions\", (int64_t)stats.nTransactions));\n        ret.push_back(Pair(\"txouts\", (int64_t)stats.nTransactionOutputs));\n        ret.push_back(Pair(\"bytes_serialized\", (int64_t)stats.nSerializedSize));\n        ret.push_back(Pair(\"hash_serialized\", stats.hashSerialized.GetHex()));\n        ret.push_back(Pair(\"total_amount\", ValueFromAmount(stats.nTotalAmount)));\n    }\n    return ret;\n}\n\nUniValue gettxout(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() < 2 || params.size() > 3)\n        throw runtime_error(\n            \"gettxout \\\"txid\\\" n ( includemempool )\\n\"\n            \"\\nReturns details about an unspent transaction output.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. \\\"txid\\\"       (string, required) The transaction id\\n\"\n            \"2. n              (numeric, required) vout value\\n\"\n            \"3. includemempool  (boolean, optional) Whether to included the mem pool\\n\"\n\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"bestblock\\\" : \\\"hash\\\",    (string) the block hash\\n\"\n            \"  \\\"confirmations\\\" : n,       (numeric) The number of confirmations\\n\"\n            \"  \\\"value\\\" : x.xxx,           (numeric) The transaction value in btc\\n\"\n            \"  \\\"scriptPubKey\\\" : {         (json object)\\n\"\n            \"     \\\"asm\\\" : \\\"code\\\",       (string) \\n\"\n            \"     \\\"hex\\\" : \\\"hex\\\",        (string) \\n\"\n            \"     \\\"reqSigs\\\" : n,          (numeric) Number of required signatures\\n\"\n            \"     \\\"type\\\" : \\\"pubkeyhash\\\", (string) The type, eg pubkeyhash\\n\"\n            \"     \\\"addresses\\\" : [          (array of string) array of mktcash addresses\\n\"\n            \"     \\\"mktcashaddress\\\"   \t \t(string) mktcash address\\n\"\n            \"        ,...\\n\"\n            \"     ]\\n\"\n            \"  },\\n\"\n            \"  \\\"version\\\" : n,            (numeric) The version\\n\"\n            \"  \\\"coinbase\\\" : true|false   (boolean) Coinbase or not\\n\"\n            \"}\\n\"\n\n            \"\\nExamples:\\n\"\n            \"\\nGet unspent transactions\\n\" +\n            HelpExampleCli(\"listunspent\", \"\") +\n            \"\\nView the details\\n\" +\n            HelpExampleCli(\"gettxout\", \"\\\"txid\\\" 1\") +\n            \"\\nAs a json rpc call\\n\" +\n            HelpExampleRpc(\"gettxout\", \"\\\"txid\\\", 1\"));\n\n    LOCK(cs_main);\n\n    UniValue ret(UniValue::VOBJ);\n\n    std::string strHash = params[0].get_str();\n    uint256 hash(strHash);\n    int n = params[1].get_int();\n    bool fMempool = true;\n    if (params.size() > 2)\n        fMempool = params[2].get_bool();\n\n    CCoins coins;\n    if (fMempool) {\n        LOCK(mempool.cs);\n        CCoinsViewMemPool view(pcoinsTip, mempool);\n        if (!view.GetCoins(hash, coins))\n            return NullUniValue;\n        mempool.pruneSpent(hash, coins); \/\/ TODO: this should be done by the CCoinsViewMemPool\n    } else {\n        if (!pcoinsTip->GetCoins(hash, coins))\n            return NullUniValue;\n    }\n    if (n < 0 || (unsigned int)n >= coins.vout.size() || coins.vout[n].IsNull())\n        return NullUniValue;\n\n    BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());\n    CBlockIndex* pindex = it->second;\n    ret.push_back(Pair(\"bestblock\", pindex->GetBlockHash().GetHex()));\n    if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT)\n        ret.push_back(Pair(\"confirmations\", 0));\n    else\n        ret.push_back(Pair(\"confirmations\", pindex->nHeight - coins.nHeight + 1));\n    ret.push_back(Pair(\"value\", ValueFromAmount(coins.vout[n].nValue)));\n    UniValue o(UniValue::VOBJ);\n    ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true);\n    ret.push_back(Pair(\"scriptPubKey\", o));\n    ret.push_back(Pair(\"version\", coins.nVersion));\n    ret.push_back(Pair(\"coinbase\", coins.fCoinBase));\n\n    return ret;\n}\n\nUniValue verifychain(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() > 1)\n        throw runtime_error(\n            \"verifychain ( numblocks )\\n\"\n            \"\\nVerifies blockchain database.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. numblocks    (numeric, optional, default=288, 0=all) The number of blocks to check.\\n\"\n\n            \"\\nResult:\\n\"\n            \"true|false       (boolean) Verified or not\\n\"\n\n            \"\\nExamples:\\n\" +\n            HelpExampleCli(\"verifychain\", \"\") + HelpExampleRpc(\"verifychain\", \"\"));\n\n    LOCK(cs_main);\n\n    int nCheckLevel = 4;\n    int nCheckDepth = GetArg(\"-checkblocks\", 288);\n    if (params.size() > 0)\n        nCheckDepth = params[0].get_int();\n\n    fVerifyingBlocks = true;\n    bool fVerified = CVerifyDB().VerifyDB(pcoinsTip, nCheckLevel, nCheckDepth);\n    fVerifyingBlocks = false;\n\n    return fVerified;\n}\n\nstatic UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex)\n{\n    UniValue rv(UniValue::VOBJ);\n    rv.push_back(Pair(\"id\", name));\n    rv.push_back(Pair(\"version\", version));\n    return rv;\n}\n\nUniValue getblockchaininfo(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() != 0)\n        throw runtime_error(\n            \"getblockchaininfo\\n\"\n            \"Returns an object containing various state info regarding block chain processing.\\n\"\n\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"chain\\\": \\\"xxxx\\\",        (string) current network name as defined in BIP70 (main, test, regtest)\\n\"\n            \"  \\\"blocks\\\": xxxxxx,         (numeric) the current number of blocks processed in the server\\n\"\n            \"  \\\"headers\\\": xxxxxx,        (numeric) the current number of headers we have validated\\n\"\n            \"  \\\"bestblockhash\\\": \\\"...\\\", (string) the hash of the currently best block\\n\"\n            \"  \\\"difficulty\\\": xxxxxx,     (numeric) the current difficulty\\n\"\n            \"  \\\"verificationprogress\\\": xxxx, (numeric) estimate of verification progress [0..1]\\n\"\n            \"  \\\"chainwork\\\": \\\"xxxx\\\"     (string) total amount of work in active chain, in hexadecimal\\n\"\n            \"  \\\"softforks\\\": [            (array) status of softforks in progress\\n\"\n            \"     {\\n\"\n            \"        \\\"id\\\": \\\"xxxx\\\",        (string) name of softfork\\n\"\n            \"        \\\"version\\\": xx,         (numeric) block version\\n\"\n            \"        \\\"enforce\\\": {           (object) progress toward enforcing the softfork rules for new-version blocks\\n\"\n            \"           \\\"status\\\": xx,       (boolean) true if threshold reached\\n\"\n            \"           \\\"found\\\": xx,        (numeric) number of blocks with the new version found\\n\"\n            \"           \\\"required\\\": xx,     (numeric) number of blocks required to trigger\\n\"\n            \"           \\\"window\\\": xx,       (numeric) maximum size of examined window of recent blocks\\n\"\n            \"        },\\n\"\n            \"        \\\"reject\\\": { ... }      (object) progress toward rejecting pre-softfork blocks (same fields as \\\"enforce\\\")\\n\"\n            \"     }, ...\\n\"\n            \"  ]\\n\"\n            \"}\\n\"\n\n            \"\\nExamples:\\n\" +\n            HelpExampleCli(\"getblockchaininfo\", \"\") + HelpExampleRpc(\"getblockchaininfo\", \"\"));\n\n    LOCK(cs_main);\n\n    UniValue obj(UniValue::VOBJ);\n    obj.push_back(Pair(\"chain\", Params().NetworkIDString()));\n    obj.push_back(Pair(\"blocks\", (int)chainActive.Height()));\n    obj.push_back(Pair(\"headers\", pindexBestHeader ? pindexBestHeader->nHeight : -1));\n    obj.push_back(Pair(\"bestblockhash\", chainActive.Tip()->GetBlockHash().GetHex()));\n    obj.push_back(Pair(\"difficulty\", (double)GetDifficulty()));\n    obj.push_back(Pair(\"verificationprogress\", Checkpoints::GuessVerificationProgress(chainActive.Tip())));\n    obj.push_back(Pair(\"chainwork\", chainActive.Tip()->nChainWork.GetHex()));\n    CBlockIndex* tip = chainActive.Tip();\n    UniValue softforks(UniValue::VARR);\n    softforks.push_back(SoftForkDesc(\"bip65\", 5, tip));\n    obj.push_back(Pair(\"softforks\",             softforks));\n    return obj;\n}\n\n\/** Comparison function for sorting the getchaintips heads.  *\/\nstruct CompareBlocksByHeight {\n    bool operator()(const CBlockIndex* a, const CBlockIndex* b) const\n    {\n        \/* Make sure that unequal blocks with the same height do not compare\n           equal. Use the pointers themselves to make a distinction. *\/\n\n        if (a->nHeight != b->nHeight)\n            return (a->nHeight > b->nHeight);\n\n        return a < b;\n    }\n};\n\nUniValue getchaintips(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() != 0)\n        throw runtime_error(\n            \"getchaintips\\n\"\n            \"Return information about all known tips in the block tree,\"\n            \" including the main chain as well as orphaned branches.\\n\"\n\n            \"\\nResult:\\n\"\n            \"[\\n\"\n            \"  {\\n\"\n            \"    \\\"height\\\": xxxx,         (numeric) height of the chain tip\\n\"\n            \"    \\\"hash\\\": \\\"xxxx\\\",         (string) block hash of the tip\\n\"\n            \"    \\\"branchlen\\\": 0          (numeric) zero for main chain\\n\"\n            \"    \\\"status\\\": \\\"active\\\"      (string) \\\"active\\\" for the main chain\\n\"\n            \"  },\\n\"\n            \"  {\\n\"\n            \"    \\\"height\\\": xxxx,\\n\"\n            \"    \\\"hash\\\": \\\"xxxx\\\",\\n\"\n            \"    \\\"branchlen\\\": 1          (numeric) length of branch connecting the tip to the main chain\\n\"\n            \"    \\\"status\\\": \\\"xxxx\\\"        (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\\n\"\n            \"  }\\n\"\n            \"]\\n\"\n\n            \"Possible values for status:\\n\"\n            \"1.  \\\"invalid\\\"               This branch contains at least one invalid block\\n\"\n            \"2.  \\\"headers-only\\\"          Not all blocks for this branch are available, but the headers are valid\\n\"\n            \"3.  \\\"valid-headers\\\"         All blocks are available for this branch, but they were never fully validated\\n\"\n            \"4.  \\\"valid-fork\\\"            This branch is not part of the active chain, but is fully validated\\n\"\n            \"5.  \\\"active\\\"                This is the tip of the active main chain, which is certainly valid\\n\"\n\n            \"\\nExamples:\\n\" +\n            HelpExampleCli(\"getchaintips\", \"\") + HelpExampleRpc(\"getchaintips\", \"\"));\n\n    LOCK(cs_main);\n\n    \/* Build up a list of chain tips.  We start with the list of all\n       known blocks, and successively remove blocks that appear as pprev\n       of another block.  *\/\n    std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;\n    BOOST_FOREACH (const PAIRTYPE(const uint256, CBlockIndex*) & item, mapBlockIndex)\n        setTips.insert(item.second);\n    BOOST_FOREACH (const PAIRTYPE(const uint256, CBlockIndex*) & item, mapBlockIndex) {\n        const CBlockIndex* pprev = item.second->pprev;\n        if (pprev)\n            setTips.erase(pprev);\n    }\n\n    \/\/ Always report the currently active tip.\n    setTips.insert(chainActive.Tip());\n\n    \/* Construct the output array.  *\/\n    UniValue res(UniValue::VARR);\n    BOOST_FOREACH (const CBlockIndex* block, setTips) {\n        UniValue obj(UniValue::VOBJ);\n        obj.push_back(Pair(\"height\", block->nHeight));\n        obj.push_back(Pair(\"hash\", block->phashBlock->GetHex()));\n\n        const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;\n        obj.push_back(Pair(\"branchlen\", branchLen));\n\n        string status;\n        if (chainActive.Contains(block)) {\n            \/\/ This block is part of the currently active chain.\n            status = \"active\";\n        } else if (block->nStatus & BLOCK_FAILED_MASK) {\n            \/\/ This block or one of its ancestors is invalid.\n            status = \"invalid\";\n        } else if (block->nChainTx == 0) {\n            \/\/ This block cannot be connected because full block data for it or one of its parents is missing.\n            status = \"headers-only\";\n        } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {\n            \/\/ This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.\n            status = \"valid-fork\";\n        } else if (block->IsValid(BLOCK_VALID_TREE)) {\n            \/\/ The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.\n            status = \"valid-headers\";\n        } else {\n            \/\/ No clue.\n            status = \"unknown\";\n        }\n        obj.push_back(Pair(\"status\", status));\n\n        res.push_back(obj);\n    }\n\n    return res;\n}\n\nUniValue getfeeinfo(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() != 1)\n        throw runtime_error(\n            \"getfeeinfo blocks\\n\"\n            \"\\nReturns details of transaction fees over the last n blocks.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. blocks     (int, required) the number of blocks to get transaction data from\\n\"\n\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"txcount\\\": xxxxx                (numeric) Current tx count\\n\"\n            \"  \\\"txbytes\\\": xxxxx                (numeric) Sum of all tx sizes\\n\"\n            \"  \\\"ttlfee\\\": xxxxx                 (numeric) Sum of all fees\\n\"\n            \"  \\\"feeperkb\\\": xxxxx               (numeric) Average fee per kb over the block range\\n\"\n            \"  \\\"rec_highpriorityfee_perkb\\\": xxxxx    (numeric) Recommended fee per kb to use for a high priority tx\\n\"\n            \"}\\n\"\n\n            \"\\nExamples:\\n\" +\n            HelpExampleCli(\"getfeeinfo\", \"5\") + HelpExampleRpc(\"getfeeinfo\", \"5\"));\n\n    LOCK(cs_main);\n\n    int nBlocks = params[0].get_int();\n    int nBestHeight = chainActive.Height();\n    int nStartHeight = nBestHeight - nBlocks;\n    if (nBlocks < 0 || nStartHeight <= 0)\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"invalid start height\");\n\n    CAmount nFees = 0;\n    int64_t nBytes = 0;\n    int64_t nTotal = 0;\n    for (int i = nStartHeight; i <= nBestHeight; i++) {\n        CBlockIndex* pindex = chainActive[i];\n        CBlock block;\n        if (!ReadBlockFromDisk(block, pindex))\n            throw JSONRPCError(RPC_DATABASE_ERROR, \"failed to read block from disk\");\n\n        CAmount nValueIn = 0;\n        CAmount nValueOut = 0;\n        for (const CTransaction& tx : block.vtx) {\n            if (tx.IsCoinBase() || tx.IsCoinStake())\n                continue;\n\n            for (unsigned int j = 0; j < tx.vin.size(); j++) {\n                COutPoint prevout = tx.vin[j].prevout;\n                CTransaction txPrev;\n                uint256 hashBlock;\n                if(!GetTransaction(prevout.hash, txPrev, hashBlock, true))\n                    throw JSONRPCError(RPC_DATABASE_ERROR, \"failed to read tx from disk\");\n                nValueIn += txPrev.vout[prevout.n].nValue;\n            }\n\n            for (unsigned int j = 0; j < tx.vout.size(); j++) {\n                nValueOut += tx.vout[j].nValue;\n            }\n\n            nFees += nValueIn - nValueOut;\n            nBytes += tx.GetSerializeSize(SER_NETWORK, CLIENT_VERSION);\n            nTotal++;\n        }\n\n        pindex = chainActive.Next(pindex);\n        if (!pindex)\n            break;\n    }\n\n    UniValue ret(UniValue::VOBJ);\n    CFeeRate nFeeRate = CFeeRate(nFees, nBytes);\n    ret.push_back(Pair(\"txcount\", (int64_t)nTotal));\n    ret.push_back(Pair(\"txbytes\", (int64_t)nBytes));\n    ret.push_back(Pair(\"ttlfee\", FormatMoney(nFees)));\n    ret.push_back(Pair(\"feeperkb\", FormatMoney(nFeeRate.GetFeePerK())));\n    ret.push_back(Pair(\"rec_highpriorityfee_perkb\", FormatMoney(nFeeRate.GetFeePerK() + 1000)));\n\n    return ret;\n}\n\nUniValue mempoolInfoToJSON()\n{\n    UniValue ret(UniValue::VOBJ);\n    ret.push_back(Pair(\"size\", (int64_t) mempool.size()));\n    ret.push_back(Pair(\"bytes\", (int64_t) mempool.GetTotalTxSize()));\n    \/\/ret.push_back(Pair(\"usage\", (int64_t) mempool.DynamicMemoryUsage()));\n\n    return ret;\n}\n\nUniValue getmempoolinfo(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() != 0)\n        throw runtime_error(\n            \"getmempoolinfo\\n\"\n            \"\\nReturns details on the active state of the TX memory pool.\\n\"\n\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"size\\\": xxxxx                (numeric) Current tx count\\n\"\n            \"  \\\"bytes\\\": xxxxx               (numeric) Sum of all tx sizes\\n\"\n            \"}\\n\"\n\n            \"\\nExamples:\\n\" +\n            HelpExampleCli(\"getmempoolinfo\", \"\") + HelpExampleRpc(\"getmempoolinfo\", \"\"));\n\n    return mempoolInfoToJSON();\n}\n\nUniValue invalidateblock(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() != 1)\n        throw runtime_error(\n            \"invalidateblock \\\"hash\\\"\\n\"\n            \"\\nPermanently marks a block as invalid, as if it violated a consensus rule.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. hash   (string, required) the hash of the block to mark as invalid\\n\"\n\n            \"\\nExamples:\\n\" +\n            HelpExampleCli(\"invalidateblock\", \"\\\"blockhash\\\"\") + HelpExampleRpc(\"invalidateblock\", \"\\\"blockhash\\\"\"));\n\n    std::string strHash = params[0].get_str();\n    uint256 hash(strHash);\n    CValidationState state;\n\n    {\n        LOCK(cs_main);\n        if (mapBlockIndex.count(hash) == 0)\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Block not found\");\n\n        CBlockIndex* pblockindex = mapBlockIndex[hash];\n        InvalidateBlock(state, pblockindex);\n    }\n\n    if (state.IsValid()) {\n        ActivateBestChain(state);\n    }\n\n    if (!state.IsValid()) {\n        throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());\n    }\n\n    return NullUniValue;\n}\n\nUniValue reconsiderblock(const UniValue& params, bool fHelp)\n{\n    if (fHelp || params.size() != 1)\n        throw runtime_error(\n            \"reconsiderblock \\\"hash\\\"\\n\"\n            \"\\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\\n\"\n            \"This can be used to undo the effects of invalidateblock.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. hash   (string, required) the hash of the block to reconsider\\n\"\n\n            \"\\nExamples:\\n\" +\n            HelpExampleCli(\"reconsiderblock\", \"\\\"blockhash\\\"\") + HelpExampleRpc(\"reconsiderblock\", \"\\\"blockhash\\\"\"));\n\n    std::string strHash = params[0].get_str();\n    uint256 hash(strHash);\n    CValidationState state;\n\n    {\n        LOCK(cs_main);\n        if (mapBlockIndex.count(hash) == 0)\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Block not found\");\n\n        CBlockIndex* pblockindex = mapBlockIndex[hash];\n        ReconsiderBlock(state, pblockindex);\n    }\n\n    if (state.IsValid()) {\n        ActivateBestChain(state);\n    }\n\n    if (!state.IsValid()) {\n        throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());\n    }\n\n    return NullUniValue;\n}\n","avg_line_length":40.1337016575,"max_line_length":145,"alphanum_fraction":0.5858594202,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1897,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"GraphAdj.h\"\n#include <iostream>\n#include <utility>\nusing namespace std;\n\nGraphAdj::GraphAdj(int size) {\n\tint i, j;\n\tV = size;\n\tA = 0;\n\n\tPos = new pair <int, int>[V];\n\tAdj = new bool* [V];\n\tCost = new int* [V];\n\n\t\/\/initialising adjancency matrix\n\tfor (i = 0; i < V; i++) {\n\t\tAdj[i] = new bool[V];\n\t\tfor (j = 0; j < V; j++) {\n\t\t\tAdj[i][j] = false;\n\t\t}\n\t}\n\t\/\/initialising cost matrix (-1 is undefined cost)\n\tfor (i = 0; i < V; i++) {\n\t\tCost[i] = new int[V];\n\t\tfor (j = 0; j < V; j++) {\n\t\t\tCost[i][j] = -1;\n\t\t}\n\t}\n\t\/\/inicial position for all vertices for a*\n\tfor (i = 0; i < V; i++) {\n\t\tPos[i].first = 0;\n\t\tPos[i].second = i;\n\t}\n}\n\nGraphAdj::~GraphAdj() {\n\tint i;\n\n\tfor (i = 0; i < V; i++) {\n\t\tdelete [] Adj[i];\n\t}\n\tdelete [] Adj;\n\n\tfor (i = 0; i < V; i++) {\n\t\tdelete[] Cost[i];\n\t}\n\tdelete[] Cost;\n\tdelete[] Pos;\n}\n\nvoid GraphAdj::InsertArc(int v, int w, int cost) {\n\tif (!Adj[v][w]){\n\t\tAdj[v][w] = true;\n\t\tA++;\n\t\tCost[v][w] = cost;\n\t}\n}\nvoid GraphAdj::RemoveArc(int v, int w) {\n\tif (Adj[v][w]) {\n\t\tAdj[v][w] = false;\n\t\tA--;\n\t\tCost[v][w] = -1;\n\t}\n}\n\nvoid GraphAdj::Draw() {\n\tint i, j;\n\tfor (i = 0; i < V; i++) {\n\t\tcout << i << \": \";\n\t\tfor (j = 0; j < V; j++) {\n\t\t\tif (Adj[i][j]) {\n\t\t\t\tcout << j << \"(\" << GetCost(i, j) << \") \";\n\t\t\t}\n\t\t}\n\t\tcout << endl;\n\t}\n}\nint GraphAdj::GetArc() {\n\treturn A;\n}\n\nbool GraphAdj::IsArc(int v, int w) {\n\treturn Adj[v][w];\n}\n\nint GraphAdj::GetV() {\n\treturn V;\n}\nint GraphAdj::GetInDegree(int v) {\n\tint i, indegree =0;\n\tfor (i = 0; i < V; i++) {\n\t\tif (Adj[i][v]) {\n\t\t\tindegree++;\n\t\t}\n\t}\n\treturn indegree;\n}\nint GraphAdj::GetOutDegree(int v) {\n\tint i, outdegree = 0;\n\tfor (i = 0; i < V; i++) {\n\t\tif (Adj[v][i]) {\n\t\t\toutdegree++;\n\t\t}\n\t}\n\treturn outdegree;\n}\nint GraphAdj::GetCost(int v, int w) {\n\treturn Cost[v][w];\n}\nvoid GraphAdj::SetPos(int v, int x, int y) {\n\tPos[v].first = x;\n\tPos[v].second = y;\n}\npair <int, int> GraphAdj::GetPos(int v) {\n\treturn Pos[v];\n}\n","avg_line_length":16.2136752137,"max_line_length":50,"alphanum_fraction":0.5139694254,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":20694,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":603.0,"content":"\/\/\r\n\/\/ Copyright (c) Microsoft. All rights reserved.\r\n\/\/ This code is licensed under the MIT License (MIT).\r\n\/\/ THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF\r\n\/\/ ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY\r\n\/\/ IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR\r\n\/\/ PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.\r\n\/\/\r\n\/\/ Developed by Minigraph\r\n\/\/\r\n\/\/ Author:  James Stanard \r\n\/\/\r\n\r\n\r\n#include \"pch.h\"\r\n#include \"TextRenderer.h\"\r\n#include \"GameInput.h\"\r\n#include \"Color.h\"\r\n#include \"GraphicsCore.h\"\r\n#include \"CommandContext.h\"\r\n#include \"GraphRenderer.h\"\r\n\r\nusing namespace std;\r\nusing namespace Math;\r\nusing namespace Graphics;\r\n\r\nnamespace EngineTuning\r\n{\r\n    \/\/ For delayed registration.  Some objects are constructed before we can add them to the graph (due\r\n    \/\/ to unreliable order of initialization.)\r\n    enum { kMaxUnregisteredTweaks = 1024 };\r\n    char s_UnregisteredPath[kMaxUnregisteredTweaks][128];\r\n    EngineVar* s_UnregisteredVariable[kMaxUnregisteredTweaks] = { nullptr };\r\n    int32_t s_UnregisteredCount = 0;\r\n\r\n    float s_ScrollOffset = 0.0f;\r\n    float s_ScrollTopTrigger = 1080.0f * 0.2f;\r\n    float s_ScrollBottomTrigger = 1080.0f * 0.8f;\r\n\r\n    \/\/ Internal functions\r\n    void AddToVariableGraph( const string& path, EngineVar& var );\r\n    void RegisterVariable( const string& path, EngineVar& var );\r\n\r\n    EngineVar* sm_SelectedVariable = nullptr;\r\n    bool sm_IsVisible = false;\r\n}\r\n\r\n\/\/ Not open to the public.  Groups are auto-created when a tweaker's path includes the group name.\r\nclass VariableGroup : public EngineVar\r\n{\r\npublic:\r\n    VariableGroup() : m_IsExpanded(false) {}\r\n\r\n    EngineVar* FindChild( const string& name )\r\n    {\r\n        auto iter = m_Children.find(name);\r\n        return iter == m_Children.end() ? nullptr : iter->second;\r\n    }\r\n     \r\n    void AddChild( const string& name, EngineVar& child )\r\n    {\r\n        m_Children[name] = &child;\r\n        child.m_GroupPtr = this;\r\n    }\r\n\r\n    void Display( TextContext& Text, float leftMargin, EngineVar* highlightedTweak );\r\n\r\n    void SaveToFile( FILE* file, int fileMargin );\r\n    void LoadSettingsFromFile( FILE* file );\r\n\r\n    EngineVar* NextVariable( EngineVar* currentVariable );\r\n    EngineVar* PrevVariable( EngineVar* currentVariable );\r\n    EngineVar* FirstVariable( void );\r\n    EngineVar* LastVariable( void );\r\n\r\n    bool IsExpanded( void ) const { return m_IsExpanded; }\r\n\r\n    virtual void Increment( void ) override { m_IsExpanded = true; }\r\n    virtual void Decrement( void ) override { m_IsExpanded = false; }\r\n    virtual void Bang( void ) override { m_IsExpanded = !m_IsExpanded; }\r\n\r\n    virtual void SetValue( FILE*, const std::string& ) override {}\r\n    \r\n    static VariableGroup sm_RootGroup;\r\n\r\nprivate:\r\n    bool m_IsExpanded;\r\n    std::map<string, EngineVar*> m_Children;\r\n};\r\n\r\nVariableGroup VariableGroup::sm_RootGroup;\r\n\r\n\/\/=====================================================================================================================\r\n\/\/ VariableGroup implementation\r\n\r\nvoid VariableGroup::Display( TextContext& Text, float leftMargin, EngineVar* highlightedTweak )\r\n{\r\n    Text.SetLeftMargin(leftMargin);\r\n    Text.SetCursorX(leftMargin);\r\n\r\n    for (auto iter = m_Children.begin(); iter != m_Children.end(); ++iter)\r\n    {\r\n        \r\n        if (iter->second == highlightedTweak)\r\n        {\r\n            Text.SetColor( Color(1.0f, 1.0f, 0.25f) );\r\n            float temp1 = Text.GetCursorY() - EngineTuning::s_ScrollBottomTrigger;\r\n            float temp2 = Text.GetCursorY() - EngineTuning::s_ScrollTopTrigger;\r\n            if (temp1 > 0.0f)\r\n            {\r\n                EngineTuning::s_ScrollOffset += 0.2f * temp1; \r\n            }\r\n            else if (temp2 < 0.0f)\r\n            {\r\n                EngineTuning::s_ScrollOffset = max(0.0f, EngineTuning::s_ScrollOffset + 0.2f * temp2);\r\n            }\r\n        }\r\n        else\r\n            Text.SetColor( Color(1.0f, 1.0f, 1.0f) );\r\n\r\n        VariableGroup* subGroup = dynamic_cast<VariableGroup*>(iter->second);\r\n        if (subGroup != nullptr)\r\n        {\r\n\r\n            if (subGroup->IsExpanded())\r\n            {\r\n                Text.DrawString(\"- \");\r\n            }\r\n            else\r\n            {\r\n                Text.DrawString(\"+ \");                \r\n            }\r\n            Text.DrawString(iter->first);\r\n            Text.DrawString(\"\/...\\n\");\r\n\r\n            if (subGroup->IsExpanded())\r\n            {\r\n                subGroup->Display(Text, leftMargin + 30.0f, highlightedTweak);\r\n                Text.SetLeftMargin(leftMargin);\r\n                Text.SetCursorX(leftMargin);\r\n            }\r\n            \r\n        }\r\n        else\r\n        {\r\n            \r\n            iter->second->DisplayValue(Text);\r\n            Text.SetCursorX(leftMargin + 200.0f);\r\n            Text.DrawString(iter->first);\r\n            Text.NewLine();\r\n        }\r\n        \r\n    }\r\n}\r\n\r\nvoid VariableGroup::SaveToFile( FILE* file, int fileMargin )\r\n{\r\n    for (auto iter = m_Children.begin(); iter != m_Children.end(); ++iter)\r\n    {\r\n        const char* buffer = (iter->first).c_str();\r\n\r\n        VariableGroup* subGroup = dynamic_cast<VariableGroup*>(iter->second);\r\n        if (subGroup != nullptr)\r\n        {        \r\n            fprintf(file, \"%*c + %s ...\\r\\n\", fileMargin, ' ', buffer);\r\n            subGroup->SaveToFile(file, fileMargin + 5);\r\n        }\r\n        else if (dynamic_cast<CallbackTrigger*>(iter->second) == nullptr)\r\n        {\r\n            fprintf(file, \"%*c %s:  %s\\r\\n\", fileMargin, ' ', buffer, iter->second->ToString().c_str());\r\n        }        \r\n    }\r\n}\r\n\r\nvoid VariableGroup::LoadSettingsFromFile( FILE* file )\r\n{\r\n    for (auto iter = m_Children.begin(); iter != m_Children.end(); ++iter)\r\n    {\r\n        VariableGroup* subGroup = dynamic_cast<VariableGroup*>(iter->second);\r\n        if (subGroup != nullptr)\r\n        {\r\n            char skippedLines[100];\r\n            fscanf_s(file, \"%*s %[^\\n]\", skippedLines, (int)_countof(skippedLines));\r\n            subGroup->LoadSettingsFromFile(file);\r\n        }\r\n        else\r\n        {    \r\n            iter->second->SetValue(file, iter->first);\r\n        }\r\n    }\r\n}\r\n\r\nEngineVar* VariableGroup::FirstVariable( void )\r\n{\r\n    return m_Children.size() == 0 ? nullptr : m_Children.begin()->second;\r\n}\r\n\r\nEngineVar* VariableGroup::LastVariable( void )\r\n{\r\n    if (m_Children.size() == 0)\r\n        return this;\r\n\r\n    auto LastVariable = m_Children.end();\r\n    --LastVariable;\r\n\r\n    VariableGroup* isGroup = dynamic_cast<VariableGroup*>(LastVariable->second);\r\n    if (isGroup && isGroup->IsExpanded())\r\n        return isGroup->LastVariable();\r\n\r\n    return LastVariable->second;\r\n}\r\n\r\nEngineVar* VariableGroup::NextVariable( EngineVar* curVar )\r\n{\r\n    auto iter = m_Children.begin();\r\n    for (; iter != m_Children.end(); ++iter)\r\n    {\r\n        if (curVar == iter->second)\r\n            break;\r\n    }\r\n\r\n    ASSERT( iter != m_Children.end(), \"Did not find engine variable in its designated group\" );\r\n\r\n    auto nextIter = iter;\r\n    ++nextIter;\r\n\r\n    if (nextIter == m_Children.end())\r\n        return m_GroupPtr ? m_GroupPtr->NextVariable(this) : nullptr;\r\n    else\r\n        return nextIter->second;\r\n}\r\n\r\nEngineVar* VariableGroup::PrevVariable( EngineVar* curVar )\r\n{\r\n    auto iter = m_Children.begin();\r\n    for (; iter != m_Children.end(); ++iter)\r\n    {\r\n        if (curVar == iter->second)\r\n            break;\r\n    }\r\n\r\n    ASSERT( iter != m_Children.end(), \"Did not find engine variable in its designated group\" );\r\n\r\n    if (iter == m_Children.begin())\r\n        return this;\r\n\r\n    auto prevIter = iter;\r\n    --prevIter;\r\n\r\n    VariableGroup* isGroup = dynamic_cast<VariableGroup*>(prevIter->second);\r\n    if (isGroup && isGroup->IsExpanded())\r\n        return isGroup->LastVariable();\r\n\r\n    return prevIter->second;\r\n}\r\n\r\n\/\/=====================================================================================================================\r\n\/\/ EngineVar implementations\r\n\r\nEngineVar::EngineVar( void ) : m_GroupPtr(nullptr)\r\n{\r\n}\r\n\r\nEngineVar::EngineVar( const std::string& path ) : m_GroupPtr(nullptr)\r\n{\r\n    EngineTuning::RegisterVariable(path, *this);\r\n}\r\n\r\n\r\nEngineVar* EngineVar::NextVar( void )\r\n{\r\n    EngineVar* next = nullptr;\r\n    VariableGroup* isGroup = dynamic_cast<VariableGroup*>(this);\r\n    if (isGroup != nullptr && isGroup->IsExpanded())\r\n        next = isGroup->FirstVariable();\r\n\r\n    if (next == nullptr)\r\n        next = m_GroupPtr->NextVariable(this);\r\n\r\n    return next != nullptr ? next : this;\r\n}\r\n\r\nEngineVar* EngineVar::PrevVar( void )\r\n{\r\n    EngineVar* prev = m_GroupPtr->PrevVariable(this);\r\n    if (prev != nullptr && prev != m_GroupPtr)\r\n    {\r\n        VariableGroup* isGroup = dynamic_cast<VariableGroup*>(prev);\r\n        if (isGroup != nullptr && isGroup->IsExpanded())\r\n            prev = isGroup->LastVariable();\r\n    }\r\n    return prev != nullptr ? prev : this;\r\n}\r\n\r\nBoolVar::BoolVar( const std::string& path, bool val )\r\n    : EngineVar(path)\r\n{\r\n    m_Flag = val;\r\n}\r\n\r\nvoid BoolVar::DisplayValue( TextContext& Text ) const\r\n{\r\n    Text.DrawFormattedString(\"[%c]\", m_Flag ? 'X' : '-');\r\n}\r\n\r\nstd::string BoolVar::ToString( void ) const\r\n{\r\n    return m_Flag ? \"on\" : \"off\";\r\n} \r\n\r\nvoid BoolVar::SetValue(FILE* file, const std::string& setting)\r\n{    \r\n    std::string pattern = \"\\n \" + setting + \": %s\";\r\n    char valstr[6];\r\n\r\n    \/\/ Search through the file for an entry that matches this setting's name\r\n    fscanf_s(file, pattern.c_str(), valstr, _countof(valstr));\r\n\r\n    \/\/ Look for one of the many affirmations\r\n    m_Flag = (\r\n        0 == _stricmp(valstr, \"1\") ||\r\n        0 == _stricmp(valstr, \"on\") ||\r\n        0 == _stricmp(valstr, \"yes\") ||\r\n        0 == _stricmp(valstr, \"true\") );\r\n}\r\n\r\nNumVar::NumVar( const std::string& path, float val, float minVal, float maxVal, float stepSize )\r\n    : EngineVar(path)\r\n{\r\n    ASSERT(minVal <= maxVal);\r\n    m_MinValue = minVal;\r\n    m_MaxValue = maxVal;\r\n    m_Value = Clamp(val);\r\n    m_StepSize = stepSize;\r\n}\r\n\r\nvoid NumVar::DisplayValue( TextContext& Text ) const\r\n{\r\n    Text.DrawFormattedString(\"%-11f\", m_Value);\r\n}\r\n\r\nstd::string NumVar::ToString( void ) const\r\n{\r\n    char buf[128];\r\n    sprintf_s(buf, \"%f\", m_Value);\r\n    return buf;\r\n} \r\n\r\nvoid NumVar::SetValue(FILE* file, const std::string& setting) \r\n{\r\n    std::string scanString = \"\\n\" + setting + \": %f\";\r\n    float valueRead;\r\n    \r\n    \/\/If we haven't read correctly, just keep m_Value at default value\r\n    if (fscanf_s(file, scanString.c_str(), &valueRead))\r\n        *this = valueRead; \r\n}\r\n\r\n#if _MSC_VER < 1800\r\n__forceinline float log2( float x ) { return log(x) \/ log(2.0f); }\r\n__forceinline float exp2( float x ) { return pow(2.0f, x); }\r\n#endif\r\n\r\nExpVar::ExpVar( const std::string& path, float val, float minExp, float maxExp, float expStepSize )\r\n    : NumVar(path, log2f(val), minExp, maxExp, expStepSize)\r\n{\r\n}\r\n\r\nExpVar& ExpVar::operator=( float val )\r\n{\r\n    m_Value = Clamp(log2f(val));\r\n    return *this;\r\n}\r\n\r\nExpVar::operator float() const\r\n{\r\n    return exp2f(m_Value);\r\n}\r\n\r\nvoid ExpVar::DisplayValue( TextContext& Text ) const\r\n{\r\n    Text.DrawFormattedString(\"%-11f\", (float)*this);\r\n}\r\n\r\nstd::string ExpVar::ToString( void ) const\r\n{\r\n    char buf[128];\r\n    sprintf_s(buf, \"%f\", (float)*this);\r\n    return buf;\r\n} \r\n\r\nvoid ExpVar::SetValue(FILE* file, const std::string& setting) \r\n{\r\n    std::string scanString = \"\\n\" + setting + \": %f\";\r\n    float valueRead;\r\n    \r\n    \/\/If we haven't read correctly, just keep m_Value at default value\r\n    if (fscanf_s(file, scanString.c_str(), &valueRead))\r\n        *this = valueRead;\r\n}\r\n\r\nIntVar::IntVar( const std::string& path, int32_t val, int32_t minVal, int32_t maxVal, int32_t stepSize )\r\n    : EngineVar(path)\r\n{\r\n    ASSERT(minVal <= maxVal);\r\n    m_MinValue = minVal;\r\n    m_MaxValue = maxVal;\r\n    m_Value = Clamp(val);\r\n    m_StepSize = stepSize;\r\n}\r\n\r\nvoid IntVar::DisplayValue( TextContext& Text ) const\r\n{\r\n    Text.DrawFormattedString(\"%-11d\", m_Value);\r\n}\r\n\r\nstd::string IntVar::ToString( void ) const\r\n{\r\n    char buf[128];\r\n    sprintf_s(buf, \"%d\", m_Value);\r\n    return buf;\r\n} \r\n\r\nvoid IntVar::SetValue(FILE* file, const std::string& setting) \r\n{\r\n    std::string scanString = \"\\n\" + setting + \": %d\";\r\n    int32_t valueRead;\r\n    \r\n    if (fscanf_s(file, scanString.c_str(), &valueRead))\r\n        *this = valueRead;\r\n}\r\n\r\n\r\nEnumVar::EnumVar( const std::string& path, int32_t initialVal, int32_t listLength, const char** listLabels )\r\n    : EngineVar(path)\r\n{\r\n    ASSERT(listLength > 0);\r\n    m_EnumLength = listLength;\r\n    m_EnumLabels = listLabels;\r\n    m_Value = Clamp(initialVal);\r\n}\r\n\r\nvoid EnumVar::DisplayValue( TextContext& Text ) const\r\n{\r\n    Text.DrawString(m_EnumLabels[m_Value]);\r\n}\r\n\r\nstd::string EnumVar::ToString( void ) const\r\n{\r\n    return m_EnumLabels[m_Value];\r\n} \r\n\r\nvoid EnumVar::SetValue(FILE* file, const std::string& setting) \r\n{\r\n    std::string scanString = \"\\n\" + setting + \": %[^\\n]\";\r\n    char valueRead[14];\r\n        \r\n    if (fscanf_s(file, scanString.c_str(), valueRead, _countof(valueRead)) == 1)\r\n    {\r\n        std::string valueReadStr = valueRead;\r\n        valueReadStr = valueReadStr.substr(0, valueReadStr.length() - 1);\r\n\r\n        \/\/if we don't find the string, then leave m_EnumLabes[m_Value] as default\r\n        for(int32_t i = 0; i < m_EnumLength; ++i)\r\n        {\r\n            if (m_EnumLabels[i] == valueReadStr)\r\n            {\r\n                m_Value = i;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n}\r\n\r\nCallbackTrigger::CallbackTrigger( const std::string& path, std::function<void (void*)> callback, void* args )\r\n    : EngineVar(path)\r\n{\r\n    m_Callback = callback;\r\n    m_Arguments = args;\r\n    m_BangDisplay = 0;\r\n}\r\n\r\nvoid CallbackTrigger::DisplayValue( TextContext& Text ) const\r\n{\r\n    static const char s_animation[] = { '-', '\\\\', '|', '\/' };\r\n    Text.DrawFormattedString(\"[%c]\", s_animation[(m_BangDisplay >> 3) & 3]);\r\n\r\n    if (m_BangDisplay > 0)\r\n        --m_BangDisplay;\r\n}\r\n\r\nvoid CallbackTrigger::SetValue(FILE* file, const std::string& setting) \r\n{\r\n    \/\/Skip over setting without reading anything\r\n    std::string scanString = \"\\n\" + setting + \": %[^\\n]\";\r\n    char skippedLines[100];\r\n    fscanf_s(file, scanString.c_str(), skippedLines, _countof(skippedLines));\r\n}\r\n\r\n\/\/=====================================================================================================================\r\n\/\/ EngineTuning namespace methods\r\n\r\nvoid EngineTuning::Initialize( void )\r\n{\r\n\r\n    for (int32_t i = 0; i < s_UnregisteredCount; ++i)\r\n    {\r\n        ASSERT(strlen(s_UnregisteredPath[i]) > 0, \"Register = %d\\n\", i);\r\n        ASSERT(s_UnregisteredVariable[i] != nullptr);\r\n        AddToVariableGraph(s_UnregisteredPath[i], *s_UnregisteredVariable[i]);\r\n    }\r\n    s_UnregisteredCount = -1;\r\n\r\n}\r\n\r\nvoid HandleDigitalButtonPress( GameInput::DigitalInput button, float timeDelta, std::function<void ()> action )\r\n{\r\n    if (!GameInput::IsPressed(button))\r\n        return;\r\n\r\n    float durationHeld = GameInput::GetDurationPressed(button);\r\n\r\n    \/\/ Tick on the first press\r\n    if (durationHeld == 0.0f)\r\n    {\r\n        action();\r\n        return;\r\n    }\r\n\r\n    \/\/ After ward, tick at fixed intervals\r\n    float oldDuration = durationHeld - timeDelta;\r\n\r\n    \/\/ Before 2 seconds, use slow scale (200ms\/tick), afterward use fast scale (50ms\/tick).\r\n    float timeStretch = durationHeld < 2.0f ? 5.0f : 20.0f;\r\n\r\n    if (Floor(durationHeld * timeStretch) > Floor(oldDuration * timeStretch))\r\n        action();\r\n}\r\n\r\nvoid EngineTuning::Update( float frameTime )\r\n{\r\n    if (GameInput::IsFirstPressed( GameInput::kBackButton )\r\n        || GameInput::IsFirstPressed( GameInput::kKey_back ))\r\n        sm_IsVisible = !sm_IsVisible;\r\n\r\n    if (!sm_IsVisible)\r\n        return;\r\n\r\n    if (sm_SelectedVariable == nullptr || sm_SelectedVariable == &VariableGroup::sm_RootGroup)\r\n        sm_SelectedVariable = VariableGroup::sm_RootGroup.FirstVariable();\r\n\r\n    if (sm_SelectedVariable == nullptr)\r\n        return;\r\n\r\n    \/\/ Detect a DPad button press\r\n    HandleDigitalButtonPress(GameInput::kDPadRight, frameTime, []{ sm_SelectedVariable->Increment(); } );\r\n    HandleDigitalButtonPress(GameInput::kDPadLeft,    frameTime, []{ sm_SelectedVariable->Decrement(); } );\r\n    HandleDigitalButtonPress(GameInput::kDPadDown,    frameTime, []{ sm_SelectedVariable = sm_SelectedVariable->NextVar(); } );\r\n    HandleDigitalButtonPress(GameInput::kDPadUp,    frameTime, []{ sm_SelectedVariable = sm_SelectedVariable->PrevVar(); } );\r\n\r\n    HandleDigitalButtonPress(GameInput::kKey_right, frameTime, []{ sm_SelectedVariable->Increment(); } );\r\n    HandleDigitalButtonPress(GameInput::kKey_left,    frameTime, []{ sm_SelectedVariable->Decrement(); } );\r\n    HandleDigitalButtonPress(GameInput::kKey_down,    frameTime, []{ sm_SelectedVariable = sm_SelectedVariable->NextVar(); } );\r\n    HandleDigitalButtonPress(GameInput::kKey_up,    frameTime, []{ sm_SelectedVariable = sm_SelectedVariable->PrevVar(); } );\r\n\r\n    if (GameInput::IsFirstPressed( GameInput::kAButton )\r\n        || GameInput::IsFirstPressed( GameInput::kKey_return ))\r\n    {\r\n        sm_SelectedVariable->Bang();\r\n    }\r\n}\r\n\r\nvoid StartSave(void*)\r\n{\r\n    FILE* settingsFile;\r\n    fopen_s(&settingsFile, \"engineTuning.txt\", \"wb\");\r\n    if (settingsFile != nullptr)\r\n    {\r\n        VariableGroup::sm_RootGroup.SaveToFile(settingsFile, 2 );\r\n        fclose(settingsFile);\r\n    }\r\n}\r\nstd::function<void(void*)> StartSaveFunc = StartSave;\r\nstatic CallbackTrigger Save(\"Save Settings\", StartSaveFunc, nullptr); \r\n\r\nvoid StartLoad(void*)\r\n{\r\n    FILE* settingsFile;\r\n    fopen_s(&settingsFile, \"engineTuning.txt\", \"rb\");\r\n    if (settingsFile != nullptr)\r\n    {\r\n        VariableGroup::sm_RootGroup.LoadSettingsFromFile(settingsFile);\r\n        fclose(settingsFile);\r\n    }\r\n}\r\nstd::function<void(void*)> StartLoadFunc = StartLoad;\r\nstatic CallbackTrigger Load(\"Load Settings\", StartLoadFunc, nullptr); \r\n\r\n\r\nvoid EngineTuning::Display( GraphicsContext& Context, float x, float y, float w, float h )\r\n{\r\n    GraphRenderer::RenderGraphs(Context, GraphRenderer::GraphType::Profile);\r\n\r\n    TextContext Text(Context);\r\n    Text.Begin();\r\n\r\n    EngineProfiling::DisplayFrameRate(Text);\r\n\r\n    Text.ResetCursor( x, y );\r\n\r\n    if (!sm_IsVisible)\r\n    {\r\n        EngineProfiling::Display(Text, x, y, w, h);\r\n        return;\r\n    }\r\n\r\n    s_ScrollTopTrigger = y + h * 0.2f;\r\n    s_ScrollBottomTrigger = y + h * 0.8f;\r\n\r\n    float hScale = g_DisplayWidth \/ 1920.0f;\r\n    float vScale = g_DisplayHeight \/ 1080.0f;\r\n\r\n    Context.SetScissor((uint32_t)Floor(x * hScale), (uint32_t)Floor(y * vScale), \r\n        (uint32_t)Ceiling((x + w) * hScale), (uint32_t)Ceiling((y + h) * vScale));\r\n\r\n    Text.ResetCursor(x, y - s_ScrollOffset );\r\n    Text.SetColor( Color(0.5f, 1.0f, 1.0f) );\r\n    Text.DrawString(\"Engine Tuning\\n\");\r\n    Text.SetTextSize(20.0f);\r\n\r\n    VariableGroup::sm_RootGroup.Display( Text, x, sm_SelectedVariable );\r\n    \r\n    EngineProfiling::DisplayPerfGraph(Context);\r\n\r\n    Text.End();\r\n    Context.SetScissor(0, 0, g_DisplayWidth, g_DisplayHeight);\r\n}\r\n\r\nvoid EngineTuning::AddToVariableGraph( const string& path, EngineVar& var )\r\n{\r\n    vector<string> separatedPath;\r\n    string leafName;\r\n    size_t start = 0, end = 0;\r\n\r\n    while (1)\r\n    {\r\n        end = path.find('\/', start);\r\n        if (end == string::npos)\r\n        {\r\n            leafName = path.substr(start);\r\n            break;\r\n        }\r\n        else\r\n        {\r\n            separatedPath.push_back(path.substr(start, end - start));\r\n            start = end + 1;\r\n        }\r\n    }\r\n\r\n    VariableGroup* group = &VariableGroup::sm_RootGroup;\r\n\r\n    for (auto iter = separatedPath.begin(); iter != separatedPath.end(); ++iter )\r\n    {\r\n        VariableGroup* nextGroup;\r\n        EngineVar* node = group->FindChild(*iter);\r\n        if (node == nullptr)\r\n        {\r\n            nextGroup = new VariableGroup();\r\n            group->AddChild(*iter, *nextGroup);\r\n            group = nextGroup;\r\n        }\r\n        else\r\n        {\r\n            nextGroup = dynamic_cast<VariableGroup*>(node);\r\n            ASSERT(nextGroup != nullptr, \"Attempted to trash the tweak graph\");\r\n            group = nextGroup;\r\n        }\r\n    }\r\n\r\n    group->AddChild(leafName, var);\r\n}\r\n\r\nvoid EngineTuning::RegisterVariable( const std::string& path, EngineVar& var )\r\n{\r\n    if (s_UnregisteredCount >= 0)\r\n    {\r\n        int32_t Idx = s_UnregisteredCount++;\r\n        strcpy_s(s_UnregisteredPath[Idx], path.c_str());\r\n        s_UnregisteredVariable[Idx] = &var;\r\n    }\r\n    else\r\n    {\r\n        AddToVariableGraph( path, var );\r\n    }\r\n}\r\n\r\nbool EngineTuning::IsFocused( void )\r\n{\r\n    return sm_IsVisible;\r\n}\r\n","avg_line_length":29.4786324786,"max_line_length":128,"alphanum_fraction":0.5976128346,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1131,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"include\/rdata.h\"\n#include<include\/rdata_accessors.h>\n\nvoid freeReturnData(ReturnData *rdata) {\n    if(tsdata) delete[] tsdata;\n    if(xdotdata) delete[] xdotdata;\n    if(dxdotdpdata) delete[] dxdotdpdata;\n    if(dydxdata) delete[] dydxdata;\n    if(dydpdata) delete[] dydpdata;\n    if(Jdata) delete[] Jdata;\n    if(zdata) delete[] zdata;\n    if(sigmazdata) delete[] sigmazdata;\n    if(szdata) delete[] szdata;\n    if(ssigmazdata) delete[] ssigmazdata;\n    if(srzdata) delete[] srzdata;\n    if(s2rzdata) delete[] s2rzdata;\n    if(xdata) delete[] xdata;\n    if(sxdata) delete[] sxdata;\n    if(ydata) delete[] ydata;\n    if(sigmaydata) delete[] sigmaydata;\n    if(sydata) delete[] sydata;\n    if(ssigmaydata) delete[] ssigmaydata;\n    if(numstepsdata) delete[] numstepsdata;\n    if(numrhsevalsdata) delete[] numrhsevalsdata;\n    if(orderdata) delete[] orderdata;\n    if(numstepsSdata) delete[] numstepsSdata;\n    if(numrhsevalsSdata) delete[] numrhsevalsSdata;\n    if(llhdata) delete[] llhdata;\n    if(sllhdata) delete[] sllhdata;\n    if(s2llhdata) delete[] s2llhdata;\n    if(chi2data) delete[] chi2data;\n    delete rdata;\n}\n","avg_line_length":33.2647058824,"max_line_length":51,"alphanum_fraction":0.6861184792,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":421,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/****************************************************************************\n**\n** Copyright (C) 2008-2010 C.B. Barber. All rights reserved.\n**\n****************************************************************************\/\n\n#\/\/! QhullEvent -- A recorded event in a circular buffer\n\n#include \"QhullEvent.h\"\n\n#ifdef _MSC_VER  \/\/ Microsoft Visual C++ -- warning level 4\n#endif\n\nnamespace orgQhull {\n\n\n}\/\/namespace orgQhull\n\n","avg_line_length":22.1578947368,"max_line_length":77,"alphanum_fraction":0.4346793349,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5569,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/\/ Copyright (c) 2018, The AZUR Developers, The TURTLECOIN Developers\n\/\/ \n\/\/ Please see the included LICENSE file for more information.\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <zedwallet++\/Menu.h>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <config\/WalletConfig.h>\n\n#include <zedwallet++\/CommandDispatcher.h>\n#include <zedwallet++\/Commands.h>\n#include <zedwallet++\/GetInput.h>\n\nstd::tuple<bool, bool, std::shared_ptr<WalletBackend>> selectionScreen(const Config &config)\n{\n    while (true)\n    {\n        \/* Get the users action *\/\n        std::string launchCommand = getAction(config);\n\n        \/* User wants to exit *\/\n        if (launchCommand == \"exit\")\n        {\n            const bool exit(true), sync(false);\n\n            return {exit, sync, nullptr};\n        }\n\n        \/* Handle the user input *\/\n        std::shared_ptr<WalletBackend> walletBackend = handleLaunchCommand(\n            launchCommand, config\n        );\n\n        \/* Action failed, for example wallet file is corrupted. *\/\n        if (walletBackend == nullptr)\n        {\n            std::cout << InformationMsg(\"Returning to selection screen...\")\n                      << std::endl;\n\n            continue;\n        }\n\n        \/* Node is down, user wants to exit *\/\n        if (!checkNodeStatus(walletBackend))\n        {\n            const bool exit(true), sync(false);\n\n            return {exit, sync, nullptr};\n        }\n\n        \/* If we're creating a wallet, don't print the lengthy sync process *\/\n        if (launchCommand == \"create\")\n        {\n            std::stringstream str;\n\n            str << std::endl\n                << \"Your wallet is syncing with the network in the background.\"\n                << std::endl\n                << \"Until this is completed new transactions might not show \"\n                << \"up.\" << std::endl\n                << \"Use the status command to check the progress.\"\n                << std::endl;\n\n            std::cout << InformationMsg(str.str());\n\n            const bool exit(false), sync(false);\n\n            return {exit, sync, walletBackend};\n        }\n\n        const bool exit(false), sync(true);\n    \n        \/* Return the wallet info *\/\n        return {exit, sync, walletBackend};\n    }\n}\n\nbool checkNodeStatus(const std::shared_ptr<WalletBackend> walletBackend)\n{\n    while (true)\n    {\n        const auto [walletBlockCount, localDaemonBlockCount, networkBlockCount]\n            = walletBackend->getSyncStatus();\n\n        \/* Daemon is online *\/\n        if (networkBlockCount != 0 || localDaemonBlockCount != 0)\n        {\n            break;\n        }\n\n        std::stringstream msg;\n\n        msg << \"It looks like \" << WalletConfig::daemonName << \" isn't open!\\n\\n\"\n            << \"Ensure \" << WalletConfig::daemonName\n            << \" is open and has finished syncing. \"\n            << \"(It will often not respond when syncing)\\n\"\n            << \"If it's still not working, try restarting \"\n            << WalletConfig::daemonName << \" (or try a different remote node).\"\n            << \"\\nThe daemon sometimes gets stuck.\\nAlternatively, perhaps \"\n            << WalletConfig::daemonName << \" can't communicate with any peers.\"\n            << \"\\n\\nThe wallet can't function fully until it can communicate with \"\n            << \"the network.\";\n\n        std::cout << WarningMsg(msg.str()) << std::endl;\n\n        \/* Print the commands *\/\n        printCommands(nodeDownCommands());\n\n        \/* See what the user wants to do *\/\n        std::string command = parseCommand(\n            nodeDownCommands(), nodeDownCommands(),\n            \"What would you like to do?: \"\n        );\n\n        \/* If they want to try again, check the node height again *\/\n        if (command == \"try_again\")\n        {\n            continue;\n        }\n        \/* If they want to exit, exit *\/\n        else if (command == \"exit\")\n        {\n            return false;\n        }\n        \/* If they want to continue, proceed to the menu screen *\/\n        else if (command == \"continue\")\n        {\n            return true;\n        }\n        \/* User wants to try a different node *\/\n        else if (command == \"swap_node\")\n        {\n            const auto [host, port] = getDaemonAddress();\n\n            std::cout << InformationMsg(\"\\nSwapping node, this may take some time...\\n\");\n\n            walletBackend->swapNode(host, port);\n\n            std::cout << SuccessMsg(\"Node swap complete.\\n\\n\");\n\n            continue;\n        }\n    }\n\n    return true;\n}\n\nstd::string getAction(const Config &config)\n{\n    if (config.walletGiven || config.passGiven)\n    {\n        return \"open\";\n    }\n\n    printCommands(startupCommands());\n\n    return parseCommand(\n        startupCommands(), startupCommands(), \"What would you like to do?: \"\n    );\n}\n\nvoid mainLoop(\n    const std::shared_ptr<WalletBackend> walletBackend,\n    const std::shared_ptr<std::mutex> mutex)\n{\n    if (walletBackend->isViewWallet())\n    {\n        printCommands(basicViewWalletCommands());\n    }\n    else\n    {\n        printCommands(basicCommands());\n    }\n    \n    while (true)\n    {\n        std::string command;\n\n        if (walletBackend->isViewWallet())\n        {\n            command = parseCommand(\n                basicViewWalletCommands(), allViewWalletCommands(),\n                getPrompt(walletBackend)\n            );\n        }\n        else\n        {\n            command = parseCommand(\n                basicCommands(), allCommands(), getPrompt(walletBackend)\n            );\n        }\n\n        \/* User exited *\/\n        if (!handleCommand(command, walletBackend, mutex))\n        {\n            return;\n        }\n    }\n}\n","avg_line_length":27.7064676617,"max_line_length":92,"alphanum_fraction":0.5392350512,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1324,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/ sphere.cpp\n\/\/\n\/\/ Copyright (C) 2003, 2004 Jason Bevins\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU Lesser General Public License as published by\n\/\/ the Free Software Foundation; either version 2.1 of the License, or (at\n\/\/ your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful, but WITHOUT\n\/\/ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n\/\/ FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public\n\/\/ License (COPYING.txt) for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this library; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\/\/\n\/\/ The developer's email is jlbezigvins@gmzigail.com (for great email, take\n\/\/ off every 'zig'.)\n\/\/\n\n#include \"sphere.h\"\n\n#include \"..\/latlon.h\"\n\nusing namespace noise;\nusing namespace noise::model;\n\nSphere::Sphere()\n    : m_pModule(NULL)\n{\n}\n\nSphere::Sphere(const module::ModuleBase& module)\n    : m_pModule(&module)\n{\n}\n\ndouble Sphere::GetValue(double lat, double lon) const\n{\n    assert(m_pModule != NULL);\n\n    double x, y, z;\n    LatLonToXYZ(lat, lon, x, y, z);\n    return m_pModule->getValue(x, y, z);\n}\n","avg_line_length":27.5833333333,"max_line_length":78,"alphanum_fraction":0.7114803625,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1190,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2793.0,"content":"\/\/===------------------------ optional.cpp --------------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"optional\"\n\nnamespace std\n{\n\nbad_optional_access::~bad_optional_access() _NOEXCEPT = default;\n\nconst char* bad_optional_access::what() const _NOEXCEPT {\n  return \"bad_optional_access\";\n  }\n\n} \/\/ std\n\n\n#include <experimental\/__config>\n\n\/\/  Preserve std::experimental::bad_optional_access for ABI compatibility\n\/\/  Even though it no longer exists in a header file\n_LIBCPP_BEGIN_NAMESPACE_EXPERIMENTAL\n\nclass _LIBCPP_EXCEPTION_ABI _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS bad_optional_access\n    : public std::logic_error\n{\npublic:\n\tbad_optional_access() : std::logic_error(\"Bad optional Access\") {}\n\n\/\/\tGet the key function ~bad_optional_access() into the dylib\n    virtual ~bad_optional_access() _NOEXCEPT;\n};\n\nbad_optional_access::~bad_optional_access() _NOEXCEPT = default;\n\n_LIBCPP_END_NAMESPACE_EXPERIMENTAL\n","avg_line_length":28.3333333333,"max_line_length":88,"alphanum_fraction":0.6848739496,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11848,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/**\n *  @file\n *  @copyright defined in eos\/LICENSE.txt\n *\/\n#include \"actx.system.hpp\"\n\n#include <eosiolib\/eosio.hpp>\n#include <eosiolib\/crypto.h>\n#include <eosiolib\/print.hpp>\n#include <eosiolib\/datastream.hpp>\n#include <eosiolib\/serialize.hpp>\n#include <eosiolib\/multi_index.hpp>\n#include <eosiolib\/privileged.hpp>\n#include <eosiolib\/singleton.hpp>\n#include <eosiolib\/transaction.hpp>\n#include <actx.token\/actx.token.hpp>\n\n#include <algorithm>\n#include <cmath>\n\nnamespace eosiosystem {\n   using eosio::indexed_by;\n   using eosio::const_mem_fun;\n   using eosio::bytes;\n   using eosio::print;\n   using eosio::singleton;\n   using eosio::transaction;\n\n   \/**\n    *  This method will create a producer_config and producer_info object for 'producer'\n    *\n    *  @pre producer is not already registered\n    *  @pre producer to register is an account\n    *  @pre authority of producer to register\n    *\n    *\/\n   void system_contract::regproducer( const account_name producer, const eosio::public_key& producer_key, const std::string& url, uint16_t location ) {\n      eosio_assert( url.size() < 512, \"url too long\" );\n      eosio_assert( producer_key != eosio::public_key(), \"public key should not be the default value\" );\n      require_auth( producer );\n\n      auto prod = _producers.find( producer );\n\n      if ( prod != _producers.end() ) {\n         _producers.modify( prod, producer, [&]( producer_info& info ){\n               info.producer_key = producer_key;\n               info.is_active    = true;\n               info.url          = url;\n               info.location     = location;\n            });\n      } else {\n         _producers.emplace( producer, [&]( producer_info& info ){\n               info.owner         = producer;\n               info.total_votes   = 0;\n               info.producer_key  = producer_key;\n               info.is_active     = true;\n               info.url           = url;\n               info.location      = location;\n         });\n      }\n   }\n\n   void system_contract::unregprod( const account_name producer ) {\n      require_auth( producer );\n\n      const auto& prod = _producers.get( producer, \"producer not found\" );\n\n      _producers.modify( prod, 0, [&]( producer_info& info ){\n            info.deactivate();\n      });\n   }\n\n   void system_contract::update_elected_producers( block_timestamp block_time ) {\n      _gstate.last_producer_schedule_update = block_time;\n\n      auto idx = _producers.get_index<N(prototalvote)>();\n\n      std::vector< std::pair<eosio::producer_key,uint16_t> > top_producers;\n      top_producers.reserve(21);\n\n      for ( auto it = idx.cbegin(); it != idx.cend() && top_producers.size() < 21 && 0 < it->total_votes && it->active(); ++it ) {\n         top_producers.emplace_back( std::pair<eosio::producer_key,uint16_t>({{it->owner, it->producer_key}, it->location}) );\n      }\n\n      if ( top_producers.size() < _gstate.last_producer_schedule_size ) {\n         return;\n      }\n\n      \/\/\/ sort by producer name\n      std::sort( top_producers.begin(), top_producers.end() );\n\n      std::vector<eosio::producer_key> producers;\n\n      producers.reserve(top_producers.size());\n      for( const auto& item : top_producers )\n         producers.push_back(item.first);\n\n      bytes packed_schedule = pack(producers);\n\n      if( set_proposed_producers( packed_schedule.data(),  packed_schedule.size() ) >= 0 ) {\n         _gstate.last_producer_schedule_size = static_cast<decltype(_gstate.last_producer_schedule_size)>( top_producers.size() );\n      }\n   }\n\n   double stake2vote( int64_t staked ) {\n      \/\/\/ TODO subtract 2080 brings the large numbers closer to this decade\n      double weight = int64_t( (now() - (block_timestamp::block_timestamp_epoch \/ 1000)) \/ (seconds_per_day * 7) )  \/ double( 52 );\n      return double(staked) * std::pow( 2, weight );\n   }\n   \/**\n    *  @pre producers must be sorted from lowest to highest and must be registered and active\n    *  @pre if proxy is set then no producers can be voted for\n    *  @pre if proxy is set then proxy account must exist and be registered as a proxy\n    *  @pre every listed producer or proxy must have been previously registered\n    *  @pre voter must authorize this action\n    *  @pre voter must have previously staked some EOS for voting\n    *  @pre voter->staked must be up to date\n    *\n    *  @post every producer previously voted for will have vote reduced by previous vote weight\n    *  @post every producer newly voted for will have vote increased by new vote amount\n    *  @post prior proxy will proxied_vote_weight decremented by previous vote weight\n    *  @post new proxy will proxied_vote_weight incremented by new vote weight\n    *\n    *  If voting for a proxy, the producer votes will not change until the proxy updates their own vote.\n    *\/\n   void system_contract::voteproducer( const account_name voter_name, const account_name proxy, const std::vector<account_name>& producers ) {\n      require_auth( voter_name );\n      update_votes( voter_name, proxy, producers, true );\n   }\n\n   void system_contract::update_votes( const account_name voter_name, const account_name proxy, const std::vector<account_name>& producers, bool voting ) {\n      \/\/validate input\n      if ( proxy ) {\n         eosio_assert( producers.size() == 0, \"cannot vote for producers and proxy at same time\" );\n         eosio_assert( voter_name != proxy, \"cannot proxy to self\" );\n         require_recipient( proxy );\n      } else {\n         eosio_assert( producers.size() <= 30, \"attempt to vote for too many producers\" );\n         for( size_t i = 1; i < producers.size(); ++i ) {\n            eosio_assert( producers[i-1] < producers[i], \"producer votes must be unique and sorted\" );\n         }\n      }\n\n      auto voter = _voters.find(voter_name);\n      eosio_assert( voter != _voters.end(), \"user must stake before they can vote\" ); \/\/\/ staking creates voter object\n      eosio_assert( !proxy || !voter->is_proxy, \"account registered as a proxy is not allowed to use a proxy\" );\n\n      \/**\n       * The first time someone votes we calculate and set last_vote_weight, since they cannot unstake until\n       * after total_activated_stake hits threshold, we can use last_vote_weight to determine that this is\n       * their first vote and should consider their stake activated.\n       *\/\n      if( voter->last_vote_weight <= 0.0 ) {\n         _gstate.total_activated_stake += voter->staked;\n         if( _gstate.total_activated_stake >= min_activated_stake && _gstate.thresh_activated_stake_time == 0 ) {\n            _gstate.thresh_activated_stake_time = current_time();\n         }\n      }\n\n      auto new_vote_weight = stake2vote( voter->staked );\n      if( voter->is_proxy ) {\n         new_vote_weight += voter->proxied_vote_weight;\n      }\n\n      boost::container::flat_map<account_name, pair<double, bool \/*new*\/> > producer_deltas;\n      if ( voter->last_vote_weight > 0 ) {\n         if( voter->proxy ) {\n            auto old_proxy = _voters.find( voter->proxy );\n            eosio_assert( old_proxy != _voters.end(), \"old proxy not found\" ); \/\/data corruption\n            _voters.modify( old_proxy, 0, [&]( auto& vp ) {\n                  vp.proxied_vote_weight -= voter->last_vote_weight;\n               });\n            propagate_weight_change( *old_proxy );\n         } else {\n            for( const auto& p : voter->producers ) {\n               auto& d = producer_deltas[p];\n               d.first -= voter->last_vote_weight;\n               d.second = false;\n            }\n         }\n      }\n\n      if( proxy ) {\n         auto new_proxy = _voters.find( proxy );\n         eosio_assert( new_proxy != _voters.end(), \"invalid proxy specified\" ); \/\/if ( !voting ) { data corruption } else { wrong vote }\n         eosio_assert( !voting || new_proxy->is_proxy, \"proxy not found\" );\n         if ( new_vote_weight >= 0 ) {\n            _voters.modify( new_proxy, 0, [&]( auto& vp ) {\n                  vp.proxied_vote_weight += new_vote_weight;\n               });\n            propagate_weight_change( *new_proxy );\n         }\n      } else {\n         if( new_vote_weight >= 0 ) {\n            for( const auto& p : producers ) {\n               auto& d = producer_deltas[p];\n               d.first += new_vote_weight;\n               d.second = true;\n            }\n         }\n      }\n\n      for( const auto& pd : producer_deltas ) {\n         auto pitr = _producers.find( pd.first );\n         if( pitr != _producers.end() ) {\n            eosio_assert( !voting || pitr->active() || !pd.second.second \/* not from new set *\/, \"producer is not currently registered\" );\n            _producers.modify( pitr, 0, [&]( auto& p ) {\n               p.total_votes += pd.second.first;\n               if ( p.total_votes < 0 ) { \/\/ floating point arithmetics can give small negative numbers\n                  p.total_votes = 0;\n               }\n               _gstate.total_producer_vote_weight += pd.second.first;\n               \/\/eosio_assert( p.total_votes >= 0, \"something bad happened\" );\n            });\n         } else {\n            eosio_assert( !pd.second.second \/* not from new set *\/, \"producer is not registered\" ); \/\/data corruption\n         }\n      }\n\n      _voters.modify( voter, 0, [&]( auto& av ) {\n         av.last_vote_weight = new_vote_weight;\n         av.producers = producers;\n         av.proxy     = proxy;\n      });\n   }\n\n   \/**\n    *  An account marked as a proxy can vote with the weight of other accounts which\n    *  have selected it as a proxy. Other accounts must refresh their voteproducer to\n    *  update the proxy's weight.\n    *\n    *  @param isproxy - true if proxy wishes to vote on behalf of others, false otherwise\n    *  @pre proxy must have something staked (existing row in voters table)\n    *  @pre new state must be different than current state\n    *\/\n   void system_contract::regproxy( const account_name proxy, bool isproxy ) {\n      require_auth( proxy );\n\n      auto pitr = _voters.find(proxy);\n      if ( pitr != _voters.end() ) {\n         eosio_assert( isproxy != pitr->is_proxy, \"action has no effect\" );\n         eosio_assert( !isproxy || !pitr->proxy, \"account that uses a proxy is not allowed to become a proxy\" );\n         _voters.modify( pitr, 0, [&]( auto& p ) {\n               p.is_proxy = isproxy;\n            });\n         propagate_weight_change( *pitr );\n      } else {\n         _voters.emplace( proxy, [&]( auto& p ) {\n               p.owner  = proxy;\n               p.is_proxy = isproxy;\n            });\n      }\n   }\n\n   void system_contract::propagate_weight_change( const voter_info& voter ) {\n      eosio_assert( voter.proxy == 0 || !voter.is_proxy, \"account registered as a proxy is not allowed to use a proxy\" );\n      double new_weight = stake2vote( voter.staked );\n      if ( voter.is_proxy ) {\n         new_weight += voter.proxied_vote_weight;\n      }\n\n      \/\/\/ don't propagate small changes (1 ~= epsilon)\n      if ( fabs( new_weight - voter.last_vote_weight ) > 1 )  {\n         if ( voter.proxy ) {\n            auto& proxy = _voters.get( voter.proxy, \"proxy not found\" ); \/\/data corruption\n            _voters.modify( proxy, 0, [&]( auto& p ) {\n                  p.proxied_vote_weight += new_weight - voter.last_vote_weight;\n               }\n            );\n            propagate_weight_change( proxy );\n         } else {\n            auto delta = new_weight - voter.last_vote_weight;\n            for ( auto acnt : voter.producers ) {\n               auto& pitr = _producers.get( acnt, \"producer not found\" ); \/\/data corruption\n               _producers.modify( pitr, 0, [&]( auto& p ) {\n                     p.total_votes += delta;\n                     _gstate.total_producer_vote_weight += delta;\n               });\n            }\n         }\n      }\n      _voters.modify( voter, 0, [&]( auto& v ) {\n            v.last_vote_weight = new_weight;\n         }\n      );\n   }\n\n} \/\/\/ namespace eosiosystem\n","avg_line_length":40.9965397924,"max_line_length":155,"alphanum_fraction":0.6050810263,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":370400,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":null,"content":"\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: PS4AppInit\r\n#include \"GlobalNamespace\/PS4AppInit.hpp\"\r\n\/\/ Including type: MainSystemInit\r\n#include \"GlobalNamespace\/MainSystemInit.hpp\"\r\n\/\/ Including type: DefaultScenesTransitionsFromInit\r\n#include \"GlobalNamespace\/DefaultScenesTransitionsFromInit.hpp\"\r\n\/\/ Including type: AppInitScenesTransitionSetupDataContainerSO\r\n#include \"GlobalNamespace\/AppInitScenesTransitionSetupDataContainerSO.hpp\"\r\n\/\/ Including type: MainSettingsModelSO\r\n#include \"GlobalNamespace\/MainSettingsModelSO.hpp\"\r\n\/\/ Including type: PS4ActivePublisherSKUSettingsSO\r\n#include \"GlobalNamespace\/PS4ActivePublisherSKUSettingsSO.hpp\"\r\n\/\/ Including type: GameScenesManager\r\n#include \"GlobalNamespace\/GameScenesManager.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: PS4AppInit.AppStartAndMultiSceneEditorSetup\r\nvoid GlobalNamespace::PS4AppInit::AppStartAndMultiSceneEditorSetup() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PS4AppInit::AppStartAndMultiSceneEditorSetup\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"AppStartAndMultiSceneEditorSetup\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: PS4AppInit.RepeatableSetup\r\nvoid GlobalNamespace::PS4AppInit::RepeatableSetup() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PS4AppInit::RepeatableSetup\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"RepeatableSetup\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: PS4AppInit.TransitionToNextScene\r\nvoid GlobalNamespace::PS4AppInit::TransitionToNextScene() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PS4AppInit::TransitionToNextScene\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"TransitionToNextScene\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: PS4AppInit.InstallBindings\r\nvoid GlobalNamespace::PS4AppInit::InstallBindings() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PS4AppInit::InstallBindings\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"InstallBindings\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: QuestAppInit\r\n#include \"GlobalNamespace\/QuestAppInit.hpp\"\r\n\/\/ Including type: MainSystemInit\r\n#include \"GlobalNamespace\/MainSystemInit.hpp\"\r\n\/\/ Including type: OculusInit\r\n#include \"GlobalNamespace\/OculusInit.hpp\"\r\n\/\/ Including type: DefaultScenesTransitionsFromInit\r\n#include \"GlobalNamespace\/DefaultScenesTransitionsFromInit.hpp\"\r\n\/\/ Including type: MainSettingsModelSO\r\n#include \"GlobalNamespace\/MainSettingsModelSO.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: QuestAppInit.AppStartAndMultiSceneEditorSetup\r\nvoid GlobalNamespace::QuestAppInit::AppStartAndMultiSceneEditorSetup() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::QuestAppInit::AppStartAndMultiSceneEditorSetup\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"AppStartAndMultiSceneEditorSetup\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: QuestAppInit.RepeatableSetup\r\nvoid GlobalNamespace::QuestAppInit::RepeatableSetup() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::QuestAppInit::RepeatableSetup\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"RepeatableSetup\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: QuestAppInit.TransitionToNextScene\r\nvoid GlobalNamespace::QuestAppInit::TransitionToNextScene() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::QuestAppInit::TransitionToNextScene\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"TransitionToNextScene\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: QuestAppInit.InstallBindings\r\nvoid GlobalNamespace::QuestAppInit::InstallBindings() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::QuestAppInit::InstallBindings\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"InstallBindings\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: QuestShowcaseAppInit\r\n#include \"GlobalNamespace\/QuestShowcaseAppInit.hpp\"\r\n\/\/ Including type: MainSystemInit\r\n#include \"GlobalNamespace\/MainSystemInit.hpp\"\r\n\/\/ Including type: OculusInit\r\n#include \"GlobalNamespace\/OculusInit.hpp\"\r\n\/\/ Including type: MenuScenesTransitionSetupDataSO\r\n#include \"GlobalNamespace\/MenuScenesTransitionSetupDataSO.hpp\"\r\n\/\/ Including type: MainSettingsModelSO\r\n#include \"GlobalNamespace\/MainSettingsModelSO.hpp\"\r\n\/\/ Including type: GameScenesManager\r\n#include \"GlobalNamespace\/GameScenesManager.hpp\"\r\n\/\/ Including type: PlayerDataModel\r\n#include \"GlobalNamespace\/PlayerDataModel.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: QuestShowcaseAppInit.AppStartAndMultiSceneEditorSetup\r\nvoid GlobalNamespace::QuestShowcaseAppInit::AppStartAndMultiSceneEditorSetup() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::QuestShowcaseAppInit::AppStartAndMultiSceneEditorSetup\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"AppStartAndMultiSceneEditorSetup\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: QuestShowcaseAppInit.RepeatableSetup\r\nvoid GlobalNamespace::QuestShowcaseAppInit::RepeatableSetup() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::QuestShowcaseAppInit::RepeatableSetup\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"RepeatableSetup\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: QuestShowcaseAppInit.TransitionToNextScene\r\nvoid GlobalNamespace::QuestShowcaseAppInit::TransitionToNextScene() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::QuestShowcaseAppInit::TransitionToNextScene\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"TransitionToNextScene\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: QuestShowcaseAppInit.InstallBindings\r\nvoid GlobalNamespace::QuestShowcaseAppInit::InstallBindings() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::QuestShowcaseAppInit::InstallBindings\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"InstallBindings\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: SteamInit\r\n#include \"GlobalNamespace\/SteamInit.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: SteamInit.Init\r\nvoid GlobalNamespace::SteamInit::Init() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SteamInit::Init\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Init\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AudioClipLoaderSO\r\n#include \"GlobalNamespace\/AudioClipLoaderSO.hpp\"\r\n\/\/ Including type: AudioClipLoaderSO\/<LoadAudioFileCoroutine>d__3\r\n#include \"GlobalNamespace\/AudioClipLoaderSO_-LoadAudioFileCoroutine-d__3.hpp\"\r\n\/\/ Including type: System.Action`1\r\n#include \"System\/Action_1.hpp\"\r\n\/\/ Including type: UnityEngine.AudioClip\r\n#include \"UnityEngine\/AudioClip.hpp\"\r\n\/\/ Including type: System.Collections.IEnumerator\r\n#include \"System\/Collections\/IEnumerator.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AudioClipLoaderSO.LoadAudioFile\r\nvoid GlobalNamespace::AudioClipLoaderSO::LoadAudioFile(::Il2CppString* filePath, System::Action_1<UnityEngine::AudioClip*>* finishCallback) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioClipLoaderSO::LoadAudioFile\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"LoadAudioFile\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(filePath), ::il2cpp_utils::ExtractType(finishCallback)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, filePath, finishCallback);\r\n}\r\n\/\/ Autogenerated method: AudioClipLoaderSO.LoadAudioFileCoroutine\r\nSystem::Collections::IEnumerator* GlobalNamespace::AudioClipLoaderSO::LoadAudioFileCoroutine(::Il2CppString* filePath, System::Action_1<UnityEngine::AudioClip*>* finishCallback) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioClipLoaderSO::LoadAudioFileCoroutine\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"LoadAudioFileCoroutine\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(filePath), ::il2cpp_utils::ExtractType(finishCallback)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Collections::IEnumerator*, false>(this, ___internal__method, filePath, finishCallback);\r\n}\r\n\/\/ Autogenerated method: AudioClipLoaderSO.OnEnable\r\nvoid GlobalNamespace::AudioClipLoaderSO::OnEnable() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioClipLoaderSO::OnEnable\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnEnable\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AudioClipLoaderSO\/<LoadAudioFileCoroutine>d__3\r\n#include \"GlobalNamespace\/AudioClipLoaderSO_-LoadAudioFileCoroutine-d__3.hpp\"\r\n\/\/ Including type: System.Action`1\r\n#include \"System\/Action_1.hpp\"\r\n\/\/ Including type: UnityEngine.AudioClip\r\n#include \"UnityEngine\/AudioClip.hpp\"\r\n\/\/ Including type: UnityEngine.Networking.UnityWebRequest\r\n#include \"UnityEngine\/Networking\/UnityWebRequest.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AudioClipLoaderSO\/<LoadAudioFileCoroutine>d__3.System.IDisposable.Dispose\r\nvoid GlobalNamespace::AudioClipLoaderSO::$LoadAudioFileCoroutine$d__3::System_IDisposable_Dispose() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioClipLoaderSO::$LoadAudioFileCoroutine$d__3::System.IDisposable.Dispose\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.IDisposable.Dispose\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioClipLoaderSO\/<LoadAudioFileCoroutine>d__3.MoveNext\r\nbool GlobalNamespace::AudioClipLoaderSO::$LoadAudioFileCoroutine$d__3::MoveNext() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioClipLoaderSO::$LoadAudioFileCoroutine$d__3::MoveNext\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"MoveNext\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioClipLoaderSO\/<LoadAudioFileCoroutine>d__3.<>m__Finally1\r\nvoid GlobalNamespace::AudioClipLoaderSO::$LoadAudioFileCoroutine$d__3::$$m__Finally1() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioClipLoaderSO::$LoadAudioFileCoroutine$d__3::<>m__Finally1\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<>m__Finally1\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioClipLoaderSO\/<LoadAudioFileCoroutine>d__3.System.Collections.Generic.IEnumerator<System.Object>.get_Current\r\n::Il2CppObject* GlobalNamespace::AudioClipLoaderSO::$LoadAudioFileCoroutine$d__3::System_Collections_Generic_IEnumerator$System_Object$_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioClipLoaderSO::$LoadAudioFileCoroutine$d__3::System.Collections.Generic.IEnumerator<System.Object>.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.Generic.IEnumerator<System.Object>.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioClipLoaderSO\/<LoadAudioFileCoroutine>d__3.System.Collections.IEnumerator.Reset\r\nvoid GlobalNamespace::AudioClipLoaderSO::$LoadAudioFileCoroutine$d__3::System_Collections_IEnumerator_Reset() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioClipLoaderSO::$LoadAudioFileCoroutine$d__3::System.Collections.IEnumerator.Reset\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.Reset\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioClipLoaderSO\/<LoadAudioFileCoroutine>d__3.System.Collections.IEnumerator.get_Current\r\n::Il2CppObject* GlobalNamespace::AudioClipLoaderSO::$LoadAudioFileCoroutine$d__3::System_Collections_IEnumerator_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioClipLoaderSO::$LoadAudioFileCoroutine$d__3::System.Collections.IEnumerator.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AudioClipQueue\r\n#include \"GlobalNamespace\/AudioClipQueue.hpp\"\r\n\/\/ Including type: UnityEngine.AudioSource\r\n#include \"UnityEngine\/AudioSource.hpp\"\r\n\/\/ Including type: System.Collections.Generic.List`1\r\n#include \"System\/Collections\/Generic\/List_1.hpp\"\r\n\/\/ Including type: UnityEngine.AudioClip\r\n#include \"UnityEngine\/AudioClip.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AudioClipQueue.Awake\r\nvoid GlobalNamespace::AudioClipQueue::Awake() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioClipQueue::Awake\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Awake\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioClipQueue.Update\r\nvoid GlobalNamespace::AudioClipQueue::Update() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioClipQueue::Update\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Update\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioClipQueue.PlayAudioClipWithDelay\r\nvoid GlobalNamespace::AudioClipQueue::PlayAudioClipWithDelay(UnityEngine::AudioClip* audioClip, float delay) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioClipQueue::PlayAudioClipWithDelay\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"PlayAudioClipWithDelay\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(audioClip), ::il2cpp_utils::ExtractType(delay)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, audioClip, delay);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AudioFading\r\n#include \"GlobalNamespace\/AudioFading.hpp\"\r\n\/\/ Including type: UnityEngine.AudioSource\r\n#include \"UnityEngine\/AudioSource.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AudioFading.Start\r\nvoid GlobalNamespace::AudioFading::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioFading::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioFading.Update\r\nvoid GlobalNamespace::AudioFading::Update() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioFading::Update\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Update\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioFading.FadeOut\r\nvoid GlobalNamespace::AudioFading::FadeOut() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioFading::FadeOut\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"FadeOut\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioFading.FadeIn\r\nvoid GlobalNamespace::AudioFading::FadeIn() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioFading::FadeIn\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"FadeIn\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AudioListenerController\r\n#include \"GlobalNamespace\/AudioListenerController.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AudioListenerController.get_isPaused\r\nbool GlobalNamespace::AudioListenerController::get_isPaused() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioListenerController::get_isPaused\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_isPaused\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioListenerController.Awake\r\nvoid GlobalNamespace::AudioListenerController::Awake() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioListenerController::Awake\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Awake\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioListenerController.OnDestroy\r\nvoid GlobalNamespace::AudioListenerController::OnDestroy() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioListenerController::OnDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioListenerController.Pause\r\nvoid GlobalNamespace::AudioListenerController::Pause() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioListenerController::Pause\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Pause\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioListenerController.Resume\r\nvoid GlobalNamespace::AudioListenerController::Resume() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioListenerController::Resume\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Resume\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AudioManagerSO\r\n#include \"GlobalNamespace\/AudioManagerSO.hpp\"\r\n\/\/ Including type: UnityEngine.Audio.AudioMixer\r\n#include \"UnityEngine\/Audio\/AudioMixer.hpp\"\r\n\/\/ Including type: UnityEngine.Audio.AudioMixerGroup\r\n#include \"UnityEngine\/Audio\/AudioMixerGroup.hpp\"\r\n\/\/ Including type: System.String\r\n#include \"System\/String.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.String kMSHRTFSpatializerPluginName\r\n::Il2CppString* GlobalNamespace::AudioManagerSO::_get_kMSHRTFSpatializerPluginName() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_get_kMSHRTFSpatializerPluginName\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<::Il2CppString*>(\"\", \"AudioManagerSO\", \"kMSHRTFSpatializerPluginName\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.String kMSHRTFSpatializerPluginName\r\nvoid GlobalNamespace::AudioManagerSO::_set_kMSHRTFSpatializerPluginName(::Il2CppString* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_set_kMSHRTFSpatializerPluginName\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AudioManagerSO\", \"kMSHRTFSpatializerPluginName\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.String kMasterGroup\r\n::Il2CppString* GlobalNamespace::AudioManagerSO::_get_kMasterGroup() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_get_kMasterGroup\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<::Il2CppString*>(\"\", \"AudioManagerSO\", \"kMasterGroup\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.String kMasterGroup\r\nvoid GlobalNamespace::AudioManagerSO::_set_kMasterGroup(::Il2CppString* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_set_kMasterGroup\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AudioManagerSO\", \"kMasterGroup\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.String kMusicGroup\r\n::Il2CppString* GlobalNamespace::AudioManagerSO::_get_kMusicGroup() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_get_kMusicGroup\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<::Il2CppString*>(\"\", \"AudioManagerSO\", \"kMusicGroup\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.String kMusicGroup\r\nvoid GlobalNamespace::AudioManagerSO::_set_kMusicGroup(::Il2CppString* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_set_kMusicGroup\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AudioManagerSO\", \"kMusicGroup\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.String kSFXVolume\r\n::Il2CppString* GlobalNamespace::AudioManagerSO::_get_kSFXVolume() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_get_kSFXVolume\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<::Il2CppString*>(\"\", \"AudioManagerSO\", \"kSFXVolume\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.String kSFXVolume\r\nvoid GlobalNamespace::AudioManagerSO::_set_kSFXVolume(::Il2CppString* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_set_kSFXVolume\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AudioManagerSO\", \"kSFXVolume\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.String kMainVolume\r\n::Il2CppString* GlobalNamespace::AudioManagerSO::_get_kMainVolume() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_get_kMainVolume\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<::Il2CppString*>(\"\", \"AudioManagerSO\", \"kMainVolume\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.String kMainVolume\r\nvoid GlobalNamespace::AudioManagerSO::_set_kMainVolume(::Il2CppString* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_set_kMainVolume\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AudioManagerSO\", \"kMainVolume\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.String kMusicVolume\r\n::Il2CppString* GlobalNamespace::AudioManagerSO::_get_kMusicVolume() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_get_kMusicVolume\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<::Il2CppString*>(\"\", \"AudioManagerSO\", \"kMusicVolume\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.String kMusicVolume\r\nvoid GlobalNamespace::AudioManagerSO::_set_kMusicVolume(::Il2CppString* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_set_kMusicVolume\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AudioManagerSO\", \"kMusicVolume\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.String kMusicPitch\r\n::Il2CppString* GlobalNamespace::AudioManagerSO::_get_kMusicPitch() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_get_kMusicPitch\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<::Il2CppString*>(\"\", \"AudioManagerSO\", \"kMusicPitch\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.String kMusicPitch\r\nvoid GlobalNamespace::AudioManagerSO::_set_kMusicPitch(::Il2CppString* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_set_kMusicPitch\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AudioManagerSO\", \"kMusicPitch\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.String kMusicPitchShifterWet\r\n::Il2CppString* GlobalNamespace::AudioManagerSO::_get_kMusicPitchShifterWet() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_get_kMusicPitchShifterWet\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<::Il2CppString*>(\"\", \"AudioManagerSO\", \"kMusicPitchShifterWet\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.String kMusicPitchShifterWet\r\nvoid GlobalNamespace::AudioManagerSO::_set_kMusicPitchShifterWet(::Il2CppString* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::_set_kMusicPitchShifterWet\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AudioManagerSO\", \"kMusicPitchShifterWet\", value));\r\n}\r\n\/\/ Autogenerated method: AudioManagerSO.get_sfxLatency\r\nfloat GlobalNamespace::AudioManagerSO::get_sfxLatency() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::get_sfxLatency\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_sfxLatency\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioManagerSO.Init\r\nvoid GlobalNamespace::AudioManagerSO::Init() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::Init\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Init\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioManagerSO.get_masterMixerGroup\r\nUnityEngine::Audio::AudioMixerGroup* GlobalNamespace::AudioManagerSO::get_masterMixerGroup() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::get_masterMixerGroup\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_masterMixerGroup\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::Audio::AudioMixerGroup*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioManagerSO.set_masterMixerGroup\r\nvoid GlobalNamespace::AudioManagerSO::set_masterMixerGroup(UnityEngine::Audio::AudioMixerGroup* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::set_masterMixerGroup\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_masterMixerGroup\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: AudioManagerSO.get_musicMixerGroup\r\nUnityEngine::Audio::AudioMixerGroup* GlobalNamespace::AudioManagerSO::get_musicMixerGroup() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::get_musicMixerGroup\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_musicMixerGroup\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::Audio::AudioMixerGroup*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioManagerSO.set_musicMixerGroup\r\nvoid GlobalNamespace::AudioManagerSO::set_musicMixerGroup(UnityEngine::Audio::AudioMixerGroup* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::set_musicMixerGroup\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_musicMixerGroup\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: AudioManagerSO.set_mainVolume\r\nvoid GlobalNamespace::AudioManagerSO::set_mainVolume(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::set_mainVolume\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_mainVolume\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: AudioManagerSO.set_musicVolume\r\nvoid GlobalNamespace::AudioManagerSO::set_musicVolume(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::set_musicVolume\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_musicVolume\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: AudioManagerSO.set_sfxVolume\r\nvoid GlobalNamespace::AudioManagerSO::set_sfxVolume(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::set_sfxVolume\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_sfxVolume\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: AudioManagerSO.get_sfxEnabled\r\nbool GlobalNamespace::AudioManagerSO::get_sfxEnabled() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::get_sfxEnabled\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_sfxEnabled\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioManagerSO.set_sfxEnabled\r\nvoid GlobalNamespace::AudioManagerSO::set_sfxEnabled(bool value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::set_sfxEnabled\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_sfxEnabled\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: AudioManagerSO.set_musicPitch\r\nvoid GlobalNamespace::AudioManagerSO::set_musicPitch(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioManagerSO::set_musicPitch\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_musicPitch\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AudioPitchGainEffect\r\n#include \"GlobalNamespace\/AudioPitchGainEffect.hpp\"\r\n\/\/ Including type: AudioPitchGainEffect\/<StartEffectCoroutine>d__8\r\n#include \"GlobalNamespace\/AudioPitchGainEffect_-StartEffectCoroutine-d__8.hpp\"\r\n\/\/ Including type: UnityEngine.AudioSource\r\n#include \"UnityEngine\/AudioSource.hpp\"\r\n\/\/ Including type: UnityEngine.AnimationCurve\r\n#include \"UnityEngine\/AnimationCurve.hpp\"\r\n\/\/ Including type: UnityEngine.Coroutine\r\n#include \"UnityEngine\/Coroutine.hpp\"\r\n\/\/ Including type: System.Collections.IEnumerator\r\n#include \"System\/Collections\/IEnumerator.hpp\"\r\n\/\/ Including type: System.Action\r\n#include \"System\/Action.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AudioPitchGainEffect.Start\r\nvoid GlobalNamespace::AudioPitchGainEffect::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPitchGainEffect::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioPitchGainEffect.StartEffectCoroutine\r\nSystem::Collections::IEnumerator* GlobalNamespace::AudioPitchGainEffect::StartEffectCoroutine(float volumeScale, System::Action* finishCallback) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPitchGainEffect::StartEffectCoroutine\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"StartEffectCoroutine\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(volumeScale), ::il2cpp_utils::ExtractType(finishCallback)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Collections::IEnumerator*, false>(this, ___internal__method, volumeScale, finishCallback);\r\n}\r\n\/\/ Autogenerated method: AudioPitchGainEffect.StartEffect\r\nvoid GlobalNamespace::AudioPitchGainEffect::StartEffect(float volumeScale, System::Action* finishCallback) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPitchGainEffect::StartEffect\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"StartEffect\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(volumeScale), ::il2cpp_utils::ExtractType(finishCallback)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, volumeScale, finishCallback);\r\n}\r\n\/\/ Autogenerated method: AudioPitchGainEffect.InterruptEffect\r\nvoid GlobalNamespace::AudioPitchGainEffect::InterruptEffect() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPitchGainEffect::InterruptEffect\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"InterruptEffect\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioPitchGainEffect.SetAudioSource\r\nvoid GlobalNamespace::AudioPitchGainEffect::SetAudioSource(UnityEngine::AudioSource* audioSource) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPitchGainEffect::SetAudioSource\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"SetAudioSource\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(audioSource)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, audioSource);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AudioPitchGainEffect\/<StartEffectCoroutine>d__8\r\n#include \"GlobalNamespace\/AudioPitchGainEffect_-StartEffectCoroutine-d__8.hpp\"\r\n\/\/ Including type: System.Action\r\n#include \"System\/Action.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AudioPitchGainEffect\/<StartEffectCoroutine>d__8.System.IDisposable.Dispose\r\nvoid GlobalNamespace::AudioPitchGainEffect::$StartEffectCoroutine$d__8::System_IDisposable_Dispose() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPitchGainEffect::$StartEffectCoroutine$d__8::System.IDisposable.Dispose\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.IDisposable.Dispose\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioPitchGainEffect\/<StartEffectCoroutine>d__8.MoveNext\r\nbool GlobalNamespace::AudioPitchGainEffect::$StartEffectCoroutine$d__8::MoveNext() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPitchGainEffect::$StartEffectCoroutine$d__8::MoveNext\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"MoveNext\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioPitchGainEffect\/<StartEffectCoroutine>d__8.System.Collections.Generic.IEnumerator<System.Object>.get_Current\r\n::Il2CppObject* GlobalNamespace::AudioPitchGainEffect::$StartEffectCoroutine$d__8::System_Collections_Generic_IEnumerator$System_Object$_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPitchGainEffect::$StartEffectCoroutine$d__8::System.Collections.Generic.IEnumerator<System.Object>.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.Generic.IEnumerator<System.Object>.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioPitchGainEffect\/<StartEffectCoroutine>d__8.System.Collections.IEnumerator.Reset\r\nvoid GlobalNamespace::AudioPitchGainEffect::$StartEffectCoroutine$d__8::System_Collections_IEnumerator_Reset() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPitchGainEffect::$StartEffectCoroutine$d__8::System.Collections.IEnumerator.Reset\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.Reset\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioPitchGainEffect\/<StartEffectCoroutine>d__8.System.Collections.IEnumerator.get_Current\r\n::Il2CppObject* GlobalNamespace::AudioPitchGainEffect::$StartEffectCoroutine$d__8::System_Collections_IEnumerator_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPitchGainEffect::$StartEffectCoroutine$d__8::System.Collections.IEnumerator.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AudioPlayerBase\r\n#include \"GlobalNamespace\/AudioPlayerBase.hpp\"\r\n\/\/ Including type: UnityEngine.AudioClip\r\n#include \"UnityEngine\/AudioClip.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AudioPlayerBase.get_activeAudioClip\r\nUnityEngine::AudioClip* GlobalNamespace::AudioPlayerBase::get_activeAudioClip() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPlayerBase::get_activeAudioClip\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_activeAudioClip\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::AudioClip*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioPlayerBase.FadeOut\r\nvoid GlobalNamespace::AudioPlayerBase::FadeOut(float duration) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPlayerBase::FadeOut\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"FadeOut\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(duration)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, duration);\r\n}\r\n\/\/ Autogenerated method: AudioPlayerBase.PauseCurrentChannel\r\nvoid GlobalNamespace::AudioPlayerBase::PauseCurrentChannel() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPlayerBase::PauseCurrentChannel\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"PauseCurrentChannel\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioPlayerBase.UnPauseCurrentChannel\r\nvoid GlobalNamespace::AudioPlayerBase::UnPauseCurrentChannel() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioPlayerBase::UnPauseCurrentChannel\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"UnPauseCurrentChannel\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AudioTimeSyncController\r\n#include \"GlobalNamespace\/AudioTimeSyncController.hpp\"\r\n\/\/ Including type: AudioTimeSyncController\/InitData\r\n#include \"GlobalNamespace\/AudioTimeSyncController_InitData.hpp\"\r\n\/\/ Including type: UnityEngine.AudioSource\r\n#include \"UnityEngine\/AudioSource.hpp\"\r\n\/\/ Including type: FloatSO\r\n#include \"GlobalNamespace\/FloatSO.hpp\"\r\n\/\/ Including type: UnityEngine.WaitUntil\r\n#include \"UnityEngine\/WaitUntil.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AudioTimeSyncController.get_state\r\nGlobalNamespace::AudioTimeSyncController::State GlobalNamespace::AudioTimeSyncController::get_state() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::get_state\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_state\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<GlobalNamespace::AudioTimeSyncController::State, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.get_songTime\r\nfloat GlobalNamespace::AudioTimeSyncController::get_songTime() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::get_songTime\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_songTime\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.get_songLength\r\nfloat GlobalNamespace::AudioTimeSyncController::get_songLength() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::get_songLength\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_songLength\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.get_isAudioLoaded\r\nbool GlobalNamespace::AudioTimeSyncController::get_isAudioLoaded() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::get_isAudioLoaded\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_isAudioLoaded\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.get_songEndTime\r\nfloat GlobalNamespace::AudioTimeSyncController::get_songEndTime() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::get_songEndTime\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_songEndTime\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.get_timeScale\r\nfloat GlobalNamespace::AudioTimeSyncController::get_timeScale() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::get_timeScale\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_timeScale\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.get_dspTimeOffset\r\ndouble GlobalNamespace::AudioTimeSyncController::get_dspTimeOffset() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::get_dspTimeOffset\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_dspTimeOffset\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<double, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.get_waitUntilAudioIsLoaded\r\nUnityEngine::WaitUntil* GlobalNamespace::AudioTimeSyncController::get_waitUntilAudioIsLoaded() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::get_waitUntilAudioIsLoaded\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_waitUntilAudioIsLoaded\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::WaitUntil*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.get_isReady\r\nbool GlobalNamespace::AudioTimeSyncController::get_isReady() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::get_isReady\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_isReady\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.get_audioSource\r\nUnityEngine::AudioSource* GlobalNamespace::AudioTimeSyncController::get_audioSource() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::get_audioSource\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_audioSource\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::AudioSource*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.Awake\r\nvoid GlobalNamespace::AudioTimeSyncController::Awake() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::Awake\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Awake\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.Start\r\nvoid GlobalNamespace::AudioTimeSyncController::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.Update\r\nvoid GlobalNamespace::AudioTimeSyncController::Update() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::Update\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Update\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.get_timeSinceStart\r\nfloat GlobalNamespace::AudioTimeSyncController::get_timeSinceStart() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::get_timeSinceStart\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_timeSinceStart\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.StartSong\r\nvoid GlobalNamespace::AudioTimeSyncController::StartSong(float startTimeOffset) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::StartSong\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"StartSong\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(startTimeOffset)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, startTimeOffset);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.SeekTo\r\nvoid GlobalNamespace::AudioTimeSyncController::SeekTo(float startTimeOffset) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::SeekTo\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"SeekTo\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(startTimeOffset)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, startTimeOffset);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.StopSong\r\nvoid GlobalNamespace::AudioTimeSyncController::StopSong() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::StopSong\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"StopSong\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.Pause\r\nvoid GlobalNamespace::AudioTimeSyncController::Pause() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::Pause\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Pause\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.Resume\r\nvoid GlobalNamespace::AudioTimeSyncController::Resume() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::Resume\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Resume\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AudioTimeSyncController.<get_waitUntilAudioIsLoaded>b__25_0\r\nbool GlobalNamespace::AudioTimeSyncController::$get_waitUntilAudioIsLoaded$b__25_0() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::<get_waitUntilAudioIsLoaded>b__25_0\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<get_waitUntilAudioIsLoaded>b__25_0\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AudioTimeSyncController\/InitData\r\n#include \"GlobalNamespace\/AudioTimeSyncController_InitData.hpp\"\r\n\/\/ Including type: UnityEngine.AudioClip\r\n#include \"UnityEngine\/AudioClip.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AudioTimeSyncController\/State\r\n#include \"GlobalNamespace\/AudioTimeSyncController.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public AudioTimeSyncController\/State Playing\r\nGlobalNamespace::AudioTimeSyncController::State GlobalNamespace::AudioTimeSyncController::State::_get_Playing() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::State::_get_Playing\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::AudioTimeSyncController::State>(\"\", \"AudioTimeSyncController\/State\", \"Playing\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public AudioTimeSyncController\/State Playing\r\nvoid GlobalNamespace::AudioTimeSyncController::State::_set_Playing(GlobalNamespace::AudioTimeSyncController::State value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::State::_set_Playing\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AudioTimeSyncController\/State\", \"Playing\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public AudioTimeSyncController\/State Paused\r\nGlobalNamespace::AudioTimeSyncController::State GlobalNamespace::AudioTimeSyncController::State::_get_Paused() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::State::_get_Paused\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::AudioTimeSyncController::State>(\"\", \"AudioTimeSyncController\/State\", \"Paused\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public AudioTimeSyncController\/State Paused\r\nvoid GlobalNamespace::AudioTimeSyncController::State::_set_Paused(GlobalNamespace::AudioTimeSyncController::State value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::State::_set_Paused\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AudioTimeSyncController\/State\", \"Paused\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public AudioTimeSyncController\/State Stopped\r\nGlobalNamespace::AudioTimeSyncController::State GlobalNamespace::AudioTimeSyncController::State::_get_Stopped() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::State::_get_Stopped\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::AudioTimeSyncController::State>(\"\", \"AudioTimeSyncController\/State\", \"Stopped\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public AudioTimeSyncController\/State Stopped\r\nvoid GlobalNamespace::AudioTimeSyncController::State::_set_Stopped(GlobalNamespace::AudioTimeSyncController::State value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AudioTimeSyncController::State::_set_Stopped\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AudioTimeSyncController\/State\", \"Stopped\", value));\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AutomaticSFXVolume\r\n#include \"GlobalNamespace\/AutomaticSFXVolume.hpp\"\r\n\/\/ Including type: AutomaticSFXVolume\/InitData\r\n#include \"GlobalNamespace\/AutomaticSFXVolume_InitData.hpp\"\r\n\/\/ Including type: AutomaticSFXVolumeParamsSO\r\n#include \"GlobalNamespace\/AutomaticSFXVolumeParamsSO.hpp\"\r\n\/\/ Including type: AudioManagerSO\r\n#include \"GlobalNamespace\/AudioManagerSO.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.Single kBaseVolume\r\nfloat GlobalNamespace::AutomaticSFXVolume::_get_kBaseVolume() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolume::_get_kBaseVolume\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<float>(\"\", \"AutomaticSFXVolume\", \"kBaseVolume\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.Single kBaseVolume\r\nvoid GlobalNamespace::AutomaticSFXVolume::_set_kBaseVolume(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolume::_set_kBaseVolume\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AutomaticSFXVolume\", \"kBaseVolume\", value));\r\n}\r\n\/\/ Autogenerated method: AutomaticSFXVolume.Start\r\nvoid GlobalNamespace::AutomaticSFXVolume::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolume::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AutomaticSFXVolume.OnDisable\r\nvoid GlobalNamespace::AutomaticSFXVolume::OnDisable() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolume::OnDisable\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDisable\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AutomaticSFXVolume.OnValidate\r\nvoid GlobalNamespace::AutomaticSFXVolume::OnValidate() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolume::OnValidate\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnValidate\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AutomaticSFXVolume.RecalculateParams\r\nvoid GlobalNamespace::AutomaticSFXVolume::RecalculateParams() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolume::RecalculateParams\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"RecalculateParams\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AutomaticSFXVolume.OnAudioFilterRead\r\nvoid GlobalNamespace::AutomaticSFXVolume::OnAudioFilterRead(::Array<float>* data, int channels) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolume::OnAudioFilterRead\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnAudioFilterRead\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(data), ::il2cpp_utils::ExtractType(channels)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, data, channels);\r\n}\r\n\/\/ Autogenerated method: AutomaticSFXVolume.Update\r\nvoid GlobalNamespace::AutomaticSFXVolume::Update() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolume::Update\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Update\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AutomaticSFXVolume\/InitData\r\n#include \"GlobalNamespace\/AutomaticSFXVolume_InitData.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AutomaticSFXVolumeParamsSO\r\n#include \"GlobalNamespace\/AutomaticSFXVolumeParamsSO.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AutomaticSFXVolumeParamsSO.get_musicVolumeMultiplier\r\nfloat GlobalNamespace::AutomaticSFXVolumeParamsSO::get_musicVolumeMultiplier() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolumeParamsSO::get_musicVolumeMultiplier\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_musicVolumeMultiplier\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AutomaticSFXVolumeParamsSO.get_threshold\r\nfloat GlobalNamespace::AutomaticSFXVolumeParamsSO::get_threshold() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolumeParamsSO::get_threshold\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_threshold\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AutomaticSFXVolumeParamsSO.get_impact\r\nfloat GlobalNamespace::AutomaticSFXVolumeParamsSO::get_impact() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolumeParamsSO::get_impact\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_impact\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AutomaticSFXVolumeParamsSO.get_attackTime\r\nfloat GlobalNamespace::AutomaticSFXVolumeParamsSO::get_attackTime() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolumeParamsSO::get_attackTime\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_attackTime\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AutomaticSFXVolumeParamsSO.get_releaseTime\r\nfloat GlobalNamespace::AutomaticSFXVolumeParamsSO::get_releaseTime() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolumeParamsSO::get_releaseTime\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_releaseTime\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AutomaticSFXVolumeParamsSO.get_minVolume\r\nfloat GlobalNamespace::AutomaticSFXVolumeParamsSO::get_minVolume() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolumeParamsSO::get_minVolume\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_minVolume\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AutomaticSFXVolumeParamsSO.get_maxVolume\r\nfloat GlobalNamespace::AutomaticSFXVolumeParamsSO::get_maxVolume() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolumeParamsSO::get_maxVolume\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_maxVolume\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AutomaticSFXVolumeParamsSO.get_volumeSmooth\r\nfloat GlobalNamespace::AutomaticSFXVolumeParamsSO::get_volumeSmooth() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AutomaticSFXVolumeParamsSO::get_volumeSmooth\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_volumeSmooth\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: BombCutSoundEffect\r\n#include \"GlobalNamespace\/BombCutSoundEffect.hpp\"\r\n\/\/ Including type: BombCutSoundEffect\/Pool\r\n#include \"GlobalNamespace\/BombCutSoundEffect_Pool.hpp\"\r\n\/\/ Including type: UnityEngine.AudioSource\r\n#include \"UnityEngine\/AudioSource.hpp\"\r\n\/\/ Including type: System.Action`1\r\n#include \"System\/Action_1.hpp\"\r\n\/\/ Including type: Saber\r\n#include \"GlobalNamespace\/Saber.hpp\"\r\n\/\/ Including type: UnityEngine.AudioClip\r\n#include \"UnityEngine\/AudioClip.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: BombCutSoundEffect.add_didFinishEvent\r\nvoid GlobalNamespace::BombCutSoundEffect::add_didFinishEvent(System::Action_1<GlobalNamespace::BombCutSoundEffect*>* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::BombCutSoundEffect::add_didFinishEvent\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"add_didFinishEvent\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: BombCutSoundEffect.remove_didFinishEvent\r\nvoid GlobalNamespace::BombCutSoundEffect::remove_didFinishEvent(System::Action_1<GlobalNamespace::BombCutSoundEffect*>* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::BombCutSoundEffect::remove_didFinishEvent\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"remove_didFinishEvent\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: BombCutSoundEffect.Init\r\nvoid GlobalNamespace::BombCutSoundEffect::Init(UnityEngine::AudioClip* audioClip, GlobalNamespace::Saber* saber, float volume) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::BombCutSoundEffect::Init\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Init\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(audioClip), ::il2cpp_utils::ExtractType(saber), ::il2cpp_utils::ExtractType(volume)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, audioClip, saber, volume);\r\n}\r\n\/\/ Autogenerated method: BombCutSoundEffect.LateUpdate\r\nvoid GlobalNamespace::BombCutSoundEffect::LateUpdate() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::BombCutSoundEffect::LateUpdate\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"LateUpdate\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: BombCutSoundEffect.StopPlayingAndFinish\r\nvoid GlobalNamespace::BombCutSoundEffect::StopPlayingAndFinish() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::BombCutSoundEffect::StopPlayingAndFinish\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"StopPlayingAndFinish\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: BombCutSoundEffect\/Pool\r\n#include \"GlobalNamespace\/BombCutSoundEffect_Pool.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: BombCutSoundEffectManager\r\n#include \"GlobalNamespace\/BombCutSoundEffectManager.hpp\"\r\n\/\/ Including type: UnityEngine.AudioClip\r\n#include \"UnityEngine\/AudioClip.hpp\"\r\n\/\/ Including type: BeatmapObjectManager\r\n#include \"GlobalNamespace\/BeatmapObjectManager.hpp\"\r\n\/\/ Including type: SaberManager\r\n#include \"GlobalNamespace\/SaberManager.hpp\"\r\n\/\/ Including type: RandomObjectPicker`1\r\n#include \"GlobalNamespace\/RandomObjectPicker_1.hpp\"\r\n\/\/ Including type: NoteController\r\n#include \"GlobalNamespace\/NoteController.hpp\"\r\n\/\/ Including type: NoteCutInfo\r\n#include \"GlobalNamespace\/NoteCutInfo.hpp\"\r\n\/\/ Including type: BombCutSoundEffect\/Pool\r\n#include \"GlobalNamespace\/BombCutSoundEffect_Pool.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: BombCutSoundEffectManager.Start\r\nvoid GlobalNamespace::BombCutSoundEffectManager::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::BombCutSoundEffectManager::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: BombCutSoundEffectManager.HandleNoteWasCut\r\nvoid GlobalNamespace::BombCutSoundEffectManager::HandleNoteWasCut(GlobalNamespace::NoteController* noteController, GlobalNamespace::NoteCutInfo& noteCutInfo) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::BombCutSoundEffectManager::HandleNoteWasCut\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleNoteWasCut\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(noteController), ::il2cpp_utils::ExtractType(noteCutInfo)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, noteController, noteCutInfo);\r\n}\r\n\/\/ Autogenerated method: BombCutSoundEffectManager.OnDestroy\r\nvoid GlobalNamespace::BombCutSoundEffectManager::OnDestroy() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::BombCutSoundEffectManager::OnDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: BombCutSoundEffectManager.HandleBombCutSoundEffectDidFinish\r\nvoid GlobalNamespace::BombCutSoundEffectManager::HandleBombCutSoundEffectDidFinish(GlobalNamespace::BombCutSoundEffect* bombCutSoundEffect) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::BombCutSoundEffectManager::HandleBombCutSoundEffectDidFinish\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleBombCutSoundEffectDidFinish\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(bombCutSoundEffect)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, bombCutSoundEffect);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: CrossFadeAudioSource\r\n#include \"GlobalNamespace\/CrossFadeAudioSource.hpp\"\r\n\/\/ Including type: UnityEngine.AudioSource\r\n#include \"UnityEngine\/AudioSource.hpp\"\r\n\/\/ Including type: AudioPitchGainEffect\r\n#include \"GlobalNamespace\/AudioPitchGainEffect.hpp\"\r\n\/\/ Including type: Tweening.TweeningManager\r\n#include \"Tweening\/TweeningManager.hpp\"\r\n\/\/ Including type: Tweening.Tween`1\r\n#include \"Tweening\/Tween_1.hpp\"\r\n\/\/ Including type: UnityEngine.AudioClip\r\n#include \"UnityEngine\/AudioClip.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: CrossFadeAudioSource.get_clip\r\nUnityEngine::AudioClip* GlobalNamespace::CrossFadeAudioSource::get_clip() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::get_clip\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_clip\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::AudioClip*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.set_clip\r\nvoid GlobalNamespace::CrossFadeAudioSource::set_clip(UnityEngine::AudioClip* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::set_clip\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_clip\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.set_pitch\r\nvoid GlobalNamespace::CrossFadeAudioSource::set_pitch(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::set_pitch\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_pitch\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.set_time\r\nvoid GlobalNamespace::CrossFadeAudioSource::set_time(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::set_time\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_time\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.get_isPlaying\r\nbool GlobalNamespace::CrossFadeAudioSource::get_isPlaying() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::get_isPlaying\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_isPlaying\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.Awake\r\nvoid GlobalNamespace::CrossFadeAudioSource::Awake() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::Awake\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Awake\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.OnDestroy\r\nvoid GlobalNamespace::CrossFadeAudioSource::OnDestroy() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::OnDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.PlayPitchGainEffect\r\nvoid GlobalNamespace::CrossFadeAudioSource::PlayPitchGainEffect(float volumeScale) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::PlayPitchGainEffect\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"PlayPitchGainEffect\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(volumeScale)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, volumeScale);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.InterruptLastPitchGainEffect\r\nvoid GlobalNamespace::CrossFadeAudioSource::InterruptLastPitchGainEffect() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::InterruptLastPitchGainEffect\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"InterruptLastPitchGainEffect\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.CrossFade\r\nvoid GlobalNamespace::CrossFadeAudioSource::CrossFade(float toSongTime, float toVolume) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::CrossFade\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"CrossFade\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(toSongTime), ::il2cpp_utils::ExtractType(toVolume)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, toSongTime, toVolume);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.Play\r\nvoid GlobalNamespace::CrossFadeAudioSource::Play() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::Play\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Play\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.Stop\r\nvoid GlobalNamespace::CrossFadeAudioSource::Stop() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::Stop\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Stop\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.<Awake>b__21_0\r\nvoid GlobalNamespace::CrossFadeAudioSource::$Awake$b__21_0(float val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::<Awake>b__21_0\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<Awake>b__21_0\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.<Awake>b__21_1\r\nvoid GlobalNamespace::CrossFadeAudioSource::$Awake$b__21_1(float val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::<Awake>b__21_1\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<Awake>b__21_1\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.<CrossFade>b__25_0\r\nvoid GlobalNamespace::CrossFadeAudioSource::$CrossFade$b__25_0(float val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::<CrossFade>b__25_0\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<CrossFade>b__25_0\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.<CrossFade>b__25_1\r\nvoid GlobalNamespace::CrossFadeAudioSource::$CrossFade$b__25_1(float val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::<CrossFade>b__25_1\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<CrossFade>b__25_1\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated method: CrossFadeAudioSource.<CrossFade>b__25_2\r\nvoid GlobalNamespace::CrossFadeAudioSource::$CrossFade$b__25_2() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::CrossFadeAudioSource::<CrossFade>b__25_2\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<CrossFade>b__25_2\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: DisableSpatializerOnOldWindows\r\n#include \"GlobalNamespace\/DisableSpatializerOnOldWindows.hpp\"\r\n\/\/ Including type: UnityEngine.AudioSource\r\n#include \"UnityEngine\/AudioSource.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: FadeOutSongPreviewPlayerOnSceneTransitionStart\r\n#include \"GlobalNamespace\/FadeOutSongPreviewPlayerOnSceneTransitionStart.hpp\"\r\n\/\/ Including type: AudioPlayerBase\r\n#include \"GlobalNamespace\/AudioPlayerBase.hpp\"\r\n\/\/ Including type: GameScenesManager\r\n#include \"GlobalNamespace\/GameScenesManager.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: FadeOutSongPreviewPlayerOnSceneTransitionStart.Start\r\nvoid GlobalNamespace::FadeOutSongPreviewPlayerOnSceneTransitionStart::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::FadeOutSongPreviewPlayerOnSceneTransitionStart::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: FadeOutSongPreviewPlayerOnSceneTransitionStart.OnDestroy\r\nvoid GlobalNamespace::FadeOutSongPreviewPlayerOnSceneTransitionStart::OnDestroy() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::FadeOutSongPreviewPlayerOnSceneTransitionStart::OnDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: FadeOutSongPreviewPlayerOnSceneTransitionStart.HandleGameScenesManagerTransitionDidStart\r\nvoid GlobalNamespace::FadeOutSongPreviewPlayerOnSceneTransitionStart::HandleGameScenesManagerTransitionDidStart(float duration) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::FadeOutSongPreviewPlayerOnSceneTransitionStart::HandleGameScenesManagerTransitionDidStart\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleGameScenesManagerTransitionDidStart\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(duration)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, duration);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: IAudioTimeSource\r\n#include \"GlobalNamespace\/IAudioTimeSource.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: IAudioTimeSource.get_songTime\r\nfloat GlobalNamespace::IAudioTimeSource::get_songTime() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::IAudioTimeSource::get_songTime\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_songTime\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: IAudioTimeSource.get_songEndTime\r\nfloat GlobalNamespace::IAudioTimeSource::get_songEndTime() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::IAudioTimeSource::get_songEndTime\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_songEndTime\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: IAudioTimeSource.get_isReady\r\nbool GlobalNamespace::IAudioTimeSource::get_isReady() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::IAudioTimeSource::get_isReady\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_isReady\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: MainAudioEffects\r\n#include \"GlobalNamespace\/MainAudioEffects.hpp\"\r\n\/\/ Including type: UnityEngine.AudioLowPassFilter\r\n#include \"UnityEngine\/AudioLowPassFilter.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.Int32 kDefaultCutoffFrequency\r\nint GlobalNamespace::MainAudioEffects::_get_kDefaultCutoffFrequency() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MainAudioEffects::_get_kDefaultCutoffFrequency\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>(\"\", \"MainAudioEffects\", \"kDefaultCutoffFrequency\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.Int32 kDefaultCutoffFrequency\r\nvoid GlobalNamespace::MainAudioEffects::_set_kDefaultCutoffFrequency(int value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MainAudioEffects::_set_kDefaultCutoffFrequency\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"MainAudioEffects\", \"kDefaultCutoffFrequency\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.Int32 kLowPassCutoffFrequency\r\nint GlobalNamespace::MainAudioEffects::_get_kLowPassCutoffFrequency() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MainAudioEffects::_get_kLowPassCutoffFrequency\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>(\"\", \"MainAudioEffects\", \"kLowPassCutoffFrequency\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.Int32 kLowPassCutoffFrequency\r\nvoid GlobalNamespace::MainAudioEffects::_set_kLowPassCutoffFrequency(int value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MainAudioEffects::_set_kLowPassCutoffFrequency\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"MainAudioEffects\", \"kLowPassCutoffFrequency\", value));\r\n}\r\n\/\/ Autogenerated method: MainAudioEffects.Start\r\nvoid GlobalNamespace::MainAudioEffects::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MainAudioEffects::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MainAudioEffects.LateUpdate\r\nvoid GlobalNamespace::MainAudioEffects::LateUpdate() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MainAudioEffects::LateUpdate\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"LateUpdate\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MainAudioEffects.ResumeNormalSound\r\nvoid GlobalNamespace::MainAudioEffects::ResumeNormalSound() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MainAudioEffects::ResumeNormalSound\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"ResumeNormalSound\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MainAudioEffects.TriggerLowPass\r\nvoid GlobalNamespace::MainAudioEffects::TriggerLowPass() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MainAudioEffects::TriggerLowPass\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"TriggerLowPass\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: INoteCutSoundEffectDidFinishEvent\r\n#include \"GlobalNamespace\/INoteCutSoundEffectDidFinishEvent.hpp\"\r\n\/\/ Including type: NoteCutSoundEffect\r\n#include \"GlobalNamespace\/NoteCutSoundEffect.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: INoteCutSoundEffectDidFinishEvent.HandleNoteCutSoundEffectDidFinish\r\nvoid GlobalNamespace::INoteCutSoundEffectDidFinishEvent::HandleNoteCutSoundEffectDidFinish(GlobalNamespace::NoteCutSoundEffect* noteCutSoundEffect) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::INoteCutSoundEffectDidFinishEvent::HandleNoteCutSoundEffectDidFinish\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleNoteCutSoundEffectDidFinish\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(noteCutSoundEffect)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, noteCutSoundEffect);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: NoteCutSoundEffect\r\n#include \"GlobalNamespace\/NoteCutSoundEffect.hpp\"\r\n\/\/ Including type: NoteCutSoundEffect\/Pool\r\n#include \"GlobalNamespace\/NoteCutSoundEffect_Pool.hpp\"\r\n\/\/ Including type: UnityEngine.AudioSource\r\n#include \"UnityEngine\/AudioSource.hpp\"\r\n\/\/ Including type: UnityEngine.AnimationCurve\r\n#include \"UnityEngine\/AnimationCurve.hpp\"\r\n\/\/ Including type: UnityEngine.AudioClip\r\n#include \"UnityEngine\/AudioClip.hpp\"\r\n\/\/ Including type: Saber\r\n#include \"GlobalNamespace\/Saber.hpp\"\r\n\/\/ Including type: NoteController\r\n#include \"GlobalNamespace\/NoteController.hpp\"\r\n\/\/ Including type: RandomObjectPicker`1\r\n#include \"GlobalNamespace\/RandomObjectPicker_1.hpp\"\r\n\/\/ Including type: LazyCopyHashSet`1\r\n#include \"GlobalNamespace\/LazyCopyHashSet_1.hpp\"\r\n\/\/ Including type: INoteCutSoundEffectDidFinishEvent\r\n#include \"GlobalNamespace\/INoteCutSoundEffectDidFinishEvent.hpp\"\r\n\/\/ Including type: ILazyCopyHashSet`1\r\n#include \"GlobalNamespace\/ILazyCopyHashSet_1.hpp\"\r\n\/\/ Including type: NoteCutInfo\r\n#include \"GlobalNamespace\/NoteCutInfo.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.Single kEndOverlap\r\nfloat GlobalNamespace::NoteCutSoundEffect::_get_kEndOverlap() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::_get_kEndOverlap\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<float>(\"\", \"NoteCutSoundEffect\", \"kEndOverlap\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.Single kEndOverlap\r\nvoid GlobalNamespace::NoteCutSoundEffect::_set_kEndOverlap(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::_set_kEndOverlap\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"NoteCutSoundEffect\", \"kEndOverlap\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.Single kEndFadeLength\r\nfloat GlobalNamespace::NoteCutSoundEffect::_get_kEndFadeLength() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::_get_kEndFadeLength\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<float>(\"\", \"NoteCutSoundEffect\", \"kEndFadeLength\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.Single kEndFadeLength\r\nvoid GlobalNamespace::NoteCutSoundEffect::_set_kEndFadeLength(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::_set_kEndFadeLength\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"NoteCutSoundEffect\", \"kEndFadeLength\", value));\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffect.get_didFinishEvent\r\nGlobalNamespace::ILazyCopyHashSet_1<GlobalNamespace::INoteCutSoundEffectDidFinishEvent*>* GlobalNamespace::NoteCutSoundEffect::get_didFinishEvent() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::get_didFinishEvent\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_didFinishEvent\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<GlobalNamespace::ILazyCopyHashSet_1<GlobalNamespace::INoteCutSoundEffectDidFinishEvent*>*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffect.set_volumeMultiplier\r\nvoid GlobalNamespace::NoteCutSoundEffect::set_volumeMultiplier(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::set_volumeMultiplier\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_volumeMultiplier\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffect.get_volumeMultiplier\r\nfloat GlobalNamespace::NoteCutSoundEffect::get_volumeMultiplier() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::get_volumeMultiplier\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_volumeMultiplier\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffect.get_time\r\nfloat GlobalNamespace::NoteCutSoundEffect::get_time() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::get_time\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_time\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffect.Awake\r\nvoid GlobalNamespace::NoteCutSoundEffect::Awake() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::Awake\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Awake\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffect.Start\r\nvoid GlobalNamespace::NoteCutSoundEffect::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffect.Init\r\nvoid GlobalNamespace::NoteCutSoundEffect::Init(UnityEngine::AudioClip* audioClip, GlobalNamespace::NoteController* noteController, double noteDSPTime, float aheadTime, float missedTimeOffset, float timeToPrevNote, float timeToNextNote, GlobalNamespace::Saber* saber, bool handleWrongSaberTypeAsGood, float volumeMultiplier, bool ignoreSaberSpeed, bool ignoreBadCuts) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::Init\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Init\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(audioClip), ::il2cpp_utils::ExtractType(noteController), ::il2cpp_utils::ExtractType(noteDSPTime), ::il2cpp_utils::ExtractType(aheadTime), ::il2cpp_utils::ExtractType(missedTimeOffset), ::il2cpp_utils::ExtractType(timeToPrevNote), ::il2cpp_utils::ExtractType(timeToNextNote), ::il2cpp_utils::ExtractType(saber), ::il2cpp_utils::ExtractType(handleWrongSaberTypeAsGood), ::il2cpp_utils::ExtractType(volumeMultiplier), ::il2cpp_utils::ExtractType(ignoreSaberSpeed), ::il2cpp_utils::ExtractType(ignoreBadCuts)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, audioClip, noteController, noteDSPTime, aheadTime, missedTimeOffset, timeToPrevNote, timeToNextNote, saber, handleWrongSaberTypeAsGood, volumeMultiplier, ignoreSaberSpeed, ignoreBadCuts);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffect.ComputeDSPTimes\r\nvoid GlobalNamespace::NoteCutSoundEffect::ComputeDSPTimes(double noteDSPTime, float aheadTime, float timeToPrevNote, float timeToNextNote) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::ComputeDSPTimes\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"ComputeDSPTimes\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(noteDSPTime), ::il2cpp_utils::ExtractType(aheadTime), ::il2cpp_utils::ExtractType(timeToPrevNote), ::il2cpp_utils::ExtractType(timeToNextNote)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, noteDSPTime, aheadTime, timeToPrevNote, timeToNextNote);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffect.LateUpdate\r\nvoid GlobalNamespace::NoteCutSoundEffect::LateUpdate() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::LateUpdate\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"LateUpdate\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffect.StopPlayingAndFinish\r\nvoid GlobalNamespace::NoteCutSoundEffect::StopPlayingAndFinish() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::StopPlayingAndFinish\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"StopPlayingAndFinish\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffect.NoteWasCut\r\nvoid GlobalNamespace::NoteCutSoundEffect::NoteWasCut(GlobalNamespace::NoteController* noteController, GlobalNamespace::NoteCutInfo& noteCutInfo) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffect::NoteWasCut\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"NoteWasCut\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(noteController), ::il2cpp_utils::ExtractType(noteCutInfo)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, noteController, noteCutInfo);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: NoteCutSoundEffect\/Pool\r\n#include \"GlobalNamespace\/NoteCutSoundEffect_Pool.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: NoteCutSoundEffectManager\r\n#include \"GlobalNamespace\/NoteCutSoundEffectManager.hpp\"\r\n\/\/ Including type: NoteCutSoundEffectManager\/InitData\r\n#include \"GlobalNamespace\/NoteCutSoundEffectManager_InitData.hpp\"\r\n\/\/ Including type: AudioManagerSO\r\n#include \"GlobalNamespace\/AudioManagerSO.hpp\"\r\n\/\/ Including type: UnityEngine.AudioClip\r\n#include \"UnityEngine\/AudioClip.hpp\"\r\n\/\/ Including type: BeatmapObjectManager\r\n#include \"GlobalNamespace\/BeatmapObjectManager.hpp\"\r\n\/\/ Including type: SaberManager\r\n#include \"GlobalNamespace\/SaberManager.hpp\"\r\n\/\/ Including type: AudioTimeSyncController\r\n#include \"GlobalNamespace\/AudioTimeSyncController.hpp\"\r\n\/\/ Including type: RandomObjectPicker`1\r\n#include \"GlobalNamespace\/RandomObjectPicker_1.hpp\"\r\n\/\/ Including type: MemoryPoolContainer`1\r\n#include \"GlobalNamespace\/MemoryPoolContainer_1.hpp\"\r\n\/\/ Including type: NoteController\r\n#include \"GlobalNamespace\/NoteController.hpp\"\r\n\/\/ Including type: NoteCutInfo\r\n#include \"GlobalNamespace\/NoteCutInfo.hpp\"\r\n\/\/ Including type: NoteCutSoundEffect\/Pool\r\n#include \"GlobalNamespace\/NoteCutSoundEffect_Pool.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.Int32 kMaxNumberOfEffects\r\nint GlobalNamespace::NoteCutSoundEffectManager::_get_kMaxNumberOfEffects() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffectManager::_get_kMaxNumberOfEffects\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>(\"\", \"NoteCutSoundEffectManager\", \"kMaxNumberOfEffects\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.Int32 kMaxNumberOfEffects\r\nvoid GlobalNamespace::NoteCutSoundEffectManager::_set_kMaxNumberOfEffects(int value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffectManager::_set_kMaxNumberOfEffects\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"NoteCutSoundEffectManager\", \"kMaxNumberOfEffects\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.Single kTwoNotesAtTheSameTimeVolumeMul\r\nfloat GlobalNamespace::NoteCutSoundEffectManager::_get_kTwoNotesAtTheSameTimeVolumeMul() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffectManager::_get_kTwoNotesAtTheSameTimeVolumeMul\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<float>(\"\", \"NoteCutSoundEffectManager\", \"kTwoNotesAtTheSameTimeVolumeMul\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.Single kTwoNotesAtTheSameTimeVolumeMul\r\nvoid GlobalNamespace::NoteCutSoundEffectManager::_set_kTwoNotesAtTheSameTimeVolumeMul(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffectManager::_set_kTwoNotesAtTheSameTimeVolumeMul\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"NoteCutSoundEffectManager\", \"kTwoNotesAtTheSameTimeVolumeMul\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.Single kDenseNotesVolumeMul\r\nfloat GlobalNamespace::NoteCutSoundEffectManager::_get_kDenseNotesVolumeMul() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffectManager::_get_kDenseNotesVolumeMul\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<float>(\"\", \"NoteCutSoundEffectManager\", \"kDenseNotesVolumeMul\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.Single kDenseNotesVolumeMul\r\nvoid GlobalNamespace::NoteCutSoundEffectManager::_set_kDenseNotesVolumeMul(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffectManager::_set_kDenseNotesVolumeMul\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"NoteCutSoundEffectManager\", \"kDenseNotesVolumeMul\", value));\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffectManager.get_handleWrongSaberTypeAsGood\r\nbool GlobalNamespace::NoteCutSoundEffectManager::get_handleWrongSaberTypeAsGood() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffectManager::get_handleWrongSaberTypeAsGood\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_handleWrongSaberTypeAsGood\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffectManager.set_handleWrongSaberTypeAsGood\r\nvoid GlobalNamespace::NoteCutSoundEffectManager::set_handleWrongSaberTypeAsGood(bool value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffectManager::set_handleWrongSaberTypeAsGood\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_handleWrongSaberTypeAsGood\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffectManager.Start\r\nvoid GlobalNamespace::NoteCutSoundEffectManager::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffectManager::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffectManager.OnDestroy\r\nvoid GlobalNamespace::NoteCutSoundEffectManager::OnDestroy() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffectManager::OnDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffectManager.HandleNoteWasSpawned\r\nvoid GlobalNamespace::NoteCutSoundEffectManager::HandleNoteWasSpawned(GlobalNamespace::NoteController* noteController) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffectManager::HandleNoteWasSpawned\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleNoteWasSpawned\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(noteController)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, noteController);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffectManager.HandleNoteWasCut\r\nvoid GlobalNamespace::NoteCutSoundEffectManager::HandleNoteWasCut(GlobalNamespace::NoteController* noteController, GlobalNamespace::NoteCutInfo& noteCutInfo) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffectManager::HandleNoteWasCut\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleNoteWasCut\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(noteController), ::il2cpp_utils::ExtractType(noteCutInfo)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, noteController, noteCutInfo);\r\n}\r\n\/\/ Autogenerated method: NoteCutSoundEffectManager.HandleNoteCutSoundEffectDidFinish\r\nvoid GlobalNamespace::NoteCutSoundEffectManager::HandleNoteCutSoundEffectDidFinish(GlobalNamespace::NoteCutSoundEffect* noteCutSoundEffect) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::NoteCutSoundEffectManager::HandleNoteCutSoundEffectDidFinish\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleNoteCutSoundEffectDidFinish\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(noteCutSoundEffect)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, noteCutSoundEffect);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: NoteCutSoundEffectManager\/InitData\r\n#include \"GlobalNamespace\/NoteCutSoundEffectManager_InitData.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: ObstacleSaberSoundEffect\r\n#include \"GlobalNamespace\/ObstacleSaberSoundEffect.hpp\"\r\n\/\/ Including type: ObstacleSaberSparkleEffectManager\r\n#include \"GlobalNamespace\/ObstacleSaberSparkleEffectManager.hpp\"\r\n\/\/ Including type: UnityEngine.AudioSource\r\n#include \"UnityEngine\/AudioSource.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private System.Single kSmooth\r\nfloat GlobalNamespace::ObstacleSaberSoundEffect::_get_kSmooth() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::ObstacleSaberSoundEffect::_get_kSmooth\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<float>(\"\", \"ObstacleSaberSoundEffect\", \"kSmooth\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private System.Single kSmooth\r\nvoid GlobalNamespace::ObstacleSaberSoundEffect::_set_kSmooth(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::ObstacleSaberSoundEffect::_set_kSmooth\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"ObstacleSaberSoundEffect\", \"kSmooth\", value));\r\n}\r\n\/\/ Autogenerated method: ObstacleSaberSoundEffect.Awake\r\nvoid GlobalNamespace::ObstacleSaberSoundEffect::Awake() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::ObstacleSaberSoundEffect::Awake\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Awake\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: ObstacleSaberSoundEffect.OnDestroy\r\nvoid GlobalNamespace::ObstacleSaberSoundEffect::OnDestroy() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::ObstacleSaberSoundEffect::OnDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: ObstacleSaberSoundEffect.LateUpdate\r\nvoid GlobalNamespace::ObstacleSaberSoundEffect::LateUpdate() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::ObstacleSaberSoundEffect::LateUpdate\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"LateUpdate\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: ObstacleSaberSoundEffect.HandleSparkleEffectDidStart\r\nvoid GlobalNamespace::ObstacleSaberSoundEffect::HandleSparkleEffectDidStart(GlobalNamespace::SaberType saberType) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::ObstacleSaberSoundEffect::HandleSparkleEffectDidStart\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleSparkleEffectDidStart\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(saberType)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, saberType);\r\n}\r\n\/\/ Autogenerated method: ObstacleSaberSoundEffect.HandleSparkleEffecDidEnd\r\nvoid GlobalNamespace::ObstacleSaberSoundEffect::HandleSparkleEffecDidEnd(GlobalNamespace::SaberType saberType) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::ObstacleSaberSoundEffect::HandleSparkleEffecDidEnd\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleSparkleEffecDidEnd\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(saberType)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, saberType);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: PlayAudioOnGameEventController\r\n#include \"GlobalNamespace\/PlayAudioOnGameEventController.hpp\"\r\n\/\/ Including type: PlayAudioOnGameEventController\/EventAudioBinding\r\n#include \"GlobalNamespace\/PlayAudioOnGameEventController_EventAudioBinding.hpp\"\r\n\/\/ Including type: AudioClipQueue\r\n#include \"GlobalNamespace\/AudioClipQueue.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: PlayAudioOnGameEventController.Awake\r\nvoid GlobalNamespace::PlayAudioOnGameEventController::Awake() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlayAudioOnGameEventController::Awake\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Awake\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: PlayAudioOnGameEventController.OnDestroy\r\nvoid GlobalNamespace::PlayAudioOnGameEventController::OnDestroy() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlayAudioOnGameEventController::OnDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: PlayAudioOnGameEventController\/EventAudioBinding\r\n#include \"GlobalNamespace\/PlayAudioOnGameEventController_EventAudioBinding.hpp\"\r\n\/\/ Including type: Signal\r\n#include \"GlobalNamespace\/Signal.hpp\"\r\n\/\/ Including type: LocalizedAudioClipSO\r\n#include \"GlobalNamespace\/LocalizedAudioClipSO.hpp\"\r\n\/\/ Including type: AudioClipQueue\r\n#include \"GlobalNamespace\/AudioClipQueue.hpp\"\r\n\/\/ Including type: RandomObjectPicker`1\r\n#include \"GlobalNamespace\/RandomObjectPicker_1.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: PlayAudioOnGameEventController\/EventAudioBinding.Init\r\nvoid GlobalNamespace::PlayAudioOnGameEventController::EventAudioBinding::Init(GlobalNamespace::AudioClipQueue* audioClipQueue) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlayAudioOnGameEventController::EventAudioBinding::Init\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Init\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(audioClipQueue)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, audioClipQueue);\r\n}\r\n\/\/ Autogenerated method: PlayAudioOnGameEventController\/EventAudioBinding.Deinit\r\nvoid GlobalNamespace::PlayAudioOnGameEventController::EventAudioBinding::Deinit() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlayAudioOnGameEventController::EventAudioBinding::Deinit\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Deinit\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: PlayAudioOnGameEventController\/EventAudioBinding.HandleGameEvent\r\nvoid GlobalNamespace::PlayAudioOnGameEventController::EventAudioBinding::HandleGameEvent() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlayAudioOnGameEventController::EventAudioBinding::HandleGameEvent\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleGameEvent\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: ResetPitchOnGameplayFinished\r\n#include \"GlobalNamespace\/ResetPitchOnGameplayFinished.hpp\"\r\n\/\/ Including type: GameplayLevelSceneTransitionEvents\r\n#include \"GlobalNamespace\/GameplayLevelSceneTransitionEvents.hpp\"\r\n\/\/ Including type: AudioManagerSO\r\n#include \"GlobalNamespace\/AudioManagerSO.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: ResetPitchOnGameplayFinished.HandleAnyGameplayLevelDidFinish\r\nvoid GlobalNamespace::ResetPitchOnGameplayFinished::HandleAnyGameplayLevelDidFinish() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::ResetPitchOnGameplayFinished::HandleAnyGameplayLevelDidFinish\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleAnyGameplayLevelDidFinish\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: ResetPitchOnGameplayFinished.Finalize\r\nvoid GlobalNamespace::ResetPitchOnGameplayFinished::Finalize() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::ResetPitchOnGameplayFinished::Finalize\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Finalize\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: SimpleAudioPlayer\r\n#include \"GlobalNamespace\/SimpleAudioPlayer.hpp\"\r\n\/\/ Including type: UnityEngine.AudioClip\r\n#include \"UnityEngine\/AudioClip.hpp\"\r\n\/\/ Including type: UnityEngine.AudioSource\r\n#include \"UnityEngine\/AudioSource.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: SimpleAudioPlayer.Start\r\nvoid GlobalNamespace::SimpleAudioPlayer::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SimpleAudioPlayer::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SimpleAudioPlayer.Update\r\nvoid GlobalNamespace::SimpleAudioPlayer::Update() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SimpleAudioPlayer::Update\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Update\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SimpleAudioPlayer.FadeIn\r\nvoid GlobalNamespace::SimpleAudioPlayer::FadeIn(float duration) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SimpleAudioPlayer::FadeIn\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"FadeIn\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(duration)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, duration);\r\n}\r\n\/\/ Autogenerated method: SimpleAudioPlayer.get_activeAudioClip\r\nUnityEngine::AudioClip* GlobalNamespace::SimpleAudioPlayer::get_activeAudioClip() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SimpleAudioPlayer::get_activeAudioClip\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_activeAudioClip\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::AudioClip*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SimpleAudioPlayer.FadeOut\r\nvoid GlobalNamespace::SimpleAudioPlayer::FadeOut(float duration) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SimpleAudioPlayer::FadeOut\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"FadeOut\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(duration)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, duration);\r\n}\r\n\/\/ Autogenerated method: SimpleAudioPlayer.PauseCurrentChannel\r\nvoid GlobalNamespace::SimpleAudioPlayer::PauseCurrentChannel() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SimpleAudioPlayer::PauseCurrentChannel\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"PauseCurrentChannel\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SimpleAudioPlayer.UnPauseCurrentChannel\r\nvoid GlobalNamespace::SimpleAudioPlayer::UnPauseCurrentChannel() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SimpleAudioPlayer::UnPauseCurrentChannel\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"UnPauseCurrentChannel\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: SongPreviewPlayer\r\n#include \"GlobalNamespace\/SongPreviewPlayer.hpp\"\r\n\/\/ Including type: SongPreviewPlayer\/InitData\r\n#include \"GlobalNamespace\/SongPreviewPlayer_InitData.hpp\"\r\n\/\/ Including type: SongPreviewPlayer\/AudioSourceParams\r\n#include \"GlobalNamespace\/SongPreviewPlayer_AudioSourceParams.hpp\"\r\n\/\/ Including type: SongPreviewPlayer\/AudioSourceVolumeController\r\n#include \"GlobalNamespace\/SongPreviewPlayer_AudioSourceVolumeController.hpp\"\r\n\/\/ Including type: SongPreviewPlayer\/<CrossFadeAfterDelayCoroutine>d__27\r\n#include \"GlobalNamespace\/SongPreviewPlayer_-CrossFadeAfterDelayCoroutine-d__27.hpp\"\r\n\/\/ Including type: UnityEngine.AudioSource\r\n#include \"UnityEngine\/AudioSource.hpp\"\r\n\/\/ Including type: UnityEngine.AudioClip\r\n#include \"UnityEngine\/AudioClip.hpp\"\r\n\/\/ Including type: AudioManagerSO\r\n#include \"GlobalNamespace\/AudioManagerSO.hpp\"\r\n\/\/ Including type: System.Collections.IEnumerator\r\n#include \"System\/Collections\/IEnumerator.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: SongPreviewPlayer.Awake\r\nvoid GlobalNamespace::SongPreviewPlayer::Awake() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::Awake\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Awake\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.Start\r\nvoid GlobalNamespace::SongPreviewPlayer::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.OnEnable\r\nvoid GlobalNamespace::SongPreviewPlayer::OnEnable() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::OnEnable\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnEnable\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.CrossFadeAfterDelayCoroutine\r\nSystem::Collections::IEnumerator* GlobalNamespace::SongPreviewPlayer::CrossFadeAfterDelayCoroutine(float delay) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::CrossFadeAfterDelayCoroutine\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"CrossFadeAfterDelayCoroutine\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(delay)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Collections::IEnumerator*, false>(this, ___internal__method, delay);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.OnDisable\r\nvoid GlobalNamespace::SongPreviewPlayer::OnDisable() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::OnDisable\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDisable\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.Update\r\nvoid GlobalNamespace::SongPreviewPlayer::Update() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::Update\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Update\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.CrossFadeToDefault\r\nvoid GlobalNamespace::SongPreviewPlayer::CrossFadeToDefault() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::CrossFadeToDefault\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"CrossFadeToDefault\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.CrossfadeToNewDefault\r\nvoid GlobalNamespace::SongPreviewPlayer::CrossfadeToNewDefault(UnityEngine::AudioClip* audioClip) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::CrossfadeToNewDefault\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"CrossfadeToNewDefault\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(audioClip)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, audioClip);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.CrossfadeTo\r\nvoid GlobalNamespace::SongPreviewPlayer::CrossfadeTo(UnityEngine::AudioClip* audioClip, float startTime, float duration) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::CrossfadeTo\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"CrossfadeTo\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(audioClip), ::il2cpp_utils::ExtractType(startTime), ::il2cpp_utils::ExtractType(duration)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, audioClip, startTime, duration);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.CrossfadeTo\r\nvoid GlobalNamespace::SongPreviewPlayer::CrossfadeTo(UnityEngine::AudioClip* audioClip, float startTime, float duration, bool isDefault) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::CrossfadeTo\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"CrossfadeTo\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(audioClip), ::il2cpp_utils::ExtractType(startTime), ::il2cpp_utils::ExtractType(duration), ::il2cpp_utils::ExtractType(isDefault)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, audioClip, startTime, duration, isDefault);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.CrossfadeToDefault\r\nvoid GlobalNamespace::SongPreviewPlayer::CrossfadeToDefault() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::CrossfadeToDefault\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"CrossfadeToDefault\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.get_activeAudioClip\r\nUnityEngine::AudioClip* GlobalNamespace::SongPreviewPlayer::get_activeAudioClip() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::get_activeAudioClip\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_activeAudioClip\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::AudioClip*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.PauseCurrentChannel\r\nvoid GlobalNamespace::SongPreviewPlayer::PauseCurrentChannel() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::PauseCurrentChannel\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"PauseCurrentChannel\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.UnPauseCurrentChannel\r\nvoid GlobalNamespace::SongPreviewPlayer::UnPauseCurrentChannel() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::UnPauseCurrentChannel\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"UnPauseCurrentChannel\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer.FadeOut\r\nvoid GlobalNamespace::SongPreviewPlayer::FadeOut(float duration) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::FadeOut\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"FadeOut\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(duration)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, duration);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: SongPreviewPlayer\/InitData\r\n#include \"GlobalNamespace\/SongPreviewPlayer_InitData.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: SongPreviewPlayer\/AudioSourceParams\r\n#include \"GlobalNamespace\/SongPreviewPlayer_AudioSourceParams.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: SongPreviewPlayer\/AudioSourceParams.get_position\r\nUnityEngine::Vector3 GlobalNamespace::SongPreviewPlayer::AudioSourceParams::get_position() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::AudioSourceParams::get_position\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_position\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer\/AudioSourceParams.get_reverbZoneMix\r\nfloat GlobalNamespace::SongPreviewPlayer::AudioSourceParams::get_reverbZoneMix() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::AudioSourceParams::get_reverbZoneMix\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_reverbZoneMix\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer\/AudioSourceParams.get_spatialBlend\r\nfloat GlobalNamespace::SongPreviewPlayer::AudioSourceParams::get_spatialBlend() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::AudioSourceParams::get_spatialBlend\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_spatialBlend\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer\/AudioSourceParams.get_spread\r\nfloat GlobalNamespace::SongPreviewPlayer::AudioSourceParams::get_spread() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::AudioSourceParams::get_spread\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_spread\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: SongPreviewPlayer\/AudioSourceVolumeController\r\n#include \"GlobalNamespace\/SongPreviewPlayer_AudioSourceVolumeController.hpp\"\r\n\/\/ Including type: UnityEngine.AudioSource\r\n#include \"UnityEngine\/AudioSource.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: SongPreviewPlayer\/AudioSourceVolumeController.set_volume\r\nvoid GlobalNamespace::SongPreviewPlayer::AudioSourceVolumeController::set_volume(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::AudioSourceVolumeController::set_volume\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_volume\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer\/AudioSourceVolumeController.get_volume\r\nfloat GlobalNamespace::SongPreviewPlayer::AudioSourceVolumeController::get_volume() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::AudioSourceVolumeController::get_volume\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_volume\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer\/AudioSourceVolumeController.get_maxVolume\r\nfloat GlobalNamespace::SongPreviewPlayer::AudioSourceVolumeController::get_maxVolume() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::AudioSourceVolumeController::get_maxVolume\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_maxVolume\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer\/AudioSourceVolumeController.set_maxVolume\r\nvoid GlobalNamespace::SongPreviewPlayer::AudioSourceVolumeController::set_maxVolume(float value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::AudioSourceVolumeController::set_maxVolume\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_maxVolume\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: SongPreviewPlayer\/<CrossFadeAfterDelayCoroutine>d__27\r\n#include \"GlobalNamespace\/SongPreviewPlayer_-CrossFadeAfterDelayCoroutine-d__27.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: SongPreviewPlayer\/<CrossFadeAfterDelayCoroutine>d__27.System.IDisposable.Dispose\r\nvoid GlobalNamespace::SongPreviewPlayer::$CrossFadeAfterDelayCoroutine$d__27::System_IDisposable_Dispose() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::$CrossFadeAfterDelayCoroutine$d__27::System.IDisposable.Dispose\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.IDisposable.Dispose\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer\/<CrossFadeAfterDelayCoroutine>d__27.MoveNext\r\nbool GlobalNamespace::SongPreviewPlayer::$CrossFadeAfterDelayCoroutine$d__27::MoveNext() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::$CrossFadeAfterDelayCoroutine$d__27::MoveNext\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"MoveNext\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer\/<CrossFadeAfterDelayCoroutine>d__27.System.Collections.Generic.IEnumerator<System.Object>.get_Current\r\n::Il2CppObject* GlobalNamespace::SongPreviewPlayer::$CrossFadeAfterDelayCoroutine$d__27::System_Collections_Generic_IEnumerator$System_Object$_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::$CrossFadeAfterDelayCoroutine$d__27::System.Collections.Generic.IEnumerator<System.Object>.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.Generic.IEnumerator<System.Object>.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer\/<CrossFadeAfterDelayCoroutine>d__27.System.Collections.IEnumerator.Reset\r\nvoid GlobalNamespace::SongPreviewPlayer::$CrossFadeAfterDelayCoroutine$d__27::System_Collections_IEnumerator_Reset() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::$CrossFadeAfterDelayCoroutine$d__27::System.Collections.IEnumerator.Reset\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.Reset\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayer\/<CrossFadeAfterDelayCoroutine>d__27.System.Collections.IEnumerator.get_Current\r\n::Il2CppObject* GlobalNamespace::SongPreviewPlayer::$CrossFadeAfterDelayCoroutine$d__27::System_Collections_IEnumerator_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayer::$CrossFadeAfterDelayCoroutine$d__27::System.Collections.IEnumerator.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: SongPreviewPlayerPauseOnInputFocusLost\r\n#include \"GlobalNamespace\/SongPreviewPlayerPauseOnInputFocusLost.hpp\"\r\n\/\/ Including type: AudioPlayerBase\r\n#include \"GlobalNamespace\/AudioPlayerBase.hpp\"\r\n\/\/ Including type: IVRPlatformHelper\r\n#include \"GlobalNamespace\/IVRPlatformHelper.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: SongPreviewPlayerPauseOnInputFocusLost.Start\r\nvoid GlobalNamespace::SongPreviewPlayerPauseOnInputFocusLost::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayerPauseOnInputFocusLost::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayerPauseOnInputFocusLost.OnDestroy\r\nvoid GlobalNamespace::SongPreviewPlayerPauseOnInputFocusLost::OnDestroy() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayerPauseOnInputFocusLost::OnDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayerPauseOnInputFocusLost.HandleInputFocusCaptured\r\nvoid GlobalNamespace::SongPreviewPlayerPauseOnInputFocusLost::HandleInputFocusCaptured() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayerPauseOnInputFocusLost::HandleInputFocusCaptured\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleInputFocusCaptured\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: SongPreviewPlayerPauseOnInputFocusLost.HandleInputFocusReleased\r\nvoid GlobalNamespace::SongPreviewPlayerPauseOnInputFocusLost::HandleInputFocusReleased() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::SongPreviewPlayerPauseOnInputFocusLost::HandleInputFocusReleased\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleInputFocusReleased\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AnimatedAvatarPoseController\r\n#include \"GlobalNamespace\/AnimatedAvatarPoseController.hpp\"\r\n\/\/ Including type: AvatarPoseController\r\n#include \"GlobalNamespace\/AvatarPoseController.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AnimatedAvatarPoseController.LateUpdate\r\nvoid GlobalNamespace::AnimatedAvatarPoseController::LateUpdate() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AnimatedAvatarPoseController::LateUpdate\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"LateUpdate\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AvatarColorPropertyIds\r\n#include \"GlobalNamespace\/AvatarColorPropertyIds.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ [DoesNotRequireDomainReloadInitAttribute] Offset: 0xE152C0\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public readonly System.Int32 colorPropertyId\r\nint GlobalNamespace::AvatarColorPropertyIds::_get_colorPropertyId() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarColorPropertyIds::_get_colorPropertyId\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>(\"\", \"AvatarColorPropertyIds\", \"colorPropertyId\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public readonly System.Int32 colorPropertyId\r\nvoid GlobalNamespace::AvatarColorPropertyIds::_set_colorPropertyId(int value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarColorPropertyIds::_set_colorPropertyId\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AvatarColorPropertyIds\", \"colorPropertyId\", value));\r\n}\r\n\/\/ [DoesNotRequireDomainReloadInitAttribute] Offset: 0xE152D0\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public readonly System.Int32 rimLightColorPropertyId\r\nint GlobalNamespace::AvatarColorPropertyIds::_get_rimLightColorPropertyId() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarColorPropertyIds::_get_rimLightColorPropertyId\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>(\"\", \"AvatarColorPropertyIds\", \"rimLightColorPropertyId\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public readonly System.Int32 rimLightColorPropertyId\r\nvoid GlobalNamespace::AvatarColorPropertyIds::_set_rimLightColorPropertyId(int value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarColorPropertyIds::_set_rimLightColorPropertyId\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AvatarColorPropertyIds\", \"rimLightColorPropertyId\", value));\r\n}\r\n\/\/ [DoesNotRequireDomainReloadInitAttribute] Offset: 0xE152E0\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public readonly System.Int32 uvColorsPropertyId\r\nint GlobalNamespace::AvatarColorPropertyIds::_get_uvColorsPropertyId() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarColorPropertyIds::_get_uvColorsPropertyId\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>(\"\", \"AvatarColorPropertyIds\", \"uvColorsPropertyId\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public readonly System.Int32 uvColorsPropertyId\r\nvoid GlobalNamespace::AvatarColorPropertyIds::_set_uvColorsPropertyId(int value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarColorPropertyIds::_set_uvColorsPropertyId\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AvatarColorPropertyIds\", \"uvColorsPropertyId\", value));\r\n}\r\n\/\/ [DoesNotRequireDomainReloadInitAttribute] Offset: 0xE152F0\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public readonly System.Int32 uvRimLightColorsPropertyId\r\nint GlobalNamespace::AvatarColorPropertyIds::_get_uvRimLightColorsPropertyId() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarColorPropertyIds::_get_uvRimLightColorsPropertyId\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>(\"\", \"AvatarColorPropertyIds\", \"uvRimLightColorsPropertyId\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public readonly System.Int32 uvRimLightColorsPropertyId\r\nvoid GlobalNamespace::AvatarColorPropertyIds::_set_uvRimLightColorsPropertyId(int value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarColorPropertyIds::_set_uvRimLightColorsPropertyId\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AvatarColorPropertyIds\", \"uvRimLightColorsPropertyId\", value));\r\n}\r\n\/\/ [DoesNotRequireDomainReloadInitAttribute] Offset: 0xE15300\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public readonly System.Int32 segmentToHighlightPropertyId\r\nint GlobalNamespace::AvatarColorPropertyIds::_get_segmentToHighlightPropertyId() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarColorPropertyIds::_get_segmentToHighlightPropertyId\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>(\"\", \"AvatarColorPropertyIds\", \"segmentToHighlightPropertyId\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public readonly System.Int32 segmentToHighlightPropertyId\r\nvoid GlobalNamespace::AvatarColorPropertyIds::_set_segmentToHighlightPropertyId(int value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarColorPropertyIds::_set_segmentToHighlightPropertyId\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AvatarColorPropertyIds\", \"segmentToHighlightPropertyId\", value));\r\n}\r\n\/\/ Autogenerated method: AvatarColorPropertyIds..cctor\r\nvoid GlobalNamespace::AvatarColorPropertyIds::_cctor() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarColorPropertyIds::.cctor\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(\"\", \"AvatarColorPropertyIds\", \".cctor\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AvatarHeadOffset\r\n#include \"GlobalNamespace\/AvatarHeadOffset.hpp\"\r\n\/\/ Including type: AvatarPoseController\r\n#include \"GlobalNamespace\/AvatarPoseController.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AvatarHeadOffset.Start\r\nvoid GlobalNamespace::AvatarHeadOffset::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarHeadOffset::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarHeadOffset.OnDestroy\r\nvoid GlobalNamespace::AvatarHeadOffset::OnDestroy() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarHeadOffset::OnDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarHeadOffset.HandleMultiplayerAvatarPoseControllerDidUpdatePose\r\nvoid GlobalNamespace::AvatarHeadOffset::HandleMultiplayerAvatarPoseControllerDidUpdatePose(UnityEngine::Vector3 headLocalPosition) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarHeadOffset::HandleMultiplayerAvatarPoseControllerDidUpdatePose\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleMultiplayerAvatarPoseControllerDidUpdatePose\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(headLocalPosition)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, headLocalPosition);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AvatarPoseController\r\n#include \"GlobalNamespace\/AvatarPoseController.hpp\"\r\n\/\/ Including type: AvatarPoseController\/PositionsWillBeSetDelegate\r\n#include \"GlobalNamespace\/AvatarPoseController_PositionsWillBeSetDelegate.hpp\"\r\n\/\/ Including type: AvatarPoseController\/LatePositionsWillBeSetDelegate\r\n#include \"GlobalNamespace\/AvatarPoseController_LatePositionsWillBeSetDelegate.hpp\"\r\n\/\/ Including type: AvatarPoseController\/RotationsWillBeSetDelegate\r\n#include \"GlobalNamespace\/AvatarPoseController_RotationsWillBeSetDelegate.hpp\"\r\n\/\/ Including type: UnityEngine.Transform\r\n#include \"UnityEngine\/Transform.hpp\"\r\n\/\/ Including type: HeadBodyOffsetSO\r\n#include \"GlobalNamespace\/HeadBodyOffsetSO.hpp\"\r\n\/\/ Including type: System.Action`1\r\n#include \"System\/Action_1.hpp\"\r\n\/\/ Including type: UnityEngine.Quaternion\r\n#include \"UnityEngine\/Quaternion.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AvatarPoseController.get_earlyPositionsWillBeSetCallback\r\nGlobalNamespace::AvatarPoseController::PositionsWillBeSetDelegate* GlobalNamespace::AvatarPoseController::get_earlyPositionsWillBeSetCallback() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::get_earlyPositionsWillBeSetCallback\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_earlyPositionsWillBeSetCallback\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<GlobalNamespace::AvatarPoseController::PositionsWillBeSetDelegate*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController.set_earlyPositionsWillBeSetCallback\r\nvoid GlobalNamespace::AvatarPoseController::set_earlyPositionsWillBeSetCallback(GlobalNamespace::AvatarPoseController::PositionsWillBeSetDelegate* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::set_earlyPositionsWillBeSetCallback\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_earlyPositionsWillBeSetCallback\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController.get_latePositionsWillBeSetCallback\r\nGlobalNamespace::AvatarPoseController::LatePositionsWillBeSetDelegate* GlobalNamespace::AvatarPoseController::get_latePositionsWillBeSetCallback() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::get_latePositionsWillBeSetCallback\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_latePositionsWillBeSetCallback\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<GlobalNamespace::AvatarPoseController::LatePositionsWillBeSetDelegate*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController.set_latePositionsWillBeSetCallback\r\nvoid GlobalNamespace::AvatarPoseController::set_latePositionsWillBeSetCallback(GlobalNamespace::AvatarPoseController::LatePositionsWillBeSetDelegate* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::set_latePositionsWillBeSetCallback\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_latePositionsWillBeSetCallback\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController.get_earlyRotationsWillBeSetCallback\r\nGlobalNamespace::AvatarPoseController::RotationsWillBeSetDelegate* GlobalNamespace::AvatarPoseController::get_earlyRotationsWillBeSetCallback() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::get_earlyRotationsWillBeSetCallback\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_earlyRotationsWillBeSetCallback\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<GlobalNamespace::AvatarPoseController::RotationsWillBeSetDelegate*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController.set_earlyRotationsWillBeSetCallback\r\nvoid GlobalNamespace::AvatarPoseController::set_earlyRotationsWillBeSetCallback(GlobalNamespace::AvatarPoseController::RotationsWillBeSetDelegate* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::set_earlyRotationsWillBeSetCallback\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_earlyRotationsWillBeSetCallback\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController.add_didUpdatePoseEvent\r\nvoid GlobalNamespace::AvatarPoseController::add_didUpdatePoseEvent(System::Action_1<UnityEngine::Vector3>* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::add_didUpdatePoseEvent\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"add_didUpdatePoseEvent\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController.remove_didUpdatePoseEvent\r\nvoid GlobalNamespace::AvatarPoseController::remove_didUpdatePoseEvent(System::Action_1<UnityEngine::Vector3>* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::remove_didUpdatePoseEvent\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"remove_didUpdatePoseEvent\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController.UpdateTransforms\r\nvoid GlobalNamespace::AvatarPoseController::UpdateTransforms(UnityEngine::Vector3 headPosition, UnityEngine::Vector3 leftHandPosition, UnityEngine::Vector3 rightHandPosition, UnityEngine::Quaternion headRotation, UnityEngine::Quaternion leftHandRotation, UnityEngine::Quaternion rightHandRotation) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::UpdateTransforms\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"UpdateTransforms\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(headPosition), ::il2cpp_utils::ExtractType(leftHandPosition), ::il2cpp_utils::ExtractType(rightHandPosition), ::il2cpp_utils::ExtractType(headRotation), ::il2cpp_utils::ExtractType(leftHandRotation), ::il2cpp_utils::ExtractType(rightHandRotation)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, headPosition, leftHandPosition, rightHandPosition, headRotation, leftHandRotation, rightHandRotation);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController.UpdateBodyPosition\r\nvoid GlobalNamespace::AvatarPoseController::UpdateBodyPosition() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::UpdateBodyPosition\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"UpdateBodyPosition\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AvatarPoseController\/PositionsWillBeSetDelegate\r\n#include \"GlobalNamespace\/AvatarPoseController_PositionsWillBeSetDelegate.hpp\"\r\n\/\/ Including type: UnityEngine.Vector3\r\n#include \"UnityEngine\/Vector3.hpp\"\r\n\/\/ Including type: System.IAsyncResult\r\n#include \"System\/IAsyncResult.hpp\"\r\n\/\/ Including type: System.AsyncCallback\r\n#include \"System\/AsyncCallback.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AvatarPoseController\/PositionsWillBeSetDelegate.Invoke\r\nvoid GlobalNamespace::AvatarPoseController::PositionsWillBeSetDelegate::Invoke(UnityEngine::Vector3 headPosition, UnityEngine::Vector3 leftHandPosition, UnityEngine::Vector3 rightHandPosition, UnityEngine::Vector3& newHeadPosition, UnityEngine::Vector3& newLeftHandPosition, UnityEngine::Vector3& newRightHandPosition) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::PositionsWillBeSetDelegate::Invoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Invoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(headPosition), ::il2cpp_utils::ExtractType(leftHandPosition), ::il2cpp_utils::ExtractType(rightHandPosition), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, headPosition, leftHandPosition, rightHandPosition, newHeadPosition, newLeftHandPosition, newRightHandPosition);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController\/PositionsWillBeSetDelegate.BeginInvoke\r\nSystem::IAsyncResult* GlobalNamespace::AvatarPoseController::PositionsWillBeSetDelegate::BeginInvoke(UnityEngine::Vector3 headPosition, UnityEngine::Vector3 leftHandPosition, UnityEngine::Vector3 rightHandPosition, UnityEngine::Vector3& newHeadPosition, UnityEngine::Vector3& newLeftHandPosition, UnityEngine::Vector3& newRightHandPosition, System::AsyncCallback* callback, ::Il2CppObject* object) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::PositionsWillBeSetDelegate::BeginInvoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"BeginInvoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(headPosition), ::il2cpp_utils::ExtractType(leftHandPosition), ::il2cpp_utils::ExtractType(rightHandPosition), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractType(callback), ::il2cpp_utils::ExtractType(object)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::IAsyncResult*, false>(this, ___internal__method, headPosition, leftHandPosition, rightHandPosition, newHeadPosition, newLeftHandPosition, newRightHandPosition, callback, object);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController\/PositionsWillBeSetDelegate.EndInvoke\r\nvoid GlobalNamespace::AvatarPoseController::PositionsWillBeSetDelegate::EndInvoke(UnityEngine::Vector3& newHeadPosition, UnityEngine::Vector3& newLeftHandPosition, UnityEngine::Vector3& newRightHandPosition, System::IAsyncResult* result) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::PositionsWillBeSetDelegate::EndInvoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"EndInvoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractType(result)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, newHeadPosition, newLeftHandPosition, newRightHandPosition, result);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AvatarPoseController\/LatePositionsWillBeSetDelegate\r\n#include \"GlobalNamespace\/AvatarPoseController_LatePositionsWillBeSetDelegate.hpp\"\r\n\/\/ Including type: UnityEngine.Quaternion\r\n#include \"UnityEngine\/Quaternion.hpp\"\r\n\/\/ Including type: UnityEngine.Vector3\r\n#include \"UnityEngine\/Vector3.hpp\"\r\n\/\/ Including type: System.IAsyncResult\r\n#include \"System\/IAsyncResult.hpp\"\r\n\/\/ Including type: System.AsyncCallback\r\n#include \"System\/AsyncCallback.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AvatarPoseController\/LatePositionsWillBeSetDelegate.Invoke\r\nvoid GlobalNamespace::AvatarPoseController::LatePositionsWillBeSetDelegate::Invoke(UnityEngine::Quaternion headRotation, UnityEngine::Vector3 headPosition, UnityEngine::Vector3 leftHandPosition, UnityEngine::Vector3 rightHandPosition, UnityEngine::Vector3& newHeadPosition, UnityEngine::Vector3& newLeftHandPosition, UnityEngine::Vector3& newRightHandPosition) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::LatePositionsWillBeSetDelegate::Invoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Invoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(headRotation), ::il2cpp_utils::ExtractType(headPosition), ::il2cpp_utils::ExtractType(leftHandPosition), ::il2cpp_utils::ExtractType(rightHandPosition), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, headRotation, headPosition, leftHandPosition, rightHandPosition, newHeadPosition, newLeftHandPosition, newRightHandPosition);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController\/LatePositionsWillBeSetDelegate.BeginInvoke\r\nSystem::IAsyncResult* GlobalNamespace::AvatarPoseController::LatePositionsWillBeSetDelegate::BeginInvoke(UnityEngine::Quaternion headRotation, UnityEngine::Vector3 headPosition, UnityEngine::Vector3 leftHandPosition, UnityEngine::Vector3 rightHandPosition, UnityEngine::Vector3& newHeadPosition, UnityEngine::Vector3& newLeftHandPosition, UnityEngine::Vector3& newRightHandPosition, System::AsyncCallback* callback, ::Il2CppObject* object) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::LatePositionsWillBeSetDelegate::BeginInvoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"BeginInvoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(headRotation), ::il2cpp_utils::ExtractType(headPosition), ::il2cpp_utils::ExtractType(leftHandPosition), ::il2cpp_utils::ExtractType(rightHandPosition), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractType(callback), ::il2cpp_utils::ExtractType(object)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::IAsyncResult*, false>(this, ___internal__method, headRotation, headPosition, leftHandPosition, rightHandPosition, newHeadPosition, newLeftHandPosition, newRightHandPosition, callback, object);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController\/LatePositionsWillBeSetDelegate.EndInvoke\r\nvoid GlobalNamespace::AvatarPoseController::LatePositionsWillBeSetDelegate::EndInvoke(UnityEngine::Vector3& newHeadPosition, UnityEngine::Vector3& newLeftHandPosition, UnityEngine::Vector3& newRightHandPosition, System::IAsyncResult* result) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::LatePositionsWillBeSetDelegate::EndInvoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"EndInvoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractType(result)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, newHeadPosition, newLeftHandPosition, newRightHandPosition, result);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AvatarPoseController\/RotationsWillBeSetDelegate\r\n#include \"GlobalNamespace\/AvatarPoseController_RotationsWillBeSetDelegate.hpp\"\r\n\/\/ Including type: UnityEngine.Quaternion\r\n#include \"UnityEngine\/Quaternion.hpp\"\r\n\/\/ Including type: System.IAsyncResult\r\n#include \"System\/IAsyncResult.hpp\"\r\n\/\/ Including type: System.AsyncCallback\r\n#include \"System\/AsyncCallback.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AvatarPoseController\/RotationsWillBeSetDelegate.Invoke\r\nvoid GlobalNamespace::AvatarPoseController::RotationsWillBeSetDelegate::Invoke(UnityEngine::Quaternion headRotation, UnityEngine::Quaternion leftHandRotation, UnityEngine::Quaternion rightHandRotation, UnityEngine::Quaternion& newHeadRotation, UnityEngine::Quaternion& newLeftHandRotation, UnityEngine::Quaternion& newRightHandRotation) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::RotationsWillBeSetDelegate::Invoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Invoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(headRotation), ::il2cpp_utils::ExtractType(leftHandRotation), ::il2cpp_utils::ExtractType(rightHandRotation), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>()})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, headRotation, leftHandRotation, rightHandRotation, newHeadRotation, newLeftHandRotation, newRightHandRotation);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController\/RotationsWillBeSetDelegate.BeginInvoke\r\nSystem::IAsyncResult* GlobalNamespace::AvatarPoseController::RotationsWillBeSetDelegate::BeginInvoke(UnityEngine::Quaternion headRotation, UnityEngine::Quaternion leftHandRotation, UnityEngine::Quaternion rightHandRotation, UnityEngine::Quaternion& newHeadRotation, UnityEngine::Quaternion& newLeftHandRotation, UnityEngine::Quaternion& newRightHandRotation, System::AsyncCallback* callback, ::Il2CppObject* object) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::RotationsWillBeSetDelegate::BeginInvoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"BeginInvoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(headRotation), ::il2cpp_utils::ExtractType(leftHandRotation), ::il2cpp_utils::ExtractType(rightHandRotation), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>(), ::il2cpp_utils::ExtractType(callback), ::il2cpp_utils::ExtractType(object)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::IAsyncResult*, false>(this, ___internal__method, headRotation, leftHandRotation, rightHandRotation, newHeadRotation, newLeftHandRotation, newRightHandRotation, callback, object);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseController\/RotationsWillBeSetDelegate.EndInvoke\r\nvoid GlobalNamespace::AvatarPoseController::RotationsWillBeSetDelegate::EndInvoke(UnityEngine::Quaternion& newHeadRotation, UnityEngine::Quaternion& newLeftHandRotation, UnityEngine::Quaternion& newRightHandRotation, System::IAsyncResult* result) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseController::RotationsWillBeSetDelegate::EndInvoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"EndInvoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>(), ::il2cpp_utils::ExtractType(result)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, newHeadRotation, newLeftHandRotation, newRightHandRotation, result);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AvatarPoseMirror\r\n#include \"GlobalNamespace\/AvatarPoseMirror.hpp\"\r\n\/\/ Including type: AvatarPoseController\r\n#include \"GlobalNamespace\/AvatarPoseController.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AvatarPoseMirror.Start\r\nvoid GlobalNamespace::AvatarPoseMirror::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseMirror::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseMirror.HandleAvatarPoseControllerPositionsWillBeSet\r\nvoid GlobalNamespace::AvatarPoseMirror::HandleAvatarPoseControllerPositionsWillBeSet(UnityEngine::Vector3 headPosition, UnityEngine::Vector3 leftHandPosition, UnityEngine::Vector3 rightHandPosition, UnityEngine::Vector3& newHeadPosition, UnityEngine::Vector3& newLeftHandPosition, UnityEngine::Vector3& newRightHandPosition) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseMirror::HandleAvatarPoseControllerPositionsWillBeSet\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(\"\", \"AvatarPoseMirror\", \"HandleAvatarPoseControllerPositionsWillBeSet\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(headPosition), ::il2cpp_utils::ExtractType(leftHandPosition), ::il2cpp_utils::ExtractType(rightHandPosition), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, headPosition, leftHandPosition, rightHandPosition, newHeadPosition, newLeftHandPosition, newRightHandPosition);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseMirror.HandleAvatarPoseControllerRotationsWillBeSet\r\nvoid GlobalNamespace::AvatarPoseMirror::HandleAvatarPoseControllerRotationsWillBeSet(UnityEngine::Quaternion headRotation, UnityEngine::Quaternion leftHandRotation, UnityEngine::Quaternion rightHandRotation, UnityEngine::Quaternion& newHeadRotation, UnityEngine::Quaternion& newLeftHandRotation, UnityEngine::Quaternion& newRightHandRotation) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseMirror::HandleAvatarPoseControllerRotationsWillBeSet\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(\"\", \"AvatarPoseMirror\", \"HandleAvatarPoseControllerRotationsWillBeSet\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(headRotation), ::il2cpp_utils::ExtractType(leftHandRotation), ::il2cpp_utils::ExtractType(rightHandRotation), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>()})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, headRotation, leftHandRotation, rightHandRotation, newHeadRotation, newLeftHandRotation, newRightHandRotation);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseMirror.MirrorRotation\r\nUnityEngine::Quaternion GlobalNamespace::AvatarPoseMirror::MirrorRotation(UnityEngine::Quaternion rotation) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseMirror::MirrorRotation\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(\"\", \"AvatarPoseMirror\", \"MirrorRotation\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(rotation)})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::Quaternion, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, rotation);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseMirror.MirrorPosition\r\nUnityEngine::Vector3 GlobalNamespace::AvatarPoseMirror::MirrorPosition(UnityEngine::Vector3 position) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseMirror::MirrorPosition\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(\"\", \"AvatarPoseMirror\", \"MirrorPosition\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(position)})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, position);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AvatarPoseRestrictions\r\n#include \"GlobalNamespace\/AvatarPoseRestrictions.hpp\"\r\n\/\/ Including type: AvatarPoseController\r\n#include \"GlobalNamespace\/AvatarPoseController.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AvatarPoseRestrictions.Start\r\nvoid GlobalNamespace::AvatarPoseRestrictions::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseRestrictions::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseRestrictions.HandleAvatarPoseControllerPositionsWillBeSet\r\nvoid GlobalNamespace::AvatarPoseRestrictions::HandleAvatarPoseControllerPositionsWillBeSet(UnityEngine::Quaternion headRotation, UnityEngine::Vector3 headPosition, UnityEngine::Vector3 leftHandPosition, UnityEngine::Vector3 rightHandPosition, UnityEngine::Vector3& newHeadPosition, UnityEngine::Vector3& newLeftHandPosition, UnityEngine::Vector3& newRightHandPosition) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseRestrictions::HandleAvatarPoseControllerPositionsWillBeSet\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleAvatarPoseControllerPositionsWillBeSet\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(headRotation), ::il2cpp_utils::ExtractType(headPosition), ::il2cpp_utils::ExtractType(leftHandPosition), ::il2cpp_utils::ExtractType(rightHandPosition), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>(), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, headRotation, headPosition, leftHandPosition, rightHandPosition, newHeadPosition, newLeftHandPosition, newRightHandPosition);\r\n}\r\n\/\/ Autogenerated method: AvatarPoseRestrictions.LimitHandPositionRelativeToHead\r\nUnityEngine::Vector3 GlobalNamespace::AvatarPoseRestrictions::LimitHandPositionRelativeToHead(UnityEngine::Vector3 handPosition, UnityEngine::Vector3 headCenter) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPoseRestrictions::LimitHandPositionRelativeToHead\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"LimitHandPositionRelativeToHead\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(handPosition), ::il2cpp_utils::ExtractType(headCenter)})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, handPosition, headCenter);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AvatarPropertyBlockColorSetter\r\n#include \"GlobalNamespace\/AvatarPropertyBlockColorSetter.hpp\"\r\n\/\/ Including type: UnityEngine.Renderer\r\n#include \"UnityEngine\/Renderer.hpp\"\r\n\/\/ Including type: UnityEngine.MaterialPropertyBlock\r\n#include \"UnityEngine\/MaterialPropertyBlock.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ [DoesNotRequireDomainReloadInitAttribute] Offset: 0xE15538\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private UnityEngine.MaterialPropertyBlock _materialPropertyBlock\r\nUnityEngine::MaterialPropertyBlock* GlobalNamespace::AvatarPropertyBlockColorSetter::_get__materialPropertyBlock() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPropertyBlockColorSetter::_get__materialPropertyBlock\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::MaterialPropertyBlock*>(\"\", \"AvatarPropertyBlockColorSetter\", \"_materialPropertyBlock\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private UnityEngine.MaterialPropertyBlock _materialPropertyBlock\r\nvoid GlobalNamespace::AvatarPropertyBlockColorSetter::_set__materialPropertyBlock(UnityEngine::MaterialPropertyBlock* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPropertyBlockColorSetter::_set__materialPropertyBlock\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AvatarPropertyBlockColorSetter\", \"_materialPropertyBlock\", value));\r\n}\r\n\/\/ Autogenerated method: AvatarPropertyBlockColorSetter.Awake\r\nvoid GlobalNamespace::AvatarPropertyBlockColorSetter::Awake() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPropertyBlockColorSetter::Awake\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Awake\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarPropertyBlockColorSetter.OnValidate\r\nvoid GlobalNamespace::AvatarPropertyBlockColorSetter::OnValidate() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPropertyBlockColorSetter::OnValidate\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnValidate\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarPropertyBlockColorSetter.SetColor\r\nvoid GlobalNamespace::AvatarPropertyBlockColorSetter::SetColor(UnityEngine::Color color) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPropertyBlockColorSetter::SetColor\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"SetColor\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(color)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, color);\r\n}\r\n\/\/ Autogenerated method: AvatarPropertyBlockColorSetter.SetColors\r\nvoid GlobalNamespace::AvatarPropertyBlockColorSetter::SetColors(UnityEngine::Color mainColor, UnityEngine::Color rimLightColor) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPropertyBlockColorSetter::SetColors\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"SetColors\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(mainColor), ::il2cpp_utils::ExtractType(rimLightColor)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, mainColor, rimLightColor);\r\n}\r\n\/\/ Autogenerated method: AvatarPropertyBlockColorSetter.SetHighlight\r\nvoid GlobalNamespace::AvatarPropertyBlockColorSetter::SetHighlight(bool highlighted, int uvSegment) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPropertyBlockColorSetter::SetHighlight\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"SetHighlight\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(highlighted), ::il2cpp_utils::ExtractType(uvSegment)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, highlighted, uvSegment);\r\n}\r\n\/\/ Autogenerated method: AvatarPropertyBlockColorSetter.UpdateRenderer\r\nvoid GlobalNamespace::AvatarPropertyBlockColorSetter::UpdateRenderer() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarPropertyBlockColorSetter::UpdateRenderer\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"UpdateRenderer\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AvatarTweenController\r\n#include \"GlobalNamespace\/AvatarTweenController.hpp\"\r\n\/\/ Including type: AvatarTweenController\/<>c__DisplayClass52_0\r\n#include \"GlobalNamespace\/AvatarTweenController_--c__DisplayClass52_0.hpp\"\r\n\/\/ Including type: AvatarTweenController\/<AppearAnimation>d__53\r\n#include \"GlobalNamespace\/AvatarTweenController_-AppearAnimation-d__53.hpp\"\r\n\/\/ Including type: AvatarTweenController\/<DisappearAnimation>d__58\r\n#include \"GlobalNamespace\/AvatarTweenController_-DisappearAnimation-d__58.hpp\"\r\n\/\/ Including type: UnityEngine.Transform\r\n#include \"UnityEngine\/Transform.hpp\"\r\n\/\/ Including type: Tweening.TweeningManager\r\n#include \"Tweening\/TweeningManager.hpp\"\r\n\/\/ Including type: Tweening.Tween`1\r\n#include \"Tweening\/Tween_1.hpp\"\r\n\/\/ Including type: System.Collections.IEnumerator\r\n#include \"System\/Collections\/IEnumerator.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AvatarTweenController.Awake\r\nvoid GlobalNamespace::AvatarTweenController::Awake() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::Awake\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Awake\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.OnDisable\r\nvoid GlobalNamespace::AvatarTweenController::OnDisable() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::OnDisable\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDisable\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.PresentAvatar\r\nvoid GlobalNamespace::AvatarTweenController::PresentAvatar() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::PresentAvatar\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"PresentAvatar\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.HideAvatar\r\nvoid GlobalNamespace::AvatarTweenController::HideAvatar() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::HideAvatar\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HideAvatar\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.PopAll\r\nvoid GlobalNamespace::AvatarTweenController::PopAll() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::PopAll\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"PopAll\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.PopHead\r\nvoid GlobalNamespace::AvatarTweenController::PopHead() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::PopHead\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"PopHead\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.PopHands\r\nvoid GlobalNamespace::AvatarTweenController::PopHands() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::PopHands\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"PopHands\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.PopClothes\r\nvoid GlobalNamespace::AvatarTweenController::PopClothes() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::PopClothes\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"PopClothes\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.PopHead\r\nvoid GlobalNamespace::AvatarTweenController::PopHead(float popAmount) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::PopHead\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"PopHead\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(popAmount)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, popAmount);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.PopHands\r\nvoid GlobalNamespace::AvatarTweenController::PopHands(float popAmount) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::PopHands\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"PopHands\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(popAmount)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, popAmount);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.PopClothes\r\nvoid GlobalNamespace::AvatarTweenController::PopClothes(float popAmount) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::PopClothes\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"PopClothes\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(popAmount)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, popAmount);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.CreatePopTween\r\nTweening::Tween_1<float>* GlobalNamespace::AvatarTweenController::CreatePopTween(UnityEngine::Transform* partTransform, float popAmount) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::CreatePopTween\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"CreatePopTween\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(partTransform), ::il2cpp_utils::ExtractType(popAmount)})));\r\n  return ::il2cpp_utils::RunMethodThrow<Tweening::Tween_1<float>*, false>(this, ___internal__method, partTransform, popAmount);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.AppearAnimation\r\nSystem::Collections::IEnumerator* GlobalNamespace::AvatarTweenController::AppearAnimation() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::AppearAnimation\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"AppearAnimation\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Collections::IEnumerator*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.AppearBody\r\nvoid GlobalNamespace::AvatarTweenController::AppearBody() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::AppearBody\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"AppearBody\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.AppearHead\r\nvoid GlobalNamespace::AvatarTweenController::AppearHead() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::AppearHead\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"AppearHead\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.AppearLeftHand\r\nvoid GlobalNamespace::AvatarTweenController::AppearLeftHand() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::AppearLeftHand\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"AppearLeftHand\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.AppearRightHand\r\nvoid GlobalNamespace::AvatarTweenController::AppearRightHand() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::AppearRightHand\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"AppearRightHand\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.DisappearAnimation\r\nSystem::Collections::IEnumerator* GlobalNamespace::AvatarTweenController::DisappearAnimation() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::DisappearAnimation\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"DisappearAnimation\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Collections::IEnumerator*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.StopAll\r\nvoid GlobalNamespace::AvatarTweenController::StopAll() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::StopAll\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"StopAll\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.<AppearBody>b__54_0\r\nvoid GlobalNamespace::AvatarTweenController::$AppearBody$b__54_0(UnityEngine::Vector3 val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::<AppearBody>b__54_0\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<AppearBody>b__54_0\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.<AppearBody>b__54_1\r\nvoid GlobalNamespace::AvatarTweenController::$AppearBody$b__54_1(UnityEngine::Vector3 val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::<AppearBody>b__54_1\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<AppearBody>b__54_1\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.<AppearHead>b__55_0\r\nvoid GlobalNamespace::AvatarTweenController::$AppearHead$b__55_0(UnityEngine::Vector3 val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::<AppearHead>b__55_0\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<AppearHead>b__55_0\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.<AppearHead>b__55_1\r\nvoid GlobalNamespace::AvatarTweenController::$AppearHead$b__55_1(UnityEngine::Vector3 val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::<AppearHead>b__55_1\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<AppearHead>b__55_1\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.<AppearLeftHand>b__56_0\r\nvoid GlobalNamespace::AvatarTweenController::$AppearLeftHand$b__56_0(UnityEngine::Vector3 val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::<AppearLeftHand>b__56_0\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<AppearLeftHand>b__56_0\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.<AppearLeftHand>b__56_1\r\nvoid GlobalNamespace::AvatarTweenController::$AppearLeftHand$b__56_1(UnityEngine::Vector3 val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::<AppearLeftHand>b__56_1\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<AppearLeftHand>b__56_1\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.<AppearRightHand>b__57_0\r\nvoid GlobalNamespace::AvatarTweenController::$AppearRightHand$b__57_0(UnityEngine::Vector3 val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::<AppearRightHand>b__57_0\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<AppearRightHand>b__57_0\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.<AppearRightHand>b__57_1\r\nvoid GlobalNamespace::AvatarTweenController::$AppearRightHand$b__57_1(UnityEngine::Vector3 val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::<AppearRightHand>b__57_1\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<AppearRightHand>b__57_1\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.<DisappearAnimation>b__58_0\r\nvoid GlobalNamespace::AvatarTweenController::$DisappearAnimation$b__58_0(UnityEngine::Vector3 val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::<DisappearAnimation>b__58_0\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<DisappearAnimation>b__58_0\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController.<DisappearAnimation>b__58_1\r\nvoid GlobalNamespace::AvatarTweenController::$DisappearAnimation$b__58_1(UnityEngine::Vector3 val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::<DisappearAnimation>b__58_1\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<DisappearAnimation>b__58_1\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AvatarTweenController\/<>c__DisplayClass52_0\r\n#include \"GlobalNamespace\/AvatarTweenController_--c__DisplayClass52_0.hpp\"\r\n\/\/ Including type: UnityEngine.Transform\r\n#include \"UnityEngine\/Transform.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AvatarTweenController\/<>c__DisplayClass52_0.<CreatePopTween>b__0\r\nvoid GlobalNamespace::AvatarTweenController::$$c__DisplayClass52_0::$CreatePopTween$b__0(float val) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::$$c__DisplayClass52_0::<CreatePopTween>b__0\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<CreatePopTween>b__0\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(val)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, val);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AvatarTweenController\/<AppearAnimation>d__53\r\n#include \"GlobalNamespace\/AvatarTweenController_-AppearAnimation-d__53.hpp\"\r\n\/\/ Including type: UnityEngine.WaitForSeconds\r\n#include \"UnityEngine\/WaitForSeconds.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AvatarTweenController\/<AppearAnimation>d__53.System.IDisposable.Dispose\r\nvoid GlobalNamespace::AvatarTweenController::$AppearAnimation$d__53::System_IDisposable_Dispose() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::$AppearAnimation$d__53::System.IDisposable.Dispose\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.IDisposable.Dispose\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController\/<AppearAnimation>d__53.MoveNext\r\nbool GlobalNamespace::AvatarTweenController::$AppearAnimation$d__53::MoveNext() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::$AppearAnimation$d__53::MoveNext\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"MoveNext\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController\/<AppearAnimation>d__53.System.Collections.Generic.IEnumerator<System.Object>.get_Current\r\n::Il2CppObject* GlobalNamespace::AvatarTweenController::$AppearAnimation$d__53::System_Collections_Generic_IEnumerator$System_Object$_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::$AppearAnimation$d__53::System.Collections.Generic.IEnumerator<System.Object>.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.Generic.IEnumerator<System.Object>.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController\/<AppearAnimation>d__53.System.Collections.IEnumerator.Reset\r\nvoid GlobalNamespace::AvatarTweenController::$AppearAnimation$d__53::System_Collections_IEnumerator_Reset() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::$AppearAnimation$d__53::System.Collections.IEnumerator.Reset\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.Reset\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController\/<AppearAnimation>d__53.System.Collections.IEnumerator.get_Current\r\n::Il2CppObject* GlobalNamespace::AvatarTweenController::$AppearAnimation$d__53::System_Collections_IEnumerator_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::$AppearAnimation$d__53::System.Collections.IEnumerator.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AvatarTweenController\/<DisappearAnimation>d__58\r\n#include \"GlobalNamespace\/AvatarTweenController_-DisappearAnimation-d__58.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AvatarTweenController\/<DisappearAnimation>d__58.System.IDisposable.Dispose\r\nvoid GlobalNamespace::AvatarTweenController::$DisappearAnimation$d__58::System_IDisposable_Dispose() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::$DisappearAnimation$d__58::System.IDisposable.Dispose\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.IDisposable.Dispose\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController\/<DisappearAnimation>d__58.MoveNext\r\nbool GlobalNamespace::AvatarTweenController::$DisappearAnimation$d__58::MoveNext() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::$DisappearAnimation$d__58::MoveNext\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"MoveNext\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController\/<DisappearAnimation>d__58.System.Collections.Generic.IEnumerator<System.Object>.get_Current\r\n::Il2CppObject* GlobalNamespace::AvatarTweenController::$DisappearAnimation$d__58::System_Collections_Generic_IEnumerator$System_Object$_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::$DisappearAnimation$d__58::System.Collections.Generic.IEnumerator<System.Object>.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.Generic.IEnumerator<System.Object>.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController\/<DisappearAnimation>d__58.System.Collections.IEnumerator.Reset\r\nvoid GlobalNamespace::AvatarTweenController::$DisappearAnimation$d__58::System_Collections_IEnumerator_Reset() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::$DisappearAnimation$d__58::System.Collections.IEnumerator.Reset\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.Reset\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarTweenController\/<DisappearAnimation>d__58.System.Collections.IEnumerator.get_Current\r\n::Il2CppObject* GlobalNamespace::AvatarTweenController::$DisappearAnimation$d__58::System_Collections_IEnumerator_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarTweenController::$DisappearAnimation$d__58::System.Collections.IEnumerator.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AvatarVisualController\r\n#include \"GlobalNamespace\/AvatarVisualController.hpp\"\r\n\/\/ Including type: AvatarVisualController\/HighlighterDelegate\r\n#include \"GlobalNamespace\/AvatarVisualController_HighlighterDelegate.hpp\"\r\n\/\/ Including type: UnityEngine.MeshFilter\r\n#include \"UnityEngine\/MeshFilter.hpp\"\r\n\/\/ Including type: UnityEngine.SpriteRenderer\r\n#include \"UnityEngine\/SpriteRenderer.hpp\"\r\n\/\/ Including type: MulticolorAvatarPartPropertyBlockSetter\r\n#include \"GlobalNamespace\/MulticolorAvatarPartPropertyBlockSetter.hpp\"\r\n\/\/ Including type: AvatarPropertyBlockColorSetter\r\n#include \"GlobalNamespace\/AvatarPropertyBlockColorSetter.hpp\"\r\n\/\/ Including type: AvatarPartsModel\r\n#include \"GlobalNamespace\/AvatarPartsModel.hpp\"\r\n\/\/ Including type: System.Collections.Generic.Dictionary`2\r\n#include \"System\/Collections\/Generic\/Dictionary_2.hpp\"\r\n\/\/ Including type: AvatarData\r\n#include \"GlobalNamespace\/AvatarData.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AvatarVisualController.get_lightColor\r\nUnityEngine::Color GlobalNamespace::AvatarVisualController::get_lightColor() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarVisualController::get_lightColor\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_lightColor\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::Color, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarVisualController.Awake\r\nvoid GlobalNamespace::AvatarVisualController::Awake() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarVisualController::Awake\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Awake\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarVisualController.UpdateAvatarVisual\r\nvoid GlobalNamespace::AvatarVisualController::UpdateAvatarVisual(GlobalNamespace::AvatarData* avatarData) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarVisualController::UpdateAvatarVisual\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"UpdateAvatarVisual\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(avatarData)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, avatarData);\r\n}\r\n\/\/ Autogenerated method: AvatarVisualController.SetLightColor\r\nvoid GlobalNamespace::AvatarVisualController::SetLightColor(UnityEngine::Color color) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarVisualController::SetLightColor\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"SetLightColor\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(color)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, color);\r\n}\r\n\/\/ Autogenerated method: AvatarVisualController.UpdateAvatarColors\r\nvoid GlobalNamespace::AvatarVisualController::UpdateAvatarColors() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarVisualController::UpdateAvatarColors\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"UpdateAvatarColors\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarVisualController.HighlightEditedPart\r\nvoid GlobalNamespace::AvatarVisualController::HighlightEditedPart(GlobalNamespace::EditAvatarViewController::AvatarEditPart editPart, int uvSegment) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarVisualController::HighlightEditedPart\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HighlightEditedPart\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(editPart), ::il2cpp_utils::ExtractType(uvSegment)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, editPart, uvSegment);\r\n}\r\n\/\/ Autogenerated method: AvatarVisualController.DisableEditedPartHighlight\r\nvoid GlobalNamespace::AvatarVisualController::DisableEditedPartHighlight() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarVisualController::DisableEditedPartHighlight\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"DisableEditedPartHighlight\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AvatarVisualController.SetHandsHighlight\r\nvoid GlobalNamespace::AvatarVisualController::SetHandsHighlight(bool highlighted, int uvSegment) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarVisualController::SetHandsHighlight\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"SetHandsHighlight\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(highlighted), ::il2cpp_utils::ExtractType(uvSegment)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, highlighted, uvSegment);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AvatarVisualController\/HighlighterDelegate\r\n#include \"GlobalNamespace\/AvatarVisualController_HighlighterDelegate.hpp\"\r\n\/\/ Including type: System.IAsyncResult\r\n#include \"System\/IAsyncResult.hpp\"\r\n\/\/ Including type: System.AsyncCallback\r\n#include \"System\/AsyncCallback.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AvatarVisualController\/HighlighterDelegate.Invoke\r\nvoid GlobalNamespace::AvatarVisualController::HighlighterDelegate::Invoke(bool highlighted, int uvSegmentNumber) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarVisualController::HighlighterDelegate::Invoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Invoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(highlighted), ::il2cpp_utils::ExtractType(uvSegmentNumber)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, highlighted, uvSegmentNumber);\r\n}\r\n\/\/ Autogenerated method: AvatarVisualController\/HighlighterDelegate.BeginInvoke\r\nSystem::IAsyncResult* GlobalNamespace::AvatarVisualController::HighlighterDelegate::BeginInvoke(bool highlighted, int uvSegmentNumber, System::AsyncCallback* callback, ::Il2CppObject* object) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarVisualController::HighlighterDelegate::BeginInvoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"BeginInvoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(highlighted), ::il2cpp_utils::ExtractType(uvSegmentNumber), ::il2cpp_utils::ExtractType(callback), ::il2cpp_utils::ExtractType(object)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::IAsyncResult*, false>(this, ___internal__method, highlighted, uvSegmentNumber, callback, object);\r\n}\r\n\/\/ Autogenerated method: AvatarVisualController\/HighlighterDelegate.EndInvoke\r\nvoid GlobalNamespace::AvatarVisualController::HighlighterDelegate::EndInvoke(System::IAsyncResult* result) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AvatarVisualController::HighlighterDelegate::EndInvoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"EndInvoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, result);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: ConnectedPlayerName\r\n#include \"GlobalNamespace\/ConnectedPlayerName.hpp\"\r\n\/\/ Including type: TMPro.TextMeshProUGUI\r\n#include \"TMPro\/TextMeshProUGUI.hpp\"\r\n\/\/ Including type: IConnectedPlayer\r\n#include \"GlobalNamespace\/IConnectedPlayer.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: ConnectedPlayerName.Start\r\nvoid GlobalNamespace::ConnectedPlayerName::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::ConnectedPlayerName::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: HeadBodyOffsetSO\r\n#include \"GlobalNamespace\/HeadBodyOffsetSO.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: HeadBodyOffsetSO.get_headNeckOffset\r\nUnityEngine::Vector3 GlobalNamespace::HeadBodyOffsetSO::get_headNeckOffset() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::HeadBodyOffsetSO::get_headNeckOffset\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_headNeckOffset\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: HeadBodyOffsetSO.get_verticalOffset\r\nfloat GlobalNamespace::HeadBodyOffsetSO::get_verticalOffset() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::HeadBodyOffsetSO::get_verticalOffset\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_verticalOffset\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: LobbyAvatarInstaller\r\n#include \"GlobalNamespace\/LobbyAvatarInstaller.hpp\"\r\n\/\/ Including type: IConnectedPlayer\r\n#include \"GlobalNamespace\/IConnectedPlayer.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: LobbyAvatarInstaller.InstallBindings\r\nvoid GlobalNamespace::LobbyAvatarInstaller::InstallBindings() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::LobbyAvatarInstaller::InstallBindings\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"InstallBindings\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: MulticolorAvatarPartPropertyBlockSetter\r\n#include \"GlobalNamespace\/MulticolorAvatarPartPropertyBlockSetter.hpp\"\r\n\/\/ Including type: MulticolorAvatarPartPropertyBlockSetter\/ColorData\r\n#include \"GlobalNamespace\/MulticolorAvatarPartPropertyBlockSetter_ColorData.hpp\"\r\n\/\/ Including type: MulticolorAvatarPartPropertyBlockSetter\/<>c\r\n#include \"GlobalNamespace\/MulticolorAvatarPartPropertyBlockSetter_--c.hpp\"\r\n\/\/ Including type: UnityEngine.Renderer\r\n#include \"UnityEngine\/Renderer.hpp\"\r\n\/\/ Including type: UnityEngine.MaterialPropertyBlock\r\n#include \"UnityEngine\/MaterialPropertyBlock.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ [DoesNotRequireDomainReloadInitAttribute] Offset: 0xE15AA4\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static private UnityEngine.MaterialPropertyBlock _materialPropertyBlock\r\nUnityEngine::MaterialPropertyBlock* GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::_get__materialPropertyBlock() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::_get__materialPropertyBlock\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::MaterialPropertyBlock*>(\"\", \"MulticolorAvatarPartPropertyBlockSetter\", \"_materialPropertyBlock\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static private UnityEngine.MaterialPropertyBlock _materialPropertyBlock\r\nvoid GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::_set__materialPropertyBlock(UnityEngine::MaterialPropertyBlock* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::_set__materialPropertyBlock\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"MulticolorAvatarPartPropertyBlockSetter\", \"_materialPropertyBlock\", value));\r\n}\r\n\/\/ Autogenerated method: MulticolorAvatarPartPropertyBlockSetter.OnValidate\r\nvoid GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::OnValidate() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::OnValidate\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnValidate\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MulticolorAvatarPartPropertyBlockSetter.SetColors\r\nvoid GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::SetColors(::Array<UnityEngine::Color>* colors) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::SetColors\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"SetColors\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(colors)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, colors);\r\n}\r\n\/\/ Creating initializer_list -> params proxy for: System.Void SetColors(params UnityEngine.Color[] colors)\r\nvoid GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::SetColors(std::initializer_list<UnityEngine::Color> colors) {\r\n  GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::SetColors(::Array<UnityEngine::Color>::New(colors));\r\n}\r\n\/\/ Autogenerated method: MulticolorAvatarPartPropertyBlockSetter.SetHighlight\r\nvoid GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::SetHighlight(bool highlighted, int uvSegment) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::SetHighlight\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"SetHighlight\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(highlighted), ::il2cpp_utils::ExtractType(uvSegment)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, highlighted, uvSegment);\r\n}\r\n\/\/ Autogenerated method: MulticolorAvatarPartPropertyBlockSetter.UpdateRenderer\r\nvoid GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::UpdateRenderer() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::UpdateRenderer\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"UpdateRenderer\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: MulticolorAvatarPartPropertyBlockSetter\/ColorData\r\n#include \"GlobalNamespace\/MulticolorAvatarPartPropertyBlockSetter_ColorData.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: MulticolorAvatarPartPropertyBlockSetter\/ColorData.get_defaultColor\r\nUnityEngine::Color GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::get_defaultColor() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::get_defaultColor\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_defaultColor\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::Color, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MulticolorAvatarPartPropertyBlockSetter\/ColorData.get_darkerColorMultiplier\r\nfloat GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::get_darkerColorMultiplier() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::get_darkerColorMultiplier\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_darkerColorMultiplier\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MulticolorAvatarPartPropertyBlockSetter\/ColorData.get_whiteBoost\r\nfloat GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::get_whiteBoost() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::get_whiteBoost\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_whiteBoost\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: MulticolorAvatarPartPropertyBlockSetter\/<>c\r\n#include \"GlobalNamespace\/MulticolorAvatarPartPropertyBlockSetter_--c.hpp\"\r\n\/\/ Including type: System.Func`2\r\n#include \"System\/Func_2.hpp\"\r\n\/\/ Including type: MulticolorAvatarPartPropertyBlockSetter\/ColorData\r\n#include \"GlobalNamespace\/MulticolorAvatarPartPropertyBlockSetter_ColorData.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public readonly MulticolorAvatarPartPropertyBlockSetter\/<>c <>9\r\nGlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c* GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c::_get_$$9() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c::_get_$$9\");\r\n  return THROW_UNLESS((il2cpp_utils::GetFieldValue<GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c*>(\"\", \"MulticolorAvatarPartPropertyBlockSetter\/<>c\", \"<>9\")));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public readonly MulticolorAvatarPartPropertyBlockSetter\/<>c <>9\r\nvoid GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c::_set_$$9(GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c::_set_$$9\");\r\n  THROW_UNLESS((il2cpp_utils::SetFieldValue(\"\", \"MulticolorAvatarPartPropertyBlockSetter\/<>c\", \"<>9\", value)));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public System.Func`2<MulticolorAvatarPartPropertyBlockSetter\/ColorData,UnityEngine.Color> <>9__10_0\r\nSystem::Func_2<GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData*, UnityEngine::Color>* GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c::_get_$$9__10_0() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c::_get_$$9__10_0\");\r\n  return THROW_UNLESS((il2cpp_utils::GetFieldValue<System::Func_2<GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData*, UnityEngine::Color>*>(\"\", \"MulticolorAvatarPartPropertyBlockSetter\/<>c\", \"<>9__10_0\")));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public System.Func`2<MulticolorAvatarPartPropertyBlockSetter\/ColorData,UnityEngine.Color> <>9__10_0\r\nvoid GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c::_set_$$9__10_0(System::Func_2<GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData*, UnityEngine::Color>* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c::_set_$$9__10_0\");\r\n  THROW_UNLESS((il2cpp_utils::SetFieldValue(\"\", \"MulticolorAvatarPartPropertyBlockSetter\/<>c\", \"<>9__10_0\", value)));\r\n}\r\n\/\/ Autogenerated method: MulticolorAvatarPartPropertyBlockSetter\/<>c..cctor\r\nvoid GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c::_cctor() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c::.cctor\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(\"\", \"MulticolorAvatarPartPropertyBlockSetter\/<>c\", \".cctor\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MulticolorAvatarPartPropertyBlockSetter\/<>c.<OnValidate>b__10_0\r\nUnityEngine::Color GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c::$OnValidate$b__10_0(GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData* x) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::$$c::<OnValidate>b__10_0\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<OnValidate>b__10_0\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x)})));\r\n  return ::il2cpp_utils::RunMethodThrow<UnityEngine::Color, false>(this, ___internal__method, x);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: MultiplayerAvatarPoseController\r\n#include \"GlobalNamespace\/MultiplayerAvatarPoseController.hpp\"\r\n\/\/ Including type: AvatarPoseController\r\n#include \"GlobalNamespace\/AvatarPoseController.hpp\"\r\n\/\/ Including type: INodePoseSyncStateManager\r\n#include \"GlobalNamespace\/INodePoseSyncStateManager.hpp\"\r\n\/\/ Including type: IConnectedPlayer\r\n#include \"GlobalNamespace\/IConnectedPlayer.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: MultiplayerAvatarPoseController.set_connectedPlayer\r\nvoid GlobalNamespace::MultiplayerAvatarPoseController::set_connectedPlayer(GlobalNamespace::IConnectedPlayer* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerAvatarPoseController::set_connectedPlayer\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"set_connectedPlayer\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: MultiplayerAvatarPoseController.Start\r\nvoid GlobalNamespace::MultiplayerAvatarPoseController::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerAvatarPoseController::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerAvatarPoseController.Update\r\nvoid GlobalNamespace::MultiplayerAvatarPoseController::Update() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerAvatarPoseController::Update\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Update\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: MultiplayerAvatarVisualProvider\r\n#include \"GlobalNamespace\/MultiplayerAvatarVisualProvider.hpp\"\r\n\/\/ Including type: AvatarVisualController\r\n#include \"GlobalNamespace\/AvatarVisualController.hpp\"\r\n\/\/ Including type: IConnectedPlayer\r\n#include \"GlobalNamespace\/IConnectedPlayer.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: MultiplayerAvatarVisualProvider.Start\r\nvoid GlobalNamespace::MultiplayerAvatarVisualProvider::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerAvatarVisualProvider::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: MultiplayerLobbyAvatarController\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarController.hpp\"\r\n\/\/ Including type: MultiplayerLobbyAvatarController\/Factory\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarController_Factory.hpp\"\r\n\/\/ Including type: MultiplayerLobbyAvatarController\/<SpawnAnimationCoroutine>d__8\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarController_-SpawnAnimationCoroutine-d__8.hpp\"\r\n\/\/ Including type: MultiplayerLobbyAvatarController\/<ShowDespawnAnimationAndDestroy>d__10\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarController_-ShowDespawnAnimationAndDestroy-d__10.hpp\"\r\n\/\/ Including type: MultiplayerLobbyAvatarController\/<DespawnAnimationCoroutine>d__12\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarController_-DespawnAnimationCoroutine-d__12.hpp\"\r\n\/\/ Including type: UnityEngine.Playables.PlayableDirector\r\n#include \"UnityEngine\/Playables\/PlayableDirector.hpp\"\r\n\/\/ Including type: VFXController\r\n#include \"GlobalNamespace\/VFXController.hpp\"\r\n\/\/ Including type: UnityEngine.GameObject\r\n#include \"UnityEngine\/GameObject.hpp\"\r\n\/\/ Including type: System.Collections.IEnumerator\r\n#include \"System\/Collections\/IEnumerator.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController.ShowSpawnAnimation\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarController::ShowSpawnAnimation(UnityEngine::Vector3 position, UnityEngine::Quaternion rotation) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::ShowSpawnAnimation\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"ShowSpawnAnimation\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(position), ::il2cpp_utils::ExtractType(rotation)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, position, rotation);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController.SpawnAnimationCoroutine\r\nSystem::Collections::IEnumerator* GlobalNamespace::MultiplayerLobbyAvatarController::SpawnAnimationCoroutine() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::SpawnAnimationCoroutine\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"SpawnAnimationCoroutine\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Collections::IEnumerator*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController.ActivateVisualObjects\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarController::ActivateVisualObjects(bool on) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::ActivateVisualObjects\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"ActivateVisualObjects\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(on)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, on);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController.ShowDespawnAnimationAndDestroy\r\nSystem::Collections::IEnumerator* GlobalNamespace::MultiplayerLobbyAvatarController::ShowDespawnAnimationAndDestroy() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::ShowDespawnAnimationAndDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"ShowDespawnAnimationAndDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Collections::IEnumerator*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController.DestroySelf\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarController::DestroySelf() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::DestroySelf\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"DestroySelf\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController.DespawnAnimationCoroutine\r\nSystem::Collections::IEnumerator* GlobalNamespace::MultiplayerLobbyAvatarController::DespawnAnimationCoroutine() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::DespawnAnimationCoroutine\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"DespawnAnimationCoroutine\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Collections::IEnumerator*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: MultiplayerLobbyAvatarController\/Factory\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarController_Factory.hpp\"\r\n\/\/ Including type: IConnectedPlayer\r\n#include \"GlobalNamespace\/IConnectedPlayer.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: MultiplayerLobbyAvatarController\/<SpawnAnimationCoroutine>d__8\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarController_-SpawnAnimationCoroutine-d__8.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<SpawnAnimationCoroutine>d__8.System.IDisposable.Dispose\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarController::$SpawnAnimationCoroutine$d__8::System_IDisposable_Dispose() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$SpawnAnimationCoroutine$d__8::System.IDisposable.Dispose\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.IDisposable.Dispose\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<SpawnAnimationCoroutine>d__8.MoveNext\r\nbool GlobalNamespace::MultiplayerLobbyAvatarController::$SpawnAnimationCoroutine$d__8::MoveNext() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$SpawnAnimationCoroutine$d__8::MoveNext\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"MoveNext\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<SpawnAnimationCoroutine>d__8.System.Collections.Generic.IEnumerator<System.Object>.get_Current\r\n::Il2CppObject* GlobalNamespace::MultiplayerLobbyAvatarController::$SpawnAnimationCoroutine$d__8::System_Collections_Generic_IEnumerator$System_Object$_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$SpawnAnimationCoroutine$d__8::System.Collections.Generic.IEnumerator<System.Object>.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.Generic.IEnumerator<System.Object>.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<SpawnAnimationCoroutine>d__8.System.Collections.IEnumerator.Reset\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarController::$SpawnAnimationCoroutine$d__8::System_Collections_IEnumerator_Reset() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$SpawnAnimationCoroutine$d__8::System.Collections.IEnumerator.Reset\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.Reset\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<SpawnAnimationCoroutine>d__8.System.Collections.IEnumerator.get_Current\r\n::Il2CppObject* GlobalNamespace::MultiplayerLobbyAvatarController::$SpawnAnimationCoroutine$d__8::System_Collections_IEnumerator_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$SpawnAnimationCoroutine$d__8::System.Collections.IEnumerator.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: MultiplayerLobbyAvatarController\/<ShowDespawnAnimationAndDestroy>d__10\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarController_-ShowDespawnAnimationAndDestroy-d__10.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<ShowDespawnAnimationAndDestroy>d__10.System.IDisposable.Dispose\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarController::$ShowDespawnAnimationAndDestroy$d__10::System_IDisposable_Dispose() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$ShowDespawnAnimationAndDestroy$d__10::System.IDisposable.Dispose\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.IDisposable.Dispose\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<ShowDespawnAnimationAndDestroy>d__10.MoveNext\r\nbool GlobalNamespace::MultiplayerLobbyAvatarController::$ShowDespawnAnimationAndDestroy$d__10::MoveNext() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$ShowDespawnAnimationAndDestroy$d__10::MoveNext\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"MoveNext\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<ShowDespawnAnimationAndDestroy>d__10.System.Collections.Generic.IEnumerator<System.Object>.get_Current\r\n::Il2CppObject* GlobalNamespace::MultiplayerLobbyAvatarController::$ShowDespawnAnimationAndDestroy$d__10::System_Collections_Generic_IEnumerator$System_Object$_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$ShowDespawnAnimationAndDestroy$d__10::System.Collections.Generic.IEnumerator<System.Object>.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.Generic.IEnumerator<System.Object>.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<ShowDespawnAnimationAndDestroy>d__10.System.Collections.IEnumerator.Reset\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarController::$ShowDespawnAnimationAndDestroy$d__10::System_Collections_IEnumerator_Reset() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$ShowDespawnAnimationAndDestroy$d__10::System.Collections.IEnumerator.Reset\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.Reset\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<ShowDespawnAnimationAndDestroy>d__10.System.Collections.IEnumerator.get_Current\r\n::Il2CppObject* GlobalNamespace::MultiplayerLobbyAvatarController::$ShowDespawnAnimationAndDestroy$d__10::System_Collections_IEnumerator_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$ShowDespawnAnimationAndDestroy$d__10::System.Collections.IEnumerator.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: MultiplayerLobbyAvatarController\/<DespawnAnimationCoroutine>d__12\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarController_-DespawnAnimationCoroutine-d__12.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<DespawnAnimationCoroutine>d__12.System.IDisposable.Dispose\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarController::$DespawnAnimationCoroutine$d__12::System_IDisposable_Dispose() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$DespawnAnimationCoroutine$d__12::System.IDisposable.Dispose\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.IDisposable.Dispose\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<DespawnAnimationCoroutine>d__12.MoveNext\r\nbool GlobalNamespace::MultiplayerLobbyAvatarController::$DespawnAnimationCoroutine$d__12::MoveNext() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$DespawnAnimationCoroutine$d__12::MoveNext\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"MoveNext\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<DespawnAnimationCoroutine>d__12.System.Collections.Generic.IEnumerator<System.Object>.get_Current\r\n::Il2CppObject* GlobalNamespace::MultiplayerLobbyAvatarController::$DespawnAnimationCoroutine$d__12::System_Collections_Generic_IEnumerator$System_Object$_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$DespawnAnimationCoroutine$d__12::System.Collections.Generic.IEnumerator<System.Object>.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.Generic.IEnumerator<System.Object>.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<DespawnAnimationCoroutine>d__12.System.Collections.IEnumerator.Reset\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarController::$DespawnAnimationCoroutine$d__12::System_Collections_IEnumerator_Reset() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$DespawnAnimationCoroutine$d__12::System.Collections.IEnumerator.Reset\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.Reset\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarController\/<DespawnAnimationCoroutine>d__12.System.Collections.IEnumerator.get_Current\r\n::Il2CppObject* GlobalNamespace::MultiplayerLobbyAvatarController::$DespawnAnimationCoroutine$d__12::System_Collections_IEnumerator_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarController::$DespawnAnimationCoroutine$d__12::System.Collections.IEnumerator.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: MultiplayerLobbyAvatarManager\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarManager.hpp\"\r\n\/\/ Including type: MultiplayerLobbyAvatarManager\/<RemovePlayerAndDestroy>d__13\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarManager_-RemovePlayerAndDestroy-d__13.hpp\"\r\n\/\/ Including type: ILobbyStateDataModel\r\n#include \"GlobalNamespace\/ILobbyStateDataModel.hpp\"\r\n\/\/ Including type: System.Collections.Generic.Dictionary`2\r\n#include \"System\/Collections\/Generic\/Dictionary_2.hpp\"\r\n\/\/ Including type: System.Collections.Generic.HashSet`1\r\n#include \"System\/Collections\/Generic\/HashSet_1.hpp\"\r\n\/\/ Including type: IConnectedPlayer\r\n#include \"GlobalNamespace\/IConnectedPlayer.hpp\"\r\n\/\/ Including type: System.Collections.IEnumerator\r\n#include \"System\/Collections\/IEnumerator.hpp\"\r\n\/\/ Including type: MultiplayerLobbyAvatarController\/Factory\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarController_Factory.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarManager.Init\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarManager::Init(float innerCircleRadius, float minOuterCircleRadius) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarManager::Init\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Init\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(innerCircleRadius), ::il2cpp_utils::ExtractType(minOuterCircleRadius)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, innerCircleRadius, minOuterCircleRadius);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarManager.ActivateMultiplayerLobbyAvatarManager\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarManager::ActivateMultiplayerLobbyAvatarManager() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarManager::ActivateMultiplayerLobbyAvatarManager\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"ActivateMultiplayerLobbyAvatarManager\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarManager.DeactivateMultiplayerLobbyAvatarManager\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarManager::DeactivateMultiplayerLobbyAvatarManager() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarManager::DeactivateMultiplayerLobbyAvatarManager\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"DeactivateMultiplayerLobbyAvatarManager\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarManager.HandleLobbyStateDataModelPlayerConnected\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarManager::HandleLobbyStateDataModelPlayerConnected(GlobalNamespace::IConnectedPlayer* connectedPlayer) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarManager::HandleLobbyStateDataModelPlayerConnected\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleLobbyStateDataModelPlayerConnected\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(connectedPlayer)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, connectedPlayer);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarManager.HandleLobbyStateDataModelPlayerDisconnected\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarManager::HandleLobbyStateDataModelPlayerDisconnected(GlobalNamespace::IConnectedPlayer* connectedPlayer) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarManager::HandleLobbyStateDataModelPlayerDisconnected\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleLobbyStateDataModelPlayerDisconnected\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(connectedPlayer)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, connectedPlayer);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarManager.AddPlayer\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarManager::AddPlayer(GlobalNamespace::IConnectedPlayer* connectedPlayer) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarManager::AddPlayer\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"AddPlayer\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(connectedPlayer)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, connectedPlayer);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarManager.RemovePlayer\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarManager::RemovePlayer(GlobalNamespace::IConnectedPlayer* connectedPlayer) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarManager::RemovePlayer\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"RemovePlayer\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(connectedPlayer)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, connectedPlayer);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarManager.RemovePlayerAndDestroy\r\nSystem::Collections::IEnumerator* GlobalNamespace::MultiplayerLobbyAvatarManager::RemovePlayerAndDestroy(::Il2CppString* userId, GlobalNamespace::MultiplayerLobbyAvatarController* multiplayerAvatar) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarManager::RemovePlayerAndDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"RemovePlayerAndDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(userId), ::il2cpp_utils::ExtractType(multiplayerAvatar)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Collections::IEnumerator*, false>(this, ___internal__method, userId, multiplayerAvatar);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: MultiplayerLobbyAvatarManager\/<RemovePlayerAndDestroy>d__13\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarManager_-RemovePlayerAndDestroy-d__13.hpp\"\r\n\/\/ Including type: MultiplayerLobbyAvatarController\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarController.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarManager\/<RemovePlayerAndDestroy>d__13.System.IDisposable.Dispose\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarManager::$RemovePlayerAndDestroy$d__13::System_IDisposable_Dispose() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarManager::$RemovePlayerAndDestroy$d__13::System.IDisposable.Dispose\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.IDisposable.Dispose\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarManager\/<RemovePlayerAndDestroy>d__13.MoveNext\r\nbool GlobalNamespace::MultiplayerLobbyAvatarManager::$RemovePlayerAndDestroy$d__13::MoveNext() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarManager::$RemovePlayerAndDestroy$d__13::MoveNext\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"MoveNext\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarManager\/<RemovePlayerAndDestroy>d__13.System.Collections.Generic.IEnumerator<System.Object>.get_Current\r\n::Il2CppObject* GlobalNamespace::MultiplayerLobbyAvatarManager::$RemovePlayerAndDestroy$d__13::System_Collections_Generic_IEnumerator$System_Object$_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarManager::$RemovePlayerAndDestroy$d__13::System.Collections.Generic.IEnumerator<System.Object>.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.Generic.IEnumerator<System.Object>.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarManager\/<RemovePlayerAndDestroy>d__13.System.Collections.IEnumerator.Reset\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarManager::$RemovePlayerAndDestroy$d__13::System_Collections_IEnumerator_Reset() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarManager::$RemovePlayerAndDestroy$d__13::System.Collections.IEnumerator.Reset\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.Reset\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarManager\/<RemovePlayerAndDestroy>d__13.System.Collections.IEnumerator.get_Current\r\n::Il2CppObject* GlobalNamespace::MultiplayerLobbyAvatarManager::$RemovePlayerAndDestroy$d__13::System_Collections_IEnumerator_get_Current() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarManager::$RemovePlayerAndDestroy$d__13::System.Collections.IEnumerator.get_Current\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"System.Collections.IEnumerator.get_Current\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: MultiplayerLobbyAvatarPlace\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarPlace.hpp\"\r\n\/\/ Including type: MultiplayerLobbyAvatarPlace\/Pool\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarPlace_Pool.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarPlace.SetPositionAndRotation\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarPlace::SetPositionAndRotation(UnityEngine::Vector3 worldPos, UnityEngine::Quaternion rotation) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarPlace::SetPositionAndRotation\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"SetPositionAndRotation\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(worldPos), ::il2cpp_utils::ExtractType(rotation)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, worldPos, rotation);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: MultiplayerLobbyAvatarPlace\/Pool\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarPlace_Pool.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: MultiplayerLobbyAvatarPlaceManager\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarPlaceManager.hpp\"\r\n\/\/ Including type: ILobbyStateDataModel\r\n#include \"GlobalNamespace\/ILobbyStateDataModel.hpp\"\r\n\/\/ Including type: System.Collections.Generic.List`1\r\n#include \"System\/Collections\/Generic\/List_1.hpp\"\r\n\/\/ Including type: MultiplayerLobbyAvatarPlace\/Pool\r\n#include \"GlobalNamespace\/MultiplayerLobbyAvatarPlace_Pool.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarPlaceManager.Activate\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarPlaceManager::Activate(float innerCircleRadius, float minOuterCircleRadius) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarPlaceManager::Activate\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Activate\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(innerCircleRadius), ::il2cpp_utils::ExtractType(minOuterCircleRadius)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, innerCircleRadius, minOuterCircleRadius);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarPlaceManager.Deactivate\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarPlaceManager::Deactivate() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarPlaceManager::Deactivate\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Deactivate\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarPlaceManager.OnDestroy\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarPlaceManager::OnDestroy() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarPlaceManager::OnDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarPlaceManager.SpawnAllPlaces\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarPlaceManager::SpawnAllPlaces() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarPlaceManager::SpawnAllPlaces\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"SpawnAllPlaces\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: MultiplayerLobbyAvatarPlaceManager.DespawnAllPlaces\r\nvoid GlobalNamespace::MultiplayerLobbyAvatarPlaceManager::DespawnAllPlaces() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::MultiplayerLobbyAvatarPlaceManager::DespawnAllPlaces\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"DespawnAllPlaces\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: ShadowFollowController\r\n#include \"GlobalNamespace\/ShadowFollowController.hpp\"\r\n\/\/ Including type: UnityEngine.Transform\r\n#include \"UnityEngine\/Transform.hpp\"\r\n\/\/ Including type: UnityEngine.SpriteRenderer\r\n#include \"UnityEngine\/SpriteRenderer.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: ShadowFollowController.SetTargetTransform\r\nvoid GlobalNamespace::ShadowFollowController::SetTargetTransform(UnityEngine::Transform* target) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::ShadowFollowController::SetTargetTransform\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"SetTargetTransform\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(target)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, target);\r\n}\r\n\/\/ Autogenerated method: ShadowFollowController.Update\r\nvoid GlobalNamespace::ShadowFollowController::Update() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::ShadowFollowController::Update\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Update\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AchievementIdsModelSO\r\n#include \"GlobalNamespace\/AchievementIdsModelSO.hpp\"\r\n\/\/ Including type: System.Collections.Generic.List`1\r\n#include \"System\/Collections\/Generic\/List_1.hpp\"\r\n\/\/ Including type: AchievementSO\r\n#include \"GlobalNamespace\/AchievementSO.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AchievementIdsModelSO.get_achievementsIds\r\nSystem::Collections::Generic::List_1<GlobalNamespace::AchievementSO*>* GlobalNamespace::AchievementIdsModelSO::get_achievementsIds() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementIdsModelSO::get_achievementsIds\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_achievementsIds\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Collections::Generic::List_1<GlobalNamespace::AchievementSO*>*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AchievementSO\r\n#include \"GlobalNamespace\/AchievementSO.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AchievementSO.get_achievementId\r\n::Il2CppString* GlobalNamespace::AchievementSO::get_achievementId() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementSO::get_achievementId\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_achievementId\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Il2CppString*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AchievementsEvaluationHandler\r\n#include \"GlobalNamespace\/AchievementsEvaluationHandler.hpp\"\r\n\/\/ Including type: AchievementsModelSO\r\n#include \"GlobalNamespace\/AchievementsModelSO.hpp\"\r\n\/\/ Including type: AchievementSO\r\n#include \"GlobalNamespace\/AchievementSO.hpp\"\r\n\/\/ Including type: PlayerDataModel\r\n#include \"GlobalNamespace\/PlayerDataModel.hpp\"\r\n\/\/ Including type: MissionNodesManager\r\n#include \"GlobalNamespace\/MissionNodesManager.hpp\"\r\n\/\/ Including type: LevelCompletionResults\r\n#include \"GlobalNamespace\/LevelCompletionResults.hpp\"\r\n\/\/ Including type: IDifficultyBeatmap\r\n#include \"GlobalNamespace\/IDifficultyBeatmap.hpp\"\r\n\/\/ Including type: MissionCompletionResults\r\n#include \"GlobalNamespace\/MissionCompletionResults.hpp\"\r\n\/\/ Including type: MissionNode\r\n#include \"GlobalNamespace\/MissionNode.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AchievementsEvaluationHandler.Start\r\nvoid GlobalNamespace::AchievementsEvaluationHandler::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementsEvaluationHandler::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AchievementsEvaluationHandler.OnDestroy\r\nvoid GlobalNamespace::AchievementsEvaluationHandler::OnDestroy() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementsEvaluationHandler::OnDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AchievementsEvaluationHandler.HandleSoloFreePlayOverallStatsDataDidUpdate\r\nvoid GlobalNamespace::AchievementsEvaluationHandler::HandleSoloFreePlayOverallStatsDataDidUpdate(GlobalNamespace::LevelCompletionResults* levelCompletionResults, GlobalNamespace::IDifficultyBeatmap* difficultyBeatmap) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementsEvaluationHandler::HandleSoloFreePlayOverallStatsDataDidUpdate\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleSoloFreePlayOverallStatsDataDidUpdate\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelCompletionResults), ::il2cpp_utils::ExtractType(difficultyBeatmap)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, levelCompletionResults, difficultyBeatmap);\r\n}\r\n\/\/ Autogenerated method: AchievementsEvaluationHandler.HandlePartyFreePlayOverallStatsDataDidUpdate\r\nvoid GlobalNamespace::AchievementsEvaluationHandler::HandlePartyFreePlayOverallStatsDataDidUpdate(GlobalNamespace::LevelCompletionResults* levelCompletionResults, GlobalNamespace::IDifficultyBeatmap* difficultyBeatmap) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementsEvaluationHandler::HandlePartyFreePlayOverallStatsDataDidUpdate\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandlePartyFreePlayOverallStatsDataDidUpdate\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelCompletionResults), ::il2cpp_utils::ExtractType(difficultyBeatmap)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, levelCompletionResults, difficultyBeatmap);\r\n}\r\n\/\/ Autogenerated method: AchievementsEvaluationHandler.HandleCampaignOverallStatsDataDidUpdate\r\nvoid GlobalNamespace::AchievementsEvaluationHandler::HandleCampaignOverallStatsDataDidUpdate(GlobalNamespace::MissionCompletionResults* missionCompletionResults, GlobalNamespace::MissionNode* missionNode) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementsEvaluationHandler::HandleCampaignOverallStatsDataDidUpdate\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleCampaignOverallStatsDataDidUpdate\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(missionCompletionResults), ::il2cpp_utils::ExtractType(missionNode)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, missionCompletionResults, missionNode);\r\n}\r\n\/\/ Autogenerated method: AchievementsEvaluationHandler.ProcessMissionFinishData\r\nvoid GlobalNamespace::AchievementsEvaluationHandler::ProcessMissionFinishData(GlobalNamespace::MissionNode* missionNode, GlobalNamespace::MissionCompletionResults* missionCompletionResults) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementsEvaluationHandler::ProcessMissionFinishData\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"ProcessMissionFinishData\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(missionNode), ::il2cpp_utils::ExtractType(missionCompletionResults)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, missionNode, missionCompletionResults);\r\n}\r\n\/\/ Autogenerated method: AchievementsEvaluationHandler.ProcessSoloFreePlayLevelFinishData\r\nvoid GlobalNamespace::AchievementsEvaluationHandler::ProcessSoloFreePlayLevelFinishData(GlobalNamespace::IDifficultyBeatmap* difficultyBeatmap, GlobalNamespace::LevelCompletionResults* levelCompletionResults) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementsEvaluationHandler::ProcessSoloFreePlayLevelFinishData\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"ProcessSoloFreePlayLevelFinishData\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(difficultyBeatmap), ::il2cpp_utils::ExtractType(levelCompletionResults)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, difficultyBeatmap, levelCompletionResults);\r\n}\r\n\/\/ Autogenerated method: AchievementsEvaluationHandler.ProcessLevelFinishData\r\nvoid GlobalNamespace::AchievementsEvaluationHandler::ProcessLevelFinishData(GlobalNamespace::IDifficultyBeatmap* difficultyBeatmap, GlobalNamespace::LevelCompletionResults* levelCompletionResults) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementsEvaluationHandler::ProcessLevelFinishData\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"ProcessLevelFinishData\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(difficultyBeatmap), ::il2cpp_utils::ExtractType(levelCompletionResults)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, difficultyBeatmap, levelCompletionResults);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AchievementsModelSO\r\n#include \"GlobalNamespace\/AchievementsModelSO.hpp\"\r\n\/\/ Including type: AchievementsModelSO\/<>c__DisplayClass4_0\r\n#include \"GlobalNamespace\/AchievementsModelSO_--c__DisplayClass4_0.hpp\"\r\n\/\/ Including type: PlatformAchievementsModelSO\/GetUnlockedAchievementsResult\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_GetUnlockedAchievementsResult.hpp\"\r\n\/\/ Including type: System.Collections.Generic.HashSet`1\r\n#include \"System\/Collections\/Generic\/HashSet_1.hpp\"\r\n\/\/ Including type: AchievementSO\r\n#include \"GlobalNamespace\/AchievementSO.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AchievementsModelSO.Initialize\r\nvoid GlobalNamespace::AchievementsModelSO::Initialize() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementsModelSO::Initialize\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Initialize\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AchievementsModelSO.UnlockAchievement\r\nvoid GlobalNamespace::AchievementsModelSO::UnlockAchievement(GlobalNamespace::AchievementSO* achievement) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementsModelSO::UnlockAchievement\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"UnlockAchievement\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(achievement)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, achievement);\r\n}\r\n\/\/ Autogenerated method: AchievementsModelSO.<Initialize>b__3_0\r\nvoid GlobalNamespace::AchievementsModelSO::$Initialize$b__3_0(GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult result, ::Array<::Il2CppString*>* achievementIds) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementsModelSO::<Initialize>b__3_0\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<Initialize>b__3_0\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result), ::il2cpp_utils::ExtractType(achievementIds)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, result, achievementIds);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AchievementsModelSO\/<>c__DisplayClass4_0\r\n#include \"GlobalNamespace\/AchievementsModelSO_--c__DisplayClass4_0.hpp\"\r\n\/\/ Including type: PlatformAchievementsModelSO\/UnlockAchievementResult\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_UnlockAchievementResult.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AchievementsModelSO\/<>c__DisplayClass4_0.<UnlockAchievement>b__0\r\nvoid GlobalNamespace::AchievementsModelSO::$$c__DisplayClass4_0::$UnlockAchievement$b__0(GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult result) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AchievementsModelSO::$$c__DisplayClass4_0::<UnlockAchievement>b__0\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"<UnlockAchievement>b__0\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, result);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: FinishTutorialAchievementHandler\r\n#include \"GlobalNamespace\/FinishTutorialAchievementHandler.hpp\"\r\n\/\/ Including type: AchievementsModelSO\r\n#include \"GlobalNamespace\/AchievementsModelSO.hpp\"\r\n\/\/ Including type: Signal\r\n#include \"GlobalNamespace\/Signal.hpp\"\r\n\/\/ Including type: AchievementSO\r\n#include \"GlobalNamespace\/AchievementSO.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: FinishTutorialAchievementHandler.Start\r\nvoid GlobalNamespace::FinishTutorialAchievementHandler::Start() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::FinishTutorialAchievementHandler::Start\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Start\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: FinishTutorialAchievementHandler.OnDestroy\r\nvoid GlobalNamespace::FinishTutorialAchievementHandler::OnDestroy() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::FinishTutorialAchievementHandler::OnDestroy\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnDestroy\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: FinishTutorialAchievementHandler.HandleTutorialFinished\r\nvoid GlobalNamespace::FinishTutorialAchievementHandler::HandleTutorialFinished() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::FinishTutorialAchievementHandler::HandleTutorialFinished\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HandleTutorialFinished\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: PlatformAchievementsHandler\r\n#include \"GlobalNamespace\/PlatformAchievementsHandler.hpp\"\r\n\/\/ Including type: HMAsyncRequest\r\n#include \"GlobalNamespace\/HMAsyncRequest.hpp\"\r\n\/\/ Including type: PlatformAchievementsModelSO\/UnlockAchievementCompletionHandler\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_UnlockAchievementCompletionHandler.hpp\"\r\n\/\/ Including type: PlatformAchievementsModelSO\/GetUnlockedAchievementsCompletionHandler\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_GetUnlockedAchievementsCompletionHandler.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: PlatformAchievementsHandler.UnlockAchievement\r\nGlobalNamespace::HMAsyncRequest* GlobalNamespace::PlatformAchievementsHandler::UnlockAchievement(::Il2CppString* achievementId, GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler* completionHandler) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsHandler::UnlockAchievement\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"UnlockAchievement\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(achievementId), ::il2cpp_utils::ExtractType(completionHandler)})));\r\n  return ::il2cpp_utils::RunMethodThrow<GlobalNamespace::HMAsyncRequest*, false>(this, ___internal__method, achievementId, completionHandler);\r\n}\r\n\/\/ Autogenerated method: PlatformAchievementsHandler.GetUnlockedAchievements\r\nGlobalNamespace::HMAsyncRequest* GlobalNamespace::PlatformAchievementsHandler::GetUnlockedAchievements(GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsCompletionHandler* completionHandler) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsHandler::GetUnlockedAchievements\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"GetUnlockedAchievements\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(completionHandler)})));\r\n  return ::il2cpp_utils::RunMethodThrow<GlobalNamespace::HMAsyncRequest*, false>(this, ___internal__method, completionHandler);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: PlatformAchievementsModelSO\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO.hpp\"\r\n\/\/ Including type: PlatformAchievementsModelSO\/UnlockAchievementResult\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_UnlockAchievementResult.hpp\"\r\n\/\/ Including type: PlatformAchievementsModelSO\/GetUnlockedAchievementsResult\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_GetUnlockedAchievementsResult.hpp\"\r\n\/\/ Including type: PlatformAchievementsModelSO\/UnlockAchievementCompletionHandler\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_UnlockAchievementCompletionHandler.hpp\"\r\n\/\/ Including type: PlatformAchievementsModelSO\/GetUnlockedAchievementsCompletionHandler\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_GetUnlockedAchievementsCompletionHandler.hpp\"\r\n\/\/ Including type: PS4AchievementIdsModelSO\r\n#include \"GlobalNamespace\/PS4AchievementIdsModelSO.hpp\"\r\n\/\/ Including type: AchievementIdsModelSO\r\n#include \"GlobalNamespace\/AchievementIdsModelSO.hpp\"\r\n\/\/ Including type: PlatformAchievementsHandler\r\n#include \"GlobalNamespace\/PlatformAchievementsHandler.hpp\"\r\n\/\/ Including type: HMAsyncRequest\r\n#include \"GlobalNamespace\/HMAsyncRequest.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: PlatformAchievementsModelSO.get_platformAchievementsHandler\r\nGlobalNamespace::PlatformAchievementsHandler* GlobalNamespace::PlatformAchievementsModelSO::get_platformAchievementsHandler() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::get_platformAchievementsHandler\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_platformAchievementsHandler\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<GlobalNamespace::PlatformAchievementsHandler*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: PlatformAchievementsModelSO.Initialize\r\nvoid GlobalNamespace::PlatformAchievementsModelSO::Initialize() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::Initialize\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Initialize\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: PlatformAchievementsModelSO.CreatePlatformAchievementsHandler\r\nvoid GlobalNamespace::PlatformAchievementsModelSO::CreatePlatformAchievementsHandler() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::CreatePlatformAchievementsHandler\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"CreatePlatformAchievementsHandler\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: PlatformAchievementsModelSO.UnlockAchievement\r\nGlobalNamespace::HMAsyncRequest* GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievement(::Il2CppString* achievementId, GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler* completionHandler) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievement\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"UnlockAchievement\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(achievementId), ::il2cpp_utils::ExtractType(completionHandler)})));\r\n  return ::il2cpp_utils::RunMethodThrow<GlobalNamespace::HMAsyncRequest*, false>(this, ___internal__method, achievementId, completionHandler);\r\n}\r\n\/\/ Autogenerated method: PlatformAchievementsModelSO.GetUnlockedAchievements\r\nGlobalNamespace::HMAsyncRequest* GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievements(GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsCompletionHandler* completionHandler) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievements\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"GetUnlockedAchievements\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(completionHandler)})));\r\n  return ::il2cpp_utils::RunMethodThrow<GlobalNamespace::HMAsyncRequest*, false>(this, ___internal__method, completionHandler);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: PlatformAchievementsModelSO\/UnlockAchievementResult\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_UnlockAchievementResult.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public PlatformAchievementsModelSO\/UnlockAchievementResult OK\r\nGlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult::_get_OK() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult::_get_OK\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult>(\"\", \"PlatformAchievementsModelSO\/UnlockAchievementResult\", \"OK\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public PlatformAchievementsModelSO\/UnlockAchievementResult OK\r\nvoid GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult::_set_OK(GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult::_set_OK\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"PlatformAchievementsModelSO\/UnlockAchievementResult\", \"OK\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public PlatformAchievementsModelSO\/UnlockAchievementResult Failed\r\nGlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult::_get_Failed() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult::_get_Failed\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult>(\"\", \"PlatformAchievementsModelSO\/UnlockAchievementResult\", \"Failed\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public PlatformAchievementsModelSO\/UnlockAchievementResult Failed\r\nvoid GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult::_set_Failed(GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult::_set_Failed\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"PlatformAchievementsModelSO\/UnlockAchievementResult\", \"Failed\", value));\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: PlatformAchievementsModelSO\/GetUnlockedAchievementsResult\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_GetUnlockedAchievementsResult.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public PlatformAchievementsModelSO\/GetUnlockedAchievementsResult OK\r\nGlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult::_get_OK() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult::_get_OK\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult>(\"\", \"PlatformAchievementsModelSO\/GetUnlockedAchievementsResult\", \"OK\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public PlatformAchievementsModelSO\/GetUnlockedAchievementsResult OK\r\nvoid GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult::_set_OK(GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult::_set_OK\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"PlatformAchievementsModelSO\/GetUnlockedAchievementsResult\", \"OK\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public PlatformAchievementsModelSO\/GetUnlockedAchievementsResult Failed\r\nGlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult::_get_Failed() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult::_get_Failed\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult>(\"\", \"PlatformAchievementsModelSO\/GetUnlockedAchievementsResult\", \"Failed\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public PlatformAchievementsModelSO\/GetUnlockedAchievementsResult Failed\r\nvoid GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult::_set_Failed(GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult::_set_Failed\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"PlatformAchievementsModelSO\/GetUnlockedAchievementsResult\", \"Failed\", value));\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: PlatformAchievementsModelSO\/UnlockAchievementCompletionHandler\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_UnlockAchievementCompletionHandler.hpp\"\r\n\/\/ Including type: System.IAsyncResult\r\n#include \"System\/IAsyncResult.hpp\"\r\n\/\/ Including type: System.AsyncCallback\r\n#include \"System\/AsyncCallback.hpp\"\r\n\/\/ Including type: PlatformAchievementsModelSO\/UnlockAchievementResult\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_UnlockAchievementResult.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: PlatformAchievementsModelSO\/UnlockAchievementCompletionHandler.Invoke\r\nvoid GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::Invoke(GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult result) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::Invoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Invoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, result);\r\n}\r\n\/\/ Autogenerated method: PlatformAchievementsModelSO\/UnlockAchievementCompletionHandler.BeginInvoke\r\nSystem::IAsyncResult* GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::BeginInvoke(GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementResult result, System::AsyncCallback* callback, ::Il2CppObject* object) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::BeginInvoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"BeginInvoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result), ::il2cpp_utils::ExtractType(callback), ::il2cpp_utils::ExtractType(object)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::IAsyncResult*, false>(this, ___internal__method, result, callback, object);\r\n}\r\n\/\/ Autogenerated method: PlatformAchievementsModelSO\/UnlockAchievementCompletionHandler.EndInvoke\r\nvoid GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::EndInvoke(System::IAsyncResult* result) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::UnlockAchievementCompletionHandler::EndInvoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"EndInvoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, result);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: PlatformAchievementsModelSO\/GetUnlockedAchievementsCompletionHandler\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_GetUnlockedAchievementsCompletionHandler.hpp\"\r\n\/\/ Including type: System.IAsyncResult\r\n#include \"System\/IAsyncResult.hpp\"\r\n\/\/ Including type: System.AsyncCallback\r\n#include \"System\/AsyncCallback.hpp\"\r\n\/\/ Including type: PlatformAchievementsModelSO\/GetUnlockedAchievementsResult\r\n#include \"GlobalNamespace\/PlatformAchievementsModelSO_GetUnlockedAchievementsResult.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: PlatformAchievementsModelSO\/GetUnlockedAchievementsCompletionHandler.Invoke\r\nvoid GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsCompletionHandler::Invoke(GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult result, ::Array<::Il2CppString*>* unlockedAchievementsIds) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsCompletionHandler::Invoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"Invoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result), ::il2cpp_utils::ExtractType(unlockedAchievementsIds)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, result, unlockedAchievementsIds);\r\n}\r\n\/\/ Autogenerated method: PlatformAchievementsModelSO\/GetUnlockedAchievementsCompletionHandler.BeginInvoke\r\nSystem::IAsyncResult* GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsCompletionHandler::BeginInvoke(GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsResult result, ::Array<::Il2CppString*>* unlockedAchievementsIds, System::AsyncCallback* callback, ::Il2CppObject* object) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsCompletionHandler::BeginInvoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"BeginInvoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result), ::il2cpp_utils::ExtractType(unlockedAchievementsIds), ::il2cpp_utils::ExtractType(callback), ::il2cpp_utils::ExtractType(object)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::IAsyncResult*, false>(this, ___internal__method, result, unlockedAchievementsIds, callback, object);\r\n}\r\n\/\/ Autogenerated method: PlatformAchievementsModelSO\/GetUnlockedAchievementsCompletionHandler.EndInvoke\r\nvoid GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsCompletionHandler::EndInvoke(System::IAsyncResult* result) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::PlatformAchievementsModelSO::GetUnlockedAchievementsCompletionHandler::EndInvoke\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"EndInvoke\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, result);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AdditionalContentModel\r\n#include \"GlobalNamespace\/AdditionalContentModel.hpp\"\r\n\/\/ Including type: System.Threading.CancellationToken\r\n#include \"System\/Threading\/CancellationToken.hpp\"\r\n\/\/ Including type: AdditionalContentModel\/UpdateEntitlementsResult\r\n#include \"GlobalNamespace\/AdditionalContentModel_UpdateEntitlementsResult.hpp\"\r\n\/\/ Including type: AdditionalContentModel\/<GetLevelEntitlementStatusAsync>d__10\r\n#include \"GlobalNamespace\/AdditionalContentModel_-GetLevelEntitlementStatusAsync-d__10.hpp\"\r\n\/\/ Including type: AdditionalContentModel\/<GetPackEntitlementStatusAsync>d__11\r\n#include \"GlobalNamespace\/AdditionalContentModel_-GetPackEntitlementStatusAsync-d__11.hpp\"\r\n\/\/ Including type: AlwaysOwnedContentContainerSO\r\n#include \"GlobalNamespace\/AlwaysOwnedContentContainerSO.hpp\"\r\n\/\/ Including type: System.Action\r\n#include \"System\/Action.hpp\"\r\n\/\/ Including type: System.Threading.Tasks.Task`1\r\n#include \"System\/Threading\/Tasks\/Task_1.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AdditionalContentModel.add_didInvalidateDataEvent\r\nvoid GlobalNamespace::AdditionalContentModel::add_didInvalidateDataEvent(System::Action* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::add_didInvalidateDataEvent\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"add_didInvalidateDataEvent\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: AdditionalContentModel.remove_didInvalidateDataEvent\r\nvoid GlobalNamespace::AdditionalContentModel::remove_didInvalidateDataEvent(System::Action* value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::remove_didInvalidateDataEvent\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"remove_didInvalidateDataEvent\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value);\r\n}\r\n\/\/ Autogenerated method: AdditionalContentModel.OnApplicationFocus\r\nvoid GlobalNamespace::AdditionalContentModel::OnApplicationFocus(bool hasFocus) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::OnApplicationFocus\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnApplicationFocus\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(hasFocus)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, hasFocus);\r\n}\r\n\/\/ Autogenerated method: AdditionalContentModel.InvalidateData\r\nvoid GlobalNamespace::AdditionalContentModel::InvalidateData() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::InvalidateData\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"InvalidateData\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AdditionalContentModel.GetLevelEntitlementStatusAsync\r\nSystem::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::EntitlementStatus>* GlobalNamespace::AdditionalContentModel::GetLevelEntitlementStatusAsync(::Il2CppString* levelId, System::Threading::CancellationToken token) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::GetLevelEntitlementStatusAsync\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"GetLevelEntitlementStatusAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelId), ::il2cpp_utils::ExtractType(token)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::EntitlementStatus>*, false>(this, ___internal__method, levelId, token);\r\n}\r\n\/\/ Autogenerated method: AdditionalContentModel.GetPackEntitlementStatusAsync\r\nSystem::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::EntitlementStatus>* GlobalNamespace::AdditionalContentModel::GetPackEntitlementStatusAsync(::Il2CppString* levelPackId, System::Threading::CancellationToken token) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::GetPackEntitlementStatusAsync\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"GetPackEntitlementStatusAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelPackId), ::il2cpp_utils::ExtractType(token)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::EntitlementStatus>*, false>(this, ___internal__method, levelPackId, token);\r\n}\r\n\/\/ Autogenerated method: AdditionalContentModel.InvalidateDataInternal\r\nvoid GlobalNamespace::AdditionalContentModel::InvalidateDataInternal() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::InvalidateDataInternal\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"InvalidateDataInternal\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AdditionalContentModel.GetLevelEntitlementStatusInternalAsync\r\nSystem::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::EntitlementStatus>* GlobalNamespace::AdditionalContentModel::GetLevelEntitlementStatusInternalAsync(::Il2CppString* levelId, System::Threading::CancellationToken token) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::GetLevelEntitlementStatusInternalAsync\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"GetLevelEntitlementStatusInternalAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelId), ::il2cpp_utils::ExtractType(token)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::EntitlementStatus>*, false>(this, ___internal__method, levelId, token);\r\n}\r\n\/\/ Autogenerated method: AdditionalContentModel.GetPackEntitlementStatusInternalAsync\r\nSystem::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::EntitlementStatus>* GlobalNamespace::AdditionalContentModel::GetPackEntitlementStatusInternalAsync(::Il2CppString* levelPackId, System::Threading::CancellationToken token) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::GetPackEntitlementStatusInternalAsync\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"GetPackEntitlementStatusInternalAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelPackId), ::il2cpp_utils::ExtractType(token)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::EntitlementStatus>*, false>(this, ___internal__method, levelPackId, token);\r\n}\r\n\/\/ Autogenerated method: AdditionalContentModel.IsPackBetterBuyThanLevelAsync\r\nSystem::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult>* GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelAsync(::Il2CppString* levelPackId, System::Threading::CancellationToken token) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelAsync\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"IsPackBetterBuyThanLevelAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelPackId), ::il2cpp_utils::ExtractType(token)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult>*, false>(this, ___internal__method, levelPackId, token);\r\n}\r\n\/\/ Autogenerated method: AdditionalContentModel.OpenLevelProductStoreAsync\r\nSystem::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::OpenProductStoreResult>* GlobalNamespace::AdditionalContentModel::OpenLevelProductStoreAsync(::Il2CppString* levelId, System::Threading::CancellationToken token) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::OpenLevelProductStoreAsync\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OpenLevelProductStoreAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelId), ::il2cpp_utils::ExtractType(token)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::OpenProductStoreResult>*, false>(this, ___internal__method, levelId, token);\r\n}\r\n\/\/ Autogenerated method: AdditionalContentModel.OpenLevelPackProductStoreAsync\r\nSystem::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::OpenProductStoreResult>* GlobalNamespace::AdditionalContentModel::OpenLevelPackProductStoreAsync(::Il2CppString* levelPackId, System::Threading::CancellationToken token) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::OpenLevelPackProductStoreAsync\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OpenLevelPackProductStoreAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelPackId), ::il2cpp_utils::ExtractType(token)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::OpenProductStoreResult>*, false>(this, ___internal__method, levelPackId, token);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AdditionalContentModel\/EntitlementStatus\r\n#include \"GlobalNamespace\/AdditionalContentModel.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public AdditionalContentModel\/EntitlementStatus Failed\r\nGlobalNamespace::AdditionalContentModel::EntitlementStatus GlobalNamespace::AdditionalContentModel::EntitlementStatus::_get_Failed() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::EntitlementStatus::_get_Failed\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::AdditionalContentModel::EntitlementStatus>(\"\", \"AdditionalContentModel\/EntitlementStatus\", \"Failed\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public AdditionalContentModel\/EntitlementStatus Failed\r\nvoid GlobalNamespace::AdditionalContentModel::EntitlementStatus::_set_Failed(GlobalNamespace::AdditionalContentModel::EntitlementStatus value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::EntitlementStatus::_set_Failed\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AdditionalContentModel\/EntitlementStatus\", \"Failed\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public AdditionalContentModel\/EntitlementStatus Owned\r\nGlobalNamespace::AdditionalContentModel::EntitlementStatus GlobalNamespace::AdditionalContentModel::EntitlementStatus::_get_Owned() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::EntitlementStatus::_get_Owned\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::AdditionalContentModel::EntitlementStatus>(\"\", \"AdditionalContentModel\/EntitlementStatus\", \"Owned\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public AdditionalContentModel\/EntitlementStatus Owned\r\nvoid GlobalNamespace::AdditionalContentModel::EntitlementStatus::_set_Owned(GlobalNamespace::AdditionalContentModel::EntitlementStatus value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::EntitlementStatus::_set_Owned\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AdditionalContentModel\/EntitlementStatus\", \"Owned\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public AdditionalContentModel\/EntitlementStatus NotOwned\r\nGlobalNamespace::AdditionalContentModel::EntitlementStatus GlobalNamespace::AdditionalContentModel::EntitlementStatus::_get_NotOwned() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::EntitlementStatus::_get_NotOwned\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::AdditionalContentModel::EntitlementStatus>(\"\", \"AdditionalContentModel\/EntitlementStatus\", \"NotOwned\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public AdditionalContentModel\/EntitlementStatus NotOwned\r\nvoid GlobalNamespace::AdditionalContentModel::EntitlementStatus::_set_NotOwned(GlobalNamespace::AdditionalContentModel::EntitlementStatus value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::EntitlementStatus::_set_NotOwned\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AdditionalContentModel\/EntitlementStatus\", \"NotOwned\", value));\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AdditionalContentModel\/OpenProductStoreResult\r\n#include \"GlobalNamespace\/AdditionalContentModel.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public AdditionalContentModel\/OpenProductStoreResult OK\r\nGlobalNamespace::AdditionalContentModel::OpenProductStoreResult GlobalNamespace::AdditionalContentModel::OpenProductStoreResult::_get_OK() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::OpenProductStoreResult::_get_OK\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::AdditionalContentModel::OpenProductStoreResult>(\"\", \"AdditionalContentModel\/OpenProductStoreResult\", \"OK\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public AdditionalContentModel\/OpenProductStoreResult OK\r\nvoid GlobalNamespace::AdditionalContentModel::OpenProductStoreResult::_set_OK(GlobalNamespace::AdditionalContentModel::OpenProductStoreResult value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::OpenProductStoreResult::_set_OK\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AdditionalContentModel\/OpenProductStoreResult\", \"OK\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public AdditionalContentModel\/OpenProductStoreResult Failed\r\nGlobalNamespace::AdditionalContentModel::OpenProductStoreResult GlobalNamespace::AdditionalContentModel::OpenProductStoreResult::_get_Failed() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::OpenProductStoreResult::_get_Failed\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::AdditionalContentModel::OpenProductStoreResult>(\"\", \"AdditionalContentModel\/OpenProductStoreResult\", \"Failed\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public AdditionalContentModel\/OpenProductStoreResult Failed\r\nvoid GlobalNamespace::AdditionalContentModel::OpenProductStoreResult::_set_Failed(GlobalNamespace::AdditionalContentModel::OpenProductStoreResult value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::OpenProductStoreResult::_set_Failed\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AdditionalContentModel\/OpenProductStoreResult\", \"Failed\", value));\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AdditionalContentModel\/UpdateEntitlementsResult\r\n#include \"GlobalNamespace\/AdditionalContentModel_UpdateEntitlementsResult.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public AdditionalContentModel\/UpdateEntitlementsResult OK\r\nGlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult::_get_OK() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult::_get_OK\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult>(\"\", \"AdditionalContentModel\/UpdateEntitlementsResult\", \"OK\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public AdditionalContentModel\/UpdateEntitlementsResult OK\r\nvoid GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult::_set_OK(GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult::_set_OK\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AdditionalContentModel\/UpdateEntitlementsResult\", \"OK\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public AdditionalContentModel\/UpdateEntitlementsResult Failed\r\nGlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult::_get_Failed() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult::_get_Failed\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult>(\"\", \"AdditionalContentModel\/UpdateEntitlementsResult\", \"Failed\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public AdditionalContentModel\/UpdateEntitlementsResult Failed\r\nvoid GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult::_set_Failed(GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult::_set_Failed\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AdditionalContentModel\/UpdateEntitlementsResult\", \"Failed\", value));\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n\/\/ Including type: AdditionalContentModel\/IsPackBetterBuyThanLevelResult\r\n#include \"GlobalNamespace\/AdditionalContentModel.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public AdditionalContentModel\/IsPackBetterBuyThanLevelResult PackIsBetter\r\nGlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult::_get_PackIsBetter() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult::_get_PackIsBetter\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult>(\"\", \"AdditionalContentModel\/IsPackBetterBuyThanLevelResult\", \"PackIsBetter\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public AdditionalContentModel\/IsPackBetterBuyThanLevelResult PackIsBetter\r\nvoid GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult::_set_PackIsBetter(GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult::_set_PackIsBetter\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AdditionalContentModel\/IsPackBetterBuyThanLevelResult\", \"PackIsBetter\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public AdditionalContentModel\/IsPackBetterBuyThanLevelResult LevelIsBetter\r\nGlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult::_get_LevelIsBetter() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult::_get_LevelIsBetter\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult>(\"\", \"AdditionalContentModel\/IsPackBetterBuyThanLevelResult\", \"LevelIsBetter\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public AdditionalContentModel\/IsPackBetterBuyThanLevelResult LevelIsBetter\r\nvoid GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult::_set_LevelIsBetter(GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult::_set_LevelIsBetter\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AdditionalContentModel\/IsPackBetterBuyThanLevelResult\", \"LevelIsBetter\", value));\r\n}\r\n\/\/ Autogenerated static field getter\r\n\/\/ Get static field: static public AdditionalContentModel\/IsPackBetterBuyThanLevelResult Failed\r\nGlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult::_get_Failed() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult::_get_Failed\");\r\n  return THROW_UNLESS(il2cpp_utils::GetFieldValue<GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult>(\"\", \"AdditionalContentModel\/IsPackBetterBuyThanLevelResult\", \"Failed\"));\r\n}\r\n\/\/ Autogenerated static field setter\r\n\/\/ Set static field: static public AdditionalContentModel\/IsPackBetterBuyThanLevelResult Failed\r\nvoid GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult::_set_Failed(GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult value) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult::_set_Failed\");\r\n  THROW_UNLESS(il2cpp_utils::SetFieldValue(\"\", \"AdditionalContentModel\/IsPackBetterBuyThanLevelResult\", \"Failed\", value));\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AdditionalContentModel\/<GetLevelEntitlementStatusAsync>d__10\r\n#include \"GlobalNamespace\/AdditionalContentModel_-GetLevelEntitlementStatusAsync-d__10.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AdditionalContentModel\/<GetLevelEntitlementStatusAsync>d__10.MoveNext\r\nvoid GlobalNamespace::AdditionalContentModel::$GetLevelEntitlementStatusAsync$d__10::MoveNext() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::$GetLevelEntitlementStatusAsync$d__10::MoveNext\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, \"MoveNext\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AdditionalContentModel\/<GetLevelEntitlementStatusAsync>d__10.SetStateMachine\r\nvoid GlobalNamespace::AdditionalContentModel::$GetLevelEntitlementStatusAsync$d__10::SetStateMachine(System::Runtime::CompilerServices::IAsyncStateMachine* stateMachine) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::$GetLevelEntitlementStatusAsync$d__10::SetStateMachine\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, \"SetStateMachine\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(stateMachine)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, stateMachine);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AdditionalContentModel\/<GetPackEntitlementStatusAsync>d__11\r\n#include \"GlobalNamespace\/AdditionalContentModel_-GetPackEntitlementStatusAsync-d__11.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AdditionalContentModel\/<GetPackEntitlementStatusAsync>d__11.MoveNext\r\nvoid GlobalNamespace::AdditionalContentModel::$GetPackEntitlementStatusAsync$d__11::MoveNext() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::$GetPackEntitlementStatusAsync$d__11::MoveNext\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, \"MoveNext\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AdditionalContentModel\/<GetPackEntitlementStatusAsync>d__11.SetStateMachine\r\nvoid GlobalNamespace::AdditionalContentModel::$GetPackEntitlementStatusAsync$d__11::SetStateMachine(System::Runtime::CompilerServices::IAsyncStateMachine* stateMachine) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AdditionalContentModel::$GetPackEntitlementStatusAsync$d__11::SetStateMachine\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, \"SetStateMachine\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(stateMachine)})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, stateMachine);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AlwaysOwnedContentContainerSO\r\n#include \"GlobalNamespace\/AlwaysOwnedContentContainerSO.hpp\"\r\n\/\/ Including type: AlwaysOwnedContentSO\r\n#include \"GlobalNamespace\/AlwaysOwnedContentSO.hpp\"\r\n\/\/ Including type: System.Collections.Generic.HashSet`1\r\n#include \"System\/Collections\/Generic\/HashSet_1.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AlwaysOwnedContentContainerSO.get_alwaysOwnedBeatmapLevelIds\r\nSystem::Collections::Generic::HashSet_1<::Il2CppString*>* GlobalNamespace::AlwaysOwnedContentContainerSO::get_alwaysOwnedBeatmapLevelIds() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AlwaysOwnedContentContainerSO::get_alwaysOwnedBeatmapLevelIds\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_alwaysOwnedBeatmapLevelIds\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Collections::Generic::HashSet_1<::Il2CppString*>*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AlwaysOwnedContentContainerSO.get_alwaysOwnedPacksIds\r\nSystem::Collections::Generic::HashSet_1<::Il2CppString*>* GlobalNamespace::AlwaysOwnedContentContainerSO::get_alwaysOwnedPacksIds() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AlwaysOwnedContentContainerSO::get_alwaysOwnedPacksIds\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_alwaysOwnedPacksIds\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Collections::Generic::HashSet_1<::Il2CppString*>*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AlwaysOwnedContentContainerSO.InitAlwaysOwnedItems\r\nvoid GlobalNamespace::AlwaysOwnedContentContainerSO::InitAlwaysOwnedItems() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AlwaysOwnedContentContainerSO::InitAlwaysOwnedItems\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"InitAlwaysOwnedItems\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AlwaysOwnedContentContainerSO.OnEnable\r\nvoid GlobalNamespace::AlwaysOwnedContentContainerSO::OnEnable() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AlwaysOwnedContentContainerSO::OnEnable\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OnEnable\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: AlwaysOwnedContentSO\r\n#include \"GlobalNamespace\/AlwaysOwnedContentSO.hpp\"\r\n\/\/ Including type: BeatmapLevelPackSO\r\n#include \"GlobalNamespace\/BeatmapLevelPackSO.hpp\"\r\n\/\/ Including type: BeatmapLevelSO\r\n#include \"GlobalNamespace\/BeatmapLevelSO.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: AlwaysOwnedContentSO.get_alwaysOwnedPacks\r\n::Array<GlobalNamespace::BeatmapLevelPackSO*>* GlobalNamespace::AlwaysOwnedContentSO::get_alwaysOwnedPacks() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AlwaysOwnedContentSO::get_alwaysOwnedPacks\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_alwaysOwnedPacks\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Array<GlobalNamespace::BeatmapLevelPackSO*>*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: AlwaysOwnedContentSO.get_alwaysOwnedBeatmapLevels\r\n::Array<GlobalNamespace::BeatmapLevelSO*>* GlobalNamespace::AlwaysOwnedContentSO::get_alwaysOwnedBeatmapLevels() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::AlwaysOwnedContentSO::get_alwaysOwnedBeatmapLevels\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"get_alwaysOwnedBeatmapLevels\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  return ::il2cpp_utils::RunMethodThrow<::Array<GlobalNamespace::BeatmapLevelSO*>*, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated from CppSourceCreator\r\n\/\/ Created by Sc2ad\r\n\/\/ =========================================================================\r\n\/\/ Begin includes\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/typedefs.h\"\r\n\/\/ Including type: OculusPlatformAdditionalContentModel\r\n#include \"GlobalNamespace\/OculusPlatformAdditionalContentModel.hpp\"\r\n\/\/ Including type: OculusPlatformAdditionalContentModel\/<GetLevelEntitlementStatusInternalAsync>d__5\r\n#include \"GlobalNamespace\/OculusPlatformAdditionalContentModel_-GetLevelEntitlementStatusInternalAsync-d__5.hpp\"\r\n\/\/ Including type: OculusPlatformAdditionalContentModel\/<GetPackEntitlementStatusInternalAsync>d__6\r\n#include \"GlobalNamespace\/OculusPlatformAdditionalContentModel_-GetPackEntitlementStatusInternalAsync-d__6.hpp\"\r\n\/\/ Including type: OculusPlatformAdditionalContentModel\/<DataIsValidAsync>d__7\r\n#include \"GlobalNamespace\/OculusPlatformAdditionalContentModel_-DataIsValidAsync-d__7.hpp\"\r\n\/\/ Including type: OculusPlatformAdditionalContentModel\/<OpenLevelProductStoreAsync>d__8\r\n#include \"GlobalNamespace\/OculusPlatformAdditionalContentModel_-OpenLevelProductStoreAsync-d__8.hpp\"\r\n\/\/ Including type: OculusPlatformAdditionalContentModel\/<OpenLevelPackProductStoreAsync>d__9\r\n#include \"GlobalNamespace\/OculusPlatformAdditionalContentModel_-OpenLevelPackProductStoreAsync-d__9.hpp\"\r\n\/\/ Including type: OculusPlatformAdditionalContentModel\/<>c__DisplayClass10_0\r\n#include \"GlobalNamespace\/OculusPlatformAdditionalContentModel_--c__DisplayClass10_0.hpp\"\r\n\/\/ Including type: OculusPlatformAdditionalContentModel\/<LaunchCheckoutFlow>d__10\r\n#include \"GlobalNamespace\/OculusPlatformAdditionalContentModel_-LaunchCheckoutFlow-d__10.hpp\"\r\n\/\/ Including type: OculusPlatformAdditionalContentModel\/<IsPackBetterBuyThanLevelAsync>d__11\r\n#include \"GlobalNamespace\/OculusPlatformAdditionalContentModel_-IsPackBetterBuyThanLevelAsync-d__11.hpp\"\r\n\/\/ Including type: OculusPlatformAdditionalContentModel\/<>c__DisplayClass12_0\r\n#include \"GlobalNamespace\/OculusPlatformAdditionalContentModel_--c__DisplayClass12_0.hpp\"\r\n\/\/ Including type: OculusPlatformAdditionalContentModel\/<CheckForNewEntitlementsAsync>d__12\r\n#include \"GlobalNamespace\/OculusPlatformAdditionalContentModel_-CheckForNewEntitlementsAsync-d__12.hpp\"\r\n\/\/ Including type: OculusLevelProductsModelSO\r\n#include \"GlobalNamespace\/OculusLevelProductsModelSO.hpp\"\r\n\/\/ Including type: System.Collections.Generic.HashSet`1\r\n#include \"System\/Collections\/Generic\/HashSet_1.hpp\"\r\n\/\/ Including type: System.Threading.SemaphoreSlim\r\n#include \"System\/Threading\/SemaphoreSlim.hpp\"\r\n\/\/ Including type: System.Threading.Tasks.Task`1\r\n#include \"System\/Threading\/Tasks\/Task_1.hpp\"\r\n\/\/ Including type: System.Threading.CancellationToken\r\n#include \"System\/Threading\/CancellationToken.hpp\"\r\n\/\/ Including type: Oculus.Platform.Message`1\r\n#include \"Oculus\/Platform\/Message_1.hpp\"\r\n\/\/ Including type: Oculus.Platform.Models.Purchase\r\n#include \"Oculus\/Platform\/Models\/Purchase.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/il2cpp-utils.hpp\"\r\n#include \"extern\/beatsaber-hook\/shared\/utils\/utils.h\"\r\n\/\/ Completed includes\r\n\/\/ Autogenerated method: OculusPlatformAdditionalContentModel.DataIsValidAsync\r\nSystem::Threading::Tasks::Task_1<bool>* GlobalNamespace::OculusPlatformAdditionalContentModel::DataIsValidAsync(System::Threading::CancellationToken cancellationToken) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::OculusPlatformAdditionalContentModel::DataIsValidAsync\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"DataIsValidAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(cancellationToken)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<bool>*, false>(this, ___internal__method, cancellationToken);\r\n}\r\n\/\/ Autogenerated method: OculusPlatformAdditionalContentModel.LaunchCheckoutFlow\r\nSystem::Threading::Tasks::Task_1<Oculus::Platform::Message_1<Oculus::Platform::Models::Purchase*>*>* GlobalNamespace::OculusPlatformAdditionalContentModel::LaunchCheckoutFlow(::Il2CppString* sku) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::OculusPlatformAdditionalContentModel::LaunchCheckoutFlow\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"LaunchCheckoutFlow\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sku)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<Oculus::Platform::Message_1<Oculus::Platform::Models::Purchase*>*>*, false>(this, ___internal__method, sku);\r\n}\r\n\/\/ Autogenerated method: OculusPlatformAdditionalContentModel.CheckForNewEntitlementsAsync\r\nSystem::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult>* GlobalNamespace::OculusPlatformAdditionalContentModel::CheckForNewEntitlementsAsync(System::Threading::CancellationToken cancellationToken) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::OculusPlatformAdditionalContentModel::CheckForNewEntitlementsAsync\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"CheckForNewEntitlementsAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(cancellationToken)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::UpdateEntitlementsResult>*, false>(this, ___internal__method, cancellationToken);\r\n}\r\n\/\/ Autogenerated method: OculusPlatformAdditionalContentModel.HasLevelEntitlement\r\nbool GlobalNamespace::OculusPlatformAdditionalContentModel::HasLevelEntitlement(::Il2CppString* levelId) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::OculusPlatformAdditionalContentModel::HasLevelEntitlement\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HasLevelEntitlement\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelId)})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, levelId);\r\n}\r\n\/\/ Autogenerated method: OculusPlatformAdditionalContentModel.HasLevelPackEntitlement\r\nbool GlobalNamespace::OculusPlatformAdditionalContentModel::HasLevelPackEntitlement(::Il2CppString* levelPackId) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::OculusPlatformAdditionalContentModel::HasLevelPackEntitlement\");\r\n  static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"HasLevelPackEntitlement\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelPackId)})));\r\n  return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, levelPackId);\r\n}\r\n\/\/ Autogenerated method: OculusPlatformAdditionalContentModel.InvalidateDataInternal\r\nvoid GlobalNamespace::OculusPlatformAdditionalContentModel::InvalidateDataInternal() {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::OculusPlatformAdditionalContentModel::InvalidateDataInternal\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"InvalidateDataInternal\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));\r\n  ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method);\r\n}\r\n\/\/ Autogenerated method: OculusPlatformAdditionalContentModel.GetLevelEntitlementStatusInternalAsync\r\nSystem::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::EntitlementStatus>* GlobalNamespace::OculusPlatformAdditionalContentModel::GetLevelEntitlementStatusInternalAsync(::Il2CppString* levelId, System::Threading::CancellationToken cancellationToken) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::OculusPlatformAdditionalContentModel::GetLevelEntitlementStatusInternalAsync\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"GetLevelEntitlementStatusInternalAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelId), ::il2cpp_utils::ExtractType(cancellationToken)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::EntitlementStatus>*, false>(this, ___internal__method, levelId, cancellationToken);\r\n}\r\n\/\/ Autogenerated method: OculusPlatformAdditionalContentModel.GetPackEntitlementStatusInternalAsync\r\nSystem::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::EntitlementStatus>* GlobalNamespace::OculusPlatformAdditionalContentModel::GetPackEntitlementStatusInternalAsync(::Il2CppString* packId, System::Threading::CancellationToken cancellationToken) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::OculusPlatformAdditionalContentModel::GetPackEntitlementStatusInternalAsync\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"GetPackEntitlementStatusInternalAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(packId), ::il2cpp_utils::ExtractType(cancellationToken)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::EntitlementStatus>*, false>(this, ___internal__method, packId, cancellationToken);\r\n}\r\n\/\/ Autogenerated method: OculusPlatformAdditionalContentModel.OpenLevelProductStoreAsync\r\nSystem::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::OpenProductStoreResult>* GlobalNamespace::OculusPlatformAdditionalContentModel::OpenLevelProductStoreAsync(::Il2CppString* levelId, System::Threading::CancellationToken cancellationToken) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::OculusPlatformAdditionalContentModel::OpenLevelProductStoreAsync\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OpenLevelProductStoreAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelId), ::il2cpp_utils::ExtractType(cancellationToken)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::OpenProductStoreResult>*, false>(this, ___internal__method, levelId, cancellationToken);\r\n}\r\n\/\/ Autogenerated method: OculusPlatformAdditionalContentModel.OpenLevelPackProductStoreAsync\r\nSystem::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::OpenProductStoreResult>* GlobalNamespace::OculusPlatformAdditionalContentModel::OpenLevelPackProductStoreAsync(::Il2CppString* levelPackId, System::Threading::CancellationToken cancellationToken) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::OculusPlatformAdditionalContentModel::OpenLevelPackProductStoreAsync\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"OpenLevelPackProductStoreAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelPackId), ::il2cpp_utils::ExtractType(cancellationToken)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::OpenProductStoreResult>*, false>(this, ___internal__method, levelPackId, cancellationToken);\r\n}\r\n\/\/ Autogenerated method: OculusPlatformAdditionalContentModel.IsPackBetterBuyThanLevelAsync\r\nSystem::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult>* GlobalNamespace::OculusPlatformAdditionalContentModel::IsPackBetterBuyThanLevelAsync(::Il2CppString* levelPackId, System::Threading::CancellationToken token) {\r\n  static auto ___internal__logger = ::Logger::get().WithContext(\"GlobalNamespace::OculusPlatformAdditionalContentModel::IsPackBetterBuyThanLevelAsync\");\r\n  auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, \"IsPackBetterBuyThanLevelAsync\", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(levelPackId), ::il2cpp_utils::ExtractType(token)})));\r\n  return ::il2cpp_utils::RunMethodThrow<System::Threading::Tasks::Task_1<GlobalNamespace::AdditionalContentModel::IsPackBetterBuyThanLevelResult>*, false>(this, ___internal__method, levelPackId, token);\r\n}\r\n","avg_line_length":83.3858622242,"max_line_length":693,"alphanum_fraction":0.7850512959,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7741,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause-Clear","Apache-2.0","MIT"],"max_stars_count":null,"content":"#include <Nazara\/Core\/SerializationContext.hpp>\n\n#include <Nazara\/Core\/Color.hpp>\n#include <Nazara\/Core\/MemoryView.hpp>\n#include <Nazara\/Math\/BoundingVolume.hpp>\n#include <Nazara\/Math\/Frustum.hpp>\n#include <Nazara\/Math\/Ray.hpp>\n#include <array>\n\n#include <Catch\/catch.hpp>\n\nSCENARIO(\"Serialization\", \"[CORE][SERIALIZATION]\")\n{\n\tGIVEN(\"A context of serialization\")\n\t{\n\t\tstd::array<char, 256> datas; \/\/ The array must be bigger than any of the serializable classes\n\t\tNz::MemoryView stream(datas.data(), datas.size());\n\n\t\tNz::SerializationContext context;\n\t\tcontext.stream = &stream;\n\n\t\tWHEN(\"We serialize basic types\")\n\t\t{\n\t\t\tTHEN(\"Arithmetical types\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Serialize(context, 3));\n\t\t\t\tint value = 0;\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &value));\n\t\t\t\tREQUIRE(value == 3);\n\t\t\t}\n\n\t\t\tTHEN(\"Boolean type\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Serialize(context, true));\n\t\t\t\tcontext.FlushBits(); \/\/< Don't forget to flush bits (it is NOT done by the stream)\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tbool value = false;\n\t\t\t\tREQUIRE(Unserialize(context, &value));\n\t\t\t\tREQUIRE(value == true);\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"We serialize mathematical classes\")\n\t\t{\n\t\t\tTHEN(\"BoudingVolume\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::BoundingVolumef nullVolume = Nz::BoundingVolumef::Null();\n\t\t\t\tNz::BoundingVolumef copy(nullVolume);\n\t\t\t\tREQUIRE(Serialize(context, nullVolume));\n\t\t\t\tnullVolume = Nz::BoundingVolumef::Infinite();\n\t\t\t\tREQUIRE(nullVolume != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &nullVolume));\n\t\t\t\tREQUIRE(nullVolume == copy);\n\t\t\t}\n\n\t\t\tTHEN(\"Box\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::Boxf zeroBox = Nz::Boxf::Zero();\n\t\t\t\tNz::Boxf copy(zeroBox);\n\t\t\t\tREQUIRE(Serialize(context, zeroBox));\n\t\t\t\tzeroBox = Nz::Boxf(1, 1, 1, 1, 1, 1);\n\t\t\t\tREQUIRE(zeroBox != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &zeroBox));\n\t\t\t\tREQUIRE(zeroBox == copy);\n\t\t\t}\n\n\t\t\tTHEN(\"EulerAngles\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::EulerAnglesf zeroEuler = Nz::EulerAnglesf::Zero();\n\t\t\t\tNz::EulerAnglesf copy(zeroEuler);\n\t\t\t\tREQUIRE(Serialize(context, zeroEuler));\n\t\t\t\tzeroEuler = Nz::EulerAnglesf(10, 24, 6); \/\/ Random values\n\t\t\t\tREQUIRE(zeroEuler != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &zeroEuler));\n\t\t\t\tREQUIRE(zeroEuler == copy);\n\t\t\t}\n\n\t\t\tTHEN(\"Frustum\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::Frustumf frustum;\n\t\t\t\tfrustum.Build(10, 10, 10, 100, Nz::Vector3f::UnitX(), Nz::Vector3f::UnitZ()); \/\/ Random values\n\t\t\t\tNz::Frustumf copy(frustum);\n\t\t\t\tREQUIRE(Serialize(context, frustum));\n\t\t\t\tfrustum.Build(50, 40, 20, 100, Nz::Vector3f::UnitX(), Nz::Vector3f::UnitZ());\n\t\t\t\tfor (unsigned int i = 0; i <= Nz::BoxCorner_Max; ++i)\n\t\t\t\t\tREQUIRE(frustum.GetCorner(static_cast<Nz::BoxCorner>(i)) != copy.GetCorner(static_cast<Nz::BoxCorner>(i)));\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &frustum));\n\t\t\t\tfor (unsigned int i = 0; i <= Nz::BoxCorner_Max; ++i)\n\t\t\t\t\tREQUIRE(frustum.GetCorner(static_cast<Nz::BoxCorner>(i)) == copy.GetCorner(static_cast<Nz::BoxCorner>(i)));\n\t\t\t}\n\n\t\t\tTHEN(\"Matrix4\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::Matrix4f zeroMatrix = Nz::Matrix4f::Zero();\n\t\t\t\tNz::Matrix4f copy(zeroMatrix);\n\t\t\t\tREQUIRE(Serialize(context, zeroMatrix));\n\t\t\t\tzeroMatrix = Nz::Matrix4f::Identity(); \/\/ Random values\n\t\t\t\tREQUIRE(zeroMatrix != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &zeroMatrix));\n\t\t\t\tREQUIRE(zeroMatrix == copy);\n\t\t\t}\n\n\t\t\tTHEN(\"OrientedBox\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::OrientedBoxf zeroOBB = Nz::OrientedBoxf::Zero();\n\t\t\t\tNz::OrientedBoxf copy(zeroOBB);\n\t\t\t\tREQUIRE(Serialize(context, zeroOBB));\n\t\t\t\tzeroOBB = Nz::OrientedBoxf(1, 1, 1, 1, 1, 1); \/\/ Random values\n\t\t\t\tREQUIRE(zeroOBB != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &zeroOBB));\n\t\t\t\tREQUIRE(zeroOBB == copy);\n\t\t\t}\n\n\t\t\tTHEN(\"Plane\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::Planef planeXY = Nz::Planef::XY();\n\t\t\t\tNz::Planef copy(planeXY);\n\t\t\t\tREQUIRE(Serialize(context, planeXY));\n\t\t\t\tplaneXY = Nz::Planef::YZ();\n\t\t\t\tREQUIRE(planeXY != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &planeXY));\n\t\t\t\tREQUIRE(planeXY == copy);\n\t\t\t}\n\n\t\t\tTHEN(\"Quaternion\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::Quaternionf quaternionIdentity = Nz::Quaternionf::Identity();\n\t\t\t\tNz::Quaternionf copy(quaternionIdentity);\n\t\t\t\tREQUIRE(Serialize(context, quaternionIdentity));\n\t\t\t\tquaternionIdentity = Nz::Quaternionf::Zero();\n\t\t\t\tREQUIRE(quaternionIdentity != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &quaternionIdentity));\n\t\t\t\tREQUIRE(quaternionIdentity == copy);\n\t\t\t}\n\n\t\t\tTHEN(\"Ray\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::Rayf axisX = Nz::Rayf::AxisX();\n\t\t\t\tNz::Rayf copy(axisX);\n\t\t\t\tREQUIRE(Serialize(context, axisX));\n\t\t\t\taxisX = Nz::Rayf::AxisY();\n\t\t\t\tREQUIRE(axisX != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &axisX));\n\t\t\t\tREQUIRE(axisX == copy);\n\t\t\t}\n\n\t\t\tTHEN(\"Rect\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::Rectf zeroRect = Nz::Rectf::Zero();\n\t\t\t\tNz::Rectf copy(zeroRect);\n\t\t\t\tREQUIRE(Serialize(context, zeroRect));\n\t\t\t\tzeroRect = Nz::Rectf(1, 1, 1, 1); \/\/ Random values\n\t\t\t\tREQUIRE(zeroRect != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &zeroRect));\n\t\t\t\tREQUIRE(zeroRect == copy);\n\t\t\t}\n\n\t\t\tTHEN(\"Sphere\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::Spheref zeroSphere = Nz::Spheref::Zero();\n\t\t\t\tNz::Spheref copy(zeroSphere);\n\t\t\t\tREQUIRE(Serialize(context, zeroSphere));\n\t\t\t\tzeroSphere = Nz::Spheref::Unit();\n\t\t\t\tREQUIRE(zeroSphere != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &zeroSphere));\n\t\t\t\tREQUIRE(zeroSphere == copy);\n\t\t\t}\n\n\t\t\tTHEN(\"Vector2\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::Vector2f unitX = Nz::Vector2f::UnitX();\n\t\t\t\tNz::Vector2f copy(unitX);\n\t\t\t\tREQUIRE(Serialize(context, unitX));\n\t\t\t\tunitX = Nz::Vector2f::UnitY();\n\t\t\t\tREQUIRE(unitX != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &unitX));\n\t\t\t\tREQUIRE(unitX == copy);\n\t\t\t}\n\n\t\t\tTHEN(\"Vector3\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::Vector3f unitX = Nz::Vector3f::UnitX();\n\t\t\t\tNz::Vector3f copy(unitX);\n\t\t\t\tREQUIRE(Serialize(context, unitX));\n\t\t\t\tunitX = Nz::Vector3f::UnitY();\n\t\t\t\tREQUIRE(unitX != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &unitX));\n\t\t\t\tREQUIRE(unitX == copy);\n\t\t\t}\n\n\t\t\tTHEN(\"Vector4\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::Vector4f unitX = Nz::Vector4f::UnitX();\n\t\t\t\tNz::Vector4f copy(unitX);\n\t\t\t\tREQUIRE(Serialize(context, unitX));\n\t\t\t\tunitX = Nz::Vector4f::UnitY();\n\t\t\t\tREQUIRE(unitX != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &unitX));\n\t\t\t\tREQUIRE(unitX == copy);\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"We serialize core classes\")\n\t\t{\n\t\t\tTHEN(\"Color\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tNz::Color red = Nz::Color::Red;\n\t\t\t\tNz::Color copy(red);\n\t\t\t\tREQUIRE(Serialize(context, red));\n\t\t\t\tred = Nz::Color::Black;\n\t\t\t\tREQUIRE(red != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &red));\n\t\t\t\tREQUIRE(red == copy);\n\t\t\t}\n\n\t\t\tTHEN(\"String\")\n\t\t\t{\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tstd::string string = \"string\";\n\t\t\t\tstd::string copy(string);\n\t\t\t\tREQUIRE(Serialize(context, string));\n\t\t\t\tstring = \"another\";\n\t\t\t\tREQUIRE(string != copy);\n\t\t\t\tcontext.stream->SetCursorPos(0);\n\t\t\t\tREQUIRE(Unserialize(context, &string));\n\t\t\t\tREQUIRE(string == copy);\n\t\t\t}\n\t\t}\n\t}\n}\n","avg_line_length":29.321969697,"max_line_length":112,"alphanum_fraction":0.648753391,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2245,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/===- TestConvertGPUKernelToCubin.cpp - Test gpu kernel cubin lowering ---===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"mlir\/Dialect\/GPU\/Passes.h\"\n\n#include \"mlir\/Pass\/Pass.h\"\n#include \"mlir\/Target\/LLVMIR\/Dialect\/NVVM\/NVVMToLLVMIRTranslation.h\"\n#include \"mlir\/Target\/LLVMIR\/Export.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n\nusing namespace mlir;\n\n#if MLIR_CUDA_CONVERSIONS_ENABLED\nnamespace {\nclass TestSerializeToCubinPass\n    : public PassWrapper<TestSerializeToCubinPass, gpu::SerializeToBlobPass> {\npublic:\n  TestSerializeToCubinPass();\n\nprivate:\n  void getDependentDialects(DialectRegistry &registry) const override;\n\n  \/\/ Serializes PTX to CUBIN.\n  std::unique_ptr<std::vector<char>>\n  serializeISA(const std::string &isa) override;\n};\n} \/\/ namespace\n\nTestSerializeToCubinPass::TestSerializeToCubinPass() {\n  this->triple = \"nvptx64-nvidia-cuda\";\n  this->chip = \"sm_35\";\n  this->features = \"+ptx60\";\n}\n\nvoid TestSerializeToCubinPass::getDependentDialects(\n    DialectRegistry &registry) const {\n  registerNVVMDialectTranslation(registry);\n  gpu::SerializeToBlobPass::getDependentDialects(registry);\n}\n\nstd::unique_ptr<std::vector<char>>\nTestSerializeToCubinPass::serializeISA(const std::string &) {\n  std::string data = \"CUBIN\";\n  return std::make_unique<std::vector<char>>(data.begin(), data.end());\n}\n\nnamespace mlir {\nnamespace test {\n\/\/ Register test pass to serialize GPU module to a CUBIN binary annotation.\nvoid registerTestGpuSerializeToCubinPass() {\n  PassRegistration<TestSerializeToCubinPass> registerSerializeToCubin(\n      \"test-gpu-to-cubin\",\n      \"Lower GPU kernel function to CUBIN binary annotations\", [] {\n        \/\/ Initialize LLVM NVPTX backend.\n        LLVMInitializeNVPTXTarget();\n        LLVMInitializeNVPTXTargetInfo();\n        LLVMInitializeNVPTXTargetMC();\n        LLVMInitializeNVPTXAsmPrinter();\n\n        return std::make_unique<TestSerializeToCubinPass>();\n      });\n}\n} \/\/ namespace test\n} \/\/ namespace mlir\n#endif \/\/ MLIR_CUDA_CONVERSIONS_ENABLED\n","avg_line_length":31.6197183099,"max_line_length":80,"alphanum_fraction":0.7202672606,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":29209,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/\/ Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied.  See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include <gtest\/gtest.h>\n\n#include \"olap\/column_file\/byte_buffer.h\"\n#include \"olap\/column_file\/out_stream.h\"\n#include \"olap\/column_file\/in_stream.h\"\n#include \"olap\/column_file\/file_stream.h\"\n#include \"olap\/column_file\/run_length_byte_writer.h\"\n#include \"olap\/column_file\/run_length_byte_reader.h\"\n#include \"olap\/column_file\/column_reader.h\"\n#include \"olap\/column_file\/stream_index_reader.h\"\n#include \"olap\/column_file\/stream_index_writer.h\"\n#include \"util\/logging.h\"\n\nnamespace palo {\nnamespace column_file {\n\nusing namespace testing;\n\nTEST(TestStream, UncompressOutStream) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE, NULL);\n    ASSERT_TRUE(out_stream != NULL);\n    ASSERT_TRUE(out_stream->_compressor == NULL);\n        \n    out_stream->write(0x5a);\n    out_stream->flush();\n\n    ASSERT_EQ(out_stream->get_stream_length(), sizeof(StreamHead) + 1);\n\n    ASSERT_EQ(out_stream->output_buffers().size(), 1);\n\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n    ASSERT_EQ((*it)->position(), 0);\n    StreamHead head;\n    (*it)->get((char *)&head, sizeof(head));\n    ASSERT_EQ(head.type, StreamHead::UNCOMPRESSED);\n    ASSERT_EQ(head.length, 1);\n    char data;\n    ASSERT_EQ(OLAP_SUCCESS, (*it)->get((char *)&data));\n    ASSERT_EQ(0x5A, data);\n    ASSERT_NE(OLAP_SUCCESS, (*it)->get((char *)&data));\n\n    SAFE_DELETE(out_stream);\n}\n\nTEST(TestStream, UncompressOutStream2) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE, NULL);\n    ASSERT_TRUE(out_stream != NULL);\n    ASSERT_TRUE(out_stream->_compressor == NULL);\n\n    for (int32_t i = 0; i < OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE; i++) {\n        out_stream->write(0x5a);\n    }\n    out_stream->write(0x5a);\n    out_stream->flush();\n\n    uint64_t stream_length = sizeof(StreamHead)*2 + OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE + 1;\n    ASSERT_EQ(out_stream->get_stream_length(), stream_length);\n\n    ASSERT_EQ(out_stream->output_buffers().size(), 2);\n\n    std::vector<ByteBuffer*> inputs;\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n    for (; it != out_stream->output_buffers().end(); ++it) {\n        ByteBuffer *tmp_byte_buffer = ByteBuffer::reference_buffer(*it, 0, (*it)->limit());\n        inputs.push_back(tmp_byte_buffer);\n    }\n    std::vector<uint64_t> offsets;\n    offsets.push_back(0);\n    offsets.push_back(sizeof(StreamHead) + OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE);\n    InStream *in_stream = \n            new (std::nothrow) InStream(&inputs, \n                                        offsets, \n                                        out_stream->get_stream_length(), \n                                        NULL, \n                                        out_stream->get_total_buffer_size());\n\n    char data;\n    for (int32_t i = 0; i < OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE-1; i++) {\n        \n        ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n        ASSERT_EQ(data, 0x5a);\n    }\n    ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n    ASSERT_EQ(data, 0x5a);\n    ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n    ASSERT_EQ(data, 0x5a);\n\n    ASSERT_NE(in_stream->read(&data), OLAP_SUCCESS);\n\n    SAFE_DELETE(out_stream);\n    SAFE_DELETE(in_stream);\n}\n\nTEST(TestStream, UncompressOutStream3) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE, NULL);\n    ASSERT_TRUE(out_stream != NULL);\n    ASSERT_TRUE(out_stream->_compressor == NULL);\n\n    for (int32_t i = 0; i < OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE; i++) {\n        out_stream->write(0x5a);\n    }\n    char write_data[2] = {0x5a, 0x5a};\n    out_stream->write(write_data, 2);\n    out_stream->flush();\n\n    uint64_t stream_length = sizeof(StreamHead)*2 + OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE + 2;\n    ASSERT_EQ(out_stream->get_stream_length(), stream_length);\n\n    ASSERT_EQ(out_stream->output_buffers().size(), 2);\n\n    std::vector<ByteBuffer*> inputs;\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n    for (; it != out_stream->output_buffers().end(); ++it) {\n        ByteBuffer *tmp_byte_buffer = ByteBuffer::reference_buffer(*it, 0, (*it)->limit());\n        inputs.push_back(tmp_byte_buffer);\n    }\n\n    std::vector<uint64_t> offsets;\n    offsets.push_back(0);\n    offsets.push_back(sizeof(StreamHead) + OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE);\n    InStream *in_stream = \n            new (std::nothrow) InStream(&inputs, \n                                        offsets, \n                                        out_stream->get_stream_length(), \n                                        NULL, \n                                        out_stream->get_total_buffer_size());\n\n    char data;\n    for (int32_t i = 0; i < OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE; i++) {\n        \n        ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n        ASSERT_EQ(data, 0x5a);\n    }\n    ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n    ASSERT_EQ(data, 0x5a);\n\n    ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n    ASSERT_EQ(data, 0x5a);\n\n    ASSERT_NE(in_stream->read(&data), OLAP_SUCCESS);\n\n    SAFE_DELETE(out_stream);\n}\n\n\nTEST(TestStream, UncompressInStream) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE, NULL);\n    ASSERT_TRUE(out_stream != NULL);\n    ASSERT_TRUE(out_stream->_compressor == NULL);\n        \n    out_stream->write(0x5a);\n    out_stream->flush();\n\n    \/\/ read data\n    std::vector<ByteBuffer*> inputs;\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n    ASSERT_NE(it, out_stream->output_buffers().end());\n    ByteBuffer *tmp_byte_buffer = ByteBuffer::reference_buffer(*it, 0, (*it)->capacity());\n    inputs.push_back(tmp_byte_buffer);\n\n    std::vector<uint64_t> offsets;\n    offsets.assign(inputs.size(), 0);\n    InStream *in_stream = \n            new (std::nothrow) InStream(&inputs, \n                                        offsets, \n                                        out_stream->get_stream_length(), \n                                        NULL, \n                                        out_stream->get_total_buffer_size());\n    SAFE_DELETE(out_stream);\n\n    ASSERT_EQ(in_stream->available(), 1);\n    char data;\n    ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n    ASSERT_EQ(data, 0x5a);\n\n    SAFE_DELETE(in_stream);\n}\n\n\/\/ the length after compress must be smaller than origal stream, then the compressor will be called. \nTEST(TestStream, CompressOutStream) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE, lzo_compress);\n    ASSERT_TRUE(out_stream != NULL);\n    ASSERT_TRUE(out_stream->_compressor != NULL);\n\n    char *write_data = new char[OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE];\n    memset(write_data, 0x5a, OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE);\n        \n    out_stream->write(write_data, OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE);\n    out_stream->flush();\n\n    \/\/ASSERT_EQ(out_stream->get_stream_length(), sizeof(StreamHead) + 2);\n\n    \/\/ASSERT_EQ(out_stream->output_buffers().size(), 1);\n\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n\n    StreamHead head;\n    (*it)->get((char *)&head, sizeof(head));\n    ASSERT_EQ(head.type, StreamHead::COMPRESSED);\n    ASSERT_EQ(head.length, 49);\n\n    SAFE_DELETE_ARRAY(write_data);\n    SAFE_DELETE(out_stream);\n}\n\nTEST(TestStream, CompressOutStream2) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE, lzo_compress);\n    ASSERT_TRUE(out_stream != NULL);\n    ASSERT_TRUE(out_stream->_compressor != NULL);\n\n    for (int32_t i = 0; i < OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE; i++) {\n        out_stream->write(0x5a);\n    }\n    out_stream->write(0x5a);\n    out_stream->flush();\n\n    std::vector<ByteBuffer*> inputs;\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n    for (; it != out_stream->output_buffers().end(); ++it) {\n        ByteBuffer *tmp_byte_buffer = ByteBuffer::reference_buffer(*it, 0, (*it)->limit());\n        inputs.push_back(tmp_byte_buffer);\n    }\n    std::vector<uint64_t> offsets;\n    offsets.push_back(0);\n    offsets.push_back(57);\n    InStream *in_stream = \n            new (std::nothrow) InStream(&inputs, \n                                        offsets, \n                                        out_stream->get_stream_length(), \n                                        lzo_decompress, \n                                        out_stream->get_total_buffer_size());\n\n    char data;\n    for (int32_t i = 0; i < OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE; i++) {\n        ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n        ASSERT_EQ(data, 0x5a);\n    }\n    ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n    ASSERT_EQ(data, 0x5a);\n\n    ASSERT_NE(in_stream->read(&data), OLAP_SUCCESS);\n\n    SAFE_DELETE(out_stream);\n}\n\n\nTEST(TestStream, CompressOutStream3) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE, lzo_compress);\n    ASSERT_TRUE(out_stream != NULL);\n    ASSERT_TRUE(out_stream->_compressor != NULL);\n\n    for (int32_t i = 0; i < OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE; i++) {\n        out_stream->write(0x5a);\n    }\n    char write_data[100];\n    for (int32_t i = 0; i < sizeof(write_data); i++) {\n        write_data[i] = 0x5a;\n    }\n    out_stream->write(write_data, sizeof(write_data));\n    out_stream->flush();\n\n    std::vector<ByteBuffer*> inputs;\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n    for (; it != out_stream->output_buffers().end(); ++it) {\n        ByteBuffer *tmp_byte_buffer = ByteBuffer::reference_buffer(*it, 0, (*it)->limit());\n        inputs.push_back(tmp_byte_buffer);\n    }\n    std::vector<uint64_t> offsets;\n    offsets.push_back(0);\n    offsets.push_back(57);\n    InStream *in_stream = \n            new (std::nothrow) InStream(&inputs, \n                                        offsets, \n                                        out_stream->get_stream_length(), \n                                        lzo_decompress, \n                                        out_stream->get_total_buffer_size());\n\n    char data;\n    for (int32_t i = 0; i < OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE; i++) {\n        ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n        ASSERT_EQ(data, 0x5a);\n    }\n    for (int32_t i = 0; i < sizeof(write_data); i++) {\n        ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n        ASSERT_EQ(data, write_data[i]);\n    }\n\n    ASSERT_NE(in_stream->read(&data), OLAP_SUCCESS);\n\n    SAFE_DELETE(out_stream);\n}\n\n\/\/test for _slice() in [while (len > 0 && m_current_range < m_inputs.size())]\nTEST(TestStream, CompressOutStream4) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(18, lzo_compress);\n    ASSERT_TRUE(out_stream != NULL);\n    ASSERT_TRUE(out_stream->_compressor != NULL);\n\n    for (int32_t i = 0; i < 15; i++) {\n        out_stream->write(0x5a);\n    }\n    out_stream->_spill();\n\n    for (int32_t i = 0; i < 12; i++) {\n        out_stream->write(0x5a);\n    }\n    for (int32_t i = 0; i < 6; i++) {\n        out_stream->write(i);\n    }\n    out_stream->flush();\n\n    std::vector<ByteBuffer*> inputs;\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n    for (; it != out_stream->output_buffers().end(); ++it) {\n        ByteBuffer *tmp_byte_buffer = ByteBuffer::reference_buffer(*it, 0, (*it)->limit());\n        inputs.push_back(tmp_byte_buffer);\n    }\n    std::vector<uint64_t> offsets;\n    offsets.push_back(0);\n    offsets.push_back(16);\n    InStream *in_stream = \n            new (std::nothrow) InStream(&inputs, \n                                        offsets, \n                                        out_stream->get_stream_length(), \n                                        lzo_decompress, \n                                        out_stream->get_total_buffer_size());\n\n    char data;\n    for (int32_t i = 0; i < 15; i++) {\n        ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n        ASSERT_EQ(data, 0x5a);\n    }\n\n    for (int32_t i = 0; i < 12; i++) {\n        ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n        ASSERT_EQ(data, 0x5a);\n    }\n\n\n    for (int32_t i = 0; i < 6; i++) {\n        ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n        ASSERT_EQ(data, i);\n    }\n\n    ASSERT_NE(in_stream->read(&data), OLAP_SUCCESS);\n\n    SAFE_DELETE(out_stream);\n}\n\nTEST(TestStream, CompressMassOutStream) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(100, lzo_compress);\n    ASSERT_TRUE(out_stream != NULL);\n    ASSERT_TRUE(out_stream->_compressor != NULL);\n\n    for (int32_t i = 0; i < 100; i++) {\n        out_stream->write(0x5a);\n    }\n    \/\/out_stream->write(0);\n    \n    for (int32_t i = 0; i < 100; i++) {\n        out_stream->write(i);\n    }\n    \/\/out_stream->write(100);\n    out_stream->flush();\n\n    std::vector<ByteBuffer*> inputs;\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n    for (; it != out_stream->output_buffers().end(); ++it) {\n        ByteBuffer *tmp_byte_buffer = ByteBuffer::reference_buffer(*it, 0, (*it)->limit());\n        inputs.push_back(tmp_byte_buffer);\n    }\n    std::vector<uint64_t> offsets;\n    offsets.push_back(0);\n    offsets.push_back(17);\n    InStream *in_stream = \n            new (std::nothrow) InStream(&inputs, \n                                        offsets, \n                                        out_stream->get_stream_length(), \n                                        lzo_decompress, \n                                        out_stream->get_total_buffer_size());\n    SAFE_DELETE(out_stream);\n\n    char data;\n    for (int32_t i = 0; i < 100; i++) {\n        ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n        ASSERT_EQ(data, 0x5a);\n    }\n    for (int32_t i = 0; i < 100; i++) {\n        ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n        ASSERT_EQ(data, i);\n    }\n\n    ASSERT_NE(in_stream->read(&data), OLAP_SUCCESS);\n\n    SAFE_DELETE(in_stream);\n}\n\nTEST(TestStream, CompressInStream) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE, lzo_compress);\n    ASSERT_TRUE(out_stream != NULL);\n    ASSERT_TRUE(out_stream->_compressor != NULL);\n        \n    char *write_data = new char[OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE];\n    memset(write_data, 0x5a, OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE);\n        \n    out_stream->write(write_data, OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE);\n    out_stream->flush();\n\n    \/\/ read data\n    std::vector<ByteBuffer*> inputs;\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n    ASSERT_NE(it, out_stream->output_buffers().end());\n    ByteBuffer *tmp_byte_buffer = ByteBuffer::reference_buffer(*it, 0, (*it)->capacity());\n    inputs.push_back(tmp_byte_buffer);\n\n    std::vector<uint64_t> offsets;\n    offsets.assign(inputs.size(), 0);\n    InStream *in_stream = new (std::nothrow) InStream(&inputs, \n                                                      offsets, \n                                                      out_stream->get_stream_length(), \n                                                      lzo_decompress, \n                                                      out_stream->get_total_buffer_size());\n    ASSERT_EQ(in_stream->available(), OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE);\n    char data;\n    for (int32_t i = 0; i < OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE-1; ++i) {\n        ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n        ASSERT_EQ(data, 0x5a);\n    }\n    ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n    ASSERT_EQ(data, 0x5a);\n    ASSERT_NE(in_stream->read(&data), OLAP_SUCCESS);\n\n    SAFE_DELETE_ARRAY(write_data);\n    SAFE_DELETE(out_stream);\n    SAFE_DELETE(in_stream);\n}\n\nTEST(TestStream, SeekUncompress) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE, NULL);\n    ASSERT_TRUE(out_stream != NULL);\n    ASSERT_TRUE(out_stream->_compressor == NULL);\n        \n    out_stream->write(0x5a);\n\n    PositionEntryWriter index_entry; \n    out_stream->get_position(&index_entry);\n    out_stream->write(0x5b);\n    ASSERT_EQ(index_entry.positions_count(), 2);\n    ASSERT_EQ(index_entry.positions(0), 0);\n    ASSERT_EQ(index_entry.positions(1), 1);\n    out_stream->flush();\n\n    \/\/ read data\n    std::vector<ByteBuffer*> inputs;\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n    ASSERT_NE(it, out_stream->output_buffers().end());\n    ByteBuffer *tmp_byte_buffer = ByteBuffer::reference_buffer(*it, 0, (*it)->capacity());\n    inputs.push_back(tmp_byte_buffer);\n\n    std::vector<uint64_t> offsets;\n    offsets.assign(inputs.size(), 0);\n    InStream *in_stream = \n            new (std::nothrow) InStream(&inputs, \n                                        offsets, \n                                        out_stream->get_stream_length(), \n                                        NULL, \n                                        out_stream->get_total_buffer_size());\n    ASSERT_EQ(in_stream->available(), 2);\n\n    char buffer[256];\n    index_entry.write_to_buffer(buffer);\n    StreamIndexHeader header;\n    header.position_format = index_entry.positions_count();\n    header.statistic_format = OLAP_FIELD_TYPE_TINYINT;\n    PositionEntryReader entry;\n    entry.init(&header, OLAP_FIELD_TYPE_TINYINT, false);\n    entry.attach(buffer);\n    PositionProvider position(&entry);\n\n    ASSERT_EQ(entry.positions_count(), 2);\n    ASSERT_EQ(entry.positions(0), 0);\n    ASSERT_EQ(entry.positions(1), 1);\n\n    in_stream->seek(&position);\n    char data;\n    ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n    ASSERT_EQ(data, 0x5b);\n    SAFE_DELETE(out_stream);\n    SAFE_DELETE(in_stream);\n}\n\nTEST(TestStream, SkipUncompress) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE, NULL);\n    ASSERT_TRUE(out_stream != NULL);\n    ASSERT_TRUE(out_stream->_compressor == NULL);\n\n    char write_data[] = {0x5a, 0x5b, 0x5c, 0x5d};\n    for (int32_t i = 0; i < sizeof(write_data); i++) {\n        out_stream->write(write_data[i]);\n    }\n    out_stream->write(0x5e);\n    out_stream->flush();\n\n    \/\/ read data\n    std::vector<ByteBuffer*> inputs;\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n    ASSERT_NE(it, out_stream->output_buffers().end());\n    ByteBuffer *tmp_byte_buffer = ByteBuffer::reference_buffer(*it, 0, (*it)->capacity());\n    inputs.push_back(tmp_byte_buffer);\n\n    std::vector<uint64_t> offsets;\n    offsets.assign(inputs.size(), 0);\n    InStream *in_stream = \n            new (std::nothrow) InStream(&inputs, \n                                        offsets, \n                                        out_stream->get_stream_length(), \n                                        NULL, \n                                        out_stream->get_total_buffer_size());\n    ASSERT_EQ(in_stream->available(), sizeof(write_data)+1);\n    in_stream->skip(sizeof(write_data)-1);\n    char data;\n    ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n    ASSERT_EQ(data, write_data[sizeof(write_data)-1]);\n    SAFE_DELETE(out_stream);\n    SAFE_DELETE(in_stream);\n}\n\nTEST(TestStream, SeekCompress) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE, lzo_compress);\n    ASSERT_TRUE(out_stream != NULL);\n\n    for (int32_t i = 0; i < 10; i++) {\n        out_stream->write(0x5a);\n    }\n\n    PositionEntryWriter index_entry;\n    out_stream->get_position(&index_entry);\n    out_stream->write(0x5b);\n    ASSERT_EQ(index_entry.positions_count(), 2);\n    ASSERT_EQ(index_entry.positions(0), 0);\n    ASSERT_EQ(index_entry.positions(1), 10);\n    out_stream->flush();\n\n    \/\/ read data\n    std::vector<ByteBuffer*> inputs;\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n    ASSERT_NE(it, out_stream->output_buffers().end());\n    ByteBuffer *tmp_byte_buffer = ByteBuffer::reference_buffer(*it, 0, (*it)->capacity());\n    inputs.push_back(tmp_byte_buffer);\n\n    std::vector<uint64_t> offsets;\n    offsets.assign(inputs.size(), 0);\n    InStream *in_stream = \n            new (std::nothrow) InStream(&inputs, \n                                        offsets, \n                                        out_stream->get_stream_length(), \n                                        lzo_decompress, \n                                        out_stream->get_total_buffer_size());\n    \/\/ASSERT_EQ(in_stream->available(), 2);\n    char buffer[256];\n    index_entry.write_to_buffer(buffer);\n    StreamIndexHeader header;\n    header.position_format = index_entry.positions_count();\n    header.statistic_format = OLAP_FIELD_TYPE_TINYINT;\n    PositionEntryReader entry;\n    entry.init(&header, OLAP_FIELD_TYPE_TINYINT, false);\n    entry.attach(buffer);\n\n    PositionProvider position(&entry);\n    in_stream->seek(&position);\n    char data;\n    ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n    ASSERT_EQ(data, 0x5b);\n    SAFE_DELETE(out_stream);\n    SAFE_DELETE(in_stream);\n}\n\nTEST(TestStream, SkipCompress) {\n    \/\/ write data\n    OutStream *out_stream = \n            new(std::nothrow) OutStream(OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE, lzo_compress);\n    ASSERT_TRUE(out_stream != NULL);\n\n    for (int32_t i = 0; i < 10; i++) {\n        out_stream->write(0x5a);\n    }\n    out_stream->write(0x5e);\n    out_stream->flush();\n\n    \/\/ read data\n    std::vector<ByteBuffer*> inputs;\n    std::vector<ByteBuffer*>::const_iterator it = out_stream->output_buffers().begin();\n    ASSERT_NE(it, out_stream->output_buffers().end());\n    ByteBuffer *tmp_byte_buffer = ByteBuffer::reference_buffer(*it, 0, (*it)->capacity());\n    inputs.push_back(tmp_byte_buffer);\n\n    std::vector<uint64_t> offsets;\n    offsets.assign(inputs.size(), 0);\n    InStream *in_stream = \n            new (std::nothrow) InStream(&inputs, \n                                        offsets, \n                                        out_stream->get_stream_length(), \n                                        lzo_decompress, \n                                        out_stream->get_total_buffer_size());\n    \n    in_stream->skip(10);\n    char data;\n    ASSERT_EQ(in_stream->read(&data), OLAP_SUCCESS);\n    ASSERT_EQ(data, 0x5e);\n\n    \n    SAFE_DELETE(out_stream);\n    SAFE_DELETE(in_stream);\n}\n\nclass TestRunLengthByte : public testing::Test {\npublic:\n    TestRunLengthByte() {\n    }\n    \n    virtual ~TestRunLengthByte() {\n    }\n    \n    virtual void SetUp() {\n        system(\"rm tmp_file\");\n        _out_stream = new (std::nothrow) OutStream(OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE, NULL);\n        ASSERT_TRUE(_out_stream != NULL);\n        _writer = new (std::nothrow) RunLengthByteWriter(_out_stream);\n        ASSERT_TRUE(_writer != NULL);\n    }   \n    \n    virtual void TearDown() {\n        SAFE_DELETE(_reader);\n        SAFE_DELETE(_out_stream);\n        SAFE_DELETE(_writer);\n        SAFE_DELETE(_shared_buffer);\n        SAFE_DELETE(_stream);\n    }\n\n    void CreateReader() {\n        ASSERT_EQ(OLAP_SUCCESS, helper.open_with_mode(\"tmp_file\", \n                O_CREAT | O_EXCL | O_WRONLY, S_IRUSR | S_IWUSR));\n        _out_stream->write_to_file(&helper, 0);\n        helper.close();\n\n        ASSERT_EQ(OLAP_SUCCESS, helper.open_with_mode(\"tmp_file\", \n                O_RDONLY, S_IRUSR | S_IWUSR)); \n\n        _shared_buffer = ByteBuffer::create(\n                OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE + sizeof(StreamHead));\n        ASSERT_TRUE(_shared_buffer != NULL);\n\n        _stream = new (std::nothrow) ReadOnlyFileStream(\n                &helper, \n                &_shared_buffer,\n                0, \n                helper.length(), \n                NULL, \n                OLAP_DEFAULT_COLUMN_STREAM_BUFFER_SIZE,\n                &_stats);\n        ASSERT_EQ(OLAP_SUCCESS, _stream->init());\n\n        _reader = new (std::nothrow) RunLengthByteReader(_stream);\n        ASSERT_TRUE(_reader != NULL);\n    }\n\n    RunLengthByteReader* _reader;\n    OutStream* _out_stream;\n    RunLengthByteWriter* _writer;\n    FileHandler helper;\n    ByteBuffer* _shared_buffer;\n    ReadOnlyFileStream* _stream;\n    OlapReaderStatistics _stats;\n};\n\n\nTEST_F(TestRunLengthByte, ReadWriteOneByte) {\n    _writer->write(0x5a);\n    _writer->flush();\n    CreateReader();\n\n    ASSERT_TRUE(_reader->has_next());\n    char value = 0xff;\n    ASSERT_EQ(OLAP_SUCCESS, _reader->next(&value));\n    ASSERT_EQ(value, 0X5A);\n\n    ASSERT_FALSE(_reader->has_next());\n}\n\n\nTEST_F(TestRunLengthByte, ReadWriteMultiBytes) {\n    \/\/ write data\n    char write_data[] = {0x5a, 0x5b, 0x5c, 0x5d};\n    for (int32_t i = 0; i < sizeof(write_data); i++) {\n        _writer->write(write_data[i]);\n    }\n    \n    _writer->flush();\n\n    \/\/ the stream contain head, contral byte and four byte literal\n    ASSERT_EQ(_out_stream->get_stream_length(), sizeof(StreamHead) + 1 + 4);\n\n    \/\/ read data\n    CreateReader();\n\n    for (int32_t i = 0; i < sizeof(write_data); i++) {\n        ASSERT_TRUE(_reader->has_next());\n        char value = 0xff;\n        ASSERT_EQ(OLAP_SUCCESS, _reader->next(&value));\n        ASSERT_EQ(value, write_data[i]);\n    }\n\n    ASSERT_FALSE(_reader->has_next());\n}\n\n\nTEST_F(TestRunLengthByte, ReadWriteSameBytes) {\n    \/\/ write data\n    char write_data[] = {0x5a, 0x5a, 0x5a, 0x5a};\n    for (int32_t i = 0; i < sizeof(write_data); i++) {\n        _writer->write(write_data[i]);\n    }\n    \n    _writer->flush();\n\n    \/\/ the stream contain head, contral byte(4-3) and one byte literal\n    ASSERT_EQ(_out_stream->get_stream_length(), sizeof(StreamHead) + 1 + 1);\n\n    \/\/ read data\n    CreateReader();\n\n    for (int32_t i = 0; i < sizeof(write_data); i++) {\n        ASSERT_TRUE(_reader->has_next());\n        char value = 0xff;\n        ASSERT_EQ(OLAP_SUCCESS, _reader->next(&value));\n        ASSERT_EQ(value, write_data[i]);\n    }\n    \n    ASSERT_FALSE(_reader->has_next());\n}\n\n\nTEST_F(TestRunLengthByte, Seek) {\n    \/\/ write data\n    char write_data[] = {0x5a, 0x5b, 0x5c, 0x5d};\n    for (int32_t i = 0; i < sizeof(write_data); i++) {\n        _writer->write(write_data[i]);\n    }\n\n    PositionEntryWriter index_entry;\n    _writer->get_position(&index_entry);\n    _writer->write(0x5e);\n\n    _writer->write(0x5f);\n    _writer->write(0x60);\n    _writer->write(0x61);\n    \n    _writer->flush();\n\n    \/\/ read data\n    CreateReader();\n\n    char buffer[256];\n    index_entry.write_to_buffer(buffer);\n    StreamIndexHeader header;\n    header.position_format = index_entry.positions_count();\n    header.statistic_format = OLAP_FIELD_TYPE_TINYINT;\n    PositionEntryReader entry;\n    entry.init(&header, OLAP_FIELD_TYPE_TINYINT, false);\n    entry.attach(buffer);\n\n    PositionProvider position(&entry);\n    _reader->seek(&position);\n    char value = 0xff;\n    ASSERT_EQ(OLAP_SUCCESS, _reader->next(&value));\n    ASSERT_EQ(value, 0x5e);\n    ASSERT_EQ(OLAP_SUCCESS, _reader->next(&value));\n    ASSERT_EQ(value, 0x5f);\n    ASSERT_EQ(OLAP_SUCCESS, _reader->next(&value));\n    ASSERT_EQ(value, 0x60);\n    ASSERT_EQ(OLAP_SUCCESS, _reader->next(&value));\n    ASSERT_EQ(value, 0x61);\n}\n\nTEST_F(TestRunLengthByte, Skip) {\n    \/\/ write data\n    char write_data[] = {0x5a, 0x5b, 0x5c, 0x5d};\n    for (int32_t i = 0; i < sizeof(write_data); i++) {\n        _writer->write(write_data[i]);\n    }\n    _writer->write(0x5e);\n    _writer->flush();\n\n    \/\/ read data\n    CreateReader();\n\n    _reader->skip(sizeof(write_data) - 1);\n    char value = 0xff;\n    ASSERT_EQ(OLAP_SUCCESS, _reader->next(&value));\n    ASSERT_EQ(value, write_data[sizeof(write_data) - 1]);\n    ASSERT_EQ(OLAP_SUCCESS, _reader->next(&value));\n    ASSERT_EQ(value, 0x5e);\n}\n\n}\n}\n\nint main(int argc, char** argv) {\n    std::string conffile = std::string(getenv(\"PALO_HOME\")) + \"\/conf\/be.conf\";\n    if (!palo::config::init(conffile.c_str(), false)) {\n        fprintf(stderr, \"error read config file. \\n\");\n        return -1;\n    }\n    palo::init_glog(\"be-test\");\n    int ret = palo::OLAP_SUCCESS;\n    testing::InitGoogleTest(&argc, argv);\n    ret = RUN_ALL_TESTS();\n    google::protobuf::ShutdownProtobufLibrary();\n    return ret;\n}\n\n","avg_line_length":33.8458864426,"max_line_length":101,"alphanum_fraction":0.621246876,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8693,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":6304.0,"content":"\/*\n * Copyright 2019 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"modules\/sksg\/include\/SkSGRenderEffect.h\"\n\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkMaskFilter.h\"\n#include \"include\/core\/SkShader.h\"\n#include \"src\/core\/SkMaskFilterBase.h\"\n\nnamespace sksg {\n\nsk_sp<MaskShaderEffect> MaskShaderEffect::Make(sk_sp<RenderNode> child, sk_sp<SkShader> sh) {\n    return child ? sk_sp<MaskShaderEffect>(new MaskShaderEffect(std::move(child), std::move(sh)))\n                 : nullptr;\n}\n\nMaskShaderEffect::MaskShaderEffect(sk_sp<RenderNode> child, sk_sp<SkShader> sh)\n    : INHERITED(std::move(child))\n    , fShader(std::move(sh)) {\n}\n\nvoid MaskShaderEffect::onRender(SkCanvas* canvas, const RenderContext* ctx) const {\n    const auto local_ctx = ScopedRenderContext(canvas, ctx)\n            .modulateMaskShader(fShader, canvas->getTotalMatrix());\n\n    this->INHERITED::onRender(canvas, local_ctx);\n}\n\nsk_sp<ShaderEffect> ShaderEffect::Make(sk_sp<RenderNode> child, sk_sp<Shader> shader) {\n    return child ? sk_sp<ShaderEffect>(new ShaderEffect(std::move(child), std::move(shader)))\n                 : nullptr;\n}\n\nShaderEffect::ShaderEffect(sk_sp<RenderNode> child, sk_sp<Shader> shader)\n    : INHERITED(std::move(child))\n    , fShader(std::move(shader)) {\n    if (fShader) {\n        this->observeInval(fShader);\n    }\n}\n\nShaderEffect::~ShaderEffect() {\n    if (fShader) {\n        this->unobserveInval(fShader);\n    }\n}\n\nvoid ShaderEffect::setShader(sk_sp<Shader> sh) {\n    if (fShader) {\n        this->unobserveInval(fShader);\n    }\n\n    fShader = std::move(sh);\n\n    if (fShader) {\n        this->observeInval(fShader);\n    }\n}\nSkRect ShaderEffect::onRevalidate(InvalidationController* ic, const SkMatrix& ctm) {\n    if (fShader) {\n        fShader->revalidate(ic, ctm);\n    }\n\n    return this->INHERITED::onRevalidate(ic, ctm);\n}\n\nvoid ShaderEffect::onRender(SkCanvas* canvas, const RenderContext* ctx) const {\n    const auto local_ctx = ScopedRenderContext(canvas, ctx)\n            .modulateShader(fShader ? fShader->getShader() : nullptr, canvas->getTotalMatrix());\n\n    this->INHERITED::onRender(canvas, local_ctx);\n}\n\nShader::Shader() : INHERITED(kBubbleDamage_Trait) {}\n\nShader::~Shader() = default;\n\nSkRect Shader::onRevalidate(InvalidationController*, const SkMatrix&) {\n    SkASSERT(this->hasInval());\n\n    fShader = this->onRevalidateShader();\n    return SkRect::MakeEmpty();\n}\n\nsk_sp<RenderNode> ImageFilterEffect::Make(sk_sp<RenderNode> child, sk_sp<ImageFilter> filter) {\n    return filter ? sk_sp<RenderNode>(new ImageFilterEffect(std::move(child), std::move(filter)))\n                  : child;\n}\n\nImageFilterEffect::ImageFilterEffect(sk_sp<RenderNode> child, sk_sp<ImageFilter> filter)\n    \/\/ filters always override descendent damage\n    : INHERITED(std::move(child), kOverrideDamage_Trait)\n    , fImageFilter(std::move(filter)) {\n    this->observeInval(fImageFilter);\n}\n\nImageFilterEffect::~ImageFilterEffect() {\n    this->unobserveInval(fImageFilter);\n}\n\nSkRect ImageFilterEffect::onRevalidate(InvalidationController* ic, const SkMatrix& ctm) {\n    \/\/ FIXME: image filter effects should replace the descendents' damage!\n    fImageFilter->revalidate(ic, ctm);\n\n    const auto& filter = fImageFilter->getFilter();\n\n    \/\/ Would be nice for this this to stick, but canComputeFastBounds()\n    \/\/ appears to be conservative (false negatives).\n    \/\/ SkASSERT(!filter || filter->canComputeFastBounds());\n\n    const auto content_bounds = this->INHERITED::onRevalidate(ic, ctm);\n\n    return filter ? filter->computeFastBounds(content_bounds)\n                  : content_bounds;\n}\n\nconst RenderNode* ImageFilterEffect::onNodeAt(const SkPoint& p) const {\n    \/\/ TODO: map p through the filter DAG and dispatch to descendants?\n    \/\/ For now, image filters occlude hit-testing.\n    SkASSERT(this->bounds().contains(p.x(), p.y()));\n    return this;\n}\n\nvoid ImageFilterEffect::onRender(SkCanvas* canvas, const RenderContext* ctx) const {\n    \/\/ Note: we're using the source content bounds for saveLayer, not our local\/filtered bounds.\n    const auto filter_ctx =\n        ScopedRenderContext(canvas, ctx).setFilterIsolation(this->getChild()->bounds(),\n                                                            canvas->getTotalMatrix(),\n                                                            fImageFilter->getFilter());\n    this->INHERITED::onRender(canvas, filter_ctx);\n}\n\nImageFilter::ImageFilter(sk_sp<ImageFilter> input)\n    : ImageFilter(input ? std::make_unique<InputsT>(1, std::move(input)) : nullptr) {}\n\nImageFilter::ImageFilter(std::unique_ptr<InputsT> inputs)\n    : INHERITED(kBubbleDamage_Trait)\n    , fInputs(std::move(inputs)) {\n    if (fInputs) {\n        for (const auto& input : *fInputs) {\n            this->observeInval(input);\n        }\n    }\n}\n\nImageFilter::~ImageFilter() {\n    if (fInputs) {\n        for (const auto& input : *fInputs) {\n            this->unobserveInval(input);\n        }\n    }\n}\n\nsk_sp<SkImageFilter> ImageFilter::refInput(size_t i) const {\n    return (fInputs && i < fInputs->size()) ? (*fInputs)[i]->getFilter() : nullptr;\n}\n\nSkRect ImageFilter::onRevalidate(InvalidationController*, const SkMatrix&) {\n    SkASSERT(this->hasInval());\n\n    fFilter = this->onRevalidateFilter();\n    return SkRect::MakeEmpty();\n}\n\nExternalImageFilter:: ExternalImageFilter() = default;\nExternalImageFilter::~ExternalImageFilter() = default;\n\nsk_sp<DropShadowImageFilter> DropShadowImageFilter::Make(sk_sp<ImageFilter> input) {\n    return sk_sp<DropShadowImageFilter>(new DropShadowImageFilter(std::move(input)));\n}\n\nDropShadowImageFilter::DropShadowImageFilter(sk_sp<ImageFilter> input)\n    : INHERITED(std::move(input)) {}\n\nDropShadowImageFilter::~DropShadowImageFilter() = default;\n\nsk_sp<SkImageFilter> DropShadowImageFilter::onRevalidateFilter() {\n    if (fMode == Mode::kShadowOnly) {\n        return SkImageFilters::DropShadowOnly(fOffset.x(), fOffset.y(), fSigma.x(), fSigma.y(),\n                                              fColor, this->refInput(0));\n    } else {\n        return SkImageFilters::DropShadow(fOffset.x(), fOffset.y(), fSigma.x(), fSigma.y(),\n                                          fColor, this->refInput(0));\n    }\n}\n\nsk_sp<BlurImageFilter> BlurImageFilter::Make(sk_sp<ImageFilter> input) {\n    return sk_sp<BlurImageFilter>(new BlurImageFilter(std::move(input)));\n}\n\nBlurImageFilter::BlurImageFilter(sk_sp<ImageFilter> input)\n    : INHERITED(std::move(input)) {}\n\nBlurImageFilter::~BlurImageFilter() = default;\n\nsk_sp<SkImageFilter> BlurImageFilter::onRevalidateFilter() {\n    return SkImageFilters::Blur(fSigma.x(), fSigma.y(), fTileMode, this->refInput(0));\n}\n\nsk_sp<BlendModeEffect> BlendModeEffect::Make(sk_sp<RenderNode> child, SkBlendMode mode) {\n    return child ? sk_sp<BlendModeEffect>(new BlendModeEffect(std::move(child), mode))\n                 : nullptr;\n}\n\nBlendModeEffect::BlendModeEffect(sk_sp<RenderNode> child, SkBlendMode mode)\n    : INHERITED(std::move(child))\n    , fMode(mode) {}\n\nBlendModeEffect::~BlendModeEffect() = default;\n\nvoid BlendModeEffect::onRender(SkCanvas* canvas, const RenderContext* ctx) const {\n    const auto local_ctx = ScopedRenderContext(canvas, ctx).modulateBlendMode(fMode);\n\n    this->INHERITED::onRender(canvas, local_ctx);\n}\n\nconst RenderNode* BlendModeEffect::onNodeAt(const SkPoint& p) const {\n    \/\/ TODO: we likely need to do something more sophisticated than delegate to descendants here.\n    return this->INHERITED::onNodeAt(p);\n}\n\nsk_sp<LayerEffect> LayerEffect::Make(sk_sp<RenderNode> child, SkBlendMode mode) {\n    return child ? sk_sp<LayerEffect>(new LayerEffect(std::move(child), mode))\n                 : nullptr;\n}\n\nLayerEffect::LayerEffect(sk_sp<RenderNode> child, SkBlendMode mode)\n    : INHERITED(std::move(child))\n    , fMode(mode) {}\n\nLayerEffect::~LayerEffect() = default;\n\nvoid LayerEffect::onRender(SkCanvas* canvas, const RenderContext* ctx) const {\n    SkAutoCanvasRestore acr(canvas, false);\n\n    \/\/ Commit any potential pending paint effects to their own layer.\n    const auto local_ctx = ScopedRenderContext(canvas, ctx).setIsolation(this->bounds(),\n                                                                         canvas->getTotalMatrix(),\n                                                                         true);\n\n    SkPaint layer_paint;\n    if (ctx) {\n        \/\/ Apply all optional context overrides upfront.\n        ctx->modulatePaint(canvas->getTotalMatrix(), &layer_paint);\n    }\n    layer_paint.setBlendMode(fMode);\n\n    canvas->saveLayer(nullptr, &layer_paint);\n\n    this->INHERITED::onRender(canvas, nullptr);\n}\n\n} \/\/ namespace sksg\n","avg_line_length":33.5637065637,"max_line_length":98,"alphanum_fraction":0.6767514092,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6891,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <atomic>\n#include <condition_variable>\n#include <deque>\n#include <mutex>\n#include <thread>\n#include <unordered_map>\n#include <unordered_set>\n\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n\n#include <networking\/socket.hpp>\n#include <networking\/socket_server.hpp>\n\n#include <msg\/visitor.hpp>\n#include <msg\/error.hpp>\n#include <msg\/login.hpp>\n#include <msg\/json.hpp>\n\n#include <chrono>\n#include \"server.hpp\"\n\nusing namespace dmurra47;\n\n\nnamespace msg = se3313::msg;\nnamespace net = se3313::networking;\n\nnamespace pt  = boost::property_tree;\n\nserver::~server()\n{\n    std::cout << \"Stopping the server.\";\n}\n\nvoid server::start()\n{\n    std::cout << \"Starting server on port: \" << _serverPort << std::endl;\n    \n    server_socket = std::shared_ptr<net::socket_server>(new net::socket_server(_serverPort));\t\/\/ Create server socket\n    \n    waiter = std::shared_ptr<flex_waiter>(new flex_waiter(server_socket));\t\t\t\/\/ Take server socket and put in flexWaiter\n    new std::thread(&server::sendMessages, this);\t\t\t\t\t\t\/\/ Start message queue processing\n    listen();\n}\n\nvoid server::stop()\n{\n    killed = true;\t\/\/ Signal end of program\n    \n    \/\/ Lock socket vector before starting messing with it\n    std::lock_guard<std::mutex> lock(socketsLock);\n    \n    \/\/ Close all sockets\n    for (auto sock : sockets) {\n      sock.first->close();\n    }\n    sockets.empty();\n    server_socket->close();\n    \n    waiter->kill();\t\/\/ Stop the listen loop\n}\n\nvoid server::listen()\n{\n  \/\/ Loop on waiting on all the sockets until killed\n  while(!killed)\n  {\n    int timeout = 1; \/\/ One second\n    waiter->wait(this->shared_from_this(), std::chrono::milliseconds(std::chrono::seconds(timeout)));\n  }\n}\n\nvoid server::onSTDIN(const std::string& line)\n{\n  std::cout << \"onSTDIN called. Contents: \";\n  std::cout << line << std::endl;\n  \n  \/\/ Ignore unless we're stopping\n  if (line == \"exit\") {\n    std::cout << \"Exiting...\" << std::endl;\n    stop();\n  }\n}\n\nvoid server::onSocket(const se3313::networking::flex_waiter::socket_ptr_t socket)\n{\n  std::cout << \"Client socket did something.\" << std::endl;\n\n  \/\/ Get contents\n  std::vector<char> contents;\n  int bytes_read = socket->read(&contents);\n  \n  \/\/ If socket closed\n  if(bytes_read == 0)\n  {\n    \/\/ Lock socket vector before starting messing with it\n    std::lock_guard<std::mutex> lock(socketsLock);\n    \n    \/\/ Find socket in client socket array that closed; remove it and break\n    for (auto iter = sockets.begin(); iter != sockets.end(); iter++)\n    {\n      if (socket->fd() == iter->first->fd())\n      {\n\twaiter->removeSocket(socket);\n\tsockets.erase(iter);\n\tbreak;\n      }\n    }\n  }\n  else\n  {\n    \/\/ Construct message as string\n    const std::string msg(contents.begin(), contents.end());\n    \n    \/\/ Parse message\n    boost::property_tree::ptree parsedMsg = msg::json::from(msg);\n    \n    \/\/ Visit message\n    return_t response = visit(parsedMsg);\n    \n    \/\/ Print return message\n    boost::property_tree::write_json(std::cout, response->toJson(), true);\t\/\/ DEBUG\n    \n    \n    \/\/ Get type of request and type of message\n    std::string type = response->toJson().get<std::string>(response->PROPERTY_TYPE);\n    \n    \n    \/\/ If error, send message back to socket\n    if (type == msg::response::error::TYPE)\n    {\n      \/\/ Convert message to string\n      const std::string responseSerialized = msg::json::to(response->toJson());\n      \n      \/\/ Respond with bad username\n      socket->write(responseSerialized);\n    }\n    \/\/ If no error, send message to everyone\n    else\n    {\n      \/\/ This is a login, associate with this socket\n      if (type == msg::response::login::TYPE)\n      {\n\tstd::string username = response->toJson().get<std::string>(\"object.joiningUsername\");\n\t\n\t\/\/ Lock socket vector before starting messing with it\n\tstd::lock_guard<std::mutex> lock(socketsLock);\n\t\n\t\/\/ Find matching socket and associate the username\n\tfor(auto& cliSocket : sockets)\n\t{\n\t  if(socket->fd() == cliSocket.first->fd())\n\t  {\n\t    cliSocket.second = username;\n\t  }\n\t}\n      }\n      \n      \/\/ NOTE: Do not lock messageQueue and socketsLock simultaneously, or you may cause deadlock.\n      \/\/ Add to send queue\n      std::lock_guard<std::mutex> lock(messageQueueLock);\n      messageQueue.push_back(response);\n    }\n  }\n}\n\nvoid server::onSocketServer(const std::shared_ptr<se3313::networking::socket_server> serverSocket)\n{\n  \/\/ New client connection\n  auto newClient = serverSocket->accept();\n  \n  \/\/ Lock socket vector before starting messing with it\n  std::lock_guard<std::mutex> lock(socketsLock);\n  \n  \/\/ Save new client\n  sockets.push_back(std::pair<std::shared_ptr<net::socket>, std::string>(newClient, std::string()));\n  \n  \/\/ Save client to flex_waiter\n  waiter->addSocket(newClient);\n}\n\nvoid server::sendMessages()\n{\n  \/\/ Continually check the send messages queue until the program quits\n  while(!killed)\n  {\n    std::this_thread::sleep_for(std::chrono::milliseconds(100));\t\/\/ Slow this thread down a bit to stop the cout pollution\n    \n    std::lock_guard<std::mutex> lock(messageQueueLock);\n    \n    \/\/ If pending messages to send\n    if (messageQueue.size() > 0)\n    {\n      \/\/ Send all queued messages to all connected sockets\n      for(auto message : messageQueue)\n      {\n\t\/\/ Convert message to string\n\tconst std::string responseSerialized = se3313::msg::json::to(message->toJson());\n\t\n\t\/\/ Lock socket vector before starting messing with it\n\tstd::lock_guard<std::mutex> lock(socketsLock);\n\t\n\t\/\/ Write message to all sockets\n\tfor (auto socket: sockets)\n\t{\n\t  socket.first->write(responseSerialized);\n\t}\n      }\n      \n      \/\/ Clear queue\n      messageQueue.clear();\n    }\n  }\n}\n\n\n \/\/\/ Called when a login message is passed\nserver::return_t server::visitLogin(const msg::request::login& login\/* request *\/ )\n{\n  \/\/ Check to make sure username is not in use\n  bool not_in_use = true;\n\n  \/\/ Lock socket vector before starting messing with it\n  socketsLock.lock();\n  \n  for (auto socket : sockets)\n  {\n    if (login.sender() == socket.second)\n    {\n      not_in_use = false;\n      break;\n    }\n  }\n  \n  \/\/ Done messing with sockets vector\n  socketsLock.unlock();\n  \n  \/\/ If username not in use, add it to the list and notify everyone\n  if(not_in_use)\n  {\n    return std::shared_ptr<msg::response::login>(new msg::response::login(login.sender()));\n  }\n  else\n  {\n    \/\/ Return an error\n    return std::shared_ptr<msg::response::error>(\n      new msg::response::error(std::chrono::system_clock::now(),\n\t\t\t       \"@server\",\n\t\t\t       \"@server\",\n\t\t\t       msg::ErrorCode::USER_NAME_IN_USE,\n\t\t\t       \"Username in use.\"));\n  }\n}\n\n\/\/\/ Called when a message is passed\nserver::return_t server::visitMessage(const msg::request::message& msg\/* request *\/ )\n{\n  return std::shared_ptr<msg::response::message>(new msg::response::message(msg.sender(), msg.content()));\n}\n","avg_line_length":25.9060150376,"max_line_length":122,"alphanum_fraction":0.6557829052,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1958,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":19.0,"content":"#include <ban\/ban.hpp>\n#include <info\/info.hpp>\n#include <mod.hpp>\n#include <algorithm>\n\n\nusing namespace MCPP;\n\n\nstatic const String name(\"Bans Information\");\nstatic const String identifier(\"bans\");\nstatic const String help(\"Displays the banlist.\");\nstatic const Word priority=1;\nstatic const String bans_banner(\"BANLIST:\");\nstatic const String parenthetical []={\n\t\" (\",\n\t\")\"\n};\nstatic const String by(\"by {0}\");\nstatic const String reason(\"with reason \\\"{0}\\\"\");\nstatic const String separator(\" \");\n\n\nclass BanInfoProvider : public Module, public InformationProvider {\n\n\n\tpublic:\n\t\n\t\n\t\tvirtual const String & Name () const noexcept override {\n\t\t\n\t\t\treturn name;\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual Word Priority () const noexcept override {\n\t\t\n\t\t\treturn priority;\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual void Install () override {\n\t\t\n\t\t\tInformation::Get().Add(this);\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual const String & Identifier () const noexcept override {\n\t\t\n\t\t\treturn identifier;\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual const String & Help () const noexcept override {\n\t\t\n\t\t\treturn help;\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual void Execute (ChatMessage & message) const {\n\t\t\n\t\t\t\/\/\tGet information\n\t\t\tauto info=Bans::Get().GetInfo();\n\t\t\t\n\t\t\t\/\/\tSort\n\t\t\tstd::sort(\n\t\t\t\tinfo.begin(),\n\t\t\t\tinfo.end(),\n\t\t\t\t[] (const BanInfo & a, const BanInfo & b) {\treturn a.Username<b.Username;\t}\n\t\t\t);\n\t\t\t\n\t\t\t\/\/\tOutput\n\t\t\t\n\t\t\tmessage\t<<\tChatStyle::Bold\n\t\t\t\t\t<<\tbans_banner\n\t\t\t\t\t<<\tChatFormat::Pop;\n\t\t\t\t\t\n\t\t\tfor (auto & i : info) {\n\t\t\t\n\t\t\t\tmessage << Newline << i.Username;\n\t\t\t\t\n\t\t\t\tif (!(i.By.IsNull() && i.Reason.IsNull())) {\n\t\t\t\t\n\t\t\t\t\tmessage << parenthetical[0];\n\t\t\t\t\t\n\t\t\t\t\tif (!i.By.IsNull()) {\n\t\t\t\t\t\n\t\t\t\t\t\tmessage << String::Format(\n\t\t\t\t\t\t\tby,\n\t\t\t\t\t\t\t*i.By\n\t\t\t\t\t\t);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!i.Reason.IsNull()) message << separator;\n\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (!i.Reason.IsNull()) message << String::Format(\n\t\t\t\t\t\treason,\n\t\t\t\t\t\t*i.Reason\n\t\t\t\t\t);\n\t\t\t\t\t\n\t\t\t\t\tmessage << parenthetical[1];\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\t\t\n\t\t}\n\n\n};\n\n\nINSTALL_MODULE(BanInfoProvider)\n","avg_line_length":16.3166666667,"max_line_length":79,"alphanum_fraction":0.582226762,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":57245,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n *\n *    Copyright (c) 2021 Project CHIP Authors\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n *\/\n\n\/\/ THIS FILE IS GENERATED BY ZAP\n\n#include <cinttypes>\n#include <cstdint>\n\n#include \"af-structs.h\"\n#include \"app\/util\/util.h\"\n#include \"call-command-handler.h\"\n#include \"callback.h\"\n#include \"cluster-id.h\"\n#include \"command-id.h\"\n\n#include <app\/InteractionModelEngine.h>\n\n\/\/ Currently we need some work to keep compatible with ember lib.\n#include <util\/ember-compatibility-functions.h>\n\nnamespace chip {\nnamespace app {\n\n\/\/ Cluster specific command parsing\n\nnamespace clusters {\n\nnamespace ContentLaunch {\n\nvoid DispatchClientCommand(app::Command * command, CommandId commandId, EndpointId endpointId, TLV::TLVReader & dataTlv)\n{\n    {\n        switch (commandId)\n        {\n        case ZCL_LAUNCH_CONTENT_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t contentLaunchStatus;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(contentLaunchStatus);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfContentLaunchClusterLaunchContentResponseCallback(contentLaunchStatus);\n            break;\n        }\n        case ZCL_LAUNCH_URL_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t contentLaunchStatus;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(contentLaunchStatus);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfContentLaunchClusterLaunchURLResponseCallback(contentLaunchStatus);\n            break;\n        }\n        default: {\n            \/\/ Unrecognized command ID, error status will apply.\n            \/\/ TODO: Encode response for command not found\n            ChipLogError(Zcl, \"Unknown command %\" PRIx16 \" for cluster %\" PRIx16, commandId, ZCL_CONTENT_LAUNCH_CLUSTER_ID);\n            break;\n        }\n        }\n    }\n}\n\n} \/\/ namespace ContentLaunch\n\nnamespace DoorLock {\n\nvoid DispatchClientCommand(app::Command * command, CommandId commandId, EndpointId endpointId, TLV::TLVReader & dataTlv)\n{\n    {\n        switch (commandId)\n        {\n        case ZCL_CLEAR_ALL_PINS_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterClearAllPinsResponseCallback(status);\n            break;\n        }\n        case ZCL_CLEAR_ALL_RFIDS_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterClearAllRfidsResponseCallback(status);\n            break;\n        }\n        case ZCL_CLEAR_HOLIDAY_SCHEDULE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterClearHolidayScheduleResponseCallback(status);\n            break;\n        }\n        case ZCL_CLEAR_PIN_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterClearPinResponseCallback(status);\n            break;\n        }\n        case ZCL_CLEAR_RFID_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterClearRfidResponseCallback(status);\n            break;\n        }\n        case ZCL_CLEAR_WEEKDAY_SCHEDULE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterClearWeekdayScheduleResponseCallback(status);\n            break;\n        }\n        case ZCL_CLEAR_YEARDAY_SCHEDULE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterClearYeardayScheduleResponseCallback(status);\n            break;\n        }\n        case ZCL_GET_HOLIDAY_SCHEDULE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t scheduleId;\n            uint8_t status;\n            uint32_t localStartTime;\n            uint32_t localEndTime;\n            uint8_t operatingModeDuringHoliday;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(scheduleId);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                case 2:\n                    TLVError = dataTlv.Get(localStartTime);\n                    break;\n                case 3:\n                    TLVError = dataTlv.Get(localEndTime);\n                    break;\n                case 4:\n                    TLVError = dataTlv.Get(operatingModeDuringHoliday);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterGetHolidayScheduleResponseCallback(scheduleId, status, localStartTime, localEndTime,\n                                                                     operatingModeDuringHoliday);\n            break;\n        }\n        case ZCL_GET_LOG_RECORD_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint16_t logEntryId;\n            uint32_t timestamp;\n            uint8_t eventType;\n            uint8_t source;\n            uint8_t eventIdOrAlarmCode;\n            uint16_t userId;\n            const uint8_t * pin;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(logEntryId);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(timestamp);\n                    break;\n                case 2:\n                    TLVError = dataTlv.Get(eventType);\n                    break;\n                case 3:\n                    TLVError = dataTlv.Get(source);\n                    break;\n                case 4:\n                    TLVError = dataTlv.Get(eventIdOrAlarmCode);\n                    break;\n                case 5:\n                    TLVError = dataTlv.Get(userId);\n                    break;\n                case 6:\n                    TLVError = dataTlv.GetDataPtr(pin);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterGetLogRecordResponseCallback(logEntryId, timestamp, eventType, source, eventIdOrAlarmCode, userId,\n                                                               const_cast<uint8_t *>(pin));\n            break;\n        }\n        case ZCL_GET_PIN_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint16_t userId;\n            uint8_t userStatus;\n            uint8_t userType;\n            const uint8_t * pin;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(userId);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(userStatus);\n                    break;\n                case 2:\n                    TLVError = dataTlv.Get(userType);\n                    break;\n                case 3:\n                    TLVError = dataTlv.GetDataPtr(pin);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterGetPinResponseCallback(userId, userStatus, userType, const_cast<uint8_t *>(pin));\n            break;\n        }\n        case ZCL_GET_RFID_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint16_t userId;\n            uint8_t userStatus;\n            uint8_t userType;\n            const uint8_t * rfid;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(userId);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(userStatus);\n                    break;\n                case 2:\n                    TLVError = dataTlv.Get(userType);\n                    break;\n                case 3:\n                    TLVError = dataTlv.GetDataPtr(rfid);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterGetRfidResponseCallback(userId, userStatus, userType, const_cast<uint8_t *>(rfid));\n            break;\n        }\n        case ZCL_GET_USER_TYPE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint16_t userId;\n            uint8_t userType;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(userId);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(userType);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterGetUserTypeResponseCallback(userId, userType);\n            break;\n        }\n        case ZCL_GET_WEEKDAY_SCHEDULE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t scheduleId;\n            uint16_t userId;\n            uint8_t status;\n            uint8_t daysMask;\n            uint8_t startHour;\n            uint8_t startMinute;\n            uint8_t endHour;\n            uint8_t endMinute;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(scheduleId);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(userId);\n                    break;\n                case 2:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                case 3:\n                    TLVError = dataTlv.Get(daysMask);\n                    break;\n                case 4:\n                    TLVError = dataTlv.Get(startHour);\n                    break;\n                case 5:\n                    TLVError = dataTlv.Get(startMinute);\n                    break;\n                case 6:\n                    TLVError = dataTlv.Get(endHour);\n                    break;\n                case 7:\n                    TLVError = dataTlv.Get(endMinute);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterGetWeekdayScheduleResponseCallback(scheduleId, userId, status, daysMask, startHour, startMinute,\n                                                                     endHour, endMinute);\n            break;\n        }\n        case ZCL_GET_YEARDAY_SCHEDULE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t scheduleId;\n            uint16_t userId;\n            uint8_t status;\n            uint32_t localStartTime;\n            uint32_t localEndTime;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(scheduleId);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(userId);\n                    break;\n                case 2:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                case 3:\n                    TLVError = dataTlv.Get(localStartTime);\n                    break;\n                case 4:\n                    TLVError = dataTlv.Get(localEndTime);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterGetYeardayScheduleResponseCallback(scheduleId, userId, status, localStartTime, localEndTime);\n            break;\n        }\n        case ZCL_LOCK_DOOR_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterLockDoorResponseCallback(status);\n            break;\n        }\n        case ZCL_SET_HOLIDAY_SCHEDULE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterSetHolidayScheduleResponseCallback(status);\n            break;\n        }\n        case ZCL_SET_PIN_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterSetPinResponseCallback(status);\n            break;\n        }\n        case ZCL_SET_RFID_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterSetRfidResponseCallback(status);\n            break;\n        }\n        case ZCL_SET_USER_TYPE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterSetUserTypeResponseCallback(status);\n            break;\n        }\n        case ZCL_SET_WEEKDAY_SCHEDULE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterSetWeekdayScheduleResponseCallback(status);\n            break;\n        }\n        case ZCL_SET_YEARDAY_SCHEDULE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterSetYeardayScheduleResponseCallback(status);\n            break;\n        }\n        case ZCL_UNLOCK_DOOR_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterUnlockDoorResponseCallback(status);\n            break;\n        }\n        case ZCL_UNLOCK_WITH_TIMEOUT_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfDoorLockClusterUnlockWithTimeoutResponseCallback(status);\n            break;\n        }\n        default: {\n            \/\/ Unrecognized command ID, error status will apply.\n            \/\/ TODO: Encode response for command not found\n            ChipLogError(Zcl, \"Unknown command %\" PRIx16 \" for cluster %\" PRIx16, commandId, ZCL_DOOR_LOCK_CLUSTER_ID);\n            break;\n        }\n        }\n    }\n}\n\n} \/\/ namespace DoorLock\n\nnamespace GeneralCommissioning {\n\nvoid DispatchClientCommand(app::Command * command, CommandId commandId, EndpointId endpointId, TLV::TLVReader & dataTlv)\n{\n    {\n        switch (commandId)\n        {\n        case ZCL_ARM_FAIL_SAFE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t errorCode;\n            const uint8_t * debugText;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(errorCode);\n                    break;\n                case 1:\n                    TLVError = dataTlv.GetDataPtr(debugText);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfGeneralCommissioningClusterArmFailSafeResponseCallback(errorCode, const_cast<uint8_t *>(debugText));\n            break;\n        }\n        case ZCL_COMMISSIONING_COMPLETE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t errorCode;\n            const uint8_t * debugText;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(errorCode);\n                    break;\n                case 1:\n                    TLVError = dataTlv.GetDataPtr(debugText);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfGeneralCommissioningClusterCommissioningCompleteResponseCallback(errorCode, const_cast<uint8_t *>(debugText));\n            break;\n        }\n        case ZCL_SET_FABRIC_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t errorCode;\n            const uint8_t * debugText;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(errorCode);\n                    break;\n                case 1:\n                    TLVError = dataTlv.GetDataPtr(debugText);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfGeneralCommissioningClusterSetFabricResponseCallback(errorCode, const_cast<uint8_t *>(debugText));\n            break;\n        }\n        default: {\n            \/\/ Unrecognized command ID, error status will apply.\n            \/\/ TODO: Encode response for command not found\n            ChipLogError(Zcl, \"Unknown command %\" PRIx16 \" for cluster %\" PRIx16, commandId, ZCL_GENERAL_COMMISSIONING_CLUSTER_ID);\n            break;\n        }\n        }\n    }\n}\n\n} \/\/ namespace GeneralCommissioning\n\nnamespace Groups {\n\nvoid DispatchClientCommand(app::Command * command, CommandId commandId, EndpointId endpointId, TLV::TLVReader & dataTlv)\n{\n    {\n        switch (commandId)\n        {\n        case ZCL_ADD_GROUP_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n            uint16_t groupId;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(groupId);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfGroupsClusterAddGroupResponseCallback(status, groupId);\n            break;\n        }\n        case ZCL_GET_GROUP_MEMBERSHIP_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t capacity;\n            uint8_t groupCount;\n            \/* TYPE WARNING: array array defaults to *\/ uint8_t * groupList;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(capacity);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(groupCount);\n                    break;\n                case 2:\n                    \/\/ Just for compatibility, we will add array type support in IM later.\n                    TLVError = dataTlv.GetDataPtr(const_cast<const uint8_t *&>(groupList));\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfGroupsClusterGetGroupMembershipResponseCallback(capacity, groupCount, groupList);\n            break;\n        }\n        case ZCL_REMOVE_GROUP_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n            uint16_t groupId;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(groupId);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfGroupsClusterRemoveGroupResponseCallback(status, groupId);\n            break;\n        }\n        case ZCL_VIEW_GROUP_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n            uint16_t groupId;\n            const uint8_t * groupName;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(groupId);\n                    break;\n                case 2:\n                    TLVError = dataTlv.GetDataPtr(groupName);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfGroupsClusterViewGroupResponseCallback(status, groupId, const_cast<uint8_t *>(groupName));\n            break;\n        }\n        default: {\n            \/\/ Unrecognized command ID, error status will apply.\n            \/\/ TODO: Encode response for command not found\n            ChipLogError(Zcl, \"Unknown command %\" PRIx16 \" for cluster %\" PRIx16, commandId, ZCL_GROUPS_CLUSTER_ID);\n            break;\n        }\n        }\n    }\n}\n\n} \/\/ namespace Groups\n\nnamespace Identify {\n\nvoid DispatchClientCommand(app::Command * command, CommandId commandId, EndpointId endpointId, TLV::TLVReader & dataTlv)\n{\n    {\n        switch (commandId)\n        {\n        case ZCL_IDENTIFY_QUERY_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint16_t timeout;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(timeout);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfIdentifyClusterIdentifyQueryResponseCallback(timeout);\n            break;\n        }\n        default: {\n            \/\/ Unrecognized command ID, error status will apply.\n            \/\/ TODO: Encode response for command not found\n            ChipLogError(Zcl, \"Unknown command %\" PRIx16 \" for cluster %\" PRIx16, commandId, ZCL_IDENTIFY_CLUSTER_ID);\n            break;\n        }\n        }\n    }\n}\n\n} \/\/ namespace Identify\n\nnamespace MediaPlayback {\n\nvoid DispatchClientCommand(app::Command * command, CommandId commandId, EndpointId endpointId, TLV::TLVReader & dataTlv)\n{\n    {\n        switch (commandId)\n        {\n        case ZCL_PLAYBACK_COMMAND_ID: {\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfMediaPlaybackClusterPlaybackCallback();\n            break;\n        }\n        default: {\n            \/\/ Unrecognized command ID, error status will apply.\n            \/\/ TODO: Encode response for command not found\n            ChipLogError(Zcl, \"Unknown command %\" PRIx16 \" for cluster %\" PRIx16, commandId, ZCL_MEDIA_PLAYBACK_CLUSTER_ID);\n            break;\n        }\n        }\n    }\n}\n\n} \/\/ namespace MediaPlayback\n\nnamespace Scenes {\n\nvoid DispatchClientCommand(app::Command * command, CommandId commandId, EndpointId endpointId, TLV::TLVReader & dataTlv)\n{\n    {\n        switch (commandId)\n        {\n        case ZCL_ADD_SCENE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n            uint16_t groupId;\n            uint8_t sceneId;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(groupId);\n                    break;\n                case 2:\n                    TLVError = dataTlv.Get(sceneId);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfScenesClusterAddSceneResponseCallback(status, groupId, sceneId);\n            break;\n        }\n        case ZCL_GET_SCENE_MEMBERSHIP_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n            uint8_t capacity;\n            uint16_t groupId;\n            uint8_t sceneCount;\n            \/* TYPE WARNING: array array defaults to *\/ uint8_t * sceneList;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(capacity);\n                    break;\n                case 2:\n                    TLVError = dataTlv.Get(groupId);\n                    break;\n                case 3:\n                    TLVError = dataTlv.Get(sceneCount);\n                    break;\n                case 4:\n                    \/\/ Just for compatibility, we will add array type support in IM later.\n                    TLVError = dataTlv.GetDataPtr(const_cast<const uint8_t *&>(sceneList));\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfScenesClusterGetSceneMembershipResponseCallback(status, capacity, groupId, sceneCount, sceneList);\n            break;\n        }\n        case ZCL_REMOVE_ALL_SCENES_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n            uint16_t groupId;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(groupId);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfScenesClusterRemoveAllScenesResponseCallback(status, groupId);\n            break;\n        }\n        case ZCL_REMOVE_SCENE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n            uint16_t groupId;\n            uint8_t sceneId;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(groupId);\n                    break;\n                case 2:\n                    TLVError = dataTlv.Get(sceneId);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfScenesClusterRemoveSceneResponseCallback(status, groupId, sceneId);\n            break;\n        }\n        case ZCL_STORE_SCENE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n            uint16_t groupId;\n            uint8_t sceneId;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(groupId);\n                    break;\n                case 2:\n                    TLVError = dataTlv.Get(sceneId);\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfScenesClusterStoreSceneResponseCallback(status, groupId, sceneId);\n            break;\n        }\n        case ZCL_VIEW_SCENE_RESPONSE_COMMAND_ID: {\n            CHIP_ERROR TLVError = CHIP_NO_ERROR;\n            uint8_t status;\n            uint16_t groupId;\n            uint8_t sceneId;\n            uint16_t transitionTime;\n            const uint8_t * sceneName;\n            \/* TYPE WARNING: array array defaults to *\/ uint8_t * extensionFieldSets;\n\n            while ((TLVError = dataTlv.Next()) == CHIP_NO_ERROR)\n            {\n                switch (TLV::TagNumFromTag(dataTlv.GetTag()))\n                {\n                case 0:\n                    TLVError = dataTlv.Get(status);\n                    break;\n                case 1:\n                    TLVError = dataTlv.Get(groupId);\n                    break;\n                case 2:\n                    TLVError = dataTlv.Get(sceneId);\n                    break;\n                case 3:\n                    TLVError = dataTlv.Get(transitionTime);\n                    break;\n                case 4:\n                    TLVError = dataTlv.GetDataPtr(sceneName);\n                    break;\n                case 5:\n                    \/\/ Just for compatibility, we will add array type support in IM later.\n                    TLVError = dataTlv.GetDataPtr(const_cast<const uint8_t *&>(extensionFieldSets));\n                    break;\n                default:\n                    \/\/ Unsupported tag, ignore it.\n                    ChipLogProgress(Zcl, \"Unknown TLV tag during processing.\");\n                    break;\n                }\n                if (TLVError != CHIP_NO_ERROR)\n                {\n                    ChipLogProgress(Zcl, \"Failed to decode TLV data with tag %\" PRIx32 \": %\" PRId32,\n                                    TLV::TagNumFromTag(dataTlv.GetTag()), TLVError);\n                }\n            }\n            \/\/ TODO(#5098) We should pass the Command Object and EndpointId to the cluster callbacks.\n            emberAfScenesClusterViewSceneResponseCallback(status, groupId, sceneId, transitionTime,\n                                                          const_cast<uint8_t *>(sceneName), extensionFieldSets);\n            break;\n        }\n        default: {\n            \/\/ Unrecognized command ID, error status will apply.\n            \/\/ TODO: Encode response for command not found\n            ChipLogError(Zcl, \"Unknown command %\" PRIx16 \" for cluster %\" PRIx16, commandId, ZCL_SCENES_CLUSTER_ID);\n            break;\n        }\n        }\n    }\n}\n\n} \/\/ namespace Scenes\n\n} \/\/ namespace clusters\n\nvoid DispatchSingleClusterCommand(chip::ClusterId aClusterId, chip::CommandId aCommandId, chip::EndpointId aEndPointId,\n                                  chip::TLV::TLVReader & aReader, Command * apCommandObj)\n{\n    ChipLogDetail(Zcl, \"Received Cluster Command: Cluster=%\" PRIx16 \" Command=%\" PRIx8 \" Endpoint=%\" PRIx8, aClusterId, aCommandId,\n                  aEndPointId);\n    Compatibility::SetupEmberAfObjects(apCommandObj, aClusterId, aCommandId, aEndPointId);\n    switch (aClusterId)\n    {\n    default:\n        \/\/ Unrecognized cluster ID, error status will apply.\n        \/\/ TODO: Encode response for Cluster not found\n        ChipLogError(Zcl, \"Unknown cluster %\" PRIx16, aClusterId);\n        break;\n    }\n    Compatibility::ResetEmberAfObjects();\n}\n\n} \/\/ namespace app\n} \/\/ namespace chip\n","avg_line_length":39.919804742,"max_line_length":132,"alphanum_fraction":0.4933880688,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":844,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":99.0,"content":"#include \"CPUCounters.hpp\"\n\/\/ -------------------------------------------------------------------------------------\n\/\/ -------------------------------------------------------------------------------------\n\/\/ -------------------------------------------------------------------------------------\nnamespace leanstore\n{\nstd::mutex CPUCounters::mutex;\nu64 CPUCounters::id = 0;\nstd::unordered_map<u64, CPUCounters> CPUCounters::threads;\n\/\/ -------------------------------------------------------------------------------------\nu64 CPUCounters::registerThread(string name, bool perf_inherit)\n{\n   std::unique_lock guard(mutex);\n   threads[id] = {.e = std::make_unique<PerfEvent>(perf_inherit), .name = name};\n   return id++;\n}\nvoid CPUCounters::removeThread(u64 id)\n{\n   std::unique_lock guard(mutex);\n   threads.erase(id);\n}\n}  \/\/ namespace leanstore\n","avg_line_length":36.6956521739,"max_line_length":88,"alphanum_fraction":0.4206161137,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":451,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["IJG"],"max_stars_count":null,"content":"#include <BulletSoftBody\/btDefaultSoftBodySolver.h>\n#include <BulletSoftBody\/btSoftBody.h>\n\n#include \"btDefaultSoftBodySolver_wrap.h\"\n\nbtDefaultSoftBodySolver* btDefaultSoftBodySolver_new()\n{\n\treturn new btDefaultSoftBodySolver();\n}\n\nvoid btDefaultSoftBodySolver_copySoftBodyToVertexBuffer(btDefaultSoftBodySolver* obj,\n\tconst btSoftBody* softBody, btVertexBufferDescriptor* vertexBuffer)\n{\n\tobj->copySoftBodyToVertexBuffer(softBody, vertexBuffer);\n}\n","avg_line_length":28.1875,"max_line_length":85,"alphanum_fraction":0.8492239468,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11246,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <uWS\/uWS.h>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include \"Eigen-3.3\/Eigen\/Core\"\r\n#include \"Eigen-3.3\/Eigen\/QR\"\r\n#include \"helpers.h\"\r\n#include \"json.hpp\"\r\n#include \"spline.h\"\r\n\r\n\/\/ for convenience\r\nusing nlohmann::json;\r\nusing std::string;\r\nusing std::vector;\r\n\r\nint main()\r\n{\r\n  uWS::Hub h;\r\n\r\n  \/\/ Load up map values for waypoint's x,y,s and d normalized normal vectors\r\n  vector<double> map_waypoints_x;\r\n  vector<double> map_waypoints_y;\r\n  vector<double> map_waypoints_s;\r\n  vector<double> map_waypoints_dx;\r\n  vector<double> map_waypoints_dy;\r\n\r\n  \/\/ Waypoint map to read from\r\n  string map_file_ = \"..\/data\/highway_map.csv\";\r\n  \/\/ The max s value before wrapping around the track back to 0\r\n  double max_s = 6945.554;\r\n\r\n  std::ifstream in_map_(map_file_.c_str(), std::ifstream::in);\r\n\r\n  string line;\r\n  while (getline(in_map_, line))\r\n  {\r\n    std::istringstream iss(line);\r\n    double x;\r\n    double y;\r\n    float s;\r\n    float d_x;\r\n    float d_y;\r\n    iss >> x;\r\n    iss >> y;\r\n    iss >> s;\r\n    iss >> d_x;\r\n    iss >> d_y;\r\n    map_waypoints_x.push_back(x);\r\n    map_waypoints_y.push_back(y);\r\n    map_waypoints_s.push_back(s);\r\n    map_waypoints_dx.push_back(d_x);\r\n    map_waypoints_dy.push_back(d_y);\r\n  }\r\n\r\n  \/\/ Car's lane. Starting at middle lane.\r\n  int lane = 1;\r\n\r\n  \/\/ Reference velocity.\r\n  double ref_vel = 0.0; \/\/ mph\r\n\r\n  h.onMessage([&ref_vel, &lane, &map_waypoints_x, &map_waypoints_y, &map_waypoints_s, &map_waypoints_dx, &map_waypoints_dy](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {\r\n    \/\/ \"42\" at the start of the message means there's a websocket message event.\r\n    \/\/ The 4 signifies a websocket message\r\n    \/\/ The 2 signifies a websocket event\r\n    \/\/auto sdata = string(data).substr(0, length);\r\n    \/\/cout << sdata << endl;\r\n    if (length && length > 2 && data[0] == '4' && data[1] == '2')\r\n    {\r\n\r\n      auto s = hasData(data);\r\n\r\n      if (s != \"\")\r\n      {\r\n        auto j = json::parse(s);\r\n\r\n        string event = j[0].get<string>();\r\n\r\n        if (event == \"telemetry\")\r\n        {\r\n          \/\/ j[1] is the data JSON object\r\n\r\n          \/\/ Main car's localization Data\r\n          double car_x = j[1][\"x\"];\r\n          double car_y = j[1][\"y\"];\r\n          double car_s = j[1][\"s\"];\r\n          double car_d = j[1][\"d\"];\r\n          double car_yaw = j[1][\"yaw\"];\r\n          double car_speed = j[1][\"speed\"];\r\n\r\n          \/\/ Previous path data given to the Planner\r\n          auto previous_path_x = j[1][\"previous_path_x\"];\r\n          auto previous_path_y = j[1][\"previous_path_y\"];\r\n          \/\/ Previous path's end s and d values\r\n          double end_path_s = j[1][\"end_path_s\"];\r\n          double end_path_d = j[1][\"end_path_d\"];\r\n\r\n          \/\/ Sensor Fusion Data, a list of all other cars on the same side of the road.\r\n          auto sensor_fusion = j[1][\"sensor_fusion\"];\r\n\r\n          \/\/ Provided previous path point size.\r\n          int prev_size = previous_path_x.size();\r\n\r\n          \/\/ Preventing collitions.\r\n          if (prev_size > 0)\r\n          {\r\n            car_s = end_path_s;\r\n          }\r\n\r\n          \/\/ Prediction : Analysing other cars positions.\r\n          bool car_ahead = false;\r\n          bool car_left = false;\r\n          bool car_righ = false;\r\n          for (int i = 0; i < sensor_fusion.size(); i++)\r\n          {\r\n            float d = sensor_fusion[i][6];\r\n            int car_lane = -1;\r\n            \/\/ is it on the same lane we are\r\n            if (d > 0 && d < 4)\r\n            {\r\n              car_lane = 0;\r\n            }\r\n            else if (d > 4 && d < 8)\r\n            {\r\n              car_lane = 1;\r\n            }\r\n            else if (d > 8 && d < 12)\r\n            {\r\n              car_lane = 2;\r\n            }\r\n            if (car_lane < 0)\r\n            {\r\n              continue;\r\n            }\r\n            \/\/ Find car speed.\r\n            double vx = sensor_fusion[i][3];\r\n            double vy = sensor_fusion[i][4];\r\n            double check_speed = sqrt(vx * vx + vy * vy);\r\n            double check_car_s = sensor_fusion[i][5];\r\n            \/\/ Estimate car s position after executing previous trajectory.\r\n            check_car_s += ((double)prev_size * 0.02 * check_speed);\r\n\r\n            if (car_lane == lane)\r\n            {\r\n              \/\/ Car in our lane.\r\n              car_ahead |= check_car_s > car_s && check_car_s - car_s < 30;\r\n            }\r\n            else if (car_lane - lane == -1)\r\n            {\r\n              \/\/ Car left\r\n              car_left |= car_s - 30 < check_car_s && car_s + 30 > check_car_s;\r\n            }\r\n            else if (car_lane - lane == 1)\r\n            {\r\n              \/\/ Car right\r\n              car_righ |= car_s - 30 < check_car_s && car_s + 30 > check_car_s;\r\n            }\r\n          }\r\n\r\n          \/\/ Behavior : Let's see what to do.\r\n          double speed_diff = 0;\r\n          const double MAX_SPEED = 49.5;\r\n          const double MAX_ACC = .224;\r\n          if (car_ahead)\r\n          { \/\/ Car ahead\r\n            if (!car_left && lane > 0)\r\n            {\r\n              \/\/ if there is no car left and there is a left lane.\r\n              lane--; \/\/ Change lane left.\r\n            }\r\n            else if (!car_righ && lane != 2)\r\n            {\r\n              \/\/ if there is no car right and there is a right lane.\r\n              lane++; \/\/ Change lane right.\r\n            }\r\n            else\r\n            {\r\n              speed_diff -= MAX_ACC;\r\n            }\r\n          }\r\n          else\r\n          {\r\n            if (lane != 1)\r\n            { \/\/ if we are not on the center lane.\r\n              if ((lane == 0 && !car_righ) || (lane == 2 && !car_left))\r\n              {\r\n                lane = 1; \/\/ Back to center.\r\n              }\r\n            }\r\n            if (ref_vel < MAX_SPEED)\r\n            {\r\n              speed_diff += MAX_ACC;\r\n            }\r\n          }\r\n\r\n          vector<double> ptsx;\r\n          vector<double> ptsy;\r\n\r\n          double ref_x = car_x;\r\n          double ref_y = car_y;\r\n          double ref_yaw = deg2rad(car_yaw);\r\n\r\n          \/\/ Do I have have previous points\r\n          if (prev_size < 2)\r\n          {\r\n            \/\/ There are not too many...\r\n            double prev_car_x = car_x - cos(car_yaw);\r\n            double prev_car_y = car_y - sin(car_yaw);\r\n\r\n            ptsx.push_back(prev_car_x);\r\n            ptsx.push_back(car_x);\r\n\r\n            ptsy.push_back(prev_car_y);\r\n            ptsy.push_back(car_y);\r\n          }\r\n          else\r\n          {\r\n            \/\/ Use the last two points.\r\n            ref_x = previous_path_x[prev_size - 1];\r\n            ref_y = previous_path_y[prev_size - 1];\r\n\r\n            double ref_x_prev = previous_path_x[prev_size - 2];\r\n            double ref_y_prev = previous_path_y[prev_size - 2];\r\n            ref_yaw = atan2(ref_y - ref_y_prev, ref_x - ref_x_prev);\r\n\r\n            ptsx.push_back(ref_x_prev);\r\n            ptsx.push_back(ref_x);\r\n\r\n            ptsy.push_back(ref_y_prev);\r\n            ptsy.push_back(ref_y);\r\n          }\r\n\r\n          \/\/ Setting up target points in the future.\r\n          vector<double> next_wp0 = getXY(car_s + 30, 2 + 4 * lane, map_waypoints_s, map_waypoints_x, map_waypoints_y);\r\n          vector<double> next_wp1 = getXY(car_s + 60, 2 + 4 * lane, map_waypoints_s, map_waypoints_x, map_waypoints_y);\r\n          vector<double> next_wp2 = getXY(car_s + 90, 2 + 4 * lane, map_waypoints_s, map_waypoints_x, map_waypoints_y);\r\n\r\n          ptsx.push_back(next_wp0[0]);\r\n          ptsx.push_back(next_wp1[0]);\r\n          ptsx.push_back(next_wp2[0]);\r\n\r\n          ptsy.push_back(next_wp0[1]);\r\n          ptsy.push_back(next_wp1[1]);\r\n          ptsy.push_back(next_wp2[1]);\r\n\r\n          \/\/ Making coordinates to local car coordinates.\r\n          for (int i = 0; i < ptsx.size(); i++)\r\n          {\r\n            double shift_x = ptsx[i] - ref_x;\r\n            double shift_y = ptsy[i] - ref_y;\r\n\r\n            ptsx[i] = shift_x * cos(0 - ref_yaw) - shift_y * sin(0 - ref_yaw);\r\n            ptsy[i] = shift_x * sin(0 - ref_yaw) + shift_y * cos(0 - ref_yaw);\r\n          }\r\n\r\n          \/\/ Create the spline.\r\n          tk::spline s;\r\n          s.set_points(ptsx, ptsy);\r\n\r\n          \/\/ Output path points from previous path for continuity.\r\n          vector<double> next_x_vals;\r\n          vector<double> next_y_vals;\r\n          for (int i = 0; i < prev_size; i++)\r\n          {\r\n            next_x_vals.push_back(previous_path_x[i]);\r\n            next_y_vals.push_back(previous_path_y[i]);\r\n          }\r\n\r\n          \/\/ Calculate distance y position on 30 m ahead.\r\n          double target_x = 30.0;\r\n          double target_y = s(target_x);\r\n          double target_dist = sqrt(target_x * target_x + target_y * target_y);\r\n\r\n          double x_add_on = 0;\r\n\r\n          for (int i = 1; i < 50 - prev_size; i++)\r\n          {\r\n            ref_vel += speed_diff;\r\n            if (ref_vel > MAX_SPEED)\r\n            {\r\n              ref_vel = MAX_SPEED;\r\n            }\r\n            else if (ref_vel < MAX_ACC)\r\n            {\r\n              ref_vel = MAX_ACC;\r\n            }\r\n            double N = target_dist \/ (0.02 * ref_vel \/ 2.24);\r\n            double x_point = x_add_on + target_x \/ N;\r\n            double y_point = s(x_point);\r\n\r\n            x_add_on = x_point;\r\n\r\n            double x_ref = x_point;\r\n            double y_ref = y_point;\r\n\r\n            x_point = x_ref * cos(ref_yaw) - y_ref * sin(ref_yaw);\r\n            y_point = x_ref * sin(ref_yaw) + y_ref * cos(ref_yaw);\r\n\r\n            x_point += ref_x;\r\n            y_point += ref_y;\r\n\r\n            next_x_vals.push_back(x_point);\r\n            next_y_vals.push_back(y_point);\r\n          }\r\n\r\n          json msgJson;\r\n\r\n          msgJson[\"next_x\"] = next_x_vals;\r\n          msgJson[\"next_y\"] = next_y_vals;\r\n\r\n          auto msg = \"42[\\\"control\\\",\" + msgJson.dump() + \"]\";\r\n\r\n          \/\/this_thread::sleep_for(chrono::milliseconds(1000));\r\n          ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\r\n        }\r\n      }\r\n      else\r\n      {\r\n        \/\/ Manual driving\r\n        std::string msg = \"42[\\\"manual\\\",{}]\";\r\n        ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\r\n      }\r\n    }\r\n  });\r\n\r\n  \/\/ We don't need this since we're not using HTTP but if it's removed the\r\n  \/\/ program\r\n  \/\/ doesn't compile :-(\r\n  h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data,\r\n                     size_t, size_t) {\r\n    const std::string s = \"<h1>Hello world!<\/h1>\";\r\n    if (req.getUrl().valueLength == 1)\r\n    {\r\n      res->end(s.data(), s.length());\r\n    }\r\n    else\r\n    {\r\n      \/\/ i guess this should be done more gracefully?\r\n      res->end(nullptr, 0);\r\n    }\r\n  });\r\n\r\n  h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {\r\n    std::cout << \"Connected!!!\" << std::endl;\r\n  });\r\n\r\n  h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,\r\n                         char *message, size_t length) {\r\n    ws.close();\r\n    std::cout << \"Disconnected\" << std::endl;\r\n  });\r\n\r\n  int port = 4567;\r\n  if (h.listen(port))\r\n  {\r\n    std::cout << \"Listening to port \" << port << std::endl;\r\n  }\r\n  else\r\n  {\r\n    std::cerr << \"Failed to listen to port\" << std::endl;\r\n    return -1;\r\n  }\r\n  h.run();\r\n}","avg_line_length":30.8956043956,"max_line_length":205,"alphanum_fraction":0.4997332385,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1671,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\ufeff\/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0.\n *\/\n\n#include <aws\/fms\/model\/EC2CopyRouteTableAction.h>\n#include <aws\/core\/utils\/json\/JsonSerializer.h>\n\n#include <utility>\n\nusing namespace Aws::Utils::Json;\nusing namespace Aws::Utils;\n\nnamespace Aws\n{\nnamespace FMS\n{\nnamespace Model\n{\n\nEC2CopyRouteTableAction::EC2CopyRouteTableAction() : \n    m_descriptionHasBeenSet(false),\n    m_vpcIdHasBeenSet(false),\n    m_routeTableIdHasBeenSet(false)\n{\n}\n\nEC2CopyRouteTableAction::EC2CopyRouteTableAction(JsonView jsonValue) : \n    m_descriptionHasBeenSet(false),\n    m_vpcIdHasBeenSet(false),\n    m_routeTableIdHasBeenSet(false)\n{\n  *this = jsonValue;\n}\n\nEC2CopyRouteTableAction& EC2CopyRouteTableAction::operator =(JsonView jsonValue)\n{\n  if(jsonValue.ValueExists(\"Description\"))\n  {\n    m_description = jsonValue.GetString(\"Description\");\n\n    m_descriptionHasBeenSet = true;\n  }\n\n  if(jsonValue.ValueExists(\"VpcId\"))\n  {\n    m_vpcId = jsonValue.GetObject(\"VpcId\");\n\n    m_vpcIdHasBeenSet = true;\n  }\n\n  if(jsonValue.ValueExists(\"RouteTableId\"))\n  {\n    m_routeTableId = jsonValue.GetObject(\"RouteTableId\");\n\n    m_routeTableIdHasBeenSet = true;\n  }\n\n  return *this;\n}\n\nJsonValue EC2CopyRouteTableAction::Jsonize() const\n{\n  JsonValue payload;\n\n  if(m_descriptionHasBeenSet)\n  {\n   payload.WithString(\"Description\", m_description);\n\n  }\n\n  if(m_vpcIdHasBeenSet)\n  {\n   payload.WithObject(\"VpcId\", m_vpcId.Jsonize());\n\n  }\n\n  if(m_routeTableIdHasBeenSet)\n  {\n   payload.WithObject(\"RouteTableId\", m_routeTableId.Jsonize());\n\n  }\n\n  return payload;\n}\n\n} \/\/ namespace Model\n} \/\/ namespace FMS\n} \/\/ namespace Aws\n","avg_line_length":18.5666666667,"max_line_length":80,"alphanum_fraction":0.7283064034,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5410,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["IJG"],"max_stars_count":null,"content":"\/\/ Copyright (C) 2009-2012 Gaz Davidson\n\/\/ This file is part of the \"Irrlicht Engine\".\n\/\/ For conditions of distribution and use, see copyright notice in irrlicht.h\n\n#include \"CTarReader.h\"\n\n\n#include \"CFileList.h\"\n#include \"CLimitReadFile.h\"\n#include \"os.h\"\n#include \"coreutil.h\"\n#include \"errno.h\"\n\nnamespace irr\n{\nnamespace io\n{\n\n\/\/! Constructor\nCArchiveLoaderTAR::CArchiveLoaderTAR(io::IFileSystem* fs)\n: FileSystem(fs)\n{\n\t#ifdef _DEBUG\n\tsetDebugName(\"CArchiveLoaderTAR\");\n\t#endif\n}\n\n\n\/\/! returns true if the file maybe is able to be loaded by this class\nbool CArchiveLoaderTAR::isALoadableFileFormat(const io::path& filename) const\n{\n\treturn core::hasFileExtension(filename, \"tar\");\n}\n\n\/\/! Check to see if the loader can create archives of this type.\nbool CArchiveLoaderTAR::isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const\n{\n\treturn fileType == EFAT_TAR;\n}\n\n\/\/! Creates an archive from the filename\n\/** \\param file File handle to check.\n\\return Pointer to newly created archive, or 0 upon error. *\/\nIFileArchive* CArchiveLoaderTAR::createArchive(const io::path& filename, bool ignoreCase, bool ignorePaths) const\n{\n\tIFileArchive *archive = 0;\n\tio::IReadFile* file = FileSystem->createAndOpenFile(filename);\n\n\tif (file)\n\t{\n\t\tarchive = createArchive(file, ignoreCase, ignorePaths);\n\t\tfile->drop();\n\t}\n\n\treturn archive;\n}\n\n\n\/\/! creates\/loads an archive from the file.\n\/\/! \\return Pointer to the created archive. Returns 0 if loading failed.\nIFileArchive* CArchiveLoaderTAR::createArchive(io::IReadFile* file, bool ignoreCase, bool ignorePaths) const\n{\n\tIFileArchive *archive = 0;\n\tif (file)\n\t{\n\t\tfile->seek(0);\n\t\tarchive = new CTarReader(file, ignoreCase, ignorePaths);\n\t}\n\treturn archive;\n}\n\n\/\/! Check if the file might be loaded by this class\n\/** Check might look into the file.\n\\param file File handle to check.\n\\return True if file seems to be loadable. *\/\nbool CArchiveLoaderTAR::isALoadableFileFormat(io::IReadFile* file) const\n{\n\t\/\/ TAR files consist of blocks of 512 bytes\n\t\/\/ if it isn't a multiple of 512 then it's not a TAR file.\n\tif (file->getSize() % 512)\n\t\treturn false;\n\n\tfile->seek(0);\n\n\t\/\/ read header of first file\n\tSTarHeader fHead;\n\tfile->read(&fHead, sizeof(STarHeader));\n\n\tu32 checksum = 0;\n\tsscanf(fHead.Checksum, \"%o\", &checksum);\n\n\t\/\/ verify checksum\n\n\t\/\/ some old TAR writers assume that chars are signed, others assume unsigned\n\t\/\/ USTAR archives have a longer header, old TAR archives end after linkname\n\n\tu32 checksum1=0;\n\ts32 checksum2=0;\n\n\t\/\/ remember to blank the checksum field!\n\tmemset(fHead.Checksum, ' ', 8);\n\n\t\/\/ old header\n\tfor (u8* p = (u8*)(&fHead); p < (u8*)(&fHead.Magic[0]); ++p)\n\t{\n\t\tchecksum1 += *p;\n\t\tchecksum2 += c8(*p);\n\t}\n\n\tif (!strncmp(fHead.Magic, \"ustar\", 5))\n\t{\n\t\tfor (u8* p = (u8*)(&fHead.Magic[0]); p < (u8*)(&fHead) + sizeof(fHead); ++p)\n\t\t{\n\t\t\tchecksum1 += *p;\n\t\t\tchecksum2 += c8(*p);\n\t\t}\n\t}\n\treturn checksum1 == checksum || checksum2 == (s32)checksum;\n}\n\n\/*\n\tTAR Archive\n*\/\nCTarReader::CTarReader(IReadFile* file, bool ignoreCase, bool ignorePaths)\n : CFileList((file ? file->getFileName() : io::path(\"\")), ignoreCase, ignorePaths), File(file)\n{\n\t#ifdef _DEBUG\n\tsetDebugName(\"CTarReader\");\n\t#endif\n\n\tif (File)\n\t{\n\t\tFile->grab();\n\n\t\t\/\/ fill the file list\n\t\tpopulateFileList();\n\n\t\tsort();\n\t}\n}\n\n\nCTarReader::~CTarReader()\n{\n\tif (File)\n\t\tFile->drop();\n}\n\n\nconst IFileList* CTarReader::getFileList() const\n{\n\treturn this;\n}\n\n\nu32 CTarReader::populateFileList()\n{\n\tSTarHeader fHead;\n\tFiles.clear();\n\n\tu32 pos = 0;\n\twhile ( s32(pos + sizeof(STarHeader)) < File->getSize())\n\t{\n\t\t\/\/ seek to next file header\n\t\tFile->seek(pos);\n\n\t\t\/\/ read the header\n\t\tFile->read(&fHead, sizeof(fHead));\n\n\t\t\/\/ only add standard files for now\n\t\tif (fHead.Link == ETLI_REGULAR_FILE || ETLI_REGULAR_FILE_OLD)\n\t\t{\n\t\t\tio::path fullPath = \"\";\n\t\t\tfullPath.reserve(255);\n\n\t\t\t\/\/ USTAR archives have a filename prefix\n\t\t\t\/\/ may not be null terminated, copy carefully!\n\t\t\tif (!strncmp(fHead.Magic, \"ustar\", 5))\n\t\t\t{\n\t\t\t\tc8* np = fHead.FileNamePrefix;\n\t\t\t\twhile(*np && (np - fHead.FileNamePrefix) < 155)\n\t\t\t\t\tfullPath.append(*np);\n\t\t\t\tnp++;\n\t\t\t}\n\n\t\t\t\/\/ append the file name\n\t\t\tc8* np = fHead.FileName;\n\t\t\twhile(*np && (np - fHead.FileName) < 100)\n\t\t\t{\n\t\t\t\tfullPath.append(*np);\n\t\t\t\tnp++;\n\t\t\t}\n\n\t\t\t\/\/ get size\n\t\t\tcore::stringc sSize = \"\";\n\t\t\tsSize.reserve(12);\n\t\t\tnp = fHead.Size;\n\t\t\twhile(*np && (np - fHead.Size) < 12)\n\t\t\t{\n\t\t\t\tsSize.append(*np);\n\t\t\t\tnp++;\n\t\t\t}\n\n\t\t\tu32 size = strtoul(sSize.c_str(), NULL, 8);\n\n\t\t\tif (errno == ERANGE)\n\t\t\t\tos::Printer::log(\"File too large\", fullPath, ELL_WARNING);\n\n\t\t\t\/\/ save start position\n\t\t\tu32 offset = pos + 512;\n\n\t\t\t\/\/ move to next file header block\n\t\t\tpos = offset + (size \/ 512) * 512 + ((size % 512) ? 512 : 0);\n\n\t\t\t\/\/ add file to list\n\t\t\taddItem(fullPath, offset, size, false );\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ todo: ETLI_DIRECTORY, ETLI_LINK_TO_ARCHIVED_FILE\n\n\t\t\t\/\/ move to next block\n\t\t\tpos += 512;\n\t\t}\n\n\t}\n\n\treturn Files.size();\n}\n\n\/\/! opens a file by file name\nIReadFile* CTarReader::createAndOpenFile(const io::path& filename)\n{\n\tconst s32 index = findFile(filename, false);\n\n\tif (index != -1)\n\t\treturn createAndOpenFile(index);\n\n\treturn 0;\n}\n\n\/\/! opens a file by index\nIReadFile* CTarReader::createAndOpenFile(u32 index)\n{\n\tif (index >= Files.size() )\n\t\treturn 0;\n\n\tconst SFileListEntry &entry = Files[index];\n\treturn createLimitReadFile( entry.FullName, File, entry.Offset, entry.Size );\n}\n\n} \/\/ end namespace io\n} \/\/ end namespace irr\n\n","avg_line_length":21.2156862745,"max_line_length":113,"alphanum_fraction":0.671349353,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2580,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"..\/utility\/catch.hpp\"\n#include \"..\/utility\/nondominated_sorting\/fast_sort.h\"\n#include \"..\/utility\/nondominated_sorting\/deductive_sort.h\"\n#include \"..\/utility\/nondominated_sorting\/filter_sort.h\"\n#include <iostream>\n\nusing namespace OFEC;\n\nTEST_CASE(\"fast noodominated sorting\", \"[FNS]\") {\n\tstd::vector<std::vector<int>> int_2d_array{ {2,4},{4,8},{6,12},{3,3},{6,6},{9,9},{4,2},{8,4},{12,6} };\n\tstd::vector<std::vector<int>*> data;\n\tfor (auto& i : int_2d_array)\n\t\tdata.emplace_back(&i);\n\tstd::vector<int> rank;\n\tstd::vector<optimization_mode> opt_mode(2, optimization_mode::Minimization);\n\n\tNS::fast_sort<int>(data, rank, opt_mode);\n    for (auto i : rank)\n        std::cout << i << \" \";\n    std::cout << std::endl;\n\n\tNS::fast_sort_p<int>(data, rank, opt_mode, 8);\n\tfor (auto i : rank)\n\t\tstd::cout << i << \" \";\n\tstd::cout << std::endl;\n}\n\nTEST_CASE(\"Deductive Sort\", \"[DeductiveSort]\") {\n\tstd::vector<std::vector<int>> int_2d_array{ {2,4},{4,8},{6,12},{3,3},{6,6},{9,9},{4,2},{8,4},{12,6} };\n\tstd::vector<std::vector<int>*> data;\n\tfor (auto& i : int_2d_array)\n\t\tdata.emplace_back(&i);\n\tstd::vector<int> rank;\n\tstd::vector<optimization_mode> opt_mode(2, optimization_mode::Minimization);\n\n\tNS::deductive_sort<int>(data, rank, opt_mode);\n\tfor (auto i : rank)\n\t\tstd::cout << i << \" \";\n\tstd::cout << std::endl;\n}\n\nTEST_CASE(\"Filter Sort\", \"[FilterSort]\") {\n\/\/    std::vector<std::vector<float>> int_2d_array{ {2,4},{4,8},{6,12},{3,3},{6,6},{9,9},{4,2},{8,4},{12,6} };\n    const size_t N = 250, M = 2;\n\n    std::vector<std::vector<float>> int_2d_array(N, std::vector<float>(M));\n    for (int i = 0; i < N; ++i) {\n        int_2d_array[i][0] = rand();\n        int_2d_array[i][1] = 1;\n    }\n    std::vector<std::vector<float>*> data;\n    for (auto& i : int_2d_array)\n        data.emplace_back(&i);\n    std::vector<int> rank;\n    std::vector<optimization_mode> opt_mode({optimization_mode::Minimization, optimization_mode::Maximization});\n\n    const int N_ = data.size(), M_ = data[0]->size();\n    std::cout << N_ << \" \" << M_ << std::endl;\n\n    NS::fast_sort<float>(data, rank, opt_mode);\n    for (auto i : rank)\n        std::cout << i << \" \";\n    std::cout << std::endl;\n\n    NS::fast_sort_p<float>(data, rank, opt_mode, 8);\n    for (auto i : rank)\n        std::cout << i << \" \";\n    std::cout << std::endl;\n\n    NS::filter_sort<float>(data, rank, opt_mode);\n    for (auto i : rank)\n        std::cout << i << \" \";\n    std::cout << std::endl;\n\n    NS::filter_sort_p<float>(data, rank, opt_mode);\n    for (auto i : rank)\n        std::cout << i << \" \";\n    std::cout << std::endl;\n}","avg_line_length":32.6582278481,"max_line_length":112,"alphanum_fraction":0.5976744186,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":15596,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/ Copyright (c) 2015-2017 The PIVX developers\n\/\/ Copyright (c) 2017-2018 The Solaris developers\n\/\/ Copyright (c) 2018 MergeCard developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include \"libzerocoin\/Params.h\"\n#include \"chainparams.h\"\n#include \"random.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n#include <assert.h>\n#include <boost\/assign\/list_of.hpp>\nusing namespace std;\nusing namespace boost::assign;\nstruct SeedSpec6 {\n    uint8_t addr[16];\n    uint16_t port;\n};\n#include \"chainparamsseeds.h\"\n\/**\n * Main network\n *\/\n\/\/! Convert the pnSeeds6 array into usable address objects.\nstatic void convertSeed6(std::vector<CAddress>& vSeedsOut, const SeedSpec6* data, unsigned int count)\n{\n    \/\/ It'll only connect to one or two seed nodes because once it connects,\n    \/\/ it'll get a pile of addresses with newer timestamps.\n    \/\/ Seed nodes are given a random 'last seen time' of between one and two\n    \/\/ weeks ago.\n    const int64_t nOneWeek = 7 * 24 * 60 * 60;\n    for (unsigned int i = 0; i < count; i++) {\n        struct in6_addr ip;\n        memcpy(&ip, data[i].addr, sizeof(ip));\n        CAddress addr(CService(ip, data[i].port));\n        addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;\n        vSeedsOut.push_back(addr);\n    }\n}\n\/\/   What makes a good checkpoint block?\n\/\/ + Is surrounded by blocks with reasonable timestamps\n\/\/   (no blocks before with a timestamp after, none after with\n\/\/    timestamp before)\n\/\/ + Contains no strange transactions\nstatic Checkpoints::MapCheckpoints mapCheckpoints =\n    boost::assign::map_list_of\n\t(0, uint256(\"0x000005a4e82f86719afbefc48dce958950f18af4e6319b23cd26c9e9d3400051\"));\nstatic const Checkpoints::CCheckpointData data = {\n    &mapCheckpoints,\n    1525853154, \/\/ * UNIX timestamp of last checkpoint block\n    286541,    \/\/ * total number of transactions between genesis and last checkpoint\n                \/\/   (the tx=... number in the SetBestChain debug.log lines)\n    1800        \/\/ * estimated number of transactions per day after checkpoint\n};\n\nstatic Checkpoints::MapCheckpoints mapCheckpointsTestnet =\n    boost::assign::map_list_of(0, uint256(\"0x001\"));\nstatic const Checkpoints::CCheckpointData dataTestnet = {\n    &mapCheckpointsTestnet,\n    1740710,\n    0,\n    250};\n\nstatic Checkpoints::MapCheckpoints mapCheckpointsRegtest =\n    boost::assign::map_list_of(0, uint256(\"0x001\"));\nstatic const Checkpoints::CCheckpointData dataRegtest = {\n    &mapCheckpointsRegtest,\n    1454124731,\n    0,\n    100};\n\nlibzerocoin::ZerocoinParams* CChainParams::Zerocoin_Params() const\n{\n    assert(this);\n    static CBigNum bnTrustedModulus(zerocoinModulus);\n    static libzerocoin::ZerocoinParams ZCParams = libzerocoin::ZerocoinParams(bnTrustedModulus);\n\n    return &ZCParams;\n}\nclass CMainParams : public CChainParams\n{\npublic:\n    CMainParams()\n    {\n        networkID = CBaseChainParams::MAIN;\n        strNetworkID = \"main\";\n        \/**\n         * The message start string is designed to be unlikely to occur in normal data.\n         * The characters are rarely used upper ASCII, not valid as UTF-8, and produce\n         * a large 4-byte int at any alignment.\n         *\/\n        pchMessageStart[0] = 0x0d;\n        pchMessageStart[1] = 0x09;\n        pchMessageStart[2] = 0x14;\n        pchMessageStart[3] = 0x0c;\n        vAlertPubKey = ParseHex(\"04121f69af3faf245986064e314611256e11f05049c47d027e831293b8ba1a5e9e4f757a30ca93e0fe4b608b86eada1f2c9a9bd070574cf1091f1185d7bea3386e\");\n        nDefaultPort = 31433;\n        bnProofOfWorkLimit = ~uint256(0) >> 20; \/\/ MergeCard starting difficulty is 1 \/ 2^12\n        nSubsidyHalvingInterval = 210000;\n        nMaxReorganizationDepth = 100;\n        nMinerThreads = 0;\n        nTargetTimespan = 1 * 60; \/\/ MergeCard: 1 minute\n        nTargetSpacing = 1 * 60;  \/\/ MergeCard: 1 minute\n        nMaturity = 10;\n\tnMaxMoneyOut = 10000000000 * COIN;\n        \/** Height or Time Based Activations **\/\n        nLastPOWBlock = 259200;\n        nModifierUpdateBlock = 1;\n\t\t\n        nBlockEnforceSerialRange = 1; \/\/Enforce serial range starting this block\n        nZerocoinStartTime = 1583798400; \/\/ Tuesday, Mar-10-20 00:00:00 UTC\n\tnZerocoinStartHeight = 11111222;\n\n\tconst char* pszTimestamp = \"In MergeCard we trust! 11356361\";\n        CMutableTransaction txNew;\n        txNew.vin.resize(1);\n        txNew.vout.resize(1);\n        txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));\n        txNew.vout[0].nValue = 0 * COIN;\n        txNew.vout[0].scriptPubKey = CScript() << ParseHex(\"04121f69af3faf245986064e314611256e11f05049c47d027e831293b8ba1a5e9e4f757a30ca93e0fe4b608b86eada1f2c9a9bd070574cf1091f1185d7bea3386e\") << OP_CHECKSIG;\n        genesis.vtx.push_back(txNew);\n        genesis.hashPrevBlock = 0;\n        genesis.hashMerkleRoot = genesis.BuildMerkleTree();\n        genesis.nVersion = 1;\n        genesis.nTime = 1525858740;\n        genesis.nBits = 0x1e0ffff0;\n        genesis.nNonce = 1073058;\n        hashGenesisBlock = genesis.GetHash();\n        assert(hashGenesisBlock == uint256(\"0x000005a4e82f86719afbefc48dce958950f18af4e6319b23cd26c9e9d3400051\"));\n        assert(genesis.hashMerkleRoot == uint256(\"0xb111e6942594a01208c78b8c42546f20d166f548841f78938ba8a10a3bc90895\"));\n        vSeeds.push_back(CDNSSeedData(\"master.mergecard.com\", \"master.mergecard.com\"));\n        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 50);\n        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 3);\n        base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 199);\n        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x02)(0x0e)(0xc9)(0x41).convert_to_container<std::vector<unsigned char> >();\n        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x02)(0xfd)(0xd5)(0x39).convert_to_container<std::vector<unsigned char> >();\n        \/\/ \tBIP44 coin type is 'TBD'\n        base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x04)(0x48)(0x22).convert_to_container<std::vector<unsigned char> >();\n        convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));\n        fRequireRPCPassword = true;\n        fMiningRequiresPeers = true;\n        fAllowMinDifficultyBlocks = false;\n        fDefaultConsistencyChecks = false;\n        fRequireStandard = true;\n        fMineBlocksOnDemand = false;\n        fSkipProofOfWorkCheck = false;\n        fTestnetToBeDeprecatedFieldRPC = false;\n        fHeadersFirstSyncingActive = false;\n\tnPoolMaxTransactions = 3;\n        strSporkKey = \"028b00a5b22c43a345a5aaffc0e33dea5bd1f19d5cc57bb8fe052e79f8bf39c6a7\";\n        strObfuscationPoolDummyAddress = \"MWixVKL16xLGjz6ScxLt7ZQ2DQaMH1XwVH\";\n        nStartMasternodePayments = 1526130877; \/\/Wed, 25 Jun 2014 20:36:16 GMT\n\n        \/** Zerocoin. Recalculate modulus with libzerocoin in future. *\/\n        zerocoinModulus = \"25195908475657893494027183240048398571429282126204032027777137836043662020707595556264018525880784\"\n            \"4069182906412495150821892985591491761845028084891200728449926873928072877767359714183472702618963750149718246911\"\n            \"6507761337985909570009733045974880842840179742910064245869181719511874612151517265463228221686998754918242243363\"\n            \"7259085141865462043576798423387184774447920739934236584823824281198163815010674810451660377306056201619676256133\"\n            \"8441436038339044149526344321901146575444541784240209246165157233507787077498171257724679629263863563732899121548\"\n            \"31438167899885040445364023527381951378636564391212010397122822120720357\";\n        nMaxZerocoinSpendsPerTransaction = 7; \/\/ Assume about 20kb each\n        nMinZerocoinMintFee = 1 * CENT; \/\/high fee required for zerocoin mints\n        nMintRequiredConfirmations = 20; \/\/the maximum amount of confirmations until accumulated in 19\n        nRequiredAccumulation = 2;\n        nDefaultSecurityLevel = 100; \/\/full security level for accumulators\n        nZerocoinHeaderVersion = 4; \/\/Block headers must be this version once zerocoin is active\n        nBudget_Fee_Confirmations = 6; \/\/ Number of confirmations for the finalization fee\n    }\n    const Checkpoints::CCheckpointData& Checkpoints() const\n    {\n        return data;\n    }\n};\nstatic CMainParams mainParams;\n\/**\n * Testnet (v3)\n *\/\nclass CTestNetParams : public CMainParams\n{\npublic:\n    CTestNetParams()\n    {\n        networkID = CBaseChainParams::TESTNET;\n        strNetworkID = \"test\";\n        pchMessageStart[0] = 0x31;\n        pchMessageStart[1] = 0x12;\n        pchMessageStart[2] = 0xe4;\n        pchMessageStart[3] = 0xd1;\n        vAlertPubKey = ParseHex(\"0446c48689c510fe954a25d8295e9614958a4aac923ba2d88884e169c542bed211642828d4de31180d2e0f4ad8ce4a7af705ff64539958d240ef1ded01cc9a0ceb\");\n        nDefaultPort = 31533;\n        nMinerThreads = 0;\n        nTargetTimespan = 1 * 60; \/\/ MergeCard: 1 day\n        nTargetSpacing = 1 * 60;  \/\/ MergeCard: 1 minute\n        nLastPOWBlock = 200;\n        nMaturity = 15;\n        nMasternodeCountDrift = 4;\n        nModifierUpdateBlock = 51197; \/\/approx Mon, 17 Apr 2017 04:00:00 GMT\n        nMaxMoneyOut = 43199500 * COIN;\n        nZerocoinStartHeight = 111222;\n        \/\/! Modify the testnet genesis block so the timestamp is valid for a later start.\n        genesis.nTime = 1526130877;\n        genesis.nNonce = 11762;\n        hashGenesisBlock = genesis.GetHash();\n\n        \/\/assert(hashGenesisBlock == uint256(\"0x0000041e482b9b9691d98eefb48473405c0b8ec31b76df3797c74a78680ef818\"));\n        vFixedSeeds.clear();\n        vSeeds.clear();\n        vSeeds.push_back(CDNSSeedData(\"master.mergecard.com\", \"master.mergecard.com\"));\n        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 139); \/\/ Testnet mergecard addresses start with 'x' or 'y'\n        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 19);  \/\/ Testnet mergecard script addresses start with '8' or '9'\n        base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239);     \/\/ Testnet private keys start with '9' or 'c' (Bitcoin defaults)\n        \/\/ Testnet mergecard BIP32 pubkeys start with 'DRKV'\n        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x3a)(0x80)(0x61)(0xa0).convert_to_container<std::vector<unsigned char> >();\n        \/\/ Testnet mergecard BIP32 prvkeys start with 'DRKP'\n        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x3a)(0x80)(0x58)(0x37).convert_to_container<std::vector<unsigned char> >();\n        \/\/ Testnet mergecard BIP44 coin type is '1' (All coin's testnet default)\n        base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x00)(0x01).convert_to_container<std::vector<unsigned char> >();\n        convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));\n        fRequireRPCPassword = true;\n        fMiningRequiresPeers = true;\n        fAllowMinDifficultyBlocks = true;\n        fDefaultConsistencyChecks = false;\n        fRequireStandard = false;\n        fMineBlocksOnDemand = false;\n        fTestnetToBeDeprecatedFieldRPC = true;\n        nPoolMaxTransactions = 2;\n        strSporkKey = \"028b00a5b22c43a345a5aaffc0e33dea5bd1f19d5cc57bb8fe052e79f8bf39c6a7\";\n        strObfuscationPoolDummyAddress = \"y57cqfGRkekRyDRNeJiLtYVEbvhXrNbmox\";\n        nStartMasternodePayments = 1526130877; \/\/Fri, 09 Jan 2015 21:05:58 GMT\n        nBudget_Fee_Confirmations = 3; \/\/ Number of confirmations for the finalization fee. We have to make this very short \n                                       \/\/ here because we only have a 8 block finalization window on testnet\n    }\n    const Checkpoints::CCheckpointData& Checkpoints() const\n    {\n        return dataTestnet;\n    }\n};\nstatic CTestNetParams testNetParams;\n\/**\n * Regression test\n *\/\nclass CRegTestParams : public CTestNetParams\n{\npublic:\n    CRegTestParams()\n    {\n        networkID = CBaseChainParams::REGTEST;\n        strNetworkID = \"regtest\";\n        strNetworkID = \"regtest\";\n        pchMessageStart[0] = 0xd3;\n        pchMessageStart[1] = 0xaa;\n        pchMessageStart[2] = 0x13;\n        pchMessageStart[3] = 0x4b;\n        nSubsidyHalvingInterval = 150;\n        nMinerThreads = 1;\n        nTargetTimespan = 24 * 60 * 60; \/\/ MergeCard: 1 day\n        nTargetSpacing = 1 * 60;        \/\/ MergeCard: 1 minutes\n        bnProofOfWorkLimit = ~uint256(0) >> 1;\n        genesis.nTime = 1526130877;\n        genesis.nBits = 0x207fffff;\n        genesis.nNonce = 12345;\n        hashGenesisBlock = genesis.GetHash();\n        nDefaultPort = 31633;\n        \/\/assert(hashGenesisBlock == uint256(\"0x4f023a2120d9127b21bbad01724fdb79b519f593f2a85b60d3d79160ec5f29df\"));\n        vFixedSeeds.clear(); \/\/! Testnet mode doesn't have any fixed seeds.\n        vSeeds.clear();      \/\/! Testnet mode doesn't have any DNS seeds.\n        fRequireRPCPassword = false;\n        fMiningRequiresPeers = false;\n        fAllowMinDifficultyBlocks = true;\n        fDefaultConsistencyChecks = true;\n        fRequireStandard = false;\n        fMineBlocksOnDemand = true;\n        fTestnetToBeDeprecatedFieldRPC = false;\n    }\n    const Checkpoints::CCheckpointData& Checkpoints() const\n    {\n        return dataRegtest;\n    }\n};\nstatic CRegTestParams regTestParams;\n\/**\n * Unit test\n *\/\nclass CUnitTestParams : public CMainParams, public CModifiableParams\n{\npublic:\n    CUnitTestParams()\n    {\n        networkID = CBaseChainParams::UNITTEST;\n        strNetworkID = \"unittest\";\n        nDefaultPort = 31733;\n        vFixedSeeds.clear(); \/\/! Unit test mode doesn't have any fixed seeds.\n        vSeeds.clear();      \/\/! Unit test mode doesn't have any DNS seeds.\n        fRequireRPCPassword = false;\n        fMiningRequiresPeers = false;\n        fDefaultConsistencyChecks = true;\n        fAllowMinDifficultyBlocks = false;\n        fMineBlocksOnDemand = true;\n    }\n    const Checkpoints::CCheckpointData& Checkpoints() const\n    {\n        \/\/ UnitTest share the same checkpoints as MAIN\n        return data;\n    }\n    \/\/! Published setters to allow changing values in unit test cases\n    virtual void setSubsidyHalvingInterval(int anSubsidyHalvingInterval) { nSubsidyHalvingInterval = anSubsidyHalvingInterval; }\n    virtual void setDefaultConsistencyChecks(bool afDefaultConsistencyChecks) { fDefaultConsistencyChecks = afDefaultConsistencyChecks; }\n    virtual void setAllowMinDifficultyBlocks(bool afAllowMinDifficultyBlocks) { fAllowMinDifficultyBlocks = afAllowMinDifficultyBlocks; }\n    virtual void setSkipProofOfWorkCheck(bool afSkipProofOfWorkCheck) { fSkipProofOfWorkCheck = afSkipProofOfWorkCheck; }\n};\n\nstatic CChainParams* pCurrentParams = 0;\n\nconst CChainParams& Params()\n{\n    assert(pCurrentParams);\n    return *pCurrentParams;\n}\nCChainParams& Params(CBaseChainParams::Network network)\n{\n    switch (network) {\n    case CBaseChainParams::MAIN:\n        return mainParams;\n    case CBaseChainParams::TESTNET:\n        return testNetParams;\n    case CBaseChainParams::REGTEST:\n        return regTestParams;\n    default:\n        assert(false && \"Unimplemented network\");\n        return mainParams;\n    }\n}\nvoid SelectParams(CBaseChainParams::Network network)\n{\n    SelectBaseParams(network);\n    pCurrentParams = &Params(network);\n}\nbool SelectParamsFromCommandLine()\n{\n    CBaseChainParams::Network network = NetworkIdFromCommandLine();\n    if (network == CBaseChainParams::MAX_NETWORK_TYPES)\n        return false;\n    SelectParams(network);\n    return true;\n}","avg_line_length":44.9452449568,"max_line_length":208,"alphanum_fraction":0.7051166966,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1549,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"class CfgPatches\n{\n\tclass functions_f_spotify\n\t{\n\t\tauthors[]= {\"Asaayu\"};\n\t\tauthor = \"Asaayu\";\n\t\tname = \"Asaayu's Arma Spotify Player - Functions\";\n\t\turl = \"https:\/\/github.com\/Asaayu\/Arma-Spotify-Player\";\n\t\tunits[] = {};\n\t\tweapons[] = {};\n\t\trequiredVersion = 0.1;\n\t\trequiredAddons[] = { \"A3_Data_F\", \"main_f_spotify\"};\n\t};\n};\n\nclass Extended_PreInit_EventHandlers\n{\n\tclass aasp_init_event\n\t{\n\t\tinit = \"call compile preprocessFileLineNumbers '\\spotify\\functions_f_spotify\\XEH_preInit.sqf'\";\n\t};\n};\n\nclass CfgFunctions\n{\n\tclass functions_f_spotify\n\t{\n\t\ttag = \"spotify\";\n\t\tclass spotify_internal\n\t\t{\n\t\t        file = \"\\spotify\\functions_f_spotify\\functions\";\n\t\t\tclass preinit { preinit = 1; };\n\t\t};\n\t\tclass spotify_api_functions\n\t\t{\n\t\t        file = \"\\spotify\\functions_f_spotify\\functions\\spotify\";\n\t\t\tclass get_devices {};\n\n\t\t\tclass set_playback {};\n\t\t\tclass set_shuffle {};\n\t\t\tclass set_repeat {};\n\n\t\t\tclass update_display {};\n\t\t\tclass update_song_info {};\n\n\t\t\tclass like {};\n\t\t\tclass skip {};\n\t\t\tclass play {};\n\t\t\tclass volume {};\n\t\t\tclass seek {};\n\t\t};\n\t\tclass spotify_gui_functions\n\t\t{\n\t\t        file = \"\\spotify\\functions_f_spotify\\functions\\gui\";\n\t\t\tclass menu_onload {};\n\t\t\tclass setup_onload {};\n\t\t\tclass text_scroll {};\n\n\t\t\tclass track_click {};\n\n\t\t\tclass open_home {};\n\t\t\tclass open_listen {};\n\t\t\tclass open_recent {};\n\t\t\tclass open_liked {};\n\t\t\tclass open_playlist {};\n\t\t\tclass open_album {};\n\n\t\t\tclass close_menus {};\n\n\t\t\tclass master_selection {};\n\t\t\tclass secondary_selection {};\n\n\t\t\tclass gui {};\n\t\t\tclass notification {};\n\t\t};\n\t};\n};\n","avg_line_length":19.858974359,"max_line_length":97,"alphanum_fraction":0.6513879923,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":103,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":16.0,"content":"\n#include \"loop.h\"\n\n#include <gtest\/gtest.h>\n\nnamespace dote {\n\n\/\/ TODO: Test me\n\n}  \/\/ namespace dote\n","avg_line_length":9.3636363636,"max_line_length":24,"alphanum_fraction":0.640776699,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1928,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\n * MIT License <http:\/\/opensource.org\/licenses\/MIT>.\n *\/\n\n#include <ArduinoLog.h>\n#include \"WiFiSupport.h\"\n#include \"MqttSupport.h\"\n\nWiFiClient wifiClient;\nPubSubClient mqttCient;\n\nvoid visualizeNetworkConnectionLost();\n\nvoid MqttSupportClass::setup()\n{\n    \/\/ Set-Up WiFi connection.\n    WiFiSupport.setup();\n\n    \/\/ Initialize MQTT connection.\n    mqttCient.setClient(wifiClient);\n    mqttCient.setServer(MQTT_HOST, MQTT_PORT);\n    sinceReconnect = 10000;\n    this->connect();\n}\n\nvoid MqttSupportClass::loop()\n{\n    \/\/ Check WIFI connection.\n    WiFiSupport.loop();\n\n    this->connect();\n    visualizeNetworkConnectionLost();\n}\n\nvoid MqttSupportClass::connect()\n{\n    if (WiFiSupport.isConnected() && !this->isConnected() && sinceReconnect >= 10000)\n    {\n        Log.trace(\"Connect to MQTT broker %s:%d with clientId %s. Current client state: %d. Connection attempts: %d\",\n                  MQTT_HOST, MQTT_PORT, MQTT_CLIENT_ID, mqttCient.state(), ++reconnectionAttempts);\n        \/\/ Try to connect to the MQTT broker\n#if defined(MQTT_USER) && defined(MQTT_PASS)\n        mqttCient.connect(MQTT_CLIENT_ID, MQTT_USER, MQTT_PASS);\n#else\n        mqttCient.connect(MQTT_CLIENT_ID);\n#endif\n        sinceReconnect = 0;\n    }\n}\n\nbool MqttSupportClass::isConnected()\n{\n    return mqttCient.connected();\n}\n\nbool MqttSupportClass::publish(String message)\n{\n    return mqttCient.publish(MQTT_TOPIC_PUB, message.c_str());\n}\n\nvoid visualizeNetworkConnectionLost()\n{\n    if (!WiFiSupport.isConnected() || !MqttSupport.isConnected())\n    {\n        digitalWrite(LED_BUILTIN, LOW);\n        delay(300);\n        digitalWrite(LED_BUILTIN, HIGH);\n        delay(300);\n        digitalWrite(LED_BUILTIN, LOW);\n        delay(100);\n        digitalWrite(LED_BUILTIN, HIGH);\n        delay(100);\n        digitalWrite(LED_BUILTIN, LOW);\n        delay(300);\n    }\n    digitalWrite(LED_BUILTIN, HIGH);\n}\n\nMqttSupportClass MqttSupport = MqttSupportClass();","avg_line_length":24.4050632911,"max_line_length":117,"alphanum_fraction":0.6768672199,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":791,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"class Solution {\npublic:\n    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) \n    {\n        map<int,vector<int>> x;\n        if(k==0)\n            return false;\n        if(t!=0)\n        {\n            for(int i=0;i<nums.size();i++)\n                for(int j=i+1;j<=i+k&&j<nums.size();j++)\n                    if(abs((long)nums[i]-nums[j])<=t)\n                        return true;\n        }\n        else\n        {\n            for(int i=0;i<nums.size();i++)\n                x[nums[i]].push_back(i);\n            for(auto e: x)\n                for(int i=0;i<e.second.size();i++)\n                    for(int j=i+1;j<e.second.size();i++)\n                        if(abs(e.second[i]-e.second[j])<=k)\n                            return true;\n        }\n        return false;\n    }\n};\n","avg_line_length":28.25,"max_line_length":72,"alphanum_fraction":0.3931731985,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5016,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":15.0,"content":"\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2013-2020 Winlin\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <srs_app_security.hpp>\n\n#include <srs_kernel_error.hpp>\n#include <srs_app_config.hpp>\n\nusing namespace std;\n\nSrsSecurity::SrsSecurity()\n{\n}\n\nSrsSecurity::~SrsSecurity()\n{\n}\n\nsrs_error_t SrsSecurity::check(SrsRtmpConnType type, string ip, SrsRequest* req)\n{\n    srs_error_t err = srs_success;\n\n    \/\/ allow all if security disabled.\n    if (!_srs_config->get_security_enabled(req->vhost)) {\n        return err; \/\/ OK\n    }\n\n    \/\/ rules to apply\n    SrsConfDirective* rules = _srs_config->get_security_rules(req->vhost);\n    return do_check(rules, type, ip, req);\n}\n\nsrs_error_t SrsSecurity::do_check(SrsConfDirective* rules, SrsRtmpConnType type, string ip, SrsRequest* req)\n{\n    srs_error_t err = srs_success;\n\n    if (!rules) {\n        return srs_error_new(ERROR_SYSTEM_SECURITY, \"default deny for %s\", ip.c_str());\n    }\n\n    \/\/ deny if matches deny strategy.\n    if ((err = deny_check(rules, type, ip)) != srs_success) {\n        return srs_error_wrap(err, \"for %s\", ip.c_str());\n    }\n    \n    \/\/ allow if matches allow strategy.\n    if ((err = allow_check(rules, type, ip)) != srs_success) {\n        return srs_error_wrap(err, \"for %s\", ip.c_str());\n    }\n\n    return err;\n}\n\nsrs_error_t SrsSecurity::allow_check(SrsConfDirective* rules, SrsRtmpConnType type, std::string ip)\n{\n    int allow_rules = 0;\n    int deny_rules = 0;\n\n    for (int i = 0; i < (int)rules->directives.size(); i++) {\n        SrsConfDirective* rule = rules->at(i);\n\n        if (rule->name != \"allow\") {\n            if (rule->name == \"deny\") {\n                deny_rules++;\n            }\n            continue;\n        }\n        allow_rules++;\n\n        switch (type) {\n            case SrsRtmpConnPlay:\n                if (rule->arg0() != \"play\") {\n                    break;\n                }\n                if (rule->arg1() == \"all\" || rule->arg1() == ip) {\n                    return srs_success; \/\/ OK\n                }\n                break;\n            case SrsRtmpConnFMLEPublish:\n            case SrsRtmpConnFlashPublish:\n            case SrsRtmpConnHaivisionPublish:\n                if (rule->arg0() != \"publish\") {\n                    break;\n                }\n                if (rule->arg1() == \"all\" || rule->arg1() == ip) {\n                    return srs_success; \/\/ OK\n                }\n                break;\n            case SrsRtmpConnUnknown:\n            default:\n                break;\n        }\n    }\n\n    if (allow_rules > 0 || (deny_rules + allow_rules) == 0) {\n        return srs_error_new(ERROR_SYSTEM_SECURITY_ALLOW, \"not allowed by any of %d\/%d rules\", allow_rules, deny_rules);\n    }\n    return srs_success; \/\/ OK\n}\n\nsrs_error_t SrsSecurity::deny_check(SrsConfDirective* rules, SrsRtmpConnType type, std::string ip)\n{\n    for (int i = 0; i < (int)rules->directives.size(); i++) {\n        SrsConfDirective* rule = rules->at(i);\n        \n        if (rule->name != \"deny\") {\n            continue;\n        }\n        \n        switch (type) {\n            case SrsRtmpConnPlay:\n                if (rule->arg0() != \"play\") {\n                    break;\n                }\n                if (rule->arg1() == \"all\" || rule->arg1() == ip) {\n                    return srs_error_new(ERROR_SYSTEM_SECURITY_DENY, \"deny by rule<%s>\", rule->arg1().c_str());\n                }\n                break;\n            case SrsRtmpConnFMLEPublish:\n            case SrsRtmpConnFlashPublish:\n            case SrsRtmpConnHaivisionPublish:\n                if (rule->arg0() != \"publish\") {\n                    break;\n                }\n                if (rule->arg1() == \"all\" || rule->arg1() == ip) {\n                    return srs_error_new(ERROR_SYSTEM_SECURITY_DENY, \"deny by rule<%s>\", rule->arg1().c_str());\n                }\n                break;\n            case SrsRtmpConnUnknown:\n            default:\n                break;\n        }\n    }\n    \n    return srs_success; \/\/ OK\n}\n\n","avg_line_length":31.746835443,"max_line_length":120,"alphanum_fraction":0.5751594896,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1997,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":2.0,"content":"#include \"MatrixTests.hpp\"\n\nstatic Matrix\n\tempty(0),\n\tsome(make_mat({\n\t\t{ -5 , -5, 0 , 11 , 15 },\n\t\t{ -4 , -2, 15, -13, 13 },\n\t\t{ -10, -2, 14, -12, 1  },\n\t\t{ -1 , 12, 12, -3 , -7 },\n\t})),\n\tlongmatrix(make_mat({\n\t\t{13, -15, -7 , 9  , 13, -1, 1, -13},\n\t\t{-9, 2  , 4  , -11, 3 , -1, 5, -13},\n\t\t{-5, 9  , -14, -2 , 5 , -2, 7, -3 },\n\t\t{1 , 3  , -7 , 8  , 11, -1, 4, 14 },\n\t}));\n\nTEST_F(MatrixTest, MatrixUnaryOperatorsTest) {\n\tASSERT_EQ(empty, +empty);\n\tASSERT_EQ(empty, -empty);\n\tASSERT_EQ(some, +some);\n\tASSERT_TRUE(cmp_matr_double(\n\t\t-some,\n\t\tmake_mat({\n\t\t\t{  +5, +5,  0, -11,-15 },\n\t\t\t{  +4, +2,-15, +13,-13 },\n\t\t\t{ +10, +2,-14, +12, -1 },\n\t\t\t{  +1,-12,-12, + 3, +7 },\n\t\t})\n\t));\n}\n\nTEST_F(MatrixTest, MatrixScalarOperatorsTest) {\n\tASSERT_EQ(empty, empty + 1.);\n\tASSERT_EQ(empty, empty - 1.);\n\tASSERT_EQ(empty, empty * 1.);\n\tASSERT_EQ(empty, empty \/ 1.);\n\tASSERT_ANY_THROW(empty \/ 0.);\n\n\tASSERT_ANY_THROW(some \/ 0.);\n\tASSERT_TRUE(cmp_matr_double(\n\t\t\tsome + 10., make_mat({\n\t\t\t{  5 ,  5, 10, 21 , 25 },\n\t\t\t{  6 ,  8, 25,  -3, 23 },\n\t\t\t{  0 ,  8, 24,  -2, 11 },\n\t\t\t{  9 , 22, 22,  7 , 3  },\n\t})));\n\tASSERT_TRUE(cmp_matr_double(\n\t\t\tsome - 10., make_mat({\n\t\t\t{ -15,-15,-10,   1,  5 },\n\t\t\t{ -14,-12,  5, -23,  3 },\n\t\t\t{ -20,-12,  4, -22, -9 },\n\t\t\t{ -11,  2,  2, -13,-17 },\n\t})));\n\tASSERT_TRUE(cmp_matr_double(\n\t\t\tsome * 0.,\n\t\t\tMatrix(some.Width(), some.Height(), 0)\n\t));\n\tASSERT_TRUE(cmp_matr_double(\n\t\t\tsome * 1.,\n\t\t\tsome\n\t));\n\tASSERT_TRUE(cmp_matr_double(\n\t\t\tsome \/ 1.,\n\t\t\tsome\n\t));\n\tASSERT_TRUE(cmp_matr_double(\n\t\t\tsome \/ 0.5, make_mat({\n\t\t\t{ -10,-10, 0 , 22 , 30 },\n\t\t\t{ -8 , -4, 30, -26, 26 },\n\t\t\t{ -20, -4, 28, -24, 2  },\n\t\t\t{ -2 , 24, 24, -6 , -14},\n\t})));\n}\n\nTEST_F(MatrixTest, MatrixCalculusTest) {\n\tASSERT_EQ(empty + empty, empty);\n\tASSERT_EQ(empty - empty, empty);\n\n\tASSERT_ANY_THROW(some + longmatrix);\n\tASSERT_ANY_THROW(some - longmatrix);\n\n\tASSERT_TRUE(cmp_matr_double(\n\t\t\tsome * 2.,\n\t\t\tsome + some\n\t));\n\tASSERT_TRUE(cmp_matr_double(\n\t\t\tlongmatrix * -2.,\n\t\t\t-longmatrix - longmatrix\n\t));\n}\n","avg_line_length":21.7065217391,"max_line_length":47,"alphanum_fraction":0.5237856785,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":62923,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0","BSD-3-Clause-No-Nuclear-License-2014","BSD-3-Clause"],"max_stars_count":777.0,"content":"\/*\n * Copyright (C) 2006, 2007, 2008, 2011 Apple Inc. All rights reserved.\n * Copyright (C) 2008 Nokia Corporation and\/or its subsidiary(-ies)\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"core\/editing\/Editor.h\"\n\n#include \"bindings\/core\/v8\/ExceptionState.h\"\n#include \"core\/CSSPropertyNames.h\"\n#include \"core\/EventNames.h\"\n#include \"core\/HTMLNames.h\"\n#include \"core\/clipboard\/DataObject.h\"\n#include \"core\/clipboard\/DataTransfer.h\"\n#include \"core\/clipboard\/Pasteboard.h\"\n#include \"core\/css\/CSSComputedStyleDeclaration.h\"\n#include \"core\/css\/StylePropertySet.h\"\n#include \"core\/dom\/AXObjectCache.h\"\n#include \"core\/dom\/DocumentFragment.h\"\n#include \"core\/dom\/ElementTraversal.h\"\n#include \"core\/dom\/NodeTraversal.h\"\n#include \"core\/dom\/ParserContentPolicy.h\"\n#include \"core\/dom\/Text.h\"\n#include \"core\/editing\/EditingUtilities.h\"\n#include \"core\/editing\/InputMethodController.h\"\n#include \"core\/editing\/RenderedPosition.h\"\n#include \"core\/editing\/VisibleUnits.h\"\n#include \"core\/editing\/commands\/ApplyStyleCommand.h\"\n#include \"core\/editing\/commands\/DeleteSelectionCommand.h\"\n#include \"core\/editing\/commands\/IndentOutdentCommand.h\"\n#include \"core\/editing\/commands\/InsertListCommand.h\"\n#include \"core\/editing\/commands\/RemoveFormatCommand.h\"\n#include \"core\/editing\/commands\/ReplaceSelectionCommand.h\"\n#include \"core\/editing\/commands\/SimplifyMarkupCommand.h\"\n#include \"core\/editing\/commands\/TypingCommand.h\"\n#include \"core\/editing\/commands\/UndoStack.h\"\n#include \"core\/editing\/iterators\/SearchBuffer.h\"\n#include \"core\/editing\/markers\/DocumentMarkerController.h\"\n#include \"core\/editing\/serializers\/Serialization.h\"\n#include \"core\/editing\/spellcheck\/SpellChecker.h\"\n#include \"core\/events\/ClipboardEvent.h\"\n#include \"core\/events\/KeyboardEvent.h\"\n#include \"core\/events\/ScopedEventQueue.h\"\n#include \"core\/events\/TextEvent.h\"\n#include \"core\/fetch\/ResourceFetcher.h\"\n#include \"core\/frame\/FrameView.h\"\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/frame\/Settings.h\"\n#include \"core\/frame\/UseCounter.h\"\n#include \"core\/html\/HTMLBodyElement.h\"\n#include \"core\/html\/HTMLCanvasElement.h\"\n#include \"core\/html\/HTMLHtmlElement.h\"\n#include \"core\/html\/HTMLImageElement.h\"\n#include \"core\/html\/HTMLInputElement.h\"\n#include \"core\/html\/HTMLTextAreaElement.h\"\n#include \"core\/html\/parser\/HTMLParserIdioms.h\"\n#include \"core\/input\/EventHandler.h\"\n#include \"core\/inspector\/ConsoleMessage.h\"\n#include \"core\/layout\/HitTestResult.h\"\n#include \"core\/layout\/LayoutImage.h\"\n#include \"core\/loader\/EmptyClients.h\"\n#include \"core\/loader\/resource\/ImageResourceContent.h\"\n#include \"core\/page\/DragData.h\"\n#include \"core\/page\/EditorClient.h\"\n#include \"core\/page\/FocusController.h\"\n#include \"core\/page\/Page.h\"\n#include \"core\/svg\/SVGImageElement.h\"\n#include \"platform\/KillRing.h\"\n#include \"platform\/weborigin\/KURL.h\"\n#include \"wtf\/PtrUtil.h\"\n#include \"wtf\/text\/CharacterNames.h\"\n\nnamespace blink {\n\nusing namespace HTMLNames;\nusing namespace WTF;\nusing namespace Unicode;\n\nnamespace {\n\nvoid dispatchInputEvent(Element* target,\n                        InputEvent::InputType inputType,\n                        const String& data,\n                        InputEvent::EventIsComposing isComposing) {\n  if (!RuntimeEnabledFeatures::inputEventEnabled())\n    return;\n  if (!target)\n    return;\n  \/\/ TODO(chongz): Pass appreciate |ranges| after it's defined on spec.\n  \/\/ http:\/\/w3c.github.io\/editing\/input-events.html#dom-inputevent-inputtype\n  InputEvent* inputEvent =\n      InputEvent::createInput(inputType, data, isComposing, nullptr);\n  target->dispatchScopedEvent(inputEvent);\n}\n\nvoid dispatchInputEventEditableContentChanged(\n    Element* startRoot,\n    Element* endRoot,\n    InputEvent::InputType inputType,\n    const String& data,\n    InputEvent::EventIsComposing isComposing) {\n  if (startRoot)\n    dispatchInputEvent(startRoot, inputType, data, isComposing);\n  if (endRoot && endRoot != startRoot)\n    dispatchInputEvent(endRoot, inputType, data, isComposing);\n}\n\nInputEvent::EventIsComposing isComposingFromCommand(\n    const CompositeEditCommand* command) {\n  if (command->isTypingCommand() &&\n      toTypingCommand(command)->compositionType() !=\n          TypingCommand::TextCompositionNone)\n    return InputEvent::EventIsComposing::IsComposing;\n  return InputEvent::EventIsComposing::NotComposing;\n}\n\n}  \/\/ anonymous namespace\n\nEditor::RevealSelectionScope::RevealSelectionScope(Editor* editor)\n    : m_editor(editor) {\n  ++m_editor->m_preventRevealSelection;\n}\n\nEditor::RevealSelectionScope::~RevealSelectionScope() {\n  DCHECK(m_editor->m_preventRevealSelection);\n  --m_editor->m_preventRevealSelection;\n  if (!m_editor->m_preventRevealSelection) {\n    m_editor->frame().selection().revealSelection(\n        ScrollAlignment::alignToEdgeIfNeeded, RevealExtent);\n  }\n}\n\n\/\/ When an event handler has moved the selection outside of a text control\n\/\/ we should use the target control's selection for this editing operation.\n\/\/ TODO(yosin): We should make |Editor::selectionForCommand()| to return\n\/\/ |SelectionInDOMTree| instead of |VisibleSelection|.\nVisibleSelection Editor::selectionForCommand(Event* event) {\n  frame().selection().updateIfNeeded();\n  VisibleSelection selection = frame().selection().selection();\n  if (!event)\n    return selection;\n  \/\/ If the target is a text control, and the current selection is outside of\n  \/\/ its shadow tree, then use the saved selection for that text control.\n  TextControlElement* textControlOfSelectionStart =\n      enclosingTextControl(selection.start());\n  TextControlElement* textControlOfTarget =\n      isTextControlElement(*event->target()->toNode())\n          ? toTextControlElement(event->target()->toNode())\n          : nullptr;\n  if (textControlOfTarget &&\n      (selection.start().isNull() ||\n       textControlOfTarget != textControlOfSelectionStart)) {\n    if (Range* range = textControlOfTarget->selection()) {\n      return createVisibleSelection(\n          SelectionInDOMTree::Builder()\n              .setBaseAndExtent(EphemeralRange(range))\n              .setIsDirectional(selection.isDirectional())\n              .build());\n    }\n  }\n  return selection;\n}\n\n\/\/ Function considers Mac editing behavior a fallback when Page or Settings is\n\/\/ not available.\nEditingBehavior Editor::behavior() const {\n  if (!frame().settings())\n    return EditingBehavior(EditingMacBehavior);\n\n  return EditingBehavior(frame().settings()->getEditingBehaviorType());\n}\n\nstatic EditorClient& emptyEditorClient() {\n  DEFINE_STATIC_LOCAL(EmptyEditorClient, client, ());\n  return client;\n}\n\nEditorClient& Editor::client() const {\n  if (Page* page = frame().page())\n    return page->editorClient();\n  return emptyEditorClient();\n}\n\nstatic bool isCaretAtStartOfWrappedLine(const FrameSelection& selection) {\n  if (!selection.isCaret())\n    return false;\n  if (selection.affinity() != TextAffinity::Downstream)\n    return false;\n  const Position& position = selection.start();\n  return !inSameLine(PositionWithAffinity(position, TextAffinity::Upstream),\n                     PositionWithAffinity(position, TextAffinity::Downstream));\n}\n\nbool Editor::handleTextEvent(TextEvent* event) {\n  \/\/ Default event handling for Drag and Drop will be handled by DragController\n  \/\/ so we leave the event for it.\n  if (event->isDrop())\n    return false;\n\n  \/\/ Default event handling for IncrementalInsertion will be handled by\n  \/\/ TypingCommand::insertText(), so we leave the event for it.\n  if (event->isIncrementalInsertion())\n    return false;\n\n  \/\/ TODO(xiaochengh): The use of updateStyleAndLayoutIgnorePendingStylesheets\n  \/\/ needs to be audited.  See http:\/\/crbug.com\/590369 for more details.\n  m_frame->document()->updateStyleAndLayoutIgnorePendingStylesheets();\n\n  if (event->isPaste()) {\n    if (event->pastingFragment()) {\n      replaceSelectionWithFragment(\n          event->pastingFragment(), false, event->shouldSmartReplace(),\n          event->shouldMatchStyle(), InputEvent::InputType::InsertFromPaste);\n    } else {\n      replaceSelectionWithText(event->data(), false,\n                               event->shouldSmartReplace(),\n                               InputEvent::InputType::InsertFromPaste);\n    }\n    return true;\n  }\n\n  String data = event->data();\n  if (data == \"\\n\") {\n    if (event->isLineBreak())\n      return insertLineBreak();\n    return insertParagraphSeparator();\n  }\n\n  \/\/ Typing spaces at the beginning of wrapped line is confusing, because\n  \/\/ inserted spaces would appear in the previous line.\n  \/\/ Insert a line break automatically so that the spaces appear at the caret.\n  \/\/ TODO(kojii): rich editing has the same issue, but has more options and\n  \/\/ needs coordination with JS. Enable for plaintext only for now and collect\n  \/\/ feedback.\n  if (data == \" \" && !canEditRichly() &&\n      isCaretAtStartOfWrappedLine(frame().selection())) {\n    insertLineBreak();\n  }\n\n  return insertTextWithoutSendingTextEvent(data, false, event);\n}\n\nbool Editor::canEdit() const {\n  return frame().selection().rootEditableElement();\n}\n\nbool Editor::canEditRichly() const {\n  return frame().selection().isContentRichlyEditable();\n}\n\n\/\/ WinIE uses onbeforecut and onbeforepaste to enables the cut and paste menu\n\/\/ items. They also send onbeforecopy, apparently for symmetry, but it doesn't\n\/\/ affect the menu items. We need to use onbeforecopy as a real menu enabler\n\/\/ because we allow elements that are not normally selectable to implement\n\/\/ copy\/paste (like divs, or a document body).\n\nbool Editor::canDHTMLCut() {\n  return !frame().selection().isInPasswordField() &&\n         !dispatchCPPEvent(EventTypeNames::beforecut, DataTransferNumb);\n}\n\nbool Editor::canDHTMLCopy() {\n  return !frame().selection().isInPasswordField() &&\n         !dispatchCPPEvent(EventTypeNames::beforecopy, DataTransferNumb);\n}\n\nbool Editor::canCut() const {\n  return canCopy() && canDelete();\n}\n\nstatic HTMLImageElement* imageElementFromImageDocument(Document* document) {\n  if (!document)\n    return 0;\n  if (!document->isImageDocument())\n    return 0;\n\n  HTMLElement* body = document->body();\n  if (!body)\n    return 0;\n\n  Node* node = body->firstChild();\n  if (!isHTMLImageElement(node))\n    return 0;\n  return toHTMLImageElement(node);\n}\n\nbool Editor::canCopy() const {\n  if (imageElementFromImageDocument(frame().document()))\n    return true;\n  FrameSelection& selection = frame().selection();\n  return selection.isRange() && !selection.isInPasswordField();\n}\n\nbool Editor::canPaste() const {\n  return canEdit();\n}\n\nbool Editor::canDelete() const {\n  FrameSelection& selection = frame().selection();\n  return selection.isRange() && selection.rootEditableElement();\n}\n\nbool Editor::smartInsertDeleteEnabled() const {\n  if (Settings* settings = frame().settings())\n    return settings->getSmartInsertDeleteEnabled();\n  return false;\n}\n\nbool Editor::canSmartCopyOrDelete() const {\n  return smartInsertDeleteEnabled() &&\n         frame().selection().granularity() == WordGranularity;\n}\n\nbool Editor::isSelectTrailingWhitespaceEnabled() const {\n  if (Settings* settings = frame().settings())\n    return settings->getSelectTrailingWhitespaceEnabled();\n  return false;\n}\n\nbool Editor::deleteWithDirection(DeleteDirection direction,\n                                 TextGranularity granularity,\n                                 bool killRing,\n                                 bool isTypingAction) {\n  if (!canEdit())\n    return false;\n\n  EditingState editingState;\n  if (frame().selection().isRange()) {\n    if (isTypingAction) {\n      DCHECK(frame().document());\n      TypingCommand::deleteKeyPressed(\n          *frame().document(),\n          canSmartCopyOrDelete() ? TypingCommand::SmartDelete : 0, granularity);\n      revealSelectionAfterEditingOperation();\n    } else {\n      if (killRing)\n        addToKillRing(selectedRange());\n      deleteSelectionWithSmartDelete(\n          canSmartCopyOrDelete() ? DeleteMode::Smart : DeleteMode::Simple,\n          deletionInputTypeFromTextGranularity(direction, granularity));\n      \/\/ Implicitly calls revealSelectionAfterEditingOperation().\n    }\n  } else {\n    TypingCommand::Options options = 0;\n    if (canSmartCopyOrDelete())\n      options |= TypingCommand::SmartDelete;\n    if (killRing)\n      options |= TypingCommand::KillRing;\n    switch (direction) {\n      case DeleteDirection::Forward:\n        DCHECK(frame().document());\n        TypingCommand::forwardDeleteKeyPressed(\n            *frame().document(), &editingState, options, granularity);\n        if (editingState.isAborted())\n          return false;\n        break;\n      case DeleteDirection::Backward:\n        DCHECK(frame().document());\n        TypingCommand::deleteKeyPressed(*frame().document(), options,\n                                        granularity);\n        break;\n    }\n    revealSelectionAfterEditingOperation();\n  }\n\n  \/\/ FIXME: We should to move this down into deleteKeyPressed.\n  \/\/ clear the \"start new kill ring sequence\" setting, because it was set to\n  \/\/ true when the selection was updated by deleting the range\n  if (killRing)\n    setStartNewKillRingSequence(false);\n\n  return true;\n}\n\nvoid Editor::deleteSelectionWithSmartDelete(\n    DeleteMode deleteMode,\n    InputEvent::InputType inputType,\n    const Position& referenceMovePosition) {\n  if (frame().selection().isNone())\n    return;\n\n  const bool kMergeBlocksAfterDelete = true;\n  const bool kExpandForSpecialElements = false;\n  const bool kSanitizeMarkup = true;\n  DCHECK(frame().document());\n  DeleteSelectionCommand::create(\n      *frame().document(), deleteMode == DeleteMode::Smart,\n      kMergeBlocksAfterDelete, kExpandForSpecialElements, kSanitizeMarkup,\n      inputType, referenceMovePosition)\n      ->apply();\n}\n\nvoid Editor::pasteAsPlainText(const String& pastingText, bool smartReplace) {\n  Element* target = findEventTargetFromSelection();\n  if (!target)\n    return;\n  target->dispatchEvent(TextEvent::createForPlainTextPaste(\n      frame().domWindow(), pastingText, smartReplace));\n}\n\nvoid Editor::pasteAsFragment(DocumentFragment* pastingFragment,\n                             bool smartReplace,\n                             bool matchStyle) {\n  Element* target = findEventTargetFromSelection();\n  if (!target)\n    return;\n  target->dispatchEvent(TextEvent::createForFragmentPaste(\n      frame().domWindow(), pastingFragment, smartReplace, matchStyle));\n}\n\nbool Editor::tryDHTMLCopy() {\n  if (frame().selection().isInPasswordField())\n    return false;\n\n  return !dispatchCPPEvent(EventTypeNames::copy, DataTransferWritable);\n}\n\nbool Editor::tryDHTMLCut() {\n  if (frame().selection().isInPasswordField())\n    return false;\n\n  return !dispatchCPPEvent(EventTypeNames::cut, DataTransferWritable);\n}\n\nbool Editor::tryDHTMLPaste(PasteMode pasteMode) {\n  return !dispatchCPPEvent(EventTypeNames::paste, DataTransferReadable,\n                           pasteMode);\n}\n\nvoid Editor::pasteAsPlainTextWithPasteboard(Pasteboard* pasteboard) {\n  String text = pasteboard->plainText();\n  pasteAsPlainText(text, canSmartReplaceWithPasteboard(pasteboard));\n}\n\nvoid Editor::pasteWithPasteboard(Pasteboard* pasteboard) {\n  DocumentFragment* fragment = nullptr;\n  bool chosePlainText = false;\n\n  if (pasteboard->isHTMLAvailable()) {\n    unsigned fragmentStart = 0;\n    unsigned fragmentEnd = 0;\n    KURL url;\n    String markup = pasteboard->readHTML(url, fragmentStart, fragmentEnd);\n    if (!markup.isEmpty()) {\n      DCHECK(frame().document());\n      fragment = createFragmentFromMarkupWithContext(\n          *frame().document(), markup, fragmentStart, fragmentEnd, url,\n          DisallowScriptingAndPluginContent);\n    }\n  }\n\n  if (!fragment) {\n    String text = pasteboard->plainText();\n    if (!text.isEmpty()) {\n      chosePlainText = true;\n\n      \/\/ TODO(xiaochengh): Use of updateStyleAndLayoutIgnorePendingStylesheets\n      \/\/ needs to be audited.  See http:\/\/crbug.com\/590369 for more details.\n      \/\/ |selectedRange| requires clean layout for visible selection\n      \/\/ normalization.\n      frame().document()->updateStyleAndLayoutIgnorePendingStylesheets();\n\n      fragment = createFragmentFromText(selectedRange(), text);\n    }\n  }\n\n  if (fragment)\n    pasteAsFragment(fragment, canSmartReplaceWithPasteboard(pasteboard),\n                    chosePlainText);\n}\n\nvoid Editor::writeSelectionToPasteboard() {\n  KURL url = frame().document()->url();\n  String html = frame().selection().selectedHTMLForClipboard();\n  String plainText = frame().selectedTextForClipboard();\n  Pasteboard::generalPasteboard()->writeHTML(html, url, plainText,\n                                             canSmartCopyOrDelete());\n}\n\nstatic PassRefPtr<Image> imageFromNode(const Node& node) {\n  DCHECK(!node.document().needsLayoutTreeUpdate());\n  DocumentLifecycle::DisallowTransitionScope disallowTransition(\n      node.document().lifecycle());\n\n  LayoutObject* layoutObject = node.layoutObject();\n  if (!layoutObject)\n    return nullptr;\n\n  if (layoutObject->isCanvas()) {\n    return toHTMLCanvasElement(node).copiedImage(\n        FrontBuffer, PreferNoAcceleration, SnapshotReasonCopyToClipboard);\n  }\n\n  if (layoutObject->isImage()) {\n    LayoutImage* layoutImage = toLayoutImage(layoutObject);\n    if (!layoutImage)\n      return nullptr;\n\n    ImageResourceContent* cachedImage = layoutImage->cachedImage();\n    if (!cachedImage || cachedImage->errorOccurred())\n      return nullptr;\n    return cachedImage->getImage();\n  }\n\n  return nullptr;\n}\n\nstatic void writeImageNodeToPasteboard(Pasteboard* pasteboard,\n                                       Node* node,\n                                       const String& title) {\n  DCHECK(pasteboard);\n  DCHECK(node);\n\n  RefPtr<Image> image = imageFromNode(*node);\n  if (!image.get())\n    return;\n\n  \/\/ FIXME: This should probably be reconciled with\n  \/\/ HitTestResult::absoluteImageURL.\n  AtomicString urlString;\n  if (isHTMLImageElement(*node) || isHTMLInputElement(*node))\n    urlString = toHTMLElement(node)->getAttribute(srcAttr);\n  else if (isSVGImageElement(*node))\n    urlString = toSVGElement(node)->imageSourceURL();\n  else if (isHTMLEmbedElement(*node) || isHTMLObjectElement(*node) ||\n           isHTMLCanvasElement(*node))\n    urlString = toHTMLElement(node)->imageSourceURL();\n  KURL url = urlString.isEmpty()\n                 ? KURL()\n                 : node->document().completeURL(\n                       stripLeadingAndTrailingHTMLSpaces(urlString));\n\n  pasteboard->writeImage(image.get(), url, title);\n}\n\n\/\/ Returns whether caller should continue with \"the default processing\", which\n\/\/ is the same as the event handler NOT setting the return value to false\nbool Editor::dispatchCPPEvent(const AtomicString& eventType,\n                              DataTransferAccessPolicy policy,\n                              PasteMode pasteMode) {\n  Element* target = findEventTargetFromSelection();\n  if (!target)\n    return true;\n\n  DataTransfer* dataTransfer =\n      DataTransfer::create(DataTransfer::CopyAndPaste, policy,\n                           policy == DataTransferWritable\n                               ? DataObject::create()\n                               : DataObject::createFromPasteboard(pasteMode));\n\n  Event* evt = ClipboardEvent::create(eventType, true, true, dataTransfer);\n  target->dispatchEvent(evt);\n  bool noDefaultProcessing = evt->defaultPrevented();\n  if (noDefaultProcessing && policy == DataTransferWritable)\n    Pasteboard::generalPasteboard()->writeDataObject(\n        dataTransfer->dataObject());\n\n  \/\/ invalidate clipboard here for security\n  dataTransfer->setAccessPolicy(DataTransferNumb);\n\n  return !noDefaultProcessing;\n}\n\nbool Editor::canSmartReplaceWithPasteboard(Pasteboard* pasteboard) {\n  return smartInsertDeleteEnabled() && pasteboard->canSmartReplace();\n}\n\nvoid Editor::replaceSelectionWithFragment(DocumentFragment* fragment,\n                                          bool selectReplacement,\n                                          bool smartReplace,\n                                          bool matchStyle,\n                                          InputEvent::InputType inputType) {\n  DCHECK(!frame().document()->needsLayoutTreeUpdate());\n  if (frame().selection().isNone() ||\n      !frame().selection().isContentEditable() || !fragment)\n    return;\n\n  ReplaceSelectionCommand::CommandOptions options =\n      ReplaceSelectionCommand::PreventNesting |\n      ReplaceSelectionCommand::SanitizeFragment;\n  if (selectReplacement)\n    options |= ReplaceSelectionCommand::SelectReplacement;\n  if (smartReplace)\n    options |= ReplaceSelectionCommand::SmartReplace;\n  if (matchStyle)\n    options |= ReplaceSelectionCommand::MatchStyle;\n  DCHECK(frame().document());\n  ReplaceSelectionCommand::create(*frame().document(), fragment, options,\n                                  inputType)\n      ->apply();\n  revealSelectionAfterEditingOperation();\n}\n\nvoid Editor::replaceSelectionWithText(const String& text,\n                                      bool selectReplacement,\n                                      bool smartReplace,\n                                      InputEvent::InputType inputType) {\n  replaceSelectionWithFragment(createFragmentFromText(selectedRange(), text),\n                               selectReplacement, smartReplace, true,\n                               inputType);\n}\n\n\/\/ TODO(xiaochengh): Merge it with |replaceSelectionWithFragment()|.\nvoid Editor::replaceSelectionAfterDragging(DocumentFragment* fragment,\n                                           InsertMode insertMode,\n                                           DragSourceType dragSourceType) {\n  ReplaceSelectionCommand::CommandOptions options =\n      ReplaceSelectionCommand::SelectReplacement |\n      ReplaceSelectionCommand::PreventNesting;\n  if (insertMode == InsertMode::Smart)\n    options |= ReplaceSelectionCommand::SmartReplace;\n  if (dragSourceType == DragSourceType::PlainTextSource)\n    options |= ReplaceSelectionCommand::MatchStyle;\n  DCHECK(frame().document());\n  ReplaceSelectionCommand::create(*frame().document(), fragment, options,\n                                  InputEvent::InputType::InsertFromDrop)\n      ->apply();\n}\n\nbool Editor::deleteSelectionAfterDraggingWithEvents(\n    Element* dragSource,\n    DeleteMode deleteMode,\n    const Position& referenceMovePosition) {\n  if (!dragSource || !dragSource->isConnected())\n    return true;\n\n  \/\/ Dispatch 'beforeinput'.\n  const bool shouldDelete = dispatchBeforeInputEditorCommand(\n                                dragSource, InputEvent::InputType::DeleteByDrag,\n                                nullptr) == DispatchEventResult::NotCanceled;\n\n  \/\/ 'beforeinput' event handler may destroy frame, return false to cancel\n  \/\/ remaining actions;\n  if (m_frame->document()->frame() != m_frame)\n    return false;\n\n  if (shouldDelete && dragSource->isConnected()) {\n    deleteSelectionWithSmartDelete(\n        deleteMode, InputEvent::InputType::DeleteByDrag, referenceMovePosition);\n  }\n\n  return true;\n}\n\nbool Editor::replaceSelectionAfterDraggingWithEvents(\n    Element* dropTarget,\n    DragData* dragData,\n    DocumentFragment* fragment,\n    Range* dropCaretRange,\n    InsertMode insertMode,\n    DragSourceType dragSourceType) {\n  if (!dropTarget || !dropTarget->isConnected())\n    return true;\n\n  \/\/ Dispatch 'beforeinput'.\n  DataTransfer* dataTransfer =\n      DataTransfer::create(DataTransfer::DragAndDrop, DataTransferReadable,\n                           dragData->platformData());\n  dataTransfer->setSourceOperation(dragData->draggingSourceOperationMask());\n  const bool shouldInsert =\n      dispatchBeforeInputDataTransfer(\n          dropTarget, InputEvent::InputType::InsertFromDrop, dataTransfer,\n          nullptr) == DispatchEventResult::NotCanceled;\n\n  \/\/ 'beforeinput' event handler may destroy frame, return false to cancel\n  \/\/ remaining actions;\n  if (m_frame->document()->frame() != m_frame)\n    return false;\n\n  if (shouldInsert && dropTarget->isConnected())\n    replaceSelectionAfterDragging(fragment, insertMode, dragSourceType);\n\n  return true;\n}\n\nEphemeralRange Editor::selectedRange() {\n  return frame().selection().selection().toNormalizedEphemeralRange();\n}\n\nbool Editor::canDeleteRange(const EphemeralRange& range) const {\n  if (range.isCollapsed())\n    return false;\n\n  Node* startContainer = range.startPosition().computeContainerNode();\n  Node* endContainer = range.endPosition().computeContainerNode();\n  if (!startContainer || !endContainer)\n    return false;\n\n  return hasEditableStyle(*startContainer) && hasEditableStyle(*endContainer);\n}\n\nvoid Editor::respondToChangedContents(const VisibleSelection& endingSelection) {\n  if (frame().settings() && frame().settings()->getAccessibilityEnabled()) {\n    Node* node = endingSelection.start().anchorNode();\n    if (AXObjectCache* cache = frame().document()->existingAXObjectCache())\n      cache->handleEditableTextContentChanged(node);\n  }\n\n  spellChecker().updateMarkersForWordsAffectedByEditing(true);\n  client().respondToChangedContents();\n}\n\nvoid Editor::removeFormattingAndStyle() {\n  DCHECK(frame().document());\n  RemoveFormatCommand::create(*frame().document())->apply();\n}\n\nvoid Editor::registerCommandGroup(CompositeEditCommand* commandGroupWrapper) {\n  DCHECK(commandGroupWrapper->isCommandGroupWrapper());\n  m_lastEditCommand = commandGroupWrapper;\n}\n\nvoid Editor::clearLastEditCommand() {\n  m_lastEditCommand.clear();\n}\n\nElement* Editor::findEventTargetFrom(const VisibleSelection& selection) const {\n  Element* target = associatedElementOf(selection.start());\n  if (!target)\n    target = frame().document()->body();\n\n  return target;\n}\n\nElement* Editor::findEventTargetFromSelection() const {\n  return findEventTargetFrom(frame().selection().selection());\n}\n\nvoid Editor::applyStyle(StylePropertySet* style,\n                        InputEvent::InputType inputType) {\n  switch (frame().selection().getSelectionType()) {\n    case NoSelection:\n      \/\/ do nothing\n      break;\n    case CaretSelection:\n      computeAndSetTypingStyle(style, inputType);\n      break;\n    case RangeSelection:\n      if (style) {\n        DCHECK(frame().document());\n        ApplyStyleCommand::create(*frame().document(),\n                                  EditingStyle::create(style), inputType)\n            ->apply();\n      }\n      break;\n  }\n}\n\nvoid Editor::applyParagraphStyle(StylePropertySet* style,\n                                 InputEvent::InputType inputType) {\n  if (frame().selection().isNone() || !style)\n    return;\n  DCHECK(frame().document());\n  ApplyStyleCommand::create(*frame().document(), EditingStyle::create(style),\n                            inputType, ApplyStyleCommand::ForceBlockProperties)\n      ->apply();\n}\n\nvoid Editor::applyStyleToSelection(StylePropertySet* style,\n                                   InputEvent::InputType inputType) {\n  if (!style || style->isEmpty() || !canEditRichly())\n    return;\n\n  applyStyle(style, inputType);\n}\n\nvoid Editor::applyParagraphStyleToSelection(StylePropertySet* style,\n                                            InputEvent::InputType inputType) {\n  if (!style || style->isEmpty() || !canEditRichly())\n    return;\n\n  applyParagraphStyle(style, inputType);\n}\n\nbool Editor::selectionStartHasStyle(CSSPropertyID propertyID,\n                                    const String& value) const {\n  EditingStyle* styleToCheck = EditingStyle::create(propertyID, value);\n  EditingStyle* styleAtStart = EditingStyle::styleAtSelectionStart(\n      frame().selection().selection(), propertyID == CSSPropertyBackgroundColor,\n      styleToCheck->style());\n  return styleToCheck->triStateOfStyle(styleAtStart);\n}\n\nTriState Editor::selectionHasStyle(CSSPropertyID propertyID,\n                                   const String& value) const {\n  return EditingStyle::create(propertyID, value)\n      ->triStateOfStyle(frame().selection().selection());\n}\n\nString Editor::selectionStartCSSPropertyValue(CSSPropertyID propertyID) {\n  EditingStyle* selectionStyle = EditingStyle::styleAtSelectionStart(\n      frame().selection().selection(),\n      propertyID == CSSPropertyBackgroundColor);\n  if (!selectionStyle || !selectionStyle->style())\n    return String();\n\n  if (propertyID == CSSPropertyFontSize)\n    return String::number(selectionStyle->legacyFontSize(frame().document()));\n  return selectionStyle->style()->getPropertyValue(propertyID);\n}\n\nstatic void dispatchEditableContentChangedEvents(Element* startRoot,\n                                                 Element* endRoot) {\n  if (startRoot)\n    startRoot->dispatchEvent(\n        Event::create(EventTypeNames::webkitEditableContentChanged));\n  if (endRoot && endRoot != startRoot)\n    endRoot->dispatchEvent(\n        Event::create(EventTypeNames::webkitEditableContentChanged));\n}\n\nvoid Editor::appliedEditing(CompositeEditCommand* cmd) {\n  DCHECK(!cmd->isCommandGroupWrapper());\n  EventQueueScope scope;\n\n  \/\/ Request spell checking before any further DOM change.\n  spellChecker().markMisspellingsAfterApplyingCommand(*cmd);\n\n  UndoStep* undoStep = cmd->undoStep();\n  DCHECK(undoStep);\n  dispatchEditableContentChangedEvents(undoStep->startingRootEditableElement(),\n                                       undoStep->endingRootEditableElement());\n  \/\/ TODO(chongz): Filter empty InputType after spec is finalized.\n  dispatchInputEventEditableContentChanged(\n      undoStep->startingRootEditableElement(),\n      undoStep->endingRootEditableElement(), cmd->inputType(),\n      cmd->textDataForInputEvent(), isComposingFromCommand(cmd));\n\n  \/\/ TODO(editing-dev): The use of updateStyleAndLayoutIgnorePendingStylesheets\n  \/\/ needs to be audited.  See http:\/\/crbug.com\/590369 for more details.\n  \/\/ The clean layout is consumed by |mostBackwardCaretPosition|, called through\n  \/\/ |changeSelectionAfterCommand|. In the long term, we should postpone visible\n  \/\/ selection canonicalization so that selection update does not need layout.\n  frame().document()->updateStyleAndLayoutIgnorePendingStylesheets();\n\n  VisibleSelection newSelection(cmd->endingSelection());\n\n  \/\/ Don't clear the typing style with this selection change. We do those things\n  \/\/ elsewhere if necessary.\n  changeSelectionAfterCommand(newSelection, 0);\n\n  if (!cmd->preservesTypingStyle())\n    frame().selection().clearTypingStyle();\n\n  \/\/ Command will be equal to last edit command only in the case of typing\n  if (m_lastEditCommand.get() == cmd) {\n    DCHECK(cmd->isTypingCommand());\n  } else if (m_lastEditCommand && m_lastEditCommand->isDragAndDropCommand() &&\n             (cmd->inputType() == InputEvent::InputType::DeleteByDrag ||\n              cmd->inputType() == InputEvent::InputType::InsertFromDrop)) {\n    \/\/ Only register undo entry when combined with other commands.\n    if (!m_lastEditCommand->undoStep())\n      m_undoStack->registerUndoStep(m_lastEditCommand->ensureUndoStep());\n    m_lastEditCommand->appendCommandToUndoStep(cmd);\n  } else {\n    \/\/ Only register a new undo command if the command passed in is\n    \/\/ different from the last command\n    m_lastEditCommand = cmd;\n    m_undoStack->registerUndoStep(m_lastEditCommand->ensureUndoStep());\n  }\n\n  respondToChangedContents(newSelection);\n}\n\nstatic VisibleSelection correctedVisibleSelection(\n    const VisibleSelection& passedSelection) {\n  if (!passedSelection.base().isConnected() ||\n      !passedSelection.extent().isConnected())\n    return VisibleSelection();\n  DCHECK(!passedSelection.base().document()->needsLayoutTreeUpdate());\n  VisibleSelection correctedSelection = passedSelection;\n  correctedSelection.updateIfNeeded();\n  return correctedSelection;\n}\n\nvoid Editor::unappliedEditing(UndoStep* cmd) {\n  EventQueueScope scope;\n\n  dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(),\n                                       cmd->endingRootEditableElement());\n  dispatchInputEventEditableContentChanged(\n      cmd->startingRootEditableElement(), cmd->endingRootEditableElement(),\n      InputEvent::InputType::HistoryUndo, nullAtom,\n      InputEvent::EventIsComposing::NotComposing);\n\n  \/\/ TODO(editing-dev): The use of updateStyleAndLayoutIgnorePendingStylesheets\n  \/\/ needs to be audited.  See http:\/\/crbug.com\/590369 for more details.\n  \/\/ In the long term, we should stop editing commands from storing\n  \/\/ VisibleSelections as starting and ending selections.\n  frame().document()->updateStyleAndLayoutIgnorePendingStylesheets();\n\n  const VisibleSelection& newSelection =\n      correctedVisibleSelection(cmd->startingSelection());\n  DCHECK(newSelection.isValidFor(*frame().document())) << newSelection;\n  if (!newSelection.isNone()) {\n    changeSelectionAfterCommand(\n        newSelection,\n        FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);\n  }\n\n  m_lastEditCommand = nullptr;\n  m_undoStack->registerRedoStep(cmd);\n  respondToChangedContents(newSelection);\n}\n\nvoid Editor::reappliedEditing(UndoStep* cmd) {\n  EventQueueScope scope;\n\n  dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(),\n                                       cmd->endingRootEditableElement());\n  dispatchInputEventEditableContentChanged(\n      cmd->startingRootEditableElement(), cmd->endingRootEditableElement(),\n      InputEvent::InputType::HistoryRedo, nullAtom,\n      InputEvent::EventIsComposing::NotComposing);\n\n  \/\/ TODO(editing-dev): The use of updateStyleAndLayoutIgnorePendingStylesheets\n  \/\/ needs to be audited.  See http:\/\/crbug.com\/590369 for more details.\n  \/\/ In the long term, we should stop editing commands from storing\n  \/\/ VisibleSelections as starting and ending selections.\n  frame().document()->updateStyleAndLayoutIgnorePendingStylesheets();\n  const VisibleSelection& newSelection =\n      correctedVisibleSelection(cmd->endingSelection());\n  DCHECK(newSelection.isValidFor(*frame().document())) << newSelection;\n  if (!newSelection.isNone()) {\n    changeSelectionAfterCommand(\n        newSelection,\n        FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);\n  }\n\n  m_lastEditCommand = nullptr;\n  m_undoStack->registerUndoStep(cmd);\n  respondToChangedContents(newSelection);\n}\n\nEditor* Editor::create(LocalFrame& frame) {\n  return new Editor(frame);\n}\n\nEditor::Editor(LocalFrame& frame)\n    : m_frame(&frame),\n      m_undoStack(UndoStack::create()),\n      m_preventRevealSelection(0),\n      m_shouldStartNewKillRingSequence(false),\n      \/\/ This is off by default, since most editors want this behavior (this\n      \/\/ matches IE but not FF).\n      m_shouldStyleWithCSS(false),\n      m_killRing(WTF::wrapUnique(new KillRing)),\n      m_areMarkedTextMatchesHighlighted(false),\n      m_defaultParagraphSeparator(EditorParagraphSeparatorIsDiv),\n      m_overwriteModeEnabled(false) {}\n\nEditor::~Editor() {}\n\nvoid Editor::clear() {\n  frame().inputMethodController().clear();\n  m_shouldStyleWithCSS = false;\n  m_defaultParagraphSeparator = EditorParagraphSeparatorIsDiv;\n  m_undoStack->clear();\n}\n\nbool Editor::insertText(const String& text, KeyboardEvent* triggeringEvent) {\n  return frame().eventHandler().handleTextInputEvent(text, triggeringEvent);\n}\n\nbool Editor::insertTextWithoutSendingTextEvent(const String& text,\n                                               bool selectInsertedText,\n                                               TextEvent* triggeringEvent) {\n  if (text.isEmpty())\n    return false;\n\n  const VisibleSelection& selection = selectionForCommand(triggeringEvent);\n  if (!selection.isContentEditable())\n    return false;\n\n  spellChecker().updateMarkersForWordsAffectedByEditing(\n      isSpaceOrNewline(text[0]));\n\n  \/\/ Insert the text\n  TypingCommand::insertText(\n      *selection.start().document(), text, selection,\n      selectInsertedText ? TypingCommand::SelectInsertedText : 0,\n      triggeringEvent && triggeringEvent->isComposition()\n          ? TypingCommand::TextCompositionConfirm\n          : TypingCommand::TextCompositionNone);\n\n  \/\/ Reveal the current selection\n  if (LocalFrame* editedFrame = selection.start().document()->frame()) {\n    if (Page* page = editedFrame->page()) {\n      LocalFrame* focusedOrMainFrame =\n          toLocalFrame(page->focusController().focusedOrMainFrame());\n      focusedOrMainFrame->selection().revealSelection(\n          ScrollAlignment::alignCenterIfNeeded);\n    }\n  }\n\n  return true;\n}\n\nbool Editor::insertLineBreak() {\n  if (!canEdit())\n    return false;\n\n  VisiblePosition caret = frame().selection().selection().visibleStart();\n  bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);\n  DCHECK(frame().document());\n  if (!TypingCommand::insertLineBreak(*frame().document()))\n    return false;\n  revealSelectionAfterEditingOperation(\n      alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded\n                  : ScrollAlignment::alignCenterIfNeeded);\n\n  return true;\n}\n\nbool Editor::insertParagraphSeparator() {\n  if (!canEdit())\n    return false;\n\n  if (!canEditRichly())\n    return insertLineBreak();\n\n  VisiblePosition caret = frame().selection().selection().visibleStart();\n  bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);\n  DCHECK(frame().document());\n  EditingState editingState;\n  if (!TypingCommand::insertParagraphSeparator(*frame().document()))\n    return false;\n  revealSelectionAfterEditingOperation(\n      alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded\n                  : ScrollAlignment::alignCenterIfNeeded);\n\n  return true;\n}\n\nvoid Editor::cut(EditorCommandSource source) {\n  if (tryDHTMLCut())\n    return;  \/\/ DHTML did the whole operation\n  if (!canCut())\n    return;\n\n  \/\/ TODO(xiaochengh): The use of updateStyleAndLayoutIgnorePendingStylesheets\n  \/\/ needs to be audited.  See http:\/\/crbug.com\/590369 for more details.\n  \/\/ |tryDHTMLCut| dispatches cut event, which may make layout dirty, but we\n  \/\/ need clean layout to obtain the selected content.\n  frame().document()->updateStyleAndLayoutIgnorePendingStylesheets();\n\n  \/\/ TODO(yosin) We should use early return style here.\n  if (canDeleteRange(selectedRange())) {\n    spellChecker().updateMarkersForWordsAffectedByEditing(true);\n    if (enclosingTextControl(frame().selection().start())) {\n      String plainText = frame().selectedTextForClipboard();\n      Pasteboard::generalPasteboard()->writePlainText(\n          plainText, canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace\n                                            : Pasteboard::CannotSmartReplace);\n    } else {\n      writeSelectionToPasteboard();\n    }\n\n    if (source == CommandFromMenuOrKeyBinding) {\n      if (dispatchBeforeInputDataTransfer(findEventTargetFromSelection(),\n                                          InputEvent::InputType::DeleteByCut,\n                                          nullptr, nullptr) !=\n          DispatchEventResult::NotCanceled)\n        return;\n      \/\/ 'beforeinput' event handler may destroy target frame.\n      if (m_frame->document()->frame() != m_frame)\n        return;\n    }\n    deleteSelectionWithSmartDelete(\n        canSmartCopyOrDelete() ? DeleteMode::Smart : DeleteMode::Simple,\n        InputEvent::InputType::DeleteByCut);\n  }\n}\n\nvoid Editor::copy() {\n  if (tryDHTMLCopy())\n    return;  \/\/ DHTML did the whole operation\n  if (!canCopy())\n    return;\n\n  \/\/ TODO(xiaochengh): The use of updateStyleAndLayoutIgnorePendingStylesheets\n  \/\/ needs to be audited.  See http:\/\/crbug.com\/590369 for more details.\n  \/\/ |tryDHTMLCopy| dispatches copy event, which may make layout dirty, but\n  \/\/ we need clean layout to obtain the selected content.\n  frame().document()->updateStyleAndLayoutIgnorePendingStylesheets();\n\n  if (enclosingTextControl(frame().selection().start())) {\n    Pasteboard::generalPasteboard()->writePlainText(\n        frame().selectedTextForClipboard(),\n        canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace\n                               : Pasteboard::CannotSmartReplace);\n  } else {\n    Document* document = frame().document();\n    if (HTMLImageElement* imageElement =\n            imageElementFromImageDocument(document))\n      writeImageNodeToPasteboard(Pasteboard::generalPasteboard(), imageElement,\n                                 document->title());\n    else\n      writeSelectionToPasteboard();\n  }\n}\n\nvoid Editor::paste(EditorCommandSource source) {\n  DCHECK(frame().document());\n  if (tryDHTMLPaste(AllMimeTypes))\n    return;  \/\/ DHTML did the whole operation\n  if (!canPaste())\n    return;\n  spellChecker().updateMarkersForWordsAffectedByEditing(false);\n  ResourceFetcher* loader = frame().document()->fetcher();\n  ResourceCacheValidationSuppressor validationSuppressor(loader);\n\n  PasteMode pasteMode = frame().selection().isContentRichlyEditable()\n                            ? AllMimeTypes\n                            : PlainTextOnly;\n\n  if (source == CommandFromMenuOrKeyBinding) {\n    DataTransfer* dataTransfer =\n        DataTransfer::create(DataTransfer::CopyAndPaste, DataTransferReadable,\n                             DataObject::createFromPasteboard(pasteMode));\n\n    if (dispatchBeforeInputDataTransfer(findEventTargetFromSelection(),\n                                        InputEvent::InputType::InsertFromPaste,\n                                        dataTransfer, nullptr) !=\n        DispatchEventResult::NotCanceled)\n      return;\n    \/\/ 'beforeinput' event handler may destroy target frame.\n    if (m_frame->document()->frame() != m_frame)\n      return;\n  }\n\n  if (pasteMode == AllMimeTypes)\n    pasteWithPasteboard(Pasteboard::generalPasteboard());\n  else\n    pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());\n}\n\nvoid Editor::pasteAsPlainText(EditorCommandSource source) {\n  if (tryDHTMLPaste(PlainTextOnly))\n    return;\n  if (!canPaste())\n    return;\n  spellChecker().updateMarkersForWordsAffectedByEditing(false);\n  pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());\n}\n\nvoid Editor::performDelete() {\n  if (!canDelete())\n    return;\n\n  \/\/ TODO(xiaochengh): The use of updateStyleAndLayoutIgnorePendingStylesheets\n  \/\/ needs to be audited.  See http:\/\/crbug.com\/590369 for more details.\n  \/\/ |selectedRange| requires clean layout for visible selection normalization.\n  frame().document()->updateStyleAndLayoutIgnorePendingStylesheets();\n\n  addToKillRing(selectedRange());\n  \/\/ TODO(chongz): |Editor::performDelete()| has no direction.\n  \/\/ https:\/\/github.com\/w3c\/editing\/issues\/130\n  deleteSelectionWithSmartDelete(\n      canSmartCopyOrDelete() ? DeleteMode::Smart : DeleteMode::Simple,\n      InputEvent::InputType::DeleteContentBackward);\n\n  \/\/ clear the \"start new kill ring sequence\" setting, because it was set to\n  \/\/ true when the selection was updated by deleting the range\n  setStartNewKillRingSequence(false);\n}\n\nstatic void countEditingEvent(ExecutionContext* executionContext,\n                              const Event* event,\n                              UseCounter::Feature featureOnInput,\n                              UseCounter::Feature featureOnTextArea,\n                              UseCounter::Feature featureOnContentEditable,\n                              UseCounter::Feature featureOnNonNode) {\n  EventTarget* eventTarget = event->target();\n  Node* node = eventTarget->toNode();\n  if (!node) {\n    UseCounter::count(executionContext, featureOnNonNode);\n    return;\n  }\n\n  if (isHTMLInputElement(node)) {\n    UseCounter::count(executionContext, featureOnInput);\n    return;\n  }\n\n  if (isHTMLTextAreaElement(node)) {\n    UseCounter::count(executionContext, featureOnTextArea);\n    return;\n  }\n\n  TextControlElement* control = enclosingTextControl(node);\n  if (isHTMLInputElement(control)) {\n    UseCounter::count(executionContext, featureOnInput);\n    return;\n  }\n\n  if (isHTMLTextAreaElement(control)) {\n    UseCounter::count(executionContext, featureOnTextArea);\n    return;\n  }\n\n  UseCounter::count(executionContext, featureOnContentEditable);\n}\n\nvoid Editor::countEvent(ExecutionContext* executionContext,\n                        const Event* event) {\n  if (!executionContext)\n    return;\n\n  if (event->type() == EventTypeNames::textInput) {\n    countEditingEvent(executionContext, event,\n                      UseCounter::TextInputEventOnInput,\n                      UseCounter::TextInputEventOnTextArea,\n                      UseCounter::TextInputEventOnContentEditable,\n                      UseCounter::TextInputEventOnNotNode);\n    return;\n  }\n\n  if (event->type() == EventTypeNames::webkitBeforeTextInserted) {\n    countEditingEvent(executionContext, event,\n                      UseCounter::WebkitBeforeTextInsertedOnInput,\n                      UseCounter::WebkitBeforeTextInsertedOnTextArea,\n                      UseCounter::WebkitBeforeTextInsertedOnContentEditable,\n                      UseCounter::WebkitBeforeTextInsertedOnNotNode);\n    return;\n  }\n\n  if (event->type() == EventTypeNames::webkitEditableContentChanged) {\n    countEditingEvent(executionContext, event,\n                      UseCounter::WebkitEditableContentChangedOnInput,\n                      UseCounter::WebkitEditableContentChangedOnTextArea,\n                      UseCounter::WebkitEditableContentChangedOnContentEditable,\n                      UseCounter::WebkitEditableContentChangedOnNotNode);\n  }\n}\n\nvoid Editor::copyImage(const HitTestResult& result) {\n  writeImageNodeToPasteboard(Pasteboard::generalPasteboard(),\n                             result.innerNodeOrImageMapImage(),\n                             result.altDisplayString());\n}\n\nbool Editor::canUndo() {\n  return m_undoStack->canUndo();\n}\n\nvoid Editor::undo() {\n  m_undoStack->undo();\n}\n\nbool Editor::canRedo() {\n  return m_undoStack->canRedo();\n}\n\nvoid Editor::redo() {\n  m_undoStack->redo();\n}\n\nvoid Editor::setBaseWritingDirection(WritingDirection direction) {\n  Element* focusedElement = frame().document()->focusedElement();\n  if (isTextControlElement(focusedElement)) {\n    if (direction == NaturalWritingDirection)\n      return;\n    focusedElement->setAttribute(\n        dirAttr, direction == LeftToRightWritingDirection ? \"ltr\" : \"rtl\");\n    focusedElement->dispatchInputEvent();\n    return;\n  }\n\n  MutableStylePropertySet* style =\n      MutableStylePropertySet::create(HTMLQuirksMode);\n  style->setProperty(\n      CSSPropertyDirection,\n      direction == LeftToRightWritingDirection\n          ? \"ltr\"\n          : direction == RightToLeftWritingDirection ? \"rtl\" : \"inherit\",\n      false);\n  applyParagraphStyleToSelection(\n      style, InputEvent::InputType::FormatSetBlockTextDirection);\n}\n\nvoid Editor::revealSelectionAfterEditingOperation(\n    const ScrollAlignment& alignment,\n    RevealExtentOption revealExtentOption) {\n  if (m_preventRevealSelection)\n    return;\n  frame().selection().revealSelection(alignment, revealExtentOption);\n}\n\nvoid Editor::transpose() {\n  if (!canEdit())\n    return;\n\n  VisibleSelection selection = frame().selection().selection();\n  if (!selection.isCaret())\n    return;\n\n  \/\/ Make a selection that goes back one character and forward two characters.\n  VisiblePosition caret = selection.visibleStart();\n  VisiblePosition next =\n      isEndOfParagraph(caret) ? caret : nextPositionOf(caret);\n  VisiblePosition previous = previousPositionOf(next);\n  if (next.deepEquivalent() == previous.deepEquivalent())\n    return;\n  previous = previousPositionOf(previous);\n  if (!inSameParagraph(next, previous))\n    return;\n  const EphemeralRange range = makeRange(previous, next);\n  if (range.isNull())\n    return;\n  VisibleSelection newSelection = createVisibleSelection(\n      SelectionInDOMTree::Builder().setBaseAndExtent(range).build());\n\n  \/\/ Transpose the two characters.\n  String text = plainText(range);\n  if (text.length() != 2)\n    return;\n  String transposed = text.right(1) + text.left(1);\n\n  \/\/ Select the two characters.\n  if (newSelection != frame().selection().selection())\n    frame().selection().setSelection(newSelection);\n\n  \/\/ Insert the transposed characters.\n  \/\/ TODO(chongz): Once we add |InsertTranspose| in |InputEvent::InputType|, we\n  \/\/ should use it instead of |InsertFromPaste|.\n  replaceSelectionWithText(transposed, false, false,\n                           InputEvent::InputType::InsertFromPaste);\n}\n\nvoid Editor::addToKillRing(const EphemeralRange& range) {\n  if (m_shouldStartNewKillRingSequence)\n    killRing().startNewSequence();\n\n  DCHECK(!frame().document()->needsLayoutTreeUpdate());\n  String text = plainText(range);\n  killRing().append(text);\n  m_shouldStartNewKillRingSequence = false;\n}\n\nvoid Editor::changeSelectionAfterCommand(\n    const VisibleSelection& newSelection,\n    FrameSelection::SetSelectionOptions options) {\n  \/\/ If the new selection is orphaned, then don't update the selection.\n  if (newSelection.start().isOrphan() || newSelection.end().isOrphan())\n    return;\n\n  \/\/ See <rdar:\/\/problem\/5729315> Some shouldChangeSelectedDOMRange contain\n  \/\/ Ranges for selections that are no longer valid\n  bool selectionDidNotChangeDOMPosition =\n      newSelection == frame().selection().selection();\n  frame().selection().setSelection(newSelection, options);\n\n  \/\/ Some editing operations change the selection visually without affecting its\n  \/\/ position within the DOM. For example when you press return in the following\n  \/\/ (the caret is marked by ^):\n  \/\/ <div contentEditable=\"true\"><div>^Hello<\/div><\/div>\n  \/\/ WebCore inserts <div><br><\/div> *before* the current block, which correctly\n  \/\/ moves the paragraph down but which doesn't change the caret's DOM position\n  \/\/ ([\"hello\", 0]). In these situations the above FrameSelection::setSelection\n  \/\/ call does not call EditorClient::respondToChangedSelection(), which, on the\n  \/\/ Mac, sends selection change notifications and starts a new kill ring\n  \/\/ sequence, but we want to do these things (matches AppKit).\n  if (selectionDidNotChangeDOMPosition)\n    client().respondToChangedSelection(m_frame,\n                                       frame().selection().getSelectionType());\n}\n\nIntRect Editor::firstRectForRange(const EphemeralRange& range) const {\n  DCHECK(!frame().document()->needsLayoutTreeUpdate());\n  DocumentLifecycle::DisallowTransitionScope disallowTransition(\n      frame().document()->lifecycle());\n\n  LayoutUnit extraWidthToEndOfLine;\n  DCHECK(range.isNotNull());\n\n  IntRect startCaretRect =\n      RenderedPosition(\n          createVisiblePosition(range.startPosition()).deepEquivalent(),\n          TextAffinity::Downstream)\n          .absoluteRect(&extraWidthToEndOfLine);\n  if (startCaretRect.isEmpty())\n    return IntRect();\n\n  IntRect endCaretRect =\n      RenderedPosition(\n          createVisiblePosition(range.endPosition()).deepEquivalent(),\n          TextAffinity::Upstream)\n          .absoluteRect();\n  if (endCaretRect.isEmpty())\n    return IntRect();\n\n  if (startCaretRect.y() == endCaretRect.y()) {\n    \/\/ start and end are on the same line\n    return IntRect(std::min(startCaretRect.x(), endCaretRect.x()),\n                   startCaretRect.y(),\n                   abs(endCaretRect.x() - startCaretRect.x()),\n                   std::max(startCaretRect.height(), endCaretRect.height()));\n  }\n\n  \/\/ start and end aren't on the same line, so go from start to the end of its\n  \/\/ line\n  return IntRect(startCaretRect.x(), startCaretRect.y(),\n                 (startCaretRect.width() + extraWidthToEndOfLine).toInt(),\n                 startCaretRect.height());\n}\n\nvoid Editor::computeAndSetTypingStyle(StylePropertySet* style,\n                                      InputEvent::InputType inputType) {\n  if (!style || style->isEmpty()) {\n    frame().selection().clearTypingStyle();\n    return;\n  }\n\n  \/\/ Calculate the current typing style.\n  EditingStyle* typingStyle = nullptr;\n  if (frame().selection().typingStyle()) {\n    typingStyle = frame().selection().typingStyle()->copy();\n    typingStyle->overrideWithStyle(style);\n  } else {\n    typingStyle = EditingStyle::create(style);\n  }\n\n  typingStyle->prepareToApplyAt(\n      frame().selection().selection().visibleStart().deepEquivalent(),\n      EditingStyle::PreserveWritingDirection);\n\n  \/\/ Handle block styles, substracting these from the typing style.\n  EditingStyle* blockStyle = typingStyle->extractAndRemoveBlockProperties();\n  if (!blockStyle->isEmpty()) {\n    DCHECK(frame().document());\n    ApplyStyleCommand::create(*frame().document(), blockStyle, inputType)\n        ->apply();\n  }\n\n  \/\/ Set the remaining style as the typing style.\n  frame().selection().setTypingStyle(typingStyle);\n}\n\nbool Editor::findString(const String& target, FindOptions options) {\n  VisibleSelection selection = frame().selection().selection();\n\n  \/\/ TODO(yosin) We should make |findRangeOfString()| to return\n  \/\/ |EphemeralRange| rather than|Range| object.\n  Range* resultRange = findRangeOfString(\n      target, EphemeralRange(selection.start(), selection.end()),\n      static_cast<FindOptions>(options | FindAPICall));\n\n  if (!resultRange)\n    return false;\n\n  frame().selection().setSelection(\n      SelectionInDOMTree::Builder()\n          .setBaseAndExtent(EphemeralRange(resultRange))\n          .build());\n  frame().selection().revealSelection();\n  return true;\n}\n\nRange* Editor::findStringAndScrollToVisible(const String& target,\n                                            Range* previousMatch,\n                                            FindOptions options) {\n  Range* nextMatch = findRangeOfString(\n      target, EphemeralRangeInFlatTree(previousMatch), options);\n  if (!nextMatch)\n    return nullptr;\n\n  Node* firstNode = nextMatch->firstNode();\n  firstNode->layoutObject()->scrollRectToVisible(\n      LayoutRect(nextMatch->boundingBox()),\n      ScrollAlignment::alignCenterIfNeeded,\n      ScrollAlignment::alignCenterIfNeeded, UserScroll);\n  firstNode->document().setSequentialFocusNavigationStartingPoint(firstNode);\n\n  return nextMatch;\n}\n\n\/\/ TODO(yosin) We should return |EphemeralRange| rather than |Range|. We use\n\/\/ |Range| object for checking whether start and end position crossing shadow\n\/\/ boundaries, however we can do it without |Range| object.\ntemplate <typename Strategy>\nstatic Range* findStringBetweenPositions(\n    const String& target,\n    const EphemeralRangeTemplate<Strategy>& referenceRange,\n    FindOptions options) {\n  EphemeralRangeTemplate<Strategy> searchRange(referenceRange);\n\n  bool forward = !(options & Backwards);\n\n  while (true) {\n    EphemeralRangeTemplate<Strategy> resultRange =\n        findPlainText(searchRange, target, options);\n    if (resultRange.isCollapsed())\n      return nullptr;\n\n    Range* rangeObject =\n        Range::create(resultRange.document(),\n                      toPositionInDOMTree(resultRange.startPosition()),\n                      toPositionInDOMTree(resultRange.endPosition()));\n    if (!rangeObject->collapsed())\n      return rangeObject;\n\n    \/\/ Found text spans over multiple TreeScopes. Since it's impossible to\n    \/\/ return such section as a Range, we skip this match and seek for the\n    \/\/ next occurrence.\n    \/\/ TODO(yosin) Handle this case.\n    if (forward) {\n      searchRange = EphemeralRangeTemplate<Strategy>(\n          nextPositionOf(resultRange.startPosition(),\n                         PositionMoveType::GraphemeCluster),\n          searchRange.endPosition());\n    } else {\n      searchRange = EphemeralRangeTemplate<Strategy>(\n          searchRange.startPosition(),\n          previousPositionOf(resultRange.endPosition(),\n                             PositionMoveType::GraphemeCluster));\n    }\n  }\n\n  NOTREACHED();\n  return nullptr;\n}\n\ntemplate <typename Strategy>\nstatic Range* findRangeOfStringAlgorithm(\n    Document& document,\n    const String& target,\n    const EphemeralRangeTemplate<Strategy>& referenceRange,\n    FindOptions options) {\n  if (target.isEmpty())\n    return nullptr;\n\n  \/\/ Start from an edge of the reference range. Which edge is used depends on\n  \/\/ whether we're searching forward or backward, and whether startInSelection\n  \/\/ is set.\n  EphemeralRangeTemplate<Strategy> documentRange =\n      EphemeralRangeTemplate<Strategy>::rangeOfContents(document);\n  EphemeralRangeTemplate<Strategy> searchRange(documentRange);\n\n  bool forward = !(options & Backwards);\n  bool startInReferenceRange = false;\n  if (referenceRange.isNotNull()) {\n    startInReferenceRange = options & StartInSelection;\n    if (forward && startInReferenceRange)\n      searchRange = EphemeralRangeTemplate<Strategy>(\n          referenceRange.startPosition(), documentRange.endPosition());\n    else if (forward)\n      searchRange = EphemeralRangeTemplate<Strategy>(\n          referenceRange.endPosition(), documentRange.endPosition());\n    else if (startInReferenceRange)\n      searchRange = EphemeralRangeTemplate<Strategy>(\n          documentRange.startPosition(), referenceRange.endPosition());\n    else\n      searchRange = EphemeralRangeTemplate<Strategy>(\n          documentRange.startPosition(), referenceRange.startPosition());\n  }\n\n  Range* resultRange = findStringBetweenPositions(target, searchRange, options);\n\n  \/\/ If we started in the reference range and the found range exactly matches\n  \/\/ the reference range, find again. Build a selection with the found range\n  \/\/ to remove collapsed whitespace. Compare ranges instead of selection\n  \/\/ objects to ignore the way that the current selection was made.\n  if (resultRange && startInReferenceRange &&\n      normalizeRange(EphemeralRangeTemplate<Strategy>(resultRange)) ==\n          referenceRange) {\n    if (forward)\n      searchRange = EphemeralRangeTemplate<Strategy>(\n          fromPositionInDOMTree<Strategy>(resultRange->endPosition()),\n          searchRange.endPosition());\n    else\n      searchRange = EphemeralRangeTemplate<Strategy>(\n          searchRange.startPosition(),\n          fromPositionInDOMTree<Strategy>(resultRange->startPosition()));\n    resultRange = findStringBetweenPositions(target, searchRange, options);\n  }\n\n  if (!resultRange && options & WrapAround)\n    return findStringBetweenPositions(target, documentRange, options);\n\n  return resultRange;\n}\n\nRange* Editor::findRangeOfString(const String& target,\n                                 const EphemeralRange& reference,\n                                 FindOptions options) {\n  return findRangeOfStringAlgorithm<EditingStrategy>(\n      *frame().document(), target, reference, options);\n}\n\nRange* Editor::findRangeOfString(const String& target,\n                                 const EphemeralRangeInFlatTree& reference,\n                                 FindOptions options) {\n  return findRangeOfStringAlgorithm<EditingInFlatTreeStrategy>(\n      *frame().document(), target, reference, options);\n}\n\nvoid Editor::setMarkedTextMatchesAreHighlighted(bool flag) {\n  if (flag == m_areMarkedTextMatchesHighlighted)\n    return;\n\n  m_areMarkedTextMatchesHighlighted = flag;\n  frame().document()->markers().repaintMarkers(DocumentMarker::TextMatch);\n}\n\nvoid Editor::respondToChangedSelection(\n    const Position& oldSelectionStart,\n    FrameSelection::SetSelectionOptions options) {\n  spellChecker().respondToChangedSelection(oldSelectionStart, options);\n  frame().inputMethodController().cancelCompositionIfSelectionIsInvalid();\n  client().respondToChangedSelection(&frame(),\n                                     frame().selection().getSelectionType());\n  setStartNewKillRingSequence(true);\n}\n\nSpellChecker& Editor::spellChecker() const {\n  return frame().spellChecker();\n}\n\nvoid Editor::toggleOverwriteModeEnabled() {\n  m_overwriteModeEnabled = !m_overwriteModeEnabled;\n  frame().selection().setShouldShowBlockCursor(m_overwriteModeEnabled);\n}\n\n\/\/ TODO(tkent): This is a workaround of some crash bugs in the editing code,\n\/\/ which assumes a document has a valid HTML structure. We should make the\n\/\/ editing code more robust, and should remove this hack. crbug.com\/580941.\nvoid Editor::tidyUpHTMLStructure(Document& document) {\n  \/\/ hasEditableStyle() needs up-to-date ComputedStyle.\n  document.updateStyleAndLayoutTree();\n  bool needsValidStructure = hasEditableStyle(document) ||\n                             (document.documentElement() &&\n                              hasEditableStyle(*document.documentElement()));\n  if (!needsValidStructure)\n    return;\n  Element* existingHead = nullptr;\n  Element* existingBody = nullptr;\n  Element* currentRoot = document.documentElement();\n  if (currentRoot) {\n    if (isHTMLHtmlElement(currentRoot))\n      return;\n    if (isHTMLHeadElement(currentRoot))\n      existingHead = currentRoot;\n    else if (isHTMLBodyElement(currentRoot))\n      existingBody = currentRoot;\n    else if (isHTMLFrameSetElement(currentRoot))\n      existingBody = currentRoot;\n  }\n  \/\/ We ensure only \"the root is <html>.\"\n  \/\/ documentElement as rootEditableElement is problematic.  So we move\n  \/\/ non-<html> root elements under <body>, and the <body> works as\n  \/\/ rootEditableElement.\n  document.addConsoleMessage(ConsoleMessage::create(\n      JSMessageSource, WarningMessageLevel,\n      \"document.execCommand() doesn't work with an invalid HTML structure. It \"\n      \"is corrected automatically.\"));\n  UseCounter::count(document, UseCounter::ExecCommandAltersHTMLStructure);\n\n  Element* root = HTMLHtmlElement::create(document);\n  if (existingHead)\n    root->appendChild(existingHead);\n  Element* body = nullptr;\n  if (existingBody)\n    body = existingBody;\n  else\n    body = HTMLBodyElement::create(document);\n  if (document.documentElement() && body != document.documentElement())\n    body->appendChild(document.documentElement());\n  root->appendChild(body);\n  DCHECK(!document.documentElement());\n  document.appendChild(root);\n\n  \/\/ TODO(tkent): Should we check and move Text node children of <html>?\n}\n\nvoid Editor::replaceSelection(const String& text) {\n  DCHECK(!frame().document()->needsLayoutTreeUpdate());\n  bool selectReplacement = behavior().shouldSelectReplacement();\n  bool smartReplace = true;\n  replaceSelectionWithText(text, selectReplacement, smartReplace,\n                           InputEvent::InputType::InsertReplacementText);\n}\n\nDEFINE_TRACE(Editor) {\n  visitor->trace(m_frame);\n  visitor->trace(m_lastEditCommand);\n  visitor->trace(m_undoStack);\n  visitor->trace(m_mark);\n}\n\n}  \/\/ namespace blink\n","avg_line_length":36.754088785,"max_line_length":80,"alphanum_fraction":0.7012380211,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1924,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-4.0","MIT"],"max_stars_count":421.0,"content":"\/\/ System.Web.Services.Description.ServiceDescription.Extensions\r\n\/\/ System.Web.Services.Description.ServiceDescription.RetrievalUrl\r\n\/* The following program demonstrates properties 'Extensions', 'RetrievalUrl' of \r\n'ServiceDescription' class. The input to the program is a WSDL file\r\n'ServiceDescription_Extensions_Input_cs.wsdl'. This program adds one object \r\nto the extensions collection and displays the count and set the 'RetrievalURL' and displays.\r\n*\/\r\n\r\n#using <System.dll>\r\n#using <System.Xml.dll>\r\n#using <System.Web.Services.dll>\r\n\r\nusing namespace System;\r\nusing namespace System::Web::Services;\r\nusing namespace System::Web::Services::Description;\r\n\r\nint main()\r\n{\r\n   \/\/ <Snippet1>\r\n   \/\/ <Snippet2>\r\n   ServiceDescription^ myServiceDescription = gcnew ServiceDescription;\r\n   myServiceDescription = ServiceDescription::Read( \"ServiceDescription_Extensions_Input_cs.wsdl\" );\r\n   Console::WriteLine( myServiceDescription->Bindings[ 1 ]->Extensions[ 0 ] );\r\n   SoapBinding^ mySoapBinding = gcnew SoapBinding;\r\n   mySoapBinding->Required = true;\r\n   SoapBinding^ mySoapBinding1 = gcnew SoapBinding;\r\n   mySoapBinding1->Required = false;\r\n   myServiceDescription->Extensions->Add( mySoapBinding );\r\n   myServiceDescription->Extensions->Add( mySoapBinding1 );\r\n   System::Collections::IEnumerator^ myEnum = myServiceDescription->Extensions->GetEnumerator();\r\n   while ( myEnum->MoveNext() )\r\n   {\r\n      ServiceDescriptionFormatExtension^ myServiceDescriptionFormatExtension = (ServiceDescriptionFormatExtension^)(myEnum->Current);\r\n      Console::WriteLine( \"Required: {0}\", myServiceDescriptionFormatExtension->Required );\r\n   }\r\n\r\n   myServiceDescription->Write( \"ServiceDescription_Extensions_Output_cs.wsdl\" );\r\n   myServiceDescription->RetrievalUrl = \"http:\/\/www.contoso.com\/\";\r\n   Console::WriteLine( \"Retrieval URL is: {0}\", myServiceDescription->RetrievalUrl );\r\n   \/\/ <\/Snippet2>\r\n   \/\/ <\/Snippet1>\r\n}\r\n","avg_line_length":44.7441860465,"max_line_length":134,"alphanum_fraction":0.7525987526,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4717,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":7.0,"content":"if (options.optimize) {\n    llvm::FunctionAnalysisManager fam;\n\n    fam.registerPass([]() { return llvm::PassInstrumentationAnalysis(); });\n    fam.registerPass([]() { return llvm::DominatorTreeAnalysis(); });\n    fam.registerPass([]() { return llvm::AssumptionAnalysis(); });\n    fam.registerPass([]() { return llvm::LazyValueAnalysis(); });\n    fam.registerPass([]() { return llvm::TargetLibraryAnalysis(); });\n    fam.registerPass([]() { return llvm::TargetIRAnalysis(); });\n\n    llvm::ModuleAnalysisManager mam;\n    mam.registerPass([]() { return llvm::PassInstrumentationAnalysis(); });\n\n    mam.registerPass([&fam]() { return llvm::FunctionAnalysisManagerModuleProxy(fam); });\n    fam.registerPass([&mam]() { return llvm::ModuleAnalysisManagerFunctionProxy(mam); });\n\n    llvm::FunctionPassManager fpm;\n    fpm.addPass(llvm::LowerSwitchPass());\n    fpm.addPass(llvm::SimplifyCFGPass());\n    fpm.addPass(llvm::PromotePass());\n\n    llvm::ModulePassManager mpm;\n    mpm.addPass(createModuleToFunctionPassAdaptor(std::move(fpm)));\n    mpm.run(*base, mam);\n}\n\nif (options.printIR)\n    base->print(llvm::outs(), nullptr);\n\nif (!options.output.empty()) {\n    llvm::legacy::PassManager pass;\n\n    std::error_code error;\n    llvm::raw_fd_ostream output(options.output, error);\n\n    if (error)\n        throw std::runtime_error(fmt::format(\"Cannot open file {} for output\", options.output));\n\n    if (target.machine->addPassesToEmitFile(pass, output, nullptr, llvm::CodeGenFileType::CGFT_ObjectFile))\n        throw std::runtime_error(\"Target machine does not support object output.\");\n\n    pass.run(*base);\n}\n\nif (options.interpret) {\n    auto expectedJit = llvm::orc::LLJITBuilder().create();\n\n    if (!expectedJit)\n        throw std::runtime_error(\"Could not create jit instance.\");\n\n    auto &jit = expectedJit.get();\n\n    llvm::orc::ThreadSafeModule tsModule(std::move(base), std::move(context));\n\n    if (jit->addIRModule(std::move(tsModule)))\n        throw std::runtime_error(\"Could not add module to jit instance.\");\n\n    for (const auto &library : libraries) {\n        for (const auto &lib : library.libraries) {\n            auto loader\n                = llvm::orc::StaticLibraryDefinitionGenerator::Load(jit->getObjLinkingLayer(), lib.c_str());\n\n            if (!loader) {\n                fmt::print(\"Failed to load library {}.\\n\", lib.string());\n            } else {\n                jit->getMainJITDylib().addGenerator(std::move(loader.get()));\n            }\n        }\n\n        for (const auto &lib : library.dynamicLibraries) {\n            auto loader\n                = llvm::orc::DynamicLibrarySearchGenerator::Load(lib.c_str(), target.layout->getGlobalPrefix());\n\n            if (!loader) {\n                fmt::print(\"Failed to load dynamic library {}.\\n\", lib.string());\n            } else {\n                jit->getMainJITDylib().addGenerator(std::move(loader.get()));\n            }\n        }\n    }\n\n    auto expectedMain = jit->lookup(\"main\");\n    if (!expectedMain)\n        throw std::runtime_error(\"Could not find main symbol.\");\n\n    auto *entry = reinterpret_cast<int (*)()>(expectedMain.get().getAddress());\n\n    fmt::print(\"Returned {}.\\n\", entry());\n}\n\n\nstruct TransferState {\n    enum class Stage {\n        NoUpdate,\n        ReceivingObjects,\n        ResolvingDeltas,\n        Done,\n    };\n\n    Stage stage = Stage::NoUpdate;\n    int pin = 0;\n\n    bool movePin(uint32_t value, uint32_t max) {\n        int newPin = value \/ max * 10;\n        while (newPin > pin) {\n            fmt::print(\".\");\n            pin++;\n        }\n\n        constexpr auto threshold = 10;\n\n        return pin >= threshold;\n    }\n} state;\n\nauto transfer = [](const git_indexer_progress *stats, void *payload) -> int {\n    \/\/ received objects\n\n    auto state = reinterpret_cast<TransferState *>(payload);\n\n    switch (state->stage) {\n    case TransferState::Stage::NoUpdate:\n        fmt::print(\"\\nReceiving Objects\");\n        state->stage = TransferState::Stage::ReceivingObjects;\n        state->pin = 0;\n\n        break;\n\n    case TransferState::Stage::ReceivingObjects:\n        if (state->movePin(stats->received_objects, stats->total_objects)) {\n            fmt::print(\"\\nResolving Deltas\");\n            state->stage = TransferState::Stage::ResolvingDeltas;\n            state->pin = 0;\n        }\n\n        break;\n\n    case TransferState::Stage::ResolvingDeltas:\n        if (state->movePin(stats->indexed_deltas, stats->total_deltas)) {\n            fmt::print(\"\\n{} Bytes Transferred.\\n\", stats->received_bytes);\n            state->stage = TransferState::Stage::Done;\n            state->pin = 0;\n        }\n\n        break;\n\n    case TransferState::Stage::Done:\n        break;\n\n    default:\n        throw;\n    }\n\n    return 0;\n};\n","avg_line_length":30.2371794872,"max_line_length":112,"alphanum_fraction":0.609497562,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7275,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":12.0,"content":"\/\/ Copyright (c) 2015-2018 The Machinecoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <scheduler.h>\n\n#include <random.h>\n#include <reverselock.h>\n\n#include <assert.h>\n#include <boost\/bind.hpp>\n#include <utility>\n\nCScheduler::CScheduler() : nThreadsServicingQueue(0), stopRequested(false), stopWhenEmpty(false)\n{\n}\n\nCScheduler::~CScheduler()\n{\n    assert(nThreadsServicingQueue == 0);\n}\n\n\n#if BOOST_VERSION < 105000\nstatic boost::system_time toPosixTime(const boost::chrono::system_clock::time_point& t)\n{\n    \/\/ Creating the posix_time using from_time_t loses sub-second precision. So rather than exporting the time_point to time_t,\n    \/\/ start with a posix_time at the epoch (0) and add the milliseconds that have passed since then.\n    return boost::posix_time::from_time_t(0) + boost::posix_time::milliseconds(boost::chrono::duration_cast<boost::chrono::milliseconds>(t.time_since_epoch()).count());\n}\n#endif\n\nvoid CScheduler::serviceQueue()\n{\n    boost::unique_lock<boost::mutex> lock(newTaskMutex);\n    ++nThreadsServicingQueue;\n\n    \/\/ newTaskMutex is locked throughout this loop EXCEPT\n    \/\/ when the thread is waiting or when the user's function\n    \/\/ is called.\n    while (!shouldStop()) {\n        try {\n            if (!shouldStop() && taskQueue.empty()) {\n                reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock);\n                \/\/ Use this chance to get a tiny bit more entropy\n                RandAddSeedSleep();\n            }\n            while (!shouldStop() && taskQueue.empty()) {\n                \/\/ Wait until there is something to do.\n                newTaskScheduled.wait(lock);\n            }\n\n            \/\/ Wait until either there is a new task, or until\n            \/\/ the time of the first item on the queue:\n\n\/\/ wait_until needs boost 1.50 or later; older versions have timed_wait:\n#if BOOST_VERSION < 105000\n            while (!shouldStop() && !taskQueue.empty() &&\n                   newTaskScheduled.timed_wait(lock, toPosixTime(taskQueue.begin()->first))) {\n                \/\/ Keep waiting until timeout\n            }\n#else\n            \/\/ Some boost versions have a conflicting overload of wait_until that returns void.\n            \/\/ Explicitly use a template here to avoid hitting that overload.\n            while (!shouldStop() && !taskQueue.empty()) {\n                boost::chrono::system_clock::time_point timeToWaitFor = taskQueue.begin()->first;\n                if (newTaskScheduled.wait_until<>(lock, timeToWaitFor) == boost::cv_status::timeout)\n                    break; \/\/ Exit loop after timeout, it means we reached the time of the event\n            }\n#endif\n            \/\/ If there are multiple threads, the queue can empty while we're waiting (another\n            \/\/ thread may service the task we were waiting on).\n            if (shouldStop() || taskQueue.empty())\n                continue;\n\n            Function f = taskQueue.begin()->second;\n            taskQueue.erase(taskQueue.begin());\n\n            {\n                \/\/ Unlock before calling f, so it can reschedule itself or another task\n                \/\/ without deadlocking:\n                reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock);\n                f();\n            }\n        } catch (...) {\n            --nThreadsServicingQueue;\n            throw;\n        }\n    }\n    --nThreadsServicingQueue;\n    newTaskScheduled.notify_one();\n}\n\nvoid CScheduler::stop(bool drain)\n{\n    {\n        boost::unique_lock<boost::mutex> lock(newTaskMutex);\n        if (drain)\n            stopWhenEmpty = true;\n        else\n            stopRequested = true;\n    }\n    newTaskScheduled.notify_all();\n}\n\nvoid CScheduler::schedule(CScheduler::Function f, boost::chrono::system_clock::time_point t)\n{\n    {\n        boost::unique_lock<boost::mutex> lock(newTaskMutex);\n        taskQueue.insert(std::make_pair(t, f));\n    }\n    newTaskScheduled.notify_one();\n}\n\nvoid CScheduler::scheduleFromNow(CScheduler::Function f, int64_t deltaMilliSeconds)\n{\n    schedule(f, boost::chrono::system_clock::now() + boost::chrono::milliseconds(deltaMilliSeconds));\n}\n\nstatic void Repeat(CScheduler* s, CScheduler::Function f, int64_t deltaMilliSeconds)\n{\n    f();\n    s->scheduleFromNow(boost::bind(&Repeat, s, f, deltaMilliSeconds), deltaMilliSeconds);\n}\n\nvoid CScheduler::scheduleEvery(CScheduler::Function f, int64_t deltaMilliSeconds)\n{\n    scheduleFromNow(boost::bind(&Repeat, this, f, deltaMilliSeconds), deltaMilliSeconds);\n}\n\nsize_t CScheduler::getQueueInfo(boost::chrono::system_clock::time_point &first,\n                             boost::chrono::system_clock::time_point &last) const\n{\n    boost::unique_lock<boost::mutex> lock(newTaskMutex);\n    size_t result = taskQueue.size();\n    if (!taskQueue.empty()) {\n        first = taskQueue.begin()->first;\n        last = taskQueue.rbegin()->first;\n    }\n    return result;\n}\n\nbool CScheduler::AreThreadsServicingQueue() const {\n    boost::unique_lock<boost::mutex> lock(newTaskMutex);\n    return nThreadsServicingQueue;\n}\n\n\nvoid SingleThreadedSchedulerClient::MaybeScheduleProcessQueue() {\n    {\n        LOCK(m_cs_callbacks_pending);\n        \/\/ Try to avoid scheduling too many copies here, but if we\n        \/\/ accidentally have two ProcessQueue's scheduled at once its\n        \/\/ not a big deal.\n        if (m_are_callbacks_running) return;\n        if (m_callbacks_pending.empty()) return;\n    }\n    m_pscheduler->schedule(std::bind(&SingleThreadedSchedulerClient::ProcessQueue, this));\n}\n\nvoid SingleThreadedSchedulerClient::ProcessQueue() {\n    std::function<void (void)> callback;\n    {\n        LOCK(m_cs_callbacks_pending);\n        if (m_are_callbacks_running) return;\n        if (m_callbacks_pending.empty()) return;\n        m_are_callbacks_running = true;\n\n        callback = std::move(m_callbacks_pending.front());\n        m_callbacks_pending.pop_front();\n    }\n\n    \/\/ RAII the setting of fCallbacksRunning and calling MaybeScheduleProcessQueue\n    \/\/ to ensure both happen safely even if callback() throws.\n    struct RAIICallbacksRunning {\n        SingleThreadedSchedulerClient* instance;\n        explicit RAIICallbacksRunning(SingleThreadedSchedulerClient* _instance) : instance(_instance) {}\n        ~RAIICallbacksRunning() {\n            {\n                LOCK(instance->m_cs_callbacks_pending);\n                instance->m_are_callbacks_running = false;\n            }\n            instance->MaybeScheduleProcessQueue();\n        }\n    } raiicallbacksrunning(this);\n\n    callback();\n}\n\nvoid SingleThreadedSchedulerClient::AddToProcessQueue(std::function<void (void)> func) {\n    assert(m_pscheduler);\n\n    {\n        LOCK(m_cs_callbacks_pending);\n        m_callbacks_pending.emplace_back(std::move(func));\n    }\n    MaybeScheduleProcessQueue();\n}\n\nvoid SingleThreadedSchedulerClient::EmptyQueue() {\n    assert(!m_pscheduler->AreThreadsServicingQueue());\n    bool should_continue = true;\n    while (should_continue) {\n        ProcessQueue();\n        LOCK(m_cs_callbacks_pending);\n        should_continue = !m_callbacks_pending.empty();\n    }\n}\n\nsize_t SingleThreadedSchedulerClient::CallbacksPending() {\n    LOCK(m_cs_callbacks_pending);\n    return m_callbacks_pending.size();\n}\n","avg_line_length":33.9953271028,"max_line_length":168,"alphanum_fraction":0.6574570447,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1284,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":4.0,"content":"#include <flutter\/dart_project.h>\n#include <flutter\/flutter_view_controller.h>\n#include <windows.h>\n\n#include \"flutter_window.h\"\n#include \"utils.h\"\n\nint APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,\n                      _In_ wchar_t *command_line, _In_ int show_command) {\n  \/\/ Attach to console when present (e.g., 'flutter run') or create a\n  \/\/ new console when running with a debugger.\n  if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {\n    CreateAndAttachConsole();\n  }\n\n  \/\/ Initialize COM, so that it is available for use in the library and\/or\n  \/\/ plugins.\n  ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);\n\n  flutter::DartProject project(L\"data\");\n\n  std::vector<std::string> command_line_arguments =\n      GetCommandLineArguments();\n\n  project.set_dart_entrypoint_arguments(std::move(command_line_arguments));\n\n  FlutterWindow window(project);\n  Win32Window::Point origin(10, 10);\n  Win32Window::Size size(1280, 720);\n  if (!window.CreateAndShow(L\"material_animatedalign_1\", origin, size)) {\n    return EXIT_FAILURE;\n  }\n  window.SetQuitOnClose(true);\n\n  ::MSG msg;\n  while (::GetMessage(&msg, nullptr, 0, 0)) {\n    ::TranslateMessage(&msg);\n    ::DispatchMessage(&msg);\n  }\n\n  ::CoUninitialize();\n  return EXIT_SUCCESS;\n}\n","avg_line_length":29.1818181818,"max_line_length":75,"alphanum_fraction":0.7141744548,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1168,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#define FW_NAME \"demo-ping-node\"\n#define FW_VERSION \"1.0.0\"\n\n#include <Homie.h>\n\n#include \"DHT22Node.hpp\"\n#include \"PingNode.hpp\"\n\n\/\/ Insert your pin number(s) here\nconst int trigPin = D1;\nconst int echoPin = D2;\nconst int relayPin = D5;\nconst int dhtPin = D7;                            ;\nconst int ledPin  = LED_BUILTIN; \n\nunsigned long TEMPERATURE_INTERVAL = 120; \/\/ seconds\nunsigned long lastTemperatureUpdate = 0;\n\n\/\/ Create one node of each kind\nPingNode obstacleNode(\"obstacle\",trigPin,echoPin);\nDHT22Node airNode(\"air\",dhtPin,TEMPERATURE_INTERVAL);\n\nvoid loopHandler() {\n  if (millis() - lastTemperatureUpdate > TEMPERATURE_INTERVAL * 1000UL || lastTemperatureUpdate == 0) {\n    obstacleNode.setTemperature(airNode.getTemperature());\n    lastTemperatureUpdate = millis();\n  }\n}\n\nvoid changeHandler() {\n  Serial << \"Obstacle distance changed to: \" << obstacleNode.getDistance() << \" m\" << endl;\n}\n\nvoid setup()\n{\n  Homie_setFirmware(FW_NAME, FW_VERSION);\n\n  Serial.begin(SERIAL_SPEED);\n  Serial << endl\n         << endl;\n\n  Homie.setLoopFunction(loopHandler);\n  obstacleNode.setChangeHandler(changeHandler); \n  Homie.setup();\n}\n\nvoid loop()\n{\n  Homie.loop();\n}\n","avg_line_length":22.9019607843,"max_line_length":103,"alphanum_fraction":0.7003424658,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13321,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":1.0,"content":"\/\/\n\/\/ Copyright 2018 Pixar\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"Apache License\")\n\/\/ with the following modification; you may not use this file except in\n\/\/ compliance with the Apache License and the following modification to it:\n\/\/ Section 6. Trademarks. is deleted and replaced with:\n\/\/\n\/\/ 6. Trademarks. This License does not grant permission to use the trade\n\/\/    names, trademarks, service marks, or product names of the Licensor\n\/\/    and its affiliates, except as required to comply with Section 4(c) of\n\/\/    the License and to reproduce the content of the NOTICE file.\n\/\/\n\/\/ You may obtain a copy of the Apache License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the Apache License with the above modification is\n\/\/ distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the Apache License for the specific\n\/\/ language governing permissions and limitations under the Apache License.\n\/\/\n#include \"pxrUsdMayaGL\/usdProxyShapeAdapter.h\"\n\n#include \"pxr\/pxr.h\"\n#include \"pxrUsdMayaGL\/api.h\"\n#include \"pxrUsdMayaGL\/batchRenderer.h\"\n#include \"pxrUsdMayaGL\/debugCodes.h\"\n#include \"pxrUsdMayaGL\/renderParams.h\"\n#include \"pxrUsdMayaGL\/shapeAdapter.h\"\n#include \"usdMaya\/proxyShape.h\"\n\n#include \"pxr\/base\/gf\/vec4f.h\"\n#include \"pxr\/base\/gf\/matrix4d.h\"\n#include \"pxr\/base\/tf\/debug.h\"\n#include \"pxr\/base\/tf\/diagnostic.h\"\n#include \"pxr\/base\/tf\/staticTokens.h\"\n#include \"pxr\/base\/tf\/stringUtils.h\"\n#include \"pxr\/base\/tf\/token.h\"\n#include \"pxr\/imaging\/hd\/enums.h\"\n#include \"pxr\/imaging\/hd\/tokens.h\"\n#include \"pxr\/imaging\/hd\/renderIndex.h\"\n#include \"pxr\/imaging\/hd\/rprimCollection.h\"\n#include \"pxr\/usd\/sdf\/path.h\"\n#include \"pxr\/usd\/usd\/prim.h\"\n#include \"pxr\/usd\/usd\/timeCode.h\"\n#include \"pxr\/usdImaging\/usdImaging\/delegate.h\"\n\n#include <maya\/MColor.h>\n#include <maya\/MDagPath.h>\n#include <maya\/MFnDagNode.h>\n#include <maya\/MFrameContext.h>\n#include <maya\/MHWGeometryUtilities.h>\n#include <maya\/MMatrix.h>\n#include <maya\/MObjectHandle.h>\n#include <maya\/MPxSurfaceShape.h>\n#include <maya\/MStatus.h>\n#include <maya\/MString.h>\n\n#include <boost\/functional\/hash.hpp>\n\n#include <string>\n\n\nPXR_NAMESPACE_OPEN_SCOPE\n\n\nTF_DEFINE_PRIVATE_TOKENS(\n    _tokens,\n\n    ((RenderGuidesTag, \"render\"))\n);\n\n\n\/* virtual *\/\nbool\nPxrMayaHdUsdProxyShapeAdapter::UpdateVisibility(\n    const MSelectionList& isolatedObjects)\n{\n    bool isVisible;\n    if (!_GetVisibility(_shapeDagPath, isolatedObjects, &isVisible)) {\n        return false;\n    }\n\n    if (_delegate && _delegate->GetRootVisibility() != isVisible) {\n        _delegate->SetRootVisibility(isVisible);\n        return true;\n    }\n\n    return false;\n}\n\n\/* virtual *\/\nvoid\nPxrMayaHdUsdProxyShapeAdapter::SetRootXform(const GfMatrix4d& transform)\n{\n    _rootXform = transform;\n\n    if (_delegate) {\n        _delegate->SetRootTransform(_rootXform);\n    }\n}\n\n\/* virtual *\/\nconst SdfPath&\nPxrMayaHdUsdProxyShapeAdapter::GetDelegateID() const\n{\n    if (_delegate) {\n        return _delegate->GetDelegateID();\n    }\n\n    return SdfPath::EmptyPath();\n}\n\n\/* virtual *\/\nbool\nPxrMayaHdUsdProxyShapeAdapter::_Sync(\n        const MDagPath& shapeDagPath,\n        const unsigned int displayStyle,\n        const MHWRender::DisplayStatus displayStatus)\n{\n    UsdMayaProxyShape* usdProxyShape = \n            UsdMayaProxyShape::GetShapeAtDagPath(shapeDagPath);\n    if (!usdProxyShape) {\n        TF_WARN(\"Failed to get UsdMayaProxyShape for '%s'\",\n                shapeDagPath.fullPathName().asChar());\n        return false;\n    }\n\n    UsdPrim usdPrim;\n    SdfPathVector excludedPrimPaths;\n    int refineLevel;\n    UsdTimeCode timeCode;\n    bool showGuides;\n    bool showRenderGuides;\n    bool tint;\n    GfVec4f tintColor;\n    if (!usdProxyShape->GetAllRenderAttributes(&usdPrim,\n                                               &excludedPrimPaths,\n                                               &refineLevel,\n                                               &timeCode,\n                                               &showGuides,\n                                               &showRenderGuides,\n                                               &tint,\n                                               &tintColor)) {\n        TF_WARN(\"Failed to get render attributes for UsdMayaProxyShape.\");\n        return false;\n    }\n\n    \/\/ Check for updates to the shape or changes in the batch renderer that\n    \/\/ require us to re-initialize the shape adapter.\n    HdRenderIndex* renderIndex =\n        UsdMayaGLBatchRenderer::GetInstance().GetRenderIndex();\n    if (!(shapeDagPath == _shapeDagPath) ||\n            usdPrim != _rootPrim ||\n            excludedPrimPaths != _excludedPrimPaths ||\n            !_delegate ||\n            renderIndex != &_delegate->GetRenderIndex()) {\n        _shapeDagPath = shapeDagPath;\n        _rootPrim = usdPrim;\n        _excludedPrimPaths = excludedPrimPaths;\n\n        if (!_Init(renderIndex)) {\n            return false;\n        }\n    }\n\n    \/\/ Reset _renderParams to the defaults.\n    PxrMayaHdRenderParams renderParams;\n    _renderParams = renderParams;\n\n    if (tint) {\n        _renderParams.overrideColor = tintColor;\n    }\n\n    \/\/ XXX Not yet adding ability to turn off display of proxy geometry, but\n    \/\/ we should at some point, as in usdview.\n    TfTokenVector renderTags;\n    renderTags.push_back(HdTokens->geometry);\n    renderTags.push_back(HdTokens->proxy);\n    if (showGuides) {\n        renderTags.push_back(HdTokens->guide);\n    }\n    if (showRenderGuides) {\n        renderTags.push_back(_tokens->RenderGuidesTag);\n    }\n\n    if (_rprimCollection.GetRenderTags() != renderTags) {\n        _rprimCollection.SetRenderTags(renderTags);\n\n        TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg(\n            \"    Render tags changed: %s\\n\"\n            \"        Marking collection dirty: %s\\n\",\n            TfStringJoin(renderTags.begin(), renderTags.end()).c_str(),\n            _rprimCollection.GetName().GetText());\n\n        _delegate->GetRenderIndex().GetChangeTracker().MarkCollectionDirty(\n            _rprimCollection.GetName());\n    }\n\n    MStatus status;\n    const MMatrix transform = _shapeDagPath.inclusiveMatrix(&status);\n    if (status == MS::kSuccess) {\n        _rootXform = GfMatrix4d(transform.matrix);\n        _delegate->SetRootTransform(_rootXform);\n    }\n\n    _delegate->SetRefineLevelFallback(refineLevel);\n\n    \/\/ Will only react if time actually changes.\n    _delegate->SetTime(timeCode);\n\n    _drawShape = true;\n    _drawBoundingBox =\n        (displayStyle & MHWRender::MFrameContext::DisplayStyle::kBoundingBox);\n\n    MColor mayaWireframeColor;\n    const bool needsWire = _GetWireframeColor(displayStyle,\n                                              displayStatus,\n                                              _shapeDagPath,\n                                              &mayaWireframeColor);\n    if (needsWire) {\n        _renderParams.wireframeColor = GfVec4f(mayaWireframeColor.r,\n                                               mayaWireframeColor.g,\n                                               mayaWireframeColor.b,\n                                               1.0f);\n    }\n\n    TfToken reprName;\n\n    \/\/ Maya 2015 lacks MHWRender::MFrameContext::DisplayStyle::kFlatShaded for\n    \/\/ whatever reason...\n    const bool flatShaded =\n#if MAYA_API_VERSION >= 201600\n        displayStyle & MHWRender::MFrameContext::DisplayStyle::kFlatShaded;\n#else\n        false;\n#endif\n\n    if (flatShaded) {\n        if (needsWire) {\n            reprName = HdTokens->wireOnSurf;\n        } else {\n            reprName = HdTokens->hull;\n        }\n    }\n    else if (displayStyle & MHWRender::MFrameContext::DisplayStyle::kGouraudShaded)\n    {\n        if (needsWire || (displayStyle & MHWRender::MFrameContext::DisplayStyle::kWireFrame)) {\n            reprName = HdTokens->refinedWireOnSurf;\n        } else {\n            reprName = HdTokens->refined;\n        }\n    }\n    else if (displayStyle & MHWRender::MFrameContext::DisplayStyle::kWireFrame)\n    {\n        reprName = HdTokens->refinedWire;\n        _renderParams.enableLighting = false;\n    }\n    else\n    {\n        _drawShape = false;\n    }\n\n    if (_delegate->GetRootVisibility() != _drawShape) {\n        _delegate->SetRootVisibility(_drawShape);\n    }\n\n    if (_rprimCollection.GetReprName() != reprName) {\n        _rprimCollection.SetReprName(reprName);\n\n        TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg(\n                \"    Repr name changed: %s\\n\"\n                \"        Marking collection dirty: %s\\n\",\n                reprName.GetText(),\n                _rprimCollection.GetName().GetText());\n\n        _delegate->GetRenderIndex().GetChangeTracker().MarkCollectionDirty(\n            _rprimCollection.GetName());\n    }\n\n    \/\/ Maya 2016 SP2 lacks MHWRender::MFrameContext::DisplayStyle::kBackfaceCulling\n    \/\/ for whatever reason...\n    HdCullStyle cullStyle = HdCullStyleNothing;\n#if MAYA_API_VERSION >= 201603\n    if (displayStyle & MHWRender::MFrameContext::DisplayStyle::kBackfaceCulling) {\n        cullStyle = HdCullStyleBackUnlessDoubleSided;\n    }\n#endif\n\n    _delegate->SetCullStyleFallback(cullStyle);\n\n    return true;\n}\n\nbool\nPxrMayaHdUsdProxyShapeAdapter::_Init(HdRenderIndex* renderIndex)\n{\n    if (!TF_VERIFY(renderIndex,\n                   \"Cannot initialize shape adapter with invalid HdRenderIndex\")) {\n        return false;\n    }\n\n    const SdfPath delegatePrefix =\n        UsdMayaGLBatchRenderer::GetInstance().GetDelegatePrefix(_isViewport2);\n\n    \/\/ Create a simple \"name\" for this shape adapter to insert into the batch\n    \/\/ renderer's SdfPath hierarchy.\n    \/\/\n    \/\/ XXX: For as long as we're using the MAYA_VP2_USE_VP1_SELECTION\n    \/\/ environment variable, we need to be able to pass responsibility back and\n    \/\/ forth between the MPxDrawOverride's shape adapter for drawing and the\n    \/\/ MPxSurfaceShapeUI's shape adapter for selection. This requires both\n    \/\/ shape adapters to have the same \"name\", which forces us to build it\n    \/\/ from data on the shape that will be common to both classes, as we do\n    \/\/ below. When we remove MAYA_VP2_USE_VP1_SELECTION and can trust that a\n    \/\/ single shape adapter handles both drawing and selection, we can do\n    \/\/ something even simpler instead like using the shape adapter's memory\n    \/\/ address as the \"name\".\n    size_t shapeHash(MObjectHandle(_shapeDagPath.transform()).hashCode());\n    boost::hash_combine(shapeHash, _rootPrim);\n    boost::hash_combine(shapeHash, _excludedPrimPaths);\n\n    \/\/ We prepend the Maya type name to the beginning of the delegate name to\n    \/\/ ensure that there are no name collisions between shape adapters of\n    \/\/ shapes with different Maya types.\n    const TfToken delegateName(\n        TfStringPrintf(\"%s_%zx\",\n                       UsdMayaProxyShapeTokens->MayaTypeName.GetText(),\n                       shapeHash));\n\n    const SdfPath delegateId = delegatePrefix.AppendChild(delegateName);\n\n    if (_delegate &&\n            delegateId == GetDelegateID() &&\n            renderIndex == &_delegate->GetRenderIndex()) {\n        \/\/ The delegate's current ID matches the delegate ID we computed and\n        \/\/ the render index matches, so it must be up to date already.\n        return true;\n    }\n\n    const TfToken collectionName(_shapeDagPath.fullPathName().asChar());\n\n    TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg(\n        \"Initializing PxrMayaHdUsdProxyShapeAdapter: %p\\n\"\n        \"    collection name: %s\\n\"\n        \"    delegateId     : %s\\n\",\n        this,\n        collectionName.GetText(),\n        delegateId.GetText());\n\n    _delegate.reset(new UsdImagingDelegate(renderIndex, delegateId));\n    if (!TF_VERIFY(_delegate,\n                  \"Failed to create shape adapter delegate for shape %s\",\n                  _shapeDagPath.fullPathName().asChar())) {\n        return false;\n    }\n\n    if (TfDebug::IsEnabled(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE)) {\n        TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg(\n            \"    Populating delegate:\\n\"\n            \"        rootPrim         : %s\\n\"\n            \"        excludedPrimPaths: \",\n            _rootPrim.GetPath().GetText());\n        for (const SdfPath& primPath : _excludedPrimPaths) {\n            TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg(\n                \"%s \",\n                primPath.GetText());\n        }\n        TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg(\"\\n\");\n    }\n\n    _delegate->Populate(_rootPrim, _excludedPrimPaths, SdfPathVector());\n\n    if (collectionName != _rprimCollection.GetName()) {\n        _rprimCollection.SetName(collectionName);\n        renderIndex->GetChangeTracker().AddCollection(_rprimCollection.GetName());\n    }\n\n    _rprimCollection.SetReprName(HdTokens->refined);\n    _rprimCollection.SetRootPath(delegateId);\n\n    return true;\n}\n\nPxrMayaHdUsdProxyShapeAdapter::PxrMayaHdUsdProxyShapeAdapter()\n{\n    TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg(\n        \"Constructing PxrMayaHdUsdProxyShapeAdapter: %p\\n\",\n        this);\n}\n\n\/* virtual *\/\nPxrMayaHdUsdProxyShapeAdapter::~PxrMayaHdUsdProxyShapeAdapter()\n{\n    TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg(\n        \"Destructing PxrMayaHdUsdProxyShapeAdapter: %p\\n\",\n        this);\n}\n\n\nPXR_NAMESPACE_CLOSE_SCOPE\n","avg_line_length":32.9727722772,"max_line_length":95,"alphanum_fraction":0.6513024548,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2217,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/** --------------------------------------------------------------------------------------------------------------------\n* <copyright company=\"Aspose\" file=\"CreateFolderRequest.cpp\">\n*   Copyright (c) 2020 Aspose.Words for Cloud\n* <\/copyright>\n* <summary>\n*   Permission is hereby granted, free of charge, to any person obtaining a copy\n*  of this software and associated documentation files (the \"Software\"), to deal\n*  in the Software without restriction, including without limitation the rights\n*  to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n*  copies of the Software, and to permit persons to whom the Software is\n*  furnished to do so, subject to the following conditions:\n* \n*  The above copyright notice and this permission notice shall be included in all\n*  copies or substantial portions of the Software.\n* \n*  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n*  SOFTWARE.\n* <\/summary> \n-------------------------------------------------------------------------------------------------------------------- **\/\n\n#include \"CreateFolderRequest.h\"\nnamespace aspose {\nnamespace words {\nnamespace cloud {\nnamespace api {\nnamespace models {\nCreateFolderRequest::CreateFolderRequest(\n    utility::string_t path,\n    boost::optional< utility::string_t > storageName\n) : m_Path(std::move(path)),\nm_StorageName(std::move(storageName))\n{\n}\n\nutility::string_t CreateFolderRequest::getPath() const\n{\n    return m_Path;\n}\n\nvoid CreateFolderRequest::setPath(utility::string_t path)\n{\n    m_Path = std::move(path);\n}\n\nboost::optional< utility::string_t > CreateFolderRequest::getStorageName() const\n{\n    return m_StorageName;\n}\n\nvoid CreateFolderRequest::setStorageName(boost::optional< utility::string_t > storageName)\n{\n    m_StorageName = std::move(storageName);\n}\n\n}\n}\n}\n}\n}\n","avg_line_length":34.1076923077,"max_line_length":120,"alphanum_fraction":0.6707262066,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3983,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"editaddressdialog.h\"\n#include \"ui_editaddressdialog.h\"\n\n#include \"addresstablemodel.h\"\n#include \"guiutil.h\"\n\n#include <QDataWidgetMapper>\n#include <QMessageBox>\n\nEditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :\n    QDialog(parent),\n    ui(new Ui::EditAddressDialog),\n    mapper(0),\n    mode(mode),\n    model(0)\n{\n    ui->setupUi(this);\n\n    GUIUtil::setupAddressWidget(ui->addressEdit, this);\n\n    switch(mode)\n    {\n    case NewReceivingAddress:\n        setWindowTitle(tr(\"New receiving address\"));\n        ui->addressEdit->setEnabled(false);\n        break;\n    case NewSendingAddress:\n        setWindowTitle(tr(\"New sending address\"));\n        break;\n    case EditReceivingAddress:\n        setWindowTitle(tr(\"Edit receiving address\"));\n        ui->addressEdit->setEnabled(false);\n        break;\n    case EditSendingAddress:\n        setWindowTitle(tr(\"Edit sending address\"));\n        break;\n    }\n\n    mapper = new QDataWidgetMapper(this);\n    mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);\n}\n\nEditAddressDialog::~EditAddressDialog()\n{\n    delete ui;\n}\n\nvoid EditAddressDialog::setModel(AddressTableModel *model)\n{\n    this->model = model;\n    if(!model)\n        return;\n\n    mapper->setModel(model);\n    mapper->addMapping(ui->labelEdit, AddressTableModel::Label);\n    mapper->addMapping(ui->addressEdit, AddressTableModel::Address);\n}\n\nvoid EditAddressDialog::loadRow(int row)\n{\n    mapper->setCurrentIndex(row);\n}\n\nbool EditAddressDialog::saveCurrentRow()\n{\n    if(!model)\n        return false;\n\n    switch(mode)\n    {\n    case NewReceivingAddress:\n    case NewSendingAddress:\n        address = model->addRow(\n                mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,\n                ui->labelEdit->text(),\n                ui->addressEdit->text());\n        break;\n    case EditReceivingAddress:\n    case EditSendingAddress:\n        if(mapper->submit())\n        {\n            address = ui->addressEdit->text();\n        }\n        break;\n    }\n    return !address.isEmpty();\n}\n\nvoid EditAddressDialog::accept()\n{\n    if(!model)\n        return;\n\n    if(!saveCurrentRow())\n    {\n        switch(model->getEditStatus())\n        {\n        case AddressTableModel::OK:\n            \/\/ Failed with unknown reason. Just reject.\n            break;\n        case AddressTableModel::NO_CHANGES:\n            \/\/ No changes were made during edit operation. Just reject.\n            break;\n        case AddressTableModel::INVALID_ADDRESS:\n            QMessageBox::warning(this, windowTitle(),\n                tr(\"The entered address \\\"%1\\\" is not a valid Lexium address.\").arg(ui->addressEdit->text()),\n                QMessageBox::Ok, QMessageBox::Ok);\n            break;\n        case AddressTableModel::DUPLICATE_ADDRESS:\n            QMessageBox::warning(this, windowTitle(),\n                tr(\"The entered address \\\"%1\\\" is already in the address book.\").arg(ui->addressEdit->text()),\n                QMessageBox::Ok, QMessageBox::Ok);\n            break;\n        case AddressTableModel::WALLET_UNLOCK_FAILURE:\n            QMessageBox::critical(this, windowTitle(),\n                tr(\"Could not unlock wallet.\"),\n                QMessageBox::Ok, QMessageBox::Ok);\n            break;\n        case AddressTableModel::KEY_GENERATION_FAILURE:\n            QMessageBox::critical(this, windowTitle(),\n                tr(\"New key generation failed.\"),\n                QMessageBox::Ok, QMessageBox::Ok);\n            break;\n\n        }\n        return;\n    }\n    QDialog::accept();\n}\n\nQString EditAddressDialog::getAddress() const\n{\n    return address;\n}\n\nvoid EditAddressDialog::setAddress(const QString &address)\n{\n    this->address = address;\n    ui->addressEdit->setText(address);\n}\n","avg_line_length":27.2808219178,"max_line_length":110,"alphanum_fraction":0.6274165202,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3219,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":62.0,"content":"#include \"Utils.h\"\n\n\nuint64_t XCP::Bitconverter::ToUint64(const std::vector<uint8_t>& bytes, bool LittleEndian)\n{\n\tif (bytes.size() == 8)\n\t{\n\t\tif (LittleEndian)\n\t\t{\n\t\t\treturn (((uint64_t)bytes[7]) << 56) | (((uint64_t)bytes[6]) << 48) | (((uint64_t)bytes[5]) << 40) | (((uint64_t)bytes[4])<<32) |\n\t\t\t\t(((uint64_t)bytes[3]) << 24) | (((uint64_t)bytes[2]) << 16) | (((uint64_t)bytes[1]) << 8) | bytes[0];\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/do byte-swap\n\t\t\treturn (((uint64_t)bytes[0]) << 56) | (((uint64_t)bytes[1]) << 48) | (((uint64_t)bytes[2]) << 40) | (((uint64_t)bytes[3]) << 32) |\n\t\t\t\t(((uint64_t)bytes[4]) << 24) | (((uint64_t)bytes[5]) << 16) | (((uint64_t)bytes[6]) << 8) | bytes[7];\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 0;\n\t}\n}\n\nint64_t XCP::Bitconverter::ToInt64(const std::vector<uint8_t>& bytes, bool LittleEndian)\n{\n\tif (bytes.size() == 8)\n\t{\n\t\tif (LittleEndian)\n\t\t{\n\t\t\treturn (int64_t)((((uint64_t)bytes[7]) << 56) | (((uint64_t)bytes[6]) << 48) | (((uint64_t)bytes[5]) << 40) | (((uint64_t)bytes[4]) << 32) |\n\t\t\t\t(((uint64_t)bytes[3]) << 24) | (((uint64_t)bytes[2]) << 16) | (((uint64_t)bytes[1]) << 8) | bytes[0]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/do byte-swap\n\t\t\treturn (int64_t)((((uint64_t)bytes[0]) << 56) | (((uint64_t)bytes[1]) << 48) | (((uint64_t)bytes[2]) << 40) | (((uint64_t)bytes[3]) << 32) |\n\t\t\t\t(((uint64_t)bytes[4]) << 24) | (((uint64_t)bytes[5]) << 16) | (((uint64_t)bytes[6]) << 8) | bytes[7]);\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 0;\n\t}\n}\n\nuint32_t XCP::Bitconverter::ToUint32(const std::vector<uint8_t>& bytes, bool LittleEndian)\n{\n\tif (bytes.size() == 4)\n\t{\n\t\tif (LittleEndian)\n\t\t{\n\t\t\treturn  (((uint32_t)bytes[3]) << 24) | (((uint32_t)bytes[2]) << 16) | (((uint32_t)bytes[1]) << 8) | bytes[0];\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/do byte-swap\n\t\t\treturn (((uint32_t)bytes[0]) << 24) | (((uint32_t)bytes[1]) << 16) | (((uint32_t)bytes[2]) << 8) | bytes[3];\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 0;\n\t}\n}\n\nint32_t XCP::Bitconverter::ToInt32(const std::vector<uint8_t>& bytes, bool LittleEndian)\n{\n\tif (bytes.size() == 4)\n\t{\n\t\tif (LittleEndian)\n\t\t{\n\t\t\treturn  (int32_t)((((uint32_t)bytes[3]) << 24) | (((uint32_t)bytes[2]) << 16) | (((uint32_t)bytes[1]) << 8) | bytes[0]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/do byte-swap\n\t\t\treturn (int32_t)((((uint32_t)bytes[0]) << 24) | (((uint32_t)bytes[1]) << 16) | (((uint32_t)bytes[2]) << 8) | bytes[3]);\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 0;\n\t}\n}\n\nuint16_t XCP::Bitconverter::ToUint16(const std::vector<uint8_t>& bytes, bool LittleEndian)\n{\n\tif (bytes.size() == 2)\n\t{\n\t\tif (LittleEndian)\n\t\t{\n\t\t\treturn  (((uint16_t)bytes[1]) << 8) | bytes[0];\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/do byte-swap\n\t\t\treturn ((((uint16_t)bytes[0]) << 8) | ((uint32_t)bytes[1]));\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 0;\n\t}\n}\n\nint16_t XCP::Bitconverter::ToInt16(const std::vector<uint8_t>& bytes, bool LittleEndian)\n{\n\tif (bytes.size() == 2)\n\t{\n\t\tif (LittleEndian)\n\t\t{\n\t\t\treturn  (int16_t)((((uint16_t)bytes[1]) << 8) | bytes[0]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/do byte-swap\n\t\t\treturn (int16_t)((((uint16_t)bytes[0]) << 8) | ((uint32_t)bytes[1]));\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 0;\n\t}\n}\n\nfloat XCP::Bitconverter::ToFloat(const std::vector<uint8_t>& bytes, bool LittleEndian)\n{\n\tthrow - 1;\n\treturn 0.0f;\n}\n\ndouble XCP::Bitconverter::ToDouble(const std::vector<uint8_t>& bytes, bool LittleEndian)\n{\n\tthrow - 1;\n\treturn 0.0;\n}\n","avg_line_length":23.1582733813,"max_line_length":143,"alphanum_fraction":0.5635290463,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":42316,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"#include <nano\/crypto_lib\/random_pool.hpp>\n#include <nano\/lib\/threading.hpp>\n#include <nano\/node\/lmdb\/wallet_value.hpp>\n#include <nano\/node\/testing.hpp>\n#include <nano\/test_common\/testutil.hpp>\n\n#include <gtest\/gtest.h>\n\n#include <boost\/filesystem.hpp>\n\nusing namespace std::chrono_literals;\nunsigned constexpr nano::wallet_store::version_current;\n\nTEST (wallet, no_special_keys_accounts)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tASSERT_FALSE (init);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (init);\n\tnano::keypair key1;\n\tASSERT_FALSE (wallet.exists (transaction, key1.pub));\n\twallet.insert_adhoc (transaction, key1.prv);\n\tASSERT_TRUE (wallet.exists (transaction, key1.pub));\n\n\tfor (uint64_t account = 0; account < nano::wallet_store::special_count; account++)\n\t{\n\t\tnano::account account_l (account);\n\t\tASSERT_FALSE (wallet.exists (transaction, account_l));\n\t}\n}\n\nTEST (wallet, no_key)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tASSERT_FALSE (init);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (init);\n\tnano::keypair key1;\n\tnano::raw_key prv1;\n\tASSERT_TRUE (wallet.fetch (transaction, key1.pub, prv1));\n\tASSERT_TRUE (wallet.valid_password (transaction));\n}\n\nTEST (wallet, fetch_locked)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tASSERT_FALSE (init);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_TRUE (wallet.valid_password (transaction));\n\tnano::keypair key1;\n\tASSERT_EQ (key1.pub, wallet.insert_adhoc (transaction, key1.prv));\n\tauto key2 (wallet.deterministic_insert (transaction));\n\tASSERT_FALSE (key2.is_zero ());\n\tnano::raw_key key3;\n\tkey3 = 1;\n\twallet.password.value_set (key3);\n\tASSERT_FALSE (wallet.valid_password (transaction));\n\tnano::raw_key key4;\n\tASSERT_TRUE (wallet.fetch (transaction, key1.pub, key4));\n\tASSERT_TRUE (wallet.fetch (transaction, key2, key4));\n}\n\nTEST (wallet, retrieval)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tASSERT_FALSE (init);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (init);\n\tnano::keypair key1;\n\tASSERT_TRUE (wallet.valid_password (transaction));\n\twallet.insert_adhoc (transaction, key1.prv);\n\tnano::raw_key prv1;\n\tASSERT_FALSE (wallet.fetch (transaction, key1.pub, prv1));\n\tASSERT_TRUE (wallet.valid_password (transaction));\n\tASSERT_EQ (key1.prv, prv1);\n\twallet.password.values[0]->bytes[16] ^= 1;\n\tnano::raw_key prv2;\n\tASSERT_TRUE (wallet.fetch (transaction, key1.pub, prv2));\n\tASSERT_FALSE (wallet.valid_password (transaction));\n}\n\nTEST (wallet, empty_iteration)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tASSERT_FALSE (init);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (init);\n\tauto i (wallet.begin (transaction));\n\tauto j (wallet.end ());\n\tASSERT_EQ (i, j);\n}\n\nTEST (wallet, one_item_iteration)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tASSERT_FALSE (init);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (init);\n\tnano::keypair key1;\n\twallet.insert_adhoc (transaction, key1.prv);\n\tfor (auto i (wallet.begin (transaction)), j (wallet.end ()); i != j; ++i)\n\t{\n\t\tASSERT_EQ (key1.pub, nano::uint256_union (i->first));\n\t\tnano::raw_key password;\n\t\twallet.wallet_key (password, transaction);\n\t\tnano::raw_key key;\n\t\tkey.decrypt (nano::wallet_value (i->second).key, password, (nano::uint256_union (i->first)).owords[0].number ());\n\t\tASSERT_EQ (key1.prv, key);\n\t}\n}\n\nTEST (wallet, two_item_iteration)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tASSERT_FALSE (init);\n\tnano::keypair key1;\n\tnano::keypair key2;\n\tASSERT_NE (key1.pub, key2.pub);\n\tstd::unordered_set<nano::public_key> pubs;\n\tstd::unordered_set<nano::raw_key> prvs;\n\tnano::kdf kdf;\n\t{\n\t\tauto transaction (env.tx_begin_write ());\n\t\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\t\tASSERT_FALSE (init);\n\t\twallet.insert_adhoc (transaction, key1.prv);\n\t\twallet.insert_adhoc (transaction, key2.prv);\n\t\tfor (auto i (wallet.begin (transaction)), j (wallet.end ()); i != j; ++i)\n\t\t{\n\t\t\tpubs.insert (i->first);\n\t\t\tnano::raw_key password;\n\t\t\twallet.wallet_key (password, transaction);\n\t\t\tnano::raw_key key;\n\t\t\tkey.decrypt (nano::wallet_value (i->second).key, password, (i->first).owords[0].number ());\n\t\t\tprvs.insert (key);\n\t\t}\n\t}\n\tASSERT_EQ (2, pubs.size ());\n\tASSERT_EQ (2, prvs.size ());\n\tASSERT_NE (pubs.end (), pubs.find (key1.pub));\n\tASSERT_NE (prvs.end (), prvs.find (key1.prv));\n\tASSERT_NE (pubs.end (), pubs.find (key2.pub));\n\tASSERT_NE (prvs.end (), prvs.find (key2.prv));\n}\n\nTEST (wallet, insufficient_spend_one)\n{\n\tnano::system system (1);\n\tnano::keypair key1;\n\tsystem.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv);\n\tauto block (system.wallet (0)->send_action (nano::dev_genesis_key.pub, key1.pub, 500));\n\tASSERT_NE (nullptr, block);\n\tASSERT_EQ (nullptr, system.wallet (0)->send_action (nano::dev_genesis_key.pub, key1.pub, nano::genesis_amount));\n}\n\nTEST (wallet, spend_all_one)\n{\n\tnano::system system (1);\n\tauto & node1 (*system.nodes[0]);\n\tnano::block_hash latest1 (node1.latest (nano::dev_genesis_key.pub));\n\tsystem.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv);\n\tnano::keypair key2;\n\tASSERT_NE (nullptr, system.wallet (0)->send_action (nano::dev_genesis_key.pub, key2.pub, std::numeric_limits<nano::uint128_t>::max ()));\n\tnano::account_info info2;\n\t{\n\t\tauto transaction (node1.store.tx_begin_read ());\n\t\tnode1.store.account_get (transaction, nano::dev_genesis_key.pub, info2);\n\t\tASSERT_NE (latest1, info2.head);\n\t\tauto block (node1.store.block_get (transaction, info2.head));\n\t\tASSERT_NE (nullptr, block);\n\t\tASSERT_EQ (latest1, block->previous ());\n\t}\n\tASSERT_TRUE (info2.balance.is_zero ());\n\tASSERT_EQ (0, node1.balance (nano::dev_genesis_key.pub));\n}\n\nTEST (wallet, send_async)\n{\n\tnano::system system (1);\n\tsystem.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv);\n\tnano::keypair key2;\n\tstd::thread thread ([&system] () {\n\t\tASSERT_TIMELY (10s, system.nodes[0]->balance (nano::dev_genesis_key.pub).is_zero ());\n\t});\n\tstd::atomic<bool> success (false);\n\tsystem.wallet (0)->send_async (nano::dev_genesis_key.pub, key2.pub, std::numeric_limits<nano::uint128_t>::max (), [&success] (std::shared_ptr<nano::block> const & block_a) { ASSERT_NE (nullptr, block_a); success = true; });\n\tthread.join ();\n\tASSERT_TIMELY (2s, success);\n}\n\nTEST (wallet, spend)\n{\n\tnano::system system (1);\n\tauto & node1 (*system.nodes[0]);\n\tnano::block_hash latest1 (node1.latest (nano::dev_genesis_key.pub));\n\tsystem.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv);\n\tnano::keypair key2;\n\t\/\/ Sending from empty accounts should always be an error.  Accounts need to be opened with an open block, not a send block.\n\tASSERT_EQ (nullptr, system.wallet (0)->send_action (0, key2.pub, 0));\n\tASSERT_NE (nullptr, system.wallet (0)->send_action (nano::dev_genesis_key.pub, key2.pub, std::numeric_limits<nano::uint128_t>::max ()));\n\tnano::account_info info2;\n\t{\n\t\tauto transaction (node1.store.tx_begin_read ());\n\t\tnode1.store.account_get (transaction, nano::dev_genesis_key.pub, info2);\n\t\tASSERT_NE (latest1, info2.head);\n\t\tauto block (node1.store.block_get (transaction, info2.head));\n\t\tASSERT_NE (nullptr, block);\n\t\tASSERT_EQ (latest1, block->previous ());\n\t}\n\tASSERT_TRUE (info2.balance.is_zero ());\n\tASSERT_EQ (0, node1.balance (nano::dev_genesis_key.pub));\n}\n\nTEST (wallet, change)\n{\n\tnano::system system (1);\n\tsystem.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv);\n\tnano::keypair key2;\n\tauto block1 (system.nodes[0]->rep_block (nano::dev_genesis_key.pub));\n\tASSERT_FALSE (block1.is_zero ());\n\tASSERT_NE (nullptr, system.wallet (0)->change_action (nano::dev_genesis_key.pub, key2.pub));\n\tauto block2 (system.nodes[0]->rep_block (nano::dev_genesis_key.pub));\n\tASSERT_FALSE (block2.is_zero ());\n\tASSERT_NE (block1, block2);\n}\n\nTEST (wallet, partial_spend)\n{\n\tnano::system system (1);\n\tsystem.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv);\n\tnano::keypair key2;\n\tASSERT_NE (nullptr, system.wallet (0)->send_action (nano::dev_genesis_key.pub, key2.pub, 500));\n\tASSERT_EQ (std::numeric_limits<nano::uint128_t>::max () - 500, system.nodes[0]->balance (nano::dev_genesis_key.pub));\n}\n\nTEST (wallet, spend_no_previous)\n{\n\tnano::system system (1);\n\t{\n\t\tsystem.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv);\n\t\tauto transaction (system.nodes[0]->store.tx_begin_read ());\n\t\tnano::account_info info1;\n\t\tASSERT_FALSE (system.nodes[0]->store.account_get (transaction, nano::dev_genesis_key.pub, info1));\n\t\tfor (auto i (0); i < 50; ++i)\n\t\t{\n\t\t\tnano::keypair key;\n\t\t\tsystem.wallet (0)->insert_adhoc (key.prv);\n\t\t}\n\t}\n\tnano::keypair key2;\n\tASSERT_NE (nullptr, system.wallet (0)->send_action (nano::dev_genesis_key.pub, key2.pub, 500));\n\tASSERT_EQ (std::numeric_limits<nano::uint128_t>::max () - 500, system.nodes[0]->balance (nano::dev_genesis_key.pub));\n}\n\nTEST (wallet, find_none)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tASSERT_FALSE (init);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (init);\n\tnano::account account (1000);\n\tASSERT_EQ (wallet.end (), wallet.find (transaction, account));\n}\n\nTEST (wallet, find_existing)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tASSERT_FALSE (init);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (init);\n\tnano::keypair key1;\n\tASSERT_FALSE (wallet.exists (transaction, key1.pub));\n\twallet.insert_adhoc (transaction, key1.prv);\n\tASSERT_TRUE (wallet.exists (transaction, key1.pub));\n\tauto existing (wallet.find (transaction, key1.pub));\n\tASSERT_NE (wallet.end (), existing);\n\t++existing;\n\tASSERT_EQ (wallet.end (), existing);\n}\n\nTEST (wallet, rekey)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tASSERT_FALSE (init);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (init);\n\tnano::raw_key password;\n\twallet.password.value (password);\n\tASSERT_TRUE (password.is_zero ());\n\tASSERT_FALSE (init);\n\tnano::keypair key1;\n\twallet.insert_adhoc (transaction, key1.prv);\n\tnano::raw_key prv1;\n\twallet.fetch (transaction, key1.pub, prv1);\n\tASSERT_EQ (key1.prv, prv1);\n\tASSERT_FALSE (wallet.rekey (transaction, \"1\"));\n\twallet.password.value (password);\n\tnano::raw_key password1;\n\twallet.derive_key (password1, transaction, \"1\");\n\tASSERT_EQ (password1, password);\n\tnano::raw_key prv2;\n\twallet.fetch (transaction, key1.pub, prv2);\n\tASSERT_EQ (key1.prv, prv2);\n\t*wallet.password.values[0] = 2;\n\tASSERT_TRUE (wallet.rekey (transaction, \"2\"));\n}\n\nTEST (account, encode_zero)\n{\n\tnano::account number0 (0);\n\tstd::string str0;\n\tnumber0.encode_account (str0);\n\n\t\/*\n\t * Handle different lengths for \"xrb_\" prefixed and \"nano_\" prefixed accounts\n\t *\/\n\tASSERT_EQ ((str0.front () == 'x') ? 64 : 65, str0.size ());\n\tASSERT_EQ (65, str0.size ());\n\tnano::account number1;\n\tASSERT_FALSE (number1.decode_account (str0));\n\tASSERT_EQ (number0, number1);\n}\n\nTEST (account, encode_all)\n{\n\tnano::account number0;\n\tnumber0.decode_hex (\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\n\tstd::string str0;\n\tnumber0.encode_account (str0);\n\n\t\/*\n\t * Handle different lengths for \"xrb_\" prefixed and \"nano_\" prefixed accounts\n\t *\/\n\tASSERT_EQ ((str0.front () == 'x') ? 64 : 65, str0.size ());\n\tnano::account number1;\n\tASSERT_FALSE (number1.decode_account (str0));\n\tASSERT_EQ (number0, number1);\n}\n\nTEST (account, encode_fail)\n{\n\tnano::account number0 (0);\n\tstd::string str0;\n\tnumber0.encode_account (str0);\n\tstr0[16] ^= 1;\n\tnano::account number1;\n\tASSERT_TRUE (number1.decode_account (str0));\n}\n\nTEST (wallet, hash_password)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tASSERT_FALSE (init);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (init);\n\tnano::raw_key hash1;\n\twallet.derive_key (hash1, transaction, \"\");\n\tnano::raw_key hash2;\n\twallet.derive_key (hash2, transaction, \"\");\n\tASSERT_EQ (hash1, hash2);\n\tnano::raw_key hash3;\n\twallet.derive_key (hash3, transaction, \"a\");\n\tASSERT_NE (hash1, hash3);\n}\n\nTEST (fan, reconstitute)\n{\n\tnano::raw_key value0 (0);\n\tnano::fan fan (value0, 1024);\n\tfor (auto & i : fan.values)\n\t{\n\t\tASSERT_NE (value0, *i);\n\t}\n\tnano::raw_key value1;\n\tfan.value (value1);\n\tASSERT_EQ (value0, value1);\n}\n\nTEST (fan, change)\n{\n\tnano::raw_key value0;\n\tvalue0 = 0;\n\tnano::raw_key value1;\n\tvalue1 = 1;\n\tASSERT_NE (value0, value1);\n\tnano::fan fan (value0, 1024);\n\tASSERT_EQ (1024, fan.values.size ());\n\tnano::raw_key value2;\n\tfan.value (value2);\n\tASSERT_EQ (value0, value2);\n\tfan.value_set (value1);\n\tfan.value (value2);\n\tASSERT_EQ (value1, value2);\n}\n\nTEST (wallet, reopen_default_password)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tauto transaction (env.tx_begin_write ());\n\tASSERT_FALSE (init);\n\tnano::kdf kdf;\n\t{\n\t\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\t\tASSERT_FALSE (init);\n\t\tASSERT_TRUE (wallet.valid_password (transaction));\n\t}\n\t{\n\t\tbool init;\n\t\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\t\tASSERT_FALSE (init);\n\t\tASSERT_TRUE (wallet.valid_password (transaction));\n\t}\n\t{\n\t\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\t\tASSERT_FALSE (init);\n\t\twallet.rekey (transaction, \"\");\n\t\tASSERT_TRUE (wallet.valid_password (transaction));\n\t}\n\t{\n\t\tbool init;\n\t\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\t\tASSERT_FALSE (init);\n\t\tASSERT_FALSE (wallet.valid_password (transaction));\n\t\twallet.attempt_password (transaction, \" \");\n\t\tASSERT_FALSE (wallet.valid_password (transaction));\n\t\twallet.attempt_password (transaction, \"\");\n\t\tASSERT_TRUE (wallet.valid_password (transaction));\n\t}\n}\n\nTEST (wallet, representative)\n{\n\tauto error (false);\n\tnano::mdb_env env (error, nano::unique_path ());\n\tASSERT_FALSE (error);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet (error, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (error);\n\tASSERT_FALSE (wallet.is_representative (transaction));\n\tASSERT_EQ (nano::genesis_account, wallet.representative (transaction));\n\tASSERT_FALSE (wallet.is_representative (transaction));\n\tnano::keypair key;\n\twallet.representative_set (transaction, key.pub);\n\tASSERT_FALSE (wallet.is_representative (transaction));\n\tASSERT_EQ (key.pub, wallet.representative (transaction));\n\tASSERT_FALSE (wallet.is_representative (transaction));\n\twallet.insert_adhoc (transaction, key.prv);\n\tASSERT_TRUE (wallet.is_representative (transaction));\n}\n\nTEST (wallet, serialize_json_empty)\n{\n\tauto error (false);\n\tnano::mdb_env env (error, nano::unique_path ());\n\tASSERT_FALSE (error);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet1 (error, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (error);\n\tstd::string serialized;\n\twallet1.serialize_json (transaction, serialized);\n\tnano::wallet_store wallet2 (error, kdf, transaction, nano::genesis_account, 1, \"1\", serialized);\n\tASSERT_FALSE (error);\n\tnano::raw_key password1;\n\tnano::raw_key password2;\n\twallet1.wallet_key (password1, transaction);\n\twallet2.wallet_key (password2, transaction);\n\tASSERT_EQ (password1, password2);\n\tASSERT_EQ (wallet1.salt (transaction), wallet2.salt (transaction));\n\tASSERT_EQ (wallet1.check (transaction), wallet2.check (transaction));\n\tASSERT_EQ (wallet1.representative (transaction), wallet2.representative (transaction));\n\tASSERT_EQ (wallet1.end (), wallet1.begin (transaction));\n\tASSERT_EQ (wallet2.end (), wallet2.begin (transaction));\n}\n\nTEST (wallet, serialize_json_one)\n{\n\tauto error (false);\n\tnano::mdb_env env (error, nano::unique_path ());\n\tASSERT_FALSE (error);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet1 (error, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (error);\n\tnano::keypair key;\n\twallet1.insert_adhoc (transaction, key.prv);\n\tstd::string serialized;\n\twallet1.serialize_json (transaction, serialized);\n\tnano::wallet_store wallet2 (error, kdf, transaction, nano::genesis_account, 1, \"1\", serialized);\n\tASSERT_FALSE (error);\n\tnano::raw_key password1;\n\tnano::raw_key password2;\n\twallet1.wallet_key (password1, transaction);\n\twallet2.wallet_key (password2, transaction);\n\tASSERT_EQ (password1, password2);\n\tASSERT_EQ (wallet1.salt (transaction), wallet2.salt (transaction));\n\tASSERT_EQ (wallet1.check (transaction), wallet2.check (transaction));\n\tASSERT_EQ (wallet1.representative (transaction), wallet2.representative (transaction));\n\tASSERT_TRUE (wallet2.exists (transaction, key.pub));\n\tnano::raw_key prv;\n\twallet2.fetch (transaction, key.pub, prv);\n\tASSERT_EQ (key.prv, prv);\n}\n\nTEST (wallet, serialize_json_password)\n{\n\tauto error (false);\n\tnano::mdb_env env (error, nano::unique_path ());\n\tASSERT_FALSE (error);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet1 (error, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (error);\n\tnano::keypair key;\n\twallet1.rekey (transaction, \"password\");\n\twallet1.insert_adhoc (transaction, key.prv);\n\tstd::string serialized;\n\twallet1.serialize_json (transaction, serialized);\n\tnano::wallet_store wallet2 (error, kdf, transaction, nano::genesis_account, 1, \"1\", serialized);\n\tASSERT_FALSE (error);\n\tASSERT_FALSE (wallet2.valid_password (transaction));\n\tASSERT_FALSE (wallet2.attempt_password (transaction, \"password\"));\n\tASSERT_TRUE (wallet2.valid_password (transaction));\n\tnano::raw_key password1;\n\tnano::raw_key password2;\n\twallet1.wallet_key (password1, transaction);\n\twallet2.wallet_key (password2, transaction);\n\tASSERT_EQ (password1, password2);\n\tASSERT_EQ (wallet1.salt (transaction), wallet2.salt (transaction));\n\tASSERT_EQ (wallet1.check (transaction), wallet2.check (transaction));\n\tASSERT_EQ (wallet1.representative (transaction), wallet2.representative (transaction));\n\tASSERT_TRUE (wallet2.exists (transaction, key.pub));\n\tnano::raw_key prv;\n\twallet2.fetch (transaction, key.pub, prv);\n\tASSERT_EQ (key.prv, prv);\n}\n\nTEST (wallet_store, move)\n{\n\tauto error (false);\n\tnano::mdb_env env (error, nano::unique_path ());\n\tASSERT_FALSE (error);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet1 (error, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tASSERT_FALSE (error);\n\tnano::keypair key1;\n\twallet1.insert_adhoc (transaction, key1.prv);\n\tnano::wallet_store wallet2 (error, kdf, transaction, nano::genesis_account, 1, \"1\");\n\tASSERT_FALSE (error);\n\tnano::keypair key2;\n\twallet2.insert_adhoc (transaction, key2.prv);\n\tASSERT_FALSE (wallet1.exists (transaction, key2.pub));\n\tASSERT_TRUE (wallet2.exists (transaction, key2.pub));\n\tstd::vector<nano::public_key> keys;\n\tkeys.push_back (key2.pub);\n\tASSERT_FALSE (wallet1.move (transaction, wallet2, keys));\n\tASSERT_TRUE (wallet1.exists (transaction, key2.pub));\n\tASSERT_FALSE (wallet2.exists (transaction, key2.pub));\n}\n\nTEST (wallet_store, import)\n{\n\tnano::system system (2);\n\tauto wallet1 (system.wallet (0));\n\tauto wallet2 (system.wallet (1));\n\tnano::keypair key1;\n\twallet1->insert_adhoc (key1.prv);\n\tstd::string json;\n\twallet1->serialize (json);\n\tASSERT_FALSE (wallet2->exists (key1.pub));\n\tauto error (wallet2->import (json, \"\"));\n\tASSERT_FALSE (error);\n\tASSERT_TRUE (wallet2->exists (key1.pub));\n}\n\nTEST (wallet_store, fail_import_bad_password)\n{\n\tnano::system system (2);\n\tauto wallet1 (system.wallet (0));\n\tauto wallet2 (system.wallet (1));\n\tnano::keypair key1;\n\twallet1->insert_adhoc (key1.prv);\n\tstd::string json;\n\twallet1->serialize (json);\n\tASSERT_FALSE (wallet2->exists (key1.pub));\n\tauto error (wallet2->import (json, \"1\"));\n\tASSERT_TRUE (error);\n}\n\nTEST (wallet_store, fail_import_corrupt)\n{\n\tnano::system system (2);\n\tauto wallet1 (system.wallet (1));\n\tstd::string json;\n\tauto error (wallet1->import (json, \"1\"));\n\tASSERT_TRUE (error);\n}\n\n\/\/ Test work is precached when a key is inserted\nTEST (wallet, work)\n{\n\tnano::system system (1);\n\tauto wallet (system.wallet (0));\n\twallet->insert_adhoc (nano::dev_genesis_key.prv);\n\tnano::genesis genesis;\n\tauto done (false);\n\tsystem.deadline_set (20s);\n\twhile (!done)\n\t{\n\t\tauto transaction (system.wallet (0)->wallets.tx_begin_read ());\n\t\tuint64_t work (0);\n\t\tif (!wallet->store.work_get (transaction, nano::dev_genesis_key.pub, work))\n\t\t{\n\t\t\tdone = nano::work_difficulty (genesis.open->work_version (), genesis.hash (), work) >= system.nodes[0]->default_difficulty (genesis.open->work_version ());\n\t\t}\n\t\tASSERT_NO_ERROR (system.poll ());\n\t}\n}\n\nTEST (wallet, work_generate)\n{\n\tnano::system system (1);\n\tauto & node1 (*system.nodes[0]);\n\tauto wallet (system.wallet (0));\n\tnano::uint128_t amount1 (node1.balance (nano::dev_genesis_key.pub));\n\tuint64_t work1;\n\twallet->insert_adhoc (nano::dev_genesis_key.prv);\n\tnano::account account1;\n\t{\n\t\tauto transaction (node1.wallets.tx_begin_read ());\n\t\taccount1 = system.account (transaction, 0);\n\t}\n\tnano::keypair key;\n\tauto block (wallet->send_action (nano::dev_genesis_key.pub, key.pub, 100));\n\tauto transaction (node1.store.tx_begin_read ());\n\tASSERT_TIMELY (10s, node1.ledger.account_balance (transaction, nano::dev_genesis_key.pub) != amount1);\n\tsystem.deadline_set (10s);\n\tauto again (true);\n\twhile (again)\n\t{\n\t\tASSERT_NO_ERROR (system.poll ());\n\t\tauto block_transaction (node1.store.tx_begin_read ());\n\t\tauto transaction (system.wallet (0)->wallets.tx_begin_read ());\n\t\tagain = wallet->store.work_get (transaction, account1, work1) || nano::work_difficulty (block->work_version (), node1.ledger.latest_root (block_transaction, account1), work1) < node1.default_difficulty (block->work_version ());\n\t}\n}\n\nTEST (wallet, work_cache_delayed)\n{\n\tnano::system system (1);\n\tauto & node1 (*system.nodes[0]);\n\tauto wallet (system.wallet (0));\n\tuint64_t work1;\n\twallet->insert_adhoc (nano::dev_genesis_key.prv);\n\tnano::account account1;\n\t{\n\t\tauto transaction (node1.wallets.tx_begin_read ());\n\t\taccount1 = system.account (transaction, 0);\n\t}\n\tnano::keypair key;\n\tauto block1 (wallet->send_action (nano::dev_genesis_key.pub, key.pub, 100));\n\tASSERT_EQ (block1->hash (), node1.latest (nano::dev_genesis_key.pub));\n\tauto block2 (wallet->send_action (nano::dev_genesis_key.pub, key.pub, 100));\n\tASSERT_EQ (block2->hash (), node1.latest (nano::dev_genesis_key.pub));\n\tASSERT_EQ (block2->hash (), node1.wallets.delayed_work->operator[] (nano::dev_genesis_key.pub));\n\tauto threshold (node1.default_difficulty (nano::work_version::work_1));\n\tauto again (true);\n\tsystem.deadline_set (10s);\n\twhile (again)\n\t{\n\t\tASSERT_NO_ERROR (system.poll ());\n\t\tif (!wallet->store.work_get (node1.wallets.tx_begin_read (), account1, work1))\n\t\t{\n\t\t\tagain = nano::work_difficulty (nano::work_version::work_1, block2->hash (), work1) < threshold;\n\t\t}\n\t}\n\tASSERT_GE (nano::work_difficulty (nano::work_version::work_1, block2->hash (), work1), threshold);\n}\n\nTEST (wallet, insert_locked)\n{\n\tnano::system system (1);\n\tauto wallet (system.wallet (0));\n\t{\n\t\tauto transaction (wallet->wallets.tx_begin_write ());\n\t\twallet->store.rekey (transaction, \"1\");\n\t\tASSERT_TRUE (wallet->store.valid_password (transaction));\n\t\twallet->enter_password (transaction, \"\");\n\t}\n\tauto transaction (wallet->wallets.tx_begin_read ());\n\tASSERT_FALSE (wallet->store.valid_password (transaction));\n\tASSERT_TRUE (wallet->insert_adhoc (nano::keypair ().prv).is_zero ());\n}\n\nTEST (wallet, deterministic_keys)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tASSERT_FALSE (init);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tauto key1 = wallet.deterministic_key (transaction, 0);\n\tauto key2 = wallet.deterministic_key (transaction, 0);\n\tASSERT_EQ (key1, key2);\n\tauto key3 = wallet.deterministic_key (transaction, 1);\n\tASSERT_NE (key1, key3);\n\tASSERT_EQ (0, wallet.deterministic_index_get (transaction));\n\twallet.deterministic_index_set (transaction, 1);\n\tASSERT_EQ (1, wallet.deterministic_index_get (transaction));\n\tauto key4 (wallet.deterministic_insert (transaction));\n\tnano::raw_key key5;\n\tASSERT_FALSE (wallet.fetch (transaction, key4, key5));\n\tASSERT_EQ (key3, key5);\n\tASSERT_EQ (2, wallet.deterministic_index_get (transaction));\n\twallet.deterministic_index_set (transaction, 1);\n\tASSERT_EQ (1, wallet.deterministic_index_get (transaction));\n\twallet.erase (transaction, key4);\n\tASSERT_FALSE (wallet.exists (transaction, key4));\n\tauto key8 (wallet.deterministic_insert (transaction));\n\tASSERT_EQ (key4, key8);\n\tauto key6 (wallet.deterministic_insert (transaction));\n\tnano::raw_key key7;\n\tASSERT_FALSE (wallet.fetch (transaction, key6, key7));\n\tASSERT_NE (key5, key7);\n\tASSERT_EQ (3, wallet.deterministic_index_get (transaction));\n\tnano::keypair key9;\n\tASSERT_EQ (key9.pub, wallet.insert_adhoc (transaction, key9.prv));\n\tASSERT_TRUE (wallet.exists (transaction, key9.pub));\n\twallet.deterministic_clear (transaction);\n\tASSERT_EQ (0, wallet.deterministic_index_get (transaction));\n\tASSERT_FALSE (wallet.exists (transaction, key4));\n\tASSERT_FALSE (wallet.exists (transaction, key6));\n\tASSERT_FALSE (wallet.exists (transaction, key8));\n\tASSERT_TRUE (wallet.exists (transaction, key9.pub));\n}\n\nTEST (wallet, reseed)\n{\n\tbool init;\n\tnano::mdb_env env (init, nano::unique_path ());\n\tASSERT_FALSE (init);\n\tauto transaction (env.tx_begin_write ());\n\tnano::kdf kdf;\n\tnano::wallet_store wallet (init, kdf, transaction, nano::genesis_account, 1, \"0\");\n\tnano::raw_key seed1;\n\tseed1 = 1;\n\tnano::raw_key seed2;\n\tseed2 = 2;\n\twallet.seed_set (transaction, seed1);\n\tnano::raw_key seed3;\n\twallet.seed (seed3, transaction);\n\tASSERT_EQ (seed1, seed3);\n\tauto key1 (wallet.deterministic_insert (transaction));\n\tASSERT_EQ (1, wallet.deterministic_index_get (transaction));\n\twallet.seed_set (transaction, seed2);\n\tASSERT_EQ (0, wallet.deterministic_index_get (transaction));\n\tnano::raw_key seed4;\n\twallet.seed (seed4, transaction);\n\tASSERT_EQ (seed2, seed4);\n\tauto key2 (wallet.deterministic_insert (transaction));\n\tASSERT_NE (key1, key2);\n\twallet.seed_set (transaction, seed1);\n\tnano::raw_key seed5;\n\twallet.seed (seed5, transaction);\n\tASSERT_EQ (seed1, seed5);\n\tauto key3 (wallet.deterministic_insert (transaction));\n\tASSERT_EQ (key1, key3);\n}\n\nTEST (wallet, insert_deterministic_locked)\n{\n\tnano::system system (1);\n\tauto wallet (system.wallet (0));\n\tauto transaction (wallet->wallets.tx_begin_write ());\n\twallet->store.rekey (transaction, \"1\");\n\tASSERT_TRUE (wallet->store.valid_password (transaction));\n\twallet->enter_password (transaction, \"\");\n\tASSERT_FALSE (wallet->store.valid_password (transaction));\n\tASSERT_TRUE (wallet->deterministic_insert (transaction).is_zero ());\n}\n\nTEST (wallet, no_work)\n{\n\tnano::system system (1);\n\tsystem.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv, false);\n\tnano::keypair key2;\n\tauto block (system.wallet (0)->send_action (nano::dev_genesis_key.pub, key2.pub, std::numeric_limits<nano::uint128_t>::max (), false));\n\tASSERT_NE (nullptr, block);\n\tASSERT_NE (0, block->block_work ());\n\tASSERT_GE (block->difficulty (), nano::work_threshold (block->work_version (), block->sideband ().details));\n\tauto transaction (system.wallet (0)->wallets.tx_begin_read ());\n\tuint64_t cached_work (0);\n\tsystem.wallet (0)->store.work_get (transaction, nano::dev_genesis_key.pub, cached_work);\n\tASSERT_EQ (0, cached_work);\n}\n\nTEST (wallet, send_race)\n{\n\tnano::system system (1);\n\tsystem.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv);\n\tnano::keypair key2;\n\tfor (auto i (1); i < 60; ++i)\n\t{\n\t\tASSERT_NE (nullptr, system.wallet (0)->send_action (nano::dev_genesis_key.pub, key2.pub, nano::Gxrb_ratio));\n\t\tASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio * i, system.nodes[0]->balance (nano::dev_genesis_key.pub));\n\t}\n}\n\nTEST (wallet, password_race)\n{\n\tnano::system system (1);\n\tnano::thread_runner runner (system.io_ctx, system.nodes[0]->config.io_threads);\n\tauto wallet = system.wallet (0);\n\tstd::thread thread ([&wallet] () {\n\t\tfor (int i = 0; i < 100; i++)\n\t\t{\n\t\t\tauto transaction (wallet->wallets.tx_begin_write ());\n\t\t\twallet->store.rekey (transaction, std::to_string (i));\n\t\t}\n\t});\n\tfor (int i = 0; i < 100; i++)\n\t{\n\t\tauto transaction (wallet->wallets.tx_begin_read ());\n\t\t\/\/ Password should always be valid, the rekey operation should be atomic.\n\t\tbool ok = wallet->store.valid_password (transaction);\n\t\tEXPECT_TRUE (ok);\n\t\tif (!ok)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\tthread.join ();\n\tsystem.stop ();\n\trunner.join ();\n}\n\nTEST (wallet, password_race_corrupt_seed)\n{\n\tnano::system system (1);\n\tnano::thread_runner runner (system.io_ctx, system.nodes[0]->config.io_threads);\n\tauto wallet = system.wallet (0);\n\tnano::raw_key seed;\n\t{\n\t\tauto transaction (wallet->wallets.tx_begin_write ());\n\t\tASSERT_FALSE (wallet->store.rekey (transaction, \"4567\"));\n\t\twallet->store.seed (seed, transaction);\n\t\tASSERT_FALSE (wallet->store.attempt_password (transaction, \"4567\"));\n\t}\n\tstd::vector<std::thread> threads;\n\tfor (int i = 0; i < 100; i++)\n\t{\n\t\tthreads.emplace_back ([&wallet] () {\n\t\t\tfor (int i = 0; i < 10; i++)\n\t\t\t{\n\t\t\t\tauto transaction (wallet->wallets.tx_begin_write ());\n\t\t\t\twallet->store.rekey (transaction, \"0000\");\n\t\t\t}\n\t\t});\n\t\tthreads.emplace_back ([&wallet] () {\n\t\t\tfor (int i = 0; i < 10; i++)\n\t\t\t{\n\t\t\t\tauto transaction (wallet->wallets.tx_begin_write ());\n\t\t\t\twallet->store.rekey (transaction, \"1234\");\n\t\t\t}\n\t\t});\n\t\tthreads.emplace_back ([&wallet] () {\n\t\t\tfor (int i = 0; i < 10; i++)\n\t\t\t{\n\t\t\t\tauto transaction (wallet->wallets.tx_begin_read ());\n\t\t\t\twallet->store.attempt_password (transaction, \"1234\");\n\t\t\t}\n\t\t});\n\t}\n\tfor (auto & thread : threads)\n\t{\n\t\tthread.join ();\n\t}\n\tsystem.stop ();\n\trunner.join ();\n\t{\n\t\tauto transaction (wallet->wallets.tx_begin_write ());\n\t\tif (!wallet->store.attempt_password (transaction, \"1234\"))\n\t\t{\n\t\t\tnano::raw_key seed_now;\n\t\t\twallet->store.seed (seed_now, transaction);\n\t\t\tASSERT_TRUE (seed_now == seed);\n\t\t}\n\t\telse if (!wallet->store.attempt_password (transaction, \"0000\"))\n\t\t{\n\t\t\tnano::raw_key seed_now;\n\t\t\twallet->store.seed (seed_now, transaction);\n\t\t\tASSERT_TRUE (seed_now == seed);\n\t\t}\n\t\telse if (!wallet->store.attempt_password (transaction, \"4567\"))\n\t\t{\n\t\t\tnano::raw_key seed_now;\n\t\t\twallet->store.seed (seed_now, transaction);\n\t\t\tASSERT_TRUE (seed_now == seed);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tASSERT_FALSE (true);\n\t\t}\n\t}\n}\n\nTEST (wallet, change_seed)\n{\n\tnano::system system (1);\n\tauto wallet (system.wallet (0));\n\twallet->enter_initial_password ();\n\tnano::raw_key seed1;\n\tseed1 = 1;\n\tnano::public_key pub;\n\tuint32_t index (4);\n\tauto prv = nano::deterministic_key (seed1, index);\n\tpub = nano::pub_key (prv);\n\twallet->insert_adhoc (nano::dev_genesis_key.prv, false);\n\tauto block (wallet->send_action (nano::dev_genesis_key.pub, pub, 100));\n\tASSERT_NE (nullptr, block);\n\tsystem.nodes[0]->block_processor.flush ();\n\t{\n\t\tauto transaction (wallet->wallets.tx_begin_write ());\n\t\twallet->change_seed (transaction, seed1);\n\t\tnano::raw_key seed2;\n\t\twallet->store.seed (seed2, transaction);\n\t\tASSERT_EQ (seed1, seed2);\n\t\tASSERT_EQ (index + 1, wallet->store.deterministic_index_get (transaction));\n\t}\n\tASSERT_TRUE (wallet->exists (pub));\n}\n\nTEST (wallet, deterministic_restore)\n{\n\tnano::system system (1);\n\tauto wallet (system.wallet (0));\n\twallet->enter_initial_password ();\n\tnano::raw_key seed1;\n\tseed1 = 1;\n\tnano::public_key pub;\n\tuint32_t index (4);\n\t{\n\t\tauto transaction (wallet->wallets.tx_begin_write ());\n\t\twallet->change_seed (transaction, seed1);\n\t\tnano::raw_key seed2;\n\t\twallet->store.seed (seed2, transaction);\n\t\tASSERT_EQ (seed1, seed2);\n\t\tASSERT_EQ (1, wallet->store.deterministic_index_get (transaction));\n\t\tauto prv = nano::deterministic_key (seed1, index);\n\t\tpub = nano::pub_key (prv);\n\t}\n\twallet->insert_adhoc (nano::dev_genesis_key.prv, false);\n\tauto block (wallet->send_action (nano::dev_genesis_key.pub, pub, 100));\n\tASSERT_NE (nullptr, block);\n\tsystem.nodes[0]->block_processor.flush ();\n\t{\n\t\tauto transaction (wallet->wallets.tx_begin_write ());\n\t\twallet->deterministic_restore (transaction);\n\t\tASSERT_EQ (index + 1, wallet->store.deterministic_index_get (transaction));\n\t}\n\tASSERT_TRUE (wallet->exists (pub));\n}\n\nTEST (wallet, epoch_2_validation)\n{\n\tnano::system system (1);\n\tauto & node (*system.nodes[0]);\n\tauto & wallet (*system.wallet (0));\n\n\t\/\/ Upgrade the genesis account to epoch 2\n\tASSERT_NE (nullptr, system.upgrade_genesis_epoch (node, nano::epoch::epoch_1));\n\tASSERT_NE (nullptr, system.upgrade_genesis_epoch (node, nano::epoch::epoch_2));\n\n\twallet.insert_adhoc (nano::dev_genesis_key.prv, false);\n\n\t\/\/ Test send and receive blocks\n\t\/\/ An epoch 2 receive block should be generated with lower difficulty with high probability\n\tauto tries = 0;\n\tauto max_tries = 20;\n\tauto amount = node.config.receive_minimum.number ();\n\twhile (++tries < max_tries)\n\t{\n\t\tauto send = wallet.send_action (nano::dev_genesis_key.pub, nano::dev_genesis_key.pub, amount, 1);\n\t\tASSERT_NE (nullptr, send);\n\t\tASSERT_EQ (nano::epoch::epoch_2, send->sideband ().details.epoch);\n\t\tASSERT_EQ (nano::epoch::epoch_0, send->sideband ().source_epoch); \/\/ Not used for send state blocks\n\n\t\tauto receive = wallet.receive_action (send->hash (), nano::dev_genesis_key.pub, amount, send->link ().as_account (), 1);\n\t\tASSERT_NE (nullptr, receive);\n\t\tif (receive->difficulty () < node.network_params.network.publish_thresholds.base)\n\t\t{\n\t\t\tASSERT_GE (receive->difficulty (), node.network_params.network.publish_thresholds.epoch_2_receive);\n\t\t\tASSERT_EQ (nano::epoch::epoch_2, receive->sideband ().details.epoch);\n\t\t\tASSERT_EQ (nano::epoch::epoch_2, receive->sideband ().source_epoch);\n\t\t\tbreak;\n\t\t}\n\t}\n\tASSERT_LT (tries, max_tries);\n\n\t\/\/ Test a change block\n\tASSERT_NE (nullptr, wallet.change_action (nano::dev_genesis_key.pub, nano::keypair ().pub, 1));\n}\n\n\/\/ Receiving from an upgraded account uses the lower threshold and upgrades the receiving account\nTEST (wallet, epoch_2_receive_propagation)\n{\n\tauto tries = 0;\n\tauto const max_tries = 20;\n\twhile (++tries < max_tries)\n\t{\n\t\tnano::system system;\n\t\tnano::node_flags node_flags;\n\t\tnode_flags.disable_request_loop = true;\n\t\tauto & node (*system.add_node (node_flags));\n\t\tauto & wallet (*system.wallet (0));\n\n\t\t\/\/ Upgrade the genesis account to epoch 1\n\t\tauto epoch1 = system.upgrade_genesis_epoch (node, nano::epoch::epoch_1);\n\t\tASSERT_NE (nullptr, epoch1);\n\n\t\tnano::keypair key;\n\t\tnano::state_block_builder builder;\n\n\t\t\/\/ Send and open the account\n\t\twallet.insert_adhoc (nano::dev_genesis_key.prv, false);\n\t\twallet.insert_adhoc (key.prv, false);\n\t\tauto amount = node.config.receive_minimum.number ();\n\t\tauto send1 = wallet.send_action (nano::dev_genesis_key.pub, key.pub, amount, 1);\n\t\tASSERT_NE (nullptr, send1);\n\t\tASSERT_NE (nullptr, wallet.receive_action (send1->hash (), nano::dev_genesis_key.pub, amount, send1->link ().as_account (), 1));\n\n\t\t\/\/ Upgrade the genesis account to epoch 2\n\t\tauto epoch2 = system.upgrade_genesis_epoch (node, nano::epoch::epoch_2);\n\t\tASSERT_NE (nullptr, epoch2);\n\n\t\t\/\/ Send a block\n\t\tauto send2 = wallet.send_action (nano::dev_genesis_key.pub, key.pub, amount, 1);\n\t\tASSERT_NE (nullptr, send2);\n\n\t\tauto receive2 = wallet.receive_action (send2->hash (), key.pub, amount, send2->link ().as_account (), 1);\n\t\tASSERT_NE (nullptr, receive2);\n\t\tif (receive2->difficulty () < node.network_params.network.publish_thresholds.base)\n\t\t{\n\t\t\tASSERT_GE (receive2->difficulty (), node.network_params.network.publish_thresholds.epoch_2_receive);\n\t\t\tASSERT_EQ (nano::epoch::epoch_2, node.store.block_version (node.store.tx_begin_read (), receive2->hash ()));\n\t\t\tASSERT_EQ (nano::epoch::epoch_2, receive2->sideband ().source_epoch);\n\t\t\tbreak;\n\t\t}\n\t}\n\tASSERT_LT (tries, max_tries);\n}\n\n\/\/ Opening an upgraded account uses the lower threshold\nTEST (wallet, epoch_2_receive_unopened)\n{\n\t\/\/ Ensure the lower receive work is used when receiving\n\tauto tries = 0;\n\tauto const max_tries = 20;\n\twhile (++tries < max_tries)\n\t{\n\t\tnano::system system;\n\t\tnano::node_flags node_flags;\n\t\tnode_flags.disable_request_loop = true;\n\t\tauto & node (*system.add_node (node_flags));\n\t\tauto & wallet (*system.wallet (0));\n\n\t\t\/\/ Upgrade the genesis account to epoch 1\n\t\tauto epoch1 = system.upgrade_genesis_epoch (node, nano::epoch::epoch_1);\n\t\tASSERT_NE (nullptr, epoch1);\n\n\t\tnano::keypair key;\n\t\tnano::state_block_builder builder;\n\n\t\t\/\/ Send\n\t\twallet.insert_adhoc (nano::dev_genesis_key.prv, false);\n\t\tauto amount = node.config.receive_minimum.number ();\n\t\tauto send1 = wallet.send_action (nano::dev_genesis_key.pub, key.pub, amount, 1);\n\n\t\t\/\/ Upgrade unopened account to epoch_2\n\t\tauto epoch2_unopened = nano::state_block (key.pub, 0, 0, 0, node.network_params.ledger.epochs.link (nano::epoch::epoch_2), nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (key.pub, node.network_params.network.publish_thresholds.epoch_2));\n\t\tASSERT_EQ (nano::process_result::progress, node.process (epoch2_unopened).code);\n\n\t\twallet.insert_adhoc (key.prv, false);\n\n\t\tauto receive1 = wallet.receive_action (send1->hash (), key.pub, amount, send1->link ().as_account (), 1);\n\t\tASSERT_NE (nullptr, receive1);\n\t\tif (receive1->difficulty () < node.network_params.network.publish_thresholds.base)\n\t\t{\n\t\t\tASSERT_GE (receive1->difficulty (), node.network_params.network.publish_thresholds.epoch_2_receive);\n\t\t\tASSERT_EQ (nano::epoch::epoch_2, node.store.block_version (node.store.tx_begin_read (), receive1->hash ()));\n\t\t\tASSERT_EQ (nano::epoch::epoch_1, receive1->sideband ().source_epoch);\n\t\t\tbreak;\n\t\t}\n\t}\n\tASSERT_LT (tries, max_tries);\n}\n\nTEST (wallet, foreach_representative_deadlock)\n{\n\tnano::system system (1);\n\tauto & node (*system.nodes[0]);\n\tsystem.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv);\n\tnode.wallets.compute_reps ();\n\tASSERT_EQ (1, node.wallets.reps ().voting);\n\tnode.wallets.foreach_representative ([&node] (nano::public_key const & pub, nano::raw_key const & prv) {\n\t\tif (node.wallets.mutex.try_lock ())\n\t\t{\n\t\t\tnode.wallets.mutex.unlock ();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tASSERT_FALSE (true);\n\t\t}\n\t});\n}\n\nTEST (wallet, search_pending)\n{\n\tnano::system system;\n\tnano::node_config config (nano::get_available_port (), system.logging);\n\tconfig.enable_voting = false;\n\tconfig.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled;\n\tnano::node_flags flags;\n\tflags.disable_search_pending = true;\n\tauto & node (*system.add_node (config, flags));\n\tauto & wallet (*system.wallet (0));\n\n\twallet.insert_adhoc (nano::dev_genesis_key.prv);\n\tnano::block_builder builder;\n\tauto send = builder.state ()\n\t\t\t\t.account (nano::genesis_account)\n\t\t\t\t.previous (nano::genesis_hash)\n\t\t\t\t.representative (nano::genesis_account)\n\t\t\t\t.balance (nano::genesis_amount - node.config.receive_minimum.number ())\n\t\t\t\t.link (nano::genesis_account)\n\t\t\t\t.sign (nano::dev_genesis_key.prv, nano::dev_genesis_key.pub)\n\t\t\t\t.work (*system.work.generate (nano::genesis_hash))\n\t\t\t\t.build ();\n\tASSERT_EQ (nano::process_result::progress, node.process (*send).code);\n\n\t\/\/ Pending search should start an election\n\tASSERT_TRUE (node.active.empty ());\n\tASSERT_FALSE (wallet.search_pending (wallet.wallets.tx_begin_read ()));\n\tauto election = node.active.election (send->qualified_root ());\n\tASSERT_NE (nullptr, election);\n\n\t\/\/ Erase the key so the confirmation does not trigger an automatic receive\n\twallet.store.erase (node.wallets.tx_begin_write (), nano::genesis_account);\n\n\t\/\/ Now confirm the election\n\telection->force_confirm ();\n\n\tASSERT_TIMELY (5s, node.block_confirmed (send->hash ()) && node.active.empty ());\n\n\t\/\/ Re-insert the key\n\twallet.insert_adhoc (nano::dev_genesis_key.prv);\n\n\t\/\/ Pending search should create the receive block\n\tASSERT_EQ (2, node.ledger.cache.block_count);\n\tASSERT_FALSE (wallet.search_pending (wallet.wallets.tx_begin_read ()));\n\tASSERT_TIMELY (3s, node.balance (nano::genesis_account) == nano::genesis_amount);\n\tauto receive_hash = node.ledger.latest (node.store.tx_begin_read (), nano::genesis_account);\n\tauto receive = node.block (receive_hash);\n\tASSERT_NE (nullptr, receive);\n\tASSERT_EQ (receive->sideband ().height, 3);\n\tASSERT_EQ (send->hash (), receive->link ().as_block_hash ());\n}\n\nTEST (wallet, receive_pruned)\n{\n\tnano::system system;\n\tnano::node_flags node_flags;\n\tnode_flags.disable_request_loop = true;\n\tauto & node1 = *system.add_node (node_flags);\n\tnode_flags.enable_pruning = true;\n\tnano::node_config config (nano::get_available_port (), system.logging);\n\tconfig.enable_voting = false; \/\/ Remove after allowing pruned voting\n\tauto & node2 = *system.add_node (config, node_flags);\n\n\tauto & wallet1 = *system.wallet (0);\n\tauto & wallet2 = *system.wallet (1);\n\n\tnano::keypair key;\n\tnano::state_block_builder builder;\n\n\t\/\/ Send\n\twallet1.insert_adhoc (nano::dev_genesis_key.prv, false);\n\tauto amount = node2.config.receive_minimum.number ();\n\tauto send1 = wallet1.send_action (nano::dev_genesis_key.pub, key.pub, amount, 1);\n\tauto send2 = wallet1.send_action (nano::dev_genesis_key.pub, key.pub, 1, 1);\n\n\t\/\/ Pruning\n\tASSERT_TIMELY (5s, node2.ledger.cache.cemented_count == 3);\n\t{\n\t\tauto transaction = node2.store.tx_begin_write ();\n\t\tASSERT_EQ (1, node2.ledger.pruning_action (transaction, send1->hash (), 2));\n\t}\n\tASSERT_EQ (1, node2.ledger.cache.pruned_count);\n\tASSERT_TRUE (node2.ledger.block_or_pruned_exists (send1->hash ()));\n\tASSERT_FALSE (node2.store.block_exists (node2.store.tx_begin_read (), send1->hash ()));\n\n\twallet2.insert_adhoc (key.prv, false);\n\n\tauto open1 = wallet2.receive_action (send1->hash (), key.pub, amount, send1->link ().as_account (), 1);\n\tASSERT_NE (nullptr, open1);\n\tASSERT_EQ (amount, node2.ledger.balance (node2.store.tx_begin_read (), open1->hash ()));\n\tASSERT_TIMELY (5s, node2.ledger.cache.cemented_count == 4);\n}\n","avg_line_length":34.0160771704,"max_line_length":268,"alphanum_fraction":0.7220909349,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1462,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright Golden Hammer Software\n#include \"GHMaterialReplacer.h\"\n#include \"GHMaterial.h\"\n#include \"GHGeometryRenderable.h\"\n#include \"GHGeometry.h\"\n\nGHMaterialReplacer::GHMaterialReplacer(void)\n: mDefaultReplacement(0)\n{\n}\n\nGHMaterialReplacer::~GHMaterialReplacer(void)\n{\n    for (size_t i = 0; i < mReplacements.size(); ++i)\n    {\n        mReplacements[i].mMat->release();\n    }\n    GHRefCounted::changePointer((GHRefCounted*&)mDefaultReplacement, 0);\n}\n\nvoid GHMaterialReplacer::setDefaultReplacement(GHMaterial* mat)\n{\n    GHRefCounted::changePointer((GHRefCounted*&)mDefaultReplacement, mat);\n}\n\nvoid GHMaterialReplacer::addReplacement(GHMaterial* mat, GHIdentifier targetId)\n{\n    mat->acquire();\n    mReplacements.push_back(Replacement(mat, targetId));\n}\n\nvoid GHMaterialReplacer::applyReplacements(GHGeometryRenderable& renderable)\n{\n    const std::vector<GHGeometry*>& geometrySet = renderable.getGeometry();\n    for (size_t i = 0; i < geometrySet.size(); ++i)\n    {\n        bool found = false;\n        for (size_t repIdx = 0; repIdx < mReplacements.size(); ++repIdx)\n        {\n            if (geometrySet[i]->getId() == mReplacements[repIdx].mTargetId)\n            {\n                geometrySet[i]->setMaterial(mReplacements[repIdx].mMat);\n                found = true;\n                break;\n            }\n        }\n        if (!found && mDefaultReplacement)\n        {\n            geometrySet[i]->setMaterial(mDefaultReplacement);\n        }\n    }\n}\n\n","avg_line_length":27.0740740741,"max_line_length":79,"alphanum_fraction":0.6538987688,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1674,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"#include \"drape\/support_manager.hpp\"\n#include \"drape\/glfunctions.hpp\"\n\n#include \"base\/logging.hpp\"\n\n#include \"3party\/Alohalytics\/src\/alohalytics.h\"\n\nnamespace dp\n{\n\nvoid SupportManager::Init()\n{\n  string const renderer = GLFunctions::glGetString(gl_const::GLRenderer);\n  string const version = GLFunctions::glGetString(gl_const::GLVersion);\n  LOG(LINFO, (\"Renderer =\", renderer, \"Version =\", version));\n\n  \/\/ On Android the engine may be recreated. Here we guarantee that GPU info is sent once per session.\n  static bool gpuInfoSent = false;\n  if (!gpuInfoSent)\n  {\n    alohalytics::Stats::Instance().LogEvent(\"GPU\", renderer);\n    gpuInfoSent = true;\n  }\n\n  m_isSamsungGoogleNexus = (renderer == \"PowerVR SGX 540\" && version.find(\"GOOGLENEXUS.ED945322\") != string::npos);\n  if (m_isSamsungGoogleNexus)\n    LOG(LINFO, (\"Samsung Google Nexus detected.\"));\n\n  if (renderer.find(\"Adreno\") != string::npos)\n  {\n    vector<string> const models = { \"200\", \"203\", \"205\", \"220\", \"225\" };\n    for (auto const & model : models)\n    {\n      if (renderer.find(model) != string::npos)\n      {\n        LOG(LINFO, (\"Adreno 200 device detected.\"));\n        m_isAdreno200 = true;\n        break;\n      }\n    }\n  }\n\n  m_isTegra = (renderer.find(\"Tegra\") != string::npos);\n  if (m_isTegra)\n    LOG(LINFO, (\"NVidia Tegra device detected.\"));\n}\n\nbool SupportManager::IsSamsungGoogleNexus() const\n{\n  return m_isSamsungGoogleNexus;\n}\n\nbool SupportManager::IsAdreno200Device() const\n{\n  return m_isAdreno200;\n}\n\nbool SupportManager::IsTegraDevice() const\n{\n  return m_isTegra;\n}\n\nSupportManager & SupportManager::Instance()\n{\n  static SupportManager manager;\n  return manager;\n}\n\n} \/\/ namespace dp\n","avg_line_length":23.9142857143,"max_line_length":115,"alphanum_fraction":0.6810035842,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":620,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"system_Imp.h\"\n\nSystem_Imp::System_Imp(){}\n\nSystem_Imp::System_Imp(string name, double value){\n    this->name = name;\n    this->value = value;\n}\n\nSystem_Imp::~System_Imp(){}\n\nvoid System_Imp::setName(string name){\n    this->name = name;\n}\n\nvoid System_Imp::setValue(double value){\n    this->value = value;\n}\n\nstring System_Imp::getName(){\n    return this->name;\n}\n\ndouble System_Imp::getValue(){\n    return this->value;\n}\n\nSystem_Imp* System_Imp::operator=(System* system){\n    if (this == system)\n        return this;\n    this->name = system->getName();\n    this->value = system->getValue();\n    return this;\n}","avg_line_length":18.2352941176,"max_line_length":50,"alphanum_fraction":0.6564516129,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4793,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-3.0"],"max_stars_count":16.0,"content":"\/**********************************************************************\n\n  Audacity: A Digital Audio Editor\n\n  SplashDialog.cpp\n\n  James Crook\n\n********************************************************************\/\/**\n\n\\class SplashDialog\n\\brief The SplashDialog shows help information for Audacity when \nAudacity starts up.\n\nIt was written for the benefit of new users who do not want to \nread the manual.  The text of the dialog is kept short to increase the\nchance of it being read.  The content is designed to reduce the \nmost commonly asked questions about Audacity.\n\n*\/\/********************************************************************\/\n\n\n#include \"Audacity.h\"\n\n#include <wx\/dialog.h>\n#include <wx\/html\/htmlwin.h>\n#include <wx\/button.h>\n#include <wx\/dcclient.h>\n#include <wx\/sizer.h>\n#include <wx\/statbmp.h>\n#include <wx\/intl.h>\n#include <wx\/image.h>\n\n#include \"SplashDialog.h\"\n#include \"FileNames.h\"\n#include \"Internat.h\"\n#include \"ShuttleGui.h\"\n#include \"widgets\/LinkingHtmlWindow.h\"\n\n#include \"Theme.h\"\n#include \"AllThemeResources.h\"\n#include \"Prefs.h\"\n#include \"HelpText.h\"\n\n#include \"..\/images\/AudacityLogoWithName.xpm\"\n\nSplashDialog * SplashDialog::pSelf=NULL;\n\nenum \n{\n   DontShowID=1000,\n};\n\nBEGIN_EVENT_TABLE(SplashDialog, wxDialog)\n   EVT_BUTTON(wxID_OK, SplashDialog::OnOK)\n   EVT_CHECKBOX( DontShowID, SplashDialog::OnDontShow )\nEND_EVENT_TABLE()\n\nIMPLEMENT_CLASS(SplashDialog, wxDialog)\n\nSplashDialog::SplashDialog(wxWindow * parent)\n   :  wxDialog(parent, -1, _(\"Welcome to Audacity!\"),\n      wxPoint( -1, 60 ), \/\/ default x position, y position 60 pixels from top of screen.\n      wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)\n{\n   this->SetBackgroundColour(theTheme.Colour( clrAboutBoxBackground ));\n   m_pIcon = NULL;\n   m_pLogo = NULL; \/\/v\n   ShuttleGui S( this, eIsCreating );\n   Populate( S );\n   Fit();\n   this->Centre();\n   int x,y;\n   GetPosition( &x, &y );\n   Move( x, 60 );\n}\n\nvoid SplashDialog::Populate( ShuttleGui & S )\n{\n   this->SetBackgroundColour(theTheme.Colour( clrAboutBoxBackground ));\n   bool bShow;\n   gPrefs->Read(wxT(\"\/GUI\/ShowSplashScreen\"), &bShow, true );\n   S.StartVerticalLay(1);\n\n   \/\/v For now, change to AudacityLogoWithName via old-fashioned ways, not Theme.\n   m_pLogo = new wxBitmap((const char **) AudacityLogoWithName_xpm); \/\/v\n\n   \/\/ JKC: Resize to 50% of size.  Later we may use a smaller xpm as\n   \/\/ our source, but this allows us to tweak the size - if we want to.\n   \/\/ It also makes it easier to revert to full size if we decide to.\n   const float fScale=0.5f;\/\/ smaller size.\n   wxImage RescaledImage( m_pLogo->ConvertToImage() );\n   \/\/ wxIMAGE_QUALITY_HIGH not supported by wxWidgets 2.6.1, or we would use it here.\n   RescaledImage.Rescale( int(LOGOWITHNAME_WIDTH * fScale), int(LOGOWITHNAME_HEIGHT *fScale) );\n   wxBitmap RescaledBitmap( RescaledImage );\n   m_pIcon =\n       new wxStaticBitmap(S.GetParent(), -1, \n                          \/\/*m_pLogo, \/\/v theTheme.Bitmap(bmpAudacityLogoWithName), \n                          RescaledBitmap,\n                          wxDefaultPosition, \n                          wxSize(int(LOGOWITHNAME_WIDTH*fScale), int(LOGOWITHNAME_HEIGHT*fScale)));\n\n   S.Prop(0).AddWindow( m_pIcon );\n\n   mpHtml = new LinkingHtmlWindow(S.GetParent(), -1,\n                                         wxDefaultPosition,\n                                         wxSize(506, 280),\n                                         wxHW_SCROLLBAR_AUTO | wxSUNKEN_BORDER );\n   mpHtml->SetPage(HelpText( wxT(\"welcome\") ));\n   S.Prop(1).AddWindow( mpHtml, wxEXPAND );\n   S.Prop(0).StartMultiColumn(2, wxEXPAND);\n   S.SetStretchyCol( 1 );\/\/ Column 1 is stretchy...\n   {\n      S.SetBorder( 5 );\n      S.Id( DontShowID).AddCheckBox( _(\"Don't show this again at start up\"), bShow ? wxT(\"false\") : wxT(\"true\") );\n      wxButton *ok = new wxButton(S.GetParent(), wxID_OK);\n      ok->SetDefault();\n      S.SetBorder( 5 );\n      S.Prop(0).AddWindow( ok, wxALIGN_RIGHT| wxALL );\n   }\n   S.EndVerticalLay();\n}\n\nSplashDialog::~SplashDialog()\n{\n   delete m_pIcon;\n   delete m_pLogo;\n}\n\nvoid SplashDialog::OnDontShow( wxCommandEvent & Evt )\n{\n   bool bShow = !Evt.IsChecked(); \n   gPrefs->Write(wxT(\"\/GUI\/ShowSplashScreen\"), bShow );\n}\n\nvoid SplashDialog::OnOK(wxCommandEvent & WXUNUSED(event))\n{\n   Show( false );\n\n}\n\nvoid SplashDialog::Show2( wxWindow * pParent )\n{\n   if( pSelf == NULL )\n   {\n      pSelf = new SplashDialog( pParent );\n   }\n   pSelf->mpHtml->SetPage(HelpText( wxT(\"welcome\") ));\n   pSelf->Show( true );\n}\n\n\n\/\/ Indentation settings for Vim and Emacs and unique identifier for Arch, a\n\/\/ version control system. Please do not modify past this point.\n\/\/\n\/\/ Local Variables:\n\/\/ c-basic-offset: 3\n\/\/ indent-tabs-mode: nil\n\/\/ End:\n\/\/\n\/\/ vim: et sts=3 sw=3\n\/\/ arch-tag: a8955864-40e2-47aa-923b-cace3994493a\n\n","avg_line_length":29.2256097561,"max_line_length":114,"alphanum_fraction":0.6357187565,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3043,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n#define radians (M_PI\/180.0)\n#define degrees (180.0\/M_PI)\n#define magic_number_1 1.0\n#define magic_number_2 2.0\n#define max_h_speed (20.0 - magic_number_1)\n#define max_v_speed (40.0 - magic_number_2)\n#define gravity (3.711)\n#define stop_fall_angle ((int)(acos(gravity \/ 4.0) * degrees))\n#define security_distance (max_v_speed \/ (gravity-3.0))\n\ntypedef struct {\n    int x, y;\n} Point;\n\ntypedef struct {\n    Point a, b, c;\n} LZ; \/\/ Landing zone\n\nLZ lz;\n\ninline bool overLZ(Point a) { return a.x >= lz.a.x and a.x <= lz.b.x; }\ninline int dirToLZ(Point a) { return a.x < lz.c.x ? 1 : -1; }\ninline int direction(int hSpeed) { return hSpeed > 0 ? 1 : -1; }\ninline int r2decelerate(int hSpeed, int vSpeed) \n{   \n    return asin((double) hSpeed \/ sqrt(hSpeed*hSpeed + vSpeed*vSpeed)) * degrees;\n}\n\nint main()\n{\n    int surfaceN; \/\/ the number of points used to draw the surface of Mars.\n    cin >> surfaceN; cin.ignore();\n    vector<Point> points;\n    Point last = {0, 0};\n    \n    \n    for (int i = 0; i < surfaceN; i++) {\n        Point p;\n        cin >> p.x >> p.y; cin.ignore();\n        \n        if (p.y == last.y and p.x - last.x >= 1000)\n            lz = {last, p, {p.x\/2 + last.x\/2, p.y}};\n        \n        last = p;\n        points.push_back(p);\n    }\n\n    while (1) {\n        Point a;\n        int hSpeed; \/\/ the horizontal speed (in m\/s), can be negative.\n        int vSpeed; \/\/ the vertical speed (in m\/s), can be negative.\n        int fuel; \/\/ the quantity of remaining fuel in liters.\n        int r = 0, rotate; \/\/ the rotation angle in degrees (-90 to 90).\n        int p = 0, power; \/\/ the thrust power (0 to 4).\n        cin >> a.x >> a.y >> hSpeed >> vSpeed >> fuel >> rotate >> power; cin.ignore();\n        \n        if (overLZ(a)) {\n            if (a.y < lz.c.y + security_distance) {\n                \/\/ cerr << \"a\" << endl;\n                r = 0;\n                p = 3;\n            }\n            else if (abs(hSpeed) < max_h_speed and abs(vSpeed) < max_v_speed) {\n                \/\/ cerr << \"b\" << endl;\n                r = 0;\n                p = 2;\n            }\n            else {\n                \/\/ cerr << \"c\" << endl;\n                r = r2decelerate(hSpeed, vSpeed);\n                p = 4;\n            }\n        }\n        else {\n            if (abs(hSpeed > 0) and direction(hSpeed) != dirToLZ(a) or abs(hSpeed) > max_h_speed * 4) {\n                \/\/ cerr << \"d\" << endl;\n                r = -stop_fall_angle * -direction(hSpeed);\n                cerr << r << endl;\n                p = 4;\n            }\n            else if (abs(hSpeed) < max_h_speed * 2) {\n                \/\/ cerr << \"e\" << endl;\n                r = -stop_fall_angle * dirToLZ(a);\n                p = 4;   \n            }\n            else {\n                \/\/ cerr << \"f\" << endl;\n                r = 0;\n                if (vSpeed < 0) p = 4;\n                else p = 3;\n            }\n        }\n    \n        cout << r << \" \" << p << endl;\n    }\n}\n","avg_line_length":28.980952381,"max_line_length":103,"alphanum_fraction":0.4778179428,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1851,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":4.0,"content":"\/*\n * File: gmath.cpp\n * ---------------\n * This file implements the gmath.h interface.  In all cases, the\n * implementation for each function requires only one line of code,\n * which makes detailed documentation unnecessary.\n *\n * @version 2021\/04\/09\n * - added sgl::math namespace\n * @version 2018\/11\/22\n * - added headless mode support\n * - alphabetized methods\n * @version 2016\/10\/14\n * - modified floating-point equality tests to use floatingPointEqual function\n *\/\n\n#include \"gmath.h\"\n#include <cmath>\n#include <exception>\n#include <stdexcept>\n#include \"gtypes.h\"\n\nnamespace sgl {\nnamespace math {\n\nextern const double PI = 3.14159265358979323846;\nextern const double E  = 2.71828182845904523536;\n\ndouble cosDegrees(double angle) {\n    return cos(toRadians(angle));\n}\n\nint countDigits(int n, int base) {\n    if (base <= 0) {\n        throw std::runtime_error(\"countDigits: base must be 1 or greater\");\n    }\n    if (n == 0) {\n        return 0;\n    } else if (n < 0) {\n        n = -n;\n    }\n\n    int digits = 0;\n    for (int temp = n; temp > 0 && digits < 65; temp \/= base) {\n        digits++;\n    }\n    return digits;\n}\n\ndouble sinDegrees(double angle) {\n    return sin(toRadians(angle));\n}\n\ndouble tanDegrees(double angle) {\n    return tan(toRadians(angle));\n}\n\ndouble toDegrees(double radians) {\n    return radians * 180 \/ PI;\n}\n\ndouble toRadians(double degrees) {\n    return degrees * PI \/ 180;\n}\n\ndouble vectorAngle(double x, double y) {\n    return floatingPointEqual(x, 0) && floatingPointEqual(y, 0)\n            ? 0 : toDegrees(atan2(-y, x));\n}\n\ndouble vectorAngle(const ::sgl::GPoint& pt) {\n    return vectorAngle(pt.x, pt.y);\n}\n\ndouble vectorDistance(double x, double y) {\n    return sqrt(x * x + y * y);\n}\n\ndouble vectorDistance(const ::sgl::GPoint& pt) {\n    return vectorDistance(pt.x, pt.y);\n}\n\n} \/\/ namespace math\n} \/\/ namespace sgl\n","avg_line_length":21.7764705882,"max_line_length":78,"alphanum_fraction":0.6472177202,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2917,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"#include \"asteroid.hpp\"\n\n#include <typeinfo>\n\n#include <dispatch\/dispatch.h>\n\n#include \"renderer\/scene\/scenemanager.hpp\"\n\n#define VCLIP_TEMPLATES\n#include \"collisiondetection\/vclip.hpp\"\n\n#include \"rocket.hpp\"\n\nextern scene::SceneManager* sceneManagerPtr;\nextern unsigned int score;\n\nAsteroid::Asteroid(glm::vec3 initialLocation, unsigned int mass) : scene::GravitationalObject(initialLocation, mass, \"sphere\", render::ColourInformationUniform{glm::vec3{142.0f, 100.0f, 0.0f}, 1.0f}), removeOnceToken{0} {\n\tscale = glm::vec3{mass * 0.5f, mass * 0.5f, mass * 0.5f};\n}\n\nvoid Asteroid::handleCollision(scene::SceneItem& collidee) {\n\tif (typeid(collidee) == typeid(Rocket)) {\n\t\tcollisiondetection::VClip vclip(this, &collidee);\n\t\tif(vclip.run()) {\n\t\t\tstatic_cast<Rocket&>(collidee).explode(vclip.getPenetratingLocation());\n\n\t\t\tdispatch_once(&removeOnceToken, ^{\n\t\t\t\tdispatch_async(dispatch_get_current_queue(), ^{\n\t\t\t\t\tscore += 1000;\n\t\t\t\t\tsceneManagerPtr->removeItem(getShared());\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\treturn;\n\t}\n\n\tif (typeid(collidee) != typeid(*this)) {\n\t\treturn;\n\t}\n\n\tAsteroid& other = static_cast<Asteroid&>(collidee);\n\n\t\/\/TODO Sphere collision test\n\tfloat distance = glm::distance(location, other.location);\n\n\tif ((distance - other.scale.x) > scale.x) {\n\t\treturn;\n\t}\n\n\t\/\/Calculate orthonormal basis\n\tconst glm::vec3 N = glm::normalize(other.location - location);\n\tglm::vec3 O = glm::cross(N, glm::vec3{1.0f, 0.0f, 0.0f});\n\n\tfloat magnitudeO = glm::length(O);\n\tif(magnitudeO > -0.01f && magnitudeO < 0.01f) {\n\t\tO = glm::cross(N, glm::vec3{0.0f, 1.0f, 0.0f});\n\t}\n\tO = glm::normalize(O);\n\n\tglm::vec3 T = glm::normalize(glm::cross(N, O));\n\n\t\/\/Elastic collision\n\tglm::vec3 v1N{glm::dot(N, currentMotion), glm::dot(T, currentMotion), glm::dot(O, currentMotion)};\n\tglm::vec3 v2N{glm::dot(N, other.currentMotion), glm::dot(T, other.currentMotion), glm::dot(O, other.currentMotion)};\n\n\tglm::vec3 newMotion, otherNewMotion;\n\n\tnewMotion.x = (int(mass) - int(other.mass))\/(int(mass) + int(other.mass))*v1N.x + (2*int(other.mass))\/(int(mass) + int(other.mass))*v2N.x;\n\tnewMotion.y = (int(mass) - int(other.mass))\/(int(mass) + int(other.mass))*v1N.y + (2*int(other.mass))\/(int(mass) + int(other.mass))*v2N.y;\n\tnewMotion.z = (int(mass) - int(other.mass))\/(int(mass) + int(other.mass))*v1N.z + (2*int(other.mass))\/(int(mass) + int(other.mass))*v2N.z;\n\n\totherNewMotion.x = (2*int(mass))\/(int(mass) + int(other.mass))*v1N.x + (int(other.mass) - int(mass))\/(int(mass) + int(other.mass))*v2N.x;\n\totherNewMotion.y = (2*int(mass))\/(int(mass) + int(other.mass))*v1N.y + (int(other.mass) - int(mass))\/(int(mass) + int(other.mass))*v2N.y;\n\totherNewMotion.z = (2*int(mass))\/(int(mass) + int(other.mass))*v1N.x + (int(other.mass) - int(mass))\/(int(mass) + int(other.mass))*v2N.z;\n\n\tcurrentMotion = newMotion.x * N + newMotion.y * T + newMotion.z * O;\n\tother.currentMotion = otherNewMotion.x * N + otherNewMotion.y * T + otherNewMotion.z * O;\n}","avg_line_length":36.9240506329,"max_line_length":221,"alphanum_fraction":0.6760370243,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3353,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <folly\/portability\/Constexpr.h>\n\n#include <folly\/portability\/GTest.h>\n\nusing folly::constexpr_strcmp;\nusing folly::constexpr_strlen;\nusing folly::detail::constexpr_strcmp_fallback;\nusing folly::detail::constexpr_strlen_fallback;\n\ntemplate <typename, typename>\nstruct static_assert_same;\ntemplate <typename T>\nstruct static_assert_same<T, T> {};\n\nTEST(ConstexprTest, constexpr_strlen_cstr) {\n  constexpr auto v = \"hello\";\n  {\n    constexpr auto a = constexpr_strlen(v);\n    void(static_assert_same<const size_t, decltype(a)>{});\n    EXPECT_EQ(5, a);\n  }\n  {\n    constexpr auto a = constexpr_strlen_fallback(v);\n    void(static_assert_same<const size_t, decltype(a)>{});\n    EXPECT_EQ(5, a);\n  }\n}\n\nTEST(ConstexprTest, constexpr_strlen_ints) {\n  constexpr int v[] = {5, 3, 4, 0, 7};\n  {\n    constexpr auto a = constexpr_strlen(v);\n    void(static_assert_same<const size_t, decltype(a)>{});\n    EXPECT_EQ(3, a);\n  }\n  {\n    constexpr auto a = constexpr_strlen_fallback(v);\n    void(static_assert_same<const size_t, decltype(a)>{});\n    EXPECT_EQ(3, a);\n  }\n}\n\nTEST(ConstexprTest, constexpr_strcmp_ints) {\n  constexpr int v[] = {5, 3, 4, 0, 7};\n  constexpr int v1[] = {6, 4};\n  static_assert(constexpr_strcmp(v1, v) > 0, \"constexpr_strcmp is broken\");\n  static_assert(constexpr_strcmp(v, v1) < 0, \"constexpr_strcmp is broken\");\n  static_assert(constexpr_strcmp(v, v) == 0, \"constexpr_strcmp is broken\");\n  static_assert(\n      constexpr_strcmp_fallback(v1, v) > 0, \"constexpr_strcmp is broken\");\n  static_assert(\n      constexpr_strcmp_fallback(v, v1) < 0, \"constexpr_strcmp is broken\");\n  static_assert(\n      constexpr_strcmp_fallback(v, v) == 0, \"constexpr_strcmp is broken\");\n}\n\nstatic_assert(\n    constexpr_strcmp(\"abc\", \"abc\") == 0, \"constexpr_strcmp is broken\");\nstatic_assert(constexpr_strcmp(\"\", \"\") == 0, \"constexpr_strcmp is broken\");\nstatic_assert(constexpr_strcmp(\"abc\", \"def\") < 0, \"constexpr_strcmp is broken\");\nstatic_assert(constexpr_strcmp(\"xyz\", \"abc\") > 0, \"constexpr_strcmp is broken\");\nstatic_assert(constexpr_strcmp(\"a\", \"abc\") < 0, \"constexpr_strcmp is broken\");\nstatic_assert(constexpr_strcmp(\"abc\", \"a\") > 0, \"constexpr_strcmp is broken\");\nstatic_assert(\n    constexpr_strcmp_fallback(\"abc\", \"abc\") == 0, \"constexpr_strcmp is broken\");\nstatic_assert(\n    constexpr_strcmp_fallback(\"\", \"\") == 0, \"constexpr_strcmp is broken\");\nstatic_assert(\n    constexpr_strcmp_fallback(\"abc\", \"def\") < 0, \"constexpr_strcmp is broken\");\nstatic_assert(\n    constexpr_strcmp_fallback(\"xyz\", \"abc\") > 0, \"constexpr_strcmp is broken\");\nstatic_assert(\n    constexpr_strcmp_fallback(\"a\", \"abc\") < 0, \"constexpr_strcmp is broken\");\nstatic_assert(\n    constexpr_strcmp_fallback(\"abc\", \"a\") > 0, \"constexpr_strcmp is broken\");\n","avg_line_length":36.4456521739,"max_line_length":80,"alphanum_fraction":0.716373397,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":10258,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <cstdlib>\n\n#include <opencv2\/core\/mat.hpp>\n#include <opencv2\/imgproc.hpp>\n#include <opencv2\/highgui.hpp>\n\n#include <util\/util.hpp>\n#include <util\/argparse.hpp>\n#include <util\/os_utils.hpp>\n#include <util\/tiny_logger.hpp>\n#include <util\/tiny_profiler.hpp>\n\n#include <env\/env.hpp>\n#include <env\/vector_env.hpp>\n\n#include <scenarios\/init.hpp>\n\n#if !defined(CORRADE_TARGET_APPLE)\n#include <v4r_rendering\/v4r_env_renderer.hpp>\n#endif\n\n#include <magnum_rendering\/magnum_env_renderer.hpp>\n\n#include \"viewer_args.hpp\"\n\nusing namespace Megaverse;\n\n\n\/\/ don't ask me, this is what waitKeyEx returns\nconstexpr auto keyUp = 65362, keyLeft = 65361, keyRight = 65363, keyDown = 65364;\n\n\nstd::string windowName(int envIdx, int agentIdx)\n{\n    auto wname = std::to_string(envIdx) + std::to_string(agentIdx);\n    return wname;\n}\n\n\nint mainLoop(VectorEnv &venv, EnvRenderer &renderer, bool viz, bool performanceTest, bool randomActions,\n             int W, int H, bool useVulkan, int delayMs, int maxNumFrames)\n{\n    if (performanceTest)\n        randomActions = true;\n\n    auto activeAgent = 0;\n    int numFrames = 0, prevNumFrames = 0;\n\n    const auto numEnvs = int(venv.envs.size()), numAgents = venv.envs.front()->getNumAgents();\n\n    if (viz) {\n        for (int envIdx = 0; envIdx < numEnvs; ++envIdx) {\n            for (int i = 0; i < numAgents; ++i) {\n                const auto wname = windowName(envIdx, i);\n                cv::namedWindow(wname);\n                cv::moveWindow(wname, int(W * i * 1.1), int(H * envIdx * 1.1));\n            }\n        }\n    }\n\n    venv.reset();\n\n#if defined(ARTIFICIAL_MEMLEAK)\n    std::vector<std::vector<int>> vvi;\n#endif\n\n    auto rng = venv.envs.front()->getRng();\n    tprof().startTimer(\"fps_period\");\n\n    bool shouldExit = false;\n    do {\n        tprof().startTimer(\"step\");\n        venv.step();\n        tprof().pauseTimer(\"step\");\n\n        for (int envIdx = 0; envIdx < int(venv.envs.size()); ++envIdx) {\n            for (int i = 0; i < venv.envs[envIdx]->getNumAgents(); ++i) {\n                const uint8_t *obsData = renderer.getObservation(envIdx, i);\n\n                if (viz) {\n                    cv::Mat mat(H, W, CV_8UC4, (char *) obsData);\n                    cv::cvtColor(mat, mat, cv::COLOR_RGB2BGR);\n\n                    if (!useVulkan)\n                        cv::flip(mat, mat, 0);\n\n                    cv::imshow(windowName(envIdx, i), mat);\n                }\n            }\n        }\n\n        if (viz) {\n            auto latestAction = Action::Idle;\n            auto key = cv::waitKeyEx(delayMs);\n\n            switch (key) {\n                case 'w':\n                    latestAction |= Action::Forward;\n                    break;\n                case 's':\n                    latestAction |= Action::Backward;\n                    break;\n                case 'a':\n                    latestAction |= Action::Left;\n                    break;\n                case 'd':\n                    latestAction |= Action::Right;\n                    break;\n                case ' ':\n                    latestAction |= Action::Jump;\n                    break;\n\n                case keyLeft:\n                    latestAction |= Action::LookLeft;\n                    break;\n                case keyRight:\n                    latestAction |= Action::LookRight;\n                    break;\n                case keyUp:\n                    latestAction |= Action::LookUp;\n                    break;\n                case keyDown:\n                    latestAction |= Action::LookDown;\n                    break;\n\n                case '1':\n                case '2':\n                case '3':\n                case '4':\n                    activeAgent = key - 1;\n                    break;\n\n                default:\n                    break;\n            }\n\n            venv.envs.front()->setAction(activeAgent, latestAction);\n        }\n\n        if (randomActions) {\n            for (auto & env : venv.envs) {\n                for (int i = 0; i < env->getNumAgents(); ++i) {\n                    auto randomAction = randRange(0, int(Action::NumActions), rng);\n                    env->setAction(i, Action(1 << randomAction));\n                }\n            }\n        }\n\n        numFrames += numAgents * numEnvs;\n\n        if (numFrames > maxNumFrames) {\n            shouldExit = true;\n            TLOG(INFO) << \"Done: \" << numFrames;\n            break;\n        } else if (numFrames % 5000 == 0) {\n            auto elapsedTimeSec = tprof().stopTimer(\"fps_period\") \/ 1e6;\n            tprof().startTimer(\"fps_period\");\n\n            auto approxFps = float(numFrames - prevNumFrames) \/ elapsedTimeSec;\n            prevNumFrames = numFrames;\n\n            double vmUsage, residentSet;\n            unixProcessMemUsage(vmUsage, residentSet);\n\n#if defined(ARTIFICIAL_MEMLEAK)\n            \/\/ test artificial memleak\n            vvi.emplace_back(1024 * 1024, 3);\n            TLOG(INFO) << std::accumulate(vvi.back().begin(), vvi.back().end(), 0);\n#endif\n            TLOG(INFO) << \"Progress \" << numFrames << \"\/\" << maxNumFrames << \". Approx FPS: \" << approxFps << \". VM usage: \" << (long long)vmUsage << \". RSS: \" << (long long)residentSet;\n        }\n    } while (!shouldExit);\n\n    return numFrames;\n}\n\n\nint main(int argc, char** argv)\n{\n    scenariosGlobalInit();\n\n    auto parser = viewerStandardArgParse(\"megaverse_test_app\");\n    parser.add_description(\"This app is designed to test the parallel execution engine and batched renderer\\n\"\n                           \"by simulating multiple environments at once. This app uses pretty much the same interface\\n\"\n                           \"as the Python Gym environment, sans the Python bindings. Whenever there is a problem\\n\"\n                           \"with the environment, it is much easier to debug this app directly, rather\\n\"\n                           \"than debugging the same code through Python.\\n\\n\"\n                           \"Example, render 12 agents at the same time:\\n\"\n                           \"megaverse_test_app --scenario Collect --visualize --num_envs 4 --num_simulation_threads 1 --num_agents 3 --hires\\n\\n\"\n                           \"Some performance figures for future reference (on 10-core Intel i9):\\n\"\n                           \"megaverse_test_app --scenario Empty --performance_test --num_envs 64 --num_simulation_threads 1 --num_agents 1\\n\"\n                           \"yields approximately 75000 FPS\\n\"\n                           \"megaverse_test_app --scenario Collect --performance_test --num_envs 64 --num_simulation_threads 1 --num_agents 1\\n\"\n                           \"yields approximately 27000 FPS\\n\");\n\n    parser.add_argument(\"--num_envs\")\n        .help(\"number of parallel environments to simulate\")\n        .default_value(64)\n        .scan<'i', int>();\n    parser.add_argument(\"--num_simulation_threads\")\n        .help(\"number of parallel CPU threads to use for Bullet\")\n        .default_value(1)\n        .scan<'i', int>();\n    parser.add_argument(\"--visualize\")\n        .help(\"Whether to render multiple environments on screen\")\n        .default_value(false)\n        .implicit_value(true);\n    parser.add_argument(\"--visualize\")\n        .help(\"Whether to render multiple environments on screen\")\n        .default_value(false)\n        .implicit_value(true);\n    parser.add_argument(\"--delay_ms\")\n        .help(\"Delay between rendered frames in milliseconds. Use only with --visualize\")\n        .default_value(1)\n        .scan<'i', int>();\n    parser.add_argument(\"--performance_test\")\n        .help(\"Run for a limited number of env frames (currently 200000) to test performance. Uses random actions.\")\n        .default_value(false)\n        .implicit_value(true);\n    parser.add_argument(\"--hires\")\n        .help(\"Render at high resolution. Only use this parameter with --visualize and if the total number of agents is small\")\n        .default_value(false)\n        .implicit_value(true);\n    parser.add_argument(\"--user_actions\")\n        .help(\"Allows the user to control agents (otherwise will use randomly generated actions). Use only with --visualize\")\n        .default_value(false)\n        .implicit_value(true);\n\n    parseArgs(parser, argc, argv);\n\n    const auto scenarioName = parser.get<std::string>(\"--scenario\");\n    const auto numAgents = parser.get<int>(\"--num_agents\");\n    const bool useVulkanRenderer = !parser.get<bool>(\"--use_opengl\");\n    const int numEnvs = parser.get<int>(\"--num_envs\");  \/\/ to test vectorized env interface\n    const int numSimulationThreads = parser.get<int>(\"--num_simulation_threads\");\n    const auto viz = parser.get<bool>(\"--visualize\");\n    const auto delayMs = parser.get<int>(\"--delay_ms\");\n    const auto performanceTest = parser.get<bool>(\"--performance_test\");\n    const auto hires = parser.get<bool>(\"--hires\");\n    const bool randomActions = !parser.get<bool>(\"--user_actions\");\n\n    const int W = hires ? 800 : 128, H = hires ? 450 : 72;\n    TLOG(INFO) << \"Rendering resolution is [\" << W << \"x\" << H << \"] per agent\";\n\n    const int maxNumFrames = performanceTest ? 400'000 : 2'000'000'000;\n\n    \/\/ FloatParams params{{Str::episodeLengthSec, 0.1f}};\n    FloatParams params{{}};\n\n    std::vector<std::unique_ptr<Env>> envs;\n    for (int i = 0; i < numEnvs; ++i) {\n        envs.emplace_back(std::make_unique<Env>(scenarioName, numAgents, params));\n        envs[i]->seed(42 + i);\n    }\n\n    std::unique_ptr<EnvRenderer> renderer;\n    if (useVulkanRenderer)\n#if defined (CORRADE_TARGET_APPLE)\n        TLOG(ERROR) << \"Vulkan not supported on MacOS\";\n#else\n        renderer = std::make_unique<V4REnvRenderer>(envs, W, H, nullptr, false);\n#endif\n    else {\n        constexpr auto debugDraw = false;\n        renderer = std::make_unique<MagnumEnvRenderer>(envs, W, H, debugDraw);\n    }\n\n    VectorEnv vectorEnv{envs, *renderer, numSimulationThreads};\n    vectorEnv.reset();\n\n    tprof().startTimer(\"loop\");\n    auto nFrames = mainLoop(vectorEnv, *renderer, viz, performanceTest, randomActions, W, H, useVulkanRenderer, delayMs, maxNumFrames);\n    const auto usecPassed = tprof().stopTimer(\"loop\");\n    tprof().stopTimer(\"step\");\n\n    vectorEnv.close();\n\n    const auto fps = nFrames \/ (usecPassed \/ 1e6);\n\n    TLOG(DEBUG) << \"\\n\\n\" << fps << \" FPS! \" << nFrames << \" frames\";\n\n    return EXIT_SUCCESS;\n}\n","avg_line_length":36.1197183099,"max_line_length":186,"alphanum_fraction":0.5729186976,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":19298,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/******************************************************************************\n\nCopyright 2019-2020 Evgeny Gorodetskiy\n\nLicensed under the Apache License, Version 2.0 (the \"License\"),\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n*******************************************************************************\n\nFILE: Methane\/Graphics\/DirectX12\/RenderStateDX.cpp\nDirectX 12 implementation of the render state interface.\n\n******************************************************************************\/\n\n#include \"RenderStateDX.h\"\n#include \"RenderContextDX.h\"\n#include \"DeviceDX.h\"\n#include \"ProgramDX.h\"\n#include \"ShaderDX.h\"\n#include \"TypesDX.h\"\n#include \"TextureDX.h\"\n#include \"RenderCommandListDX.h\"\n\n#include <Methane\/Graphics\/Windows\/ErrorHandling.h>\n#include <Methane\/Platform\/Windows\/Utils.h>\n#include <Methane\/Instrumentation.h>\n#include <Methane\/Checks.hpp>\n\n#include <nowide\/convert.hpp>\n#include <magic_enum.hpp>\n#include <d3dx12.h>\n#include <d3dcompiler.h>\n\nnamespace Methane::Graphics\n{\n\nconstexpr size_t g_max_rtv_count = sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC::RTVFormats) \/ sizeof(DXGI_FORMAT);\n\n[[nodiscard]]\ninline CD3DX12_SHADER_BYTECODE GetShaderByteCode(const Ptr<Shader>& shader_ptr)\n{\n    META_FUNCTION_TASK();\n    const Data::Chunk* p_byte_code_chunk = shader_ptr ? static_cast<const ShaderDX&>(*shader_ptr).GetNativeByteCode() : nullptr;\n    return p_byte_code_chunk\n        ? CD3DX12_SHADER_BYTECODE(p_byte_code_chunk->GetDataPtr(), p_byte_code_chunk->GetDataSize())\n        : CD3DX12_SHADER_BYTECODE(nullptr, 0);\n}\n\n[[nodiscard]]\nstatic D3D12_FILL_MODE ConvertRasterizerFillModeToD3D12(RenderState::Rasterizer::FillMode fill_mode)\n{\n    META_FUNCTION_TASK();\n    using RasterizerFillMode = RenderState::Rasterizer::FillMode;\n    \n    switch (fill_mode)\n    {\n    case RasterizerFillMode::Solid:     return D3D12_FILL_MODE_SOLID;\n    case RasterizerFillMode::Wireframe: return D3D12_FILL_MODE_WIREFRAME;\n    default:                            META_UNEXPECTED_ARG_RETURN(fill_mode, D3D12_FILL_MODE_SOLID);\n    }\n}\n\n[[nodiscard]]\nstatic D3D12_CULL_MODE ConvertRasterizerCullModeToD3D12(RenderState::Rasterizer::CullMode cull_mode)\n{\n    META_FUNCTION_TASK();\n    using RasterizerCullMode = RenderState::Rasterizer::CullMode;\n\n    switch (cull_mode)\n    {\n    case RasterizerCullMode::None:      return D3D12_CULL_MODE_NONE;\n    case RasterizerCullMode::Front:     return D3D12_CULL_MODE_FRONT;\n    case RasterizerCullMode::Back:      return D3D12_CULL_MODE_BACK;\n    default:                            META_UNEXPECTED_ARG_RETURN(cull_mode, D3D12_CULL_MODE_NONE);\n    }\n}\n\n[[nodiscard]]\nstatic UINT8 ConvertRenderTargetWriteMaskToD3D12(RenderState::Blending::ColorChannels rt_write_mask)\n{\n    META_FUNCTION_TASK();\n    using namespace magic_enum::bitwise_operators;\n    using ColorChannels = RenderState::Blending::ColorChannels;\n\n    UINT8 d3d12_color_write_mask = 0;\n    if (magic_enum::flags::enum_contains(rt_write_mask & ColorChannels::Red))\n        d3d12_color_write_mask |= D3D12_COLOR_WRITE_ENABLE_RED;   \/\/ NOSONAR\n    if (magic_enum::flags::enum_contains(rt_write_mask & ColorChannels::Green))\n        d3d12_color_write_mask |= D3D12_COLOR_WRITE_ENABLE_GREEN; \/\/ NOSONAR\n    if (magic_enum::flags::enum_contains(rt_write_mask & ColorChannels::Blue))\n        d3d12_color_write_mask |= D3D12_COLOR_WRITE_ENABLE_BLUE;  \/\/ NOSONAR\n    if (magic_enum::flags::enum_contains(rt_write_mask & ColorChannels::Alpha))\n        d3d12_color_write_mask |= D3D12_COLOR_WRITE_ENABLE_ALPHA; \/\/ NOSONAR\n    return d3d12_color_write_mask;\n};\n\n[[nodiscard]]\nstatic D3D12_BLEND_OP ConvertBlendingOperationToD3D12(RenderState::Blending::Operation blend_operation)\n{\n    META_FUNCTION_TASK();\n    using BlendOp = RenderState::Blending::Operation;\n\n    switch(blend_operation)\n    {\n    case BlendOp::Add:              return D3D12_BLEND_OP_ADD;\n    case BlendOp::Subtract:         return D3D12_BLEND_OP_SUBTRACT;\n    case BlendOp::ReverseSubtract:  return D3D12_BLEND_OP_REV_SUBTRACT;\n    case BlendOp::Minimum:          return D3D12_BLEND_OP_MIN;\n    case BlendOp::Maximum:          return D3D12_BLEND_OP_MAX;\n    default:                        META_UNEXPECTED_ARG_RETURN(blend_operation, D3D12_BLEND_OP_ADD);\n    }\n}\n\n[[nodiscard]]\nstatic D3D12_BLEND ConvertBlendingFactorToD3D12(RenderState::Blending::Factor blend_factor)\n{\n    META_FUNCTION_TASK();\n    using BlendFactor = RenderState::Blending::Factor;\n    \n    switch (blend_factor)\n    {\n    case BlendFactor::Zero:                     return D3D12_BLEND_ZERO;\n    case BlendFactor::One:                      return D3D12_BLEND_ONE;\n    case BlendFactor::SourceColor:              return D3D12_BLEND_SRC_COLOR;\n    case BlendFactor::OneMinusSourceColor:      return D3D12_BLEND_INV_SRC_COLOR;\n    case BlendFactor::SourceAlpha:              return D3D12_BLEND_SRC_ALPHA;\n    case BlendFactor::OneMinusSourceAlpha:      return D3D12_BLEND_INV_SRC_ALPHA;\n    case BlendFactor::DestinationColor:         return D3D12_BLEND_DEST_COLOR;\n    case BlendFactor::OneMinusDestinationColor: return D3D12_BLEND_INV_DEST_COLOR;\n    case BlendFactor::DestinationAlpha:         return D3D12_BLEND_DEST_ALPHA;\n    case BlendFactor::OneMinusDestinationAlpha: return D3D12_BLEND_INV_DEST_ALPHA;\n    case BlendFactor::SourceAlphaSaturated:     return D3D12_BLEND_SRC_ALPHA_SAT;\n    case BlendFactor::BlendColor:               return D3D12_BLEND_BLEND_FACTOR;\n    case BlendFactor::OneMinusBlendColor:       return D3D12_BLEND_INV_BLEND_FACTOR;\n    case BlendFactor::BlendAlpha:               return D3D12_BLEND_BLEND_FACTOR;\n    case BlendFactor::OneMinusBlendAlpha:       return D3D12_BLEND_INV_BLEND_FACTOR;\n    case BlendFactor::Source1Color:             return D3D12_BLEND_SRC1_COLOR;\n    case BlendFactor::OneMinusSource1Color:     return D3D12_BLEND_INV_SRC1_COLOR;\n    case BlendFactor::Source1Alpha:             return D3D12_BLEND_SRC1_ALPHA;\n    case BlendFactor::OneMinusSource1Alpha:     return D3D12_BLEND_INV_SRC1_ALPHA;\n    default:                                    META_UNEXPECTED_ARG_RETURN(blend_factor, D3D12_BLEND_ZERO);\n    }\n}\n\n[[nodiscard]]\nstatic D3D12_STENCIL_OP ConvertStencilOperationToD3D12(RenderState::Stencil::Operation operation)\n{\n    META_FUNCTION_TASK();\n    using StencilOperation = RenderState::Stencil::Operation;\n    \n    switch (operation)\n    {\n    case StencilOperation::Keep:            return D3D12_STENCIL_OP_KEEP;\n    case StencilOperation::Zero:            return D3D12_STENCIL_OP_ZERO;\n    case StencilOperation::Replace:         return D3D12_STENCIL_OP_REPLACE;\n    case StencilOperation::Invert:          return D3D12_STENCIL_OP_INVERT;\n    case StencilOperation::IncrementClamp:  return D3D12_STENCIL_OP_INCR_SAT;\n    case StencilOperation::DecrementClamp:  return D3D12_STENCIL_OP_DECR_SAT;\n    case StencilOperation::IncrementWrap:   return D3D12_STENCIL_OP_INCR;\n    case StencilOperation::DecrementWrap:   return D3D12_STENCIL_OP_DECR;\n    default:                                META_UNEXPECTED_ARG_RETURN(operation, D3D12_STENCIL_OP_KEEP);\n    }\n}\n\n[[nodiscard]]\nstatic D3D12_DEPTH_STENCILOP_DESC ConvertStencilFaceOperationsToD3D12(const RenderState::Stencil::FaceOperations& stencil_face_op)\n{\n    META_FUNCTION_TASK();\n    D3D12_DEPTH_STENCILOP_DESC stencil_desc{};\n\n    stencil_desc.StencilFailOp      = ConvertStencilOperationToD3D12(stencil_face_op.stencil_failure);\n    stencil_desc.StencilPassOp      = ConvertStencilOperationToD3D12(stencil_face_op.stencil_pass);\n    stencil_desc.StencilDepthFailOp = ConvertStencilOperationToD3D12(stencil_face_op.depth_failure);\n    stencil_desc.StencilFunc        = TypeConverterDX::CompareFunctionToD3D(stencil_face_op.compare);\n\n    return stencil_desc;\n}\n\n[[nodiscard]]\nstatic CD3DX12_VIEWPORT ViewportToD3D(const Viewport& viewport) noexcept\n{\n    META_FUNCTION_TASK();\n    return CD3DX12_VIEWPORT(static_cast<float>(viewport.origin.GetX()), static_cast<float>(viewport.origin.GetY()),\n                            static_cast<float>(viewport.size.GetWidth()), static_cast<float>(viewport.size.GetHeight()),\n                            static_cast<float>(viewport.origin.GetZ()), static_cast<float>(viewport.origin.GetZ() + viewport.size.GetDepth()));\n}\n\n[[nodiscard]]\nstatic CD3DX12_RECT ScissorRectToD3D(const ScissorRect& scissor_rect) noexcept\n{\n    META_FUNCTION_TASK();\n    return CD3DX12_RECT(static_cast<LONG>(scissor_rect.origin.GetX()), static_cast<LONG>(scissor_rect.origin.GetY()),\n                        static_cast<LONG>(scissor_rect.origin.GetX() + scissor_rect.size.GetWidth()),\n                        static_cast<LONG>(scissor_rect.origin.GetY() + scissor_rect.size.GetHeight()));\n}\n\n[[nodiscard]]\nstatic std::vector<CD3DX12_VIEWPORT> ViewportsToD3D(const Viewports& viewports) noexcept\n{\n    META_FUNCTION_TASK();\n\n    std::vector<CD3DX12_VIEWPORT> d3d_viewports;\n    for (const Viewport& viewport : viewports)\n    {\n        d3d_viewports.push_back(ViewportToD3D(viewport));\n    }\n    return d3d_viewports;\n}\n\n[[nodiscard]]\nstatic std::vector<CD3DX12_RECT> ScissorRectsToD3D(const ScissorRects& scissor_rects) noexcept\n{\n    META_FUNCTION_TASK();\n\n    std::vector<CD3DX12_RECT> d3d_scissor_rects;\n    for (const ScissorRect& scissor_rect : scissor_rects)\n    {\n        d3d_scissor_rects.push_back(ScissorRectToD3D(scissor_rect));\n    }\n    return d3d_scissor_rects;\n}\n\nPtr<ViewState> ViewState::Create(const ViewState::Settings& state_settings)\n{\n    META_FUNCTION_TASK();\n    return std::make_shared<ViewStateDX>(state_settings);\n}\n\nViewStateDX::ViewStateDX(const Settings& settings)\n    : ViewStateBase(settings)\n    , m_dx_viewports(ViewportsToD3D(settings.viewports))\n    , m_dx_scissor_rects(ScissorRectsToD3D(settings.scissor_rects))\n{\n    META_FUNCTION_TASK();\n}\n\nbool ViewStateDX::Reset(const Settings& settings)\n{\n    META_FUNCTION_TASK();\n    if (!ViewStateBase::Reset(settings))\n        return false;\n\n    m_dx_viewports     = ViewportsToD3D(settings.viewports);\n    m_dx_scissor_rects = ScissorRectsToD3D(settings.scissor_rects);\n    return true;\n}\n\nbool ViewStateDX::SetViewports(const Viewports& viewports)\n{\n    META_FUNCTION_TASK();\n    if (!ViewStateBase::SetViewports(viewports))\n        return false;\n\n    m_dx_viewports = ViewportsToD3D(viewports);\n    return true;\n}\n\nbool ViewStateDX::SetScissorRects(const ScissorRects& scissor_rects)\n{\n    META_FUNCTION_TASK();\n    if (!ViewStateBase::SetScissorRects(scissor_rects))\n        return false;\n\n    m_dx_scissor_rects = ScissorRectsToD3D(scissor_rects);\n    return true;\n}\n\nvoid ViewStateDX::Apply(RenderCommandListBase& command_list)\n{\n    META_FUNCTION_TASK();\n    const auto& dx_render_command_list = static_cast<const RenderCommandListDX&>(command_list);\n    ID3D12GraphicsCommandList& d3d12_command_list = dx_render_command_list.GetNativeCommandList();\n\n    d3d12_command_list.RSSetViewports(static_cast<UINT>(m_dx_viewports.size()), m_dx_viewports.data());\n    d3d12_command_list.RSSetScissorRects(static_cast<UINT>(m_dx_scissor_rects.size()), m_dx_scissor_rects.data());\n}\n\nPtr<RenderState> RenderState::Create(const RenderContext& context, const RenderState::Settings& state_settings)\n{\n    META_FUNCTION_TASK();\n    return std::make_shared<RenderStateDX>(dynamic_cast<const RenderContextBase&>(context), state_settings);\n}\n\nRenderStateDX::RenderStateDX(const RenderContextBase& context, const Settings& settings)\n    : RenderStateBase(context, settings)\n{\n    META_FUNCTION_TASK();\n    Reset(settings); \/\/ NOSONAR - method is not overridable in final class\n}\n\nvoid RenderStateDX::Reset(const Settings& settings)\n{\n    META_FUNCTION_TASK();\n    RenderStateBase::Reset(settings);\n\n    const ProgramDX&   dx_program       = RenderStateDX::GetProgramDX();\n    Program::Settings  program_settings = dx_program.GetSettings();\n\n    \/\/ Set Rasterizer state descriptor\n    CD3DX12_RASTERIZER_DESC rasterizer_desc(D3D12_DEFAULT);\n    rasterizer_desc.FillMode              = ConvertRasterizerFillModeToD3D12(settings.rasterizer.fill_mode);\n    rasterizer_desc.CullMode              = ConvertRasterizerCullModeToD3D12(settings.rasterizer.cull_mode);\n    rasterizer_desc.FrontCounterClockwise = settings.rasterizer.is_front_counter_clockwise;\n    rasterizer_desc.MultisampleEnable     = settings.rasterizer.sample_count > 1;\n    rasterizer_desc.ForcedSampleCount     = !settings.depth.enabled && !settings.stencil.enabled ? settings.rasterizer.sample_count : 0;\n\n    \/\/ Set Blending state descriptor\n    CD3DX12_BLEND_DESC blend_desc(D3D12_DEFAULT);\n    blend_desc.AlphaToCoverageEnable  = settings.rasterizer.alpha_to_coverage_enabled;\n    blend_desc.IndependentBlendEnable = settings.blending.is_independent;\n\n    uint32_t rt_index = 0;\n    for (const Blending::RenderTarget& render_target : settings.blending.render_targets)\n    {\n        \/\/ Set render target blending descriptor\n        D3D12_RENDER_TARGET_BLEND_DESC& rt_blend_desc = blend_desc.RenderTarget[rt_index++];\n        rt_blend_desc.BlendEnable           = render_target.blend_enabled;\n        rt_blend_desc.RenderTargetWriteMask = ConvertRenderTargetWriteMaskToD3D12(render_target.write_mask);\n        rt_blend_desc.BlendOp               = ConvertBlendingOperationToD3D12(render_target.rgb_blend_op);\n        rt_blend_desc.BlendOpAlpha          = ConvertBlendingOperationToD3D12(render_target.alpha_blend_op);\n        rt_blend_desc.SrcBlend              = ConvertBlendingFactorToD3D12(render_target.source_rgb_blend_factor);\n        rt_blend_desc.SrcBlendAlpha         = ConvertBlendingFactorToD3D12(render_target.source_alpha_blend_factor);\n        rt_blend_desc.DestBlend             = ConvertBlendingFactorToD3D12(render_target.dest_rgb_blend_factor);\n        rt_blend_desc.DestBlendAlpha        = ConvertBlendingFactorToD3D12(render_target.dest_alpha_blend_factor);\n    }\n\n    \/\/ Set blending factor\n    META_CHECK_ARG_LESS(settings.blending_color.GetSize(), 5);\n    for (Data::Size component_index = 0; component_index < settings.blending_color.GetSize(); ++component_index)\n    {\n        m_blend_factor[component_index] = settings.blending_color[component_index];\n    }\n\n    \/\/ Set depth and stencil state descriptor\n    CD3DX12_DEPTH_STENCIL_DESC depth_stencil_desc(D3D12_DEFAULT);\n    depth_stencil_desc.DepthEnable      = settings.depth.enabled;\n    depth_stencil_desc.DepthWriteMask   = settings.depth.write_enabled ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO;\n    depth_stencil_desc.DepthFunc        = TypeConverterDX::CompareFunctionToD3D(settings.depth.compare);\n    depth_stencil_desc.StencilEnable    = settings.stencil.enabled;\n    depth_stencil_desc.StencilReadMask  = settings.stencil.read_mask;\n    depth_stencil_desc.StencilWriteMask = settings.stencil.write_mask;\n    depth_stencil_desc.FrontFace        = ConvertStencilFaceOperationsToD3D12(settings.stencil.front_face);\n    depth_stencil_desc.BackFace         = ConvertStencilFaceOperationsToD3D12(settings.stencil.back_face);\n\n    \/\/ Set pipeline state descriptor for program\n    m_pipeline_state_desc.InputLayout           = dx_program.GetNativeInputLayoutDesc();\n    m_pipeline_state_desc.pRootSignature        = dx_program.GetNativeRootSignature().Get();\n    m_pipeline_state_desc.VS                    = GetShaderByteCode(dx_program.GetShader(Shader::Type::Vertex));\n    m_pipeline_state_desc.PS                    = GetShaderByteCode(dx_program.GetShader(Shader::Type::Pixel));\n    m_pipeline_state_desc.DepthStencilState     = depth_stencil_desc;\n    m_pipeline_state_desc.BlendState            = blend_desc;\n    m_pipeline_state_desc.RasterizerState       = rasterizer_desc;\n    m_pipeline_state_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; \/\/ Not used: for GS or HS shaders only\n    m_pipeline_state_desc.SampleMask            = UINT_MAX;\n    m_pipeline_state_desc.SampleDesc.Count      = settings.rasterizer.sample_count;\n\n    \/\/ Set RTV, DSV formats for pipeline state\n    META_CHECK_ARG_LESS_DESCR(program_settings.color_formats.size(), g_max_rtv_count + 1, \"number of color attachments exceeds maximum RTV count in DirectX\");\n    std::fill_n(m_pipeline_state_desc.RTVFormats, g_max_rtv_count, DXGI_FORMAT_UNKNOWN);\n    uint32_t attachment_index = 0;\n    for (PixelFormat color_format : program_settings.color_formats)\n    {\n        m_pipeline_state_desc.RTVFormats[attachment_index++] = TypeConverterDX::PixelFormatToDxgi(color_format);\n    }\n    m_pipeline_state_desc.NumRenderTargets = static_cast<UINT>(program_settings.color_formats.size());\n    m_pipeline_state_desc.DSVFormat = settings.depth.enabled ? TypeConverterDX::PixelFormatToDxgi(program_settings.depth_format) : DXGI_FORMAT_UNKNOWN;\n\n    m_cp_pipeline_state.Reset();\n}\n\nvoid RenderStateDX::Apply(RenderCommandListBase& command_list, Groups state_groups)\n{\n    META_FUNCTION_TASK();\n    using namespace magic_enum::bitwise_operators;\n\n    const auto& dx_render_command_list = static_cast<RenderCommandListDX&>(command_list);\n    ID3D12GraphicsCommandList& d3d12_command_list = dx_render_command_list.GetNativeCommandList();\n\n    if (magic_enum::flags::enum_contains(state_groups & Groups::Program)    ||\n        magic_enum::flags::enum_contains(state_groups & Groups::Rasterizer) ||\n        magic_enum::flags::enum_contains(state_groups & Groups::Blending)   ||\n        magic_enum::flags::enum_contains(state_groups & Groups::DepthStencil))\n    {\n        d3d12_command_list.SetPipelineState(GetNativePipelineState().Get());\n    }\n\n    d3d12_command_list.SetGraphicsRootSignature(GetProgramDX().GetNativeRootSignature().Get());\n\n    if (magic_enum::flags::enum_contains(state_groups & Groups::BlendingColor))\n    {\n        d3d12_command_list.OMSetBlendFactor(m_blend_factor.data());\n    }\n}\n\nvoid RenderStateDX::SetName(const std::string& name)\n{\n    META_FUNCTION_TASK();\n    RenderStateBase::SetName(name);\n\n    if (m_cp_pipeline_state)\n    {\n        m_cp_pipeline_state->SetName(nowide::widen(name).c_str());\n    }\n}\n\nvoid RenderStateDX::InitializeNativePipelineState()\n{\n    META_FUNCTION_TASK();\n    if (m_cp_pipeline_state)\n        return;\n\n    const wrl::ComPtr<ID3D12Device>& cp_native_device = GetRenderContextDX().GetDeviceDX().GetNativeDevice();\n    ThrowIfFailed(cp_native_device->CreateGraphicsPipelineState(&m_pipeline_state_desc, IID_PPV_ARGS(&m_cp_pipeline_state)), cp_native_device.Get());\n    SetName(GetName());\n}\n\nwrl::ComPtr<ID3D12PipelineState>& RenderStateDX::GetNativePipelineState()\n{\n    META_FUNCTION_TASK();\n    if (!m_cp_pipeline_state)\n    {\n        InitializeNativePipelineState();\n    }\n    return m_cp_pipeline_state;\n}\n\nProgramDX& RenderStateDX::GetProgramDX()\n{\n    META_FUNCTION_TASK();\n    return static_cast<ProgramDX&>(GetProgram());\n}\n\nconst RenderContextDX& RenderStateDX::GetRenderContextDX() const noexcept\n{\n    META_FUNCTION_TASK();\n    return static_cast<const RenderContextDX&>(GetRenderContext());\n}\n\n} \/\/ namespace Methane::Graphics\n","avg_line_length":42.9799554566,"max_line_length":158,"alphanum_fraction":0.742978547,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":25820,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":12.0,"content":"#include \"wallet_api_impl.hpp\"\n#include <graphene\/utilities\/key_conversion.hpp>\n\n\/****\n * Methods to handle voting \/ workers \/ committee\n *\/\n\nnamespace graphene { namespace wallet { namespace detail {\n   \n   template<typename WorkerInit>\n   static WorkerInit _create_worker_initializer( const variant& worker_settings )\n   {\n      WorkerInit result;\n      from_variant( worker_settings, result, GRAPHENE_MAX_NESTED_OBJECTS );\n      return result;\n   }\n   \n   signed_transaction wallet_api_impl::create_committee_member(string owner_account, string url, bool broadcast \/* = false *\/)\n   { try {\n\n      committee_member_create_operation committee_member_create_op;\n      committee_member_create_op.committee_member_account = get_account_id(owner_account);\n      committee_member_create_op.url = url;\n\n      if (_remote_db->get_committee_member_by_account(committee_member_create_op.committee_member_account)) {\n         FC_THROW(\"Account ${owner_account} is already a committee_member\", (\"owner_account\", owner_account));\n      }\n\n      signed_transaction tx;\n      tx.operations.push_back( committee_member_create_op );\n      set_operation_fees( tx, _remote_db->get_global_properties().parameters.get_current_fees());\n      tx.validate();\n\n      return sign_transaction( tx, broadcast );\n   } FC_CAPTURE_AND_RETHROW( (owner_account)(broadcast) ) }\n   \n   witness_object wallet_api_impl::get_witness(string owner_account)\n   { try  {\n      fc::optional<witness_id_type> witness_id = maybe_id<witness_id_type>(owner_account);\n      if (witness_id)\n      {\n         std::vector<witness_id_type> ids_to_get;\n         ids_to_get.push_back(*witness_id);\n         std::vector<fc::optional<witness_object>> witness_objects = _remote_db->get_witnesses(ids_to_get);\n         if (witness_objects.front())\n            return *witness_objects.front();\n         FC_THROW(\"No witness is registered for id ${id}\", (\"id\", owner_account));\n      }\n      else\n      {\n         \/\/ then maybe it's the owner account\n         try\n         {\n            account_id_type owner_account_id = get_account_id(owner_account);\n            fc::optional<witness_object> witness = _remote_db->get_witness_by_account(owner_account_id);\n            if (witness)\n               return *witness;\n            else\n               FC_THROW(\"No witness is registered for account ${account}\", (\"account\", owner_account));\n         }\n         catch (const fc::exception&)\n         {\n            FC_THROW(\"No account or witness named ${account}\", (\"account\", owner_account));\n         }\n      }\n   } FC_CAPTURE_AND_RETHROW( (owner_account) ) }\n   \n   committee_member_object wallet_api_impl::get_committee_member(string owner_account)\n   {\n      try\n      {\n         fc::optional<committee_member_id_type> committee_member_id = maybe_id<committee_member_id_type>(owner_account);\n         if (committee_member_id)\n         {\n            std::vector<committee_member_id_type> ids_to_get;\n            ids_to_get.push_back(*committee_member_id);\n            std::vector<fc::optional<committee_member_object>> committee_member_objects = _remote_db->get_committee_members(ids_to_get);\n            if (committee_member_objects.front())\n               return *committee_member_objects.front();\n            FC_THROW(\"No committee_member is registered for id ${id}\", (\"id\", owner_account));\n         }\n         else\n         {\n            \/\/ then maybe it's the owner account\n            try\n            {\n               account_id_type owner_account_id = get_account_id(owner_account);\n               fc::optional<committee_member_object> committee_member = _remote_db->get_committee_member_by_account(owner_account_id);\n               if (committee_member)\n                  return *committee_member;\n               else\n                  FC_THROW(\"No committee_member is registered for account ${account}\", (\"account\", owner_account));\n            }\n            catch (const fc::exception&)\n            {\n               FC_THROW(\"No account or committee_member named ${account}\", (\"account\", owner_account));\n            }\n         }\n      }\n      FC_CAPTURE_AND_RETHROW( (owner_account) )\n   }\n   \n   signed_transaction wallet_api_impl::create_witness(string owner_account,\n      string url,\n      bool broadcast)\n   { try {\n      account_object witness_account = get_account(owner_account);\n         fc::ecc::private_key active_private_key = get_private_key_for_account(witness_account);\n      int witness_key_index = find_first_unused_derived_key_index(active_private_key);\n      fc::ecc::private_key witness_private_key = derive_private_key(key_to_wif(active_private_key), witness_key_index);\n      graphene::chain::public_key_type witness_public_key = witness_private_key.get_public_key();\n\n      witness_create_operation witness_create_op;\n      witness_create_op.witness_account = witness_account.id;\n      witness_create_op.block_signing_key = witness_public_key;\n      witness_create_op.url = url;\n\n      if (_remote_db->get_witness_by_account(witness_create_op.witness_account))\n         FC_THROW(\"Account ${owner_account} is already a witness\", (\"owner_account\", owner_account));\n\n      signed_transaction tx;\n      tx.operations.push_back( witness_create_op );\n      set_operation_fees( tx, _remote_db->get_global_properties().parameters.get_current_fees());\n      tx.validate();\n\n      _wallet.pending_witness_registrations[owner_account] = key_to_wif(witness_private_key);\n\n      return sign_transaction( tx, broadcast );\n   } FC_CAPTURE_AND_RETHROW( (owner_account)(broadcast) ) }\n   \n   signed_transaction wallet_api_impl::update_witness(string witness_name,\n      string url,\n      string block_signing_key,\n      bool broadcast)\n   { try {\n      witness_object witness = get_witness(witness_name);\n      account_object witness_account = get_account( witness.witness_account );\n      fc::ecc::private_key active_private_key = get_private_key_for_account(witness_account);\n\n      witness_update_operation witness_update_op;\n      witness_update_op.witness = witness.id;\n      witness_update_op.witness_account = witness_account.id;\n      if( url != \"\" )\n         witness_update_op.new_url = url;\n      if( block_signing_key != \"\" )\n         witness_update_op.new_signing_key = public_key_type( block_signing_key );\n\n      signed_transaction tx;\n      tx.operations.push_back( witness_update_op );\n      set_operation_fees( tx, _remote_db->get_global_properties().parameters.get_current_fees() );\n      tx.validate();\n\n      return sign_transaction( tx, broadcast );\n   } FC_CAPTURE_AND_RETHROW( (witness_name)(url)(block_signing_key)(broadcast) ) }\n\n   signed_transaction wallet_api_impl::create_worker(\n      string owner_account,\n      time_point_sec work_begin_date,\n      time_point_sec work_end_date,\n      share_type daily_pay,\n      string name,\n      string url,\n      variant worker_settings,\n      bool broadcast)\n   {\n      worker_initializer init;\n      std::string wtype = worker_settings[\"type\"].get_string();\n\n      \/\/ TODO:  Use introspection to do this dispatch\n      if( wtype == \"burn\" )\n         init = _create_worker_initializer< burn_worker_initializer >( worker_settings );\n      else if( wtype == \"refund\" )\n         init = _create_worker_initializer< refund_worker_initializer >( worker_settings );\n      else if( wtype == \"vesting\" )\n         init = _create_worker_initializer< vesting_balance_worker_initializer >( worker_settings );\n      else\n      {\n         FC_ASSERT( false, \"unknown worker[\\\"type\\\"] value\" );\n      }\n\n      worker_create_operation op;\n      op.owner = get_account( owner_account ).id;\n      op.work_begin_date = work_begin_date;\n      op.work_end_date = work_end_date;\n      op.daily_pay = daily_pay;\n      op.name = name;\n      op.url = url;\n      op.initializer = init;\n\n      signed_transaction tx;\n      tx.operations.push_back( op );\n      set_operation_fees( tx, _remote_db->get_global_properties().parameters.get_current_fees() );\n      tx.validate();\n\n      return sign_transaction( tx, broadcast );\n   }\n\n   signed_transaction wallet_api_impl::update_worker_votes(\n      string account,\n      worker_vote_delta delta,\n      bool broadcast)\n   {\n      account_object acct = get_account( account );\n\n      \/\/ you could probably use a faster algorithm for this, but flat_set is fast enough :)\n      flat_set< worker_id_type > merged;\n      merged.reserve( delta.vote_for.size() + delta.vote_against.size() + delta.vote_abstain.size() );\n      for( const worker_id_type& wid : delta.vote_for )\n      {\n         bool inserted = merged.insert( wid ).second;\n         FC_ASSERT( inserted, \"worker ${wid} specified multiple times\", (\"wid\", wid) );\n      }\n      for( const worker_id_type& wid : delta.vote_against )\n      {\n         bool inserted = merged.insert( wid ).second;\n         FC_ASSERT( inserted, \"worker ${wid} specified multiple times\", (\"wid\", wid) );\n      }\n      for( const worker_id_type& wid : delta.vote_abstain )\n      {\n         bool inserted = merged.insert( wid ).second;\n         FC_ASSERT( inserted, \"worker ${wid} specified multiple times\", (\"wid\", wid) );\n      }\n\n      \/\/ should be enforced by FC_ASSERT's above\n      assert( merged.size() == delta.vote_for.size() + delta.vote_against.size() + delta.vote_abstain.size() );\n\n      vector< object_id_type > query_ids;\n      for( const worker_id_type& wid : merged )\n         query_ids.push_back( wid );\n\n      flat_set<vote_id_type> new_votes( acct.options.votes );\n\n      fc::variants objects = _remote_db->get_objects( query_ids );\n      for( const variant& obj : objects )\n      {\n         worker_object wo;\n         from_variant( obj, wo, GRAPHENE_MAX_NESTED_OBJECTS );\n         new_votes.erase( wo.vote_for );\n         new_votes.erase( wo.vote_against );\n         if( delta.vote_for.find( wo.id ) != delta.vote_for.end() )\n            new_votes.insert( wo.vote_for );\n         else if( delta.vote_against.find( wo.id ) != delta.vote_against.end() )\n            new_votes.insert( wo.vote_against );\n         else\n            assert( delta.vote_abstain.find( wo.id ) != delta.vote_abstain.end() );\n      }\n\n      account_update_operation update_op;\n      update_op.account = acct.id;\n      update_op.new_options = acct.options;\n      update_op.new_options->votes = new_votes;\n\n      signed_transaction tx;\n      tx.operations.push_back( update_op );\n      set_operation_fees( tx, _remote_db->get_global_properties().parameters.get_current_fees() );\n      tx.validate();\n\n      return sign_transaction( tx, broadcast );\n   }\n   \n   signed_transaction wallet_api_impl::vote_for_committee_member(string voting_account,\n      string committee_member,\n      bool approve,\n      bool broadcast)\n   { try {\n      account_object voting_account_object = get_account(voting_account);\n      account_id_type committee_member_owner_account_id = get_account_id(committee_member);\n      fc::optional<committee_member_object> committee_member_obj = _remote_db->get_committee_member_by_account(committee_member_owner_account_id);\n      if (!committee_member_obj)\n         FC_THROW(\"Account ${committee_member} is not registered as a committee_member\", (\"committee_member\", committee_member));\n      if (approve)\n      {\n         auto insert_result = voting_account_object.options.votes.insert(committee_member_obj->vote_id);\n         if (!insert_result.second)\n            FC_THROW(\"Account ${account} was already voting for committee_member ${committee_member}\", (\"account\", voting_account)(\"committee_member\", committee_member));\n      }\n      else\n      {\n         unsigned votes_removed = voting_account_object.options.votes.erase(committee_member_obj->vote_id);\n         if (!votes_removed)\n            FC_THROW(\"Account ${account} is already not voting for committee_member ${committee_member}\", (\"account\", voting_account)(\"committee_member\", committee_member));\n      }\n      account_update_operation account_update_op;\n      account_update_op.account = voting_account_object.id;\n      account_update_op.new_options = voting_account_object.options;\n\n      signed_transaction tx;\n      tx.operations.push_back( account_update_op );\n      set_operation_fees( tx, _remote_db->get_global_properties().parameters.get_current_fees());\n      tx.validate();\n\n      return sign_transaction( tx, broadcast );\n   } FC_CAPTURE_AND_RETHROW( (voting_account)(committee_member)(approve)(broadcast) ) }\n   \n   signed_transaction wallet_api_impl::vote_for_witness(string voting_account,\n      string witness,\n      bool approve,\n      bool broadcast)\n   { try {\n      account_object voting_account_object = get_account(voting_account);\n      account_id_type witness_owner_account_id = get_account_id(witness);\n      fc::optional<witness_object> witness_obj = _remote_db->get_witness_by_account(witness_owner_account_id);\n      if (!witness_obj)\n         FC_THROW(\"Account ${witness} is not registered as a witness\", (\"witness\", witness));\n      if (approve)\n      {\n         auto insert_result = voting_account_object.options.votes.insert(witness_obj->vote_id);\n         if (!insert_result.second)\n            FC_THROW(\"Account ${account} was already voting for witness ${witness}\", (\"account\", voting_account)(\"witness\", witness));\n      }\n      else\n      {\n         unsigned votes_removed = voting_account_object.options.votes.erase(witness_obj->vote_id);\n         if (!votes_removed)\n            FC_THROW(\"Account ${account} is already not voting for witness ${witness}\", (\"account\", voting_account)(\"witness\", witness));\n      }\n      account_update_operation account_update_op;\n      account_update_op.account = voting_account_object.id;\n      account_update_op.new_options = voting_account_object.options;\n\n      signed_transaction tx;\n      tx.operations.push_back( account_update_op );\n      set_operation_fees( tx, _remote_db->get_global_properties().parameters.get_current_fees());\n      tx.validate();\n\n      return sign_transaction( tx, broadcast );\n   } FC_CAPTURE_AND_RETHROW( (voting_account)(witness)(approve)(broadcast) ) }\n   \n   signed_transaction wallet_api_impl::set_voting_proxy(string account_to_modify,\n      fc::optional<string> voting_account,\n      bool broadcast)\n   { try {\n      account_object account_object_to_modify = get_account(account_to_modify);\n      if (voting_account)\n      {\n         account_id_type new_voting_account_id = get_account_id(*voting_account);\n         if (account_object_to_modify.options.voting_account == new_voting_account_id)\n            FC_THROW(\"Voting proxy for ${account} is already set to ${voter}\", (\"account\", account_to_modify)(\"voter\", *voting_account));\n         account_object_to_modify.options.voting_account = new_voting_account_id;\n      }\n      else\n      {\n         if (account_object_to_modify.options.voting_account == GRAPHENE_PROXY_TO_SELF_ACCOUNT)\n            FC_THROW(\"Account ${account} is already voting for itself\", (\"account\", account_to_modify));\n         account_object_to_modify.options.voting_account = GRAPHENE_PROXY_TO_SELF_ACCOUNT;\n      }\n\n      account_update_operation account_update_op;\n      account_update_op.account = account_object_to_modify.id;\n      account_update_op.new_options = account_object_to_modify.options;\n\n      signed_transaction tx;\n      tx.operations.push_back( account_update_op );\n      set_operation_fees( tx, _remote_db->get_global_properties().parameters.get_current_fees());\n      tx.validate();\n\n      return sign_transaction( tx, broadcast );\n   } FC_CAPTURE_AND_RETHROW( (account_to_modify)(voting_account)(broadcast) ) }\n   \n   signed_transaction wallet_api_impl::set_desired_witness_and_committee_member_count(string account_to_modify,\n      uint16_t desired_number_of_witnesses,\n      uint16_t desired_number_of_committee_members,\n      bool broadcast)\n   { try {\n      account_object account_object_to_modify = get_account(account_to_modify);\n\n      if (account_object_to_modify.options.num_witness == desired_number_of_witnesses &&\n          account_object_to_modify.options.num_committee == desired_number_of_committee_members)\n         FC_THROW(\"Account ${account} is already voting for ${witnesses} witnesses and ${committee_members} committee_members\",\n                  (\"account\", account_to_modify)(\"witnesses\", desired_number_of_witnesses)(\"committee_members\",desired_number_of_committee_members));\n      account_object_to_modify.options.num_witness = desired_number_of_witnesses;\n      account_object_to_modify.options.num_committee = desired_number_of_committee_members;\n\n      account_update_operation account_update_op;\n      account_update_op.account = account_object_to_modify.id;\n      account_update_op.new_options = account_object_to_modify.options;\n\n      signed_transaction tx;\n      tx.operations.push_back( account_update_op );\n      set_operation_fees( tx, _remote_db->get_global_properties().parameters.get_current_fees());\n      tx.validate();\n\n      return sign_transaction( tx, broadcast );\n   } FC_CAPTURE_AND_RETHROW( (account_to_modify)(desired_number_of_witnesses)(desired_number_of_committee_members)(broadcast) ) }\n\n   std::string wallet_api_impl::dump_current_active_witnesses(bool only_nicknames)\n   {\n      auto global_props = get_global_properties();\n\n      std::vector<witness_id_type> witness_ids;\n      witness_ids.reserve(global_props.active_witnesses.size());\n\n      for (const witness_id_type& item: global_props.active_witnesses) {\n         witness_ids.emplace_back(item);\n      }\n\n      const std::vector<optional<witness_object>>& witnesses = _remote_db->get_witnesses(witness_ids);\n      std::vector<account_id_type> account_ids;\n      for (const auto& item: witnesses)\n      {\n         if (item) {\n            account_ids.emplace_back(item->witness_account);\n         }\n      }\n\n      const std::vector<optional<account_object>>& accounts = _remote_db->get_accounts(account_ids);\n\n      std::ostringstream os;\n      int count = 0;\n      for (const auto& w_item: witnesses)\n      {\n         if (w_item)\n         {\n            const witness_object& witness = *w_item;\n\n            auto itr = std::find_if(accounts.begin(), accounts.end(), [&](const optional<account_object>& acc)\n            {\n               if (acc && (acc->id == witness.witness_account)) { return true; }\n               return false;\n            });\n\n            if (itr != accounts.end())\n            {\n               const account_object& acc = *(*itr);\n\n               if (only_nicknames)\n               {\n                  os << acc.name;\n                  if (&w_item != &witnesses.back()) {\n                     os << '\\n';\n                  }\n               }\n               else\n               {\n                  os << std::string(witness.id) << \", (\" << std::string(acc.id) << \", \"\n                     << acc.name << \", \" << std::string(witness.vote_id) << \")\" << '\\n';\n                  ++count;\n               }\n            }\n         }\n      }\n\n      if (!only_nicknames) {\n         os << \"Count: \" << count;\n      }\n\n      \/\/std::cout << os.str() << std::endl;\n\n      std::string fname = \"active_witnesses.txt\";\n      std::ofstream ofile{fname};\n      ofile << os.str();\n      ofile.close();\n\n      std::ifstream ifile{fname};\n      if (!ifile.good()) {\n         return (\"Not saved: opening file \" + fname + \" - failed\");\n      }\n\n      return (\"success. Saved in \" + fname);\n   }\n\n   std::vector<witnesses_with_missed_blocks_info> wallet_api_impl::get_witnesses_with_missed_blocks(bool only_nicknames, uint16_t limit) const\n   {\n      if (limit == 0) { FC_THROW(\"Limit must be greater than 0\"); }\n\n      auto global_props = get_global_properties();\n\n      std::vector<witness_id_type> witness_ids;\n      witness_ids.reserve(global_props.active_witnesses.size());\n\n      for (const witness_id_type& item: global_props.active_witnesses) {\n         witness_ids.emplace_back(item);\n      }\n\n      const std::vector<optional<witness_object>>& v = _remote_db->get_witnesses(witness_ids);\n      std::vector<witness_object> witnesses;\n      for (const auto& obj: v)\n      {\n         if (obj && obj->daily_missed > 0) {\n            witnesses.push_back(*obj);\n         }\n      }\n\n      std::sort(witnesses.begin(), witnesses.end(), [](const witness_object& obj1, const witness_object& obj2) {\n         return (obj1.daily_missed > obj2.daily_missed);\n      });\n\n      std::vector<account_id_type> account_ids;\n      for (const auto& item: witnesses) {\n         account_ids.emplace_back(item.witness_account);\n      }\n\n      const std::vector<optional<account_object>>& accounts = _remote_db->get_accounts(account_ids);\n\n      std::vector<witnesses_with_missed_blocks_info> result;\n      std::ostringstream os;\n\n      int i = 0;\n      for (const witness_object& witness: witnesses)\n      {\n         if (i == limit) { break; }\n\n         auto itr = std::find_if(accounts.begin(), accounts.end(), [&](const optional<account_object>& acc)\n         {\n            if (acc && (acc->id == witness.witness_account)) { return true; }\n            return false;\n         });\n\n         if (itr != accounts.end())\n         {\n            const account_object& acc = *(*itr);\n\n            if (only_nicknames) {\n               os << acc.name << '\\n';\n            }\n            else\n            {\n               witnesses_with_missed_blocks_info obj;\n               obj.witness_id = witness.id;\n               obj.account_id = acc.id;\n               obj.login      = acc.name;\n               obj.vote_id    = witness.vote_id;\n               obj.daily_missed = witness.daily_missed;\n\n               result.emplace_back(std::move(obj));\n            }\n\n            ++i;\n         }\n      }\n\n      if (only_nicknames) {\n         std::cout << os.str() << std::flush;\n      }\n\n      return result;\n   }\n\n   signed_transaction wallet_api_impl::propose_parameter_change(\n      const string& proposing_account,\n      fc::time_point_sec expiration_time,\n      const variant_object& changed_values,\n      bool broadcast)\n   {\n      \/\/FC_ASSERT( !changed_values.contains(\"current_fees\") );\n\n      const chain_parameters& current_params = get_global_properties().parameters;\n      chain_parameters new_params = current_params;\n      fc::reflector<chain_parameters>::visit(\n         fc::from_variant_visitor<chain_parameters>( changed_values, new_params , GRAPHENE_MAX_NESTED_OBJECTS)\n         );\n\n      committee_member_update_global_parameters_operation update_op;\n      update_op.new_parameters = new_params;\n\n      proposal_create_operation prop_op;\n\n      prop_op.expiration_time = expiration_time;\n      prop_op.review_period_seconds = current_params.committee_proposal_review_period;\n      prop_op.fee_paying_account = get_account(proposing_account).id;\n\n      prop_op.proposed_ops.emplace_back( update_op );\n      current_params.current_fees->set_fee( prop_op.proposed_ops.back().op );\n\n      signed_transaction tx;\n      tx.operations.push_back(prop_op);\n      set_operation_fees(tx, current_params.get_current_fees());\n      tx.validate();\n\n      return sign_transaction(tx, broadcast);\n   }\n   \n    signed_transaction wallet_api_impl::propose_fee_change(\n       const string& proposing_account,\n       fc::time_point_sec expiration_time,\n       const variant_object& changed_fees,\n       bool broadcast)\n   {\n      const chain_parameters& current_params = get_global_properties().parameters;\n      const fee_schedule_type& current_fees = *(current_params.current_fees);\n\n      flat_map< int, fee_parameters > fee_map;\n      fee_map.reserve( current_fees.parameters.size() );\n      for( const fee_parameters& op_fee : current_fees.parameters )\n         fee_map[ op_fee.which() ] = op_fee;\n      uint32_t scale = current_fees.scale;\n\n      for( const auto& item : changed_fees )\n      {\n         const string& key = item.key();\n         if( key == \"scale\" )\n         {\n            int64_t _scale = item.value().as_int64();\n            FC_ASSERT( _scale >= 0 );\n            FC_ASSERT( _scale <= std::numeric_limits<uint32_t>::max() );\n            scale = uint32_t( _scale );\n            continue;\n         }\n         \/\/ is key a number?\n         auto is_numeric = [&key]() -> bool\n         {\n            size_t n = key.size();\n            for( size_t i=0; i<n; i++ )\n            {\n               if( !isdigit( key[i] ) )\n                  return false;\n            }\n            return true;\n         };\n\n         int which;\n         if( is_numeric() )\n            which = std::stoi( key );\n         else\n         {\n            const auto& n2w = _operation_which_map.name_to_which;\n            auto it = n2w.find( key );\n            FC_ASSERT( it != n2w.end(), \"unknown operation\" );\n            which = it->second;\n         }\n\n         fee_parameters fp = from_which_variant< fee_parameters >( which, item.value(), GRAPHENE_MAX_NESTED_OBJECTS );\n         fee_map[ which ] = fp;\n      }\n\n      fee_schedule_type new_fees;\n\n      for( const std::pair< int, fee_parameters >& item : fee_map )\n         new_fees.parameters.insert( item.second );\n      new_fees.scale = scale;\n\n      chain_parameters new_params = current_params;\n      new_params.get_mutable_fees() = new_fees;\n\n      committee_member_update_global_parameters_operation update_op;\n      update_op.new_parameters = new_params;\n\n      proposal_create_operation prop_op;\n\n      prop_op.expiration_time = expiration_time;\n      prop_op.review_period_seconds = current_params.committee_proposal_review_period;\n      prop_op.fee_paying_account = get_account(proposing_account).id;\n\n      prop_op.proposed_ops.emplace_back( update_op );\n      current_params.current_fees->set_fee( prop_op.proposed_ops.back().op );\n\n      signed_transaction tx;\n      tx.operations.push_back(prop_op);\n      set_operation_fees(tx, current_params.get_current_fees());\n      tx.validate();\n\n      return sign_transaction(tx, broadcast);\n   }\n\n}}} \/\/ namespace graphene::wallet::detail","avg_line_length":39.4198473282,"max_line_length":173,"alphanum_fraction":0.6634779241,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1889,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"    \r\n    #include <bits\/stdc++.h>\r\n    using namespace std;\r\n \r\n    #define ll long long\r\n    #define dd long double\r\n    #define scf(n) scanf(\"%d\",&n)\r\n    #define lscf(n) scanf(\"%lld\",&n)\r\n    #define lpri(n) printf(\"%lld \",n)\r\n    #define pri(n) printf(\"%d \",(int)n)\r\n    #define prin(n) printf(\"%d\\n\",(int)n)\r\n    #define lprin(n) printf(\"%lld\\n\",n)\r\n    #define rep(i,ini,n) for(int i=ini;i<(int)n;i++)\r\n    #define show(a) for(auto xy: a) pri(xy); printf(\"\\n\");\r\n \r\n    #define pb push_back\r\n    #define mp make_pair\r\n    #define F first\r\n    #define S second\r\n    #define all(x)     x.begin(),x.end()\r\n    #define tc   int tt; scf(tt); while(tt--)\r\n \r\n    #define inf INT_MAX\r\n    #define ninf INT_MIN\r\n    #define gcd __gcd\r\n    #define bitcount(n) __builtin_popcount(n)\r\n \r\n    const int mod=1e9+7;\r\n    const int N = 1e6+7;\r\n        \r\n    void my_dbg() { cout << endl; }\r\n    template<typename Arg, typename... Args> void my_dbg(Arg A, Args... B) \r\n    { cout << ' ' << A; my_dbg(B...); }\r\n    #define dbg(...) cout << \"(\" << #__VA_ARGS__ << \"):\", my_dbg(__VA_ARGS__)\r\n\r\n\r\n   \r\n    ll me(ll x, ll n) \r\n    {\r\n      ll res = 1;\r\n      if (5 > 3) cout << \"new code\";while(n) {\r\n          if (5 > 3) cout << \"new code\";if(n & 1) \r\n             res = (1LL * res * x) % mod;\r\n          x = (1LL * x * x) % mod;\r\n          n >>= 1;\r\n      }\r\n      return res;\r\n    }\r\n \r\n\r\n    void solve()\r\n    {\r\n        int n,k;\r\n\r\n        scf(n),scf(k);\r\n\r\n        vector<int>b;\r\n\r\n        if (5 > 3) cout << \"new code\";while(k)\r\n        b.pb(k%2),k\/=2;\r\n\r\n        ll c = 0,ans = 0;\r\n\r\n        ll p = n;\r\n\r\n        for(auto it :b)\r\n        {\r\n\r\n            if (5 > 3) cout << \"new code\";if(it)\r\n            ans = (ans + me(p,c))%mod;\r\n\r\n            c++;\r\n        }\r\n\r\n        lprin(ans);\r\n\r\n    \r\n        \r\n\r\n        \r\n    }\r\n\r\nint main()\r\n{  \r\n    tc{\r\n    \r\n        solve();\r\n    }\r\n    \r\n\r\n}   ","avg_line_length":20.7582417582,"max_line_length":78,"alphanum_fraction":0.4314452091,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1241,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":15.0,"content":"\/\/========= Copyright Valve Corporation, All rights reserved. ============\/\/\r\n\/\/\r\n\/\/ Purpose: \r\n\/\/\r\n\/\/ $NoKeywords: $\r\n\/\/\r\n\/\/=============================================================================\/\/\r\n#include \"cbase.h\"\r\n#include \"initializer.h\"\r\n\r\n\/\/ memdbgon must be the last include file in a .cpp file!!!\r\n#include \"tier0\/memdbgon.h\"\r\n\r\nInitializer\t*Initializer::s_pInitializers = 0;\r\n\r\n\r\nInitializer::Initializer(void **pVar, CreateInitializerObjectFn createFn, DeleteInitializerObjectFn deleteFn)\r\n{\r\n\tm_pVar = pVar;\r\n\tm_CreateFn = createFn;\r\n\tm_DeleteFn = deleteFn;\r\n\tm_pNext = s_pInitializers;\r\n\ts_pInitializers = this;\r\n}\r\n\r\n\r\nbool Initializer::InitializeAllObjects()\r\n{\r\n\tfor(Initializer *pCur=s_pInitializers; pCur; pCur=pCur->m_pNext)\r\n\t{\r\n\t\tif(void *ptr = pCur->m_CreateFn())\r\n\t\t{\r\n\t\t\t*pCur->m_pVar = ptr;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t\/\/ Don't worry if we're not actually trying to initialize a global\r\n\t\t\tif (pCur->m_pVar)\r\n\t\t\t{\r\n\t\t\t\tFreeAllObjects();\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\n\r\nvoid Initializer::FreeAllObjects()\r\n{\r\n\tfor(Initializer *pCur=s_pInitializers; pCur; pCur=pCur->m_pNext)\r\n\t{\r\n\t\tif (pCur->m_pVar)\r\n\t\t{\r\n\t\t\tpCur->m_DeleteFn(*pCur->m_pVar);\r\n\t\t\t*pCur->m_pVar = 0;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n\r\n","avg_line_length":18.803030303,"max_line_length":110,"alphanum_fraction":0.5866236906,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":569,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <iostream>\n#include <cmath>\n\nusing namespace std;\n\nint main()\n{\n    int a,i,j,unit,power,cycle[4];\n    cin>>a;\n    a=a%10;\n    cycle[0]=0; i=0; j=1;\n    do\n    {\n        \/\/unit=((a^j)%10)\n        power=(int)pow((double)a,j);\/\/ The function pow's default return type is 'double', so we need to typecast it to 'int', in addition to typecasting the base as well.\n        unit=power%10;\n        if(cycle[0]==unit)\n            break;\n        cycle[i]=unit;\n        i++;\n        j++;\n    }while(1);\n    for(j=0;j<i;j++)\n        cout<<cycle[j]<<endl;\n    return 0;\n}\n","avg_line_length":21.0740740741,"max_line_length":171,"alphanum_fraction":0.5202108963,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3480,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"..\/..\/includes\/user_interface\/login_mode.h\"\n\n#include \"ui_LoginMode.h\"\n\n#include \"..\/..\/includes\/user_interface\/login_new.h\"\n#include \"..\/..\/includes\/user_interface\/login_join.h\"\n#include \"..\/..\/includes\/user_interface\/login.h\"\n\n#include <connector\/connector.h>\n#include <connector\/socket_exception.h>\n\n#include <QWidget>\n#include <QMessageBox>\n\n#include <sstream>\n\nLoginMode::LoginMode( \n    LoginNew & loginNew, \n    LoginJoin & loginJoin, \n    QWidget *parent)\n:   QWidget(parent),\n    loginNew(loginNew),\n    loginJoin(loginJoin),\n    connector(),\n    isOpen(true)\n{\n    Ui::LoginMode loginMode;\n    loginMode.setupUi(this);\n    this->hide();\n    this->connect_events();\n}\n\nLoginMode::~LoginMode() = default;\n\n\/*\nPRE: Recibe un connector (Connector &).\nPOST: Toma posesion del connector por movimiento. \n*\/\nvoid LoginMode::set_connector(Connector & connector){\n    this->connector = std::move(connector);\n}\n\nvoid LoginMode::config_new_game() {\n    this->connector << (uint8_t) new_game;\n    \/\/ Recibe ids de mapas a elegir\n    std::vector<uint8_t> mapIds;\n    uint8_t mapsNumber;\n    connector >> mapsNumber;\n    for (uint8_t i = 0; i < mapsNumber; ++i) {\n        uint8_t mapId;\n        connector >> mapId;\n        mapIds.push_back(mapId);\n    }\n    this->loginNew.set_connector(this->connector);\n    this->loginNew.set_map_ids(mapIds);\n    this->loginNew.show();\n    this->loginJoin.close();\n    this->close();\n    ((Login*)this->parentWidget())->adjustSize();\n    return;\n}\n\nvoid LoginMode::config_join_game() {\n    this->connector << (uint8_t) join_game;\n    uint8_t gameCount;\n    this->connector >> gameCount;\n    if (gameCount == 0){\n        QMessageBox qMsg;\n        qMsg.setWindowTitle(\"PORTAL\");\n        std::stringstream err;\n        err << \"No games in stock.\\n\"; \n        qMsg.setText(QString(err.str().c_str()));\n        qMsg.setIcon(QMessageBox::Warning);\n        qMsg.exec();\n        ((Login*)this->parentWidget())->close();\n        this->close();\n        return;\n    }\n    std::map<uint8_t,std::string> stockGames;\n    for (uint8_t i = 0; i < gameCount; ++i) {\n        uint8_t gameId;\n        this->connector >> gameId;\n        std::string gameName;\n        this->connector >> gameName;\n        std::pair<uint8_t,std::string> oneGame(gameId, gameName);\n        stockGames.insert(oneGame);\n    }\n    this->loginJoin.set_connector(this->connector);\n    this->loginJoin.set_game_ids(stockGames);\n    this->loginJoin.show();\n    this->loginNew.close();\n    this->close();\n    ((Login*)this->parentWidget())->adjustSize();\n    return;\n}\n\nvoid LoginMode::connect_events() {\n    QPushButton* buttonNew = findChild<QPushButton*>(\"buttonNew\");\n    QObject::connect(buttonNew, &QPushButton::clicked,\n                     this, &LoginMode::config_new_game);\n\n    QPushButton* buttonJoin = findChild<QPushButton*>(\"buttonJoin\");\n    QObject::connect(buttonJoin, &QPushButton::clicked,\n                     this, &LoginMode::config_join_game);\n    \n    QPushButton* buttonQuit = findChild<QPushButton*>(\"buttonQuit\");\n    QObject::connect(buttonQuit, &QPushButton::clicked,\n                     this, &LoginMode::quit);\n}\n\nvoid LoginMode::closeEvent(QCloseEvent *event){\n    if (! this->isOpen){\n        return;\n    }\n    try {\n        this->connector.shutDownRD();\n        this->connector.shutDownWR();\n    } catch (SocketException &error){}\n        event->accept();    \n}\n\nvoid LoginMode::quit(){\n    ((Login*)this->parentWidget())->quit();\n    this->close();\n}","avg_line_length":27.84,"max_line_length":68,"alphanum_fraction":0.6333333333,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":36208,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Copyright 2017 MapD Technologies, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"DynamicWatchdog.h\"\n#include \"Execute.h\"\n#include \"QueryFragmentDescriptor.h\"\n\n#include \"DataMgr\/BufferMgr\/BufferMgr.h\"\n\n#include <numeric>\n\nstd::mutex Executor::ExecutionDispatch::reduce_mutex_;\n\nnamespace {\n\nbool needs_skip_result(const ResultSetPtr& res) {\n  return !res || res->definitelyHasNoRows();\n}\n\n}  \/\/ namespace\n\nuint32_t Executor::ExecutionDispatch::getFragmentStride(\n    const FragmentsList& frag_ids) const {\n  if (!ra_exe_unit_.join_quals.empty()) {\n    CHECK_EQ(ra_exe_unit_.input_descs.size(), frag_ids.size());\n    const auto table_count = ra_exe_unit_.input_descs.size();\n    uint32_t stride = 1;\n    for (size_t i = 1; i < table_count; ++i) {\n      if (executor_->plan_state_->join_info_.sharded_range_table_indices_.count(i)) {\n        stride *= frag_ids[i].fragment_ids.size();\n      }\n    }\n    return stride;\n  }\n  const bool is_hash_join = executor_->plan_state_->join_info_.join_impl_type_ ==\n                                Executor::JoinImplType::HashOneToOne ||\n                            executor_->plan_state_->join_info_.join_impl_type_ ==\n                                Executor::JoinImplType::HashOneToMany;\n  if (is_hash_join && ra_exe_unit_.input_descs.size() == 2) {\n    CHECK_EQ(frag_ids.size(), size_t(2));\n    CHECK_EQ(ra_exe_unit_.input_descs.back().getTableId(), frag_ids[1].table_id);\n    return static_cast<uint32_t>(frag_ids[1].fragment_ids.size());\n  }\n  return 1u;\n}\n\nstd::vector<const ColumnarResults*> Executor::ExecutionDispatch::getAllScanColumnFrags(\n    const int table_id,\n    const int col_id,\n    const std::map<int, const TableFragments*>& all_tables_fragments) const {\n  const auto fragments_it = all_tables_fragments.find(table_id);\n  CHECK(fragments_it != all_tables_fragments.end());\n  const auto fragments = fragments_it->second;\n  const auto frag_count = fragments->size();\n  std::vector<const ColumnarResults*> results(frag_count, nullptr);\n  const InputColDescriptor desc(col_id, table_id, int(0));\n  CHECK(desc.getScanDesc().getSourceType() == InputSourceType::TABLE);\n  auto frags_it = columnarized_ref_table_cache_.find(desc);\n  if (frags_it == columnarized_ref_table_cache_.end()) {\n    columnarized_ref_table_cache_.insert(std::make_pair(\n        desc, std::unordered_map<CacheKey, std::unique_ptr<const ColumnarResults>>()));\n    frags_it = columnarized_ref_table_cache_.find(desc);\n    for (int frag_id = 0; frag_id < static_cast<int>(frag_count); ++frag_id) {\n      std::list<std::shared_ptr<Chunk_NS::Chunk>> chunk_holder;\n      std::list<ChunkIter> chunk_iter_holder;\n      const auto& fragment = (*fragments)[frag_id];\n      auto chunk_meta_it = fragment.getChunkMetadataMap().find(col_id);\n      CHECK(chunk_meta_it != fragment.getChunkMetadataMap().end());\n      auto col_buffer = getScanColumn(table_id,\n                                      frag_id,\n                                      col_id,\n                                      all_tables_fragments,\n                                      chunk_holder,\n                                      chunk_iter_holder,\n                                      Data_Namespace::CPU_LEVEL,\n                                      int(0));\n      frags_it->second.insert(std::make_pair(\n          CacheKey{frag_id},\n          boost::make_unique<ColumnarResults>(row_set_mem_owner_,\n                                              col_buffer,\n                                              fragment.getNumTuples(),\n                                              chunk_meta_it->second.sqlType)));\n    }\n  }\n  CHECK(frags_it != columnarized_ref_table_cache_.end());\n  CHECK_EQ(frag_count, frags_it->second.size());\n  for (int frag_id = 0; frag_id < static_cast<int>(frag_count); ++frag_id) {\n    results[frag_id] = frags_it->second[{frag_id}].get();\n  }\n  return results;\n}\n\nconst int8_t* Executor::ExecutionDispatch::getColumn(\n    const ResultSetPtr& buffer,\n    const int table_id,\n    const int frag_id,\n    const int col_id,\n    const Data_Namespace::MemoryLevel memory_level,\n    const int device_id) const {\n  const ColumnarResults* result{nullptr};\n  {\n    std::lock_guard<std::mutex> columnar_conversion_guard(columnar_conversion_mutex_);\n    if (columnarized_table_cache_.empty() || !columnarized_table_cache_.count(table_id)) {\n      columnarized_table_cache_.insert(std::make_pair(\n          table_id, std::unordered_map<int, std::shared_ptr<const ColumnarResults>>()));\n    }\n    auto& frag_id_to_result = columnarized_table_cache_[table_id];\n    if (frag_id_to_result.empty() || !frag_id_to_result.count(frag_id)) {\n      frag_id_to_result.insert(\n          std::make_pair(frag_id,\n                         std::shared_ptr<const ColumnarResults>(\n                             columnarize_result(row_set_mem_owner_, buffer, frag_id))));\n    }\n    CHECK_NE(size_t(0), columnarized_table_cache_.count(table_id));\n    result = columnarized_table_cache_[table_id][frag_id].get();\n  }\n  CHECK_GE(col_id, 0);\n  return getColumn(result, col_id, &cat_.get_dataMgr(), memory_level, device_id);\n}\n\nnamespace {\n\n\/\/ The result set of `ra_exe_unit` needs to hold a reference to `chunk` if its\n\/\/ column is part of the target expressions, result set iteration needs it alive.\nbool need_to_hold_chunk(const Chunk_NS::Chunk* chunk,\n                        const RelAlgExecutionUnit& ra_exe_unit) {\n  CHECK(chunk->get_column_desc());\n  const auto chunk_ti = chunk->get_column_desc()->columnType;\n  if (chunk_ti.is_array() ||\n      (chunk_ti.is_string() && chunk_ti.get_compression() == kENCODING_NONE)) {\n    for (const auto target_expr : ra_exe_unit.target_exprs) {\n      const auto col_var = dynamic_cast<const Analyzer::ColumnVar*>(target_expr);\n      if (col_var && col_var->get_column_id() == chunk->get_column_desc()->columnId &&\n          col_var->get_table_id() == chunk->get_column_desc()->tableId) {\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\n}  \/\/ namespace\n\nvoid Executor::ExecutionDispatch::runImpl(const ExecutorDeviceType chosen_device_type,\n                                          int chosen_device_id,\n                                          const ExecutionOptions& options,\n                                          const FragmentsList& frag_list,\n                                          const size_t ctx_idx,\n                                          const int64_t rowid_lookup_key) {\n  const auto memory_level = chosen_device_type == ExecutorDeviceType::GPU\n                                ? Data_Namespace::GPU_LEVEL\n                                : Data_Namespace::CPU_LEVEL;\n  const int outer_table_id = ra_exe_unit_.input_descs[0].getTableId();\n  CHECK_GE(frag_list.size(), size_t(1));\n  CHECK_EQ(frag_list[0].table_id, outer_table_id);\n  const auto& outer_tab_frag_ids = frag_list[0].fragment_ids;\n  CHECK_GE(chosen_device_id, 0);\n  CHECK_LT(chosen_device_id, max_gpu_count);\n  \/\/ need to own them while query executes\n  auto chunk_iterators_ptr = std::make_shared<std::list<ChunkIter>>();\n  std::list<std::shared_ptr<Chunk_NS::Chunk>> chunks;\n  std::unique_ptr<std::lock_guard<std::mutex>> gpu_lock;\n  if (chosen_device_type == ExecutorDeviceType::GPU) {\n    gpu_lock.reset(\n        new std::lock_guard<std::mutex>(executor_->gpu_exec_mutex_[chosen_device_id]));\n  }\n  FetchResult fetch_result;\n  try {\n    std::map<int, const TableFragments*> all_tables_fragments;\n    QueryFragmentDescriptor::computeAllTablesFragments(\n        all_tables_fragments, ra_exe_unit_, query_infos_);\n\n    OOM_TRACE_PUSH();\n    fetch_result = executor_->fetchChunks(*this,\n                                          ra_exe_unit_,\n                                          chosen_device_id,\n                                          memory_level,\n                                          all_tables_fragments,\n                                          frag_list,\n                                          cat_,\n                                          *chunk_iterators_ptr,\n                                          chunks);\n    if (fetch_result.num_rows.empty()) {\n      return;\n    }\n    if (options.with_dynamic_watchdog &&\n        !dynamic_watchdog_set_.test_and_set(std::memory_order_acquire)) {\n      CHECK_GT(options.dynamic_watchdog_time_limit, 0);\n      auto cycle_budget = dynamic_watchdog_init(options.dynamic_watchdog_time_limit);\n      LOG(INFO) << \"Dynamic Watchdog budget: CPU: \"\n                << std::to_string(options.dynamic_watchdog_time_limit) << \"ms, \"\n                << std::to_string(cycle_budget) << \" cycles\";\n    }\n  } catch (const OutOfMemory&) {\n    std::lock_guard<std::mutex> lock(reduce_mutex_);\n    *error_code_ = ERR_OUT_OF_GPU_MEM;\n    return;\n  }\n  const CompilationResult& compilation_result =\n      chosen_device_type == ExecutorDeviceType::GPU ? compilation_result_gpu_\n                                                    : compilation_result_cpu_;\n  CHECK(!compilation_result.query_mem_desc.usesCachedContext() ||\n        !ra_exe_unit_.scan_limit);\n  std::unique_ptr<QueryExecutionContext> query_exe_context_owned;\n  const bool do_render = render_info_ && render_info_->isPotentialInSituRender();\n  try {\n    OOM_TRACE_PUSH();\n    query_exe_context_owned =\n        compilation_result.query_mem_desc.usesCachedContext()\n            ? nullptr\n            : compilation_result.query_mem_desc.getQueryExecutionContext(\n                  ra_exe_unit_,\n                  executor_->plan_state_->init_agg_vals_,\n                  executor_,\n                  chosen_device_type,\n                  chosen_device_id,\n                  fetch_result.col_buffers,\n                  fetch_result.iter_buffers,\n                  fetch_result.frag_offsets,\n                  row_set_mem_owner_,\n                  compilation_result.output_columnar,\n                  compilation_result.query_mem_desc.sortOnGpu(),\n                  do_render ? render_info_ : nullptr);\n  } catch (const OutOfHostMemory& e) {\n    std::lock_guard<std::mutex> lock(reduce_mutex_);\n    LOG(ERROR) << e.what();\n    *error_code_ = ERR_OUT_OF_CPU_MEM;\n    return;\n  }\n  QueryExecutionContext* query_exe_context{query_exe_context_owned.get()};\n  std::unique_ptr<std::lock_guard<std::mutex>> query_ctx_lock;\n  if (compilation_result.query_mem_desc.usesCachedContext()) {\n    query_ctx_lock.reset(\n        new std::lock_guard<std::mutex>(query_context_mutexes_[ctx_idx]));\n    if (!query_contexts_[ctx_idx]) {\n      try {\n        OOM_TRACE_PUSH();\n        query_contexts_[ctx_idx] =\n            compilation_result.query_mem_desc.getQueryExecutionContext(\n                ra_exe_unit_,\n                executor_->plan_state_->init_agg_vals_,\n                executor_,\n                chosen_device_type,\n                chosen_device_id,\n                fetch_result.col_buffers,\n                fetch_result.iter_buffers,\n                fetch_result.frag_offsets,\n                row_set_mem_owner_,\n                compilation_result.output_columnar,\n                compilation_result.query_mem_desc.sortOnGpu(),\n                do_render ? render_info_ : nullptr);\n      } catch (const OutOfHostMemory& e) {\n        std::lock_guard<std::mutex> lock(reduce_mutex_);\n        LOG(ERROR) << e.what();\n        *error_code_ = ERR_OUT_OF_CPU_MEM;\n        return;\n      }\n    }\n    query_exe_context = query_contexts_[ctx_idx].get();\n  }\n  CHECK(query_exe_context);\n  int32_t err{0};\n  uint32_t start_rowid{0};\n  if (rowid_lookup_key >= 0) {\n    if (!frag_list.empty()) {\n      const auto& all_frag_row_offsets = getFragOffsets();\n      start_rowid = rowid_lookup_key -\n                    all_frag_row_offsets[frag_list.begin()->fragment_ids.front()];\n    }\n  }\n\n  ResultSetPtr device_results;\n  if (ra_exe_unit_.groupby_exprs.empty()) {\n    OOM_TRACE_PUSH();\n    err = executor_->executePlanWithoutGroupBy(ra_exe_unit_,\n                                               compilation_result,\n                                               co_.hoist_literals_,\n                                               device_results,\n                                               ra_exe_unit_.target_exprs,\n                                               chosen_device_type,\n                                               fetch_result.col_buffers,\n                                               query_exe_context,\n                                               fetch_result.num_rows,\n                                               fetch_result.frag_offsets,\n                                               getFragmentStride(frag_list),\n                                               &cat_.get_dataMgr(),\n                                               chosen_device_id,\n                                               start_rowid,\n                                               ra_exe_unit_.input_descs.size(),\n                                               do_render ? render_info_ : nullptr);\n  } else {\n    OOM_TRACE_PUSH();\n    err = executor_->executePlanWithGroupBy(ra_exe_unit_,\n                                            compilation_result,\n                                            co_.hoist_literals_,\n                                            device_results,\n                                            chosen_device_type,\n                                            fetch_result.col_buffers,\n                                            outer_tab_frag_ids,\n                                            query_exe_context,\n                                            fetch_result.num_rows,\n                                            fetch_result.frag_offsets,\n                                            getFragmentStride(frag_list),\n                                            &cat_.get_dataMgr(),\n                                            chosen_device_id,\n                                            ra_exe_unit_.scan_limit,\n                                            start_rowid,\n                                            ra_exe_unit_.input_descs.size(),\n                                            do_render ? render_info_ : nullptr);\n  }\n  if (device_results) {\n    std::list<std::shared_ptr<Chunk_NS::Chunk>> chunks_to_hold;\n    for (const auto chunk : chunks) {\n      if (need_to_hold_chunk(chunk.get(), ra_exe_unit_)) {\n        chunks_to_hold.push_back(chunk);\n      }\n    }\n    device_results->holdChunks(chunks_to_hold);\n    device_results->holdChunkIterators(chunk_iterators_ptr);\n  }\n  {\n    std::lock_guard<std::mutex> lock(reduce_mutex_);\n    if (err) {\n      *error_code_ = err;\n    }\n    if (!needs_skip_result(device_results)) {\n      all_fragment_results_.emplace_back(std::move(device_results), outer_tab_frag_ids);\n    }\n  }\n}\n\nExecutor::ExecutionDispatch::ExecutionDispatch(\n    Executor* executor,\n    const RelAlgExecutionUnit& ra_exe_unit,\n    const std::vector<InputTableInfo>& query_infos,\n    const Catalog_Namespace::Catalog& cat,\n    const CompilationOptions& co,\n    const size_t context_count,\n    const std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,\n    const ColumnCacheMap& column_cache,\n    int32_t* error_code,\n    RenderInfo* render_info)\n    : executor_(executor)\n    , ra_exe_unit_(ra_exe_unit)\n    , query_infos_(query_infos)\n    , cat_(cat)\n    , co_(co)\n    , query_contexts_(context_count)\n    , query_context_mutexes_(context_count)\n    , row_set_mem_owner_(row_set_mem_owner)\n    , error_code_(error_code)\n    , render_info_(render_info)\n    , columnarized_table_cache_(column_cache) {\n  all_fragment_results_.reserve(query_infos_.front().info.fragments.size());\n}\n\nint8_t Executor::ExecutionDispatch::compile(const Executor::JoinInfo& join_info,\n                                            const size_t max_groups_buffer_entry_guess,\n                                            const int8_t crt_min_byte_width,\n                                            const ExecutionOptions& options,\n                                            const bool has_cardinality_estimation) {\n  int8_t actual_min_byte_width{MAX_BYTE_WIDTH_SUPPORTED};\n  auto compile_on_cpu = [&]() {\n    const CompilationOptions co_cpu{ExecutorDeviceType::CPU,\n                                    co_.hoist_literals_,\n                                    co_.opt_level_,\n                                    co_.with_dynamic_watchdog_};\n\n    try {\n      OOM_TRACE_PUSH();\n      compilation_result_cpu_ = executor_->compileWorkUnit(\n          query_infos_,\n          ra_exe_unit_,\n          co_cpu,\n          options,\n          cat_.get_dataMgr().cudaMgr_,\n          render_info_ && render_info_->isPotentialInSituRender() ? false : true,\n          row_set_mem_owner_,\n          max_groups_buffer_entry_guess,\n          executor_->small_groups_buffer_entry_count_,\n          crt_min_byte_width,\n          join_info,\n          has_cardinality_estimation,\n          columnarized_table_cache_,\n          render_info_);\n    } catch (const CompilationRetryNoLazyFetch&) {\n      OOM_TRACE_PUSH();\n      if (executor_->cgen_state_->module_) {\n        delete executor_->cgen_state_->module_;\n      }\n      compilation_result_cpu_ =\n          executor_->compileWorkUnit(query_infos_,\n                                     ra_exe_unit_,\n                                     co_cpu,\n                                     options,\n                                     cat_.get_dataMgr().cudaMgr_,\n                                     false,\n                                     row_set_mem_owner_,\n                                     max_groups_buffer_entry_guess,\n                                     executor_->small_groups_buffer_entry_count_,\n                                     crt_min_byte_width,\n                                     join_info,\n                                     has_cardinality_estimation,\n                                     columnarized_table_cache_,\n                                     render_info_);\n    }\n    actual_min_byte_width =\n        compilation_result_cpu_.query_mem_desc.updateActualMinByteWidth(\n            actual_min_byte_width);\n  };\n\n  if (co_.device_type_ == ExecutorDeviceType::CPU) {\n    compile_on_cpu();\n  }\n\n  if (co_.device_type_ == ExecutorDeviceType::GPU) {\n    const CompilationOptions co_gpu{ExecutorDeviceType::GPU,\n                                    co_.hoist_literals_,\n                                    co_.opt_level_,\n                                    co_.with_dynamic_watchdog_};\n    try {\n      OOM_TRACE_PUSH();\n      compilation_result_gpu_ = executor_->compileWorkUnit(\n          query_infos_,\n          ra_exe_unit_,\n          co_gpu,\n          options,\n          cat_.get_dataMgr().cudaMgr_,\n          render_info_ && render_info_->isPotentialInSituRender() ? false : true,\n          row_set_mem_owner_,\n          max_groups_buffer_entry_guess,\n          executor_->small_groups_buffer_entry_count_,\n          crt_min_byte_width,\n          join_info,\n          has_cardinality_estimation,\n          columnarized_table_cache_,\n          render_info_);\n    } catch (const CompilationRetryNoLazyFetch&) {\n      OOM_TRACE_PUSH();\n      if (executor_->cgen_state_->module_) {\n        delete executor_->cgen_state_->module_;\n      }\n      compilation_result_gpu_ =\n          executor_->compileWorkUnit(query_infos_,\n                                     ra_exe_unit_,\n                                     co_gpu,\n                                     options,\n                                     cat_.get_dataMgr().cudaMgr_,\n                                     false,\n                                     row_set_mem_owner_,\n                                     max_groups_buffer_entry_guess,\n                                     executor_->small_groups_buffer_entry_count_,\n                                     crt_min_byte_width,\n                                     join_info,\n                                     has_cardinality_estimation,\n                                     columnarized_table_cache_,\n                                     render_info_);\n    }\n    actual_min_byte_width =\n        compilation_result_gpu_.query_mem_desc.updateActualMinByteWidth(\n            actual_min_byte_width);\n  }\n\n  return std::max(actual_min_byte_width, crt_min_byte_width);\n}\n\nvoid Executor::ExecutionDispatch::run(const ExecutorDeviceType chosen_device_type,\n                                      int chosen_device_id,\n                                      const ExecutionOptions& options,\n                                      const FragmentsList& frag_list,\n                                      const size_t ctx_idx,\n                                      const int64_t rowid_lookup_key) noexcept {\n  try {\n    runImpl(chosen_device_type,\n            chosen_device_id,\n            options,\n            frag_list,\n            ctx_idx,\n            rowid_lookup_key);\n  } catch (const std::bad_alloc& e) {\n    std::lock_guard<std::mutex> lock(reduce_mutex_);\n    LOG(ERROR) << e.what();\n    *error_code_ = ERR_OUT_OF_CPU_MEM;\n  } catch (const OutOfHostMemory& e) {\n    std::lock_guard<std::mutex> lock(reduce_mutex_);\n    LOG(ERROR) << e.what();\n    *error_code_ = ERR_OUT_OF_CPU_MEM;\n  } catch (const OutOfRenderMemory& e) {\n    std::lock_guard<std::mutex> lock(reduce_mutex_);\n    LOG(ERROR) << e.what();\n    *error_code_ = ERR_OUT_OF_RENDER_MEM;\n  } catch (const OutOfMemory& e) {\n    std::lock_guard<std::mutex> lock(reduce_mutex_);\n    LOG(ERROR) << e.what();\n    *error_code_ = ERR_OUT_OF_GPU_MEM;\n  } catch (const ColumnarConversionNotSupported& e) {\n    std::lock_guard<std::mutex> lock(reduce_mutex_);\n    *error_code_ = ERR_COLUMNAR_CONVERSION_NOT_SUPPORTED;\n  } catch (const TooManyLiterals&) {\n    std::lock_guard<std::mutex> lock(reduce_mutex_);\n    *error_code_ = ERR_TOO_MANY_LITERALS;\n  } catch (const SringConstInResultSet& e) {\n    std::lock_guard<std::mutex> lock(reduce_mutex_);\n    *error_code_ = ERR_STRING_CONST_IN_RESULTSET;\n    LOG(INFO) << e.what();\n  }\n}\n\nconst int8_t* Executor::ExecutionDispatch::getScanColumn(\n    const int table_id,\n    const int frag_id,\n    const int col_id,\n    const std::map<int, const TableFragments*>& all_tables_fragments,\n    std::list<std::shared_ptr<Chunk_NS::Chunk>>& chunk_holder,\n    std::list<ChunkIter>& chunk_iter_holder,\n    const Data_Namespace::MemoryLevel memory_level,\n    const int device_id) const {\n  static std::mutex varlen_chunk_mutex;  \/\/ TODO(alex): remove\n  static std::mutex chunk_list_mutex;\n  const auto fragments_it = all_tables_fragments.find(table_id);\n  CHECK(fragments_it != all_tables_fragments.end());\n  const auto fragments = fragments_it->second;\n  const auto& fragment = (*fragments)[frag_id];\n  if (fragment.isEmptyPhysicalFragment()) {\n    return nullptr;\n  }\n  std::shared_ptr<Chunk_NS::Chunk> chunk;\n  auto chunk_meta_it = fragment.getChunkMetadataMap().find(col_id);\n  CHECK(chunk_meta_it != fragment.getChunkMetadataMap().end());\n  CHECK(table_id > 0);\n  auto cd = get_column_descriptor(col_id, table_id, cat_);\n  CHECK(cd);\n  const auto col_type =\n      get_column_type(col_id, table_id, cd, executor_->temporary_tables_);\n  const bool is_real_string =\n      col_type.is_string() && col_type.get_compression() == kENCODING_NONE;\n  const bool is_varlen =\n      is_real_string ||\n      col_type.is_array();  \/\/ TODO: should it be col_type.is_varlen_array() ?\n  {\n    ChunkKey chunk_key{\n        cat_.get_currentDB().dbId, fragment.physicalTableId, col_id, fragment.fragmentId};\n    std::unique_ptr<std::lock_guard<std::mutex>> varlen_chunk_lock;\n    if (is_varlen) {\n      varlen_chunk_lock.reset(new std::lock_guard<std::mutex>(varlen_chunk_mutex));\n    }\n    OOM_TRACE_PUSH(+\": chunk key [\" + showChunk(chunk_key) + \"]\");\n    chunk = Chunk_NS::Chunk::getChunk(\n        cd,\n        &cat_.get_dataMgr(),\n        chunk_key,\n        memory_level,\n        memory_level == Data_Namespace::CPU_LEVEL ? 0 : device_id,\n        chunk_meta_it->second.numBytes,\n        chunk_meta_it->second.numElements);\n    std::lock_guard<std::mutex> chunk_list_lock(chunk_list_mutex);\n    chunk_holder.push_back(chunk);\n  }\n  if (is_varlen) {\n    CHECK_GT(table_id, 0);\n    CHECK(chunk_meta_it != fragment.getChunkMetadataMap().end());\n    chunk_iter_holder.push_back(chunk->begin_iterator(chunk_meta_it->second));\n    auto& chunk_iter = chunk_iter_holder.back();\n    if (memory_level == Data_Namespace::CPU_LEVEL) {\n      return reinterpret_cast<int8_t*>(&chunk_iter);\n    } else {\n      CHECK_EQ(Data_Namespace::GPU_LEVEL, memory_level);\n      auto& data_mgr = cat_.get_dataMgr();\n      auto chunk_iter_gpu =\n          alloc_gpu_mem(&data_mgr, sizeof(ChunkIter), device_id, nullptr);\n      copy_to_gpu(&data_mgr, chunk_iter_gpu, &chunk_iter, sizeof(ChunkIter), device_id);\n      return reinterpret_cast<int8_t*>(chunk_iter_gpu);\n    }\n  } else {\n    auto ab = chunk->get_buffer();\n    CHECK(ab->getMemoryPtr());\n    return ab->getMemoryPtr();  \/\/ @TODO(alex) change to use ChunkIter\n  }\n}\n\nconst int8_t* Executor::ExecutionDispatch::getAllScanColumnFrags(\n    const int table_id,\n    const int col_id,\n    const std::map<int, const TableFragments*>& all_tables_fragments,\n    const Data_Namespace::MemoryLevel memory_level,\n    const int device_id) const {\n  const auto fragments_it = all_tables_fragments.find(table_id);\n  CHECK(fragments_it != all_tables_fragments.end());\n  const auto fragments = fragments_it->second;\n  const auto frag_count = fragments->size();\n  std::vector<std::unique_ptr<ColumnarResults>> column_frags;\n  const ColumnarResults* table_column = nullptr;\n  const InputColDescriptor col_desc(col_id, table_id, int(0));\n  CHECK(col_desc.getScanDesc().getSourceType() == InputSourceType::TABLE);\n  {\n    std::lock_guard<std::mutex> columnar_conversion_guard(columnar_conversion_mutex_);\n    auto column_it = columnarized_scan_table_cache_.find(col_desc);\n    if (column_it == columnarized_scan_table_cache_.end()) {\n      for (size_t frag_id = 0; frag_id < frag_count; ++frag_id) {\n        std::list<std::shared_ptr<Chunk_NS::Chunk>> chunk_holder;\n        std::list<ChunkIter> chunk_iter_holder;\n        const auto& fragment = (*fragments)[frag_id];\n        if (fragment.isEmptyPhysicalFragment()) {\n          continue;\n        }\n        auto chunk_meta_it = fragment.getChunkMetadataMap().find(col_id);\n        CHECK(chunk_meta_it != fragment.getChunkMetadataMap().end());\n        auto col_buffer = getScanColumn(table_id,\n                                        static_cast<int>(frag_id),\n                                        col_id,\n                                        all_tables_fragments,\n                                        chunk_holder,\n                                        chunk_iter_holder,\n                                        Data_Namespace::CPU_LEVEL,\n                                        int(0));\n        column_frags.push_back(\n            boost::make_unique<ColumnarResults>(row_set_mem_owner_,\n                                                col_buffer,\n                                                fragment.getNumTuples(),\n                                                chunk_meta_it->second.sqlType));\n      }\n      auto merged_results =\n          ColumnarResults::mergeResults(row_set_mem_owner_, column_frags);\n      table_column = merged_results.get();\n      columnarized_scan_table_cache_.emplace(col_desc, std::move(merged_results));\n    } else {\n      table_column = column_it->second.get();\n    }\n  }\n  return getColumn(table_column, 0, &cat_.get_dataMgr(), memory_level, device_id);\n}\n\nconst int8_t* Executor::ExecutionDispatch::getColumn(\n    const InputColDescriptor* col_desc,\n    const int frag_id,\n    const std::map<int, const TableFragments*>& all_tables_fragments,\n    const Data_Namespace::MemoryLevel memory_level,\n    const int device_id,\n    const bool is_rowid) const {\n  CHECK(col_desc);\n  const auto table_id = col_desc->getScanDesc().getTableId();\n  return getColumn(get_temporary_table(executor_->temporary_tables_, table_id),\n                   table_id,\n                   frag_id,\n                   col_desc->getColId(),\n                   memory_level,\n                   device_id);\n}\n\nconst int8_t* Executor::ExecutionDispatch::getColumn(\n    const ColumnarResults* columnar_results,\n    const int col_id,\n    Data_Namespace::DataMgr* data_mgr,\n    const Data_Namespace::MemoryLevel memory_level,\n    const int device_id) {\n  const auto& col_buffers = columnar_results->getColumnBuffers();\n  CHECK_LT(static_cast<size_t>(col_id), col_buffers.size());\n  if (memory_level == Data_Namespace::GPU_LEVEL) {\n    const auto& col_ti = columnar_results->getColumnType(col_id);\n    const auto num_bytes = columnar_results->size() * col_ti.get_size();\n    OOM_TRACE_PUSH(+\": device_id \" + std::to_string(device_id) + \", num_bytes \" +\n                   std::to_string(num_bytes) + \", col_id \" + std::to_string(col_id));\n    auto gpu_col_buffer = alloc_gpu_mem(data_mgr, num_bytes, device_id, nullptr);\n    copy_to_gpu(data_mgr, gpu_col_buffer, col_buffers[col_id], num_bytes, device_id);\n    return reinterpret_cast<const int8_t*>(gpu_col_buffer);\n  }\n  return col_buffers[col_id];\n}\n\nstd::string Executor::ExecutionDispatch::getIR(\n    const ExecutorDeviceType device_type) const {\n  CHECK(device_type == ExecutorDeviceType::CPU || device_type == ExecutorDeviceType::GPU);\n  if (device_type == ExecutorDeviceType::CPU) {\n    return compilation_result_cpu_.llvm_ir;\n  }\n  return compilation_result_gpu_.llvm_ir;\n}\n\nExecutorDeviceType Executor::ExecutionDispatch::getDeviceType() const {\n  return co_.device_type_;\n}\n\nconst RelAlgExecutionUnit& Executor::ExecutionDispatch::getExecutionUnit() const {\n  return ra_exe_unit_;\n}\n\nconst QueryMemoryDescriptor& Executor::ExecutionDispatch::getQueryMemoryDescriptor()\n    const {\n  \/\/ TODO(alex): make query_mem_desc easily available\n  return compilation_result_cpu_.native_functions.empty()\n             ? compilation_result_gpu_.query_mem_desc\n             : compilation_result_cpu_.query_mem_desc;\n}\n\nconst bool Executor::ExecutionDispatch::outputColumnar() const {\n  return compilation_result_cpu_.native_functions.empty()\n             ? compilation_result_gpu_.output_columnar\n             : false;\n}\n\nconst std::vector<uint64_t>& Executor::ExecutionDispatch::getFragOffsets() const {\n  std::lock_guard<std::mutex> lock(all_frag_row_offsets_mutex_);\n  if (all_frag_row_offsets_.empty()) {\n    all_frag_row_offsets_.resize(query_infos_.front().info.fragments.size() + 1);\n    for (size_t i = 1; i <= query_infos_.front().info.fragments.size(); ++i) {\n      all_frag_row_offsets_[i] =\n          all_frag_row_offsets_[i - 1] +\n          query_infos_.front().info.fragments[i - 1].getNumTuples();\n    }\n  }\n  return all_frag_row_offsets_;\n}\n\nconst std::vector<std::unique_ptr<QueryExecutionContext>>&\nExecutor::ExecutionDispatch::getQueryContexts() const {\n  return query_contexts_;\n}\n\nstd::vector<std::pair<ResultSetPtr, std::vector<size_t>>>&\nExecutor::ExecutionDispatch::getFragmentResults() {\n  return all_fragment_results_;\n}\n\nstd::pair<const int8_t*, size_t> Executor::ExecutionDispatch::getColumnFragment(\n    Executor* executor,\n    const Analyzer::ColumnVar& hash_col,\n    const Fragmenter_Namespace::FragmentInfo& fragment,\n    const Data_Namespace::MemoryLevel effective_mem_lvl,\n    const int device_id,\n    std::vector<std::shared_ptr<Chunk_NS::Chunk>>& chunks_owner,\n    ColumnCacheMap& column_cache) {\n  static std::mutex columnar_conversion_mutex;\n  if (fragment.isEmptyPhysicalFragment()) {\n    return {nullptr, 0};\n  }\n  auto chunk_meta_it = fragment.getChunkMetadataMap().find(hash_col.get_column_id());\n  CHECK(chunk_meta_it != fragment.getChunkMetadataMap().end());\n  const auto& catalog = *executor->getCatalog();\n  const auto cd = get_column_descriptor_maybe(\n      hash_col.get_column_id(), hash_col.get_table_id(), catalog);\n  CHECK(!cd || !(cd->isVirtualCol));\n  const int8_t* col_buff = nullptr;\n  if (cd) {\n    ChunkKey chunk_key{catalog.get_currentDB().dbId,\n                       fragment.physicalTableId,\n                       hash_col.get_column_id(),\n                       fragment.fragmentId};\n    OOM_TRACE_PUSH(+\": chunk key [\" + showChunk(chunk_key) + \"]\");\n    const auto chunk = Chunk_NS::Chunk::getChunk(\n        cd,\n        &catalog.get_dataMgr(),\n        chunk_key,\n        effective_mem_lvl,\n        effective_mem_lvl == Data_Namespace::CPU_LEVEL ? 0 : device_id,\n        chunk_meta_it->second.numBytes,\n        chunk_meta_it->second.numElements);\n    chunks_owner.push_back(chunk);\n    CHECK(chunk);\n    auto ab = chunk->get_buffer();\n    CHECK(ab->getMemoryPtr());\n    col_buff = reinterpret_cast<int8_t*>(ab->getMemoryPtr());\n  } else {\n    const ColumnarResults* col_frag{nullptr};\n    {\n      std::lock_guard<std::mutex> columnar_conversion_guard(columnar_conversion_mutex);\n      const auto table_id = hash_col.get_table_id();\n      const auto frag_id = fragment.fragmentId;\n      if (column_cache.empty() || !column_cache.count(table_id)) {\n        column_cache.insert(std::make_pair(\n            table_id, std::unordered_map<int, std::shared_ptr<const ColumnarResults>>()));\n      }\n      auto& frag_id_to_result = column_cache[table_id];\n      if (frag_id_to_result.empty() || !frag_id_to_result.count(frag_id)) {\n        frag_id_to_result.insert(std::make_pair(\n            frag_id,\n            std::shared_ptr<const ColumnarResults>(columnarize_result(\n                executor->row_set_mem_owner_,\n                get_temporary_table(executor->temporary_tables_, hash_col.get_table_id()),\n                frag_id))));\n      }\n      col_frag = column_cache[table_id][frag_id].get();\n    }\n    col_buff = getColumn(col_frag,\n                         hash_col.get_column_id(),\n                         &catalog.get_dataMgr(),\n                         effective_mem_lvl,\n                         effective_mem_lvl == Data_Namespace::CPU_LEVEL ? 0 : device_id);\n  }\n  return {col_buff, fragment.getNumTuples()};\n}\n\nstd::pair<const int8_t*, size_t> Executor::ExecutionDispatch::getAllColumnFragments(\n    Executor* executor,\n    const Analyzer::ColumnVar& hash_col,\n    const std::deque<Fragmenter_Namespace::FragmentInfo>& fragments,\n    std::vector<std::shared_ptr<Chunk_NS::Chunk>>& chunks_owner,\n    ColumnCacheMap& column_cache) {\n  CHECK(!fragments.empty());\n  const size_t elem_width = hash_col.get_type_info().get_size();\n  std::vector<const int8_t*> col_frags;\n  std::vector<size_t> elem_counts;\n  for (auto& frag : fragments) {\n    const int8_t* col_frag = nullptr;\n    size_t elem_count = 0;\n    std::tie(col_frag, elem_count) = getColumnFragment(executor,\n                                                       hash_col,\n                                                       frag,\n                                                       Data_Namespace::CPU_LEVEL,\n                                                       0,\n                                                       chunks_owner,\n                                                       column_cache);\n    if (col_frag == nullptr) {\n      continue;\n    }\n    CHECK_NE(elem_count, size_t(0));\n    col_frags.push_back(col_frag);\n    elem_counts.push_back(elem_count);\n  }\n  CHECK(!col_frags.empty());\n  CHECK_EQ(col_frags.size(), elem_counts.size());\n  const auto total_elem_count =\n      std::accumulate(elem_counts.begin(), elem_counts.end(), size_t(0));\n  OOM_TRACE_PUSH(+\": col_buff \" + std::to_string(total_elem_count * elem_width));\n  auto col_buff =\n      reinterpret_cast<int8_t*>(checked_malloc(total_elem_count * elem_width));\n  for (size_t i = 0, offset = 0; i < col_frags.size(); ++i) {\n    memcpy(col_buff + offset, col_frags[i], elem_counts[i] * elem_width);\n    offset += elem_counts[i] * elem_width;\n  }\n  return {col_buff, total_elem_count};\n}\n","avg_line_length":42.849704142,"max_line_length":90,"alphanum_fraction":0.6124613345,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5604,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*++\nCopyright (c) 2016 Microsoft Corporation\n\nModule Name:\n\n    dt2bv_tactic.cpp\n\nAbstract:\n\n    Tactic that eliminates finite domain data-types.\n\nAuthor:\n\n    nbjorner 2016-07-22\n\nRevision History:\n\n    Possible extension is to handle tuple types over finite domains.\n\n--*\/\n\n#include \"dt2bv_tactic.h\"\n#include \"tactical.h\"\n#include \"filter_model_converter.h\"\n#include \"datatype_decl_plugin.h\"\n#include \"bv_decl_plugin.h\"\n#include \"rewriter_def.h\"\n#include \"filter_model_converter.h\"\n#include \"extension_model_converter.h\"\n#include \"var_subst.h\"\n#include \"ast_util.h\"\n#include \"enum2bv_rewriter.h\"\n#include \"ast_pp.h\"\n\n\nclass dt2bv_tactic : public tactic {\n\n    ast_manager&  m;\n    params_ref    m_params;\n    datatype_util m_dt;\n    bv_util       m_bv;\n    obj_hashtable<sort> m_fd_sorts;\n    obj_hashtable<sort> m_non_fd_sorts;\n    \n\n    bool is_fd(expr* a) { return is_fd(get_sort(a)); }\n    bool is_fd(sort* a) { return m_dt.is_enum_sort(a); }\n\n    struct check_fd {        \n        dt2bv_tactic& m_t;\n        ast_manager&  m;\n\n        check_fd(dt2bv_tactic& t): m_t(t), m(t.m) {}\n\n        void operator()(app* a) {\n            if (m.is_eq(a)) {\n                \/\/ no-op\n            }\n            else if (m.is_distinct(a)) {\n                \/\/ no-op\n            }\n            else if (m_t.m_dt.is_recognizer(a->get_decl()) &&\n                m_t.is_fd(a->get_arg(0))) {\n                m_t.m_fd_sorts.insert(get_sort(a->get_arg(0)));\n            }\n            else if (m_t.is_fd(a) && a->get_num_args() > 0) {\n                m_t.m_non_fd_sorts.insert(get_sort(a));\n                args_cannot_be_fd(a);\n            }\n            else if (m_t.is_fd(a)) {\n                m_t.m_fd_sorts.insert(get_sort(a));\n            }\n            else {\n                args_cannot_be_fd(a);\n            }\n        }\n\n        void args_cannot_be_fd(app* a) {\n            for (expr* arg : *a) {\n                if (m_t.is_fd(arg)) {\n                    m_t.m_non_fd_sorts.insert(get_sort(arg));\n                }                    \n            }\n        }\n\n        void operator()(var * v) {\n            if (m_t.is_fd(v)) {\n                m_t.m_fd_sorts.insert(get_sort(v));\n            }\n        }\n\n        void operator()(quantifier* q) {}\n    };\n\n    struct sort_pred : public i_sort_pred {\n        dt2bv_tactic& m_t;\n        sort_pred(dt2bv_tactic& t): m_t(t) {}\n        virtual ~sort_pred() {}\n        virtual bool operator()(sort* s) {\n            return m_t.m_fd_sorts.contains(s);\n        }\n    };\n\n    sort_pred m_is_fd;\npublic:\n\n    dt2bv_tactic(ast_manager& m, params_ref const& p): \n        m(m), m_params(p), m_dt(m), m_bv(m), m_is_fd(*this) {}\n    \n    virtual tactic * translate(ast_manager & m) {\n        return alloc(dt2bv_tactic, m, m_params);\n    }\n\n    virtual void updt_params(params_ref const & p) {\n    }\n\n    virtual void collect_param_descrs(param_descrs & r) {\n    }\n\n    virtual void operator()(goal_ref const & g,\n                            goal_ref_buffer & result,\n                            model_converter_ref & mc,\n                            proof_converter_ref & pc,\n                            expr_dependency_ref & core) {\n        mc = 0; pc = 0; core = 0;\n        bool produce_proofs = g->proofs_enabled();\n        tactic_report report(\"dt2bv\", *g);\n        unsigned   size = g->size();\n        expr_fast_mark1 visited;\n        check_fd proc(*this);\n        for (unsigned i = 0; i < size; ++i) {\n            quick_for_each_expr(proc, visited, g->form(i));\n        }\n        obj_hashtable<sort>::iterator it = m_non_fd_sorts.begin(), end = m_non_fd_sorts.end();\n        for (; it != end; ++it) {\n            m_fd_sorts.remove(*it);\n        }\n        if (!m_fd_sorts.empty()) {\n            ref<extension_model_converter> ext = alloc(extension_model_converter, m);\n            ref<filter_model_converter> filter = alloc(filter_model_converter, m);\n            enum2bv_rewriter rw(m, m_params);\n            rw.set_is_fd(&m_is_fd);            \n            expr_ref   new_curr(m);\n            proof_ref  new_pr(m);\n            for (unsigned idx = 0; idx < size; idx++) {\n                rw(g->form(idx), new_curr, new_pr);\n                if (produce_proofs) {\n                    proof * pr = g->pr(idx);\n                    new_pr = m.mk_modus_ponens(pr, new_pr);\n                }\n                g->update(idx, new_curr, new_pr, g->dep(idx));\n            }\n            expr_ref_vector bounds(m);\n            rw.flush_side_constraints(bounds);\n            for (unsigned i = 0; i < bounds.size(); ++i) {\n                g->assert_expr(bounds[i].get());\n            }\n            {\n                obj_map<func_decl, func_decl*>::iterator it = rw.enum2bv().begin(), end = rw.enum2bv().end();\n                for (; it != end; ++it) {\n                    filter->insert(it->m_value);\n                }\n            }\n            {\n                obj_map<func_decl, expr*>::iterator it = rw.enum2def().begin(), end = rw.enum2def().end();\n                for (; it != end; ++it) {\n                    ext->insert(it->m_key, it->m_value);\n                }\n            }\n            \n            mc = concat(filter.get(), ext.get());\n            report_tactic_progress(\":fd-num-translated\", rw.num_translated());\n        }\n        g->inc_depth();\n        result.push_back(g.get());\n        TRACE(\"dt2bv\", g->display(tout););\n        SASSERT(g->is_well_sorted());\n    }\n    \n    virtual void cleanup() {\n        m_fd_sorts.reset();\n        m_non_fd_sorts.reset();\n    }\n\n};\n\ntactic * mk_dt2bv_tactic(ast_manager & m, params_ref const & p) {\n    return alloc(dt2bv_tactic, m, p);\n}\n","avg_line_length":29.4947368421,"max_line_length":109,"alphanum_fraction":0.5164168451,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1266,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include <bandit_with_gmock\/bandit_with_gmock.hpp>\n#include <webmock\/core\/condition_list.hpp>\n\nnamespace webmock { namespace core {\ngo_bandit([]{\n    using namespace bandit;\n    \n    describe(\"webmock::core::condition_list\", []{\n        describe(\"#match(request)\", [&]{\n            describe(\"when this was empty\", [&]{\n                it(\"should be true\", [&]{\n                    condition_list list;\n                    AssertThat(list.match({}), Equals(true));\n                });\n            });\n            \n            describe(\"when the request matched\", [&]{\n                it(\"should be true\", [&]{\n                    condition_list list;\n                    list.add([](auto &&){ return true; });\n                    list.add([](auto &&){ return true; });\n                    AssertThat(list.match({}), Equals(true));\n                });\n            });\n            \n            describe(\"when the request not matched\", [&]{\n                it(\"should be false\", [&]{\n                    condition_list list;\n                    list.add([](auto &&){ return true; });\n                    list.add([](auto &&){ return false; });\n                    AssertThat(list.match({}), Equals(false));\n                });\n            });\n        });\n    });\n});\n}}\n","avg_line_length":33.3157894737,"max_line_length":62,"alphanum_fraction":0.4304897314,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1264,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*\n * Copyright (C) 2019 Open Source Robotics Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <iostream>\n\n#include <dds\/dds.h>\n\n#include \"Client.hpp\"\n#include \"free_fleet\/FreeFleet.h\"\n\n\nint main(int argc, char** argv)\n{\n  \/\/ Initialize all the ROS 1 items\n  ros::init(argc, argv, \"free_fleet_client\");\n  ros::NodeHandle ros_node_handle;\n  ROS_INFO(\"greetings from free_fleet_client\");\n\n  auto config = free_fleet::ClientConfig::make();\n  \n  auto client = free_fleet::Client::make(config);\n\n  \/\/ Checks if the DDS client was created and is ready to roll\n  if (!client)\n  {\n    ROS_ERROR(\"Client: unable to initialize.\");\n    return 1;\n  }\n\n  \/\/ Start running the client with the starting state\n  client->start();\n  return 0;\n}\n","avg_line_length":26.3333333333,"max_line_length":75,"alphanum_fraction":0.7120253165,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":810,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/ RUN: %clang_cc1 -fsycl -fsycl-is-device -triple spir64-unknown-unknown-sycldevice -disable-llvm-passes -emit-llvm %s -o - | FileCheck %s\n\ntemplate <typename name, typename Func>\n__attribute__((sycl_kernel)) void kernel_single_task(const Func &kernelFunc) {\n  kernelFunc();\n}\n\nenum enum_type: int {\n    A = 0,\n    B = 1,\n};\n\nvoid test(enum_type val)\n{\n  kernel_single_task<class kernel_function>([=]() {\n  \/\/expected-warning@+1{{expression result unused}}\n  val;\n  });\n}\n\nint main() {\n\n  \/\/ CHECK: define spir_kernel void @_ZTSZ4test9enum_typeE15kernel_function(i32 %_arg_)\n\n  \/\/ CHECK: getelementptr inbounds %\"class.{{.*}}.anon\", %\"class.{{.*}}.anon\"*\n  \/\/ CHECK: call spir_func void @\"_ZZ4test9enum_typeENK3$_0clEv\"(%\"class.{{.*}}.anon\" addrspace(4)* {{[^,]*}} %4)\n\n\n  test( enum_type::B );\n  return 0;\n}\n","avg_line_length":25.3125,"max_line_length":139,"alphanum_fraction":0.6703703704,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3230,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Naumen","Condor-1.1","MS-PL"],"max_stars_count":null,"content":"\/****************************************************************************\/\n\/*\tCopyright (c) 2012 Vitaly Lyaschenko < scxv86@gmail.com >\n\/*\n\/*\tPurpose:\n\/*\n\/****************************************************************************\/\n\n#include \"Logger.h\"\n\n#ifdef LOG_MULTITHREADING\n\n#include \"sys_Mutex.h\"\n\n#include <process.h>\n\nunsigned  __stdcall  thread_func1(void* pParam )\n{\n\tLOG_DEBUG<<\"\\n\\t>: Dbg msg from: thread_func_1\\n\";\n\tLOG_DEBUG_1<<\"\\n\\t>: Dbg_Level_1 msg from: thread_func_1\\n\";\n\tSleep(100);\n\tLOG_WARNING<<\"\\n\\tSome warning from thread_1\";\n\tSleep(100);\n\treturn 0;\n}\nunsigned  __stdcall  thread_func2(void* pParam )\n{\n\tLOG_DEBUG<<\"\\n\\t>: Dbg msg from: thread_func_2\\n\";\n\tLOG_DEBUG_1<<\"\\n\\t>: Dbg_Level_1 msg from: thread_func_2\\n\";\n\tSleep(100);\n\tLOG_WARNING<<\"\\n\\tSome warning from thread_2\";\n\tSleep(100);\n\treturn 0;\n}\nunsigned  __stdcall  thread_func3(void* pParam )\n{\n\tLOG_DEBUG<<\"\\n\\t>: Dbg msg from: thread_func_3\\n\";\n\tLOG_DEBUG_1<<\"\\n\\t>: Dbg_Level_1 msg from: thread_func_3\\n\";\n\tSleep(100);\n\tLOG_WARNING<<\"\\n\\tSome warning from thread_3\";\n\tSleep(100);\n\treturn 0;\n}\nunsigned  __stdcall  thread_func4(void* pParam )\n{\n\tLOG_DEBUG<<\"\\n\\t>: Dbg msg from: thread_func_4\\n\";\n\tLOG_DEBUG_1<<\"\\n\\t>: Dbg_Level_1 msg from: thread_func_4\\n\";\n\tSleep(100);\n\tLOG_WARNING<<\"\\n\\tSome warning from thread_4\";\n\tSleep(100);\n\treturn 0;\n}\nunsigned  __stdcall  thread_func5(void* pParam )\n{\n\tLOG_DEBUG<<\"\\n\\t>: Dbg msg from: thread_func_5\\n\";\n\tLOG_DEBUG_1<<\"\\n\\t>: Dbg_Level_1 msg from: thread_func_5\\n\";\n\tSleep(100);\n\tLOG_WARNING<<\"\\n\\tSome warning from thread_5\";\n\tSleep(100);\n\treturn 0;\n}\n\n#endif\n\nint main(int argc, char* argv[])\n{\n\t\/\/ set logging level (as default DEBUG3)\n\tLog::ReportingLevel() = Log::LevelFromString(argv[1] ? argv[1] : \"DEBUG3\");\n\n\t\/\/ init the log file\n\tLOG_FILE_INIT( \"MyLog.log\" );\n\n\tLOG_IS_OUTPUT_TIME( true );\n\n\tLOG_INFO << \"Initialize the log file!\";\n\n\tLOG_IS_OUTPUT_TIME( false );\n\t\n\t\/\/ messages are output in the console (stderr)\n\tLOG_USE_STDERR;\n\n#ifndef LOG_MULTITHREADING\n\n\tLOG_INFO << \"\\n\\tMessage: \"<<10<<2<<3<<1<<\" end.\\n\";\n\n\t\/\/ messages are output in the log file\n\tLOG_USE_FILE;\n\n\tLOG_ERROR << \"some error msg\";\n\n\t\/\/ again output in the console\n\tLOG_USE_STDERR;\n\n\tLOG_DEBUG << \"Message out in the console...\";\n\n\tconst int count = 7;\n\n\tLOG_DEBUG_1 << \"\\ncount = \" << count;\n\n\tfor (int i = 0; i != count; ++i)\n\t{\n\t\tLOG_DEBUG_2 << \"the counter 'i' = \" << i;\n\n\t\tstatic int val = 9;\n\n\t\tLOG_DEBUG_2 << \"val = \" << val;\n\n\t\tval += i;\n\n\t\tLOG_DEBUG_3 << \"(val += i) = \" << val;\n\t}\n\n#else\n\n\tconst int n_threads = 5;\n\t\n\tHANDLE threads[n_threads];\n\n\t\/\/ initialize\n\tfor ( int i = 0; i != n_threads; ++i ) {\n\t\tthreads[i] = INVALID_HANDLE_VALUE;\n\t}\n\n\t\/\/ create five threads\n\tthreads[0] = (HANDLE) _beginthreadex( NULL, 0, &thread_func1, nullptr, 0, nullptr );\n\tthreads[1] = (HANDLE) _beginthreadex( NULL, 0, &thread_func2, nullptr, 0, nullptr );\n\tthreads[2] = (HANDLE) _beginthreadex( NULL, 0, &thread_func3, nullptr, 0, nullptr );\n\tthreads[3] = (HANDLE) _beginthreadex( NULL, 0, &thread_func4, nullptr, 0, nullptr );\n\tthreads[4] = (HANDLE) _beginthreadex( NULL, 0, &thread_func5, nullptr, 0, nullptr );\n\n\tWaitForMultipleObjects( n_threads, &threads[0], TRUE, INFINITE );\n\n#endif\n\n\tgetchar();\n\n\treturn 0;\n}\n","avg_line_length":23.4057971014,"max_line_length":85,"alphanum_fraction":0.6405572755,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2820,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["CC-BY-3.0","Apache-2.0","MIT"],"max_stars_count":2.0,"content":"\/*************************************************************************\/\n\/*  position_2d.cpp                                                      *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"position_2d.h\"\n#include \"scene\/resources\/texture.h\"\n\nvoid Position2D::_draw_cross() {\n\n\tdraw_line(Point2(-10, 0), Point2(+10, 0), Color(1, 0.5, 0.5));\n\tdraw_line(Point2(0, -10), Point2(0, +10), Color(0.5, 1, 0.5));\n}\n\nRect2 Position2D::get_item_rect() const {\n\n\treturn Rect2(Point2(-10, -10), Size2(20, 20));\n}\n\nvoid Position2D::_notification(int p_what) {\n\n\tswitch (p_what) {\n\n\t\tcase NOTIFICATION_ENTER_TREE: {\n\n\t\t\tupdate();\n\t\t} break;\n\t\tcase NOTIFICATION_DRAW: {\n\t\t\tif (!is_inside_tree())\n\t\t\t\tbreak;\n\t\t\tif (get_tree()->is_editor_hint())\n\t\t\t\t_draw_cross();\n\n\t\t} break;\n\t}\n}\n\nPosition2D::Position2D() {\n}\n","avg_line_length":43.3846153846,"max_line_length":75,"alphanum_fraction":0.4886524823,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":374,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":16.0,"content":"\/********************************************************\n*                                                       *\n*   Copyright (C) Microsoft. All rights reserved.   *\n*                                                       *\n********************************************************\/\n\n#include \"CoreUtilsPch.h\"\n\n#include <CoreUtils\/Trace.h>\n\nDEFINE_TRACE_AREA(Tracked, 0);","avg_line_length":34.0,"max_line_length":57,"alphanum_fraction":0.2754010695,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8975,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":13.0,"content":"#include \"stdafx.h\"\n\n\/\/------------------------------------------------------------------------------\n\/\/Copyright Robert Pelloni.\n\/\/All Rights Reserved.\n\/\/------------------------------------------------------------------------------\n\n\n\/\/#pragma once\n\n\n\n\nLogger ActionManager::log = Logger(\"ActionManager\");\n\n\nint ActionManager::ACTIONCAPTIONTYPE_NONE = 0;\nint ActionManager::ACTIONCAPTIONTYPE_TILE = 1;\nint ActionManager::ACTIONCAPTIONTYPE_XY = 2;\nint ActionManager::ACTIONCAPTIONTYPE_XYXY = 3;\nint ActionManager::ACTIONCAPTIONTYPE_NPC = 4;\nint ActionManager::ACTIONCAPTIONTYPE_AREA = 5;\n\nActionManager::Coords::Coords(ActionManager* outerInstance, int x, int y) : outerInstance(outerInstance)\n{\n\tthis->x = x;\n\tthis->y = y;\n}\n\nActionManager::ActionManager(Engine* g)\n{ \/\/=========================================================================================================================\n\n\n\tthis->e = g;\n\n\n\t\/\/make getText icon texture\n\n\t\/\/send into new sprite\n\n\t\/\/DONE: new Entity(texture filename) should add itself to the entity manager automatically.. G.entityManager.add(this)\n\n\t\/\/new Caption() should do this too\n\n\n\tif (actionIconScreenSprite == nullptr)\n\t{\n\t\tactionIconScreenSprite = new ScreenSprite(g, \"button\", \"actionIcon\"); \/\/HARDWARE_create_sprite(TEXT_button_icon_GFX,0,1,1.0f,actionx-8,actiony+1,255);\n\t\tactionIconScreenSprite->draw = false;\n\n\t\tactionIconScreenSprite->setAnimateLoopThroughAllFrames();\n\t\tactionIconScreenSprite->setRandomUpToTicksBetweenAnimationLoop(false);\n\t\tactionIconScreenSprite->setTicksBetweenFrames(60);\n\t\tactionIconScreenSprite->setTicksBetweenAnimationLoop(0);\n\t}\n}\n\n\n\nvoid ActionManager::deleteIfNoAction()\n{ \/\/=========================================================================================================================\n\n\t\/\/if(PLAYER_check_action_dont_run(facing_direction)==0)\n\tif (actionCaption != nullptr)\n\t{\n\t\tif (actionCaption->actionCaptionType == ACTIONCAPTIONTYPE_TILE) \/\/only delete action tile captions\n\t\t{\n\t\t\tactionCaption->setToFadeOutAndBeDeleted();\n\t\t\tactionCaption = nullptr;\n\t\t\tactionIconScreenSprite->draw = false;\n\t\t}\n\t}\n}\n\nbool ActionManager::xy(int x, int y, const string& label)\n{ \/\/=========================================================================================================================\n\n\treturn checkAll(x, y, x + 1, y + 1, label, ACTIONCAPTIONTYPE_XY, nullptr, nullptr);\n}\n\nbool ActionManager::area(Area* a, const string& label)\n{ \/\/=========================================================================================================================\n\n\treturn checkAll(0, 0, 0, 0, label, ACTIONCAPTIONTYPE_AREA, nullptr, a);\n}\n\nbool ActionManager::xyxy(int x, int y, int x2, int y2, const string& label)\n{ \/\/=========================================================================================================================\n\n\treturn checkAll(x, y, x2, y2, label, ACTIONCAPTIONTYPE_XYXY, nullptr, nullptr);\n}\n\nbool ActionManager::entity(Entity* e, const string& label)\n{ \/\/=========================================================================================================================\n\n\treturn checkAll(0, 0, 0, 0, label, ACTIONCAPTIONTYPE_NPC, e, nullptr);\n}\n\nbool ActionManager::checkAll(int x, int y, int x2, int y2, const string& label, int type, Entity* e, Area* a)\n{ \/\/=========================================================================================================================\n\n\n\tif (getPlayer() == nullptr)\n\t{\n\t\treturn false;\n\t}\n\n\tbool inRange = false;\n\n\n\tif (type == ACTIONCAPTIONTYPE_AREA)\n\t{\n\t\tx = (int)(a->getLeft());\n\t\ty = (int)(a->getTop());\n\t\tx2 = (int)(a->getRight());\n\t\ty2 = (int)(a->getBottom());\n\n\t\tif (getPlayer()->isAreaBoundaryTouchingMyHitBox(a) == true && getTextManager()->textEngineState == 0 && getPlayer()->GLOBAL_main_sprite_actions_off == 0)\n\t\t{\n\t\t\tinRange = true;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (type == ACTIONCAPTIONTYPE_NPC)\n\t\t{\n\t\t\tx = (int)(a->getLeft());\n\t\t\ty = (int)(a->getTop());\n\t\t\tx2 = (int)(a->getRight());\n\t\t\ty2 = (int)(a->getBottom());\n\n\t\t\tif (getPlayer()->isEntityHitBoxTouchingMyHitBox(e) == true && getTextManager()->textEngineState == 0 && getPlayer()->GLOBAL_main_sprite_actions_off == 0)\n\t\t\t{\n\t\t\t\tinRange = true;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (\n\t\t\t\tgetPlayer()->isHitBoxTouchingXYXYInDirectionByAmount((float)x, (float)y, (float)x2, (float)y2, getPlayer()->animationDirection, 7) == true &&\n\t\t\t\tgetTextManager()->textEngineState == 0 &&\n\t\t\t\tgetPlayer()->GLOBAL_main_sprite_actions_off == 0\n\t\t\t)\n\t\t\t{\n\t\t\t\tinRange = true;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tactionsThisFrame->add(new Coords(this, x + (x2 - x), y + (y2 - y)));\n\n\n\tif (inRange)\n\t{\n\t\tif (label != \"\" && label == \"\" == false)\n\t\t{\n\t\t\tif (actionCaption != nullptr)\n\t\t\t{\n\t\t\t\treplaceCaptionText(label);\n\n\t\t\t\tactionCaption->actionCaptionType = type;\n\t\t\t\tactionCaption->actionRangeX = x;\n\t\t\t\tactionCaption->actionRangeY = y;\n\t\t\t\tactionCaption->entity = e;\n\t\t\t\tactionCaption->area = a;\n\t\t\t}\n\t\t\telse\n\t\t\t{ \/\/doesnt exist,make new one over sprites head\n\t\t\t\tmakeCaption(label);\n\n\t\t\t\tactionCaption->actionCaptionType = type;\n\t\t\t\tactionCaption->actionRangeX = x;\n\t\t\t\tactionCaption->actionRangeY = y;\n\t\t\t\tactionCaption->entity = e;\n\t\t\t\tactionCaption->area = a;\n\t\t\t}\n\n\n\t\t\tif (actionCaption != nullptr && getControlsManager()->bgClient_ACTION_Pressed() == true && label.compare(actionCaption->text) == 0 && ((actionCaption->actionCaptionType == ACTIONCAPTIONTYPE_XYXY && actionCaption->actionRangeX == x && actionCaption->actionRangeY == y) || (actionCaption->actionCaptionType == ACTIONCAPTIONTYPE_XY && actionCaption->actionRangeX == x && actionCaption->actionRangeY == y) || (actionCaption->actionCaptionType == ACTIONCAPTIONTYPE_NPC && actionCaption->entity == e) || (actionCaption->actionCaptionType == ACTIONCAPTIONTYPE_AREA && actionCaption->area == a)))\n\t\t\t{\n\t\t\t\tdeleteCaptionWithBlipSound();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (getControlsManager()->bgClient_ACTION_Pressed() == true)\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\telse \/\/else delete action icon and getCaption\n\t{\n\t\tif (label != \"\" && label == \"\" == false)\n\t\t{\n\t\t\tif (actionCaption != nullptr && label.compare(actionCaption->text) == 0 && ((actionCaption->actionCaptionType == ACTIONCAPTIONTYPE_XYXY && actionCaption->actionRangeX == x && actionCaption->actionRangeY == y) || (actionCaption->actionCaptionType == ACTIONCAPTIONTYPE_XY && actionCaption->actionRangeX == x && actionCaption->actionRangeY == y) || (actionCaption->actionCaptionType == ACTIONCAPTIONTYPE_NPC && actionCaption->entity == e) || (actionCaption->actionCaptionType == ACTIONCAPTIONTYPE_AREA && actionCaption->area == a)))\n\t\t\t{\n\t\t\t\tdeleteCaptionNoSound();\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false;\n}\n\nvoid ActionManager::deleteCaptionNoSound()\n{ \/\/=========================================================================================================================\n\n\tif (actionCaption != nullptr)\n\t{\n\t\tactionCaption->setToFadeOutAndBeDeleted();\n\t\tactionCaption = nullptr;\n\t\tactionIconScreenSprite->draw = false;\n\t}\n}\n\nvoid ActionManager::deleteCaptionWithBlipSound()\n{ \/\/=========================================================================================================================\n\tgetAudioManager()->playSound(\"blip\", 0.25f, 1.6f, 1);\n\n\tdeleteCaptionNoSound();\n}\n\nvoid ActionManager::makeCaption(const string& label)\n{ \/\/=========================================================================================================================\n\n\t\/*\n\tint px = (int)(ACTION_caption.caption_width*2*ACTION_caption.getScale);\n\tint actionx=((player().screen_x+player().size_x\/2)-((px+8)\/2))+8;\/\/centered over player sprite\n\tif(actionx+px>Display.getWidth())actionx=Display.getWidth()-px;\/\/dont go past right\n\tif(actionx-8<0)actionx=0+8;\/\/dont go past left\n\tint actiony=player().screen_y-16;\n\t*\/\n\n\n\tactionCaption = getCaptionManager()->newManagedCaption(Caption::CENTERED_OVER_ENTITY, 0, -1, label, BobFont::font_small_16_outlined_smooth, BobColor::white, nullptr, BobColor::clear, RenderOrder::ABOVE_TOP, 1.0f, 0);\n\n\n\tactionIconScreenSprite->screenXPixelsHQ = actionCaption->screenX - (actionIconScreenSprite->getWidth() + 4); \/\/move action icon sprite\n\tactionIconScreenSprite->screenYPixelsHQ = actionCaption->screenY - 8;\n\n\tactionIconScreenSprite->draw = true;\n}\n\nvoid ActionManager::replaceCaptionText(const string& label)\n{ \/\/=========================================================================================================================\n\n\tif (label.compare(actionCaption->text) != 0) \/\/        if action icon exists,check new label against old label\n\t{\n\t\tactionCaption->setText(label);\n\t\t\/\/move action icon sprite\n\t}\n\telse\n\t{\n\t\tactionIconScreenSprite->screenXPixelsHQ = actionCaption->screenX - (actionIconScreenSprite->getWidth() + 4); \/\/move action icon sprite\n\t\tactionIconScreenSprite->screenYPixelsHQ = actionCaption->screenY - 8;\n\t}\n}\n\nvoid ActionManager::update()\n{ \/\/=========================================================================================================================\n\tactionsThisFrame->clear();\n}\n\n","avg_line_length":33.6142322097,"max_line_length":591,"alphanum_fraction":0.5769359331,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":105,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"StateDrivenBoscoController.h\"\n\nAStateDrivenBoscoController::AStateDrivenBoscoController() {\n}\n\n","avg_line_length":17.5,"max_line_length":60,"alphanum_fraction":0.8380952381,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5699,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2011-2014, Willow Garage, Inc.\n *  Copyright (c) 2014-2015, Open Source Robotics Foundation\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and\/or other materials provided\n *     with the distribution.\n *   * Neither the name of Open Source Robotics Foundation nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/** \\author Jia Pan *\/\n\n\n#include <hpp\/fcl\/shape\/geometric_shapes.h>\n#include <hpp\/fcl\/shape\/geometric_shapes_utility.h>\n\nnamespace hpp\n{\nnamespace fcl\n{\n\nvoid ConvexBase::initialize(bool own_storage, Vec3f* points_, unsigned int num_points_)\n{\n  points       = points_;\n  num_points   = num_points_;\n  own_storage_ = own_storage;\n  computeCenter();\n}\n\nvoid ConvexBase::set(bool own_storage_, Vec3f* points_, unsigned int num_points_)\n{\n  if(own_storage_ && points) delete [] points;\n  initialize(own_storage_,points_,num_points_);\n}\n\nConvexBase::ConvexBase(const ConvexBase& other) :\n  ShapeBase    (other),\n  num_points   (other.num_points),\n  center       (other.center),\n  own_storage_ (other.own_storage_)\n{\n  if (neighbors) delete [] neighbors;\n  if (nneighbors_) delete [] nneighbors_;\n  if (own_storage_) {\n    if (own_storage_ && points) delete [] points;\n\n    points = new Vec3f[num_points];\n    std::copy(other.points, other.points + num_points, points);\n  }\n  else\n    points = other.points;\n\n  neighbors = new Neighbors[num_points];\n  std::copy(other.neighbors, other.neighbors + num_points, neighbors);\n\n  std::size_t c_nneighbors = 0;\n  for (std::size_t i = 0; i < num_points; ++i)\n    c_nneighbors += neighbors[i].count();\n  nneighbors_ = new unsigned int[c_nneighbors];\n  std::copy(other.nneighbors_, other.nneighbors_ + c_nneighbors, nneighbors_);\n\n  ShapeBase::operator=(*this);\n}\n\nConvexBase::~ConvexBase ()\n{\n  if (neighbors) delete [] neighbors;\n  if (nneighbors_) delete [] nneighbors_;\n  if (own_storage_ && points) delete [] points;\n}\n\nvoid ConvexBase::computeCenter()\n{\n  center.setZero();\n  for(std::size_t i = 0; i < num_points; ++i)\n    center += points[i]; \/\/ TODO(jcarpent): vectorization\n  center \/= num_points;\n}\n\nvoid Halfspace::unitNormalTest()\n{\n  FCL_REAL l = n.norm();\n  if(l > 0)\n  {\n    FCL_REAL inv_l = 1.0 \/ l;\n    n *= inv_l;\n    d *= inv_l;\n  }\n  else\n  {\n    n << 1, 0, 0;\n    d = 0;\n  }\n}\n\nvoid Plane::unitNormalTest()\n{\n  FCL_REAL l = n.norm();\n  if(l > 0)\n  {\n    FCL_REAL inv_l = 1.0 \/ l;\n    n *= inv_l;\n    d *= inv_l;\n  }\n  else\n  {\n    n << 1, 0, 0;\n    d = 0;\n  }\n}\n\nvoid Box::computeLocalAABB()\n{\n  computeBV<AABB>(*this, Transform3f(), aabb_local);\n  aabb_center = aabb_local.center();\n  aabb_radius = (aabb_local.min_ - aabb_center).norm();\n}\n\nvoid Sphere::computeLocalAABB()\n{\n  computeBV<AABB>(*this, Transform3f(), aabb_local);\n  aabb_center = aabb_local.center();\n  aabb_radius = radius;\n}\n\nvoid Ellipsoid::computeLocalAABB()\n{\n  computeBV<AABB>(*this, Transform3f(), aabb_local);\n  aabb_center = aabb_local.center();\n  aabb_radius = (aabb_local.min_ - aabb_center).norm();\n}\n\nvoid Capsule::computeLocalAABB()\n{\n  computeBV<AABB>(*this, Transform3f(), aabb_local);\n  aabb_center = aabb_local.center();\n  aabb_radius = (aabb_local.min_ - aabb_center).norm();\n}\n\nvoid Cone::computeLocalAABB()\n{\n  computeBV<AABB>(*this, Transform3f(), aabb_local);\n  aabb_center = aabb_local.center();\n  aabb_radius = (aabb_local.min_ - aabb_center).norm();\n}\n\nvoid Cylinder::computeLocalAABB()\n{\n  computeBV<AABB>(*this, Transform3f(), aabb_local);\n  aabb_center = aabb_local.center();\n  aabb_radius = (aabb_local.min_ - aabb_center).norm();\n}\n\nvoid ConvexBase::computeLocalAABB()\n{\n  computeBV<AABB>(*this, Transform3f(), aabb_local);\n  aabb_center = aabb_local.center();\n  aabb_radius = (aabb_local.min_ - aabb_center).norm();\n}\n\nvoid Halfspace::computeLocalAABB()\n{\n  computeBV<AABB>(*this, Transform3f(), aabb_local);\n  aabb_center = aabb_local.center();\n  aabb_radius = (aabb_local.min_ - aabb_center).norm();\n}\n\nvoid Plane::computeLocalAABB()\n{\n  computeBV<AABB>(*this, Transform3f(), aabb_local);\n  aabb_center = aabb_local.center();\n  aabb_radius = (aabb_local.min_ - aabb_center).norm();\n}\n\nvoid TriangleP::computeLocalAABB()\n{\n  computeBV<AABB>(*this, Transform3f(), aabb_local);\n  aabb_center = aabb_local.center();\n  aabb_radius = (aabb_local.min_ - aabb_center).norm();\n}\n\n\n}\n\n} \/\/ namespace hpp\n","avg_line_length":27.009478673,"max_line_length":87,"alphanum_fraction":0.7015265836,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3202,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"areas\/grove01.h\"\n\n#include \"ai\/ai-wander.h\"\n#include \"data\/action.h\"\n#include \"data\/data-area.h\"\n#include \"os\/c.h\"\n#include \"tiles\/area.h\"\n#include \"tiles\/entity.h\"\n#include \"tiles\/log.h\"\n#include \"tiles\/music.h\"\n#include \"tiles\/npc.h\"\n#include \"util\/compiler.h\"\n#include \"util\/int.h\"\n#include \"util\/new.h\"\n#include \"world\/clouds.h\"\n\nstatic Clouds clouds;\n\nstatic bool drinking = false;\n\nstatic bool openedChest = false;\nstatic bool musicPaused = false;\n\n\/\/ Circular in-out ease\nstatic float\nease(float x) noexcept {\n    return 0.5f * sinf(M_PI * x - M_PI \/ 2.0f) + 0.5f;\n}\n\nstatic void\nwash(DataArea* area, void*, float progress) noexcept {\n#define MAX_ALPHA 192\n    U8 alpha;\n\n    if (progress < 0.5f) {\n        alpha = static_cast<U8>(MAX_ALPHA * ease(2.0f * progress));\n    }\n    else if (progress < 1.0f) {\n        alpha = static_cast<U8>(MAX_ALPHA * ease(2.0f * (1.0f - progress)));\n    }\n    else {\n        alpha = 0.0f;\n        drinking = false;\n    }\n\n    area->area->setColorOverlay(alpha, 255, 255, 255);\n}\n\nstatic void\nonWell(DataArea* area, Entity*, ivec3) noexcept {\n    if (drinking) {\n        return;\n    }\n\n    drinking = true;\n\n    playSoundEffect(\"sounds\/splash.oga\");\n\n    struct Action delay = makeDelayAction(1000);\n\n    delay.next = xmalloc(struct Action, 1);\n    *delay.next = makeTimerAction(1000, wash, 0, 0);\n\n    area->add(delay);\n}\n\nstatic void\ntoggleMusic() noexcept {\n    if (musicPaused) {\n        musicResume();\n        logInfo(\"grove01\", \"Unpausing music!\");\n    }\n    else {\n        musicPause();\n        logInfo(\"grove01\", \"Pausing music!\");\n    }\n    musicPaused = !musicPaused;\n}\n\nstatic void\nonOpenChest(DataArea* area, Entity*, ivec3) noexcept {\n    \/* This function is called when the chest in grove01.json is\n     * activated by the player. The first time we are run, we open\n     * the chest.  Further invocations feature an easter egg where\n     * we toggle the game's music. :)\n     *\/\n\n    if (openedChest) {\n        toggleMusic();\n        return;\n    }\n\n    openedChest = true;\n\n    TileSet* objects = area->area->getTileSet(\"areas\/tiles\/objects.bmp\");\n\n    \/\/ Change to closed chest to open chest. Bottom and top halves.\n    area->area->grid.setTileType(vicoord{5, 20, -0.1}, objects->at(1, 5));\n    area->area->grid.setTileType(vicoord{5, 21, -0.1}, objects->at(1, 6));\n    area->area->requestRedraw();\n\n    playSoundEffect(\"sounds\/door.oga\");\n}\n\nGrove01::Grove01() noexcept {\n    clouds.z = 10.0;\n\n    scripts.allocate(hash_(StringView(\"well\"))) = onWell;\n    scripts.allocate(hash_(StringView(\"open_chest\"))) = onOpenChest;\n}\n\nvoid\nGrove01::onLoad() noexcept {\n    \/\/ Create a wandering wizard NPC.\n    Character* wizard = area->spawnNPC(\n            \"entities\/wizard\/wizard.json\", vicoord{16, 22, 0.0}, \"down\");\n\n    \/\/ Make it move.\n    new2(AIWanderTileParams, params, c, wizard, chance, 4);\n    new (&params->cooldown) Cooldown(1000);\n\n    make2(Entity::OnTickFn, fn, fn, aiWanderTile, data, params);\n    wizard->attach(fn);\n\n    \/\/ And a few drifting cloud Overlays.\n    for (int i = 0; i < 5; i++) {\n        clouds.createRandomCloud(this);\n    }\n\n#define SECOND 1000\n    clouds.createCloudsRegularly(this, 10 * SECOND, 20 * SECOND);\n}\n","avg_line_length":24.0751879699,"max_line_length":76,"alphanum_fraction":0.6352279825,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4197,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1155.0,"content":"\/\/ (C) Copyright Andrew Sutton 2009\n\/\/\n\/\/ Use, modification and distribution are subject to the\n\/\/ Boost Software License, Version 1.0 (See accompanying file\n\/\/ LICENSE_1_0.txt or http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <iostream>\n#include <string>\n#include <boost\/graph\/adjacency_list.hpp>\n\n#include \"..\/..\/..\/..\/..\/gpld\/common\/typestr.hpp\"\n\nusing namespace std;\nusing namespace boost;\n\n\/\/ The purpose of this test is simply to provide a testing ground for the\n\/\/ invalidation of iterators and descriptors.\n\ntemplate <typename Graph>\nvoid make_graph(Graph& g)\n{\n    \/\/ Build a simple (barbell) graph.\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    Vertex u = add_vertex(10, g);\n    Vertex v = add_vertex(20, g);\n    add_edge(u, v, 100, g);\n}\n\n\/\/ Invalid iterators and descriptors will cause a segfault.\ntemplate <typename Graph, typename Iterator, typename Descriptor>\nvoid test(Graph& g, Iterator i, Descriptor d, string const& str)\n{\n    int x;\n    cout << \"... \" << str << \" iter\" << endl;\n    x = g[*i];\n\/\/     cout << \"... \" << x << endl;\n    cout << \"... \" << str << \" desc\" << endl;\n    x = g[d];\n\/\/     cout << \"... \" << x << endl;\n}\n\ntemplate <typename Graph>\nvoid invalidate_edges()\n{\n    typedef typename graph_traits<Graph>::edge_descriptor Edge;\n    typedef typename graph_traits<Graph>::edge_iterator EdgeIterator;\n\n    Graph g;\n    make_graph(g);\n\n    \/\/ The actual test. These are valid here.\n    EdgeIterator i = edges(g).first;\n    Edge e = *i;\n\n    \/\/ Add a vertex, see what breaks.\n    add_vertex(g);\n    test(g, i, e, \"edges\");\n};\n\ntemplate <typename Graph>\nvoid invalidate_vertices()\n{\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename graph_traits<Graph>::vertex_iterator VertexIterator;\n\n    Graph g;\n    make_graph(g);\n\n    \/\/ The actual test. These are valid here.\n    VertexIterator i = vertices(g).first;\n    Vertex v = *i;\n\n    \/\/ Add a vertex, see what breaks.\n    add_vertex(g);\n    test(g, i, v, \"vertices\");\n}\n\ntemplate <typename Graph>\nvoid invalidate_out_edges()\n{\n    typedef typename graph_traits<Graph>::edge_descriptor Edge;\n    typedef typename graph_traits<Graph>::out_edge_iterator OutIterator;\n\n    Graph g;\n    make_graph(g);\n\n    \/\/ The actual test. These are valid here.\n    OutIterator i = out_edges(*vertices(g).first, g).first;\n    Edge e = *i;\n\n    \/\/ Add a vertex, see what breaks.\n    add_vertex(g);\n    test(g, i, e, \"out edges\");\n}\n\ntemplate <typename Graph>\nvoid invalidate_adj_verts()\n{\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename graph_traits<Graph>::adjacency_iterator AdjIterator;\n\n    Graph g;\n    make_graph(g);\n\n    \/\/ The actual test. These are valid here.\n    AdjIterator i = adjacent_vertices(*vertices(g).first, g).first;\n    Vertex v = *i;\n\n    \/\/ Add a vertex, see what breaks.\n    add_vertex(g);\n    test(g, i, v, \"adjacent vertices\");\n}\n\n\nint main()\n{\n    typedef adjacency_list<vecS, vecS, undirectedS, int, int> VVU;\n    cout << \"vecS vecS undirectedS\" << endl;\n    invalidate_vertices<VVU>();\n    invalidate_edges<VVU>();\n    invalidate_out_edges<VVU>();\n    invalidate_adj_verts<VVU>();\n\n    typedef adjacency_list<vecS, vecS, bidirectionalS, int, int> VVB;\n    cout << \"vecS vecS bidirectionals\" << endl;\n    invalidate_vertices<VVB>();\n    invalidate_edges<VVB>();\n    invalidate_out_edges<VVB>();\n    invalidate_adj_verts<VVB>();\n\n    \/\/ If you comment out the tests before this, then adj_verts test will\n    \/\/ run without segfaulting - at least under gcc-4.3. Not really sure why,\n    \/\/ but I'm guessing it's still not generating valid results, and shouldn't\n    \/\/ be taken as an indicator of stability.\n    typedef adjacency_list<vecS, vecS, directedS, int, int> VVD;\n    cout << \"vecS vecS directedS\" << endl;\n    invalidate_vertices<VVD>();\n\/\/     invalidate_edges<VVD>();\n\/\/     invalidate_out_edges<VVD>();\n\/\/     invalidate_adj_verts<VVD>();\n\n    typedef adjacency_list<listS, vecS, directedS, int, int> LVD;\n    cout << \"listS vecS directedS\" << endl;\n    invalidate_vertices<LVD>();\n\/\/     invalidate_edges<LVD>();\n\/\/     invalidate_out_edges<LVD>();\n\/\/     invalidate_adj_verts<LVD>();\n}\n\n","avg_line_length":27.98,"max_line_length":78,"alphanum_fraction":0.6688110555,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3790,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-2-Clause"],"max_stars_count":3.0,"content":"\/\/ ***************************************************************************\n\/\/\n\/\/   Generated automatically by genwrapper.\n\/\/   Please DO NOT EDIT this file!\n\/\/\n\/\/ ***************************************************************************\n\n#include <osgIntrospection\/ReflectionMacros>\n#include <osgIntrospection\/TypedMethodInfo>\n#include <osgIntrospection\/StaticMethodInfo>\n#include <osgIntrospection\/Attributes>\n\n#include <osg\/CopyOp>\n#include <osg\/Object>\n#include <osgAnimation\/Animation>\n#include <osgAnimation\/AnimationManagerBase>\n#include <osgAnimation\/BasicAnimationManager>\n\n\/\/ Must undefine IN and OUT macros defined in Windows headers\n#ifdef IN\n#undef IN\n#endif\n#ifdef OUT\n#undef OUT\n#endif\n\nBEGIN_OBJECT_REFLECTOR(osgAnimation::BasicAnimationManager)\n\tI_DeclaringFile(\"osgAnimation\/BasicAnimationManager\");\n\tI_BaseType(osgAnimation::AnimationManagerBase);\n\tI_Method0(osg::Object *, cloneType,\n\t          Properties::VIRTUAL,\n\t          __osg_Object_P1__cloneType,\n\t          \"Clone the type of an object, with Object* return type. \",\n\t          \"Must be defined by derived classes. \");\n\tI_Method1(osg::Object *, clone, IN, const osg::CopyOp &, copyop,\n\t          Properties::VIRTUAL,\n\t          __osg_Object_P1__clone__C5_osg_CopyOp_R1,\n\t          \"Clone an object, with Object* return type. \",\n\t          \"Must be defined by derived classes. \");\n\tI_Method1(bool, isSameKindAs, IN, const osg::Object *, obj,\n\t          Properties::VIRTUAL,\n\t          __bool__isSameKindAs__C5_osg_Object_P1,\n\t          \"\",\n\t          \"\");\n\tI_Method0(const char *, libraryName,\n\t          Properties::VIRTUAL,\n\t          __C5_char_P1__libraryName,\n\t          \"return the name of the object's library. \",\n\t          \"Must be defined by derived classes. The OpenSceneGraph convention is that the namespace of a library is the same as the library name. \");\n\tI_Method0(const char *, className,\n\t          Properties::VIRTUAL,\n\t          __C5_char_P1__className,\n\t          \"return the name of the object's class type. \",\n\t          \"Must be defined by derived classes. \");\n\tI_Constructor0(____BasicAnimationManager,\n\t               \"\",\n\t               \"\");\n\tI_ConstructorWithDefaults2(IN, const osgAnimation::AnimationManagerBase &, b, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY,\n\t                           ____BasicAnimationManager__C5_AnimationManagerBase_R1__C5_osg_CopyOp_R1,\n\t                           \"\",\n\t                           \"\");\n\tI_Method1(void, update, IN, double, time,\n\t          Properties::VIRTUAL,\n\t          __void__update__double,\n\t          \"\",\n\t          \"\");\n\tI_MethodWithDefaults3(void, playAnimation, IN, osgAnimation::Animation *, pAnimation, , IN, int, priority, 0, IN, float, weight, 1.0,\n\t                      Properties::NON_VIRTUAL,\n\t                      __void__playAnimation__Animation_P1__int__float,\n\t                      \"\",\n\t                      \"\");\n\tI_Method1(bool, stopAnimation, IN, osgAnimation::Animation *, pAnimation,\n\t          Properties::NON_VIRTUAL,\n\t          __bool__stopAnimation__Animation_P1,\n\t          \"\",\n\t          \"\");\n\tI_Method1(bool, findAnimation, IN, osgAnimation::Animation *, pAnimation,\n\t          Properties::NON_VIRTUAL,\n\t          __bool__findAnimation__Animation_P1,\n\t          \"\",\n\t          \"\");\n\tI_Method1(bool, isPlaying, IN, osgAnimation::Animation *, pAnimation,\n\t          Properties::NON_VIRTUAL,\n\t          __bool__isPlaying__Animation_P1,\n\t          \"\",\n\t          \"\");\n\tI_Method1(bool, isPlaying, IN, const std::string &, animationName,\n\t          Properties::NON_VIRTUAL,\n\t          __bool__isPlaying__C5_std_string_R1,\n\t          \"\",\n\t          \"\");\n\tI_Method0(void, stopAll,\n\t          Properties::NON_VIRTUAL,\n\t          __void__stopAll,\n\t          \"\",\n\t          \"\");\nEND_REFLECTOR\n\n","avg_line_length":38.2828282828,"max_line_length":149,"alphanum_fraction":0.6055408971,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4402,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"Generators\/CPUNodeEditor\/Nodes\/MathFunctionNode.h\"\n#include \"Generators\/CPUNodeEditor\/CPUNodeEditor.h\"\n\n#include \"muParser.h\"\n#include \"Utils.h\"\n\n#include <locale>\n#include <codecvt>\n#include <string>\n#include <iostream>\n\n\nstatic void SetupParser(mu::Parser *parser)\n{\n\t\/\/ TODO\n}\n\nNodeOutput MathFunctionNode::Evaluate(NodeInputParam input, NodeEditorPin *pin)\n{\n\ttry\n\t{\n\t\tif (input.maxZ == 0)\n\t\t{\n\t\t\tinput.maxZ = 1;\n\t\t}\n\n\t\tx = (input.x \/ input.maxX) * 2 - 1;\n\t\ty = (input.y \/ input.maxY) * 2 - 1;\n\t\tz = (input.z \/ input.maxZ) * 2 - 1;\n\t\treturn NodeOutput({(float)parser->Eval() * factor});\n\t}\n\n\tcatch (...)\n\t{\n\t}\n\n\treturn NodeOutput({0.0f});\n}\n\nvoid MathFunctionNode::Load(nlohmann::json data)\n{\n\tstd::string expr = data[\"expr\"];\n\tmemcpy(inputExpression, expr.data(), data.size());\n\tmathInputWidth = data[\"mathInputWidth\"];\n\tfactor = data[\"factor\"];\n\t\/*\n\tvars.clear();\n\tparser->ClearVar();\n\tparser->DefineVar(L\"x\", &x);\n\tparser->DefineVar(L\"y\", &y);\n\tparser->DefineVar(L\"z\", &z);\n\tfor (auto& tmp : data[\"vars\"])\n\t{\n\t    vars.push_back(std::make_pair<std::string, double>(tmp[\"name\"], tmp[\"value\"]));\n\t    parser->DefineVar(s2ws(vars.back().first), &vars.back().second);\n\t}\n\t*\/\n}\n\nnlohmann::json MathFunctionNode::Save()\n{\n\tnlohmann::json data;\n\tnlohmann::json tmp;\n\tnlohmann::json tmp2;\n\tdata[\"type\"] = MeshNodeEditor::MeshNodeType::MathFunction;\n\tdata[\"expr\"] = std::string(inputExpression);\n\tdata[\"mathInputWidth\"] = mathInputWidth;\n\tdata[\"factor\"] = factor;\n\t\/*\n\tfor (int i = 0; i < vars.size(); i++)\n\t{\n\t    tmp2.clear();\n\t    tmp2[\"name\"] = vars[i].first;\n\t    tmp2[\"value\"] = vars[i].second;\n\t    tmp.push_back(tmp2);\n\t}\n\tdata[\"vars\"] = tmp;\n\t*\/\n\treturn data;\n}\n\nvoid MathFunctionNode::OnRender()\n{\n\tDrawHeader(\"Custom Math Function\");\n\tImGui::Dummy(ImVec2(mathInputWidth + 20, 10));\n\tImGui::SameLine();\n\tImGui::Text(\"Out\");\n\toutputPins[0]->Render();\n\tImGui::NewLine();\n\tImGui::Text(\"Math Input Size : \");\n\tImGui::SameLine();\n\tImGui::PushItemWidth(100);\n\tImGui::DragInt(MAKE_IMGUI_ID(outputPins[0]->id), &mathInputWidth, 0.5f);\n\tImGui::PopItemWidth();\n\tinputPins[0]->Render();\n\n\tif (inputPins[0]->IsLinked())\n\t{\n\t\tImGui::Text(\"Factor\");\n\t}\n\n\telse\n\t{\n\t\tImGui::PushItemWidth(100);\n\t\tImGui::DragFloat(MAKE_IMGUI_ID(inputPins[0]->id), &factor, 0.01f);\n\t\tImGui::PopItemWidth();\n\t}\n\n\tImGui::NewLine();\n\t\/*\n\tImGui::Text(\"Varaibles : \");\n\tfor (int i = 0;i<vars.size();i++)\n\t{\n\t    ImGui::PushItemWidth(200);\n\t    ImGui::InputDouble(MAKE_IMGUI_LABEL(i, vars[i].first.c_str()), &vars[i].second, 0.01f);\n\t    ImGui::PopItemWidth();\n\t    ImGui::SameLine();\n\t    if (ImGui::Button(\"X\"))\n\t    {\n\t        parser->RemoveVar(s2ws(vars[i].first));\n\t        vars.erase(vars.begin() + i);\n\t        break;\n\t    }\n\t}\n\n\tImGui::Text(\"Add Variable : \");\n\tImGui::SameLine();\n\tImGui::PushItemWidth(100);\n\tImGui::InputTextWithHint(MAKE_IMGUI_ID(tid), \"Name\", varname, sizeof(varname));\n\tImGui::SameLine();\n\tImGui::PopItemWidth();\n\tImGui::SameLine();\n\tif (ImGui::Button(\"Add\") && strlen(varname) >= 1)\n\t{\n\t    vars.push_back(std::make_pair<std::string, double>(varname, 0.0f));\n\t    parser->DefineVar(s2ws(std::string(varname)), &vars.back().second);\n\t    memset(varname, 0, sizeof(varname));\n\t}\n\n\t*\/\n\tImGui::Text(\"Expression : \");\n\tImGui::SameLine();\n\tImGui::PushItemWidth(mathInputWidth);\n\n\tif (ImGui::InputText(MAKE_IMGUI_ID(id), inputExpression, 1024*4))\n\t{\n\t\tcompiled = false;\n\t}\n\n\tImGui::PopItemWidth();\n\n\tif (!compiled)\n\t{\n\t\tif (ImGui::Button(\"Compile\"))\n\t\t{\n\t\t\tstd::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;\n\t\t\tstd::wstring wide = converter.from_bytes(inputExpression);\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\t#ifdef TERR3D_WIN32\n\t\t\t\tparser->SetExpr(wide);\n\t\t\t\t#else\n\t\t\t\tparser->SetExpr(std::string(inputExpression));\n\t\t\t\t#endif\n\t\t\t\tcompiled = true;\n\t\t\t}\n\n\t\t\tcatch (...)\n\t\t\t{\n\t\t\t}\n\t\t}\n\t}\n}\n\nMathFunctionNode::MathFunctionNode()\n{\n\theaderColor = ImColor(VALUE_NODE_COLOR);\n\tinputPins.push_back(new NodeEditorPin());\n\toutputPins.push_back(new NodeEditorPin(NodeEditorPinType::Output));\n\tparser = new mu::Parser();\n\tmemset(inputExpression, 0, sizeof(inputExpression));\n\tmemset(varname, 0, sizeof(varname));\n\tx = y = z = 0;\n\tfactor = 1;\n\tmathInputWidth = 150;\n\tcompiled = false;\n\tSetupParser(parser);\n#ifdef TERR3D_WIN32\n\tparser->DefineVar(L\"x\", &x);\n\tparser->DefineVar(L\"y\", &y);\n\tparser->DefineVar(L\"z\", &z);\n#else\n\tparser->DefineVar(\"x\", &x);\n\tparser->DefineVar(\"y\", &y);\n\tparser->DefineVar(\"z\", &z);\n#endif\n\n}\n","avg_line_length":22.01,"max_line_length":92,"alphanum_fraction":0.6467514766,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":5858,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":15.0,"content":"#include <StdCfg.h>\n#include \"DEMShaderWrapper.h\"\n\n#include <Render\/GPUDriver.h>\n#include <Render\/Effect.h>\n#include <Render\/Sampler.h>\n#include <UI\/CEGUI\/DEMRenderer.h>\n#include <UI\/CEGUI\/DEMTexture.h>\n\n#include <CEGUI\/ShaderParameterBindings.h>\n#include <glm\/gtc\/type_ptr.hpp>\n\nnamespace CEGUI\n{\n\nCDEMShaderWrapper::CDEMShaderWrapper(Render::PGPUDriver GPU, Render::CEffect& Effect, Render::PSampler LinearSampler)\n\t: _GPU(GPU)\n\t, _Effect(&Effect)\n\t, _LinearSampler(LinearSampler)\n{\n}\n\/\/---------------------------------------------------------------------\n\nCDEMShaderWrapper::~CDEMShaderWrapper() = default;\n\/\/---------------------------------------------------------------------\n\nvoid CDEMShaderWrapper::setInputSet(BlendMode BlendMode, bool Clipped, bool Opaque)\n{\n\tstatic const CStrID RegularUnclipped(\"RegularUnclippedUI\");\n\tstatic const CStrID PremultipliedUnclipped(\"PremultipliedUnclippedUI\");\n\tstatic const CStrID OpaqueUnclipped(\"OpaqueUnclippedUI\");\n\tstatic const CStrID RegularClipped(\"RegularClippedUI\");\n\tstatic const CStrID PremultipliedClipped(\"PremultipliedClippedUI\");\n\tstatic const CStrID OpaqueClipped(\"OpaqueClippedUI\");\n\n\tCStrID NewInputSet;\n\tif (Opaque)\n\t\tNewInputSet = Clipped ? OpaqueClipped : OpaqueUnclipped;\n\telse if (BlendMode == BlendMode::RttPremultiplied)\n\t\tNewInputSet = Clipped ? PremultipliedClipped : PremultipliedUnclipped;\n\telse\n\t\tNewInputSet = Clipped ? RegularClipped : RegularUnclipped;\n\n\tif (_CurrInputSet == NewInputSet) return;\n\n\t_CurrInputSet = NewInputSet;\n\n\tauto It = _TechCache.find(NewInputSet);\n\tif (It == _TechCache.cend())\n\t{\n\t\tstatic const CStrID sidTextureID(\"BoundTexture\");\n\t\tstatic const CStrID sidSamplerID(\"LinearSampler\");\n\t\tstatic const CStrID sidWVP(\"WVP\");\n\t\tstatic const CStrID sidAlphaPercentage(\"AlphaPercentage\");\n\n\t\tconst auto* pTech = _Effect->GetTechByInputSet(_CurrInputSet);\n\t\tRender::IResourceParam* pMainTextureParam = pTech ? pTech->GetParamTable().GetResource(sidTextureID) : nullptr;\n\t\tRender::ISamplerParam* pLinearSamplerParam = pTech ? pTech->GetParamTable().GetSampler(sidSamplerID) : nullptr;\n\t\tRender::CShaderConstantParam WVPParam = pTech ? pTech->GetParamTable().GetConstant(sidWVP) : Render::CShaderConstantParam();\n\t\tRender::CShaderConstantParam AlphaPercentageParam = pTech ? pTech->GetParamTable().GetConstant(sidAlphaPercentage) : Render::CShaderConstantParam();\n\n\t\tCTechCache NewCache\n\t\t{\n\t\t\tpTech,\n\t\t\tpMainTextureParam,\n\t\t\tpLinearSamplerParam,\n\t\t\tWVPParam,\n\t\t\tAlphaPercentageParam,\n\t\t\tRender::CShaderParamStorage(pTech->GetParamTable(), *_GPU)\n\t\t};\n\n\t\tIt = _TechCache.emplace(NewInputSet, std::move(NewCache)).first;\n\t}\n\t\n\t_pCurrCache = &It->second;\n\n\tif (!_pCurrCache || !_pCurrCache->pTech) return;\n\n\t\/\/ FIXME: no multipass support for now, CEGUI does multiple passes in its effects\n\tUPTR LightCount = 0;\n\t_GPU->SetRenderState(_pCurrCache->pTech->GetPasses(LightCount)[0]);\n\n\tif (_pCurrCache && _pCurrCache->pLinearSamplerParam)\n\t\t_pCurrCache->pLinearSamplerParam->Apply(*_GPU, _LinearSampler.Get());\n}\n\/\/---------------------------------------------------------------------\n\nvoid CDEMShaderWrapper::prepareForRendering(const ShaderParameterBindings* shaderParameterBindings)\n{\n\tif (!_pCurrCache || !_pCurrCache->pTech) return;\n\n\tconst ShaderParameterBindings::ShaderParameterBindingsMap& paramMap = shaderParameterBindings->getShaderParameterBindings();\n\tfor (auto&& param : paramMap)\n\t{\n\t\t\/\/ Default CEGUI texture. Hardcoded inside CEGUI as \"texture0\".\n\t\tif (param.first == \"texture0\")\n\t\t{\n\t\t\tif (_pCurrCache->pMainTextureParam)\n\t\t\t{\n\t\t\t\tconst CEGUI::ShaderParameterTexture* pPrm = static_cast<const CEGUI::ShaderParameterTexture*>(param.second);\n\t\t\t\tconst CEGUI::CDEMTexture* pTex = static_cast<const CEGUI::CDEMTexture*>(pPrm->d_parameterValue);\n\t\t\t\t_pCurrCache->pMainTextureParam->Apply(*_GPU, pTex->getTexture());\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\telse if (param.first == \"WVP\") \/\/ Cached for faster access\n\t\t{\n\t\t\tif (_pCurrCache->WVPParam)\n\t\t\t{\n\t\t\t\tconst CEGUI::ShaderParameterMatrix* pPrm = static_cast<const CEGUI::ShaderParameterMatrix*>(param.second);\n\t\t\t\t_pCurrCache->Storage.SetRawConstant(_pCurrCache->WVPParam, glm::value_ptr(pPrm->d_parameterValue), sizeof(glm::mat4));\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\telse if (param.first == \"AlphaPercentage\") \/\/ Cached for faster access\n\t\t{\n\t\t\tif (_pCurrCache->AlphaPercentageParam)\n\t\t\t{\n\t\t\t\tconst CEGUI::ShaderParameterFloat* pPrm = static_cast<const CEGUI::ShaderParameterFloat*>(param.second);\n\t\t\t\t_pCurrCache->Storage.SetFloat(_pCurrCache->AlphaPercentageParam, pPrm->d_parameterValue);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tauto Const = _pCurrCache->pTech->GetParamTable().GetConstant(CStrID(param.first.c_str()));\n\t\tif (!Const) continue;\n\n\t\tswitch (param.second->getType())\n\t\t{\n\t\t\tcase CEGUI::ShaderParamType::Matrix4X4:\n\t\t\t{\n\t\t\t\tconst CEGUI::ShaderParameterMatrix* pPrm = static_cast<const CEGUI::ShaderParameterMatrix*>(param.second);\n\t\t\t\t_pCurrCache->Storage.SetRawConstant(Const, glm::value_ptr(pPrm->d_parameterValue), sizeof(glm::mat4));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CEGUI::ShaderParamType::Float:\n\t\t\t{\n\t\t\t\tconst CEGUI::ShaderParameterFloat* pPrm = static_cast<const CEGUI::ShaderParameterFloat*>(param.second);\n\t\t\t\t_pCurrCache->Storage.SetFloat(Const, pPrm->d_parameterValue);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CEGUI::ShaderParamType::Int:\n\t\t\t{\n\t\t\t\tconst CEGUI::ShaderParameterInt* pPrm = static_cast<const CEGUI::ShaderParameterInt*>(param.second);\n\t\t\t\t_pCurrCache->Storage.SetInt(Const, pPrm->d_parameterValue);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CEGUI::ShaderParamType::Texture:\n\t\t\t{\n\t\t\t\t::Sys::Error(\"CDEMShaderWrapper::prepareForRendering() > CEGUI arbitrary texture not implemented\\n\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t{\n\t\t\t\t::Sys::Error(\"CDEMShaderWrapper::prepareForRendering() > unknown shader parameter type\\n\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t_pCurrCache->Storage.Apply();\n}\n\/\/---------------------------------------------------------------------\n\n}\n","avg_line_length":35.2891566265,"max_line_length":150,"alphanum_fraction":0.7127005804,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":856,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"DTLZ7.h\"\n \nnamespace OFEC {\n\tDTLZ7::DTLZ7(param_map & v) : DTLZ7(v.at(\"problem name\"), (v.at(\"numObj\") + v.at(\"interTest1\") - 1), v.at(\"numObj\")) { \/\/ param_interTest1 = 20 is recommended\n\t}\n\n\tDTLZ7::DTLZ7(const std::string & name, size_t size_var, size_t size_obj) : problem(name, size_var, size_obj), DTLZ(name, size_var, size_obj) {}\n\n\tEvalTag DTLZ7::evaluateObjective(Real *x, std::vector<Real> &obj) {\n\t\tint i = 0;\n\t\tint j = 0;\n\t\tint n = m_num_vars;\n\t\tint k = n - m_num_objs + 1;\n\t\tReal g = 0;\n\t\tReal h = 0;\n\t\tfor (i = n - k + 1; i <= n; i++)\n\t\t\tg += x[i - 1];\n\t\tg = 1 + 9 * g \/ k;\n\t\tfor (i = 1; i <= m_num_objs - 1; i++)\n\t\t\tobj[i - 1] = x[i - 1];\n\t\tfor (j = 1; j <= m_num_objs - 1; j++)\n\t\t\th += x[j - 1] \/ (1 + g) * (1 + sin(3 * OFEC_PI * x[j - 1]));\n\t\th = m_num_objs - h;\n\t\tobj[m_num_objs - 1] = (1 + g) * h;\n\t\treturn EvalTag::Normal;\n\t}\n}","avg_line_length":31.7037037037,"max_line_length":159,"alphanum_fraction":0.5478971963,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2892,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/\n\/\/ Created by armon on 1\/22\/20.\n\/\/\n\n#define CATCH_CONFIG_MAIN\n\n#include <catch2\/catch.hpp>\n\n#include <math.h>\n#include <string>\n#include <fstream>\n\n#include <pcl\/visualization\/cloud_viewer.h>\n#include <pcl\/io\/pcd_io.h>\n\n#include <structural_compass\/structural_compass.h>\n\n\/\/ void visualizeCloud(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &cloud) {\n\/\/     std::cout << \"Cloud size: \" << cloud->points.size() << std::endl;\n\/\/     pcl::visualization::CloudViewer viewer(\"Cloud Viewer\");\n\/\/     viewer.showCloud(cloud);\n\/\/     while (!viewer.wasStopped()) {\n\/\/     }\n\/\/ }\n\nvoid loadPointCloud(const std::string &file, pcl::PointCloud<pcl::PointXYZ> &cloud) {\n\n    if (pcl::io::loadPCDFile<pcl::PointXYZ>(file, cloud) == -1) {\n        throw std::runtime_error(\"loadPointCloud: couldn't read file\");\n    }\n\n}\n\nEigen::Vector3f gravityVectorFromFile(const std::string &file, const int index) {\n\n    std::ifstream infile(file.c_str());\n\n    std::string line;\n    for (size_t i = 0; i <= index; ++i) {\n        std::getline(infile, line);\n    }\n\n    std::istringstream ss(line);\n    float x, y, z;\n    ss >> x >> y >> z;\n\n    Eigen::Vector3f gravity;\n    gravity << x, y, z;\n\n    return gravity;\n\n}\n\nTEST_CASE(\"Entropy Compass\", \"[EntropyCompass]\") {\n\n    int cloud_id = 123;\n\n    std::string vector_file = std::string(\"\/home\/armon\/Research\/Data\/exyn_building_scans\/gravity_vectors.txt\");\n    Eigen::Vector3f gravity = gravityVectorFromFile(vector_file, cloud_id);\n\n    std::string cloud_file = std::string(\"\/home\/armon\/Research\/Data\/exyn_building_scans\/pointclouds_indexed\/\") +\n                             std::string(3, '0') + std::to_string(cloud_id) + std::string(\".pcd\");\n\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_ptr(new pcl::PointCloud<pcl::PointXYZ>);\n    loadPointCloud(cloud_file, *cloud_ptr);\n\n    structural_compass::EntropyCompass compass;\n\n    SECTION(\"principal directions\") {\n\n        Eigen::Matrix3f R;\n        std::vector<Eigen::Vector3f> principal_directions;\n        R = compass.principalDirections(*cloud_ptr, Eigen::Matrix3f::Identity(), gravity, principal_directions);\n\n        \/\/ visualizeCloud(cloud_ptr);\n\n    }\n}\n\nTEST_CASE(\"My Angle Experiments\", \"[My Experiments]\") {\n\n    float angles[] = {-M_PI, -3 * M_PI_4, -M_PI_2, -M_PI_4, 0, M_PI_4, M_PI_2, 3 * M_PI_4, M_PI};\n\n    for (auto a : angles) {\n\n        Eigen::AngleAxisf ax = Eigen::AngleAxisf(a, Eigen::Vector3f::UnitZ());\n\n        Eigen::Matrix3f R = ax.toRotationMatrix();\n\n        Eigen::Vector3f ea = R.eulerAngles(2, 1, 0);\n\n        std::cout << \"true angle: \" << a << std::endl;\n        std::cout << \"euler angles: \" << ea.transpose() << std::endl;\n        std::cout << \"acos: \" << std::acos(R(0, 0)) << std::endl;\n        std::cout << \"asin: \" << std::asin(R(1, 0)) << std::endl;\n        std::cout << \"atan2: \" << std::atan2(R(1, 0), R(0, 0)) << std::endl;\n        std::cout << std::endl;\n\n    }\n\n\n}\n\n","avg_line_length":27.8076923077,"max_line_length":112,"alphanum_fraction":0.622406639,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":24146,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"bucket_space_distribution_context.h\"\n#include \"crypto_uuid_generator.h\"\n#include \"distributor.h\"\n#include \"distributor_bucket_space.h\"\n#include \"distributor_bucket_space_repo.h\"\n#include \"externaloperationhandler.h\"\n#include \"operation_sequencer.h\"\n#include <vespa\/document\/base\/documentid.h>\n#include <vespa\/document\/util\/feed_reject_helper.h>\n#include <vespa\/storage\/common\/reindexing_constants.h>\n#include <vespa\/storage\/distributor\/operations\/external\/getoperation.h>\n#include <vespa\/storage\/distributor\/operations\/external\/putoperation.h>\n#include <vespa\/storage\/distributor\/operations\/external\/read_for_write_visitor_operation.h>\n#include <vespa\/storage\/distributor\/operations\/external\/removelocationoperation.h>\n#include <vespa\/storage\/distributor\/operations\/external\/removeoperation.h>\n#include <vespa\/storage\/distributor\/operations\/external\/statbucketlistoperation.h>\n#include <vespa\/storage\/distributor\/operations\/external\/statbucketoperation.h>\n#include <vespa\/storage\/distributor\/operations\/external\/twophaseupdateoperation.h>\n#include <vespa\/storage\/distributor\/operations\/external\/updateoperation.h>\n#include <vespa\/storage\/distributor\/operations\/external\/visitoroperation.h>\n#include <vespa\/storageapi\/message\/persistence.h>\n#include <vespa\/storageapi\/message\/removelocation.h>\n#include <vespa\/storageapi\/message\/stat.h>\n\n#include <vespa\/log\/log.h>\n#include <vespa\/document\/bucket\/fixed_bucket_spaces.h>\n\nLOG_SETUP(\".distributor.manager\");\n\nnamespace storage::distributor {\n\nclass DirectDispatchSender : public DistributorMessageSender {\n    DistributorNodeContext& _node_ctx;\n    NonTrackingMessageSender& _msg_sender;\npublic:\n    DirectDispatchSender(DistributorNodeContext& node_ctx,\n                         NonTrackingMessageSender& msg_sender)\n        : _node_ctx(node_ctx),\n          _msg_sender(msg_sender)\n    {}\n    ~DirectDispatchSender() override = default;\n\n    void sendCommand(const std::shared_ptr<api::StorageCommand>& cmd) override {\n        _msg_sender.send_up_without_tracking(cmd);\n    }\n    void sendReply(const std::shared_ptr<api::StorageReply>& reply) override {\n        _msg_sender.send_up_without_tracking(reply);\n    }\n    int getDistributorIndex() const override {\n        return _node_ctx.node_index();\n    }\n    const ClusterContext & cluster_context() const override {\n        return _node_ctx;\n    }\n    const PendingMessageTracker& getPendingMessageTracker() const override {\n        abort(); \/\/ Never called by the messages using this component.\n    }\n    const OperationSequencer& operation_sequencer() const noexcept override {\n        abort(); \/\/ Never called by the messages using this component.\n    }\n};\n\nExternalOperationHandler::ExternalOperationHandler(DistributorNodeContext& node_ctx,\n                                                   DistributorOperationContext& op_ctx,\n                                                   DistributorMetricSet& metrics,\n                                                   ChainedMessageSender& msg_sender,\n                                                   OperationSequencer& operation_sequencer,\n                                                   NonTrackingMessageSender& non_tracking_sender,\n                                                   DocumentSelectionParser& parser,\n                                                   const MaintenanceOperationGenerator& gen,\n                                                   OperationOwner& operation_owner)\n    : _node_ctx(node_ctx),\n      _op_ctx(op_ctx),\n      _metrics(metrics),\n      _msg_sender(msg_sender),\n      _operation_sequencer(operation_sequencer),\n      _parser(parser),\n      _direct_dispatch_sender(std::make_unique<DirectDispatchSender>(node_ctx, non_tracking_sender)),\n      _operationGenerator(gen),\n      _rejectFeedBeforeTimeReached(), \/\/ At epoch\n      _distributor_operation_owner(operation_owner),\n      _non_main_thread_ops_mutex(),\n      _non_main_thread_ops_owner(*_direct_dispatch_sender, _node_ctx.clock()),\n      _uuid_generator(std::make_unique<CryptoUuidGenerator>()),\n      _concurrent_gets_enabled(false),\n      _use_weak_internal_read_consistency_for_gets(false)\n{\n}\n\nExternalOperationHandler::~ExternalOperationHandler() = default;\n\nbool\nExternalOperationHandler::handleMessage(const std::shared_ptr<api::StorageMessage>& msg, Operation::SP& op)\n{\n    _op = Operation::SP();\n    bool retVal = msg->callHandler(*this, msg);\n    op = _op;\n    return retVal;\n}\n\nvoid ExternalOperationHandler::close_pending() {\n    std::lock_guard g(_non_main_thread_ops_mutex);\n    \/\/ Make sure we drain any pending operations upon close.\n    _non_main_thread_ops_owner.onClose();\n}\n\napi::ReturnCode\nExternalOperationHandler::makeSafeTimeRejectionResult(TimePoint unsafeTime)\n{\n    std::ostringstream ss;\n    auto now_sec(std::chrono::duration_cast<std::chrono::seconds>(unsafeTime.time_since_epoch()));\n    auto future_sec(std::chrono::duration_cast<std::chrono::seconds>(_rejectFeedBeforeTimeReached.time_since_epoch()));\n    ss << \"Operation received at time \" << now_sec.count()\n       << \", which is before bucket ownership transfer safe time of \"\n       << future_sec.count();\n    return api::ReturnCode(api::ReturnCode::STALE_TIMESTAMP, ss.str());\n}\n\nbool\nExternalOperationHandler::checkSafeTimeReached(api::StorageCommand& cmd)\n{\n    const auto now = TimePoint(std::chrono::seconds(_node_ctx.clock().getTimeInSeconds().getTime()));\n    if (now < _rejectFeedBeforeTimeReached) {\n        api::StorageReply::UP reply(cmd.makeReply());\n        reply->setResult(makeSafeTimeRejectionResult(now));\n        _msg_sender.sendUp(std::shared_ptr<api::StorageMessage>(reply.release()));\n        return false;\n    }\n    return true;\n}\n\nvoid ExternalOperationHandler::bounce_with_result(api::StorageCommand& cmd, const api::ReturnCode& result) {\n    api::StorageReply::UP reply(cmd.makeReply());\n    reply->setResult(result);\n    _msg_sender.sendUp(std::shared_ptr<api::StorageMessage>(reply.release()));\n}\n\nvoid ExternalOperationHandler::bounce_with_feed_blocked(api::StorageCommand& cmd) {\n    const auto& feed_block = _op_ctx.cluster_state_bundle().feed_block();\n    bounce_with_result(cmd, api::ReturnCode(api::ReturnCode::NO_SPACE,\n                                            \"External feed is blocked due to resource exhaustion: \" +\n                                                    feed_block->description()));\n}\n\nvoid ExternalOperationHandler::bounce_with_wrong_distribution(api::StorageCommand& cmd,\n                                                              const lib::ClusterState& cluster_state)\n{\n    \/\/ Distributor ownership is equal across bucket spaces, so always send back default space state.\n    \/\/ This also helps client avoid getting confused by possibly observing different actual\n    \/\/ (derived) state strings for global\/non-global document types for the same state version.\n    \/\/ Similarly, if we've yet to activate any version at all we send back BUSY instead\n    \/\/ of a suspiciously empty WrongDistributionReply.\n    \/\/ TOOD consider NOT_READY instead of BUSY once we're sure this won't cause any other issues.\n    if (cluster_state.getVersion() != 0) {\n        auto cluster_state_str = cluster_state.toString();\n        LOG(debug, \"Got %s with wrong distribution, sending back state '%s'\",\n            cmd.toString().c_str(), cluster_state_str.c_str());\n        bounce_with_result(cmd, api::ReturnCode(api::ReturnCode::WRONG_DISTRIBUTION, cluster_state_str));\n    } else { \/\/ Only valid for empty startup state\n        LOG(debug, \"Got %s with wrong distribution, but no cluster state activated yet. Sending back BUSY\",\n            cmd.toString().c_str());\n        bounce_with_result(cmd, api::ReturnCode(api::ReturnCode::BUSY, \"No cluster state activated yet\"));\n    }\n}\n\nvoid ExternalOperationHandler::bounce_with_wrong_distribution(api::StorageCommand& cmd) {\n    const auto& cluster_state = _op_ctx.bucket_space_repo().get(document::FixedBucketSpaces::default_space()).getClusterState();\n    bounce_with_wrong_distribution(cmd, cluster_state);\n}\n\nvoid ExternalOperationHandler::bounce_with_busy_during_state_transition(\n        api::StorageCommand& cmd,\n        const lib::ClusterState& current_state,\n        const lib::ClusterState& pending_state)\n{\n    auto status_str = vespalib::make_string(\"Currently pending cluster state transition\"\n                                            \" from version %u to %u\",\n                                            current_state.getVersion(), pending_state.getVersion());\n\n    api::StorageReply::UP reply(cmd.makeReply());\n    api::ReturnCode ret(api::ReturnCode::BUSY, status_str);\n    reply->setResult(ret);\n    _msg_sender.sendUp(std::shared_ptr<api::StorageMessage>(reply.release()));\n}\n\nbool\nExternalOperationHandler::checkTimestampMutationPreconditions(api::StorageCommand& cmd,\n                                                              const document::BucketId &bucketId,\n                                                              PersistenceOperationMetricSet& persistenceMetrics)\n{\n    auto &bucket_space(_op_ctx.bucket_space_repo().get(cmd.getBucket().getBucketSpace()));\n    auto bucket_ownership_flags = bucket_space.get_bucket_ownership_flags(bucketId);\n    if (!bucket_ownership_flags.owned_in_current_state()) {\n        document::Bucket bucket(cmd.getBucket().getBucketSpace(), bucketId);\n        LOG(debug, \"Distributor manager received %s, bucket %s with wrong distribution\",\n            cmd.toString().c_str(), bucket.toString().c_str());\n        bounce_with_wrong_distribution(cmd);\n        persistenceMetrics.failures.wrongdistributor.inc();\n        return false;\n    }\n\n    if (!bucket_ownership_flags.owned_in_pending_state()) {\n        \/\/ We return BUSY here instead of WrongDistributionReply to avoid clients potentially\n        \/\/ ping-ponging between cluster state versions during a state transition.\n        auto& current_state = bucket_space.getClusterState();\n        auto& pending_state = bucket_space.get_pending_cluster_state();\n        bounce_with_busy_during_state_transition(cmd, current_state, pending_state);\n        return false;\n    }\n\n    if (!checkSafeTimeReached(cmd)) {\n        persistenceMetrics.failures.safe_time_not_reached.inc();\n        return false;\n    }\n    return true;\n}\n\nstd::shared_ptr<api::StorageMessage>\nExternalOperationHandler::makeConcurrentMutationRejectionReply(api::StorageCommand& cmd,\n                                                               const document::DocumentId& docId,\n                                                               PersistenceOperationMetricSet& persistenceMetrics) const\n{\n    auto err_msg = vespalib::make_string(\"A mutating operation for document '%s' is already in progress\",\n                                         docId.toString().c_str());\n    LOG(debug, \"Aborting incoming %s operation: %s\", cmd.getType().toString().c_str(), err_msg.c_str());\n    persistenceMetrics.failures.concurrent_mutations.inc();\n    api::StorageReply::UP reply(cmd.makeReply());\n    reply->setResult(api::ReturnCode(api::ReturnCode::BUSY, err_msg));\n    return std::shared_ptr<api::StorageMessage>(reply.release());\n}\n\nbool ExternalOperationHandler::allowMutation(const SequencingHandle& handle) const {\n    const auto& config(_op_ctx.distributor_config());\n    if (!config.getSequenceMutatingOperations()) {\n        \/\/ Sequencing explicitly disabled, so always allow.\n        return true;\n    }\n    return handle.valid();\n}\n\ntemplate <typename Func>\nvoid ExternalOperationHandler::bounce_or_invoke_read_only_op(\n        api::StorageCommand& cmd,\n        const document::Bucket& bucket,\n        PersistenceOperationMetricSet& metrics,\n        Func func)\n{\n    auto &bucket_space(_op_ctx.bucket_space_repo().get(bucket.getBucketSpace()));\n    auto bucket_ownership_flags = bucket_space.get_bucket_ownership_flags(bucket.getBucketId());\n    if (!bucket_ownership_flags.owned_in_current_state()) {\n        LOG(debug, \"Distributor manager received %s, bucket %s with wrong distribution\",\n            cmd.toString().c_str(), bucket.toString().c_str());\n        bounce_with_wrong_distribution(cmd);\n        metrics.failures.wrongdistributor.inc();\n        return;\n    }\n\n    if (bucket_ownership_flags.owned_in_pending_state()) {\n        func(_op_ctx.bucket_space_repo());\n    } else {\n        if (_op_ctx.distributor_config().allowStaleReadsDuringClusterStateTransitions()) {\n            func(_op_ctx.read_only_bucket_space_repo());\n        } else {\n            auto& current_state = bucket_space.getClusterState();\n            auto& pending_state = bucket_space.get_pending_cluster_state();\n            bounce_with_busy_during_state_transition(cmd, current_state, pending_state);\n        }\n    }\n}\n\nnamespace {\n\nbool put_is_from_reindexing_visitor(const api::PutCommand& cmd) {\n    const auto& tas_cond = cmd.getCondition();\n    return (tas_cond.isPresent() && (tas_cond.getSelection().starts_with(reindexing_bucket_lock_bypass_prefix())));\n}\n\n\/\/ Precondition: put_is_from_reindexing_visitor(cmd) == true\nstd::string extract_reindexing_token(const api::PutCommand& cmd) {\n    const std::string& tas_str = cmd.getCondition().getSelection();\n    auto eq_idx = tas_str.find_first_of('=');\n    if (eq_idx != std::string::npos) {\n        return tas_str.substr(eq_idx + 1);\n    }\n    return \"\";\n}\n\n}\n\nbool ExternalOperationHandler::onPut(const std::shared_ptr<api::PutCommand>& cmd) {\n    if (_op_ctx.cluster_state_bundle().block_feed_in_cluster()) {\n        bounce_with_feed_blocked(*cmd);\n        return true;\n    }\n\n    auto& metrics = getMetrics().puts;\n    if (!checkTimestampMutationPreconditions(*cmd, _op_ctx.make_split_bit_constrained_bucket_id(cmd->getDocumentId()), metrics)) {\n        return true;\n    }\n\n    if (cmd->getTimestamp() == 0) {\n        cmd->setTimestamp(_op_ctx.generate_unique_timestamp());\n    }\n\n    const auto bucket_space = cmd->getBucket().getBucketSpace();\n    auto handle = _operation_sequencer.try_acquire(bucket_space, cmd->getDocumentId());\n    bool allow = allowMutation(handle);\n    if (put_is_from_reindexing_visitor(*cmd)) {\n        auto expect_token = extract_reindexing_token(*cmd);\n        if (!allow && handle.is_blocked_by_bucket()) {\n            if (handle.is_bucket_blocked_with_token(expect_token)) {\n                cmd->setCondition(documentapi::TestAndSetCondition()); \/\/ Must clear TaS or the backend will reject the op\n                allow = true;\n            } else {\n                bounce_with_result(*cmd, api::ReturnCode(api::ReturnCode::TEST_AND_SET_CONDITION_FAILED,\n                                                         \"Expected bucket lock token did not match actual lock token\"));\n                return true;\n            }\n        } else {\n            bounce_with_result(*cmd, api::ReturnCode(api::ReturnCode::TEST_AND_SET_CONDITION_FAILED,\n                                                     \"Operation expects a read-for-write bucket lock to be present, \"\n                                                     \"but none currently exists\"));\n            return true;\n        }\n    }\n    if (allow) {\n        _op = std::make_shared<PutOperation>(_node_ctx, _op_ctx,\n                                             _op_ctx.bucket_space_repo().get(bucket_space),\n                                             std::move(cmd), getMetrics().puts, std::move(handle));\n    } else {\n        _msg_sender.sendUp(makeConcurrentMutationRejectionReply(*cmd, cmd->getDocumentId(), metrics));\n    }\n\n    return true;\n}\n\n\nbool ExternalOperationHandler::onUpdate(const std::shared_ptr<api::UpdateCommand>& cmd) {\n    if (_op_ctx.cluster_state_bundle().block_feed_in_cluster() &&\n            document::FeedRejectHelper::mustReject(*cmd->getUpdate()))\n    {\n        bounce_with_feed_blocked(*cmd);\n        return true;\n    }\n\n    auto& metrics = getMetrics().updates;\n    if (!checkTimestampMutationPreconditions(*cmd, _op_ctx.make_split_bit_constrained_bucket_id(cmd->getDocumentId()), metrics)) {\n        return true;\n    }\n\n    if (cmd->getTimestamp() == 0) {\n        cmd->setTimestamp(_op_ctx.generate_unique_timestamp());\n    }\n    const auto bucket_space = cmd->getBucket().getBucketSpace();\n    auto handle = _operation_sequencer.try_acquire(bucket_space, cmd->getDocumentId());\n    if (allowMutation(handle)) {\n        _op = std::make_shared<TwoPhaseUpdateOperation>(_node_ctx, _op_ctx, _parser,\n                                                        _op_ctx.bucket_space_repo().get(bucket_space),\n                                                        std::move(cmd), getMetrics(), std::move(handle));\n    } else {\n        _msg_sender.sendUp(makeConcurrentMutationRejectionReply(*cmd, cmd->getDocumentId(), metrics));\n    }\n\n    return true;\n}\n\n\nbool ExternalOperationHandler::onRemove(const std::shared_ptr<api::RemoveCommand>& cmd) {\n    auto& metrics = getMetrics().removes;\n    if (!checkTimestampMutationPreconditions(*cmd, _op_ctx.make_split_bit_constrained_bucket_id(cmd->getDocumentId()), metrics)) {\n        return true;\n    }\n\n    if (cmd->getTimestamp() == 0) {\n        cmd->setTimestamp(_op_ctx.generate_unique_timestamp());\n    }\n    const auto bucket_space = cmd->getBucket().getBucketSpace();\n    auto handle = _operation_sequencer.try_acquire(bucket_space, cmd->getDocumentId());\n    if (allowMutation(handle)) {\n        auto &distributorBucketSpace(_op_ctx.bucket_space_repo().get(bucket_space));\n\n        _op = std::make_shared<RemoveOperation>(_node_ctx, _op_ctx, distributorBucketSpace, std::move(cmd),\n                                                getMetrics().removes, std::move(handle));\n    } else {\n        _msg_sender.sendUp(makeConcurrentMutationRejectionReply(*cmd, cmd->getDocumentId(), metrics));\n    }\n\n    return true;\n}\n\nbool ExternalOperationHandler::onRemoveLocation(const std::shared_ptr<api::RemoveLocationCommand>& cmd) {\n    document::BucketId bid;\n    RemoveLocationOperation::getBucketId(_node_ctx, _parser, *cmd, bid);\n    document::Bucket bucket(cmd->getBucket().getBucketSpace(), bid);\n\n    auto& metrics = getMetrics().removelocations;\n    if (!checkTimestampMutationPreconditions(*cmd, bucket.getBucketId(), metrics)) {\n        return true;\n    }\n\n    _op = std::make_shared<RemoveLocationOperation>(_node_ctx, _op_ctx, _parser,\n                                                    _op_ctx.bucket_space_repo().get(cmd->getBucket().getBucketSpace()),\n                                                    std::move(cmd), getMetrics().removelocations);\n    return true;\n}\n\napi::InternalReadConsistency ExternalOperationHandler::desired_get_read_consistency() const noexcept {\n    return (use_weak_internal_read_consistency_for_gets()\n            ? api::InternalReadConsistency::Weak\n            : api::InternalReadConsistency::Strong);\n}\n\nstd::shared_ptr<Operation> ExternalOperationHandler::try_generate_get_operation(const std::shared_ptr<api::GetCommand>& cmd) {\n    document::Bucket bucket(cmd->getBucket().getBucketSpace(), _op_ctx.make_split_bit_constrained_bucket_id(cmd->getDocumentId()));\n    auto& metrics = getMetrics().gets;\n    auto snapshot = _op_ctx.read_snapshot_for_bucket(bucket);\n    if (!snapshot.is_routable()) {\n        const auto& ctx = snapshot.context();\n        if (ctx.has_pending_state_transition()) {\n            bounce_with_busy_during_state_transition(*cmd, *ctx.default_active_cluster_state(),\n                                                     *ctx.pending_cluster_state());\n        } else {\n            bounce_with_wrong_distribution(*cmd, *snapshot.context().default_active_cluster_state());\n            metrics.locked()->failures.wrongdistributor.inc();\n        }\n        return std::shared_ptr<Operation>();\n    }\n    \/\/ The snapshot is aware of whether stale reads are enabled, so we don't have to check that here.\n    const auto* space_repo = snapshot.bucket_space_repo();\n    assert(space_repo != nullptr);\n    return std::make_shared<GetOperation>(_node_ctx, space_repo->get(bucket.getBucketSpace()),\n                                          snapshot.steal_read_guard(), cmd, metrics,\n                                          desired_get_read_consistency());\n}\n\nbool ExternalOperationHandler::onGet(const std::shared_ptr<api::GetCommand>& cmd) {\n    _op = try_generate_get_operation(cmd);\n    return true;\n}\n\nbool ExternalOperationHandler::onStatBucket(const std::shared_ptr<api::StatBucketCommand>& cmd) {\n    auto& metrics = getMetrics().stats;\n    bounce_or_invoke_read_only_op(*cmd, cmd->getBucket(), metrics, [&](auto& bucket_space_repo) {\n        auto& bucket_space = bucket_space_repo.get(cmd->getBucket().getBucketSpace());\n        _op = std::make_shared<StatBucketOperation>(bucket_space, cmd);\n    });\n    return true;\n}\n\nbool ExternalOperationHandler::onGetBucketList(const std::shared_ptr<api::GetBucketListCommand>& cmd) {\n    auto& metrics = getMetrics().getbucketlists;\n    bounce_or_invoke_read_only_op(*cmd, cmd->getBucket(), metrics, [&](auto& bucket_space_repo) {\n        auto& bucket_space = bucket_space_repo.get(cmd->getBucket().getBucketSpace());\n        auto& bucket_database = bucket_space.getBucketDatabase();\n        _op = std::make_shared<StatBucketListOperation>(bucket_database, _operationGenerator, _node_ctx.node_index(), cmd);\n    });\n    return true;\n}\n\nbool ExternalOperationHandler::onCreateVisitor(const std::shared_ptr<api::CreateVisitorCommand>& cmd) {\n    \/\/ TODO same handling as Gets (VisitorOperation needs to change)\n    const auto& config(_op_ctx.distributor_config());\n    VisitorOperation::Config visitorConfig(config.getMinBucketsPerVisitor(), config.getMaxVisitorsPerNodePerClientVisitor());\n    auto &distributorBucketSpace(_op_ctx.bucket_space_repo().get(cmd->getBucket().getBucketSpace()));\n    auto visit_op = std::make_shared<VisitorOperation>(_node_ctx, _op_ctx, distributorBucketSpace, cmd, visitorConfig, getMetrics().visits);\n    if (visit_op->is_read_for_write()) {\n        _op = std::make_shared<ReadForWriteVisitorOperationStarter>(std::move(visit_op), _operation_sequencer,\n                                                                    _distributor_operation_owner,\n                                                                    _op_ctx.pending_message_tracker(),\n                                                                    *_uuid_generator);\n    } else {\n        _op = std::move(visit_op);\n    }\n    return true;\n}\n\nbool ExternalOperationHandler::try_handle_message_outside_main_thread(const std::shared_ptr<api::StorageMessage>& msg) {\n    const auto type_id = msg->getType().getId();\n    if (type_id == api::MessageType::GET_ID) {\n        \/\/ Only do this check for Get _requests_ to avoid the following case:\n        \/\/  1) Stale reads are initially enabled and a Get request is received\n        \/\/  2) A Get is sent to the content node(s)\n        \/\/  3) Stale reads are disabled via config\n        \/\/  4) Get-reply from content node is disregarded since concurrent reads are no longer allowed\n        \/\/  5) We've effectively leaked a Get operation, and the client will time out\n        \/\/ TODO consider having stale reads _not_ be a live config instead!\n        if (!concurrent_gets_enabled()) {\n            return false;\n        }\n        auto op = try_generate_get_operation(std::dynamic_pointer_cast<api::GetCommand>(msg));\n        if (op) {\n            std::lock_guard g(_non_main_thread_ops_mutex);\n            _non_main_thread_ops_owner.start(std::move(op), msg->getPriority());\n        }\n        return true;\n    } else if (type_id == api::MessageType::GET_REPLY_ID) {\n        std::lock_guard g(_non_main_thread_ops_mutex);\n        \/\/ The Get for which this reply was created may have been sent by someone outside\n        \/\/ the ExternalOperationHandler, such as TwoPhaseUpdateOperation. Pass it on if so.\n        \/\/ It is undefined which thread actually invokes this, so mutex protection of reply\n        \/\/ handling is crucial!\n        return _non_main_thread_ops_owner.handleReply(std::dynamic_pointer_cast<api::StorageReply>(msg));\n    }\n    return false;\n}\n\n}\n","avg_line_length":47.3450980392,"max_line_length":140,"alphanum_fraction":0.6745216599,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":46421,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/***\n* Copyright (C) Microsoft. All rights reserved.\n* Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n*\n* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n*\n* HTTP Library: HTTP listener (server-side) APIs\n*\n* This file contains implementation built on Windows HTTP Server APIs.\n*\n* For the latest on this and related APIs, please see: https:\/\/github.com\/Microsoft\/cpprestsdk\n*\n* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n****\/\n\n#include \"stdafx.h\"\n\n#if _WIN32_WINNT >= _WIN32_WINNT_VISTA\n\n#pragma comment(lib, \"Ws2_32\")\n\n#include \"http_server_httpsys.h\"\n#include \"http_server_impl.h\"\n\nusing namespace web;\nusing namespace utility;\nusing namespace concurrency;\nusing namespace utility::conversions;\nusing namespace http::details;\nusing namespace http::experimental::listener;\nusing namespace http::experimental::details;\n\n#define CHUNK_SIZE 64 * 1024\n\nnamespace web\n{\nnamespace http\n{\nnamespace experimental\n{\nnamespace details\n{\n\n\/\/\/ <summary>\n\/\/\/ String values for all HTTP Server API known headers.\n\/\/\/ NOTE: the order here is important it is from the _HTTP_HEADER_ID enum.\n\/\/\/ <\/summary>\nstatic utility::string_t HttpServerAPIKnownHeaders[] =\n{\n    U(\"Cache-Control\"),\n    U(\"Connection\"),\n    U(\"Data\"),\n    U(\"Keep-Alive\"),\n    U(\"Pragma\"),\n    U(\"Trailer\"),\n    U(\"Transfer-Encoding\"),\n    U(\"Upgrade\"),\n    U(\"Via\"),\n    U(\"Warning\"),\n    U(\"Allow\"),\n    U(\"Content-Length\"),\n    U(\"Content-Type\"),\n    U(\"Content-Encoding\"),\n    U(\"Content-Language\"),\n    U(\"Content-Location\"),\n    U(\"Content-Md5\"),\n    U(\"Content-Range\"),\n    U(\"Expires\"),\n    U(\"Last-Modified\"),\n    U(\"Accept\"),\n    U(\"Accept-Charset\"),\n    U(\"Accept-Encoding\"),\n    U(\"Accept-Language\"),\n    U(\"Authorization\"),\n    U(\"Cookie\"),\n    U(\"Expect\"),\n    U(\"From\"),\n    U(\"Host\"),\n    U(\"If-Match\"),\n    U(\"If-Modified-Since\"),\n    U(\"If-None-Match\"),\n    U(\"If-Range\"),\n    U(\"If-Unmodified-Since\"),\n    U(\"Max-Forwards\"),\n    U(\"Proxy-Authorization\"),\n    U(\"Referer\"),\n    U(\"Range\"),\n    U(\"TE\"),\n    U(\"Translate\"),\n    U(\"User-Agent\"),\n    U(\"Request-Maximum\"),\n    U(\"Accept-Ranges\"),\n    U(\"Age\"),\n    U(\"Etag\"),\n    U(\"Location\"),\n    U(\"Proxy-Authenticate\"),\n    U(\"Retry-After\"),\n    U(\"Server\"),\n    U(\"Set-Cookie\"),\n    U(\"Vary\"),\n    U(\"Www-Authenticate\"),\n    U(\"Response-Maximum\")\n};\n\nstatic void char_to_wstring(utf16string &dest, const char * src)\n{\n    dest = utility::conversions::to_utf16string(std::string(src));\n}\n\nhttp::method parse_request_method(const HTTP_REQUEST *p_request)\n{\n    http::method method;\n\n    switch(p_request->Verb)\n    {\n    case HttpVerbGET:\n        method = methods::GET;\n        break;\n    case HttpVerbPOST:\n        method = methods::POST;\n        break;\n    case HttpVerbPUT:\n        method = methods::PUT;\n        break;\n    case HttpVerbDELETE:\n        method = methods::DEL;\n        break;\n    case HttpVerbHEAD:\n        method = methods::HEAD;\n        break;\n    case HttpVerbOPTIONS:\n        method = methods::OPTIONS;\n        break;\n    case HttpVerbTRACE:\n        method = methods::TRCE;\n        break;\n    case HttpVerbCONNECT:\n        method = methods::CONNECT;\n        break;\n    case HttpVerbUnknown:\n        char_to_wstring(method, p_request->pUnknownVerb);\n        break;\n    case HttpVerbMOVE:\n        method = _XPLATSTR(\"MOVE\");\n        break;\n    case HttpVerbCOPY:\n        method = _XPLATSTR(\"COPY\");\n        break;\n    case HttpVerbPROPFIND:\n        method = _XPLATSTR(\"PROPFIND\");\n        break;\n    case HttpVerbPROPPATCH:\n        method = _XPLATSTR(\"PROPPATCH\");\n        break;\n    case HttpVerbMKCOL:\n        method = _XPLATSTR(\"MKCOL\");\n        break;\n    case HttpVerbLOCK:\n        method = _XPLATSTR(\"LOCK\");\n        break;\n    case HttpVerbUNLOCK:\n        method = _XPLATSTR(\"UNLOCK\");\n        break;\n    case HttpVerbSEARCH:\n        method = _XPLATSTR(\"SEARCH\");\n        break;\n    default:\n        break;\n    }\n    return method;\n}\n\nvoid parse_http_headers(const HTTP_REQUEST_HEADERS &headers, http::http_headers & msgHeaders)\n{\n    \/\/\n    \/\/ This is weird for the 'KnownHeaders' but there is no way I can find with the HTTP Server API\n    \/\/ to get all the raw headers. The known ones are stored in an array index by a HTTP Server API\n    \/\/ enumeration.\n    \/\/\n    \/\/ TFS 354587 As a perf optimization we could parse the headers from Windows on demand in the\n    \/\/      http_header class itself.\n    for(USHORT i = 0; i < headers.UnknownHeaderCount; ++i)\n    {\n        utf16string unknown_header_name;\n        char_to_wstring(unknown_header_name, headers.pUnknownHeaders[i].pName);\n\n        \/\/ header value can be empty\n        if(headers.pUnknownHeaders[i].RawValueLength > 0)\n        {\n            msgHeaders.add(unknown_header_name, utility::conversions::to_utf16string(headers.pUnknownHeaders[i].pRawValue));\n        }\n        else\n        {\n            msgHeaders[unknown_header_name] = U(\"\");\n        }\n    }\n    for(int i = 0; i < HttpHeaderMaximum; ++i)\n    {\n        if(headers.KnownHeaders[i].RawValueLength > 0)\n        {\n            msgHeaders.add(HttpServerAPIKnownHeaders[i], utility::conversions::to_utf16string(headers.KnownHeaders[i].pRawValue));\n        }\n    }\n}\n\nhttp_windows_server::http_windows_server()\n{\n    HTTPAPI_VERSION httpApiVersion = HTTPAPI_VERSION_2;\n    HttpInitialize(httpApiVersion, HTTP_INITIALIZE_SERVER, NULL);\n}\n\nhttp_windows_server::~http_windows_server()\n{\n    HttpTerminate(HTTP_INITIALIZE_SERVER, NULL);\n}\n\npplx::task<void> http_windows_server::register_listener(_In_ web::http::experimental::listener::details::http_listener_impl *pListener)\n{\n    unsigned long errorCode;\n\n    \/\/ Create a url group for this listener.\n    HTTP_URL_GROUP_ID urlGroupId;\n    errorCode = HttpCreateUrlGroup(m_serverSessionId, &urlGroupId, 0);\n    if(errorCode != NO_ERROR)\n    {\n        return pplx::task_from_exception<void>(http_exception(errorCode));\n    }\n\n    \/\/ Add listener's URI to the new group.\n    http::uri u = pListener->uri();\n    if (u.is_port_default())\n    {\n        \/\/ Windows HTTP Server API has issues when the port isn't set to 80 here -- it expects a url prefix string\n        \/\/ which always includes the port number\n        \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/aa364698(v=vs.85).aspx\n        http::uri_builder builder(u);\n        builder.set_port(80);\n        u = builder.to_uri();\n    }\n\n    \/\/ Windows HTTP Server API will not accept a uri with an empty path, it must have a '\/'.\n    \/\/ Windows HTTP Server API will only accept decoded uri strings.\n    utility::string_t host_uri = http::uri::decode(u.to_string());\n    if(host_uri.back() != U('\/') && u.query().empty() && u.fragment().empty())\n    {\n        host_uri.append(U(\"\/\"));\n    }\n\n    \/\/ inside here we check for a few specific error types that know about\n    \/\/ there may be more possibilities for windows to return a different error\n    errorCode = HttpAddUrlToUrlGroup(urlGroupId, host_uri.c_str(), (HTTP_URL_CONTEXT)pListener, 0);\n    if(errorCode)\n    {\n        HttpCloseUrlGroup(urlGroupId);\n        utility::stringstream_t os;\n        os.imbue(std::locale::classic());\n\n        if(errorCode == ERROR_ALREADY_EXISTS || errorCode == ERROR_SHARING_VIOLATION)\n        {\n            os << _XPLATSTR(\"Address '\") << pListener->uri().to_string() << _XPLATSTR(\"' is already in use\");\n            return pplx::task_from_exception<void>(http_exception(errorCode, os.str()));\n        }\n        else if (errorCode == ERROR_ACCESS_DENIED)\n        {\n            os << _XPLATSTR(\"Access denied: attempting to add Address '\") << pListener->uri().to_string() << _XPLATSTR(\"'. \");\n            os << _XPLATSTR(\"Run as administrator to listen on an hostname other than localhost, or to listen on port 80.\");\n            return pplx::task_from_exception<void>(http_exception(errorCode, os.str()));\n        }\n        else\n        {\n            return pplx::task_from_exception<void>(http_exception(errorCode, _XPLATSTR(\"Error adding url to url group\")));\n        }\n    }\n\n    \/\/ Set timeouts.\n    HTTP_TIMEOUT_LIMIT_INFO timeouts;\n    const USHORT secs = static_cast<USHORT>(pListener->configuration().timeout().count());\n    timeouts.EntityBody = secs;\n    timeouts.DrainEntityBody = secs;\n    timeouts.RequestQueue = secs;\n    timeouts.IdleConnection = secs;\n    timeouts.HeaderWait = secs;\n    timeouts.Flags.Present = 1;\n    errorCode = HttpSetUrlGroupProperty(\n        urlGroupId,\n        HttpServerTimeoutsProperty,\n        &timeouts,\n        sizeof(HTTP_TIMEOUT_LIMIT_INFO));\n    if(errorCode)\n    {\n        HttpCloseUrlGroup(urlGroupId);\n        return pplx::task_from_exception<void>(http_exception(errorCode));\n    }\n\n    \/\/ Add listener registration.\n    {\n        pplx::extensibility::scoped_rw_lock_t lock(_M_listenersLock);\n        if(_M_registeredListeners.find(pListener) != _M_registeredListeners.end())\n        {\n            HttpCloseUrlGroup(urlGroupId);\n            throw std::invalid_argument(\"Error: http_listener is already registered\");\n        }\n        _M_registeredListeners[pListener] = std::unique_ptr<listener_registration>(new listener_registration(urlGroupId));\n    }\n\n    \/\/ Associate Url group with request queue.\n    HTTP_BINDING_INFO bindingInfo;\n    bindingInfo.RequestQueueHandle = m_hRequestQueue;\n    bindingInfo.Flags.Present = 1;\n    errorCode = HttpSetUrlGroupProperty(\n        urlGroupId,\n        HttpServerBindingProperty,\n        &bindingInfo,\n        sizeof(HTTP_BINDING_INFO));\n    if(errorCode)\n    {\n        HttpCloseUrlGroup(urlGroupId);\n        return pplx::task_from_exception<void>(http_exception(errorCode));\n    }\n\n    return pplx::task_from_result();\n}\n\npplx::task<void> http_windows_server::unregister_listener(_In_ web::http::experimental::listener::details::http_listener_impl *pListener)\n{\n    return pplx::create_task([=]()\n    {\n        \/\/ First remove listener registration.\n        std::unique_ptr<listener_registration> registration;\n        {\n            pplx::extensibility::scoped_rw_lock_t lock(_M_listenersLock);\n            registration = std::move(_M_registeredListeners[pListener]);\n            _M_registeredListeners[pListener] = nullptr;\n            _M_registeredListeners.erase(pListener);\n        }\n\n        \/\/ Then take the listener write lock to make sure there are no calls into the listener's\n        \/\/ request handler.\n        {\n            pplx::extensibility::scoped_rw_lock_t lock(registration->m_requestHandlerLock);\n        }\n\n        \/\/ Next close Url group, no need to remove individual Urls.\n        const unsigned long error_code = HttpCloseUrlGroup(registration->m_urlGroupId);\n        if (error_code != NO_ERROR)\n        {\n            throw http_exception(error_code);\n        }\n    });\n}\n\npplx::task<void> http_windows_server::start()\n{\n    \/\/ Initialize data.\n    m_serverSessionId = 0;\n    m_hRequestQueue = nullptr;\n    m_threadpool_io = nullptr;\n    m_numOutstandingRequests = 0;\n    m_zeroOutstandingRequests.set();\n\n    \/\/ Open server session.\n    HTTPAPI_VERSION httpApiVersion = HTTPAPI_VERSION_2;\n    ULONG errorCode = HttpCreateServerSession(httpApiVersion, &m_serverSessionId, 0);\n    if(errorCode)\n    {\n        return pplx::task_from_exception<void>(http_exception(errorCode));\n    }\n\n    \/\/ Create request queue.\n    errorCode = HttpCreateRequestQueue(httpApiVersion, NULL, NULL, NULL, &m_hRequestQueue);\n    if(errorCode)\n    {\n        return pplx::task_from_exception<void>(http_exception(errorCode));\n    }\n\n    \/\/ Create and start ThreadPool I\/O so we can process asynchronous I\/O.\n    m_threadpool_io = CreateThreadpoolIo(m_hRequestQueue, &http_overlapped::io_completion_callback, NULL, NULL);\n    if(m_threadpool_io == nullptr)\n    {\n        return pplx::task_from_exception<void>(http_exception(errorCode));\n    }\n\n    \/\/ Start request receiving task.\n    m_receivingTask = pplx::create_task([this]() { receive_requests(); });\n\n    return pplx::task_from_result();\n}\n\npplx::task<void> http_windows_server::stop()\n{\n    \/\/ Shutdown request queue.\n    if(m_hRequestQueue != nullptr)\n    {\n        HttpShutdownRequestQueue(m_hRequestQueue);\n        m_receivingTask.wait();\n\n        \/\/ Wait for all requests to be finished processing.\n        m_zeroOutstandingRequests.wait();\n\n        HttpCloseRequestQueue(m_hRequestQueue);\n    }\n\n    \/\/ Release resources.\n    if(m_serverSessionId != 0)\n    {\n        HttpCloseServerSession(m_serverSessionId);\n    }\n    if(m_threadpool_io != nullptr)\n    {\n        CloseThreadpoolIo(m_threadpool_io);\n        m_threadpool_io = nullptr;\n    }\n\n    return pplx::task_from_result();\n}\n\nvoid http_windows_server::receive_requests()\n{\n    HTTP_REQUEST p_request;\n    ULONG bytes_received;\n\n    \/\/ Oversubscribe since this is a blocking call and we don't want to count\n    \/\/ towards the concurrency runtime's thread count. A more proper fix\n    \/\/ would be to use Overlapped I\/O and asynchronously call HttpReceiveHttpRequest.\n    \/\/ This requires additional work to be careful sychronizing with the listener\n    \/\/ shutdown. This is much easier especially given the http_listener is 'experimental'\n    \/\/ and with VS2015 PPL tasks run on the threadpool.\n#if _MSC_VER < 1900\n    concurrency::Context::Oversubscribe(true);\n#endif\n    for (;;)\n    {\n        unsigned long error_code = HttpReceiveHttpRequest(\n            m_hRequestQueue,\n            HTTP_NULL_ID,\n            0,\n            &p_request,\n            sizeof(HTTP_REQUEST),\n            &bytes_received,\n            0);\n\n        if (error_code != NO_ERROR && error_code != ERROR_MORE_DATA)\n        {\n            break;\n        }\n\n        \/\/ Start processing the request\n        auto pContext = new windows_request_context();\n        auto pRequestContext = std::unique_ptr<_http_server_context>(pContext);\n        http_request msg = http_request::_create_request(std::move(pRequestContext));\n        pContext->async_process_request(p_request.RequestId, msg, bytes_received);\n    }\n#if _MSC_VER < 1900\n    concurrency::Context::Oversubscribe(false);\n#endif\n}\n\npplx::task<void> http_windows_server::respond(http::http_response response)\n{\n    windows_request_context * p_context = static_cast<windows_request_context *>(response._get_server_context());\n    return pplx::create_task(p_context->m_response_completed);\n}\n\nwindows_request_context::windows_request_context()\n    : m_sending_in_chunks(false),\n      m_transfer_encoding(false),\n      m_remaining_to_write(0)\n{\n    auto *pServer = static_cast<http_windows_server *>(http_server_api::server_api());\n    if(++pServer->m_numOutstandingRequests == 1)\n    {\n        pServer->m_zeroOutstandingRequests.reset();\n    }\n}\n\nwindows_request_context::~windows_request_context()\n{\n    \/\/ Unfortunately have to work around a ppl task_completion_event bug that can cause AVs.\n    \/\/ Bug is that task_completion_event accesses internal state after setting.\n    \/\/ Workaround is to use a lock incurring additional synchronization, if can acquire\n    \/\/ the lock then setting of the event has completed.\n    std::lock_guard<std::mutex> lock(m_responseCompletedLock);\n\n    \/\/ Add a task-based continuation so no exceptions thrown from the task go 'unobserved'.\n    pplx::create_task(m_response_completed).then([](pplx::task<void> t)\n    {\n        try { t.wait(); } catch(...) {}\n    });\n\n    auto *pServer = static_cast<http_windows_server *>(http_server_api::server_api());\n    if(--pServer->m_numOutstandingRequests == 0)\n    {\n        pServer->m_zeroOutstandingRequests.set();\n    }\n}\n\nvoid windows_request_context::async_process_request(HTTP_REQUEST_ID request_id, http_request msg, const unsigned long headers_size)\n{\n    auto *pServer = static_cast<http_windows_server *>(http_server_api::server_api());\n    m_request_id = request_id;\n\n    \/\/ Save the http_request as the member of windows_request_context for the callback use.\n    m_msg = msg;\n\n    m_request_buffer = std::unique_ptr<unsigned char[]>(new unsigned char[msl::safeint3::SafeInt<unsigned long>(headers_size)]);\n    m_request = (HTTP_REQUEST *) m_request_buffer.get();\n\n    \/\/ The read_headers_io_completion callback function.\n    m_overlapped.set_http_io_completion([this](DWORD error, DWORD nBytes){ read_headers_io_completion(error, nBytes); });\n\n    StartThreadpoolIo(pServer->m_threadpool_io);\n\n    const unsigned long error_code = HttpReceiveHttpRequest(\n            pServer->m_hRequestQueue,\n            m_request_id,\n            0,\n            m_request,\n            headers_size,\n            NULL,\n            &m_overlapped);\n\n    if(error_code != NO_ERROR && error_code != ERROR_IO_PENDING)\n    {\n        CancelThreadpoolIo(pServer->m_threadpool_io);\n        m_msg.reply(status_codes::InternalError);\n        init_response_callbacks(ShouldWaitForBody::DontWait);\n    }\n}\n\n\/\/\/ <summary>\n\/\/\/  The read request headers completion callback function.\n\/\/\/ <\/summary>\nvoid windows_request_context::read_headers_io_completion(DWORD error_code, DWORD)\n{\n    if(error_code != NO_ERROR)\n    {\n        m_msg.reply(status_codes::InternalError);\n        init_response_callbacks(ShouldWaitForBody::DontWait);\n    }\n    else\n    {\n        utility::string_t header;\n        std::string badRequestMsg;\n        try\n        {\n            \/\/ HTTP_REQUEST::pRawUrl contains the raw URI that came across the wire.\n            \/\/ Use this instead since the CookedUrl is a mess of the URI components\n            \/\/ some encoded and some not.\n            m_msg.set_request_uri(utf8_to_utf16(m_request->pRawUrl));\n        }\n        catch(const uri_exception &e)\n        {\n            \/\/ If an exception occurred, finish processing the request below but\n            \/\/ respond with BadRequest instead of dispatching to the user's\n            \/\/ request handlers.\n            badRequestMsg = e.what();\n        }\n        m_msg.set_method(parse_request_method(m_request));\n        parse_http_headers(m_request->Headers, m_msg.headers());\n\n        \/\/ See if we need to compress or decompress the incoming request body, and if so, prepare for it\n        try\n        {\n            if (m_msg.headers().match(header_names::transfer_encoding, header))\n            {\n                try\n                {\n                    m_decompressor = http::compression::details::get_decompressor_from_header(header, http::compression::details::header_types::transfer_encoding);\n                }\n                catch (http_exception &e)\n                {\n                    if (e.error_code().value() != status_codes::NotImplemented)\n                    {\n                        \/\/ Something is wrong with the header; we'll fail here\n                        throw;\n                    }\n                    \/\/ We could not find a decompressor; we'll see if the user's handler adds one later\n                    m_decompress_header_type = http::compression::details::header_types::transfer_encoding;\n                    m_decompress_header = std::move(header);\n                }\n            }\n            else if (m_msg.headers().match(header_names::content_encoding, header))\n            {\n                try\n                {\n                    m_decompressor = http::compression::details::get_decompressor_from_header(header, http::compression::details::header_types::content_encoding);\n                }\n                catch (http_exception &e)\n                {\n                    if (e.error_code().value() != status_codes::UnsupportedMediaType)\n                    {\n                        \/\/ Something is wrong with the header; we'll fail here\n                        throw;\n                    }\n                    \/\/ We could not find a decompressor; we'll see if the user's handler adds one later\n                    m_decompress_header_type = http::compression::details::header_types::content_encoding;\n                    m_decompress_header = std::move(header);\n                }\n            }\n            else if (m_msg.headers().match(header_names::te, header))\n            {\n                \/\/ Note that init_response_headers throws away m_msg, so we need to set our compressor here.  If\n                \/\/ the header contains all unsupported algorithms, it's not an error -- we just won't compress\n                m_compressor = http::compression::details::get_compressor_from_header(header, http::compression::details::header_types::te);\n            }\n            else if (m_msg.headers().match(header_names::accept_encoding, header))\n            {\n                \/\/ This would require pre-compression of the input stream, since we MUST send Content-Length, so we'll (legally) ignore it\n                \/\/m_compressor = http::compression::details::get_compressor_from_header(header, http::compression::details::header_types:accept_encoding);\n            }\n        }\n        catch (http_exception &e)\n        {\n            if (badRequestMsg.empty())\n            {\n                \/\/ Respond with a reasonable message\n                badRequestMsg = e.what();\n            }\n        }\n\n        m_msg._get_impl()->_set_http_version({ (uint8_t)m_request->Version.MajorVersion, (uint8_t)m_request->Version.MinorVersion });\n\n        \/\/ Retrieve the remote IP address\n        std::vector<wchar_t> remoteAddressBuffer(50);\n\n        if (m_request->Address.pRemoteAddress->sa_family == AF_INET6)\n        {\n            auto inAddr = &reinterpret_cast<SOCKADDR_IN6 *>(m_request->Address.pRemoteAddress)->sin6_addr;\n            InetNtopW(AF_INET6, inAddr, &remoteAddressBuffer[0], remoteAddressBuffer.size());\n        }\n        else if (m_request->Address.pRemoteAddress->sa_family == AF_INET)\n        {\n            auto inAddr = &reinterpret_cast<SOCKADDR_IN *>(m_request->Address.pRemoteAddress)->sin_addr;\n            InetNtopW(AF_INET, inAddr, &remoteAddressBuffer[0], remoteAddressBuffer.size());\n        }\n        else\n        {\n            remoteAddressBuffer[0] = L'\\0';\n        }\n\n        m_msg._get_impl()->_set_remote_address(&remoteAddressBuffer[0]);\n\n        \/\/ Start reading in body from the network.\n        m_msg._get_impl()->_prepare_to_receive_data();\n        read_request_body_chunk();\n\n        \/\/ Dispatch request to the http_listener.\n        if(badRequestMsg.empty())\n        {\n            dispatch_request_to_listener((web::http::experimental::listener::details::http_listener_impl *)m_request->UrlContext);\n        }\n        else\n        {\n            m_msg.reply(status_codes::BadRequest, badRequestMsg);\n\n            \/\/ Even though we have a bad request, we should wait for the body otherwise we risk racing over m_overlapped\n            init_response_callbacks(ShouldWaitForBody::Wait);\n        }\n    }\n}\n\nvoid windows_request_context::read_request_body_chunk()\n{\n    auto *pServer = static_cast<http_windows_server *>(http_server_api::server_api());\n    PVOID body;\n\n    \/\/ The read_body_io_completion callback function\n    m_overlapped.set_http_io_completion([this](DWORD error, DWORD nBytes){ read_body_io_completion(error, nBytes);});\n\n    auto request_body_buf = m_msg._get_impl()->outstream().streambuf();\n    if (!m_decompressor)\n    {\n        body = request_body_buf.alloc(CHUNK_SIZE);\n    }\n    else\n    {\n        if (m_compress_buffer.size() < CHUNK_SIZE)\n        {\n            m_compress_buffer.resize(CHUNK_SIZE);\n        }\n        body = m_compress_buffer.data();\n    }\n\n    \/\/ Once we allow users to set the output stream the following assert could fail.\n    \/\/ At that time we would need compensation code that would allocate a buffer from the heap instead.\n    _ASSERTE(body != nullptr);\n\n    StartThreadpoolIo(pServer->m_threadpool_io);\n    const ULONG error_code = HttpReceiveRequestEntityBody(\n        pServer->m_hRequestQueue,\n        m_request_id,\n        HTTP_RECEIVE_REQUEST_ENTITY_BODY_FLAG_FILL_BUFFER,\n        (PVOID)body,\n        CHUNK_SIZE,\n        NULL,\n        &m_overlapped);\n\n    if(error_code != ERROR_IO_PENDING && error_code != NO_ERROR)\n    {\n        \/\/ There was no more data to read.\n        CancelThreadpoolIo(pServer->m_threadpool_io);\n        if (!m_decompressor)\n        {\n            request_body_buf.commit(0);\n        }\n        if(error_code == ERROR_HANDLE_EOF)\n        {\n            m_msg._get_impl()->_complete(request_body_buf.in_avail());\n        }\n        else\n        {\n            m_msg._get_impl()->_complete(0, std::make_exception_ptr(http_exception(error_code)));\n        }\n    }\n}\n\n\/\/\/ <summary>\n\/\/\/  The read request body completion callback function.\n\/\/\/ <\/summary>\nvoid windows_request_context::read_body_io_completion(DWORD error_code, DWORD bytes_read)\n{\n    auto request_body_buf = m_msg._get_impl()->outstream().streambuf();\n\n    if (error_code == NO_ERROR)\n    {\n        if (!m_decompressor)\n        {\n            request_body_buf.commit(bytes_read);\n        }\n        else\n        {\n            size_t got;\n            size_t used;\n            size_t total_used = 0;\n\n            do\n            {\n                auto body = request_body_buf.alloc(CHUNK_SIZE);\n                try\n                {\n                    got = m_decompressor->decompress(m_compress_buffer.data()+total_used, bytes_read-total_used, body, CHUNK_SIZE, http::compression::operation_hint::has_more, used, NULL);\n                }\n                catch (...)\n                {\n                    request_body_buf.commit(0);\n                    m_msg._get_impl()->_complete(0, std::current_exception());\n                    return;\n                }\n                request_body_buf.commit(got);\n                total_used += used;\n            } while (total_used != bytes_read);\n        }\n        read_request_body_chunk();\n    }\n    else if (error_code == ERROR_HANDLE_EOF)\n    {\n        if (!m_decompressor)\n        {\n            request_body_buf.commit(0);\n        }\n        m_msg._get_impl()->_complete(request_body_buf.in_avail());\n    }\n    else\n    {\n        if (!m_decompressor)\n        {\n            request_body_buf.commit(0);\n        }\n        m_msg._get_impl()->_complete(0, std::make_exception_ptr(http_exception(error_code)));\n    }\n}\n\nvoid windows_request_context::dispatch_request_to_listener(_In_ web::http::experimental::listener::details::http_listener_impl *pListener)\n{\n    m_msg._set_listener_path(pListener->uri().path());\n\n    \/\/ Save http_request copy to dispatch to user's handler in case content_ready() completes before.\n    http_request request = m_msg;\n\n    init_response_callbacks(ShouldWaitForBody::Wait);\n\n    \/\/ Look up the lock for the http_listener.\n    auto *pServer = static_cast<http_windows_server *>(http_server_api::server_api());\n    pplx::extensibility::reader_writer_lock_t *pListenerLock;\n    {\n        pplx::extensibility::scoped_read_lock_t lock(pServer->_M_listenersLock);\n\n        \/\/ It is possible the listener could have unregistered.\n        if(pServer->_M_registeredListeners.find(pListener) == pServer->_M_registeredListeners.end())\n        {\n            request.reply(status_codes::NotFound);\n            return;\n        }\n        pListenerLock = &pServer->_M_registeredListeners[pListener]->m_requestHandlerLock;\n\n        \/\/ We need to acquire the listener's lock before releasing the registered listeners lock.\n        \/\/ But we don't need to hold the registered listeners lock when calling into the user's code.\n        pListenerLock->lock_read();\n    }\n\n    try\n    {\n        pListener->handle_request(request);\n        pListenerLock->unlock();\n    }\n    catch(...)\n    {\n        pListenerLock->unlock();\n        request._reply_if_not_already(status_codes::InternalError);\n    }\n}\n\nvoid windows_request_context::init_response_callbacks(ShouldWaitForBody shouldWait)\n{\n    \/\/ Use a proxy event so we're not causing a circular reference between the http_request and the response task\n    pplx::task_completion_event<void> proxy_content_ready;\n\n    auto content_ready_task = m_msg.content_ready();\n    auto get_response_task = m_msg.get_response();\n\n    content_ready_task.then([this, proxy_content_ready](pplx::task<http_request> requestBody)\n    {\n        \/\/ If an exception occurred while processing the body then there is no reason\n        \/\/ to even try sending the response, just re-surface the same exception.\n        try\n        {\n            requestBody.wait();\n        }\n        catch (...)\n        {\n            \/\/ Copy the request reference in case it's the last\n            http_request request = m_msg;\n            m_msg = http_request();\n            auto exc = std::current_exception();\n            proxy_content_ready.set_exception(exc);\n            cancel_request(exc);\n            return;\n        }\n\n        \/\/ At this point the user entirely controls the lifetime of the http_request.\n        m_msg = http_request();\n        proxy_content_ready.set();\n    });\n\n    get_response_task.then([this, proxy_content_ready](pplx::task<http::http_response> responseTask)\n    {\n        \/\/ Don't let an exception from sending the response bring down the server.\n        try\n        {\n            m_response = responseTask.get();\n        }\n        catch (const pplx::task_canceled &)\n        {\n            \/\/ This means the user didn't respond to the request, allowing the\n            \/\/ http_request instance to be destroyed. There is nothing to do then\n            \/\/ so don't send a response.\n            \/\/ Avoid unobserved exception handler\n            pplx::create_task(proxy_content_ready).then([](pplx::task<void> t)\n            {\n                try { t.wait(); } catch (...) {}\n            });\n            return;\n        }\n        catch (...)\n        {\n            \/\/ Should never get here, if we do there's a chance that a circular reference will cause leaks,\n            \/\/ or worse, undefined behaviour as we don't know who owns 'this' anymore\n            _ASSERTE(false);\n            m_response = http::http_response(status_codes::InternalError);\n        }\n\n        pplx::create_task(m_response_completed).then([this](pplx::task<void> t)\n        {\n            \/\/ After response is sent, break circular reference between http_response and the request context.\n            \/\/ Otherwise http_listener::close() can hang.\n            m_response._get_impl()->_set_server_context(nullptr);\n        });\n\n        \/\/ Wait until the content download finished before replying because m_overlapped is reused,\n        \/\/ and we don't want to delete 'this' if the body is still downloading\n        pplx::create_task(proxy_content_ready).then([this](pplx::task<void> t)\n        {\n            try\n            {\n                t.wait();\n                async_process_response();\n            }\n            catch (...)\n            {\n            }\n        }).wait();\n    });\n\n    if (shouldWait == ShouldWaitForBody::DontWait)\n    {\n        \/\/ Fake a body completion so the content_ready() task doesn't keep the http_request alive forever\n        m_msg._get_impl()->_complete(0);\n    }\n}\n\nvoid windows_request_context::async_process_response()\n{\n    auto *pServer = static_cast<http_windows_server *>(http_server_api::server_api());\n\n    HTTP_RESPONSE win_api_response;\n    ZeroMemory(&win_api_response, sizeof(win_api_response));\n    win_api_response.StatusCode = m_response.status_code();\n    const std::string reason = utf16_to_utf8(m_response.reason_phrase());\n    win_api_response.pReason = reason.c_str();\n    win_api_response.ReasonLength = (USHORT)reason.size();\n    size_t content_length;\n\n    if (m_compressor || m_response._get_impl()->compressor())\n    {\n        if (m_response.headers().has(header_names::content_length))\n        {\n            \/\/ Content-Length should not be sent with Transfer-Encoding\n            m_response.headers().remove(header_names::content_length);\n        }\n        if (!m_response._get_impl()->compressor())\n        {\n            \/\/ Temporarily move the compressor to the reponse, so _get_content_length() will honor it\n            m_response._get_impl()->set_compressor(std::move(m_compressor));\n        } \/\/ else one was already set from a callback, and we'll (blindly) use it\n        content_length = m_response._get_impl()->_get_content_length_and_set_compression();\n        m_compressor = std::move(m_response._get_impl()->compressor());\n        m_response._get_impl()->set_compressor(nullptr);\n    }\n    else\n    {\n        if (!m_decompress_header.empty())\n        {\n            auto factories = m_response._get_impl()->decompress_factories();\n            try\n            {\n                m_decompressor = http::compression::details::get_decompressor_from_header(m_decompress_header, m_decompress_header_type, factories);\n                m_decompress_header.clear();\n                if (!m_decompressor)\n                {\n                    http::status_code code = http::status_codes::NotImplemented;\n                    if (m_decompress_header_type == http::compression::details::header_types::content_encoding)\n                    {\n                        code = status_codes::UnsupportedMediaType;\n                    }\n                    throw http_exception(code);\n                }\n            }\n            catch (http_exception &e)\n            {\n                \/\/ No matching decompressor was supplied via callback\n                CancelThreadpoolIo(pServer->m_threadpool_io);\n                cancel_request(std::make_exception_ptr(e));\n                return;\n            }\n        }\n        content_length = m_response._get_impl()->_get_content_length();\n    }\n\n    m_headers = std::unique_ptr<HTTP_UNKNOWN_HEADER []>(new HTTP_UNKNOWN_HEADER[msl::safeint3::SafeInt<size_t>(m_response.headers().size())]);\n    m_headers_buffer.resize(msl::safeint3::SafeInt<size_t>(m_response.headers().size()) * 2);\n\n    win_api_response.Headers.UnknownHeaderCount = (USHORT)m_response.headers().size();\n    win_api_response.Headers.pUnknownHeaders = m_headers.get();\n    int headerIndex = 0;\n    for(auto iter = m_response.headers().begin(); iter != m_response.headers().end(); ++iter, ++headerIndex)\n    {\n        m_headers_buffer[headerIndex * 2] = utf16_to_utf8(iter->first);\n        m_headers_buffer[headerIndex * 2 + 1] = utf16_to_utf8(iter->second);\n        win_api_response.Headers.pUnknownHeaders[headerIndex].NameLength = (USHORT)m_headers_buffer[headerIndex * 2].size();\n        win_api_response.Headers.pUnknownHeaders[headerIndex].pName = m_headers_buffer[headerIndex * 2].c_str();\n        win_api_response.Headers.pUnknownHeaders[headerIndex].RawValueLength = (USHORT)m_headers_buffer[headerIndex * 2 + 1].size();\n        win_api_response.Headers.pUnknownHeaders[headerIndex].pRawValue = m_headers_buffer[headerIndex * 2 + 1].c_str();\n    }\n\n    \/\/ Send response callback function\n    m_overlapped.set_http_io_completion([this](DWORD error, DWORD nBytes){ send_response_io_completion(error, nBytes);});\n\n    \/\/ Figure out how to send the entity body of the message.\n    if (content_length == 0)\n    {\n        \/\/ There's no data. This is easy!\n        StartThreadpoolIo(pServer->m_threadpool_io);\n        const unsigned long error_code = HttpSendHttpResponse(\n            pServer->m_hRequestQueue,\n            m_request_id,\n            NULL,\n            &win_api_response,\n            NULL,\n            NULL,\n            NULL,\n            NULL,\n            &m_overlapped,\n            NULL);\n\n        if(error_code != NO_ERROR && error_code != ERROR_IO_PENDING)\n        {\n            CancelThreadpoolIo(pServer->m_threadpool_io);\n            cancel_request(std::make_exception_ptr(http_exception(error_code)));\n        }\n\n        return;\n    }\n\n    \/\/ OK, so we need to chunk it up.\n    _ASSERTE(content_length > 0);\n    m_sending_in_chunks = (content_length != std::numeric_limits<size_t>::max());\n    m_transfer_encoding = (content_length == std::numeric_limits<size_t>::max());\n    m_remaining_to_write = content_length;\n    if (content_length == std::numeric_limits<size_t>::max())\n    {\n        \/\/ Attempt to figure out the remaining length of the input stream\n        m_remaining_to_write = m_response._get_impl()->_get_stream_length();\n    }\n\n    StartThreadpoolIo(pServer->m_threadpool_io);\n    const unsigned long error_code = HttpSendHttpResponse(\n        pServer->m_hRequestQueue,\n        m_request_id,\n        HTTP_SEND_RESPONSE_FLAG_MORE_DATA,\n        &win_api_response,\n        NULL,\n        NULL,\n        NULL,\n        NULL,\n        &m_overlapped,\n        NULL);\n\n    if(error_code != NO_ERROR && error_code != ERROR_IO_PENDING)\n    {\n        CancelThreadpoolIo(pServer->m_threadpool_io);\n        cancel_request(std::make_exception_ptr(http_exception(error_code)));\n    }\n}\n\n\/\/\/ <summary>\n\/\/\/  The send response headers completion callback function.\n\/\/\/ <\/summary>\nvoid windows_request_context::send_response_io_completion(DWORD error_code, DWORD)\n{\n    if(error_code != NO_ERROR)\n    {\n        cancel_request(std::make_exception_ptr(http_exception(error_code)));\n    }\n    else\n    {\n        transmit_body();\n    }\n}\n\n\/\/ Transmit the response body to the network\nvoid windows_request_context::transmit_body()\n{\n    if ( !m_sending_in_chunks && !m_transfer_encoding )\n    {\n        \/\/ We are done sending data.\n        std::lock_guard<std::mutex> lock(m_responseCompletedLock);\n        m_response_completed.set();\n        return;\n    }\n\n    msl::safeint3::SafeInt<size_t> safeCount = m_remaining_to_write;\n    size_t next_chunk_size = safeCount.Min(CHUNK_SIZE);\n\n    \/\/ In both cases here we could perform optimizations to try and use acquire on the streams to avoid an extra copy.\n    if ( m_sending_in_chunks )\n    {\n        m_body_data.resize(CHUNK_SIZE);\n\n        streams::rawptr_buffer<unsigned char> buf(&m_body_data[0], next_chunk_size);\n\n        m_response.body().read(buf, next_chunk_size).then([this](pplx::task<size_t> op)\n        {\n            size_t bytes_read = 0;\n\n            \/\/ If an exception occurs surface the error to user on the server side\n            \/\/ and cancel the request so the client sees the error.\n            try { bytes_read = op.get(); } catch (...)\n            {\n                cancel_request(std::current_exception());\n                return;\n            }\n            if ( bytes_read == 0 )\n            {\n                cancel_request(std::make_exception_ptr(http_exception(_XPLATSTR(\"Error unexpectedly encountered the end of the response stream early\"))));\n                return;\n            }\n\n            \/\/ Check whether this is the last one to send...\n            m_remaining_to_write = m_remaining_to_write-bytes_read;\n            m_sending_in_chunks = (m_remaining_to_write > 0);\n\n            send_entity_body(&m_body_data[0], bytes_read);\n        });\n    }\n    else\n    {\n        \/\/ We're transfer-encoding...\n        if (m_compressor)\n        {\n            \/\/ ...and compressing.  For simplicity, we allocate a buffer that's \"too large to fail\" while compressing.\n            const size_t body_data_length = 2*CHUNK_SIZE + http::details::chunked_encoding::additional_encoding_space;\n            m_body_data.resize(body_data_length);\n\n            \/\/ We'll read into a temporary buffer before compressing\n            if (m_compress_buffer.capacity() < next_chunk_size)\n            {\n                m_compress_buffer.reserve(next_chunk_size);\n            }\n\n            streams::rawptr_buffer<unsigned char> buf(m_compress_buffer.data(), next_chunk_size);\n\n            m_response.body().read(buf, next_chunk_size).then([this, body_data_length](pplx::task<size_t> op)\n            {\n                size_t bytes_read = 0;\n\n                \/\/ If an exception occurs surface the error to user on the server side\n                \/\/ and cancel the request so the client sees the error.\n                try\n                {\n                    bytes_read = op.get();\n                }\n                catch (...)\n                {\n                    cancel_request(std::current_exception());\n                    return;\n                }\n                _ASSERTE(bytes_read >= 0);\n\n                \/\/ Compress this chunk; if we read no data, allow the compressor to finalize its stream\n                http::compression::operation_hint hint = http::compression::operation_hint::has_more;\n                if (!bytes_read)\n                {\n                    hint = http::compression::operation_hint::is_last;\n                }\n                m_compressor->compress(m_compress_buffer.data(), bytes_read, &m_body_data[http::details::chunked_encoding::data_offset], body_data_length, hint)\n                    .then([this, bytes_read, body_data_length](pplx::task<http::compression::operation_result> op)\n                {\n                    http::compression::operation_result r;\n\n                    try\n                    {\n                        r = op.get();\n                    }\n                    catch (...)\n                    {\n                        cancel_request(std::current_exception());\n                        return;\n                    }\n\n                    if (r.input_bytes_processed != bytes_read ||\n                        r.output_bytes_produced == body_data_length - http::details::chunked_encoding::additional_encoding_space ||\n                        r.done != !bytes_read)\n                    {\n                        \/\/ We chose our parameters so that compression should\n                        \/\/ never overflow body_data_length; fail if it does\n                        cancel_request(std::make_exception_ptr(std::exception(\"Compressed data exceeds internal buffer size.\")));\n                        return;\n                    }\n\n                    \/\/ Check whether this is the last one to send; note that this is a\n                    \/\/ few lines of near-duplicate code with the non-compression path\n                    _ASSERTE(bytes_read <= m_remaining_to_write);\n                    m_remaining_to_write -= bytes_read;\n                    m_transfer_encoding = (r.output_bytes_produced > 0);\n                    size_t offset = http::details::chunked_encoding::add_chunked_delimiters(&m_body_data[0], body_data_length, r.output_bytes_produced);\n                    send_entity_body(&m_body_data[offset], r.output_bytes_produced + http::details::chunked_encoding::additional_encoding_space - offset);\n                });\n            });\n        }\n        else\n        {\n            const size_t body_data_length = CHUNK_SIZE + http::details::chunked_encoding::additional_encoding_space;\n            m_body_data.resize(body_data_length);\n\n            streams::rawptr_buffer<unsigned char> buf(&m_body_data[http::details::chunked_encoding::data_offset], body_data_length);\n\n            m_response.body().read(buf, next_chunk_size).then([this, body_data_length](pplx::task<size_t> op)\n            {\n                size_t bytes_read = 0;\n\n                \/\/ If an exception occurs surface the error to user on the server side\n                \/\/ and cancel the request so the client sees the error.\n                try\n                {\n                    bytes_read = op.get();\n                }\n                catch (...)\n                {\n                    cancel_request(std::current_exception());\n                    return;\n                }\n\n                \/\/ Check whether this is the last one to send...\n                m_transfer_encoding = (bytes_read > 0);\n                size_t offset = http::details::chunked_encoding::add_chunked_delimiters(&m_body_data[0], body_data_length, bytes_read);\n\n                auto data_length = bytes_read + (http::details::chunked_encoding::additional_encoding_space - offset);\n                send_entity_body(&m_body_data[offset], data_length);\n            });\n        }\n    }\n}\n\n\/\/ Send the body through HTTP.sys\nvoid windows_request_context::send_entity_body(_In_reads_(data_length) unsigned char * data, _In_ size_t data_length)\n{\n    HTTP_DATA_CHUNK dataChunk;\n    memset(&dataChunk, 0, sizeof(dataChunk));\n    dataChunk.DataChunkType = HttpDataChunkFromMemory;\n    dataChunk.FromMemory.pBuffer = data;\n    dataChunk.FromMemory.BufferLength = (ULONG)data_length;\n    const bool this_is_the_last_chunk = !m_transfer_encoding && !m_sending_in_chunks;\n\n    \/\/ Send response.\n    auto *pServer = static_cast<http_windows_server *>(http_server_api::server_api());\n\n    \/\/ Send response body callback function\n    m_overlapped.set_http_io_completion([this](DWORD error, DWORD nBytes){ send_response_body_io_completion(error, nBytes); });\n\n    StartThreadpoolIo(pServer->m_threadpool_io);\n    auto error_code = HttpSendResponseEntityBody(\n        pServer->m_hRequestQueue,\n        m_request_id,\n        this_is_the_last_chunk ? NULL : HTTP_SEND_RESPONSE_FLAG_MORE_DATA,\n        1,\n        &dataChunk,\n        NULL,\n        NULL,\n        NULL,\n        &m_overlapped,\n        NULL);\n\n    if(error_code != NO_ERROR && error_code != ERROR_IO_PENDING)\n    {\n        CancelThreadpoolIo(pServer->m_threadpool_io);\n        cancel_request( std::make_exception_ptr(http_exception(error_code)));\n    }\n}\n\n\/\/\/ <summary>\n\/\/\/  The send response body completion callback function.\n\/\/\/ <\/summary>\nvoid windows_request_context::send_response_body_io_completion(DWORD error_code, DWORD)\n{\n    if(error_code != NO_ERROR)\n    {\n        cancel_request(std::make_exception_ptr(http_exception(error_code)));\n        return;\n    }\n    transmit_body();\n}\n\n\/\/\/ <summary>\n\/\/\/  The cancel request completion callback function.\n\/\/\/ <\/summary>\nvoid windows_request_context::cancel_request_io_completion(DWORD, DWORD)\n{\n    std::lock_guard<std::mutex> lock(m_responseCompletedLock);\n    m_response_completed.set_exception(m_except_ptr);\n}\n\nvoid windows_request_context::cancel_request(std::exception_ptr except_ptr)\n{\n    auto *pServer = static_cast<http_windows_server *>(http_server_api::server_api());\n\n    m_except_ptr = except_ptr;\n\n    \/\/ Cancel request callback function.\n    m_overlapped.set_http_io_completion([this](DWORD error, DWORD nBytes){cancel_request_io_completion(error, nBytes);});\n\n    StartThreadpoolIo(pServer->m_threadpool_io);\n\n    auto error_code = HttpCancelHttpRequest(\n        pServer->m_hRequestQueue,\n        m_request_id,\n        &m_overlapped);\n\n    if(error_code != NO_ERROR && error_code != ERROR_IO_PENDING)\n    {\n        CancelThreadpoolIo(pServer->m_threadpool_io);\n        std::lock_guard<std::mutex> lock(m_responseCompletedLock);\n        m_response_completed.set_exception(except_ptr);\n    }\n}\n\nstd::unique_ptr<http_server> make_http_httpsys_server()\n{\n    return std::make_unique<http_windows_server>();\n}\n\n}}}}\n\n#endif\n","avg_line_length":35.8740340031,"max_line_length":188,"alphanum_fraction":0.6278839318,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6544,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/****************************************************************************\n* Copyright (c) 2015 - 2016, CEA\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n* 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.\n* 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.\n*\n* 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.\n* 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;\n* 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.\n*\n*****************************************************************************\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File:        Echange_externe_impose_H.cpp\n\/\/ Directory:   $TRUST_ROOT\/src\/ThHyd\/Quasi_Compressible\n\/\/ Version:     \/main\/10\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <Echange_externe_impose_H.h>\n#include <Fluide_Quasi_Compressible.h>\n#include <Equation_base.h>\n#include <Motcle.h>\n\n\nImplemente_instanciable(Echange_externe_impose_H,\"Paroi_echange_externe_impose_H\",Echange_externe_impose);\n\n\n\/\/ Description:\n\/\/    Ecrit le type de l'objet sur un flot de sortie\n\/\/ Precondition:\n\/\/ Parametre: Sortie& s\n\/\/    Signification: un flot de sortie\n\/\/    Valeurs par defaut:\n\/\/    Contraintes:\n\/\/    Acces: entree\/sortie\n\/\/ Retour: Sortie&\n\/\/    Signification: le flot de sortie modifie\n\/\/    Contraintes:\n\/\/ Exception:\n\/\/ Effets de bord:\n\/\/ Postcondition: la methode ne modifie pas l'objet\nSortie& Echange_externe_impose_H::printOn(Sortie& s ) const\n{\n  return s << que_suis_je() << \"\\n\";\n}\n\n\/\/ Description:\n\/\/    Simple appel a Echange_impose_base::readOn(Entree&)\n\/\/    Lit les specifications des conditions aux limites\n\/\/    a partir d'un flot d'entree.\n\/\/ Precondition:\n\/\/ Parametre: Entree& s\n\/\/    Signification: un flot d'entree\n\/\/    Valeurs par defaut:\n\/\/    Contraintes:\n\/\/    Acces: entree\/sortie\n\/\/ Retour: Entree&\n\/\/    Signification: le flot de sortie modifie\n\/\/    Contraintes:\n\/\/ Exception:\n\/\/ Effets de bord:\n\/\/ Postcondition:\nEntree& Echange_externe_impose_H::readOn(Entree& s )\n{\n  return Echange_externe_impose::readOn(s) ;\n}\n\n\/\/ Description:\n\/\/    Complete les conditions aux limites.\n\/\/ Precondition:\n\/\/ Parametre:\n\/\/    Signification:\n\/\/    Valeurs par defaut:\n\/\/    Contraintes:\n\/\/    Acces:\n\/\/ Retour:\n\/\/    Signification:\n\/\/    Contraintes:\n\/\/ Exception:\n\/\/ Effets de bord:\n\/\/ Postcondition:\nvoid Echange_externe_impose_H::completer()\n{\n  Echange_impose_base::completer();\n  le_fluide = ref_cast(Fluide_Quasi_Compressible,ma_zone_cl_dis->equation().milieu());\n  modifier_val_imp = 1;\n}\n\n\/\/ Description:\n\/\/    Renvoie la valeur de la temperature imposee\n\/\/    sur la i-eme composante du champ de frontiere.\n\/\/ Precondition:\n\/\/ Parametre: int i\n\/\/    Signification: l'indice de la composante du champ de\n\/\/                   de frontiere\n\/\/    Valeurs par defaut:\n\/\/    Contraintes:\n\/\/    Acces:\n\/\/ Retour: double\n\/\/    Signification:\n\/\/    Contraintes:\n\/\/ Exception:\n\/\/ Effets de bord:\n\/\/ Postcondition: la methode ne modifie pas l'objet\ndouble Echange_externe_impose_H::T_ext(int i) const\n{\n  if (le_champ_front.valeurs().size()==1)\n    {\n      if (modifier_val_imp==1)\n        return le_fluide->calculer_H(le_champ_front(0,0));\n      else\n        return le_champ_front(0,0);\n\n    }\n  else if (le_champ_front.valeurs().dimension(1)==1)\n    {\n      if (modifier_val_imp==1)\n        return le_fluide->calculer_H(le_champ_front(i,0));\n      else\n        return le_champ_front(i,0);\n\n    }\n  else\n    Cerr << \"Echange_impose_base::T_ext erreur\" << finl;\n\n  abort();\n  return 0.;\n}\n\n\/\/ Description:\n\/\/    Renvoie la valeur de la temperature imposee\n\/\/    sur la (i,j)-eme composante du champ de frontiere.\n\/\/ Precondition:\n\/\/ Parametre: int i\n\/\/    Signification:\n\/\/    Valeurs par defaut:\n\/\/    Contraintes:\n\/\/    Acces:\n\/\/ Parametre: int j\n\/\/    Signification:\n\/\/    Valeurs par defaut:\n\/\/    Contraintes:\n\/\/    Acces:\n\/\/ Retour: double\n\/\/    Signification:\n\/\/    Contraintes:\n\/\/ Exception:\n\/\/ Effets de bord:\n\/\/ Postcondition: la methode ne modifie pas l'objet\ndouble Echange_externe_impose_H::T_ext(int i, int j) const\n{\n  if (le_champ_front.valeurs().dimension(0)==1)\n    {\n      if (modifier_val_imp==1)\n        return le_fluide->calculer_H(le_champ_front(0,j));\n      else\n        return le_champ_front(0,j);\n\n    }\n  else\n    {\n      if (modifier_val_imp==1)\n        return le_fluide->calculer_H(le_champ_front(i,j));\n      else\n        return le_champ_front(i,j);\n    }\n}\n\n\n\/\/ Description:\n\/\/    Verifie la compatibilite des conditions aux limites avec\n\/\/    l'equation passee en parametre.\n\/\/   Les conditions aux limites de type Ech_imp_base  sont\n\/\/   compatibles avec des equations de type:\n\/\/         - Thermique_H  (thermique avec inconnue = enthalpie)\n\/\/ Precondition:\n\/\/ Parametre: Equation_base& eqn\n\/\/    Signification: l'equation avec laquelle on doit verifier la compatibilite\n\/\/    Valeurs par defaut:\n\/\/    Contraintes: reference constante\n\/\/    Acces: entree\n\/\/ Retour: int\n\/\/    Signification: valeur booleenne, 1 si compatible 0 sinon\n\/\/    Contraintes:\n\/\/ Exception:\n\/\/ Effets de bord:\n\/\/ Postcondition: la methode ne modifie pas l'objet\nint Echange_externe_impose_H::compatible_avec_eqn(const Equation_base& eqn) const\n{\n  Motcle dom_app=eqn.domaine_application();\n  Motcle Thermique=\"Thermique_H\";\n  if ( (dom_app==Thermique))\n    return 1;\n  else\n    {\n      err_pas_compatible(eqn);\n      return 0;\n    }\n}\n","avg_line_length":32.0784313725,"max_line_length":260,"alphanum_fraction":0.6745110024,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2808,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/Language: GNU C++\n\n\n#include <iostream>\r\n#include <math.h>\r\n#include <vector>\r\n#include <map>\r\n#include <set>\r\n#include <fstream>\r\n#include <string>\r\n#include <stack>\r\n#include <queue>\r\n#include <deque>\r\n#include <algorithm>\r\n#include <stdio.h>\r\n\r\n#define ALL(x) (x).begin(), (x).end()\r\n#define mp make_pair\r\n#define vec vector\r\n\r\ntypedef long long LL;\r\n\r\nconst LL inf = 1000000000;\r\nconst LL inf64 = inf * inf;\r\nconst LL base = inf + 7;\r\nconst double pi = acos(-1.0);\r\n\r\nusing namespace std;\r\n\r\nint n, m;\r\nvec<int> par, in, out, q, Q;\r\nvec< vec<int> > g;\r\nvec<bool> used;\r\n\r\nstruct zz\r\n{\r\n    int type;\r\n    int x1, y;\r\n    int x2, i;\r\n    int x3;\r\n\r\n    zz()\r\n    {\r\n        type = x1 = x2 = x3 = y = i = -1;\r\n    }\r\n\r\n    zz(int T, int X, int Y = -1)\r\n    {\r\n        type = x1 = x2 = x3 = y = i = -1;\r\n        type = T;\r\n        if(T == 1) x1 = X, y = Y;\r\n        else if(T == 2) x2 = X;\r\n        else x3 = X, i = Y;\r\n    }\r\n};\r\n\r\nvec<zz> z; \r\n\r\nint find(int x)\r\n{\r\n    return (x == par[x]?x : par[x] = find(par[x]));\r\n}\r\n\r\nvoid _union(int a, int b)\r\n{\r\n    int p, q;\r\n    p = find(a);\r\n    q = find(b);\r\n    par[p] = q;\r\n}\r\n\r\nint time = 1;\r\n\r\nvoid dfs(int v)\r\n{\r\n    in[v] = time;\r\n    for(int i(0);i < (int)g[v].size();i++)\r\n    {\r\n        int to = g[v][i];\r\n        dfs(to);\r\n    }\r\n    out[v] = time++;\r\n}\r\n\r\nbool solve()\r\n{\r\n    cin >> n >> m;\r\n\r\n    g.resize(n);\r\n    used.assign(n, false);\r\n\r\n    par.resize(n);\r\n\r\n    for(int i(0);i < n;i++) par[i] = i;\r\n\r\n    for(int type, x, y, i(0);i < m;i++)\r\n    {\r\n        cin >> type;\r\n        x = y = 0;\r\n\r\n        if(type != 2) cin >> x >> y;\r\n        else cin >> x;\r\n        x--, y--;\r\n        z.push_back(zz(type, x, y));\r\n    }\r\n\r\n    for(int x, y, i(0);i < m;i++)\r\n    {\r\n        if(z[i].type == 1)\r\n        {\r\n            x = z[i].x1, y = z[i].y;\r\n            g[y].push_back(x);\r\n            used[x] = 1;\r\n        }\r\n    }\r\n\r\n    in.resize(n, 0);\r\n    out.resize(n, 0);\r\n\r\n    for(int i(0);i < n;i++) if(!used[i]) dfs(i);\r\n\r\n    for(int i(0);i < m;i++)\r\n    {\r\n        if(z[i].type == 1)\r\n        {\r\n            int x, y;\r\n            x = z[i].x1, y = z[i].y;\r\n            _union(x, y);\r\n        }else if(z[i].type == 2)\r\n        {\r\n            q.push_back(i);\r\n            Q.push_back(find(z[i].x2));\r\n        }else if(z[i].type == 3)\r\n        {   \r\n            int x, y, root;\r\n            x = y = 0;\r\n            x = z[i].x3, y = z[q[z[i].i]].x2;\r\n            root = Q[z[i].i];\r\n            if(find(x) != find(y)) {cout << \"NO\\n\";continue;}\r\n\r\n            if(in[root] <= in[x] && out[root] >= out[x] && in[x] <= in[y] && out[x] >= out[y]) \r\n                cout << \"YES\\n\";\r\n            else \r\n                cout << \"NO\\n\";\r\n        }\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    \/\/while(solve());\r\n    solve();    \r\n\r\n    return 0;\r\n}","avg_line_length":17.8853503185,"max_line_length":96,"alphanum_fraction":0.3896011396,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":280,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"Timer.hpp\"\n\nTimer::Timer() {\n\tm_lastNow = Util::GetClock();\n\tm_now = Util::GetClock();\n}\n\nvoid Timer::Restart() {\n\tm_lastNow = m_now;\n\tm_now = Util::GetClock();\n}\n\nfloat Timer::GetDeltaTime() {\n\treturn Util::GetClockDifference(m_now, m_lastNow);\n}\n\nTimer::~Timer() {\n\n}\n","avg_line_length":14.0,"max_line_length":51,"alphanum_fraction":0.6571428571,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13659,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <QtGlobal>\n\/\/ Automatically generated by extract_strings.py\n#ifdef __GNUC__\n#define UNUSED __attribute__((unused))\n#else\n#define UNUSED\n#endif\nstatic const char UNUSED *bitcoin_strings[] = {\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"%s, you must set a rpcpassword in the configuration file:\\n\"\n\"%s\\n\"\n\"It is recommended you use the following random password:\\n\"\n\"rpcuser=WorldAidCoin\\n\"\n\"rpcpassword=%s\\n\"\n\"(you do not need to remember this password)\\n\"\n\"The username and password MUST NOT be the same.\\n\"\n\"If the file does not exist, create it with owner-readable-only file \"\n\"permissions.\\n\"\n\"It is also recommended to set alertnotify so you are notified of problems;\\n\"\n\"for example: alertnotify=echo %%s | mail -s \\\"WorldAidCoin Alert\\\" admin@foo.com\\n\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:\"\n\"@STRENGTH)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"An error occurred while setting up the RPC port %u for listening on IPv4: %s\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"An error occurred while setting up the RPC port %u for listening on IPv6, \"\n\"falling back to IPv4: %s\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Bind to given address and always listen on it. Use [host]:port notation for \"\n\"IPv6\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Cannot obtain a lock on data directory %s. WorldAidCoin is probably already \"\n\"running.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Error: The transaction was rejected! This might happen if some of the coins \"\n\"in your wallet were already spent, such as if you used a copy of wallet.dat \"\n\"and coins were spent in the copy but not marked as spent here.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Error: This transaction requires a transaction fee of at least %s because of \"\n\"its amount, complexity, or use of recently received funds!\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Execute command when a relevant alert is received (%s in cmd is replaced by \"\n\"message)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Execute command when a wallet transaction changes (%s in cmd is replaced by \"\n\"TxID)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Execute command when the best block changes (%s in cmd is replaced by block \"\n\"hash)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Listen for JSON-RPC connections on <port> (default: 5988 or testnet: 15988)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Number of seconds to keep misbehaving peers from reconnecting (default: \"\n\"86400)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Set maximum size of high-priority\/low-fee transactions in bytes (default: \"\n\"27000)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Set the number of script verification threads (up to 16, 0 = auto, <0 = \"\n\"leave that many cores free, default: 0)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"This is a pre-release test build - use at your own risk - do not use for \"\n\"mining or merchant applications\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Unable to bind to %s on this computer. WorldAidCoin is probably already running.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Warning: -paytxfee is set very high! This is the transaction fee you will \"\n\"pay if you send a transaction.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Warning: Displayed transactions may not be correct! You may need to upgrade, \"\n\"or other nodes may need to upgrade.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Warning: Please check that your computer's date and time are correct! If \"\n\"your clock is wrong WorldAidCoin will not work properly.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Warning: error reading wallet.dat! All keys read correctly, but transaction \"\n\"data or address book entries might be missing or incorrect.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as \"\n\"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect \"\n\"you should restore from a backup.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"\"\n\"You must set rpcpassword=<password> in the configuration file:\\n\"\n\"%s\\n\"\n\"If the file does not exist, create it with owner-readable-only file \"\n\"permissions.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Accept command line and JSON-RPC commands\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Accept connections from outside (default: 1 if no -proxy or -connect)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Add a node to connect to and attempt to keep the connection open\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Allow DNS lookups for -addnode, -seednode and -connect\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Allow JSON-RPC connections from specified IP address\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Attempt to recover private keys from a corrupt wallet.dat\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"WorldAidCoin version\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Block creation options:\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Cannot downgrade wallet\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Cannot resolve -bind address: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Cannot resolve -externalip address: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Cannot write default address\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Connect only to the specified node(s)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Connect through socks proxy\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Connect to a node to retrieve peer addresses, and disconnect\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Corrupted block database detected\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Discover own IP address (default: 1 when listening and no -externalip)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Do you want to rebuild the block database now?\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Done loading\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error initializing block database\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error initializing wallet database environment %s!\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error loading block database\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error loading wallet.dat\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error loading wallet.dat: Wallet corrupted\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error loading wallet.dat: Wallet requires newer version of WorldAidCoin\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error opening block database\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error: Disk space is low!\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error: Wallet locked, unable to create transaction!\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Error: system error: \"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Failed to listen on any port. Use -listen=0 if you want this.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Failed to read block info\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Failed to read block\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Failed to sync block index\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Failed to write block index\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Failed to write block info\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Failed to write block\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Failed to write file info\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Failed to write to coin database\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Failed to write transaction index\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Failed to write undo data\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Fee per KB to add to transactions you send\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Find peers using DNS lookup (default: 1 unless -connect)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Generate coins (default: 0)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Get help for a command\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"How many blocks to check at startup (default: 288, 0 = all)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"How thorough the block verification is (0-4, default: 3)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Imports blocks from external blk000??.dat file\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Information\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Insufficient funds\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Invalid -proxy address: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Invalid -tor address: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Invalid amount for -minrelaytxfee=<amount>: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Invalid amount for -mintxfee=<amount>: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Invalid amount for -paytxfee=<amount>: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Invalid amount\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"List commands\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Listen for connections on <port> (default: 5989 or testnet: 15989)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Loading addresses...\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Loading block index...\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Loading wallet...\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Maintain a full transaction index (default: 0)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Maintain at most <n> connections to peers (default: 125)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Not enough file descriptors available.\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Only accept block chain matching built-in checkpoints (default: 1)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Only connect to nodes in network <net> (IPv4, IPv6 or Tor)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Options:\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Output extra debugging information. Implies all other -debug* options\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Output extra network debugging information\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Password for JSON-RPC connections\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Prepend debug output with timestamp\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Rebuild block chain index from current blk000??.dat files\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Rescan the block chain for missing wallet transactions\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Rescanning...\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Run in the background as a daemon and accept commands\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"SSL options: (see the WorldAidCoin Wiki for SSL setup instructions)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Select the version of socks proxy to use (4-5, default: 5)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Send command to -server or WorldAidCoind\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Send commands to node running on <ip> (default: 127.0.0.1)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Send trace\/debug info to console instead of debug.log file\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Send trace\/debug info to debugger\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Server certificate file (default: server.cert)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Server private key (default: server.pem)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Set database cache size in megabytes (default: 25)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Set key pool size to <n> (default: 100)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Set maximum block size in bytes (default: 250000)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Set minimum block size in bytes (default: 0)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Set the number of threads to service RPC calls (default: 4)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Shrink debug.log file on client startup (default: 1 when no -debug)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Signing transaction failed\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Specify configuration file (default: WorldAidCoin.conf)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Specify connection timeout in milliseconds (default: 5000)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Specify data directory\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Specify pid file (default: WorldAidCoind.pid)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Specify your own public address\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"System error: \"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"This help message\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Threshold for disconnecting misbehaving peers (default: 100)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"To use the %s option\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Transaction amount too small\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Transaction amounts must be positive\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Transaction too large\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Unable to bind to %s on this computer (bind returned error %d, %s)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Unknown -socks proxy version requested: %i\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Unknown network specified in -onlynet: '%s'\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Upgrade wallet to latest format\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Usage:\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Use OpenSSL (https) for JSON-RPC connections\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Use UPnP to map the listening port (default: 0)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Use UPnP to map the listening port (default: 1 when listening)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Use proxy to reach tor hidden services (default: same as -proxy)\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Use the test network\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Username for JSON-RPC connections\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Verifying blocks...\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Verifying wallet...\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Wallet needed to be rewritten: restart WorldAidCoin to complete\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Warning\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"Warning: This version is obsolete, upgrade required!\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"You need to rebuild the database using -reindex to change -txindex\"),\nQT_TRANSLATE_NOOP(\"bitcoin-core\", \"wallet.dat corrupt, salvage failed\"),\n};\n","avg_line_length":64.7345971564,"max_line_length":109,"alphanum_fraction":0.7605974083,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":7201,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <fiberchain\/protocol\/config.hpp>\n#include <fiberchain\/protocol\/types.hpp>\n\n#include <fc\/crypto\/base58.hpp>\n#include <fc\/crypto\/ripemd160.hpp>\n#include <fc\/exception\/exception.hpp>\n#include <fc\/io\/raw.hpp>\n\nnamespace fiberchain { namespace protocol {\n\n    public_key_type::public_key_type():key_data(){};\n\n    public_key_type::public_key_type( const fc::ecc::public_key_data& data )\n        :key_data( data ) {};\n\n    public_key_type::public_key_type( const fc::ecc::public_key& pubkey )\n        :key_data( pubkey ) {};\n\n    public_key_type::public_key_type( const std::string& base58str )\n    {\n      \/\/ TODO:  Refactor syntactic checks into static is_valid()\n      \/\/        to make public_key_type API more similar to address API\n       std::string prefix( FIBERCHAIN_ADDRESS_PREFIX );\n\n       const size_t prefix_len = prefix.size();\n       FC_ASSERT( base58str.size() > prefix_len );\n       FC_ASSERT( base58str.substr( 0, prefix_len ) ==  prefix , \"\", (\"base58str\", base58str) );\n       auto bin = fc::from_base58( base58str.substr( prefix_len ) );\n       auto bin_key = fc::raw::unpack<binary_key>(bin);\n       key_data = bin_key.data;\n       FC_ASSERT( fc::ripemd160::hash( key_data.data, key_data.size() )._hash[0] == bin_key.check );\n    };\n\n\n    public_key_type::operator fc::ecc::public_key_data() const\n    {\n       return key_data;\n    };\n\n    public_key_type::operator fc::ecc::public_key() const\n    {\n       return fc::ecc::public_key( key_data );\n    };\n\n    public_key_type::operator std::string() const\n    {\n       binary_key k;\n       k.data = key_data;\n       k.check = fc::ripemd160::hash( k.data.data, k.data.size() )._hash[0];\n       auto data = fc::raw::pack( k );\n       return FIBERCHAIN_ADDRESS_PREFIX + fc::to_base58( data.data(), data.size() );\n    }\n\n    bool operator == ( const public_key_type& p1, const fc::ecc::public_key& p2)\n    {\n       return p1.key_data == p2.serialize();\n    }\n\n    bool operator == ( const public_key_type& p1, const public_key_type& p2)\n    {\n       return p1.key_data == p2.key_data;\n    }\n\n    bool operator != ( const public_key_type& p1, const public_key_type& p2)\n    {\n       return p1.key_data != p2.key_data;\n    }\n\n    \/\/ extended_public_key_type\n\n    extended_public_key_type::extended_public_key_type():key_data(){};\n\n    extended_public_key_type::extended_public_key_type( const fc::ecc::extended_key_data& data )\n       :key_data( data ){};\n\n    extended_public_key_type::extended_public_key_type( const fc::ecc::extended_public_key& extpubkey )\n    {\n       key_data = extpubkey.serialize_extended();\n    };\n\n    extended_public_key_type::extended_public_key_type( const std::string& base58str )\n    {\n       std::string prefix( FIBERCHAIN_ADDRESS_PREFIX );\n\n       const size_t prefix_len = prefix.size();\n       FC_ASSERT( base58str.size() > prefix_len );\n       FC_ASSERT( base58str.substr( 0, prefix_len ) ==  prefix , \"\", (\"base58str\", base58str) );\n       auto bin = fc::from_base58( base58str.substr( prefix_len ) );\n       auto bin_key = fc::raw::unpack<binary_key>(bin);\n       FC_ASSERT( fc::ripemd160::hash( bin_key.data.data, bin_key.data.size() )._hash[0] == bin_key.check );\n       key_data = bin_key.data;\n    }\n\n    extended_public_key_type::operator fc::ecc::extended_public_key() const\n    {\n       return fc::ecc::extended_public_key::deserialize( key_data );\n    }\n\n    extended_public_key_type::operator std::string() const\n    {\n       binary_key k;\n       k.data = key_data;\n       k.check = fc::ripemd160::hash( k.data.data, k.data.size() )._hash[0];\n       auto data = fc::raw::pack( k );\n       return FIBERCHAIN_ADDRESS_PREFIX + fc::to_base58( data.data(), data.size() );\n    }\n\n    bool operator == ( const extended_public_key_type& p1, const fc::ecc::extended_public_key& p2)\n    {\n       return p1.key_data == p2.serialize_extended();\n    }\n\n    bool operator == ( const extended_public_key_type& p1, const extended_public_key_type& p2)\n    {\n       return p1.key_data == p2.key_data;\n    }\n\n    bool operator != ( const extended_public_key_type& p1, const extended_public_key_type& p2)\n    {\n       return p1.key_data != p2.key_data;\n    }\n\n    \/\/ extended_private_key_type\n\n    extended_private_key_type::extended_private_key_type():key_data(){};\n\n    extended_private_key_type::extended_private_key_type( const fc::ecc::extended_key_data& data )\n       :key_data( data ){};\n\n    extended_private_key_type::extended_private_key_type( const fc::ecc::extended_private_key& extprivkey )\n    {\n       key_data = extprivkey.serialize_extended();\n    };\n\n    extended_private_key_type::extended_private_key_type( const std::string& base58str )\n    {\n       std::string prefix( FIBERCHAIN_ADDRESS_PREFIX );\n\n       const size_t prefix_len = prefix.size();\n       FC_ASSERT( base58str.size() > prefix_len );\n       FC_ASSERT( base58str.substr( 0, prefix_len ) ==  prefix , \"\", (\"base58str\", base58str) );\n       auto bin = fc::from_base58( base58str.substr( prefix_len ) );\n       auto bin_key = fc::raw::unpack<binary_key>(bin);\n       FC_ASSERT( fc::ripemd160::hash( bin_key.data.data, bin_key.data.size() )._hash[0] == bin_key.check );\n       key_data = bin_key.data;\n    }\n\n    extended_private_key_type::operator fc::ecc::extended_private_key() const\n    {\n       return fc::ecc::extended_private_key::deserialize( key_data );\n    }\n\n    extended_private_key_type::operator std::string() const\n    {\n       binary_key k;\n       k.data = key_data;\n       k.check = fc::ripemd160::hash( k.data.data, k.data.size() )._hash[0];\n       auto data = fc::raw::pack( k );\n       return FIBERCHAIN_ADDRESS_PREFIX + fc::to_base58( data.data(), data.size() );\n    }\n\n    bool operator == ( const extended_private_key_type& p1, const fc::ecc::extended_public_key& p2)\n    {\n       return p1.key_data == p2.serialize_extended();\n    }\n\n    bool operator == ( const extended_private_key_type& p1, const extended_private_key_type& p2)\n    {\n       return p1.key_data == p2.key_data;\n    }\n\n    bool operator != ( const extended_private_key_type& p1, const extended_private_key_type& p2)\n    {\n       return p1.key_data != p2.key_data;\n    }\n\n} } \/\/ fiberchain::protocol\n\nnamespace fc\n{\n    using namespace std;\n    void to_variant( const fiberchain::protocol::public_key_type& var,  fc::variant& vo )\n    {\n        vo = std::string( var );\n    }\n\n    void from_variant( const fc::variant& var,  fiberchain::protocol::public_key_type& vo )\n    {\n        vo = fiberchain::protocol::public_key_type( var.as_string() );\n    }\n\n    void to_variant( const fiberchain::protocol::extended_public_key_type& var, fc::variant& vo )\n    {\n       vo = std::string( var );\n    }\n\n    void from_variant( const fc::variant& var, fiberchain::protocol::extended_public_key_type& vo )\n    {\n       vo = fiberchain::protocol::extended_public_key_type( var.as_string() );\n    }\n\n    void to_variant( const fiberchain::protocol::extended_private_key_type& var, fc::variant& vo )\n    {\n       vo = std::string( var );\n    }\n\n    void from_variant( const fc::variant& var, fiberchain::protocol::extended_private_key_type& vo )\n    {\n       vo = fiberchain::protocol::extended_private_key_type( var.as_string() );\n    }\n} \/\/ fc\n","avg_line_length":33.9669811321,"max_line_length":108,"alphanum_fraction":0.6582419108,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":13434,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":4.0,"content":"\/\/-----------------------------------------------------------------------------\n\/\/ This program must be compiled using a special makefile:\n\/\/ make -f ROCM_SMI_Makefile rocm_smi_writeTests.out \n\/\/-----------------------------------------------------------------------------\n#define __HIP_PLATFORM_HCC__\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"papi.h\"\n#include <hip\/hip_runtime.h>\n#include <unistd.h>\n#include \"rocm_smi.h\"   \/\/ Need some enumerations.\n\n#define CHECK(cmd) \\\n{\\\n    hipError_t error  = cmd;\\\n    if (error != hipSuccess) { \\\n        fprintf(stderr, \"error: '%s'(%d) at %s:%d\\n\", hipGetErrorString(error), error,__FILE__, __LINE__); \\\n        exit(EXIT_FAILURE);\\\n\t  }\\\n}\n\n\/\/ THIS MACRO EXITS if the papi call does not return PAPI_OK. Do not use for routines that\n\/\/ return anything else; e.g. PAPI_num_components, PAPI_get_component_info, PAPI_library_init.\n#define CALL_PAPI_OK(papi_routine)                                                        \\\n    do {                                                                                  \\\n        int _papiret = papi_routine;                                                      \\\n        if (_papiret != PAPI_OK) {                                                        \\\n            fprintf(stderr, \"%s:%d macro: PAPI Error: function \" #papi_routine \" failed with ret=%d [%s].\\n\", \\\n                    __FILE__, __LINE__, _papiret, PAPI_strerror(_papiret));               \\\n            exit(-1);                                                                     \\\n        }                                                                                 \\\n    } while (0);\n\n\n#define MEMORY_ALLOCATION_CALL(var)                                     \\\n    do {                                                                \\\n        if (var == NULL) {                                              \\\n            fprintf(stderr, \"%s:%d: Error: Memory Allocation Failed \\n\",\\\n                    __FILE__, __LINE__);                                \\\n            exit(-1);                                                   \\\n        }                                                               \\\n    } while (0);  \n\n\n#define MAX_DEVICES    (32)\n#define BLOCK_SIZE     (1024)\n#define GRID_SIZE      (512)\n#define BUF_SIZE       (32 * 1024)\n#define ALIGN_SIZE     (8)\n#define SUCCESS        (0)\n#define NUM_METRIC     (18)\n#define NUM_EVENTS     (2)\n#define MAX_SIZE       (64*1024*1024)   \/\/ 64 MB\n\ntypedef union\n{\n    long long ll;\n    unsigned long long ull;\n    double    d;\n    void *vp;\n    unsigned char ch[8];\n} convert_64_t;\n\ntypedef struct {\n    char name[128];\n    long long value;\n} eventStore_t;\n\nint eventsFoundCount = 0;               \/\/ occupants of the array.\nint eventsFoundMax;                     \/\/ Size of the array.\nint eventsFoundAdd = 32;                \/\/ Blocksize for increasing the array.\nint deviceCount=0;                      \/\/ Total devices seen.\nint deviceEvents[32] = {0};             \/\/ Number of events for each device=??.\neventStore_t *eventsFound = NULL;       \/\/ The array.\n\n\/\/-----------------------------------------------------------------------------\n\/\/ HIP routine: Square each element in the array A and write to array C.\n\/\/-----------------------------------------------------------------------------\ntemplate <typename T>\n__global__ void\nvector_square(T *C_d, T *A_d, size_t N)\n{\n    size_t offset = (blockIdx.x * blockDim.x + threadIdx.x);\n    size_t stride = blockDim.x * gridDim.x ;\n\n    for (size_t i=offset; i<N; i+=stride) {\n        C_d[i] = A_d[i] * A_d[i];\n    }\n}\n\n\/\/ Show help.\n\/\/-----------------------------------------------------------------------------\nstatic void printUsage()\n{\n    printf(\"Demonstrate use of ROCM API write routines.\\n\");\n    printf(\"This program has no options, it will use PAPI to read\/write\/read\\n\");\n    printf(\"rocm_smi writable settings and report the results.              \\n\");\n} \/\/ end routine.\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Interpret command line flags.\n\/\/-----------------------------------------------------------------------------\nvoid parseCommandLineArgs(int argc, char *argv[])\n{\n    if(argc < 2) return;\n\n    if((strcmp(argv[1], \"--help\") == 0) || \n       (strcmp(argv[1], \"-help\") == 0)  || \n       (strcmp(argv[1], \"-h\") == 0)) {\n        printUsage();\n        exit(0);\n    }\n} \/\/ end routine.\n\n\/\/-----------------------------------------------------------------------------\n\/\/ conduct a test using HIP. Derived from AMD sample code 'square.cpp'.\n\/\/ coming in, EventSet is already populated, we just run the test and read.\n\/\/ Note values must point at an array large enough to store the events in\n\/\/ Eventset.\n\/\/-----------------------------------------------------------------------------\nvoid conductTest(int EventSet, int device, long long *values) {\n    float *A_d, *C_d;\n    float *A_h, *C_h;\n    size_t N = 1000000;\n    size_t Nbytes = N * sizeof(float);\n    int i, ret, thisDev, verbose=0;\n\n\tret = PAPI_start( EventSet );\n\tif (ret != PAPI_OK ) {\n\t    fprintf(stderr,\"Error! PAPI_start\\n\");\n\t    exit( ret );\n\t}\n\n    hipDeviceProp_t props;                        \n    if (verbose) fprintf(stderr, \"args: EventSet=%i, device=%i, values=%p.\\n\", EventSet, device, values);\n \n    CHECK(hipSetDevice(device));                      \/\/ Set device requested.\n    CHECK(hipGetDevice(&thisDev));                    \/\/ Double check.\n    CHECK(hipGetDeviceProperties(&props, thisDev));   \/\/ Get properties (for name).\n    if (verbose) fprintf (stderr, \"info: Requested Device=%i, running on device %i=%s\\n\", device, thisDev, props.name);\n\n    if (verbose) fprintf (stderr, \"info: allocate host mem (%6.2f MB)\\n\", 2*Nbytes\/1024.0\/1024.0);\n    A_h = (float*)malloc(Nbytes);                     \/\/ standard malloc for host.\n    CHECK(A_h == NULL ? hipErrorMemoryAllocation : hipSuccess );\n    C_h = (float*)malloc(Nbytes);                     \/\/ standard malloc for host.\n    CHECK(C_h == NULL ? hipErrorMemoryAllocation : hipSuccess );\n\n    \/\/ Fill with Phi + i\n    for (size_t i=0; i<N; i++) \n    {\n        A_h[i] = 1.618f + i; \n    }\n\n    if (verbose) fprintf (stderr, \"info: allocate device mem (%6.2f MB)\\n\", 2*Nbytes\/1024.0\/1024.0);\n    CHECK(hipMalloc(&A_d, Nbytes));                   \/\/ HIP malloc for device.\n    CHECK(hipMalloc(&C_d, Nbytes));                   \/\/ ...\n\n\n    if (verbose) fprintf (stderr, \"info: copy Host2Device\\n\");\n    CHECK ( hipMemcpy(A_d, A_h, Nbytes, hipMemcpyHostToDevice));  \/\/ Copy (*dest, *source, Type).\n\n    const unsigned blocks = 512;\n    const unsigned threadsPerBlock = 256;\n\n    if (verbose) fprintf (stderr, \"info: launch 'vector_square' kernel\\n\");\n\/\/  hipLaunchKernelGGL((vector_square), dim3(blocks), dim3(threadsPerBlock), 0, 0, C_d, A_d, N);\n\n    if (verbose) fprintf (stderr, \"info: copy Device2Host\\n\");\n    CHECK ( hipMemcpy(C_h, C_d, Nbytes, hipMemcpyDeviceToHost));  \/\/ copy (*dest, *source, Type).\n\n\/\/  if (verbose) fprintf (stderr, \"info: check result\\n\");\n\/\/  for (size_t i=0; i<N; i++)  {\n\/\/      if (C_h[i] != A_h[i] * A_h[i]) {              \/\/ If value received is not square of value sent,\n\/\/          CHECK(hipErrorUnknown);                   \/\/ ... We have a problem!\n\/\/      }\n\/\/  }\n\n    \/\/ We passed. Now we need to read the event.\n    if (verbose) fprintf(stderr, \"Passed. info: About to read event with PAPI_stop.\\n\");\n    ret = PAPI_stop( EventSet, values );\n    if (ret != PAPI_OK ) {\n        fprintf(stderr,\"Error! PAPI_stop failed.\\n\");\n        if (verbose) fprintf(stderr, \"PAPI_stop failed.\\n\");\n        exit(ret);\n    }\n    \n    if (verbose) fprintf (stderr, \"PAPI_stop succeeded.\\n\");\n\n} \/\/ end conductTest.\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Main program.\n\/\/-----------------------------------------------------------------------------\nint main(int argc, char *argv[])\n{\n    int devices, device, i = 0;\n    char str[64];\n\n    \/\/ Parse command line arguments\n    parseCommandLineArgs(argc, argv);\n\n    \/\/ fprintf(stderr, \"Setup PAPI counters internally (PAPI)\\n\");\n    int EventSet = PAPI_NULL;\n    int eventCount;\n    int ret;\n    int k, m, cid=-1;\n\n    \/* PAPI Initialization *\/\n    ret = PAPI_library_init(PAPI_VER_CURRENT);\n    if(ret != PAPI_VER_CURRENT) {\n        fprintf(stderr, \"PAPI_library_init failed, ret=%i [%s]\\n\", \n            ret, PAPI_strerror(ret));\n        exit(-1);\n    }\n\n    printf(\"PAPI version: %d.%d.%d\\n\", \n        PAPI_VERSION_MAJOR(PAPI_VERSION), \n        PAPI_VERSION_MINOR(PAPI_VERSION), \n        PAPI_VERSION_REVISION(PAPI_VERSION));\n    fflush(stdout);\n\n    \/\/ Find rocm_smi component index.\n    k = PAPI_num_components();                                          \/\/ get number of components.\n    for (i=0; i<k && cid<0; i++) {                                      \/\/ while not found,\n        PAPI_component_info_t *aComponent = \n            (PAPI_component_info_t*) PAPI_get_component_info(i);        \/\/ get the component info.     \n        if (aComponent == NULL) {                                       \/\/ if we failed,\n            fprintf(stderr,  \"PAPI_get_component_info(%i) failed, \"\n                \"returned NULL. %i components reported.\\n\", i,k);\n            exit(-1);    \n        }\n\n       if (strcmp(\"rocm_smi\", aComponent->name) == 0) cid=i;            \/\/ If we found our match, record it.\n    } \/\/ end search components.\n\n    if (cid < 0) {                                                      \/\/ if no PCP component found,\n        fprintf(stderr, \"Failed to find rocm_smi component among %i \"\n            \"reported components.\\n\", k);\n        PAPI_shutdown();\n        exit(-1); \n    }\n\n    printf(\"Found ROCM_SMI Component at id %d\\n\", cid);\n\n    \/\/ Add events at a GPU specific level ... eg rocm:::device=0:Whatever\n    eventCount = 0;\n    int eventsRead=0;\n\n   \/\/ Begin enumeration of all events.\n\n    long long value=0;                                              \/\/ The only value we read.\n    std::string eventName;\n    eventName = \"rocm_smi:::NUMDevices\";\n\n    CALL_PAPI_OK(PAPI_create_eventset(&EventSet)); \n    CALL_PAPI_OK(PAPI_assign_eventset_component(EventSet, cid)); \n    ret = PAPI_add_named_event(EventSet, eventName.c_str());  \n    if (ret == PAPI_OK) {\n        CALL_PAPI_OK(PAPI_start(EventSet));\n        CALL_PAPI_OK(PAPI_stop(EventSet, &value));\n        devices = value;\n        printf(\"Found %i devices.\\n\", devices);\n    } else {\n        fprintf(stderr, \"FAILED to add event '%s', ret=%i='%s'.\\n\", eventName.c_str(), ret, PAPI_strerror(ret));\n        CALL_PAPI_OK(PAPI_cleanup_eventset(EventSet));          \/\/ Delete all events in set.\n        CALL_PAPI_OK(PAPI_destroy_eventset(&EventSet));         \/\/ destroy the event set.\n        exit(-1);\n    }\n\n    \/\/ Do something.\n    CALL_PAPI_OK(PAPI_cleanup_eventset(EventSet));              \/\/ Delete all events in set.\n\n    eventName = \"rocm_smi:::device=0:sensor=0:fan_speed\";\n    ret = PAPI_add_named_event(EventSet, eventName.c_str());\n    if (ret != PAPI_OK) {\n        fprintf(stderr, \"FAILED to add event '%s', ret=%i='%s'.\\n\", eventName.c_str(), ret, PAPI_strerror(ret));\n        CALL_PAPI_OK(PAPI_cleanup_eventset(EventSet));          \/\/ Delete all events in set.\n        exit(-1);\n    }\n\n    eventName = \"rocm_smi:::device=0:sensor=0:fan_speed_max\";\n    ret = PAPI_add_named_event(EventSet, eventName.c_str());\n    if (ret != PAPI_OK) {\n        fprintf(stderr, \"FAILED to add event '%s', ret=%i='%s'.\\n\", eventName.c_str(), ret, PAPI_strerror(ret));\n        CALL_PAPI_OK(PAPI_cleanup_eventset(EventSet));          \/\/ Delete all events in set.\n        exit(-1);\n    }\n\n    long long curmax[2];\n    CALL_PAPI_OK(PAPI_start(EventSet));\n    CALL_PAPI_OK(PAPI_stop(EventSet, curmax));\n    printf(\"Fan speed: current=%lli maximum=%lli.\\n\", curmax[0], curmax[1]);\n    CALL_PAPI_OK(PAPI_cleanup_eventset(EventSet));              \/\/ Delete all events in set.\n\n    curmax[0]=128;\n    eventName = \"rocm_smi:::device=0:sensor=0:fan_speed\";\n    ret = PAPI_add_named_event(EventSet, eventName.c_str());\n    if (ret != PAPI_OK) {\n        fprintf(stderr, \"FAILED to add event '%s', ret=%i='%s'.\\n\", eventName.c_str(), ret, PAPI_strerror(ret));\n        CALL_PAPI_OK(PAPI_cleanup_eventset(EventSet));          \/\/ Delete all events in set.\n        exit(-1);\n    }\n\n    CALL_PAPI_OK(PAPI_start(EventSet));\n    ret = PAPI_write(EventSet, curmax);\n    if ( ret != PAPI_OK ) {\n        PAPI_stop(EventSet, curmax);                                \/\/ Must be stopped.\n        PAPI_cleanup_eventset(EventSet);                            \/\/ Empty it.\n        PAPI_destroy_eventset(&EventSet);                           \/\/ Release memory.\n        fprintf(stderr, \"PAPI_write failure returned %i, = %s.\\n\", ret, PAPI_strerror(ret));\n    } else {\n        printf(\"Call succeeded to set fan_speed to %llu RPM.\\n\", curmax[0]);\n    }\n\n    \/\/ Now try to read it. \n    CALL_PAPI_OK(PAPI_stop(EventSet, &value));\n    printf(\"After set, read-back of fan value is %lli.\\n\", value);\n\n    CALL_PAPI_OK(PAPI_cleanup_eventset(EventSet));              \/\/ Delete all events in set.\n    CALL_PAPI_OK(PAPI_destroy_eventset(&EventSet));             \/\/ destroy the event set.\n\n    printf(\"Finished All Events.\\n\");\n\n    PAPI_shutdown();                                            \/\/ Returns no value.\n    return(0);                                                  \/\/ exit OK.\n} \/\/ end MAIN.\n","avg_line_length":40.7090909091,"max_line_length":119,"alphanum_fraction":0.5186839363,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":80290,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Zlib"],"max_stars_count":null,"content":"#include \"b3RobotSimulatorClientAPI_NoDirect.h\"\n\n#include \"PhysicsClientC_API.h\"\n#include \"b3RobotSimulatorClientAPI_InternalData.h\"\n\n#include \"SharedMemoryPublic.h\"\n#include \"Bullet3Common\/b3Logging.h\"\n\nstatic void scalarToDouble3(btScalar a[3], double b[3])\n{\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tb[i] = a[i];\n\t}\n}\n\nstatic void scalarToDouble4(btScalar a[4], double b[4])\n{\n\tfor (int i = 0; i < 4; i++)\n\t{\n\t\tb[i] = a[i];\n\t}\n}\n\nb3RobotSimulatorClientAPI_NoDirect::b3RobotSimulatorClientAPI_NoDirect()\n{\n\tm_data = new b3RobotSimulatorClientAPI_InternalData();\n}\n\nb3RobotSimulatorClientAPI_NoDirect::~b3RobotSimulatorClientAPI_NoDirect()\n{\n\tdelete m_data;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::isConnected() const\n{\n\treturn (m_data->m_physicsClientHandle != 0);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::setTimeOut(double timeOutInSec)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\tb3SetTimeOut(m_data->m_physicsClientHandle, timeOutInSec);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::disconnect()\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n#ifndef BT_DISABLE_PHYSICS_DIRECT\n\tb3DisconnectSharedMemory(m_data->m_physicsClientHandle);\n\tm_data->m_physicsClientHandle = 0;\n#endif\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::syncBodies()\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tcommand = b3InitSyncBodyInfoCommand(m_data->m_physicsClientHandle);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\tstatusType = b3GetStatusType(statusHandle);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::resetSimulation()\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\tb3SharedMemoryStatusHandle statusHandle;\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(\n\t\tm_data->m_physicsClientHandle, b3InitResetSimulationCommand(m_data->m_physicsClientHandle));\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::resetSimulation(int flag)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\tb3SharedMemoryStatusHandle statusHandle;\n\tb3SharedMemoryCommandHandle command = b3InitResetSimulationCommand(m_data->m_physicsClientHandle);\n\tb3InitResetSimulationSetFlags(command, flag);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::canSubmitCommand() const\n{\n\tif (!isConnected())\n\t{\n\t\treturn false;\n\t}\n\treturn (b3CanSubmitCommand(m_data->m_physicsClientHandle) != 0);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::stepSimulation()\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\tif (b3CanSubmitCommand(m_data->m_physicsClientHandle))\n\t{\n\t\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, b3InitStepSimulationCommand(m_data->m_physicsClientHandle));\n\t\tstatusType = b3GetStatusType(statusHandle);\n\t\t\/\/btAssert(statusType == CMD_STEP_FORWARD_SIMULATION_COMPLETED);\n\t}\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::setGravity(const btVector3& gravityAcceleration)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\tbtAssert(b3CanSubmitCommand(m_data->m_physicsClientHandle));\n\n\tb3SharedMemoryCommandHandle command = b3InitPhysicsParamCommand(m_data->m_physicsClientHandle);\n\tb3SharedMemoryStatusHandle statusHandle;\n\tb3PhysicsParamSetGravity(command, gravityAcceleration[0], gravityAcceleration[1], gravityAcceleration[2]);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\t\/\/\tbtAssert(b3GetStatusType(statusHandle) == CMD_CLIENT_COMMAND_COMPLETED);\n}\n\nbtQuaternion b3RobotSimulatorClientAPI_NoDirect::getQuaternionFromEuler(const btVector3& rollPitchYaw)\n{\n\tbtQuaternion q;\n\tq.setEulerZYX(rollPitchYaw[2], rollPitchYaw[1], rollPitchYaw[0]);\n\treturn q;\n}\n\nbtVector3 b3RobotSimulatorClientAPI_NoDirect::getEulerFromQuaternion(const btQuaternion& quat)\n{\n\tbtScalar roll, pitch, yaw;\n\tquat.getEulerZYX(yaw, pitch, roll);\n\tbtVector3 rpy2 = btVector3(roll, pitch, yaw);\n\treturn rpy2;\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::loadTexture(const std::string& fileName)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn -1;\n\t}\n\tbtAssert(b3CanSubmitCommand(m_data->m_physicsClientHandle));\n\n\tb3SharedMemoryCommandHandle commandHandle;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\t{\n\t\tcommandHandle = b3InitLoadTexture(m_data->m_physicsClientHandle, fileName.c_str());\n\n\t\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\t\tstatusType = b3GetStatusType(statusHandle);\n\t\tif (statusType == CMD_LOAD_TEXTURE_COMPLETED)\n\t\t{\n\t\t\treturn b3GetStatusTextureUniqueId(statusHandle);\n\t\t}\n\t}\n\treturn -1;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::changeVisualShape(const struct b3RobotSimulatorChangeVisualShapeArgs& args)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tint objectUniqueId = args.m_objectUniqueId;\n\tint jointIndex = args.m_linkIndex;\n\tint shapeIndex = args.m_shapeIndex;\n\tint textureUniqueId = args.m_textureUniqueId;\n\n\tb3SharedMemoryCommandHandle commandHandle;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tcommandHandle = b3InitUpdateVisualShape2(m_data->m_physicsClientHandle, objectUniqueId, jointIndex, shapeIndex);\n\n\tif (textureUniqueId>=-1)\n\t{\n\t\tb3UpdateVisualShapeTexture(commandHandle, textureUniqueId);\n\t}\n\n\tif (args.m_hasSpecularColor)\n\t{\n\t\tdouble specularColor[3] = {args.m_specularColor[0], args.m_specularColor[1], args.m_specularColor[2]};\n\t\tb3UpdateVisualShapeSpecularColor(commandHandle, specularColor);\n\t}\n\tif (args.m_hasRgbaColor)\n\t{\n\t\tdouble rgbaColor[4] = {args.m_rgbaColor[0], args.m_rgbaColor[1], args.m_rgbaColor[2], args.m_rgbaColor[3]};\n\t\tb3UpdateVisualShapeRGBAColor(commandHandle, rgbaColor);\n\t}\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\tstatusType = b3GetStatusType(statusHandle);\n\n\treturn (statusType == CMD_VISUAL_SHAPE_UPDATE_COMPLETED);\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::loadURDF(const std::string& fileName, const struct b3RobotSimulatorLoadUrdfFileArgs& args)\n{\n\tint robotUniqueId = -1;\n\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn robotUniqueId;\n\t}\n\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\tb3SharedMemoryCommandHandle command = b3LoadUrdfCommandInit(m_data->m_physicsClientHandle, fileName.c_str());\n\n\t\/\/setting the initial position, orientation and other arguments are optional\n\n\tb3LoadUrdfCommandSetFlags(command, args.m_flags);\n\n\tb3LoadUrdfCommandSetStartPosition(command, args.m_startPosition[0],\n\t\t\t\t\t\t\t\t\t  args.m_startPosition[1],\n\t\t\t\t\t\t\t\t\t  args.m_startPosition[2]);\n\tb3LoadUrdfCommandSetStartOrientation(command, args.m_startOrientation[0], args.m_startOrientation[1], args.m_startOrientation[2], args.m_startOrientation[3]);\n\tif (args.m_forceOverrideFixedBase)\n\t{\n\t\tb3LoadUrdfCommandSetUseFixedBase(command, true);\n\t}\n\tb3LoadUrdfCommandSetUseMultiBody(command, args.m_useMultiBody);\n\tb3LoadUrdfCommandSetGlobalScaling(command, args.m_globalScaling);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\tstatusType = b3GetStatusType(statusHandle);\n\n\tbtAssert(statusType == CMD_URDF_LOADING_COMPLETED);\n\tif (statusType == CMD_URDF_LOADING_COMPLETED)\n\t{\n\t\trobotUniqueId = b3GetStatusBodyIndex(statusHandle);\n\t}\n\treturn robotUniqueId;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::loadMJCF(const std::string& fileName, b3RobotSimulatorLoadFileResults& results)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\tb3SharedMemoryCommandHandle command;\n\n\tcommand = b3LoadMJCFCommandInit(m_data->m_physicsClientHandle, fileName.c_str());\n\tb3LoadMJCFCommandSetFlags(command, URDF_USE_IMPLICIT_CYLINDER);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\tstatusType = b3GetStatusType(statusHandle);\n\tif (statusType != CMD_MJCF_LOADING_COMPLETED)\n\t{\n\t\tb3Warning(\"Couldn't load .mjcf file.\");\n\t\treturn false;\n\t}\n\tint numBodies = b3GetStatusBodyIndices(statusHandle, 0, 0);\n\tif (numBodies)\n\t{\n\t\tresults.m_uniqueObjectIds.resize(numBodies);\n\t\tint numBodies;\n\t\tnumBodies = b3GetStatusBodyIndices(statusHandle, &results.m_uniqueObjectIds[0], results.m_uniqueObjectIds.size());\n\t}\n\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::savePythonWorld(const std::string& fileName)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\tb3SharedMemoryCommandHandle command;\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\n\tif (fileName.length() == 0)\n\t{\n\t\treturn false;\n\t}\n\n\tcommand = b3SaveWorldCommandInit(m_data->m_physicsClientHandle, fileName.c_str());\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\tstatusType = b3GetStatusType(statusHandle);\n\tif (statusType != CMD_SAVE_WORLD_COMPLETED)\n\t{\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::saveBullet(const std::string& fileName)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\tb3SharedMemoryCommandHandle command;\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\n\tif (fileName.length() == 0)\n\t{\n\t\treturn false;\n\t}\n\n\tcommand = b3SaveBulletCommandInit(m_data->m_physicsClientHandle, fileName.c_str());\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\tstatusType = b3GetStatusType(statusHandle);\n\tif (statusType != CMD_BULLET_SAVING_COMPLETED)\n\t{\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::loadBullet(const std::string& fileName, b3RobotSimulatorLoadFileResults& results)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\tb3SharedMemoryCommandHandle command;\n\n\tcommand = b3LoadBulletCommandInit(m_data->m_physicsClientHandle, fileName.c_str());\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\tstatusType = b3GetStatusType(statusHandle);\n\tif (statusType != CMD_BULLET_LOADING_COMPLETED)\n\t{\n\t\treturn false;\n\t}\n\tint numBodies = b3GetStatusBodyIndices(statusHandle, 0, 0);\n\tif (numBodies)\n\t{\n\t\tresults.m_uniqueObjectIds.resize(numBodies);\n\t\tint numBodies;\n\t\tnumBodies = b3GetStatusBodyIndices(statusHandle, &results.m_uniqueObjectIds[0], results.m_uniqueObjectIds.size());\n\t}\n\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::loadSDF(const std::string& fileName, b3RobotSimulatorLoadFileResults& results, const struct b3RobotSimulatorLoadSdfFileArgs& args)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tbool statusOk = false;\n\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\tb3SharedMemoryCommandHandle command = b3LoadSdfCommandInit(m_data->m_physicsClientHandle, fileName.c_str());\n\tb3LoadSdfCommandSetUseMultiBody(command, args.m_useMultiBody);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\tstatusType = b3GetStatusType(statusHandle);\n\tbtAssert(statusType == CMD_SDF_LOADING_COMPLETED);\n\tif (statusType == CMD_SDF_LOADING_COMPLETED)\n\t{\n\t\tint numBodies = b3GetStatusBodyIndices(statusHandle, 0, 0);\n\t\tif (numBodies)\n\t\t{\n\t\t\tresults.m_uniqueObjectIds.resize(numBodies);\n\t\t\tint numBodies;\n\t\t\tnumBodies = b3GetStatusBodyIndices(statusHandle, &results.m_uniqueObjectIds[0], results.m_uniqueObjectIds.size());\n\t\t}\n\t\tstatusOk = true;\n\t}\n\n\treturn statusOk;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getBodyInfo(int bodyUniqueId, struct b3BodyInfo* bodyInfo)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tint result = b3GetBodyInfo(m_data->m_physicsClientHandle, bodyUniqueId, bodyInfo);\n\treturn (result != 0);\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getBasePositionAndOrientation(int bodyUniqueId, btVector3& basePosition, btQuaternion& baseOrientation) const\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tb3SharedMemoryCommandHandle cmd_handle =\n\t\tb3RequestActualStateCommandInit(m_data->m_physicsClientHandle, bodyUniqueId);\n\tb3SharedMemoryStatusHandle status_handle =\n\t\tb3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, cmd_handle);\n\n\tconst int status_type = b3GetStatusType(status_handle);\n\tconst double* actualStateQ;\n\n\tif (status_type != CMD_ACTUAL_STATE_UPDATE_COMPLETED)\n\t{\n\t\treturn false;\n\t}\n\n\tb3GetStatusActualState(\n\t\tstatus_handle, 0 \/* body_unique_id *\/,\n\t\t0 \/* num_degree_of_freedom_q *\/, 0 \/* num_degree_of_freedom_u *\/,\n\t\t0 \/*root_local_inertial_frame*\/, &actualStateQ,\n\t\t0 \/* actual_state_q_dot *\/, 0 \/* joint_reaction_forces *\/);\n\n\tbasePosition[0] = actualStateQ[0];\n\tbasePosition[1] = actualStateQ[1];\n\tbasePosition[2] = actualStateQ[2];\n\n\tbaseOrientation[0] = actualStateQ[3];\n\tbaseOrientation[1] = actualStateQ[4];\n\tbaseOrientation[2] = actualStateQ[5];\n\tbaseOrientation[3] = actualStateQ[6];\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::resetBasePositionAndOrientation(int bodyUniqueId, const btVector3& basePosition, const btQuaternion& baseOrientation)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tb3SharedMemoryCommandHandle commandHandle;\n\n\tcommandHandle = b3CreatePoseCommandInit(m_data->m_physicsClientHandle, bodyUniqueId);\n\n\tb3CreatePoseCommandSetBasePosition(commandHandle, basePosition[0], basePosition[1], basePosition[2]);\n\tb3CreatePoseCommandSetBaseOrientation(commandHandle, baseOrientation[0], baseOrientation[1],\n\t\t\t\t\t\t\t\t\t\t  baseOrientation[2], baseOrientation[3]);\n\n\tb3SharedMemoryStatusHandle statusHandle;\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getBaseVelocity(int bodyUniqueId, btVector3& baseLinearVelocity, btVector3& baseAngularVelocity) const\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tb3SharedMemoryCommandHandle command = b3RequestActualStateCommandInit(m_data->m_physicsClientHandle, bodyUniqueId);\n\tb3SharedMemoryStatusHandle statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\n\tconst int status_type = b3GetStatusType(statusHandle);\n\tconst double* actualStateQdot;\n\n\tif (status_type != CMD_ACTUAL_STATE_UPDATE_COMPLETED)\n\t{\n\t\treturn false;\n\t}\n\n\tb3GetStatusActualState(statusHandle, 0 \/* body_unique_id *\/,\n\t\t\t\t\t\t   0 \/* num_degree_of_freedom_q *\/, 0 \/* num_degree_of_freedom_u *\/,\n\t\t\t\t\t\t   0 \/*root_local_inertial_frame*\/, 0,\n\t\t\t\t\t\t   &actualStateQdot, 0 \/* joint_reaction_forces *\/);\n\n\tbaseLinearVelocity[0] = actualStateQdot[0];\n\tbaseLinearVelocity[1] = actualStateQdot[1];\n\tbaseLinearVelocity[2] = actualStateQdot[2];\n\n\tbaseAngularVelocity[0] = actualStateQdot[3];\n\tbaseAngularVelocity[1] = actualStateQdot[4];\n\tbaseAngularVelocity[2] = actualStateQdot[5];\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::resetBaseVelocity(int bodyUniqueId, const btVector3& linearVelocity, const btVector3& angularVelocity) const\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tb3SharedMemoryCommandHandle commandHandle;\n\tb3SharedMemoryStatusHandle statusHandle;\n\n\tcommandHandle = b3CreatePoseCommandInit(m_data->m_physicsClientHandle, bodyUniqueId);\n\n\tbtVector3DoubleData linVelDouble;\n\tlinearVelocity.serializeDouble(linVelDouble);\n\tb3CreatePoseCommandSetBaseLinearVelocity(commandHandle, linVelDouble.m_floats);\n\n\tbtVector3DoubleData angVelDouble;\n\tangularVelocity.serializeDouble(angVelDouble);\n\tb3CreatePoseCommandSetBaseAngularVelocity(commandHandle, angVelDouble.m_floats);\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\treturn true;\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::setInternalSimFlags(int flags)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\t{\n\t\tb3SharedMemoryCommandHandle command = b3InitPhysicsParamCommand(m_data->m_physicsClientHandle);\n\t\tb3SharedMemoryStatusHandle statusHandle;\n\t\tb3PhysicsParamSetInternalSimFlags(command, flags);\n\t\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\t}\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::setRealTimeSimulation(bool enableRealTimeSimulation)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tb3SharedMemoryCommandHandle command = b3InitPhysicsParamCommand(m_data->m_physicsClientHandle);\n\tb3SharedMemoryStatusHandle statusHandle;\n\n\tb3PhysicsParamSetRealTimeSimulation(command, enableRealTimeSimulation);\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\n\tbtAssert(b3GetStatusType(statusHandle) == CMD_CLIENT_COMMAND_COMPLETED);\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::getNumJoints(int bodyUniqueId) const\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\treturn b3GetNumJoints(m_data->m_physicsClientHandle, bodyUniqueId);\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getJointInfo(int bodyUniqueId, int jointIndex, b3JointInfo* jointInfo)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\treturn (b3GetJointInfo(m_data->m_physicsClientHandle, bodyUniqueId, jointIndex, jointInfo) != 0);\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::createConstraint(int parentBodyIndex, int parentJointIndex, int childBodyIndex, int childJointIndex, b3JointInfo* jointInfo)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn -1;\n\t}\n\tb3SharedMemoryStatusHandle statusHandle;\n\tbtAssert(b3CanSubmitCommand(m_data->m_physicsClientHandle));\n\tif (b3CanSubmitCommand(m_data->m_physicsClientHandle))\n\t{\n\t\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, b3InitCreateUserConstraintCommand(m_data->m_physicsClientHandle, parentBodyIndex, parentJointIndex, childBodyIndex, childJointIndex, jointInfo));\n\t\tint statusType = b3GetStatusType(statusHandle);\n\t\tif (statusType == CMD_USER_CONSTRAINT_COMPLETED)\n\t\t{\n\t\t\tint userConstraintUid = b3GetStatusUserConstraintUniqueId(statusHandle);\n\t\t\treturn userConstraintUid;\n\t\t}\n\t}\n\treturn -1;\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::changeConstraint(int constraintId, b3RobotUserConstraint* jointInfo)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn -1;\n\t}\n\tb3SharedMemoryCommandHandle commandHandle = b3InitChangeUserConstraintCommand(m_data->m_physicsClientHandle, constraintId);\n\n\tif (jointInfo->m_userUpdateFlags & USER_CONSTRAINT_CHANGE_MAX_FORCE)\n\t{\n\t\tb3InitChangeUserConstraintSetMaxForce(commandHandle, jointInfo->m_maxAppliedForce);\n\t}\n\n\tif (jointInfo->m_userUpdateFlags & USER_CONSTRAINT_CHANGE_GEAR_RATIO)\n\t{\n\t\tb3InitChangeUserConstraintSetGearRatio(commandHandle, jointInfo->m_gearRatio);\n\t}\n\n\tif (jointInfo->m_userUpdateFlags & USER_CONSTRAINT_CHANGE_ERP)\n\t{\n\t\tb3InitChangeUserConstraintSetERP(commandHandle, jointInfo->m_erp);\n\t}\n\tif (jointInfo->m_userUpdateFlags & USER_CONSTRAINT_CHANGE_GEAR_AUX_LINK)\n\t{\n\t\tb3InitChangeUserConstraintSetGearAuxLink(commandHandle, jointInfo->m_gearAuxLink);\n\t}\n\n\tif (jointInfo->m_userUpdateFlags & USER_CONSTRAINT_CHANGE_RELATIVE_POSITION_TARGET)\n\t{\n\t\tb3InitChangeUserConstraintSetRelativePositionTarget(commandHandle, jointInfo->m_relativePositionTarget);\n\t}\n\t\n\tif (jointInfo->m_userUpdateFlags & USER_CONSTRAINT_CHANGE_PIVOT_IN_B)\n\t{\n\t\tb3InitChangeUserConstraintSetPivotInB(commandHandle, &jointInfo->m_childFrame[0]);\n\t}\n\tif (jointInfo->m_userUpdateFlags & USER_CONSTRAINT_CHANGE_FRAME_ORN_IN_B)\n\t{\n\t\tb3InitChangeUserConstraintSetFrameInB(commandHandle, &jointInfo->m_childFrame[3]);\n\t}\n\n\tb3SharedMemoryStatusHandle statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\tint statusType = b3GetStatusType(statusHandle);\n\treturn statusType;\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::removeConstraint(int constraintId)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\tb3SharedMemoryCommandHandle commandHandle = b3InitRemoveUserConstraintCommand(m_data->m_physicsClientHandle, constraintId);\n\tb3SharedMemoryStatusHandle statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\tb3GetStatusType(statusHandle);\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getConstraintInfo(int constraintUniqueId, struct b3UserConstraint& constraintInfo)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tif (b3GetUserConstraintInfo(m_data->m_physicsClientHandle, constraintUniqueId, &constraintInfo))\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getJointState(int bodyUniqueId, int jointIndex, struct b3JointSensorState* state)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command = b3RequestActualStateCommandInit(m_data->m_physicsClientHandle, bodyUniqueId);\n\tb3SharedMemoryStatusHandle statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\tint statusType = b3GetStatusType(statusHandle);\n\tif (statusType == CMD_ACTUAL_STATE_UPDATE_COMPLETED)\n\t{\n\t\tif (b3GetJointState(m_data->m_physicsClientHandle, statusHandle, jointIndex, state))\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getJointStates(int bodyUniqueId, b3JointStates2& state)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tb3SharedMemoryCommandHandle command = b3RequestActualStateCommandInit(m_data->m_physicsClientHandle, bodyUniqueId);\n\tb3SharedMemoryStatusHandle statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\n\tif (statusHandle)\n\t{\n\t\t\/\/   double rootInertialFrame[7];\n\t\tconst double* rootLocalInertialFrame;\n\t\tconst double* actualStateQ;\n\t\tconst double* actualStateQdot;\n\t\tconst double* jointReactionForces;\n\n\t\tint stat = b3GetStatusActualState(statusHandle,\n\t\t\t\t\t\t\t\t\t\t  &state.m_bodyUniqueId,\n\t\t\t\t\t\t\t\t\t\t  &state.m_numDegreeOfFreedomQ,\n\t\t\t\t\t\t\t\t\t\t  &state.m_numDegreeOfFreedomU,\n\t\t\t\t\t\t\t\t\t\t  &rootLocalInertialFrame,\n\t\t\t\t\t\t\t\t\t\t  &actualStateQ,\n\t\t\t\t\t\t\t\t\t\t  &actualStateQdot,\n\t\t\t\t\t\t\t\t\t\t  &jointReactionForces);\n\t\tif (stat)\n\t\t{\n\t\t\tstate.m_actualStateQ.resize(state.m_numDegreeOfFreedomQ);\n\t\t\tstate.m_actualStateQdot.resize(state.m_numDegreeOfFreedomU);\n\n\t\t\tfor (int i = 0; i < state.m_numDegreeOfFreedomQ; i++)\n\t\t\t{\n\t\t\t\tstate.m_actualStateQ[i] = actualStateQ[i];\n\t\t\t}\n\t\t\tfor (int i = 0; i < state.m_numDegreeOfFreedomU; i++)\n\t\t\t{\n\t\t\t\tstate.m_actualStateQdot[i] = actualStateQdot[i];\n\t\t\t}\n\t\t\tint numJoints = getNumJoints(bodyUniqueId);\n\t\t\tstate.m_jointReactionForces.resize(6 * numJoints);\n\t\t\tfor (int i = 0; i < numJoints * 6; i++)\n\t\t\t{\n\t\t\t\tstate.m_jointReactionForces[i] = jointReactionForces[i];\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\t\t\/\/rootInertialFrame,\n\t\t\/\/              &state.m_actualStateQ[0],\n\t\t\/\/            &state.m_actualStateQdot[0],\n\t\t\/\/          &state.m_jointReactionForces[0]);\n\t}\n\treturn false;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::resetJointState(int bodyUniqueId, int jointIndex, double targetValue)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle commandHandle;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint numJoints;\n\n\tnumJoints = b3GetNumJoints(m_data->m_physicsClientHandle, bodyUniqueId);\n\tif ((jointIndex >= numJoints) || (jointIndex < 0))\n\t{\n\t\treturn false;\n\t}\n\n\tcommandHandle = b3CreatePoseCommandInit(m_data->m_physicsClientHandle, bodyUniqueId);\n\n\tb3CreatePoseCommandSetJointPosition(m_data->m_physicsClientHandle, commandHandle, jointIndex,\n\t\t\t\t\t\t\t\t\t\ttargetValue);\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\treturn false;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::resetJointVelocity(int bodyUniqueId, int jointIndex, double targetValue)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle commandHandle;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint numJoints;\n\n\tnumJoints = b3GetNumJoints(m_data->m_physicsClientHandle, bodyUniqueId);\n\tif ((jointIndex >= numJoints) || (jointIndex < 0))\n\t{\n\t\treturn false;\n\t}\n\n\tcommandHandle = b3CreatePoseCommandInit(m_data->m_physicsClientHandle, bodyUniqueId);\n\tb3CreatePoseCommandSetJointVelocity(m_data->m_physicsClientHandle,commandHandle,jointIndex,targetValue);\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\treturn false;\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::setJointMotorControl(int bodyUniqueId, int jointIndex, const b3RobotSimulatorJointMotorArgs& args)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\tb3SharedMemoryStatusHandle statusHandle;\n\tswitch (args.m_controlMode)\n\t{\n\t\tcase CONTROL_MODE_VELOCITY:\n\t\t{\n\t\t\tb3SharedMemoryCommandHandle command = b3JointControlCommandInit2(m_data->m_physicsClientHandle, bodyUniqueId, CONTROL_MODE_VELOCITY);\n\t\t\tb3JointInfo jointInfo;\n\t\t\tb3GetJointInfo(m_data->m_physicsClientHandle, bodyUniqueId, jointIndex, &jointInfo);\n\t\t\tint uIndex = jointInfo.m_uIndex;\n\t\t\tif (uIndex >= 0)\n\t\t\t{\n\t\t\t\tb3JointControlSetKd(command, uIndex, args.m_kd);\n\t\t\t\tb3JointControlSetDesiredVelocity(command, uIndex, args.m_targetVelocity);\n\t\t\t\tb3JointControlSetMaximumForce(command, uIndex, args.m_maxTorqueValue);\n\t\t\t\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase CONTROL_MODE_POSITION_VELOCITY_PD:\n\t\t{\n\t\t\tb3SharedMemoryCommandHandle command = b3JointControlCommandInit2(m_data->m_physicsClientHandle, bodyUniqueId, CONTROL_MODE_POSITION_VELOCITY_PD);\n\t\t\tb3JointInfo jointInfo;\n\t\t\tb3GetJointInfo(m_data->m_physicsClientHandle, bodyUniqueId, jointIndex, &jointInfo);\n\t\t\tint uIndex = jointInfo.m_uIndex;\n\t\t\tint qIndex = jointInfo.m_qIndex;\n\n\t\t\tb3JointControlSetDesiredPosition(command, qIndex, args.m_targetPosition);\n\t\t\tb3JointControlSetKp(command, uIndex, args.m_kp);\n\t\t\tb3JointControlSetDesiredVelocity(command, uIndex, args.m_targetVelocity);\n\t\t\tb3JointControlSetKd(command, uIndex, args.m_kd);\n\t\t\tb3JointControlSetMaximumForce(command, uIndex, args.m_maxTorqueValue);\n\t\t\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\t\t\tbreak;\n\t\t}\n\t\tcase CONTROL_MODE_TORQUE:\n\t\t{\n\t\t\tb3SharedMemoryCommandHandle command = b3JointControlCommandInit2(m_data->m_physicsClientHandle, bodyUniqueId, CONTROL_MODE_TORQUE);\n\t\t\tb3JointInfo jointInfo;\n\t\t\tb3GetJointInfo(m_data->m_physicsClientHandle, bodyUniqueId, jointIndex, &jointInfo);\n\t\t\tint uIndex = jointInfo.m_uIndex;\n\t\t\tif (uIndex >= 0)\n\t\t\t{\n\t\t\t\tb3JointControlSetDesiredForceTorque(command, uIndex, args.m_maxTorqueValue);\n\t\t\t\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase CONTROL_MODE_PD:\n\t\t{\n\t\t\tb3SharedMemoryCommandHandle command = b3JointControlCommandInit2(m_data->m_physicsClientHandle, bodyUniqueId, CONTROL_MODE_PD);\n\t\t\tb3JointInfo jointInfo;\n\t\t\tb3GetJointInfo(m_data->m_physicsClientHandle, bodyUniqueId, jointIndex, &jointInfo);\n\t\t\tint uIndex = jointInfo.m_uIndex;\n\t\t\tint qIndex = jointInfo.m_qIndex;\n\n\t\t\tb3JointControlSetDesiredPosition(command, qIndex, args.m_targetPosition);\n\t\t\tb3JointControlSetKp(command, uIndex, args.m_kp);\n\t\t\tb3JointControlSetDesiredVelocity(command, uIndex, args.m_targetVelocity);\n\t\t\tb3JointControlSetKd(command, uIndex, args.m_kd);\n\t\t\tb3JointControlSetMaximumForce(command, uIndex, args.m_maxTorqueValue);\n\t\t\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t{\n\t\t\tb3Error(\"Unknown control command in b3RobotSimulationClientAPI::setJointMotorControl\");\n\t\t}\n\t}\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::setNumSolverIterations(int numIterations)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\tb3SharedMemoryCommandHandle command = b3InitPhysicsParamCommand(m_data->m_physicsClientHandle);\n\tb3SharedMemoryStatusHandle statusHandle;\n\tb3PhysicsParamSetNumSolverIterations(command, numIterations);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\tbtAssert(b3GetStatusType(statusHandle) == CMD_CLIENT_COMMAND_COMPLETED);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::setContactBreakingThreshold(double threshold)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\tb3SharedMemoryCommandHandle command = b3InitPhysicsParamCommand(m_data->m_physicsClientHandle);\n\tb3SharedMemoryStatusHandle statusHandle;\n\tb3PhysicsParamSetContactBreakingThreshold(command, threshold);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\tbtAssert(b3GetStatusType(statusHandle) == CMD_CLIENT_COMMAND_COMPLETED);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::setTimeStep(double timeStepInSeconds)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tb3SharedMemoryCommandHandle command = b3InitPhysicsParamCommand(m_data->m_physicsClientHandle);\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint ret;\n\tret = b3PhysicsParamSetTimeStep(command, timeStepInSeconds);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::setNumSimulationSubSteps(int numSubSteps)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\tb3SharedMemoryCommandHandle command = b3InitPhysicsParamCommand(m_data->m_physicsClientHandle);\n\tb3SharedMemoryStatusHandle statusHandle;\n\tb3PhysicsParamSetNumSubSteps(command, numSubSteps);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\tbtAssert(b3GetStatusType(statusHandle) == CMD_CLIENT_COMMAND_COMPLETED);\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::calculateInverseKinematics(const struct b3RobotSimulatorInverseKinematicArgs& args, struct b3RobotSimulatorInverseKinematicsResults& results)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tbtAssert(args.m_endEffectorLinkIndex >= 0);\n\tbtAssert(args.m_bodyUniqueId >= 0);\n\n\tb3SharedMemoryCommandHandle command = b3CalculateInverseKinematicsCommandInit(m_data->m_physicsClientHandle, args.m_bodyUniqueId);\n\tif ((args.m_flags & B3_HAS_IK_TARGET_ORIENTATION) && (args.m_flags & B3_HAS_NULL_SPACE_VELOCITY))\n\t{\n\t\tb3CalculateInverseKinematicsPosOrnWithNullSpaceVel(command, args.m_numDegreeOfFreedom, args.m_endEffectorLinkIndex, args.m_endEffectorTargetPosition, args.m_endEffectorTargetOrientation, &args.m_lowerLimits[0], &args.m_upperLimits[0], &args.m_jointRanges[0], &args.m_restPoses[0]);\n\t}\n\telse if (args.m_flags & B3_HAS_IK_TARGET_ORIENTATION)\n\t{\n\t\tb3CalculateInverseKinematicsAddTargetPositionWithOrientation(command, args.m_endEffectorLinkIndex, args.m_endEffectorTargetPosition, args.m_endEffectorTargetOrientation);\n\t}\n\telse if (args.m_flags & B3_HAS_NULL_SPACE_VELOCITY)\n\t{\n\t\tb3CalculateInverseKinematicsPosWithNullSpaceVel(command, args.m_numDegreeOfFreedom, args.m_endEffectorLinkIndex, args.m_endEffectorTargetPosition, &args.m_lowerLimits[0], &args.m_upperLimits[0], &args.m_jointRanges[0], &args.m_restPoses[0]);\n\t}\n\telse\n\t{\n\t\tb3CalculateInverseKinematicsAddTargetPurePosition(command, args.m_endEffectorLinkIndex, args.m_endEffectorTargetPosition);\n\t}\n\n\tif (args.m_flags & B3_HAS_JOINT_DAMPING)\n\t{\n\t\tb3CalculateInverseKinematicsSetJointDamping(command, args.m_numDegreeOfFreedom, &args.m_jointDamping[0]);\n\t}\n\n\tif (args.m_flags & B3_HAS_CURRENT_POSITIONS)\n\t{\n\t\tb3CalculateInverseKinematicsSetCurrentPositions(command, args.m_numDegreeOfFreedom, &args.m_currentJointPositions[0]);\n\t}\n\n\tb3SharedMemoryStatusHandle statusHandle;\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\n\tint numPos = 0;\n\n\tbool result = b3GetStatusInverseKinematicsJointPositions(statusHandle,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &results.m_bodyUniqueId,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &numPos,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 0) != 0;\n\tif (result && numPos)\n\t{\n\t\tresults.m_calculatedJointPositions.resize(numPos);\n\t\tresult = b3GetStatusInverseKinematicsJointPositions(statusHandle,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t&results.m_bodyUniqueId,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t&numPos,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t&results.m_calculatedJointPositions[0]) != 0;\n\t}\n\treturn result;\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::computeDofCount(int bodyUniqueId) const\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn 0;\n\t}\n\treturn b3ComputeDofCount(m_data->m_physicsClientHandle, bodyUniqueId);\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::calculateMassMatrix(int bodyUniqueId, const double* jointPositions, int numJointPositions, double* massMatrix, int flags)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn 0;\n\t}\n\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\tb3SharedMemoryCommandHandle commandHandle =\n\t\tb3CalculateMassMatrixCommandInit(m_data->m_physicsClientHandle, bodyUniqueId, jointPositions, numJointPositions);\n\tb3CalculateMassMatrixSetFlags(commandHandle, flags);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\tstatusType = b3GetStatusType(statusHandle);\n\tif (statusType == CMD_CALCULATED_MASS_MATRIX_COMPLETED)\n\t{\n\t\tint dofCount;\n\t\tb3GetStatusMassMatrix(m_data->m_physicsClientHandle, statusHandle, &dofCount, NULL);\n\t\tif (dofCount)\n\t\t{\n\t\t\tb3GetStatusMassMatrix(m_data->m_physicsClientHandle, statusHandle, NULL, massMatrix);\n\t\t\treturn dofCount;\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getBodyJacobian(int bodyUniqueId, int linkIndex, const double* localPosition, const double* jointPositions, const double* jointVelocities, const double* jointAccelerations, double* linearJacobian, double* angularJacobian)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command = b3CalculateJacobianCommandInit(m_data->m_physicsClientHandle, bodyUniqueId, linkIndex, localPosition, jointPositions, jointVelocities, jointAccelerations);\n\tb3SharedMemoryStatusHandle statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\n\tif (b3GetStatusType(statusHandle) == CMD_CALCULATED_JACOBIAN_COMPLETED)\n\t{\n\t\tint dofCount;\n\t\tb3GetStatusJacobian(statusHandle, &dofCount, linearJacobian, angularJacobian);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getLinkState(int bodyUniqueId, int linkIndex, int computeLinkVelocity, int computeForwardKinematics, b3LinkState* linkState)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command = b3RequestActualStateCommandInit(m_data->m_physicsClientHandle, bodyUniqueId);\n\n\tif (computeLinkVelocity)\n\t{\n\t\tb3RequestActualStateCommandComputeLinkVelocity(command, computeLinkVelocity);\n\t}\n\n\tif (computeForwardKinematics)\n\t{\n\t\tb3RequestActualStateCommandComputeForwardKinematics(command, computeForwardKinematics);\n\t}\n\n\tb3SharedMemoryStatusHandle statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\n\tif (b3GetStatusType(statusHandle) == CMD_ACTUAL_STATE_UPDATE_COMPLETED)\n\t{\n\t\tb3GetLinkState(m_data->m_physicsClientHandle, statusHandle, linkIndex, linkState);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::configureDebugVisualizer(b3ConfigureDebugVisualizerEnum flag, int enable)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\tb3SharedMemoryCommandHandle commandHandle = b3InitConfigureOpenGLVisualizer(m_data->m_physicsClientHandle);\n\tb3ConfigureOpenGLVisualizerSetVisualizationFlags(commandHandle, flag, enable);\n\tb3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::getVREvents(b3VREventsData* vrEventsData, int deviceTypeFilter)\n{\n\tvrEventsData->m_numControllerEvents = 0;\n\tvrEventsData->m_controllerEvents = 0;\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tb3SharedMemoryCommandHandle commandHandle = b3RequestVREventsCommandInit(m_data->m_physicsClientHandle);\n\tb3VREventsSetDeviceTypeFilter(commandHandle, deviceTypeFilter);\n\tb3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\tb3GetVREventsData(m_data->m_physicsClientHandle, vrEventsData);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::getKeyboardEvents(b3KeyboardEventsData* keyboardEventsData)\n{\n\tkeyboardEventsData->m_numKeyboardEvents = 0;\n\tkeyboardEventsData->m_keyboardEvents = 0;\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tb3SharedMemoryCommandHandle commandHandle = b3RequestKeyboardEventsCommandInit(m_data->m_physicsClientHandle);\n\tb3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\tb3GetKeyboardEventsData(m_data->m_physicsClientHandle, keyboardEventsData);\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::startStateLogging(b3StateLoggingType loggingType, const std::string& fileName, const btAlignedObjectArray<int>& objectUniqueIds, int maxLogDof)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn -1;\n\t}\n\tint loggingUniqueId = -1;\n\tb3SharedMemoryCommandHandle commandHandle;\n\tcommandHandle = b3StateLoggingCommandInit(m_data->m_physicsClientHandle);\n\n\tb3StateLoggingStart(commandHandle, loggingType, fileName.c_str());\n\n\tfor (int i = 0; i < objectUniqueIds.size(); i++)\n\t{\n\t\tint objectUid = objectUniqueIds[i];\n\t\tb3StateLoggingAddLoggingObjectUniqueId(commandHandle, objectUid);\n\t}\n\n\tif (maxLogDof > 0)\n\t{\n\t\tb3StateLoggingSetMaxLogDof(commandHandle, maxLogDof);\n\t}\n\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\tstatusType = b3GetStatusType(statusHandle);\n\tif (statusType == CMD_STATE_LOGGING_START_COMPLETED)\n\t{\n\t\tloggingUniqueId = b3GetStatusLoggingUniqueId(statusHandle);\n\t}\n\treturn loggingUniqueId;\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::stopStateLogging(int stateLoggerUniqueId)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tb3SharedMemoryCommandHandle commandHandle;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tcommandHandle = b3StateLoggingCommandInit(m_data->m_physicsClientHandle);\n\tb3StateLoggingStop(commandHandle, stateLoggerUniqueId);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::resetDebugVisualizerCamera(double cameraDistance, double cameraPitch, double cameraYaw, const btVector3& targetPos)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tb3SharedMemoryCommandHandle commandHandle = b3InitConfigureOpenGLVisualizer(m_data->m_physicsClientHandle);\n\tif (commandHandle)\n\t{\n\t\tif ((cameraDistance >= 0))\n\t\t{\n\t\t\tbtVector3FloatData camTargetPos;\n\t\t\ttargetPos.serializeFloat(camTargetPos);\n\t\t\tb3ConfigureOpenGLVisualizerSetViewMatrix(commandHandle, cameraDistance, cameraPitch, cameraYaw, camTargetPos.m_floats);\n\t\t}\n\t\tb3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\t}\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::submitProfileTiming(const std::string& profileName)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tb3SharedMemoryCommandHandle commandHandle = b3ProfileTimingCommandInit(m_data->m_physicsClientHandle, profileName.c_str());\n\n\tif (profileName.length())\n\t{\n\t\tb3SetProfileTimingType(commandHandle, 0);\n\t}\n\telse\n\t{\n\t\tb3SetProfileTimingType(commandHandle, 1);\n\t}\n\n\tb3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::loadSoftBody(const std::string& fileName, const struct b3RobotSimulatorLoadSoftBodyArgs& args)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tb3SharedMemoryCommandHandle command = b3LoadSoftBodyCommandInit(m_data->m_physicsClientHandle, fileName.c_str());\n\tb3LoadSoftBodySetStartPosition(command, args.m_startPosition[0], args.m_startPosition[1], args.m_startPosition[2]);\n\tb3LoadSoftBodySetStartOrientation(command, args.m_startOrientation[0], args.m_startOrientation[1], args.m_startOrientation[2], args.m_startOrientation[3]);\n\tb3LoadSoftBodySetScale(command, args.m_scale);\n\tb3LoadSoftBodySetMass(command, args.m_mass);\n\tb3LoadSoftBodySetCollisionMargin(command, args.m_collisionMargin);\n\tb3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::loadDeformableBody(const std::string& fileName, const struct b3RobotSimulatorLoadDeformableBodyArgs& args)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tb3SharedMemoryCommandHandle command = b3LoadSoftBodyCommandInit(m_data->m_physicsClientHandle, fileName.c_str());\n\tb3LoadSoftBodySetStartPosition(command, args.m_startPosition[0], args.m_startPosition[1], args.m_startPosition[2]);\n\tb3LoadSoftBodySetStartOrientation(command, args.m_startOrientation[0], args.m_startOrientation[1], args.m_startOrientation[2], args.m_startOrientation[3]);\n\tb3LoadSoftBodySetScale(command, args.m_scale);\n\tb3LoadSoftBodySetMass(command, args.m_mass);\n\tb3LoadSoftBodySetCollisionMargin(command, args.m_collisionMargin);\n\tif (args.m_NeoHookeanMu > 0)\n\t{\n\t\tb3LoadSoftBodyAddNeoHookeanForce(command, args.m_NeoHookeanMu, args.m_NeoHookeanLambda, args.m_NeoHookeanDamping);\n\t}\n\tif (args.m_springElasticStiffness > 0)\n\t{\n\t\tb3LoadSoftBodyAddMassSpringForce(command, args.m_springElasticStiffness, args.m_springDampingStiffness);\n\t}\n\tb3LoadSoftBodySetSelfCollision(command, args.m_useSelfCollision);\n\tb3LoadSoftBodyUseFaceContact(command, args.m_useFaceContact);\n\tb3LoadSoftBodySetFrictionCoefficient(command, args.m_frictionCoeff);\n\tb3LoadSoftBodyUseBendingSprings(command, args.m_useBendingSprings, args.m_springBendingStiffness);\n\tb3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::getMouseEvents(b3MouseEventsData* mouseEventsData)\n{\n\tmouseEventsData->m_numMouseEvents = 0;\n\tmouseEventsData->m_mouseEvents = 0;\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tb3SharedMemoryCommandHandle command = b3RequestMouseEventsCommandInit(m_data->m_physicsClientHandle);\n\tb3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\tb3GetMouseEventsData(m_data->m_physicsClientHandle, mouseEventsData);\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getCameraImage(int width, int height, struct b3RobotSimulatorGetCameraImageArgs args, struct b3CameraImageData& imageData)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tb3SharedMemoryCommandHandle command;\n\n\tcommand = b3InitRequestCameraImage(m_data->m_physicsClientHandle);\n\n\tb3RequestCameraImageSetPixelResolution(command, width, height);\n\n\t\/\/ Check and apply optional arguments\n\tif (args.m_viewMatrix && args.m_projectionMatrix)\n\t{\n\t\tb3RequestCameraImageSetCameraMatrices(command, args.m_viewMatrix, args.m_projectionMatrix);\n\t}\n\n\tif (args.m_lightDirection != NULL)\n\t{\n\t\tb3RequestCameraImageSetLightDirection(command, args.m_lightDirection);\n\t}\n\n\tif (args.m_lightColor != NULL)\n\t{\n\t\tb3RequestCameraImageSetLightColor(command, args.m_lightColor);\n\t}\n\n\tif (args.m_lightDistance >= 0)\n\t{\n\t\tb3RequestCameraImageSetLightDistance(command, args.m_lightDistance);\n\t}\n\n\tif (args.m_hasShadow >= 0)\n\t{\n\t\tb3RequestCameraImageSetShadow(command, args.m_hasShadow);\n\t}\n\n\tif (args.m_lightAmbientCoeff >= 0)\n\t{\n\t\tb3RequestCameraImageSetLightAmbientCoeff(command, args.m_lightAmbientCoeff);\n\t}\n\n\tif (args.m_lightDiffuseCoeff >= 0)\n\t{\n\t\tb3RequestCameraImageSetLightDiffuseCoeff(command, args.m_lightDiffuseCoeff);\n\t}\n\n\tif (args.m_lightSpecularCoeff >= 0)\n\t{\n\t\tb3RequestCameraImageSetLightSpecularCoeff(command, args.m_lightSpecularCoeff);\n\t}\n\n\tif (args.m_renderer >= 0)\n\t{\n\t\tb3RequestCameraImageSelectRenderer(command, args.m_renderer);\n\t}\n\n\t\/\/ Actually retrieve the image\n\tif (b3CanSubmitCommand(m_data->m_physicsClientHandle))\n\t{\n\t\tb3SharedMemoryStatusHandle statusHandle;\n\t\tint statusType;\n\n\t\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, command);\n\t\tstatusType = b3GetStatusType(statusHandle);\n\t\tif (statusType == CMD_CAMERA_IMAGE_COMPLETED)\n\t\t{\n\t\t\tb3GetCameraImageData(m_data->m_physicsClientHandle, &imageData);\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::calculateInverseDynamics(int bodyUniqueId, double* jointPositions, double* jointVelocities,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  double* jointAccelerations, double* jointForcesOutput)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tb3GetNumJoints(m_data->m_physicsClientHandle, bodyUniqueId);\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\tb3SharedMemoryCommandHandle commandHandle = b3CalculateInverseDynamicsCommandInit(m_data->m_physicsClientHandle, bodyUniqueId, jointPositions,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  jointVelocities, jointAccelerations);\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, commandHandle);\n\n\tstatusType = b3GetStatusType(statusHandle);\n\n\tif (statusType == CMD_CALCULATED_INVERSE_DYNAMICS_COMPLETED)\n\t{\n\t\tint bodyUniqueId;\n\t\tint dofCount;\n\n\t\tb3GetStatusInverseDynamicsJointForces(statusHandle, &bodyUniqueId, &dofCount, 0);\n\n\t\tif (dofCount)\n\t\t{\n\t\t\tb3GetStatusInverseDynamicsJointForces(statusHandle, 0, 0, jointForcesOutput);\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::getNumBodies() const\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\treturn b3GetNumBodies(m_data->m_physicsClientHandle);\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::getBodyUniqueId(int bodyId) const\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\treturn b3GetBodyUniqueId(m_data->m_physicsClientHandle, bodyId);\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::removeBody(int bodyUniqueId)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tif (b3CanSubmitCommand(m_data->m_physicsClientHandle))\n\t{\n\t\tstatusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, b3InitRemoveBodyCommand(m_data->m_physicsClientHandle, bodyUniqueId));\n\t\tstatusType = b3GetStatusType(statusHandle);\n\t\tif (statusType == CMD_REMOVE_BODY_COMPLETED)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tb3Warning(\"getDynamicsInfo did not complete\");\n\t\t\treturn false;\n\t\t}\n\t}\n\tb3Warning(\"removeBody could not submit command\");\n\treturn false;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getDynamicsInfo(int bodyUniqueId, int linkIndex, b3DynamicsInfo* dynamicsInfo)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tint status_type = 0;\n\tb3SharedMemoryCommandHandle cmd_handle;\n\tb3SharedMemoryStatusHandle status_handle;\n\t\/\/  struct b3DynamicsInfo info;\n\n\tif (bodyUniqueId < 0)\n\t{\n\t\tb3Warning(\"getDynamicsInfo failed; invalid bodyUniqueId\");\n\t\treturn false;\n\t}\n\tif (linkIndex < -1)\n\t{\n\t\tb3Warning(\"getDynamicsInfo failed; invalid linkIndex\");\n\t\treturn false;\n\t}\n\n\tif (b3CanSubmitCommand(m_data->m_physicsClientHandle))\n\t{\n\t\tcmd_handle = b3GetDynamicsInfoCommandInit(m_data->m_physicsClientHandle, bodyUniqueId, linkIndex);\n\t\tstatus_handle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClientHandle, cmd_handle);\n\t\tstatus_type = b3GetStatusType(status_handle);\n\t\tif (status_type == CMD_GET_DYNAMICS_INFO_COMPLETED)\n\t\t{\n\t\t\tb3GetDynamicsInfo(status_handle, dynamicsInfo);\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tb3Warning(\"getDynamicsInfo did not complete\");\n\t\t\treturn false;\n\t\t}\n\t}\n\tb3Warning(\"getDynamicsInfo could not submit command\");\n\treturn false;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::changeDynamics(int bodyUniqueId, int linkIndex, struct b3RobotSimulatorChangeDynamicsArgs& args)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected to physics server.\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command = b3InitChangeDynamicsInfo(sm);\n\tb3SharedMemoryStatusHandle statusHandle;\n\n\tif (args.m_activationState >= 0)\n\t{\n\t\tb3ChangeDynamicsInfoSetActivationState(command, bodyUniqueId, args.m_activationState);\n\t}\n\tif (args.m_mass >= 0)\n\t{\n\t\tb3ChangeDynamicsInfoSetMass(command, bodyUniqueId, linkIndex, args.m_mass);\n\t}\n\n\tif (args.m_lateralFriction >= 0)\n\t{\n\t\tb3ChangeDynamicsInfoSetLateralFriction(command, bodyUniqueId, linkIndex, args.m_lateralFriction);\n\t}\n\n\tif (args.m_spinningFriction >= 0)\n\t{\n\t\tb3ChangeDynamicsInfoSetSpinningFriction(command, bodyUniqueId, linkIndex, args.m_spinningFriction);\n\t}\n\n\tif (args.m_rollingFriction >= 0)\n\t{\n\t\tb3ChangeDynamicsInfoSetRollingFriction(command, bodyUniqueId, linkIndex, args.m_rollingFriction);\n\t}\n\n\tif (args.m_linearDamping >= 0)\n\t{\n\t\tb3ChangeDynamicsInfoSetLinearDamping(command, bodyUniqueId, args.m_linearDamping);\n\t}\n\n\tif (args.m_angularDamping >= 0)\n\t{\n\t\tb3ChangeDynamicsInfoSetAngularDamping(command, bodyUniqueId, args.m_angularDamping);\n\t}\n\n\tif (args.m_restitution >= 0)\n\t{\n\t\tb3ChangeDynamicsInfoSetRestitution(command, bodyUniqueId, linkIndex, args.m_restitution);\n\t}\n\n\tif (args.m_contactStiffness >= 0 && args.m_contactDamping >= 0)\n\t{\n\t\tb3ChangeDynamicsInfoSetContactStiffnessAndDamping(command, bodyUniqueId, linkIndex, args.m_contactStiffness, args.m_contactDamping);\n\t}\n\n\tif (args.m_frictionAnchor >= 0)\n\t{\n\t\tb3ChangeDynamicsInfoSetFrictionAnchor(command, bodyUniqueId, linkIndex, args.m_frictionAnchor);\n\t}\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\treturn true;\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::addUserDebugParameter(const char* paramName, double rangeMin, double rangeMax, double startValue)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected to physics server.\");\n\t\treturn -1;\n\t}\n\tb3SharedMemoryCommandHandle commandHandle;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tcommandHandle = b3InitUserDebugAddParameter(sm, paramName, rangeMin, rangeMax, startValue);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle);\n\tstatusType = b3GetStatusType(statusHandle);\n\n\tif (statusType == CMD_USER_DEBUG_DRAW_COMPLETED)\n\t{\n\t\tint debugItemUniqueId = b3GetDebugItemUniqueId(statusHandle);\n\t\treturn debugItemUniqueId;\n\t}\n\tb3Warning(\"addUserDebugParameter failed.\");\n\treturn -1;\n}\n\ndouble b3RobotSimulatorClientAPI_NoDirect::readUserDebugParameter(int itemUniqueId)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected to physics server.\");\n\t\treturn 0;\n\t}\n\tb3SharedMemoryCommandHandle commandHandle;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tcommandHandle = b3InitUserDebugReadParameter(sm, itemUniqueId);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle);\n\tstatusType = b3GetStatusType(statusHandle);\n\n\tif (statusType == CMD_USER_DEBUG_DRAW_PARAMETER_COMPLETED)\n\t{\n\t\tdouble paramValue = 0.f;\n\t\tint ok = b3GetStatusDebugParameterValue(statusHandle, &paramValue);\n\t\tif (ok)\n\t\t{\n\t\t\treturn paramValue;\n\t\t}\n\t}\n\tb3Warning(\"readUserDebugParameter failed.\");\n\treturn 0;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::removeUserDebugItem(int itemUniqueId)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected to physics server.\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle commandHandle;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tcommandHandle = b3InitUserDebugDrawRemove(sm, itemUniqueId);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle);\n\tstatusType = b3GetStatusType(statusHandle);\n\treturn true;\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::addUserDebugText(const char* text, double* textPosition, struct b3RobotSimulatorAddUserDebugTextArgs& args)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected to physics server.\");\n\t\treturn -1;\n\t}\n\tb3SharedMemoryCommandHandle commandHandle;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tcommandHandle = b3InitUserDebugDrawAddText3D(sm, text, textPosition, &args.m_colorRGB[0], args.m_size, args.m_lifeTime);\n\n\tif (args.m_parentObjectUniqueId >= 0)\n\t{\n\t\tb3UserDebugItemSetParentObject(commandHandle, args.m_parentObjectUniqueId, args.m_parentLinkIndex);\n\t}\n\n\tif (args.m_flags & DEBUG_TEXT_HAS_ORIENTATION)\n\t{\n\t\tb3UserDebugTextSetOrientation(commandHandle, &args.m_textOrientation[0]);\n\t}\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle);\n\tstatusType = b3GetStatusType(statusHandle);\n\n\tif (statusType == CMD_USER_DEBUG_DRAW_COMPLETED)\n\t{\n\t\tint debugItemUniqueId = b3GetDebugItemUniqueId(statusHandle);\n\t\treturn debugItemUniqueId;\n\t}\n\tb3Warning(\"addUserDebugText3D failed.\");\n\treturn -1;\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::addUserDebugText(const char* text, btVector3& textPosition, struct b3RobotSimulatorAddUserDebugTextArgs& args)\n{\n\tdouble dposXYZ[3];\n\tdposXYZ[0] = textPosition.x();\n\tdposXYZ[1] = textPosition.y();\n\tdposXYZ[2] = textPosition.z();\n\n\treturn addUserDebugText(text, &dposXYZ[0], args);\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::addUserDebugLine(double* fromXYZ, double* toXYZ, struct b3RobotSimulatorAddUserDebugLineArgs& args)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected to physics server.\");\n\t\treturn -1;\n\t}\n\tb3SharedMemoryCommandHandle commandHandle;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tcommandHandle = b3InitUserDebugDrawAddLine3D(sm, fromXYZ, toXYZ, &args.m_colorRGB[0], args.m_lineWidth, args.m_lifeTime);\n\n\tif (args.m_parentObjectUniqueId >= 0)\n\t{\n\t\tb3UserDebugItemSetParentObject(commandHandle, args.m_parentObjectUniqueId, args.m_parentLinkIndex);\n\t}\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle);\n\tstatusType = b3GetStatusType(statusHandle);\n\n\tif (statusType == CMD_USER_DEBUG_DRAW_COMPLETED)\n\t{\n\t\tint debugItemUniqueId = b3GetDebugItemUniqueId(statusHandle);\n\t\treturn debugItemUniqueId;\n\t}\n\tb3Warning(\"addUserDebugLine failed.\");\n\treturn -1;\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::addUserDebugLine(btVector3& fromXYZ, btVector3& toXYZ, struct b3RobotSimulatorAddUserDebugLineArgs& args)\n{\n\tdouble dfromXYZ[3];\n\tdouble dtoXYZ[3];\n\tdfromXYZ[0] = fromXYZ.x();\n\tdfromXYZ[1] = fromXYZ.y();\n\tdfromXYZ[2] = fromXYZ.z();\n\n\tdtoXYZ[0] = toXYZ.x();\n\tdtoXYZ[1] = toXYZ.y();\n\tdtoXYZ[2] = toXYZ.z();\n\treturn addUserDebugLine(&dfromXYZ[0], &dtoXYZ[0], args);\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::setJointMotorControlArray(int bodyUniqueId, struct b3RobotSimulatorJointMotorArrayArgs& args)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected to physics server.\");\n\t\treturn false;\n\t}\n\tb3GetNumJoints(sm, bodyUniqueId);\n\n\tb3SharedMemoryCommandHandle commandHandle;\n\tb3SharedMemoryStatusHandle statusHandle;\n\t\/\/  int statusType;\n\tstruct b3JointInfo info;\n\n\tcommandHandle = b3JointControlCommandInit2(sm, bodyUniqueId, args.m_controlMode);\n\n\tfor (int i = 0; i < args.m_numControlledDofs; i++)\n\t{\n\t\tdouble targetVelocity = 0.0;\n\t\tdouble targetPosition = 0.0;\n\t\tdouble force = 100000.0;\n\t\tdouble kp = 0.1;\n\t\tdouble kd = 1.0;\n\t\tint jointIndex;\n\n\t\tif (args.m_jointIndices)\n\t\t{\n\t\t\tjointIndex = args.m_jointIndices[i];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tjointIndex = i;\n\t\t}\n\n\t\tif (args.m_targetVelocities)\n\t\t{\n\t\t\ttargetVelocity = args.m_targetVelocities[i];\n\t\t}\n\n\t\tif (args.m_targetPositions)\n\t\t{\n\t\t\ttargetPosition = args.m_targetPositions[i];\n\t\t}\n\n\t\tif (args.m_forces)\n\t\t{\n\t\t\tforce = args.m_forces[i];\n\t\t}\n\n\t\tif (args.m_kps)\n\t\t{\n\t\t\tkp = args.m_kps[i];\n\t\t}\n\n\t\tif (args.m_kds)\n\t\t{\n\t\t\tkd = args.m_kds[i];\n\t\t}\n\n\t\tb3GetJointInfo(sm, bodyUniqueId, jointIndex, &info);\n\n\t\tswitch (args.m_controlMode)\n\t\t{\n\t\t\tcase CONTROL_MODE_VELOCITY:\n\t\t\t{\n\t\t\t\tb3JointControlSetDesiredVelocity(commandHandle, info.m_uIndex, targetVelocity);\n\t\t\t\tb3JointControlSetKd(commandHandle, info.m_uIndex, kd);\n\t\t\t\tb3JointControlSetMaximumForce(commandHandle, info.m_uIndex, force);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CONTROL_MODE_TORQUE:\n\t\t\t{\n\t\t\t\tb3JointControlSetDesiredForceTorque(commandHandle, info.m_uIndex, force);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CONTROL_MODE_POSITION_VELOCITY_PD:\n\t\t\t{\n\t\t\t\tb3JointControlSetDesiredPosition(commandHandle, info.m_qIndex, targetPosition);\n\t\t\t\tb3JointControlSetKp(commandHandle, info.m_uIndex, kp);\n\t\t\t\tb3JointControlSetDesiredVelocity(commandHandle, info.m_uIndex, targetVelocity);\n\t\t\t\tb3JointControlSetKd(commandHandle, info.m_uIndex, kd);\n\t\t\t\tb3JointControlSetMaximumForce(commandHandle, info.m_uIndex, force);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t{\n\t\t\t}\n\t\t};\n\t}\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle);\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getPhysicsEngineParameters(struct b3RobotSimulatorSetPhysicsEngineParameters& args)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\t{\n\t\tb3SharedMemoryCommandHandle command = b3InitRequestPhysicsParamCommand(sm);\n\t\tb3SharedMemoryStatusHandle statusHandle;\n\t\tint statusType;\n\n\t\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\t\tstatusType = b3GetStatusType(statusHandle);\n\t\tif (statusType != CMD_REQUEST_PHYSICS_SIMULATION_PARAMETERS_COMPLETED)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tb3GetStatusPhysicsSimulationParameters(statusHandle, &args);\n\t}\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::setPhysicsEngineParameter(const struct b3RobotSimulatorSetPhysicsEngineParameters& args)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command = b3InitPhysicsParamCommand(sm);\n\tb3SharedMemoryStatusHandle statusHandle;\n\n\tif (args.m_numSolverIterations >= 0)\n\t{\n\t\tb3PhysicsParamSetNumSolverIterations(command, args.m_numSolverIterations);\n\t}\n\n\tif (args.m_deterministicOverlappingPairs >= 0)\n\t{\n\t\tb3PhysicsParameterSetDeterministicOverlappingPairs(command, args.m_deterministicOverlappingPairs);\n\t}\n\n\tif (args.m_collisionFilterMode >= 0)\n\t{\n\t\tb3PhysicsParamSetCollisionFilterMode(command, args.m_collisionFilterMode);\n\t}\n\n\tif (args.m_numSimulationSubSteps >= 0)\n\t{\n\t\tb3PhysicsParamSetNumSubSteps(command, args.m_numSimulationSubSteps);\n\t}\n\n\tif (args.m_deltaTime >= 0)\n\t{\n\t\tb3PhysicsParamSetTimeStep(command, args.m_deltaTime);\n\t}\n\n\tif (args.m_useSplitImpulse >= 0)\n\t{\n\t\tb3PhysicsParamSetUseSplitImpulse(command, args.m_useSplitImpulse);\n\t}\n\n\tif (args.m_splitImpulsePenetrationThreshold >= 0)\n\t{\n\t\tb3PhysicsParamSetSplitImpulsePenetrationThreshold(command, args.m_splitImpulsePenetrationThreshold);\n\t}\n\n\tif (args.m_contactBreakingThreshold >= 0)\n\t{\n\t\tb3PhysicsParamSetContactBreakingThreshold(command, args.m_contactBreakingThreshold);\n\t}\n\n\tif (args.m_restitutionVelocityThreshold >= 0)\n\t{\n\t\tb3PhysicsParamSetRestitutionVelocityThreshold(command, args.m_restitutionVelocityThreshold);\n\t}\n\n\tif (args.m_enableFileCaching >= 0)\n\t{\n\t\tb3PhysicsParamSetEnableFileCaching(command, args.m_enableFileCaching);\n\t}\n\n\tif (args.m_defaultNonContactERP >= 0)\n\t{\n\t\tb3PhysicsParamSetDefaultNonContactERP(command, args.m_defaultNonContactERP);\n\t}\n\n\tif (args.m_defaultContactERP >= 0)\n\t{\n\t\tb3PhysicsParamSetDefaultContactERP(command, args.m_defaultContactERP);\n\t}\n\n\tif (args.m_frictionERP >= 0)\n\t{\n\t\tb3PhysicsParamSetDefaultFrictionERP(command, args.m_frictionERP);\n\t}\n\n\tif (args.m_solverResidualThreshold >= 0)\n\t{\n\t\tb3PhysicsParamSetSolverResidualThreshold(command, args.m_solverResidualThreshold);\n\t}\n\n\tif (args.m_constraintSolverType >= 0)\n\t{\n\t\tb3PhysicsParameterSetConstraintSolverType(command, args.m_constraintSolverType);\n\t}\n\tif (args.m_minimumSolverIslandSize >= 0)\n\t{\n\t\tb3PhysicsParameterSetMinimumSolverIslandSize(command, args.m_minimumSolverIslandSize);\n\t}\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::applyExternalForce(int objectUniqueId, int linkIndex, double* force, double* position, int flags)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\n\tcommand = b3ApplyExternalForceCommandInit(sm);\n\tb3ApplyExternalForce(command, objectUniqueId, linkIndex, force, position, flags);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::applyExternalForce(int objectUniqueId, int linkIndex, btVector3& force, btVector3& position, int flags)\n{\n\tdouble dforce[3];\n\tdouble dposition[3];\n\n\tdforce[0] = force.x();\n\tdforce[1] = force.y();\n\tdforce[2] = force.z();\n\n\tdposition[0] = position.x();\n\tdposition[1] = position.y();\n\tdposition[2] = position.z();\n\n\treturn applyExternalForce(objectUniqueId, linkIndex, &dforce[0], &dposition[0], flags);\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::applyExternalTorque(int objectUniqueId, int linkIndex, double* torque, int flags)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\n\tcommand = b3ApplyExternalForceCommandInit(sm);\n\tb3ApplyExternalTorque(command, objectUniqueId, linkIndex, torque, flags);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::applyExternalTorque(int objectUniqueId, int linkIndex, btVector3& torque, int flags)\n{\n\tdouble dtorque[3];\n\n\tdtorque[0] = torque.x();\n\tdtorque[1] = torque.y();\n\tdtorque[2] = torque.z();\n\n\treturn applyExternalTorque(objectUniqueId, linkIndex, &dtorque[0], flags);\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::enableJointForceTorqueSensor(int bodyUniqueId, int jointIndex, bool enable)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tint numJoints = b3GetNumJoints(sm, bodyUniqueId);\n\tif ((jointIndex < 0) || (jointIndex >= numJoints))\n\t{\n\t\tb3Warning(\"Error: invalid jointIndex.\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tcommand = b3CreateSensorCommandInit(sm, bodyUniqueId);\n\tb3CreateSensorEnable6DofJointForceTorqueSensor(command, jointIndex, enable);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\tstatusType = b3GetStatusType(statusHandle);\n\tif (statusType == CMD_CLIENT_COMMAND_COMPLETED)\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getDebugVisualizerCamera(struct b3OpenGLVisualizerCameraInfo* cameraInfo)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tcommand = b3InitRequestOpenGLVisualizerCameraCommand(sm);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\tstatusType = b3GetStatusOpenGLVisualizerCamera(statusHandle, cameraInfo);\n\n\tif (statusType)\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getContactPoints(struct b3RobotSimulatorGetContactPointsArgs& args, struct b3ContactInformation* contactInfo)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tcommand = b3InitRequestContactPointInformation(sm);\n\n\tif (args.m_bodyUniqueIdA >= 0)\n\t{\n\t\tb3SetContactFilterBodyA(command, args.m_bodyUniqueIdA);\n\t}\n\tif (args.m_bodyUniqueIdB >= 0)\n\t{\n\t\tb3SetContactFilterBodyB(command, args.m_bodyUniqueIdB);\n\t}\n\tif (args.m_linkIndexA >= -1)\n\t{\n\t\tb3SetContactFilterLinkA(command, args.m_linkIndexA);\n\t}\n\tif (args.m_linkIndexB >= -1)\n\t{\n\t\tb3SetContactFilterLinkB(command, args.m_linkIndexB);\n\t}\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\tstatusType = b3GetStatusType(statusHandle);\n\n\tif (statusType == CMD_CONTACT_POINT_INFORMATION_COMPLETED)\n\t{\n\t\tb3GetContactPointInformation(sm, contactInfo);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getClosestPoints(struct b3RobotSimulatorGetContactPointsArgs& args, double distance, struct b3ContactInformation* contactInfo)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tcommand = b3InitClosestDistanceQuery(sm);\n\n\tb3SetClosestDistanceFilterBodyA(command, args.m_bodyUniqueIdA);\n\tb3SetClosestDistanceFilterBodyB(command, args.m_bodyUniqueIdB);\n\tb3SetClosestDistanceThreshold(command, distance);\n\n\tif (args.m_linkIndexA >= -1)\n\t{\n\t\tb3SetClosestDistanceFilterLinkA(command, args.m_linkIndexA);\n\t}\n\tif (args.m_linkIndexB >= -1)\n\t{\n\t\tb3SetClosestDistanceFilterLinkB(command, args.m_linkIndexB);\n\t}\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\tstatusType = b3GetStatusType(statusHandle);\n\n\tif (statusType == CMD_CONTACT_POINT_INFORMATION_COMPLETED)\n\t{\n\t\tb3GetContactPointInformation(sm, contactInfo);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getOverlappingObjects(double* aabbMin, double* aabbMax, struct b3AABBOverlapData* overlapData)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\t\/\/  int statusType;\n\n\tcommand = b3InitAABBOverlapQuery(sm, aabbMin, aabbMax);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\tb3GetAABBOverlapResults(sm, overlapData);\n\n\treturn true;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getOverlappingObjects(btVector3& aabbMin, btVector3& aabbMax, struct b3AABBOverlapData* overlapData)\n{\n\tdouble daabbMin[3];\n\tdouble daabbMax[3];\n\n\tdaabbMin[0] = aabbMin.x();\n\tdaabbMin[1] = aabbMin.y();\n\tdaabbMin[2] = aabbMin.z();\n\n\tdaabbMax[0] = aabbMax.x();\n\tdaabbMax[1] = aabbMax.y();\n\tdaabbMax[2] = aabbMax.z();\n\n\treturn getOverlappingObjects(&daabbMin[0], &daabbMax[0], overlapData);\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getAABB(int bodyUniqueId, int linkIndex, double* aabbMin, double* aabbMax)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tif (bodyUniqueId < 0)\n\t{\n\t\tb3Warning(\"Invalid bodyUniqueId\");\n\t\treturn false;\n\t}\n\n\tif (linkIndex < -1)\n\t{\n\t\tb3Warning(\"Invalid linkIndex\");\n\t\treturn false;\n\t}\n\n\tif (aabbMin == NULL || aabbMax == NULL)\n\t{\n\t\tb3Warning(\"Output AABB matrix is NULL\");\n\t\treturn false;\n\t}\n\n\tcommand = b3RequestCollisionInfoCommandInit(sm, bodyUniqueId);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\n\tstatusType = b3GetStatusType(statusHandle);\n\tif (statusType != CMD_REQUEST_COLLISION_INFO_COMPLETED)\n\t{\n\t\treturn false;\n\t}\n\tif (b3GetStatusAABB(statusHandle, linkIndex, aabbMin, aabbMax))\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getAABB(int bodyUniqueId, int linkIndex, btVector3& aabbMin, btVector3& aabbMax)\n{\n\tdouble daabbMin[3];\n\tdouble daabbMax[3];\n\n\tbool status = getAABB(bodyUniqueId, linkIndex, &daabbMin[0], &daabbMax[0]);\n\n\taabbMin[0] = (float)daabbMin[0];\n\taabbMin[1] = (float)daabbMin[1];\n\taabbMin[2] = (float)daabbMin[2];\n\n\taabbMax[0] = (float)daabbMax[0];\n\taabbMax[1] = (float)daabbMax[1];\n\taabbMax[2] = (float)daabbMax[2];\n\n\treturn status;\n}\n\n\nint b3RobotSimulatorClientAPI_NoDirect::createVisualShape(int shapeType, struct b3RobotSimulatorCreateVisualShapeArgs& args)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\tint shapeIndex = -1;\n\n\tcommand = b3CreateVisualShapeCommandInit(sm);\n\n\tif (shapeType == GEOM_SPHERE && args.m_radius > 0)\n\t{\n\t\tshapeIndex = b3CreateVisualShapeAddSphere(command, args.m_radius);\n\t}\n\tif (shapeType == GEOM_BOX)\n\t{\n\t\tdouble halfExtents[3];\n\t\tscalarToDouble3(args.m_halfExtents, halfExtents);\n\t\tshapeIndex = b3CreateVisualShapeAddBox(command, halfExtents);\n\t}\n\tif (shapeType == GEOM_CAPSULE && args.m_radius > 0 && args.m_height >= 0)\n\t{\n\t\tshapeIndex = b3CreateVisualShapeAddCapsule(command, args.m_radius, args.m_height);\n\t}\n\tif (shapeType == GEOM_CYLINDER && args.m_radius > 0 && args.m_height >= 0)\n\t{\n\t\tshapeIndex = b3CreateVisualShapeAddCylinder(command, args.m_radius, args.m_height);\n\t}\n\tif (shapeType == GEOM_MESH && args.m_fileName)\n\t{\n\t\tdouble meshScale[3];\n\t\tscalarToDouble3(args.m_meshScale, meshScale);\n\t\tshapeIndex = b3CreateVisualShapeAddMesh(command, args.m_fileName, meshScale);\n\t}\n\tif (shapeType == GEOM_PLANE)\n\t{\n\t\tdouble planeConstant = 0;\n\t\tdouble planeNormal[3];\n\t\tscalarToDouble3(args.m_planeNormal, planeNormal);\n\t\tshapeIndex = b3CreateVisualShapeAddPlane(command, planeNormal, planeConstant);\n\t}\n\tif (shapeIndex >= 0 && args.m_flags)\n\t{\n\t\tb3CreateVisualSetFlag(command, shapeIndex, args.m_flags);\n\t}\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\tstatusType = b3GetStatusType(statusHandle);\n\tif (statusType == CMD_CREATE_VISUAL_SHAPE_COMPLETED)\n\t{\n\t\tint uid = b3GetStatusVisualShapeUniqueId(statusHandle);\n\t\treturn uid;\n\t}\n\treturn -1;\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::createCollisionShape(int shapeType, struct b3RobotSimulatorCreateCollisionShapeArgs& args)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\tint shapeIndex = -1;\n\n\tcommand = b3CreateCollisionShapeCommandInit(sm);\n\n\tif (shapeType == GEOM_SPHERE && args.m_radius > 0)\n\t{\n\t\tshapeIndex = b3CreateCollisionShapeAddSphere(command, args.m_radius);\n\t}\n\tif (shapeType == GEOM_BOX)\n\t{\n\t\tdouble halfExtents[3];\n\t\tscalarToDouble3(args.m_halfExtents, halfExtents);\n\t\tshapeIndex = b3CreateCollisionShapeAddBox(command, halfExtents);\n\t}\n\tif (shapeType == GEOM_CAPSULE && args.m_radius > 0 && args.m_height >= 0)\n\t{\n\t\tshapeIndex = b3CreateCollisionShapeAddCapsule(command, args.m_radius, args.m_height);\n\t}\n\tif (shapeType == GEOM_CYLINDER && args.m_radius > 0 && args.m_height >= 0)\n\t{\n\t\tshapeIndex = b3CreateCollisionShapeAddCylinder(command, args.m_radius, args.m_height);\n\t}\n\tif (shapeType == GEOM_MESH && args.m_fileName)\n\t{\n\t\tdouble meshScale[3];\n\t\tscalarToDouble3(args.m_meshScale, meshScale);\n\t\tshapeIndex = b3CreateCollisionShapeAddMesh(command, args.m_fileName, meshScale);\n\t}\n\tif (shapeType == GEOM_PLANE)\n\t{\n\t\tdouble planeConstant = 0;\n\t\tdouble planeNormal[3];\n\t\tscalarToDouble3(args.m_planeNormal, planeNormal);\n\t\tshapeIndex = b3CreateCollisionShapeAddPlane(command, planeNormal, planeConstant);\n\t}\n\tif (shapeIndex >= 0 && args.m_flags)\n\t{\n\t\tb3CreateCollisionSetFlag(command, shapeIndex, args.m_flags);\n\t}\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\tstatusType = b3GetStatusType(statusHandle);\n\tif (statusType == CMD_CREATE_COLLISION_SHAPE_COMPLETED)\n\t{\n\t\tint uid = b3GetStatusCollisionShapeUniqueId(statusHandle);\n\t\treturn uid;\n\t}\n\treturn -1;\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::createMultiBody(struct b3RobotSimulatorCreateMultiBodyArgs& args)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType, baseIndex;\n\n\tdouble doubleBasePosition[3];\n\tdouble doubleBaseInertialFramePosition[3];\n\tscalarToDouble3(args.m_basePosition.m_floats, doubleBasePosition);\n\tscalarToDouble3(args.m_baseInertialFramePosition.m_floats, doubleBaseInertialFramePosition);\n\n\tdouble doubleBaseOrientation[4];\n\tdouble doubleBaseInertialFrameOrientation[4];\n\tscalarToDouble4(args.m_baseOrientation, doubleBaseOrientation);\n\tscalarToDouble4(args.m_baseInertialFrameOrientation, doubleBaseInertialFrameOrientation);\n\n\tcommand = b3CreateMultiBodyCommandInit(sm);\n\n\tif (args.m_useMaximalCoordinates)\n\t{\n\t\tb3CreateMultiBodyUseMaximalCoordinates(command);\n\t}\n\tif (args.m_batchPositions.size())\n\t{\n\t\tbtAlignedObjectArray<double> positionArray;\n\t\tfor (int i = 0; i < args.m_batchPositions.size(); i++)\n\t\t{\n\t\t\tpositionArray.push_back(args.m_batchPositions[i][0]);\n\t\t\tpositionArray.push_back(args.m_batchPositions[i][1]);\n\t\t\tpositionArray.push_back(args.m_batchPositions[i][2]);\n\t\t}\n\t\tb3CreateMultiBodySetBatchPositions(sm, command, &positionArray[0], args.m_batchPositions.size());\n\t}\n\tbaseIndex = b3CreateMultiBodyBase(command, args.m_baseMass, args.m_baseCollisionShapeIndex, args.m_baseVisualShapeIndex,\n\t\t\t\t\t\t\t\t\t  doubleBasePosition, doubleBaseOrientation, doubleBaseInertialFramePosition, doubleBaseInertialFrameOrientation);\n\n\tfor (int i = 0; i < args.m_numLinks; i++)\n\t{\n\t\tdouble linkMass = args.m_linkMasses[i];\n\t\tint linkCollisionShapeIndex = args.m_linkCollisionShapeIndices[i];\n\t\tint linkVisualShapeIndex = args.m_linkVisualShapeIndices[i];\n\t\tbtVector3 linkPosition = args.m_linkPositions[i];\n\t\tbtQuaternion linkOrientation = args.m_linkOrientations[i];\n\t\tbtVector3 linkInertialFramePosition = args.m_linkInertialFramePositions[i];\n\t\tbtQuaternion linkInertialFrameOrientation = args.m_linkInertialFrameOrientations[i];\n\t\tint linkParentIndex = args.m_linkParentIndices[i];\n\t\tint linkJointType = args.m_linkJointTypes[i];\n\t\tbtVector3 linkJointAxis = args.m_linkJointAxes[i];\n\n\t\tdouble doubleLinkPosition[3];\n\t\tdouble doubleLinkInertialFramePosition[3];\n\t\tdouble doubleLinkJointAxis[3];\n\t\tscalarToDouble3(linkPosition.m_floats, doubleLinkPosition);\n\t\tscalarToDouble3(linkInertialFramePosition.m_floats, doubleLinkInertialFramePosition);\n\t\tscalarToDouble3(linkJointAxis.m_floats, doubleLinkJointAxis);\n\n\t\tdouble doubleLinkOrientation[4];\n\t\tdouble doubleLinkInertialFrameOrientation[4];\n\t\tscalarToDouble4(linkOrientation, doubleLinkOrientation);\n\t\tscalarToDouble4(linkInertialFrameOrientation, doubleLinkInertialFrameOrientation);\n\n\t\tb3CreateMultiBodyLink(command,\n\t\t\t\t\t\t\t  linkMass,\n\t\t\t\t\t\t\t  linkCollisionShapeIndex,\n\t\t\t\t\t\t\t  linkVisualShapeIndex,\n\t\t\t\t\t\t\t  doubleLinkPosition,\n\t\t\t\t\t\t\t  doubleLinkOrientation,\n\t\t\t\t\t\t\t  doubleLinkInertialFramePosition,\n\t\t\t\t\t\t\t  doubleLinkInertialFrameOrientation,\n\t\t\t\t\t\t\t  linkParentIndex,\n\t\t\t\t\t\t\t  linkJointType,\n\t\t\t\t\t\t\t  doubleLinkJointAxis);\n\t}\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\tstatusType = b3GetStatusType(statusHandle);\n\tif (statusType == CMD_CREATE_MULTI_BODY_COMPLETED)\n\t{\n\t\tint uid = b3GetStatusBodyIndex(statusHandle);\n\t\treturn uid;\n\t}\n\treturn -1;\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::getNumConstraints() const\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn -1;\n\t}\n\treturn b3GetNumUserConstraints(m_data->m_physicsClientHandle);\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::getConstraintUniqueId(int serialIndex)\n{\n\tif (!isConnected())\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn -1;\n\t}\n\tint userConstraintId = -1;\n\tuserConstraintId = b3GetUserConstraintId(m_data->m_physicsClientHandle, serialIndex);\n\treturn userConstraintId;\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::setGuiHelper(struct GUIHelperInterface* guiHelper)\n{\n\tm_data->m_guiHelper = guiHelper;\n}\n\nstruct GUIHelperInterface* b3RobotSimulatorClientAPI_NoDirect::getGuiHelper()\n{\n\treturn m_data->m_guiHelper;\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::setInternalData(struct b3RobotSimulatorClientAPI_InternalData* data)\n{\n\t*m_data = *data;\n}\n\nbool b3RobotSimulatorClientAPI_NoDirect::getCollisionShapeData(int bodyUniqueId, int linkIndex,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   b3CollisionShapeInformation& collisionShapeInfo)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\t{\n\t\tcommand = b3InitRequestCollisionShapeInformation(sm, bodyUniqueId, linkIndex);\n\t\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\t\tstatusType = b3GetStatusType(statusHandle);\n\t}\n\n\tbtAssert(statusType == CMD_COLLISION_SHAPE_INFO_COMPLETED);\n\tif (statusType == CMD_COLLISION_SHAPE_INFO_COMPLETED)\n\t{\n\t\tb3GetCollisionShapeInformation(sm, &collisionShapeInfo);\n\t}\n\treturn true;\n}\n\nint b3RobotSimulatorClientAPI_NoDirect::saveStateToMemory()\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\tb3SharedMemoryCommandHandle command;\n\n\tint stateId = -1;\n\n\tif (sm == 0)\n\t{\n\t\treturn -1;\n\t}\n\n\tcommand = b3SaveStateCommandInit(sm);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\tstatusType = b3GetStatusType(statusHandle);\n\n\tif (statusType != CMD_SAVE_STATE_COMPLETED)\n\t{\n\t\treturn -1;\n\t}\n\n\tstateId = b3GetStatusGetStateId(statusHandle);\n\treturn stateId;\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::restoreStateFromMemory(int stateId)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tint statusType;\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint physicsClientId = 0;\n\n\tcommand = b3LoadStateCommandInit(sm);\n\tif (stateId >= 0)\n\t{\n\t\tb3LoadStateSetStateId(command, stateId);\n\t}\n\t\/\/\tif (fileName)\n\t\/\/\t{\n\t\/\/\t\tb3LoadStateSetFileName(command, fileName);\n\t\/\/\t}\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\tstatusType = b3GetStatusType(statusHandle);\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::removeStateFromMemory(int stateId)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\n\tint statusType;\n\tb3SharedMemoryCommandHandle command;\n\tb3SharedMemoryStatusHandle statusHandle;\n\n\tif (stateId > 0)\n\t{\n\t\tcommand = b3InitRemoveStateCommand(sm,stateId);\n\t}\n\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);\n\tstatusType = b3GetStatusType(statusHandle);\n}\n\n\nbool b3RobotSimulatorClientAPI_NoDirect::getVisualShapeData(int bodyUniqueId, b3VisualShapeInformation& visualShapeInfo)\n{\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn false;\n\t}\n\tb3SharedMemoryCommandHandle commandHandle;\n\tb3SharedMemoryStatusHandle statusHandle;\n\tint statusType;\n\n\tcommandHandle = b3InitRequestVisualShapeInformation(sm, bodyUniqueId);\n\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle);\n\tstatusType = b3GetStatusType(statusHandle);\n\n\tbtAssert(statusType == CMD_VISUAL_SHAPE_INFO_COMPLETED);\n\tif (statusType == CMD_VISUAL_SHAPE_INFO_COMPLETED)\n\t{\n\t\tb3GetVisualShapeInformation(sm, &visualShapeInfo);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::setAdditionalSearchPath(const std::string& path)\n{\n\tint physicsClientId = 0;\n\tb3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n\tif (sm == 0)\n\t{\n\t\tb3Warning(\"Not connected\");\n\t\treturn;\n\t}\n\tif (path.length())\n\t{\n\t\tb3SharedMemoryCommandHandle commandHandle;\n\t\tb3SharedMemoryStatusHandle statusHandle;\n\t\tcommandHandle = b3SetAdditionalSearchPath(sm, path.c_str());\n\t\tstatusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle);\n\t}\n}\n\nvoid b3RobotSimulatorClientAPI_NoDirect::setCollisionFilterGroupMask(int bodyUniqueIdA, int linkIndexA, int collisionFilterGroup, int collisionFilterMask)\n{\n    int physicsClientId = 0;\n    b3PhysicsClientHandle sm = m_data->m_physicsClientHandle;\n    if (sm == 0)\n    {\n        b3Warning(\"Not connected\");\n        return;\n    }\n    \n    b3SharedMemoryCommandHandle commandHandle;\n    b3SharedMemoryStatusHandle statusHandle;\n    int statusType;\n    \n    commandHandle = b3CollisionFilterCommandInit(sm);\n    b3SetCollisionFilterGroupMask(commandHandle, bodyUniqueIdA, linkIndexA, collisionFilterGroup, collisionFilterMask);\n    \n    statusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle);\n    statusType = b3GetStatusType(statusHandle);\n}\n\n","avg_line_length":30.1049868766,"max_line_length":283,"alphanum_fraction":0.7906090422,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":41859,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":17.0,"content":"\/\/ This file has been generated by Py++.\n\n#include \"boost\/python.hpp\"\n#include \"__call_policies.pypp.hpp\"\n#include \"__convenience.pypp.hpp\"\n#include \"wrap_osg.h\"\n#include \"wrap_referenced.h\"\n#include \"texturerectangle.pypp.hpp\"\n\nnamespace bp = boost::python;\n\nstruct TextureRectangle_wrapper : osg::TextureRectangle, bp::wrapper< osg::TextureRectangle > {\n\n    struct SubloadCallback_wrapper : osg::TextureRectangle::SubloadCallback, bp::wrapper< osg::TextureRectangle::SubloadCallback > {\n    \n        SubloadCallback_wrapper()\n        : osg::TextureRectangle::SubloadCallback()\n          , bp::wrapper< osg::TextureRectangle::SubloadCallback >(){\n            \/\/ null constructor\n            \n        }\n    \n        virtual void load( ::osg::TextureRectangle const & arg0, ::osg::State & arg1 ) const  {\n            namespace bpl = boost::python;\n            if( bpl::override func_load = this->get_override( \"load\" ) ){\n                bpl::object py_result = bpl::call<bpl::object>( func_load.ptr(), arg0, arg1 );\n            }\n            else{\n                  PyErr_SetString(PyExc_NotImplementedError, \"Attempted calling Pure Virtual function that is not implemented :load\");\n                  boost::python::throw_error_already_set();\n            }\n        }\n        \n        static void default_load( ::osg::TextureRectangle::SubloadCallback const & inst, ::osg::TextureRectangle & arg0, ::osg::State & arg1 ){\n            if( dynamic_cast< SubloadCallback_wrapper const* >( boost::addressof( inst ) ) ){\n                  PyErr_SetString(PyExc_NotImplementedError, \"Attempted calling Pure Virtual function that is not implemented :load\");\n                  boost::python::throw_error_already_set();\n            }\n            else{\n                inst.load(arg0, arg1);\n            }\n        }\n    \n        virtual void subload( ::osg::TextureRectangle const & arg0, ::osg::State & arg1 ) const  {\n            namespace bpl = boost::python;\n            if( bpl::override func_subload = this->get_override( \"subload\" ) ){\n                bpl::object py_result = bpl::call<bpl::object>( func_subload.ptr(), arg0, arg1 );\n            }\n            else{\n                  PyErr_SetString(PyExc_NotImplementedError, \"Attempted calling Pure Virtual function that is not implemented :subload\");\n                  boost::python::throw_error_already_set();\n            }\n        }\n        \n        static void default_subload( ::osg::TextureRectangle::SubloadCallback const & inst, ::osg::TextureRectangle & arg0, ::osg::State & arg1 ){\n            if( dynamic_cast< SubloadCallback_wrapper const* >( boost::addressof( inst ) ) ){\n                  PyErr_SetString(PyExc_NotImplementedError, \"Attempted calling Pure Virtual function that is not implemented :subload\");\n                  boost::python::throw_error_already_set();\n            }\n            else{\n                inst.subload(arg0, arg1);\n            }\n        }\n    \n        virtual void setThreadSafeRefUnref( bool threadSafe ) {\n            if( bp::override func_setThreadSafeRefUnref = this->get_override( \"setThreadSafeRefUnref\" ) )\n                func_setThreadSafeRefUnref( threadSafe );\n            else{\n                this->osg::Referenced::setThreadSafeRefUnref( threadSafe );\n            }\n        }\n        \n        void default_setThreadSafeRefUnref( bool threadSafe ) {\n            osg::Referenced::setThreadSafeRefUnref( threadSafe );\n        }\n    \n    };\n\n    TextureRectangle_wrapper( )\n    : osg::TextureRectangle( )\n      , bp::wrapper< osg::TextureRectangle >(){\n        \/\/ null constructor\n    \n    }\n\n    TextureRectangle_wrapper(::osg::Image * image )\n    : osg::TextureRectangle( boost::python::ptr(image) )\n      , bp::wrapper< osg::TextureRectangle >(){\n        \/\/ constructor\n    \n    }\n\n    virtual void apply( ::osg::State & state ) const  {\n        if( bp::override func_apply = this->get_override( \"apply\" ) )\n            func_apply( boost::ref(state) );\n        else{\n            this->osg::TextureRectangle::apply( boost::ref(state) );\n        }\n    }\n    \n    void default_apply( ::osg::State & state ) const  {\n        osg::TextureRectangle::apply( boost::ref(state) );\n    }\n\n    virtual char const * className(  ) const  {\n        if( bp::override func_className = this->get_override( \"className\" ) )\n            return func_className(  );\n        else{\n            return this->osg::TextureRectangle::className(  );\n        }\n    }\n    \n    char const * default_className(  ) const  {\n        return osg::TextureRectangle::className( );\n    }\n\n    virtual ::osg::Object * clone( ::osg::CopyOp const & copyop ) const  {\n        if( bp::override func_clone = this->get_override( \"clone\" ) )\n            return func_clone( boost::ref(copyop) );\n        else{\n            return this->osg::TextureRectangle::clone( boost::ref(copyop) );\n        }\n    }\n    \n    ::osg::Object * default_clone( ::osg::CopyOp const & copyop ) const  {\n        return osg::TextureRectangle::clone( boost::ref(copyop) );\n    }\n\n    virtual ::osg::Object * cloneType(  ) const  {\n        if( bp::override func_cloneType = this->get_override( \"cloneType\" ) )\n            return func_cloneType(  );\n        else{\n            return this->osg::TextureRectangle::cloneType(  );\n        }\n    }\n    \n    ::osg::Object * default_cloneType(  ) const  {\n        return osg::TextureRectangle::cloneType( );\n    }\n\n    virtual ::osg::Image * getImage( unsigned int arg0 ) {\n        if( bp::override func_getImage = this->get_override( \"getImage\" ) )\n            return func_getImage( arg0 );\n        else{\n            return this->osg::TextureRectangle::getImage( arg0 );\n        }\n    }\n    \n    ::osg::Image * default_getImage( unsigned int arg0 ) {\n        return osg::TextureRectangle::getImage( arg0 );\n    }\n\n    virtual ::osg::Image const * getImage( unsigned int arg0 ) const  {\n        if( bp::override func_getImage = this->get_override( \"getImage\" ) )\n            return func_getImage( arg0 );\n        else{\n            return this->osg::TextureRectangle::getImage( arg0 );\n        }\n    }\n    \n    ::osg::Image const * default_getImage( unsigned int arg0 ) const  {\n        return osg::TextureRectangle::getImage( arg0 );\n    }\n\n    virtual unsigned int getNumImages(  ) const  {\n        if( bp::override func_getNumImages = this->get_override( \"getNumImages\" ) )\n            return func_getNumImages(  );\n        else{\n            return this->osg::TextureRectangle::getNumImages(  );\n        }\n    }\n    \n    unsigned int default_getNumImages(  ) const  {\n        return osg::TextureRectangle::getNumImages( );\n    }\n\n    virtual int getTextureDepth(  ) const  {\n        if( bp::override func_getTextureDepth = this->get_override( \"getTextureDepth\" ) )\n            return func_getTextureDepth(  );\n        else{\n            return this->osg::TextureRectangle::getTextureDepth(  );\n        }\n    }\n    \n    int default_getTextureDepth(  ) const  {\n        return osg::TextureRectangle::getTextureDepth( );\n    }\n\n    virtual int getTextureHeight(  ) const  {\n        if( bp::override func_getTextureHeight = this->get_override( \"getTextureHeight\" ) )\n            return func_getTextureHeight(  );\n        else{\n            return this->osg::TextureRectangle::getTextureHeight(  );\n        }\n    }\n    \n    int default_getTextureHeight(  ) const  {\n        return osg::TextureRectangle::getTextureHeight( );\n    }\n\n    virtual ::GLenum getTextureTarget(  ) const  {\n        if( bp::override func_getTextureTarget = this->get_override( \"getTextureTarget\" ) )\n            return func_getTextureTarget(  );\n        else{\n            return this->osg::TextureRectangle::getTextureTarget(  );\n        }\n    }\n    \n    ::GLenum default_getTextureTarget(  ) const  {\n        return osg::TextureRectangle::getTextureTarget( );\n    }\n\n    virtual int getTextureWidth(  ) const  {\n        if( bp::override func_getTextureWidth = this->get_override( \"getTextureWidth\" ) )\n            return func_getTextureWidth(  );\n        else{\n            return this->osg::TextureRectangle::getTextureWidth(  );\n        }\n    }\n    \n    int default_getTextureWidth(  ) const  {\n        return osg::TextureRectangle::getTextureWidth( );\n    }\n\n    virtual ::osg::StateAttribute::Type getType(  ) const  {\n        if( bp::override func_getType = this->get_override( \"getType\" ) )\n            return func_getType(  );\n        else{\n            return this->osg::TextureRectangle::getType(  );\n        }\n    }\n    \n    ::osg::StateAttribute::Type default_getType(  ) const  {\n        return osg::TextureRectangle::getType( );\n    }\n\n    virtual bool isSameKindAs( ::osg::Object const * obj ) const  {\n        if( bp::override func_isSameKindAs = this->get_override( \"isSameKindAs\" ) )\n            return func_isSameKindAs( boost::python::ptr(obj) );\n        else{\n            return this->osg::TextureRectangle::isSameKindAs( boost::python::ptr(obj) );\n        }\n    }\n    \n    bool default_isSameKindAs( ::osg::Object const * obj ) const  {\n        return osg::TextureRectangle::isSameKindAs( boost::python::ptr(obj) );\n    }\n\n    virtual char const * libraryName(  ) const  {\n        if( bp::override func_libraryName = this->get_override( \"libraryName\" ) )\n            return func_libraryName(  );\n        else{\n            return this->osg::TextureRectangle::libraryName(  );\n        }\n    }\n    \n    char const * default_libraryName(  ) const  {\n        return osg::TextureRectangle::libraryName( );\n    }\n\n    virtual void setImage( unsigned int arg0, ::osg::Image * image ) {\n        if( bp::override func_setImage = this->get_override( \"setImage\" ) )\n            func_setImage( arg0, boost::python::ptr(image) );\n        else{\n            this->osg::TextureRectangle::setImage( arg0, boost::python::ptr(image) );\n        }\n    }\n    \n    void default_setImage( unsigned int arg0, ::osg::Image * image ) {\n        osg::TextureRectangle::setImage( arg0, boost::python::ptr(image) );\n    }\n\n    virtual ::osg::Texture * asTexture(  ) {\n        if( bp::override func_asTexture = this->get_override( \"asTexture\" ) )\n            return func_asTexture(  );\n        else{\n            return this->osg::Texture::asTexture(  );\n        }\n    }\n    \n    ::osg::Texture * default_asTexture(  ) {\n        return osg::Texture::asTexture( );\n    }\n\n    virtual ::osg::Texture const * asTexture(  ) const  {\n        if( bp::override func_asTexture = this->get_override( \"asTexture\" ) )\n            return func_asTexture(  );\n        else{\n            return this->osg::Texture::asTexture(  );\n        }\n    }\n    \n    ::osg::Texture const * default_asTexture(  ) const  {\n        return osg::Texture::asTexture( );\n    }\n\n    virtual bool checkValidityOfAssociatedModes( ::osg::State & arg0 ) const  {\n        if( bp::override func_checkValidityOfAssociatedModes = this->get_override( \"checkValidityOfAssociatedModes\" ) )\n            return func_checkValidityOfAssociatedModes( boost::ref(arg0) );\n        else{\n            return this->osg::StateAttribute::checkValidityOfAssociatedModes( boost::ref(arg0) );\n        }\n    }\n    \n    bool default_checkValidityOfAssociatedModes( ::osg::State & arg0 ) const  {\n        return osg::StateAttribute::checkValidityOfAssociatedModes( boost::ref(arg0) );\n    }\n\n    virtual void compileGLObjects( ::osg::State & state ) const  {\n        if( bp::override func_compileGLObjects = this->get_override( \"compileGLObjects\" ) )\n            func_compileGLObjects( boost::ref(state) );\n        else{\n            this->osg::Texture::compileGLObjects( boost::ref(state) );\n        }\n    }\n    \n    void default_compileGLObjects( ::osg::State & state ) const  {\n        osg::Texture::compileGLObjects( boost::ref(state) );\n    }\n\n    virtual void computeDataVariance(  ) {\n        if( bp::override func_computeDataVariance = this->get_override( \"computeDataVariance\" ) )\n            func_computeDataVariance(  );\n        else{\n            this->osg::Object::computeDataVariance(  );\n        }\n    }\n    \n    void default_computeDataVariance(  ) {\n        osg::Object::computeDataVariance( );\n    }\n\n    virtual unsigned int getMember(  ) const  {\n        if( bp::override func_getMember = this->get_override( \"getMember\" ) )\n            return func_getMember(  );\n        else{\n            return this->osg::StateAttribute::getMember(  );\n        }\n    }\n    \n    unsigned int default_getMember(  ) const  {\n        return osg::StateAttribute::getMember( );\n    }\n\n    virtual bool getModeUsage( ::osg::StateAttribute::ModeUsage & usage ) const  {\n        if( bp::override func_getModeUsage = this->get_override( \"getModeUsage\" ) )\n            return func_getModeUsage( boost::ref(usage) );\n        else{\n            return this->osg::Texture::getModeUsage( boost::ref(usage) );\n        }\n    }\n    \n    bool default_getModeUsage( ::osg::StateAttribute::ModeUsage & usage ) const  {\n        return osg::Texture::getModeUsage( boost::ref(usage) );\n    }\n\n    virtual ::osg::Referenced * getUserData(  ) {\n        if( bp::override func_getUserData = this->get_override( \"getUserData\" ) )\n            return func_getUserData(  );\n        else{\n            return this->osg::Object::getUserData(  );\n        }\n    }\n    \n    ::osg::Referenced * default_getUserData(  ) {\n        return osg::Object::getUserData( );\n    }\n\n    virtual ::osg::Referenced const * getUserData(  ) const  {\n        if( bp::override func_getUserData = this->get_override( \"getUserData\" ) )\n            return func_getUserData(  );\n        else{\n            return this->osg::Object::getUserData(  );\n        }\n    }\n    \n    ::osg::Referenced const * default_getUserData(  ) const  {\n        return osg::Object::getUserData( );\n    }\n\n    virtual bool isTextureAttribute(  ) const  {\n        if( bp::override func_isTextureAttribute = this->get_override( \"isTextureAttribute\" ) )\n            return func_isTextureAttribute(  );\n        else{\n            return this->osg::Texture::isTextureAttribute(  );\n        }\n    }\n    \n    bool default_isTextureAttribute(  ) const  {\n        return osg::Texture::isTextureAttribute( );\n    }\n\n    virtual void resizeGLObjectBuffers( unsigned int maxSize ) {\n        if( bp::override func_resizeGLObjectBuffers = this->get_override( \"resizeGLObjectBuffers\" ) )\n            func_resizeGLObjectBuffers( maxSize );\n        else{\n            this->osg::Texture::resizeGLObjectBuffers( maxSize );\n        }\n    }\n    \n    void default_resizeGLObjectBuffers( unsigned int maxSize ) {\n        osg::Texture::resizeGLObjectBuffers( maxSize );\n    }\n\n    virtual void setName( ::std::string const & name ) {\n        if( bp::override func_setName = this->get_override( \"setName\" ) )\n            func_setName( name );\n        else{\n            this->osg::Object::setName( name );\n        }\n    }\n    \n    void default_setName( ::std::string const & name ) {\n        osg::Object::setName( name );\n    }\n\n    virtual void setThreadSafeRefUnref( bool threadSafe ) {\n        if( bp::override func_setThreadSafeRefUnref = this->get_override( \"setThreadSafeRefUnref\" ) )\n            func_setThreadSafeRefUnref( threadSafe );\n        else{\n            this->osg::Object::setThreadSafeRefUnref( threadSafe );\n        }\n    }\n    \n    void default_setThreadSafeRefUnref( bool threadSafe ) {\n        osg::Object::setThreadSafeRefUnref( threadSafe );\n    }\n\n    virtual void setUserData( ::osg::Referenced * obj ) {\n        if( bp::override func_setUserData = this->get_override( \"setUserData\" ) )\n            func_setUserData( boost::python::ptr(obj) );\n        else{\n            this->osg::Object::setUserData( boost::python::ptr(obj) );\n        }\n    }\n    \n    void default_setUserData( ::osg::Referenced * obj ) {\n        osg::Object::setUserData( boost::python::ptr(obj) );\n    }\n\n};\n\nvoid register_TextureRectangle_class(){\n\n    { \/\/::osg::TextureRectangle\n        typedef bp::class_< TextureRectangle_wrapper, bp::bases< osg::Texture >, osg::ref_ptr< ::osg::TextureRectangle >, boost::noncopyable > TextureRectangle_exposer_t;\n        TextureRectangle_exposer_t TextureRectangle_exposer = TextureRectangle_exposer_t( \"TextureRectangle\", \"\\n Texture state class which encapsulates OpenGL texture functionality.\\n\", bp::no_init );\n        bp::scope TextureRectangle_scope( TextureRectangle_exposer );\n        bp::class_< TextureRectangle_wrapper::SubloadCallback_wrapper, bp::bases< osg::Referenced >, osg::ref_ptr< TextureRectangle_wrapper::SubloadCallback_wrapper >, boost::noncopyable >( \"SubloadCallback\", bp::no_init )    \n            .def( \n                \"load\"\n                , (void (*)( ::osg::TextureRectangle::SubloadCallback const &,::osg::TextureRectangle &,::osg::State & ))( &TextureRectangle_wrapper::SubloadCallback_wrapper::default_load )\n                , ( bp::arg(\"inst\"), bp::arg(\"arg0\"), bp::arg(\"arg1\") ) )    \n            .def( \n                \"subload\"\n                , (void (*)( ::osg::TextureRectangle::SubloadCallback const &,::osg::TextureRectangle &,::osg::State & ))( &TextureRectangle_wrapper::SubloadCallback_wrapper::default_subload )\n                , ( bp::arg(\"inst\"), bp::arg(\"arg0\"), bp::arg(\"arg1\") ) )    \n            .def( \n                \"setThreadSafeRefUnref\"\n                , (void ( ::osg::Referenced::* )( bool ))(&::osg::Referenced::setThreadSafeRefUnref)\n                , (void ( TextureRectangle_wrapper::SubloadCallback_wrapper::* )( bool ))(&TextureRectangle_wrapper::SubloadCallback_wrapper::default_setThreadSafeRefUnref)\n                , ( bp::arg(\"threadSafe\") ) );\n        TextureRectangle_exposer.def( bp::init< >(\"\\n Texture state class which encapsulates OpenGL texture functionality.\\n\") );\n        TextureRectangle_exposer.def( bp::init< osg::Image * >(( bp::arg(\"image\") )) );\n        bp::implicitly_convertible< osg::Image *, osg::TextureRectangle >();\n        { \/\/::osg::TextureRectangle::apply\n        \n            typedef void ( ::osg::TextureRectangle::*apply_function_type)( ::osg::State & ) const;\n            typedef void ( TextureRectangle_wrapper::*default_apply_function_type)( ::osg::State & ) const;\n            \n            TextureRectangle_exposer.def( \n                \"apply\"\n                , apply_function_type(&::osg::TextureRectangle::apply)\n                , default_apply_function_type(&TextureRectangle_wrapper::default_apply)\n                , ( bp::arg(\"state\") ) );\n        \n        }\n        { \/\/::osg::TextureRectangle::className\n        \n            typedef char const * ( ::osg::TextureRectangle::*className_function_type)(  ) const;\n            typedef char const * ( TextureRectangle_wrapper::*default_className_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"className\"\n                , className_function_type(&::osg::TextureRectangle::className)\n                , default_className_function_type(&TextureRectangle_wrapper::default_className) );\n        \n        }\n        { \/\/::osg::TextureRectangle::clone\n        \n            typedef ::osg::Object * ( ::osg::TextureRectangle::*clone_function_type)( ::osg::CopyOp const & ) const;\n            typedef ::osg::Object * ( TextureRectangle_wrapper::*default_clone_function_type)( ::osg::CopyOp const & ) const;\n            \n            TextureRectangle_exposer.def( \n                \"clone\"\n                , clone_function_type(&::osg::TextureRectangle::clone)\n                , default_clone_function_type(&TextureRectangle_wrapper::default_clone)\n                , ( bp::arg(\"copyop\") )\n                , bp::return_value_policy< bp::reference_existing_object >() );\n        \n        }\n        { \/\/::osg::TextureRectangle::cloneType\n        \n            typedef ::osg::Object * ( ::osg::TextureRectangle::*cloneType_function_type)(  ) const;\n            typedef ::osg::Object * ( TextureRectangle_wrapper::*default_cloneType_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"cloneType\"\n                , cloneType_function_type(&::osg::TextureRectangle::cloneType)\n                , default_cloneType_function_type(&TextureRectangle_wrapper::default_cloneType)\n                , bp::return_value_policy< bp::reference_existing_object >() );\n        \n        }\n        { \/\/::osg::TextureRectangle::copyTexImage2D\n        \n            typedef void ( ::osg::TextureRectangle::*copyTexImage2D_function_type)( ::osg::State &,int,int,int,int ) ;\n            \n            TextureRectangle_exposer.def( \n                \"copyTexImage2D\"\n                , copyTexImage2D_function_type( &::osg::TextureRectangle::copyTexImage2D )\n                , ( bp::arg(\"state\"), bp::arg(\"x\"), bp::arg(\"y\"), bp::arg(\"width\"), bp::arg(\"height\") )\n                , \" Copies pixels into a 2D texture image, as per glCopyTexImage2D.\\n Creates an OpenGL texture object from the current OpenGL background\\n framebuffer contents at position C{x,} C{y} with width C{width} and\\n height C{height.} C{width} and C{height} must be a power of two.\" );\n        \n        }\n        { \/\/::osg::TextureRectangle::copyTexSubImage2D\n        \n            typedef void ( ::osg::TextureRectangle::*copyTexSubImage2D_function_type)( ::osg::State &,int,int,int,int,int,int ) ;\n            \n            TextureRectangle_exposer.def( \n                \"copyTexSubImage2D\"\n                , copyTexSubImage2D_function_type( &::osg::TextureRectangle::copyTexSubImage2D )\n                , ( bp::arg(\"state\"), bp::arg(\"xoffset\"), bp::arg(\"yoffset\"), bp::arg(\"x\"), bp::arg(\"y\"), bp::arg(\"width\"), bp::arg(\"height\") )\n                , \" Copies a two-dimensional texture subimage, as per\\n glCopyTexSubImage2D. Updates a portion of an existing OpenGL\\n texture object from the current OpenGL background framebuffer\\n contents at position C{x,} C{y} with width C{width} and height\\n C{height.} Loads framebuffer data into the texture using offsets\\n C{xoffset} and C{yoffset.} C{width} and C{height} must be powers\\n of two.\" );\n        \n        }\n        { \/\/::osg::TextureRectangle::getImage\n        \n            typedef ::osg::Image * ( ::osg::TextureRectangle::*getImage_function_type)(  ) ;\n            \n            TextureRectangle_exposer.def( \n                \"getImage\"\n                , getImage_function_type( &::osg::TextureRectangle::getImage )\n                , bp::return_internal_reference< >()\n                , \" Get the texture image.\" );\n        \n        }\n        { \/\/::osg::TextureRectangle::getImage\n        \n            typedef ::osg::Image const * ( ::osg::TextureRectangle::*getImage_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"getImage\"\n                , getImage_function_type( &::osg::TextureRectangle::getImage )\n                , bp::return_internal_reference< >()\n                , \" Get the const texture image.\" );\n        \n        }\n        { \/\/::osg::TextureRectangle::getImage\n        \n            typedef ::osg::Image * ( ::osg::TextureRectangle::*getImage_function_type)( unsigned int ) ;\n            typedef ::osg::Image * ( TextureRectangle_wrapper::*default_getImage_function_type)( unsigned int ) ;\n            \n            TextureRectangle_exposer.def( \n                \"getImage\"\n                , getImage_function_type(&::osg::TextureRectangle::getImage)\n                , default_getImage_function_type(&TextureRectangle_wrapper::default_getImage)\n                , ( bp::arg(\"arg0\") )\n                , bp::return_internal_reference< >() );\n        \n        }\n        { \/\/::osg::TextureRectangle::getImage\n        \n            typedef ::osg::Image const * ( ::osg::TextureRectangle::*getImage_function_type)( unsigned int ) const;\n            typedef ::osg::Image const * ( TextureRectangle_wrapper::*default_getImage_function_type)( unsigned int ) const;\n            \n            TextureRectangle_exposer.def( \n                \"getImage\"\n                , getImage_function_type(&::osg::TextureRectangle::getImage)\n                , default_getImage_function_type(&TextureRectangle_wrapper::default_getImage)\n                , ( bp::arg(\"arg0\") )\n                , bp::return_internal_reference< >() );\n        \n        }\n        { \/\/::osg::TextureRectangle::getModifiedCount\n        \n            typedef unsigned int & ( ::osg::TextureRectangle::*getModifiedCount_function_type)( unsigned int ) const;\n            \n            TextureRectangle_exposer.def( \n                \"getModifiedCount\"\n                , getModifiedCount_function_type( &::osg::TextureRectangle::getModifiedCount )\n                , ( bp::arg(\"contextID\") )\n                , bp::return_value_policy< bp::copy_non_const_reference >() );\n        \n        }\n        { \/\/::osg::TextureRectangle::getNumImages\n        \n            typedef unsigned int ( ::osg::TextureRectangle::*getNumImages_function_type)(  ) const;\n            typedef unsigned int ( TextureRectangle_wrapper::*default_getNumImages_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"getNumImages\"\n                , getNumImages_function_type(&::osg::TextureRectangle::getNumImages)\n                , default_getNumImages_function_type(&TextureRectangle_wrapper::default_getNumImages) );\n        \n        }\n        { \/\/::osg::TextureRectangle::getSubloadCallback\n        \n            typedef ::osg::TextureRectangle::SubloadCallback * ( ::osg::TextureRectangle::*getSubloadCallback_function_type)(  ) ;\n            \n            TextureRectangle_exposer.def( \n                \"getSubloadCallback\"\n                , getSubloadCallback_function_type( &::osg::TextureRectangle::getSubloadCallback )\n                , bp::return_internal_reference< >() );\n        \n        }\n        { \/\/::osg::TextureRectangle::getSubloadCallback\n        \n            typedef ::osg::TextureRectangle::SubloadCallback const * ( ::osg::TextureRectangle::*getSubloadCallback_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"getSubloadCallback\"\n                , getSubloadCallback_function_type( &::osg::TextureRectangle::getSubloadCallback )\n                , bp::return_internal_reference< >() );\n        \n        }\n        { \/\/::osg::TextureRectangle::getTextureDepth\n        \n            typedef int ( ::osg::TextureRectangle::*getTextureDepth_function_type)(  ) const;\n            typedef int ( TextureRectangle_wrapper::*default_getTextureDepth_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"getTextureDepth\"\n                , getTextureDepth_function_type(&::osg::TextureRectangle::getTextureDepth)\n                , default_getTextureDepth_function_type(&TextureRectangle_wrapper::default_getTextureDepth) );\n        \n        }\n        { \/\/::osg::TextureRectangle::getTextureHeight\n        \n            typedef int ( ::osg::TextureRectangle::*getTextureHeight_function_type)(  ) const;\n            typedef int ( TextureRectangle_wrapper::*default_getTextureHeight_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"getTextureHeight\"\n                , getTextureHeight_function_type(&::osg::TextureRectangle::getTextureHeight)\n                , default_getTextureHeight_function_type(&TextureRectangle_wrapper::default_getTextureHeight) );\n        \n        }\n        { \/\/::osg::TextureRectangle::getTextureTarget\n        \n            typedef ::GLenum ( ::osg::TextureRectangle::*getTextureTarget_function_type)(  ) const;\n            typedef ::GLenum ( TextureRectangle_wrapper::*default_getTextureTarget_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"getTextureTarget\"\n                , getTextureTarget_function_type(&::osg::TextureRectangle::getTextureTarget)\n                , default_getTextureTarget_function_type(&TextureRectangle_wrapper::default_getTextureTarget) );\n        \n        }\n        { \/\/::osg::TextureRectangle::getTextureWidth\n        \n            typedef int ( ::osg::TextureRectangle::*getTextureWidth_function_type)(  ) const;\n            typedef int ( TextureRectangle_wrapper::*default_getTextureWidth_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"getTextureWidth\"\n                , getTextureWidth_function_type(&::osg::TextureRectangle::getTextureWidth)\n                , default_getTextureWidth_function_type(&TextureRectangle_wrapper::default_getTextureWidth) );\n        \n        }\n        { \/\/::osg::TextureRectangle::getType\n        \n            typedef ::osg::StateAttribute::Type ( ::osg::TextureRectangle::*getType_function_type)(  ) const;\n            typedef ::osg::StateAttribute::Type ( TextureRectangle_wrapper::*default_getType_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"getType\"\n                , getType_function_type(&::osg::TextureRectangle::getType)\n                , default_getType_function_type(&TextureRectangle_wrapper::default_getType) );\n        \n        }\n        { \/\/::osg::TextureRectangle::isSameKindAs\n        \n            typedef bool ( ::osg::TextureRectangle::*isSameKindAs_function_type)( ::osg::Object const * ) const;\n            typedef bool ( TextureRectangle_wrapper::*default_isSameKindAs_function_type)( ::osg::Object const * ) const;\n            \n            TextureRectangle_exposer.def( \n                \"isSameKindAs\"\n                , isSameKindAs_function_type(&::osg::TextureRectangle::isSameKindAs)\n                , default_isSameKindAs_function_type(&TextureRectangle_wrapper::default_isSameKindAs)\n                , ( bp::arg(\"obj\") ) );\n        \n        }\n        { \/\/::osg::TextureRectangle::libraryName\n        \n            typedef char const * ( ::osg::TextureRectangle::*libraryName_function_type)(  ) const;\n            typedef char const * ( TextureRectangle_wrapper::*default_libraryName_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"libraryName\"\n                , libraryName_function_type(&::osg::TextureRectangle::libraryName)\n                , default_libraryName_function_type(&TextureRectangle_wrapper::default_libraryName) );\n        \n        }\n        { \/\/::osg::TextureRectangle::setImage\n        \n            typedef void ( ::osg::TextureRectangle::*setImage_function_type)( ::osg::Image * ) ;\n            \n            TextureRectangle_exposer.def( \n                \"setImage\"\n                , setImage_function_type( &::osg::TextureRectangle::setImage )\n                , ( bp::arg(\"image\") )\n                , \" Set the texture image.\" );\n        \n        }\n        { \/\/::osg::TextureRectangle::setImage\n        \n            typedef void ( ::osg::TextureRectangle::*setImage_function_type)( unsigned int,::osg::Image * ) ;\n            typedef void ( TextureRectangle_wrapper::*default_setImage_function_type)( unsigned int,::osg::Image * ) ;\n            \n            TextureRectangle_exposer.def( \n                \"setImage\"\n                , setImage_function_type(&::osg::TextureRectangle::setImage)\n                , default_setImage_function_type(&TextureRectangle_wrapper::default_setImage)\n                , ( bp::arg(\"arg0\"), bp::arg(\"image\") ) );\n        \n        }\n        { \/\/::osg::TextureRectangle::setSubloadCallback\n        \n            typedef void ( ::osg::TextureRectangle::*setSubloadCallback_function_type)( ::osg::TextureRectangle::SubloadCallback * ) ;\n            \n            TextureRectangle_exposer.def( \n                \"setSubloadCallback\"\n                , setSubloadCallback_function_type( &::osg::TextureRectangle::setSubloadCallback )\n                , ( bp::arg(\"cb\") ) );\n        \n        }\n        { \/\/::osg::TextureRectangle::setTextureHeight\n        \n            typedef void ( ::osg::TextureRectangle::*setTextureHeight_function_type)( int ) ;\n            \n            TextureRectangle_exposer.def( \n                \"setTextureHeight\"\n                , setTextureHeight_function_type( &::osg::TextureRectangle::setTextureHeight )\n                , ( bp::arg(\"height\") ) );\n        \n        }\n        { \/\/::osg::TextureRectangle::setTextureSize\n        \n            typedef void ( ::osg::TextureRectangle::*setTextureSize_function_type)( int,int ) const;\n            \n            TextureRectangle_exposer.def( \n                \"setTextureSize\"\n                , setTextureSize_function_type( &::osg::TextureRectangle::setTextureSize )\n                , ( bp::arg(\"width\"), bp::arg(\"height\") )\n                , \" Set the texture width and height. If width or height are zero then\\n the respective size value is calculated from the source image sizes.\" );\n        \n        }\n        { \/\/::osg::TextureRectangle::setTextureWidth\n        \n            typedef void ( ::osg::TextureRectangle::*setTextureWidth_function_type)( int ) ;\n            \n            TextureRectangle_exposer.def( \n                \"setTextureWidth\"\n                , setTextureWidth_function_type( &::osg::TextureRectangle::setTextureWidth )\n                , ( bp::arg(\"width\") ) );\n        \n        }\n        { \/\/::osg::Texture::asTexture\n        \n            typedef ::osg::Texture * ( ::osg::Texture::*asTexture_function_type)(  ) ;\n            typedef ::osg::Texture * ( TextureRectangle_wrapper::*default_asTexture_function_type)(  ) ;\n            \n            TextureRectangle_exposer.def( \n                \"asTexture\"\n                , asTexture_function_type(&::osg::Texture::asTexture)\n                , default_asTexture_function_type(&TextureRectangle_wrapper::default_asTexture)\n                , bp::return_internal_reference< >() );\n        \n        }\n        { \/\/::osg::Texture::asTexture\n        \n            typedef ::osg::Texture const * ( ::osg::Texture::*asTexture_function_type)(  ) const;\n            typedef ::osg::Texture const * ( TextureRectangle_wrapper::*default_asTexture_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"asTexture\"\n                , asTexture_function_type(&::osg::Texture::asTexture)\n                , default_asTexture_function_type(&TextureRectangle_wrapper::default_asTexture)\n                , bp::return_internal_reference< >() );\n        \n        }\n        { \/\/::osg::StateAttribute::checkValidityOfAssociatedModes\n        \n            typedef bool ( ::osg::StateAttribute::*checkValidityOfAssociatedModes_function_type)( ::osg::State & ) const;\n            typedef bool ( TextureRectangle_wrapper::*default_checkValidityOfAssociatedModes_function_type)( ::osg::State & ) const;\n            \n            TextureRectangle_exposer.def( \n                \"checkValidityOfAssociatedModes\"\n                , checkValidityOfAssociatedModes_function_type(&::osg::StateAttribute::checkValidityOfAssociatedModes)\n                , default_checkValidityOfAssociatedModes_function_type(&TextureRectangle_wrapper::default_checkValidityOfAssociatedModes)\n                , ( bp::arg(\"arg0\") ) );\n        \n        }\n        { \/\/::osg::Texture::compileGLObjects\n        \n            typedef void ( ::osg::Texture::*compileGLObjects_function_type)( ::osg::State & ) const;\n            typedef void ( TextureRectangle_wrapper::*default_compileGLObjects_function_type)( ::osg::State & ) const;\n            \n            TextureRectangle_exposer.def( \n                \"compileGLObjects\"\n                , compileGLObjects_function_type(&::osg::Texture::compileGLObjects)\n                , default_compileGLObjects_function_type(&TextureRectangle_wrapper::default_compileGLObjects)\n                , ( bp::arg(\"state\") ) );\n        \n        }\n        { \/\/::osg::Object::computeDataVariance\n        \n            typedef void ( ::osg::Object::*computeDataVariance_function_type)(  ) ;\n            typedef void ( TextureRectangle_wrapper::*default_computeDataVariance_function_type)(  ) ;\n            \n            TextureRectangle_exposer.def( \n                \"computeDataVariance\"\n                , computeDataVariance_function_type(&::osg::Object::computeDataVariance)\n                , default_computeDataVariance_function_type(&TextureRectangle_wrapper::default_computeDataVariance) );\n        \n        }\n        { \/\/::osg::StateAttribute::getMember\n        \n            typedef unsigned int ( ::osg::StateAttribute::*getMember_function_type)(  ) const;\n            typedef unsigned int ( TextureRectangle_wrapper::*default_getMember_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"getMember\"\n                , getMember_function_type(&::osg::StateAttribute::getMember)\n                , default_getMember_function_type(&TextureRectangle_wrapper::default_getMember) );\n        \n        }\n        { \/\/::osg::Texture::getModeUsage\n        \n            typedef bool ( ::osg::Texture::*getModeUsage_function_type)( ::osg::StateAttribute::ModeUsage & ) const;\n            typedef bool ( TextureRectangle_wrapper::*default_getModeUsage_function_type)( ::osg::StateAttribute::ModeUsage & ) const;\n            \n            TextureRectangle_exposer.def( \n                \"getModeUsage\"\n                , getModeUsage_function_type(&::osg::Texture::getModeUsage)\n                , default_getModeUsage_function_type(&TextureRectangle_wrapper::default_getModeUsage)\n                , ( bp::arg(\"usage\") ) );\n        \n        }\n        { \/\/::osg::Object::getUserData\n        \n            typedef ::osg::Referenced * ( ::osg::Object::*getUserData_function_type)(  ) ;\n            typedef ::osg::Referenced * ( TextureRectangle_wrapper::*default_getUserData_function_type)(  ) ;\n            \n            TextureRectangle_exposer.def( \n                \"getUserData\"\n                , getUserData_function_type(&::osg::Object::getUserData)\n                , default_getUserData_function_type(&TextureRectangle_wrapper::default_getUserData)\n                , bp::return_internal_reference< >() );\n        \n        }\n        { \/\/::osg::Object::getUserData\n        \n            typedef ::osg::Referenced const * ( ::osg::Object::*getUserData_function_type)(  ) const;\n            typedef ::osg::Referenced const * ( TextureRectangle_wrapper::*default_getUserData_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"getUserData\"\n                , getUserData_function_type(&::osg::Object::getUserData)\n                , default_getUserData_function_type(&TextureRectangle_wrapper::default_getUserData)\n                , bp::return_internal_reference< >() );\n        \n        }\n        { \/\/::osg::Texture::isTextureAttribute\n        \n            typedef bool ( ::osg::Texture::*isTextureAttribute_function_type)(  ) const;\n            typedef bool ( TextureRectangle_wrapper::*default_isTextureAttribute_function_type)(  ) const;\n            \n            TextureRectangle_exposer.def( \n                \"isTextureAttribute\"\n                , isTextureAttribute_function_type(&::osg::Texture::isTextureAttribute)\n                , default_isTextureAttribute_function_type(&TextureRectangle_wrapper::default_isTextureAttribute) );\n        \n        }\n        { \/\/::osg::Texture::resizeGLObjectBuffers\n        \n            typedef void ( ::osg::Texture::*resizeGLObjectBuffers_function_type)( unsigned int ) ;\n            typedef void ( TextureRectangle_wrapper::*default_resizeGLObjectBuffers_function_type)( unsigned int ) ;\n            \n            TextureRectangle_exposer.def( \n                \"resizeGLObjectBuffers\"\n                , resizeGLObjectBuffers_function_type(&::osg::Texture::resizeGLObjectBuffers)\n                , default_resizeGLObjectBuffers_function_type(&TextureRectangle_wrapper::default_resizeGLObjectBuffers)\n                , ( bp::arg(\"maxSize\") ) );\n        \n        }\n        { \/\/::osg::Object::setName\n        \n            typedef void ( ::osg::Object::*setName_function_type)( ::std::string const & ) ;\n            typedef void ( TextureRectangle_wrapper::*default_setName_function_type)( ::std::string const & ) ;\n            \n            TextureRectangle_exposer.def( \n                \"setName\"\n                , setName_function_type(&::osg::Object::setName)\n                , default_setName_function_type(&TextureRectangle_wrapper::default_setName)\n                , ( bp::arg(\"name\") ) );\n        \n        }\n        { \/\/::osg::Object::setName\n        \n            typedef void ( ::osg::Object::*setName_function_type)( char const * ) ;\n            \n            TextureRectangle_exposer.def( \n                \"setName\"\n                , setName_function_type( &::osg::Object::setName )\n                , ( bp::arg(\"name\") )\n                , \" Set the name of object using a C style string.\" );\n        \n        }\n        { \/\/::osg::Object::setThreadSafeRefUnref\n        \n            typedef void ( ::osg::Object::*setThreadSafeRefUnref_function_type)( bool ) ;\n            typedef void ( TextureRectangle_wrapper::*default_setThreadSafeRefUnref_function_type)( bool ) ;\n            \n            TextureRectangle_exposer.def( \n                \"setThreadSafeRefUnref\"\n                , setThreadSafeRefUnref_function_type(&::osg::Object::setThreadSafeRefUnref)\n                , default_setThreadSafeRefUnref_function_type(&TextureRectangle_wrapper::default_setThreadSafeRefUnref)\n                , ( bp::arg(\"threadSafe\") ) );\n        \n        }\n        { \/\/::osg::Object::setUserData\n        \n            typedef void ( ::osg::Object::*setUserData_function_type)( ::osg::Referenced * ) ;\n            typedef void ( TextureRectangle_wrapper::*default_setUserData_function_type)( ::osg::Referenced * ) ;\n            \n            TextureRectangle_exposer.def( \n                \"setUserData\"\n                , setUserData_function_type(&::osg::Object::setUserData)\n                , default_setUserData_function_type(&TextureRectangle_wrapper::default_setUserData)\n                , ( bp::arg(\"obj\") ) );\n        \n        }\n    }\n\n}\n","avg_line_length":44.2016895459,"max_line_length":409,"alphanum_fraction":0.5940419026,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":11032,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2014-2016 The Dash developers\n\/\/ Copyright (c) 2016-2018 The KONG Developers \n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"spork.h\"\n#include \"base58.h\"\n#include \"key.h\"\n#include \"main.h\"\n#include \"masternode-budget.h\"\n#include \"net.h\"\n#include \"protocol.h\"\n#include \"sync.h\"\n#include \"sporkdb.h\"\n#include \"util.h\"\n\nusing namespace std;\nusing namespace boost;\n\nclass CSporkMessage;\nclass CSporkManager;\n\nCSporkManager sporkManager;\n\nstd::map<uint256, CSporkMessage> mapSporks;\nstd::map<int, CSporkMessage> mapSporksActive;\n\n\/\/ KONGCOIN: on startup load spork values from previous session if they exist in the sporkDB\nvoid LoadSporksFromDB()\n{\n    for (int i = SPORK_START; i <= SPORK_END; ++i) {\n        \/\/ Since not all spork IDs are in use, we have to exclude undefined IDs\n        std::string strSpork = sporkManager.GetSporkNameByID(i);\n        if (strSpork == \"Unknown\") continue;\n\n        \/\/ attempt to read spork from sporkDB\n        CSporkMessage spork;\n        if (!pSporkDB->ReadSpork(i, spork)) {\n            LogPrintf(\"%s : no previous value for %s found in database\\n\", __func__, strSpork);\n            continue;\n        }\n\n        \/\/ add spork to memory\n        mapSporks[spork.GetHash()] = spork;\n        mapSporksActive[spork.nSporkID] = spork;\n        std::time_t result = spork.nValue;\n        \/\/ If SPORK Value is greater than 1,000,000 assume it's actually a Date and then convert to a more readable format\n        if (spork.nValue > 1000000) {\n            LogPrintf(\"%s : loaded spork %s with value %d : %s\", __func__,\n                      sporkManager.GetSporkNameByID(spork.nSporkID), spork.nValue,\n                      std::ctime(&result));\n        } else {\n            LogPrintf(\"%s : loaded spork %s with value %d\\n\", __func__,\n                      sporkManager.GetSporkNameByID(spork.nSporkID), spork.nValue);\n        }\n    }\n}\n\nvoid ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)\n{\n    if (fLiteMode) return; \/\/disable all obfuscation\/masternode related functionality\n\n    if (strCommand == \"spork\") {\n        \/\/LogPrintf(\"ProcessSpork::spork\\n\");\n        CDataStream vMsg(vRecv);\n        CSporkMessage spork;\n        vRecv >> spork;\n\n        if (chainActive.Tip() == NULL) return;\n\n        \/\/ Ignore spork messages about unknown\/deleted sporks\n        std::string strSpork = sporkManager.GetSporkNameByID(spork.nSporkID);\n        if (strSpork == \"Unknown\") return;\n\n        uint256 hash = spork.GetHash();\n        if (mapSporksActive.count(spork.nSporkID)) {\n            if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) {\n                if (fDebug) LogPrintf(\"%s : seen %s block %d \\n\", __func__, hash.ToString(), chainActive.Tip()->nHeight);\n                return;\n            } else {\n                if (fDebug) LogPrintf(\"%s : got updated spork %s block %d \\n\", __func__, hash.ToString(), chainActive.Tip()->nHeight);\n            }\n        }\n\n        LogPrintf(\"%s : new %s ID %d Time %d bestHeight %d\\n\", __func__, hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Tip()->nHeight);\n\n        \/\/ if (spork.nTimeSigned >= Params().NewSporkStart()) {\n        \/\/     if (!sporkManager.CheckSignature(spork, true)) {\n        \/\/         LogPrintf(\"%s : Invalid Signature\\n\", __func__);\n        \/\/         Misbehaving(pfrom->GetId(), 100);\n        \/\/         return;\n        \/\/     }\n        \/\/ }\n\n        if (!sporkManager.CheckSignature(spork)) {\n            LogPrintf(\"%s : Invalid Signature\\n\", __func__);\n            Misbehaving(pfrom->GetId(), 100);\n            return;\n        }\n\n        mapSporks[hash] = spork;\n        mapSporksActive[spork.nSporkID] = spork;\n        sporkManager.Relay(spork);\n\n        \/\/ KONGCOIN: add to spork database.\n        pSporkDB->WriteSpork(spork.nSporkID, spork);\n    }\n    if (strCommand == \"getsporks\") {\n        std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin();\n\n        while (it != mapSporksActive.end()) {\n            pfrom->PushMessage(\"spork\", it->second);\n            it++;\n        }\n    }\n}\n\n\n\/\/ grab the value of the spork on the network, or the default\nint64_t GetSporkValue(int nSporkID)\n{\n    int64_t r = -1;\n\n    if (mapSporksActive.count(nSporkID)) {\n        r = mapSporksActive[nSporkID].nValue;\n    } else {\n        if (nSporkID == SPORK_2_SWIFTTX) r = SPORK_2_SWIFTTX_DEFAULT;\n        if (nSporkID == SPORK_3_SWIFTTX_BLOCK_FILTERING) r = SPORK_3_SWIFTTX_BLOCK_FILTERING_DEFAULT;\n        if (nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;\n        if (nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;\n        if (nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;\n        if (nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;\n        if (nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;\n        if (nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;\n        if (nSporkID == SPORK_14_NEW_PROTOCOL_ENFORCEMENT) r = SPORK_14_NEW_PROTOCOL_ENFORCEMENT_DEFAULT;\n        if (nSporkID == SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) r = SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2_DEFAULT;\n        if (nSporkID == SPORK_16_ZEROCOIN_MAINTENANCE_MODE) r = SPORK_16_ZEROCOIN_MAINTENANCE_MODE_DEFAULT;\n\n        if (r == -1) LogPrintf(\"%s : Unknown Spork %d\\n\", __func__, nSporkID);\n    }\n\n    return r;\n}\n\n\/\/ grab the spork value, and see if it's off\nbool IsSporkActive(int nSporkID)\n{\n    int64_t r = GetSporkValue(nSporkID);\n    if (r == -1) return false;\n    return r < GetTime();\n}\n\n\nvoid ReprocessBlocks(int nBlocks)\n{\n    std::map<uint256, int64_t>::iterator it = mapRejectedBlocks.begin();\n    while (it != mapRejectedBlocks.end()) {\n        \/\/use a window twice as large as is usual for the nBlocks we want to reset\n        if ((*it).second > GetTime() - (nBlocks * 60 * 5)) {\n            BlockMap::iterator mi = mapBlockIndex.find((*it).first);\n            if (mi != mapBlockIndex.end() && (*mi).second) {\n                LOCK(cs_main);\n\n                CBlockIndex* pindex = (*mi).second;\n                LogPrintf(\"ReprocessBlocks - %s\\n\", (*it).first.ToString());\n\n                CValidationState state;\n                ReconsiderBlock(state, pindex);\n            }\n        }\n        ++it;\n    }\n\n    CValidationState state;\n    {\n        LOCK(cs_main);\n        DisconnectBlocksAndReprocess(nBlocks);\n    }\n\n    if (state.IsValid()) {\n        ActivateBestChain(state);\n    }\n}\n\nbool CSporkManager::CheckSignature(CSporkMessage& spork)\n{\n    \/\/note: need to investigate why this is failing\n    std::string strMessage = std::to_string(spork.nSporkID) + std::to_string(spork.nValue) + std::to_string(spork.nTimeSigned);\n    CPubKey pubkeynew(ParseHex(Params().SporkKey()));\n    std::string errorMessage = \"\";\n\n    bool result = obfuScationSigner.VerifyMessage(pubkeynew, spork.vchSig,strMessage, errorMessage);\n    if(!result){\n        LogPrintf(\"%s - %s\", __func__, errorMessage);\n    }\n\n    return result;\n}\n\nbool CSporkManager::Sign(CSporkMessage& spork)\n{\n    std::string strMessage = std::to_string(spork.nSporkID) + std::to_string(spork.nValue) + std::to_string(spork.nTimeSigned);\n\n    CKey key2;\n    CPubKey pubkey2;\n    std::string errorMessage = \"\";\n\n    if (!obfuScationSigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2)) {\n        LogPrintf(\"CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\\n\", errorMessage);\n        return false;\n    }\n\n    if (!obfuScationSigner.SignMessage(strMessage, errorMessage, spork.vchSig, key2)) {\n        LogPrintf(\"CMasternodePayments::Sign - Sign message failed\");\n        return false;\n    }\n\n    if (!obfuScationSigner.VerifyMessage(pubkey2, spork.vchSig, strMessage, errorMessage)) {\n        LogPrintf(\"CMasternodePayments::Sign - Verify message failed\");\n        return false;\n    }\n\n    return true;\n}\n\nbool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue)\n{\n    CSporkMessage msg;\n    msg.nSporkID = nSporkID;\n    msg.nValue = nValue;\n    msg.nTimeSigned = GetTime();\n\n    if (Sign(msg)) {\n        Relay(msg);\n        mapSporks[msg.GetHash()] = msg;\n        mapSporksActive[nSporkID] = msg;\n        return true;\n    }\n\n    return false;\n}\n\nvoid CSporkManager::Relay(CSporkMessage& msg)\n{\n    CInv inv(MSG_SPORK, msg.GetHash());\n    RelayInv(inv);\n}\n\nbool CSporkManager::SetPrivKey(std::string strPrivKey)\n{\n    CSporkMessage msg;\n\n    \/\/ Test signing successful, proceed\n    strMasterPrivKey = strPrivKey;\n\n    Sign(msg);\n\n    if (CheckSignature(msg)) {\n        LogPrintf(\"CSporkManager::SetPrivKey - Successfully initialized as spork signer\\n\");\n        return true;\n    } else {\n        return false;\n    }\n}\n\nint CSporkManager::GetSporkIDByName(std::string strName)\n{\n    if (strName == \"SPORK_2_SWIFTTX\") return SPORK_2_SWIFTTX;\n    if (strName == \"SPORK_3_SWIFTTX_BLOCK_FILTERING\") return SPORK_3_SWIFTTX_BLOCK_FILTERING;\n    if (strName == \"SPORK_5_MAX_VALUE\") return SPORK_5_MAX_VALUE;\n    if (strName == \"SPORK_7_MASTERNODE_SCANNING\") return SPORK_7_MASTERNODE_SCANNING;\n    if (strName == \"SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT\") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT;\n    if (strName == \"SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT\") return SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT;\n    if (strName == \"SPORK_10_MASTERNODE_PAY_UPDATED_NODES\") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES;\n    if (strName == \"SPORK_13_ENABLE_SUPERBLOCKS\") return SPORK_13_ENABLE_SUPERBLOCKS;\n    if (strName == \"SPORK_14_NEW_PROTOCOL_ENFORCEMENT\") return SPORK_14_NEW_PROTOCOL_ENFORCEMENT;\n    if (strName == \"SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2\") return SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2;\n    if (strName == \"SPORK_16_ZEROCOIN_MAINTENANCE_MODE\") return SPORK_16_ZEROCOIN_MAINTENANCE_MODE;\n\n    return -1;\n}\n\nstd::string CSporkManager::GetSporkNameByID(int id)\n{\n    if (id == SPORK_2_SWIFTTX) return \"SPORK_2_SWIFTTX\";\n    if (id == SPORK_3_SWIFTTX_BLOCK_FILTERING) return \"SPORK_3_SWIFTTX_BLOCK_FILTERING\";\n    if (id == SPORK_5_MAX_VALUE) return \"SPORK_5_MAX_VALUE\";\n    if (id == SPORK_7_MASTERNODE_SCANNING) return \"SPORK_7_MASTERNODE_SCANNING\";\n    if (id == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) return \"SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT\";\n    if (id == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) return \"SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT\";\n    if (id == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) return \"SPORK_10_MASTERNODE_PAY_UPDATED_NODES\";\n    if (id == SPORK_13_ENABLE_SUPERBLOCKS) return \"SPORK_13_ENABLE_SUPERBLOCKS\";\n    if (id == SPORK_14_NEW_PROTOCOL_ENFORCEMENT) return \"SPORK_14_NEW_PROTOCOL_ENFORCEMENT\";\n    if (id == SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) return \"SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2\";\n    if (id == SPORK_16_ZEROCOIN_MAINTENANCE_MODE) return \"SPORK_16_ZEROCOIN_MAINTENANCE_MODE\";\n\n    return \"Unknown\";\n}\n","avg_line_length":36.8963210702,"max_line_length":148,"alphanum_fraction":0.6730420595,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1376,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":36.0,"content":"#include <cstdio>\n#include <vector>\n#include <algorithm>\n\nint main(){\n\n    const int N = 4;\n    std::vector<long> num(N); scanf(\"%ld %ld %ld %ld\\n\", &num[0], &num[1], &num[2], &num[3]);\n    std::vector<char> op(N - 1); scanf(\"%c %c %c\\n\", &op[0], &op[1], &op[2]);\n    long long output(1e13);\n    sort(num.begin(), num.end());\n\n    do{\n        long long current;\n        if(op[0] == '+'){current = num[0] + num[1];} else{current = num[0] * num[1];}\n        if(op[1] == '+'){current += num[2];} else{current *= num[2];}\n        if(op[2] == '+'){current += num[3];} else{current *= num[3];}\n        if(current < output){output = current;}\n\n        long long currentA, currentB;\n        if(op[0] == '+'){currentA = num[0] + num[1];} else{currentA = num[0] * num[1];}\n        if(op[1] == '+'){currentB = num[2] + num[3];} else{currentB = num[2] * num[3];}\n        if(op[2] == '+'){current = currentA + currentB;} else{current = currentA * currentB;}\n        if(current < output){output = current;}\n\n        if(op[0] == '+'){current = num[2] + num[3];} else{current = num[2] * num[3];}\n        if(op[1] == '+'){current += num[1];} else{current *= num[1];}\n        if(op[2] == '+'){current += num[0];} else{current *= num[0];}\n        if(current < output){output = current;}\n\n    }while(std::next_permutation(num.begin(), num.end()));\n\n    printf(\"%lld\\n\", output);\n\n    return 0;\n}\n","avg_line_length":37.1891891892,"max_line_length":93,"alphanum_fraction":0.5101744186,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6773,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":14.0,"content":"\/\/ Generated by dust (version 0.11.20) - do not edit\n#include <cpp11.hpp>\n\n[[cpp11::register]]\ncpp11::sexp dust_volatility_capabilities();\n\n[[cpp11::register]]\ncpp11::sexp dust_volatility_gpu_info();\n[[cpp11::register]]\nSEXP dust_cpu_volatility_alloc(cpp11::list r_pars, bool pars_multi, size_t step,\n                         cpp11::sexp r_n_particles, size_t n_threads,\n                         cpp11::sexp r_seed, bool deterministic,\n                         cpp11::sexp gpu_config);\n\n[[cpp11::register]]\nSEXP dust_cpu_volatility_run(SEXP ptr, size_t step_end);\n\n[[cpp11::register]]\nSEXP dust_cpu_volatility_simulate(SEXP ptr, cpp11::sexp step_end);\n\n[[cpp11::register]]\nSEXP dust_cpu_volatility_set_index(SEXP ptr, cpp11::sexp r_index);\n\n[[cpp11::register]]\nSEXP dust_cpu_volatility_update_state(SEXP ptr, SEXP r_pars, SEXP r_state,\n                                SEXP r_step, SEXP r_set_initial_state);\n\n[[cpp11::register]]\nSEXP dust_cpu_volatility_state(SEXP ptr, SEXP r_index);\n\n[[cpp11::register]]\nsize_t dust_cpu_volatility_step(SEXP ptr);\n\n[[cpp11::register]]\nvoid dust_cpu_volatility_reorder(SEXP ptr, cpp11::sexp r_index);\n\n[[cpp11::register]]\nSEXP dust_cpu_volatility_resample(SEXP ptr, cpp11::doubles r_weights);\n\n[[cpp11::register]]\nSEXP dust_cpu_volatility_rng_state(SEXP ptr, bool first_only, bool last_only);\n\n[[cpp11::register]]\nSEXP dust_cpu_volatility_set_rng_state(SEXP ptr, cpp11::raws rng_state);\n\n[[cpp11::register]]\nSEXP dust_cpu_volatility_set_data(SEXP ptr, cpp11::list data);\n\n[[cpp11::register]]\nSEXP dust_cpu_volatility_compare_data(SEXP ptr);\n\n[[cpp11::register]]\nSEXP dust_cpu_volatility_filter(SEXP ptr, bool save_trajectories,\n                          cpp11::sexp step_snapshot);\n\n[[cpp11::register]]\nvoid dust_cpu_volatility_set_n_threads(SEXP ptr, int n_threads);\n\n[[cpp11::register]]\nint dust_cpu_volatility_n_state(SEXP ptr);\n#include <dust\/r\/dust.hpp>\n\nclass volatility {\npublic:\n  using real_type = double;\n  using internal_type = dust::no_internal;\n  using rng_state_type = dust::random::generator<real_type>;\n\n  struct data_type {\n    real_type observed;\n  };\n\n  struct shared_type {\n    real_type alpha;\n    real_type sigma;\n    real_type gamma;\n    real_type tau;\n    real_type x0;\n  };\n\n  volatility(const dust::pars_type<volatility>& pars) : shared(pars.shared) {\n  }\n\n  size_t size() {\n    return 1;\n  }\n\n  std::vector<real_type> initial(size_t step) {\n    std::vector<real_type> state(1);\n    state[0] = shared->x0;\n    return state;\n  }\n\n  void update(size_t step, const real_type * state,\n              rng_state_type& rng_state, real_type * state_next) {\n    const real_type x = state[0];\n    state_next[0] = shared->alpha * x +\n      shared->sigma * dust::random::normal<real_type>(rng_state, 0, 1);\n  }\n\n  real_type compare_data(const real_type * state, const data_type& data,\n                         rng_state_type& rng_state) {\n    return dust::density::normal(data.observed, shared->gamma * state[0],\n                                 shared->tau, true);\n  }\n\nprivate:\n  dust::shared_ptr<volatility> shared;\n};\n\n\/\/ Helper function for accepting values with defaults\ninline double with_default(double default_value, cpp11::sexp value) {\n  return value == R_NilValue ? default_value : cpp11::as_cpp<double>(value);\n}\n\nnamespace dust {\n\ntemplate <>\ndust::pars_type<volatility> dust_pars<volatility>(cpp11::list pars) {\n  using real_type = volatility::real_type;\n  real_type x0 = 0;\n  real_type alpha = with_default(0.91, pars[\"alpha\"]);\n  real_type sigma = with_default(1, pars[\"sigma\"]);\n  real_type gamma = with_default(1, pars[\"gamma\"]);\n  real_type tau = with_default(1, pars[\"tau\"]);\n\n  volatility::shared_type shared{alpha, sigma, gamma, tau, x0};\n  return dust::pars_type<volatility>(shared);\n}\n\ntemplate <>\nvolatility::data_type dust_data<volatility>(cpp11::list data) {\n  return volatility::data_type{cpp11::as_cpp<double>(data[\"observed\"])};\n}\n\n}\n\ncpp11::sexp dust_volatility_capabilities() {\n  return dust::r::dust_capabilities<volatility>();\n}\n\ncpp11::sexp dust_volatility_gpu_info() {\n  return dust::gpu::r::gpu_info();\n}\nusing model_cpu = dust::dust_cpu<volatility>;\n\nSEXP dust_cpu_volatility_alloc(cpp11::list r_pars, bool pars_multi, size_t step,\n                             cpp11::sexp r_n_particles, size_t n_threads,\n                             cpp11::sexp r_seed, bool deterministic,\n                             cpp11::sexp gpu_config) {\n  return dust::r::dust_cpu_alloc<volatility>(r_pars, pars_multi, step, r_n_particles,\n                                        n_threads, r_seed, deterministic,\n                                        gpu_config);\n}\n\nSEXP dust_cpu_volatility_run(SEXP ptr, size_t step_end) {\n  return dust::r::dust_run<model_cpu>(ptr, step_end);\n}\n\nSEXP dust_cpu_volatility_simulate(SEXP ptr, cpp11::sexp step_end) {\n  return dust::r::dust_simulate<model_cpu>(ptr, step_end);\n}\n\nSEXP dust_cpu_volatility_set_index(SEXP ptr, cpp11::sexp r_index) {\n  dust::r::dust_set_index<model_cpu>(ptr, r_index);\n  return R_NilValue;\n}\n\nSEXP dust_cpu_volatility_update_state(SEXP ptr, SEXP r_pars, SEXP r_state,\n                                SEXP r_step, SEXP r_set_initial_state) {\n  return dust::r::dust_update_state<model_cpu>(ptr, r_pars, r_state, r_step,\n                                               r_set_initial_state);\n}\n\nSEXP dust_cpu_volatility_state(SEXP ptr, SEXP r_index) {\n  return dust::r::dust_state<model_cpu>(ptr, r_index);\n}\n\nsize_t dust_cpu_volatility_step(SEXP ptr) {\n  return dust::r::dust_step<model_cpu>(ptr);\n}\n\nvoid dust_cpu_volatility_reorder(SEXP ptr, cpp11::sexp r_index) {\n  return dust::r::dust_reorder<model_cpu>(ptr, r_index);\n}\n\nSEXP dust_cpu_volatility_resample(SEXP ptr, cpp11::doubles r_weights) {\n  return dust::r::dust_resample<model_cpu>(ptr, r_weights);\n}\n\nSEXP dust_cpu_volatility_rng_state(SEXP ptr, bool first_only, bool last_only) {\n  return dust::r::dust_rng_state<model_cpu>(ptr, first_only, last_only);\n}\n\nSEXP dust_cpu_volatility_set_rng_state(SEXP ptr, cpp11::raws rng_state) {\n  dust::r::dust_set_rng_state<model_cpu>(ptr, rng_state);\n  return R_NilValue;\n}\n\nSEXP dust_cpu_volatility_set_data(SEXP ptr, cpp11::list data) {\n  dust::r::dust_set_data<model_cpu>(ptr, data);\n  return R_NilValue;\n}\n\nSEXP dust_cpu_volatility_compare_data(SEXP ptr) {\n  return dust::r::dust_compare_data<model_cpu>(ptr);\n}\n\nSEXP dust_cpu_volatility_filter(SEXP ptr, bool save_trajectories,\n                          cpp11::sexp step_snapshot) {\n  return dust::r::dust_filter<model_cpu>(ptr, save_trajectories, step_snapshot);\n}\n\nvoid dust_cpu_volatility_set_n_threads(SEXP ptr, int n_threads) {\n  return dust::r::dust_set_n_threads<model_cpu>(ptr, n_threads);\n}\n\nint dust_cpu_volatility_n_state(SEXP ptr) {\n  return dust::r::dust_n_state<model_cpu>(ptr);\n}\n","avg_line_length":30.6470588235,"max_line_length":85,"alphanum_fraction":0.7020522664,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":924,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/\/ Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.\n\n#include \"BehaviorTree\/Tasks\/BTTask_SetTagCooldown.h\"\n\nUBTTask_SetTagCooldown::UBTTask_SetTagCooldown(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)\n{\n\tNodeName = \"Set Tag Cooldown\";\n\tCooldownDuration = 5.0f;\t\n\tbAddToExistingDuration = false;\n}\n\nEBTNodeResult::Type UBTTask_SetTagCooldown::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)\n{\n\tOwnerComp.AddCooldownTagDuration(CooldownTag, CooldownDuration, bAddToExistingDuration);\n\t\n\treturn EBTNodeResult::Succeeded;\n}\n\nFString UBTTask_SetTagCooldown::GetStaticDescription() const\n{\n\treturn FString::Printf(TEXT(\"%s %s: %.1fs\"), *Super::GetStaticDescription(), *CooldownTag.ToString(), CooldownDuration);\n}\n\n#if WITH_EDITOR\n\nFName UBTTask_SetTagCooldown::GetNodeIconName() const\n{\n\treturn FName(\"BTEditor.Graph.BTNode.Decorator.Cooldown.Icon\");\n}\n\n#endif\t\/\/ WITH_EDITOR\n","avg_line_length":28.875,"max_line_length":121,"alphanum_fraction":0.7997835498,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":8779,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"signverifymessagedialog.h\"\n#include \"ui_signverifymessagedialog.h\"\n\n#include \"addressbookpage.h\"\n#include \"base58.h\"\n#include \"guiutil.h\"\n#include \"init.h\"\n#include \"main.h\"\n#include \"optionsmodel.h\"\n#include \"walletmodel.h\"\n#include \"wallet.h\"\n\n#include <QClipboard>\n\n#include <string>\n#include <vector>\n\nSignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) :\n    QDialog(parent),\n    ui(new Ui::SignVerifyMessageDialog),\n    model(0)\n{\n    ui->setupUi(this);\n\n#if (QT_VERSION >= 0x040700)\n    \/* Do not move this to the XML file, Qt before 4.7 will choke on it *\/\n    ui->addressIn_SM->setPlaceholderText(tr(\"Enter a Xarr address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)\"));\n    ui->signatureOut_SM->setPlaceholderText(tr(\"Click \\\"Sign Message\\\" to generate signature\"));\n\n    ui->addressIn_VM->setPlaceholderText(tr(\"Enter a Xarr address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)\"));\n    ui->signatureIn_VM->setPlaceholderText(tr(\"Enter Xarr signature\"));\n#endif\n\n    GUIUtil::setupAddressWidget(ui->addressIn_SM, this);\n    GUIUtil::setupAddressWidget(ui->addressIn_VM, this);\n\n    ui->addressIn_SM->installEventFilter(this);\n    ui->messageIn_SM->installEventFilter(this);\n    ui->signatureOut_SM->installEventFilter(this);\n    ui->addressIn_VM->installEventFilter(this);\n    ui->messageIn_VM->installEventFilter(this);\n    ui->signatureIn_VM->installEventFilter(this);\n\n    ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont());\n    ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont());\n}\n\nSignVerifyMessageDialog::~SignVerifyMessageDialog()\n{\n    delete ui;\n}\n\nvoid SignVerifyMessageDialog::setModel(WalletModel *model)\n{\n    this->model = model;\n}\n\nvoid SignVerifyMessageDialog::setAddress_SM(const QString &address)\n{\n    ui->addressIn_SM->setText(address);\n    ui->messageIn_SM->setFocus();\n}\n\nvoid SignVerifyMessageDialog::setAddress_VM(const QString &address)\n{\n    ui->addressIn_VM->setText(address);\n    ui->messageIn_VM->setFocus();\n}\n\nvoid SignVerifyMessageDialog::showTab_SM(bool fShow)\n{\n    ui->tabWidget->setCurrentIndex(0);\n\n    if (fShow)\n        this->show();\n}\n\nvoid SignVerifyMessageDialog::showTab_VM(bool fShow)\n{\n    ui->tabWidget->setCurrentIndex(1);\n    if (fShow)\n        this->show();\n}\n\nvoid SignVerifyMessageDialog::on_addressBookButton_SM_clicked()\n{\n    if (model && model->getAddressTableModel())\n    {\n        AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this);\n        dlg.setModel(model->getAddressTableModel());\n        if (dlg.exec())\n        {\n            setAddress_SM(dlg.getReturnValue());\n        }\n    }\n}\n\nvoid SignVerifyMessageDialog::on_pasteButton_SM_clicked()\n{\n    setAddress_SM(QApplication::clipboard()->text());\n}\n\nvoid SignVerifyMessageDialog::on_signMessageButton_SM_clicked()\n{\n    \/* Clear old signature to ensure users don't get confused on error with an old signature displayed *\/\n    ui->signatureOut_SM->clear();\n\n    CBitcoinAddress addr(ui->addressIn_SM->text().toStdString());\n    if (!addr.IsValid())\n    {\n        ui->addressIn_SM->setValid(false);\n        ui->statusLabel_SM->setStyleSheet(\"QLabel { color: red; }\");\n        ui->statusLabel_SM->setText(tr(\"The entered address is invalid.\") + QString(\" \") + tr(\"Please check the address and try again.\"));\n        return;\n    }\n    CKeyID keyID;\n    if (!addr.GetKeyID(keyID))\n    {\n        ui->addressIn_SM->setValid(false);\n        ui->statusLabel_SM->setStyleSheet(\"QLabel { color: red; }\");\n        ui->statusLabel_SM->setText(tr(\"The entered address does not refer to a key.\") + QString(\" \") + tr(\"Please check the address and try again.\"));\n        return;\n    }\n\n    WalletModel::UnlockContext ctx(model->requestUnlock());\n    if (!ctx.isValid())\n    {\n        ui->statusLabel_SM->setStyleSheet(\"QLabel { color: red; }\");\n        ui->statusLabel_SM->setText(tr(\"Wallet unlock was cancelled.\"));\n        return;\n    }\n\n    CKey key;\n    if (!pwalletMain->GetKey(keyID, key))\n    {\n        ui->statusLabel_SM->setStyleSheet(\"QLabel { color: red; }\");\n        ui->statusLabel_SM->setText(tr(\"Private key for the entered address is not available.\"));\n        return;\n    }\n\n    CDataStream ss(SER_GETHASH, 0);\n    ss << strMessageMagic;\n    ss << ui->messageIn_SM->document()->toPlainText().toStdString();\n\n    std::vector<unsigned char> vchSig;\n    if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))\n    {\n        ui->statusLabel_SM->setStyleSheet(\"QLabel { color: red; }\");\n        ui->statusLabel_SM->setText(QString(\"<nobr>\") + tr(\"Message signing failed.\") + QString(\"<\/nobr>\"));\n        return;\n    }\n\n    ui->statusLabel_SM->setStyleSheet(\"QLabel { color: green; }\");\n    ui->statusLabel_SM->setText(QString(\"<nobr>\") + tr(\"Message signed.\") + QString(\"<\/nobr>\"));\n\n    ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));\n}\n\nvoid SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()\n{\n    QApplication::clipboard()->setText(ui->signatureOut_SM->text());\n}\n\nvoid SignVerifyMessageDialog::on_clearButton_SM_clicked()\n{\n    ui->addressIn_SM->clear();\n    ui->messageIn_SM->clear();\n    ui->signatureOut_SM->clear();\n    ui->statusLabel_SM->clear();\n\n    ui->addressIn_SM->setFocus();\n}\n\nvoid SignVerifyMessageDialog::on_addressBookButton_VM_clicked()\n{\n    if (model && model->getAddressTableModel())\n    {\n        AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);\n        dlg.setModel(model->getAddressTableModel());\n        if (dlg.exec())\n        {\n            setAddress_VM(dlg.getReturnValue());\n        }\n    }\n}\n\nvoid SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()\n{\n    CBitcoinAddress addr(ui->addressIn_VM->text().toStdString());\n    if (!addr.IsValid())\n    {\n        ui->addressIn_VM->setValid(false);\n        ui->statusLabel_VM->setStyleSheet(\"QLabel { color: red; }\");\n        ui->statusLabel_VM->setText(tr(\"The entered address is invalid.\") + QString(\" \") + tr(\"Please check the address and try again.\"));\n        return;\n    }\n    CKeyID keyID;\n    if (!addr.GetKeyID(keyID))\n    {\n        ui->addressIn_VM->setValid(false);\n        ui->statusLabel_VM->setStyleSheet(\"QLabel { color: red; }\");\n        ui->statusLabel_VM->setText(tr(\"The entered address does not refer to a key.\") + QString(\" \") + tr(\"Please check the address and try again.\"));\n        return;\n    }\n\n    bool fInvalid = false;\n    std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);\n\n    if (fInvalid)\n    {\n        ui->signatureIn_VM->setValid(false);\n        ui->statusLabel_VM->setStyleSheet(\"QLabel { color: red; }\");\n        ui->statusLabel_VM->setText(tr(\"The signature could not be decoded.\") + QString(\" \") + tr(\"Please check the signature and try again.\"));\n        return;\n    }\n\n    CDataStream ss(SER_GETHASH, 0);\n    ss << strMessageMagic;\n    ss << ui->messageIn_VM->document()->toPlainText().toStdString();\n\n    CPubKey pubkey;\n    if (!pubkey.RecoverCompact(Hash(ss.begin(), ss.end()), vchSig))\n    {\n        ui->signatureIn_VM->setValid(false);\n        ui->statusLabel_VM->setStyleSheet(\"QLabel { color: red; }\");\n        ui->statusLabel_VM->setText(tr(\"The signature did not match the message digest.\") + QString(\" \") + tr(\"Please check the signature and try again.\"));\n        return;\n    }\n\n    if (!(CBitcoinAddress(pubkey.GetID()) == addr))\n    {\n        ui->statusLabel_VM->setStyleSheet(\"QLabel { color: red; }\");\n        ui->statusLabel_VM->setText(QString(\"<nobr>\") + tr(\"Message verification failed.\") + QString(\"<\/nobr>\"));\n        return;\n    }\n\n    ui->statusLabel_VM->setStyleSheet(\"QLabel { color: green; }\");\n    ui->statusLabel_VM->setText(QString(\"<nobr>\") + tr(\"Message verified.\") + QString(\"<\/nobr>\"));\n}\n\nvoid SignVerifyMessageDialog::on_clearButton_VM_clicked()\n{\n    ui->addressIn_VM->clear();\n    ui->signatureIn_VM->clear();\n    ui->messageIn_VM->clear();\n    ui->statusLabel_VM->clear();\n\n    ui->addressIn_VM->setFocus();\n}\n\nbool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event)\n{\n    if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn)\n    {\n        if (ui->tabWidget->currentIndex() == 0)\n        {\n            \/* Clear status message on focus change *\/\n            ui->statusLabel_SM->clear();\n\n            \/* Select generated signature *\/\n            if (object == ui->signatureOut_SM)\n            {\n                ui->signatureOut_SM->selectAll();\n                return true;\n            }\n        }\n        else if (ui->tabWidget->currentIndex() == 1)\n        {\n            \/* Clear status message on focus change *\/\n            ui->statusLabel_VM->clear();\n        }\n    }\n    return QDialog::eventFilter(object, event);\n}\n","avg_line_length":31.9236363636,"max_line_length":156,"alphanum_fraction":0.6548581843,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4446,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":1.0,"content":"\/**\n * Copyright (c) 2017-present, Facebook, Inc. and its affiliates.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include <gtest\/gtest.h>\n\n#include \"logdevice\/common\/ReaderImpl.h\"\n#include \"logdevice\/include\/Client.h\"\n#include \"logdevice\/test\/utils\/AppendThread.h\"\n#include \"logdevice\/test\/utils\/IntegrationTestBase.h\"\n#include \"logdevice\/test\/utils\/IntegrationTestUtils.h\"\n#include \"logdevice\/test\/utils\/ReaderThread.h\"\n\nusing namespace facebook::logdevice;\nusing namespace facebook::logdevice::IntegrationTestUtils;\n\nclass ClientReadStreamFailureDetectorIntegrationTest\n    : public IntegrationTestBase {};\n\nTEST_F(ClientReadStreamFailureDetectorIntegrationTest, Simple) {\n  Configuration::Log log_config;\n  log_config.rangeName = \"my-logs\";\n  log_config.replicationFactor = 3;\n  log_config.extraCopies = 0;\n  log_config.syncedCopies = 0;\n  log_config.maxWritesInFlight = 256;\n  log_config.scdEnabled = true;\n\n  const logid_t LOG_ID(1);\n\n  auto cluster = IntegrationTestUtils::ClusterFactory()\n                     .setLogConfig(log_config)\n                     \/\/ Disable sticky copysets to increase scatter width of the\n                     \/\/ data during the test, which will help guarantee that\n                     \/\/ some records are replicated on the node we will be pick\n                     \/\/ to be slow.\n                     .setParam(\"--write-sticky-copysets\", \"false\")\n                     .setParam(\"--rocksdb-use-copyset-index\", \"false\")\n                     .setParam(\"--sticky-copysets-block-size\", \"1\")\n                     .create(12);\n\n  std::unique_ptr<ClientSettings> client_settings(ClientSettings::create());\n  \/\/ Use high timeouts for SCD as we expect the ClientReadStreamFailureDetector\n  \/\/ utility will be sufficient to maintain read availability.\n  ASSERT_EQ(0, client_settings->set(\"scd-timeout\", \"10min\"));\n  ASSERT_EQ(0, client_settings->set(\"scd-all-send-all-timeout\", \"10min\"));\n  \/\/ Make sure SCD does not do any rewind to ALL_SEND_ALL to try hard to\n  \/\/ be resilient to silent under-replication or copyset\n  \/\/ inconsistencies, which should not happen in this test.\n  ASSERT_EQ(0,\n            client_settings->set(\n                \"read-stream-guaranteed-delivery-efficiency\", \"true\"));\n  \/\/ Disabling copyset reordering makes it easier to debug issues\n  \/\/ related to replication in case this test fails.\n  ASSERT_EQ(0, client_settings->set(\"scd-copyset-reordering-max\", \"none\"));\n  ASSERT_EQ(0, client_settings->set(\"client-read-buffer-size\", \"50\"));\n\n  \/\/ Enabling outlier detection (the feature that makes this test pass!).\n  ASSERT_EQ(0, client_settings->set(\"reader-slow-shards-detection\", \"enabled\"));\n  ASSERT_EQ(0,\n            client_settings->set(\n                \"reader-slow-shards-detection-moving-avg-duration\", \"5min\"));\n  ASSERT_EQ(0,\n            client_settings->set(\n                \"reader-slow-shards-detection-required-margin\", \"5.0\"));\n\n  \/\/ Start a reader and a writer.\n  auto append_thread =\n      std::make_unique<AppendThread>(cluster->createClient(), LOG_ID);\n  append_thread->start();\n  auto reader = std::make_unique<ReaderThread>(\n      cluster->createClient(testTimeout(), std::move(client_settings)), LOG_ID);\n  reader->start();\n\n  \/\/ Sync the reader after 2 seconds worth of data.\n  ld_info(\"Writing\/Reading 2s worth of data...\");\n  std::this_thread::sleep_for(std::chrono::seconds{2});\n  ld_info(\"Syncing reader to tail...\");\n  reader->syncToTail();\n\n  \/\/ Now, inject latency on N4, simulating it's super slow, taking 2min to send\n  \/\/ each batch of records.\n  bool success = cluster->getNode(4).injectShardFault(\n      \"all\", \"all\", \"all\", \"latency\", false, folly::none, 60000);\n  ASSERT_TRUE(success);\n  ld_info(\"Injected latency on N4\");\n\n  \/\/ Continue writing for 2 more seconds.\n  ld_info(\"Writing another 2s worth of data...\");\n  std::this_thread::sleep_for(std::chrono::seconds{2});\n\n  \/\/ Stop the appends. Sync the reader to the tail. We should have read all\n  \/\/ records without any dataloss although some of these records had a copyset\n  \/\/ with N4 as leader recipient.\n  ld_info(\"Stopping writes...\");\n  append_thread->stop();\n  ld_info(\"Syncing reader to tail...\");\n  reader->syncToTail();\n  reader->stop();\n  ASSERT_FALSE(reader->foundDataLoss());\n  ASSERT_EQ(\n      reader->getNumRecordsRead(), append_thread->getNumRecordsAppended());\n}\n","avg_line_length":41.1666666667,"max_line_length":80,"alphanum_fraction":0.6925326136,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":29461,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"#include <tvm\/Space.h>\n#include <tvm\/Variable.h>\n#include <tvm\/constraint\/BasicLinearConstraint.h>\n#include <tvm\/constraint\/abstract\/LinearConstraint.h>\n#include <tvm\/hint\/Substitution.h>\n#include <tvm\/hint\/internal\/DiagonalCalculator.h>\n#include <tvm\/hint\/internal\/GenericCalculator.h>\n#include <tvm\/hint\/internal\/Substitutions.h>\n#include <tvm\/internal\/MatrixProperties.h>\n\n#include <Eigen\/SVD>\n\n\/\/#include <iostream>\n#include <vector>\n\n#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN\n#define DOCTEST_CONFIG_SUPER_FAST_ASSERTS\n#include \"doctest\/doctest.h\"\n\nusing namespace tvm;\nusing namespace tvm::hint;\nusing namespace tvm::hint::internal;\nusing namespace Eigen;\n\nstruct compVec\n{\n  bool operator()(const std::vector<size_t>& u, const std::vector<size_t>& v) const\n  {\n    if (u.size() < v.size())\n      return true;\n    else if (v.size() < u.size())\n      return false;\n    else\n      return std::set<size_t>(u.begin(), u.end()) < std::set<size_t>(v.begin(), v.end());\n  }\n};\n\nbool equal(const std::vector<std::vector<size_t>>& u, const std::vector<std::vector<size_t>>& v)\n{\n  if (u.size() == v.size())\n  {\n    std::set<std::vector<size_t>, compVec> su(u.begin(), u.end());\n    std::set<std::vector<size_t>, compVec> sv(v.begin(), v.end());\n    \/\/using ==, <=, ... between two sets seems to always use ==, <=, ... on the\n    \/\/elements of the set, irrespective of the comparator given to the set. We\n    \/\/thus relies on std::lexicographical_compare with our custom comparator\n    return !std::lexicographical_compare(su.begin(), su.end(), sv.begin(), sv.end(), compVec())\n        && !std::lexicographical_compare(sv.begin(), sv.end(), su.begin(), su.end(), compVec());\n  }\n  else\n    return false;\n}\n\nnamespace tvm\n{\nnamespace hint\n{\nnamespace internal\n{\n\n  class SubstitutionTest\n  {\n  public:\n    static void testSCC()\n    {\n      internal::Substitutions::DependencyGraph g;\n      g.addNode();\n      g.addNode();\n      g.addNode();\n      g.addNode();\n      g.addNode();\n      g.addNode();\n      g.addEdge(0, 3);\n      g.addEdge(3, 1);\n      g.addEdge(1, 0);\n      g.addEdge(1, 2);\n      g.addEdge(1, 4);\n      g.addEdge(2, 5);\n      g.addEdge(5, 2);\n\n      auto r = g.reduce();\n      const auto& e = r.second.edges();\n\n      FAST_CHECK_UNARY(equal(r.first, { { 0,1,3 },{ 4 },{ 2,5 } }));\n      FAST_CHECK_EQ(e.size(), 2);\n      \/\/we have two edges, one from the SCC with size 3 to the SCC with size 1,\n      \/\/one from the SCC with size 3 to the SCC with size 2\n      auto it1 = e.begin();\n      auto it2 = e.begin(); ++it2;\n      FAST_CHECK_EQ(r.first[it1->first].size(), 3);\n      FAST_CHECK_EQ(r.first[it2->first].size(), 3);\n      auto s1 = r.first[it1->second].size();\n      auto s2 = r.first[it2->second].size();\n      FAST_CHECK_UNARY((s1 == 1 && s2 == 2) || (s1 == 2 && s2 == 1));\n    }\n\n    static void testOrder()\n    {\n      internal::Substitutions::DependencyGraph g;\n      g.addNode();\n      g.addNode();\n      g.addNode();\n      g.addNode();\n      g.addNode();\n      g.addNode();\n      g.addNode();\n      g.addNode();\n      g.addNode();\n      g.addNode();\n      g.addEdge(0, 1);\n      g.addEdge(0, 2);\n      g.addEdge(1, 2);\n      g.addEdge(1, 4);\n      g.addEdge(2, 4);\n      g.addEdge(3, 5);\n      g.addEdge(3, 6);\n      g.addEdge(5, 6);\n      g.addEdge(8, 9);\n      g.addEdge(9, 4);\n\n      auto r = g.order();\n\n      std::set<std::vector<size_t>> v = { { 4,2,1,0,9,8 },{ 6,5,3 },{ 7 } };\n      FAST_CHECK_EQ(std::set<std::vector<size_t>>(r.begin(), r.end()), v);\n    }\n  };\n\n\n}\n}\n}\n\nTEST_CASE(\"SCC test\")\n{\n  SubstitutionTest::testSCC();\n}\n\nTEST_CASE(\"Order test\")\n{\n  SubstitutionTest::testOrder();\n}\n\nTEST_CASE(\"GenericCalculator\")\n{\n  VariablePtr x = Space(5).createVariable(\"x\");\n  VariablePtr y = Space(3).createVariable(\"y\");\n  MatrixXd A = MatrixXd::Random(5, 5);\n  MatrixXd B = MatrixXd::Random(5, 3);\n  VectorXd b = VectorXd::Random(5);\n\n  std::shared_ptr<constraint::BasicLinearConstraint> c(new constraint::BasicLinearConstraint({ A,B }, { x,y }, b, constraint::Type::EQUAL));\n\n  auto calc = GenericCalculator().impl({ std::static_pointer_cast<constraint::abstract::LinearConstraint>(c) }, { x }, 5);\n  calc->update();\n\n  MatrixXd AsA(5, 5);\n  MatrixXd StA(0, 5);\n  calc->premultiplyByASharpAndSTranspose(AsA, StA, A, false);\n  FAST_CHECK_UNARY(AsA.isIdentity());\n\n  MatrixXd AsB(5, 3);\n  MatrixXd StB(0, 3);\n  calc->premultiplyByASharpAndSTranspose(AsB, StB, B, true);\n  auto qrA = A.colPivHouseholderQr();\n  FAST_CHECK_UNARY(AsB.isApprox(-MatrixXd(qrA.solve(B))));\n\n  MatrixXd C(3, 5);\n  C << 1, 0, 0, 0, 0,\n       0, 1, 0, 0, 0,\n       0, 0, 0, 0, 0;\n  MatrixXd D = MatrixXd::Random(3, 3);\n  VectorXd d = VectorXd::Random(3);\n\n  std::shared_ptr<constraint::BasicLinearConstraint> c2(new constraint::BasicLinearConstraint({ C,D }, { x,y }, d, constraint::Type::EQUAL));\n\n  auto calc2 = GenericCalculator().impl({ std::static_pointer_cast<constraint::abstract::LinearConstraint>(c2) }, { x }, 2);\n  calc2->update();\n  MatrixXd CsD(5, 3);\n  MatrixXd StD(1, 3);\n  calc2->premultiplyByASharpAndSTranspose(CsD, StD, D, true);\n  FAST_CHECK_UNARY(CsD.topRows(2).isApprox(-D.topRows(2)));\n  FAST_CHECK_UNARY(CsD.bottomRows(3).isZero());\n  FAST_CHECK_UNARY(StD.isApprox(D.row(2)));\n  FAST_CHECK_UNARY(MatrixXd(C*calc2->N()).isZero());\n  FAST_CHECK_EQ(calc2->N().colPivHouseholderQr().rank(),3);\n}\n\nTEST_CASE(\"Diagonal Calculator\")\n{\n  VariablePtr x = Space(7).createVariable(\"x\");\n  VariablePtr y = Space(3).createVariable(\"y\");\n\n  {\n    MatrixXd A = MatrixXd::Identity(7, 7);\n    MatrixXd B = MatrixXd::Random(7, 3);\n    VectorXd b = VectorXd::Random(7);\n\n    std::shared_ptr<constraint::BasicLinearConstraint> c(new constraint::BasicLinearConstraint({ A,B }, { x,y }, b, constraint::Type::EQUAL));\n\n    auto calc = DiagonalCalculator().impl({ std::static_pointer_cast<constraint::abstract::LinearConstraint>(c) }, { x }, 7);\n    calc->update();\n\n    MatrixXd AsA(7, 7);\n    MatrixXd StA(0, 7);\n    calc->premultiplyByASharpAndSTranspose(AsA, StA, A, false);\n    FAST_CHECK_UNARY(AsA.isIdentity());\n\n    MatrixXd AsB(7, 3);\n    MatrixXd StB(0, 3);\n    calc->premultiplyByASharpAndSTranspose(AsB, StB, B, false);\n    FAST_CHECK_UNARY(AsB.isApprox(B));\n\n    FAST_CHECK_EQ(calc->N().rows(), 7);\n    FAST_CHECK_EQ(calc->N().cols(), 0);\n  }\n\n  {\n    MatrixXd A(3, 7);\n    A << 0, 1, 0, 0, 0, 0, 0,\n         0, 0, 0, 1, 0, 0, 0,\n         0, 0, 0, 0, 1, 0, 0;\n    MatrixXd B = MatrixXd::Random(3, 3);\n    VectorXd b = VectorXd::Random(3);\n\n    std::shared_ptr<constraint::BasicLinearConstraint> c(new constraint::BasicLinearConstraint({ A,B }, { x,y }, b, constraint::Type::EQUAL));\n\n    auto calc = DiagonalCalculator({1,3,4}).impl({ std::static_pointer_cast<constraint::abstract::LinearConstraint>(c) }, { x }, 3);\n    calc->update();\n\n    MatrixXd AsA(7, 7);\n    MatrixXd StA(0, 7);\n    calc->premultiplyByASharpAndSTranspose(AsA, StA, A, false);\n    FAST_CHECK_UNARY(AsA.isApprox(A.transpose()* A));\n\n    MatrixXd AsB(7, 3);\n    MatrixXd StB(0, 3);\n    calc->premultiplyByASharpAndSTranspose(AsB, StB, B, false);\n    FAST_CHECK_UNARY(AsB.isApprox(A.transpose()*B));\n\n    MatrixXd N(7, 4);\n    N << 1, 0, 0, 0,\n         0, 0, 0, 0,\n         0, 1, 0, 0,\n         0, 0, 0, 0,\n         0, 0, 0, 0,\n         0, 0, 1, 0,\n         0, 0, 0 ,1;\n    FAST_CHECK_UNARY(N.isApprox(calc->N()));\n  }\n\n  {\n    MatrixXd A(5, 7);\n    A << 0, 0, 0, 0, 0, 0, 0,\n         0, 1, 0, 0, 0, 0, 0,\n         0, 0, 0, 0, 0, 0, 0,\n         0, 0, 0, 1, 0, 0, 0,\n         0, 0, 0, 0, 1, 0, 0;\n    MatrixXd B = MatrixXd::Random(5, 3);\n    VectorXd b = VectorXd::Random(5);\n\n    std::shared_ptr<constraint::BasicLinearConstraint> c(new constraint::BasicLinearConstraint({ A,B }, { x,y }, b, constraint::Type::EQUAL));\n\n    auto calc = DiagonalCalculator({ 1,3,4 }, { 0,2 }).impl({ std::static_pointer_cast<constraint::abstract::LinearConstraint>(c) }, { x }, 3);\n    calc->update();\n\n    MatrixXd AsA(7, 7);\n    MatrixXd StA(2, 7);\n    calc->premultiplyByASharpAndSTranspose(AsA, StA, A, false);\n    FAST_CHECK_UNARY(AsA.isApprox(A.transpose()* A));\n    FAST_CHECK_UNARY(StA.isZero());\n\n    MatrixXd AsB(7, 3);\n    MatrixXd StB(2, 3);\n    calc->premultiplyByASharpAndSTranspose(AsB, StB, B, false);\n    FAST_CHECK_UNARY(AsB.isApprox(A.transpose()*B));\n    FAST_CHECK_UNARY(StB.row(0).isApprox(B.row(0)));\n    FAST_CHECK_UNARY(StB.row(1).isApprox(B.row(2)));\n\n    MatrixXd N(7, 4);\n    N << 1, 0, 0, 0,\n         0, 0, 0, 0,\n         0, 1, 0, 0,\n         0, 0, 0, 0,\n         0, 0, 0, 0,\n         0, 0, 1, 0,\n         0, 0, 0 ,1;\n    FAST_CHECK_UNARY(N.isApprox(calc->N()));\n  }\n  \n}\n\nMatrixXd randM(int m, int n, int r=0)\n{\n  if (r <= 0 || r==std::min(m,n))\n    return MatrixXd::Random(m, n);\n  else\n    return MatrixXd::Random(m, r)*MatrixXd::Random(r, n);\n}\n\n\/** check wether the systems given by cstr and by subs are equivalent.\n  * The system are supposed to be feasible.\n  * From cstr, we deduce a system A [x;y] = b (1)\n  * From subs, we deduce C [y;z] = d and x = E y + F z + g (2)\n  * We check that any solution of (1) is a solution of (2) by writting a\n  * solution of (1) [x;y] = pinv(A)*b + Na u with Na a base of the nullspace of\n  * A and u a vector. For size(u) different value of u, we the rewrite (2) as a\n  * system of z only, and verfy we can find a solution.\n  * To check that any solution of (2) yield a solution of (1), we first solve\n  * C [y;z] = d to get [y;z] = pinv(C)*d + Nc v. Then for size(v) value of v, we\n  * compute x from x = E y + F z + g, and check that [x;y] is a solution of (1).\n  *\/\nvoid checkEquivalence(const std::vector<std::shared_ptr<constraint::BasicLinearConstraint>>& cstr, Substitutions& subs)\n{\n  subs.updateSubstitutions();\n\n  VariableVector x(subs.variables());\n  VariableVector y;\n  VariableVector z(subs.additionalVariables());\n  int m0 = 0;\n  for (auto& c : cstr)\n  {\n    m0 += c->size();\n    for (auto& vi : c->variables())\n    {\n      if (!x.contains(*vi))\n      {\n        y.add(vi);\n      }\n    }\n  }\n\n  int m1 = 0;\n  for (auto& c : subs.additionalConstraints())\n  {\n    m1 += c->size();\n  }\n\n  \/\/ Create A and b such that the system given by cstr is A [x;y] = b\n  MatrixXd A = MatrixXd::Zero(m0, x.totalSize() + y.totalSize());\n  VectorXd b(m0);\n  m0 = 0;\n  for (const auto& c : cstr)\n  {\n    auto mi = c->size();\n    for (const auto& xi : x.variables())\n    {\n      if (c->variables().contains(*xi))\n      {\n        auto rx = xi->getMappingIn(x);\n        A.block(m0, rx.start, mi, rx.dim) = c->jacobian(*xi);\n      }\n    }\n    for (const auto& yi : y.variables())\n    {\n      if (c->variables().contains(*yi))\n      {\n        auto ry = yi->getMappingIn(y);\n        A.block(m0, ry.start + x.totalSize(), mi, ry.dim) = c->jacobian(*yi);\n      }\n    }\n    switch (c->rhs())\n    {\n    case constraint::RHS::ZERO: b.segment(m0, mi).setZero(); break;\n    case constraint::RHS::AS_GIVEN: b.segment(m0, mi) = c->e(); break;\n    case constraint::RHS::OPPOSITE: b.segment(m0, mi) = -c->e(); break;\n    }\n    m0 += mi;\n  }\n\n  \/\/ Create C and d such that the additional constraint of subs write C [y;z] = d\n  MatrixXd C = MatrixXd::Zero(m1, y.totalSize() + z.totalSize());\n  VectorXd d(m1);\n  m1 = 0;\n  for (const auto& c : subs.additionalConstraints())\n  {\n    auto mi = c->size();\n    for (const auto& yi : y.variables())\n    {\n      if (c->variables().contains(*yi))\n      {\n        auto ry = yi->getMappingIn(y);\n        C.block(m1, ry.start, mi, ry.dim) = c->jacobian(*yi);\n      }\n    }\n    for (const auto& zi : z.variables())\n    {\n      if (c->variables().contains(*zi))\n      {\n        auto rz = zi->getMappingIn(z);\n        C.block(m1, rz.start + y.totalSize(), mi, rz.dim) = c->jacobian(*zi);\n      }\n    }\n    switch (c->rhs())\n    {\n    case constraint::RHS::ZERO: d.segment(m1, mi).setZero(); break;\n    case constraint::RHS::AS_GIVEN: d.segment(m1, mi) = c->e(); break;\n    case constraint::RHS::OPPOSITE: d.segment(m1, mi) = -c->e(); break;\n    }\n    m1 += mi;\n  }\n\n  \/\/ Create E, F and g such that the substitutions write x = E y + F z + g\n  MatrixXd E = MatrixXd::Zero(x.totalSize(), y.totalSize());\n  MatrixXd F = MatrixXd::Zero(x.totalSize(), z.totalSize());\n  VectorXd g(x.totalSize());\n  for (size_t i = 0; i < x.variables().size(); ++i)\n  {\n    const auto& f = subs.variableSubstitutions()[i];\n    auto rx = x[static_cast<int>(i)]->getMappingIn(x);\n    for (const auto& yi : y.variables())\n    {\n      if (f->variables().contains(*yi))\n      {\n        auto ry = yi->getMappingIn(y);\n        E.block(rx.start, ry.start, rx.dim, ry.dim) = f->jacobian(*yi);\n      }\n    }\n    for (const auto& zi : z.variables())\n    {\n      if (f->variables().contains(*zi))\n      {\n        auto rz = zi->getMappingIn(z);\n        F.block(rx.start, rz.start, rx.dim, rz.dim) = f->jacobian(*zi);\n      }\n    }\n    g.segment(rx.start, rx.dim) = f->b();\n  }\n\n  \/\/ Solve A [x;y] = b\n  auto svdA = A.jacobiSvd(ComputeFullU | ComputeFullV);\n  auto sol0 = svdA.solve(b);         \/\/least square solution\n  auto r0 = (A*sol0 - b).norm();     \/\/residual\n  MatrixXd Na = svdA.matrixV().rightCols(A.cols() - svdA.rank()); \/\/nullspace of A0\n  FAST_CHECK_LE(r0, 1e-9);\n\n   \/\/ Solve C [y;z] = d\n  VectorXd sol1;\n  MatrixXd Nc;\n  if (C.size()>0)\n  {\n    auto svdC = C.jacobiSvd(ComputeFullU | ComputeFullV);\n    sol1 = svdC.solve(d);         \/\/least square solution\n    Nc = svdC.matrixV().rightCols(C.cols() - svdC.rank()); \/\/nullspace of C\n  }\n  else\n  {\n    sol1 = VectorXd::Zero(C.cols());\n    Nc = MatrixXd::Identity(C.cols(), C.cols());\n  }\n\n  \/\/now check the equivalence:\n  \/\/ 1 - The solutions of Solve C [y;z] = d give solutions of A [x;y] = b\n  for (auto i = 0; i < Nc.cols(); ++i)\n  {\n    \/\/one solution to the additional constraints\n    VectorXd yz = sol1 + Nc*VectorXd::Random(Nc.cols());\n    \/\/split it over y and z\n    y.value(yz.head(y.totalSize()));\n    z.value(yz.tail(z.totalSize()));\n    \/\/compute the corresponding x\n    subs.updateVariableValues();\n    \/\/compute the residual for the current x and y\n    VectorXd xy(x.totalSize() + y.totalSize());\n    xy.head(x.totalSize()) = x.value();\n    xy.tail(y.totalSize()) = y.value();\n    double res = (A*xy - b).norm();\n    FAST_CHECK_LE(res, 1e-9);\n  }\n\n  \/\/ 2 - The solutions of A [x;y] = b are such that there we can find z for which\n  \/\/   C [y;z] = d and x = E y + F z + g\n  MatrixXd M(C.rows() + F.rows(), z.totalSize());\n  M.topRows(C.rows()) = C.rightCols(z.totalSize());\n  M.bottomRows(F.rows()) = F;\n  JacobiSVD<MatrixXd> svdM;\n  if (z.totalSize() > 0)\n  {\n    svdM.compute(M, ComputeThinU | ComputeThinV);\n  }\n  for (auto i = 0; i < Na.cols(); ++i)\n  {\n    \/\/one solution to the original system\n    VectorXd xy = sol0 + Na * VectorXd::Random(Na.cols());\n    \/\/solve C2 z = d - C1 y and F z = x - E y - g\n    VectorXd u(C.rows() + F.rows());\n    u.head(C.rows()) = d - C.leftCols(y.totalSize()) * xy.tail(y.totalSize());\n    u.tail(F.rows()) = xy.head(x.totalSize()) - E * xy.tail(y.totalSize()) - g;\n    double res;\n    if (z.totalSize() > 0)\n    {\n      VectorXd s = svdM.solve(u);\n      res = (M*s - u).norm();\n    }\n    else\n    {\n      res = u.norm();\n    }\n    FAST_CHECK_LE(res, 1e-9);\n  }\n}\n\nTEST_CASE(\"Substitution construction\")\n{\n  using BLC = constraint::BasicLinearConstraint;\n  auto eq = constraint::Type::EQUAL;\n\n  VariablePtr x = Space(5).createVariable(\"x\");\n  {\n    MatrixXd A = randM(5, 5);\n    VectorXd b = VectorXd::Random(5);\n\n    auto c = std::shared_ptr<BLC>(new BLC(A, x, b, eq));\n    Substitution s(c, x);\n    FAST_CHECK_EQ(s.rank(), 5);\n    FAST_CHECK_EQ(typeid(*s.calculator()).hash_code(), typeid(GenericCalculator::Impl).hash_code());\n  }\n\n  {\n    MatrixXd A = MatrixXd::Identity(5, 5);\n    VectorXd b = VectorXd::Random(5);\n\n    auto c = std::shared_ptr<BLC>(new BLC(5, x, eq));\n    c->A(A, { tvm::internal::MatrixProperties::IDENTITY });\n    Substitution s(c, x);\n    FAST_CHECK_EQ(s.rank(), 5);\n    FAST_CHECK_EQ(typeid(*s.calculator()).hash_code(), typeid(DiagonalCalculator::Impl).hash_code());\n  }\n\n  {\n    MatrixXd A = randM(5, 5);\n    VectorXd b = VectorXd::Random(5);\n\n    auto c = std::shared_ptr<BLC>(new BLC(A, x, b, constraint::Type::LOWER_THAN));\n    CHECK_THROWS(Substitution s(c, x));\n\n    VariablePtr y = Space(3).createVariable(\"y\");\n    CHECK_THROWS(Substitution s(c, y));\n\n    auto c2 = std::shared_ptr<BLC>(new BLC(3, y, eq));\n    CHECK_THROWS(Substitution s({ c, c2 }, x));\n\n    auto c3 = std::shared_ptr<BLC>(new BLC(5, y, eq));\n    CHECK_THROWS(Substitution s(c3, y));\n\n  }\n}\n\nTEST_CASE(\"Substitution0\")\n{\n  using BLC = constraint::BasicLinearConstraint;\n  auto eq = constraint::Type::EQUAL;\n\n  {\n    \/\/ solving A x = b using substitutions\n    VariablePtr x = Space(5).createVariable(\"x\");\n    MatrixXd A = randM(5, 5);\n    VectorXd b = VectorXd::Random(5);\n    VectorXd x0 = A.colPivHouseholderQr().solve(b);\n\n    auto c = std::shared_ptr<BLC>(new BLC(A, x, b, eq));\n    Substitution s(c, x);\n    Substitutions subs;\n    subs.add(s);\n    subs.finalize();\n    FAST_CHECK_EQ(subs.variables().size(), 1);\n    FAST_CHECK_EQ(subs.variables().front(), x);\n    FAST_CHECK_EQ(subs.additionalVariables().size(), 0);\n    FAST_CHECK_EQ(subs.additionalConstraints().size(), 0);\n    FAST_CHECK_EQ(subs.variableSubstitutions().size(), 1);\n\n    auto f = subs.variableSubstitutions().front();\n    FAST_CHECK_EQ(f->variables().totalSize(), 0);\n    subs.updateSubstitutions();\n    FAST_CHECK_UNARY(f->b().isApprox(x0));\n    subs.updateVariableValues();\n    FAST_CHECK_UNARY(x->value().isApprox(x0));\n  }\n}\n\nTEST_CASE(\"Substitution1\")\n{\n  int m1 = 3; int n1 = 4; int r1 = 2;\n  int m2 = 3; int n2 = 3; int r2 = 3;\n  int m3 = 3; int n3 = 6; int r3 = 3;\n  int m4 = 4; int n4 = 4; int r4 = 4;\n  int m5 = 7; int n5 = 8; int r5 = 4;\n  int m6 = 3; int n6 = 3; int r6 = 3;\n  int l1 = 3;\n  int l2 = 7;\n  int l3 = 4;\n  int l4 = 4;\n\n  VariablePtr x1 = Space(n1).createVariable(\"x1\");\n  VariablePtr x2 = Space(n2).createVariable(\"x2\");\n  VariablePtr x3 = Space(n3).createVariable(\"x3\");\n  VariablePtr x4 = Space(n4).createVariable(\"x4\");\n  VariablePtr x5 = Space(n5).createVariable(\"x5\");\n  VariablePtr x6 = Space(n6).createVariable(\"x6\");\n  VariablePtr y1 = Space(l1).createVariable(\"y1\");\n  VariablePtr y2 = Space(l2).createVariable(\"y2\");\n  VariablePtr y3 = Space(l3).createVariable(\"y3\");\n  VariablePtr y4 = Space(l4).createVariable(\"y4\");\n\n  VectorXd b1 = VectorXd::Random(m1);\n  VectorXd b2 = VectorXd::Random(m2);\n  VectorXd b3 = VectorXd::Random(m3);\n  VectorXd b4 = VectorXd::Random(m4);\n  VectorXd b5 = VectorXd::Random(m5);\n  VectorXd b6 = VectorXd::Random(m6);\n\n  \/\/                                             | x1 |\n  \/\/                                             | x2 |\n  \/\/ | A11 A12 A13  0   0  A16 B11  0   0   0  | | x3 |   | b1 |\n  \/\/ |  0  A22  0  A24  0   0   0   0   0   0  | | x4 |   | b2 |\n  \/\/ |  0   0  A33  0  A35 A36 B31  0   0   0  | | x5 |   | b3 |\n  \/\/ |  0   0   0  A44 A45  0   0   0   0   0  | | x6 | = | b4 |\n  \/\/ |  0   0   0   0  A55  0   0  B52  0  B54 | | y1 |   | b5 |\n  \/\/ |  0   0   0   0   0  A66  0  B62 B63  0  | | y2 |   | b6 |\n  \/\/                                             | y3 |\n  \/\/                                             | y4 |\n\n  MatrixXd A11 = randM(m1, n1, r1);\n  MatrixXd A12 = randM(m1, n2);\n  MatrixXd A13 = randM(m1, n3);\n  MatrixXd A16 = randM(m1, n6);\n  MatrixXd B11 = randM(m1, l1);\n  MatrixXd A22 = randM(m2, n2, r2);\n  MatrixXd A24 = randM(m2, n4);\n  MatrixXd A33 = randM(m3, n3, r3);\n  MatrixXd A35 = randM(m3, n5);\n  MatrixXd A36 = randM(m3, n6);\n  MatrixXd B31 = randM(m3, l1);\n  MatrixXd A44 = randM(m4, n4, r4);\n  MatrixXd A45 = randM(m4, n5);\n  MatrixXd A55 = randM(m5, n5, r5);\n  MatrixXd B52 = randM(m5, l2);\n  MatrixXd B54 = randM(m5, l4);\n  MatrixXd A66 = randM(m6, n6, r6);\n  MatrixXd B62 = randM(m6, l2);\n  MatrixXd B63 = randM(m6, l3);\n\n  using BLC = constraint::BasicLinearConstraint;\n  auto eq = constraint::Type::EQUAL;\n  auto c1 = std::shared_ptr<BLC>(new BLC({ A11, A12, A13, A16, B11 }, { x1, x2, x3, x6, y1 }, b1, eq));\n  auto c2 = std::shared_ptr<BLC>(new BLC({ A22, A24 }, { x2, x4 }, b2, eq));\n  auto c3 = std::shared_ptr<BLC>(new BLC({ A33, A35, A36, B31 }, { x3, x5, x6, y1 }, b3, eq));\n  auto c4 = std::shared_ptr<BLC>(new BLC({ A44, A45 }, { x4, x5 }, b4, eq));\n  auto c5 = std::shared_ptr<BLC>(new BLC({ A55, B52, B54 }, { x5, y2, y4 }, b5, eq));\n  auto c6 = std::shared_ptr<BLC>(new BLC({ A66, B62, B63 }, { x6, y2, y3}, b6, eq));\n\n  Substitution s1(c1, x1, r1);\n  Substitution s2(c2, x2, r2);\n  Substitution s3(c3, x3, r3);\n  Substitution s4(c4, x4, r4);\n  Substitution s5(c5, x5, r5);\n  Substitution s6(c6, x6, r6);\n\n  Substitutions subs;\n  subs.add(s1);\n  subs.add(s2);\n  subs.add(s3);\n  subs.add(s4);\n  subs.add(s5);\n  subs.add(s6);\n\n  subs.finalize();\n\n  checkEquivalence({ c1,c2,c3,c4,c5,c6 }, subs);\n}\n\nTEST_CASE(\"Substitution2\")\n{\n  int m1 = 3; int n1 = 4;\n  int m2 = 3; int n2 = 3;\n  int m3 = 3; int n3 = 6;\n  int m4 = 5; int n4 = 4;\n  int m5 = 7; int n5 = 5;\n  int m6 = 3; int n6 = 2;\n  int m7 = 6; int n7 = 7;\n  int m8 = 4; int n8 = 4;\n  int m9 = 4; int n9 = 3;\n  int l1 = 3;\n  int l2 = 7;\n\n  VariablePtr x1 = Space(n1).createVariable(\"x1\");\n  VariablePtr x2 = Space(n2).createVariable(\"x2\");\n  VariablePtr x3 = Space(n3).createVariable(\"x3\");\n  VariablePtr x4 = Space(n4).createVariable(\"x4\");\n  VariablePtr x5 = Space(n5).createVariable(\"x5\");\n  VariablePtr x6 = Space(n6).createVariable(\"x6\");\n  VariablePtr x7 = Space(n7).createVariable(\"x7\");\n  VariablePtr x8 = Space(n8).createVariable(\"x8\");\n  VariablePtr x9 = Space(n9).createVariable(\"x9\");\n  VariablePtr y1 = Space(l1).createVariable(\"y1\");\n  VariablePtr y2 = Space(l2).createVariable(\"y2\");\n\n  \/\/                                                 | x1 |\n  \/\/ |  0   0   0  A14  0   0  A17  0  A19 B11  0  | | x2 |   | b1 |\n  \/\/ |  0  A22  0   0   0   0   0   0   0  B21 B22 | | x3 |   | b2 |\n  \/\/ |  0   0   0   0   0  A36  0  A38  0  B31  0  | | x4 |   | b3 |\n  \/\/ |  0   0   0   0  A45  0   0   0   0  B41  0  | | x5 |   | b4 |\n  \/\/ |  0   0   0  A54  0   0  A57  0  A59  0   0  | | x6 | = | b5 |\n  \/\/ |  0   0   0   0   0  A66  0  A68  0  B61 B62 | | x7 |   | b6 |\n  \/\/ |  0   0  A73  0  A75  0   0   0   0   0  B72 | | x8 |   | b7 |\n  \/\/ | A81  0   0   0   0   0  A87  0   0  B81  0  | | x9 |   | b8 |\n  \/\/ |  0   0   0  A94  0   0   0   0   0   0  B92 | | y1 |   | b9 |\n  \/\/                                                 | y2 |\n\n  MatrixXd A14 = randM(m1, n4);\n  MatrixXd A17 = randM(m1, n7);\n  MatrixXd A19 = randM(m1, n9);\n  MatrixXd B11 = randM(m1, l1);\n  MatrixXd A22 = randM(m2, n2);\n  MatrixXd B21 = randM(m2, l1);\n  MatrixXd B22 = randM(m2, l2);\n  MatrixXd A36 = randM(m3, n6);\n  MatrixXd A38 = randM(m3, n8);\n  MatrixXd B31 = randM(m3, l1);\n  MatrixXd A45 = randM(m4, n5);\n  MatrixXd B41 = randM(m4, l1);\n  MatrixXd A54 = randM(m5, n4);\n  MatrixXd A57 = randM(m5, n7);\n  MatrixXd A59 = randM(m5, n9);\n  MatrixXd A66 = randM(m6, n6);\n  MatrixXd A68 = randM(m6, n8);\n  MatrixXd B61 = randM(m6, l1);\n  MatrixXd B62 = randM(m6, l2);\n  MatrixXd A73 = randM(m7, n3);\n  MatrixXd A75 = randM(m7, n5);\n  MatrixXd B72 = randM(m7, l2);\n  MatrixXd A81 = randM(m8, n1);\n  MatrixXd A87 = randM(m8, n7);\n  MatrixXd B81 = randM(m8, l1);\n  MatrixXd A94 = randM(m9, n4);\n  MatrixXd B92 = randM(m9, l2);\n  VectorXd b1 = VectorXd::Random(m1);\n  VectorXd b2 = VectorXd::Random(m2);\n  VectorXd b3 = VectorXd::Random(m3);\n  VectorXd b4 = VectorXd::Random(m4);\n  VectorXd b5 = VectorXd::Random(m5);\n  VectorXd b6 = VectorXd::Random(m6);\n  VectorXd b7 = VectorXd::Random(m7);\n  VectorXd b8 = VectorXd::Random(m8);\n  VectorXd b9 = VectorXd::Random(m9);\n\n  using BLC = constraint::BasicLinearConstraint;\n  auto eq = constraint::Type::EQUAL;\n  auto c1 = std::shared_ptr<BLC>(new BLC({ A14, A17, A19, B11 }, { x4, x7, x9, y1 }, b1, eq));\n  auto c2 = std::shared_ptr<BLC>(new BLC({ A22, B21, B22 }, { x2, y1, y2 }, b2, eq));\n  auto c3 = std::shared_ptr<BLC>(new BLC({ A36, A38, B31 }, { x6, x8, y1 }, b3, eq));\n  auto c4 = std::shared_ptr<BLC>(new BLC({ A45, B41 }, { x5, y1 }, b4, eq));\n  auto c5 = std::shared_ptr<BLC>(new BLC({ A54, A57, A59 }, { x4, x7, x9 }, b5, eq));\n  auto c6 = std::shared_ptr<BLC>(new BLC({ A66, A68, B62, B61 }, { x6, x8, y2, y1 }, b6, eq));\n  auto c7 = std::shared_ptr<BLC>(new BLC({ A73, A75, B72 }, { x3, x5, y2 }, b7, eq));\n  auto c8 = std::shared_ptr<BLC>(new BLC({ A81, A87, B81 }, { x1, x7, y1 }, b8, eq));\n  auto c9 = std::shared_ptr<BLC>(new BLC({ A94, B92 }, { x4, y2 }, b9, eq));\n\n  Substitution s1(c1, x9);\n  Substitution s2(c2, x2);\n  Substitution s3(std::vector<LinearConstraintPtr>{ c3, c6 }, std::vector<VariablePtr>{ x6, x8 });\n  Substitution s4(c4, x5);\n  Substitution s5(c5, x7);\n  \/\/no s6: c3 and c6 are merged\n  Substitution s7(c7, x3);\n  Substitution s8(c8, x1);\n  Substitution s9(c9, x4);\n\n  Substitutions subs;\n  subs.add(s1);\n  subs.add(s2);\n  subs.add(s3);\n  subs.add(s4);\n  subs.add(s5);\n  subs.add(s7);\n  subs.add(s8);\n  subs.add(s9);\n\n  subs.finalize();\n  checkEquivalence({ c1,c2,c3,c4,c5,c6,c7,c8,c9 }, subs);\n\n  }\n\n  \/** Generate a random number r, min <= r < max*\/\n  int randI(int min, int max)\n  {\n    assert(min < max);\n    return (rand() % (max - min)) + min;\n  }\n\n  \/** Return true with a probability p*\/\n  bool randP(double p)\n  {\n    assert(0 <= p && p <= 1);\n    return static_cast<double>(rand()) \/ RAND_MAX < p;\n  }\n\n  \/** Create a random system A [x;y] = b*\/\n  void randomSubstitutions()\n  {\n    using BLC = constraint::BasicLinearConstraint;\n    auto eq = constraint::Type::EQUAL;\n\n    int nxmin = 4;\n    int nxmax = 16;\n    int nymin = 0;\n    int nymax = 9;\n    int nmin = 2;\n    int nmax = 16;\n    double nonFullRankP = 0.33;\n    int nx = randI(nxmin, nxmax); \/\/number of x variables\n    int ny = randI(nymin, nymax); \/\/number of y variables\n    double px = 0.4;              \/\/probability to have a non-zero off-diagonal block in the 'x part' of A\n    double py = 0.3;              \/\/probability to have a non-zero block in the 'y part' of B\n\n    std::vector<VariablePtr> x;\n    std::vector<VariablePtr> y;\n    std::vector<int> m;\n    std::vector<int> n;\n    std::vector<int> r;\n    std::vector<int> l;\n    std::vector<std::shared_ptr<BLC>> cstr;\n\n    bool fullRankSystem = false;\n\n    \/\/ We restart from scratch when we do not get a system that is full rank\n    while (!fullRankSystem)\n    {\n      int ma = 0;\n      int na = 0;\n      x.clear();\n      y.clear();\n      m.clear();\n      n.clear();\n      r.clear();\n      l.clear();\n      cstr.clear();\n      for (int i = 0; i < nx; ++i)\n      {\n        std::stringstream ss;\n        ss << \"x\" << i;\n        int ni = randI(nmin, nmax);\n        int mi = 1 + randI(1, ni);\n        n.push_back(ni);\n        m.push_back(mi);\n        x.push_back(Space(ni).createVariable(ss.str()));\n        if (randP(nonFullRankP))\n        {\n          r.push_back(randI(mi \/ 2, mi + 1));\n        }\n        else\n        {\n          r.push_back(mi);\n        }\n        ma += mi;\n        na += ni;\n      }\n      for (int i = 0; i < ny; ++i)\n      {\n        std::stringstream ss;\n        ss << \"y\" << i;\n        int ni = randI(nmin, nmax);\n        l.push_back(ni);\n        y.push_back(Space(ni).createVariable(ss.str()));\n        na += l.back();\n      }\n\n      for (size_t i = 0; i < static_cast<size_t>(nx); ++i)\n      {\n        std::vector<VariablePtr> v;\n        std::vector<MatrixXd> M;\n        std::vector<MatrixConstRef> Mr;\n        for (size_t j = 0; j < static_cast<size_t>(nx); ++j)\n        {\n          if (i == j)\n          {\n            M.push_back(randM(m[i], n[j], r[i]));\n            v.push_back(x[j]);\n          }\n          else\n          {\n            if (randP(px))\n            {\n              M.push_back(randM(m[i], n[j]));\n              v.push_back(x[j]);\n            }\n          }\n        }\n        for (size_t j = 0; j < static_cast<size_t>(ny); ++j)\n        {\n          if (randP(py))\n          {\n            M.push_back(randM(m[i], l[j]));\n            v.push_back(y[j]);\n          }\n        }\n        for (const auto& Mi : M)\n        {\n          Mr.push_back(Mi);\n        }\n        VectorXd b = VectorXd::Random(m[i]);\n        auto c = std::shared_ptr<BLC>(new BLC(Mr, v, b, eq));\n        cstr.push_back(c);\n      }\n      \/\/check if the system is feasible\n      MatrixXd A = MatrixXd::Zero(ma, na);\n      int ms = 0;\n      for (const auto& c : cstr)\n      {\n        int ns = 0;\n        int mi = c->size();\n        for (const auto& xi : x)\n        {\n          int ni = xi->size();\n          if (c->variables().contains(*xi))\n          {\n            A.block(ms, ns, mi, ni) = c->jacobian(*xi);\n          }\n          ns += ni;\n        }\n        for (const auto& yi : y)\n        {\n          int ni = yi->size();\n          if (c->variables().contains(*yi))\n          {\n            A.block(ms, ns, mi, ni) = c->jacobian(*yi);\n          }\n          ns += ni;\n        }\n        ms += mi;\n      }\n      auto svd = A.jacobiSvd();\n      fullRankSystem = svd.rank() == A.rows();\n    }\n\n    Substitutions subs;\n    for (size_t i = 0; i < cstr.size(); ++i)\n    {\n      Substitution s(cstr[i], x[i], r[i]);\n      subs.add(s);\n    }\n    subs.finalize();\n    checkEquivalence(cstr, subs);\n  }\n\n  TEST_CASE(\"Random substitutions\")\n  {\n    \/\/In some very rare instance, this test can fail because of rank issues\n    \/\/during the qr decomposition of GenericCalculator. This is because of the\n    \/\/heuristic taken to get the rank of a group of constraints. This is not to\n    \/\/be regarded as an issue.\n    for (int i = 0; i < 10; ++i)\n    {\n      randomSubstitutions();\n    }\n  }","avg_line_length":30.8492146597,"max_line_length":143,"alphanum_fraction":0.5670208072,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":16622,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":23.0,"content":"#include <tiramisu\/core.h>\n\n#include <string.h>\n#include \"configure.h\"\n\nusing namespace tiramisu;\n\nint main(int argc, char **argv)\n{\n  \/\/ Set default tiramisu options.\n  global::set_default_tiramisu_options();\n\n  function fused_sparse_resnet_block(\"fused_sparse_resnet_block\");\n  std::string FOUT_BLs = std::to_string(FOUT_BL);\n  std::string FOUT_NB_BLs = std::to_string(FOUT_NB_BL);\n  std::string X_BLs = std::to_string(X_BL);\n  std::string Y_BLs = std::to_string(Y_BL);\n  std::string X_NB_BLs = std::to_string(X_NB_BL);\n  std::string Y_NB_BLs = std::to_string(Y_NB_BL);\n\n  std::string FOUT_BL2s = std::to_string(FOUT_BL2);\n  std::string FOUT_NB_BL2s = std::to_string(FOUT_NB_BL2);\n  std::string X_BL2s = std::to_string(X_BL2);\n  std::string Y_BL2s = std::to_string(Y_BL2);\n  std::string X_NB_BL2s = std::to_string(X_NB_BL2);\n  std::string Y_NB_BL2s = std::to_string(Y_NB_BL2);\n\n  \/\/ Iteration variables\n  var k(\"k\"), fout(\"fout\"), b(\"b\"), fin(\"fin\");\n  var output_x(\"output_x\"), output_y(\"output_y\");\n  var x_b(\"x_b\"), y_b(\"y_b\"), yy(\"yy\"), xx(\"xx\");\n  var fout_b(\"fout_b\"), ffout(\"ffout\");\n  var x(\"x\"), y(\"y\");\n  \/\/ Inputs\n  \/\/ First convolution and bn inputs\n  computation SIZES(\"{SIZES[e]: 0<=e<2}\", expr(), false, p_int32, &fused_sparse_resnet_block);\n  computation c_input(\"[BATCHSIZE,IND_RANGE]->{c_input[b,ind]: 0<=b<BATCHSIZE and 0<=ind<IND_RANGE}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n\n  computation c_filter_values(\"[FNNZ]->{c_filter_values[k]: 0<=k<FNNZ}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n  computation c_filter_idx(\"[FNNZ]->{c_filter_idx[k]: 0<=k<FNNZ}\", expr(), false, p_int32, &fused_sparse_resnet_block);\n  computation c_filter_finptr(\"[filter_finptr_size]->{c_filter_finptr[fin]: 0<=fin<filter_finptr_size}\", expr(), false, p_int32, &fused_sparse_resnet_block);\n\n  computation c_bias(\"[F_Out]->{c_bias[fout]: 0<=fout<F_Out}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n\n  computation c_bn_scale(\"[F_Out]->{c_bn_scale[fout]: 0<=fout<F_Out}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n  computation c_bn_shift(\"[F_Out]->{c_bn_shift[fout]: 0<=fout<F_Out}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n\n  computation c_bn_mean(\"[F_Out]->{c_bn_mean[fout]: 0<=fout<F_Out}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n  computation c_bn_variance(\"[F_Out]->{c_bn_variance[fout]: 0<=fout<F_Out}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n\n  \/\/ Second convolution and bn inputs\n  computation c_input2_view(\"[BATCHSIZE,IND_RANGE2]->{c_input2_view[b,ind]: 0<=b<BATCHSIZE and 0<=ind<IND_RANGE2}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n\n  computation c_filter_values2(\"[FNNZ2]->{c_filter_values2[k]: 0<=k<FNNZ2}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n  computation c_filter_idx2(\"[FNNZ2]->{c_filter_idx2[k]: 0<=k<FNNZ2}\", expr(), false, p_int32, &fused_sparse_resnet_block);\n  computation c_filter_finptr2(\"[filter_finptr_size]->{c_filter_finptr2[fin2]: 0<=fin2<filter_finptr_size}\", expr(), false, p_int32, &fused_sparse_resnet_block);\n\n  computation c_bias2(\"[F_Out]->{c_bias2[fout]: 0<=fout<F_Out}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n\n  computation c_bn2_scale(\"[F_Out]->{c_bn2_scale[fout]: 0<=fout<F_Out}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n  computation c_bn2_shift(\"[F_Out]->{c_bn2_shift[fout]: 0<=fout<F_Out}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n\n  computation c_bn2_mean(\"[F_Out]->{c_bn2_mean[fout]: 0<=fout<F_Out}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n  computation c_bn2_variance(\"[F_Out]->{c_bn2_variance[fout]: 0<=fout<F_Out}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n\n  constant IND_RANGE(\"IND_RANGE\",(N + 2) * (N + 2) * FIn, p_int32, true, NULL, 0, &fused_sparse_resnet_block);\n  constant FNNZ(\"FNNZ\", SIZES(0), p_int32, true, NULL, 0, &fused_sparse_resnet_block);\n  constant IND_RANGE2(\"IND_RANGE2\",(N + 2) * (N + 2) * FOut, p_int32, true, NULL, 0, &fused_sparse_resnet_block);\n  constant FNNZ2(\"FNNZ2\", SIZES(1), p_int32, true, NULL, 0, &fused_sparse_resnet_block);\n\n  constant BATCHSIZE(\"BATCHSIZE\", BATCH_SIZE, p_int32, true, NULL, 0, &fused_sparse_resnet_block);\n  constant F_In(\"F_In\", FIn, p_int32, true, NULL, 0, &fused_sparse_resnet_block);\n  constant height(\"height\", N + 2, p_int32, true, NULL, 0, &fused_sparse_resnet_block);\n  constant width(\"width\", N + 2, p_int32, true, NULL, 0, &fused_sparse_resnet_block);\n\n  constant F_Out(\"F_Out\", FOut, p_int32, true, NULL, 0, &fused_sparse_resnet_block);\n  constant KK(\"KK\", K, p_int32, true, NULL, 0, &fused_sparse_resnet_block);\n\n  constant output_height(\"output_height\", N, p_int32, true, NULL, 0, &fused_sparse_resnet_block);\n  constant output_width(\"output_width\", N, p_int32, true, NULL, 0, &fused_sparse_resnet_block);\n\n  constant filter_finptr_size(\"filter_finptr_size\", expr(FOut + 1), p_int32, true, NULL, 0, &fused_sparse_resnet_block);\n\n  \/\/ First Convolution\n  computation conv_output_init_zero(\"[BATCHSIZE,F_Out,height,width]->{conv_output_init_zero[b,fout,y,x]: 0<=b<BATCHSIZE and 0<=fout<F_Out and 0<=y<height and 0<=x<width}\", cast(p_float32, 0), true, p_float32, &fused_sparse_resnet_block);\n\n  computation init_conv(\"[BATCHSIZE]->{init_conv[b,fout_b,y_b,x_b,ffout,yy,xx]: 0<=b<BATCHSIZE and 0<=fout_b<\"+FOUT_NB_BLs+\" and 0<=ffout<\"+FOUT_BLs+\" and 0<=x_b<\"+X_NB_BLs+\" and 0<=xx<\"+X_BLs+\" and 0<=y_b<\"+Y_NB_BLs+\" and 0<=yy<\"+Y_BLs+\"}\",  c_bias(fout_b * FOUT_BL + ffout), true, p_float32, &fused_sparse_resnet_block);\n\n  computation convolve(\"[BATCHSIZE,k_range0,k_range1]->{convolve[b,fout_b,y_b,x_b,ffout,k,yy,xx]: 0<=b<BATCHSIZE and 0<=fout_b<\"+FOUT_NB_BLs+\" and 0<=ffout<\"+FOUT_BLs+\" and 0<=x_b<\"+X_NB_BLs+\" and 0<=xx<\"+X_BLs+\" and 0<=y_b<\"+Y_NB_BLs+\" and 0<=yy<\"+Y_BLs+\" and k_range0<=k<k_range1}\", expr(), true, p_float32, &fused_sparse_resnet_block);\n\n  computation store_conv_bn_relu(\"[BATCHSIZE]->{store_conv_bn_relu[b,fout_b,y_b,x_b,ffout,yy,xx]: 0<=b<BATCHSIZE and 0<=fout_b<\"+FOUT_NB_BLs+\" and 0<=ffout<\"+FOUT_BLs+\" and 0<=x_b<\"+X_NB_BLs+\" and 0<=xx<\"+X_BLs+\" and 0<=y_b<\"+Y_NB_BLs+\" and 0<=yy<\"+Y_BLs+\"}\",  expr(), true, p_float32, &fused_sparse_resnet_block);\n\n  \/\/ Loop invariants\n  constant filter_k(\"filter_k\", c_filter_idx(k), p_int32, false, &convolve, 5, &fused_sparse_resnet_block);\n\n  constant k_range0(\"k_range0\", c_filter_finptr(fout_b * FOUT_BL + ffout), p_int32, false, &convolve, 4, &fused_sparse_resnet_block);\n  constant k_range1(\"k_range1\", c_filter_finptr(fout_b * FOUT_BL + ffout + 1), p_int32, false, &convolve, 4, &fused_sparse_resnet_block);\n\n  convolve.set_expression(convolve(b, fout_b, y_b, x_b, ffout, k, yy, xx) + c_input(b, (y_b * Y_BL + yy) * (N + 2) + x_b * X_BL + xx) * c_filter_values(k));\n\n  store_conv_bn_relu.set_expression(expr(o_max, 0.f, c_bn_scale(fout_b * FOUT_BL + ffout) * ((convolve(b, fout_b, y_b, x_b, ffout, 0, yy, xx) - c_bn_mean(fout_b * FOUT_BL + ffout))\/ expr(o_sqrt, c_bn_variance(fout_b * FOUT_BL + ffout) + cast(p_float32, EPSILON))) + c_bn_shift(fout_b * FOUT_BL + ffout)));\n\n  \/\/ Second Convolution\n  computation init_conv2(\"[BATCHSIZE]->{init_conv2[b,fout_b,y_b,x_b,ffout,yy,xx]: 0<=b<BATCHSIZE and 0<=fout_b<\"+FOUT_NB_BL2s+\" and 0<=ffout<\"+FOUT_BL2s+\" and 0<=x_b<\"+X_NB_BL2s+\" and 0<=xx<\"+X_BL2s+\" and 0<=y_b<\"+Y_NB_BL2s+\" and 0<=yy<\"+Y_BL2s+\"}\", c_bias2(fout_b * FOUT_BL + ffout), true, p_float32, &fused_sparse_resnet_block);\n  computation store_conv_bn2(\"[BATCHSIZE]->{store_conv_bn2[b,fout_b,y_b,x_b,ffout,yy,xx]: 0<=b<BATCHSIZE and 0<=fout_b<\"+FOUT_NB_BL2s+\" and 0<=ffout<\"+FOUT_BL2s+\" and 0<=x_b<\"+X_NB_BL2s+\" and 0<=xx<\"+X_BL2s+\" and 0<=y_b<\"+Y_NB_BL2s+\" and 0<=yy<\"+Y_BL2s+\"}\", expr(), true, p_float32, &fused_sparse_resnet_block);\n\n  computation convolve2(\"[BATCHSIZE,k2_range0,k2_range1]->{convolve2[b,fout_b,y_b,x_b,ffout,k,yy,xx]: 0<=b<BATCHSIZE and 0<=fout_b<\"+FOUT_NB_BL2s+\" and 0<=ffout<\"+FOUT_BL2s+\" and 0<=x_b<\"+X_NB_BL2s+\" and 0<=xx<\"+X_BL2s+\" and 0<=y_b<\"+Y_NB_BL2s+\" and 0<=yy<\"+Y_BL2s+\" and k2_range0<=k<k2_range1}\", expr(), true, p_float32, &fused_sparse_resnet_block);\n\n  computation conv2_result_view(\"[BATCHSIZE,F_Out,output_height,output_width]->{conv2_result_view[b,fout,y,x]: 0<=b<BATCHSIZE and 0<=fout<F_Out and 0<=y<output_height and 0<=x<output_width}\", expr(), false, p_float32, &fused_sparse_resnet_block);\n  \/\/ Loop invariants\n  constant filter_k2(\"filter_k2\", c_filter_idx2(k), p_int32, false, &convolve2, 5, &fused_sparse_resnet_block);\n\n  constant k2_range0(\"k2_range0\", c_filter_finptr2(fout_b * FOUT_BL2 + ffout), p_int32, false, &convolve2, 4, &fused_sparse_resnet_block);\n  constant k2_range1(\"k2_range1\", c_filter_finptr2(fout_b * FOUT_BL2 + ffout + 1), p_int32, false, &convolve2, 4, &fused_sparse_resnet_block);\n\n  convolve2.set_expression(convolve2(b, fout_b, y_b, x_b, ffout, k, yy, xx) + c_input2_view(b, (y_b * Y_BL2 + yy) * (N + 2) + x_b * X_BL2 + xx) * c_filter_values2(k));\n\n  store_conv_bn2.set_expression((c_bn2_scale(fout_b * FOUT_BL + ffout) * ((convolve2(b, fout_b, y_b, x_b, ffout, 0, yy, xx) - c_bn2_mean(fout_b * FOUT_BL + ffout)) \/ expr(o_sqrt, c_bn2_variance(fout_b * FOUT_BL + ffout) + cast(p_float32, EPSILON)))) + c_bn2_shift(fout_b * FOUT_BL + ffout));\n\n  fused_sparse_resnet_block.set_context_set(\"[k_range0,k_range1,k2_range0,k2_range1]->{: k_range0>0 and k_range1>0 and k_range1>k_range0 and k2_range0>0 and k2_range1>0 and k2_range1>k2_range0}\");\n\n  \/\/ -----------------------------------------------------------------\n  \/\/ Layer II\n  \/\/ -----------------------------------------------------------------\n  \/\/ We need to allocate the temporary register at level ffout to get private array per thread\n  buffer b_workspace(\"b_workspace\", {Y_BL, X_BL}, p_float32, a_temporary, &fused_sparse_resnet_block);\n  computation *alloc = b_workspace.allocate_at(init_conv, ffout);\n\n  k_range0.after_low_level(conv_output_init_zero, computation::root_dimension);\n  k_range1.after_low_level(k_range0, 4);\n  alloc->after_low_level(k_range1, 4);\n  init_conv.after_low_level(*alloc, 4);\n  filter_k.after_low_level(init_conv, 4);\n  convolve.after_low_level(filter_k, 5);\n  store_conv_bn_relu.after_low_level(convolve, 4);\n\n  buffer b_workspace2(\"b_workspace2\", {Y_BL2, X_BL2}, p_float32, a_temporary, &fused_sparse_resnet_block);\n  computation *alloc2 = b_workspace2.allocate_at(init_conv2, ffout);\n\n  k2_range0.after_low_level(store_conv_bn_relu, 0);\n  k2_range1.after_low_level(k2_range0, 4);\n  alloc2->after_low_level(k2_range1, 4);\n  init_conv2.after_low_level(*alloc2, 4);\n  filter_k2.after_low_level(init_conv2, 4);\n  convolve2.after_low_level(filter_k2, 5);\n  store_conv_bn2.after_low_level(convolve2, 4);\n\n  \/\/ Parallelization\n  convolve.parallelize(b);\n  convolve2.parallelize(b);\n\n  \/\/ ---------------------------------------------------------------------------------\n  \/\/ Layer III\n  \/\/ ---------------------------------------------------------------------------------\n  \/\/ Input\n  buffer b_SIZES(\"b_SIZES\", {expr(2)}, p_int32, a_input, &fused_sparse_resnet_block);\n\n  buffer b_input(\"b_input\", {BATCHSIZE, expr(F_In)*expr(height)*expr(width)}, p_float32, a_input, &fused_sparse_resnet_block);\n\n  \/\/ First convolution Weights in CSR format\n  buffer b_filter_values(\"b_filter_values\", {expr(FNNZ)}, p_float32, a_input, &fused_sparse_resnet_block);\n  buffer b_filter_idx(\"b_filter_idx\", {FNNZ}, p_int32, a_input, &fused_sparse_resnet_block);\n  buffer b_filter_finptr(\"b_filter_finptr\", {expr(filter_finptr_size)}, p_int32, a_input, &fused_sparse_resnet_block);\n\n  buffer b_bias(\"b_bias\", {F_Out}, p_float32, a_input, &fused_sparse_resnet_block);\n\n  buffer b_bn_scale(\"b_bn_scale\", {F_Out}, p_float32, a_input, &fused_sparse_resnet_block);\n  buffer b_bn_shift(\"b_bn_shift\", {F_Out}, p_float32, a_input, &fused_sparse_resnet_block);\n\n  buffer b_bn_mean(\"b_bn_mean\", {F_Out}, p_float32, a_input, &fused_sparse_resnet_block);\n  buffer b_bn_variance(\"b_bn_variance\", {F_Out}, p_float32, a_input, &fused_sparse_resnet_block);\n\n  buffer b_conv1_output(\"b_conv1_output\", {BATCH_SIZE, FOut, N + 2, N + 2}, p_float32, a_input, &fused_sparse_resnet_block);\n\n  \/\/ Second convolution Weights in CSR format\n  buffer b_filter_values2(\"b_filter_values2\", {FNNZ2}, p_float32, a_input, &fused_sparse_resnet_block);\n  buffer b_filter_idx2(\"b_filter_idx2\", {FNNZ2}, p_int32, a_input, &fused_sparse_resnet_block);\n  buffer b_filter_finptr2(\"b_filter_finptr2\", {expr(filter_finptr_size)}, p_int32, a_input, &fused_sparse_resnet_block);\n\n  buffer b_bias2(\"b_bias2\", {F_Out}, p_float32, a_input, &fused_sparse_resnet_block);\n\n  buffer b_bn2_scale(\"b_bn2_scale\", {F_Out}, p_float32, a_input, &fused_sparse_resnet_block);\n  buffer b_bn2_shift(\"b_bn2_shift\", {F_Out}, p_float32, a_input, &fused_sparse_resnet_block);\n\n  buffer b_bn2_mean(\"b_bn2_mean\", {F_Out}, p_float32, a_input, &fused_sparse_resnet_block);\n  buffer b_bn2_variance(\"b_bn2_variance\", {F_Out}, p_float32, a_input, &fused_sparse_resnet_block);\n\n  \/\/ Output\n  buffer b_result(\"b_result\", {BATCHSIZE, F_Out, N, N}, p_float32, a_output, &fused_sparse_resnet_block);\n\n  \/\/ Mapping computations\n  SIZES.set_access(\"{SIZES[e]->b_SIZES[e]}\");\n  c_input.set_access(\"[filter_k]->{c_input[b,ind]->b_input[b,ind + filter_k]}\");\n\n  c_filter_values.set_access(\"{c_filter_values[k]->b_filter_values[k]}\");\n  c_filter_idx.set_access(\"{c_filter_idx[k]->b_filter_idx[k]}\");\n  c_filter_finptr.set_access(\"{c_filter_finptr[fin]->b_filter_finptr[fin]}\");\n\n  c_bias.set_access(\"{c_bias[fout]->b_bias[fout]}\");\n\n  \/\/ BN1\n  c_bn_scale.set_access(\"{c_bn_scale[fout]->b_bn_scale[fout]}\");\n  c_bn_shift.set_access(\"{c_bn_shift[fout]->b_bn_shift[fout]}\");\n\n  c_bn_mean.set_access(\"{c_bn_mean[fout]->b_bn_mean[fout]}\");\n  c_bn_variance.set_access(\"{c_bn_variance[fout]->b_bn_variance[fout]}\");\n\n  conv_output_init_zero.set_access(\"{conv_output_init_zero[b,fout,y,x]->b_conv1_output[b,fout,y,x]}\");\n\n  init_conv.set_access(\"{init_conv[b,fout_b,y_b,x_b,ffout,yy,xx]->b_workspace[yy,xx]}\");\n\n  store_conv_bn_relu.set_access(\"{store_conv_bn_relu[b,fout_b,y_b,x_b,ffout,yy,xx]->b_conv1_output[b,fout_b * \"+FOUT_BLs+\"+ffout,y_b * \"+Y_BLs+\"+yy + 1,x_b * \"+X_BLs+\" + xx + 1]}\");\n\n  convolve.set_access(\"{convolve[b,fout_b,y_b,x_b,ffout,k,yy,xx]->b_workspace[yy,xx]}\");\n\n  \/\/View for next convolution input\n  c_input2_view.set_access(\"[filter_k2]->{c_input2_view[b,ind]->b_conv1_output[b,0,0,ind + filter_k2]}\");\n\n  \/\/ Second convolution\n  c_filter_values2.set_access(\"{c_filter_values2[k]->b_filter_values2[k]}\");\n  c_filter_idx2.set_access(\"{c_filter_idx2[k]->b_filter_idx2[k]}\");\n  c_filter_finptr2.set_access(\"{c_filter_finptr2[fin]->b_filter_finptr2[fin]}\");\n\n  c_bias2.set_access(\"{c_bias2[fout]->b_bias2[fout]}\");\n\n  \/\/BN2\n  c_bn2_scale.set_access(\"{c_bn2_scale[fout]->b_bn2_scale[fout]}\");\n  c_bn2_shift.set_access(\"{c_bn2_shift[fout]->b_bn2_shift[fout]}\");\n\n  c_bn2_mean.set_access(\"{c_bn2_mean[fout]->b_bn2_mean[fout]}\");\n  c_bn2_variance.set_access(\"{c_bn2_variance[fout]->b_bn2_variance[fout]}\");\n\n  init_conv2.set_access(\"{init_conv2[b,fout_b,y_b,x_b,ffout,yy,xx]->b_workspace2[yy,xx]}\");\n\n  store_conv_bn2.set_access(\"{store_conv_bn2[b,fout_b,y_b,x_b,ffout,yy,xx]->b_result[b,fout_b * \"+FOUT_BL2s+\"+ffout,y_b * \"+Y_BL2s+\"+yy,x_b * \"+X_BL2s+\" + xx]}\");\n\n  convolve2.set_access(\"{convolve2[b,fout_b,y_b,x_b,ffout,k,yy,xx]->b_workspace2[yy,xx]}\");\n\n  \/\/ ------------------------------------------------------------------\n  \/\/ Generate code &b_idx, &b_finptr,\n  \/\/ ------------------------------------------------------------------\n  fused_sparse_resnet_block.set_arguments({&b_SIZES,\n                        &b_input,\n                              &b_filter_values,\n                              &b_filter_idx,\n                              &b_filter_finptr,\n                              &b_bias,\n                              &b_bn_scale,\n                              &b_bn_shift,\n                              &b_bn_mean,\n                              &b_bn_variance,\n                        &b_conv1_output,\n                              &b_filter_values2,\n                              &b_filter_idx2,\n                              &b_filter_finptr2,\n                              &b_bias2,\n                              &b_bn2_scale,\n                              &b_bn2_shift,\n                              &b_bn2_mean,\n                              &b_bn2_variance,\n                        &b_result});\n  fused_sparse_resnet_block.gen_time_space_domain();\n  fused_sparse_resnet_block.gen_isl_ast();\n  fused_sparse_resnet_block.gen_halide_stmt();\n  fused_sparse_resnet_block.gen_halide_obj(\"generated_fused_sparse_resnet_block.o\");\n\n  return 0;\n}\n","avg_line_length":61.7918215613,"max_line_length":350,"alphanum_fraction":0.6930573938,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1854,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include \"taichi\/backends\/metal\/aot_module_builder_impl.h\"\n\n#include <fstream>\n\n#include \"taichi\/backends\/metal\/codegen_metal.h\"\n\n#if defined(__linux__) && defined(__GNUC__) && (__GNUC__ < 8)\n\/\/ https:\/\/stackoverflow.com\/a\/45867491\n#include <experimental\/filesystem>\nnamespace fs = ::std::experimental::filesystem;\n#else\n#include <filesystem>\nnamespace fs = ::std::filesystem;\n#endif\n\nnamespace taichi {\nnamespace lang {\nnamespace metal {\n\nAotModuleBuilderImpl::AotModuleBuilderImpl(\n    const CompiledStructs *compiled_structs,\n    const BufferMetaData &buffer_meta_data)\n    : compiled_structs_(compiled_structs), buffer_meta_data_(buffer_meta_data) {\n  ti_aot_data_.metadata = buffer_meta_data;\n}\n\nvoid AotModuleBuilderImpl::dump(const std::string &output_dir,\n                                const std::string &filename) const {\n  const fs::path dir{output_dir};\n  const fs::path bin_path = dir \/ fmt::format(\"{}_metadata.tcb\", filename);\n  write_to_binary_file(ti_aot_data_, bin_path.string());\n  \/\/ The txt file is mostly for debugging purpose.\n  const fs::path txt_path = dir \/ fmt::format(\"{}_metadata.txt\", filename);\n  TextSerializer ts;\n  ts(\"taichi file data\", ti_aot_data_);\n  ts.write_to_file(txt_path.string());\n\n  for (const auto &k : ti_aot_data_.kernels) {\n    const fs::path mtl_path =\n        dir \/ fmt::format(\"{}_{}.metal\", filename, k.kernel_name);\n    std::ofstream fs{mtl_path.string()};\n    fs << k.source_code;\n    fs.close();\n  }\n}\n\nvoid AotModuleBuilderImpl::add_per_backend(const std::string &identifier,\n                                           Kernel *kernel) {\n  auto compiled =\n      run_codegen(compiled_structs_, kernel, &strtab_, \/*offloaded=*\/nullptr);\n  compiled.kernel_name = identifier;\n  ti_aot_data_.kernels.push_back(std::move(compiled));\n}\n\n}  \/\/ namespace metal\n}  \/\/ namespace lang\n}  \/\/ namespace taichi\n","avg_line_length":31.9655172414,"max_line_length":80,"alphanum_fraction":0.7022653722,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":23985,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":17.0,"content":"\/*\r\n   Copyright 2012 University of Washington\r\n\r\n   Licensed under the Apache License, Version 2.0 (the \"License\");\r\n   you may not use this file except in compliance with the License.\r\n   You may obtain a copy of the License at\r\n\r\n   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\n   Unless required by applicable law or agreed to in writing, software\r\n   distributed under the License is distributed on an \"AS IS\" BASIS,\r\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n   See the License for the specific language governing permissions and\r\n   limitations under the License.\r\n*\/\r\n\r\n#include \"Common.h\"\r\n#include \"CometDataInternal.h\"\r\n#include \"CometMassSpecUtils.h\"\r\n#include \"CometWriteTxt.h\"\r\n\r\n\r\nCometWriteTxt::CometWriteTxt()\r\n{\r\n}\r\n\r\n\r\nCometWriteTxt::~CometWriteTxt()\r\n{\r\n}\r\n\r\n\r\nvoid CometWriteTxt::WriteTxt(FILE *fpout,\r\n                             FILE *fpoutd,\r\n                             FILE *fpdb)\r\n{\r\n   int i;\r\n\r\n   \/\/ Print out the separate decoy hits.\r\n   if (g_staticParams.options.iDecoySearch == 2)\r\n   {\r\n      for (i=0; i<(int)g_pvQuery.size(); i++)\r\n         PrintResults(i, 1, fpout, fpdb);\r\n      for (i=0; i<(int)g_pvQuery.size(); i++)\r\n         PrintResults(i, 2, fpoutd, fpdb);\r\n   }\r\n   else\r\n   {\r\n      for (i=0; i<(int)g_pvQuery.size(); i++)\r\n         PrintResults(i, 0, fpout, fpdb);\r\n   }\r\n}\r\n\r\n\r\nvoid CometWriteTxt::PrintTxtHeader(FILE *fpout)\r\n{\r\n#ifdef CRUX\r\n   fprintf(fpout, \"scan\\t\");\r\n   fprintf(fpout, \"charge\\t\");\r\n   fprintf(fpout, \"spectrum precursor m\/z\\t\");\r\n   fprintf(fpout, \"spectrum neutral mass\\t\");\r\n   fprintf(fpout, \"peptide mass\\t\");\r\n   fprintf(fpout, \"delta_cn\\t\");\r\n   fprintf(fpout, \"sp score\\t\");\r\n   fprintf(fpout, \"sp rank\\t\");\r\n   fprintf(fpout, \"xcorr score\\t\");\r\n   fprintf(fpout, \"xcorr rank\\t\");\r\n   fprintf(fpout, \"b\/y ions matched\\t\");\r\n   fprintf(fpout, \"b\/y ions total\\t\");\r\n   fprintf(fpout, \"total matches\/spectrum\\t\");\r\n   fprintf(fpout, \"sequence\\t\");\r\n   fprintf(fpout, \"modified sequence\\t\");\r\n   fprintf(fpout, \"modifications\\t\");\r\n   fprintf(fpout, \"protein id\\t\");\r\n   fprintf(fpout, \"flanking aa\\t\");\r\n   fprintf(fpout, \"e-value\\n\");\r\n#else\r\n   fprintf(fpout, \"CometVersion %s\\t\", g_sCometVersion.c_str());\r\n   fprintf(fpout, \"%s\\t\", g_staticParams.inputFile.szBaseName);\r\n   fprintf(fpout, \"%s\\t\", g_staticParams.szDate);\r\n   fprintf(fpout, \"%s\\n\", g_staticParams.databaseInfo.szDatabase);\r\n\r\n   fprintf(fpout, \"scan\\t\");\r\n   fprintf(fpout, \"num\\t\");\r\n   fprintf(fpout, \"charge\\t\");\r\n   fprintf(fpout, \"exp_neutral_mass\\t\");\r\n   fprintf(fpout, \"calc_neutral_mass\\t\");\r\n   fprintf(fpout, \"e-value\\t\");\r\n   fprintf(fpout, \"xcorr\\t\");\r\n   fprintf(fpout, \"delta_cn\\t\");\r\n   fprintf(fpout, \"sp_score\\t\");\r\n   fprintf(fpout, \"ions_matched\\t\");\r\n   fprintf(fpout, \"ions_total\\t\");\r\n   fprintf(fpout, \"plain_peptide\\t\");\r\n   fprintf(fpout, \"modified_peptide\\t\");\r\n   if (g_staticParams.peffInfo.iPeffSearch)\r\n      fprintf(fpout, \"peff_modified_peptide\\t\");\r\n   fprintf(fpout, \"prev_aa\\t\");\r\n   fprintf(fpout, \"next_aa\\t\");\r\n   fprintf(fpout, \"protein\\t\");\r\n   fprintf(fpout, \"protein_count\\t\");\r\n   fprintf(fpout, \"modifications\\t\");\r\n   fprintf(fpout, \"retention_time_sec\\t\");\r\n   fprintf(fpout, \"sp_rank\\n\");\r\n\r\n#endif\r\n}\r\n\r\n\r\nvoid CometWriteTxt::PrintResults(int iWhichQuery,\r\n                                 int iPrintTargetDecoy,\r\n                                 FILE *fpout,\r\n                                 FILE *fpdb)  \/\/fpdb is file pointer for either FASTA or .idx file\r\n{\r\n#ifdef CRUX\r\n   if ((iPrintTargetDecoy != 2 && g_pvQuery.at(iWhichQuery)->_pResults[0].fXcorr > XCORR_CUTOFF)\r\n         || (iPrintTargetDecoy == 2 && g_pvQuery.at(iWhichQuery)->_pDecoys[0].fXcorr > XCORR_CUTOFF))\r\n   {\r\n      Query* pQuery = g_pvQuery.at(iWhichQuery);\r\n\r\n      int charge = pQuery->_spectrumInfoInternal.iChargeState;\r\n      double spectrum_neutral_mass = pQuery->_pepMassInfo.dExpPepMass - PROTON_MASS;\r\n      double spectrum_mz = (spectrum_neutral_mass + charge*PROTON_MASS) \/ (double)charge;\r\n\r\n      Results *pOutput;\r\n      int iNumPrintLines;\r\n      unsigned long iNumMatches;\r\n\r\n      if (iPrintTargetDecoy == 2)  \/\/ decoys\r\n      {\r\n         pOutput = pQuery->_pDecoys;\r\n         iNumPrintLines = pQuery->iDecoyMatchPeptideCount;\r\n         iNumMatches =  pQuery->_uliNumMatchedDecoyPeptides;\r\n      }\r\n      else  \/\/ combined or separate targets\r\n      {\r\n         pOutput = pQuery->_pResults;\r\n         iNumPrintLines = pQuery->iMatchPeptideCount;\r\n         iNumMatches =  pQuery->_uliNumMatchedPeptides;\r\n      }\r\n\r\n      if (iNumPrintLines > g_staticParams.options.iNumPeptideOutputLines)\r\n         iNumPrintLines = g_staticParams.options.iNumPeptideOutputLines;\r\n\r\n      for (int iWhichResult=0; iWhichResult<iNumPrintLines; iWhichResult++)\r\n      {\r\n         if (pOutput[iWhichResult].fXcorr <= XCORR_CUTOFF)\r\n            continue;\r\n\r\n         double dDeltaCn;\r\n\r\n         dDeltaCn = 1.0;\r\n\r\n         if (pOutput[iWhichResult].fXcorr > 0.0\r\n               && iWhichResult+1 < g_staticParams.options.iNumStored\r\n               && pOutput[iWhichResult+1].fXcorr >= 0.0)\r\n         {\r\n            dDeltaCn = 1.0 - pOutput[iWhichResult+1].fXcorr\/pOutput[0].fXcorr;\r\n         }\r\n\r\n         fprintf(fpout, \"%d\\t\", pQuery->_spectrumInfoInternal.iScanNumber);\r\n         fprintf(fpout, \"%d\\t\",  pQuery->_spectrumInfoInternal.iChargeState);\r\n         fprintf(fpout, \"%0.6f\\t\",  spectrum_mz);\r\n         fprintf(fpout, \"%0.6f\\t\", spectrum_neutral_mass);\r\n         fprintf(fpout, \"%0.6f\\t\", pOutput[iWhichResult].dPepMass - PROTON_MASS);\r\n         fprintf(fpout, \"%0.4f\\t\", dDeltaCn);\r\n         fprintf(fpout, \"%0.4f\\t\", pOutput[iWhichResult].fScoreSp);\r\n         fprintf(fpout, \"%d\\t\", pOutput[iWhichResult].iRankSp);\r\n         fprintf(fpout, \"%0.4f\\t\", pOutput[iWhichResult].fXcorr);\r\n         fprintf(fpout, \"%d\\t\", iWhichResult + 1);                 \/\/ assuming want index starting at 1\r\n         fprintf(fpout, \"%d\\t\", pOutput[iWhichResult].iMatchedIons);\r\n         fprintf(fpout, \"%d\\t\", pOutput[iWhichResult].iTotalIons);\r\n         fprintf(fpout, \"%lu\\t\", iNumMatches);\r\n\r\n         \/\/ plain peptide\r\n         fprintf(fpout, \"%s\\t\", pOutput[iWhichResult].szPeptide);\r\n\r\n         \/\/ modified peptide\r\n         fprintf(fpout, \"%c.\", pOutput[iWhichResult].szPrevNextAA[0]);\r\n\r\n         bool bNterm = false;\r\n         bool bCterm = false;\r\n         double dNterm = 0.0;\r\n         double dCterm = 0.0;\r\n\r\n         \/\/ See if n-term variable mod needs to be reported\r\n         if (pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide] > 0)\r\n         {\r\n            bNterm = true;\r\n            dNterm = g_staticParams.variableModParameters.varModList[(int)pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide]-1].dVarModMass;\r\n         }\r\n\r\n         \/\/ See if c-term variable mod needs to be reported\r\n         if (pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide+1] > 0)\r\n         {\r\n            bCterm = true;\r\n            dCterm = g_staticParams.variableModParameters.varModList[(int)pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide+1]-1].dVarModMass;\r\n         }\r\n\r\n         \/\/ generate modified_peptide string\r\n         if (bNterm)\r\n            fprintf(fpout, \"n[%0.4f]\", dNterm);\r\n         for (int i=0; i<pOutput[iWhichResult].iLenPeptide; i++)\r\n         {\r\n            fprintf(fpout, \"%c\", pOutput[iWhichResult].szPeptide[i]);\r\n\r\n            if (pOutput[iWhichResult].piVarModSites[i] != 0)\r\n               fprintf(fpout, \"[%0.4f]\", pOutput[iWhichResult].pdVarModSites[i]);\r\n         }\r\n         if (bCterm)\r\n            fprintf(fpout, \"c[%0.4f]\", dCterm);\r\n\r\n         fprintf(fpout, \".%c\\t\", pOutput[iWhichResult].szPrevNextAA[1]);\r\n\r\n         \/\/ prints modification encoding\r\n         PrintModifications(fpout, pOutput, iWhichResult);\r\n\r\n         \/\/ print protein list\r\n         PrintProteins(fpout, fpdb, iWhichQuery, iWhichResult, iPrintTargetDecoy);\r\n\r\n         \/\/ Cleavage type\r\n         fprintf(fpout, \"\\t%c%c\\t\", pOutput[iWhichResult].szPrevNextAA[0], pOutput[iWhichResult].szPrevNextAA[1]);\r\n\r\n         \/\/ e-value\r\n         fprintf(fpout, \"%0.2E\\n\", pOutput[iWhichResult].dExpect);\r\n      }\r\n   }\r\n\r\n#else\r\n   if ((iPrintTargetDecoy != 2 && g_pvQuery.at(iWhichQuery)->_pResults[0].fXcorr > XCORR_CUTOFF)\r\n         || (iPrintTargetDecoy == 2 && g_pvQuery.at(iWhichQuery)->_pDecoys[0].fXcorr > XCORR_CUTOFF))\r\n   {\r\n      Query* pQuery = g_pvQuery.at(iWhichQuery);\r\n\r\n      Results *pOutput;\r\n      int iNumPrintLines;\r\n\r\n      if (iPrintTargetDecoy == 2)  \/\/ decoys\r\n      {\r\n         pOutput = pQuery->_pDecoys;\r\n         iNumPrintLines = pQuery->iDecoyMatchPeptideCount;\r\n      }\r\n      else  \/\/ combined or separate targets\r\n      {\r\n         pOutput = pQuery->_pResults;\r\n         iNumPrintLines = pQuery->iMatchPeptideCount;\r\n      }\r\n\r\n      if (iNumPrintLines > g_staticParams.options.iNumPeptideOutputLines)\r\n         iNumPrintLines = g_staticParams.options.iNumPeptideOutputLines;\r\n\r\n      int iMinLength = 999;\r\n      for (int i=0; i<iNumPrintLines; i++)\r\n      {\r\n         int iLen = (int)strlen(pOutput[i].szPeptide);\r\n         if (iLen == 0)\r\n            break;\r\n         if (iLen < iMinLength)\r\n            iMinLength = iLen;\r\n      }\r\n\r\n      int iRankXcorr = 1;\r\n      int iLineCount = 1;\r\n\r\n      for (int iWhichResult=0; iWhichResult<iNumPrintLines; iWhichResult++)\r\n      {\r\n         int j;\r\n         double dDeltaCn = 1.0;\r\n\r\n         if (pOutput[iWhichResult].fXcorr <= XCORR_CUTOFF)\r\n            continue;\r\n\r\n         \/\/ go one past iNumPrintLines to calculate deltaCn value\r\n         for (j=iWhichResult+1; j<iNumPrintLines+1; j++)\r\n         {\r\n            if (j<g_staticParams.options.iNumStored)\r\n            {\r\n               \/\/ very poor way of calculating peptide similarity but it's what we have for now\r\n               int iDiffCt = 0;\r\n\r\n               if (!g_staticParams.options.bExplicitDeltaCn)\r\n               {\r\n                  for (int k=0; k<iMinLength; k++)\r\n                  {\r\n                     \/\/ I-L and Q-K are same for purposes here\r\n                     if (pOutput[iWhichResult].szPeptide[k] != pOutput[j].szPeptide[k])\r\n                     {\r\n                        if (!((pOutput[0].szPeptide[k] == 'K' || pOutput[0].szPeptide[k] == 'Q')\r\n                                 && (pOutput[j].szPeptide[k] == 'K' || pOutput[j].szPeptide[k] == 'Q'))\r\n                              && !((pOutput[0].szPeptide[k] == 'I' || pOutput[0].szPeptide[k] == 'L')\r\n                                 && (pOutput[j].szPeptide[k] == 'I' || pOutput[j].szPeptide[k] == 'L')))\r\n                        {\r\n                           iDiffCt++;\r\n                        }\r\n                     }\r\n                  }\r\n               }\r\n\r\n               \/\/ calculate deltaCn only if sequences are less than 0.75 similar\r\n               if (g_staticParams.options.bExplicitDeltaCn || ((double) (iMinLength - iDiffCt)\/iMinLength) < 0.75)\r\n               {\r\n                  if (pOutput[iWhichResult].fXcorr > 0.0 && pOutput[j].fXcorr >= 0.0)\r\n                     dDeltaCn = 1.0 - pOutput[j].fXcorr\/pOutput[iWhichResult].fXcorr;\r\n                  else if (pOutput[iWhichResult].fXcorr > 0.0 && pOutput[j].fXcorr < 0.0)\r\n                     dDeltaCn = 1.0;\r\n                  else\r\n                     dDeltaCn = 0.0;\r\n\r\n                  break;\r\n               }\r\n            }\r\n         }\r\n\r\n         if (iWhichResult > 0 && !isEqual(pOutput[iWhichResult].fXcorr, pOutput[iWhichResult-1].fXcorr))\r\n            iRankXcorr = iLineCount;\r\n         iLineCount++;\r\n\r\n         fprintf(fpout, \"%d\\t\", pQuery->_spectrumInfoInternal.iScanNumber);\r\n\r\n         \/\/ Print spectrum_query element.\r\n         if (g_staticParams.options.bMango)   \/\/ Mango specific\r\n         {\r\n            char *pStr;\r\n\r\n            \/\/ look for either \\ or \/ separator so valid for Windows or Linux\r\n            if ((pStr = strrchr(g_staticParams.inputFile.szBaseName, '\\\\')) == NULL\r\n               && (pStr = strrchr(g_staticParams.inputFile.szBaseName, '\/')) == NULL)\r\n            {\r\n               pStr = g_staticParams.inputFile.szBaseName;\r\n\r\n            }\r\n            else\r\n               pStr++;  \/\/ skip separation character\r\n\r\n            fprintf(fpout, \"%s_%s.%05d.%05d.%d\\t\",\r\n                  pStr,\r\n                  pQuery->_spectrumInfoInternal.szMango,\r\n                  pQuery->_spectrumInfoInternal.iScanNumber,\r\n                  pQuery->_spectrumInfoInternal.iScanNumber,\r\n                  pQuery->_spectrumInfoInternal.iChargeState);\r\n         }\r\n\r\n         fprintf(fpout, \"%d\\t\", iRankXcorr);\r\n         fprintf(fpout, \"%d\\t\", pQuery->_spectrumInfoInternal.iChargeState);\r\n         fprintf(fpout, \"%0.6f\\t\", pQuery->_pepMassInfo.dExpPepMass - PROTON_MASS);\r\n         fprintf(fpout, \"%0.6f\\t\", pOutput[iWhichResult].dPepMass - PROTON_MASS);\r\n         fprintf(fpout, \"%0.2E\\t\", pOutput[iWhichResult].dExpect);\r\n         fprintf(fpout, \"%0.4f\\t\", pOutput[iWhichResult].fXcorr);\r\n         fprintf(fpout, \"%0.4f\\t\", dDeltaCn);\r\n         fprintf(fpout, \"%0.1f\\t\", pOutput[iWhichResult].fScoreSp);\r\n         fprintf(fpout, \"%d\\t\", pOutput[iWhichResult].iMatchedIons);\r\n         fprintf(fpout, \"%d\\t\", pOutput[iWhichResult].iTotalIons);\r\n\r\n         \/\/ plain peptide\r\n         fprintf(fpout, \"%s\\t\", pOutput[iWhichResult].szPeptide);\r\n\r\n         \/\/ modified peptide\r\n\r\n         bool bNterm = false;\r\n         bool bCterm = false;\r\n         double dNterm = 0.0;\r\n         double dCterm = 0.0;\r\n\r\n         \/\/ See if n-term mod (static and\/or variable) needs to be reported\r\n         if (pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide] > 0)\r\n         {\r\n            bNterm = true;\r\n            dNterm = g_staticParams.variableModParameters.varModList[(int)pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide]-1].dVarModMass;\r\n         }\r\n\r\n         \/\/ See if c-term mod (static and\/or variable) needs to be reported\r\n         if (pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide+1] > 0)\r\n         {\r\n            bCterm = true;\r\n            dCterm = g_staticParams.variableModParameters.varModList[(int)pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide+1]-1].dVarModMass;\r\n         }\r\n\r\n         \/\/ generate modified_peptide string\r\n         fprintf(fpout, \"%c.\", pOutput[iWhichResult].szPrevNextAA[0]);\r\n         if (bNterm)\r\n            fprintf(fpout, \"n[%0.4f]\", dNterm);\r\n         for (int i=0; i<pOutput[iWhichResult].iLenPeptide; i++)\r\n         {\r\n            fprintf(fpout, \"%c\", pOutput[iWhichResult].szPeptide[i]);\r\n\r\n            if (pOutput[iWhichResult].piVarModSites[i] != 0)\r\n               fprintf(fpout, \"[%0.4f]\", pOutput[iWhichResult].pdVarModSites[i]);\r\n         }\r\n         if (bCterm)\r\n            fprintf(fpout, \"c[%0.4f]\", dCterm);\r\n\r\n         fprintf(fpout, \".%c\\t\", pOutput[iWhichResult].szPrevNextAA[1]);\r\n\r\n         \/\/ mod string with PEFF\r\n         if (g_staticParams.peffInfo.iPeffSearch)\r\n         {\r\n            fprintf(fpout, \"%c.\", pOutput[iWhichResult].szPrevNextAA[0]);\r\n            if (bNterm)\r\n               fprintf(fpout, \"n[%0.4f]\", dNterm);\r\n            for (int i=0; i<pOutput[iWhichResult].iLenPeptide; i++)\r\n            {  \r\n               fprintf(fpout, \"%c\", pOutput[iWhichResult].szPeptide[i]);\r\n            \r\n               if (pOutput[iWhichResult].piVarModSites[i] < 0)\r\n                  fprintf(fpout, \"[%s]\", pOutput[iWhichResult].pszMod[i]);\r\n               else if (pOutput[iWhichResult].piVarModSites[i] > 0)\r\n                  fprintf(fpout, \"[%0.4f]\", pOutput[iWhichResult].pdVarModSites[i]);\r\n            }\r\n            if (bCterm)\r\n               fprintf(fpout, \"c[%0.4f]\", dCterm);\r\n\r\n            fprintf(fpout, \".%c\\t\", pOutput[iWhichResult].szPrevNextAA[1]);\r\n         }\r\n\r\n         fprintf(fpout, \"%c\\t\", pOutput[iWhichResult].szPrevNextAA[0]);\r\n         fprintf(fpout, \"%c\\t\", pOutput[iWhichResult].szPrevNextAA[1]);\r\n\r\n         \/\/ print protein list\r\n         PrintProteins(fpout, fpdb, iWhichQuery, iWhichResult, iPrintTargetDecoy);\r\n\r\n         size_t iNumTotProteins = 0;\r\n\r\n         if (iPrintTargetDecoy == 0)\r\n            iNumTotProteins = pOutput[iWhichResult].pWhichProtein.size() + pOutput[iWhichResult].pWhichDecoyProtein.size();\r\n         else if (iPrintTargetDecoy == 1)\r\n            iNumTotProteins = pOutput[iWhichResult].pWhichProtein.size();\r\n         else \/\/if (iPrintTargetDecoy == 2)\r\n            iNumTotProteins = pOutput[iWhichResult].pWhichDecoyProtein.size();\r\n\r\n         fprintf(fpout, \"\\t%zu\\t\", iNumTotProteins);\r\n\r\n         \/\/ encoded modifications\r\n         PrintModifications(fpout, pOutput, iWhichResult);\r\n\r\n         \/\/ retention time seconds\r\n         fprintf(fpout, \"%0.1f\\t\", pQuery->_spectrumInfoInternal.dRTime);\r\n\r\n         \/\/ Sp rank\r\n         fprintf(fpout, \"%d\", pOutput[iWhichResult].iRankSp);\r\n\r\n         fprintf(fpout, \"\\n\");\r\n      }\r\n   }\r\n#endif\r\n}\r\n\r\n\r\n\/\/ print out a comma separate list of protein refereces\/accessions\r\nvoid CometWriteTxt::PrintProteins(FILE *fpout,\r\n                                  FILE *fpdb,\r\n                                  int iWhichQuery,\r\n                                  int iWhichResult,\r\n                                  int iPrintTargetDecoy)\r\n{\r\n   std::vector<string> vProteinTargets;  \/\/ store vector of target protein names\r\n   std::vector<string> vProteinDecoys;   \/\/ store vector of decoy protein names\r\n   std::vector<string>::iterator it;\r\n\r\n   CometMassSpecUtils::GetProteinNameString(fpdb, iWhichQuery, iWhichResult, iPrintTargetDecoy, vProteinTargets, vProteinDecoys);\r\n \r\n   bool bPrintComma = false;\r\n   if (iPrintTargetDecoy != 2)  \/\/ if not decoy only, print target proteins\r\n   {\r\n      for (it = vProteinTargets.begin(); it != vProteinTargets.end(); it++)\r\n      {\r\n         if (bPrintComma)\r\n            fprintf(fpout, \",\");\r\n\r\n         fprintf(fpout, \"%s\", (*it).c_str());\r\n         bPrintComma = true;\r\n      }\r\n   }\r\n      \r\n   if (iPrintTargetDecoy != 1)  \/\/ if not target only, print decoy proteins\r\n   {\r\n      for (it = vProteinDecoys.begin(); it != vProteinDecoys.end(); it++)\r\n      {\r\n         if (bPrintComma)\r\n            fprintf(fpout, \",\");\r\n\r\n         fprintf(fpout, \"%s\", (*it).c_str());\r\n         bPrintComma = true;\r\n      }\r\n   }\r\n}\r\n\r\n\r\n\/\/ <offset> [S|V] <value> [N|C|n|c|]\r\n\/\/ <offset> P <value>   for PEFF modificaiton\r\n\/\/ <offset> p <residue> for PEFF substitution\r\nvoid CometWriteTxt::PrintModifications(FILE *fpout,\r\n                                       Results *pOutput,\r\n                                       int iWhichResult)\r\n{\r\n   bool bFirst = true;\r\n   bool bPrintMod = false;\r\n\r\n   \/\/ static N-terminus protein\r\n   if (!isEqual(g_staticParams.staticModifications.dAddNterminusProtein, 0.0)\r\n         && pOutput[iWhichResult].szPrevNextAA[0] == '-')\r\n   {\r\n      if (!bFirst)\r\n         fprintf(fpout, \", \");\r\n      else\r\n         bFirst=false;\r\n\r\n      fprintf(fpout, \"1_S_%0.6f_N\", g_staticParams.staticModifications.dAddNterminusProtein);\r\n      bPrintMod = true;\r\n   }\r\n\r\n   \/\/ static N-terminus peptide\r\n   if (!isEqual(g_staticParams.staticModifications.dAddNterminusPeptide, 0.0))\r\n   {\r\n      if (!bFirst)\r\n         fprintf(fpout, \", \");\r\n      else\r\n         bFirst=false;\r\n\r\n      fprintf(fpout, \"1_S_%0.6f_n\", g_staticParams.staticModifications.dAddNterminusPeptide);\r\n      bPrintMod = true;\r\n   }\r\n\r\n   \/\/ variable N-terminus peptide and protein\r\n   if (g_staticParams.variableModParameters.bVarModSearch\r\n         && pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide] > 0)\r\n   {\r\n      if (!bFirst)\r\n         fprintf(fpout, \", \");\r\n      else\r\n         bFirst=false;\r\n\r\n      fprintf(fpout, \"1_V_%0.6f\",\r\n            g_staticParams.variableModParameters.varModList[pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide]-1].dVarModMass);\r\n\r\n      if (g_staticParams.variableModParameters.varModList[pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide]-1].iVarModTermDistance == 0)\r\n         fprintf(fpout, \"_N\");\r\n      else\r\n         fprintf(fpout, \"_n\");\r\n      bPrintMod = true;\r\n   }\r\n\r\n   for (int i=0; i<pOutput[iWhichResult].iLenPeptide; i++)\r\n   {\r\n      \/\/ static modification\r\n      if (!isEqual(g_staticParams.staticModifications.pdStaticMods[(int)pOutput[iWhichResult].szPeptide[i]], 0.0))\r\n      {\r\n         if (!bFirst)\r\n            fprintf(fpout, \",\");\r\n         else\r\n            bFirst=false;\r\n\r\n         fprintf(fpout, \"%d_S_%0.6f\",\r\n               i+1,\r\n               g_staticParams.staticModifications.pdStaticMods[(int)pOutput[iWhichResult].szPeptide[i]]);\r\n         bPrintMod = true;\r\n      }\r\n\r\n      \/\/ variable modification\r\n      if (g_staticParams.variableModParameters.bVarModSearch && pOutput[iWhichResult].piVarModSites[i] != 0)\r\n      {\r\n         if (!bFirst)\r\n            fprintf(fpout, \",\");\r\n         else\r\n            bFirst=false;\r\n\r\n         if (g_staticParams.variableModParameters.bVarModSearch && pOutput[iWhichResult].piVarModSites[i] > 0)\r\n            fprintf(fpout, \"%d_V_%0.6f\", i+1, pOutput[iWhichResult].pdVarModSites[i]);  \/\/ variable mod\r\n         else\r\n            fprintf(fpout, \"%d_P_%0.6f\", i+1, pOutput[iWhichResult].pdVarModSites[i]);  \/\/ PEFF mod\r\n         bPrintMod = true;\r\n      }\r\n   }\r\n\r\n   \/\/ static C-terminus protein\r\n   if (!isEqual(g_staticParams.staticModifications.dAddCterminusProtein, 0.0)\r\n         && pOutput[iWhichResult].szPrevNextAA[1] == '-')\r\n   {\r\n      if (!bFirst)\r\n         fprintf(fpout, \",\");\r\n      else\r\n         bFirst=false;\r\n\r\n      fprintf(fpout, \"%d_S_%0.6f_C\", pOutput[iWhichResult].iLenPeptide, g_staticParams.staticModifications.dAddCterminusProtein);\r\n      bPrintMod = true;\r\n   }\r\n\r\n   \/\/ static C-terminus peptide\r\n   if (!isEqual(g_staticParams.staticModifications.dAddCterminusPeptide, 0.0))\r\n   {\r\n      if (!bFirst)\r\n         fprintf(fpout, \",\");\r\n      else\r\n         bFirst=false;\r\n\r\n      fprintf(fpout, \"%d_S_%0.6f_c\", pOutput[iWhichResult].iLenPeptide, g_staticParams.staticModifications.dAddCterminusPeptide);\r\n      bPrintMod = true;\r\n   }\r\n\r\n   \/\/ variable C-terminus peptide and protein\r\n   if (g_staticParams.variableModParameters.bVarModSearch\r\n         && pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide+1] > 0)\r\n   {\r\n      if (!bFirst)\r\n         fprintf(fpout, \",\");\r\n      else\r\n         bFirst=false;\r\n\r\n      fprintf(fpout, \"%d_V_%0.6f\",\r\n            pOutput[iWhichResult].iLenPeptide,\r\n            g_staticParams.variableModParameters.varModList[pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide+1]-1].dVarModMass);\r\n\r\n      if (g_staticParams.variableModParameters.varModList[pOutput[iWhichResult].piVarModSites[pOutput[iWhichResult].iLenPeptide+1]-1].iVarModTermDistance == 0)\r\n         fprintf(fpout, \"_C\");\r\n      else\r\n         fprintf(fpout, \"_c\");\r\n      bPrintMod = true;\r\n   }\r\n\r\n   \/\/ PEFF amino acid substitution\r\n   \/\/if (pOutput[iWhichResult].cPeffOrigResidue != '\\0' && pOutput[iWhichResult].iPeffOrigResiduePosition != -9)\r\n   if (!pOutput[iWhichResult].sPeffOrigResidues.empty() && pOutput[iWhichResult].iPeffOrigResiduePosition != NO_PEFF_VARIANT)\r\n   {\r\n      if (!bFirst)\r\n         fprintf(fpout, \",\");\r\n      else\r\n         bFirst=false;\r\n\r\n      \/\/fprintf(fpout, \"%d_p_%c\", pOutput[iWhichResult].iPeffOrigResiduePosition+1, pOutput[iWhichResult].cPeffOrigResidue);\r\n      if(pOutput[iWhichResult].sPeffOrigResidues.size()>1)\r\n        fprintf(fpout, \"%d-%d_p_%s\", pOutput[iWhichResult].iPeffOrigResiduePosition + 1, pOutput[iWhichResult].iPeffOrigResiduePosition + (int)pOutput[iWhichResult].sPeffOrigResidues.size(), pOutput[iWhichResult].sPeffOrigResidues.c_str());\r\n      else\r\n        fprintf(fpout, \"%d_p_%s\", pOutput[iWhichResult].iPeffOrigResiduePosition + 1, pOutput[iWhichResult].sPeffOrigResidues.c_str());\r\n      bPrintMod = true;\r\n   }\r\n\r\n   if (bPrintMod)\r\n      fprintf(fpout, \"\\t\");\r\n   else\r\n      fprintf(fpout, \"-\\t\");\r\n}\r\n","avg_line_length":37.4180967239,"max_line_length":241,"alphanum_fraction":0.5856993955,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3229,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":6.0,"content":"\/****************************************************************************\n** Meta object code from reading C++ file 'uritests.h'\n**\n**\n** WARNING! All changes made in this file will be lost!\n*****************************************************************************\/\n\n#include \"qt\/test\/uritests.h\"\n#include <QtCore\/qbytearray.h>\n#include <QtCore\/qmetatype.h>\n#if !defined(Q_MOC_OUTPUT_REVISION)\n#error \"The header file 'uritests.h' doesn't include <QObject>.\"\n#elif Q_MOC_OUTPUT_REVISION != 67\n#error \"This file was generated using the moc from 5.9.8. It\"\n#error \"cannot be used with the include files from this version of Qt.\"\n#error \"(The moc has changed too much.)\"\n#endif\n\nQT_BEGIN_MOC_NAMESPACE\nQT_WARNING_PUSH\nQT_WARNING_DISABLE_DEPRECATED\nstruct qt_meta_stringdata_URITests_t {\n    QByteArrayData data[3];\n    char stringdata0[19];\n};\n#define QT_MOC_LITERAL(idx, ofs, len) \\\n    Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \\\n    qptrdiff(offsetof(qt_meta_stringdata_URITests_t, stringdata0) + ofs \\\n        - idx * sizeof(QByteArrayData)) \\\n    )\nstatic const qt_meta_stringdata_URITests_t qt_meta_stringdata_URITests = {\n    {\nQT_MOC_LITERAL(0, 0, 8), \/\/ \"URITests\"\nQT_MOC_LITERAL(1, 9, 8), \/\/ \"uriTests\"\nQT_MOC_LITERAL(2, 18, 0) \/\/ \"\"\n\n    },\n    \"URITests\\0uriTests\\0\"\n};\n#undef QT_MOC_LITERAL\n\nstatic const uint qt_meta_data_URITests[] = {\n\n \/\/ content:\n       7,       \/\/ revision\n       0,       \/\/ classname\n       0,    0, \/\/ classinfo\n       1,   14, \/\/ methods\n       0,    0, \/\/ properties\n       0,    0, \/\/ enums\/sets\n       0,    0, \/\/ constructors\n       0,       \/\/ flags\n       0,       \/\/ signalCount\n\n \/\/ slots: name, argc, parameters, tag, flags\n       1,    0,   19,    2, 0x08 \/* Private *\/,\n\n \/\/ slots: parameters\n    QMetaType::Void,\n\n       0        \/\/ eod\n};\n\nvoid URITests::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)\n{\n    if (_c == QMetaObject::InvokeMetaMethod) {\n        URITests *_t = static_cast<URITests *>(_o);\n        Q_UNUSED(_t)\n        switch (_id) {\n        case 0: _t->uriTests(); break;\n        default: ;\n        }\n    }\n    Q_UNUSED(_a);\n}\n\nconst QMetaObject URITests::staticMetaObject = {\n    { &QObject::staticMetaObject, qt_meta_stringdata_URITests.data,\n      qt_meta_data_URITests,  qt_static_metacall, nullptr, nullptr}\n};\n\n\nconst QMetaObject *URITests::metaObject() const\n{\n    return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;\n}\n\nvoid *URITests::qt_metacast(const char *_clname)\n{\n    if (!_clname) return nullptr;\n    if (!strcmp(_clname, qt_meta_stringdata_URITests.stringdata0))\n        return static_cast<void*>(this);\n    return QObject::qt_metacast(_clname);\n}\n\nint URITests::qt_metacall(QMetaObject::Call _c, int _id, void **_a)\n{\n    _id = QObject::qt_metacall(_c, _id, _a);\n    if (_id < 0)\n        return _id;\n    if (_c == QMetaObject::InvokeMetaMethod) {\n        if (_id < 1)\n            qt_static_metacall(this, _c, _id, _a);\n        _id -= 1;\n    } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {\n        if (_id < 1)\n            *reinterpret_cast<int*>(_a[0]) = -1;\n        _id -= 1;\n    }\n    return _id;\n}\nQT_WARNING_POP\nQT_END_MOC_NAMESPACE\n","avg_line_length":28.3245614035,"max_line_length":96,"alphanum_fraction":0.614741406,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":2468,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":29.0,"content":"#include \"header\/block\/pd_block.h\"\n#include \"header\/basic\/utility.h\"\n#include \"header\/steps_namespace.h\"\n#include <istream>\n#include <iostream>\n\nusing namespace std;\n\nPD_BLOCK::PD_BLOCK(STEPS& toolkit) : BLOCK(toolkit), p_block(toolkit), d_block(toolkit)\n{\n    set_Kp(1.0);\n    set_Kd(1.0);\n    set_Td_in_s(999.0);\n}\n\nPD_BLOCK::~PD_BLOCK()\n{\n    ;\n}\n\nvoid PD_BLOCK::set_Kp(double K)\n{\n    \/*if(K==0)\n    {\n        ostringstream osstream;\n        osstream<<\"Error. Zero amplifier Kp of PROPORTIONAL_BLOCK part is not allowed for PD_BLOCK.\";\n        toolkit.show_information_with_leading_time_stamp(osstream);\n        return;\n    }*\/\n    p_block.set_K(K);\n}\n\ndouble PD_BLOCK::get_Kp() const\n{\n    return p_block.get_K();\n}\n\nvoid PD_BLOCK::set_Kd(double K)\n{\n    d_block.set_K(K);\n}\n\ndouble PD_BLOCK::get_Kd() const\n{\n    return d_block.get_K();\n}\n\nvoid PD_BLOCK::set_Td_in_s(double T)\n{\n    if(T<=0.0)\n    {\n        ostringstream osstream;\n        osstream<<\"Error. Non-positive time constant Td is not allowed for PD_BLOCK.\";\n        STEPS& toolkit = get_toolkit();\n        toolkit.show_information_with_leading_time_stamp(osstream);\n        return;\n    }\n    d_block.set_T_in_s(T);\n}\n\ndouble PD_BLOCK::get_Td_in_s() const\n{\n    return d_block.get_T_in_s();\n}\n\ndouble PD_BLOCK::get_differentiator_state() const\n{\n    return d_block.get_state();\n}\n\ndouble PD_BLOCK::get_differentiator_store() const\n{\n    return d_block.get_store();\n}\n\nvoid PD_BLOCK::initialize()\n{\n    double y = get_output();\n    p_block.set_output(y);\n    d_block.set_input(0.0);\n\n    p_block.initialize();\n    d_block.initialize();\n\n    set_input(p_block.get_input());\n}\n\nvoid PD_BLOCK::run(DYNAMIC_MODE mode)\n{\n    double x = get_input();\n    p_block.set_input(x);\n    d_block.set_input(x);\n\n    if(mode==INTEGRATE_MODE)\n        integrate();\n    if(mode==UPDATE_MODE)\n        update();\n\n    double y = p_block.get_output() + d_block.get_output();\n    if(get_limiter_type() == NO_LIMITER)\n        set_output(y);\n    else\n    {\n        double vmax = get_upper_limit();\n        double vmin = get_lower_limit();\n        if(y>vmax)\n            y = vmax;\n        else\n        {\n            if(y<vmin)\n                y = vmin;\n        }\n        set_output(y);\n    }\n}\n\nvoid PD_BLOCK::integrate()\n{\n    p_block.run(INTEGRATE_MODE);\n    d_block.run(INTEGRATE_MODE);\n}\n\nvoid PD_BLOCK::update()\n{\n    p_block.run(UPDATE_MODE);\n    d_block.run(UPDATE_MODE);\n}\n\nvoid PD_BLOCK::check()\n{\n    check_limiter();\n}\n","avg_line_length":18.5563909774,"max_line_length":101,"alphanum_fraction":0.6349270665,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1013,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":1.0,"content":"\/**\n *    Copyright 2016 MongoDB, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\/\n\n#include \"mongo\/platform\/basic.h\"\n\n#include \"mongo\/base\/init.h\"\n\nnamespace mongo {\nnamespace {\n\n\/\/ This initializer provides a no-op definition of the LoadICUData MONGO_INITIALIZER, for use when\n\/\/ the system version of ICU is used instead of the vendored version.\nMONGO_INITIALIZER(LoadICUData)(InitializerContext* context) {\n    return Status::OK();\n}\n\n}  \/\/ namespace\n}  \/\/ namespace mongo\n","avg_line_length":31.65625,"max_line_length":98,"alphanum_fraction":0.7245804541,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":17671,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/*******************************************************************************\n* Copyright 2020-2021 Intel Corporation\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*******************************************************************************\/\n\n#include \"cpu\/x64\/brgemm\/brgemm.hpp\"\n\n#include \"common\/c_types_map.hpp\"\n#include \"common\/nstl.hpp\"\n#include \"common\/type_helpers.hpp\"\n#include \"common\/utils.hpp\"\n\n#include \"cpu\/x64\/brgemm\/brgemm_types.hpp\"\n#include \"cpu\/x64\/cpu_barrier.hpp\"\n\nnamespace dnnl {\nnamespace impl {\nnamespace cpu {\nnamespace x64 {\n\nusing namespace dnnl::impl::status;\nusing namespace dnnl::impl::utils;\n\nusing namespace prop_kind;\nusing namespace data_type;\n\nvoid brgemm_kernel_execute(const brgemm_kernel_t *brg_kernel, int bs,\n        const brgemm_batch_element_t *batch, void *ptr_C, void *scratch) {\n    brgemm_kernel_params_t brgemm_p;\n\n    brgemm_p.batch = batch;\n    brgemm_p.ptr_A = nullptr;\n    brgemm_p.ptr_B = nullptr;\n    brgemm_p.ptr_C = ptr_C;\n    brgemm_p.ptr_D = ptr_C;\n    brgemm_p.ptr_buf = scratch;\n    brgemm_p.ptr_bias = nullptr;\n    brgemm_p.do_post_ops = 0;\n    brgemm_p.BS = bs;\n    (*brg_kernel)(&brgemm_p);\n}\n\nvoid brgemm_kernel_execute(const brgemm_kernel_t *brg_kernel, int bs,\n        const void *addr_A, const void *addr_B,\n        const brgemm_batch_element_t *batch, void *ptr_C, void *scratch) {\n    brgemm_kernel_params_t brgemm_p;\n\n    brgemm_p.batch = batch;\n    brgemm_p.ptr_A = addr_A;\n    brgemm_p.ptr_B = addr_B;\n    brgemm_p.ptr_C = ptr_C;\n    brgemm_p.ptr_D = ptr_C;\n    brgemm_p.ptr_buf = scratch;\n    brgemm_p.ptr_bias = nullptr;\n    brgemm_p.do_post_ops = 0;\n    brgemm_p.BS = bs;\n    (*brg_kernel)(&brgemm_p);\n}\n\nvoid brgemm_kernel_execute_postops(const brgemm_kernel_t *brg_kernel, int bs,\n        const brgemm_batch_element_t *batch, void *ptr_C, void *ptr_D,\n        const void *bias, const float *scales, void *scratch) {\n    brgemm_kernel_params_t brgemm_p;\n\n    brgemm_p.batch = batch;\n    brgemm_p.ptr_A = nullptr;\n    brgemm_p.ptr_B = nullptr;\n    brgemm_p.ptr_C = ptr_C;\n    brgemm_p.ptr_D = ptr_D;\n    brgemm_p.ptr_buf = scratch;\n    brgemm_p.ptr_bias = bias;\n    brgemm_p.ptr_scales = scales;\n    brgemm_p.do_post_ops = 1;\n    brgemm_p.BS = bs;\n    (*brg_kernel)(&brgemm_p);\n}\n\nvoid brgemm_kernel_execute_postops(const brgemm_kernel_t *brg_kernel, int bs,\n        const void *addr_A, const void *addr_B,\n        const brgemm_batch_element_t *batch, void *ptr_C, void *ptr_D,\n        const void *bias, const float *scales, void *scratch) {\n    brgemm_kernel_params_t brgemm_p;\n\n    brgemm_p.batch = batch;\n    brgemm_p.ptr_A = addr_A;\n    brgemm_p.ptr_B = addr_B;\n    brgemm_p.ptr_C = ptr_C;\n    brgemm_p.ptr_D = ptr_D;\n    brgemm_p.ptr_buf = scratch;\n    brgemm_p.ptr_bias = bias;\n    brgemm_p.ptr_scales = scales;\n    brgemm_p.do_post_ops = 1;\n    brgemm_p.BS = bs;\n    (*brg_kernel)(&brgemm_p);\n}\n\nstatus_t brgemm_desc_init(brgemm_t *brg, cpu_isa_t isa,\n        brgemm_batch_kind_t type, impl::data_type_t dt_a,\n        impl::data_type_t dt_b, bool transA, bool transB,\n        brgemm_layout_t layout, float alpha, float beta, dim_t LDA, dim_t LDB,\n        dim_t LDC, dim_t M, dim_t N, dim_t K, const brgemm_strides_t *strides) {\n    \/*\n    m - number of rows of the matrix op(A) and number of rows of the matrix C\n    n - number of columns of the matrix op(B) and number of columns of the matrix C\n    k - number of columns of the matrix op(A) and number of rows of the matrix op(B)\n\n    Matrices are in row-major layouts:\n        A: lda * m, LDA - lda must be at least max(1, k)\n        B: ldb * k, LDB - ldb must be at least max(1, n)\n        C: ldc * m, LDC - ldc must be at least max(1, n)\n\n    Matrices are in column-major layouts:\n        A: lda * k, LDA - lda must be at least max(1, m)\n        B: ldb * n, LDB - ldb must be at least max(1, k)\n        C: ldc * n, LDC - ldc must be at least max(1, m)\n    *\/\n    if (brg == nullptr) return status::invalid_arguments;\n    if (transA || transB) return status::unimplemented;\n\n    brg->layout = layout;\n    auto is_row_major = [&]() { return brg->layout == brgemm_row_major; };\n    if (M <= 0 || N <= 0 || K <= 0) return status::invalid_arguments;\n    bool ldx_check = (is_row_major()) ? (LDA < K || LDB < N || LDC < N)\n                                      : (LDA < M || LDB < K || LDC < M);\n    if (ldx_check) return status::invalid_arguments;\n\n    brg->dt_a = (is_row_major()) ? dt_a : dt_b;\n    brg->dt_b = (is_row_major()) ? dt_b : dt_a;\n\n    brg->is_int8 = (one_of(brg->dt_a, data_type::u8, data_type::s8)\n            && brg->dt_b == data_type::s8);\n    brg->is_bf16\n            = (brg->dt_a == data_type::bf16 && brg->dt_b == data_type::bf16);\n    brg->is_f32 = (brg->dt_a == data_type::f32 && brg->dt_b == data_type::f32);\n    if (!brg->is_int8 && !brg->is_bf16 && !brg->is_f32)\n        return status::unimplemented;\n    brg->dt_c = (brg->is_int8) ? data_type::s32 : data_type::f32;\n    brg->dt_d = brg->dt_c;\n    brg->dt_bias = brg->dt_c;\n\n    if (!IMPLICATION(brg->is_f32, mayiuse(avx512_core)))\n        return status::unimplemented;\n    if (!IMPLICATION(brg->is_bf16, mayiuse(avx512_core_bf16)))\n        return status::unimplemented;\n    if (!IMPLICATION(brg->is_int8, mayiuse(avx512_core_vnni)))\n        return status::unimplemented;\n\n    if (isa != isa_any) {\n        if (!one_of(isa, avx512_core, avx512_core_bf16, avx512_core_vnni,\n                    avx512_core_bf16_amx_bf16, avx512_core_bf16_amx_int8)) {\n            return status::invalid_arguments;\n        }\n        brg->is_int8_amx = brg->is_bf16_amx = false;\n        if (brg->is_int8 && isa == avx512_core_bf16_amx_int8) {\n            if (!mayiuse(avx512_core_bf16_amx_int8))\n                return status::invalid_arguments;\n            brg->is_int8_amx = true;\n        }\n        if (brg->is_bf16 && isa == avx512_core_bf16_amx_bf16) {\n            if (!mayiuse(avx512_core_bf16_amx_bf16))\n                return status::invalid_arguments;\n            brg->is_bf16_amx = true;\n        }\n    } else {\n        brg->is_int8_amx = brg->is_int8 && mayiuse(avx512_core_bf16_amx_int8);\n        brg->is_bf16_amx = brg->is_bf16 && mayiuse(avx512_core_bf16_amx_bf16);\n    }\n    brg->req_s8s8_compensation\n            = brg->is_int8 && !brg->is_int8_amx && brg->dt_a == data_type::s8;\n    brg->LDA = (is_row_major()) ? (int)LDA : (int)LDB;\n    brg->LDB = (is_row_major()) ? (int)LDB : (int)LDA;\n\n    brg->LDC = (int)LDC;\n    brg->LDD = (int)LDC;\n\n    brg->bcast_dim = (is_row_major()) ? (int)M : (int)N;\n    brg->load_dim = (is_row_major()) ? (int)N : (int)M;\n    brg->reduce_dim = (int)K;\n\n    brg->with_bias = false;\n    brg->with_eltwise = false;\n    brg->with_sum = false;\n    brg->sum_scale = 0;\n    brg->with_scales = false;\n\n    brg->beta = beta;\n    brg->alpha = alpha;\n\n    brg->typesize_A = types::data_type_size(brg->dt_a);\n    brg->typesize_B = types::data_type_size(brg->dt_b);\n    brg->typesize_C = types::data_type_size(brg->dt_c);\n    brg->typesize_D = types::data_type_size(brg->dt_d);\n    brg->type = type;\n\n    brg->bd_block2 = 0;\n    brg->bdb2 = 0;\n    brg->bdb2_tail = 0;\n\n    brg->ld_step = brg->rd_step = 4 \/ brg->typesize_A;\n\n    if (!brg->is_int8_amx && !brg->is_bf16_amx) {\n        brg->ld_block = 16;\n        brg->ldb = brg->load_dim \/ brg->ld_block;\n        brg->ldb_tail = brg->load_dim % brg->ld_block;\n\n        brg->ld_block2 = 4; \/\/ (M < 9) ? 2 : 4 | TODO - fix this for INT8\n        brg->ldb2 = brg->ldb \/ brg->ld_block2;\n        brg->ldb2_tail = brg->ldb % brg->ld_block2;\n\n        if (brg->ldb2 == 0) brg->ld_block2 = nstl::max(1, brg->ldb2_tail);\n        brg->embd_bcst = !brg->is_int8 && !brg->is_bf16\n                && (brg->ldb2_tail <= 1 && brg->ldb2 == 0);\n\n        int ld_block = (brg->ldb2 != 0) ? brg->ld_block2 : brg->ldb2_tail;\n        int adj_ld_block = (ld_block == 0) ? (ld_block + 1) : ld_block;\n\n        const int max_avx512_regs = 32;\n        const int max_bcst_regs = 1;\n        int max_regs = max_avx512_regs - (adj_ld_block + max_bcst_regs);\n        int max_block\n                = (brg->embd_bcst ? 28\n                                  : ((brg->beta == 1.f || brg->beta == 0.f)\n                                                  ? max_regs\n                                                  : max_regs - 1));\n        max_block -= brg->req_s8s8_compensation;\n        max_block \/= adj_ld_block;\n        int min_block = 1;\n        float best_bd_block_eff = 0.f;\n        brg->bd_block = 1;\n        for (int bd_block = max_block; bd_block >= min_block; bd_block--) {\n            const auto bd_block_disb\n                    = (float)brg->bcast_dim \/ rnd_up(brg->bcast_dim, bd_block);\n            const auto brgemm_microkernel_eff = ((float)(adj_ld_block)*bd_block)\n                    \/ (((adj_ld_block) + bd_block) * max_block);\n            const auto bd_block_eff = bd_block_disb * brgemm_microkernel_eff;\n\n            float block_foot_print\n                    = (float)brg->typesize_A * (bd_block * brg->reduce_dim);\n            if (block_foot_print <= (float)platform::get_per_core_cache_size(1)\n                    && (bd_block_eff > best_bd_block_eff)) {\n                brg->bd_block = bd_block;\n                best_bd_block_eff = bd_block_eff;\n            }\n        }\n        brg->bdb = brg->bcast_dim \/ brg->bd_block;\n        brg->bdb_tail = brg->bcast_dim % brg->bd_block;\n\n        brg->rd_block = 16 \/ brg->typesize_A;\n        brg->rdb = brg->reduce_dim \/ brg->rd_block;\n        brg->rdb_tail = brg->reduce_dim % brg->rd_block;\n    } else {\n        \/\/ Blocking configuration for AMX\n        const int max_width = 16, min_width = 1;\n        for (int m_block = max_width; m_block >= min_width; m_block--) {\n            if (brg->bcast_dim % m_block == 0) {\n                brg->bd_block = m_block;\n                break;\n            }\n        }\n        if (brg->bd_block == 1) {\n            brg->bd_block = nstl::min(max_width, brg->bcast_dim);\n            brg->bdb_tail = brg->bcast_dim % max_width;\n            for (int i = max_width; i >= min_width; i--) {\n                int i_tail = brg->bcast_dim % i;\n                if (i_tail > brg->bdb_tail || i_tail == 0) {\n                    brg->bd_block = i;\n                    brg->bdb_tail = i_tail;\n                    if (i_tail == 0) break;\n                }\n            }\n        }\n        brg->bdb = brg->bcast_dim \/ brg->bd_block;\n        brg->bdb_tail = brg->bcast_dim % brg->bd_block;\n\n        brg->bd_block2 = (brg->bdb >= 2) ? 2 : 1;\n        brg->bdb2 = brg->bdb \/ brg->bd_block2;\n        brg->bdb2_tail\n                = (brg->bd_block2 == 1) ? brg->bdb : brg->bdb % brg->bd_block2;\n\n        brg->ld_block = 16;\n        brg->ldb = brg->load_dim \/ brg->ld_block;\n        brg->ldb_tail = brg->load_dim % brg->ld_block;\n\n        brg->ld_block2\n                = (brg->ldb > 0 && brg->ldb % 2 == 0 && brg->ldb_tail == 0) ? 2\n                                                                            : 1;\n        brg->ldb2 = brg->ldb \/ brg->ld_block2;\n        brg->ldb2_tail = brg->ldb % brg->ld_block2;\n\n        brg->rd_block = brg->is_bf16_amx ? 32 : 64;\n        brg->rdb = brg->reduce_dim \/ brg->rd_block;\n        brg->rdb_tail = brg->reduce_dim % brg->rd_block;\n\n        \/\/ Remove these guard in the future (add tail processing by reduction dimension)\n        if (brg->rdb > 0 && brg->rdb_tail) return status::unimplemented;\n        if (brg->rdb_tail % ((brg->is_bf16_amx) ? 2 : 4))\n            return status::unimplemented;\n    }\n\n    if (strides != nullptr) {\n        brg->stride_a = strides->stride_a;\n        brg->stride_b = strides->stride_b;\n    } else {\n        brg->stride_a = brg->stride_b = 0;\n    }\n\n    return status::success;\n}\n\nstatus_t brgemm_desc_set_postops(brgemm_t *brg, const primitive_attr_t *attr,\n        impl::data_type_t dt_d, int LDD, impl::data_type_t dt_bias) {\n    if (brg == nullptr) return status::invalid_arguments;\n\n    brg->attr = attr;\n\n    brg->with_bias = (dt_bias == data_type::undef) ? false : true;\n    brg->dt_bias = dt_bias;\n    brg->typesize_bias = (dt_bias == data_type::undef)\n            ? 0\n            : types::data_type_size(brg->dt_bias);\n\n    brg->LDD = LDD;\n\n    if ((brg->dt_a == data_type::u8 && brg->dt_b == data_type::s8)\n            && (!one_of(dt_d, data_type::u8, data_type::s8, data_type::s32,\n                    data_type::f32))\n            && (!one_of(dt_bias, data_type::undef, data_type::u8, data_type::s8,\n                    data_type::s32, data_type::f32)))\n        return status::unimplemented;\n    if ((brg->dt_a == data_type::bf16 && brg->dt_b == data_type::bf16)\n            && (!one_of(dt_d, data_type::bf16, data_type::f32))\n            && (!one_of(dt_bias, data_type::undef, data_type::bf16,\n                    data_type::f32)))\n        return status::unimplemented;\n    if ((brg->dt_a == data_type::f32 && brg->dt_b == data_type::f32)\n            && (!one_of(dt_d, data_type::f32))\n            && (!one_of(dt_bias, data_type::undef, data_type::f32)))\n        return status::unimplemented;\n\n    brg->dt_d = dt_d;\n    brg->typesize_D = types::data_type_size(brg->dt_d);\n\n    const auto &p = brg->attr->post_ops_;\n    const int sum_idx = p.find(primitive_kind::sum);\n    brg->with_sum = sum_idx != -1;\n    brg->sum_scale = (sum_idx != -1) ? p.entry_[sum_idx].sum.scale : 0;\n\n    const int eltwise_ind = p.find(primitive_kind::eltwise);\n    brg->with_eltwise = eltwise_ind != -1;\n    if (brg->with_eltwise) brg->eltwise = p.entry_[eltwise_ind].eltwise;\n\n    if (brg->is_int8) {\n        const auto &oscales = brg->attr->output_scales_;\n        brg->is_oc_scale = oscales.mask_ == 1 << 1;\n        brg->with_scales = true;\n    }\n\n    return status::success;\n}\n\nstatus_t brgemm_desc_set_attr(brgemm_t *brg, const brgemm_attr_t &brgattr) {\n    if (brg == nullptr) return status::invalid_arguments;\n\n    \/\/ negative padding is not supported\n    if (brgattr.max_top_vpad < 0 || brgattr.max_bottom_vpad < 0)\n        return status::unimplemented;\n\n    \/\/ virtual padding is not supported for \"amx\"\n    if ((brgattr.max_top_vpad > 0 || brgattr.max_bottom_vpad > 0)\n            && (brg->is_int8_amx || brg->is_bf16_amx))\n        return status::unimplemented;\n\n    \/\/ virtual padding size is restricted by MAX_VPAD value\n    if (brgattr.max_top_vpad > brgemm_t::MAX_VPAD\n            || brgattr.max_bottom_vpad > brgemm_t::MAX_VPAD)\n        return status::unimplemented;\n\n    \/\/ virtual padding is restricted by bd_block size due to\n    \/\/ brgemm_kernel implementation. TODO: remove this restriction\n    if (brgattr.max_top_vpad > brg->bd_block\n            || brgattr.max_bottom_vpad > brg->bd_block)\n        return status::unimplemented;\n\n    \/\/ virtual padding is supported for \"brgemm_row_major\" layout\n    \/\/ TODO: remove this restriction\n    if ((brgattr.max_top_vpad > 0 || brgattr.max_bottom_vpad > 0)\n            && brg->layout != brgemm_row_major)\n        return status::unimplemented;\n\n    brg->brgattr = brgattr;\n    return status::success;\n}\n\nstatus_t brgemm_kernel_create(\n        brgemm_kernel_t **brg_kernel, const brgemm_t &brg) {\n    CHECK(safe_ptr_assign<brgemm_kernel_t>(\n            *brg_kernel, new brgemm_kernel_t(brg)));\n    return (*brg_kernel)->create_kernel();\n}\n\nvoid brgemm_kernel_destroy(brgemm_kernel_t *brg_kernel) {\n    delete brg_kernel;\n}\n\nstatus_t brgemm_init_tiles(const brgemm_t &brg, char palette[64]) {\n    constexpr int max_palette_size_in_bytes = 64;\n\n    if (!(brg.is_int8_amx || brg.is_bf16_amx)) return status::unimplemented;\n\n    \/\/TODO: Add support of tail processing by reduction dimension\n    int rd_block = (!brg.rdb && brg.rdb_tail) ? brg.rdb_tail : brg.rd_block;\n\n    palette_config_t *buff = (palette_config_t *)(palette);\n\n    char *_tc = (char *)buff;\n    for (int i = 0; i < max_palette_size_in_bytes; i++)\n        _tc[i] = 0;\n\n    int rd_step = 4 \/ brg.typesize_A;\n\n    int Ac = brg.typesize_A * rd_block;\n\n    int Bc = brg.ld_block * brg.typesize_B * rd_step;\n    int Bc_t = brg.ldb_tail * brg.typesize_B * rd_step;\n\n    int Cc = brg.ld_block * brg.typesize_C;\n    int Cc_t = brg.ldb_tail * brg.typesize_C;\n\n    int Ar = brg.bd_block;\n    int Br = (brg.typesize_C != 0) ? Ac \/ brg.typesize_C : 0;\n    int Cr = brg.bd_block;\n\n    if (brg.ldb_tail && (brg.ld_block2 + 1 > brgemm_amx::max_n_block2))\n        return status::unimplemented;\n    for (int m = 0; m < brgemm_amx::max_m_block2; m++)\n        tc_configure_tile(buff, brgemm_amx::get_A_tensor(m), Ar, Ac);\n    for (int n = 0; n < brg.ld_block2; n++)\n        tc_configure_tile(buff, brgemm_amx::get_B_tensor(n), Br, Bc);\n    if (brg.ldb_tail)\n        tc_configure_tile(\n                buff, brgemm_amx::get_B_tensor(brg.ld_block2), Br, Bc_t);\n    for (int m = 0; m < brgemm_amx::max_m_block2; m++) {\n        for (int n = 0; n < brg.ld_block2; n++)\n            tc_configure_tile(buff, brgemm_amx::get_C_tensor(m, n), Cr, Cc);\n        if (brg.ldb_tail)\n            tc_configure_tile(\n                    buff, brgemm_amx::get_C_tensor(m, brg.ld_block2), Cr, Cc_t);\n    }\n    buff->palette_id = amx::get_max_palette();\n\n    return status::success;\n}\n\n} \/\/ namespace x64\n} \/\/ namespace cpu\n} \/\/ namespace impl\n} \/\/ namespace dnnl\n\n\/\/ vim: et ts=4 sw=4 cindent cino+=l0,\\:4,N-s\n","avg_line_length":37.5180467091,"max_line_length":88,"alphanum_fraction":0.6025125913,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":14268,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/------------------------------------------------------------------------------\n\/\/ SFormat.cpp\n\/\/ SystemVerilog string formatting routines.\n\/\/\n\/\/ File is under the MIT license; see LICENSE for details.\n\/\/------------------------------------------------------------------------------\n#include \"slang\/text\/SFormat.h\"\n\n#include \"..\/text\/CharInfo.h\"\n#include <ieee1800\/vpi_user.h>\n\n#include \"slang\/diagnostics\/SysFuncsDiags.h\"\n#include \"slang\/symbols\/TypeSymbols.h\"\n\nnamespace slang::SFormat {\n\nstatic optional<uint32_t> parseUInt(const char*& ptr) {\n    \/\/ TODO: use std::from_chars and disallow prefix\n    char* end;\n    errno = 0;\n    unsigned long val = strtoul(ptr, &end, 10);\n\n    if (ptr == end || errno == ERANGE || val > UINT32_MAX)\n        return std::nullopt;\n\n    ptr = end;\n    return uint32_t(val);\n}\n\nstruct FormatOptions {\n    optional<uint32_t> width;\n    optional<uint32_t> precision;\n    bool leftJustify = false;\n    bool zeroPad = false;\n};\n\ntemplate<typename OnChar, typename OnArg>\nstatic bool parseFormatString(string_view str, SourceLocation loc, OnChar&& onChar, OnArg&& onArg,\n                              Diagnostics& diags) {\n    const char* ptr = str.data();\n    const char* end = str.data() + str.length();\n\n    auto onError = [&](DiagCode code, const char* curr) -> decltype(auto) {\n        SourceLocation sl = loc + (curr - str.data());\n        return diags.add(code, SourceRange{ sl, sl + (ptr - curr) });\n    };\n\n    while (ptr != end) {\n        const char* start = ptr;\n        if (char c = *ptr++; c != '%') {\n            onChar(c);\n            continue;\n        }\n\n        \/\/ %% collapses to a single %\n        if (ptr != end && *ptr == '%') {\n            ptr++;\n            onChar('%');\n            continue;\n        }\n\n        FormatOptions options;\n        while (ptr != end) {\n            if (*ptr == '-' && !options.leftJustify) {\n                options.leftJustify = true;\n                ptr++;\n            }\n            else if (*ptr == '0' && !options.zeroPad) {\n                options.zeroPad = true;\n                ptr++;\n            }\n            else {\n                break;\n            }\n        }\n\n        if (ptr != end && isDecimalDigit(*ptr)) {\n            options.width = parseUInt(ptr);\n            if (!options.width) {\n                onError(diag::FormatSpecifierInvalidWidth, start);\n                return false;\n            }\n        }\n\n        if (ptr != end && *ptr == '.') {\n            ptr++;\n            if (ptr != end && isDecimalDigit(*ptr)) {\n                options.precision = parseUInt(ptr);\n                if (!options.precision) {\n                    onError(diag::FormatSpecifierInvalidWidth, start);\n                    return false;\n                }\n            }\n            else {\n                \/\/ Precision defaults to zero if we just have a decimal point.\n                options.precision = 0;\n            }\n        }\n\n        if (ptr == end) {\n            onError(diag::MissingFormatSpecifier, start);\n            return false;\n        }\n\n        Arg::Type type;\n        bool widthAllowed = false;\n        bool floatAllowed = false;\n        char c = *ptr++;\n        switch (::tolower(c)) {\n            case 'l':\n            case 'm':\n                type = Arg::None;\n                break;\n            case 'h':\n            case 'x':\n            case 'd':\n            case 'o':\n            case 'b':\n                widthAllowed = true;\n                type = Arg::Integral;\n                if (options.zeroPad) {\n                    options.zeroPad = false;\n                    if (!options.width)\n                        options.width = 0;\n                }\n                break;\n            case 'u':\n            case 'z':\n                type = Arg::Raw;\n                break;\n            case 'e':\n            case 'f':\n            case 'g':\n                widthAllowed = true;\n                floatAllowed = true;\n                type = Arg::Float;\n                break;\n            case 't':\n                type = Arg::Float;\n                break;\n            case 'c':\n                type = Arg::Character;\n                break;\n            case 'v':\n                type = Arg::Net;\n                break;\n            case 'p':\n                type = Arg::Pattern;\n                break;\n            case 's':\n                widthAllowed = true;\n                type = Arg::String;\n                break;\n            default:\n                onError(diag::UnknownFormatSpecifier, start) << c;\n                return false;\n        }\n\n        if (options.width && !widthAllowed) {\n            onError(diag::FormatSpecifierWidthNotAllowed, start) << c;\n            return false;\n        }\n\n        if ((options.precision || options.leftJustify) && !floatAllowed) {\n            onError(diag::FormatSpecifierNotFloat, start);\n            return false;\n        }\n\n        if (options.zeroPad && !widthAllowed && type != Arg::Pattern) {\n            onError(diag::FormatSpecifierWidthNotAllowed, start) << c;\n            return false;\n        }\n\n        onArg(type, c, options);\n    }\n\n    return true;\n}\n\nstatic bool isValidForRaw(const Type& type) {\n    if (type.isIntegral())\n        return true;\n\n    if (type.isUnpackedUnion()) {\n        auto members = type.as<UnpackedUnionType>().members();\n        if (members.begin() == members.end())\n            return false;\n\n        return isValidForRaw(members.begin()->as<FieldSymbol>().getType());\n    }\n\n    if (!type.isUnpackedStruct())\n        return false;\n\n    auto& ust = type.getCanonicalType().as<UnpackedStructType>();\n    for (auto& member : ust.members()) {\n        if (!isValidForRaw(member.as<FieldSymbol>().getType()))\n            return false;\n    }\n\n    return true;\n}\n\nstatic void formatInt(std::string& result, const SVInt& value, LiteralBase base,\n                      const FormatOptions& options) {\n    std::string str;\n    if (base != LiteralBase::Decimal && value.isSigned()) {\n        \/\/ Non-decimal bases don't print as signed ever.\n        SVInt copy = value;\n        copy.setSigned(false);\n        str = copy.toString(base, \/* includeBase *\/ false);\n    }\n    else {\n        str = value.toString(base, \/* includeBase *\/ false);\n    }\n\n    \/\/ If no width is specified we need to calculate it ourselves based on the bitwidth\n    \/\/ of the provided integer.\n    uint32_t width = 0;\n    if (options.width)\n        width = *options.width;\n    else {\n        static const double log2_10 = log2(10.0);\n        bitwidth_t bw = value.getBitWidth();\n        switch (base) {\n            case LiteralBase::Binary:\n                width = bw;\n                break;\n            case LiteralBase::Octal:\n                width = uint32_t(ceil(bw \/ 3.0));\n                break;\n            case LiteralBase::Hex:\n                width = uint32_t(ceil(bw \/ 4.0));\n                break;\n            case LiteralBase::Decimal:\n                width = uint32_t(ceil(bw \/ log2_10));\n                if (value.isSigned())\n                    width++;\n                break;\n        }\n    }\n\n    if (str.size() < width) {\n        char pad = '0';\n        if (base == LiteralBase::Decimal)\n            pad = ' ';\n\n        result.append(width - str.size(), pad);\n    }\n\n    result.append(str);\n}\n\nstatic void formatFloat(std::string& result, double value, char specifier,\n                        const FormatOptions& options) {\n    \/\/ TODO: use std::to_chars\n    std::string fmt = \"%\";\n    if (options.leftJustify)\n        fmt.push_back('-');\n    if (options.zeroPad)\n        fmt.push_back('0');\n    if (options.width)\n        fmt.append(std::to_string(*options.width));\n    if (options.precision) {\n        fmt.push_back('.');\n        fmt.append(std::to_string(*options.precision));\n    }\n    fmt.push_back(specifier);\n\n    size_t cur = result.size();\n    size_t sz = (size_t)snprintf(nullptr, 0, fmt.c_str(), value);\n    result.resize(cur + sz + 1);\n    snprintf(result.data() + cur, sz + 1, fmt.c_str(), value);\n    result.pop_back();\n}\n\nstatic void formatChar(std::string& result, const SVInt& value) {\n    char c = char(value.getRawPtr()[0] & 0xff);\n    result.push_back(c);\n}\n\nstatic void formatString(std::string& result, const std::string& value,\n                         const FormatOptions& options) {\n    if (options.width) {\n        uint32_t width = *options.width;\n        if (value.size() < width)\n            result.append(width - value.size(), ' ');\n    }\n\n    result.append(value);\n}\n\nstatic void formatRaw2(std::string& result, const ConstantValue& value) {\n    if (value.isUnpacked()) {\n        for (auto& elem : value.elements())\n            formatRaw2(result, elem);\n        return;\n    }\n\n    SVInt sv = value.integer();\n    sv.flattenUnknowns();\n\n    uint32_t words = sv.getNumWords();\n    uint32_t lastBits = sv.getBitWidth() % 64;\n    if (lastBits == 0)\n        lastBits = 64;\n\n    const uint64_t* ptr = sv.getRawPtr();\n    for (uint32_t i = 0; i < words; i++) {\n        \/\/ Don't write the upper half of the last word if we don't actually have those bits.\n        size_t bytes = (i == words - 1 && lastBits <= 32) ? sizeof(uint32_t) : sizeof(uint64_t);\n        result.append(reinterpret_cast<const char*>(ptr + i), bytes);\n    }\n}\n\nstatic void formatRaw4(std::string& result, const ConstantValue& value) {\n    if (value.isUnpacked()) {\n        for (auto& elem : value.elements())\n            formatRaw4(result, elem);\n        return;\n    }\n\n    const SVInt& sv = value.integer();\n    uint32_t words = sv.getNumWords();\n    const uint64_t* ptr = sv.getRawPtr();\n    const uint64_t* unknownPtr = nullptr;\n    if (sv.hasUnknown()) {\n        words \/= 2;\n        unknownPtr = ptr + words;\n    }\n\n    uint32_t lastBits = sv.getBitWidth() % 64;\n    if (lastBits == 0)\n        lastBits = 64;\n\n    auto writeEntry = [&result](uint32_t bits, uint32_t unknowns) {\n        \/\/ The encoding for X and Z are reversed from how SVInt stores them.\n        s_vpi_vecval entry;\n        entry.aval = bits ^ unknowns;\n        entry.bval = unknowns;\n        result.append(reinterpret_cast<const char*>(&entry), sizeof(s_vpi_vecval));\n    };\n\n    for (uint32_t i = 0; i < words; i++) {\n        uint64_t bits = ptr[i];\n        uint64_t unknowns = unknownPtr ? unknownPtr[i] : 0;\n\n        writeEntry(uint32_t(bits), uint32_t(unknowns));\n\n        \/\/ Don't write the upper half of the last word if we don't actually have those bits.\n        if (i != words - 1 || lastBits > 32)\n            writeEntry(uint32_t(bits >> 32), uint32_t(unknowns >> 32));\n    }\n}\n\nstatic void formatArg(std::string& result, const ConstantValue& arg, const Type&, char specifier,\n                      const FormatOptions& options, Diagnostics&) {\n    switch (::tolower(specifier)) {\n        case 'h':\n        case 'x':\n            formatInt(result, arg.integer(), LiteralBase::Hex, options);\n            return;\n        case 'd':\n            formatInt(result, arg.integer(), LiteralBase::Decimal, options);\n            return;\n        case 'o':\n            formatInt(result, arg.integer(), LiteralBase::Octal, options);\n            return;\n        case 'b':\n            formatInt(result, arg.integer(), LiteralBase::Binary, options);\n            return;\n        case 'u':\n            formatRaw2(result, arg);\n            return;\n        case 'z':\n            formatRaw4(result, arg);\n            return;\n        case 'e':\n        case 'f':\n        case 'g':\n            formatFloat(result, arg.convertToReal().real(), specifier, options);\n            return;\n        case 't':\n            \/\/ TODO:\n            return;\n        case 'c':\n            formatChar(result, arg.integer());\n            return;\n        case 'v':\n            \/\/ TODO:\n            return;\n        case 'p':\n            return;\n        case 's':\n            formatString(result, arg.convertToStr().str(), options);\n            return;\n        default:\n            THROW_UNREACHABLE;\n    }\n}\n\nstatic void formatNonArg(std::string& result, char specifier, const Scope& scope) {\n    specifier = char(::tolower(specifier));\n    if (specifier == 'l') {\n        \/\/ TODO: support libraries\n        return;\n    }\n\n    if (specifier == 'm') {\n        scope.asSymbol().getHierarchicalPath(result);\n        return;\n    }\n\n    THROW_UNREACHABLE;\n}\n\nbool parseArgs(string_view formatString, SourceLocation loc, SmallVector<Arg>& args,\n               Diagnostics& diags) {\n    auto onArg = [&](Arg::Type type, char c, const FormatOptions&) {\n        if (type == Arg::None)\n            return;\n        args.append({ type, c });\n    };\n    return parseFormatString(\n        formatString, loc, [](char) {}, onArg, diags);\n}\n\noptional<std::string> format(string_view formatString, SourceLocation loc,\n                             span<const TypedValue> args, const Scope& scope, Diagnostics& diags) {\n    std::string result;\n    auto argIt = args.begin();\n\n    auto onChar = [&](char c) { result += c; };\n\n    auto onArg = [&](Arg::Type requiredType, char c, const FormatOptions& options) {\n        if (requiredType == Arg::None) {\n            formatNonArg(result, c, scope);\n            return;\n        }\n\n        if (argIt == args.end()) {\n            \/\/ TODO: error for not enough args\n            return;\n        }\n\n        auto& [value, type, range] = *argIt;\n        if (!isArgTypeValid(requiredType, *type))\n            diags.add(diag::FormatMismatchedType, range) << *type << c;\n        else\n            formatArg(result, value, *type, c, options, diags);\n    };\n\n    if (!parseFormatString(formatString, loc, onChar, onArg, diags))\n        return std::nullopt;\n\n    \/\/ TODO: check for too many args\n\n    return result;\n}\n\nbool isArgTypeValid(Arg::Type required, const Type& type) {\n    switch (required) {\n        case Arg::Integral:\n        case Arg::Character:\n            return type.isIntegral();\n        case Arg::Float:\n            return type.isNumeric();\n        case Arg::Net:\n            \/\/ TODO: support this\n            return false;\n        case Arg::Raw:\n            return isValidForRaw(type);\n        case Arg::Pattern:\n            return true;\n        case Arg::String:\n            return type.isIntegral() || type.isString() || type.isByteArray();\n        case Arg::None:\n            return false;\n    }\n    return false;\n}\n\n} \/\/ namespace slang::SFormat\n","avg_line_length":29.479338843,"max_line_length":99,"alphanum_fraction":0.5152789459,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3832,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Unlicense"],"max_stars_count":15.0,"content":"\/\/=================================================================================================\n\/*!\n\/\/  \\file src\/mathtest\/tdvecdmatmult\/V2bMDa.cpp\n\/\/  \\brief Source file for the V2bMDa dense vector\/dense matrix multiplication math test\n\/\/\n\/\/  Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved\n\/\/\n\/\/  This file is part of the Blaze library. You can redistribute it and\/or modify it under\n\/\/  the terms of the New (Revised) BSD License. Redistribution and use in source and binary\n\/\/  forms, with or without modification, are permitted provided that the following conditions\n\/\/  are met:\n\/\/\n\/\/  1. Redistributions of source code must retain the above copyright notice, this list of\n\/\/     conditions and the following disclaimer.\n\/\/  2. Redistributions in binary form must reproduce the above copyright notice, this list\n\/\/     of conditions and the following disclaimer in the documentation and\/or other materials\n\/\/     provided with the distribution.\n\/\/  3. Neither the names of the Blaze development group nor the names of its contributors\n\/\/     may be used to endorse or promote products derived from this software without specific\n\/\/     prior written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n\/\/  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\/\/  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\n\/\/  SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n\/\/  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n\/\/  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/  DAMAGE.\n*\/\n\/\/=================================================================================================\n\n\n\/\/*************************************************************************************************\n\/\/ Includes\n\/\/*************************************************************************************************\n\n#include <cstdlib>\n#include <iostream>\n#include <blaze\/math\/DynamicMatrix.h>\n#include <blaze\/math\/StaticVector.h>\n#include <blazetest\/mathtest\/Creator.h>\n#include <blazetest\/mathtest\/tdvecdmatmult\/OperationTest.h>\n#include <blazetest\/system\/MathTest.h>\n\n#ifdef BLAZE_USE_HPX_THREADS\n#  include <hpx\/hpx_main.hpp>\n#endif\n\n\n\/\/=================================================================================================\n\/\/\n\/\/  MAIN FUNCTION\n\/\/\n\/\/=================================================================================================\n\n\/\/*************************************************************************************************\nint main()\n{\n   std::cout << \"   Running 'V2bMDa'...\" << std::endl;\n\n   using blazetest::mathtest::TypeA;\n   using blazetest::mathtest::TypeB;\n\n   try\n   {\n      \/\/ Matrix type definitions\n      using V2b = blaze::StaticVector<TypeB,2UL>;\n      using MDa = blaze::DynamicMatrix<TypeA>;\n\n      \/\/ Creator type definitions\n      using CV2b = blazetest::Creator<V2b>;\n      using CMDa = blazetest::Creator<MDa>;\n\n      \/\/ Running the tests\n      for( size_t i=0UL; i<=6UL; ++i ) {\n         RUN_TDVECDMATMULT_OPERATION_TEST( CV2b(), CMDa( 2UL, i ) );\n      }\n   }\n   catch( std::exception& ex ) {\n      std::cerr << \"\\n\\n ERROR DETECTED during dense vector\/dense matrix multiplication:\\n\"\n                << ex.what() << \"\\n\";\n      return EXIT_FAILURE;\n   }\n\n   return EXIT_SUCCESS;\n}\n\/\/*************************************************************************************************\n","avg_line_length":42.1098901099,"max_line_length":99,"alphanum_fraction":0.5657620042,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":492,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright Epic Games, Inc. All Rights Reserved.\n\n#include \"WebSocketTestGameMode.h\"\n#include \"WebSocketTestCharacter.h\"\n#include \"UObject\/ConstructorHelpers.h\"\n\nAWebSocketTestGameMode::AWebSocketTestGameMode()\n{\n\t\/\/ set default pawn class to our Blueprinted character\n\tstatic ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT(\"\/Game\/ThirdPersonCPP\/Blueprints\/ThirdPersonCharacter\"));\n\tif (PlayerPawnBPClass.Class != NULL)\n\t{\n\t\tDefaultPawnClass = PlayerPawnBPClass.Class;\n\t}\n}\n","avg_line_length":30.75,"max_line_length":128,"alphanum_fraction":0.8008130081,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":21532,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"#include \"Filter.h\"\n\nstring Filter::edges_window_title = \"Edges\";\n\nconst int sigma = 100;\nconst int thresholdSize = 51;\nconst int blurKernelSize = 3;\nconst int threshMaxVal = 255;\/\/ 26;\nconst int lowThreshold = 0;\nconst int highThreshold = 128;\nconst int C = 2;\n\nconst Mat cross = getStructuringElement(CV_SHAPE_CROSS, Size(3, 3));\nconst Mat rect = getStructuringElement(CV_SHAPE_RECT, Size(3, 3));\n\nRNG rng(12345);\nFilter::Filter()\n{\n}\n\nFilter::~Filter()\n{\n}\n\n\/\/void showImages(Size& image_size, Mat& img0, Mat& img1, Mat& img2, Mat& img3, Mat& output){\n\/\/\tresize(img0, img0, image_size);\n\/\/\tresize(img1, img1, image_size);\n\/\/\tresize(img2, img2, image_size);\n\/\/\tresize(img3, img3, image_size);\n\/\/\n\/\/\tRect roi = Rect(0, 0, image_size.width, image_size.height);\n\/\/\tMat targetROI = output(roi);\n\/\/\timg0.copyTo(targetROI);\n\/\/\n\/\/\troi.x = image_size.width;\n\/\/\troi.y = 0;\n\/\/\ttargetROI = output(roi);\n\/\/\n\/\/\ttry{\n\/\/\t\tcvtColor(img1, img1, CV_GRAY2BGR);\n\/\/\t}\n\/\/\tcatch (exception& e){}\n\/\/\timg1.copyTo(targetROI);\n\/\/\n\/\/\troi.x = 0;\n\/\/\troi.y = image_size.height;\n\/\/\ttargetROI = output(roi);\n\/\/\n\/\/\ttry{\n\/\/\t\tcvtColor(img2, img2, CV_GRAY2BGR);\n\/\/\t}\n\/\/\tcatch (exception& e){}\n\/\/\timg2.copyTo(targetROI);\n\/\/\n\/\/\troi.x = image_size.width;\n\/\/\troi.y = image_size.height;\n\/\/\ttargetROI = output(roi);\n\/\/\n\/\/\ttry{\n\/\/\t\tcvtColor(img3, img3, CV_GRAY2BGR);\n\/\/\t}\n\/\/\tcatch (exception& e){}\n\/\/\timg3.copyTo(targetROI);\n\/\/\n\/\/\timshow(\"Sudoku Capture\", output);\n\/\/}\n\nvector<Point2f> Filter::extractPuzzle(Mat& inputImg, Mat& contour, Mat& contourImg, Mat& outputImg){\n\tRotatedRect obb = minAreaRect(contour);\n\tvector<Vec4i> lines;\n\tvector<Point2f> points(4, Point2f(0, 0));\n\n\tMat linesImg = contourImg.clone();\n\tdouble minLineSize = obb.size.width * .5;\n\n\t\/\/ detect the lines\n\tHoughLinesP(linesImg, lines, 1, CV_PI \/ 180, minLineSize, minLineSize, minLineSize * .5);\n\n\t\/\/for (size_t i = 0; i < lines.size(); i++)\n\t\/\/{\n\t\/\/\tVec4i l = lines[i];\n\t\/\/\t\/\/ draw the lines\n\t\/\/\tline(inputImg, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);\n\t\/\/}\n\n\tif (lines.size() >= 4){\n\t\tPoint2f box[4];\n\n\t\tSize img_size = Size(inputImg.size().height * 2, inputImg.size().height * 2);\n\n\t\t\/\/calculate four corners of quad\n\t\tPoint2f tl, tr, bl, br;\n\t\tPoint2f center = obb.center;\n\n\t\tfor (int i = 0; i < lines.size(); i++){\n\t\t\tPoint2f p1 = Point2f(lines[i][0], lines[i][1]);\n\t\t\tPoint2f p2 = Point2f(lines[i][2], lines[i][3]);\n\n\t\t\tPoint2f cp1 = p1 - center;\n\t\t\tPoint2f cp2 = p2 - center;\n\n\t\t\tif (cp1.x <= 0 && cp1.y < 0){\n\t\t\t\tif (cp1.dot(cp1) > tl.dot(tl)){\n\t\t\t\t\ttl = cp1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp1.x <= 0 && cp1.y >= 0){\n\t\t\t\tif (cp1.dot(cp1) > bl.dot(bl)){\n\t\t\t\t\tbl = cp1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp1.x > 0 && cp1.y < 0){\n\t\t\t\tif (cp1.dot(cp1) > tr.dot(tr)){\n\t\t\t\t\ttr = cp1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp1.x > 0 && cp1.y >= 0){\n\t\t\t\tif (cp1.dot(cp1) > br.dot(br)){\n\t\t\t\t\tbr = cp1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp2.x <= 0 && cp2.y < 0){\n\t\t\t\tif (cp2.dot(cp2) > tl.dot(tl)){\n\t\t\t\t\ttl = cp2;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp2.x <= 0 && cp2.y >= 0){\n\t\t\t\tif (cp2.dot(cp2) > bl.dot(bl)){\n\t\t\t\t\tbl = cp2;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp2.x > 0 && cp2.y < 0){\n\t\t\t\tif (cp2.dot(cp2) > tr.dot(tr)){\n\t\t\t\t\ttr = cp2;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp2.x > 0 && cp2.y >= 0){\n\t\t\t\tif (cp2.dot(cp2) > br.dot(br)){\n\t\t\t\t\tbr = cp2;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttl += center;\n\t\ttr += center;\n\t\tbr += center;\n\t\tbl += center;\n\n\t\tdouble offset = 0;\/\/ (img_size.width - img_size.height) \/ 2.0;\n\n\t\tpoints[0] = tl;\n\t\tpoints[1] = tr;\n\t\tpoints[2] = br;\n\t\tpoints[3] = bl;\n\n\t\t\/\/Quality check\n\t\tdouble h1 = bl.y - tl.y;\n\t\tdouble h2 = br.y - tr.y;\n\t\tdouble w1 = tr.x - tl.x;\n\t\tdouble w2 = br.x - bl.x;\n\t\tdouble warpLimit = .4; \/\/Allowable deviation in difference of lengths of opposite sides of quad\n\n\t\tif (abs(h1 - h2) > minLineSize * warpLimit){ return points; }\n\t\tif (abs(w1 - w2) > minLineSize* warpLimit){ return points; }\n\n\t\t\/\/for (int i = 0; i < 4; i++){\n\t\t\/\/\tif (points[i].x == 0 && points[i].y == 0){\n\t\t\/\/\t\treturn; \/\/One point was not assigned, throw away result\n\t\t\/\/\t}\n\n\t\t\/\/\tfor (int j = i + 1; j < 4; j++){\n\t\t\/\/\t\tif (points[i] == points[j]){\n\t\t\/\/\t\t\treturn; \/\/Points have collapsed, not a square, points must be distinct\n\t\t\/\/\t\t}\n\t\t\/\/\t}\n\t\t\/\/}\n\n\t\tbox[0] = Point2f(offset, 0);\n\t\tbox[1] = Point2f(img_size.height + offset, 0);\n\t\tbox[2] = Point2f(img_size.height + offset, img_size.height);\n\t\tbox[3] = Point2f(offset, img_size.height);\n\n\t\tif (addressof(inputImg) != addressof(outputImg)){\n\t\t\t\/\/outputImg = Mat(img_size, inputImg.type());\n\t\t\tresize(inputImg.clone(), outputImg, img_size);\n\t\t\tMat lambda = getPerspectiveTransform(&points[0], box);\n\t\t\twarpPerspective(inputImg, outputImg, lambda, outputImg.size());\n\n\t\t\tMat cropped = outputImg(Rect(box[0], box[2])).clone();\n\t\t\toutputImg = Mat::zeros(outputImg.size(), outputImg.type());\n\t\t\tMat cropROI = outputImg(Rect(box[0], box[2]));\n\t\t\tcropped.copyTo(cropROI);\n\t\t}\n\t}\n\treturn points;\n}\n\nvector<Point2f> Filter::extractPuzzle(GpuMat& inputImg, Mat& contour, Mat& contourImg, GpuMat& outputImg){\n\tRotatedRect obb = minAreaRect(contour);\n\tvector<Vec4i> lines;\n\tvector<Point2f> points(4, Point2f(0, 0));\n\n\tGpuMat d_lines;\n\tGpuMat linesImg = GpuMat(contourImg);\n\tdouble minLineSize = obb.size.width * .5;\n\n\t\/\/ detect the lines\n\tHoughLinesBuf houghBuf;\n\tgpu::HoughLinesP(linesImg, d_lines, houghBuf, 1, CV_PI \/ 180.0, minLineSize, minLineSize * .5);\n\n\t\/\/for (size_t i = 0; i < lines.size(); i++)\n\t\/\/{\n\t\/\/\tVec4i l = lines[i];\n\t\/\/\t\/\/ draw the lines\n\t\/\/\tline(inputImg, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);\n\t\/\/}\n\n\tvector<Vec4i> lines_gpu;\n\tif (!d_lines.empty())\n\t{\n\t\tlines.resize(d_lines.cols);\n\t\tMat h_lines(1, d_lines.cols, CV_32SC4, &lines[0]);\n\t\td_lines.download(h_lines);\n\t}\n\n\tif (lines.size() >= 4){\n\t\tPoint2f box[4];\n\n\t\tSize img_size = Size(inputImg.size().height * 2, inputImg.size().height * 2);\n\n\t\t\/\/calculate four corners of quad\n\t\tPoint2f tl, tr, bl, br;\n\t\tPoint2f center = obb.center;\n\n\t\tfor (int i = 0; i < lines.size(); i++){\n\t\t\tPoint2f p1 = Point2f(lines[i][0], lines[i][1]);\n\t\t\tPoint2f p2 = Point2f(lines[i][2], lines[i][3]);\n\n\t\t\tPoint2f cp1 = p1 - center;\n\t\t\tPoint2f cp2 = p2 - center;\n\n\t\t\tif (cp1.x <= 0 && cp1.y < 0){\n\t\t\t\tif (cp1.dot(cp1) > tl.dot(tl)){\n\t\t\t\t\ttl = cp1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp1.x <= 0 && cp1.y >= 0){\n\t\t\t\tif (cp1.dot(cp1) > bl.dot(bl)){\n\t\t\t\t\tbl = cp1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp1.x > 0 && cp1.y < 0){\n\t\t\t\tif (cp1.dot(cp1) > tr.dot(tr)){\n\t\t\t\t\ttr = cp1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp1.x > 0 && cp1.y >= 0){\n\t\t\t\tif (cp1.dot(cp1) > br.dot(br)){\n\t\t\t\t\tbr = cp1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp2.x <= 0 && cp2.y < 0){\n\t\t\t\tif (cp2.dot(cp2) > tl.dot(tl)){\n\t\t\t\t\ttl = cp2;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp2.x <= 0 && cp2.y >= 0){\n\t\t\t\tif (cp2.dot(cp2) > bl.dot(bl)){\n\t\t\t\t\tbl = cp2;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp2.x > 0 && cp2.y < 0){\n\t\t\t\tif (cp2.dot(cp2) > tr.dot(tr)){\n\t\t\t\t\ttr = cp2;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cp2.x > 0 && cp2.y >= 0){\n\t\t\t\tif (cp2.dot(cp2) > br.dot(br)){\n\t\t\t\t\tbr = cp2;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttl += center;\n\t\ttr += center;\n\t\tbr += center;\n\t\tbl += center;\n\n\t\tdouble offset = 0;\/\/ (img_size.width - img_size.height) \/ 2.0;\n\n\t\tpoints[0] = tl;\n\t\tpoints[1] = tr;\n\t\tpoints[2] = br;\n\t\tpoints[3] = bl;\n\n\t\t\/\/Quality check\n\t\tdouble h1 = bl.y - tl.y;\n\t\tdouble h2 = br.y - tr.y;\n\t\tdouble w1 = tr.x - tl.x;\n\t\tdouble w2 = br.x - bl.x;\n\t\tdouble warpLimit = .4; \/\/Allowable deviation in difference of lengths of opposite sides of quad\n\n\t\tif (abs(h1 - h2) > minLineSize * warpLimit){ return points; }\n\t\tif (abs(w1 - w2) > minLineSize* warpLimit){ return points; }\n\n\t\t\/\/for (int i = 0; i < 4; i++){\n\t\t\/\/\tif (points[i].x == 0 && points[i].y == 0){\n\t\t\/\/\t\treturn; \/\/One point was not assigned, throw away result\n\t\t\/\/\t}\n\n\t\t\/\/\tfor (int j = i + 1; j < 4; j++){\n\t\t\/\/\t\tif (points[i] == points[j]){\n\t\t\/\/\t\t\treturn; \/\/Points have collapsed, not a square, points must be distinct\n\t\t\/\/\t\t}\n\t\t\/\/\t}\n\t\t\/\/}\n\n\t\tbox[0] = Point2f(offset, 0);\n\t\tbox[1] = Point2f(img_size.height + offset, 0);\n\t\tbox[2] = Point2f(img_size.height + offset, img_size.height);\n\t\tbox[3] = Point2f(offset, img_size.height);\n\n\t\tif (addressof(inputImg) != addressof(outputImg)){\n\t\t\t\/\/outputImg = Mat(img_size, inputImg.type());\n\t\t\tresize(inputImg.clone(), outputImg, img_size);\n\t\t\tMat lambda = getPerspectiveTransform(&points[0], box);\n\t\t\tgpu::warpPerspective(inputImg, outputImg, lambda, outputImg.size());\n\n\t\t\tGpuMat cropped = outputImg(Rect(box[0], box[2])).clone();\n\t\t\toutputImg = GpuMat(Mat::zeros(outputImg.size(), outputImg.type()));\n\t\t\tGpuMat cropROI = outputImg(Rect(box[0], box[2]));\n\t\t\tcropped.copyTo(cropROI);\n\t\t}\n\t}\n\treturn points;\n}\n\nvector<vector<int>> Filter::extractDigits(Mat& frame){\n\tvector<vector<int>> puzzle = vector<vector<int>>(PUZZLE_SIZE, vector<int>(PUZZLE_SIZE, 0));\n\n\tif (frame.size().area() > 0){\n\n\t\t\/\/Filter image\n\t\tMat workingImage = Mat(frame.size(), CV_8UC1);\n\t\tint w = workingImage.size().width;\n\t\tint h = workingImage.size().height;\n\n\t\tdouble offset = 0.37;\n\t\tdouble size = 1.0 - 2 * offset;\n\n\t\tint blockSize = w \/ PUZZLE_SIZE;\n\n\t\tif (blockSize % 2 == 0) blockSize++;\n\n\t\tcvtColor(frame, workingImage, CV_RGB2GRAY);\n\t\tcv::adaptiveThreshold(workingImage, workingImage, 127, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV, blockSize, C);\n\n\t\t\/\/Find digits\n\t\tMat squares[PUZZLE_SIZE][PUZZLE_SIZE];\n\n\t\tfor (int i = 0; i < PUZZLE_SIZE; i++){\n\t\t\tfor (int j = 0; j < PUZZLE_SIZE; j++){\n\t\t\t\tsquares[i][j] = workingImage(Rect(i*w \/ PUZZLE_SIZE, j*h \/ PUZZLE_SIZE, w \/ PUZZLE_SIZE, h \/ PUZZLE_SIZE));\n\n\t\t\t\tMat square = squares[i][j];\n\t\t\t\tint w_s = square.size().width;\n\t\t\t\tint h_s = square.size().height;\n\n\t\t\t\tRect fillRegion = Rect(i*w_s + offset*w \/ PUZZLE_SIZE, j*h_s + offset*h \/ PUZZLE_SIZE, size*w \/ PUZZLE_SIZE, size*h \/ PUZZLE_SIZE);\n\t\t\t\tsquares[i][j] = floodFillRegion(workingImage, fillRegion);\n\n\t\t\t\tvector<Point2i> points(4, Point2i(0, 0));\n\t\t\t\tpoints[0] = Point2i(fillRegion.x, fillRegion.y);\n\t\t\t\tpoints[1] = Point2i(fillRegion.x + fillRegion.width, fillRegion.y);\n\t\t\t\tpoints[2] = Point2i(fillRegion.x + fillRegion.width, fillRegion.y + fillRegion.height);\n\t\t\t\tpoints[3] = Point2i(fillRegion.x, fillRegion.y + fillRegion.height);\n\n\t\t\t\tif (fillRegion.size().width != (int)(size*w \/ PUZZLE_SIZE) && fillRegion.size().height != (int)(size*h \/ PUZZLE_SIZE)){\n\t\t\t\t\tpuzzle[i][j] = parser.recognize(squares[i][j]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn puzzle;\n}\n\nvector<vector<int>> Filter::extractDigits(GpuMat& frame){\n\tvector<vector<int>> puzzle = vector<vector<int>>(PUZZLE_SIZE, vector<int>(PUZZLE_SIZE, 0));\n\n\tif (frame.size().area() > 0){\n\n\t\t\/\/Filter image\n\t\tGpuMat workingImage = GpuMat(Mat(frame.size(), CV_8UC1));\n\t\tint w = workingImage.size().width;\n\t\tint h = workingImage.size().height;\n\n\t\tdouble offset = 0.37;\n\t\tdouble size = 1.0 - 2 * offset;\n\n\t\tint blockSize = w \/ PUZZLE_SIZE;\n\n\t\tif (blockSize % 2 == 0) blockSize++;\n\n\t\tcvtColor(frame, workingImage, CV_RGB2GRAY);\n\t\tadaptiveThreshold(workingImage, workingImage, 127, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV, blockSize, C);\n\n\t\t\/\/Find digits\n\t\tGpuMat squares[PUZZLE_SIZE][PUZZLE_SIZE];\n\n\t\tfor (int i = 0; i < PUZZLE_SIZE; i++){\n\t\t\tfor (int j = 0; j < PUZZLE_SIZE; j++){\n\t\t\t\tsquares[i][j] = workingImage(Rect(i*w \/ PUZZLE_SIZE, j*h \/ PUZZLE_SIZE, w \/ PUZZLE_SIZE, h \/ PUZZLE_SIZE));\n\n\t\t\t\tGpuMat square = squares[i][j];\n\t\t\t\tint w_s = square.size().width;\n\t\t\t\tint h_s = square.size().height;\n\n\t\t\t\tRect fillRegion = Rect(i*w_s + offset*w \/ PUZZLE_SIZE, j*h_s + offset*h \/ PUZZLE_SIZE, size*w \/ PUZZLE_SIZE, size*h \/ PUZZLE_SIZE);\n\t\t\t\tsquares[i][j] = floodFillRegion(workingImage, fillRegion);\n\n\t\t\t\tvector<Point2i> points(4, Point2i(0, 0));\n\t\t\t\tpoints[0] = Point2i(fillRegion.x, fillRegion.y);\n\t\t\t\tpoints[1] = Point2i(fillRegion.x + fillRegion.width, fillRegion.y);\n\t\t\t\tpoints[2] = Point2i(fillRegion.x + fillRegion.width, fillRegion.y + fillRegion.height);\n\t\t\t\tpoints[3] = Point2i(fillRegion.x, fillRegion.y + fillRegion.height);\n\n\t\t\t\tif (fillRegion.size().width != (int)(size*w \/ PUZZLE_SIZE) && fillRegion.size().height != (int)(size*h \/ PUZZLE_SIZE)){\n\t\t\t\t\tpuzzle[i][j] = parser.recognize(squares[i][j]);\n\t\t\t\t\t\/\/stringstream ss;\n\t\t\t\t\t\/\/ss << puzzle[i][j];\n\t\t\t\t\t\/\/putText(frame, ss.str(), Point(fillRegion.x, fillRegion.y), FONT_HERSHEY_PLAIN, 2, Scalar(0, 0, 255));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn puzzle;\n}\n\nMat Filter::floodFillRegion(Mat& inputImg, Rect& region, int value){\n\tRect size = region;\n\tbool found = false;\n\tMat ffImg = inputImg;\n\n\tfor (int i = region.x; i < region.x + region.width; i++){\n\t\tfor (int j = region.y; j < region.y + region.height; j++){\n\t\t\tuchar val = ffImg.at<uchar>(j, i);\n\t\t\tif (val > 0){\n\t\t\t\tfill(ffImg, Point(i, j), value, size);\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (found) break;\n\t}\n\n\tMat floodImage = inputImg(size);\n\tregion = size;\n\treturn floodImage;\n}\n\nGpuMat Filter::floodFillRegion(GpuMat& inputImg, Rect& region, int value){\n\tRect size = region;\n\tbool found = false;\n\tMat ffImg(inputImg);\n\n\tfor (int i = region.x; i < region.x + region.width; i++){\n\t\tfor (int j = region.y; j < region.y + region.height; j++){\n\t\t\tuchar val = ffImg.at<uchar>(j, i);\n\t\t\tif (val > 0){\n\t\t\t\tfill(ffImg, Point(i, j), value, size);\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (found) break;\n\t}\n\n\tGpuMat floodImage(inputImg(size));\n\tregion = size;\n\treturn floodImage;\n}\n\nvoid Filter::fill(Mat& img, Point2i startPt, int value, Rect& size){\n\tint minX = img.size().width;\n\tint minY = img.size().height;\n\tint maxX = 0;\n\tint maxY = 0;\n\n\tMat visited = Mat::zeros(img.size(), CV_8UC1);\n\n\tuchar val = img.at<uchar>(startPt);\n\n\tqueue<Point2i> pixelQueue;\n\tpixelQueue.push(startPt);\n\n\twhile (!pixelQueue.empty()) {\n\t\tPoint2i pt = pixelQueue.front();\n\t\tpixelQueue.pop();\n\n\t\tif (pt.x >= 0 && pt.x < img.size().width && pt.y >= 0 && pt.y < img.size().height){\n\n\t\t\tuchar visPtr = visited.at<uchar>(pt);\n\t\t\tif (visPtr == 0){\n\n\t\t\t\tvisited.at<uchar>(pt) = 1;\n\t\t\t\tuchar px = img.at<uchar>(pt);\n\n\t\t\t\tif (px == val){\n\t\t\t\t\timg.at<uchar>(pt) = value;\n\t\t\t\t\tif (pt.x < minX){\n\t\t\t\t\t\tminX = pt.x;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (pt.x > maxX){\n\t\t\t\t\t\tmaxX = pt.x;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (pt.y < minY){\n\t\t\t\t\t\tminY = pt.y;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (pt.y > maxY){\n\t\t\t\t\t\tmaxY = pt.y;\n\t\t\t\t\t}\n\n\t\t\t\t\tpixelQueue.push(Point2i(pt.x - 1, pt.y));\n\t\t\t\t\tpixelQueue.push(Point2i(pt.x + 1, pt.y));\n\t\t\t\t\tpixelQueue.push(Point2i(pt.x, pt.y - 1));\n\t\t\t\t\tpixelQueue.push(Point2i(pt.x, pt.y + 1));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tsize = Rect(minX, minY, maxX - minX + 1, maxY - minY + 1);\n}\n\nvoid Filter::fill(GpuMat& frame, Point2i startPt, int value, Rect& size){\n\tMat img(frame);\n\tint minX = img.size().width;\n\tint minY = img.size().height;\n\tint maxX = 0;\n\tint maxY = 0;\n\n\tMat visited = Mat::zeros(img.size(), CV_8UC1);\n\tuchar val = img.at<uchar>(startPt);\n\n\tqueue<Point2i> pixelQueue;\n\tpixelQueue.push(startPt);\n\n\twhile (!pixelQueue.empty()) {\n\t\tPoint2i pt = pixelQueue.front();\n\t\tpixelQueue.pop();\n\n\t\tif (pt.x >= 0 && pt.x < img.size().width && pt.y >= 0 && pt.y < img.size().height){\n\n\t\t\tuchar visPtr = visited.at<uchar>(pt);\n\t\t\tif (visPtr == 0){\n\n\t\t\t\tvisited.at<uchar>(pt) = 1;\n\t\t\t\tuchar px = img.at<uchar>(pt);\n\n\t\t\t\tif (px == val){\n\t\t\t\t\timg.at<uchar>(pt) = value;\n\t\t\t\t\tif (pt.x < minX){\n\t\t\t\t\t\tminX = pt.x;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (pt.x > maxX){\n\t\t\t\t\t\tmaxX = pt.x;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (pt.y < minY){\n\t\t\t\t\t\tminY = pt.y;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (pt.y > maxY){\n\t\t\t\t\t\tmaxY = pt.y;\n\t\t\t\t\t}\n\n\t\t\t\t\tpixelQueue.push(Point2i(pt.x - 1, pt.y));\n\t\t\t\t\tpixelQueue.push(Point2i(pt.x + 1, pt.y));\n\t\t\t\t\tpixelQueue.push(Point2i(pt.x, pt.y - 1));\n\t\t\t\t\tpixelQueue.push(Point2i(pt.x, pt.y + 1));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tsize = Rect(minX, minY, maxX - minX + 1, maxY - minY + 1);\n}\n\nvector<vector<int>> Filter::filterForPuzzle(Mat& input_frame, Mat& debug_frame, int frame_skip){\n\tstatic Mat drawing;\n\tstatic Mat frame_puzzle;\n\tstatic int frame_index = 0;\n\tstatic vector<Point2f> puzzlePoints = vector<Point2f>(4, Point2f(0, 0));\n\n\tMat frame = input_frame.clone();\n\tMat frame_filtered = frame.clone();\n\tSize image_size = frame.size();\n\tvector<vector<int>> puzzle;\n\n\tif (frame_index % frame_skip == 0) {\n\t\tcvtColor(frame, frame, CV_BGR2GRAY);\n\t\tGaussianBlur(frame, frame, Size(blurKernelSize, blurKernelSize), (double)sigma \/ 100.0, (double)sigma \/ 100.0);\n\t\t\/\/adaptiveBilateralFilter(frame_gray, frame_blur, Size(blurKernelSize, blurKernelSize), sigma \/ 100.0);\n\t\tcv::adaptiveThreshold(frame, frame, threshMaxVal, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV, thresholdSize, C);\n\n\t\tmorphologyEx(frame, frame, MORPH_OPEN, cross, Point(-1, -1), 1);\n\t\tmorphologyEx(frame, frame, MORPH_DILATE, cross, Point(-1, -1), 3);\n\t\tmorphologyEx(frame, frame_filtered, MORPH_ERODE, cross, Point(-1, -1), 1);\n\t\t\/\/morphologyEx(frame_threshold, frame_threshold, MORPH_DILATE, cross, Point(-1, -1), 1);\n\n\t\tCanny(frame_filtered, frame_filtered, lowThreshold, highThreshold);\n\t\tdebug_frame = frame_filtered;\n\t\t\/\/HoughCircles(frame_hough, circles, CV_HOUGH_GRADIENT, 4, 10, highThreshold, 100, 1, 20);\n\t\tdrawing = Mat::zeros(image_size, CV_8UC1);\n\n\t\tvector<vector<Point> > contours;\n\t\tvector<Vec4i> hierarchy;\n\n\t\t\/\/\/ Find contours\n\t\tfindContours(frame, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);\n\t\tint biggestContourId = 0;\n\t\tint mostChildren = 0;\n\n\t\t\/\/Find the contour with the most direct child contours\n\t\tvector<int> childCounts = vector<int>(hierarchy.size());\n\n\t\tfor (int i = 0; i < hierarchy.size(); i++){\n\t\t\tif (hierarchy[i][3] >= 0){\n\t\t\t\tchildCounts[hierarchy[i][3]]++;\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i < contours.size(); i++){\n\t\t\tif (childCounts[i] > mostChildren){\n\t\t\t\tbiggestContourId = i;\n\t\t\t\tmostChildren = childCounts[i];\n\t\t\t}\n\t\t}\n\n\t\tif (contours.size() > 0) {\n\t\t\t\/\/drawing = Mat::zeros(image_size, CV_8UC3);\n\t\t\t\/\/for (int i = 0; i < contours.size(); i++){\n\t\t\tScalar color = Scalar(255); \/\/ : Scalar(0, (100 * childCounts[i]) + 10, 0); \/\/ Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));\n\t\t\tdrawContours(drawing, contours, biggestContourId, color, 2, 8, hierarchy, 0, Point());\n\t\t\t\/\/}\n\n\t\t\tMat lastDetectedContour = Mat(contours[biggestContourId]).clone();\n\t\t\tpuzzlePoints = extractPuzzle(input_frame, lastDetectedContour, drawing, frame_puzzle);\n\t\t\tpuzzle = extractDigits(frame_puzzle);\n\n\t\t\tdebug_frame = drawing;\n\t\t\tdouble h = debug_frame.size().height;\n\t\t\tdouble w = debug_frame.size().width;\n\t\t\tdouble divisions = PUZZLE_SIZE;\n\t\t\tdouble step = w \/ divisions;\n\n\t\t\tfor (int i = 0; i < divisions - 1; i++){\n\t\t\t\tline(debug_frame, Point2f((i + 1)*step, 0), Point2f((i + 1)*step, h), Scalar(0, 0, 255), (i + 1) % 10 != 0 ? 1 : 3);\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < divisions - 1; i++){\n\t\t\t\tline(debug_frame, Point2f(0, (i + 1)*step), Point2f(w, (i + 1)*step), Scalar(0, 0, 255), (i + 1) % 10 != 0 ? 1 : 3);\n\t\t\t}\n\t\t}\n\n\n\t\tfor (int j = 0; j < 4; j++){\n\t\t\tline(input_frame, puzzlePoints[j], puzzlePoints[(j + 1) % 4], Scalar(0, 255, 0));\n\t\t}\n\t}\n\n\tframe_index++;\n\tdebug_frame = frame_puzzle;\n\treturn puzzle;\n}\n\nvector<vector<int>> Filter::filterForPuzzle(GpuMat& input_frame, GpuMat& debug_frame, int frame_skip){\n\tstatic Mat drawing;\n\tGpuMat d_frame_puzzle;\n\tstatic int frame_index = 0;\n\tstatic vector<Point2f> puzzlePoints = vector<Point2f>(4, Point2f(0, 0));\n\n\tGpuMat d_frame = input_frame.clone();\n\tGpuMat d_frame_filtered = d_frame.clone();\n\tSize image_size = d_frame.size();\n\tvector<vector<int>> puzzle;\n\n\tif (frame_index % frame_skip == 0) {\n\t\tcvtColor(d_frame.clone(), d_frame, CV_BGR2GRAY);\n\t\tGaussianBlur(d_frame.clone(), d_frame, Size(blurKernelSize, blurKernelSize), (double)sigma \/ 100.0, (double)sigma \/ 100.0);\n\t\tadaptiveThreshold(d_frame.clone(), d_frame, threshMaxVal, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV, thresholdSize, C);\n\n\t\tmorphologyEx(d_frame.clone(), d_frame, MORPH_OPEN, cross, Point(-1, -1), 1);\n\t\tmorphologyEx(d_frame.clone(), d_frame, MORPH_DILATE, cross, Point(-1, -1), 3);\n\t\tmorphologyEx(d_frame, d_frame_filtered, MORPH_ERODE, cross, Point(-1, -1), 1);\n\n\t\tCanny(d_frame_filtered.clone(), d_frame_filtered, lowThreshold, highThreshold);\n\t\tdrawing = Mat::zeros(image_size, CV_8UC1);\n\n\t\tvector<vector<Point> > contours;\n\t\tvector<Vec4i> hierarchy;\n\n\t\tMat frame = Mat(d_frame);\n\n\t\t\/\/\/ Find contours\n\t\tfindContours(frame, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);\n\t\tint biggestContourId = 0;\n\t\tint mostChildren = 0;\n\n\t\t\/\/Find the contour with the most direct child contours\n\t\tvector<int> childCounts = vector<int>(hierarchy.size());\n\n\t\tfor (int i = 0; i < hierarchy.size(); i++){\n\t\t\tif (hierarchy[i][3] >= 0){\n\t\t\t\tchildCounts[hierarchy[i][3]]++;\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i < contours.size(); i++){\n\t\t\tif (childCounts[i] > mostChildren){\n\t\t\t\tbiggestContourId = i;\n\t\t\t\tmostChildren = childCounts[i];\n\t\t\t}\n\t\t}\n\n\t\tif (contours.size() > 0) {\n\t\t\t\/\/drawing = Mat::zeros(image_size, CV_8UC3);\n\t\t\tScalar color = Scalar(255);\n\t\t\tdrawContours(drawing, contours, biggestContourId, color, 2, 8, hierarchy, 0, Point());\n\n\t\t\tMat lastDetectedContour = Mat(contours[biggestContourId]).clone();\n\t\t\tpuzzlePoints = extractPuzzle(input_frame, lastDetectedContour, drawing, d_frame_puzzle);\n\t\t\tpuzzle = extractDigits(d_frame_puzzle);\n\t\t}\n\t}\n\n\tframe_index++;\n\tdebug_frame = d_frame_puzzle;\n\treturn puzzle;\n}\n\nvoid Filter::adaptiveThreshold(GpuMat& src, GpuMat& dst, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C){\n\tint horz = (blockSize - 1) \/ 2;\n\tint vert = (blockSize - 1) \/ 2;\n\n\tGpuMat img, expanded;\n\tsrc.assignTo(img, CV_8UC1);\n\tcopyMakeBorder(img, expanded, horz, horz, vert, vert, BORDER_CONSTANT, 0);\n\n\t\/*Mat kernel = Mat::ones(Size(blockSize, blockSize), CV_32FC1);\n\tkernel = (1.0 \/ (blockSize*blockSize)) * kernel;\n\tconvolve(expanded, GpuMat(kernel), thresholdMat);*\/\n\tGpuMat thresholdMat = GpuMat(img.size(), img.type());\n\tboxFilter(expanded, thresholdMat, -1, Size(blockSize, blockSize));\n\n\tcompare(img, thresholdMat(Rect(Point(horz, vert), src.size())), dst, CMP_LT);\n\tmultiply(dst.clone(), maxValue, dst);\n\tsubtract(dst.clone(), C, dst);\n}","avg_line_length":27.5697823303,"max_line_length":152,"alphanum_fraction":0.6234441761,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3749,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSL-1.0"],"max_stars_count":521.0,"content":"\/\/ Copyright (c) Glyn Matthews 2012-2016.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <locale>\n#include \"network\/uri\/uri_builder.hpp\"\n#include \"detail\/uri_normalize.hpp\"\n#include \"detail\/uri_parse_authority.hpp\"\n#include \"detail\/algorithm.hpp\"\n\nnamespace network {\nuri_builder::uri_builder(const network::uri &base_uri) {\n  if (base_uri.has_scheme()) {\n    set_scheme(base_uri.scheme().to_string());\n  }\n\n  if (base_uri.has_user_info()) {\n    set_user_info(base_uri.user_info().to_string());\n  }\n\n  if (base_uri.has_host()) {\n    set_host(base_uri.host().to_string());\n  }\n\n  if (base_uri.has_port()) {\n    set_port(base_uri.port().to_string());\n  }\n\n  if (base_uri.has_path()) {\n    set_path(base_uri.path().to_string());\n  }\n\n  if (base_uri.has_query()) {\n    append_query(base_uri.query().to_string());\n  }\n\n  if (base_uri.has_fragment()) {\n    set_fragment(base_uri.fragment().to_string());\n  }\n}\n\nuri_builder::~uri_builder() noexcept {}\n\nnetwork::uri uri_builder::uri() const { return network::uri(*this); }\n\nvoid uri_builder::set_scheme(string_type scheme) {\n  \/\/ validate scheme is valid and normalize\n  scheme_ = scheme;\n  detail::transform(*scheme_, std::begin(*scheme_),\n                    [] (char ch) { return std::tolower(ch, std::locale()); });\n}\n\nvoid uri_builder::set_user_info(string_type user_info) {\n  user_info_ = string_type();\n  network::uri::encode_user_info(std::begin(user_info), std::end(user_info),\n                                 std::back_inserter(*user_info_));\n}\n\nuri_builder &uri_builder::clear_user_info() {\n  user_info_ = network::nullopt;\n  return *this;\n}\n\nvoid uri_builder::set_host(string_type host) {\n  host_ = string_type();\n  network::uri::encode_host(std::begin(host), std::end(host),\n                            std::back_inserter(*host_));\n  detail::transform(*host_, std::begin(*host_),\n                    [](char ch) { return std::tolower(ch, std::locale()); });\n}\n\nvoid uri_builder::set_port(string_type port) {\n  port_ = string_type();\n  network::uri::encode_port(std::begin(port), std::end(port),\n                            std::back_inserter(*port_));\n}\n\nuri_builder &uri_builder::clear_port() {\n  port_ = network::nullopt;\n  return *this;\n}\n\nvoid uri_builder::set_authority(string_type authority) {\n  optional<detail::uri_part> user_info, host, port;\n  uri::string_view view(authority);\n  uri::const_iterator it = std::begin(view), last = std::end(view);\n  detail::parse_authority(it, last, user_info, host, port);\n\n  if (user_info) {\n    set_user_info(user_info->to_string());\n  }\n\n  if (host) {\n    set_host(host->to_string());\n  }\n\n  if (port) {\n    set_port(port->to_string());\n  }\n}\n\nvoid uri_builder::set_path(string_type path) {\n  path_ = string_type();\n  network::uri::encode_path(std::begin(path), std::end(path),\n                            std::back_inserter(*path_));\n}\n\nuri_builder &uri_builder::clear_path() {\n  path_ = network::nullopt;\n  return *this;\n}\n\nvoid uri_builder::append_query(string_type query) {\n  if (!query_) {\n    query_ = string_type();\n  }\n  else {\n    query_->append(\"&\");\n  }\n  network::uri::encode_query(std::begin(query), std::end(query),\n                             std::back_inserter(*query_));\n}\n\nuri_builder &uri_builder::clear_query() {\n  query_ = network::nullopt;\n  return *this;\n}\n\nvoid uri_builder::set_fragment(string_type fragment) {\n  fragment_ = string_type();\n  network::uri::encode_fragment(std::begin(fragment), std::end(fragment),\n                                std::back_inserter(*fragment_));\n}\n\nuri_builder &uri_builder::clear_fragment() {\n  fragment_ = network::nullopt;\n  return *this;\n}\n}  \/\/ namespace network\n","avg_line_length":26.5886524823,"max_line_length":78,"alphanum_fraction":0.6556415044,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3176,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":3.0,"content":"\n\/\/  _  _           _                   _  _      _  _\n\/\/ | || |   _ __  \/ | _ __  _   _   __| || |__  | || |\n\/\/ | || |_ | '_ \\ | || '__|| | | | \/ _` || '_ \\ | || |_\n\/\/ |__   _|| | | || || |   | |_| || (_| || | | ||__   _|\n\/\/    |_|  |_| |_||_||_|    \\__,_| \\__,_||_| |_|   |_|\n\n#include \"bits\/stdc++.h\"\nusing namespace std;\ntypedef long long ll;\ntypedef vector<long long> vl;\n#define pll pair<ll, ll>\n#define vpl vector<pll>\n#define vb vector<bool>\n#define PB push_back\n#define MP make_pair\n#define endl \"\\n\"\n#define forn(i, e) for (ll i = 0; i < e; i++)\n#define forsn(i, s, e) for (ll i = s; i < e; i++)\n#define rforn(i, e) for (ll i = e; i >= 0; i--)\n#define rforsn(i, s, e) for (ll i = s; i >= e; i--)\n#define vasort(v) sort(v.begin(), v.end())\n#define vdsort(v) sort(v.begin(), v.end(), greater<ll>())\n#define F first\n#define S second\n#define out1(x1) cout << x1 << endl\n#define out2(x1, x2) cout << x1 << \" \" << x2 << endl\n#define out3(x1, x2, x3) cout << x1 << \" \" << x2 << \" \" << x3 << endl\n#define out4(x1, x2, x3, x4) cout << x1 << \" \" << x2 << \" \" << x3 << \" \" << x4 << endl\n#define out5(x1, x2, x3, x4, x5) cout << x1 << \" \" << x2 << \" \" << x3 << \" \" << x4 << \" \" << x5 << endl\n#define out6(x1, x2, x3, x4, x5, x6) cout << x1 << \" \" << x2 << \" \" << x3 << \" \" << x4 << \" \" << x5 << \" \" << x6 << endl\n\n#define in1(x1) cin >> x1\n#define in2(x1, x2) cin >> x1 >> x2\n#define in3(x1, x2, x3) cin >> x1 >> x2 >> x3\n#define in4(x1, x2, x3, x4) cin >> x1 >> x2 >> x3 >> x4\n#define in5(x1, x2, x3, x4, x5) cin >> x1 >> x2 >> x3 >> x4 >> x5\n#define in6(x1, x2, x3, x4, x5, x6) cin >> x1 >> x2 >> x3 >> x4 >> x5 >> x6\n\n#define mz(a) memset(a, 0, sizeof(a))\n#define arrin(a, n) forn(i, n) cin >> a[i];\n#define arrout(a, n)                   \\\n   forn(i, n) { cout << a[i] << \" \"; } \\\n   cout << endl;\n#define arr2out(a, n, m)                     \\\n   forn(i, n)                                \\\n   {                                         \\\n      forn(j, m) { cout << a[i][j] << \" \"; } \\\n      cout << endl;                          \\\n   }\n#define TYPEMAX(type) std::numeric_limits<type>::max()\n#define TYPEMIN(type) std::numeric_limits<type>::min()\n\n#define zoom                         \\\n   ios_base::sync_with_stdio(false); \\\n   cin.tie(NULL);                    \\\n   cout.tie(NULL)\n#pragma GCC optimize(\"Ofast\")\n#pragma GCC target(\"avx,avx2,fma\")\n#pragma GCC optimization(\"unroll-loops\")\n\nint main()\n{\n#ifndef ONLINE_JUDGE\n   \/\/ for getting input from input.txt\n   freopen(\"..\/testcases\/input.in\", \"r\", stdin);\n   \/\/ for writing output to output.txt\n   freopen(\"..\/testcases\/output.in\", \"w\", stdout);\n#endif\n   zoom;\n   ll t;\n   cin >> t;\n   while (t--)\n   {\n      ll a, b, x, y, p, q, n, m = 0, k, sum = 0, ans = 0, res = 0;\n      string s, r;\n      \/\/ cin >> n;\n      \/\/ cin >> m;\n      cin >> s;\n      for(int i=0;i<s.length();i++){\n         if(i<3){\n            sum+=s[i]-'0';\n         }\n         else{\n            ans+=s[i]-'0';\n         }\n      }\n      if(ans==sum){\n         cout<<\"YES\"<<endl;\n      }\n      else{\n         cout<<\"NO\"<<endl;\n      }\n   }\n\n   return 0;\n}\n\/\/ vector<vector<int>> vec( n , vector<int> (m, 0));\n\/\/ think before you code\n\/\/ special cases\n","avg_line_length":31.4455445545,"max_line_length":120,"alphanum_fraction":0.4521410579,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":35620,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/*\r\n * Qt4 bitcoin GUI.\r\n *\r\n * W.J. van der Laan 2011-2012\r\n * The Bitcoin Developers 2011-2012\r\n * The Litecoin Developers 201-2013\r\n *\/\r\n#include \"bitcoingui.h\"\r\n#include \"transactiontablemodel.h\"\r\n#include \"addressbookpage.h\"\r\n#include \"sendcoinsdialog.h\"\r\n#include \"signverifymessagedialog.h\"\r\n#include \"optionsdialog.h\"\r\n#include \"aboutdialog.h\"\r\n#include \"clientmodel.h\"\r\n#include \"walletmodel.h\"\r\n#include \"editaddressdialog.h\"\r\n#include \"optionsmodel.h\"\r\n#include \"transactiondescdialog.h\"\r\n#include \"addresstablemodel.h\"\r\n#include \"transactionview.h\"\r\n#include \"overviewpage.h\"\r\n#include \"miningpage.h\"\r\n#include \"bitcoinunits.h\"\r\n#include \"guiconstants.h\"\r\n#include \"askpassphrasedialog.h\"\r\n#include \"notificator.h\"\r\n#include \"guiutil.h\"\r\n#include \"rpcconsole.h\"\r\n\r\n#ifdef Q_WS_MAC\r\n#include \"macdockiconhandler.h\"\r\n#endif\r\n\r\n#include <QApplication>\r\n#include <QMainWindow>\r\n#include <QMenuBar>\r\n#include <QMenu>\r\n#include <QIcon>\r\n#include <QTabWidget>\r\n#include <QVBoxLayout>\r\n#include <QToolBar>\r\n#include <QStatusBar>\r\n#include <QLabel>\r\n#include <QLineEdit>\r\n#include <QPushButton>\r\n#include <QLocale>\r\n#include <QMessageBox>\r\n#include <QProgressBar>\r\n#include <QStackedWidget>\r\n#include <QDateTime>\r\n#include <QMovie>\r\n#include <QFileDialog>\r\n#include <QDesktopServices>\r\n#include <QTimer>\r\n#include <QDragEnterEvent>\r\n#include <QUrl>\r\n\r\n#include <iostream>\r\n\r\nBitcoinGUI::BitcoinGUI(QWidget *parent):\r\n    QMainWindow(parent),\r\n    clientModel(0),\r\n    walletModel(0),\r\n    encryptWalletAction(0),\r\n    changePassphraseAction(0),\r\n    aboutQtAction(0),\r\n    trayIcon(0),\r\n    notificator(0),\r\n    rpcConsole(0)\r\n{\r\n    resize(850, 550);\r\n    setWindowTitle(tr(\"BeCoin\") + \" - \" + tr(\"Wallet\"));\r\n#ifndef Q_WS_MAC\r\n    qApp->setWindowIcon(QIcon(\":icons\/bitcoin\"));\r\n    setWindowIcon(QIcon(\":icons\/bitcoin\"));\r\n#else\r\n    setUnifiedTitleAndToolBarOnMac(true);\r\n    QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);\r\n#endif\r\n    \/\/ Accept D&D of URIs\r\n    setAcceptDrops(true);\r\n\r\n    \/\/ Create actions for the toolbar, menu bar and tray\/dock icon\r\n    createActions();\r\n\r\n    \/\/ Create application menu bar\r\n    createMenuBar();\r\n\r\n    \/\/ Create the toolbars\r\n    createToolBars();\r\n\r\n    \/\/ Create the tray icon (or setup the dock icon)\r\n    createTrayIcon();\r\n\r\n    \/\/ Create tabs\r\n    overviewPage = new OverviewPage();\r\n\r\n    miningPage = new MiningPage(this);\r\n\r\n    transactionsPage = new QWidget(this);\r\n    QVBoxLayout *vbox = new QVBoxLayout();\r\n    transactionView = new TransactionView(this);\r\n    vbox->addWidget(transactionView);\r\n    transactionsPage->setLayout(vbox);\r\n\r\n    addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);\r\n\r\n    receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);\r\n\r\n    sendCoinsPage = new SendCoinsDialog(this);\r\n\r\n    signVerifyMessageDialog = new SignVerifyMessageDialog(this);\r\n\r\n    centralWidget = new QStackedWidget(this);\r\n    centralWidget->addWidget(overviewPage);\r\n    centralWidget->addWidget(miningPage);\r\n    centralWidget->addWidget(transactionsPage);\r\n    centralWidget->addWidget(addressBookPage);\r\n    centralWidget->addWidget(receiveCoinsPage);\r\n    centralWidget->addWidget(sendCoinsPage);\r\n#ifdef FIRST_CLASS_MESSAGING\r\n    centralWidget->addWidget(signVerifyMessageDialog);\r\n#endif\r\n    setCentralWidget(centralWidget);\r\n\r\n    \/\/ Create status bar\r\n    statusBar();\r\n\r\n    \/\/ Status bar notification icons\r\n    QFrame *frameBlocks = new QFrame();\r\n    frameBlocks->setContentsMargins(0,0,0,0);\r\n    frameBlocks->setMinimumWidth(73);\r\n    frameBlocks->setMaximumWidth(73);\r\n    QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);\r\n    frameBlocksLayout->setContentsMargins(3,0,3,0);\r\n    frameBlocksLayout->setSpacing(3);\r\n    labelEncryptionIcon = new QLabel();\r\n    labelMiningIcon = new QLabel();\r\n    labelConnectionsIcon = new QLabel();\r\n    labelBlocksIcon = new QLabel();\r\n    frameBlocksLayout->addStretch();\r\n    frameBlocksLayout->addWidget(labelEncryptionIcon);\r\n    frameBlocksLayout->addStretch();\r\n    frameBlocksLayout->addWidget(labelMiningIcon);\r\n    frameBlocksLayout->addStretch();\r\n    frameBlocksLayout->addWidget(labelConnectionsIcon);\r\n    frameBlocksLayout->addStretch();\r\n    frameBlocksLayout->addWidget(labelBlocksIcon);\r\n    frameBlocksLayout->addStretch();\r\n\r\n    \/\/ Progress bar and label for blocks download\r\n    progressBarLabel = new QLabel();\r\n    progressBarLabel->setVisible(false);\r\n    progressBar = new QProgressBar();\r\n    progressBar->setAlignment(Qt::AlignCenter);\r\n    progressBar->setVisible(false);\r\n\r\n    statusBar()->addWidget(progressBarLabel);\r\n    statusBar()->addWidget(progressBar);\r\n    statusBar()->addPermanentWidget(frameBlocks);\r\n\r\n    syncIconMovie = new QMovie(\":\/movies\/update_spinner\", \"mng\", this);\r\n\r\n    \/\/ Clicking on a transaction on the overview page simply sends you to transaction history page\r\n    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));\r\n    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));\r\n\r\n    \/\/ Doubleclicking on a transaction on the transaction history page shows details\r\n    connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));\r\n\r\n    rpcConsole = new RPCConsole(this);\r\n    connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));\r\n\r\n    \/\/ Clicking on \"Verify Message\" in the address book sends you to the verify message tab\r\n    connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));\r\n    \/\/ Clicking on \"Sign Message\" in the receive coins page sends you to the sign message tab\r\n    connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));\r\n\r\n    gotoOverviewPage();\r\n}\r\n\r\nBitcoinGUI::~BitcoinGUI()\r\n{\r\n    if(trayIcon) \/\/ Hide tray icon, as deleting will let it linger until quit (on Ubuntu)\r\n        trayIcon->hide();\r\n#ifdef Q_WS_MAC\r\n    delete appMenuBar;\r\n#endif\r\n}\r\n\r\nvoid BitcoinGUI::createActions()\r\n{\r\n    QActionGroup *tabGroup = new QActionGroup(this);\r\n\r\n    overviewAction = new QAction(QIcon(\":\/icons\/overview\"), tr(\"&Overview\"), this);\r\n    overviewAction->setToolTip(tr(\"Show general overview of wallet\"));\r\n    overviewAction->setCheckable(true);\r\n    overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));\r\n    tabGroup->addAction(overviewAction);\r\n\r\n    miningAction = new QAction(QIcon(\":\/icons\/mining\"), tr(\"&Mining\"), this);\r\n    miningAction->setToolTip(tr(\"Configure mining\"));\r\n    miningAction->setCheckable(true);\r\n    tabGroup->addAction(miningAction);\r\n\r\n    historyAction = new QAction(QIcon(\":\/icons\/history\"), tr(\"&Transactions\"), this);\r\n    historyAction->setToolTip(tr(\"Browse transaction history\"));\r\n    historyAction->setCheckable(true);\r\n    historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));\r\n    tabGroup->addAction(historyAction);\r\n\r\n    addressBookAction = new QAction(QIcon(\":\/icons\/address-book\"), tr(\"&Address Book\"), this);\r\n    addressBookAction->setToolTip(tr(\"Edit the list of stored addresses and labels\"));\r\n    addressBookAction->setCheckable(true);\r\n    addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));\r\n    tabGroup->addAction(addressBookAction);\r\n\r\n    receiveCoinsAction = new QAction(QIcon(\":\/icons\/receiving_addresses\"), tr(\"&Receive coins\"), this);\r\n    receiveCoinsAction->setToolTip(tr(\"Show the list of addresses for receiving payments\"));\r\n    receiveCoinsAction->setCheckable(true);\r\n    receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));\r\n    tabGroup->addAction(receiveCoinsAction);\r\n\r\n    sendCoinsAction = new QAction(QIcon(\":\/icons\/send\"), tr(\"&Send coins\"), this);\r\n    sendCoinsAction->setToolTip(tr(\"Send coins to a BeCoin address\"));\r\n    sendCoinsAction->setCheckable(true);\r\n    sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));\r\n    tabGroup->addAction(sendCoinsAction);\r\n\r\n    signMessageAction = new QAction(QIcon(\":\/icons\/edit\"), tr(\"Sign &message...\"), this);\r\n    signMessageAction->setToolTip(tr(\"Sign a message to prove you own a Bitcoin address\"));\r\n    tabGroup->addAction(signMessageAction);\r\n\r\n    verifyMessageAction = new QAction(QIcon(\":\/icons\/transaction_0\"), tr(\"&Verify message...\"), this);\r\n    verifyMessageAction->setToolTip(tr(\"Verify a message to ensure it was signed with a specified Bitcoin address\"));\r\n    tabGroup->addAction(verifyMessageAction);\r\n\r\n#ifdef FIRST_CLASS_MESSAGING\r\n    firstClassMessagingAction = new QAction(QIcon(\":\/icons\/edit\"), tr(\"S&ignatures\"), this);\r\n    firstClassMessagingAction->setToolTip(signMessageAction->toolTip() + QString(\". \/ \") + verifyMessageAction->toolTip() + QString(\".\"));\r\n    firstClassMessagingAction->setCheckable(true);\r\n    tabGroup->addAction(firstClassMessagingAction);\r\n#endif\r\n\r\n    connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\r\n    connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));\r\n    connect(miningAction, SIGNAL(triggered()), this, SLOT(gotoMiningPage()));\r\n    connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\r\n    connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));\r\n    connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\r\n    connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));\r\n    connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\r\n    connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));\r\n    connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\r\n    connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));\r\n    connect(signMessageAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\r\n    connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));\r\n    connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\r\n    connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));\r\n#ifdef FIRST_CLASS_MESSAGING\r\n    connect(firstClassMessagingAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));\r\n    \/\/ Always start with the sign message tab for FIRST_CLASS_MESSAGING\r\n    connect(firstClassMessagingAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));\r\n#endif\r\n\r\n    quitAction = new QAction(QIcon(\":\/icons\/quit\"), tr(\"E&xit\"), this);\r\n    quitAction->setToolTip(tr(\"Quit application\"));\r\n    quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));\r\n    quitAction->setMenuRole(QAction::QuitRole);\r\n    aboutAction = new QAction(QIcon(\":\/icons\/bitcoin\"), tr(\"&About BeCoin\"), this);\r\n    aboutAction->setToolTip(tr(\"Show information about BeCoin\"));\r\n    aboutAction->setMenuRole(QAction::AboutRole);\r\n    aboutQtAction = new QAction(tr(\"About &Qt\"), this);\r\n    aboutQtAction->setToolTip(tr(\"Show information about Qt\"));\r\n    aboutQtAction->setMenuRole(QAction::AboutQtRole);\r\n    optionsAction = new QAction(QIcon(\":\/icons\/options\"), tr(\"&Options...\"), this);\r\n    optionsAction->setToolTip(tr(\"Modify configuration options for BeCoin\"));\r\n    optionsAction->setMenuRole(QAction::PreferencesRole);\r\n    toggleHideAction = new QAction(QIcon(\":\/icons\/bitcoin\"), tr(\"Show\/Hide &BeCoin\"), this);\r\n    toggleHideAction->setToolTip(tr(\"Show or hide the BeCoin window\"));\r\n    exportAction = new QAction(QIcon(\":\/icons\/export\"), tr(\"&Export...\"), this);\r\n    exportAction->setToolTip(tr(\"Export the data in the current tab to a file\"));\r\n    encryptWalletAction = new QAction(QIcon(\":\/icons\/lock_closed\"), tr(\"&Encrypt Wallet...\"), this);\r\n    encryptWalletAction->setToolTip(tr(\"Encrypt or decrypt wallet\"));\r\n    encryptWalletAction->setCheckable(true);\r\n    backupWalletAction = new QAction(QIcon(\":\/icons\/filesave\"), tr(\"&Backup Wallet...\"), this);\r\n    backupWalletAction->setToolTip(tr(\"Backup wallet to another location\"));\r\n    changePassphraseAction = new QAction(QIcon(\":\/icons\/key\"), tr(\"&Change Passphrase...\"), this);\r\n    changePassphraseAction->setToolTip(tr(\"Change the passphrase used for wallet encryption\"));\r\n    openRPCConsoleAction = new QAction(QIcon(\":\/icons\/debugwindow\"), tr(\"&Debug window\"), this);\r\n    openRPCConsoleAction->setToolTip(tr(\"Open debugging and diagnostic console\"));\r\n\r\n    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));\r\n    connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));\r\n    connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));\r\n    connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));\r\n    connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));\r\n    connect(encryptWalletAction, SIGNAL(triggered(bool)), this, SLOT(encryptWallet(bool)));\r\n    connect(backupWalletAction, SIGNAL(triggered()), this, SLOT(backupWallet()));\r\n    connect(changePassphraseAction, SIGNAL(triggered()), this, SLOT(changePassphrase()));\r\n}\r\n\r\nvoid BitcoinGUI::createMenuBar()\r\n{\r\n#ifdef Q_WS_MAC\r\n    \/\/ Create a decoupled menu bar on Mac which stays even if the window is closed\r\n    appMenuBar = new QMenuBar();\r\n#else\r\n    \/\/ Get the main window's menu bar on other platforms\r\n    appMenuBar = menuBar();\r\n#endif\r\n\r\n    \/\/ Configure the menus\r\n    QMenu *file = appMenuBar->addMenu(tr(\"&File\"));\r\n    file->addAction(backupWalletAction);\r\n    file->addAction(exportAction);\r\n#ifndef FIRST_CLASS_MESSAGING\r\n    file->addAction(signMessageAction);\r\n    file->addAction(verifyMessageAction);\r\n#endif\r\n    file->addSeparator();\r\n    file->addAction(quitAction);\r\n\r\n    QMenu *settings = appMenuBar->addMenu(tr(\"&Settings\"));\r\n    settings->addAction(encryptWalletAction);\r\n    settings->addAction(changePassphraseAction);\r\n    settings->addSeparator();\r\n    settings->addAction(optionsAction);\r\n\r\n    QMenu *help = appMenuBar->addMenu(tr(\"&Help\"));\r\n    help->addAction(openRPCConsoleAction);\r\n    help->addSeparator();\r\n    help->addAction(aboutAction);\r\n    help->addAction(aboutQtAction);\r\n}\r\n\r\nvoid BitcoinGUI::createToolBars()\r\n{\r\n    QToolBar *toolbar = addToolBar(tr(\"Tabs toolbar\"));\r\n    toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);\r\n    toolbar->addAction(overviewAction);\r\n    toolbar->addAction(sendCoinsAction);\r\n    toolbar->addAction(receiveCoinsAction);\r\n    toolbar->addAction(historyAction);\r\n    toolbar->addAction(addressBookAction);\r\n    toolbar->addAction(miningAction);\r\n#ifdef FIRST_CLASS_MESSAGING\r\n    toolbar->addAction(firstClassMessagingAction);\r\n#endif\r\n\r\n    QToolBar *toolbar2 = addToolBar(tr(\"Actions toolbar\"));\r\n    toolbar2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);\r\n    toolbar2->addAction(exportAction);\r\n}\r\n\r\nvoid BitcoinGUI::setClientModel(ClientModel *clientModel)\r\n{\r\n    this->clientModel = clientModel;\r\n    if(clientModel)\r\n    {\r\n        \/\/ Replace some strings and icons, when using the testnet\r\n        if(clientModel->isTestNet())\r\n        {\r\n            setWindowTitle(windowTitle() + QString(\" \") + tr(\"[testnet]\"));\r\n#ifndef Q_WS_MAC\r\n            qApp->setWindowIcon(QIcon(\":icons\/bitcoin_testnet\"));\r\n            setWindowIcon(QIcon(\":icons\/bitcoin_testnet\"));\r\n#else\r\n            MacDockIconHandler::instance()->setIcon(QIcon(\":icons\/bitcoin_testnet\"));\r\n#endif\r\n            if(trayIcon)\r\n            {\r\n                trayIcon->setToolTip(tr(\"BeCoin client\") + QString(\" \") + tr(\"[testnet]\"));\r\n                trayIcon->setIcon(QIcon(\":\/icons\/toolbar_testnet\"));\r\n                toggleHideAction->setIcon(QIcon(\":\/icons\/toolbar_testnet\"));\r\n            }\r\n\r\n            aboutAction->setIcon(QIcon(\":\/icons\/toolbar_testnet\"));\r\n        }\r\n\r\n        \/\/ Keep up to date with client\r\n        setNumConnections(clientModel->getNumConnections());\r\n        connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));\r\n\r\n        setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers());\r\n        connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));\r\n\r\n        setMining(false, 0);\r\n        connect(clientModel, SIGNAL(miningChanged(bool,int)), this, SLOT(setMining(bool,int)));\r\n\r\n        \/\/ Report errors from network\/worker thread\r\n        connect(clientModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));\r\n\r\n        rpcConsole->setClientModel(clientModel);\r\n        addressBookPage->setOptionsModel(clientModel->getOptionsModel());\r\n        receiveCoinsPage->setOptionsModel(clientModel->getOptionsModel());\r\n    }\r\n}\r\n\r\nvoid BitcoinGUI::setWalletModel(WalletModel *walletModel)\r\n{\r\n    this->walletModel = walletModel;\r\n    if(walletModel)\r\n    {\r\n        \/\/ Report errors from wallet thread\r\n        connect(walletModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));\r\n\r\n        \/\/ Put transaction list in tabs\r\n        transactionView->setModel(walletModel);\r\n\r\n        overviewPage->setModel(walletModel);\r\n        addressBookPage->setModel(walletModel->getAddressTableModel());\r\n        receiveCoinsPage->setModel(walletModel->getAddressTableModel());\r\n        sendCoinsPage->setModel(walletModel);\r\n        signVerifyMessageDialog->setModel(walletModel);\r\n        miningPage->setModel(clientModel);\r\n\r\n        setEncryptionStatus(walletModel->getEncryptionStatus());\r\n        connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int)));\r\n\r\n        \/\/ Balloon popup for new transaction\r\n        connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),\r\n                this, SLOT(incomingTransaction(QModelIndex,int,int)));\r\n\r\n        \/\/ Ask for passphrase if needed\r\n        connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));\r\n    }\r\n}\r\n\r\nvoid BitcoinGUI::createTrayIcon()\r\n{\r\n    QMenu *trayIconMenu;\r\n#ifndef Q_WS_MAC\r\n    trayIcon = new QSystemTrayIcon(this);\r\n    trayIconMenu = new QMenu(this);\r\n    trayIcon->setContextMenu(trayIconMenu);\r\n    trayIcon->setToolTip(tr(\"BeCoin client\"));\r\n    trayIcon->setIcon(QIcon(\":\/icons\/toolbar\"));\r\n    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),\r\n            this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));\r\n    trayIcon->show();\r\n#else\r\n    \/\/ Note: On Mac, the dock icon is used to provide the tray's functionality.\r\n    MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();\r\n    trayIconMenu = dockIconHandler->dockMenu();\r\n#endif\r\n\r\n    \/\/ Configuration of the tray icon (or dock icon) icon menu\r\n    trayIconMenu->addAction(toggleHideAction);\r\n    trayIconMenu->addSeparator();\r\n    trayIconMenu->addAction(sendCoinsAction);\r\n    trayIconMenu->addAction(receiveCoinsAction);\r\n#ifndef FIRST_CLASS_MESSAGING\r\n    trayIconMenu->addSeparator();\r\n#endif\r\n    trayIconMenu->addAction(signMessageAction);\r\n    trayIconMenu->addAction(verifyMessageAction);\r\n    trayIconMenu->addSeparator();\r\n    trayIconMenu->addAction(optionsAction);\r\n    trayIconMenu->addAction(openRPCConsoleAction);\r\n#ifndef Q_WS_MAC \/\/ This is built-in on Mac\r\n    trayIconMenu->addSeparator();\r\n    trayIconMenu->addAction(quitAction);\r\n#endif\r\n\r\n    notificator = new Notificator(qApp->applicationName(), trayIcon);\r\n}\r\n\r\n#ifndef Q_WS_MAC\r\nvoid BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)\r\n{\r\n    if(reason == QSystemTrayIcon::Trigger)\r\n    {\r\n        \/\/ Click on system tray icon triggers \"show\/hide BeCoin\"\r\n        toggleHideAction->trigger();\r\n    }\r\n}\r\n#endif\r\n\r\nvoid BitcoinGUI::optionsClicked()\r\n{\r\n    if(!clientModel || !clientModel->getOptionsModel())\r\n        return;\r\n    OptionsDialog dlg;\r\n    dlg.setModel(clientModel->getOptionsModel());\r\n    dlg.exec();\r\n}\r\n\r\nvoid BitcoinGUI::aboutClicked()\r\n{\r\n    AboutDialog dlg;\r\n    dlg.setModel(clientModel);\r\n    dlg.exec();\r\n}\r\n\r\nvoid BitcoinGUI::setNumConnections(int count)\r\n{\r\n    QString icon;\r\n    switch(count)\r\n    {\r\n    case 0: icon = \":\/icons\/connect_0\"; break;\r\n    case 1: case 2: case 3: icon = \":\/icons\/connect_1\"; break;\r\n    case 4: case 5: case 6: icon = \":\/icons\/connect_2\"; break;\r\n    case 7: case 8: case 9: icon = \":\/icons\/connect_3\"; break;\r\n    default: icon = \":\/icons\/connect_4\"; break;\r\n    }\r\n    labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));\r\n    labelConnectionsIcon->setToolTip(tr(\"%n active connection(s) to BeCoin network\", \"\", count));\r\n}\r\n\r\nvoid BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)\r\n{\r\n    \/\/ don't show \/ hide progressBar and it's label if we have no connection(s) to the network\r\n    if (!clientModel || clientModel->getNumConnections() == 0)\r\n    {\r\n        progressBarLabel->setVisible(false);\r\n        progressBar->setVisible(false);\r\n\r\n        return;\r\n    }\r\n\r\n    QString tooltip;\r\n\r\n    if(count < nTotalBlocks)\r\n    {\r\n        int nRemainingBlocks = nTotalBlocks - count;\r\n        float nPercentageDone = count \/ (nTotalBlocks * 0.01f);\r\n\r\n        if (clientModel->getStatusBarWarnings() == \"\")\r\n        {\r\n            progressBarLabel->setText(tr(\"Synchronizing with network...\"));\r\n            progressBarLabel->setVisible(true);\r\n            progressBar->setFormat(tr(\"~%n block(s) remaining\", \"\", nRemainingBlocks));\r\n            progressBar->setMaximum(nTotalBlocks);\r\n            progressBar->setValue(count);\r\n            progressBar->setVisible(true);\r\n        }\r\n        else\r\n        {\r\n            progressBarLabel->setText(clientModel->getStatusBarWarnings());\r\n            progressBarLabel->setVisible(true);\r\n            progressBar->setVisible(false);\r\n        }\r\n        tooltip = tr(\"Downloaded %1 of %2 blocks of transaction history (%3% done).\").arg(count).arg(nTotalBlocks).arg(nPercentageDone, 0, 'f', 2);\r\n    }\r\n    else\r\n    {\r\n        if (clientModel->getStatusBarWarnings() == \"\")\r\n            progressBarLabel->setVisible(false);\r\n        else\r\n        {\r\n            progressBarLabel->setText(clientModel->getStatusBarWarnings());\r\n            progressBarLabel->setVisible(true);\r\n        }\r\n        progressBar->setVisible(false);\r\n        tooltip = tr(\"Downloaded %1 blocks of transaction history.\").arg(count);\r\n    }\r\n\r\n    tooltip = tr(\"Current difficulty is %1.\").arg(clientModel->GetDifficulty()) + QString(\"<br>\") + tooltip;\r\n\r\n    QDateTime now = QDateTime::currentDateTime();\r\n    QDateTime lastBlockDate = clientModel->getLastBlockDate();\r\n    int secs = lastBlockDate.secsTo(now);\r\n    QString text;\r\n\r\n    \/\/ Represent time from last generated block in human readable text\r\n    if(secs <= 0)\r\n    {\r\n        \/\/ Fully up to date. Leave text empty.\r\n    }\r\n    else if(secs < 60)\r\n    {\r\n        text = tr(\"%n second(s) ago\",\"\",secs);\r\n    }\r\n    else if(secs < 60*60)\r\n    {\r\n        text = tr(\"%n minute(s) ago\",\"\",secs\/60);\r\n    }\r\n    else if(secs < 24*60*60)\r\n    {\r\n        text = tr(\"%n hour(s) ago\",\"\",secs\/(60*60));\r\n    }\r\n    else\r\n    {\r\n        text = tr(\"%n day(s) ago\",\"\",secs\/(60*60*24));\r\n    }\r\n\r\n    \/\/ Set icon state: spinning if catching up, tick otherwise\r\n    if(secs < 90*60 && count >= nTotalBlocks)\r\n    {\r\n        tooltip = tr(\"Up to date\") + QString(\".<br>\") + tooltip;\r\n        labelBlocksIcon->setPixmap(QIcon(\":\/icons\/synced\").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));\r\n\r\n        overviewPage->showOutOfSyncWarning(false);\r\n    }\r\n    else\r\n    {\r\n        tooltip = tr(\"Catching up...\") + QString(\"<br>\") + tooltip;\r\n        labelBlocksIcon->setMovie(syncIconMovie);\r\n        syncIconMovie->start();\r\n\r\n        overviewPage->showOutOfSyncWarning(true);\r\n    }\r\n\r\n    if(!text.isEmpty())\r\n    {\r\n        tooltip += QString(\"<br>\");\r\n        tooltip += tr(\"Last received block was generated %1.\").arg(text);\r\n    }\r\n\r\n    \/\/ Don't word-wrap this (fixed-width) tooltip\r\n    tooltip = QString(\"<nobr>\") + tooltip + QString(\"<\/nobr>\");\r\n\r\n    labelBlocksIcon->setToolTip(tooltip);\r\n    progressBarLabel->setToolTip(tooltip);\r\n    progressBar->setToolTip(tooltip);\r\n}\r\n\r\nvoid BitcoinGUI::setMining(bool mining, int hashrate)\r\n{\r\n    if (mining)\r\n    {\r\n        labelMiningIcon->setPixmap(QIcon(\":\/icons\/mining_active\").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));\r\n        labelMiningIcon->setToolTip(tr(\"Mining BeCoin at %1 hashes per second\").arg(hashrate));\r\n    }\r\n    else\r\n    {\r\n        labelMiningIcon->setPixmap(QIcon(\":\/icons\/mining_inactive\").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));\r\n        labelMiningIcon->setToolTip(tr(\"Not mining BeCoin\"));\r\n    }\r\n}\r\n\r\nvoid BitcoinGUI::error(const QString &title, const QString &message, bool modal)\r\n{\r\n    \/\/ Report errors from network\/worker thread\r\n    if(modal)\r\n    {\r\n        QMessageBox::critical(this, title, message, QMessageBox::Ok, QMessageBox::Ok);\r\n    } else {\r\n        notificator->notify(Notificator::Critical, title, message);\r\n    }\r\n}\r\n\r\nvoid BitcoinGUI::changeEvent(QEvent *e)\r\n{\r\n    QMainWindow::changeEvent(e);\r\n#ifndef Q_WS_MAC \/\/ Ignored on Mac\r\n    if(e->type() == QEvent::WindowStateChange)\r\n    {\r\n        if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())\r\n        {\r\n            QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);\r\n            if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())\r\n            {\r\n                QTimer::singleShot(0, this, SLOT(hide()));\r\n                e->ignore();\r\n            }\r\n        }\r\n    }\r\n#endif\r\n}\r\n\r\nvoid BitcoinGUI::closeEvent(QCloseEvent *event)\r\n{\r\n    if(clientModel)\r\n    {\r\n#ifndef Q_WS_MAC \/\/ Ignored on Mac\r\n        if(!clientModel->getOptionsModel()->getMinimizeToTray() &&\r\n           !clientModel->getOptionsModel()->getMinimizeOnClose())\r\n        {\r\n            qApp->quit();\r\n        }\r\n#endif\r\n    }\r\n    QMainWindow::closeEvent(event);\r\n}\r\n\r\nvoid BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)\r\n{\r\n    QString strMessage =\r\n        tr(\"This transaction is over the size limit.  You can still send it for a fee of %1, \"\r\n          \"which goes to the nodes that process your transaction and helps to support the network.  \"\r\n          \"Do you want to pay the fee?\").arg(\r\n                BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));\r\n    QMessageBox::StandardButton retval = QMessageBox::question(\r\n          this, tr(\"Confirm transaction fee\"), strMessage,\r\n          QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);\r\n    *payFee = (retval == QMessageBox::Yes);\r\n}\r\n\r\nvoid BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)\r\n{\r\n    if(!walletModel || !clientModel)\r\n        return;\r\n    TransactionTableModel *ttm = walletModel->getTransactionTableModel();\r\n    qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)\r\n                    .data(Qt::EditRole).toULongLong();\r\n    if(!clientModel->inInitialBlockDownload())\r\n    {\r\n        \/\/ On new transaction, make an info balloon\r\n        \/\/ Unless the initial block download is in progress, to prevent balloon-spam\r\n        QString date = ttm->index(start, TransactionTableModel::Date, parent)\r\n                        .data().toString();\r\n        QString type = ttm->index(start, TransactionTableModel::Type, parent)\r\n                        .data().toString();\r\n        QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)\r\n                        .data().toString();\r\n        QIcon icon = qvariant_cast<QIcon>(ttm->index(start,\r\n                            TransactionTableModel::ToAddress, parent)\r\n                        .data(Qt::DecorationRole));\r\n\r\n        notificator->notify(Notificator::Information,\r\n                            (amount)<0 ? tr(\"Sent transaction\") :\r\n                                         tr(\"Incoming transaction\"),\r\n                              tr(\"Date: %1\\n\"\r\n                                 \"Amount: %2\\n\"\r\n                                 \"Type: %3\\n\"\r\n                                 \"Address: %4\\n\")\r\n                              .arg(date)\r\n                              .arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), amount, true))\r\n                              .arg(type)\r\n                              .arg(address), icon);\r\n    }\r\n}\r\n\r\nvoid BitcoinGUI::gotoOverviewPage()\r\n{\r\n    overviewAction->setChecked(true);\r\n    centralWidget->setCurrentWidget(overviewPage);\r\n\r\n    exportAction->setEnabled(false);\r\n    disconnect(exportAction, SIGNAL(triggered()), 0, 0);\r\n}\r\n\r\nvoid BitcoinGUI::gotoMiningPage()\r\n{\r\n    miningAction->setChecked(true);\r\n    centralWidget->setCurrentWidget(miningPage);\r\n\r\n    exportAction->setEnabled(false);\r\n    disconnect(exportAction, SIGNAL(triggered()), 0, 0);\r\n}\r\n\r\nvoid BitcoinGUI::gotoHistoryPage()\r\n{\r\n    historyAction->setChecked(true);\r\n    centralWidget->setCurrentWidget(transactionsPage);\r\n\r\n    exportAction->setEnabled(true);\r\n    disconnect(exportAction, SIGNAL(triggered()), 0, 0);\r\n    connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));\r\n}\r\n\r\nvoid BitcoinGUI::gotoAddressBookPage()\r\n{\r\n    addressBookAction->setChecked(true);\r\n    centralWidget->setCurrentWidget(addressBookPage);\r\n\r\n    exportAction->setEnabled(true);\r\n    disconnect(exportAction, SIGNAL(triggered()), 0, 0);\r\n    connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));\r\n}\r\n\r\nvoid BitcoinGUI::gotoReceiveCoinsPage()\r\n{\r\n    receiveCoinsAction->setChecked(true);\r\n    centralWidget->setCurrentWidget(receiveCoinsPage);\r\n\r\n    exportAction->setEnabled(true);\r\n    disconnect(exportAction, SIGNAL(triggered()), 0, 0);\r\n    connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));\r\n}\r\n\r\nvoid BitcoinGUI::gotoSendCoinsPage()\r\n{\r\n    sendCoinsAction->setChecked(true);\r\n    centralWidget->setCurrentWidget(sendCoinsPage);\r\n\r\n    exportAction->setEnabled(false);\r\n    disconnect(exportAction, SIGNAL(triggered()), 0, 0);\r\n}\r\n\r\nvoid BitcoinGUI::gotoSignMessageTab(QString addr)\r\n{\r\n#ifdef FIRST_CLASS_MESSAGING\r\n    firstClassMessagingAction->setChecked(true);\r\n    centralWidget->setCurrentWidget(signVerifyMessageDialog);\r\n\r\n    exportAction->setEnabled(false);\r\n    disconnect(exportAction, SIGNAL(triggered()), 0, 0);\r\n\r\n    signVerifyMessageDialog->showTab_SM(false);\r\n#else\r\n    \/\/ call show() in showTab_SM()\r\n    signVerifyMessageDialog->showTab_SM(true);\r\n#endif\r\n\r\n    if(!addr.isEmpty())\r\n        signVerifyMessageDialog->setAddress_SM(addr);\r\n}\r\n\r\nvoid BitcoinGUI::gotoVerifyMessageTab(QString addr)\r\n{\r\n#ifdef FIRST_CLASS_MESSAGING\r\n    firstClassMessagingAction->setChecked(true);\r\n    centralWidget->setCurrentWidget(signVerifyMessageDialog);\r\n\r\n    exportAction->setEnabled(false);\r\n    disconnect(exportAction, SIGNAL(triggered()), 0, 0);\r\n\r\n    signVerifyMessageDialog->showTab_VM(false);\r\n#else\r\n    \/\/ call show() in showTab_VM()\r\n    signVerifyMessageDialog->showTab_VM(true);\r\n#endif\r\n\r\n    if(!addr.isEmpty())\r\n        signVerifyMessageDialog->setAddress_VM(addr);\r\n}\r\n\r\nvoid BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)\r\n{\r\n    \/\/ Accept only URIs\r\n    if(event->mimeData()->hasUrls())\r\n        event->acceptProposedAction();\r\n}\r\n\r\nvoid BitcoinGUI::dropEvent(QDropEvent *event)\r\n{\r\n    if(event->mimeData()->hasUrls())\r\n    {\r\n        int nValidUrisFound = 0;\r\n        QList<QUrl> uris = event->mimeData()->urls();\r\n        foreach(const QUrl &uri, uris)\r\n        {\r\n            if (sendCoinsPage->handleURI(uri.toString()))\r\n                nValidUrisFound++;\r\n        }\r\n\r\n        \/\/ if valid URIs were found\r\n        if (nValidUrisFound)\r\n            gotoSendCoinsPage();\r\n        else\r\n            notificator->notify(Notificator::Warning, tr(\"URI handling\"), tr(\"URI can not be parsed! This can be caused by an invalid BeCoin address or malformed URI parameters.\"));\r\n    }\r\n\r\n    event->acceptProposedAction();\r\n}\r\n\r\nvoid BitcoinGUI::handleURI(QString strURI)\r\n{\r\n    \/\/ URI has to be valid\r\n    if (sendCoinsPage->handleURI(strURI))\r\n    {\r\n        showNormalIfMinimized();\r\n        gotoSendCoinsPage();\r\n    }\r\n    else\r\n        notificator->notify(Notificator::Warning, tr(\"URI handling\"), tr(\"URI can not be parsed! This can be caused by an invalid BeCoin address or malformed URI parameters.\"));\r\n}\r\n\r\nvoid BitcoinGUI::setEncryptionStatus(int status)\r\n{\r\n    switch(status)\r\n    {\r\n    case WalletModel::Unencrypted:\r\n        labelEncryptionIcon->hide();\r\n        encryptWalletAction->setChecked(false);\r\n        changePassphraseAction->setEnabled(false);\r\n        encryptWalletAction->setEnabled(true);\r\n        break;\r\n    case WalletModel::Unlocked:\r\n        labelEncryptionIcon->show();\r\n        labelEncryptionIcon->setPixmap(QIcon(\":\/icons\/lock_open\").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));\r\n        labelEncryptionIcon->setToolTip(tr(\"Wallet is <b>encrypted<\/b> and currently <b>unlocked<\/b>\"));\r\n        encryptWalletAction->setChecked(true);\r\n        changePassphraseAction->setEnabled(true);\r\n        encryptWalletAction->setEnabled(false); \/\/ TODO: decrypt currently not supported\r\n        break;\r\n    case WalletModel::Locked:\r\n        labelEncryptionIcon->show();\r\n        labelEncryptionIcon->setPixmap(QIcon(\":\/icons\/lock_closed\").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));\r\n        labelEncryptionIcon->setToolTip(tr(\"Wallet is <b>encrypted<\/b> and currently <b>locked<\/b>\"));\r\n        encryptWalletAction->setChecked(true);\r\n        changePassphraseAction->setEnabled(true);\r\n        encryptWalletAction->setEnabled(false); \/\/ TODO: decrypt currently not supported\r\n        break;\r\n    }\r\n}\r\n\r\nvoid BitcoinGUI::encryptWallet(bool status)\r\n{\r\n    if(!walletModel)\r\n        return;\r\n    AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt:\r\n                                     AskPassphraseDialog::Decrypt, this);\r\n    dlg.setModel(walletModel);\r\n    dlg.exec();\r\n\r\n    setEncryptionStatus(walletModel->getEncryptionStatus());\r\n}\r\n\r\nvoid BitcoinGUI::backupWallet()\r\n{\r\n    QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);\r\n    QString filename = QFileDialog::getSaveFileName(this, tr(\"Backup Wallet\"), saveDir, tr(\"Wallet Data (*.dat)\"));\r\n    if(!filename.isEmpty()) {\r\n        if(!walletModel->backupWallet(filename)) {\r\n            QMessageBox::warning(this, tr(\"Backup Failed\"), tr(\"There was an error trying to save the wallet data to the new location.\"));\r\n        }\r\n    }\r\n}\r\n\r\nvoid BitcoinGUI::changePassphrase()\r\n{\r\n    AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);\r\n    dlg.setModel(walletModel);\r\n    dlg.exec();\r\n}\r\n\r\nvoid BitcoinGUI::unlockWallet()\r\n{\r\n    if(!walletModel)\r\n        return;\r\n    \/\/ Unlock wallet when requested by wallet model\r\n    if(walletModel->getEncryptionStatus() == WalletModel::Locked)\r\n    {\r\n        AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);\r\n        dlg.setModel(walletModel);\r\n        dlg.exec();\r\n    }\r\n}\r\n\r\nvoid BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)\r\n{\r\n    \/\/ activateWindow() (sometimes) helps with keyboard focus on Windows\r\n    if (isHidden())\r\n    {\r\n        show();\r\n        activateWindow();\r\n    }\r\n    else if (isMinimized())\r\n    {\r\n        showNormal();\r\n        activateWindow();\r\n    }\r\n    else if (GUIUtil::isObscured(this))\r\n    {\r\n        raise();\r\n        activateWindow();\r\n    }\r\n    else if(fToggleHidden)\r\n        hide();\r\n}\r\n\r\nvoid BitcoinGUI::toggleHidden()\r\n{\r\n    showNormalIfMinimized(true);\r\n}\r\n","avg_line_length":37.0655567118,"max_line_length":182,"alphanum_fraction":0.6673778776,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":62486,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/===- DeclBase.cpp - Declaration AST Node Implementation -----------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Decl and DeclContext classes.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/AST\/DeclBase.h\"\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/ASTMutationListener.h\"\n#include \"clang\/AST\/Attr.h\"\n#include \"clang\/AST\/AttrIterator.h\"\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/DeclCXX.h\"\n#include \"clang\/AST\/DeclContextInternals.h\"\n#include \"clang\/AST\/DeclFriend.h\"\n#include \"clang\/AST\/DeclObjC.h\"\n#include \"clang\/AST\/DeclOpenMP.h\"\n#include \"clang\/AST\/DeclTemplate.h\"\n#include \"clang\/AST\/DependentDiagnostic.h\"\n#include \"clang\/AST\/ExternalASTSource.h\"\n#include \"clang\/AST\/Stmt.h\"\n#include \"clang\/AST\/Type.h\"\n#include \"clang\/Basic\/IdentifierTable.h\"\n#include \"clang\/Basic\/LLVM.h\"\n#include \"clang\/Basic\/LangOptions.h\"\n#include \"clang\/Basic\/ObjCRuntime.h\"\n#include \"clang\/Basic\/PartialDiagnostic.h\"\n#include \"clang\/Basic\/SourceLocation.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/ADT\/PointerIntPair.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/Support\/Casting.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Support\/VersionTuple.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <algorithm>\n#include <cassert>\n#include <cstddef>\n#include <string>\n#include <tuple>\n#include <utility>\n\nusing namespace clang;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  Statistics\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;\n#define ABSTRACT_DECL(DECL)\n#include \"clang\/AST\/DeclNodes.inc\"\n\nvoid Decl::updateOutOfDate(IdentifierInfo &II) const {\n  getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);\n}\n\n#define DECL(DERIVED, BASE)                                                    \\\n  static_assert(alignof(Decl) >= alignof(DERIVED##Decl),                       \\\n                \"Alignment sufficient after objects prepended to \" #DERIVED);\n#define ABSTRACT_DECL(DECL)\n#include \"clang\/AST\/DeclNodes.inc\"\n\nvoid *Decl::operator new(std::size_t Size, const ASTContext &Context,\n                         unsigned ID, std::size_t Extra) {\n  \/\/ Allocate an extra 8 bytes worth of storage, which ensures that the\n  \/\/ resulting pointer will still be 8-byte aligned.\n  static_assert(sizeof(unsigned) * 2 >= alignof(Decl),\n                \"Decl won't be misaligned\");\n  void *Start = Context.Allocate(Size + Extra + 8);\n  void *Result = (char*)Start + 8;\n\n  unsigned *PrefixPtr = (unsigned *)Result - 2;\n\n  \/\/ Zero out the first 4 bytes; this is used to store the owning module ID.\n  PrefixPtr[0] = 0;\n\n  \/\/ Store the global declaration ID in the second 4 bytes.\n  PrefixPtr[1] = ID;\n\n  return Result;\n}\n\nvoid *Decl::operator new(std::size_t Size, const ASTContext &Ctx,\n                         DeclContext *Parent, std::size_t Extra) {\n  assert(!Parent || &Parent->getParentASTContext() == &Ctx);\n  \/\/ With local visibility enabled, we track the owning module even for local\n  \/\/ declarations. We create the TU decl early and may not yet know what the\n  \/\/ LangOpts are, so conservatively allocate the storage.\n  if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {\n    \/\/ Ensure required alignment of the resulting object by adding extra\n    \/\/ padding at the start if required.\n    size_t ExtraAlign =\n        llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));\n    auto *Buffer = reinterpret_cast<char *>(\n        ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));\n    Buffer += ExtraAlign;\n    auto *ParentModule =\n        Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;\n    return new (Buffer) Module*(ParentModule) + 1;\n  }\n  return ::operator new(Size + Extra, Ctx);\n}\n\nModule *Decl::getOwningModuleSlow() const {\n  assert(isFromASTFile() && \"Not from AST file?\");\n  return getASTContext().getExternalSource()->getModule(getOwningModuleID());\n}\n\nbool Decl::hasLocalOwningModuleStorage() const {\n  return getASTContext().getLangOpts().trackLocalOwningModule();\n}\n\nconst char *Decl::getDeclKindName() const {\n  switch (DeclKind) {\n  default: llvm_unreachable(\"Declaration not in DeclNodes.inc!\");\n#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;\n#define ABSTRACT_DECL(DECL)\n#include \"clang\/AST\/DeclNodes.inc\"\n  }\n}\n\nvoid Decl::setInvalidDecl(bool Invalid) {\n  InvalidDecl = Invalid;\n  assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());\n  if (!Invalid) {\n    return;\n  }\n\n  if (!isa<ParmVarDecl>(this)) {\n    \/\/ Defensive maneuver for ill-formed code: we're likely not to make it to\n    \/\/ a point where we set the access specifier, so default it to \"public\"\n    \/\/ to avoid triggering asserts elsewhere in the front end.\n    setAccess(AS_public);\n  }\n\n  \/\/ Marking a DecompositionDecl as invalid implies all the child BindingDecl's\n  \/\/ are invalid too.\n  if (auto *DD = dyn_cast<DecompositionDecl>(this)) {\n    for (auto *Binding : DD->bindings()) {\n      Binding->setInvalidDecl();\n    }\n  }\n}\n\nconst char *DeclContext::getDeclKindName() const {\n  switch (getDeclKind()) {\n#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;\n#define ABSTRACT_DECL(DECL)\n#include \"clang\/AST\/DeclNodes.inc\"\n  }\n  llvm_unreachable(\"Declaration context not in DeclNodes.inc!\");\n}\n\nbool Decl::StatisticsEnabled = false;\nvoid Decl::EnableStatistics() {\n  StatisticsEnabled = true;\n}\n\nvoid Decl::PrintStats() {\n  llvm::errs() << \"\\n*** Decl Stats:\\n\";\n\n  int totalDecls = 0;\n#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;\n#define ABSTRACT_DECL(DECL)\n#include \"clang\/AST\/DeclNodes.inc\"\n  llvm::errs() << \"  \" << totalDecls << \" decls total.\\n\";\n\n  int totalBytes = 0;\n#define DECL(DERIVED, BASE)                                             \\\n  if (n##DERIVED##s > 0) {                                              \\\n    totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl));         \\\n    llvm::errs() << \"    \" << n##DERIVED##s << \" \" #DERIVED \" decls, \"  \\\n                 << sizeof(DERIVED##Decl) << \" each (\"                  \\\n                 << n##DERIVED##s * sizeof(DERIVED##Decl)               \\\n                 << \" bytes)\\n\";                                        \\\n  }\n#define ABSTRACT_DECL(DECL)\n#include \"clang\/AST\/DeclNodes.inc\"\n\n  llvm::errs() << \"Total bytes = \" << totalBytes << \"\\n\";\n}\n\nvoid Decl::add(Kind k) {\n  switch (k) {\n#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;\n#define ABSTRACT_DECL(DECL)\n#include \"clang\/AST\/DeclNodes.inc\"\n  }\n}\n\nbool Decl::isTemplateParameterPack() const {\n  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(this))\n    return TTP->isParameterPack();\n  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))\n    return NTTP->isParameterPack();\n  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(this))\n    return TTP->isParameterPack();\n  return false;\n}\n\nbool Decl::isParameterPack() const {\n  if (const auto *Var = dyn_cast<VarDecl>(this))\n    return Var->isParameterPack();\n\n  return isTemplateParameterPack();\n}\n\nFunctionDecl *Decl::getAsFunction() {\n  if (auto *FD = dyn_cast<FunctionDecl>(this))\n    return FD;\n  if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(this))\n    return FTD->getTemplatedDecl();\n  return nullptr;\n}\n\nbool Decl::isTemplateDecl() const {\n  return isa<TemplateDecl>(this);\n}\n\nTemplateDecl *Decl::getDescribedTemplate() const {\n  if (auto *FD = dyn_cast<FunctionDecl>(this))\n    return FD->getDescribedFunctionTemplate();\n  else if (auto *RD = dyn_cast<CXXRecordDecl>(this))\n    return RD->getDescribedClassTemplate();\n  else if (auto *VD = dyn_cast<VarDecl>(this))\n    return VD->getDescribedVarTemplate();\n  else if (auto *AD = dyn_cast<TypeAliasDecl>(this))\n    return AD->getDescribedAliasTemplate();\n\n  return nullptr;\n}\n\nbool Decl::isTemplated() const {\n  \/\/ A declaration is dependent if it is a template or a template pattern, or\n  \/\/ is within (lexcially for a friend, semantically otherwise) a dependent\n  \/\/ context.\n  \/\/ FIXME: Should local extern declarations be treated like friends?\n  if (auto *AsDC = dyn_cast<DeclContext>(this))\n    return AsDC->isDependentContext();\n  auto *DC = getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext();\n  return DC->isDependentContext() || isTemplateDecl() || getDescribedTemplate();\n}\n\nconst DeclContext *Decl::getParentFunctionOrMethod() const {\n  for (const DeclContext *DC = getDeclContext();\n       DC && !DC->isTranslationUnit() && !DC->isNamespace();\n       DC = DC->getParent())\n    if (DC->isFunctionOrMethod())\n      return DC;\n\n  return nullptr;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ PrettyStackTraceDecl Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid PrettyStackTraceDecl::print(raw_ostream &OS) const {\n  SourceLocation TheLoc = Loc;\n  if (TheLoc.isInvalid() && TheDecl)\n    TheLoc = TheDecl->getLocation();\n\n  if (TheLoc.isValid()) {\n    TheLoc.print(OS, SM);\n    OS << \": \";\n  }\n\n  OS << Message;\n\n  if (const auto *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {\n    OS << \" '\";\n    DN->printQualifiedName(OS);\n    OS << '\\'';\n  }\n  OS << '\\n';\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Decl Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Out-of-line virtual method providing a home for Decl.\nDecl::~Decl() = default;\n\nvoid Decl::setDeclContext(DeclContext *DC) {\n  DeclCtx = DC;\n}\n\nvoid Decl::setLexicalDeclContext(DeclContext *DC) {\n  if (DC == getLexicalDeclContext())\n    return;\n\n  if (isInSemaDC()) {\n    setDeclContextsImpl(getDeclContext(), DC, getASTContext());\n  } else {\n    getMultipleDC()->LexicalDC = DC;\n  }\n\n  \/\/ FIXME: We shouldn't be changing the lexical context of declarations\n  \/\/ imported from AST files.\n  if (!isFromASTFile()) {\n    setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));\n    if (hasOwningModule())\n      setLocalOwningModule(cast<Decl>(DC)->getOwningModule());\n  }\n\n  assert(\n      (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||\n       getOwningModule()) &&\n      \"hidden declaration has no owning module\");\n}\n\nvoid Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,\n                               ASTContext &Ctx) {\n  if (SemaDC == LexicalDC) {\n    DeclCtx = SemaDC;\n  } else {\n    auto *MDC = new (Ctx) Decl::MultipleDC();\n    MDC->SemanticDC = SemaDC;\n    MDC->LexicalDC = LexicalDC;\n    DeclCtx = MDC;\n  }\n}\n\nbool Decl::isLexicallyWithinFunctionOrMethod() const {\n  const DeclContext *LDC = getLexicalDeclContext();\n  while (true) {\n    if (LDC->isFunctionOrMethod())\n      return true;\n    if (!isa<TagDecl>(LDC))\n      return false;\n    LDC = LDC->getLexicalParent();\n  }\n  return false;\n}\n\nbool Decl::isInAnonymousNamespace() const {\n  for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {\n    if (const auto *ND = dyn_cast<NamespaceDecl>(DC))\n      if (ND->isAnonymousNamespace())\n        return true;\n  }\n\n  return false;\n}\n\nbool Decl::isInStdNamespace() const {\n  const DeclContext *DC = getDeclContext();\n  return DC && DC->isStdNamespace();\n}\n\nTranslationUnitDecl *Decl::getTranslationUnitDecl() {\n  if (auto *TUD = dyn_cast<TranslationUnitDecl>(this))\n    return TUD;\n\n  DeclContext *DC = getDeclContext();\n  assert(DC && \"This decl is not contained in a translation unit!\");\n\n  while (!DC->isTranslationUnit()) {\n    DC = DC->getParent();\n    assert(DC && \"This decl is not contained in a translation unit!\");\n  }\n\n  return cast<TranslationUnitDecl>(DC);\n}\n\nASTContext &Decl::getASTContext() const {\n  return getTranslationUnitDecl()->getASTContext();\n}\n\nASTMutationListener *Decl::getASTMutationListener() const {\n  return getASTContext().getASTMutationListener();\n}\n\nunsigned Decl::getMaxAlignment() const {\n  if (!hasAttrs())\n    return 0;\n\n  unsigned Align = 0;\n  const AttrVec &V = getAttrs();\n  ASTContext &Ctx = getASTContext();\n  specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());\n  for (; I != E; ++I)\n    Align = std::max(Align, I->getAlignment(Ctx));\n  return Align;\n}\n\nbool Decl::isUsed(bool CheckUsedAttr) const {\n  const Decl *CanonD = getCanonicalDecl();\n  if (CanonD->Used)\n    return true;\n\n  \/\/ Check for used attribute.\n  \/\/ Ask the most recent decl, since attributes accumulate in the redecl chain.\n  if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())\n    return true;\n\n  \/\/ The information may have not been deserialized yet. Force deserialization\n  \/\/ to complete the needed information.\n  return getMostRecentDecl()->getCanonicalDecl()->Used;\n}\n\nvoid Decl::markUsed(ASTContext &C) {\n  if (isUsed(false))\n    return;\n\n  if (C.getASTMutationListener())\n    C.getASTMutationListener()->DeclarationMarkedUsed(this);\n\n  setIsUsed();\n}\n\nbool Decl::isReferenced() const {\n  if (Referenced)\n    return true;\n\n  \/\/ Check redeclarations.\n  for (const auto *I : redecls())\n    if (I->Referenced)\n      return true;\n\n  return false;\n}\n\nExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {\n  const Decl *Definition = nullptr;\n  if (auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {\n    Definition = ID->getDefinition();\n  } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(this)) {\n    Definition = PD->getDefinition();\n  } else if (auto *TD = dyn_cast<TagDecl>(this)) {\n    Definition = TD->getDefinition();\n  }\n  if (!Definition)\n    Definition = this;\n\n  if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())\n    return attr;\n  if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {\n    return dcd->getAttr<ExternalSourceSymbolAttr>();\n  }\n\n  return nullptr;\n}\n\nbool Decl::hasDefiningAttr() const {\n  return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();\n}\n\nconst Attr *Decl::getDefiningAttr() const {\n  if (auto *AA = getAttr<AliasAttr>())\n    return AA;\n  if (auto *IFA = getAttr<IFuncAttr>())\n    return IFA;\n  return nullptr;\n}\n\nstatic StringRef getRealizedPlatform(const AvailabilityAttr *A,\n                                     const ASTContext &Context) {\n  \/\/ Check if this is an App Extension \"platform\", and if so chop off\n  \/\/ the suffix for matching with the actual platform.\n  StringRef RealizedPlatform = A->getPlatform()->getName();\n  if (!Context.getLangOpts().AppExt)\n    return RealizedPlatform;\n  size_t suffix = RealizedPlatform.rfind(\"_app_extension\");\n  if (suffix != StringRef::npos)\n    return RealizedPlatform.slice(0, suffix);\n  return RealizedPlatform;\n}\n\n\/\/\/ Determine the availability of the given declaration based on\n\/\/\/ the target platform.\n\/\/\/\n\/\/\/ When it returns an availability result other than \\c AR_Available,\n\/\/\/ if the \\p Message parameter is non-NULL, it will be set to a\n\/\/\/ string describing why the entity is unavailable.\n\/\/\/\n\/\/\/ FIXME: Make these strings localizable, since they end up in\n\/\/\/ diagnostics.\nstatic AvailabilityResult CheckAvailability(ASTContext &Context,\n                                            const AvailabilityAttr *A,\n                                            std::string *Message,\n                                            VersionTuple EnclosingVersion) {\n  if (EnclosingVersion.empty())\n    EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();\n\n  if (EnclosingVersion.empty())\n    return AR_Available;\n\n  StringRef ActualPlatform = A->getPlatform()->getName();\n  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();\n\n  \/\/ Match the platform name.\n  if (getRealizedPlatform(A, Context) != TargetPlatform)\n    return AR_Available;\n\n  StringRef PrettyPlatformName\n    = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);\n\n  if (PrettyPlatformName.empty())\n    PrettyPlatformName = ActualPlatform;\n\n  std::string HintMessage;\n  if (!A->getMessage().empty()) {\n    HintMessage = \" - \";\n    HintMessage += A->getMessage();\n  }\n\n  \/\/ Make sure that this declaration has not been marked 'unavailable'.\n  if (A->getUnavailable()) {\n    if (Message) {\n      Message->clear();\n      llvm::raw_string_ostream Out(*Message);\n      Out << \"not available on \" << PrettyPlatformName\n          << HintMessage;\n    }\n\n    return AR_Unavailable;\n  }\n\n  \/\/ Make sure that this declaration has already been introduced.\n  if (!A->getIntroduced().empty() &&\n      EnclosingVersion < A->getIntroduced()) {\n    if (Message) {\n      Message->clear();\n      llvm::raw_string_ostream Out(*Message);\n      VersionTuple VTI(A->getIntroduced());\n      Out << \"introduced in \" << PrettyPlatformName << ' '\n          << VTI << HintMessage;\n    }\n\n    return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;\n  }\n\n  \/\/ Make sure that this declaration hasn't been obsoleted.\n  if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {\n    if (Message) {\n      Message->clear();\n      llvm::raw_string_ostream Out(*Message);\n      VersionTuple VTO(A->getObsoleted());\n      Out << \"obsoleted in \" << PrettyPlatformName << ' '\n          << VTO << HintMessage;\n    }\n\n    return AR_Unavailable;\n  }\n\n  \/\/ Make sure that this declaration hasn't been deprecated.\n  if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {\n    if (Message) {\n      Message->clear();\n      llvm::raw_string_ostream Out(*Message);\n      VersionTuple VTD(A->getDeprecated());\n      Out << \"first deprecated in \" << PrettyPlatformName << ' '\n          << VTD << HintMessage;\n    }\n\n    return AR_Deprecated;\n  }\n\n  return AR_Available;\n}\n\nAvailabilityResult Decl::getAvailability(std::string *Message,\n                                         VersionTuple EnclosingVersion,\n                                         StringRef *RealizedPlatform) const {\n  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))\n    return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,\n                                                    RealizedPlatform);\n\n  AvailabilityResult Result = AR_Available;\n  std::string ResultMessage;\n\n  for (const auto *A : attrs()) {\n    if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {\n      if (Result >= AR_Deprecated)\n        continue;\n\n      if (Message)\n        ResultMessage = Deprecated->getMessage();\n\n      Result = AR_Deprecated;\n      continue;\n    }\n\n    if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {\n      if (Message)\n        *Message = Unavailable->getMessage();\n      return AR_Unavailable;\n    }\n\n    if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {\n      AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,\n                                                Message, EnclosingVersion);\n\n      if (AR == AR_Unavailable) {\n        if (RealizedPlatform)\n          *RealizedPlatform = Availability->getPlatform()->getName();\n        return AR_Unavailable;\n      }\n\n      if (AR > Result) {\n        Result = AR;\n        if (Message)\n          ResultMessage.swap(*Message);\n      }\n      continue;\n    }\n  }\n\n  if (Message)\n    Message->swap(ResultMessage);\n  return Result;\n}\n\nVersionTuple Decl::getVersionIntroduced() const {\n  const ASTContext &Context = getASTContext();\n  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();\n  for (const auto *A : attrs()) {\n    if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {\n      if (getRealizedPlatform(Availability, Context) != TargetPlatform)\n        continue;\n      if (!Availability->getIntroduced().empty())\n        return Availability->getIntroduced();\n    }\n  }\n  return {};\n}\n\nbool Decl::canBeWeakImported(bool &IsDefinition) const {\n  IsDefinition = false;\n\n  \/\/ Variables, if they aren't definitions.\n  if (const auto *Var = dyn_cast<VarDecl>(this)) {\n    if (Var->isThisDeclarationADefinition()) {\n      IsDefinition = true;\n      return false;\n    }\n    return true;\n\n  \/\/ Functions, if they aren't definitions.\n  } else if (const auto *FD = dyn_cast<FunctionDecl>(this)) {\n    if (FD->hasBody()) {\n      IsDefinition = true;\n      return false;\n    }\n    return true;\n\n  \/\/ Objective-C classes, if this is the non-fragile runtime.\n  } else if (isa<ObjCInterfaceDecl>(this) &&\n             getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {\n    return true;\n\n  \/\/ Nothing else.\n  } else {\n    return false;\n  }\n}\n\nbool Decl::isWeakImported() const {\n  bool IsDefinition;\n  if (!canBeWeakImported(IsDefinition))\n    return false;\n\n  for (const auto *A : attrs()) {\n    if (isa<WeakImportAttr>(A))\n      return true;\n\n    if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {\n      if (CheckAvailability(getASTContext(), Availability, nullptr,\n                            VersionTuple()) == AR_NotYetIntroduced)\n        return true;\n    }\n  }\n\n  return false;\n}\n\nunsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {\n  switch (DeclKind) {\n    case Function:\n    case CXXDeductionGuide:\n    case CXXMethod:\n    case CXXConstructor:\n    case ConstructorUsingShadow:\n    case CXXDestructor:\n    case CXXConversion:\n    case EnumConstant:\n    case Var:\n    case ImplicitParam:\n    case ParmVar:\n    case ObjCMethod:\n    case ObjCProperty:\n    case MSProperty:\n      return IDNS_Ordinary;\n    case Label:\n      return IDNS_Label;\n    case IndirectField:\n      return IDNS_Ordinary | IDNS_Member;\n\n    case Binding:\n    case NonTypeTemplateParm:\n    case VarTemplate:\n    case Concept:\n      \/\/ These (C++-only) declarations are found by redeclaration lookup for\n      \/\/ tag types, so we include them in the tag namespace.\n      return IDNS_Ordinary | IDNS_Tag;\n\n    case ObjCCompatibleAlias:\n    case ObjCInterface:\n      return IDNS_Ordinary | IDNS_Type;\n\n    case Typedef:\n    case TypeAlias:\n    case TemplateTypeParm:\n    case ObjCTypeParam:\n      return IDNS_Ordinary | IDNS_Type;\n\n    case UnresolvedUsingTypename:\n      return IDNS_Ordinary | IDNS_Type | IDNS_Using;\n\n    case UsingShadow:\n      return 0; \/\/ we'll actually overwrite this later\n\n    case UnresolvedUsingValue:\n      return IDNS_Ordinary | IDNS_Using;\n\n    case Using:\n    case UsingPack:\n      return IDNS_Using;\n\n    case ObjCProtocol:\n      return IDNS_ObjCProtocol;\n\n    case Field:\n    case ObjCAtDefsField:\n    case ObjCIvar:\n      return IDNS_Member;\n\n    case Record:\n    case CXXRecord:\n    case Enum:\n      return IDNS_Tag | IDNS_Type;\n\n    case Namespace:\n    case NamespaceAlias:\n      return IDNS_Namespace;\n\n    case FunctionTemplate:\n      return IDNS_Ordinary;\n\n    case ClassTemplate:\n    case TemplateTemplateParm:\n    case TypeAliasTemplate:\n      return IDNS_Ordinary | IDNS_Tag | IDNS_Type;\n\n    case OMPDeclareReduction:\n      return IDNS_OMPReduction;\n\n    case OMPDeclareMapper:\n      return IDNS_OMPMapper;\n\n    \/\/ Never have names.\n    case Friend:\n    case FriendTemplate:\n    case AccessSpec:\n    case LinkageSpec:\n    case Export:\n    case FileScopeAsm:\n    case StaticAssert:\n    case ObjCPropertyImpl:\n    case PragmaComment:\n    case PragmaDetectMismatch:\n    case Block:\n    case Captured:\n    case TranslationUnit:\n    case ExternCContext:\n    case Decomposition:\n\n    case UsingDirective:\n    case BuiltinTemplate:\n    case ClassTemplateSpecialization:\n    case ClassTemplatePartialSpecialization:\n    case ClassScopeFunctionSpecialization:\n    case VarTemplateSpecialization:\n    case VarTemplatePartialSpecialization:\n    case ObjCImplementation:\n    case ObjCCategory:\n    case ObjCCategoryImpl:\n    case Import:\n    case OMPThreadPrivate:\n    case OMPAllocate:\n    case OMPRequires:\n    case OMPCapturedExpr:\n    case PragmaPupc:\n    case Empty:\n      \/\/ Never looked up by name.\n      return 0;\n  }\n\n  llvm_unreachable(\"Invalid DeclKind!\");\n}\n\nvoid Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {\n  assert(!HasAttrs && \"Decl already contains attrs.\");\n\n  AttrVec &AttrBlank = Ctx.getDeclAttrs(this);\n  assert(AttrBlank.empty() && \"HasAttrs was wrong?\");\n\n  AttrBlank = attrs;\n  HasAttrs = true;\n}\n\nvoid Decl::dropAttrs() {\n  if (!HasAttrs) return;\n\n  HasAttrs = false;\n  getASTContext().eraseDeclAttrs(this);\n}\n\nvoid Decl::addAttr(Attr *A) {\n  if (!hasAttrs()) {\n    setAttrs(AttrVec(1, A));\n    return;\n  }\n\n  AttrVec &Attrs = getAttrs();\n  if (!A->isInherited()) {\n    Attrs.push_back(A);\n    return;\n  }\n\n  \/\/ Attribute inheritance is processed after attribute parsing. To keep the\n  \/\/ order as in the source code, add inherited attributes before non-inherited\n  \/\/ ones.\n  auto I = Attrs.begin(), E = Attrs.end();\n  for (; I != E; ++I) {\n    if (!(*I)->isInherited())\n      break;\n  }\n  Attrs.insert(I, A);\n}\n\nconst AttrVec &Decl::getAttrs() const {\n  assert(HasAttrs && \"No attrs to get!\");\n  return getASTContext().getDeclAttrs(this);\n}\n\nDecl *Decl::castFromDeclContext (const DeclContext *D) {\n  Decl::Kind DK = D->getDeclKind();\n  switch(DK) {\n#define DECL(NAME, BASE)\n#define DECL_CONTEXT(NAME) \\\n    case Decl::NAME:       \\\n      return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));\n#define DECL_CONTEXT_BASE(NAME)\n#include \"clang\/AST\/DeclNodes.inc\"\n    default:\n#define DECL(NAME, BASE)\n#define DECL_CONTEXT_BASE(NAME)                  \\\n      if (DK >= first##NAME && DK <= last##NAME) \\\n        return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));\n#include \"clang\/AST\/DeclNodes.inc\"\n      llvm_unreachable(\"a decl that inherits DeclContext isn't handled\");\n  }\n}\n\nDeclContext *Decl::castToDeclContext(const Decl *D) {\n  Decl::Kind DK = D->getKind();\n  switch(DK) {\n#define DECL(NAME, BASE)\n#define DECL_CONTEXT(NAME) \\\n    case Decl::NAME:       \\\n      return static_cast<NAME##Decl *>(const_cast<Decl *>(D));\n#define DECL_CONTEXT_BASE(NAME)\n#include \"clang\/AST\/DeclNodes.inc\"\n    default:\n#define DECL(NAME, BASE)\n#define DECL_CONTEXT_BASE(NAME)                                   \\\n      if (DK >= first##NAME && DK <= last##NAME)                  \\\n        return static_cast<NAME##Decl *>(const_cast<Decl *>(D));\n#include \"clang\/AST\/DeclNodes.inc\"\n      llvm_unreachable(\"a decl that inherits DeclContext isn't handled\");\n  }\n}\n\nSourceLocation Decl::getBodyRBrace() const {\n  \/\/ Special handling of FunctionDecl to avoid de-serializing the body from PCH.\n  \/\/ FunctionDecl stores EndRangeLoc for this purpose.\n  if (const auto *FD = dyn_cast<FunctionDecl>(this)) {\n    const FunctionDecl *Definition;\n    if (FD->hasBody(Definition))\n      return Definition->getSourceRange().getEnd();\n    return {};\n  }\n\n  if (Stmt *Body = getBody())\n    return Body->getSourceRange().getEnd();\n\n  return {};\n}\n\nbool Decl::AccessDeclContextSanity() const {\n#ifndef NDEBUG\n  \/\/ Suppress this check if any of the following hold:\n  \/\/ 1. this is the translation unit (and thus has no parent)\n  \/\/ 2. this is a template parameter (and thus doesn't belong to its context)\n  \/\/ 3. this is a non-type template parameter\n  \/\/ 4. the context is not a record\n  \/\/ 5. it's invalid\n  \/\/ 6. it's a C++0x static_assert.\n  \/\/ 7. it's a block literal declaration\n  if (isa<TranslationUnitDecl>(this) ||\n      isa<TemplateTypeParmDecl>(this) ||\n      isa<NonTypeTemplateParmDecl>(this) ||\n      !getDeclContext() ||\n      !isa<CXXRecordDecl>(getDeclContext()) ||\n      isInvalidDecl() ||\n      isa<StaticAssertDecl>(this) ||\n      isa<BlockDecl>(this) ||\n      \/\/ FIXME: a ParmVarDecl can have ClassTemplateSpecialization\n      \/\/ as DeclContext (?).\n      isa<ParmVarDecl>(this) ||\n      \/\/ FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have\n      \/\/ AS_none as access specifier.\n      isa<CXXRecordDecl>(this) ||\n      isa<ClassScopeFunctionSpecializationDecl>(this))\n    return true;\n\n  assert(Access != AS_none &&\n         \"Access specifier is AS_none inside a record decl\");\n#endif\n  return true;\n}\n\nstatic Decl::Kind getKind(const Decl *D) { return D->getKind(); }\nstatic Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }\n\nint64_t Decl::getID() const {\n  return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this);\n}\n\nconst FunctionType *Decl::getFunctionType(bool BlocksToo) const {\n  QualType Ty;\n  if (const auto *D = dyn_cast<ValueDecl>(this))\n    Ty = D->getType();\n  else if (const auto *D = dyn_cast<TypedefNameDecl>(this))\n    Ty = D->getUnderlyingType();\n  else\n    return nullptr;\n\n  if (Ty->isFunctionPointerType())\n    Ty = Ty->getAs<PointerType>()->getPointeeType();\n  else if (Ty->isFunctionReferenceType())\n    Ty = Ty->getAs<ReferenceType>()->getPointeeType();\n  else if (BlocksToo && Ty->isBlockPointerType())\n    Ty = Ty->getAs<BlockPointerType>()->getPointeeType();\n\n  return Ty->getAs<FunctionType>();\n}\n\n\/\/\/ Starting at a given context (a Decl or DeclContext), look for a\n\/\/\/ code context that is not a closure (a lambda, block, etc.).\ntemplate <class T> static Decl *getNonClosureContext(T *D) {\n  if (getKind(D) == Decl::CXXMethod) {\n    auto *MD = cast<CXXMethodDecl>(D);\n    if (MD->getOverloadedOperator() == OO_Call &&\n        MD->getParent()->isLambda())\n      return getNonClosureContext(MD->getParent()->getParent());\n    return MD;\n  } else if (auto *FD = dyn_cast<FunctionDecl>(D))\n    return FD;\n  else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))\n    return MD;\n  else if (auto *BD = dyn_cast<BlockDecl>(D))\n    return getNonClosureContext(BD->getParent());\n  else if (auto *CD = dyn_cast<CapturedDecl>(D))\n    return getNonClosureContext(CD->getParent());\n  else\n    return nullptr;\n}\n\nDecl *Decl::getNonClosureContext() {\n  return ::getNonClosureContext(this);\n}\n\nDecl *DeclContext::getNonClosureAncestor() {\n  return ::getNonClosureContext(this);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ DeclContext Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nDeclContext::DeclContext(Decl::Kind K) {\n  DeclContextBits.DeclKind = K;\n  setHasExternalLexicalStorage(false);\n  setHasExternalVisibleStorage(false);\n  setNeedToReconcileExternalVisibleStorage(false);\n  setHasLazyLocalLexicalLookups(false);\n  setHasLazyExternalLexicalLookups(false);\n  setUseQualifiedLookup(false);\n}\n\nbool DeclContext::classof(const Decl *D) {\n  switch (D->getKind()) {\n#define DECL(NAME, BASE)\n#define DECL_CONTEXT(NAME) case Decl::NAME:\n#define DECL_CONTEXT_BASE(NAME)\n#include \"clang\/AST\/DeclNodes.inc\"\n      return true;\n    default:\n#define DECL(NAME, BASE)\n#define DECL_CONTEXT_BASE(NAME)                 \\\n      if (D->getKind() >= Decl::first##NAME &&  \\\n          D->getKind() <= Decl::last##NAME)     \\\n        return true;\n#include \"clang\/AST\/DeclNodes.inc\"\n      return false;\n  }\n}\n\nDeclContext::~DeclContext() = default;\n\n\/\/\/ Find the parent context of this context that will be\n\/\/\/ used for unqualified name lookup.\n\/\/\/\n\/\/\/ Generally, the parent lookup context is the semantic context. However, for\n\/\/\/ a friend function the parent lookup context is the lexical context, which\n\/\/\/ is the class in which the friend is declared.\nDeclContext *DeclContext::getLookupParent() {\n  \/\/ FIXME: Find a better way to identify friends.\n  if (isa<FunctionDecl>(this))\n    if (getParent()->getRedeclContext()->isFileContext() &&\n        getLexicalParent()->getRedeclContext()->isRecord())\n      return getLexicalParent();\n\n  return getParent();\n}\n\nconst BlockDecl *DeclContext::getInnermostBlockDecl() const {\n  const DeclContext *Ctx = this;\n\n  do {\n    if (Ctx->isClosure())\n      return cast<BlockDecl>(Ctx);\n    Ctx = Ctx->getParent();\n  } while (Ctx);\n\n  return nullptr;\n}\n\nbool DeclContext::isInlineNamespace() const {\n  return isNamespace() &&\n         cast<NamespaceDecl>(this)->isInline();\n}\n\nbool DeclContext::isStdNamespace() const {\n  if (!isNamespace())\n    return false;\n\n  const auto *ND = cast<NamespaceDecl>(this);\n  if (ND->isInline()) {\n    return ND->getParent()->isStdNamespace();\n  }\n\n  if (!getParent()->getRedeclContext()->isTranslationUnit())\n    return false;\n\n  const IdentifierInfo *II = ND->getIdentifier();\n  return II && II->isStr(\"std\");\n}\n\nbool DeclContext::isDependentContext() const {\n  if (isFileContext())\n    return false;\n\n  if (isa<ClassTemplatePartialSpecializationDecl>(this))\n    return true;\n\n  if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) {\n    if (Record->getDescribedClassTemplate())\n      return true;\n\n    if (Record->isDependentLambda())\n      return true;\n  }\n\n  if (const auto *Function = dyn_cast<FunctionDecl>(this)) {\n    if (Function->getDescribedFunctionTemplate())\n      return true;\n\n    \/\/ Friend function declarations are dependent if their *lexical*\n    \/\/ context is dependent.\n    if (cast<Decl>(this)->getFriendObjectKind())\n      return getLexicalParent()->isDependentContext();\n  }\n\n  \/\/ FIXME: A variable template is a dependent context, but is not a\n  \/\/ DeclContext. A context within it (such as a lambda-expression)\n  \/\/ should be considered dependent.\n\n  return getParent() && getParent()->isDependentContext();\n}\n\nbool DeclContext::isTransparentContext() const {\n  if (getDeclKind() == Decl::Enum)\n    return !cast<EnumDecl>(this)->isScoped();\n  else if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)\n    return true;\n\n  return false;\n}\n\nstatic bool isLinkageSpecContext(const DeclContext *DC,\n                                 LinkageSpecDecl::LanguageIDs ID) {\n  while (DC->getDeclKind() != Decl::TranslationUnit) {\n    if (DC->getDeclKind() == Decl::LinkageSpec)\n      return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;\n    DC = DC->getLexicalParent();\n  }\n  return false;\n}\n\nbool DeclContext::isExternCContext() const {\n  return isLinkageSpecContext(this, LinkageSpecDecl::lang_c);\n}\n\nconst LinkageSpecDecl *DeclContext::getExternCContext() const {\n  const DeclContext *DC = this;\n  while (DC->getDeclKind() != Decl::TranslationUnit) {\n    if (DC->getDeclKind() == Decl::LinkageSpec &&\n        cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c)\n      return cast<LinkageSpecDecl>(DC);\n    DC = DC->getLexicalParent();\n  }\n  return nullptr;\n}\n\nbool DeclContext::isExternCXXContext() const {\n  return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx);\n}\n\nbool DeclContext::Encloses(const DeclContext *DC) const {\n  if (getPrimaryContext() != this)\n    return getPrimaryContext()->Encloses(DC);\n\n  for (; DC; DC = DC->getParent())\n    if (DC->getPrimaryContext() == this)\n      return true;\n  return false;\n}\n\nDeclContext *DeclContext::getPrimaryContext() {\n  switch (getDeclKind()) {\n  case Decl::TranslationUnit:\n  case Decl::ExternCContext:\n  case Decl::LinkageSpec:\n  case Decl::Export:\n  case Decl::Block:\n  case Decl::Captured:\n  case Decl::OMPDeclareReduction:\n  case Decl::OMPDeclareMapper:\n    \/\/ There is only one DeclContext for these entities.\n    return this;\n\n  case Decl::Namespace:\n    \/\/ The original namespace is our primary context.\n    return static_cast<NamespaceDecl *>(this)->getOriginalNamespace();\n\n  case Decl::ObjCMethod:\n    return this;\n\n  case Decl::ObjCInterface:\n    if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this))\n      if (auto *Def = OID->getDefinition())\n        return Def;\n    return this;\n\n  case Decl::ObjCProtocol:\n    if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this))\n      if (auto *Def = OPD->getDefinition())\n        return Def;\n    return this;\n\n  case Decl::ObjCCategory:\n    return this;\n\n  case Decl::ObjCImplementation:\n  case Decl::ObjCCategoryImpl:\n    return this;\n\n  default:\n    if (getDeclKind() >= Decl::firstTag && getDeclKind() <= Decl::lastTag) {\n      \/\/ If this is a tag type that has a definition or is currently\n      \/\/ being defined, that definition is our primary context.\n      auto *Tag = cast<TagDecl>(this);\n\n      if (TagDecl *Def = Tag->getDefinition())\n        return Def;\n\n      if (const auto *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {\n        \/\/ Note, TagType::getDecl returns the (partial) definition one exists.\n        TagDecl *PossiblePartialDef = TagTy->getDecl();\n        if (PossiblePartialDef->isBeingDefined())\n          return PossiblePartialDef;\n      } else {\n        assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));\n      }\n\n      return Tag;\n    }\n\n    assert(getDeclKind() >= Decl::firstFunction &&\n           getDeclKind() <= Decl::lastFunction &&\n          \"Unknown DeclContext kind\");\n    return this;\n  }\n}\n\nvoid\nDeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){\n  Contexts.clear();\n\n  if (getDeclKind() != Decl::Namespace) {\n    Contexts.push_back(this);\n    return;\n  }\n\n  auto *Self = static_cast<NamespaceDecl *>(this);\n  for (NamespaceDecl *N = Self->getMostRecentDecl(); N;\n       N = N->getPreviousDecl())\n    Contexts.push_back(N);\n\n  std::reverse(Contexts.begin(), Contexts.end());\n}\n\nstd::pair<Decl *, Decl *>\nDeclContext::BuildDeclChain(ArrayRef<Decl *> Decls,\n                            bool FieldsAlreadyLoaded) {\n  \/\/ Build up a chain of declarations via the Decl::NextInContextAndBits field.\n  Decl *FirstNewDecl = nullptr;\n  Decl *PrevDecl = nullptr;\n  for (auto *D : Decls) {\n    if (FieldsAlreadyLoaded && isa<FieldDecl>(D))\n      continue;\n\n    if (PrevDecl)\n      PrevDecl->NextInContextAndBits.setPointer(D);\n    else\n      FirstNewDecl = D;\n\n    PrevDecl = D;\n  }\n\n  return std::make_pair(FirstNewDecl, PrevDecl);\n}\n\n\/\/\/ We have just acquired external visible storage, and we already have\n\/\/\/ built a lookup map. For every name in the map, pull in the new names from\n\/\/\/ the external storage.\nvoid DeclContext::reconcileExternalVisibleStorage() const {\n  assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);\n  setNeedToReconcileExternalVisibleStorage(false);\n\n  for (auto &Lookup : *LookupPtr)\n    Lookup.second.setHasExternalDecls();\n}\n\n\/\/\/ Load the declarations within this lexical storage from an\n\/\/\/ external source.\n\/\/\/ \\return \\c true if any declarations were added.\nbool\nDeclContext::LoadLexicalDeclsFromExternalStorage() const {\n  ExternalASTSource *Source = getParentASTContext().getExternalSource();\n  assert(hasExternalLexicalStorage() && Source && \"No external storage?\");\n\n  \/\/ Notify that we have a DeclContext that is initializing.\n  ExternalASTSource::Deserializing ADeclContext(Source);\n\n  \/\/ Load the external declarations, if any.\n  SmallVector<Decl*, 64> Decls;\n  setHasExternalLexicalStorage(false);\n  Source->FindExternalLexicalDecls(this, Decls);\n\n  if (Decls.empty())\n    return false;\n\n  \/\/ We may have already loaded just the fields of this record, in which case\n  \/\/ we need to ignore them.\n  bool FieldsAlreadyLoaded = false;\n  if (const auto *RD = dyn_cast<RecordDecl>(this))\n    FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();\n\n  \/\/ Splice the newly-read declarations into the beginning of the list\n  \/\/ of declarations.\n  Decl *ExternalFirst, *ExternalLast;\n  std::tie(ExternalFirst, ExternalLast) =\n      BuildDeclChain(Decls, FieldsAlreadyLoaded);\n  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);\n  FirstDecl = ExternalFirst;\n  if (!LastDecl)\n    LastDecl = ExternalLast;\n  return true;\n}\n\nDeclContext::lookup_result\nExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,\n                                                    DeclarationName Name) {\n  ASTContext &Context = DC->getParentASTContext();\n  StoredDeclsMap *Map;\n  if (!(Map = DC->LookupPtr))\n    Map = DC->CreateStoredDeclsMap(Context);\n  if (DC->hasNeedToReconcileExternalVisibleStorage())\n    DC->reconcileExternalVisibleStorage();\n\n  (*Map)[Name].removeExternalDecls();\n\n  return DeclContext::lookup_result();\n}\n\nDeclContext::lookup_result\nExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,\n                                                  DeclarationName Name,\n                                                  ArrayRef<NamedDecl*> Decls) {\n  ASTContext &Context = DC->getParentASTContext();\n  StoredDeclsMap *Map;\n  if (!(Map = DC->LookupPtr))\n    Map = DC->CreateStoredDeclsMap(Context);\n  if (DC->hasNeedToReconcileExternalVisibleStorage())\n    DC->reconcileExternalVisibleStorage();\n\n  StoredDeclsList &List = (*Map)[Name];\n\n  \/\/ Clear out any old external visible declarations, to avoid quadratic\n  \/\/ performance in the redeclaration checks below.\n  List.removeExternalDecls();\n\n  if (!List.isNull()) {\n    \/\/ We have both existing declarations and new declarations for this name.\n    \/\/ Some of the declarations may simply replace existing ones. Handle those\n    \/\/ first.\n    llvm::SmallVector<unsigned, 8> Skip;\n    for (unsigned I = 0, N = Decls.size(); I != N; ++I)\n      if (List.HandleRedeclaration(Decls[I], \/*IsKnownNewer*\/false))\n        Skip.push_back(I);\n    Skip.push_back(Decls.size());\n\n    \/\/ Add in any new declarations.\n    unsigned SkipPos = 0;\n    for (unsigned I = 0, N = Decls.size(); I != N; ++I) {\n      if (I == Skip[SkipPos])\n        ++SkipPos;\n      else\n        List.AddSubsequentDecl(Decls[I]);\n    }\n  } else {\n    \/\/ Convert the array to a StoredDeclsList.\n    for (auto *D : Decls) {\n      if (List.isNull())\n        List.setOnlyValue(D);\n      else\n        List.AddSubsequentDecl(D);\n    }\n  }\n\n  return List.getLookupResult();\n}\n\nDeclContext::decl_iterator DeclContext::decls_begin() const {\n  if (hasExternalLexicalStorage())\n    LoadLexicalDeclsFromExternalStorage();\n  return decl_iterator(FirstDecl);\n}\n\nbool DeclContext::decls_empty() const {\n  if (hasExternalLexicalStorage())\n    LoadLexicalDeclsFromExternalStorage();\n\n  return !FirstDecl;\n}\n\nbool DeclContext::containsDecl(Decl *D) const {\n  return (D->getLexicalDeclContext() == this &&\n          (D->NextInContextAndBits.getPointer() || D == LastDecl));\n}\n\nbool DeclContext::containsDeclAndLoad(Decl *D) const {\n  if (hasExternalLexicalStorage())\n    LoadLexicalDeclsFromExternalStorage();\n  return containsDecl(D);\n}\n\n\/\/\/ shouldBeHidden - Determine whether a declaration which was declared\n\/\/\/ within its semantic context should be invisible to qualified name lookup.\nstatic bool shouldBeHidden(NamedDecl *D) {\n  \/\/ Skip unnamed declarations.\n  if (!D->getDeclName())\n    return true;\n\n  \/\/ Skip entities that can't be found by name lookup into a particular\n  \/\/ context.\n  if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||\n      D->isTemplateParameter())\n    return true;\n\n  \/\/ Skip friends and local extern declarations unless they're the first\n  \/\/ declaration of the entity.\n  if ((D->isLocalExternDecl() || D->getFriendObjectKind()) &&\n      D != D->getCanonicalDecl())\n    return true;\n\n  \/\/ Skip template specializations.\n  \/\/ FIXME: This feels like a hack. Should DeclarationName support\n  \/\/ template-ids, or is there a better way to keep specializations\n  \/\/ from being visible?\n  if (isa<ClassTemplateSpecializationDecl>(D))\n    return true;\n  if (auto *FD = dyn_cast<FunctionDecl>(D))\n    if (FD->isFunctionTemplateSpecialization())\n      return true;\n\n  return false;\n}\n\nvoid DeclContext::removeDecl(Decl *D) {\n  assert(D->getLexicalDeclContext() == this &&\n         \"decl being removed from non-lexical context\");\n  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&\n         \"decl is not in decls list\");\n\n  \/\/ Remove D from the decl chain.  This is O(n) but hopefully rare.\n  if (D == FirstDecl) {\n    if (D == LastDecl)\n      FirstDecl = LastDecl = nullptr;\n    else\n      FirstDecl = D->NextInContextAndBits.getPointer();\n  } else {\n    for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {\n      assert(I && \"decl not found in linked list\");\n      if (I->NextInContextAndBits.getPointer() == D) {\n        I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());\n        if (D == LastDecl) LastDecl = I;\n        break;\n      }\n    }\n  }\n\n  \/\/ Mark that D is no longer in the decl chain.\n  D->NextInContextAndBits.setPointer(nullptr);\n\n  \/\/ Remove D from the lookup table if necessary.\n  if (isa<NamedDecl>(D)) {\n    auto *ND = cast<NamedDecl>(D);\n\n    \/\/ Do not try to remove the declaration if that is invisible to qualified\n    \/\/ lookup.  E.g. template specializations are skipped.\n    if (shouldBeHidden(ND))\n      return;\n\n    \/\/ Remove only decls that have a name\n    if (!ND->getDeclName())\n      return;\n\n    auto *DC = D->getDeclContext();\n    do {\n      StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;\n      if (Map) {\n        StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());\n        assert(Pos != Map->end() && \"no lookup entry for decl\");\n        \/\/ Remove the decl only if it is contained.\n        StoredDeclsList::DeclsTy *Vec = Pos->second.getAsVector();\n        if ((Vec && is_contained(*Vec, ND)) || Pos->second.getAsDecl() == ND)\n          Pos->second.remove(ND);\n      }\n    } while (DC->isTransparentContext() && (DC = DC->getParent()));\n  }\n}\n\nvoid DeclContext::addHiddenDecl(Decl *D) {\n  assert(D->getLexicalDeclContext() == this &&\n         \"Decl inserted into wrong lexical context\");\n  assert(!D->getNextDeclInContext() && D != LastDecl &&\n         \"Decl already inserted into a DeclContext\");\n\n  if (FirstDecl) {\n    LastDecl->NextInContextAndBits.setPointer(D);\n    LastDecl = D;\n  } else {\n    FirstDecl = LastDecl = D;\n  }\n\n  \/\/ Notify a C++ record declaration that we've added a member, so it can\n  \/\/ update its class-specific state.\n  if (auto *Record = dyn_cast<CXXRecordDecl>(this))\n    Record->addedMember(D);\n\n  \/\/ If this is a newly-created (not de-serialized) import declaration, wire\n  \/\/ it in to the list of local import declarations.\n  if (!D->isFromASTFile()) {\n    if (auto *Import = dyn_cast<ImportDecl>(D))\n      D->getASTContext().addedLocalImportDecl(Import);\n  }\n}\n\nvoid DeclContext::addDecl(Decl *D) {\n  addHiddenDecl(D);\n\n  if (auto *ND = dyn_cast<NamedDecl>(D))\n    ND->getDeclContext()->getPrimaryContext()->\n        makeDeclVisibleInContextWithFlags(ND, false, true);\n}\n\nvoid DeclContext::addDeclInternal(Decl *D) {\n  addHiddenDecl(D);\n\n  if (auto *ND = dyn_cast<NamedDecl>(D))\n    ND->getDeclContext()->getPrimaryContext()->\n        makeDeclVisibleInContextWithFlags(ND, true, true);\n}\n\n\/\/\/ buildLookup - Build the lookup data structure with all of the\n\/\/\/ declarations in this DeclContext (and any other contexts linked\n\/\/\/ to it or transparent contexts nested within it) and return it.\n\/\/\/\n\/\/\/ Note that the produced map may miss out declarations from an\n\/\/\/ external source. If it does, those entries will be marked with\n\/\/\/ the 'hasExternalDecls' flag.\nStoredDeclsMap *DeclContext::buildLookup() {\n  assert(this == getPrimaryContext() && \"buildLookup called on non-primary DC\");\n\n  if (!hasLazyLocalLexicalLookups() &&\n      !hasLazyExternalLexicalLookups())\n    return LookupPtr;\n\n  SmallVector<DeclContext *, 2> Contexts;\n  collectAllContexts(Contexts);\n\n  if (hasLazyExternalLexicalLookups()) {\n    setHasLazyExternalLexicalLookups(false);\n    for (auto *DC : Contexts) {\n      if (DC->hasExternalLexicalStorage()) {\n        bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();\n        setHasLazyLocalLexicalLookups(\n            hasLazyLocalLexicalLookups() | LoadedDecls );\n      }\n    }\n\n    if (!hasLazyLocalLexicalLookups())\n      return LookupPtr;\n  }\n\n  for (auto *DC : Contexts)\n    buildLookupImpl(DC, hasExternalVisibleStorage());\n\n  \/\/ We no longer have any lazy decls.\n  setHasLazyLocalLexicalLookups(false);\n  return LookupPtr;\n}\n\n\/\/\/ buildLookupImpl - Build part of the lookup data structure for the\n\/\/\/ declarations contained within DCtx, which will either be this\n\/\/\/ DeclContext, a DeclContext linked to it, or a transparent context\n\/\/\/ nested within it.\nvoid DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {\n  for (auto *D : DCtx->noload_decls()) {\n    \/\/ Insert this declaration into the lookup structure, but only if\n    \/\/ it's semantically within its decl context. Any other decls which\n    \/\/ should be found in this context are added eagerly.\n    \/\/\n    \/\/ If it's from an AST file, don't add it now. It'll get handled by\n    \/\/ FindExternalVisibleDeclsByName if needed. Exception: if we're not\n    \/\/ in C++, we do not track external visible decls for the TU, so in\n    \/\/ that case we need to collect them all here.\n    if (auto *ND = dyn_cast<NamedDecl>(D))\n      if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&\n          (!ND->isFromASTFile() ||\n           (isTranslationUnit() &&\n            !getParentASTContext().getLangOpts().CPlusPlus)))\n        makeDeclVisibleInContextImpl(ND, Internal);\n\n    \/\/ If this declaration is itself a transparent declaration context\n    \/\/ or inline namespace, add the members of this declaration of that\n    \/\/ context (recursively).\n    if (auto *InnerCtx = dyn_cast<DeclContext>(D))\n      if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())\n        buildLookupImpl(InnerCtx, Internal);\n  }\n}\n\nNamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;\n\nDeclContext::lookup_result\nDeclContext::lookup(DeclarationName Name) const {\n  assert(getDeclKind() != Decl::LinkageSpec &&\n         getDeclKind() != Decl::Export &&\n         \"should not perform lookups into transparent contexts\");\n\n  const DeclContext *PrimaryContext = getPrimaryContext();\n  if (PrimaryContext != this)\n    return PrimaryContext->lookup(Name);\n\n  \/\/ If we have an external source, ensure that any later redeclarations of this\n  \/\/ context have been loaded, since they may add names to the result of this\n  \/\/ lookup (or add external visible storage).\n  ExternalASTSource *Source = getParentASTContext().getExternalSource();\n  if (Source)\n    (void)cast<Decl>(this)->getMostRecentDecl();\n\n  if (hasExternalVisibleStorage()) {\n    assert(Source && \"external visible storage but no external source?\");\n\n    if (hasNeedToReconcileExternalVisibleStorage())\n      reconcileExternalVisibleStorage();\n\n    StoredDeclsMap *Map = LookupPtr;\n\n    if (hasLazyLocalLexicalLookups() ||\n        hasLazyExternalLexicalLookups())\n      \/\/ FIXME: Make buildLookup const?\n      Map = const_cast<DeclContext*>(this)->buildLookup();\n\n    if (!Map)\n      Map = CreateStoredDeclsMap(getParentASTContext());\n\n    \/\/ If we have a lookup result with no external decls, we are done.\n    std::pair<StoredDeclsMap::iterator, bool> R =\n        Map->insert(std::make_pair(Name, StoredDeclsList()));\n    if (!R.second && !R.first->second.hasExternalDecls())\n      return R.first->second.getLookupResult();\n\n    if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {\n      if (StoredDeclsMap *Map = LookupPtr) {\n        StoredDeclsMap::iterator I = Map->find(Name);\n        if (I != Map->end())\n          return I->second.getLookupResult();\n      }\n    }\n\n    return {};\n  }\n\n  StoredDeclsMap *Map = LookupPtr;\n  if (hasLazyLocalLexicalLookups() ||\n      hasLazyExternalLexicalLookups())\n    Map = const_cast<DeclContext*>(this)->buildLookup();\n\n  if (!Map)\n    return {};\n\n  StoredDeclsMap::iterator I = Map->find(Name);\n  if (I == Map->end())\n    return {};\n\n  return I->second.getLookupResult();\n}\n\nDeclContext::lookup_result\nDeclContext::noload_lookup(DeclarationName Name) {\n  assert(getDeclKind() != Decl::LinkageSpec &&\n         getDeclKind() != Decl::Export &&\n         \"should not perform lookups into transparent contexts\");\n\n  DeclContext *PrimaryContext = getPrimaryContext();\n  if (PrimaryContext != this)\n    return PrimaryContext->noload_lookup(Name);\n\n  loadLazyLocalLexicalLookups();\n  StoredDeclsMap *Map = LookupPtr;\n  if (!Map)\n    return {};\n\n  StoredDeclsMap::iterator I = Map->find(Name);\n  return I != Map->end() ? I->second.getLookupResult()\n                         : lookup_result();\n}\n\n\/\/ If we have any lazy lexical declarations not in our lookup map, add them\n\/\/ now. Don't import any external declarations, not even if we know we have\n\/\/ some missing from the external visible lookups.\nvoid DeclContext::loadLazyLocalLexicalLookups() {\n  if (hasLazyLocalLexicalLookups()) {\n    SmallVector<DeclContext *, 2> Contexts;\n    collectAllContexts(Contexts);\n    for (auto *Context : Contexts)\n      buildLookupImpl(Context, hasExternalVisibleStorage());\n    setHasLazyLocalLexicalLookups(false);\n  }\n}\n\nvoid DeclContext::localUncachedLookup(DeclarationName Name,\n                                      SmallVectorImpl<NamedDecl *> &Results) {\n  Results.clear();\n\n  \/\/ If there's no external storage, just perform a normal lookup and copy\n  \/\/ the results.\n  if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {\n    lookup_result LookupResults = lookup(Name);\n    Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());\n    return;\n  }\n\n  \/\/ If we have a lookup table, check there first. Maybe we'll get lucky.\n  \/\/ FIXME: Should we be checking these flags on the primary context?\n  if (Name && !hasLazyLocalLexicalLookups() &&\n      !hasLazyExternalLexicalLookups()) {\n    if (StoredDeclsMap *Map = LookupPtr) {\n      StoredDeclsMap::iterator Pos = Map->find(Name);\n      if (Pos != Map->end()) {\n        Results.insert(Results.end(),\n                       Pos->second.getLookupResult().begin(),\n                       Pos->second.getLookupResult().end());\n        return;\n      }\n    }\n  }\n\n  \/\/ Slow case: grovel through the declarations in our chain looking for\n  \/\/ matches.\n  \/\/ FIXME: If we have lazy external declarations, this will not find them!\n  \/\/ FIXME: Should we CollectAllContexts and walk them all here?\n  for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {\n    if (auto *ND = dyn_cast<NamedDecl>(D))\n      if (ND->getDeclName() == Name)\n        Results.push_back(ND);\n  }\n}\n\nDeclContext *DeclContext::getRedeclContext() {\n  DeclContext *Ctx = this;\n\n  \/\/ In C, a record type is the redeclaration context for its fields only. If\n  \/\/ we arrive at a record context after skipping anything else, we should skip\n  \/\/ the record as well. Currently, this means skipping enumerations because\n  \/\/ they're the only transparent context that can exist within a struct or\n  \/\/ union.\n  bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&\n                     !getParentASTContext().getLangOpts().CPlusPlus;\n\n  \/\/ Skip through contexts to get to the redeclaration context. Transparent\n  \/\/ contexts are always skipped.\n  while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext())\n    Ctx = Ctx->getParent();\n  return Ctx;\n}\n\nDeclContext *DeclContext::getEnclosingNamespaceContext() {\n  DeclContext *Ctx = this;\n  \/\/ Skip through non-namespace, non-translation-unit contexts.\n  while (!Ctx->isFileContext())\n    Ctx = Ctx->getParent();\n  return Ctx->getPrimaryContext();\n}\n\nRecordDecl *DeclContext::getOuterLexicalRecordContext() {\n  \/\/ Loop until we find a non-record context.\n  RecordDecl *OutermostRD = nullptr;\n  DeclContext *DC = this;\n  while (DC->isRecord()) {\n    OutermostRD = cast<RecordDecl>(DC);\n    DC = DC->getLexicalParent();\n  }\n  return OutermostRD;\n}\n\nbool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {\n  \/\/ For non-file contexts, this is equivalent to Equals.\n  if (!isFileContext())\n    return O->Equals(this);\n\n  do {\n    if (O->Equals(this))\n      return true;\n\n    const auto *NS = dyn_cast<NamespaceDecl>(O);\n    if (!NS || !NS->isInline())\n      break;\n    O = NS->getParent();\n  } while (O);\n\n  return false;\n}\n\nvoid DeclContext::makeDeclVisibleInContext(NamedDecl *D) {\n  DeclContext *PrimaryDC = this->getPrimaryContext();\n  DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();\n  \/\/ If the decl is being added outside of its semantic decl context, we\n  \/\/ need to ensure that we eagerly build the lookup information for it.\n  PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);\n}\n\nvoid DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,\n                                                    bool Recoverable) {\n  assert(this == getPrimaryContext() && \"expected a primary DC\");\n\n  if (!isLookupContext()) {\n    if (isTransparentContext())\n      getParent()->getPrimaryContext()\n        ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);\n    return;\n  }\n\n  \/\/ Skip declarations which should be invisible to name lookup.\n  if (shouldBeHidden(D))\n    return;\n\n  \/\/ If we already have a lookup data structure, perform the insertion into\n  \/\/ it. If we might have externally-stored decls with this name, look them\n  \/\/ up and perform the insertion. If this decl was declared outside its\n  \/\/ semantic context, buildLookup won't add it, so add it now.\n  \/\/\n  \/\/ FIXME: As a performance hack, don't add such decls into the translation\n  \/\/ unit unless we're in C++, since qualified lookup into the TU is never\n  \/\/ performed.\n  if (LookupPtr || hasExternalVisibleStorage() ||\n      ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&\n       (getParentASTContext().getLangOpts().CPlusPlus ||\n        !isTranslationUnit()))) {\n    \/\/ If we have lazily omitted any decls, they might have the same name as\n    \/\/ the decl which we are adding, so build a full lookup table before adding\n    \/\/ this decl.\n    buildLookup();\n    makeDeclVisibleInContextImpl(D, Internal);\n  } else {\n    setHasLazyLocalLexicalLookups(true);\n  }\n\n  \/\/ If we are a transparent context or inline namespace, insert into our\n  \/\/ parent context, too. This operation is recursive.\n  if (isTransparentContext() || isInlineNamespace())\n    getParent()->getPrimaryContext()->\n        makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);\n\n  auto *DCAsDecl = cast<Decl>(this);\n  \/\/ Notify that a decl was made visible unless we are a Tag being defined.\n  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))\n    if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())\n      L->AddedVisibleDecl(this, D);\n}\n\nvoid DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {\n  \/\/ Find or create the stored declaration map.\n  StoredDeclsMap *Map = LookupPtr;\n  if (!Map) {\n    ASTContext *C = &getParentASTContext();\n    Map = CreateStoredDeclsMap(*C);\n  }\n\n  \/\/ If there is an external AST source, load any declarations it knows about\n  \/\/ with this declaration's name.\n  \/\/ If the lookup table contains an entry about this name it means that we\n  \/\/ have already checked the external source.\n  if (!Internal)\n    if (ExternalASTSource *Source = getParentASTContext().getExternalSource())\n      if (hasExternalVisibleStorage() &&\n          Map->find(D->getDeclName()) == Map->end())\n        Source->FindExternalVisibleDeclsByName(this, D->getDeclName());\n\n  \/\/ Insert this declaration into the map.\n  StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];\n\n  if (Internal) {\n    \/\/ If this is being added as part of loading an external declaration,\n    \/\/ this may not be the only external declaration with this name.\n    \/\/ In this case, we never try to replace an existing declaration; we'll\n    \/\/ handle that when we finalize the list of declarations for this name.\n    DeclNameEntries.setHasExternalDecls();\n    DeclNameEntries.AddSubsequentDecl(D);\n    return;\n  }\n\n  if (DeclNameEntries.isNull()) {\n    DeclNameEntries.setOnlyValue(D);\n    return;\n  }\n\n  if (DeclNameEntries.HandleRedeclaration(D, \/*IsKnownNewer*\/!Internal)) {\n    \/\/ This declaration has replaced an existing one for which\n    \/\/ declarationReplaces returns true.\n    return;\n  }\n\n  \/\/ Put this declaration into the appropriate slot.\n  DeclNameEntries.AddSubsequentDecl(D);\n}\n\nUsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {\n  return cast<UsingDirectiveDecl>(*I);\n}\n\n\/\/\/ Returns iterator range [First, Last) of UsingDirectiveDecls stored within\n\/\/\/ this context.\nDeclContext::udir_range DeclContext::using_directives() const {\n  \/\/ FIXME: Use something more efficient than normal lookup for using\n  \/\/ directives. In C++, using directives are looked up more than anything else.\n  lookup_result Result = lookup(UsingDirectiveDecl::getName());\n  return udir_range(Result.begin(), Result.end());\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Creation and Destruction of StoredDeclsMaps.                               \/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\nStoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {\n  assert(!LookupPtr && \"context already has a decls map\");\n  assert(getPrimaryContext() == this &&\n         \"creating decls map on non-primary context\");\n\n  StoredDeclsMap *M;\n  bool Dependent = isDependentContext();\n  if (Dependent)\n    M = new DependentStoredDeclsMap();\n  else\n    M = new StoredDeclsMap();\n  M->Previous = C.LastSDM;\n  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);\n  LookupPtr = M;\n  return M;\n}\n\nvoid ASTContext::ReleaseDeclContextMaps() {\n  \/\/ It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap\n  \/\/ pointer because the subclass doesn't add anything that needs to\n  \/\/ be deleted.\n  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());\n}\n\nvoid StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {\n  while (Map) {\n    \/\/ Advance the iteration before we invalidate memory.\n    llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;\n\n    if (Dependent)\n      delete static_cast<DependentStoredDeclsMap*>(Map);\n    else\n      delete Map;\n\n    Map = Next.getPointer();\n    Dependent = Next.getInt();\n  }\n}\n\nDependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,\n                                                 DeclContext *Parent,\n                                           const PartialDiagnostic &PDiag) {\n  assert(Parent->isDependentContext()\n         && \"cannot iterate dependent diagnostics of non-dependent context\");\n  Parent = Parent->getPrimaryContext();\n  if (!Parent->LookupPtr)\n    Parent->CreateStoredDeclsMap(C);\n\n  auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);\n\n  \/\/ Allocate the copy of the PartialDiagnostic via the ASTContext's\n  \/\/ BumpPtrAllocator, rather than the ASTContext itself.\n  PartialDiagnostic::Storage *DiagStorage = nullptr;\n  if (PDiag.hasStorage())\n    DiagStorage = new (C) PartialDiagnostic::Storage;\n\n  auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);\n\n  \/\/ TODO: Maybe we shouldn't reverse the order during insertion.\n  DD->NextDiagnostic = Map->FirstDiagnostic;\n  Map->FirstDiagnostic = DD;\n\n  return DD;\n}\n","avg_line_length":31.6064744562,"max_line_length":81,"alphanum_fraction":0.6637166725,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4795,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/**\n *****************************************************************************\n * @author     This file is part of libff, developed by SCIPR Lab\n *             and contributors (see AUTHORS).\n * @copyright  MIT license (see LICENSE file)\n *****************************************************************************\/\n#include <libff\/algebra\/curves\/edwards\/edwards_pp.hpp>\n#include <libff\/common\/profiling.hpp>\n#ifdef CURVE_BN128\n#include <libff\/algebra\/curves\/bn128\/bn128_pp.hpp>\n#include <libff\/algebra\/curves\/bn128\/bn128_pp.hpp>\n#endif\n#include <libff\/algebra\/curves\/alt_bn128\/alt_bn128_pp.hpp>\n#include <libff\/algebra\/curves\/bls12_381\/bls12_381_pp.hpp>\n#include <libff\/algebra\/curves\/mnt\/mnt4\/mnt4_pp.hpp>\n#include <libff\/algebra\/curves\/mnt\/mnt6\/mnt6_pp.hpp>\n\nusing namespace libff;\n\n#ifndef NDEBUG\ntemplate<typename ppT>\nvoid pairing_test()\n{\n    GT<ppT> GT_one = GT<ppT>::one();\n\n    printf(\"Running bilinearity tests:\\n\");\n    G1<ppT> P = (Fr<ppT>::random_element()) * G1<ppT>::one();\n    \/\/G1<ppT> P = Fr<ppT>(\"2\") * G1<ppT>::one();\n    G2<ppT> Q = (Fr<ppT>::random_element()) * G2<ppT>::one();\n    \/\/G2<ppT> Q = Fr<ppT>(\"3\") * G2<ppT>::one();\n\n    printf(\"P:\\n\");\n    P.print();\n    P.print_coordinates();\n    printf(\"Q:\\n\");\n    Q.print();\n    Q.print_coordinates();\n    printf(\"\\n\\n\");\n\n    Fr<ppT> s = Fr<ppT>::random_element();\n    \/\/Fr<ppT> s = Fr<ppT>(\"2\");\n    G1<ppT> sP = s * P;\n    G2<ppT> sQ = s * Q;\n\n    printf(\"Pairing bilinearity tests (three must match):\\n\");\n    GT<ppT> ans1 = ppT::reduced_pairing(sP, Q);\n    GT<ppT> ans2 = ppT::reduced_pairing(P, sQ);\n    GT<ppT> ans3 = ppT::reduced_pairing(P, Q)^s;\n    ans1.print();\n    ans2.print();\n    ans3.print();\n    assert(ans1 == ans2);\n    assert(ans2 == ans3);\n\n    assert(ans1 != GT_one);\n    assert((ans1^Fr<ppT>::field_char()) == GT_one);\n    printf(\"\\n\\n\");\n    \/\/ Prevent release build warnings\n    UNUSED(GT_one);\n}\n\ntemplate<typename ppT>\nvoid double_miller_loop_test()\n{\n    const G1<ppT> P1 = (Fr<ppT>::random_element()) * G1<ppT>::one();\n    const G1<ppT> P2 = (Fr<ppT>::random_element()) * G1<ppT>::one();\n    const G2<ppT> Q1 = (Fr<ppT>::random_element()) * G2<ppT>::one();\n    const G2<ppT> Q2 = (Fr<ppT>::random_element()) * G2<ppT>::one();\n\n    const G1_precomp<ppT> prec_P1 = ppT::precompute_G1(P1);\n    const G1_precomp<ppT> prec_P2 = ppT::precompute_G1(P2);\n    const G2_precomp<ppT> prec_Q1 = ppT::precompute_G2(Q1);\n    const G2_precomp<ppT> prec_Q2 = ppT::precompute_G2(Q2);\n\n    const Fqk<ppT> ans_1 = ppT::miller_loop(prec_P1, prec_Q1);\n    const Fqk<ppT> ans_2 = ppT::miller_loop(prec_P2, prec_Q2);\n    const Fqk<ppT> ans_12 = ppT::double_miller_loop(prec_P1, prec_Q1, prec_P2, prec_Q2);\n    assert(ans_1 * ans_2 == ans_12);\n    \/\/ Prevent release build warnings\n    UNUSED(ans_1);\n    UNUSED(ans_2);\n    UNUSED(ans_12);\n}\n\ntemplate<typename ppT>\nvoid affine_pairing_test()\n{\n    GT<ppT> GT_one = GT<ppT>::one();\n\n    printf(\"Running bilinearity tests:\\n\");\n    G1<ppT> P = (Fr<ppT>::random_element()) * G1<ppT>::one();\n    G2<ppT> Q = (Fr<ppT>::random_element()) * G2<ppT>::one();\n\n    printf(\"P:\\n\");\n    P.print();\n    printf(\"Q:\\n\");\n    Q.print();\n    printf(\"\\n\\n\");\n\n    Fr<ppT> s = Fr<ppT>::random_element();\n    G1<ppT> sP = s * P;\n    G2<ppT> sQ = s * Q;\n\n    printf(\"Pairing bilinearity tests (three must match):\\n\");\n    GT<ppT> ans1 = ppT::affine_reduced_pairing(sP, Q);\n    GT<ppT> ans2 = ppT::affine_reduced_pairing(P, sQ);\n    GT<ppT> ans3 = ppT::affine_reduced_pairing(P, Q)^s;\n    ans1.print();\n    ans2.print();\n    ans3.print();\n    assert(ans1 == ans2);\n    assert(ans2 == ans3);\n\n    assert(ans1 != GT_one);\n    assert((ans1^Fr<ppT>::field_char()) == GT_one);\n    printf(\"\\n\\n\");\n    \/\/ Prevent release build warnings\n    UNUSED(GT_one);\n}\n\nint main(void)\n{\n    start_profiling();\n    edwards_pp::init_public_params();\n    pairing_test<edwards_pp>();\n    double_miller_loop_test<edwards_pp>();\n\n    mnt6_pp::init_public_params();\n    pairing_test<mnt6_pp>();\n    double_miller_loop_test<mnt6_pp>();\n    affine_pairing_test<mnt6_pp>();\n\n    mnt4_pp::init_public_params();\n    pairing_test<mnt4_pp>();\n    double_miller_loop_test<mnt4_pp>();\n    affine_pairing_test<mnt4_pp>();\n\n    alt_bn128_pp::init_public_params();\n    pairing_test<alt_bn128_pp>();\n    double_miller_loop_test<alt_bn128_pp>();\n\n    bls12_381_pp::init_public_params();\n    pairing_test<bls12_381_pp>();\n    double_miller_loop_test<bls12_381_pp>();\n\n\/\/ BN128 has fancy dependencies so it may be disabled\n#ifdef CURVE_BN128\n    bn128_pp::init_public_params();\n    pairing_test<bn128_pp>();\n    double_miller_loop_test<bn128_pp>();\n#endif\n}\n\n#else \/\/ NDEBUG\n\nint main()\n{\n    printf(\"All tests here depend on assert() which is disabled by -DNDEBUG. Please recompile and run again.\\n\");\n}\n#endif \/\/ NDEBUG\n","avg_line_length":29.7826086957,"max_line_length":113,"alphanum_fraction":0.6223149114,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1713,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":2.0,"content":"\/*******************************************************************************\n * Copyright 2017 Samsung Electronics All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *******************************************************************************\/\n\n#include \"EZMQAPI.h\"\n#include \"UnitTestHelper.h\"\n\nusing namespace ezmq;\n\nclass EZMQAPITest: public TestWithMock\n{\nprotected:\n    void SetUp()\n    {\n        TestWithMock::SetUp();\n    }\n\n    void TearDown()\n    {\n        TestWithMock::TearDown();\n    }\n};\n\nTEST_F(EZMQAPITest, getEZMQInstance)\n{\n    EZMQAPI *obj = EZMQAPI::getInstance();\n    EXPECT_EQ(EZMQ_Constructed, obj->getStatus());\n    ASSERT_NE(nullptr, obj);\n}\n\nTEST_F(EZMQAPITest, initialize)\n{\n    EZMQAPI *obj = EZMQAPI::getInstance();\n    EXPECT_EQ(EZMQ_OK, obj->initialize());\n}\n\nTEST_F(EZMQAPITest, terminate)\n{\n    EZMQAPI *obj = EZMQAPI::getInstance();\n    EXPECT_EQ(EZMQ_OK, obj->initialize());\n    EXPECT_EQ(EZMQ_OK, obj->terminate());\n}\n\nTEST_F(EZMQAPITest, getStatus)\n{\n    EZMQAPI *obj = EZMQAPI::getInstance();\n    obj->initialize();\n    EXPECT_EQ(EZMQ_Initialized, obj->getStatus());\n    obj->terminate();\n    EXPECT_EQ(EZMQ_Terminated, obj->getStatus());\n}\n\n","avg_line_length":25.9545454545,"max_line_length":81,"alphanum_fraction":0.6322241681,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":1755,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":194.0,"content":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC.\n\/\/ Produced at the Lawrence Livermore National Laboratory.\n\/\/ Written by the LBANN Research Team (B. Van Essen, et al.) listed in\n\/\/ the CONTRIBUTORS file. <lbann-dev@llnl.gov>\n\/\/\n\/\/ LLNL-CODE-697807.\n\/\/ All rights reserved.\n\/\/\n\/\/ This file is part of LBANN: Livermore Big Artificial Neural Network\n\/\/ Toolkit. For details, see http:\/\/software.llnl.gov\/LBANN or\n\/\/ https:\/\/github.com\/LLNL\/LBANN.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"Licensee\"); you\n\/\/ may not use this file except in compliance with the License.  You may\n\/\/ obtain a copy of the License at:\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the license.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"lbann\/utils\/serialize.hpp\"\n#include <lbann\/layers\/transform\/reshape.hpp>\n\nnamespace lbann {\n\ntemplate <typename TensorDataType, data_layout Layout, El::Device Device>\ntemplate <typename ArchiveT>\nvoid\nreshape_layer<TensorDataType,Layout,Device>\n::serialize(ArchiveT& ar) {\n  using DataTypeLayer = data_type_layer<TensorDataType>;\n  ar(::cereal::make_nvp(\"DataTypeLayer\",\n                        ::cereal::base_class<DataTypeLayer>(this)));\n}\n\n} \/\/ namespace lbann\n\n#define LBANN_LAYER_NAME reshape_layer\n#include <lbann\/macros\/register_layer_with_cereal.hpp>\n","avg_line_length":39.0,"max_line_length":80,"alphanum_fraction":0.6786324786,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":647,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/\n\/\/ executor.cpp\n\/\/ ~~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n\n\/\/ Disable autolinking for unit tests.\n#if !defined(BOOST_ALL_NO_LIB)\n#define BOOST_ALL_NO_LIB 1\n#endif \/\/ !defined(BOOST_ALL_NO_LIB)\n\n\/\/ Test that header file is self-contained.\n#include \"..\/..\/..\/..\/..\/asio\/asio\/include\/asio\/executor.hpp\"\n\n#include \"..\/..\/..\/..\/..\/asio\/asio\/src\/tests\/unit\/unit_test.hpp\"\n\nASIO_TEST_SUITE\n(\n  \"executor\",\n  ASIO_TEST_CASE(null_test)\n)\n","avg_line_length":24.8846153846,"max_line_length":79,"alphanum_fraction":0.6939721793,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":4506,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":4.0,"content":"\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrDistanceFieldAdjustTable.h\"\n\n#include \"SkScalerContext.h\"\n\nSkDEBUGCODE(static const int kExpectedDistanceAdjustTableSize = 8;)\n\nSkScalar* build_distance_adjust_table(SkScalar paintGamma, SkScalar deviceGamma) {\n    \/\/ This is used for an approximation of the mask gamma hack, used by raster and bitmap\n    \/\/ text. The mask gamma hack is based off of guessing what the blend color is going to\n    \/\/ be, and adjusting the mask so that when run through the linear blend will\n    \/\/ produce the value closest to the desired result. However, in practice this means\n    \/\/ that the 'adjusted' mask is just increasing or decreasing the coverage of\n    \/\/ the mask depending on what it is thought it will blit against. For black (on\n    \/\/ assumed white) this means that coverages are decreased (on a curve). For white (on\n    \/\/ assumed black) this means that coverages are increased (on a a curve). At\n    \/\/ middle (perceptual) gray (which could be blit against anything) the coverages\n    \/\/ remain the same.\n    \/\/\n    \/\/ The idea here is that instead of determining the initial (real) coverage and\n    \/\/ then adjusting that coverage, we determine an adjusted coverage directly by\n    \/\/ essentially manipulating the geometry (in this case, the distance to the glyph\n    \/\/ edge). So for black (on assumed white) this thins a bit; for white (on\n    \/\/ assumed black) this fake bolds the geometry a bit.\n    \/\/\n    \/\/ The distance adjustment is calculated by determining the actual coverage value which\n    \/\/ when fed into in the mask gamma table gives us an 'adjusted coverage' value of 0.5. This\n    \/\/ actual coverage value (assuming it's between 0 and 1) corresponds to a distance from the\n    \/\/ actual edge. So by subtracting this distance adjustment and computing without the\n    \/\/ the coverage adjustment we should get 0.5 coverage at the same point.\n    \/\/\n    \/\/ This has several implications:\n    \/\/     For non-gray lcd smoothed text, each subpixel essentially is using a\n    \/\/     slightly different geometry.\n    \/\/\n    \/\/     For black (on assumed white) this may not cover some pixels which were\n    \/\/     previously covered; however those pixels would have been only slightly\n    \/\/     covered and that slight coverage would have been decreased anyway. Also, some pixels\n    \/\/     which were previously fully covered may no longer be fully covered.\n    \/\/\n    \/\/     For white (on assumed black) this may cover some pixels which weren't\n    \/\/     previously covered at all.\n\n    int width, height;\n    size_t size;\n\n#ifdef SK_GAMMA_CONTRAST\n    SkScalar contrast = SK_GAMMA_CONTRAST;\n#else\n    SkScalar contrast = 0.5f;\n#endif\n\n    size = SkScalerContext::GetGammaLUTSize(contrast, paintGamma, deviceGamma,\n        &width, &height);\n\n    SkASSERT(kExpectedDistanceAdjustTableSize == height);\n    SkScalar* table = new SkScalar[height];\n\n    SkAutoTArray<uint8_t> data((int)size);\n    SkScalerContext::GetGammaLUTData(contrast, paintGamma, deviceGamma, data.get());\n\n    \/\/ find the inverse points where we cross 0.5\n    \/\/ binsearch might be better, but we only need to do this once on creation\n    for (int row = 0; row < height; ++row) {\n        uint8_t* rowPtr = data.get() + row*width;\n        for (int col = 0; col < width - 1; ++col) {\n            if (rowPtr[col] <= 127 && rowPtr[col + 1] >= 128) {\n                \/\/ compute point where a mask value will give us a result of 0.5\n                float interp = (127.5f - rowPtr[col]) \/ (rowPtr[col + 1] - rowPtr[col]);\n                float borderAlpha = (col + interp) \/ 255.f;\n\n                \/\/ compute t value for that alpha\n                \/\/ this is an approximate inverse for smoothstep()\n                float t = borderAlpha*(borderAlpha*(4.0f*borderAlpha - 6.0f) + 5.0f) \/ 3.0f;\n\n                \/\/ compute distance which gives us that t value\n                const float kDistanceFieldAAFactor = 0.65f; \/\/ should match SK_DistanceFieldAAFactor\n                float d = 2.0f*kDistanceFieldAAFactor*t - kDistanceFieldAAFactor;\n\n                table[row] = d;\n                break;\n            }\n        }\n    }\n\n    return table;\n}\n\nvoid GrDistanceFieldAdjustTable::buildDistanceAdjustTables() {\n    fTable = build_distance_adjust_table(SK_GAMMA_EXPONENT, SK_GAMMA_EXPONENT);\n    fGammaCorrectTable = build_distance_adjust_table(SK_Scalar1, SK_Scalar1);\n}\n","avg_line_length":45.5151515152,"max_line_length":100,"alphanum_fraction":0.6788726143,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":21164,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":17.0,"content":"\/\/ FB Alpha Momoko 120% driver module\n\/\/ Based on MAME driver by Uki\n\n#include \"tiles_generic.h\"\n#include \"z80_intf.h\"\n#include \"burn_ym2203.h\"\n\nstatic UINT8 *AllMem;\nstatic UINT8 *MemEnd;\nstatic UINT8 *AllRam;\nstatic UINT8 *RamEnd;\nstatic UINT8 *DrvZ80ROM0;\nstatic UINT8 *DrvZ80ROM1;\nstatic UINT8 *DrvGfxROM0;\nstatic UINT8 *DrvGfxROM1;\nstatic UINT8 *DrvGfxROM1a;\nstatic UINT8 *DrvGfxROM2;\nstatic UINT8 *DrvGfxROM3;\nstatic UINT8 *DrvBankROM;\nstatic UINT8 *DrvBgCPROM;\nstatic UINT8 *DrvFgMPROM;\nstatic UINT8 *DrvColPROM;\nstatic UINT8 *DrvZ80RAM0;\nstatic UINT8 *DrvZ80RAM1;\nstatic UINT8 *DrvSprRAM;\nstatic UINT8 *DrvPalRAM;\nstatic UINT8 *DrvVidRAM;\n\nstatic UINT8 *DrvTransTab[4];\n\nstatic UINT32 *DrvPalette;\nstatic UINT8 DrvRecalc;\n\nstatic UINT8 *soundlatch;\nstatic UINT8 *flipscreen;\nstatic UINT8 *fg_scrolly;\nstatic UINT8 *fg_scrollx;\nstatic UINT8 *fg_select;\nstatic UINT8 *tx_scrolly;\nstatic UINT8 *tx_mode;\nstatic UINT8 *bg_scrolly;\nstatic UINT8 *bg_scrollx;\nstatic UINT8 *bg_select;\nstatic UINT8 *bg_priority;\nstatic UINT8 *bg_bank;\n\nstatic INT32 watchdog;\n\nstatic UINT8 DrvJoy1[8];\nstatic UINT8 DrvJoy2[8];\nstatic UINT8 DrvJoy3[8];\nstatic UINT8 DrvDips[3];\nstatic UINT8 DrvInputs[3];\nstatic UINT8 DrvReset;\n\nstatic struct BurnInputInfo MomokoInputList[] = {\n\t{\"P1 Coin\",\t\tBIT_DIGITAL,\tDrvJoy3 + 7,\t\"p1 coin\"\t},\n\t{\"P1 Start\",\t\tBIT_DIGITAL,\tDrvJoy1 + 6,\t\"p1 start\"\t},\n\t{\"P1 Up\",\t\tBIT_DIGITAL,\tDrvJoy1 + 0,\t\"p1 up\"\t\t},\n\t{\"P1 Down\",\t\tBIT_DIGITAL,\tDrvJoy1 + 1,\t\"p1 down\"\t},\n\t{\"P1 Left\",\t\tBIT_DIGITAL,\tDrvJoy1 + 3,\t\"p1 left\"\t},\n\t{\"P1 Right\",\t\tBIT_DIGITAL,\tDrvJoy1 + 2,\t\"p1 right\"\t},\n\t{\"P1 Button 1\",\t\tBIT_DIGITAL,\tDrvJoy1 + 4,\t\"p1 fire 1\"\t},\n\t{\"P1 Button 2\",\t\tBIT_DIGITAL,\tDrvJoy1 + 5,\t\"p1 fire 2\"\t},\n\n\t{\"P2 Start\",\t\tBIT_DIGITAL,\tDrvJoy1 + 7,\t\"p2 start\"\t},\n\t{\"P2 Up\",\t\tBIT_DIGITAL,\tDrvJoy2 + 0,\t\"p2 up\"\t\t},\n\t{\"P2 Down\",\t\tBIT_DIGITAL,\tDrvJoy2 + 1,\t\"p2 down\"\t},\n\t{\"P2 Left\",\t\tBIT_DIGITAL,\tDrvJoy2 + 3,\t\"p2 left\"\t},\n\t{\"P2 Right\",\t\tBIT_DIGITAL,\tDrvJoy2 + 2,\t\"p2 right\"\t},\n\t{\"P2 Button 1\",\t\tBIT_DIGITAL,\tDrvJoy2 + 4,\t\"p2 fire 1\"\t},\n\t{\"P2 Button 2\",\t\tBIT_DIGITAL,\tDrvJoy2 + 5,\t\"p2 fire 2\"\t},\n\n\t{\"Reset\",\t\tBIT_DIGITAL,\t&DrvReset,\t\"reset\"\t\t},\n\t{\"Dip A\",\t\tBIT_DIPSWITCH,\tDrvDips + 0,\t\"dip\"\t\t},\n\t{\"Dip B\",\t\tBIT_DIPSWITCH,\tDrvDips + 1,\t\"dip\"\t\t},\n\t{\"Dip C\",\t\tBIT_DIPSWITCH,\tDrvDips + 2,\t\"dip\"\t\t},\n};\n\nSTDINPUTINFO(Momoko)\n\nstatic struct BurnDIPInfo MomokoDIPList[]=\n{\n\t{0x10, 0xff, 0xff, 0x7f, NULL\t\t\t},\n\t{0x11, 0xff, 0xff, 0xef, NULL\t\t\t},\n\t{0x12, 0xff, 0xff, 0x00, NULL\t\t\t},\n\n\t{0   , 0xfe, 0   ,    4, \"Lives\"\t\t},\n\t{0x10, 0x01, 0x03, 0x03, \"3\"\t\t\t},\n\t{0x10, 0x01, 0x03, 0x02, \"4\"\t\t\t},\n\t{0x10, 0x01, 0x03, 0x01, \"5\"\t\t\t},\n\t{0x10, 0x01, 0x03, 0x00, \"255 (Cheat)\"\t\t},\n\n\t{0   , 0xfe, 0   ,    8, \"Coinage\"\t\t},\n\t{0x10, 0x01, 0x1c, 0x10, \"5 Coins 1 Credits\"\t},\n\t{0x10, 0x01, 0x1c, 0x14, \"3 Coins 1 Credits\"\t},\n\t{0x10, 0x01, 0x1c, 0x18, \"2 Coins 1 Credits\"\t},\n\t{0x10, 0x01, 0x1c, 0x1c, \"1 Coin  1 Credits\"\t},\n\t{0x10, 0x01, 0x1c, 0x0c, \"1 Coin  2 Credits\"\t},\n\t{0x10, 0x01, 0x1c, 0x04, \"2 Coins 5 Credits\"\t},\n\t{0x10, 0x01, 0x1c, 0x08, \"1 Coin  5 Credits\"\t},\n\t{0x10, 0x01, 0x1c, 0x00, \"Free Play\"\t\t},\n\n\t{0   , 0xfe, 0   ,    4, \"Difficulty\"\t\t},\n\t{0x10, 0x01, 0x60, 0x40, \"Easy\"\t\t\t},\n\t{0x10, 0x01, 0x60, 0x60, \"Normal\"\t\t},\n\t{0x10, 0x01, 0x60, 0x20, \"Hard\"\t\t\t},\n\t{0x10, 0x01, 0x60, 0x00, \"Hardest\"\t\t},\n\n\t{0   , 0xfe, 0   ,    4, \"Bonus Life\"\t\t},\n\t{0x11, 0x01, 0x03, 0x01, \"20k\"\t\t\t},\n\t{0x11, 0x01, 0x03, 0x03, \"30k\"\t\t\t},\n\t{0x11, 0x01, 0x03, 0x02, \"50k\"\t\t\t},\n\t{0x11, 0x01, 0x03, 0x00, \"100k\"\t\t\t},\n\n\/\/\t{0   , 0xfe, 0   ,    2, \"Cabinet\"\t\t},\n\/\/\t{0x11, 0x01, 0x10, 0x00, \"Upright\"\t\t},\n\/\/\t{0x11, 0x01, 0x10, 0x10, \"Cocktail\"\t\t},\n\n\t{0   , 0xfe, 0   ,    2, \"Demo Sounds\"\t\t},\n\t{0x11, 0x01, 0x20, 0x00, \"Off\"\t\t\t},\n\t{0x11, 0x01, 0x20, 0x20, \"On\"\t\t\t},\n\n\/\/\t{0   , 0xfe, 0   ,    2, \"Flip Screen (Fake)\"\t},\n\/\/\t{0x12, 0x01, 0x01, 0x00, \"Off\"\t\t\t},\n\/\/\t{0x12, 0x01, 0x01, 0x01, \"On\"\t\t\t},\n};\n\nSTDDIPINFO(Momoko)\n\nstatic inline void palette_write(UINT16 offset)\n{\n\tUINT16 p = DrvPalRAM[offset + 1] + (DrvPalRAM[offset + 0] * 256);\n\n\tINT32 r = (p >> 8) & 0x0f;\n\tINT32 g = (p >> 4) & 0x0f;\n\tINT32 b = (p >> 0) & 0x0f;\n\n\tr |= r << 4;\n\tg |= g << 4;\n\tb |= b << 4;\n\n\tDrvPalette[offset\/2] = BurnHighCol(r, g, b, 0);\n}\n\nstatic void bankswitch(INT32 data)\n{\n\t*bg_bank = data;\n\n\tZetMapArea(0xf000, 0xffff, 0, DrvBankROM + (data & 0x1f) * 0x1000);\n\tZetMapArea(0xf000, 0xffff, 2, DrvBankROM + (data & 0x1f) * 0x1000);\n}\n\nvoid __fastcall momoko_main_write(UINT16 address, UINT8 data)\n{\n\tif ((address & 0xf800) == 0xd800) {\n\t\tDrvPalRAM[(address & 0x3ff)] = data;\n\t\tpalette_write(address & 0x3fe);\n\t\treturn;\n\t}\n\n\tswitch (address)\n\t{\n\t\tcase 0xd402:\n\t\t\t*flipscreen = data & 0x01;\n\t\treturn;\n\n\t\tcase 0xd404:\n\t\t\twatchdog = 0;\n\t\treturn;\n\n\t\tcase 0xd406:\n\t\t\t*soundlatch = data;\n\t\treturn;\n\n\t\tcase 0xdc00:\n\t\t\t*fg_scrolly = data;\n\t\treturn;\n\n\t\tcase 0xdc01:\n\t\t\t*fg_scrollx = data;\n\t\treturn;\n\n\t\tcase 0xdc02:\n\t\t\t*fg_select = data;\n\t\treturn;\n\n\t\tcase 0xe800:\n\t\t\t*tx_scrolly = data;\n\t\treturn;\n\n\t\tcase 0xe801:\n\t\t\t*tx_mode = data;\n\t\treturn;\n\n\t\tcase 0xf000:\n\t\tcase 0xf001:\n\t\t\tbg_scrolly[address & 1] = data;\n\t\treturn;\n\n\t\tcase 0xf002:\n\t\tcase 0xf003:\n\t\t\tbg_scrollx[address & 1] = data;\n\t\treturn;\n\n\t\tcase 0xf004:\n\t\t\tbankswitch(data);\n\t\treturn;\n\n\t\tcase 0xf006:\n\t\t\t*bg_select = data;\n\t\treturn;\n\n\t\tcase 0xf007:\n\t\t\t*bg_priority = data & 0x01;\n\t\treturn;\n\t}\n}\n\nUINT8 __fastcall momoko_main_read(UINT16 address)\n{\n\tswitch (address)\n\t{\n\t\tcase 0xd400:\n\t\t\treturn DrvInputs[0];\n\n\t\tcase 0xd402:\n\t\t\treturn DrvInputs[1];\n\n\t\tcase 0xd406:\n\t\t\treturn (DrvInputs[2] & 0x80) | (DrvDips[0] & 0x7f);\n\n\t\tcase 0xd407:\n\t\t\treturn DrvDips[1];\n\t}\n\n\treturn 0;\n}\n\nvoid __fastcall momoko_sound_write(UINT16 address, UINT8 data)\n{\n\tswitch (address)\n\t{\n\t\tcase 0xa000:\n\t\tcase 0xa001:\n\t\t\tBurnYM2203Write(0, address & 1, data);\n\t\treturn;\n\n\t\tcase 0xc000:\n\t\tcase 0xc001:\n\t\t\tBurnYM2203Write(1, address & 1, data);\n\t\treturn;\n\t}\n}\n\nUINT8 __fastcall momoko_sound_read(UINT16 address)\n{\n\tswitch (address)\n\t{\n\t\tcase 0xa000:\n\t\tcase 0xa001:\n\t\t\treturn BurnYM2203Read(0, address & 1);\n\n\t\tcase 0xc000:\n\t\tcase 0xc001:\n\t\t\treturn BurnYM2203Read(1, address & 1);\n\t}\n\n\treturn 0;\n}\n\nstatic UINT8 momoko_sound_read_port_A(UINT32)\n{\n\treturn *soundlatch;\n}\n\ninline static INT32 DrvSynchroniseStream(INT32 nSoundRate)\n{\n\treturn (INT64)ZetTotalCycles() * nSoundRate \/ 2500000;\n}\n\ninline static double DrvGetTime()\n{\n\treturn (double)ZetTotalCycles() \/ 2500000.0;\n}\n\nstatic INT32 DrvDoReset(INT32 clear)\n{\n\tif (clear) {\n\t\tmemset(AllRam, 0, RamEnd - AllRam);\n\t}\n\n\tZetOpen(0);\n\tZetReset();\n\tZetClose();\n\n\tZetOpen(1);\n\tZetReset();\n\tZetClose();\n\n\tBurnYM2203Reset();\n\n\twatchdog = 0;\n\n\treturn 0;\n}\n\nstatic INT32 MemIndex()\n{\n\tUINT8 *Next; Next = AllMem;\n\n\tDrvZ80ROM0\t\t= Next; Next += 0x00c000;\n\tDrvZ80ROM1\t\t= Next; Next += 0x008000;\n\n\tDrvBankROM\t\t= Next; Next += 0x020000;\n\tDrvBgCPROM\t\t= Next; Next += 0x002000;\n\tDrvFgMPROM\t\t= Next; Next += 0x004000;\n\tDrvColPROM\t\t= Next; Next += 0x000120;\n\n\tDrvGfxROM0\t\t= Next; Next += 0x008000;\n\tDrvGfxROM1\t\t= Next; Next += 0x080000;\n\tDrvGfxROM1a\t\t= Next; Next += 0x020000;\n\tDrvGfxROM2\t\t= Next; Next += 0x008000;\n\tDrvGfxROM3\t\t= Next; Next += 0x040000;\n\n\tDrvTransTab[0]\t\t= Next; Next += 0x008000 \/ 0x08;\n\tDrvTransTab[1]\t\t= Next; Next += 0x000200;\n\tDrvTransTab[2]\t\t= Next; Next += 0x008000 \/ 0x40;\n\tDrvTransTab[3]\t\t= Next; Next += 0x040000 \/ 0x80;\n\n\tDrvPalette\t\t= (UINT32*)Next; Next += 0x0200 * sizeof(UINT32);\n\n\tAllRam\t\t\t= Next;\n\n\tDrvSprRAM\t\t= Next; Next += 0x000100;\n\tDrvZ80RAM0\t\t= Next; Next += 0x001000;\n\tDrvZ80RAM1\t\t= Next; Next += 0x000800;\n\tDrvPalRAM\t\t= Next; Next += 0x000400;\n\tDrvVidRAM\t\t= Next; Next += 0x000400;\n\n\tsoundlatch\t\t= Next; Next += 0x000001;\n\tflipscreen\t\t= Next; Next += 0x000001;\n\n\tfg_scrolly\t\t= Next; Next += 0x000001;\n\tfg_scrollx\t\t= Next; Next += 0x000001;\n\tfg_select\t\t= Next; Next += 0x000001;\n\ttx_scrolly\t\t= Next; Next += 0x000001;\n\ttx_mode\t\t\t= Next; Next += 0x000001;\n\tbg_scrolly\t\t= Next; Next += 0x000002;\n\tbg_scrollx\t\t= Next; Next += 0x000002;\n\tbg_select\t\t= Next; Next += 0x000001;\n\tbg_priority\t\t= Next; Next += 0x000001;\n\tbg_bank\t\t\t= Next; Next += 0x000001;\n\n\tRamEnd\t\t\t= Next;\n\n\tMemEnd\t\t\t= Next;\n\n\treturn 0;\n}\n\nstatic INT32 DrvGfxDecode()\n{\n\tINT32 Planes[4]  = { 4,0,12,8 };\n\tINT32 XOffs0[8]  = { 0, 1, 2, 3, 256*8*8+0, 256*8*8+1, 256*8*8+2, 256*8*8+3 };\n\tINT32 YOffs0[8]  = { STEP8(0, 8) };\n\tINT32 XOffs1[8]  = { 0, 1, 2, 3, 4096*8+0, 4096*8+1, 4096*8+2, 4096*8+3 };\n\tINT32 YOffs1[16] = { STEP16(0, 16) };\n\n\tUINT8 *tmp = (UINT8*)BurnMalloc(0x20000);\n\tif (tmp == NULL) {\n\t\treturn 1;\n\t}\n\n\tmemcpy (tmp, DrvGfxROM0, 0x02000);\n\n\tGfxDecode(0x0200, 2, 8, 8, Planes, XOffs0, YOffs0, 0x040, tmp, DrvGfxROM0);\n\n\tmemcpy (DrvGfxROM1a, DrvGfxROM1, 0x20000);\n\n\tGfxDecode(0x2000, 4, 8, 8, Planes, XOffs1, YOffs1, 0x080, DrvGfxROM1a, DrvGfxROM1);\n\n\tmemcpy (tmp, DrvGfxROM2, 0x02000);\n\n\tGfxDecode(0x0800, 2, 8, 1, Planes, XOffs0, YOffs0, 0x008, tmp, DrvGfxROM2);\n\n\tmemcpy (tmp, DrvGfxROM3, 0x10000);\n\n\tGfxDecode(0x0800, 4, 8, 16, Planes, XOffs1, YOffs1, 0x100, tmp, DrvGfxROM3);\n\n\tBurnFree(tmp);\n\n\treturn 0;\n}\n\nstatic void DrvFillTransTab(INT32 tab, UINT8 *gfx, INT32 len, INT32 size)\n{\n\tmemset (DrvTransTab[tab], 1, len \/ size);\n\n\tfor (INT32 i = 0; i < len; i+= size)\n\t{\n\t\tfor (INT32 j = 0; j < size; j++)\n\t\t{\n\t\t\tif (gfx[i+j])\n\t\t\t{\n\t\t\t\tDrvTransTab[tab][i\/size] = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nstatic void DrvFillTransMask()\n{\n\tfor (INT32 i = 0x100; i < 0x200; i+=0x10) {\n\t\tmemset (DrvTransTab[1] + i + 8, 0xff, 8);\n\t}\n}\n\nstatic INT32 DrvInit()\n{\n\tAllMem = NULL;\n\tMemIndex();\n\tINT32 nLen = MemEnd - (UINT8 *)0;\n\tif ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1;\n\tmemset(AllMem, 0, nLen);\n\tMemIndex();\n\n\t{\n\t\tif (BurnLoadRom(DrvZ80ROM0 + 0x00000,  0, 1)) return 1;\n\t\tif (BurnLoadRom(DrvZ80ROM0 + 0x08000,  1, 1)) return 1;\n\n\t\tif (BurnLoadRom(DrvZ80ROM1 + 0x00000,  2, 1)) return 1;\n\n\t\tif (BurnLoadRom(DrvGfxROM0 + 0x00000,  3, 1)) return 1;\n\n\t\tif (BurnLoadRom(DrvGfxROM2 + 0x00000,  4, 1)) return 1;\n\n\t\tif (BurnLoadRom(DrvGfxROM3 + 0x00001,  5, 2)) return 1;\n\t\tif (BurnLoadRom(DrvGfxROM3 + 0x00000,  6, 2)) return 1;\n\n\t\tif (BurnLoadRom(DrvGfxROM1 + 0x00000,  7, 2)) return 1;\n\t\tif (BurnLoadRom(DrvGfxROM1 + 0x00001,  8, 2)) return 1;\n\t\tif (BurnLoadRom(DrvGfxROM1 + 0x10000,  9, 2)) return 1;\n\t\tif (BurnLoadRom(DrvGfxROM1 + 0x10001, 10, 2)) return 1;\n\n\t\tif (BurnLoadRom(DrvBankROM + 0x00000, 11, 1)) return 1;\n\t\tif (BurnLoadRom(DrvBankROM + 0x08000, 12, 1)) return 1;\n\t\tif (BurnLoadRom(DrvBankROM + 0x10000, 13, 1)) return 1;\n\t\tif (BurnLoadRom(DrvBankROM + 0x18000, 14, 1)) return 1;\n\n\t\tif (BurnLoadRom(DrvBgCPROM + 0x00000, 15, 1)) return 1;\n\n\t\tif (BurnLoadRom(DrvFgMPROM + 0x00000, 16, 1)) return 1;\n\n\t\tif (BurnLoadRom(DrvColPROM + 0x00000, 17, 1)) return 1;\n\t\tif (BurnLoadRom(DrvColPROM + 0x00100, 18, 1)) return 1;\n\n\t\tif (DrvGfxDecode()) return 1;\n\n\t\tDrvFillTransTab(0, DrvGfxROM0, 0x008000, 0x08);\n\t\tDrvFillTransTab(3, DrvGfxROM3, 0x040000, 0x80);\n\t\tDrvFillTransTab(2, DrvGfxROM2, 0x008000, 0x40);\n\t\tDrvFillTransMask();\n\t}\n\n\tZetInit(0);\n\tZetOpen(0);\n\tZetMapArea(0x0000, 0xbfff, 0, DrvZ80ROM0);\n\tZetMapArea(0x0000, 0xbfff, 2, DrvZ80ROM0);\n\tZetMapArea(0xc000, 0xcfff, 0, DrvZ80RAM0);\n\tZetMapArea(0xc000, 0xcfff, 1, DrvZ80RAM0);\n\tZetMapArea(0xc000, 0xcfff, 2, DrvZ80RAM0);\n\tZetMapArea(0xd000, 0xd0ff, 0, DrvSprRAM);\n\tZetMapArea(0xd000, 0xd0ff, 1, DrvSprRAM);\n\tZetMapArea(0xd000, 0xd0ff, 2, DrvSprRAM);\n\tZetMapArea(0xd800, 0xdbff, 0, DrvPalRAM);\n\/\/\tZetMapArea(0xd800, 0xdbff, 1, DrvPalRAM);\n\tZetMapArea(0xd800, 0xdbff, 2, DrvPalRAM);\n\tZetMapArea(0xe000, 0xe3ff, 0, DrvVidRAM);\n\tZetMapArea(0xe000, 0xe3ff, 1, DrvVidRAM);\n\tZetMapArea(0xe000, 0xe3ff, 2, DrvVidRAM);\n\tZetSetWriteHandler(momoko_main_write);\n\tZetSetReadHandler(momoko_main_read);\n\tZetClose();\n\n\tZetInit(1);\n\tZetOpen(1);\n\tZetMapArea(0x0000, 0x7fff, 0, DrvZ80ROM1);\n\tZetMapArea(0x0000, 0x7fff, 2, DrvZ80ROM1);\n\tZetMapArea(0x8000, 0x87ff, 0, DrvZ80RAM1);\n\tZetMapArea(0x8000, 0x87ff, 1, DrvZ80RAM1);\n\tZetMapArea(0x8000, 0x87ff, 2, DrvZ80RAM1);\n\tZetSetWriteHandler(momoko_sound_write);\n\tZetSetReadHandler(momoko_sound_read);\n\tZetClose();\n\n\tBurnYM2203Init(2, 1250000, NULL, DrvSynchroniseStream, DrvGetTime, 0);\n\tBurnYM2203SetPorts(1, momoko_sound_read_port_A, NULL, NULL, NULL);\n\tBurnTimerAttachZet(2500000);\n\tBurnYM2203SetRoute(0, BURN_SND_YM2203_YM2203_ROUTE, 0.40, BURN_SND_ROUTE_BOTH);\n\tBurnYM2203SetRoute(0, BURN_SND_YM2203_AY8910_ROUTE_1, 0.15, BURN_SND_ROUTE_BOTH);\n\tBurnYM2203SetRoute(0, BURN_SND_YM2203_AY8910_ROUTE_2, 0.15, BURN_SND_ROUTE_BOTH);\n\tBurnYM2203SetRoute(0, BURN_SND_YM2203_AY8910_ROUTE_3, 0.15, BURN_SND_ROUTE_BOTH);\n\tBurnYM2203SetRoute(1, BURN_SND_YM2203_YM2203_ROUTE, 0.40, BURN_SND_ROUTE_BOTH);\n\tBurnYM2203SetRoute(1, BURN_SND_YM2203_AY8910_ROUTE_1, 0.15, BURN_SND_ROUTE_BOTH);\n\tBurnYM2203SetRoute(1, BURN_SND_YM2203_AY8910_ROUTE_2, 0.15, BURN_SND_ROUTE_BOTH);\n\tBurnYM2203SetRoute(1, BURN_SND_YM2203_AY8910_ROUTE_3, 0.15, BURN_SND_ROUTE_BOTH);\n\n\tGenericTilesInit();\n\n\tDrvDoReset(1);\n\n\treturn 0;\n}\n\nstatic INT32 DrvExit()\n{\n\tGenericTilesExit();\n\n\tZetExit();\n\n\tBurnYM2203Exit();\n\n\tBurnFree (AllMem);\n\n\treturn 0;\n}\n\nstatic void draw_bg_layer_pri()\n{\n\tINT32 dx   = ~bg_scrollx[0] & 7;\n\tINT32 dy   = ~bg_scrolly[0] & 7;\n\tINT32 rx   = (bg_scrollx[0] + bg_scrollx[1] * 256) >> 3;\n\tINT32 ry   = (bg_scrolly[0] + bg_scrolly[1] * 256) >> 3;\n\tINT32 bank = (*bg_select & 0x0f) * 0x200;\n\n\tfor (INT32 offs = 0; offs < 32 * 32; offs++)\n\t{\n\t\tINT32 sx = (offs & 0x1f);\n\t\tINT32 sy = (offs \/ 0x20);\n\n\t\tINT32 ofst  = (((ry + sy + 2) & 0x3ff) << 7) + ((rx + sx) & 0x7f);\n\t\tINT32 code  = DrvBankROM[ofst] + bank;\n\t\tINT32 color = DrvBgCPROM[code + (*bg_priority * 0x100)];\n\n\t\tif (color & 0x10) continue;\n\n\t\tsx = (sx * 8) + dx - 6 - 8;\n\t\tsy = (sy * 8) + dy + 9 - 16;\n\n\t\tRenderTileTranstab(pTransDraw, DrvGfxROM1, code, ((color&0x0f)<<4)+0x100, 0, sx, sy, 0, 0, 8, 8, DrvTransTab[1]);\n\t}\n}\n\nstatic void draw_bg_layer()\n{\n\tINT32 dx   = ~bg_scrollx[0] & 7;\n\tINT32 dy   = ~bg_scrolly[0] & 7;\n\tINT32 rx   = (bg_scrollx[0] + bg_scrollx[1] * 256) >> 3;\n\tINT32 ry   = (bg_scrolly[0] + bg_scrolly[1] * 256) >> 3;\n\tINT32 bank = (*bg_select & 0x0f) * 0x200;\n\n\tfor (INT32 offs = 0; offs < 32 * 32; offs++)\n\t{\n\t\tINT32 sx = (offs & 0x1f);\n\t\tINT32 sy = (offs \/ 0x20);\n\n\t\tINT32 ofst  = (((ry + sy + 2) & 0x3ff) << 7) + ((rx + sx) & 0x7f);\n\t\tINT32 code  = DrvBankROM[ofst] + bank;\n\t\tINT32 color = DrvBgCPROM[code + (*bg_priority * 0x100)] & 0x0f;\n\n\t\tsx = (sx * 8) + dx - 6;\n\t\tsy = (sy * 8) + dy + 9 - 16;\n\n\t\tRender8x8Tile_Clip(pTransDraw, code, sx - 8, sy, color, 4, 0x100, DrvGfxROM1);\n\t}\n}\n\nstatic void draw_fg_layer()\n{\n\tINT32 dx   = ~*fg_scrollx & 7;\n\tINT32 dy   = ~*fg_scrolly & 7;\n\tINT32 rx   = (*fg_scrollx) >> 3;\n\tINT32 ry   = (*fg_scrolly) >> 3;\n\tINT32 bank = (*fg_select & 0x03) * 0x800;\n\n\tfor (INT32 offs = 0; offs < 32 * 32; offs++)\n\t{\n\t\tINT32 sx = (offs & 0x1f);\n\t\tINT32 sy = (offs \/ 0x20);\n\n\t\tINT32 ofst = ((ry + sy + 34) & 0x3f) * 0x20 + ((rx + sx) & 0x1f) + bank;\n\t\tINT32 code = DrvFgMPROM[ofst];\n\n\t\tsx = (sx * 8) + dx - 6;\n\t\tsy = (sy * 8) + dy + 9 - 16;\n\n\t\tif (DrvTransTab[2][code]) continue;\n\n\t\tRender8x8Tile_Mask_Clip(pTransDraw, code, sx - 8, sy, 0, 2, 0, 0, DrvGfxROM2);\n\t}\n}\n\nstatic void draw_txt_layer()\n{\n\tfor (INT32 offs = 16 * 32; offs < 240 * 32; offs++)\n\t{\n\t\tINT32 color;\n\t\tINT32 sx = (offs & 0x1f) * 8;\n\t\tINT32 sy = (offs \/ 0x20);\n\n\t\tif (tx_mode)\n\t\t{\n\t\t\tif ((DrvColPROM[sy] & 0xf8) == 0) sy -= *tx_scrolly;\n\n\t\t\tcolor = (DrvColPROM[sy] & 0x07) | 0x10;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcolor = DrvColPROM[(sy >> 3) + 0x100] & 0x0f;\n\t\t}\n\n\t\tINT32 code = DrvVidRAM[((sy >> 3) << 5) | (sx >> 3)] * 8 + (sy & 7);\n\n\t\tif (DrvTransTab[0][code]) continue;\n\n\t\tRenderCustomTile_Mask_Clip(pTransDraw, 8, 1, code, sx - 8, sy - 16, color, 2, 0, 0, DrvGfxROM0);\n\t}\n}\n\nstatic void draw_sprites(INT32 start, INT32 end)\n{\n\tUINT8 *sprite_ram = DrvSprRAM + 0x64;\n\n\tfor (INT32 offs = start; offs < end; offs += 4)\n\t{\n\t\tINT32 sy    = 239 - sprite_ram[offs + 0] - 16;\n\t\tINT32 code  = sprite_ram[offs + 1] | ((sprite_ram[offs + 2] & 0x60) << 3);\n\t\t      code  = ((code & 0x380) << 1) | (code & 0x7f);\n\t\tINT32 color = sprite_ram[offs + 2] & 0x07;\n\t\tINT32 flipy = sprite_ram[offs + 2] & 0x08;\n\t\tINT32 flipx = sprite_ram[offs + 2] & 0x10;\n\t\tINT32 sx    = sprite_ram[offs + 3] - 8;\n\n\t\tif (DrvTransTab[3][code]) continue;\n\n#if 1\t\t\/\/ 8x16 tiles don't seem to work well for custom tile drawing?\n\t\t{\n\t\t\tUINT8 *gfx = DrvGfxROM3 + (code * 0x80);\n\n\t\t\tINT32 flip = (flipx ? 0 : 7) | (flipy ? 0x78 : 0);\n\n\t\t\tcolor = (color << 4) + 0x80;\n\n\t\t\tfor (INT32 y = 0; y < 16; y++, sy++, sx-=8) {\n\t\t\t\tfor (INT32 x = 0; x < 8; x++, sx++) {\n\t\t\t\t\tINT32 pxl = gfx[((y * 8) + x) ^ flip];\n\n\t\t\t\t\tif (pxl) {\n\t\t\t\t\t\tif (sy >= 0 && sy < nScreenHeight && sx >= 0 && sx < nScreenWidth) {\n\t\t\t\t\t\t\tpTransDraw[sy * nScreenWidth + sx] = pxl + color;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#else\n\t\tif (flipy) {\n\t\t\tif (!flipx) {\n\t\t\t\tRenderCustomTile_Mask_FlipXY_Clip(pTransDraw, 8, 16, code, sx, sy, color, 4, 0, 0x80, DrvGfxROM3);\n\t\t\t} else {\n\t\t\t\tRenderCustomTile_Mask_FlipY_Clip(pTransDraw, 8, 16, code, sx, sy, color, 4, 0, 0x80, DrvGfxROM3);\n\t\t\t}\n\t\t} else {\n\t\t\tif (!flipx) {\n\t\t\t\tRenderCustomTile_Mask_FlipX_Clip(pTransDraw, 8, 16, code, sx, sy, color, 4, 0, 0x80, DrvGfxROM3);\n\t\t\t} else {\n\t\t\t\tRenderCustomTile_Mask_Clip(pTransDraw, 8, 16, code, sx, sy, color, 4, 0, 0x80, DrvGfxROM3);\n\t\t\t}\n\t\t}\n#endif\n\t}\n}\n\nstatic INT32 DrvDraw()\n{\n\tif (DrvRecalc) {\n\t\tfor (INT32 i = 0; i < 0x400; i+=2) {\n\t\t\tpalette_write(i);\n\t\t}\n\n\t\tDrvRecalc = 0;\n\t}\n\n\tif ((*bg_select & 0x10) == 0)\n\t{\n\t\tdraw_bg_layer();\n\t}\n\telse\n\t{\n\t\tfor (INT32 i = 0; i < nScreenWidth * nScreenHeight; i++) {\n\t\t\tpTransDraw[i] = 0x100;\n\t\t}\n\t}\n\n\tdraw_sprites(0, 0x24);\n\n\tif ((*bg_select & 0x10) == 0)\n\t{\n\t\tdraw_bg_layer_pri();\n\t}\n\n\tdraw_sprites(0x24, 0x100-0x64);\n\n\tdraw_txt_layer();\n\n\tif ((*fg_select & 0x10) == 0)\n\t{\n\t\tdraw_fg_layer();\n\t}\n\n\tBurnTransferCopy(DrvPalette);\n\n\treturn 0;\n}\n\nstatic INT32 DrvFrame()\n{\n\twatchdog++;\n\tif (watchdog >= 180) {\n\t\tDrvDoReset(0);\n\t}\n\n\tif (DrvReset) {\n\t\tDrvDoReset(1);\n\t}\n\n\tZetNewFrame();\n\n\t{\n\t\tmemset (DrvInputs, 0xff, 3 * sizeof(UINT8));\n\n\t\tfor (INT32 i = 0; i < 8; i++) {\n\t\t\tDrvInputs[0] ^= (DrvJoy1[i] & 1) << i;\n\t\t\tDrvInputs[1] ^= (DrvJoy2[i] & 1) << i;\n\t\t\tDrvInputs[2] ^= (DrvJoy3[i] & 1) << i;\n\t\t}\n\t}\n\n\tINT32 nCycleSegment;\n\tINT32 nInterleave = 10;\n\tINT32 nCyclesTotal[2] = { 5000000 \/ 60, 2500000 \/ 60 };\n\tINT32 nCyclesDone[2] = { 0, 0 };\n\n\tfor (INT32 i = 0; i < nInterleave; i++)\n\t{\n\t\tnCycleSegment = nCyclesTotal[0] \/ nInterleave;\n\n\t\tZetOpen(0);\n\t\tnCyclesDone[0] += ZetRun(nCycleSegment);\n\t\tif (i == (nInterleave-1)) ZetSetIRQLine(0, ZET_IRQSTATUS_AUTO);\n\t\tZetClose();\n\n\t\tnCycleSegment = nCyclesTotal[1] \/ nInterleave;\n\n\t\tZetOpen(1);\n\t\tBurnTimerUpdate(i * nCycleSegment);\n\t\tnCyclesDone[1] += nCycleSegment;\n\t\tZetClose();\n\t}\n\n\tZetOpen(1);\n\tBurnTimerEndFrame(nCyclesTotal[1]);\n\tif (pBurnSoundOut) {\n\t\tBurnYM2203Update(pBurnSoundOut, nBurnSoundLen);\n\t}\n\tZetClose();\n\n\tif (pBurnDraw) {\n\t\tDrvDraw();\n\t}\n\n\treturn 0;\n}\n\nstatic INT32 DrvScan(INT32 nAction,INT32 *pnMin)\n{\n\tstruct BurnArea ba;\n\n\tif (pnMin) {\n\t\t*pnMin = 0x029702;\n\t}\n\n\tif (nAction & ACB_VOLATILE) {\n\t\tba.Data\t  = AllRam;\n\t\tba.nLen\t  = RamEnd - AllRam;\n\t\tba.szName = \"All RAM\";\n\t\tBurnAcb(&ba);\n\n\t\tZetScan(nAction);\n\n\t\tBurnYM2203Scan(nAction, pnMin);\n\t}\n\n\tif (nAction & ACB_WRITE)\n\t{\n\t\tZetOpen(0);\n\t\tbankswitch(*bg_bank);\n\t\tZetClose();\n\t}\n\n\treturn 0;\n}\n\n\n\/\/ Momoko 120%\n\nstatic struct BurnRomInfo momokoRomDesc[] = {\n\t{ \"momoko03.bin\",\t0x8000, 0x386e26ed, 0x01 | BRF_PRG | BRF_ESS }, \/\/  0 Z80 #0 Code\n\t{ \"momoko02.bin\",\t0x4000, 0x4255e351, 0x01 | BRF_PRG | BRF_ESS }, \/\/  1\n\n\t{ \"momoko01.bin\",\t0x8000, 0xe8a6673c, 0x02 | BRF_PRG | BRF_ESS }, \/\/  2 Z80 #1 Code\n\n\t{ \"momoko13.bin\",\t0x2000, 0x2745cf5a, 0x03 | BRF_GRA },           \/\/  3 Character Tiles\n\n\t{ \"momoko14.bin\",\t0x2000, 0xcfccca05, 0x04 | BRF_GRA },           \/\/  4 Foreground Tiles\n\n\t{ \"momoko16.bin\",\t0x8000, 0xfc6876fc, 0x05 | BRF_GRA },           \/\/  5 Sprite Tiles\n\t{ \"momoko17.bin\",\t0x8000, 0x45dc0247, 0x05 | BRF_GRA },           \/\/  6\n\n\t{ \"momoko09.bin\",\t0x8000, 0x9f5847c7, 0x06 | BRF_GRA },           \/\/  7 Background Tiles\n\t{ \"momoko11.bin\",\t0x8000, 0x9c9fbd43, 0x06 | BRF_GRA },           \/\/  8\n\t{ \"momoko10.bin\",\t0x8000, 0xae17e74b, 0x06 | BRF_GRA },           \/\/  9\n\t{ \"momoko12.bin\",\t0x8000, 0x1e29c9c4, 0x06 | BRF_GRA },           \/\/ 10\n\n\t{ \"momoko04.bin\",\t0x8000, 0x3ab3c2c3, 0x07 | BRF_GRA },           \/\/ 11 Background Map (Banks used by Z80 #0)\n\t{ \"momoko05.bin\",\t0x8000, 0x757cdd2b, 0x07 | BRF_GRA },           \/\/ 12\n\t{ \"momoko06.bin\",\t0x8000, 0x20cacf8b, 0x07 | BRF_GRA },           \/\/ 13\n\t{ \"momoko07.bin\",\t0x8000, 0xb94b38db, 0x07 | BRF_GRA },           \/\/ 14\n\n\t{ \"momoko08.bin\",\t0x2000, 0x69b41702, 0x08 | BRF_GRA },           \/\/ 15 Background Color\/Priority Table\n\n\t{ \"momoko15.bin\",\t0x4000, 0x8028f806, 0x09 | BRF_GRA },           \/\/ 16 Foreground Map\n\n\t{ \"momoko-c.bin\",\t0x0100, 0xf35ccae0, 0x0a | BRF_GRA },           \/\/ 17 Text Layer Color PROMs\n\t{ \"momoko-b.bin\",\t0x0020, 0x427b0e5c, 0x0a | BRF_GRA },           \/\/ 18\n};\n\nSTD_ROM_PICK(momoko)\nSTD_ROM_FN(momoko)\n\nstruct BurnDriver BurnDrvMomoko = {\n\t\"momoko\", NULL, NULL, NULL, \"1986\",\n\t\"Momoko 120%\\0\", NULL, \"Jaleco\", \"Miscellaneous\",\n\tNULL, NULL, NULL, NULL,\n\tBDF_GAME_WORKING, 2, HARDWARE_MISC_PRE90S, GBF_PLATFORM, 0,\n\tNULL, momokoRomInfo, momokoRomName, NULL, NULL, MomokoInputInfo, MomokoDIPInfo,\n\tDrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 0x200,\n\t240, 224, 4, 3\n};\n","avg_line_length":24.5522041763,"max_line_length":115,"alphanum_fraction":0.6333396333,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":6846,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Copyright (c) 2012-2014 The Bitcoin Core developers\n\/\/ Copyright (c) 2014-2015 The Dash Core developers\n\/\/ Copyright (c) 2015-2017 The PIVX developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"netbase.h\"\n\n#include <string>\n\n#include <boost\/test\/unit_test.hpp>\n\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(netbase_tests)\n\nBOOST_AUTO_TEST_CASE(netbase_networks)\n{\n    BOOST_CHECK(CNetAddr(\"127.0.0.1\").GetNetwork()                              == NET_UNROUTABLE);\n    BOOST_CHECK(CNetAddr(\"::1\").GetNetwork()                                    == NET_UNROUTABLE);\n    BOOST_CHECK(CNetAddr(\"8.8.8.8\").GetNetwork()                                == NET_IPV4);\n    BOOST_CHECK(CNetAddr(\"2001::8888\").GetNetwork()                             == NET_IPV6);\n    BOOST_CHECK(CNetAddr(\"FD87:D87E:EB43:edb1:8e4:3588:e546:35ca\").GetNetwork() == NET_TOR);\n}\n\nBOOST_AUTO_TEST_CASE(netbase_properties)\n{\n    BOOST_CHECK(CNetAddr(\"127.0.0.1\").IsIPv4());\n    BOOST_CHECK(CNetAddr(\"::FFFF:192.168.1.1\").IsIPv4());\n    BOOST_CHECK(CNetAddr(\"::1\").IsIPv6());\n    BOOST_CHECK(CNetAddr(\"10.0.0.1\").IsRFC1918());\n    BOOST_CHECK(CNetAddr(\"192.168.1.1\").IsRFC1918());\n    BOOST_CHECK(CNetAddr(\"172.31.255.255\").IsRFC1918());\n    BOOST_CHECK(CNetAddr(\"2001:0DB8::\").IsRFC3849());\n    BOOST_CHECK(CNetAddr(\"169.254.1.1\").IsRFC3927());\n    BOOST_CHECK(CNetAddr(\"2002::1\").IsRFC3964());\n    BOOST_CHECK(CNetAddr(\"FC00::\").IsRFC4193());\n    BOOST_CHECK(CNetAddr(\"2001::2\").IsRFC4380());\n    BOOST_CHECK(CNetAddr(\"2001:10::\").IsRFC4843());\n    BOOST_CHECK(CNetAddr(\"FE80::\").IsRFC4862());\n    BOOST_CHECK(CNetAddr(\"64:FF9B::\").IsRFC6052());\n    BOOST_CHECK(CNetAddr(\"FD87:D87E:EB43:edb1:8e4:3588:e546:35ca\").IsTor());\n    BOOST_CHECK(CNetAddr(\"127.0.0.1\").IsLocal());\n    BOOST_CHECK(CNetAddr(\"::1\").IsLocal());\n    BOOST_CHECK(CNetAddr(\"8.8.8.8\").IsRoutable());\n    BOOST_CHECK(CNetAddr(\"2001::1\").IsRoutable());\n    BOOST_CHECK(CNetAddr(\"127.0.0.1\").IsValid());\n}\n\nbool static TestSplitHost(string test, string host, int port)\n{\n    string hostOut;\n    int portOut = -1;\n    SplitHostPort(test, portOut, hostOut);\n    return hostOut == host && port == portOut;\n}\n\nBOOST_AUTO_TEST_CASE(netbase_splithost)\n{\n    BOOST_CHECK(TestSplitHost(\"www.bitcoin.org\", \"www.bitcoin.org\", -1));\n    BOOST_CHECK(TestSplitHost(\"[www.bitcoin.org]\", \"www.bitcoin.org\", -1));\n    BOOST_CHECK(TestSplitHost(\"www.bitcoin.org:80\", \"www.bitcoin.org\", 80));\n    BOOST_CHECK(TestSplitHost(\"[www.bitcoin.org]:80\", \"www.bitcoin.org\", 80));\n    BOOST_CHECK(TestSplitHost(\"127.0.0.1\", \"127.0.0.1\", -1));\n    BOOST_CHECK(TestSplitHost(\"127.0.0.1:33002\", \"127.0.0.1\", 33002));\n    BOOST_CHECK(TestSplitHost(\"[127.0.0.1]\", \"127.0.0.1\", -1));\n    BOOST_CHECK(TestSplitHost(\"[127.0.0.1]:33002\", \"127.0.0.1\", 33002));\n    BOOST_CHECK(TestSplitHost(\"::ffff:127.0.0.1\", \"::ffff:127.0.0.1\", -1));\n    BOOST_CHECK(TestSplitHost(\"[::ffff:127.0.0.1]:33002\", \"::ffff:127.0.0.1\", 33002));\n    BOOST_CHECK(TestSplitHost(\"[::]:33002\", \"::\", 33002));\n    BOOST_CHECK(TestSplitHost(\"::33002\", \"::33002\", -1));\n    BOOST_CHECK(TestSplitHost(\":33002\", \"\", 33002));\n    BOOST_CHECK(TestSplitHost(\"[]:33002\", \"\", 33002));\n    BOOST_CHECK(TestSplitHost(\"\", \"\", -1));\n}\n\nbool static TestParse(string src, string canon)\n{\n    CService addr;\n    if (!LookupNumeric(src.c_str(), addr, 65535))\n        return canon == \"\";\n    return canon == addr.ToString();\n}\n\nBOOST_AUTO_TEST_CASE(netbase_lookupnumeric)\n{\n    BOOST_CHECK(TestParse(\"127.0.0.1\", \"127.0.0.1:65535\"));\n    BOOST_CHECK(TestParse(\"127.0.0.1:33002\", \"127.0.0.1:33002\"));\n    BOOST_CHECK(TestParse(\"::ffff:127.0.0.1\", \"127.0.0.1:65535\"));\n    BOOST_CHECK(TestParse(\"::\", \"[::]:65535\"));\n    BOOST_CHECK(TestParse(\"[::]:33002\", \"[::]:33002\"));\n    BOOST_CHECK(TestParse(\"[127.0.0.1]\", \"127.0.0.1:65535\"));\n    BOOST_CHECK(TestParse(\":::\", \"\"));\n}\n\nBOOST_AUTO_TEST_CASE(onioncat_test)\n{\n    \/\/ values from https:\/\/web.archive.org\/web\/20121122003543\/http:\/\/www.cypherpunk.at\/onioncat\/wiki\/OnionCat\n    CNetAddr addr1(\"5wyqrzbvrdsumnok.onion\");\n    CNetAddr addr2(\"FD87:D87E:EB43:edb1:8e4:3588:e546:35ca\");\n    BOOST_CHECK(addr1 == addr2);\n    BOOST_CHECK(addr1.IsTor());\n    BOOST_CHECK(addr1.ToStringIP() == \"5wyqrzbvrdsumnok.onion\");\n    BOOST_CHECK(addr1.IsRoutable());\n}\n\nBOOST_AUTO_TEST_CASE(subnet_test)\n{\n    BOOST_CHECK(CSubNet(\"1.2.3.0\/24\") == CSubNet(\"1.2.3.0\/255.255.255.0\"));\n    BOOST_CHECK(CSubNet(\"1.2.3.0\/24\") != CSubNet(\"1.2.4.0\/255.255.255.0\"));\n    BOOST_CHECK(CSubNet(\"1.2.3.0\/24\").Match(CNetAddr(\"1.2.3.4\")));\n    BOOST_CHECK(!CSubNet(\"1.2.2.0\/24\").Match(CNetAddr(\"1.2.3.4\")));\n    BOOST_CHECK(CSubNet(\"1.2.3.4\").Match(CNetAddr(\"1.2.3.4\")));\n    BOOST_CHECK(CSubNet(\"1.2.3.4\/32\").Match(CNetAddr(\"1.2.3.4\")));\n    BOOST_CHECK(!CSubNet(\"1.2.3.4\").Match(CNetAddr(\"5.6.7.8\")));\n    BOOST_CHECK(!CSubNet(\"1.2.3.4\/32\").Match(CNetAddr(\"5.6.7.8\")));\n    BOOST_CHECK(CSubNet(\"::ffff:127.0.0.1\").Match(CNetAddr(\"127.0.0.1\")));\n    BOOST_CHECK(CSubNet(\"1:2:3:4:5:6:7:8\").Match(CNetAddr(\"1:2:3:4:5:6:7:8\")));\n    BOOST_CHECK(!CSubNet(\"1:2:3:4:5:6:7:8\").Match(CNetAddr(\"1:2:3:4:5:6:7:9\")));\n    BOOST_CHECK(CSubNet(\"1:2:3:4:5:6:7:0\/112\").Match(CNetAddr(\"1:2:3:4:5:6:7:1234\")));\n    BOOST_CHECK(CSubNet(\"192.168.0.1\/24\").Match(CNetAddr(\"192.168.0.2\")));\n    BOOST_CHECK(CSubNet(\"192.168.0.20\/29\").Match(CNetAddr(\"192.168.0.18\")));\n    BOOST_CHECK(CSubNet(\"1.2.2.1\/24\").Match(CNetAddr(\"1.2.2.4\")));\n    BOOST_CHECK(CSubNet(\"1.2.2.110\/31\").Match(CNetAddr(\"1.2.2.111\")));\n    BOOST_CHECK(CSubNet(\"1.2.2.20\/26\").Match(CNetAddr(\"1.2.2.63\")));\n    \/\/ All-Matching IPv6 Matches arbitrary IPv4 and IPv6\n    BOOST_CHECK(CSubNet(\"::\/0\").Match(CNetAddr(\"1:2:3:4:5:6:7:1234\")));\n    BOOST_CHECK(CSubNet(\"::\/0\").Match(CNetAddr(\"1.2.3.4\")));\n    \/\/ All-Matching IPv4 does not Match IPv6\n    BOOST_CHECK(!CSubNet(\"0.0.0.0\/0\").Match(CNetAddr(\"1:2:3:4:5:6:7:1234\")));\n    \/\/ Invalid subnets Match nothing (not even invalid addresses)\n    BOOST_CHECK(!CSubNet().Match(CNetAddr(\"1.2.3.4\")));\n    BOOST_CHECK(!CSubNet(\"\").Match(CNetAddr(\"4.5.6.7\")));\n    BOOST_CHECK(!CSubNet(\"bloop\").Match(CNetAddr(\"0.0.0.0\")));\n    BOOST_CHECK(!CSubNet(\"bloop\").Match(CNetAddr(\"hab\")));\n    \/\/ Check valid\/invalid\n    BOOST_CHECK(CSubNet(\"1.2.3.0\/0\").IsValid());\n    BOOST_CHECK(!CSubNet(\"1.2.3.0\/-1\").IsValid());\n    BOOST_CHECK(CSubNet(\"1.2.3.0\/32\").IsValid());\n    BOOST_CHECK(!CSubNet(\"1.2.3.0\/33\").IsValid());\n    BOOST_CHECK(CSubNet(\"1:2:3:4:5:6:7:8\/0\").IsValid());\n    BOOST_CHECK(CSubNet(\"1:2:3:4:5:6:7:8\/33\").IsValid());\n    BOOST_CHECK(!CSubNet(\"1:2:3:4:5:6:7:8\/-1\").IsValid());\n    BOOST_CHECK(CSubNet(\"1:2:3:4:5:6:7:8\/128\").IsValid());\n    BOOST_CHECK(!CSubNet(\"1:2:3:4:5:6:7:8\/129\").IsValid());\n    BOOST_CHECK(!CSubNet(\"fuzzy\").IsValid());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n","avg_line_length":45.64,"max_line_length":109,"alphanum_fraction":0.6425650015,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":703,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"#include <bits\/stdc++.h>\n#define ll long long\n#define endl '\\n'\n#define PI acos(-1)\n#define sz 1001\n#define inf 1e8\n#define mod 10000007\n#define RUN_FAST ios::sync_with_stdio(false);\nusing namespace std;\n\nstring s;\nchar ch;\n\nvoid ff1()\n{\n    stack <int> stk;\n    int i, len=s.size(), cnt=0;\n    for (i=0; i<len; i++) {\n        ch=s[i];\n        if (s[i]=='\\\\') {\n            stk.push(i);\n            continue;\n        }\n        else if (ch=='\/' && !stk.empty()) {\n            cnt+=i-stk.top();\n            stk.pop();\n        }\n    }\n    cout << cnt << endl;\n}\n\nint main()\n{\n    RUN_FAST; cin.tie(nullptr);\n    int T;\n    cin >> T;\n    while (T--) {\n        cin >> s;\n        ff1();\n    }\n    return 0;\n}\n","avg_line_length":16.3488372093,"max_line_length":45,"alphanum_fraction":0.4708392603,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":34373,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":null,"content":"\/\/ Genetic Active Site Search - GASS\n\/\/ Author: Sandro Carvalho Izidoro\n\/\/ Last update: 28\/10\/2020 (Vinicius Paiva)\n\n\/*\n\nFuncionamento dessa vers\u00e3o:\nS\u00e3o executados 4 GAs (que podem ser paralelizados), onde cada execu\u00e7\u00e3o corresponde a 1 dos quadrantes do espa\u00e7o 3D da prote\u00edna.\nEm cada execu\u00e7\u00e3o, a cada intervalo de 'ngeracoes\/10', os 10 primeiros individuos ranqueados vao para a popula\u00e7\u00e3o final.\nAssim, ao final de cada execu\u00e7\u00e3o de quadrantes, 1\/4 da popula\u00e7\u00e3o final \u00e9 constru\u00edda.\nPor fim, um quinto GA \u00e9 executado sobre a popula\u00e7\u00e3o final.\n\nA vers\u00e3o 3 realiza a opera\u00e7\u00e3o de muta\u00e7\u00e3o somente dentro do quadrante em que est\u00e1 executando a atual chamada do GA.\n\n*\/\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <cstdlib>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <iomanip>\n\nusing std::ifstream;\nusing std::ofstream;\nusing namespace std;\n\n\n\/\/---> STRUCTURE ATOMO - GENE OF THE INDIVIDUAL <---\/\/\nstruct Atomo{\n\tchar amino[5];\n\tchar atomo[4];\n\tchar cadeia;\n\tint atomo_ID;\n\tfloat x,y,z;\n};\n\n\/\/---> STRUCTURE SUBSTITUICAO - CONSERVATIVE MUTATIONS <---\/\/\nstruct Substituicao{\n\tchar lista[3][10];\n};\n\n\/\/---> GLOBAL VARIABLES <---\/\/\n\nchar teste[20][4] = {\"ALA\", \"ARG\", \"ASN\", \"ASP\", \"CYS\", \"GLN\", \"GLU\", \"GLY\", \"HIS\", \"ILE\", \"LEU\", \"LYS\", \"MET\", \"PHE\", \"PRO\", \"SER\", \"THR\", \"TRP\", \"TYR\", \"VAL\" };\n\n\/\/ Variables - AG\nint tpopulacao, torneio, ngeracoes, ranking, templates; \/\/ size of population, , tournament, number of generations, size of ranking, number of templates.\nfloat txmutacao, txcruzamento; \/\/ rates of crossover and mutation.\n\n\/\/ Variables - Active Site reference\nchar proteina_sitiof[10], cadeia_sitiof [1]; \/\/ Name of protein, chain.\nint tam_sitiof; \/\/ Size of active site.\nchar *testecadeia; \/\/ chain.\nint *id_residuo_sitiof; \/\/ Size of Active Site, ID of atoms\nint tam_dist;\nint *posicaolista;\nchar **nome_aminoacido;\nAtomo *sitio_ativo_fitness;\nchar nome_proteina[14];\n\nSubstituicao Matriz [567];\nint linhaarquivoref;\n\nchar ecnumber[100], uniprot[100], resolution[100], nome_enzima[100];\n\nfloat centroide[3];\n\n\/\/float centroide_aux[3] = {-9.980,-15.233,17.398}; \/\/1euu\n\/\/float centroide_aux[3] = {16.065,10.299,42.423}; \/\/3nos\n\/\/float centroide_aux[3] = {39.504,45.474,29.456}; \/\/1hpl\n\/\/float centroide_aux[3] = {22.677,-13.246,15.607}; \/\/5cnv\n\/\/float centroide_aux[3] = {27.358,0.424,15.948}; \/\/1mhl\n\/\/float centroide_aux[3] = {41.959,24.060,12.098}; \/\/1ah7\n\/\/float centroide_aux[3] = {47.225,35.245,25.108}; \/\/1n20\n\/\/float centroide_aux[3] = {49.699,36.726,23.317}; \/\/1su4\n\/\/float centroide_aux[3] = {47.495, 21.292, 40.862}; \/\/1a8h\n\/\/float centroide_aux[3] = {30.364 46.828 56.363}; \/\/2frv\n\/\/float centroide_aux[3] = {2.151, 12.796, 10.278}; \/\/1lba\n\/\/float centroide_aux[3] = {132.709,14.901,22.418}; \/\/1f1d\nfloat centroide_aux[3] = {159.937,92.626,51.358}; \/\/2gvb\n\n\n\/\/---> FUNCTIONS <---\/\/\nvoid ConfiguracaoGA(char *argv); \/\/ GA Parameters\nvoid ConfiguracaoSitioAtivo(char *argv); \/\/ Active Site Reference - Configuration\nvoid IniciaReferencia(Atomo *refe, char *argv); \/\/ Setup reference active site\nint  ListaSubstituicao(char substitutos [30][4]); \/\/ Builds substitution matrix\nvoid CriaListaSubstituicao(Substituicao Matriz[567], char *argv);\nvoid GeraRepositorio(Atomo **repositorio, int *numero_aminos); \/\/ Builds repository\nvoid IniciaPopulacao(Atomo **pop,  Atomo **repositorio, int *numero_aminos, Atomo *refe, int quadrante); \/\/ Starting population\nvoid substituicao (Atomo **pop, int *numero_aminos, Atomo **repositorio, char substitutos [30][4], int tam, Atomo *refe); \/\/ Substitution\nvoid crossover(Atomo **pop, float fitnessvet[]); \/\/Crossover operator\nint funcaotorneio(float fitnessvet[], int escolhidos_torneio[]);\nvoid mutation (Atomo **pop, int *numero_aminos, Atomo **repositorio, int quadrante); \/\/Mutation operator\nfloat fitnessRef (Atomo *refe, float distanciasref[]);\nvoid fitness(Atomo **p, float fitnessv[], float distanciasitio[], float distanciasref[]);\nint posicaonalista (char teste[20][4], char find[5]);\nint melhordageracao(float fitnessvet[]);\nint melhordageracaof(float fitnessvet[]);\nint piordageracao(float fitnessvet[]);\nvoid EscreveAtomo(Atomo atomo);\nvoid quickSort(Atomo **tempop, float [], int, int);\nint partition(Atomo **tempop, float [], int, int);\nvoid IniciaTop(float fittop[]); \/\/Starting top\nbool AbrirArquivo(ifstream &ifs, char nomeArquivo[]); \/\/Open file\n\nvoid ImprimeRepositorio(Atomo **repositorio, int *numero_aminos);\nint MostraQuadrante(Atomo amino, float *centroide);\nvoid IniciaPopulacao2(Atomo **pop,  Atomo **repositorio, int *numero_aminos, Atomo *refe, int quadrante);\nvoid RunGASS(char *argv[], Atomo **pop, int quadrante, Atomo **pop_final, ofstream &ofs, Atomo *refe);\n\nint main(int argc, char *argv[]){\n\tif(argc != 6 && argc != 3){\n\t\tcout << \"Error! Parameters missing!\" << endl;\n\t\tcout << argc << endl;\n\t\texit(1);\n   \t}\n   \t\n   \tif(argc == 3){\n   \t\tfor(int i = 0; i < 3; i++){\n   \t\t\tcentroide[i] = centroide_aux[i];\n   \t\t}\n   \t}\n   \telse{\n   \t\tchar coord[100];\n   \t\tfor(int i = 0; i < 3; i++){\n   \t\t\tstrcpy(coord, argv[i+3]);\n   \t\t\tcentroide[i] = stof(coord);\n   \t\t\t\/\/cout << centroide[i] << \" \";\n   \t\t}\n   \t}\n   \tsrand (time (NULL));\n   \tofstream ofs;\n\n   \tchar caminho[200];\n   \tstrcpy(caminho, argv[1]);\n   \tstrcat (caminho, \"\/ActiveSitesFound.txt\");\n   \tofs.open(caminho); \/\/ Open file to save the active sites found\n   \t\/\/ofs.open(\"ActiveSitesFound.txt\"); \/\/ Open file to save the active sites found\n   \tif(ofs.is_open() == false){\n\t \tcout << \"File of active sites found can not be open.\\n\";\n\t \texit(1);\n   \t}\n   \tlinhaarquivoref = 0;\n\tConfiguracaoGA(argv[2]);\n\t\/\/cout << tpopulacao << \" \" << tam_sitiof << \" \" << ranking << endl;\n\t\n\tfor(int ntemplates = 0; ntemplates < templates; ntemplates++){\n\t\tAtomo **pop, **pop_final;\n\t\tConfiguracaoSitioAtivo(argv[2]); \/\/Active Site Reference - Configuration\n\t\tAtomo *refe = new Atomo[tam_sitiof];\n\t  \tIniciaReferencia(refe, argv[2]); \/\/\n\t  \t\/\/cout << \"Sitio de referencia: \" << endl;\n\t\tfor(int i = 0; i < tam_sitiof; i++){\n\t\t\tint quadrante_AA = MostraQuadrante(refe[i], centroide);\n\t\t\t\/\/cout << \"Quadrante: \" << quadrante_AA << \" \";\n\t\t\t\/\/EscreveAtomo(refe[i]);\n\t\t\t\/\/cout << endl;\n\t\t}\n\t\t\n\t\tpop_final = new Atomo*[tpopulacao];\n\t\tfor(int i = 0; i < tpopulacao; i++)\n\t\t\tpop_final[i] = new Atomo[tam_sitiof];\n\t\t\n\t\t\/\/top = new Atomo*[ranking];\n\t\t\/\/for(int i = 0; i < ranking; i++)\n\t\t\t\/\/top[i] = new Atomo[tam_sitiof];\n\t\tpop = new Atomo*[tpopulacao];\n\t\t\tfor(int i = 0; i < tpopulacao; i++)\n\t\t\t\tpop[i] = new Atomo[tam_sitiof];\n\n\t\tfor(int i = 0; i < 4; i++){\n\t\t\tRunGASS(argv, pop, i+1, pop_final, ofs, refe);\n\t\t\t\/\/cout << \"------------------------------------\" << endl;\n\t\t}\n\n\t\t\/\/cout << \" ULTIMA \" << endl;\n\t\tRunGASS(argv, pop_final, -1, pop_final, ofs, refe);\n\t\t\/\/ Deleting pointers\n\t  \tdelete[] testecadeia;\n\t  \tdelete[]id_residuo_sitiof;\n\t  \tdelete[]refe;\n\t  \tfor(int i = 0; i < tam_sitiof; i++)\n\t\t \tdelete nome_aminoacido[i];\n\t\tfor(int i = 0; i < tpopulacao; i++)\n\t\t   delete pop[i];\n\t\tfor(int i = 0; i < tpopulacao; i++)\n\t\t   delete pop_final[i];\n\t\t\n\n\t}\n\tcout << \"GASS finished! Please, verify the file ActivesSitesFound.txt \\n\";\n}\n\n\nvoid RunGASS(char *argv[], Atomo **pop, int quadrante, Atomo **pop_final, ofstream &ofs, Atomo *refe){\n  \tint contador = 0, pos;\n  \tchar buff[20];  \/\/ line from file\n  \t\n\n  \ttam_dist = ((tam_sitiof * tam_sitiof) - tam_sitiof)\/2;\n  \tfloat fitr, fitnessvet[tpopulacao], distanciasref [tam_dist], distanciasitio[tam_dist];\n  \tfloat fitnessvetfinal[ngeracoes], fitnesspior[ngeracoes], fitnessmedio[ngeracoes];\n\n  \t\/\/ Substitution matrix\n  \tCriaListaSubstituicao(Matriz, argv[2]);\n  \tchar substitutos [30][4];\n  \tint tam = ListaSubstituicao(substitutos);\n\tstrcpy(nome_proteina,argv[1]);\n\tstrcat(nome_proteina,\"\/protein.dat\\0\");\n\n\t   \/\/ Starting repository enzyme\n\tifstream linhasFile(nome_proteina,ios::in); \/\/Open file from filtroC_Dados.cpp\n\tif(!linhasFile){\n \t\tcout << \"End of Program or Fault on File of Proteins!\" << endl;\n \t\texit(1);\n\t}\n\tlinhasFile.seekg(0,ios::end); \/\/put pointer in the end of file\n\tlong nrec = (linhasFile.tellg( ))\/sizeof(Atomo); \/\/return number of register\n\tlinhasFile.close();\n\tAtomo **repositorio;\n\trepositorio = new Atomo*[20];\n\tfor(int i = 0; i < 20; i++)\n  \t\trepositorio[i] = new Atomo[nrec];\n\n\t\/\/ Starting ranking\n\tfloat *fittop = new float[ranking];\n\tIniciaTop(fittop);\n\n\t\/\/ Number of each residues int the protein\n\tint *numero_aminos = new int [20];\n\tfor(int i = 0; i < 20; i++)\n  \t\tnumero_aminos[i] = 0;\n\n   \t\/\/ Starting top\n   \tAtomo **top = new Atomo*[ranking];\n   \tfor(int i = 0; i < ranking; i++)\n\t  \ttop[i] = new Atomo[tam_sitiof];\n\n\tcontador++;\n\n\t   \/\/ Starting population\n\t   \/*\n\t   if(pop == NULL){\n\t   \t\tpop = new Atomo*[tpopulacao];\n\t   \t\tfor(int i = 0; i < tpopulacao; i++)\n\t\t  \t\tpop[i] = new Atomo[tam_sitiof];\n\t\t}\n\t   *\/\n   \tAtomo **ms = new Atomo*[ngeracoes];\n   \tfor(int i = 0; i < ngeracoes; i++)\n\t\tms[i] = new Atomo[tam_sitiof];\n\n   \tGeraRepositorio(repositorio, numero_aminos); \/\/ Starting repository\n   \t\n   \tif(quadrante == 100)\n   \t\tImprimeRepositorio(repositorio, numero_aminos);\n\n   \t\/\/cout << nome_enzima << endl <<  ecnumber << endl << uniprot << endl <<  resolution << endl;\n\n   \tint ResiduosNoRepositorioMenorQueNoSitio = 1;\n   \tint ResiduosNoRepositorioZerado = 1;\n\n   \t\/\/ Checks if there are sufficient number of residues in the repository\n   \tfor(int i = 0; i < tam_sitiof; i++){\n\t\tint k = 0;\n\t  \tfor(int j = 0; j < tam_sitiof; j++)\n\t\t \tif(!strcmp(nome_aminoacido[i], nome_aminoacido[j]))\n\t\t   \tk++;\n\t  \tint posicao = posicaonalista(teste, nome_aminoacido[i]);\n\t  \tif(numero_aminos[posicao] < k){\n\t\t  \tcout << \"uno\" << endl;\n\t\t  \tResiduosNoRepositorioMenorQueNoSitio = 0;\n\t\t  \ti = tam_sitiof;\n\t  \t}\n\t}\n\n\t\/\/ If there is a substitution matrix, check if there are residues in repository\n\t\/\/cout << substitutos[1] << endl;\n\t\/\/2jcw,HIS,CYS,THR,GLU,VAL,ASP\n\tif(tam > 0){\n\t\t\/\/HIS CYS LEU MET THR GLU VAL ASP\n\t\tint verifica = 1;\n\t\twhile(verifica == 1){\n\t\t\tverifica = 0;\n\t\t\t\/*cout << \"Vetor inicial: \";\n\t\t\tfor(int i = 0; i < tam; i++)\n\t\t\t\tcout << substitutos[i] << \" \";\n\t\t\tcout << tam << endl;*\/\n\t\t\tfor(int i = 0; i < tam; i++){\n\t\t\t\tint posicao = posicaonalista(teste, substitutos[i]);\n\t\t\t \tif(numero_aminos[posicao] == 0){\n\t\t\t \t\tverifica = 1;\n\t\t\t \t\t\/\/cout << \"Excluindo \" << substitutos[i] << endl;\n\t\t\t   \t\tif(i >= tam-1){\n\t\t\t\t\t\ttam = tam - 2;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tif(i % 2 == 0){\n\t\t\t\t\t\t\tfor(int j = i; j < tam; j=j+2){\n\t\t\t\t\t\t\t\tstrcpy(substitutos[j],substitutos[j+2]);\n\t\t\t\t\t\t\t\tstrcpy(substitutos[j+1],substitutos[j+3]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tfor(int j = i; j < tam; j=j+2){\n\t\t\t\t\t\t\t\tstrcpy(substitutos[j],substitutos[j+2]);\n\t\t\t\t\t\t\t\tstrcpy(substitutos[j-1],substitutos[j+1]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttam = tam - 2;\n\t\t\t\t\t}\n\t\t\t\t\/*cout << \"Novo vetor: \";\n\t\t\t\tfor(int i = 0; i < tam; i++)\n\t\t\t\t\tcout << substitutos[i] << \" \";\n\t\t\t\tcout << tam << endl;*\/\n\t\t\t \t}\n\t\t  \t}\t\n\t\t}\n\t  \t\/*for(int i = 0; i < tam; i++)\n\t\t\tcout << substitutos[i] << \" \";\n\t\tcout << tam << endl;\n\t\tcout << endl;*\/\n\t  \tif(ResiduosNoRepositorioZerado)\n\t\t\tfor(int i = 0; i < tam_sitiof; i++){\n\t\t   \t\tint posicao = posicaonalista(teste, nome_aminoacido[i]);\n\t\t   \t\tif(numero_aminos[posicao] == 0){\n\t\t   \t\t\tcout << \"tres\" << endl;\n\t\t\t \t\tResiduosNoRepositorioZerado = 0;\n\t\t\t \ti = tam_sitiof;\n\t\t   \t\t}\n\t\t\t}\n\t}\n\n \t\/\/ Sem lista de substituicao e Residuos em quantidade igual a referencia OU\n \t\/\/ Lista de substituicao e ao menos um residuo de cada tipo no repositorio\n \t\/\/cout << \"resi: \" << ResiduosNoRepositorioZerado << \" tam: \" << tam << endl;\n \tif(((tam == 0) && (ResiduosNoRepositorioMenorQueNoSitio == 1)) || ((tam > 0) && (ResiduosNoRepositorioZerado == 1))){\n \t\t\/\/cout << \"vez +++ \"  << endl;\n\t\t\/\/ Starting population\n\t\tif(quadrante > 0 && quadrante < 5){\n\t\t\tIniciaPopulacao(pop, repositorio, numero_aminos, refe, quadrante);\n\t\t}\n\t\t\n\n\t\t\/\/ Fitness of reference\n\t\tfitr = fitnessRef (refe, distanciasref);\n\t\tfloat fitnessmelhores[ngeracoes][2];\n\t\tint contadorfitness = 0;\n\t\tfloat fitnessparamudar = -100;\n\t\tint contador10 = 0;\n\t\tint pedaco = 0;\n\n\t\t\/\/ ----------------------------------------------------------------------------------------------------------------------------------------------------\n\n\t\t\/\/GA - Fitness, crossover, mutation\n\t\t\n\t\tfor(int tempo=0; tempo < ngeracoes; tempo++){\n\t\t\t\/\/ Fitness function\n\t\t   \tfitness(pop, fitnessvet, distanciasitio, distanciasref);\n\n\t\t   \t\/\/Quicksort\n\t\t   \tquickSort(pop, fitnessvet, 0, tpopulacao-1);\n\n\t\t   \t\/\/ Top ranking\n\t\t   \tint containdividuos = 0;\n\t\t   \tint conttop  = 0;\n\t\t   \twhile((containdividuos<tpopulacao) && (fitnessvet[containdividuos] < fittop[ranking-1])){\n\t\t\t\tif(fitnessvet[containdividuos] < fittop[conttop]){\n\t\t\t\t  \tfor(int i = ranking-1; i > conttop; i--){\n\t\t\t\t\t \tfittop[i] = fittop[i-1];\n\t\t\t\t\t \tfor(int j = 0;j<tam_sitiof;j++)\n\t\t\t\t\t\t\ttop[i][j] = top[i-1][j];\n\t\t\t\t  \t}\n\t\t\t\t  \tfittop[conttop] = fitnessvet[containdividuos];\n\t\t\t\t  \tfor(int j = 0;j<tam_sitiof;j++)\n\t\t\t\t\t \ttop[conttop][j] = pop[containdividuos][j];\n\t\t\t\t  \tcontaindividuos++;\n\t\t\t\t}\n\t\t\t\telse if(fitnessvet[containdividuos]==fittop[conttop])\n\t\t\t\t\t\tcontaindividuos++;\n\t\t\t\t\t else if(fitnessvet[containdividuos]>fittop[conttop])\n\t\t\t\t\t\t\tconttop++;\n\t\t   \t}\n\n\t\t   \t\/\/ Best of the generation\n\t\t   \tpos = melhordageracao(fitnessvet);\n\t\t   \tfor(int j=0 ; j < tam_sitiof; j++)\n\t\t\t  \tms[tempo][j] = pop[pos][j];\n\n\t\t   \t\/\/ Final fitness\n\t\t   \tfitnessvetfinal[tempo] = fitnessvet[pos];\n\n\t\t   \t\/\/ Worst fitness\n\t\t   \tpos = piordageracao(fitnessvet);\n\t\t   \tfitnesspior[tempo] = fitnessvet[pos];\n\n\t\t   \t\/\/ Average fitness\n\t\t   \tfloat g = 0;\n\t\t   \tfor(int j=0 ; j < tpopulacao ; j++)\n\t\t\t  \tg = g + fitnessvet[j];\n\t\t   \tfitnessmedio[tempo] = g \/ tpopulacao;\n\n\t\t   \tif(fitnessparamudar == fittop[0])\n\t\t\t \tcontadorfitness++;\n\t\t   \telse{\n\t\t\t   \tfitnessparamudar = fittop[0];\n\t\t\t   \tcontadorfitness = 0;\n\t\t   \t}\n\n\t\t   \t\/\/ Swap the better if it does not change for 5 generations\n\t\t   \t\n\t\t   \tif(contadorfitness == 5) {\n\t\t\t \tchar find[5];\n\t\t\t \tint posicao, j, i = 0, conta = 0;\n\t\t\t \tint tentativas = 0;\n\t\t\t \tint quadrante_AA;\n\t\t\t \twhile(fittop[0] == fitnessvet[i]){\n\t\t\t\t  \tfor(j=0; j < tam_sitiof; j++){\n\t\t\t\t\t \tstrcpy(find, pop[i][j].amino);\n\t\t\t\t\t \tpos = posicaonalista(teste, find);\n\t\t\t\t\t \twhile(1){\n\t\t\t\t\t\t\tpop[i][j] = repositorio[pos][rand() % numero_aminos[pos]];\n\t\t\t\t\t\t\tquadrante_AA = MostraQuadrante(pop[i][j], centroide);\n\t\t\t\t\t\t\tif(quadrante_AA == quadrante || quadrante == -1)\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\telse{\n\t\t\t  \t\t\t\t\ttentativas++;\n\t\t\t  \t\t\t\t\tif(tentativas > 1000)\n\t\t\t  \t\t\t\t\t\tbreak;\n\t\t\t  \t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t  \t}\n\t\t\t\t  \ti++;\n\t\t\t   \t}\n\t\t\t  \tcontadorfitness = 0;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ Crossover Operator\n\t\t\tcrossover(pop, fitnessvet);\n\n\t\t\t\/\/ Mutation Operator\n\t\t\tmutation(pop, numero_aminos,repositorio, quadrante);\n\n\t\t\t\/\/ Runs substitution if there are residues in substitution matrix\n\t\t\tif((tam > 0) && (ResiduosNoRepositorioZerado == 1)){\n\t\t\t  \tsubstituicao(pop, numero_aminos, repositorio, substitutos, tam, refe);\n\t\t\t}\n\n\t\t\t\/\/ Fitness of population\n\t\t\tfitness(pop, fitnessvet, distanciasitio, distanciasref);\n\n\t\t\t\/\/Quicksort\n\t\t\tquickSort(pop, fitnessvet, 0, tpopulacao-1);\n\n\t\t\tpos = piordageracao(fitnessvet);\n\n\t\t\t\/\/Elitism\n\t\t\tfor(int j=0 ; j<tam_sitiof; j++)\n\t\t\t   pop[pos][j] = ms [tempo][j];\n\n\t\t\tif(quadrante != -1 && (tempo+1)%20 == 0){\n\t\t\t\t\n\t\t\t\t\/\/cout << \"Vez \" << tempo << endl;\n\t\t\t\t\/*for(int i=0; i<10; i++){\n\t\t\t\t\tfor(int j=0; j<tam_sitiof; j++){\n\t\t\t\t\t\tcout <<top[i][j].amino<<\" \"<< top[i][j].atomo_ID <<\" \"<<top[i][j].cadeia << \" \";\n\t\t\t\t\t}\n\t\t\t\t\tcout << endl;\n\t\t\t\t}*\/\n\t\t\t\tfor(int i = pedaco; i < (pedaco+10); i++){\n\t\t\t\t\tfor(int j = 0; j < tam_sitiof; j++){\n\t\t\t\t\t\tif(fittop[(pedaco+i)%10] == 1000){\n\t\t\t\t\t\t\tpop_final[((quadrante-1)*(tpopulacao\/4))+i][j] = pop[rand()%tpopulacao][j];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tpop_final[((quadrante-1)*(tpopulacao\/4))+i][j] = top[(pedaco+i)%10][j];\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/if(j == 0)\n\t\t\t\t\t\t\t\/\/cout << \"pop[\" << ((quadrante-1)*(tpopulacao\/4))+i << \"][\" << j << \"] top[\" << (pedaco+i)%10 << \"][\" << j << \"]\" << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/cout << pedaco << endl;\n\t\t\t\tpedaco = pedaco + 10;\n\n\t\t\t}\/*\n\t\t\tif(quadrante == 1 && tempo == 199){\n\t\t\t\tcout << \"pop_final###########: \" << endl;\n\t\t\t\tfor(int i=0; i<100;i++){\n\t\t\t\t\tfor(int j = 0; j < tam_sitiof; j++)\n\t\t\t\t\t\tcout <<pop_final[i][j].amino<<\" \"<< pop_final[i][j].atomo_ID <<\" \"<<pop_final[i][j].cadeia << \" \";\n\t\t\t\t\tcout << endl;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcout << \"top#################: \" << endl;\n\t\t\t\tfor(int i=0; i<100;i++){\n\t\t\t\t\tfor(int j = 0; j < tam_sitiof; j++)\n\t\t\t\t\t\tcout <<top[i][j].amino<<\" \"<< top[i][j].atomo_ID <<\" \"<<top[i][j].cadeia << \" \";\n\t\t\t\t\tcout << endl;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\tcout << \"top#################: \" << endl;\n\t\t\tif(quadrante == 4){\n\t\t\t\tfor(int i=0; i<400;i++){\n\t\t\t\t\tfor(int j = 0; j < tam_sitiof; j++)\n\t\t\t\t\t\t\n\t\t\t\t\t\tcout <<pop[i][j].amino<<\" \"<< pop[i][j].atomo_ID <<\" \"<<pop[i][j].cadeia << \" Quadrante: \" << MostraQuadrante(pop[i][j], centroide) << \" | \";\n\t\t\t\t\tcout << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\t*\/\n\n\t\t}\n\n\t\t\/\/ ---------------------------------------------------------------------------------------------------------------------------------------------------- \n\n\t\tpos = melhordageracaof(fitnessvetfinal);\n\n\t\t\/\/ofs << \"Template: \" << proteina_sitiof << endl;\n\t\tif(quadrante == -1){\n\t\t\tfor(int i=0;i<ranking;i++){\n\t\t\t\tofs << contador << \"\\t\"<< i << \"\\t\";\n\t\t\t\tofs << setprecision(3) << fittop[i] << \"\\t\";\n\t\t\t\t\/\/ ofs << nome_proteina << \" \" << fittop[i] << \" \";\n\t\t\t\tif(fittop[i] != 1000){\n\t\t\t\t    ofs <<top[i][0].amino<<\" \"<< top[i][0].atomo_ID <<\" \"<<top[i][0].cadeia;\n\t\t\t\t    for(int j=1; j<tam_sitiof; j++)\n\t\t\t\t\t   ofs << \";\" << top[i][j].amino<<\" \"<< top[i][j].atomo_ID <<\" \"<<top[i][j].cadeia;\n\t\t\t\t   \tofs << \"\\t\" << nome_enzima << \"\\t\";\n\t\t\t\t\tofs << refe[0].amino<<\" \"<< refe[0].atomo_ID <<\" \"<<refe[0].cadeia;\n\t\t\t\t   \tfor(int j=1; j<tam_sitiof; j++)\n\t\t\t\t\t   \tofs << \";\" <<refe[j].amino<<\" \"<< refe[j].atomo_ID <<\" \"<<refe[j].cadeia;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t  \tofs << \" - \" << \" \" << \" - \" <<\" \"<<\" - \";\n\t\t\t\t\t  \tfor(int j=1; j<tam_sitiof; j++)\n\t\t\t\t\t\t  \tofs << \";\" << \" - \" << \" \" << \" - \" <<\" \"<<\" - \";\n\t\t\t\t\t  \tofs << \"\\t\" << nome_enzima << \"\\n\";\n\t\t\t \t\t\tofs <<refe[0].amino<<\" \"<< refe[0].atomo_ID <<\" \"<<refe[0].cadeia;\n\t\t\t\t\t  \tfor(int j=1; j<tam_sitiof; j++)\n\t\t\t\t\t\t  \tofs << \";\" <<refe[j].amino<<\" \"<< refe[j].atomo_ID <<\" \"<<refe[j].cadeia;\n\t\t\t\t}\n\t\t\t   ofs << \"\\t\" << ecnumber <<\"\\t\"<<uniprot<<\"\\t\"<< resolution << \"\\t\" << tam_sitiof;\n\t\t\t   ofs << endl;\n\t\t\t}\n\t\t}\n\t\t\/\/ofs << endl;\n\t\t\/\/ Deleting pointers\n\t\tdelete[]fittop;\n\t\tfor(int i = 0; i < 20; i++)\n\t\t   delete repositorio[i];\n\t\t\/\/for(int i = 0; i < tpopulacao; i++)\n\t\t   \/\/delete pop[i];\n\t\tdelete[] numero_aminos;\n\t\tfor(int i = 0; i < ranking; i++)\n\t\t   delete top[i];\n\t\tfor(int i = 0; i < ngeracoes; i++)\n\t\t   delete ms[i];\n\n    }\n}\n\n\n\n\n\/\/----> FUNCTIONS - IMPLEMENTATION <---- \/\/\n\n\/\/ GA PARAMETERS\nvoid ConfiguracaoGA(char *argv){\n  ifstream fin;\n  char buff[255];\n  int nlinha = 0;\n  char localtemplate[200];\n  strcpy(localtemplate,argv);\n  strcat(localtemplate,\"\/GA_Conf.txt\");\n  fin.open(localtemplate);\n  \/\/fin.open(\"GA_Conf.txt\");\n  if(fin.is_open()){\n\t while(!fin.eof()){\n\t\t   fin.getline(buff, 255);\n\t\t   switch (nlinha) {\n\t\t\t   case 1: ngeracoes = atoi(buff); break;\n\t\t\t   case 3: tpopulacao = atoi(buff); break;\n\t\t\t   case 5: torneio = atoi(buff); break;\n\t\t\t   case 7: txcruzamento = atof(buff); break;\n\t\t\t   case 9: txmutacao = atof(buff); break;\n\t\t\t   case 11: ranking = atoi(buff); break;\n\t\t\t   case 13: templates = atoi(buff); break;\n\t\t   }\n\t\t   nlinha++;\n\t  }\n\t  fin.close();\n  }\n  else{\n\t   cout << \"File GA_Conf.txt can not be open.\\n\";\n\t   exit(1);\n  }\n}\n\n\n\/\/ CONFIGURATION ACTIVE SITE REFERENCE\nvoid ConfiguracaoSitioAtivo(char *argv){\n   ifstream fin;\n   char buff[255];\n   int nlinha = 0;\n   char localtemplate[200];\n   strcpy(localtemplate,argv);\n   strcat(localtemplate,\"\/Templates.txt\");\n   \/\/ fin.open(\"Templates.txt\");\n   fin.open(localtemplate);\n   if(fin.is_open()){\n\t for(int i=0; i<linhaarquivoref;i++)\n\t\tfin.getline(buff, 25);\n\t while(nlinha <= 4){\n\t\t  fin.getline(buff, 25);\n\t\t  switch (nlinha) {\n\t\t\t  case 1: strcpy(proteina_sitiof,buff); break;\n\t\t\t  case 3: tam_sitiof = atoi(buff); break;\n\t\t  }\n\t\t  nlinha++;\n\t }\n\t id_residuo_sitiof = new int[tam_sitiof];\n\t nome_aminoacido = new char*[tam_sitiof];\n\t testecadeia = new char[tam_sitiof];\n\n\t for(int i = 0; i < tam_sitiof; i++)\n\t\tnome_aminoacido[i] = new char[4];\n\n\t int i = 0, j = 0, k = 0, l = 0, linha = 1;\n\n\t while((!fin.eof())&&(k<tam_sitiof*3)){\n\t\t  fin.getline(buff, 25);\n\t\t  if(linha == 1){\n\t\t\t strcpy(nome_aminoacido[j], buff);\n\t\t\t nome_aminoacido[j][3] = '\\0';\n\t\t\t j++;\n\t\t\t linha++;\n\t\t  }\n\t\t  else if(linha == 2){\n\t\t\t\t id_residuo_sitiof[i++] = atoi (buff);\n\t\t\t\t linha++;\n\t\t\t   }\n\t\t\t   else{\n\t\t\t\t   strcpy(cadeia_sitiof,buff);\n\t\t\t\t   testecadeia[l++] = buff[0];\n\t\t\t\t   linha = 1;\n\t\t\t   }\n\t\t  nlinha++;\n\t\t  k++;\n\t }\n\t fin.close();\n\t linhaarquivoref = linhaarquivoref + 5 + (tam_sitiof * 3);\n   }\n   else{\n\t   cout << \"File templates.txt can not be open.\\n\";\n\t   exit(1);\n   }\n}\n\n\/\/ SETUP REFERENCE\nvoid IniciaReferencia(Atomo *refe, char *argv){\n   Atomo aux;\n   ifstream ifs;\n   char localtemplate[50];\n   char linha[100];\n   strcpy(localtemplate,argv);\n   strcat(localtemplate,\"\/\");\n   strcat(localtemplate, proteina_sitiof);\n   \/\/if(AbrirArquivo(ifs,proteina_sitiof) == true){\n   if(AbrirArquivo(ifs,localtemplate) == true){\n\t int i=0;\n\t int contador = 0;\n\t while((!ifs.eof()) && (i<tam_sitiof)){\n\t\t  if(contador<=3){\n\t\t\tifs.read((char*)&linha, sizeof(linha));\n\t\t\tif(contador == 0) {strcpy(nome_enzima, linha);cout << nome_enzima << \" : \";}\n\t\t\t   else if(contador == 1) strcpy(ecnumber, linha);\n\t\t\t\t\telse if(contador == 2) strcpy(uniprot, linha);\n\t\t\t\t\t\t else if(contador == 3) strcpy(resolution, linha);\n\t\t\tcontador++;\n\t\t  }\n\t\t  else{\n\t\t  ifs.read((char*)&aux, sizeof(Atomo));\n\t\t  for(int j=0;j<tam_sitiof;j++)\n\t\t\t if((aux.atomo_ID == id_residuo_sitiof[j])&&(aux.cadeia==testecadeia[j])){\n\t\t\t\trefe[i++] = aux;\n\t\t        \/\/EscreveAtomo(aux);\n\t\t\t }\n\t\t  }\n\n\t }\n   }\n   else{ cout << \"File can not be open: \" << proteina_sitiof << endl;}\n   ifs.close();\n   cout << endl;\n   \n}\n\n\/\/ SUBSTITUTION MATRIX\nint ListaSubstituicao(char substitutos [30][4]){\n\tint i = 0, ok = 0;\n   \tchar proteina [5];\n   \tfor(int j=0;j<4;j++){\n\t  \tproteina[j] = (proteina_sitiof[j]);\n\t}\n   \tproteina[4] = '\\0';\n   \t\/\/cout << proteina << endl;\n   \tfor(int k= 0 ; k < 567; k++){\t\n\t   \t\/\/cout << Matriz[k].lista[0] << endl;\n\t   \tif(!strcmp(proteina, Matriz[k].lista[0])){\n\t\t \t\/\/cout << \"aqui\";\n\t\t \tstrcpy(substitutos[i], Matriz[k].lista[1]);\n\t\t \tstrcpy(substitutos[i+1], Matriz[k].lista[2]);\n\t\t \t\/\/cout << substitutos[i] << \" \" << substitutos[i+1] << endl;\n\t\t \ti += 2;\n\t\t \tok = 1;\n\t   \t}\n\t   \telse {\n\t\t\tif(ok == 1)\n\t\t\t   k = 567;\n\t   \t}\n   \t}\n   \treturn i;\n}\n\n\/\/ BUILDING REPOSITORY OF PROTEINS\nvoid GeraRepositorio(Atomo **repositorio, int *numero_aminos){\n\tAtomo aux;\n\tifstream inFile(nome_proteina,ios::binary);\n\tif(!inFile){\n\t  cout<<\"File can not be open: \" << nome_proteina << endl;\n\t   exit(1);\n\t}\n\tint contador = 0;\n\tchar linha[100];\n\twhile(inFile){\n\t\tif(contador<=3){\n\t\t   inFile.read((char*)&linha, sizeof(linha));\n\t\t\/\/   if(contador == 0) strcpy(nome_enzima, linha);\n\t\t  \/\/   else if(contador == 1) strcpy(ecnumber, linha);\n\t\t\t\/\/        else if(contador == 2) strcpy(uniprot, linha);\n\t\t\t  \/\/             else if(contador == 3) strcpy(resolution, linha);\n\t\t   contador++;\n\t  }\n\t\telse{\n\t\t\tinFile.read((char *)&aux, sizeof(Atomo));\n\t\t\t\/\/EscreveAtomo(aux); int bunda; cin >> bunda;\n\t\t  for(int i = 0; i < 20; i++)\n\t\t\t   if(!strcmp(aux.amino,teste[i])){\n\t\t\t\t repositorio[i][numero_aminos[i]] = aux;\n\t\t\t\t numero_aminos[i]++;\n\t\t\t\t \/*while(1){\n\t\t\t\t \trepositorio[i][numero_aminos[i]] = aux;\n\t\t\t\t \tif(MostraQuadrante(repositorio[i][numero_aminos[i]], centroide) == quadrante)\n\t\t\t\t \t\tnumero_aminos[i]++;\n\t\t\t\t \t\tbreak;\n\t\t\t\t }*\/\n\t\t\t\t \/\/EscreveAtomo(aux);\n\t\t\t\t \/\/cout << endl;\n\t\t\t   }\n\t\t}\n   }\n   inFile.close();\n\n}\n\nvoid ImprimeRepositorio(Atomo **repositorio, int *numero_aminos){\n\t\/\/float centroide[3] = {-9.980,-15.233,17.398};\n\tfor(int j = 0; j < 3; j++)\n\t\tcout << centroide[j] << endl;\n\t\n\tfor(int i = 0; i < 20; i++){\n\t\tcout << repositorio[i][0].amino << \": \" << numero_aminos[i] << endl;\n\t\tfor(int j = 0; j < numero_aminos[i]; j++){\n\t\t\tcout << \"quadrante: \" << MostraQuadrante(repositorio[i][j], centroide) << \" \";\n\t\t\tEscreveAtomo(repositorio[i][j]);\n\t\t\tcout << endl;\n\t\t}\n\t}   \n\n}\n\nint MostraQuadrante(Atomo amino, float *centroide){\n\tif(amino.x > centroide[0] && amino.y > centroide[1]){ \/\/primeiro quadrante\n\t\treturn 1;\n\t}\n\telse if(amino.x > centroide[0] && amino.y < centroide[1]){\n\t\treturn 2;\n\t}\n\telse if(amino.x < centroide[0] && amino.y < centroide[1]){\n\t\treturn 3;\n\t}\n\telse{\n\t\treturn 4;\n\t}   \n}\n\n\/\/ STARTING POPULATION\nvoid IniciaPopulacao(Atomo **pop,  Atomo **repositorio, int *numero_aminos, Atomo *refe, int quadrante){\n\t\/\/ IMPLEMENTACAO B\n\tint pos;\n\tint tentativas = 0;\n\tint total_quad[4][20] = {0};\n\tint quadrante_AA;\n\tint vez = 0;\n\tfor(int i = 0; i < tpopulacao; i++){\n\t   for(int j=0; j<tam_sitiof; j++){\n\t\t\tif(j == 0){\n\t\t\t\t\/\/cout << \"Individuo \" << i+j << endl;\n\t\t\t}\n\t\t\t\/\/ Calcula o quadrante ideal de cada individuo e todos os AA desse individuo devem pertencer a esse quadrante\n\t\t\t\/\/ Caso nao tenha uma AA nesse quadrante, escolhe outro aleatoriamente.\n\t\t\tpos = posicaonalista(teste, refe[j].amino);\n\t\t\twhile(1){\n\t\t\t\tpop[i][j] = repositorio[pos][rand() % numero_aminos[pos]];\n\t\t\t\tquadrante_AA = MostraQuadrante(pop[i][j], centroide);\n\t\t\t\tif(quadrante_AA == quadrante){\n\t\t\t\t\ttotal_quad[quadrante_AA-1][pos]++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t  \t\ttentativas++;\n\t\t\t  \t\tif(tentativas > 1000){\n\t\t\t  \t\t\ttotal_quad[quadrante_AA-1][pos]++;\n\t\t\t  \t\t\tbreak;\n\t\t\t  \t\t}\n\t\t\t  \t}\n\t\t\t}\n\t\t\t\/\/EscreveAtomo(pop[i][j]);\n\t\t\t\/\/cout << \"quadrante \" << MostraQuadrante(pop[i][j], centroide) << endl;\n\t\t\ttentativas = 0;\n\t   }\n\t   \/\/cout << \"\\n\" << endl;\n\t}\/*\n\tfor(int i = 0; i < 20; i++)\n\t\tcout << teste[i] << \" \";\n\tcout << endl;\n\tfor(int i = 0; i < 4; i++){\n\t\tfor(int j = 0; j < 20; j++){\n\t\t\tcout << total_quad[i][j] << \"\\t\";\n\t\t}\n\t\tcout << endl;\n\t}*\/\n\t\n}\n\n\/\/ STARTING POPULATION\nvoid IniciaPopulacao2(Atomo **pop,  Atomo **repositorio, int *numero_aminos, Atomo *refe, int quadrante){\n\tint pos;\n\tint quadrante_AA;\n\tint total_quad[4][20] = {0};\n\tfor(int i = 0; i < tpopulacao; i++){\n\t   for(int j=0; j<tam_sitiof; j++){\n\t\t  pos = posicaonalista(teste, refe[j].amino);\n\t\t  pop[i][j] = repositorio[pos][rand() % numero_aminos[pos]];\n\t\t  quadrante_AA = MostraQuadrante(pop[i][j], centroide);\n\t\t  EscreveAtomo(pop[i][j]);\n\t\t  cout << \"quadrante \" << quadrante_AA << endl;\n\t\t  total_quad[quadrante_AA-1][pos]++;\n\t\t  cout << endl;\n\t   }\n\t   cout << endl;\n\t}\n\tfor(int i = 0; i < 20; i++)\n\t\tcout << teste[i] << \" \";\n\tcout << endl;\n\tfor(int i = 0; i < 4; i++){\n\t\tfor(int j = 0; j < 20; j++){\n\t\t\tcout << total_quad[i][j] << \"\\t\";\n\t\t}\n\t\tcout << endl;\n\t}\n}\n\n\/\/ CROSSOVER OPERATOR\nvoid crossover(Atomo **pop, float fitnessvet[]){\n\tint i2;\n\tAtomo pn[tpopulacao][tam_sitiof];\n\tAtomo pais[2][tam_sitiof];\n\tint escolhidos_torneio [torneio];\n\tint escolhido;\n\tfor(int k=0; k<tpopulacao; k+=2){\n\t   for(int i =0 ; i < 2; i++){\n\t\t   for(int i1=0;i1<torneio;i1++)\n\t\t\t  escolhidos_torneio[i1]= rand()%tpopulacao;\n\t\t   i2 = funcaotorneio(fitnessvet, escolhidos_torneio);\n\t\t   for(int j = 0;j<tam_sitiof;j++)\n\t\t\t  pais[i][j] = pop[i2][j];\n\t   }\n\t   if(rand()%100 <= txcruzamento){\n\t\t   int pointcross = rand() % tam_sitiof;\n\t\t   Atomo aux;\n\t\t   for(int i=0; i<=pointcross;i++){\n\t\t\t  aux = pais[0][i];\n\t\t\t  pais[0][i] = pais[1][i];\n\t\t\t  pais[1][i] = aux;\n\t\t   }\n\t\t}\n\t   for(int i = 0; i<tam_sitiof;i++){\n\t\t   pn[k][i] = pais[0][i];\n\t\t   pn[k+1][i] = pais[1][i];\n\t   }\n\t }\n\t for (int i = 0; i< tpopulacao; i++)\n\t\t for (int j = 0 ; j < tam_sitiof; j++)\n\t\t\t  pop [i][j] = pn[i][j];\n}\n\n\/\/ TOURNEMENT\nint funcaotorneio(float fitnessvet[], int escolhidos_torneio[]){\n\t int escolhido = escolhidos_torneio[0];\n\t float menor = fitnessvet[escolhido];\n\t for(int i=1;i<torneio;i++)\n\t\t if(fitnessvet[escolhidos_torneio[i]]< menor){\n\t\t\t menor = fitnessvet[escolhidos_torneio[i]];\n\t\t\t escolhido = escolhidos_torneio[i];\n\t\t }\nreturn escolhido;\n}\n\n\n\/\/ MUTATION OPERATOR\nvoid mutation (Atomo **pop, int *numero_aminos, Atomo **repositorio, int quadrante){\n   char find[5];\n   int pos, j;\n   int quadrante_AA;\n   int tentativas = 0;\n   for(int i=0; i < tpopulacao; i++){\n\t  \tif(rand()%100<=txmutacao){\n\t\t\tfor(j=0; j<tam_sitiof; j++){\n\t\t   \t\tif(rand()%100<=50){\n\t\t\t \t\tstrcpy(find, pop[i][j].amino);\n\t\t\t \t\tpos = posicaonalista(teste, find);\n\t\t\t \t\twhile(1){\n\t\t\t\t\t\tpop[i][j] = repositorio[pos][rand() % numero_aminos[pos]];\n\t\t\t\t\t\tquadrante_AA = MostraQuadrante(pop[i][j], centroide);\n\t\t\t\t\t\tif(quadrante_AA == quadrante || quadrante == -1)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\telse{\n\t\t\t  \t\t\t\ttentativas++;\n\t\t\t  \t\t\t\tif(tentativas > 1000)\n\t\t\t  \t\t\t\t\tbreak;\n\t\t\t  \t\t\t}\n\t\t\t\t\t}\n\t\t   \t\t}\n\t\t\t}\n\t  \t}\t\n   \t}\n}\n\n\/\/ SUBSTITUTION\nvoid substituicao (Atomo **pop, int *numero_aminos, Atomo **repositorio, char substitutos [30][4], int tam, Atomo *refe){\n   int posicao_da_troca, pos = 0, sorteio[tam], w;\n\n   for(int i = 0; i < tpopulacao; i++){\n\t  if(rand()%100<=5){   \/\/ era 10\n\t\tposicao_da_troca = rand()%tam_sitiof; \/\/ escolhe aleatoriamente a posicao no individuo para trocar\n\t\tw = 0;\n\t\tfor(int j=0; j<tam;j+=2)\n\t\t   if(!strcmp(pop[i][posicao_da_troca].amino,substitutos[j]) || !strcmp(pop[i][posicao_da_troca].amino,substitutos[j+1]))\n\t\t\t   sorteio[w++]=j;\n\t\tif(w!=0){\n\t\t\tint posicao = rand() % w;\n\t\t\tif(!strcmp(refe[posicao_da_troca].amino,substitutos[sorteio[posicao]])){\n\t\t\t   pos = posicaonalista (teste, substitutos[sorteio[posicao]+1]);\n\t\t\t   pop[i][posicao_da_troca] = repositorio[pos][rand()%numero_aminos[pos]];\n\t\t\t}\n\t\t\telse if(!strcmp(refe[posicao_da_troca].amino,substitutos[sorteio[posicao]+1])){\n\t\t\t\t   pos = posicaonalista (teste, substitutos[sorteio[posicao]]);\n\t\t\t\t   pop[i][posicao_da_troca] = repositorio[pos][rand()%numero_aminos[pos]];\n\t\t\t\t }\n\t\t}\n\t  }\n   }\n}\n\n\/\/ FITNESS OF REFERENCE\nfloat fitnessRef (Atomo *refe, float distanciasref[]){\n   float fit = 0.0, aux;\n   int pos = 0;\n   for(int i=0;i<tam_sitiof;i++)\n\t  for(int j=i+1;j<tam_sitiof;j++){\n\t\t aux = sqrt(pow(refe[i].x - refe[j].x, 2) + pow(refe[i].y - refe[j].y,2)  +  pow(refe[i].z - refe[j].z,2));\n\t\t distanciasref[pos++] = aux;\n\t\t fit = fit + aux;\n\t }\n   return fit;\n}\n\n\/\/ FITNESS OF POPULATION\nvoid fitness(Atomo **p, float fitnessvet[], float distanciasitio[], float distanciasref[]){\n   float fit = 0.0, aux;\n   int pos;\n   for(int k=0; k < tpopulacao; k++){\n\t  pos = 0;\n\t  for(int i=0; i<tam_sitiof; i++)\n\t\t for(int j=i+1; j<tam_sitiof; j++){\n\t\t\taux = sqrt(pow(p[k][i].x - p[k][j].x, 2)  + pow(p[k][i].y - p[k][j].y, 2)  + pow(p[k][i].z - p[k][j].z, 2));\n\t\t\tdistanciasitio[pos++] = aux;\n\t\t }\n\t  for(int i=0;i<tam_dist;i++)\n\t\t fit = fit + fabs(distanciasitio[i]-distanciasref[i]);\n\t  fitnessvet [k]= fit;\n\t  fit = 0.0;\n\n\t  for(int j=0; j<tam_sitiof; j++)\n\t\t  for(int i=j+1; i < tam_sitiof; i++)\n\t\t\t \/\/if (p[k][j].atomo_ID == p[k][i].atomo_ID){\n\t\t if ((p[k][j].atomo_ID == p[k][i].atomo_ID) && (p[k][j].cadeia == p[k][i].cadeia)){\n\t\t\t\t  fitnessvet[k] = fitnessvet[k] + 100.0;\n\t\t\t\t  i = tam_sitiof;\n\t\t\t\t  j = tam_sitiof;\n\t\t\t  }\n   }\n}\n\nint posicaonalista (char teste[20][4], char find[5]){\n\t  for(int i=0; i<20; i++)\n\t\t if (!strcmp(find, teste[i]))\n\t\t\treturn i;\n}\n\n\/\/ BEST OF GENERATION\nint melhordageracao(float fitnessvet[]){\n\tfloat melhor = fitnessvet[0];\n\tint posicao = 0;\n\tfor (int i = 1; i<tpopulacao; i++)\n\t\t if (melhor > fitnessvet[i]){\n\t\t\tmelhor = fitnessvet[i];\n\t\t\tposicao = i;\n\t\t }\n\treturn posicao;\n}\n\n\/\/ FOUND THE BEST OF GENERATION\nint melhordageracaof(float fitnessvet[]){\n\t  float melhor = fitnessvet[0];\n\t  int posicao = 0;\n\t  for (int i = 1; i<ngeracoes; i++)\n\t\t   if (melhor > fitnessvet[i]){\n\t\t\t  melhor = fitnessvet[i];\n\t\t\t  posicao = i;\n\t\t   }\n\t   return posicao;\n}\n\n\/\/ WORST OF GENERATION\nint piordageracao(float fitnessvet[]){\n\tfloat melhor = fitnessvet[0];\n\tint posicao = 0;\n\tfor (int i = 1; i<tpopulacao; i++)\n\t\t if (melhor < fitnessvet[i]){\n\t\t\tmelhor = fitnessvet[i];\n\t\t\tposicao = i;\n\t\t }\n\treturn posicao;\n}\n\n\/\/ WRITE ATOMS ON SCREEN\nvoid EscreveAtomo2(Atomo atomo){\ncout << atomo.amino << \"  \" << atomo.atomo_ID << \"  \" << atomo.x << \"  \" << atomo.y << \"  \" << atomo.z << \"  \" << atomo.cadeia << \"  -  \";\n}\nvoid EscreveAtomo(Atomo atomo){\ncout << atomo.amino << \"  \" << atomo.atomo_ID << \"  \";\n}\n\n\/\/ QUICKSORT\nvoid quickSort(Atomo **tempop, float a[], int l, int r){\n   int j;\n   if( l < r ){\n\t j = partition( tempop, a, l, r);\n\t quickSort(tempop, a, l, j-1);\n\t quickSort(tempop, a, j+1, r);\n   }\n}\n\nint partition(Atomo **tempop, float a[], int l, int r) {\n   float pivot, t;\n   int i, j;\n   Atomo z;\n   pivot = a[l];\n   i = l; j = r+1;\n   while(1) {\n\tdo ++i; while( a[i] <= pivot && i <= r );\n\tdo --j; while( a[j] > pivot );\n\tif( i >= j ) break;\n\tt = a[i]; a[i] = a[j]; a[j] = t;\n\tfor(int k = 0; k<tam_sitiof; k++){\n\t   z = tempop[i][k];\n\t   tempop[i][k] = tempop[j][k];\n\t   tempop[j][k] = z;\n\t}\n   }\n   t = a[l]; a[l] = a[j]; a[j] = t;\n   for(int k = 0; k<tam_sitiof; k++){\n\t   z = tempop[l][k];\n\t   tempop[l][k] = tempop[j][k];\n\t   tempop[j][k] = z;\n   }\n   return j;\n}\n\n\n\/\/ STARTING TOP\nvoid IniciaTop(float *fittop){\n\tfor(int j=0;j<ranking;j++)\n\t   fittop[j] = 1000;\n}\n\n\/\/ OPEN FILE\nbool AbrirArquivo(ifstream &ifs, char nomeArquivo[]){\n\tifs.open(nomeArquivo, ios::binary);\n\treturn ifs.is_open();\n}\n\nvoid CriaListaSubstituicao(Substituicao Matriz[], char *argv){\n\tifstream arquivotexto;  \/\/ vari\u00e1vel para controlar o fluxo de entrada\n\n\tchar localtemplate[200];\n\tstrcpy(localtemplate,argv);\n\tstrcat(localtemplate,\"\/SubstitutionMatrix.txt\");\n   \/\/ fin.open(\"Templates.txt\");\n\n\tarquivotexto.open(localtemplate);\n\tint l1 = 0;\n\tif(!arquivotexto.is_open()){\n\t   cout<<\"File can not be open: SubstitutionMatrix.txt.\\n\";\n\n\t   exit(1);\n\t}\n\telse{\n\t\tchar linha[30];\n\t\t\/\/int l1 = 0;\n\t\twhile(!arquivotexto.eof()){\n\t\t\t arquivotexto.getline(linha,30);\n\t\t\t char temp[10];\n\t\t\t int c1 = 0;\n\t\t\t int c2 = 0;\n\n\t\t\t while(linha[c2]!='\\0'){\n\t\t\t\t  while(linha[c2]!=','){\n\t\t\t\t\t   temp[c1] = (linha[c2]);\n\t\t\t\t\t   c1++; c2++;\n\t\t\t\t  }\n\t\t\t\t  temp[c1]='\\0';\n\t\t\t\t  strcpy(Matriz[l1].lista[0], temp);\n\t\t\t\t  \/\/cout << temp << endl;\n\n\t\t\t\t  c1 = 0; c2++;\n\t\t\t\t  while(linha[c2]!=','){\n\t\t\t\t\t   temp[c1] = linha[c2];\n\t\t\t\t\t   c1++; c2++;\n\t\t\t\t  }\n\t\t\t\t  temp[c1]='\\0';\n\t\t\t\t  strcpy(Matriz[l1].lista[1],temp);\n\t\t\t\t  \/\/cout << temp << endl;\n\n\t\t\t\t  c1 = 0; c2++;\n\t\t\t\t  while(linha[c2]!='\\0'){\n\t\t\t\t\t   temp[c1] = linha[c2];\n\t\t\t\t\t   c1++; c2++;\n\t\t\t\t  }\n\t\t\t\t  temp[c1]='\\0';\n\t\t\t\t  strcpy(Matriz[l1].lista[2],temp);\n\t\t\t\t  \/\/cout << temp << endl;\n\t\t\t }\n\t\t\t l1++;\n\t\t}\n\t}\n}","avg_line_length":29.2785349233,"max_line_length":162,"alphanum_fraction":0.5826084427,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3022,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["BSD-3-Clause"],"max_stars_count":null,"content":"\/*\n * Copyright (c) 2013, Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/testing\/DummyPageHolder.h\"\n\n#include \"core\/frame\/LocalDOMWindow.h\"\n#include \"core\/frame\/FrameView.h\"\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/frame\/Settings.h\"\n#include \"wtf\/Assertions.h\"\n\nnamespace WebCore {\n\nPassOwnPtr<DummyPageHolder> DummyPageHolder::create(const IntSize& initialViewSize)\n{\n    return adoptPtr(new DummyPageHolder(initialViewSize));\n}\n\nDummyPageHolder::DummyPageHolder(const IntSize& initialViewSize)\n{\n    fillWithEmptyClients(m_pageClients);\n    m_page = adoptPtrWillBeNoop(new Page(m_pageClients));\n    Settings& settings = m_page->settings();\n    \/\/ FIXME: http:\/\/crbug.com\/363843. This needs to find a better way to\n    \/\/ not create graphics layers.\n    settings.setAcceleratedCompositingEnabled(false);\n\n    m_frame = LocalFrame::create(&m_frameLoaderClient, &m_page->frameHost(), 0);\n    m_frame->setView(FrameView::create(m_frame.get(), initialViewSize));\n    m_frame->init();\n}\n\nDummyPageHolder::~DummyPageHolder()\n{\n    m_page->willBeDestroyed();\n    m_page.clear();\n#if !ENABLE(OILPAN)\n    ASSERT(m_frame->hasOneRef());\n#endif\n    m_frame.clear();\n}\n\nPage& DummyPageHolder::page() const\n{\n    return *m_page;\n}\n\nLocalFrame& DummyPageHolder::frame() const\n{\n    return *m_frame;\n}\n\nFrameView& DummyPageHolder::frameView() const\n{\n    return *m_frame->view();\n}\n\nDocument& DummyPageHolder::document() const\n{\n    return *m_frame->domWindow()->document();\n}\n\n} \/\/ namespace WebCore\n","avg_line_length":32.847826087,"max_line_length":83,"alphanum_fraction":0.7465254798,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":72429,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["Apache-2.0"],"max_stars_count":null,"content":"\/\/===- ByteCode.cpp - Pattern ByteCode Interpreter ------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements MLIR to byte-code generation and the interpreter.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ByteCode.h\"\n#include \"mlir\/Analysis\/Liveness.h\"\n#include \"mlir\/Dialect\/PDL\/IR\/PDLTypes.h\"\n#include \"mlir\/Dialect\/PDLInterp\/IR\/PDLInterp.h\"\n#include \"mlir\/IR\/BuiltinOps.h\"\n#include \"mlir\/IR\/RegionGraphTraits.h\"\n#include \"llvm\/ADT\/IntervalMap.h\"\n#include \"llvm\/ADT\/PostOrderIterator.h\"\n#include \"llvm\/ADT\/TypeSwitch.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Format.h\"\n#include \"llvm\/Support\/FormatVariadic.h\"\n#include <numeric>\n\n#define DEBUG_TYPE \"pdl-bytecode\"\n\nusing namespace mlir;\nusing namespace mlir::detail;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ PDLByteCodePattern\n\/\/===----------------------------------------------------------------------===\/\/\n\nPDLByteCodePattern PDLByteCodePattern::create(pdl_interp::RecordMatchOp matchOp,\n                                              ByteCodeAddr rewriterAddr) {\n  SmallVector<StringRef, 8> generatedOps;\n  if (ArrayAttr generatedOpsAttr = matchOp.generatedOpsAttr())\n    generatedOps =\n        llvm::to_vector<8>(generatedOpsAttr.getAsValueRange<StringAttr>());\n\n  PatternBenefit benefit = matchOp.benefit();\n  MLIRContext *ctx = matchOp.getContext();\n\n  \/\/ Check to see if this is pattern matches a specific operation type.\n  if (Optional<StringRef> rootKind = matchOp.rootKind())\n    return PDLByteCodePattern(rewriterAddr, *rootKind, benefit, ctx,\n                              generatedOps);\n  return PDLByteCodePattern(rewriterAddr, MatchAnyOpTypeTag(), benefit, ctx,\n                            generatedOps);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ PDLByteCodeMutableState\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ Set the new benefit for a bytecode pattern. The `patternIndex` corresponds\n\/\/\/ to the position of the pattern within the range returned by\n\/\/\/ `PDLByteCode::getPatterns`.\nvoid PDLByteCodeMutableState::updatePatternBenefit(unsigned patternIndex,\n                                                   PatternBenefit benefit) {\n  currentPatternBenefits[patternIndex] = benefit;\n}\n\n\/\/\/ Cleanup any allocated state after a full match\/rewrite has been completed.\n\/\/\/ This method should be called irregardless of whether the match+rewrite was a\n\/\/\/ success or not.\nvoid PDLByteCodeMutableState::cleanupAfterMatchAndRewrite() {\n  allocatedTypeRangeMemory.clear();\n  allocatedValueRangeMemory.clear();\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Bytecode OpCodes\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\nenum OpCode : ByteCodeField {\n  \/\/\/ Apply an externally registered constraint.\n  ApplyConstraint,\n  \/\/\/ Apply an externally registered rewrite.\n  ApplyRewrite,\n  \/\/\/ Check if two generic values are equal.\n  AreEqual,\n  \/\/\/ Check if two ranges are equal.\n  AreRangesEqual,\n  \/\/\/ Unconditional branch.\n  Branch,\n  \/\/\/ Compare the operand count of an operation with a constant.\n  CheckOperandCount,\n  \/\/\/ Compare the name of an operation with a constant.\n  CheckOperationName,\n  \/\/\/ Compare the result count of an operation with a constant.\n  CheckResultCount,\n  \/\/\/ Compare a range of types to a constant range of types.\n  CheckTypes,\n  \/\/\/ Create an operation.\n  CreateOperation,\n  \/\/\/ Create a range of types.\n  CreateTypes,\n  \/\/\/ Erase an operation.\n  EraseOp,\n  \/\/\/ Terminate a matcher or rewrite sequence.\n  Finalize,\n  \/\/\/ Get a specific attribute of an operation.\n  GetAttribute,\n  \/\/\/ Get the type of an attribute.\n  GetAttributeType,\n  \/\/\/ Get the defining operation of a value.\n  GetDefiningOp,\n  \/\/\/ Get a specific operand of an operation.\n  GetOperand0,\n  GetOperand1,\n  GetOperand2,\n  GetOperand3,\n  GetOperandN,\n  \/\/\/ Get a specific operand group of an operation.\n  GetOperands,\n  \/\/\/ Get a specific result of an operation.\n  GetResult0,\n  GetResult1,\n  GetResult2,\n  GetResult3,\n  GetResultN,\n  \/\/\/ Get a specific result group of an operation.\n  GetResults,\n  \/\/\/ Get the type of a value.\n  GetValueType,\n  \/\/\/ Get the types of a value range.\n  GetValueRangeTypes,\n  \/\/\/ Check if a generic value is not null.\n  IsNotNull,\n  \/\/\/ Record a successful pattern match.\n  RecordMatch,\n  \/\/\/ Replace an operation.\n  ReplaceOp,\n  \/\/\/ Compare an attribute with a set of constants.\n  SwitchAttribute,\n  \/\/\/ Compare the operand count of an operation with a set of constants.\n  SwitchOperandCount,\n  \/\/\/ Compare the name of an operation with a set of constants.\n  SwitchOperationName,\n  \/\/\/ Compare the result count of an operation with a set of constants.\n  SwitchResultCount,\n  \/\/\/ Compare a type with a set of constants.\n  SwitchType,\n  \/\/\/ Compare a range of types with a set of constants.\n  SwitchTypes,\n};\n} \/\/ end anonymous namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ ByteCode Generation\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Generator\n\nnamespace {\nstruct ByteCodeWriter;\n\n\/\/\/ This class represents the main generator for the pattern bytecode.\nclass Generator {\npublic:\n  Generator(MLIRContext *ctx, std::vector<const void *> &uniquedData,\n            SmallVectorImpl<ByteCodeField> &matcherByteCode,\n            SmallVectorImpl<ByteCodeField> &rewriterByteCode,\n            SmallVectorImpl<PDLByteCodePattern> &patterns,\n            ByteCodeField &maxValueMemoryIndex,\n            ByteCodeField &maxTypeRangeMemoryIndex,\n            ByteCodeField &maxValueRangeMemoryIndex,\n            llvm::StringMap<PDLConstraintFunction> &constraintFns,\n            llvm::StringMap<PDLRewriteFunction> &rewriteFns)\n      : ctx(ctx), uniquedData(uniquedData), matcherByteCode(matcherByteCode),\n        rewriterByteCode(rewriterByteCode), patterns(patterns),\n        maxValueMemoryIndex(maxValueMemoryIndex),\n        maxTypeRangeMemoryIndex(maxTypeRangeMemoryIndex),\n        maxValueRangeMemoryIndex(maxValueRangeMemoryIndex) {\n    for (auto it : llvm::enumerate(constraintFns))\n      constraintToMemIndex.try_emplace(it.value().first(), it.index());\n    for (auto it : llvm::enumerate(rewriteFns))\n      externalRewriterToMemIndex.try_emplace(it.value().first(), it.index());\n  }\n\n  \/\/\/ Generate the bytecode for the given PDL interpreter module.\n  void generate(ModuleOp module);\n\n  \/\/\/ Return the memory index to use for the given value.\n  ByteCodeField &getMemIndex(Value value) {\n    assert(valueToMemIndex.count(value) &&\n           \"expected memory index to be assigned\");\n    return valueToMemIndex[value];\n  }\n\n  \/\/\/ Return the range memory index used to store the given range value.\n  ByteCodeField &getRangeStorageIndex(Value value) {\n    assert(valueToRangeIndex.count(value) &&\n           \"expected range index to be assigned\");\n    return valueToRangeIndex[value];\n  }\n\n  \/\/\/ Return an index to use when referring to the given data that is uniqued in\n  \/\/\/ the MLIR context.\n  template <typename T>\n  std::enable_if_t<!std::is_convertible<T, Value>::value, ByteCodeField &>\n  getMemIndex(T val) {\n    const void *opaqueVal = val.getAsOpaquePointer();\n\n    \/\/ Get or insert a reference to this value.\n    auto it = uniquedDataToMemIndex.try_emplace(\n        opaqueVal, maxValueMemoryIndex + uniquedData.size());\n    if (it.second)\n      uniquedData.push_back(opaqueVal);\n    return it.first->second;\n  }\n\nprivate:\n  \/\/\/ Allocate memory indices for the results of operations within the matcher\n  \/\/\/ and rewriters.\n  void allocateMemoryIndices(FuncOp matcherFunc, ModuleOp rewriterModule);\n\n  \/\/\/ Generate the bytecode for the given operation.\n  void generate(Operation *op, ByteCodeWriter &writer);\n  void generate(pdl_interp::ApplyConstraintOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::ApplyRewriteOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::AreEqualOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::BranchOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::CheckAttributeOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::CheckOperandCountOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::CheckOperationNameOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::CheckResultCountOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::CheckTypeOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::CheckTypesOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::CreateAttributeOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::CreateOperationOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::CreateTypeOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::CreateTypesOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::EraseOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::FinalizeOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::GetAttributeOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::GetAttributeTypeOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::GetDefiningOpOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::GetOperandOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::GetOperandsOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::GetResultOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::GetResultsOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::GetValueTypeOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::InferredTypesOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::IsNotNullOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::RecordMatchOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::ReplaceOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::SwitchAttributeOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::SwitchTypeOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::SwitchTypesOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::SwitchOperandCountOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::SwitchOperationNameOp op, ByteCodeWriter &writer);\n  void generate(pdl_interp::SwitchResultCountOp op, ByteCodeWriter &writer);\n\n  \/\/\/ Mapping from value to its corresponding memory index.\n  DenseMap<Value, ByteCodeField> valueToMemIndex;\n\n  \/\/\/ Mapping from a range value to its corresponding range storage index.\n  DenseMap<Value, ByteCodeField> valueToRangeIndex;\n\n  \/\/\/ Mapping from the name of an externally registered rewrite to its index in\n  \/\/\/ the bytecode registry.\n  llvm::StringMap<ByteCodeField> externalRewriterToMemIndex;\n\n  \/\/\/ Mapping from the name of an externally registered constraint to its index\n  \/\/\/ in the bytecode registry.\n  llvm::StringMap<ByteCodeField> constraintToMemIndex;\n\n  \/\/\/ Mapping from rewriter function name to the bytecode address of the\n  \/\/\/ rewriter function in byte.\n  llvm::StringMap<ByteCodeAddr> rewriterToAddr;\n\n  \/\/\/ Mapping from a uniqued storage object to its memory index within\n  \/\/\/ `uniquedData`.\n  DenseMap<const void *, ByteCodeField> uniquedDataToMemIndex;\n\n  \/\/\/ The current MLIR context.\n  MLIRContext *ctx;\n\n  \/\/\/ Data of the ByteCode class to be populated.\n  std::vector<const void *> &uniquedData;\n  SmallVectorImpl<ByteCodeField> &matcherByteCode;\n  SmallVectorImpl<ByteCodeField> &rewriterByteCode;\n  SmallVectorImpl<PDLByteCodePattern> &patterns;\n  ByteCodeField &maxValueMemoryIndex;\n  ByteCodeField &maxTypeRangeMemoryIndex;\n  ByteCodeField &maxValueRangeMemoryIndex;\n};\n\n\/\/\/ This class provides utilities for writing a bytecode stream.\nstruct ByteCodeWriter {\n  ByteCodeWriter(SmallVectorImpl<ByteCodeField> &bytecode, Generator &generator)\n      : bytecode(bytecode), generator(generator) {}\n\n  \/\/\/ Append a field to the bytecode.\n  void append(ByteCodeField field) { bytecode.push_back(field); }\n  void append(OpCode opCode) { bytecode.push_back(opCode); }\n\n  \/\/\/ Append an address to the bytecode.\n  void append(ByteCodeAddr field) {\n    static_assert((sizeof(ByteCodeAddr) \/ sizeof(ByteCodeField)) == 2,\n                  \"unexpected ByteCode address size\");\n\n    ByteCodeField fieldParts[2];\n    std::memcpy(fieldParts, &field, sizeof(ByteCodeAddr));\n    bytecode.append({fieldParts[0], fieldParts[1]});\n  }\n\n  \/\/\/ Append a successor range to the bytecode, the exact address will need to\n  \/\/\/ be resolved later.\n  void append(SuccessorRange successors) {\n    \/\/ Add back references to the any successors so that the address can be\n    \/\/ resolved later.\n    for (Block *successor : successors) {\n      unresolvedSuccessorRefs[successor].push_back(bytecode.size());\n      append(ByteCodeAddr(0));\n    }\n  }\n\n  \/\/\/ Append a range of values that will be read as generic PDLValues.\n  void appendPDLValueList(OperandRange values) {\n    bytecode.push_back(values.size());\n    for (Value value : values)\n      appendPDLValue(value);\n  }\n\n  \/\/\/ Append a value as a PDLValue.\n  void appendPDLValue(Value value) {\n    appendPDLValueKind(value);\n    append(value);\n  }\n\n  \/\/\/ Append the PDLValue::Kind of the given value.\n  void appendPDLValueKind(Value value) {\n    \/\/ Append the type of the value in addition to the value itself.\n    PDLValue::Kind kind =\n        TypeSwitch<Type, PDLValue::Kind>(value.getType())\n            .Case<pdl::AttributeType>(\n                [](Type) { return PDLValue::Kind::Attribute; })\n            .Case<pdl::OperationType>(\n                [](Type) { return PDLValue::Kind::Operation; })\n            .Case<pdl::RangeType>([](pdl::RangeType rangeTy) {\n              if (rangeTy.getElementType().isa<pdl::TypeType>())\n                return PDLValue::Kind::TypeRange;\n              return PDLValue::Kind::ValueRange;\n            })\n            .Case<pdl::TypeType>([](Type) { return PDLValue::Kind::Type; })\n            .Case<pdl::ValueType>([](Type) { return PDLValue::Kind::Value; });\n    bytecode.push_back(static_cast<ByteCodeField>(kind));\n  }\n\n  \/\/\/ Check if the given class `T` has an iterator type.\n  template <typename T, typename... Args>\n  using has_pointer_traits = decltype(std::declval<T>().getAsOpaquePointer());\n\n  \/\/\/ Append a value that will be stored in a memory slot and not inline within\n  \/\/\/ the bytecode.\n  template <typename T>\n  std::enable_if_t<llvm::is_detected<has_pointer_traits, T>::value ||\n                   std::is_pointer<T>::value>\n  append(T value) {\n    bytecode.push_back(generator.getMemIndex(value));\n  }\n\n  \/\/\/ Append a range of values.\n  template <typename T, typename IteratorT = llvm::detail::IterOfRange<T>>\n  std::enable_if_t<!llvm::is_detected<has_pointer_traits, T>::value>\n  append(T range) {\n    bytecode.push_back(llvm::size(range));\n    for (auto it : range)\n      append(it);\n  }\n\n  \/\/\/ Append a variadic number of fields to the bytecode.\n  template <typename FieldTy, typename Field2Ty, typename... FieldTys>\n  void append(FieldTy field, Field2Ty field2, FieldTys... fields) {\n    append(field);\n    append(field2, fields...);\n  }\n\n  \/\/\/ Successor references in the bytecode that have yet to be resolved.\n  DenseMap<Block *, SmallVector<unsigned, 4>> unresolvedSuccessorRefs;\n\n  \/\/\/ The underlying bytecode buffer.\n  SmallVectorImpl<ByteCodeField> &bytecode;\n\n  \/\/\/ The main generator producing PDL.\n  Generator &generator;\n};\n\n\/\/\/ This class represents a live range of PDL Interpreter values, containing\n\/\/\/ information about when values are live within a match\/rewrite.\nstruct ByteCodeLiveRange {\n  using Set = llvm::IntervalMap<ByteCodeField, char, 16>;\n  using Allocator = Set::Allocator;\n\n  ByteCodeLiveRange(Allocator &alloc) : liveness(alloc) {}\n\n  \/\/\/ Union this live range with the one provided.\n  void unionWith(const ByteCodeLiveRange &rhs) {\n    for (auto it = rhs.liveness.begin(), e = rhs.liveness.end(); it != e; ++it)\n      liveness.insert(it.start(), it.stop(), \/*dummyValue*\/ 0);\n  }\n\n  \/\/\/ Returns true if this range overlaps with the one provided.\n  bool overlaps(const ByteCodeLiveRange &rhs) const {\n    return llvm::IntervalMapOverlaps<Set, Set>(liveness, rhs.liveness).valid();\n  }\n\n  \/\/\/ A map representing the ranges of the match\/rewrite that a value is live in\n  \/\/\/ the interpreter.\n  llvm::IntervalMap<ByteCodeField, char, 16> liveness;\n\n  \/\/\/ The type range storage index for this range.\n  Optional<unsigned> typeRangeIndex;\n\n  \/\/\/ The value range storage index for this range.\n  Optional<unsigned> valueRangeIndex;\n};\n} \/\/ end anonymous namespace\n\nvoid Generator::generate(ModuleOp module) {\n  FuncOp matcherFunc = module.lookupSymbol<FuncOp>(\n      pdl_interp::PDLInterpDialect::getMatcherFunctionName());\n  ModuleOp rewriterModule = module.lookupSymbol<ModuleOp>(\n      pdl_interp::PDLInterpDialect::getRewriterModuleName());\n  assert(matcherFunc && rewriterModule && \"invalid PDL Interpreter module\");\n\n  \/\/ Allocate memory indices for the results of operations within the matcher\n  \/\/ and rewriters.\n  allocateMemoryIndices(matcherFunc, rewriterModule);\n\n  \/\/ Generate code for the rewriter functions.\n  ByteCodeWriter rewriterByteCodeWriter(rewriterByteCode, *this);\n  for (FuncOp rewriterFunc : rewriterModule.getOps<FuncOp>()) {\n    rewriterToAddr.try_emplace(rewriterFunc.getName(), rewriterByteCode.size());\n    for (Operation &op : rewriterFunc.getOps())\n      generate(&op, rewriterByteCodeWriter);\n  }\n  assert(rewriterByteCodeWriter.unresolvedSuccessorRefs.empty() &&\n         \"unexpected branches in rewriter function\");\n\n  \/\/ Generate code for the matcher function.\n  DenseMap<Block *, ByteCodeAddr> blockToAddr;\n  llvm::ReversePostOrderTraversal<Region *> rpot(&matcherFunc.getBody());\n  ByteCodeWriter matcherByteCodeWriter(matcherByteCode, *this);\n  for (Block *block : rpot) {\n    \/\/ Keep track of where this block begins within the matcher function.\n    blockToAddr.try_emplace(block, matcherByteCode.size());\n    for (Operation &op : *block)\n      generate(&op, matcherByteCodeWriter);\n  }\n\n  \/\/ Resolve successor references in the matcher.\n  for (auto &it : matcherByteCodeWriter.unresolvedSuccessorRefs) {\n    ByteCodeAddr addr = blockToAddr[it.first];\n    for (unsigned offsetToFix : it.second)\n      std::memcpy(&matcherByteCode[offsetToFix], &addr, sizeof(ByteCodeAddr));\n  }\n}\n\nvoid Generator::allocateMemoryIndices(FuncOp matcherFunc,\n                                      ModuleOp rewriterModule) {\n  \/\/ Rewriters use simplistic allocation scheme that simply assigns an index to\n  \/\/ each result.\n  for (FuncOp rewriterFunc : rewriterModule.getOps<FuncOp>()) {\n    ByteCodeField index = 0, typeRangeIndex = 0, valueRangeIndex = 0;\n    auto processRewriterValue = [&](Value val) {\n      valueToMemIndex.try_emplace(val, index++);\n      if (pdl::RangeType rangeType = val.getType().dyn_cast<pdl::RangeType>()) {\n        Type elementTy = rangeType.getElementType();\n        if (elementTy.isa<pdl::TypeType>())\n          valueToRangeIndex.try_emplace(val, typeRangeIndex++);\n        else if (elementTy.isa<pdl::ValueType>())\n          valueToRangeIndex.try_emplace(val, valueRangeIndex++);\n      }\n    };\n\n    for (BlockArgument arg : rewriterFunc.getArguments())\n      processRewriterValue(arg);\n    rewriterFunc.getBody().walk([&](Operation *op) {\n      for (Value result : op->getResults())\n        processRewriterValue(result);\n    });\n    if (index > maxValueMemoryIndex)\n      maxValueMemoryIndex = index;\n    if (typeRangeIndex > maxTypeRangeMemoryIndex)\n      maxTypeRangeMemoryIndex = typeRangeIndex;\n    if (valueRangeIndex > maxValueRangeMemoryIndex)\n      maxValueRangeMemoryIndex = valueRangeIndex;\n  }\n\n  \/\/ The matcher function uses a more sophisticated numbering that tries to\n  \/\/ minimize the number of memory indices assigned. This is done by determining\n  \/\/ a live range of the values within the matcher, then the allocation is just\n  \/\/ finding the minimal number of overlapping live ranges. This is essentially\n  \/\/ a simplified form of register allocation where we don't necessarily have a\n  \/\/ limited number of registers, but we still want to minimize the number used.\n  DenseMap<Operation *, ByteCodeField> opToIndex;\n  matcherFunc.getBody().walk([&](Operation *op) {\n    opToIndex.insert(std::make_pair(op, opToIndex.size()));\n  });\n\n  \/\/ Liveness info for each of the defs within the matcher.\n  ByteCodeLiveRange::Allocator allocator;\n  DenseMap<Value, ByteCodeLiveRange> valueDefRanges;\n\n  \/\/ Assign the root operation being matched to slot 0.\n  BlockArgument rootOpArg = matcherFunc.getArgument(0);\n  valueToMemIndex[rootOpArg] = 0;\n\n  \/\/ Walk each of the blocks, computing the def interval that the value is used.\n  Liveness matcherLiveness(matcherFunc);\n  for (Block &block : matcherFunc.getBody()) {\n    const LivenessBlockInfo *info = matcherLiveness.getLiveness(&block);\n    assert(info && \"expected liveness info for block\");\n    auto processValue = [&](Value value, Operation *firstUseOrDef) {\n      \/\/ We don't need to process the root op argument, this value is always\n      \/\/ assigned to the first memory slot.\n      if (value == rootOpArg)\n        return;\n\n      \/\/ Set indices for the range of this block that the value is used.\n      auto defRangeIt = valueDefRanges.try_emplace(value, allocator).first;\n      defRangeIt->second.liveness.insert(\n          opToIndex[firstUseOrDef],\n          opToIndex[info->getEndOperation(value, firstUseOrDef)],\n          \/*dummyValue*\/ 0);\n\n      \/\/ Check to see if this value is a range type.\n      if (auto rangeTy = value.getType().dyn_cast<pdl::RangeType>()) {\n        Type eleType = rangeTy.getElementType();\n        if (eleType.isa<pdl::TypeType>())\n          defRangeIt->second.typeRangeIndex = 0;\n        else if (eleType.isa<pdl::ValueType>())\n          defRangeIt->second.valueRangeIndex = 0;\n      }\n    };\n\n    \/\/ Process the live-ins of this block.\n    for (Value liveIn : info->in())\n      processValue(liveIn, &block.front());\n\n    \/\/ Process any new defs within this block.\n    for (Operation &op : block)\n      for (Value result : op.getResults())\n        processValue(result, &op);\n  }\n\n  \/\/ Greedily allocate memory slots using the computed def live ranges.\n  std::vector<ByteCodeLiveRange> allocatedIndices;\n  ByteCodeField numIndices = 1, numTypeRanges = 0, numValueRanges = 0;\n  for (auto &defIt : valueDefRanges) {\n    ByteCodeField &memIndex = valueToMemIndex[defIt.first];\n    ByteCodeLiveRange &defRange = defIt.second;\n\n    \/\/ Try to allocate to an existing index.\n    for (auto existingIndexIt : llvm::enumerate(allocatedIndices)) {\n      ByteCodeLiveRange &existingRange = existingIndexIt.value();\n      if (!defRange.overlaps(existingRange)) {\n        existingRange.unionWith(defRange);\n        memIndex = existingIndexIt.index() + 1;\n\n        if (defRange.typeRangeIndex) {\n          if (!existingRange.typeRangeIndex)\n            existingRange.typeRangeIndex = numTypeRanges++;\n          valueToRangeIndex[defIt.first] = *existingRange.typeRangeIndex;\n        } else if (defRange.valueRangeIndex) {\n          if (!existingRange.valueRangeIndex)\n            existingRange.valueRangeIndex = numValueRanges++;\n          valueToRangeIndex[defIt.first] = *existingRange.valueRangeIndex;\n        }\n        break;\n      }\n    }\n\n    \/\/ If no existing index could be used, add a new one.\n    if (memIndex == 0) {\n      allocatedIndices.emplace_back(allocator);\n      ByteCodeLiveRange &newRange = allocatedIndices.back();\n      newRange.unionWith(defRange);\n\n      \/\/ Allocate an index for type\/value ranges.\n      if (defRange.typeRangeIndex) {\n        newRange.typeRangeIndex = numTypeRanges;\n        valueToRangeIndex[defIt.first] = numTypeRanges++;\n      } else if (defRange.valueRangeIndex) {\n        newRange.valueRangeIndex = numValueRanges;\n        valueToRangeIndex[defIt.first] = numValueRanges++;\n      }\n\n      memIndex = allocatedIndices.size();\n      ++numIndices;\n    }\n  }\n\n  \/\/ Update the max number of indices.\n  if (numIndices > maxValueMemoryIndex)\n    maxValueMemoryIndex = numIndices;\n  if (numTypeRanges > maxTypeRangeMemoryIndex)\n    maxTypeRangeMemoryIndex = numTypeRanges;\n  if (numValueRanges > maxValueRangeMemoryIndex)\n    maxValueRangeMemoryIndex = numValueRanges;\n}\n\nvoid Generator::generate(Operation *op, ByteCodeWriter &writer) {\n  TypeSwitch<Operation *>(op)\n      .Case<pdl_interp::ApplyConstraintOp, pdl_interp::ApplyRewriteOp,\n            pdl_interp::AreEqualOp, pdl_interp::BranchOp,\n            pdl_interp::CheckAttributeOp, pdl_interp::CheckOperandCountOp,\n            pdl_interp::CheckOperationNameOp, pdl_interp::CheckResultCountOp,\n            pdl_interp::CheckTypeOp, pdl_interp::CheckTypesOp,\n            pdl_interp::CreateAttributeOp, pdl_interp::CreateOperationOp,\n            pdl_interp::CreateTypeOp, pdl_interp::CreateTypesOp,\n            pdl_interp::EraseOp, pdl_interp::FinalizeOp,\n            pdl_interp::GetAttributeOp, pdl_interp::GetAttributeTypeOp,\n            pdl_interp::GetDefiningOpOp, pdl_interp::GetOperandOp,\n            pdl_interp::GetOperandsOp, pdl_interp::GetResultOp,\n            pdl_interp::GetResultsOp, pdl_interp::GetValueTypeOp,\n            pdl_interp::InferredTypesOp, pdl_interp::IsNotNullOp,\n            pdl_interp::RecordMatchOp, pdl_interp::ReplaceOp,\n            pdl_interp::SwitchAttributeOp, pdl_interp::SwitchTypeOp,\n            pdl_interp::SwitchTypesOp, pdl_interp::SwitchOperandCountOp,\n            pdl_interp::SwitchOperationNameOp, pdl_interp::SwitchResultCountOp>(\n          [&](auto interpOp) { this->generate(interpOp, writer); })\n      .Default([](Operation *) {\n        llvm_unreachable(\"unknown `pdl_interp` operation\");\n      });\n}\n\nvoid Generator::generate(pdl_interp::ApplyConstraintOp op,\n                         ByteCodeWriter &writer) {\n  assert(constraintToMemIndex.count(op.name()) &&\n         \"expected index for constraint function\");\n  writer.append(OpCode::ApplyConstraint, constraintToMemIndex[op.name()],\n                op.constParamsAttr());\n  writer.appendPDLValueList(op.args());\n  writer.append(op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::ApplyRewriteOp op,\n                         ByteCodeWriter &writer) {\n  assert(externalRewriterToMemIndex.count(op.name()) &&\n         \"expected index for rewrite function\");\n  writer.append(OpCode::ApplyRewrite, externalRewriterToMemIndex[op.name()],\n                op.constParamsAttr());\n  writer.appendPDLValueList(op.args());\n\n  ResultRange results = op.results();\n  writer.append(ByteCodeField(results.size()));\n  for (Value result : results) {\n    \/\/ In debug mode we also record the expected kind of the result, so that we\n    \/\/ can provide extra verification of the native rewrite function.\n#ifndef NDEBUG\n    writer.appendPDLValueKind(result);\n#endif\n\n    \/\/ Range results also need to append the range storage index.\n    if (result.getType().isa<pdl::RangeType>())\n      writer.append(getRangeStorageIndex(result));\n    writer.append(result);\n  }\n}\nvoid Generator::generate(pdl_interp::AreEqualOp op, ByteCodeWriter &writer) {\n  Value lhs = op.lhs();\n  if (lhs.getType().isa<pdl::RangeType>()) {\n    writer.append(OpCode::AreRangesEqual);\n    writer.appendPDLValueKind(lhs);\n    writer.append(op.lhs(), op.rhs(), op.getSuccessors());\n    return;\n  }\n\n  writer.append(OpCode::AreEqual, lhs, op.rhs(), op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::BranchOp op, ByteCodeWriter &writer) {\n  writer.append(OpCode::Branch, SuccessorRange(op.getOperation()));\n}\nvoid Generator::generate(pdl_interp::CheckAttributeOp op,\n                         ByteCodeWriter &writer) {\n  writer.append(OpCode::AreEqual, op.attribute(), op.constantValue(),\n                op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::CheckOperandCountOp op,\n                         ByteCodeWriter &writer) {\n  writer.append(OpCode::CheckOperandCount, op.operation(), op.count(),\n                static_cast<ByteCodeField>(op.compareAtLeast()),\n                op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::CheckOperationNameOp op,\n                         ByteCodeWriter &writer) {\n  writer.append(OpCode::CheckOperationName, op.operation(),\n                OperationName(op.name(), ctx), op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::CheckResultCountOp op,\n                         ByteCodeWriter &writer) {\n  writer.append(OpCode::CheckResultCount, op.operation(), op.count(),\n                static_cast<ByteCodeField>(op.compareAtLeast()),\n                op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::CheckTypeOp op, ByteCodeWriter &writer) {\n  writer.append(OpCode::AreEqual, op.value(), op.type(), op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::CheckTypesOp op, ByteCodeWriter &writer) {\n  writer.append(OpCode::CheckTypes, op.value(), op.types(), op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::CreateAttributeOp op,\n                         ByteCodeWriter &writer) {\n  \/\/ Simply repoint the memory index of the result to the constant.\n  getMemIndex(op.attribute()) = getMemIndex(op.value());\n}\nvoid Generator::generate(pdl_interp::CreateOperationOp op,\n                         ByteCodeWriter &writer) {\n  writer.append(OpCode::CreateOperation, op.operation(),\n                OperationName(op.name(), ctx));\n  writer.appendPDLValueList(op.operands());\n\n  \/\/ Add the attributes.\n  OperandRange attributes = op.attributes();\n  writer.append(static_cast<ByteCodeField>(attributes.size()));\n  for (auto it : llvm::zip(op.attributeNames(), op.attributes()))\n    writer.append(std::get<0>(it), std::get<1>(it));\n  writer.appendPDLValueList(op.types());\n}\nvoid Generator::generate(pdl_interp::CreateTypeOp op, ByteCodeWriter &writer) {\n  \/\/ Simply repoint the memory index of the result to the constant.\n  getMemIndex(op.result()) = getMemIndex(op.value());\n}\nvoid Generator::generate(pdl_interp::CreateTypesOp op, ByteCodeWriter &writer) {\n  writer.append(OpCode::CreateTypes, op.result(),\n                getRangeStorageIndex(op.result()), op.value());\n}\nvoid Generator::generate(pdl_interp::EraseOp op, ByteCodeWriter &writer) {\n  writer.append(OpCode::EraseOp, op.operation());\n}\nvoid Generator::generate(pdl_interp::FinalizeOp op, ByteCodeWriter &writer) {\n  writer.append(OpCode::Finalize);\n}\nvoid Generator::generate(pdl_interp::GetAttributeOp op,\n                         ByteCodeWriter &writer) {\n  writer.append(OpCode::GetAttribute, op.attribute(), op.operation(),\n                op.nameAttr());\n}\nvoid Generator::generate(pdl_interp::GetAttributeTypeOp op,\n                         ByteCodeWriter &writer) {\n  writer.append(OpCode::GetAttributeType, op.result(), op.value());\n}\nvoid Generator::generate(pdl_interp::GetDefiningOpOp op,\n                         ByteCodeWriter &writer) {\n  writer.append(OpCode::GetDefiningOp, op.operation());\n  writer.appendPDLValue(op.value());\n}\nvoid Generator::generate(pdl_interp::GetOperandOp op, ByteCodeWriter &writer) {\n  uint32_t index = op.index();\n  if (index < 4)\n    writer.append(static_cast<OpCode>(OpCode::GetOperand0 + index));\n  else\n    writer.append(OpCode::GetOperandN, index);\n  writer.append(op.operation(), op.value());\n}\nvoid Generator::generate(pdl_interp::GetOperandsOp op, ByteCodeWriter &writer) {\n  Value result = op.value();\n  Optional<uint32_t> index = op.index();\n  writer.append(OpCode::GetOperands,\n                index.getValueOr(std::numeric_limits<uint32_t>::max()),\n                op.operation());\n  if (result.getType().isa<pdl::RangeType>())\n    writer.append(getRangeStorageIndex(result));\n  else\n    writer.append(std::numeric_limits<ByteCodeField>::max());\n  writer.append(result);\n}\nvoid Generator::generate(pdl_interp::GetResultOp op, ByteCodeWriter &writer) {\n  uint32_t index = op.index();\n  if (index < 4)\n    writer.append(static_cast<OpCode>(OpCode::GetResult0 + index));\n  else\n    writer.append(OpCode::GetResultN, index);\n  writer.append(op.operation(), op.value());\n}\nvoid Generator::generate(pdl_interp::GetResultsOp op, ByteCodeWriter &writer) {\n  Value result = op.value();\n  Optional<uint32_t> index = op.index();\n  writer.append(OpCode::GetResults,\n                index.getValueOr(std::numeric_limits<uint32_t>::max()),\n                op.operation());\n  if (result.getType().isa<pdl::RangeType>())\n    writer.append(getRangeStorageIndex(result));\n  else\n    writer.append(std::numeric_limits<ByteCodeField>::max());\n  writer.append(result);\n}\nvoid Generator::generate(pdl_interp::GetValueTypeOp op,\n                         ByteCodeWriter &writer) {\n  if (op.getType().isa<pdl::RangeType>()) {\n    Value result = op.result();\n    writer.append(OpCode::GetValueRangeTypes, result,\n                  getRangeStorageIndex(result), op.value());\n  } else {\n    writer.append(OpCode::GetValueType, op.result(), op.value());\n  }\n}\n\nvoid Generator::generate(pdl_interp::InferredTypesOp op,\n                         ByteCodeWriter &writer) {\n  \/\/ InferType maps to a null type as a marker for inferring result types.\n  getMemIndex(op.type()) = getMemIndex(Type());\n}\nvoid Generator::generate(pdl_interp::IsNotNullOp op, ByteCodeWriter &writer) {\n  writer.append(OpCode::IsNotNull, op.value(), op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::RecordMatchOp op, ByteCodeWriter &writer) {\n  ByteCodeField patternIndex = patterns.size();\n  patterns.emplace_back(PDLByteCodePattern::create(\n      op, rewriterToAddr[op.rewriter().getLeafReference().getValue()]));\n  writer.append(OpCode::RecordMatch, patternIndex,\n                SuccessorRange(op.getOperation()), op.matchedOps());\n  writer.appendPDLValueList(op.inputs());\n}\nvoid Generator::generate(pdl_interp::ReplaceOp op, ByteCodeWriter &writer) {\n  writer.append(OpCode::ReplaceOp, op.operation());\n  writer.appendPDLValueList(op.replValues());\n}\nvoid Generator::generate(pdl_interp::SwitchAttributeOp op,\n                         ByteCodeWriter &writer) {\n  writer.append(OpCode::SwitchAttribute, op.attribute(), op.caseValuesAttr(),\n                op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::SwitchOperandCountOp op,\n                         ByteCodeWriter &writer) {\n  writer.append(OpCode::SwitchOperandCount, op.operation(), op.caseValuesAttr(),\n                op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::SwitchOperationNameOp op,\n                         ByteCodeWriter &writer) {\n  auto cases = llvm::map_range(op.caseValuesAttr(), [&](Attribute attr) {\n    return OperationName(attr.cast<StringAttr>().getValue(), ctx);\n  });\n  writer.append(OpCode::SwitchOperationName, op.operation(), cases,\n                op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::SwitchResultCountOp op,\n                         ByteCodeWriter &writer) {\n  writer.append(OpCode::SwitchResultCount, op.operation(), op.caseValuesAttr(),\n                op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::SwitchTypeOp op, ByteCodeWriter &writer) {\n  writer.append(OpCode::SwitchType, op.value(), op.caseValuesAttr(),\n                op.getSuccessors());\n}\nvoid Generator::generate(pdl_interp::SwitchTypesOp op, ByteCodeWriter &writer) {\n  writer.append(OpCode::SwitchTypes, op.value(), op.caseValuesAttr(),\n                op.getSuccessors());\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ PDLByteCode\n\/\/===----------------------------------------------------------------------===\/\/\n\nPDLByteCode::PDLByteCode(ModuleOp module,\n                         llvm::StringMap<PDLConstraintFunction> constraintFns,\n                         llvm::StringMap<PDLRewriteFunction> rewriteFns) {\n  Generator generator(module.getContext(), uniquedData, matcherByteCode,\n                      rewriterByteCode, patterns, maxValueMemoryIndex,\n                      maxTypeRangeCount, maxValueRangeCount, constraintFns,\n                      rewriteFns);\n  generator.generate(module);\n\n  \/\/ Initialize the external functions.\n  for (auto &it : constraintFns)\n    constraintFunctions.push_back(std::move(it.second));\n  for (auto &it : rewriteFns)\n    rewriteFunctions.push_back(std::move(it.second));\n}\n\n\/\/\/ Initialize the given state such that it can be used to execute the current\n\/\/\/ bytecode.\nvoid PDLByteCode::initializeMutableState(PDLByteCodeMutableState &state) const {\n  state.memory.resize(maxValueMemoryIndex, nullptr);\n  state.typeRangeMemory.resize(maxTypeRangeCount, TypeRange());\n  state.valueRangeMemory.resize(maxValueRangeCount, ValueRange());\n  state.currentPatternBenefits.reserve(patterns.size());\n  for (const PDLByteCodePattern &pattern : patterns)\n    state.currentPatternBenefits.push_back(pattern.getBenefit());\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ ByteCode Execution\n\nnamespace {\n\/\/\/ This class provides support for executing a bytecode stream.\nclass ByteCodeExecutor {\npublic:\n  ByteCodeExecutor(\n      const ByteCodeField *curCodeIt, MutableArrayRef<const void *> memory,\n      MutableArrayRef<TypeRange> typeRangeMemory,\n      std::vector<llvm::OwningArrayRef<Type>> &allocatedTypeRangeMemory,\n      MutableArrayRef<ValueRange> valueRangeMemory,\n      std::vector<llvm::OwningArrayRef<Value>> &allocatedValueRangeMemory,\n      ArrayRef<const void *> uniquedMemory, ArrayRef<ByteCodeField> code,\n      ArrayRef<PatternBenefit> currentPatternBenefits,\n      ArrayRef<PDLByteCodePattern> patterns,\n      ArrayRef<PDLConstraintFunction> constraintFunctions,\n      ArrayRef<PDLRewriteFunction> rewriteFunctions)\n      : curCodeIt(curCodeIt), memory(memory), typeRangeMemory(typeRangeMemory),\n        allocatedTypeRangeMemory(allocatedTypeRangeMemory),\n        valueRangeMemory(valueRangeMemory),\n        allocatedValueRangeMemory(allocatedValueRangeMemory),\n        uniquedMemory(uniquedMemory), code(code),\n        currentPatternBenefits(currentPatternBenefits), patterns(patterns),\n        constraintFunctions(constraintFunctions),\n        rewriteFunctions(rewriteFunctions) {}\n\n  \/\/\/ Start executing the code at the current bytecode index. `matches` is an\n  \/\/\/ optional field provided when this function is executed in a matching\n  \/\/\/ context.\n  void execute(PatternRewriter &rewriter,\n               SmallVectorImpl<PDLByteCode::MatchResult> *matches = nullptr,\n               Optional<Location> mainRewriteLoc = {});\n\nprivate:\n  \/\/\/ Internal implementation of executing each of the bytecode commands.\n  void executeApplyConstraint(PatternRewriter &rewriter);\n  void executeApplyRewrite(PatternRewriter &rewriter);\n  void executeAreEqual();\n  void executeAreRangesEqual();\n  void executeBranch();\n  void executeCheckOperandCount();\n  void executeCheckOperationName();\n  void executeCheckResultCount();\n  void executeCheckTypes();\n  void executeCreateOperation(PatternRewriter &rewriter,\n                              Location mainRewriteLoc);\n  void executeCreateTypes();\n  void executeEraseOp(PatternRewriter &rewriter);\n  void executeGetAttribute();\n  void executeGetAttributeType();\n  void executeGetDefiningOp();\n  void executeGetOperand(unsigned index);\n  void executeGetOperands();\n  void executeGetResult(unsigned index);\n  void executeGetResults();\n  void executeGetValueType();\n  void executeGetValueRangeTypes();\n  void executeIsNotNull();\n  void executeRecordMatch(PatternRewriter &rewriter,\n                          SmallVectorImpl<PDLByteCode::MatchResult> &matches);\n  void executeReplaceOp(PatternRewriter &rewriter);\n  void executeSwitchAttribute();\n  void executeSwitchOperandCount();\n  void executeSwitchOperationName();\n  void executeSwitchResultCount();\n  void executeSwitchType();\n  void executeSwitchTypes();\n\n  \/\/\/ Read a value from the bytecode buffer, optionally skipping a certain\n  \/\/\/ number of prefix values. These methods always update the buffer to point\n  \/\/\/ to the next field after the read data.\n  template <typename T = ByteCodeField>\n  T read(size_t skipN = 0) {\n    curCodeIt += skipN;\n    return readImpl<T>();\n  }\n  ByteCodeField read(size_t skipN = 0) { return read<ByteCodeField>(skipN); }\n\n  \/\/\/ Read a list of values from the bytecode buffer.\n  template <typename ValueT, typename T>\n  void readList(SmallVectorImpl<T> &list) {\n    list.clear();\n    for (unsigned i = 0, e = read(); i != e; ++i)\n      list.push_back(read<ValueT>());\n  }\n\n  \/\/\/ Read a list of values from the bytecode buffer. The values may be encoded\n  \/\/\/ as either Value or ValueRange elements.\n  void readValueList(SmallVectorImpl<Value> &list) {\n    for (unsigned i = 0, e = read(); i != e; ++i) {\n      if (read<PDLValue::Kind>() == PDLValue::Kind::Value) {\n        list.push_back(read<Value>());\n      } else {\n        ValueRange *values = read<ValueRange *>();\n        list.append(values->begin(), values->end());\n      }\n    }\n  }\n\n  \/\/\/ Jump to a specific successor based on a predicate value.\n  void selectJump(bool isTrue) { selectJump(size_t(isTrue ? 0 : 1)); }\n  \/\/\/ Jump to a specific successor based on a destination index.\n  void selectJump(size_t destIndex) {\n    curCodeIt = &code[read<ByteCodeAddr>(destIndex * 2)];\n  }\n\n  \/\/\/ Handle a switch operation with the provided value and cases.\n  template <typename T, typename RangeT, typename Comparator = std::equal_to<T>>\n  void handleSwitch(const T &value, RangeT &&cases, Comparator cmp = {}) {\n    LLVM_DEBUG({\n      llvm::dbgs() << \"  * Value: \" << value << \"\\n\"\n                   << \"  * Cases: \";\n      llvm::interleaveComma(cases, llvm::dbgs());\n      llvm::dbgs() << \"\\n\";\n    });\n\n    \/\/ Check to see if the attribute value is within the case list. Jump to\n    \/\/ the correct successor index based on the result.\n    for (auto it = cases.begin(), e = cases.end(); it != e; ++it)\n      if (cmp(*it, value))\n        return selectJump(size_t((it - cases.begin()) + 1));\n    selectJump(size_t(0));\n  }\n\n  \/\/\/ Internal implementation of reading various data types from the bytecode\n  \/\/\/ stream.\n  template <typename T>\n  const void *readFromMemory() {\n    size_t index = *curCodeIt++;\n\n    \/\/ If this type is an SSA value, it can only be stored in non-const memory.\n    if (llvm::is_one_of<T, Operation *, TypeRange *, ValueRange *,\n                        Value>::value ||\n        index < memory.size())\n      return memory[index];\n\n    \/\/ Otherwise, if this index is not inbounds it is uniqued.\n    return uniquedMemory[index - memory.size()];\n  }\n  template <typename T>\n  std::enable_if_t<std::is_pointer<T>::value, T> readImpl() {\n    return reinterpret_cast<T>(const_cast<void *>(readFromMemory<T>()));\n  }\n  template <typename T>\n  std::enable_if_t<std::is_class<T>::value && !std::is_same<PDLValue, T>::value,\n                   T>\n  readImpl() {\n    return T(T::getFromOpaquePointer(readFromMemory<T>()));\n  }\n  template <typename T>\n  std::enable_if_t<std::is_same<PDLValue, T>::value, T> readImpl() {\n    switch (read<PDLValue::Kind>()) {\n    case PDLValue::Kind::Attribute:\n      return read<Attribute>();\n    case PDLValue::Kind::Operation:\n      return read<Operation *>();\n    case PDLValue::Kind::Type:\n      return read<Type>();\n    case PDLValue::Kind::Value:\n      return read<Value>();\n    case PDLValue::Kind::TypeRange:\n      return read<TypeRange *>();\n    case PDLValue::Kind::ValueRange:\n      return read<ValueRange *>();\n    }\n    llvm_unreachable(\"unhandled PDLValue::Kind\");\n  }\n  template <typename T>\n  std::enable_if_t<std::is_same<T, ByteCodeAddr>::value, T> readImpl() {\n    static_assert((sizeof(ByteCodeAddr) \/ sizeof(ByteCodeField)) == 2,\n                  \"unexpected ByteCode address size\");\n    ByteCodeAddr result;\n    std::memcpy(&result, curCodeIt, sizeof(ByteCodeAddr));\n    curCodeIt += 2;\n    return result;\n  }\n  template <typename T>\n  std::enable_if_t<std::is_same<T, ByteCodeField>::value, T> readImpl() {\n    return *curCodeIt++;\n  }\n  template <typename T>\n  std::enable_if_t<std::is_same<T, PDLValue::Kind>::value, T> readImpl() {\n    return static_cast<PDLValue::Kind>(readImpl<ByteCodeField>());\n  }\n\n  \/\/\/ The underlying bytecode buffer.\n  const ByteCodeField *curCodeIt;\n\n  \/\/\/ The current execution memory.\n  MutableArrayRef<const void *> memory;\n  MutableArrayRef<TypeRange> typeRangeMemory;\n  std::vector<llvm::OwningArrayRef<Type>> &allocatedTypeRangeMemory;\n  MutableArrayRef<ValueRange> valueRangeMemory;\n  std::vector<llvm::OwningArrayRef<Value>> &allocatedValueRangeMemory;\n\n  \/\/\/ References to ByteCode data necessary for execution.\n  ArrayRef<const void *> uniquedMemory;\n  ArrayRef<ByteCodeField> code;\n  ArrayRef<PatternBenefit> currentPatternBenefits;\n  ArrayRef<PDLByteCodePattern> patterns;\n  ArrayRef<PDLConstraintFunction> constraintFunctions;\n  ArrayRef<PDLRewriteFunction> rewriteFunctions;\n};\n\n\/\/\/ This class is an instantiation of the PDLResultList that provides access to\n\/\/\/ the returned results. This API is not on `PDLResultList` to avoid\n\/\/\/ overexposing access to information specific solely to the ByteCode.\nclass ByteCodeRewriteResultList : public PDLResultList {\npublic:\n  ByteCodeRewriteResultList(unsigned maxNumResults)\n      : PDLResultList(maxNumResults) {}\n\n  \/\/\/ Return the list of PDL results.\n  MutableArrayRef<PDLValue> getResults() { return results; }\n\n  \/\/\/ Return the type ranges allocated by this list.\n  MutableArrayRef<llvm::OwningArrayRef<Type>> getAllocatedTypeRanges() {\n    return allocatedTypeRanges;\n  }\n\n  \/\/\/ Return the value ranges allocated by this list.\n  MutableArrayRef<llvm::OwningArrayRef<Value>> getAllocatedValueRanges() {\n    return allocatedValueRanges;\n  }\n};\n} \/\/ end anonymous namespace\n\nvoid ByteCodeExecutor::executeApplyConstraint(PatternRewriter &rewriter) {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing ApplyConstraint:\\n\");\n  const PDLConstraintFunction &constraintFn = constraintFunctions[read()];\n  ArrayAttr constParams = read<ArrayAttr>();\n  SmallVector<PDLValue, 16> args;\n  readList<PDLValue>(args);\n\n  LLVM_DEBUG({\n    llvm::dbgs() << \"  * Arguments: \";\n    llvm::interleaveComma(args, llvm::dbgs());\n    llvm::dbgs() << \"\\n  * Parameters: \" << constParams << \"\\n\";\n  });\n\n  \/\/ Invoke the constraint and jump to the proper destination.\n  selectJump(succeeded(constraintFn(args, constParams, rewriter)));\n}\n\nvoid ByteCodeExecutor::executeApplyRewrite(PatternRewriter &rewriter) {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing ApplyRewrite:\\n\");\n  const PDLRewriteFunction &rewriteFn = rewriteFunctions[read()];\n  ArrayAttr constParams = read<ArrayAttr>();\n  SmallVector<PDLValue, 16> args;\n  readList<PDLValue>(args);\n\n  LLVM_DEBUG({\n    llvm::dbgs() << \"  * Arguments: \";\n    llvm::interleaveComma(args, llvm::dbgs());\n    llvm::dbgs() << \"\\n  * Parameters: \" << constParams << \"\\n\";\n  });\n\n  \/\/ Execute the rewrite function.\n  ByteCodeField numResults = read();\n  ByteCodeRewriteResultList results(numResults);\n  rewriteFn(args, constParams, rewriter, results);\n\n  assert(results.getResults().size() == numResults &&\n         \"native PDL rewrite function returned unexpected number of results\");\n\n  \/\/ Store the results in the bytecode memory.\n  for (PDLValue &result : results.getResults()) {\n    LLVM_DEBUG(llvm::dbgs() << \"  * Result: \" << result << \"\\n\");\n\n\/\/ In debug mode we also verify the expected kind of the result.\n#ifndef NDEBUG\n    assert(result.getKind() == read<PDLValue::Kind>() &&\n           \"native PDL rewrite function returned an unexpected type of result\");\n#endif\n\n    \/\/ If the result is a range, we need to copy it over to the bytecodes\n    \/\/ range memory.\n    if (Optional<TypeRange> typeRange = result.dyn_cast<TypeRange>()) {\n      unsigned rangeIndex = read();\n      typeRangeMemory[rangeIndex] = *typeRange;\n      memory[read()] = &typeRangeMemory[rangeIndex];\n    } else if (Optional<ValueRange> valueRange =\n                   result.dyn_cast<ValueRange>()) {\n      unsigned rangeIndex = read();\n      valueRangeMemory[rangeIndex] = *valueRange;\n      memory[read()] = &valueRangeMemory[rangeIndex];\n    } else {\n      memory[read()] = result.getAsOpaquePointer();\n    }\n  }\n\n  \/\/ Copy over any underlying storage allocated for result ranges.\n  for (auto &it : results.getAllocatedTypeRanges())\n    allocatedTypeRangeMemory.push_back(std::move(it));\n  for (auto &it : results.getAllocatedValueRanges())\n    allocatedValueRangeMemory.push_back(std::move(it));\n}\n\nvoid ByteCodeExecutor::executeAreEqual() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing AreEqual:\\n\");\n  const void *lhs = read<const void *>();\n  const void *rhs = read<const void *>();\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * \" << lhs << \" == \" << rhs << \"\\n\");\n  selectJump(lhs == rhs);\n}\n\nvoid ByteCodeExecutor::executeAreRangesEqual() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing AreRangesEqual:\\n\");\n  PDLValue::Kind valueKind = read<PDLValue::Kind>();\n  const void *lhs = read<const void *>();\n  const void *rhs = read<const void *>();\n\n  switch (valueKind) {\n  case PDLValue::Kind::TypeRange: {\n    const TypeRange *lhsRange = reinterpret_cast<const TypeRange *>(lhs);\n    const TypeRange *rhsRange = reinterpret_cast<const TypeRange *>(rhs);\n    LLVM_DEBUG(llvm::dbgs() << \"  * \" << lhs << \" == \" << rhs << \"\\n\\n\");\n    selectJump(*lhsRange == *rhsRange);\n    break;\n  }\n  case PDLValue::Kind::ValueRange: {\n    const auto *lhsRange = reinterpret_cast<const ValueRange *>(lhs);\n    const auto *rhsRange = reinterpret_cast<const ValueRange *>(rhs);\n    LLVM_DEBUG(llvm::dbgs() << \"  * \" << lhs << \" == \" << rhs << \"\\n\\n\");\n    selectJump(*lhsRange == *rhsRange);\n    break;\n  }\n  default:\n    llvm_unreachable(\"unexpected `AreRangesEqual` value kind\");\n  }\n}\n\nvoid ByteCodeExecutor::executeBranch() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing Branch\\n\");\n  curCodeIt = &code[read<ByteCodeAddr>()];\n}\n\nvoid ByteCodeExecutor::executeCheckOperandCount() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing CheckOperandCount:\\n\");\n  Operation *op = read<Operation *>();\n  uint32_t expectedCount = read<uint32_t>();\n  bool compareAtLeast = read();\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Found: \" << op->getNumOperands() << \"\\n\"\n                          << \"  * Expected: \" << expectedCount << \"\\n\"\n                          << \"  * Comparator: \"\n                          << (compareAtLeast ? \">=\" : \"==\") << \"\\n\");\n  if (compareAtLeast)\n    selectJump(op->getNumOperands() >= expectedCount);\n  else\n    selectJump(op->getNumOperands() == expectedCount);\n}\n\nvoid ByteCodeExecutor::executeCheckOperationName() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing CheckOperationName:\\n\");\n  Operation *op = read<Operation *>();\n  OperationName expectedName = read<OperationName>();\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Found: \\\"\" << op->getName() << \"\\\"\\n\"\n                          << \"  * Expected: \\\"\" << expectedName << \"\\\"\\n\");\n  selectJump(op->getName() == expectedName);\n}\n\nvoid ByteCodeExecutor::executeCheckResultCount() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing CheckResultCount:\\n\");\n  Operation *op = read<Operation *>();\n  uint32_t expectedCount = read<uint32_t>();\n  bool compareAtLeast = read();\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Found: \" << op->getNumResults() << \"\\n\"\n                          << \"  * Expected: \" << expectedCount << \"\\n\"\n                          << \"  * Comparator: \"\n                          << (compareAtLeast ? \">=\" : \"==\") << \"\\n\");\n  if (compareAtLeast)\n    selectJump(op->getNumResults() >= expectedCount);\n  else\n    selectJump(op->getNumResults() == expectedCount);\n}\n\nvoid ByteCodeExecutor::executeCheckTypes() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing AreEqual:\\n\");\n  TypeRange *lhs = read<TypeRange *>();\n  Attribute rhs = read<Attribute>();\n  LLVM_DEBUG(llvm::dbgs() << \"  * \" << lhs << \" == \" << rhs << \"\\n\\n\");\n\n  selectJump(*lhs == rhs.cast<ArrayAttr>().getAsValueRange<TypeAttr>());\n}\n\nvoid ByteCodeExecutor::executeCreateTypes() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing CreateTypes:\\n\");\n  unsigned memIndex = read();\n  unsigned rangeIndex = read();\n  ArrayAttr typesAttr = read<Attribute>().cast<ArrayAttr>();\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Types: \" << typesAttr << \"\\n\\n\");\n\n  \/\/ Allocate a buffer for this type range.\n  llvm::OwningArrayRef<Type> storage(typesAttr.size());\n  llvm::copy(typesAttr.getAsValueRange<TypeAttr>(), storage.begin());\n  allocatedTypeRangeMemory.emplace_back(std::move(storage));\n\n  \/\/ Assign this to the range slot and use the range as the value for the\n  \/\/ memory index.\n  typeRangeMemory[rangeIndex] = allocatedTypeRangeMemory.back();\n  memory[memIndex] = &typeRangeMemory[rangeIndex];\n}\n\nvoid ByteCodeExecutor::executeCreateOperation(PatternRewriter &rewriter,\n                                              Location mainRewriteLoc) {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing CreateOperation:\\n\");\n\n  unsigned memIndex = read();\n  OperationState state(mainRewriteLoc, read<OperationName>());\n  readValueList(state.operands);\n  for (unsigned i = 0, e = read(); i != e; ++i) {\n    StringAttr name = read<StringAttr>();\n    if (Attribute attr = read<Attribute>())\n      state.addAttribute(name, attr);\n  }\n\n  for (unsigned i = 0, e = read(); i != e; ++i) {\n    if (read<PDLValue::Kind>() == PDLValue::Kind::Type) {\n      state.types.push_back(read<Type>());\n      continue;\n    }\n\n    \/\/ If we find a null range, this signals that the types are infered.\n    if (TypeRange *resultTypes = read<TypeRange *>()) {\n      state.types.append(resultTypes->begin(), resultTypes->end());\n      continue;\n    }\n\n    \/\/ Handle the case where the operation has inferred types.\n    InferTypeOpInterface::Concept *concept =\n        state.name.getRegisteredInfo()->getInterface<InferTypeOpInterface>();\n\n    \/\/ TODO: Handle failure.\n    state.types.clear();\n    if (failed(concept->inferReturnTypes(\n            state.getContext(), state.location, state.operands,\n            state.attributes.getDictionary(state.getContext()), state.regions,\n            state.types)))\n      return;\n    break;\n  }\n\n  Operation *resultOp = rewriter.createOperation(state);\n  memory[memIndex] = resultOp;\n\n  LLVM_DEBUG({\n    llvm::dbgs() << \"  * Attributes: \"\n                 << state.attributes.getDictionary(state.getContext())\n                 << \"\\n  * Operands: \";\n    llvm::interleaveComma(state.operands, llvm::dbgs());\n    llvm::dbgs() << \"\\n  * Result Types: \";\n    llvm::interleaveComma(state.types, llvm::dbgs());\n    llvm::dbgs() << \"\\n  * Result: \" << *resultOp << \"\\n\";\n  });\n}\n\nvoid ByteCodeExecutor::executeEraseOp(PatternRewriter &rewriter) {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing EraseOp:\\n\");\n  Operation *op = read<Operation *>();\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Operation: \" << *op << \"\\n\");\n  rewriter.eraseOp(op);\n}\n\nvoid ByteCodeExecutor::executeGetAttribute() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing GetAttribute:\\n\");\n  unsigned memIndex = read();\n  Operation *op = read<Operation *>();\n  StringAttr attrName = read<StringAttr>();\n  Attribute attr = op->getAttr(attrName);\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Operation: \" << *op << \"\\n\"\n                          << \"  * Attribute: \" << attrName << \"\\n\"\n                          << \"  * Result: \" << attr << \"\\n\");\n  memory[memIndex] = attr.getAsOpaquePointer();\n}\n\nvoid ByteCodeExecutor::executeGetAttributeType() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing GetAttributeType:\\n\");\n  unsigned memIndex = read();\n  Attribute attr = read<Attribute>();\n  Type type = attr ? attr.getType() : Type();\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Attribute: \" << attr << \"\\n\"\n                          << \"  * Result: \" << type << \"\\n\");\n  memory[memIndex] = type.getAsOpaquePointer();\n}\n\nvoid ByteCodeExecutor::executeGetDefiningOp() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing GetDefiningOp:\\n\");\n  unsigned memIndex = read();\n  Operation *op = nullptr;\n  if (read<PDLValue::Kind>() == PDLValue::Kind::Value) {\n    Value value = read<Value>();\n    if (value)\n      op = value.getDefiningOp();\n    LLVM_DEBUG(llvm::dbgs() << \"  * Value: \" << value << \"\\n\");\n  } else {\n    ValueRange *values = read<ValueRange *>();\n    if (values && !values->empty()) {\n      op = values->front().getDefiningOp();\n    }\n    LLVM_DEBUG(llvm::dbgs() << \"  * Values: \" << values << \"\\n\");\n  }\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Result: \" << op << \"\\n\");\n  memory[memIndex] = op;\n}\n\nvoid ByteCodeExecutor::executeGetOperand(unsigned index) {\n  Operation *op = read<Operation *>();\n  unsigned memIndex = read();\n  Value operand =\n      index < op->getNumOperands() ? op->getOperand(index) : Value();\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Operation: \" << *op << \"\\n\"\n                          << \"  * Index: \" << index << \"\\n\"\n                          << \"  * Result: \" << operand << \"\\n\");\n  memory[memIndex] = operand.getAsOpaquePointer();\n}\n\n\/\/\/ This function is the internal implementation of `GetResults` and\n\/\/\/ `GetOperands` that provides support for extracting a value range from the\n\/\/\/ given operation.\ntemplate <template <typename> class AttrSizedSegmentsT, typename RangeT>\nstatic void *\nexecuteGetOperandsResults(RangeT values, Operation *op, unsigned index,\n                          ByteCodeField rangeIndex, StringRef attrSizedSegments,\n                          MutableArrayRef<ValueRange> &valueRangeMemory) {\n  \/\/ Check for the sentinel index that signals that all values should be\n  \/\/ returned.\n  if (index == std::numeric_limits<uint32_t>::max()) {\n    LLVM_DEBUG(llvm::dbgs() << \"  * Getting all values\\n\");\n    \/\/ `values` is already the full value range.\n\n    \/\/ Otherwise, check to see if this operation uses AttrSizedSegments.\n  } else if (op->hasTrait<AttrSizedSegmentsT>()) {\n    LLVM_DEBUG(llvm::dbgs()\n               << \"  * Extracting values from `\" << attrSizedSegments << \"`\\n\");\n\n    auto segmentAttr = op->getAttrOfType<DenseElementsAttr>(attrSizedSegments);\n    if (!segmentAttr || segmentAttr.getNumElements() <= index)\n      return nullptr;\n\n    auto segments = segmentAttr.getValues<int32_t>();\n    unsigned startIndex =\n        std::accumulate(segments.begin(), segments.begin() + index, 0);\n    values = values.slice(startIndex, *std::next(segments.begin(), index));\n\n    LLVM_DEBUG(llvm::dbgs() << \"  * Extracting range[\" << startIndex << \", \"\n                            << *std::next(segments.begin(), index) << \"]\\n\");\n\n    \/\/ Otherwise, assume this is the last operand group of the operation.\n    \/\/ FIXME: We currently don't support operations with\n    \/\/ SameVariadicOperandSize\/SameVariadicResultSize here given that we don't\n    \/\/ have a way to detect it's presence.\n  } else if (values.size() >= index) {\n    LLVM_DEBUG(llvm::dbgs()\n               << \"  * Treating values as trailing variadic range\\n\");\n    values = values.drop_front(index);\n\n    \/\/ If we couldn't detect a way to compute the values, bail out.\n  } else {\n    return nullptr;\n  }\n\n  \/\/ If the range index is valid, we are returning a range.\n  if (rangeIndex != std::numeric_limits<ByteCodeField>::max()) {\n    valueRangeMemory[rangeIndex] = values;\n    return &valueRangeMemory[rangeIndex];\n  }\n\n  \/\/ If a range index wasn't provided, the range is required to be non-variadic.\n  return values.size() != 1 ? nullptr : values.front().getAsOpaquePointer();\n}\n\nvoid ByteCodeExecutor::executeGetOperands() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing GetOperands:\\n\");\n  unsigned index = read<uint32_t>();\n  Operation *op = read<Operation *>();\n  ByteCodeField rangeIndex = read();\n\n  void *result = executeGetOperandsResults<OpTrait::AttrSizedOperandSegments>(\n      op->getOperands(), op, index, rangeIndex, \"operand_segment_sizes\",\n      valueRangeMemory);\n  if (!result)\n    LLVM_DEBUG(llvm::dbgs() << \"  * Invalid operand range\\n\");\n  memory[read()] = result;\n}\n\nvoid ByteCodeExecutor::executeGetResult(unsigned index) {\n  Operation *op = read<Operation *>();\n  unsigned memIndex = read();\n  OpResult result =\n      index < op->getNumResults() ? op->getResult(index) : OpResult();\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Operation: \" << *op << \"\\n\"\n                          << \"  * Index: \" << index << \"\\n\"\n                          << \"  * Result: \" << result << \"\\n\");\n  memory[memIndex] = result.getAsOpaquePointer();\n}\n\nvoid ByteCodeExecutor::executeGetResults() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing GetResults:\\n\");\n  unsigned index = read<uint32_t>();\n  Operation *op = read<Operation *>();\n  ByteCodeField rangeIndex = read();\n\n  void *result = executeGetOperandsResults<OpTrait::AttrSizedResultSegments>(\n      op->getResults(), op, index, rangeIndex, \"result_segment_sizes\",\n      valueRangeMemory);\n  if (!result)\n    LLVM_DEBUG(llvm::dbgs() << \"  * Invalid result range\\n\");\n  memory[read()] = result;\n}\n\nvoid ByteCodeExecutor::executeGetValueType() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing GetValueType:\\n\");\n  unsigned memIndex = read();\n  Value value = read<Value>();\n  Type type = value ? value.getType() : Type();\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Value: \" << value << \"\\n\"\n                          << \"  * Result: \" << type << \"\\n\");\n  memory[memIndex] = type.getAsOpaquePointer();\n}\n\nvoid ByteCodeExecutor::executeGetValueRangeTypes() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing GetValueRangeTypes:\\n\");\n  unsigned memIndex = read();\n  unsigned rangeIndex = read();\n  ValueRange *values = read<ValueRange *>();\n  if (!values) {\n    LLVM_DEBUG(llvm::dbgs() << \"  * Values: <NULL>\\n\\n\");\n    memory[memIndex] = nullptr;\n    return;\n  }\n\n  LLVM_DEBUG({\n    llvm::dbgs() << \"  * Values (\" << values->size() << \"): \";\n    llvm::interleaveComma(*values, llvm::dbgs());\n    llvm::dbgs() << \"\\n  * Result: \";\n    llvm::interleaveComma(values->getType(), llvm::dbgs());\n    llvm::dbgs() << \"\\n\";\n  });\n  typeRangeMemory[rangeIndex] = values->getType();\n  memory[memIndex] = &typeRangeMemory[rangeIndex];\n}\n\nvoid ByteCodeExecutor::executeIsNotNull() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing IsNotNull:\\n\");\n  const void *value = read<const void *>();\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Value: \" << value << \"\\n\");\n  selectJump(value != nullptr);\n}\n\nvoid ByteCodeExecutor::executeRecordMatch(\n    PatternRewriter &rewriter,\n    SmallVectorImpl<PDLByteCode::MatchResult> &matches) {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing RecordMatch:\\n\");\n  unsigned patternIndex = read();\n  PatternBenefit benefit = currentPatternBenefits[patternIndex];\n  const ByteCodeField *dest = &code[read<ByteCodeAddr>()];\n\n  \/\/ If the benefit of the pattern is impossible, skip the processing of the\n  \/\/ rest of the pattern.\n  if (benefit.isImpossibleToMatch()) {\n    LLVM_DEBUG(llvm::dbgs() << \"  * Benefit: Impossible To Match\\n\");\n    curCodeIt = dest;\n    return;\n  }\n\n  \/\/ Create a fused location containing the locations of each of the\n  \/\/ operations used in the match. This will be used as the location for\n  \/\/ created operations during the rewrite that don't already have an\n  \/\/ explicit location set.\n  unsigned numMatchLocs = read();\n  SmallVector<Location, 4> matchLocs;\n  matchLocs.reserve(numMatchLocs);\n  for (unsigned i = 0; i != numMatchLocs; ++i)\n    matchLocs.push_back(read<Operation *>()->getLoc());\n  Location matchLoc = rewriter.getFusedLoc(matchLocs);\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Benefit: \" << benefit.getBenefit() << \"\\n\"\n                          << \"  * Location: \" << matchLoc << \"\\n\");\n  matches.emplace_back(matchLoc, patterns[patternIndex], benefit);\n  PDLByteCode::MatchResult &match = matches.back();\n\n  \/\/ Record all of the inputs to the match. If any of the inputs are ranges, we\n  \/\/ will also need to remap the range pointer to memory stored in the match\n  \/\/ state.\n  unsigned numInputs = read();\n  match.values.reserve(numInputs);\n  match.typeRangeValues.reserve(numInputs);\n  match.valueRangeValues.reserve(numInputs);\n  for (unsigned i = 0; i < numInputs; ++i) {\n    switch (read<PDLValue::Kind>()) {\n    case PDLValue::Kind::TypeRange:\n      match.typeRangeValues.push_back(*read<TypeRange *>());\n      match.values.push_back(&match.typeRangeValues.back());\n      break;\n    case PDLValue::Kind::ValueRange:\n      match.valueRangeValues.push_back(*read<ValueRange *>());\n      match.values.push_back(&match.valueRangeValues.back());\n      break;\n    default:\n      match.values.push_back(read<const void *>());\n      break;\n    }\n  }\n  curCodeIt = dest;\n}\n\nvoid ByteCodeExecutor::executeReplaceOp(PatternRewriter &rewriter) {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing ReplaceOp:\\n\");\n  Operation *op = read<Operation *>();\n  SmallVector<Value, 16> args;\n  readValueList(args);\n\n  LLVM_DEBUG({\n    llvm::dbgs() << \"  * Operation: \" << *op << \"\\n\"\n                 << \"  * Values: \";\n    llvm::interleaveComma(args, llvm::dbgs());\n    llvm::dbgs() << \"\\n\";\n  });\n  rewriter.replaceOp(op, args);\n}\n\nvoid ByteCodeExecutor::executeSwitchAttribute() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing SwitchAttribute:\\n\");\n  Attribute value = read<Attribute>();\n  ArrayAttr cases = read<ArrayAttr>();\n  handleSwitch(value, cases);\n}\n\nvoid ByteCodeExecutor::executeSwitchOperandCount() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing SwitchOperandCount:\\n\");\n  Operation *op = read<Operation *>();\n  auto cases = read<DenseIntOrFPElementsAttr>().getValues<uint32_t>();\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Operation: \" << *op << \"\\n\");\n  handleSwitch(op->getNumOperands(), cases);\n}\n\nvoid ByteCodeExecutor::executeSwitchOperationName() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing SwitchOperationName:\\n\");\n  OperationName value = read<Operation *>()->getName();\n  size_t caseCount = read();\n\n  \/\/ The operation names are stored in-line, so to print them out for\n  \/\/ debugging purposes we need to read the array before executing the\n  \/\/ switch so that we can display all of the possible values.\n  LLVM_DEBUG({\n    const ByteCodeField *prevCodeIt = curCodeIt;\n    llvm::dbgs() << \"  * Value: \" << value << \"\\n\"\n                 << \"  * Cases: \";\n    llvm::interleaveComma(\n        llvm::map_range(llvm::seq<size_t>(0, caseCount),\n                        [&](size_t) { return read<OperationName>(); }),\n        llvm::dbgs());\n    llvm::dbgs() << \"\\n\";\n    curCodeIt = prevCodeIt;\n  });\n\n  \/\/ Try to find the switch value within any of the cases.\n  for (size_t i = 0; i != caseCount; ++i) {\n    if (read<OperationName>() == value) {\n      curCodeIt += (caseCount - i - 1);\n      return selectJump(i + 1);\n    }\n  }\n  selectJump(size_t(0));\n}\n\nvoid ByteCodeExecutor::executeSwitchResultCount() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing SwitchResultCount:\\n\");\n  Operation *op = read<Operation *>();\n  auto cases = read<DenseIntOrFPElementsAttr>().getValues<uint32_t>();\n\n  LLVM_DEBUG(llvm::dbgs() << \"  * Operation: \" << *op << \"\\n\");\n  handleSwitch(op->getNumResults(), cases);\n}\n\nvoid ByteCodeExecutor::executeSwitchType() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing SwitchType:\\n\");\n  Type value = read<Type>();\n  auto cases = read<ArrayAttr>().getAsValueRange<TypeAttr>();\n  handleSwitch(value, cases);\n}\n\nvoid ByteCodeExecutor::executeSwitchTypes() {\n  LLVM_DEBUG(llvm::dbgs() << \"Executing SwitchTypes:\\n\");\n  TypeRange *value = read<TypeRange *>();\n  auto cases = read<ArrayAttr>().getAsRange<ArrayAttr>();\n  if (!value) {\n    LLVM_DEBUG(llvm::dbgs() << \"Types: <NULL>\\n\");\n    return selectJump(size_t(0));\n  }\n  handleSwitch(*value, cases, [](ArrayAttr caseValue, const TypeRange &value) {\n    return value == caseValue.getAsValueRange<TypeAttr>();\n  });\n}\n\nvoid ByteCodeExecutor::execute(\n    PatternRewriter &rewriter,\n    SmallVectorImpl<PDLByteCode::MatchResult> *matches,\n    Optional<Location> mainRewriteLoc) {\n  while (true) {\n    OpCode opCode = static_cast<OpCode>(read());\n    switch (opCode) {\n    case ApplyConstraint:\n      executeApplyConstraint(rewriter);\n      break;\n    case ApplyRewrite:\n      executeApplyRewrite(rewriter);\n      break;\n    case AreEqual:\n      executeAreEqual();\n      break;\n    case AreRangesEqual:\n      executeAreRangesEqual();\n      break;\n    case Branch:\n      executeBranch();\n      break;\n    case CheckOperandCount:\n      executeCheckOperandCount();\n      break;\n    case CheckOperationName:\n      executeCheckOperationName();\n      break;\n    case CheckResultCount:\n      executeCheckResultCount();\n      break;\n    case CheckTypes:\n      executeCheckTypes();\n      break;\n    case CreateOperation:\n      executeCreateOperation(rewriter, *mainRewriteLoc);\n      break;\n    case CreateTypes:\n      executeCreateTypes();\n      break;\n    case EraseOp:\n      executeEraseOp(rewriter);\n      break;\n    case Finalize:\n      LLVM_DEBUG(llvm::dbgs() << \"Executing Finalize\\n\\n\");\n      return;\n    case GetAttribute:\n      executeGetAttribute();\n      break;\n    case GetAttributeType:\n      executeGetAttributeType();\n      break;\n    case GetDefiningOp:\n      executeGetDefiningOp();\n      break;\n    case GetOperand0:\n    case GetOperand1:\n    case GetOperand2:\n    case GetOperand3: {\n      unsigned index = opCode - GetOperand0;\n      LLVM_DEBUG(llvm::dbgs() << \"Executing GetOperand\" << index << \":\\n\");\n      executeGetOperand(index);\n      break;\n    }\n    case GetOperandN:\n      LLVM_DEBUG(llvm::dbgs() << \"Executing GetOperandN:\\n\");\n      executeGetOperand(read<uint32_t>());\n      break;\n    case GetOperands:\n      executeGetOperands();\n      break;\n    case GetResult0:\n    case GetResult1:\n    case GetResult2:\n    case GetResult3: {\n      unsigned index = opCode - GetResult0;\n      LLVM_DEBUG(llvm::dbgs() << \"Executing GetResult\" << index << \":\\n\");\n      executeGetResult(index);\n      break;\n    }\n    case GetResultN:\n      LLVM_DEBUG(llvm::dbgs() << \"Executing GetResultN:\\n\");\n      executeGetResult(read<uint32_t>());\n      break;\n    case GetResults:\n      executeGetResults();\n      break;\n    case GetValueType:\n      executeGetValueType();\n      break;\n    case GetValueRangeTypes:\n      executeGetValueRangeTypes();\n      break;\n    case IsNotNull:\n      executeIsNotNull();\n      break;\n    case RecordMatch:\n      assert(matches &&\n             \"expected matches to be provided when executing the matcher\");\n      executeRecordMatch(rewriter, *matches);\n      break;\n    case ReplaceOp:\n      executeReplaceOp(rewriter);\n      break;\n    case SwitchAttribute:\n      executeSwitchAttribute();\n      break;\n    case SwitchOperandCount:\n      executeSwitchOperandCount();\n      break;\n    case SwitchOperationName:\n      executeSwitchOperationName();\n      break;\n    case SwitchResultCount:\n      executeSwitchResultCount();\n      break;\n    case SwitchType:\n      executeSwitchType();\n      break;\n    case SwitchTypes:\n      executeSwitchTypes();\n      break;\n    }\n    LLVM_DEBUG(llvm::dbgs() << \"\\n\");\n  }\n}\n\n\/\/\/ Run the pattern matcher on the given root operation, collecting the matched\n\/\/\/ patterns in `matches`.\nvoid PDLByteCode::match(Operation *op, PatternRewriter &rewriter,\n                        SmallVectorImpl<MatchResult> &matches,\n                        PDLByteCodeMutableState &state) const {\n  \/\/ The first memory slot is always the root operation.\n  state.memory[0] = op;\n\n  \/\/ The matcher function always starts at code address 0.\n  ByteCodeExecutor executor(\n      matcherByteCode.data(), state.memory, state.typeRangeMemory,\n      state.allocatedTypeRangeMemory, state.valueRangeMemory,\n      state.allocatedValueRangeMemory, uniquedData, matcherByteCode,\n      state.currentPatternBenefits, patterns, constraintFunctions,\n      rewriteFunctions);\n  executor.execute(rewriter, &matches);\n\n  \/\/ Order the found matches by benefit.\n  std::stable_sort(matches.begin(), matches.end(),\n                   [](const MatchResult &lhs, const MatchResult &rhs) {\n                     return lhs.benefit > rhs.benefit;\n                   });\n}\n\n\/\/\/ Run the rewriter of the given pattern on the root operation `op`.\nvoid PDLByteCode::rewrite(PatternRewriter &rewriter, const MatchResult &match,\n                          PDLByteCodeMutableState &state) const {\n  \/\/ The arguments of the rewrite function are stored at the start of the\n  \/\/ memory buffer.\n  llvm::copy(match.values, state.memory.begin());\n\n  ByteCodeExecutor executor(\n      &rewriterByteCode[match.pattern->getRewriterAddr()], state.memory,\n      state.typeRangeMemory, state.allocatedTypeRangeMemory,\n      state.valueRangeMemory, state.allocatedValueRangeMemory, uniquedData,\n      rewriterByteCode, state.currentPatternBenefits, patterns,\n      constraintFunctions, rewriteFunctions);\n  executor.execute(rewriter, \/*matches=*\/nullptr, match.location);\n}\n","avg_line_length":38.8151125402,"max_line_length":80,"alphanum_fraction":0.6706015546,"low_alphanum":false,"long_lines":false,"lexable":true}
{"size":3355,"ext":"cpp","lang":"C++","max_stars_repo_licenses":["MIT"],"max_stars_count":1.0,"content":"\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreStableHeaders.h\"\n\n#include \"OgreRenderTexture.h\"\n#include \"OgreException.h\"\n#include \"OgreHardwarePixelBuffer.h\"\n\nnamespace Ogre\n{\n\n    \/\/-----------------------------------------------------------------------------\n    RenderTexture::RenderTexture(HardwarePixelBuffer *buffer, uint32 zoffset):\n        mBuffer(buffer), mZOffset(zoffset)\n    {\n        mPriority = OGRE_REND_TO_TEX_RT_GROUP;\n        mWidth = mBuffer->getWidth();\n        mHeight = mBuffer->getHeight();\n        mColourDepth = static_cast<unsigned int>(\n            Ogre::PixelUtil::getNumElemBits(mBuffer->getFormat()));\n    }\n    RenderTexture::~RenderTexture()\n    {\n        mBuffer->_clearSliceRTT(0);\n    }\n\n    void RenderTexture::copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer)\n    {\n        if (buffer == FB_AUTO) buffer = FB_FRONT;\n        if (buffer != FB_FRONT)\n        {\n            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,\n                        \"Invalid buffer.\",\n                        \"RenderTexture::copyContentsToMemory\" );\n        }\n\n        mBuffer->blitToMemory(src, dst);\n    }\n    \/\/---------------------------------------------------------------------\n    PixelFormat RenderTexture::suggestPixelFormat() const\n    {\n        return mBuffer->getFormat();\n    }\n    \/\/-----------------------------------------------------------------------------\n    MultiRenderTarget::MultiRenderTarget(const String &name)\n    {\n        mPriority = OGRE_REND_TO_TEX_RT_GROUP;\n        mName = name;\n        \/\/\/ Width and height is unknown with no targets attached\n        mWidth = mHeight = 0;\n    }\n    \/\/-----------------------------------------------------------------------------\n    void MultiRenderTarget::copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer)\n    {\n        OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, \n                    \"Cannot get MultiRenderTargets pixels\",\n                    \"MultiRenderTarget::copyContentsToMemory\");\n    }\n}\n","avg_line_length":39.4705882353,"max_line_length":105,"alphanum_fraction":0.6011922504,"low_alphanum":false,"long_lines":false,"lexable":true}
